Skip to content

armgit / mocha

Public Imported from GitHub
0

☕️ Classic, reliable, trusted test framework for Node.js and the browser

add Runnable.globals(arr) method for per test global whitelist

Roman Shtylman1d24a15c845a
diff --git a/lib/runnable.js b/lib/runnable.js
index b34bf1e1..03b8792b 100644
--- a/lib/runnable.js
+++ b/lib/runnable.js
@@ -141,6 +141,16 @@ Runnable.prototype.resetTimeout = function(){
}, ms);
};
+/**
+ * Whitelist these globals for this test run
+ *
+ * @api private
+ */
+Runnable.prototype.globals = function(arr){
+ var self = this;
+ this._allowedGlobals = arr;
+};
+
/**
* Run the test and invoke `fn(err)`.
*
diff --git a/lib/runner.js b/lib/runner.js
index 6f7e28ca..ff01fee8 100644
--- a/lib/runner.js
+++ b/lib/runner.js
@@ -158,10 +158,15 @@ Runner.prototype.globals = function(arr){
Runner.prototype.checkGlobals = function(test){
if (this.ignoreLeaks) return;
var ok = this._globals;
+
var globals = this.globalProps();
var isNode = process.kill;
var leaks;
+ if (test) {
+ ok = ok.concat(test._allowedGlobals || []);
+ }
+
// check length - 2 ('errno' and 'location' globals)
if (isNode && 1 == ok.length - globals.length) return;
else if (2 == ok.length - globals.length) return;
diff --git a/test/runnable.js b/test/runnable.js
index 8e08af2c..bf4718e9 100644
--- a/test/runnable.js
+++ b/test/runnable.js
@@ -71,6 +71,16 @@ describe('Runnable(title, fn)', function(){
})
})
+ describe('#globals', function(){
+ it('should allow for whitelisting globals', function(done){
+ var test = new Runnable('foo', function(){});
+ test.async.should.be.equal(0);
+ test.sync.should.be.true;
+ test.globals(['foobar']);
+ test.run(done);
+ })
+ })
+
describe('.run(fn)', function(){
describe('when .pending', function(){
it('should not invoke the callback', function(done){
diff --git a/test/runner.js b/test/runner.js
index 54d574c9..499bbd2e 100644
--- a/test/runner.js
+++ b/test/runner.js
@@ -132,6 +132,39 @@ describe('Runner', function(){
});
runner.checkGlobals('im a test');
})
+
+ it('should respect per test whitelisted globals', function() {
+ var test = new Test('im a test about lions');
+ test.globals(['foo']);
+
+ suite.addTest(test);
+ var runner = new Runner(suite);
+
+ global.foo = 'bar';
+
+ // verify the test hasn't failed.
+ runner.checkGlobals(test);
+ test.should.not.have.key('state');
+
+ delete global.foo;
+ })
+
+ it('should respect per test whitelisted globals but still detect other leaks', function(done) {
+ var test = new Test('im a test about lions');
+ test.globals(['foo']);
+
+ suite.addTest(test);
+
+ global.foo = 'bar';
+ global.bar = 'baz';
+ runner.on('fail', function(test, err){
+ test.title.should.equal('im a test about lions');
+ err.message.should.equal('global leak detected: bar');
+ delete global.foo;
+ done();
+ });
+ runner.checkGlobals(test);
+ })
})
describe('.fail(test, err)', function(){