github.com/arieschain/arieschain@v0.0.0-20191023063405-37c074544356/les/randselect_test.go (about)

     1  package les
     2  
     3  import (
     4  	"math/rand"
     5  	"testing"
     6  )
     7  
     8  type testWrsItem struct {
     9  	idx  int
    10  	widx *int
    11  }
    12  
    13  func (t *testWrsItem) Weight() int64 {
    14  	w := *t.widx
    15  	if w == -1 || w == t.idx {
    16  		return int64(t.idx + 1)
    17  	}
    18  	return 0
    19  }
    20  
    21  func TestWeightedRandomSelect(t *testing.T) {
    22  	testFn := func(cnt int) {
    23  		s := newWeightedRandomSelect()
    24  		w := -1
    25  		list := make([]testWrsItem, cnt)
    26  		for i := range list {
    27  			list[i] = testWrsItem{idx: i, widx: &w}
    28  			s.update(&list[i])
    29  		}
    30  		w = rand.Intn(cnt)
    31  		c := s.choose()
    32  		if c == nil {
    33  			t.Errorf("expected item, got nil")
    34  		} else {
    35  			if c.(*testWrsItem).idx != w {
    36  				t.Errorf("expected another item")
    37  			}
    38  		}
    39  		w = -2
    40  		if s.choose() != nil {
    41  			t.Errorf("expected nil, got item")
    42  		}
    43  	}
    44  	testFn(1)
    45  	testFn(10)
    46  	testFn(100)
    47  	testFn(1000)
    48  	testFn(10000)
    49  	testFn(100000)
    50  	testFn(1000000)
    51  }