github.com/cockroachdb/cockroach@v20.2.0-alpha.1+incompatible/pkg/kv/kvserver/replica_rankings_test.go (about) 1 // Copyright 2018 The Cockroach Authors. 2 // 3 // Use of this software is governed by the Business Source License 4 // included in the file licenses/BSL.txt. 5 // 6 // As of the Change Date specified in that file, in accordance with 7 // the Business Source License, use of this software will be governed 8 // by the Apache License, Version 2.0, included in the file 9 // licenses/APL.txt. 10 11 package kvserver 12 13 import ( 14 "math/rand" 15 "reflect" 16 "testing" 17 18 "github.com/cockroachdb/cockroach/pkg/roachpb" 19 "github.com/cockroachdb/cockroach/pkg/util/leaktest" 20 ) 21 22 func TestReplicaRankings(t *testing.T) { 23 defer leaktest.AfterTest(t)() 24 25 rr := newReplicaRankings() 26 27 testCases := []struct { 28 replicasByQPS []float64 29 }{ 30 {replicasByQPS: []float64{}}, 31 {replicasByQPS: []float64{0}}, 32 {replicasByQPS: []float64{1, 0}}, 33 {replicasByQPS: []float64{3, 2, 1, 0}}, 34 {replicasByQPS: []float64{3, 3, 2, 2, 1, 1, 0, 0}}, 35 {replicasByQPS: []float64{1.1, 1.0, 0.9, -0.9, -1.0, -1.1}}, 36 } 37 38 for _, tc := range testCases { 39 acc := rr.newAccumulator() 40 41 // Randomize the order of the inputs each time the test is run. 42 want := make([]float64, len(tc.replicasByQPS)) 43 copy(want, tc.replicasByQPS) 44 rand.Shuffle(len(tc.replicasByQPS), func(i, j int) { 45 tc.replicasByQPS[i], tc.replicasByQPS[j] = tc.replicasByQPS[j], tc.replicasByQPS[i] 46 }) 47 48 for i, replQPS := range tc.replicasByQPS { 49 acc.addReplica(replicaWithStats{ 50 repl: &Replica{RangeID: roachpb.RangeID(i)}, 51 qps: replQPS, 52 }) 53 } 54 rr.update(acc) 55 56 // Make sure we can read off all expected replicas in the correct order. 57 repls := rr.topQPS() 58 if len(repls) != len(want) { 59 t.Errorf("wrong number of replicas in output; got: %v; want: %v", repls, tc.replicasByQPS) 60 continue 61 } 62 for i := range want { 63 if repls[i].qps != want[i] { 64 t.Errorf("got %f for %d'th element; want %f (input: %v)", repls[i].qps, i, want, tc.replicasByQPS) 65 break 66 } 67 } 68 replsCopy := rr.topQPS() 69 if !reflect.DeepEqual(repls, replsCopy) { 70 t.Errorf("got different replicas on second call to topQPS; first call: %v, second call: %v", repls, replsCopy) 71 } 72 } 73 }