From 636f0028a5333256f556f304a6174d9a7763aa41 Mon Sep 17 00:00:00 2001 From: Bob Zoller Date: Mon, 4 May 2015 14:34:19 -0700 Subject: [PATCH] fixes Worker.startTime closes #38 --- src/worker.coffee | 11 ++-------- test/librato.coffee | 4 +--- test/worker.test.coffee | 48 +++++++++++++++++++++++++++++++++++++++++ 3 files changed, 51 insertions(+), 12 deletions(-) create mode 100644 test/worker.test.coffee diff --git a/src/worker.coffee b/src/worker.coffee index b5369d9..b89e84a 100644 --- a/src/worker.coffee +++ b/src/worker.coffee @@ -28,15 +28,8 @@ class Worker # Give some structure to worker start times so when possible they will be in sync. @startTime: (period) -> - earliest = new Date(Date.now() + period) - # already on a whole minute - return earliest.valueOf() if earliest.getSeconds() is 0 - if period > 30 - # bump to whole minute - return earliest.valueOf() + (60 - earliest.getSeconds()) - else - # ensure sync to whole minute if minute is evenly divisible - return earliest.valueOf() + (period - (earliest.getSeconds() % period)) + now = Date.now() + return now + (period - (now % period)) module.exports = Worker diff --git a/test/librato.coffee b/test/librato.coffee index c1a33ba..ece3721 100644 --- a/test/librato.coffee +++ b/test/librato.coffee @@ -109,7 +109,7 @@ describe 'librato', -> {clock} = {} beforeEach -> - clock = sinon.useFakeTimers(new Date().getTime()) + clock = sinon.useFakeTimers(0) it 'sends data every 60 seconds', -> sinon.stub(librato, 'flush') @@ -128,5 +128,3 @@ describe 'librato', -> clock.tick(4000) expect(librato.flush.calledOnce).to.be true - afterEach -> - clock.restore() diff --git a/test/worker.test.coffee b/test/worker.test.coffee new file mode 100644 index 0000000..fbc96cd --- /dev/null +++ b/test/worker.test.coffee @@ -0,0 +1,48 @@ +require './support/test_helper' +Worker = require '../lib/worker' + +given_period = (period) -> + return { + returns: (expected) -> + it "given period #{period} returns #{expected}", -> + expect(Worker.startTime(period)).to.equal expected + } + +describe 'Worker', -> + + describe '.startTime', -> + {clock, period} = {} + + beforeEach -> + clock = sinon.useFakeTimers(0) + + describe 'at 00:00:00', -> + + given_period(60000).returns(60000) + given_period(30000).returns(30000) + given_period(1000).returns(1000) + + describe 'at 00:00:01', -> + beforeEach -> + clock.tick 1000 + + given_period(60000).returns(60000) + given_period(30000).returns(30000) + given_period(1000).returns(2000) + + describe 'at 00:00:30', -> + beforeEach -> + clock.tick 30000 + + given_period(60000).returns(60000) + given_period(30000).returns(60000) + given_period(1000).returns(31000) + + describe 'at 00:01:00.100', -> + beforeEach -> + clock.tick 60100 + + given_period(60000).returns(120000) + given_period(30000).returns(90000) + given_period(1000).returns(61000) +