Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[pull] main from nodejs:main #29

Merged
merged 3 commits into from
Jan 4, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 23 additions & 0 deletions doc/api/test.md
Original file line number Diff line number Diff line change
Expand Up @@ -1750,6 +1750,29 @@ describe('tests', async () => {
});
```

## `assert`

<!-- YAML
added: REPLACEME
-->

An object whose methods are used to configure available assertions on the
`TestContext` objects in the current process. The methods from `node:assert`
and snapshot testing functions are available by default.

It is possible to apply the same configuration to all files by placing common
configuration code in a module
preloaded with `--require` or `--import`.

### `assert.register(name, fn)`

<!-- YAML
added: REPLACEME
-->

Defines a new assertion function with the provided name and function. If an
assertion already exists with the same name, it is overwritten.

## `snapshot`

<!-- YAML
Expand Down
50 changes: 50 additions & 0 deletions lib/internal/test_runner/assert.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
'use strict';
const {
SafeMap,
} = primordials;
const {
validateFunction,
validateString,
} = require('internal/validators');
const assert = require('assert');
const methodsToCopy = [
'deepEqual',
'deepStrictEqual',
'doesNotMatch',
'doesNotReject',
'doesNotThrow',
'equal',
'fail',
'ifError',
'match',
'notDeepEqual',
'notDeepStrictEqual',
'notEqual',
'notStrictEqual',
'partialDeepStrictEqual',
'rejects',
'strictEqual',
'throws',
];
let assertMap;

function getAssertionMap() {
if (assertMap === undefined) {
assertMap = new SafeMap();

for (let i = 0; i < methodsToCopy.length; i++) {
assertMap.set(methodsToCopy[i], assert[methodsToCopy[i]]);
}
}

return assertMap;
}

function register(name, fn) {
validateString(name, 'name');
validateFunction(fn, 'fn');
const map = getAssertionMap();
map.set(name, fn);
}

module.exports = { getAssertionMap, register };
52 changes: 18 additions & 34 deletions lib/internal/test_runner/test.js
Original file line number Diff line number Diff line change
Expand Up @@ -100,34 +100,15 @@ function lazyFindSourceMap(file) {

function lazyAssertObject(harness) {
if (assertObj === undefined) {
assertObj = new SafeMap();
const assert = require('assert');
const { SnapshotManager } = require('internal/test_runner/snapshot');
const methodsToCopy = [
'deepEqual',
'deepStrictEqual',
'doesNotMatch',
'doesNotReject',
'doesNotThrow',
'equal',
'fail',
'ifError',
'match',
'notDeepEqual',
'notDeepStrictEqual',
'notEqual',
'notStrictEqual',
'partialDeepStrictEqual',
'rejects',
'strictEqual',
'throws',
];
for (let i = 0; i < methodsToCopy.length; i++) {
assertObj.set(methodsToCopy[i], assert[methodsToCopy[i]]);
}
const { getAssertionMap } = require('internal/test_runner/assert');

assertObj = getAssertionMap();
if (!assertObj.has('snapshot')) {
const { SnapshotManager } = require('internal/test_runner/snapshot');

harness.snapshotManager = new SnapshotManager(harness.config.updateSnapshots);
assertObj.set('snapshot', harness.snapshotManager.createAssert());
harness.snapshotManager = new SnapshotManager(harness.config.updateSnapshots);
assertObj.set('snapshot', harness.snapshotManager.createAssert());
}
}
return assertObj;
}
Expand Down Expand Up @@ -264,15 +245,18 @@ class TestContext {
};
});

// This is a hack. It allows the innerOk function to collect the stacktrace from the correct starting point.
function ok(...args) {
if (plan !== null) {
plan.actual++;
if (!map.has('ok')) {
// This is a hack. It allows the innerOk function to collect the
// stacktrace from the correct starting point.
function ok(...args) {
if (plan !== null) {
plan.actual++;
}
innerOk(ok, args.length, ...args);
}
innerOk(ok, args.length, ...args);
}

assert.ok = ok;
assert.ok = ok;
}
}
return this.#assert;
}
Expand Down
12 changes: 12 additions & 0 deletions lib/test.js
Original file line number Diff line number Diff line change
Expand Up @@ -61,3 +61,15 @@ ObjectDefineProperty(module.exports, 'snapshot', {
return lazySnapshot;
},
});

ObjectDefineProperty(module.exports, 'assert', {
__proto__: null,
configurable: true,
enumerable: true,
get() {
const { register } = require('internal/test_runner/assert');
const assert = { __proto__: null, register };
ObjectDefineProperty(module.exports, 'assert', assert);
return assert;
},
});
47 changes: 23 additions & 24 deletions test/parallel/test-child-process-windows-hide.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,49 +3,48 @@
const common = require('../common');
const assert = require('assert');
const cp = require('child_process');
const { test } = require('node:test');
const internalCp = require('internal/child_process');
const cmd = process.execPath;
const args = ['-p', '42'];
const options = { windowsHide: true };

// Since windowsHide isn't really observable, monkey patch spawn() and
// spawnSync() to verify that the flag is being passed through correctly.
const originalSpawn = internalCp.ChildProcess.prototype.spawn;
const originalSpawnSync = internalCp.spawnSync;
// Since windowsHide isn't really observable, this test relies on monkey
// patching spawn() and spawnSync() to verify that the flag is being passed
// through correctly.

internalCp.ChildProcess.prototype.spawn = common.mustCall(function(options) {
assert.strictEqual(options.windowsHide, true);
return originalSpawn.apply(this, arguments);
}, 2);

internalCp.spawnSync = common.mustCall(function(options) {
assert.strictEqual(options.windowsHide, true);
return originalSpawnSync.apply(this, arguments);
});

{
test('spawnSync() passes windowsHide correctly', (t) => {
const spy = t.mock.method(internalCp, 'spawnSync');
const child = cp.spawnSync(cmd, args, options);

assert.strictEqual(child.status, 0);
assert.strictEqual(child.signal, null);
assert.strictEqual(child.stdout.toString().trim(), '42');
assert.strictEqual(child.stderr.toString().trim(), '');
}
assert.strictEqual(spy.mock.calls.length, 1);
assert.strictEqual(spy.mock.calls[0].arguments[0].windowsHide, true);
});

{
test('spawn() passes windowsHide correctly', (t, done) => {
const spy = t.mock.method(internalCp.ChildProcess.prototype, 'spawn');
const child = cp.spawn(cmd, args, options);

child.on('exit', common.mustCall((code, signal) => {
assert.strictEqual(code, 0);
assert.strictEqual(signal, null);
assert.strictEqual(spy.mock.calls.length, 1);
assert.strictEqual(spy.mock.calls[0].arguments[0].windowsHide, true);
done();
}));
}
});

{
const callback = common.mustSucceed((stdout, stderr) => {
test('execFile() passes windowsHide correctly', (t, done) => {
const spy = t.mock.method(internalCp.ChildProcess.prototype, 'spawn');
cp.execFile(cmd, args, options, common.mustSucceed((stdout, stderr) => {
assert.strictEqual(stdout.trim(), '42');
assert.strictEqual(stderr.trim(), '');
});

cp.execFile(cmd, args, options, callback);
}
assert.strictEqual(spy.mock.calls.length, 1);
assert.strictEqual(spy.mock.calls[0].arguments[0].windowsHide, true);
done();
}));
});
63 changes: 63 additions & 0 deletions test/parallel/test-runner-custom-assertions.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
'use strict';
require('../common');
const assert = require('node:assert');
const { test, assert: testAssertions } = require('node:test');

testAssertions.register('isOdd', (n) => {
assert.strictEqual(n % 2, 1);
});

testAssertions.register('ok', () => {
return 'ok';
});

testAssertions.register('snapshot', () => {
return 'snapshot';
});

testAssertions.register('deepStrictEqual', () => {
return 'deepStrictEqual';
});

testAssertions.register('context', function() {
return this;
});

test('throws if name is not a string', () => {
assert.throws(() => {
testAssertions.register(5);
}, {
code: 'ERR_INVALID_ARG_TYPE',
message: 'The "name" argument must be of type string. Received type number (5)'
});
});

test('throws if fn is not a function', () => {
assert.throws(() => {
testAssertions.register('foo', 5);
}, {
code: 'ERR_INVALID_ARG_TYPE',
message: 'The "fn" argument must be of type function. Received type number (5)'
});
});

test('invokes a custom assertion as part of the test plan', (t) => {
t.plan(2);
t.assert.isOdd(5);
assert.throws(() => {
t.assert.isOdd(4);
}, {
code: 'ERR_ASSERTION',
message: /Expected values to be strictly equal/
});
});

test('can override existing assertions', (t) => {
assert.strictEqual(t.assert.ok(), 'ok');
assert.strictEqual(t.assert.snapshot(), 'snapshot');
assert.strictEqual(t.assert.deepStrictEqual(), 'deepStrictEqual');
});

test('"this" is set to the TestContext', (t) => {
assert.strictEqual(t.assert.context(), t);
});
37 changes: 8 additions & 29 deletions test/parallel/test-set-http-max-http-headers.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,17 +4,10 @@ const common = require('../common');
const assert = require('assert');
const { spawn } = require('child_process');
const path = require('path');
const { suite, test } = require('node:test');
const testName = path.join(__dirname, 'test-http-max-http-headers.js');

const timeout = common.platformTimeout(100);

const tests = [];

function test(fn) {
tests.push(fn);
}

test(function(cb) {
test(function(_, cb) {
console.log('running subtest expecting failure');

// Validate that the test fails if the max header size is too small.
Expand All @@ -30,7 +23,7 @@ test(function(cb) {
}));
});

test(function(cb) {
test(function(_, cb) {
console.log('running subtest expecting success');

const env = Object.assign({}, process.env, {
Expand All @@ -54,13 +47,13 @@ test(function(cb) {
}));
});

// Next, repeat the same checks using NODE_OPTIONS if it is supported.
if (!process.config.variables.node_without_node_options) {
const skip = process.config.variables.node_without_node_options;
suite('same checks using NODE_OPTIONS if it is supported', { skip }, () => {
const env = Object.assign({}, process.env, {
NODE_OPTIONS: '--max-http-header-size=1024'
});

test(function(cb) {
test(function(_, cb) {
console.log('running subtest expecting failure');

// Validate that the test fails if the max header size is too small.
Expand All @@ -74,7 +67,7 @@ if (!process.config.variables.node_without_node_options) {
}));
});

test(function(cb) {
test(function(_, cb) {
// Validate that the test now passes if the same limit is large enough.
const args = ['--expose-internals', testName, '1024'];
const cp = spawn(process.execPath, args, { env, stdio: 'inherit' });
Expand All @@ -85,18 +78,4 @@ if (!process.config.variables.node_without_node_options) {
cb();
}));
});
}

function runTest() {
const fn = tests.shift();

if (!fn) {
return;
}

fn(() => {
setTimeout(runTest, timeout);
});
}

runTest();
});
Loading