From 46a1ae83a0446b684aec2ca859419cb9fff44ca0 Mon Sep 17 00:00:00 2001 From: Christopher Willis-Ford Date: Thu, 7 Feb 2019 16:31:36 -0800 Subject: [PATCH] Use MockTimer for TaskQueue tests --- src/util/task-queue.js | 2 +- test/unit/util_task-queue.js | 37 +++++++++++++++++++++++------------- 2 files changed, 25 insertions(+), 14 deletions(-) diff --git a/src/util/task-queue.js b/src/util/task-queue.js index db890e329..accddfbbb 100644 --- a/src/util/task-queue.js +++ b/src/util/task-queue.js @@ -154,7 +154,7 @@ class TaskQueue { } resolve(); }; - this._timeout = timeout = setTimeout(onTimeout, estimatedWait); + this._timeout = timeout = this._timer.setTimeout(onTimeout, estimatedWait); }); } } diff --git a/test/unit/util_task-queue.js b/test/unit/util_task-queue.js index ab8b5c42c..4dd68c3b5 100644 --- a/test/unit/util_task-queue.js +++ b/test/unit/util_task-queue.js @@ -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'); });