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();
};
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 MockTimer = require('../fixtures/mock-timer');
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 TaskQueue(1000, 1000, 0);
// Simulate time passing with a stubbed timer
const simulatedTimeStart = Date.now();
bukkit._timer = {timeElapsed: () => Date.now() - simulatedTimeStart};
const mockTimer = new MockTimer();
bukkit._timer = mockTimer;
mockTimer.start();
const taskResults = [];
const promises = [];
@ -25,16 +26,26 @@ test('constructor', t => {
);
bukkit.cancelAll();
promises.push(
bukkit.do(() => taskResults.push('a'), 50).then(() =>
testCompare(t, bukkit._timer.timeElapsed(), '>=', 50, 'Costly task must wait')
),
bukkit.do(() => taskResults.push('b'), 10).then(() =>
testCompare(t, bukkit._timer.timeElapsed(), '>=', 60, 'Tasks must run in serial')
),
bukkit.do(() => taskResults.push('c'), 1).then(() =>
testCompare(t, bukkit._timer.timeElapsed(), '<', 80, 'Cheap task should run soon')
)
bukkit.do(() => taskResults.push('a'), 50).then(() => {
testCompare(t, bukkit._timer.timeElapsed(), '>=', 50, 'Costly task must wait');
}),
bukkit.do(() => taskResults.push('b'), 10).then(() => {
testCompare(t, bukkit._timer.timeElapsed(), '>=', 60, 'Tasks must run in serial');
}),
bukkit.do(() => taskResults.push('c'), 1).then(() => {
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(() => {
t.deepEqual(taskResults, [goodCancelMessage, 'a', 'b', 'c'], 'All tasks must run in correct order');
});