Skip to content

Commit e340a66

Browse files
committed
test: add makeDuplexPair() helper
Add a utility for adding simple, streams-API based duplex pairs. PR-URL: #16269 Reviewed-By: Anatoli Papirovski <[email protected]> Reviewed-By: James M Snell <[email protected]>
1 parent 170bc31 commit e340a66

File tree

2 files changed

+54
-0
lines changed

2 files changed

+54
-0
lines changed

test/common/README.md

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ This directory contains modules used to test the Node.js implementation.
88
* [Common module API](#common-module-api)
99
* [Countdown module](#countdown-module)
1010
* [DNS module](#dns-module)
11+
* [Duplex pair helper](#duplex-pair-helper)
1112
* [Fixtures module](#fixtures-module)
1213
* [WPT module](#wpt-module)
1314

@@ -458,6 +459,14 @@ Reads a Domain String and returns a Buffer containing the domain.
458459
Takes in a parsed Object and writes its fields to a DNS packet as a Buffer
459460
object.
460461

462+
## Duplex pair helper
463+
464+
The `common/duplexpair` module exports a single function `makeDuplexPair`,
465+
which returns an object `{ clientSide, serverSide }` where each side is a
466+
`Duplex` stream connected to the other side.
467+
468+
There is no difference between client or server side beyond their names.
469+
461470
## Fixtures Module
462471

463472
The `common/fixtures` module provides convenience methods for working with

test/common/duplexpair.js

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
/* eslint-disable required-modules */
2+
'use strict';
3+
const { Duplex } = require('stream');
4+
const assert = require('assert');
5+
6+
const kCallback = Symbol('Callback');
7+
const kOtherSide = Symbol('Other');
8+
9+
class DuplexSocket extends Duplex {
10+
constructor() {
11+
super();
12+
this[kCallback] = null;
13+
this[kOtherSide] = null;
14+
}
15+
16+
_read() {
17+
const callback = this[kCallback];
18+
if (callback) {
19+
this[kCallback] = null;
20+
callback();
21+
}
22+
}
23+
24+
_write(chunk, encoding, callback) {
25+
assert.notStrictEqual(this[kOtherSide], null);
26+
assert.strictEqual(this[kOtherSide][kCallback], null);
27+
this[kOtherSide][kCallback] = callback;
28+
this[kOtherSide].push(chunk);
29+
}
30+
31+
_final(callback) {
32+
this[kOtherSide].on('end', callback);
33+
this[kOtherSide].push(null);
34+
}
35+
}
36+
37+
function makeDuplexPair() {
38+
const clientSide = new DuplexSocket();
39+
const serverSide = new DuplexSocket();
40+
clientSide[kOtherSide] = serverSide;
41+
serverSide[kOtherSide] = clientSide;
42+
return { clientSide, serverSide };
43+
}
44+
45+
module.exports = makeDuplexPair;

0 commit comments

Comments
 (0)