-
Notifications
You must be signed in to change notification settings - Fork 0
/
onceper_test.go
94 lines (86 loc) · 1.44 KB
/
onceper_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
package onceper_test
import (
"github.com/spartan0x117/onceper"
"testing"
)
func TestOncePerString(t *testing.T) {
o := onceper.New[string]()
var count int
f := func() {
count++
}
o.Do("foo", f)
o.Do("foo", f)
o.Do("bar", f)
o.Do("bar", f)
if count != 2 {
t.Errorf("count = %d, want 2", count)
}
}
func TestOncePerInt(t *testing.T) {
o := onceper.New[int]()
var count int
f := func() {
count++
}
o.Do(1, f)
o.Do(1, f)
o.Do(2, f)
o.Do(2, f)
if count != 2 {
t.Errorf("count = %d, want 2", count)
}
}
func TestOncePerStruct(t *testing.T) {
type S struct {
a int
b string
}
o := onceper.New[S]()
var count int
f := func() {
count++
}
o.Do(S{1, "foo"}, f)
o.Do(S{1, "foo"}, f)
o.Do(S{2, "bar"}, f)
o.Do(S{2, "bar"}, f)
if count != 2 {
t.Errorf("count = %d, want 2", count)
}
o.Do(S{1, "bar"}, f)
o.Do(S{1, "bar"}, f)
if count != 3 {
t.Errorf("count = %d, want 3", count)
}
}
func TestOncePerDoWith(t *testing.T) {
o := onceper.New[string]()
seen := make(map[string]int)
f := func(s string) {
seen[s] = seen[s] + 1
}
o.DoWith("foo", f)
o.DoWith("foo", f)
o.DoWith("bar", f)
o.DoWith("bar", f)
o.DoWith("baz", f)
o.DoWith("baz", f)
for k, v := range seen {
if v != 1 {
t.Errorf("count[%s] = %d, want 1", k, v)
}
}
}
func BenchmarkOncePer(b *testing.B) {
o := onceper.New[int]()
var count int
f := func() {
count++
}
b.RunParallel(func(pb *testing.PB) {
for pb.Next() {
o.Do(1, f)
}
})
}