-
Notifications
You must be signed in to change notification settings - Fork 1
/
hash_test.go
105 lines (97 loc) · 1.99 KB
/
hash_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
package balancer
import (
"sync"
"sync/atomic"
"testing"
)
func TestConsistentHash(t *testing.T) {
lb := NewConsistentHash()
item := lb.Select()
if item != nil {
t.Fatalf("hash expected nil, actual %s", item)
}
lb = NewConsistentHash(
&Choice{Item: "A"},
&Choice{Item: "B"},
&Choice{Item: "C"},
&Choice{Item: "D"},
)
item = lb.Select()
if item != "B" {
t.Fatalf("hash expected B, actual %s", item)
}
item = lb.Select()
if item != "B" {
t.Fatalf("hash expected B, actual %s", item)
}
item = lb.Select("192.168.1.100")
if item != "A" {
t.Fatalf("hash expected A, actual %s", item)
}
item = lb.Select("192.168.1.101")
if item != "C" {
t.Fatalf("hash expected C, actual %s", item)
}
item = lb.Select("192.168.1.102")
if item != "D" {
t.Fatalf("hash expected D, actual %s", item)
}
item = lb.Select("192.168.1.100")
if item != "A" {
t.Fatalf("hash expected A, actual %s", item)
}
item = lb.Select("2400:da00::6666")
if item != "C" {
t.Fatalf("hash expected C, actual %s", item)
}
for i := 0; i < 2000; i++ {
item := lb.Select("192.168.1.100")
if item != "A" {
t.Fatalf("hash expected A, actual %s", item)
}
}
nodes := []*Choice{
{Item: "X"},
{Item: "Y"},
}
ok := lb.Update(nodes)
if ok != true {
t.Fatal("hash update wrong")
}
item = lb.Select()
if item != "Y" {
t.Fatal("hash update wrong")
}
item = lb.Select()
if item != "Y" {
t.Fatal("hash update wrong")
}
}
func TestConsistentHash_C(t *testing.T) {
var c int64
nodes := []*Choice{
{Item: "A"},
{Item: "B"},
{Item: "C"},
{Item: "D"},
}
lb := NewConsistentHash(nodes...)
var wg sync.WaitGroup
for i := 0; i < 500; i++ {
wg.Add(1)
go func() {
defer wg.Done()
for j := 0; j < 2000; j++ {
switch lb.Select("192.168.1.7") {
case "C":
atomic.AddInt64(&c, 1)
default:
}
}
}()
}
wg.Wait()
if atomic.LoadInt64(&c) != 1000000 {
t.Fatalf("hash expected C == 1000000, actual C == %d, item: %s", atomic.LoadInt64(&c), lb.Select("192.168.1.7"))
}
}