|
| 1 | +'use strict'; |
| 2 | + |
| 3 | +const common = require('../common'); |
| 4 | +const assert = require('assert'); |
| 5 | +const { readFile } = require('fs'); |
| 6 | +const { |
| 7 | + createHook, |
| 8 | + executionAsyncResource, |
| 9 | + AsyncResource |
| 10 | +} = require('async_hooks'); |
| 11 | + |
| 12 | +// Ignore any asyncIds created before our hook is active. |
| 13 | +let firstSeenAsyncId = -1; |
| 14 | +const idResMap = new Map(); |
| 15 | +const numExpectedCalls = 5; |
| 16 | + |
| 17 | +createHook({ |
| 18 | + init: common.mustCallAtLeast( |
| 19 | + (asyncId, type, triggerId, resource) => { |
| 20 | + if (firstSeenAsyncId === -1) { |
| 21 | + firstSeenAsyncId = asyncId; |
| 22 | + } |
| 23 | + assert.ok(idResMap.get(asyncId) === undefined); |
| 24 | + idResMap.set(asyncId, resource); |
| 25 | + }, numExpectedCalls), |
| 26 | + before(asyncId) { |
| 27 | + if (asyncId >= firstSeenAsyncId) { |
| 28 | + beforeHook(asyncId); |
| 29 | + } |
| 30 | + }, |
| 31 | + after(asyncId) { |
| 32 | + if (asyncId >= firstSeenAsyncId) { |
| 33 | + afterHook(asyncId); |
| 34 | + } |
| 35 | + } |
| 36 | +}).enable(); |
| 37 | + |
| 38 | +const beforeHook = common.mustCallAtLeast( |
| 39 | + (asyncId) => { |
| 40 | + const res = idResMap.get(asyncId); |
| 41 | + assert.ok(res !== undefined); |
| 42 | + const execRes = executionAsyncResource(); |
| 43 | + assert.ok(execRes === res, 'resource mismatch in before'); |
| 44 | + }, numExpectedCalls); |
| 45 | + |
| 46 | +const afterHook = common.mustCallAtLeast( |
| 47 | + (asyncId) => { |
| 48 | + const res = idResMap.get(asyncId); |
| 49 | + assert.ok(res !== undefined); |
| 50 | + const execRes = executionAsyncResource(); |
| 51 | + assert.ok(execRes === res, 'resource mismatch in after'); |
| 52 | + }, numExpectedCalls); |
| 53 | + |
| 54 | +const res = new AsyncResource('TheResource'); |
| 55 | +const initRes = idResMap.get(res.asyncId()); |
| 56 | +assert.ok(initRes === res, 'resource mismatch in init'); |
| 57 | +res.runInAsyncScope(common.mustCall(() => { |
| 58 | + const execRes = executionAsyncResource(); |
| 59 | + assert.ok(execRes === res, 'resource mismatch in cb'); |
| 60 | +})); |
| 61 | + |
| 62 | +readFile(__filename, common.mustCall()); |
0 commit comments