-
Notifications
You must be signed in to change notification settings - Fork 8
/
counter_test.go
136 lines (123 loc) · 2.49 KB
/
counter_test.go
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
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
package counters
import (
"fmt"
"testing"
)
func TestWriteTo(t *testing.T) {
box := NewCounterBox()
box.GetCounter("test").Increment()
fmt.Println(box.String())
}
func TestIncrement(t *testing.T) {
box := NewCounterBox()
cnt := box.GetCounter("test")
cnt.Increment()
cnt.IncrementBy(7)
if v := box.GetCounter("test"); v.Value() != 8 {
t.Errorf("got %d, expected 8", v.Value())
}
}
func TestIncrementParallel(t *testing.T) {
box := NewCounterBox()
end := make(chan bool, 10)
for x := 0; x < 10; x++ {
go func() {
for y := 0; y < 100; y++ {
cnt := box.GetCounter("test")
cnt.Increment()
cnt.IncrementBy(3)
}
end <- true
}()
}
for i := 0; i < 10; {
if _, ok := <-end; ok {
i++
}
}
if v := box.GetCounter("test"); v.Value() != 4000 {
t.Errorf("got %d, expected 4000", v.Value())
}
}
func TestMax(t *testing.T) {
box := NewCounterBox()
r := box.GetMax("Olsztyn")
r.Set(5)
r.Set(10)
r.Set(7)
if v := box.GetMax("Olsztyn").Value(); v != 10 {
t.Errorf("Max, want: 10, got %d", v)
}
}
func TestPrefix(t *testing.T) {
box := NewCounterBox()
pref := box.WithPrefix("prefix:")
cnt := pref.GetCounter("test")
cnt.Increment()
cnt.IncrementBy(7)
if v := box.GetCounter("prefix:test"); v.Value() != 8 {
t.Errorf("got %d, expected 8", v.Value())
}
if v := pref.GetCounter("test"); v.Value() != 8 {
t.Errorf("got %d, expected 8", v.Value())
}
}
func BenchmarkCounters(b *testing.B) {
b.StopTimer()
e := make(chan bool)
c := NewCounterBox()
f := func(b *testing.B, c *CounterBox, e chan bool) {
for i := 0; i < b.N; i++ {
c.GetCounter("abc123").IncrementBy(5)
c.GetCounter("def456").IncrementBy(5)
c.GetCounter("ghi789").IncrementBy(5)
c.GetCounter("abc123").IncrementBy(5)
c.GetCounter("def456").IncrementBy(5)
c.GetCounter("ghi789").IncrementBy(5)
}
e <- true
}
b.StartTimer()
go f(b, c, e)
go f(b, c, e)
go f(b, c, e)
go f(b, c, e)
go f(b, c, e)
go f(b, c, e)
<-e
<-e
<-e
<-e
<-e
}
func BenchmarkCountersCached(b *testing.B) {
b.StopTimer()
e := make(chan bool)
c := NewCounterBox()
f := func(b *testing.B, c *CounterBox, e chan bool) {
x := c.GetCounter("abc123")
y := c.GetCounter("def456")
z := c.GetCounter("ghi789")
for i := 0; i < b.N; i++ {
x.IncrementBy(5)
y.IncrementBy(5)
z.IncrementBy(5)
x.IncrementBy(5)
y.IncrementBy(5)
z.IncrementBy(5)
}
e <- true
}
b.StartTimer()
go f(b, c, e)
go f(b, c, e)
go f(b, c, e)
go f(b, c, e)
go f(b, c, e)
go f(b, c, e)
<-e
<-e
<-e
<-e
<-e
}