github.com/glide-im/glide@v1.6.0/pkg/hash/consisten_hash_test.go (about)

     1  package hash
     2  
     3  import (
     4  	"math/rand"
     5  	"strconv"
     6  	"testing"
     7  )
     8  
     9  func TestConsistentHash_Add(t *testing.T) {
    10  	c := NewConsistentHash()
    11  	_ = c.Add("A")
    12  	_ = c.Add("B")
    13  	_ = c.Add("C")
    14  	_ = c.Add("D")
    15  	_ = c.Add("E")
    16  	_ = c.Add("F")
    17  	_ = c.Add("G")
    18  
    19  	//for _, n := range hash.nodes {
    20  	//	t.Log(n.Val, n.hash, n.virtual)
    21  	//}
    22  
    23  	rates := map[string]int{
    24  		"A": 0,
    25  		"B": 0,
    26  		"C": 0,
    27  		"D": 0,
    28  		"E": 0,
    29  		"F": 0,
    30  		"G": 0,
    31  	}
    32  
    33  	count := 10000
    34  
    35  	for i := 0; i < count; i++ {
    36  		s := strconv.FormatInt(rand.Int63n(100000), 10)
    37  		nd, _ := c.Get(s)
    38  		r := rates[nd.Val]
    39  		rates[nd.Val] = r + 1
    40  	}
    41  
    42  	for k, v := range rates {
    43  		t.Log(k, v, int(float64(v)/float64(count)*float64(100)))
    44  	}
    45  }
    46  
    47  func TestConsistentHash_Remove(t *testing.T) {
    48  	c := NewConsistentHash()
    49  	_ = c.Add("A")
    50  	_ = c.Add("B")
    51  	_ = c.Add("C")
    52  	_ = c.Add("D")
    53  	_ = c.Add("E")
    54  	_ = c.Add("F")
    55  	//for _, n := range hash.nodes {
    56  	//	t.Log(n.Val, n.hash, n.virtual)
    57  	//}
    58  	e := c.Remove("A")
    59  	if e != nil {
    60  		t.Error(e)
    61  	}
    62  	//t.Log("=====================")
    63  	//for _, n := range hash.nodes {
    64  	//	t.Log(n.Val, n.hash, n.virtual)
    65  	//}
    66  }
    67  
    68  func TestAdd(t *testing.T) {
    69  	c := NewConsistentHash2(1)
    70  	_ = c.Add("A")
    71  	_ = c.Add("B")
    72  
    73  	for i := 0; i < 5; i++ {
    74  		s := strconv.FormatInt(int64(i), 10)
    75  		n, _ := c.Get(s)
    76  		t.Log(i, ":", n.Val)
    77  	}
    78  
    79  	t.Log("===================")
    80  	_ = c.Add("C")
    81  	for i := 0; i < 5; i++ {
    82  		s := strconv.FormatInt(int64(i), 10)
    83  		n, _ := c.Get(s)
    84  		t.Log(i, ":", n.Val)
    85  	}
    86  }