navidrome/utils/weighted_random_chooser_tes...

Ignoring revisions in .git-blame-ignore-revs. Click here to bypass and see the normal blame view.

51 lines
1.1 KiB
Go
Raw Normal View History

2021-05-29 05:51:56 +02:00
package utils
import (
2022-07-26 22:47:16 +02:00
. "github.com/onsi/ginkgo/v2"
2021-05-29 05:51:56 +02:00
. "github.com/onsi/gomega"
)
var _ = Describe("WeightedRandomChooser", func() {
var w *WeightedChooser
2021-05-29 05:51:56 +02:00
BeforeEach(func() {
w = NewWeightedRandomChooser()
for i := 0; i < 10; i++ {
w.Add(i, i)
2021-05-29 05:51:56 +02:00
}
})
It("removes a random item", func() {
Expect(w.Size()).To(Equal(10))
_, err := w.GetAndRemove()
Expect(err).ToNot(HaveOccurred())
Expect(w.Size()).To(Equal(9))
})
It("returns the sole item", func() {
w = NewWeightedRandomChooser()
w.Add("a", 1)
2021-05-29 05:51:56 +02:00
Expect(w.GetAndRemove()).To(Equal("a"))
})
It("fails when trying to choose from empty set", func() {
w = NewWeightedRandomChooser()
w.Add("a", 1)
w.Add("b", 1)
2021-05-29 05:51:56 +02:00
Expect(w.GetAndRemove()).To(BeElementOf("a", "b"))
Expect(w.GetAndRemove()).To(BeElementOf("a", "b"))
_, err := w.GetAndRemove()
Expect(err).To(HaveOccurred())
})
It("chooses based on weights", func() {
counts := [10]int{}
for i := 0; i < 200000; i++ {
c, _ := w.weightedChoice()
counts[c] = counts[c] + 1
}
for i := 0; i < 9; i++ {
Expect(counts[i]).To(BeNumerically("<", counts[i+1]))
}
})
})