Skip to content

Commit

Permalink
test: add test for halfOpen state allowing only one fire()
Browse files Browse the repository at this point in the history
Refs: #119
  • Loading branch information
lance committed Dec 13, 2017
1 parent 04df6f7 commit 602a43c
Show file tree
Hide file tree
Showing 2 changed files with 54 additions and 0 deletions.
12 changes: 12 additions & 0 deletions test/common.js
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,17 @@ function timedFunction (ms) {
});
}

function timedFailingFunction (ms) {
return new Promise((resolve, reject) => {
const timer = setTimeout(() => {
reject(`Failed after ${ms}`);
}, ms);
if (typeof timer.unref === 'function') {
timer.unref();
}
});
}

function nonPromise () {
return 'foo';
}
Expand All @@ -49,6 +60,7 @@ module.exports = exports = {
passFail,
slowFunction,
timedFunction,
timedFailingFunction,
callbackFunction,
failedCallbackFunction,
nonPromise
Expand Down
42 changes: 42 additions & 0 deletions test/half-open-test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
'use strict';

const test = require('tape');
const opossum = require('../');
const { timedFailingFunction } = require('./common');

test('When half-open, the circuit only allows one request through', t => {
t.plan(12);
const options = {
errorThresholdPercentage: 1,
resetTimeout: 500
};

const breaker = opossum(timedFailingFunction, options);
breaker.fire(1)
.catch((e) => t.equals(e, 'Failed after 1'))
.then(() => {
t.ok(breaker.opened, 'breaker should be open');
t.notOk(breaker.pendingClose, 'breaker should not be pending close');
})
.then(() => {
setTimeout(() => {
t.ok(breaker.halfOpen, 'breaker should be halfOpen');
t.ok(breaker.pendingClose, 'breaker should be pending close');
breaker
.fire(500) // fail after a long time, letting possibly other fire()s to occur
.catch((e) => t.equals(e, 'Failed after 500', 'function should fail again'))
.then(() => {
t.ok(breaker.opened, 'breaker should be open again');
t.notOk(breaker.halfOpen, 'breaker should not be halfOpen');
t.notOk(breaker.pendingClose, 'breaker should not be pending close');
});
}, options.resetTimeout * 1.1);
});
// fire the breaker again, and be sure it fails as expected
breaker.fire(1)
.catch((e) => t.equals(e, 'Failed after 1'))
.then(() => {
t.ok(breaker.opened, 'breaker should be open');
t.notOk(breaker.pendingClose, 'breaker should not be pending close');
});
});

0 comments on commit 602a43c

Please sign in to comment.