1'use strict'; 2const common = require('../common'); 3 4// This test ensures async hooks are being properly called 5// when using async-await mechanics. This involves: 6// 1. Checking that all initialized promises are being resolved 7// 2. Checking that for each 'before' corresponding hook 'after' hook is called 8 9const assert = require('assert'); 10const initHooks = require('./init-hooks'); 11 12const util = require('util'); 13 14const sleep = util.promisify(setTimeout); 15// Either 'inited' or 'resolved' 16const promisesInitState = new Map(); 17// Either 'before' or 'after' AND asyncId must be present in the other map 18const promisesExecutionState = new Map(); 19 20const hooks = initHooks({ 21 oninit, 22 onbefore, 23 onafter, 24 ondestroy: null, // Intentionally not tested, since it will be removed soon 25 onpromiseResolve 26}); 27hooks.enable(); 28 29function oninit(asyncId, type) { 30 if (type === 'PROMISE') { 31 promisesInitState.set(asyncId, 'inited'); 32 } 33} 34 35function onbefore(asyncId) { 36 if (!promisesInitState.has(asyncId)) { 37 return; 38 } 39 promisesExecutionState.set(asyncId, 'before'); 40} 41 42function onafter(asyncId) { 43 if (!promisesInitState.has(asyncId)) { 44 return; 45 } 46 47 assert.strictEqual(promisesExecutionState.get(asyncId), 'before', 48 'after hook called for promise without prior call' + 49 'to before hook'); 50 assert.strictEqual(promisesInitState.get(asyncId), 'resolved', 51 'after hook called for promise without prior call' + 52 'to resolve hook'); 53 promisesExecutionState.set(asyncId, 'after'); 54} 55 56function onpromiseResolve(asyncId) { 57 assert(promisesInitState.has(asyncId), 58 'resolve hook called for promise without prior call to init hook'); 59 60 promisesInitState.set(asyncId, 'resolved'); 61} 62 63const timeout = common.platformTimeout(10); 64 65function checkPromisesInitState() { 66 for (const initState of promisesInitState.values()) { 67 // Promise should not be initialized without being resolved. 68 assert.strictEqual(initState, 'resolved'); 69 } 70} 71 72function checkPromisesExecutionState() { 73 for (const executionState of promisesExecutionState.values()) { 74 // Check for mismatch between before and after hook calls. 75 assert.strictEqual(executionState, 'after'); 76 } 77} 78 79process.on('beforeExit', common.mustCall(() => { 80 hooks.disable(); 81 hooks.sanityCheck('PROMISE'); 82 83 checkPromisesInitState(); 84 checkPromisesExecutionState(); 85})); 86 87async function asyncFunc() { 88 await sleep(timeout); 89} 90 91asyncFunc(); 92