@@ -18,6 +18,7 @@ package picker
1818
1919import (
2020 "context"
21+ "math"
2122 "testing"
2223
2324 "github.com/google/go-cmp/cmp"
@@ -138,8 +139,8 @@ func TestPickMaxScorePicker(t *testing.T) {
138139
139140func TestPickWeightedRandomPicker (t * testing.T ) {
140141 const (
141- testIterations = 1000
142- tolerance = 0.2 // 20% tolerance in [0,1] range
142+ testIterations = 10000
143+ tolerance = 0.05 // Verify within tolerance ±5%
143144 )
144145
145146 pod1 := & types.PodMetrics {Pod : & backend.Pod {NamespacedName : k8stypes.NamespacedName {Name : "pod1" }}}
@@ -197,14 +198,14 @@ func TestPickWeightedRandomPicker(t *testing.T) {
197198 for _ , test := range tests {
198199 t .Run (test .name , func (t * testing.T ) {
199200 picker := NewWeightedRandomPicker (test .maxPods )
200- selectionCounts := make (map [string ]int )
201201
202- // Calculate expected probabilities based on scores
202+ // Summarize the total score of all pods
203203 totalScore := 0.0
204204 for _ , pod := range test .input {
205205 totalScore += pod .Score
206206 }
207207
208+ // Calculate expected probabilities based on scores
208209 expectedProbabilities := make (map [string ]float64 )
209210 for _ , pod := range test .input {
210211 podName := pod .GetPod ().NamespacedName .Name
@@ -216,32 +217,27 @@ func TestPickWeightedRandomPicker(t *testing.T) {
216217 }
217218
218219 // Initialize selection counters for each pod
220+ selectionCounts := make (map [string ]int )
219221 for _ , pod := range test .input {
220222 podName := pod .GetPod ().NamespacedName .Name
221223 selectionCounts [podName ] = 0
222224 }
223225
224226 // Run multiple iterations to gather statistical data
225- for i := 0 ; i < testIterations ; i ++ {
227+ for range testIterations {
226228 result := picker .Pick (context .Background (), types .NewCycleState (), test .input )
227229
228230 // Count selections for probability analysis
229- if len (result .TargetPods ) > 0 {
230- selectedPodName := result .TargetPods [0 ].GetPod ().NamespacedName .Name
231- selectionCounts [selectedPodName ]++
232- }
231+ selectedPodName := result .TargetPods [0 ].GetPod ().NamespacedName .Name
232+ selectionCounts [selectedPodName ]++
233233 }
234234
235235 // Verify probability distribution
236236 for podName , expectedProb := range expectedProbabilities {
237237 actualCount := selectionCounts [podName ]
238238 actualProb := float64 (actualCount ) / float64 (testIterations )
239239
240- toleranceValue := expectedProb * tolerance
241- lowerBound := expectedProb - toleranceValue
242- upperBound := expectedProb + toleranceValue
243-
244- if actualProb < lowerBound || actualProb > upperBound {
240+ if math .Abs (actualProb - expectedProb ) > tolerance {
245241 t .Errorf ("Pod %s: expected probability %.3f ±%.1f%%, got %.3f (count: %d/%d)" ,
246242 podName , expectedProb , tolerance * 100 , actualProb , actualCount , testIterations )
247243 } else {
0 commit comments