Skip to content

Commit 8090db5

Browse files
liggittcpanato
authored andcommitted
Switch to private instances of rand for seeding for tests
1 parent 88300c4 commit 8090db5

File tree

7 files changed

+26
-18
lines changed

7 files changed

+26
-18
lines changed

pkg/scheduler/framework/plugins/defaultpreemption/default_preemption.go

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -136,10 +136,14 @@ func (pl *DefaultPreemption) calculateNumCandidates(numNodes int32) int32 {
136136
return n
137137
}
138138

139+
// getOffsetRand is a dedicated random source for GetOffsetAndNumCandidates calls.
140+
// It defaults to rand.Int31n, but is a package variable so it can be overridden to make unit tests deterministic.
141+
var getOffsetRand = rand.Int31n
142+
139143
// GetOffsetAndNumCandidates chooses a random offset and calculates the number
140144
// of candidates that should be shortlisted for dry running preemption.
141145
func (pl *DefaultPreemption) GetOffsetAndNumCandidates(numNodes int32) (int32, int32) {
142-
return rand.Int31n(numNodes), pl.calculateNumCandidates(numNodes)
146+
return getOffsetRand(numNodes), pl.calculateNumCandidates(numNodes)
143147
}
144148

145149
// This function is not applicable for out-of-tree preemption plugins that exercise

pkg/scheduler/framework/plugins/defaultpreemption/default_preemption_test.go

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1197,7 +1197,7 @@ func TestDryRunPreemption(t *testing.T) {
11971197
// Using 4 as a seed source to test getOffsetAndNumCandidates() deterministically.
11981198
// However, we need to do it after informerFactory.WaitforCacheSync() which might
11991199
// set a seed.
1200-
rand.Seed(4)
1200+
getOffsetRand = rand.New(rand.NewSource(4)).Int31n
12011201
var prevNumFilterCalled int32
12021202
for cycle, pod := range tt.testPods {
12031203
state := framework.NewCycleState()
@@ -1396,7 +1396,7 @@ func TestSelectBestCandidate(t *testing.T) {
13961396
}
13971397
for _, tt := range tests {
13981398
t.Run(tt.name, func(t *testing.T) {
1399-
rand.Seed(4)
1399+
getOffsetRand = rand.New(rand.NewSource(4)).Int31n
14001400
nodes := make([]*v1.Node, len(tt.nodeNames))
14011401
for i, nodeName := range tt.nodeNames {
14021402
nodes[i] = st.MakeNode().Name(nodeName).Capacity(veryLargeRes).Obj()

plugin/pkg/auth/authorizer/node/node_authorizer_test.go

Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1237,7 +1237,7 @@ func BenchmarkAuthorization(b *testing.B) {
12371237
},
12381238
}
12391239

1240-
podToAdd, _ := generatePod("testwrite", "ns0", "node0", "default", opts)
1240+
podToAdd, _ := generatePod("testwrite", "ns0", "node0", "default", opts, rand.Perm)
12411241

12421242
b.ResetTimer()
12431243
for _, testWriteContention := range []bool{false, true} {
@@ -1338,11 +1338,11 @@ func populate(graph *Graph, nodes []*corev1.Node, pods []*corev1.Pod, pvs []*cor
13381338
}
13391339
}
13401340

1341-
func randomSubset(a, b int) []int {
1341+
func randomSubset(a, b int, randPerm func(int) []int) []int {
13421342
if b < a {
13431343
b = a
13441344
}
1345-
return rand.Perm(b)[:a]
1345+
return randPerm(b)[:a]
13461346
}
13471347

13481348
// generate creates sample pods and persistent volumes based on the provided options.
@@ -1356,7 +1356,7 @@ func generate(opts *sampleDataOpts) ([]*corev1.Node, []*corev1.Pod, []*corev1.Pe
13561356
attachments := make([]*storagev1.VolumeAttachment, 0, opts.nodes*opts.attachmentsPerNode)
13571357
slices := make([]*resourceapi.ResourceSlice, 0, opts.nodes*opts.nodeResourceSlicesPerNode)
13581358

1359-
rand.Seed(12345)
1359+
r := rand.New(rand.NewSource(12345))
13601360

13611361
for n := 0; n < opts.nodes; n++ {
13621362
nodeName := fmt.Sprintf("node%d", n)
@@ -1365,7 +1365,7 @@ func generate(opts *sampleDataOpts) ([]*corev1.Node, []*corev1.Pod, []*corev1.Pe
13651365
namespace := fmt.Sprintf("ns%d", p%opts.namespaces)
13661366
svcAccountName := fmt.Sprintf("svcacct%d-%s", p, nodeName)
13671367

1368-
pod, podPVs := generatePod(name, namespace, nodeName, svcAccountName, opts)
1368+
pod, podPVs := generatePod(name, namespace, nodeName, svcAccountName, opts, r.Perm)
13691369
pods = append(pods, pod)
13701370
pvs = append(pvs, podPVs...)
13711371
}
@@ -1395,7 +1395,7 @@ func generate(opts *sampleDataOpts) ([]*corev1.Node, []*corev1.Pod, []*corev1.Pe
13951395
return nodes, pods, pvs, attachments, slices
13961396
}
13971397

1398-
func generatePod(name, namespace, nodeName, svcAccountName string, opts *sampleDataOpts) (*corev1.Pod, []*corev1.PersistentVolume) {
1398+
func generatePod(name, namespace, nodeName, svcAccountName string, opts *sampleDataOpts, randPerm func(int) []int) (*corev1.Pod, []*corev1.PersistentVolume) {
13991399
pvs := make([]*corev1.PersistentVolume, 0, opts.uniquePVCsPerPod+opts.sharedPVCsPerPod)
14001400

14011401
pod := &corev1.Pod{}
@@ -1410,7 +1410,7 @@ func generatePod(name, namespace, nodeName, svcAccountName string, opts *sampleD
14101410
}})
14111411
}
14121412
// Choose shared secrets randomly from shared secrets in a namespace.
1413-
subset := randomSubset(opts.sharedSecretsPerPod, opts.sharedSecretsPerNamespace)
1413+
subset := randomSubset(opts.sharedSecretsPerPod, opts.sharedSecretsPerNamespace, randPerm)
14141414
for _, i := range subset {
14151415
pod.Spec.Volumes = append(pod.Spec.Volumes, corev1.Volume{VolumeSource: corev1.VolumeSource{
14161416
Secret: &corev1.SecretVolumeSource{SecretName: fmt.Sprintf("secret%d-shared", i)},
@@ -1423,7 +1423,7 @@ func generatePod(name, namespace, nodeName, svcAccountName string, opts *sampleD
14231423
}})
14241424
}
14251425
// Choose shared configmaps randomly from shared configmaps in a namespace.
1426-
subset = randomSubset(opts.sharedConfigMapsPerPod, opts.sharedConfigMapsPerNamespace)
1426+
subset = randomSubset(opts.sharedConfigMapsPerPod, opts.sharedConfigMapsPerNamespace, randPerm)
14271427
for _, i := range subset {
14281428
pod.Spec.Volumes = append(pod.Spec.Volumes, corev1.Volume{VolumeSource: corev1.VolumeSource{
14291429
ConfigMap: &corev1.ConfigMapVolumeSource{LocalObjectReference: corev1.LocalObjectReference{Name: fmt.Sprintf("configmap%d-shared", i)}},
@@ -1470,7 +1470,7 @@ func generatePod(name, namespace, nodeName, svcAccountName string, opts *sampleD
14701470
})
14711471
}
14721472
// Choose shared pvcs randomly from shared pvcs in a namespace.
1473-
subset = randomSubset(opts.sharedPVCsPerPod, opts.sharedPVCsPerNamespace)
1473+
subset = randomSubset(opts.sharedPVCsPerPod, opts.sharedPVCsPerNamespace, randPerm)
14741474
for _, i := range subset {
14751475
pv := &corev1.PersistentVolume{}
14761476
pv.Name = fmt.Sprintf("pv%d-shared-%s", i, pod.Namespace)

staging/src/k8s.io/apimachinery/pkg/util/rand/rand_test.go

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -65,10 +65,10 @@ func TestIntn(t *testing.T) {
6565

6666
func TestPerm(t *testing.T) {
6767
Seed(5)
68-
rand.Seed(5)
68+
r := rand.New(rand.NewSource(5))
6969
for i := 1; i < 20; i++ {
7070
actual := Perm(i)
71-
expected := rand.Perm(i)
71+
expected := r.Perm(i)
7272
for j := 0; j < i; j++ {
7373
if actual[j] != expected[j] {
7474
t.Errorf("Perm call result is unexpected")

staging/src/k8s.io/apimachinery/pkg/util/wait/wait.go

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -80,6 +80,10 @@ func Forever(f func(), period time.Duration) {
8080
Until(f, period, NeverStop)
8181
}
8282

83+
// jitterRand is a dedicated random source for jitter calculations.
84+
// It defaults to rand.Float64, but is a package variable so it can be overridden to make unit tests deterministic.
85+
var jitterRand = rand.Float64
86+
8387
// Jitter returns a time.Duration between duration and duration + maxFactor *
8488
// duration.
8589
//
@@ -89,7 +93,7 @@ func Jitter(duration time.Duration, maxFactor float64) time.Duration {
8993
if maxFactor <= 0.0 {
9094
maxFactor = 1.0
9195
}
92-
wait := duration + time.Duration(rand.Float64()*maxFactor*float64(duration))
96+
wait := duration + time.Duration(jitterRand()*maxFactor*float64(duration))
9397
return wait
9498
}
9599

staging/src/k8s.io/apimachinery/pkg/util/wait/wait_test.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -682,7 +682,7 @@ func TestBackoff_Step(t *testing.T) {
682682
initial = nil
683683
}
684684
t.Run(fmt.Sprintf("%#v seed=%d", initial, seed), func(t *testing.T) {
685-
rand.Seed(seed)
685+
jitterRand = rand.New(rand.NewSource(seed)).Float64
686686
for i := 0; i < len(tt.want); i++ {
687687
got := initial.Step()
688688
t.Logf("[%d]=%s", i, got)

test/e2e/storage/utils/utils.go

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -490,9 +490,9 @@ func readFile(content, path string) string {
490490
// genBinDataFromSeed generate binData with random seed
491491
func genBinDataFromSeed(len int, seed int64) []byte {
492492
binData := make([]byte, len)
493-
rand.Seed(seed)
493+
r := rand.New(rand.NewSource(seed))
494494

495-
_, err := rand.Read(binData)
495+
_, err := r.Read(binData)
496496
if err != nil {
497497
fmt.Printf("Error: %v\n", err)
498498
}

0 commit comments

Comments
 (0)