Add tests for TokenBucket

This commit is contained in:
Christopher Willis-Ford 2018-08-31 12:38:06 -07:00
parent 28621c9860
commit 33e0197ad5
3 changed files with 48 additions and 2 deletions

View file

@ -117,8 +117,8 @@ class TokenBucket {
if (cost <= this._tokenCount) {
return Promise.resolve();
}
if (!(cost <= this._limit)) {
return Promise.reject(new Error('Task cost is greater than bucket limit'));
if (!(cost <= this._maxTokens)) {
return Promise.reject(new Error(`Task cost ${cost} is greater than bucket limit ${this._maxTokens}`));
}
return new Promise(resolve => {
const tokensNeeded = this._tokenCount - cost;

15
test/fixtures/test-compare.js vendored Normal file
View file

@ -0,0 +1,15 @@
const testCompare = (t, lhs, op, rhs, message) => {
const details = `Expected: ${lhs} ${op} ${rhs}`;
const extra = {details};
switch (op) {
case '<': return t.ok(lhs < rhs, message, extra);
case '<=': return t.ok(lhs <= rhs, message, extra);
case '===': return t.ok(lhs === rhs, message, extra);
case '!==': return t.ok(lhs !== rhs, message, extra);
case '>=': return t.ok(lhs >= rhs, message, extra);
case '>': return t.ok(lhs > rhs, message, extra);
default: return t.fail(`Unrecognized op: ${op}`);
}
};
module.exports = testCompare;

View file

@ -0,0 +1,31 @@
const test = require('tap').test;
const Timer = require('../../src/util/timer');
const TokenBucket = require('../../src/util/token-bucket');
const testCompare = require('../fixtures/test-compare');
test('constructor', t => {
// Max tokens = 1000, refill 1000 tokens per second (1 per millisecond), and start with 0 tokens
const bukkit = new TokenBucket(1000, 1000, 0);
const timer = new Timer();
timer.start();
const taskResults = [];
const promises = [];
promises.push(
bukkit.do(() => taskResults.push('a'), 100).then(() =>
testCompare(t, timer.timeElapsed(), '>=', 100, 'Costly task must wait')
),
bukkit.do(() => taskResults.push('b'), 0).then(() =>
testCompare(t, timer.timeElapsed(), '<', 150, 'Cheap task should run soon')
),
bukkit.do(() => taskResults.push('c'), 101).then(() =>
testCompare(t, timer.timeElapsed(), '>=', 200, 'Tasks must run in serial')
)
);
return Promise.all(promises).then(() => {
t.deepEqual(taskResults, ['a', 'b', 'c'], 'All tasks must run in correct order');
});
});