11cb0ef41Sopenharmony_ci'use strict';
21cb0ef41Sopenharmony_ci// Flags: --expose-gc
31cb0ef41Sopenharmony_ci
41cb0ef41Sopenharmony_ciconst common = require('../../common');
51cb0ef41Sopenharmony_ciconst test_finalizer = require(`./build/${common.buildType}/test_finalizer`);
61cb0ef41Sopenharmony_ciconst assert = require('assert');
71cb0ef41Sopenharmony_ci
81cb0ef41Sopenharmony_ci// The goal of this test is to show that we can run "pure" finalizers in the
91cb0ef41Sopenharmony_ci// current JS loop tick. Thus, we do not use common.gcUntil function works
101cb0ef41Sopenharmony_ci// asynchronously using micro tasks.
111cb0ef41Sopenharmony_ci// We use IIFE for the obj scope instead of {} to be compatible with
121cb0ef41Sopenharmony_ci// non-V8 JS engines that do not support scoped variables.
131cb0ef41Sopenharmony_ci(() => {
141cb0ef41Sopenharmony_ci  const obj = {};
151cb0ef41Sopenharmony_ci  test_finalizer.addFinalizer(obj);
161cb0ef41Sopenharmony_ci})();
171cb0ef41Sopenharmony_ci
181cb0ef41Sopenharmony_cifor (let i = 0; i < 10; ++i) {
191cb0ef41Sopenharmony_ci  global.gc();
201cb0ef41Sopenharmony_ci  if (test_finalizer.getFinalizerCallCount() === 1) {
211cb0ef41Sopenharmony_ci    break;
221cb0ef41Sopenharmony_ci  }
231cb0ef41Sopenharmony_ci}
241cb0ef41Sopenharmony_ci
251cb0ef41Sopenharmony_ciassert.strictEqual(test_finalizer.getFinalizerCallCount(), 1);
261cb0ef41Sopenharmony_ci
271cb0ef41Sopenharmony_ci// The finalizer that access JS cannot run synchronously. They are run in the
281cb0ef41Sopenharmony_ci// next JS loop tick. Thus, we must use common.gcUntil.
291cb0ef41Sopenharmony_ciasync function runAsyncTests() {
301cb0ef41Sopenharmony_ci  // We do not use common.mustCall() because we want to see the finalizer
311cb0ef41Sopenharmony_ci  // called in response to GC and not as a part of env destruction.
321cb0ef41Sopenharmony_ci  let js_is_called = false;
331cb0ef41Sopenharmony_ci  // We use IIFE for the obj scope instead of {} to be compatible with
341cb0ef41Sopenharmony_ci  // non-V8 JS engines that do not support scoped variables.
351cb0ef41Sopenharmony_ci  (() => {
361cb0ef41Sopenharmony_ci    const obj = {};
371cb0ef41Sopenharmony_ci    test_finalizer.addFinalizerWithJS(obj, () => { js_is_called = true; });
381cb0ef41Sopenharmony_ci  })();
391cb0ef41Sopenharmony_ci  await common.gcUntil('ensure JS finalizer called',
401cb0ef41Sopenharmony_ci                       () => (test_finalizer.getFinalizerCallCount() === 2));
411cb0ef41Sopenharmony_ci  assert(js_is_called);
421cb0ef41Sopenharmony_ci}
431cb0ef41Sopenharmony_cirunAsyncTests();
44