GeezerVison is showing github.com — test_runner: use AsyncLocalStorage instead of async_hooks · nodejs/node@c3fd64d
File treeExpand file treeCollapse file tree Open diff view settings fixtures/test-runner/output
Expand file treeCollapse file tree Open diff view settings Collapse file Copy file name to clipboardExpand all lines: lib/internal/test_runner/harness.js +5-34Lines changed: 5 additions & 34 deletions | Original file line number | Diff line number | Diff line change |
|---|
| 6 | 6 | Promise, | 7 | 7 | PromiseResolve, | 8 | 8 | PromiseWithResolvers, | 9 | | - SafeMap, | 10 | 9 | SafePromiseAllReturnVoid, | 11 | 10 | } = primordials; | 12 | 11 | const { getCallerLocation } = internalBinding('util'); | 13 | | -const { | 14 | | - createHook, | 15 | | - executionAsyncId, | 16 | | -} = require('async_hooks'); | 17 | 12 | const { relative } = require('path'); | 18 | 13 | const { | 19 | 14 | codes: { | @@ -26,6 +21,7 @@ const { | 26 | 21 | parseCommandLine, | 27 | 22 | reporterScope, | 28 | 23 | shouldColorizeTestFiles, | | 24 | + testStorage, | 29 | 25 | setupGlobalSetupTeardownFunctions, | 30 | 26 | parsePreviousRuns, | 31 | 27 | } = require('internal/test_runner/utils'); | @@ -35,12 +31,9 @@ const { queueMicrotask } = require('internal/process/task_queues'); | 35 | 31 | const { TIMEOUT_MAX } = require('internal/timers'); | 36 | 32 | const { clearInterval, setImmediate, setInterval } = require('timers'); | 37 | 33 | const { bigint: hrtime } = process.hrtime; | 38 | | -const testResources = new SafeMap(); | 39 | 34 | let globalRoot; | 40 | 35 | let globalSetupExecuted = false; | 41 | 36 |
| 42 | | -testResources.set(reporterScope.asyncId(), reporterScope); | 43 | | - | 44 | 37 | function createTestTree(rootTestOptions, globalOptions) { | 45 | 38 | const buildPhaseDeferred = PromiseWithResolvers(); | 46 | 39 | const isFilteringByName = globalOptions.testNamePatterns || | @@ -124,7 +117,7 @@ function createProcessEventHandler(eventName, rootTest) { | 124 | 117 | throw err; | 125 | 118 | } | 126 | 119 |
| 127 | | - const test = testResources.get(executionAsyncId()); | | 120 | + const test = testStorage.getStore(); | 128 | 121 |
| 129 | 122 | // Check if this error is coming from a reporter. If it is, throw it. | 130 | 123 | if (test === reporterScope) { | @@ -230,27 +223,6 @@ function setupFailureStateFile(rootTest, globalOptions) { | 230 | 223 | } | 231 | 224 |
| 232 | 225 | function setupProcessState(root, globalOptions) { | 233 | | - const hook = createHook({ | 234 | | - __proto__: null, | 235 | | - init(asyncId, type, triggerAsyncId, resource) { | 236 | | - if (resource instanceof Test) { | 237 | | - testResources.set(asyncId, resource); | 238 | | - return; | 239 | | - } | 240 | | - | 241 | | - const parent = testResources.get(triggerAsyncId); | 242 | | - | 243 | | - if (parent !== undefined) { | 244 | | - testResources.set(asyncId, parent); | 245 | | - } | 246 | | - }, | 247 | | - destroy(asyncId) { | 248 | | - testResources.delete(asyncId); | 249 | | - }, | 250 | | - }); | 251 | | - | 252 | | - hook.enable(); | 253 | | - | 254 | 226 | const exceptionHandler = | 255 | 227 | createProcessEventHandler('uncaughtException', root); | 256 | 228 | const rejectionHandler = | @@ -282,7 +254,6 @@ function setupProcessState(root, globalOptions) { | 282 | 254 | root.harness.globalTeardownFunction = null; | 283 | 255 | } | 284 | 256 |
| 285 | | - hook.disable(); | 286 | 257 | process.removeListener('uncaughtException', exceptionHandler); | 287 | 258 | process.removeListener('unhandledRejection', rejectionHandler); | 288 | 259 | process.removeListener('beforeExit', exitHandler); | @@ -389,7 +360,7 @@ async function startSubtestAfterBootstrap(subtest) { | 389 | 360 |
| 390 | 361 | function runInParentContext(Factory) { | 391 | 362 | function run(name, options, fn, overrides) { | 392 | | - const parent = testResources.get(executionAsyncId()) || lazyBootstrapRoot(); | | 363 | + const parent = testStorage.getStore() || lazyBootstrapRoot(); | 393 | 364 | const subtest = parent.createSubtest(Factory, name, options, fn, overrides); | 394 | 365 | if (parent instanceof Suite) { | 395 | 366 | return PromiseResolve(); | @@ -422,7 +393,7 @@ function runInParentContext(Factory) { | 422 | 393 |
| 423 | 394 | function hook(hook) { | 424 | 395 | return (fn, options) => { | 425 | | - const parent = testResources.get(executionAsyncId()) || lazyBootstrapRoot(); | | 396 | + const parent = testStorage.getStore() || lazyBootstrapRoot(); | 426 | 397 | parent.createHook(hook, fn, { | 427 | 398 | __proto__: null, | 428 | 399 | ...options, | @@ -434,7 +405,7 @@ function hook(hook) { | 434 | 405 | } | 435 | 406 |
| 436 | 407 | function getTestContext() { | 437 | | - const test = testResources.get(executionAsyncId()); | | 408 | + const test = testStorage.getStore(); | 438 | 409 | // Exclude the reporter sentinel | 439 | 410 | if (test === undefined || test === reporterScope) { | 440 | 411 | return undefined; | |
Collapse file Copy file name to clipboardExpand all lines: lib/internal/test_runner/test.js +30Lines changed: 30 additions & 0 deletions | Original file line number | Diff line number | Diff line change |
|---|
@@ -44,6 +44,12 @@ const { exitCodes: { kGenericUserError } } = internalBinding('errors'); | 44 | 44 | const { addAbortListener } = require('internal/events/abort_listener'); | 45 | 45 | const { queueMicrotask } = require('internal/process/task_queues'); | 46 | 46 | const { AsyncResource } = require('async_hooks'); | | 47 | +const AsyncContextFrame = require('internal/async_context_frame'); | | 48 | +const { | | 49 | + emitAfter, | | 50 | + emitBefore, | | 51 | + hasAsyncIdStack, | | 52 | +} = require('internal/async_hooks'); | 47 | 53 | const { AbortController } = require('internal/abort_controller'); | 48 | 54 | const { | 49 | 55 | AbortError, | @@ -67,6 +73,7 @@ const { | 67 | 73 | isTestFailureError, | 68 | 74 | reporterScope, | 69 | 75 | testChannel, | | 76 | + testStorage, | 70 | 77 | } = require('internal/test_runner/utils'); | 71 | 78 | const { | 72 | 79 | kEmptyObject, | @@ -574,9 +581,12 @@ class Test extends AsyncResource { | 574 | 581 | outerSignal; | 575 | 582 | #reportedSubtest; | 576 | 583 | #tagsArray = null; | | 584 | + #asyncContextFrame; | 577 | 585 |
| 578 | 586 | constructor(options) { | 579 | 587 | super('Test'); | | 588 | + // The context captured by AsyncResource, with this test as the owner. | | 589 | + this.#asyncContextFrame = new AsyncContextFrame(testStorage, this); | 580 | 590 |
| 581 | 591 | let { fn, name, parent } = options; | 582 | 592 | const { concurrency, entryFile, expectFailure, loc, only, timeout, todo, skip, signal, plan } = options; | @@ -858,6 +868,26 @@ class Test extends AsyncResource { | 858 | 868 | return this.#tagsArray; | 859 | 869 | } | 860 | 870 |
| | 871 | + // Same as AsyncResource#runInAsyncScope(), but the restored context also | | 872 | + // makes this test the owner of everything that runs or is scheduled inside | | 873 | + // fn. This is how the harness maps uncaught errors and nested test() or | | 874 | + // hook calls back to the right test. It is inlined rather than wrapping | | 875 | + // super.runInAsyncScope() to avoid adding frames to user stack traces. | | 876 | + runInAsyncScope(fn, thisArg, ...args) { | | 877 | + const asyncId = this.asyncId(); | | 878 | + emitBefore(asyncId, this.triggerAsyncId(), this); | | 879 | + | | 880 | + const prior = AsyncContextFrame.exchange(this.#asyncContextFrame); | | 881 | + try { | | 882 | + return ReflectApply(fn, thisArg, args); | | 883 | + } finally { | | 884 | + AsyncContextFrame.set(prior); | | 885 | + if (hasAsyncIdStack()) { | | 886 | + emitAfter(asyncId); | | 887 | + } | | 888 | + } | | 889 | + } | | 890 | + | 861 | 891 | applyFilters() { | 862 | 892 | if (this.error) { | 863 | 893 | // Never filter out errors. | |
Collapse file Copy file name to clipboardExpand all lines: lib/internal/test_runner/utils.js +6-3Lines changed: 6 additions & 3 deletions | Original file line number | Diff line number | Diff line change |
|---|
@@ -33,7 +33,7 @@ const { | 33 | 33 | parseTagFilterExpression, | 34 | 34 | } = require('internal/test_runner/tag_filter'); | 35 | 35 |
| 36 | | -const { AsyncResource } = require('async_hooks'); | | 36 | +const { AsyncLocalStorage, AsyncResource } = require('async_hooks'); | 37 | 37 | const { tracingChannel } = require('diagnostics_channel'); | 38 | 38 | const { relative, sep, resolve } = require('path'); | 39 | 39 | const { createWriteStream, readFileSync } = require('fs'); | @@ -235,6 +235,8 @@ async function getReportersMap(reporters, destinations) { | 235 | 235 | } | 236 | 236 |
| 237 | 237 | const reporterScope = new AsyncResource('TestReporterScope'); | | 238 | +// Tracks the Test (or reporterScope) that owns the current async context. | | 239 | +const testStorage = new AsyncLocalStorage(); | 238 | 240 | const testChannel = tracingChannel('node.test'); | 239 | 241 | let globalTestOptions; | 240 | 242 |
| @@ -397,15 +399,15 @@ function parseCommandLine() { | 397 | 399 | randomize = true; | 398 | 400 | } | 399 | 401 |
| 400 | | - const setup = reporterScope.bind(async (rootReporter) => { | | 402 | + const setup = reporterScope.bind((rootReporter) => testStorage.run(reporterScope, async () => { | 401 | 403 | const reportersMap = await getReportersMap(reporters, destinations); | 402 | 404 | for (let i = 0; i < reportersMap.length; i++) { | 403 | 405 | const { reporter, destination } = reportersMap[i]; | 404 | 406 | compose(rootReporter, reporter).pipe(destination); | 405 | 407 | } | 406 | 408 |
| 407 | 409 | reporterScope.reporters = reportersMap; | 408 | | - }); | | 410 | + })); | 409 | 411 |
| 410 | 412 | globalTestOptions = { | 411 | 413 | __proto__: null, | @@ -734,6 +736,7 @@ module.exports = { | 734 | 736 | kMaxRandomSeed, | 735 | 737 | parseCommandLine, | 736 | 738 | reporterScope, | | 739 | + testStorage, | 737 | 740 | shouldColorizeTestFiles, | 738 | 741 | getCoverageReport, | 739 | 742 | setupGlobalSetupTeardownFunctions, | |
Collapse file Copy file name to clipboardExpand all lines: test/fixtures/test-runner/output/describe_it.snapshot -1Lines changed: 0 additions & 1 deletion | Original file line number | Diff line number | Diff line change |
|---|
@@ -439,7 +439,6 @@ not ok 50 - callback called twice | 439 | 439 | code: 'ERR_TEST_FAILURE' | 440 | 440 | stack: |- | 441 | 441 | TestContext.<anonymous> (<project-root>/test/fixtures/test-runner/output/describe_it.js:255:3) | 442 | | - <node-internal-frames> | 443 | 442 | ... | 444 | 443 | # Subtest: callback called twice in different ticks | 445 | 444 | ok 51 - callback called twice in different ticks | |
Collapse file Copy file name to clipboardExpand all lines: test/fixtures/test-runner/output/junit_reporter.snapshot +3-6Lines changed: 3 additions & 6 deletions | Original file line number | Diff line number | Diff line change |
|---|
@@ -132,8 +132,7 @@ true !== false | 132 | 132 | <testcase name="+sync throw fail" time="*" classname="subtest sync throw fail" file="*" failure="thrown from subtest sync throw fail"> | 133 | 133 | <failure type="testCodeFailure" message="thrown from subtest sync throw fail"> | 134 | 134 | Error [ERR_TEST_FAILURE]: thrown from subtest sync throw fail | 135 | | - at TestContext.<anonymous> (<project-root>/test/fixtures/test-runner/output/output.js:125:11) | 136 | | - at <node-internal-frames> { | | 135 | + at TestContext.<anonymous> (<project-root>/test/fixtures/test-runner/output/output.js:125:11) { | 137 | 136 | code: 'ERR_TEST_FAILURE', | 138 | 137 | failureType: 'testCodeFailure', | 139 | 138 | cause: Error: thrown from subtest sync throw fail | @@ -229,8 +228,7 @@ Error [ERR_TEST_FAILURE]: thrown from subtest sync throw fail | 229 | 228 | <testcase name="callback called twice" time="*" classname="test" file="*" failure="callback invoked multiple times"> | 230 | 229 | <failure type="multipleCallbackInvocations" message="callback invoked multiple times"> | 231 | 230 | Error [ERR_TEST_FAILURE]: callback invoked multiple times | 232 | | - at TestContext.<anonymous> (<project-root>/test/fixtures/test-runner/output/output.js:272:3) | 233 | | - at <node-internal-frames> { | | 231 | + at TestContext.<anonymous> (<project-root>/test/fixtures/test-runner/output/output.js:272:3) { | 234 | 232 | code: 'ERR_TEST_FAILURE', | 235 | 233 | failureType: 'multipleCallbackInvocations', | 236 | 234 | cause: 'callback invoked multiple times' | @@ -292,8 +290,7 @@ Error [ERR_TEST_FAILURE]: thrown from callback async throw | 292 | 290 | <testcase name="sync throw fails at first" time="*" classname="subtest sync throw fails" file="*" failure="thrown from subtest sync throw fails at first"> | 293 | 291 | <failure type="testCodeFailure" message="thrown from subtest sync throw fails at first"> | 294 | 292 | Error [ERR_TEST_FAILURE]: thrown from subtest sync throw fails at first | 295 | | - at TestContext.<anonymous> (<project-root>/test/fixtures/test-runner/output/output.js:334:11) | 296 | | - at <node-internal-frames> { | | 293 | + at TestContext.<anonymous> (<project-root>/test/fixtures/test-runner/output/output.js:334:11) { | 297 | 294 | code: 'ERR_TEST_FAILURE', | 298 | 295 | failureType: 'testCodeFailure', | 299 | 296 | cause: Error: thrown from subtest sync throw fails at first | |
Collapse file Copy file name to clipboardExpand all lines: test/fixtures/test-runner/output/output.snapshot -1Lines changed: 0 additions & 1 deletion | Original file line number | Diff line number | Diff line change |
|---|
@@ -457,7 +457,6 @@ not ok 50 - callback called twice | 457 | 457 | code: 'ERR_TEST_FAILURE' | 458 | 458 | stack: |- | 459 | 459 | TestContext.<anonymous> (<project-root>/test/fixtures/test-runner/output/output.js:272:3) | 460 | | - <node-internal-frames> | 461 | 460 | ... | 462 | 461 | # Subtest: callback called twice in different ticks | 463 | 462 | ok 51 - callback called twice in different ticks | |
Collapse file Copy file name to clipboardExpand all lines: test/fixtures/test-runner/output/output_cli.snapshot -1Lines changed: 0 additions & 1 deletion | Original file line number | Diff line number | Diff line change |
|---|
@@ -457,7 +457,6 @@ not ok 50 - callback called twice | 457 | 457 | code: 'ERR_TEST_FAILURE' | 458 | 458 | stack: |- | 459 | 459 | TestContext.<anonymous> (<project-root>/test/fixtures/test-runner/output/output.js:272:3) | 460 | | - <node-internal-frames> | 461 | 460 | ... | 462 | 461 | # Subtest: callback called twice in different ticks | 463 | 462 | ok 51 - callback called twice in different ticks | |
Collapse file Copy file name to clipboard +22Lines changed: 22 additions & 0 deletions | Original file line number | Diff line number | Diff line change |
|---|
| | 1 | +// Flags: --expose-internals | | 2 | +'use strict'; | | 3 | + | | 4 | +// The test runner tracks which test owns the current async context with | | 5 | +// AsyncLocalStorage, so it must not install any async_hooks. | | 6 | + | | 7 | +const common = require('../common'); | | 8 | +const assert = require('assert'); | | 9 | +const { setTimeout } = require('timers/promises'); | | 10 | +const { enabledHooksExist } = require('internal/async_hooks'); | | 11 | +const { test } = require('node:test'); | | 12 | + | | 13 | +test('no async hooks are enabled', common.mustCall(async (t) => { | | 14 | + assert.strictEqual(enabledHooksExist(), false); | | 15 | + | | 16 | + await t.test('subtest', common.mustCall(async () => { | | 17 | + await setTimeout(1); | | 18 | + assert.strictEqual(enabledHooksExist(), false); | | 19 | + })); | | 20 | + | | 21 | + assert.strictEqual(enabledHooksExist(), false); | | 22 | +})); |
|