1'use strict';
2
3if (process.argv[2] === 'child') {
4  const common = require('../../common');
5  const test_general = require(`./build/${common.buildType}/test_general`);
6
7  // The second argument to `envCleanupWrap()` is an index into the global
8  // static string array named `env_cleanup_finalizer_messages` on the native
9  // side. A reverse mapping is reproduced here for clarity.
10  const finalizerMessages = {
11    'simple wrap': 0,
12    'wrap, removeWrap': 1,
13    'first wrap': 2,
14    'second wrap': 3,
15  };
16
17  // We attach the three objects we will test to `module.exports` to ensure they
18  // will not be garbage-collected before the process exits.
19
20  // Make sure the finalizer for a simple wrap will be called at env cleanup.
21  module.exports['simple wrap'] =
22    test_general.envCleanupWrap({}, finalizerMessages['simple wrap']);
23
24  // Make sure that a removed wrap does not result in a call to its finalizer at
25  // env cleanup.
26  module.exports['wrap, removeWrap'] =
27    test_general.envCleanupWrap({}, finalizerMessages['wrap, removeWrap']);
28  test_general.removeWrap(module.exports['wrap, removeWrap']);
29
30  // Make sure that only the latest attached version of a re-wrapped item's
31  // finalizer gets called at env cleanup.
32  module.exports['first wrap'] =
33    test_general.envCleanupWrap({}, finalizerMessages['first wrap']);
34  test_general.removeWrap(module.exports['first wrap']);
35  test_general.envCleanupWrap(module.exports['first wrap'],
36                              finalizerMessages['second wrap']);
37} else {
38  const assert = require('assert');
39  const { spawnSync } = require('child_process');
40
41  const child = spawnSync(process.execPath, [__filename, 'child'], {
42    stdio: [ process.stdin, 'pipe', process.stderr ],
43  });
44
45  // Grab the child's output and construct an object whose keys are the rows of
46  // the output and whose values are `true`, so we can compare the output while
47  // ignoring the order in which the lines of it were produced.
48  assert.deepStrictEqual(
49    child.stdout.toString().split(/\r\n|\r|\n/g).reduce((obj, item) =>
50      Object.assign(obj, item ? { [item]: true } : {}), {}), {
51      'finalize at env cleanup for simple wrap': true,
52      'finalize at env cleanup for second wrap': true,
53    });
54
55  // Ensure that the child exited successfully.
56  assert.strictEqual(child.status, 0);
57}
58