-
Notifications
You must be signed in to change notification settings - Fork 1
/
swrr_test.go
93 lines (86 loc) · 1.84 KB
/
swrr_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
package balancer
import (
"sync"
"sync/atomic"
"testing"
)
func TestSmoothWeightedRoundRobin(t *testing.T) {
lb := NewSmoothWeightedRoundRobin()
item := lb.Select()
if item != nil {
t.Fatalf("swrr expected nil, actual %s", item)
}
lb = NewSmoothWeightedRoundRobin(
&Choice{Item: "A", Weight: 0},
&Choice{Item: "B", Weight: 1},
&Choice{Item: "C", Weight: 7},
&Choice{Item: "D", Weight: 2},
)
count := make(map[string]int)
for i := 0; i < 1000; i++ {
item := lb.Select()
count[item.(string)]++
}
if count["A"] != 0 || count["B"] != 100 || count["C"] != 700 || count["D"] != 200 {
t.Fatal("swrr wrong")
}
nodes := []*Choice{
{Item: "X", Weight: 0},
{Item: "Y", Weight: 1},
}
ok := lb.Update(nodes)
if ok != true {
t.Fatal("swrr update wrong")
}
item = lb.Select()
if item != "Y" {
t.Fatal("swrr update wrong")
}
}
func TestSmoothWeightedRoundRobin_C(t *testing.T) {
var (
a, b, c, d int64
wg sync.WaitGroup
mu sync.Mutex
)
nodes := []*Choice{
{Item: "A", Weight: 5},
{Item: "B", Weight: 1},
{Item: "C", Weight: 4},
{Item: "D", Weight: 0},
}
lb := NewSmoothWeightedRoundRobin(nodes...)
for i := 0; i < 500; i++ {
wg.Add(1)
go func() {
defer wg.Done()
for j := 0; j < 2000; j++ {
mu.Lock()
switch lb.Select() {
case "A":
atomic.AddInt64(&a, 1)
case "B":
atomic.AddInt64(&b, 1)
case "C":
atomic.AddInt64(&c, 1)
case "D":
atomic.AddInt64(&d, 1)
}
mu.Unlock()
}
}()
}
wg.Wait()
if atomic.LoadInt64(&a) != 500000 {
t.Fatal("swrr wrong: a", atomic.LoadInt64(&a))
}
if atomic.LoadInt64(&b) != 100000 {
t.Fatal("swrr wrong: b", atomic.LoadInt64(&b))
}
if atomic.LoadInt64(&c) != 400000 {
t.Fatal("swrr wrong: c", atomic.LoadInt64(&c))
}
if atomic.LoadInt64(&d) != 0 {
t.Fatal("swrr wrong: d", atomic.LoadInt64(&d))
}
}