Specs / implementation for Throttler#when_does_next_period_start?
parent
6add1455c9
commit
ddd8c03ced
|
@ -32,6 +32,10 @@ class Throttler
|
|||
@entries[unique_id] || 0
|
||||
end
|
||||
|
||||
def when_does_next_period_start?(now = Time.now)
|
||||
Time.at(current_period * time_unit_in_seconds.to_i) + time_unit_in_seconds
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
def reset_everything(now)
|
||||
|
|
|
@ -1,11 +1,11 @@
|
|||
require "spec_helper"
|
||||
|
||||
describe Throttler do
|
||||
NOW = Time.new("2018-05-18T09:38:02.259-05:00")
|
||||
let(:stub_time) { Time.new(2018, 5, 18, 9, 38, 2) }
|
||||
|
||||
it "sets a time unit window size" do
|
||||
expected_time_period = 25246440
|
||||
one_min = Throttler.new(1.minute, NOW)
|
||||
one_min = Throttler.new(1.minute, stub_time)
|
||||
|
||||
expect(one_min.current_period).to eq(expected_time_period)
|
||||
expect(one_min.time_unit_in_seconds).to eq(60)
|
||||
|
@ -13,23 +13,31 @@ describe Throttler do
|
|||
end
|
||||
|
||||
it "increments the count" do
|
||||
t = Throttler.new(1.minute, NOW)
|
||||
t = Throttler.new(1.minute, stub_time)
|
||||
uid = 123
|
||||
|
||||
# Ignore events from the past.
|
||||
t.record_event(uid, NOW - 90)
|
||||
t.record_event(uid, stub_time - 90)
|
||||
expect(t.usage_count_for(uid)).to eq(0)
|
||||
|
||||
# Record events from the present
|
||||
t.record_event(uid, NOW + 30)
|
||||
t.record_event(uid, stub_time + 30)
|
||||
expect(t.usage_count_for(uid)).to eq(1)
|
||||
|
||||
# Keep recording events from the present
|
||||
t.record_event(uid, NOW + 31)
|
||||
t.record_event(uid, stub_time + 31)
|
||||
expect(t.usage_count_for(uid)).to eq(2)
|
||||
|
||||
# Invalidate cache when time window passes
|
||||
t.record_event(uid, NOW + 75)
|
||||
t.record_event(uid, stub_time + 75)
|
||||
expect(t.usage_count_for(uid)).to eq(0)
|
||||
end
|
||||
|
||||
it "tells you when the next time period starts" do
|
||||
one_hour = Throttler.new(1.hour, stub_time)
|
||||
next_hour = one_hour.when_does_next_period_start?(stub_time)
|
||||
expect(next_hour).to be_kind_of(Time)
|
||||
expect(next_hour.hour).to be(stub_time.hour + 1)
|
||||
expect(next_hour.min).to be(0)
|
||||
end
|
||||
end
|
||||
|
|
Loading…
Reference in New Issue