...
1
16
17 package consistenthash
18
19 import (
20 "fmt"
21 "strconv"
22 "testing"
23 )
24
25 func TestHashing(t *testing.T) {
26
27
28
29 hash := New(3, func(key []byte) uint32 {
30 i, err := strconv.Atoi(string(key))
31 if err != nil {
32 panic(err)
33 }
34 return uint32(i)
35 })
36
37
38
39 hash.Add("6", "4", "2")
40
41 testCases := map[string]string{
42 "2": "2",
43 "11": "2",
44 "23": "4",
45 "27": "2",
46 }
47
48 for k, v := range testCases {
49 if hash.Get(k) != v {
50 t.Errorf("Asking for %s, should have yielded %s", k, v)
51 }
52 }
53
54
55 hash.Add("8")
56
57
58 testCases["27"] = "8"
59
60 for k, v := range testCases {
61 if hash.Get(k) != v {
62 t.Errorf("Asking for %s, should have yielded %s", k, v)
63 }
64 }
65
66 }
67
68 func TestConsistency(t *testing.T) {
69 hash1 := New(1, nil)
70 hash2 := New(1, nil)
71
72 hash1.Add("Bill", "Bob", "Bonny")
73 hash2.Add("Bob", "Bonny", "Bill")
74
75 if hash1.Get("Ben") != hash2.Get("Ben") {
76 t.Errorf("Fetching 'Ben' from both hashes should be the same")
77 }
78
79 hash2.Add("Becky", "Ben", "Bobby")
80
81 if hash1.Get("Ben") != hash2.Get("Ben") ||
82 hash1.Get("Bob") != hash2.Get("Bob") ||
83 hash1.Get("Bonny") != hash2.Get("Bonny") {
84 t.Errorf("Direct matches should always return the same entry")
85 }
86
87 }
88
89 func BenchmarkGet8(b *testing.B) { benchmarkGet(b, 8) }
90 func BenchmarkGet32(b *testing.B) { benchmarkGet(b, 32) }
91 func BenchmarkGet128(b *testing.B) { benchmarkGet(b, 128) }
92 func BenchmarkGet512(b *testing.B) { benchmarkGet(b, 512) }
93
94 func benchmarkGet(b *testing.B, shards int) {
95
96 hash := New(50, nil)
97
98 var buckets []string
99 for i := 0; i < shards; i++ {
100 buckets = append(buckets, fmt.Sprintf("shard-%d", i))
101 }
102
103 hash.Add(buckets...)
104
105 b.ResetTimer()
106
107 for i := 0; i < b.N; i++ {
108 hash.Get(buckets[i&(shards-1)])
109 }
110 }
111
View as plain text