Skip to content
Myr

Split files into smaller ones (#976)

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

authored by ehmicky · committed by GitHub · parent 7faa8f5 · Browse files · 134 files+6999 added−6655 removed
This commit

State

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

Diff stats

134 files+6999 added−6655 removed

  • tests:+6118 added−5808 removed
  • other:+881 added−847 removed

134 files+6999 added−6655 removed

added:lib/arguments/command.js+13 added
modified:lib/arguments/cwd.js+1 added-13 removed
added:lib/arguments/file-url.js+13 added
modified:lib/arguments/node.js+1 added-1 removed
modified:lib/arguments/normalize.js+1 added-1 removed
modified:lib/arguments/options.js+3 added-14 removed
2 unmodified lines
3import crossSpawn from 'cross-spawn';4import {npmRunPathEnv} from 'npm-run-path';5import {normalizeForceKillAfterDelay} from '../exit/kill.js';6import {validateTimeout} from '../exit/timeout.js';7import {logCommand} from '../verbose/start.js';8import {getVerboseInfo} from '../verbose/info.js';9import {getStartTime} from '../return/duration.js';7import {validateEncoding, BINARY_ENCODINGS} from './encoding.js';8import {handleNodeOption} from './node.js';12import {joinCommand} from './escape.js';13import {normalizeCwd, normalizeFileUrl} from './cwd.js';14import {normalizeFdSpecificOptions, normalizeFdSpecificOption} from './specific.js';9import {normalizeCwd} from './cwd.js';10import {normalizeFileUrl} from './file-url.js';11import {normalizeFdSpecificOptions} from './specific.js';1216export const handleCommand = (filePath, rawArgs, rawOptions) => {17 const startTime = getStartTime();18 const {command, escapedCommand} = joinCommand(filePath, rawArgs);19 const verboseInfo = getVerboseInfo(normalizeFdSpecificOption(rawOptions, 'verbose'));20 logCommand(escapedCommand, verboseInfo, rawOptions);21 return {command, escapedCommand, startTime, verboseInfo};22};2313export const handleOptions = (filePath, rawArgs, rawOptions) => {14 rawOptions.cwd = normalizeCwd(rawOptions.cwd);15 const [processedFile, processedArgs, processedOptions] = handleNodeOption(filePath, rawArgs, rawOptions);16
60 unmodified lines
modified:lib/arguments/template.js+3 added-1 removed
1import {ChildProcess} from 'node:child_process';2import {isUint8Array, uint8ArrayToString} from '../stdio/uint-array.js';2import {isSubprocess} from '../utils.js';34export const isTemplateString = templates => Array.isArray(templates) && Array.isArray(templates.raw);56export const parseTemplates = (templates, expressions) => {
123 unmodified lines
130 }131132 throw new TypeError(`Unexpected "${typeOfExpression}" in template expression`);133};134135const isSubprocess = value => value instanceof ChildProcess;
added:lib/convert/fd-options.js+105 added
1import {parseFd} from '../arguments/specific.js';23export const getWritable = (destination, to = 'stdin') => {4 const isWritable = true;5 const {options, fileDescriptors} = SUBPROCESS_OPTIONS.get(destination);6 const fdNumber = getFdNumber(fileDescriptors, to, isWritable);7 const destinationStream = destination.stdio[fdNumber];89 if (destinationStream === null) {10 throw new TypeError(getInvalidStdioOptionMessage(fdNumber, to, options, isWritable));11 }1213 return destinationStream;14};1516export const getReadable = (source, from = 'stdout') => {17 const isWritable = false;18 const {options, fileDescriptors} = SUBPROCESS_OPTIONS.get(source);19 const fdNumber = getFdNumber(fileDescriptors, from, isWritable);20 const sourceStream = fdNumber === 'all' ? source.all : source.stdio[fdNumber];2122 if (sourceStream === null || sourceStream === undefined) {23 throw new TypeError(getInvalidStdioOptionMessage(fdNumber, from, options, isWritable));24 }2526 return sourceStream;27};2829export const SUBPROCESS_OPTIONS = new WeakMap();3031const getFdNumber = (fileDescriptors, fdName, isWritable) => {32 const fdNumber = parseFdNumber(fdName, isWritable);33 validateFdNumber(fdNumber, fdName, isWritable, fileDescriptors);34 return fdNumber;35};3637const parseFdNumber = (fdName, isWritable) => {38 const fdNumber = parseFd(fdName);39 if (fdNumber !== undefined) {40 return fdNumber;41 }4243 const {validOptions, defaultValue} = isWritable44 ? {validOptions: '"stdin"', defaultValue: 'stdin'}45 : {validOptions: '"stdout", "stderr", "all"', defaultValue: 'stdout'};46 throw new TypeError(`"${getOptionName(isWritable)}" must not be "${fdName}".47It must be ${validOptions} or "fd3", "fd4" (and so on).48It is optional and defaults to "${defaultValue}".`);49};5051const validateFdNumber = (fdNumber, fdName, isWritable, fileDescriptors) => {52 const fileDescriptor = fileDescriptors[getUsedDescriptor(fdNumber)];53 if (fileDescriptor === undefined) {54 throw new TypeError(`"${getOptionName(isWritable)}" must not be ${fdName}. That file descriptor does not exist.55Please set the "stdio" option to ensure that file descriptor exists.`);56 }5758 if (fileDescriptor.direction === 'input' && !isWritable) {59 throw new TypeError(`"${getOptionName(isWritable)}" must not be ${fdName}. It must be a readable stream, not writable.`);60 }6162 if (fileDescriptor.direction !== 'input' && isWritable) {63 throw new TypeError(`"${getOptionName(isWritable)}" must not be ${fdName}. It must be a writable stream, not readable.`);64 }65};6667const getInvalidStdioOptionMessage = (fdNumber, fdName, options, isWritable) => {68 if (fdNumber === 'all' && !options.all) {69 return 'The "all" option must be true to use "from: \'all\'".';70 }7172 const {optionName, optionValue} = getInvalidStdioOption(fdNumber, options);73 return `The "${optionName}: ${serializeOptionValue(optionValue)}" option is incompatible with using "${getOptionName(isWritable)}: ${serializeOptionValue(fdName)}".74Please set this option with "pipe" instead.`;75};7677const getInvalidStdioOption = (fdNumber, {stdin, stdout, stderr, stdio}) => {78 const usedDescriptor = getUsedDescriptor(fdNumber);7980 if (usedDescriptor === 0 && stdin !== undefined) {81 return {optionName: 'stdin', optionValue: stdin};82 }8384 if (usedDescriptor === 1 && stdout !== undefined) {85 return {optionName: 'stdout', optionValue: stdout};86 }8788 if (usedDescriptor === 2 && stderr !== undefined) {89 return {optionName: 'stderr', optionValue: stderr};90 }9192 return {optionName: `stdio[${usedDescriptor}]`, optionValue: stdio[usedDescriptor]};93};9495const getUsedDescriptor = fdNumber => fdNumber === 'all' ? 1 : fdNumber;9697const getOptionName = isWritable => isWritable ? 'to' : 'from';9899export const serializeOptionValue = value => {100 if (typeof value === 'string') {101 return `'${value}'`;102 }103104 return typeof value === 'number' ? `${value}` : 'Stream';105};
modified:lib/convert/iterable.js+1 added-1 removed
modified:lib/convert/loop.js+1 added-1 removed
1import {on} from 'node:events';2import {getEncodingTransformGenerator} from '../stdio/encoding-transform.js';3import {getSplitLinesGenerator} from '../stdio/split.js';4import {transformChunkSync, finalChunksSync} from '../stdio/transform.js';4import {transformChunkSync, finalChunksSync} from '../stdio/transform-sync.js';56// Iterate over lines of `subprocess.stdout`, used by `subprocess.readable|duplex|iterable()`7export const iterateOnSubprocessStream = ({subprocessStdout, subprocess, binary, shouldEncode, encoding, preserveNewlines}) => {8 const controller = new AbortController();
88 unmodified lines
modified:lib/convert/readable.js+1 added-1 removed
1import {Readable} from 'node:stream';2import {callbackify} from 'node:util';3import {BINARY_ENCODINGS} from '../arguments/encoding.js';4import {getReadable} from '../pipe/validate.js';4import {getReadable} from './fd-options.js';5import {addConcurrentStream, waitForConcurrentStreams} from './concurrent.js';6import {7 createDeferred,8 safeWaitForSubprocessStdin,
87 unmodified lines
modified:lib/convert/writable.js+1 added-1 removed
1import {Writable} from 'node:stream';2import {callbackify} from 'node:util';3import {getWritable} from '../pipe/validate.js';3import {getWritable} from './fd-options.js';4import {addConcurrentStream, waitForConcurrentStreams} from './concurrent.js';5import {6 safeWaitForSubprocessStdout,7 waitForSubprocessStdin,
78 unmodified lines
deleted:lib/exit/code.js-30 removed
1import {DiscardedError} from '../return/cause.js';2import {isMaxBufferSync} from '../stream/max-buffer.js';34export const waitForSuccessfulExit = async exitPromise => {5 const [exitCode, signal] = await exitPromise;67 if (!isSubprocessErrorExit(exitCode, signal) && isFailedExit(exitCode, signal)) {8 throw new DiscardedError();9 }1011 return [exitCode, signal];12};1314export const getSyncExitResult = ({error, status: exitCode, signal, output}, {maxBuffer}) => {15 const resultError = getResultError(error, exitCode, signal);16 const timedOut = resultError?.code === 'ETIMEDOUT';17 const isMaxBuffer = isMaxBufferSync(resultError, output, maxBuffer);18 return {resultError, exitCode, signal, timedOut, isMaxBuffer};19};2021const getResultError = (error, exitCode, signal) => {22 if (error !== undefined) {23 return error;24 }2526 return isFailedExit(exitCode, signal) ? new DiscardedError() : undefined;27};2829const isSubprocessErrorExit = (exitCode, signal) => exitCode === undefined && signal === undefined;30const isFailedExit = (exitCode, signal) => exitCode !== 0 || signal !== null;
modified:lib/pipe/streaming.js+1 added-1 removed
1import {finished} from 'node:stream/promises';2import mergeStreams from '@sindresorhus/merge-streams';3import {incrementMaxListeners} from '../utils.js';3import {incrementMaxListeners} from '../max-listener.js';4import {pipeStreams} from '../stdio/pipeline.js';56// The piping behavior is like Bash.7// In particular, when one subprocess exits, the other is not terminated by a signal.
44 unmodified lines
modified:lib/pipe/validate.js+1 added-98 removed
1import {normalizeArguments} from '../arguments/normalize.js';2import {getStartTime} from '../return/duration.js';3import {serializeOptionValue} from '../stdio/native.js';4import {parseFd} from '../arguments/specific.js';3import {SUBPROCESS_OPTIONS, getWritable, getReadable} from '../convert/fd-options.js';45export const normalizePipeArguments = ({source, sourcePromise, boundOptions, createNested}, ...args) => {6 const startTime = getStartTime();7 const {
60 unmodified lines
68};6970const mapDestinationArguments = ({options}) => ({options: {...options, stdin: 'pipe', piped: true}});7173export const SUBPROCESS_OPTIONS = new WeakMap();7475export const getWritable = (destination, to = 'stdin') => {76 const isWritable = true;77 const {options, fileDescriptors} = SUBPROCESS_OPTIONS.get(destination);78 const fdNumber = getFdNumber(fileDescriptors, to, isWritable);79 const destinationStream = destination.stdio[fdNumber];8081 if (destinationStream === null) {82 throw new TypeError(getInvalidStdioOptionMessage(fdNumber, to, options, isWritable));83 }8485 return destinationStream;86};8772const getSourceStream = (source, from) => {73 try {74 const sourceStream = getReadable(source, from);75 return {sourceStream};76 } catch (error) {77 return {sourceError: error};78 }79};9697export const getReadable = (source, from = 'stdout') => {98 const isWritable = false;99 const {options, fileDescriptors} = SUBPROCESS_OPTIONS.get(source);100 const fdNumber = getFdNumber(fileDescriptors, from, isWritable);101 const sourceStream = fdNumber === 'all' ? source.all : source.stdio[fdNumber];102103 if (sourceStream === null || sourceStream === undefined) {104 throw new TypeError(getInvalidStdioOptionMessage(fdNumber, from, options, isWritable));105 }106107 return sourceStream;108};109110const getFdNumber = (fileDescriptors, fdName, isWritable) => {111 const fdNumber = parseFdNumber(fdName, isWritable);112 validateFdNumber(fdNumber, fdName, isWritable, fileDescriptors);113 return fdNumber;114};115116const parseFdNumber = (fdName, isWritable) => {117 const fdNumber = parseFd(fdName);118 if (fdNumber !== undefined) {119 return fdNumber;120 }121122 const {validOptions, defaultValue} = isWritable123 ? {validOptions: '"stdin"', defaultValue: 'stdin'}124 : {validOptions: '"stdout", "stderr", "all"', defaultValue: 'stdout'};125 throw new TypeError(`"${getOptionName(isWritable)}" must not be "${fdName}".126It must be ${validOptions} or "fd3", "fd4" (and so on).127It is optional and defaults to "${defaultValue}".`);128};129130const validateFdNumber = (fdNumber, fdName, isWritable, fileDescriptors) => {131 const fileDescriptor = fileDescriptors[getUsedDescriptor(fdNumber)];132 if (fileDescriptor === undefined) {133 throw new TypeError(`"${getOptionName(isWritable)}" must not be ${fdName}. That file descriptor does not exist.134Please set the "stdio" option to ensure that file descriptor exists.`);135 }136137 if (fileDescriptor.direction === 'input' && !isWritable) {138 throw new TypeError(`"${getOptionName(isWritable)}" must not be ${fdName}. It must be a readable stream, not writable.`);139 }140141 if (fileDescriptor.direction !== 'input' && isWritable) {142 throw new TypeError(`"${getOptionName(isWritable)}" must not be ${fdName}. It must be a writable stream, not readable.`);143 }144};145146const getInvalidStdioOptionMessage = (fdNumber, fdName, options, isWritable) => {147 if (fdNumber === 'all' && !options.all) {148 return 'The "all" option must be true to use "from: \'all\'".';149 }150151 const {optionName, optionValue} = getInvalidStdioOption(fdNumber, options);152 return `The "${optionName}: ${serializeOptionValue(optionValue)}" option is incompatible with using "${getOptionName(isWritable)}: ${serializeOptionValue(fdName)}".153Please set this option with "pipe" instead.`;154};155156const getInvalidStdioOption = (fdNumber, {stdin, stdout, stderr, stdio}) => {157 const usedDescriptor = getUsedDescriptor(fdNumber);158159 if (usedDescriptor === 0 && stdin !== undefined) {160 return {optionName: 'stdin', optionValue: stdin};161 }162163 if (usedDescriptor === 1 && stdout !== undefined) {164 return {optionName: 'stdout', optionValue: stdout};165 }166167 if (usedDescriptor === 2 && stderr !== undefined) {168 return {optionName: 'stderr', optionValue: stderr};169 }170171 return {optionName: `stdio[${usedDescriptor}]`, optionValue: stdio[usedDescriptor]};172};173174const getUsedDescriptor = fdNumber => fdNumber === 'all' ? 1 : fdNumber;175176const getOptionName = isWritable => isWritable ? 'to' : 'from';
modified:lib/return/early-error.js+1 added-1 removed
1import {ChildProcess} from 'node:child_process';2import {PassThrough, Readable, Writable, Duplex} from 'node:stream';3import {cleanupCustomStreams} from '../stdio/async.js';4import {makeEarlyError} from './error.js';5import {handleResult} from './output.js';5import {handleResult} from './reject.js';67// When the subprocess fails to spawn.8// We ensure the returned error is always both a promise and a subprocess.9export const handleEarlyError = ({error, command, escapedCommand, fileDescriptors, options, startTime, verboseInfo}) => {
32 unmodified lines
modified:lib/return/error.js+2 added-89 removed
1import {signalsByName} from 'human-signals';2import stripFinalNewline from 'strip-final-newline';3import {isUint8Array, uint8ArrayToString} from '../stdio/uint-array.js';4import {fixCwdError} from '../arguments/cwd.js';5import {escapeLines} from '../arguments/escape.js';6import {getMaxBufferMessage} from '../stream/max-buffer.js';2import {getDurationMs} from './duration.js';8import {getFinalError, DiscardedError, isExecaError} from './cause.js';3import {getFinalError} from './cause.js';4import {createMessages} from './message.js';56export const makeSuccessResult = ({7 command,8 escapedCommand,
110 unmodified lines
119 const signal = rawSignal === null ? undefined : rawSignal;120 const signalDescription = signal === undefined ? undefined : signalsByName[rawSignal].description;121 return {exitCode, signal, signalDescription};122};127128const createMessages = ({129 stdio,130 all,131 originalError,132 signal,133 signalDescription,134 exitCode,135 escapedCommand,136 timedOut,137 isCanceled,138 isMaxBuffer,139 maxBuffer,140 timeout,141 cwd,142}) => {143 const errorCode = originalError?.code;144 const prefix = getErrorPrefix({originalError, timedOut, timeout, isMaxBuffer, maxBuffer, errorCode, signal, signalDescription, exitCode, isCanceled});145 const originalMessage = getOriginalMessage(originalError, cwd);146 const newline = originalMessage === '' ? '' : '\n';147 const shortMessage = `${prefix}: ${escapedCommand}${newline}${originalMessage}`;148 const messageStdio = all === undefined ? [stdio[2], stdio[1]] : [all];149 const message = [shortMessage, ...messageStdio, ...stdio.slice(3)]150 .map(messagePart => escapeLines(stripFinalNewline(serializeMessagePart(messagePart))))151 .filter(Boolean)152 .join('\n\n');153 return {originalMessage, shortMessage, message};154};155156const getErrorPrefix = ({originalError, timedOut, timeout, isMaxBuffer, maxBuffer, errorCode, signal, signalDescription, exitCode, isCanceled}) => {157 if (timedOut) {158 return `Command timed out after ${timeout} milliseconds`;159 }160161 if (isCanceled) {162 return 'Command was canceled';163 }164165 if (isMaxBuffer) {166 return getMaxBufferMessage(originalError, maxBuffer);167 }168169 if (errorCode !== undefined) {170 return `Command failed with ${errorCode}`;171 }172173 if (signal !== undefined) {174 return `Command was killed with ${signal} (${signalDescription})`;175 }176177 if (exitCode !== undefined) {178 return `Command failed with exit code ${exitCode}`;179 }180181 return 'Command failed';182};183184const getOriginalMessage = (originalError, cwd) => {185 if (originalError instanceof DiscardedError) {186 return '';187 }188189 const originalMessage = isExecaError(originalError)190 ? originalError.originalMessage191 : String(originalError?.message ?? originalError);192 return escapeLines(fixCwdError(originalMessage, cwd));193};194195const serializeMessagePart = messagePart => Array.isArray(messagePart)196 ? messagePart.map(messageItem => stripFinalNewline(serializeMessageItem(messageItem))).filter(Boolean).join('\n')197 : serializeMessageItem(messagePart);198199const serializeMessageItem = messageItem => {200 if (typeof messageItem === 'string') {201 return messageItem;202 }203204 if (isUint8Array(messageItem)) {205 return uint8ArrayToString(messageItem);206 }207208 return '';209};
added:lib/return/message.js+89 added
1import stripFinalNewline from 'strip-final-newline';2import {isUint8Array, uint8ArrayToString} from '../stdio/uint-array.js';3import {fixCwdError} from '../arguments/cwd.js';4import {escapeLines} from '../arguments/escape.js';5import {getMaxBufferMessage} from '../stream/max-buffer.js';6import {DiscardedError, isExecaError} from './cause.js';78export const createMessages = ({9 stdio,10 all,11 originalError,12 signal,13 signalDescription,14 exitCode,15 escapedCommand,16 timedOut,17 isCanceled,18 isMaxBuffer,19 maxBuffer,20 timeout,21 cwd,22}) => {23 const errorCode = originalError?.code;24 const prefix = getErrorPrefix({originalError, timedOut, timeout, isMaxBuffer, maxBuffer, errorCode, signal, signalDescription, exitCode, isCanceled});25 const originalMessage = getOriginalMessage(originalError, cwd);26 const newline = originalMessage === '' ? '' : '\n';27 const shortMessage = `${prefix}: ${escapedCommand}${newline}${originalMessage}`;28 const messageStdio = all === undefined ? [stdio[2], stdio[1]] : [all];29 const message = [shortMessage, ...messageStdio, ...stdio.slice(3)]30 .map(messagePart => escapeLines(stripFinalNewline(serializeMessagePart(messagePart))))31 .filter(Boolean)32 .join('\n\n');33 return {originalMessage, shortMessage, message};34};3536const getErrorPrefix = ({originalError, timedOut, timeout, isMaxBuffer, maxBuffer, errorCode, signal, signalDescription, exitCode, isCanceled}) => {37 if (timedOut) {38 return `Command timed out after ${timeout} milliseconds`;39 }4041 if (isCanceled) {42 return 'Command was canceled';43 }4445 if (isMaxBuffer) {46 return getMaxBufferMessage(originalError, maxBuffer);47 }4849 if (errorCode !== undefined) {50 return `Command failed with ${errorCode}`;51 }5253 if (signal !== undefined) {54 return `Command was killed with ${signal} (${signalDescription})`;55 }5657 if (exitCode !== undefined) {58 return `Command failed with exit code ${exitCode}`;59 }6061 return 'Command failed';62};6364const getOriginalMessage = (originalError, cwd) => {65 if (originalError instanceof DiscardedError) {66 return '';67 }6869 const originalMessage = isExecaError(originalError)70 ? originalError.originalMessage71 : String(originalError?.message ?? originalError);72 return escapeLines(fixCwdError(originalMessage, cwd));73};7475const serializeMessagePart = messagePart => Array.isArray(messagePart)76 ? messagePart.map(messageItem => stripFinalNewline(serializeMessageItem(messageItem))).filter(Boolean).join('\n')77 : serializeMessageItem(messagePart);7879const serializeMessageItem = messageItem => {80 if (typeof messageItem === 'string') {81 return messageItem;82 }8384 if (isUint8Array(messageItem)) {85 return uint8ArrayToString(messageItem);86 }8788 return '';89};
deleted:lib/return/output.js-20 removed
1import stripFinalNewlineFunction from 'strip-final-newline';2import {logFinalResult} from '../verbose/complete.js';34export const stripNewline = (value, {stripFinalNewline}, fdNumber) => getStripFinalNewline(stripFinalNewline, fdNumber) && value !== undefined && !Array.isArray(value)5 ? stripFinalNewlineFunction(value)6 : value;78export const getStripFinalNewline = (stripFinalNewline, fdNumber) => fdNumber === 'all'9 ? stripFinalNewline[1] || stripFinalNewline[2]10 : stripFinalNewline[fdNumber];1112export const handleResult = (result, verboseInfo, {reject}) => {13 logFinalResult(result, reject, verboseInfo);1415 if (result.failed && reject) {16 throw result;17 }1819 return result;20};
added:lib/return/reject.js+11 added
1import {logFinalResult} from '../verbose/complete.js';23export const handleResult = (result, verboseInfo, {reject}) => {4 logFinalResult(result, reject, verboseInfo);56 if (result.failed && reject) {7 throw result;8 }910 return result;11};
added:lib/return/strip-newline.js+9 added
1import stripFinalNewlineFunction from 'strip-final-newline';23export const stripNewline = (value, {stripFinalNewline}, fdNumber) => getStripFinalNewline(stripFinalNewline, fdNumber) && value !== undefined && !Array.isArray(value)4 ? stripFinalNewlineFunction(value)5 : value;67export const getStripFinalNewline = (stripFinalNewline, fdNumber) => fdNumber === 'all'8 ? stripFinalNewline[1] || stripFinalNewline[2]9 : stripFinalNewline[fdNumber];
added:lib/stdio/all-sync.js+32 added
1import {stripNewline} from '../return/strip-newline.js';2import {isUint8Array, concatUint8Arrays} from './uint-array.js';34export const getAllSync = ([, stdout, stderr], options) => {5 if (!options.all) {6 return;7 }89 if (stdout === undefined) {10 return stderr;11 }1213 if (stderr === undefined) {14 return stdout;15 }1617 if (Array.isArray(stdout)) {18 return Array.isArray(stderr)19 ? [...stdout, ...stderr]20 : [...stdout, stripNewline(stderr, options, 'all')];21 }2223 if (Array.isArray(stderr)) {24 return [stripNewline(stdout, options, 'all'), ...stderr];25 }2627 if (isUint8Array(stdout) && isUint8Array(stderr)) {28 return concatUint8Arrays([stdout, stderr]);29 }3031 return `${stdout}${stderr}`;32};
modified:lib/stdio/async.js+4 added-54 removed
1import {createReadStream, createWriteStream} from 'node:fs';2import {Buffer} from 'node:buffer';3import {Readable, Writable, Duplex} from 'node:stream';4import mergeStreams from '@sindresorhus/merge-streams';5import {isStandardStream, incrementMaxListeners} from '../utils.js';4import {isStandardStream} from '../utils.js';5import {handleInput} from './handle.js';7import {pipeStreams} from './pipeline.js';6import {TYPE_TO_MESSAGE} from './type.js';9import {generatorToDuplexStream, pipeTransform, TRANSFORM_TYPES} from './generator.js';7import {generatorToStream} from './transform-run.js';89// Handle `input`, `inputFile`, `stdin`, `stdout` and `stderr` options, before spawning, in async mode10export const handleInputAsync = (options, verboseInfo) => handleInput(addPropertiesAsync, options, verboseInfo, false);11
1 unmodified line
13 throw new TypeError(`The \`${optionName}\` option cannot be ${TYPE_TO_MESSAGE[type]}.`);14};1516const addProperties = {19 generator: generatorToDuplexStream,20 asyncGenerator: generatorToDuplexStream,17 generator: generatorToStream,18 asyncGenerator: generatorToStream,19 nodeStream: ({value}) => ({stream: value}),20 webTransform({value: {transform, writableObjectMode, readableObjectMode}}) {21 const objectMode = writableObjectMode || readableObjectMode;22 const stream = Duplex.fromWeb(transform, {objectMode});
25 unmodified lines
48 uint8Array: forbiddenIfAsync,49 },50};5154// Handle `input`, `inputFile`, `stdin`, `stdout` and `stderr` options, after spawning, in async mode55// When multiple input streams are used, we merge them to ensure the output stream ends only once each input stream has ended56export const pipeOutputAsync = (subprocess, fileDescriptors, controller) => {57 const inputStreamsGroups = {};5859 for (const [fdNumber, {stdioItems, direction}] of Object.entries(fileDescriptors)) {60 for (const {stream} of stdioItems.filter(({type}) => TRANSFORM_TYPES.has(type))) {61 pipeTransform(subprocess, stream, direction, fdNumber);62 }6364 for (const {stream} of stdioItems.filter(({type}) => !TRANSFORM_TYPES.has(type))) {65 pipeStdioItem({subprocess, stream, direction, fdNumber, inputStreamsGroups, controller});66 }67 }6869 for (const [fdNumber, inputStreams] of Object.entries(inputStreamsGroups)) {70 const inputStream = inputStreams.length === 1 ? inputStreams[0] : mergeStreams(inputStreams);71 pipeStreams(inputStream, subprocess.stdio[fdNumber]);72 }73};7475const pipeStdioItem = ({subprocess, stream, direction, fdNumber, inputStreamsGroups, controller}) => {76 if (stream === undefined) {77 return;78 }7980 setStandardStreamMaxListeners(stream, controller);8182 if (direction === 'output') {83 pipeStreams(subprocess.stdio[fdNumber], stream);84 } else {85 inputStreamsGroups[fdNumber] = [...(inputStreamsGroups[fdNumber] ?? []), stream];86 }87};8889// Multiple subprocesses might be piping from/to `process.std*` at the same time.90// This is not necessarily an error and should not print a `maxListeners` warning.91const setStandardStreamMaxListeners = (stream, {signal}) => {92 if (isStandardStream(stream)) {93 incrementMaxListeners(stream, MAX_LISTENERS_INCREMENT, signal);94 }95};9697// `source.pipe(destination)` adds at most 1 listener for each event.98// If `stdin` option is an array, the values might be combined with `merge-streams`.99// That library also listens for `source` end, which adds 1 more listener.100const MAX_LISTENERS_INCREMENT = 2;10152// The stream error handling is performed by the piping logic above, which cannot be performed before subprocess spawning.53// If the subprocess spawning fails (e.g. due to an invalid command), the streams need to be manually destroyed.54// We need to create those streams before subprocess spawning, in case their creation fails, e.g. when passing an invalid generator as argument.55// Like this, an exception would be thrown, which would prevent spawning a subprocess.
9 unmodified lines
deleted:lib/stdio/generator.js-198 removed
1import isPlainObj from 'is-plain-obj';2import {BINARY_ENCODINGS} from '../arguments/encoding.js';3import {generatorsToTransform, runTransformSync} from './transform.js';4import {getEncodingTransformGenerator} from './encoding-transform.js';5import {getSplitLinesGenerator, getAppendNewlineGenerator} from './split.js';6import {pipeStreams} from './pipeline.js';7import {isAsyncGenerator} from './type.js';8import {getValidateTransformInput, getValidateTransformReturn} from './validate.js';910export const normalizeTransforms = (stdioItems, optionName, direction, options) => [11 ...stdioItems.filter(({type}) => !TRANSFORM_TYPES.has(type)),12 ...getTransforms(stdioItems, optionName, direction, options),13];1415const getTransforms = (stdioItems, optionName, direction, {encoding}) => {16 const transforms = stdioItems.filter(({type}) => TRANSFORM_TYPES.has(type));17 const newTransforms = Array.from({length: transforms.length});1819 for (const [index, stdioItem] of Object.entries(transforms)) {20 newTransforms[index] = normalizeTransform({stdioItem, index: Number(index), newTransforms, optionName, direction, encoding});21 }2223 return sortTransforms(newTransforms, direction);24};2526export const TRANSFORM_TYPES = new Set(['generator', 'asyncGenerator', 'duplex', 'webTransform']);2728const normalizeTransform = ({stdioItem, stdioItem: {type}, index, newTransforms, optionName, direction, encoding}) => {29 if (type === 'duplex') {30 return normalizeDuplex({stdioItem, optionName});31 }3233 if (type === 'webTransform') {34 return normalizeTransformStream({stdioItem, index, newTransforms, direction});35 }3637 return normalizeGenerator({stdioItem, index, newTransforms, direction, encoding});38};3940const normalizeDuplex = ({41 stdioItem,42 stdioItem: {43 value: {44 transform,45 transform: {writableObjectMode, readableObjectMode},46 objectMode = readableObjectMode,47 },48 },49 optionName,50}) => {51 if (objectMode && !readableObjectMode) {52 throw new TypeError(`The \`${optionName}.objectMode\` option can only be \`true\` if \`new Duplex({objectMode: true})\` is used.`);53 }5455 if (!objectMode && readableObjectMode) {56 throw new TypeError(`The \`${optionName}.objectMode\` option cannot be \`false\` if \`new Duplex({objectMode: true})\` is used.`);57 }5859 return {60 ...stdioItem,61 value: {transform, writableObjectMode, readableObjectMode},62 };63};6465const normalizeTransformStream = ({stdioItem, stdioItem: {value}, index, newTransforms, direction}) => {66 const {transform, objectMode} = isPlainObj(value) ? value : {transform: value};67 const {writableObjectMode, readableObjectMode} = getObjectModes(objectMode, index, newTransforms, direction);68 return ({69 ...stdioItem,70 value: {transform, writableObjectMode, readableObjectMode},71 });72};7374const normalizeGenerator = ({stdioItem, stdioItem: {value}, index, newTransforms, direction, encoding}) => {75 const {76 transform,77 final,78 binary: binaryOption = false,79 preserveNewlines = false,80 objectMode,81 } = isPlainObj(value) ? value : {transform: value};82 const binary = binaryOption || BINARY_ENCODINGS.has(encoding);83 const {writableObjectMode, readableObjectMode} = getObjectModes(objectMode, index, newTransforms, direction);84 return {...stdioItem, value: {transform, final, binary, preserveNewlines, writableObjectMode, readableObjectMode}};85};8687/*88`objectMode` determines the return value's type, i.e. the `readableObjectMode`.89The chunk argument's type is based on the previous generator's return value, i.e. the `writableObjectMode` is based on the previous `readableObjectMode`.90The last input's generator is read by `subprocess.stdin` which:91- should not be in `objectMode` for performance reasons.92- can only be strings, Buffers and Uint8Arrays.93Therefore its `readableObjectMode` must be `false`.94The same applies to the first output's generator's `writableObjectMode`.95*/96const getObjectModes = (objectMode, index, newTransforms, direction) => direction === 'output'97 ? getOutputObjectModes(objectMode, index, newTransforms)98 : getInputObjectModes(objectMode, index, newTransforms);99100const getOutputObjectModes = (objectMode, index, newTransforms) => {101 const writableObjectMode = index !== 0 && newTransforms[index - 1].value.readableObjectMode;102 const readableObjectMode = objectMode ?? writableObjectMode;103 return {writableObjectMode, readableObjectMode};104};105106const getInputObjectModes = (objectMode, index, newTransforms) => {107 const writableObjectMode = index === 0108 ? objectMode === true109 : newTransforms[index - 1].value.readableObjectMode;110 const readableObjectMode = index !== newTransforms.length - 1 && (objectMode ?? writableObjectMode);111 return {writableObjectMode, readableObjectMode};112};113114const sortTransforms = (newTransforms, direction) => direction === 'input' ? newTransforms.reverse() : newTransforms;115116export const getObjectMode = (stdioItems, direction) => {117 const lastTransform = stdioItems.findLast(({type}) => TRANSFORM_TYPES.has(type));118 if (lastTransform === undefined) {119 return false;120 }121122 return direction === 'input'123 ? lastTransform.value.writableObjectMode124 : lastTransform.value.readableObjectMode;125};126127/*128Generators can be used to transform/filter standard streams.129130Generators have a simple syntax, yet allows all of the following:131- Sharing `state` between chunks132- Flushing logic, by using a `final` function133- Asynchronous logic134- Emitting multiple chunks from a single source chunk, even if spaced in time, by using multiple `yield`135- Filtering, by using no `yield`136137Therefore, there is no need to allow Node.js or web transform streams.138139The `highWaterMark` is kept as the default value, since this is what `subprocess.std*` uses.140141Chunks are currently processed serially. We could add a `concurrency` option to parallelize in the future.142*/143export const generatorToDuplexStream = ({144 value,145 value: {transform, final, writableObjectMode, readableObjectMode},146 optionName,147}, {encoding}) => {148 const generators = addInternalGenerators(value, encoding, optionName);149 const transformAsync = isAsyncGenerator(transform);150 const finalAsync = isAsyncGenerator(final);151 const stream = generatorsToTransform(generators, {transformAsync, finalAsync, writableObjectMode, readableObjectMode});152 return {stream};153};154155export const getGenerators = stdioItems => stdioItems.filter(({type}) => type === 'generator');156157export const runGeneratorsSync = (chunks, generators, encoding) => {158 for (const {value, optionName} of generators) {159 const generators = addInternalGenerators(value, encoding, optionName);160 chunks = runTransformSync(generators, chunks);161 }162163 return chunks;164};165166const addInternalGenerators = (167 {transform, final, binary, writableObjectMode, readableObjectMode, preserveNewlines},168 encoding,169 optionName,170) => {171 const state = {};172 return [173 {transform: getValidateTransformInput(writableObjectMode, optionName)},174 getEncodingTransformGenerator(binary, encoding, writableObjectMode),175 getSplitLinesGenerator(binary, preserveNewlines, writableObjectMode, state),176 {transform, final},177 {transform: getValidateTransformReturn(readableObjectMode, optionName)},178 getAppendNewlineGenerator({binary, preserveNewlines, readableObjectMode, state}),179 ].filter(Boolean);180};181182// `subprocess.stdin|stdout|stderr|stdio` is directly mutated.183export const pipeTransform = (subprocess, stream, direction, fdNumber) => {184 if (direction === 'output') {185 pipeStreams(subprocess.stdio[fdNumber], stream);186 } else {187 pipeStreams(stream, subprocess.stdio[fdNumber]);188 }189190 const streamProperty = SUBPROCESS_STREAM_PROPERTIES[fdNumber];191 if (streamProperty !== undefined) {192 subprocess[streamProperty] = stream;193 }194195 subprocess.stdio[fdNumber] = stream;196};197198const SUBPROCESS_STREAM_PROPERTIES = ['stdin', 'stdout', 'stderr'];
modified:lib/stdio/handle.js+3 added-2 removed
2 unmodified lines
3import {getStreamDirection} from './direction.js';4import {normalizeStdio} from './option.js';5import {handleNativeStream} from './native.js';6import {handleInputOptions} from './input.js';7import {normalizeTransforms, getObjectMode} from './generator.js';7import {normalizeTransforms} from './normalize-transform.js';8import {getFdObjectMode} from './object-mode.js';910// Handle `input`, `inputFile`, `stdin`, `stdout` and `stderr` options, before spawning, in async/sync mode11export const handleInput = (addProperties, options, verboseInfo, isSync) => {12 const stdio = normalizeStdio(options, isSync);
11 unmodified lines
24 const {stdioItems: initialStdioItems, isStdioArray} = initializeStdioItems({stdioOption, fdNumber, options, optionName});25 const direction = getStreamDirection(initialStdioItems, fdNumber, optionName);26 const stdioItems = initialStdioItems.map(stdioItem => handleNativeStream({stdioItem, isStdioArray, fdNumber, direction, isSync}));27 const normalizedStdioItems = normalizeTransforms(stdioItems, optionName, direction, options);27 const objectMode = getObjectMode(normalizedStdioItems, direction);28 const objectMode = getFdObjectMode(normalizedStdioItems, direction);29 validateFileObjectMode(normalizedStdioItems, objectMode);30 const finalStdioItems = normalizedStdioItems.map(stdioItem => addStreamProperties(stdioItem, addProperties, direction, options));31 return {direction, objectMode, stdioItems: finalStdioItems};32};
94 unmodified lines
modified:lib/stdio/input-sync.js+2 added-3 removed
1import {joinToUint8Array, isUint8Array} from './uint-array.js';2import {TYPE_TO_MESSAGE} from './type.js';3import {getGenerators, runGeneratorsSync} from './generator.js';3import {runGeneratorsSync} from './transform-run.js';45// Apply `stdin`/`input`/`inputFile` options, before spawning, in sync mode, by converting it to the `input` option6export const addInputOptionsSync = (fileDescriptors, options) => {7 for (const fdNumber of getInputFdNumbers(fileDescriptors)) {
22 unmodified lines
30 options.input = joinToUint8Array(transformedContents);31};3233const applySingleInputGeneratorsSync = (contents, stdioItems) => {34 const generators = getGenerators(stdioItems).reverse();35 const newContents = runGeneratorsSync(contents, generators, 'utf8');34 const newContents = runGeneratorsSync(contents, stdioItems, 'utf8', true);35 validateSerializable(newContents);36 return joinToUint8Array(newContents);37};38
6 unmodified lines
modified:lib/stdio/native.js+1 added-8 removed
1import {readFileSync} from 'node:fs';2import tty from 'node:tty';3import {isStream as isNodeStream} from 'is-stream';4import {STANDARD_STREAMS} from '../utils.js';5import {serializeOptionValue} from '../convert/fd-options.js';6import {bufferToUint8Array} from './uint-array.js';78// When we use multiple `stdio` values for the same streams, we pass 'pipe' to `child_process.spawn()`.9// We then emulate the piping done by core Node.js.
56 unmodified lines
66 return standardStreamIndex;67 }68};6969export const serializeOptionValue = value => {70 if (typeof value === 'string') {71 return `'${value}'`;72 }7374 return typeof value === 'number' ? `${value}` : 'Stream';75};7670const handleNativeStreamAsync = ({stdioItem, stdioItem: {value, optionName}, fdNumber}) => {71 if (value === 'inherit') {72 return {type: 'nodeStream', value: getStandardStream(fdNumber, value, optionName), optionName};73 }
26 unmodified lines
added:lib/stdio/normalize-transform.js+83 added
1import isPlainObj from 'is-plain-obj';2import {BINARY_ENCODINGS} from '../arguments/encoding.js';3import {TRANSFORM_TYPES} from './type.js';4import {getTransformObjectModes} from './object-mode.js';56// Transforms generators/duplex/TransformStream can have multiple shapes.7// This normalizes it and applies default values.8export const normalizeTransforms = (stdioItems, optionName, direction, options) => [9 ...stdioItems.filter(({type}) => !TRANSFORM_TYPES.has(type)),10 ...getTransforms(stdioItems, optionName, direction, options),11];1213const getTransforms = (stdioItems, optionName, direction, {encoding}) => {14 const transforms = stdioItems.filter(({type}) => TRANSFORM_TYPES.has(type));15 const newTransforms = Array.from({length: transforms.length});1617 for (const [index, stdioItem] of Object.entries(transforms)) {18 newTransforms[index] = normalizeTransform({stdioItem, index: Number(index), newTransforms, optionName, direction, encoding});19 }2021 return sortTransforms(newTransforms, direction);22};2324const normalizeTransform = ({stdioItem, stdioItem: {type}, index, newTransforms, optionName, direction, encoding}) => {25 if (type === 'duplex') {26 return normalizeDuplex({stdioItem, optionName});27 }2829 if (type === 'webTransform') {30 return normalizeTransformStream({stdioItem, index, newTransforms, direction});31 }3233 return normalizeGenerator({stdioItem, index, newTransforms, direction, encoding});34};3536const normalizeDuplex = ({37 stdioItem,38 stdioItem: {39 value: {40 transform,41 transform: {writableObjectMode, readableObjectMode},42 objectMode = readableObjectMode,43 },44 },45 optionName,46}) => {47 if (objectMode && !readableObjectMode) {48 throw new TypeError(`The \`${optionName}.objectMode\` option can only be \`true\` if \`new Duplex({objectMode: true})\` is used.`);49 }5051 if (!objectMode && readableObjectMode) {52 throw new TypeError(`The \`${optionName}.objectMode\` option cannot be \`false\` if \`new Duplex({objectMode: true})\` is used.`);53 }5455 return {56 ...stdioItem,57 value: {transform, writableObjectMode, readableObjectMode},58 };59};6061const normalizeTransformStream = ({stdioItem, stdioItem: {value}, index, newTransforms, direction}) => {62 const {transform, objectMode} = isPlainObj(value) ? value : {transform: value};63 const {writableObjectMode, readableObjectMode} = getTransformObjectModes(objectMode, index, newTransforms, direction);64 return ({65 ...stdioItem,66 value: {transform, writableObjectMode, readableObjectMode},67 });68};6970const normalizeGenerator = ({stdioItem, stdioItem: {value}, index, newTransforms, direction, encoding}) => {71 const {72 transform,73 final,74 binary: binaryOption = false,75 preserveNewlines = false,76 objectMode,77 } = isPlainObj(value) ? value : {transform: value};78 const binary = binaryOption || BINARY_ENCODINGS.has(encoding);79 const {writableObjectMode, readableObjectMode} = getTransformObjectModes(objectMode, index, newTransforms, direction);80 return {...stdioItem, value: {transform, final, binary, preserveNewlines, writableObjectMode, readableObjectMode}};81};8283const sortTransforms = (newTransforms, direction) => direction === 'input' ? newTransforms.reverse() : newTransforms;
added:lib/stdio/object-mode.js+41 added
1import {TRANSFORM_TYPES} from './type.js';23/*4Retrieve the `objectMode`s of a single transform.5`objectMode` determines the return value's type, i.e. the `readableObjectMode`.6The chunk argument's type is based on the previous generator's return value, i.e. the `writableObjectMode` is based on the previous `readableObjectMode`.7The last input's generator is read by `subprocess.stdin` which:8- should not be in `objectMode` for performance reasons.9- can only be strings, Buffers and Uint8Arrays.10Therefore its `readableObjectMode` must be `false`.11The same applies to the first output's generator's `writableObjectMode`.12*/13export const getTransformObjectModes = (objectMode, index, newTransforms, direction) => direction === 'output'14 ? getOutputObjectModes(objectMode, index, newTransforms)15 : getInputObjectModes(objectMode, index, newTransforms);1617const getOutputObjectModes = (objectMode, index, newTransforms) => {18 const writableObjectMode = index !== 0 && newTransforms[index - 1].value.readableObjectMode;19 const readableObjectMode = objectMode ?? writableObjectMode;20 return {writableObjectMode, readableObjectMode};21};2223const getInputObjectModes = (objectMode, index, newTransforms) => {24 const writableObjectMode = index === 025 ? objectMode === true26 : newTransforms[index - 1].value.readableObjectMode;27 const readableObjectMode = index !== newTransforms.length - 1 && (objectMode ?? writableObjectMode);28 return {writableObjectMode, readableObjectMode};29};3031// Retrieve the `objectMode` of a file descriptor, e.g. `stdout` or `stderr`32export const getFdObjectMode = (stdioItems, direction) => {33 const lastTransform = stdioItems.findLast(({type}) => TRANSFORM_TYPES.has(type));34 if (lastTransform === undefined) {35 return false;36 }3738 return direction === 'input'39 ? lastTransform.value.writableObjectMode40 : lastTransform.value.readableObjectMode;41};
added:lib/stdio/output-async.js+71 added
1import mergeStreams from '@sindresorhus/merge-streams';2import {isStandardStream} from '../utils.js';3import {incrementMaxListeners} from '../max-listener.js';4import {pipeStreams} from './pipeline.js';5import {TRANSFORM_TYPES} from './type.js';67// Handle `input`, `inputFile`, `stdin`, `stdout` and `stderr` options, after spawning, in async mode8// When multiple input streams are used, we merge them to ensure the output stream ends only once each input stream has ended9export const pipeOutputAsync = (subprocess, fileDescriptors, controller) => {10 const inputStreamsGroups = {};1112 for (const [fdNumber, {stdioItems, direction}] of Object.entries(fileDescriptors)) {13 for (const {stream} of stdioItems.filter(({type}) => TRANSFORM_TYPES.has(type))) {14 pipeTransform(subprocess, stream, direction, fdNumber);15 }1617 for (const {stream} of stdioItems.filter(({type}) => !TRANSFORM_TYPES.has(type))) {18 pipeStdioItem({subprocess, stream, direction, fdNumber, inputStreamsGroups, controller});19 }20 }2122 for (const [fdNumber, inputStreams] of Object.entries(inputStreamsGroups)) {23 const inputStream = inputStreams.length === 1 ? inputStreams[0] : mergeStreams(inputStreams);24 pipeStreams(inputStream, subprocess.stdio[fdNumber]);25 }26};2728// `subprocess.stdin|stdout|stderr|stdio` is directly mutated.29const pipeTransform = (subprocess, stream, direction, fdNumber) => {30 if (direction === 'output') {31 pipeStreams(subprocess.stdio[fdNumber], stream);32 } else {33 pipeStreams(stream, subprocess.stdio[fdNumber]);34 }3536 const streamProperty = SUBPROCESS_STREAM_PROPERTIES[fdNumber];37 if (streamProperty !== undefined) {38 subprocess[streamProperty] = stream;39 }4041 subprocess.stdio[fdNumber] = stream;42};4344const SUBPROCESS_STREAM_PROPERTIES = ['stdin', 'stdout', 'stderr'];4546const pipeStdioItem = ({subprocess, stream, direction, fdNumber, inputStreamsGroups, controller}) => {47 if (stream === undefined) {48 return;49 }5051 setStandardStreamMaxListeners(stream, controller);5253 if (direction === 'output') {54 pipeStreams(subprocess.stdio[fdNumber], stream);55 } else {56 inputStreamsGroups[fdNumber] = [...(inputStreamsGroups[fdNumber] ?? []), stream];57 }58};5960// Multiple subprocesses might be piping from/to `process.std*` at the same time.61// This is not necessarily an error and should not print a `maxListeners` warning.62const setStandardStreamMaxListeners = (stream, {signal}) => {63 if (isStandardStream(stream)) {64 incrementMaxListeners(stream, MAX_LISTENERS_INCREMENT, signal);65 }66};6768// `source.pipe(destination)` adds at most 1 listener for each event.69// If `stdin` option is an array, the values might be combined with `merge-streams`.70// That library also listens for `source` end, which adds 1 more listener.71const MAX_LISTENERS_INCREMENT = 2;
modified:lib/stdio/output-sync.js+5 added-37 removed
1import {writeFileSync} from 'node:fs';2import {shouldLogOutput, logLinesSync} from '../verbose/output.js';3import {getMaxBufferSync} from '../stream/max-buffer.js';4import {stripNewline} from '../return/output.js';5import {joinToString, joinToUint8Array, bufferToUint8Array, isUint8Array, concatUint8Arrays} from './uint-array.js';6import {getGenerators, runGeneratorsSync} from './generator.js';4import {joinToString, joinToUint8Array, bufferToUint8Array} from './uint-array.js';5import {runGeneratorsSync} from './transform-run.js';6import {splitLinesSync} from './split.js';7import {FILE_TYPES} from './type.js';89// Apply `stdout`/`stderr` options, after spawning, in sync mode
15 unmodified lines
2526 const truncatedResult = truncateResult(result, isMaxBuffer, getMaxBufferSync(maxBuffer));27 const uint8ArrayResult = bufferToUint8Array(truncatedResult);28 const {stdioItems, objectMode} = fileDescriptors[fdNumber];30 const generators = getGenerators(stdioItems);31 const chunks = runOutputGeneratorsSync([uint8ArrayResult], generators, encoding, state);29 const chunks = runOutputGeneratorsSync([uint8ArrayResult], stdioItems, encoding, state);30 const {31 serializedResult,32 finalResult = serializedResult,33 } = serializeChunks({chunks, objectMode, encoding, lines, stripFinalNewline, fdNumber});
20 unmodified lines
54const truncateResult = (result, isMaxBuffer, maxBuffer) => isMaxBuffer && result.length > maxBuffer55 ? result.slice(0, maxBuffer)56 : result;5760const runOutputGeneratorsSync = (chunks, generators, encoding, state) => {58const runOutputGeneratorsSync = (chunks, stdioItems, encoding, state) => {59 try {62 return runGeneratorsSync(chunks, generators, encoding);60 return runGeneratorsSync(chunks, stdioItems, encoding, false);61 } catch (error) {62 state.error = error;63 return chunks;64 }
22 unmodified lines
87 writeFileSync(path, serializedResult);88 }89 }90};9394export const getAllSync = ([, stdout, stderr], options) => {95 if (!options.all) {96 return;97 }9899 if (stdout === undefined) {100 return stderr;101 }102103 if (stderr === undefined) {104 return stdout;105 }106107 if (Array.isArray(stdout)) {108 return Array.isArray(stderr)109 ? [...stdout, ...stderr]110 : [...stdout, stripNewline(stderr, options, 'all')];111 }112113 if (Array.isArray(stderr)) {114 return [stripNewline(stdout, options, 'all'), ...stderr];115 }116117 if (isUint8Array(stdout) && isUint8Array(stderr)) {118 return concatUint8Arrays([stdout, stderr]);119 }120121 return `${stdout}${stderr}`;122};
added:lib/stdio/transform-async.js+59 added
1import {callbackify} from 'node:util';23export const pushChunks = callbackify(async (getChunks, state, args, transformStream) => {4 state.currentIterable = getChunks(...args);56 try {7 for await (const chunk of state.currentIterable) {8 transformStream.push(chunk);9 }10 } finally {11 delete state.currentIterable;12 }13});1415// For each new chunk, apply each `transform()` method16export const transformChunk = async function * (chunk, generators, index) {17 if (index === generators.length) {18 yield chunk;19 return;20 }2122 const {transform = identityGenerator} = generators[index];23 for await (const transformedChunk of transform(chunk)) {24 yield * transformChunk(transformedChunk, generators, index + 1);25 }26};2728// At the end, apply each `final()` method, followed by the `transform()` method of the next transforms29export const finalChunks = async function * (generators) {30 for (const [index, {final}] of Object.entries(generators)) {31 yield * generatorFinalChunks(final, Number(index), generators);32 }33};3435const generatorFinalChunks = async function * (final, index, generators) {36 if (final === undefined) {37 return;38 }3940 for await (const finalChunk of final()) {41 yield * transformChunk(finalChunk, generators, index + 1);42 }43};4445// Cancel any ongoing async generator when the Transform is destroyed, e.g. when the subprocess errors46export const destroyTransform = callbackify(async ({currentIterable}, error) => {47 if (currentIterable !== undefined) {48 await (error ? currentIterable.throw(error) : currentIterable.return());49 return;50 }5152 if (error) {53 throw error;54 }55});5657const identityGenerator = function * (chunk) {58 yield chunk;59};
added:lib/stdio/transform-run.js+90 added
1import {Transform, getDefaultHighWaterMark} from 'node:stream';2import {pushChunks, transformChunk, finalChunks, destroyTransform} from './transform-async.js';3import {pushChunksSync, transformChunkSync, finalChunksSync, runTransformSync} from './transform-sync.js';4import {getEncodingTransformGenerator} from './encoding-transform.js';5import {getSplitLinesGenerator, getAppendNewlineGenerator} from './split.js';6import {getValidateTransformInput, getValidateTransformReturn} from './validate.js';7import {isAsyncGenerator} from './type.js';89/*10Generators can be used to transform/filter standard streams.1112Generators have a simple syntax, yet allows all of the following:13- Sharing `state` between chunks14- Flushing logic, by using a `final` function15- Asynchronous logic16- Emitting multiple chunks from a single source chunk, even if spaced in time, by using multiple `yield`17- Filtering, by using no `yield`1819Therefore, there is no need to allow Node.js or web transform streams.2021The `highWaterMark` is kept as the default value, since this is what `subprocess.std*` uses.2223Chunks are currently processed serially. We could add a `concurrency` option to parallelize in the future.2425Transform an array of generator functions into a `Transform` stream.26`Duplex.from(generator)` cannot be used because it does not allow setting the `objectMode` and `highWaterMark`.27*/28export const generatorToStream = ({29 value,30 value: {transform, final, writableObjectMode, readableObjectMode},31 optionName,32}, {encoding}) => {33 const state = {};34 const generators = addInternalGenerators(value, encoding, optionName);3536 const transformAsync = isAsyncGenerator(transform);37 const finalAsync = isAsyncGenerator(final);38 const transformMethod = transformAsync39 ? pushChunks.bind(undefined, transformChunk, state)40 : pushChunksSync.bind(undefined, transformChunkSync);41 const finalMethod = transformAsync || finalAsync42 ? pushChunks.bind(undefined, finalChunks, state)43 : pushChunksSync.bind(undefined, finalChunksSync);44 const destroyMethod = transformAsync || finalAsync45 ? destroyTransform.bind(undefined, state)46 : undefined;4748 const stream = new Transform({49 writableObjectMode,50 writableHighWaterMark: getDefaultHighWaterMark(writableObjectMode),51 readableObjectMode,52 readableHighWaterMark: getDefaultHighWaterMark(readableObjectMode),53 transform(chunk, encoding, done) {54 transformMethod([chunk, generators, 0], this, done);55 },56 flush(done) {57 finalMethod([generators], this, done);58 },59 destroy: destroyMethod,60 });61 return {stream};62};6364export const runGeneratorsSync = (chunks, stdioItems, encoding, isInput) => {65 const generators = stdioItems.filter(({type}) => type === 'generator');66 const reversedGenerators = isInput ? generators.reverse() : generators;6768 for (const {value, optionName} of reversedGenerators) {69 const generators = addInternalGenerators(value, encoding, optionName);70 chunks = runTransformSync(generators, chunks);71 }7273 return chunks;74};7576const addInternalGenerators = (77 {transform, final, binary, writableObjectMode, readableObjectMode, preserveNewlines},78 encoding,79 optionName,80) => {81 const state = {};82 return [83 {transform: getValidateTransformInput(writableObjectMode, optionName)},84 getEncodingTransformGenerator(binary, encoding, writableObjectMode),85 getSplitLinesGenerator(binary, preserveNewlines, writableObjectMode, state),86 {transform, final},87 {transform: getValidateTransformReturn(readableObjectMode, optionName)},88 getAppendNewlineGenerator({binary, preserveNewlines, readableObjectMode, state}),89 ].filter(Boolean);90};
added:lib/stdio/transform-sync.js+50 added
1// Duplicate the code from `transform-async.js` but as synchronous functions2export const pushChunksSync = (getChunksSync, args, transformStream, done) => {3 try {4 for (const chunk of getChunksSync(...args)) {5 transformStream.push(chunk);6 }78 done();9 } catch (error) {10 done(error);11 }12};1314// Run synchronous generators with `execaSync()`15export const runTransformSync = (generators, chunks) => [16 ...chunks.flatMap(chunk => [...transformChunkSync(chunk, generators, 0)]),17 ...finalChunksSync(generators),18];1920export const transformChunkSync = function * (chunk, generators, index) {21 if (index === generators.length) {22 yield chunk;23 return;24 }2526 const {transform = identityGenerator} = generators[index];27 for (const transformedChunk of transform(chunk)) {28 yield * transformChunkSync(transformedChunk, generators, index + 1);29 }30};3132export const finalChunksSync = function * (generators) {33 for (const [index, {final}] of Object.entries(generators)) {34 yield * generatorFinalChunksSync(final, Number(index), generators);35 }36};3738const generatorFinalChunksSync = function * (final, index, generators) {39 if (final === undefined) {40 return;41 }4243 for (const finalChunk of final()) {44 yield * transformChunkSync(finalChunk, generators, index + 1);45 }46};4748const identityGenerator = function * (chunk) {49 yield chunk;50};
deleted:lib/stdio/transform.js-137 removed
1import {Transform, getDefaultHighWaterMark} from 'node:stream';2import {callbackify} from 'node:util';34// Transform an array of generator functions into a `Transform` stream.5// `Duplex.from(generator)` cannot be used because it does not allow setting the `objectMode` and `highWaterMark`.6export const generatorsToTransform = (generators, {transformAsync, finalAsync, writableObjectMode, readableObjectMode}) => {7 const state = {};8 const transformMethod = transformAsync9 ? pushChunks.bind(undefined, transformChunk, state)10 : pushChunksSync.bind(undefined, transformChunkSync);11 const finalMethod = transformAsync || finalAsync12 ? pushChunks.bind(undefined, finalChunks, state)13 : pushChunksSync.bind(undefined, finalChunksSync);14 const destroyMethod = transformAsync || finalAsync15 ? destroyTransform.bind(undefined, state)16 : undefined;1718 return new Transform({19 writableObjectMode,20 writableHighWaterMark: getDefaultHighWaterMark(writableObjectMode),21 readableObjectMode,22 readableHighWaterMark: getDefaultHighWaterMark(readableObjectMode),23 transform(chunk, encoding, done) {24 transformMethod([chunk, generators, 0], this, done);25 },26 flush(done) {27 finalMethod([generators], this, done);28 },29 destroy: destroyMethod,30 });31};3233const pushChunks = callbackify(async (getChunks, state, args, transformStream) => {34 state.currentIterable = getChunks(...args);3536 try {37 for await (const chunk of state.currentIterable) {38 transformStream.push(chunk);39 }40 } finally {41 delete state.currentIterable;42 }43});4445// For each new chunk, apply each `transform()` method46const transformChunk = async function * (chunk, generators, index) {47 if (index === generators.length) {48 yield chunk;49 return;50 }5152 const {transform = identityGenerator} = generators[index];53 for await (const transformedChunk of transform(chunk)) {54 yield * transformChunk(transformedChunk, generators, index + 1);55 }56};5758// At the end, apply each `final()` method, followed by the `transform()` method of the next transforms59const finalChunks = async function * (generators) {60 for (const [index, {final}] of Object.entries(generators)) {61 yield * generatorFinalChunks(final, Number(index), generators);62 }63};6465const generatorFinalChunks = async function * (final, index, generators) {66 if (final === undefined) {67 return;68 }6970 for await (const finalChunk of final()) {71 yield * transformChunk(finalChunk, generators, index + 1);72 }73};7475// Cancel any ongoing async generator when the Transform is destroyed, e.g. when the subprocess errors76const destroyTransform = callbackify(async ({currentIterable}, error) => {77 if (currentIterable !== undefined) {78 await (error ? currentIterable.throw(error) : currentIterable.return());79 return;80 }8182 if (error) {83 throw error;84 }85});8687// Duplicate the code above but as synchronous functions.88// This is a performance optimization when the `transform`/`flush` function is synchronous, which is the common case.89const pushChunksSync = (getChunksSync, args, transformStream, done) => {90 try {91 for (const chunk of getChunksSync(...args)) {92 transformStream.push(chunk);93 }9495 done();96 } catch (error) {97 done(error);98 }99};100101// Run synchronous generators with `execaSync()`102export const runTransformSync = (generators, chunks) => [103 ...chunks.flatMap(chunk => [...transformChunkSync(chunk, generators, 0)]),104 ...finalChunksSync(generators),105];106107export const transformChunkSync = function * (chunk, generators, index) {108 if (index === generators.length) {109 yield chunk;110 return;111 }112113 const {transform = identityGenerator} = generators[index];114 for (const transformedChunk of transform(chunk)) {115 yield * transformChunkSync(transformedChunk, generators, index + 1);116 }117};118119export const finalChunksSync = function * (generators) {120 for (const [index, {final}] of Object.entries(generators)) {121 yield * generatorFinalChunksSync(final, Number(index), generators);122 }123};124125const generatorFinalChunksSync = function * (final, index, generators) {126 if (final === undefined) {127 return;128 }129130 for (const finalChunk of final()) {131 yield * transformChunkSync(finalChunk, generators, index + 1);132 }133};134135const identityGenerator = function * (chunk) {136 yield chunk;137};
modified:lib/stdio/type.js+1 added
140 unmodified lines
141const isAsyncIterableObject = value => isObject(value) && typeof value[Symbol.asyncIterator] === 'function';142const isIterableObject = value => isObject(value) && typeof value[Symbol.iterator] === 'function';143const isObject = value => typeof value === 'object' && value !== null;144145export const TRANSFORM_TYPES = new Set(['generator', 'asyncGenerator', 'duplex', 'webTransform']);146export const FILE_TYPES = new Set(['fileUrl', 'filePath', 'fileNumber']);147148// Convert types to human-friendly strings for error messages149export const TYPE_TO_MESSAGE = {
14 unmodified lines
added:lib/stream/contents.js+63 added
1import {setImmediate} from 'node:timers/promises';2import getStream, {getStreamAsArrayBuffer, getStreamAsArray} from 'get-stream';3import {isArrayBuffer} from '../stdio/uint-array.js';4import {iterateForResult} from '../convert/loop.js';5import {shouldLogOutput, logLines} from '../verbose/output.js';6import {getStripFinalNewline} from '../return/strip-newline.js';7import {handleMaxBuffer} from './max-buffer.js';89export const getStreamOutput = async ({stream, onStreamEnd, fdNumber, encoding, buffer, maxBuffer, lines, allMixed, stripFinalNewline, verboseInfo, streamInfo: {fileDescriptors}}) => {10 if (shouldLogOutput({stdioItems: fileDescriptors[fdNumber]?.stdioItems, encoding, verboseInfo, fdNumber})) {11 const linesIterable = iterateForResult({stream, onStreamEnd, lines: true, encoding, stripFinalNewline: true, allMixed});12 logLines(linesIterable, stream, verboseInfo);13 }1415 if (!buffer) {16 await resumeStream(stream);17 return;18 }1920 const stripFinalNewlineValue = getStripFinalNewline(stripFinalNewline, fdNumber);21 const iterable = iterateForResult({stream, onStreamEnd, lines, encoding, stripFinalNewline: stripFinalNewlineValue, allMixed});22 return getStreamContents({stream, iterable, fdNumber, encoding, maxBuffer, lines});23};2425// When using `buffer: false`, users need to read `subprocess.stdout|stderr|all` right away26// See https://github.com/sindresorhus/execa/issues/730 and https://github.com/sindresorhus/execa/pull/729#discussion_r146549631027const resumeStream = async stream => {28 await setImmediate();29 if (stream.readableFlowing === null) {30 stream.resume();31 }32};3334const getStreamContents = async ({stream, stream: {readableObjectMode}, iterable, fdNumber, encoding, maxBuffer, lines}) => {35 try {36 if (readableObjectMode || lines) {37 return await getStreamAsArray(iterable, {maxBuffer});38 }3940 if (encoding === 'buffer') {41 return new Uint8Array(await getStreamAsArrayBuffer(iterable, {maxBuffer}));42 }4344 return await getStream(iterable, {maxBuffer});45 } catch (error) {46 return handleBufferedData(handleMaxBuffer({error, stream, readableObjectMode, lines, encoding, fdNumber}));47 }48};4950// On failure, `result.stdout|stderr|all` should contain the currently buffered stream51// They are automatically closed and flushed by Node.js when the subprocess exits52// When `buffer` is `false`, `streamPromise` is `undefined` and there is no buffered data to retrieve53export const getBufferedData = async streamPromise => {54 try {55 return await streamPromise;56 } catch (error) {57 return handleBufferedData(error);58 }59};6061const handleBufferedData = ({bufferedData}) => isArrayBuffer(bufferedData)62 ? new Uint8Array(bufferedData)63 : bufferedData;
added:lib/stream/exit-async.js+45 added
1import {once} from 'node:events';2import {DiscardedError} from '../return/cause.js';34// If `error` is emitted before `spawn`, `exit` will never be emitted.5// However, `error` might be emitted after `spawn`, e.g. with the `cancelSignal` option.6// In that case, `exit` will still be emitted.7// Since the `exit` event contains the signal name, we want to make sure we are listening for it.8// This function also takes into account the following unlikely cases:9// - `exit` being emitted in the same microtask as `spawn`10// - `error` being emitted multiple times11export const waitForExit = async subprocess => {12 const [spawnPayload, exitPayload] = await Promise.allSettled([13 once(subprocess, 'spawn'),14 once(subprocess, 'exit'),15 ]);1617 if (spawnPayload.status === 'rejected') {18 return [];19 }2021 return exitPayload.status === 'rejected'22 ? waitForSubprocessExit(subprocess)23 : exitPayload.value;24};2526const waitForSubprocessExit = async subprocess => {27 try {28 return await once(subprocess, 'exit');29 } catch {30 return waitForSubprocessExit(subprocess);31 }32};3334export const waitForSuccessfulExit = async exitPromise => {35 const [exitCode, signal] = await exitPromise;3637 if (!isSubprocessErrorExit(exitCode, signal) && isFailedExit(exitCode, signal)) {38 throw new DiscardedError();39 }4041 return [exitCode, signal];42};4344const isSubprocessErrorExit = (exitCode, signal) => exitCode === undefined && signal === undefined;45export const isFailedExit = (exitCode, signal) => exitCode !== 0 || signal !== null;
added:lib/stream/exit-sync.js+18 added
1import {DiscardedError} from '../return/cause.js';2import {isMaxBufferSync} from './max-buffer.js';3import {isFailedExit} from './exit-async.js';45export const getExitResultSync = ({error, status: exitCode, signal, output}, {maxBuffer}) => {6 const resultError = getResultError(error, exitCode, signal);7 const timedOut = resultError?.code === 'ETIMEDOUT';8 const isMaxBuffer = isMaxBufferSync(resultError, output, maxBuffer);9 return {resultError, exitCode, signal, timedOut, isMaxBuffer};10};1112const getResultError = (error, exitCode, signal) => {13 if (error !== undefined) {14 return error;15 }1617 return isFailedExit(exitCode, signal) ? new DiscardedError() : undefined;18};
deleted:lib/stream/exit.js-31 removed
1import {once} from 'node:events';23// If `error` is emitted before `spawn`, `exit` will never be emitted.4// However, `error` might be emitted after `spawn`, e.g. with the `cancelSignal` option.5// In that case, `exit` will still be emitted.6// Since the `exit` event contains the signal name, we want to make sure we are listening for it.7// This function also takes into account the following unlikely cases:8// - `exit` being emitted in the same microtask as `spawn`9// - `error` being emitted multiple times10export const waitForExit = async subprocess => {11 const [spawnPayload, exitPayload] = await Promise.allSettled([12 once(subprocess, 'spawn'),13 once(subprocess, 'exit'),14 ]);1516 if (spawnPayload.status === 'rejected') {17 return [];18 }1920 return exitPayload.status === 'rejected'21 ? waitForSubprocessExit(subprocess)22 : exitPayload.value;23};2425const waitForSubprocessExit = async subprocess => {26 try {27 return await once(subprocess, 'exit');28 } catch {29 return waitForSubprocessExit(subprocess);30 }31};
modified:lib/stream/resolve.js+4 added-8 removed
1import {once} from 'node:events';2import {isStream as isNodeStream} from 'is-stream';3import {waitForSuccessfulExit} from '../exit/code.js';3import {errorSignal} from '../exit/kill.js';4import {throwOnTimeout} from '../exit/timeout.js';5import {isStandardStream} from '../utils.js';7import {TRANSFORM_TYPES} from '../stdio/generator.js';6import {TRANSFORM_TYPES} from '../stdio/type.js';7import {waitForAllStream} from './all.js';9import {waitForSubprocessStream, getBufferedData} from './subprocess.js';10import {waitForExit} from './exit.js';8import {waitForSubprocessStreams} from './subprocess.js';9import {getBufferedData} from './contents.js';10import {waitForExit, waitForSuccessfulExit} from './exit-async.js';11import {waitForStream} from './wait.js';1213// Retrieve result of subprocess: exit code, signal, error, streams (stdout/stderr/all)14export const getSubprocessResult = async ({
38 unmodified lines
53 ]);54 }55};5657// Read the contents of `subprocess.std*` and|or wait for its completion58const waitForSubprocessStreams = ({subprocess, encoding, buffer, maxBuffer, lines, stripFinalNewline, verboseInfo, streamInfo}) =>59 subprocess.stdio.map((stream, fdNumber) => waitForSubprocessStream({stream, fdNumber, encoding, buffer: buffer[fdNumber], maxBuffer: maxBuffer[fdNumber], lines: lines[fdNumber], allMixed: false, stripFinalNewline, verboseInfo, streamInfo}));6057// Transforms replace `subprocess.std*`, which means they are not exposed to users.58// However, we still want to wait for their completion.59const waitForOriginalStreams = (originalStreams, subprocess, streamInfo) =>60 originalStreams.map((stream, fdNumber) => stream === subprocess.stdio[fdNumber]
22 unmodified lines
modified:lib/stream/subprocess.js+21 added-69 removed
1import {setImmediate} from 'node:timers/promises';2import getStream, {getStreamAsArrayBuffer, getStreamAsArray} from 'get-stream';3import {iterateForResult} from '../convert/loop.js';4import {isArrayBuffer} from '../stdio/uint-array.js';5import {shouldLogOutput, logLines} from '../verbose/output.js';6import {getStripFinalNewline} from '../return/output.js';7import {handleMaxBuffer} from './max-buffer.js';1import {waitForStream, isInputFileDescriptor} from './wait.js';2import {getStreamOutput} from './contents.js';34// Read the contents of `subprocess.std*` and|or wait for its completion5export const waitForSubprocessStreams = ({subprocess, encoding, buffer, maxBuffer, lines, stripFinalNewline, verboseInfo, streamInfo}) => subprocess.stdio.map((stream, fdNumber) => waitForSubprocessStream({6 stream,7 fdNumber,8 encoding,9 buffer: buffer[fdNumber],10 maxBuffer: maxBuffer[fdNumber],11 lines: lines[fdNumber],12 allMixed: false,13 stripFinalNewline,14 verboseInfo,15 streamInfo,16}));1718export const waitForSubprocessStream = async ({stream, fdNumber, encoding, buffer, maxBuffer, lines, allMixed, stripFinalNewline, verboseInfo, streamInfo}) => {19 if (!stream) {20 return;21 }2223 const onStreamEnd = waitForStream(stream, fdNumber, streamInfo);24 if (isInputFileDescriptor(streamInfo, fdNumber)) {25 await onStreamEnd;26 return;27 }2829 const [output] = await Promise.all([17 waitForDefinedStream({stream, onStreamEnd, fdNumber, encoding, buffer, maxBuffer, lines, allMixed, stripFinalNewline, verboseInfo, streamInfo}),30 getStreamOutput({stream, onStreamEnd, fdNumber, encoding, buffer, maxBuffer, lines, allMixed, stripFinalNewline, verboseInfo, streamInfo}),31 onStreamEnd,32 ]);33 return output;34};2223const waitForDefinedStream = async ({stream, onStreamEnd, fdNumber, encoding, buffer, maxBuffer, lines, allMixed, stripFinalNewline, verboseInfo, streamInfo, streamInfo: {fileDescriptors}}) => {24 if (isInputFileDescriptor(streamInfo, fdNumber)) {25 return;26 }2728 if (shouldLogOutput({stdioItems: fileDescriptors[fdNumber]?.stdioItems, encoding, verboseInfo, fdNumber})) {29 const linesIterable = iterateForResult({stream, onStreamEnd, lines: true, encoding, stripFinalNewline: true, allMixed});30 logLines(linesIterable, stream, verboseInfo);31 }3233 if (!buffer) {34 await resumeStream(stream);35 return;36 }3738 const stripFinalNewlineValue = getStripFinalNewline(stripFinalNewline, fdNumber);39 const iterable = iterateForResult({stream, onStreamEnd, lines, encoding, stripFinalNewline: stripFinalNewlineValue, allMixed});40 return getStreamContents({stream, iterable, fdNumber, encoding, maxBuffer, lines});41};4243// When using `buffer: false`, users need to read `subprocess.stdout|stderr|all` right away44// See https://github.com/sindresorhus/execa/issues/730 and https://github.com/sindresorhus/execa/pull/729#discussion_r146549631045const resumeStream = async stream => {46 await setImmediate();47 if (stream.readableFlowing === null) {48 stream.resume();49 }50};5152const getStreamContents = async ({stream, stream: {readableObjectMode}, iterable, fdNumber, encoding, maxBuffer, lines}) => {53 try {54 if (readableObjectMode || lines) {55 return await getStreamAsArray(iterable, {maxBuffer});56 }5758 if (encoding === 'buffer') {59 return new Uint8Array(await getStreamAsArrayBuffer(iterable, {maxBuffer}));60 }6162 return await getStream(iterable, {maxBuffer});63 } catch (error) {64 return handleBufferedData(handleMaxBuffer({error, stream, readableObjectMode, lines, encoding, fdNumber}));65 }66};6768// On failure, `result.stdout|stderr|all` should contain the currently buffered stream69// They are automatically closed and flushed by Node.js when the subprocess exits70// When `buffer` is `false`, `streamPromise` is `undefined` and there is no buffered data to retrieve71export const getBufferedData = async streamPromise => {72 try {73 return await streamPromise;74 } catch (error) {75 return handleBufferedData(error);76 }77};7879const handleBufferedData = ({bufferedData}) => isArrayBuffer(bufferedData)80 ? new Uint8Array(bufferedData)81 : bufferedData;82
modified:lib/verbose/output.js+1 added-1 removed
1import {inspect} from 'node:util';2import {escapeLines} from '../arguments/escape.js';3import {BINARY_ENCODINGS} from '../arguments/encoding.js';4import {TRANSFORM_TYPES} from '../stdio/generator.js';4import {TRANSFORM_TYPES} from '../stdio/type.js';5import {verboseLog} from './log.js';67// `ignore` opts-out of `verbose` for a specific stream.8// `ipc` cannot use piping.
51 unmodified lines
modified:lib/async.js+7 added-4 removed
1import {setMaxListeners} from 'node:events';2import {spawn} from 'node:child_process';3import {MaxBufferError} from 'get-stream';4import {handleCommand, handleOptions} from './arguments/options.js';4import {handleCommand} from './arguments/command.js';5import {handleOptions} from './arguments/options.js';6import {makeError, makeSuccessResult} from './return/error.js';6import {stripNewline, handleResult} from './return/output.js';7import {stripNewline} from './return/strip-newline.js';8import {handleResult} from './return/reject.js';9import {handleEarlyError} from './return/early-error.js';8import {handleInputAsync, pipeOutputAsync} from './stdio/async.js';10import {handleInputAsync} from './stdio/async.js';11import {pipeOutputAsync} from './stdio/output-async.js';12import {subprocessKill} from './exit/kill.js';13import {cleanupOnExit} from './exit/cleanup.js';14import {pipeToSubprocess} from './pipe/setup.js';12import {SUBPROCESS_OPTIONS} from './pipe/validate.js';15import {SUBPROCESS_OPTIONS} from './convert/fd-options.js';16import {logEarlyResult} from './verbose/complete.js';17import {makeAllStream} from './stream/all.js';18import {addConvertedStreams} from './convert/add.js';19import {getSubprocessResult} from './stream/resolve.js';
91 unmodified lines
added:lib/max-listener.js+13 added
1import {addAbortListener} from 'node:events';23export const incrementMaxListeners = (eventEmitter, maxListenersIncrement, signal) => {4 const maxListeners = eventEmitter.getMaxListeners();5 if (maxListeners === 0 || maxListeners === Number.POSITIVE_INFINITY) {6 return;7 }89 eventEmitter.setMaxListeners(maxListeners + maxListenersIncrement);10 addAbortListener(signal, () => {11 eventEmitter.setMaxListeners(eventEmitter.getMaxListeners() - maxListenersIncrement);12 });13};
modified:lib/sync.js+8 added-5 removed
1import {spawnSync} from 'node:child_process';2import {handleCommand, handleOptions} from './arguments/options.js';2import {handleCommand} from './arguments/command.js';3import {handleOptions} from './arguments/options.js';4import {makeError, makeEarlyError, makeSuccessResult} from './return/error.js';4import {stripNewline, handleResult} from './return/output.js';5import {stripNewline} from './return/strip-newline.js';6import {handleResult} from './return/reject.js';7import {handleInputSync} from './stdio/sync.js';8import {addInputOptionsSync} from './stdio/input-sync.js';7import {transformOutputSync, getAllSync} from './stdio/output-sync.js';9import {transformOutputSync} from './stdio/output-sync.js';10import {getAllSync} from './stdio/all-sync.js';11import {logEarlyResult} from './verbose/complete.js';9import {getSyncExitResult} from './exit/code.js';12import {getExitResultSync} from './stream/exit-sync.js';13import {getMaxBufferSync} from './stream/max-buffer.js';1415export const execaCoreSync = (rawFile, rawArgs, rawOptions) => {16 const {file, args, command, escapedCommand, startTime, verboseInfo, options, fileDescriptors} = handleSyncArguments(rawFile, rawArgs, rawOptions);
41 unmodified lines
58 if (syncResult.failed) {59 return syncResult;60 }6159 const {resultError, exitCode, signal, timedOut, isMaxBuffer} = getSyncExitResult(syncResult, options);62 const {resultError, exitCode, signal, timedOut, isMaxBuffer} = getExitResultSync(syncResult, options);63 const {output, error = resultError} = transformOutputSync({fileDescriptors, syncResult, options, isMaxBuffer, verboseInfo});64 const stdio = output.map((stdioOutput, fdNumber) => stripNewline(stdioOutput, options, fdNumber));65 const all = stripNewline(getAllSync(output, options), options, 'all');66 return getSyncResult({error, exitCode, signal, timedOut, isMaxBuffer, stdio, all, options, command, escapedCommand, startTime});
31 unmodified lines
modified:lib/utils.js-16 removed
1import {ChildProcess} from 'node:child_process';2import {addAbortListener} from 'node:events';1import process from 'node:process';23export const isStandardStream = stream => STANDARD_STREAMS.includes(stream);4export const STANDARD_STREAMS = [process.stdin, process.stdout, process.stderr];5export const STANDARD_STREAMS_ALIASES = ['stdin', 'stdout', 'stderr'];6export const getStreamName = fdNumber => STANDARD_STREAMS_ALIASES[fdNumber] ?? `stdio[${fdNumber}]`;910export const incrementMaxListeners = (eventEmitter, maxListenersIncrement, signal) => {11 const maxListeners = eventEmitter.getMaxListeners();12 if (maxListeners === 0 || maxListeners === Number.POSITIVE_INFINITY) {13 return;14 }1516 eventEmitter.setMaxListeners(maxListeners + maxListenersIncrement);17 addAbortListener(signal, () => {18 eventEmitter.setMaxListeners(eventEmitter.getMaxListeners() - maxListenersIncrement);19 });20};2122export const isSubprocess = value => value instanceof ChildProcess;
added:test/arguments/create-bind.js+104 added
1import {join} from 'node:path';2import test from 'ava';3import {execa, execaSync, execaNode, $} from '../../index.js';4import {foobarString, foobarUppercase} from '../helpers/input.js';5import {uppercaseGenerator} from '../helpers/generator.js';6import {setFixtureDir, FIXTURES_DIR} from '../helpers/fixtures-dir.js';78setFixtureDir();910const NOOP_PATH = join(FIXTURES_DIR, 'noop.js');11const PRINT_ENV_PATH = join(FIXTURES_DIR, 'environment.js');1213const testBindOptions = async (t, execaMethod) => {14 const {stdout} = await execaMethod({stripFinalNewline: false})(NOOP_PATH, [foobarString]);15 t.is(stdout, `${foobarString}\n`);16};1718test('execa() can bind options', testBindOptions, execa);19test('execaNode() can bind options', testBindOptions, execaNode);20test('$ can bind options', testBindOptions, $);2122const testBindOptionsSync = (t, execaMethod) => {23 const {stdout} = execaMethod({stripFinalNewline: false})(NOOP_PATH, [foobarString]);24 t.is(stdout, `${foobarString}\n`);25};2627test('execaSync() can bind options', testBindOptionsSync, execaSync);28test('$.sync can bind options', testBindOptionsSync, $.sync);2930const testBindPriority = async (t, execaMethod) => {31 const {stdout} = await execaMethod({stripFinalNewline: false})(NOOP_PATH, [foobarString], {stripFinalNewline: true});32 t.is(stdout, foobarString);33};3435test('execa() bound options have lower priority', testBindPriority, execa);36test('execaSync() bound options have lower priority', testBindPriority, execaSync);37test('execaNode() bound options have lower priority', testBindPriority, execaNode);38test('$ bound options have lower priority', testBindPriority, $);39test('$.sync bound options have lower priority', testBindPriority, $.sync);4041const testBindUndefined = async (t, execaMethod) => {42 const {stdout} = await execaMethod({stripFinalNewline: false})(NOOP_PATH, [foobarString], {stripFinalNewline: undefined});43 t.is(stdout, foobarString);44};4546test('execa() undefined options use default value', testBindUndefined, execa);47test('execaSync() undefined options use default value', testBindUndefined, execaSync);48test('execaNode() undefined options use default value', testBindUndefined, execaNode);49test('$ undefined options use default value', testBindUndefined, $);50test('$.sync undefined options use default value', testBindUndefined, $.sync);5152const testMergeEnv = async (t, execaMethod) => {53 const {stdout} = await execaMethod({env: {FOO: 'foo'}})(PRINT_ENV_PATH, {env: {BAR: 'bar'}});54 t.is(stdout, 'foo\nbar');55};5657test('execa() bound options are merged', testMergeEnv, execa);58test('execaSync() bound options are merged', testMergeEnv, execaSync);59test('execaNode() bound options are merged', testMergeEnv, execaNode);60test('$ bound options are merged', testMergeEnv, $);61test('$.sync bound options are merged', testMergeEnv, $.sync);6263const testMergeMultiple = async (t, execaMethod) => {64 const {stdout} = await execaMethod({env: {FOO: 'baz'}})({env: {BAR: 'bar'}})(PRINT_ENV_PATH, {env: {FOO: 'foo'}});65 t.is(stdout, 'foo\nbar');66};6768test('execa() bound options are merged multiple times', testMergeMultiple, execa);69test('execaSync() bound options are merged multiple times', testMergeMultiple, execaSync);70test('execaNode() bound options are merged multiple times', testMergeMultiple, execaNode);71test('$ bound options are merged multiple times', testMergeMultiple, $);72test('$.sync bound options are merged multiple times', testMergeMultiple, $.sync);7374const testMergeFdSpecific = async (t, execaMethod) => {75 const {isMaxBuffer, shortMessage} = await t.throwsAsync(execaMethod({maxBuffer: {stdout: 1}})(NOOP_PATH, [foobarString], {maxBuffer: {stderr: 100}}));76 t.true(isMaxBuffer);77 t.true(shortMessage.includes('Command\'s stdout was larger than 1'));78};7980test('execa() bound options merge fd-specific ones', testMergeFdSpecific, execa);81test('execaNode() bound options merge fd-specific ones', testMergeFdSpecific, execaNode);82test('$ bound options merge fd-specific ones', testMergeFdSpecific, $);8384const testMergeEnvUndefined = async (t, execaMethod) => {85 const {stdout} = await execaMethod({env: {FOO: 'foo'}})(PRINT_ENV_PATH, {env: {BAR: undefined}});86 t.is(stdout, 'foo\nundefined');87};8889test('execa() bound options are merged even if undefined', testMergeEnvUndefined, execa);90test('execaSync() bound options are merged even if undefined', testMergeEnvUndefined, execaSync);91test('execaNode() bound options are merged even if undefined', testMergeEnvUndefined, execaNode);92test('$ bound options are merged even if undefined', testMergeEnvUndefined, $);93test('$.sync bound options are merged even if undefined', testMergeEnvUndefined, $.sync);9495const testMergeSpecific = async (t, execaMethod) => {96 const {stdout} = await execaMethod({stdout: {transform: uppercaseGenerator().transform, objectMode: true}})(NOOP_PATH, {stdout: {transform: uppercaseGenerator().transform}});97 t.is(stdout, foobarUppercase);98};99100test('execa() bound options only merge specific ones', testMergeSpecific, execa);101test('execaSync() bound options only merge specific ones', testMergeSpecific, execaSync);102test('execaNode() bound options only merge specific ones', testMergeSpecific, execaNode);103test('$ bound options only merge specific ones', testMergeSpecific, $);104test('$.sync bound options only merge specific ones', testMergeSpecific, $.sync);
added:test/arguments/create-main.js+58 added
1import {join} from 'node:path';2import test from 'ava';3import {execa, execaSync, execaNode, $} from '../../index.js';4import {foobarString, foobarArray} from '../helpers/input.js';5import {setFixtureDir, FIXTURES_DIR} from '../helpers/fixtures-dir.js';67setFixtureDir();89const NOOP_PATH = join(FIXTURES_DIR, 'noop.js');1011const testTemplate = async (t, execaMethod) => {12 const {stdout} = await execaMethod`${NOOP_PATH} ${foobarString}`;13 t.is(stdout, foobarString);14};1516test('execa() can use template strings', testTemplate, execa);17test('execaNode() can use template strings', testTemplate, execaNode);18test('$ can use template strings', testTemplate, $);1920const testTemplateSync = (t, execaMethod) => {21 const {stdout} = execaMethod`${NOOP_PATH} ${foobarString}`;22 t.is(stdout, foobarString);23};2425test('execaSync() can use template strings', testTemplateSync, execaSync);26test('$.sync can use template strings', testTemplateSync, $.sync);2728const testTemplateOptions = async (t, execaMethod) => {29 const {stdout} = await execaMethod({stripFinalNewline: false})`${NOOP_PATH} ${foobarString}`;30 t.is(stdout, `${foobarString}\n`);31};3233test('execa() can use template strings with options', testTemplateOptions, execa);34test('execaNode() can use template strings with options', testTemplateOptions, execaNode);35test('$ can use template strings with options', testTemplateOptions, $);3637const testTemplateOptionsSync = (t, execaMethod) => {38 const {stdout} = execaMethod({stripFinalNewline: false})`${NOOP_PATH} ${foobarString}`;39 t.is(stdout, `${foobarString}\n`);40};4142test('execaSync() can use template strings with options', testTemplateOptionsSync, execaSync);43test('$.sync can use template strings with options', testTemplateOptionsSync, $.sync);4445const testSpacedCommand = async (t, args, execaMethod) => {46 const {stdout} = await execaMethod('command with space.js', args);47 const expectedStdout = args === undefined ? '' : args.join('\n');48 t.is(stdout, expectedStdout);49};5051test('allow commands with spaces and no array arguments', testSpacedCommand, undefined, execa);52test('allow commands with spaces and array arguments', testSpacedCommand, foobarArray, execa);53test('allow commands with spaces and no array arguments, execaSync', testSpacedCommand, undefined, execaSync);54test('allow commands with spaces and array arguments, execaSync', testSpacedCommand, foobarArray, execaSync);55test('allow commands with spaces and no array arguments, $', testSpacedCommand, undefined, $);56test('allow commands with spaces and array arguments, $', testSpacedCommand, foobarArray, $);57test('allow commands with spaces and no array arguments, $.sync', testSpacedCommand, undefined, $.sync);58test('allow commands with spaces and array arguments, $.sync', testSpacedCommand, foobarArray, $.sync);
deleted:test/arguments/create.js-152 removed
1import {join} from 'node:path';2import test from 'ava';3import {execa, execaSync, execaNode, $} from '../../index.js';4import {foobarString, foobarArray, foobarUppercase} from '../helpers/input.js';5import {uppercaseGenerator} from '../helpers/generator.js';6import {setFixtureDir, FIXTURES_DIR} from '../helpers/fixtures-dir.js';78setFixtureDir();9const NOOP_PATH = join(FIXTURES_DIR, 'noop.js');10const PRINT_ENV_PATH = join(FIXTURES_DIR, 'environment.js');1112const testTemplate = async (t, execaMethod) => {13 const {stdout} = await execaMethod`${NOOP_PATH} ${foobarString}`;14 t.is(stdout, foobarString);15};1617test('execa() can use template strings', testTemplate, execa);18test('execaNode() can use template strings', testTemplate, execaNode);19test('$ can use template strings', testTemplate, $);2021const testTemplateSync = (t, execaMethod) => {22 const {stdout} = execaMethod`${NOOP_PATH} ${foobarString}`;23 t.is(stdout, foobarString);24};2526test('execaSync() can use template strings', testTemplateSync, execaSync);27test('$.sync can use template strings', testTemplateSync, $.sync);2829const testTemplateOptions = async (t, execaMethod) => {30 const {stdout} = await execaMethod({stripFinalNewline: false})`${NOOP_PATH} ${foobarString}`;31 t.is(stdout, `${foobarString}\n`);32};3334test('execa() can use template strings with options', testTemplateOptions, execa);35test('execaNode() can use template strings with options', testTemplateOptions, execaNode);36test('$ can use template strings with options', testTemplateOptions, $);3738const testTemplateOptionsSync = (t, execaMethod) => {39 const {stdout} = execaMethod({stripFinalNewline: false})`${NOOP_PATH} ${foobarString}`;40 t.is(stdout, `${foobarString}\n`);41};4243test('execaSync() can use template strings with options', testTemplateOptionsSync, execaSync);44test('$.sync can use template strings with options', testTemplateOptionsSync, $.sync);4546const testBindOptions = async (t, execaMethod) => {47 const {stdout} = await execaMethod({stripFinalNewline: false})(NOOP_PATH, [foobarString]);48 t.is(stdout, `${foobarString}\n`);49};5051test('execa() can bind options', testBindOptions, execa);52test('execaNode() can bind options', testBindOptions, execaNode);53test('$ can bind options', testBindOptions, $);5455const testBindOptionsSync = (t, execaMethod) => {56 const {stdout} = execaMethod({stripFinalNewline: false})(NOOP_PATH, [foobarString]);57 t.is(stdout, `${foobarString}\n`);58};5960test('execaSync() can bind options', testBindOptionsSync, execaSync);61test('$.sync can bind options', testBindOptionsSync, $.sync);6263const testBindPriority = async (t, execaMethod) => {64 const {stdout} = await execaMethod({stripFinalNewline: false})(NOOP_PATH, [foobarString], {stripFinalNewline: true});65 t.is(stdout, foobarString);66};6768test('execa() bound options have lower priority', testBindPriority, execa);69test('execaSync() bound options have lower priority', testBindPriority, execaSync);70test('execaNode() bound options have lower priority', testBindPriority, execaNode);71test('$ bound options have lower priority', testBindPriority, $);72test('$.sync bound options have lower priority', testBindPriority, $.sync);7374const testBindUndefined = async (t, execaMethod) => {75 const {stdout} = await execaMethod({stripFinalNewline: false})(NOOP_PATH, [foobarString], {stripFinalNewline: undefined});76 t.is(stdout, foobarString);77};7879test('execa() undefined options use default value', testBindUndefined, execa);80test('execaSync() undefined options use default value', testBindUndefined, execaSync);81test('execaNode() undefined options use default value', testBindUndefined, execaNode);82test('$ undefined options use default value', testBindUndefined, $);83test('$.sync undefined options use default value', testBindUndefined, $.sync);8485const testMergeEnv = async (t, execaMethod) => {86 const {stdout} = await execaMethod({env: {FOO: 'foo'}})(PRINT_ENV_PATH, {env: {BAR: 'bar'}});87 t.is(stdout, 'foo\nbar');88};8990test('execa() bound options are merged', testMergeEnv, execa);91test('execaSync() bound options are merged', testMergeEnv, execaSync);92test('execaNode() bound options are merged', testMergeEnv, execaNode);93test('$ bound options are merged', testMergeEnv, $);94test('$.sync bound options are merged', testMergeEnv, $.sync);9596const testMergeMultiple = async (t, execaMethod) => {97 const {stdout} = await execaMethod({env: {FOO: 'baz'}})({env: {BAR: 'bar'}})(PRINT_ENV_PATH, {env: {FOO: 'foo'}});98 t.is(stdout, 'foo\nbar');99};100101test('execa() bound options are merged multiple times', testMergeMultiple, execa);102test('execaSync() bound options are merged multiple times', testMergeMultiple, execaSync);103test('execaNode() bound options are merged multiple times', testMergeMultiple, execaNode);104test('$ bound options are merged multiple times', testMergeMultiple, $);105test('$.sync bound options are merged multiple times', testMergeMultiple, $.sync);106107const testMergeFdSpecific = async (t, execaMethod) => {108 const {isMaxBuffer, shortMessage} = await t.throwsAsync(execaMethod({maxBuffer: {stdout: 1}})(NOOP_PATH, [foobarString], {maxBuffer: {stderr: 100}}));109 t.true(isMaxBuffer);110 t.true(shortMessage.includes('Command\'s stdout was larger than 1'));111};112113test('execa() bound options merge fd-specific ones', testMergeFdSpecific, execa);114test('execaNode() bound options merge fd-specific ones', testMergeFdSpecific, execaNode);115test('$ bound options merge fd-specific ones', testMergeFdSpecific, $);116117const testMergeEnvUndefined = async (t, execaMethod) => {118 const {stdout} = await execaMethod({env: {FOO: 'foo'}})(PRINT_ENV_PATH, {env: {BAR: undefined}});119 t.is(stdout, 'foo\nundefined');120};121122test('execa() bound options are merged even if undefined', testMergeEnvUndefined, execa);123test('execaSync() bound options are merged even if undefined', testMergeEnvUndefined, execaSync);124test('execaNode() bound options are merged even if undefined', testMergeEnvUndefined, execaNode);125test('$ bound options are merged even if undefined', testMergeEnvUndefined, $);126test('$.sync bound options are merged even if undefined', testMergeEnvUndefined, $.sync);127128const testMergeSpecific = async (t, execaMethod) => {129 const {stdout} = await execaMethod({stdout: {transform: uppercaseGenerator().transform, objectMode: true}})(NOOP_PATH, {stdout: {transform: uppercaseGenerator().transform}});130 t.is(stdout, foobarUppercase);131};132133test('execa() bound options only merge specific ones', testMergeSpecific, execa);134test('execaSync() bound options only merge specific ones', testMergeSpecific, execaSync);135test('execaNode() bound options only merge specific ones', testMergeSpecific, execaNode);136test('$ bound options only merge specific ones', testMergeSpecific, $);137test('$.sync bound options only merge specific ones', testMergeSpecific, $.sync);138139const testSpacedCommand = async (t, args, execaMethod) => {140 const {stdout} = await execaMethod('command with space.js', args);141 const expectedStdout = args === undefined ? '' : args.join('\n');142 t.is(stdout, expectedStdout);143};144145test('allow commands with spaces and no array arguments', testSpacedCommand, undefined, execa);146test('allow commands with spaces and array arguments', testSpacedCommand, foobarArray, execa);147test('allow commands with spaces and no array arguments, execaSync', testSpacedCommand, undefined, execaSync);148test('allow commands with spaces and array arguments, execaSync', testSpacedCommand, foobarArray, execaSync);149test('allow commands with spaces and no array arguments, $', testSpacedCommand, undefined, $);150test('allow commands with spaces and array arguments, $', testSpacedCommand, foobarArray, $);151test('allow commands with spaces and no array arguments, $.sync', testSpacedCommand, undefined, $.sync);152test('allow commands with spaces and array arguments, $.sync', testSpacedCommand, foobarArray, $.sync);
added:test/arguments/env.js+32 added
1import process from 'node:process';2import test from 'ava';3import {execa} from '../../index.js';4import {setFixtureDir, PATH_KEY} from '../helpers/fixtures-dir.js';56setFixtureDir();7process.env.FOO = 'foo';89const isWindows = process.platform === 'win32';1011test('use environment variables by default', async t => {12 const {stdout} = await execa('environment.js');13 t.deepEqual(stdout.split('\n'), ['foo', 'undefined']);14});1516test('extend environment variables by default', async t => {17 const {stdout} = await execa('environment.js', [], {env: {BAR: 'bar', [PATH_KEY]: process.env[PATH_KEY]}});18 t.deepEqual(stdout.split('\n'), ['foo', 'bar']);19});2021test('do not extend environment with `extendEnv: false`', async t => {22 const {stdout} = await execa('environment.js', [], {env: {BAR: 'bar', [PATH_KEY]: process.env[PATH_KEY]}, extendEnv: false});23 t.deepEqual(stdout.split('\n'), ['undefined', 'bar']);24});2526test('use extend environment with `extendEnv: true` and `shell: true`', async t => {27 process.env.TEST = 'test';28 const command = isWindows ? 'echo %TEST%' : 'echo $TEST';29 const {stdout} = await execa(command, {shell: true, env: {}, extendEnv: true});30 t.is(stdout, 'test');31 delete process.env.TEST;32});
added:test/arguments/local.js+71 added
1import {delimiter} from 'node:path';2import process from 'node:process';3import {pathToFileURL} from 'node:url';4import test from 'ava';5import {execa, $} from '../../index.js';6import {setFixtureDir, PATH_KEY} from '../helpers/fixtures-dir.js';78setFixtureDir();9process.env.FOO = 'foo';1011const isWindows = process.platform === 'win32';12const ENOENT_REGEXP = isWindows ? /failed with exit code 1/ : /spawn.* ENOENT/;1314const getPathWithoutLocalDir = () => {15 const newPath = process.env[PATH_KEY].split(delimiter).filter(pathDir => !BIN_DIR_REGEXP.test(pathDir)).join(delimiter);16 return {[PATH_KEY]: newPath};17};1819const BIN_DIR_REGEXP = /node_modules[\\/]\.bin/;2021const pathWitoutLocalDir = getPathWithoutLocalDir();2223test('preferLocal: true', async t => {24 await t.notThrowsAsync(execa('ava', ['--version'], {preferLocal: true, env: pathWitoutLocalDir}));25});2627test('preferLocal: false', async t => {28 await t.throwsAsync(execa('ava', ['--version'], {preferLocal: false, env: pathWitoutLocalDir}), {message: ENOENT_REGEXP});29});3031test('preferLocal: undefined', async t => {32 await t.throwsAsync(execa('ava', ['--version'], {env: pathWitoutLocalDir}), {message: ENOENT_REGEXP});33});3435test('preferLocal: undefined with $', async t => {36 await t.notThrowsAsync($('ava', ['--version'], {env: pathWitoutLocalDir}));37});3839test('preferLocal: undefined with $.sync', t => {40 t.notThrows(() => $.sync('ava', ['--version'], {env: pathWitoutLocalDir}));41});4243test('preferLocal: undefined with execa.pipe`...`', async t => {44 await t.throwsAsync(() => execa('node', ['--version']).pipe({env: pathWitoutLocalDir})`ava --version`);45});4647test('preferLocal: undefined with $.pipe`...`', async t => {48 await t.notThrows(() => $('node', ['--version']).pipe({env: pathWitoutLocalDir})`ava --version`);49});5051test('preferLocal: undefined with execa.pipe()', async t => {52 await t.throwsAsync(() => execa('node', ['--version']).pipe('ava', ['--version'], {env: pathWitoutLocalDir}));53});5455test('preferLocal: undefined with $.pipe()', async t => {56 await t.notThrows(() => $('node', ['--version']).pipe('ava', ['--version'], {env: pathWitoutLocalDir}));57});5859test('localDir option', async t => {60 const command = isWindows ? 'echo %PATH%' : 'echo $PATH';61 const {stdout} = await execa(command, {shell: true, preferLocal: true, localDir: '/test'});62 const envPaths = stdout.split(delimiter);63 t.true(envPaths.some(envPath => envPath.endsWith('.bin')));64});6566test('localDir option can be a URL', async t => {67 const command = isWindows ? 'echo %PATH%' : 'echo $PATH';68 const {stdout} = await execa(command, {shell: true, preferLocal: true, localDir: pathToFileURL('/test')});69 const envPaths = stdout.split(delimiter);70 t.true(envPaths.some(envPath => envPath.endsWith('.bin')));71});
added:test/arguments/normalize-args.js+47 added
1import test from 'ava';2import {execa, execaSync, execaCommand, execaCommandSync, execaNode, $} from '../../index.js';3import {setFixtureDir} from '../helpers/fixtures-dir.js';45setFixtureDir();67const testInvalidArgs = async (t, execaMethod) => {8 t.throws(() => {9 execaMethod('echo', true);10 }, {message: /Second argument must be either/});11};1213test('execa()\'s second argument must be valid', testInvalidArgs, execa);14test('execaSync()\'s second argument must be valid', testInvalidArgs, execaSync);15test('execaCommand()\'s second argument must be valid', testInvalidArgs, execaCommand);16test('execaCommandSync()\'s second argument must be valid', testInvalidArgs, execaCommandSync);17test('execaNode()\'s second argument must be valid', testInvalidArgs, execaNode);18test('$\'s second argument must be valid', testInvalidArgs, $);19test('$.sync\'s second argument must be valid', testInvalidArgs, $.sync);2021const testInvalidArgsItems = async (t, execaMethod) => {22 t.throws(() => {23 execaMethod('echo', [{}]);24 }, {message: 'Second argument must be an array of strings: [object Object]'});25};2627test('execa()\'s second argument must not be objects', testInvalidArgsItems, execa);28test('execaSync()\'s second argument must not be objects', testInvalidArgsItems, execaSync);29test('execaCommand()\'s second argument must not be objects', testInvalidArgsItems, execaCommand);30test('execaCommandSync()\'s second argument must not be objects', testInvalidArgsItems, execaCommandSync);31test('execaNode()\'s second argument must not be objects', testInvalidArgsItems, execaNode);32test('$\'s second argument must not be objects', testInvalidArgsItems, $);33test('$.sync\'s second argument must not be objects', testInvalidArgsItems, $.sync);3435const testNullByteArg = async (t, execaMethod) => {36 t.throws(() => {37 execaMethod('echo', ['a\0b']);38 }, {message: /null bytes/});39};4041test('execa()\'s second argument must not include \\0', testNullByteArg, execa);42test('execaSync()\'s second argument must not include \\0', testNullByteArg, execaSync);43test('execaCommand()\'s second argument must not include \\0', testNullByteArg, execaCommand);44test('execaCommandSync()\'s second argument must not include \\0', testNullByteArg, execaCommandSync);45test('execaNode()\'s second argument must not include \\0', testNullByteArg, execaNode);46test('$\'s second argument must not include \\0', testNullByteArg, $);47test('$.sync\'s second argument must not include \\0', testNullByteArg, $.sync);
added:test/arguments/normalize-command.js+80 added
1import {join, basename} from 'node:path';2import {fileURLToPath} from 'node:url';3import test from 'ava';4import {execa, execaSync, execaCommand, execaCommandSync, execaNode, $} from '../../index.js';5import {setFixtureDir, FIXTURES_DIR_URL} from '../helpers/fixtures-dir.js';6import {foobarString} from '../helpers/input.js';78setFixtureDir();910const testFileUrl = async (t, execaMethod) => {11 const command = new URL('noop.js', FIXTURES_DIR_URL);12 const {stdout} = await execaMethod(command);13 t.is(stdout, foobarString);14};1516test('execa()\'s command argument can be a file URL', testFileUrl, execa);17test('execaSync()\'s command argument can be a file URL', testFileUrl, execaSync);18test('execaCommand()\'s command argument can be a file URL', testFileUrl, execaCommand);19test('execaCommandSync()\'s command argument can be a file URL', testFileUrl, execaCommandSync);20test('execaNode()\'s command argument can be a file URL', testFileUrl, execaNode);21test('$\'s command argument can be a file URL', testFileUrl, $);22test('$.sync\'s command argument can be a file URL', testFileUrl, $.sync);2324const testInvalidFileUrl = async (t, execaMethod) => {25 const invalidUrl = new URL('https://invalid.com');26 t.throws(() => {27 execaMethod(invalidUrl);28 }, {code: 'ERR_INVALID_URL_SCHEME'});29};3031test('execa()\'s command argument cannot be a non-file URL', testInvalidFileUrl, execa);32test('execaSync()\'s command argument cannot be a non-file URL', testInvalidFileUrl, execaSync);33test('execaCommand()\'s command argument cannot be a non-file URL', testInvalidFileUrl, execaCommand);34test('execaCommandSync()\'s command argument cannot be a non-file URL', testInvalidFileUrl, execaCommandSync);35test('execaNode()\'s command argument cannot be a non-file URL', testInvalidFileUrl, execaNode);36test('$\'s command argument cannot be a non-file URL', testInvalidFileUrl, $);37test('$.sync\'s command argument cannot be a non-file URL', testInvalidFileUrl, $.sync);3839const testInvalidCommand = async (t, arg, execaMethod) => {40 t.throws(() => {41 execaMethod(arg);42 }, {message: /First argument must be a string or a file URL/});43};4445test('execa()\'s first argument must be defined', testInvalidCommand, undefined, execa);46test('execaSync()\'s first argument must be defined', testInvalidCommand, undefined, execaSync);47test('execaCommand()\'s first argument must be defined', testInvalidCommand, undefined, execaCommand);48test('execaCommandSync()\'s first argument must be defined', testInvalidCommand, undefined, execaCommandSync);49test('execaNode()\'s first argument must be defined', testInvalidCommand, undefined, execaNode);50test('$\'s first argument must be defined', testInvalidCommand, undefined, $);51test('$.sync\'s first argument must be defined', testInvalidCommand, undefined, $.sync);52test('execa()\'s first argument must be valid', testInvalidCommand, true, execa);53test('execaSync()\'s first argument must be valid', testInvalidCommand, true, execaSync);54test('execaCommand()\'s first argument must be valid', testInvalidCommand, true, execaCommand);55test('execaCommandSync()\'s first argument must be valid', testInvalidCommand, true, execaCommandSync);56test('execaNode()\'s first argument must be valid', testInvalidCommand, true, execaNode);57test('$\'s first argument must be valid', testInvalidCommand, true, $);58test('$.sync\'s first argument must be valid', testInvalidCommand, true, $.sync);59test('execa()\'s command argument must be a string or file URL', testInvalidCommand, ['command', 'arg'], execa);60test('execaSync()\'s command argument must be a string or file URL', testInvalidCommand, ['command', 'arg'], execaSync);61test('execaCommand()\'s command argument must be a string or file URL', testInvalidCommand, ['command', 'arg'], execaCommand);62test('execaCommandSync()\'s command argument must be a string or file URL', testInvalidCommand, ['command', 'arg'], execaCommandSync);63test('execaNode()\'s command argument must be a string or file URL', testInvalidCommand, ['command', 'arg'], execaNode);64test('$\'s command argument must be a string or file URL', testInvalidCommand, ['command', 'arg'], $);65test('$.sync\'s command argument must be a string or file URL', testInvalidCommand, ['command', 'arg'], $.sync);6667const testRelativePath = async (t, execaMethod) => {68 const rootDir = basename(fileURLToPath(new URL('../..', import.meta.url)));69 const pathViaParentDir = join('..', rootDir, 'test', 'fixtures', 'noop.js');70 const {stdout} = await execaMethod(pathViaParentDir);71 t.is(stdout, foobarString);72};7374test('execa() use relative path with \'..\' chars', testRelativePath, execa);75test('execaSync() use relative path with \'..\' chars', testRelativePath, execaSync);76test('execaCommand() use relative path with \'..\' chars', testRelativePath, execaCommand);77test('execaCommandSync() use relative path with \'..\' chars', testRelativePath, execaCommandSync);78test('execaNode() use relative path with \'..\' chars', testRelativePath, execaNode);79test('$ use relative path with \'..\' chars', testRelativePath, $);80test('$.sync use relative path with \'..\' chars', testRelativePath, $.sync);
added:test/arguments/normalize-options.js+68 added
1import {join} from 'node:path';2import test from 'ava';3import {execa, execaSync, execaCommand, execaCommandSync, execaNode, $} from '../../index.js';4import {setFixtureDir, FIXTURES_DIR} from '../helpers/fixtures-dir.js';56setFixtureDir();78const NOOP_PATH = join(FIXTURES_DIR, 'noop.js');910const testSerializeArg = async (t, arg, execaMethod) => {11 const {stdout} = await execaMethod(NOOP_PATH, [arg]);12 t.is(stdout, String(arg));13};1415test('execa()\'s arguments can be numbers', testSerializeArg, 1, execa);16test('execa()\'s arguments can be booleans', testSerializeArg, true, execa);17test('execa()\'s arguments can be NaN', testSerializeArg, Number.NaN, execa);18test('execa()\'s arguments can be Infinity', testSerializeArg, Number.POSITIVE_INFINITY, execa);19test('execa()\'s arguments can be null', testSerializeArg, null, execa);20test('execa()\'s arguments can be undefined', testSerializeArg, undefined, execa);21test('execa()\'s arguments can be bigints', testSerializeArg, 1n, execa);22test('execa()\'s arguments can be symbols', testSerializeArg, Symbol('test'), execa);23test('execaSync()\'s arguments can be numbers', testSerializeArg, 1, execaSync);24test('execaSync()\'s arguments can be booleans', testSerializeArg, true, execaSync);25test('execaSync()\'s arguments can be NaN', testSerializeArg, Number.NaN, execaSync);26test('execaSync()\'s arguments can be Infinity', testSerializeArg, Number.POSITIVE_INFINITY, execaSync);27test('execaSync()\'s arguments can be null', testSerializeArg, null, execaSync);28test('execaSync()\'s arguments can be undefined', testSerializeArg, undefined, execaSync);29test('execaSync()\'s arguments can be bigints', testSerializeArg, 1n, execaSync);30test('execaSync()\'s arguments can be symbols', testSerializeArg, Symbol('test'), execaSync);31test('execaNode()\'s arguments can be numbers', testSerializeArg, 1, execaNode);32test('execaNode()\'s arguments can be booleans', testSerializeArg, true, execaNode);33test('execaNode()\'s arguments can be NaN', testSerializeArg, Number.NaN, execaNode);34test('execaNode()\'s arguments can be Infinity', testSerializeArg, Number.POSITIVE_INFINITY, execaNode);35test('execaNode()\'s arguments can be null', testSerializeArg, null, execaNode);36test('execaNode()\'s arguments can be undefined', testSerializeArg, undefined, execaNode);37test('execaNode()\'s arguments can be bigints', testSerializeArg, 1n, execaNode);38test('execaNode()\'s arguments can be symbols', testSerializeArg, Symbol('test'), execaNode);39test('$\'s arguments can be numbers', testSerializeArg, 1, $);40test('$\'s arguments can be booleans', testSerializeArg, true, $);41test('$\'s arguments can be NaN', testSerializeArg, Number.NaN, $);42test('$\'s arguments can be Infinity', testSerializeArg, Number.POSITIVE_INFINITY, $);43test('$\'s arguments can be null', testSerializeArg, null, $);44test('$\'s arguments can be undefined', testSerializeArg, undefined, $);45test('$\'s arguments can be bigints', testSerializeArg, 1n, $);46test('$\'s arguments can be symbols', testSerializeArg, Symbol('test'), $);47test('$.sync\'s arguments can be numbers', testSerializeArg, 1, $.sync);48test('$.sync\'s arguments can be booleans', testSerializeArg, true, $.sync);49test('$.sync\'s arguments can be NaN', testSerializeArg, Number.NaN, $.sync);50test('$.sync\'s arguments can be Infinity', testSerializeArg, Number.POSITIVE_INFINITY, $.sync);51test('$.sync\'s arguments can be null', testSerializeArg, null, $.sync);52test('$.sync\'s arguments can be undefined', testSerializeArg, undefined, $.sync);53test('$.sync\'s arguments can be bigints', testSerializeArg, 1n, $.sync);54test('$.sync\'s arguments can be symbols', testSerializeArg, Symbol('test'), $.sync);5556const testInvalidOptions = async (t, execaMethod) => {57 t.throws(() => {58 execaMethod('echo', [], new Map());59 }, {message: /Last argument must be an options object/});60};6162test('execa()\'s third argument must be a plain object', testInvalidOptions, execa);63test('execaSync()\'s third argument must be a plain object', testInvalidOptions, execaSync);64test('execaCommand()\'s third argument must be a plain object', testInvalidOptions, execaCommand);65test('execaCommandSync()\'s third argument must be a plain object', testInvalidOptions, execaCommandSync);66test('execaNode()\'s third argument must be a plain object', testInvalidOptions, execaNode);67test('$\'s third argument must be a plain object', testInvalidOptions, $);68test('$.sync\'s third argument must be a plain object', testInvalidOptions, $.sync);
deleted:test/arguments/normalize.js-183 removed
1import {join, basename} from 'node:path';2import {fileURLToPath} from 'node:url';3import test from 'ava';4import {execa, execaSync, execaCommand, execaCommandSync, execaNode, $} from '../../index.js';5import {setFixtureDir, FIXTURES_DIR, FIXTURES_DIR_URL} from '../helpers/fixtures-dir.js';6import {foobarString} from '../helpers/input.js';78setFixtureDir();9const NOOP_PATH = join(FIXTURES_DIR, 'noop.js');1011const testFileUrl = async (t, execaMethod) => {12 const command = new URL('noop.js', FIXTURES_DIR_URL);13 const {stdout} = await execaMethod(command);14 t.is(stdout, foobarString);15};1617test('execa()\'s command argument can be a file URL', testFileUrl, execa);18test('execaSync()\'s command argument can be a file URL', testFileUrl, execaSync);19test('execaCommand()\'s command argument can be a file URL', testFileUrl, execaCommand);20test('execaCommandSync()\'s command argument can be a file URL', testFileUrl, execaCommandSync);21test('execaNode()\'s command argument can be a file URL', testFileUrl, execaNode);22test('$\'s command argument can be a file URL', testFileUrl, $);23test('$.sync\'s command argument can be a file URL', testFileUrl, $.sync);2425const testInvalidFileUrl = async (t, execaMethod) => {26 const invalidUrl = new URL('https://invalid.com');27 t.throws(() => {28 execaMethod(invalidUrl);29 }, {code: 'ERR_INVALID_URL_SCHEME'});30};3132test('execa()\'s command argument cannot be a non-file URL', testInvalidFileUrl, execa);33test('execaSync()\'s command argument cannot be a non-file URL', testInvalidFileUrl, execaSync);34test('execaCommand()\'s command argument cannot be a non-file URL', testInvalidFileUrl, execaCommand);35test('execaCommandSync()\'s command argument cannot be a non-file URL', testInvalidFileUrl, execaCommandSync);36test('execaNode()\'s command argument cannot be a non-file URL', testInvalidFileUrl, execaNode);37test('$\'s command argument cannot be a non-file URL', testInvalidFileUrl, $);38test('$.sync\'s command argument cannot be a non-file URL', testInvalidFileUrl, $.sync);3940const testInvalidCommand = async (t, arg, execaMethod) => {41 t.throws(() => {42 execaMethod(arg);43 }, {message: /First argument must be a string or a file URL/});44};4546test('execa()\'s first argument must be defined', testInvalidCommand, undefined, execa);47test('execaSync()\'s first argument must be defined', testInvalidCommand, undefined, execaSync);48test('execaCommand()\'s first argument must be defined', testInvalidCommand, undefined, execaCommand);49test('execaCommandSync()\'s first argument must be defined', testInvalidCommand, undefined, execaCommandSync);50test('execaNode()\'s first argument must be defined', testInvalidCommand, undefined, execaNode);51test('$\'s first argument must be defined', testInvalidCommand, undefined, $);52test('$.sync\'s first argument must be defined', testInvalidCommand, undefined, $.sync);53test('execa()\'s first argument must be valid', testInvalidCommand, true, execa);54test('execaSync()\'s first argument must be valid', testInvalidCommand, true, execaSync);55test('execaCommand()\'s first argument must be valid', testInvalidCommand, true, execaCommand);56test('execaCommandSync()\'s first argument must be valid', testInvalidCommand, true, execaCommandSync);57test('execaNode()\'s first argument must be valid', testInvalidCommand, true, execaNode);58test('$\'s first argument must be valid', testInvalidCommand, true, $);59test('$.sync\'s first argument must be valid', testInvalidCommand, true, $.sync);60test('execa()\'s command argument must be a string or file URL', testInvalidCommand, ['command', 'arg'], execa);61test('execaSync()\'s command argument must be a string or file URL', testInvalidCommand, ['command', 'arg'], execaSync);62test('execaCommand()\'s command argument must be a string or file URL', testInvalidCommand, ['command', 'arg'], execaCommand);63test('execaCommandSync()\'s command argument must be a string or file URL', testInvalidCommand, ['command', 'arg'], execaCommandSync);64test('execaNode()\'s command argument must be a string or file URL', testInvalidCommand, ['command', 'arg'], execaNode);65test('$\'s command argument must be a string or file URL', testInvalidCommand, ['command', 'arg'], $);66test('$.sync\'s command argument must be a string or file URL', testInvalidCommand, ['command', 'arg'], $.sync);6768const testInvalidArgs = async (t, execaMethod) => {69 t.throws(() => {70 execaMethod('echo', true);71 }, {message: /Second argument must be either/});72};7374test('execa()\'s second argument must be valid', testInvalidArgs, execa);75test('execaSync()\'s second argument must be valid', testInvalidArgs, execaSync);76test('execaCommand()\'s second argument must be valid', testInvalidArgs, execaCommand);77test('execaCommandSync()\'s second argument must be valid', testInvalidArgs, execaCommandSync);78test('execaNode()\'s second argument must be valid', testInvalidArgs, execaNode);79test('$\'s second argument must be valid', testInvalidArgs, $);80test('$.sync\'s second argument must be valid', testInvalidArgs, $.sync);8182const testInvalidArgsItems = async (t, execaMethod) => {83 t.throws(() => {84 execaMethod('echo', [{}]);85 }, {message: 'Second argument must be an array of strings: [object Object]'});86};8788test('execa()\'s second argument must not be objects', testInvalidArgsItems, execa);89test('execaSync()\'s second argument must not be objects', testInvalidArgsItems, execaSync);90test('execaCommand()\'s second argument must not be objects', testInvalidArgsItems, execaCommand);91test('execaCommandSync()\'s second argument must not be objects', testInvalidArgsItems, execaCommandSync);92test('execaNode()\'s second argument must not be objects', testInvalidArgsItems, execaNode);93test('$\'s second argument must not be objects', testInvalidArgsItems, $);94test('$.sync\'s second argument must not be objects', testInvalidArgsItems, $.sync);9596const testNullByteArg = async (t, execaMethod) => {97 t.throws(() => {98 execaMethod('echo', ['a\0b']);99 }, {message: /null bytes/});100};101102test('execa()\'s second argument must not include \\0', testNullByteArg, execa);103test('execaSync()\'s second argument must not include \\0', testNullByteArg, execaSync);104test('execaCommand()\'s second argument must not include \\0', testNullByteArg, execaCommand);105test('execaCommandSync()\'s second argument must not include \\0', testNullByteArg, execaCommandSync);106test('execaNode()\'s second argument must not include \\0', testNullByteArg, execaNode);107test('$\'s second argument must not include \\0', testNullByteArg, $);108test('$.sync\'s second argument must not include \\0', testNullByteArg, $.sync);109110const testSerializeArg = async (t, arg, execaMethod) => {111 const {stdout} = await execaMethod(NOOP_PATH, [arg]);112 t.is(stdout, String(arg));113};114115test('execa()\'s arguments can be numbers', testSerializeArg, 1, execa);116test('execa()\'s arguments can be booleans', testSerializeArg, true, execa);117test('execa()\'s arguments can be NaN', testSerializeArg, Number.NaN, execa);118test('execa()\'s arguments can be Infinity', testSerializeArg, Number.POSITIVE_INFINITY, execa);119test('execa()\'s arguments can be null', testSerializeArg, null, execa);120test('execa()\'s arguments can be undefined', testSerializeArg, undefined, execa);121test('execa()\'s arguments can be bigints', testSerializeArg, 1n, execa);122test('execa()\'s arguments can be symbols', testSerializeArg, Symbol('test'), execa);123test('execaSync()\'s arguments can be numbers', testSerializeArg, 1, execaSync);124test('execaSync()\'s arguments can be booleans', testSerializeArg, true, execaSync);125test('execaSync()\'s arguments can be NaN', testSerializeArg, Number.NaN, execaSync);126test('execaSync()\'s arguments can be Infinity', testSerializeArg, Number.POSITIVE_INFINITY, execaSync);127test('execaSync()\'s arguments can be null', testSerializeArg, null, execaSync);128test('execaSync()\'s arguments can be undefined', testSerializeArg, undefined, execaSync);129test('execaSync()\'s arguments can be bigints', testSerializeArg, 1n, execaSync);130test('execaSync()\'s arguments can be symbols', testSerializeArg, Symbol('test'), execaSync);131test('execaNode()\'s arguments can be numbers', testSerializeArg, 1, execaNode);132test('execaNode()\'s arguments can be booleans', testSerializeArg, true, execaNode);133test('execaNode()\'s arguments can be NaN', testSerializeArg, Number.NaN, execaNode);134test('execaNode()\'s arguments can be Infinity', testSerializeArg, Number.POSITIVE_INFINITY, execaNode);135test('execaNode()\'s arguments can be null', testSerializeArg, null, execaNode);136test('execaNode()\'s arguments can be undefined', testSerializeArg, undefined, execaNode);137test('execaNode()\'s arguments can be bigints', testSerializeArg, 1n, execaNode);138test('execaNode()\'s arguments can be symbols', testSerializeArg, Symbol('test'), execaNode);139test('$\'s arguments can be numbers', testSerializeArg, 1, $);140test('$\'s arguments can be booleans', testSerializeArg, true, $);141test('$\'s arguments can be NaN', testSerializeArg, Number.NaN, $);142test('$\'s arguments can be Infinity', testSerializeArg, Number.POSITIVE_INFINITY, $);143test('$\'s arguments can be null', testSerializeArg, null, $);144test('$\'s arguments can be undefined', testSerializeArg, undefined, $);145test('$\'s arguments can be bigints', testSerializeArg, 1n, $);146test('$\'s arguments can be symbols', testSerializeArg, Symbol('test'), $);147test('$.sync\'s arguments can be numbers', testSerializeArg, 1, $.sync);148test('$.sync\'s arguments can be booleans', testSerializeArg, true, $.sync);149test('$.sync\'s arguments can be NaN', testSerializeArg, Number.NaN, $.sync);150test('$.sync\'s arguments can be Infinity', testSerializeArg, Number.POSITIVE_INFINITY, $.sync);151test('$.sync\'s arguments can be null', testSerializeArg, null, $.sync);152test('$.sync\'s arguments can be undefined', testSerializeArg, undefined, $.sync);153test('$.sync\'s arguments can be bigints', testSerializeArg, 1n, $.sync);154test('$.sync\'s arguments can be symbols', testSerializeArg, Symbol('test'), $.sync);155156const testInvalidOptions = async (t, execaMethod) => {157 t.throws(() => {158 execaMethod('echo', [], new Map());159 }, {message: /Last argument must be an options object/});160};161162test('execa()\'s third argument must be a plain object', testInvalidOptions, execa);163test('execaSync()\'s third argument must be a plain object', testInvalidOptions, execaSync);164test('execaCommand()\'s third argument must be a plain object', testInvalidOptions, execaCommand);165test('execaCommandSync()\'s third argument must be a plain object', testInvalidOptions, execaCommandSync);166test('execaNode()\'s third argument must be a plain object', testInvalidOptions, execaNode);167test('$\'s third argument must be a plain object', testInvalidOptions, $);168test('$.sync\'s third argument must be a plain object', testInvalidOptions, $.sync);169170const testRelativePath = async (t, execaMethod) => {171 const rootDir = basename(fileURLToPath(new URL('../..', import.meta.url)));172 const pathViaParentDir = join('..', rootDir, 'test', 'fixtures', 'noop.js');173 const {stdout} = await execaMethod(pathViaParentDir);174 t.is(stdout, foobarString);175};176177test('execa() use relative path with \'..\' chars', testRelativePath, execa);178test('execaSync() use relative path with \'..\' chars', testRelativePath, execaSync);179test('execaCommand() use relative path with \'..\' chars', testRelativePath, execaCommand);180test('execaCommandSync() use relative path with \'..\' chars', testRelativePath, execaCommandSync);181test('execaNode() use relative path with \'..\' chars', testRelativePath, execaNode);182test('$ use relative path with \'..\' chars', testRelativePath, $);183test('$.sync use relative path with \'..\' chars', testRelativePath, $.sync);
deleted:test/arguments/options.js-111 removed
1import {delimiter} from 'node:path';2import process from 'node:process';3import {pathToFileURL} from 'node:url';4import test from 'ava';5import which from 'which';6import {execa, $} from '../../index.js';7import {setFixtureDir, PATH_KEY} from '../helpers/fixtures-dir.js';8import {identity} from '../helpers/stdio.js';910setFixtureDir();11process.env.FOO = 'foo';1213const isWindows = process.platform === 'win32';14const ENOENT_REGEXP = isWindows ? /failed with exit code 1/ : /spawn.* ENOENT/;1516const getPathWithoutLocalDir = () => {17 const newPath = process.env[PATH_KEY].split(delimiter).filter(pathDir => !BIN_DIR_REGEXP.test(pathDir)).join(delimiter);18 return {[PATH_KEY]: newPath};19};2021const BIN_DIR_REGEXP = /node_modules[\\/]\.bin/;2223const pathWitoutLocalDir = getPathWithoutLocalDir();2425test('preferLocal: true', async t => {26 await t.notThrowsAsync(execa('ava', ['--version'], {preferLocal: true, env: pathWitoutLocalDir}));27});2829test('preferLocal: false', async t => {30 await t.throwsAsync(execa('ava', ['--version'], {preferLocal: false, env: pathWitoutLocalDir}), {message: ENOENT_REGEXP});31});3233test('preferLocal: undefined', async t => {34 await t.throwsAsync(execa('ava', ['--version'], {env: pathWitoutLocalDir}), {message: ENOENT_REGEXP});35});3637test('preferLocal: undefined with $', async t => {38 await t.notThrowsAsync($('ava', ['--version'], {env: pathWitoutLocalDir}));39});4041test('preferLocal: undefined with $.sync', t => {42 t.notThrows(() => $.sync('ava', ['--version'], {env: pathWitoutLocalDir}));43});4445test('preferLocal: undefined with execa.pipe`...`', async t => {46 await t.throwsAsync(() => execa('node', ['--version']).pipe({env: pathWitoutLocalDir})`ava --version`);47});4849test('preferLocal: undefined with $.pipe`...`', async t => {50 await t.notThrows(() => $('node', ['--version']).pipe({env: pathWitoutLocalDir})`ava --version`);51});5253test('preferLocal: undefined with execa.pipe()', async t => {54 await t.throwsAsync(() => execa('node', ['--version']).pipe('ava', ['--version'], {env: pathWitoutLocalDir}));55});5657test('preferLocal: undefined with $.pipe()', async t => {58 await t.notThrows(() => $('node', ['--version']).pipe('ava', ['--version'], {env: pathWitoutLocalDir}));59});6061test('localDir option', async t => {62 const command = isWindows ? 'echo %PATH%' : 'echo $PATH';63 const {stdout} = await execa(command, {shell: true, preferLocal: true, localDir: '/test'});64 const envPaths = stdout.split(delimiter);65 t.true(envPaths.some(envPath => envPath.endsWith('.bin')));66});6768test('localDir option can be a URL', async t => {69 const command = isWindows ? 'echo %PATH%' : 'echo $PATH';70 const {stdout} = await execa(command, {shell: true, preferLocal: true, localDir: pathToFileURL('/test')});71 const envPaths = stdout.split(delimiter);72 t.true(envPaths.some(envPath => envPath.endsWith('.bin')));73});7475test('use environment variables by default', async t => {76 const {stdout} = await execa('environment.js');77 t.deepEqual(stdout.split('\n'), ['foo', 'undefined']);78});7980test('extend environment variables by default', async t => {81 const {stdout} = await execa('environment.js', [], {env: {BAR: 'bar', [PATH_KEY]: process.env[PATH_KEY]}});82 t.deepEqual(stdout.split('\n'), ['foo', 'bar']);83});8485test('do not extend environment with `extendEnv: false`', async t => {86 const {stdout} = await execa('environment.js', [], {env: {BAR: 'bar', [PATH_KEY]: process.env[PATH_KEY]}, extendEnv: false});87 t.deepEqual(stdout.split('\n'), ['undefined', 'bar']);88});8990test('use extend environment with `extendEnv: true` and `shell: true`', async t => {91 process.env.TEST = 'test';92 const command = isWindows ? 'echo %TEST%' : 'echo $TEST';93 const {stdout} = await execa(command, {shell: true, env: {}, extendEnv: true});94 t.is(stdout, 'test');95 delete process.env.TEST;96});9798test('can use `options.shell: true`', async t => {99 const {stdout} = await execa('node test/fixtures/noop.js foo', {shell: true});100 t.is(stdout, 'foo');101});102103const testShellPath = async (t, mapPath) => {104 const shellPath = isWindows ? 'cmd.exe' : 'bash';105 const shell = mapPath(await which(shellPath));106 const {stdout} = await execa('node test/fixtures/noop.js foo', {shell});107 t.is(stdout, 'foo');108};109110test('can use `options.shell: string`', testShellPath, identity);111test('can use `options.shell: file URL`', testShellPath, pathToFileURL);
added:test/arguments/shell.js+27 added
1import process from 'node:process';2import {pathToFileURL} from 'node:url';3import test from 'ava';4import which from 'which';5import {execa} from '../../index.js';6import {setFixtureDir} from '../helpers/fixtures-dir.js';7import {identity} from '../helpers/stdio.js';89setFixtureDir();10process.env.FOO = 'foo';1112const isWindows = process.platform === 'win32';1314test('can use `options.shell: true`', async t => {15 const {stdout} = await execa('node test/fixtures/noop.js foo', {shell: true});16 t.is(stdout, 'foo');17});1819const testShellPath = async (t, mapPath) => {20 const shellPath = isWindows ? 'cmd.exe' : 'bash';21 const shell = mapPath(await which(shellPath));22 const {stdout} = await execa('node test/fixtures/noop.js foo', {shell});23 t.is(stdout, 'foo');24};2526test('can use `options.shell: string`', testShellPath, identity);27test('can use `options.shell: file URL`', testShellPath, pathToFileURL);
added:test/arguments/specific.js+38 added
1import test from 'ava';2import {execa, execaSync} from '../../index.js';3import {setFixtureDir} from '../helpers/fixtures-dir.js';4import {foobarString} from '../helpers/input.js';56setFixtureDir();78// eslint-disable-next-line max-params9const testPriorityOrder = async (t, 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);13};1415test('buffer: {stdout, fd1}', testPriorityOrder, {stdout: true, fd1: false}, true, true, execa);16test('buffer: {stdout, all}', testPriorityOrder, {stdout: true, all: false}, true, false, execa);17test('buffer: {fd1, all}', testPriorityOrder, {fd1: true, all: false}, true, false, execa);18test('buffer: {stderr, fd2}', testPriorityOrder, {stderr: true, fd2: false}, true, true, execa);19test('buffer: {stderr, all}', testPriorityOrder, {stderr: true, all: false}, false, true, execa);20test('buffer: {fd2, all}', testPriorityOrder, {fd2: true, all: false}, false, true, execa);21test('buffer: {fd1, stdout}', testPriorityOrder, {fd1: false, stdout: true}, true, true, execa);22test('buffer: {all, stdout}', testPriorityOrder, {all: false, stdout: true}, true, false, execa);23test('buffer: {all, fd1}', testPriorityOrder, {all: false, fd1: true}, true, false, execa);24test('buffer: {fd2, stderr}', testPriorityOrder, {fd2: false, stderr: true}, true, true, execa);25test('buffer: {all, stderr}', testPriorityOrder, {all: false, stderr: true}, false, true, execa);26test('buffer: {all, fd2}', testPriorityOrder, {all: false, fd2: true}, false, true, execa);27test('buffer: {stdout, fd1}, sync', testPriorityOrder, {stdout: true, fd1: false}, true, true, execaSync);28test('buffer: {stdout, all}, sync', testPriorityOrder, {stdout: true, all: false}, true, false, execaSync);29test('buffer: {fd1, all}, sync', testPriorityOrder, {fd1: true, all: false}, true, false, execaSync);30test('buffer: {stderr, fd2}, sync', testPriorityOrder, {stderr: true, fd2: false}, true, true, execaSync);31test('buffer: {stderr, all}, sync', testPriorityOrder, {stderr: true, all: false}, false, true, execaSync);32test('buffer: {fd2, all}, sync', testPriorityOrder, {fd2: true, all: false}, false, true, execaSync);33test('buffer: {fd1, stdout}, sync', testPriorityOrder, {fd1: false, stdout: true}, true, true, execaSync);34test('buffer: {all, stdout}, sync', testPriorityOrder, {all: false, stdout: true}, true, false, execaSync);35test('buffer: {all, fd1}, sync', testPriorityOrder, {all: false, fd1: true}, true, false, execaSync);36test('buffer: {fd2, stderr}, sync', testPriorityOrder, {fd2: false, stderr: true}, true, true, execaSync);37test('buffer: {all, stderr}, sync', testPriorityOrder, {all: false, stderr: true}, false, true, execaSync);38test('buffer: {all, fd2}, sync', testPriorityOrder, {all: false, fd2: true}, false, true, execaSync);
added:test/convert/fd-options.js+725 added
1import {PassThrough} from 'node:stream';2import {spawn} from 'node:child_process';3import process from 'node:process';4import test from 'ava';5import {execa} from '../../index.js';6import {setFixtureDir} from '../helpers/fixtures-dir.js';7import {fullStdio, getStdio} from '../helpers/stdio.js';8import {getEarlyErrorSubprocess} from '../helpers/early-error.js';9import {assertPipeError} from '../helpers/pipe.js';1011setFixtureDir();1213const getMessage = message => Array.isArray(message)14 ? `"${message[0]}: ${message[1]}" option is incompatible`15 : message;1617const testPipeError = async (t, {18 message,19 sourceOptions = {},20 destinationOptions = {},21 getSource = () => execa('empty.js', sourceOptions),22 getDestination = () => execa('empty.js', destinationOptions),23 isScript = false,24 from,25 to,26}) => {27 const source = getSource();28 const pipePromise = isScript ? source.pipe({from, to})`empty.js` : source.pipe(getDestination(), {from, to});29 await assertPipeError(t, pipePromise, getMessage(message));30};3132const testNodeStream = async (t, {33 message,34 sourceOptions = {},35 getSource = () => execa('empty.js', sourceOptions),36 from,37 to,38 writable = to !== undefined,39}) => {40 assertNodeStream({t, message, getSource, from, to, methodName: writable ? 'writable' : 'readable'});41 assertNodeStream({t, message, getSource, from, to, methodName: 'duplex'});42};4344const assertNodeStream = ({t, message, getSource, from, to, methodName}) => {45 const error = t.throws(() => {46 getSource()[methodName]({from, to});47 });48 t.true(error.message.includes(getMessage(message)));49};5051const testIterable = async (t, {52 message,53 sourceOptions = {},54 getSource = () => execa('empty.js', sourceOptions),55 from,56}) => {57 const error = t.throws(() => {58 getSource().iterable({from});59 });60 t.true(error.message.includes(getMessage(message)));61};6263test('Must set "all" option to "true" to use .pipe("all")', testPipeError, {64 from: 'all',65 message: '"all" option must be true',66});67test('Must set "all" option to "true" to use .duplex("all")', testNodeStream, {68 from: 'all',69 message: '"all" option must be true',70});71test('Must set "all" option to "true" to use .iterable("all")', testIterable, {72 from: 'all',73 message: '"all" option must be true',74});75test('.pipe() cannot pipe to non-subprocesses', testPipeError, {76 getDestination: () => new PassThrough(),77 message: 'an Execa subprocess',78});79test('.pipe() cannot pipe to non-Execa subprocesses', testPipeError, {80 getDestination: () => spawn('node', ['--version']),81 message: 'an Execa subprocess',82});83test('.pipe() "from" option cannot be "stdin"', testPipeError, {84 from: 'stdin',85 message: '"from" must not be',86});87test('.duplex() "from" option cannot be "stdin"', testNodeStream, {88 from: 'stdin',89 message: '"from" must not be',90});91test('.iterable() "from" option cannot be "stdin"', testIterable, {92 from: 'stdin',93 message: '"from" must not be',94});95test('$.pipe() "from" option cannot be "stdin"', testPipeError, {96 from: 'stdin',97 isScript: true,98 message: '"from" must not be',99});100test('.pipe() "to" option cannot be "stdout"', testPipeError, {101 to: 'stdout',102 message: '"to" must not be',103});104test('.duplex() "to" option cannot be "stdout"', testNodeStream, {105 to: 'stdout',106 message: '"to" must not be',107});108test('$.pipe() "to" option cannot be "stdout"', testPipeError, {109 to: 'stdout',110 isScript: true,111 message: '"to" must not be',112});113test('.pipe() "from" option cannot be any string', testPipeError, {114 from: 'other',115 message: 'must be "stdout", "stderr", "all"',116});117test('.duplex() "from" option cannot be any string', testNodeStream, {118 from: 'other',119 message: 'must be "stdout", "stderr", "all"',120});121test('.iterable() "from" option cannot be any string', testIterable, {122 from: 'other',123 message: 'must be "stdout", "stderr", "all"',124});125test('.pipe() "to" option cannot be any string', testPipeError, {126 to: 'other',127 message: 'must be "stdin"',128});129test('.duplex() "to" option cannot be any string', testNodeStream, {130 to: 'other',131 message: 'must be "stdin"',132});133test('.pipe() "from" option cannot be a number without "fd"', testPipeError, {134 from: '1',135 message: 'must be "stdout", "stderr", "all"',136});137test('.duplex() "from" option cannot be a number without "fd"', testNodeStream, {138 from: '1',139 message: 'must be "stdout", "stderr", "all"',140});141test('.iterable() "from" option cannot be a number without "fd"', testIterable, {142 from: '1',143 message: 'must be "stdout", "stderr", "all"',144});145test('.pipe() "to" option cannot be a number without "fd"', testPipeError, {146 to: '0',147 message: 'must be "stdin"',148});149test('.duplex() "to" option cannot be a number without "fd"', testNodeStream, {150 to: '0',151 message: 'must be "stdin"',152});153test('.pipe() "from" option cannot be just "fd"', testPipeError, {154 from: 'fd',155 message: 'must be "stdout", "stderr", "all"',156});157test('.duplex() "from" option cannot be just "fd"', testNodeStream, {158 from: 'fd',159 message: 'must be "stdout", "stderr", "all"',160});161test('.iterable() "from" option cannot be just "fd"', testIterable, {162 from: 'fd',163 message: 'must be "stdout", "stderr", "all"',164});165test('.pipe() "to" option cannot be just "fd"', testPipeError, {166 to: 'fd',167 message: 'must be "stdin"',168});169test('.duplex() "to" option cannot be just "fd"', testNodeStream, {170 to: 'fd',171 message: 'must be "stdin"',172});173test('.pipe() "from" option cannot be a float', testPipeError, {174 from: 'fd1.5',175 message: 'must be "stdout", "stderr", "all"',176});177test('.duplex() "from" option cannot be a float', testNodeStream, {178 from: 'fd1.5',179 message: 'must be "stdout", "stderr", "all"',180});181test('.iterable() "from" option cannot be a float', testIterable, {182 from: 'fd1.5',183 message: 'must be "stdout", "stderr", "all"',184});185test('.pipe() "to" option cannot be a float', testPipeError, {186 to: 'fd1.5',187 message: 'must be "stdin"',188});189test('.duplex() "to" option cannot be a float', testNodeStream, {190 to: 'fd1.5',191 message: 'must be "stdin"',192});193test('.pipe() "from" option cannot be a negative number', testPipeError, {194 from: 'fd-1',195 message: 'must be "stdout", "stderr", "all"',196});197test('.duplex() "from" option cannot be a negative number', testNodeStream, {198 from: 'fd-1',199 message: 'must be "stdout", "stderr", "all"',200});201test('.iterable() "from" option cannot be a negative number', testIterable, {202 from: 'fd-1',203 message: 'must be "stdout", "stderr", "all"',204});205test('.pipe() "to" option cannot be a negative number', testPipeError, {206 to: 'fd-1',207 message: 'must be "stdin"',208});209test('.duplex() "to" option cannot be a negative number', testNodeStream, {210 to: 'fd-1',211 message: 'must be "stdin"',212});213test('.pipe() "from" option cannot be a non-existing file descriptor', testPipeError, {214 from: 'fd3',215 message: 'file descriptor does not exist',216});217test('.duplex() "from" cannot be a non-existing file descriptor', testNodeStream, {218 from: 'fd3',219 message: 'file descriptor does not exist',220});221test('.iterable() "from" cannot be a non-existing file descriptor', testIterable, {222 from: 'fd3',223 message: 'file descriptor does not exist',224});225test('.pipe() "to" option cannot be a non-existing file descriptor', testPipeError, {226 to: 'fd3',227 message: 'file descriptor does not exist',228});229test('.duplex() "to" cannot be a non-existing file descriptor', testNodeStream, {230 to: 'fd3',231 message: 'file descriptor does not exist',232});233test('.pipe() "from" option cannot be an input file descriptor', testPipeError, {234 sourceOptions: getStdio(3, new Uint8Array()),235 from: 'fd3',236 message: 'must be a readable stream',237});238test('.duplex() "from" option cannot be an input file descriptor', testNodeStream, {239 sourceOptions: getStdio(3, new Uint8Array()),240 from: 'fd3',241 message: 'must be a readable stream',242});243test('.iterable() "from" option cannot be an input file descriptor', testIterable, {244 sourceOptions: getStdio(3, new Uint8Array()),245 from: 'fd3',246 message: 'must be a readable stream',247});248test('.pipe() "to" option cannot be an output file descriptor', testPipeError, {249 destinationOptions: fullStdio,250 to: 'fd3',251 message: 'must be a writable stream',252});253test('.duplex() "to" option cannot be an output file descriptor', testNodeStream, {254 sourceOptions: fullStdio,255 to: 'fd3',256 message: 'must be a writable stream',257});258test('.pipe() "to" option cannot be "all"', testPipeError, {259 destinationOptions: fullStdio,260 to: 'all',261 message: 'must be a writable stream',262});263test('.duplex() "to" option cannot be "all"', testNodeStream, {264 sourceOptions: fullStdio,265 to: 'all',266 message: 'must be a writable stream',267});268test('Cannot set "stdout" option to "ignore" to use .pipe()', testPipeError, {269 sourceOptions: {stdout: 'ignore'},270 message: ['stdout', '\'ignore\''],271});272test('Cannot set "stdout" option to "ignore" to use .duplex()', testNodeStream, {273 sourceOptions: {stdout: 'ignore'},274 message: ['stdout', '\'ignore\''],275});276test('Cannot set "stdout" option to "ignore" to use .iterable()', testIterable, {277 sourceOptions: {stdout: 'ignore'},278 message: ['stdout', '\'ignore\''],279});280test('Cannot set "stdin" option to "ignore" to use .pipe()', testPipeError, {281 destinationOptions: {stdin: 'ignore'},282 message: ['stdin', '\'ignore\''],283});284test('Cannot set "stdin" option to "ignore" to use .duplex()', testNodeStream, {285 sourceOptions: {stdin: 'ignore'},286 message: ['stdin', '\'ignore\''],287 writable: true,288});289test('Cannot set "stdout" option to "ignore" to use .pipe(1)', testPipeError, {290 sourceOptions: {stdout: 'ignore'},291 from: 'fd1',292 message: ['stdout', '\'ignore\''],293});294test('Cannot set "stdout" option to "ignore" to use .duplex(1)', testNodeStream, {295 sourceOptions: {stdout: 'ignore'},296 from: 'fd1',297 message: ['stdout', '\'ignore\''],298});299test('Cannot set "stdout" option to "ignore" to use .iterable(1)', testIterable, {300 sourceOptions: {stdout: 'ignore'},301 from: 'fd1',302 message: ['stdout', '\'ignore\''],303});304test('Cannot set "stdin" option to "ignore" to use .pipe(0)', testPipeError, {305 destinationOptions: {stdin: 'ignore'},306 message: ['stdin', '\'ignore\''],307 to: 'fd0',308});309test('Cannot set "stdin" option to "ignore" to use .duplex(0)', testNodeStream, {310 sourceOptions: {stdin: 'ignore'},311 message: ['stdin', '\'ignore\''],312 to: 'fd0',313});314test('Cannot set "stdout" option to "ignore" to use .pipe("stdout")', testPipeError, {315 sourceOptions: {stdout: 'ignore'},316 from: 'stdout',317 message: ['stdout', '\'ignore\''],318});319test('Cannot set "stdout" option to "ignore" to use .duplex("stdout")', testNodeStream, {320 sourceOptions: {stdout: 'ignore'},321 from: 'stdout',322 message: ['stdout', '\'ignore\''],323});324test('Cannot set "stdout" option to "ignore" to use .iterable("stdout")', testIterable, {325 sourceOptions: {stdout: 'ignore'},326 from: 'stdout',327 message: ['stdout', '\'ignore\''],328});329test('Cannot set "stdin" option to "ignore" to use .pipe("stdin")', testPipeError, {330 destinationOptions: {stdin: 'ignore'},331 message: ['stdin', '\'ignore\''],332 to: 'stdin',333});334test('Cannot set "stdin" option to "ignore" to use .duplex("stdin")', testNodeStream, {335 sourceOptions: {stdin: 'ignore'},336 message: ['stdin', '\'ignore\''],337 to: 'stdin',338});339test('Cannot set "stdout" + "stderr" option to "ignore" to use .pipe()', testPipeError, {340 sourceOptions: {stdout: 'ignore', stderr: 'ignore'},341 message: ['stdout', '\'ignore\''],342});343test('Cannot set "stdout" + "stderr" option to "ignore" to use .duplex()', testNodeStream, {344 sourceOptions: {stdout: 'ignore', stderr: 'ignore'},345 message: ['stdout', '\'ignore\''],346});347test('Cannot set "stdout" + "stderr" option to "ignore" to use .iterable()', testIterable, {348 sourceOptions: {stdout: 'ignore', stderr: 'ignore'},349 message: ['stdout', '\'ignore\''],350});351test('Cannot set "stdout" + "stderr" option to "ignore" to use .pipe(1)', testPipeError, {352 sourceOptions: {stdout: 'ignore', stderr: 'ignore'},353 from: 'fd1',354 message: ['stdout', '\'ignore\''],355});356test('Cannot set "stdout" + "stderr" option to "ignore" to use .duplex(1)', testNodeStream, {357 sourceOptions: {stdout: 'ignore', stderr: 'ignore'},358 from: 'fd1',359 message: ['stdout', '\'ignore\''],360});361test('Cannot set "stdout" + "stderr" option to "ignore" to use .iterable(1)', testIterable, {362 sourceOptions: {stdout: 'ignore', stderr: 'ignore'},363 from: 'fd1',364 message: ['stdout', '\'ignore\''],365});366test('Cannot set "stdout" + "stderr" option to "ignore" to use .pipe("stdout")', testPipeError, {367 sourceOptions: {stdout: 'ignore', stderr: 'ignore'},368 from: 'stdout',369 message: ['stdout', '\'ignore\''],370});371test('Cannot set "stdout" + "stderr" option to "ignore" to use .duplex("stdout")', testNodeStream, {372 sourceOptions: {stdout: 'ignore', stderr: 'ignore'},373 from: 'stdout',374 message: ['stdout', '\'ignore\''],375});376test('Cannot set "stdout" + "stderr" option to "ignore" to use .iterable("stdout")', testIterable, {377 sourceOptions: {stdout: 'ignore', stderr: 'ignore'},378 from: 'stdout',379 message: ['stdout', '\'ignore\''],380});381test('Cannot set "stdio[1]" option to "ignore" to use .pipe()', testPipeError, {382 sourceOptions: {stdio: ['pipe', 'ignore', 'pipe']},383 message: ['stdio[1]', '\'ignore\''],384});385test('Cannot set "stdio[1]" option to "ignore" to use .duplex()', testNodeStream, {386 sourceOptions: {stdio: ['pipe', 'ignore', 'pipe']},387 message: ['stdio[1]', '\'ignore\''],388});389test('Cannot set "stdio[1]" option to "ignore" to use .iterable()', testIterable, {390 sourceOptions: {stdio: ['pipe', 'ignore', 'pipe']},391 message: ['stdio[1]', '\'ignore\''],392});393test('Cannot set "stdio[0]" option to "ignore" to use .pipe()', testPipeError, {394 destinationOptions: {stdio: ['ignore', 'pipe', 'pipe']},395 message: ['stdio[0]', '\'ignore\''],396});397test('Cannot set "stdio[0]" option to "ignore" to use .duplex()', testNodeStream, {398 sourceOptions: {stdio: ['ignore', 'pipe', 'pipe']},399 message: ['stdio[0]', '\'ignore\''],400 writable: true,401});402test('Cannot set "stdio[1]" option to "ignore" to use .pipe(1)', testPipeError, {403 sourceOptions: {stdio: ['pipe', 'ignore', 'pipe']},404 from: 'fd1',405 message: ['stdio[1]', '\'ignore\''],406});407test('Cannot set "stdio[1]" option to "ignore" to use .duplex(1)', testNodeStream, {408 sourceOptions: {stdio: ['pipe', 'ignore', 'pipe']},409 from: 'fd1',410 message: ['stdio[1]', '\'ignore\''],411});412test('Cannot set "stdio[1]" option to "ignore" to use .iterable(1)', testIterable, {413 sourceOptions: {stdio: ['pipe', 'ignore', 'pipe']},414 from: 'fd1',415 message: ['stdio[1]', '\'ignore\''],416});417test('Cannot set "stdio[0]" option to "ignore" to use .pipe(0)', testPipeError, {418 destinationOptions: {stdio: ['ignore', 'pipe', 'pipe']},419 message: ['stdio[0]', '\'ignore\''],420 to: 'fd0',421});422test('Cannot set "stdio[0]" option to "ignore" to use .duplex(0)', testNodeStream, {423 sourceOptions: {stdio: ['ignore', 'pipe', 'pipe']},424 message: ['stdio[0]', '\'ignore\''],425 to: 'fd0',426});427test('Cannot set "stdio[1]" option to "ignore" to use .pipe("stdout")', testPipeError, {428 sourceOptions: {stdio: ['pipe', 'ignore', 'pipe']},429 from: 'stdout',430 message: ['stdio[1]', '\'ignore\''],431});432test('Cannot set "stdio[1]" option to "ignore" to use .duplex("stdout")', testNodeStream, {433 sourceOptions: {stdio: ['pipe', 'ignore', 'pipe']},434 from: 'stdout',435 message: ['stdio[1]', '\'ignore\''],436});437test('Cannot set "stdio[1]" option to "ignore" to use .iterable("stdout")', testIterable, {438 sourceOptions: {stdio: ['pipe', 'ignore', 'pipe']},439 from: 'stdout',440 message: ['stdio[1]', '\'ignore\''],441});442test('Cannot set "stdio[0]" option to "ignore" to use .pipe("stdin")', testPipeError, {443 destinationOptions: {stdio: ['ignore', 'pipe', 'pipe']},444 message: ['stdio[0]', '\'ignore\''],445 to: 'stdin',446});447test('Cannot set "stdio[0]" option to "ignore" to use .duplex("stdin")', testNodeStream, {448 sourceOptions: {stdio: ['ignore', 'pipe', 'pipe']},449 message: ['stdio[0]', '\'ignore\''],450 to: 'stdin',451});452test('Cannot set "stderr" option to "ignore" to use .pipe(2)', testPipeError, {453 sourceOptions: {stderr: 'ignore'},454 from: 'fd2',455 message: ['stderr', '\'ignore\''],456});457test('Cannot set "stderr" option to "ignore" to use .duplex(2)', testNodeStream, {458 sourceOptions: {stderr: 'ignore'},459 from: 'fd2',460 message: ['stderr', '\'ignore\''],461});462test('Cannot set "stderr" option to "ignore" to use .iterable(2)', testIterable, {463 sourceOptions: {stderr: 'ignore'},464 from: 'fd2',465 message: ['stderr', '\'ignore\''],466});467test('Cannot set "stderr" option to "ignore" to use .pipe("stderr")', testPipeError, {468 sourceOptions: {stderr: 'ignore'},469 from: 'stderr',470 message: ['stderr', '\'ignore\''],471});472test('Cannot set "stderr" option to "ignore" to use .duplex("stderr")', testNodeStream, {473 sourceOptions: {stderr: 'ignore'},474 from: 'stderr',475 message: ['stderr', '\'ignore\''],476});477test('Cannot set "stderr" option to "ignore" to use .iterable("stderr")', testIterable, {478 sourceOptions: {stderr: 'ignore'},479 from: 'stderr',480 message: ['stderr', '\'ignore\''],481});482test('Cannot set "stdout" + "stderr" option to "ignore" to use .pipe(2)', testPipeError, {483 sourceOptions: {stdout: 'ignore', stderr: 'ignore'},484 from: 'fd2',485 message: ['stderr', '\'ignore\''],486});487test('Cannot set "stdout" + "stderr" option to "ignore" to use .duplex(2)', testNodeStream, {488 sourceOptions: {stdout: 'ignore', stderr: 'ignore'},489 from: 'fd2',490 message: ['stderr', '\'ignore\''],491});492test('Cannot set "stdout" + "stderr" option to "ignore" to use .iterable(2)', testIterable, {493 sourceOptions: {stdout: 'ignore', stderr: 'ignore'},494 from: 'fd2',495 message: ['stderr', '\'ignore\''],496});497test('Cannot set "stdout" + "stderr" option to "ignore" to use .pipe("stderr")', testPipeError, {498 sourceOptions: {stdout: 'ignore', stderr: 'ignore'},499 from: 'stderr',500 message: ['stderr', '\'ignore\''],501});502test('Cannot set "stdout" + "stderr" option to "ignore" to use .duplex("stderr")', testNodeStream, {503 sourceOptions: {stdout: 'ignore', stderr: 'ignore'},504 from: 'stderr',505 message: ['stderr', '\'ignore\''],506});507test('Cannot set "stdout" + "stderr" option to "ignore" to use .iterable("stderr")', testIterable, {508 sourceOptions: {stdout: 'ignore', stderr: 'ignore'},509 from: 'stderr',510 message: ['stderr', '\'ignore\''],511});512test('Cannot set "stdio[2]" option to "ignore" to use .pipe(2)', testPipeError, {513 sourceOptions: {stdio: ['pipe', 'pipe', 'ignore']},514 from: 'fd2',515 message: ['stdio[2]', '\'ignore\''],516});517test('Cannot set "stdio[2]" option to "ignore" to use .duplex(2)', testNodeStream, {518 sourceOptions: {stdio: ['pipe', 'pipe', 'ignore']},519 from: 'fd2',520 message: ['stdio[2]', '\'ignore\''],521});522test('Cannot set "stdio[2]" option to "ignore" to use .iterable(2)', testIterable, {523 sourceOptions: {stdio: ['pipe', 'pipe', 'ignore']},524 from: 'fd2',525 message: ['stdio[2]', '\'ignore\''],526});527test('Cannot set "stdio[2]" option to "ignore" to use .pipe("stderr")', testPipeError, {528 sourceOptions: {stdio: ['pipe', 'pipe', 'ignore']},529 from: 'stderr',530 message: ['stdio[2]', '\'ignore\''],531});532test('Cannot set "stdio[2]" option to "ignore" to use .duplex("stderr")', testNodeStream, {533 sourceOptions: {stdio: ['pipe', 'pipe', 'ignore']},534 from: 'stderr',535 message: ['stdio[2]', '\'ignore\''],536});537test('Cannot set "stdio[2]" option to "ignore" to use .iterable("stderr")', testIterable, {538 sourceOptions: {stdio: ['pipe', 'pipe', 'ignore']},539 from: 'stderr',540 message: ['stdio[2]', '\'ignore\''],541});542test('Cannot set "stdio[3]" option to "ignore" to use .pipe(3)', testPipeError, {543 sourceOptions: getStdio(3, 'ignore'),544 from: 'fd3',545 message: ['stdio[3]', '\'ignore\''],546});547test('Cannot set "stdio[3]" option to "ignore" to use .duplex(3)', testNodeStream, {548 sourceOptions: getStdio(3, 'ignore'),549 from: 'fd3',550 message: ['stdio[3]', '\'ignore\''],551});552test('Cannot set "stdio[3]" option to "ignore" to use .iterable(3)', testIterable, {553 sourceOptions: getStdio(3, 'ignore'),554 from: 'fd3',555 message: ['stdio[3]', '\'ignore\''],556});557test('Cannot set "stdout" + "stderr" option to "ignore" to use .pipe("all")', testPipeError, {558 sourceOptions: {stdout: 'ignore', stderr: 'ignore', all: true},559 from: 'all',560 message: ['stdout', '\'ignore\''],561});562test('Cannot set "stdout" + "stderr" option to "ignore" to use .duplex("all")', testNodeStream, {563 sourceOptions: {stdout: 'ignore', stderr: 'ignore', all: true},564 from: 'all',565 message: ['stdout', '\'ignore\''],566});567test('Cannot set "stdout" + "stderr" option to "ignore" to use .iterable("all")', testIterable, {568 sourceOptions: {stdout: 'ignore', stderr: 'ignore', all: true},569 from: 'all',570 message: ['stdout', '\'ignore\''],571});572test('Cannot set "stdio[1]" + "stdio[2]" option to "ignore" to use .pipe("all")', testPipeError, {573 sourceOptions: {stdio: ['pipe', 'ignore', 'ignore'], all: true},574 from: 'all',575 message: ['stdio[1]', '\'ignore\''],576});577test('Cannot set "stdio[1]" + "stdio[2]" option to "ignore" to use .duplex("all")', testNodeStream, {578 sourceOptions: {stdio: ['pipe', 'ignore', 'ignore'], all: true},579 from: 'all',580 message: ['stdio[1]', '\'ignore\''],581});582test('Cannot set "stdio[1]" + "stdio[2]" option to "ignore" to use .iterable("all")', testIterable, {583 sourceOptions: {stdio: ['pipe', 'ignore', 'ignore'], all: true},584 from: 'all',585 message: ['stdio[1]', '\'ignore\''],586});587test('Cannot set "stdout" option to "inherit" to use .pipe()', testPipeError, {588 sourceOptions: {stdout: 'inherit'},589 message: ['stdout', '\'inherit\''],590});591test('Cannot set "stdout" option to "inherit" to use .duplex()', testNodeStream, {592 sourceOptions: {stdout: 'inherit'},593 message: ['stdout', '\'inherit\''],594});595test('Cannot set "stdout" option to "inherit" to use .iterable()', testIterable, {596 sourceOptions: {stdout: 'inherit'},597 message: ['stdout', '\'inherit\''],598});599test('Cannot set "stdin" option to "inherit" to use .pipe()', testPipeError, {600 destinationOptions: {stdin: 'inherit'},601 message: ['stdin', '\'inherit\''],602});603test('Cannot set "stdin" option to "inherit" to use .duplex()', testNodeStream, {604 sourceOptions: {stdin: 'inherit'},605 message: ['stdin', '\'inherit\''],606 writable: true,607});608test('Cannot set "stdout" option to "ipc" to use .pipe()', testPipeError, {609 sourceOptions: {stdout: 'ipc'},610 message: ['stdout', '\'ipc\''],611});612test('Cannot set "stdout" option to "ipc" to use .duplex()', testNodeStream, {613 sourceOptions: {stdout: 'ipc'},614 message: ['stdout', '\'ipc\''],615});616test('Cannot set "stdout" option to "ipc" to use .iterable()', testIterable, {617 sourceOptions: {stdout: 'ipc'},618 message: ['stdout', '\'ipc\''],619});620test('Cannot set "stdin" option to "ipc" to use .pipe()', testPipeError, {621 destinationOptions: {stdin: 'ipc'},622 message: ['stdin', '\'ipc\''],623});624test('Cannot set "stdin" option to "ipc" to use .duplex()', testNodeStream, {625 sourceOptions: {stdin: 'ipc'},626 message: ['stdin', '\'ipc\''],627 writable: true,628});629test('Cannot set "stdout" option to file descriptors to use .pipe()', testPipeError, {630 sourceOptions: {stdout: 1},631 message: ['stdout', '1'],632});633test('Cannot set "stdout" option to file descriptors to use .duplex()', testNodeStream, {634 sourceOptions: {stdout: 1},635 message: ['stdout', '1'],636});637test('Cannot set "stdout" option to file descriptors to use .iterable()', testIterable, {638 sourceOptions: {stdout: 1},639 message: ['stdout', '1'],640});641test('Cannot set "stdin" option to file descriptors to use .pipe()', testPipeError, {642 destinationOptions: {stdin: 0},643 message: ['stdin', '0'],644});645test('Cannot set "stdin" option to file descriptors to use .duplex()', testNodeStream, {646 sourceOptions: {stdin: 0},647 message: ['stdin', '0'],648 writable: true,649});650test('Cannot set "stdout" option to Node.js streams to use .pipe()', testPipeError, {651 sourceOptions: {stdout: process.stdout},652 message: ['stdout', 'Stream'],653});654test('Cannot set "stdout" option to Node.js streams to use .duplex()', testNodeStream, {655 sourceOptions: {stdout: process.stdout},656 message: ['stdout', 'Stream'],657});658test('Cannot set "stdout" option to Node.js streams to use .iterable()', testIterable, {659 sourceOptions: {stdout: process.stdout},660 message: ['stdout', 'Stream'],661});662test('Cannot set "stdin" option to Node.js streams to use .pipe()', testPipeError, {663 destinationOptions: {stdin: process.stdin},664 message: ['stdin', 'Stream'],665});666test('Cannot set "stdin" option to Node.js streams to use .duplex()', testNodeStream, {667 sourceOptions: {stdin: process.stdin},668 message: ['stdin', 'Stream'],669 writable: true,670});671test('Cannot set "stdio[3]" option to Node.js Writable streams to use .pipe()', testPipeError, {672 sourceOptions: getStdio(3, process.stdout),673 message: ['stdio[3]', 'Stream'],674 from: 'fd3',675});676test('Cannot set "stdio[3]" option to Node.js Writable streams to use .duplex()', testNodeStream, {677 sourceOptions: getStdio(3, process.stdout),678 message: ['stdio[3]', 'Stream'],679 from: 'fd3',680});681test('Cannot set "stdio[3]" option to Node.js Writable streams to use .iterable()', testIterable, {682 sourceOptions: getStdio(3, process.stdout),683 message: ['stdio[3]', 'Stream'],684 from: 'fd3',685});686test('Cannot set "stdio[3]" option to Node.js Readable streams to use .pipe()', testPipeError, {687 destinationOptions: getStdio(3, process.stdin),688 message: ['stdio[3]', 'Stream'],689 to: 'fd3',690});691test('Cannot set "stdio[3]" option to Node.js Readable streams to use .duplex()', testNodeStream, {692 sourceOptions: getStdio(3, process.stdin),693 message: ['stdio[3]', 'Stream'],694 to: 'fd3',695});696697test('Sets the right error message when the "all" option is incompatible - execa.$', async t => {698 await assertPipeError(699 t,700 execa('empty.js')701 .pipe({all: false})`stdin.js`702 .pipe(execa('empty.js'), {from: 'all'}),703 '"all" option must be true',704 );705});706707test('Sets the right error message when the "all" option is incompatible - execa.execa', async t => {708 await assertPipeError(709 t,710 execa('empty.js')711 .pipe(execa('stdin.js', {all: false}))712 .pipe(execa('empty.js'), {from: 'all'}),713 '"all" option must be true',714 );715});716717test('Sets the right error message when the "all" option is incompatible - early error', async t => {718 await assertPipeError(719 t,720 getEarlyErrorSubprocess()721 .pipe(execa('stdin.js', {all: false}))722 .pipe(execa('empty.js'), {from: 'all'}),723 '"all" option must be true',724 );725});
deleted:test/exit/code.js-85 removed
1import process from 'node:process';2import test from 'ava';3import {execa} from '../../index.js';4import {setFixtureDir} from '../helpers/fixtures-dir.js';56const isWindows = process.platform === 'win32';78setFixtureDir();910test('exitCode is 0 on success', async t => {11 const {exitCode} = await execa('noop.js', ['foo']);12 t.is(exitCode, 0);13});1415const testExitCode = async (t, expectedExitCode) => {16 const {exitCode, originalMessage, shortMessage, message} = await t.throwsAsync(17 execa('exit.js', [`${expectedExitCode}`]),18 );19 t.is(exitCode, expectedExitCode);20 t.is(originalMessage, '');21 t.is(shortMessage, `Command failed with exit code ${expectedExitCode}: exit.js ${expectedExitCode}`);22 t.is(message, shortMessage);23};2425test('exitCode is 2', testExitCode, 2);26test('exitCode is 3', testExitCode, 3);27test('exitCode is 4', testExitCode, 4);2829if (!isWindows) {30 test('error.signal is SIGINT', async t => {31 const subprocess = execa('forever.js');3233 process.kill(subprocess.pid, 'SIGINT');3435 const {signal} = await t.throwsAsync(subprocess, {message: /was killed with SIGINT/});36 t.is(signal, 'SIGINT');37 });3839 test('error.signalDescription is defined', async t => {40 const subprocess = execa('forever.js');4142 process.kill(subprocess.pid, 'SIGINT');4344 const {signalDescription} = await t.throwsAsync(subprocess, {message: /User interruption with CTRL-C/});45 t.is(signalDescription, 'User interruption with CTRL-C');46 });4748 test('error.signal is SIGTERM', async t => {49 const subprocess = execa('forever.js');5051 process.kill(subprocess.pid, 'SIGTERM');5253 const {signal} = await t.throwsAsync(subprocess, {message: /was killed with SIGTERM/});54 t.is(signal, 'SIGTERM');55 });5657 test('error.signal uses killSignal', async t => {58 const {signal} = await t.throwsAsync(execa('forever.js', {killSignal: 'SIGINT', timeout: 1, message: /timed out after/}));59 t.is(signal, 'SIGINT');60 });6162 test('exitCode is undefined on signal termination', async t => {63 const subprocess = execa('forever.js');6465 process.kill(subprocess.pid);6667 const {exitCode} = await t.throwsAsync(subprocess);68 t.is(exitCode, undefined);69 });70}7172test('result.signal is undefined for successful execution', async t => {73 const {signal} = await execa('noop.js');74 t.is(signal, undefined);75});7677test('result.signal is undefined if subprocess failed, but was not killed', async t => {78 const {signal} = await t.throwsAsync(execa('fail.js'));79 t.is(signal, undefined);80});8182test('result.signalDescription is undefined for successful execution', async t => {83 const {signalDescription} = await execa('noop.js');84 t.is(signalDescription, undefined);85});
added:test/exit/kill-error.js+83 added
1import {once} from 'node:events';2import {setImmediate} from 'node:timers/promises';3import test from 'ava';4import isRunning from 'is-running';5import {execa} from '../../index.js';6import {setFixtureDir} from '../helpers/fixtures-dir.js';78setFixtureDir();910test('.kill(error) propagates error', async t => {11 const subprocess = execa('forever.js');12 const originalMessage = 'test';13 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'));24});2526test('.kill(error) uses killSignal', async t => {27 const subprocess = execa('forever.js', {killSignal: 'SIGINT'});28 const cause = new Error('test');29 subprocess.kill(cause);30 const error = await t.throwsAsync(subprocess);31 t.is(error.cause, cause);32 t.is(error.signal, 'SIGINT');33});3435test('.kill(signal, error) uses signal', async t => {36 const subprocess = execa('forever.js');37 const cause = new Error('test');38 subprocess.kill('SIGINT', cause);39 const error = await t.throwsAsync(subprocess);40 t.is(error.cause, cause);41 t.is(error.signal, 'SIGINT');42});4344test('.kill(error) is a noop if subprocess already exited', async t => {45 const subprocess = execa('empty.js');46 await subprocess;47 t.false(isRunning(subprocess.pid));48 t.false(subprocess.kill(new Error('test')));49});5051test('.kill(error) terminates but does not change the error if the subprocess already errored but did not exit yet', async t => {52 const subprocess = execa('forever.js');53 const cause = new Error('first');54 subprocess.stdout.destroy(cause);55 await setImmediate();56 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));64});6566test('.kill(error) twice in a row', async t => {67 const subprocess = execa('forever.js');68 const cause = new Error('first');69 subprocess.kill(cause);70 const secondCause = new Error('second');71 subprocess.kill(secondCause);72 const error = await t.throwsAsync(subprocess);73 t.is(error.cause, cause);74 t.false(error.message.includes(secondCause.message));75});7677test('.kill(error) does not emit the "error" event', async t => {78 const subprocess = execa('forever.js');79 const cause = new Error('test');80 subprocess.kill(cause);81 const error = await Promise.race([t.throwsAsync(subprocess), once(subprocess, 'error')]);82 t.is(error.cause, cause);83});
added:test/exit/kill-force.js+140 added
1import process from 'node:process';2import {once, defaultMaxListeners} from 'node:events';3import {constants} from 'node:os';4import {setTimeout} from 'node:timers/promises';5import test from 'ava';6import {pEvent} from 'p-event';7import isRunning from 'is-running';8import {execa} from '../../index.js';9import {setFixtureDir} from '../helpers/fixtures-dir.js';10import {assertMaxListeners} from '../helpers/listeners.js';1112setFixtureDir();1314const isWindows = process.platform === 'win32';1516const spawnNoKillable = async (forceKillAfterDelay, options) => {17 const subprocess = execa('no-killable.js', {18 ipc: true,19 forceKillAfterDelay,20 ...options,21 });22 await pEvent(subprocess, 'message');23 return {subprocess};24};2526const spawnNoKillableSimple = options => execa('forever.js', {killSignal: 'SIGWINCH', forceKillAfterDelay: 1, ...options});2728test('kill("SIGKILL") should terminate cleanly', async t => {29 const {subprocess} = await spawnNoKillable();3031 subprocess.kill('SIGKILL');3233 const {isTerminated, signal} = await t.throwsAsync(subprocess);34 t.true(isTerminated);35 t.is(signal, 'SIGKILL');36});3738const testInvalidForceKill = async (t, forceKillAfterDelay) => {39 t.throws(() => {40 execa('empty.js', {forceKillAfterDelay});41 }, {instanceOf: TypeError, message: /non-negative integer/});42};4344test('`forceKillAfterDelay` should not be NaN', testInvalidForceKill, Number.NaN);45test('`forceKillAfterDelay` should not be negative', testInvalidForceKill, -1);4647// `SIGTERM` cannot be caught on Windows, and it always aborts the subprocess (like `SIGKILL` on Unix).48// Therefore, this feature and those tests must be different on Windows.49if (isWindows) {50 test('Can call `.kill()` with `forceKillAfterDelay` on Windows', async t => {51 const {subprocess} = await spawnNoKillable(1);52 subprocess.kill();5354 const {isTerminated, signal} = await t.throwsAsync(subprocess);55 t.true(isTerminated);56 t.is(signal, 'SIGTERM');57 });58} else {59 const testNoForceKill = async (t, forceKillAfterDelay, killArgument, options) => {60 const {subprocess} = await spawnNoKillable(forceKillAfterDelay, options);6162 subprocess.kill(killArgument);6364 await setTimeout(6e3);65 t.true(isRunning(subprocess.pid));66 subprocess.kill('SIGKILL');6768 const {isTerminated, signal} = await t.throwsAsync(subprocess);69 t.true(isTerminated);70 t.is(signal, 'SIGKILL');71 };7273 test('`forceKillAfterDelay: false` should not kill after a timeout', testNoForceKill, false);74 test('`forceKillAfterDelay` should not kill after a timeout with other signals', testNoForceKill, true, 'SIGINT');75 test('`forceKillAfterDelay` should not kill after a timeout with wrong killSignal string', testNoForceKill, true, 'SIGTERM', {killSignal: 'SIGINT'});76 test('`forceKillAfterDelay` should not kill after a timeout with wrong killSignal number', testNoForceKill, true, constants.signals.SIGTERM, {killSignal: constants.signals.SIGINT});7778 const testForceKill = async (t, forceKillAfterDelay, killArgument, options) => {79 const {subprocess} = await spawnNoKillable(forceKillAfterDelay, options);8081 subprocess.kill(killArgument);8283 const {isTerminated, signal} = await t.throwsAsync(subprocess);84 t.true(isTerminated);85 t.is(signal, 'SIGKILL');86 };8788 test('`forceKillAfterDelay: number` should kill after a timeout', testForceKill, 50);89 test('`forceKillAfterDelay: true` should kill after a timeout', testForceKill, true);90 test('`forceKillAfterDelay: undefined` should kill after a timeout', testForceKill, undefined);91 test('`forceKillAfterDelay` should kill after a timeout with SIGTERM', testForceKill, 50, 'SIGTERM');92 test('`forceKillAfterDelay` should kill after a timeout with the killSignal string', testForceKill, 50, 'SIGINT', {killSignal: 'SIGINT'});93 test('`forceKillAfterDelay` should kill after a timeout with the killSignal number', testForceKill, 50, constants.signals.SIGINT, {killSignal: constants.signals.SIGINT});94 test('`forceKillAfterDelay` should kill after a timeout with an error', testForceKill, 50, new Error('test'));95 test('`forceKillAfterDelay` should kill after a timeout with an error and a killSignal', testForceKill, 50, new Error('test'), {killSignal: 'SIGINT'});9697 test('`forceKillAfterDelay` works with the "signal" option', async t => {98 const abortController = new AbortController();99 const subprocess = spawnNoKillableSimple({cancelSignal: abortController.signal});100 await once(subprocess, 'spawn');101 abortController.abort();102 const {isTerminated, signal, isCanceled} = await t.throwsAsync(subprocess);103 t.true(isTerminated);104 t.is(signal, 'SIGKILL');105 t.true(isCanceled);106 });107108 test('`forceKillAfterDelay` works with the "timeout" option', async t => {109 const subprocess = spawnNoKillableSimple({timeout: 1});110 const {isTerminated, signal, timedOut} = await t.throwsAsync(subprocess);111 t.true(isTerminated);112 t.is(signal, 'SIGKILL');113 t.true(timedOut);114 });115116 test.serial('Can call `.kill()` with `forceKillAfterDelay` many times without triggering the maxListeners warning', async t => {117 const checkMaxListeners = assertMaxListeners(t);118119 const subprocess = spawnNoKillableSimple();120 for (let index = 0; index < defaultMaxListeners + 1; index += 1) {121 subprocess.kill();122 }123124 const {isTerminated, signal} = await t.throwsAsync(subprocess);125 t.true(isTerminated);126 t.is(signal, 'SIGKILL');127128 checkMaxListeners();129 });130131 test('Can call `.kill()` with `forceKillAfterDelay` multiple times', async t => {132 const subprocess = spawnNoKillableSimple();133 subprocess.kill();134 subprocess.kill();135136 const {isTerminated, signal} = await t.throwsAsync(subprocess);137 t.true(isTerminated);138 t.is(signal, 'SIGKILL');139 });140}
added:test/exit/kill-signal.js+95 added
1import {once} from 'node:events';2import {setImmediate} from 'node:timers/promises';3import test from 'ava';4import {execa} from '../../index.js';5import {setFixtureDir} from '../helpers/fixtures-dir.js';67setFixtureDir();89test('Can call `.kill()` multiple times', async t => {10 const subprocess = execa('forever.js');11 subprocess.kill();12 subprocess.kill();1314 const {isTerminated, signal} = await t.throwsAsync(subprocess);15 t.true(isTerminated);16 t.is(signal, 'SIGTERM');17});1819test('execa() returns a promise with kill()', async t => {20 const subprocess = execa('noop.js', ['foo']);21 t.is(typeof subprocess.kill, 'function');22 await subprocess;23});2425const testInvalidKillArgument = async (t, killArgument, secondKillArgument) => {26 const subprocess = execa('empty.js');27 const message = secondKillArgument instanceof Error || secondKillArgument === undefined28 ? /error instance or a signal name/29 : /second argument is optional/;30 t.throws(() => {31 subprocess.kill(killArgument, secondKillArgument);32 }, {message});33 await subprocess;34};3536test('Cannot call .kill(null)', testInvalidKillArgument, null);37test('Cannot call .kill(0n)', testInvalidKillArgument, 0n);38test('Cannot call .kill(true)', testInvalidKillArgument, true);39test('Cannot call .kill(errorObject)', testInvalidKillArgument, {name: '', message: '', stack: ''});40test('Cannot call .kill(errorArray)', testInvalidKillArgument, [new Error('test')]);41test('Cannot call .kill(undefined, true)', testInvalidKillArgument, undefined, true);42test('Cannot call .kill("SIGTERM", true)', testInvalidKillArgument, 'SIGTERM', true);43test('Cannot call .kill(true, error)', testInvalidKillArgument, true, new Error('test'));4445test('subprocess errors are handled before spawn', async t => {46 const subprocess = execa('forever.js');47 const cause = new Error('test');48 subprocess.emit('error', cause);49 subprocess.kill();50 const error = await t.throwsAsync(subprocess);51 t.is(error.cause, cause);52 t.is(error.exitCode, undefined);53 t.is(error.signal, undefined);54 t.false(error.isTerminated);55});5657test('subprocess errors are handled after spawn', async t => {58 const subprocess = execa('forever.js');59 await once(subprocess, 'spawn');60 const cause = new Error('test');61 subprocess.emit('error', cause);62 subprocess.kill();63 const error = await t.throwsAsync(subprocess);64 t.is(error.cause, cause);65 t.is(error.exitCode, undefined);66 t.is(error.signal, 'SIGTERM');67 t.true(error.isTerminated);68});6970test('subprocess double errors are handled after spawn', async t => {71 const abortController = new AbortController();72 const subprocess = execa('forever.js', {cancelSignal: abortController.signal});73 await once(subprocess, 'spawn');74 const cause = new Error('test');75 subprocess.emit('error', cause);76 await setImmediate();77 abortController.abort();78 const error = await t.throwsAsync(subprocess);79 t.is(error.cause, cause);80 t.is(error.exitCode, undefined);81 t.is(error.signal, 'SIGTERM');82 t.true(error.isTerminated);83});8485test('subprocess errors use killSignal', async t => {86 const subprocess = execa('forever.js', {killSignal: 'SIGINT'});87 await once(subprocess, 'spawn');88 const cause = new Error('test');89 subprocess.emit('error', cause);90 subprocess.kill();91 const error = await t.throwsAsync(subprocess);92 t.is(error.cause, cause);93 t.true(error.isTerminated);94 t.is(error.signal, 'SIGINT');95});
deleted:test/exit/kill.js-303 removed
1import process from 'node:process';2import {once, defaultMaxListeners} from 'node:events';3import {constants} from 'node:os';4import {setTimeout, setImmediate} from 'node:timers/promises';5import test from 'ava';6import {pEvent} from 'p-event';7import isRunning from 'is-running';8import {execa} from '../../index.js';9import {setFixtureDir} from '../helpers/fixtures-dir.js';10import {assertMaxListeners} from '../helpers/listeners.js';1112setFixtureDir();1314const isWindows = process.platform === 'win32';1516const spawnNoKillable = async (forceKillAfterDelay, options) => {17 const subprocess = execa('no-killable.js', {18 ipc: true,19 forceKillAfterDelay,20 ...options,21 });22 await pEvent(subprocess, 'message');23 return {subprocess};24};2526const spawnNoKillableSimple = options => execa('forever.js', {killSignal: 'SIGWINCH', forceKillAfterDelay: 1, ...options});2728test('kill("SIGKILL") should terminate cleanly', async t => {29 const {subprocess} = await spawnNoKillable();3031 subprocess.kill('SIGKILL');3233 const {isTerminated, signal} = await t.throwsAsync(subprocess);34 t.true(isTerminated);35 t.is(signal, 'SIGKILL');36});3738const testInvalidForceKill = async (t, forceKillAfterDelay) => {39 t.throws(() => {40 execa('empty.js', {forceKillAfterDelay});41 }, {instanceOf: TypeError, message: /non-negative integer/});42};4344test('`forceKillAfterDelay` should not be NaN', testInvalidForceKill, Number.NaN);45test('`forceKillAfterDelay` should not be negative', testInvalidForceKill, -1);4647// `SIGTERM` cannot be caught on Windows, and it always aborts the subprocess (like `SIGKILL` on Unix).48// Therefore, this feature and those tests must be different on Windows.49if (isWindows) {50 test('Can call `.kill()` with `forceKillAfterDelay` on Windows', async t => {51 const {subprocess} = await spawnNoKillable(1);52 subprocess.kill();5354 const {isTerminated, signal} = await t.throwsAsync(subprocess);55 t.true(isTerminated);56 t.is(signal, 'SIGTERM');57 });58} else {59 const testNoForceKill = async (t, forceKillAfterDelay, killArgument, options) => {60 const {subprocess} = await spawnNoKillable(forceKillAfterDelay, options);6162 subprocess.kill(killArgument);6364 await setTimeout(6e3);65 t.true(isRunning(subprocess.pid));66 subprocess.kill('SIGKILL');6768 const {isTerminated, signal} = await t.throwsAsync(subprocess);69 t.true(isTerminated);70 t.is(signal, 'SIGKILL');71 };7273 test('`forceKillAfterDelay: false` should not kill after a timeout', testNoForceKill, false);74 test('`forceKillAfterDelay` should not kill after a timeout with other signals', testNoForceKill, true, 'SIGINT');75 test('`forceKillAfterDelay` should not kill after a timeout with wrong killSignal string', testNoForceKill, true, 'SIGTERM', {killSignal: 'SIGINT'});76 test('`forceKillAfterDelay` should not kill after a timeout with wrong killSignal number', testNoForceKill, true, constants.signals.SIGTERM, {killSignal: constants.signals.SIGINT});7778 const testForceKill = async (t, forceKillAfterDelay, killArgument, options) => {79 const {subprocess} = await spawnNoKillable(forceKillAfterDelay, options);8081 subprocess.kill(killArgument);8283 const {isTerminated, signal} = await t.throwsAsync(subprocess);84 t.true(isTerminated);85 t.is(signal, 'SIGKILL');86 };8788 test('`forceKillAfterDelay: number` should kill after a timeout', testForceKill, 50);89 test('`forceKillAfterDelay: true` should kill after a timeout', testForceKill, true);90 test('`forceKillAfterDelay: undefined` should kill after a timeout', testForceKill, undefined);91 test('`forceKillAfterDelay` should kill after a timeout with SIGTERM', testForceKill, 50, 'SIGTERM');92 test('`forceKillAfterDelay` should kill after a timeout with the killSignal string', testForceKill, 50, 'SIGINT', {killSignal: 'SIGINT'});93 test('`forceKillAfterDelay` should kill after a timeout with the killSignal number', testForceKill, 50, constants.signals.SIGINT, {killSignal: constants.signals.SIGINT});94 test('`forceKillAfterDelay` should kill after a timeout with an error', testForceKill, 50, new Error('test'));95 test('`forceKillAfterDelay` should kill after a timeout with an error and a killSignal', testForceKill, 50, new Error('test'), {killSignal: 'SIGINT'});9697 test('`forceKillAfterDelay` works with the "signal" option', async t => {98 const abortController = new AbortController();99 const subprocess = spawnNoKillableSimple({cancelSignal: abortController.signal});100 await once(subprocess, 'spawn');101 abortController.abort();102 const {isTerminated, signal, isCanceled} = await t.throwsAsync(subprocess);103 t.true(isTerminated);104 t.is(signal, 'SIGKILL');105 t.true(isCanceled);106 });107108 test('`forceKillAfterDelay` works with the "timeout" option', async t => {109 const subprocess = spawnNoKillableSimple({timeout: 1});110 const {isTerminated, signal, timedOut} = await t.throwsAsync(subprocess);111 t.true(isTerminated);112 t.is(signal, 'SIGKILL');113 t.true(timedOut);114 });115116 test.serial('Can call `.kill()` with `forceKillAfterDelay` many times without triggering the maxListeners warning', async t => {117 const checkMaxListeners = assertMaxListeners(t);118119 const subprocess = spawnNoKillableSimple();120 for (let index = 0; index < defaultMaxListeners + 1; index += 1) {121 subprocess.kill();122 }123124 const {isTerminated, signal} = await t.throwsAsync(subprocess);125 t.true(isTerminated);126 t.is(signal, 'SIGKILL');127128 checkMaxListeners();129 });130131 test('Can call `.kill()` with `forceKillAfterDelay` multiple times', async t => {132 const subprocess = spawnNoKillableSimple();133 subprocess.kill();134 subprocess.kill();135136 const {isTerminated, signal} = await t.throwsAsync(subprocess);137 t.true(isTerminated);138 t.is(signal, 'SIGKILL');139 });140}141142test('Can call `.kill()` multiple times', async t => {143 const subprocess = execa('forever.js');144 subprocess.kill();145 subprocess.kill();146147 const {isTerminated, signal} = await t.throwsAsync(subprocess);148 t.true(isTerminated);149 t.is(signal, 'SIGTERM');150});151152test('execa() returns a promise with kill()', async t => {153 const subprocess = execa('noop.js', ['foo']);154 t.is(typeof subprocess.kill, 'function');155 await subprocess;156});157158const testInvalidKillArgument = async (t, killArgument, secondKillArgument) => {159 const subprocess = execa('empty.js');160 const message = secondKillArgument instanceof Error || secondKillArgument === undefined161 ? /error instance or a signal name/162 : /second argument is optional/;163 t.throws(() => {164 subprocess.kill(killArgument, secondKillArgument);165 }, {message});166 await subprocess;167};168169test('Cannot call .kill(null)', testInvalidKillArgument, null);170test('Cannot call .kill(0n)', testInvalidKillArgument, 0n);171test('Cannot call .kill(true)', testInvalidKillArgument, true);172test('Cannot call .kill(errorObject)', testInvalidKillArgument, {name: '', message: '', stack: ''});173test('Cannot call .kill(errorArray)', testInvalidKillArgument, [new Error('test')]);174test('Cannot call .kill(undefined, true)', testInvalidKillArgument, undefined, true);175test('Cannot call .kill("SIGTERM", true)', testInvalidKillArgument, 'SIGTERM', true);176test('Cannot call .kill(true, error)', testInvalidKillArgument, true, new Error('test'));177178test('.kill(error) propagates error', async t => {179 const subprocess = execa('forever.js');180 const originalMessage = 'test';181 const cause = new Error(originalMessage);182 t.true(subprocess.kill(cause));183 const error = await t.throwsAsync(subprocess);184 t.is(error.cause, cause);185 t.true(cause.stack.includes(import.meta.url));186 t.is(error.exitCode, undefined);187 t.is(error.signal, 'SIGTERM');188 t.true(error.isTerminated);189 t.is(error.originalMessage, originalMessage);190 t.true(error.message.includes(originalMessage));191 t.true(error.message.includes('was killed with SIGTERM'));192});193194test('.kill(error) uses killSignal', async t => {195 const subprocess = execa('forever.js', {killSignal: 'SIGINT'});196 const cause = new Error('test');197 subprocess.kill(cause);198 const error = await t.throwsAsync(subprocess);199 t.is(error.cause, cause);200 t.is(error.signal, 'SIGINT');201});202203test('.kill(signal, error) uses signal', async t => {204 const subprocess = execa('forever.js');205 const cause = new Error('test');206 subprocess.kill('SIGINT', cause);207 const error = await t.throwsAsync(subprocess);208 t.is(error.cause, cause);209 t.is(error.signal, 'SIGINT');210});211212test('.kill(error) is a noop if subprocess already exited', async t => {213 const subprocess = execa('empty.js');214 await subprocess;215 t.false(isRunning(subprocess.pid));216 t.false(subprocess.kill(new Error('test')));217});218219test('.kill(error) terminates but does not change the error if the subprocess already errored but did not exit yet', async t => {220 const subprocess = execa('forever.js');221 const cause = new Error('first');222 subprocess.stdout.destroy(cause);223 await setImmediate();224 const secondError = new Error('second');225 t.true(subprocess.kill(secondError));226 const error = await t.throwsAsync(subprocess);227 t.is(error.cause, cause);228 t.is(error.exitCode, undefined);229 t.is(error.signal, 'SIGTERM');230 t.true(error.isTerminated);231 t.false(error.message.includes(secondError.message));232});233234test('.kill(error) twice in a row', async t => {235 const subprocess = execa('forever.js');236 const cause = new Error('first');237 subprocess.kill(cause);238 const secondCause = new Error('second');239 subprocess.kill(secondCause);240 const error = await t.throwsAsync(subprocess);241 t.is(error.cause, cause);242 t.false(error.message.includes(secondCause.message));243});244245test('.kill(error) does not emit the "error" event', async t => {246 const subprocess = execa('forever.js');247 const cause = new Error('test');248 subprocess.kill(cause);249 const error = await Promise.race([t.throwsAsync(subprocess), once(subprocess, 'error')]);250 t.is(error.cause, cause);251});252253test('subprocess errors are handled before spawn', async t => {254 const subprocess = execa('forever.js');255 const cause = new Error('test');256 subprocess.emit('error', cause);257 subprocess.kill();258 const error = await t.throwsAsync(subprocess);259 t.is(error.cause, cause);260 t.is(error.exitCode, undefined);261 t.is(error.signal, undefined);262 t.false(error.isTerminated);263});264265test('subprocess errors are handled after spawn', async t => {266 const subprocess = execa('forever.js');267 await once(subprocess, 'spawn');268 const cause = new Error('test');269 subprocess.emit('error', cause);270 subprocess.kill();271 const error = await t.throwsAsync(subprocess);272 t.is(error.cause, cause);273 t.is(error.exitCode, undefined);274 t.is(error.signal, 'SIGTERM');275 t.true(error.isTerminated);276});277278test('subprocess double errors are handled after spawn', async t => {279 const abortController = new AbortController();280 const subprocess = execa('forever.js', {cancelSignal: abortController.signal});281 await once(subprocess, 'spawn');282 const cause = new Error('test');283 subprocess.emit('error', cause);284 await setImmediate();285 abortController.abort();286 const error = await t.throwsAsync(subprocess);287 t.is(error.cause, cause);288 t.is(error.exitCode, undefined);289 t.is(error.signal, 'SIGTERM');290 t.true(error.isTerminated);291});292293test('subprocess errors use killSignal', async t => {294 const subprocess = execa('forever.js', {killSignal: 'SIGINT'});295 await once(subprocess, 'spawn');296 const cause = new Error('test');297 subprocess.emit('error', cause);298 subprocess.kill();299 const error = await t.throwsAsync(subprocess);300 t.is(error.cause, cause);301 t.true(error.isTerminated);302 t.is(error.signal, 'SIGINT');303});
added:test/helpers/file-path.js+4 added
1import {relative} from 'node:path';23export const getAbsolutePath = file => ({file});4export const getRelativePath = filePath => ({file: relative('.', filePath)});
modified:test/helpers/lines.js+6 added
1import {Buffer} from 'node:buffer';2import {execa} from '../../index.js';34const textEncoder = new TextEncoder();56export const stringsToUint8Arrays = strings => strings.map(string => stringToUint8Arrays(string, true));
30 unmodified lines
37export const singleComplexUint8Array = textEncoder.encode(complexFull);38export const singleComplexHex = complexFullBuffer.toString('hex');39export const complexChunksEnd = ['\n', 'aaa\r\n', 'bbb\n', '\n', 'ccc'];40export const complexChunks = ['', 'aaa', 'bbb', '', 'ccc'];41export const singleFull = 'aaa';42export const singleFullEnd = `${singleFull}\n`;4344export const getSimpleChunkSubprocessAsync = options => getSimpleChunkSubprocess(execa, options);45export const getSimpleChunkSubprocess = (execaMethod, options) => execaMethod('noop-fd.js', ['1', simpleFull], {lines: true, ...options});
added:test/helpers/pipe.js+26 added
1export const assertPipeError = async (t, pipePromise, message) => {2 const error = await t.throwsAsync(pipePromise);34 t.is(error.command, 'source.pipe(destination)');5 t.is(error.escapedCommand, error.command);67 t.is(typeof error.cwd, 'string');8 t.true(error.failed);9 t.false(error.timedOut);10 t.false(error.isCanceled);11 t.false(error.isTerminated);12 t.is(error.exitCode, undefined);13 t.is(error.signal, undefined);14 t.is(error.signalDescription, undefined);15 t.is(error.stdout, undefined);16 t.is(error.stderr, undefined);17 t.is(error.all, undefined);18 t.deepEqual(error.stdio, Array.from({length: error.stdio.length}));19 t.deepEqual(error.pipedFrom, []);2021 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));2425 t.true(error.originalMessage.includes(message));26};
added:test/helpers/wait.js+17 added
1import {getStdio} from '../helpers/stdio.js';2import {noopGenerator} from '../helpers/generator.js';34export const endOptionStream = ({stream}) => {5 stream.end();6};78export const destroyOptionStream = ({stream, error}) => {9 stream.destroy(error);10};1112export const destroySubprocessStream = ({subprocess, fdNumber, error}) => {13 subprocess.stdio[fdNumber].destroy(error);14};1516export const getStreamStdio = (fdNumber, stream, useTransform) =>17 getStdio(fdNumber, [stream, useTransform ? noopGenerator(false) : 'pipe']);
deleted:test/pipe/template.js-272 removed
1import {spawn} from 'node:child_process';2import {pathToFileURL} from 'node:url';3import test from 'ava';4import {$, execa} from '../../index.js';5import {setFixtureDir, FIXTURES_DIR} from '../helpers/fixtures-dir.js';6import {foobarString} from '../helpers/input.js';78setFixtureDir();910test('$.pipe(subprocess)', async t => {11 const {stdout} = await $`noop.js ${foobarString}`.pipe($({stdin: 'pipe'})`stdin.js`);12 t.is(stdout, foobarString);13});1415test('execa.$.pipe(subprocess)', async t => {16 const {stdout} = await execa('noop.js', [foobarString]).pipe($({stdin: 'pipe'})`stdin.js`);17 t.is(stdout, foobarString);18});1920test('$.pipe.pipe(subprocess)', async t => {21 const {stdout} = await $`noop.js ${foobarString}`22 .pipe($({stdin: 'pipe'})`stdin.js`)23 .pipe($({stdin: 'pipe'})`stdin.js`);24 t.is(stdout, foobarString);25});2627test('$.pipe`command`', async t => {28 const {stdout} = await $`noop.js ${foobarString}`.pipe`stdin.js`;29 t.is(stdout, foobarString);30});3132test('execa.$.pipe`command`', async t => {33 const {stdout} = await execa('noop.js', [foobarString]).pipe`stdin.js`;34 t.is(stdout, foobarString);35});3637test('$.pipe.pipe`command`', async t => {38 const {stdout} = await $`noop.js ${foobarString}`39 .pipe`stdin.js`40 .pipe`stdin.js`;41 t.is(stdout, foobarString);42});4344test('$.pipe("file")', async t => {45 const {stdout} = await $`noop.js ${foobarString}`.pipe('stdin.js');46 t.is(stdout, foobarString);47});4849test('execa.$.pipe("file")`', async t => {50 const {stdout} = await execa('noop.js', [foobarString]).pipe('stdin.js');51 t.is(stdout, foobarString);52});5354test('$.pipe.pipe("file")', async t => {55 const {stdout} = await $`noop.js ${foobarString}`56 .pipe`stdin.js`57 .pipe('stdin.js');58 t.is(stdout, foobarString);59});6061test('execa.$.pipe(fileUrl)`', async t => {62 const {stdout} = await execa('noop.js', [foobarString]).pipe(pathToFileURL(`${FIXTURES_DIR}/stdin.js`));63 t.is(stdout, foobarString);64});6566test('$.pipe("file", args, options)', async t => {67 const {stdout} = await $`noop.js ${foobarString}`.pipe('node', ['stdin.js'], {cwd: FIXTURES_DIR});68 t.is(stdout, foobarString);69});7071test('execa.$.pipe("file", args, options)`', async t => {72 const {stdout} = await execa('noop.js', [foobarString]).pipe('node', ['stdin.js'], {cwd: FIXTURES_DIR});73 t.is(stdout, foobarString);74});7576test('$.pipe.pipe("file", args, options)', async t => {77 const {stdout} = await $`noop.js ${foobarString}`78 .pipe`stdin.js`79 .pipe('node', ['stdin.js'], {cwd: FIXTURES_DIR});80 t.is(stdout, foobarString);81});8283test('$.pipe(subprocess, pipeOptions)', async t => {84 const {stdout} = await $`noop-fd.js 2 ${foobarString}`.pipe($({stdin: 'pipe'})`stdin.js`, {from: 'stderr'});85 t.is(stdout, foobarString);86});8788test('execa.$.pipe(subprocess, pipeOptions)', async t => {89 const {stdout} = await execa('noop-fd.js', ['2', foobarString]).pipe($({stdin: 'pipe'})`stdin.js`, {from: 'stderr'});90 t.is(stdout, foobarString);91});9293test('$.pipe.pipe(subprocess, pipeOptions)', async t => {94 const {stdout} = await $`noop-fd.js 2 ${foobarString}`95 .pipe($({stdin: 'pipe'})`noop-stdin-fd.js 2`, {from: 'stderr'})96 .pipe($({stdin: 'pipe'})`stdin.js`, {from: 'stderr'});97 t.is(stdout, foobarString);98});99100test('$.pipe(pipeOptions)`command`', async t => {101 const {stdout} = await $`noop-fd.js 2 ${foobarString}`.pipe({from: 'stderr'})`stdin.js`;102 t.is(stdout, foobarString);103});104105test('execa.$.pipe(pipeOptions)`command`', async t => {106 const {stdout} = await execa('noop-fd.js', ['2', foobarString]).pipe({from: 'stderr'})`stdin.js`;107 t.is(stdout, foobarString);108});109110test('$.pipe.pipe(pipeOptions)`command`', async t => {111 const {stdout} = await $`noop-fd.js 2 ${foobarString}`112 .pipe({from: 'stderr'})`noop-stdin-fd.js 2`113 .pipe({from: 'stderr'})`stdin.js`;114 t.is(stdout, foobarString);115});116117test('$.pipe("file", pipeOptions)', async t => {118 const {stdout} = await $`noop-fd.js 2 ${foobarString}`.pipe('stdin.js', {from: 'stderr'});119 t.is(stdout, foobarString);120});121122test('execa.$.pipe("file", pipeOptions)', async t => {123 const {stdout} = await execa('noop-fd.js', ['2', foobarString]).pipe('stdin.js', {from: 'stderr'});124 t.is(stdout, foobarString);125});126127test('$.pipe.pipe("file", pipeOptions)', async t => {128 const {stdout} = await $`noop-fd.js 2 ${foobarString}`129 .pipe({from: 'stderr'})`noop-stdin-fd.js 2`130 .pipe('stdin.js', {from: 'stderr'});131 t.is(stdout, foobarString);132});133134test('$.pipe(options)`command`', async t => {135 const {stdout} = await $`noop.js ${foobarString}`.pipe({stripFinalNewline: false})`stdin.js`;136 t.is(stdout, `${foobarString}\n`);137});138139test('execa.$.pipe(options)`command`', async t => {140 const {stdout} = await execa('noop.js', [foobarString]).pipe({stripFinalNewline: false})`stdin.js`;141 t.is(stdout, `${foobarString}\n`);142});143144test('$.pipe.pipe(options)`command`', async t => {145 const {stdout} = await $`noop.js ${foobarString}`146 .pipe({})`stdin.js`147 .pipe({stripFinalNewline: false})`stdin.js`;148 t.is(stdout, `${foobarString}\n`);149});150151test('$.pipe("file", options)', async t => {152 const {stdout} = await $`noop.js ${foobarString}`.pipe('stdin.js', {stripFinalNewline: false});153 t.is(stdout, `${foobarString}\n`);154});155156test('execa.$.pipe("file", options)', async t => {157 const {stdout} = await execa('noop.js', [foobarString]).pipe('stdin.js', {stripFinalNewline: false});158 t.is(stdout, `${foobarString}\n`);159});160161test('$.pipe.pipe("file", options)', async t => {162 const {stdout} = await $`noop.js ${foobarString}`163 .pipe({})`stdin.js`164 .pipe('stdin.js', {stripFinalNewline: false});165 t.is(stdout, `${foobarString}\n`);166});167168test('$.pipe(pipeAndSubprocessOptions)`command`', async t => {169 const {stdout} = await $`noop-fd.js 2 ${foobarString}\n`.pipe({from: 'stderr', stripFinalNewline: false})`stdin.js`;170 t.is(stdout, `${foobarString}\n`);171});172173test('execa.$.pipe(pipeAndSubprocessOptions)`command`', async t => {174 const {stdout} = await execa('noop-fd.js', ['2', `${foobarString}\n`]).pipe({from: 'stderr', stripFinalNewline: false})`stdin.js`;175 t.is(stdout, `${foobarString}\n`);176});177178test('$.pipe.pipe(pipeAndSubprocessOptions)`command`', async t => {179 const {stdout} = await $`noop-fd.js 2 ${foobarString}\n`180 .pipe({from: 'stderr'})`noop-stdin-fd.js 2`181 .pipe({from: 'stderr', stripFinalNewline: false})`stdin.js`;182 t.is(stdout, `${foobarString}\n`);183});184185test('$.pipe("file", pipeAndSubprocessOptions)', async t => {186 const {stdout} = await $`noop-fd.js 2 ${foobarString}\n`.pipe('stdin.js', {from: 'stderr', stripFinalNewline: false});187 t.is(stdout, `${foobarString}\n`);188});189190test('execa.$.pipe("file", pipeAndSubprocessOptions)', async t => {191 const {stdout} = await execa('noop-fd.js', ['2', `${foobarString}\n`]).pipe('stdin.js', {from: 'stderr', stripFinalNewline: false});192 t.is(stdout, `${foobarString}\n`);193});194195test('$.pipe.pipe("file", pipeAndSubprocessOptions)', async t => {196 const {stdout} = await $`noop-fd.js 2 ${foobarString}\n`197 .pipe({from: 'stderr'})`noop-stdin-fd.js 2`198 .pipe('stdin.js', {from: 'stderr', stripFinalNewline: false});199 t.is(stdout, `${foobarString}\n`);200});201202test('$.pipe(options)(secondOptions)`command`', async t => {203 const {stdout} = await $`noop.js ${foobarString}`.pipe({stripFinalNewline: false})({stripFinalNewline: true})`stdin.js`;204 t.is(stdout, foobarString);205});206207test('execa.$.pipe(options)(secondOptions)`command`', async t => {208 const {stdout} = await execa('noop.js', [foobarString]).pipe({stripFinalNewline: false})({stripFinalNewline: true})`stdin.js`;209 t.is(stdout, foobarString);210});211212test('$.pipe.pipe(options)(secondOptions)`command`', async t => {213 const {stdout} = await $`noop.js ${foobarString}`214 .pipe({})({})`stdin.js`215 .pipe({stripFinalNewline: false})({stripFinalNewline: true})`stdin.js`;216 t.is(stdout, foobarString);217});218219test('$.pipe`command` forces "stdin: pipe"', async t => {220 const {stdout} = await $`noop.js ${foobarString}`.pipe({stdin: 'ignore'})`stdin.js`;221 t.is(stdout, foobarString);222});223224test('execa.pipe("file") forces "stdin: "pipe"', async t => {225 const {stdout} = await execa('noop.js', [foobarString]).pipe('stdin.js', {stdin: 'ignore'});226 t.is(stdout, foobarString);227});228229test('execa.pipe(subprocess) does not force "stdin: pipe"', async t => {230 await t.throwsAsync(231 execa('noop.js', [foobarString]).pipe(execa('stdin.js', {stdin: 'ignore'})),232 {message: /"stdin: 'ignore'" option is incompatible/},233 );234});235236test('$.pipe(options)(subprocess) fails', async t => {237 await t.throwsAsync(238 $`empty.js`.pipe({stdout: 'pipe'})($`empty.js`),239 {message: /Please use \.pipe/},240 );241});242243test('execa.$.pipe(options)(subprocess) fails', async t => {244 await t.throwsAsync(245 execa('empty.js').pipe({stdout: 'pipe'})($`empty.js`),246 {message: /Please use \.pipe/},247 );248});249250test('$.pipe(options)("file") fails', async t => {251 await t.throwsAsync(252 $`empty.js`.pipe({stdout: 'pipe'})('empty.js'),253 {message: /Please use \.pipe/},254 );255});256257test('execa.$.pipe(options)("file") fails', async t => {258 await t.throwsAsync(259 execa('empty.js').pipe({stdout: 'pipe'})('empty.js'),260 {message: /Please use \.pipe/},261 );262});263264const testInvalidPipe = async (t, ...args) => {265 await t.throwsAsync(266 $`empty.js`.pipe(...args),267 {message: /must be a template string/},268 );269};270271test('$.pipe(nonExecaSubprocess) fails', testInvalidPipe, spawn('node', ['--version']));272test('$.pipe(false) fails', testInvalidPipe, false);
added:test/pipe/throw.js+38 added
1import test from 'ava';2import {execa} from '../../index.js';3import {foobarString} from '../helpers/input.js';4import {setFixtureDir} from '../helpers/fixtures-dir.js';5import {assertPipeError} from '../helpers/pipe.js';67setFixtureDir();89test('Destination stream is ended when first argument is invalid', async t => {10 const source = execa('empty.js', {stdout: 'ignore'});11 const destination = execa('stdin.js');12 const pipePromise = source.pipe(destination);1314 await assertPipeError(t, pipePromise, 'option is incompatible');15 await source;16 t.like(await destination, {stdout: ''});17});1819test('Destination stream is ended when first argument is invalid - $', async t => {20 const pipePromise = execa('empty.js', {stdout: 'ignore'}).pipe`stdin.js`;21 await assertPipeError(t, pipePromise, 'option is incompatible');22});2324test('Source stream is aborted when second argument is invalid', async t => {25 const source = execa('noop.js', [foobarString]);26 const pipePromise = source.pipe(false);2728 await assertPipeError(t, pipePromise, 'an Execa subprocess');29 t.like(await source, {stdout: ''});30});3132test('Both arguments might be invalid', async t => {33 const source = execa('empty.js', {stdout: 'ignore'});34 const pipePromise = source.pipe(false);3536 await assertPipeError(t, pipePromise, 'an Execa subprocess');37 t.like(await source, {stdout: undefined});38});
modified:test/pipe/validate.js+212 added-723 removed
1import {PassThrough} from 'node:stream';1import {spawn} from 'node:child_process';3import process from 'node:process';2import {pathToFileURL} from 'node:url';3import test from 'ava';5import {execa} from '../../index.js';6import {setFixtureDir} from '../helpers/fixtures-dir.js';4import {$, execa} from '../../index.js';5import {setFixtureDir, FIXTURES_DIR} from '../helpers/fixtures-dir.js';6import {foobarString} from '../helpers/input.js';8import {fullStdio, getStdio} from '../helpers/stdio.js';9import {getEarlyErrorSubprocess} from '../helpers/early-error.js';78setFixtureDir();913const assertPipeError = async (t, pipePromise, message) => {14 const error = await t.throwsAsync(pipePromise);10test('$.pipe(subprocess)', async t => {11 const {stdout} = await $`noop.js ${foobarString}`.pipe($({stdin: 'pipe'})`stdin.js`);12 t.is(stdout, foobarString);13});1416 t.is(error.command, 'source.pipe(destination)');17 t.is(error.escapedCommand, error.command);15test('execa.$.pipe(subprocess)', async t => {16 const {stdout} = await execa('noop.js', [foobarString]).pipe($({stdin: 'pipe'})`stdin.js`);17 t.is(stdout, foobarString);18});1919 t.is(typeof error.cwd, 'string');20 t.true(error.failed);21 t.false(error.timedOut);22 t.false(error.isCanceled);23 t.false(error.isTerminated);24 t.is(error.exitCode, undefined);25 t.is(error.signal, undefined);26 t.is(error.signalDescription, undefined);27 t.is(error.stdout, undefined);28 t.is(error.stderr, undefined);29 t.is(error.all, undefined);30 t.deepEqual(error.stdio, Array.from({length: error.stdio.length}));31 t.deepEqual(error.pipedFrom, []);20test('$.pipe.pipe(subprocess)', async t => {21 const {stdout} = await $`noop.js ${foobarString}`22 .pipe($({stdin: 'pipe'})`stdin.js`)23 .pipe($({stdin: 'pipe'})`stdin.js`);24 t.is(stdout, foobarString);25});2633 t.true(error.shortMessage.includes(`Command failed: ${error.command}`));34 t.true(error.shortMessage.includes(error.originalMessage));35 t.true(error.message.includes(error.shortMessage));27test('$.pipe`command`', async t => {28 const {stdout} = await $`noop.js ${foobarString}`.pipe`stdin.js`;29 t.is(stdout, foobarString);30});3137 t.true(error.originalMessage.includes(message));38};32test('execa.$.pipe`command`', async t => {33 const {stdout} = await execa('noop.js', [foobarString]).pipe`stdin.js`;34 t.is(stdout, foobarString);35});3640const getMessage = message => Array.isArray(message)41 ? `"${message[0]}: ${message[1]}" option is incompatible`42 : message;37test('$.pipe.pipe`command`', async t => {38 const {stdout} = await $`noop.js ${foobarString}`39 .pipe`stdin.js`40 .pipe`stdin.js`;41 t.is(stdout, foobarString);42});4344const testPipeError = async (t, {45 message,46 sourceOptions = {},47 destinationOptions = {},48 getSource = () => execa('empty.js', sourceOptions),49 getDestination = () => execa('empty.js', destinationOptions),50 isScript = false,51 from,52 to,53}) => {54 const source = getSource();55 const pipePromise = isScript ? source.pipe({from, to})`empty.js` : source.pipe(getDestination(), {from, to});56 await assertPipeError(t, pipePromise, getMessage(message));57};44test('$.pipe("file")', async t => {45 const {stdout} = await $`noop.js ${foobarString}`.pipe('stdin.js');46 t.is(stdout, foobarString);47});4859const testNodeStream = async (t, {60 message,61 sourceOptions = {},62 getSource = () => execa('empty.js', sourceOptions),63 from,64 to,65 writable = to !== undefined,66}) => {67 assertNodeStream({t, message, getSource, from, to, methodName: writable ? 'writable' : 'readable'});68 assertNodeStream({t, message, getSource, from, to, methodName: 'duplex'});69};49test('execa.$.pipe("file")`', async t => {50 const {stdout} = await execa('noop.js', [foobarString]).pipe('stdin.js');51 t.is(stdout, foobarString);52});5371const assertNodeStream = ({t, message, getSource, from, to, methodName}) => {72 const error = t.throws(() => {73 getSource()[methodName]({from, to});74 });75 t.true(error.message.includes(getMessage(message)));76};54test('$.pipe.pipe("file")', async t => {55 const {stdout} = await $`noop.js ${foobarString}`56 .pipe`stdin.js`57 .pipe('stdin.js');58 t.is(stdout, foobarString);59});6078const testIterable = async (t, {79 message,80 sourceOptions = {},81 getSource = () => execa('empty.js', sourceOptions),82 from,83}) => {84 const error = t.throws(() => {85 getSource().iterable({from});86 });87 t.true(error.message.includes(getMessage(message)));88};61test('execa.$.pipe(fileUrl)`', async t => {62 const {stdout} = await execa('noop.js', [foobarString]).pipe(pathToFileURL(`${FIXTURES_DIR}/stdin.js`));63 t.is(stdout, foobarString);64});6590test('Must set "all" option to "true" to use .pipe("all")', testPipeError, {91 from: 'all',92 message: '"all" option must be true',66test('$.pipe("file", args, options)', async t => {67 const {stdout} = await $`noop.js ${foobarString}`.pipe('node', ['stdin.js'], {cwd: FIXTURES_DIR});68 t.is(stdout, foobarString);69});94test('Must set "all" option to "true" to use .duplex("all")', testNodeStream, {95 from: 'all',96 message: '"all" option must be true',7071test('execa.$.pipe("file", args, options)`', async t => {72 const {stdout} = await execa('noop.js', [foobarString]).pipe('node', ['stdin.js'], {cwd: FIXTURES_DIR});73 t.is(stdout, foobarString);74});98test('Must set "all" option to "true" to use .iterable("all")', testIterable, {99 from: 'all',100 message: '"all" option must be true',7576test('$.pipe.pipe("file", args, options)', async t => {77 const {stdout} = await $`noop.js ${foobarString}`78 .pipe`stdin.js`79 .pipe('node', ['stdin.js'], {cwd: FIXTURES_DIR});80 t.is(stdout, foobarString);81});102test('.pipe() cannot pipe to non-subprocesses', testPipeError, {103 getDestination: () => new PassThrough(),104 message: 'an Execa subprocess',8283test('$.pipe(subprocess, pipeOptions)', async t => {84 const {stdout} = await $`noop-fd.js 2 ${foobarString}`.pipe($({stdin: 'pipe'})`stdin.js`, {from: 'stderr'});85 t.is(stdout, foobarString);86});106test('.pipe() cannot pipe to non-Execa subprocesses', testPipeError, {107 getDestination: () => spawn('node', ['--version']),108 message: 'an Execa subprocess',8788test('execa.$.pipe(subprocess, pipeOptions)', async t => {89 const {stdout} = await execa('noop-fd.js', ['2', foobarString]).pipe($({stdin: 'pipe'})`stdin.js`, {from: 'stderr'});90 t.is(stdout, foobarString);91});110test('.pipe() "from" option cannot be "stdin"', testPipeError, {111 from: 'stdin',112 message: '"from" must not be',9293test('$.pipe.pipe(subprocess, pipeOptions)', async t => {94 const {stdout} = await $`noop-fd.js 2 ${foobarString}`95 .pipe($({stdin: 'pipe'})`noop-stdin-fd.js 2`, {from: 'stderr'})96 .pipe($({stdin: 'pipe'})`stdin.js`, {from: 'stderr'});97 t.is(stdout, foobarString);98});114test('.duplex() "from" option cannot be "stdin"', testNodeStream, {115 from: 'stdin',116 message: '"from" must not be',99100test('$.pipe(pipeOptions)`command`', async t => {101 const {stdout} = await $`noop-fd.js 2 ${foobarString}`.pipe({from: 'stderr'})`stdin.js`;102 t.is(stdout, foobarString);103});118test('.iterable() "from" option cannot be "stdin"', testIterable, {119 from: 'stdin',120 message: '"from" must not be',104105test('execa.$.pipe(pipeOptions)`command`', async t => {106 const {stdout} = await execa('noop-fd.js', ['2', foobarString]).pipe({from: 'stderr'})`stdin.js`;107 t.is(stdout, foobarString);108});122test('$.pipe() "from" option cannot be "stdin"', testPipeError, {123 from: 'stdin',124 isScript: true,125 message: '"from" must not be',109110test('$.pipe.pipe(pipeOptions)`command`', async t => {111 const {stdout} = await $`noop-fd.js 2 ${foobarString}`112 .pipe({from: 'stderr'})`noop-stdin-fd.js 2`113 .pipe({from: 'stderr'})`stdin.js`;114 t.is(stdout, foobarString);115});127test('.pipe() "to" option cannot be "stdout"', testPipeError, {128 to: 'stdout',129 message: '"to" must not be',116117test('$.pipe("file", pipeOptions)', async t => {118 const {stdout} = await $`noop-fd.js 2 ${foobarString}`.pipe('stdin.js', {from: 'stderr'});119 t.is(stdout, foobarString);120});131test('.duplex() "to" option cannot be "stdout"', testNodeStream, {132 to: 'stdout',133 message: '"to" must not be',121122test('execa.$.pipe("file", pipeOptions)', async t => {123 const {stdout} = await execa('noop-fd.js', ['2', foobarString]).pipe('stdin.js', {from: 'stderr'});124 t.is(stdout, foobarString);125});135test('$.pipe() "to" option cannot be "stdout"', testPipeError, {136 to: 'stdout',137 isScript: true,138 message: '"to" must not be',126127test('$.pipe.pipe("file", pipeOptions)', async t => {128 const {stdout} = await $`noop-fd.js 2 ${foobarString}`129 .pipe({from: 'stderr'})`noop-stdin-fd.js 2`130 .pipe('stdin.js', {from: 'stderr'});131 t.is(stdout, foobarString);132});140test('.pipe() "from" option cannot be any string', testPipeError, {141 from: 'other',142 message: 'must be "stdout", "stderr", "all"',133134test('$.pipe(options)`command`', async t => {135 const {stdout} = await $`noop.js ${foobarString}`.pipe({stripFinalNewline: false})`stdin.js`;136 t.is(stdout, `${foobarString}\n`);137});144test('.duplex() "from" option cannot be any string', testNodeStream, {145 from: 'other',146 message: 'must be "stdout", "stderr", "all"',138139test('execa.$.pipe(options)`command`', async t => {140 const {stdout} = await execa('noop.js', [foobarString]).pipe({stripFinalNewline: false})`stdin.js`;141 t.is(stdout, `${foobarString}\n`);142});148test('.iterable() "from" option cannot be any string', testIterable, {149 from: 'other',150 message: 'must be "stdout", "stderr", "all"',143144test('$.pipe.pipe(options)`command`', async t => {145 const {stdout} = await $`noop.js ${foobarString}`146 .pipe({})`stdin.js`147 .pipe({stripFinalNewline: false})`stdin.js`;148 t.is(stdout, `${foobarString}\n`);149});152test('.pipe() "to" option cannot be any string', testPipeError, {153 to: 'other',154 message: 'must be "stdin"',150151test('$.pipe("file", options)', async t => {152 const {stdout} = await $`noop.js ${foobarString}`.pipe('stdin.js', {stripFinalNewline: false});153 t.is(stdout, `${foobarString}\n`);154});156test('.duplex() "to" option cannot be any string', testNodeStream, {157 to: 'other',158 message: 'must be "stdin"',155156test('execa.$.pipe("file", options)', async t => {157 const {stdout} = await execa('noop.js', [foobarString]).pipe('stdin.js', {stripFinalNewline: false});158 t.is(stdout, `${foobarString}\n`);159});160test('.pipe() "from" option cannot be a number without "fd"', testPipeError, {161 from: '1',162 message: 'must be "stdout", "stderr", "all"',160161test('$.pipe.pipe("file", options)', async t => {162 const {stdout} = await $`noop.js ${foobarString}`163 .pipe({})`stdin.js`164 .pipe('stdin.js', {stripFinalNewline: false});165 t.is(stdout, `${foobarString}\n`);166});164test('.duplex() "from" option cannot be a number without "fd"', testNodeStream, {165 from: '1',166 message: 'must be "stdout", "stderr", "all"',167168test('$.pipe(pipeAndSubprocessOptions)`command`', async t => {169 const {stdout} = await $`noop-fd.js 2 ${foobarString}\n`.pipe({from: 'stderr', stripFinalNewline: false})`stdin.js`;170 t.is(stdout, `${foobarString}\n`);171});168test('.iterable() "from" option cannot be a number without "fd"', testIterable, {169 from: '1',170 message: 'must be "stdout", "stderr", "all"',172173test('execa.$.pipe(pipeAndSubprocessOptions)`command`', async t => {174 const {stdout} = await execa('noop-fd.js', ['2', `${foobarString}\n`]).pipe({from: 'stderr', stripFinalNewline: false})`stdin.js`;175 t.is(stdout, `${foobarString}\n`);176});172test('.pipe() "to" option cannot be a number without "fd"', testPipeError, {173 to: '0',174 message: 'must be "stdin"',177178test('$.pipe.pipe(pipeAndSubprocessOptions)`command`', async t => {179 const {stdout} = await $`noop-fd.js 2 ${foobarString}\n`180 .pipe({from: 'stderr'})`noop-stdin-fd.js 2`181 .pipe({from: 'stderr', stripFinalNewline: false})`stdin.js`;182 t.is(stdout, `${foobarString}\n`);183});176test('.duplex() "to" option cannot be a number without "fd"', testNodeStream, {177 to: '0',178 message: 'must be "stdin"',184185test('$.pipe("file", pipeAndSubprocessOptions)', async t => {186 const {stdout} = await $`noop-fd.js 2 ${foobarString}\n`.pipe('stdin.js', {from: 'stderr', stripFinalNewline: false});187 t.is(stdout, `${foobarString}\n`);188});180test('.pipe() "from" option cannot be just "fd"', testPipeError, {181 from: 'fd',182 message: 'must be "stdout", "stderr", "all"',189190test('execa.$.pipe("file", pipeAndSubprocessOptions)', async t => {191 const {stdout} = await execa('noop-fd.js', ['2', `${foobarString}\n`]).pipe('stdin.js', {from: 'stderr', stripFinalNewline: false});192 t.is(stdout, `${foobarString}\n`);193});184test('.duplex() "from" option cannot be just "fd"', testNodeStream, {185 from: 'fd',186 message: 'must be "stdout", "stderr", "all"',194195test('$.pipe.pipe("file", pipeAndSubprocessOptions)', async t => {196 const {stdout} = await $`noop-fd.js 2 ${foobarString}\n`197 .pipe({from: 'stderr'})`noop-stdin-fd.js 2`198 .pipe('stdin.js', {from: 'stderr', stripFinalNewline: false});199 t.is(stdout, `${foobarString}\n`);200});188test('.iterable() "from" option cannot be just "fd"', testIterable, {189 from: 'fd',190 message: 'must be "stdout", "stderr", "all"',201202test('$.pipe(options)(secondOptions)`command`', async t => {203 const {stdout} = await $`noop.js ${foobarString}`.pipe({stripFinalNewline: false})({stripFinalNewline: true})`stdin.js`;204 t.is(stdout, foobarString);205});192test('.pipe() "to" option cannot be just "fd"', testPipeError, {193 to: 'fd',194 message: 'must be "stdin"',206207test('execa.$.pipe(options)(secondOptions)`command`', async t => {208 const {stdout} = await execa('noop.js', [foobarString]).pipe({stripFinalNewline: false})({stripFinalNewline: true})`stdin.js`;209 t.is(stdout, foobarString);210});196test('.duplex() "to" option cannot be just "fd"', testNodeStream, {197 to: 'fd',198 message: 'must be "stdin"',211212test('$.pipe.pipe(options)(secondOptions)`command`', async t => {213 const {stdout} = await $`noop.js ${foobarString}`214 .pipe({})({})`stdin.js`215 .pipe({stripFinalNewline: false})({stripFinalNewline: true})`stdin.js`;216 t.is(stdout, foobarString);217});200test('.pipe() "from" option cannot be a float', testPipeError, {201 from: 'fd1.5',202 message: 'must be "stdout", "stderr", "all"',203});204test('.duplex() "from" option cannot be a float', testNodeStream, {205 from: 'fd1.5',206 message: 'must be "stdout", "stderr", "all"',207});208test('.iterable() "from" option cannot be a float', testIterable, {209 from: 'fd1.5',210 message: 'must be "stdout", "stderr", "all"',211});212test('.pipe() "to" option cannot be a float', testPipeError, {213 to: 'fd1.5',214 message: 'must be "stdin"',215});216test('.duplex() "to" option cannot be a float', testNodeStream, {217 to: 'fd1.5',218 message: 'must be "stdin"',219});220test('.pipe() "from" option cannot be a negative number', testPipeError, {221 from: 'fd-1',222 message: 'must be "stdout", "stderr", "all"',223});224test('.duplex() "from" option cannot be a negative number', testNodeStream, {225 from: 'fd-1',226 message: 'must be "stdout", "stderr", "all"',227});228test('.iterable() "from" option cannot be a negative number', testIterable, {229 from: 'fd-1',230 message: 'must be "stdout", "stderr", "all"',231});232test('.pipe() "to" option cannot be a negative number', testPipeError, {233 to: 'fd-1',234 message: 'must be "stdin"',235});236test('.duplex() "to" option cannot be a negative number', testNodeStream, {237 to: 'fd-1',238 message: 'must be "stdin"',239});240test('.pipe() "from" option cannot be a non-existing file descriptor', testPipeError, {241 from: 'fd3',242 message: 'file descriptor does not exist',243});244test('.duplex() "from" cannot be a non-existing file descriptor', testNodeStream, {245 from: 'fd3',246 message: 'file descriptor does not exist',247});248test('.iterable() "from" cannot be a non-existing file descriptor', testIterable, {249 from: 'fd3',250 message: 'file descriptor does not exist',251});252test('.pipe() "to" option cannot be a non-existing file descriptor', testPipeError, {253 to: 'fd3',254 message: 'file descriptor does not exist',255});256test('.duplex() "to" cannot be a non-existing file descriptor', testNodeStream, {257 to: 'fd3',258 message: 'file descriptor does not exist',259});260test('.pipe() "from" option cannot be an input file descriptor', testPipeError, {261 sourceOptions: getStdio(3, new Uint8Array()),262 from: 'fd3',263 message: 'must be a readable stream',264});265test('.duplex() "from" option cannot be an input file descriptor', testNodeStream, {266 sourceOptions: getStdio(3, new Uint8Array()),267 from: 'fd3',268 message: 'must be a readable stream',269});270test('.iterable() "from" option cannot be an input file descriptor', testIterable, {271 sourceOptions: getStdio(3, new Uint8Array()),272 from: 'fd3',273 message: 'must be a readable stream',274});275test('.pipe() "to" option cannot be an output file descriptor', testPipeError, {276 destinationOptions: fullStdio,277 to: 'fd3',278 message: 'must be a writable stream',279});280test('.duplex() "to" option cannot be an output file descriptor', testNodeStream, {281 sourceOptions: fullStdio,282 to: 'fd3',283 message: 'must be a writable stream',284});285test('.pipe() "to" option cannot be "all"', testPipeError, {286 destinationOptions: fullStdio,287 to: 'all',288 message: 'must be a writable stream',289});290test('.duplex() "to" option cannot be "all"', testNodeStream, {291 sourceOptions: fullStdio,292 to: 'all',293 message: 'must be a writable stream',294});295test('Cannot set "stdout" option to "ignore" to use .pipe()', testPipeError, {296 sourceOptions: {stdout: 'ignore'},297 message: ['stdout', '\'ignore\''],298});299test('Cannot set "stdout" option to "ignore" to use .duplex()', testNodeStream, {300 sourceOptions: {stdout: 'ignore'},301 message: ['stdout', '\'ignore\''],302});303test('Cannot set "stdout" option to "ignore" to use .iterable()', testIterable, {304 sourceOptions: {stdout: 'ignore'},305 message: ['stdout', '\'ignore\''],306});307test('Cannot set "stdin" option to "ignore" to use .pipe()', testPipeError, {308 destinationOptions: {stdin: 'ignore'},309 message: ['stdin', '\'ignore\''],310});311test('Cannot set "stdin" option to "ignore" to use .duplex()', testNodeStream, {312 sourceOptions: {stdin: 'ignore'},313 message: ['stdin', '\'ignore\''],314 writable: true,315});316test('Cannot set "stdout" option to "ignore" to use .pipe(1)', testPipeError, {317 sourceOptions: {stdout: 'ignore'},318 from: 'fd1',319 message: ['stdout', '\'ignore\''],320});321test('Cannot set "stdout" option to "ignore" to use .duplex(1)', testNodeStream, {322 sourceOptions: {stdout: 'ignore'},323 from: 'fd1',324 message: ['stdout', '\'ignore\''],325});326test('Cannot set "stdout" option to "ignore" to use .iterable(1)', testIterable, {327 sourceOptions: {stdout: 'ignore'},328 from: 'fd1',329 message: ['stdout', '\'ignore\''],330});331test('Cannot set "stdin" option to "ignore" to use .pipe(0)', testPipeError, {332 destinationOptions: {stdin: 'ignore'},333 message: ['stdin', '\'ignore\''],334 to: 'fd0',335});336test('Cannot set "stdin" option to "ignore" to use .duplex(0)', testNodeStream, {337 sourceOptions: {stdin: 'ignore'},338 message: ['stdin', '\'ignore\''],339 to: 'fd0',340});341test('Cannot set "stdout" option to "ignore" to use .pipe("stdout")', testPipeError, {342 sourceOptions: {stdout: 'ignore'},343 from: 'stdout',344 message: ['stdout', '\'ignore\''],345});346test('Cannot set "stdout" option to "ignore" to use .duplex("stdout")', testNodeStream, {347 sourceOptions: {stdout: 'ignore'},348 from: 'stdout',349 message: ['stdout', '\'ignore\''],350});351test('Cannot set "stdout" option to "ignore" to use .iterable("stdout")', testIterable, {352 sourceOptions: {stdout: 'ignore'},353 from: 'stdout',354 message: ['stdout', '\'ignore\''],355});356test('Cannot set "stdin" option to "ignore" to use .pipe("stdin")', testPipeError, {357 destinationOptions: {stdin: 'ignore'},358 message: ['stdin', '\'ignore\''],359 to: 'stdin',360});361test('Cannot set "stdin" option to "ignore" to use .duplex("stdin")', testNodeStream, {362 sourceOptions: {stdin: 'ignore'},363 message: ['stdin', '\'ignore\''],364 to: 'stdin',365});366test('Cannot set "stdout" + "stderr" option to "ignore" to use .pipe()', testPipeError, {367 sourceOptions: {stdout: 'ignore', stderr: 'ignore'},368 message: ['stdout', '\'ignore\''],369});370test('Cannot set "stdout" + "stderr" option to "ignore" to use .duplex()', testNodeStream, {371 sourceOptions: {stdout: 'ignore', stderr: 'ignore'},372 message: ['stdout', '\'ignore\''],373});374test('Cannot set "stdout" + "stderr" option to "ignore" to use .iterable()', testIterable, {375 sourceOptions: {stdout: 'ignore', stderr: 'ignore'},376 message: ['stdout', '\'ignore\''],377});378test('Cannot set "stdout" + "stderr" option to "ignore" to use .pipe(1)', testPipeError, {379 sourceOptions: {stdout: 'ignore', stderr: 'ignore'},380 from: 'fd1',381 message: ['stdout', '\'ignore\''],382});383test('Cannot set "stdout" + "stderr" option to "ignore" to use .duplex(1)', testNodeStream, {384 sourceOptions: {stdout: 'ignore', stderr: 'ignore'},385 from: 'fd1',386 message: ['stdout', '\'ignore\''],387});388test('Cannot set "stdout" + "stderr" option to "ignore" to use .iterable(1)', testIterable, {389 sourceOptions: {stdout: 'ignore', stderr: 'ignore'},390 from: 'fd1',391 message: ['stdout', '\'ignore\''],392});393test('Cannot set "stdout" + "stderr" option to "ignore" to use .pipe("stdout")', testPipeError, {394 sourceOptions: {stdout: 'ignore', stderr: 'ignore'},395 from: 'stdout',396 message: ['stdout', '\'ignore\''],397});398test('Cannot set "stdout" + "stderr" option to "ignore" to use .duplex("stdout")', testNodeStream, {399 sourceOptions: {stdout: 'ignore', stderr: 'ignore'},400 from: 'stdout',401 message: ['stdout', '\'ignore\''],402});403test('Cannot set "stdout" + "stderr" option to "ignore" to use .iterable("stdout")', testIterable, {404 sourceOptions: {stdout: 'ignore', stderr: 'ignore'},405 from: 'stdout',406 message: ['stdout', '\'ignore\''],407});408test('Cannot set "stdio[1]" option to "ignore" to use .pipe()', testPipeError, {409 sourceOptions: {stdio: ['pipe', 'ignore', 'pipe']},410 message: ['stdio[1]', '\'ignore\''],411});412test('Cannot set "stdio[1]" option to "ignore" to use .duplex()', testNodeStream, {413 sourceOptions: {stdio: ['pipe', 'ignore', 'pipe']},414 message: ['stdio[1]', '\'ignore\''],415});416test('Cannot set "stdio[1]" option to "ignore" to use .iterable()', testIterable, {417 sourceOptions: {stdio: ['pipe', 'ignore', 'pipe']},418 message: ['stdio[1]', '\'ignore\''],419});420test('Cannot set "stdio[0]" option to "ignore" to use .pipe()', testPipeError, {421 destinationOptions: {stdio: ['ignore', 'pipe', 'pipe']},422 message: ['stdio[0]', '\'ignore\''],423});424test('Cannot set "stdio[0]" option to "ignore" to use .duplex()', testNodeStream, {425 sourceOptions: {stdio: ['ignore', 'pipe', 'pipe']},426 message: ['stdio[0]', '\'ignore\''],427 writable: true,428});429test('Cannot set "stdio[1]" option to "ignore" to use .pipe(1)', testPipeError, {430 sourceOptions: {stdio: ['pipe', 'ignore', 'pipe']},431 from: 'fd1',432 message: ['stdio[1]', '\'ignore\''],433});434test('Cannot set "stdio[1]" option to "ignore" to use .duplex(1)', testNodeStream, {435 sourceOptions: {stdio: ['pipe', 'ignore', 'pipe']},436 from: 'fd1',437 message: ['stdio[1]', '\'ignore\''],438});439test('Cannot set "stdio[1]" option to "ignore" to use .iterable(1)', testIterable, {440 sourceOptions: {stdio: ['pipe', 'ignore', 'pipe']},441 from: 'fd1',442 message: ['stdio[1]', '\'ignore\''],443});444test('Cannot set "stdio[0]" option to "ignore" to use .pipe(0)', testPipeError, {445 destinationOptions: {stdio: ['ignore', 'pipe', 'pipe']},446 message: ['stdio[0]', '\'ignore\''],447 to: 'fd0',448});449test('Cannot set "stdio[0]" option to "ignore" to use .duplex(0)', testNodeStream, {450 sourceOptions: {stdio: ['ignore', 'pipe', 'pipe']},451 message: ['stdio[0]', '\'ignore\''],452 to: 'fd0',453});454test('Cannot set "stdio[1]" option to "ignore" to use .pipe("stdout")', testPipeError, {455 sourceOptions: {stdio: ['pipe', 'ignore', 'pipe']},456 from: 'stdout',457 message: ['stdio[1]', '\'ignore\''],458});459test('Cannot set "stdio[1]" option to "ignore" to use .duplex("stdout")', testNodeStream, {460 sourceOptions: {stdio: ['pipe', 'ignore', 'pipe']},461 from: 'stdout',462 message: ['stdio[1]', '\'ignore\''],463});464test('Cannot set "stdio[1]" option to "ignore" to use .iterable("stdout")', testIterable, {465 sourceOptions: {stdio: ['pipe', 'ignore', 'pipe']},466 from: 'stdout',467 message: ['stdio[1]', '\'ignore\''],468});469test('Cannot set "stdio[0]" option to "ignore" to use .pipe("stdin")', testPipeError, {470 destinationOptions: {stdio: ['ignore', 'pipe', 'pipe']},471 message: ['stdio[0]', '\'ignore\''],472 to: 'stdin',473});474test('Cannot set "stdio[0]" option to "ignore" to use .duplex("stdin")', testNodeStream, {475 sourceOptions: {stdio: ['ignore', 'pipe', 'pipe']},476 message: ['stdio[0]', '\'ignore\''],477 to: 'stdin',478});479test('Cannot set "stderr" option to "ignore" to use .pipe(2)', testPipeError, {480 sourceOptions: {stderr: 'ignore'},481 from: 'fd2',482 message: ['stderr', '\'ignore\''],483});484test('Cannot set "stderr" option to "ignore" to use .duplex(2)', testNodeStream, {485 sourceOptions: {stderr: 'ignore'},486 from: 'fd2',487 message: ['stderr', '\'ignore\''],488});489test('Cannot set "stderr" option to "ignore" to use .iterable(2)', testIterable, {490 sourceOptions: {stderr: 'ignore'},491 from: 'fd2',492 message: ['stderr', '\'ignore\''],493});494test('Cannot set "stderr" option to "ignore" to use .pipe("stderr")', testPipeError, {495 sourceOptions: {stderr: 'ignore'},496 from: 'stderr',497 message: ['stderr', '\'ignore\''],498});499test('Cannot set "stderr" option to "ignore" to use .duplex("stderr")', testNodeStream, {500 sourceOptions: {stderr: 'ignore'},501 from: 'stderr',502 message: ['stderr', '\'ignore\''],503});504test('Cannot set "stderr" option to "ignore" to use .iterable("stderr")', testIterable, {505 sourceOptions: {stderr: 'ignore'},506 from: 'stderr',507 message: ['stderr', '\'ignore\''],508});509test('Cannot set "stdout" + "stderr" option to "ignore" to use .pipe(2)', testPipeError, {510 sourceOptions: {stdout: 'ignore', stderr: 'ignore'},511 from: 'fd2',512 message: ['stderr', '\'ignore\''],513});514test('Cannot set "stdout" + "stderr" option to "ignore" to use .duplex(2)', testNodeStream, {515 sourceOptions: {stdout: 'ignore', stderr: 'ignore'},516 from: 'fd2',517 message: ['stderr', '\'ignore\''],518});519test('Cannot set "stdout" + "stderr" option to "ignore" to use .iterable(2)', testIterable, {520 sourceOptions: {stdout: 'ignore', stderr: 'ignore'},521 from: 'fd2',522 message: ['stderr', '\'ignore\''],523});524test('Cannot set "stdout" + "stderr" option to "ignore" to use .pipe("stderr")', testPipeError, {525 sourceOptions: {stdout: 'ignore', stderr: 'ignore'},526 from: 'stderr',527 message: ['stderr', '\'ignore\''],528});529test('Cannot set "stdout" + "stderr" option to "ignore" to use .duplex("stderr")', testNodeStream, {530 sourceOptions: {stdout: 'ignore', stderr: 'ignore'},531 from: 'stderr',532 message: ['stderr', '\'ignore\''],533});534test('Cannot set "stdout" + "stderr" option to "ignore" to use .iterable("stderr")', testIterable, {535 sourceOptions: {stdout: 'ignore', stderr: 'ignore'},536 from: 'stderr',537 message: ['stderr', '\'ignore\''],538});539test('Cannot set "stdio[2]" option to "ignore" to use .pipe(2)', testPipeError, {540 sourceOptions: {stdio: ['pipe', 'pipe', 'ignore']},541 from: 'fd2',542 message: ['stdio[2]', '\'ignore\''],543});544test('Cannot set "stdio[2]" option to "ignore" to use .duplex(2)', testNodeStream, {545 sourceOptions: {stdio: ['pipe', 'pipe', 'ignore']},546 from: 'fd2',547 message: ['stdio[2]', '\'ignore\''],548});549test('Cannot set "stdio[2]" option to "ignore" to use .iterable(2)', testIterable, {550 sourceOptions: {stdio: ['pipe', 'pipe', 'ignore']},551 from: 'fd2',552 message: ['stdio[2]', '\'ignore\''],553});554test('Cannot set "stdio[2]" option to "ignore" to use .pipe("stderr")', testPipeError, {555 sourceOptions: {stdio: ['pipe', 'pipe', 'ignore']},556 from: 'stderr',557 message: ['stdio[2]', '\'ignore\''],558});559test('Cannot set "stdio[2]" option to "ignore" to use .duplex("stderr")', testNodeStream, {560 sourceOptions: {stdio: ['pipe', 'pipe', 'ignore']},561 from: 'stderr',562 message: ['stdio[2]', '\'ignore\''],563});564test('Cannot set "stdio[2]" option to "ignore" to use .iterable("stderr")', testIterable, {565 sourceOptions: {stdio: ['pipe', 'pipe', 'ignore']},566 from: 'stderr',567 message: ['stdio[2]', '\'ignore\''],568});569test('Cannot set "stdio[3]" option to "ignore" to use .pipe(3)', testPipeError, {570 sourceOptions: getStdio(3, 'ignore'),571 from: 'fd3',572 message: ['stdio[3]', '\'ignore\''],573});574test('Cannot set "stdio[3]" option to "ignore" to use .duplex(3)', testNodeStream, {575 sourceOptions: getStdio(3, 'ignore'),576 from: 'fd3',577 message: ['stdio[3]', '\'ignore\''],578});579test('Cannot set "stdio[3]" option to "ignore" to use .iterable(3)', testIterable, {580 sourceOptions: getStdio(3, 'ignore'),581 from: 'fd3',582 message: ['stdio[3]', '\'ignore\''],583});584test('Cannot set "stdout" + "stderr" option to "ignore" to use .pipe("all")', testPipeError, {585 sourceOptions: {stdout: 'ignore', stderr: 'ignore', all: true},586 from: 'all',587 message: ['stdout', '\'ignore\''],588});589test('Cannot set "stdout" + "stderr" option to "ignore" to use .duplex("all")', testNodeStream, {590 sourceOptions: {stdout: 'ignore', stderr: 'ignore', all: true},591 from: 'all',592 message: ['stdout', '\'ignore\''],593});594test('Cannot set "stdout" + "stderr" option to "ignore" to use .iterable("all")', testIterable, {595 sourceOptions: {stdout: 'ignore', stderr: 'ignore', all: true},596 from: 'all',597 message: ['stdout', '\'ignore\''],598});599test('Cannot set "stdio[1]" + "stdio[2]" option to "ignore" to use .pipe("all")', testPipeError, {600 sourceOptions: {stdio: ['pipe', 'ignore', 'ignore'], all: true},601 from: 'all',602 message: ['stdio[1]', '\'ignore\''],603});604test('Cannot set "stdio[1]" + "stdio[2]" option to "ignore" to use .duplex("all")', testNodeStream, {605 sourceOptions: {stdio: ['pipe', 'ignore', 'ignore'], all: true},606 from: 'all',607 message: ['stdio[1]', '\'ignore\''],608});609test('Cannot set "stdio[1]" + "stdio[2]" option to "ignore" to use .iterable("all")', testIterable, {610 sourceOptions: {stdio: ['pipe', 'ignore', 'ignore'], all: true},611 from: 'all',612 message: ['stdio[1]', '\'ignore\''],613});614test('Cannot set "stdout" option to "inherit" to use .pipe()', testPipeError, {615 sourceOptions: {stdout: 'inherit'},616 message: ['stdout', '\'inherit\''],617});618test('Cannot set "stdout" option to "inherit" to use .duplex()', testNodeStream, {619 sourceOptions: {stdout: 'inherit'},620 message: ['stdout', '\'inherit\''],621});622test('Cannot set "stdout" option to "inherit" to use .iterable()', testIterable, {623 sourceOptions: {stdout: 'inherit'},624 message: ['stdout', '\'inherit\''],625});626test('Cannot set "stdin" option to "inherit" to use .pipe()', testPipeError, {627 destinationOptions: {stdin: 'inherit'},628 message: ['stdin', '\'inherit\''],629});630test('Cannot set "stdin" option to "inherit" to use .duplex()', testNodeStream, {631 sourceOptions: {stdin: 'inherit'},632 message: ['stdin', '\'inherit\''],633 writable: true,634});635test('Cannot set "stdout" option to "ipc" to use .pipe()', testPipeError, {636 sourceOptions: {stdout: 'ipc'},637 message: ['stdout', '\'ipc\''],638});639test('Cannot set "stdout" option to "ipc" to use .duplex()', testNodeStream, {640 sourceOptions: {stdout: 'ipc'},641 message: ['stdout', '\'ipc\''],642});643test('Cannot set "stdout" option to "ipc" to use .iterable()', testIterable, {644 sourceOptions: {stdout: 'ipc'},645 message: ['stdout', '\'ipc\''],646});647test('Cannot set "stdin" option to "ipc" to use .pipe()', testPipeError, {648 destinationOptions: {stdin: 'ipc'},649 message: ['stdin', '\'ipc\''],650});651test('Cannot set "stdin" option to "ipc" to use .duplex()', testNodeStream, {652 sourceOptions: {stdin: 'ipc'},653 message: ['stdin', '\'ipc\''],654 writable: true,655});656test('Cannot set "stdout" option to file descriptors to use .pipe()', testPipeError, {657 sourceOptions: {stdout: 1},658 message: ['stdout', '1'],659});660test('Cannot set "stdout" option to file descriptors to use .duplex()', testNodeStream, {661 sourceOptions: {stdout: 1},662 message: ['stdout', '1'],663});664test('Cannot set "stdout" option to file descriptors to use .iterable()', testIterable, {665 sourceOptions: {stdout: 1},666 message: ['stdout', '1'],667});668test('Cannot set "stdin" option to file descriptors to use .pipe()', testPipeError, {669 destinationOptions: {stdin: 0},670 message: ['stdin', '0'],671});672test('Cannot set "stdin" option to file descriptors to use .duplex()', testNodeStream, {673 sourceOptions: {stdin: 0},674 message: ['stdin', '0'],675 writable: true,676});677test('Cannot set "stdout" option to Node.js streams to use .pipe()', testPipeError, {678 sourceOptions: {stdout: process.stdout},679 message: ['stdout', 'Stream'],680});681test('Cannot set "stdout" option to Node.js streams to use .duplex()', testNodeStream, {682 sourceOptions: {stdout: process.stdout},683 message: ['stdout', 'Stream'],684});685test('Cannot set "stdout" option to Node.js streams to use .iterable()', testIterable, {686 sourceOptions: {stdout: process.stdout},687 message: ['stdout', 'Stream'],688});689test('Cannot set "stdin" option to Node.js streams to use .pipe()', testPipeError, {690 destinationOptions: {stdin: process.stdin},691 message: ['stdin', 'Stream'],692});693test('Cannot set "stdin" option to Node.js streams to use .duplex()', testNodeStream, {694 sourceOptions: {stdin: process.stdin},695 message: ['stdin', 'Stream'],696 writable: true,697});698test('Cannot set "stdio[3]" option to Node.js Writable streams to use .pipe()', testPipeError, {699 sourceOptions: getStdio(3, process.stdout),700 message: ['stdio[3]', 'Stream'],701 from: 'fd3',702});703test('Cannot set "stdio[3]" option to Node.js Writable streams to use .duplex()', testNodeStream, {704 sourceOptions: getStdio(3, process.stdout),705 message: ['stdio[3]', 'Stream'],706 from: 'fd3',707});708test('Cannot set "stdio[3]" option to Node.js Writable streams to use .iterable()', testIterable, {709 sourceOptions: getStdio(3, process.stdout),710 message: ['stdio[3]', 'Stream'],711 from: 'fd3',712});713test('Cannot set "stdio[3]" option to Node.js Readable streams to use .pipe()', testPipeError, {714 destinationOptions: getStdio(3, process.stdin),715 message: ['stdio[3]', 'Stream'],716 to: 'fd3',717});718test('Cannot set "stdio[3]" option to Node.js Readable streams to use .duplex()', testNodeStream, {719 sourceOptions: getStdio(3, process.stdin),720 message: ['stdio[3]', 'Stream'],721 to: 'fd3',722});218724test('Destination stream is ended when first argument is invalid', async t => {725 const source = execa('empty.js', {stdout: 'ignore'});726 const destination = execa('stdin.js');727 const pipePromise = source.pipe(destination);728729 await assertPipeError(t, pipePromise, 'option is incompatible');730 await source;731 t.like(await destination, {stdout: ''});219test('$.pipe`command` forces "stdin: pipe"', async t => {220 const {stdout} = await $`noop.js ${foobarString}`.pipe({stdin: 'ignore'})`stdin.js`;221 t.is(stdout, foobarString);222});223734test('Destination stream is ended when first argument is invalid - $', async t => {735 const pipePromise = execa('empty.js', {stdout: 'ignore'}).pipe`stdin.js`;736 await assertPipeError(t, pipePromise, 'option is incompatible');224test('execa.pipe("file") forces "stdin: "pipe"', async t => {225 const {stdout} = await execa('noop.js', [foobarString]).pipe('stdin.js', {stdin: 'ignore'});226 t.is(stdout, foobarString);227});228739test('Source stream is aborted when second argument is invalid', async t => {740 const source = execa('noop.js', [foobarString]);741 const pipePromise = source.pipe(false);742743 await assertPipeError(t, pipePromise, 'an Execa subprocess');744 t.like(await source, {stdout: ''});229test('execa.pipe(subprocess) does not force "stdin: pipe"', async t => {230 await t.throwsAsync(231 execa('noop.js', [foobarString]).pipe(execa('stdin.js', {stdin: 'ignore'})),232 {message: /"stdin: 'ignore'" option is incompatible/},233 );234});235747test('Both arguments might be invalid', async t => {748 const source = execa('empty.js', {stdout: 'ignore'});749 const pipePromise = source.pipe(false);750751 await assertPipeError(t, pipePromise, 'an Execa subprocess');752 t.like(await source, {stdout: undefined});236test('$.pipe(options)(subprocess) fails', async t => {237 await t.throwsAsync(238 $`empty.js`.pipe({stdout: 'pipe'})($`empty.js`),239 {message: /Please use \.pipe/},240 );241});242755test('Sets the right error message when the "all" option is incompatible - execa.$', async t => {756 await assertPipeError(757 t,758 execa('empty.js')759 .pipe({all: false})`stdin.js`760 .pipe(execa('empty.js'), {from: 'all'}),761 '"all" option must be true',243test('execa.$.pipe(options)(subprocess) fails', async t => {244 await t.throwsAsync(245 execa('empty.js').pipe({stdout: 'pipe'})($`empty.js`),246 {message: /Please use \.pipe/},247 );248});249765test('Sets the right error message when the "all" option is incompatible - execa.execa', async t => {766 await assertPipeError(767 t,768 execa('empty.js')769 .pipe(execa('stdin.js', {all: false}))770 .pipe(execa('empty.js'), {from: 'all'}),771 '"all" option must be true',250test('$.pipe(options)("file") fails', async t => {251 await t.throwsAsync(252 $`empty.js`.pipe({stdout: 'pipe'})('empty.js'),253 {message: /Please use \.pipe/},254 );255});256775test('Sets the right error message when the "all" option is incompatible - early error', async t => {776 await assertPipeError(777 t,778 getEarlyErrorSubprocess()779 .pipe(execa('stdin.js', {all: false}))780 .pipe(execa('empty.js'), {from: 'all'}),781 '"all" option must be true',257test('execa.$.pipe(options)("file") fails', async t => {258 await t.throwsAsync(259 execa('empty.js').pipe({stdout: 'pipe'})('empty.js'),260 {message: /Please use \.pipe/},261 );262});263264const testInvalidPipe = async (t, ...args) => {265 await t.throwsAsync(266 $`empty.js`.pipe(...args),267 {message: /must be a template string/},268 );269};270271test('$.pipe(nonExecaSubprocess) fails', testInvalidPipe, spawn('node', ['--version']));272test('$.pipe(false) fails', testInvalidPipe, false);
modified:test/return/error.js+1 added-86 removed
1import process from 'node:process';2import test from 'ava';3import {execa, execaSync} from '../../index.js';4import {setFixtureDir} from '../helpers/fixtures-dir.js';5import {fullStdio, getStdio} from '../helpers/stdio.js';6import {foobarString} from '../helpers/input.js';7import {QUOTE} from '../helpers/verbose.js';8import {noopGenerator, outputObjectGenerator} from '../helpers/generator.js';5import {fullStdio} from '../helpers/stdio.js';67const isWindows = process.platform === 'win32';89setFixtureDir();
53 unmodified lines
6364test('Error properties are not missing and are ordered', testErrorShape, execa);65test('Error properties are not missing and are ordered, sync', testErrorShape, execaSync);6670test('error.message contains the command', async t => {71 await t.throwsAsync(execa('exit.js', ['2', 'foo', 'bar']), {message: /exit.js 2 foo bar/});72});7374// eslint-disable-next-line max-params75const testStdioMessage = async (t, encoding, all, objectMode, execaMethod) => {76 const {exitCode, message} = await execaMethod('echo-fail.js', {...getStdio(1, noopGenerator(objectMode, false, true), 4), encoding, all, reject: false});77 t.is(exitCode, 1);78 const output = all ? 'stdout\nstderr' : 'stderr\n\nstdout';79 t.true(message.endsWith(`echo-fail.js\n\n${output}\n\nfd3`));80};8182test('error.message contains stdout/stderr/stdio if available', testStdioMessage, 'utf8', false, false, execa);83test('error.message contains stdout/stderr/stdio even with encoding "buffer"', testStdioMessage, 'buffer', false, false, execa);84test('error.message contains all if available', testStdioMessage, 'utf8', true, false, execa);85test('error.message contains all even with encoding "buffer"', testStdioMessage, 'buffer', true, false, execa);86test('error.message contains stdout/stderr/stdio if available, objectMode', testStdioMessage, 'utf8', false, true, execa);87test('error.message contains stdout/stderr/stdio even with encoding "buffer", objectMode', testStdioMessage, 'buffer', false, true, execa);88test('error.message contains all if available, objectMode', testStdioMessage, 'utf8', true, true, execa);89test('error.message contains all even with encoding "buffer", objectMode', testStdioMessage, 'buffer', true, true, execa);90test('error.message contains stdout/stderr/stdio if available, sync', testStdioMessage, 'utf8', false, false, execaSync);91test('error.message contains stdout/stderr/stdio even with encoding "buffer", sync', testStdioMessage, 'buffer', false, false, execaSync);92test('error.message contains all if available, sync', testStdioMessage, 'utf8', true, false, execaSync);93test('error.message contains all even with encoding "buffer", sync', testStdioMessage, 'buffer', true, false, execaSync);94test('error.message contains stdout/stderr/stdio if available, objectMode, sync', testStdioMessage, 'utf8', false, true, execaSync);95test('error.message contains stdout/stderr/stdio even with encoding "buffer", objectMode, sync', testStdioMessage, 'buffer', false, true, execaSync);96test('error.message contains all if available, objectMode, sync', testStdioMessage, 'utf8', true, true, execaSync);97test('error.message contains all even with encoding "buffer", objectMode, sync', testStdioMessage, 'buffer', true, true, execaSync);9899const testLinesMessage = async (t, encoding, stripFinalNewline, execaMethod) => {100 const {failed, message} = await execaMethod('noop-fail.js', ['1', `${foobarString}\n${foobarString}\n`], {101 lines: true,102 encoding,103 stripFinalNewline,104 reject: false,105 });106 t.true(failed);107 t.true(message.endsWith(`noop-fail.js 1 ${QUOTE}${foobarString}\\n${foobarString}\\n${QUOTE}\n\n${foobarString}\n${foobarString}`));108};109110test('error.message handles "lines: true"', testLinesMessage, 'utf8', false, execa);111test('error.message handles "lines: true", stripFinalNewline', testLinesMessage, 'utf8', true, execa);112test('error.message handles "lines: true", buffer', testLinesMessage, 'buffer', false, execa);113test('error.message handles "lines: true", buffer, stripFinalNewline', testLinesMessage, 'buffer', true, execa);114test('error.message handles "lines: true", sync', testLinesMessage, 'utf8', false, execaSync);115test('error.message handles "lines: true", stripFinalNewline, sync', testLinesMessage, 'utf8', true, execaSync);116test('error.message handles "lines: true", buffer, sync', testLinesMessage, 'buffer', false, execaSync);117test('error.message handles "lines: true", buffer, stripFinalNewline, sync', testLinesMessage, 'buffer', true, execaSync);118119const testPartialIgnoreMessage = async (t, fdNumber, stdioOption, output) => {120 const {message} = await t.throwsAsync(execa('echo-fail.js', getStdio(fdNumber, stdioOption, 4)));121 t.true(message.endsWith(`echo-fail.js\n\n${output}\n\nfd3`));122};123124test('error.message does not contain stdout if not available', testPartialIgnoreMessage, 1, 'ignore', 'stderr');125test('error.message does not contain stderr if not available', testPartialIgnoreMessage, 2, 'ignore', 'stdout');126test('error.message does not contain stdout if it is an object', testPartialIgnoreMessage, 1, outputObjectGenerator(), 'stderr');127test('error.message does not contain stderr if it is an object', testPartialIgnoreMessage, 2, outputObjectGenerator(), 'stdout');128129const testFullIgnoreMessage = async (t, options, resultProperty) => {130 const {[resultProperty]: message} = await t.throwsAsync(execa('echo-fail.js', options));131 t.false(message.includes('stderr'));132 t.false(message.includes('stdout'));133 t.false(message.includes('fd3'));134};135136test('error.message does not contain stdout/stderr/stdio if not available', testFullIgnoreMessage, {stdio: 'ignore'}, 'message');137test('error.shortMessage does not contain stdout/stderr/stdio', testFullIgnoreMessage, fullStdio, 'shortMessage');138139const testErrorMessageConsistent = async (t, stdout) => {140 const {message} = await t.throwsAsync(execa('noop-both-fail-strict.js', [stdout, 'stderr']));141 t.true(message.endsWith(' stderr\n\nstderr\n\nstdout'));142};143144test('error.message newlines are consistent - no newline', testErrorMessageConsistent, 'stdout');145test('error.message newlines are consistent - newline', testErrorMessageConsistent, 'stdout\n');146147test('Original error.message is kept', async t => {148 const {originalMessage} = await t.throwsAsync(execa('noop.js', {uid: true}));149 t.is(originalMessage, 'The "options.uid" property must be int32. Received type boolean (true)');150});15167test('failed is false on success', async t => {68 const {failed} = await execa('noop.js', ['foo']);69 t.false(failed);70});
75 unmodified lines
added:test/return/message.js+91 added
1import test from 'ava';2import {execa, execaSync} from '../../index.js';3import {setFixtureDir} from '../helpers/fixtures-dir.js';4import {fullStdio, getStdio} from '../helpers/stdio.js';5import {foobarString} from '../helpers/input.js';6import {QUOTE} from '../helpers/verbose.js';7import {noopGenerator, outputObjectGenerator} from '../helpers/generator.js';89setFixtureDir();1011test('error.message contains the command', async t => {12 await t.throwsAsync(execa('exit.js', ['2', 'foo', 'bar']), {message: /exit.js 2 foo bar/});13});1415// eslint-disable-next-line max-params16const testStdioMessage = async (t, encoding, all, objectMode, execaMethod) => {17 const {exitCode, message} = await execaMethod('echo-fail.js', {...getStdio(1, noopGenerator(objectMode, false, true), 4), encoding, all, reject: false});18 t.is(exitCode, 1);19 const output = all ? 'stdout\nstderr' : 'stderr\n\nstdout';20 t.true(message.endsWith(`echo-fail.js\n\n${output}\n\nfd3`));21};2223test('error.message contains stdout/stderr/stdio if available', testStdioMessage, 'utf8', false, false, execa);24test('error.message contains stdout/stderr/stdio even with encoding "buffer"', testStdioMessage, 'buffer', false, false, execa);25test('error.message contains all if available', testStdioMessage, 'utf8', true, false, execa);26test('error.message contains all even with encoding "buffer"', testStdioMessage, 'buffer', true, false, execa);27test('error.message contains stdout/stderr/stdio if available, objectMode', testStdioMessage, 'utf8', false, true, execa);28test('error.message contains stdout/stderr/stdio even with encoding "buffer", objectMode', testStdioMessage, 'buffer', false, true, execa);29test('error.message contains all if available, objectMode', testStdioMessage, 'utf8', true, true, execa);30test('error.message contains all even with encoding "buffer", objectMode', testStdioMessage, 'buffer', true, true, execa);31test('error.message contains stdout/stderr/stdio if available, sync', testStdioMessage, 'utf8', false, false, execaSync);32test('error.message contains stdout/stderr/stdio even with encoding "buffer", sync', testStdioMessage, 'buffer', false, false, execaSync);33test('error.message contains all if available, sync', testStdioMessage, 'utf8', true, false, execaSync);34test('error.message contains all even with encoding "buffer", sync', testStdioMessage, 'buffer', true, false, execaSync);35test('error.message contains stdout/stderr/stdio if available, objectMode, sync', testStdioMessage, 'utf8', false, true, execaSync);36test('error.message contains stdout/stderr/stdio even with encoding "buffer", objectMode, sync', testStdioMessage, 'buffer', false, true, execaSync);37test('error.message contains all if available, objectMode, sync', testStdioMessage, 'utf8', true, true, execaSync);38test('error.message contains all even with encoding "buffer", objectMode, sync', testStdioMessage, 'buffer', true, true, execaSync);3940const testLinesMessage = async (t, encoding, stripFinalNewline, execaMethod) => {41 const {failed, message} = await execaMethod('noop-fail.js', ['1', `${foobarString}\n${foobarString}\n`], {42 lines: true,43 encoding,44 stripFinalNewline,45 reject: false,46 });47 t.true(failed);48 t.true(message.endsWith(`noop-fail.js 1 ${QUOTE}${foobarString}\\n${foobarString}\\n${QUOTE}\n\n${foobarString}\n${foobarString}`));49};5051test('error.message handles "lines: true"', testLinesMessage, 'utf8', false, execa);52test('error.message handles "lines: true", stripFinalNewline', testLinesMessage, 'utf8', true, execa);53test('error.message handles "lines: true", buffer', testLinesMessage, 'buffer', false, execa);54test('error.message handles "lines: true", buffer, stripFinalNewline', testLinesMessage, 'buffer', true, execa);55test('error.message handles "lines: true", sync', testLinesMessage, 'utf8', false, execaSync);56test('error.message handles "lines: true", stripFinalNewline, sync', testLinesMessage, 'utf8', true, execaSync);57test('error.message handles "lines: true", buffer, sync', testLinesMessage, 'buffer', false, execaSync);58test('error.message handles "lines: true", buffer, stripFinalNewline, sync', testLinesMessage, 'buffer', true, execaSync);5960const testPartialIgnoreMessage = async (t, fdNumber, stdioOption, output) => {61 const {message} = await t.throwsAsync(execa('echo-fail.js', getStdio(fdNumber, stdioOption, 4)));62 t.true(message.endsWith(`echo-fail.js\n\n${output}\n\nfd3`));63};6465test('error.message does not contain stdout if not available', testPartialIgnoreMessage, 1, 'ignore', 'stderr');66test('error.message does not contain stderr if not available', testPartialIgnoreMessage, 2, 'ignore', 'stdout');67test('error.message does not contain stdout if it is an object', testPartialIgnoreMessage, 1, outputObjectGenerator(), 'stderr');68test('error.message does not contain stderr if it is an object', testPartialIgnoreMessage, 2, outputObjectGenerator(), 'stdout');6970const testFullIgnoreMessage = async (t, options, resultProperty) => {71 const {[resultProperty]: message} = await t.throwsAsync(execa('echo-fail.js', options));72 t.false(message.includes('stderr'));73 t.false(message.includes('stdout'));74 t.false(message.includes('fd3'));75};7677test('error.message does not contain stdout/stderr/stdio if not available', testFullIgnoreMessage, {stdio: 'ignore'}, 'message');78test('error.shortMessage does not contain stdout/stderr/stdio', testFullIgnoreMessage, fullStdio, 'shortMessage');7980const testErrorMessageConsistent = async (t, stdout) => {81 const {message} = await t.throwsAsync(execa('noop-both-fail-strict.js', [stdout, 'stderr']));82 t.true(message.endsWith(' stderr\n\nstderr\n\nstdout'));83};8485test('error.message newlines are consistent - no newline', testErrorMessageConsistent, 'stdout');86test('error.message newlines are consistent - newline', testErrorMessageConsistent, 'stdout\n');8788test('Original error.message is kept', async t => {89 const {originalMessage} = await t.throwsAsync(execa('noop.js', {uid: true}));90 t.is(originalMessage, 'The "options.uid" property must be int32. Received type boolean (true)');91});
modified:test/return/output.js-49 removed
1import test from 'ava';2import {execa, execaSync} from '../../index.js';3import {setFixtureDir} from '../helpers/fixtures-dir.js';4import {fullStdio, getStdio} from '../helpers/stdio.js';5import {noopGenerator} from '../helpers/generator.js';5import {foobarString} from '../helpers/input.js';67setFixtureDir();8
98 unmodified lines
107};108109test('error.stdout/stderr/stdio is defined', testErrorOutput, execa);110test('error.stdout/stderr/stdio is defined, sync', testErrorOutput, execaSync);112113// eslint-disable-next-line max-params114const testStripFinalNewline = async (t, fdNumber, stripFinalNewline, shouldStrip, execaMethod) => {115 const {stdio} = await execaMethod('noop-fd.js', [`${fdNumber}`, `${foobarString}\n`], {...fullStdio, stripFinalNewline});116 t.is(stdio[fdNumber], `${foobarString}${shouldStrip ? '' : '\n'}`);117};118119test('stripFinalNewline: default with stdout', testStripFinalNewline, 1, undefined, true, execa);120test('stripFinalNewline: true with stdout', testStripFinalNewline, 1, true, true, execa);121test('stripFinalNewline: false with stdout', testStripFinalNewline, 1, false, false, execa);122test('stripFinalNewline: default with stderr', testStripFinalNewline, 2, undefined, true, execa);123test('stripFinalNewline: true with stderr', testStripFinalNewline, 2, true, true, execa);124test('stripFinalNewline: false with stderr', testStripFinalNewline, 2, false, false, execa);125test('stripFinalNewline: default with stdio[*]', testStripFinalNewline, 3, undefined, true, execa);126test('stripFinalNewline: true with stdio[*]', testStripFinalNewline, 3, true, true, execa);127test('stripFinalNewline: false with stdio[*]', testStripFinalNewline, 3, false, false, execa);128test('stripFinalNewline: default with stdout, fd-specific', testStripFinalNewline, 1, {}, true, execa);129test('stripFinalNewline: true with stdout, fd-specific', testStripFinalNewline, 1, {stdout: true}, true, execa);130test('stripFinalNewline: false with stdout, fd-specific', testStripFinalNewline, 1, {stdout: false}, false, execa);131test('stripFinalNewline: default with stderr, fd-specific', testStripFinalNewline, 2, {}, true, execa);132test('stripFinalNewline: true with stderr, fd-specific', testStripFinalNewline, 2, {stderr: true}, true, execa);133test('stripFinalNewline: false with stderr, fd-specific', testStripFinalNewline, 2, {stderr: false}, false, execa);134test('stripFinalNewline: default with stdio[*], fd-specific', testStripFinalNewline, 3, {}, true, execa);135test('stripFinalNewline: true with stdio[*], fd-specific', testStripFinalNewline, 3, {fd3: true}, true, execa);136test('stripFinalNewline: false with stdio[*], fd-specific', testStripFinalNewline, 3, {fd3: false}, false, execa);137test('stripFinalNewline: default with stdout, sync', testStripFinalNewline, 1, undefined, true, execaSync);138test('stripFinalNewline: true with stdout, sync', testStripFinalNewline, 1, true, true, execaSync);139test('stripFinalNewline: false with stdout, sync', testStripFinalNewline, 1, false, false, execaSync);140test('stripFinalNewline: default with stderr, sync', testStripFinalNewline, 2, undefined, true, execaSync);141test('stripFinalNewline: true with stderr, sync', testStripFinalNewline, 2, true, true, execaSync);142test('stripFinalNewline: false with stderr, sync', testStripFinalNewline, 2, false, false, execaSync);143test('stripFinalNewline: default with stdio[*], sync', testStripFinalNewline, 3, undefined, true, execaSync);144test('stripFinalNewline: true with stdio[*], sync', testStripFinalNewline, 3, true, true, execaSync);145test('stripFinalNewline: false with stdio[*], sync', testStripFinalNewline, 3, false, false, execaSync);146test('stripFinalNewline: default with stdout, fd-specific, sync', testStripFinalNewline, 1, {}, true, execaSync);147test('stripFinalNewline: true with stdout, fd-specific, sync', testStripFinalNewline, 1, {stdout: true}, true, execaSync);148test('stripFinalNewline: false with stdout, fd-specific, sync', testStripFinalNewline, 1, {stdout: false}, false, execaSync);149test('stripFinalNewline: default with stderr, fd-specific, sync', testStripFinalNewline, 2, {}, true, execaSync);150test('stripFinalNewline: true with stderr, fd-specific, sync', testStripFinalNewline, 2, {stderr: true}, true, execaSync);151test('stripFinalNewline: false with stderr, fd-specific, sync', testStripFinalNewline, 2, {stderr: false}, false, execaSync);152test('stripFinalNewline: default with stdio[*], fd-specific, sync', testStripFinalNewline, 3, {}, true, execaSync);153test('stripFinalNewline: true with stdio[*], fd-specific, sync', testStripFinalNewline, 3, {fd3: true}, true, execaSync);154test('stripFinalNewline: false with stdio[*], fd-specific, sync', testStripFinalNewline, 3, {fd3: false}, false, execaSync);155156test('stripFinalNewline is not used in objectMode', async t => {157 const {stdout} = await execa('noop-fd.js', ['1', `${foobarString}\n`], {stripFinalNewline: true, stdout: noopGenerator(true, false, true)});158 t.deepEqual(stdout, [`${foobarString}\n`]);159});
added:test/return/reject.js+15 added
1import test from 'ava';2import {execa, execaSync} from '../../index.js';3import {setFixtureDir} from '../helpers/fixtures-dir.js';45setFixtureDir();67test('skip throwing when using reject option', async t => {8 const {exitCode} = await execa('fail.js', {reject: false});9 t.is(exitCode, 2);10});1112test('skip throwing when using reject option in sync mode', t => {13 const {exitCode} = execaSync('fail.js', {reject: false});14 t.is(exitCode, 2);15});
added:test/return/strip-newline.js+56 added
1import test from 'ava';2import {execa, execaSync} from '../../index.js';3import {setFixtureDir} from '../helpers/fixtures-dir.js';4import {fullStdio} from '../helpers/stdio.js';5import {noopGenerator} from '../helpers/generator.js';6import {foobarString} from '../helpers/input.js';78setFixtureDir();910// eslint-disable-next-line max-params11const testStripFinalNewline = async (t, 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'}`);14};1516test('stripFinalNewline: default with stdout', testStripFinalNewline, 1, undefined, true, execa);17test('stripFinalNewline: true with stdout', testStripFinalNewline, 1, true, true, execa);18test('stripFinalNewline: false with stdout', testStripFinalNewline, 1, false, false, execa);19test('stripFinalNewline: default with stderr', testStripFinalNewline, 2, undefined, true, execa);20test('stripFinalNewline: true with stderr', testStripFinalNewline, 2, true, true, execa);21test('stripFinalNewline: false with stderr', testStripFinalNewline, 2, false, false, execa);22test('stripFinalNewline: default with stdio[*]', testStripFinalNewline, 3, undefined, true, execa);23test('stripFinalNewline: true with stdio[*]', testStripFinalNewline, 3, true, true, execa);24test('stripFinalNewline: false with stdio[*]', testStripFinalNewline, 3, false, false, execa);25test('stripFinalNewline: default with stdout, fd-specific', testStripFinalNewline, 1, {}, true, execa);26test('stripFinalNewline: true with stdout, fd-specific', testStripFinalNewline, 1, {stdout: true}, true, execa);27test('stripFinalNewline: false with stdout, fd-specific', testStripFinalNewline, 1, {stdout: false}, false, execa);28test('stripFinalNewline: default with stderr, fd-specific', testStripFinalNewline, 2, {}, true, execa);29test('stripFinalNewline: true with stderr, fd-specific', testStripFinalNewline, 2, {stderr: true}, true, execa);30test('stripFinalNewline: false with stderr, fd-specific', testStripFinalNewline, 2, {stderr: false}, false, execa);31test('stripFinalNewline: default with stdio[*], fd-specific', testStripFinalNewline, 3, {}, true, execa);32test('stripFinalNewline: true with stdio[*], fd-specific', testStripFinalNewline, 3, {fd3: true}, true, execa);33test('stripFinalNewline: false with stdio[*], fd-specific', testStripFinalNewline, 3, {fd3: false}, false, execa);34test('stripFinalNewline: default with stdout, sync', testStripFinalNewline, 1, undefined, true, execaSync);35test('stripFinalNewline: true with stdout, sync', testStripFinalNewline, 1, true, true, execaSync);36test('stripFinalNewline: false with stdout, sync', testStripFinalNewline, 1, false, false, execaSync);37test('stripFinalNewline: default with stderr, sync', testStripFinalNewline, 2, undefined, true, execaSync);38test('stripFinalNewline: true with stderr, sync', testStripFinalNewline, 2, true, true, execaSync);39test('stripFinalNewline: false with stderr, sync', testStripFinalNewline, 2, false, false, execaSync);40test('stripFinalNewline: default with stdio[*], sync', testStripFinalNewline, 3, undefined, true, execaSync);41test('stripFinalNewline: true with stdio[*], sync', testStripFinalNewline, 3, true, true, execaSync);42test('stripFinalNewline: false with stdio[*], sync', testStripFinalNewline, 3, false, false, execaSync);43test('stripFinalNewline: default with stdout, fd-specific, sync', testStripFinalNewline, 1, {}, true, execaSync);44test('stripFinalNewline: true with stdout, fd-specific, sync', testStripFinalNewline, 1, {stdout: true}, true, execaSync);45test('stripFinalNewline: false with stdout, fd-specific, sync', testStripFinalNewline, 1, {stdout: false}, false, execaSync);46test('stripFinalNewline: default with stderr, fd-specific, sync', testStripFinalNewline, 2, {}, true, execaSync);47test('stripFinalNewline: true with stderr, fd-specific, sync', testStripFinalNewline, 2, {stderr: true}, true, execaSync);48test('stripFinalNewline: false with stderr, fd-specific, sync', testStripFinalNewline, 2, {stderr: false}, false, execaSync);49test('stripFinalNewline: default with stdio[*], fd-specific, sync', testStripFinalNewline, 3, {}, true, execaSync);50test('stripFinalNewline: true with stdio[*], fd-specific, sync', testStripFinalNewline, 3, {fd3: true}, true, execaSync);51test('stripFinalNewline: false with stdio[*], fd-specific, sync', testStripFinalNewline, 3, {fd3: false}, false, execaSync);5253test('stripFinalNewline is not used in objectMode', async t => {54 const {stdout} = await execa('noop-fd.js', ['1', `${foobarString}\n`], {stripFinalNewline: true, stdout: noopGenerator(true, false, true)});55 t.deepEqual(stdout, [`${foobarString}\n`]);56});
deleted:test/stdio/async.js-84 removed
1import {once, defaultMaxListeners} from 'node:events';2import process from 'node:process';3import {setImmediate} from 'node:timers/promises';4import test from 'ava';5import {execa} from '../../index.js';6import {STANDARD_STREAMS} from '../helpers/stdio.js';7import {foobarString} from '../helpers/input.js';8import {setFixtureDir} from '../helpers/fixtures-dir.js';9import {assertMaxListeners} from '../helpers/listeners.js';1011setFixtureDir();1213const getStandardStreamListeners = stream => Object.fromEntries(stream.eventNames().map(eventName => [eventName, stream.listeners(eventName)]));14const getStandardStreamsListeners = () => STANDARD_STREAMS.map(stream => getStandardStreamListeners(stream));1516const getComplexStdio = isMultiple => ({17 stdin: ['pipe', 'inherit', ...(isMultiple ? [0, process.stdin] : [])],18 stdout: ['pipe', 'inherit', ...(isMultiple ? [1, process.stdout] : [])],19 stderr: ['pipe', 'inherit', ...(isMultiple ? [2, process.stderr] : [])],20});2122const onStdinRemoveListener = () => once(process.stdin, 'removeListener');2324const testListenersCleanup = async (t, isMultiple) => {25 const streamsPreviousListeners = getStandardStreamsListeners();26 const subprocess = execa('empty.js', getComplexStdio(isMultiple));27 t.notDeepEqual(getStandardStreamsListeners(), streamsPreviousListeners);28 await Promise.all([subprocess, onStdinRemoveListener()]);29 if (isMultiple) {30 await onStdinRemoveListener();31 }3233 for (const [fdNumber, streamNewListeners] of Object.entries(getStandardStreamsListeners())) {34 const defaultListeners = Object.fromEntries(Reflect.ownKeys(streamNewListeners).map(eventName => [eventName, []]));35 t.deepEqual(streamNewListeners, {...defaultListeners, ...streamsPreviousListeners[fdNumber]});36 }37};3839test.serial('process.std* listeners are cleaned up on success with a single input', testListenersCleanup, false);40test.serial('process.std* listeners are cleaned up on success with multiple inputs', testListenersCleanup, true);4142const subprocessesCount = 100;4344test.serial('Can spawn many subprocesses in parallel', async t => {45 const results = await Promise.all(46 Array.from({length: subprocessesCount}, () => execa('noop.js', [foobarString])),47 );48 t.true(results.every(({stdout}) => stdout === foobarString));49});5051const testMaxListeners = async (t, isMultiple, maxListenersCount) => {52 const checkMaxListeners = assertMaxListeners(t);5354 for (const standardStream of STANDARD_STREAMS) {55 standardStream.setMaxListeners(maxListenersCount);56 }5758 try {59 const results = await Promise.all(60 Array.from({length: subprocessesCount}, () => execa('empty.js', getComplexStdio(isMultiple))),61 );62 t.true(results.every(({exitCode}) => exitCode === 0));63 } finally {64 await setImmediate();65 await setImmediate();66 checkMaxListeners();6768 for (const standardStream of STANDARD_STREAMS) {69 t.is(standardStream.getMaxListeners(), maxListenersCount);70 standardStream.setMaxListeners(defaultMaxListeners);71 }72 }73};7475test.serial('No warning with maxListeners 1 and ["pipe", "inherit"]', testMaxListeners, false, 1);76test.serial('No warning with maxListeners default and ["pipe", "inherit"]', testMaxListeners, false, defaultMaxListeners);77test.serial('No warning with maxListeners 100 and ["pipe", "inherit"]', testMaxListeners, false, 100);78test.serial('No warning with maxListeners Infinity and ["pipe", "inherit"]', testMaxListeners, false, Number.POSITIVE_INFINITY);79test.serial('No warning with maxListeners 0 and ["pipe", "inherit"]', testMaxListeners, false, 0);80test.serial('No warning with maxListeners 1 and ["pipe", "inherit"], multiple inputs', testMaxListeners, true, 1);81test.serial('No warning with maxListeners default and ["pipe", "inherit"], multiple inputs', testMaxListeners, true, defaultMaxListeners);82test.serial('No warning with maxListeners 100 and ["pipe", "inherit"], multiple inputs', testMaxListeners, true, 100);83test.serial('No warning with maxListeners Infinity and ["pipe", "inherit"], multiple inputs', testMaxListeners, true, Number.POSITIVE_INFINITY);84test.serial('No warning with maxListeners 0 and ["pipe", "inherit"], multiple inputs', testMaxListeners, true, 0);
modified:test/stdio/encoding-final.js+1 added-110 removed
1import {Buffer} from 'node:buffer';2import {exec} from 'node:child_process';3import process from 'node:process';3import {promisify} from 'node:util';4import test from 'ava';5import getStream from 'get-stream';6import {execa, execaSync} from '../../index.js';7import {setFixtureDir, FIXTURES_DIR} from '../helpers/fixtures-dir.js';8import {fullStdio} from '../helpers/stdio.js';10import {outputObjectGenerator, getOutputsGenerator, addNoopGenerator} from '../helpers/generator.js';11import {foobarString, foobarUint8Array, foobarObject, foobarHex} from '../helpers/input.js';9import {foobarString, foobarUint8Array, foobarHex} from '../helpers/input.js';1011const pExec = promisify(exec);1213setFixtureDir();
78 unmodified lines
92test('can pass encoding "hex" to stdio[*] - sync', checkEncoding, 'hex', 3, execaSync);93test('can pass encoding "base64" to stdio[*] - sync', checkEncoding, 'base64', 3, execaSync);94test('can pass encoding "base64url" to stdio[*] - sync', checkEncoding, 'base64url', 3, execaSync);9598const foobarArray = ['fo', 'ob', 'ar', '..'];99100const testMultibyteCharacters = async (t, objectMode, addNoopTransform, execaMethod) => {101 const {stdout} = await execaMethod('noop.js', {102 stdout: addNoopGenerator(getOutputsGenerator(foobarArray)(objectMode, true), addNoopTransform, objectMode),103 encoding: 'base64',104 });105 if (objectMode) {106 t.deepEqual(stdout, foobarArray);107 } else {108 t.is(stdout, btoa(foobarArray.join('')));109 }110};111112test('Handle multibyte characters', testMultibyteCharacters, false, false, execa);113test('Handle multibyte characters, noop transform', testMultibyteCharacters, false, true, execa);114test('Handle multibyte characters, with objectMode', testMultibyteCharacters, true, false, execa);115test('Handle multibyte characters, with objectMode, noop transform', testMultibyteCharacters, true, true, execa);116test('Handle multibyte characters, sync', testMultibyteCharacters, false, false, execaSync);117test('Handle multibyte characters, noop transform, sync', testMultibyteCharacters, false, true, execaSync);118test('Handle multibyte characters, with objectMode, sync', testMultibyteCharacters, true, false, execaSync);119test('Handle multibyte characters, with objectMode, noop transform, sync', testMultibyteCharacters, true, true, execaSync);120121const testObjectMode = async (t, addNoopTransform, execaMethod) => {122 const {stdout} = await execaMethod('noop.js', {123 stdout: addNoopGenerator(outputObjectGenerator(), addNoopTransform, true),124 encoding: 'base64',125 });126 t.deepEqual(stdout, [foobarObject]);127};128129test('Other encodings work with transforms that return objects', testObjectMode, false, execa);130test('Other encodings work with transforms that return objects, noop transform', testObjectMode, true, execa);131test('Other encodings work with transforms that return objects, sync', testObjectMode, false, execaSync);132test('Other encodings work with transforms that return objects, noop transform, sync', testObjectMode, true, execaSync);13396// eslint-disable-next-line max-params135const testIgnoredEncoding = async (t, stdoutOption, isUndefined, options, execaMethod) => {136 const {stdout} = await execaMethod('empty.js', {stdout: stdoutOption, ...options});137 t.is(stdout === undefined, isUndefined);138};139140const base64Options = {encoding: 'base64'};141const linesOptions = {lines: true};142test('Is ignored with other encodings and "ignore"', testIgnoredEncoding, 'ignore', true, base64Options, execa);143test('Is ignored with other encodings and ["ignore"]', testIgnoredEncoding, ['ignore'], true, base64Options, execa);144test('Is ignored with other encodings and "ipc"', testIgnoredEncoding, 'ipc', true, base64Options, execa);145test('Is ignored with other encodings and ["ipc"]', testIgnoredEncoding, ['ipc'], true, base64Options, execa);146test('Is ignored with other encodings and "inherit"', testIgnoredEncoding, 'inherit', true, base64Options, execa);147test('Is ignored with other encodings and ["inherit"]', testIgnoredEncoding, ['inherit'], true, base64Options, execa);148test('Is ignored with other encodings and 1', testIgnoredEncoding, 1, true, base64Options, execa);149test('Is ignored with other encodings and [1]', testIgnoredEncoding, [1], true, base64Options, execa);150test('Is ignored with other encodings and process.stdout', testIgnoredEncoding, process.stdout, true, base64Options, execa);151test('Is ignored with other encodings and [process.stdout]', testIgnoredEncoding, [process.stdout], true, base64Options, execa);152test('Is not ignored with other encodings and "pipe"', testIgnoredEncoding, 'pipe', false, base64Options, execa);153test('Is not ignored with other encodings and ["pipe"]', testIgnoredEncoding, ['pipe'], false, base64Options, execa);154test('Is not ignored with other encodings and "overlapped"', testIgnoredEncoding, 'overlapped', false, base64Options, execa);155test('Is not ignored with other encodings and ["overlapped"]', testIgnoredEncoding, ['overlapped'], false, base64Options, execa);156test('Is not ignored with other encodings and ["inherit", "pipe"]', testIgnoredEncoding, ['inherit', 'pipe'], false, base64Options, execa);157test('Is not ignored with other encodings and undefined', testIgnoredEncoding, undefined, false, base64Options, execa);158test('Is not ignored with other encodings and null', testIgnoredEncoding, null, false, base64Options, execa);159test('Is ignored with "lines: true" and "ignore"', testIgnoredEncoding, 'ignore', true, linesOptions, execa);160test('Is ignored with "lines: true" and ["ignore"]', testIgnoredEncoding, ['ignore'], true, linesOptions, execa);161test('Is ignored with "lines: true" and "ipc"', testIgnoredEncoding, 'ipc', true, linesOptions, execa);162test('Is ignored with "lines: true" and ["ipc"]', testIgnoredEncoding, ['ipc'], true, linesOptions, execa);163test('Is ignored with "lines: true" and "inherit"', testIgnoredEncoding, 'inherit', true, linesOptions, execa);164test('Is ignored with "lines: true" and ["inherit"]', testIgnoredEncoding, ['inherit'], true, linesOptions, execa);165test('Is ignored with "lines: true" and 1', testIgnoredEncoding, 1, true, linesOptions, execa);166test('Is ignored with "lines: true" and [1]', testIgnoredEncoding, [1], true, linesOptions, execa);167test('Is ignored with "lines: true" and process.stdout', testIgnoredEncoding, process.stdout, true, linesOptions, execa);168test('Is ignored with "lines: true" and [process.stdout]', testIgnoredEncoding, [process.stdout], true, linesOptions, execa);169test('Is not ignored with "lines: true" and "pipe"', testIgnoredEncoding, 'pipe', false, linesOptions, execa);170test('Is not ignored with "lines: true" and ["pipe"]', testIgnoredEncoding, ['pipe'], false, linesOptions, execa);171test('Is not ignored with "lines: true" and "overlapped"', testIgnoredEncoding, 'overlapped', false, linesOptions, execa);172test('Is not ignored with "lines: true" and ["overlapped"]', testIgnoredEncoding, ['overlapped'], false, linesOptions, execa);173test('Is not ignored with "lines: true" and ["inherit", "pipe"]', testIgnoredEncoding, ['inherit', 'pipe'], false, linesOptions, execa);174test('Is not ignored with "lines: true" and undefined', testIgnoredEncoding, undefined, false, linesOptions, execa);175test('Is not ignored with "lines: true" and null', testIgnoredEncoding, null, false, linesOptions, execa);176test('Is ignored with "lines: true", other encodings and "ignore"', testIgnoredEncoding, 'ignore', true, {...base64Options, ...linesOptions}, execa);177test('Is not ignored with "lines: true", other encodings and "pipe"', testIgnoredEncoding, 'pipe', false, {...base64Options, ...linesOptions}, execa);178test('Is ignored with other encodings and "ignore", sync', testIgnoredEncoding, 'ignore', true, base64Options, execaSync);179test('Is ignored with other encodings and ["ignore"], sync', testIgnoredEncoding, ['ignore'], true, base64Options, execaSync);180test('Is ignored with other encodings and "inherit", sync', testIgnoredEncoding, 'inherit', true, base64Options, execaSync);181test('Is ignored with other encodings and ["inherit"], sync', testIgnoredEncoding, ['inherit'], true, base64Options, execaSync);182test('Is ignored with other encodings and 1, sync', testIgnoredEncoding, 1, true, base64Options, execaSync);183test('Is ignored with other encodings and [1], sync', testIgnoredEncoding, [1], true, base64Options, execaSync);184test('Is ignored with other encodings and process.stdout, sync', testIgnoredEncoding, process.stdout, true, base64Options, execaSync);185test('Is ignored with other encodings and [process.stdout], sync', testIgnoredEncoding, [process.stdout], true, base64Options, execaSync);186test('Is not ignored with other encodings and "pipe", sync', testIgnoredEncoding, 'pipe', false, base64Options, execaSync);187test('Is not ignored with other encodings and ["pipe"], sync', testIgnoredEncoding, ['pipe'], false, base64Options, execaSync);188test('Is not ignored with other encodings and undefined, sync', testIgnoredEncoding, undefined, false, base64Options, execaSync);189test('Is not ignored with other encodings and null, sync', testIgnoredEncoding, null, false, base64Options, execaSync);190test('Is ignored with "lines: true" and "ignore", sync', testIgnoredEncoding, 'ignore', true, linesOptions, execaSync);191test('Is ignored with "lines: true" and ["ignore"], sync', testIgnoredEncoding, ['ignore'], true, linesOptions, execaSync);192test('Is ignored with "lines: true" and "inherit", sync', testIgnoredEncoding, 'inherit', true, linesOptions, execaSync);193test('Is ignored with "lines: true" and ["inherit"], sync', testIgnoredEncoding, ['inherit'], true, linesOptions, execaSync);194test('Is ignored with "lines: true" and 1, sync', testIgnoredEncoding, 1, true, linesOptions, execaSync);195test('Is ignored with "lines: true" and [1], sync', testIgnoredEncoding, [1], true, linesOptions, execaSync);196test('Is ignored with "lines: true" and process.stdout, sync', testIgnoredEncoding, process.stdout, true, linesOptions, execaSync);197test('Is ignored with "lines: true" and [process.stdout], sync', testIgnoredEncoding, [process.stdout], true, linesOptions, execaSync);198test('Is not ignored with "lines: true" and "pipe", sync', testIgnoredEncoding, 'pipe', false, linesOptions, execaSync);199test('Is not ignored with "lines: true" and ["pipe"], sync', testIgnoredEncoding, ['pipe'], false, linesOptions, execaSync);200test('Is not ignored with "lines: true" and undefined, sync', testIgnoredEncoding, undefined, false, linesOptions, execaSync);201test('Is not ignored with "lines: true" and null, sync', testIgnoredEncoding, null, false, linesOptions, execaSync);202test('Is ignored with "lines: true", other encodings and "ignore", sync', testIgnoredEncoding, 'ignore', true, {...base64Options, ...linesOptions}, execaSync);203test('Is not ignored with "lines: true", other encodings and "pipe", sync', testIgnoredEncoding, 'pipe', false, {...base64Options, ...linesOptions}, execaSync);204205// eslint-disable-next-line max-params97const testEncodingInput = async (t, input, expectedStdout, encoding, execaMethod) => {98 const {stdout} = await execaMethod('stdin.js', {input, encoding});99 t.deepEqual(stdout, expectedStdout);100};
29 unmodified lines
added:test/stdio/encoding-ignored.js+92 added
1import process from 'node:process';2import test from 'ava';3import {execa, execaSync} from '../../index.js';4import {setFixtureDir} from '../helpers/fixtures-dir.js';5import {outputObjectGenerator, addNoopGenerator} from '../helpers/generator.js';6import {foobarObject} from '../helpers/input.js';78setFixtureDir();910const testObjectMode = async (t, addNoopTransform, execaMethod) => {11 const {stdout} = await execaMethod('noop.js', {12 stdout: addNoopGenerator(outputObjectGenerator(), addNoopTransform, true),13 encoding: 'base64',14 });15 t.deepEqual(stdout, [foobarObject]);16};1718test('Other encodings work with transforms that return objects', testObjectMode, false, execa);19test('Other encodings work with transforms that return objects, noop transform', testObjectMode, true, execa);20test('Other encodings work with transforms that return objects, sync', testObjectMode, false, execaSync);21test('Other encodings work with transforms that return objects, noop transform, sync', testObjectMode, true, execaSync);2223// eslint-disable-next-line max-params24const testIgnoredEncoding = async (t, stdoutOption, isUndefined, options, execaMethod) => {25 const {stdout} = await execaMethod('empty.js', {stdout: stdoutOption, ...options});26 t.is(stdout === undefined, isUndefined);27};2829const base64Options = {encoding: 'base64'};30const linesOptions = {lines: true};31test('Is ignored with other encodings and "ignore"', testIgnoredEncoding, 'ignore', true, base64Options, execa);32test('Is ignored with other encodings and ["ignore"]', testIgnoredEncoding, ['ignore'], true, base64Options, execa);33test('Is ignored with other encodings and "ipc"', testIgnoredEncoding, 'ipc', true, base64Options, execa);34test('Is ignored with other encodings and ["ipc"]', testIgnoredEncoding, ['ipc'], true, base64Options, execa);35test('Is ignored with other encodings and "inherit"', testIgnoredEncoding, 'inherit', true, base64Options, execa);36test('Is ignored with other encodings and ["inherit"]', testIgnoredEncoding, ['inherit'], true, base64Options, execa);37test('Is ignored with other encodings and 1', testIgnoredEncoding, 1, true, base64Options, execa);38test('Is ignored with other encodings and [1]', testIgnoredEncoding, [1], true, base64Options, execa);39test('Is ignored with other encodings and process.stdout', testIgnoredEncoding, process.stdout, true, base64Options, execa);40test('Is ignored with other encodings and [process.stdout]', testIgnoredEncoding, [process.stdout], true, base64Options, execa);41test('Is not ignored with other encodings and "pipe"', testIgnoredEncoding, 'pipe', false, base64Options, execa);42test('Is not ignored with other encodings and ["pipe"]', testIgnoredEncoding, ['pipe'], false, base64Options, execa);43test('Is not ignored with other encodings and "overlapped"', testIgnoredEncoding, 'overlapped', false, base64Options, execa);44test('Is not ignored with other encodings and ["overlapped"]', testIgnoredEncoding, ['overlapped'], false, base64Options, execa);45test('Is not ignored with other encodings and ["inherit", "pipe"]', testIgnoredEncoding, ['inherit', 'pipe'], false, base64Options, execa);46test('Is not ignored with other encodings and undefined', testIgnoredEncoding, undefined, false, base64Options, execa);47test('Is not ignored with other encodings and null', testIgnoredEncoding, null, false, base64Options, execa);48test('Is ignored with "lines: true" and "ignore"', testIgnoredEncoding, 'ignore', true, linesOptions, execa);49test('Is ignored with "lines: true" and ["ignore"]', testIgnoredEncoding, ['ignore'], true, linesOptions, execa);50test('Is ignored with "lines: true" and "ipc"', testIgnoredEncoding, 'ipc', true, linesOptions, execa);51test('Is ignored with "lines: true" and ["ipc"]', testIgnoredEncoding, ['ipc'], true, linesOptions, execa);52test('Is ignored with "lines: true" and "inherit"', testIgnoredEncoding, 'inherit', true, linesOptions, execa);53test('Is ignored with "lines: true" and ["inherit"]', testIgnoredEncoding, ['inherit'], true, linesOptions, execa);54test('Is ignored with "lines: true" and 1', testIgnoredEncoding, 1, true, linesOptions, execa);55test('Is ignored with "lines: true" and [1]', testIgnoredEncoding, [1], true, linesOptions, execa);56test('Is ignored with "lines: true" and process.stdout', testIgnoredEncoding, process.stdout, true, linesOptions, execa);57test('Is ignored with "lines: true" and [process.stdout]', testIgnoredEncoding, [process.stdout], true, linesOptions, execa);58test('Is not ignored with "lines: true" and "pipe"', testIgnoredEncoding, 'pipe', false, linesOptions, execa);59test('Is not ignored with "lines: true" and ["pipe"]', testIgnoredEncoding, ['pipe'], false, linesOptions, execa);60test('Is not ignored with "lines: true" and "overlapped"', testIgnoredEncoding, 'overlapped', false, linesOptions, execa);61test('Is not ignored with "lines: true" and ["overlapped"]', testIgnoredEncoding, ['overlapped'], false, linesOptions, execa);62test('Is not ignored with "lines: true" and ["inherit", "pipe"]', testIgnoredEncoding, ['inherit', 'pipe'], false, linesOptions, execa);63test('Is not ignored with "lines: true" and undefined', testIgnoredEncoding, undefined, false, linesOptions, execa);64test('Is not ignored with "lines: true" and null', testIgnoredEncoding, null, false, linesOptions, execa);65test('Is ignored with "lines: true", other encodings and "ignore"', testIgnoredEncoding, 'ignore', true, {...base64Options, ...linesOptions}, execa);66test('Is not ignored with "lines: true", other encodings and "pipe"', testIgnoredEncoding, 'pipe', false, {...base64Options, ...linesOptions}, execa);67test('Is ignored with other encodings and "ignore", sync', testIgnoredEncoding, 'ignore', true, base64Options, execaSync);68test('Is ignored with other encodings and ["ignore"], sync', testIgnoredEncoding, ['ignore'], true, base64Options, execaSync);69test('Is ignored with other encodings and "inherit", sync', testIgnoredEncoding, 'inherit', true, base64Options, execaSync);70test('Is ignored with other encodings and ["inherit"], sync', testIgnoredEncoding, ['inherit'], true, base64Options, execaSync);71test('Is ignored with other encodings and 1, sync', testIgnoredEncoding, 1, true, base64Options, execaSync);72test('Is ignored with other encodings and [1], sync', testIgnoredEncoding, [1], true, base64Options, execaSync);73test('Is ignored with other encodings and process.stdout, sync', testIgnoredEncoding, process.stdout, true, base64Options, execaSync);74test('Is ignored with other encodings and [process.stdout], sync', testIgnoredEncoding, [process.stdout], true, base64Options, execaSync);75test('Is not ignored with other encodings and "pipe", sync', testIgnoredEncoding, 'pipe', false, base64Options, execaSync);76test('Is not ignored with other encodings and ["pipe"], sync', testIgnoredEncoding, ['pipe'], false, base64Options, execaSync);77test('Is not ignored with other encodings and undefined, sync', testIgnoredEncoding, undefined, false, base64Options, execaSync);78test('Is not ignored with other encodings and null, sync', testIgnoredEncoding, null, false, base64Options, execaSync);79test('Is ignored with "lines: true" and "ignore", sync', testIgnoredEncoding, 'ignore', true, linesOptions, execaSync);80test('Is ignored with "lines: true" and ["ignore"], sync', testIgnoredEncoding, ['ignore'], true, linesOptions, execaSync);81test('Is ignored with "lines: true" and "inherit", sync', testIgnoredEncoding, 'inherit', true, linesOptions, execaSync);82test('Is ignored with "lines: true" and ["inherit"], sync', testIgnoredEncoding, ['inherit'], true, linesOptions, execaSync);83test('Is ignored with "lines: true" and 1, sync', testIgnoredEncoding, 1, true, linesOptions, execaSync);84test('Is ignored with "lines: true" and [1], sync', testIgnoredEncoding, [1], true, linesOptions, execaSync);85test('Is ignored with "lines: true" and process.stdout, sync', testIgnoredEncoding, process.stdout, true, linesOptions, execaSync);86test('Is ignored with "lines: true" and [process.stdout], sync', testIgnoredEncoding, [process.stdout], true, linesOptions, execaSync);87test('Is not ignored with "lines: true" and "pipe", sync', testIgnoredEncoding, 'pipe', false, linesOptions, execaSync);88test('Is not ignored with "lines: true" and ["pipe"], sync', testIgnoredEncoding, ['pipe'], false, linesOptions, execaSync);89test('Is not ignored with "lines: true" and undefined, sync', testIgnoredEncoding, undefined, false, linesOptions, execaSync);90test('Is not ignored with "lines: true" and null, sync', testIgnoredEncoding, null, false, linesOptions, execaSync);91test('Is ignored with "lines: true", other encodings and "ignore", sync', testIgnoredEncoding, 'ignore', true, {...base64Options, ...linesOptions}, execaSync);92test('Is not ignored with "lines: true", other encodings and "pipe", sync', testIgnoredEncoding, 'pipe', false, {...base64Options, ...linesOptions}, execaSync);
added:test/stdio/encoding-multibyte.js+73 added
1import test from 'ava';2import {execa, execaSync} from '../../index.js';3import {setFixtureDir} from '../helpers/fixtures-dir.js';4import {noopGenerator, getOutputsGenerator, addNoopGenerator} from '../helpers/generator.js';5import {multibyteChar, multibyteString, multibyteUint8Array, breakingLength, brokenSymbol} from '../helpers/encoding.js';67setFixtureDir();89const foobarArray = ['fo', 'ob', 'ar', '..'];1011const testMultibyteCharacters = async (t, objectMode, addNoopTransform, execaMethod) => {12 const {stdout} = await execaMethod('noop.js', {13 stdout: addNoopGenerator(getOutputsGenerator(foobarArray)(objectMode, true), addNoopTransform, objectMode),14 encoding: 'base64',15 });16 if (objectMode) {17 t.deepEqual(stdout, foobarArray);18 } else {19 t.is(stdout, btoa(foobarArray.join('')));20 }21};2223test('Handle multibyte characters', testMultibyteCharacters, false, false, execa);24test('Handle multibyte characters, noop transform', testMultibyteCharacters, false, true, execa);25test('Handle multibyte characters, with objectMode', testMultibyteCharacters, true, false, execa);26test('Handle multibyte characters, with objectMode, noop transform', testMultibyteCharacters, true, true, execa);27test('Handle multibyte characters, sync', testMultibyteCharacters, false, false, execaSync);28test('Handle multibyte characters, noop transform, sync', testMultibyteCharacters, false, true, execaSync);29test('Handle multibyte characters, with objectMode, sync', testMultibyteCharacters, true, false, execaSync);30test('Handle multibyte characters, with objectMode, noop transform, sync', testMultibyteCharacters, true, true, execaSync);3132const testMultibyte = async (t, objectMode, execaMethod) => {33 const {stdout} = await execaMethod('stdin.js', {34 stdin: [35 [multibyteUint8Array.slice(0, breakingLength), multibyteUint8Array.slice(breakingLength)],36 noopGenerator(objectMode, true),37 ],38 });39 t.is(stdout, multibyteString);40};4142test('Generator handles multibyte characters with Uint8Array', testMultibyte, false, execa);43test('Generator handles multibyte characters with Uint8Array, objectMode', testMultibyte, true, execa);44test('Generator handles multibyte characters with Uint8Array, sync', testMultibyte, false, execaSync);45test('Generator handles multibyte characters with Uint8Array, objectMode, sync', testMultibyte, true, execaSync);4647const testMultibytePartial = async (t, objectMode, execaMethod) => {48 const {stdout} = await execaMethod('stdin.js', {49 stdin: [50 [multibyteUint8Array.slice(0, breakingLength)],51 noopGenerator(objectMode, true),52 ],53 });54 t.is(stdout, `${multibyteChar}${brokenSymbol}`);55};5657test('Generator handles partial multibyte characters with Uint8Array', testMultibytePartial, false, execa);58test('Generator handles partial multibyte characters with Uint8Array, objectMode', testMultibytePartial, true, execa);59test('Generator handles partial multibyte characters with Uint8Array, sync', testMultibytePartial, false, execaSync);60test('Generator handles partial multibyte characters with Uint8Array, objectMode, sync', testMultibytePartial, true, execaSync);6162const testMultibytePartialOutput = async (t, execaMethod) => {63 const {stdout} = await execaMethod('noop.js', {64 stdout: getOutputsGenerator([65 multibyteUint8Array.slice(0, breakingLength),66 multibyteUint8Array.slice(breakingLength),67 ])(false, true),68 });69 t.is(stdout, multibyteString);70};7172test('Generator handles output multibyte characters with Uint8Array', testMultibytePartialOutput, execa);73test('Generator handles output multibyte characters with Uint8Array, sync', testMultibytePartialOutput, execaSync);
modified:test/stdio/encoding-transform.js+1 added-187 removed
2 unmodified lines
3import {execa, execaSync} from '../../index.js';4import {setFixtureDir} from '../helpers/fixtures-dir.js';5import {getStdio} from '../helpers/stdio.js';6import {foobarString, foobarUint8Array, foobarBuffer, foobarObject} from '../helpers/input.js';7import {noopGenerator, getOutputGenerator, getOutputsGenerator, convertTransformToFinal} from '../helpers/generator.js';8import {multibyteChar, multibyteString, multibyteUint8Array, breakingLength, brokenSymbol} from '../helpers/encoding.js';7import {noopGenerator, getOutputGenerator} from '../helpers/generator.js';89setFixtureDir();1011const getTypeofGenerator = lines => (objectMode, binary) => ({
157 unmodified lines
169test('The first generator with result.stdio[*] does not receive an object argument even in objectMode', testFirstOutputGeneratorArgument, 3, execa);170test('The first generator with result.stdout does not receive an object argument even in objectMode, sync', testFirstOutputGeneratorArgument, 1, execaSync);171test('The first generator with result.stderr does not receive an object argument even in objectMode, sync', testFirstOutputGeneratorArgument, 2, execaSync);172test('The first generator with result.stdio[*] does not receive an object argument even in objectMode, sync', testFirstOutputGeneratorArgument, 3, execaSync);174175// eslint-disable-next-line max-params176const testGeneratorReturnType = async (t, input, encoding, reject, objectMode, final, execaMethod) => {177 const fixtureName = reject ? 'noop-fd.js' : 'noop-fail.js';178 const {stdout} = await execaMethod(fixtureName, ['1', foobarString], {179 stdout: convertTransformToFinal(getOutputGenerator(input)(objectMode, true), final),180 encoding,181 reject,182 });183 const typeofChunk = Array.isArray(stdout) ? stdout[0] : stdout;184 const output = Buffer.from(typeofChunk, encoding === 'buffer' || objectMode ? undefined : encoding).toString();185 t.is(output, foobarString);186};187188test('Generator can return string with default encoding', testGeneratorReturnType, foobarString, 'utf8', true, false, false, execa);189test('Generator can return Uint8Array with default encoding', testGeneratorReturnType, foobarUint8Array, 'utf8', true, false, false, execa);190test('Generator can return string with encoding "utf16le"', testGeneratorReturnType, foobarString, 'utf16le', true, false, false, execa);191test('Generator can return Uint8Array with encoding "utf16le"', testGeneratorReturnType, foobarUint8Array, 'utf16le', true, false, false, execa);192test('Generator can return string with encoding "buffer"', testGeneratorReturnType, foobarString, 'buffer', true, false, false, execa);193test('Generator can return Uint8Array with encoding "buffer"', testGeneratorReturnType, foobarUint8Array, 'buffer', true, false, false, execa);194test('Generator can return string with encoding "hex"', testGeneratorReturnType, foobarString, 'hex', true, false, false, execa);195test('Generator can return Uint8Array with encoding "hex"', testGeneratorReturnType, foobarUint8Array, 'hex', true, false, false, execa);196test('Generator can return string with default encoding, failure', testGeneratorReturnType, foobarString, 'utf8', false, false, false, execa);197test('Generator can return Uint8Array with default encoding, failure', testGeneratorReturnType, foobarUint8Array, 'utf8', false, false, false, execa);198test('Generator can return string with encoding "utf16le", failure', testGeneratorReturnType, foobarString, 'utf16le', false, false, false, execa);199test('Generator can return Uint8Array with encoding "utf16le", failure', testGeneratorReturnType, foobarUint8Array, 'utf16le', false, false, false, execa);200test('Generator can return string with encoding "buffer", failure', testGeneratorReturnType, foobarString, 'buffer', false, false, false, execa);201test('Generator can return Uint8Array with encoding "buffer", failure', testGeneratorReturnType, foobarUint8Array, 'buffer', false, false, false, execa);202test('Generator can return string with encoding "hex", failure', testGeneratorReturnType, foobarString, 'hex', false, false, false, execa);203test('Generator can return Uint8Array with encoding "hex", failure', testGeneratorReturnType, foobarUint8Array, 'hex', false, false, false, execa);204test('Generator can return string with default encoding, objectMode', testGeneratorReturnType, foobarString, 'utf8', true, true, false, execa);205test('Generator can return Uint8Array with default encoding, objectMode', testGeneratorReturnType, foobarUint8Array, 'utf8', true, true, false, execa);206test('Generator can return string with encoding "utf16le", objectMode', testGeneratorReturnType, foobarString, 'utf16le', true, true, false, execa);207test('Generator can return Uint8Array with encoding "utf16le", objectMode', testGeneratorReturnType, foobarUint8Array, 'utf16le', true, true, false, execa);208test('Generator can return string with encoding "buffer", objectMode', testGeneratorReturnType, foobarString, 'buffer', true, true, false, execa);209test('Generator can return Uint8Array with encoding "buffer", objectMode', testGeneratorReturnType, foobarUint8Array, 'buffer', true, true, false, execa);210test('Generator can return string with encoding "hex", objectMode', testGeneratorReturnType, foobarString, 'hex', true, true, false, execa);211test('Generator can return Uint8Array with encoding "hex", objectMode', testGeneratorReturnType, foobarUint8Array, 'hex', true, true, false, execa);212test('Generator can return string with default encoding, objectMode, failure', testGeneratorReturnType, foobarString, 'utf8', false, true, false, execa);213test('Generator can return Uint8Array with default encoding, objectMode, failure', testGeneratorReturnType, foobarUint8Array, 'utf8', false, true, false, execa);214test('Generator can return string with encoding "utf16le", objectMode, failure', testGeneratorReturnType, foobarString, 'utf16le', false, true, false, execa);215test('Generator can return Uint8Array with encoding "utf16le", objectMode, failure', testGeneratorReturnType, foobarUint8Array, 'utf16le', false, true, false, execa);216test('Generator can return string with encoding "buffer", objectMode, failure', testGeneratorReturnType, foobarString, 'buffer', false, true, false, execa);217test('Generator can return Uint8Array with encoding "buffer", objectMode, failure', testGeneratorReturnType, foobarUint8Array, 'buffer', false, true, false, execa);218test('Generator can return string with encoding "hex", objectMode, failure', testGeneratorReturnType, foobarString, 'hex', false, true, false, execa);219test('Generator can return Uint8Array with encoding "hex", objectMode, failure', testGeneratorReturnType, foobarUint8Array, 'hex', false, true, false, execa);220test('Generator can return final string with default encoding', testGeneratorReturnType, foobarString, 'utf8', true, false, true, execa);221test('Generator can return final Uint8Array with default encoding', testGeneratorReturnType, foobarUint8Array, 'utf8', true, false, true, execa);222test('Generator can return final string with encoding "utf16le"', testGeneratorReturnType, foobarString, 'utf16le', true, false, true, execa);223test('Generator can return final Uint8Array with encoding "utf16le"', testGeneratorReturnType, foobarUint8Array, 'utf16le', true, false, true, execa);224test('Generator can return final string with encoding "buffer"', testGeneratorReturnType, foobarString, 'buffer', true, false, true, execa);225test('Generator can return final Uint8Array with encoding "buffer"', testGeneratorReturnType, foobarUint8Array, 'buffer', true, false, true, execa);226test('Generator can return final string with encoding "hex"', testGeneratorReturnType, foobarString, 'hex', true, false, true, execa);227test('Generator can return final Uint8Array with encoding "hex"', testGeneratorReturnType, foobarUint8Array, 'hex', true, false, true, execa);228test('Generator can return final string with default encoding, failure', testGeneratorReturnType, foobarString, 'utf8', false, false, true, execa);229test('Generator can return final Uint8Array with default encoding, failure', testGeneratorReturnType, foobarUint8Array, 'utf8', false, false, true, execa);230test('Generator can return final string with encoding "utf16le", failure', testGeneratorReturnType, foobarString, 'utf16le', false, false, true, execa);231test('Generator can return final Uint8Array with encoding "utf16le", failure', testGeneratorReturnType, foobarUint8Array, 'utf16le', false, false, true, execa);232test('Generator can return final string with encoding "buffer", failure', testGeneratorReturnType, foobarString, 'buffer', false, false, true, execa);233test('Generator can return final Uint8Array with encoding "buffer", failure', testGeneratorReturnType, foobarUint8Array, 'buffer', false, false, true, execa);234test('Generator can return final string with encoding "hex", failure', testGeneratorReturnType, foobarString, 'hex', false, false, true, execa);235test('Generator can return final Uint8Array with encoding "hex", failure', testGeneratorReturnType, foobarUint8Array, 'hex', false, false, true, execa);236test('Generator can return final string with default encoding, objectMode', testGeneratorReturnType, foobarString, 'utf8', true, true, true, execa);237test('Generator can return final Uint8Array with default encoding, objectMode', testGeneratorReturnType, foobarUint8Array, 'utf8', true, true, true, execa);238test('Generator can return final string with encoding "utf16le", objectMode', testGeneratorReturnType, foobarString, 'utf16le', true, true, true, execa);239test('Generator can return final Uint8Array with encoding "utf16le", objectMode', testGeneratorReturnType, foobarUint8Array, 'utf16le', true, true, true, execa);240test('Generator can return final string with encoding "buffer", objectMode', testGeneratorReturnType, foobarString, 'buffer', true, true, true, execa);241test('Generator can return final Uint8Array with encoding "buffer", objectMode', testGeneratorReturnType, foobarUint8Array, 'buffer', true, true, true, execa);242test('Generator can return final string with encoding "hex", objectMode', testGeneratorReturnType, foobarString, 'hex', true, true, true, execa);243test('Generator can return final Uint8Array with encoding "hex", objectMode', testGeneratorReturnType, foobarUint8Array, 'hex', true, true, true, execa);244test('Generator can return final string with default encoding, objectMode, failure', testGeneratorReturnType, foobarString, 'utf8', false, true, true, execa);245test('Generator can return final Uint8Array with default encoding, objectMode, failure', testGeneratorReturnType, foobarUint8Array, 'utf8', false, true, true, execa);246test('Generator can return final string with encoding "utf16le", objectMode, failure', testGeneratorReturnType, foobarString, 'utf16le', false, true, true, execa);247test('Generator can return final Uint8Array with encoding "utf16le", objectMode, failure', testGeneratorReturnType, foobarUint8Array, 'utf16le', false, true, true, execa);248test('Generator can return final string with encoding "buffer", objectMode, failure', testGeneratorReturnType, foobarString, 'buffer', false, true, true, execa);249test('Generator can return final Uint8Array with encoding "buffer", objectMode, failure', testGeneratorReturnType, foobarUint8Array, 'buffer', false, true, true, execa);250test('Generator can return final string with encoding "hex", objectMode, failure', testGeneratorReturnType, foobarString, 'hex', false, true, true, execa);251test('Generator can return final Uint8Array with encoding "hex", objectMode, failure', testGeneratorReturnType, foobarUint8Array, 'hex', false, true, true, execa);252test('Generator can return string with default encoding, sync', testGeneratorReturnType, foobarString, 'utf8', true, false, false, execaSync);253test('Generator can return Uint8Array with default encoding, sync', testGeneratorReturnType, foobarUint8Array, 'utf8', true, false, false, execaSync);254test('Generator can return string with encoding "utf16le", sync', testGeneratorReturnType, foobarString, 'utf16le', true, false, false, execaSync);255test('Generator can return Uint8Array with encoding "utf16le", sync', testGeneratorReturnType, foobarUint8Array, 'utf16le', true, false, false, execaSync);256test('Generator can return string with encoding "buffer", sync', testGeneratorReturnType, foobarString, 'buffer', true, false, false, execaSync);257test('Generator can return Uint8Array with encoding "buffer", sync', testGeneratorReturnType, foobarUint8Array, 'buffer', true, false, false, execaSync);258test('Generator can return string with encoding "hex", sync', testGeneratorReturnType, foobarString, 'hex', true, false, false, execaSync);259test('Generator can return Uint8Array with encoding "hex", sync', testGeneratorReturnType, foobarUint8Array, 'hex', true, false, false, execaSync);260test('Generator can return string with default encoding, failure, sync', testGeneratorReturnType, foobarString, 'utf8', false, false, false, execaSync);261test('Generator can return Uint8Array with default encoding, failure, sync', testGeneratorReturnType, foobarUint8Array, 'utf8', false, false, false, execaSync);262test('Generator can return string with encoding "utf16le", failure, sync', testGeneratorReturnType, foobarString, 'utf16le', false, false, false, execaSync);263test('Generator can return Uint8Array with encoding "utf16le", failure, sync', testGeneratorReturnType, foobarUint8Array, 'utf16le', false, false, false, execaSync);264test('Generator can return string with encoding "buffer", failure, sync', testGeneratorReturnType, foobarString, 'buffer', false, false, false, execaSync);265test('Generator can return Uint8Array with encoding "buffer", failure, sync', testGeneratorReturnType, foobarUint8Array, 'buffer', false, false, false, execaSync);266test('Generator can return string with encoding "hex", failure, sync', testGeneratorReturnType, foobarString, 'hex', false, false, false, execaSync);267test('Generator can return Uint8Array with encoding "hex", failure, sync', testGeneratorReturnType, foobarUint8Array, 'hex', false, false, false, execaSync);268test('Generator can return string with default encoding, objectMode, sync', testGeneratorReturnType, foobarString, 'utf8', true, true, false, execaSync);269test('Generator can return Uint8Array with default encoding, objectMode, sync', testGeneratorReturnType, foobarUint8Array, 'utf8', true, true, false, execaSync);270test('Generator can return string with encoding "utf16le", objectMode, sync', testGeneratorReturnType, foobarString, 'utf16le', true, true, false, execaSync);271test('Generator can return Uint8Array with encoding "utf16le", objectMode, sync', testGeneratorReturnType, foobarUint8Array, 'utf16le', true, true, false, execaSync);272test('Generator can return string with encoding "buffer", objectMode, sync', testGeneratorReturnType, foobarString, 'buffer', true, true, false, execaSync);273test('Generator can return Uint8Array with encoding "buffer", objectMode, sync', testGeneratorReturnType, foobarUint8Array, 'buffer', true, true, false, execaSync);274test('Generator can return string with encoding "hex", objectMode, sync', testGeneratorReturnType, foobarString, 'hex', true, true, false, execaSync);275test('Generator can return Uint8Array with encoding "hex", objectMode, sync', testGeneratorReturnType, foobarUint8Array, 'hex', true, true, false, execaSync);276test('Generator can return string with default encoding, objectMode, failure, sync', testGeneratorReturnType, foobarString, 'utf8', false, true, false, execaSync);277test('Generator can return Uint8Array with default encoding, objectMode, failure, sync', testGeneratorReturnType, foobarUint8Array, 'utf8', false, true, false, execaSync);278test('Generator can return string with encoding "utf16le", objectMode, failure, sync', testGeneratorReturnType, foobarString, 'utf16le', false, true, false, execaSync);279test('Generator can return Uint8Array with encoding "utf16le", objectMode, failure, sync', testGeneratorReturnType, foobarUint8Array, 'utf16le', false, true, false, execaSync);280test('Generator can return string with encoding "buffer", objectMode, failure, sync', testGeneratorReturnType, foobarString, 'buffer', false, true, false, execaSync);281test('Generator can return Uint8Array with encoding "buffer", objectMode, failure, sync', testGeneratorReturnType, foobarUint8Array, 'buffer', false, true, false, execaSync);282test('Generator can return string with encoding "hex", objectMode, failure, sync', testGeneratorReturnType, foobarString, 'hex', false, true, false, execaSync);283test('Generator can return Uint8Array with encoding "hex", objectMode, failure, sync', testGeneratorReturnType, foobarUint8Array, 'hex', false, true, false, execaSync);284test('Generator can return final string with default encoding, sync', testGeneratorReturnType, foobarString, 'utf8', true, false, true, execaSync);285test('Generator can return final Uint8Array with default encoding, sync', testGeneratorReturnType, foobarUint8Array, 'utf8', true, false, true, execaSync);286test('Generator can return final string with encoding "utf16le", sync', testGeneratorReturnType, foobarString, 'utf16le', true, false, true, execaSync);287test('Generator can return final Uint8Array with encoding "utf16le", sync', testGeneratorReturnType, foobarUint8Array, 'utf16le', true, false, true, execaSync);288test('Generator can return final string with encoding "buffer", sync', testGeneratorReturnType, foobarString, 'buffer', true, false, true, execaSync);289test('Generator can return final Uint8Array with encoding "buffer", sync', testGeneratorReturnType, foobarUint8Array, 'buffer', true, false, true, execaSync);290test('Generator can return final string with encoding "hex", sync', testGeneratorReturnType, foobarString, 'hex', true, false, true, execaSync);291test('Generator can return final Uint8Array with encoding "hex", sync', testGeneratorReturnType, foobarUint8Array, 'hex', true, false, true, execaSync);292test('Generator can return final string with default encoding, failure, sync', testGeneratorReturnType, foobarString, 'utf8', false, false, true, execaSync);293test('Generator can return final Uint8Array with default encoding, failure, sync', testGeneratorReturnType, foobarUint8Array, 'utf8', false, false, true, execaSync);294test('Generator can return final string with encoding "utf16le", failure, sync', testGeneratorReturnType, foobarString, 'utf16le', false, false, true, execaSync);295test('Generator can return final Uint8Array with encoding "utf16le", failure, sync', testGeneratorReturnType, foobarUint8Array, 'utf16le', false, false, true, execaSync);296test('Generator can return final string with encoding "buffer", failure, sync', testGeneratorReturnType, foobarString, 'buffer', false, false, true, execaSync);297test('Generator can return final Uint8Array with encoding "buffer", failure, sync', testGeneratorReturnType, foobarUint8Array, 'buffer', false, false, true, execaSync);298test('Generator can return final string with encoding "hex", failure, sync', testGeneratorReturnType, foobarString, 'hex', false, false, true, execaSync);299test('Generator can return final Uint8Array with encoding "hex", failure, sync', testGeneratorReturnType, foobarUint8Array, 'hex', false, false, true, execaSync);300test('Generator can return final string with default encoding, objectMode, sync', testGeneratorReturnType, foobarString, 'utf8', true, true, true, execaSync);301test('Generator can return final Uint8Array with default encoding, objectMode, sync', testGeneratorReturnType, foobarUint8Array, 'utf8', true, true, true, execaSync);302test('Generator can return final string with encoding "utf16le", objectMode, sync', testGeneratorReturnType, foobarString, 'utf16le', true, true, true, execaSync);303test('Generator can return final Uint8Array with encoding "utf16le", objectMode, sync', testGeneratorReturnType, foobarUint8Array, 'utf16le', true, true, true, execaSync);304test('Generator can return final string with encoding "buffer", objectMode, sync', testGeneratorReturnType, foobarString, 'buffer', true, true, true, execaSync);305test('Generator can return final Uint8Array with encoding "buffer", objectMode, sync', testGeneratorReturnType, foobarUint8Array, 'buffer', true, true, true, execaSync);306test('Generator can return final string with encoding "hex", objectMode, sync', testGeneratorReturnType, foobarString, 'hex', true, true, true, execaSync);307test('Generator can return final Uint8Array with encoding "hex", objectMode, sync', testGeneratorReturnType, foobarUint8Array, 'hex', true, true, true, execaSync);308test('Generator can return final string with default encoding, objectMode, failure, sync', testGeneratorReturnType, foobarString, 'utf8', false, true, true, execaSync);309test('Generator can return final Uint8Array with default encoding, objectMode, failure, sync', testGeneratorReturnType, foobarUint8Array, 'utf8', false, true, true, execaSync);310test('Generator can return final string with encoding "utf16le", objectMode, failure, sync', testGeneratorReturnType, foobarString, 'utf16le', false, true, true, execaSync);311test('Generator can return final Uint8Array with encoding "utf16le", objectMode, failure, sync', testGeneratorReturnType, foobarUint8Array, 'utf16le', false, true, true, execaSync);312test('Generator can return final string with encoding "buffer", objectMode, failure, sync', testGeneratorReturnType, foobarString, 'buffer', false, true, true, execaSync);313test('Generator can return final Uint8Array with encoding "buffer", objectMode, failure, sync', testGeneratorReturnType, foobarUint8Array, 'buffer', false, true, true, execaSync);314test('Generator can return final string with encoding "hex", objectMode, failure, sync', testGeneratorReturnType, foobarString, 'hex', false, true, true, execaSync);315test('Generator can return final Uint8Array with encoding "hex", objectMode, failure, sync', testGeneratorReturnType, foobarUint8Array, 'hex', false, true, true, execaSync);316317const testMultibyte = async (t, objectMode, execaMethod) => {318 const {stdout} = await execaMethod('stdin.js', {319 stdin: [320 [multibyteUint8Array.slice(0, breakingLength), multibyteUint8Array.slice(breakingLength)],321 noopGenerator(objectMode, true),322 ],323 });324 t.is(stdout, multibyteString);325};326327test('Generator handles multibyte characters with Uint8Array', testMultibyte, false, execa);328test('Generator handles multibyte characters with Uint8Array, objectMode', testMultibyte, true, execa);329test('Generator handles multibyte characters with Uint8Array, sync', testMultibyte, false, execaSync);330test('Generator handles multibyte characters with Uint8Array, objectMode, sync', testMultibyte, true, execaSync);331332const testMultibytePartial = async (t, objectMode, execaMethod) => {333 const {stdout} = await execaMethod('stdin.js', {334 stdin: [335 [multibyteUint8Array.slice(0, breakingLength)],336 noopGenerator(objectMode, true),337 ],338 });339 t.is(stdout, `${multibyteChar}${brokenSymbol}`);340};341342test('Generator handles partial multibyte characters with Uint8Array', testMultibytePartial, false, execa);343test('Generator handles partial multibyte characters with Uint8Array, objectMode', testMultibytePartial, true, execa);344test('Generator handles partial multibyte characters with Uint8Array, sync', testMultibytePartial, false, execaSync);345test('Generator handles partial multibyte characters with Uint8Array, objectMode, sync', testMultibytePartial, true, execaSync);346347const testMultibytePartialOutput = async (t, execaMethod) => {348 const {stdout} = await execaMethod('noop.js', {349 stdout: getOutputsGenerator([350 multibyteUint8Array.slice(0, breakingLength),351 multibyteUint8Array.slice(breakingLength),352 ])(false, true),353 });354 t.is(stdout, multibyteString);355};356357test('Generator handles output multibyte characters with Uint8Array', testMultibytePartialOutput, execa);358test('Generator handles output multibyte characters with Uint8Array, sync', testMultibytePartialOutput, execaSync);
added:test/stdio/file-path-error.js+168 added
1import {readFile, writeFile, rm} from 'node:fs/promises';2import {pathToFileURL} from 'node:url';3import test from 'ava';4import {pathExists} from 'path-exists';5import tempfile from 'tempfile';6import {execa, execaSync} from '../../index.js';7import {setFixtureDir} from '../helpers/fixtures-dir.js';8import {identity, getStdio} from '../helpers/stdio.js';9import {foobarString, foobarUppercase} from '../helpers/input.js';10import {outputObjectGenerator, uppercaseGenerator, serializeGenerator, throwingGenerator} from '../helpers/generator.js';11import {getAbsolutePath} from '../helpers/file-path.js';1213setFixtureDir();1415const nonFileUrl = new URL('https://example.com');1617const testStdioNonFileUrl = (t, fdNumber, execaMethod) => {18 t.throws(() => {19 execaMethod('empty.js', getStdio(fdNumber, nonFileUrl));20 }, {message: /pathToFileURL/});21};2223test('inputFile cannot be a non-file URL', testStdioNonFileUrl, 'inputFile', execa);24test('stdin cannot be a non-file URL', testStdioNonFileUrl, 0, execa);25test('stdout cannot be a non-file URL', testStdioNonFileUrl, 1, execa);26test('stderr cannot be a non-file URL', testStdioNonFileUrl, 2, execa);27test('stdio[*] cannot be a non-file URL', testStdioNonFileUrl, 3, execa);28test('inputFile cannot be a non-file URL - sync', testStdioNonFileUrl, 'inputFile', execaSync);29test('stdin cannot be a non-file URL - sync', testStdioNonFileUrl, 0, execaSync);30test('stdout cannot be a non-file URL - sync', testStdioNonFileUrl, 1, execaSync);31test('stderr cannot be a non-file URL - sync', testStdioNonFileUrl, 2, execaSync);32test('stdio[*] cannot be a non-file URL - sync', testStdioNonFileUrl, 3, execaSync);3334const testInvalidInputFile = (t, execaMethod) => {35 t.throws(() => {36 execaMethod('empty.js', getStdio('inputFile', false));37 }, {message: /a file path string or a file URL/});38};3940test('inputFile must be a file URL or string', testInvalidInputFile, execa);41test('inputFile must be a file URL or string - sync', testInvalidInputFile, execaSync);4243const testFilePathObject = (t, fdNumber, execaMethod) => {44 t.throws(() => {45 execaMethod('empty.js', getStdio(fdNumber, foobarString));46 }, {message: /must be used/});47};4849test('stdin must be an object when it is a file path string', testFilePathObject, 0, execa);50test('stdout must be an object when it is a file path string', testFilePathObject, 1, execa);51test('stderr must be an object when it is a file path string', testFilePathObject, 2, execa);52test('stdio[*] must be an object when it is a file path string', testFilePathObject, 3, execa);53test('stdin be an object when it is a file path string - sync', testFilePathObject, 0, execaSync);54test('stdout be an object when it is a file path string - sync', testFilePathObject, 1, execaSync);55test('stderr be an object when it is a file path string - sync', testFilePathObject, 2, execaSync);56test('stdio[*] must be an object when it is a file path string - sync', testFilePathObject, 3, execaSync);5758const testFileError = async (t, fixtureName, mapFile, fdNumber) => {59 await t.throwsAsync(60 execa(fixtureName, [`${fdNumber}`], getStdio(fdNumber, mapFile('./unknown/file'))),61 {code: 'ENOENT'},62 );63};6465test.serial('inputFile file URL errors should be handled', testFileError, 'stdin-fd.js', pathToFileURL, 'inputFile');66test.serial('stdin file URL errors should be handled', testFileError, 'stdin-fd.js', pathToFileURL, 0);67test.serial('stdout file URL errors should be handled', testFileError, 'noop-fd.js', pathToFileURL, 1);68test.serial('stderr file URL errors should be handled', testFileError, 'noop-fd.js', pathToFileURL, 2);69test.serial('stdio[*] file URL errors should be handled', testFileError, 'noop-fd.js', pathToFileURL, 3);70test.serial('inputFile file path errors should be handled', testFileError, 'stdin-fd.js', identity, 'inputFile');71test.serial('stdin file path errors should be handled', testFileError, 'stdin-fd.js', getAbsolutePath, 0);72test.serial('stdout file path errors should be handled', testFileError, 'noop-fd.js', getAbsolutePath, 1);73test.serial('stderr file path errors should be handled', testFileError, 'noop-fd.js', getAbsolutePath, 2);74test.serial('stdio[*] file path errors should be handled', testFileError, 'noop-fd.js', getAbsolutePath, 3);7576const testFileErrorSync = (t, mapFile, fdNumber) => {77 t.throws(() => {78 execaSync('empty.js', getStdio(fdNumber, mapFile('./unknown/file')));79 }, {code: 'ENOENT'});80};8182test('inputFile file URL errors should be handled - sync', testFileErrorSync, pathToFileURL, 'inputFile');83test('stdin file URL errors should be handled - sync', testFileErrorSync, pathToFileURL, 0);84test('stdout file URL errors should be handled - sync', testFileErrorSync, pathToFileURL, 1);85test('stderr file URL errors should be handled - sync', testFileErrorSync, pathToFileURL, 2);86test('stdio[*] file URL errors should be handled - sync', testFileErrorSync, pathToFileURL, 3);87test('inputFile file path errors should be handled - sync', testFileErrorSync, identity, 'inputFile');88test('stdin file path errors should be handled - sync', testFileErrorSync, getAbsolutePath, 0);89test('stdout file path errors should be handled - sync', testFileErrorSync, getAbsolutePath, 1);90test('stderr file path errors should be handled - sync', testFileErrorSync, getAbsolutePath, 2);91test('stdio[*] file path errors should be handled - sync', testFileErrorSync, getAbsolutePath, 3);9293const testInputFileObject = async (t, fdNumber, mapFile, execaMethod) => {94 const filePath = tempfile();95 await writeFile(filePath, foobarString);96 t.throws(() => {97 execaMethod('stdin-fd.js', [`${fdNumber}`], getStdio(fdNumber, [98 new Uint8Array(),99 mapFile(filePath),100 serializeGenerator(true),101 ]));102 }, {message: /cannot use both files and transforms in objectMode/});103 await rm(filePath);104};105106test('stdin cannot use objectMode together with input file paths', testInputFileObject, 0, getAbsolutePath, execa);107test('stdin cannot use objectMode together with input file URLs', testInputFileObject, 0, pathToFileURL, execa);108test('stdio[*] cannot use objectMode together with input file paths', testInputFileObject, 3, getAbsolutePath, execa);109test('stdio[*] cannot use objectMode together with input file URLs', testInputFileObject, 3, pathToFileURL, execa);110test('stdin cannot use objectMode together with input file paths, sync', testInputFileObject, 0, getAbsolutePath, execaSync);111test('stdin cannot use objectMode together with input file URLs, sync', testInputFileObject, 0, pathToFileURL, execaSync);112113const testOutputFileObject = async (t, fdNumber, mapFile, execaMethod) => {114 const filePath = tempfile();115 t.throws(() => {116 execaMethod('noop-fd.js', [`${fdNumber}`, foobarString], getStdio(fdNumber, [117 outputObjectGenerator(),118 mapFile(filePath),119 ]));120 }, {message: /cannot use both files and transforms in objectMode/});121 t.false(await pathExists(filePath));122};123124test('stdout cannot use objectMode together with output file paths', testOutputFileObject, 1, getAbsolutePath, execa);125test('stdout cannot use objectMode together with output file URLs', testOutputFileObject, 1, pathToFileURL, execa);126test('stderr cannot use objectMode together with output file paths', testOutputFileObject, 2, getAbsolutePath, execa);127test('stderr cannot use objectMode together with output file URLs', testOutputFileObject, 2, pathToFileURL, execa);128test('stdio[*] cannot use objectMode together with output file paths', testOutputFileObject, 3, getAbsolutePath, execa);129test('stdio[*] cannot use objectMode together with output file URLs', testOutputFileObject, 3, pathToFileURL, execa);130test('stdout cannot use objectMode together with output file paths, sync', testOutputFileObject, 1, getAbsolutePath, execaSync);131test('stdout cannot use objectMode together with output file URLs, sync', testOutputFileObject, 1, pathToFileURL, execaSync);132test('stderr cannot use objectMode together with output file paths, sync', testOutputFileObject, 2, getAbsolutePath, execaSync);133test('stderr cannot use objectMode together with output file URLs, sync', testOutputFileObject, 2, pathToFileURL, execaSync);134test('stdio[*] cannot use objectMode together with output file paths, sync', testOutputFileObject, 3, getAbsolutePath, execaSync);135test('stdio[*] cannot use objectMode together with output file URLs, sync', testOutputFileObject, 3, pathToFileURL, execaSync);136137test('Generator error stops writing to output file', async t => {138 const filePath = tempfile();139 const cause = new Error(foobarString);140 const error = await t.throwsAsync(execa('noop.js', {141 stdout: [throwingGenerator(cause)(), getAbsolutePath(filePath)],142 }));143 t.is(error.cause, cause);144 t.is(await readFile(filePath, 'utf8'), '');145});146147test('Generator error does not create output file, sync', async t => {148 const filePath = tempfile();149 const cause = new Error(foobarString);150 const error = t.throws(() => {151 execaSync('noop.js', {152 stdout: [throwingGenerator(cause)(), getAbsolutePath(filePath)],153 });154 });155 t.is(error.cause, cause);156 t.false(await pathExists(filePath));157});158159test('Output file error still returns transformed output, sync', async t => {160 const filePath = tempfile();161 const {stdout} = t.throws(() => {162 execaSync('noop-fd.js', ['1', foobarString], {163 stdout: [uppercaseGenerator(), getAbsolutePath('./unknown/file')],164 });165 }, {code: 'ENOENT'});166 t.false(await pathExists(filePath));167 t.is(stdout, foobarUppercase);168});
added:test/stdio/file-path-main.js+155 added
1import {readFile, writeFile, rm} from 'node:fs/promises';2import {dirname, basename} from 'node:path';3import process from 'node:process';4import {pathToFileURL} from 'node:url';5import test from 'ava';6import tempfile from 'tempfile';7import {execa, execaSync} from '../../index.js';8import {setFixtureDir} from '../helpers/fixtures-dir.js';9import {identity, getStdio} from '../helpers/stdio.js';10import {runExeca, runExecaSync, runScript, runScriptSync} from '../helpers/run.js';11import {foobarString, foobarUint8Array} from '../helpers/input.js';12import {getAbsolutePath, getRelativePath} from '../helpers/file-path.js';1314setFixtureDir();1516const getStdioInput = (fdNumberOrName, file) => {17 if (fdNumberOrName === 'string') {18 return {input: foobarString};19 }2021 if (fdNumberOrName === 'binary') {22 return {input: foobarUint8Array};23 }2425 return getStdioInputFile(fdNumberOrName, file);26};2728const getStdioInputFile = (fdNumberOrName, file) => getStdio(fdNumberOrName, typeof fdNumberOrName === 'string' ? file : {file});2930const testStdinFile = async (t, mapFilePath, fdNumber, execaMethod) => {31 const filePath = tempfile();32 await writeFile(filePath, foobarString);33 const {stdout} = await execaMethod('stdin.js', getStdio(fdNumber, mapFilePath(filePath)));34 t.is(stdout, foobarString);35 await rm(filePath);36};3738test('inputFile can be a file URL', testStdinFile, pathToFileURL, 'inputFile', execa);39test('stdin can be a file URL', testStdinFile, pathToFileURL, 0, execa);40test('inputFile can be an absolute file path', testStdinFile, identity, 'inputFile', execa);41test('stdin can be an absolute file path', testStdinFile, getAbsolutePath, 0, execa);42test('inputFile can be a relative file path', testStdinFile, identity, 'inputFile', execa);43test('stdin can be a relative file path', testStdinFile, getRelativePath, 0, execa);44test('inputFile can be a file URL - sync', testStdinFile, pathToFileURL, 'inputFile', execaSync);45test('stdin can be a file URL - sync', testStdinFile, pathToFileURL, 0, execaSync);46test('inputFile can be an absolute file path - sync', testStdinFile, identity, 'inputFile', execaSync);47test('stdin can be an absolute file path - sync', testStdinFile, getAbsolutePath, 0, execaSync);48test('inputFile can be a relative file path - sync', testStdinFile, identity, 'inputFile', execaSync);49test('stdin can be a relative file path - sync', testStdinFile, getRelativePath, 0, execaSync);5051const testOutputFile = async (t, mapFile, fdNumber, execaMethod) => {52 const filePath = tempfile();53 await execaMethod('noop-fd.js', [`${fdNumber}`, foobarString], getStdio(fdNumber, mapFile(filePath)));54 t.is(await readFile(filePath, 'utf8'), foobarString);55 await rm(filePath);56};5758test('stdout can be a file URL', testOutputFile, pathToFileURL, 1, execa);59test('stderr can be a file URL', testOutputFile, pathToFileURL, 2, execa);60test('stdio[*] can be a file URL', testOutputFile, pathToFileURL, 3, execa);61test('stdout can be an absolute file path', testOutputFile, getAbsolutePath, 1, execa);62test('stderr can be an absolute file path', testOutputFile, getAbsolutePath, 2, execa);63test('stdio[*] can be an absolute file path', testOutputFile, getAbsolutePath, 3, execa);64test('stdout can be a relative file path', testOutputFile, getRelativePath, 1, execa);65test('stderr can be a relative file path', testOutputFile, getRelativePath, 2, execa);66test('stdio[*] can be a relative file path', testOutputFile, getRelativePath, 3, execa);67test('stdout can be a file URL - sync', testOutputFile, pathToFileURL, 1, execaSync);68test('stderr can be a file URL - sync', testOutputFile, pathToFileURL, 2, execaSync);69test('stdio[*] can be a file URL - sync', testOutputFile, pathToFileURL, 3, execaSync);70test('stdout can be an absolute file path - sync', testOutputFile, getAbsolutePath, 1, execaSync);71test('stderr can be an absolute file path - sync', testOutputFile, getAbsolutePath, 2, execaSync);72test('stdio[*] can be an absolute file path - sync', testOutputFile, getAbsolutePath, 3, execaSync);73test('stdout can be a relative file path - sync', testOutputFile, getRelativePath, 1, execaSync);74test('stderr can be a relative file path - sync', testOutputFile, getRelativePath, 2, execaSync);75test('stdio[*] can be a relative file path - sync', testOutputFile, getRelativePath, 3, execaSync);7677const testInputFileValidUrl = async (t, fdNumber, execaMethod) => {78 const filePath = tempfile();79 await writeFile(filePath, foobarString);80 const currentCwd = process.cwd();81 process.chdir(dirname(filePath));8283 try {84 const {stdout} = await execaMethod('stdin.js', getStdioInputFile(fdNumber, basename(filePath)));85 t.is(stdout, foobarString);86 } finally {87 process.chdir(currentCwd);88 await rm(filePath);89 }90};9192test.serial('inputFile does not need to start with . when being a relative file path', testInputFileValidUrl, 'inputFile', execa);93test.serial('stdin does not need to start with . when being a relative file path', testInputFileValidUrl, 0, execa);94test.serial('inputFile does not need to start with . when being a relative file path - sync', testInputFileValidUrl, 'inputFile', execaSync);95test.serial('stdin does not need to start with . when being a relative file path - sync', testInputFileValidUrl, 0, execaSync);9697const testMultipleInputs = async (t, indices, execaMethod) => {98 const filePath = tempfile();99 await writeFile(filePath, foobarString);100 const options = Object.assign({}, ...indices.map(fdNumber => getStdioInput(fdNumber, filePath)));101 const {stdout} = await execaMethod('stdin.js', options);102 t.is(stdout, foobarString.repeat(indices.length));103 await rm(filePath);104};105106test('inputFile can be set', testMultipleInputs, ['inputFile'], runExeca);107test('inputFile can be set - sync', testMultipleInputs, ['inputFile'], runExecaSync);108test('inputFile can be set with $', testMultipleInputs, ['inputFile'], runScript);109test('inputFile can be set with $.sync', testMultipleInputs, ['inputFile'], runScriptSync);110test('input String and inputFile can be both set', testMultipleInputs, ['inputFile', 'string'], execa);111test('input String and stdin can be both set', testMultipleInputs, [0, 'string'], execa);112test('input Uint8Array and inputFile can be both set', testMultipleInputs, ['inputFile', 'binary'], execa);113test('input Uint8Array and stdin can be both set', testMultipleInputs, [0, 'binary'], execa);114test('stdin and inputFile can be both set', testMultipleInputs, [0, 'inputFile'], execa);115test('input String, stdin and inputFile can be all set', testMultipleInputs, ['inputFile', 0, 'string'], execa);116test('input Uint8Array, stdin and inputFile can be all set', testMultipleInputs, ['inputFile', 0, 'binary'], execa);117test('input String and inputFile can be both set - sync', testMultipleInputs, ['inputFile', 'string'], execaSync);118test('input String and stdin can be both set - sync', testMultipleInputs, [0, 'string'], execaSync);119test('input Uint8Array and inputFile can be both set - sync', testMultipleInputs, ['inputFile', 'binary'], execaSync);120test('input Uint8Array and stdin can be both set - sync', testMultipleInputs, [0, 'binary'], execaSync);121test('stdin and inputFile can be both set - sync', testMultipleInputs, [0, 'inputFile'], execaSync);122test('input String, stdin and inputFile can be all set - sync', testMultipleInputs, ['inputFile', 0, 'string'], execaSync);123test('input Uint8Array, stdin and inputFile can be all set - sync', testMultipleInputs, ['inputFile', 0, 'binary'], execaSync);124125const testMultipleOutputs = async (t, mapFile, fdNumber, execaMethod) => {126 const filePath = tempfile();127 const filePathTwo = tempfile();128 await execaMethod('noop-fd.js', [`${fdNumber}`, foobarString], getStdio(fdNumber, [mapFile(filePath), mapFile(filePathTwo)]));129 t.is(await readFile(filePath, 'utf8'), foobarString);130 t.is(await readFile(filePathTwo, 'utf8'), foobarString);131 await Promise.all([rm(filePath), rm(filePathTwo)]);132};133134test('stdout can be two file URLs', testMultipleOutputs, pathToFileURL, 1, execa);135test('stdout can be two file paths', testMultipleOutputs, getAbsolutePath, 1, execa);136test('stdout can be two file URLs - sync', testMultipleOutputs, pathToFileURL, 1, execaSync);137test('stdout can be two file paths - sync', testMultipleOutputs, getAbsolutePath, 1, execaSync);138test('stderr can be two file URLs', testMultipleOutputs, pathToFileURL, 2, execa);139test('stderr can be two file paths', testMultipleOutputs, getAbsolutePath, 2, execa);140test('stderr can be two file URLs - sync', testMultipleOutputs, pathToFileURL, 2, execaSync);141test('stderr can be two file paths - sync', testMultipleOutputs, getAbsolutePath, 2, execaSync);142test('stdio[*] can be two file URLs', testMultipleOutputs, pathToFileURL, 3, execa);143test('stdio[*] can be two file paths', testMultipleOutputs, getAbsolutePath, 3, execa);144test('stdio[*] can be two file URLs - sync', testMultipleOutputs, pathToFileURL, 3, execaSync);145test('stdio[*] can be two file paths - sync', testMultipleOutputs, getAbsolutePath, 3, execaSync);146147const testInputFileHanging = async (t, mapFilePath) => {148 const filePath = tempfile();149 await writeFile(filePath, foobarString);150 await t.throwsAsync(execa('stdin.js', {stdin: mapFilePath(filePath), timeout: 1}), {message: /timed out/});151 await rm(filePath);152};153154test('Passing an input file path when subprocess exits does not make promise hang', testInputFileHanging, getAbsolutePath);155test('Passing an input file URL when subprocess exits does not make promise hang', testInputFileHanging, pathToFileURL);
added:test/stdio/file-path-mixed.js+94 added
1import {readFile, writeFile, rm} from 'node:fs/promises';2import {pathToFileURL} from 'node:url';3import test from 'ava';4import tempfile from 'tempfile';5import {execa, execaSync} from '../../index.js';6import {setFixtureDir} from '../helpers/fixtures-dir.js';7import {getStdio} from '../helpers/stdio.js';8import {foobarString, foobarUppercase} from '../helpers/input.js';9import {uppercaseGenerator} from '../helpers/generator.js';10import {getAbsolutePath} from '../helpers/file-path.js';1112setFixtureDir();1314const testInputFileTransform = async (t, fdNumber, mapFile, execaMethod) => {15 const filePath = tempfile();16 await writeFile(filePath, foobarString);17 const {stdout} = await execaMethod('stdin-fd.js', [`${fdNumber}`], getStdio(fdNumber, [18 new Uint8Array(),19 mapFile(filePath),20 uppercaseGenerator(),21 ]));22 t.is(stdout, foobarUppercase);23 await rm(filePath);24};2526test('stdin can use generators together with input file paths', testInputFileTransform, 0, getAbsolutePath, execa);27test('stdin can use generators together with input file URLs', testInputFileTransform, 0, pathToFileURL, execa);28test('stdio[*] can use generators together with input file paths', testInputFileTransform, 3, getAbsolutePath, execa);29test('stdio[*] can use generators together with input file URLs', testInputFileTransform, 3, pathToFileURL, execa);30test('stdin can use generators together with input file paths, sync', testInputFileTransform, 0, getAbsolutePath, execaSync);31test('stdin can use generators together with input file URLs, sync', testInputFileTransform, 0, pathToFileURL, execaSync);3233const testOutputFileTransform = async (t, fdNumber, mapFile, execaMethod) => {34 const filePath = tempfile();35 await execaMethod('noop-fd.js', [`${fdNumber}`, foobarString], getStdio(fdNumber, [36 uppercaseGenerator(),37 mapFile(filePath),38 ]));39 t.is(await readFile(filePath, 'utf8'), `${foobarUppercase}\n`);40 await rm(filePath);41};4243test('stdout can use generators together with output file paths', testOutputFileTransform, 1, getAbsolutePath, execa);44test('stdout can use generators together with output file URLs', testOutputFileTransform, 1, pathToFileURL, execa);45test('stderr can use generators together with output file paths', testOutputFileTransform, 2, getAbsolutePath, execa);46test('stderr can use generators together with output file URLs', testOutputFileTransform, 2, pathToFileURL, execa);47test('stdio[*] can use generators together with output file paths', testOutputFileTransform, 3, getAbsolutePath, execa);48test('stdio[*] can use generators together with output file URLs', testOutputFileTransform, 3, pathToFileURL, execa);49test('stdout can use generators together with output file paths, sync', testOutputFileTransform, 1, getAbsolutePath, execaSync);50test('stdout can use generators together with output file URLs, sync', testOutputFileTransform, 1, pathToFileURL, execaSync);51test('stderr can use generators together with output file paths, sync', testOutputFileTransform, 2, getAbsolutePath, execaSync);52test('stderr can use generators together with output file URLs, sync', testOutputFileTransform, 2, pathToFileURL, execaSync);53test('stdio[*] can use generators together with output file paths, sync', testOutputFileTransform, 3, getAbsolutePath, execaSync);54test('stdio[*] can use generators together with output file URLs, sync', testOutputFileTransform, 3, pathToFileURL, execaSync);5556const testOutputFileLines = async (t, fdNumber, mapFile, execaMethod) => {57 const filePath = tempfile();58 const {stdio} = await execaMethod('noop-fd.js', [`${fdNumber}`, foobarString], {59 ...getStdio(fdNumber, mapFile(filePath)),60 lines: true,61 });62 t.deepEqual(stdio[fdNumber], [foobarString]);63 t.is(await readFile(filePath, 'utf8'), foobarString);64 await rm(filePath);65};6667test('stdout can use "lines: true" together with output file paths', testOutputFileLines, 1, getAbsolutePath, execa);68test('stdout can use "lines: true" together with output file URLs', testOutputFileLines, 1, pathToFileURL, execa);69test('stderr can use "lines: true" together with output file paths', testOutputFileLines, 2, getAbsolutePath, execa);70test('stderr can use "lines: true" together with output file URLs', testOutputFileLines, 2, pathToFileURL, execa);71test('stdio[*] can use "lines: true" together with output file paths', testOutputFileLines, 3, getAbsolutePath, execa);72test('stdio[*] can use "lines: true" together with output file URLs', testOutputFileLines, 3, pathToFileURL, execa);73test('stdout can use "lines: true" together with output file paths, sync', testOutputFileLines, 1, getAbsolutePath, execaSync);74test('stdout can use "lines: true" together with output file URLs, sync', testOutputFileLines, 1, pathToFileURL, execaSync);75test('stderr can use "lines: true" together with output file paths, sync', testOutputFileLines, 2, getAbsolutePath, execaSync);76test('stderr can use "lines: true" together with output file URLs, sync', testOutputFileLines, 2, pathToFileURL, execaSync);77test('stdio[*] can use "lines: true" together with output file paths, sync', testOutputFileLines, 3, getAbsolutePath, execaSync);78test('stdio[*] can use "lines: true" together with output file URLs, sync', testOutputFileLines, 3, pathToFileURL, execaSync);7980const testOutputFileNoBuffer = async (t, buffer, execaMethod) => {81 const filePath = tempfile();82 const {stdout} = await execaMethod('noop-fd.js', ['1', foobarString], {83 stdout: getAbsolutePath(filePath),84 buffer,85 });86 t.is(stdout, undefined);87 t.is(await readFile(filePath, 'utf8'), foobarString);88 await rm(filePath);89};9091test('stdout can use "buffer: false" together with output file paths', testOutputFileNoBuffer, false, execa);92test('stdout can use "buffer: false" together with output file paths, fd-specific', testOutputFileNoBuffer, {stdout: false}, execa);93test('stdout can use "buffer: false" together with output file paths, sync', testOutputFileNoBuffer, false, execaSync);94test('stdout can use "buffer: false" together with output file paths, fd-specific, sync', testOutputFileNoBuffer, {stdout: false}, execaSync);
deleted:test/stdio/file-path.js-396 removed
1import {readFile, writeFile, rm} from 'node:fs/promises';2import {relative, dirname, basename} from 'node:path';3import process from 'node:process';4import {pathToFileURL} from 'node:url';5import test from 'ava';6import {pathExists} from 'path-exists';7import tempfile from 'tempfile';8import {execa, execaSync} from '../../index.js';9import {setFixtureDir} from '../helpers/fixtures-dir.js';10import {identity, getStdio} from '../helpers/stdio.js';11import {runExeca, runExecaSync, runScript, runScriptSync} from '../helpers/run.js';12import {foobarString, foobarUint8Array, foobarUppercase} from '../helpers/input.js';13import {outputObjectGenerator, uppercaseGenerator, serializeGenerator, throwingGenerator} from '../helpers/generator.js';1415setFixtureDir();1617const nonFileUrl = new URL('https://example.com');1819const getAbsolutePath = file => ({file});20const getRelativePath = filePath => ({file: relative('.', filePath)});2122const getStdioInput = (fdNumberOrName, file) => {23 if (fdNumberOrName === 'string') {24 return {input: foobarString};25 }2627 if (fdNumberOrName === 'binary') {28 return {input: foobarUint8Array};29 }3031 return getStdioInputFile(fdNumberOrName, file);32};3334const getStdioInputFile = (fdNumberOrName, file) => getStdio(fdNumberOrName, typeof fdNumberOrName === 'string' ? file : {file});3536const testStdinFile = async (t, mapFilePath, fdNumber, execaMethod) => {37 const filePath = tempfile();38 await writeFile(filePath, foobarString);39 const {stdout} = await execaMethod('stdin.js', getStdio(fdNumber, mapFilePath(filePath)));40 t.is(stdout, foobarString);41 await rm(filePath);42};4344test('inputFile can be a file URL', testStdinFile, pathToFileURL, 'inputFile', execa);45test('stdin can be a file URL', testStdinFile, pathToFileURL, 0, execa);46test('inputFile can be an absolute file path', testStdinFile, identity, 'inputFile', execa);47test('stdin can be an absolute file path', testStdinFile, getAbsolutePath, 0, execa);48test('inputFile can be a relative file path', testStdinFile, identity, 'inputFile', execa);49test('stdin can be a relative file path', testStdinFile, getRelativePath, 0, execa);50test('inputFile can be a file URL - sync', testStdinFile, pathToFileURL, 'inputFile', execaSync);51test('stdin can be a file URL - sync', testStdinFile, pathToFileURL, 0, execaSync);52test('inputFile can be an absolute file path - sync', testStdinFile, identity, 'inputFile', execaSync);53test('stdin can be an absolute file path - sync', testStdinFile, getAbsolutePath, 0, execaSync);54test('inputFile can be a relative file path - sync', testStdinFile, identity, 'inputFile', execaSync);55test('stdin can be a relative file path - sync', testStdinFile, getRelativePath, 0, execaSync);5657const testOutputFile = async (t, mapFile, fdNumber, execaMethod) => {58 const filePath = tempfile();59 await execaMethod('noop-fd.js', [`${fdNumber}`, foobarString], getStdio(fdNumber, mapFile(filePath)));60 t.is(await readFile(filePath, 'utf8'), foobarString);61 await rm(filePath);62};6364test('stdout can be a file URL', testOutputFile, pathToFileURL, 1, execa);65test('stderr can be a file URL', testOutputFile, pathToFileURL, 2, execa);66test('stdio[*] can be a file URL', testOutputFile, pathToFileURL, 3, execa);67test('stdout can be an absolute file path', testOutputFile, getAbsolutePath, 1, execa);68test('stderr can be an absolute file path', testOutputFile, getAbsolutePath, 2, execa);69test('stdio[*] can be an absolute file path', testOutputFile, getAbsolutePath, 3, execa);70test('stdout can be a relative file path', testOutputFile, getRelativePath, 1, execa);71test('stderr can be a relative file path', testOutputFile, getRelativePath, 2, execa);72test('stdio[*] can be a relative file path', testOutputFile, getRelativePath, 3, execa);73test('stdout can be a file URL - sync', testOutputFile, pathToFileURL, 1, execaSync);74test('stderr can be a file URL - sync', testOutputFile, pathToFileURL, 2, execaSync);75test('stdio[*] can be a file URL - sync', testOutputFile, pathToFileURL, 3, execaSync);76test('stdout can be an absolute file path - sync', testOutputFile, getAbsolutePath, 1, execaSync);77test('stderr can be an absolute file path - sync', testOutputFile, getAbsolutePath, 2, execaSync);78test('stdio[*] can be an absolute file path - sync', testOutputFile, getAbsolutePath, 3, execaSync);79test('stdout can be a relative file path - sync', testOutputFile, getRelativePath, 1, execaSync);80test('stderr can be a relative file path - sync', testOutputFile, getRelativePath, 2, execaSync);81test('stdio[*] can be a relative file path - sync', testOutputFile, getRelativePath, 3, execaSync);8283const testStdioNonFileUrl = (t, fdNumber, execaMethod) => {84 t.throws(() => {85 execaMethod('empty.js', getStdio(fdNumber, nonFileUrl));86 }, {message: /pathToFileURL/});87};8889test('inputFile cannot be a non-file URL', testStdioNonFileUrl, 'inputFile', execa);90test('stdin cannot be a non-file URL', testStdioNonFileUrl, 0, execa);91test('stdout cannot be a non-file URL', testStdioNonFileUrl, 1, execa);92test('stderr cannot be a non-file URL', testStdioNonFileUrl, 2, execa);93test('stdio[*] cannot be a non-file URL', testStdioNonFileUrl, 3, execa);94test('inputFile cannot be a non-file URL - sync', testStdioNonFileUrl, 'inputFile', execaSync);95test('stdin cannot be a non-file URL - sync', testStdioNonFileUrl, 0, execaSync);96test('stdout cannot be a non-file URL - sync', testStdioNonFileUrl, 1, execaSync);97test('stderr cannot be a non-file URL - sync', testStdioNonFileUrl, 2, execaSync);98test('stdio[*] cannot be a non-file URL - sync', testStdioNonFileUrl, 3, execaSync);99100const testInvalidInputFile = (t, execaMethod) => {101 t.throws(() => {102 execaMethod('empty.js', getStdio('inputFile', false));103 }, {message: /a file path string or a file URL/});104};105106test('inputFile must be a file URL or string', testInvalidInputFile, execa);107test('inputFile must be a file URL or string - sync', testInvalidInputFile, execaSync);108109const testInputFileValidUrl = async (t, fdNumber, execaMethod) => {110 const filePath = tempfile();111 await writeFile(filePath, foobarString);112 const currentCwd = process.cwd();113 process.chdir(dirname(filePath));114115 try {116 const {stdout} = await execaMethod('stdin.js', getStdioInputFile(fdNumber, basename(filePath)));117 t.is(stdout, foobarString);118 } finally {119 process.chdir(currentCwd);120 await rm(filePath);121 }122};123124test.serial('inputFile does not need to start with . when being a relative file path', testInputFileValidUrl, 'inputFile', execa);125test.serial('stdin does not need to start with . when being a relative file path', testInputFileValidUrl, 0, execa);126test.serial('inputFile does not need to start with . when being a relative file path - sync', testInputFileValidUrl, 'inputFile', execaSync);127test.serial('stdin does not need to start with . when being a relative file path - sync', testInputFileValidUrl, 0, execaSync);128129const testFilePathObject = (t, fdNumber, execaMethod) => {130 t.throws(() => {131 execaMethod('empty.js', getStdio(fdNumber, foobarString));132 }, {message: /must be used/});133};134135test('stdin must be an object when it is a file path string', testFilePathObject, 0, execa);136test('stdout must be an object when it is a file path string', testFilePathObject, 1, execa);137test('stderr must be an object when it is a file path string', testFilePathObject, 2, execa);138test('stdio[*] must be an object when it is a file path string', testFilePathObject, 3, execa);139test('stdin be an object when it is a file path string - sync', testFilePathObject, 0, execaSync);140test('stdout be an object when it is a file path string - sync', testFilePathObject, 1, execaSync);141test('stderr be an object when it is a file path string - sync', testFilePathObject, 2, execaSync);142test('stdio[*] must be an object when it is a file path string - sync', testFilePathObject, 3, execaSync);143144const testFileError = async (t, fixtureName, mapFile, fdNumber) => {145 await t.throwsAsync(146 execa(fixtureName, [`${fdNumber}`], getStdio(fdNumber, mapFile('./unknown/file'))),147 {code: 'ENOENT'},148 );149};150151test.serial('inputFile file URL errors should be handled', testFileError, 'stdin-fd.js', pathToFileURL, 'inputFile');152test.serial('stdin file URL errors should be handled', testFileError, 'stdin-fd.js', pathToFileURL, 0);153test.serial('stdout file URL errors should be handled', testFileError, 'noop-fd.js', pathToFileURL, 1);154test.serial('stderr file URL errors should be handled', testFileError, 'noop-fd.js', pathToFileURL, 2);155test.serial('stdio[*] file URL errors should be handled', testFileError, 'noop-fd.js', pathToFileURL, 3);156test.serial('inputFile file path errors should be handled', testFileError, 'stdin-fd.js', identity, 'inputFile');157test.serial('stdin file path errors should be handled', testFileError, 'stdin-fd.js', getAbsolutePath, 0);158test.serial('stdout file path errors should be handled', testFileError, 'noop-fd.js', getAbsolutePath, 1);159test.serial('stderr file path errors should be handled', testFileError, 'noop-fd.js', getAbsolutePath, 2);160test.serial('stdio[*] file path errors should be handled', testFileError, 'noop-fd.js', getAbsolutePath, 3);161162const testFileErrorSync = (t, mapFile, fdNumber) => {163 t.throws(() => {164 execaSync('empty.js', getStdio(fdNumber, mapFile('./unknown/file')));165 }, {code: 'ENOENT'});166};167168test('inputFile file URL errors should be handled - sync', testFileErrorSync, pathToFileURL, 'inputFile');169test('stdin file URL errors should be handled - sync', testFileErrorSync, pathToFileURL, 0);170test('stdout file URL errors should be handled - sync', testFileErrorSync, pathToFileURL, 1);171test('stderr file URL errors should be handled - sync', testFileErrorSync, pathToFileURL, 2);172test('stdio[*] file URL errors should be handled - sync', testFileErrorSync, pathToFileURL, 3);173test('inputFile file path errors should be handled - sync', testFileErrorSync, identity, 'inputFile');174test('stdin file path errors should be handled - sync', testFileErrorSync, getAbsolutePath, 0);175test('stdout file path errors should be handled - sync', testFileErrorSync, getAbsolutePath, 1);176test('stderr file path errors should be handled - sync', testFileErrorSync, getAbsolutePath, 2);177test('stdio[*] file path errors should be handled - sync', testFileErrorSync, getAbsolutePath, 3);178179const testMultipleInputs = async (t, indices, execaMethod) => {180 const filePath = tempfile();181 await writeFile(filePath, foobarString);182 const options = Object.assign({}, ...indices.map(fdNumber => getStdioInput(fdNumber, filePath)));183 const {stdout} = await execaMethod('stdin.js', options);184 t.is(stdout, foobarString.repeat(indices.length));185 await rm(filePath);186};187188test('inputFile can be set', testMultipleInputs, ['inputFile'], runExeca);189test('inputFile can be set - sync', testMultipleInputs, ['inputFile'], runExecaSync);190test('inputFile can be set with $', testMultipleInputs, ['inputFile'], runScript);191test('inputFile can be set with $.sync', testMultipleInputs, ['inputFile'], runScriptSync);192test('input String and inputFile can be both set', testMultipleInputs, ['inputFile', 'string'], execa);193test('input String and stdin can be both set', testMultipleInputs, [0, 'string'], execa);194test('input Uint8Array and inputFile can be both set', testMultipleInputs, ['inputFile', 'binary'], execa);195test('input Uint8Array and stdin can be both set', testMultipleInputs, [0, 'binary'], execa);196test('stdin and inputFile can be both set', testMultipleInputs, [0, 'inputFile'], execa);197test('input String, stdin and inputFile can be all set', testMultipleInputs, ['inputFile', 0, 'string'], execa);198test('input Uint8Array, stdin and inputFile can be all set', testMultipleInputs, ['inputFile', 0, 'binary'], execa);199test('input String and inputFile can be both set - sync', testMultipleInputs, ['inputFile', 'string'], execaSync);200test('input String and stdin can be both set - sync', testMultipleInputs, [0, 'string'], execaSync);201test('input Uint8Array and inputFile can be both set - sync', testMultipleInputs, ['inputFile', 'binary'], execaSync);202test('input Uint8Array and stdin can be both set - sync', testMultipleInputs, [0, 'binary'], execaSync);203test('stdin and inputFile can be both set - sync', testMultipleInputs, [0, 'inputFile'], execaSync);204test('input String, stdin and inputFile can be all set - sync', testMultipleInputs, ['inputFile', 0, 'string'], execaSync);205test('input Uint8Array, stdin and inputFile can be all set - sync', testMultipleInputs, ['inputFile', 0, 'binary'], execaSync);206207const testMultipleOutputs = async (t, mapFile, fdNumber, execaMethod) => {208 const filePath = tempfile();209 const filePathTwo = tempfile();210 await execaMethod('noop-fd.js', [`${fdNumber}`, foobarString], getStdio(fdNumber, [mapFile(filePath), mapFile(filePathTwo)]));211 t.is(await readFile(filePath, 'utf8'), foobarString);212 t.is(await readFile(filePathTwo, 'utf8'), foobarString);213 await Promise.all([rm(filePath), rm(filePathTwo)]);214};215216test('stdout can be two file URLs', testMultipleOutputs, pathToFileURL, 1, execa);217test('stdout can be two file paths', testMultipleOutputs, getAbsolutePath, 1, execa);218test('stdout can be two file URLs - sync', testMultipleOutputs, pathToFileURL, 1, execaSync);219test('stdout can be two file paths - sync', testMultipleOutputs, getAbsolutePath, 1, execaSync);220test('stderr can be two file URLs', testMultipleOutputs, pathToFileURL, 2, execa);221test('stderr can be two file paths', testMultipleOutputs, getAbsolutePath, 2, execa);222test('stderr can be two file URLs - sync', testMultipleOutputs, pathToFileURL, 2, execaSync);223test('stderr can be two file paths - sync', testMultipleOutputs, getAbsolutePath, 2, execaSync);224test('stdio[*] can be two file URLs', testMultipleOutputs, pathToFileURL, 3, execa);225test('stdio[*] can be two file paths', testMultipleOutputs, getAbsolutePath, 3, execa);226test('stdio[*] can be two file URLs - sync', testMultipleOutputs, pathToFileURL, 3, execaSync);227test('stdio[*] can be two file paths - sync', testMultipleOutputs, getAbsolutePath, 3, execaSync);228229const testInputFileHanging = async (t, mapFilePath) => {230 const filePath = tempfile();231 await writeFile(filePath, foobarString);232 await t.throwsAsync(execa('stdin.js', {stdin: mapFilePath(filePath), timeout: 1}), {message: /timed out/});233 await rm(filePath);234};235236test('Passing an input file path when subprocess exits does not make promise hang', testInputFileHanging, getAbsolutePath);237test('Passing an input file URL when subprocess exits does not make promise hang', testInputFileHanging, pathToFileURL);238239const testInputFileTransform = async (t, fdNumber, mapFile, execaMethod) => {240 const filePath = tempfile();241 await writeFile(filePath, foobarString);242 const {stdout} = await execaMethod('stdin-fd.js', [`${fdNumber}`], getStdio(fdNumber, [243 new Uint8Array(),244 mapFile(filePath),245 uppercaseGenerator(),246 ]));247 t.is(stdout, foobarUppercase);248 await rm(filePath);249};250251test('stdin can use generators together with input file paths', testInputFileTransform, 0, getAbsolutePath, execa);252test('stdin can use generators together with input file URLs', testInputFileTransform, 0, pathToFileURL, execa);253test('stdio[*] can use generators together with input file paths', testInputFileTransform, 3, getAbsolutePath, execa);254test('stdio[*] can use generators together with input file URLs', testInputFileTransform, 3, pathToFileURL, execa);255test('stdin can use generators together with input file paths, sync', testInputFileTransform, 0, getAbsolutePath, execaSync);256test('stdin can use generators together with input file URLs, sync', testInputFileTransform, 0, pathToFileURL, execaSync);257258const testInputFileObject = async (t, fdNumber, mapFile, execaMethod) => {259 const filePath = tempfile();260 await writeFile(filePath, foobarString);261 t.throws(() => {262 execaMethod('stdin-fd.js', [`${fdNumber}`], getStdio(fdNumber, [263 new Uint8Array(),264 mapFile(filePath),265 serializeGenerator(true),266 ]));267 }, {message: /cannot use both files and transforms in objectMode/});268 await rm(filePath);269};270271test('stdin cannot use objectMode together with input file paths', testInputFileObject, 0, getAbsolutePath, execa);272test('stdin cannot use objectMode together with input file URLs', testInputFileObject, 0, pathToFileURL, execa);273test('stdio[*] cannot use objectMode together with input file paths', testInputFileObject, 3, getAbsolutePath, execa);274test('stdio[*] cannot use objectMode together with input file URLs', testInputFileObject, 3, pathToFileURL, execa);275test('stdin cannot use objectMode together with input file paths, sync', testInputFileObject, 0, getAbsolutePath, execaSync);276test('stdin cannot use objectMode together with input file URLs, sync', testInputFileObject, 0, pathToFileURL, execaSync);277278const testOutputFileTransform = async (t, fdNumber, mapFile, execaMethod) => {279 const filePath = tempfile();280 await execaMethod('noop-fd.js', [`${fdNumber}`, foobarString], getStdio(fdNumber, [281 uppercaseGenerator(),282 mapFile(filePath),283 ]));284 t.is(await readFile(filePath, 'utf8'), `${foobarUppercase}\n`);285 await rm(filePath);286};287288test('stdout can use generators together with output file paths', testOutputFileTransform, 1, getAbsolutePath, execa);289test('stdout can use generators together with output file URLs', testOutputFileTransform, 1, pathToFileURL, execa);290test('stderr can use generators together with output file paths', testOutputFileTransform, 2, getAbsolutePath, execa);291test('stderr can use generators together with output file URLs', testOutputFileTransform, 2, pathToFileURL, execa);292test('stdio[*] can use generators together with output file paths', testOutputFileTransform, 3, getAbsolutePath, execa);293test('stdio[*] can use generators together with output file URLs', testOutputFileTransform, 3, pathToFileURL, execa);294test('stdout can use generators together with output file paths, sync', testOutputFileTransform, 1, getAbsolutePath, execaSync);295test('stdout can use generators together with output file URLs, sync', testOutputFileTransform, 1, pathToFileURL, execaSync);296test('stderr can use generators together with output file paths, sync', testOutputFileTransform, 2, getAbsolutePath, execaSync);297test('stderr can use generators together with output file URLs, sync', testOutputFileTransform, 2, pathToFileURL, execaSync);298test('stdio[*] can use generators together with output file paths, sync', testOutputFileTransform, 3, getAbsolutePath, execaSync);299test('stdio[*] can use generators together with output file URLs, sync', testOutputFileTransform, 3, pathToFileURL, execaSync);300301const testOutputFileLines = async (t, fdNumber, mapFile, execaMethod) => {302 const filePath = tempfile();303 const {stdio} = await execaMethod('noop-fd.js', [`${fdNumber}`, foobarString], {304 ...getStdio(fdNumber, mapFile(filePath)),305 lines: true,306 });307 t.deepEqual(stdio[fdNumber], [foobarString]);308 t.is(await readFile(filePath, 'utf8'), foobarString);309 await rm(filePath);310};311312test('stdout can use "lines: true" together with output file paths', testOutputFileLines, 1, getAbsolutePath, execa);313test('stdout can use "lines: true" together with output file URLs', testOutputFileLines, 1, pathToFileURL, execa);314test('stderr can use "lines: true" together with output file paths', testOutputFileLines, 2, getAbsolutePath, execa);315test('stderr can use "lines: true" together with output file URLs', testOutputFileLines, 2, pathToFileURL, execa);316test('stdio[*] can use "lines: true" together with output file paths', testOutputFileLines, 3, getAbsolutePath, execa);317test('stdio[*] can use "lines: true" together with output file URLs', testOutputFileLines, 3, pathToFileURL, execa);318test('stdout can use "lines: true" together with output file paths, sync', testOutputFileLines, 1, getAbsolutePath, execaSync);319test('stdout can use "lines: true" together with output file URLs, sync', testOutputFileLines, 1, pathToFileURL, execaSync);320test('stderr can use "lines: true" together with output file paths, sync', testOutputFileLines, 2, getAbsolutePath, execaSync);321test('stderr can use "lines: true" together with output file URLs, sync', testOutputFileLines, 2, pathToFileURL, execaSync);322test('stdio[*] can use "lines: true" together with output file paths, sync', testOutputFileLines, 3, getAbsolutePath, execaSync);323test('stdio[*] can use "lines: true" together with output file URLs, sync', testOutputFileLines, 3, pathToFileURL, execaSync);324325const testOutputFileNoBuffer = async (t, buffer, execaMethod) => {326 const filePath = tempfile();327 const {stdout} = await execaMethod('noop-fd.js', ['1', foobarString], {328 stdout: getAbsolutePath(filePath),329 buffer,330 });331 t.is(stdout, undefined);332 t.is(await readFile(filePath, 'utf8'), foobarString);333 await rm(filePath);334};335336test('stdout can use "buffer: false" together with output file paths', testOutputFileNoBuffer, false, execa);337test('stdout can use "buffer: false" together with output file paths, fd-specific', testOutputFileNoBuffer, {stdout: false}, execa);338test('stdout can use "buffer: false" together with output file paths, sync', testOutputFileNoBuffer, false, execaSync);339test('stdout can use "buffer: false" together with output file paths, fd-specific, sync', testOutputFileNoBuffer, {stdout: false}, execaSync);340341const testOutputFileObject = async (t, fdNumber, mapFile, execaMethod) => {342 const filePath = tempfile();343 t.throws(() => {344 execaMethod('noop-fd.js', [`${fdNumber}`, foobarString], getStdio(fdNumber, [345 outputObjectGenerator(),346 mapFile(filePath),347 ]));348 }, {message: /cannot use both files and transforms in objectMode/});349 t.false(await pathExists(filePath));350};351352test('stdout cannot use objectMode together with output file paths', testOutputFileObject, 1, getAbsolutePath, execa);353test('stdout cannot use objectMode together with output file URLs', testOutputFileObject, 1, pathToFileURL, execa);354test('stderr cannot use objectMode together with output file paths', testOutputFileObject, 2, getAbsolutePath, execa);355test('stderr cannot use objectMode together with output file URLs', testOutputFileObject, 2, pathToFileURL, execa);356test('stdio[*] cannot use objectMode together with output file paths', testOutputFileObject, 3, getAbsolutePath, execa);357test('stdio[*] cannot use objectMode together with output file URLs', testOutputFileObject, 3, pathToFileURL, execa);358test('stdout cannot use objectMode together with output file paths, sync', testOutputFileObject, 1, getAbsolutePath, execaSync);359test('stdout cannot use objectMode together with output file URLs, sync', testOutputFileObject, 1, pathToFileURL, execaSync);360test('stderr cannot use objectMode together with output file paths, sync', testOutputFileObject, 2, getAbsolutePath, execaSync);361test('stderr cannot use objectMode together with output file URLs, sync', testOutputFileObject, 2, pathToFileURL, execaSync);362test('stdio[*] cannot use objectMode together with output file paths, sync', testOutputFileObject, 3, getAbsolutePath, execaSync);363test('stdio[*] cannot use objectMode together with output file URLs, sync', testOutputFileObject, 3, pathToFileURL, execaSync);364365test('Generator error stops writing to output file', async t => {366 const filePath = tempfile();367 const cause = new Error(foobarString);368 const error = await t.throwsAsync(execa('noop.js', {369 stdout: [throwingGenerator(cause)(), getAbsolutePath(filePath)],370 }));371 t.is(error.cause, cause);372 t.is(await readFile(filePath, 'utf8'), '');373});374375test('Generator error does not create output file, sync', async t => {376 const filePath = tempfile();377 const cause = new Error(foobarString);378 const error = t.throws(() => {379 execaSync('noop.js', {380 stdout: [throwingGenerator(cause)(), getAbsolutePath(filePath)],381 });382 });383 t.is(error.cause, cause);384 t.false(await pathExists(filePath));385});386387test('Output file error still returns transformed output, sync', async t => {388 const filePath = tempfile();389 const {stdout} = t.throws(() => {390 execaSync('noop-fd.js', ['1', foobarString], {391 stdout: [uppercaseGenerator(), getAbsolutePath('./unknown/file')],392 });393 }, {code: 'ENOENT'});394 t.false(await pathExists(filePath));395 t.is(stdout, foobarUppercase);396});
added:test/stdio/generator-return.js+150 added
1import {Buffer} from 'node:buffer';2import test from 'ava';3import {execa, execaSync} from '../../index.js';4import {setFixtureDir} from '../helpers/fixtures-dir.js';5import {foobarString, foobarUint8Array} from '../helpers/input.js';6import {getOutputGenerator, convertTransformToFinal} from '../helpers/generator.js';78setFixtureDir();910// eslint-disable-next-line max-params11const testGeneratorReturnType = async (t, input, encoding, reject, objectMode, final, execaMethod) => {12 const fixtureName = reject ? 'noop-fd.js' : 'noop-fail.js';13 const {stdout} = await execaMethod(fixtureName, ['1', foobarString], {14 stdout: convertTransformToFinal(getOutputGenerator(input)(objectMode, true), final),15 encoding,16 reject,17 });18 const typeofChunk = Array.isArray(stdout) ? stdout[0] : stdout;19 const output = Buffer.from(typeofChunk, encoding === 'buffer' || objectMode ? undefined : encoding).toString();20 t.is(output, foobarString);21};2223test('Generator can return string with default encoding', testGeneratorReturnType, foobarString, 'utf8', true, false, false, execa);24test('Generator can return Uint8Array with default encoding', testGeneratorReturnType, foobarUint8Array, 'utf8', true, false, false, execa);25test('Generator can return string with encoding "utf16le"', testGeneratorReturnType, foobarString, 'utf16le', true, false, false, execa);26test('Generator can return Uint8Array with encoding "utf16le"', testGeneratorReturnType, foobarUint8Array, 'utf16le', true, false, false, execa);27test('Generator can return string with encoding "buffer"', testGeneratorReturnType, foobarString, 'buffer', true, false, false, execa);28test('Generator can return Uint8Array with encoding "buffer"', testGeneratorReturnType, foobarUint8Array, 'buffer', true, false, false, execa);29test('Generator can return string with encoding "hex"', testGeneratorReturnType, foobarString, 'hex', true, false, false, execa);30test('Generator can return Uint8Array with encoding "hex"', testGeneratorReturnType, foobarUint8Array, 'hex', true, false, false, execa);31test('Generator can return string with default encoding, failure', testGeneratorReturnType, foobarString, 'utf8', false, false, false, execa);32test('Generator can return Uint8Array with default encoding, failure', testGeneratorReturnType, foobarUint8Array, 'utf8', false, false, false, execa);33test('Generator can return string with encoding "utf16le", failure', testGeneratorReturnType, foobarString, 'utf16le', false, false, false, execa);34test('Generator can return Uint8Array with encoding "utf16le", failure', testGeneratorReturnType, foobarUint8Array, 'utf16le', false, false, false, execa);35test('Generator can return string with encoding "buffer", failure', testGeneratorReturnType, foobarString, 'buffer', false, false, false, execa);36test('Generator can return Uint8Array with encoding "buffer", failure', testGeneratorReturnType, foobarUint8Array, 'buffer', false, false, false, execa);37test('Generator can return string with encoding "hex", failure', testGeneratorReturnType, foobarString, 'hex', false, false, false, execa);38test('Generator can return Uint8Array with encoding "hex", failure', testGeneratorReturnType, foobarUint8Array, 'hex', false, false, false, execa);39test('Generator can return string with default encoding, objectMode', testGeneratorReturnType, foobarString, 'utf8', true, true, false, execa);40test('Generator can return Uint8Array with default encoding, objectMode', testGeneratorReturnType, foobarUint8Array, 'utf8', true, true, false, execa);41test('Generator can return string with encoding "utf16le", objectMode', testGeneratorReturnType, foobarString, 'utf16le', true, true, false, execa);42test('Generator can return Uint8Array with encoding "utf16le", objectMode', testGeneratorReturnType, foobarUint8Array, 'utf16le', true, true, false, execa);43test('Generator can return string with encoding "buffer", objectMode', testGeneratorReturnType, foobarString, 'buffer', true, true, false, execa);44test('Generator can return Uint8Array with encoding "buffer", objectMode', testGeneratorReturnType, foobarUint8Array, 'buffer', true, true, false, execa);45test('Generator can return string with encoding "hex", objectMode', testGeneratorReturnType, foobarString, 'hex', true, true, false, execa);46test('Generator can return Uint8Array with encoding "hex", objectMode', testGeneratorReturnType, foobarUint8Array, 'hex', true, true, false, execa);47test('Generator can return string with default encoding, objectMode, failure', testGeneratorReturnType, foobarString, 'utf8', false, true, false, execa);48test('Generator can return Uint8Array with default encoding, objectMode, failure', testGeneratorReturnType, foobarUint8Array, 'utf8', false, true, false, execa);49test('Generator can return string with encoding "utf16le", objectMode, failure', testGeneratorReturnType, foobarString, 'utf16le', false, true, false, execa);50test('Generator can return Uint8Array with encoding "utf16le", objectMode, failure', testGeneratorReturnType, foobarUint8Array, 'utf16le', false, true, false, execa);51test('Generator can return string with encoding "buffer", objectMode, failure', testGeneratorReturnType, foobarString, 'buffer', false, true, false, execa);52test('Generator can return Uint8Array with encoding "buffer", objectMode, failure', testGeneratorReturnType, foobarUint8Array, 'buffer', false, true, false, execa);53test('Generator can return string with encoding "hex", objectMode, failure', testGeneratorReturnType, foobarString, 'hex', false, true, false, execa);54test('Generator can return Uint8Array with encoding "hex", objectMode, failure', testGeneratorReturnType, foobarUint8Array, 'hex', false, true, false, execa);55test('Generator can return final string with default encoding', testGeneratorReturnType, foobarString, 'utf8', true, false, true, execa);56test('Generator can return final Uint8Array with default encoding', testGeneratorReturnType, foobarUint8Array, 'utf8', true, false, true, execa);57test('Generator can return final string with encoding "utf16le"', testGeneratorReturnType, foobarString, 'utf16le', true, false, true, execa);58test('Generator can return final Uint8Array with encoding "utf16le"', testGeneratorReturnType, foobarUint8Array, 'utf16le', true, false, true, execa);59test('Generator can return final string with encoding "buffer"', testGeneratorReturnType, foobarString, 'buffer', true, false, true, execa);60test('Generator can return final Uint8Array with encoding "buffer"', testGeneratorReturnType, foobarUint8Array, 'buffer', true, false, true, execa);61test('Generator can return final string with encoding "hex"', testGeneratorReturnType, foobarString, 'hex', true, false, true, execa);62test('Generator can return final Uint8Array with encoding "hex"', testGeneratorReturnType, foobarUint8Array, 'hex', true, false, true, execa);63test('Generator can return final string with default encoding, failure', testGeneratorReturnType, foobarString, 'utf8', false, false, true, execa);64test('Generator can return final Uint8Array with default encoding, failure', testGeneratorReturnType, foobarUint8Array, 'utf8', false, false, true, execa);65test('Generator can return final string with encoding "utf16le", failure', testGeneratorReturnType, foobarString, 'utf16le', false, false, true, execa);66test('Generator can return final Uint8Array with encoding "utf16le", failure', testGeneratorReturnType, foobarUint8Array, 'utf16le', false, false, true, execa);67test('Generator can return final string with encoding "buffer", failure', testGeneratorReturnType, foobarString, 'buffer', false, false, true, execa);68test('Generator can return final Uint8Array with encoding "buffer", failure', testGeneratorReturnType, foobarUint8Array, 'buffer', false, false, true, execa);69test('Generator can return final string with encoding "hex", failure', testGeneratorReturnType, foobarString, 'hex', false, false, true, execa);70test('Generator can return final Uint8Array with encoding "hex", failure', testGeneratorReturnType, foobarUint8Array, 'hex', false, false, true, execa);71test('Generator can return final string with default encoding, objectMode', testGeneratorReturnType, foobarString, 'utf8', true, true, true, execa);72test('Generator can return final Uint8Array with default encoding, objectMode', testGeneratorReturnType, foobarUint8Array, 'utf8', true, true, true, execa);73test('Generator can return final string with encoding "utf16le", objectMode', testGeneratorReturnType, foobarString, 'utf16le', true, true, true, execa);74test('Generator can return final Uint8Array with encoding "utf16le", objectMode', testGeneratorReturnType, foobarUint8Array, 'utf16le', true, true, true, execa);75test('Generator can return final string with encoding "buffer", objectMode', testGeneratorReturnType, foobarString, 'buffer', true, true, true, execa);76test('Generator can return final Uint8Array with encoding "buffer", objectMode', testGeneratorReturnType, foobarUint8Array, 'buffer', true, true, true, execa);77test('Generator can return final string with encoding "hex", objectMode', testGeneratorReturnType, foobarString, 'hex', true, true, true, execa);78test('Generator can return final Uint8Array with encoding "hex", objectMode', testGeneratorReturnType, foobarUint8Array, 'hex', true, true, true, execa);79test('Generator can return final string with default encoding, objectMode, failure', testGeneratorReturnType, foobarString, 'utf8', false, true, true, execa);80test('Generator can return final Uint8Array with default encoding, objectMode, failure', testGeneratorReturnType, foobarUint8Array, 'utf8', false, true, true, execa);81test('Generator can return final string with encoding "utf16le", objectMode, failure', testGeneratorReturnType, foobarString, 'utf16le', false, true, true, execa);82test('Generator can return final Uint8Array with encoding "utf16le", objectMode, failure', testGeneratorReturnType, foobarUint8Array, 'utf16le', false, true, true, execa);83test('Generator can return final string with encoding "buffer", objectMode, failure', testGeneratorReturnType, foobarString, 'buffer', false, true, true, execa);84test('Generator can return final Uint8Array with encoding "buffer", objectMode, failure', testGeneratorReturnType, foobarUint8Array, 'buffer', false, true, true, execa);85test('Generator can return final string with encoding "hex", objectMode, failure', testGeneratorReturnType, foobarString, 'hex', false, true, true, execa);86test('Generator can return final Uint8Array with encoding "hex", objectMode, failure', testGeneratorReturnType, foobarUint8Array, 'hex', false, true, true, execa);87test('Generator can return string with default encoding, sync', testGeneratorReturnType, foobarString, 'utf8', true, false, false, execaSync);88test('Generator can return Uint8Array with default encoding, sync', testGeneratorReturnType, foobarUint8Array, 'utf8', true, false, false, execaSync);89test('Generator can return string with encoding "utf16le", sync', testGeneratorReturnType, foobarString, 'utf16le', true, false, false, execaSync);90test('Generator can return Uint8Array with encoding "utf16le", sync', testGeneratorReturnType, foobarUint8Array, 'utf16le', true, false, false, execaSync);91test('Generator can return string with encoding "buffer", sync', testGeneratorReturnType, foobarString, 'buffer', true, false, false, execaSync);92test('Generator can return Uint8Array with encoding "buffer", sync', testGeneratorReturnType, foobarUint8Array, 'buffer', true, false, false, execaSync);93test('Generator can return string with encoding "hex", sync', testGeneratorReturnType, foobarString, 'hex', true, false, false, execaSync);94test('Generator can return Uint8Array with encoding "hex", sync', testGeneratorReturnType, foobarUint8Array, 'hex', true, false, false, execaSync);95test('Generator can return string with default encoding, failure, sync', testGeneratorReturnType, foobarString, 'utf8', false, false, false, execaSync);96test('Generator can return Uint8Array with default encoding, failure, sync', testGeneratorReturnType, foobarUint8Array, 'utf8', false, false, false, execaSync);97test('Generator can return string with encoding "utf16le", failure, sync', testGeneratorReturnType, foobarString, 'utf16le', false, false, false, execaSync);98test('Generator can return Uint8Array with encoding "utf16le", failure, sync', testGeneratorReturnType, foobarUint8Array, 'utf16le', false, false, false, execaSync);99test('Generator can return string with encoding "buffer", failure, sync', testGeneratorReturnType, foobarString, 'buffer', false, false, false, execaSync);100test('Generator can return Uint8Array with encoding "buffer", failure, sync', testGeneratorReturnType, foobarUint8Array, 'buffer', false, false, false, execaSync);101test('Generator can return string with encoding "hex", failure, sync', testGeneratorReturnType, foobarString, 'hex', false, false, false, execaSync);102test('Generator can return Uint8Array with encoding "hex", failure, sync', testGeneratorReturnType, foobarUint8Array, 'hex', false, false, false, execaSync);103test('Generator can return string with default encoding, objectMode, sync', testGeneratorReturnType, foobarString, 'utf8', true, true, false, execaSync);104test('Generator can return Uint8Array with default encoding, objectMode, sync', testGeneratorReturnType, foobarUint8Array, 'utf8', true, true, false, execaSync);105test('Generator can return string with encoding "utf16le", objectMode, sync', testGeneratorReturnType, foobarString, 'utf16le', true, true, false, execaSync);106test('Generator can return Uint8Array with encoding "utf16le", objectMode, sync', testGeneratorReturnType, foobarUint8Array, 'utf16le', true, true, false, execaSync);107test('Generator can return string with encoding "buffer", objectMode, sync', testGeneratorReturnType, foobarString, 'buffer', true, true, false, execaSync);108test('Generator can return Uint8Array with encoding "buffer", objectMode, sync', testGeneratorReturnType, foobarUint8Array, 'buffer', true, true, false, execaSync);109test('Generator can return string with encoding "hex", objectMode, sync', testGeneratorReturnType, foobarString, 'hex', true, true, false, execaSync);110test('Generator can return Uint8Array with encoding "hex", objectMode, sync', testGeneratorReturnType, foobarUint8Array, 'hex', true, true, false, execaSync);111test('Generator can return string with default encoding, objectMode, failure, sync', testGeneratorReturnType, foobarString, 'utf8', false, true, false, execaSync);112test('Generator can return Uint8Array with default encoding, objectMode, failure, sync', testGeneratorReturnType, foobarUint8Array, 'utf8', false, true, false, execaSync);113test('Generator can return string with encoding "utf16le", objectMode, failure, sync', testGeneratorReturnType, foobarString, 'utf16le', false, true, false, execaSync);114test('Generator can return Uint8Array with encoding "utf16le", objectMode, failure, sync', testGeneratorReturnType, foobarUint8Array, 'utf16le', false, true, false, execaSync);115test('Generator can return string with encoding "buffer", objectMode, failure, sync', testGeneratorReturnType, foobarString, 'buffer', false, true, false, execaSync);116test('Generator can return Uint8Array with encoding "buffer", objectMode, failure, sync', testGeneratorReturnType, foobarUint8Array, 'buffer', false, true, false, execaSync);117test('Generator can return string with encoding "hex", objectMode, failure, sync', testGeneratorReturnType, foobarString, 'hex', false, true, false, execaSync);118test('Generator can return Uint8Array with encoding "hex", objectMode, failure, sync', testGeneratorReturnType, foobarUint8Array, 'hex', false, true, false, execaSync);119test('Generator can return final string with default encoding, sync', testGeneratorReturnType, foobarString, 'utf8', true, false, true, execaSync);120test('Generator can return final Uint8Array with default encoding, sync', testGeneratorReturnType, foobarUint8Array, 'utf8', true, false, true, execaSync);121test('Generator can return final string with encoding "utf16le", sync', testGeneratorReturnType, foobarString, 'utf16le', true, false, true, execaSync);122test('Generator can return final Uint8Array with encoding "utf16le", sync', testGeneratorReturnType, foobarUint8Array, 'utf16le', true, false, true, execaSync);123test('Generator can return final string with encoding "buffer", sync', testGeneratorReturnType, foobarString, 'buffer', true, false, true, execaSync);124test('Generator can return final Uint8Array with encoding "buffer", sync', testGeneratorReturnType, foobarUint8Array, 'buffer', true, false, true, execaSync);125test('Generator can return final string with encoding "hex", sync', testGeneratorReturnType, foobarString, 'hex', true, false, true, execaSync);126test('Generator can return final Uint8Array with encoding "hex", sync', testGeneratorReturnType, foobarUint8Array, 'hex', true, false, true, execaSync);127test('Generator can return final string with default encoding, failure, sync', testGeneratorReturnType, foobarString, 'utf8', false, false, true, execaSync);128test('Generator can return final Uint8Array with default encoding, failure, sync', testGeneratorReturnType, foobarUint8Array, 'utf8', false, false, true, execaSync);129test('Generator can return final string with encoding "utf16le", failure, sync', testGeneratorReturnType, foobarString, 'utf16le', false, false, true, execaSync);130test('Generator can return final Uint8Array with encoding "utf16le", failure, sync', testGeneratorReturnType, foobarUint8Array, 'utf16le', false, false, true, execaSync);131test('Generator can return final string with encoding "buffer", failure, sync', testGeneratorReturnType, foobarString, 'buffer', false, false, true, execaSync);132test('Generator can return final Uint8Array with encoding "buffer", failure, sync', testGeneratorReturnType, foobarUint8Array, 'buffer', false, false, true, execaSync);133test('Generator can return final string with encoding "hex", failure, sync', testGeneratorReturnType, foobarString, 'hex', false, false, true, execaSync);134test('Generator can return final Uint8Array with encoding "hex", failure, sync', testGeneratorReturnType, foobarUint8Array, 'hex', false, false, true, execaSync);135test('Generator can return final string with default encoding, objectMode, sync', testGeneratorReturnType, foobarString, 'utf8', true, true, true, execaSync);136test('Generator can return final Uint8Array with default encoding, objectMode, sync', testGeneratorReturnType, foobarUint8Array, 'utf8', true, true, true, execaSync);137test('Generator can return final string with encoding "utf16le", objectMode, sync', testGeneratorReturnType, foobarString, 'utf16le', true, true, true, execaSync);138test('Generator can return final Uint8Array with encoding "utf16le", objectMode, sync', testGeneratorReturnType, foobarUint8Array, 'utf16le', true, true, true, execaSync);139test('Generator can return final string with encoding "buffer", objectMode, sync', testGeneratorReturnType, foobarString, 'buffer', true, true, true, execaSync);140test('Generator can return final Uint8Array with encoding "buffer", objectMode, sync', testGeneratorReturnType, foobarUint8Array, 'buffer', true, true, true, execaSync);141test('Generator can return final string with encoding "hex", objectMode, sync', testGeneratorReturnType, foobarString, 'hex', true, true, true, execaSync);142test('Generator can return final Uint8Array with encoding "hex", objectMode, sync', testGeneratorReturnType, foobarUint8Array, 'hex', true, true, true, execaSync);143test('Generator can return final string with default encoding, objectMode, failure, sync', testGeneratorReturnType, foobarString, 'utf8', false, true, true, execaSync);144test('Generator can return final Uint8Array with default encoding, objectMode, failure, sync', testGeneratorReturnType, foobarUint8Array, 'utf8', false, true, true, execaSync);145test('Generator can return final string with encoding "utf16le", objectMode, failure, sync', testGeneratorReturnType, foobarString, 'utf16le', false, true, true, execaSync);146test('Generator can return final Uint8Array with encoding "utf16le", objectMode, failure, sync', testGeneratorReturnType, foobarUint8Array, 'utf16le', false, true, true, execaSync);147test('Generator can return final string with encoding "buffer", objectMode, failure, sync', testGeneratorReturnType, foobarString, 'buffer', false, true, true, execaSync);148test('Generator can return final Uint8Array with encoding "buffer", objectMode, failure, sync', testGeneratorReturnType, foobarUint8Array, 'buffer', false, true, true, execaSync);149test('Generator can return final string with encoding "hex", objectMode, failure, sync', testGeneratorReturnType, foobarString, 'hex', false, true, true, execaSync);150test('Generator can return final Uint8Array with encoding "hex", objectMode, failure, sync', testGeneratorReturnType, foobarUint8Array, 'hex', false, true, true, execaSync);
deleted:test/stdio/generator.js-792 removed
1import {Buffer} from 'node:buffer';2import {readFile, writeFile, rm} from 'node:fs/promises';3import {PassThrough} from 'node:stream';4import test from 'ava';5import getStream, {getStreamAsArray} from 'get-stream';6import tempfile from 'tempfile';7import {execa, execaSync} from '../../index.js';8import {setFixtureDir} from '../helpers/fixtures-dir.js';9import {getStdio} from '../helpers/stdio.js';10import {11 foobarString,12 foobarUppercase,13 foobarHex,14 foobarUint8Array,15 foobarBuffer,16 foobarObject,17 foobarObjectString,18} from '../helpers/input.js';19import {20 outputObjectGenerator,21 uppercaseGenerator,22 uppercaseBufferGenerator,23 appendGenerator,24 appendAsyncGenerator,25 casedSuffix,26} from '../helpers/generator.js';27import {appendDuplex, uppercaseBufferDuplex} from '../helpers/duplex.js';28import {appendWebTransform, uppercaseBufferWebTransform} from '../helpers/web-transform.js';29import {generatorsMap} from '../helpers/map.js';3031setFixtureDir();3233const textEncoder = new TextEncoder();3435const getInputObjectMode = (objectMode, addNoopTransform, type) => objectMode36 ? {37 input: [foobarObject],38 generators: generatorsMap[type].addNoop(generatorsMap[type].serialize(objectMode), addNoopTransform, objectMode),39 output: foobarObjectString,40 }41 : {42 input: foobarUint8Array,43 generators: generatorsMap[type].addNoop(generatorsMap[type].uppercase(objectMode), addNoopTransform, objectMode),44 output: foobarUppercase,45 };4647const getOutputObjectMode = (objectMode, addNoopTransform, type, binary) => objectMode48 ? {49 generators: generatorsMap[type].addNoop(generatorsMap[type].outputObject(), addNoopTransform, objectMode, binary),50 output: [foobarObject],51 getStreamMethod: getStreamAsArray,52 }53 : {54 generators: generatorsMap[type].addNoop(generatorsMap[type].uppercaseBuffer(objectMode, true), addNoopTransform, objectMode, binary),55 output: foobarUppercase,56 getStreamMethod: getStream,57 };5859// eslint-disable-next-line max-params60const testGeneratorInput = async (t, fdNumber, objectMode, addNoopTransform, type, execaMethod) => {61 const {input, generators, output} = getInputObjectMode(objectMode, addNoopTransform, type);62 const {stdout} = await execaMethod('stdin-fd.js', [`${fdNumber}`], getStdio(fdNumber, [input, ...generators]));63 t.is(stdout, output);64};6566test('Can use generators with result.stdin', testGeneratorInput, 0, false, false, 'generator', execa);67test('Can use generators with result.stdio[*] as input', testGeneratorInput, 3, false, false, 'generator', execa);68test('Can use generators with result.stdin, objectMode', testGeneratorInput, 0, true, false, 'generator', execa);69test('Can use generators with result.stdio[*] as input, objectMode', testGeneratorInput, 3, true, false, 'generator', execa);70test('Can use generators with result.stdin, noop transform', testGeneratorInput, 0, false, true, 'generator', execa);71test('Can use generators with result.stdio[*] as input, noop transform', testGeneratorInput, 3, false, true, 'generator', execa);72test('Can use generators with result.stdin, objectMode, noop transform', testGeneratorInput, 0, true, true, 'generator', execa);73test('Can use generators with result.stdio[*] as input, objectMode, noop transform', testGeneratorInput, 3, true, true, 'generator', execa);74test('Can use generators with result.stdin, sync', testGeneratorInput, 0, false, false, 'generator', execaSync);75test('Can use generators with result.stdin, objectMode, sync', testGeneratorInput, 0, true, false, 'generator', execaSync);76test('Can use generators with result.stdin, noop transform, sync', testGeneratorInput, 0, false, true, 'generator', execaSync);77test('Can use generators with result.stdin, objectMode, noop transform, sync', testGeneratorInput, 0, true, true, 'generator', execaSync);78test('Can use duplexes with result.stdin', testGeneratorInput, 0, false, false, 'duplex', execa);79test('Can use duplexes with result.stdio[*] as input', testGeneratorInput, 3, false, false, 'duplex', execa);80test('Can use duplexes with result.stdin, objectMode', testGeneratorInput, 0, true, false, 'duplex', execa);81test('Can use duplexes with result.stdio[*] as input, objectMode', testGeneratorInput, 3, true, false, 'duplex', execa);82test('Can use duplexes with result.stdin, noop transform', testGeneratorInput, 0, false, true, 'duplex', execa);83test('Can use duplexes with result.stdio[*] as input, noop transform', testGeneratorInput, 3, false, true, 'duplex', execa);84test('Can use duplexes with result.stdin, objectMode, noop transform', testGeneratorInput, 0, true, true, 'duplex', execa);85test('Can use duplexes with result.stdio[*] as input, objectMode, noop transform', testGeneratorInput, 3, true, true, 'duplex', execa);86test('Can use webTransforms with result.stdin', testGeneratorInput, 0, false, false, 'webTransform', execa);87test('Can use webTransforms with result.stdio[*] as input', testGeneratorInput, 3, false, false, 'webTransform', execa);88test('Can use webTransforms with result.stdin, objectMode', testGeneratorInput, 0, true, false, 'webTransform', execa);89test('Can use webTransforms with result.stdio[*] as input, objectMode', testGeneratorInput, 3, true, false, 'webTransform', execa);90test('Can use webTransforms with result.stdin, noop transform', testGeneratorInput, 0, false, true, 'webTransform', execa);91test('Can use webTransforms with result.stdio[*] as input, noop transform', testGeneratorInput, 3, false, true, 'webTransform', execa);92test('Can use webTransforms with result.stdin, objectMode, noop transform', testGeneratorInput, 0, true, true, 'webTransform', execa);93test('Can use webTransforms with result.stdio[*] as input, objectMode, noop transform', testGeneratorInput, 3, true, true, 'webTransform', execa);9495// eslint-disable-next-line max-params96const testGeneratorInputPipe = async (t, useShortcutProperty, objectMode, addNoopTransform, type, input) => {97 const {generators, output} = getInputObjectMode(objectMode, addNoopTransform, type);98 const subprocess = execa('stdin-fd.js', ['0'], getStdio(0, generators));99 const stream = useShortcutProperty ? subprocess.stdin : subprocess.stdio[0];100 stream.end(...input);101 const {stdout} = await subprocess;102 const expectedOutput = input[1] === 'utf16le' ? Buffer.from(output, input[1]).toString() : output;103 t.is(stdout, expectedOutput);104};105106test('Can use generators with subprocess.stdio[0] and default encoding', testGeneratorInputPipe, false, false, false, 'generator', [foobarString, 'utf8']);107test('Can use generators with subprocess.stdin and default encoding', testGeneratorInputPipe, true, false, false, 'generator', [foobarString, 'utf8']);108test('Can use generators with subprocess.stdio[0] and encoding "utf16le"', testGeneratorInputPipe, false, false, false, 'generator', [foobarString, 'utf16le']);109test('Can use generators with subprocess.stdin and encoding "utf16le"', testGeneratorInputPipe, true, false, false, 'generator', [foobarString, 'utf16le']);110test('Can use generators with subprocess.stdio[0] and encoding "buffer"', testGeneratorInputPipe, false, false, false, 'generator', [foobarBuffer, 'buffer']);111test('Can use generators with subprocess.stdin and encoding "buffer"', testGeneratorInputPipe, true, false, false, 'generator', [foobarBuffer, 'buffer']);112test('Can use generators with subprocess.stdio[0] and encoding "hex"', testGeneratorInputPipe, false, false, false, 'generator', [foobarHex, 'hex']);113test('Can use generators with subprocess.stdin and encoding "hex"', testGeneratorInputPipe, true, false, false, 'generator', [foobarHex, 'hex']);114test('Can use generators with subprocess.stdio[0], objectMode', testGeneratorInputPipe, false, true, false, 'generator', [foobarObject]);115test('Can use generators with subprocess.stdin, objectMode', testGeneratorInputPipe, true, true, false, 'generator', [foobarObject]);116test('Can use generators with subprocess.stdio[0] and default encoding, noop transform', testGeneratorInputPipe, false, false, true, 'generator', [foobarString, 'utf8']);117test('Can use generators with subprocess.stdin and default encoding, noop transform', testGeneratorInputPipe, true, false, true, 'generator', [foobarString, 'utf8']);118test('Can use generators with subprocess.stdio[0] and encoding "utf16le", noop transform', testGeneratorInputPipe, false, false, true, 'generator', [foobarString, 'utf16le']);119test('Can use generators with subprocess.stdin and encoding "utf16le", noop transform', testGeneratorInputPipe, true, false, true, 'generator', [foobarString, 'utf16le']);120test('Can use generators with subprocess.stdio[0] and encoding "buffer", noop transform', testGeneratorInputPipe, false, false, true, 'generator', [foobarBuffer, 'buffer']);121test('Can use generators with subprocess.stdin and encoding "buffer", noop transform', testGeneratorInputPipe, true, false, true, 'generator', [foobarBuffer, 'buffer']);122test('Can use generators with subprocess.stdio[0] and encoding "hex", noop transform', testGeneratorInputPipe, false, false, true, 'generator', [foobarHex, 'hex']);123test('Can use generators with subprocess.stdin and encoding "hex", noop transform', testGeneratorInputPipe, true, false, true, 'generator', [foobarHex, 'hex']);124test('Can use generators with subprocess.stdio[0], objectMode, noop transform', testGeneratorInputPipe, false, true, true, 'generator', [foobarObject]);125test('Can use generators with subprocess.stdin, objectMode, noop transform', testGeneratorInputPipe, true, true, true, 'generator', [foobarObject]);126test('Can use duplexes with subprocess.stdio[0] and default encoding', testGeneratorInputPipe, false, false, false, 'duplex', [foobarString, 'utf8']);127test('Can use duplexes with subprocess.stdin and default encoding', testGeneratorInputPipe, true, false, false, 'duplex', [foobarString, 'utf8']);128test('Can use duplexes with subprocess.stdio[0] and encoding "utf16le"', testGeneratorInputPipe, false, false, false, 'duplex', [foobarString, 'utf16le']);129test('Can use duplexes with subprocess.stdin and encoding "utf16le"', testGeneratorInputPipe, true, false, false, 'duplex', [foobarString, 'utf16le']);130test('Can use duplexes with subprocess.stdio[0] and encoding "buffer"', testGeneratorInputPipe, false, false, false, 'duplex', [foobarBuffer, 'buffer']);131test('Can use duplexes with subprocess.stdin and encoding "buffer"', testGeneratorInputPipe, true, false, false, 'duplex', [foobarBuffer, 'buffer']);132test('Can use duplexes with subprocess.stdio[0] and encoding "hex"', testGeneratorInputPipe, false, false, false, 'duplex', [foobarHex, 'hex']);133test('Can use duplexes with subprocess.stdin and encoding "hex"', testGeneratorInputPipe, true, false, false, 'duplex', [foobarHex, 'hex']);134test('Can use duplexes with subprocess.stdio[0], objectMode', testGeneratorInputPipe, false, true, false, 'duplex', [foobarObject]);135test('Can use duplexes with subprocess.stdin, objectMode', testGeneratorInputPipe, true, true, false, 'duplex', [foobarObject]);136test('Can use duplexes with subprocess.stdio[0] and default encoding, noop transform', testGeneratorInputPipe, false, false, true, 'duplex', [foobarString, 'utf8']);137test('Can use duplexes with subprocess.stdin and default encoding, noop transform', testGeneratorInputPipe, true, false, true, 'duplex', [foobarString, 'utf8']);138test('Can use duplexes with subprocess.stdio[0] and encoding "utf16le", noop transform', testGeneratorInputPipe, false, false, true, 'duplex', [foobarString, 'utf16le']);139test('Can use duplexes with subprocess.stdin and encoding "utf16le", noop transform', testGeneratorInputPipe, true, false, true, 'duplex', [foobarString, 'utf16le']);140test('Can use duplexes with subprocess.stdio[0] and encoding "buffer", noop transform', testGeneratorInputPipe, false, false, true, 'duplex', [foobarBuffer, 'buffer']);141test('Can use duplexes with subprocess.stdin and encoding "buffer", noop transform', testGeneratorInputPipe, true, false, true, 'duplex', [foobarBuffer, 'buffer']);142test('Can use duplexes with subprocess.stdio[0] and encoding "hex", noop transform', testGeneratorInputPipe, false, false, true, 'duplex', [foobarHex, 'hex']);143test('Can use duplexes with subprocess.stdin and encoding "hex", noop transform', testGeneratorInputPipe, true, false, true, 'duplex', [foobarHex, 'hex']);144test('Can use duplexes with subprocess.stdio[0], objectMode, noop transform', testGeneratorInputPipe, false, true, true, 'duplex', [foobarObject]);145test('Can use duplexes with subprocess.stdin, objectMode, noop transform', testGeneratorInputPipe, true, true, true, 'duplex', [foobarObject]);146test('Can use webTransforms with subprocess.stdio[0] and default encoding', testGeneratorInputPipe, false, false, false, 'webTransform', [foobarString, 'utf8']);147test('Can use webTransforms with subprocess.stdin and default encoding', testGeneratorInputPipe, true, false, false, 'webTransform', [foobarString, 'utf8']);148test('Can use webTransforms with subprocess.stdio[0] and encoding "utf16le"', testGeneratorInputPipe, false, false, false, 'webTransform', [foobarString, 'utf16le']);149test('Can use webTransforms with subprocess.stdin and encoding "utf16le"', testGeneratorInputPipe, true, false, false, 'webTransform', [foobarString, 'utf16le']);150test('Can use webTransforms with subprocess.stdio[0] and encoding "buffer"', testGeneratorInputPipe, false, false, false, 'webTransform', [foobarBuffer, 'buffer']);151test('Can use webTransforms with subprocess.stdin and encoding "buffer"', testGeneratorInputPipe, true, false, false, 'webTransform', [foobarBuffer, 'buffer']);152test('Can use webTransforms with subprocess.stdio[0] and encoding "hex"', testGeneratorInputPipe, false, false, false, 'webTransform', [foobarHex, 'hex']);153test('Can use webTransforms with subprocess.stdin and encoding "hex"', testGeneratorInputPipe, true, false, false, 'webTransform', [foobarHex, 'hex']);154test('Can use webTransforms with subprocess.stdio[0], objectMode', testGeneratorInputPipe, false, true, false, 'webTransform', [foobarObject]);155test('Can use webTransforms with subprocess.stdin, objectMode', testGeneratorInputPipe, true, true, false, 'webTransform', [foobarObject]);156test('Can use webTransforms with subprocess.stdio[0] and default encoding, noop transform', testGeneratorInputPipe, false, false, true, 'webTransform', [foobarString, 'utf8']);157test('Can use webTransforms with subprocess.stdin and default encoding, noop transform', testGeneratorInputPipe, true, false, true, 'webTransform', [foobarString, 'utf8']);158test('Can use webTransforms with subprocess.stdio[0] and encoding "utf16le", noop transform', testGeneratorInputPipe, false, false, true, 'webTransform', [foobarString, 'utf16le']);159test('Can use webTransforms with subprocess.stdin and encoding "utf16le", noop transform', testGeneratorInputPipe, true, false, true, 'webTransform', [foobarString, 'utf16le']);160test('Can use webTransforms with subprocess.stdio[0] and encoding "buffer", noop transform', testGeneratorInputPipe, false, false, true, 'webTransform', [foobarBuffer, 'buffer']);161test('Can use webTransforms with subprocess.stdin and encoding "buffer", noop transform', testGeneratorInputPipe, true, false, true, 'webTransform', [foobarBuffer, 'buffer']);162test('Can use webTransforms with subprocess.stdio[0] and encoding "hex", noop transform', testGeneratorInputPipe, false, false, true, 'webTransform', [foobarHex, 'hex']);163test('Can use webTransforms with subprocess.stdin and encoding "hex", noop transform', testGeneratorInputPipe, true, false, true, 'webTransform', [foobarHex, 'hex']);164test('Can use webTransforms with subprocess.stdio[0], objectMode, noop transform', testGeneratorInputPipe, false, true, true, 'webTransform', [foobarObject]);165test('Can use webTransforms with subprocess.stdin, objectMode, noop transform', testGeneratorInputPipe, true, true, true, 'webTransform', [foobarObject]);166167const testGeneratorStdioInputPipe = async (t, objectMode, addNoopTransform, type) => {168 const {input, generators, output} = getInputObjectMode(objectMode, addNoopTransform, type);169 const subprocess = execa('stdin-fd.js', ['3'], getStdio(3, [[], ...generators]));170 subprocess.stdio[3].write(Array.isArray(input) ? input[0] : input);171 const {stdout} = await subprocess;172 t.is(stdout, output);173};174175test('Can use generators with subprocess.stdio[*] as input', testGeneratorStdioInputPipe, false, false, 'generator');176test('Can use generators with subprocess.stdio[*] as input, objectMode', testGeneratorStdioInputPipe, true, false, 'generator');177test('Can use generators with subprocess.stdio[*] as input, noop transform', testGeneratorStdioInputPipe, false, true, 'generator');178test('Can use generators with subprocess.stdio[*] as input, objectMode, noop transform', testGeneratorStdioInputPipe, true, true, 'generator');179test('Can use duplexes with subprocess.stdio[*] as input', testGeneratorStdioInputPipe, false, false, 'duplex');180test('Can use duplexes with subprocess.stdio[*] as input, objectMode', testGeneratorStdioInputPipe, true, false, 'duplex');181test('Can use duplexes with subprocess.stdio[*] as input, noop transform', testGeneratorStdioInputPipe, false, true, 'duplex');182test('Can use duplexes with subprocess.stdio[*] as input, objectMode, noop transform', testGeneratorStdioInputPipe, true, true, 'duplex');183test('Can use webTransforms with subprocess.stdio[*] as input', testGeneratorStdioInputPipe, false, false, 'webTransform');184test('Can use webTransforms with subprocess.stdio[*] as input, objectMode', testGeneratorStdioInputPipe, true, false, 'webTransform');185test('Can use webTransforms with subprocess.stdio[*] as input, noop transform', testGeneratorStdioInputPipe, false, true, 'webTransform');186test('Can use webTransforms with subprocess.stdio[*] as input, objectMode, noop transform', testGeneratorStdioInputPipe, true, true, 'webTransform');187188// eslint-disable-next-line max-params189const testGeneratorOutput = async (t, fdNumber, reject, useShortcutProperty, objectMode, addNoopTransform, type, execaMethod) => {190 const {generators, output} = getOutputObjectMode(objectMode, addNoopTransform, type);191 const fixtureName = reject ? 'noop-fd.js' : 'noop-fail.js';192 const {stdout, stderr, stdio} = await execaMethod(fixtureName, [`${fdNumber}`, foobarString], {...getStdio(fdNumber, generators), reject});193 const result = useShortcutProperty ? [stdout, stderr][fdNumber - 1] : stdio[fdNumber];194 t.deepEqual(result, output);195};196197test('Can use generators with result.stdio[1]', testGeneratorOutput, 1, true, false, false, false, 'generator', execa);198test('Can use generators with result.stdout', testGeneratorOutput, 1, true, true, false, false, 'generator', execa);199test('Can use generators with result.stdio[2]', testGeneratorOutput, 2, true, false, false, false, 'generator', execa);200test('Can use generators with result.stderr', testGeneratorOutput, 2, true, true, false, false, 'generator', execa);201test('Can use generators with result.stdio[*] as output', testGeneratorOutput, 3, true, false, false, false, 'generator', execa);202test('Can use generators with error.stdio[1]', testGeneratorOutput, 1, false, false, false, false, 'generator', execa);203test('Can use generators with error.stdout', testGeneratorOutput, 1, false, true, false, false, 'generator', execa);204test('Can use generators with error.stdio[2]', testGeneratorOutput, 2, false, false, false, false, 'generator', execa);205test('Can use generators with error.stderr', testGeneratorOutput, 2, false, true, false, false, 'generator', execa);206test('Can use generators with error.stdio[*] as output', testGeneratorOutput, 3, false, false, false, false, 'generator', execa);207test('Can use generators with result.stdio[1], objectMode', testGeneratorOutput, 1, true, false, true, false, 'generator', execa);208test('Can use generators with result.stdout, objectMode', testGeneratorOutput, 1, true, true, true, false, 'generator', execa);209test('Can use generators with result.stdio[2], objectMode', testGeneratorOutput, 2, true, false, true, false, 'generator', execa);210test('Can use generators with result.stderr, objectMode', testGeneratorOutput, 2, true, true, true, false, 'generator', execa);211test('Can use generators with result.stdio[*] as output, objectMode', testGeneratorOutput, 3, true, false, true, false, 'generator', execa);212test('Can use generators with error.stdio[1], objectMode', testGeneratorOutput, 1, false, false, true, false, 'generator', execa);213test('Can use generators with error.stdout, objectMode', testGeneratorOutput, 1, false, true, true, false, 'generator', execa);214test('Can use generators with error.stdio[2], objectMode', testGeneratorOutput, 2, false, false, true, false, 'generator', execa);215test('Can use generators with error.stderr, objectMode', testGeneratorOutput, 2, false, true, true, false, 'generator', execa);216test('Can use generators with error.stdio[*] as output, objectMode', testGeneratorOutput, 3, false, false, true, false, 'generator', execa);217test('Can use generators with result.stdio[1], noop transform', testGeneratorOutput, 1, true, false, false, true, 'generator', execa);218test('Can use generators with result.stdout, noop transform', testGeneratorOutput, 1, true, true, false, true, 'generator', execa);219test('Can use generators with result.stdio[2], noop transform', testGeneratorOutput, 2, true, false, false, true, 'generator', execa);220test('Can use generators with result.stderr, noop transform', testGeneratorOutput, 2, true, true, false, true, 'generator', execa);221test('Can use generators with result.stdio[*] as output, noop transform', testGeneratorOutput, 3, true, false, false, true, 'generator', execa);222test('Can use generators with error.stdio[1], noop transform', testGeneratorOutput, 1, false, false, false, true, 'generator', execa);223test('Can use generators with error.stdout, noop transform', testGeneratorOutput, 1, false, true, false, true, 'generator', execa);224test('Can use generators with error.stdio[2], noop transform', testGeneratorOutput, 2, false, false, false, true, 'generator', execa);225test('Can use generators with error.stderr, noop transform', testGeneratorOutput, 2, false, true, false, true, 'generator', execa);226test('Can use generators with error.stdio[*] as output, noop transform', testGeneratorOutput, 3, false, false, false, true, 'generator', execa);227test('Can use generators with result.stdio[1], objectMode, noop transform', testGeneratorOutput, 1, true, false, true, true, 'generator', execa);228test('Can use generators with result.stdout, objectMode, noop transform', testGeneratorOutput, 1, true, true, true, true, 'generator', execa);229test('Can use generators with result.stdio[2], objectMode, noop transform', testGeneratorOutput, 2, true, false, true, true, 'generator', execa);230test('Can use generators with result.stderr, objectMode, noop transform', testGeneratorOutput, 2, true, true, true, true, 'generator', execa);231test('Can use generators with result.stdio[*] as output, objectMode, noop transform', testGeneratorOutput, 3, true, false, true, true, 'generator', execa);232test('Can use generators with error.stdio[1], objectMode, noop transform', testGeneratorOutput, 1, false, false, true, true, 'generator', execa);233test('Can use generators with error.stdout, objectMode, noop transform', testGeneratorOutput, 1, false, true, true, true, 'generator', execa);234test('Can use generators with error.stdio[2], objectMode, noop transform', testGeneratorOutput, 2, false, false, true, true, 'generator', execa);235test('Can use generators with error.stderr, objectMode, noop transform', testGeneratorOutput, 2, false, true, true, true, 'generator', execa);236test('Can use generators with error.stdio[*] as output, objectMode, noop transform', testGeneratorOutput, 3, false, false, true, true, 'generator', execa);237test('Can use generators with result.stdio[1], sync', testGeneratorOutput, 1, true, false, false, false, 'generator', execaSync);238test('Can use generators with result.stdout, sync', testGeneratorOutput, 1, true, true, false, false, 'generator', execaSync);239test('Can use generators with result.stdio[2], sync', testGeneratorOutput, 2, true, false, false, false, 'generator', execaSync);240test('Can use generators with result.stderr, sync', testGeneratorOutput, 2, true, true, false, false, 'generator', execaSync);241test('Can use generators with result.stdio[*] as output, sync', testGeneratorOutput, 3, true, false, false, false, 'generator', execaSync);242test('Can use generators with error.stdio[1], sync', testGeneratorOutput, 1, false, false, false, false, 'generator', execaSync);243test('Can use generators with error.stdout, sync', testGeneratorOutput, 1, false, true, false, false, 'generator', execaSync);244test('Can use generators with error.stdio[2], sync', testGeneratorOutput, 2, false, false, false, false, 'generator', execaSync);245test('Can use generators with error.stderr, sync', testGeneratorOutput, 2, false, true, false, false, 'generator', execaSync);246test('Can use generators with error.stdio[*] as output, sync', testGeneratorOutput, 3, false, false, false, false, 'generator', execaSync);247test('Can use generators with result.stdio[1], objectMode, sync', testGeneratorOutput, 1, true, false, true, false, 'generator', execaSync);248test('Can use generators with result.stdout, objectMode, sync', testGeneratorOutput, 1, true, true, true, false, 'generator', execaSync);249test('Can use generators with result.stdio[2], objectMode, sync', testGeneratorOutput, 2, true, false, true, false, 'generator', execaSync);250test('Can use generators with result.stderr, objectMode, sync', testGeneratorOutput, 2, true, true, true, false, 'generator', execaSync);251test('Can use generators with result.stdio[*] as output, objectMode, sync', testGeneratorOutput, 3, true, false, true, false, 'generator', execaSync);252test('Can use generators with error.stdio[1], objectMode, sync', testGeneratorOutput, 1, false, false, true, false, 'generator', execaSync);253test('Can use generators with error.stdout, objectMode, sync', testGeneratorOutput, 1, false, true, true, false, 'generator', execaSync);254test('Can use generators with error.stdio[2], objectMode, sync', testGeneratorOutput, 2, false, false, true, false, 'generator', execaSync);255test('Can use generators with error.stderr, objectMode, sync', testGeneratorOutput, 2, false, true, true, false, 'generator', execaSync);256test('Can use generators with error.stdio[*] as output, objectMode, sync', testGeneratorOutput, 3, false, false, true, false, 'generator', execaSync);257test('Can use generators with result.stdio[1], noop transform, sync', testGeneratorOutput, 1, true, false, false, true, 'generator', execaSync);258test('Can use generators with result.stdout, noop transform, sync', testGeneratorOutput, 1, true, true, false, true, 'generator', execaSync);259test('Can use generators with result.stdio[2], noop transform, sync', testGeneratorOutput, 2, true, false, false, true, 'generator', execaSync);260test('Can use generators with result.stderr, noop transform, sync', testGeneratorOutput, 2, true, true, false, true, 'generator', execaSync);261test('Can use generators with result.stdio[*] as output, noop transform, sync', testGeneratorOutput, 3, true, false, false, true, 'generator', execaSync);262test('Can use generators with error.stdio[1], noop transform, sync', testGeneratorOutput, 1, false, false, false, true, 'generator', execaSync);263test('Can use generators with error.stdout, noop transform, sync', testGeneratorOutput, 1, false, true, false, true, 'generator', execaSync);264test('Can use generators with error.stdio[2], noop transform, sync', testGeneratorOutput, 2, false, false, false, true, 'generator', execaSync);265test('Can use generators with error.stderr, noop transform, sync', testGeneratorOutput, 2, false, true, false, true, 'generator', execaSync);266test('Can use generators with error.stdio[*] as output, noop transform, sync', testGeneratorOutput, 3, false, false, false, true, 'generator', execaSync);267test('Can use generators with result.stdio[1], objectMode, noop transform, sync', testGeneratorOutput, 1, true, false, true, true, 'generator', execaSync);268test('Can use generators with result.stdout, objectMode, noop transform, sync', testGeneratorOutput, 1, true, true, true, true, 'generator', execaSync);269test('Can use generators with result.stdio[2], objectMode, noop transform, sync', testGeneratorOutput, 2, true, false, true, true, 'generator', execaSync);270test('Can use generators with result.stderr, objectMode, noop transform, sync', testGeneratorOutput, 2, true, true, true, true, 'generator', execaSync);271test('Can use generators with result.stdio[*] as output, objectMode, noop transform, sync', testGeneratorOutput, 3, true, false, true, true, 'generator', execaSync);272test('Can use generators with error.stdio[1], objectMode, noop transform, sync', testGeneratorOutput, 1, false, false, true, true, 'generator', execaSync);273test('Can use generators with error.stdout, objectMode, noop transform, sync', testGeneratorOutput, 1, false, true, true, true, 'generator', execaSync);274test('Can use generators with error.stdio[2], objectMode, noop transform, sync', testGeneratorOutput, 2, false, false, true, true, 'generator', execaSync);275test('Can use generators with error.stderr, objectMode, noop transform, sync', testGeneratorOutput, 2, false, true, true, true, 'generator', execaSync);276test('Can use generators with error.stdio[*] as output, objectMode, noop transform, sync', testGeneratorOutput, 3, false, false, true, true, 'generator', execaSync);277test('Can use duplexes with result.stdio[1]', testGeneratorOutput, 1, true, false, false, false, 'duplex', execa);278test('Can use duplexes with result.stdout', testGeneratorOutput, 1, true, true, false, false, 'duplex', execa);279test('Can use duplexes with result.stdio[2]', testGeneratorOutput, 2, true, false, false, false, 'duplex', execa);280test('Can use duplexes with result.stderr', testGeneratorOutput, 2, true, true, false, false, 'duplex', execa);281test('Can use duplexes with result.stdio[*] as output', testGeneratorOutput, 3, true, false, false, false, 'duplex', execa);282test('Can use duplexes with error.stdio[1]', testGeneratorOutput, 1, false, false, false, false, 'duplex', execa);283test('Can use duplexes with error.stdout', testGeneratorOutput, 1, false, true, false, false, 'duplex', execa);284test('Can use duplexes with error.stdio[2]', testGeneratorOutput, 2, false, false, false, false, 'duplex', execa);285test('Can use duplexes with error.stderr', testGeneratorOutput, 2, false, true, false, false, 'duplex', execa);286test('Can use duplexes with error.stdio[*] as output', testGeneratorOutput, 3, false, false, false, false, 'duplex', execa);287test('Can use duplexes with result.stdio[1], objectMode', testGeneratorOutput, 1, true, false, true, false, 'duplex', execa);288test('Can use duplexes with result.stdout, objectMode', testGeneratorOutput, 1, true, true, true, false, 'duplex', execa);289test('Can use duplexes with result.stdio[2], objectMode', testGeneratorOutput, 2, true, false, true, false, 'duplex', execa);290test('Can use duplexes with result.stderr, objectMode', testGeneratorOutput, 2, true, true, true, false, 'duplex', execa);291test('Can use duplexes with result.stdio[*] as output, objectMode', testGeneratorOutput, 3, true, false, true, false, 'duplex', execa);292test('Can use duplexes with error.stdio[1], objectMode', testGeneratorOutput, 1, false, false, true, false, 'duplex', execa);293test('Can use duplexes with error.stdout, objectMode', testGeneratorOutput, 1, false, true, true, false, 'duplex', execa);294test('Can use duplexes with error.stdio[2], objectMode', testGeneratorOutput, 2, false, false, true, false, 'duplex', execa);295test('Can use duplexes with error.stderr, objectMode', testGeneratorOutput, 2, false, true, true, false, 'duplex', execa);296test('Can use duplexes with error.stdio[*] as output, objectMode', testGeneratorOutput, 3, false, false, true, false, 'duplex', execa);297test('Can use duplexes with result.stdio[1], noop transform', testGeneratorOutput, 1, true, false, false, true, 'duplex', execa);298test('Can use duplexes with result.stdout, noop transform', testGeneratorOutput, 1, true, true, false, true, 'duplex', execa);299test('Can use duplexes with result.stdio[2], noop transform', testGeneratorOutput, 2, true, false, false, true, 'duplex', execa);300test('Can use duplexes with result.stderr, noop transform', testGeneratorOutput, 2, true, true, false, true, 'duplex', execa);301test('Can use duplexes with result.stdio[*] as output, noop transform', testGeneratorOutput, 3, true, false, false, true, 'duplex', execa);302test('Can use duplexes with error.stdio[1], noop transform', testGeneratorOutput, 1, false, false, false, true, 'duplex', execa);303test('Can use duplexes with error.stdout, noop transform', testGeneratorOutput, 1, false, true, false, true, 'duplex', execa);304test('Can use duplexes with error.stdio[2], noop transform', testGeneratorOutput, 2, false, false, false, true, 'duplex', execa);305test('Can use duplexes with error.stderr, noop transform', testGeneratorOutput, 2, false, true, false, true, 'duplex', execa);306test('Can use duplexes with error.stdio[*] as output, noop transform', testGeneratorOutput, 3, false, false, false, true, 'duplex', execa);307test('Can use duplexes with result.stdio[1], objectMode, noop transform', testGeneratorOutput, 1, true, false, true, true, 'duplex', execa);308test('Can use duplexes with result.stdout, objectMode, noop transform', testGeneratorOutput, 1, true, true, true, true, 'duplex', execa);309test('Can use duplexes with result.stdio[2], objectMode, noop transform', testGeneratorOutput, 2, true, false, true, true, 'duplex', execa);310test('Can use duplexes with result.stderr, objectMode, noop transform', testGeneratorOutput, 2, true, true, true, true, 'duplex', execa);311test('Can use duplexes with result.stdio[*] as output, objectMode, noop transform', testGeneratorOutput, 3, true, false, true, true, 'duplex', execa);312test('Can use duplexes with error.stdio[1], objectMode, noop transform', testGeneratorOutput, 1, false, false, true, true, 'duplex', execa);313test('Can use duplexes with error.stdout, objectMode, noop transform', testGeneratorOutput, 1, false, true, true, true, 'duplex', execa);314test('Can use duplexes with error.stdio[2], objectMode, noop transform', testGeneratorOutput, 2, false, false, true, true, 'duplex', execa);315test('Can use duplexes with error.stderr, objectMode, noop transform', testGeneratorOutput, 2, false, true, true, true, 'duplex', execa);316test('Can use duplexes with error.stdio[*] as output, objectMode, noop transform', testGeneratorOutput, 3, false, false, true, true, 'duplex', execa);317test('Can use webTransforms with result.stdio[1]', testGeneratorOutput, 1, true, false, false, false, 'webTransform', execa);318test('Can use webTransforms with result.stdout', testGeneratorOutput, 1, true, true, false, false, 'webTransform', execa);319test('Can use webTransforms with result.stdio[2]', testGeneratorOutput, 2, true, false, false, false, 'webTransform', execa);320test('Can use webTransforms with result.stderr', testGeneratorOutput, 2, true, true, false, false, 'webTransform', execa);321test('Can use webTransforms with result.stdio[*] as output', testGeneratorOutput, 3, true, false, false, false, 'webTransform', execa);322test('Can use webTransforms with error.stdio[1]', testGeneratorOutput, 1, false, false, false, false, 'webTransform', execa);323test('Can use webTransforms with error.stdout', testGeneratorOutput, 1, false, true, false, false, 'webTransform', execa);324test('Can use webTransforms with error.stdio[2]', testGeneratorOutput, 2, false, false, false, false, 'webTransform', execa);325test('Can use webTransforms with error.stderr', testGeneratorOutput, 2, false, true, false, false, 'webTransform', execa);326test('Can use webTransforms with error.stdio[*] as output', testGeneratorOutput, 3, false, false, false, false, 'webTransform', execa);327test('Can use webTransforms with result.stdio[1], objectMode', testGeneratorOutput, 1, true, false, true, false, 'webTransform', execa);328test('Can use webTransforms with result.stdout, objectMode', testGeneratorOutput, 1, true, true, true, false, 'webTransform', execa);329test('Can use webTransforms with result.stdio[2], objectMode', testGeneratorOutput, 2, true, false, true, false, 'webTransform', execa);330test('Can use webTransforms with result.stderr, objectMode', testGeneratorOutput, 2, true, true, true, false, 'webTransform', execa);331test('Can use webTransforms with result.stdio[*] as output, objectMode', testGeneratorOutput, 3, true, false, true, false, 'webTransform', execa);332test('Can use webTransforms with error.stdio[1], objectMode', testGeneratorOutput, 1, false, false, true, false, 'webTransform', execa);333test('Can use webTransforms with error.stdout, objectMode', testGeneratorOutput, 1, false, true, true, false, 'webTransform', execa);334test('Can use webTransforms with error.stdio[2], objectMode', testGeneratorOutput, 2, false, false, true, false, 'webTransform', execa);335test('Can use webTransforms with error.stderr, objectMode', testGeneratorOutput, 2, false, true, true, false, 'webTransform', execa);336test('Can use webTransforms with error.stdio[*] as output, objectMode', testGeneratorOutput, 3, false, false, true, false, 'webTransform', execa);337test('Can use webTransforms with result.stdio[1], noop transform', testGeneratorOutput, 1, true, false, false, true, 'webTransform', execa);338test('Can use webTransforms with result.stdout, noop transform', testGeneratorOutput, 1, true, true, false, true, 'webTransform', execa);339test('Can use webTransforms with result.stdio[2], noop transform', testGeneratorOutput, 2, true, false, false, true, 'webTransform', execa);340test('Can use webTransforms with result.stderr, noop transform', testGeneratorOutput, 2, true, true, false, true, 'webTransform', execa);341test('Can use webTransforms with result.stdio[*] as output, noop transform', testGeneratorOutput, 3, true, false, false, true, 'webTransform', execa);342test('Can use webTransforms with error.stdio[1], noop transform', testGeneratorOutput, 1, false, false, false, true, 'webTransform', execa);343test('Can use webTransforms with error.stdout, noop transform', testGeneratorOutput, 1, false, true, false, true, 'webTransform', execa);344test('Can use webTransforms with error.stdio[2], noop transform', testGeneratorOutput, 2, false, false, false, true, 'webTransform', execa);345test('Can use webTransforms with error.stderr, noop transform', testGeneratorOutput, 2, false, true, false, true, 'webTransform', execa);346test('Can use webTransforms with error.stdio[*] as output, noop transform', testGeneratorOutput, 3, false, false, false, true, 'webTransform', execa);347test('Can use webTransforms with result.stdio[1], objectMode, noop transform', testGeneratorOutput, 1, true, false, true, true, 'webTransform', execa);348test('Can use webTransforms with result.stdout, objectMode, noop transform', testGeneratorOutput, 1, true, true, true, true, 'webTransform', execa);349test('Can use webTransforms with result.stdio[2], objectMode, noop transform', testGeneratorOutput, 2, true, false, true, true, 'webTransform', execa);350test('Can use webTransforms with result.stderr, objectMode, noop transform', testGeneratorOutput, 2, true, true, true, true, 'webTransform', execa);351test('Can use webTransforms with result.stdio[*] as output, objectMode, noop transform', testGeneratorOutput, 3, true, false, true, true, 'webTransform', execa);352test('Can use webTransforms with error.stdio[1], objectMode, noop transform', testGeneratorOutput, 1, false, false, true, true, 'webTransform', execa);353test('Can use webTransforms with error.stdout, objectMode, noop transform', testGeneratorOutput, 1, false, true, true, true, 'webTransform', execa);354test('Can use webTransforms with error.stdio[2], objectMode, noop transform', testGeneratorOutput, 2, false, false, true, true, 'webTransform', execa);355test('Can use webTransforms with error.stderr, objectMode, noop transform', testGeneratorOutput, 2, false, true, true, true, 'webTransform', execa);356test('Can use webTransforms with error.stdio[*] as output, objectMode, noop transform', testGeneratorOutput, 3, false, false, true, true, 'webTransform', execa);357358// eslint-disable-next-line max-params359const testGeneratorOutputPipe = async (t, fdNumber, useShortcutProperty, objectMode, addNoopTransform, type) => {360 const {generators, output, getStreamMethod} = getOutputObjectMode(objectMode, addNoopTransform, type, true);361 const subprocess = execa('noop-fd.js', [`${fdNumber}`, foobarString], getStdio(fdNumber, generators));362 const stream = useShortcutProperty ? [subprocess.stdout, subprocess.stderr][fdNumber - 1] : subprocess.stdio[fdNumber];363 const [result] = await Promise.all([getStreamMethod(stream), subprocess]);364 t.deepEqual(result, output);365};366367test('Can use generators with subprocess.stdio[1]', testGeneratorOutputPipe, 1, false, false, false, 'generator');368test('Can use generators with subprocess.stdout', testGeneratorOutputPipe, 1, true, false, false, 'generator');369test('Can use generators with subprocess.stdio[2]', testGeneratorOutputPipe, 2, false, false, false, 'generator');370test('Can use generators with subprocess.stderr', testGeneratorOutputPipe, 2, true, false, false, 'generator');371test('Can use generators with subprocess.stdio[*] as output', testGeneratorOutputPipe, 3, false, false, false, 'generator');372test('Can use generators with subprocess.stdio[1], objectMode', testGeneratorOutputPipe, 1, false, true, false, 'generator');373test('Can use generators with subprocess.stdout, objectMode', testGeneratorOutputPipe, 1, true, true, false, 'generator');374test('Can use generators with subprocess.stdio[2], objectMode', testGeneratorOutputPipe, 2, false, true, false, 'generator');375test('Can use generators with subprocess.stderr, objectMode', testGeneratorOutputPipe, 2, true, true, false, 'generator');376test('Can use generators with subprocess.stdio[*] as output, objectMode', testGeneratorOutputPipe, 3, false, true, false, 'generator');377test('Can use generators with subprocess.stdio[1], noop transform', testGeneratorOutputPipe, 1, false, false, true, 'generator');378test('Can use generators with subprocess.stdout, noop transform', testGeneratorOutputPipe, 1, true, false, true, 'generator');379test('Can use generators with subprocess.stdio[2], noop transform', testGeneratorOutputPipe, 2, false, false, true, 'generator');380test('Can use generators with subprocess.stderr, noop transform', testGeneratorOutputPipe, 2, true, false, true, 'generator');381test('Can use generators with subprocess.stdio[*] as output, noop transform', testGeneratorOutputPipe, 3, false, false, true, 'generator');382test('Can use generators with subprocess.stdio[1], objectMode, noop transform', testGeneratorOutputPipe, 1, false, true, true, 'generator');383test('Can use generators with subprocess.stdout, objectMode, noop transform', testGeneratorOutputPipe, 1, true, true, true, 'generator');384test('Can use generators with subprocess.stdio[2], objectMode, noop transform', testGeneratorOutputPipe, 2, false, true, true, 'generator');385test('Can use generators with subprocess.stderr, objectMode, noop transform', testGeneratorOutputPipe, 2, true, true, true, 'generator');386test('Can use generators with subprocess.stdio[*] as output, objectMode, noop transform', testGeneratorOutputPipe, 3, false, true, true, 'generator');387test('Can use duplexes with subprocess.stdio[1]', testGeneratorOutputPipe, 1, false, false, false, 'duplex');388test('Can use duplexes with subprocess.stdout', testGeneratorOutputPipe, 1, true, false, false, 'duplex');389test('Can use duplexes with subprocess.stdio[2]', testGeneratorOutputPipe, 2, false, false, false, 'duplex');390test('Can use duplexes with subprocess.stderr', testGeneratorOutputPipe, 2, true, false, false, 'duplex');391test('Can use duplexes with subprocess.stdio[*] as output', testGeneratorOutputPipe, 3, false, false, false, 'duplex');392test('Can use duplexes with subprocess.stdio[1], objectMode', testGeneratorOutputPipe, 1, false, true, false, 'duplex');393test('Can use duplexes with subprocess.stdout, objectMode', testGeneratorOutputPipe, 1, true, true, false, 'duplex');394test('Can use duplexes with subprocess.stdio[2], objectMode', testGeneratorOutputPipe, 2, false, true, false, 'duplex');395test('Can use duplexes with subprocess.stderr, objectMode', testGeneratorOutputPipe, 2, true, true, false, 'duplex');396test('Can use duplexes with subprocess.stdio[*] as output, objectMode', testGeneratorOutputPipe, 3, false, true, false, 'duplex');397test('Can use duplexes with subprocess.stdio[1], noop transform', testGeneratorOutputPipe, 1, false, false, true, 'duplex');398test('Can use duplexes with subprocess.stdout, noop transform', testGeneratorOutputPipe, 1, true, false, true, 'duplex');399test('Can use duplexes with subprocess.stdio[2], noop transform', testGeneratorOutputPipe, 2, false, false, true, 'duplex');400test('Can use duplexes with subprocess.stderr, noop transform', testGeneratorOutputPipe, 2, true, false, true, 'duplex');401test('Can use duplexes with subprocess.stdio[*] as output, noop transform', testGeneratorOutputPipe, 3, false, false, true, 'duplex');402test('Can use duplexes with subprocess.stdio[1], objectMode, noop transform', testGeneratorOutputPipe, 1, false, true, true, 'duplex');403test('Can use duplexes with subprocess.stdout, objectMode, noop transform', testGeneratorOutputPipe, 1, true, true, true, 'duplex');404test('Can use duplexes with subprocess.stdio[2], objectMode, noop transform', testGeneratorOutputPipe, 2, false, true, true, 'duplex');405test('Can use duplexes with subprocess.stderr, objectMode, noop transform', testGeneratorOutputPipe, 2, true, true, true, 'duplex');406test('Can use duplexes with subprocess.stdio[*] as output, objectMode, noop transform', testGeneratorOutputPipe, 3, false, true, true, 'duplex');407test('Can use webTransforms with subprocess.stdio[1]', testGeneratorOutputPipe, 1, false, false, false, 'webTransform');408test('Can use webTransforms with subprocess.stdout', testGeneratorOutputPipe, 1, true, false, false, 'webTransform');409test('Can use webTransforms with subprocess.stdio[2]', testGeneratorOutputPipe, 2, false, false, false, 'webTransform');410test('Can use webTransforms with subprocess.stderr', testGeneratorOutputPipe, 2, true, false, false, 'webTransform');411test('Can use webTransforms with subprocess.stdio[*] as output', testGeneratorOutputPipe, 3, false, false, false, 'webTransform');412test('Can use webTransforms with subprocess.stdio[1], objectMode', testGeneratorOutputPipe, 1, false, true, false, 'webTransform');413test('Can use webTransforms with subprocess.stdout, objectMode', testGeneratorOutputPipe, 1, true, true, false, 'webTransform');414test('Can use webTransforms with subprocess.stdio[2], objectMode', testGeneratorOutputPipe, 2, false, true, false, 'webTransform');415test('Can use webTransforms with subprocess.stderr, objectMode', testGeneratorOutputPipe, 2, true, true, false, 'webTransform');416test('Can use webTransforms with subprocess.stdio[*] as output, objectMode', testGeneratorOutputPipe, 3, false, true, false, 'webTransform');417test('Can use webTransforms with subprocess.stdio[1], noop transform', testGeneratorOutputPipe, 1, false, false, true, 'webTransform');418test('Can use webTransforms with subprocess.stdout, noop transform', testGeneratorOutputPipe, 1, true, false, true, 'webTransform');419test('Can use webTransforms with subprocess.stdio[2], noop transform', testGeneratorOutputPipe, 2, false, false, true, 'webTransform');420test('Can use webTransforms with subprocess.stderr, noop transform', testGeneratorOutputPipe, 2, true, false, true, 'webTransform');421test('Can use webTransforms with subprocess.stdio[*] as output, noop transform', testGeneratorOutputPipe, 3, false, false, true, 'webTransform');422test('Can use webTransforms with subprocess.stdio[1], objectMode, noop transform', testGeneratorOutputPipe, 1, false, true, true, 'webTransform');423test('Can use webTransforms with subprocess.stdout, objectMode, noop transform', testGeneratorOutputPipe, 1, true, true, true, 'webTransform');424test('Can use webTransforms with subprocess.stdio[2], objectMode, noop transform', testGeneratorOutputPipe, 2, false, true, true, 'webTransform');425test('Can use webTransforms with subprocess.stderr, objectMode, noop transform', testGeneratorOutputPipe, 2, true, true, true, 'webTransform');426test('Can use webTransforms with subprocess.stdio[*] as output, objectMode, noop transform', testGeneratorOutputPipe, 3, false, true, true, 'webTransform');427428const getAllStdioOption = (stdioOption, encoding, objectMode) => {429 if (stdioOption) {430 return 'pipe';431 }432433 if (objectMode) {434 return outputObjectGenerator();435 }436437 return encoding === 'utf8' ? uppercaseGenerator() : uppercaseBufferGenerator();438};439440const getStdoutStderrOutput = ({output, stdioOption, encoding, objectMode, lines}) => {441 if (objectMode && !stdioOption) {442 return encoding === 'utf8' ? [foobarObject, foobarObject] : [foobarObject];443 }444445 const stdioOutput = stdioOption ? output : output.toUpperCase();446447 if (encoding === 'hex') {448 return Buffer.from(stdioOutput).toString('hex');449 }450451 if (encoding === 'buffer') {452 return textEncoder.encode(stdioOutput);453 }454455 return lines ? stdioOutput.trim().split('\n').map(string => `${string}\n`) : stdioOutput;456};457458const getAllOutput = ({stdoutOutput, stderrOutput, encoding, objectMode, lines}) => {459 if (objectMode || (lines && encoding === 'utf8')) {460 return [stdoutOutput, stderrOutput].flat();461 }462463 return encoding === 'buffer'464 ? new Uint8Array([...stdoutOutput, ...stderrOutput])465 : `${stdoutOutput}${stderrOutput}`;466};467468// eslint-disable-next-line max-params469const testGeneratorAll = async (t, reject, encoding, objectMode, stdoutOption, stderrOption, lines, execaMethod) => {470 const fixtureName = reject ? 'all.js' : 'all-fail.js';471 const {stdout, stderr, all} = await execaMethod(fixtureName, {472 all: true,473 reject,474 stdout: getAllStdioOption(stdoutOption, encoding, objectMode),475 stderr: getAllStdioOption(stderrOption, encoding, objectMode),476 encoding,477 lines,478 stripFinalNewline: false,479 });480481 const stdoutOutput = getStdoutStderrOutput({output: 'std\nout\n', stdioOption: stdoutOption, encoding, objectMode, lines});482 t.deepEqual(stdout, stdoutOutput);483 const stderrOutput = getStdoutStderrOutput({output: 'std\nerr\n', stdioOption: stderrOption, encoding, objectMode, lines});484 t.deepEqual(stderr, stderrOutput);485 const allOutput = getAllOutput({stdoutOutput, stderrOutput, encoding, objectMode, lines});486 if (Array.isArray(all) && Array.isArray(allOutput)) {487 t.deepEqual([...all].sort(), [...allOutput].sort());488 } else {489 t.deepEqual(all, allOutput);490 }491};492493test('Can use generators with result.all = transform + transform', testGeneratorAll, true, 'utf8', false, false, false, false, execa);494test('Can use generators with error.all = transform + transform', testGeneratorAll, false, 'utf8', false, false, false, false, execa);495test('Can use generators with result.all = transform + transform, encoding "buffer"', testGeneratorAll, true, 'buffer', false, false, false, false, execa);496test('Can use generators with error.all = transform + transform, encoding "buffer"', testGeneratorAll, false, 'buffer', false, false, false, false, execa);497test('Can use generators with result.all = transform + transform, encoding "hex"', testGeneratorAll, true, 'hex', false, false, false, false, execa);498test('Can use generators with error.all = transform + transform, encoding "hex"', testGeneratorAll, false, 'hex', false, false, false, false, execa);499test('Can use generators with result.all = transform + pipe', testGeneratorAll, true, 'utf8', false, false, true, false, execa);500test('Can use generators with error.all = transform + pipe', testGeneratorAll, false, 'utf8', false, false, true, false, execa);501test('Can use generators with result.all = transform + pipe, encoding "buffer"', testGeneratorAll, true, 'buffer', false, false, true, false, execa);502test('Can use generators with error.all = transform + pipe, encoding "buffer"', testGeneratorAll, false, 'buffer', false, false, true, false, execa);503test('Can use generators with result.all = transform + pipe, encoding "hex"', testGeneratorAll, true, 'hex', false, false, true, false, execa);504test('Can use generators with error.all = transform + pipe, encoding "hex"', testGeneratorAll, false, 'hex', false, false, true, false, execa);505test('Can use generators with result.all = pipe + transform', testGeneratorAll, true, 'utf8', false, true, false, false, execa);506test('Can use generators with error.all = pipe + transform', testGeneratorAll, false, 'utf8', false, true, false, false, execa);507test('Can use generators with result.all = pipe + transform, encoding "buffer"', testGeneratorAll, true, 'buffer', false, true, false, false, execa);508test('Can use generators with error.all = pipe + transform, encoding "buffer"', testGeneratorAll, false, 'buffer', false, true, false, false, execa);509test('Can use generators with result.all = pipe + transform, encoding "hex"', testGeneratorAll, true, 'hex', false, true, false, false, execa);510test('Can use generators with error.all = pipe + transform, encoding "hex"', testGeneratorAll, false, 'hex', false, true, false, false, execa);511test('Can use generators with result.all = transform + transform, objectMode', testGeneratorAll, true, 'utf8', true, false, false, false, execa);512test('Can use generators with error.all = transform + transform, objectMode', testGeneratorAll, false, 'utf8', true, false, false, false, execa);513test('Can use generators with result.all = transform + transform, objectMode, encoding "buffer"', testGeneratorAll, true, 'buffer', true, false, false, false, execa);514test('Can use generators with error.all = transform + transform, objectMode, encoding "buffer"', testGeneratorAll, false, 'buffer', true, false, false, false, execa);515test('Can use generators with result.all = transform + transform, objectMode, encoding "hex"', testGeneratorAll, true, 'hex', true, false, false, false, execa);516test('Can use generators with error.all = transform + transform, objectMode, encoding "hex"', testGeneratorAll, false, 'hex', true, false, false, false, execa);517test('Can use generators with result.all = transform + pipe, objectMode', testGeneratorAll, true, 'utf8', true, false, true, false, execa);518test('Can use generators with error.all = transform + pipe, objectMode', testGeneratorAll, false, 'utf8', true, false, true, false, execa);519test('Can use generators with result.all = transform + pipe, objectMode, encoding "buffer"', testGeneratorAll, true, 'buffer', true, false, true, false, execa);520test('Can use generators with error.all = transform + pipe, objectMode, encoding "buffer"', testGeneratorAll, false, 'buffer', true, false, true, false, execa);521test('Can use generators with result.all = transform + pipe, objectMode, encoding "hex"', testGeneratorAll, true, 'hex', true, false, true, false, execa);522test('Can use generators with error.all = transform + pipe, objectMode, encoding "hex"', testGeneratorAll, false, 'hex', true, false, true, false, execa);523test('Can use generators with result.all = pipe + transform, objectMode', testGeneratorAll, true, 'utf8', true, true, false, false, execa);524test('Can use generators with error.all = pipe + transform, objectMode', testGeneratorAll, false, 'utf8', true, true, false, false, execa);525test('Can use generators with result.all = pipe + transform, objectMode, encoding "buffer"', testGeneratorAll, true, 'buffer', true, true, false, false, execa);526test('Can use generators with error.all = pipe + transform, objectMode, encoding "buffer"', testGeneratorAll, false, 'buffer', true, true, false, false, execa);527test('Can use generators with result.all = pipe + transform, objectMode, encoding "hex"', testGeneratorAll, true, 'hex', true, true, false, false, execa);528test('Can use generators with error.all = pipe + transform, objectMode, encoding "hex"', testGeneratorAll, false, 'hex', true, true, false, false, execa);529test('Can use generators with result.all = transform + transform, sync', testGeneratorAll, true, 'utf8', false, false, false, false, execaSync);530test('Can use generators with error.all = transform + transform, sync', testGeneratorAll, false, 'utf8', false, false, false, false, execaSync);531test('Can use generators with result.all = transform + transform, encoding "buffer", sync', testGeneratorAll, true, 'buffer', false, false, false, false, execaSync);532test('Can use generators with error.all = transform + transform, encoding "buffer", sync', testGeneratorAll, false, 'buffer', false, false, false, false, execaSync);533test('Can use generators with result.all = transform + transform, encoding "hex", sync', testGeneratorAll, true, 'hex', false, false, false, false, execaSync);534test('Can use generators with error.all = transform + transform, encoding "hex", sync', testGeneratorAll, false, 'hex', false, false, false, false, execaSync);535test('Can use generators with result.all = transform + pipe, sync', testGeneratorAll, true, 'utf8', false, false, true, false, execaSync);536test('Can use generators with error.all = transform + pipe, sync', testGeneratorAll, false, 'utf8', false, false, true, false, execaSync);537test('Can use generators with result.all = transform + pipe, encoding "buffer", sync', testGeneratorAll, true, 'buffer', false, false, true, false, execaSync);538test('Can use generators with error.all = transform + pipe, encoding "buffer", sync', testGeneratorAll, false, 'buffer', false, false, true, false, execaSync);539test('Can use generators with result.all = transform + pipe, encoding "hex", sync', testGeneratorAll, true, 'hex', false, false, true, false, execaSync);540test('Can use generators with error.all = transform + pipe, encoding "hex", sync', testGeneratorAll, false, 'hex', false, false, true, false, execaSync);541test('Can use generators with result.all = pipe + transform, sync', testGeneratorAll, true, 'utf8', false, true, false, false, execaSync);542test('Can use generators with error.all = pipe + transform, sync', testGeneratorAll, false, 'utf8', false, true, false, false, execaSync);543test('Can use generators with result.all = pipe + transform, encoding "buffer", sync', testGeneratorAll, true, 'buffer', false, true, false, false, execaSync);544test('Can use generators with error.all = pipe + transform, encoding "buffer", sync', testGeneratorAll, false, 'buffer', false, true, false, false, execaSync);545test('Can use generators with result.all = pipe + transform, encoding "hex", sync', testGeneratorAll, true, 'hex', false, true, false, false, execaSync);546test('Can use generators with error.all = pipe + transform, encoding "hex", sync', testGeneratorAll, false, 'hex', false, true, false, false, execaSync);547test('Can use generators with result.all = transform + transform, objectMode, sync', testGeneratorAll, true, 'utf8', true, false, false, false, execaSync);548test('Can use generators with error.all = transform + transform, objectMode, sync', testGeneratorAll, false, 'utf8', true, false, false, false, execaSync);549test('Can use generators with result.all = transform + transform, objectMode, encoding "buffer", sync', testGeneratorAll, true, 'buffer', true, false, false, false, execaSync);550test('Can use generators with error.all = transform + transform, objectMode, encoding "buffer", sync', testGeneratorAll, false, 'buffer', true, false, false, false, execaSync);551test('Can use generators with result.all = transform + transform, objectMode, encoding "hex", sync', testGeneratorAll, true, 'hex', true, false, false, false, execaSync);552test('Can use generators with error.all = transform + transform, objectMode, encoding "hex", sync', testGeneratorAll, false, 'hex', true, false, false, false, execaSync);553test('Can use generators with result.all = transform + pipe, objectMode, sync', testGeneratorAll, true, 'utf8', true, false, true, false, execaSync);554test('Can use generators with error.all = transform + pipe, objectMode, sync', testGeneratorAll, false, 'utf8', true, false, true, false, execaSync);555test('Can use generators with result.all = transform + pipe, objectMode, encoding "buffer", sync', testGeneratorAll, true, 'buffer', true, false, true, false, execaSync);556test('Can use generators with error.all = transform + pipe, objectMode, encoding "buffer", sync', testGeneratorAll, false, 'buffer', true, false, true, false, execaSync);557test('Can use generators with result.all = transform + pipe, objectMode, encoding "hex", sync', testGeneratorAll, true, 'hex', true, false, true, false, execaSync);558test('Can use generators with error.all = transform + pipe, objectMode, encoding "hex", sync', testGeneratorAll, false, 'hex', true, false, true, false, execaSync);559test('Can use generators with result.all = pipe + transform, objectMode, sync', testGeneratorAll, true, 'utf8', true, true, false, false, execaSync);560test('Can use generators with error.all = pipe + transform, objectMode, sync', testGeneratorAll, false, 'utf8', true, true, false, false, execaSync);561test('Can use generators with result.all = pipe + transform, objectMode, encoding "buffer", sync', testGeneratorAll, true, 'buffer', true, true, false, false, execaSync);562test('Can use generators with error.all = pipe + transform, objectMode, encoding "buffer", sync', testGeneratorAll, false, 'buffer', true, true, false, false, execaSync);563test('Can use generators with result.all = pipe + transform, objectMode, encoding "hex", sync', testGeneratorAll, true, 'hex', true, true, false, false, execaSync);564test('Can use generators with error.all = pipe + transform, objectMode, encoding "hex", sync', testGeneratorAll, false, 'hex', true, true, false, false, execaSync);565test('Can use generators with result.all = transform + transform, lines', testGeneratorAll, true, 'utf8', false, false, false, true, execa);566test('Can use generators with error.all = transform + transform, lines', testGeneratorAll, false, 'utf8', false, false, false, true, execa);567test('Can use generators with result.all = transform + transform, encoding "buffer", lines', testGeneratorAll, true, 'buffer', false, false, false, true, execa);568test('Can use generators with error.all = transform + transform, encoding "buffer", lines', testGeneratorAll, false, 'buffer', false, false, false, true, execa);569test('Can use generators with result.all = transform + transform, encoding "hex", lines', testGeneratorAll, true, 'hex', false, false, false, true, execa);570test('Can use generators with error.all = transform + transform, encoding "hex", lines', testGeneratorAll, false, 'hex', false, false, false, true, execa);571test('Can use generators with result.all = transform + pipe, lines', testGeneratorAll, true, 'utf8', false, false, true, true, execa);572test('Can use generators with error.all = transform + pipe, lines', testGeneratorAll, false, 'utf8', false, false, true, true, execa);573test('Can use generators with result.all = transform + pipe, encoding "buffer", lines', testGeneratorAll, true, 'buffer', false, false, true, true, execa);574test('Can use generators with error.all = transform + pipe, encoding "buffer", lines', testGeneratorAll, false, 'buffer', false, false, true, true, execa);575test('Can use generators with result.all = transform + pipe, encoding "hex", lines', testGeneratorAll, true, 'hex', false, false, true, true, execa);576test('Can use generators with error.all = transform + pipe, encoding "hex", lines', testGeneratorAll, false, 'hex', false, false, true, true, execa);577test('Can use generators with result.all = pipe + transform, lines', testGeneratorAll, true, 'utf8', false, true, false, true, execa);578test('Can use generators with error.all = pipe + transform, lines', testGeneratorAll, false, 'utf8', false, true, false, true, execa);579test('Can use generators with result.all = pipe + transform, encoding "buffer", lines', testGeneratorAll, true, 'buffer', false, true, false, true, execa);580test('Can use generators with error.all = pipe + transform, encoding "buffer", lines', testGeneratorAll, false, 'buffer', false, true, false, true, execa);581test('Can use generators with result.all = pipe + transform, encoding "hex", lines', testGeneratorAll, true, 'hex', false, true, false, true, execa);582test('Can use generators with error.all = pipe + transform, encoding "hex", lines', testGeneratorAll, false, 'hex', false, true, false, true, execa);583test('Can use generators with result.all = transform + transform, objectMode, lines', testGeneratorAll, true, 'utf8', true, false, false, true, execa);584test('Can use generators with error.all = transform + transform, objectMode, lines', testGeneratorAll, false, 'utf8', true, false, false, true, execa);585test('Can use generators with result.all = transform + transform, objectMode, encoding "buffer", lines', testGeneratorAll, true, 'buffer', true, false, false, true, execa);586test('Can use generators with error.all = transform + transform, objectMode, encoding "buffer", lines', testGeneratorAll, false, 'buffer', true, false, false, true, execa);587test('Can use generators with result.all = transform + transform, objectMode, encoding "hex", lines', testGeneratorAll, true, 'hex', true, false, false, true, execa);588test('Can use generators with error.all = transform + transform, objectMode, encoding "hex", lines', testGeneratorAll, false, 'hex', true, false, false, true, execa);589test('Can use generators with result.all = transform + pipe, objectMode, lines', testGeneratorAll, true, 'utf8', true, false, true, true, execa);590test('Can use generators with error.all = transform + pipe, objectMode, lines', testGeneratorAll, false, 'utf8', true, false, true, true, execa);591test('Can use generators with result.all = transform + pipe, objectMode, encoding "buffer", lines', testGeneratorAll, true, 'buffer', true, false, true, true, execa);592test('Can use generators with error.all = transform + pipe, objectMode, encoding "buffer", lines', testGeneratorAll, false, 'buffer', true, false, true, true, execa);593test('Can use generators with result.all = transform + pipe, objectMode, encoding "hex", lines', testGeneratorAll, true, 'hex', true, false, true, true, execa);594test('Can use generators with error.all = transform + pipe, objectMode, encoding "hex", lines', testGeneratorAll, false, 'hex', true, false, true, true, execa);595test('Can use generators with result.all = pipe + transform, objectMode, lines', testGeneratorAll, true, 'utf8', true, true, false, true, execa);596test('Can use generators with error.all = pipe + transform, objectMode, lines', testGeneratorAll, false, 'utf8', true, true, false, true, execa);597test('Can use generators with result.all = pipe + transform, objectMode, encoding "buffer", lines', testGeneratorAll, true, 'buffer', true, true, false, true, execa);598test('Can use generators with error.all = pipe + transform, objectMode, encoding "buffer", lines', testGeneratorAll, false, 'buffer', true, true, false, true, execa);599test('Can use generators with result.all = pipe + transform, objectMode, encoding "hex", lines', testGeneratorAll, true, 'hex', true, true, false, true, execa);600test('Can use generators with error.all = pipe + transform, objectMode, encoding "hex", lines', testGeneratorAll, false, 'hex', true, true, false, true, execa);601test('Can use generators with result.all = transform + transform, sync, lines', testGeneratorAll, true, 'utf8', false, false, false, true, execaSync);602test('Can use generators with error.all = transform + transform, sync, lines', testGeneratorAll, false, 'utf8', false, false, false, true, execaSync);603test('Can use generators with result.all = transform + transform, encoding "buffer", sync, lines', testGeneratorAll, true, 'buffer', false, false, false, true, execaSync);604test('Can use generators with error.all = transform + transform, encoding "buffer", sync, lines', testGeneratorAll, false, 'buffer', false, false, false, true, execaSync);605test('Can use generators with result.all = transform + transform, encoding "hex", sync, lines', testGeneratorAll, true, 'hex', false, false, false, true, execaSync);606test('Can use generators with error.all = transform + transform, encoding "hex", sync, lines', testGeneratorAll, false, 'hex', false, false, false, true, execaSync);607test('Can use generators with result.all = transform + pipe, sync, lines', testGeneratorAll, true, 'utf8', false, false, true, true, execaSync);608test('Can use generators with error.all = transform + pipe, sync, lines', testGeneratorAll, false, 'utf8', false, false, true, true, execaSync);609test('Can use generators with result.all = transform + pipe, encoding "buffer", sync, lines', testGeneratorAll, true, 'buffer', false, false, true, true, execaSync);610test('Can use generators with error.all = transform + pipe, encoding "buffer", sync, lines', testGeneratorAll, false, 'buffer', false, false, true, true, execaSync);611test('Can use generators with result.all = transform + pipe, encoding "hex", sync, lines', testGeneratorAll, true, 'hex', false, false, true, true, execaSync);612test('Can use generators with error.all = transform + pipe, encoding "hex", sync, lines', testGeneratorAll, false, 'hex', false, false, true, true, execaSync);613test('Can use generators with result.all = pipe + transform, sync, lines', testGeneratorAll, true, 'utf8', false, true, false, true, execaSync);614test('Can use generators with error.all = pipe + transform, sync, lines', testGeneratorAll, false, 'utf8', false, true, false, true, execaSync);615test('Can use generators with result.all = pipe + transform, encoding "buffer", sync, lines', testGeneratorAll, true, 'buffer', false, true, false, true, execaSync);616test('Can use generators with error.all = pipe + transform, encoding "buffer", sync, lines', testGeneratorAll, false, 'buffer', false, true, false, true, execaSync);617test('Can use generators with result.all = pipe + transform, encoding "hex", sync, lines', testGeneratorAll, true, 'hex', false, true, false, true, execaSync);618test('Can use generators with error.all = pipe + transform, encoding "hex", sync, lines', testGeneratorAll, false, 'hex', false, true, false, true, execaSync);619test('Can use generators with result.all = transform + transform, objectMode, sync, lines', testGeneratorAll, true, 'utf8', true, false, false, true, execaSync);620test('Can use generators with error.all = transform + transform, objectMode, sync, lines', testGeneratorAll, false, 'utf8', true, false, false, true, execaSync);621test('Can use generators with result.all = transform + transform, objectMode, encoding "buffer", sync, lines', testGeneratorAll, true, 'buffer', true, false, false, true, execaSync);622test('Can use generators with error.all = transform + transform, objectMode, encoding "buffer", sync, lines', testGeneratorAll, false, 'buffer', true, false, false, true, execaSync);623test('Can use generators with result.all = transform + transform, objectMode, encoding "hex", sync, lines', testGeneratorAll, true, 'hex', true, false, false, true, execaSync);624test('Can use generators with error.all = transform + transform, objectMode, encoding "hex", sync, lines', testGeneratorAll, false, 'hex', true, false, false, true, execaSync);625test('Can use generators with result.all = transform + pipe, objectMode, sync, lines', testGeneratorAll, true, 'utf8', true, false, true, true, execaSync);626test('Can use generators with error.all = transform + pipe, objectMode, sync, lines', testGeneratorAll, false, 'utf8', true, false, true, true, execaSync);627test('Can use generators with result.all = transform + pipe, objectMode, encoding "buffer", sync, lines', testGeneratorAll, true, 'buffer', true, false, true, true, execaSync);628test('Can use generators with error.all = transform + pipe, objectMode, encoding "buffer", sync, lines', testGeneratorAll, false, 'buffer', true, false, true, true, execaSync);629test('Can use generators with result.all = transform + pipe, objectMode, encoding "hex", sync, lines', testGeneratorAll, true, 'hex', true, false, true, true, execaSync);630test('Can use generators with error.all = transform + pipe, objectMode, encoding "hex", sync, lines', testGeneratorAll, false, 'hex', true, false, true, true, execaSync);631test('Can use generators with result.all = pipe + transform, objectMode, sync, lines', testGeneratorAll, true, 'utf8', true, true, false, true, execaSync);632test('Can use generators with error.all = pipe + transform, objectMode, sync, lines', testGeneratorAll, false, 'utf8', true, true, false, true, execaSync);633test('Can use generators with result.all = pipe + transform, objectMode, encoding "buffer", sync, lines', testGeneratorAll, true, 'buffer', true, true, false, true, execaSync);634test('Can use generators with error.all = pipe + transform, objectMode, encoding "buffer", sync, lines', testGeneratorAll, false, 'buffer', true, true, false, true, execaSync);635test('Can use generators with result.all = pipe + transform, objectMode, encoding "hex", sync, lines', testGeneratorAll, true, 'hex', true, true, false, true, execaSync);636test('Can use generators with error.all = pipe + transform, objectMode, encoding "hex", sync, lines', testGeneratorAll, false, 'hex', true, true, false, true, execaSync);637638const testInputOption = async (t, type, execaMethod) => {639 const {stdout} = await execaMethod('stdin-fd.js', ['0'], {stdin: generatorsMap[type].uppercase(), input: foobarUint8Array});640 t.is(stdout, foobarUppercase);641};642643test('Can use generators with input option', testInputOption, 'generator', execa);644test('Can use generators with input option, sync', testInputOption, 'generator', execaSync);645test('Can use duplexes with input option', testInputOption, 'duplex', execa);646test('Can use webTransforms with input option', testInputOption, 'webTransform', execa);647648// eslint-disable-next-line max-params649const testInputFile = async (t, stdinOption, useInputFile, reversed, execaMethod) => {650 const filePath = tempfile();651 await writeFile(filePath, foobarString);652 const options = useInputFile653 ? {inputFile: filePath, stdin: stdinOption}654 : {stdin: [{file: filePath}, stdinOption]};655 options.stdin = reversed ? options.stdin.reverse() : options.stdin;656 const {stdout} = await execaMethod('stdin-fd.js', ['0'], options);657 t.is(stdout, foobarUppercase);658 await rm(filePath);659};660661test('Can use generators with a file as input', testInputFile, uppercaseGenerator(), false, false, execa);662test('Can use generators with a file as input, reversed', testInputFile, uppercaseGenerator(), false, true, execa);663test('Can use generators with inputFile option', testInputFile, uppercaseGenerator(), true, false, execa);664test('Can use generators with a file as input, sync', testInputFile, uppercaseGenerator(), false, false, execaSync);665test('Can use generators with a file as input, reversed, sync', testInputFile, uppercaseGenerator(), false, true, execaSync);666test('Can use generators with inputFile option, sync', testInputFile, uppercaseGenerator(), true, false, execaSync);667test('Can use duplexes with a file as input', testInputFile, uppercaseBufferDuplex(), false, false, execa);668test('Can use duplexes with a file as input, reversed', testInputFile, uppercaseBufferDuplex(), false, true, execa);669test('Can use duplexes with inputFile option', testInputFile, uppercaseBufferDuplex(), true, false, execa);670test('Can use webTransforms with a file as input', testInputFile, uppercaseBufferWebTransform(), false, false, execa);671test('Can use webTransforms with a file as input, reversed', testInputFile, uppercaseBufferWebTransform(), false, true, execa);672test('Can use webTransforms with inputFile option', testInputFile, uppercaseBufferWebTransform(), true, false, execa);673674const testOutputFile = async (t, reversed, type, execaMethod) => {675 const filePath = tempfile();676 const stdoutOption = [generatorsMap[type].uppercaseBuffer(false, true), {file: filePath}];677 const reversedStdoutOption = reversed ? stdoutOption.reverse() : stdoutOption;678 const {stdout} = await execaMethod('noop-fd.js', ['1'], {stdout: reversedStdoutOption});679 t.is(stdout, foobarUppercase);680 t.is(await readFile(filePath, 'utf8'), foobarUppercase);681 await rm(filePath);682};683684test('Can use generators with a file as output', testOutputFile, false, 'generator', execa);685test('Can use generators with a file as output, reversed', testOutputFile, true, 'generator', execa);686test('Can use generators with a file as output, sync', testOutputFile, false, 'generator', execaSync);687test('Can use generators with a file as output, reversed, sync', testOutputFile, true, 'generator', execaSync);688test('Can use duplexes with a file as output', testOutputFile, false, 'duplex', execa);689test('Can use duplexes with a file as output, reversed', testOutputFile, true, 'duplex', execa);690test('Can use webTransforms with a file as output', testOutputFile, false, 'webTransform', execa);691test('Can use webTransforms with a file as output, reversed', testOutputFile, true, 'webTransform', execa);692693const testWritableDestination = async (t, type) => {694 const passThrough = new PassThrough();695 const [{stdout}, streamOutput] = await Promise.all([696 execa('noop-fd.js', ['1', foobarString], {stdout: [generatorsMap[type].uppercaseBuffer(false, true), passThrough]}),697 getStream(passThrough),698 ]);699 t.is(stdout, foobarUppercase);700 t.is(streamOutput, foobarUppercase);701};702703test('Can use generators to a Writable stream', testWritableDestination, 'generator');704test('Can use duplexes to a Writable stream', testWritableDestination, 'duplex');705test('Can use webTransforms to a Writable stream', testWritableDestination, 'webTransform');706707const testReadableSource = async (t, type) => {708 const passThrough = new PassThrough();709 const subprocess = execa('stdin-fd.js', ['0'], {stdin: [passThrough, generatorsMap[type].uppercase()]});710 passThrough.end(foobarString);711 const {stdout} = await subprocess;712 t.is(stdout, foobarUppercase);713};714715test('Can use generators from a Readable stream', testReadableSource, 'generator');716test('Can use duplexes from a Readable stream', testReadableSource, 'duplex');717test('Can use webTransforms from a Readable stream', testReadableSource, 'webTransform');718719const testInherit = async (t, type) => {720 const {stdout} = await execa('nested-inherit.js', [type]);721 t.is(stdout, foobarUppercase);722};723724test('Can use generators with "inherit"', testInherit, 'generator');725test('Can use duplexes with "inherit"', testInherit, 'duplex');726test('Can use webTransforms with "inherit"', testInherit, 'webTransform');727728const testAppendInput = async (t, reversed, type, execaMethod) => {729 const stdin = [foobarUint8Array, generatorsMap[type].uppercase(), generatorsMap[type].append()];730 const reversedStdin = reversed ? stdin.reverse() : stdin;731 const {stdout} = await execaMethod('stdin-fd.js', ['0'], {stdin: reversedStdin});732 const reversedSuffix = reversed ? casedSuffix.toUpperCase() : casedSuffix;733 t.is(stdout, `${foobarUppercase}${reversedSuffix}`);734};735736test('Can use multiple generators as input', testAppendInput, false, 'generator', execa);737test('Can use multiple generators as input, reversed', testAppendInput, true, 'generator', execa);738test('Can use multiple generators as input, sync', testAppendInput, false, 'generator', execaSync);739test('Can use multiple generators as input, reversed, sync', testAppendInput, true, 'generator', execaSync);740test('Can use multiple duplexes as input', testAppendInput, false, 'duplex', execa);741test('Can use multiple duplexes as input, reversed', testAppendInput, true, 'duplex', execa);742test('Can use multiple webTransforms as input', testAppendInput, false, 'webTransform', execa);743test('Can use multiple webTransforms as input, reversed', testAppendInput, true, 'webTransform', execa);744745const testAppendOutput = async (t, reversed, type, execaMethod) => {746 const stdoutOption = [generatorsMap[type].uppercase(), generatorsMap[type].append()];747 const reversedStdoutOption = reversed ? stdoutOption.reverse() : stdoutOption;748 const {stdout} = await execaMethod('noop-fd.js', ['1', foobarString], {stdout: reversedStdoutOption});749 const reversedSuffix = reversed ? casedSuffix.toUpperCase() : casedSuffix;750 t.is(stdout, `${foobarUppercase}${reversedSuffix}`);751};752753test('Can use multiple generators as output', testAppendOutput, false, 'generator', execa);754test('Can use multiple generators as output, reversed', testAppendOutput, true, 'generator', execa);755test('Can use multiple generators as output, sync', testAppendOutput, false, 'generator', execaSync);756test('Can use multiple generators as output, reversed, sync', testAppendOutput, true, 'generator', execaSync);757test('Can use multiple duplexes as output', testAppendOutput, false, 'duplex', execa);758test('Can use multiple duplexes as output, reversed', testAppendOutput, true, 'duplex', execa);759test('Can use multiple webTransforms as output', testAppendOutput, false, 'webTransform', execa);760test('Can use multiple webTransforms as output, reversed', testAppendOutput, true, 'webTransform', execa);761762// eslint-disable-next-line max-params763const testTwoGenerators = async (t, producesTwo, execaMethod, firstGenerator, secondGenerator = firstGenerator) => {764 const {stdout} = await execaMethod('noop-fd.js', ['1', foobarString], {stdout: [firstGenerator, secondGenerator]});765 const expectedSuffix = producesTwo ? `${casedSuffix}${casedSuffix}` : casedSuffix;766 t.is(stdout, `${foobarString}${expectedSuffix}`);767};768769test('Can use multiple identical generators', testTwoGenerators, true, execa, appendGenerator().transform);770test('Can use multiple identical generators, options object', testTwoGenerators, true, execa, appendGenerator());771test('Can use multiple identical generators, async', testTwoGenerators, true, execa, appendAsyncGenerator().transform);772test('Can use multiple identical generators, options object, async', testTwoGenerators, true, execa, appendAsyncGenerator());773test('Can use multiple identical generators, sync', testTwoGenerators, true, execaSync, appendGenerator().transform);774test('Can use multiple identical generators, options object, sync', testTwoGenerators, true, execaSync, appendGenerator());775test('Ignore duplicate identical duplexes', testTwoGenerators, false, execa, appendDuplex());776test('Ignore duplicate identical webTransforms', testTwoGenerators, false, execa, appendWebTransform());777test('Can use multiple generators with duplexes', testTwoGenerators, true, execa, appendGenerator(false, false, true), appendDuplex());778test('Can use multiple generators with webTransforms', testTwoGenerators, true, execa, appendGenerator(false, false, true), appendWebTransform());779test('Can use multiple duplexes with webTransforms', testTwoGenerators, true, execa, appendDuplex(), appendWebTransform());780781const testGeneratorSyntax = async (t, type, usePlainObject, execaMethod) => {782 const transform = generatorsMap[type].uppercase();783 const {stdout} = await execaMethod('noop-fd.js', ['1', foobarString], {stdout: usePlainObject ? transform : transform.transform});784 t.is(stdout, foobarUppercase);785};786787test('Can pass generators with an options plain object', testGeneratorSyntax, 'generator', false, execa);788test('Can pass generators without an options plain object', testGeneratorSyntax, 'generator', true, execa);789test('Can pass generators with an options plain object, sync', testGeneratorSyntax, 'generator', false, execaSync);790test('Can pass generators without an options plain object, sync', testGeneratorSyntax, 'generator', true, execaSync);791test('Can pass webTransforms with an options plain object', testGeneratorSyntax, 'webTransform', true, execa);792test('Can pass webTransforms without an options plain object', testGeneratorSyntax, 'webTransform', false, execa);
added:test/stdio/handle-invalid.js+60 added
1import test from 'ava';2import {execa, execaSync} from '../../index.js';3import {getStdio} from '../helpers/stdio.js';4import {setFixtureDir} from '../helpers/fixtures-dir.js';56setFixtureDir();78const testEmptyArray = (t, fdNumber, optionName, execaMethod) => {9 t.throws(() => {10 execaMethod('empty.js', getStdio(fdNumber, []));11 }, {message: `The \`${optionName}\` option must not be an empty array.`});12};1314test('Cannot pass an empty array to stdin', testEmptyArray, 0, 'stdin', execa);15test('Cannot pass an empty array to stdout', testEmptyArray, 1, 'stdout', execa);16test('Cannot pass an empty array to stderr', testEmptyArray, 2, 'stderr', execa);17test('Cannot pass an empty array to stdio[*]', testEmptyArray, 3, 'stdio[3]', execa);18test('Cannot pass an empty array to stdin - sync', testEmptyArray, 0, 'stdin', execaSync);19test('Cannot pass an empty array to stdout - sync', testEmptyArray, 1, 'stdout', execaSync);20test('Cannot pass an empty array to stderr - sync', testEmptyArray, 2, 'stderr', execaSync);21test('Cannot pass an empty array to stdio[*] - sync', testEmptyArray, 3, 'stdio[3]', execaSync);2223const testInvalidValueSync = (t, fdNumber, stdioOption) => {24 const {message} = t.throws(() => {25 execaSync('empty.js', getStdio(fdNumber, stdioOption));26 });27 t.true(message.includes(`cannot be "${stdioOption}" with synchronous methods`));28};2930test('stdin cannot be "ipc", sync', testInvalidValueSync, 0, 'ipc');31test('stdout cannot be "ipc", sync', testInvalidValueSync, 1, 'ipc');32test('stderr cannot be "ipc", sync', testInvalidValueSync, 2, 'ipc');33test('stdio[*] cannot be "ipc", sync', testInvalidValueSync, 3, 'ipc');34test('stdin cannot be "overlapped", sync', testInvalidValueSync, 0, 'overlapped');35test('stdout cannot be "overlapped", sync', testInvalidValueSync, 1, 'overlapped');36test('stderr cannot be "overlapped", sync', testInvalidValueSync, 2, 'overlapped');37test('stdio[*] cannot be "overlapped", sync', testInvalidValueSync, 3, 'overlapped');3839const testInvalidArrayValue = (t, invalidStdio, fdNumber, execaMethod) => {40 t.throws(() => {41 execaMethod('empty.js', getStdio(fdNumber, ['pipe', invalidStdio]));42 }, {message: /must not include/});43};4445test('Cannot pass "ignore" and another value to stdin', testInvalidArrayValue, 'ignore', 0, execa);46test('Cannot pass "ignore" and another value to stdout', testInvalidArrayValue, 'ignore', 1, execa);47test('Cannot pass "ignore" and another value to stderr', testInvalidArrayValue, 'ignore', 2, execa);48test('Cannot pass "ignore" and another value to stdio[*]', testInvalidArrayValue, 'ignore', 3, execa);49test('Cannot pass "ignore" and another value to stdin - sync', testInvalidArrayValue, 'ignore', 0, execaSync);50test('Cannot pass "ignore" and another value to stdout - sync', testInvalidArrayValue, 'ignore', 1, execaSync);51test('Cannot pass "ignore" and another value to stderr - sync', testInvalidArrayValue, 'ignore', 2, execaSync);52test('Cannot pass "ignore" and another value to stdio[*] - sync', testInvalidArrayValue, 'ignore', 3, execaSync);53test('Cannot pass "ipc" and another value to stdin', testInvalidArrayValue, 'ipc', 0, execa);54test('Cannot pass "ipc" and another value to stdout', testInvalidArrayValue, 'ipc', 1, execa);55test('Cannot pass "ipc" and another value to stderr', testInvalidArrayValue, 'ipc', 2, execa);56test('Cannot pass "ipc" and another value to stdio[*]', testInvalidArrayValue, 'ipc', 3, execa);57test('Cannot pass "ipc" and another value to stdin - sync', testInvalidArrayValue, 'ipc', 0, execaSync);58test('Cannot pass "ipc" and another value to stdout - sync', testInvalidArrayValue, 'ipc', 1, execaSync);59test('Cannot pass "ipc" and another value to stderr - sync', testInvalidArrayValue, 'ipc', 2, execaSync);60test('Cannot pass "ipc" and another value to stdio[*] - sync', testInvalidArrayValue, 'ipc', 3, execaSync);
added:test/stdio/handle-options.js+72 added
1import test from 'ava';2import {execa, execaSync} from '../../index.js';3import {getStdio} from '../helpers/stdio.js';4import {setFixtureDir} from '../helpers/fixtures-dir.js';5import {appendGenerator, appendAsyncGenerator, casedSuffix} from '../helpers/generator.js';6import {appendDuplex} from '../helpers/duplex.js';7import {appendWebTransform} from '../helpers/web-transform.js';8import {foobarString} from '../helpers/input.js';910setFixtureDir();1112const testNoPipeOption = async (t, stdioOption, fdNumber) => {13 const subprocess = execa('empty.js', getStdio(fdNumber, stdioOption));14 t.is(subprocess.stdio[fdNumber], null);15 await subprocess;16};1718test('stdin can be "ignore"', testNoPipeOption, 'ignore', 0);19test('stdin can be ["ignore"]', testNoPipeOption, ['ignore'], 0);20test('stdin can be ["ignore", "ignore"]', testNoPipeOption, ['ignore', 'ignore'], 0);21test('stdin can be "ipc"', testNoPipeOption, 'ipc', 0);22test('stdin can be ["ipc"]', testNoPipeOption, ['ipc'], 0);23test('stdin can be "inherit"', testNoPipeOption, 'inherit', 0);24test('stdin can be ["inherit"]', testNoPipeOption, ['inherit'], 0);25test('stdin can be 0', testNoPipeOption, 0, 0);26test('stdin can be [0]', testNoPipeOption, [0], 0);27test('stdout can be "ignore"', testNoPipeOption, 'ignore', 1);28test('stdout can be ["ignore"]', testNoPipeOption, ['ignore'], 1);29test('stdout can be ["ignore", "ignore"]', testNoPipeOption, ['ignore', 'ignore'], 1);30test('stdout can be "ipc"', testNoPipeOption, 'ipc', 1);31test('stdout can be ["ipc"]', testNoPipeOption, ['ipc'], 1);32test('stdout can be "inherit"', testNoPipeOption, 'inherit', 1);33test('stdout can be ["inherit"]', testNoPipeOption, ['inherit'], 1);34test('stdout can be 1', testNoPipeOption, 1, 1);35test('stdout can be [1]', testNoPipeOption, [1], 1);36test('stderr can be "ignore"', testNoPipeOption, 'ignore', 2);37test('stderr can be ["ignore"]', testNoPipeOption, ['ignore'], 2);38test('stderr can be ["ignore", "ignore"]', testNoPipeOption, ['ignore', 'ignore'], 2);39test('stderr can be "ipc"', testNoPipeOption, 'ipc', 2);40test('stderr can be ["ipc"]', testNoPipeOption, ['ipc'], 2);41test('stderr can be "inherit"', testNoPipeOption, 'inherit', 2);42test('stderr can be ["inherit"]', testNoPipeOption, ['inherit'], 2);43test('stderr can be 2', testNoPipeOption, 2, 2);44test('stderr can be [2]', testNoPipeOption, [2], 2);45test('stdio[*] can be "ignore"', testNoPipeOption, 'ignore', 3);46test('stdio[*] can be ["ignore"]', testNoPipeOption, ['ignore'], 3);47test('stdio[*] can be ["ignore", "ignore"]', testNoPipeOption, ['ignore', 'ignore'], 3);48test('stdio[*] can be "ipc"', testNoPipeOption, 'ipc', 3);49test('stdio[*] can be ["ipc"]', testNoPipeOption, ['ipc'], 3);50test('stdio[*] can be "inherit"', testNoPipeOption, 'inherit', 3);51test('stdio[*] can be ["inherit"]', testNoPipeOption, ['inherit'], 3);52test('stdio[*] can be 3', testNoPipeOption, 3, 3);53test('stdio[*] can be [3]', testNoPipeOption, [3], 3);5455// eslint-disable-next-line max-params56const testTwoGenerators = async (t, producesTwo, execaMethod, firstGenerator, secondGenerator = firstGenerator) => {57 const {stdout} = await execaMethod('noop-fd.js', ['1', foobarString], {stdout: [firstGenerator, secondGenerator]});58 const expectedSuffix = producesTwo ? `${casedSuffix}${casedSuffix}` : casedSuffix;59 t.is(stdout, `${foobarString}${expectedSuffix}`);60};6162test('Can use multiple identical generators', testTwoGenerators, true, execa, appendGenerator().transform);63test('Can use multiple identical generators, options object', testTwoGenerators, true, execa, appendGenerator());64test('Can use multiple identical generators, async', testTwoGenerators, true, execa, appendAsyncGenerator().transform);65test('Can use multiple identical generators, options object, async', testTwoGenerators, true, execa, appendAsyncGenerator());66test('Can use multiple identical generators, sync', testTwoGenerators, true, execaSync, appendGenerator().transform);67test('Can use multiple identical generators, options object, sync', testTwoGenerators, true, execaSync, appendGenerator());68test('Ignore duplicate identical duplexes', testTwoGenerators, false, execa, appendDuplex());69test('Ignore duplicate identical webTransforms', testTwoGenerators, false, execa, appendWebTransform());70test('Can use multiple generators with duplexes', testTwoGenerators, true, execa, appendGenerator(false, false, true), appendDuplex());71test('Can use multiple generators with webTransforms', testTwoGenerators, true, execa, appendGenerator(false, false, true), appendWebTransform());72test('Can use multiple duplexes with webTransforms', testTwoGenerators, true, execa, appendDuplex(), appendWebTransform());
deleted:test/stdio/handle.js-103 removed
1import test from 'ava';2import {execa, execaSync} from '../../index.js';3import {getStdio} from '../helpers/stdio.js';4import {setFixtureDir} from '../helpers/fixtures-dir.js';56setFixtureDir();78const testEmptyArray = (t, fdNumber, optionName, execaMethod) => {9 t.throws(() => {10 execaMethod('empty.js', getStdio(fdNumber, []));11 }, {message: `The \`${optionName}\` option must not be an empty array.`});12};1314test('Cannot pass an empty array to stdin', testEmptyArray, 0, 'stdin', execa);15test('Cannot pass an empty array to stdout', testEmptyArray, 1, 'stdout', execa);16test('Cannot pass an empty array to stderr', testEmptyArray, 2, 'stderr', execa);17test('Cannot pass an empty array to stdio[*]', testEmptyArray, 3, 'stdio[3]', execa);18test('Cannot pass an empty array to stdin - sync', testEmptyArray, 0, 'stdin', execaSync);19test('Cannot pass an empty array to stdout - sync', testEmptyArray, 1, 'stdout', execaSync);20test('Cannot pass an empty array to stderr - sync', testEmptyArray, 2, 'stderr', execaSync);21test('Cannot pass an empty array to stdio[*] - sync', testEmptyArray, 3, 'stdio[3]', execaSync);2223const testNoPipeOption = async (t, stdioOption, fdNumber) => {24 const subprocess = execa('empty.js', getStdio(fdNumber, stdioOption));25 t.is(subprocess.stdio[fdNumber], null);26 await subprocess;27};2829test('stdin can be "ignore"', testNoPipeOption, 'ignore', 0);30test('stdin can be ["ignore"]', testNoPipeOption, ['ignore'], 0);31test('stdin can be ["ignore", "ignore"]', testNoPipeOption, ['ignore', 'ignore'], 0);32test('stdin can be "ipc"', testNoPipeOption, 'ipc', 0);33test('stdin can be ["ipc"]', testNoPipeOption, ['ipc'], 0);34test('stdin can be "inherit"', testNoPipeOption, 'inherit', 0);35test('stdin can be ["inherit"]', testNoPipeOption, ['inherit'], 0);36test('stdin can be 0', testNoPipeOption, 0, 0);37test('stdin can be [0]', testNoPipeOption, [0], 0);38test('stdout can be "ignore"', testNoPipeOption, 'ignore', 1);39test('stdout can be ["ignore"]', testNoPipeOption, ['ignore'], 1);40test('stdout can be ["ignore", "ignore"]', testNoPipeOption, ['ignore', 'ignore'], 1);41test('stdout can be "ipc"', testNoPipeOption, 'ipc', 1);42test('stdout can be ["ipc"]', testNoPipeOption, ['ipc'], 1);43test('stdout can be "inherit"', testNoPipeOption, 'inherit', 1);44test('stdout can be ["inherit"]', testNoPipeOption, ['inherit'], 1);45test('stdout can be 1', testNoPipeOption, 1, 1);46test('stdout can be [1]', testNoPipeOption, [1], 1);47test('stderr can be "ignore"', testNoPipeOption, 'ignore', 2);48test('stderr can be ["ignore"]', testNoPipeOption, ['ignore'], 2);49test('stderr can be ["ignore", "ignore"]', testNoPipeOption, ['ignore', 'ignore'], 2);50test('stderr can be "ipc"', testNoPipeOption, 'ipc', 2);51test('stderr can be ["ipc"]', testNoPipeOption, ['ipc'], 2);52test('stderr can be "inherit"', testNoPipeOption, 'inherit', 2);53test('stderr can be ["inherit"]', testNoPipeOption, ['inherit'], 2);54test('stderr can be 2', testNoPipeOption, 2, 2);55test('stderr can be [2]', testNoPipeOption, [2], 2);56test('stdio[*] can be "ignore"', testNoPipeOption, 'ignore', 3);57test('stdio[*] can be ["ignore"]', testNoPipeOption, ['ignore'], 3);58test('stdio[*] can be ["ignore", "ignore"]', testNoPipeOption, ['ignore', 'ignore'], 3);59test('stdio[*] can be "ipc"', testNoPipeOption, 'ipc', 3);60test('stdio[*] can be ["ipc"]', testNoPipeOption, ['ipc'], 3);61test('stdio[*] can be "inherit"', testNoPipeOption, 'inherit', 3);62test('stdio[*] can be ["inherit"]', testNoPipeOption, ['inherit'], 3);63test('stdio[*] can be 3', testNoPipeOption, 3, 3);64test('stdio[*] can be [3]', testNoPipeOption, [3], 3);6566const testInvalidValueSync = (t, fdNumber, stdioOption) => {67 const {message} = t.throws(() => {68 execaSync('empty.js', getStdio(fdNumber, stdioOption));69 });70 t.true(message.includes(`cannot be "${stdioOption}" with synchronous methods`));71};7273test('stdin cannot be "ipc", sync', testInvalidValueSync, 0, 'ipc');74test('stdout cannot be "ipc", sync', testInvalidValueSync, 1, 'ipc');75test('stderr cannot be "ipc", sync', testInvalidValueSync, 2, 'ipc');76test('stdio[*] cannot be "ipc", sync', testInvalidValueSync, 3, 'ipc');77test('stdin cannot be "overlapped", sync', testInvalidValueSync, 0, 'overlapped');78test('stdout cannot be "overlapped", sync', testInvalidValueSync, 1, 'overlapped');79test('stderr cannot be "overlapped", sync', testInvalidValueSync, 2, 'overlapped');80test('stdio[*] cannot be "overlapped", sync', testInvalidValueSync, 3, 'overlapped');8182const testInvalidArrayValue = (t, invalidStdio, fdNumber, execaMethod) => {83 t.throws(() => {84 execaMethod('empty.js', getStdio(fdNumber, ['pipe', invalidStdio]));85 }, {message: /must not include/});86};8788test('Cannot pass "ignore" and another value to stdin', testInvalidArrayValue, 'ignore', 0, execa);89test('Cannot pass "ignore" and another value to stdout', testInvalidArrayValue, 'ignore', 1, execa);90test('Cannot pass "ignore" and another value to stderr', testInvalidArrayValue, 'ignore', 2, execa);91test('Cannot pass "ignore" and another value to stdio[*]', testInvalidArrayValue, 'ignore', 3, execa);92test('Cannot pass "ignore" and another value to stdin - sync', testInvalidArrayValue, 'ignore', 0, execaSync);93test('Cannot pass "ignore" and another value to stdout - sync', testInvalidArrayValue, 'ignore', 1, execaSync);94test('Cannot pass "ignore" and another value to stderr - sync', testInvalidArrayValue, 'ignore', 2, execaSync);95test('Cannot pass "ignore" and another value to stdio[*] - sync', testInvalidArrayValue, 'ignore', 3, execaSync);96test('Cannot pass "ipc" and another value to stdin', testInvalidArrayValue, 'ipc', 0, execa);97test('Cannot pass "ipc" and another value to stdout', testInvalidArrayValue, 'ipc', 1, execa);98test('Cannot pass "ipc" and another value to stderr', testInvalidArrayValue, 'ipc', 2, execa);99test('Cannot pass "ipc" and another value to stdio[*]', testInvalidArrayValue, 'ipc', 3, execa);100test('Cannot pass "ipc" and another value to stdin - sync', testInvalidArrayValue, 'ipc', 0, execaSync);101test('Cannot pass "ipc" and another value to stdout - sync', testInvalidArrayValue, 'ipc', 1, execaSync);102test('Cannot pass "ipc" and another value to stderr - sync', testInvalidArrayValue, 'ipc', 2, execaSync);103test('Cannot pass "ipc" and another value to stdio[*] - sync', testInvalidArrayValue, 'ipc', 3, execaSync);
added:test/stdio/lines-main.js+108 added
1import test from 'ava';2import {execa, execaSync} from '../../index.js';3import {setFixtureDir} from '../helpers/fixtures-dir.js';4import {fullStdio} from '../helpers/stdio.js';5import {getOutputsGenerator} from '../helpers/generator.js';6import {foobarString} from '../helpers/input.js';7import {8 simpleFull,9 simpleChunks,10 simpleFullEndChunks,11 simpleLines,12 simpleFullEndLines,13 noNewlinesChunks,14 getSimpleChunkSubprocessAsync,15} from '../helpers/lines.js';1617setFixtureDir();1819// eslint-disable-next-line max-params20const testStreamLines = async (t, fdNumber, input, expectedOutput, lines, stripFinalNewline, execaMethod) => {21 const {stdio} = await execaMethod('noop-fd.js', [`${fdNumber}`, input], {...fullStdio, lines, stripFinalNewline});22 t.deepEqual(stdio[fdNumber], expectedOutput);23};2425test('"lines: true" splits lines, stdout', testStreamLines, 1, simpleFull, simpleLines, true, false, execa);26test('"lines: true" splits lines, stdout, fd-specific', testStreamLines, 1, simpleFull, simpleLines, {stdout: true}, false, execa);27test('"lines: true" splits lines, stderr', testStreamLines, 2, simpleFull, simpleLines, true, false, execa);28test('"lines: true" splits lines, stderr, fd-specific', testStreamLines, 2, simpleFull, simpleLines, {stderr: true}, false, execa);29test('"lines: true" splits lines, stdio[*]', testStreamLines, 3, simpleFull, simpleLines, true, false, execa);30test('"lines: true" splits lines, stdio[*], fd-specific', testStreamLines, 3, simpleFull, simpleLines, {fd3: true}, false, execa);31test('"lines: true" splits lines, stdout, stripFinalNewline', testStreamLines, 1, simpleFull, noNewlinesChunks, true, true, execa);32test('"lines: true" splits lines, stdout, stripFinalNewline, fd-specific', testStreamLines, 1, simpleFull, noNewlinesChunks, true, {stdout: true}, execa);33test('"lines: true" splits lines, stderr, stripFinalNewline', testStreamLines, 2, simpleFull, noNewlinesChunks, true, true, execa);34test('"lines: true" splits lines, stderr, stripFinalNewline, fd-specific', testStreamLines, 2, simpleFull, noNewlinesChunks, true, {stderr: true}, execa);35test('"lines: true" splits lines, stdio[*], stripFinalNewline', testStreamLines, 3, simpleFull, noNewlinesChunks, true, true, execa);36test('"lines: true" splits lines, stdio[*], stripFinalNewline, fd-specific', testStreamLines, 3, simpleFull, noNewlinesChunks, true, {fd3: true}, execa);37test('"lines: true" splits lines, stdout, sync', testStreamLines, 1, simpleFull, simpleLines, true, false, execaSync);38test('"lines: true" splits lines, stdout, fd-specific, sync', testStreamLines, 1, simpleFull, simpleLines, {stdout: true}, false, execaSync);39test('"lines: true" splits lines, stderr, sync', testStreamLines, 2, simpleFull, simpleLines, true, false, execaSync);40test('"lines: true" splits lines, stderr, fd-specific, sync', testStreamLines, 2, simpleFull, simpleLines, {stderr: true}, false, execaSync);41test('"lines: true" splits lines, stdio[*], sync', testStreamLines, 3, simpleFull, simpleLines, true, false, execaSync);42test('"lines: true" splits lines, stdio[*], fd-specific, sync', testStreamLines, 3, simpleFull, simpleLines, {fd3: true}, false, execaSync);43test('"lines: true" splits lines, stdout, stripFinalNewline, sync', testStreamLines, 1, simpleFull, noNewlinesChunks, true, true, execaSync);44test('"lines: true" splits lines, stdout, stripFinalNewline, fd-specific, sync', testStreamLines, 1, simpleFull, noNewlinesChunks, true, {stdout: true}, execaSync);45test('"lines: true" splits lines, stderr, stripFinalNewline, sync', testStreamLines, 2, simpleFull, noNewlinesChunks, true, true, execaSync);46test('"lines: true" splits lines, stderr, stripFinalNewline, fd-specific, sync', testStreamLines, 2, simpleFull, noNewlinesChunks, true, {stderr: true}, execaSync);47test('"lines: true" splits lines, stdio[*], stripFinalNewline, sync', testStreamLines, 3, simpleFull, noNewlinesChunks, true, true, execaSync);48test('"lines: true" splits lines, stdio[*], stripFinalNewline, fd-specific, sync', testStreamLines, 3, simpleFull, noNewlinesChunks, true, {fd3: true}, execaSync);4950const bigArray = Array.from({length: 1e5}).fill('.\n');51const bigString = bigArray.join('');52const bigStringNoNewlines = '.'.repeat(1e6);53const bigStringNoNewlinesEnd = `${bigStringNoNewlines}\n`;5455// eslint-disable-next-line max-params56const testStreamLinesGenerator = async (t, input, expectedLines, objectMode, binary, stripFinalNewline, execaMethod) => {57 const {stdout} = await execaMethod('noop.js', {58 stdout: getOutputsGenerator(input)(objectMode, binary),59 lines: true,60 stripFinalNewline,61 });62 t.deepEqual(stdout, expectedLines);63};6465test('"lines: true" works with strings generators', testStreamLinesGenerator, simpleChunks, simpleFullEndLines, false, false, false, execa);66test('"lines: true" works with strings generators, binary', testStreamLinesGenerator, simpleChunks, simpleLines, false, true, false, execa);67test('"lines: true" works with big strings generators', testStreamLinesGenerator, [bigString], bigArray, false, false, false, execa);68test('"lines: true" works with big strings generators without newlines', testStreamLinesGenerator, [bigStringNoNewlines], [bigStringNoNewlinesEnd], false, false, false, execa);69test('"lines: true" is a noop with strings generators, objectMode', testStreamLinesGenerator, simpleFullEndChunks, simpleFullEndChunks, true, false, false, execa);70test('"lines: true" is a noop with strings generators, stripFinalNewline, objectMode', testStreamLinesGenerator, simpleFullEndChunks, simpleFullEndChunks, true, false, true, execa);71test('"lines: true" is a noop with strings generators, stripFinalNewline, fd-specific, objectMode', testStreamLinesGenerator, simpleFullEndChunks, simpleFullEndChunks, true, false, {stdout: true}, execa);72test('"lines: true" is a noop with strings generators, binary, objectMode', testStreamLinesGenerator, simpleChunks, simpleChunks, true, true, false, execa);73test('"lines: true" is a noop big strings generators, objectMode', testStreamLinesGenerator, [bigString], [bigString], true, false, false, execa);74test('"lines: true" is a noop big strings generators without newlines, objectMode', testStreamLinesGenerator, [bigStringNoNewlines], [bigStringNoNewlines], true, false, false, execa);75test('"lines: true" works with strings generators, sync', testStreamLinesGenerator, simpleChunks, simpleFullEndLines, false, false, false, execaSync);76test('"lines: true" works with strings generators, binary, sync', testStreamLinesGenerator, simpleChunks, simpleLines, false, true, false, execaSync);77test('"lines: true" works with big strings generators, sync', testStreamLinesGenerator, [bigString], bigArray, false, false, false, execaSync);78test('"lines: true" works with big strings generators without newlines, sync', testStreamLinesGenerator, [bigStringNoNewlines], [bigStringNoNewlinesEnd], false, false, false, execaSync);79test('"lines: true" is a noop with strings generators, objectMode, sync', testStreamLinesGenerator, simpleFullEndChunks, simpleFullEndChunks, true, false, false, execaSync);80test('"lines: true" is a noop with strings generators, stripFinalNewline, objectMode, sync', testStreamLinesGenerator, simpleFullEndChunks, simpleFullEndChunks, true, false, true, execaSync);81test('"lines: true" is a noop with strings generators, stripFinalNewline, fd-specific, objectMode, sync', testStreamLinesGenerator, simpleFullEndChunks, simpleFullEndChunks, true, false, {stdout: true}, execaSync);82test('"lines: true" is a noop with strings generators, binary, objectMode, sync', testStreamLinesGenerator, simpleChunks, simpleChunks, true, true, false, execaSync);83test('"lines: true" is a noop big strings generators, objectMode, sync', testStreamLinesGenerator, [bigString], [bigString], true, false, false, execaSync);84test('"lines: true" is a noop big strings generators without newlines, objectMode, sync', testStreamLinesGenerator, [bigStringNoNewlines], [bigStringNoNewlines], true, false, false, execaSync);8586test('"lines: true" stops on stream error', async t => {87 const cause = new Error(foobarString);88 const error = await t.throwsAsync(getSimpleChunkSubprocessAsync({89 * stdout(line) {90 if (line === noNewlinesChunks[2]) {91 throw cause;92 }9394 yield line;95 },96 }));97 t.is(error.cause, cause);98 t.deepEqual(error.stdout, noNewlinesChunks.slice(0, 2));99});100101test('"lines: true" stops on stream error event', async t => {102 const cause = new Error(foobarString);103 const subprocess = getSimpleChunkSubprocessAsync();104 subprocess.stdout.emit('error', cause);105 const error = await t.throwsAsync(subprocess);106 t.is(error.cause, cause);107 t.deepEqual(error.stdout, []);108});
added:test/stdio/lines-max-buffer.js+50 added
1import test from 'ava';2import {execa, execaSync} from '../../index.js';3import {setFixtureDir} from '../helpers/fixtures-dir.js';4import {simpleLines, noNewlinesChunks, getSimpleChunkSubprocessAsync} from '../helpers/lines.js';5import {assertErrorMessage} from '../helpers/max-buffer.js';67setFixtureDir();89const maxBuffer = simpleLines.length - 1;1011const testBelowMaxBuffer = async (t, lines) => {12 const {isMaxBuffer, stdout} = await getSimpleChunkSubprocessAsync({lines, maxBuffer: maxBuffer + 1});13 t.false(isMaxBuffer);14 t.deepEqual(stdout, noNewlinesChunks);15};1617test('"lines: true" can be below "maxBuffer"', testBelowMaxBuffer, true);18test('"lines: true" can be below "maxBuffer", fd-specific', testBelowMaxBuffer, {stdout: true});1920const 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));25};2627test('"lines: true" can be above "maxBuffer"', testAboveMaxBuffer, true);28test('"lines: true" can be above "maxBuffer", fd-specific', testAboveMaxBuffer, {stdout: true});2930const 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, ['...', '...']);35};3637test('"maxBuffer" is measured in lines with "lines: true"', testMaxBufferUnit, true);38test('"maxBuffer" is measured in lines with "lines: true", fd-specific', testMaxBufferUnit, {stdout: true});3940const testMaxBufferUnitSync = (t, lines) => {41 const {isMaxBuffer, shortMessage, stdout} = t.throws(() => {42 execaSync('noop-repeat.js', ['1', '...\n'], {lines, maxBuffer});43 }, {code: 'ENOBUFS'});44 t.true(isMaxBuffer);45 assertErrorMessage(t, shortMessage, {execaMethod: execaSync, length: maxBuffer});46 t.deepEqual(stdout, ['..']);47};4849test('"maxBuffer" is measured in bytes with "lines: true", sync', testMaxBufferUnitSync, true);50test('"maxBuffer" is measured in bytes with "lines: true", fd-specific, sync', testMaxBufferUnitSync, {stdout: true});
added:test/stdio/lines-mixed.js+55 added
1import {Writable} from 'node:stream';2import test from 'ava';3import {setFixtureDir} from '../helpers/fixtures-dir.js';4import {assertStreamOutput, assertStreamDataEvents, assertIterableChunks} from '../helpers/convert.js';5import {simpleFull, simpleLines, noNewlinesChunks, getSimpleChunkSubprocessAsync} from '../helpers/lines.js';67setFixtureDir();89const testAsyncIteration = async (t, expectedLines, stripFinalNewline) => {10 const subprocess = getSimpleChunkSubprocessAsync({stripFinalNewline});11 t.false(subprocess.stdout.readableObjectMode);12 await assertStreamOutput(t, subprocess.stdout, simpleFull);13 const {stdout} = await subprocess;14 t.deepEqual(stdout, expectedLines);15};1617test('"lines: true" works with stream async iteration', testAsyncIteration, simpleLines, false);18test('"lines: true" works with stream async iteration, stripFinalNewline', testAsyncIteration, noNewlinesChunks, true);1920const testDataEvents = async (t, expectedLines, stripFinalNewline) => {21 const subprocess = getSimpleChunkSubprocessAsync({stripFinalNewline});22 await assertStreamDataEvents(t, subprocess.stdout, simpleFull);23 const {stdout} = await subprocess;24 t.deepEqual(stdout, expectedLines);25};2627test('"lines: true" works with stream "data" events', testDataEvents, simpleLines, false);28test('"lines: true" works with stream "data" events, stripFinalNewline', testDataEvents, noNewlinesChunks, true);2930const testWritableStream = async (t, expectedLines, stripFinalNewline) => {31 let output = '';32 const writable = new Writable({33 write(line, encoding, done) {34 output += line.toString();35 done();36 },37 decodeStrings: false,38 });39 const {stdout} = await getSimpleChunkSubprocessAsync({stripFinalNewline, stdout: ['pipe', writable]});40 t.deepEqual(output, simpleFull);41 t.deepEqual(stdout, expectedLines);42};4344test('"lines: true" works with writable streams targets', testWritableStream, simpleLines, false);45test('"lines: true" works with writable streams targets, stripFinalNewline', testWritableStream, noNewlinesChunks, true);4647const testIterable = async (t, expectedLines, stripFinalNewline) => {48 const subprocess = getSimpleChunkSubprocessAsync({stripFinalNewline});49 await assertIterableChunks(t, subprocess, noNewlinesChunks);50 const {stdout} = await subprocess;51 t.deepEqual(stdout, expectedLines);52};5354test('"lines: true" works with subprocess.iterable()', testIterable, simpleLines, false);55test('"lines: true" works with subprocess.iterable(), stripFinalNewline', testIterable, noNewlinesChunks, true);
added:test/stdio/lines-noop.js+84 added
1import test from 'ava';2import {execa, execaSync} from '../../index.js';3import {setFixtureDir} from '../helpers/fixtures-dir.js';4import {getOutputsGenerator} from '../helpers/generator.js';5import {foobarObject} from '../helpers/input.js';6import {7 simpleFull,8 simpleFullUint8Array,9 simpleFullHex,10 simpleFullUtf16Uint8Array,11 simpleLines,12 noNewlinesChunks,13 getSimpleChunkSubprocess,14} from '../helpers/lines.js';1516setFixtureDir();1718const testStreamLinesNoop = async (t, lines, execaMethod) => {19 const {stdout} = await execaMethod('noop-fd.js', ['1', simpleFull], {lines});20 t.is(stdout, simpleFull);21};2223test('"lines: false" is a noop', testStreamLinesNoop, false, execa);24test('"lines: false" is a noop, fd-specific', testStreamLinesNoop, {stderr: true}, execa);25test('"lines: false" is a noop, fd-specific none', testStreamLinesNoop, {}, execa);26test('"lines: false" is a noop, sync', testStreamLinesNoop, false, execaSync);27test('"lines: false" is a noop, fd-specific, sync', testStreamLinesNoop, {stderr: true}, execaSync);28test('"lines: false" is a noop, fd-specific none, sync', testStreamLinesNoop, {}, execaSync);2930const testLinesObjectMode = async (t, lines, execaMethod) => {31 const {stdout} = await execaMethod('noop.js', {32 stdout: getOutputsGenerator([foobarObject])(true),33 lines,34 });35 t.deepEqual(stdout, [foobarObject]);36};3738test('"lines: true" is a noop with objects generators, objectMode', testLinesObjectMode, true, execa);39test('"lines: true" is a noop with objects generators, fd-specific, objectMode', testLinesObjectMode, {stdout: true}, execa);40test('"lines: true" is a noop with objects generators, objectMode, sync', testLinesObjectMode, true, execaSync);41test('"lines: true" is a noop with objects generators, fd-specific, objectMode, sync', testLinesObjectMode, {stdout: true}, execaSync);4243// eslint-disable-next-line max-params44const testEncoding = async (t, input, expectedOutput, encoding, lines, stripFinalNewline, execaMethod) => {45 const {stdout} = await execaMethod('stdin.js', {lines, stripFinalNewline, encoding, input});46 t.deepEqual(stdout, expectedOutput);47};4849test('"lines: true" is a noop with "encoding: utf16"', testEncoding, simpleFullUtf16Uint8Array, simpleLines, 'utf16le', true, false, execa);50test('"lines: true" is a noop with "encoding: utf16", fd-specific', testEncoding, simpleFullUtf16Uint8Array, simpleLines, 'utf16le', {stdout: true}, false, execa);51test('"lines: true" is a noop with "encoding: utf16", stripFinalNewline', testEncoding, simpleFullUtf16Uint8Array, noNewlinesChunks, 'utf16le', true, true, execa);52test('"lines: true" is a noop with "encoding: utf16", stripFinalNewline, fd-specific', testEncoding, simpleFullUtf16Uint8Array, noNewlinesChunks, 'utf16le', true, {stdout: true}, execa);53test('"lines: true" is a noop with "encoding: buffer"', testEncoding, simpleFull, simpleFullUint8Array, 'buffer', true, false, execa);54test('"lines: true" is a noop with "encoding: buffer", fd-specific', testEncoding, simpleFull, simpleFullUint8Array, 'buffer', {stdout: true}, false, execa);55test('"lines: true" is a noop with "encoding: buffer", stripFinalNewline', testEncoding, simpleFull, simpleFullUint8Array, 'buffer', true, false, execa);56test('"lines: true" is a noop with "encoding: buffer", stripFinalNewline, fd-specific', testEncoding, simpleFull, simpleFullUint8Array, 'buffer', true, {stdout: false}, execa);57test('"lines: true" is a noop with "encoding: hex"', testEncoding, simpleFull, simpleFullHex, 'hex', true, false, execa);58test('"lines: true" is a noop with "encoding: hex", fd-specific', testEncoding, simpleFull, simpleFullHex, 'hex', {stdout: true}, false, execa);59test('"lines: true" is a noop with "encoding: hex", stripFinalNewline', testEncoding, simpleFull, simpleFullHex, 'hex', true, true, execa);60test('"lines: true" is a noop with "encoding: hex", stripFinalNewline, fd-specific', testEncoding, simpleFull, simpleFullHex, 'hex', true, {stdout: true}, execa);61test('"lines: true" is a noop with "encoding: utf16", sync', testEncoding, simpleFullUtf16Uint8Array, simpleLines, 'utf16le', true, false, execaSync);62test('"lines: true" is a noop with "encoding: utf16", fd-specific, sync', testEncoding, simpleFullUtf16Uint8Array, simpleLines, 'utf16le', {stdout: true}, false, execaSync);63test('"lines: true" is a noop with "encoding: utf16", stripFinalNewline, sync', testEncoding, simpleFullUtf16Uint8Array, noNewlinesChunks, 'utf16le', true, true, execaSync);64test('"lines: true" is a noop with "encoding: utf16", stripFinalNewline, fd-specific, sync', testEncoding, simpleFullUtf16Uint8Array, noNewlinesChunks, 'utf16le', true, {stdout: true}, execaSync);65test('"lines: true" is a noop with "encoding: buffer", sync', testEncoding, simpleFull, simpleFullUint8Array, 'buffer', true, false, execaSync);66test('"lines: true" is a noop with "encoding: buffer", fd-specific, sync', testEncoding, simpleFull, simpleFullUint8Array, 'buffer', {stdout: true}, false, execaSync);67test('"lines: true" is a noop with "encoding: buffer", stripFinalNewline, sync', testEncoding, simpleFull, simpleFullUint8Array, 'buffer', true, false, execaSync);68test('"lines: true" is a noop with "encoding: buffer", stripFinalNewline, fd-specific, sync', testEncoding, simpleFull, simpleFullUint8Array, 'buffer', true, {stdout: false}, execaSync);69test('"lines: true" is a noop with "encoding: hex", sync', testEncoding, simpleFull, simpleFullHex, 'hex', true, false, execaSync);70test('"lines: true" is a noop with "encoding: hex", fd-specific, sync', testEncoding, simpleFull, simpleFullHex, 'hex', {stdout: true}, false, execaSync);71test('"lines: true" is a noop with "encoding: hex", stripFinalNewline, sync', testEncoding, simpleFull, simpleFullHex, 'hex', true, true, execaSync);72test('"lines: true" is a noop with "encoding: hex", stripFinalNewline, fd-specific, sync', testEncoding, simpleFull, simpleFullHex, 'hex', true, {stdout: true}, execaSync);7374const testLinesNoBuffer = async (t, lines, buffer, execaMethod) => {75 const {stdout} = await getSimpleChunkSubprocess(execaMethod, {lines, buffer});76 t.is(stdout, undefined);77};7879test('"lines: true" is a noop with "buffer: false"', testLinesNoBuffer, true, false, execa);80test('"lines: true" is a noop with "buffer: false", fd-specific buffer', testLinesNoBuffer, true, {stdout: false}, execa);81test('"lines: true" is a noop with "buffer: false", fd-specific lines', testLinesNoBuffer, {stdout: true}, false, execa);82test('"lines: true" is a noop with "buffer: false", sync', testLinesNoBuffer, true, false, execaSync);83test('"lines: true" is a noop with "buffer: false", fd-specific buffer, sync', testLinesNoBuffer, true, {stdout: false}, execaSync);84test('"lines: true" is a noop with "buffer: false", fd-specific lines, sync', testLinesNoBuffer, {stdout: true}, false, execaSync);
deleted:test/stdio/lines.js-275 removed
1import {Writable} from 'node:stream';2import test from 'ava';3import {execa, execaSync} from '../../index.js';4import {setFixtureDir} from '../helpers/fixtures-dir.js';5import {fullStdio} from '../helpers/stdio.js';6import {getOutputsGenerator} from '../helpers/generator.js';7import {foobarString, foobarObject} from '../helpers/input.js';8import {assertStreamOutput, assertStreamDataEvents, assertIterableChunks} from '../helpers/convert.js';9import {10 simpleFull,11 simpleChunks,12 simpleFullEndChunks,13 simpleFullUint8Array,14 simpleFullHex,15 simpleFullUtf16Uint8Array,16 simpleLines,17 simpleFullEndLines,18 noNewlinesChunks,19} from '../helpers/lines.js';20import {assertErrorMessage} from '../helpers/max-buffer.js';2122setFixtureDir();2324const getSimpleChunkSubprocessAsync = options => getSimpleChunkSubprocess(execa, options);25const getSimpleChunkSubprocess = (execaMethod, options) => execaMethod('noop-fd.js', ['1', simpleFull], {lines: true, ...options});2627// eslint-disable-next-line max-params28const testStreamLines = async (t, fdNumber, input, expectedOutput, lines, stripFinalNewline, execaMethod) => {29 const {stdio} = await execaMethod('noop-fd.js', [`${fdNumber}`, input], {...fullStdio, lines, stripFinalNewline});30 t.deepEqual(stdio[fdNumber], expectedOutput);31};3233test('"lines: true" splits lines, stdout', testStreamLines, 1, simpleFull, simpleLines, true, false, execa);34test('"lines: true" splits lines, stdout, fd-specific', testStreamLines, 1, simpleFull, simpleLines, {stdout: true}, false, execa);35test('"lines: true" splits lines, stderr', testStreamLines, 2, simpleFull, simpleLines, true, false, execa);36test('"lines: true" splits lines, stderr, fd-specific', testStreamLines, 2, simpleFull, simpleLines, {stderr: true}, false, execa);37test('"lines: true" splits lines, stdio[*]', testStreamLines, 3, simpleFull, simpleLines, true, false, execa);38test('"lines: true" splits lines, stdio[*], fd-specific', testStreamLines, 3, simpleFull, simpleLines, {fd3: true}, false, execa);39test('"lines: true" splits lines, stdout, stripFinalNewline', testStreamLines, 1, simpleFull, noNewlinesChunks, true, true, execa);40test('"lines: true" splits lines, stdout, stripFinalNewline, fd-specific', testStreamLines, 1, simpleFull, noNewlinesChunks, true, {stdout: true}, execa);41test('"lines: true" splits lines, stderr, stripFinalNewline', testStreamLines, 2, simpleFull, noNewlinesChunks, true, true, execa);42test('"lines: true" splits lines, stderr, stripFinalNewline, fd-specific', testStreamLines, 2, simpleFull, noNewlinesChunks, true, {stderr: true}, execa);43test('"lines: true" splits lines, stdio[*], stripFinalNewline', testStreamLines, 3, simpleFull, noNewlinesChunks, true, true, execa);44test('"lines: true" splits lines, stdio[*], stripFinalNewline, fd-specific', testStreamLines, 3, simpleFull, noNewlinesChunks, true, {fd3: true}, execa);45test('"lines: true" splits lines, stdout, sync', testStreamLines, 1, simpleFull, simpleLines, true, false, execaSync);46test('"lines: true" splits lines, stdout, fd-specific, sync', testStreamLines, 1, simpleFull, simpleLines, {stdout: true}, false, execaSync);47test('"lines: true" splits lines, stderr, sync', testStreamLines, 2, simpleFull, simpleLines, true, false, execaSync);48test('"lines: true" splits lines, stderr, fd-specific, sync', testStreamLines, 2, simpleFull, simpleLines, {stderr: true}, false, execaSync);49test('"lines: true" splits lines, stdio[*], sync', testStreamLines, 3, simpleFull, simpleLines, true, false, execaSync);50test('"lines: true" splits lines, stdio[*], fd-specific, sync', testStreamLines, 3, simpleFull, simpleLines, {fd3: true}, false, execaSync);51test('"lines: true" splits lines, stdout, stripFinalNewline, sync', testStreamLines, 1, simpleFull, noNewlinesChunks, true, true, execaSync);52test('"lines: true" splits lines, stdout, stripFinalNewline, fd-specific, sync', testStreamLines, 1, simpleFull, noNewlinesChunks, true, {stdout: true}, execaSync);53test('"lines: true" splits lines, stderr, stripFinalNewline, sync', testStreamLines, 2, simpleFull, noNewlinesChunks, true, true, execaSync);54test('"lines: true" splits lines, stderr, stripFinalNewline, fd-specific, sync', testStreamLines, 2, simpleFull, noNewlinesChunks, true, {stderr: true}, execaSync);55test('"lines: true" splits lines, stdio[*], stripFinalNewline, sync', testStreamLines, 3, simpleFull, noNewlinesChunks, true, true, execaSync);56test('"lines: true" splits lines, stdio[*], stripFinalNewline, fd-specific, sync', testStreamLines, 3, simpleFull, noNewlinesChunks, true, {fd3: true}, execaSync);5758const testStreamLinesNoop = async (t, lines, execaMethod) => {59 const {stdout} = await execaMethod('noop-fd.js', ['1', simpleFull], {lines});60 t.is(stdout, simpleFull);61};6263test('"lines: false" is a noop', testStreamLinesNoop, false, execa);64test('"lines: false" is a noop, fd-specific', testStreamLinesNoop, {stderr: true}, execa);65test('"lines: false" is a noop, fd-specific none', testStreamLinesNoop, {}, execa);66test('"lines: false" is a noop, sync', testStreamLinesNoop, false, execaSync);67test('"lines: false" is a noop, fd-specific, sync', testStreamLinesNoop, {stderr: true}, execaSync);68test('"lines: false" is a noop, fd-specific none, sync', testStreamLinesNoop, {}, execaSync);6970const bigArray = Array.from({length: 1e5}).fill('.\n');71const bigString = bigArray.join('');72const bigStringNoNewlines = '.'.repeat(1e6);73const bigStringNoNewlinesEnd = `${bigStringNoNewlines}\n`;7475// eslint-disable-next-line max-params76const testStreamLinesGenerator = async (t, input, expectedLines, objectMode, binary, stripFinalNewline, execaMethod) => {77 const {stdout} = await execaMethod('noop.js', {78 stdout: getOutputsGenerator(input)(objectMode, binary),79 lines: true,80 stripFinalNewline,81 });82 t.deepEqual(stdout, expectedLines);83};8485test('"lines: true" works with strings generators', testStreamLinesGenerator, simpleChunks, simpleFullEndLines, false, false, false, execa);86test('"lines: true" works with strings generators, binary', testStreamLinesGenerator, simpleChunks, simpleLines, false, true, false, execa);87test('"lines: true" works with big strings generators', testStreamLinesGenerator, [bigString], bigArray, false, false, false, execa);88test('"lines: true" works with big strings generators without newlines', testStreamLinesGenerator, [bigStringNoNewlines], [bigStringNoNewlinesEnd], false, false, false, execa);89test('"lines: true" is a noop with strings generators, objectMode', testStreamLinesGenerator, simpleFullEndChunks, simpleFullEndChunks, true, false, false, execa);90test('"lines: true" is a noop with strings generators, stripFinalNewline, objectMode', testStreamLinesGenerator, simpleFullEndChunks, simpleFullEndChunks, true, false, true, execa);91test('"lines: true" is a noop with strings generators, stripFinalNewline, fd-specific, objectMode', testStreamLinesGenerator, simpleFullEndChunks, simpleFullEndChunks, true, false, {stdout: true}, execa);92test('"lines: true" is a noop with strings generators, binary, objectMode', testStreamLinesGenerator, simpleChunks, simpleChunks, true, true, false, execa);93test('"lines: true" is a noop big strings generators, objectMode', testStreamLinesGenerator, [bigString], [bigString], true, false, false, execa);94test('"lines: true" is a noop big strings generators without newlines, objectMode', testStreamLinesGenerator, [bigStringNoNewlines], [bigStringNoNewlines], true, false, false, execa);95test('"lines: true" works with strings generators, sync', testStreamLinesGenerator, simpleChunks, simpleFullEndLines, false, false, false, execaSync);96test('"lines: true" works with strings generators, binary, sync', testStreamLinesGenerator, simpleChunks, simpleLines, false, true, false, execaSync);97test('"lines: true" works with big strings generators, sync', testStreamLinesGenerator, [bigString], bigArray, false, false, false, execaSync);98test('"lines: true" works with big strings generators without newlines, sync', testStreamLinesGenerator, [bigStringNoNewlines], [bigStringNoNewlinesEnd], false, false, false, execaSync);99test('"lines: true" is a noop with strings generators, objectMode, sync', testStreamLinesGenerator, simpleFullEndChunks, simpleFullEndChunks, true, false, false, execaSync);100test('"lines: true" is a noop with strings generators, stripFinalNewline, objectMode, sync', testStreamLinesGenerator, simpleFullEndChunks, simpleFullEndChunks, true, false, true, execaSync);101test('"lines: true" is a noop with strings generators, stripFinalNewline, fd-specific, objectMode, sync', testStreamLinesGenerator, simpleFullEndChunks, simpleFullEndChunks, true, false, {stdout: true}, execaSync);102test('"lines: true" is a noop with strings generators, binary, objectMode, sync', testStreamLinesGenerator, simpleChunks, simpleChunks, true, true, false, execaSync);103test('"lines: true" is a noop big strings generators, objectMode, sync', testStreamLinesGenerator, [bigString], [bigString], true, false, false, execaSync);104test('"lines: true" is a noop big strings generators without newlines, objectMode, sync', testStreamLinesGenerator, [bigStringNoNewlines], [bigStringNoNewlines], true, false, false, execaSync);105106const testLinesObjectMode = async (t, lines, execaMethod) => {107 const {stdout} = await execaMethod('noop.js', {108 stdout: getOutputsGenerator([foobarObject])(true),109 lines,110 });111 t.deepEqual(stdout, [foobarObject]);112};113114test('"lines: true" is a noop with objects generators, objectMode', testLinesObjectMode, true, execa);115test('"lines: true" is a noop with objects generators, fd-specific, objectMode', testLinesObjectMode, {stdout: true}, execa);116test('"lines: true" is a noop with objects generators, objectMode, sync', testLinesObjectMode, true, execaSync);117test('"lines: true" is a noop with objects generators, fd-specific, objectMode, sync', testLinesObjectMode, {stdout: true}, execaSync);118119// eslint-disable-next-line max-params120const testEncoding = async (t, input, expectedOutput, encoding, lines, stripFinalNewline, execaMethod) => {121 const {stdout} = await execaMethod('stdin.js', {lines, stripFinalNewline, encoding, input});122 t.deepEqual(stdout, expectedOutput);123};124125test('"lines: true" is a noop with "encoding: utf16"', testEncoding, simpleFullUtf16Uint8Array, simpleLines, 'utf16le', true, false, execa);126test('"lines: true" is a noop with "encoding: utf16", fd-specific', testEncoding, simpleFullUtf16Uint8Array, simpleLines, 'utf16le', {stdout: true}, false, execa);127test('"lines: true" is a noop with "encoding: utf16", stripFinalNewline', testEncoding, simpleFullUtf16Uint8Array, noNewlinesChunks, 'utf16le', true, true, execa);128test('"lines: true" is a noop with "encoding: utf16", stripFinalNewline, fd-specific', testEncoding, simpleFullUtf16Uint8Array, noNewlinesChunks, 'utf16le', true, {stdout: true}, execa);129test('"lines: true" is a noop with "encoding: buffer"', testEncoding, simpleFull, simpleFullUint8Array, 'buffer', true, false, execa);130test('"lines: true" is a noop with "encoding: buffer", fd-specific', testEncoding, simpleFull, simpleFullUint8Array, 'buffer', {stdout: true}, false, execa);131test('"lines: true" is a noop with "encoding: buffer", stripFinalNewline', testEncoding, simpleFull, simpleFullUint8Array, 'buffer', true, false, execa);132test('"lines: true" is a noop with "encoding: buffer", stripFinalNewline, fd-specific', testEncoding, simpleFull, simpleFullUint8Array, 'buffer', true, {stdout: false}, execa);133test('"lines: true" is a noop with "encoding: hex"', testEncoding, simpleFull, simpleFullHex, 'hex', true, false, execa);134test('"lines: true" is a noop with "encoding: hex", fd-specific', testEncoding, simpleFull, simpleFullHex, 'hex', {stdout: true}, false, execa);135test('"lines: true" is a noop with "encoding: hex", stripFinalNewline', testEncoding, simpleFull, simpleFullHex, 'hex', true, true, execa);136test('"lines: true" is a noop with "encoding: hex", stripFinalNewline, fd-specific', testEncoding, simpleFull, simpleFullHex, 'hex', true, {stdout: true}, execa);137test('"lines: true" is a noop with "encoding: utf16", sync', testEncoding, simpleFullUtf16Uint8Array, simpleLines, 'utf16le', true, false, execaSync);138test('"lines: true" is a noop with "encoding: utf16", fd-specific, sync', testEncoding, simpleFullUtf16Uint8Array, simpleLines, 'utf16le', {stdout: true}, false, execaSync);139test('"lines: true" is a noop with "encoding: utf16", stripFinalNewline, sync', testEncoding, simpleFullUtf16Uint8Array, noNewlinesChunks, 'utf16le', true, true, execaSync);140test('"lines: true" is a noop with "encoding: utf16", stripFinalNewline, fd-specific, sync', testEncoding, simpleFullUtf16Uint8Array, noNewlinesChunks, 'utf16le', true, {stdout: true}, execaSync);141test('"lines: true" is a noop with "encoding: buffer", sync', testEncoding, simpleFull, simpleFullUint8Array, 'buffer', true, false, execaSync);142test('"lines: true" is a noop with "encoding: buffer", fd-specific, sync', testEncoding, simpleFull, simpleFullUint8Array, 'buffer', {stdout: true}, false, execaSync);143test('"lines: true" is a noop with "encoding: buffer", stripFinalNewline, sync', testEncoding, simpleFull, simpleFullUint8Array, 'buffer', true, false, execaSync);144test('"lines: true" is a noop with "encoding: buffer", stripFinalNewline, fd-specific, sync', testEncoding, simpleFull, simpleFullUint8Array, 'buffer', true, {stdout: false}, execaSync);145test('"lines: true" is a noop with "encoding: hex", sync', testEncoding, simpleFull, simpleFullHex, 'hex', true, false, execaSync);146test('"lines: true" is a noop with "encoding: hex", fd-specific, sync', testEncoding, simpleFull, simpleFullHex, 'hex', {stdout: true}, false, execaSync);147test('"lines: true" is a noop with "encoding: hex", stripFinalNewline, sync', testEncoding, simpleFull, simpleFullHex, 'hex', true, true, execaSync);148test('"lines: true" is a noop with "encoding: hex", stripFinalNewline, fd-specific, sync', testEncoding, simpleFull, simpleFullHex, 'hex', true, {stdout: true}, execaSync);149150const testLinesNoBuffer = async (t, lines, buffer, execaMethod) => {151 const {stdout} = await getSimpleChunkSubprocess(execaMethod, {lines, buffer});152 t.is(stdout, undefined);153};154155test('"lines: true" is a noop with "buffer: false"', testLinesNoBuffer, true, false, execa);156test('"lines: true" is a noop with "buffer: false", fd-specific buffer', testLinesNoBuffer, true, {stdout: false}, execa);157test('"lines: true" is a noop with "buffer: false", fd-specific lines', testLinesNoBuffer, {stdout: true}, false, execa);158test('"lines: true" is a noop with "buffer: false", sync', testLinesNoBuffer, true, false, execaSync);159test('"lines: true" is a noop with "buffer: false", fd-specific buffer, sync', testLinesNoBuffer, true, {stdout: false}, execaSync);160test('"lines: true" is a noop with "buffer: false", fd-specific lines, sync', testLinesNoBuffer, {stdout: true}, false, execaSync);161162const maxBuffer = simpleLines.length - 1;163164const testBelowMaxBuffer = async (t, lines) => {165 const {isMaxBuffer, stdout} = await getSimpleChunkSubprocessAsync({lines, maxBuffer: maxBuffer + 1});166 t.false(isMaxBuffer);167 t.deepEqual(stdout, noNewlinesChunks);168};169170test('"lines: true" can be below "maxBuffer"', testBelowMaxBuffer, true);171test('"lines: true" can be below "maxBuffer", fd-specific', testBelowMaxBuffer, {stdout: true});172173const testAboveMaxBuffer = async (t, lines) => {174 const {isMaxBuffer, shortMessage, stdout} = await t.throwsAsync(getSimpleChunkSubprocessAsync({lines, maxBuffer}));175 t.true(isMaxBuffer);176 assertErrorMessage(t, shortMessage, {length: maxBuffer, unit: 'lines'});177 t.deepEqual(stdout, noNewlinesChunks.slice(0, maxBuffer));178};179180test('"lines: true" can be above "maxBuffer"', testAboveMaxBuffer, true);181test('"lines: true" can be above "maxBuffer", fd-specific', testAboveMaxBuffer, {stdout: true});182183const testMaxBufferUnit = async (t, lines) => {184 const {isMaxBuffer, shortMessage, stdout} = await t.throwsAsync(execa('noop-repeat.js', ['1', '...\n'], {lines, maxBuffer}));185 t.true(isMaxBuffer);186 assertErrorMessage(t, shortMessage, {length: maxBuffer, unit: 'lines'});187 t.deepEqual(stdout, ['...', '...']);188};189190test('"maxBuffer" is measured in lines with "lines: true"', testMaxBufferUnit, true);191test('"maxBuffer" is measured in lines with "lines: true", fd-specific', testMaxBufferUnit, {stdout: true});192193const testMaxBufferUnitSync = (t, lines) => {194 const {isMaxBuffer, shortMessage, stdout} = t.throws(() => {195 execaSync('noop-repeat.js', ['1', '...\n'], {lines, maxBuffer});196 }, {code: 'ENOBUFS'});197 t.true(isMaxBuffer);198 assertErrorMessage(t, shortMessage, {execaMethod: execaSync, length: maxBuffer});199 t.deepEqual(stdout, ['..']);200};201202test('"maxBuffer" is measured in bytes with "lines: true", sync', testMaxBufferUnitSync, true);203test('"maxBuffer" is measured in bytes with "lines: true", fd-specific, sync', testMaxBufferUnitSync, {stdout: true});204205test('"lines: true" stops on stream error', async t => {206 const cause = new Error(foobarString);207 const error = await t.throwsAsync(getSimpleChunkSubprocessAsync({208 * stdout(line) {209 if (line === noNewlinesChunks[2]) {210 throw cause;211 }212213 yield line;214 },215 }));216 t.is(error.cause, cause);217 t.deepEqual(error.stdout, noNewlinesChunks.slice(0, 2));218});219220test('"lines: true" stops on stream error event', async t => {221 const cause = new Error(foobarString);222 const subprocess = getSimpleChunkSubprocessAsync();223 subprocess.stdout.emit('error', cause);224 const error = await t.throwsAsync(subprocess);225 t.is(error.cause, cause);226 t.deepEqual(error.stdout, []);227});228229const testAsyncIteration = async (t, expectedLines, stripFinalNewline) => {230 const subprocess = getSimpleChunkSubprocessAsync({stripFinalNewline});231 t.false(subprocess.stdout.readableObjectMode);232 await assertStreamOutput(t, subprocess.stdout, simpleFull);233 const {stdout} = await subprocess;234 t.deepEqual(stdout, expectedLines);235};236237test('"lines: true" works with stream async iteration', testAsyncIteration, simpleLines, false);238test('"lines: true" works with stream async iteration, stripFinalNewline', testAsyncIteration, noNewlinesChunks, true);239240const testDataEvents = async (t, expectedLines, stripFinalNewline) => {241 const subprocess = getSimpleChunkSubprocessAsync({stripFinalNewline});242 await assertStreamDataEvents(t, subprocess.stdout, simpleFull);243 const {stdout} = await subprocess;244 t.deepEqual(stdout, expectedLines);245};246247test('"lines: true" works with stream "data" events', testDataEvents, simpleLines, false);248test('"lines: true" works with stream "data" events, stripFinalNewline', testDataEvents, noNewlinesChunks, true);249250const testWritableStream = async (t, expectedLines, stripFinalNewline) => {251 let output = '';252 const writable = new Writable({253 write(line, encoding, done) {254 output += line.toString();255 done();256 },257 decodeStrings: false,258 });259 const {stdout} = await getSimpleChunkSubprocessAsync({stripFinalNewline, stdout: ['pipe', writable]});260 t.deepEqual(output, simpleFull);261 t.deepEqual(stdout, expectedLines);262};263264test('"lines: true" works with writable streams targets', testWritableStream, simpleLines, false);265test('"lines: true" works with writable streams targets, stripFinalNewline', testWritableStream, noNewlinesChunks, true);266267const testIterable = async (t, expectedLines, stripFinalNewline) => {268 const subprocess = getSimpleChunkSubprocessAsync({stripFinalNewline});269 await assertIterableChunks(t, subprocess, noNewlinesChunks);270 const {stdout} = await subprocess;271 t.deepEqual(stdout, expectedLines);272};273274test('"lines: true" works with subprocess.iterable()', testIterable, simpleLines, false);275test('"lines: true" works with subprocess.iterable(), stripFinalNewline', testIterable, noNewlinesChunks, true);
added:test/stdio/native-fd.js+76 added
1import {platform} from 'node:process';2import test from 'ava';3import {execa, execaSync} from '../../index.js';4import {getStdio, fullStdio} from '../helpers/stdio.js';5import {setFixtureDir} from '../helpers/fixtures-dir.js';6import {foobarString} from '../helpers/input.js';7import {parentExecaAsync, parentExecaSync} from '../helpers/nested.js';89setFixtureDir();1011const isLinux = platform === 'linux';12const isWindows = platform === 'win32';1314const testFd3InheritOutput = async (t, stdioOption, execaMethod) => {15 const {stdio} = await execaMethod('noop-fd.js', ['3', foobarString], getStdio(3, stdioOption), fullStdio);16 t.is(stdio[3], foobarString);17};1819test('stdio[*] output can use "inherit"', testFd3InheritOutput, 'inherit', parentExecaAsync);20test('stdio[*] output can use ["inherit"]', testFd3InheritOutput, ['inherit'], parentExecaAsync);21test('stdio[*] output can use "inherit", sync', testFd3InheritOutput, 'inherit', parentExecaSync);22test('stdio[*] output can use ["inherit"], sync', testFd3InheritOutput, ['inherit'], parentExecaSync);2324if (isLinux) {25 const testOverflowStream = async (t, fdNumber, stdioOption, execaMethod) => {26 const {stdout} = await execaMethod('empty.js', getStdio(fdNumber, stdioOption), fullStdio);27 t.is(stdout, '');28 };2930 test('stdin can use 4+', testOverflowStream, 0, 4, parentExecaAsync);31 test('stdin can use [4+]', testOverflowStream, 0, [4], parentExecaAsync);32 test('stdout can use 4+', testOverflowStream, 1, 4, parentExecaAsync);33 test('stdout can use [4+]', testOverflowStream, 1, [4], parentExecaAsync);34 test('stderr can use 4+', testOverflowStream, 2, 4, parentExecaAsync);35 test('stderr can use [4+]', testOverflowStream, 2, [4], parentExecaAsync);36 test('stdio[*] can use 4+', testOverflowStream, 3, 4, parentExecaAsync);37 test('stdio[*] can use [4+]', testOverflowStream, 3, [4], parentExecaAsync);38 test('stdin can use 4+, sync', testOverflowStream, 0, 4, parentExecaSync);39 test('stdin can use [4+], sync', testOverflowStream, 0, [4], parentExecaSync);40 test('stdout can use 4+, sync', testOverflowStream, 1, 4, parentExecaSync);41 test('stdout can use [4+], sync', testOverflowStream, 1, [4], parentExecaSync);42 test('stderr can use 4+, sync', testOverflowStream, 2, 4, parentExecaSync);43 test('stderr can use [4+], sync', testOverflowStream, 2, [4], parentExecaSync);44 test('stdio[*] can use 4+, sync', testOverflowStream, 3, 4, parentExecaSync);45 test('stdio[*] can use [4+], sync', testOverflowStream, 3, [4], parentExecaSync);46}4748const testOverflowStreamArray = (t, fdNumber, stdioOption) => {49 t.throws(() => {50 execa('empty.js', getStdio(fdNumber, stdioOption));51 }, {message: /no such standard stream/});52};5354test('stdin cannot use 4+ and another value', testOverflowStreamArray, 0, [4, 'pipe']);55test('stdout cannot use 4+ and another value', testOverflowStreamArray, 1, [4, 'pipe']);56test('stderr cannot use 4+ and another value', testOverflowStreamArray, 2, [4, 'pipe']);57test('stdio[*] cannot use 4+ and another value', testOverflowStreamArray, 3, [4, 'pipe']);58test('stdio[*] cannot use "inherit" and another value', testOverflowStreamArray, 3, ['inherit', 'pipe']);5960const getInvalidFdCode = () => {61 if (isLinux) {62 return 'EINVAL';63 }6465 return isWindows ? 'EBADF' : 'ENXIO';66};6768const testOverflowStreamArraySync = (t, fdNumber) => {69 t.throws(() => {70 execaSync('noop-fd.js', [fdNumber, foobarString], getStdio(fdNumber, [4, 'pipe']));71 }, {code: getInvalidFdCode()});72};7374test('stdout cannot use 4+ and another value, sync', testOverflowStreamArraySync, 1);75test('stderr cannot use 4+ and another value, sync', testOverflowStreamArraySync, 2);76test('stdio[*] cannot use 4+ and another value, sync', testOverflowStreamArraySync, 3);
added:test/stdio/native-inherit-pipe.js+97 added
1import {readFile, rm} from 'node:fs/promises';2import test from 'ava';3import tempfile from 'tempfile';4import {execa} from '../../index.js';5import {getStdio, fullStdio} from '../helpers/stdio.js';6import {setFixtureDir} from '../helpers/fixtures-dir.js';7import {foobarString} from '../helpers/input.js';8import {parentExecaAsync, parentExecaSync} from '../helpers/nested.js';910setFixtureDir();1112const testInheritStdin = async (t, stdioOption, isSync) => {13 const {stdout} = await execa('nested-multiple-stdin.js', [JSON.stringify(stdioOption), `${isSync}`], {input: foobarString});14 t.is(stdout, `${foobarString}${foobarString}`);15};1617test('stdin can be ["inherit", "pipe"]', testInheritStdin, ['inherit', 'pipe'], false);18test('stdin can be [0, "pipe"]', testInheritStdin, [0, 'pipe'], false);19test('stdin can be [process.stdin, "pipe"]', testInheritStdin, ['stdin', 'pipe'], false);20test.serial('stdin can be ["inherit", "pipe"], sync', testInheritStdin, ['inherit', 'pipe'], true);21test.serial('stdin can be [0, "pipe"], sync', testInheritStdin, [0, 'pipe'], true);22test.serial('stdin can be [process.stdin, "pipe"], sync', testInheritStdin, ['stdin', 'pipe'], true);2324// eslint-disable-next-line max-params25const testInheritStdioOutput = async (t, fdNumber, outerFdNumber, stdioOption, isSync, encoding) => {26 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};3031test('stdout can be ["inherit", "pipe"]', testInheritStdioOutput, 1, 2, ['inherit', 'pipe'], false, 'utf8');32test('stdout can be [1, "pipe"]', testInheritStdioOutput, 1, 2, [1, 'pipe'], false, 'utf8');33test('stdout can be [process.stdout, "pipe"]', testInheritStdioOutput, 1, 2, ['stdout', 'pipe'], false, 'utf8');34test('stderr can be ["inherit", "pipe"]', testInheritStdioOutput, 2, 1, ['inherit', 'pipe'], false, 'utf8');35test('stderr can be [2, "pipe"]', testInheritStdioOutput, 2, 1, [2, 'pipe'], false, 'utf8');36test('stderr can be [process.stderr, "pipe"]', testInheritStdioOutput, 2, 1, ['stderr', 'pipe'], false, 'utf8');37test('stdout can be ["inherit", "pipe"], encoding "buffer"', testInheritStdioOutput, 1, 2, ['inherit', 'pipe'], false, 'buffer');38test('stdout can be [1, "pipe"], encoding "buffer"', testInheritStdioOutput, 1, 2, [1, 'pipe'], false, 'buffer');39test('stdout can be [process.stdout, "pipe"], encoding "buffer"', testInheritStdioOutput, 1, 2, ['stdout', 'pipe'], false, 'buffer');40test('stderr can be ["inherit", "pipe"], encoding "buffer"', testInheritStdioOutput, 2, 1, ['inherit', 'pipe'], false, 'buffer');41test('stderr can be [2, "pipe"], encoding "buffer"', testInheritStdioOutput, 2, 1, [2, 'pipe'], false, 'buffer');42test('stderr can be [process.stderr, "pipe"], encoding "buffer"', testInheritStdioOutput, 2, 1, ['stderr', 'pipe'], false, 'buffer');43test('stdout can be ["inherit", "pipe"], sync', testInheritStdioOutput, 1, 2, ['inherit', 'pipe'], true, 'utf8');44test('stdout can be [1, "pipe"], sync', testInheritStdioOutput, 1, 2, [1, 'pipe'], true, 'utf8');45test('stdout can be [process.stdout, "pipe"], sync', testInheritStdioOutput, 1, 2, ['stdout', 'pipe'], true, 'utf8');46test('stderr can be ["inherit", "pipe"], sync', testInheritStdioOutput, 2, 1, ['inherit', 'pipe'], true, 'utf8');47test('stderr can be [2, "pipe"], sync', testInheritStdioOutput, 2, 1, [2, 'pipe'], true, 'utf8');48test('stderr can be [process.stderr, "pipe"], sync', testInheritStdioOutput, 2, 1, ['stderr', 'pipe'], true, 'utf8');49test('stdio[*] output can be ["inherit", "pipe"], sync', testInheritStdioOutput, 3, 1, ['inherit', 'pipe'], true, 'utf8');50test('stdio[*] output can be [3, "pipe"], sync', testInheritStdioOutput, 3, 1, [3, 'pipe'], true, 'utf8');51test('stdout can be ["inherit", "pipe"], encoding "buffer", sync', testInheritStdioOutput, 1, 2, ['inherit', 'pipe'], true, 'buffer');52test('stdout can be [1, "pipe"], encoding "buffer", sync', testInheritStdioOutput, 1, 2, [1, 'pipe'], true, 'buffer');53test('stdout can be [process.stdout, "pipe"], encoding "buffer", sync', testInheritStdioOutput, 1, 2, ['stdout', 'pipe'], true, 'buffer');54test('stderr can be ["inherit", "pipe"], encoding "buffer", sync', testInheritStdioOutput, 2, 1, ['inherit', 'pipe'], true, 'buffer');55test('stderr can be [2, "pipe"], encoding "buffer", sync', testInheritStdioOutput, 2, 1, [2, 'pipe'], true, 'buffer');56test('stderr can be [process.stderr, "pipe"], encoding "buffer", sync', testInheritStdioOutput, 2, 1, ['stderr', 'pipe'], true, 'buffer');57test('stdio[*] output can be ["inherit", "pipe"], encoding "buffer", sync', testInheritStdioOutput, 3, 1, ['inherit', 'pipe'], true, 'buffer');58test('stdio[*] output can be [3, "pipe"], encoding "buffer", sync', testInheritStdioOutput, 3, 1, [3, 'pipe'], true, 'buffer');5960const testInheritNoBuffer = async (t, stdioOption, execaMethod) => {61 const filePath = tempfile();62 await execaMethod('nested-write.js', [filePath, foobarString], {stdin: stdioOption, buffer: false}, {input: foobarString});63 t.is(await readFile(filePath, 'utf8'), `${foobarString} ${foobarString}`);64 await rm(filePath);65};6667test('stdin can be ["inherit", "pipe"], buffer: false', testInheritNoBuffer, ['inherit', 'pipe'], parentExecaAsync);68test('stdin can be [0, "pipe"], buffer: false', testInheritNoBuffer, [0, 'pipe'], parentExecaAsync);69test.serial('stdin can be ["inherit", "pipe"], buffer: false, sync', testInheritNoBuffer, ['inherit', 'pipe'], parentExecaSync);70test.serial('stdin can be [0, "pipe"], buffer: false, sync', testInheritNoBuffer, [0, 'pipe'], parentExecaSync);7172test('stdin can use ["inherit", "pipe"] in a TTY', async t => {73 const stdioOption = [['inherit', 'pipe'], 'inherit', 'pipe'];74 const {stdout} = await execa('nested-sync-tty.js', [JSON.stringify({stdio: stdioOption}), 'false', 'stdin-fd.js', '0'], {input: foobarString});75 t.is(stdout, foobarString);76});7778const testNoTtyInput = async (t, fdNumber, optionName) => {79 const stdioOption = ['pipe', 'inherit', 'pipe'];80 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};8485test('stdin cannot use ["inherit", "pipe"] in a TTY, sync', testNoTtyInput, 0, 'stdin');86test('stdio[*] input cannot use ["inherit", "pipe"] in a TTY, sync', testNoTtyInput, 3, 'stdio[3]');8788const testTtyOutput = async (t, fdNumber, isSync) => {89 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);91};9293test('stdout can use ["inherit", "pipe"] in a TTY', testTtyOutput, 1, false);94test('stderr can use ["inherit", "pipe"] in a TTY', testTtyOutput, 2, false);95test('stdout can use ["inherit", "pipe"] in a TTY, sync', testTtyOutput, 1, true);96test('stderr can use ["inherit", "pipe"] in a TTY, sync', testTtyOutput, 2, true);97test('stdio[*] output can use ["inherit", "pipe"] in a TTY, sync', testTtyOutput, 3, true);
added:test/stdio/native-redirect.js+75 added
1import test from 'ava';2import {execa} from '../../index.js';3import {setFixtureDir} from '../helpers/fixtures-dir.js';4import {foobarString} from '../helpers/input.js';56setFixtureDir();78// eslint-disable-next-line max-params9const testRedirect = async (t, 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);16};1718const isStderrDescriptor = stdioOption => stdioOption === 219 || stdioOption === 'stderr'20 || (Array.isArray(stdioOption) && isStderrDescriptor(stdioOption[0]));2122test.serial('stdio[*] can be 0', testRedirect, 0, 3, true, false);23test.serial('stdio[*] can be [0]', testRedirect, [0], 3, true, false);24test.serial('stdio[*] can be [0, "pipe"]', testRedirect, [0, 'pipe'], 3, true, false);25test.serial('stdio[*] can be process.stdin', testRedirect, 'stdin', 3, true, false);26test.serial('stdio[*] can be [process.stdin]', testRedirect, ['stdin'], 3, true, false);27test.serial('stdio[*] can be [process.stdin, "pipe"]', testRedirect, ['stdin', 'pipe'], 3, true, false);28test('stdout can be 2', testRedirect, 2, 1, false, false);29test('stdout can be [2]', testRedirect, [2], 1, false, false);30test('stdout can be [2, "pipe"]', testRedirect, [2, 'pipe'], 1, false, false);31test('stdout can be process.stderr', testRedirect, 'stderr', 1, false, false);32test('stdout can be [process.stderr]', testRedirect, ['stderr'], 1, false, false);33test('stdout can be [process.stderr, "pipe"]', testRedirect, ['stderr', 'pipe'], 1, false, false);34test('stderr can be 1', testRedirect, 1, 2, false, false);35test('stderr can be [1]', testRedirect, [1], 2, false, false);36test('stderr can be [1, "pipe"]', testRedirect, [1, 'pipe'], 2, false, false);37test('stderr can be process.stdout', testRedirect, 'stdout', 2, false, false);38test('stderr can be [process.stdout]', testRedirect, ['stdout'], 2, false, false);39test('stderr can be [process.stdout, "pipe"]', testRedirect, ['stdout', 'pipe'], 2, false, false);40test('stdio[*] can be 1', testRedirect, 1, 3, false, false);41test('stdio[*] can be [1]', testRedirect, [1], 3, false, false);42test('stdio[*] can be [1, "pipe"]', testRedirect, [1, 'pipe'], 3, false, false);43test('stdio[*] can be 2', testRedirect, 2, 3, false, false);44test('stdio[*] can be [2]', testRedirect, [2], 3, false, false);45test('stdio[*] can be [2, "pipe"]', testRedirect, [2, 'pipe'], 3, false, false);46test('stdio[*] can be process.stdout', testRedirect, 'stdout', 3, false, false);47test('stdio[*] can be [process.stdout]', testRedirect, ['stdout'], 3, false, false);48test('stdio[*] can be [process.stdout, "pipe"]', testRedirect, ['stdout', 'pipe'], 3, false, false);49test('stdio[*] can be process.stderr', testRedirect, 'stderr', 3, false, false);50test('stdio[*] can be [process.stderr]', testRedirect, ['stderr'], 3, false, false);51test('stdio[*] can be [process.stderr, "pipe"]', testRedirect, ['stderr', 'pipe'], 3, false, false);52test('stdout can be 2, sync', testRedirect, 2, 1, false, true);53test('stdout can be [2], sync', testRedirect, [2], 1, false, true);54test('stdout can be [2, "pipe"], sync', testRedirect, [2, 'pipe'], 1, false, true);55test('stdout can be process.stderr, sync', testRedirect, 'stderr', 1, false, true);56test('stdout can be [process.stderr], sync', testRedirect, ['stderr'], 1, false, true);57test('stdout can be [process.stderr, "pipe"], sync', testRedirect, ['stderr', 'pipe'], 1, false, true);58test('stderr can be 1, sync', testRedirect, 1, 2, false, true);59test('stderr can be [1], sync', testRedirect, [1], 2, false, true);60test('stderr can be [1, "pipe"], sync', testRedirect, [1, 'pipe'], 2, false, true);61test('stderr can be process.stdout, sync', testRedirect, 'stdout', 2, false, true);62test('stderr can be [process.stdout], sync', testRedirect, ['stdout'], 2, false, true);63test('stderr can be [process.stdout, "pipe"], sync', testRedirect, ['stdout', 'pipe'], 2, false, true);64test('stdio[*] can be 1, sync', testRedirect, 1, 3, false, true);65test('stdio[*] can be [1], sync', testRedirect, [1], 3, false, true);66test('stdio[*] can be [1, "pipe"], sync', testRedirect, [1, 'pipe'], 3, false, true);67test('stdio[*] can be 2, sync', testRedirect, 2, 3, false, true);68test('stdio[*] can be [2], sync', testRedirect, [2], 3, false, true);69test('stdio[*] can be [2, "pipe"], sync', testRedirect, [2, 'pipe'], 3, false, true);70test('stdio[*] can be process.stdout, sync', testRedirect, 'stdout', 3, false, true);71test('stdio[*] can be [process.stdout], sync', testRedirect, ['stdout'], 3, false, true);72test('stdio[*] can be [process.stdout, "pipe"], sync', testRedirect, ['stdout', 'pipe'], 3, false, true);73test('stdio[*] can be process.stderr, sync', testRedirect, 'stderr', 3, false, true);74test('stdio[*] can be [process.stderr], sync', testRedirect, ['stderr'], 3, false, true);75test('stdio[*] can be [process.stderr, "pipe"], sync', testRedirect, ['stderr', 'pipe'], 3, false, true);
deleted:test/stdio/native.js-234 removed
1import {readFile, rm} from 'node:fs/promises';2import {platform} from 'node:process';3import test from 'ava';4import tempfile from 'tempfile';5import {execa, execaSync} from '../../index.js';6import {getStdio, fullStdio} from '../helpers/stdio.js';7import {setFixtureDir} from '../helpers/fixtures-dir.js';8import {foobarString} from '../helpers/input.js';9import {parentExecaAsync, parentExecaSync} from '../helpers/nested.js';1011setFixtureDir();1213const isLinux = platform === 'linux';14const isWindows = platform === 'win32';1516// eslint-disable-next-line max-params17const testRedirect = async (t, stdioOption, fdNumber, isInput, isSync) => {18 const {fixtureName, ...options} = isInput19 ? {fixtureName: 'stdin-fd.js', input: foobarString}20 : {fixtureName: 'noop-fd.js'};21 const {stdio} = await execa('nested-stdio.js', [JSON.stringify(stdioOption), `${fdNumber}`, `${isSync}`, fixtureName, foobarString], options);22 const resultFdNumber = isStderrDescriptor(stdioOption) ? 2 : 1;23 t.is(stdio[resultFdNumber], foobarString);24};2526const isStderrDescriptor = stdioOption => stdioOption === 227 || stdioOption === 'stderr'28 || (Array.isArray(stdioOption) && isStderrDescriptor(stdioOption[0]));2930test.serial('stdio[*] can be 0', testRedirect, 0, 3, true, false);31test.serial('stdio[*] can be [0]', testRedirect, [0], 3, true, false);32test.serial('stdio[*] can be [0, "pipe"]', testRedirect, [0, 'pipe'], 3, true, false);33test.serial('stdio[*] can be process.stdin', testRedirect, 'stdin', 3, true, false);34test.serial('stdio[*] can be [process.stdin]', testRedirect, ['stdin'], 3, true, false);35test.serial('stdio[*] can be [process.stdin, "pipe"]', testRedirect, ['stdin', 'pipe'], 3, true, false);36test('stdout can be 2', testRedirect, 2, 1, false, false);37test('stdout can be [2]', testRedirect, [2], 1, false, false);38test('stdout can be [2, "pipe"]', testRedirect, [2, 'pipe'], 1, false, false);39test('stdout can be process.stderr', testRedirect, 'stderr', 1, false, false);40test('stdout can be [process.stderr]', testRedirect, ['stderr'], 1, false, false);41test('stdout can be [process.stderr, "pipe"]', testRedirect, ['stderr', 'pipe'], 1, false, false);42test('stderr can be 1', testRedirect, 1, 2, false, false);43test('stderr can be [1]', testRedirect, [1], 2, false, false);44test('stderr can be [1, "pipe"]', testRedirect, [1, 'pipe'], 2, false, false);45test('stderr can be process.stdout', testRedirect, 'stdout', 2, false, false);46test('stderr can be [process.stdout]', testRedirect, ['stdout'], 2, false, false);47test('stderr can be [process.stdout, "pipe"]', testRedirect, ['stdout', 'pipe'], 2, false, false);48test('stdio[*] can be 1', testRedirect, 1, 3, false, false);49test('stdio[*] can be [1]', testRedirect, [1], 3, false, false);50test('stdio[*] can be [1, "pipe"]', testRedirect, [1, 'pipe'], 3, false, false);51test('stdio[*] can be 2', testRedirect, 2, 3, false, false);52test('stdio[*] can be [2]', testRedirect, [2], 3, false, false);53test('stdio[*] can be [2, "pipe"]', testRedirect, [2, 'pipe'], 3, false, false);54test('stdio[*] can be process.stdout', testRedirect, 'stdout', 3, false, false);55test('stdio[*] can be [process.stdout]', testRedirect, ['stdout'], 3, false, false);56test('stdio[*] can be [process.stdout, "pipe"]', testRedirect, ['stdout', 'pipe'], 3, false, false);57test('stdio[*] can be process.stderr', testRedirect, 'stderr', 3, false, false);58test('stdio[*] can be [process.stderr]', testRedirect, ['stderr'], 3, false, false);59test('stdio[*] can be [process.stderr, "pipe"]', testRedirect, ['stderr', 'pipe'], 3, false, false);60test('stdout can be 2, sync', testRedirect, 2, 1, false, true);61test('stdout can be [2], sync', testRedirect, [2], 1, false, true);62test('stdout can be [2, "pipe"], sync', testRedirect, [2, 'pipe'], 1, false, true);63test('stdout can be process.stderr, sync', testRedirect, 'stderr', 1, false, true);64test('stdout can be [process.stderr], sync', testRedirect, ['stderr'], 1, false, true);65test('stdout can be [process.stderr, "pipe"], sync', testRedirect, ['stderr', 'pipe'], 1, false, true);66test('stderr can be 1, sync', testRedirect, 1, 2, false, true);67test('stderr can be [1], sync', testRedirect, [1], 2, false, true);68test('stderr can be [1, "pipe"], sync', testRedirect, [1, 'pipe'], 2, false, true);69test('stderr can be process.stdout, sync', testRedirect, 'stdout', 2, false, true);70test('stderr can be [process.stdout], sync', testRedirect, ['stdout'], 2, false, true);71test('stderr can be [process.stdout, "pipe"], sync', testRedirect, ['stdout', 'pipe'], 2, false, true);72test('stdio[*] can be 1, sync', testRedirect, 1, 3, false, true);73test('stdio[*] can be [1], sync', testRedirect, [1], 3, false, true);74test('stdio[*] can be [1, "pipe"], sync', testRedirect, [1, 'pipe'], 3, false, true);75test('stdio[*] can be 2, sync', testRedirect, 2, 3, false, true);76test('stdio[*] can be [2], sync', testRedirect, [2], 3, false, true);77test('stdio[*] can be [2, "pipe"], sync', testRedirect, [2, 'pipe'], 3, false, true);78test('stdio[*] can be process.stdout, sync', testRedirect, 'stdout', 3, false, true);79test('stdio[*] can be [process.stdout], sync', testRedirect, ['stdout'], 3, false, true);80test('stdio[*] can be [process.stdout, "pipe"], sync', testRedirect, ['stdout', 'pipe'], 3, false, true);81test('stdio[*] can be process.stderr, sync', testRedirect, 'stderr', 3, false, true);82test('stdio[*] can be [process.stderr], sync', testRedirect, ['stderr'], 3, false, true);83test('stdio[*] can be [process.stderr, "pipe"], sync', testRedirect, ['stderr', 'pipe'], 3, false, true);8485const testInheritStdin = async (t, stdioOption, isSync) => {86 const {stdout} = await execa('nested-multiple-stdin.js', [JSON.stringify(stdioOption), `${isSync}`], {input: foobarString});87 t.is(stdout, `${foobarString}${foobarString}`);88};8990test('stdin can be ["inherit", "pipe"]', testInheritStdin, ['inherit', 'pipe'], false);91test('stdin can be [0, "pipe"]', testInheritStdin, [0, 'pipe'], false);92test('stdin can be [process.stdin, "pipe"]', testInheritStdin, ['stdin', 'pipe'], false);93test.serial('stdin can be ["inherit", "pipe"], sync', testInheritStdin, ['inherit', 'pipe'], true);94test.serial('stdin can be [0, "pipe"], sync', testInheritStdin, [0, 'pipe'], true);95test.serial('stdin can be [process.stdin, "pipe"], sync', testInheritStdin, ['stdin', 'pipe'], true);9697// eslint-disable-next-line max-params98const testInheritStdioOutput = async (t, fdNumber, outerFdNumber, stdioOption, isSync, encoding) => {99 const {stdio} = await execa('nested-multiple-stdio-output.js', [JSON.stringify(stdioOption), `${fdNumber}`, `${outerFdNumber}`, `${isSync}`, encoding], fullStdio);100 t.is(stdio[fdNumber], foobarString);101 t.is(stdio[outerFdNumber], `nested ${foobarString}`);102};103104test('stdout can be ["inherit", "pipe"]', testInheritStdioOutput, 1, 2, ['inherit', 'pipe'], false, 'utf8');105test('stdout can be [1, "pipe"]', testInheritStdioOutput, 1, 2, [1, 'pipe'], false, 'utf8');106test('stdout can be [process.stdout, "pipe"]', testInheritStdioOutput, 1, 2, ['stdout', 'pipe'], false, 'utf8');107test('stderr can be ["inherit", "pipe"]', testInheritStdioOutput, 2, 1, ['inherit', 'pipe'], false, 'utf8');108test('stderr can be [2, "pipe"]', testInheritStdioOutput, 2, 1, [2, 'pipe'], false, 'utf8');109test('stderr can be [process.stderr, "pipe"]', testInheritStdioOutput, 2, 1, ['stderr', 'pipe'], false, 'utf8');110test('stdout can be ["inherit", "pipe"], encoding "buffer"', testInheritStdioOutput, 1, 2, ['inherit', 'pipe'], false, 'buffer');111test('stdout can be [1, "pipe"], encoding "buffer"', testInheritStdioOutput, 1, 2, [1, 'pipe'], false, 'buffer');112test('stdout can be [process.stdout, "pipe"], encoding "buffer"', testInheritStdioOutput, 1, 2, ['stdout', 'pipe'], false, 'buffer');113test('stderr can be ["inherit", "pipe"], encoding "buffer"', testInheritStdioOutput, 2, 1, ['inherit', 'pipe'], false, 'buffer');114test('stderr can be [2, "pipe"], encoding "buffer"', testInheritStdioOutput, 2, 1, [2, 'pipe'], false, 'buffer');115test('stderr can be [process.stderr, "pipe"], encoding "buffer"', testInheritStdioOutput, 2, 1, ['stderr', 'pipe'], false, 'buffer');116test('stdout can be ["inherit", "pipe"], sync', testInheritStdioOutput, 1, 2, ['inherit', 'pipe'], true, 'utf8');117test('stdout can be [1, "pipe"], sync', testInheritStdioOutput, 1, 2, [1, 'pipe'], true, 'utf8');118test('stdout can be [process.stdout, "pipe"], sync', testInheritStdioOutput, 1, 2, ['stdout', 'pipe'], true, 'utf8');119test('stderr can be ["inherit", "pipe"], sync', testInheritStdioOutput, 2, 1, ['inherit', 'pipe'], true, 'utf8');120test('stderr can be [2, "pipe"], sync', testInheritStdioOutput, 2, 1, [2, 'pipe'], true, 'utf8');121test('stderr can be [process.stderr, "pipe"], sync', testInheritStdioOutput, 2, 1, ['stderr', 'pipe'], true, 'utf8');122test('stdio[*] output can be ["inherit", "pipe"], sync', testInheritStdioOutput, 3, 1, ['inherit', 'pipe'], true, 'utf8');123test('stdio[*] output can be [3, "pipe"], sync', testInheritStdioOutput, 3, 1, [3, 'pipe'], true, 'utf8');124test('stdout can be ["inherit", "pipe"], encoding "buffer", sync', testInheritStdioOutput, 1, 2, ['inherit', 'pipe'], true, 'buffer');125test('stdout can be [1, "pipe"], encoding "buffer", sync', testInheritStdioOutput, 1, 2, [1, 'pipe'], true, 'buffer');126test('stdout can be [process.stdout, "pipe"], encoding "buffer", sync', testInheritStdioOutput, 1, 2, ['stdout', 'pipe'], true, 'buffer');127test('stderr can be ["inherit", "pipe"], encoding "buffer", sync', testInheritStdioOutput, 2, 1, ['inherit', 'pipe'], true, 'buffer');128test('stderr can be [2, "pipe"], encoding "buffer", sync', testInheritStdioOutput, 2, 1, [2, 'pipe'], true, 'buffer');129test('stderr can be [process.stderr, "pipe"], encoding "buffer", sync', testInheritStdioOutput, 2, 1, ['stderr', 'pipe'], true, 'buffer');130test('stdio[*] output can be ["inherit", "pipe"], encoding "buffer", sync', testInheritStdioOutput, 3, 1, ['inherit', 'pipe'], true, 'buffer');131test('stdio[*] output can be [3, "pipe"], encoding "buffer", sync', testInheritStdioOutput, 3, 1, [3, 'pipe'], true, 'buffer');132133const testFd3InheritOutput = async (t, stdioOption, execaMethod) => {134 const {stdio} = await execaMethod('noop-fd.js', ['3', foobarString], getStdio(3, stdioOption), fullStdio);135 t.is(stdio[3], foobarString);136};137138test('stdio[*] output can use "inherit"', testFd3InheritOutput, 'inherit', parentExecaAsync);139test('stdio[*] output can use ["inherit"]', testFd3InheritOutput, ['inherit'], parentExecaAsync);140test('stdio[*] output can use "inherit", sync', testFd3InheritOutput, 'inherit', parentExecaSync);141test('stdio[*] output can use ["inherit"], sync', testFd3InheritOutput, ['inherit'], parentExecaSync);142143const testInheritNoBuffer = async (t, stdioOption, execaMethod) => {144 const filePath = tempfile();145 await execaMethod('nested-write.js', [filePath, foobarString], {stdin: stdioOption, buffer: false}, {input: foobarString});146 t.is(await readFile(filePath, 'utf8'), `${foobarString} ${foobarString}`);147 await rm(filePath);148};149150test('stdin can be ["inherit", "pipe"], buffer: false', testInheritNoBuffer, ['inherit', 'pipe'], parentExecaAsync);151test('stdin can be [0, "pipe"], buffer: false', testInheritNoBuffer, [0, 'pipe'], parentExecaAsync);152test.serial('stdin can be ["inherit", "pipe"], buffer: false, sync', testInheritNoBuffer, ['inherit', 'pipe'], parentExecaSync);153test.serial('stdin can be [0, "pipe"], buffer: false, sync', testInheritNoBuffer, [0, 'pipe'], parentExecaSync);154155if (isLinux) {156 const testOverflowStream = async (t, fdNumber, stdioOption, execaMethod) => {157 const {stdout} = await execaMethod('empty.js', getStdio(fdNumber, stdioOption), fullStdio);158 t.is(stdout, '');159 };160161 test('stdin can use 4+', testOverflowStream, 0, 4, parentExecaAsync);162 test('stdin can use [4+]', testOverflowStream, 0, [4], parentExecaAsync);163 test('stdout can use 4+', testOverflowStream, 1, 4, parentExecaAsync);164 test('stdout can use [4+]', testOverflowStream, 1, [4], parentExecaAsync);165 test('stderr can use 4+', testOverflowStream, 2, 4, parentExecaAsync);166 test('stderr can use [4+]', testOverflowStream, 2, [4], parentExecaAsync);167 test('stdio[*] can use 4+', testOverflowStream, 3, 4, parentExecaAsync);168 test('stdio[*] can use [4+]', testOverflowStream, 3, [4], parentExecaAsync);169 test('stdin can use 4+, sync', testOverflowStream, 0, 4, parentExecaSync);170 test('stdin can use [4+], sync', testOverflowStream, 0, [4], parentExecaSync);171 test('stdout can use 4+, sync', testOverflowStream, 1, 4, parentExecaSync);172 test('stdout can use [4+], sync', testOverflowStream, 1, [4], parentExecaSync);173 test('stderr can use 4+, sync', testOverflowStream, 2, 4, parentExecaSync);174 test('stderr can use [4+], sync', testOverflowStream, 2, [4], parentExecaSync);175 test('stdio[*] can use 4+, sync', testOverflowStream, 3, 4, parentExecaSync);176 test('stdio[*] can use [4+], sync', testOverflowStream, 3, [4], parentExecaSync);177}178179const testOverflowStreamArray = (t, fdNumber, stdioOption) => {180 t.throws(() => {181 execa('empty.js', getStdio(fdNumber, stdioOption));182 }, {message: /no such standard stream/});183};184185test('stdin cannot use 4+ and another value', testOverflowStreamArray, 0, [4, 'pipe']);186test('stdout cannot use 4+ and another value', testOverflowStreamArray, 1, [4, 'pipe']);187test('stderr cannot use 4+ and another value', testOverflowStreamArray, 2, [4, 'pipe']);188test('stdio[*] cannot use 4+ and another value', testOverflowStreamArray, 3, [4, 'pipe']);189test('stdio[*] cannot use "inherit" and another value', testOverflowStreamArray, 3, ['inherit', 'pipe']);190191const getInvalidFdCode = () => {192 if (isLinux) {193 return 'EINVAL';194 }195196 return isWindows ? 'EBADF' : 'ENXIO';197};198199const testOverflowStreamArraySync = (t, fdNumber) => {200 t.throws(() => {201 execaSync('noop-fd.js', [fdNumber, foobarString], getStdio(fdNumber, [4, 'pipe']));202 }, {code: getInvalidFdCode()});203};204205test('stdout cannot use 4+ and another value, sync', testOverflowStreamArraySync, 1);206test('stderr cannot use 4+ and another value, sync', testOverflowStreamArraySync, 2);207test('stdio[*] cannot use 4+ and another value, sync', testOverflowStreamArraySync, 3);208209test('stdin can use ["inherit", "pipe"] in a TTY', async t => {210 const stdioOption = [['inherit', 'pipe'], 'inherit', 'pipe'];211 const {stdout} = await execa('nested-sync-tty.js', [JSON.stringify({stdio: stdioOption}), 'false', 'stdin-fd.js', '0'], {input: foobarString});212 t.is(stdout, foobarString);213});214215const testNoTtyInput = async (t, fdNumber, optionName) => {216 const stdioOption = ['pipe', 'inherit', 'pipe'];217 stdioOption[fdNumber] = [[''], 'inherit', 'pipe'];218 const {message} = await t.throwsAsync(execa('nested-sync-tty.js', [JSON.stringify({stdio: stdioOption}), 'true', 'stdin-fd.js', `${fdNumber}`], fullStdio));219 t.true(message.includes(`The \`${optionName}: 'inherit'\` option is invalid: it cannot be a TTY`));220};221222test('stdin cannot use ["inherit", "pipe"] in a TTY, sync', testNoTtyInput, 0, 'stdin');223test('stdio[*] input cannot use ["inherit", "pipe"] in a TTY, sync', testNoTtyInput, 3, 'stdio[3]');224225const testTtyOutput = async (t, fdNumber, isSync) => {226 const {stdio} = await execa('nested-sync-tty.js', [JSON.stringify(getStdio(fdNumber, ['inherit', 'pipe'])), `${isSync}`, 'noop-fd.js', `${fdNumber}`, foobarString], fullStdio);227 t.is(stdio[fdNumber], foobarString);228};229230test('stdout can use ["inherit", "pipe"] in a TTY', testTtyOutput, 1, false);231test('stderr can use ["inherit", "pipe"] in a TTY', testTtyOutput, 2, false);232test('stdout can use ["inherit", "pipe"] in a TTY, sync', testTtyOutput, 1, true);233test('stderr can use ["inherit", "pipe"] in a TTY, sync', testTtyOutput, 2, true);234test('stdio[*] output can use ["inherit", "pipe"] in a TTY, sync', testTtyOutput, 3, true);
added:test/stdio/node-stream-custom.js+158 added
1import {createReadStream, createWriteStream} from 'node:fs';2import {readFile, writeFile, rm} from 'node:fs/promises';3import {Writable, PassThrough} from 'node:stream';4import {text} from 'node:stream/consumers';5import {setImmediate} from 'node:timers/promises';6import {callbackify} from 'node:util';7import test from 'ava';8import tempfile from 'tempfile';9import {execa, execaSync} from '../../index.js';10import {setFixtureDir} from '../helpers/fixtures-dir.js';11import {getStdio} from '../helpers/stdio.js';12import {foobarString} from '../helpers/input.js';13import {noopReadable, noopWritable} from '../helpers/stream.js';1415setFixtureDir();1617const testLazyFileReadable = async (t, fdNumber) => {18 const filePath = tempfile();19 await writeFile(filePath, 'foobar');20 const stream = createReadStream(filePath);2122 const {stdout} = await execa('stdin-fd.js', [`${fdNumber}`], getStdio(fdNumber, [stream, 'pipe']));23 t.is(stdout, 'foobar');2425 await rm(filePath);26};2728test('stdin can be [Readable, "pipe"] without a file descriptor', testLazyFileReadable, 0);29test('stdio[*] can be [Readable, "pipe"] without a file descriptor', testLazyFileReadable, 3);3031const testLazyFileReadableSync = (t, fdNumber) => {32 t.throws(() => {33 execaSync('stdin-fd.js', [`${fdNumber}`], getStdio(fdNumber, [noopReadable(), 'pipe']));34 }, {message: /cannot both be an array and include a stream/});35};3637test('stdin cannot be [Readable, "pipe"] without a file descriptor, sync', testLazyFileReadableSync, 0);38test('stdio[*] cannot be [Readable, "pipe"] without a file descriptor, sync', testLazyFileReadableSync, 3);3940const testLazyFileWritable = async (t, fdNumber) => {41 const filePath = tempfile();42 const stream = createWriteStream(filePath);4344 await execa('noop-fd.js', [`${fdNumber}`, 'foobar'], getStdio(fdNumber, [stream, 'pipe']));45 t.is(await readFile(filePath, 'utf8'), 'foobar');4647 await rm(filePath);48};4950test('stdout can be [Writable, "pipe"] without a file descriptor', testLazyFileWritable, 1);51test('stderr can be [Writable, "pipe"] without a file descriptor', testLazyFileWritable, 2);52test('stdio[*] can be [Writable, "pipe"] without a file descriptor', testLazyFileWritable, 3);5354const testLazyFileWritableSync = (t, fdNumber) => {55 t.throws(() => {56 execaSync('noop-fd.js', [`${fdNumber}`], getStdio(fdNumber, [noopWritable(), 'pipe']));57 }, {message: /cannot both be an array and include a stream/});58};5960test('stdout cannot be [Writable, "pipe"] without a file descriptor, sync', testLazyFileWritableSync, 1);61test('stderr cannot be [Writable, "pipe"] without a file descriptor, sync', testLazyFileWritableSync, 2);62test('stdio[*] cannot be [Writable, "pipe"] without a file descriptor, sync', testLazyFileWritableSync, 3);6364test('Waits for custom streams destroy on subprocess errors', async t => {65 let waitedForDestroy = false;66 const stream = new Writable({67 destroy: callbackify(async error => {68 await setImmediate();69 waitedForDestroy = true;70 return error;71 }),72 });73 const {timedOut} = await t.throwsAsync(execa('forever.js', {stdout: [stream, 'pipe'], timeout: 1}));74 t.true(timedOut);75 t.true(waitedForDestroy);76});7778test('Handles custom streams destroy errors on subprocess success', async t => {79 const cause = new Error('test');80 const stream = new Writable({81 destroy(destroyError, done) {82 done(destroyError ?? cause);83 },84 });85 const error = await t.throwsAsync(execa('empty.js', {stdout: [stream, 'pipe']}));86 t.is(error.cause, cause);87});8889const testStreamEarlyExit = async (t, stream, streamName) => {90 await t.throwsAsync(execa('noop.js', {[streamName]: [stream, 'pipe'], uid: -1}));91 t.true(stream.destroyed);92};9394test('Input streams are canceled on early subprocess exit', testStreamEarlyExit, noopReadable(), 'stdin');95test('Output streams are canceled on early subprocess exit', testStreamEarlyExit, noopWritable(), 'stdout');9697const testInputDuplexStream = async (t, fdNumber) => {98 const stream = new PassThrough();99 stream.end(foobarString);100 const {stdout} = await execa('stdin-fd.js', [`${fdNumber}`], getStdio(fdNumber, [stream, new Uint8Array()]));101 t.is(stdout, foobarString);102};103104test('Can pass Duplex streams to stdin', testInputDuplexStream, 0);105test('Can pass Duplex streams to input stdio[*]', testInputDuplexStream, 3);106107const testOutputDuplexStream = async (t, fdNumber) => {108 const stream = new PassThrough();109 const [output] = await Promise.all([110 text(stream),111 execa('noop-fd.js', [`${fdNumber}`], getStdio(fdNumber, [stream, 'pipe'])),112 ]);113 t.is(output, foobarString);114};115116test('Can pass Duplex streams to stdout', testOutputDuplexStream, 1);117test('Can pass Duplex streams to stderr', testOutputDuplexStream, 2);118test('Can pass Duplex streams to output stdio[*]', testOutputDuplexStream, 3);119120const testInputStreamAbort = async (t, fdNumber) => {121 const stream = new PassThrough();122 stream.destroy();123124 const subprocess = execa('stdin-fd.js', [`${fdNumber}`], getStdio(fdNumber, [stream, new Uint8Array()]));125 await subprocess;126 t.true(subprocess.stdio[fdNumber].writableEnded);127};128129test('subprocess.stdin is ended when an input stream aborts', testInputStreamAbort, 0);130test('subprocess.stdio[*] is ended when an input stream aborts', testInputStreamAbort, 3);131132const testInputStreamError = async (t, fdNumber) => {133 const stream = new PassThrough();134 const cause = new Error(foobarString);135 stream.destroy(cause);136137 const subprocess = execa('stdin-fd.js', [`${fdNumber}`], getStdio(fdNumber, [stream, new Uint8Array()]));138 t.like(await t.throwsAsync(subprocess), {cause});139 t.true(subprocess.stdio[fdNumber].writableEnded);140};141142test('subprocess.stdin is ended when an input stream errors', testInputStreamError, 0);143test('subprocess.stdio[*] is ended when an input stream errors', testInputStreamError, 3);144145const testOutputStreamError = async (t, fdNumber) => {146 const stream = new PassThrough();147 const cause = new Error(foobarString);148 stream.destroy(cause);149150 const subprocess = execa('noop-fd.js', [`${fdNumber}`], getStdio(fdNumber, [stream, 'pipe']));151 t.like(await t.throwsAsync(subprocess), {cause});152 t.true(subprocess.stdio[fdNumber].readableAborted);153 t.is(subprocess.stdio[fdNumber].errored, null);154};155156test('subprocess.stdout is aborted when an output stream errors', testOutputStreamError, 1);157test('subprocess.stderr is aborted when an output stream errors', testOutputStreamError, 2);158test('subprocess.stdio[*] is aborted when an output stream errors', testOutputStreamError, 3);
added:test/stdio/node-stream-native.js+180 added
1import {once} from 'node:events';2import {createReadStream, createWriteStream} from 'node:fs';3import {readFile, writeFile, rm} from 'node:fs/promises';4import test from 'ava';5import tempfile from 'tempfile';6import {execa, execaSync} from '../../index.js';7import {setFixtureDir} from '../helpers/fixtures-dir.js';8import {getStdio} from '../helpers/stdio.js';9import {foobarString} from '../helpers/input.js';10import {noopReadable, noopWritable, noopDuplex, simpleReadable} from '../helpers/stream.js';1112setFixtureDir();1314const testNoFileStreamSync = async (t, fdNumber, stream) => {15 t.throws(() => {16 execaSync('empty.js', getStdio(fdNumber, stream));17 }, {code: 'ERR_INVALID_ARG_VALUE'});18};1920test('stdin cannot be a Node.js Readable without a file descriptor - sync', testNoFileStreamSync, 0, noopReadable());21test('stdin cannot be a Node.js Duplex without a file descriptor - sync', testNoFileStreamSync, 0, noopDuplex());22test('stdout cannot be a Node.js Writable without a file descriptor - sync', testNoFileStreamSync, 1, noopWritable());23test('stdout cannot be a Node.js Duplex without a file descriptor - sync', testNoFileStreamSync, 1, noopDuplex());24test('stderr cannot be a Node.js Writable without a file descriptor - sync', testNoFileStreamSync, 2, noopWritable());25test('stderr cannot be a Node.js Duplex without a file descriptor - sync', testNoFileStreamSync, 2, noopDuplex());26test('stdio[*] cannot be a Node.js Readable without a file descriptor - sync', testNoFileStreamSync, 3, noopReadable());27test('stdio[*] cannot be a Node.js Writable without a file descriptor - sync', testNoFileStreamSync, 3, noopWritable());28test('stdio[*] cannot be a Node.js Duplex without a file descriptor - sync', testNoFileStreamSync, 3, noopDuplex());2930test('input can be a Node.js Readable without a file descriptor', async t => {31 const {stdout} = await execa('stdin.js', {input: simpleReadable()});32 t.is(stdout, foobarString);33});3435test('input cannot be a Node.js Readable without a file descriptor - sync', t => {36 t.throws(() => {37 execaSync('empty.js', {input: simpleReadable()});38 }, {message: 'The `input` option cannot be a Node.js stream with synchronous methods.'});39});4041const testNoFileStream = async (t, fdNumber, stream) => {42 await t.throwsAsync(execa('empty.js', getStdio(fdNumber, stream)), {code: 'ERR_INVALID_ARG_VALUE'});43};4445test('stdin cannot be a Node.js Readable without a file descriptor', testNoFileStream, 0, noopReadable());46test('stdin cannot be a Node.js Duplex without a file descriptor', testNoFileStream, 0, noopDuplex());47test('stdout cannot be a Node.js Writable without a file descriptor', testNoFileStream, 1, noopWritable());48test('stdout cannot be a Node.js Duplex without a file descriptor', testNoFileStream, 1, noopDuplex());49test('stderr cannot be a Node.js Writable without a file descriptor', testNoFileStream, 2, noopWritable());50test('stderr cannot be a Node.js Duplex without a file descriptor', testNoFileStream, 2, noopDuplex());51test('stdio[*] cannot be a Node.js Readable without a file descriptor', testNoFileStream, 3, noopReadable());52test('stdio[*] cannot be a Node.js Writable without a file descriptor', testNoFileStream, 3, noopWritable());53test('stdio[*] cannot be a Node.js Duplex without a file descriptor', testNoFileStream, 3, noopDuplex());5455const createFileReadStream = async () => {56 const filePath = tempfile();57 await writeFile(filePath, 'foobar');58 const stream = createReadStream(filePath);59 await once(stream, 'open');60 return {stream, filePath};61};6263const createFileWriteStream = async () => {64 const filePath = tempfile();65 const stream = createWriteStream(filePath);66 await once(stream, 'open');67 return {stream, filePath};68};6970const assertFileStreamError = async (t, subprocess, stream, filePath) => {71 const cause = new Error('test');72 stream.destroy(cause);7374 const error = await t.throwsAsync(subprocess);75 t.is(error.cause, cause);76 t.is(error.exitCode, 0);77 t.is(error.signal, undefined);7879 await rm(filePath);80};8182const testFileReadable = async (t, fdNumber, execaMethod) => {83 const {stream, filePath} = await createFileReadStream();8485 const fdNumberString = fdNumber === 'input' ? '0' : `${fdNumber}`;86 const {stdout} = await execaMethod('stdin-fd.js', [fdNumberString], getStdio(fdNumber, stream));87 t.is(stdout, 'foobar');8889 await rm(filePath);90};9192test('input can be a Node.js Readable with a file descriptor', testFileReadable, 'input', execa);93test('stdin can be a Node.js Readable with a file descriptor', testFileReadable, 0, execa);94test('stdio[*] can be a Node.js Readable with a file descriptor', testFileReadable, 3, execa);95test('stdin can be a Node.js Readable with a file descriptor - sync', testFileReadable, 0, execaSync);96test('stdio[*] can be a Node.js Readable with a file descriptor - sync', testFileReadable, 3, execaSync);9798const testFileReadableError = async (t, fdNumber) => {99 const {stream, filePath} = await createFileReadStream();100101 const fdNumberString = fdNumber === 'input' ? '0' : `${fdNumber}`;102 const subprocess = execa('stdin-fd.js', [fdNumberString], getStdio(fdNumber, stream));103104 await assertFileStreamError(t, subprocess, stream, filePath);105};106107test.serial('input handles errors from a Node.js Readable with a file descriptor', testFileReadableError, 'input');108test.serial('stdin handles errors from a Node.js Readable with a file descriptor', testFileReadableError, 0);109test.serial('stdio[*] handles errors from a Node.js Readable with a file descriptor', testFileReadableError, 3);110111const testFileReadableOpen = async (t, fdNumber, useSingle, execaMethod) => {112 const {stream, filePath} = await createFileReadStream();113 t.deepEqual(stream.eventNames(), []);114115 const stdioOption = useSingle ? stream : [stream, 'pipe'];116 await execaMethod('empty.js', getStdio(fdNumber, stdioOption));117118 t.is(stream.readable, useSingle && fdNumber !== 'input');119 t.deepEqual(stream.eventNames(), []);120121 await rm(filePath);122};123124test('input closes a Node.js Readable with a file descriptor', testFileReadableOpen, 'input', true, execa);125test('stdin leaves open a single Node.js Readable with a file descriptor', testFileReadableOpen, 0, true, execa);126test('stdin closes a combined Node.js Readable with a file descriptor', testFileReadableOpen, 0, false, execa);127test('stdio[*] leaves open a single Node.js Readable with a file descriptor', testFileReadableOpen, 3, true, execa);128test('stdin leaves open a single Node.js Readable with a file descriptor - sync', testFileReadableOpen, 0, true, execaSync);129test('stdio[*] leaves open a single Node.js Readable with a file descriptor - sync', testFileReadableOpen, 3, true, execaSync);130131const testFileWritable = async (t, fdNumber, execaMethod) => {132 const {stream, filePath} = await createFileWriteStream();133134 await execaMethod('noop-fd.js', [`${fdNumber}`, 'foobar'], getStdio(fdNumber, stream));135 t.is(await readFile(filePath, 'utf8'), 'foobar');136137 await rm(filePath);138};139140test('stdout can be a Node.js Writable with a file descriptor', testFileWritable, 1, execa);141test('stderr can be a Node.js Writable with a file descriptor', testFileWritable, 2, execa);142test('stdio[*] can be a Node.js Writable with a file descriptor', testFileWritable, 3, execa);143test('stdout can be a Node.js Writable with a file descriptor - sync', testFileWritable, 1, execaSync);144test('stderr can be a Node.js Writable with a file descriptor - sync', testFileWritable, 2, execaSync);145test('stdio[*] can be a Node.js Writable with a file descriptor - sync', testFileWritable, 3, execaSync);146147const testFileWritableError = async (t, fdNumber) => {148 const {stream, filePath} = await createFileWriteStream();149150 const subprocess = execa('noop-fd.js', [`${fdNumber}`, foobarString], getStdio(fdNumber, stream));151152 await assertFileStreamError(t, subprocess, stream, filePath);153};154155test.serial('stdout handles errors from a Node.js Writable with a file descriptor', testFileWritableError, 1);156test.serial('stderr handles errors from a Node.js Writable with a file descriptor', testFileWritableError, 2);157test.serial('stdio[*] handles errors from a Node.js Writable with a file descriptor', testFileWritableError, 3);158159const testFileWritableOpen = async (t, fdNumber, useSingle, execaMethod) => {160 const {stream, filePath} = await createFileWriteStream();161 t.deepEqual(stream.eventNames(), []);162163 const stdioOption = useSingle ? stream : [stream, 'pipe'];164 await execaMethod('empty.js', getStdio(fdNumber, stdioOption));165166 t.is(stream.writable, useSingle);167 t.deepEqual(stream.eventNames(), []);168169 await rm(filePath);170};171172test('stdout leaves open a single Node.js Writable with a file descriptor', testFileWritableOpen, 1, true, execa);173test('stdout closes a combined Node.js Writable with a file descriptor', testFileWritableOpen, 1, false, execa);174test('stderr leaves open a single Node.js Writable with a file descriptor', testFileWritableOpen, 2, true, execa);175test('stderr closes a combined Node.js Writable with a file descriptor', testFileWritableOpen, 2, false, execa);176test('stdio[*] leaves open a single Node.js Writable with a file descriptor', testFileWritableOpen, 3, true, execa);177test('stdio[*] closes a combined Node.js Writable with a file descriptor', testFileWritableOpen, 3, false, execa);178test('stdout leaves open a single Node.js Writable with a file descriptor - sync', testFileWritableOpen, 1, true, execaSync);179test('stderr leaves open a single Node.js Writable with a file descriptor - sync', testFileWritableOpen, 2, true, execaSync);180test('stdio[*] leaves open a single Node.js Writable with a file descriptor - sync', testFileWritableOpen, 3, true, execaSync);
deleted:test/stdio/node-stream.js-327 removed
1import {once} from 'node:events';2import {createReadStream, createWriteStream} from 'node:fs';3import {readFile, writeFile, rm} from 'node:fs/promises';4import {Writable, PassThrough} from 'node:stream';5import {text} from 'node:stream/consumers';6import {setImmediate} from 'node:timers/promises';7import {callbackify} from 'node:util';8import test from 'ava';9import tempfile from 'tempfile';10import {execa, execaSync} from '../../index.js';11import {setFixtureDir} from '../helpers/fixtures-dir.js';12import {getStdio} from '../helpers/stdio.js';13import {foobarString} from '../helpers/input.js';14import {noopReadable, noopWritable, noopDuplex, simpleReadable} from '../helpers/stream.js';1516setFixtureDir();1718const testNoFileStreamSync = async (t, fdNumber, stream) => {19 t.throws(() => {20 execaSync('empty.js', getStdio(fdNumber, stream));21 }, {code: 'ERR_INVALID_ARG_VALUE'});22};2324test('stdin cannot be a Node.js Readable without a file descriptor - sync', testNoFileStreamSync, 0, noopReadable());25test('stdin cannot be a Node.js Duplex without a file descriptor - sync', testNoFileStreamSync, 0, noopDuplex());26test('stdout cannot be a Node.js Writable without a file descriptor - sync', testNoFileStreamSync, 1, noopWritable());27test('stdout cannot be a Node.js Duplex without a file descriptor - sync', testNoFileStreamSync, 1, noopDuplex());28test('stderr cannot be a Node.js Writable without a file descriptor - sync', testNoFileStreamSync, 2, noopWritable());29test('stderr cannot be a Node.js Duplex without a file descriptor - sync', testNoFileStreamSync, 2, noopDuplex());30test('stdio[*] cannot be a Node.js Readable without a file descriptor - sync', testNoFileStreamSync, 3, noopReadable());31test('stdio[*] cannot be a Node.js Writable without a file descriptor - sync', testNoFileStreamSync, 3, noopWritable());32test('stdio[*] cannot be a Node.js Duplex without a file descriptor - sync', testNoFileStreamSync, 3, noopDuplex());3334test('input can be a Node.js Readable without a file descriptor', async t => {35 const {stdout} = await execa('stdin.js', {input: simpleReadable()});36 t.is(stdout, foobarString);37});3839test('input cannot be a Node.js Readable without a file descriptor - sync', t => {40 t.throws(() => {41 execaSync('empty.js', {input: simpleReadable()});42 }, {message: 'The `input` option cannot be a Node.js stream with synchronous methods.'});43});4445const testNoFileStream = async (t, fdNumber, stream) => {46 await t.throwsAsync(execa('empty.js', getStdio(fdNumber, stream)), {code: 'ERR_INVALID_ARG_VALUE'});47};4849test('stdin cannot be a Node.js Readable without a file descriptor', testNoFileStream, 0, noopReadable());50test('stdin cannot be a Node.js Duplex without a file descriptor', testNoFileStream, 0, noopDuplex());51test('stdout cannot be a Node.js Writable without a file descriptor', testNoFileStream, 1, noopWritable());52test('stdout cannot be a Node.js Duplex without a file descriptor', testNoFileStream, 1, noopDuplex());53test('stderr cannot be a Node.js Writable without a file descriptor', testNoFileStream, 2, noopWritable());54test('stderr cannot be a Node.js Duplex without a file descriptor', testNoFileStream, 2, noopDuplex());55test('stdio[*] cannot be a Node.js Readable without a file descriptor', testNoFileStream, 3, noopReadable());56test('stdio[*] cannot be a Node.js Writable without a file descriptor', testNoFileStream, 3, noopWritable());57test('stdio[*] cannot be a Node.js Duplex without a file descriptor', testNoFileStream, 3, noopDuplex());5859const createFileReadStream = async () => {60 const filePath = tempfile();61 await writeFile(filePath, 'foobar');62 const stream = createReadStream(filePath);63 await once(stream, 'open');64 return {stream, filePath};65};6667const createFileWriteStream = async () => {68 const filePath = tempfile();69 const stream = createWriteStream(filePath);70 await once(stream, 'open');71 return {stream, filePath};72};7374const assertFileStreamError = async (t, subprocess, stream, filePath) => {75 const cause = new Error('test');76 stream.destroy(cause);7778 const error = await t.throwsAsync(subprocess);79 t.is(error.cause, cause);80 t.is(error.exitCode, 0);81 t.is(error.signal, undefined);8283 await rm(filePath);84};8586const testFileReadable = async (t, fdNumber, execaMethod) => {87 const {stream, filePath} = await createFileReadStream();8889 const fdNumberString = fdNumber === 'input' ? '0' : `${fdNumber}`;90 const {stdout} = await execaMethod('stdin-fd.js', [fdNumberString], getStdio(fdNumber, stream));91 t.is(stdout, 'foobar');9293 await rm(filePath);94};9596test('input can be a Node.js Readable with a file descriptor', testFileReadable, 'input', execa);97test('stdin can be a Node.js Readable with a file descriptor', testFileReadable, 0, execa);98test('stdio[*] can be a Node.js Readable with a file descriptor', testFileReadable, 3, execa);99test('stdin can be a Node.js Readable with a file descriptor - sync', testFileReadable, 0, execaSync);100test('stdio[*] can be a Node.js Readable with a file descriptor - sync', testFileReadable, 3, execaSync);101102const testFileReadableError = async (t, fdNumber) => {103 const {stream, filePath} = await createFileReadStream();104105 const fdNumberString = fdNumber === 'input' ? '0' : `${fdNumber}`;106 const subprocess = execa('stdin-fd.js', [fdNumberString], getStdio(fdNumber, stream));107108 await assertFileStreamError(t, subprocess, stream, filePath);109};110111test.serial('input handles errors from a Node.js Readable with a file descriptor', testFileReadableError, 'input');112test.serial('stdin handles errors from a Node.js Readable with a file descriptor', testFileReadableError, 0);113test.serial('stdio[*] handles errors from a Node.js Readable with a file descriptor', testFileReadableError, 3);114115const testFileReadableOpen = async (t, fdNumber, useSingle, execaMethod) => {116 const {stream, filePath} = await createFileReadStream();117 t.deepEqual(stream.eventNames(), []);118119 const stdioOption = useSingle ? stream : [stream, 'pipe'];120 await execaMethod('empty.js', getStdio(fdNumber, stdioOption));121122 t.is(stream.readable, useSingle && fdNumber !== 'input');123 t.deepEqual(stream.eventNames(), []);124125 await rm(filePath);126};127128test('input closes a Node.js Readable with a file descriptor', testFileReadableOpen, 'input', true, execa);129test('stdin leaves open a single Node.js Readable with a file descriptor', testFileReadableOpen, 0, true, execa);130test('stdin closes a combined Node.js Readable with a file descriptor', testFileReadableOpen, 0, false, execa);131test('stdio[*] leaves open a single Node.js Readable with a file descriptor', testFileReadableOpen, 3, true, execa);132test('stdin leaves open a single Node.js Readable with a file descriptor - sync', testFileReadableOpen, 0, true, execaSync);133test('stdio[*] leaves open a single Node.js Readable with a file descriptor - sync', testFileReadableOpen, 3, true, execaSync);134135const testFileWritable = async (t, fdNumber, execaMethod) => {136 const {stream, filePath} = await createFileWriteStream();137138 await execaMethod('noop-fd.js', [`${fdNumber}`, 'foobar'], getStdio(fdNumber, stream));139 t.is(await readFile(filePath, 'utf8'), 'foobar');140141 await rm(filePath);142};143144test('stdout can be a Node.js Writable with a file descriptor', testFileWritable, 1, execa);145test('stderr can be a Node.js Writable with a file descriptor', testFileWritable, 2, execa);146test('stdio[*] can be a Node.js Writable with a file descriptor', testFileWritable, 3, execa);147test('stdout can be a Node.js Writable with a file descriptor - sync', testFileWritable, 1, execaSync);148test('stderr can be a Node.js Writable with a file descriptor - sync', testFileWritable, 2, execaSync);149test('stdio[*] can be a Node.js Writable with a file descriptor - sync', testFileWritable, 3, execaSync);150151const testFileWritableError = async (t, fdNumber) => {152 const {stream, filePath} = await createFileWriteStream();153154 const subprocess = execa('noop-fd.js', [`${fdNumber}`, foobarString], getStdio(fdNumber, stream));155156 await assertFileStreamError(t, subprocess, stream, filePath);157};158159test.serial('stdout handles errors from a Node.js Writable with a file descriptor', testFileWritableError, 1);160test.serial('stderr handles errors from a Node.js Writable with a file descriptor', testFileWritableError, 2);161test.serial('stdio[*] handles errors from a Node.js Writable with a file descriptor', testFileWritableError, 3);162163const testFileWritableOpen = async (t, fdNumber, useSingle, execaMethod) => {164 const {stream, filePath} = await createFileWriteStream();165 t.deepEqual(stream.eventNames(), []);166167 const stdioOption = useSingle ? stream : [stream, 'pipe'];168 await execaMethod('empty.js', getStdio(fdNumber, stdioOption));169170 t.is(stream.writable, useSingle);171 t.deepEqual(stream.eventNames(), []);172173 await rm(filePath);174};175176test('stdout leaves open a single Node.js Writable with a file descriptor', testFileWritableOpen, 1, true, execa);177test('stdout closes a combined Node.js Writable with a file descriptor', testFileWritableOpen, 1, false, execa);178test('stderr leaves open a single Node.js Writable with a file descriptor', testFileWritableOpen, 2, true, execa);179test('stderr closes a combined Node.js Writable with a file descriptor', testFileWritableOpen, 2, false, execa);180test('stdio[*] leaves open a single Node.js Writable with a file descriptor', testFileWritableOpen, 3, true, execa);181test('stdio[*] closes a combined Node.js Writable with a file descriptor', testFileWritableOpen, 3, false, execa);182test('stdout leaves open a single Node.js Writable with a file descriptor - sync', testFileWritableOpen, 1, true, execaSync);183test('stderr leaves open a single Node.js Writable with a file descriptor - sync', testFileWritableOpen, 2, true, execaSync);184test('stdio[*] leaves open a single Node.js Writable with a file descriptor - sync', testFileWritableOpen, 3, true, execaSync);185186const testLazyFileReadable = async (t, fdNumber) => {187 const filePath = tempfile();188 await writeFile(filePath, 'foobar');189 const stream = createReadStream(filePath);190191 const {stdout} = await execa('stdin-fd.js', [`${fdNumber}`], getStdio(fdNumber, [stream, 'pipe']));192 t.is(stdout, 'foobar');193194 await rm(filePath);195};196197test('stdin can be [Readable, "pipe"] without a file descriptor', testLazyFileReadable, 0);198test('stdio[*] can be [Readable, "pipe"] without a file descriptor', testLazyFileReadable, 3);199200const testLazyFileReadableSync = (t, fdNumber) => {201 t.throws(() => {202 execaSync('stdin-fd.js', [`${fdNumber}`], getStdio(fdNumber, [noopReadable(), 'pipe']));203 }, {message: /cannot both be an array and include a stream/});204};205206test('stdin cannot be [Readable, "pipe"] without a file descriptor, sync', testLazyFileReadableSync, 0);207test('stdio[*] cannot be [Readable, "pipe"] without a file descriptor, sync', testLazyFileReadableSync, 3);208209const testLazyFileWritable = async (t, fdNumber) => {210 const filePath = tempfile();211 const stream = createWriteStream(filePath);212213 await execa('noop-fd.js', [`${fdNumber}`, 'foobar'], getStdio(fdNumber, [stream, 'pipe']));214 t.is(await readFile(filePath, 'utf8'), 'foobar');215216 await rm(filePath);217};218219test('stdout can be [Writable, "pipe"] without a file descriptor', testLazyFileWritable, 1);220test('stderr can be [Writable, "pipe"] without a file descriptor', testLazyFileWritable, 2);221test('stdio[*] can be [Writable, "pipe"] without a file descriptor', testLazyFileWritable, 3);222223const testLazyFileWritableSync = (t, fdNumber) => {224 t.throws(() => {225 execaSync('noop-fd.js', [`${fdNumber}`], getStdio(fdNumber, [noopWritable(), 'pipe']));226 }, {message: /cannot both be an array and include a stream/});227};228229test('stdout cannot be [Writable, "pipe"] without a file descriptor, sync', testLazyFileWritableSync, 1);230test('stderr cannot be [Writable, "pipe"] without a file descriptor, sync', testLazyFileWritableSync, 2);231test('stdio[*] cannot be [Writable, "pipe"] without a file descriptor, sync', testLazyFileWritableSync, 3);232233test('Waits for custom streams destroy on subprocess errors', async t => {234 let waitedForDestroy = false;235 const stream = new Writable({236 destroy: callbackify(async error => {237 await setImmediate();238 waitedForDestroy = true;239 return error;240 }),241 });242 const {timedOut} = await t.throwsAsync(execa('forever.js', {stdout: [stream, 'pipe'], timeout: 1}));243 t.true(timedOut);244 t.true(waitedForDestroy);245});246247test('Handles custom streams destroy errors on subprocess success', async t => {248 const cause = new Error('test');249 const stream = new Writable({250 destroy(destroyError, done) {251 done(destroyError ?? cause);252 },253 });254 const error = await t.throwsAsync(execa('empty.js', {stdout: [stream, 'pipe']}));255 t.is(error.cause, cause);256});257258const testStreamEarlyExit = async (t, stream, streamName) => {259 await t.throwsAsync(execa('noop.js', {[streamName]: [stream, 'pipe'], uid: -1}));260 t.true(stream.destroyed);261};262263test('Input streams are canceled on early subprocess exit', testStreamEarlyExit, noopReadable(), 'stdin');264test('Output streams are canceled on early subprocess exit', testStreamEarlyExit, noopWritable(), 'stdout');265266const testInputDuplexStream = async (t, fdNumber) => {267 const stream = new PassThrough();268 stream.end(foobarString);269 const {stdout} = await execa('stdin-fd.js', [`${fdNumber}`], getStdio(fdNumber, [stream, new Uint8Array()]));270 t.is(stdout, foobarString);271};272273test('Can pass Duplex streams to stdin', testInputDuplexStream, 0);274test('Can pass Duplex streams to input stdio[*]', testInputDuplexStream, 3);275276const testOutputDuplexStream = async (t, fdNumber) => {277 const stream = new PassThrough();278 const [output] = await Promise.all([279 text(stream),280 execa('noop-fd.js', [`${fdNumber}`], getStdio(fdNumber, [stream, 'pipe'])),281 ]);282 t.is(output, foobarString);283};284285test('Can pass Duplex streams to stdout', testOutputDuplexStream, 1);286test('Can pass Duplex streams to stderr', testOutputDuplexStream, 2);287test('Can pass Duplex streams to output stdio[*]', testOutputDuplexStream, 3);288289const testInputStreamAbort = async (t, fdNumber) => {290 const stream = new PassThrough();291 stream.destroy();292293 const subprocess = execa('stdin-fd.js', [`${fdNumber}`], getStdio(fdNumber, [stream, new Uint8Array()]));294 await subprocess;295 t.true(subprocess.stdio[fdNumber].writableEnded);296};297298test('subprocess.stdin is ended when an input stream aborts', testInputStreamAbort, 0);299test('subprocess.stdio[*] is ended when an input stream aborts', testInputStreamAbort, 3);300301const testInputStreamError = async (t, fdNumber) => {302 const stream = new PassThrough();303 const cause = new Error(foobarString);304 stream.destroy(cause);305306 const subprocess = execa('stdin-fd.js', [`${fdNumber}`], getStdio(fdNumber, [stream, new Uint8Array()]));307 t.like(await t.throwsAsync(subprocess), {cause});308 t.true(subprocess.stdio[fdNumber].writableEnded);309};310311test('subprocess.stdin is ended when an input stream errors', testInputStreamError, 0);312test('subprocess.stdio[*] is ended when an input stream errors', testInputStreamError, 3);313314const testOutputStreamError = async (t, fdNumber) => {315 const stream = new PassThrough();316 const cause = new Error(foobarString);317 stream.destroy(cause);318319 const subprocess = execa('noop-fd.js', [`${fdNumber}`], getStdio(fdNumber, [stream, 'pipe']));320 t.like(await t.throwsAsync(subprocess), {cause});321 t.true(subprocess.stdio[fdNumber].readableAborted);322 t.is(subprocess.stdio[fdNumber].errored, null);323};324325test('subprocess.stdout is aborted when an output stream errors', testOutputStreamError, 1);326test('subprocess.stderr is aborted when an output stream errors', testOutputStreamError, 2);327test('subprocess.stdio[*] is aborted when an output stream errors', testOutputStreamError, 3);
added:test/stdio/normalize-transform.js+55 added
1import test from 'ava';2import {execa, execaSync} from '../../index.js';3import {setFixtureDir} from '../helpers/fixtures-dir.js';4import {foobarString, foobarUppercase, foobarUint8Array} from '../helpers/input.js';5import {casedSuffix} from '../helpers/generator.js';6import {generatorsMap} from '../helpers/map.js';78setFixtureDir();910const testAppendInput = async (t, reversed, type, execaMethod) => {11 const stdin = [foobarUint8Array, generatorsMap[type].uppercase(), generatorsMap[type].append()];12 const reversedStdin = reversed ? stdin.reverse() : stdin;13 const {stdout} = await execaMethod('stdin-fd.js', ['0'], {stdin: reversedStdin});14 const reversedSuffix = reversed ? casedSuffix.toUpperCase() : casedSuffix;15 t.is(stdout, `${foobarUppercase}${reversedSuffix}`);16};1718test('Can use multiple generators as input', testAppendInput, false, 'generator', execa);19test('Can use multiple generators as input, reversed', testAppendInput, true, 'generator', execa);20test('Can use multiple generators as input, sync', testAppendInput, false, 'generator', execaSync);21test('Can use multiple generators as input, reversed, sync', testAppendInput, true, 'generator', execaSync);22test('Can use multiple duplexes as input', testAppendInput, false, 'duplex', execa);23test('Can use multiple duplexes as input, reversed', testAppendInput, true, 'duplex', execa);24test('Can use multiple webTransforms as input', testAppendInput, false, 'webTransform', execa);25test('Can use multiple webTransforms as input, reversed', testAppendInput, true, 'webTransform', execa);2627const testAppendOutput = async (t, reversed, type, execaMethod) => {28 const stdoutOption = [generatorsMap[type].uppercase(), generatorsMap[type].append()];29 const reversedStdoutOption = reversed ? stdoutOption.reverse() : stdoutOption;30 const {stdout} = await execaMethod('noop-fd.js', ['1', foobarString], {stdout: reversedStdoutOption});31 const reversedSuffix = reversed ? casedSuffix.toUpperCase() : casedSuffix;32 t.is(stdout, `${foobarUppercase}${reversedSuffix}`);33};3435test('Can use multiple generators as output', testAppendOutput, false, 'generator', execa);36test('Can use multiple generators as output, reversed', testAppendOutput, true, 'generator', execa);37test('Can use multiple generators as output, sync', testAppendOutput, false, 'generator', execaSync);38test('Can use multiple generators as output, reversed, sync', testAppendOutput, true, 'generator', execaSync);39test('Can use multiple duplexes as output', testAppendOutput, false, 'duplex', execa);40test('Can use multiple duplexes as output, reversed', testAppendOutput, true, 'duplex', execa);41test('Can use multiple webTransforms as output', testAppendOutput, false, 'webTransform', execa);42test('Can use multiple webTransforms as output, reversed', testAppendOutput, true, 'webTransform', execa);4344const testGeneratorSyntax = async (t, type, usePlainObject, execaMethod) => {45 const transform = generatorsMap[type].uppercase();46 const {stdout} = await execaMethod('noop-fd.js', ['1', foobarString], {stdout: usePlainObject ? transform : transform.transform});47 t.is(stdout, foobarUppercase);48};4950test('Can pass generators with an options plain object', testGeneratorSyntax, 'generator', false, execa);51test('Can pass generators without an options plain object', testGeneratorSyntax, 'generator', true, execa);52test('Can pass generators with an options plain object, sync', testGeneratorSyntax, 'generator', false, execaSync);53test('Can pass generators without an options plain object, sync', testGeneratorSyntax, 'generator', true, execaSync);54test('Can pass webTransforms with an options plain object', testGeneratorSyntax, 'webTransform', true, execa);55test('Can pass webTransforms without an options plain object', testGeneratorSyntax, 'webTransform', false, execa);
added:test/stdio/output-async.js+84 added
1import {once, defaultMaxListeners} from 'node:events';2import process from 'node:process';3import {setImmediate} from 'node:timers/promises';4import test from 'ava';5import {execa} from '../../index.js';6import {STANDARD_STREAMS} from '../helpers/stdio.js';7import {foobarString} from '../helpers/input.js';8import {setFixtureDir} from '../helpers/fixtures-dir.js';9import {assertMaxListeners} from '../helpers/listeners.js';1011setFixtureDir();1213const getStandardStreamListeners = stream => Object.fromEntries(stream.eventNames().map(eventName => [eventName, stream.listeners(eventName)]));14const getStandardStreamsListeners = () => STANDARD_STREAMS.map(stream => getStandardStreamListeners(stream));1516const getComplexStdio = isMultiple => ({17 stdin: ['pipe', 'inherit', ...(isMultiple ? [0, process.stdin] : [])],18 stdout: ['pipe', 'inherit', ...(isMultiple ? [1, process.stdout] : [])],19 stderr: ['pipe', 'inherit', ...(isMultiple ? [2, process.stderr] : [])],20});2122const onStdinRemoveListener = () => once(process.stdin, 'removeListener');2324const testListenersCleanup = async (t, isMultiple) => {25 const streamsPreviousListeners = getStandardStreamsListeners();26 const subprocess = execa('empty.js', getComplexStdio(isMultiple));27 t.notDeepEqual(getStandardStreamsListeners(), streamsPreviousListeners);28 await Promise.all([subprocess, onStdinRemoveListener()]);29 if (isMultiple) {30 await onStdinRemoveListener();31 }3233 for (const [fdNumber, streamNewListeners] of Object.entries(getStandardStreamsListeners())) {34 const defaultListeners = Object.fromEntries(Reflect.ownKeys(streamNewListeners).map(eventName => [eventName, []]));35 t.deepEqual(streamNewListeners, {...defaultListeners, ...streamsPreviousListeners[fdNumber]});36 }37};3839test.serial('process.std* listeners are cleaned up on success with a single input', testListenersCleanup, false);40test.serial('process.std* listeners are cleaned up on success with multiple inputs', testListenersCleanup, true);4142const subprocessesCount = 100;4344test.serial('Can spawn many subprocesses in parallel', async t => {45 const results = await Promise.all(46 Array.from({length: subprocessesCount}, () => execa('noop.js', [foobarString])),47 );48 t.true(results.every(({stdout}) => stdout === foobarString));49});5051const testMaxListeners = async (t, isMultiple, maxListenersCount) => {52 const checkMaxListeners = assertMaxListeners(t);5354 for (const standardStream of STANDARD_STREAMS) {55 standardStream.setMaxListeners(maxListenersCount);56 }5758 try {59 const results = await Promise.all(60 Array.from({length: subprocessesCount}, () => execa('empty.js', getComplexStdio(isMultiple))),61 );62 t.true(results.every(({exitCode}) => exitCode === 0));63 } finally {64 await setImmediate();65 await setImmediate();66 checkMaxListeners();6768 for (const standardStream of STANDARD_STREAMS) {69 t.is(standardStream.getMaxListeners(), maxListenersCount);70 standardStream.setMaxListeners(defaultMaxListeners);71 }72 }73};7475test.serial('No warning with maxListeners 1 and ["pipe", "inherit"]', testMaxListeners, false, 1);76test.serial('No warning with maxListeners default and ["pipe", "inherit"]', testMaxListeners, false, defaultMaxListeners);77test.serial('No warning with maxListeners 100 and ["pipe", "inherit"]', testMaxListeners, false, 100);78test.serial('No warning with maxListeners Infinity and ["pipe", "inherit"]', testMaxListeners, false, Number.POSITIVE_INFINITY);79test.serial('No warning with maxListeners 0 and ["pipe", "inherit"]', testMaxListeners, false, 0);80test.serial('No warning with maxListeners 1 and ["pipe", "inherit"], multiple inputs', testMaxListeners, true, 1);81test.serial('No warning with maxListeners default and ["pipe", "inherit"], multiple inputs', testMaxListeners, true, defaultMaxListeners);82test.serial('No warning with maxListeners 100 and ["pipe", "inherit"], multiple inputs', testMaxListeners, true, 100);83test.serial('No warning with maxListeners Infinity and ["pipe", "inherit"], multiple inputs', testMaxListeners, true, Number.POSITIVE_INFINITY);84test.serial('No warning with maxListeners 0 and ["pipe", "inherit"], multiple inputs', testMaxListeners, true, 0);
added:test/stdio/split-binary.js+95 added
1import test from 'ava';2import {execa, execaSync} from '../../index.js';3import {setFixtureDir} from '../helpers/fixtures-dir.js';4import {getOutputsGenerator, resultGenerator} from '../helpers/generator.js';5import {6 simpleFull,7 simpleChunks,8 simpleFullUint8Array,9 simpleFullUtf16Inverted,10 simpleFullUtf16Uint8Array,11 simpleChunksUint8Array,12 simpleFullEnd,13 simpleFullEndUtf16Inverted,14 simpleFullHex,15 simpleLines,16 noNewlinesChunks,17} from '../helpers/lines.js';1819setFixtureDir();2021// eslint-disable-next-line max-params22const testBinaryOption = async (t, binary, input, expectedLines, expectedOutput, objectMode, preserveNewlines, encoding, execaMethod) => {23 const lines = [];24 const {stdout} = await execaMethod('noop.js', {25 stdout: [26 getOutputsGenerator(input)(false, true),27 resultGenerator(lines)(objectMode, binary, preserveNewlines),28 ],29 stripFinalNewline: false,30 encoding,31 });32 t.deepEqual(lines, expectedLines);33 t.deepEqual(stdout, expectedOutput);34};3536test('Does not split lines when "binary" is true', testBinaryOption, true, simpleChunks, simpleChunksUint8Array, simpleFull, false, true, 'utf8', execa);37test('Splits lines when "binary" is false', testBinaryOption, false, simpleChunks, simpleLines, simpleFull, false, true, 'utf8', execa);38test('Splits lines when "binary" is undefined', testBinaryOption, undefined, simpleChunks, simpleLines, simpleFull, false, true, 'utf8', execa);39test('Does not split lines when "binary" is true, encoding "utf16le"', testBinaryOption, true, simpleChunks, simpleChunksUint8Array, simpleFullUtf16Inverted, false, true, 'utf16le', execa);40test('Splits lines when "binary" is false, encoding "utf16le"', testBinaryOption, false, [simpleFullUtf16Uint8Array], simpleLines, simpleFullUtf16Inverted, false, true, 'utf16le', execa);41test('Splits lines when "binary" is undefined, encoding "utf16le"', testBinaryOption, undefined, [simpleFullUtf16Uint8Array], simpleLines, simpleFullUtf16Inverted, false, true, 'utf16le', execa);42test('Does not split lines when "binary" is true, encoding "buffer"', testBinaryOption, true, simpleChunks, simpleChunksUint8Array, simpleFullUint8Array, false, true, 'buffer', execa);43test('Does not split lines when "binary" is undefined, encoding "buffer"', testBinaryOption, undefined, simpleChunks, simpleChunksUint8Array, simpleFullUint8Array, false, true, 'buffer', execa);44test('Does not split lines when "binary" is false, encoding "buffer"', testBinaryOption, false, simpleChunks, simpleChunksUint8Array, simpleFullUint8Array, false, true, 'buffer', execa);45test('Does not split lines when "binary" is true, encoding "hex"', testBinaryOption, true, simpleChunks, simpleChunksUint8Array, simpleFullHex, false, true, 'hex', execa);46test('Does not split lines when "binary" is undefined, encoding "hex"', testBinaryOption, undefined, simpleChunks, simpleChunksUint8Array, simpleFullHex, false, true, 'hex', execa);47test('Does not split lines when "binary" is false, encoding "hex"', testBinaryOption, false, simpleChunks, simpleChunksUint8Array, simpleFullHex, false, true, 'hex', execa);48test('Does not split lines when "binary" is true, objectMode', testBinaryOption, true, simpleChunks, simpleChunksUint8Array, simpleChunksUint8Array, true, true, 'utf8', execa);49test('Splits lines when "binary" is false, objectMode', testBinaryOption, false, simpleChunks, simpleLines, simpleLines, true, true, 'utf8', execa);50test('Splits lines when "binary" is undefined, objectMode', testBinaryOption, undefined, simpleChunks, simpleLines, simpleLines, true, true, 'utf8', execa);51test('Does not split lines when "binary" is true, preserveNewlines', testBinaryOption, true, simpleChunks, simpleChunksUint8Array, simpleFull, false, false, 'utf8', execa);52test('Splits lines when "binary" is false, preserveNewlines', testBinaryOption, false, simpleChunks, noNewlinesChunks, simpleFullEnd, false, false, 'utf8', execa);53test('Splits lines when "binary" is undefined, preserveNewlines', testBinaryOption, undefined, simpleChunks, noNewlinesChunks, simpleFullEnd, false, false, 'utf8', execa);54test('Does not split lines when "binary" is true, preserveNewlines, encoding "utf16le"', testBinaryOption, true, simpleChunks, simpleChunksUint8Array, simpleFullUtf16Inverted, false, false, 'utf16le', execa);55test('Splits lines when "binary" is false, preserveNewlines, encoding "utf16le"', testBinaryOption, false, [simpleFullUtf16Uint8Array], noNewlinesChunks, simpleFullEndUtf16Inverted, false, false, 'utf16le', execa);56test('Splits lines when "binary" is undefined, preserveNewlines, encoding "utf16le"', testBinaryOption, undefined, [simpleFullUtf16Uint8Array], noNewlinesChunks, simpleFullEndUtf16Inverted, false, false, 'utf16le', execa);57test('Does not split lines when "binary" is true, encoding "buffer", preserveNewlines', testBinaryOption, true, simpleChunks, simpleChunksUint8Array, simpleFullUint8Array, false, false, 'buffer', execa);58test('Does not split lines when "binary" is undefined, encoding "buffer", preserveNewlines', testBinaryOption, undefined, simpleChunks, simpleChunksUint8Array, simpleFullUint8Array, false, false, 'buffer', execa);59test('Does not split lines when "binary" is false, encoding "buffer", preserveNewlines', testBinaryOption, false, simpleChunks, simpleChunksUint8Array, simpleFullUint8Array, false, false, 'buffer', execa);60test('Does not split lines when "binary" is true, objectMode, preserveNewlines', testBinaryOption, true, simpleChunks, simpleChunksUint8Array, simpleChunksUint8Array, true, false, 'utf8', execa);61test('Does not split lines when "binary" is true, encoding "hex", preserveNewlines', testBinaryOption, true, simpleChunks, simpleChunksUint8Array, simpleFullHex, false, false, 'hex', execa);62test('Does not split lines when "binary" is undefined, encoding "hex", preserveNewlines', testBinaryOption, undefined, simpleChunks, simpleChunksUint8Array, simpleFullHex, false, false, 'hex', execa);63test('Does not split lines when "binary" is false, encoding "hex", preserveNewlines', testBinaryOption, false, simpleChunks, simpleChunksUint8Array, simpleFullHex, false, false, 'hex', execa);64test('Splits lines when "binary" is false, objectMode, preserveNewlines', testBinaryOption, false, simpleChunks, noNewlinesChunks, noNewlinesChunks, true, false, 'utf8', execa);65test('Splits lines when "binary" is undefined, objectMode, preserveNewlines', testBinaryOption, undefined, simpleChunks, noNewlinesChunks, noNewlinesChunks, true, false, 'utf8', execa);66test('Does not split lines when "binary" is true, sync', testBinaryOption, true, simpleChunks, simpleChunksUint8Array, simpleFull, false, true, 'utf8', execaSync);67test('Splits lines when "binary" is false, sync', testBinaryOption, false, simpleChunks, simpleLines, simpleFull, false, true, 'utf8', execaSync);68test('Splits lines when "binary" is undefined, sync', testBinaryOption, undefined, simpleChunks, simpleLines, simpleFull, false, true, 'utf8', execaSync);69test('Does not split lines when "binary" is true, encoding "utf16le", sync', testBinaryOption, true, simpleChunks, simpleChunksUint8Array, simpleFullUtf16Inverted, false, true, 'utf16le', execaSync);70test('Splits lines when "binary" is false, encoding "utf16le", sync', testBinaryOption, false, [simpleFullUtf16Uint8Array], simpleLines, simpleFullUtf16Inverted, false, true, 'utf16le', execaSync);71test('Splits lines when "binary" is undefined, encoding "utf16le", sync', testBinaryOption, undefined, [simpleFullUtf16Uint8Array], simpleLines, simpleFullUtf16Inverted, false, true, 'utf16le', execaSync);72test('Does not split lines when "binary" is true, encoding "buffer", sync', testBinaryOption, true, simpleChunks, simpleChunksUint8Array, simpleFullUint8Array, false, true, 'buffer', execaSync);73test('Does not split lines when "binary" is undefined, encoding "buffer", sync', testBinaryOption, undefined, simpleChunks, simpleChunksUint8Array, simpleFullUint8Array, false, true, 'buffer', execaSync);74test('Does not split lines when "binary" is false, encoding "buffer", sync', testBinaryOption, false, simpleChunks, simpleChunksUint8Array, simpleFullUint8Array, false, true, 'buffer', execaSync);75test('Does not split lines when "binary" is true, encoding "hex", sync', testBinaryOption, true, simpleChunks, simpleChunksUint8Array, simpleFullHex, false, true, 'hex', execaSync);76test('Does not split lines when "binary" is undefined, encoding "hex", sync', testBinaryOption, undefined, simpleChunks, simpleChunksUint8Array, simpleFullHex, false, true, 'hex', execaSync);77test('Does not split lines when "binary" is false, encoding "hex", sync', testBinaryOption, false, simpleChunks, simpleChunksUint8Array, simpleFullHex, false, true, 'hex', execaSync);78test('Does not split lines when "binary" is true, objectMode, sync', testBinaryOption, true, simpleChunks, simpleChunksUint8Array, simpleChunksUint8Array, true, true, 'utf8', execaSync);79test('Splits lines when "binary" is false, objectMode, sync', testBinaryOption, false, simpleChunks, simpleLines, simpleLines, true, true, 'utf8', execaSync);80test('Splits lines when "binary" is undefined, objectMode, sync', testBinaryOption, undefined, simpleChunks, simpleLines, simpleLines, true, true, 'utf8', execaSync);81test('Does not split lines when "binary" is true, preserveNewlines, sync', testBinaryOption, true, simpleChunks, simpleChunksUint8Array, simpleFull, false, false, 'utf8', execaSync);82test('Splits lines when "binary" is false, preserveNewlines, sync', testBinaryOption, false, simpleChunks, noNewlinesChunks, simpleFullEnd, false, false, 'utf8', execaSync);83test('Splits lines when "binary" is undefined, preserveNewlines, sync', testBinaryOption, undefined, simpleChunks, noNewlinesChunks, simpleFullEnd, false, false, 'utf8', execaSync);84test('Does not split lines when "binary" is true, preserveNewlines, encoding "utf16le", sync', testBinaryOption, true, simpleChunks, simpleChunksUint8Array, simpleFullUtf16Inverted, false, false, 'utf16le', execaSync);85test('Splits lines when "binary" is false, preserveNewlines, encoding "utf16le", sync', testBinaryOption, false, [simpleFullUtf16Uint8Array], noNewlinesChunks, simpleFullEndUtf16Inverted, false, false, 'utf16le', execaSync);86test('Splits lines when "binary" is undefined, preserveNewlines, encoding "utf16le", sync', testBinaryOption, undefined, [simpleFullUtf16Uint8Array], noNewlinesChunks, simpleFullEndUtf16Inverted, false, false, 'utf16le', execaSync);87test('Does not split lines when "binary" is true, encoding "buffer", preserveNewlines, sync', testBinaryOption, true, simpleChunks, simpleChunksUint8Array, simpleFullUint8Array, false, false, 'buffer', execaSync);88test('Does not split lines when "binary" is undefined, encoding "buffer", preserveNewlines, sync', testBinaryOption, undefined, simpleChunks, simpleChunksUint8Array, simpleFullUint8Array, false, false, 'buffer', execaSync);89test('Does not split lines when "binary" is false, encoding "buffer", preserveNewlines, sync', testBinaryOption, false, simpleChunks, simpleChunksUint8Array, simpleFullUint8Array, false, false, 'buffer', execaSync);90test('Does not split lines when "binary" is true, objectMode, preserveNewlines, sync', testBinaryOption, true, simpleChunks, simpleChunksUint8Array, simpleChunksUint8Array, true, false, 'utf8', execaSync);91test('Does not split lines when "binary" is true, encoding "hex", preserveNewlines, sync', testBinaryOption, true, simpleChunks, simpleChunksUint8Array, simpleFullHex, false, false, 'hex', execaSync);92test('Does not split lines when "binary" is undefined, encoding "hex", preserveNewlines, sync', testBinaryOption, undefined, simpleChunks, simpleChunksUint8Array, simpleFullHex, false, false, 'hex', execaSync);93test('Does not split lines when "binary" is false, encoding "hex", preserveNewlines, sync', testBinaryOption, false, simpleChunks, simpleChunksUint8Array, simpleFullHex, false, false, 'hex', execaSync);94test('Splits lines when "binary" is false, objectMode, preserveNewlines, sync', testBinaryOption, false, simpleChunks, noNewlinesChunks, noNewlinesChunks, true, false, 'utf8', execaSync);95test('Splits lines when "binary" is undefined, objectMode, preserveNewlines, sync', testBinaryOption, undefined, simpleChunks, noNewlinesChunks, noNewlinesChunks, true, false, 'utf8', execaSync);
added:test/stdio/split-lines.js+174 added
1import test from 'ava';2import {execa, execaSync} from '../../index.js';3import {setFixtureDir} from '../helpers/fixtures-dir.js';4import {getStdio} from '../helpers/stdio.js';5import {getOutputsGenerator, resultGenerator} from '../helpers/generator.js';6import {7 singleFull,8 singleFullEnd,9 simpleFull,10 simpleChunks,11 simpleFullEnd,12 simpleFullEndChunks,13 simpleLines,14 simpleFullEndLines,15 noNewlinesFull,16 noNewlinesChunks,17} from '../helpers/lines.js';1819setFixtureDir();2021const windowsFull = 'aaa\r\nbbb\r\nccc';22const windowsFullEnd = `${windowsFull}\r\n`;23const windowsChunks = [windowsFull];24const windowsLines = ['aaa\r\n', 'bbb\r\n', 'ccc'];25const noNewlinesFullEnd = `${noNewlinesFull}\n`;26const noNewlinesLines = ['aaabbbccc'];27const singleChunks = [singleFull];28const noLines = [];29const emptyFull = '';30const emptyChunks = [emptyFull];31const manyEmptyChunks = [emptyFull, emptyFull, emptyFull];32const newlineFull = '\n';33const newlineChunks = [newlineFull];34const newlinesFull = '\n\n\n';35const newlinesChunks = [newlinesFull];36const newlinesLines = ['\n', '\n', '\n'];37const windowsNewlinesFull = '\r\n\r\n\r\n';38const windowsNewlinesChunks = [windowsNewlinesFull];39const windowsNewlinesLines = ['\r\n', '\r\n', '\r\n'];40const runOverChunks = ['aaa\nb', 'b', 'b\nccc'];41const bigFull = '.'.repeat(1e5);42const bigFullEnd = `${bigFull}\n`;43const bigChunks = [bigFull];44const manyChunks = Array.from({length: 1e3}).fill('.');45const manyFull = manyChunks.join('');46const manyFullEnd = `${manyFull}\n`;47const manyLines = [manyFull];4849// eslint-disable-next-line max-params50const testLines = async (t, fdNumber, input, expectedLines, expectedOutput, objectMode, preserveNewlines, execaMethod) => {51 const lines = [];52 const {stdio} = await execaMethod('noop-fd.js', [`${fdNumber}`], {53 ...getStdio(fdNumber, [54 getOutputsGenerator(input)(false, true),55 resultGenerator(lines)(objectMode, false, preserveNewlines),56 ]),57 stripFinalNewline: false,58 });59 t.deepEqual(lines, expectedLines);60 t.deepEqual(stdio[fdNumber], expectedOutput);61};6263test('Split stdout - n newlines, 1 chunk', testLines, 1, simpleChunks, simpleLines, simpleFull, false, true, execa);64test('Split stderr - n newlines, 1 chunk', testLines, 2, simpleChunks, simpleLines, simpleFull, false, true, execa);65test('Split stdio[*] - n newlines, 1 chunk', testLines, 3, simpleChunks, simpleLines, simpleFull, false, true, execa);66test('Split stdout - preserveNewlines, n chunks', testLines, 1, noNewlinesChunks, noNewlinesLines, noNewlinesFull, false, true, execa);67test('Split stdout - 0 newlines, 1 chunk', testLines, 1, singleChunks, singleChunks, singleFull, false, true, execa);68test('Split stdout - empty, 1 chunk', testLines, 1, emptyChunks, noLines, emptyFull, false, true, execa);69test('Split stdout - Windows newlines', testLines, 1, windowsChunks, windowsLines, windowsFull, false, true, execa);70test('Split stdout - chunk ends with newline', testLines, 1, simpleFullEndChunks, simpleFullEndLines, simpleFullEnd, false, true, execa);71test('Split stdout - single newline', testLines, 1, newlineChunks, newlineChunks, newlineFull, false, true, execa);72test('Split stdout - only newlines', testLines, 1, newlinesChunks, newlinesLines, newlinesFull, false, true, execa);73test('Split stdout - only Windows newlines', testLines, 1, windowsNewlinesChunks, windowsNewlinesLines, windowsNewlinesFull, false, true, execa);74test('Split stdout - line split over multiple chunks', testLines, 1, runOverChunks, simpleLines, simpleFull, false, true, execa);75test('Split stdout - 0 newlines, big line', testLines, 1, bigChunks, bigChunks, bigFull, false, true, execa);76test('Split stdout - 0 newlines, many chunks', testLines, 1, manyChunks, manyLines, manyFull, false, true, execa);77test('Split stdout - n newlines, 1 chunk, objectMode', testLines, 1, simpleChunks, simpleLines, simpleLines, true, true, execa);78test('Split stderr - n newlines, 1 chunk, objectMode', testLines, 2, simpleChunks, simpleLines, simpleLines, true, true, execa);79test('Split stdio[*] - n newlines, 1 chunk, objectMode', testLines, 3, simpleChunks, simpleLines, simpleLines, true, true, execa);80test('Split stdout - preserveNewlines, n chunks, objectMode', testLines, 1, noNewlinesChunks, noNewlinesLines, noNewlinesLines, true, true, execa);81test('Split stdout - empty, 1 chunk, objectMode', testLines, 1, emptyChunks, noLines, noLines, true, true, execa);82test('Split stdout - 0 newlines, 1 chunk, objectMode', testLines, 1, singleChunks, singleChunks, singleChunks, true, true, execa);83test('Split stdout - Windows newlines, objectMode', testLines, 1, windowsChunks, windowsLines, windowsLines, true, true, execa);84test('Split stdout - chunk ends with newline, objectMode', testLines, 1, simpleFullEndChunks, simpleFullEndLines, simpleFullEndLines, true, true, execa);85test('Split stdout - single newline, objectMode', testLines, 1, newlineChunks, newlineChunks, newlineChunks, true, true, execa);86test('Split stdout - only newlines, objectMode', testLines, 1, newlinesChunks, newlinesLines, newlinesLines, true, true, execa);87test('Split stdout - only Windows newlines, objectMode', testLines, 1, windowsNewlinesChunks, windowsNewlinesLines, windowsNewlinesLines, true, true, execa);88test('Split stdout - line split over multiple chunks, objectMode', testLines, 1, runOverChunks, simpleLines, simpleLines, true, true, execa);89test('Split stdout - 0 newlines, big line, objectMode', testLines, 1, bigChunks, bigChunks, bigChunks, true, true, execa);90test('Split stdout - 0 newlines, many chunks, objectMode', testLines, 1, manyChunks, manyLines, manyLines, true, true, execa);91test('Split stdout - n newlines, 1 chunk, preserveNewlines', testLines, 1, simpleChunks, noNewlinesChunks, simpleFullEnd, false, false, execa);92test('Split stderr - n newlines, 1 chunk, preserveNewlines', testLines, 2, simpleChunks, noNewlinesChunks, simpleFullEnd, false, false, execa);93test('Split stdio[*] - n newlines, 1 chunk, preserveNewlines', testLines, 3, simpleChunks, noNewlinesChunks, simpleFullEnd, false, false, execa);94test('Split stdout - preserveNewlines, n chunks, preserveNewlines', testLines, 1, noNewlinesChunks, noNewlinesLines, noNewlinesFullEnd, false, false, execa);95test('Split stdout - empty, 1 chunk, preserveNewlines', testLines, 1, emptyChunks, noLines, emptyFull, false, false, execa);96test('Split stdout - 0 newlines, 1 chunk, preserveNewlines', testLines, 1, singleChunks, singleChunks, singleFullEnd, false, false, execa);97test('Split stdout - Windows newlines, preserveNewlines', testLines, 1, windowsChunks, noNewlinesChunks, windowsFullEnd, false, false, execa);98test('Split stdout - chunk ends with newline, preserveNewlines', testLines, 1, simpleFullEndChunks, noNewlinesChunks, simpleFullEnd, false, false, execa);99test('Split stdout - single newline, preserveNewlines', testLines, 1, newlineChunks, emptyChunks, newlineFull, false, false, execa);100test('Split stdout - only newlines, preserveNewlines', testLines, 1, newlinesChunks, manyEmptyChunks, newlinesFull, false, false, execa);101test('Split stdout - only Windows newlines, preserveNewlines', testLines, 1, windowsNewlinesChunks, manyEmptyChunks, windowsNewlinesFull, false, false, execa);102test('Split stdout - line split over multiple chunks, preserveNewlines', testLines, 1, runOverChunks, noNewlinesChunks, simpleFullEnd, false, false, execa);103test('Split stdout - 0 newlines, big line, preserveNewlines', testLines, 1, bigChunks, bigChunks, bigFullEnd, false, false, execa);104test('Split stdout - 0 newlines, many chunks, preserveNewlines', testLines, 1, manyChunks, manyLines, manyFullEnd, false, false, execa);105test('Split stdout - n newlines, 1 chunk, objectMode, preserveNewlines', testLines, 1, simpleChunks, noNewlinesChunks, noNewlinesChunks, true, false, execa);106test('Split stderr - n newlines, 1 chunk, objectMode, preserveNewlines', testLines, 2, simpleChunks, noNewlinesChunks, noNewlinesChunks, true, false, execa);107test('Split stdio[*] - n newlines, 1 chunk, objectMode, preserveNewlines', testLines, 3, simpleChunks, noNewlinesChunks, noNewlinesChunks, true, false, execa);108test('Split stdout - preserveNewlines, n chunks, objectMode, preserveNewlines', testLines, 1, noNewlinesChunks, noNewlinesLines, noNewlinesLines, true, false, execa);109test('Split stdout - empty, 1 chunk, objectMode, preserveNewlines', testLines, 1, emptyChunks, noLines, noLines, true, false, execa);110test('Split stdout - 0 newlines, 1 chunk, objectMode, preserveNewlines', testLines, 1, singleChunks, singleChunks, singleChunks, true, false, execa);111test('Split stdout - Windows newlines, objectMode, preserveNewlines', testLines, 1, windowsChunks, noNewlinesChunks, noNewlinesChunks, true, false, execa);112test('Split stdout - chunk ends with newline, objectMode, preserveNewlines', testLines, 1, simpleFullEndChunks, noNewlinesChunks, noNewlinesChunks, true, false, execa);113test('Split stdout - single newline, objectMode, preserveNewlines', testLines, 1, newlineChunks, emptyChunks, emptyChunks, true, false, execa);114test('Split stdout - only newlines, objectMode, preserveNewlines', testLines, 1, newlinesChunks, manyEmptyChunks, manyEmptyChunks, true, false, execa);115test('Split stdout - only Windows newlines, objectMode, preserveNewlines', testLines, 1, windowsNewlinesChunks, manyEmptyChunks, manyEmptyChunks, true, false, execa);116test('Split stdout - line split over multiple chunks, objectMode, preserveNewlines', testLines, 1, runOverChunks, noNewlinesChunks, noNewlinesChunks, true, false, execa);117test('Split stdout - 0 newlines, big line, objectMode, preserveNewlines', testLines, 1, bigChunks, bigChunks, bigChunks, true, false, execa);118test('Split stdout - 0 newlines, many chunks, objectMode, preserveNewlines', testLines, 1, manyChunks, manyLines, manyLines, true, false, execa);119test('Split stdout - n newlines, 1 chunk, sync', testLines, 1, simpleChunks, simpleLines, simpleFull, false, true, execaSync);120test('Split stderr - n newlines, 1 chunk, sync', testLines, 2, simpleChunks, simpleLines, simpleFull, false, true, execaSync);121test('Split stdio[*] - n newlines, 1 chunk, sync', testLines, 3, simpleChunks, simpleLines, simpleFull, false, true, execaSync);122test('Split stdout - preserveNewlines, n chunks, sync', testLines, 1, noNewlinesChunks, noNewlinesLines, noNewlinesFull, false, true, execaSync);123test('Split stdout - 0 newlines, 1 chunk, sync', testLines, 1, singleChunks, singleChunks, singleFull, false, true, execaSync);124test('Split stdout - empty, 1 chunk, sync', testLines, 1, emptyChunks, noLines, emptyFull, false, true, execaSync);125test('Split stdout - Windows newlines, sync', testLines, 1, windowsChunks, windowsLines, windowsFull, false, true, execaSync);126test('Split stdout - chunk ends with newline, sync', testLines, 1, simpleFullEndChunks, simpleFullEndLines, simpleFullEnd, false, true, execaSync);127test('Split stdout - single newline, sync', testLines, 1, newlineChunks, newlineChunks, newlineFull, false, true, execaSync);128test('Split stdout - only newlines, sync', testLines, 1, newlinesChunks, newlinesLines, newlinesFull, false, true, execaSync);129test('Split stdout - only Windows newlines, sync', testLines, 1, windowsNewlinesChunks, windowsNewlinesLines, windowsNewlinesFull, false, true, execaSync);130test('Split stdout - line split over multiple chunks, sync', testLines, 1, runOverChunks, simpleLines, simpleFull, false, true, execaSync);131test('Split stdout - 0 newlines, big line, sync', testLines, 1, bigChunks, bigChunks, bigFull, false, true, execaSync);132test('Split stdout - 0 newlines, many chunks, sync', testLines, 1, manyChunks, manyLines, manyFull, false, true, execaSync);133test('Split stdout - n newlines, 1 chunk, objectMode, sync', testLines, 1, simpleChunks, simpleLines, simpleLines, true, true, execaSync);134test('Split stderr - n newlines, 1 chunk, objectMode, sync', testLines, 2, simpleChunks, simpleLines, simpleLines, true, true, execaSync);135test('Split stdio[*] - n newlines, 1 chunk, objectMode, sync', testLines, 3, simpleChunks, simpleLines, simpleLines, true, true, execaSync);136test('Split stdout - preserveNewlines, n chunks, objectMode, sync', testLines, 1, noNewlinesChunks, noNewlinesLines, noNewlinesLines, true, true, execaSync);137test('Split stdout - empty, 1 chunk, objectMode, sync', testLines, 1, emptyChunks, noLines, noLines, true, true, execaSync);138test('Split stdout - 0 newlines, 1 chunk, objectMode, sync', testLines, 1, singleChunks, singleChunks, singleChunks, true, true, execaSync);139test('Split stdout - Windows newlines, objectMode, sync', testLines, 1, windowsChunks, windowsLines, windowsLines, true, true, execaSync);140test('Split stdout - chunk ends with newline, objectMode, sync', testLines, 1, simpleFullEndChunks, simpleFullEndLines, simpleFullEndLines, true, true, execaSync);141test('Split stdout - single newline, objectMode, sync', testLines, 1, newlineChunks, newlineChunks, newlineChunks, true, true, execaSync);142test('Split stdout - only newlines, objectMode, sync', testLines, 1, newlinesChunks, newlinesLines, newlinesLines, true, true, execaSync);143test('Split stdout - only Windows newlines, objectMode, sync', testLines, 1, windowsNewlinesChunks, windowsNewlinesLines, windowsNewlinesLines, true, true, execaSync);144test('Split stdout - line split over multiple chunks, objectMode, sync', testLines, 1, runOverChunks, simpleLines, simpleLines, true, true, execaSync);145test('Split stdout - 0 newlines, big line, objectMode, sync', testLines, 1, bigChunks, bigChunks, bigChunks, true, true, execaSync);146test('Split stdout - 0 newlines, many chunks, objectMode, sync', testLines, 1, manyChunks, manyLines, manyLines, true, true, execaSync);147test('Split stdout - n newlines, 1 chunk, preserveNewlines, sync', testLines, 1, simpleChunks, noNewlinesChunks, simpleFullEnd, false, false, execaSync);148test('Split stderr - n newlines, 1 chunk, preserveNewlines, sync', testLines, 2, simpleChunks, noNewlinesChunks, simpleFullEnd, false, false, execaSync);149test('Split stdio[*] - n newlines, 1 chunk, preserveNewlines, sync', testLines, 3, simpleChunks, noNewlinesChunks, simpleFullEnd, false, false, execaSync);150test('Split stdout - preserveNewlines, n chunks, preserveNewlines, sync', testLines, 1, noNewlinesChunks, noNewlinesLines, noNewlinesFullEnd, false, false, execaSync);151test('Split stdout - empty, 1 chunk, preserveNewlines, sync', testLines, 1, emptyChunks, noLines, emptyFull, false, false, execaSync);152test('Split stdout - 0 newlines, 1 chunk, preserveNewlines, sync', testLines, 1, singleChunks, singleChunks, singleFullEnd, false, false, execaSync);153test('Split stdout - Windows newlines, preserveNewlines, sync', testLines, 1, windowsChunks, noNewlinesChunks, windowsFullEnd, false, false, execaSync);154test('Split stdout - chunk ends with newline, preserveNewlines, sync', testLines, 1, simpleFullEndChunks, noNewlinesChunks, simpleFullEnd, false, false, execaSync);155test('Split stdout - single newline, preserveNewlines, sync', testLines, 1, newlineChunks, emptyChunks, newlineFull, false, false, execaSync);156test('Split stdout - only newlines, preserveNewlines, sync', testLines, 1, newlinesChunks, manyEmptyChunks, newlinesFull, false, false, execaSync);157test('Split stdout - only Windows newlines, preserveNewlines, sync', testLines, 1, windowsNewlinesChunks, manyEmptyChunks, windowsNewlinesFull, false, false, execaSync);158test('Split stdout - line split over multiple chunks, preserveNewlines, sync', testLines, 1, runOverChunks, noNewlinesChunks, simpleFullEnd, false, false, execaSync);159test('Split stdout - 0 newlines, big line, preserveNewlines, sync', testLines, 1, bigChunks, bigChunks, bigFullEnd, false, false, execaSync);160test('Split stdout - 0 newlines, many chunks, preserveNewlines, sync', testLines, 1, manyChunks, manyLines, manyFullEnd, false, false, execaSync);161test('Split stdout - n newlines, 1 chunk, objectMode, preserveNewlines, sync', testLines, 1, simpleChunks, noNewlinesChunks, noNewlinesChunks, true, false, execaSync);162test('Split stderr - n newlines, 1 chunk, objectMode, preserveNewlines, sync', testLines, 2, simpleChunks, noNewlinesChunks, noNewlinesChunks, true, false, execaSync);163test('Split stdio[*] - n newlines, 1 chunk, objectMode, preserveNewlines, sync', testLines, 3, simpleChunks, noNewlinesChunks, noNewlinesChunks, true, false, execaSync);164test('Split stdout - preserveNewlines, n chunks, objectMode, preserveNewlines, sync', testLines, 1, noNewlinesChunks, noNewlinesLines, noNewlinesLines, true, false, execaSync);165test('Split stdout - empty, 1 chunk, objectMode, preserveNewlines, sync', testLines, 1, emptyChunks, noLines, noLines, true, false, execaSync);166test('Split stdout - 0 newlines, 1 chunk, objectMode, preserveNewlines, sync', testLines, 1, singleChunks, singleChunks, singleChunks, true, false, execaSync);167test('Split stdout - Windows newlines, objectMode, preserveNewlines, sync', testLines, 1, windowsChunks, noNewlinesChunks, noNewlinesChunks, true, false, execaSync);168test('Split stdout - chunk ends with newline, objectMode, preserveNewlines, sync', testLines, 1, simpleFullEndChunks, noNewlinesChunks, noNewlinesChunks, true, false, execaSync);169test('Split stdout - single newline, objectMode, preserveNewlines, sync', testLines, 1, newlineChunks, emptyChunks, emptyChunks, true, false, execaSync);170test('Split stdout - only newlines, objectMode, preserveNewlines, sync', testLines, 1, newlinesChunks, manyEmptyChunks, manyEmptyChunks, true, false, execaSync);171test('Split stdout - only Windows newlines, objectMode, preserveNewlines, sync', testLines, 1, windowsNewlinesChunks, manyEmptyChunks, manyEmptyChunks, true, false, execaSync);172test('Split stdout - line split over multiple chunks, objectMode, preserveNewlines, sync', testLines, 1, runOverChunks, noNewlinesChunks, noNewlinesChunks, true, false, execaSync);173test('Split stdout - 0 newlines, big line, objectMode, preserveNewlines, sync', testLines, 1, bigChunks, bigChunks, bigChunks, true, false, execaSync);174test('Split stdout - 0 newlines, many chunks, objectMode, preserveNewlines, sync', testLines, 1, manyChunks, manyLines, manyLines, true, false, execaSync);
added:test/stdio/split-newline.js+37 added
1import test from 'ava';2import {execa, execaSync} from '../../index.js';3import {setFixtureDir} from '../helpers/fixtures-dir.js';4import {getOutputsGenerator, noopGenerator, noopAsyncGenerator} from '../helpers/generator.js';5import {singleFull, singleFullEnd} from '../helpers/lines.js';67setFixtureDir();89const singleFullEndWindows = `${singleFull}\r\n`;10const mixedNewlines = '.\n.\r\n.\n.\r\n.\n';1112const testStripNewline = async (t, input, expectedOutput, execaMethod) => {13 const {stdout} = await execaMethod('noop.js', {14 stdout: getOutputsGenerator([input])(),15 stripFinalNewline: false,16 });17 t.is(stdout, expectedOutput);18};1920test('Strips newline when user do not mistakenly yield one at the end', testStripNewline, singleFull, singleFullEnd, execa);21test('Strips newline when user mistakenly yielded one at the end', testStripNewline, singleFullEnd, singleFullEnd, execa);22test('Strips newline when user mistakenly yielded one at the end, Windows newline', testStripNewline, singleFullEndWindows, singleFullEndWindows, execa);23test('Strips newline when user do not mistakenly yield one at the end, sync', testStripNewline, singleFull, singleFullEnd, execaSync);24test('Strips newline when user mistakenly yielded one at the end, sync', testStripNewline, singleFullEnd, singleFullEnd, execaSync);25test('Strips newline when user mistakenly yielded one at the end, Windows newline, sync', testStripNewline, singleFullEndWindows, singleFullEndWindows, execaSync);2627const testMixNewlines = async (t, generator, execaMethod) => {28 const {stdout} = await execaMethod('noop-fd.js', ['1', mixedNewlines], {29 stdout: generator(),30 stripFinalNewline: false,31 });32 t.is(stdout, mixedNewlines);33};3435test('Can mix Unix and Windows newlines', testMixNewlines, noopGenerator, execa);36test('Can mix Unix and Windows newlines, sync', testMixNewlines, noopGenerator, execaSync);37test('Can mix Unix and Windows newlines, async', testMixNewlines, noopAsyncGenerator, execa);
added:test/stdio/split-transform.js+78 added
1import test from 'ava';2import {execa, execaSync} from '../../index.js';3import {setFixtureDir} from '../helpers/fixtures-dir.js';4import {getOutputsGenerator, resultGenerator} from '../helpers/generator.js';5import {foobarString, foobarUint8Array, foobarObject, foobarObjectString} from '../helpers/input.js';67setFixtureDir();89const resultUint8ArrayGenerator = function * (lines, chunk) {10 lines.push(chunk);11 yield new TextEncoder().encode(chunk);12};1314// eslint-disable-next-line max-params15const testStringToUint8Array = async (t, expectedOutput, objectMode, preserveNewlines, execaMethod) => {16 const lines = [];17 const {stdout} = await execaMethod('noop-fd.js', ['1', foobarString], {18 stdout: {19 transform: resultUint8ArrayGenerator.bind(undefined, lines),20 objectMode,21 preserveNewlines,22 },23 lines: true,24 });25 t.deepEqual(lines, [foobarString]);26 t.deepEqual(stdout, expectedOutput);27};2829test('Line splitting when converting from string to Uint8Array', testStringToUint8Array, [foobarString], false, true, execa);30test('Line splitting when converting from string to Uint8Array, objectMode', testStringToUint8Array, [foobarUint8Array], true, true, execa);31test('Line splitting when converting from string to Uint8Array, preserveNewlines', testStringToUint8Array, [foobarString], false, false, execa);32test('Line splitting when converting from string to Uint8Array, objectMode, preserveNewlines', testStringToUint8Array, [foobarUint8Array], true, false, execa);33test('Line splitting when converting from string to Uint8Array, sync', testStringToUint8Array, [foobarString], false, true, execaSync);34test('Line splitting when converting from string to Uint8Array, objectMode, sync', testStringToUint8Array, [foobarUint8Array], true, true, execaSync);35test('Line splitting when converting from string to Uint8Array, preserveNewlines, sync', testStringToUint8Array, [foobarString], false, false, execaSync);36test('Line splitting when converting from string to Uint8Array, objectMode, preserveNewlines, sync', testStringToUint8Array, [foobarUint8Array], true, false, execaSync);3738const serializeResultGenerator = function * (lines, chunk) {39 lines.push(chunk);40 yield JSON.stringify(chunk);41};4243const testUnsetObjectMode = async (t, expectedOutput, preserveNewlines, execaMethod) => {44 const lines = [];45 const {stdout} = await execaMethod('noop.js', {46 stdout: [47 getOutputsGenerator([foobarObject])(true),48 {transform: serializeResultGenerator.bind(undefined, lines), preserveNewlines, objectMode: false},49 ],50 stripFinalNewline: false,51 });52 t.deepEqual(lines, [foobarObject]);53 t.is(stdout, expectedOutput);54};5556test('Can switch from objectMode to non-objectMode', testUnsetObjectMode, `${foobarObjectString}\n`, false, execa);57test('Can switch from objectMode to non-objectMode, preserveNewlines', testUnsetObjectMode, foobarObjectString, true, execa);58test('Can switch from objectMode to non-objectMode, sync', testUnsetObjectMode, `${foobarObjectString}\n`, false, execaSync);59test('Can switch from objectMode to non-objectMode, preserveNewlines, sync', testUnsetObjectMode, foobarObjectString, true, execaSync);6061// eslint-disable-next-line max-params62const testYieldArray = async (t, input, expectedLines, expectedOutput, execaMethod) => {63 const lines = [];64 const {stdout} = await execaMethod('noop.js', {65 stdout: [66 getOutputsGenerator(input)(),67 resultGenerator(lines)(),68 ],69 stripFinalNewline: false,70 });71 t.deepEqual(lines, expectedLines);72 t.deepEqual(stdout, expectedOutput);73};7475test('Can use "yield* array" to produce multiple lines', testYieldArray, [foobarString, foobarString], [foobarString, foobarString], `${foobarString}\n${foobarString}\n`, execa);76test('Can use "yield* array" to produce empty lines', testYieldArray, [foobarString, ''], [foobarString, ''], `${foobarString}\n\n`, execa);77test('Can use "yield* array" to produce multiple lines, sync', testYieldArray, [foobarString, foobarString], [foobarString, foobarString], `${foobarString}\n${foobarString}\n`, execaSync);78test('Can use "yield* array" to produce empty lines, sync', testYieldArray, [foobarString, ''], [foobarString, ''], `${foobarString}\n\n`, execaSync);
deleted:test/stdio/split.js-362 removed
1import test from 'ava';2import {execa, execaSync} from '../../index.js';3import {setFixtureDir} from '../helpers/fixtures-dir.js';4import {getStdio} from '../helpers/stdio.js';5import {6 getOutputsGenerator,7 noopGenerator,8 noopAsyncGenerator,9 resultGenerator,10} from '../helpers/generator.js';11import {foobarString, foobarUint8Array, foobarObject, foobarObjectString} from '../helpers/input.js';12import {13 simpleFull,14 simpleChunks,15 simpleFullUint8Array,16 simpleFullUtf16Inverted,17 simpleFullUtf16Uint8Array,18 simpleChunksUint8Array,19 simpleFullEnd,20 simpleFullEndChunks,21 simpleFullEndUtf16Inverted,22 simpleFullHex,23 simpleLines,24 simpleFullEndLines,25 noNewlinesFull,26 noNewlinesChunks,27} from '../helpers/lines.js';2829setFixtureDir();3031const windowsFull = 'aaa\r\nbbb\r\nccc';32const windowsFullEnd = `${windowsFull}\r\n`;33const windowsChunks = [windowsFull];34const windowsLines = ['aaa\r\n', 'bbb\r\n', 'ccc'];35const noNewlinesFullEnd = `${noNewlinesFull}\n`;36const noNewlinesLines = ['aaabbbccc'];37const singleFull = 'aaa';38const singleFullEnd = `${singleFull}\n`;39const singleFullEndWindows = `${singleFull}\r\n`;40const singleChunks = [singleFull];41const noLines = [];42const emptyFull = '';43const emptyChunks = [emptyFull];44const manyEmptyChunks = [emptyFull, emptyFull, emptyFull];45const newlineFull = '\n';46const newlineChunks = [newlineFull];47const newlinesFull = '\n\n\n';48const newlinesChunks = [newlinesFull];49const newlinesLines = ['\n', '\n', '\n'];50const windowsNewlinesFull = '\r\n\r\n\r\n';51const windowsNewlinesChunks = [windowsNewlinesFull];52const windowsNewlinesLines = ['\r\n', '\r\n', '\r\n'];53const runOverChunks = ['aaa\nb', 'b', 'b\nccc'];54const bigFull = '.'.repeat(1e5);55const bigFullEnd = `${bigFull}\n`;56const bigChunks = [bigFull];57const manyChunks = Array.from({length: 1e3}).fill('.');58const manyFull = manyChunks.join('');59const manyFullEnd = `${manyFull}\n`;60const manyLines = [manyFull];61const mixedNewlines = '.\n.\r\n.\n.\r\n.\n';6263// eslint-disable-next-line max-params64const testLines = async (t, fdNumber, input, expectedLines, expectedOutput, objectMode, preserveNewlines, execaMethod) => {65 const lines = [];66 const {stdio} = await execaMethod('noop-fd.js', [`${fdNumber}`], {67 ...getStdio(fdNumber, [68 getOutputsGenerator(input)(false, true),69 resultGenerator(lines)(objectMode, false, preserveNewlines),70 ]),71 stripFinalNewline: false,72 });73 t.deepEqual(lines, expectedLines);74 t.deepEqual(stdio[fdNumber], expectedOutput);75};7677test('Split stdout - n newlines, 1 chunk', testLines, 1, simpleChunks, simpleLines, simpleFull, false, true, execa);78test('Split stderr - n newlines, 1 chunk', testLines, 2, simpleChunks, simpleLines, simpleFull, false, true, execa);79test('Split stdio[*] - n newlines, 1 chunk', testLines, 3, simpleChunks, simpleLines, simpleFull, false, true, execa);80test('Split stdout - preserveNewlines, n chunks', testLines, 1, noNewlinesChunks, noNewlinesLines, noNewlinesFull, false, true, execa);81test('Split stdout - 0 newlines, 1 chunk', testLines, 1, singleChunks, singleChunks, singleFull, false, true, execa);82test('Split stdout - empty, 1 chunk', testLines, 1, emptyChunks, noLines, emptyFull, false, true, execa);83test('Split stdout - Windows newlines', testLines, 1, windowsChunks, windowsLines, windowsFull, false, true, execa);84test('Split stdout - chunk ends with newline', testLines, 1, simpleFullEndChunks, simpleFullEndLines, simpleFullEnd, false, true, execa);85test('Split stdout - single newline', testLines, 1, newlineChunks, newlineChunks, newlineFull, false, true, execa);86test('Split stdout - only newlines', testLines, 1, newlinesChunks, newlinesLines, newlinesFull, false, true, execa);87test('Split stdout - only Windows newlines', testLines, 1, windowsNewlinesChunks, windowsNewlinesLines, windowsNewlinesFull, false, true, execa);88test('Split stdout - line split over multiple chunks', testLines, 1, runOverChunks, simpleLines, simpleFull, false, true, execa);89test('Split stdout - 0 newlines, big line', testLines, 1, bigChunks, bigChunks, bigFull, false, true, execa);90test('Split stdout - 0 newlines, many chunks', testLines, 1, manyChunks, manyLines, manyFull, false, true, execa);91test('Split stdout - n newlines, 1 chunk, objectMode', testLines, 1, simpleChunks, simpleLines, simpleLines, true, true, execa);92test('Split stderr - n newlines, 1 chunk, objectMode', testLines, 2, simpleChunks, simpleLines, simpleLines, true, true, execa);93test('Split stdio[*] - n newlines, 1 chunk, objectMode', testLines, 3, simpleChunks, simpleLines, simpleLines, true, true, execa);94test('Split stdout - preserveNewlines, n chunks, objectMode', testLines, 1, noNewlinesChunks, noNewlinesLines, noNewlinesLines, true, true, execa);95test('Split stdout - empty, 1 chunk, objectMode', testLines, 1, emptyChunks, noLines, noLines, true, true, execa);96test('Split stdout - 0 newlines, 1 chunk, objectMode', testLines, 1, singleChunks, singleChunks, singleChunks, true, true, execa);97test('Split stdout - Windows newlines, objectMode', testLines, 1, windowsChunks, windowsLines, windowsLines, true, true, execa);98test('Split stdout - chunk ends with newline, objectMode', testLines, 1, simpleFullEndChunks, simpleFullEndLines, simpleFullEndLines, true, true, execa);99test('Split stdout - single newline, objectMode', testLines, 1, newlineChunks, newlineChunks, newlineChunks, true, true, execa);100test('Split stdout - only newlines, objectMode', testLines, 1, newlinesChunks, newlinesLines, newlinesLines, true, true, execa);101test('Split stdout - only Windows newlines, objectMode', testLines, 1, windowsNewlinesChunks, windowsNewlinesLines, windowsNewlinesLines, true, true, execa);102test('Split stdout - line split over multiple chunks, objectMode', testLines, 1, runOverChunks, simpleLines, simpleLines, true, true, execa);103test('Split stdout - 0 newlines, big line, objectMode', testLines, 1, bigChunks, bigChunks, bigChunks, true, true, execa);104test('Split stdout - 0 newlines, many chunks, objectMode', testLines, 1, manyChunks, manyLines, manyLines, true, true, execa);105test('Split stdout - n newlines, 1 chunk, preserveNewlines', testLines, 1, simpleChunks, noNewlinesChunks, simpleFullEnd, false, false, execa);106test('Split stderr - n newlines, 1 chunk, preserveNewlines', testLines, 2, simpleChunks, noNewlinesChunks, simpleFullEnd, false, false, execa);107test('Split stdio[*] - n newlines, 1 chunk, preserveNewlines', testLines, 3, simpleChunks, noNewlinesChunks, simpleFullEnd, false, false, execa);108test('Split stdout - preserveNewlines, n chunks, preserveNewlines', testLines, 1, noNewlinesChunks, noNewlinesLines, noNewlinesFullEnd, false, false, execa);109test('Split stdout - empty, 1 chunk, preserveNewlines', testLines, 1, emptyChunks, noLines, emptyFull, false, false, execa);110test('Split stdout - 0 newlines, 1 chunk, preserveNewlines', testLines, 1, singleChunks, singleChunks, singleFullEnd, false, false, execa);111test('Split stdout - Windows newlines, preserveNewlines', testLines, 1, windowsChunks, noNewlinesChunks, windowsFullEnd, false, false, execa);112test('Split stdout - chunk ends with newline, preserveNewlines', testLines, 1, simpleFullEndChunks, noNewlinesChunks, simpleFullEnd, false, false, execa);113test('Split stdout - single newline, preserveNewlines', testLines, 1, newlineChunks, emptyChunks, newlineFull, false, false, execa);114test('Split stdout - only newlines, preserveNewlines', testLines, 1, newlinesChunks, manyEmptyChunks, newlinesFull, false, false, execa);115test('Split stdout - only Windows newlines, preserveNewlines', testLines, 1, windowsNewlinesChunks, manyEmptyChunks, windowsNewlinesFull, false, false, execa);116test('Split stdout - line split over multiple chunks, preserveNewlines', testLines, 1, runOverChunks, noNewlinesChunks, simpleFullEnd, false, false, execa);117test('Split stdout - 0 newlines, big line, preserveNewlines', testLines, 1, bigChunks, bigChunks, bigFullEnd, false, false, execa);118test('Split stdout - 0 newlines, many chunks, preserveNewlines', testLines, 1, manyChunks, manyLines, manyFullEnd, false, false, execa);119test('Split stdout - n newlines, 1 chunk, objectMode, preserveNewlines', testLines, 1, simpleChunks, noNewlinesChunks, noNewlinesChunks, true, false, execa);120test('Split stderr - n newlines, 1 chunk, objectMode, preserveNewlines', testLines, 2, simpleChunks, noNewlinesChunks, noNewlinesChunks, true, false, execa);121test('Split stdio[*] - n newlines, 1 chunk, objectMode, preserveNewlines', testLines, 3, simpleChunks, noNewlinesChunks, noNewlinesChunks, true, false, execa);122test('Split stdout - preserveNewlines, n chunks, objectMode, preserveNewlines', testLines, 1, noNewlinesChunks, noNewlinesLines, noNewlinesLines, true, false, execa);123test('Split stdout - empty, 1 chunk, objectMode, preserveNewlines', testLines, 1, emptyChunks, noLines, noLines, true, false, execa);124test('Split stdout - 0 newlines, 1 chunk, objectMode, preserveNewlines', testLines, 1, singleChunks, singleChunks, singleChunks, true, false, execa);125test('Split stdout - Windows newlines, objectMode, preserveNewlines', testLines, 1, windowsChunks, noNewlinesChunks, noNewlinesChunks, true, false, execa);126test('Split stdout - chunk ends with newline, objectMode, preserveNewlines', testLines, 1, simpleFullEndChunks, noNewlinesChunks, noNewlinesChunks, true, false, execa);127test('Split stdout - single newline, objectMode, preserveNewlines', testLines, 1, newlineChunks, emptyChunks, emptyChunks, true, false, execa);128test('Split stdout - only newlines, objectMode, preserveNewlines', testLines, 1, newlinesChunks, manyEmptyChunks, manyEmptyChunks, true, false, execa);129test('Split stdout - only Windows newlines, objectMode, preserveNewlines', testLines, 1, windowsNewlinesChunks, manyEmptyChunks, manyEmptyChunks, true, false, execa);130test('Split stdout - line split over multiple chunks, objectMode, preserveNewlines', testLines, 1, runOverChunks, noNewlinesChunks, noNewlinesChunks, true, false, execa);131test('Split stdout - 0 newlines, big line, objectMode, preserveNewlines', testLines, 1, bigChunks, bigChunks, bigChunks, true, false, execa);132test('Split stdout - 0 newlines, many chunks, objectMode, preserveNewlines', testLines, 1, manyChunks, manyLines, manyLines, true, false, execa);133test('Split stdout - n newlines, 1 chunk, sync', testLines, 1, simpleChunks, simpleLines, simpleFull, false, true, execaSync);134test('Split stderr - n newlines, 1 chunk, sync', testLines, 2, simpleChunks, simpleLines, simpleFull, false, true, execaSync);135test('Split stdio[*] - n newlines, 1 chunk, sync', testLines, 3, simpleChunks, simpleLines, simpleFull, false, true, execaSync);136test('Split stdout - preserveNewlines, n chunks, sync', testLines, 1, noNewlinesChunks, noNewlinesLines, noNewlinesFull, false, true, execaSync);137test('Split stdout - 0 newlines, 1 chunk, sync', testLines, 1, singleChunks, singleChunks, singleFull, false, true, execaSync);138test('Split stdout - empty, 1 chunk, sync', testLines, 1, emptyChunks, noLines, emptyFull, false, true, execaSync);139test('Split stdout - Windows newlines, sync', testLines, 1, windowsChunks, windowsLines, windowsFull, false, true, execaSync);140test('Split stdout - chunk ends with newline, sync', testLines, 1, simpleFullEndChunks, simpleFullEndLines, simpleFullEnd, false, true, execaSync);141test('Split stdout - single newline, sync', testLines, 1, newlineChunks, newlineChunks, newlineFull, false, true, execaSync);142test('Split stdout - only newlines, sync', testLines, 1, newlinesChunks, newlinesLines, newlinesFull, false, true, execaSync);143test('Split stdout - only Windows newlines, sync', testLines, 1, windowsNewlinesChunks, windowsNewlinesLines, windowsNewlinesFull, false, true, execaSync);144test('Split stdout - line split over multiple chunks, sync', testLines, 1, runOverChunks, simpleLines, simpleFull, false, true, execaSync);145test('Split stdout - 0 newlines, big line, sync', testLines, 1, bigChunks, bigChunks, bigFull, false, true, execaSync);146test('Split stdout - 0 newlines, many chunks, sync', testLines, 1, manyChunks, manyLines, manyFull, false, true, execaSync);147test('Split stdout - n newlines, 1 chunk, objectMode, sync', testLines, 1, simpleChunks, simpleLines, simpleLines, true, true, execaSync);148test('Split stderr - n newlines, 1 chunk, objectMode, sync', testLines, 2, simpleChunks, simpleLines, simpleLines, true, true, execaSync);149test('Split stdio[*] - n newlines, 1 chunk, objectMode, sync', testLines, 3, simpleChunks, simpleLines, simpleLines, true, true, execaSync);150test('Split stdout - preserveNewlines, n chunks, objectMode, sync', testLines, 1, noNewlinesChunks, noNewlinesLines, noNewlinesLines, true, true, execaSync);151test('Split stdout - empty, 1 chunk, objectMode, sync', testLines, 1, emptyChunks, noLines, noLines, true, true, execaSync);152test('Split stdout - 0 newlines, 1 chunk, objectMode, sync', testLines, 1, singleChunks, singleChunks, singleChunks, true, true, execaSync);153test('Split stdout - Windows newlines, objectMode, sync', testLines, 1, windowsChunks, windowsLines, windowsLines, true, true, execaSync);154test('Split stdout - chunk ends with newline, objectMode, sync', testLines, 1, simpleFullEndChunks, simpleFullEndLines, simpleFullEndLines, true, true, execaSync);155test('Split stdout - single newline, objectMode, sync', testLines, 1, newlineChunks, newlineChunks, newlineChunks, true, true, execaSync);156test('Split stdout - only newlines, objectMode, sync', testLines, 1, newlinesChunks, newlinesLines, newlinesLines, true, true, execaSync);157test('Split stdout - only Windows newlines, objectMode, sync', testLines, 1, windowsNewlinesChunks, windowsNewlinesLines, windowsNewlinesLines, true, true, execaSync);158test('Split stdout - line split over multiple chunks, objectMode, sync', testLines, 1, runOverChunks, simpleLines, simpleLines, true, true, execaSync);159test('Split stdout - 0 newlines, big line, objectMode, sync', testLines, 1, bigChunks, bigChunks, bigChunks, true, true, execaSync);160test('Split stdout - 0 newlines, many chunks, objectMode, sync', testLines, 1, manyChunks, manyLines, manyLines, true, true, execaSync);161test('Split stdout - n newlines, 1 chunk, preserveNewlines, sync', testLines, 1, simpleChunks, noNewlinesChunks, simpleFullEnd, false, false, execaSync);162test('Split stderr - n newlines, 1 chunk, preserveNewlines, sync', testLines, 2, simpleChunks, noNewlinesChunks, simpleFullEnd, false, false, execaSync);163test('Split stdio[*] - n newlines, 1 chunk, preserveNewlines, sync', testLines, 3, simpleChunks, noNewlinesChunks, simpleFullEnd, false, false, execaSync);164test('Split stdout - preserveNewlines, n chunks, preserveNewlines, sync', testLines, 1, noNewlinesChunks, noNewlinesLines, noNewlinesFullEnd, false, false, execaSync);165test('Split stdout - empty, 1 chunk, preserveNewlines, sync', testLines, 1, emptyChunks, noLines, emptyFull, false, false, execaSync);166test('Split stdout - 0 newlines, 1 chunk, preserveNewlines, sync', testLines, 1, singleChunks, singleChunks, singleFullEnd, false, false, execaSync);167test('Split stdout - Windows newlines, preserveNewlines, sync', testLines, 1, windowsChunks, noNewlinesChunks, windowsFullEnd, false, false, execaSync);168test('Split stdout - chunk ends with newline, preserveNewlines, sync', testLines, 1, simpleFullEndChunks, noNewlinesChunks, simpleFullEnd, false, false, execaSync);169test('Split stdout - single newline, preserveNewlines, sync', testLines, 1, newlineChunks, emptyChunks, newlineFull, false, false, execaSync);170test('Split stdout - only newlines, preserveNewlines, sync', testLines, 1, newlinesChunks, manyEmptyChunks, newlinesFull, false, false, execaSync);171test('Split stdout - only Windows newlines, preserveNewlines, sync', testLines, 1, windowsNewlinesChunks, manyEmptyChunks, windowsNewlinesFull, false, false, execaSync);172test('Split stdout - line split over multiple chunks, preserveNewlines, sync', testLines, 1, runOverChunks, noNewlinesChunks, simpleFullEnd, false, false, execaSync);173test('Split stdout - 0 newlines, big line, preserveNewlines, sync', testLines, 1, bigChunks, bigChunks, bigFullEnd, false, false, execaSync);174test('Split stdout - 0 newlines, many chunks, preserveNewlines, sync', testLines, 1, manyChunks, manyLines, manyFullEnd, false, false, execaSync);175test('Split stdout - n newlines, 1 chunk, objectMode, preserveNewlines, sync', testLines, 1, simpleChunks, noNewlinesChunks, noNewlinesChunks, true, false, execaSync);176test('Split stderr - n newlines, 1 chunk, objectMode, preserveNewlines, sync', testLines, 2, simpleChunks, noNewlinesChunks, noNewlinesChunks, true, false, execaSync);177test('Split stdio[*] - n newlines, 1 chunk, objectMode, preserveNewlines, sync', testLines, 3, simpleChunks, noNewlinesChunks, noNewlinesChunks, true, false, execaSync);178test('Split stdout - preserveNewlines, n chunks, objectMode, preserveNewlines, sync', testLines, 1, noNewlinesChunks, noNewlinesLines, noNewlinesLines, true, false, execaSync);179test('Split stdout - empty, 1 chunk, objectMode, preserveNewlines, sync', testLines, 1, emptyChunks, noLines, noLines, true, false, execaSync);180test('Split stdout - 0 newlines, 1 chunk, objectMode, preserveNewlines, sync', testLines, 1, singleChunks, singleChunks, singleChunks, true, false, execaSync);181test('Split stdout - Windows newlines, objectMode, preserveNewlines, sync', testLines, 1, windowsChunks, noNewlinesChunks, noNewlinesChunks, true, false, execaSync);182test('Split stdout - chunk ends with newline, objectMode, preserveNewlines, sync', testLines, 1, simpleFullEndChunks, noNewlinesChunks, noNewlinesChunks, true, false, execaSync);183test('Split stdout - single newline, objectMode, preserveNewlines, sync', testLines, 1, newlineChunks, emptyChunks, emptyChunks, true, false, execaSync);184test('Split stdout - only newlines, objectMode, preserveNewlines, sync', testLines, 1, newlinesChunks, manyEmptyChunks, manyEmptyChunks, true, false, execaSync);185test('Split stdout - only Windows newlines, objectMode, preserveNewlines, sync', testLines, 1, windowsNewlinesChunks, manyEmptyChunks, manyEmptyChunks, true, false, execaSync);186test('Split stdout - line split over multiple chunks, objectMode, preserveNewlines, sync', testLines, 1, runOverChunks, noNewlinesChunks, noNewlinesChunks, true, false, execaSync);187test('Split stdout - 0 newlines, big line, objectMode, preserveNewlines, sync', testLines, 1, bigChunks, bigChunks, bigChunks, true, false, execaSync);188test('Split stdout - 0 newlines, many chunks, objectMode, preserveNewlines, sync', testLines, 1, manyChunks, manyLines, manyLines, true, false, execaSync);189190// eslint-disable-next-line max-params191const testBinaryOption = async (t, binary, input, expectedLines, expectedOutput, objectMode, preserveNewlines, encoding, execaMethod) => {192 const lines = [];193 const {stdout} = await execaMethod('noop.js', {194 stdout: [195 getOutputsGenerator(input)(false, true),196 resultGenerator(lines)(objectMode, binary, preserveNewlines),197 ],198 stripFinalNewline: false,199 encoding,200 });201 t.deepEqual(lines, expectedLines);202 t.deepEqual(stdout, expectedOutput);203};204205test('Does not split lines when "binary" is true', testBinaryOption, true, simpleChunks, simpleChunksUint8Array, simpleFull, false, true, 'utf8', execa);206test('Splits lines when "binary" is false', testBinaryOption, false, simpleChunks, simpleLines, simpleFull, false, true, 'utf8', execa);207test('Splits lines when "binary" is undefined', testBinaryOption, undefined, simpleChunks, simpleLines, simpleFull, false, true, 'utf8', execa);208test('Does not split lines when "binary" is true, encoding "utf16le"', testBinaryOption, true, simpleChunks, simpleChunksUint8Array, simpleFullUtf16Inverted, false, true, 'utf16le', execa);209test('Splits lines when "binary" is false, encoding "utf16le"', testBinaryOption, false, [simpleFullUtf16Uint8Array], simpleLines, simpleFullUtf16Inverted, false, true, 'utf16le', execa);210test('Splits lines when "binary" is undefined, encoding "utf16le"', testBinaryOption, undefined, [simpleFullUtf16Uint8Array], simpleLines, simpleFullUtf16Inverted, false, true, 'utf16le', execa);211test('Does not split lines when "binary" is true, encoding "buffer"', testBinaryOption, true, simpleChunks, simpleChunksUint8Array, simpleFullUint8Array, false, true, 'buffer', execa);212test('Does not split lines when "binary" is undefined, encoding "buffer"', testBinaryOption, undefined, simpleChunks, simpleChunksUint8Array, simpleFullUint8Array, false, true, 'buffer', execa);213test('Does not split lines when "binary" is false, encoding "buffer"', testBinaryOption, false, simpleChunks, simpleChunksUint8Array, simpleFullUint8Array, false, true, 'buffer', execa);214test('Does not split lines when "binary" is true, encoding "hex"', testBinaryOption, true, simpleChunks, simpleChunksUint8Array, simpleFullHex, false, true, 'hex', execa);215test('Does not split lines when "binary" is undefined, encoding "hex"', testBinaryOption, undefined, simpleChunks, simpleChunksUint8Array, simpleFullHex, false, true, 'hex', execa);216test('Does not split lines when "binary" is false, encoding "hex"', testBinaryOption, false, simpleChunks, simpleChunksUint8Array, simpleFullHex, false, true, 'hex', execa);217test('Does not split lines when "binary" is true, objectMode', testBinaryOption, true, simpleChunks, simpleChunksUint8Array, simpleChunksUint8Array, true, true, 'utf8', execa);218test('Splits lines when "binary" is false, objectMode', testBinaryOption, false, simpleChunks, simpleLines, simpleLines, true, true, 'utf8', execa);219test('Splits lines when "binary" is undefined, objectMode', testBinaryOption, undefined, simpleChunks, simpleLines, simpleLines, true, true, 'utf8', execa);220test('Does not split lines when "binary" is true, preserveNewlines', testBinaryOption, true, simpleChunks, simpleChunksUint8Array, simpleFull, false, false, 'utf8', execa);221test('Splits lines when "binary" is false, preserveNewlines', testBinaryOption, false, simpleChunks, noNewlinesChunks, simpleFullEnd, false, false, 'utf8', execa);222test('Splits lines when "binary" is undefined, preserveNewlines', testBinaryOption, undefined, simpleChunks, noNewlinesChunks, simpleFullEnd, false, false, 'utf8', execa);223test('Does not split lines when "binary" is true, preserveNewlines, encoding "utf16le"', testBinaryOption, true, simpleChunks, simpleChunksUint8Array, simpleFullUtf16Inverted, false, false, 'utf16le', execa);224test('Splits lines when "binary" is false, preserveNewlines, encoding "utf16le"', testBinaryOption, false, [simpleFullUtf16Uint8Array], noNewlinesChunks, simpleFullEndUtf16Inverted, false, false, 'utf16le', execa);225test('Splits lines when "binary" is undefined, preserveNewlines, encoding "utf16le"', testBinaryOption, undefined, [simpleFullUtf16Uint8Array], noNewlinesChunks, simpleFullEndUtf16Inverted, false, false, 'utf16le', execa);226test('Does not split lines when "binary" is true, encoding "buffer", preserveNewlines', testBinaryOption, true, simpleChunks, simpleChunksUint8Array, simpleFullUint8Array, false, false, 'buffer', execa);227test('Does not split lines when "binary" is undefined, encoding "buffer", preserveNewlines', testBinaryOption, undefined, simpleChunks, simpleChunksUint8Array, simpleFullUint8Array, false, false, 'buffer', execa);228test('Does not split lines when "binary" is false, encoding "buffer", preserveNewlines', testBinaryOption, false, simpleChunks, simpleChunksUint8Array, simpleFullUint8Array, false, false, 'buffer', execa);229test('Does not split lines when "binary" is true, objectMode, preserveNewlines', testBinaryOption, true, simpleChunks, simpleChunksUint8Array, simpleChunksUint8Array, true, false, 'utf8', execa);230test('Does not split lines when "binary" is true, encoding "hex", preserveNewlines', testBinaryOption, true, simpleChunks, simpleChunksUint8Array, simpleFullHex, false, false, 'hex', execa);231test('Does not split lines when "binary" is undefined, encoding "hex", preserveNewlines', testBinaryOption, undefined, simpleChunks, simpleChunksUint8Array, simpleFullHex, false, false, 'hex', execa);232test('Does not split lines when "binary" is false, encoding "hex", preserveNewlines', testBinaryOption, false, simpleChunks, simpleChunksUint8Array, simpleFullHex, false, false, 'hex', execa);233test('Splits lines when "binary" is false, objectMode, preserveNewlines', testBinaryOption, false, simpleChunks, noNewlinesChunks, noNewlinesChunks, true, false, 'utf8', execa);234test('Splits lines when "binary" is undefined, objectMode, preserveNewlines', testBinaryOption, undefined, simpleChunks, noNewlinesChunks, noNewlinesChunks, true, false, 'utf8', execa);235test('Does not split lines when "binary" is true, sync', testBinaryOption, true, simpleChunks, simpleChunksUint8Array, simpleFull, false, true, 'utf8', execaSync);236test('Splits lines when "binary" is false, sync', testBinaryOption, false, simpleChunks, simpleLines, simpleFull, false, true, 'utf8', execaSync);237test('Splits lines when "binary" is undefined, sync', testBinaryOption, undefined, simpleChunks, simpleLines, simpleFull, false, true, 'utf8', execaSync);238test('Does not split lines when "binary" is true, encoding "utf16le", sync', testBinaryOption, true, simpleChunks, simpleChunksUint8Array, simpleFullUtf16Inverted, false, true, 'utf16le', execaSync);239test('Splits lines when "binary" is false, encoding "utf16le", sync', testBinaryOption, false, [simpleFullUtf16Uint8Array], simpleLines, simpleFullUtf16Inverted, false, true, 'utf16le', execaSync);240test('Splits lines when "binary" is undefined, encoding "utf16le", sync', testBinaryOption, undefined, [simpleFullUtf16Uint8Array], simpleLines, simpleFullUtf16Inverted, false, true, 'utf16le', execaSync);241test('Does not split lines when "binary" is true, encoding "buffer", sync', testBinaryOption, true, simpleChunks, simpleChunksUint8Array, simpleFullUint8Array, false, true, 'buffer', execaSync);242test('Does not split lines when "binary" is undefined, encoding "buffer", sync', testBinaryOption, undefined, simpleChunks, simpleChunksUint8Array, simpleFullUint8Array, false, true, 'buffer', execaSync);243test('Does not split lines when "binary" is false, encoding "buffer", sync', testBinaryOption, false, simpleChunks, simpleChunksUint8Array, simpleFullUint8Array, false, true, 'buffer', execaSync);244test('Does not split lines when "binary" is true, encoding "hex", sync', testBinaryOption, true, simpleChunks, simpleChunksUint8Array, simpleFullHex, false, true, 'hex', execaSync);245test('Does not split lines when "binary" is undefined, encoding "hex", sync', testBinaryOption, undefined, simpleChunks, simpleChunksUint8Array, simpleFullHex, false, true, 'hex', execaSync);246test('Does not split lines when "binary" is false, encoding "hex", sync', testBinaryOption, false, simpleChunks, simpleChunksUint8Array, simpleFullHex, false, true, 'hex', execaSync);247test('Does not split lines when "binary" is true, objectMode, sync', testBinaryOption, true, simpleChunks, simpleChunksUint8Array, simpleChunksUint8Array, true, true, 'utf8', execaSync);248test('Splits lines when "binary" is false, objectMode, sync', testBinaryOption, false, simpleChunks, simpleLines, simpleLines, true, true, 'utf8', execaSync);249test('Splits lines when "binary" is undefined, objectMode, sync', testBinaryOption, undefined, simpleChunks, simpleLines, simpleLines, true, true, 'utf8', execaSync);250test('Does not split lines when "binary" is true, preserveNewlines, sync', testBinaryOption, true, simpleChunks, simpleChunksUint8Array, simpleFull, false, false, 'utf8', execaSync);251test('Splits lines when "binary" is false, preserveNewlines, sync', testBinaryOption, false, simpleChunks, noNewlinesChunks, simpleFullEnd, false, false, 'utf8', execaSync);252test('Splits lines when "binary" is undefined, preserveNewlines, sync', testBinaryOption, undefined, simpleChunks, noNewlinesChunks, simpleFullEnd, false, false, 'utf8', execaSync);253test('Does not split lines when "binary" is true, preserveNewlines, encoding "utf16le", sync', testBinaryOption, true, simpleChunks, simpleChunksUint8Array, simpleFullUtf16Inverted, false, false, 'utf16le', execaSync);254test('Splits lines when "binary" is false, preserveNewlines, encoding "utf16le", sync', testBinaryOption, false, [simpleFullUtf16Uint8Array], noNewlinesChunks, simpleFullEndUtf16Inverted, false, false, 'utf16le', execaSync);255test('Splits lines when "binary" is undefined, preserveNewlines, encoding "utf16le", sync', testBinaryOption, undefined, [simpleFullUtf16Uint8Array], noNewlinesChunks, simpleFullEndUtf16Inverted, false, false, 'utf16le', execaSync);256test('Does not split lines when "binary" is true, encoding "buffer", preserveNewlines, sync', testBinaryOption, true, simpleChunks, simpleChunksUint8Array, simpleFullUint8Array, false, false, 'buffer', execaSync);257test('Does not split lines when "binary" is undefined, encoding "buffer", preserveNewlines, sync', testBinaryOption, undefined, simpleChunks, simpleChunksUint8Array, simpleFullUint8Array, false, false, 'buffer', execaSync);258test('Does not split lines when "binary" is false, encoding "buffer", preserveNewlines, sync', testBinaryOption, false, simpleChunks, simpleChunksUint8Array, simpleFullUint8Array, false, false, 'buffer', execaSync);259test('Does not split lines when "binary" is true, objectMode, preserveNewlines, sync', testBinaryOption, true, simpleChunks, simpleChunksUint8Array, simpleChunksUint8Array, true, false, 'utf8', execaSync);260test('Does not split lines when "binary" is true, encoding "hex", preserveNewlines, sync', testBinaryOption, true, simpleChunks, simpleChunksUint8Array, simpleFullHex, false, false, 'hex', execaSync);261test('Does not split lines when "binary" is undefined, encoding "hex", preserveNewlines, sync', testBinaryOption, undefined, simpleChunks, simpleChunksUint8Array, simpleFullHex, false, false, 'hex', execaSync);262test('Does not split lines when "binary" is false, encoding "hex", preserveNewlines, sync', testBinaryOption, false, simpleChunks, simpleChunksUint8Array, simpleFullHex, false, false, 'hex', execaSync);263test('Splits lines when "binary" is false, objectMode, preserveNewlines, sync', testBinaryOption, false, simpleChunks, noNewlinesChunks, noNewlinesChunks, true, false, 'utf8', execaSync);264test('Splits lines when "binary" is undefined, objectMode, preserveNewlines, sync', testBinaryOption, undefined, simpleChunks, noNewlinesChunks, noNewlinesChunks, true, false, 'utf8', execaSync);265266const resultUint8ArrayGenerator = function * (lines, chunk) {267 lines.push(chunk);268 yield new TextEncoder().encode(chunk);269};270271// eslint-disable-next-line max-params272const testStringToUint8Array = async (t, expectedOutput, objectMode, preserveNewlines, execaMethod) => {273 const lines = [];274 const {stdout} = await execaMethod('noop-fd.js', ['1', foobarString], {275 stdout: {276 transform: resultUint8ArrayGenerator.bind(undefined, lines),277 objectMode,278 preserveNewlines,279 },280 lines: true,281 });282 t.deepEqual(lines, [foobarString]);283 t.deepEqual(stdout, expectedOutput);284};285286test('Line splitting when converting from string to Uint8Array', testStringToUint8Array, [foobarString], false, true, execa);287test('Line splitting when converting from string to Uint8Array, objectMode', testStringToUint8Array, [foobarUint8Array], true, true, execa);288test('Line splitting when converting from string to Uint8Array, preserveNewlines', testStringToUint8Array, [foobarString], false, false, execa);289test('Line splitting when converting from string to Uint8Array, objectMode, preserveNewlines', testStringToUint8Array, [foobarUint8Array], true, false, execa);290test('Line splitting when converting from string to Uint8Array, sync', testStringToUint8Array, [foobarString], false, true, execaSync);291test('Line splitting when converting from string to Uint8Array, objectMode, sync', testStringToUint8Array, [foobarUint8Array], true, true, execaSync);292test('Line splitting when converting from string to Uint8Array, preserveNewlines, sync', testStringToUint8Array, [foobarString], false, false, execaSync);293test('Line splitting when converting from string to Uint8Array, objectMode, preserveNewlines, sync', testStringToUint8Array, [foobarUint8Array], true, false, execaSync);294295const testStripNewline = async (t, input, expectedOutput, execaMethod) => {296 const {stdout} = await execaMethod('noop.js', {297 stdout: getOutputsGenerator([input])(),298 stripFinalNewline: false,299 });300 t.is(stdout, expectedOutput);301};302303test('Strips newline when user do not mistakenly yield one at the end', testStripNewline, singleFull, singleFullEnd, execa);304test('Strips newline when user mistakenly yielded one at the end', testStripNewline, singleFullEnd, singleFullEnd, execa);305test('Strips newline when user mistakenly yielded one at the end, Windows newline', testStripNewline, singleFullEndWindows, singleFullEndWindows, execa);306test('Strips newline when user do not mistakenly yield one at the end, sync', testStripNewline, singleFull, singleFullEnd, execaSync);307test('Strips newline when user mistakenly yielded one at the end, sync', testStripNewline, singleFullEnd, singleFullEnd, execaSync);308test('Strips newline when user mistakenly yielded one at the end, Windows newline, sync', testStripNewline, singleFullEndWindows, singleFullEndWindows, execaSync);309310const testMixNewlines = async (t, generator, execaMethod) => {311 const {stdout} = await execaMethod('noop-fd.js', ['1', mixedNewlines], {312 stdout: generator(),313 stripFinalNewline: false,314 });315 t.is(stdout, mixedNewlines);316};317318test('Can mix Unix and Windows newlines', testMixNewlines, noopGenerator, execa);319test('Can mix Unix and Windows newlines, sync', testMixNewlines, noopGenerator, execaSync);320test('Can mix Unix and Windows newlines, async', testMixNewlines, noopAsyncGenerator, execa);321322const serializeResultGenerator = function * (lines, chunk) {323 lines.push(chunk);324 yield JSON.stringify(chunk);325};326327const testUnsetObjectMode = async (t, expectedOutput, preserveNewlines, execaMethod) => {328 const lines = [];329 const {stdout} = await execaMethod('noop.js', {330 stdout: [331 getOutputsGenerator([foobarObject])(true),332 {transform: serializeResultGenerator.bind(undefined, lines), preserveNewlines, objectMode: false},333 ],334 stripFinalNewline: false,335 });336 t.deepEqual(lines, [foobarObject]);337 t.is(stdout, expectedOutput);338};339340test('Can switch from objectMode to non-objectMode', testUnsetObjectMode, `${foobarObjectString}\n`, false, execa);341test('Can switch from objectMode to non-objectMode, preserveNewlines', testUnsetObjectMode, foobarObjectString, true, execa);342test('Can switch from objectMode to non-objectMode, sync', testUnsetObjectMode, `${foobarObjectString}\n`, false, execaSync);343test('Can switch from objectMode to non-objectMode, preserveNewlines, sync', testUnsetObjectMode, foobarObjectString, true, execaSync);344345// eslint-disable-next-line max-params346const testYieldArray = async (t, input, expectedLines, expectedOutput, execaMethod) => {347 const lines = [];348 const {stdout} = await execaMethod('noop.js', {349 stdout: [350 getOutputsGenerator(input)(),351 resultGenerator(lines)(),352 ],353 stripFinalNewline: false,354 });355 t.deepEqual(lines, expectedLines);356 t.deepEqual(stdout, expectedOutput);357};358359test('Can use "yield* array" to produce multiple lines', testYieldArray, [foobarString, foobarString], [foobarString, foobarString], `${foobarString}\n${foobarString}\n`, execa);360test('Can use "yield* array" to produce empty lines', testYieldArray, [foobarString, ''], [foobarString, ''], `${foobarString}\n\n`, execa);361test('Can use "yield* array" to produce multiple lines, sync', testYieldArray, [foobarString, foobarString], [foobarString, foobarString], `${foobarString}\n${foobarString}\n`, execaSync);362test('Can use "yield* array" to produce empty lines, sync', testYieldArray, [foobarString, ''], [foobarString, ''], `${foobarString}\n\n`, execaSync);
added:test/stdio/transform-all.js+224 added
1import {Buffer} from 'node:buffer';2import test from 'ava';3import {execa, execaSync} from '../../index.js';4import {setFixtureDir} from '../helpers/fixtures-dir.js';5import {foobarObject} from '../helpers/input.js';6import {7 outputObjectGenerator,8 uppercaseGenerator,9 uppercaseBufferGenerator,10} from '../helpers/generator.js';1112setFixtureDir();1314const textEncoder = new TextEncoder();1516const getAllStdioOption = (stdioOption, encoding, objectMode) => {17 if (stdioOption) {18 return 'pipe';19 }2021 if (objectMode) {22 return outputObjectGenerator();23 }2425 return encoding === 'utf8' ? uppercaseGenerator() : uppercaseBufferGenerator();26};2728const getStdoutStderrOutput = ({output, stdioOption, encoding, objectMode, lines}) => {29 if (objectMode && !stdioOption) {30 return encoding === 'utf8' ? [foobarObject, foobarObject] : [foobarObject];31 }3233 const stdioOutput = stdioOption ? output : output.toUpperCase();3435 if (encoding === 'hex') {36 return Buffer.from(stdioOutput).toString('hex');37 }3839 if (encoding === 'buffer') {40 return textEncoder.encode(stdioOutput);41 }4243 return lines ? stdioOutput.trim().split('\n').map(string => `${string}\n`) : stdioOutput;44};4546const getAllOutput = ({stdoutOutput, stderrOutput, encoding, objectMode, lines}) => {47 if (objectMode || (lines && encoding === 'utf8')) {48 return [stdoutOutput, stderrOutput].flat();49 }5051 return encoding === 'buffer'52 ? new Uint8Array([...stdoutOutput, ...stderrOutput])53 : `${stdoutOutput}${stderrOutput}`;54};5556// eslint-disable-next-line max-params57const testGeneratorAll = async (t, reject, encoding, objectMode, stdoutOption, stderrOption, lines, execaMethod) => {58 const fixtureName = reject ? 'all.js' : 'all-fail.js';59 const {stdout, stderr, all} = await execaMethod(fixtureName, {60 all: true,61 reject,62 stdout: getAllStdioOption(stdoutOption, encoding, objectMode),63 stderr: getAllStdioOption(stderrOption, encoding, objectMode),64 encoding,65 lines,66 stripFinalNewline: false,67 });6869 const stdoutOutput = getStdoutStderrOutput({output: 'std\nout\n', stdioOption: stdoutOption, encoding, objectMode, lines});70 t.deepEqual(stdout, stdoutOutput);71 const stderrOutput = getStdoutStderrOutput({output: 'std\nerr\n', stdioOption: stderrOption, encoding, objectMode, lines});72 t.deepEqual(stderr, stderrOutput);73 const allOutput = getAllOutput({stdoutOutput, stderrOutput, encoding, objectMode, lines});74 if (Array.isArray(all) && Array.isArray(allOutput)) {75 t.deepEqual([...all].sort(), [...allOutput].sort());76 } else {77 t.deepEqual(all, allOutput);78 }79};8081test('Can use generators with result.all = transform + transform', testGeneratorAll, true, 'utf8', false, false, false, false, execa);82test('Can use generators with error.all = transform + transform', testGeneratorAll, false, 'utf8', false, false, false, false, execa);83test('Can use generators with result.all = transform + transform, encoding "buffer"', testGeneratorAll, true, 'buffer', false, false, false, false, execa);84test('Can use generators with error.all = transform + transform, encoding "buffer"', testGeneratorAll, false, 'buffer', false, false, false, false, execa);85test('Can use generators with result.all = transform + transform, encoding "hex"', testGeneratorAll, true, 'hex', false, false, false, false, execa);86test('Can use generators with error.all = transform + transform, encoding "hex"', testGeneratorAll, false, 'hex', false, false, false, false, execa);87test('Can use generators with result.all = transform + pipe', testGeneratorAll, true, 'utf8', false, false, true, false, execa);88test('Can use generators with error.all = transform + pipe', testGeneratorAll, false, 'utf8', false, false, true, false, execa);89test('Can use generators with result.all = transform + pipe, encoding "buffer"', testGeneratorAll, true, 'buffer', false, false, true, false, execa);90test('Can use generators with error.all = transform + pipe, encoding "buffer"', testGeneratorAll, false, 'buffer', false, false, true, false, execa);91test('Can use generators with result.all = transform + pipe, encoding "hex"', testGeneratorAll, true, 'hex', false, false, true, false, execa);92test('Can use generators with error.all = transform + pipe, encoding "hex"', testGeneratorAll, false, 'hex', false, false, true, false, execa);93test('Can use generators with result.all = pipe + transform', testGeneratorAll, true, 'utf8', false, true, false, false, execa);94test('Can use generators with error.all = pipe + transform', testGeneratorAll, false, 'utf8', false, true, false, false, execa);95test('Can use generators with result.all = pipe + transform, encoding "buffer"', testGeneratorAll, true, 'buffer', false, true, false, false, execa);96test('Can use generators with error.all = pipe + transform, encoding "buffer"', testGeneratorAll, false, 'buffer', false, true, false, false, execa);97test('Can use generators with result.all = pipe + transform, encoding "hex"', testGeneratorAll, true, 'hex', false, true, false, false, execa);98test('Can use generators with error.all = pipe + transform, encoding "hex"', testGeneratorAll, false, 'hex', false, true, false, false, execa);99test('Can use generators with result.all = transform + transform, objectMode', testGeneratorAll, true, 'utf8', true, false, false, false, execa);100test('Can use generators with error.all = transform + transform, objectMode', testGeneratorAll, false, 'utf8', true, false, false, false, execa);101test('Can use generators with result.all = transform + transform, objectMode, encoding "buffer"', testGeneratorAll, true, 'buffer', true, false, false, false, execa);102test('Can use generators with error.all = transform + transform, objectMode, encoding "buffer"', testGeneratorAll, false, 'buffer', true, false, false, false, execa);103test('Can use generators with result.all = transform + transform, objectMode, encoding "hex"', testGeneratorAll, true, 'hex', true, false, false, false, execa);104test('Can use generators with error.all = transform + transform, objectMode, encoding "hex"', testGeneratorAll, false, 'hex', true, false, false, false, execa);105test('Can use generators with result.all = transform + pipe, objectMode', testGeneratorAll, true, 'utf8', true, false, true, false, execa);106test('Can use generators with error.all = transform + pipe, objectMode', testGeneratorAll, false, 'utf8', true, false, true, false, execa);107test('Can use generators with result.all = transform + pipe, objectMode, encoding "buffer"', testGeneratorAll, true, 'buffer', true, false, true, false, execa);108test('Can use generators with error.all = transform + pipe, objectMode, encoding "buffer"', testGeneratorAll, false, 'buffer', true, false, true, false, execa);109test('Can use generators with result.all = transform + pipe, objectMode, encoding "hex"', testGeneratorAll, true, 'hex', true, false, true, false, execa);110test('Can use generators with error.all = transform + pipe, objectMode, encoding "hex"', testGeneratorAll, false, 'hex', true, false, true, false, execa);111test('Can use generators with result.all = pipe + transform, objectMode', testGeneratorAll, true, 'utf8', true, true, false, false, execa);112test('Can use generators with error.all = pipe + transform, objectMode', testGeneratorAll, false, 'utf8', true, true, false, false, execa);113test('Can use generators with result.all = pipe + transform, objectMode, encoding "buffer"', testGeneratorAll, true, 'buffer', true, true, false, false, execa);114test('Can use generators with error.all = pipe + transform, objectMode, encoding "buffer"', testGeneratorAll, false, 'buffer', true, true, false, false, execa);115test('Can use generators with result.all = pipe + transform, objectMode, encoding "hex"', testGeneratorAll, true, 'hex', true, true, false, false, execa);116test('Can use generators with error.all = pipe + transform, objectMode, encoding "hex"', testGeneratorAll, false, 'hex', true, true, false, false, execa);117test('Can use generators with result.all = transform + transform, sync', testGeneratorAll, true, 'utf8', false, false, false, false, execaSync);118test('Can use generators with error.all = transform + transform, sync', testGeneratorAll, false, 'utf8', false, false, false, false, execaSync);119test('Can use generators with result.all = transform + transform, encoding "buffer", sync', testGeneratorAll, true, 'buffer', false, false, false, false, execaSync);120test('Can use generators with error.all = transform + transform, encoding "buffer", sync', testGeneratorAll, false, 'buffer', false, false, false, false, execaSync);121test('Can use generators with result.all = transform + transform, encoding "hex", sync', testGeneratorAll, true, 'hex', false, false, false, false, execaSync);122test('Can use generators with error.all = transform + transform, encoding "hex", sync', testGeneratorAll, false, 'hex', false, false, false, false, execaSync);123test('Can use generators with result.all = transform + pipe, sync', testGeneratorAll, true, 'utf8', false, false, true, false, execaSync);124test('Can use generators with error.all = transform + pipe, sync', testGeneratorAll, false, 'utf8', false, false, true, false, execaSync);125test('Can use generators with result.all = transform + pipe, encoding "buffer", sync', testGeneratorAll, true, 'buffer', false, false, true, false, execaSync);126test('Can use generators with error.all = transform + pipe, encoding "buffer", sync', testGeneratorAll, false, 'buffer', false, false, true, false, execaSync);127test('Can use generators with result.all = transform + pipe, encoding "hex", sync', testGeneratorAll, true, 'hex', false, false, true, false, execaSync);128test('Can use generators with error.all = transform + pipe, encoding "hex", sync', testGeneratorAll, false, 'hex', false, false, true, false, execaSync);129test('Can use generators with result.all = pipe + transform, sync', testGeneratorAll, true, 'utf8', false, true, false, false, execaSync);130test('Can use generators with error.all = pipe + transform, sync', testGeneratorAll, false, 'utf8', false, true, false, false, execaSync);131test('Can use generators with result.all = pipe + transform, encoding "buffer", sync', testGeneratorAll, true, 'buffer', false, true, false, false, execaSync);132test('Can use generators with error.all = pipe + transform, encoding "buffer", sync', testGeneratorAll, false, 'buffer', false, true, false, false, execaSync);133test('Can use generators with result.all = pipe + transform, encoding "hex", sync', testGeneratorAll, true, 'hex', false, true, false, false, execaSync);134test('Can use generators with error.all = pipe + transform, encoding "hex", sync', testGeneratorAll, false, 'hex', false, true, false, false, execaSync);135test('Can use generators with result.all = transform + transform, objectMode, sync', testGeneratorAll, true, 'utf8', true, false, false, false, execaSync);136test('Can use generators with error.all = transform + transform, objectMode, sync', testGeneratorAll, false, 'utf8', true, false, false, false, execaSync);137test('Can use generators with result.all = transform + transform, objectMode, encoding "buffer", sync', testGeneratorAll, true, 'buffer', true, false, false, false, execaSync);138test('Can use generators with error.all = transform + transform, objectMode, encoding "buffer", sync', testGeneratorAll, false, 'buffer', true, false, false, false, execaSync);139test('Can use generators with result.all = transform + transform, objectMode, encoding "hex", sync', testGeneratorAll, true, 'hex', true, false, false, false, execaSync);140test('Can use generators with error.all = transform + transform, objectMode, encoding "hex", sync', testGeneratorAll, false, 'hex', true, false, false, false, execaSync);141test('Can use generators with result.all = transform + pipe, objectMode, sync', testGeneratorAll, true, 'utf8', true, false, true, false, execaSync);142test('Can use generators with error.all = transform + pipe, objectMode, sync', testGeneratorAll, false, 'utf8', true, false, true, false, execaSync);143test('Can use generators with result.all = transform + pipe, objectMode, encoding "buffer", sync', testGeneratorAll, true, 'buffer', true, false, true, false, execaSync);144test('Can use generators with error.all = transform + pipe, objectMode, encoding "buffer", sync', testGeneratorAll, false, 'buffer', true, false, true, false, execaSync);145test('Can use generators with result.all = transform + pipe, objectMode, encoding "hex", sync', testGeneratorAll, true, 'hex', true, false, true, false, execaSync);146test('Can use generators with error.all = transform + pipe, objectMode, encoding "hex", sync', testGeneratorAll, false, 'hex', true, false, true, false, execaSync);147test('Can use generators with result.all = pipe + transform, objectMode, sync', testGeneratorAll, true, 'utf8', true, true, false, false, execaSync);148test('Can use generators with error.all = pipe + transform, objectMode, sync', testGeneratorAll, false, 'utf8', true, true, false, false, execaSync);149test('Can use generators with result.all = pipe + transform, objectMode, encoding "buffer", sync', testGeneratorAll, true, 'buffer', true, true, false, false, execaSync);150test('Can use generators with error.all = pipe + transform, objectMode, encoding "buffer", sync', testGeneratorAll, false, 'buffer', true, true, false, false, execaSync);151test('Can use generators with result.all = pipe + transform, objectMode, encoding "hex", sync', testGeneratorAll, true, 'hex', true, true, false, false, execaSync);152test('Can use generators with error.all = pipe + transform, objectMode, encoding "hex", sync', testGeneratorAll, false, 'hex', true, true, false, false, execaSync);153test('Can use generators with result.all = transform + transform, lines', testGeneratorAll, true, 'utf8', false, false, false, true, execa);154test('Can use generators with error.all = transform + transform, lines', testGeneratorAll, false, 'utf8', false, false, false, true, execa);155test('Can use generators with result.all = transform + transform, encoding "buffer", lines', testGeneratorAll, true, 'buffer', false, false, false, true, execa);156test('Can use generators with error.all = transform + transform, encoding "buffer", lines', testGeneratorAll, false, 'buffer', false, false, false, true, execa);157test('Can use generators with result.all = transform + transform, encoding "hex", lines', testGeneratorAll, true, 'hex', false, false, false, true, execa);158test('Can use generators with error.all = transform + transform, encoding "hex", lines', testGeneratorAll, false, 'hex', false, false, false, true, execa);159test('Can use generators with result.all = transform + pipe, lines', testGeneratorAll, true, 'utf8', false, false, true, true, execa);160test('Can use generators with error.all = transform + pipe, lines', testGeneratorAll, false, 'utf8', false, false, true, true, execa);161test('Can use generators with result.all = transform + pipe, encoding "buffer", lines', testGeneratorAll, true, 'buffer', false, false, true, true, execa);162test('Can use generators with error.all = transform + pipe, encoding "buffer", lines', testGeneratorAll, false, 'buffer', false, false, true, true, execa);163test('Can use generators with result.all = transform + pipe, encoding "hex", lines', testGeneratorAll, true, 'hex', false, false, true, true, execa);164test('Can use generators with error.all = transform + pipe, encoding "hex", lines', testGeneratorAll, false, 'hex', false, false, true, true, execa);165test('Can use generators with result.all = pipe + transform, lines', testGeneratorAll, true, 'utf8', false, true, false, true, execa);166test('Can use generators with error.all = pipe + transform, lines', testGeneratorAll, false, 'utf8', false, true, false, true, execa);167test('Can use generators with result.all = pipe + transform, encoding "buffer", lines', testGeneratorAll, true, 'buffer', false, true, false, true, execa);168test('Can use generators with error.all = pipe + transform, encoding "buffer", lines', testGeneratorAll, false, 'buffer', false, true, false, true, execa);169test('Can use generators with result.all = pipe + transform, encoding "hex", lines', testGeneratorAll, true, 'hex', false, true, false, true, execa);170test('Can use generators with error.all = pipe + transform, encoding "hex", lines', testGeneratorAll, false, 'hex', false, true, false, true, execa);171test('Can use generators with result.all = transform + transform, objectMode, lines', testGeneratorAll, true, 'utf8', true, false, false, true, execa);172test('Can use generators with error.all = transform + transform, objectMode, lines', testGeneratorAll, false, 'utf8', true, false, false, true, execa);173test('Can use generators with result.all = transform + transform, objectMode, encoding "buffer", lines', testGeneratorAll, true, 'buffer', true, false, false, true, execa);174test('Can use generators with error.all = transform + transform, objectMode, encoding "buffer", lines', testGeneratorAll, false, 'buffer', true, false, false, true, execa);175test('Can use generators with result.all = transform + transform, objectMode, encoding "hex", lines', testGeneratorAll, true, 'hex', true, false, false, true, execa);176test('Can use generators with error.all = transform + transform, objectMode, encoding "hex", lines', testGeneratorAll, false, 'hex', true, false, false, true, execa);177test('Can use generators with result.all = transform + pipe, objectMode, lines', testGeneratorAll, true, 'utf8', true, false, true, true, execa);178test('Can use generators with error.all = transform + pipe, objectMode, lines', testGeneratorAll, false, 'utf8', true, false, true, true, execa);179test('Can use generators with result.all = transform + pipe, objectMode, encoding "buffer", lines', testGeneratorAll, true, 'buffer', true, false, true, true, execa);180test('Can use generators with error.all = transform + pipe, objectMode, encoding "buffer", lines', testGeneratorAll, false, 'buffer', true, false, true, true, execa);181test('Can use generators with result.all = transform + pipe, objectMode, encoding "hex", lines', testGeneratorAll, true, 'hex', true, false, true, true, execa);182test('Can use generators with error.all = transform + pipe, objectMode, encoding "hex", lines', testGeneratorAll, false, 'hex', true, false, true, true, execa);183test('Can use generators with result.all = pipe + transform, objectMode, lines', testGeneratorAll, true, 'utf8', true, true, false, true, execa);184test('Can use generators with error.all = pipe + transform, objectMode, lines', testGeneratorAll, false, 'utf8', true, true, false, true, execa);185test('Can use generators with result.all = pipe + transform, objectMode, encoding "buffer", lines', testGeneratorAll, true, 'buffer', true, true, false, true, execa);186test('Can use generators with error.all = pipe + transform, objectMode, encoding "buffer", lines', testGeneratorAll, false, 'buffer', true, true, false, true, execa);187test('Can use generators with result.all = pipe + transform, objectMode, encoding "hex", lines', testGeneratorAll, true, 'hex', true, true, false, true, execa);188test('Can use generators with error.all = pipe + transform, objectMode, encoding "hex", lines', testGeneratorAll, false, 'hex', true, true, false, true, execa);189test('Can use generators with result.all = transform + transform, sync, lines', testGeneratorAll, true, 'utf8', false, false, false, true, execaSync);190test('Can use generators with error.all = transform + transform, sync, lines', testGeneratorAll, false, 'utf8', false, false, false, true, execaSync);191test('Can use generators with result.all = transform + transform, encoding "buffer", sync, lines', testGeneratorAll, true, 'buffer', false, false, false, true, execaSync);192test('Can use generators with error.all = transform + transform, encoding "buffer", sync, lines', testGeneratorAll, false, 'buffer', false, false, false, true, execaSync);193test('Can use generators with result.all = transform + transform, encoding "hex", sync, lines', testGeneratorAll, true, 'hex', false, false, false, true, execaSync);194test('Can use generators with error.all = transform + transform, encoding "hex", sync, lines', testGeneratorAll, false, 'hex', false, false, false, true, execaSync);195test('Can use generators with result.all = transform + pipe, sync, lines', testGeneratorAll, true, 'utf8', false, false, true, true, execaSync);196test('Can use generators with error.all = transform + pipe, sync, lines', testGeneratorAll, false, 'utf8', false, false, true, true, execaSync);197test('Can use generators with result.all = transform + pipe, encoding "buffer", sync, lines', testGeneratorAll, true, 'buffer', false, false, true, true, execaSync);198test('Can use generators with error.all = transform + pipe, encoding "buffer", sync, lines', testGeneratorAll, false, 'buffer', false, false, true, true, execaSync);199test('Can use generators with result.all = transform + pipe, encoding "hex", sync, lines', testGeneratorAll, true, 'hex', false, false, true, true, execaSync);200test('Can use generators with error.all = transform + pipe, encoding "hex", sync, lines', testGeneratorAll, false, 'hex', false, false, true, true, execaSync);201test('Can use generators with result.all = pipe + transform, sync, lines', testGeneratorAll, true, 'utf8', false, true, false, true, execaSync);202test('Can use generators with error.all = pipe + transform, sync, lines', testGeneratorAll, false, 'utf8', false, true, false, true, execaSync);203test('Can use generators with result.all = pipe + transform, encoding "buffer", sync, lines', testGeneratorAll, true, 'buffer', false, true, false, true, execaSync);204test('Can use generators with error.all = pipe + transform, encoding "buffer", sync, lines', testGeneratorAll, false, 'buffer', false, true, false, true, execaSync);205test('Can use generators with result.all = pipe + transform, encoding "hex", sync, lines', testGeneratorAll, true, 'hex', false, true, false, true, execaSync);206test('Can use generators with error.all = pipe + transform, encoding "hex", sync, lines', testGeneratorAll, false, 'hex', false, true, false, true, execaSync);207test('Can use generators with result.all = transform + transform, objectMode, sync, lines', testGeneratorAll, true, 'utf8', true, false, false, true, execaSync);208test('Can use generators with error.all = transform + transform, objectMode, sync, lines', testGeneratorAll, false, 'utf8', true, false, false, true, execaSync);209test('Can use generators with result.all = transform + transform, objectMode, encoding "buffer", sync, lines', testGeneratorAll, true, 'buffer', true, false, false, true, execaSync);210test('Can use generators with error.all = transform + transform, objectMode, encoding "buffer", sync, lines', testGeneratorAll, false, 'buffer', true, false, false, true, execaSync);211test('Can use generators with result.all = transform + transform, objectMode, encoding "hex", sync, lines', testGeneratorAll, true, 'hex', true, false, false, true, execaSync);212test('Can use generators with error.all = transform + transform, objectMode, encoding "hex", sync, lines', testGeneratorAll, false, 'hex', true, false, false, true, execaSync);213test('Can use generators with result.all = transform + pipe, objectMode, sync, lines', testGeneratorAll, true, 'utf8', true, false, true, true, execaSync);214test('Can use generators with error.all = transform + pipe, objectMode, sync, lines', testGeneratorAll, false, 'utf8', true, false, true, true, execaSync);215test('Can use generators with result.all = transform + pipe, objectMode, encoding "buffer", sync, lines', testGeneratorAll, true, 'buffer', true, false, true, true, execaSync);216test('Can use generators with error.all = transform + pipe, objectMode, encoding "buffer", sync, lines', testGeneratorAll, false, 'buffer', true, false, true, true, execaSync);217test('Can use generators with result.all = transform + pipe, objectMode, encoding "hex", sync, lines', testGeneratorAll, true, 'hex', true, false, true, true, execaSync);218test('Can use generators with error.all = transform + pipe, objectMode, encoding "hex", sync, lines', testGeneratorAll, false, 'hex', true, false, true, true, execaSync);219test('Can use generators with result.all = pipe + transform, objectMode, sync, lines', testGeneratorAll, true, 'utf8', true, true, false, true, execaSync);220test('Can use generators with error.all = pipe + transform, objectMode, sync, lines', testGeneratorAll, false, 'utf8', true, true, false, true, execaSync);221test('Can use generators with result.all = pipe + transform, objectMode, encoding "buffer", sync, lines', testGeneratorAll, true, 'buffer', true, true, false, true, execaSync);222test('Can use generators with error.all = pipe + transform, objectMode, encoding "buffer", sync, lines', testGeneratorAll, false, 'buffer', true, true, false, true, execaSync);223test('Can use generators with result.all = pipe + transform, objectMode, encoding "hex", sync, lines', testGeneratorAll, true, 'hex', true, true, false, true, execaSync);224test('Can use generators with error.all = pipe + transform, objectMode, encoding "hex", sync, lines', testGeneratorAll, false, 'hex', true, true, false, true, execaSync);
added:test/stdio/transform-error.js+89 added
1import {once} from 'node:events';2import test from 'ava';3import {execa, execaSync} from '../../index.js';4import {foobarString} from '../helpers/input.js';5import {noopGenerator, infiniteGenerator, convertTransformToFinal} from '../helpers/generator.js';6import {generatorsMap} from '../helpers/map.js';7import {setFixtureDir} from '../helpers/fixtures-dir.js';89setFixtureDir();1011const assertProcessError = async (t, type, execaMethod, getSubprocess) => {12 const cause = new Error(foobarString);13 const transform = generatorsMap[type].throwing(cause)();14 const error = execaMethod === execa15 ? await t.throwsAsync(getSubprocess(transform))16 : t.throws(() => {17 getSubprocess(transform);18 });19 t.is(error.cause, cause);20};2122const testThrowingGenerator = async (t, type, final, execaMethod) => {23 await assertProcessError(t, type, execaMethod, transform => execaMethod('noop.js', {24 stdout: convertTransformToFinal(transform, final),25 }));26};2728test('Generators "transform" errors make subprocess fail', testThrowingGenerator, 'generator', false, execa);29test('Generators "final" errors make subprocess fail', testThrowingGenerator, 'generator', true, execa);30test('Generators "transform" errors make subprocess fail, sync', testThrowingGenerator, 'generator', false, execaSync);31test('Generators "final" errors make subprocess fail, sync', testThrowingGenerator, 'generator', true, execaSync);32test('Duplexes "transform" errors make subprocess fail', testThrowingGenerator, 'duplex', false, execa);33test('WebTransform "transform" errors make subprocess fail', testThrowingGenerator, 'webTransform', false, execa);3435const testSingleErrorOutput = async (t, type, execaMethod) => {36 await assertProcessError(t, type, execaMethod, transform => execaMethod('noop.js', {37 stdout: [38 generatorsMap[type].noop(false),39 transform,40 generatorsMap[type].noop(false),41 ],42 }));43};4445test('Generators errors make subprocess fail even when other output generators do not throw', testSingleErrorOutput, 'generator', execa);46test('Generators errors make subprocess fail even when other output generators do not throw, sync', testSingleErrorOutput, 'generator', execaSync);47test('Duplexes errors make subprocess fail even when other output generators do not throw', testSingleErrorOutput, 'duplex', execa);48test('WebTransform errors make subprocess fail even when other output generators do not throw', testSingleErrorOutput, 'webTransform', execa);4950const testSingleErrorInput = async (t, type, execaMethod) => {51 await assertProcessError(t, type, execaMethod, transform => execaMethod('stdin.js', {52 stdin: [53 ['foobar\n'],54 generatorsMap[type].noop(false),55 transform,56 generatorsMap[type].noop(false),57 ],58 }));59};6061test('Generators errors make subprocess fail even when other input generators do not throw', testSingleErrorInput, 'generator', execa);62test('Generators errors make subprocess fail even when other input generators do not throw, sync', testSingleErrorInput, 'generator', execaSync);63test('Duplexes errors make subprocess fail even when other input generators do not throw', testSingleErrorInput, 'duplex', execa);64test('WebTransform errors make subprocess fail even when other input generators do not throw', testSingleErrorInput, 'webTransform', execa);6566const testGeneratorCancel = async (t, error) => {67 const subprocess = execa('noop.js', {stdout: infiniteGenerator()});68 await once(subprocess.stdout, 'data');69 subprocess.stdout.destroy(error);70 await (error === undefined ? t.notThrowsAsync(subprocess) : t.throwsAsync(subprocess));71};7273test('Running generators are canceled on subprocess abort', testGeneratorCancel, undefined);74test('Running generators are canceled on subprocess error', testGeneratorCancel, new Error('test'));7576const testGeneratorDestroy = async (t, transform) => {77 const subprocess = execa('forever.js', {stdout: transform});78 const cause = new Error('test');79 subprocess.stdout.destroy(cause);80 subprocess.kill();81 t.like(await t.throwsAsync(subprocess), {cause});82};8384test('Generators are destroyed on subprocess error, sync', testGeneratorDestroy, noopGenerator(false));85test('Generators are destroyed on subprocess error, async', testGeneratorDestroy, infiniteGenerator());8687test('Generators are destroyed on early subprocess exit', async t => {88 await t.throwsAsync(execa('noop.js', {stdout: infiniteGenerator(), uid: -1}));89});
added:test/stdio/transform-final.js+35 added
1import test from 'ava';2import {execa, execaSync} from '../../index.js';3import {foobarString} from '../helpers/input.js';4import {getOutputAsyncGenerator, getOutputGenerator, convertTransformToFinal} from '../helpers/generator.js';5import {setFixtureDir} from '../helpers/fixtures-dir.js';67setFixtureDir();89const testGeneratorFinal = async (t, fixtureName, execaMethod) => {10 const {stdout} = await execaMethod(fixtureName, {stdout: convertTransformToFinal(getOutputGenerator(foobarString)(), true)});11 t.is(stdout, foobarString);12};1314test('Generators "final" can be used', testGeneratorFinal, 'noop.js', execa);15test('Generators "final" is used even on empty streams', testGeneratorFinal, 'empty.js', execa);16test('Generators "final" can be used, sync', testGeneratorFinal, 'noop.js', execaSync);17test('Generators "final" is used even on empty streams, sync', testGeneratorFinal, 'empty.js', execaSync);1819const testFinalAlone = async (t, final, execaMethod) => {20 const {stdout} = await execaMethod('noop-fd.js', ['1', '.'], {stdout: {final: final(foobarString)().transform, binary: true}});21 t.is(stdout, `.${foobarString}`);22};2324test('Generators "final" can be used without "transform"', testFinalAlone, getOutputGenerator, execa);25test('Generators "final" can be used without "transform", sync', testFinalAlone, getOutputGenerator, execaSync);26test('Generators "final" can be used without "transform", async', testFinalAlone, getOutputAsyncGenerator, execa);2728const testFinalNoOutput = async (t, final, execaMethod) => {29 const {stdout} = await execaMethod('empty.js', {stdout: {final: final(foobarString)().transform}});30 t.is(stdout, foobarString);31};3233test('Generators "final" can be used without "transform" nor output', testFinalNoOutput, getOutputGenerator, execa);34test('Generators "final" can be used without "transform" nor output, sync', testFinalNoOutput, getOutputGenerator, execaSync);35test('Generators "final" can be used without "transform" nor output, async', testFinalNoOutput, getOutputAsyncGenerator, execa);
added:test/stdio/transform-input.js+158 added
1import {Buffer} from 'node:buffer';2import test from 'ava';3import {execa, execaSync} from '../../index.js';4import {setFixtureDir} from '../helpers/fixtures-dir.js';5import {getStdio} from '../helpers/stdio.js';6import {7 foobarString,8 foobarUppercase,9 foobarHex,10 foobarUint8Array,11 foobarBuffer,12 foobarObject,13 foobarObjectString,14} from '../helpers/input.js';15import {generatorsMap} from '../helpers/map.js';1617setFixtureDir();1819const getInputObjectMode = (objectMode, addNoopTransform, type) => objectMode20 ? {21 input: [foobarObject],22 generators: generatorsMap[type].addNoop(generatorsMap[type].serialize(objectMode), addNoopTransform, objectMode),23 output: foobarObjectString,24 }25 : {26 input: foobarUint8Array,27 generators: generatorsMap[type].addNoop(generatorsMap[type].uppercase(objectMode), addNoopTransform, objectMode),28 output: foobarUppercase,29 };3031// eslint-disable-next-line max-params32const testGeneratorInput = async (t, fdNumber, objectMode, addNoopTransform, type, execaMethod) => {33 const {input, generators, output} = getInputObjectMode(objectMode, addNoopTransform, type);34 const {stdout} = await execaMethod('stdin-fd.js', [`${fdNumber}`], getStdio(fdNumber, [input, ...generators]));35 t.is(stdout, output);36};3738test('Can use generators with result.stdin', testGeneratorInput, 0, false, false, 'generator', execa);39test('Can use generators with result.stdio[*] as input', testGeneratorInput, 3, false, false, 'generator', execa);40test('Can use generators with result.stdin, objectMode', testGeneratorInput, 0, true, false, 'generator', execa);41test('Can use generators with result.stdio[*] as input, objectMode', testGeneratorInput, 3, true, false, 'generator', execa);42test('Can use generators with result.stdin, noop transform', testGeneratorInput, 0, false, true, 'generator', execa);43test('Can use generators with result.stdio[*] as input, noop transform', testGeneratorInput, 3, false, true, 'generator', execa);44test('Can use generators with result.stdin, objectMode, noop transform', testGeneratorInput, 0, true, true, 'generator', execa);45test('Can use generators with result.stdio[*] as input, objectMode, noop transform', testGeneratorInput, 3, true, true, 'generator', execa);46test('Can use generators with result.stdin, sync', testGeneratorInput, 0, false, false, 'generator', execaSync);47test('Can use generators with result.stdin, objectMode, sync', testGeneratorInput, 0, true, false, 'generator', execaSync);48test('Can use generators with result.stdin, noop transform, sync', testGeneratorInput, 0, false, true, 'generator', execaSync);49test('Can use generators with result.stdin, objectMode, noop transform, sync', testGeneratorInput, 0, true, true, 'generator', execaSync);50test('Can use duplexes with result.stdin', testGeneratorInput, 0, false, false, 'duplex', execa);51test('Can use duplexes with result.stdio[*] as input', testGeneratorInput, 3, false, false, 'duplex', execa);52test('Can use duplexes with result.stdin, objectMode', testGeneratorInput, 0, true, false, 'duplex', execa);53test('Can use duplexes with result.stdio[*] as input, objectMode', testGeneratorInput, 3, true, false, 'duplex', execa);54test('Can use duplexes with result.stdin, noop transform', testGeneratorInput, 0, false, true, 'duplex', execa);55test('Can use duplexes with result.stdio[*] as input, noop transform', testGeneratorInput, 3, false, true, 'duplex', execa);56test('Can use duplexes with result.stdin, objectMode, noop transform', testGeneratorInput, 0, true, true, 'duplex', execa);57test('Can use duplexes with result.stdio[*] as input, objectMode, noop transform', testGeneratorInput, 3, true, true, 'duplex', execa);58test('Can use webTransforms with result.stdin', testGeneratorInput, 0, false, false, 'webTransform', execa);59test('Can use webTransforms with result.stdio[*] as input', testGeneratorInput, 3, false, false, 'webTransform', execa);60test('Can use webTransforms with result.stdin, objectMode', testGeneratorInput, 0, true, false, 'webTransform', execa);61test('Can use webTransforms with result.stdio[*] as input, objectMode', testGeneratorInput, 3, true, false, 'webTransform', execa);62test('Can use webTransforms with result.stdin, noop transform', testGeneratorInput, 0, false, true, 'webTransform', execa);63test('Can use webTransforms with result.stdio[*] as input, noop transform', testGeneratorInput, 3, false, true, 'webTransform', execa);64test('Can use webTransforms with result.stdin, objectMode, noop transform', testGeneratorInput, 0, true, true, 'webTransform', execa);65test('Can use webTransforms with result.stdio[*] as input, objectMode, noop transform', testGeneratorInput, 3, true, true, 'webTransform', execa);6667// eslint-disable-next-line max-params68const testGeneratorInputPipe = async (t, useShortcutProperty, objectMode, addNoopTransform, type, input) => {69 const {generators, output} = getInputObjectMode(objectMode, addNoopTransform, type);70 const subprocess = execa('stdin-fd.js', ['0'], getStdio(0, generators));71 const stream = useShortcutProperty ? subprocess.stdin : subprocess.stdio[0];72 stream.end(...input);73 const {stdout} = await subprocess;74 const expectedOutput = input[1] === 'utf16le' ? Buffer.from(output, input[1]).toString() : output;75 t.is(stdout, expectedOutput);76};7778test('Can use generators with subprocess.stdio[0] and default encoding', testGeneratorInputPipe, false, false, false, 'generator', [foobarString, 'utf8']);79test('Can use generators with subprocess.stdin and default encoding', testGeneratorInputPipe, true, false, false, 'generator', [foobarString, 'utf8']);80test('Can use generators with subprocess.stdio[0] and encoding "utf16le"', testGeneratorInputPipe, false, false, false, 'generator', [foobarString, 'utf16le']);81test('Can use generators with subprocess.stdin and encoding "utf16le"', testGeneratorInputPipe, true, false, false, 'generator', [foobarString, 'utf16le']);82test('Can use generators with subprocess.stdio[0] and encoding "buffer"', testGeneratorInputPipe, false, false, false, 'generator', [foobarBuffer, 'buffer']);83test('Can use generators with subprocess.stdin and encoding "buffer"', testGeneratorInputPipe, true, false, false, 'generator', [foobarBuffer, 'buffer']);84test('Can use generators with subprocess.stdio[0] and encoding "hex"', testGeneratorInputPipe, false, false, false, 'generator', [foobarHex, 'hex']);85test('Can use generators with subprocess.stdin and encoding "hex"', testGeneratorInputPipe, true, false, false, 'generator', [foobarHex, 'hex']);86test('Can use generators with subprocess.stdio[0], objectMode', testGeneratorInputPipe, false, true, false, 'generator', [foobarObject]);87test('Can use generators with subprocess.stdin, objectMode', testGeneratorInputPipe, true, true, false, 'generator', [foobarObject]);88test('Can use generators with subprocess.stdio[0] and default encoding, noop transform', testGeneratorInputPipe, false, false, true, 'generator', [foobarString, 'utf8']);89test('Can use generators with subprocess.stdin and default encoding, noop transform', testGeneratorInputPipe, true, false, true, 'generator', [foobarString, 'utf8']);90test('Can use generators with subprocess.stdio[0] and encoding "utf16le", noop transform', testGeneratorInputPipe, false, false, true, 'generator', [foobarString, 'utf16le']);91test('Can use generators with subprocess.stdin and encoding "utf16le", noop transform', testGeneratorInputPipe, true, false, true, 'generator', [foobarString, 'utf16le']);92test('Can use generators with subprocess.stdio[0] and encoding "buffer", noop transform', testGeneratorInputPipe, false, false, true, 'generator', [foobarBuffer, 'buffer']);93test('Can use generators with subprocess.stdin and encoding "buffer", noop transform', testGeneratorInputPipe, true, false, true, 'generator', [foobarBuffer, 'buffer']);94test('Can use generators with subprocess.stdio[0] and encoding "hex", noop transform', testGeneratorInputPipe, false, false, true, 'generator', [foobarHex, 'hex']);95test('Can use generators with subprocess.stdin and encoding "hex", noop transform', testGeneratorInputPipe, true, false, true, 'generator', [foobarHex, 'hex']);96test('Can use generators with subprocess.stdio[0], objectMode, noop transform', testGeneratorInputPipe, false, true, true, 'generator', [foobarObject]);97test('Can use generators with subprocess.stdin, objectMode, noop transform', testGeneratorInputPipe, true, true, true, 'generator', [foobarObject]);98test('Can use duplexes with subprocess.stdio[0] and default encoding', testGeneratorInputPipe, false, false, false, 'duplex', [foobarString, 'utf8']);99test('Can use duplexes with subprocess.stdin and default encoding', testGeneratorInputPipe, true, false, false, 'duplex', [foobarString, 'utf8']);100test('Can use duplexes with subprocess.stdio[0] and encoding "utf16le"', testGeneratorInputPipe, false, false, false, 'duplex', [foobarString, 'utf16le']);101test('Can use duplexes with subprocess.stdin and encoding "utf16le"', testGeneratorInputPipe, true, false, false, 'duplex', [foobarString, 'utf16le']);102test('Can use duplexes with subprocess.stdio[0] and encoding "buffer"', testGeneratorInputPipe, false, false, false, 'duplex', [foobarBuffer, 'buffer']);103test('Can use duplexes with subprocess.stdin and encoding "buffer"', testGeneratorInputPipe, true, false, false, 'duplex', [foobarBuffer, 'buffer']);104test('Can use duplexes with subprocess.stdio[0] and encoding "hex"', testGeneratorInputPipe, false, false, false, 'duplex', [foobarHex, 'hex']);105test('Can use duplexes with subprocess.stdin and encoding "hex"', testGeneratorInputPipe, true, false, false, 'duplex', [foobarHex, 'hex']);106test('Can use duplexes with subprocess.stdio[0], objectMode', testGeneratorInputPipe, false, true, false, 'duplex', [foobarObject]);107test('Can use duplexes with subprocess.stdin, objectMode', testGeneratorInputPipe, true, true, false, 'duplex', [foobarObject]);108test('Can use duplexes with subprocess.stdio[0] and default encoding, noop transform', testGeneratorInputPipe, false, false, true, 'duplex', [foobarString, 'utf8']);109test('Can use duplexes with subprocess.stdin and default encoding, noop transform', testGeneratorInputPipe, true, false, true, 'duplex', [foobarString, 'utf8']);110test('Can use duplexes with subprocess.stdio[0] and encoding "utf16le", noop transform', testGeneratorInputPipe, false, false, true, 'duplex', [foobarString, 'utf16le']);111test('Can use duplexes with subprocess.stdin and encoding "utf16le", noop transform', testGeneratorInputPipe, true, false, true, 'duplex', [foobarString, 'utf16le']);112test('Can use duplexes with subprocess.stdio[0] and encoding "buffer", noop transform', testGeneratorInputPipe, false, false, true, 'duplex', [foobarBuffer, 'buffer']);113test('Can use duplexes with subprocess.stdin and encoding "buffer", noop transform', testGeneratorInputPipe, true, false, true, 'duplex', [foobarBuffer, 'buffer']);114test('Can use duplexes with subprocess.stdio[0] and encoding "hex", noop transform', testGeneratorInputPipe, false, false, true, 'duplex', [foobarHex, 'hex']);115test('Can use duplexes with subprocess.stdin and encoding "hex", noop transform', testGeneratorInputPipe, true, false, true, 'duplex', [foobarHex, 'hex']);116test('Can use duplexes with subprocess.stdio[0], objectMode, noop transform', testGeneratorInputPipe, false, true, true, 'duplex', [foobarObject]);117test('Can use duplexes with subprocess.stdin, objectMode, noop transform', testGeneratorInputPipe, true, true, true, 'duplex', [foobarObject]);118test('Can use webTransforms with subprocess.stdio[0] and default encoding', testGeneratorInputPipe, false, false, false, 'webTransform', [foobarString, 'utf8']);119test('Can use webTransforms with subprocess.stdin and default encoding', testGeneratorInputPipe, true, false, false, 'webTransform', [foobarString, 'utf8']);120test('Can use webTransforms with subprocess.stdio[0] and encoding "utf16le"', testGeneratorInputPipe, false, false, false, 'webTransform', [foobarString, 'utf16le']);121test('Can use webTransforms with subprocess.stdin and encoding "utf16le"', testGeneratorInputPipe, true, false, false, 'webTransform', [foobarString, 'utf16le']);122test('Can use webTransforms with subprocess.stdio[0] and encoding "buffer"', testGeneratorInputPipe, false, false, false, 'webTransform', [foobarBuffer, 'buffer']);123test('Can use webTransforms with subprocess.stdin and encoding "buffer"', testGeneratorInputPipe, true, false, false, 'webTransform', [foobarBuffer, 'buffer']);124test('Can use webTransforms with subprocess.stdio[0] and encoding "hex"', testGeneratorInputPipe, false, false, false, 'webTransform', [foobarHex, 'hex']);125test('Can use webTransforms with subprocess.stdin and encoding "hex"', testGeneratorInputPipe, true, false, false, 'webTransform', [foobarHex, 'hex']);126test('Can use webTransforms with subprocess.stdio[0], objectMode', testGeneratorInputPipe, false, true, false, 'webTransform', [foobarObject]);127test('Can use webTransforms with subprocess.stdin, objectMode', testGeneratorInputPipe, true, true, false, 'webTransform', [foobarObject]);128test('Can use webTransforms with subprocess.stdio[0] and default encoding, noop transform', testGeneratorInputPipe, false, false, true, 'webTransform', [foobarString, 'utf8']);129test('Can use webTransforms with subprocess.stdin and default encoding, noop transform', testGeneratorInputPipe, true, false, true, 'webTransform', [foobarString, 'utf8']);130test('Can use webTransforms with subprocess.stdio[0] and encoding "utf16le", noop transform', testGeneratorInputPipe, false, false, true, 'webTransform', [foobarString, 'utf16le']);131test('Can use webTransforms with subprocess.stdin and encoding "utf16le", noop transform', testGeneratorInputPipe, true, false, true, 'webTransform', [foobarString, 'utf16le']);132test('Can use webTransforms with subprocess.stdio[0] and encoding "buffer", noop transform', testGeneratorInputPipe, false, false, true, 'webTransform', [foobarBuffer, 'buffer']);133test('Can use webTransforms with subprocess.stdin and encoding "buffer", noop transform', testGeneratorInputPipe, true, false, true, 'webTransform', [foobarBuffer, 'buffer']);134test('Can use webTransforms with subprocess.stdio[0] and encoding "hex", noop transform', testGeneratorInputPipe, false, false, true, 'webTransform', [foobarHex, 'hex']);135test('Can use webTransforms with subprocess.stdin and encoding "hex", noop transform', testGeneratorInputPipe, true, false, true, 'webTransform', [foobarHex, 'hex']);136test('Can use webTransforms with subprocess.stdio[0], objectMode, noop transform', testGeneratorInputPipe, false, true, true, 'webTransform', [foobarObject]);137test('Can use webTransforms with subprocess.stdin, objectMode, noop transform', testGeneratorInputPipe, true, true, true, 'webTransform', [foobarObject]);138139const testGeneratorStdioInputPipe = async (t, objectMode, addNoopTransform, type) => {140 const {input, generators, output} = getInputObjectMode(objectMode, addNoopTransform, type);141 const subprocess = execa('stdin-fd.js', ['3'], getStdio(3, [[], ...generators]));142 subprocess.stdio[3].write(Array.isArray(input) ? input[0] : input);143 const {stdout} = await subprocess;144 t.is(stdout, output);145};146147test('Can use generators with subprocess.stdio[*] as input', testGeneratorStdioInputPipe, false, false, 'generator');148test('Can use generators with subprocess.stdio[*] as input, objectMode', testGeneratorStdioInputPipe, true, false, 'generator');149test('Can use generators with subprocess.stdio[*] as input, noop transform', testGeneratorStdioInputPipe, false, true, 'generator');150test('Can use generators with subprocess.stdio[*] as input, objectMode, noop transform', testGeneratorStdioInputPipe, true, true, 'generator');151test('Can use duplexes with subprocess.stdio[*] as input', testGeneratorStdioInputPipe, false, false, 'duplex');152test('Can use duplexes with subprocess.stdio[*] as input, objectMode', testGeneratorStdioInputPipe, true, false, 'duplex');153test('Can use duplexes with subprocess.stdio[*] as input, noop transform', testGeneratorStdioInputPipe, false, true, 'duplex');154test('Can use duplexes with subprocess.stdio[*] as input, objectMode, noop transform', testGeneratorStdioInputPipe, true, true, 'duplex');155test('Can use webTransforms with subprocess.stdio[*] as input', testGeneratorStdioInputPipe, false, false, 'webTransform');156test('Can use webTransforms with subprocess.stdio[*] as input, objectMode', testGeneratorStdioInputPipe, true, false, 'webTransform');157test('Can use webTransforms with subprocess.stdio[*] as input, noop transform', testGeneratorStdioInputPipe, false, true, 'webTransform');158test('Can use webTransforms with subprocess.stdio[*] as input, objectMode, noop transform', testGeneratorStdioInputPipe, true, true, 'webTransform');
added:test/stdio/transform-mixed.js+104 added
1import {readFile, writeFile, rm} from 'node:fs/promises';2import {PassThrough} from 'node:stream';3import test from 'ava';4import getStream from 'get-stream';5import tempfile from 'tempfile';6import {execa, execaSync} from '../../index.js';7import {setFixtureDir} from '../helpers/fixtures-dir.js';8import {foobarString, foobarUppercase, foobarUint8Array} from '../helpers/input.js';9import {uppercaseGenerator} from '../helpers/generator.js';10import {uppercaseBufferDuplex} from '../helpers/duplex.js';11import {uppercaseBufferWebTransform} from '../helpers/web-transform.js';12import {generatorsMap} from '../helpers/map.js';1314setFixtureDir();1516const testInputOption = async (t, type, execaMethod) => {17 const {stdout} = await execaMethod('stdin-fd.js', ['0'], {stdin: generatorsMap[type].uppercase(), input: foobarUint8Array});18 t.is(stdout, foobarUppercase);19};2021test('Can use generators with input option', testInputOption, 'generator', execa);22test('Can use generators with input option, sync', testInputOption, 'generator', execaSync);23test('Can use duplexes with input option', testInputOption, 'duplex', execa);24test('Can use webTransforms with input option', testInputOption, 'webTransform', execa);2526// eslint-disable-next-line max-params27const testInputFile = async (t, stdinOption, useInputFile, reversed, execaMethod) => {28 const filePath = tempfile();29 await writeFile(filePath, foobarString);30 const options = useInputFile31 ? {inputFile: filePath, stdin: stdinOption}32 : {stdin: [{file: filePath}, stdinOption]};33 options.stdin = reversed ? options.stdin.reverse() : options.stdin;34 const {stdout} = await execaMethod('stdin-fd.js', ['0'], options);35 t.is(stdout, foobarUppercase);36 await rm(filePath);37};3839test('Can use generators with a file as input', testInputFile, uppercaseGenerator(), false, false, execa);40test('Can use generators with a file as input, reversed', testInputFile, uppercaseGenerator(), false, true, execa);41test('Can use generators with inputFile option', testInputFile, uppercaseGenerator(), true, false, execa);42test('Can use generators with a file as input, sync', testInputFile, uppercaseGenerator(), false, false, execaSync);43test('Can use generators with a file as input, reversed, sync', testInputFile, uppercaseGenerator(), false, true, execaSync);44test('Can use generators with inputFile option, sync', testInputFile, uppercaseGenerator(), true, false, execaSync);45test('Can use duplexes with a file as input', testInputFile, uppercaseBufferDuplex(), false, false, execa);46test('Can use duplexes with a file as input, reversed', testInputFile, uppercaseBufferDuplex(), false, true, execa);47test('Can use duplexes with inputFile option', testInputFile, uppercaseBufferDuplex(), true, false, execa);48test('Can use webTransforms with a file as input', testInputFile, uppercaseBufferWebTransform(), false, false, execa);49test('Can use webTransforms with a file as input, reversed', testInputFile, uppercaseBufferWebTransform(), false, true, execa);50test('Can use webTransforms with inputFile option', testInputFile, uppercaseBufferWebTransform(), true, false, execa);5152const testOutputFile = async (t, reversed, type, execaMethod) => {53 const filePath = tempfile();54 const stdoutOption = [generatorsMap[type].uppercaseBuffer(false, true), {file: filePath}];55 const reversedStdoutOption = reversed ? stdoutOption.reverse() : stdoutOption;56 const {stdout} = await execaMethod('noop-fd.js', ['1'], {stdout: reversedStdoutOption});57 t.is(stdout, foobarUppercase);58 t.is(await readFile(filePath, 'utf8'), foobarUppercase);59 await rm(filePath);60};6162test('Can use generators with a file as output', testOutputFile, false, 'generator', execa);63test('Can use generators with a file as output, reversed', testOutputFile, true, 'generator', execa);64test('Can use generators with a file as output, sync', testOutputFile, false, 'generator', execaSync);65test('Can use generators with a file as output, reversed, sync', testOutputFile, true, 'generator', execaSync);66test('Can use duplexes with a file as output', testOutputFile, false, 'duplex', execa);67test('Can use duplexes with a file as output, reversed', testOutputFile, true, 'duplex', execa);68test('Can use webTransforms with a file as output', testOutputFile, false, 'webTransform', execa);69test('Can use webTransforms with a file as output, reversed', testOutputFile, true, 'webTransform', execa);7071const testWritableDestination = async (t, type) => {72 const passThrough = new PassThrough();73 const [{stdout}, streamOutput] = await Promise.all([74 execa('noop-fd.js', ['1', foobarString], {stdout: [generatorsMap[type].uppercaseBuffer(false, true), passThrough]}),75 getStream(passThrough),76 ]);77 t.is(stdout, foobarUppercase);78 t.is(streamOutput, foobarUppercase);79};8081test('Can use generators to a Writable stream', testWritableDestination, 'generator');82test('Can use duplexes to a Writable stream', testWritableDestination, 'duplex');83test('Can use webTransforms to a Writable stream', testWritableDestination, 'webTransform');8485const testReadableSource = async (t, type) => {86 const passThrough = new PassThrough();87 const subprocess = execa('stdin-fd.js', ['0'], {stdin: [passThrough, generatorsMap[type].uppercase()]});88 passThrough.end(foobarString);89 const {stdout} = await subprocess;90 t.is(stdout, foobarUppercase);91};9293test('Can use generators from a Readable stream', testReadableSource, 'generator');94test('Can use duplexes from a Readable stream', testReadableSource, 'duplex');95test('Can use webTransforms from a Readable stream', testReadableSource, 'webTransform');9697const testInherit = async (t, type) => {98 const {stdout} = await execa('nested-inherit.js', [type]);99 t.is(stdout, foobarUppercase);100};101102test('Can use generators with "inherit"', testInherit, 'generator');103test('Can use duplexes with "inherit"', testInherit, 'duplex');104test('Can use webTransforms with "inherit"', testInherit, 'webTransform');
added:test/stdio/transform-output.js+261 added
1import test from 'ava';2import getStream, {getStreamAsArray} from 'get-stream';3import {execa, execaSync} from '../../index.js';4import {setFixtureDir} from '../helpers/fixtures-dir.js';5import {getStdio} from '../helpers/stdio.js';6import {foobarString, foobarUppercase, foobarObject} from '../helpers/input.js';7import {generatorsMap} from '../helpers/map.js';89setFixtureDir();1011const getOutputObjectMode = (objectMode, addNoopTransform, type, binary) => objectMode12 ? {13 generators: generatorsMap[type].addNoop(generatorsMap[type].outputObject(), addNoopTransform, objectMode, binary),14 output: [foobarObject],15 getStreamMethod: getStreamAsArray,16 }17 : {18 generators: generatorsMap[type].addNoop(generatorsMap[type].uppercaseBuffer(objectMode, true), addNoopTransform, objectMode, binary),19 output: foobarUppercase,20 getStreamMethod: getStream,21 };2223// eslint-disable-next-line max-params24const testGeneratorOutput = async (t, fdNumber, reject, useShortcutProperty, objectMode, addNoopTransform, type, execaMethod) => {25 const {generators, output} = getOutputObjectMode(objectMode, addNoopTransform, type);26 const fixtureName = reject ? 'noop-fd.js' : 'noop-fail.js';27 const {stdout, stderr, stdio} = await execaMethod(fixtureName, [`${fdNumber}`, foobarString], {...getStdio(fdNumber, generators), reject});28 const result = useShortcutProperty ? [stdout, stderr][fdNumber - 1] : stdio[fdNumber];29 t.deepEqual(result, output);30};3132test('Can use generators with result.stdio[1]', testGeneratorOutput, 1, true, false, false, false, 'generator', execa);33test('Can use generators with result.stdout', testGeneratorOutput, 1, true, true, false, false, 'generator', execa);34test('Can use generators with result.stdio[2]', testGeneratorOutput, 2, true, false, false, false, 'generator', execa);35test('Can use generators with result.stderr', testGeneratorOutput, 2, true, true, false, false, 'generator', execa);36test('Can use generators with result.stdio[*] as output', testGeneratorOutput, 3, true, false, false, false, 'generator', execa);37test('Can use generators with error.stdio[1]', testGeneratorOutput, 1, false, false, false, false, 'generator', execa);38test('Can use generators with error.stdout', testGeneratorOutput, 1, false, true, false, false, 'generator', execa);39test('Can use generators with error.stdio[2]', testGeneratorOutput, 2, false, false, false, false, 'generator', execa);40test('Can use generators with error.stderr', testGeneratorOutput, 2, false, true, false, false, 'generator', execa);41test('Can use generators with error.stdio[*] as output', testGeneratorOutput, 3, false, false, false, false, 'generator', execa);42test('Can use generators with result.stdio[1], objectMode', testGeneratorOutput, 1, true, false, true, false, 'generator', execa);43test('Can use generators with result.stdout, objectMode', testGeneratorOutput, 1, true, true, true, false, 'generator', execa);44test('Can use generators with result.stdio[2], objectMode', testGeneratorOutput, 2, true, false, true, false, 'generator', execa);45test('Can use generators with result.stderr, objectMode', testGeneratorOutput, 2, true, true, true, false, 'generator', execa);46test('Can use generators with result.stdio[*] as output, objectMode', testGeneratorOutput, 3, true, false, true, false, 'generator', execa);47test('Can use generators with error.stdio[1], objectMode', testGeneratorOutput, 1, false, false, true, false, 'generator', execa);48test('Can use generators with error.stdout, objectMode', testGeneratorOutput, 1, false, true, true, false, 'generator', execa);49test('Can use generators with error.stdio[2], objectMode', testGeneratorOutput, 2, false, false, true, false, 'generator', execa);50test('Can use generators with error.stderr, objectMode', testGeneratorOutput, 2, false, true, true, false, 'generator', execa);51test('Can use generators with error.stdio[*] as output, objectMode', testGeneratorOutput, 3, false, false, true, false, 'generator', execa);52test('Can use generators with result.stdio[1], noop transform', testGeneratorOutput, 1, true, false, false, true, 'generator', execa);53test('Can use generators with result.stdout, noop transform', testGeneratorOutput, 1, true, true, false, true, 'generator', execa);54test('Can use generators with result.stdio[2], noop transform', testGeneratorOutput, 2, true, false, false, true, 'generator', execa);55test('Can use generators with result.stderr, noop transform', testGeneratorOutput, 2, true, true, false, true, 'generator', execa);56test('Can use generators with result.stdio[*] as output, noop transform', testGeneratorOutput, 3, true, false, false, true, 'generator', execa);57test('Can use generators with error.stdio[1], noop transform', testGeneratorOutput, 1, false, false, false, true, 'generator', execa);58test('Can use generators with error.stdout, noop transform', testGeneratorOutput, 1, false, true, false, true, 'generator', execa);59test('Can use generators with error.stdio[2], noop transform', testGeneratorOutput, 2, false, false, false, true, 'generator', execa);60test('Can use generators with error.stderr, noop transform', testGeneratorOutput, 2, false, true, false, true, 'generator', execa);61test('Can use generators with error.stdio[*] as output, noop transform', testGeneratorOutput, 3, false, false, false, true, 'generator', execa);62test('Can use generators with result.stdio[1], objectMode, noop transform', testGeneratorOutput, 1, true, false, true, true, 'generator', execa);63test('Can use generators with result.stdout, objectMode, noop transform', testGeneratorOutput, 1, true, true, true, true, 'generator', execa);64test('Can use generators with result.stdio[2], objectMode, noop transform', testGeneratorOutput, 2, true, false, true, true, 'generator', execa);65test('Can use generators with result.stderr, objectMode, noop transform', testGeneratorOutput, 2, true, true, true, true, 'generator', execa);66test('Can use generators with result.stdio[*] as output, objectMode, noop transform', testGeneratorOutput, 3, true, false, true, true, 'generator', execa);67test('Can use generators with error.stdio[1], objectMode, noop transform', testGeneratorOutput, 1, false, false, true, true, 'generator', execa);68test('Can use generators with error.stdout, objectMode, noop transform', testGeneratorOutput, 1, false, true, true, true, 'generator', execa);69test('Can use generators with error.stdio[2], objectMode, noop transform', testGeneratorOutput, 2, false, false, true, true, 'generator', execa);70test('Can use generators with error.stderr, objectMode, noop transform', testGeneratorOutput, 2, false, true, true, true, 'generator', execa);71test('Can use generators with error.stdio[*] as output, objectMode, noop transform', testGeneratorOutput, 3, false, false, true, true, 'generator', execa);72test('Can use generators with result.stdio[1], sync', testGeneratorOutput, 1, true, false, false, false, 'generator', execaSync);73test('Can use generators with result.stdout, sync', testGeneratorOutput, 1, true, true, false, false, 'generator', execaSync);74test('Can use generators with result.stdio[2], sync', testGeneratorOutput, 2, true, false, false, false, 'generator', execaSync);75test('Can use generators with result.stderr, sync', testGeneratorOutput, 2, true, true, false, false, 'generator', execaSync);76test('Can use generators with result.stdio[*] as output, sync', testGeneratorOutput, 3, true, false, false, false, 'generator', execaSync);77test('Can use generators with error.stdio[1], sync', testGeneratorOutput, 1, false, false, false, false, 'generator', execaSync);78test('Can use generators with error.stdout, sync', testGeneratorOutput, 1, false, true, false, false, 'generator', execaSync);79test('Can use generators with error.stdio[2], sync', testGeneratorOutput, 2, false, false, false, false, 'generator', execaSync);80test('Can use generators with error.stderr, sync', testGeneratorOutput, 2, false, true, false, false, 'generator', execaSync);81test('Can use generators with error.stdio[*] as output, sync', testGeneratorOutput, 3, false, false, false, false, 'generator', execaSync);82test('Can use generators with result.stdio[1], objectMode, sync', testGeneratorOutput, 1, true, false, true, false, 'generator', execaSync);83test('Can use generators with result.stdout, objectMode, sync', testGeneratorOutput, 1, true, true, true, false, 'generator', execaSync);84test('Can use generators with result.stdio[2], objectMode, sync', testGeneratorOutput, 2, true, false, true, false, 'generator', execaSync);85test('Can use generators with result.stderr, objectMode, sync', testGeneratorOutput, 2, true, true, true, false, 'generator', execaSync);86test('Can use generators with result.stdio[*] as output, objectMode, sync', testGeneratorOutput, 3, true, false, true, false, 'generator', execaSync);87test('Can use generators with error.stdio[1], objectMode, sync', testGeneratorOutput, 1, false, false, true, false, 'generator', execaSync);88test('Can use generators with error.stdout, objectMode, sync', testGeneratorOutput, 1, false, true, true, false, 'generator', execaSync);89test('Can use generators with error.stdio[2], objectMode, sync', testGeneratorOutput, 2, false, false, true, false, 'generator', execaSync);90test('Can use generators with error.stderr, objectMode, sync', testGeneratorOutput, 2, false, true, true, false, 'generator', execaSync);91test('Can use generators with error.stdio[*] as output, objectMode, sync', testGeneratorOutput, 3, false, false, true, false, 'generator', execaSync);92test('Can use generators with result.stdio[1], noop transform, sync', testGeneratorOutput, 1, true, false, false, true, 'generator', execaSync);93test('Can use generators with result.stdout, noop transform, sync', testGeneratorOutput, 1, true, true, false, true, 'generator', execaSync);94test('Can use generators with result.stdio[2], noop transform, sync', testGeneratorOutput, 2, true, false, false, true, 'generator', execaSync);95test('Can use generators with result.stderr, noop transform, sync', testGeneratorOutput, 2, true, true, false, true, 'generator', execaSync);96test('Can use generators with result.stdio[*] as output, noop transform, sync', testGeneratorOutput, 3, true, false, false, true, 'generator', execaSync);97test('Can use generators with error.stdio[1], noop transform, sync', testGeneratorOutput, 1, false, false, false, true, 'generator', execaSync);98test('Can use generators with error.stdout, noop transform, sync', testGeneratorOutput, 1, false, true, false, true, 'generator', execaSync);99test('Can use generators with error.stdio[2], noop transform, sync', testGeneratorOutput, 2, false, false, false, true, 'generator', execaSync);100test('Can use generators with error.stderr, noop transform, sync', testGeneratorOutput, 2, false, true, false, true, 'generator', execaSync);101test('Can use generators with error.stdio[*] as output, noop transform, sync', testGeneratorOutput, 3, false, false, false, true, 'generator', execaSync);102test('Can use generators with result.stdio[1], objectMode, noop transform, sync', testGeneratorOutput, 1, true, false, true, true, 'generator', execaSync);103test('Can use generators with result.stdout, objectMode, noop transform, sync', testGeneratorOutput, 1, true, true, true, true, 'generator', execaSync);104test('Can use generators with result.stdio[2], objectMode, noop transform, sync', testGeneratorOutput, 2, true, false, true, true, 'generator', execaSync);105test('Can use generators with result.stderr, objectMode, noop transform, sync', testGeneratorOutput, 2, true, true, true, true, 'generator', execaSync);106test('Can use generators with result.stdio[*] as output, objectMode, noop transform, sync', testGeneratorOutput, 3, true, false, true, true, 'generator', execaSync);107test('Can use generators with error.stdio[1], objectMode, noop transform, sync', testGeneratorOutput, 1, false, false, true, true, 'generator', execaSync);108test('Can use generators with error.stdout, objectMode, noop transform, sync', testGeneratorOutput, 1, false, true, true, true, 'generator', execaSync);109test('Can use generators with error.stdio[2], objectMode, noop transform, sync', testGeneratorOutput, 2, false, false, true, true, 'generator', execaSync);110test('Can use generators with error.stderr, objectMode, noop transform, sync', testGeneratorOutput, 2, false, true, true, true, 'generator', execaSync);111test('Can use generators with error.stdio[*] as output, objectMode, noop transform, sync', testGeneratorOutput, 3, false, false, true, true, 'generator', execaSync);112test('Can use duplexes with result.stdio[1]', testGeneratorOutput, 1, true, false, false, false, 'duplex', execa);113test('Can use duplexes with result.stdout', testGeneratorOutput, 1, true, true, false, false, 'duplex', execa);114test('Can use duplexes with result.stdio[2]', testGeneratorOutput, 2, true, false, false, false, 'duplex', execa);115test('Can use duplexes with result.stderr', testGeneratorOutput, 2, true, true, false, false, 'duplex', execa);116test('Can use duplexes with result.stdio[*] as output', testGeneratorOutput, 3, true, false, false, false, 'duplex', execa);117test('Can use duplexes with error.stdio[1]', testGeneratorOutput, 1, false, false, false, false, 'duplex', execa);118test('Can use duplexes with error.stdout', testGeneratorOutput, 1, false, true, false, false, 'duplex', execa);119test('Can use duplexes with error.stdio[2]', testGeneratorOutput, 2, false, false, false, false, 'duplex', execa);120test('Can use duplexes with error.stderr', testGeneratorOutput, 2, false, true, false, false, 'duplex', execa);121test('Can use duplexes with error.stdio[*] as output', testGeneratorOutput, 3, false, false, false, false, 'duplex', execa);122test('Can use duplexes with result.stdio[1], objectMode', testGeneratorOutput, 1, true, false, true, false, 'duplex', execa);123test('Can use duplexes with result.stdout, objectMode', testGeneratorOutput, 1, true, true, true, false, 'duplex', execa);124test('Can use duplexes with result.stdio[2], objectMode', testGeneratorOutput, 2, true, false, true, false, 'duplex', execa);125test('Can use duplexes with result.stderr, objectMode', testGeneratorOutput, 2, true, true, true, false, 'duplex', execa);126test('Can use duplexes with result.stdio[*] as output, objectMode', testGeneratorOutput, 3, true, false, true, false, 'duplex', execa);127test('Can use duplexes with error.stdio[1], objectMode', testGeneratorOutput, 1, false, false, true, false, 'duplex', execa);128test('Can use duplexes with error.stdout, objectMode', testGeneratorOutput, 1, false, true, true, false, 'duplex', execa);129test('Can use duplexes with error.stdio[2], objectMode', testGeneratorOutput, 2, false, false, true, false, 'duplex', execa);130test('Can use duplexes with error.stderr, objectMode', testGeneratorOutput, 2, false, true, true, false, 'duplex', execa);131test('Can use duplexes with error.stdio[*] as output, objectMode', testGeneratorOutput, 3, false, false, true, false, 'duplex', execa);132test('Can use duplexes with result.stdio[1], noop transform', testGeneratorOutput, 1, true, false, false, true, 'duplex', execa);133test('Can use duplexes with result.stdout, noop transform', testGeneratorOutput, 1, true, true, false, true, 'duplex', execa);134test('Can use duplexes with result.stdio[2], noop transform', testGeneratorOutput, 2, true, false, false, true, 'duplex', execa);135test('Can use duplexes with result.stderr, noop transform', testGeneratorOutput, 2, true, true, false, true, 'duplex', execa);136test('Can use duplexes with result.stdio[*] as output, noop transform', testGeneratorOutput, 3, true, false, false, true, 'duplex', execa);137test('Can use duplexes with error.stdio[1], noop transform', testGeneratorOutput, 1, false, false, false, true, 'duplex', execa);138test('Can use duplexes with error.stdout, noop transform', testGeneratorOutput, 1, false, true, false, true, 'duplex', execa);139test('Can use duplexes with error.stdio[2], noop transform', testGeneratorOutput, 2, false, false, false, true, 'duplex', execa);140test('Can use duplexes with error.stderr, noop transform', testGeneratorOutput, 2, false, true, false, true, 'duplex', execa);141test('Can use duplexes with error.stdio[*] as output, noop transform', testGeneratorOutput, 3, false, false, false, true, 'duplex', execa);142test('Can use duplexes with result.stdio[1], objectMode, noop transform', testGeneratorOutput, 1, true, false, true, true, 'duplex', execa);143test('Can use duplexes with result.stdout, objectMode, noop transform', testGeneratorOutput, 1, true, true, true, true, 'duplex', execa);144test('Can use duplexes with result.stdio[2], objectMode, noop transform', testGeneratorOutput, 2, true, false, true, true, 'duplex', execa);145test('Can use duplexes with result.stderr, objectMode, noop transform', testGeneratorOutput, 2, true, true, true, true, 'duplex', execa);146test('Can use duplexes with result.stdio[*] as output, objectMode, noop transform', testGeneratorOutput, 3, true, false, true, true, 'duplex', execa);147test('Can use duplexes with error.stdio[1], objectMode, noop transform', testGeneratorOutput, 1, false, false, true, true, 'duplex', execa);148test('Can use duplexes with error.stdout, objectMode, noop transform', testGeneratorOutput, 1, false, true, true, true, 'duplex', execa);149test('Can use duplexes with error.stdio[2], objectMode, noop transform', testGeneratorOutput, 2, false, false, true, true, 'duplex', execa);150test('Can use duplexes with error.stderr, objectMode, noop transform', testGeneratorOutput, 2, false, true, true, true, 'duplex', execa);151test('Can use duplexes with error.stdio[*] as output, objectMode, noop transform', testGeneratorOutput, 3, false, false, true, true, 'duplex', execa);152test('Can use webTransforms with result.stdio[1]', testGeneratorOutput, 1, true, false, false, false, 'webTransform', execa);153test('Can use webTransforms with result.stdout', testGeneratorOutput, 1, true, true, false, false, 'webTransform', execa);154test('Can use webTransforms with result.stdio[2]', testGeneratorOutput, 2, true, false, false, false, 'webTransform', execa);155test('Can use webTransforms with result.stderr', testGeneratorOutput, 2, true, true, false, false, 'webTransform', execa);156test('Can use webTransforms with result.stdio[*] as output', testGeneratorOutput, 3, true, false, false, false, 'webTransform', execa);157test('Can use webTransforms with error.stdio[1]', testGeneratorOutput, 1, false, false, false, false, 'webTransform', execa);158test('Can use webTransforms with error.stdout', testGeneratorOutput, 1, false, true, false, false, 'webTransform', execa);159test('Can use webTransforms with error.stdio[2]', testGeneratorOutput, 2, false, false, false, false, 'webTransform', execa);160test('Can use webTransforms with error.stderr', testGeneratorOutput, 2, false, true, false, false, 'webTransform', execa);161test('Can use webTransforms with error.stdio[*] as output', testGeneratorOutput, 3, false, false, false, false, 'webTransform', execa);162test('Can use webTransforms with result.stdio[1], objectMode', testGeneratorOutput, 1, true, false, true, false, 'webTransform', execa);163test('Can use webTransforms with result.stdout, objectMode', testGeneratorOutput, 1, true, true, true, false, 'webTransform', execa);164test('Can use webTransforms with result.stdio[2], objectMode', testGeneratorOutput, 2, true, false, true, false, 'webTransform', execa);165test('Can use webTransforms with result.stderr, objectMode', testGeneratorOutput, 2, true, true, true, false, 'webTransform', execa);166test('Can use webTransforms with result.stdio[*] as output, objectMode', testGeneratorOutput, 3, true, false, true, false, 'webTransform', execa);167test('Can use webTransforms with error.stdio[1], objectMode', testGeneratorOutput, 1, false, false, true, false, 'webTransform', execa);168test('Can use webTransforms with error.stdout, objectMode', testGeneratorOutput, 1, false, true, true, false, 'webTransform', execa);169test('Can use webTransforms with error.stdio[2], objectMode', testGeneratorOutput, 2, false, false, true, false, 'webTransform', execa);170test('Can use webTransforms with error.stderr, objectMode', testGeneratorOutput, 2, false, true, true, false, 'webTransform', execa);171test('Can use webTransforms with error.stdio[*] as output, objectMode', testGeneratorOutput, 3, false, false, true, false, 'webTransform', execa);172test('Can use webTransforms with result.stdio[1], noop transform', testGeneratorOutput, 1, true, false, false, true, 'webTransform', execa);173test('Can use webTransforms with result.stdout, noop transform', testGeneratorOutput, 1, true, true, false, true, 'webTransform', execa);174test('Can use webTransforms with result.stdio[2], noop transform', testGeneratorOutput, 2, true, false, false, true, 'webTransform', execa);175test('Can use webTransforms with result.stderr, noop transform', testGeneratorOutput, 2, true, true, false, true, 'webTransform', execa);176test('Can use webTransforms with result.stdio[*] as output, noop transform', testGeneratorOutput, 3, true, false, false, true, 'webTransform', execa);177test('Can use webTransforms with error.stdio[1], noop transform', testGeneratorOutput, 1, false, false, false, true, 'webTransform', execa);178test('Can use webTransforms with error.stdout, noop transform', testGeneratorOutput, 1, false, true, false, true, 'webTransform', execa);179test('Can use webTransforms with error.stdio[2], noop transform', testGeneratorOutput, 2, false, false, false, true, 'webTransform', execa);180test('Can use webTransforms with error.stderr, noop transform', testGeneratorOutput, 2, false, true, false, true, 'webTransform', execa);181test('Can use webTransforms with error.stdio[*] as output, noop transform', testGeneratorOutput, 3, false, false, false, true, 'webTransform', execa);182test('Can use webTransforms with result.stdio[1], objectMode, noop transform', testGeneratorOutput, 1, true, false, true, true, 'webTransform', execa);183test('Can use webTransforms with result.stdout, objectMode, noop transform', testGeneratorOutput, 1, true, true, true, true, 'webTransform', execa);184test('Can use webTransforms with result.stdio[2], objectMode, noop transform', testGeneratorOutput, 2, true, false, true, true, 'webTransform', execa);185test('Can use webTransforms with result.stderr, objectMode, noop transform', testGeneratorOutput, 2, true, true, true, true, 'webTransform', execa);186test('Can use webTransforms with result.stdio[*] as output, objectMode, noop transform', testGeneratorOutput, 3, true, false, true, true, 'webTransform', execa);187test('Can use webTransforms with error.stdio[1], objectMode, noop transform', testGeneratorOutput, 1, false, false, true, true, 'webTransform', execa);188test('Can use webTransforms with error.stdout, objectMode, noop transform', testGeneratorOutput, 1, false, true, true, true, 'webTransform', execa);189test('Can use webTransforms with error.stdio[2], objectMode, noop transform', testGeneratorOutput, 2, false, false, true, true, 'webTransform', execa);190test('Can use webTransforms with error.stderr, objectMode, noop transform', testGeneratorOutput, 2, false, true, true, true, 'webTransform', execa);191test('Can use webTransforms with error.stdio[*] as output, objectMode, noop transform', testGeneratorOutput, 3, false, false, true, true, 'webTransform', execa);192193// eslint-disable-next-line max-params194const testGeneratorOutputPipe = async (t, fdNumber, useShortcutProperty, objectMode, addNoopTransform, type) => {195 const {generators, output, getStreamMethod} = getOutputObjectMode(objectMode, addNoopTransform, type, true);196 const subprocess = execa('noop-fd.js', [`${fdNumber}`, foobarString], getStdio(fdNumber, generators));197 const stream = useShortcutProperty ? [subprocess.stdout, subprocess.stderr][fdNumber - 1] : subprocess.stdio[fdNumber];198 const [result] = await Promise.all([getStreamMethod(stream), subprocess]);199 t.deepEqual(result, output);200};201202test('Can use generators with subprocess.stdio[1]', testGeneratorOutputPipe, 1, false, false, false, 'generator');203test('Can use generators with subprocess.stdout', testGeneratorOutputPipe, 1, true, false, false, 'generator');204test('Can use generators with subprocess.stdio[2]', testGeneratorOutputPipe, 2, false, false, false, 'generator');205test('Can use generators with subprocess.stderr', testGeneratorOutputPipe, 2, true, false, false, 'generator');206test('Can use generators with subprocess.stdio[*] as output', testGeneratorOutputPipe, 3, false, false, false, 'generator');207test('Can use generators with subprocess.stdio[1], objectMode', testGeneratorOutputPipe, 1, false, true, false, 'generator');208test('Can use generators with subprocess.stdout, objectMode', testGeneratorOutputPipe, 1, true, true, false, 'generator');209test('Can use generators with subprocess.stdio[2], objectMode', testGeneratorOutputPipe, 2, false, true, false, 'generator');210test('Can use generators with subprocess.stderr, objectMode', testGeneratorOutputPipe, 2, true, true, false, 'generator');211test('Can use generators with subprocess.stdio[*] as output, objectMode', testGeneratorOutputPipe, 3, false, true, false, 'generator');212test('Can use generators with subprocess.stdio[1], noop transform', testGeneratorOutputPipe, 1, false, false, true, 'generator');213test('Can use generators with subprocess.stdout, noop transform', testGeneratorOutputPipe, 1, true, false, true, 'generator');214test('Can use generators with subprocess.stdio[2], noop transform', testGeneratorOutputPipe, 2, false, false, true, 'generator');215test('Can use generators with subprocess.stderr, noop transform', testGeneratorOutputPipe, 2, true, false, true, 'generator');216test('Can use generators with subprocess.stdio[*] as output, noop transform', testGeneratorOutputPipe, 3, false, false, true, 'generator');217test('Can use generators with subprocess.stdio[1], objectMode, noop transform', testGeneratorOutputPipe, 1, false, true, true, 'generator');218test('Can use generators with subprocess.stdout, objectMode, noop transform', testGeneratorOutputPipe, 1, true, true, true, 'generator');219test('Can use generators with subprocess.stdio[2], objectMode, noop transform', testGeneratorOutputPipe, 2, false, true, true, 'generator');220test('Can use generators with subprocess.stderr, objectMode, noop transform', testGeneratorOutputPipe, 2, true, true, true, 'generator');221test('Can use generators with subprocess.stdio[*] as output, objectMode, noop transform', testGeneratorOutputPipe, 3, false, true, true, 'generator');222test('Can use duplexes with subprocess.stdio[1]', testGeneratorOutputPipe, 1, false, false, false, 'duplex');223test('Can use duplexes with subprocess.stdout', testGeneratorOutputPipe, 1, true, false, false, 'duplex');224test('Can use duplexes with subprocess.stdio[2]', testGeneratorOutputPipe, 2, false, false, false, 'duplex');225test('Can use duplexes with subprocess.stderr', testGeneratorOutputPipe, 2, true, false, false, 'duplex');226test('Can use duplexes with subprocess.stdio[*] as output', testGeneratorOutputPipe, 3, false, false, false, 'duplex');227test('Can use duplexes with subprocess.stdio[1], objectMode', testGeneratorOutputPipe, 1, false, true, false, 'duplex');228test('Can use duplexes with subprocess.stdout, objectMode', testGeneratorOutputPipe, 1, true, true, false, 'duplex');229test('Can use duplexes with subprocess.stdio[2], objectMode', testGeneratorOutputPipe, 2, false, true, false, 'duplex');230test('Can use duplexes with subprocess.stderr, objectMode', testGeneratorOutputPipe, 2, true, true, false, 'duplex');231test('Can use duplexes with subprocess.stdio[*] as output, objectMode', testGeneratorOutputPipe, 3, false, true, false, 'duplex');232test('Can use duplexes with subprocess.stdio[1], noop transform', testGeneratorOutputPipe, 1, false, false, true, 'duplex');233test('Can use duplexes with subprocess.stdout, noop transform', testGeneratorOutputPipe, 1, true, false, true, 'duplex');234test('Can use duplexes with subprocess.stdio[2], noop transform', testGeneratorOutputPipe, 2, false, false, true, 'duplex');235test('Can use duplexes with subprocess.stderr, noop transform', testGeneratorOutputPipe, 2, true, false, true, 'duplex');236test('Can use duplexes with subprocess.stdio[*] as output, noop transform', testGeneratorOutputPipe, 3, false, false, true, 'duplex');237test('Can use duplexes with subprocess.stdio[1], objectMode, noop transform', testGeneratorOutputPipe, 1, false, true, true, 'duplex');238test('Can use duplexes with subprocess.stdout, objectMode, noop transform', testGeneratorOutputPipe, 1, true, true, true, 'duplex');239test('Can use duplexes with subprocess.stdio[2], objectMode, noop transform', testGeneratorOutputPipe, 2, false, true, true, 'duplex');240test('Can use duplexes with subprocess.stderr, objectMode, noop transform', testGeneratorOutputPipe, 2, true, true, true, 'duplex');241test('Can use duplexes with subprocess.stdio[*] as output, objectMode, noop transform', testGeneratorOutputPipe, 3, false, true, true, 'duplex');242test('Can use webTransforms with subprocess.stdio[1]', testGeneratorOutputPipe, 1, false, false, false, 'webTransform');243test('Can use webTransforms with subprocess.stdout', testGeneratorOutputPipe, 1, true, false, false, 'webTransform');244test('Can use webTransforms with subprocess.stdio[2]', testGeneratorOutputPipe, 2, false, false, false, 'webTransform');245test('Can use webTransforms with subprocess.stderr', testGeneratorOutputPipe, 2, true, false, false, 'webTransform');246test('Can use webTransforms with subprocess.stdio[*] as output', testGeneratorOutputPipe, 3, false, false, false, 'webTransform');247test('Can use webTransforms with subprocess.stdio[1], objectMode', testGeneratorOutputPipe, 1, false, true, false, 'webTransform');248test('Can use webTransforms with subprocess.stdout, objectMode', testGeneratorOutputPipe, 1, true, true, false, 'webTransform');249test('Can use webTransforms with subprocess.stdio[2], objectMode', testGeneratorOutputPipe, 2, false, true, false, 'webTransform');250test('Can use webTransforms with subprocess.stderr, objectMode', testGeneratorOutputPipe, 2, true, true, false, 'webTransform');251test('Can use webTransforms with subprocess.stdio[*] as output, objectMode', testGeneratorOutputPipe, 3, false, true, false, 'webTransform');252test('Can use webTransforms with subprocess.stdio[1], noop transform', testGeneratorOutputPipe, 1, false, false, true, 'webTransform');253test('Can use webTransforms with subprocess.stdout, noop transform', testGeneratorOutputPipe, 1, true, false, true, 'webTransform');254test('Can use webTransforms with subprocess.stdio[2], noop transform', testGeneratorOutputPipe, 2, false, false, true, 'webTransform');255test('Can use webTransforms with subprocess.stderr, noop transform', testGeneratorOutputPipe, 2, true, false, true, 'webTransform');256test('Can use webTransforms with subprocess.stdio[*] as output, noop transform', testGeneratorOutputPipe, 3, false, false, true, 'webTransform');257test('Can use webTransforms with subprocess.stdio[1], objectMode, noop transform', testGeneratorOutputPipe, 1, false, true, true, 'webTransform');258test('Can use webTransforms with subprocess.stdout, objectMode, noop transform', testGeneratorOutputPipe, 1, true, true, true, 'webTransform');259test('Can use webTransforms with subprocess.stdio[2], objectMode, noop transform', testGeneratorOutputPipe, 2, false, true, true, 'webTransform');260test('Can use webTransforms with subprocess.stderr, objectMode, noop transform', testGeneratorOutputPipe, 2, true, true, true, 'webTransform');261test('Can use webTransforms with subprocess.stdio[*] as output, objectMode, noop transform', testGeneratorOutputPipe, 3, false, true, true, 'webTransform');
added:test/stdio/transform-run.js+185 added
1import {Buffer} from 'node:buffer';2import {scheduler} from 'node:timers/promises';3import test from 'ava';4import {getStreamAsArray} from 'get-stream';5import {execa, execaSync} from '../../index.js';6import {foobarString} from '../helpers/input.js';7import {8 noopGenerator,9 outputObjectGenerator,10 convertTransformToFinal,11 prefix,12 suffix,13} from '../helpers/generator.js';14import {generatorsMap} from '../helpers/map.js';15import {defaultHighWaterMark} from '../helpers/stream.js';16import {setFixtureDir} from '../helpers/fixtures-dir.js';17import {maxBuffer, assertErrorMessage} from '../helpers/max-buffer.js';1819setFixtureDir();2021const repeatCount = defaultHighWaterMark * 3;2223const writerGenerator = function * () {24 for (let index = 0; index < repeatCount; index += 1) {25 yield '\n';26 }27};2829const getLengthGenerator = function * (t, chunk) {30 t.is(chunk.length, 1);31 yield chunk;32};3334// eslint-disable-next-line max-params35const testHighWaterMark = async (t, passThrough, binary, objectMode, execaMethod) => {36 const {stdout} = await execaMethod('noop.js', {37 stdout: [38 ...(objectMode ? [outputObjectGenerator()] : []),39 writerGenerator,40 ...(passThrough ? [noopGenerator(false, binary)] : []),41 {transform: getLengthGenerator.bind(undefined, t), preserveNewlines: true, objectMode: true},42 ],43 });44 t.is(stdout.length, repeatCount);45 t.true(stdout.every(chunk => chunk === '\n'));46};4748test('Synchronous yields are not buffered, no passThrough', testHighWaterMark, false, false, false, execa);49test('Synchronous yields are not buffered, line-wise passThrough', testHighWaterMark, true, false, false, execa);50test('Synchronous yields are not buffered, binary passThrough', testHighWaterMark, true, true, false, execa);51test('Synchronous yields are not buffered, objectMode as input but not output', testHighWaterMark, false, false, true, execa);52test('Synchronous yields are not buffered, no passThrough, sync', testHighWaterMark, false, false, false, execaSync);53test('Synchronous yields are not buffered, line-wise passThrough, sync', testHighWaterMark, true, false, false, execaSync);54test('Synchronous yields are not buffered, binary passThrough, sync', testHighWaterMark, true, true, false, execaSync);55test('Synchronous yields are not buffered, objectMode as input but not output, sync', testHighWaterMark, false, false, true, execaSync);5657// eslint-disable-next-line max-params58const testNoYield = async (t, type, objectMode, final, output, execaMethod) => {59 const {stdout} = await execaMethod('noop.js', {stdout: convertTransformToFinal(generatorsMap[type].noYield(objectMode), final)});60 t.deepEqual(stdout, output);61};6263test('Generator can filter "transform" by not calling yield', testNoYield, 'generator', false, false, '', execa);64test('Generator can filter "transform" by not calling yield, objectMode', testNoYield, 'generator', true, false, [], execa);65test('Generator can filter "final" by not calling yield', testNoYield, 'generator', false, true, '', execa);66test('Generator can filter "final" by not calling yield, objectMode', testNoYield, 'generator', true, true, [], execa);67test('Generator can filter "transform" by not calling yield, sync', testNoYield, 'generator', false, false, '', execaSync);68test('Generator can filter "transform" by not calling yield, objectMode, sync', testNoYield, 'generator', true, false, [], execaSync);69test('Generator can filter "final" by not calling yield, sync', testNoYield, 'generator', false, true, '', execaSync);70test('Generator can filter "final" by not calling yield, objectMode, sync', testNoYield, 'generator', true, true, [], execaSync);71test('Duplex can filter by not calling push', testNoYield, 'duplex', false, false, '', execa);72test('Duplex can filter by not calling push, objectMode', testNoYield, 'duplex', true, false, [], execa);73test('WebTransform can filter by not calling push', testNoYield, 'webTransform', false, false, '', execa);74test('WebTransform can filter by not calling push, objectMode', testNoYield, 'webTransform', true, false, [], execa);7576const testMultipleYields = async (t, type, final, binary) => {77 const {stdout} = await execa('noop-fd.js', ['1', foobarString], {stdout: convertTransformToFinal(generatorsMap[type].multipleYield(), final)});78 const newline = binary ? '' : '\n';79 t.is(stdout, `${prefix}${newline}${foobarString}${newline}${suffix}`);80};8182test('Generator can yield "transform" multiple times at different moments', testMultipleYields, 'generator', false, false);83test('Generator can yield "final" multiple times at different moments', testMultipleYields, 'generator', true, false);84test('Duplex can push multiple times at different moments', testMultipleYields, 'duplex', false, true);85test('WebTransform can push multiple times at different moments', testMultipleYields, 'webTransform', false, true);8687const partsPerChunk = 4;88const chunksPerCall = 10;89const callCount = 5;90const fullString = '\n'.repeat(defaultHighWaterMark / partsPerChunk);9192const yieldFullStrings = function * () {93 yield * Array.from({length: partsPerChunk * chunksPerCall}).fill(fullString);94};9596const manyYieldGenerator = async function * () {97 for (let index = 0; index < callCount; index += 1) {98 yield * yieldFullStrings();99 // eslint-disable-next-line no-await-in-loop100 await scheduler.yield();101 }102};103104const testManyYields = async (t, final) => {105 const subprocess = execa('noop.js', {stdout: convertTransformToFinal(manyYieldGenerator, final), stripFinalNewline: false});106 const [chunks, {stdout}] = await Promise.all([getStreamAsArray(subprocess.stdout), subprocess]);107 const expectedChunk = Buffer.from(fullString);108 t.deepEqual(chunks, Array.from({length: callCount * partsPerChunk * chunksPerCall}).fill(expectedChunk));109 t.is(chunks.join(''), stdout);110};111112test('Generator "transform" yields are sent right away', testManyYields, false);113test('Generator "final" yields are sent right away', testManyYields, true);114115const testMaxBuffer = async (t, type) => {116 const bigString = '.'.repeat(maxBuffer);117 const {stdout} = await execa('noop.js', {118 maxBuffer,119 stdout: generatorsMap[type].getOutput(bigString)(false, true),120 });121 t.is(stdout, bigString);122123 const {isMaxBuffer, shortMessage} = await t.throwsAsync(execa('noop.js', {124 maxBuffer,125 stdout: generatorsMap[type].getOutput(`${bigString}.`)(false, true),126 }));127 t.true(isMaxBuffer);128 assertErrorMessage(t, shortMessage);129};130131test('Generators take "maxBuffer" into account', testMaxBuffer, 'generator');132test('Duplexes take "maxBuffer" into account', testMaxBuffer, 'duplex');133test('WebTransforms take "maxBuffer" into account', testMaxBuffer, 'webTransform');134135test('Generators does not take "maxBuffer" into account, sync', t => {136 const bigString = '.'.repeat(maxBuffer);137 const {isMaxBuffer, stdout} = execaSync('noop.js', {138 maxBuffer,139 stdout: generatorsMap.generator.getOutput(`${bigString}.`)(false, true),140 });141 t.false(isMaxBuffer);142 t.is(stdout.length, maxBuffer + 1);143});144145const testMaxBufferObject = async (t, type) => {146 const bigArray = Array.from({length: maxBuffer}).fill('..');147 const {stdout} = await execa('noop.js', {148 maxBuffer,149 stdout: generatorsMap[type].getOutputs(bigArray)(true, true),150 });151 t.is(stdout.length, maxBuffer);152153 const {isMaxBuffer, shortMessage} = await t.throwsAsync(execa('noop.js', {154 maxBuffer,155 stdout: generatorsMap[type].getOutputs([...bigArray, ''])(true, true),156 }));157 t.true(isMaxBuffer);158 assertErrorMessage(t, shortMessage, {unit: 'objects'});159};160161test('Generators take "maxBuffer" into account, objectMode', testMaxBufferObject, 'generator');162test('Duplexes take "maxBuffer" into account, objectMode', testMaxBufferObject, 'duplex');163test('WebTransforms take "maxBuffer" into account, objectMode', testMaxBufferObject, 'webTransform');164165test('Generators does not take "maxBuffer" into account, objectMode, sync', t => {166 const bigArray = Array.from({length: maxBuffer}).fill('..');167 const {isMaxBuffer, stdout} = execaSync('noop.js', {168 maxBuffer,169 stdout: generatorsMap.generator.getOutputs([...bigArray, ''])(true, true),170 });171 t.false(isMaxBuffer);172 t.is(stdout.length, maxBuffer + 1);173});174175const testAsyncGenerators = async (t, type, final) => {176 const {stdout} = await execa('noop.js', {177 stdout: convertTransformToFinal(generatorsMap[type].timeout(1e2)(), final),178 });179 t.is(stdout, foobarString);180};181182test('Generators "transform" is awaited on success', testAsyncGenerators, 'generator', false);183test('Generators "final" is awaited on success', testAsyncGenerators, 'generator', true);184test('Duplex is awaited on success', testAsyncGenerators, 'duplex', false);185test('WebTransform is awaited on success', testAsyncGenerators, 'webTransform', false);
deleted:test/stdio/transform.js-297 removed
1import {Buffer} from 'node:buffer';2import {once} from 'node:events';3import {scheduler} from 'node:timers/promises';4import test from 'ava';5import {getStreamAsArray} from 'get-stream';6import {execa, execaSync} from '../../index.js';7import {foobarString} from '../helpers/input.js';8import {9 noopGenerator,10 getOutputAsyncGenerator,11 getOutputGenerator,12 infiniteGenerator,13 outputObjectGenerator,14 convertTransformToFinal,15 prefix,16 suffix,17} from '../helpers/generator.js';18import {generatorsMap} from '../helpers/map.js';19import {defaultHighWaterMark} from '../helpers/stream.js';20import {setFixtureDir} from '../helpers/fixtures-dir.js';21import {maxBuffer, assertErrorMessage} from '../helpers/max-buffer.js';2223setFixtureDir();2425const testGeneratorFinal = async (t, fixtureName, execaMethod) => {26 const {stdout} = await execaMethod(fixtureName, {stdout: convertTransformToFinal(getOutputGenerator(foobarString)(), true)});27 t.is(stdout, foobarString);28};2930test('Generators "final" can be used', testGeneratorFinal, 'noop.js', execa);31test('Generators "final" is used even on empty streams', testGeneratorFinal, 'empty.js', execa);32test('Generators "final" can be used, sync', testGeneratorFinal, 'noop.js', execaSync);33test('Generators "final" is used even on empty streams, sync', testGeneratorFinal, 'empty.js', execaSync);3435const testFinalAlone = async (t, final, execaMethod) => {36 const {stdout} = await execaMethod('noop-fd.js', ['1', '.'], {stdout: {final: final(foobarString)().transform, binary: true}});37 t.is(stdout, `.${foobarString}`);38};3940test('Generators "final" can be used without "transform"', testFinalAlone, getOutputGenerator, execa);41test('Generators "final" can be used without "transform", sync', testFinalAlone, getOutputGenerator, execaSync);42test('Generators "final" can be used without "transform", async', testFinalAlone, getOutputAsyncGenerator, execa);4344const testFinalNoOutput = async (t, final, execaMethod) => {45 const {stdout} = await execaMethod('empty.js', {stdout: {final: final(foobarString)().transform}});46 t.is(stdout, foobarString);47};4849test('Generators "final" can be used without "transform" nor output', testFinalNoOutput, getOutputGenerator, execa);50test('Generators "final" can be used without "transform" nor output, sync', testFinalNoOutput, getOutputGenerator, execaSync);51test('Generators "final" can be used without "transform" nor output, async', testFinalNoOutput, getOutputAsyncGenerator, execa);5253const repeatCount = defaultHighWaterMark * 3;5455const writerGenerator = function * () {56 for (let index = 0; index < repeatCount; index += 1) {57 yield '\n';58 }59};6061const getLengthGenerator = function * (t, chunk) {62 t.is(chunk.length, 1);63 yield chunk;64};6566// eslint-disable-next-line max-params67const testHighWaterMark = async (t, passThrough, binary, objectMode, execaMethod) => {68 const {stdout} = await execaMethod('noop.js', {69 stdout: [70 ...(objectMode ? [outputObjectGenerator()] : []),71 writerGenerator,72 ...(passThrough ? [noopGenerator(false, binary)] : []),73 {transform: getLengthGenerator.bind(undefined, t), preserveNewlines: true, objectMode: true},74 ],75 });76 t.is(stdout.length, repeatCount);77 t.true(stdout.every(chunk => chunk === '\n'));78};7980test('Synchronous yields are not buffered, no passThrough', testHighWaterMark, false, false, false, execa);81test('Synchronous yields are not buffered, line-wise passThrough', testHighWaterMark, true, false, false, execa);82test('Synchronous yields are not buffered, binary passThrough', testHighWaterMark, true, true, false, execa);83test('Synchronous yields are not buffered, objectMode as input but not output', testHighWaterMark, false, false, true, execa);84test('Synchronous yields are not buffered, no passThrough, sync', testHighWaterMark, false, false, false, execaSync);85test('Synchronous yields are not buffered, line-wise passThrough, sync', testHighWaterMark, true, false, false, execaSync);86test('Synchronous yields are not buffered, binary passThrough, sync', testHighWaterMark, true, true, false, execaSync);87test('Synchronous yields are not buffered, objectMode as input but not output, sync', testHighWaterMark, false, false, true, execaSync);8889// eslint-disable-next-line max-params90const testNoYield = async (t, type, objectMode, final, output, execaMethod) => {91 const {stdout} = await execaMethod('noop.js', {stdout: convertTransformToFinal(generatorsMap[type].noYield(objectMode), final)});92 t.deepEqual(stdout, output);93};9495test('Generator can filter "transform" by not calling yield', testNoYield, 'generator', false, false, '', execa);96test('Generator can filter "transform" by not calling yield, objectMode', testNoYield, 'generator', true, false, [], execa);97test('Generator can filter "final" by not calling yield', testNoYield, 'generator', false, true, '', execa);98test('Generator can filter "final" by not calling yield, objectMode', testNoYield, 'generator', true, true, [], execa);99test('Generator can filter "transform" by not calling yield, sync', testNoYield, 'generator', false, false, '', execaSync);100test('Generator can filter "transform" by not calling yield, objectMode, sync', testNoYield, 'generator', true, false, [], execaSync);101test('Generator can filter "final" by not calling yield, sync', testNoYield, 'generator', false, true, '', execaSync);102test('Generator can filter "final" by not calling yield, objectMode, sync', testNoYield, 'generator', true, true, [], execaSync);103test('Duplex can filter by not calling push', testNoYield, 'duplex', false, false, '', execa);104test('Duplex can filter by not calling push, objectMode', testNoYield, 'duplex', true, false, [], execa);105test('WebTransform can filter by not calling push', testNoYield, 'webTransform', false, false, '', execa);106test('WebTransform can filter by not calling push, objectMode', testNoYield, 'webTransform', true, false, [], execa);107108const testMultipleYields = async (t, type, final, binary) => {109 const {stdout} = await execa('noop-fd.js', ['1', foobarString], {stdout: convertTransformToFinal(generatorsMap[type].multipleYield(), final)});110 const newline = binary ? '' : '\n';111 t.is(stdout, `${prefix}${newline}${foobarString}${newline}${suffix}`);112};113114test('Generator can yield "transform" multiple times at different moments', testMultipleYields, 'generator', false, false);115test('Generator can yield "final" multiple times at different moments', testMultipleYields, 'generator', true, false);116test('Duplex can push multiple times at different moments', testMultipleYields, 'duplex', false, true);117test('WebTransform can push multiple times at different moments', testMultipleYields, 'webTransform', false, true);118119const partsPerChunk = 4;120const chunksPerCall = 10;121const callCount = 5;122const fullString = '\n'.repeat(defaultHighWaterMark / partsPerChunk);123124const yieldFullStrings = function * () {125 yield * Array.from({length: partsPerChunk * chunksPerCall}).fill(fullString);126};127128const manyYieldGenerator = async function * () {129 for (let index = 0; index < callCount; index += 1) {130 yield * yieldFullStrings();131 // eslint-disable-next-line no-await-in-loop132 await scheduler.yield();133 }134};135136const testManyYields = async (t, final) => {137 const subprocess = execa('noop.js', {stdout: convertTransformToFinal(manyYieldGenerator, final), stripFinalNewline: false});138 const [chunks, {stdout}] = await Promise.all([getStreamAsArray(subprocess.stdout), subprocess]);139 const expectedChunk = Buffer.from(fullString);140 t.deepEqual(chunks, Array.from({length: callCount * partsPerChunk * chunksPerCall}).fill(expectedChunk));141 t.is(chunks.join(''), stdout);142};143144test('Generator "transform" yields are sent right away', testManyYields, false);145test('Generator "final" yields are sent right away', testManyYields, true);146147const testMaxBuffer = async (t, type) => {148 const bigString = '.'.repeat(maxBuffer);149 const {stdout} = await execa('noop.js', {150 maxBuffer,151 stdout: generatorsMap[type].getOutput(bigString)(false, true),152 });153 t.is(stdout, bigString);154155 const {isMaxBuffer, shortMessage} = await t.throwsAsync(execa('noop.js', {156 maxBuffer,157 stdout: generatorsMap[type].getOutput(`${bigString}.`)(false, true),158 }));159 t.true(isMaxBuffer);160 assertErrorMessage(t, shortMessage);161};162163test('Generators take "maxBuffer" into account', testMaxBuffer, 'generator');164test('Duplexes take "maxBuffer" into account', testMaxBuffer, 'duplex');165test('WebTransforms take "maxBuffer" into account', testMaxBuffer, 'webTransform');166167test('Generators does not take "maxBuffer" into account, sync', t => {168 const bigString = '.'.repeat(maxBuffer);169 const {isMaxBuffer, stdout} = execaSync('noop.js', {170 maxBuffer,171 stdout: generatorsMap.generator.getOutput(`${bigString}.`)(false, true),172 });173 t.false(isMaxBuffer);174 t.is(stdout.length, maxBuffer + 1);175});176177const testMaxBufferObject = async (t, type) => {178 const bigArray = Array.from({length: maxBuffer}).fill('..');179 const {stdout} = await execa('noop.js', {180 maxBuffer,181 stdout: generatorsMap[type].getOutputs(bigArray)(true, true),182 });183 t.is(stdout.length, maxBuffer);184185 const {isMaxBuffer, shortMessage} = await t.throwsAsync(execa('noop.js', {186 maxBuffer,187 stdout: generatorsMap[type].getOutputs([...bigArray, ''])(true, true),188 }));189 t.true(isMaxBuffer);190 assertErrorMessage(t, shortMessage, {unit: 'objects'});191};192193test('Generators take "maxBuffer" into account, objectMode', testMaxBufferObject, 'generator');194test('Duplexes take "maxBuffer" into account, objectMode', testMaxBufferObject, 'duplex');195test('WebTransforms take "maxBuffer" into account, objectMode', testMaxBufferObject, 'webTransform');196197test('Generators does not take "maxBuffer" into account, objectMode, sync', t => {198 const bigArray = Array.from({length: maxBuffer}).fill('..');199 const {isMaxBuffer, stdout} = execaSync('noop.js', {200 maxBuffer,201 stdout: generatorsMap.generator.getOutputs([...bigArray, ''])(true, true),202 });203 t.false(isMaxBuffer);204 t.is(stdout.length, maxBuffer + 1);205});206207const testAsyncGenerators = async (t, type, final) => {208 const {stdout} = await execa('noop.js', {209 stdout: convertTransformToFinal(generatorsMap[type].timeout(1e2)(), final),210 });211 t.is(stdout, foobarString);212};213214test('Generators "transform" is awaited on success', testAsyncGenerators, 'generator', false);215test('Generators "final" is awaited on success', testAsyncGenerators, 'generator', true);216test('Duplex is awaited on success', testAsyncGenerators, 'duplex', false);217test('WebTransform is awaited on success', testAsyncGenerators, 'webTransform', false);218219const assertProcessError = async (t, type, execaMethod, getSubprocess) => {220 const cause = new Error(foobarString);221 const transform = generatorsMap[type].throwing(cause)();222 const error = execaMethod === execa223 ? await t.throwsAsync(getSubprocess(transform))224 : t.throws(() => {225 getSubprocess(transform);226 });227 t.is(error.cause, cause);228};229230const testThrowingGenerator = async (t, type, final, execaMethod) => {231 await assertProcessError(t, type, execaMethod, transform => execaMethod('noop.js', {232 stdout: convertTransformToFinal(transform, final),233 }));234};235236test('Generators "transform" errors make subprocess fail', testThrowingGenerator, 'generator', false, execa);237test('Generators "final" errors make subprocess fail', testThrowingGenerator, 'generator', true, execa);238test('Generators "transform" errors make subprocess fail, sync', testThrowingGenerator, 'generator', false, execaSync);239test('Generators "final" errors make subprocess fail, sync', testThrowingGenerator, 'generator', true, execaSync);240test('Duplexes "transform" errors make subprocess fail', testThrowingGenerator, 'duplex', false, execa);241test('WebTransform "transform" errors make subprocess fail', testThrowingGenerator, 'webTransform', false, execa);242243const testSingleErrorOutput = async (t, type, execaMethod) => {244 await assertProcessError(t, type, execaMethod, transform => execaMethod('noop.js', {245 stdout: [246 generatorsMap[type].noop(false),247 transform,248 generatorsMap[type].noop(false),249 ],250 }));251};252253test('Generators errors make subprocess fail even when other output generators do not throw', testSingleErrorOutput, 'generator', execa);254test('Generators errors make subprocess fail even when other output generators do not throw, sync', testSingleErrorOutput, 'generator', execaSync);255test('Duplexes errors make subprocess fail even when other output generators do not throw', testSingleErrorOutput, 'duplex', execa);256test('WebTransform errors make subprocess fail even when other output generators do not throw', testSingleErrorOutput, 'webTransform', execa);257258const testSingleErrorInput = async (t, type, execaMethod) => {259 await assertProcessError(t, type, execaMethod, transform => execaMethod('stdin.js', {260 stdin: [261 ['foobar\n'],262 generatorsMap[type].noop(false),263 transform,264 generatorsMap[type].noop(false),265 ],266 }));267};268269test('Generators errors make subprocess fail even when other input generators do not throw', testSingleErrorInput, 'generator', execa);270test('Generators errors make subprocess fail even when other input generators do not throw, sync', testSingleErrorInput, 'generator', execaSync);271test('Duplexes errors make subprocess fail even when other input generators do not throw', testSingleErrorInput, 'duplex', execa);272test('WebTransform errors make subprocess fail even when other input generators do not throw', testSingleErrorInput, 'webTransform', execa);273274const testGeneratorCancel = async (t, error) => {275 const subprocess = execa('noop.js', {stdout: infiniteGenerator()});276 await once(subprocess.stdout, 'data');277 subprocess.stdout.destroy(error);278 await (error === undefined ? t.notThrowsAsync(subprocess) : t.throwsAsync(subprocess));279};280281test('Running generators are canceled on subprocess abort', testGeneratorCancel, undefined);282test('Running generators are canceled on subprocess error', testGeneratorCancel, new Error('test'));283284const testGeneratorDestroy = async (t, transform) => {285 const subprocess = execa('forever.js', {stdout: transform});286 const cause = new Error('test');287 subprocess.stdout.destroy(cause);288 subprocess.kill();289 t.like(await t.throwsAsync(subprocess), {cause});290};291292test('Generators are destroyed on subprocess error, sync', testGeneratorDestroy, noopGenerator(false));293test('Generators are destroyed on subprocess error, async', testGeneratorDestroy, infiniteGenerator());294295test('Generators are destroyed on early subprocess exit', async t => {296 await t.throwsAsync(execa('noop.js', {stdout: infiniteGenerator(), uid: -1}));297});
added:test/stream/buffer-end.js+78 added
1import {once} from 'node:events';2import {setTimeout} from 'node:timers/promises';3import test from 'ava';4import {execa} from '../../index.js';5import {setFixtureDir} from '../helpers/fixtures-dir.js';6import {fullStdio, getStdio} from '../helpers/stdio.js';78setFixtureDir();910const testBufferIgnore = async (t, fdNumber, all) => {11 await t.notThrowsAsync(execa('max-buffer.js', [`${fdNumber}`], {...getStdio(fdNumber, 'ignore'), buffer: false, all}));12};1314test('Subprocess buffers stdout, which does not prevent exit if ignored', testBufferIgnore, 1, false);15test('Subprocess buffers stderr, which does not prevent exit if ignored', testBufferIgnore, 2, false);16test('Subprocess buffers all, which does not prevent exit if ignored', testBufferIgnore, 1, true);1718const testBufferNotRead = async (t, fdNumber, all) => {19 const subprocess = execa('max-buffer.js', [`${fdNumber}`], {...fullStdio, buffer: false, all});20 await t.notThrowsAsync(subprocess);21};2223test('Subprocess buffers stdout, which does not prevent exit if not read and buffer is false', testBufferNotRead, 1, false);24test('Subprocess buffers stderr, which does not prevent exit if not read and buffer is false', testBufferNotRead, 2, false);25test('Subprocess buffers stdio[*], which does not prevent exit if not read and buffer is false', testBufferNotRead, 3, false);26test('Subprocess buffers all, which does not prevent exit if not read and buffer is false', testBufferNotRead, 1, true);2728const testBufferRead = async (t, fdNumber, all) => {29 const subprocess = execa('max-buffer.js', [`${fdNumber}`], {...fullStdio, buffer: false, all});30 const stream = all ? subprocess.all : subprocess.stdio[fdNumber];31 stream.resume();32 await t.notThrowsAsync(subprocess);33};3435test('Subprocess buffers stdout, which does not prevent exit if read and buffer is false', testBufferRead, 1, false);36test('Subprocess buffers stderr, which does not prevent exit if read and buffer is false', testBufferRead, 2, false);37test('Subprocess buffers stdio[*], which does not prevent exit if read and buffer is false', testBufferRead, 3, false);38test('Subprocess buffers all, which does not prevent exit if read and buffer is false', testBufferRead, 1, true);3940const testBufferExit = async (t, fdNumber, fixtureName, reject) => {41 const subprocess = execa(fixtureName, [`${fdNumber}`], {...fullStdio, reject});42 await setTimeout(100);43 const {stdio} = await subprocess;44 t.is(stdio[fdNumber], 'foobar');45};4647test('Subprocess buffers stdout before it is read', testBufferExit, 1, 'noop-delay.js', true);48test('Subprocess buffers stderr before it is read', testBufferExit, 2, 'noop-delay.js', true);49test('Subprocess buffers stdio[*] before it is read', testBufferExit, 3, 'noop-delay.js', true);50test('Subprocess buffers stdout right away, on successfully exit', testBufferExit, 1, 'noop-fd.js', true);51test('Subprocess buffers stderr right away, on successfully exit', testBufferExit, 2, 'noop-fd.js', true);52test('Subprocess buffers stdio[*] right away, on successfully exit', testBufferExit, 3, 'noop-fd.js', true);53test('Subprocess buffers stdout right away, on failure', testBufferExit, 1, 'noop-fail.js', false);54test('Subprocess buffers stderr right away, on failure', testBufferExit, 2, 'noop-fail.js', false);55test('Subprocess buffers stdio[*] right away, on failure', testBufferExit, 3, 'noop-fail.js', false);5657const testBufferDirect = async (t, fdNumber) => {58 const subprocess = execa('noop-fd.js', [`${fdNumber}`], fullStdio);59 const data = await once(subprocess.stdio[fdNumber], 'data');60 t.is(data.toString().trim(), 'foobar');61 const result = await subprocess;62 t.is(result.stdio[fdNumber], 'foobar');63};6465test('Subprocess buffers stdout right away, even if directly read', testBufferDirect, 1);66test('Subprocess buffers stderr right away, even if directly read', testBufferDirect, 2);67test('Subprocess buffers stdio[*] right away, even if directly read', testBufferDirect, 3);6869const testBufferDestroyOnEnd = async (t, fdNumber) => {70 const subprocess = execa('noop-fd.js', [`${fdNumber}`], fullStdio);71 const result = await subprocess;72 t.is(result.stdio[fdNumber], 'foobar');73 t.true(subprocess.stdio[fdNumber].destroyed);74};7576test('subprocess.stdout must be read right away', testBufferDestroyOnEnd, 1);77test('subprocess.stderr must be read right away', testBufferDestroyOnEnd, 2);78test('subprocess.stdio[*] must be read right away', testBufferDestroyOnEnd, 3);
modified:test/stream/exit.js+67 added-60 removed
1import {once} from 'node:events';2import {setTimeout} from 'node:timers/promises';1import process from 'node:process';2import test from 'ava';3import {execa} from '../../index.js';4import {setFixtureDir} from '../helpers/fixtures-dir.js';6import {fullStdio, getStdio} from '../helpers/stdio.js';56const isWindows = process.platform === 'win32';78setFixtureDir();910const testBufferIgnore = async (t, fdNumber, all) => {11 await t.notThrowsAsync(execa('max-buffer.js', [`${fdNumber}`], {...getStdio(fdNumber, 'ignore'), buffer: false, all}));10test('exitCode is 0 on success', async t => {11 const {exitCode} = await execa('noop.js', ['foo']);12 t.is(exitCode, 0);13});1415const testExitCode = async (t, expectedExitCode) => {16 const {exitCode, originalMessage, shortMessage, message} = await t.throwsAsync(17 execa('exit.js', [`${expectedExitCode}`]),18 );19 t.is(exitCode, expectedExitCode);20 t.is(originalMessage, '');21 t.is(shortMessage, `Command failed with exit code ${expectedExitCode}: exit.js ${expectedExitCode}`);22 t.is(message, shortMessage);23};2414test('Subprocess buffers stdout, which does not prevent exit if ignored', testBufferIgnore, 1, false);15test('Subprocess buffers stderr, which does not prevent exit if ignored', testBufferIgnore, 2, false);16test('Subprocess buffers all, which does not prevent exit if ignored', testBufferIgnore, 1, true);25test('exitCode is 2', testExitCode, 2);26test('exitCode is 3', testExitCode, 3);27test('exitCode is 4', testExitCode, 4);2818const testBufferNotRead = async (t, fdNumber, all) => {19 const subprocess = execa('max-buffer.js', [`${fdNumber}`], {...fullStdio, buffer: false, all});20 await t.notThrowsAsync(subprocess);21};29if (!isWindows) {30 test('error.signal is SIGINT', async t => {31 const subprocess = execa('forever.js');3223test('Subprocess buffers stdout, which does not prevent exit if not read and buffer is false', testBufferNotRead, 1, false);24test('Subprocess buffers stderr, which does not prevent exit if not read and buffer is false', testBufferNotRead, 2, false);25test('Subprocess buffers stdio[*], which does not prevent exit if not read and buffer is false', testBufferNotRead, 3, false);26test('Subprocess buffers all, which does not prevent exit if not read and buffer is false', testBufferNotRead, 1, true);33 process.kill(subprocess.pid, 'SIGINT');3428const testBufferRead = async (t, fdNumber, all) => {29 const subprocess = execa('max-buffer.js', [`${fdNumber}`], {...fullStdio, buffer: false, all});30 const stream = all ? subprocess.all : subprocess.stdio[fdNumber];31 stream.resume();32 await t.notThrowsAsync(subprocess);33};35 const {signal} = await t.throwsAsync(subprocess, {message: /was killed with SIGINT/});36 t.is(signal, 'SIGINT');37 });3835test('Subprocess buffers stdout, which does not prevent exit if read and buffer is false', testBufferRead, 1, false);36test('Subprocess buffers stderr, which does not prevent exit if read and buffer is false', testBufferRead, 2, false);37test('Subprocess buffers stdio[*], which does not prevent exit if read and buffer is false', testBufferRead, 3, false);38test('Subprocess buffers all, which does not prevent exit if read and buffer is false', testBufferRead, 1, true);39 test('error.signalDescription is defined', async t => {40 const subprocess = execa('forever.js');4140const testBufferExit = async (t, fdNumber, fixtureName, reject) => {41 const subprocess = execa(fixtureName, [`${fdNumber}`], {...fullStdio, reject});42 await setTimeout(100);43 const {stdio} = await subprocess;44 t.is(stdio[fdNumber], 'foobar');45};42 process.kill(subprocess.pid, 'SIGINT');4347test('Subprocess buffers stdout before it is read', testBufferExit, 1, 'noop-delay.js', true);48test('Subprocess buffers stderr before it is read', testBufferExit, 2, 'noop-delay.js', true);49test('Subprocess buffers stdio[*] before it is read', testBufferExit, 3, 'noop-delay.js', true);50test('Subprocess buffers stdout right away, on successfully exit', testBufferExit, 1, 'noop-fd.js', true);51test('Subprocess buffers stderr right away, on successfully exit', testBufferExit, 2, 'noop-fd.js', true);52test('Subprocess buffers stdio[*] right away, on successfully exit', testBufferExit, 3, 'noop-fd.js', true);53test('Subprocess buffers stdout right away, on failure', testBufferExit, 1, 'noop-fail.js', false);54test('Subprocess buffers stderr right away, on failure', testBufferExit, 2, 'noop-fail.js', false);55test('Subprocess buffers stdio[*] right away, on failure', testBufferExit, 3, 'noop-fail.js', false);44 const {signalDescription} = await t.throwsAsync(subprocess, {message: /User interruption with CTRL-C/});45 t.is(signalDescription, 'User interruption with CTRL-C');46 });4757const testBufferDirect = async (t, fdNumber) => {58 const subprocess = execa('noop-fd.js', [`${fdNumber}`], fullStdio);59 const data = await once(subprocess.stdio[fdNumber], 'data');60 t.is(data.toString().trim(), 'foobar');61 const result = await subprocess;62 t.is(result.stdio[fdNumber], 'foobar');63};48 test('error.signal is SIGTERM', async t => {49 const subprocess = execa('forever.js');5065test('Subprocess buffers stdout right away, even if directly read', testBufferDirect, 1);66test('Subprocess buffers stderr right away, even if directly read', testBufferDirect, 2);67test('Subprocess buffers stdio[*] right away, even if directly read', testBufferDirect, 3);51 process.kill(subprocess.pid, 'SIGTERM');5269const testBufferDestroyOnEnd = async (t, fdNumber) => {70 const subprocess = execa('noop-fd.js', [`${fdNumber}`], fullStdio);71 const result = await subprocess;72 t.is(result.stdio[fdNumber], 'foobar');73 t.true(subprocess.stdio[fdNumber].destroyed);74};53 const {signal} = await t.throwsAsync(subprocess, {message: /was killed with SIGTERM/});54 t.is(signal, 'SIGTERM');55 });5676test('subprocess.stdout must be read right away', testBufferDestroyOnEnd, 1);77test('subprocess.stderr must be read right away', testBufferDestroyOnEnd, 2);78test('subprocess.stdio[*] must be read right away', testBufferDestroyOnEnd, 3);57 test('error.signal uses killSignal', async t => {58 const {signal} = await t.throwsAsync(execa('forever.js', {killSignal: 'SIGINT', timeout: 1, message: /timed out after/}));59 t.is(signal, 'SIGINT');60 });6162 test('exitCode is undefined on signal termination', async t => {63 const subprocess = execa('forever.js');6465 process.kill(subprocess.pid);6667 const {exitCode} = await t.throwsAsync(subprocess);68 t.is(exitCode, undefined);69 });70}7172test('result.signal is undefined for successful execution', async t => {73 const {signal} = await execa('noop.js');74 t.is(signal, undefined);75});7677test('result.signal is undefined if subprocess failed, but was not killed', async t => {78 const {signal} = await t.throwsAsync(execa('fail.js'));79 t.is(signal, undefined);80});8182test('result.signalDescription is undefined for successful execution', async t => {83 const {signalDescription} = await execa('noop.js');84 t.is(signalDescription, undefined);85});
modified:test/stream/no-buffer.js-32 removed
143 unmodified lines
144test('buffer: {stdout: false}, all: true, sync', testNoOutputAll, {stdout: false}, false, true, execaSync);145test('buffer: {stderr: false}, all: true, sync', testNoOutputAll, {stderr: false}, true, false, execaSync);146test('buffer: {all: false}, all: true, sync', testNoOutputAll, {all: false}, false, false, execaSync);147148// eslint-disable-next-line max-params149const testPriorityOrder = async (t, buffer, bufferStdout, bufferStderr, execaMethod) => {150 const {stdout, stderr} = await execaMethod('noop-both.js', {buffer});151 t.is(stdout, bufferStdout ? foobarString : undefined);152 t.is(stderr, bufferStderr ? foobarString : undefined);153};154155test('buffer: {stdout, fd1}', testPriorityOrder, {stdout: true, fd1: false}, true, true, execa);156test('buffer: {stdout, all}', testPriorityOrder, {stdout: true, all: false}, true, false, execa);157test('buffer: {fd1, all}', testPriorityOrder, {fd1: true, all: false}, true, false, execa);158test('buffer: {stderr, fd2}', testPriorityOrder, {stderr: true, fd2: false}, true, true, execa);159test('buffer: {stderr, all}', testPriorityOrder, {stderr: true, all: false}, false, true, execa);160test('buffer: {fd2, all}', testPriorityOrder, {fd2: true, all: false}, false, true, execa);161test('buffer: {fd1, stdout}', testPriorityOrder, {fd1: false, stdout: true}, true, true, execa);162test('buffer: {all, stdout}', testPriorityOrder, {all: false, stdout: true}, true, false, execa);163test('buffer: {all, fd1}', testPriorityOrder, {all: false, fd1: true}, true, false, execa);164test('buffer: {fd2, stderr}', testPriorityOrder, {fd2: false, stderr: true}, true, true, execa);165test('buffer: {all, stderr}', testPriorityOrder, {all: false, stderr: true}, false, true, execa);166test('buffer: {all, fd2}', testPriorityOrder, {all: false, fd2: true}, false, true, execa);167test('buffer: {stdout, fd1}, sync', testPriorityOrder, {stdout: true, fd1: false}, true, true, execaSync);168test('buffer: {stdout, all}, sync', testPriorityOrder, {stdout: true, all: false}, true, false, execaSync);169test('buffer: {fd1, all}, sync', testPriorityOrder, {fd1: true, all: false}, true, false, execaSync);170test('buffer: {stderr, fd2}, sync', testPriorityOrder, {stderr: true, fd2: false}, true, true, execaSync);171test('buffer: {stderr, all}, sync', testPriorityOrder, {stderr: true, all: false}, false, true, execaSync);172test('buffer: {fd2, all}, sync', testPriorityOrder, {fd2: true, all: false}, false, true, execaSync);173test('buffer: {fd1, stdout}, sync', testPriorityOrder, {fd1: false, stdout: true}, true, true, execaSync);174test('buffer: {all, stdout}, sync', testPriorityOrder, {all: false, stdout: true}, true, false, execaSync);175test('buffer: {all, fd1}, sync', testPriorityOrder, {all: false, fd1: true}, true, false, execaSync);176test('buffer: {fd2, stderr}, sync', testPriorityOrder, {fd2: false, stderr: true}, true, true, execaSync);177test('buffer: {all, stderr}, sync', testPriorityOrder, {all: false, stderr: true}, false, true, execaSync);178test('buffer: {all, fd2}, sync', testPriorityOrder, {all: false, fd2: true}, false, true, execaSync);179148const testTransform = async (t, objectMode, execaMethod) => {149 const lines = [];150 const {stdout} = await execaMethod('noop.js', {151 buffer: false,
41 unmodified lines
added:test/stream/wait-abort.js+99 added
1import {setImmediate} from 'node:timers/promises';2import test from 'ava';3import {execa} from '../../index.js';4import {setFixtureDir} from '../helpers/fixtures-dir.js';5import {prematureClose} from '../helpers/stdio.js';6import {noopReadable, noopWritable, noopDuplex} from '../helpers/stream.js';7import {endOptionStream, destroyOptionStream, destroySubprocessStream, getStreamStdio} from '../helpers/wait.js';89setFixtureDir();1011const noop = () => {};1213// eslint-disable-next-line max-params14const testStreamAbortWait = async (t, streamMethod, stream, fdNumber, useTransform) => {15 const subprocess = execa('noop-stdin-fd.js', [`${fdNumber}`], getStreamStdio(fdNumber, stream, useTransform));16 streamMethod({stream, subprocess, fdNumber});17 subprocess.stdin.end();18 await setImmediate();19 stream.destroy();2021 const {stdout} = await subprocess;22 t.is(stdout, '');23 t.true(stream.destroyed);24};2526test('Keeps running when stdin option is used and subprocess.stdin ends', testStreamAbortWait, noop, noopReadable(), 0, false);27test('Keeps running when stdin option is used and subprocess.stdin Duplex ends', testStreamAbortWait, noop, noopDuplex(), 0, false);28test('Keeps running when input stdio[*] option is used and input subprocess.stdio[*] ends', testStreamAbortWait, noop, noopReadable(), 3, false);29test('Keeps running when stdin option is used and subprocess.stdin ends, with a transform', testStreamAbortWait, noop, noopReadable(), 0, true);30test('Keeps running when stdin option is used and subprocess.stdin Duplex ends, with a transform', testStreamAbortWait, noop, noopDuplex(), 0, true);31test('Keeps running when input stdio[*] option is used and input subprocess.stdio[*] ends, with a transform', testStreamAbortWait, noop, noopReadable(), 3, true);3233// eslint-disable-next-line max-params34const testStreamAbortSuccess = async (t, streamMethod, stream, fdNumber, useTransform) => {35 const subprocess = execa('noop-stdin-fd.js', [`${fdNumber}`], getStreamStdio(fdNumber, stream, useTransform));36 streamMethod({stream, subprocess, fdNumber});37 subprocess.stdin.end();3839 const {stdout} = await subprocess;40 t.is(stdout, '');41 t.true(stream.destroyed);42};4344test('Passes when stdin option aborts', testStreamAbortSuccess, destroyOptionStream, noopReadable(), 0, false);45test('Passes when stdin option Duplex aborts', testStreamAbortSuccess, destroyOptionStream, noopDuplex(), 0, false);46test('Passes when input stdio[*] option aborts', testStreamAbortSuccess, destroyOptionStream, noopReadable(), 3, false);47test('Passes when stdout option ends with no more writes', testStreamAbortSuccess, endOptionStream, noopWritable(), 1, false);48test('Passes when stderr option ends with no more writes', testStreamAbortSuccess, endOptionStream, noopWritable(), 2, false);49test('Passes when output stdio[*] option ends with no more writes', testStreamAbortSuccess, endOptionStream, noopWritable(), 3, false);50test('Passes when subprocess.stdout aborts with no more writes', testStreamAbortSuccess, destroySubprocessStream, noopWritable(), 1, false);51test('Passes when subprocess.stdout Duplex aborts with no more writes', testStreamAbortSuccess, destroySubprocessStream, noopDuplex(), 1, false);52test('Passes when subprocess.stderr aborts with no more writes', testStreamAbortSuccess, destroySubprocessStream, noopWritable(), 2, false);53test('Passes when subprocess.stderr Duplex aborts with no more writes', testStreamAbortSuccess, destroySubprocessStream, noopDuplex(), 2, false);54test('Passes when output subprocess.stdio[*] aborts with no more writes', testStreamAbortSuccess, destroySubprocessStream, noopWritable(), 3, false);55test('Passes when output subprocess.stdio[*] Duplex aborts with no more writes', testStreamAbortSuccess, destroySubprocessStream, noopDuplex(), 3, false);56test('Passes when stdin option aborts, with a transform', testStreamAbortSuccess, destroyOptionStream, noopReadable(), 0, true);57test('Passes when stdin option Duplex aborts, with a transform', testStreamAbortSuccess, destroyOptionStream, noopDuplex(), 0, true);58test('Passes when input stdio[*] option aborts, with a transform', testStreamAbortSuccess, destroyOptionStream, noopReadable(), 3, true);59test('Passes when stdout option ends with no more writes, with a transform', testStreamAbortSuccess, endOptionStream, noopWritable(), 1, true);60test('Passes when stderr option ends with no more writes, with a transform', testStreamAbortSuccess, endOptionStream, noopWritable(), 2, true);61test('Passes when output stdio[*] option ends with no more writes, with a transform', testStreamAbortSuccess, endOptionStream, noopWritable(), 3, true);62test('Passes when subprocess.stdout aborts with no more writes, with a transform', testStreamAbortSuccess, destroySubprocessStream, noopWritable(), 1, true);63test('Passes when subprocess.stdout Duplex aborts with no more writes, with a transform', testStreamAbortSuccess, destroySubprocessStream, noopDuplex(), 1, true);64test('Passes when subprocess.stderr aborts with no more writes, with a transform', testStreamAbortSuccess, destroySubprocessStream, noopWritable(), 2, true);65test('Passes when subprocess.stderr Duplex aborts with no more writes, with a transform', testStreamAbortSuccess, destroySubprocessStream, noopDuplex(), 2, true);66test('Passes when output subprocess.stdio[*] aborts with no more writes, with a transform', testStreamAbortSuccess, destroySubprocessStream, noopWritable(), 3, true);67test('Passes when output subprocess.stdio[*] Duplex aborts with no more writes, with a transform', testStreamAbortSuccess, destroySubprocessStream, noopDuplex(), 3, true);6869// eslint-disable-next-line max-params70const testStreamAbortFail = async (t, streamMethod, stream, fdNumber, useTransform) => {71 const subprocess = execa('noop-stdin-fd.js', [`${fdNumber}`], getStreamStdio(fdNumber, stream, useTransform));72 streamMethod({stream, subprocess, fdNumber});73 if (fdNumber !== 0) {74 subprocess.stdin.end();75 }7677 const error = await t.throwsAsync(subprocess);78 t.like(error, {...prematureClose, exitCode: 0});79 t.true(stream.destroyed);80};8182test('Throws abort error when subprocess.stdin aborts', testStreamAbortFail, destroySubprocessStream, noopReadable(), 0, false);83test('Throws abort error when subprocess.stdin Duplex aborts', testStreamAbortFail, destroySubprocessStream, noopDuplex(), 0, false);84test('Throws abort error when input subprocess.stdio[*] aborts', testStreamAbortFail, destroySubprocessStream, noopReadable(), 3, false);85test('Throws abort error when stdout option aborts with no more writes', testStreamAbortFail, destroyOptionStream, noopWritable(), 1, false);86test('Throws abort error when stdout option Duplex aborts with no more writes', testStreamAbortFail, destroyOptionStream, noopDuplex(), 1, false);87test('Throws abort error when stderr option aborts with no more writes', testStreamAbortFail, destroyOptionStream, noopWritable(), 2, false);88test('Throws abort error when stderr option Duplex aborts with no more writes', testStreamAbortFail, destroyOptionStream, noopDuplex(), 2, false);89test('Throws abort error when output stdio[*] option aborts with no more writes', testStreamAbortFail, destroyOptionStream, noopWritable(), 3, false);90test('Throws abort error when output stdio[*] Duplex option aborts with no more writes', testStreamAbortFail, destroyOptionStream, noopDuplex(), 3, false);91test('Throws abort error when subprocess.stdin aborts, with a transform', testStreamAbortFail, destroySubprocessStream, noopReadable(), 0, true);92test('Throws abort error when subprocess.stdin Duplex aborts, with a transform', testStreamAbortFail, destroySubprocessStream, noopDuplex(), 0, true);93test('Throws abort error when input subprocess.stdio[*] aborts, with a transform', testStreamAbortFail, destroySubprocessStream, noopReadable(), 3, true);94test('Throws abort error when stdout option aborts with no more writes, with a transform', testStreamAbortFail, destroyOptionStream, noopWritable(), 1, true);95test('Throws abort error when stdout option Duplex aborts with no more writes, with a transform', testStreamAbortFail, destroyOptionStream, noopDuplex(), 1, true);96test('Throws abort error when stderr option aborts with no more writes, with a transform', testStreamAbortFail, destroyOptionStream, noopWritable(), 2, true);97test('Throws abort error when stderr option Duplex aborts with no more writes, with a transform', testStreamAbortFail, destroyOptionStream, noopDuplex(), 2, true);98test('Throws abort error when output stdio[*] option aborts with no more writes, with a transform', testStreamAbortFail, destroyOptionStream, noopWritable(), 3, true);99test('Throws abort error when output stdio[*] Duplex option aborts with no more writes, with a transform', testStreamAbortFail, destroyOptionStream, noopDuplex(), 3, true);
added:test/stream/wait-epipe.js+55 added
1import {setImmediate} from 'node:timers/promises';2import test from 'ava';3import {execa} from '../../index.js';4import {setFixtureDir} from '../helpers/fixtures-dir.js';5import {assertEpipe} from '../helpers/stdio.js';6import {foobarString} from '../helpers/input.js';7import {noopWritable, noopDuplex} from '../helpers/stream.js';8import {endOptionStream, destroyOptionStream, destroySubprocessStream, getStreamStdio} from '../helpers/wait.js';910setFixtureDir();1112// eslint-disable-next-line max-params13const testStreamEpipeFail = async (t, streamMethod, stream, fdNumber, useTransform) => {14 const subprocess = execa('noop-stdin-fd.js', [`${fdNumber}`], getStreamStdio(fdNumber, stream, useTransform));15 streamMethod({stream, subprocess, fdNumber});16 await setImmediate();17 subprocess.stdin.end(foobarString);1819 const {exitCode, stdio, stderr} = await t.throwsAsync(subprocess);20 t.is(exitCode, 1);21 t.is(stdio[fdNumber], '');22 t.true(stream.destroyed);23 assertEpipe(t, stderr, fdNumber);24};2526test('Throws EPIPE when stdout option ends with more writes', testStreamEpipeFail, endOptionStream, noopWritable(), 1, false);27test('Throws EPIPE when stdout option aborts with more writes', testStreamEpipeFail, destroyOptionStream, noopWritable(), 1, false);28test('Throws EPIPE when stdout option Duplex aborts with more writes', testStreamEpipeFail, destroyOptionStream, noopDuplex(), 1, false);29test('Throws EPIPE when stderr option ends with more writes', testStreamEpipeFail, endOptionStream, noopWritable(), 2, false);30test('Throws EPIPE when stderr option aborts with more writes', testStreamEpipeFail, destroyOptionStream, noopWritable(), 2, false);31test('Throws EPIPE when stderr option Duplex aborts with more writes', testStreamEpipeFail, destroyOptionStream, noopDuplex(), 2, false);32test('Throws EPIPE when output stdio[*] option ends with more writes', testStreamEpipeFail, endOptionStream, noopWritable(), 3, false);33test('Throws EPIPE when output stdio[*] option aborts with more writes', testStreamEpipeFail, destroyOptionStream, noopWritable(), 3, false);34test('Throws EPIPE when output stdio[*] option Duplex aborts with more writes', testStreamEpipeFail, destroyOptionStream, noopDuplex(), 3, false);35test('Throws EPIPE when subprocess.stdout aborts with more writes', testStreamEpipeFail, destroySubprocessStream, noopWritable(), 1, false);36test('Throws EPIPE when subprocess.stdout Duplex aborts with more writes', testStreamEpipeFail, destroySubprocessStream, noopDuplex(), 1, false);37test('Throws EPIPE when subprocess.stderr aborts with more writes', testStreamEpipeFail, destroySubprocessStream, noopWritable(), 2, false);38test('Throws EPIPE when subprocess.stderr Duplex aborts with more writes', testStreamEpipeFail, destroySubprocessStream, noopDuplex(), 2, false);39test('Throws EPIPE when output subprocess.stdio[*] aborts with more writes', testStreamEpipeFail, destroySubprocessStream, noopWritable(), 3, false);40test('Throws EPIPE when output subprocess.stdio[*] Duplex aborts with more writes', testStreamEpipeFail, destroySubprocessStream, noopDuplex(), 3, false);41test('Throws EPIPE when stdout option ends with more writes, with a transform', testStreamEpipeFail, endOptionStream, noopWritable(), 1, true);42test('Throws EPIPE when stdout option aborts with more writes, with a transform', testStreamEpipeFail, destroyOptionStream, noopWritable(), 1, true);43test('Throws EPIPE when stdout option Duplex aborts with more writes, with a transform', testStreamEpipeFail, destroyOptionStream, noopDuplex(), 1, true);44test('Throws EPIPE when stderr option ends with more writes, with a transform', testStreamEpipeFail, endOptionStream, noopWritable(), 2, true);45test('Throws EPIPE when stderr option aborts with more writes, with a transform', testStreamEpipeFail, destroyOptionStream, noopWritable(), 2, true);46test('Throws EPIPE when stderr option Duplex aborts with more writes, with a transform', testStreamEpipeFail, destroyOptionStream, noopDuplex(), 2, true);47test('Throws EPIPE when output stdio[*] option ends with more writes, with a transform', testStreamEpipeFail, endOptionStream, noopWritable(), 3, true);48test('Throws EPIPE when output stdio[*] option aborts with more writes, with a transform', testStreamEpipeFail, destroyOptionStream, noopWritable(), 3, true);49test('Throws EPIPE when output stdio[*] option Duplex aborts with more writes, with a transform', testStreamEpipeFail, destroyOptionStream, noopDuplex(), 3, true);50test('Throws EPIPE when subprocess.stdout aborts with more writes, with a transform', testStreamEpipeFail, destroySubprocessStream, noopWritable(), 1, true);51test('Throws EPIPE when subprocess.stdout Duplex aborts with more writes, with a transform', testStreamEpipeFail, destroySubprocessStream, noopDuplex(), 1, true);52test('Throws EPIPE when subprocess.stderr aborts with more writes, with a transform', testStreamEpipeFail, destroySubprocessStream, noopWritable(), 2, true);53test('Throws EPIPE when subprocess.stderr Duplex aborts with more writes, with a transform', testStreamEpipeFail, destroySubprocessStream, noopDuplex(), 2, true);54test('Throws EPIPE when output subprocess.stdio[*] aborts with more writes, with a transform', testStreamEpipeFail, destroySubprocessStream, noopWritable(), 3, true);55test('Throws EPIPE when output subprocess.stdio[*] Duplex aborts with more writes, with a transform', testStreamEpipeFail, destroySubprocessStream, noopDuplex(), 3, true);
added:test/stream/wait-error.js+59 added
1import test from 'ava';2import {execa} from '../../index.js';3import {setFixtureDir} from '../helpers/fixtures-dir.js';4import {noopReadable, noopWritable, noopDuplex} from '../helpers/stream.js';5import {destroyOptionStream, destroySubprocessStream, getStreamStdio} from '../helpers/wait.js';67setFixtureDir();89// eslint-disable-next-line max-params10const testStreamError = async (t, streamMethod, stream, fdNumber, useTransform) => {11 const subprocess = execa('empty.js', getStreamStdio(fdNumber, stream, useTransform));12 const cause = new Error('test');13 streamMethod({stream, subprocess, fdNumber, error: cause});1415 const error = await t.throwsAsync(subprocess);16 t.is(error.cause, cause);17 t.is(error.exitCode, 0);18 t.is(error.signal, undefined);19 t.false(error.isTerminated);20 t.true(error.failed);21 t.true(stream.destroyed);22};2324test('Throws stream error when stdin option errors', testStreamError, destroyOptionStream, noopReadable(), 0, false);25test('Throws stream error when stdin option Duplex errors', testStreamError, destroyOptionStream, noopDuplex(), 0, false);26test('Throws stream error when stdout option errors', testStreamError, destroyOptionStream, noopWritable(), 1, false);27test('Throws stream error when stdout option Duplex errors', testStreamError, destroyOptionStream, noopDuplex(), 1, false);28test('Throws stream error when stderr option errors', testStreamError, destroyOptionStream, noopWritable(), 2, false);29test('Throws stream error when stderr option Duplex errors', testStreamError, destroyOptionStream, noopDuplex(), 2, false);30test('Throws stream error when output stdio[*] option errors', testStreamError, destroyOptionStream, noopWritable(), 3, false);31test('Throws stream error when output stdio[*] Duplex option errors', testStreamError, destroyOptionStream, noopDuplex(), 3, false);32test('Throws stream error when input stdio[*] option errors', testStreamError, destroyOptionStream, noopReadable(), 3, false);33test('Throws stream error when subprocess.stdin errors', testStreamError, destroySubprocessStream, noopReadable(), 0, false);34test('Throws stream error when subprocess.stdin Duplex errors', testStreamError, destroySubprocessStream, noopDuplex(), 0, false);35test('Throws stream error when subprocess.stdout errors', testStreamError, destroySubprocessStream, noopWritable(), 1, false);36test('Throws stream error when subprocess.stdout Duplex errors', testStreamError, destroySubprocessStream, noopDuplex(), 1, false);37test('Throws stream error when subprocess.stderr errors', testStreamError, destroySubprocessStream, noopWritable(), 2, false);38test('Throws stream error when subprocess.stderr Duplex errors', testStreamError, destroySubprocessStream, noopDuplex(), 2, false);39test('Throws stream error when output subprocess.stdio[*] errors', testStreamError, destroySubprocessStream, noopWritable(), 3, false);40test('Throws stream error when output subprocess.stdio[*] Duplex errors', testStreamError, destroySubprocessStream, noopDuplex(), 3, false);41test('Throws stream error when input subprocess.stdio[*] errors', testStreamError, destroySubprocessStream, noopReadable(), 3, false);42test('Throws stream error when stdin option errors, with a transform', testStreamError, destroyOptionStream, noopReadable(), 0, true);43test('Throws stream error when stdin option Duplex errors, with a transform', testStreamError, destroyOptionStream, noopDuplex(), 0, true);44test('Throws stream error when stdout option errors, with a transform', testStreamError, destroyOptionStream, noopWritable(), 1, true);45test('Throws stream error when stdout option Duplex errors, with a transform', testStreamError, destroyOptionStream, noopDuplex(), 1, true);46test('Throws stream error when stderr option errors, with a transform', testStreamError, destroyOptionStream, noopWritable(), 2, true);47test('Throws stream error when stderr option Duplex errors, with a transform', testStreamError, destroyOptionStream, noopDuplex(), 2, true);48test('Throws stream error when output stdio[*] option errors, with a transform', testStreamError, destroyOptionStream, noopWritable(), 3, true);49test('Throws stream error when output stdio[*] Duplex option errors, with a transform', testStreamError, destroyOptionStream, noopDuplex(), 3, true);50test('Throws stream error when input stdio[*] option errors, with a transform', testStreamError, destroyOptionStream, noopReadable(), 3, true);51test('Throws stream error when subprocess.stdin errors, with a transform', testStreamError, destroySubprocessStream, noopReadable(), 0, true);52test('Throws stream error when subprocess.stdin Duplex errors, with a transform', testStreamError, destroySubprocessStream, noopDuplex(), 0, true);53test('Throws stream error when subprocess.stdout errors, with a transform', testStreamError, destroySubprocessStream, noopWritable(), 1, true);54test('Throws stream error when subprocess.stdout Duplex errors, with a transform', testStreamError, destroySubprocessStream, noopDuplex(), 1, true);55test('Throws stream error when subprocess.stderr errors, with a transform', testStreamError, destroySubprocessStream, noopWritable(), 2, true);56test('Throws stream error when subprocess.stderr Duplex errors, with a transform', testStreamError, destroySubprocessStream, noopDuplex(), 2, true);57test('Throws stream error when output subprocess.stdio[*] errors, with a transform', testStreamError, destroySubprocessStream, noopWritable(), 3, true);58test('Throws stream error when output subprocess.stdio[*] Duplex errors, with a transform', testStreamError, destroySubprocessStream, noopDuplex(), 3, true);59test('Throws stream error when input subprocess.stdio[*] errors, with a transform', testStreamError, destroySubprocessStream, noopReadable(), 3, true);
deleted:test/stream/wait.js-211 removed
1import {setImmediate} from 'node:timers/promises';2import test from 'ava';3import {execa} from '../../index.js';4import {setFixtureDir} from '../helpers/fixtures-dir.js';5import {getStdio, prematureClose, assertEpipe} from '../helpers/stdio.js';6import {foobarString} from '../helpers/input.js';7import {noopGenerator} from '../helpers/generator.js';8import {noopReadable, noopWritable, noopDuplex} from '../helpers/stream.js';910setFixtureDir();1112const noop = () => {};1314const endOptionStream = ({stream}) => {15 stream.end();16};1718const destroyOptionStream = ({stream, error}) => {19 stream.destroy(error);20};2122const destroySubprocessStream = ({subprocess, fdNumber, error}) => {23 subprocess.stdio[fdNumber].destroy(error);24};2526const getStreamStdio = (fdNumber, stream, useTransform) => getStdio(fdNumber, [stream, useTransform ? noopGenerator(false) : 'pipe']);2728// eslint-disable-next-line max-params29const testStreamAbortWait = async (t, streamMethod, stream, fdNumber, useTransform) => {30 const subprocess = execa('noop-stdin-fd.js', [`${fdNumber}`], getStreamStdio(fdNumber, stream, useTransform));31 streamMethod({stream, subprocess, fdNumber});32 subprocess.stdin.end();33 await setImmediate();34 stream.destroy();3536 const {stdout} = await subprocess;37 t.is(stdout, '');38 t.true(stream.destroyed);39};4041test('Keeps running when stdin option is used and subprocess.stdin ends', testStreamAbortWait, noop, noopReadable(), 0, false);42test('Keeps running when stdin option is used and subprocess.stdin Duplex ends', testStreamAbortWait, noop, noopDuplex(), 0, false);43test('Keeps running when input stdio[*] option is used and input subprocess.stdio[*] ends', testStreamAbortWait, noop, noopReadable(), 3, false);44test('Keeps running when stdin option is used and subprocess.stdin ends, with a transform', testStreamAbortWait, noop, noopReadable(), 0, true);45test('Keeps running when stdin option is used and subprocess.stdin Duplex ends, with a transform', testStreamAbortWait, noop, noopDuplex(), 0, true);46test('Keeps running when input stdio[*] option is used and input subprocess.stdio[*] ends, with a transform', testStreamAbortWait, noop, noopReadable(), 3, true);4748// eslint-disable-next-line max-params49const testStreamAbortSuccess = async (t, streamMethod, stream, fdNumber, useTransform) => {50 const subprocess = execa('noop-stdin-fd.js', [`${fdNumber}`], getStreamStdio(fdNumber, stream, useTransform));51 streamMethod({stream, subprocess, fdNumber});52 subprocess.stdin.end();5354 const {stdout} = await subprocess;55 t.is(stdout, '');56 t.true(stream.destroyed);57};5859test('Passes when stdin option aborts', testStreamAbortSuccess, destroyOptionStream, noopReadable(), 0, false);60test('Passes when stdin option Duplex aborts', testStreamAbortSuccess, destroyOptionStream, noopDuplex(), 0, false);61test('Passes when input stdio[*] option aborts', testStreamAbortSuccess, destroyOptionStream, noopReadable(), 3, false);62test('Passes when stdout option ends with no more writes', testStreamAbortSuccess, endOptionStream, noopWritable(), 1, false);63test('Passes when stderr option ends with no more writes', testStreamAbortSuccess, endOptionStream, noopWritable(), 2, false);64test('Passes when output stdio[*] option ends with no more writes', testStreamAbortSuccess, endOptionStream, noopWritable(), 3, false);65test('Passes when subprocess.stdout aborts with no more writes', testStreamAbortSuccess, destroySubprocessStream, noopWritable(), 1, false);66test('Passes when subprocess.stdout Duplex aborts with no more writes', testStreamAbortSuccess, destroySubprocessStream, noopDuplex(), 1, false);67test('Passes when subprocess.stderr aborts with no more writes', testStreamAbortSuccess, destroySubprocessStream, noopWritable(), 2, false);68test('Passes when subprocess.stderr Duplex aborts with no more writes', testStreamAbortSuccess, destroySubprocessStream, noopDuplex(), 2, false);69test('Passes when output subprocess.stdio[*] aborts with no more writes', testStreamAbortSuccess, destroySubprocessStream, noopWritable(), 3, false);70test('Passes when output subprocess.stdio[*] Duplex aborts with no more writes', testStreamAbortSuccess, destroySubprocessStream, noopDuplex(), 3, false);71test('Passes when stdin option aborts, with a transform', testStreamAbortSuccess, destroyOptionStream, noopReadable(), 0, true);72test('Passes when stdin option Duplex aborts, with a transform', testStreamAbortSuccess, destroyOptionStream, noopDuplex(), 0, true);73test('Passes when input stdio[*] option aborts, with a transform', testStreamAbortSuccess, destroyOptionStream, noopReadable(), 3, true);74test('Passes when stdout option ends with no more writes, with a transform', testStreamAbortSuccess, endOptionStream, noopWritable(), 1, true);75test('Passes when stderr option ends with no more writes, with a transform', testStreamAbortSuccess, endOptionStream, noopWritable(), 2, true);76test('Passes when output stdio[*] option ends with no more writes, with a transform', testStreamAbortSuccess, endOptionStream, noopWritable(), 3, true);77test('Passes when subprocess.stdout aborts with no more writes, with a transform', testStreamAbortSuccess, destroySubprocessStream, noopWritable(), 1, true);78test('Passes when subprocess.stdout Duplex aborts with no more writes, with a transform', testStreamAbortSuccess, destroySubprocessStream, noopDuplex(), 1, true);79test('Passes when subprocess.stderr aborts with no more writes, with a transform', testStreamAbortSuccess, destroySubprocessStream, noopWritable(), 2, true);80test('Passes when subprocess.stderr Duplex aborts with no more writes, with a transform', testStreamAbortSuccess, destroySubprocessStream, noopDuplex(), 2, true);81test('Passes when output subprocess.stdio[*] aborts with no more writes, with a transform', testStreamAbortSuccess, destroySubprocessStream, noopWritable(), 3, true);82test('Passes when output subprocess.stdio[*] Duplex aborts with no more writes, with a transform', testStreamAbortSuccess, destroySubprocessStream, noopDuplex(), 3, true);8384// eslint-disable-next-line max-params85const testStreamAbortFail = async (t, streamMethod, stream, fdNumber, useTransform) => {86 const subprocess = execa('noop-stdin-fd.js', [`${fdNumber}`], getStreamStdio(fdNumber, stream, useTransform));87 streamMethod({stream, subprocess, fdNumber});88 if (fdNumber !== 0) {89 subprocess.stdin.end();90 }9192 const error = await t.throwsAsync(subprocess);93 t.like(error, {...prematureClose, exitCode: 0});94 t.true(stream.destroyed);95};9697test('Throws abort error when subprocess.stdin aborts', testStreamAbortFail, destroySubprocessStream, noopReadable(), 0, false);98test('Throws abort error when subprocess.stdin Duplex aborts', testStreamAbortFail, destroySubprocessStream, noopDuplex(), 0, false);99test('Throws abort error when input subprocess.stdio[*] aborts', testStreamAbortFail, destroySubprocessStream, noopReadable(), 3, false);100test('Throws abort error when stdout option aborts with no more writes', testStreamAbortFail, destroyOptionStream, noopWritable(), 1, false);101test('Throws abort error when stdout option Duplex aborts with no more writes', testStreamAbortFail, destroyOptionStream, noopDuplex(), 1, false);102test('Throws abort error when stderr option aborts with no more writes', testStreamAbortFail, destroyOptionStream, noopWritable(), 2, false);103test('Throws abort error when stderr option Duplex aborts with no more writes', testStreamAbortFail, destroyOptionStream, noopDuplex(), 2, false);104test('Throws abort error when output stdio[*] option aborts with no more writes', testStreamAbortFail, destroyOptionStream, noopWritable(), 3, false);105test('Throws abort error when output stdio[*] Duplex option aborts with no more writes', testStreamAbortFail, destroyOptionStream, noopDuplex(), 3, false);106test('Throws abort error when subprocess.stdin aborts, with a transform', testStreamAbortFail, destroySubprocessStream, noopReadable(), 0, true);107test('Throws abort error when subprocess.stdin Duplex aborts, with a transform', testStreamAbortFail, destroySubprocessStream, noopDuplex(), 0, true);108test('Throws abort error when input subprocess.stdio[*] aborts, with a transform', testStreamAbortFail, destroySubprocessStream, noopReadable(), 3, true);109test('Throws abort error when stdout option aborts with no more writes, with a transform', testStreamAbortFail, destroyOptionStream, noopWritable(), 1, true);110test('Throws abort error when stdout option Duplex aborts with no more writes, with a transform', testStreamAbortFail, destroyOptionStream, noopDuplex(), 1, true);111test('Throws abort error when stderr option aborts with no more writes, with a transform', testStreamAbortFail, destroyOptionStream, noopWritable(), 2, true);112test('Throws abort error when stderr option Duplex aborts with no more writes, with a transform', testStreamAbortFail, destroyOptionStream, noopDuplex(), 2, true);113test('Throws abort error when output stdio[*] option aborts with no more writes, with a transform', testStreamAbortFail, destroyOptionStream, noopWritable(), 3, true);114test('Throws abort error when output stdio[*] Duplex option aborts with no more writes, with a transform', testStreamAbortFail, destroyOptionStream, noopDuplex(), 3, true);115116// eslint-disable-next-line max-params117const testStreamEpipeFail = async (t, streamMethod, stream, fdNumber, useTransform) => {118 const subprocess = execa('noop-stdin-fd.js', [`${fdNumber}`], getStreamStdio(fdNumber, stream, useTransform));119 streamMethod({stream, subprocess, fdNumber});120 await setImmediate();121 subprocess.stdin.end(foobarString);122123 const {exitCode, stdio, stderr} = await t.throwsAsync(subprocess);124 t.is(exitCode, 1);125 t.is(stdio[fdNumber], '');126 t.true(stream.destroyed);127 assertEpipe(t, stderr, fdNumber);128};129130test('Throws EPIPE when stdout option ends with more writes', testStreamEpipeFail, endOptionStream, noopWritable(), 1, false);131test('Throws EPIPE when stdout option aborts with more writes', testStreamEpipeFail, destroyOptionStream, noopWritable(), 1, false);132test('Throws EPIPE when stdout option Duplex aborts with more writes', testStreamEpipeFail, destroyOptionStream, noopDuplex(), 1, false);133test('Throws EPIPE when stderr option ends with more writes', testStreamEpipeFail, endOptionStream, noopWritable(), 2, false);134test('Throws EPIPE when stderr option aborts with more writes', testStreamEpipeFail, destroyOptionStream, noopWritable(), 2, false);135test('Throws EPIPE when stderr option Duplex aborts with more writes', testStreamEpipeFail, destroyOptionStream, noopDuplex(), 2, false);136test('Throws EPIPE when output stdio[*] option ends with more writes', testStreamEpipeFail, endOptionStream, noopWritable(), 3, false);137test('Throws EPIPE when output stdio[*] option aborts with more writes', testStreamEpipeFail, destroyOptionStream, noopWritable(), 3, false);138test('Throws EPIPE when output stdio[*] option Duplex aborts with more writes', testStreamEpipeFail, destroyOptionStream, noopDuplex(), 3, false);139test('Throws EPIPE when subprocess.stdout aborts with more writes', testStreamEpipeFail, destroySubprocessStream, noopWritable(), 1, false);140test('Throws EPIPE when subprocess.stdout Duplex aborts with more writes', testStreamEpipeFail, destroySubprocessStream, noopDuplex(), 1, false);141test('Throws EPIPE when subprocess.stderr aborts with more writes', testStreamEpipeFail, destroySubprocessStream, noopWritable(), 2, false);142test('Throws EPIPE when subprocess.stderr Duplex aborts with more writes', testStreamEpipeFail, destroySubprocessStream, noopDuplex(), 2, false);143test('Throws EPIPE when output subprocess.stdio[*] aborts with more writes', testStreamEpipeFail, destroySubprocessStream, noopWritable(), 3, false);144test('Throws EPIPE when output subprocess.stdio[*] Duplex aborts with more writes', testStreamEpipeFail, destroySubprocessStream, noopDuplex(), 3, false);145test('Throws EPIPE when stdout option ends with more writes, with a transform', testStreamEpipeFail, endOptionStream, noopWritable(), 1, true);146test('Throws EPIPE when stdout option aborts with more writes, with a transform', testStreamEpipeFail, destroyOptionStream, noopWritable(), 1, true);147test('Throws EPIPE when stdout option Duplex aborts with more writes, with a transform', testStreamEpipeFail, destroyOptionStream, noopDuplex(), 1, true);148test('Throws EPIPE when stderr option ends with more writes, with a transform', testStreamEpipeFail, endOptionStream, noopWritable(), 2, true);149test('Throws EPIPE when stderr option aborts with more writes, with a transform', testStreamEpipeFail, destroyOptionStream, noopWritable(), 2, true);150test('Throws EPIPE when stderr option Duplex aborts with more writes, with a transform', testStreamEpipeFail, destroyOptionStream, noopDuplex(), 2, true);151test('Throws EPIPE when output stdio[*] option ends with more writes, with a transform', testStreamEpipeFail, endOptionStream, noopWritable(), 3, true);152test('Throws EPIPE when output stdio[*] option aborts with more writes, with a transform', testStreamEpipeFail, destroyOptionStream, noopWritable(), 3, true);153test('Throws EPIPE when output stdio[*] option Duplex aborts with more writes, with a transform', testStreamEpipeFail, destroyOptionStream, noopDuplex(), 3, true);154test('Throws EPIPE when subprocess.stdout aborts with more writes, with a transform', testStreamEpipeFail, destroySubprocessStream, noopWritable(), 1, true);155test('Throws EPIPE when subprocess.stdout Duplex aborts with more writes, with a transform', testStreamEpipeFail, destroySubprocessStream, noopDuplex(), 1, true);156test('Throws EPIPE when subprocess.stderr aborts with more writes, with a transform', testStreamEpipeFail, destroySubprocessStream, noopWritable(), 2, true);157test('Throws EPIPE when subprocess.stderr Duplex aborts with more writes, with a transform', testStreamEpipeFail, destroySubprocessStream, noopDuplex(), 2, true);158test('Throws EPIPE when output subprocess.stdio[*] aborts with more writes, with a transform', testStreamEpipeFail, destroySubprocessStream, noopWritable(), 3, true);159test('Throws EPIPE when output subprocess.stdio[*] Duplex aborts with more writes, with a transform', testStreamEpipeFail, destroySubprocessStream, noopDuplex(), 3, true);160161// eslint-disable-next-line max-params162const testStreamError = async (t, streamMethod, stream, fdNumber, useTransform) => {163 const subprocess = execa('empty.js', getStreamStdio(fdNumber, stream, useTransform));164 const cause = new Error('test');165 streamMethod({stream, subprocess, fdNumber, error: cause});166167 const error = await t.throwsAsync(subprocess);168 t.is(error.cause, cause);169 t.is(error.exitCode, 0);170 t.is(error.signal, undefined);171 t.false(error.isTerminated);172 t.true(error.failed);173 t.true(stream.destroyed);174};175176test('Throws stream error when stdin option errors', testStreamError, destroyOptionStream, noopReadable(), 0, false);177test('Throws stream error when stdin option Duplex errors', testStreamError, destroyOptionStream, noopDuplex(), 0, false);178test('Throws stream error when stdout option errors', testStreamError, destroyOptionStream, noopWritable(), 1, false);179test('Throws stream error when stdout option Duplex errors', testStreamError, destroyOptionStream, noopDuplex(), 1, false);180test('Throws stream error when stderr option errors', testStreamError, destroyOptionStream, noopWritable(), 2, false);181test('Throws stream error when stderr option Duplex errors', testStreamError, destroyOptionStream, noopDuplex(), 2, false);182test('Throws stream error when output stdio[*] option errors', testStreamError, destroyOptionStream, noopWritable(), 3, false);183test('Throws stream error when output stdio[*] Duplex option errors', testStreamError, destroyOptionStream, noopDuplex(), 3, false);184test('Throws stream error when input stdio[*] option errors', testStreamError, destroyOptionStream, noopReadable(), 3, false);185test('Throws stream error when subprocess.stdin errors', testStreamError, destroySubprocessStream, noopReadable(), 0, false);186test('Throws stream error when subprocess.stdin Duplex errors', testStreamError, destroySubprocessStream, noopDuplex(), 0, false);187test('Throws stream error when subprocess.stdout errors', testStreamError, destroySubprocessStream, noopWritable(), 1, false);188test('Throws stream error when subprocess.stdout Duplex errors', testStreamError, destroySubprocessStream, noopDuplex(), 1, false);189test('Throws stream error when subprocess.stderr errors', testStreamError, destroySubprocessStream, noopWritable(), 2, false);190test('Throws stream error when subprocess.stderr Duplex errors', testStreamError, destroySubprocessStream, noopDuplex(), 2, false);191test('Throws stream error when output subprocess.stdio[*] errors', testStreamError, destroySubprocessStream, noopWritable(), 3, false);192test('Throws stream error when output subprocess.stdio[*] Duplex errors', testStreamError, destroySubprocessStream, noopDuplex(), 3, false);193test('Throws stream error when input subprocess.stdio[*] errors', testStreamError, destroySubprocessStream, noopReadable(), 3, false);194test('Throws stream error when stdin option errors, with a transform', testStreamError, destroyOptionStream, noopReadable(), 0, true);195test('Throws stream error when stdin option Duplex errors, with a transform', testStreamError, destroyOptionStream, noopDuplex(), 0, true);196test('Throws stream error when stdout option errors, with a transform', testStreamError, destroyOptionStream, noopWritable(), 1, true);197test('Throws stream error when stdout option Duplex errors, with a transform', testStreamError, destroyOptionStream, noopDuplex(), 1, true);198test('Throws stream error when stderr option errors, with a transform', testStreamError, destroyOptionStream, noopWritable(), 2, true);199test('Throws stream error when stderr option Duplex errors, with a transform', testStreamError, destroyOptionStream, noopDuplex(), 2, true);200test('Throws stream error when output stdio[*] option errors, with a transform', testStreamError, destroyOptionStream, noopWritable(), 3, true);201test('Throws stream error when output stdio[*] Duplex option errors, with a transform', testStreamError, destroyOptionStream, noopDuplex(), 3, true);202test('Throws stream error when input stdio[*] option errors, with a transform', testStreamError, destroyOptionStream, noopReadable(), 3, true);203test('Throws stream error when subprocess.stdin errors, with a transform', testStreamError, destroySubprocessStream, noopReadable(), 0, true);204test('Throws stream error when subprocess.stdin Duplex errors, with a transform', testStreamError, destroySubprocessStream, noopDuplex(), 0, true);205test('Throws stream error when subprocess.stdout errors, with a transform', testStreamError, destroySubprocessStream, noopWritable(), 1, true);206test('Throws stream error when subprocess.stdout Duplex errors, with a transform', testStreamError, destroySubprocessStream, noopDuplex(), 1, true);207test('Throws stream error when subprocess.stderr errors, with a transform', testStreamError, destroySubprocessStream, noopWritable(), 2, true);208test('Throws stream error when subprocess.stderr Duplex errors, with a transform', testStreamError, destroySubprocessStream, noopDuplex(), 2, true);209test('Throws stream error when output subprocess.stdio[*] errors, with a transform', testStreamError, destroySubprocessStream, noopWritable(), 3, true);210test('Throws stream error when output subprocess.stdio[*] Duplex errors, with a transform', testStreamError, destroySubprocessStream, noopDuplex(), 3, true);211test('Throws stream error when input subprocess.stdio[*] errors, with a transform', testStreamError, destroySubprocessStream, noopReadable(), 3, true);
added:test/verbose/output-buffer.js+39 added
1import test from 'ava';2import {setFixtureDir} from '../helpers/fixtures-dir.js';3import {foobarString, foobarUppercase} from '../helpers/input.js';4import {parentExeca, parentExecaAsync, parentExecaSync} from '../helpers/nested.js';5import {getOutputLine, testTimestamp, fdFullOption, fdStderrFullOption} from '../helpers/verbose.js';67setFixtureDir();89const testPrintOutputNoBuffer = async (t, verbose, buffer, execaMethod) => {10 const {stderr} = await execaMethod('noop.js', [foobarString], {verbose, buffer});11 t.is(getOutputLine(stderr), `${testTimestamp} [0] ${foobarString}`);12};1314test('Prints stdout, buffer: false', testPrintOutputNoBuffer, 'full', false, parentExecaAsync);15test('Prints stdout, buffer: false, fd-specific buffer', testPrintOutputNoBuffer, 'full', {stdout: false}, parentExecaAsync);16test('Prints stdout, buffer: false, fd-specific verbose', testPrintOutputNoBuffer, fdFullOption, false, parentExecaAsync);17test('Prints stdout, buffer: false, sync', testPrintOutputNoBuffer, 'full', false, parentExecaSync);18test('Prints stdout, buffer: false, fd-specific buffer, sync', testPrintOutputNoBuffer, 'full', {stdout: false}, parentExecaSync);19test('Prints stdout, buffer: false, fd-specific verbose, sync', testPrintOutputNoBuffer, fdFullOption, false, parentExecaSync);2021const testPrintOutputNoBufferFalse = async (t, buffer, execaMethod) => {22 const {stderr} = await execaMethod('noop.js', [foobarString], {verbose: fdStderrFullOption, buffer});23 t.is(getOutputLine(stderr), undefined);24};2526test('Does not print stdout, buffer: false, different fd', testPrintOutputNoBufferFalse, false, parentExecaAsync);27test('Does not print stdout, buffer: false, different fd, fd-specific buffer', testPrintOutputNoBufferFalse, {stdout: false}, parentExecaAsync);28test('Does not print stdout, buffer: false, different fd, sync', testPrintOutputNoBufferFalse, false, parentExecaSync);29test('Does not print stdout, buffer: false, different fd, fd-specific buffer, sync', testPrintOutputNoBufferFalse, {stdout: false}, parentExecaSync);3031const testPrintOutputNoBufferTransform = async (t, buffer, isSync) => {32 const {stderr} = await parentExeca('nested-transform.js', 'noop.js', [foobarString], {verbose: 'full', buffer, type: 'generator', isSync});33 t.is(getOutputLine(stderr), `${testTimestamp} [0] ${foobarUppercase}`);34};3536test('Prints stdout, buffer: false, transform', testPrintOutputNoBufferTransform, false, false);37test('Prints stdout, buffer: false, transform, fd-specific buffer', testPrintOutputNoBufferTransform, {stdout: false}, false);38test('Prints stdout, buffer: false, transform, sync', testPrintOutputNoBufferTransform, false, true);39test('Prints stdout, buffer: false, transform, fd-specific buffer, sync', testPrintOutputNoBufferTransform, {stdout: false}, true);
added:test/verbose/output-enable.js+141 added
1import test from 'ava';2import {red} from 'yoctocolors';3import {setFixtureDir} from '../helpers/fixtures-dir.js';4import {foobarString} from '../helpers/input.js';5import {fullStdio} from '../helpers/stdio.js';6import {nestedExecaAsync, parentExeca, parentExecaAsync, parentExecaSync} from '../helpers/nested.js';7import {8 runErrorSubprocessAsync,9 runErrorSubprocessSync,10 getOutputLine,11 getOutputLines,12 testTimestamp,13 fdShortOption,14 fdFullOption,15 fdStdoutNoneOption,16 fdStderrNoneOption,17 fdStderrShortOption,18 fdStderrFullOption,19 fd3NoneOption,20 fd3ShortOption,21 fd3FullOption,22} from '../helpers/verbose.js';2324setFixtureDir();2526const testPrintOutput = async (t, verbose, fdNumber, execaMethod) => {27 const {stderr} = await execaMethod('noop-fd.js', [`${fdNumber}`, foobarString], {verbose});28 t.is(getOutputLine(stderr), `${testTimestamp} [0] ${foobarString}`);29};3031test('Prints stdout, verbose "full"', testPrintOutput, 'full', 1, parentExecaAsync);32test('Prints stderr, verbose "full"', testPrintOutput, 'full', 2, parentExecaAsync);33test('Prints stdout, verbose "full", fd-specific', testPrintOutput, fdFullOption, 1, parentExecaAsync);34test('Prints stderr, verbose "full", fd-specific', testPrintOutput, fdStderrFullOption, 2, parentExecaAsync);35test('Prints stdout, verbose "full", sync', testPrintOutput, 'full', 1, parentExecaSync);36test('Prints stderr, verbose "full", sync', testPrintOutput, 'full', 2, parentExecaSync);37test('Prints stdout, verbose "full", fd-specific, sync', testPrintOutput, fdFullOption, 1, parentExecaSync);38test('Prints stderr, verbose "full", fd-specific, sync', testPrintOutput, fdStderrFullOption, 2, parentExecaSync);3940const testNoPrintOutput = async (t, verbose, fdNumber, execaMethod) => {41 const {stderr} = await execaMethod('noop-fd.js', [`${fdNumber}`, foobarString], {verbose, ...fullStdio});42 t.is(getOutputLine(stderr), undefined);43};4445test('Does not print stdout, verbose default', testNoPrintOutput, undefined, 1, parentExecaAsync);46test('Does not print stdout, verbose "none"', testNoPrintOutput, 'none', 1, parentExecaAsync);47test('Does not print stdout, verbose "short"', testNoPrintOutput, 'short', 1, parentExecaAsync);48test('Does not print stderr, verbose default', testNoPrintOutput, undefined, 2, parentExecaAsync);49test('Does not print stderr, verbose "none"', testNoPrintOutput, 'none', 2, parentExecaAsync);50test('Does not print stderr, verbose "short"', testNoPrintOutput, 'short', 2, parentExecaAsync);51test('Does not print stdio[*], verbose default', testNoPrintOutput, undefined, 3, parentExecaAsync);52test('Does not print stdio[*], verbose "none"', testNoPrintOutput, 'none', 3, parentExecaAsync);53test('Does not print stdio[*], verbose "short"', testNoPrintOutput, 'short', 3, parentExecaAsync);54test('Does not print stdio[*], verbose "full"', testNoPrintOutput, 'full', 3, parentExecaAsync);55test('Does not print stdout, verbose default, fd-specific', testNoPrintOutput, {}, 1, parentExecaAsync);56test('Does not print stdout, verbose "none", fd-specific', testNoPrintOutput, fdStdoutNoneOption, 1, parentExecaAsync);57test('Does not print stdout, verbose "short", fd-specific', testNoPrintOutput, fdShortOption, 1, parentExecaAsync);58test('Does not print stderr, verbose default, fd-specific', testNoPrintOutput, {}, 2, parentExecaAsync);59test('Does not print stderr, verbose "none", fd-specific', testNoPrintOutput, fdStderrNoneOption, 2, parentExecaAsync);60test('Does not print stderr, verbose "short", fd-specific', testNoPrintOutput, fdStderrShortOption, 2, parentExecaAsync);61test('Does not print stdio[*], verbose default, fd-specific', testNoPrintOutput, {}, 3, parentExecaAsync);62test('Does not print stdio[*], verbose "none", fd-specific', testNoPrintOutput, fd3NoneOption, 3, parentExecaAsync);63test('Does not print stdio[*], verbose "short", fd-specific', testNoPrintOutput, fd3ShortOption, 3, parentExecaAsync);64test('Does not print stdio[*], verbose "full", fd-specific', testNoPrintOutput, fd3FullOption, 3, parentExecaAsync);65test('Does not print stdout, verbose default, sync', testNoPrintOutput, undefined, 1, parentExecaSync);66test('Does not print stdout, verbose "none", sync', testNoPrintOutput, 'none', 1, parentExecaSync);67test('Does not print stdout, verbose "short", sync', testNoPrintOutput, 'short', 1, parentExecaSync);68test('Does not print stderr, verbose default, sync', testNoPrintOutput, undefined, 2, parentExecaSync);69test('Does not print stderr, verbose "none", sync', testNoPrintOutput, 'none', 2, parentExecaSync);70test('Does not print stderr, verbose "short", sync', testNoPrintOutput, 'short', 2, parentExecaSync);71test('Does not print stdio[*], verbose default, sync', testNoPrintOutput, undefined, 3, parentExecaSync);72test('Does not print stdio[*], verbose "none", sync', testNoPrintOutput, 'none', 3, parentExecaSync);73test('Does not print stdio[*], verbose "short", sync', testNoPrintOutput, 'short', 3, parentExecaSync);74test('Does not print stdio[*], verbose "full", sync', testNoPrintOutput, 'full', 3, parentExecaSync);75test('Does not print stdout, verbose default, fd-specific, sync', testNoPrintOutput, {}, 1, parentExecaSync);76test('Does not print stdout, verbose "none", fd-specific, sync', testNoPrintOutput, fdStdoutNoneOption, 1, parentExecaSync);77test('Does not print stdout, verbose "short", fd-specific, sync', testNoPrintOutput, fdShortOption, 1, parentExecaSync);78test('Does not print stderr, verbose default, fd-specific, sync', testNoPrintOutput, {}, 2, parentExecaSync);79test('Does not print stderr, verbose "none", fd-specific, sync', testNoPrintOutput, fdStderrNoneOption, 2, parentExecaSync);80test('Does not print stderr, verbose "short", fd-specific, sync', testNoPrintOutput, fdStderrShortOption, 2, parentExecaSync);81test('Does not print stdio[*], verbose default, fd-specific, sync', testNoPrintOutput, {}, 3, parentExecaSync);82test('Does not print stdio[*], verbose "none", fd-specific, sync', testNoPrintOutput, fd3NoneOption, 3, parentExecaSync);83test('Does not print stdio[*], verbose "short", fd-specific, sync', testNoPrintOutput, fd3ShortOption, 3, parentExecaSync);84test('Does not print stdio[*], verbose "full", fd-specific, sync', testNoPrintOutput, fd3FullOption, 3, parentExecaSync);8586const testPrintError = async (t, execaMethod) => {87 const stderr = await execaMethod(t, 'full');88 t.is(getOutputLine(stderr), `${testTimestamp} [0] ${foobarString}`);89};9091test('Prints stdout after errors', testPrintError, runErrorSubprocessAsync);92test('Prints stdout after errors, sync', testPrintError, runErrorSubprocessSync);9394test('Does not quote spaces from stdout', async t => {95 const {stderr} = await parentExecaAsync('noop.js', ['foo bar'], {verbose: 'full'});96 t.is(getOutputLine(stderr), `${testTimestamp} [0] foo bar`);97});9899test('Does not quote special punctuation from stdout', async t => {100 const {stderr} = await parentExecaAsync('noop.js', ['%'], {verbose: 'full'});101 t.is(getOutputLine(stderr), `${testTimestamp} [0] %`);102});103104test('Does not escape internal characters from stdout', async t => {105 const {stderr} = await parentExecaAsync('noop.js', ['ã'], {verbose: 'full'});106 t.is(getOutputLine(stderr), `${testTimestamp} [0] ã`);107});108109test('Strips color sequences from stdout', async t => {110 const {stderr} = await parentExecaAsync('noop.js', [red(foobarString)], {verbose: 'full'}, {env: {FORCE_COLOR: '1'}});111 t.is(getOutputLine(stderr), `${testTimestamp} [0] ${foobarString}`);112});113114test('Escapes control characters from stdout', async t => {115 const {stderr} = await parentExecaAsync('noop.js', ['\u0001'], {verbose: 'full'});116 t.is(getOutputLine(stderr), `${testTimestamp} [0] \\u0001`);117});118119const testStdioSame = async (t, fdNumber) => {120 const {stdio} = await nestedExecaAsync('noop-fd.js', [`${fdNumber}`, foobarString], {verbose: true});121 t.is(stdio[fdNumber], foobarString);122};123124test('Does not change subprocess.stdout', testStdioSame, 1);125test('Does not change subprocess.stderr', testStdioSame, 2);126127const testSingleNewline = async (t, execaMethod) => {128 const {stderr} = await execaMethod('noop-fd.js', ['1', '\n'], {verbose: 'full'});129 t.deepEqual(getOutputLines(stderr), [`${testTimestamp} [0] `]);130};131132test('Prints stdout, single newline', testSingleNewline, parentExecaAsync);133test('Prints stdout, single newline, sync', testSingleNewline, parentExecaSync);134135const testUtf16 = async (t, isSync) => {136 const {stderr} = await parentExeca('nested-input.js', 'stdin.js', [`${isSync}`], {verbose: 'full', encoding: 'utf16le'});137 t.is(getOutputLine(stderr), `${testTimestamp} [0] ${foobarString}`);138};139140test('Can use encoding UTF16, verbose "full"', testUtf16, false);141test('Can use encoding UTF16, verbose "full", sync', testUtf16, true);
added:test/verbose/output-mixed.js+57 added
1import {inspect} from 'node:util';2import test from 'ava';3import {setFixtureDir} from '../helpers/fixtures-dir.js';4import {foobarString, foobarObject} from '../helpers/input.js';5import {simpleFull, noNewlinesChunks} from '../helpers/lines.js';6import {parentExeca, parentExecaAsync, parentExecaSync} from '../helpers/nested.js';7import {getOutputLine, getOutputLines, testTimestamp} from '../helpers/verbose.js';89setFixtureDir();1011const testLines = async (t, lines, stripFinalNewline, execaMethod) => {12 const {stderr} = await execaMethod('noop-fd.js', ['1', simpleFull], {verbose: 'full', lines, stripFinalNewline});13 t.deepEqual(getOutputLines(stderr), noNewlinesChunks.map(line => `${testTimestamp} [0] ${line}`));14};1516test('Prints stdout, "lines: true"', testLines, true, false, parentExecaAsync);17test('Prints stdout, "lines: true", fd-specific', testLines, {stdout: true}, false, parentExecaAsync);18test('Prints stdout, "lines: true", stripFinalNewline', testLines, true, true, parentExecaAsync);19test('Prints stdout, "lines: true", sync', testLines, true, false, parentExecaSync);20test('Prints stdout, "lines: true", fd-specific, sync', testLines, {stdout: true}, false, parentExecaSync);21test('Prints stdout, "lines: true", stripFinalNewline, sync', testLines, true, true, parentExecaSync);2223const testOnlyTransforms = async (t, type, isSync) => {24 const {stderr} = await parentExeca('nested-transform.js', 'noop.js', [foobarString], {verbose: 'full', type, isSync});25 t.is(getOutputLine(stderr), `${testTimestamp} [0] ${foobarString.toUpperCase()}`);26};2728test('Prints stdout with only transforms', testOnlyTransforms, 'generator', false);29test('Prints stdout with only transforms, sync', testOnlyTransforms, 'generator', true);30test('Prints stdout with only duplexes', testOnlyTransforms, 'duplex', false);3132const testObjectMode = async (t, isSync) => {33 const {stderr} = await parentExeca('nested-transform.js', 'noop.js', {verbose: 'full', transformName: 'object', isSync});34 t.is(getOutputLine(stderr), `${testTimestamp} [0] ${inspect(foobarObject)}`);35};3637test('Prints stdout with object transforms', testObjectMode, false);38test('Prints stdout with object transforms, sync', testObjectMode, true);3940const testBigArray = async (t, isSync) => {41 const {stderr} = await parentExeca('nested-transform.js', 'noop.js', {verbose: 'full', transformName: 'bigArray', isSync});42 const lines = getOutputLines(stderr);43 t.is(lines[0], `${testTimestamp} [0] [`);44 t.true(lines[1].startsWith(`${testTimestamp} [0] 0, 1,`));45 t.is(lines.at(-1), `${testTimestamp} [0] ]`);46};4748test('Prints stdout with big object transforms', testBigArray, false);49test('Prints stdout with big object transforms, sync', testBigArray, true);5051const testObjectModeString = async (t, isSync) => {52 const {stderr} = await parentExeca('nested-transform.js', 'noop.js', {verbose: 'full', transformName: 'stringObject', isSync});53 t.deepEqual(getOutputLines(stderr), noNewlinesChunks.map(line => `${testTimestamp} [0] ${line}`));54};5556test('Prints stdout with string transforms in objectMode', testObjectModeString, false);57test('Prints stdout with string transforms in objectMode, sync', testObjectModeString, true);
added:test/verbose/output-noop.js+57 added
1import {rm, readFile} from 'node:fs/promises';2import test from 'ava';3import tempfile from 'tempfile';4import {setFixtureDir} from '../helpers/fixtures-dir.js';5import {foobarString} from '../helpers/input.js';6import {parentExeca, parentExecaAsync, parentExecaSync} from '../helpers/nested.js';7import {getOutputLine, testTimestamp} from '../helpers/verbose.js';89setFixtureDir();1011const testNoOutputOptions = async (t, fixtureName, options = {}) => {12 const {stderr} = await parentExeca(fixtureName, 'noop.js', [foobarString], {verbose: 'full', ...options});13 t.is(getOutputLine(stderr), undefined);14};1516test('Does not print stdout, encoding "buffer"', testNoOutputOptions, 'nested.js', {encoding: 'buffer'});17test('Does not print stdout, encoding "hex"', testNoOutputOptions, 'nested.js', {encoding: 'hex'});18test('Does not print stdout, encoding "base64"', testNoOutputOptions, 'nested.js', {encoding: 'base64'});19test('Does not print stdout, stdout "ignore"', testNoOutputOptions, 'nested.js', {stdout: 'ignore'});20test('Does not print stdout, stdout "inherit"', testNoOutputOptions, 'nested.js', {stdout: 'inherit'});21test('Does not print stdout, stdout 1', testNoOutputOptions, 'nested.js', {stdout: 1});22test('Does not print stdout, stdout Writable', testNoOutputOptions, 'nested-writable.js');23test('Does not print stdout, stdout WritableStream', testNoOutputOptions, 'nested-writable-web.js');24test('Does not print stdout, .pipe(stream)', testNoOutputOptions, 'nested-pipe-stream.js');25test('Does not print stdout, .pipe(subprocess)', testNoOutputOptions, 'nested-pipe-subprocess.js');26test('Does not print stdout, encoding "buffer", sync', testNoOutputOptions, 'nested-sync.js', {encoding: 'buffer'});27test('Does not print stdout, encoding "hex", sync', testNoOutputOptions, 'nested-sync.js', {encoding: 'hex'});28test('Does not print stdout, encoding "base64", sync', testNoOutputOptions, 'nested-sync.js', {encoding: 'base64'});29test('Does not print stdout, stdout "ignore", sync', testNoOutputOptions, 'nested-sync.js', {stdout: 'ignore'});30test('Does not print stdout, stdout "inherit", sync', testNoOutputOptions, 'nested-sync.js', {stdout: 'inherit'});31test('Does not print stdout, stdout 1, sync', testNoOutputOptions, 'nested-sync.js', {stdout: 1});3233const testStdoutFile = async (t, fixtureName, getStdout) => {34 const file = tempfile();35 const {stderr} = await parentExeca(fixtureName, 'noop.js', [foobarString], {verbose: 'full', stdout: getStdout(file)});36 t.is(getOutputLine(stderr), undefined);37 const contents = await readFile(file, 'utf8');38 t.is(contents.trim(), foobarString);39 await rm(file);40};4142test('Does not print stdout, stdout { file }', testStdoutFile, 'nested.js', file => ({file}));43test('Does not print stdout, stdout fileUrl', testStdoutFile, 'nested-file-url.js', file => file);44test('Does not print stdout, stdout { file }, sync', testStdoutFile, 'nested-sync.js', file => ({file}));4546const testPrintOutputOptions = async (t, options, execaMethod) => {47 const {stderr} = await execaMethod('noop.js', [foobarString], {verbose: 'full', ...options});48 t.is(getOutputLine(stderr), `${testTimestamp} [0] ${foobarString}`);49};5051test('Prints stdout, stdout "pipe"', testPrintOutputOptions, {stdout: 'pipe'}, parentExecaAsync);52test('Prints stdout, stdout "overlapped"', testPrintOutputOptions, {stdout: 'overlapped'}, parentExecaAsync);53test('Prints stdout, stdout null', testPrintOutputOptions, {stdout: null}, parentExecaAsync);54test('Prints stdout, stdout ["pipe"]', testPrintOutputOptions, {stdout: ['pipe']}, parentExecaAsync);55test('Prints stdout, stdout "pipe", sync', testPrintOutputOptions, {stdout: 'pipe'}, parentExecaSync);56test('Prints stdout, stdout null, sync', testPrintOutputOptions, {stdout: null}, parentExecaSync);57test('Prints stdout, stdout ["pipe"], sync', testPrintOutputOptions, {stdout: ['pipe']}, parentExecaSync);
added:test/verbose/output-pipe.js+45 added
1import test from 'ava';2import {execa} from '../../index.js';3import {setFixtureDir} from '../helpers/fixtures-dir.js';4import {foobarString} from '../helpers/input.js';5import {parentExeca} from '../helpers/nested.js';6import {getOutputLine, getOutputLines, testTimestamp, getVerboseOption} from '../helpers/verbose.js';78setFixtureDir();910const testPipeOutput = async (t, fixtureName, sourceVerbose, destinationVerbose) => {11 const {stderr} = await execa(`nested-pipe-${fixtureName}.js`, [12 JSON.stringify(getVerboseOption(sourceVerbose, 'full')),13 'noop.js',14 foobarString,15 JSON.stringify(getVerboseOption(destinationVerbose, 'full')),16 'stdin.js',17 ]);1819 const lines = getOutputLines(stderr);20 const id = sourceVerbose && destinationVerbose ? 1 : 0;21 t.deepEqual(lines, destinationVerbose22 ? [`${testTimestamp} [${id}] ${foobarString}`]23 : []);24};2526test('Prints stdout if both verbose with .pipe("file")', testPipeOutput, 'file', true, true);27test('Prints stdout if both verbose with .pipe`command`', testPipeOutput, 'script', true, true);28test('Prints stdout if both verbose with .pipe(subprocess)', testPipeOutput, 'subprocesses', true, true);29test('Prints stdout if only second verbose with .pipe("file")', testPipeOutput, 'file', false, true);30test('Prints stdout if only second verbose with .pipe`command`', testPipeOutput, 'script', false, true);31test('Prints stdout if only second verbose with .pipe(subprocess)', testPipeOutput, 'subprocesses', false, true);32test('Does not print stdout if only first verbose with .pipe("file")', testPipeOutput, 'file', true, false);33test('Does not print stdout if only first verbose with .pipe`command`', testPipeOutput, 'script', true, false);34test('Does not print stdout if only first verbose with .pipe(subprocess)', testPipeOutput, 'subprocesses', true, false);35test('Does not print stdout if neither verbose with .pipe("file")', testPipeOutput, 'file', false, false);36test('Does not print stdout if neither verbose with .pipe`command`', testPipeOutput, 'script', false, false);37test('Does not print stdout if neither verbose with .pipe(subprocess)', testPipeOutput, 'subprocesses', false, false);3839const testPrintOutputFixture = async (t, fixtureName, ...args) => {40 const {stderr} = await parentExeca(fixtureName, 'noop.js', [foobarString, ...args], {verbose: 'full'});41 t.is(getOutputLine(stderr), `${testTimestamp} [0] ${foobarString}`);42};4344test('Prints stdout, .pipe(stream) + .unpipe()', testPrintOutputFixture, 'nested-pipe-stream.js', 'true');45test('Prints stdout, .pipe(subprocess) + .unpipe()', testPrintOutputFixture, 'nested-pipe-subprocess.js', 'true');
added:test/verbose/output-progressive.js+58 added
1import {on} from 'node:events';2import test from 'ava';3import {setFixtureDir} from '../helpers/fixtures-dir.js';4import {foobarString} from '../helpers/input.js';5import {parentExeca, parentExecaAsync, parentExecaSync} from '../helpers/nested.js';6import {getOutputLine, getOutputLines, testTimestamp} from '../helpers/verbose.js';78setFixtureDir();910test('Prints stdout one line at a time', async t => {11 const subprocess = parentExecaAsync('noop-progressive.js', [foobarString], {verbose: 'full'});1213 for await (const chunk of on(subprocess.stderr, 'data')) {14 const outputLine = getOutputLine(chunk.toString().trim());15 if (outputLine !== undefined) {16 t.is(outputLine, `${testTimestamp} [0] ${foobarString}`);17 break;18 }19 }2021 await subprocess;22});2324test.serial('Prints stdout progressively, interleaved', async t => {25 const subprocess = parentExeca('nested-double.js', 'noop-repeat.js', ['1', `${foobarString}\n`], {verbose: 'full'});2627 let firstSubprocessPrinted = false;28 let secondSubprocessPrinted = false;29 for await (const chunk of on(subprocess.stderr, 'data')) {30 const outputLine = getOutputLine(chunk.toString().trim());31 if (outputLine === undefined) {32 continue;33 }3435 if (outputLine.includes(foobarString)) {36 t.is(outputLine, `${testTimestamp} [0] ${foobarString}`);37 firstSubprocessPrinted ||= true;38 } else {39 t.is(outputLine, `${testTimestamp} [1] ${foobarString.toUpperCase()}`);40 secondSubprocessPrinted ||= true;41 }4243 if (firstSubprocessPrinted && secondSubprocessPrinted) {44 break;45 }46 }4748 subprocess.kill();49 await t.throwsAsync(subprocess);50});5152const testInterleaved = async (t, expectedLines, execaMethod) => {53 const {stderr} = await execaMethod('noop-132.js', {verbose: 'full'});54 t.deepEqual(getOutputLines(stderr), expectedLines.map(line => `${testTimestamp} [0] ${line}`));55};5657test('Prints stdout + stderr interleaved', testInterleaved, [1, 2, 3], parentExecaAsync);58test('Prints stdout + stderr not interleaved, sync', testInterleaved, [1, 3, 2], parentExecaSync);
deleted:test/verbose/output.js-363 removed
1import {on} from 'node:events';2import {rm, readFile} from 'node:fs/promises';3import {inspect} from 'node:util';4import test from 'ava';5import tempfile from 'tempfile';6import {red} from 'yoctocolors';7import {execa} from '../../index.js';8import {setFixtureDir} from '../helpers/fixtures-dir.js';9import {foobarString, foobarObject, foobarUppercase} from '../helpers/input.js';10import {simpleFull, noNewlinesChunks} from '../helpers/lines.js';11import {fullStdio} from '../helpers/stdio.js';12import {nestedExecaAsync, parentExeca, parentExecaAsync, parentExecaSync} from '../helpers/nested.js';13import {14 runErrorSubprocessAsync,15 runErrorSubprocessSync,16 getOutputLine,17 getOutputLines,18 testTimestamp,19 getVerboseOption,20 fdShortOption,21 fdFullOption,22 fdStdoutNoneOption,23 fdStderrNoneOption,24 fdStderrShortOption,25 fdStderrFullOption,26 fd3NoneOption,27 fd3ShortOption,28 fd3FullOption,29} from '../helpers/verbose.js';3031setFixtureDir();3233const testPrintOutput = async (t, verbose, fdNumber, execaMethod) => {34 const {stderr} = await execaMethod('noop-fd.js', [`${fdNumber}`, foobarString], {verbose});35 t.is(getOutputLine(stderr), `${testTimestamp} [0] ${foobarString}`);36};3738test('Prints stdout, verbose "full"', testPrintOutput, 'full', 1, parentExecaAsync);39test('Prints stderr, verbose "full"', testPrintOutput, 'full', 2, parentExecaAsync);40test('Prints stdout, verbose "full", fd-specific', testPrintOutput, fdFullOption, 1, parentExecaAsync);41test('Prints stderr, verbose "full", fd-specific', testPrintOutput, fdStderrFullOption, 2, parentExecaAsync);42test('Prints stdout, verbose "full", sync', testPrintOutput, 'full', 1, parentExecaSync);43test('Prints stderr, verbose "full", sync', testPrintOutput, 'full', 2, parentExecaSync);44test('Prints stdout, verbose "full", fd-specific, sync', testPrintOutput, fdFullOption, 1, parentExecaSync);45test('Prints stderr, verbose "full", fd-specific, sync', testPrintOutput, fdStderrFullOption, 2, parentExecaSync);4647const testNoPrintOutput = async (t, verbose, fdNumber, execaMethod) => {48 const {stderr} = await execaMethod('noop-fd.js', [`${fdNumber}`, foobarString], {verbose, ...fullStdio});49 t.is(getOutputLine(stderr), undefined);50};5152test('Does not print stdout, verbose default', testNoPrintOutput, undefined, 1, parentExecaAsync);53test('Does not print stdout, verbose "none"', testNoPrintOutput, 'none', 1, parentExecaAsync);54test('Does not print stdout, verbose "short"', testNoPrintOutput, 'short', 1, parentExecaAsync);55test('Does not print stderr, verbose default', testNoPrintOutput, undefined, 2, parentExecaAsync);56test('Does not print stderr, verbose "none"', testNoPrintOutput, 'none', 2, parentExecaAsync);57test('Does not print stderr, verbose "short"', testNoPrintOutput, 'short', 2, parentExecaAsync);58test('Does not print stdio[*], verbose default', testNoPrintOutput, undefined, 3, parentExecaAsync);59test('Does not print stdio[*], verbose "none"', testNoPrintOutput, 'none', 3, parentExecaAsync);60test('Does not print stdio[*], verbose "short"', testNoPrintOutput, 'short', 3, parentExecaAsync);61test('Does not print stdio[*], verbose "full"', testNoPrintOutput, 'full', 3, parentExecaAsync);62test('Does not print stdout, verbose default, fd-specific', testNoPrintOutput, {}, 1, parentExecaAsync);63test('Does not print stdout, verbose "none", fd-specific', testNoPrintOutput, fdStdoutNoneOption, 1, parentExecaAsync);64test('Does not print stdout, verbose "short", fd-specific', testNoPrintOutput, fdShortOption, 1, parentExecaAsync);65test('Does not print stderr, verbose default, fd-specific', testNoPrintOutput, {}, 2, parentExecaAsync);66test('Does not print stderr, verbose "none", fd-specific', testNoPrintOutput, fdStderrNoneOption, 2, parentExecaAsync);67test('Does not print stderr, verbose "short", fd-specific', testNoPrintOutput, fdStderrShortOption, 2, parentExecaAsync);68test('Does not print stdio[*], verbose default, fd-specific', testNoPrintOutput, {}, 3, parentExecaAsync);69test('Does not print stdio[*], verbose "none", fd-specific', testNoPrintOutput, fd3NoneOption, 3, parentExecaAsync);70test('Does not print stdio[*], verbose "short", fd-specific', testNoPrintOutput, fd3ShortOption, 3, parentExecaAsync);71test('Does not print stdio[*], verbose "full", fd-specific', testNoPrintOutput, fd3FullOption, 3, parentExecaAsync);72test('Does not print stdout, verbose default, sync', testNoPrintOutput, undefined, 1, parentExecaSync);73test('Does not print stdout, verbose "none", sync', testNoPrintOutput, 'none', 1, parentExecaSync);74test('Does not print stdout, verbose "short", sync', testNoPrintOutput, 'short', 1, parentExecaSync);75test('Does not print stderr, verbose default, sync', testNoPrintOutput, undefined, 2, parentExecaSync);76test('Does not print stderr, verbose "none", sync', testNoPrintOutput, 'none', 2, parentExecaSync);77test('Does not print stderr, verbose "short", sync', testNoPrintOutput, 'short', 2, parentExecaSync);78test('Does not print stdio[*], verbose default, sync', testNoPrintOutput, undefined, 3, parentExecaSync);79test('Does not print stdio[*], verbose "none", sync', testNoPrintOutput, 'none', 3, parentExecaSync);80test('Does not print stdio[*], verbose "short", sync', testNoPrintOutput, 'short', 3, parentExecaSync);81test('Does not print stdio[*], verbose "full", sync', testNoPrintOutput, 'full', 3, parentExecaSync);82test('Does not print stdout, verbose default, fd-specific, sync', testNoPrintOutput, {}, 1, parentExecaSync);83test('Does not print stdout, verbose "none", fd-specific, sync', testNoPrintOutput, fdStdoutNoneOption, 1, parentExecaSync);84test('Does not print stdout, verbose "short", fd-specific, sync', testNoPrintOutput, fdShortOption, 1, parentExecaSync);85test('Does not print stderr, verbose default, fd-specific, sync', testNoPrintOutput, {}, 2, parentExecaSync);86test('Does not print stderr, verbose "none", fd-specific, sync', testNoPrintOutput, fdStderrNoneOption, 2, parentExecaSync);87test('Does not print stderr, verbose "short", fd-specific, sync', testNoPrintOutput, fdStderrShortOption, 2, parentExecaSync);88test('Does not print stdio[*], verbose default, fd-specific, sync', testNoPrintOutput, {}, 3, parentExecaSync);89test('Does not print stdio[*], verbose "none", fd-specific, sync', testNoPrintOutput, fd3NoneOption, 3, parentExecaSync);90test('Does not print stdio[*], verbose "short", fd-specific, sync', testNoPrintOutput, fd3ShortOption, 3, parentExecaSync);91test('Does not print stdio[*], verbose "full", fd-specific, sync', testNoPrintOutput, fd3FullOption, 3, parentExecaSync);9293const testPrintError = async (t, execaMethod) => {94 const stderr = await execaMethod(t, 'full');95 t.is(getOutputLine(stderr), `${testTimestamp} [0] ${foobarString}`);96};9798test('Prints stdout after errors', testPrintError, runErrorSubprocessAsync);99test('Prints stdout after errors, sync', testPrintError, runErrorSubprocessSync);100101const testPipeOutput = async (t, fixtureName, sourceVerbose, destinationVerbose) => {102 const {stderr} = await execa(`nested-pipe-${fixtureName}.js`, [103 JSON.stringify(getVerboseOption(sourceVerbose, 'full')),104 'noop.js',105 foobarString,106 JSON.stringify(getVerboseOption(destinationVerbose, 'full')),107 'stdin.js',108 ]);109110 const lines = getOutputLines(stderr);111 const id = sourceVerbose && destinationVerbose ? 1 : 0;112 t.deepEqual(lines, destinationVerbose113 ? [`${testTimestamp} [${id}] ${foobarString}`]114 : []);115};116117test('Prints stdout if both verbose with .pipe("file")', testPipeOutput, 'file', true, true);118test('Prints stdout if both verbose with .pipe`command`', testPipeOutput, 'script', true, true);119test('Prints stdout if both verbose with .pipe(subprocess)', testPipeOutput, 'subprocesses', true, true);120test('Prints stdout if only second verbose with .pipe("file")', testPipeOutput, 'file', false, true);121test('Prints stdout if only second verbose with .pipe`command`', testPipeOutput, 'script', false, true);122test('Prints stdout if only second verbose with .pipe(subprocess)', testPipeOutput, 'subprocesses', false, true);123test('Does not print stdout if only first verbose with .pipe("file")', testPipeOutput, 'file', true, false);124test('Does not print stdout if only first verbose with .pipe`command`', testPipeOutput, 'script', true, false);125test('Does not print stdout if only first verbose with .pipe(subprocess)', testPipeOutput, 'subprocesses', true, false);126test('Does not print stdout if neither verbose with .pipe("file")', testPipeOutput, 'file', false, false);127test('Does not print stdout if neither verbose with .pipe`command`', testPipeOutput, 'script', false, false);128test('Does not print stdout if neither verbose with .pipe(subprocess)', testPipeOutput, 'subprocesses', false, false);129130test('Does not quote spaces from stdout', async t => {131 const {stderr} = await parentExecaAsync('noop.js', ['foo bar'], {verbose: 'full'});132 t.is(getOutputLine(stderr), `${testTimestamp} [0] foo bar`);133});134135test('Does not quote special punctuation from stdout', async t => {136 const {stderr} = await parentExecaAsync('noop.js', ['%'], {verbose: 'full'});137 t.is(getOutputLine(stderr), `${testTimestamp} [0] %`);138});139140test('Does not escape internal characters from stdout', async t => {141 const {stderr} = await parentExecaAsync('noop.js', ['ã'], {verbose: 'full'});142 t.is(getOutputLine(stderr), `${testTimestamp} [0] ã`);143});144145test('Strips color sequences from stdout', async t => {146 const {stderr} = await parentExecaAsync('noop.js', [red(foobarString)], {verbose: 'full'}, {env: {FORCE_COLOR: '1'}});147 t.is(getOutputLine(stderr), `${testTimestamp} [0] ${foobarString}`);148});149150test('Escapes control characters from stdout', async t => {151 const {stderr} = await parentExecaAsync('noop.js', ['\u0001'], {verbose: 'full'});152 t.is(getOutputLine(stderr), `${testTimestamp} [0] \\u0001`);153});154155const testStdioSame = async (t, fdNumber) => {156 const {stdio} = await nestedExecaAsync('noop-fd.js', [`${fdNumber}`, foobarString], {verbose: true});157 t.is(stdio[fdNumber], foobarString);158};159160test('Does not change subprocess.stdout', testStdioSame, 1);161test('Does not change subprocess.stderr', testStdioSame, 2);162163const testLines = async (t, lines, stripFinalNewline, execaMethod) => {164 const {stderr} = await execaMethod('noop-fd.js', ['1', simpleFull], {verbose: 'full', lines, stripFinalNewline});165 t.deepEqual(getOutputLines(stderr), noNewlinesChunks.map(line => `${testTimestamp} [0] ${line}`));166};167168test('Prints stdout, "lines: true"', testLines, true, false, parentExecaAsync);169test('Prints stdout, "lines: true", fd-specific', testLines, {stdout: true}, false, parentExecaAsync);170test('Prints stdout, "lines: true", stripFinalNewline', testLines, true, true, parentExecaAsync);171test('Prints stdout, "lines: true", sync', testLines, true, false, parentExecaSync);172test('Prints stdout, "lines: true", fd-specific, sync', testLines, {stdout: true}, false, parentExecaSync);173test('Prints stdout, "lines: true", stripFinalNewline, sync', testLines, true, true, parentExecaSync);174175const testOnlyTransforms = async (t, type, isSync) => {176 const {stderr} = await parentExeca('nested-transform.js', 'noop.js', [foobarString], {verbose: 'full', type, isSync});177 t.is(getOutputLine(stderr), `${testTimestamp} [0] ${foobarString.toUpperCase()}`);178};179180test('Prints stdout with only transforms', testOnlyTransforms, 'generator', false);181test('Prints stdout with only transforms, sync', testOnlyTransforms, 'generator', true);182test('Prints stdout with only duplexes', testOnlyTransforms, 'duplex', false);183184const testObjectMode = async (t, isSync) => {185 const {stderr} = await parentExeca('nested-transform.js', 'noop.js', {verbose: 'full', transformName: 'object', isSync});186 t.is(getOutputLine(stderr), `${testTimestamp} [0] ${inspect(foobarObject)}`);187};188189test('Prints stdout with object transforms', testObjectMode, false);190test('Prints stdout with object transforms, sync', testObjectMode, true);191192const testBigArray = async (t, isSync) => {193 const {stderr} = await parentExeca('nested-transform.js', 'noop.js', {verbose: 'full', transformName: 'bigArray', isSync});194 const lines = getOutputLines(stderr);195 t.is(lines[0], `${testTimestamp} [0] [`);196 t.true(lines[1].startsWith(`${testTimestamp} [0] 0, 1,`));197 t.is(lines.at(-1), `${testTimestamp} [0] ]`);198};199200test('Prints stdout with big object transforms', testBigArray, false);201test('Prints stdout with big object transforms, sync', testBigArray, true);202203const testObjectModeString = async (t, isSync) => {204 const {stderr} = await parentExeca('nested-transform.js', 'noop.js', {verbose: 'full', transformName: 'stringObject', isSync});205 t.deepEqual(getOutputLines(stderr), noNewlinesChunks.map(line => `${testTimestamp} [0] ${line}`));206};207208test('Prints stdout with string transforms in objectMode', testObjectModeString, false);209test('Prints stdout with string transforms in objectMode, sync', testObjectModeString, true);210211test('Prints stdout one line at a time', async t => {212 const subprocess = parentExecaAsync('noop-progressive.js', [foobarString], {verbose: 'full'});213214 for await (const chunk of on(subprocess.stderr, 'data')) {215 const outputLine = getOutputLine(chunk.toString().trim());216 if (outputLine !== undefined) {217 t.is(outputLine, `${testTimestamp} [0] ${foobarString}`);218 break;219 }220 }221222 await subprocess;223});224225test.serial('Prints stdout progressively, interleaved', async t => {226 const subprocess = parentExeca('nested-double.js', 'noop-repeat.js', ['1', `${foobarString}\n`], {verbose: 'full'});227228 let firstSubprocessPrinted = false;229 let secondSubprocessPrinted = false;230 for await (const chunk of on(subprocess.stderr, 'data')) {231 const outputLine = getOutputLine(chunk.toString().trim());232 if (outputLine === undefined) {233 continue;234 }235236 if (outputLine.includes(foobarString)) {237 t.is(outputLine, `${testTimestamp} [0] ${foobarString}`);238 firstSubprocessPrinted ||= true;239 } else {240 t.is(outputLine, `${testTimestamp} [1] ${foobarString.toUpperCase()}`);241 secondSubprocessPrinted ||= true;242 }243244 if (firstSubprocessPrinted && secondSubprocessPrinted) {245 break;246 }247 }248249 subprocess.kill();250 await t.throwsAsync(subprocess);251});252253const testSingleNewline = async (t, execaMethod) => {254 const {stderr} = await execaMethod('noop-fd.js', ['1', '\n'], {verbose: 'full'});255 t.deepEqual(getOutputLines(stderr), [`${testTimestamp} [0] `]);256};257258test('Prints stdout, single newline', testSingleNewline, parentExecaAsync);259test('Prints stdout, single newline, sync', testSingleNewline, parentExecaSync);260261const testUtf16 = async (t, isSync) => {262 const {stderr} = await parentExeca('nested-input.js', 'stdin.js', [`${isSync}`], {verbose: 'full', encoding: 'utf16le'});263 t.is(getOutputLine(stderr), `${testTimestamp} [0] ${foobarString}`);264};265266test('Can use encoding UTF16, verbose "full"', testUtf16, false);267test('Can use encoding UTF16, verbose "full", sync', testUtf16, true);268269const testNoOutputOptions = async (t, fixtureName, options = {}) => {270 const {stderr} = await parentExeca(fixtureName, 'noop.js', [foobarString], {verbose: 'full', ...options});271 t.is(getOutputLine(stderr), undefined);272};273274test('Does not print stdout, encoding "buffer"', testNoOutputOptions, 'nested.js', {encoding: 'buffer'});275test('Does not print stdout, encoding "hex"', testNoOutputOptions, 'nested.js', {encoding: 'hex'});276test('Does not print stdout, encoding "base64"', testNoOutputOptions, 'nested.js', {encoding: 'base64'});277test('Does not print stdout, stdout "ignore"', testNoOutputOptions, 'nested.js', {stdout: 'ignore'});278test('Does not print stdout, stdout "inherit"', testNoOutputOptions, 'nested.js', {stdout: 'inherit'});279test('Does not print stdout, stdout 1', testNoOutputOptions, 'nested.js', {stdout: 1});280test('Does not print stdout, stdout Writable', testNoOutputOptions, 'nested-writable.js');281test('Does not print stdout, stdout WritableStream', testNoOutputOptions, 'nested-writable-web.js');282test('Does not print stdout, .pipe(stream)', testNoOutputOptions, 'nested-pipe-stream.js');283test('Does not print stdout, .pipe(subprocess)', testNoOutputOptions, 'nested-pipe-subprocess.js');284test('Does not print stdout, encoding "buffer", sync', testNoOutputOptions, 'nested-sync.js', {encoding: 'buffer'});285test('Does not print stdout, encoding "hex", sync', testNoOutputOptions, 'nested-sync.js', {encoding: 'hex'});286test('Does not print stdout, encoding "base64", sync', testNoOutputOptions, 'nested-sync.js', {encoding: 'base64'});287test('Does not print stdout, stdout "ignore", sync', testNoOutputOptions, 'nested-sync.js', {stdout: 'ignore'});288test('Does not print stdout, stdout "inherit", sync', testNoOutputOptions, 'nested-sync.js', {stdout: 'inherit'});289test('Does not print stdout, stdout 1, sync', testNoOutputOptions, 'nested-sync.js', {stdout: 1});290291const testStdoutFile = async (t, fixtureName, getStdout) => {292 const file = tempfile();293 const {stderr} = await parentExeca(fixtureName, 'noop.js', [foobarString], {verbose: 'full', stdout: getStdout(file)});294 t.is(getOutputLine(stderr), undefined);295 const contents = await readFile(file, 'utf8');296 t.is(contents.trim(), foobarString);297 await rm(file);298};299300test('Does not print stdout, stdout { file }', testStdoutFile, 'nested.js', file => ({file}));301test('Does not print stdout, stdout fileUrl', testStdoutFile, 'nested-file-url.js', file => file);302test('Does not print stdout, stdout { file }, sync', testStdoutFile, 'nested-sync.js', file => ({file}));303304const testPrintOutputOptions = async (t, options, execaMethod) => {305 const {stderr} = await execaMethod('noop.js', [foobarString], {verbose: 'full', ...options});306 t.is(getOutputLine(stderr), `${testTimestamp} [0] ${foobarString}`);307};308309test('Prints stdout, stdout "pipe"', testPrintOutputOptions, {stdout: 'pipe'}, parentExecaAsync);310test('Prints stdout, stdout "overlapped"', testPrintOutputOptions, {stdout: 'overlapped'}, parentExecaAsync);311test('Prints stdout, stdout null', testPrintOutputOptions, {stdout: null}, parentExecaAsync);312test('Prints stdout, stdout ["pipe"]', testPrintOutputOptions, {stdout: ['pipe']}, parentExecaAsync);313test('Prints stdout, stdout "pipe", sync', testPrintOutputOptions, {stdout: 'pipe'}, parentExecaSync);314test('Prints stdout, stdout null, sync', testPrintOutputOptions, {stdout: null}, parentExecaSync);315test('Prints stdout, stdout ["pipe"], sync', testPrintOutputOptions, {stdout: ['pipe']}, parentExecaSync);316317const testPrintOutputNoBuffer = async (t, verbose, buffer, execaMethod) => {318 const {stderr} = await execaMethod('noop.js', [foobarString], {verbose, buffer});319 t.is(getOutputLine(stderr), `${testTimestamp} [0] ${foobarString}`);320};321322test('Prints stdout, buffer: false', testPrintOutputNoBuffer, 'full', false, parentExecaAsync);323test('Prints stdout, buffer: false, fd-specific buffer', testPrintOutputNoBuffer, 'full', {stdout: false}, parentExecaAsync);324test('Prints stdout, buffer: false, fd-specific verbose', testPrintOutputNoBuffer, fdFullOption, false, parentExecaAsync);325test('Prints stdout, buffer: false, sync', testPrintOutputNoBuffer, 'full', false, parentExecaSync);326test('Prints stdout, buffer: false, fd-specific buffer, sync', testPrintOutputNoBuffer, 'full', {stdout: false}, parentExecaSync);327test('Prints stdout, buffer: false, fd-specific verbose, sync', testPrintOutputNoBuffer, fdFullOption, false, parentExecaSync);328329const testPrintOutputNoBufferFalse = async (t, buffer, execaMethod) => {330 const {stderr} = await execaMethod('noop.js', [foobarString], {verbose: fdStderrFullOption, buffer});331 t.is(getOutputLine(stderr), undefined);332};333334test('Does not print stdout, buffer: false, different fd', testPrintOutputNoBufferFalse, false, parentExecaAsync);335test('Does not print stdout, buffer: false, different fd, fd-specific buffer', testPrintOutputNoBufferFalse, {stdout: false}, parentExecaAsync);336test('Does not print stdout, buffer: false, different fd, sync', testPrintOutputNoBufferFalse, false, parentExecaSync);337test('Does not print stdout, buffer: false, different fd, fd-specific buffer, sync', testPrintOutputNoBufferFalse, {stdout: false}, parentExecaSync);338339const testPrintOutputNoBufferTransform = async (t, buffer, isSync) => {340 const {stderr} = await parentExeca('nested-transform.js', 'noop.js', [foobarString], {verbose: 'full', buffer, type: 'generator', isSync});341 t.is(getOutputLine(stderr), `${testTimestamp} [0] ${foobarUppercase}`);342};343344test('Prints stdout, buffer: false, transform', testPrintOutputNoBufferTransform, false, false);345test('Prints stdout, buffer: false, transform, fd-specific buffer', testPrintOutputNoBufferTransform, {stdout: false}, false);346test('Prints stdout, buffer: false, transform, sync', testPrintOutputNoBufferTransform, false, true);347test('Prints stdout, buffer: false, transform, fd-specific buffer, sync', testPrintOutputNoBufferTransform, {stdout: false}, true);348349const testPrintOutputFixture = async (t, fixtureName, ...args) => {350 const {stderr} = await parentExeca(fixtureName, 'noop.js', [foobarString, ...args], {verbose: 'full'});351 t.is(getOutputLine(stderr), `${testTimestamp} [0] ${foobarString}`);352};353354test('Prints stdout, .pipe(stream) + .unpipe()', testPrintOutputFixture, 'nested-pipe-stream.js', 'true');355test('Prints stdout, .pipe(subprocess) + .unpipe()', testPrintOutputFixture, 'nested-pipe-subprocess.js', 'true');356357const testInterleaved = async (t, expectedLines, execaMethod) => {358 const {stderr} = await execaMethod('noop-132.js', {verbose: 'full'});359 t.deepEqual(getOutputLines(stderr), expectedLines.map(line => `${testTimestamp} [0] ${line}`));360};361362test('Prints stdout + stderr interleaved', testInterleaved, [1, 2, 3], parentExecaAsync);363test('Prints stdout + stderr not interleaved, sync', testInterleaved, [1, 3, 2], parentExecaSync);
modified:test/async.js+1 added-11 removed
1import process from 'node:process';2import test from 'ava';3import {execa, execaSync} from '../index.js';3import {execa} from '../index.js';4import {setFixtureDir} from './helpers/fixtures-dir.js';56setFixtureDir();7
10 unmodified lines
18 t.is(stdout, 'Hello World');19 });20}2122test('skip throwing when using reject option', async t => {23 const {exitCode} = await execa('fail.js', {reject: false});24 t.is(exitCode, 2);25});2627test('skip throwing when using reject option in sync mode', t => {28 const {exitCode} = execaSync('fail.js', {reject: false});29 t.is(exitCode, 2);30});3122test('execa() returns a promise with pid', async t => {23 const subprocess = execa('noop.js', ['foo']);24 t.is(typeof subprocess.pid, 'number');25 await subprocess;
1 unmodified line
modified:package.json+1 added-1 removed
86 unmodified lines
87 },88 "ava": {89 "workerThreads": false,90 "concurrency": 1,91 "timeout": "60s"91 "timeout": "120s"92 },93 "xo": {94 "rules": {95 "unicorn/no-empty-file": "off",
4 unmodified lines