Skip to content

Commit 7f2d3d0

Browse files
jasnelltargos
authored andcommitted
test: move hijackstdio out of require('common')
Move the hijackstdio functions out of common so that they are imported only into the tests that actually need them PR-URL: #22462 Reviewed-By: Ruben Bridgewater <[email protected]> Reviewed-By: Refael Ackermann <[email protected]> Reviewed-By: Trivikram Kamat <[email protected]> Reviewed-By: Luigi Pinca <[email protected]>
1 parent 1eac11f commit 7f2d3d0

13 files changed

+146
-96
lines changed

test/common/README.md

+48-30
Original file line numberDiff line numberDiff line change
@@ -173,24 +173,6 @@ Indicates whether `IPv6` is supported on this platform.
173173

174174
Indicates if there are multiple localhosts available.
175175

176-
### hijackStderr(listener)
177-
* `listener` [&lt;Function>]: a listener with a single parameter
178-
called `data`.
179-
180-
Eavesdrop to `process.stderr.write` calls. Once `process.stderr.write` is
181-
called, `listener` will also be called and the `data` of `write` function will
182-
be passed to `listener`. What's more, `process.stderr.writeTimes` is a count of
183-
the number of calls.
184-
185-
### hijackStdout(listener)
186-
* `listener` [&lt;Function>]: a listener with a single parameter
187-
called `data`.
188-
189-
Eavesdrop to `process.stdout.write` calls. Once `process.stdout.write` is
190-
called, `listener` will also be called and the `data` of `write` function will
191-
be passed to `listener`. What's more, `process.stdout.writeTimes` is a count of
192-
the number of calls.
193-
194176
### inFreeBSDJail
195177
* [&lt;boolean>]
196178

@@ -355,16 +337,6 @@ A port number for tests to use if one is needed.
355337

356338
Logs '1..0 # Skipped: ' + `msg`
357339

358-
### restoreStderr()
359-
360-
Restore the original `process.stderr.write`. Used to restore `stderr` to its
361-
original state after calling [`common.hijackStdErr()`][].
362-
363-
### restoreStdout()
364-
365-
Restore the original `process.stdout.write`. Used to restore `stdout` to its
366-
original state after calling [`common.hijackStdOut()`][].
367-
368340
### rootDir
369341
* [&lt;string>]
370342

@@ -596,6 +568,52 @@ validateSnapshotNodes('TLSWRAP', [
596568
]);
597569
```
598570

571+
## hijackstdio Module
572+
573+
The `hijackstdio` module provides utility functions for temporarily redirecting
574+
`stdout` and `stderr` output.
575+
576+
<!-- eslint-disable no-undef, node-core/required-modules -->
577+
```js
578+
const { hijackStdout, restoreStdout } = require('../common/hijackstdio');
579+
580+
hijackStdout((data) => {
581+
/* Do something with data */
582+
restoreStdout();
583+
});
584+
585+
console.log('this is sent to the hijacked listener');
586+
```
587+
588+
### hijackStderr(listener)
589+
* `listener` [&lt;Function>]: a listener with a single parameter
590+
called `data`.
591+
592+
Eavesdrop to `process.stderr.write()` calls. Once `process.stderr.write()` is
593+
called, `listener` will also be called and the `data` of `write` function will
594+
be passed to `listener`. What's more, `process.stderr.writeTimes` is a count of
595+
the number of calls.
596+
597+
### hijackStdout(listener)
598+
* `listener` [&lt;Function>]: a listener with a single parameter
599+
called `data`.
600+
601+
Eavesdrop to `process.stdout.write()` calls. Once `process.stdout.write()` is
602+
called, `listener` will also be called and the `data` of `write` function will
603+
be passed to `listener`. What's more, `process.stdout.writeTimes` is a count of
604+
the number of calls.
605+
606+
### restoreStderr()
607+
608+
Restore the original `process.stderr.write()`. Used to restore `stderr` to its
609+
original state after calling [`hijackstdio.hijackStdErr()`][].
610+
611+
### restoreStdout()
612+
613+
Restore the original `process.stdout.write()`. Used to restore `stdout` to its
614+
original state after calling [`hijackstdio.hijackStdOut()`][].
615+
616+
599617
## HTTP/2 Module
600618

601619
The http2.js module provides a handful of utilities for creating mock HTTP/2
@@ -773,6 +791,6 @@ implementation with tests from
773791
[&lt;boolean>]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type
774792
[&lt;number>]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type
775793
[&lt;string>]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type
776-
[`common.hijackStdErr()`]: #hijackstderrlistener
777-
[`common.hijackStdOut()`]: #hijackstdoutlistener
794+
[`hijackstdio.hijackStdErr()`]: #hijackstderrlistener
795+
[`hijackstdio.hijackStdOut()`]: #hijackstdoutlistener
778796
[internationalization]: https://github.com/nodejs/node/wiki/Intl

test/common/hijackstdio.js

+33
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
/* eslint-disable node-core/required-modules */
2+
'use strict';
3+
4+
// Hijack stdout and stderr
5+
const stdWrite = {};
6+
function hijackStdWritable(name, listener) {
7+
const stream = process[name];
8+
const _write = stdWrite[name] = stream.write;
9+
10+
stream.writeTimes = 0;
11+
stream.write = function(data, callback) {
12+
try {
13+
listener(data);
14+
} catch (e) {
15+
process.nextTick(() => { throw e; });
16+
}
17+
18+
_write.call(stream, data, callback);
19+
stream.writeTimes++;
20+
};
21+
}
22+
23+
function restoreWritable(name) {
24+
process[name].write = stdWrite[name];
25+
delete process[name].writeTimes;
26+
}
27+
28+
module.exports = {
29+
hijackStdout: hijackStdWritable.bind(null, 'stdout'),
30+
hijackStderr: hijackStdWritable.bind(null, 'stderr'),
31+
restoreStdout: restoreWritable.bind(null, 'stdout'),
32+
restoreStderr: restoreWritable.bind(null, 'stderr')
33+
};

test/common/index.js

-28
Original file line numberDiff line numberDiff line change
@@ -787,30 +787,6 @@ exports.getTTYfd = function getTTYfd() {
787787
return ttyFd;
788788
};
789789

790-
// Hijack stdout and stderr
791-
const stdWrite = {};
792-
function hijackStdWritable(name, listener) {
793-
const stream = process[name];
794-
const _write = stdWrite[name] = stream.write;
795-
796-
stream.writeTimes = 0;
797-
stream.write = function(data, callback) {
798-
try {
799-
listener(data);
800-
} catch (e) {
801-
process.nextTick(() => { throw e; });
802-
}
803-
804-
_write.call(stream, data, callback);
805-
stream.writeTimes++;
806-
};
807-
}
808-
809-
function restoreWritable(name) {
810-
process[name].write = stdWrite[name];
811-
delete process[name].writeTimes;
812-
}
813-
814790
exports.runWithInvalidFD = function(func) {
815791
let fd = 1 << 30;
816792
// Get first known bad file descriptor. 1 << 30 is usually unlikely to
@@ -824,10 +800,6 @@ exports.runWithInvalidFD = function(func) {
824800
exports.printSkipMessage('Could not generate an invalid fd');
825801
};
826802

827-
exports.hijackStdout = hijackStdWritable.bind(null, 'stdout');
828-
exports.hijackStderr = hijackStdWritable.bind(null, 'stderr');
829-
exports.restoreStdout = restoreWritable.bind(null, 'stdout');
830-
exports.restoreStderr = restoreWritable.bind(null, 'stderr');
831803
exports.isCPPSymbolsNotMapped = exports.isWindows ||
832804
exports.isSunOS ||
833805
exports.isAIX ||

test/common/index.mjs

-8
Original file line numberDiff line numberDiff line change
@@ -52,10 +52,6 @@ const {
5252
disableCrashOnUnhandledRejection,
5353
getTTYfd,
5454
runWithInvalidFD,
55-
hijackStdout,
56-
hijackStderr,
57-
restoreStdout,
58-
restoreStderr,
5955
isCPPSymbolsNotMapped
6056
} = common;
6157

@@ -109,9 +105,5 @@ export {
109105
disableCrashOnUnhandledRejection,
110106
getTTYfd,
111107
runWithInvalidFD,
112-
hijackStdout,
113-
hijackStderr,
114-
restoreStdout,
115-
restoreStderr,
116108
isCPPSymbolsNotMapped
117109
};

test/parallel/test-common.js

+5-4
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@
2121

2222
'use strict';
2323
const common = require('../common');
24+
const hijackstdio = require('../common/hijackstdio');
2425
const fixtures = require('../common/fixtures');
2526
const assert = require('assert');
2627
const { execFile } = require('child_process');
@@ -95,7 +96,7 @@ const HIJACK_TEST_ARRAY = [ 'foo\n', 'bar\n', 'baz\n' ];
9596
const stream = process[`std${txt}`];
9697
const originalWrite = stream.write;
9798

98-
common[`hijackStd${txt}`](common.mustCall(function(data) {
99+
hijackstdio[`hijackStd${txt}`](common.mustCall(function(data) {
99100
assert.strictEqual(data, HIJACK_TEST_ARRAY[stream.writeTimes]);
100101
}, HIJACK_TEST_ARRAY.length));
101102
assert.notStrictEqual(originalWrite, stream.write);
@@ -105,22 +106,22 @@ const HIJACK_TEST_ARRAY = [ 'foo\n', 'bar\n', 'baz\n' ];
105106
});
106107

107108
assert.strictEqual(HIJACK_TEST_ARRAY.length, stream.writeTimes);
108-
common[`restoreStd${txt}`]();
109+
hijackstdio[`restoreStd${txt}`]();
109110
assert.strictEqual(originalWrite, stream.write);
110111
});
111112

112113
// hijackStderr and hijackStdout again
113114
// for console
114115
[[ 'err', 'error' ], [ 'out', 'log' ]].forEach(([ type, method ]) => {
115-
common[`hijackStd${type}`](common.mustCall(function(data) {
116+
hijackstdio[`hijackStd${type}`](common.mustCall(function(data) {
116117
assert.strictEqual(data, 'test\n');
117118

118119
// throw an error
119120
throw new Error(`console ${type} error`);
120121
}));
121122

122123
console[method]('test');
123-
common[`restoreStd${type}`]();
124+
hijackstdio[`restoreStd${type}`]();
124125
});
125126

126127
let uncaughtTimes = 0;

test/parallel/test-console-group.js

+11-5
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,11 @@
11
'use strict';
2-
const common = require('../common');
2+
require('../common');
3+
const {
4+
hijackStdout,
5+
hijackStderr,
6+
restoreStdout,
7+
restoreStderr
8+
} = require('../common/hijackstdio');
39

410
const assert = require('assert');
511
const Console = require('console').Console;
@@ -8,21 +14,21 @@ let c, stdout, stderr;
814

915
function setup() {
1016
stdout = '';
11-
common.hijackStdout(function(data) {
17+
hijackStdout(function(data) {
1218
stdout += data;
1319
});
1420

1521
stderr = '';
16-
common.hijackStderr(function(data) {
22+
hijackStderr(function(data) {
1723
stderr += data;
1824
});
1925

2026
c = new Console(process.stdout, process.stderr);
2127
}
2228

2329
function teardown() {
24-
common.restoreStdout();
25-
common.restoreStderr();
30+
restoreStdout();
31+
restoreStderr();
2632
}
2733

2834
// Basic group() functionality

test/parallel/test-console.js

+13-6
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,13 @@ const common = require('../common');
2424
const assert = require('assert');
2525
const util = require('util');
2626

27+
const {
28+
hijackStdout,
29+
hijackStderr,
30+
restoreStdout,
31+
restoreStderr
32+
} = require('../common/hijackstdio');
33+
2734
assert.ok(process.stdout.writable);
2835
assert.ok(process.stderr.writable);
2936
// Support legacy API
@@ -60,11 +67,11 @@ const custom_inspect = { foo: 'bar', [util.inspect.custom]: () => 'inspect' };
6067
const strings = [];
6168
const errStrings = [];
6269
process.stdout.isTTY = false;
63-
common.hijackStdout(function(data) {
70+
hijackStdout(function(data) {
6471
strings.push(data);
6572
});
6673
process.stderr.isTTY = false;
67-
common.hijackStderr(function(data) {
74+
hijackStderr(function(data) {
6875
errStrings.push(data);
6976
});
7077

@@ -163,8 +170,8 @@ console.assert(true, 'this should not throw');
163170

164171
assert.strictEqual(strings.length, process.stdout.writeTimes);
165172
assert.strictEqual(errStrings.length, process.stderr.writeTimes);
166-
common.restoreStdout();
167-
common.restoreStderr();
173+
restoreStdout();
174+
restoreStderr();
168175

169176
// verify that console.timeEnd() doesn't leave dead links
170177
const timesMapSize = console._times.size;
@@ -234,8 +241,8 @@ assert.strictEqual(errStrings.shift().split('\n').shift(),
234241

235242
// hijack stderr to catch `process.emitWarning` which is using
236243
// `process.nextTick`
237-
common.hijackStderr(common.mustCall(function(data) {
238-
common.restoreStderr();
244+
hijackStderr(common.mustCall(function(data) {
245+
restoreStderr();
239246

240247
// stderr.write will catch sync error, so use `process.nextTick` here
241248
process.nextTick(function() {

test/parallel/test-internal-errors.js

+8-5
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,10 @@
11
// Flags: --expose-internals
22
'use strict';
33
const common = require('../common');
4-
4+
const {
5+
hijackStdout,
6+
restoreStdout,
7+
} = require('../common/hijackstdio');
58
const assert = require('assert');
69
const errors = require('internal/errors');
710

@@ -246,22 +249,22 @@ assert.strictEqual(
246249
// browser. Note that `message` remains non-enumerable after being assigned.
247250
{
248251
let initialConsoleLog = '';
249-
common.hijackStdout((data) => { initialConsoleLog += data; });
252+
hijackStdout((data) => { initialConsoleLog += data; });
250253
const myError = new errors.codes.ERR_TLS_HANDSHAKE_TIMEOUT();
251254
assert.deepStrictEqual(Object.keys(myError), []);
252255
const initialToString = myError.toString();
253256
console.log(myError);
254257
assert.notStrictEqual(initialConsoleLog, '');
255258

256-
common.restoreStdout();
259+
restoreStdout();
257260

258261
let subsequentConsoleLog = '';
259-
common.hijackStdout((data) => { subsequentConsoleLog += data; });
262+
hijackStdout((data) => { subsequentConsoleLog += data; });
260263
myError.message = 'Fhqwhgads';
261264
assert.deepStrictEqual(Object.keys(myError), []);
262265
assert.notStrictEqual(myError.toString(), initialToString);
263266
console.log(myError);
264267
assert.strictEqual(subsequentConsoleLog, initialConsoleLog);
265268

266-
common.restoreStdout();
269+
restoreStdout();
267270
}

test/parallel/test-process-raw-debug.js

+2-1
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@
2121

2222
'use strict';
2323
const common = require('../common');
24+
const { hijackStderr } = require('../common/hijackstdio');
2425
const assert = require('assert');
2526
const os = require('os');
2627

@@ -63,7 +64,7 @@ function child() {
6364
throw new Error('No ticking!');
6465
};
6566

66-
common.hijackStderr(common.mustNotCall('stderr.write must not be called.'));
67+
hijackStderr(common.mustNotCall('stderr.write must not be called.'));
6768

6869
process._rawDebug('I can still %s!', 'debug');
6970
}

0 commit comments

Comments
 (0)