-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathround_robin_test.go
84 lines (67 loc) · 2.04 KB
/
round_robin_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
package balancer
import (
"testing"
)
func TestNewRoundRobin_EmptyList_ReturnsEmptyBalancer(t *testing.T) {
rr := NewRoundRobin[int](nil)
assertEqual(t, 0, rr.Next())
assertEqual(t, 0, len(rr.Elements()))
}
func TestRoundRobin_Next_ThreeElems_IteratesInOrderIncludingWrapping(t *testing.T) {
type idStruct struct{ ID int }
testElemOne := &idStruct{ID: 1}
testElemTwo := &idStruct{ID: 2}
testElemThree := &idStruct{ID: 3}
balancer := NewRoundRobin([]*idStruct{testElemOne, testElemTwo, testElemThree})
for i := 0; i < 100; i++ {
switch i % 3 {
case 0:
assertEqual(t, 1, balancer.Next().ID)
case 1:
assertEqual(t, 2, balancer.Next().ID)
case 2:
assertEqual(t, 3, balancer.Next().ID)
}
}
}
func TestRoundRobin_Next_Uint32Overflow_IteratesInOrderDespiteOverflow(t *testing.T) {
type idStruct struct{ ID int }
testElemOne := &idStruct{ID: 1}
testElemTwo := &idStruct{ID: 2}
testElemThree := &idStruct{ID: 3}
balancer := newRoundRobin([]*idStruct{testElemOne, testElemTwo, testElemThree})
ctr := uint32(4294967292) // max value for uint32 is 4294967295
balancer.ctr = &ctr
// get to the overflow
assertEqual(t, 2, balancer.Next().ID)
assertEqual(t, 3, balancer.Next().ID)
assertEqual(t, 1, balancer.Next().ID)
for i := 0; i < 100; i++ {
switch i % 3 {
case 0:
assertEqual(t, 1, balancer.Next().ID)
case 1:
assertEqual(t, 2, balancer.Next().ID)
case 2:
assertEqual(t, 3, balancer.Next().ID)
}
}
}
func TestRoundRobin_Elements_GetsAllElementsBack(t *testing.T) {
type idStruct struct{ ID int }
testElemOne := &idStruct{ID: 1}
testElemTwo := &idStruct{ID: 2}
testElemThree := &idStruct{ID: 3}
balancer := NewRoundRobin([]*idStruct{testElemOne, testElemTwo, testElemThree})
elems := balancer.Elements()
assertEqual(t, 3, len(elems))
assertEqual(t, 1, elems[0].ID)
assertEqual(t, 2, elems[1].ID)
assertEqual(t, 3, elems[2].ID)
}
func assertEqual[T comparable](t *testing.T, expected T, actual T) {
if expected != actual {
t.Helper()
t.Fatalf("Not equal! Expected %v but got %v", expected, actual)
}
}