github.com/hardtosaygoodbye/go-ethereum@v1.10.16-0.20220122011429-97003b9e6c15/les/utils/weighted_select_test.go (about) 1 // Copyright 2016 The go-ethereum Authors 2 // This file is part of the go-ethereum library. 3 // 4 // The go-ethereum library is free software: you can redistribute it and/or modify 5 // it under the terms of the GNU Lesser General Public License as published by 6 // the Free Software Foundation, either version 3 of the License, or 7 // (at your option) any later version. 8 // 9 // The go-ethereum library is distributed in the hope that it will be useful, 10 // but WITHOUT ANY WARRANTY; without even the implied warranty of 11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 // GNU Lesser General Public License for more details. 13 // 14 // You should have received a copy of the GNU Lesser General Public License 15 // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>. 16 17 package utils 18 19 import ( 20 "math/rand" 21 "testing" 22 ) 23 24 type testWrsItem struct { 25 idx int 26 widx *int 27 } 28 29 func testWeight(i interface{}) uint64 { 30 t := i.(*testWrsItem) 31 w := *t.widx 32 if w == -1 || w == t.idx { 33 return uint64(t.idx + 1) 34 } 35 return 0 36 } 37 38 func TestWeightedRandomSelect(t *testing.T) { 39 testFn := func(cnt int) { 40 s := NewWeightedRandomSelect(testWeight) 41 w := -1 42 list := make([]testWrsItem, cnt) 43 for i := range list { 44 list[i] = testWrsItem{idx: i, widx: &w} 45 s.Update(&list[i]) 46 } 47 w = rand.Intn(cnt) 48 c := s.Choose() 49 if c == nil { 50 t.Errorf("expected item, got nil") 51 } else { 52 if c.(*testWrsItem).idx != w { 53 t.Errorf("expected another item") 54 } 55 } 56 w = -2 57 if s.Choose() != nil { 58 t.Errorf("expected nil, got item") 59 } 60 } 61 testFn(1) 62 testFn(10) 63 testFn(100) 64 testFn(1000) 65 testFn(10000) 66 testFn(100000) 67 testFn(1000000) 68 }