randselect_test.go 1.6 KB

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