github.com/insionng/yougam@v0.0.0-20170714101924-2bc18d833463/libraries/golang/groupcache/consistenthash/consistenthash_test.go (about) 1 /* 2 Copyright 2013 Google Inc. 3 4 Licensed under the Apache License, Version 2.0 (the "License"); 5 you may not use this file except in compliance with the License. 6 You may obtain a copy of the License at 7 8 http://www.apache.org/licenses/LICENSE-2.0 9 10 Unless required by applicable law or agreed to in writing, software 11 distributed under the License is distributed on an "AS IS" BASIS, 12 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 See the License for the specific language governing permissions and 14 limitations under the License. 15 */ 16 17 package consistenthash 18 19 import ( 20 "fmt" 21 "strconv" 22 "testing" 23 ) 24 25 func TestHashing(t *testing.T) { 26 27 // Override the hash function to return easier to reason about values. Assumes 28 // the keys can be converted to an integer. 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 // Given the above hash function, this will give replicas with "hashes": 38 // 2, 4, 6, 12, 14, 16, 22, 24, 26 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 // Adds 8, 18, 28 55 hash.Add("8") 56 57 // 27 should now map to 8. 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 }