-
-
Notifications
You must be signed in to change notification settings - Fork 512
/
Copy pathcallbackcontext-test.js
79 lines (70 loc) · 2.33 KB
/
callbackcontext-test.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
/*********************************************************************
* NAN - Native Abstractions for Node.js
*
* Copyright (c) 2018 NAN contributors
*
* MIT License <https://github.com/nodejs/nan/blob/master/LICENSE.md>
********************************************************************/
const bindingName = 'callbackcontext';
const version = process.versions.node.split('.');
if (version[0] < 9) {
console.log('1..0 # Skipped: ' + bindingName);
process.exit(0);
}
try {
require('async_hooks');
} catch (e) {
console.log('1..0 # Skipped: ' + bindingName);
process.exit(0);
}
const test = require('tap').test
, testRoot = require('path').resolve(__dirname, '..')
, delay = require('bindings')({ module_root: testRoot, bindings: bindingName }).delay
, asyncHooks = require('async_hooks');
test(bindingName, function (t) {
t.plan(7);
var resourceAsyncId;
var originalExecutionAsyncId;
var beforeCalled = false;
var afterCalled = false;
var destroyCalled = false;
var hooks = asyncHooks.createHook({
init: function(asyncId, type, triggerAsyncId, resource) {
if (type === 'nan:test.DelayRequest') {
resourceAsyncId = asyncId;
}
},
before: function(asyncId) {
if (asyncId === resourceAsyncId) {
beforeCalled = true;
}
},
after: function(asyncId) {
if (asyncId === resourceAsyncId) {
afterCalled = true;
}
},
destroy: function(asyncId) {
if (asyncId === resourceAsyncId) {
destroyCalled = true;
}
}
});
hooks.enable();
originalExecutionAsyncId = asyncHooks.executionAsyncId();
delay(1000, function() {
t.equal(asyncHooks.executionAsyncId(), resourceAsyncId,
'callback should have the correct execution context');
t.equal(asyncHooks.triggerAsyncId(), originalExecutionAsyncId,
'callback should have the correct trigger context');
t.ok(beforeCalled, 'before should have been called');
t.notOk(afterCalled, 'after should not have been called yet');
setTimeout(function() {
t.ok(afterCalled, 'after should have been called');
t.ok(destroyCalled, 'destroy should have been called');
t.equal(asyncHooks.triggerAsyncId(), resourceAsyncId,
'setTimeout should have been triggered by the async resource');
hooks.disable();
}, 1);
});
});