methods.js
This file
Path
test/pipe/methods.js
447 lines · 14.6 KiB · JavaScript
Last changed by
Add `.readableStream()`, `.writableStream()` and `.transformStream()` methods (#1254)Sindre Sorhusbefore adoption29d9cfc
History of this fileTake it
Expose the destination subprocess methods on `.pipe()` (#1252)Sindre Sorhusbefore adoptionc31c94c
lines 1–68why, one step back1import {setTimeout} from 'node:timers/promises';2import {Readable} from 'node:stream';3import {text} from 'node:stream/consumers';4import test from 'ava';5import {execa} from '../../index.js';6import {setFixtureDirectory} from '../helpers/fixtures-directory.js';7import {simpleFull, noNewlinesFull, noNewlinesChunks} from '../helpers/lines.js';8import {foobarString, foobarArray} from '../helpers/input.js';910setFixtureDirectory();1112const timeoutSymbol = Symbol('timeout');1314// `stdin.js` pipes its stdin to its stdout, so the piped output equals the source output15const pipeSimple = () => execa('noop-fd.js', ['1', simpleFull]).pipe('stdin.js');16const pipeAll = () => execa('noop-fd.js', ['1', simpleFull]).pipe('stdin.js', {all: true});17const pipeDistinctBoth = () => execa('noop-fd.js', ['1', simpleFull]).pipe('stdin-distinct-both.js');1819const assertSettles = async (t, promise, timeout = 1000) => {20 const result = await Promise.race([21 promise,22 // Several pipe cancellation tests are specifically checking that a pending reader does not hang.23 setTimeout(timeout, timeoutSymbol, {ref: false}),24 ]);2526 t.not(result, timeoutSymbol);27 return result;28};2930const cleanupSubprocesses = async (...subprocesses) => {31 for (const subprocess of subprocesses) {32 subprocess.kill();33 }3435 await Promise.allSettled(subprocesses);36};3738const getPipeMessages = async piped => {39 const messages = [];40 for await (const message of piped.getEachMessage()) {41 messages.push(message);42 }4344 return messages;45};4647test('The .pipe() return value can be iterated', async t => {48 const lines = [];49 for await (const line of pipeSimple()) {50 lines.push(line);51 }5253 t.deepEqual(lines, noNewlinesChunks);54});5556test('The .pipe() return value has an .iterable() method', async t => {57 const lines = [];58 for await (const line of pipeSimple().iterable()) {59 lines.push(line);60 }6162 t.deepEqual(lines, noNewlinesChunks);63});6465test('The .pipe() return value has a .readable() method', async t => {66 t.is(await text(pipeSimple().readable()), simpleFull);67});68Add `.readableStream()`, `.writableStream()` and `.transformStream()` methods (#1254)Sindre Sorhusbefore adoption29d9cfc
lines 69–72why, one step back69test('The .pipe() return value has a .readableStream() method', async t => {70 t.is(await text(pipeSimple().readableStream()), simpleFull);71});72Expose the destination subprocess methods on `.pipe()` (#1252)Sindre Sorhusbefore adoptionc31c94c
lines 73–97why, one step back73test('The .pipe() return value .readable() can be called multiple times', async t => {74 const piped = pipeSimple();75 const [output, secondOutput] = await Promise.all([76 text(piped.readable()),77 text(piped.readable()),78 ]);7980 t.is(output, simpleFull);81 t.is(secondOutput, simpleFull);82});8384test('The .pipe() return value .readable() keeps conversion options', async t => {85 const chunks = [];86 for await (const chunk of pipeSimple().readable({binary: false, preserveNewlines: false})) {87 chunks.push(chunk);88 }8990 t.deepEqual(chunks, noNewlinesChunks);91 t.is(chunks.join(''), noNewlinesFull);92});9394test('The .pipe() return value does not have a .writable() method', async t => {95 const piped = pipeSimple();96 t.is(piped.writable, undefined);97 t.is(piped.duplex, undefined);Add `.readableStream()`, `.writableStream()` and `.transformStream()` methods (#1254)Sindre Sorhusbefore adoption29d9cfc
lines 98–99why, one step back98 t.is(piped.writableStream, undefined);99 t.is(piped.transformStream, undefined);Expose the destination subprocess methods on `.pipe()` (#1252)Sindre Sorhusbefore adoptionc31c94c
lines 100–381why, one step back100 await piped;101});102103test('The .pipe() return value does not have .all unless destination uses the "all" option', async t => {104 const piped = pipeSimple();105 const descriptor = Object.getOwnPropertyDescriptor(piped, 'all');106107 t.is(piped.all, undefined);108 t.is(descriptor.value, undefined);109 t.is(descriptor.get, undefined);110 await piped;111});112113test('The .pipe() return value has an .all property', async t => {114 const piped = pipeAll();115 t.true(piped.all instanceof Readable);116 t.is(await text(piped.all), simpleFull);117 await piped;118});119120test('The .pipe() return value .all is created lazily and cached', async t => {121 const piped = pipeAll();122 const descriptor = Object.getOwnPropertyDescriptor(piped, 'all');123124 t.is(typeof descriptor.get, 'function');125 const {all} = piped;126 t.true(all instanceof Readable);127 t.is(piped.all, all);128 t.is(Object.getOwnPropertyDescriptor(piped, 'all').get, undefined);129 t.is(await text(all), simpleFull);130 await piped;131});132133test('The .pipe() return value .readable() can read destination stderr', async t => {134 const piped = pipeDistinctBoth();135136 t.is(await text(piped.readable({from: 'stderr'})), `${simpleFull}:stderr`);137 await piped;138});139140test('The .pipe() return value .iterable() can read destination stderr', async t => {141 const piped = pipeDistinctBoth();142 const lines = [];143 for await (const line of piped.iterable({from: 'stderr'})) {144 lines.push(line);145 }146147 t.deepEqual(lines, ['aaa', 'bbb', 'ccc:stderr']);148 await piped;149});150151test('The .pipe() return value has IPC methods', async t => {152 const piped = execa('empty.js').pipe('ipc-send-twice.js', {ipc: true});153 t.deepEqual(await getPipeMessages(piped), foobarArray);154 const {ipcOutput} = await piped;155 t.deepEqual(ipcOutput, foobarArray);156});157158test('The .pipe() return value .getEachMessage() can be called twice at the same time', async t => {159 const piped = execa('empty.js').pipe('ipc-send-twice.js', {ipc: true});160161 t.deepEqual(162 await Promise.all([getPipeMessages(piped), getPipeMessages(piped)]),163 [foobarArray, foobarArray],164 );165166 const {ipcOutput} = await piped;167 t.deepEqual(ipcOutput, foobarArray);168});169170test('The .pipe() return value .getEachMessage() preserves setup errors', async t => {171 const piped = execa('empty.js').pipe('ipc-send-twice.js', {ipc: true});172173 t.throws(() => {174 piped.getEachMessage(null);175 }, {instanceOf: TypeError});176177 await piped;178});179180test('The .pipe() return value .getEachMessage() waits for source failure', async t => {181 const piped = execa('fail.js').pipe('ipc-send-twice.js', {ipc: true});182183 await t.throwsAsync(async () => {184 for await (const message of piped.getEachMessage()) {185 t.true(foobarArray.includes(message));186 }187 }, {message: /Command failed with exit code 2/});188});189190test('The .pipe() return value .getEachMessage() waits for pipe cancellation', async t => {191 const abortController = new AbortController();192 const source = execa('noop-repeat.js');193 const destination = execa('ipc-send-forever.js', {ipc: true});194 t.teardown(async () => {195 await cleanupSubprocesses(source, destination);196 });197198 const piped = source.pipe(destination, {unpipeSignal: abortController.signal});199 const iterator = piped.getEachMessage();200 t.deepEqual(await iterator.next(), {done: false, value: foobarString});201202 const readerPromise = t.throwsAsync(iterator.next(), {message: /Pipe canceled/});203 abortController.abort();204 await assertSettles(t, readerPromise);205});206207test('The .pipe() return value .getEachMessage() cancels every pending reader', async t => {208 const abortController = new AbortController();209 const source = execa('noop-repeat.js');210 const destination = execa('ipc-send-forever.js', {ipc: true});211 t.teardown(async () => {212 await cleanupSubprocesses(source, destination);213 });214215 const piped = source.pipe(destination, {unpipeSignal: abortController.signal});216 const iterators = [217 piped.getEachMessage(),218 piped.getEachMessage(),219 ];220221 t.deepEqual(222 await Promise.all(iterators.map(async iterator => iterator.next())),223 [224 {done: false, value: foobarString},225 {done: false, value: foobarString},226 ],227 );228229 const readerPromises = iterators.map(iterator => t.throwsAsync(iterator.next(), {message: /Pipe canceled/}));230 abortController.abort();231 await Promise.all(readerPromises.map(async readerPromise => assertSettles(t, readerPromise)));232});233234const assertCanceledPipeMessageReader = async (t, getReader, abortBeforePipe = false) => {235 const abortController = new AbortController();236 if (abortBeforePipe) {237 abortController.abort();238 }239240 const source = execa('noop-repeat.js');241 const destination = execa('ipc-get.js', {ipc: true});242 t.teardown(async () => {243 await cleanupSubprocesses(source, destination);244 });245246 const piped = source.pipe(destination, {unpipeSignal: abortController.signal});247 const readerPromise = t.throwsAsync(getReader(piped), {message: /Pipe canceled/});248249 if (!abortBeforePipe) {250 abortController.abort();251 }252253 await assertSettles(t, readerPromise);254 await t.throwsAsync(piped, {message: /Pipe canceled/});255};256257test('The .pipe() return value .getEachMessage() waits for pipe cancellation before IPC messages', async t => {258 await assertCanceledPipeMessageReader(t, piped => piped.getEachMessage().next());259});260261test('The .pipe() return value .getEachMessage() waits for already canceled pipes', async t => {262 await assertCanceledPipeMessageReader(t, piped => piped.getEachMessage().next(), true);263});264265test('The .pipe() return value .getOneMessage() waits for pipe cancellation before IPC messages', async t => {266 await assertCanceledPipeMessageReader(t, piped => piped.getOneMessage());267});268269test('The .pipe() return value .getOneMessage() waits for already canceled pipes', async t => {270 await assertCanceledPipeMessageReader(t, piped => piped.getOneMessage(), true);271});272273test('The .pipe() return value .getEachMessage() waits for the pipe when the iterator is returned', async t => {274 const source = execa('empty.js');275 const destination = execa('ipc-send-forever.js', {ipc: true});276 t.teardown(async () => {277 await cleanupSubprocesses(source, destination);278 });279280 const piped = source.pipe(destination);281 const iterator = piped.getEachMessage();282283 t.deepEqual(await iterator.next(), {done: false, value: foobarString});284 const returnPromise = t.throwsAsync(iterator.return());285 destination.kill();286 const error = await returnPromise;287 t.true(error.isTerminated);288 await Promise.allSettled([source, destination, piped]);289});290291test('The .pipe() return value .getEachMessage() propagates source failure when the iterator is returned', async t => {292 const source = execa('ipc-echo-fail.js', {ipc: true});293 const piped = source.pipe('ipc-send-wait-print.js', {ipc: true});294 const iterator = piped.getEachMessage();295296 t.deepEqual(await iterator.next(), {done: false, value: foobarString});297 const returnPromise = t.throwsAsync(iterator.return(), {message: /Command failed with exit code 1/});298 await source.sendMessage(foobarString);299 await returnPromise;300});301302test('The .pipe() return value .getEachMessage() propagates destination failure', async t => {303 const piped = execa('empty.js').pipe('ipc-send-fail.js', {ipc: true});304305 await t.throwsAsync(async () => {306 for await (const message of piped.getEachMessage()) {307 t.is(message, foobarString);308 }309 }, {message: /Command failed with exit code 1/});310311 const {ipcOutput} = await t.throwsAsync(piped);312 t.deepEqual(ipcOutput, [foobarString]);313});314315test('The .pipe() return value .getEachMessage() waits for the pipe when the consumer throws', async t => {316 const piped = execa('empty.js').pipe('ipc-send-wait-print.js', {ipc: true});317 const cause = new Error(foobarString);318319 t.is(await t.throwsAsync(async () => {320 // eslint-disable-next-line no-unreachable-loop321 for await (const message of piped.getEachMessage()) {322 t.is(message, foobarString);323 throw cause;324 }325 }), cause);326327 const {ipcOutput, stdout} = await piped;328 t.deepEqual(ipcOutput, [foobarString]);329 t.is(stdout, '.');330});331332test('The .pipe() return value .getEachMessage() validates IPC immediately', async t => {333 const source = execa('stdin.js');334 const destination = execa('stdin.js');335 t.teardown(async () => {336 await cleanupSubprocesses(source, destination);337 });338339 const piped = source.pipe(destination);340 const {message} = t.throws(() => piped.getEachMessage());341342 t.true(message.includes('subprocess.getEachMessage() can only be used'));343 source.kill();344 destination.kill();345 await Promise.allSettled([source, destination, piped]);346});347348test('The .pipe() return value can exchange IPC messages', async t => {349 const piped = execa('empty.js').pipe('ipc-echo.js', {ipc: true});350 await piped.sendMessage(foobarString);351 t.is(await piped.getOneMessage(), foobarString);352 await piped;353});354355test('A chained .pipe() return value can be iterated', async t => {356 const lines = [];357 for await (const line of execa('noop-fd.js', ['1', simpleFull]).pipe('stdin.js').pipe('stdin.js')) {358 lines.push(line);359 }360361 t.deepEqual(lines, noNewlinesChunks);362});363364test('The .pipe() return value still awaits both subprocesses', async t => {365 await t.throwsAsync(execa('fail.js').pipe('stdin.js'), {message: /Command failed with exit code 2/});366});367368test('The .pipe() return value iteration waits for source failure', async t => {369 const piped = execa('fail.js').pipe('stdin.js');370371 await t.throwsAsync(async () => {372 for await (const line of piped) {373 t.fail(`Unexpected line: ${line}`);374 }375 }, {message: /Command failed with exit code 2/});376});377378test('The .pipe() return value .readable() waits for source failure', async t => {379 const piped = execa('fail.js').pipe('stdin.js');380381 await t.throwsAsync(text(piped.readable()), {message: /Command failed with exit code 2/});Add `.readableStream()`, `.writableStream()` and `.transformStream()` methods (#1254)Sindre Sorhusbefore adoption29d9cfc
lines 382–387why, one step back382});383384test('The .pipe() return value .readableStream() waits for source failure', async t => {385 const piped = execa('fail.js').pipe('stdin.js');386387 await t.throwsAsync(text(piped.readableStream()), {message: /Command failed with exit code 2/});Expose the destination subprocess methods on `.pipe()` (#1252)Sindre Sorhusbefore adoptionc31c94c
lines 388–447why, one step back388});389390test('The .pipe() return value .all waits for source failure', async t => {391 const piped = execa('fail.js').pipe('stdin.js', {all: true});392393 await t.throwsAsync(text(piped.all), {message: /Command failed with exit code 2/});394});395396const assertCanceledPipeReader = async (t, getReader, abortBeforePipe = false) => {397 const abortController = new AbortController();398 if (abortBeforePipe) {399 abortController.abort();400 }401402 const source = execa('stdin.js');403 const destination = execa('stdin.js', {all: true});404 t.teardown(async () => {405 await cleanupSubprocesses(source, destination);406 });407408 const piped = source.pipe(destination, {unpipeSignal: abortController.signal});409 const readerPromise = t.throwsAsync(getReader(piped), {message: /Pipe canceled/});410411 if (!abortBeforePipe) {412 abortController.abort();413 }414415 await assertSettles(t, readerPromise, 200);416};417418test('The .pipe() return value .readable() waits for pipe cancellation', async t => {419 await assertCanceledPipeReader(t, piped => text(piped.readable()));420});421422test('The .pipe() return value .all waits for pipe cancellation', async t => {423 await assertCanceledPipeReader(t, piped => text(piped.all));424});425426test('The .pipe() return value .readable() waits for already canceled pipes', async t => {427 await assertCanceledPipeReader(t, piped => text(piped.readable()), true);428});429430test('The .pipe() return value .all waits for already canceled pipes', async t => {431 await assertCanceledPipeReader(t, piped => text(piped.all), true);432});433434test('Multiple sources piped to one destination each expose the destination methods', async t => {435 const destination = execa('stdin.js');436 const piped = [437 execa('noop-fd.js', ['1', foobarString]).pipe(destination),438 execa('noop-fd.js', ['1', foobarString]).pipe(destination),439 ];440441 for (const pipePromise of piped) {442 t.is(typeof pipePromise.iterable, 'function');443 t.is(typeof pipePromise[Symbol.asyncIterator], 'function');444 }445446 await Promise.all(piped);447});