Tests for Ruby code

pull/862/head
Rick Carlino 2018-05-23 08:53:43 -05:00
parent fb26b24dab
commit 55e61b1132
5 changed files with 30 additions and 11 deletions

View File

@ -1,3 +1,7 @@
# Handles devices that spin out of control and send too many logs to the server.
# Class Hierarchy:
# ThrotllePolicy has => Rules creates => Violation
# Violation has => Rule has => TimePeriod
class ThrottlePolicy
attr_reader :rules
@ -7,7 +11,7 @@ class ThrottlePolicy
end
def track(unique_id, now = Time.now)
rules.each { |r| r.throttler.record_event(unique_id, now) }
rules.each { |r| r.time_period.record_event(unique_id, now) }
end
# If throttled, returns the timeperiod when device will be unthrottled
@ -15,7 +19,7 @@ class ThrottlePolicy
def is_throttled(unique_id)
rules
.map do |rule|
is_violation = rule.throttler.usage_count_for(unique_id) > rule.limit
is_violation = rule.time_period.usage_count_for(unique_id) > rule.limit
is_violation ? Violation.new(rule) : nil
end
.compact

View File

@ -1,10 +1,10 @@
class ThrottlePolicy
# A throttler object paired with a max limit
# A time_period object paired with a max limit
class Rule
attr_reader :throttler, :limit
attr_reader :time_period, :limit
def initialize(throttler, limit)
@throttler, @limit = throttler, limit
def initialize(time_period, limit)
@time_period, @limit = time_period, limit
end
end
end

View File

@ -7,7 +7,7 @@ class ThrottlePolicy
end
def ends_at
@rule.throttler.when_does_next_period_start?
@rule.time_period.when_does_next_period_start?
end
def <=>(other)
@ -15,7 +15,7 @@ class ThrottlePolicy
end
def timeframe
rule.throttler.time_unit
rule.time_period.time_unit
end
def limit

View File

@ -12,16 +12,16 @@ describe klass do
it "initializes" do
expect(policy.rules).to be
expect(policy.rules.map(&:limit).sort).to eq([1, 10, 100])
actual = policy.rules.map(&:throttler).map(&:time_unit).sort
actual = policy.rules.map(&:time_period).map(&:time_unit).sort
expected = [1.minute, 1.hour, 1.day]
expect(actual).to eq(expected)
end
it "tracks things" do
count1 = policy.rules.map(&:throttler).map{|t| t.usage_count_for(123)}
count1 = policy.rules.map(&:time_period).map{|t| t.usage_count_for(123)}
expect(count1).to eq([0, 0, 0])
5.times { policy.track(123, NOW + 1) }
count2 = policy.rules.map(&:throttler).map{|t| t.usage_count_for(123)}
count2 = policy.rules.map(&:time_period).map{|t| t.usage_count_for(123)}
expect(count2).to eq([5, 5, 5])
end

View File

@ -0,0 +1,15 @@
describe ThrottlePolicy::Violation do
violation = ThrottlePolicy::Violation
rule = ThrottlePolicy::Rule
time_period = ThrottlePolicy::TimePeriod
it 'is comparable' do
smaller = violation.new(rule.new(time_period.new(1.minute), 10))
bigger = violation.new(rule.new(time_period.new(1.day), 10))
medium = violation.new(rule.new(time_period.new(1.hour), 10))
violations = [medium, smaller, bigger]
result = violations.sort
expect(result.first).to be(smaller)
expect(result.last).to be(bigger)
end
end