Skip to content
Myr

Refactor tests (#934)

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

authored by ehmicky · committed by GitHub · parent 8074d85 · Browse files · 26 files+262 added−263 removed
This commit

State

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

Diff stats

26 files+262 added−263 removed

  • tests:+193 added−198 removed
  • other:+69 added−65 removed

26 files+262 added−263 removed

modified:lib/stdio/async.js+12 added-10 removed
modified:lib/stdio/generator.js+28 added-25 removed
1import isPlainObj from 'is-plain-obj';2import {BINARY_ENCODINGS} from '../arguments/encoding.js';3import {generatorsToTransform} from './transform.js';4import {getEncodingTransformGenerator} from './encoding-transform.js';5import {getSplitLinesGenerator, getAppendNewlineGenerator} from './split.js';6import {pipeStreams} from './pipeline.js';6import {isGeneratorOptions, isAsyncGenerator} from './type.js';7import {isAsyncGenerator} from './type.js';8import {getValidateTransformReturn} from './validate.js';910export const getObjectMode = (stdioItems, direction, options) => {10 const generators = getGenerators(stdioItems, direction, options);11 if (generators.length === 0) {11 const transforms = getTransforms(stdioItems, direction, options);12 if (transforms.length === 0) {13 return false;14 }1515 const {value: {readableObjectMode, writableObjectMode}} = generators.at(-1);16 const {value: {readableObjectMode, writableObjectMode}} = transforms.at(-1);17 return direction === 'input' ? writableObjectMode : readableObjectMode;18};1919export const normalizeGenerators = (stdioItems, direction, options) => [20export const normalizeTransforms = (stdioItems, direction, options) => [21 ...stdioItems.filter(({type}) => type !== 'generator'),21 ...getGenerators(stdioItems, direction, options),22 ...getTransforms(stdioItems, direction, options),23];2424const getGenerators = (stdioItems, direction, {encoding}) => {25 const generators = stdioItems.filter(({type}) => type === 'generator');26 const newGenerators = Array.from({length: generators.length});25const getTransforms = (stdioItems, direction, {encoding}) => {26 const transforms = stdioItems.filter(({type}) => type === 'generator');27 const newTransforms = Array.from({length: transforms.length});2828 for (const [index, stdioItem] of Object.entries(generators)) {29 newGenerators[index] = normalizeGenerator({stdioItem, index: Number(index), newGenerators, direction, encoding});29 for (const [index, stdioItem] of Object.entries(transforms)) {30 newTransforms[index] = normalizeTransform({stdioItem, index: Number(index), newTransforms, direction, encoding});31 }3232 return sortGenerators(newGenerators, direction);33 return sortTransforms(newTransforms, direction);34};3535const normalizeGenerator = ({stdioItem, stdioItem: {value}, index, newGenerators, direction, encoding}) => {36const normalizeTransform = ({stdioItem, stdioItem: {value}, index, newTransforms, direction, encoding}) => {37 const {38 transform,39 final,40 binary: binaryOption = false,41 preserveNewlines = false,42 objectMode,42 } = isGeneratorOptions(value) ? value : {transform: value};43 } = isPlainObj(value) ? value : {transform: value};44 const binary = binaryOption || BINARY_ENCODINGS.has(encoding);44 const objectModes = direction === 'output'45 ? getOutputObjectModes(objectMode, index, newGenerators)46 : getInputObjectModes(objectMode, index, newGenerators);47 return {...stdioItem, value: {transform, final, binary, preserveNewlines, ...objectModes}};45 const {writableObjectMode, readableObjectMode} = getObjectModes(objectMode, index, newTransforms, direction);46 return {...stdioItem, value: {transform, final, binary, preserveNewlines, writableObjectMode, readableObjectMode}};47};4849/*50`objectMode` determines the return value's type, i.e. the `readableObjectMode`.
3 unmodified lines
54- can only be strings, Buffers and Uint8Arrays.55Therefore its `readableObjectMode` must be `false`.56The same applies to the first output's generator's `writableObjectMode`.57*/58const getObjectModes = (objectMode, index, newTransforms, direction) => direction === 'output'59 ? getOutputObjectModes(objectMode, index, newTransforms)60 : getInputObjectModes(objectMode, index, newTransforms);6159const getOutputObjectModes = (objectMode, index, newGenerators) => {60 const writableObjectMode = index !== 0 && newGenerators[index - 1].value.readableObjectMode;62const getOutputObjectModes = (objectMode, index, newTransforms) => {63 const writableObjectMode = index !== 0 && newTransforms[index - 1].value.readableObjectMode;64 const readableObjectMode = objectMode ?? writableObjectMode;65 return {writableObjectMode, readableObjectMode};66};6765const getInputObjectModes = (objectMode, index, newGenerators) => {68const getInputObjectModes = (objectMode, index, newTransforms) => {69 const writableObjectMode = index === 070 ? objectMode === true68 : newGenerators[index - 1].value.readableObjectMode;69 const readableObjectMode = index !== newGenerators.length - 1 && (objectMode ?? writableObjectMode);71 : newTransforms[index - 1].value.readableObjectMode;72 const readableObjectMode = index !== newTransforms.length - 1 && (objectMode ?? writableObjectMode);73 return {writableObjectMode, readableObjectMode};74};7573const sortGenerators = (newGenerators, direction) => direction === 'input' ? newGenerators.reverse() : newGenerators;76const sortTransforms = (newTransforms, direction) => direction === 'input' ? newTransforms.reverse() : newTransforms;7778/*79Generators can be used to transform/filter standard streams.80
29 unmodified lines
110 return {stream};111};112113// `subprocess.stdin|stdout|stderr|stdio` is directly mutated.111export const pipeGenerator = (subprocess, stream, direction, fdNumber) => {114export const pipeTransform = (subprocess, stream, direction, fdNumber) => {115 if (direction === 'output') {116 pipeStreams(subprocess.stdio[fdNumber], stream);117 } else {118 pipeStreams(stream, subprocess.stdio[fdNumber]);
11 unmodified lines
modified:lib/stdio/handle.js+2 added-2 removed
4 unmodified lines
5import {handleNativeStream} from './native.js';6import {handleInputOptions} from './input.js';7import {handleStreamsLines} from './lines.js';8import {handleStreamsEncoding} from './encoding-final.js';9import {normalizeGenerators, getObjectMode} from './generator.js';9import {normalizeTransforms, getObjectMode} from './generator.js';10import {forwardStdio, willPipeFileDescriptor} from './forward.js';1112// Handle `input`, `inputFile`, `stdin`, `stdout` and `stderr` options, before spawning, in async/sync mode13export const handleInput = (addProperties, options, verboseInfo, isSync) => {
82 unmodified lines
96};9798const normalizeStdioItems = ({stdioItems, fdNumber, optionName, addProperties, options, isSync, direction, stdioState, verboseInfo, outputLines}) => {99 const allStdioItems = addInternalStdioItems({stdioItems, fdNumber, optionName, options, isSync, direction, stdioState, verboseInfo, outputLines});100 const normalizedStdioItems = normalizeGenerators(allStdioItems, direction, options);100 const normalizedStdioItems = normalizeTransforms(allStdioItems, direction, options);101 return normalizedStdioItems.map(stdioItem => addStreamProperties(stdioItem, addProperties, direction));102};103104const addInternalStdioItems = ({stdioItems, fdNumber, optionName, options, isSync, direction, stdioState, verboseInfo, outputLines}) => {
20 unmodified lines
modified:lib/stdio/sync.js+10 added-10 removed
modified:lib/stdio/type.js+6 added-7 removed
1import {isStream as isNodeStream} from 'is-stream';2import isPlainObj from 'is-plain-obj';3import {isUint8Array} from '../utils.js';45// The `stdin`/`stdout`/`stderr` option can be of many types. This detects it.6export const getStdioItemType = (value, optionName) => {
24 unmodified lines
31 if (isIterableObject(value)) {32 return 'iterable';33 }3434 if (isGeneratorOptions(value)) {35 return getGeneratorObjectType(value, optionName);35 if (isTransformOptions(value)) {36 return getTransformObjectType(value, optionName);37 }3839 return 'native';40};4141const getGeneratorObjectType = ({transform, final, binary, objectMode}, optionName) => {42const getTransformObjectType = ({transform, final, binary, objectMode}, optionName) => {43 if (transform !== undefined && !isGenerator(transform)) {44 throw new TypeError(`The \`${optionName}.transform\` option must be a generator.`);45 }46
15 unmodified lines
6263const isGenerator = value => isAsyncGenerator(value) || isSyncGenerator(value);64export const isAsyncGenerator = value => Object.prototype.toString.call(value) === '[object AsyncGeneratorFunction]';65const isSyncGenerator = value => Object.prototype.toString.call(value) === '[object GeneratorFunction]';65export const isGeneratorOptions = value => typeof value === 'object'66 && value !== null66const isTransformOptions = value => isPlainObj(value)67 && (value.transform !== undefined || value.final !== undefined);6869export const isUrl = value => Object.prototype.toString.call(value) === '[object URL]';70export const isRegularUrl = value => isUrl(value) && value.protocol !== 'file:';7172const isFilePathObject = value => typeof value === 'object'73 && value !== null72const isFilePathObject = value => isPlainObj(value)73 && Object.keys(value).length === 174 && isFilePathString(value.file);75export const isFilePathString = file => typeof file === 'string';76
25 unmodified lines
modified:test/convert/loop.js+7 added-7 removed
133 unmodified lines
134135test('.iterable() uses Uint8Arrays with "binary: true"', testObjectMode, simpleChunksUint8Array, 'iterable', null, false, false, true);136test('.iterable() uses strings with "binary: true" and .setEncoding("utf8")', testObjectMode, simpleChunks, 'iterable', 'utf8', false, false, true);137test('.iterable() uses strings with "binary: true" and "encoding: buffer"', testObjectMode, simpleChunks, 'iterable', 'utf8', false, false, true, {encoding: 'buffer'});138test('.iterable() uses strings in objectMode with "binary: true" and object transforms', testObjectMode, foobarObjectChunks, 'iterable', null, true, true, true, {stdout: outputObjectGenerator});138test('.iterable() uses strings in objectMode with "binary: true" and object transforms', testObjectMode, foobarObjectChunks, 'iterable', null, true, true, true, {stdout: outputObjectGenerator()});139test('.iterable() uses strings in objectMode with "binary: false"', testObjectMode, simpleLines, 'iterable', null, false, true, false);140test('.iterable() uses strings in objectMode with "binary: false" and .setEncoding("utf8")', testObjectMode, simpleLines, 'iterable', 'utf8', false, true, false);141test('.iterable() uses strings in objectMode with "binary: false" and "encoding: buffer"', testObjectMode, simpleChunks, 'iterable', 'utf8', false, true, false, {encoding: 'buffer'});142test('.iterable() uses strings in objectMode with "binary: false" and object transforms', testObjectMode, foobarObjectChunks, 'iterable', null, true, true, false, {stdout: outputObjectGenerator});142test('.iterable() uses strings in objectMode with "binary: false" and object transforms', testObjectMode, foobarObjectChunks, 'iterable', null, true, true, false, {stdout: outputObjectGenerator()});143test('.readable() uses Buffers with "binary: true"', testObjectMode, simpleChunksBuffer, 'readable', null, false, false, true);144test('.readable() uses strings with "binary: true" and .setEncoding("utf8")', testObjectMode, simpleChunks, 'readable', 'utf8', false, false, true);145test('.readable() uses strings with "binary: true" and "encoding: buffer"', testObjectMode, simpleChunks, 'readable', 'utf8', false, false, true, {encoding: 'buffer'});146test('.readable() uses strings in objectMode with "binary: true" and object transforms', testObjectMode, foobarObjectChunks, 'readable', null, true, true, true, {stdout: outputObjectGenerator});146test('.readable() uses strings in objectMode with "binary: true" and object transforms', testObjectMode, foobarObjectChunks, 'readable', null, true, true, true, {stdout: outputObjectGenerator()});147test('.readable() uses strings in objectMode with "binary: false"', testObjectMode, simpleLines, 'readable', null, false, true, false);148test('.readable() uses strings in objectMode with "binary: false" and .setEncoding("utf8")', testObjectMode, simpleLines, 'readable', 'utf8', false, true, false);149test('.readable() uses strings in objectMode with "binary: false" and "encoding: buffer"', testObjectMode, simpleChunks, 'readable', 'utf8', false, false, false, {encoding: 'buffer'});150test('.readable() uses strings in objectMode with "binary: false" and object transforms', testObjectMode, foobarObjectChunks, 'readable', null, true, true, false, {stdout: outputObjectGenerator});150test('.readable() uses strings in objectMode with "binary: false" and object transforms', testObjectMode, foobarObjectChunks, 'readable', null, true, true, false, {stdout: outputObjectGenerator()});151test('.duplex() uses Buffers with "binary: true"', testObjectMode, simpleChunksBuffer, 'duplex', null, false, false, true);152test('.duplex() uses strings with "binary: true" and .setEncoding("utf8")', testObjectMode, simpleChunks, 'duplex', 'utf8', false, false, true);153test('.duplex() uses strings with "binary: true" and "encoding: buffer"', testObjectMode, simpleChunks, 'duplex', 'utf8', false, false, true, {encoding: 'buffer'});154test('.duplex() uses strings in objectMode with "binary: true" and object transforms', testObjectMode, foobarObjectChunks, 'duplex', null, true, true, true, {stdout: outputObjectGenerator});154test('.duplex() uses strings in objectMode with "binary: true" and object transforms', testObjectMode, foobarObjectChunks, 'duplex', null, true, true, true, {stdout: outputObjectGenerator()});155test('.duplex() uses strings in objectMode with "binary: false"', testObjectMode, simpleLines, 'duplex', null, false, true, false);156test('.duplex() uses strings in objectMode with "binary: false" and .setEncoding("utf8")', testObjectMode, simpleLines, 'duplex', 'utf8', false, true, false);157test('.duplex() uses strings in objectMode with "binary: false" and "encoding: buffer"', testObjectMode, simpleChunks, 'duplex', 'utf8', false, false, false, {encoding: 'buffer'});158test('.duplex() uses strings in objectMode with "binary: false" and object transforms', testObjectMode, foobarObjectChunks, 'duplex', null, true, true, false, {stdout: outputObjectGenerator});158test('.duplex() uses strings in objectMode with "binary: false" and object transforms', testObjectMode, foobarObjectChunks, 'duplex', null, true, true, false, {stdout: outputObjectGenerator()});159160const testObjectSplit = async (t, methodName) => {161 const subprocess = getSubprocess(methodName, foobarString, {stdout: getOutputGenerator(simpleFull, true)});161 const subprocess = getSubprocess(methodName, foobarString, {stdout: getOutputGenerator(simpleFull)(true)});162 const stream = subprocess[methodName]({binary: false});163 await assertChunks(t, stream, [simpleFull], methodName);164 await subprocess;165};
18 unmodified lines
modified:test/convert/readable.js+4 added-4 removed
23 unmodified lines
24} from '../helpers/convert.js';25import {foobarString, foobarBuffer, foobarObject} from '../helpers/input.js';26import {simpleFull} from '../helpers/lines.js';27import {prematureClose, fullStdio} from '../helpers/stdio.js';28import {outputObjectGenerator, getChunksGenerator} from '../helpers/generator.js';28import {outputObjectGenerator, getOutputsAsyncGenerator} from '../helpers/generator.js';29import {defaultHighWaterMark, defaultObjectHighWaterMark} from '../helpers/stream.js';3031setFixtureDir();32
209 unmodified lines
242 await assertSubprocessOutput(t, subprocess);243});244245test('.readable() works with objectMode', async t => {246 const subprocess = execa('noop.js', {stdout: outputObjectGenerator});246 const subprocess = execa('noop.js', {stdout: outputObjectGenerator()});247 const stream = subprocess.readable();248 t.true(stream.readableObjectMode);249 t.is(stream.readableHighWaterMark, defaultObjectHighWaterMark);250
1 unmodified line
252 await assertSubprocessOutput(t, subprocess, [foobarObject]);253});254255test('.duplex() works with objectMode and reads', async t => {256 const subprocess = getReadWriteSubprocess({stdout: outputObjectGenerator});256 const subprocess = getReadWriteSubprocess({stdout: outputObjectGenerator()});257 const stream = subprocess.duplex();258 t.true(stream.readableObjectMode);259 t.is(stream.readableHighWaterMark, defaultObjectHighWaterMark);260 t.false(stream.writableObjectMode);
63 unmodified lines
324 await assertSubprocessOutput(t, subprocess, simpleFull);325});326327test('.readable() can wait for data', async t => {328 const subprocess = execa('noop.js', {stdout: getChunksGenerator([foobarString, foobarString], false, true)});328 const subprocess = execa('noop.js', {stdout: getOutputsAsyncGenerator([foobarString, foobarString])(false, true)});329 const stream = subprocess.readable();330331 t.is(stream.read(), null);332 await once(stream, 'readable');
122 unmodified lines
modified:test/convert/writable.js+1 added-1 removed
336 unmodified lines
337 await assertSubprocessOutput(t, subprocess, expectedOutput);338});339340const testPropagateError = async (t, methodName) => {341 const subprocess = getReadWriteSubprocess({stdin: throwingGenerator});341 const subprocess = getReadWriteSubprocess({stdin: throwingGenerator()});342 const stream = subprocess[methodName]();343 stream.end('.');344 await t.throwsAsync(finishedStream(stream), {message: GENERATOR_ERROR_REGEXP});345};
44 unmodified lines
modified:test/fixtures/nested-big-array.js+1 added-1 removed
3 unmodified lines
4import {getOutputGenerator} from '../helpers/generator.js';56const bigArray = Array.from({length: 100}, (_, index) => index);7const [options, file, ...args] = process.argv.slice(2);8await execa(file, args, {stdout: getOutputGenerator(bigArray, true), ...JSON.parse(options)});8await execa(file, args, {stdout: getOutputGenerator(bigArray)(true), ...JSON.parse(options)});
modified:test/fixtures/nested-object.js+1 added-1 removed
2 unmodified lines
3import {execa} from '../../index.js';4import {outputObjectGenerator} from '../helpers/generator.js';56const [options, file, ...args] = process.argv.slice(2);7await execa(file, args, {stdout: outputObjectGenerator, ...JSON.parse(options)});7await execa(file, args, {stdout: outputObjectGenerator(), ...JSON.parse(options)});
modified:test/helpers/generator.js+67 added-60 removed
1import {setImmediate, setInterval} from 'node:timers/promises';2import {foobarObject} from './input.js';1import {setImmediate, setInterval, setTimeout, scheduler} from 'node:timers/promises';2import {foobarObject, foobarString} from './input.js';34export const noopAsyncGenerator = (objectMode, binary) => ({5 async * transform(line) {6 yield line;7 },4const getGenerator = transform => (objectMode, binary, preserveNewlines) => ({5 transform,6 objectMode,7 binary,8 preserveNewlines,9});1012export const addNoopGenerator = (transform, addNoopTransform) => addNoopTransform13 ? [transform, noopGenerator(undefined, true)]11export const addNoopGenerator = (transform, addNoopTransform, objectMode, binary) => addNoopTransform12 ? [transform, noopGenerator(objectMode, binary)]13 : [transform];1416export const noopGenerator = (objectMode, binary, preserveNewlines) => ({17 * transform(line) {18 yield line;19 },20 objectMode,21 binary,22 preserveNewlines,15export const noopGenerator = getGenerator(function * (value) {16 yield value;17});1825export const serializeGenerator = (objectMode, binary) => ({26 * transform(object) {27 yield JSON.stringify(object);28 },29 objectMode,30 binary,19export const noopAsyncGenerator = getGenerator(async function * (value) {20 yield value;21});2233export const getOutputsGenerator = (inputs, objectMode) => ({34 * transform() {35 yield * inputs;36 },37 objectMode,23export const serializeGenerator = getGenerator(function * (object) {24 yield JSON.stringify(object);25});2640export const identityGenerator = input => function * () {27export const getOutputGenerator = input => getGenerator(function * () {28 yield input;42};29});3044export const identityAsyncGenerator = input => async function * () {31export const outputObjectGenerator = () => getOutputGenerator(foobarObject)(true);3233export const getOutputAsyncGenerator = input => getGenerator(async function * () {34 yield input;46};35});3648export const getOutputGenerator = (input, objectMode, binary) => ({49 transform: identityGenerator(input),50 objectMode,51 binary,37export const getOutputsGenerator = inputs => getGenerator(function * () {38 yield * inputs;39});4054export const outputObjectGenerator = getOutputGenerator(foobarObject, true);5556export const getChunksGenerator = (chunks, objectMode, binary) => ({57 async * transform() {58 for (const chunk of chunks) {59 yield chunk;60 // eslint-disable-next-line no-await-in-loop61 await setImmediate();62 }41export const getOutputsAsyncGenerator = inputs => getGenerator(async function * () {42 for (const input of inputs) {43 yield input;44 // eslint-disable-next-line no-await-in-loop45 await setImmediate();46 }63 },64 objectMode,65 binary,47});4849const noYieldTransform = function * () {};5070export const noYieldGenerator = objectMode => ({71 transform: noYieldTransform,72 objectMode,51export const noYieldGenerator = getGenerator(noYieldTransform);5253export const prefix = '> ';54export const suffix = ' <';5556export const multipleYieldGenerator = getGenerator(async function * (line = foobarString) {57 yield prefix;58 await scheduler.yield();59 yield line;60 await scheduler.yield();61 yield suffix;62});6364export const convertTransformToFinal = (transform, final) => {65 if (!final) {
3 unmodified lines
69 const generatorOptions = typeof transform === 'function' ? {transform} : transform;70 return ({...generatorOptions, transform: noYieldTransform, final: generatorOptions.transform});71};7284export const infiniteGenerator = async function * () {85 for await (const value of setInterval(100, 'foo')) {73export const infiniteGenerator = getGenerator(async function * () {74 for await (const value of setInterval(100, foobarString)) {75 yield value;76 }88};77});7890export const uppercaseGenerator = (objectMode, binary) => ({91 * transform(line) {92 yield line.toUpperCase();93 },94 objectMode,95 binary,79const textDecoder = new TextDecoder();8081export const uppercaseBufferGenerator = getGenerator(function * (buffer) {82 yield textDecoder.decode(buffer).toUpperCase();83});8485export const uppercaseGenerator = getGenerator(function * (string) {86 yield string.toUpperCase();87});8889// eslint-disable-next-line require-yield99export const throwingGenerator = function * () {90export const throwingGenerator = getGenerator(function * () {91 throw new Error('Generator error');101};92});9394export const GENERATOR_ERROR_REGEXP = /Generator error/;9596export const appendGenerator = getGenerator(function * (string) {97 yield `${string}${casedSuffix}`;98});99100export const casedSuffix = 'k';101102export const resultGenerator = inputs => getGenerator(function * (input) {103 inputs.push(input);104 yield input;105});106107export const timeoutGenerator = timeout => getGenerator(async function * () {108 await setTimeout(timeout);109 yield foobarString;110});
modified:test/helpers/input.js+2 added
11 unmodified lines
12export const foobarBuffer = Buffer.from(foobarString);13const foobarUtf16Buffer = Buffer.from(foobarString, 'utf16le');14export const foobarUtf16Uint8Array = bufferToUint8Array(foobarUtf16Buffer);15export const foobarDataView = new DataView(foobarArrayBuffer);16export const foobarHex = foobarBuffer.toString('hex');17export const foobarUppercase = foobarString.toUpperCase();18export const foobarObject = {foo: 'bar'};19export const foobarObjectString = JSON.stringify(foobarObject);
modified:test/return/duration.js-1 removed
6 unmodified lines
78const assertDurationMs = (t, durationMs) => {9 t.is(typeof durationMs, 'number');10 t.true(Number.isFinite(durationMs));11 t.false(Number.isInteger(durationMs));11 t.not(durationMs, 0);12 t.true(durationMs > 0);13};14
47 unmodified lines
modified:test/return/error.js+2 added-2 removed
96 unmodified lines
97};9899test('error.message does not contain stdout if not available', testPartialIgnoreMessage, 1, 'ignore', 'stderr');100test('error.message does not contain stderr if not available', testPartialIgnoreMessage, 2, 'ignore', 'stdout');101test('error.message does not contain stdout if it is an object', testPartialIgnoreMessage, 1, outputObjectGenerator, 'stderr');102test('error.message does not contain stderr if it is an object', testPartialIgnoreMessage, 2, outputObjectGenerator, 'stdout');101test('error.message does not contain stdout if it is an object', testPartialIgnoreMessage, 1, outputObjectGenerator(), 'stderr');102test('error.message does not contain stderr if it is an object', testPartialIgnoreMessage, 2, outputObjectGenerator(), 'stdout');103104const testFullIgnoreMessage = async (t, options, resultProperty) => {105 const {[resultProperty]: message} = await t.throwsAsync(execa('echo-fail.js', options));106 t.false(message.includes('stderr'));
99 unmodified lines
modified:test/stdio/encoding-final.js+3 added-3 removed
5 unmodified lines
6import getStream, {getStreamAsBuffer} from 'get-stream';7import {execa, execaSync} from '../../index.js';8import {setFixtureDir, FIXTURES_DIR} from '../helpers/fixtures-dir.js';9import {fullStdio} from '../helpers/stdio.js';10import {outputObjectGenerator, getChunksGenerator, addNoopGenerator} from '../helpers/generator.js';10import {outputObjectGenerator, getOutputsGenerator, addNoopGenerator} from '../helpers/generator.js';11import {foobarObject} from '../helpers/input.js';1213const pExec = promisify(exec);14
84 unmodified lines
99const foobarArray = ['fo', 'ob', 'ar', '..'];100101const testMultibyteCharacters = async (t, objectMode, addNoopTransform) => {102 const {stdout} = await execa('noop.js', {103 stdout: addNoopGenerator(getChunksGenerator(foobarArray, objectMode, true), addNoopTransform),103 stdout: addNoopGenerator(getOutputsGenerator(foobarArray)(objectMode, true), addNoopTransform, objectMode),104 encoding: 'base64',105 });106 if (objectMode) {107 t.deepEqual(stdout, foobarArray);
7 unmodified lines
115test('Handle multibyte characters, with objectMode', testMultibyteCharacters, true, false);116test('Handle multibyte characters, with objectMode, noop transform', testMultibyteCharacters, true, true);117118const testObjectMode = async (t, addNoopTransform) => {119 const {stdout} = await execa('noop.js', {stdout: addNoopGenerator(outputObjectGenerator, addNoopTransform), encoding: 'base64'});119 const {stdout} = await execa('noop.js', {stdout: addNoopGenerator(outputObjectGenerator(), addNoopTransform, true), encoding: 'base64'});120 t.deepEqual(stdout, [foobarObject]);121};122123test('Other encodings work with transforms that return objects', testObjectMode, false);
45 unmodified lines
modified:test/stdio/encoding-transform.js+2 added-2 removed
64 unmodified lines
65// eslint-disable-next-line max-params66const testGeneratorNextEncoding = async (t, input, encoding, firstObjectMode, secondObjectMode, expectedType) => {67 const {stdout} = await execa('noop.js', ['other'], {68 stdout: [69 getOutputGenerator(input, firstObjectMode),69 getOutputGenerator(input)(firstObjectMode),70 getTypeofGenerator(secondObjectMode),71 ],72 encoding,73 });
30 unmodified lines
104// eslint-disable-next-line max-params105const testGeneratorReturnType = async (t, input, encoding, reject, objectMode, final) => {106 const fixtureName = reject ? 'noop-fd.js' : 'noop-fail.js';107 const {stdout} = await execa(fixtureName, ['1', foobarString], {108 stdout: convertTransformToFinal(getOutputGenerator(input, objectMode, true), final),108 stdout: convertTransformToFinal(getOutputGenerator(input)(objectMode, true), final),109 encoding,110 reject,111 });112 const typeofChunk = Array.isArray(stdout) ? stdout[0] : stdout;
77 unmodified lines
modified:test/stdio/generator.js+46 added-35 removed
5 unmodified lines
6import tempfile from 'tempfile';7import {execa} from '../../index.js';8import {setFixtureDir} from '../helpers/fixtures-dir.js';9import {getStdio} from '../helpers/stdio.js';10import {foobarString, foobarUint8Array, foobarBuffer, foobarObject, foobarObjectString} from '../helpers/input.js';11import {serializeGenerator, outputObjectGenerator, addNoopGenerator, uppercaseGenerator} from '../helpers/generator.js';10import {11 foobarString,12 foobarUppercase,13 foobarHex,14 foobarUint8Array,15 foobarBuffer,16 foobarObject,17 foobarObjectString,18} from '../helpers/input.js';19import {20 addNoopGenerator,21 serializeGenerator,22 outputObjectGenerator,23 uppercaseGenerator,24 uppercaseBufferGenerator,25 appendGenerator,26 casedSuffix,27} from '../helpers/generator.js';2829setFixtureDir();3031const textEncoder = new TextEncoder();16const textDecoder = new TextDecoder();3218const foobarUppercase = foobarString.toUpperCase();19const foobarHex = foobarBuffer.toString('hex');2021const uppercaseBufferGenerator = {22 * transform(line) {23 yield textDecoder.decode(line).toUpperCase();24 },25 binary: true,26};2733const getInputObjectMode = (objectMode, addNoopTransform) => objectMode34 ? {35 input: [foobarObject],31 generators: addNoopGenerator(serializeGenerator(true), addNoopTransform),36 generators: addNoopGenerator(serializeGenerator(objectMode), addNoopTransform, objectMode),37 output: foobarObjectString,38 }39 : {40 input: foobarUint8Array,36 generators: addNoopGenerator(uppercaseGenerator(), addNoopTransform),41 generators: addNoopGenerator(uppercaseGenerator(objectMode), addNoopTransform, objectMode),42 output: foobarUppercase,43 };4440const getOutputObjectMode = (objectMode, addNoopTransform) => objectMode45const getOutputObjectMode = (objectMode, addNoopTransform, binary) => objectMode46 ? {42 generators: addNoopGenerator(outputObjectGenerator, addNoopTransform),47 generators: addNoopGenerator(outputObjectGenerator(), addNoopTransform, objectMode, binary),48 output: [foobarObject],49 getStreamMethod: getStreamAsArray,50 }51 : {47 generators: addNoopGenerator(uppercaseBufferGenerator, addNoopTransform),52 generators: addNoopGenerator(uppercaseBufferGenerator(objectMode, true), addNoopTransform, objectMode, binary),53 output: foobarUppercase,54 getStreamMethod: getStream,55 };56
103 unmodified lines
160test('Can use generators with error.stdio[*] as output, objectMode, noop transform', testGeneratorOutput, 3, false, false, true, true);161162// eslint-disable-next-line max-params163const testGeneratorOutputPipe = async (t, fdNumber, useShortcutProperty, objectMode, addNoopTransform) => {159 const {generators, output, getStreamMethod} = getOutputObjectMode(objectMode, addNoopTransform);164 const {generators, output, getStreamMethod} = getOutputObjectMode(objectMode, addNoopTransform, true);165 const subprocess = execa('noop-fd.js', [`${fdNumber}`, foobarString], getStdio(fdNumber, generators));166 const stream = useShortcutProperty ? [subprocess.stdout, subprocess.stderr][fdNumber - 1] : subprocess.stdio[fdNumber];167 const [result] = await Promise.all([getStreamMethod(stream), subprocess]);168 t.deepEqual(result, output);
25 unmodified lines
194 return 'pipe';195 }196197 if (objectMode) {193 return outputObjectGenerator;198 return outputObjectGenerator();199 }200196 return encoding === 'utf8' ? uppercaseGenerator() : uppercaseBufferGenerator;201 return encoding === 'utf8' ? uppercaseGenerator() : uppercaseBufferGenerator();202};203204const getStdoutStderrOutput = (output, stdioOption, encoding, objectMode) => {205 if (objectMode && !stdioOption) {
96 unmodified lines
302test('Can use generators with inputFile option', testInputFile, filePath => ({inputFile: filePath, stdin: uppercaseGenerator()}), false);303304const testOutputFile = async (t, reversed) => {305 const filePath = tempfile();301 const stdoutOption = [uppercaseBufferGenerator, {file: filePath}];306 const stdoutOption = [uppercaseBufferGenerator(false, true), {file: filePath}];307 const reversedStdoutOption = reversed ? stdoutOption.reverse() : stdoutOption;308 const {stdout} = await execa('noop-fd.js', ['1'], {stdout: reversedStdoutOption});309 t.is(stdout, foobarUppercase);310 t.is(await readFile(filePath, 'utf8'), foobarUppercase);
5 unmodified lines
316317test('Can use generators to a Writable stream', async t => {318 const passThrough = new PassThrough();319 const [{stdout}, streamOutput] = await Promise.all([315 execa('noop-fd.js', ['1', foobarString], {stdout: [uppercaseBufferGenerator, passThrough]}),320 execa('noop-fd.js', ['1', foobarString], {stdout: [uppercaseBufferGenerator(false, true), passThrough]}),321 getStream(passThrough),322 ]);323 t.is(stdout, foobarUppercase);324 t.is(streamOutput, foobarUppercase);
11 unmodified lines
336 const {stdout} = await execa('nested-inherit.js');337 t.is(stdout, foobarUppercase);338});339335const casedSuffix = 'k';336337const appendGenerator = function * (line) {338 yield `${line}${casedSuffix}`;339};340340const testAppendInput = async (t, reversed) => {342 const stdin = [foobarUint8Array, uppercaseGenerator(), appendGenerator];341 const stdin = [foobarUint8Array, uppercaseGenerator(), appendGenerator()];342 const reversedStdin = reversed ? stdin.reverse() : stdin;343 const {stdout} = await execa('stdin-fd.js', ['0'], {stdin: reversedStdin});344 const reversedSuffix = reversed ? casedSuffix.toUpperCase() : casedSuffix;345 t.is(stdout, `${foobarUppercase}${reversedSuffix}`);
2 unmodified lines
348test('Can use multiple generators as input', testAppendInput, false);349test('Can use multiple generators as input, reversed', testAppendInput, true);350351const testAppendOutput = async (t, reversed) => {353 const stdoutOption = [uppercaseGenerator(), appendGenerator];352 const stdoutOption = [uppercaseGenerator(), appendGenerator()];353 const reversedStdoutOption = reversed ? stdoutOption.reverse() : stdoutOption;354 const {stdout} = await execa('noop-fd.js', ['1', foobarString], {stdout: reversedStdoutOption});355 const reversedSuffix = reversed ? casedSuffix.toUpperCase() : casedSuffix;356 t.is(stdout, `${foobarUppercase}${reversedSuffix}`);
1 unmodified line
358359test('Can use multiple generators as output', testAppendOutput, false);360test('Can use multiple generators as output, reversed', testAppendOutput, true);361363test('Can use multiple identical generators', async t => {364 const {stdout} = await execa('noop-fd.js', ['1', foobarString], {stdout: [appendGenerator, appendGenerator]});365 t.is(stdout, `${foobarString}${casedSuffix}${casedSuffix}`);366});362const testTwoGenerators = async (t, producesTwo, firstGenerator, secondGenerator = firstGenerator) => {363 const {stdout} = await execa('noop-fd.js', ['1', foobarString], {stdout: [firstGenerator, secondGenerator]});364 const expectedSuffix = producesTwo ? `${casedSuffix}${casedSuffix}` : casedSuffix;365 t.is(stdout, `${foobarString}${expectedSuffix}`);366};367368test('Can use multiple identical generators', testTwoGenerators, true, appendGenerator().transform);369test('Can use multiple identical generators, options object', testTwoGenerators, true, appendGenerator());370371const testGeneratorSyntax = async (t, generator) => {372 const {stdout} = await execa('noop-fd.js', ['1', foobarString], {stdout: generator});373 t.is(stdout, foobarUppercase);374};375376test('Can pass generators with an options plain object', testGeneratorSyntax, uppercaseGenerator());377test('Can pass generators without an options plain object', testGeneratorSyntax, uppercaseGenerator().transform);
modified:test/stdio/iterable.js+5 added-10 removed
3 unmodified lines
4import {execa, execaSync} from '../../index.js';5import {setFixtureDir} from '../helpers/fixtures-dir.js';6import {getStdio} from '../helpers/stdio.js';7import {foobarObject, foobarObjectString} from '../helpers/input.js';8import {serializeGenerator, infiniteGenerator} from '../helpers/generator.js';8import {serializeGenerator, infiniteGenerator, throwingGenerator} from '../helpers/generator.js';910const stringArray = ['foo', 'bar'];1112const stringGenerator = function * () {
64 unmodified lines
77test('stdio[*] option cannot be a sync iterable - sync', testIterableSync, stringGenerator(), 3);78test('stdin option cannot be an async iterable - sync', testIterableSync, asyncGenerator(), 0);79test('stdio[*] option cannot be an async iterable - sync', testIterableSync, asyncGenerator(), 3);8081// eslint-disable-next-line require-yield82const throwingGenerator = function * () {83 throw new Error('generator error');84};8581const testIterableError = async (t, fdNumber) => {87 const {originalMessage} = await t.throwsAsync(execa('stdin-fd.js', [`${fdNumber}`], getStdio(fdNumber, throwingGenerator())));88 t.is(originalMessage, 'generator error');82 const {originalMessage} = await t.throwsAsync(execa('stdin-fd.js', [`${fdNumber}`], getStdio(fdNumber, throwingGenerator().transform())));83 t.is(originalMessage, 'Generator error');84};8586test('stdin option handles errors in iterables', testIterableError, 0);87test('stdio[*] option handles errors in iterables', testIterableError, 3);
13 unmodified lines
101test('stdout option cannot be an iterable - sync', testNoIterableOutput, stringGenerator(), 1, execaSync);102test('stderr option cannot be an iterable - sync', testNoIterableOutput, stringGenerator(), 2, execaSync);103104test('stdin option can be an infinite iterable', async t => {110 const iterable = infiniteGenerator();105 const iterable = infiniteGenerator().transform();106 const subprocess = execa('stdin.js', getStdio(0, iterable));107 await once(subprocess.stdout, 'data');108 subprocess.kill();109 const {stdout} = await t.throwsAsync(subprocess);
9 unmodified lines
119test('stdin option can be multiple iterables', testMultipleIterable, 0);120test('stdio[*] option can be multiple iterables', testMultipleIterable, 3);121122test('stdin option iterable is canceled on subprocess error', async t => {128 const iterable = infiniteGenerator();123 const iterable = infiniteGenerator().transform();124 await t.throwsAsync(execa('stdin.js', {stdin: iterable, timeout: 1}), {message: /timed out/});125 // eslint-disable-next-line no-unused-vars, no-empty126 for await (const _ of iterable) {}127});
modified:test/stdio/lines.js+3 added-3 removed
4 unmodified lines
5import {MaxBufferError} from 'get-stream';6import {execa, execaSync} from '../../index.js';7import {setFixtureDir} from '../helpers/fixtures-dir.js';8import {fullStdio} from '../helpers/stdio.js';9import {getChunksGenerator} from '../helpers/generator.js';9import {getOutputsGenerator} from '../helpers/generator.js';10import {foobarString, foobarObject} from '../helpers/input.js';11import {assertStreamOutput, assertIterableChunks} from '../helpers/convert.js';12import {13 simpleFull,
43 unmodified lines
5758// eslint-disable-next-line max-params59const testStreamLinesGenerator = async (t, input, expectedLines, objectMode, binary) => {60 const {stdout} = await execa('noop.js', {61 stdout: getChunksGenerator(input, objectMode, binary),61 stdout: getOutputsGenerator(input)(objectMode, binary),62 lines: true,63 stripFinalNewline: false,64 });65 t.deepEqual(stdout, expectedLines);
9 unmodified lines
75test('"lines: true" is a noop big strings generators without newlines, objectMode', testStreamLinesGenerator, [bigStringNoNewlines], [bigStringNoNewlines], true, false);7677test('"lines: true" is a noop with objects generators, objectMode', async t => {78 const {stdout} = await execa('noop.js', {79 stdout: getChunksGenerator([foobarObject], true),79 stdout: getOutputsGenerator([foobarObject])(true),80 lines: true,81 });82 t.deepEqual(stdout, [foobarObject]);83});
105 unmodified lines
modified:test/stdio/split.js+9 added-14 removed
1 unmodified line
2import {execa} from '../../index.js';3import {setFixtureDir} from '../helpers/fixtures-dir.js';4import {getStdio} from '../helpers/stdio.js';5import {6 getChunksGenerator,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,
42 unmodified lines
56const manyFullEnd = `${manyFull}\n`;57const manyLines = [manyFull];58const mixedNewlines = '.\n.\r\n.\n.\r\n.\n';5960const resultGenerator = function * (lines, chunk) {61 lines.push(chunk);62 yield chunk;63};6460// eslint-disable-next-line max-params61const testLines = async (t, fdNumber, input, expectedLines, expectedOutput, objectMode, preserveNewlines) => {62 const lines = [];63 const {stdio} = await execa('noop-fd.js', [`${fdNumber}`], {64 ...getStdio(fdNumber, [70 getChunksGenerator(input, false, true),71 {transform: resultGenerator.bind(undefined, lines), preserveNewlines, objectMode},65 getOutputsGenerator(input)(false, true),66 resultGenerator(lines)(objectMode, false, preserveNewlines),67 ]),68 stripFinalNewline: false,69 });70 t.deepEqual(lines, expectedLines);
61 unmodified lines
132const testBinaryOption = async (t, binary, input, expectedLines, expectedOutput, objectMode, preserveNewlines, encoding) => {133 const lines = [];134 const {stdout} = await execa('noop.js', {135 stdout: [141 getChunksGenerator(input, false, true),142 {transform: resultGenerator.bind(undefined, lines), binary, preserveNewlines, objectMode},136 getOutputsGenerator(input)(false, true),137 resultGenerator(lines)(objectMode, binary, preserveNewlines),138 ],139 stripFinalNewline: false,140 encoding,141 });
47 unmodified lines
189test('Line splitting when converting from string to Uint8Array, objectMode, preserveNewlines', testStringToUint8Array, [foobarUint8Array], true, false);190191const testStripNewline = async (t, input, expectedOutput) => {192 const {stdout} = await execa('noop.js', {198 stdout: getChunksGenerator([input]),193 stdout: getOutputsGenerator([input])(),194 stripFinalNewline: false,195 });196 t.is(stdout, expectedOutput);197};
21 unmodified lines
219const testUnsetObjectMode = async (t, expectedOutput, preserveNewlines) => {220 const lines = [];221 const {stdout} = await execa('noop.js', {222 stdout: [228 getChunksGenerator([foobarObject], true),223 getOutputsGenerator([foobarObject])(true),224 {transform: serializeResultGenerator.bind(undefined, lines), preserveNewlines, objectMode: false},225 ],226 stripFinalNewline: false,227 });
7 unmodified lines
235const testYieldArray = async (t, input, expectedLines, expectedOutput) => {236 const lines = [];237 const {stdout} = await execa('noop.js', {238 stdout: [244 getOutputsGenerator(input),245 resultGenerator.bind(undefined, lines),239 getOutputsGenerator(input)(),240 resultGenerator(lines)(),241 ],242 stripFinalNewline: false,243 });244 t.deepEqual(lines, expectedLines);
5 unmodified lines
modified:test/stdio/transform.js+30 added-44 removed
1import {Buffer} from 'node:buffer';2import {once} from 'node:events';3import {setTimeout, scheduler} from 'node:timers/promises';3import {scheduler} from 'node:timers/promises';4import test from 'ava';5import {getStreamAsArray} from 'get-stream';6import {execa} from '../../index.js';7import {foobarString} from '../helpers/input.js';8import {9 noopGenerator,10 identityGenerator,11 identityAsyncGenerator,12 getOutputsGenerator,10 getOutputAsyncGenerator,11 getOutputGenerator,12 getOutputsGenerator,13 infiniteGenerator,14 outputObjectGenerator,16 convertTransformToFinal,15 noYieldGenerator,16 multipleYieldGenerator,17 convertTransformToFinal,18 prefix,19 suffix,20 throwingGenerator,21 GENERATOR_ERROR_REGEXP,22 timeoutGenerator,23} from '../helpers/generator.js';24import {defaultHighWaterMark} from '../helpers/stream.js';25import {setFixtureDir} from '../helpers/fixtures-dir.js';2627setFixtureDir();2829const testGeneratorFinal = async (t, fixtureName) => {27 const {stdout} = await execa(fixtureName, {stdout: convertTransformToFinal(getOutputGenerator(foobarString), true)});30 const {stdout} = await execa(fixtureName, {stdout: convertTransformToFinal(getOutputGenerator(foobarString)(), true)});31 t.is(stdout, foobarString);32};3334test('Generators "final" can be used', testGeneratorFinal, 'noop.js');35test('Generators "final" is used even on empty streams', testGeneratorFinal, 'empty.js');3637const testFinalAlone = async (t, final) => {35 const {stdout} = await execa('noop-fd.js', ['1', '.'], {stdout: {final: final(foobarString), binary: true}});38 const {stdout} = await execa('noop-fd.js', ['1', '.'], {stdout: {final: final(foobarString)().transform, binary: true}});39 t.is(stdout, `.${foobarString}`);40};4139test('Generators "final" can be used without "transform"', testFinalAlone, identityGenerator);40test('Generators "final" can be used without "transform", async', testFinalAlone, identityAsyncGenerator);42test('Generators "final" can be used without "transform"', testFinalAlone, getOutputGenerator);43test('Generators "final" can be used without "transform", async', testFinalAlone, getOutputAsyncGenerator);4445const testFinalNoOutput = async (t, final) => {43 const {stdout} = await execa('empty.js', {stdout: {final: final(foobarString)}});46 const {stdout} = await execa('empty.js', {stdout: {final: final(foobarString)().transform}});47 t.is(stdout, foobarString);48};4947test('Generators "final" can be used without "transform" nor output', testFinalNoOutput, identityGenerator);48test('Generators "final" can be used without "transform" nor output, async', testFinalNoOutput, identityAsyncGenerator);50test('Generators "final" can be used without "transform" nor output', testFinalNoOutput, getOutputGenerator);51test('Generators "final" can be used without "transform" nor output, async', testFinalNoOutput, getOutputAsyncGenerator);5253const repeatCount = defaultHighWaterMark * 3;5455const writerGenerator = function * () {
9 unmodified lines
6566const testHighWaterMark = async (t, passThrough, binary, objectMode) => {67 const {stdout} = await execa('noop.js', {68 stdout: [66 ...(objectMode ? [outputObjectGenerator] : []),69 ...(objectMode ? [outputObjectGenerator()] : []),70 writerGenerator,71 ...(passThrough ? [noopGenerator(false, binary)] : []),72 {transform: getLengthGenerator.bind(undefined, t), preserveNewlines: true, objectMode: true},73 ],
13 unmodified lines
87};8889test('Generator can filter "transform" by not calling yield', testNoYield, false, false, '');90test('Generator can filter "transform" by not calling yield, objectMode', testNoYield, true, false, []);88test('Generator can filter "final" by not calling yield', testNoYield, false, false, '');89test('Generator can filter "final" by not calling yield, objectMode', testNoYield, true, false, []);91test('Generator can filter "final" by not calling yield', testNoYield, false, true, '');92test('Generator can filter "final" by not calling yield, objectMode', testNoYield, true, true, []);9391const prefix = '> ';92const suffix = ' <';9394const multipleYieldGenerator = async function * (line = foobarString) {95 yield prefix;96 await scheduler.yield();97 yield line;98 await scheduler.yield();99 yield suffix;100};10194const testMultipleYields = async (t, final) => {103 const {stdout} = await execa('noop-fd.js', ['1', foobarString], {stdout: convertTransformToFinal(multipleYieldGenerator, final)});95 const {stdout} = await execa('noop-fd.js', ['1', foobarString], {stdout: convertTransformToFinal(multipleYieldGenerator(), final)});96 t.is(stdout, `${prefix}\n${foobarString}\n${suffix}`);97};9899test('Generator can yield "transform" multiple times at different moments', testMultipleYields, false);
32 unmodified lines
132test('Generators take "maxBuffer" into account', async t => {133 const bigString = '.'.repeat(maxBuffer);134 const {stdout} = await execa('noop.js', {135 maxBuffer,144 stdout: getOutputGenerator(bigString, false, true),136 stdout: getOutputGenerator(bigString)(false, true),137 });138 t.is(stdout, bigString);139148 await t.throwsAsync(execa('noop.js', {maxBuffer, stdout: getOutputGenerator(`${bigString}.`, false)}));140 await t.throwsAsync(execa('noop.js', {maxBuffer, stdout: getOutputGenerator(`${bigString}.`)(false)}));141});142143test('Generators take "maxBuffer" into account, objectMode', async t => {144 const bigArray = Array.from({length: maxBuffer}).fill('.');145 const {stdout} = await execa('noop.js', {146 maxBuffer,155 stdout: getOutputsGenerator(bigArray, true, true),147 stdout: getOutputsGenerator(bigArray)(true, true),148 });149 t.is(stdout.length, maxBuffer);150159 await t.throwsAsync(execa('noop.js', {maxBuffer, stdout: getOutputsGenerator([...bigArray, ''], true)}));151 await t.throwsAsync(execa('noop.js', {maxBuffer, stdout: getOutputsGenerator([...bigArray, ''])(true)}));152});153162const timeoutGenerator = async function * (timeout) {163 await setTimeout(timeout);164 yield foobarString;165};166154const testAsyncGenerators = async (t, final) => {155 const {stdout} = await execa('noop.js', {169 maxBuffer,170 stdout: convertTransformToFinal(timeoutGenerator.bind(undefined, 1e2), final),156 stdout: convertTransformToFinal(timeoutGenerator(1e2)(), final),157 });158 t.is(stdout, foobarString);159};160
1 unmodified line
162test('Generators "final" is awaited on success', testAsyncGenerators, true);163164const testThrowingGenerator = async (t, final) => {165 await t.throwsAsync(180 execa('noop-fd.js', ['1', foobarString], {stdout: convertTransformToFinal(throwingGenerator, final)}),166 execa('noop-fd.js', ['1', foobarString], {stdout: convertTransformToFinal(throwingGenerator(), final)}),167 {message: GENERATOR_ERROR_REGEXP},168 );169};170
1 unmodified line
172test('Generators "final" errors make subprocess fail', testThrowingGenerator, true);173174test('Generators errors make subprocess fail even when other output generators do not throw', async t => {175 await t.throwsAsync(190 execa('noop-fd.js', ['1', foobarString], {stdout: [noopGenerator(false), throwingGenerator, noopGenerator(false)]}),176 execa('noop-fd.js', ['1', foobarString], {stdout: [noopGenerator(false), throwingGenerator(), noopGenerator(false)]}),177 {message: GENERATOR_ERROR_REGEXP},178 );179});180181test('Generators errors make subprocess fail even when other input generators do not throw', async t => {196 const subprocess = execa('stdin-fd.js', ['0'], {stdin: [noopGenerator(false), throwingGenerator, noopGenerator(false)]});182 const subprocess = execa('stdin-fd.js', ['0'], {stdin: [noopGenerator(false), throwingGenerator(), noopGenerator(false)]});183 subprocess.stdin.write('foobar\n');184 await t.throwsAsync(subprocess, {message: GENERATOR_ERROR_REGEXP});185});186187const testGeneratorCancel = async (t, error) => {202 const subprocess = execa('noop.js', {stdout: infiniteGenerator});188 const subprocess = execa('noop.js', {stdout: infiniteGenerator()});189 await once(subprocess.stdout, 'data');190 subprocess.stdout.destroy(error);191 await (error === undefined ? t.notThrowsAsync(subprocess) : t.throwsAsync(subprocess));192};
9 unmodified lines
202 t.like(await t.throwsAsync(subprocess), {cause});203};204205test('Generators are destroyed on subprocess error, sync', testGeneratorDestroy, noopGenerator(false));220test('Generators are destroyed on subprocess error, async', testGeneratorDestroy, infiniteGenerator);206test('Generators are destroyed on subprocess error, async', testGeneratorDestroy, infiniteGenerator());207208test('Generators are destroyed on early subprocess exit', async t => {223 await t.throwsAsync(execa('noop.js', {stdout: infiniteGenerator, uid: -1}));209 await t.throwsAsync(execa('noop.js', {stdout: infiniteGenerator(), uid: -1}));210});
modified:test/stdio/type.js+5 added-5 removed
34 unmodified lines
35test('Cannot use invalid "objectMode" with stdout', testInvalidBinary, 1, 'objectMode');36test('Cannot use invalid "objectMode" with stderr', testInvalidBinary, 2, 'objectMode');37test('Cannot use invalid "objectMode" with stdio[*]', testInvalidBinary, 3, 'objectMode');3839const testSyncMethods = (t, fdNumber) => {39const testSyncMethodsGenerator = (t, fdNumber) => {40 t.throws(() => {41 execaSync('empty.js', getStdio(fdNumber, uppercaseGenerator()));42 }, {message: /cannot be a generator/});43};4445test('Cannot use generators with sync methods and stdin', testSyncMethods, 0);46test('Cannot use generators with sync methods and stdout', testSyncMethods, 1);47test('Cannot use generators with sync methods and stderr', testSyncMethods, 2);48test('Cannot use generators with sync methods and stdio[*]', testSyncMethods, 3);45test('Cannot use generators with sync methods and stdin', testSyncMethodsGenerator, 0);46test('Cannot use generators with sync methods and stdout', testSyncMethodsGenerator, 1);47test('Cannot use generators with sync methods and stderr', testSyncMethodsGenerator, 2);48test('Cannot use generators with sync methods and stdio[*]', testSyncMethodsGenerator, 3);
modified:test/stdio/validate.js+4 added-4 removed
9 unmodified lines
1011// eslint-disable-next-line max-params12const testGeneratorReturn = async (t, fdNumber, generator, input, objectMode, isInput) => {13 const fixtureName = isInput ? 'stdin-fd.js' : 'noop-fd.js';14 const subprocess = execa(fixtureName, [`${fdNumber}`], getStdio(fdNumber, generator(input, objectMode)));14 const subprocess = execa(fixtureName, [`${fdNumber}`], getStdio(fdNumber, generator(input)(objectMode)));15 const {message} = await t.throwsAsync(subprocess);16 t.true(message.includes(getMessage(input)));17};18
8 unmodified lines
2728 return 'a string or an Uint8Array';29};3031const lastInputGenerator = (input, objectMode) => [foobarUint8Array, getOutputGenerator(input, objectMode)];32const inputGenerator = (input, objectMode) => [...lastInputGenerator(input, objectMode), serializeGenerator(true)];31const lastInputGenerator = input => objectMode => [foobarUint8Array, getOutputGenerator(input)(objectMode)];32const inputGenerator = input => objectMode => [...lastInputGenerator(input)(objectMode), serializeGenerator(true)];3334test('Generators with result.stdin cannot return an object if not in objectMode', testGeneratorReturn, 0, inputGenerator, foobarObject, false, true);35test('Generators with result.stdio[*] as input cannot return an object if not in objectMode', testGeneratorReturn, 3, inputGenerator, foobarObject, false, true);36test('The last generator with result.stdin cannot return an object even in objectMode', testGeneratorReturn, 0, lastInputGenerator, foobarObject, true, true);
17 unmodified lines
54test('Generators with result.stdout cannot return undefined if not in objectMode', testGeneratorReturn, 1, getOutputGenerator, undefined, false, false);55test('Generators with result.stdout cannot return undefined if in objectMode', testGeneratorReturn, 1, getOutputGenerator, undefined, true, false);5657test('Generators "final" return value is validated', async t => {58 const subprocess = execa('noop.js', {stdout: convertTransformToFinal(getOutputGenerator(null, true), true)});58 const subprocess = execa('noop.js', {stdout: convertTransformToFinal(getOutputGenerator(null)(true), true)});59 await t.throwsAsync(subprocess, {message: /not be called at all/});60});
modified:test/stream/subprocess.js+1 added-1 removed
6 unmodified lines
78setFixtureDir();910const getStreamInputSubprocess = fdNumber => execa('stdin-fd.js', [`${fdNumber}`], fdNumber === 311 ? getStdio(3, [new Uint8Array(), infiniteGenerator])11 ? getStdio(3, [new Uint8Array(), infiniteGenerator()])12 : {});13const getStreamOutputSubprocess = fdNumber => execa('noop-repeat.js', [`${fdNumber}`], fdNumber === 3 ? fullStdio : {});1415const assertStreamInputError = (t, {exitCode, signal, isTerminated, failed}) => {
102 unmodified lines
modified:index.d.ts+10 added-10 removed
19 unmodified lines
20 | 'inherit';2122// @todo Use `string`, `Uint8Array` or `unknown` for both the argument and the return type, based on whether `encoding: 'buffer'` and `objectMode: true` are used.23// See https://github.com/sindresorhus/execa/issues/69424type StdioTransform = (chunk: unknown) => AsyncGenerator<unknown, void, void> | Generator<unknown, void, void>;25type StdioFinal = () => AsyncGenerator<unknown, void, void> | Generator<unknown, void, void>;24type GeneratorTransform = (chunk: unknown) => AsyncGenerator<unknown, void, void> | Generator<unknown, void, void>;25type GeneratorFinal = () => AsyncGenerator<unknown, void, void> | Generator<unknown, void, void>;2627type StdioTransformFull = {28 transform: StdioTransform;29 final?: StdioFinal;27type GeneratorTransformFull = {28 transform: GeneratorTransform;29 final?: GeneratorFinal;30 binary?: boolean;31 preserveNewlines?: boolean;32 objectMode?: boolean;33};
5 unmodified lines
39 | undefined40 | URL41 | {file: string}42 | IfAsync<IsSync,43 | StdioTransform44 | StdioTransformFull>;43 | GeneratorTransform44 | GeneratorTransformFull>;4546type InputStdioOption<IsSync extends boolean = boolean> =47 | Uint8Array48 | Readable
70 unmodified lines
119 ? OutputOptions[number]120 : OutputOptions121>;122123type IsObjectOutputOption<OutputOption extends StdioSingleOption> = OutputOption extends StdioTransformFull123type IsObjectOutputOption<OutputOption extends StdioSingleOption> = OutputOption extends GeneratorTransformFull124 ? BooleanObjectMode<OutputOption['objectMode']>125 : false;126127type BooleanObjectMode<ObjectModeOption extends StdioTransformFull['objectMode']> = ObjectModeOption extends true ? true : false;127type BooleanObjectMode<ObjectModeOption extends GeneratorTransformFull['objectMode']> = ObjectModeOption extends true ? true : false;128129// Whether `result.stdout|stderr|all` is `undefined`, excluding the `buffer` option130type IgnoresStreamResult<131 FdNumber extends string,
1044 unmodified lines
11761177```1178import {execa} from 'execa';11791180const arg = 'unicorns'1180const arg = 'unicorns';1181const {stdout} = await execa`echo ${arg} & rainbows!`;1182console.log(stdout);1183//=> 'unicorns & rainbows!'1184```
399 unmodified lines
modified:readme.md+1 added-1 removed
97 unmodified lines
9899```js100import {execa} from 'execa';101102const arg = 'unicorns'102const arg = 'unicorns';103const {stdout} = await execa`echo ${arg} & rainbows!`;104console.log(stdout);105//=> 'unicorns & rainbows!'106```
1119 unmodified lines