-
Notifications
You must be signed in to change notification settings - Fork 582
/
Copy pathsampler_test.go
137 lines (127 loc) · 2.31 KB
/
sampler_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
137
//go:build !binary_log
// +build !binary_log
package zerolog
import (
"testing"
"time"
)
var samplers = []struct {
name string
sampler func() Sampler
total int
wantMin int
wantMax int
}{
{
"BasicSampler_1",
func() Sampler {
return &BasicSampler{N: 1}
},
100, 100, 100,
},
{
"BasicSampler_5",
func() Sampler {
return &BasicSampler{N: 5}
},
100, 20, 20,
},
{
"BasicSampler_0",
func() Sampler {
return &BasicSampler{N: 0}
},
100, 0, 0,
},
{
"RandomSampler",
func() Sampler {
return RandomSampler(5)
},
100, 10, 30,
},
{
"RandomSampler_0",
func() Sampler {
return RandomSampler(0)
},
100, 0, 0,
},
{
"BurstSampler",
func() Sampler {
return &BurstSampler{Burst: 20, Period: time.Second}
},
100, 20, 20,
},
{
"BurstSampler_0",
func() Sampler {
return &BurstSampler{Burst: 0, Period: time.Second}
},
100, 0, 0,
},
{
"BurstSamplerNext",
func() Sampler {
return &BurstSampler{Burst: 20, Period: time.Second, NextSampler: &BasicSampler{N: 5}}
},
120, 40, 40,
},
}
func TestSamplers(t *testing.T) {
for i := range samplers {
s := samplers[i]
t.Run(s.name, func(t *testing.T) {
sampler := s.sampler()
got := 0
for t := s.total; t > 0; t-- {
if sampler.Sample(0) {
got++
}
}
if got < s.wantMin || got > s.wantMax {
t.Errorf("%s.Sample(0) == true %d on %d, want [%d, %d]", s.name, got, s.total, s.wantMin, s.wantMax)
}
})
}
}
func BenchmarkSamplers(b *testing.B) {
for i := range samplers {
s := samplers[i]
b.Run(s.name, func(b *testing.B) {
sampler := s.sampler()
b.RunParallel(func(pb *testing.PB) {
for pb.Next() {
sampler.Sample(0)
}
})
})
}
}
func TestBurst(t *testing.T) {
sampler := &BurstSampler{Burst: 1, Period: time.Second}
t0 := time.Now()
now := t0
mockedTime := func() time.Time {
return now
}
TimestampFunc = mockedTime
defer func() { TimestampFunc = time.Now }()
scenario := []struct {
tm time.Time
want bool
}{
{t0, true},
{t0.Add(time.Second - time.Nanosecond), false},
{t0.Add(time.Second), true},
{t0.Add(time.Second + time.Nanosecond), false},
}
for i, step := range scenario {
now = step.tm
got := sampler.Sample(NoLevel)
if got != step.want {
t.Errorf("step %d (t=%s): expect %t got %t", i, step.tm, step.want, got)
}
}
}