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