mirror of
https://github.com/nodejs/node.git
synced 2026-11-24 21:50:36 -05:00
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:
1 parent
e8c3db1364
commit
d03d96889b
17 files changed
+981
-16
No files matched your search
@@ -1237,6 +1237,23 @@ Enable module mocking in the test runner.
|
||||
|
||||
This feature requires `--allow-worker` if used with the [Permission Model][].
|
||||
|
||||
### `--experimental-test-tag-filter=<tag>`
|
||||
|
||||
<!-- YAML
|
||||
added: REPLACEME
|
||||
-->
|
||||
|
||||
> Stability: 1.0 - Early development
|
||||
|
||||
Run only tests whose tag set contains `<tag>`. Tests declare tags via the
|
||||
`tags` option on `test()`, `it()`, `suite()`, or `describe()`; tags
|
||||
inherit from suites to nested tests by union. Filtering is
|
||||
case-insensitive.
|
||||
|
||||
The flag may be specified more than once; tests must contain **every**
|
||||
filter value to run. See [Test tags][] for details on declaring and
|
||||
inheriting tags.
|
||||
|
||||
### `--experimental-transform-types`
|
||||
|
||||
<!-- YAML
|
||||
@@ -4140,6 +4157,7 @@ node --stack-trace-limit=12 -p -e "Error.stackTraceLimit" # prints 12
|
||||
[ScriptCoverage]: https://chromedevtools.github.io/devtools-protocol/tot/Profiler#type-ScriptCoverage
|
||||
[ShadowRealm]: https://github.com/tc39/proposal-shadowrealm
|
||||
[Source Map]: https://tc39.es/ecma426/
|
||||
[Test tags]: test.md#test-tags
|
||||
[TypeScript type-stripping]: typescript.md#type-stripping
|
||||
[V8 Inspector integration for Node.js]: debugger.md#v8-inspector-integration-for-nodejs
|
||||
[V8 JavaScript code coverage]: https://v8project.blogspot.com/2017/12/javascript-code-coverage.html
|
||||
|
||||
+134
@@ -478,6 +478,82 @@ Test name patterns do not change the set of files that the test runner executes.
|
||||
If both `--test-name-pattern` and `--test-skip-pattern` are supplied,
|
||||
tests must satisfy **both** requirements in order to be executed.
|
||||
|
||||
## Test tags
|
||||
|
||||
<!-- YAML
|
||||
added: REPLACEME
|
||||
-->
|
||||
|
||||
> Stability: 1.0 - Early development
|
||||
|
||||
Tags annotate tests and suites with arbitrary string labels. The
|
||||
[`--experimental-test-tag-filter`][] CLI flag (or the `testTagFilters`
|
||||
option on [`run()`][]) selects tests whose tag set contains every
|
||||
provided filter value.
|
||||
|
||||
Tags are an alternative to encoding metadata into test names. They are
|
||||
useful for cross-cutting axes such as subsystem, speed bucket, flakiness,
|
||||
or environment, where a name pattern would be brittle.
|
||||
|
||||
### Authoring tagged tests
|
||||
|
||||
Pass a `tags` array on any of `test()`, `it()`, `suite()`, or `describe()`.
|
||||
Tags inherit from a suite to its child tests by union—a test inside a
|
||||
suite tagged `['db']` that declares its own `tags: ['integration']`
|
||||
effectively has both tags.
|
||||
|
||||
```mjs
|
||||
import { describe, it } from 'node:test';
|
||||
|
||||
describe('database', { tags: ['db'] }, () => {
|
||||
it('reads a row'); // tags: ['db']
|
||||
it('writes a row', { tags: ['integration'] }); // tags: ['db', 'integration']
|
||||
it('reconnects after disconnect', { tags: ['flaky'] }); // tags: ['db', 'flaky']
|
||||
});
|
||||
```
|
||||
|
||||
```cjs
|
||||
const { describe, it } = require('node:test');
|
||||
|
||||
describe('database', { tags: ['db'] }, () => {
|
||||
it('reads a row'); // tags: ['db']
|
||||
it('writes a row', { tags: ['integration'] }); // tags: ['db', 'integration']
|
||||
it('reconnects after disconnect', { tags: ['flaky'] }); // tags: ['db', 'flaky']
|
||||
});
|
||||
```
|
||||
|
||||
Tag values must be non-empty strings. Tags are matched case-insensitively;
|
||||
the canonical form is lowercase. Duplicates within a single `tags` array
|
||||
are collapsed on the lowercased form, preserving the first-seen
|
||||
declaration order.
|
||||
|
||||
Hooks (`before`, `after`, `beforeEach`, `afterEach`) do not declare their
|
||||
own tags. They run as part of their owning suite, which carries the
|
||||
suite's tags.
|
||||
|
||||
### Filtering by tag
|
||||
|
||||
Each [`--experimental-test-tag-filter`][] value is a literal tag name. A
|
||||
test runs only when its tag set contains that name. The flag may be
|
||||
specified more than once; tests must match **every** filter to run. The
|
||||
same applies to the `testTagFilters` array on [`run()`][]. Filters are
|
||||
case-insensitive and AND'd with [`--test-name-pattern`][],
|
||||
[`--test-skip-pattern`][], and `.only` filtering.
|
||||
|
||||
Untagged tests are excluded under any non-empty filter, since the filter
|
||||
requires the tag to be present.
|
||||
|
||||
### Reading tags from inside a test
|
||||
|
||||
The [`TestContext`][] object exposes the test's tags as a frozen array
|
||||
through [`context.tags`][], so tests can branch on their own metadata.
|
||||
|
||||
### Errors
|
||||
|
||||
A tag value that violates the validation rules above throws
|
||||
`ERR_INVALID_ARG_VALUE` at the registration site, before any test runs.
|
||||
A non-array `tags` value throws `ERR_INVALID_ARG_TYPE`.
|
||||
|
||||
## Extraneous asynchronous activity
|
||||
|
||||
Once a test function finishes executing, the results are reported as quickly
|
||||
@@ -749,6 +825,8 @@ test runner functionality:
|
||||
|
||||
* `--test` - Prevented to avoid recursive test execution
|
||||
* `--experimental-test-coverage` - Managed by the test runner
|
||||
* `--experimental-test-tag-filter` - Filter values are validated by the parent
|
||||
process and re-emitted to child processes
|
||||
* `--watch` - Watch mode is handled at the parent level
|
||||
* `--experimental-default-config-file` - Config file loading is handled by the parent
|
||||
* `--test-reporter` - Reporting is managed by the parent process
|
||||
@@ -1570,6 +1648,9 @@ added:
|
||||
- v18.9.0
|
||||
- v16.19.0
|
||||
changes:
|
||||
- version: REPLACEME
|
||||
pr-url: https://github.com/nodejs/node/pull/63221
|
||||
description: Added the `testTagFilters` option.
|
||||
- version: v24.14.0
|
||||
pr-url: https://github.com/nodejs/node/pull/61367
|
||||
description: Add the `env` option.
|
||||
@@ -1656,6 +1737,10 @@ changes:
|
||||
For each test that is executed, any corresponding test hooks, such as
|
||||
`beforeEach()`, are also run.
|
||||
**Default:** `undefined`.
|
||||
* `testTagFilters` {string|string\[]} A tag name, or an array of tag names,
|
||||
used to filter tests by their declared tags. Tests must contain every
|
||||
listed tag to run. Equivalent to passing [`--experimental-test-tag-filter`][]
|
||||
on the command line. See [Test tags][]. **Default:** `undefined`.
|
||||
* `timeout` {number} A number of milliseconds the test execution will
|
||||
fail after.
|
||||
If unspecified, subtests inherit this value from their parent.
|
||||
@@ -1799,6 +1884,9 @@ added:
|
||||
- v18.0.0
|
||||
- v16.17.0
|
||||
changes:
|
||||
- version: REPLACEME
|
||||
pr-url: https://github.com/nodejs/node/pull/63221
|
||||
description: Added the `tags` option.
|
||||
- version:
|
||||
- v20.2.0
|
||||
- v18.17.0
|
||||
@@ -1842,6 +1930,10 @@ changes:
|
||||
* `skip` {boolean|string} If truthy, the test is skipped. If a string is
|
||||
provided, that string is displayed in the test results as the reason for
|
||||
skipping the test. **Default:** `false`.
|
||||
* `tags` {string\[]} An array of string labels associated with the test.
|
||||
Used together with [`--experimental-test-tag-filter`][] to filter which
|
||||
tests run. Tags inherit from suites to nested tests by union. See
|
||||
[Test tags][]. **Default:** `[]`.
|
||||
* `todo` {boolean|string} If truthy, the test marked as `TODO`. If a string
|
||||
is provided, that string is displayed in the test results as the reason why
|
||||
the test is `TODO`. **Default:** `false`.
|
||||
@@ -3425,6 +3517,9 @@ Emitted when code coverage is enabled and all tests have completed.
|
||||
`undefined` if the test was run through the REPL.
|
||||
* `name` {string} The test name.
|
||||
* `nesting` {number} The nesting level of the test.
|
||||
* `tags` {string\[]} The flattened lowercased tags declared on the test
|
||||
and its ancestor suites, in declaration order. Empty for untagged tests.
|
||||
See [Test tags][].
|
||||
* `testId` {number} A numeric identifier for this test instance, unique
|
||||
within the test file's process. Consistent across all events for the same
|
||||
test instance, enabling reliable correlation in custom reporters.
|
||||
@@ -3448,6 +3543,9 @@ The corresponding declaration ordered events are `'test:pass'` and `'test:fail'`
|
||||
`undefined` if the test was run through the REPL.
|
||||
* `name` {string} The test name.
|
||||
* `nesting` {number} The nesting level of the test.
|
||||
* `tags` {string\[]} The flattened lowercased tags declared on the test
|
||||
and its ancestor suites, in declaration order. Empty for untagged tests.
|
||||
See [Test tags][].
|
||||
* `testId` {number} A numeric identifier for this test instance, unique
|
||||
within the test file's process. Consistent across all events for the same
|
||||
test instance, enabling reliable correlation in custom reporters.
|
||||
@@ -3489,6 +3587,9 @@ defined.
|
||||
`undefined` if the test was run through the REPL.
|
||||
* `name` {string} The test name.
|
||||
* `nesting` {number} The nesting level of the test.
|
||||
* `tags` {string\[]} The flattened lowercased tags declared on the test
|
||||
and its ancestor suites, in declaration order. Empty for untagged tests.
|
||||
See [Test tags][].
|
||||
* `testId` {number} A numeric identifier for this test instance, unique
|
||||
within the test file's process. Consistent across all events for the same
|
||||
test instance, enabling reliable correlation in custom reporters.
|
||||
@@ -3515,6 +3616,9 @@ Emitted when a test is enqueued for execution.
|
||||
`undefined` if the test was run through the REPL.
|
||||
* `name` {string} The test name.
|
||||
* `nesting` {number} The nesting level of the test.
|
||||
* `tags` {string\[]} The flattened lowercased tags declared on the test
|
||||
and its ancestor suites, in declaration order. Empty for untagged tests.
|
||||
See [Test tags][].
|
||||
* `testId` {number} A numeric identifier for this test instance, unique
|
||||
within the test file's process. Consistent across all events for the same
|
||||
test instance, enabling reliable correlation in custom reporters.
|
||||
@@ -3572,6 +3676,9 @@ since the parent runner only knows about file-level tests. When using
|
||||
`undefined` if the test was run through the REPL.
|
||||
* `name` {string} The test name.
|
||||
* `nesting` {number} The nesting level of the test.
|
||||
* `tags` {string\[]} The flattened lowercased tags declared on the test
|
||||
and its ancestor suites, in declaration order. Empty for untagged tests.
|
||||
See [Test tags][].
|
||||
* `testId` {number} A numeric identifier for this test instance, unique
|
||||
within the test file's process. Consistent across all events for the same
|
||||
test instance, enabling reliable correlation in custom reporters.
|
||||
@@ -3611,6 +3718,9 @@ defined.
|
||||
`undefined` if the test was run through the REPL.
|
||||
* `name` {string} The test name.
|
||||
* `nesting` {number} The nesting level of the test.
|
||||
* `tags` {string\[]} The flattened lowercased tags declared on the test
|
||||
and its ancestor suites, in declaration order. Empty for untagged tests.
|
||||
See [Test tags][].
|
||||
* `testId` {number} A numeric identifier for this test instance, unique
|
||||
within the test file's process. Consistent across all events for the same
|
||||
test instance, enabling reliable correlation in custom reporters.
|
||||
@@ -4114,6 +4224,20 @@ The attempt number of the test. This value is zero-based, so the first attempt i
|
||||
the second attempt is `1`, and so on. This property is useful in conjunction with the
|
||||
`--test-rerun-failures` option to determine which attempt the test is currently running.
|
||||
|
||||
### `context.tags`
|
||||
|
||||
<!-- YAML
|
||||
added: REPLACEME
|
||||
-->
|
||||
|
||||
> Stability: 1.0 - Early development
|
||||
|
||||
* Type: {string\[]}
|
||||
|
||||
A frozen array of the test's flattened lowercased tags, in declaration
|
||||
order, including any tags inherited from ancestor suites. Empty when the
|
||||
test has no tags. See [Test tags][].
|
||||
|
||||
### `context.workerId`
|
||||
|
||||
<!-- YAML
|
||||
@@ -4329,6 +4453,9 @@ added:
|
||||
- v18.0.0
|
||||
- v16.17.0
|
||||
changes:
|
||||
- version: REPLACEME
|
||||
pr-url: https://github.com/nodejs/node/pull/63221
|
||||
description: Added the `tags` option.
|
||||
- version:
|
||||
- v18.8.0
|
||||
- v16.18.0
|
||||
@@ -4359,6 +4486,10 @@ changes:
|
||||
* `skip` {boolean|string} If truthy, the test is skipped. If a string is
|
||||
provided, that string is displayed in the test results as the reason for
|
||||
skipping the test. **Default:** `false`.
|
||||
* `tags` {string\[]} An array of string labels associated with the subtest.
|
||||
Used together with [`--experimental-test-tag-filter`][] to filter which
|
||||
tests run. Tags inherit from the parent test or suite by union. See
|
||||
[Test tags][]. **Default:** `[]`.
|
||||
* `todo` {boolean|string} If truthy, the test marked as `TODO`. If a string
|
||||
is provided, that string is displayed in the test results as the reason why
|
||||
the test is `TODO`. **Default:** `false`.
|
||||
@@ -4507,8 +4638,10 @@ test.describe('my suite', (suite) => {
|
||||
```
|
||||
|
||||
[TAP]: https://testanything.org/
|
||||
[Test tags]: #test-tags
|
||||
[`--experimental-test-coverage`]: cli.md#--experimental-test-coverage
|
||||
[`--experimental-test-module-mocks`]: cli.md#--experimental-test-module-mocks
|
||||
[`--experimental-test-tag-filter`]: cli.md#--experimental-test-tag-filtertag
|
||||
[`--import`]: cli.md#--importmodule
|
||||
[`--no-strip-types`]: cli.md#--no-strip-types
|
||||
[`--test-concurrency`]: cli.md#--test-concurrency
|
||||
@@ -4534,6 +4667,7 @@ test.describe('my suite', (suite) => {
|
||||
[`assert.throws`]: assert.md#assertthrowsfn-error-message
|
||||
[`context.diagnostic`]: #contextdiagnosticmessage
|
||||
[`context.skip`]: #contextskipmessage
|
||||
[`context.tags`]: #contexttags
|
||||
[`context.todo`]: #contexttodomessage
|
||||
[`describe()`]: #describename-options-fn
|
||||
[`diagnostics_channel`]: diagnostics_channel.md
|
||||
|
||||
@@ -222,6 +222,10 @@ Disable support for loading ECMAScript modules with require().
|
||||
.It Fl -no-strip-types
|
||||
Disable type-stripping for TypeScript files.
|
||||
.
|
||||
.It Fl -experimental-test-tag-filter Ar tag
|
||||
Run only tests whose tag set contains \fItag\fR. May be specified multiple
|
||||
times; tests must contain every filter to run.
|
||||
.
|
||||
.It Fl -experimental-vm-modules
|
||||
Enable experimental ES module support in VM module.
|
||||
.
|
||||
|
||||
@@ -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();
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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,
|
||||
};
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -959,6 +959,11 @@ EnvironmentOptionsParser::EnvironmentOptionsParser() {
|
||||
&EnvironmentOptions::test_skip_pattern,
|
||||
kAllowedInEnvvar,
|
||||
OptionNamespaces::kTestRunnerNamespace);
|
||||
AddOption("--experimental-test-tag-filter",
|
||||
"run tests matching the given tag filter expression",
|
||||
&EnvironmentOptions::experimental_test_tag_filter,
|
||||
kDisallowedInEnvvar,
|
||||
OptionNamespaces::kTestRunnerNamespace);
|
||||
AddOption("--test-coverage-include",
|
||||
"include files in coverage report that match this glob pattern",
|
||||
&EnvironmentOptions::coverage_include_pattern,
|
||||
|
||||
@@ -215,6 +215,7 @@ class EnvironmentOptions : public Options {
|
||||
std::string test_isolation = "process";
|
||||
std::string test_shard;
|
||||
std::vector<std::string> test_skip_pattern;
|
||||
std::vector<std::string> experimental_test_tag_filter;
|
||||
std::vector<std::string> coverage_include_pattern;
|
||||
std::vector<std::string> coverage_exclude_pattern;
|
||||
bool throw_deprecation = false;
|
||||
|
||||
Vendored
+22
@@ -0,0 +1,22 @@
|
||||
'use strict';
|
||||
const { describe, it, test } = require('node:test');
|
||||
|
||||
describe('db suite', { tags: ['db'] }, () => {
|
||||
it('db only', () => {});
|
||||
it('db plus integration', { tags: ['integration'] }, () => {});
|
||||
it('db flaky', { tags: ['flaky'] }, () => {});
|
||||
});
|
||||
|
||||
describe('unit suite', { tags: ['unit'] }, () => {
|
||||
it('unit only', () => {});
|
||||
it('unit slow', { tags: ['slow'] }, () => {});
|
||||
});
|
||||
|
||||
test('untagged', () => {});
|
||||
test('only flaky', { tags: ['flaky'] }, () => {});
|
||||
test('db wildcard match', { tags: ['db:postgres'] }, () => {});
|
||||
|
||||
describe('plain suite', () => {
|
||||
it('lonely child', { tags: ['lonely'] }, () => {});
|
||||
it('plain sibling', () => {});
|
||||
});
|
||||
@@ -0,0 +1,108 @@
|
||||
import '../common/index.mjs';
|
||||
import * as fixtures from '../common/fixtures.mjs';
|
||||
import assert from 'node:assert';
|
||||
import { spawnSync } from 'node:child_process';
|
||||
import { test } from 'node:test';
|
||||
|
||||
const fixture = fixtures.path('test-runner', 'tagged.js');
|
||||
|
||||
function run(filterArgs, extraArgs = []) {
|
||||
const args = [
|
||||
'--test',
|
||||
'--test-reporter=tap',
|
||||
...filterArgs,
|
||||
...extraArgs,
|
||||
fixture,
|
||||
];
|
||||
const child = spawnSync(process.execPath, args);
|
||||
return {
|
||||
status: child.status,
|
||||
stdout: child.stdout.toString(),
|
||||
stderr: child.stderr.toString(),
|
||||
};
|
||||
}
|
||||
|
||||
function pass(stdout, n) {
|
||||
assert.match(stdout, new RegExp(`^# pass ${n}$`, 'm'));
|
||||
assert.match(stdout, /^# fail 0$/m);
|
||||
}
|
||||
|
||||
test('no filter: every test runs', () => {
|
||||
const { status, stdout } = run([]);
|
||||
assert.strictEqual(status, 0);
|
||||
pass(stdout, 10);
|
||||
});
|
||||
|
||||
test('single filter: db', () => {
|
||||
const { status, stdout } = run(['--experimental-test-tag-filter=db']);
|
||||
assert.strictEqual(status, 0);
|
||||
pass(stdout, 3);
|
||||
assert.match(stdout, /ok \d+ - db only/);
|
||||
assert.match(stdout, /ok \d+ - db plus integration/);
|
||||
assert.match(stdout, /ok \d+ - db flaky/);
|
||||
assert.doesNotMatch(stdout, /unit only/);
|
||||
assert.doesNotMatch(stdout, /^ok \d+ - untagged/m);
|
||||
});
|
||||
|
||||
test('filter is case-insensitive', () => {
|
||||
const { status, stdout } = run(['--experimental-test-tag-filter=DB']);
|
||||
assert.strictEqual(status, 0);
|
||||
pass(stdout, 3);
|
||||
});
|
||||
|
||||
test('untagged parent runs only the matching tagged child', () => {
|
||||
// 'plain suite' has no own tags, so on its own it would be filtered out
|
||||
// by any include filter. The 'lonely child' carries the tag, so the
|
||||
// runner reinstates the parent and runs that child. The untagged sibling
|
||||
// 'plain sibling' must still be filtered out.
|
||||
const { status, stdout } = run(['--experimental-test-tag-filter=lonely']);
|
||||
assert.strictEqual(status, 0);
|
||||
pass(stdout, 1);
|
||||
assert.match(stdout, /ok \d+ - lonely child/);
|
||||
assert.doesNotMatch(stdout, /plain sibling/);
|
||||
});
|
||||
|
||||
test('repeated --experimental-test-tag-filter ANDs together', () => {
|
||||
// db AND integration: only "db plus integration" satisfies both.
|
||||
const { status, stdout } = run([
|
||||
'--experimental-test-tag-filter=db',
|
||||
'--experimental-test-tag-filter=integration',
|
||||
]);
|
||||
assert.strictEqual(status, 0);
|
||||
pass(stdout, 1);
|
||||
assert.match(stdout, /ok \d+ - db plus integration/);
|
||||
assert.doesNotMatch(stdout, /^ok \d+ - db only/m);
|
||||
assert.doesNotMatch(stdout, /^ok \d+ - db flaky/m);
|
||||
});
|
||||
|
||||
test('untagged tests are excluded under any positive filter', () => {
|
||||
const { status, stdout } = run(['--experimental-test-tag-filter=db']);
|
||||
assert.strictEqual(status, 0);
|
||||
assert.doesNotMatch(stdout, /^ok \d+ - untagged/m);
|
||||
});
|
||||
|
||||
test('isolation=none produces identical filtered set', () => {
|
||||
const proc = run(['--experimental-test-tag-filter=db']);
|
||||
const none = run(['--experimental-test-tag-filter=db'], ['--test-isolation=none']);
|
||||
assert.strictEqual(proc.status, 0);
|
||||
assert.strictEqual(none.status, 0);
|
||||
pass(proc.stdout, 3);
|
||||
pass(none.stdout, 3);
|
||||
});
|
||||
|
||||
test('combined with --test-skip-pattern (pure AND)', () => {
|
||||
// The db filter selects 3, then skip-pattern removes any name matching /flaky/.
|
||||
const { status, stdout } = run([
|
||||
'--experimental-test-tag-filter=db',
|
||||
'--test-skip-pattern=/flaky/',
|
||||
]);
|
||||
assert.strictEqual(status, 0);
|
||||
pass(stdout, 2);
|
||||
assert.doesNotMatch(stdout, /db flaky/);
|
||||
});
|
||||
|
||||
test('empty --experimental-test-tag-filter= is rejected by argv parser', () => {
|
||||
const { status, stderr } = run(['--experimental-test-tag-filter=']);
|
||||
assert.notStrictEqual(status, 0);
|
||||
assert.match(stderr, /requires an argument/);
|
||||
});
|
||||
@@ -0,0 +1,100 @@
|
||||
import * as common from '../common/index.mjs';
|
||||
import * as fixtures from '../common/fixtures.mjs';
|
||||
import assert from 'node:assert';
|
||||
import { describe, it, run } from 'node:test';
|
||||
|
||||
const fixture = fixtures.path('test-runner', 'tagged.js');
|
||||
|
||||
const kEventsWithTags = ['test:enqueue', 'test:dequeue', 'test:start', 'test:pass', 'test:fail', 'test:complete'];
|
||||
|
||||
async function collectEvents(opts = {}) {
|
||||
const events = [];
|
||||
const stream = run({ files: [fixture], ...opts });
|
||||
for (const kind of kEventsWithTags) {
|
||||
stream.on(kind, (data) => {
|
||||
events.push({ kind, name: data.name, tags: data.tags, nesting: data.nesting });
|
||||
});
|
||||
}
|
||||
// eslint-disable-next-line no-unused-vars
|
||||
for await (const _ of stream);
|
||||
return events;
|
||||
}
|
||||
|
||||
function indexByName(events) {
|
||||
const byName = new Map();
|
||||
for (const ev of events) {
|
||||
let array = byName.get(ev.name);
|
||||
if (array == null) {
|
||||
byName.set(ev.name, array = []);
|
||||
}
|
||||
array.push(ev);
|
||||
}
|
||||
return byName;
|
||||
}
|
||||
|
||||
describe('tag-bearing event payloads', { concurrency: false }, () => {
|
||||
it('every event carries a tags array', async () => {
|
||||
const events = await collectEvents();
|
||||
assert.ok(events.length > 0);
|
||||
for (const ev of events) {
|
||||
assert.ok(
|
||||
Array.isArray(ev.tags),
|
||||
`${ev.kind} ${ev.name}: tags should be an array, got ${typeof ev.tags}`,
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
it('untagged tests have an empty array, not undefined', async () => {
|
||||
const events = await collectEvents();
|
||||
const untagged = events.filter((e) => e.name === 'untagged');
|
||||
assert.ok(untagged.length > 0, 'expected events for "untagged"');
|
||||
for (const ev of untagged) {
|
||||
assert.deepStrictEqual(ev.tags, [], `${ev.kind} should have empty tags`);
|
||||
}
|
||||
});
|
||||
|
||||
it('tag values match the flattened canonical set', async () => {
|
||||
const events = await collectEvents();
|
||||
const byName = indexByName(events);
|
||||
|
||||
function expectTags(name, expected) {
|
||||
const evs = byName.get(name);
|
||||
assert.ok(evs && evs.length > 0, `no events for ${name}`);
|
||||
for (const ev of evs) {
|
||||
assert.deepStrictEqual(ev.tags, expected, `${ev.kind} ${ev.name}`);
|
||||
}
|
||||
}
|
||||
|
||||
expectTags('db only', ['db']);
|
||||
expectTags('db plus integration', ['db', 'integration']);
|
||||
expectTags('only flaky', ['flaky']);
|
||||
expectTags('db suite', ['db']);
|
||||
expectTags('unit slow', ['unit', 'slow']);
|
||||
});
|
||||
|
||||
it('all required event kinds carry tags', async () => {
|
||||
const events = await collectEvents();
|
||||
const seenKinds = new Set(events.map((ev) => ev.kind));
|
||||
for (const required of ['test:enqueue', 'test:start', 'test:pass', 'test:complete']) {
|
||||
assert.ok(seenKinds.has(required), `expected ${required}`);
|
||||
}
|
||||
for (const ev of events) {
|
||||
assert.ok(
|
||||
kEventsWithTags.includes(ev.kind),
|
||||
`unexpected event kind ${ev.kind}`,
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
it('test:pass fires only for selected tagged tests when filtered', async () => {
|
||||
// isolation='none' so the parent applies the filter directly. Under
|
||||
// 'process', the FileTest wrapper (which has no tags) would itself be
|
||||
// filtered out by the include filter - same wart as --test-name-pattern.
|
||||
const stream = run({ files: [fixture], testTagFilters: ['db'], isolation: 'none' });
|
||||
stream.on('test:fail', common.mustNotCall());
|
||||
// 3 db-tagged tests pass + the db suite itself.
|
||||
stream.on('test:pass', common.mustCall(4));
|
||||
// eslint-disable-next-line no-unused-vars
|
||||
for await (const _ of stream);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,97 @@
|
||||
import { expectWarning } from '../common/index.mjs';
|
||||
import * as fixtures from '../common/fixtures.mjs';
|
||||
import assert from 'node:assert';
|
||||
import { spawnSync } from 'node:child_process';
|
||||
import { it, test } from 'node:test';
|
||||
|
||||
const fixture = fixtures.path('test-runner', 'tagged.js');
|
||||
|
||||
function runChild(args, opts = {}) {
|
||||
// Strip NODE_TEST_CONTEXT so a child run() works as a top-level invocation.
|
||||
const env = { ...process.env, ...(opts.env || {}) };
|
||||
delete env.NODE_TEST_CONTEXT;
|
||||
delete env.NODE_TEST_WORKER_ID;
|
||||
const child = spawnSync(process.execPath, args, {
|
||||
stdio: ['ignore', 'pipe', 'pipe'],
|
||||
env,
|
||||
});
|
||||
return {
|
||||
status: child.status,
|
||||
stdout: child.stdout.toString(),
|
||||
stderr: child.stderr.toString(),
|
||||
};
|
||||
}
|
||||
|
||||
function countWarnings(stderr) {
|
||||
let count = 0;
|
||||
let idx = 0;
|
||||
while (true) {
|
||||
const next = stderr.indexOf('ExperimentalWarning: Test tags', idx);
|
||||
if (next === -1) break;
|
||||
count++;
|
||||
idx = next + 1;
|
||||
}
|
||||
return count;
|
||||
}
|
||||
|
||||
// In-process: when tags are registered with no other trigger, the warning
|
||||
// fires exactly once for the lifetime of the process.
|
||||
expectWarning('ExperimentalWarning', 'Test tags is an experimental feature and might change at any time');
|
||||
|
||||
test('the warning fires once per process for tag registration', () => {
|
||||
it('first', { tags: ['db'] }, () => {});
|
||||
it('second', { tags: ['unit'] }, () => {});
|
||||
it('third', { tags: ['integration'] }, () => {});
|
||||
// expectWarning's mustCall(_, 1) will fail if the warning is emitted a
|
||||
// second time for any of the registrations above.
|
||||
});
|
||||
|
||||
test('--experimental-test-tag-filter fires the warning', () => {
|
||||
const { stderr } = runChild([
|
||||
'--test',
|
||||
'--test-reporter=tap',
|
||||
'--experimental-test-tag-filter=db',
|
||||
'--test-isolation=none',
|
||||
fixture,
|
||||
]);
|
||||
assert.strictEqual(countWarnings(stderr), 1, stderr);
|
||||
});
|
||||
|
||||
test('programmatic testTagFilters fires the warning', () => {
|
||||
const driver = `
|
||||
'use strict';
|
||||
const { run } = require('node:test');
|
||||
run({
|
||||
files: [${JSON.stringify(fixture)}],
|
||||
isolation: 'none',
|
||||
testTagFilters: ['db'],
|
||||
}).resume();
|
||||
`;
|
||||
const { stderr } = runChild(['-e', driver]);
|
||||
assert.strictEqual(countWarnings(stderr), 1, stderr);
|
||||
});
|
||||
|
||||
test('tags: [] does not fire the warning', () => {
|
||||
const driver = `
|
||||
'use strict';
|
||||
const { it } = require('node:test');
|
||||
it('a', { tags: [] }, () => {});
|
||||
it('b', { tags: [] }, () => {});
|
||||
it('c', () => {});
|
||||
`;
|
||||
const { stderr } = runChild(['-e', driver]);
|
||||
assert.strictEqual(countWarnings(stderr), 0, stderr);
|
||||
});
|
||||
|
||||
test('multiple triggers in one process emit the warning once', () => {
|
||||
const driver = `
|
||||
'use strict';
|
||||
const { it, run } = require('node:test');
|
||||
// Trigger 1: tag registration.
|
||||
it('a', { tags: ['db'] }, () => {});
|
||||
// Trigger 2: programmatic testTagFilters.
|
||||
run({ files: [${JSON.stringify(fixture)}], isolation: 'none', testTagFilters: ['db'] }).resume();
|
||||
`;
|
||||
const { stderr } = runChild(['-e', driver]);
|
||||
assert.strictEqual(countWarnings(stderr), 1, stderr);
|
||||
});
|
||||
@@ -0,0 +1,118 @@
|
||||
import { expectWarning } from '../common/index.mjs';
|
||||
import assert from 'node:assert';
|
||||
import { afterEach, beforeEach, describe, it, test } from 'node:test';
|
||||
|
||||
expectWarning('ExperimentalWarning', 'Test tags is an experimental feature and might change at any time');
|
||||
|
||||
test('child inherits parent suite tags', () => {
|
||||
describe('outer', { tags: ['db'] }, () => {
|
||||
it('child', (t) => {
|
||||
assert.deepStrictEqual(t.tags, ['db']);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
test('child unions own tags with parent', () => {
|
||||
describe('outer', { tags: ['db'] }, () => {
|
||||
it('child', { tags: ['integration'] }, (t) => {
|
||||
assert.deepStrictEqual(t.tags, ['db', 'integration']);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
test('parent tags appear before child tags (parent-first order)', () => {
|
||||
describe('outer', { tags: ['z'] }, () => {
|
||||
it('child', { tags: ['a'] }, (t) => {
|
||||
assert.deepStrictEqual(t.tags, ['z', 'a']);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
test('union dedupes across parent and child', () => {
|
||||
describe('outer', { tags: ['db'] }, () => {
|
||||
it('child', { tags: ['DB', 'integration'] }, (t) => {
|
||||
assert.deepStrictEqual(t.tags, ['db', 'integration']);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
test('multi-level nesting flattens by union', () => {
|
||||
describe('outer', { tags: ['a'] }, () => {
|
||||
describe('mid', { tags: ['b'] }, () => {
|
||||
it('leaf', { tags: ['c'] }, (t) => {
|
||||
assert.deepStrictEqual(t.tags, ['a', 'b', 'c']);
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
test('child without own tags inherits parent set unchanged', () => {
|
||||
describe('outer', { tags: ['db', 'fast'] }, () => {
|
||||
it('child', (t) => {
|
||||
assert.deepStrictEqual(t.tags, ['db', 'fast']);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
test('tagged child under untagged parent shows only own tags', () => {
|
||||
describe('outer', () => {
|
||||
it('child', { tags: ['x'] }, (t) => {
|
||||
assert.deepStrictEqual(t.tags, ['x']);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
test('untagged child under untagged parent has empty tags', () => {
|
||||
describe('outer', () => {
|
||||
it('child', (t) => {
|
||||
assert.deepStrictEqual(t.tags, []);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
test('tags: [] yields an empty array, not undefined', () => {
|
||||
it('empty', { tags: [] }, (t) => {
|
||||
assert.deepStrictEqual(t.tags, []);
|
||||
});
|
||||
});
|
||||
|
||||
test('tags: [] on a child still inherits parent tags (not an opt-out)', () => {
|
||||
describe('outer', { tags: ['db'] }, () => {
|
||||
it('child', { tags: [] }, (t) => {
|
||||
assert.deepStrictEqual(t.tags, ['db']);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
test('t.tags returns a frozen view', () => {
|
||||
it('frozen', { tags: ['db'] }, (t) => {
|
||||
const tags = t.tags;
|
||||
assert.strictEqual(Object.isFrozen(tags), true);
|
||||
});
|
||||
});
|
||||
|
||||
test('successive t.tags reads return equivalent arrays', () => {
|
||||
it('idempotent', { tags: ['db', 'fast'] }, (t) => {
|
||||
assert.deepStrictEqual(t.tags, t.tags);
|
||||
assert.deepStrictEqual(t.tags, ['db', 'fast']);
|
||||
});
|
||||
});
|
||||
|
||||
test('beforeEach and afterEach see the flattened tags of the current test', () => {
|
||||
describe('outer', { tags: ['db'] }, () => {
|
||||
beforeEach((t) => t.assert.deepStrictEqual(t.tags, ['db', 'integration']));
|
||||
afterEach((t) => t.assert.deepStrictEqual(t.tags, ['db', 'integration']));
|
||||
it('child', { tags: ['integration'] }, (t) => {
|
||||
t.assert.deepStrictEqual(t.tags, ['db', 'integration']);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
test('context.test() accepts and inherits tags', async (t) => {
|
||||
await t.test('parent', { tags: ['db'] }, async (parent) => {
|
||||
parent.assert.deepStrictEqual(parent.tags, ['db']);
|
||||
await parent.test('child', { tags: ['integration'] }, (child) => {
|
||||
child.assert.deepStrictEqual(child.tags, ['db', 'integration']);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,117 @@
|
||||
import { expectWarning } from '../common/index.mjs';
|
||||
import assert from 'node:assert';
|
||||
import { test, suite, describe, it, before, beforeEach, after, afterEach, run } from 'node:test';
|
||||
|
||||
// Silence the one-shot ExperimentalWarning that fires the first time tags are
|
||||
// registered. Validation tests focus on the throw, not the warning.
|
||||
expectWarning('ExperimentalWarning', 'Test tags is an experimental feature and might change at any time');
|
||||
|
||||
test('non-array tags throws ERR_INVALID_ARG_TYPE', () => {
|
||||
for (const bad of ['db', 42, {}, true, Symbol('s'), null]) {
|
||||
assert.throws(
|
||||
() => test('x', { tags: bad }, () => {}),
|
||||
{ code: 'ERR_INVALID_ARG_TYPE' },
|
||||
`expected throw for tags=${String(bad)}`,
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
test('non-string element throws ERR_INVALID_ARG_TYPE', () => {
|
||||
for (const bad of [42, {}, true, null, undefined, Symbol('s')]) {
|
||||
assert.throws(
|
||||
() => test('x', { tags: ['db', bad] }, () => {}),
|
||||
{ code: 'ERR_INVALID_ARG_TYPE' },
|
||||
`expected throw for element=${String(bad)}`,
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
test('empty-string tag throws ERR_INVALID_ARG_VALUE', () => {
|
||||
assert.throws(
|
||||
() => test('x', { tags: [''] }, () => {}),
|
||||
{ code: 'ERR_INVALID_ARG_VALUE' },
|
||||
);
|
||||
assert.throws(
|
||||
() => test('x', { tags: ['db', ''] }, () => {}),
|
||||
{ code: 'ERR_INVALID_ARG_VALUE' },
|
||||
);
|
||||
});
|
||||
|
||||
test('Unicode and most punctuation are allowed', () => {
|
||||
// None of these should throw.
|
||||
test('unicode-1', { tags: ['café'] }, () => {});
|
||||
test('unicode-2', { tags: ['日本語'] }, () => {});
|
||||
test('punct-1', { tags: ['db:postgres'] }, () => {});
|
||||
test('punct-2', { tags: ['db-1'] }, () => {});
|
||||
test('punct-3', { tags: ['db.fast'] }, () => {});
|
||||
test('punct-4', { tags: ['db_fast'] }, () => {});
|
||||
test('punct-5', { tags: ['#critical'] }, () => {});
|
||||
});
|
||||
|
||||
test('tags: [] is a no-op (does not throw)', () => {
|
||||
test('empty-tags', { tags: [] }, () => {});
|
||||
});
|
||||
|
||||
test('case dedup: ["db", "DB", "Db"] collapses to single canonical entry', async (t) => {
|
||||
await t.test('child', { tags: ['db', 'DB', 'Db'] }, (ct) => {
|
||||
assert.deepStrictEqual(ct.tags, ['db']);
|
||||
});
|
||||
});
|
||||
|
||||
test('declaration order is preserved on dedup', async (t) => {
|
||||
await t.test('child', { tags: ['Z', 'a', 'z', 'A'] }, (ct) => {
|
||||
assert.deepStrictEqual(ct.tags, ['z', 'a']);
|
||||
});
|
||||
});
|
||||
|
||||
test('hooks silently ignore the tags option', () => {
|
||||
// Hooks must not throw if a caller mistakenly passes tags — the API has no
|
||||
// tags concept for hooks, but it should be tolerated. The validator only
|
||||
// runs on Test/Suite construction, not in the hook factory.
|
||||
before(() => {}, { tags: ['db'] });
|
||||
after(() => {}, { tags: ['db'] });
|
||||
beforeEach(() => {}, { tags: ['db'] });
|
||||
afterEach(() => {}, { tags: ['db'] });
|
||||
});
|
||||
|
||||
test('suite() and describe() validate tags identically', () => {
|
||||
assert.throws(
|
||||
() => suite('s', { tags: 'db' }, () => {}),
|
||||
{ code: 'ERR_INVALID_ARG_TYPE' },
|
||||
);
|
||||
assert.throws(
|
||||
() => describe('s', { tags: [''] }, () => {}),
|
||||
{ code: 'ERR_INVALID_ARG_VALUE' },
|
||||
);
|
||||
});
|
||||
|
||||
test('it() validates tags identically to test()', () => {
|
||||
assert.throws(
|
||||
() => it('i', { tags: [42] }, () => {}),
|
||||
{ code: 'ERR_INVALID_ARG_TYPE' },
|
||||
);
|
||||
});
|
||||
|
||||
test('run() rejects non-string testTagFilters values', () => {
|
||||
for (const bad of [[42], [{}], [null], [undefined], [true], [Symbol('s')]]) {
|
||||
assert.throws(
|
||||
() => run({ testTagFilters: bad }),
|
||||
{ code: 'ERR_INVALID_ARG_TYPE' },
|
||||
`expected throw for testTagFilters=${JSON.stringify(bad)}`,
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
test('run() accepts a bare-string testTagFilters and normalizes it', async () => {
|
||||
// The string form is converted to a single-element array internally and
|
||||
// must not throw.
|
||||
const stream = run({ files: [], testTagFilters: 'db' });
|
||||
// eslint-disable-next-line no-unused-vars
|
||||
for await (const _ of stream);
|
||||
});
|
||||
|
||||
test('run() treats an empty testTagFilters array as a no-op', async () => {
|
||||
const stream = run({ files: [], testTagFilters: [] });
|
||||
// eslint-disable-next-line no-unused-vars
|
||||
for await (const _ of stream);
|
||||
});
|
||||
Reference in new issue
Block a user