-
Notifications
You must be signed in to change notification settings - Fork 0
/
cashing_test.go
95 lines (65 loc) · 2.55 KB
/
cashing_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
package cashing
import (
"testing"
"github.com/stretchr/testify/assert"
)
type CustomString string
func (cs CustomString) String() string {
return string(cs)
}
func TestAddNode(t *testing.T) {
hashRing := NewHashRing[CustomString](3, nil)
hashRing.AddNode("node1")
hashRing.AddNode("node2")
hashRing.AddNode("node3")
assert.Equal(t, 3*hashRing.replicas, len(hashRing.nodes), "Expected %d nodes in the hash ring, got %d", 3*hashRing.replicas, len(hashRing.nodes))
}
func TestRemoveNode(t *testing.T) {
hashRing := NewHashRing[CustomString](3, nil)
hashRing.AddNode("node1")
hashRing.AddNode("node2")
hashRing.AddNode("node3")
hashRing.RemoveNode("node2")
assert.Equal(t, 2*hashRing.replicas, len(hashRing.nodes), "Expected %d nodes in the hash ring after removing node2, got %d", 2*hashRing.replicas, len(hashRing.nodes))
_, ok := hashRing.nodesMap[hashRing.hash("node2-0")]
assert.False(t, ok, "Node2 replica 0 should be removed from nodesMap")
}
func TestGetNode(t *testing.T) {
hashRing := NewHashRing[CustomString](3, nil)
hashRing.AddNode("node1")
hashRing.AddNode("node2")
hashRing.AddNode("node3")
key := "test"
node := hashRing.GetNode(key)
assert.NotEmpty(t, node, "GetNode should return a non-empty node for key '%s'", key)
err := hashRing.RemoveNode("node2")
assert.Nil(t, err, "Remove Node returned an error")
err = hashRing.RemoveNode("node9999")
assert.Error(t, err, "Remove non exixtent node should return an error")
newNode := hashRing.GetNode(key)
assert.NotEmpty(t, newNode, "GetNode should return a non-empty node for key '%s' after removing node2", key)
assert.NotEqual(t, node, newNode, "Nodes before and after removing node2 should be different")
}
func TestChangeHashFunction(t *testing.T) {
numTimesHashCalled := 0
customHashFunction := func(key string) uint32 {
hash := uint32(0)
for _, char := range key {
hash += uint32(char)
}
numTimesHashCalled++
return hash % 10
}
hashRing := NewHashRing[CustomString](1, customHashFunction)
hashRing.AddNode("node1")
hashRing.AddNode("node2")
hashRing.AddNode("node3")
key := "foobar"
node := hashRing.GetNode(key)
assert.NotEmpty(t, node, "GetNode should return a non-empty node for key '%s'", key)
hashRing.RemoveNode("node1")
newNode := hashRing.GetNode(key)
assert.NotEmpty(t, newNode, "GetNode should return a non-empty node for key '%s' after removing node2", key)
assert.NotEqual(t, node, newNode, "Nodes before and after removing node2 should be different")
assert.Equal(t, 6, numTimesHashCalled, "The hash function should have been called 4 times")
}