• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# Node.js Core Test Common Modules
2
3This directory contains modules used to test the Node.js implementation.
4
5## Table of Contents
6
7* [ArrayStream module](#arraystream-module)
8* [Benchmark module](#benchmark-module)
9* [Child process module](#child-process-module)
10* [Common module API](#common-module-api)
11* [Countdown module](#countdown-module)
12* [CPU Profiler module](#cpu-profiler-module)
13* [Debugger module](#debugger-module)
14* [DNS module](#dns-module)
15* [Duplex pair helper](#duplex-pair-helper)
16* [Environment variables](#environment-variables)
17* [Fixtures module](#fixtures-module)
18* [Heap dump checker module](#heap-dump-checker-module)
19* [hijackstdio module](#hijackstdio-module)
20* [HTTP2 module](#http2-module)
21* [Internet module](#internet-module)
22* [ongc module](#ongc-module)
23* [Report module](#report-module)
24* [tick module](#tick-module)
25* [tmpdir module](#tmpdir-module)
26* [UDP pair helper](#udp-pair-helper)
27* [WPT module](#wpt-module)
28
29## Benchmark Module
30
31The `benchmark` module is used by tests to run benchmarks.
32
33### `runBenchmark(name, env)`
34
35* `name` [\<string>][<string>] Name of benchmark suite to be run.
36* `env` [\<Object>][<Object>] Environment variables to be applied during the
37  run.
38
39## Child Process Module
40
41The `child_process` module is used by tests that launch child processes.
42
43### `expectSyncExit(child, options)`
44
45Checks if a _synchronous_ child process runs in the way expected. If it does
46not, print the stdout and stderr output from the child process and additional
47information about it to the stderr of the current process before throwing
48and error. This helps gathering more information about test failures
49coming from child processes.
50
51* `child` [\<ChildProcess>][<ChildProcess>]: a `ChildProcess` instance
52  returned by `child_process.spawnSync()`.
53* `options` [\<Object>][<Object>]
54  * `status` [\<number>][<number>] Expected `child.status`
55  * `signal` [\<string>][<string>] | `null` Expected `child.signal`
56  * `stderr` [\<string>][<string>] | [\<RegExp>][<RegExp>] |
57    [\<Function>][<Function>] Optional. If it's a string, check that the output
58    to the stderr of the child process is exactly the same as the string. If
59    it's a regular expression, check that the stderr matches it. If it's a
60    function, invoke it with the stderr output as a string and check
61    that it returns true. The function can just throw errors (e.g. assertion
62    errors) to provide more information if the check fails.
63  * `stdout` [\<string>][<string>] | [\<RegExp>][<RegExp>] |
64    [\<Function>][<Function>] Optional. Similar to `stderr` but for the stdout.
65  * `trim` [\<boolean>][<boolean>] Optional. Whether this method should trim
66    out the whitespace characters when checking `stderr` and `stdout` outputs.
67    Defaults to `false`.
68
69### `expectSyncExitWithoutError(child[, options])`
70
71Similar to `expectSyncExit()` with the `status` expected to be 0 and
72`signal` expected to be `null`. Any other optional options are passed
73into `expectSyncExit()`.
74
75## Common Module API
76
77The `common` module is used by tests for consistency across repeated
78tasks.
79
80### `allowGlobals(...allowlist)`
81
82* `allowlist` [\<Array>][<Array>] Array of Globals
83* return [\<Array>][<Array>]
84
85Takes `allowlist` and concats that with predefined `knownGlobals`.
86
87### `canCreateSymLink()`
88
89* return [\<boolean>][<boolean>]
90
91Checks whether the current running process can create symlinks. On Windows, this
92returns `false` if the process running doesn't have privileges to create
93symlinks
94([SeCreateSymbolicLinkPrivilege](https://msdn.microsoft.com/en-us/library/windows/desktop/bb530716\(v=vs.85\).aspx)).
95On non-Windows platforms, this always returns `true`.
96
97### `createZeroFilledFile(filename)`
98
99Creates a 10 MiB file of all null characters.
100
101### `enoughTestMem`
102
103* [\<boolean>][<boolean>]
104
105Indicates if there is more than 1gb of total memory.
106
107### `expectsError(validator[, exact])`
108
109* `validator` [\<Object>][<Object>] | [\<RegExp>][<RegExp>] |
110  [\<Function>][<Function>] | [\<Error>][<Error>] The validator behaves
111  identical to `assert.throws(fn, validator)`.
112* `exact` [\<number>][<number>] default = 1
113* return [\<Function>][<Function>] A callback function that expects an error.
114
115A function suitable as callback to validate callback based errors. The error is
116validated using `assert.throws(() => { throw error; }, validator)`. If the
117returned function has not been called exactly `exact` number of times when the
118test is complete, then the test will fail.
119
120### `expectWarning(name[, expected[, code]])`
121
122* `name` [\<string>][<string>] | [\<Object>][<Object>]
123* `expected` [\<string>][<string>] | [\<Array>][<Array>] | [\<Object>][<Object>]
124* `code` [\<string>][<string>]
125
126Tests whether `name`, `expected`, and `code` are part of a raised warning.
127
128The code is required in case the name is set to `'DeprecationWarning'`.
129
130Examples:
131
132```js
133const { expectWarning } = require('../common');
134
135expectWarning('Warning', 'Foobar is really bad');
136
137expectWarning('DeprecationWarning', 'Foobar is deprecated', 'DEP0XXX');
138
139expectWarning('DeprecationWarning', [
140  'Foobar is deprecated', 'DEP0XXX',
141]);
142
143expectWarning('DeprecationWarning', [
144  ['Foobar is deprecated', 'DEP0XXX'],
145  ['Baz is also deprecated', 'DEP0XX2'],
146]);
147
148expectWarning('DeprecationWarning', {
149  DEP0XXX: 'Foobar is deprecated',
150  DEP0XX2: 'Baz is also deprecated',
151});
152
153expectWarning({
154  DeprecationWarning: {
155    DEP0XXX: 'Foobar is deprecated',
156    DEP0XX1: 'Baz is also deprecated',
157  },
158  Warning: [
159    ['Multiple array entries are fine', 'SpecialWarningCode'],
160    ['No code is also fine'],
161  ],
162  SingleEntry: ['This will also work', 'WarningCode'],
163  SingleString: 'Single string entries without code will also work',
164});
165```
166
167### `getArrayBufferViews(buf)`
168
169* `buf` [\<Buffer>][<Buffer>]
170* return [\<ArrayBufferView>][<ArrayBufferView>]\[]
171
172Returns an instance of all possible `ArrayBufferView`s of the provided Buffer.
173
174### `getBufferSources(buf)`
175
176* `buf` [\<Buffer>][<Buffer>]
177* return [\<BufferSource>][<BufferSource>]\[]
178
179Returns an instance of all possible `BufferSource`s of the provided Buffer,
180consisting of all `ArrayBufferView` and an `ArrayBuffer`.
181
182### `getCallSite(func)`
183
184* `func` [\<Function>][<Function>]
185* return [\<string>][<string>]
186
187Returns the file name and line number for the provided Function.
188
189### `getTTYfd()`
190
191Attempts to get a valid TTY file descriptor. Returns `-1` if it fails.
192
193The TTY file descriptor is assumed to be capable of being writable.
194
195### `hasCrypto`
196
197* [\<boolean>][<boolean>]
198
199Indicates whether OpenSSL is available.
200
201### `hasFipsCrypto`
202
203* [\<boolean>][<boolean>]
204
205Indicates that Node.js has been linked with a FIPS compatible OpenSSL library,
206and that FIPS as been enabled using `--enable-fips`.
207
208To only detect if the OpenSSL library is FIPS compatible, regardless if it has
209been enabled or not, then `process.config.variables.openssl_is_fips` can be
210used to determine that situation.
211
212### `hasIntl`
213
214* [\<boolean>][<boolean>]
215
216Indicates if [internationalization][] is supported.
217
218### `hasIPv6`
219
220* [\<boolean>][<boolean>]
221
222Indicates whether `IPv6` is supported on this platform.
223
224### `hasMultiLocalhost`
225
226* [\<boolean>][<boolean>]
227
228Indicates if there are multiple localhosts available.
229
230### `inFreeBSDJail`
231
232* [\<boolean>][<boolean>]
233
234Checks whether free BSD Jail is true or false.
235
236### `isAIX`
237
238* [\<boolean>][<boolean>]
239
240Platform check for Advanced Interactive eXecutive (AIX).
241
242### `isAlive(pid)`
243
244* `pid` [\<number>][<number>]
245* return [\<boolean>][<boolean>]
246
247Attempts to 'kill' `pid`
248
249### `isDumbTerminal`
250
251* [\<boolean>][<boolean>]
252
253### `isFreeBSD`
254
255* [\<boolean>][<boolean>]
256
257Platform check for Free BSD.
258
259### `isIBMi`
260
261* [\<boolean>][<boolean>]
262
263Platform check for IBMi.
264
265### `isLinux`
266
267* [\<boolean>][<boolean>]
268
269Platform check for Linux.
270
271### `isLinuxPPCBE`
272
273* [\<boolean>][<boolean>]
274
275Platform check for Linux on PowerPC.
276
277### `isOSX`
278
279* [\<boolean>][<boolean>]
280
281Platform check for macOS.
282
283### `isSunOS`
284
285* [\<boolean>][<boolean>]
286
287Platform check for SunOS.
288
289### `isWindows`
290
291* [\<boolean>][<boolean>]
292
293Platform check for Windows.
294
295### `localhostIPv4`
296
297* [\<string>][<string>]
298
299IP of `localhost`.
300
301### `localIPv6Hosts`
302
303* [\<Array>][<Array>]
304
305Array of IPV6 representations for `localhost`.
306
307### `mustCall([fn][, exact])`
308
309* `fn` [\<Function>][<Function>] default = () => {}
310* `exact` [\<number>][<number>] default = 1
311* return [\<Function>][<Function>]
312
313Returns a function that calls `fn`. If the returned function has not been called
314exactly `exact` number of times when the test is complete, then the test will
315fail.
316
317If `fn` is not provided, an empty function will be used.
318
319### `mustCallAtLeast([fn][, minimum])`
320
321* `fn` [\<Function>][<Function>] default = () => {}
322* `minimum` [\<number>][<number>] default = 1
323* return [\<Function>][<Function>]
324
325Returns a function that calls `fn`. If the returned function has not been called
326at least `minimum` number of times when the test is complete, then the test will
327fail.
328
329If `fn` is not provided, an empty function will be used.
330
331### `mustNotCall([msg])`
332
333* `msg` [\<string>][<string>] default = 'function should not have been called'
334* return [\<Function>][<Function>]
335
336Returns a function that triggers an `AssertionError` if it is invoked. `msg` is
337used as the error message for the `AssertionError`.
338
339### `mustNotMutateObjectDeep([target])`
340
341* `target` [\<any>][<any>] default = `undefined`
342* return [\<any>][<any>]
343
344If `target` is an Object, returns a proxy object that triggers
345an `AssertionError` on mutation attempt, including mutation of deeply nested
346Objects. Otherwise, it returns `target` directly.
347
348Use of this function is encouraged for relevant regression tests.
349
350```mjs
351import { open } from 'node:fs/promises';
352import { mustNotMutateObjectDeep } from '../common/index.mjs';
353
354const _mutableOptions = { length: 4, position: 8 };
355const options = mustNotMutateObjectDeep(_mutableOptions);
356
357// In filehandle.read or filehandle.write, attempt to mutate options will throw
358// In the test code, options can still be mutated via _mutableOptions
359const fh = await open('/path/to/file', 'r+');
360const { buffer } = await fh.read(options);
361_mutableOptions.position = 4;
362await fh.write(buffer, options);
363
364// Inline usage
365const stats = await fh.stat(mustNotMutateObjectDeep({ bigint: true }));
366console.log(stats.size);
367```
368
369Caveats: built-in objects that make use of their internal slots (for example,
370`Map`s and `Set`s) might not work with this function. It returns Functions
371directly, not preventing their mutation.
372
373### `mustSucceed([fn])`
374
375* `fn` [\<Function>][<Function>] default = () => {}
376* return [\<Function>][<Function>]
377
378Returns a function that accepts arguments `(err, ...args)`. If `err` is not
379`undefined` or `null`, it triggers an `AssertionError`. Otherwise, it calls
380`fn(...args)`.
381
382### `nodeProcessAborted(exitCode, signal)`
383
384* `exitCode` [\<number>][<number>]
385* `signal` [\<string>][<string>]
386* return [\<boolean>][<boolean>]
387
388Returns `true` if the exit code `exitCode` and/or signal name `signal` represent
389the exit code and/or signal name of a node process that aborted, `false`
390otherwise.
391
392### `opensslCli`
393
394* [\<boolean>][<boolean>]
395
396Indicates whether 'opensslCli' is supported.
397
398### `platformTimeout(ms)`
399
400* `ms` [\<number>][<number>] | [\<bigint>][<bigint>]
401* return [\<number>][<number>] | [\<bigint>][<bigint>]
402
403Returns a timeout value based on detected conditions. For example, a debug build
404may need extra time so the returned value will be larger than on a release
405build.
406
407### `PIPE`
408
409* [\<string>][<string>]
410
411Path to the test socket.
412
413### `PORT`
414
415* [\<number>][<number>]
416
417A port number for tests to use if one is needed.
418
419### `printSkipMessage(msg)`
420
421* `msg` [\<string>][<string>]
422
423Logs '1..0 # Skipped: ' + `msg`
424
425### `pwdCommand`
426
427* [\<array>][<array>] First two argument for the `spawn`/`exec` functions.
428
429Platform normalized `pwd` command options. Usage example:
430
431```js
432const common = require('../common');
433const { spawn } = require('node:child_process');
434
435spawn(...common.pwdCommand, { stdio: ['pipe'] });
436```
437
438### `requireNoPackageJSONAbove([dir])`
439
440* `dir` [\<string>][<string>] default = \_\_dirname
441
442Throws an `AssertionError` if a `package.json` file exists in any ancestor
443directory above `dir`. Such files may interfere with proper test functionality.
444
445### `runWithInvalidFD(func)`
446
447* `func` [\<Function>][<Function>]
448
449Runs `func` with an invalid file descriptor that is an unsigned integer and
450can be used to trigger `EBADF` as the first argument. If no such file
451descriptor could be generated, a skip message will be printed and the `func`
452will not be run.
453
454### `skip(msg)`
455
456* `msg` [\<string>][<string>]
457
458Logs '1..0 # Skipped: ' + `msg` and exits with exit code `0`.
459
460### `skipIfDumbTerminal()`
461
462Skip the rest of the tests if the current terminal is a dumb terminal
463
464### `skipIfEslintMissing()`
465
466Skip the rest of the tests in the current file when `ESLint` is not available
467at `tools/node_modules/eslint`
468
469### `skipIfInspectorDisabled()`
470
471Skip the rest of the tests in the current file when the Inspector
472was disabled at compile time.
473
474### `skipIf32Bits()`
475
476Skip the rest of the tests in the current file when the Node.js executable
477was compiled with a pointer size smaller than 64 bits.
478
479### `skipIfWorker()`
480
481Skip the rest of the tests in the current file when not running on a main
482thread.
483
484## ArrayStream Module
485
486The `ArrayStream` module provides a simple `Stream` that pushes elements from
487a given array.
488
489<!-- eslint-disable no-undef, node-core/require-common-first, node-core/required-modules -->
490
491```js
492const ArrayStream = require('../common/arraystream');
493const stream = new ArrayStream();
494stream.run(['a', 'b', 'c']);
495```
496
497It can be used within tests as a simple mock stream.
498
499## Countdown Module
500
501The `Countdown` module provides a simple countdown mechanism for tests that
502require a particular action to be taken after a given number of completed
503tasks (for instance, shutting down an HTTP server after a specific number of
504requests). The Countdown will fail the test if the remainder did not reach 0.
505
506<!-- eslint-disable strict, node-core/require-common-first, node-core/required-modules -->
507
508```js
509const Countdown = require('../common/countdown');
510
511function doSomething() {
512  console.log('.');
513}
514
515const countdown = new Countdown(2, doSomething);
516countdown.dec();
517countdown.dec();
518```
519
520### `new Countdown(limit, callback)`
521
522* `limit` {number}
523* `callback` {function}
524
525Creates a new `Countdown` instance.
526
527### `Countdown.prototype.dec()`
528
529Decrements the `Countdown` counter.
530
531### `Countdown.prototype.remaining`
532
533Specifies the remaining number of times `Countdown.prototype.dec()` must be
534called before the callback is invoked.
535
536## CPU Profiler module
537
538The `cpu-prof` module provides utilities related to CPU profiling tests.
539
540### `env`
541
542* Default: { ...process.env, NODE\_DEBUG\_NATIVE: 'INSPECTOR\_PROFILER' }
543
544Environment variables used in profiled processes.
545
546### `getCpuProfiles(dir)`
547
548* `dir` {string} The directory containing the CPU profile files.
549* return [\<string>][<string>]
550
551Returns an array of all `.cpuprofile` files found in `dir`.
552
553### `getFrames(file, suffix)`
554
555* `file` {string} Path to a `.cpuprofile` file.
556* `suffix` {string} Suffix of the URL of call frames to retrieve.
557* returns { frames: [\<Object>][<Object>], nodes: [\<Object>][<Object>] }
558
559Returns an object containing an array of the relevant call frames and an array
560of all the profile nodes.
561
562### `kCpuProfInterval`
563
564Sampling interval in microseconds.
565
566### `verifyFrames(output, file, suffix)`
567
568* `output` {string}
569* `file` {string}
570* `suffix` {string}
571
572Throws an `AssertionError` if there are no call frames with the expected
573`suffix` in the profiling data contained in `file`.
574
575## Debugger module
576
577Provides common functionality for tests for `node inspect`.
578
579### `startCLI(args[[, flags], spawnOpts])`
580
581* `args` [\<string>][<string>]
582* `flags` [\<string>][<string>] default = \[]
583* `showOpts` [\<Object>][<Object>] default = {}
584* return [\<Object>][<Object>]
585
586Returns a null-prototype object with properties that are functions and getters
587used to interact with the `node inspect` CLI. These functions are:
588
589* `flushOutput()`
590* `waitFor()`
591* `waitForPrompt()`
592* `waitForInitialBreak()`
593* `breakInfo`
594* `ctrlC()`
595* `output`
596* `rawOutput`
597* `parseSourceLines()`
598* `writeLine()`
599* `command()`
600* `stepCommand()`
601* `quit()`
602
603## `DNS` Module
604
605The `DNS` module provides utilities related to the `dns` built-in module.
606
607### `errorLookupMock(code, syscall)`
608
609* `code` [\<string>][<string>] Defaults to `dns.mockedErrorCode`.
610* `syscall` [\<string>][<string>] Defaults to `dns.mockedSysCall`.
611* return [\<Function>][<Function>]
612
613A mock for the `lookup` option of `net.connect()` that would result in an error
614with the `code` and the `syscall` specified. Returns a function that has the
615same signature as `dns.lookup()`.
616
617### `mockedErrorCode`
618
619The default `code` of errors generated by `errorLookupMock`.
620
621### `mockedSysCall`
622
623The default `syscall` of errors generated by `errorLookupMock`.
624
625### `readDomainFromPacket(buffer, offset)`
626
627* `buffer` [\<Buffer>][<Buffer>]
628* `offset` [\<number>][<number>]
629* return [\<Object>][<Object>]
630
631Reads the domain string from a packet and returns an object containing the
632number of bytes read and the domain.
633
634### `parseDNSPacket(buffer)`
635
636* `buffer` [\<Buffer>][<Buffer>]
637* return [\<Object>][<Object>]
638
639Parses a DNS packet. Returns an object with the values of the various flags of
640the packet depending on the type of packet.
641
642### `writeIPv6(ip)`
643
644* `ip` [\<string>][<string>]
645* return [\<Buffer>][<Buffer>]
646
647Reads an IPv6 String and returns a Buffer containing the parts.
648
649### `writeDomainName(domain)`
650
651* `domain` [\<string>][<string>]
652* return [\<Buffer>][<Buffer>]
653
654Reads a Domain String and returns a Buffer containing the domain.
655
656### `writeDNSPacket(parsed)`
657
658* `parsed` [\<Object>][<Object>]
659* return [\<Buffer>][<Buffer>]
660
661Takes in a parsed Object and writes its fields to a DNS packet as a Buffer
662object.
663
664## Duplex pair helper
665
666The `common/duplexpair` module exports a single function `makeDuplexPair`,
667which returns an object `{ clientSide, serverSide }` where each side is a
668`Duplex` stream connected to the other side.
669
670There is no difference between client or server side beyond their names.
671
672## Environment variables
673
674The behavior of the Node.js test suite can be altered using the following
675environment variables.
676
677### `NODE_COMMON_PORT`
678
679If set, `NODE_COMMON_PORT`'s value overrides the `common.PORT` default value of
68012346\.
681
682### `NODE_REGENERATE_SNAPSHOTS`
683
684If set, test snapshots for a the current test are regenerated.
685for example `NODE_REGENERATE_SNAPSHOTS=1 out/Release/node test/parallel/test-runner-output.mjs`
686will update all the test runner output snapshots.
687
688### `NODE_SKIP_FLAG_CHECK`
689
690If set, command line arguments passed to individual tests are not validated.
691
692### `NODE_SKIP_CRYPTO`
693
694If set, crypto tests are skipped.
695
696### `NODE_TEST_KNOWN_GLOBALS`
697
698A comma-separated list of variables names that are appended to the global
699variable allowlist. Alternatively, if `NODE_TEST_KNOWN_GLOBALS` is set to `'0'`,
700global leak detection is disabled.
701
702## Fixtures Module
703
704The `common/fixtures` module provides convenience methods for working with
705files in the `test/fixtures` directory.
706
707### `fixtures.fixturesDir`
708
709* [\<string>][<string>]
710
711The absolute path to the `test/fixtures/` directory.
712
713### `fixtures.path(...args)`
714
715* `...args` [\<string>][<string>]
716
717Returns the result of `path.join(fixtures.fixturesDir, ...args)`.
718
719### `fixtures.readSync(args[, enc])`
720
721* `args` [\<string>][<string>] | [\<Array>][<Array>]
722
723Returns the result of
724`fs.readFileSync(path.join(fixtures.fixturesDir, ...args), 'enc')`.
725
726### `fixtures.readKey(arg[, enc])`
727
728* `arg` [\<string>][<string>]
729
730Returns the result of
731`fs.readFileSync(path.join(fixtures.fixturesDir, 'keys', arg), 'enc')`.
732
733## Heap dump checker module
734
735This provides utilities for checking the validity of heap dumps.
736This requires the usage of `--expose-internals`.
737
738### `heap.recordState()`
739
740Create a heap dump and an embedder graph copy for inspection.
741The returned object has a `validateSnapshotNodes` function similar to the
742one listed below. (`heap.validateSnapshotNodes(...)` is a shortcut for
743`heap.recordState().validateSnapshotNodes(...)`.)
744
745### `heap.validateSnapshotNodes(name, expected, options)`
746
747* `name` [\<string>][<string>] Look for this string as the name of heap dump
748  nodes.
749* `expected` [\<Array>][<Array>] A list of objects, possibly with an `children`
750  property that points to expected other adjacent nodes.
751* `options` [\<Array>][<Array>]
752  * `loose` [\<boolean>][<boolean>] Do not expect an exact listing of
753    occurrences of nodes with name `name` in `expected`.
754
755Create a heap dump and an embedder graph copy and validate occurrences.
756
757<!-- eslint-disable no-undef, node-core/require-common-first, node-core/required-modules -->
758
759```js
760validateSnapshotNodes('TLSWRAP', [
761  {
762    children: [
763      { name: 'enc_out' },
764      { name: 'enc_in' },
765      { name: 'TLSWrap' },
766    ],
767  },
768]);
769```
770
771## hijackstdio Module
772
773The `hijackstdio` module provides utility functions for temporarily redirecting
774`stdout` and `stderr` output.
775
776<!-- eslint-disable no-undef, node-core/require-common-first, node-core/required-modules -->
777
778```js
779const { hijackStdout, restoreStdout } = require('../common/hijackstdio');
780
781hijackStdout((data) => {
782  /* Do something with data */
783  restoreStdout();
784});
785
786console.log('this is sent to the hijacked listener');
787```
788
789### `hijackStderr(listener)`
790
791* `listener` [\<Function>][<Function>]: a listener with a single parameter
792  called `data`.
793
794Eavesdrop to `process.stderr.write()` calls. Once `process.stderr.write()` is
795called, `listener` will also be called and the `data` of `write` function will
796be passed to `listener`. What's more, `process.stderr.writeTimes` is a count of
797the number of calls.
798
799### `hijackStdout(listener)`
800
801* `listener` [\<Function>][<Function>]: a listener with a single parameter
802  called `data`.
803
804Eavesdrop to `process.stdout.write()` calls. Once `process.stdout.write()` is
805called, `listener` will also be called and the `data` of `write` function will
806be passed to `listener`. What's more, `process.stdout.writeTimes` is a count of
807the number of calls.
808
809### restoreStderr()
810
811Restore the original `process.stderr.write()`. Used to restore `stderr` to its
812original state after calling [`hijackstdio.hijackStdErr()`][].
813
814### restoreStdout()
815
816Restore the original `process.stdout.write()`. Used to restore `stdout` to its
817original state after calling [`hijackstdio.hijackStdOut()`][].
818
819## HTTP/2 Module
820
821The http2.js module provides a handful of utilities for creating mock HTTP/2
822frames for testing of HTTP/2 endpoints
823
824<!-- eslint-disable no-unused-vars, node-core/require-common-first, node-core/required-modules -->
825
826```js
827const http2 = require('../common/http2');
828```
829
830### Class: Frame
831
832The `http2.Frame` is a base class that creates a `Buffer` containing a
833serialized HTTP/2 frame header.
834
835<!-- eslint-disable no-undef, node-core/require-common-first, node-core/required-modules -->
836
837```js
838// length is a 24-bit unsigned integer
839// type is an 8-bit unsigned integer identifying the frame type
840// flags is an 8-bit unsigned integer containing the flag bits
841// id is the 32-bit stream identifier, if any.
842const frame = new http2.Frame(length, type, flags, id);
843
844// Write the frame data to a socket
845socket.write(frame.data);
846```
847
848The serialized `Buffer` may be retrieved using the `frame.data` property.
849
850### Class: DataFrame extends Frame
851
852The `http2.DataFrame` is a subclass of `http2.Frame` that serializes a `DATA`
853frame.
854
855<!-- eslint-disable no-undef, node-core/require-common-first, node-core/required-modules -->
856
857```js
858// id is the 32-bit stream identifier
859// payload is a Buffer containing the DATA payload
860// padlen is an 8-bit integer giving the number of padding bytes to include
861// final is a boolean indicating whether the End-of-stream flag should be set,
862// defaults to false.
863const frame = new http2.DataFrame(id, payload, padlen, final);
864
865socket.write(frame.data);
866```
867
868### Class: HeadersFrame
869
870The `http2.HeadersFrame` is a subclass of `http2.Frame` that serializes a
871`HEADERS` frame.
872
873<!-- eslint-disable no-undef, node-core/require-common-first, node-core/required-modules -->
874
875```js
876// id is the 32-bit stream identifier
877// payload is a Buffer containing the HEADERS payload (see either
878// http2.kFakeRequestHeaders or http2.kFakeResponseHeaders).
879// padlen is an 8-bit integer giving the number of padding bytes to include
880// final is a boolean indicating whether the End-of-stream flag should be set,
881// defaults to false.
882const frame = new http2.HeadersFrame(id, payload, padlen, final);
883
884socket.write(frame.data);
885```
886
887### Class: SettingsFrame
888
889The `http2.SettingsFrame` is a subclass of `http2.Frame` that serializes an
890empty `SETTINGS` frame.
891
892<!-- eslint-disable no-undef, node-core/require-common-first, node-core/required-modules -->
893
894```js
895// ack is a boolean indicating whether or not to set the ACK flag.
896const frame = new http2.SettingsFrame(ack);
897
898socket.write(frame.data);
899```
900
901### `http2.kFakeRequestHeaders`
902
903Set to a `Buffer` instance that contains a minimal set of serialized HTTP/2
904request headers to be used as the payload of a `http2.HeadersFrame`.
905
906<!-- eslint-disable no-undef, node-core/require-common-first, node-core/required-modules -->
907
908```js
909const frame = new http2.HeadersFrame(1, http2.kFakeRequestHeaders, 0, true);
910
911socket.write(frame.data);
912```
913
914### `http2.kFakeResponseHeaders`
915
916Set to a `Buffer` instance that contains a minimal set of serialized HTTP/2
917response headers to be used as the payload a `http2.HeadersFrame`.
918
919<!-- eslint-disable no-undef, node-core/require-common-first, node-core/required-modules -->
920
921```js
922const frame = new http2.HeadersFrame(1, http2.kFakeResponseHeaders, 0, true);
923
924socket.write(frame.data);
925```
926
927### `http2.kClientMagic`
928
929Set to a `Buffer` containing the preamble bytes an HTTP/2 client must send
930upon initial establishment of a connection.
931
932<!-- eslint-disable no-undef, node-core/require-common-first, node-core/required-modules -->
933
934```js
935socket.write(http2.kClientMagic);
936```
937
938## Internet Module
939
940The `common/internet` module provides utilities for working with
941internet-related tests.
942
943### `internet.addresses`
944
945* [\<Object>][<Object>]
946  * `INET_HOST` [\<string>][<string>] A generic host that has registered common
947    DNS records, supports both IPv4 and IPv6, and provides basic HTTP/HTTPS
948    services
949  * `INET4_HOST` [\<string>][<string>] A host that provides IPv4 services
950  * `INET6_HOST` [\<string>][<string>] A host that provides IPv6 services
951  * `INET4_IP` [\<string>][<string>] An accessible IPv4 IP, defaults to the
952    Google Public DNS IPv4 address
953  * `INET6_IP` [\<string>][<string>] An accessible IPv6 IP, defaults to the
954    Google Public DNS IPv6 address
955  * `INVALID_HOST` [\<string>][<string>] An invalid host that cannot be resolved
956  * `MX_HOST` [\<string>][<string>] A host with MX records registered
957  * `SRV_HOST` [\<string>][<string>] A host with SRV records registered
958  * `PTR_HOST` [\<string>][<string>] A host with PTR records registered
959  * `NAPTR_HOST` [\<string>][<string>] A host with NAPTR records registered
960  * `SOA_HOST` [\<string>][<string>] A host with SOA records registered
961  * `CNAME_HOST` [\<string>][<string>] A host with CNAME records registered
962  * `NS_HOST` [\<string>][<string>] A host with NS records registered
963  * `TXT_HOST` [\<string>][<string>] A host with TXT records registered
964  * `DNS4_SERVER` [\<string>][<string>] An accessible IPv4 DNS server
965  * `DNS6_SERVER` [\<string>][<string>] An accessible IPv6 DNS server
966
967A set of addresses for internet-related tests. All properties are configurable
968via `NODE_TEST_*` environment variables. For example, to configure
969`internet.addresses.INET_HOST`, set the environment
970variable `NODE_TEST_INET_HOST` to a specified host.
971
972## ongc Module
973
974The `ongc` module allows a garbage collection listener to be installed. The
975module exports a single `onGC()` function.
976
977```js
978require('../common');
979const onGC = require('../common/ongc');
980
981onGC({}, { ongc() { console.log('collected'); } });
982```
983
984### `onGC(target, listener)`
985
986* `target` [\<Object>][<Object>]
987* `listener` [\<Object>][<Object>]
988  * `ongc` [\<Function>][<Function>]
989
990Installs a GC listener for the collection of `target`.
991
992This uses `async_hooks` for GC tracking. This means that it enables
993`async_hooks` tracking, which may affect the test functionality. It also
994means that between a `global.gc()` call and the listener being invoked
995a full `setImmediate()` invocation passes.
996
997`listener` is an object to make it easier to use a closure; the target object
998should not be in scope when `listener.ongc()` is created.
999
1000## Report Module
1001
1002The `report` module provides helper functions for testing diagnostic reporting
1003functionality.
1004
1005### `findReports(pid, dir)`
1006
1007* `pid` [\<number>][<number>] Process ID to retrieve diagnostic report files
1008  for.
1009* `dir` [\<string>][<string>] Directory to search for diagnostic report files.
1010* return [\<Array>][<Array>]
1011
1012Returns an array of diagnostic report file names found in `dir`. The files
1013should have been generated by a process whose PID matches `pid`.
1014
1015### `validate(filepath)`
1016
1017* `filepath` [\<string>][<string>] Diagnostic report filepath to validate.
1018
1019Validates the schema of a diagnostic report file whose path is specified in
1020`filepath`. If the report fails validation, an exception is thrown.
1021
1022### `validateContent(report)`
1023
1024* `report` [\<Object>][<Object>] | [\<string>][<string>] JSON contents of a
1025  diagnostic report file, the parsed Object thereof, or the result of
1026  `process.report.getReport()`.
1027
1028Validates the schema of a diagnostic report whose content is specified in
1029`report`. If the report fails validation, an exception is thrown.
1030
1031## tick Module
1032
1033The `tick` module provides a helper function that can be used to call a callback
1034after a given number of event loop "ticks".
1035
1036### `tick(x, cb)`
1037
1038* `x` [\<number>][<number>] Number of event loop "ticks".
1039* `cb` [\<Function>][<Function>] A callback function.
1040
1041## tmpdir Module
1042
1043The `tmpdir` module supports the use of a temporary directory for testing.
1044
1045### `path`
1046
1047* [\<string>][<string>]
1048
1049The realpath of the testing temporary directory.
1050
1051### `fileURL([...paths])`
1052
1053* `...paths` [\<string>][<string>]
1054* return [\<URL>][<URL>]
1055
1056Resolves a sequence of paths into absolute url in the temporary directory.
1057
1058When called without arguments, returns absolute url of the testing
1059temporary directory with explicit trailing `/`.
1060
1061### `refresh()`
1062
1063Deletes and recreates the testing temporary directory.
1064
1065The first time `refresh()` runs, it adds a listener to process `'exit'` that
1066cleans the temporary directory. Thus, every file under `tmpdir.path` needs to
1067be closed before the test completes. A good way to do this is to add a
1068listener to process `'beforeExit'`. If a file needs to be left open until
1069Node.js completes, use a child process and call `refresh()` only in the
1070parent.
1071
1072It is usually only necessary to call `refresh()` once in a test file.
1073Avoid calling it more than once in an asynchronous context as one call
1074might refresh the temporary directory of a different context, causing
1075the test to fail somewhat mysteriously.
1076
1077### `resolve([...paths])`
1078
1079* `...paths` [\<string>][<string>]
1080* return [\<string>][<string>]
1081
1082Resolves a sequence of paths into absolute path in the temporary directory.
1083
1084### `hasEnoughSpace(size)`
1085
1086* `size` [\<number>][<number>] Required size, in bytes.
1087
1088Returns `true` if the available blocks of the file system underlying `path`
1089are likely sufficient to hold a single file of `size` bytes. This is useful for
1090skipping tests that require hundreds of megabytes or even gigabytes of temporary
1091files, but it is inaccurate and susceptible to race conditions.
1092
1093## UDP pair helper
1094
1095The `common/udppair` module exports a function `makeUDPPair` and a class
1096`FakeUDPWrap`.
1097
1098`FakeUDPWrap` emits `'send'` events when data is to be sent on it, and provides
1099an `emitReceived()` API for actin as if data has been received on it.
1100
1101`makeUDPPair` returns an object `{ clientSide, serverSide }` where each side
1102is an `FakeUDPWrap` connected to the other side.
1103
1104There is no difference between client or server side beyond their names.
1105
1106## WPT Module
1107
1108### `harness`
1109
1110A legacy port of [Web Platform Tests][] harness.
1111
1112See the source code for definitions. Please avoid using it in new
1113code - the current usage of this port in tests is being migrated to
1114the original WPT harness, see [the WPT tests README][].
1115
1116### Class: WPTRunner
1117
1118A driver class for running WPT with the WPT harness in a worker thread.
1119
1120See [the WPT tests README][] for details.
1121
1122[<Array>]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array
1123[<ArrayBufferView>]: https://developer.mozilla.org/en-US/docs/Web/API/ArrayBufferView
1124[<Buffer>]: https://nodejs.org/api/buffer.html#buffer_class_buffer
1125[<BufferSource>]: https://developer.mozilla.org/en-US/docs/Web/API/BufferSource
1126[<ChildProcess>]: ../../doc/api/child_process.md#class-childprocess
1127[<Error>]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error
1128[<Function>]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function
1129[<Object>]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object
1130[<RegExp>]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp
1131[<URL>]: https://developer.mozilla.org/en-US/docs/Web/API/URL
1132[<any>]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types
1133[<bigint>]: https://github.com/tc39/proposal-bigint
1134[<boolean>]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type
1135[<number>]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type
1136[<string>]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type
1137[Web Platform Tests]: https://github.com/web-platform-tests/wpt
1138[`hijackstdio.hijackStdErr()`]: #hijackstderrlistener
1139[`hijackstdio.hijackStdOut()`]: #hijackstdoutlistener
1140[internationalization]: ../../doc/api/intl.md
1141[the WPT tests README]: ../wpt/README.md
1142