You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 

51 lines
1.1 KiB

package deliver
import (
"strconv"
"testing"
)
func TestConsistentHashPicker(t *testing.T) {
var nodes []*PickNode
var hits = make(map[string]int, 10)
for i := 0; i < 10; i++ {
node := &PickNode{
Key: "node-" + strconv.Itoa(i),
Weight: 10,
}
if i < 5 {
node.Weight = 5 // 遵循 weight 进行负载均衡
}
nodes = append(nodes, node)
hits[node.Key] = 0
}
picker := NewConsistentHashPicker(nodes, DefaultReplicas, DefaultSalt)
picker.Init()
for i := 0; i < 100000; i++ {
node1, ok1 := picker.Pick(strconv.Itoa(i))
node2, ok2 := picker.Pick(strconv.Itoa(i))
if !ok1 || !ok2 {
t.Error("pick non node")
}
if node1 != node2 {
t.Error("pick same key not same node")
}
hits[node1.Key]++
}
for nodeKey, hit := range hits {
if hit == 0 {
t.Errorf("node %s not picked", nodeKey)
}
}
node1, same1, ok1 := picker.PickOffset("100", 1)
node2, same2, ok2 := picker.PickOffset("100", 1)
if !ok1 || !ok2 {
t.Error("pick non node")
}
if node1 != node2 || same1 != same2 {
t.Error("pick same key not same node")
}
}