-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcounter_internal_test.go
124 lines (116 loc) · 2.32 KB
/
counter_internal_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
package hops
import (
"reflect"
"testing"
"time"
)
func TestMoveWindow(t *testing.T) {
var newCounter = func() *Counter {
c := NewCounter(5, time.Second)
c.prevCounts = []uint32{1, 2, 3, 4}
c.crtCount = 99
return c
}
tests := map[string]struct {
timeUnitsFromWindowEnd int
expectedPrevCounts []uint32
}{
"one_unit": {
1,
[]uint32{2, 3, 4, 99},
},
"two_units": {
2,
[]uint32{3, 4, 99, 0},
},
"keep_only_current_unit": {
4,
[]uint32{99, 0, 0, 0},
},
"just_outside_of_the_window": {
5,
[]uint32{0, 0, 0, 0},
},
"way_outside_of_the_window": {
10,
[]uint32{0, 0, 0, 0},
},
}
for name, tt := range tests {
t.Run(name, func(t *testing.T) {
c := newCounter()
windowEnd := c.windowStart.Add(c.WindowSize - c.Unit)
// Simulate a couple of time units have passed since the counter was last used
unitsPassed := time.Duration(tt.timeUnitsFromWindowEnd) * c.Unit
c.moveWindow(windowEnd.Add(unitsPassed))
if !reflect.DeepEqual(c.prevCounts, tt.expectedPrevCounts) {
t.Errorf("Old counts were not removed: expected: %v, got: %v",
tt.expectedPrevCounts, c.prevCounts)
}
if c.crtCount != 0 {
t.Errorf("Current count was not reset. Got: %d", c.crtCount)
}
})
}
}
func TestLeftShiftInPlace(t *testing.T) {
tests := map[string]struct {
shift int
slice []uint32
want []uint32
}{
"shift_one": {
1,
[]uint32{1, 2, 3, 4, 5},
[]uint32{2, 3, 4, 5, 0},
},
"shift_two": {
2,
[]uint32{1, 2, 3, 4, 5},
[]uint32{3, 4, 5, 0, 0},
},
"all_elements_out": {
10,
[]uint32{1, 2, 3, 4, 5},
[]uint32{0, 0, 0, 0, 0},
},
"shift_by_slice_length": {
5,
[]uint32{1, 2, 3, 4, 5},
[]uint32{0, 0, 0, 0, 0},
},
"keep_the_rightmost_element": {
4,
[]uint32{1, 2, 3, 4, 5},
[]uint32{5, 0, 0, 0, 0},
},
"one_element_slice": {
1,
[]uint32{1},
[]uint32{0},
},
"empty_slice": {
1,
[]uint32{},
[]uint32{},
},
"no_shift": {
0,
[]uint32{1, 2, 3, 4, 5},
[]uint32{1, 2, 3, 4, 5},
},
"negative_shift": {
-3,
[]uint32{1, 2, 3, 4, 5},
[]uint32{1, 2, 3, 4, 5},
},
}
for name, tt := range tests {
t.Run(name, func(t *testing.T) {
leftShiftInPlace(tt.slice, tt.shift)
if !reflect.DeepEqual(tt.slice, tt.want) {
t.Errorf("expected: %v, got: %v", tt.want, tt.slice)
}
})
}
}