-
Notifications
You must be signed in to change notification settings - Fork 276
/
counter_test.go
77 lines (62 loc) · 1.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
package counter_test
import (
"fmt"
"math"
"math/rand"
"testing"
"github.com/google/uuid"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/pomerium/pomerium/pkg/counter"
)
func stableRandomUUIDs(n int) []string {
r := rand.New(rand.NewSource(1234567890))
out := make([]string, 0, n)
for i := 0; i < n; i++ {
u, _ := uuid.NewRandomFromReader(r)
out = append(out, u.String())
}
return out
}
func TestStableRandomUUIDs(t *testing.T) {
t.Parallel()
assert.Equal(t, stableRandomUUIDs(20), stableRandomUUIDs(20))
}
func TestCounter(t *testing.T) {
t.Parallel()
limit := 1000
n := (limit * 8) / 10
for j := 0; j < 20; j++ {
t.Run(fmt.Sprint(j), func(t *testing.T) {
c := counter.New(uint(limit))
for _, id := range stableRandomUUIDs(n) {
c.Mark(id)
}
est := c.Count()
assert.LessOrEqual(t, math.Abs(float64(n)-float64(est)), math.Ceil(float64(n)*0.01))
})
}
}
func TestSerialize(t *testing.T) {
t.Parallel()
c := counter.New(counter.DefaultCap)
for _, id := range stableRandomUUIDs(20) {
c.Mark(id)
}
assert.EqualValues(t, 20, c.Count())
data, err := c.ToBinary()
require.NoError(t, err)
c2, err := counter.FromBinary(data)
require.NoError(t, err)
assert.EqualValues(t, 20, c2.Count())
}
func TestReset(t *testing.T) {
t.Parallel()
c := counter.New(counter.DefaultCap)
for _, id := range stableRandomUUIDs(20) {
c.Mark(id)
}
assert.EqualValues(t, 20, c.Count())
c.Reset()
assert.EqualValues(t, 0, c.Count())
}