github.com/bloxroute-labs/bor@v0.1.4/les/randselect_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 les
    18  
    19  import (
    20  	"math/rand"
    21  	"testing"
    22  )
    23  
    24  type testWrsItem struct {
    25  	idx  int
    26  	widx *int
    27  }
    28  
    29  func (t *testWrsItem) Weight() int64 {
    30  	w := *t.widx
    31  	if w == -1 || w == t.idx {
    32  		return int64(t.idx + 1)
    33  	}
    34  	return 0
    35  }
    36  
    37  func TestWeightedRandomSelect(t *testing.T) {
    38  	testFn := func(cnt int) {
    39  		s := newWeightedRandomSelect()
    40  		w := -1
    41  		list := make([]testWrsItem, cnt)
    42  		for i := range list {
    43  			list[i] = testWrsItem{idx: i, widx: &w}
    44  			s.update(&list[i])
    45  		}
    46  		w = rand.Intn(cnt)
    47  		c := s.choose()
    48  		if c == nil {
    49  			t.Errorf("expected item, got nil")
    50  		} else {
    51  			if c.(*testWrsItem).idx != w {
    52  				t.Errorf("expected another item")
    53  			}
    54  		}
    55  		w = -2
    56  		if s.choose() != nil {
    57  			t.Errorf("expected nil, got item")
    58  		}
    59  	}
    60  	testFn(1)
    61  	testFn(10)
    62  	testFn(100)
    63  	testFn(1000)
    64  	testFn(10000)
    65  	testFn(100000)
    66  	testFn(1000000)
    67  }