From 22e0b090a38de826b30ef607a4bcfa586fc605fa Mon Sep 17 00:00:00 2001
From: cjihrig <cjihrig@gmail.com>
Date: Mon, 15 Apr 2019 09:31:10 -0400
Subject: [PATCH] test: allow leaked global check to be skipped

This simplifies the process of running tests on different
versions of Node, which might have a different set of
global variables.
---
 test/common/index.js         | 38 +++++++++++++++++++-----------------
 test/parallel/test-common.js | 11 +++++++++++
 2 files changed, 31 insertions(+), 18 deletions(-)

diff --git a/test/common/index.js b/test/common/index.js
index 8c61fdc5cfcda1..278f8b6561a3dd 100644
--- a/test/common/index.js
+++ b/test/common/index.js
@@ -277,34 +277,36 @@ if (global.gc) {
   knownGlobals.push(global.gc);
 }
 
-if (process.env.NODE_TEST_KNOWN_GLOBALS) {
-  const knownFromEnv = process.env.NODE_TEST_KNOWN_GLOBALS.split(',');
-  allowGlobals(...knownFromEnv);
-}
-
 function allowGlobals(...whitelist) {
   knownGlobals = knownGlobals.concat(whitelist);
 }
 
-function leakedGlobals() {
-  const leaked = [];
+if (process.env.NODE_TEST_KNOWN_GLOBALS !== '0') {
+  if (process.env.NODE_TEST_KNOWN_GLOBALS) {
+    const knownFromEnv = process.env.NODE_TEST_KNOWN_GLOBALS.split(',');
+    allowGlobals(...knownFromEnv);
+  }
 
-  for (const val in global) {
-    if (!knownGlobals.includes(global[val])) {
-      leaked.push(val);
+  function leakedGlobals() {
+    const leaked = [];
+
+    for (const val in global) {
+      if (!knownGlobals.includes(global[val])) {
+        leaked.push(val);
+      }
     }
+
+    return leaked;
   }
 
-  return leaked;
+  process.on('exit', function() {
+    const leaked = leakedGlobals();
+    if (leaked.length > 0) {
+      assert.fail(`Unexpected global(s) found: ${leaked.join(', ')}`);
+    }
+  });
 }
 
-process.on('exit', function() {
-  const leaked = leakedGlobals();
-  if (leaked.length > 0) {
-    assert.fail(`Unexpected global(s) found: ${leaked.join(', ')}`);
-  }
-});
-
 const mustCallChecks = [];
 
 function runCallChecks(exitCode) {
diff --git a/test/parallel/test-common.js b/test/parallel/test-common.js
index 62f4eb050fb5d5..ad5680bc2f8175 100644
--- a/test/parallel/test-common.js
+++ b/test/parallel/test-common.js
@@ -35,6 +35,17 @@ const { execFile } = require('child_process');
   }));
 }
 
+// Test for disabling leaked global detection
+{
+  const p = fixtures.path('leakedGlobal.js');
+  execFile(process.execPath, [p], {
+    env: { ...process.env, NODE_TEST_KNOWN_GLOBALS: 0 }
+  }, common.mustCall((err, stdout, stderr) => {
+    assert.strictEqual(err, null);
+    assert.strictEqual(stderr.trim(), '');
+  }));
+}
+
 // common.mustCall() tests
 assert.throws(function() {
   common.mustCall(function() {}, 'foo');