methods.js
This file
Path
test/pipe/methods.js
462 lines · 16.1 KiB · JavaScript
Last changed by
Fix IPC edge casesSindre Sorhusbefore adoption5f80cde
History of this fileTake it
1import assert from 'node:assert/strict';2import {setTimeout} from 'node:timers/promises';3import {Readable, Writable} from 'node:stream';4import {text} from 'node:stream/consumers';5import test from 'node:test';6import {assertThrows, assertRejects} from '../helpers/assert.js';7import {execa} from '../../index.js';8import {setFixtureDirectory} from '../helpers/fixtures-directory.js';9import {simpleFull, noNewlinesFull, noNewlinesChunks} from '../helpers/lines.js';10import {foobarString, foobarArray} from '../helpers/input.js';11/* eslint-disable node-test/no-conditional-assertion -- shared helper functions are called from conditional paths on purpose */1213setFixtureDirectory();1415const timeoutSymbol = Symbol('timeout');1617// `stdin.js` pipes its stdin to its stdout, so the piped output equals the source output18const pipeSimple = () => execa('noop-fd.js', ['1', simpleFull]).pipe('stdin.js');19const pipeAll = () => execa('noop-fd.js', ['1', simpleFull]).pipe('stdin.js', {all: true});20const pipeDistinctBoth = () => execa('noop-fd.js', ['1', simpleFull]).pipe('stdin-distinct-both.js');2122const assertSettles = async (promise, timeout = 1000) => {23 const result = await Promise.race([24 promise,25 // Several pipe cancellation tests are specifically checking that a pending reader does not hang.26 setTimeout(timeout, timeoutSymbol, {ref: false}),27 ]);2829 assert.notEqual(result, timeoutSymbol);30 return result;31};3233const cleanupSubprocesses = async (...subprocesses) => {34 for (const subprocess of subprocesses) {35 subprocess.kill();36 }3738 await Promise.allSettled(subprocesses);39};4041const getPipeMessages = async piped => {42 const messages = await Array.fromAsync(piped.getEachMessage());4344 return messages;45};4647test('The .pipe() return value can be iterated', async () => {48 const lines = await Array.fromAsync(pipeSimple());4950 assert.deepEqual(lines, noNewlinesChunks);51});5253test('The .pipe() return value has an .iterable() method', async () => {54 const lines = await Array.fromAsync(pipeSimple().iterable());5556 assert.deepEqual(lines, noNewlinesChunks);57});5859test('The .pipe() return value has a .readable() method', async () => {60 assert.equal(await text(pipeSimple().readable()), simpleFull);61});6263test('The .pipe() return value has a .readableStream() method', async () => {64 assert.equal(await text(pipeSimple().readableStream()), simpleFull);65});6667test('The .pipe() return value .readable() can be called multiple times', async () => {68 const piped = pipeSimple();69 const [output, secondOutput] = await Promise.all([70 text(piped.readable()),71 text(piped.readable()),72 ]);7374 assert.equal(output, simpleFull);75 assert.equal(secondOutput, simpleFull);76});7778test('The .pipe() return value .readable() keeps conversion options', async () => {79 const chunks = await Array.fromAsync(pipeSimple().readable({binary: false, preserveNewlines: false}));8081 assert.deepEqual(chunks, noNewlinesChunks);82 assert.equal(chunks.join(''), noNewlinesFull);83});8485test('The .pipe() return value does not have a .writable() method', async () => {86 const piped = pipeSimple();87 assert.equal(piped.writable, undefined);88 assert.equal(piped.duplex, undefined);89 assert.equal(piped.writableStream, undefined);90 assert.equal(piped.transformStream, undefined);91 await piped;92});9394test('The .pipe() return value does not have .all unless destination uses the "all" option', async () => {95 const piped = pipeSimple();96 const descriptor = Object.getOwnPropertyDescriptor(piped, 'all');9798 assert.equal(piped.all, undefined);99 assert.equal(descriptor.value, undefined);100 assert.equal(descriptor.get, undefined);101 await piped;102});103104test('The .pipe() return value has an .all property', async () => {105 const piped = pipeAll();106 assert.ok(piped.all instanceof Readable);107 assert.equal(await text(piped.all), simpleFull);108 await piped;109});110111test('The .pipe() return value .all is created lazily and cached', async () => {112 const piped = pipeAll();113 const descriptor = Object.getOwnPropertyDescriptor(piped, 'all');114115 assert.equal(typeof descriptor.get, 'function');116 const {all} = piped;117 assert.ok(all instanceof Readable);118 assert.equal(piped.all, all);119 assert.equal(Object.getOwnPropertyDescriptor(piped, 'all').get, undefined);120 assert.equal(await text(all), simpleFull);121 await piped;122});123124test('The .pipe() return value .readable() can read destination stderr', async () => {125 const piped = pipeDistinctBoth();126127 assert.equal(await text(piped.readable({from: 'stderr'})), `${simpleFull}:stderr`);128 await piped;129});130131test('The .pipe() return value .iterable() can read destination stderr', async () => {132 const piped = pipeDistinctBoth();133 const lines = await Array.fromAsync(piped.iterable({from: 'stderr'}));134135 assert.deepEqual(lines, ['aaa', 'bbb', 'ccc:stderr']);136 await piped;137});138139test('The .pipe() return value has IPC methods', async () => {140 const piped = execa('empty.js').pipe('ipc-send-twice.js', {ipc: true});141 assert.deepEqual(await getPipeMessages(piped), foobarArray);142 const {ipcOutput} = await piped;143 assert.deepEqual(ipcOutput, foobarArray);144});145146test('The .pipe() return value .getEachMessage() can be called twice at the same time', async () => {147 const piped = execa('empty.js').pipe('ipc-send-twice.js', {ipc: true});148149 assert.deepEqual(150 await Promise.all([getPipeMessages(piped), getPipeMessages(piped)]),151 [foobarArray, foobarArray],152 );153154 const {ipcOutput} = await piped;155 assert.deepEqual(ipcOutput, foobarArray);156});157158test('The .pipe() return value .getEachMessage() preserves setup errors', async () => {159 const piped = execa('empty.js').pipe('ipc-send-twice.js', {ipc: true});160161 assertThrows(() => {162 piped.getEachMessage(null);163 }, {instanceOf: TypeError});164165 await piped;166});167168test('The .pipe() return value .getEachMessage() waits for source failure', async () => {169 const piped = execa('fail.js').pipe('ipc-send-twice.js', {ipc: true});170171 await assertRejects(async () => {172 for await (const message of piped.getEachMessage()) {173 assert.ok(foobarArray.includes(message));174 }175 }, {message: /Command failed with exit code 2/});176});177178test('The .pipe() return value .getEachMessage() waits for pipe cancellation', async t => {179 const abortController = new AbortController();180 const source = execa('noop-repeat.js');181 const destination = execa('ipc-send-forever.js', {ipc: true});182 t.after(async () => {183 await cleanupSubprocesses(source, destination);184 });185186 const piped = source.pipe(destination, {unpipeSignal: abortController.signal});187 const iterator = piped.getEachMessage();188 assert.deepEqual(await iterator.next(), {done: false, value: foobarString});189190 const readerPromise = assertRejects(iterator.next(), {message: /Pipe canceled/});191 abortController.abort();192 await assertSettles(readerPromise);193 assert.equal(destination.nodeChildProcess.connected, true);194});195196test('The .pipe() return value .getEachMessage() cancels every pending reader', async t => {197 const abortController = new AbortController();198 const source = execa('noop-repeat.js');199 const destination = execa('ipc-send-forever.js', {ipc: true});200 t.after(async () => {201 await cleanupSubprocesses(source, destination);202 });203204 const piped = source.pipe(destination, {unpipeSignal: abortController.signal});205 const iterators = [206 piped.getEachMessage(),207 piped.getEachMessage(),208 ];209210 assert.deepEqual(211 await Promise.all(iterators.map(async iterator => iterator.next())),212 [213 {done: false, value: foobarString},214 {done: false, value: foobarString},215 ],216 );217218 const readerPromises = iterators.map(iterator => assertRejects(iterator.next(), {message: /Pipe canceled/}));219 abortController.abort();220 await Promise.all(readerPromises.map(async readerPromise => assertSettles(readerPromise)));221});222223const assertCanceledPipeMessageReader = async (t, getReader, shouldAbortBeforePipe = false) => {224 const abortController = new AbortController();225 if (shouldAbortBeforePipe) {226 abortController.abort();227 }228229 const source = execa('noop-repeat.js');230 const destination = execa('ipc-get.js', {ipc: true});231 t.after(async () => {232 await cleanupSubprocesses(source, destination);233 });234235 const piped = source.pipe(destination, {unpipeSignal: abortController.signal});236 const readerPromise = assertRejects(getReader(piped), {message: /Pipe canceled/});237238 if (!shouldAbortBeforePipe) {239 abortController.abort();240 }241242 await assertSettles(readerPromise);243 await assertRejects(piped, {message: /Pipe canceled/});244245 // The destination keeps running after the pipe is canceled, so it must still be able to use IPC246 assert.equal(destination.nodeChildProcess.connected, true);247 await destination.sendMessage(foobarString);248 await destination;249};250251test('The .pipe() return value .getEachMessage() waits for pipe cancellation before IPC messages', async t => {252 await assertCanceledPipeMessageReader(t, piped => piped.getEachMessage().next());253});254255test('The .pipe() return value .getEachMessage() waits for already canceled pipes', async t => {256 await assertCanceledPipeMessageReader(t, piped => piped.getEachMessage().next(), true);257});258259test('The .pipe() return value .getOneMessage() waits for pipe cancellation before IPC messages', async t => {260 await assertCanceledPipeMessageReader(t, piped => piped.getOneMessage());261});262263test('The .pipe() return value .getOneMessage() waits for already canceled pipes', async t => {264 await assertCanceledPipeMessageReader(t, piped => piped.getOneMessage(), true);265});266267test('The .pipe() return value .getEachMessage() waits for the pipe when the iterator is returned', async t => {268 const source = execa('empty.js');269 const destination = execa('ipc-send-forever.js', {ipc: true});270 t.after(async () => {271 await cleanupSubprocesses(source, destination);272 });273274 const piped = source.pipe(destination);275 const iterator = piped.getEachMessage();276277 assert.deepEqual(await iterator.next(), {done: false, value: foobarString});278 const returnPromise = assertRejects(iterator.return());279 destination.kill();280 const error = await returnPromise;281 assert.equal(error.isTerminated, true);282 await Promise.allSettled([source, destination, piped]);283});284285test('The .pipe() return value .getEachMessage() propagates source failure when the iterator is returned', async () => {286 const source = execa('ipc-echo-fail.js', {ipc: true});287 const piped = source.pipe('ipc-send-wait-print.js', {ipc: true});288 const iterator = piped.getEachMessage();289290 assert.deepEqual(await iterator.next(), {done: false, value: foobarString});291 const returnPromise = assertRejects(iterator.return(), {message: /Command failed with exit code 1/});292 await source.sendMessage(foobarString);293 await returnPromise;294});295296test('The .pipe() return value .getEachMessage() propagates destination failure', async () => {297 const piped = execa('empty.js').pipe('ipc-send-fail.js', {ipc: true});298299 await assertRejects(async () => {300 for await (const message of piped.getEachMessage()) {301 assert.equal(message, foobarString);302 }303 }, {message: /Command failed with exit code 1/});304305 const {ipcOutput} = await assertRejects(piped);306 assert.deepEqual(ipcOutput, [foobarString]);307});308309test('The .pipe() return value .getEachMessage() waits for the pipe when the consumer throws', async () => {310 const piped = execa('empty.js').pipe('ipc-send-wait-print.js', {ipc: true});311 const cause = new Error(foobarString);312313 assert.equal(await assertRejects(async () => {314 // eslint-disable-next-line no-unreachable-loop315 for await (const message of piped.getEachMessage()) {316 assert.equal(message, foobarString);317 throw cause;318 }319 }), cause);320321 const {ipcOutput, stdout} = await piped;322 assert.deepEqual(ipcOutput, [foobarString]);323 assert.equal(stdout, '.');324});325326test('The .pipe() return value .getEachMessage() validates IPC immediately', async t => {327 const source = execa('stdin.js');328 const destination = execa('stdin.js');329 t.after(async () => {330 await cleanupSubprocesses(source, destination);331 });332333 const piped = source.pipe(destination);334 const {message} = assertThrows(() => piped.getEachMessage());335336 assert.ok(message.includes('subprocess.getEachMessage() can only be used'));337 source.kill();338 destination.kill();339 await Promise.allSettled([source, destination, piped]);340});341342test('The .pipe() return value can exchange IPC messages', async () => {343 const piped = execa('empty.js').pipe('ipc-echo.js', {ipc: true});344 await piped.sendMessage(foobarString);345 assert.equal(await piped.getOneMessage(), foobarString);346 await piped;347});348349test('A chained .pipe() return value can be iterated', async () => {350 const lines = await Array.fromAsync(execa('noop-fd.js', ['1', simpleFull]).pipe('stdin.js').pipe('stdin.js'));351352 assert.deepEqual(lines, noNewlinesChunks);353});354355test('The .pipe() return value still awaits both subprocesses', async () => {356 await assertRejects(execa('fail.js').pipe('stdin.js'), {message: /Command failed with exit code 2/});357});358359test('The .pipe() return value iteration waits for source failure', async () => {360 const piped = execa('fail.js').pipe('stdin.js');361362 await assertRejects(async () => {363 for await (const line of piped) {364 assert.fail(`Unexpected line: ${line}`);365 }366 }, {message: /Command failed with exit code 2/});367});368369test('The .pipe() return value .readable() waits for source failure', async () => {370 const piped = execa('fail.js').pipe('stdin.js');371372 await assertRejects(text(piped.readable()), {message: /Command failed with exit code 2/});373});374375test('The .pipe() return value .readableStream() waits for source failure', async () => {376 const piped = execa('fail.js').pipe('stdin.js');377378 await assertRejects(text(piped.readableStream()), {message: /Command failed with exit code 2/});379});380381test('The .pipe() return value .all waits for source failure', async () => {382 const piped = execa('fail.js').pipe('stdin.js', {all: true});383384 await assertRejects(text(piped.all), {message: /Command failed with exit code 2/});385});386387// Like `subprocess.all`, `.all` does not need an `error` listener, as long as the pipe is awaited388test('The .pipe() return value .all does not need an error listener on source failure', async () => {389 const piped = execa('fail.js').pipe('stdin.js', {all: true});390 piped.all.resume();391 await assertRejects(piped, {message: /Command failed with exit code 2/});392 await setTimeout(0);393});394395test('The .pipe() return value .all does not need an error listener when piped', async () => {396 const piped = execa('fail.js').pipe('stdin.js', {all: true});397 const chunks = [];398 piped.all.pipe(new Writable({399 write(chunk, encoding, done) {400 chunks.push(chunk);401 done();402 },403 }));404 await assertRejects(piped, {message: /Command failed with exit code 2/});405 await setTimeout(0);406 assert.deepEqual(chunks, []);407});408409const assertCanceledPipeReader = async (t, getReader, shouldAbortBeforePipe = false) => {410 const abortController = new AbortController();411 if (shouldAbortBeforePipe) {412 abortController.abort();413 }414415 const source = execa('stdin.js');416 const destination = execa('stdin.js', {all: true});417 t.after(async () => {418 await cleanupSubprocesses(source, destination);419 });420421 const piped = source.pipe(destination, {unpipeSignal: abortController.signal});422 const readerPromise = assertRejects(getReader(piped), {message: /Pipe canceled/});423424 if (!shouldAbortBeforePipe) {425 abortController.abort();426 }427428 await assertSettles(readerPromise, 200);429};430431test('The .pipe() return value .readable() waits for pipe cancellation', async t => {432 await assertCanceledPipeReader(t, piped => text(piped.readable()));433});434435test('The .pipe() return value .all waits for pipe cancellation', async t => {436 await assertCanceledPipeReader(t, piped => text(piped.all));437});438439test('The .pipe() return value .readable() waits for already canceled pipes', async t => {440 await assertCanceledPipeReader(t, piped => text(piped.readable()), true);441});442443test('The .pipe() return value .all waits for already canceled pipes', async t => {444 await assertCanceledPipeReader(t, piped => text(piped.all), true);445});446447test('Multiple sources piped to one destination each expose the destination methods', async () => {448 const destination = execa('stdin.js');449 const piped = [450 execa('noop-fd.js', ['1', foobarString]).pipe(destination),451 execa('noop-fd.js', ['1', foobarString]).pipe(destination),452 ];453454 for (const pipePromise of piped) {455 assert.equal(typeof pipePromise.iterable, 'function');456 assert.equal(typeof pipePromise[Symbol.asyncIterator], 'function');457 }458459 await Promise.all(piped);460});461462/* eslint-enable node-test/no-conditional-assertion */