Skip to content

Commit

Permalink
test: lazily load modules on test runner
Browse files Browse the repository at this point in the history
  • Loading branch information
anonrig committed Feb 9, 2025
1 parent a2aa6ca commit a099ba0
Show file tree
Hide file tree
Showing 13 changed files with 71 additions and 60 deletions.
13 changes: 7 additions & 6 deletions test/common/child_process.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,14 @@

const assert = require('assert');
const { spawnSync, execFileSync } = require('child_process');
const common = require('./');
const util = require('util');
const { platformTimeout, isWindows } = require('./');
let inspect;

// Workaround for Windows Server 2008R2
// When CMD is used to launch a process and CMD is killed too quickly, the
// process can stay behind running in suspended state, never completing.
function cleanupStaleProcess(filename) {
if (!common.isWindows) {
if (!isWindows) {
return;
}
process.once('beforeExit', () => {
Expand All @@ -30,7 +30,7 @@ function cleanupStaleProcess(filename) {

// This should keep the child process running long enough to expire
// the timeout.
const kExpiringChildRunTime = common.platformTimeout(20 * 1000);
const kExpiringChildRunTime = platformTimeout(20 * 1000);
const kExpiringParentTimer = 1;
assert(kExpiringChildRunTime > kExpiringParentTimer);

Expand All @@ -43,17 +43,18 @@ function logAfterTime(time) {
}

function checkOutput(str, check) {
inspect ??= require('util').inspect;
if ((check instanceof RegExp && !check.test(str)) ||
(typeof check === 'string' && check !== str)) {
return { passed: false, reason: `did not match ${util.inspect(check)}` };
return { passed: false, reason: `did not match ${inspect(check)}` };
}
if (typeof check === 'function') {
try {
check(str);
} catch (error) {
return {
passed: false,
reason: `did not match expectation, checker throws:\n${util.inspect(error)}`,
reason: `did not match expectation, checker throws:\n${inspect(error)}`,
};
}
}
Expand Down
11 changes: 5 additions & 6 deletions test/common/crypto.js
Original file line number Diff line number Diff line change
@@ -1,20 +1,19 @@
'use strict';

const common = require('../common');
if (!common.hasCrypto) {
common.skip('missing crypto');
const { hasCrypto, skip } = require('../common');
if (!hasCrypto) {
skip('missing crypto');
}

const assert = require('assert');
const crypto = require('crypto');
const {
createSign,
createVerify,
publicEncrypt,
privateDecrypt,
sign,
verify,
} = crypto;
} = require('crypto');

Check failure on line 16 in test/common/crypto.js

View workflow job for this annotation

GitHub Actions / lint-js-and-md

Please add a hasCrypto check to allow this test to be skipped when Node is built "--without-ssl"

// The values below (modp2/modp2buf) are for a 1024 bits long prime from
// RFC 2412 E.2, see https://tools.ietf.org/html/rfc2412. */
Expand Down Expand Up @@ -109,7 +108,7 @@ const opensslVersionNumber = (major = 0, minor = 0, patch = 0) => {

let OPENSSL_VERSION_NUMBER;
const hasOpenSSL = (major = 0, minor = 0, patch = 0) => {
if (!common.hasCrypto) return false;
if (!hasCrypto) return false;
if (OPENSSL_VERSION_NUMBER === undefined) {
const regexp = /(?<m>\d+)\.(?<n>\d+)\.(?<p>\d+)/;
const { m, n, p } = process.versions.openssl.match(regexp).groups;
Expand Down
10 changes: 5 additions & 5 deletions test/common/debugger.js
Original file line number Diff line number Diff line change
@@ -1,18 +1,18 @@
'use strict';
const common = require('../common');
const spawn = require('child_process').spawn;
const { isWindows, platformTimeout } = require('../common');
const { spawn } = require('child_process');

const BREAK_MESSAGE = new RegExp('(?:' + [
'assert', 'break', 'break on start', 'debugCommand',
'exception', 'other', 'promiseRejection', 'step',
].join('|') + ') in', 'i');

let TIMEOUT = common.platformTimeout(5000);
if (common.isWindows) {
let TIMEOUT = platformTimeout(5000);
if (isWindows) {
// Some of the windows machines in the CI need more time to receive
// the outputs from the client.
// https://github.com/nodejs/build/issues/3014
TIMEOUT = common.platformTimeout(15000);
TIMEOUT = platformTimeout(15000);
}

function isPreBreak(output) {
Expand Down
9 changes: 6 additions & 3 deletions test/common/dns.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
'use strict';

const assert = require('assert');
const os = require('os');
const { isIP } = require('net');
let endianness;
let isIP;

const types = {
A: 1,
Expand Down Expand Up @@ -284,11 +284,13 @@ function writeDNSPacket(parsed) {
}
}

endianness ??= require('os').endianness();

return Buffer.concat(buffers.map((typedArray) => {
const buf = Buffer.from(typedArray.buffer,
typedArray.byteOffset,
typedArray.byteLength);
if (os.endianness() === 'LE') {
if (endianness === 'LE') {
if (typedArray.BYTES_PER_ELEMENT === 2) buf.swap16();
if (typedArray.BYTES_PER_ELEMENT === 4) buf.swap32();
}
Expand All @@ -311,6 +313,7 @@ function errorLookupMock(code = mockedErrorCode, syscall = mockedSysCall) {
}

function createMockedLookup(...addresses) {
isIP ??= require('net').isIP;
addresses = addresses.map((address) => ({ address: address, family: isIP(address) }));

// Create a DNS server which replies with a AAAA and a A record for the same host
Expand Down
10 changes: 5 additions & 5 deletions test/common/heap.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
'use strict';
const assert = require('assert');
const util = require('util');
const { inspect } = require('util');

let _buildEmbedderGraph;
function buildEmbedderGraph() {
Expand Down Expand Up @@ -91,7 +91,7 @@ function readHeapInfo(raw, fields, types, strings) {
}

function inspectNode(snapshot) {
return util.inspect(snapshot, { depth: 4 });
return inspect(snapshot, { depth: 4 });
}

function isEdge(edge, { node_name, edge_name }) {
Expand Down Expand Up @@ -144,7 +144,7 @@ class State {
if (!hasChild) {
throw new Error(
'expected to find child ' +
`${util.inspect(expectedEdge)} in ${inspectNode(rootNodes)}`);
`${inspect(expectedEdge)} in ${inspectNode(rootNodes)}`);
}
}
}
Expand Down Expand Up @@ -196,7 +196,7 @@ class State {
if (!hasChild) {
throw new Error(
'expected to find child ' +
`${util.inspect(expectedEdge)} in ${inspectNode(rootNodes)}`);
`${inspect(expectedEdge)} in ${inspectNode(rootNodes)}`);
}
}
}
Expand Down Expand Up @@ -269,7 +269,7 @@ function findByRetainingPath(rootName, retainingPath) {
}

if (newHaystack.length === 0) {
const format = (val) => util.inspect(val, { breakLength: 128, depth: 3 });
const format = (val) => inspect(val, { breakLength: 128, depth: 3 });
console.error('#');
console.error('# Retaining path to search for:');
for (let j = 0; j < retainingPath.length; ++j) {
Expand Down
9 changes: 6 additions & 3 deletions test/common/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,10 @@ const process = globalThis.process; // Some tests tamper with the process globa

const assert = require('assert');
const fs = require('fs');
const net = require('net');
const {
getDefaultAutoSelectFamilyAttemptTimeout,
setDefaultAutoSelectFamilyAttemptTimeout,
} = require('net');
// Do not require 'os' until needed so that test-os-checked-function can
// monkey patch it. If 'os' is required here, that test will fail.
const path = require('path');
Expand Down Expand Up @@ -139,8 +142,8 @@ const isPi = (() => {
})();

// When using high concurrency or in the CI we need much more time for each connection attempt
net.setDefaultAutoSelectFamilyAttemptTimeout(platformTimeout(net.getDefaultAutoSelectFamilyAttemptTimeout() * 10));
const defaultAutoSelectFamilyAttemptTimeout = net.getDefaultAutoSelectFamilyAttemptTimeout();
const defaultAutoSelectFamilyAttemptTimeout = platformTimeout(getDefaultAutoSelectFamilyAttemptTimeout() * 10)

Check failure on line 145 in test/common/index.js

View workflow job for this annotation

GitHub Actions / lint-js-and-md

Missing semicolon
setDefaultAutoSelectFamilyAttemptTimeout(defaultAutoSelectFamilyAttemptTimeout);

const buildType = process.config.target_defaults ?
process.config.target_defaults.default_configuration :
Expand Down
2 changes: 1 addition & 1 deletion test/common/inspector-helper.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ const fs = require('fs');
const http = require('http');
const fixtures = require('../common/fixtures');
const { spawn } = require('child_process');
const { URL, pathToFileURL } = require('url');
const { pathToFileURL } = require('url');
const { EventEmitter, once } = require('events');

const _MAINSCRIPT = fixtures.path('loop.js');
Expand Down
5 changes: 3 additions & 2 deletions test/common/measure-memory.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
'use strict';

const assert = require('assert');
const common = require('./');
let expectWarning;

// The formats could change when V8 is updated, then the tests should be
// updated accordingly.
Expand Down Expand Up @@ -43,7 +43,8 @@ function assertSingleDetailedShape(result) {
}

function expectExperimentalWarning() {
common.expectWarning(
expectWarning ??= require('./').expectWarning;
expectWarning(
'ExperimentalWarning',
'vm.measureMemory is an experimental feature and might change at any time',
);
Expand Down
6 changes: 3 additions & 3 deletions test/common/net.js
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
'use strict';
const net = require('net');

const options = { port: 0, reusePort: true };
let createServer;

function checkSupportReusePort() {
createServer ??= require('net').createServer;
return new Promise((resolve, reject) => {
const server = net.createServer().listen(options);
const server = createServer().listen(options);
server.on('listening', () => {
server.close(resolve);
});
Expand Down
4 changes: 2 additions & 2 deletions test/common/tls.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,11 @@

'use strict';
const crypto = require('crypto');
const net = require('net');
const { Socket } = require('net');

exports.ccs = Buffer.from('140303000101', 'hex');

class TestTLSSocket extends net.Socket {
class TestTLSSocket extends Socket {
constructor(server_cert) {
super();
this.server_cert = server_cert;
Expand Down
24 changes: 12 additions & 12 deletions test/common/udp.js
Original file line number Diff line number Diff line change
@@ -1,21 +1,21 @@
'use strict';
const dgram = require('dgram');
const { createSocket } = require('dgram');

const options = { type: 'udp4', reusePort: true };

function checkSupportReusePort() {
return new Promise((resolve, reject) => {
const socket = dgram.createSocket(options);
socket.bind(0);
socket.on('listening', () => {
socket.close(resolve);
});
socket.on('error', (err) => {
console.log('The `reusePort` option is not supported:', err.message);
socket.close();
reject(err);
});
const { promise, resolve, reject } = Promise.withResolvers();
const socket = createSocket(options);
socket.bind(0);
socket.on('listening', () => {
socket.close(resolve);
});
socket.on('error', (err) => {
console.log('The `reusePort` option is not supported:', err.message);
socket.close();
reject(err);
});
return promise;
}

module.exports = {
Expand Down
17 changes: 9 additions & 8 deletions test/common/v8.js
Original file line number Diff line number Diff line change
@@ -1,15 +1,16 @@
'use strict';
const assert = require('assert');
const { GCProfiler } = require('v8');
let GCProfiler;

function collectGCProfile({ duration }) {
return new Promise((resolve) => {
const profiler = new GCProfiler();
profiler.start();
setTimeout(() => {
resolve(profiler.stop());
}, duration);
});
GCProfiler ??= require('v8').GCProfiler;
const { promise, resolve } = Promise.withResolvers();
const profiler = new GCProfiler();
profiler.start();
setTimeout(() => {
resolve(profiler.stop());
}, duration);
return promise;
}

function checkGCProfile(data) {
Expand Down
11 changes: 7 additions & 4 deletions test/common/wpt.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,12 +6,14 @@ const fs = require('fs');
const fsPromises = fs.promises;
const path = require('path');
const events = require('events');
const os = require('os');
const { inspect } = require('util');
const { Worker } = require('worker_threads');

const workerPath = path.join(__dirname, 'wpt/worker.js');

let availableParallelism;

Check failure on line 14 in test/common/wpt.js

View workflow job for this annotation

GitHub Actions / lint-js-and-md

'availableParallelism' is defined but never used
let osType;

function getBrowserProperties() {
const { node: version } = process.versions; // e.g. 18.13.0, 20.0.0-nightly202302078e6e215481
const release = /^\d+\.\d+\.\d+$/.test(version);
Expand All @@ -28,7 +30,8 @@ function getBrowserProperties() {
* https://github.com/web-platform-tests/wpt/blob/1c6ff12/tools/wptrunner/wptrunner/tests/test_update.py#L953-L958
*/
function getOs() {
switch (os.type()) {
osType ??= require('os').type();
switch (osType) {
case 'Linux':
return 'linux';
case 'Darwin':
Expand Down Expand Up @@ -512,10 +515,10 @@ const limit = (concurrency) => {
};

class WPTRunner {
constructor(path, { concurrency = os.availableParallelism() - 1 || 1 } = {}) {
constructor(path, { concurrency } = {}) {
this.path = path;
this.resource = new ResourceLoader(path);
this.concurrency = concurrency;
this.concurrency = concurrency ?? (require('os').availableParallelism() - 1 || 1);

this.flags = [];
this.globalThisInitScripts = [];
Expand Down

0 comments on commit a099ba0

Please sign in to comment.