test_runner: add tags option and tag-name filter

Adds a `tags` option to test(), it(), suite(), and describe() that
accepts an array of string labels. Tags are canonicalized to lowercase
and inherited from suites to nested tests by union. Reporter events
expose the tag set on every test, and TestContext exposes the test's
tags via `context.tags`.

Filtering is done by literal tag name through the new
`--experimental-test-tag-filter=<tag>` flag (or `testTagFilters` on
run()). The flag may be specified more than once; tests must contain
every filter to run. Untagged tests are excluded under any positive
filter.

The tagging mechanism is gated behind a one-shot ExperimentalWarning.

Signed-off-by: atlowChemi <chemi@atlow.co.il>
PR-URL: https://github.com/nodejs/node/pull/63221
Reviewed-By: Moshe Atlow <moshe@atlow.co.il>
Reviewed-By: Pietro Marchini <pietro.marchini94@gmail.com>
Reviewed-By: Aviv Keller <me@aviv.sh>
This commit is contained in:
Chemi Atlow authored and Antoine du Hamel committed 2026-07-30 13:51:48 +02:00
1 parent e8c3db1364
commit d03d96889b
17 files changed
+981 -16

No files matched your search

+2
View File
@@ -47,6 +47,7 @@ function createTestTree(rootTestOptions, globalOptions) {
globalOptions.testSkipPatterns;
const isFilteringByOnly = (globalOptions.isolation === 'process' || process.env.NODE_TEST_CONTEXT) ?
globalOptions.only : true;
const isFilteringByTags = globalOptions.testTagFilters != null;
const harness = {
__proto__: null,
buildPromise: buildPhaseDeferred.promise,
@@ -76,6 +77,7 @@ function createTestTree(rootTestOptions, globalOptions) {
previousRuns: null,
isFilteringByName,
isFilteringByOnly,
isFilteringByTags,
async runBootstrap() {
if (globalSetupExecuted) {
return PromiseResolve();
+31
View File
@@ -67,6 +67,7 @@ const { getInspectPort, isUsingInspector, isInspectorMessage } = require('intern
const { isRegExp } = require('internal/util/types');
const { pathToFileURL } = require('internal/url');
const {
emitExperimentalWarning,
kEmptyObject,
} = require('internal/util');
const { kEmitMessage } = require('internal/test_runner/tests_stream');
@@ -91,6 +92,9 @@ const {
kDefaultPattern,
parseCommandLine,
} = require('internal/test_runner/utils');
const {
validateAndCanonicalizeTagFilter,
} = require('internal/test_runner/tag_filter');
const { Glob } = require('internal/fs/glob');
const { once } = require('events');
const { validatePath } = require('internal/fs/utils');
@@ -112,6 +116,7 @@ const kFilterArgs = [
'--experimental-default-config-file',
];
const kFilterArgValues = [
'--experimental-test-tag-filter',
'--test-reporter',
'--test-reporter-destination',
'--test-random-seed',
@@ -173,6 +178,7 @@ function getRunArgs(path, { forceExit,
inspectPort,
testNamePatterns,
testSkipPatterns,
testTagFilterExpressions,
only,
hasFiles,
testFiles,
@@ -214,6 +220,9 @@ function getRunArgs(path, { forceExit,
if (testSkipPatterns != null) {
ArrayPrototypeForEach(testSkipPatterns, (pattern) => ArrayPrototypePush(runArgs, `--test-skip-pattern=${pattern}`));
}
if (testTagFilterExpressions != null) {
ArrayPrototypeForEach(testTagFilterExpressions, (value) => ArrayPrototypePush(runArgs, `--experimental-test-tag-filter=${value}`));
}
if (only === true) {
ArrayPrototypePush(runArgs, '--test-only');
}
@@ -687,6 +696,7 @@ function run(options = kEmptyObject) {
let {
testNamePatterns,
testSkipPatterns,
testTagFilters,
shard,
coverageExcludeGlobs,
coverageIncludeGlobs,
@@ -844,6 +854,24 @@ function run(options = kEmptyObject) {
throw new ERR_INVALID_ARG_TYPE(name, ['string', 'RegExp'], value);
});
}
let testTagFilterExpressions = null;
if (testTagFilters != null) {
if (!ArrayIsArray(testTagFilters)) {
testTagFilters = [testTagFilters];
}
if (testTagFilters.length === 0) {
testTagFilters = null;
} else {
emitExperimentalWarning('Test tags');
testTagFilters = ArrayPrototypeMap(testTagFilters, (value, i) => (
validateAndCanonicalizeTagFilter(value, `options.testTagFilters[${i}]`)
));
testTagFilterExpressions = testTagFilters;
}
}
testTagFilterExpressions ??= options.testTagFilterExpressions;
validateOneOf(isolation, 'options.isolation', ['process', 'none']);
validateBoolean(coverage, 'options.coverage');
if (coverageExcludeGlobs != null) {
@@ -897,6 +925,7 @@ function run(options = kEmptyObject) {
globalSetupPath,
randomize,
randomSeed,
testTagFilters,
};
const root = createTestTree(rootTestOptions, globalOptions);
@@ -941,6 +970,8 @@ function run(options = kEmptyObject) {
inspectPort,
testNamePatterns,
testSkipPatterns,
testTagFilters,
testTagFilterExpressions,
hasFiles: files != null,
globPatterns,
only,
+117
View File
@@ -0,0 +1,117 @@
'use strict';
const {
ArrayPrototypePush,
ObjectFreeze,
SafeSet,
StringPrototypeToLowerCase,
} = primordials;
const {
codes: {
ERR_INVALID_ARG_VALUE,
},
} = require('internal/errors');
const {
emitExperimentalWarning,
} = require('internal/util');
const {
validateArray,
validateString,
} = require('internal/validators');
const kEmptyTagArray = ObjectFreeze([]);
/**
* Validate and canonicalize a `tags` option value supplied to `test()`,
* `it()`, `suite()`, or `describe()`.
*
* Each tag must be a non-empty string. Tags are canonicalized to lowercase
* and deduplicated, preserving first-seen declaration order.
*
* Calling this with a non-empty array also emits the one-shot
* `ExperimentalWarning` for the test-tags feature.
* @param {unknown} tags - The value supplied by the user for `options.tags`.
* @param {string} optName - Option name to embed in thrown error messages
* (typically `'options.tags'`).
* @returns {string[]} Lowercased, deduplicated tags in declaration order.
* Returns an empty array when `tags` is `[]`.
* @throws {ERR_INVALID_ARG_TYPE} If `tags` is not an array, or any element
* is not a string.
* @throws {ERR_INVALID_ARG_VALUE} If any element is empty.
*/
function validateAndCanonicalizeTagValues(tags, optName) {
validateArray(tags, optName);
if (tags.length === 0) {
return kEmptyTagArray;
}
emitExperimentalWarning('Test tags');
const seen = new SafeSet();
const result = [];
for (let i = 0; i < tags.length; i++) {
const tag = tags[i];
const elemName = `${optName}[${i}]`;
const lower = validateAndCanonicalizeTagFilter(tag, elemName);
if (!seen.has(lower)) {
seen.add(lower);
ArrayPrototypePush(result, lower);
}
}
return ObjectFreeze(result);
}
/**
* Validate and canonicalize a single tag-filter string supplied via
* `--experimental-test-tag-filter` or `testTagFilters`.
*
* Filters are literal tag names: a test passes the filter when its tag set
* contains the lowercased filter value. Multi-occurrence composes by AND
* at the call site (see `evaluateTagFilters`).
* @param {unknown} value - The supplied filter string.
* @param {string} name - Argument name embedded in thrown error messages.
* @returns {string} The lowercased filter value.
* @throws {ERR_INVALID_ARG_TYPE} If `value` is not a string.
* @throws {ERR_INVALID_ARG_VALUE} If `value` is empty.
*/
function validateAndCanonicalizeTagFilter(value, name) {
validateString(value, name);
if (value.length === 0) {
throw new ERR_INVALID_ARG_VALUE(name, value, 'must not be empty');
}
return StringPrototypeToLowerCase(value);
}
/**
* Evaluate a list of tag filters against a test's tag set.
*
* Multiple filters compose by AND: a test passes only when every filter is
* present in its tag set. An empty `filters` array always passes. Untagged
* tests have an empty tag set and so are excluded under any non-empty
* filter.
* @param {string[]} filters - Lowercased canonical filter values.
* @param {SafeSet<string>} tags - The test's lowercased canonical tag set.
* @returns {boolean} `true` if the test should run.
*/
function evaluateTagFilters(filters, tags) {
for (let i = 0; i < filters.length; i++) {
if (!tags.has(filters[i])) {
return false;
}
}
return true;
}
module.exports = {
evaluateTagFilters,
kEmptyTagArray,
validateAndCanonicalizeTagFilter,
validateAndCanonicalizeTagValues,
};
+58 -9
View File
@@ -1,5 +1,6 @@
'use strict';
const {
ArrayFrom,
ArrayPrototypeEvery,
ArrayPrototypePush,
ArrayPrototypePushApply,
@@ -17,6 +18,7 @@ const {
MathRound,
Number,
NumberPrototypeToFixed,
ObjectFreeze,
ObjectKeys,
ObjectSeal,
Promise,
@@ -30,6 +32,7 @@ const {
SafePromiseAllReturnVoid,
SafePromiseRace,
SafeSet,
SetPrototypeUnion,
StringPrototypeStartsWith,
StringPrototypeTrim,
Symbol,
@@ -50,6 +53,11 @@ const {
},
} = require('internal/errors');
const { MockTracker } = require('internal/test_runner/mock/mock');
const {
evaluateTagFilters,
kEmptyTagArray,
validateAndCanonicalizeTagValues,
} = require('internal/test_runner/tag_filter');
const { TestsStream } = require('internal/test_runner/tests_stream');
const {
createDeferredCallback,
@@ -294,6 +302,10 @@ class TestContext {
return this.#test.attempt ?? 0;
}
get tags() {
return this.#test.tags;
}
get workerId() {
const envWorkerId = process.env.NODE_TEST_WORKER_ID;
return Number(envWorkerId) || undefined;
@@ -551,12 +563,14 @@ class Test extends AsyncResource {
abortController;
outerSignal;
#reportedSubtest;
#tagsArray = null;
constructor(options) {
super('Test');
let { fn, name, parent } = options;
const { concurrency, entryFile, expectFailure, loc, only, timeout, todo, skip, signal, plan } = options;
const rawTags = options.tags;
if (typeof fn !== 'function') {
fn = noop;
@@ -577,8 +591,19 @@ class Test extends AsyncResource {
this.diagnostics = [];
this.filtered = false;
this.filteredByName = false;
this.filteredByTag = false;
this.hasOnlyTests = false;
// Hooks pass no tags option, so rawTags is undefined for them.
const ownTags = rawTags !== undefined ?
validateAndCanonicalizeTagValues(rawTags, 'options.tags') :
kEmptyTagArray;
const ownTagSet = new SafeSet(ownTags);
this.tagSet = parent !== null && parent.tagSet.size > 0 ?
SetPrototypeUnion(parent.tagSet, ownTagSet) :
ownTagSet;
if (parent === null) {
this.root = this;
this.harness = options.harness;
@@ -597,7 +622,7 @@ class Test extends AsyncResource {
} else {
const nesting = parent.parent === null ? parent.nesting :
parent.nesting + 1;
const { config, isFilteringByName, isFilteringByOnly } = parent.root.harness;
const { config, isFilteringByName, isFilteringByOnly, isFilteringByTags } = parent.root.harness;
this.root = parent.root;
this.harness = null;
@@ -621,6 +646,15 @@ class Test extends AsyncResource {
}
}
if (isFilteringByTags) {
this.filteredByTag = !evaluateTagFilters(config.testTagFilters, this.tagSet);
if (!this.filteredByTag) {
for (let t = this.parent; t !== null && t.filteredByTag; t = t.parent) {
t.filteredByTag = false;
}
}
}
if (isFilteringByOnly) {
if (this.only) {
// If filtering impacts the tests within a suite, then the suite only
@@ -804,6 +838,16 @@ class Test extends AsyncResource {
}
}
get tags() {
if (this.#tagsArray !== null) {
return this.#tagsArray;
}
this.#tagsArray = this.tagSet.size === 0 ?
kEmptyTagArray :
ObjectFreeze(ArrayFrom(this.tagSet));
return this.#tagsArray;
}
applyFilters() {
if (this.error) {
// Never filter out errors.
@@ -820,8 +864,13 @@ class Test extends AsyncResource {
this.parent.hasOnlyTests ||
this.only === false) {
this.filtered = true;
return;
}
}
if (this.filteredByTag) {
this.filtered = true;
}
}
willBeFilteredByName() {
@@ -907,7 +956,7 @@ class Test extends AsyncResource {
const deferred = this.dequeuePendingSubtest();
const test = deferred.test;
this.assignReportOrder(test);
test.reporter.dequeue(test.nesting, test.loc, test.name, this.reportedType, test.testId);
test.reporter.dequeue(test.nesting, test.loc, test.name, this.reportedType, test.testId, test.tags);
await test.run();
deferred.resolve();
}
@@ -1164,7 +1213,7 @@ class Test extends AsyncResource {
// it. Otherwise, return a Promise to the caller and mark the test as
// pending for later execution.
this.parent.unfinishedSubtests.add(this);
this.reporter.enqueue(this.nesting, this.loc, this.name, this.reportedType, this.testId);
this.reporter.enqueue(this.nesting, this.loc, this.name, this.reportedType, this.testId, this.tags);
if (this.root.harness.buildPromise || !this.parent.hasConcurrency()) {
const deferred = PromiseWithResolvers();
@@ -1187,7 +1236,7 @@ class Test extends AsyncResource {
}
this.parent.assignReportOrder(this);
this.reporter.dequeue(this.nesting, this.loc, this.name, this.reportedType, this.testId);
this.reporter.dequeue(this.nesting, this.loc, this.name, this.reportedType, this.testId, this.tags);
return this.run();
}
@@ -1455,7 +1504,7 @@ class Test extends AsyncResource {
this.testNumber ||= ++this.parent.outputSubtestCount;
this.reporter.complete(
this.nesting, this.loc, this.testNumber, this.name,
report.details, report.directive, this.testId,
report.details, report.directive, this.testId, this.tags,
);
this.parent.activeSubtests--;
}
@@ -1611,12 +1660,12 @@ class Test extends AsyncResource {
if (this.passed) {
this.reporter.ok(
this.nesting, this.loc, this.testNumber, this.name,
report.details, report.directive, this.testId,
report.details, report.directive, this.testId, this.tags,
);
} else {
this.reporter.fail(
this.nesting, this.loc, this.testNumber, this.name,
report.details, report.directive, this.testId,
report.details, report.directive, this.testId, this.tags,
);
}
@@ -1631,7 +1680,7 @@ class Test extends AsyncResource {
}
this.#reportedSubtest = true;
this.parent.reportStarted();
this.reporter.start(this.nesting, this.loc, this.name, this.testId);
this.reporter.start(this.nesting, this.loc, this.name, this.testId, this.tags);
}
clearExecutionTime() {
@@ -1688,7 +1737,7 @@ class TestHook extends Test {
__proto__: null,
duration_ms: this.duration(),
error,
}, undefined);
}, undefined, undefined, parent.tags);
}
}
}
+13 -6
View File
@@ -2,6 +2,7 @@
const {
ArrayPrototypePush,
ArrayPrototypeShift,
ArrayPrototypeSlice,
NumberMAX_SAFE_INTEGER,
Symbol,
} = primordials;
@@ -34,7 +35,7 @@ class TestsStream extends Readable {
}
}
fail(nesting, loc, testNumber, name, details, directive, testId) {
fail(nesting, loc, testNumber, name, details, directive, testId, tags) {
this[kEmitMessage]('test:fail', {
__proto__: null,
name,
@@ -42,12 +43,13 @@ class TestsStream extends Readable {
testNumber,
testId,
details,
tags: ArrayPrototypeSlice(tags),
...loc,
...directive,
});
}
ok(nesting, loc, testNumber, name, details, directive, testId) {
ok(nesting, loc, testNumber, name, details, directive, testId, tags) {
this[kEmitMessage]('test:pass', {
__proto__: null,
name,
@@ -55,12 +57,13 @@ class TestsStream extends Readable {
testNumber,
testId,
details,
tags: ArrayPrototypeSlice(tags),
...loc,
...directive,
});
}
complete(nesting, loc, testNumber, name, details, directive, testId) {
complete(nesting, loc, testNumber, name, details, directive, testId, tags) {
this[kEmitMessage]('test:complete', {
__proto__: null,
name,
@@ -68,6 +71,7 @@ class TestsStream extends Readable {
testNumber,
testId,
details,
tags: ArrayPrototypeSlice(tags),
...loc,
...directive,
});
@@ -94,34 +98,37 @@ class TestsStream extends Readable {
return { __proto__: null, expectFailure: expectation ?? true };
}
enqueue(nesting, loc, name, type, testId) {
enqueue(nesting, loc, name, type, testId, tags) {
this[kEmitMessage]('test:enqueue', {
__proto__: null,
nesting,
name,
type,
testId,
tags: ArrayPrototypeSlice(tags),
...loc,
});
}
dequeue(nesting, loc, name, type, testId) {
dequeue(nesting, loc, name, type, testId, tags) {
this[kEmitMessage]('test:dequeue', {
__proto__: null,
nesting,
name,
type,
testId,
tags: ArrayPrototypeSlice(tags),
...loc,
});
}
start(nesting, loc, name, testId) {
start(nesting, loc, name, testId, tags) {
this[kEmitMessage]('test:start', {
__proto__: null,
nesting,
name,
testId,
tags: ArrayPrototypeSlice(tags),
...loc,
});
}
+36 -1
View File
@@ -29,6 +29,10 @@ const {
StringPrototypeSplit,
} = primordials;
const {
validateAndCanonicalizeTagFilter,
} = require('internal/test_runner/tag_filter');
const { AsyncResource } = require('async_hooks');
const { tracingChannel } = require('diagnostics_channel');
const { relative, sep, resolve } = require('path');
@@ -51,7 +55,7 @@ const {
validateUint32,
} = require('internal/validators');
const { validatePath } = require('internal/fs/utils');
const { kEmptyObject } = require('internal/util');
const { emitExperimentalWarning, kEmptyObject } = require('internal/util');
const coverageColors = {
__proto__: null,
@@ -267,6 +271,8 @@ function parseCommandLine() {
let shard;
let testNamePatterns = mapPatternFlagToRegExArray('--test-name-pattern');
let testSkipPatterns = mapPatternFlagToRegExArray('--test-skip-pattern');
let testTagFilters = null;
let testTagFilterExpressions = null;
if (isChildProcessV8) {
kBuiltinReporters.set('v8-serializer', 'internal/test_runner/reporter/v8-serializer');
@@ -299,6 +305,24 @@ function parseCommandLine() {
if (isTestRunner) {
isolation = getOptionValue('--test-isolation');
const tagFilterFlag = getOptionValue('--experimental-test-tag-filter');
if (tagFilterFlag?.length > 0) {
emitExperimentalWarning('Test tags');
testTagFilterExpressions = tagFilterFlag;
// Validate at parent startup so a malformed flag fails fast,
// independent of isolation mode. Under isolation='process' the
// validated strings go unused at the parent (children re-validate
// and apply the filter); the validation here only surfaces input
// errors early.
const validated = ArrayPrototypeMap(
tagFilterFlag,
(value, i) => validateAndCanonicalizeTagFilter(value, `--experimental-test-tag-filter[${i}]`),
);
if (isolation === 'none') {
testTagFilters = validated;
}
}
if (isolation === 'none') {
concurrency = 1;
} else {
@@ -337,6 +361,15 @@ function parseCommandLine() {
const testSkipPatternFlag = getOptionValue('--test-skip-pattern');
testSkipPatterns = testSkipPatternFlag?.length > 0 ?
ArrayPrototypeMap(testSkipPatternFlag, (re) => convertStringToRegExp(re, '--test-skip-pattern')) : null;
const tagFilterFlag = getOptionValue('--experimental-test-tag-filter');
if (tagFilterFlag?.length > 0) {
emitExperimentalWarning('Test tags');
testTagFilterExpressions = tagFilterFlag;
testTagFilters = ArrayPrototypeMap(
tagFilterFlag,
(value, i) => validateAndCanonicalizeTagFilter(value, `--experimental-test-tag-filter[${i}]`),
);
}
}
if (coverage) {
@@ -398,6 +431,8 @@ function parseCommandLine() {
sourceMaps,
testNamePatterns,
testSkipPatterns,
testTagFilterExpressions,
testTagFilters,
timeout,
updateSnapshots,
watch,