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