Use MockTimer for TaskQueue tests

This commit is contained in:
Christopher Willis-Ford 2019-02-07 16:31:36 -08:00
parent 7f80fe17b3
commit 46a1ae83a0
2 changed files with 25 additions and 14 deletions

View file

@ -154,7 +154,7 @@ class TaskQueue {
} }
resolve(); resolve();
}; };
this._timeout = timeout = setTimeout(onTimeout, estimatedWait); this._timeout = timeout = this._timer.setTimeout(onTimeout, estimatedWait);
}); });
} }
} }

View file

@ -1,16 +1,17 @@
const test = require('tap').skip; const test = require('tap').test;
const TaskQueue = require('../../src/util/task-queue'); const TaskQueue = require('../../src/util/task-queue');
const MockTimer = require('../fixtures/mock-timer');
const testCompare = require('../fixtures/test-compare'); const testCompare = require('../fixtures/test-compare');
test('constructor', t => { test('constructor', t => {
// Max tokens = 1000, refill 1000 tokens per second (1 per millisecond), and start with 0 tokens // Max tokens = 1000, refill 1000 tokens per second (1 per millisecond), and start with 0 tokens
const bukkit = new TaskQueue(1000, 1000, 0); const bukkit = new TaskQueue(1000, 1000, 0);
// Simulate time passing with a stubbed timer const mockTimer = new MockTimer();
const simulatedTimeStart = Date.now(); bukkit._timer = mockTimer;
bukkit._timer = {timeElapsed: () => Date.now() - simulatedTimeStart}; mockTimer.start();
const taskResults = []; const taskResults = [];
const promises = []; const promises = [];
@ -25,16 +26,26 @@ test('constructor', t => {
); );
bukkit.cancelAll(); bukkit.cancelAll();
promises.push( promises.push(
bukkit.do(() => taskResults.push('a'), 50).then(() => bukkit.do(() => taskResults.push('a'), 50).then(() => {
testCompare(t, bukkit._timer.timeElapsed(), '>=', 50, 'Costly task must wait') testCompare(t, bukkit._timer.timeElapsed(), '>=', 50, 'Costly task must wait');
), }),
bukkit.do(() => taskResults.push('b'), 10).then(() => bukkit.do(() => taskResults.push('b'), 10).then(() => {
testCompare(t, bukkit._timer.timeElapsed(), '>=', 60, 'Tasks must run in serial') testCompare(t, bukkit._timer.timeElapsed(), '>=', 60, 'Tasks must run in serial');
), }),
bukkit.do(() => taskResults.push('c'), 1).then(() => bukkit.do(() => taskResults.push('c'), 1).then(() => {
testCompare(t, bukkit._timer.timeElapsed(), '<', 80, 'Cheap task should run soon') testCompare(t, bukkit._timer.timeElapsed(), '<=', 80, 'Cheap task should run soon');
) })
); );
// advance 10 simulated milliseconds per JS tick
const step = () => {
mockTimer.advanceMockTime(10);
if (mockTimer.timeElapsed() < 100) {
global.setTimeout(step, 0);
}
};
step();
return Promise.all(promises).then(() => { return Promise.all(promises).then(() => {
t.deepEqual(taskResults, [goodCancelMessage, 'a', 'b', 'c'], 'All tasks must run in correct order'); t.deepEqual(taskResults, [goodCancelMessage, 'a', 'b', 'c'], 'All tasks must run in correct order');
}); });