Skip to content

Commit

Permalink
test: add unit test covg for callbackscopes
Browse files Browse the repository at this point in the history
PR-URL: #1262
Reviewed-By: Michael Dawson <midawson@redhat.com
  • Loading branch information
JckXia authored and mhdawson committed Jan 13, 2023
1 parent b11e4de commit 0213134
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 5 deletions.
21 changes: 19 additions & 2 deletions test/callbackscope.cc
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
#include "assert.h"
#include "napi.h"

using namespace Napi;

#if (NAPI_VERSION > 2)

namespace {

static void RunInCallbackScope(const CallbackInfo& info) {
Expand All @@ -12,11 +13,27 @@ static void RunInCallbackScope(const CallbackInfo& info) {
callback.Call({});
}

} // end anonymous namespace
static void RunInCallbackScopeFromExisting(const CallbackInfo& info) {
Function callback = info[0].As<Function>();
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);
assert(existingScope.Env() == env);

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
9 changes: 6 additions & 3 deletions test/callbackscope.js
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}
},
Expand All @@ -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();
});
});
});
}

0 comments on commit 0213134

Please sign in to comment.