Skip to content
Myr

methods.js

This file

Path

test/pipe/methods.js

434 lines · 15.0 KiB · JavaScript

Last changed by

TweaksSindre Sorhusbefore adoption698a1b8

History of this file

Take it

1import assert from 'node:assert/strict';2import {setTimeout} from 'node:timers/promises';3import {Readable} 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});194195test('The .pipe() return value .getEachMessage() cancels every pending reader', async t => {196	const abortController = new AbortController();197	const source = execa('noop-repeat.js');198	const destination = execa('ipc-send-forever.js', {ipc: true});199	t.after(async () => {200		await cleanupSubprocesses(source, destination);201	});202203	const piped = source.pipe(destination, {unpipeSignal: abortController.signal});204	const iterators = [205		piped.getEachMessage(),206		piped.getEachMessage(),207	];208209	assert.deepEqual(210		await Promise.all(iterators.map(async iterator => iterator.next())),211		[212			{done: false, value: foobarString},213			{done: false, value: foobarString},214		],215	);216217	const readerPromises = iterators.map(iterator => assertRejects(iterator.next(), {message: /Pipe canceled/}));218	abortController.abort();219	await Promise.all(readerPromises.map(async readerPromise => assertSettles(readerPromise)));220});221222const assertCanceledPipeMessageReader = async (t, getReader, shouldAbortBeforePipe = false) => {223	const abortController = new AbortController();224	if (shouldAbortBeforePipe) {225		abortController.abort();226	}227228	const source = execa('noop-repeat.js');229	const destination = execa('ipc-get.js', {ipc: true});230	t.after(async () => {231		await cleanupSubprocesses(source, destination);232	});233234	const piped = source.pipe(destination, {unpipeSignal: abortController.signal});235	const readerPromise = assertRejects(getReader(piped), {message: /Pipe canceled/});236237	if (!shouldAbortBeforePipe) {238		abortController.abort();239	}240241	await assertSettles(readerPromise);242	await assertRejects(piped, {message: /Pipe canceled/});243};244245test('The .pipe() return value .getEachMessage() waits for pipe cancellation before IPC messages', async t => {246	await assertCanceledPipeMessageReader(t, piped => piped.getEachMessage().next());247});248249test('The .pipe() return value .getEachMessage() waits for already canceled pipes', async t => {250	await assertCanceledPipeMessageReader(t, piped => piped.getEachMessage().next(), true);251});252253test('The .pipe() return value .getOneMessage() waits for pipe cancellation before IPC messages', async t => {254	await assertCanceledPipeMessageReader(t, piped => piped.getOneMessage());255});256257test('The .pipe() return value .getOneMessage() waits for already canceled pipes', async t => {258	await assertCanceledPipeMessageReader(t, piped => piped.getOneMessage(), true);259});260261test('The .pipe() return value .getEachMessage() waits for the pipe when the iterator is returned', async t => {262	const source = execa('empty.js');263	const destination = execa('ipc-send-forever.js', {ipc: true});264	t.after(async () => {265		await cleanupSubprocesses(source, destination);266	});267268	const piped = source.pipe(destination);269	const iterator = piped.getEachMessage();270271	assert.deepEqual(await iterator.next(), {done: false, value: foobarString});272	const returnPromise = assertRejects(iterator.return());273	destination.kill();274	const error = await returnPromise;275	assert.equal(error.isTerminated, true);276	await Promise.allSettled([source, destination, piped]);277});278279test('The .pipe() return value .getEachMessage() propagates source failure when the iterator is returned', async () => {280	const source = execa('ipc-echo-fail.js', {ipc: true});281	const piped = source.pipe('ipc-send-wait-print.js', {ipc: true});282	const iterator = piped.getEachMessage();283284	assert.deepEqual(await iterator.next(), {done: false, value: foobarString});285	const returnPromise = assertRejects(iterator.return(), {message: /Command failed with exit code 1/});286	await source.sendMessage(foobarString);287	await returnPromise;288});289290test('The .pipe() return value .getEachMessage() propagates destination failure', async () => {291	const piped = execa('empty.js').pipe('ipc-send-fail.js', {ipc: true});292293	await assertRejects(async () => {294		for await (const message of piped.getEachMessage()) {295			assert.equal(message, foobarString);296		}297	}, {message: /Command failed with exit code 1/});298299	const {ipcOutput} = await assertRejects(piped);300	assert.deepEqual(ipcOutput, [foobarString]);301});302303test('The .pipe() return value .getEachMessage() waits for the pipe when the consumer throws', async () => {304	const piped = execa('empty.js').pipe('ipc-send-wait-print.js', {ipc: true});305	const cause = new Error(foobarString);306307	assert.equal(await assertRejects(async () => {308		// eslint-disable-next-line no-unreachable-loop309		for await (const message of piped.getEachMessage()) {310			assert.equal(message, foobarString);311			throw cause;312		}313	}), cause);314315	const {ipcOutput, stdout} = await piped;316	assert.deepEqual(ipcOutput, [foobarString]);317	assert.equal(stdout, '.');318});319320test('The .pipe() return value .getEachMessage() validates IPC immediately', async t => {321	const source = execa('stdin.js');322	const destination = execa('stdin.js');323	t.after(async () => {324		await cleanupSubprocesses(source, destination);325	});326327	const piped = source.pipe(destination);328	const {message} = assertThrows(() => piped.getEachMessage());329330	assert.ok(message.includes('subprocess.getEachMessage() can only be used'));331	source.kill();332	destination.kill();333	await Promise.allSettled([source, destination, piped]);334});335336test('The .pipe() return value can exchange IPC messages', async () => {337	const piped = execa('empty.js').pipe('ipc-echo.js', {ipc: true});338	await piped.sendMessage(foobarString);339	assert.equal(await piped.getOneMessage(), foobarString);340	await piped;341});342343test('A chained .pipe() return value can be iterated', async () => {344	const lines = await Array.fromAsync(execa('noop-fd.js', ['1', simpleFull]).pipe('stdin.js').pipe('stdin.js'));345346	assert.deepEqual(lines, noNewlinesChunks);347});348349test('The .pipe() return value still awaits both subprocesses', async () => {350	await assertRejects(execa('fail.js').pipe('stdin.js'), {message: /Command failed with exit code 2/});351});352353test('The .pipe() return value iteration waits for source failure', async () => {354	const piped = execa('fail.js').pipe('stdin.js');355356	await assertRejects(async () => {357		for await (const line of piped) {358			assert.fail(`Unexpected line: ${line}`);359		}360	}, {message: /Command failed with exit code 2/});361});362363test('The .pipe() return value .readable() waits for source failure', async () => {364	const piped = execa('fail.js').pipe('stdin.js');365366	await assertRejects(text(piped.readable()), {message: /Command failed with exit code 2/});367});368369test('The .pipe() return value .readableStream() waits for source failure', async () => {370	const piped = execa('fail.js').pipe('stdin.js');371372	await assertRejects(text(piped.readableStream()), {message: /Command failed with exit code 2/});373});374375test('The .pipe() return value .all waits for source failure', async () => {376	const piped = execa('fail.js').pipe('stdin.js', {all: true});377378	await assertRejects(text(piped.all), {message: /Command failed with exit code 2/});379});380381const assertCanceledPipeReader = async (t, getReader, shouldAbortBeforePipe = false) => {382	const abortController = new AbortController();383	if (shouldAbortBeforePipe) {384		abortController.abort();385	}386387	const source = execa('stdin.js');388	const destination = execa('stdin.js', {all: true});389	t.after(async () => {390		await cleanupSubprocesses(source, destination);391	});392393	const piped = source.pipe(destination, {unpipeSignal: abortController.signal});394	const readerPromise = assertRejects(getReader(piped), {message: /Pipe canceled/});395396	if (!shouldAbortBeforePipe) {397		abortController.abort();398	}399400	await assertSettles(readerPromise, 200);401};402403test('The .pipe() return value .readable() waits for pipe cancellation', async t => {404	await assertCanceledPipeReader(t, piped => text(piped.readable()));405});406407test('The .pipe() return value .all waits for pipe cancellation', async t => {408	await assertCanceledPipeReader(t, piped => text(piped.all));409});410411test('The .pipe() return value .readable() waits for already canceled pipes', async t => {412	await assertCanceledPipeReader(t, piped => text(piped.readable()), true);413});414415test('The .pipe() return value .all waits for already canceled pipes', async t => {416	await assertCanceledPipeReader(t, piped => text(piped.all), true);417});418419test('Multiple sources piped to one destination each expose the destination methods', async () => {420	const destination = execa('stdin.js');421	const piped = [422		execa('noop-fd.js', ['1', foobarString]).pipe(destination),423		execa('noop-fd.js', ['1', foobarString]).pipe(destination),424	];425426	for (const pipePromise of piped) {427		assert.equal(typeof pipePromise.iterable, 'function');428		assert.equal(typeof pipePromise[Symbol.asyncIterator], 'function');429	}430431	await Promise.all(piped);432});433434/* eslint-enable node-test/no-conditional-assertion */