From 1f2b70a043ec27f19b5f294b55a4fad24a0ffe2a Mon Sep 17 00:00:00 2001 From: Mads Jensen Date: Sat, 7 Mar 2026 10:17:15 +0100 Subject: [PATCH] Lint: Use modernize/rangeint in test/{e2e,e2e_node,images,soak} --- test/e2e/apimachinery/chunking.go | 2 +- .../apimachinery/crd_conversion_webhook.go | 2 +- test/e2e/apimachinery/crd_publish_openapi.go | 2 +- test/e2e/apimachinery/crd_validation_rules.go | 2 +- .../custom_resource_definition.go | 2 +- test/e2e/apimachinery/garbage_collector.go | 2 +- test/e2e/apimachinery/namespace.go | 2 +- test/e2e/apimachinery/watch.go | 2 +- test/e2e/apimachinery/webhook.go | 4 +-- test/e2e/apps/deployment.go | 2 +- test/e2e/apps/disruption.go | 2 +- test/e2e/apps/statefulset.go | 4 +-- .../autoscaling/cluster_size_autoscaling.go | 6 ++-- test/e2e/cloud/gcp/ha_master.go | 12 ++++---- test/e2e/common/node/pods.go | 4 +-- test/e2e/common/node/security_context.go | 2 +- test/e2e/dra/dra.go | 8 +++--- test/e2e/dra/utils/builder.go | 4 +-- .../framework/debug/log_size_monitoring.go | 2 +- test/e2e/framework/kubectl/kubectl_utils.go | 2 +- test/e2e/framework/network/utils.go | 6 ++-- test/e2e/framework/pv/pv.go | 2 +- test/e2e/framework/service/jig.go | 2 +- test/e2e/framework/service/resource.go | 2 +- test/e2e/framework/volume/fixtures.go | 2 +- test/e2e/kubectl/exec.go | 6 ++-- test/e2e/kubectl/kubectl.go | 4 +-- test/e2e/network/dns_scale_records.go | 6 ++-- test/e2e/network/hostport.go | 2 +- test/e2e/network/kube_proxy.go | 2 +- test/e2e/network/netpol/probe.go | 2 +- test/e2e/network/netpol/test_helper.go | 2 +- test/e2e/network/pod_lifecycle.go | 4 +-- test/e2e/network/proxy.go | 4 +-- test/e2e/network/service.go | 28 +++++++++---------- test/e2e/network/service_cidrs.go | 2 +- test/e2e/network/service_latency.go | 4 +-- test/e2e/node/pods.go | 6 ++-- test/e2e/scheduling/preemption.go | 14 +++++----- test/e2e/scheduling/priorities.go | 4 +-- test/e2e/storage/empty_dir_wrapper.go | 8 +++--- test/e2e/storage/persistent_volumes-local.go | 8 +++--- test/e2e/storage/persistent_volumes.go | 6 ++-- test/e2e/storage/testsuites/multivolume.go | 10 +++---- test/e2e/storage/testsuites/provisioning.go | 2 +- test/e2e/storage/testsuites/snapshottable.go | 2 +- test/e2e/storage/testsuites/topology.go | 2 +- test/e2e/storage/testsuites/volumelimits.go | 4 +-- test/e2e/windows/cpu_limits.go | 2 +- test/e2e/windows/density.go | 2 +- test/e2e/windows/hybrid_network.go | 2 +- test/e2e/windows/kubelet_stats.go | 6 ++-- test/e2e_dra/upgradedowngrade_test.go | 2 +- test/e2e_node/cpu_manager_metrics_test.go | 4 +-- test/e2e_node/dra_test.go | 10 +++---- test/e2e_node/image_list.go | 2 +- test/e2e_node/mirror_pod_grace_period_test.go | 2 +- test/e2e_node/node_problem_detector_linux.go | 2 +- test/e2e_node/numa_alignment.go | 2 +- test/e2e_node/podresources_test.go | 2 +- test/e2e_node/probe_stress_test.go | 2 +- test/e2e_node/resource_collector.go | 2 +- test/e2e_node/restart_all_containers_test.go | 4 +-- test/e2e_node/restart_test.go | 2 +- test/e2e_node/topology_manager_test.go | 12 ++++---- test/e2e_node/volume_manager_test.go | 2 +- test/images/agnhost/nettest/nettest.go | 2 +- .../port-forward-tester/portforwardtester.go | 2 +- .../controller.go | 6 ++-- test/images/agnhost/webhook/convert_test.go | 4 +-- test/soak/serve_hostnames/serve_hostnames.go | 6 ++-- 71 files changed, 148 insertions(+), 148 deletions(-) diff --git a/test/e2e/apimachinery/chunking.go b/test/e2e/apimachinery/chunking.go index 048708496c7..24d313cbd83 100644 --- a/test/e2e/apimachinery/chunking.go +++ b/test/e2e/apimachinery/chunking.go @@ -85,7 +85,7 @@ var _ = SIGDescribe("Servers with support for API chunking", func() { c := f.ClientSet client := c.CoreV1().PodTemplates(ns) ginkgo.By("retrieving those results in paged fashion several times") - for i := 0; i < 3; i++ { + for range 3 { opts := metav1.ListOptions{} found := 0 var lastRV string diff --git a/test/e2e/apimachinery/crd_conversion_webhook.go b/test/e2e/apimachinery/crd_conversion_webhook.go index 110b6b8e5a7..1c13dd18f47 100644 --- a/test/e2e/apimachinery/crd_conversion_webhook.go +++ b/test/e2e/apimachinery/crd_conversion_webhook.go @@ -446,7 +446,7 @@ func testCRListConversion(ctx context.Context, f *framework.Framework, testCrd * // Just retrying fixes that. // // TODO: we have to wait for the storage version to become effective. Storage version changes are not instant. - for i := 0; i < 5; i++ { + for range 5 { _, err = customResourceClients["v1"].Create(ctx, crInstance, metav1.CreateOptions{}) if err == nil { break diff --git a/test/e2e/apimachinery/crd_publish_openapi.go b/test/e2e/apimachinery/crd_publish_openapi.go index 1930adc1960..c3585748d6d 100644 --- a/test/e2e/apimachinery/crd_publish_openapi.go +++ b/test/e2e/apimachinery/crd_publish_openapi.go @@ -598,7 +598,7 @@ const waitSuccessThreshold = 10 // might be lagging behind. Calling f multiple times reduces the chance exponentially. func mustSucceedMultipleTimes(n int, f func() (bool, error)) func() (bool, error) { return func() (bool, error) { - for i := 0; i < n; i++ { + for range n { ok, err := f() if err != nil || !ok { return ok, err diff --git a/test/e2e/apimachinery/crd_validation_rules.go b/test/e2e/apimachinery/crd_validation_rules.go index 35926ac0b84..0362c3eadea 100644 --- a/test/e2e/apimachinery/crd_validation_rules.go +++ b/test/e2e/apimachinery/crd_validation_rules.go @@ -331,7 +331,7 @@ var _ = SIGDescribe("CustomResourceValidationRules [Privileged:ClusterAdmin]", f func genLargeArray(n, x int64) []int64 { arr := make([]int64, n) - for i := int64(0); i < n; i++ { + for i := range n { arr[i] = x } return arr diff --git a/test/e2e/apimachinery/custom_resource_definition.go b/test/e2e/apimachinery/custom_resource_definition.go index 1235ea815e0..c3f9a4fad7d 100644 --- a/test/e2e/apimachinery/custom_resource_definition.go +++ b/test/e2e/apimachinery/custom_resource_definition.go @@ -97,7 +97,7 @@ var _ = SIGDescribe("CustomResourceDefinition resources [Privileged:ClusterAdmin // Create CRD and wait for the resource to be recognized and available. crds := make([]*v1.CustomResourceDefinition, testListSize) - for i := 0; i < testListSize; i++ { + for i := range testListSize { crd := fixtures.NewRandomNameV1CustomResourceDefinition(v1.ClusterScoped) crd.Labels = map[string]string{"e2e-list-test-uuid": testUUID} crd, err = fixtures.CreateNewV1CustomResourceDefinitionWatchUnsafe(crd, apiExtensionClient) diff --git a/test/e2e/apimachinery/garbage_collector.go b/test/e2e/apimachinery/garbage_collector.go index ded6a385632..52626551817 100644 --- a/test/e2e/apimachinery/garbage_collector.go +++ b/test/e2e/apimachinery/garbage_collector.go @@ -748,7 +748,7 @@ var _ = SIGDescribe("Garbage collector", func() { pods, err := podClient.List(ctx, metav1.ListOptions{}) framework.ExpectNoError(err, "failed to list pods in namespace: %s", f.Namespace.Name) patch := fmt.Sprintf(`{"metadata":{"ownerReferences":[{"apiVersion":"v1","kind":"ReplicationController","name":"%s","uid":"%s"}]}}`, rc2.ObjectMeta.Name, rc2.ObjectMeta.UID) - for i := 0; i < halfReplicas; i++ { + for i := range halfReplicas { pod := pods.Items[i] _, err := podClient.Patch(ctx, pod.Name, types.StrategicMergePatchType, []byte(patch), metav1.PatchOptions{}) framework.ExpectNoError(err, "failed to apply to pod %s in namespace %s, a strategic merge patch: %s", pod.Name, f.Namespace.Name, patch) diff --git a/test/e2e/apimachinery/namespace.go b/test/e2e/apimachinery/namespace.go index 8db14a461e2..204fa2461a4 100644 --- a/test/e2e/apimachinery/namespace.go +++ b/test/e2e/apimachinery/namespace.go @@ -52,7 +52,7 @@ func extinguish(ctx context.Context, f *framework.Framework, totalNS int, maxAll ginkgo.By("Creating testing namespaces") wg := &sync.WaitGroup{} wg.Add(totalNS) - for n := 0; n < totalNS; n++ { + for n := range totalNS { go func(n int) { defer wg.Done() defer ginkgo.GinkgoRecover() diff --git a/test/e2e/apimachinery/watch.go b/test/e2e/apimachinery/watch.go index 1e0bfeb5b96..7d082d7abed 100644 --- a/test/e2e/apimachinery/watch.go +++ b/test/e2e/apimachinery/watch.go @@ -359,7 +359,7 @@ var _ = SIGDescribe("Watchers", func() { ginkgo.By("creating watches starting from each resource version of the events produced and verifying they all receive resource versions in the same order") wcs := []watch.Interface{} - for i := 0; i < iterations; i++ { + for range iterations { wc, err := watchtools.NewRetryWatcher(resourceVersion, listWatcher) framework.ExpectNoError(err, "Failed to watch configmaps in the namespace %s", ns) wcs = append(wcs, wc) diff --git a/test/e2e/apimachinery/webhook.go b/test/e2e/apimachinery/webhook.go index b4cecda6f8b..ae3063ecbd8 100644 --- a/test/e2e/apimachinery/webhook.go +++ b/test/e2e/apimachinery/webhook.go @@ -575,7 +575,7 @@ var _ = SIGDescribe("AdmissionWebhook [Privileged:ClusterAdmin]", func() { testListSize := 10 testUUID := string(uuid.NewUUID()) - for i := 0; i < testListSize; i++ { + for i := range testListSize { name := fmt.Sprintf("%s-%d", f.UniqueName, i) _, err := createValidatingWebhookConfiguration(ctx, f, &admissionregistrationv1.ValidatingWebhookConfiguration{ ObjectMeta: metav1.ObjectMeta{ @@ -649,7 +649,7 @@ var _ = SIGDescribe("AdmissionWebhook [Privileged:ClusterAdmin]", func() { testListSize := 10 testUUID := string(uuid.NewUUID()) - for i := 0; i < testListSize; i++ { + for i := range testListSize { name := fmt.Sprintf("%s-%d", f.UniqueName, i) _, err := createMutatingWebhookConfiguration(ctx, f, &admissionregistrationv1.MutatingWebhookConfiguration{ ObjectMeta: metav1.ObjectMeta{ diff --git a/test/e2e/apps/deployment.go b/test/e2e/apps/deployment.go index 74f16f147cd..8e7770ea32b 100644 --- a/test/e2e/apps/deployment.go +++ b/test/e2e/apps/deployment.go @@ -1043,7 +1043,7 @@ func testIterativeDeployments(ctx context.Context, f *framework.Framework) { framework.ExpectNoError(err) iterations := 20 - for i := 0; i < iterations; i++ { + for i := range iterations { if r := rand.Float32(); r < 0.6 { time.Sleep(time.Duration(float32(i) * r * float32(time.Second))) } diff --git a/test/e2e/apps/disruption.go b/test/e2e/apps/disruption.go index 33cd8b0047d..3434ad93c2a 100644 --- a/test/e2e/apps/disruption.go +++ b/test/e2e/apps/disruption.go @@ -648,7 +648,7 @@ func waitForPDBCollectionToBeDeleted(ctx context.Context, cs kubernetes.Interfac } func createPodsOrDie(ctx context.Context, cs kubernetes.Interface, ns string, n int) { - for i := 0; i < n; i++ { + for i := range n { pod := &v1.Pod{ ObjectMeta: metav1.ObjectMeta{ Name: fmt.Sprintf("pod-%d", i), diff --git a/test/e2e/apps/statefulset.go b/test/e2e/apps/statefulset.go index 076bc5fbbc7..fb0c1c930fb 100644 --- a/test/e2e/apps/statefulset.go +++ b/test/e2e/apps/statefulset.go @@ -1574,7 +1574,7 @@ var _ = SIGDescribe("StatefulSet", func() { framework.ExpectNoError(err) claimNames := make([]string, 4) - for i := 0; i < 4; i++ { + for i := range 4 { claimNames[i] = fmt.Sprintf("%s-%s-%d", statefulPodMounts[0].Name, ssName, i) } @@ -2034,7 +2034,7 @@ func uncordonNode(ctx context.Context, c clientset.Interface, oldData, newData [ func kubectlExecWithRetries(ns string, args ...string) (out string) { var err error - for i := 0; i < 3; i++ { + for range 3 { if out, err = e2ekubectl.RunKubectl(ns, args...); err == nil { return } diff --git a/test/e2e/autoscaling/cluster_size_autoscaling.go b/test/e2e/autoscaling/cluster_size_autoscaling.go index 8d8ea8025f4..33320f283df 100644 --- a/test/e2e/autoscaling/cluster_size_autoscaling.go +++ b/test/e2e/autoscaling/cluster_size_autoscaling.go @@ -611,7 +611,7 @@ func waitForAllCaPodsReadyInNamespace(ctx context.Context, f *framework.Framewor func makeNodeUnschedulable(ctx context.Context, c clientset.Interface, node *v1.Node) error { ginkgo.By(fmt.Sprintf("Taint node %s", node.Name)) - for j := 0; j < 3; j++ { + for j := range 3 { freshNode, err := c.CoreV1().Nodes().Get(ctx, node.Name, metav1.GetOptions{}) if err != nil { return err @@ -648,7 +648,7 @@ func (CriticalAddonsOnlyError) Error() string { func makeNodeSchedulable(ctx context.Context, c clientset.Interface, node *v1.Node, failOnCriticalAddonsOnly bool) error { ginkgo.By(fmt.Sprintf("Remove taint from node %s", node.Name)) - for j := 0; j < 3; j++ { + for j := range 3 { freshNode, err := c.CoreV1().Nodes().Get(ctx, node.Name, metav1.GetOptions{}) if err != nil { return err @@ -798,7 +798,7 @@ func runReplicatedPodOnEachNode(ctx context.Context, f *framework.Framework, nod // Update replicas count, to create new pods that will be allocated on node // (we retry 409 errors in case rc reference got out of sync) - for j := 0; j < 3; j++ { + for j := range 3 { *rc.Spec.Replicas = int32((i + 1) * podsPerNode) rc, err = f.ClientSet.CoreV1().ReplicationControllers(namespace).Update(ctx, rc, metav1.UpdateOptions{}) if err == nil { diff --git a/test/e2e/cloud/gcp/ha_master.go b/test/e2e/cloud/gcp/ha_master.go index 99a26d55d55..8594e98f1a0 100644 --- a/test/e2e/cloud/gcp/ha_master.go +++ b/test/e2e/cloud/gcp/ha_master.go @@ -236,10 +236,10 @@ var _ = SIGDescribe("HA-master", feature.HAMaster, func() { zone := framework.TestContext.CloudConfig.Zone step(ctx, None, "") numAdditionalReplicas := 2 - for i := 0; i < numAdditionalReplicas; i++ { + for range numAdditionalReplicas { step(ctx, AddReplica, zone) } - for i := 0; i < numAdditionalReplicas; i++ { + for range numAdditionalReplicas { step(ctx, RemoveReplica, zone) } }) @@ -254,10 +254,10 @@ var _ = SIGDescribe("HA-master", feature.HAMaster, func() { // If numAdditionalReplicas is larger then the number of remaining zones in the region, // we create a few masters in the same zone and zone entry is repeated in additionalReplicaZones. numAdditionalReplicas := 2 - for i := 0; i < numAdditionalReplicas; i++ { + for i := range numAdditionalReplicas { step(ctx, AddReplica, zones[i%len(zones)]) } - for i := 0; i < numAdditionalReplicas; i++ { + for i := range numAdditionalReplicas { step(ctx, RemoveReplica, zones[i%len(zones)]) } }) @@ -280,12 +280,12 @@ var _ = SIGDescribe("HA-master", feature.HAMaster, func() { // // If numAdditionalReplicas is larger then the number of remaining zones in the region, // we create a few masters in the same zone and zone entry is repeated in additionalReplicaZones. - for i := 0; i < numAdditionalReplicas; i++ { + for i := range numAdditionalReplicas { step(ctx, AddReplica, zones[i%len(zones)]) } // Remove master repilcas. - for i := 0; i < numAdditionalReplicas; i++ { + for i := range numAdditionalReplicas { step(ctx, RemoveReplica, zones[i%len(zones)]) } diff --git a/test/e2e/common/node/pods.go b/test/e2e/common/node/pods.go index 00e0eae1c9e..c948a2e5445 100644 --- a/test/e2e/common/node/pods.go +++ b/test/e2e/common/node/pods.go @@ -176,7 +176,7 @@ func getRestartDelay(ctx context.Context, podClient *e2epod.PodClient, podName s func expectNoErrorWithRetries(fn func() error, maxRetries int, explain ...interface{}) { // TODO (pohly): replace the entire function with gomege.Eventually. var err error - for i := 0; i < maxRetries; i++ { + for i := range maxRetries { err = fn() if err == nil { return @@ -750,7 +750,7 @@ var _ = SIGDescribe("Pods", func() { delay1 time.Duration err error ) - for i := 0; i < 3; i++ { + for range 3 { delay1, err = getRestartDelay(ctx, podClient, podName, containerName) if err != nil { framework.Failf("timed out waiting for container restart in pod=%s/%s", podName, containerName) diff --git a/test/e2e/common/node/security_context.go b/test/e2e/common/node/security_context.go index 85400318d27..3a95fb57ca3 100644 --- a/test/e2e/common/node/security_context.go +++ b/test/e2e/common/node/security_context.go @@ -209,7 +209,7 @@ var _ = SIGDescribe("Security Context", func() { e2eskipper.Skipf("node is not setup for userns with kubelet mappings: %v", err) } - for i := 0; i < 4; i++ { + for range 4 { // makePod(false) creates the pod with user namespace podClient := e2epod.PodClientNS(f, f.Namespace.Name) createdPod := podClient.Create(ctx, makePod(false)) diff --git a/test/e2e/dra/dra.go b/test/e2e/dra/dra.go index 6aeb45d2d88..4f2d746f563 100644 --- a/test/e2e/dra/dra.go +++ b/test/e2e/dra/dra.go @@ -875,7 +875,7 @@ var _ = framework.SIGDescribe("node")(framework.WithLabel("DRA"), func() { tCtx := f.TContext(ctx) var objects []klog.KMetadata pods := make([]*v1.Pod, numPods) - for i := 0; i < numPods; i++ { + for i := range numPods { pod, template := b.PodInline() pods[i] = pod objects = append(objects, pod, template) @@ -886,7 +886,7 @@ var _ = framework.SIGDescribe("node")(framework.WithLabel("DRA"), func() { // We don't know the order. All that matters is that all of them get scheduled eventually. var wg sync.WaitGroup wg.Add(numPods) - for i := 0; i < numPods; i++ { + for i := range numPods { pod := pods[i] go func() { defer ginkgo.GinkgoRecover() @@ -906,7 +906,7 @@ var _ = framework.SIGDescribe("node")(framework.WithLabel("DRA"), func() { claim := b.ExternalClaim() objects = append(objects, claim) pods := make([]*v1.Pod, numPods) - for i := 0; i < numPods; i++ { + for i := range numPods { pod := b.PodExternal(claim.Name) pods[i] = pod objects = append(objects, pod) @@ -918,7 +918,7 @@ var _ = framework.SIGDescribe("node")(framework.WithLabel("DRA"), func() { f.Timeouts.PodStartSlow *= time.Duration(numPods) var wg sync.WaitGroup wg.Add(numPods) - for i := 0; i < numPods; i++ { + for i := range numPods { pod := pods[i] go func() { defer ginkgo.GinkgoRecover() diff --git a/test/e2e/dra/utils/builder.go b/test/e2e/dra/utils/builder.go index 0341ec844f2..f0400a4500c 100644 --- a/test/e2e/dra/utils/builder.go +++ b/test/e2e/dra/utils/builder.go @@ -580,7 +580,7 @@ func NetworkResources(maxAllocations int, tainted bool) driverResourcesGenFunc { return func(nodes *Nodes) map[string]resourceslice.DriverResources { driverResources := make(map[string]resourceslice.DriverResources) devices := make([]resourceapi.Device, 0) - for i := 0; i < maxAllocations; i++ { + for i := range maxAllocations { device := resourceapi.Device{ Name: fmt.Sprintf("device-%d", i), } @@ -646,7 +646,7 @@ func DriverResourcesNow(nodes *Nodes, maxAllocations int, devicesPerNode ...map[ } } else if maxAllocations >= 0 { devices := make([]resourceapi.Device, maxAllocations) - for i := 0; i < maxAllocations; i++ { + for i := range maxAllocations { devices[i] = resourceapi.Device{ Name: fmt.Sprintf("device-%02d", i), } diff --git a/test/e2e/framework/debug/log_size_monitoring.go b/test/e2e/framework/debug/log_size_monitoring.go index 073cbe891af..9da8e921800 100644 --- a/test/e2e/framework/debug/log_size_monitoring.go +++ b/test/e2e/framework/debug/log_size_monitoring.go @@ -175,7 +175,7 @@ func NewLogsVerifier(ctx context.Context, c clientset.Interface) *LogsSizeVerifi workers: workers, } verifier.wg.Add(workersNo) - for i := 0; i < workersNo; i++ { + for i := range workersNo { workers[i] = &LogSizeGatherer{ data: verifier.data, wg: &verifier.wg, diff --git a/test/e2e/framework/kubectl/kubectl_utils.go b/test/e2e/framework/kubectl/kubectl_utils.go index b3fe86b8bba..2b67d5d68d0 100644 --- a/test/e2e/framework/kubectl/kubectl_utils.go +++ b/test/e2e/framework/kubectl/kubectl_utils.go @@ -161,7 +161,7 @@ func (tk *TestKubeconfig) ReadFileViaContainer(podName, containerName string, pa } func (tk *TestKubeconfig) kubectlExecWithRetry(namespace string, podName, containerName string, args ...string) ([]byte, []byte, error) { - for numRetries := 0; numRetries < maxKubectlExecRetries; numRetries++ { + for numRetries := range maxKubectlExecRetries { if numRetries > 0 { framework.Logf("Retrying kubectl exec (retry count=%v/%v)", numRetries+1, maxKubectlExecRetries) } diff --git a/test/e2e/framework/network/utils.go b/test/e2e/framework/network/utils.go index 65e31d31dcb..d1fb2abb006 100644 --- a/test/e2e/framework/network/utils.go +++ b/test/e2e/framework/network/utils.go @@ -331,7 +331,7 @@ func (config *NetworkingTestConfig) DialFromContainer(ctx context.Context, proto responses := sets.NewString() - for i := 0; i < maxTries; i++ { + for i := range maxTries { resp, err := config.GetResponseFromContainer(ctx, protocol, dialCommand, containerIP, targetIP, containerHTTPPort, targetPort) if err != nil { // A failure to kubectl exec counts as a try, not a hard fail. @@ -387,7 +387,7 @@ func (config *NetworkingTestConfig) GetEndpointsFromContainer(ctx context.Contex eps := sets.NewString() - for i := 0; i < tries; i++ { + for i := range tries { stdout, stderr, err := e2epod.ExecShellInPodWithFullOutput(ctx, config.f, config.TestContainerPod.Name, cmd) if err != nil { // A failure to kubectl exec counts as a try, not a hard fail. @@ -493,7 +493,7 @@ func (config *NetworkingTestConfig) DialFromNode(ctx context.Context, protocol, filterCmd := fmt.Sprintf("%s | grep -v '^\\s*$'", cmd) framework.Logf("Going to poll %v on port %v at least %v times, with a maximum of %v tries before failing", targetIP, targetPort, minTries, maxTries) - for i := 0; i < maxTries; i++ { + for i := range maxTries { stdout, stderr, err := e2epod.ExecShellInPodWithFullOutput(ctx, config.f, config.HostTestContainerPod.Name, filterCmd) if err != nil || len(stderr) > 0 { // A failure to exec command counts as a try, not a hard fail. diff --git a/test/e2e/framework/pv/pv.go b/test/e2e/framework/pv/pv.go index d748b5b0029..938a1b54aa7 100644 --- a/test/e2e/framework/pv/pv.go +++ b/test/e2e/framework/pv/pv.go @@ -433,7 +433,7 @@ func CreatePVsPVCs(ctx context.Context, numpvs, numpvcs int, c clientset.Interfa pvsToCreate := numpvs - extraPVs // want the min(numpvs, numpvcs) // create pvs and pvcs - for i := 0; i < pvsToCreate; i++ { + for range pvsToCreate { pv, pvc, err := CreatePVPVC(ctx, c, timeouts, pvConfig, pvcConfig, ns, false) if err != nil { return pvMap, pvcMap, err diff --git a/test/e2e/framework/service/jig.go b/test/e2e/framework/service/jig.go index 78cd28d1a05..ecbd897496c 100644 --- a/test/e2e/framework/service/jig.go +++ b/test/e2e/framework/service/jig.go @@ -548,7 +548,7 @@ func needsNodePorts(svc *v1.Service) bool { // then attempts to send the updated service. It tries up to 3 times in the // face of timeouts and conflicts. func (j *TestJig) UpdateService(ctx context.Context, update func(*v1.Service)) (*v1.Service, error) { - for i := 0; i < 3; i++ { + for range 3 { service, err := j.Client.CoreV1().Services(j.Namespace).Get(ctx, j.Name, metav1.GetOptions{}) if err != nil { return nil, fmt.Errorf("failed to get Service %q: %w", j.Name, err) diff --git a/test/e2e/framework/service/resource.go b/test/e2e/framework/service/resource.go index 21a18546282..e612e18f435 100644 --- a/test/e2e/framework/service/resource.go +++ b/test/e2e/framework/service/resource.go @@ -64,7 +64,7 @@ func CreateServiceSpec(serviceName, externalName string, isHeadless bool, select func UpdateService(ctx context.Context, c clientset.Interface, namespace, serviceName string, update func(*v1.Service)) (*v1.Service, error) { var service *v1.Service var err error - for i := 0; i < 3; i++ { + for range 3 { service, err = c.CoreV1().Services(namespace).Get(ctx, serviceName, metav1.GetOptions{}) if err != nil { return service, err diff --git a/test/e2e/framework/volume/fixtures.go b/test/e2e/framework/volume/fixtures.go index b2938eae896..ebbc0083a5b 100644 --- a/test/e2e/framework/volume/fixtures.go +++ b/test/e2e/framework/volume/fixtures.go @@ -302,7 +302,7 @@ func startVolumeServer(ctx context.Context, client clientset.Interface, config T portCount := len(config.ServerPorts) serverPodPorts := make([]v1.ContainerPort, portCount) - for i := 0; i < portCount; i++ { + for i := range portCount { portName := fmt.Sprintf("%s-%d", config.Prefix, i) serverPodPorts[i] = v1.ContainerPort{ diff --git a/test/e2e/kubectl/exec.go b/test/e2e/kubectl/exec.go index de3cceb8943..9509edaec8f 100644 --- a/test/e2e/kubectl/exec.go +++ b/test/e2e/kubectl/exec.go @@ -69,11 +69,11 @@ var _ = SIGDescribe("Kubectl exec", func() { // 10 workers for 1000 executions ginkgo.By("Starting workers to exec on pod") - for w := 0; w < 10; w++ { + for w := range 10 { framework.Logf("Starting worker %d", w) go worker(f, pod, w, jobs, results) } - for i := 0; i < size; i++ { + for i := range size { framework.Logf("Sending job %d", i) jobs <- i } @@ -81,7 +81,7 @@ var _ = SIGDescribe("Kubectl exec", func() { close(jobs) errors := []error{} - for c := 0; c < size; c++ { + for c := range size { framework.Logf("Getting results %d", c) err := <-results if err != nil { diff --git a/test/e2e/kubectl/kubectl.go b/test/e2e/kubectl/kubectl.go index 34c170498a8..bcaa3f607c1 100644 --- a/test/e2e/kubectl/kubectl.go +++ b/test/e2e/kubectl/kubectl.go @@ -239,7 +239,7 @@ func readTestFileOrDie(file string) []byte { func runKubectlRetryOrDie(ns string, args ...string) string { var err error var output string - for i := 0; i < 5; i++ { + for range 5 { output, err = e2ekubectl.RunKubectl(ns, args...) if err == nil || (!strings.Contains(err.Error(), genericregistry.OptimisticLockErrorMsg) && !strings.Contains(err.Error(), "Operation cannot be fulfilled")) { break @@ -446,7 +446,7 @@ var _ = SIGDescribe("Kubectl client", func() { ginkgo.By("executing a very long command in the container") veryLongData := make([]rune, 20000) - for i := 0; i < len(veryLongData); i++ { + for i := range veryLongData { veryLongData[i] = 'a' } execOutput = e2ekubectl.RunKubectlOrDie(ns, "exec", podRunningTimeoutArg, simplePodName, "--", "echo", string(veryLongData)) diff --git a/test/e2e/network/dns_scale_records.go b/test/e2e/network/dns_scale_records.go index 806ba1387dc..a533b3e7177 100644 --- a/test/e2e/network/dns_scale_records.go +++ b/test/e2e/network/dns_scale_records.go @@ -61,7 +61,7 @@ var _ = common.SIGDescribe(feature.PerformanceDNS, framework.WithSerial(), func( numNs := (maxServicesPerCluster + maxServicesPerNamespace - 1) / maxServicesPerNamespace var namespaces []string - for i := 0; i < numNs; i++ { + for range numNs { ns, _ := f.CreateNamespace(ctx, f.BaseName, nil) namespaces = append(namespaces, ns.Name) f.AddNamespacesToDelete(ns) @@ -82,7 +82,7 @@ var _ = common.SIGDescribe(feature.PerformanceDNS, framework.WithSerial(), func( dnsTest.createUtilPodLabel(ctx, "e2e-dns-scale-records") ginkgo.DeferCleanup(dnsTest.deleteUtilPod) framework.Logf("Querying %v%% of service records", checkServicePercent*100) - for i := 0; i < len(services); i++ { + for i := range services { if i%(1/checkServicePercent) != 0 { continue } @@ -105,7 +105,7 @@ var _ = common.SIGDescribe(feature.PerformanceDNS, framework.WithSerial(), func( func generateServicesInNamespaces(namespaces []string, num int) []*v1.Service { services := make([]*v1.Service, num) - for i := 0; i < num; i++ { + for i := range num { services[i] = &v1.Service{ ObjectMeta: metav1.ObjectMeta{ Name: "svc-" + strconv.Itoa(i), diff --git a/test/e2e/network/hostport.go b/test/e2e/network/hostport.go index 56b2fb2cedc..25d7b00a2a0 100644 --- a/test/e2e/network/hostport.go +++ b/test/e2e/network/hostport.go @@ -124,7 +124,7 @@ var _ = common.SIGDescribe("HostPort", func() { cmdPod2 := []string{"/bin/sh", "-c", fmt.Sprintf("curl -g --connect-timeout %v http://%s/hostname", timeout, net.JoinHostPort(hostIP, strconv.Itoa(int(port))))} cmdPod3 := []string{"/bin/sh", "-c", fmt.Sprintf("echo hostname | nc -u -w %v %s %d", timeout, hostIP, port)} // try 5 times to connect to the exposed ports - for i := 0; i < 5; i++ { + for range 5 { // check pod1 ginkgo.By(fmt.Sprintf("checking connectivity from pod %s to serverIP: %s, port: %d", hostExecPod.Name, localhost, port)) hostname1, _, err := e2epod.ExecCommandInContainerWithFullOutput(f, hostExecPod.Name, "e2e-host-exec", cmdPod1...) diff --git a/test/e2e/network/kube_proxy.go b/test/e2e/network/kube_proxy.go index 41ada214a7d..58f05e924f1 100644 --- a/test/e2e/network/kube_proxy.go +++ b/test/e2e/network/kube_proxy.go @@ -365,7 +365,7 @@ var _ = common.SIGDescribe("KubeProxy", func() { framework.ExpectNoError(err) ginkgo.By("accessing endpoint via localhost nodeports 10 times") - for i := 0; i < 10; i++ { + for range 10 { if err := wait.PollUntilContextTimeout(ctx, 1*time.Second, 10*time.Second, true, func(_ context.Context) (bool, error) { _, err = e2epodoutput.RunHostCmd(fr.Namespace.Name, hostExecPodName, fmt.Sprintf("curl --silent http://localhost:%d/hostname", svc.Spec.Ports[0].NodePort)) if err != nil { diff --git a/test/e2e/network/netpol/probe.go b/test/e2e/network/netpol/probe.go index 144e1886fbd..bfe48af0b4d 100644 --- a/test/e2e/network/netpol/probe.go +++ b/test/e2e/network/netpol/probe.go @@ -88,7 +88,7 @@ func ProbePodToPodConnectivity(prober Prober, allPods []TestPod, dnsDomain strin } close(jobs) - for i := 0; i < size; i++ { + for range size { result := <-results job := result.Job if result.Err != nil { diff --git a/test/e2e/network/netpol/test_helper.go b/test/e2e/network/netpol/test_helper.go index b54c7781a43..97fa93ebbc8 100644 --- a/test/e2e/network/netpol/test_helper.go +++ b/test/e2e/network/netpol/test_helper.go @@ -84,7 +84,7 @@ func waitForHTTPServers(k *kubeManager, model *Model) error { notReady[caseName] = true } - for i := 0; i < maxTries; i++ { + for range maxTries { for caseName, testCase := range testCases { if notReady[caseName] { reachability := NewReachability(k.AllPodStrings(), true) diff --git a/test/e2e/network/pod_lifecycle.go b/test/e2e/network/pod_lifecycle.go index a7a246f111f..58d6ddc5004 100644 --- a/test/e2e/network/pod_lifecycle.go +++ b/test/e2e/network/pod_lifecycle.go @@ -183,7 +183,7 @@ var _ = common.SIGDescribe("Connectivity Pod Lifecycle", func() { ginkgo.By("Try to connect to the blue pod through the service") scvAddress := net.JoinHostPort(blueGreenService.Spec.ClusterIP, strconv.Itoa(80)) // assert 5 times that we can connect only to the blue pod - for i := 0; i < 5; i++ { + for range 5 { err := wait.PollUntilContextTimeout(ctx, 3*time.Second, 30*time.Second, true, func(ctx context.Context) (done bool, err error) { cmd := fmt.Sprintf(`curl -q -s --connect-timeout 5 %s/hostname`, scvAddress) stdout, err := e2eoutput.RunHostCmd(clientPod.Namespace, clientPod.Name, cmd) @@ -301,7 +301,7 @@ var _ = common.SIGDescribe("Connectivity Pod Lifecycle", func() { ginkgo.By("Try to connect to the green pod through the service") // assert 5 times that we can connect ONLY to the green pod - for i := 0; i < 5; i++ { + for range 5 { err := wait.PollUntilContextTimeout(ctx, 3*time.Second, e2eservice.KubeProxyEndpointLagTimeout, true, func(ctx context.Context) (done bool, err error) { cmd := fmt.Sprintf(`curl -q -s --connect-timeout 5 %s/hostname`, scvAddress) stdout, err := e2eoutput.RunHostCmd(clientPod.Namespace, clientPod.Name, cmd) diff --git a/test/e2e/network/proxy.go b/test/e2e/network/proxy.go index 0897d71a291..4925872fdbe 100644 --- a/test/e2e/network/proxy.go +++ b/test/e2e/network/proxy.go @@ -284,7 +284,7 @@ var _ = common.SIGDescribe("Proxy", func() { totalAttempts := numberTestCases * proxyAttempts ginkgo.By(fmt.Sprintf("running %v cases, %v attempts per case, %v total attempts", numberTestCases, proxyAttempts, totalAttempts)) - for i := 0; i < proxyAttempts; i++ { + for i := range proxyAttempts { wg.Add(numberTestCases) for path, val := range expectations { go func(i int, path, val string) { @@ -631,7 +631,7 @@ func nodeProxyTest(ctx context.Context, f *framework.Framework, prefix, nodeDest // TODO: Change it to test whether all requests succeeded when requests // not reaching Kubelet issue is debugged. serviceUnavailableErrors := 0 - for i := 0; i < proxyAttempts; i++ { + for i := range proxyAttempts { _, status, d, err := doProxy(ctx, f, prefix+node.Name+nodeDest, i) if status == http.StatusServiceUnavailable { framework.Logf("ginkgo.Failed proxying node logs due to service unavailable: %v", err) diff --git a/test/e2e/network/service.go b/test/e2e/network/service.go index f1cd06b3e7d..08efe86412c 100644 --- a/test/e2e/network/service.go +++ b/test/e2e/network/service.go @@ -150,7 +150,7 @@ func affinityCheckFromTest(ctx context.Context, cs clientset.Interface, serviceI params := &e2enetwork.HTTPPokeParams{Timeout: 2 * time.Second} getHosts := func() []string { var hosts []string - for i := 0; i < AffinityConfirmCount; i++ { + for range AffinityConfirmCount { result := e2enetwork.PokeHTTP(serviceIP, servicePort, "", params) if result.Status == e2enetwork.HTTPSuccess { hosts = append(hosts, string(result.Body)) @@ -1712,7 +1712,7 @@ var _ = common.SIGDescribe("Services", func() { numberOfRetries := 5 ginkgo.By("creating service " + serviceName + " with type NodePort in namespace " + ns) var err error - for i := 0; i < numberOfRetries; i++ { + for range numberOfRetries { port, err := e2eservice.GetUnusedStaticNodePort() framework.ExpectNoError(err, "Static node port allocator was not able to find a free nodeport.") baseService.Spec.Ports[0].NodePort = port @@ -2056,7 +2056,7 @@ var _ = common.SIGDescribe("Services", func() { nodePortAddress0 := net.JoinHostPort(nodeIPs0[0], strconv.Itoa(int(svc.Spec.Ports[0].NodePort))) nodePortAddress1 := net.JoinHostPort(nodeIPs1[0], strconv.Itoa(int(svc.Spec.Ports[0].NodePort))) // connect 3 times every 5 seconds to the Service with the unready and terminating endpoint - for i := 0; i < 5; i++ { + for range 5 { execHostnameTest(*pausePod1, clusterIPAddress, webserverPod0.Name) execHostnameTest(*pausePod1, nodePortAddress0, webserverPod0.Name) execHostnameTest(*pausePod1, nodePortAddress1, webserverPod0.Name) @@ -2199,7 +2199,7 @@ var _ = common.SIGDescribe("Services", func() { clusterIPAddress := net.JoinHostPort(svc.Spec.ClusterIP, strconv.Itoa(servicePort)) // connect 3 times every 5 seconds to the Service and expect a failure - for i := 0; i < 5; i++ { + for range 5 { cmd = fmt.Sprintf(`curl -q -s --connect-timeout 5 %s/hostname`, clusterIPAddress) _, err := e2eoutput.RunHostCmd(pausePod1.Namespace, pausePod1.Name, cmd) gomega.Expect(err).To(gomega.HaveOccurred(), "expected error when trying to connect to cluster IP") @@ -2582,7 +2582,7 @@ var _ = common.SIGDescribe("Services", func() { // assert 5 times that the first pause pod can connect to the Service locally and the second one errors with a timeout serviceAddress := net.JoinHostPort(svc.Spec.ClusterIP, strconv.Itoa(servicePort)) - for i := 0; i < 5; i++ { + for range 5 { // the first pause pod should be on the same node as the webserver, so it can connect to the local pod using clusterIP execHostnameTest(*pausePod0, serviceAddress, webserverPod0.Name) @@ -2653,7 +2653,7 @@ var _ = common.SIGDescribe("Services", func() { // assert 5 times that the first pause pod can connect to the Service locally and the second one errors with a timeout serviceAddress := net.JoinHostPort(svc.Spec.ClusterIP, strconv.Itoa(servicePort)) - for i := 0; i < 5; i++ { + for range 5 { // the first pause pod should be on the same node as the webserver, so it can connect to the local pod using clusterIP execHostnameTest(*pausePod0, serviceAddress, webserverPod0.Name) @@ -2726,7 +2726,7 @@ var _ = common.SIGDescribe("Services", func() { // assert 5 times that the first pause pod can connect to the Service locally and the second one errors with a timeout serviceAddress := net.JoinHostPort(svc.Spec.ClusterIP, strconv.Itoa(servicePort)) - for i := 0; i < 5; i++ { + for range 5 { // the first pause pod should be on the same node as the webserver, so it can connect to the local pod using clusterIP // note that the expected hostname is the node name because the backend pod is on host network execHostnameTest(*pausePod0, serviceAddress, node0.Name) @@ -2755,7 +2755,7 @@ var _ = common.SIGDescribe("Services", func() { framework.ExpectNoError(e2epod.WaitTimeoutForPodReadyInNamespace(ctx, f.ClientSet, pausePod3.Name, f.Namespace.Name, framework.PodStartTimeout)) // assert 5 times that the first pause pod can connect to the Service locally and the second one errors with a timeout - for i := 0; i < 5; i++ { + for range 5 { // the first pause pod should be on the same node as the webserver, so it can connect to the local pod using clusterIP // note that the expected hostname is the node name because the backend pod is on host network execHostnameTest(*pausePod2, serviceAddress, node0.Name) @@ -2977,7 +2977,7 @@ var _ = common.SIGDescribe("Services", func() { // assert 5 times that both the local and remote pod can connect to the Service while all endpoints are terminating serviceAddress := net.JoinHostPort(svc.Spec.ClusterIP, strconv.Itoa(servicePort)) - for i := 0; i < 5; i++ { + for range 5 { // There's a Service with internalTrafficPolicy=Cluster, // with a single endpoint (which is terminating) called webserver0 running on node0. // pausePod0 and pausePod1 are on node0 and node1 respectively. @@ -3053,7 +3053,7 @@ var _ = common.SIGDescribe("Services", func() { // assert 5 times that the first pause pod can connect to the Service locally and the second one errors with a timeout serviceAddress := net.JoinHostPort(svc.Spec.ClusterIP, strconv.Itoa(servicePort)) - for i := 0; i < 5; i++ { + for range 5 { // There's a Service with internalTrafficPolicy=Local, // with a single endpoint (which is terminating) called webserver0 running on node0. // pausePod0 and pausePod1 are on node0 and node1 respectively. @@ -3132,7 +3132,7 @@ var _ = common.SIGDescribe("Services", func() { // assert 5 times that both the local and remote pod can connect to the Service NodePort while all endpoints are terminating nodeIPs := e2enode.GetAddresses(&node0, v1.NodeInternalIP) nodePortAddress := net.JoinHostPort(nodeIPs[0], strconv.Itoa(int(svc.Spec.Ports[0].NodePort))) - for i := 0; i < 5; i++ { + for range 5 { // There's a Service Type=NodePort with externalTrafficPolicy=Cluster, // with a single endpoint (which is terminating) called webserver0 running on node0. // pausePod0 and pausePod1 are on node0 and node1 respectively. @@ -3211,7 +3211,7 @@ var _ = common.SIGDescribe("Services", func() { nodeIPs1 := e2enode.GetAddresses(&node1, v1.NodeInternalIP) nodePortAddress0 := net.JoinHostPort(nodeIPs0[0], strconv.Itoa(int(svc.Spec.Ports[0].NodePort))) nodePortAddress1 := net.JoinHostPort(nodeIPs1[0], strconv.Itoa(int(svc.Spec.Ports[0].NodePort))) - for i := 0; i < 5; i++ { + for range 5 { // There's a Service Type=NodePort with externalTrafficPolicy=Local, // with a single endpoint (which is terminating) called webserver0 running on node0. // pausePod0 and pausePod1 are on node0 and node1 respectively. @@ -3847,7 +3847,7 @@ var _ = common.SIGDescribe("Services", func() { ginkgo.By("creating the service") var svc *v1.Service numberOfRetries := 5 - for i := 0; i < numberOfRetries; i++ { + for range numberOfRetries { port, err := e2eservice.GetUnusedStaticNodePort() framework.ExpectNoError(err, "Static node port allocator was not able to find a free nodeport.") svc, err = jig.CreateLoadBalancerServiceWaitForClusterIPOnly(func(svc *v1.Service) { @@ -4237,7 +4237,7 @@ func execAffinityTestForSessionAffinityTimeout(ctx context.Context, f *framework // try several times to avoid the probability that we hit the same pod twice hosts := sets.NewString() cmd := fmt.Sprintf(`curl -q -s --connect-timeout 2 http://%s/`, net.JoinHostPort(svcIP, strconv.Itoa(servicePort))) - for i := 0; i < 10; i++ { + for range 10 { hostname, err := e2eoutput.RunHostCmd(execPod.Namespace, execPod.Name, cmd) if err == nil { hosts.Insert(hostname) diff --git a/test/e2e/network/service_cidrs.go b/test/e2e/network/service_cidrs.go index c7733743ca8..3c4cc515410 100644 --- a/test/e2e/network/service_cidrs.go +++ b/test/e2e/network/service_cidrs.go @@ -107,7 +107,7 @@ var _ = common.SIGDescribe("Service CIDRs", func() { // gets allocated, we also need to ensure the ClusterIP belongs to the new Service range // so we need to explicitly set it. Try several times before giving up. var nodePortService *v1.Service - for i := 0; i < 5; i++ { + for range 5 { nodePortService, err = jig.CreateTCPService(ctx, func(svc *v1.Service) { svc.Spec.ClusterIP = serviceIP.String() svc.Spec.Type = v1.ServiceTypeNodePort diff --git a/test/e2e/network/service_latency.go b/test/e2e/network/service_latency.go index d6304ad289f..d87717c34cc 100644 --- a/test/e2e/network/service_latency.go +++ b/test/e2e/network/service_latency.go @@ -163,7 +163,7 @@ func runServiceLatencies(ctx context.Context, f *framework.Framework, inParallel durations := make(chan time.Duration, total) blocker := make(chan struct{}, inParallel) - for i := 0; i < total; i++ { + for range total { go func() { defer ginkgo.GinkgoRecover() blocker <- struct{}{} @@ -177,7 +177,7 @@ func runServiceLatencies(ctx context.Context, f *framework.Framework, inParallel } errCount := 0 - for i := 0; i < total; i++ { + for range total { select { case e := <-errs: framework.Logf("Got error: %v", e) diff --git a/test/e2e/node/pods.go b/test/e2e/node/pods.go index 58d5d07cf51..e42ee716fa5 100644 --- a/test/e2e/node/pods.go +++ b/test/e2e/node/pods.go @@ -596,7 +596,7 @@ var _ = SIGDescribe("Pods Extended (pod generation)", func() { return podClient.Delete(ctx, pod.Name, metav1.DeleteOptions{}) }) - for i := 0; i < 499; i++ { + for range 499 { podClient.Update(ctx, pod.Name, func(pod *v1.Pod) { *pod.Spec.ActiveDeadlineSeconds-- }) @@ -1323,12 +1323,12 @@ func createAndTestPodRepeatedly(ctx context.Context, workers, iterations int, sc }, []string{"node"}) r.MustRegister(h) - for i := 0; i < workers; i++ { + for i := range workers { wg.Add(1) go func(i int) { defer ginkgo.GinkgoRecover() defer wg.Done() - for retries := 0; retries < iterations; retries++ { + for retries := range iterations { pod := scenario.Pod(i, retries) // create the pod, capture the change events, then delete the pod diff --git a/test/e2e/scheduling/preemption.go b/test/e2e/scheduling/preemption.go index 6bbab4c02b0..37df7b84d02 100644 --- a/test/e2e/scheduling/preemption.go +++ b/test/e2e/scheduling/preemption.go @@ -137,7 +137,7 @@ var _ = SIGDescribe("SchedulerPreemption", framework.WithSerial(), func() { // Update each node to advertise 3 available extended resources e2enode.AddExtendedResource(ctx, cs, node.Name, testExtendedResource, resource.MustParse("5")) - for j := 0; j < 2; j++ { + for j := range 2 { // Request 2 of the available resources for the victim pods podRes = v1.ResourceList{} podRes[testExtendedResource] = resource.MustParse("2") @@ -224,7 +224,7 @@ var _ = SIGDescribe("SchedulerPreemption", framework.WithSerial(), func() { // Update each node to advertise 3 available extended resources e2enode.AddExtendedResource(ctx, cs, node.Name, testExtendedResource, resource.MustParse("5")) - for j := 0; j < 2; j++ { + for j := range 2 { // Request 2 of the available resources for the victim pods podRes = v1.ResourceList{} podRes[testExtendedResource] = resource.MustParse("2") @@ -328,7 +328,7 @@ var _ = SIGDescribe("SchedulerPreemption", framework.WithSerial(), func() { e2enode.AddExtendedResource(ctx, cs, node.Name, testExtendedResource, resource.MustParse("10")) // Create 10 low priority pods on each node, which will use up 10/10 of the node's resources. - for j := 0; j < 10; j++ { + for j := range 10 { // Request 1 of the available resources for the victim pods podRes = v1.ResourceList{} podRes[testExtendedResource] = resource.MustParse("1") @@ -379,7 +379,7 @@ var _ = SIGDescribe("SchedulerPreemption", framework.WithSerial(), func() { for i := range nodeList.Items { // Create medium priority pods first // to confirm the scheduler finally prioritize the high priority pods, ignoring the medium priority pods. - for j := 0; j < 10; j++ { + for j := range 10 { // 5 pods per node will be unschedulable // because the node only has 10 resource, and high priority pods will use 5 resource. p := createPausePod(ctx, f, pausePodConfig{ @@ -410,7 +410,7 @@ var _ = SIGDescribe("SchedulerPreemption", framework.WithSerial(), func() { ginkgo.By("Run high priority pods that have same requirements as that of lower priority pod") for i := range nodeList.Items { - for j := 0; j < 5; j++ { + for j := range 5 { p := createPausePod(ctx, f, pausePodConfig{ Name: fmt.Sprintf("pod%d-%d-%v", i, j, highPriorityClassName), PriorityClassName: highPriorityClassName, @@ -875,7 +875,7 @@ var _ = SIGDescribe("SchedulerPreemption", framework.WithSerial(), func() { // "*2" means pods of ReplicaSet{1,2} are expected to be only preempted once. expectedRSPods := []int32{1 * 2, 1 * 2, 1} err := wait.PollUntilContextTimeout(ctx, framework.Poll, framework.PollShortTimeout, false, func(ctx context.Context) (bool, error) { - for i := 0; i < len(podNamesSeen); i++ { + for i := range len(podNamesSeen) { got := podNamesSeen[i].Load() if got < expectedRSPods[i] { framework.Logf("waiting for rs%d to observe %d pod creations, got %d", i+1, expectedRSPods[i], got) @@ -899,7 +899,7 @@ var _ = SIGDescribe("SchedulerPreemption", framework.WithSerial(), func() { // If logic continues to here, we should do a final check to ensure within a time period, // the state is stable; otherwise, pods may be over-preempted. time.Sleep(5 * time.Second) - for i := 0; i < len(podNamesSeen); i++ { + for i := range len(podNamesSeen) { got := podNamesSeen[i].Load() if got < expectedRSPods[i] { framework.Failf("pods of ReplicaSet%d have been under-preempted: expect %v pod names, but got %d", i+1, expectedRSPods[i], got) diff --git a/test/e2e/scheduling/priorities.go b/test/e2e/scheduling/priorities.go index 91dac4bdfa2..903ed069ea0 100644 --- a/test/e2e/scheduling/priorities.go +++ b/test/e2e/scheduling/priorities.go @@ -210,7 +210,7 @@ var _ = SIGDescribe("SchedulerPriorities", framework.WithSerial(), func() { // Generate 10 tolerable taints for the first node (and matching tolerations) tolerableTaints := make([]v1.Taint, 0) var tolerations []v1.Toleration - for i := 0; i < 10; i++ { + for range 10 { testTaint := getRandomTaint() tolerableTaints = append(tolerableTaints, testTaint) tolerations = append(tolerations, v1.Toleration{Key: testTaint.Key, Value: testTaint.Value, Effect: testTaint.Effect}) @@ -219,7 +219,7 @@ var _ = SIGDescribe("SchedulerPriorities", framework.WithSerial(), func() { intolerableTaints := make(map[string][]v1.Taint) for i := 1; i < len(nodeList.Items); i++ { nodeTaints := make([]v1.Taint, 0) - for i := 0; i < 10; i++ { + for range 10 { nodeTaints = append(nodeTaints, getRandomTaint()) } intolerableTaints[nodeList.Items[i].Name] = nodeTaints diff --git a/test/e2e/storage/empty_dir_wrapper.go b/test/e2e/storage/empty_dir_wrapper.go index a2bce3eddaa..c6d489d0475 100644 --- a/test/e2e/storage/empty_dir_wrapper.go +++ b/test/e2e/storage/empty_dir_wrapper.go @@ -191,7 +191,7 @@ var _ = utils.SIGDescribe("EmptyDir wrapper volumes", func() { configMapNames := createConfigmapsForRace(ctx, f) ginkgo.DeferCleanup(deleteConfigMaps, f, configMapNames) volumes, volumeMounts := makeConfigMapVolumes(configMapNames) - for i := 0; i < wrappedVolumeRaceConfigMapIterationCount; i++ { + for range wrappedVolumeRaceConfigMapIterationCount { testNoWrappedVolumeRace(ctx, f, volumes, volumeMounts, wrappedVolumeRaceConfigMapPodCount) } }) @@ -204,7 +204,7 @@ var _ = utils.SIGDescribe("EmptyDir wrapper volumes", func() { gitURL, gitRepo, cleanup := createGitServer(ctx, f) defer cleanup() volumes, volumeMounts := makeGitRepoVolumes(gitURL, gitRepo) - for i := 0; i < wrappedVolumeRaceGitRepoIterationCount; i++ { + for range wrappedVolumeRaceGitRepoIterationCount { testNoWrappedVolumeRace(ctx, f, volumes, volumeMounts, wrappedVolumeRaceGitRepoPodCount) } }) @@ -257,7 +257,7 @@ func createGitServer(ctx context.Context, f *framework.Framework) (gitURL string } func makeGitRepoVolumes(gitURL, gitRepo string) (volumes []v1.Volume, volumeMounts []v1.VolumeMount) { - for i := 0; i < wrappedVolumeRaceGitRepoVolumeCount; i++ { + for i := range wrappedVolumeRaceGitRepoVolumeCount { volumeName := fmt.Sprintf("racey-git-repo-%d", i) volumes = append(volumes, v1.Volume{ Name: volumeName, @@ -278,7 +278,7 @@ func makeGitRepoVolumes(gitURL, gitRepo string) (volumes []v1.Volume, volumeMoun func createConfigmapsForRace(ctx context.Context, f *framework.Framework) (configMapNames []string) { ginkgo.By(fmt.Sprintf("Creating %d configmaps", wrappedVolumeRaceConfigMapVolumeCount)) - for i := 0; i < wrappedVolumeRaceConfigMapVolumeCount; i++ { + for i := range wrappedVolumeRaceConfigMapVolumeCount { configMapName := fmt.Sprintf("racey-configmap-%d", i) configMapNames = append(configMapNames, configMapName) configMap := &v1.ConfigMap{ diff --git a/test/e2e/storage/persistent_volumes-local.go b/test/e2e/storage/persistent_volumes-local.go index d2c4275dd49..d886731916b 100644 --- a/test/e2e/storage/persistent_volumes-local.go +++ b/test/e2e/storage/persistent_volumes-local.go @@ -576,9 +576,9 @@ var _ = utils.SIGDescribe("PersistentVolumes-local", func() { return } - for i := 0; i < numConcurrentPods; i++ { + for range numConcurrentPods { pvcs := []*v1.PersistentVolumeClaim{} - for j := 0; j < volsPerPod; j++ { + for range volsPerPod { pvc := e2epv.MakePersistentVolumeClaim(makeLocalPVCConfig(config, volType), config.ns) pvc, err := e2epv.CreatePVC(ctx, config.client, config.ns, pvc) framework.ExpectNoError(err) @@ -776,7 +776,7 @@ func podNodeName(ctx context.Context, config *localTestConfig, pod *v1.Pod) (str // setupLocalVolumes sets up directories to use for local PV func setupLocalVolumes(ctx context.Context, config *localTestConfig, localVolumeType localVolumeType, node *v1.Node, count int) []*localTestVolume { vols := []*localTestVolume{} - for i := 0; i < count; i++ { + for range count { ltrType, ok := setupLocalVolumeMap[localVolumeType] if !ok { framework.Failf("Invalid localVolumeType: %v", localVolumeType) @@ -1081,7 +1081,7 @@ func newLocalClaimWithName(config *localTestConfig, name string) *v1.PersistentV func createStatefulSet(ctx context.Context, config *localTestConfig, ssReplicas int32, volumeCount int, anti, parallel bool) *appsv1.StatefulSet { mounts := []v1.VolumeMount{} claims := []v1.PersistentVolumeClaim{} - for i := 0; i < volumeCount; i++ { + for i := range volumeCount { name := fmt.Sprintf("vol%v", i+1) pvc := newLocalClaimWithName(config, name) mounts = append(mounts, v1.VolumeMount{Name: name, MountPath: "/" + name}) diff --git a/test/e2e/storage/persistent_volumes.go b/test/e2e/storage/persistent_volumes.go index f6dd3c73e6b..68913fd83f2 100644 --- a/test/e2e/storage/persistent_volumes.go +++ b/test/e2e/storage/persistent_volumes.go @@ -831,7 +831,7 @@ var _ = utils.SIGDescribe("PersistentVolumes", func() { ginkgo.By("Creating a StatefulSet pod to initialize data") writeCmd := "true" - for i := 0; i < numVols; i++ { + for i := range numVols { writeCmd += fmt.Sprintf("&& touch %v", getVolumeFile(i)) } writeCmd += "&& sleep 10000" @@ -850,7 +850,7 @@ var _ = utils.SIGDescribe("PersistentVolumes", func() { mounts := []v1.VolumeMount{} claims := []v1.PersistentVolumeClaim{} - for i := 0; i < numVols; i++ { + for i := range numVols { pvc := e2epv.MakePersistentVolumeClaim(e2epv.PersistentVolumeClaimConfig{}, ns) pvc.Name = getVolName(i) mounts = append(mounts, v1.VolumeMount{Name: pvc.Name, MountPath: getMountPath(i)}) @@ -872,7 +872,7 @@ var _ = utils.SIGDescribe("PersistentVolumes", func() { ginkgo.By("Creating a new Statefulset and validating the data") validateCmd := "true" - for i := 0; i < numVols; i++ { + for i := range numVols { validateCmd += fmt.Sprintf("&& test -f %v", getVolumeFile(i)) } validateCmd += "&& sleep 10000" diff --git a/test/e2e/storage/testsuites/multivolume.go b/test/e2e/storage/testsuites/multivolume.go index a3d4acff814..4b8aa5bbce7 100644 --- a/test/e2e/storage/testsuites/multivolume.go +++ b/test/e2e/storage/testsuites/multivolume.go @@ -149,7 +149,7 @@ func (t *multiVolumeTestSuite) DefineTests(driver storageframework.TestDriver, p var pvcs []*v1.PersistentVolumeClaim numVols := 2 - for i := 0; i < numVols; i++ { + for range numVols { testVolumeSizeRange := t.GetTestSuiteInfo().SupportedSizeRange resource := storageframework.CreateVolumeResource(ctx, driver, l.config, pattern, testVolumeSizeRange) l.resources = append(l.resources, resource) @@ -189,7 +189,7 @@ func (t *multiVolumeTestSuite) DefineTests(driver storageframework.TestDriver, p var pvcs []*v1.PersistentVolumeClaim numVols := 2 - for i := 0; i < numVols; i++ { + for range numVols { testVolumeSizeRange := t.GetTestSuiteInfo().SupportedSizeRange resource := storageframework.CreateVolumeResource(ctx, driver, l.config, pattern, testVolumeSizeRange) l.resources = append(l.resources, resource) @@ -223,7 +223,7 @@ func (t *multiVolumeTestSuite) DefineTests(driver storageframework.TestDriver, p var pvcs []*v1.PersistentVolumeClaim numVols := 2 - for i := 0; i < numVols; i++ { + for i := range numVols { curPattern := pattern if i != 0 { // 1st volume should be block and set filesystem for 2nd and later volumes @@ -273,7 +273,7 @@ func (t *multiVolumeTestSuite) DefineTests(driver storageframework.TestDriver, p var pvcs []*v1.PersistentVolumeClaim numVols := 2 - for i := 0; i < numVols; i++ { + for i := range numVols { curPattern := pattern if i != 0 { // 1st volume should be block and set filesystem for 2nd and later volumes @@ -564,7 +564,7 @@ func TestConcurrentAccessToSingleVolume(ctx context.Context, f *framework.Framew var pods []*v1.Pod // Create each pod with pvc - for i := 0; i < numPods; i++ { + for i := range numPods { index := i + 1 ginkgo.By(fmt.Sprintf("Creating pod%d with a volume on %+v", index, node)) podConfig := e2epod.Config{ diff --git a/test/e2e/storage/testsuites/provisioning.go b/test/e2e/storage/testsuites/provisioning.go index 938ca5d965d..895bca89991 100644 --- a/test/e2e/storage/testsuites/provisioning.go +++ b/test/e2e/storage/testsuites/provisioning.go @@ -659,7 +659,7 @@ func (p *provisioningTestSuite) DefineTests(driver storageframework.TestDriver, l.pvc.Spec.DataSourceRef = dataSourceRef var wg sync.WaitGroup - for i := 0; i < 5; i++ { + for i := range 5 { wg.Add(1) go func(i int) { defer ginkgo.GinkgoRecover() diff --git a/test/e2e/storage/testsuites/snapshottable.go b/test/e2e/storage/testsuites/snapshottable.go index 69580e27a01..c8fe3cc585f 100644 --- a/test/e2e/storage/testsuites/snapshottable.go +++ b/test/e2e/storage/testsuites/snapshottable.go @@ -315,7 +315,7 @@ func (s *snapshottableTestSuite) DefineTests(driver storageframework.TestDriver, framework.ExpectNoError(err) volumesInUse := node.Status.VolumesInUse framework.Logf("current volumes in use: %+v", volumesInUse) - for i := 0; i < len(volumesInUse); i++ { + for i := range volumesInUse { if strings.HasSuffix(string(volumesInUse[i]), volumeName) { return false } diff --git a/test/e2e/storage/testsuites/topology.go b/test/e2e/storage/testsuites/topology.go index 74292a8e461..ac2617c8ca1 100644 --- a/test/e2e/storage/testsuites/topology.go +++ b/test/e2e/storage/testsuites/topology.go @@ -282,7 +282,7 @@ func (t *topologyTestSuite) setAllowedTopologies(sc *storagev1.StorageClass, top allowedTopologies := []topology{} sc.AllowedTopologies = []v1.TopologySelectorTerm{} - for i := 0; i < len(topos); i++ { + for i := range topos { if i != excludedIndex { exprs := []v1.TopologySelectorLabelRequirement{} for k, v := range topos[i] { diff --git a/test/e2e/storage/testsuites/volumelimits.go b/test/e2e/storage/testsuites/volumelimits.go index 153437705cb..a18b7f63618 100644 --- a/test/e2e/storage/testsuites/volumelimits.go +++ b/test/e2e/storage/testsuites/volumelimits.go @@ -224,7 +224,7 @@ func (t *volumeLimitsTestSuite) DefineTests(driver storageframework.TestDriver, if pattern.VolType == storageframework.GenericEphemeralVolume { // Create Pods. ginkgo.By(fmt.Sprintf("Creating %d Pod(s) with one volume each", limit)) - for i := 0; i < limit; i++ { + for range limit { pod := StartInPodWithVolumeSource(ctx, l.cs, *l.resource.VolSource, l.ns.Name, "volume-limits", e2epod.InfiniteSleepCommand, selection) l.podNames = append(l.podNames, pod.Name) l.pvcNames = append(l.pvcNames, ephemeral.VolumeClaimName(pod, &pod.Spec.Volumes[0])) @@ -233,7 +233,7 @@ func (t *volumeLimitsTestSuite) DefineTests(driver storageframework.TestDriver, // Create PVCs for one gigantic pod. var pvcs []*v1.PersistentVolumeClaim ginkgo.By(fmt.Sprintf("Creating %d PVC(s)", limit)) - for i := 0; i < limit; i++ { + for range limit { pvc := e2epv.MakePersistentVolumeClaim(e2epv.PersistentVolumeClaimConfig{ ClaimSize: claimSize, StorageClassName: &l.resource.Sc.Name, diff --git a/test/e2e/windows/cpu_limits.go b/test/e2e/windows/cpu_limits.go index 371c03cb283..bbcdf6064d7 100644 --- a/test/e2e/windows/cpu_limits.go +++ b/test/e2e/windows/cpu_limits.go @@ -116,7 +116,7 @@ func newCPUBurnPods(numPods int, image imageutils.Config, cpuLimit string, memor cpuLimitQuantity, err := resource.ParseQuantity(cpuLimit) framework.ExpectNoError(err) - for i := 0; i < numPods; i++ { + for range numPods { podName := "cpulimittest-" + string(uuid.NewUUID()) pod := v1.Pod{ diff --git a/test/e2e/windows/density.go b/test/e2e/windows/density.go index 1cc5cf82179..59999378b27 100644 --- a/test/e2e/windows/density.go +++ b/test/e2e/windows/density.go @@ -225,7 +225,7 @@ func newInformerWatchPod(ctx context.Context, f *framework.Framework, mutex *syn func newDensityTestPods(numPods int, volume bool, imageName, podType string) []*v1.Pod { var pods []*v1.Pod - for i := 0; i < numPods; i++ { + for range numPods { podName := "test-" + string(uuid.NewUUID()) pod := v1.Pod{ diff --git a/test/e2e/windows/hybrid_network.go b/test/e2e/windows/hybrid_network.go index c90395db3c6..3ca0709e0a5 100644 --- a/test/e2e/windows/hybrid_network.go +++ b/test/e2e/windows/hybrid_network.go @@ -112,7 +112,7 @@ func assertConsistentConnectivity(ctx context.Context, f *framework.Framework, p var err error var stdout string var stderr string - for i := 0; i < maxTries; i++ { + for range maxTries { ginkgo.By(fmt.Sprintf("checking connectivity of %s-container in %s", os, podName)) stdout, stderr, err = e2epod.ExecCommandInContainerWithFullOutput(f, podName, os+"-container", cmd...) if err == nil { diff --git a/test/e2e/windows/kubelet_stats.go b/test/e2e/windows/kubelet_stats.go index e2fc5a5c10c..3ea3e29e2c9 100644 --- a/test/e2e/windows/kubelet_stats.go +++ b/test/e2e/windows/kubelet_stats.go @@ -68,7 +68,7 @@ var _ = sigDescribe(feature.Windows, "Kubelet-Stats", framework.WithSerial(), sk iterations := 5 var totalDurationMs int64 - for i := 0; i < iterations; i++ { + for range iterations { start := time.Now() nodeStats, err := e2ekubelet.GetStatsSummary(ctx, f.ClientSet, targetNode.Name) duration := time.Since(start) @@ -160,7 +160,7 @@ var _ = sigDescribe(feature.Windows, "Kubelet-Stats", skipUnlessWindows(func() { iterations := 1 var totalDurationMs int64 - for i := 0; i < iterations; i++ { + for range iterations { start := time.Now() nodeStats, err := e2ekubelet.GetStatsSummary(ctx, f.ClientSet, targetNode.Name) duration := time.Since(start) @@ -260,7 +260,7 @@ func findWindowsNodes(ctx context.Context, f *framework.Framework) ([]v1.Node, e func newKubeletStatsTestPods(numPods int, image imageutils.Config, nodeName string) []*v1.Pod { var pods []*v1.Pod - for i := 0; i < numPods; i++ { + for i := range numPods { podName := "statscollectiontest-" + string(uuid.NewUUID()) pod := v1.Pod{ ObjectMeta: metav1.ObjectMeta{ diff --git a/test/e2e_dra/upgradedowngrade_test.go b/test/e2e_dra/upgradedowngrade_test.go index 76b78001cc4..02fc633ce7c 100644 --- a/test/e2e_dra/upgradedowngrade_test.go +++ b/test/e2e_dra/upgradedowngrade_test.go @@ -98,7 +98,7 @@ func currentBinDir() (envName, content string) { // directly in the root (as in `make test-e2e` or `ginkgo ./test/e2e`), or somewhere deep inside // the _output directory (`ginkgo _output/bin/e2e.test` where `_output/bin` is actually a symlink). func repoRootDefault() string { - for i := 0; i < 10; i++ { + for i := range 10 { path := "." + strings.Repeat("/..", i) if _, err := os.Stat(path + "/test/e2e/framework"); err == nil { return path diff --git a/test/e2e_node/cpu_manager_metrics_test.go b/test/e2e_node/cpu_manager_metrics_test.go index 94ccb20954d..acf7e85e731 100644 --- a/test/e2e_node/cpu_manager_metrics_test.go +++ b/test/e2e_node/cpu_manager_metrics_test.go @@ -415,7 +415,7 @@ var _ = SIGDescribe("CPU Manager Metrics", framework.WithSerial(), feature.CPUMa keys := make(map[interface{}]types.GomegaMatcher) idFn := makeCustomLabelID(metrics.AlignedNUMANode) - for i := 0; i < numaNodes; i++ { + for i := range numaNodes { keys["kubelet_cpu_manager_allocation_per_numa"] = gstruct.MatchAllElements(idFn, gstruct.Elements{ fmt.Sprintf("%d", i): timelessSample(0), }) @@ -491,7 +491,7 @@ var _ = SIGDescribe("CPU Manager Metrics", framework.WithSerial(), feature.CPUMa idFn := makeCustomLabelID(metrics.AlignedNUMANode) // On a clean environment with no other pods running if distribute-across-numa policy option is enabled - for i := 0; i < numaNodes; i++ { + for i := range numaNodes { keys["kubelet_cpu_manager_allocation_per_numa"] = gstruct.MatchAllElements(idFn, gstruct.Elements{ fmt.Sprintf("%d", i): timelessSample(2), }) diff --git a/test/e2e_node/dra_test.go b/test/e2e_node/dra_test.go index c66d4164270..43fe4fb4c8a 100644 --- a/test/e2e_node/dra_test.go +++ b/test/e2e_node/dra_test.go @@ -1074,7 +1074,7 @@ var _ = framework.SIGDescribe("node")(framework.WithLabel("DRA"), feature.Dynami deviceNames := make([]string, numPods) ginkgo.By(fmt.Sprintf("Creating %d pods concurrently to stress test connection management", numPods)) - for i := 0; i < numPods; i++ { + for i := range numPods { className := fmt.Sprintf("concurrent-class-%d", i) claimNames[i] = fmt.Sprintf("concurrent-claim-%d", i) podName := fmt.Sprintf("concurrent-pod-%d", i) @@ -1097,7 +1097,7 @@ var _ = framework.SIGDescribe("node")(framework.WithLabel("DRA"), feature.Dynami "NodePrepareResources should be called at least once per pod") ginkgo.By("Sending health updates for all devices concurrently") - for i := 0; i < numPods; i++ { + for i := range numPods { kubeletPlugin.HealthControlChan <- testdriver.DeviceHealthUpdate{ PoolName: poolNames[i], DeviceName: deviceNames[i], @@ -1106,7 +1106,7 @@ var _ = framework.SIGDescribe("node")(framework.WithLabel("DRA"), feature.Dynami } ginkgo.By("Verifying all health updates are correctly reflected") - for i := 0; i < numPods; i++ { + for i := range numPods { pod := pods[i] poolName := poolNames[i] deviceName := deviceNames[i] @@ -1119,7 +1119,7 @@ var _ = framework.SIGDescribe("node")(framework.WithLabel("DRA"), feature.Dynami } ginkgo.By("Changing health status for all devices to verify continued operation") - for i := 0; i < numPods; i++ { + for i := range numPods { kubeletPlugin.HealthControlChan <- testdriver.DeviceHealthUpdate{ PoolName: poolNames[i], DeviceName: deviceNames[i], @@ -1128,7 +1128,7 @@ var _ = framework.SIGDescribe("node")(framework.WithLabel("DRA"), feature.Dynami } ginkgo.By("Verifying all health changes are correctly reflected") - for i := 0; i < numPods; i++ { + for i := range numPods { pod := pods[i] poolName := poolNames[i] deviceName := deviceNames[i] diff --git a/test/e2e_node/image_list.go b/test/e2e_node/image_list.go index 4304af19386..aa2ad9a552a 100644 --- a/test/e2e_node/image_list.go +++ b/test/e2e_node/image_list.go @@ -180,7 +180,7 @@ func PrePullAllImages(ctx context.Context) error { pullErr error output []byte ) - for retryCount := 0; retryCount < maxImagePullRetries; retryCount++ { + for retryCount := range maxImagePullRetries { select { case <-ctx.Done(): return diff --git a/test/e2e_node/mirror_pod_grace_period_test.go b/test/e2e_node/mirror_pod_grace_period_test.go index 7f5afa4513b..64b8585aad7 100644 --- a/test/e2e_node/mirror_pod_grace_period_test.go +++ b/test/e2e_node/mirror_pod_grace_period_test.go @@ -114,7 +114,7 @@ var _ = SIGDescribe("MirrorPodWithGracePeriod", func() { uid := pod.UID ginkgo.By("update the pod manifest multiple times during the graceful termination period") - for i := 0; i < 300; i++ { + for i := range 300 { err = createStaticPod(podPath, staticPodName, ns, fmt.Sprintf("image-%d", i), v1.RestartPolicyAlways) framework.ExpectNoError(err) diff --git a/test/e2e_node/node_problem_detector_linux.go b/test/e2e_node/node_problem_detector_linux.go index 17dc30d38eb..da8e7b4694a 100644 --- a/test/e2e_node/node_problem_detector_linux.go +++ b/test/e2e_node/node_problem_detector_linux.go @@ -452,7 +452,7 @@ func injectLog(file string, timestamp time.Time, log string, num int) error { return err } defer f.Close() - for i := 0; i < num; i++ { + for range num { _, err := f.WriteString(fmt.Sprintf("%s kernel: [0.000000] %s\n", timestamp.Format(time.Stamp), log)) if err != nil { return err diff --git a/test/e2e_node/numa_alignment.go b/test/e2e_node/numa_alignment.go index 5aa3b3f5d34..bf9039af6b3 100644 --- a/test/e2e_node/numa_alignment.go +++ b/test/e2e_node/numa_alignment.go @@ -107,7 +107,7 @@ func getCPUToNUMANodeMapFromEnv(f *framework.Framework, pod *v1.Pod, cnt *v1.Con } cpusPerNUMA := make(map[int][]int) - for numaNode := 0; numaNode < numaNodes; numaNode++ { + for numaNode := range numaNodes { nodeCPUList := e2epod.ExecCommandInContainer(f, pod.Name, cnt.Name, "/bin/cat", fmt.Sprintf("/sys/devices/system/node/node%d/cpulist", numaNode)) diff --git a/test/e2e_node/podresources_test.go b/test/e2e_node/podresources_test.go index a097176d1b4..18c0f125aab 100644 --- a/test/e2e_node/podresources_test.go +++ b/test/e2e_node/podresources_test.go @@ -2019,7 +2019,7 @@ var _ = SIGDescribe("POD Resources API", framework.WithSerial(), feature.PodReso ginkgo.By(fmt.Sprintf("Issuing %d List() calls in a tight loop", tries)) startTime := time.Now() - for try := 0; try < tries; try++ { + for range tries { _, err = cli.List(ctx, &kubeletpodresourcesv1.ListPodResourcesRequest{}) errs = append(errs, err) } diff --git a/test/e2e_node/probe_stress_test.go b/test/e2e_node/probe_stress_test.go index 5f99e76b3f3..a7b8c69de60 100644 --- a/test/e2e_node/probe_stress_test.go +++ b/test/e2e_node/probe_stress_test.go @@ -162,7 +162,7 @@ func createProbeStressPod(numContainers int, generator func(i int) (v1.Probe, [] podName := "probe-stress-" + string(uuid.NewUUID()) containers := make([]v1.Container, numContainers) - for i := 0; i < numContainers; i++ { + for i := range numContainers { probe, ports, args := generator(i) containers[i] = v1.Container{ Name: fmt.Sprintf("container-%d", i), diff --git a/test/e2e_node/resource_collector.go b/test/e2e_node/resource_collector.go index 71b17bf2bae..9277fa080fe 100644 --- a/test/e2e_node/resource_collector.go +++ b/test/e2e_node/resource_collector.go @@ -381,7 +381,7 @@ func deletePodsSync(ctx context.Context, f *framework.Framework, pods []*v1.Pod) // newTestPods creates a list of pods (specification) for test. func newTestPods(numPods int, volume bool, imageName, podType string) []*v1.Pod { var pods []*v1.Pod - for i := 0; i < numPods; i++ { + for range numPods { podName := "test-" + string(uuid.NewUUID()) labels := map[string]string{ "type": podType, diff --git a/test/e2e_node/restart_all_containers_test.go b/test/e2e_node/restart_all_containers_test.go index 85f9440bfba..69ad5cf44ce 100644 --- a/test/e2e_node/restart_all_containers_test.go +++ b/test/e2e_node/restart_all_containers_test.go @@ -93,7 +93,7 @@ var _ = SIGDescribe("RestartAllContainersWithKubeletRestarts", }, } // Setting up extra containers so the cleanup takes more time to coordinate with kubelet restart. - for i := 0; i < containerCount; i++ { + for i := range containerCount { pod.Spec.Containers = append(pod.Spec.Containers, v1.Container{ Name: fmt.Sprintf("container-%d", i), Image: imageutils.GetE2EImage(imageutils.BusyBox), @@ -195,7 +195,7 @@ var _ = SIGDescribe("RestartAllContainersWithKubeletRestarts", }, } // Setting up extra containers so the cleanup takes more time to coordinate with kubelet restart. - for i := 0; i < containerCount; i++ { + for i := range containerCount { pod.Spec.Containers = append(pod.Spec.Containers, v1.Container{ Name: fmt.Sprintf("container-%d", i), Image: imageutils.GetE2EImage(imageutils.BusyBox), diff --git a/test/e2e_node/restart_test.go b/test/e2e_node/restart_test.go index a9dda81c6ab..35ad1b8c1f5 100644 --- a/test/e2e_node/restart_test.go +++ b/test/e2e_node/restart_test.go @@ -105,7 +105,7 @@ var _ = SIGDescribe("Restart", framework.WithSerial(), framework.WithSlow(), fra framework.Failf("Failed to start %d pods, cannot test that restarting container runtime doesn't leak IPs", minPods) } - for i := 0; i < restartCount; i++ { + for i := range restartCount { ginkgo.By(fmt.Sprintf("Killing container runtime iteration %d", i)) // Wait for container runtime to be running var pid int diff --git a/test/e2e_node/topology_manager_test.go b/test/e2e_node/topology_manager_test.go index d4ba9ca5a4c..a3612883003 100644 --- a/test/e2e_node/topology_manager_test.go +++ b/test/e2e_node/topology_manager_test.go @@ -127,7 +127,7 @@ func detectNUMADistances(numaNodes int) map[int][]int { ginkgo.GinkgoHelper() nodeToDistances := make(map[int][]int) - for i := 0; i < numaNodes; i++ { + for i := range numaNodes { outData, err := os.ReadFile(fmt.Sprintf("/sys/devices/system/node/node%d/distance", i)) framework.ExpectNoError(err) @@ -195,7 +195,7 @@ func makeTopologyManagerTestPod(podName string, tmCtnAttributes, tmInitCtnAttrib } func findNUMANodeWithoutSRIOVDevicesFromConfigMap(configMap *v1.ConfigMap, numaNodes int) (int, bool) { - for nodeNum := 0; nodeNum < numaNodes; nodeNum++ { + for nodeNum := range numaNodes { value, ok := configMap.Annotations[fmt.Sprintf("pcidevice_node%d", nodeNum)] if !ok { framework.Logf("missing pcidevice annotation for NUMA node %d", nodeNum) @@ -232,7 +232,7 @@ func findNUMANodeWithoutSRIOVDevicesFromSysfs(numaNodes int) (int, bool) { return -1, false } - for nodeNum := 0; nodeNum < numaNodes; nodeNum++ { + for nodeNum := range numaNodes { v := pciPerNuma[nodeNum] if v == 0 { framework.Logf("NUMA node %d has no SRIOV devices attached", nodeNum) @@ -472,7 +472,7 @@ func runTopologyManagerPolicySuiteTests(ctx context.Context, f *framework.Framew func runTopologyManagerPositiveTest(ctx context.Context, f *framework.Framework, numPods int, ctnAttrs, initCtnAttrs []tmCtnAttribute, envInfo *testEnvInfo) { podMap := make(map[string]*v1.Pod) - for podID := 0; podID < numPods; podID++ { + for podID := range numPods { podName := fmt.Sprintf("gu-pod-%d", podID) framework.Logf("creating pod %s attrs %v", podName, ctnAttrs) pod := makeTopologyManagerTestPod(podName, ctnAttrs, initCtnAttrs) @@ -1145,7 +1145,7 @@ func runPreferClosestNUMATestSuite(ctx context.Context, f *framework.Framework, func runPreferClosestNUMAOptimalAllocationTest(ctx context.Context, f *framework.Framework, numaNodes int, distances map[int][]int) { ginkgo.By("Admit two guaranteed pods. Both consist of 1 containers, each pod asks for cpus from 2 NUMA nodes. CPUs should be assigned from closest NUMA") podMap := make(map[string]*v1.Pod) - for podID := 0; podID < 2; podID++ { + for podID := range 2 { numCores := 0 for nodeNum := 0 + 2*podID; nodeNum <= 1+2*podID; nodeNum++ { cpus, err := getCPUsPerNUMANode(nodeNum) @@ -1189,7 +1189,7 @@ func runPreferClosestNUMASubOptimalAllocationTest(ctx context.Context, f *framew e2eskipper.Skipf("Less than 5 cpus per NUMA node on this system. Skipping test.") } podMap := make(map[string]*v1.Pod) - for podID := 0; podID < 2; podID++ { + for podID := range 2 { // asks for all but one cpus from one less than half NUMA nodes, and half from the other // plus add one less than half NUMA nodes, to accommodate for reserved cpus numCores := ((numaNodes/2)-1)*(len(cpusPerNUMA)-1) + (len(cpusPerNUMA) / 2) + (numaNodes/2 - 1) diff --git a/test/e2e_node/volume_manager_test.go b/test/e2e_node/volume_manager_test.go index 38a1ba54185..ab98f83e4da 100644 --- a/test/e2e_node/volume_manager_test.go +++ b/test/e2e_node/volume_manager_test.go @@ -80,7 +80,7 @@ var _ = SIGDescribe("Kubelet Volume Manager", func() { ginkgo.By("Verifying the memory backed volume was removed from node", func() { volumePath := fmt.Sprintf("/tmp/%s/volumes/kubernetes.io~empty-dir/%s", string(memoryBackedPod.UID), volumeName) var err error - for i := 0; i < 10; i++ { + for range 10 { // need to create a new verification pod on each pass since updates //to the HostPath volume aren't propogated to the pod pod := e2epod.NewPodClient(f).Create(ctx, &v1.Pod{ diff --git a/test/images/agnhost/nettest/nettest.go b/test/images/agnhost/nettest/nettest.go index 434fc51d11f..2bfcb84bf5a 100644 --- a/test/images/agnhost/nettest/nettest.go +++ b/test/images/agnhost/nettest/nettest.go @@ -304,7 +304,7 @@ func contactOthers(state *State) { // Do this repeatedly, in case there's some propagation delay with getting // newly started pods into the endpoints list. - for i := 0; i < 15; i++ { + for range 15 { eps := getWebserverEndpoints(client) for ep := range eps { state.Logf("Attempting to contact %s", ep) diff --git a/test/images/agnhost/port-forward-tester/portforwardtester.go b/test/images/agnhost/port-forward-tester/portforwardtester.go index 9cff3ba5ea2..255f4f59acb 100644 --- a/test/images/agnhost/port-forward-tester/portforwardtester.go +++ b/test/images/agnhost/port-forward-tester/portforwardtester.go @@ -130,7 +130,7 @@ func main(cmd *cobra.Command, args []string) { stringData := strings.Repeat("x", chunkSize) data := []byte(stringData) - for i := 0; i < chunks; i++ { + for i := range chunks { written, err := conn.Write(data) if written != chunkSize { fmt.Printf("Expected to write %d bytes from client, but wrote %d instead. err=%v\n", chunkSize, written, err) diff --git a/test/images/agnhost/resource-consumer-controller/controller.go b/test/images/agnhost/resource-consumer-controller/controller.go index b79dd999e49..a1136c76634 100644 --- a/test/images/agnhost/resource-consumer-controller/controller.go +++ b/test/images/agnhost/resource-consumer-controller/controller.go @@ -221,19 +221,19 @@ func (c *controller) handleBumpMetric(w http.ResponseWriter, query url.Values) { } func (c *controller) sendConsumeCPURequests(w http.ResponseWriter, requests, millicores, durationSec int) { - for i := 0; i < requests; i++ { + for range requests { go c.sendOneConsumeCPURequest(w, millicores, durationSec) } } func (c *controller) sendConsumeMemRequests(w http.ResponseWriter, requests, megabytes, durationSec int) { - for i := 0; i < requests; i++ { + for range requests { go c.sendOneConsumeMemRequest(w, megabytes, durationSec) } } func (c *controller) sendConsumeCustomMetric(w http.ResponseWriter, metric string, requests, delta, durationSec int) { - for i := 0; i < requests; i++ { + for range requests { go c.sendOneConsumeCustomMetric(w, metric, delta, durationSec) } } diff --git a/test/images/agnhost/webhook/convert_test.go b/test/images/agnhost/webhook/convert_test.go index f2a5c5558f0..dff1387fe9e 100644 --- a/test/images/agnhost/webhook/convert_test.go +++ b/test/images/agnhost/webhook/convert_test.go @@ -35,7 +35,7 @@ import ( func TestConvertAdmissionRequestToV1(t *testing.T) { f := fuzzer.FuzzerFor(admissionfuzzer.Funcs, rand.NewSource(rand.Int63()), serializer.NewCodecFactory(runtime.NewScheme())) - for i := 0; i < 100; i++ { + for i := range 100 { t.Run(fmt.Sprintf("Run %d/100", i), func(t *testing.T) { orig := &v1beta1.AdmissionRequest{} f.Fill(orig) @@ -50,7 +50,7 @@ func TestConvertAdmissionRequestToV1(t *testing.T) { func TestConvertAdmissionResponseToV1beta1(t *testing.T) { f := randfill.New() - for i := 0; i < 100; i++ { + for i := range 100 { t.Run(fmt.Sprintf("Run %d/100", i), func(t *testing.T) { orig := &v1.AdmissionResponse{} f.Fill(orig) diff --git a/test/soak/serve_hostnames/serve_hostnames.go b/test/soak/serve_hostnames/serve_hostnames.go index ed92655d912..d317fade8ed 100644 --- a/test/soak/serve_hostnames/serve_hostnames.go +++ b/test/soak/serve_hostnames/serve_hostnames.go @@ -126,7 +126,7 @@ func main() { klog.Warningf("Failed to delete namespace %s: %v", ns, err) } else { // wait until the namespace disappears - for i := 0; i < int(namespaceDeleteTimeout/time.Second); i++ { + for range int(namespaceDeleteTimeout / time.Second) { if _, err := client.CoreV1().Namespaces().Get(context.TODO(), ns, metav1.GetOptions{}); err != nil { if apierrors.IsNotFound(err) { return @@ -297,7 +297,7 @@ func main() { // of in-flight requests to avoid overloading the service. inFlight := make(chan struct{}, *maxPar) start := time.Now() - for q := 0; q < queries; q++ { + for q := range queries { go func(i int, query int) { inFlight <- struct{}{} t := time.Now() @@ -319,7 +319,7 @@ func main() { } responses := make(map[string]int, *podsPerNode*len(nodes.Items)) missing := 0 - for q := 0; q < queries; q++ { + for range queries { r := <-responseChan klog.V(4).Infof("Got response from %s", r) responses[r]++