-
Notifications
You must be signed in to change notification settings - Fork 0
/
window_counter_spec.rb
100 lines (84 loc) · 2.66 KB
/
window_counter_spec.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
require File.expand_path(File.join(File.dirname(__FILE__), '..', 'spec_helper'))
describe QueueStick::WindowCounter do
describe "initialize" do
it "should take a name and time window in minutes for the counter" do
lambda {
QueueStick::WindowCounter.new(:my_counter, 5)
}.should_not raise_error(ArgumentError)
end
it "should raise an error if a nil name is provided" do
lambda {
QueueStick::WindowCounter.new(nil, nil)
}.should raise_error(ArgumentError)
end
it "should raise an error if a time window is not provided" do
lambda {
QueueStick::WindowCounter.new(:name, nil)
}.should raise_error(ArgumentError)
end
end
describe "name" do
it "should return the correct name" do
counter = QueueStick::WindowCounter.new(:test, 5)
counter.name.should == :test
end
end
describe "count" do
it "should be zero at construction" do
counter = QueueStick::WindowCounter.new(:test, 5)
counter.count.should == 0
end
# see lighthouse ticket #11
it "should not flip the count back to 0 randomly with multiple threads contending" do
counter = QueueStick::WindowCounter.new(:test, 1)
threads = []
# 16 increments, 4 threads
4.times do
threads << Thread.new(counter) do |c|
4.times do
c.count
c.increment!
c.count
end
end
end
threads.each { |thread| thread.join }
counter.count.should == 16
end
end
describe "increment!" do
before(:each) do
@counter = QueueStick::WindowCounter.new(:test, 3)
end
it "should increment the counter by one, default" do
lambda {
@counter.increment!
}.should change(@counter, :count).by(1)
end
it "should increment the counter by the amount given" do
lambda {
@counter.increment!(10)
}.should change(@counter, :count).by(10)
end
it "should only maintain a count for the last X minutes" do
Time.stub!(:now).
and_return(Time.mktime(2009, 5, 18, 22, 30, 0, 0))
@counter.increment!(5)
@counter.count.should == 5
Time.stub!(:now).
and_return(Time.mktime(2009, 5, 18, 22, 31, 0, 0))
@counter.increment!(3)
@counter.count.should == 8
Time.stub!(:now).
and_return(Time.mktime(2009, 5, 18, 22, 33, 30, 0))
@counter.count.should == 3
@counter.increment!(10)
@counter.count.should == 13
@counter.increment!(20)
@counter.count.should == 33
Time.stub!(:now).
and_return(Time.mktime(2009, 5, 18, 22, 37, 31, 0))
@counter.count.should == 0
end
end
end