From 5d39974057cdf4eec456219dd51497e8faf95897 Mon Sep 17 00:00:00 2001 From: JckXia Date: Fri, 23 Dec 2022 16:24:03 -0500 Subject: [PATCH 1/2] test: Add unit test covg for callbackscopes --- test/callbackscope.cc | 17 ++++++++++++++++- test/callbackscope.js | 9 ++++++--- 2 files changed, 22 insertions(+), 4 deletions(-) diff --git a/test/callbackscope.cc b/test/callbackscope.cc index 5cfa96a87..2f3120e4e 100644 --- a/test/callbackscope.cc +++ b/test/callbackscope.cc @@ -3,6 +3,7 @@ using namespace Napi; #if (NAPI_VERSION > 2) + namespace { static void RunInCallbackScope(const CallbackInfo& info) { @@ -12,11 +13,25 @@ static void RunInCallbackScope(const CallbackInfo& info) { callback.Call({}); } -} // end anonymous namespace +static void RunInCallbackScopeFromExisting(const CallbackInfo& info) { + Function callback = info[0].As(); + Env env = info.Env(); + + AsyncContext ctx(env, "existing_callback_scope_test"); + napi_callback_scope scope; + napi_open_callback_scope(env, Object::New(env), ctx, &scope); + + CallbackScope existingScope(env, scope); + callback.Call({}); +} + +} // namespace Object InitCallbackScope(Env env) { Object exports = Object::New(env); exports["runInCallbackScope"] = Function::New(env, RunInCallbackScope); + exports["runInPreExistingCbScope"] = + Function::New(env, RunInCallbackScopeFromExisting); return exports; } #endif diff --git a/test/callbackscope.js b/test/callbackscope.js index 54a3844df..cafb180ca 100644 --- a/test/callbackscope.js +++ b/test/callbackscope.js @@ -24,7 +24,7 @@ function test (binding) { let insideHook = false; const hook = asyncHooks.createHook({ init (asyncId, type, triggerAsyncId, resource) { - if (id === undefined && type === 'callback_scope_test') { + if (id === undefined && (type === 'callback_scope_test' || type === 'existing_callback_scope_test')) { id = asyncId; } }, @@ -39,8 +39,11 @@ function test (binding) { return new Promise(resolve => { binding.callbackscope.runInCallbackScope(function () { assert(insideHook); - hook.disable(); - resolve(); + binding.callbackscope.runInPreExistingCbScope(function () { + assert(insideHook); + hook.disable(); + resolve(); + }); }); }); } From 7b9fdab5c7b4dda25a7cf1935699b262f37854df Mon Sep 17 00:00:00 2001 From: JckXia Date: Fri, 23 Dec 2022 16:30:02 -0500 Subject: [PATCH 2/2] test: Minor fix --- test/callbackscope.cc | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/test/callbackscope.cc b/test/callbackscope.cc index 2f3120e4e..9554a731a 100644 --- a/test/callbackscope.cc +++ b/test/callbackscope.cc @@ -1,5 +1,5 @@ +#include "assert.h" #include "napi.h" - using namespace Napi; #if (NAPI_VERSION > 2) @@ -22,6 +22,8 @@ static void RunInCallbackScopeFromExisting(const CallbackInfo& info) { napi_open_callback_scope(env, Object::New(env), ctx, &scope); CallbackScope existingScope(env, scope); + assert(existingScope.Env() == env); + callback.Call({}); }