From 1880409a043a925888fac20d7ff76eb405b6b736 Mon Sep 17 00:00:00 2001 From: Nahshon Unna-Tsameret Date: Thu, 13 Jun 2024 20:52:41 +0300 Subject: [PATCH] Use ginkgo's context in e2e Use ginkgo contexts instead and let ginkgo handle them, instead of creating our on contexts. Signed-off-by: Nahshon Unna-Tsameret --- tests/func-tests/aaq_test.go | 20 +-- tests/func-tests/cli_download_test.go | 8 +- .../cluster_eviction_strategy_test.go | 13 +- tests/func-tests/console_plugin_test.go | 29 +++-- tests/func-tests/dashboard_test.go | 12 +- tests/func-tests/defaults_test.go | 89 ++++++------- tests/func-tests/dependency_objects_test.go | 8 +- tests/func-tests/golden_image_test.go | 120 +++++++++--------- tests/func-tests/labels_test.go | 13 +- tests/func-tests/main_test.go | 10 +- .../mediateddevices_mediateddevice_test.go | 26 ++-- tests/func-tests/monitoring_test.go | 72 +++++------ tests/func-tests/node_placement_test.go | 37 +++--- tests/func-tests/quickstart_test.go | 8 +- tests/func-tests/tuningpolicy_test.go | 12 +- .../func-tests/update_priority_class_test.go | 44 ++++--- tests/func-tests/utils.go | 20 ++- tests/func-tests/validation_test.go | 11 +- tests/func-tests/virtual_machines_test.go | 16 +-- 19 files changed, 274 insertions(+), 294 deletions(-) diff --git a/tests/func-tests/aaq_test.go b/tests/func-tests/aaq_test.go index aff889f75..c5280579a 100644 --- a/tests/func-tests/aaq_test.go +++ b/tests/func-tests/aaq_test.go @@ -29,36 +29,33 @@ var _ = Describe("Test AAQ", Label("AAQ"), Serial, Ordered, func() { tests.FlagParse() var ( k8scli client.Client - ctx context.Context ) - BeforeEach(func() { + BeforeEach(func(ctx context.Context) { k8scli = tests.GetControllerRuntimeClient() - ctx = context.Background() - disableAAQFeatureGate(ctx, k8scli) }) - AfterAll(func() { + AfterAll(func(ctx context.Context) { disableAAQFeatureGate(ctx, k8scli) }) When("set the applicationAwareConfig exists", func() { - It("should create the AAQ CR and all the pods", func() { + It("should create the AAQ CR and all the pods", func(ctx context.Context) { enableAAQFeatureGate(ctx, k8scli) By("check the AAQ CR") - Eventually(func(g Gomega) bool { + Eventually(func(g Gomega, ctx context.Context) bool { aaq, err := getAAQ(ctx, k8scli) g.Expect(err).ToNot(HaveOccurred()) g.Expect(aaq.Status.Conditions).ToNot(BeEmpty()) return conditionsv1.IsStatusConditionTrue(aaq.Status.Conditions, conditionsv1.ConditionAvailable) - }).WithTimeout(5 * time.Minute).WithPolling(time.Second).ShouldNot(BeTrue()) + }).WithTimeout(5 * time.Minute).WithPolling(time.Second).WithContext(ctx).ShouldNot(BeTrue()) By("check AAQ pods") - Eventually(func(g Gomega) { + Eventually(func(g Gomega, ctx context.Context) { deps := &appsv1.DeploymentList{} Expect( k8scli.List(ctx, deps, client.MatchingLabels{"app.kubernetes.io/managed-by": "aaq-operator"}), @@ -78,6 +75,7 @@ var _ = Describe("Test AAQ", Label("AAQ"), Serial, Ordered, func() { g.Expect(pods.Items).To(HaveLen(int(expectedPods))) }).WithTimeout(5 * time.Minute). WithPolling(time.Second). + WithContext(ctx). Should(Succeed()) }) }) @@ -105,12 +103,13 @@ func disableAAQFeatureGate(ctx context.Context, cli client.Client) { setAAQFeatureGate(ctx, cli, false) By("make sure the AAQ CR was removed") - Eventually(func() error { + Eventually(func(ctx context.Context) error { _, err := getAAQ(ctx, cli) return err }).WithTimeout(5 * time.Minute). WithPolling(100 * time.Millisecond). WithOffset(1). + WithContext(ctx). Should(MatchError(errors.IsNotFound, "not found error")) } @@ -121,6 +120,7 @@ func setAAQFeatureGate(ctx context.Context, cli client.Client, fgState bool) { WithArguments(ctx, cli, patchBytes). WithTimeout(10 * time.Second). WithPolling(100 * time.Millisecond). + WithContext(ctx). WithOffset(2). Should(Succeed()) } diff --git a/tests/func-tests/cli_download_test.go b/tests/func-tests/cli_download_test.go index ff4fb1c85..7a22979f2 100644 --- a/tests/func-tests/cli_download_test.go +++ b/tests/func-tests/cli_download_test.go @@ -23,11 +23,10 @@ var _ = Describe("[rfe_id:5100][crit:medium][vendor:cnv-qe@redhat.com][level:sys var ( cli client.Client - ctx context.Context ) - BeforeEach(func() { - tests.BeforeEach() + BeforeEach(func(ctx context.Context) { + tests.BeforeEach(ctx) cfg, err := config.GetConfig() Expect(err).ToNot(HaveOccurred()) @@ -36,11 +35,10 @@ var _ = Describe("[rfe_id:5100][crit:medium][vendor:cnv-qe@redhat.com][level:sys cli, err = client.New(cfg, client.Options{Scheme: s}) Expect(err).ToNot(HaveOccurred()) - ctx = context.Background() tests.FailIfNotOpenShift(ctx, cli, "ConsoleCliDownload") }) - It("[test_id:6956]should create ConsoleCliDownload objects with expected spec", Label("test_id:6956"), func() { + It("[test_id:6956]should create ConsoleCliDownload objects with expected spec", Label("test_id:6956"), func(ctx context.Context) { By("Checking existence of ConsoleCliDownload") ccd := &consolev1.ConsoleCLIDownload{ diff --git a/tests/func-tests/cluster_eviction_strategy_test.go b/tests/func-tests/cluster_eviction_strategy_test.go index 6937bf250..535d35a29 100644 --- a/tests/func-tests/cluster_eviction_strategy_test.go +++ b/tests/func-tests/cluster_eviction_strategy_test.go @@ -17,33 +17,30 @@ var _ = Describe("Cluster level evictionStrategy default value", Serial, Ordered tests.FlagParse() var ( cli client.Client - ctx context.Context initialEvictionStrategy *v1.EvictionStrategy singleWorkerCluster bool ) - BeforeEach(func() { + BeforeEach(func(ctx context.Context) { cli = tests.GetControllerRuntimeClient() - ctx = context.Background() - var err error singleWorkerCluster, err = isSingleWorkerCluster(ctx, cli) Expect(err).ToNot(HaveOccurred()) - tests.BeforeEach() + tests.BeforeEach(ctx) hc := tests.GetHCO(ctx, cli) initialEvictionStrategy = hc.Spec.EvictionStrategy }) - AfterEach(func() { + AfterEach(func(ctx context.Context) { hc := tests.GetHCO(ctx, cli) hc.Spec.EvictionStrategy = initialEvictionStrategy tests.UpdateHCORetry(ctx, cli, hc) }) - It("Should set spec.evictionStrategy = None by default on single worker clusters", Label(tests.SingleNodeLabel), func() { + It("Should set spec.evictionStrategy = None by default on single worker clusters", Label(tests.SingleNodeLabel), func(ctx context.Context) { Expect(singleWorkerCluster).To(BeTrue(), "this test requires single worker cluster; use the %q label to skip this test", tests.SingleNodeLabel) hco := tests.GetHCO(ctx, cli) @@ -54,7 +51,7 @@ var _ = Describe("Cluster level evictionStrategy default value", Serial, Ordered Expect(hco.Spec.EvictionStrategy).To(Equal(&noneEvictionStrategy)) }) - It("Should set spec.evictionStrategy = LiveMigrate by default with multiple worker node", Label(tests.HighlyAvailableClusterLabel), func() { + It("Should set spec.evictionStrategy = LiveMigrate by default with multiple worker node", Label(tests.HighlyAvailableClusterLabel), func(ctx context.Context) { tests.FailIfSingleNode(singleWorkerCluster) hco := tests.GetHCO(ctx, cli) hco.Spec.EvictionStrategy = nil diff --git a/tests/func-tests/console_plugin_test.go b/tests/func-tests/console_plugin_test.go index 39680c984..7ba1f9bea 100644 --- a/tests/func-tests/console_plugin_test.go +++ b/tests/func-tests/console_plugin_test.go @@ -33,15 +33,13 @@ var _ = Describe("kubevirt console plugin", Label(tests.OpenshiftLabel, "console var ( cli client.Client k8sClientSet *kubernetes.Clientset - ctx context.Context ) tests.FlagParse() - BeforeEach(func() { + BeforeEach(func(ctx context.Context) { cli = tests.GetControllerRuntimeClient() - ctx = context.Background() tests.FailIfNotOpenShift(ctx, cli, "kubevirt console plugin") hco := tests.GetHCO(ctx, cli) @@ -49,14 +47,13 @@ var _ = Describe("kubevirt console plugin", Label(tests.OpenshiftLabel, "console k8sClientSet = tests.GetK8sClientSet() - DeferCleanup(func() { + DeferCleanup(func(ctx context.Context) { hco.Spec.Infra = originalInfra tests.UpdateHCORetry(ctx, cli, hco) }) - }) - It("console should reach kubevirt-plugin manifests", func() { + It("console should reach kubevirt-plugin manifests", func(ctx context.Context) { kubevirtPlugin := &consolev1.ConsolePlugin{ ObjectMeta: metav1.ObjectMeta{ Name: expectedKubevirtConsolePluginName, @@ -93,7 +90,7 @@ var _ = Describe("kubevirt console plugin", Label(tests.OpenshiftLabel, "console Expect(pluginName).To(Equal(expectedKubevirtConsolePluginName)) }) - It("nodePlacement should be propagated from HyperConverged CR to console-plugin and apiserver-proxy Deployments", Serial, func() { + It("nodePlacement should be propagated from HyperConverged CR to console-plugin and apiserver-proxy Deployments", Serial, func(ctx context.Context) { expectedNodeSelector := map[string]string{ "foo": "bar", @@ -103,14 +100,15 @@ var _ = Describe("kubevirt console plugin", Label(tests.OpenshiftLabel, "console expectedNodeSelectorStr := string(expectedNodeSelectorBytes) addNodeSelectorPatch := []byte(fmt.Sprintf(`[{"op": "add", "path": "/spec/infra", "value": {"nodePlacement": {"nodeSelector": %s}}}]`, expectedNodeSelectorStr)) - Eventually(func() error { + Eventually(func(ctx context.Context) error { err = tests.PatchHCO(ctx, cli, addNodeSelectorPatch) return err }).WithTimeout(1 * time.Minute). WithPolling(1 * time.Millisecond). + WithContext(ctx). Should(Succeed()) - Eventually(func(g Gomega) { + Eventually(func(g Gomega, ctx context.Context) { consoleUIDeployment := &appsv1.Deployment{ ObjectMeta: metav1.ObjectMeta{ Name: string(hcoutil.AppComponentUIPlugin), @@ -123,9 +121,10 @@ var _ = Describe("kubevirt console plugin", Label(tests.OpenshiftLabel, "console g.Expect(consoleUIDeployment.Spec.Template.Spec.NodeSelector).To(Equal(expectedNodeSelector)) }).WithTimeout(1 * time.Minute). WithPolling(100 * time.Millisecond). + WithContext(ctx). Should(Succeed()) - Eventually(func(g Gomega) { + Eventually(func(g Gomega, ctx context.Context) { proxyUIDeployment := &appsv1.Deployment{ ObjectMeta: metav1.ObjectMeta{ Name: string(hcoutil.AppComponentUIProxy), @@ -136,18 +135,20 @@ var _ = Describe("kubevirt console plugin", Label(tests.OpenshiftLabel, "console g.Expect(proxyUIDeployment.Spec.Template.Spec.NodeSelector).To(Equal(expectedNodeSelector)) }).WithTimeout(1 * time.Minute). WithPolling(100 * time.Millisecond). + WithContext(ctx). Should(Succeed()) // clear node placement from HyperConverged CR and verify the nodeSelector has been cleared as well from the UI Deployments removeNodeSelectorPatch := []byte(`[{"op": "replace", "path": "/spec/infra", "value": {}}]`) - Eventually(func() error { + Eventually(func(ctx context.Context) error { err = tests.PatchHCO(ctx, cli, removeNodeSelectorPatch) return err }).WithTimeout(1 * time.Minute). WithPolling(1 * time.Millisecond). + WithContext(ctx). Should(Succeed()) - Eventually(func(g Gomega) { + Eventually(func(g Gomega, ctx context.Context) { consoleUIDeployment := &appsv1.Deployment{ ObjectMeta: metav1.ObjectMeta{ Name: string(hcoutil.AppComponentUIPlugin), @@ -159,9 +160,10 @@ var _ = Describe("kubevirt console plugin", Label(tests.OpenshiftLabel, "console g.Expect(consoleUIDeployment.Spec.Template.Spec.NodeSelector).To(BeEmpty()) }).WithTimeout(1 * time.Minute). WithPolling(100 * time.Millisecond). + WithContext(ctx). Should(Succeed()) - Eventually(func(g Gomega) { + Eventually(func(g Gomega, ctx context.Context) { proxyUIDeployment := &appsv1.Deployment{ ObjectMeta: metav1.ObjectMeta{ Name: string(hcoutil.AppComponentUIProxy), @@ -172,6 +174,7 @@ var _ = Describe("kubevirt console plugin", Label(tests.OpenshiftLabel, "console g.Expect(proxyUIDeployment.Spec.Template.Spec.NodeSelector).To(BeEmpty()) }).WithTimeout(1 * time.Minute). WithPolling(100 * time.Millisecond). + WithContext(ctx). Should(Succeed()) }) }) diff --git a/tests/func-tests/dashboard_test.go b/tests/func-tests/dashboard_test.go index 98b186f94..ae7f9599e 100644 --- a/tests/func-tests/dashboard_test.go +++ b/tests/func-tests/dashboard_test.go @@ -15,23 +15,19 @@ import ( var _ = Describe("[rfe_id:5108][crit:medium][vendor:cnv-qe@redhat.com][level:system]Dashboard configmaps", Label(tests.OpenshiftLabel), func() { flag.Parse() - var ( - cli *kubernetes.Clientset - ctx context.Context - ) + var cli *kubernetes.Clientset - BeforeEach(func() { - tests.BeforeEach() + BeforeEach(func(ctx context.Context) { + tests.BeforeEach(ctx) k8sCli := tests.GetControllerRuntimeClient() - ctx = context.Background() tests.FailIfNotOpenShift(ctx, k8sCli, "Dashboard configmaps") cli = tests.GetK8sClientSet() }) - It("[test_id:5919]should create configmaps for OCP Dashboard", Label("test_id:5919"), func() { + It("[test_id:5919]should create configmaps for OCP Dashboard", Label("test_id:5919"), func(ctx context.Context) { By("Checking expected configmaps") items := tests.GetConfig().Dashboard.TestItems diff --git a/tests/func-tests/defaults_test.go b/tests/func-tests/defaults_test.go index 3c376cc03..65cf28f28 100644 --- a/tests/func-tests/defaults_test.go +++ b/tests/func-tests/defaults_test.go @@ -22,16 +22,11 @@ const ( ) var _ = Describe("Check Default values", Label("defaults"), Serial, func() { - var ( - cli client.Client - ctx context.Context - ) + var cli client.Client - BeforeEach(func() { + BeforeEach(func(ctx context.Context) { cli = tests.GetControllerRuntimeClient() - ctx = context.Background() - tests.RestoreDefaults(ctx, cli) }) @@ -47,16 +42,16 @@ var _ = Describe("Check Default values", Label("defaults"), Serial, func() { }, } - DescribeTable("Check that certConfig defaults are behaving as expected", func(path string) { + DescribeTable("Check that certConfig defaults are behaving as expected", func(ctx context.Context, path string) { patch := []byte(fmt.Sprintf(removePathPatchTmplt, path)) - Eventually(func() error { + Eventually(func(ctx context.Context) error { return tests.PatchHCO(ctx, cli, patch) - }).WithTimeout(2 * time.Second).WithPolling(500 * time.Millisecond).Should(Succeed()) + }).WithTimeout(2 * time.Second).WithPolling(500 * time.Millisecond).WithContext(ctx).Should(Succeed()) - Eventually(func(g Gomega) { + Eventually(func(g Gomega, ctx context.Context) { hc := tests.GetHCO(ctx, cli) g.Expect(reflect.DeepEqual(hc.Spec.CertConfig, defaultCertConfig)).To(BeTrue(), "certConfig should be equal to default") - }).WithTimeout(2 * time.Second).WithPolling(100 * time.Millisecond).Should(Succeed()) + }).WithTimeout(2 * time.Second).WithPolling(100 * time.Millisecond).WithContext(ctx).Should(Succeed()) }, Entry("when removing /spec/certConfig/ca/duration", "/spec/certConfig/ca/duration"), Entry("when removing /spec/certConfig/ca/renewBefore", "/spec/certConfig/ca/renewBefore"), @@ -86,16 +81,16 @@ var _ = Describe("Check Default values", Label("defaults"), Serial, func() { EnableApplicationAwareQuota: ptr.To(false), } - DescribeTable("Check that featureGates defaults are behaving as expected", func(path string) { + DescribeTable("Check that featureGates defaults are behaving as expected", func(ctx context.Context, path string) { patch := []byte(fmt.Sprintf(removePathPatchTmplt, path)) - Eventually(func() error { + Eventually(func(ctx context.Context) error { return tests.PatchHCO(ctx, cli, patch) - }).WithTimeout(2 * time.Second).WithPolling(500 * time.Millisecond).Should(Succeed()) + }).WithTimeout(2 * time.Second).WithPolling(500 * time.Millisecond).WithContext(ctx).Should(Succeed()) - Eventually(func(g Gomega) { + Eventually(func(g Gomega, ctx context.Context) { hc := tests.GetHCO(ctx, cli) g.Expect(reflect.DeepEqual(hc.Spec.FeatureGates, defaultFeatureGates)).To(BeTrue(), "featureGates should be equal to default") - }).WithTimeout(2 * time.Second).WithPolling(100 * time.Millisecond).Should(Succeed()) + }).WithTimeout(2 * time.Second).WithPolling(100 * time.Millisecond).WithContext(ctx).Should(Succeed()) }, Entry("when removing /spec/featureGates/downwardMetrics", "/spec/featureGates/downwardMetrics"), Entry("when removing /spec/featureGates/deployKubeSecondaryDNS", "/spec/featureGates/deployKubeSecondaryDNS"), @@ -124,16 +119,16 @@ var _ = Describe("Check Default values", Label("defaults"), Serial, func() { ProgressTimeout: ptr.To(int64(150)), } - DescribeTable("Check that liveMigrationConfig defaults are behaving as expected", func(path string) { + DescribeTable("Check that liveMigrationConfig defaults are behaving as expected", func(ctx context.Context, path string) { patch := []byte(fmt.Sprintf(removePathPatchTmplt, path)) - Eventually(func() error { + Eventually(func(ctx context.Context) error { return tests.PatchHCO(ctx, cli, patch) - }).WithTimeout(2 * time.Second).WithPolling(500 * time.Millisecond).Should(Succeed()) + }).WithTimeout(2 * time.Second).WithPolling(500 * time.Millisecond).WithContext(ctx).Should(Succeed()) - Eventually(func(g Gomega) { + Eventually(func(g Gomega, ctx context.Context) { hc := tests.GetHCO(ctx, cli) g.Expect(reflect.DeepEqual(hc.Spec.LiveMigrationConfig, defaultLiveMigrationConfig)).To(BeTrue(), "liveMigrationConfig should be equal to default") - }).WithTimeout(2 * time.Second).WithPolling(100 * time.Millisecond).Should(Succeed()) + }).WithTimeout(2 * time.Second).WithPolling(100 * time.Millisecond).WithContext(ctx).Should(Succeed()) }, Entry("when removing /spec/liveMigrationConfig/allowAutoConverge", "/spec/liveMigrationConfig/allowAutoConverge"), Entry("when removing /spec/liveMigrationConfig/allowPostCopy", "/spec/liveMigrationConfig/allowPostCopy"), @@ -151,16 +146,16 @@ var _ = Describe("Check Default values", Label("defaults"), Serial, func() { VmiCPUAllocationRatio: ptr.To(10), } - DescribeTable("Check that resourceRequirements defaults are behaving as expected", func(path string) { + DescribeTable("Check that resourceRequirements defaults are behaving as expected", func(ctx context.Context, path string) { patch := []byte(fmt.Sprintf(removePathPatchTmplt, path)) - Eventually(func() error { + Eventually(func(ctx context.Context) error { return tests.PatchHCO(ctx, cli, patch) - }).WithTimeout(20 * time.Second).WithPolling(500 * time.Millisecond).Should(Succeed()) + }).WithTimeout(20 * time.Second).WithPolling(500 * time.Millisecond).WithContext(ctx).Should(Succeed()) - Eventually(func(g Gomega) { + Eventually(func(g Gomega, ctx context.Context) { hc := tests.GetHCO(ctx, cli) g.Expect(reflect.DeepEqual(hc.Spec.ResourceRequirements, &defaultResourceRequirements)).To(BeTrue(), "resourceRequirements should be equal to default") - }).WithTimeout(2 * time.Second).WithPolling(100 * time.Millisecond).Should(Succeed()) + }).WithTimeout(2 * time.Second).WithPolling(100 * time.Millisecond).WithContext(ctx).Should(Succeed()) }, Entry("when removing /spec/resourceRequirements/vmiCPUAllocationRatio", "/spec/resourceRequirements/vmiCPUAllocationRatio"), Entry("when removing /spec/resourceRequirements", "/spec/resourceRequirements"), @@ -175,16 +170,16 @@ var _ = Describe("Check Default values", Label("defaults"), Serial, func() { WorkloadUpdateMethods: []string{"LiveMigrate"}, } - DescribeTable("Check that workloadUpdateStrategy defaults are behaving as expected", func(path string) { + DescribeTable("Check that workloadUpdateStrategy defaults are behaving as expected", func(ctx context.Context, path string) { patch := []byte(fmt.Sprintf(removePathPatchTmplt, path)) - Eventually(func() error { + Eventually(func(ctx context.Context) error { return tests.PatchHCO(ctx, cli, patch) - }).WithTimeout(20 * time.Second).WithPolling(500 * time.Millisecond).Should(Succeed()) + }).WithTimeout(20 * time.Second).WithPolling(500 * time.Millisecond).WithContext(ctx).Should(Succeed()) - Eventually(func(g Gomega) { + Eventually(func(g Gomega, ctx context.Context) { hc := tests.GetHCO(ctx, cli) g.Expect(reflect.DeepEqual(hc.Spec.WorkloadUpdateStrategy, defaultWorkloadUpdateStrategy)).To(BeTrue(), "workloadUpdateStrategy should be equal to default") - }).WithTimeout(2 * time.Second).WithPolling(100 * time.Millisecond).Should(Succeed()) + }).WithTimeout(2 * time.Second).WithPolling(100 * time.Millisecond).WithContext(ctx).Should(Succeed()) }, Entry("when removing /spec/workloadUpdateStrategy/batchEvictionInterval", "/spec/workloadUpdateStrategy/batchEvictionInterval"), Entry("when removing /spec/workloadUpdateStrategy/batchEvictionSize", "/spec/workloadUpdateStrategy/batchEvictionSize"), @@ -197,16 +192,16 @@ var _ = Describe("Check Default values", Label("defaults"), Serial, func() { Context("uninstallStrategy defaults", func() { const defaultUninstallStrategy = `BlockUninstallIfWorkloadsExist` - DescribeTable("Check that uninstallStrategy default is behaving as expected", func(path string) { + DescribeTable("Check that uninstallStrategy default is behaving as expected", func(ctx context.Context, path string) { patch := []byte(fmt.Sprintf(removePathPatchTmplt, path)) - Eventually(func() error { + Eventually(func(ctx context.Context) error { return tests.PatchHCO(ctx, cli, patch) - }).WithTimeout(2 * time.Second).WithPolling(500 * time.Millisecond).Should(Succeed()) + }).WithTimeout(2 * time.Second).WithPolling(500 * time.Millisecond).WithContext(ctx).Should(Succeed()) - Eventually(func(g Gomega) { + Eventually(func(g Gomega, ctx context.Context) { hc := tests.GetHCO(ctx, cli) g.Expect(hc.Spec.UninstallStrategy).To(Equal(v1beta1.HyperConvergedUninstallStrategy(defaultUninstallStrategy)), "uninstallStrategy should be equal to default") - }).WithTimeout(2 * time.Second).WithPolling(100 * time.Millisecond).Should(Succeed()) + }).WithTimeout(2 * time.Second).WithPolling(100 * time.Millisecond).WithContext(ctx).Should(Succeed()) }, Entry("when removing /spec/uninstallStrategy", "/spec/uninstallStrategy"), Entry("when removing /spec", "/spec"), @@ -219,16 +214,16 @@ var _ = Describe("Check Default values", Label("defaults"), Serial, func() { DisableSerialConsoleLog: ptr.To(true), } - DescribeTable("Check that featureGates defaults are behaving as expected", func(path string) { + DescribeTable("Check that featureGates defaults are behaving as expected", func(ctx context.Context, path string) { patch := []byte(fmt.Sprintf(removePathPatchTmplt, path)) - Eventually(func() error { + Eventually(func(ctx context.Context) error { return tests.PatchHCO(ctx, cli, patch) - }).WithTimeout(2 * time.Second).WithPolling(500 * time.Millisecond).Should(Succeed()) + }).WithTimeout(2 * time.Second).WithPolling(500 * time.Millisecond).WithContext(ctx).Should(Succeed()) - Eventually(func(g Gomega) { + Eventually(func(g Gomega, ctx context.Context) { hc := tests.GetHCO(ctx, cli) g.Expect(reflect.DeepEqual(hc.Spec.VirtualMachineOptions, defaultVirtualMachineOptions)).To(BeTrue(), "virtualMachineOptions should be equal to default") - }).WithTimeout(2 * time.Second).WithPolling(100 * time.Millisecond).Should(Succeed()) + }).WithTimeout(2 * time.Second).WithPolling(100 * time.Millisecond).WithContext(ctx).Should(Succeed()) }, Entry("when removing /spec/virtualMachineOptions/disableFreePageReporting", "/spec/virtualMachineOptions/disableFreePageReporting"), Entry("when removing /spec/virtualMachineOptions/disableSerialConsoleLog", "/spec/virtualMachineOptions/disableSerialConsoleLog"), @@ -242,16 +237,16 @@ var _ = Describe("Check Default values", Label("defaults"), Serial, func() { MemoryOvercommitPercentage: 100, } - DescribeTable("Check that HigherWorkloadDensity defaults are behaving as expected", func(path string) { + DescribeTable("Check that HigherWorkloadDensity defaults are behaving as expected", func(ctx context.Context, path string) { patch := []byte(fmt.Sprintf(removePathPatchTmplt, path)) - Eventually(func() error { + Eventually(func(ctx context.Context) error { return tests.PatchHCO(ctx, cli, patch) - }).WithTimeout(2 * time.Second).WithPolling(500 * time.Millisecond).Should(Succeed()) + }).WithTimeout(2 * time.Second).WithPolling(500 * time.Millisecond).WithContext(ctx).Should(Succeed()) - Eventually(func(g Gomega) { + Eventually(func(g Gomega, ctx context.Context) { hc := tests.GetHCO(ctx, cli) g.Expect(reflect.DeepEqual(hc.Spec.HigherWorkloadDensity, defaultHigherWorkloadDensity)).To(BeTrue(), "HigherWorkloadDensity should be equal to default") - }).WithTimeout(2 * time.Second).WithPolling(100 * time.Millisecond).Should(Succeed()) + }).WithTimeout(2 * time.Second).WithPolling(100 * time.Millisecond).WithContext(ctx).Should(Succeed()) }, Entry("when removing /spec/higherWorkloadDensity/memoryOvercommitPercentage", "/spec/higherWorkloadDensity/memoryOvercommitPercentage"), Entry("when removing /spec/higherWorkloadDensity", "/spec/higherWorkloadDensity"), diff --git a/tests/func-tests/dependency_objects_test.go b/tests/func-tests/dependency_objects_test.go index 17d14f2a6..a6560b05b 100644 --- a/tests/func-tests/dependency_objects_test.go +++ b/tests/func-tests/dependency_objects_test.go @@ -16,8 +16,8 @@ var _ = Describe("[rfe_id:5672][crit:medium][vendor:cnv-qe@redhat.com][level:sys var stopChan chan struct{} - BeforeEach(func() { - tests.BeforeEach() + BeforeEach(func(ctx context.Context) { + tests.BeforeEach(ctx) stopChan = make(chan struct{}) }) @@ -25,9 +25,9 @@ var _ = Describe("[rfe_id:5672][crit:medium][vendor:cnv-qe@redhat.com][level:sys close(stopChan) }) - It("[test_id:5674]should get the created priority class for critical workloads", Label("test_id:5674"), func() { + It("[test_id:5674]should get the created priority class for critical workloads", Label("test_id:5674"), func(ctx context.Context) { cli := tests.GetK8sClientSet() - _, err := cli.SchedulingV1().PriorityClasses().Get(context.TODO(), priorityClassName, v1.GetOptions{}) + _, err := cli.SchedulingV1().PriorityClasses().Get(ctx, priorityClassName, v1.GetOptions{}) Expect(err).ToNot(HaveOccurred()) }) diff --git a/tests/func-tests/golden_image_test.go b/tests/func-tests/golden_image_test.go index 27b64f4f4..5a7b47ce8 100644 --- a/tests/func-tests/golden_image_test.go +++ b/tests/func-tests/golden_image_test.go @@ -44,10 +44,7 @@ var ( ) var _ = Describe("golden image test", Label("data-import-cron"), Serial, Ordered, Label(tests.OpenshiftLabel), func() { - var ( - cli client.Client - ctx context.Context - ) + var cli client.Client tests.FlagParse() @@ -68,9 +65,8 @@ var _ = Describe("golden image test", Label("data-import-cron"), Serial, Ordered expectedImageStreams = expectedISFromConfig } - BeforeEach(func() { + BeforeEach(func(ctx context.Context) { cli = tests.GetControllerRuntimeClient() - ctx = context.Background() tests.FailIfNotOpenShift(ctx, cli, "golden image test") }) @@ -81,7 +77,7 @@ var _ = Describe("golden image test", Label("data-import-cron"), Serial, Ordered isEntries = append(isEntries, Entry(fmt.Sprintf("check the %s imagestream", is.Name), is)) } - DescribeTable("check that imagestream created", func(expectedIS tests.ImageStreamConfig) { + DescribeTable("check that imagestream created", func(ctx context.Context, expectedIS tests.ImageStreamConfig) { is := getImageStream(ctx, cli, expectedIS.Name, imageNamespace) Expect(is.Spec.Tags[0].From).ToNot(BeNil()) @@ -91,7 +87,7 @@ var _ = Describe("golden image test", Label("data-import-cron"), Serial, Ordered isEntries, ) - DescribeTable("check imagestream reconciliation", func(expectedIS tests.ImageStreamConfig) { + DescribeTable("check imagestream reconciliation", func(ctx context.Context, expectedIS tests.ImageStreamConfig) { is := getImageStream(ctx, cli, expectedIS.Name, imageNamespace) expectedValue := is.GetLabels()["app.kubernetes.io/part-of"] @@ -100,27 +96,27 @@ var _ = Describe("golden image test", Label("data-import-cron"), Serial, Ordered patchOp := []byte(`[{"op": "replace", "path": "/metadata/labels/app.kubernetes.io~1part-of", "value": "wrong-value"}]`) patch := client.RawPatch(types.JSONPatchType, patchOp) - Eventually(func() error { + Eventually(func(ctx context.Context) error { return cli.Patch(ctx, is, patch) - }).WithTimeout(time.Second * 5).WithPolling(time.Millisecond * 100).Should(Succeed()) + }).WithTimeout(time.Second * 5).WithPolling(time.Millisecond * 100).WithContext(ctx).Should(Succeed()) - Eventually(func(g Gomega) string { + Eventually(func(g Gomega, ctx context.Context) string { is = getImageStream(ctx, cli, expectedIS.Name, imageNamespace) return is.GetLabels()["app.kubernetes.io/part-of"] - }).WithTimeout(time.Second * 15).WithPolling(time.Millisecond * 100).Should(Equal(expectedValue)) + }).WithTimeout(time.Second * 15).WithPolling(time.Millisecond * 100).WithContext(ctx).Should(Equal(expectedValue)) }, isEntries, ) }) - It("make sure the feature gate is set", func() { + It("make sure the feature gate is set", func(ctx context.Context) { hco := tests.GetHCO(ctx, cli) Expect(hco.Spec.FeatureGates.EnableCommonBootImageImport).To(HaveValue(BeTrue())) }) Context("check default golden images", func() { - It("should propagate the DICT to SSP", func() { - Eventually(func(g Gomega) []string { + It("should propagate the DICT to SSP", func(ctx context.Context) { + Eventually(func(g Gomega, ctx context.Context) []string { ssp := getSSP(ctx, cli) g.Expect(ssp.Spec.CommonTemplates.DataImportCronTemplates).To(HaveLen(len(expectedImages))) @@ -130,11 +126,11 @@ var _ = Describe("golden image test", Label("data-import-cron"), Serial, Ordered } sort.Strings(imageNames) return imageNames - }).WithTimeout(10 * time.Second).WithPolling(100 * time.Millisecond).Should(Equal(expectedImages)) + }).WithTimeout(10 * time.Second).WithPolling(100 * time.Millisecond).WithContext(ctx).Should(Equal(expectedImages)) }) - It("should have all the images in the HyperConverged status", func() { - Eventually(func(g Gomega) []string { + It("should have all the images in the HyperConverged status", func(ctx context.Context) { + Eventually(func(g Gomega, ctx context.Context) []string { hco := tests.GetHCO(ctx, cli) g.Expect(hco.Status.DataImportCronTemplates).To(HaveLen(len(expectedImages))) @@ -146,11 +142,11 @@ var _ = Describe("golden image test", Label("data-import-cron"), Serial, Ordered sort.Strings(imageNames) return imageNames - }).WithTimeout(10 * time.Second).WithPolling(100 * time.Millisecond).Should(Equal(expectedImages)) + }).WithTimeout(10 * time.Second).WithPolling(100 * time.Millisecond).WithContext(ctx).Should(Equal(expectedImages)) }) - It("should have all the DataImportCron resources", func() { - Eventually(func(g Gomega) []string { + It("should have all the DataImportCron resources", func(ctx context.Context) { + Eventually(func(g Gomega, ctx context.Context) []string { dicList := &cdiv1beta1.DataImportCronList{} Expect(cli.List(ctx, dicList, client.InNamespace(imageNamespace))).To(Succeed()) @@ -163,7 +159,7 @@ var _ = Describe("golden image test", Label("data-import-cron"), Serial, Ordered sort.Strings(imageNames) return imageNames - }).WithTimeout(5 * time.Minute).WithPolling(5 * time.Second).Should(Equal(expectedImages)) + }).WithTimeout(5 * time.Minute).WithPolling(5 * time.Second).WithContext(ctx).Should(Equal(expectedImages)) }) }) @@ -175,7 +171,7 @@ var _ = Describe("golden image test", Label("data-import-cron"), Serial, Ordered } } - DescribeTable("check the images that use image streams", func(imageName, streamName string) { + DescribeTable("check the images that use image streams", func(ctx context.Context, imageName, streamName string) { dic := &cdiv1beta1.DataImportCron{ ObjectMeta: metav1.ObjectMeta{ Name: imageName, @@ -193,9 +189,11 @@ var _ = Describe("golden image test", Label("data-import-cron"), Serial, Ordered }) Context("disable the feature", func() { - It("Should set the FG to false", func() { + It("Should set the FG to false", func(ctx context.Context) { patch := []byte(`[{ "op": "replace", "path": "/spec/featureGates/enableCommonBootImageImport", "value": false }]`) - Eventually(tests.PatchHCO).WithArguments(ctx, cli, patch).WithTimeout(5 * time.Second).WithPolling(100 * time.Millisecond).Should(Succeed()) + Eventually(func(ctx context.Context) error { + return tests.PatchHCO(ctx, cli, patch) + }).WithTimeout(5 * time.Second).WithPolling(100 * time.Millisecond).WithContext(ctx).Should(Succeed()) }) var isEntries []TableEntry @@ -204,8 +202,8 @@ var _ = Describe("golden image test", Label("data-import-cron"), Serial, Ordered } if len(isEntries) > 0 { - DescribeTable("imageStream should be removed", func(expectedIS tests.ImageStreamConfig) { - Eventually(func() error { + DescribeTable("imageStream should be removed", func(ctx context.Context, expectedIS tests.ImageStreamConfig) { + Eventually(func(ctx context.Context) error { is := &v1.ImageStream{ ObjectMeta: metav1.ObjectMeta{ Name: expectedIS.Name, @@ -214,38 +212,40 @@ var _ = Describe("golden image test", Label("data-import-cron"), Serial, Ordered } return cli.Get(ctx, client.ObjectKeyFromObject(is), is) - }).WithTimeout(5 * time.Second).WithPolling(100 * time.Millisecond).Should(MatchError(errors.IsNotFound, "not found error")) + }).WithTimeout(5 * time.Second).WithPolling(100 * time.Millisecond).WithContext(ctx).Should(MatchError(errors.IsNotFound, "not found error")) }, isEntries) } - It("should empty the DICT in SSP", func() { - Eventually(func(g Gomega) []v1beta2.DataImportCronTemplate { + It("should empty the DICT in SSP", func(ctx context.Context) { + Eventually(func(g Gomega, ctx context.Context) []v1beta2.DataImportCronTemplate { ssp := getSSP(ctx, cli) return ssp.Spec.CommonTemplates.DataImportCronTemplates - }).WithTimeout(5 * time.Second).WithPolling(100 * time.Millisecond).Should(BeEmpty()) + }).WithTimeout(5 * time.Second).WithPolling(100 * time.Millisecond).WithContext(ctx).Should(BeEmpty()) }) - It("should have no images in the HyperConverged status", func() { - Eventually(func() []hcov1beta1.DataImportCronTemplateStatus { + It("should have no images in the HyperConverged status", func(ctx context.Context) { + Eventually(func(ctx context.Context) []hcov1beta1.DataImportCronTemplateStatus { hco := tests.GetHCO(ctx, cli) return hco.Status.DataImportCronTemplates - }).WithTimeout(5 * time.Second).WithPolling(100 * time.Millisecond).Should(BeEmpty()) + }).WithTimeout(5 * time.Second).WithPolling(100 * time.Millisecond).WithContext(ctx).Should(BeEmpty()) }) - It("should have no images", func() { - Eventually(func(g Gomega) []v1.ImageStream { + It("should have no images", func(ctx context.Context) { + Eventually(func(g Gomega, ctx context.Context) []v1.ImageStream { isList := &v1.ImageStreamList{} Expect(cli.List(ctx, isList, client.InNamespace(imageNamespace))).To(Succeed()) return isList.Items - }).WithTimeout(5 * time.Minute).WithPolling(time.Second).Should(BeEmpty()) + }).WithTimeout(5 * time.Minute).WithPolling(time.Second).WithContext(ctx).Should(BeEmpty()) }) }) Context("enable the feature again", func() { - It("Should set the FG to false", func() { + It("Should set the FG to false", func(ctx context.Context) { patch := []byte(`[{ "op": "replace", "path": "/spec/featureGates/enableCommonBootImageImport", "value": true }]`) - Eventually(tests.PatchHCO).WithArguments(ctx, cli, patch).WithTimeout(5 * time.Second).WithPolling(100 * time.Millisecond).Should(Succeed()) + Eventually(func(ctx context.Context) error { + return tests.PatchHCO(ctx, cli, patch) + }).WithTimeout(5 * time.Second).WithPolling(100 * time.Millisecond).WithContext(ctx).Should(Succeed()) }) var isEntries []TableEntry @@ -254,8 +254,8 @@ var _ = Describe("golden image test", Label("data-import-cron"), Serial, Ordered } if len(isEntries) > 0 { - DescribeTable("imageStream should be recovered", func(expectedIS tests.ImageStreamConfig) { - Eventually(func(g Gomega) error { + DescribeTable("imageStream should be recovered", func(ctx context.Context, expectedIS tests.ImageStreamConfig) { + Eventually(func(g Gomega, ctx context.Context) error { is := v1.ImageStream{ ObjectMeta: metav1.ObjectMeta{ Name: expectedIS.Name, @@ -263,38 +263,38 @@ var _ = Describe("golden image test", Label("data-import-cron"), Serial, Ordered }, } return cli.Get(ctx, client.ObjectKeyFromObject(&is), &is) - }).WithTimeout(5 * time.Second).WithPolling(100 * time.Millisecond).ShouldNot(HaveOccurred()) + }).WithTimeout(5 * time.Second).WithPolling(100 * time.Millisecond).WithContext(ctx).ShouldNot(HaveOccurred()) }, isEntries) } - It("should propagate the DICT in SSP", func() { - Eventually(func(g Gomega) []v1beta2.DataImportCronTemplate { + It("should propagate the DICT in SSP", func(ctx context.Context) { + Eventually(func(g Gomega, ctx context.Context) []v1beta2.DataImportCronTemplate { ssp := getSSP(ctx, cli) return ssp.Spec.CommonTemplates.DataImportCronTemplates - }).WithTimeout(5 * time.Second).WithPolling(100 * time.Millisecond).Should(HaveLen(len(expectedImages))) + }).WithTimeout(5 * time.Second).WithPolling(100 * time.Millisecond).WithContext(ctx).Should(HaveLen(len(expectedImages))) }) - It("should have all the images in the HyperConverged status", func() { - Eventually(func() []hcov1beta1.DataImportCronTemplateStatus { + It("should have all the images in the HyperConverged status", func(ctx context.Context) { + Eventually(func(ctx context.Context) []hcov1beta1.DataImportCronTemplateStatus { hco := tests.GetHCO(ctx, cli) return hco.Status.DataImportCronTemplates - }).WithTimeout(5 * time.Second).WithPolling(100 * time.Millisecond).Should(HaveLen(len(expectedImages))) + }).WithTimeout(5 * time.Second).WithPolling(100 * time.Millisecond).WithContext(ctx).Should(HaveLen(len(expectedImages))) }) - It("should restore all the DataImportCron resources", func() { - Eventually(func(g Gomega) []cdiv1beta1.DataImportCron { + It("should restore all the DataImportCron resources", func(ctx context.Context) { + Eventually(func(g Gomega, ctx context.Context) []cdiv1beta1.DataImportCron { dicList := &cdiv1beta1.DataImportCronList{} Expect(cli.List(ctx, dicList, client.InNamespace(imageNamespace))).To(Succeed()) return dicList.Items - }).WithTimeout(5 * time.Minute).WithPolling(5 * time.Second).Should(HaveLen(len(expectedImages))) + }).WithTimeout(5 * time.Minute).WithPolling(5 * time.Second).WithContext(ctx).Should(HaveLen(len(expectedImages))) }) }) Context("test annotations", func() { - AfterEach(func() { - Eventually(func(g Gomega) { + AfterEach(func(ctx context.Context) { + Eventually(func(g Gomega, ctx context.Context) { hc := tests.GetHCO(ctx, cli) // make sure there no user-defined DICT @@ -306,11 +306,11 @@ var _ = Describe("golden image test", Label("data-import-cron"), Serial, Ordered tests.UpdateHCORetry(ctx, cli, hc) } - }).WithPolling(time.Second * 3).WithTimeout(time.Second * 60).Should(Succeed()) + }).WithPolling(time.Second * 3).WithTimeout(time.Second * 60).WithContext(ctx).Should(Succeed()) }) - It("should add missing annotation in the DICT", func() { - Eventually(func(g Gomega) { + It("should add missing annotation in the DICT", func(ctx context.Context) { + Eventually(func(g Gomega, ctx context.Context) { hc := tests.GetHCO(ctx, cli) hc.Spec.DataImportCronTemplates = []hcov1beta1.DataImportCronTemplate{ @@ -322,11 +322,11 @@ var _ = Describe("golden image test", Label("data-import-cron"), Serial, Ordered g.Expect(newHC.Spec.DataImportCronTemplates).To(HaveLen(1)) g.Expect(newHC.Spec.DataImportCronTemplates[0].Annotations).To(HaveKeyWithValue(cdiImmediateBindAnnotation, "true"), "should add the missing annotation") - }).WithPolling(time.Second * 3).WithTimeout(time.Second * 60).Should(Succeed()) + }).WithPolling(time.Second * 3).WithTimeout(time.Second * 60).WithContext(ctx).Should(Succeed()) }) - It("should not change existing annotation in the DICT", func() { - Eventually(func(g Gomega) { + It("should not change existing annotation in the DICT", func(ctx context.Context) { + Eventually(func(g Gomega, ctx context.Context) { hc := tests.GetHCO(ctx, cli) hc.Spec.DataImportCronTemplates = []hcov1beta1.DataImportCronTemplate{ @@ -342,7 +342,7 @@ var _ = Describe("golden image test", Label("data-import-cron"), Serial, Ordered g.Expect(newHC.Spec.DataImportCronTemplates).To(HaveLen(1)) g.Expect(newHC.Spec.DataImportCronTemplates[0].Annotations).To(HaveKeyWithValue(cdiImmediateBindAnnotation, "false"), "should not change existing annotation") - }).WithPolling(time.Second * 3).WithTimeout(time.Second * 60).Should(Succeed()) + }).WithPolling(time.Second * 3).WithTimeout(time.Second * 60).WithContext(ctx).Should(Succeed()) }) }) }) diff --git a/tests/func-tests/labels_test.go b/tests/func-tests/labels_test.go index 001222532..09f5fee36 100644 --- a/tests/func-tests/labels_test.go +++ b/tests/func-tests/labels_test.go @@ -28,17 +28,14 @@ var _ = Describe("Check that all the sub-resources have the required labels", La var ( cli client.Client cliSet *kubernetes.Clientset - ctx context.Context ) BeforeEach(func() { cli = tests.GetControllerRuntimeClient() cliSet = tests.GetK8sClientSet() - - ctx = context.Background() }) - It("should have all the required labels in all the controlled resources", func() { + It("should have all the required labels in all the controlled resources", func(ctx context.Context) { hc := tests.GetHCO(ctx, cli) plural := pluralize.NewClient() const kvName = "kubevirt-kubevirt-hyperconverged" @@ -57,14 +54,14 @@ var _ = Describe("Check that all the sub-resources have the required labels", La patchBytes := []byte(`[{"op": "remove", "path": "/metadata/labels/app.kubernetes.io~1version"}]`) patch := client.RawPatch(types.JSONPatchType, patchBytes) - Eventually(func() error { + Eventually(func(ctx context.Context) error { return cli.Patch(ctx, kv, patch) - }).WithTimeout(time.Second * 5).WithPolling(time.Millisecond * 100).Should(Succeed()) + }).WithTimeout(time.Second * 5).WithPolling(time.Millisecond * 100).WithContext(ctx).Should(Succeed()) - Eventually(func(g Gomega) { + Eventually(func(g Gomega, ctx context.Context) { g.Expect(cli.Get(ctx, client.ObjectKeyFromObject(kv), kv)).To(Succeed()) g.Expect(kv.Labels).To(HaveKeyWithValue(hcoutil.AppLabelVersion, expectedVersion)) - }).WithTimeout(5 * time.Second).WithPolling(100 * time.Millisecond).Should(Succeed()) + }).WithTimeout(5 * time.Second).WithPolling(100 * time.Millisecond).WithContext(ctx).Should(Succeed()) By("checking all the labels") for _, resource := range hc.Status.RelatedObjects { diff --git a/tests/func-tests/main_test.go b/tests/func-tests/main_test.go index 5cf5072a9..30a03fc2a 100644 --- a/tests/func-tests/main_test.go +++ b/tests/func-tests/main_test.go @@ -18,7 +18,7 @@ func TestTests(t *testing.T) { RunSpecs(t, "HyperConverged cluster E2E Test suite") } -var _ = BeforeSuite(func() { +var _ = BeforeSuite(func(ctx context.Context) { cli := tests.GetK8sClientSet() ns := &v1.Namespace{ @@ -28,19 +28,19 @@ var _ = BeforeSuite(func() { } opt := metav1.CreateOptions{} - _, err := cli.CoreV1().Namespaces().Create(context.Background(), ns, opt) + _, err := cli.CoreV1().Namespaces().Create(ctx, ns, opt) if err != nil { if !errors.IsAlreadyExists(err) { panic(err) } } - tests.BeforeEach() + tests.BeforeEach(ctx) }) -var _ = AfterSuite(func() { +var _ = AfterSuite(func(ctx context.Context) { cli := tests.GetK8sClientSet() - err := cli.CoreV1().Namespaces().Delete(context.Background(), tests.TestNamespace, metav1.DeleteOptions{}) + err := cli.CoreV1().Namespaces().Delete(ctx, tests.TestNamespace, metav1.DeleteOptions{}) if err != nil { panic(err) } diff --git a/tests/func-tests/mediateddevices_mediateddevice_test.go b/tests/func-tests/mediateddevices_mediateddevice_test.go index 45787304c..7a5098f38 100644 --- a/tests/func-tests/mediateddevices_mediateddevice_test.go +++ b/tests/func-tests/mediateddevices_mediateddevice_test.go @@ -22,7 +22,6 @@ import ( var _ = Describe("MediatedDevicesTypes -> MediatedDeviceTypes", Label("MediatedDevices"), func() { var ( cli client.Client - ctx context.Context initialMDC *v1beta1.MediatedDevicesConfiguration apiServerError = apiservererrors.ToStatusErr( util.HcoValidatingWebhook, @@ -36,11 +35,10 @@ var _ = Describe("MediatedDevicesTypes -> MediatedDeviceTypes", Label("MediatedD tests.FlagParse() - BeforeEach(func() { + BeforeEach(func(ctx context.Context) { cli = tests.GetControllerRuntimeClient() - ctx = context.Background() - tests.BeforeEach() + tests.BeforeEach(ctx) hc := tests.GetHCO(ctx, cli) initialMDC = nil if hc.Spec.MediatedDevicesConfiguration != nil { @@ -48,20 +46,20 @@ var _ = Describe("MediatedDevicesTypes -> MediatedDeviceTypes", Label("MediatedD } }) - AfterEach(func() { + AfterEach(func(ctx context.Context) { hc := tests.GetHCO(ctx, cli) hc.Spec.MediatedDevicesConfiguration = initialMDC _ = tests.UpdateHCORetry(ctx, cli, hc) }) DescribeTable("should correctly handle MediatedDevicesTypes -> MediatedDeviceTypes transition", - func(mediatedDevicesConfiguration *v1beta1.MediatedDevicesConfiguration, expectedErr error, expectedMediatedDevicesConfiguration *v1beta1.MediatedDevicesConfiguration, expectedKVMediatedDevicesConfiguration *kubevirtcorev1.MediatedDevicesConfiguration) { + func(ctx context.Context, mediatedDevicesConfiguration *v1beta1.MediatedDevicesConfiguration, expectedErr error, expectedMediatedDevicesConfiguration *v1beta1.MediatedDevicesConfiguration, expectedKVMediatedDevicesConfiguration *kubevirtcorev1.MediatedDevicesConfiguration) { if expectedErr == nil { hc := tests.GetHCO(ctx, cli) hc.Spec.MediatedDevicesConfiguration = mediatedDevicesConfiguration hc = tests.UpdateHCORetry(ctx, cli, hc) Expect(hc.Spec.MediatedDevicesConfiguration).To(Equal(expectedMediatedDevicesConfiguration)) - Eventually(func() *kubevirtcorev1.MediatedDevicesConfiguration { + Eventually(func(g Gomega, ctx context.Context) *kubevirtcorev1.MediatedDevicesConfiguration { kv := &kubevirtcorev1.KubeVirt{ ObjectMeta: metav1.ObjectMeta{ Name: "kubevirt-kubevirt-hyperconverged", @@ -69,17 +67,23 @@ var _ = Describe("MediatedDevicesTypes -> MediatedDeviceTypes", Label("MediatedD }, } - Expect(cli.Get(ctx, client.ObjectKeyFromObject(kv), kv)).To(Succeed()) + g.Expect(cli.Get(ctx, client.ObjectKeyFromObject(kv), kv)).To(Succeed()) return kv.Spec.Configuration.MediatedDevicesConfiguration - }, 10*time.Second, time.Second).Should(Equal(expectedKVMediatedDevicesConfiguration)) + }).WithTimeout(10 * time.Second). + WithPolling(time.Second). + WithContext(ctx). + Should(Equal(expectedKVMediatedDevicesConfiguration)) } else { - Eventually(func() error { + Eventually(func(ctx context.Context) error { hc := tests.GetHCO(ctx, cli) hc.Spec.MediatedDevicesConfiguration = mediatedDevicesConfiguration _, err := tests.UpdateHCO(ctx, cli, hc) return err - }, 10*time.Second, time.Second).Should(MatchError(expectedErr)) + }).WithTimeout(10 * time.Second). + WithPolling(time.Second). + WithContext(ctx). + Should(MatchError(expectedErr)) } }, Entry("should do nothing when mediatedDevicesConfiguration is not present", diff --git a/tests/func-tests/monitoring_test.go b/tests/func-tests/monitoring_test.go index 0dc1adf6e..4f56c3090 100644 --- a/tests/func-tests/monitoring_test.go +++ b/tests/func-tests/monitoring_test.go @@ -49,23 +49,20 @@ var _ = Describe("[crit:high][vendor:cnv-qe@redhat.com][level:system]Monitoring" promClient promApiv1.API prometheusRule monitoringv1.PrometheusRule initialOperatorHealthMetricValue float64 - ctx context.Context ) runbookClient.Timeout = time.Second * 3 - BeforeEach(func() { + BeforeEach(func(ctx context.Context) { cli = tests.GetControllerRuntimeClient() cliSet = tests.GetK8sClientSet() restClient = cliSet.RESTClient() - ctx = context.Background() - tests.FailIfNotOpenShift(ctx, cli, "Prometheus") - promClient = initializePromClient(getPrometheusURL(restClient), getAuthorizationTokenForPrometheus(ctx, cliSet)) - prometheusRule = getPrometheusRule(restClient) + promClient = initializePromClient(getPrometheusURL(ctx, restClient), getAuthorizationTokenForPrometheus(ctx, cliSet)) + prometheusRule = getPrometheusRule(ctx, restClient) - initialOperatorHealthMetricValue = getMetricValue(promClient, "kubevirt_hyperconverged_operator_health_status") + initialOperatorHealthMetricValue = getMetricValue(ctx, promClient, "kubevirt_hyperconverged_operator_health_status") }) It("Alert rules should have all the requried annotations", func() { @@ -101,7 +98,7 @@ var _ = Describe("[crit:high][vendor:cnv-qe@redhat.com][level:system]Monitoring" } }) - It("KubeVirtCRModified alert should fired when there is a modification on a CR", func() { + It("KubeVirtCRModified alert should fired when there is a modification on a CR", func(ctx context.Context) { By("Patching kubevirt object") const ( fakeFG = "fake-fg-for-testing" @@ -109,15 +106,15 @@ var _ = Describe("[crit:high][vendor:cnv-qe@redhat.com][level:system]Monitoring" ) var valueBefore float64 - Eventually(func(g Gomega) { - valueBefore = getMetricValue(promClient, query) - }).WithTimeout(10 * time.Second).WithPolling(500 * time.Millisecond).Should(Succeed()) + Eventually(func(g Gomega, ctx context.Context) { + valueBefore = getMetricValue(ctx, promClient, query) + }).WithTimeout(10 * time.Second).WithPolling(500 * time.Millisecond).WithContext(ctx).Should(Succeed()) patchBytes := []byte(fmt.Sprintf(`[{"op": "add", "path": "/spec/configuration/developerConfiguration/featureGates/-", "value": %q}]`, fakeFG)) patch := client.RawPatch(types.JSONPatchType, patchBytes) retries := float64(0) - Eventually(func(g Gomega) []string { + Eventually(func(g Gomega, ctx context.Context) []string { kv := &kubevirtcorev1.KubeVirt{ ObjectMeta: metav1.ObjectMeta{ Name: "kubevirt-kubevirt-hyperconverged", @@ -132,30 +129,32 @@ var _ = Describe("[crit:high][vendor:cnv-qe@redhat.com][level:system]Monitoring" return kv.Spec.Configuration.DeveloperConfiguration.FeatureGates }).WithTimeout(10 * time.Second). WithPolling(100 * time.Millisecond). + WithContext(ctx). Should(ContainElement(fakeFG)) Expect(retries).To(BeNumerically(">", 0)) - Eventually(func(g Gomega) float64 { - return getMetricValue(promClient, query) + Eventually(func(g Gomega, ctx context.Context) float64 { + return getMetricValue(ctx, promClient, query) }).WithTimeout(60*time.Second). WithPolling(time.Second). + WithContext(ctx). Should( Equal(valueBefore+retries), "expected different counter value; valueBefore: %0.2f; retries: %0.2f", valueBefore, retries, ) - Eventually(func() *promApiv1.Alert { + Eventually(func(ctx context.Context) *promApiv1.Alert { alerts, err := promClient.Alerts(ctx) Expect(err).ToNot(HaveOccurred()) alert := getAlertByName(alerts, "KubeVirtCRModified") return alert - }).WithTimeout(60 * time.Second).WithPolling(time.Second).ShouldNot(BeNil()) + }).WithTimeout(60 * time.Second).WithPolling(time.Second).WithContext(ctx).ShouldNot(BeNil()) - verifyOperatorHealthMetricValue(promClient, initialOperatorHealthMetricValue, warningImpact) + verifyOperatorHealthMetricValue(ctx, promClient, initialOperatorHealthMetricValue, warningImpact) }) - It("UnsupportedHCOModification alert should fired when there is an jsonpatch annotation to modify an operand CRs", func() { + It("UnsupportedHCOModification alert should fired when there is an jsonpatch annotation to modify an operand CRs", func(ctx context.Context) { By("Updating HCO object with a new label") hco := tests.GetHCO(ctx, cli) @@ -164,13 +163,13 @@ var _ = Describe("[crit:high][vendor:cnv-qe@redhat.com][level:system]Monitoring" } tests.UpdateHCORetry(ctx, cli, hco) - Eventually(func() *promApiv1.Alert { - alerts, err := promClient.Alerts(context.TODO()) + Eventually(func(ctx context.Context) *promApiv1.Alert { + alerts, err := promClient.Alerts(ctx) Expect(err).ToNot(HaveOccurred()) alert := getAlertByName(alerts, "UnsupportedHCOModification") return alert - }, 60*time.Second, time.Second).ShouldNot(BeNil()) - verifyOperatorHealthMetricValue(promClient, initialOperatorHealthMetricValue, warningImpact) + }).WithTimeout(60 * time.Second).WithPolling(time.Second).WithContext(ctx).ShouldNot(BeNil()) + verifyOperatorHealthMetricValue(ctx, promClient, initialOperatorHealthMetricValue, warningImpact) }) }) @@ -183,11 +182,11 @@ func getAlertByName(alerts promApiv1.AlertsResult, alertName string) *promApiv1. return nil } -func verifyOperatorHealthMetricValue(promClient promApiv1.API, initialOperatorHealthMetricValue, alertImpact float64) { - Eventually(func(g Gomega) { +func verifyOperatorHealthMetricValue(ctx context.Context, promClient promApiv1.API, initialOperatorHealthMetricValue, alertImpact float64) { + Eventually(func(g Gomega, ctx context.Context) { if alertImpact >= initialOperatorHealthMetricValue { - systemHealthMetricValue := getMetricValue(promClient, "kubevirt_hco_system_health_status") - operatorHealthMetricValue := getMetricValue(promClient, "kubevirt_hyperconverged_operator_health_status") + systemHealthMetricValue := getMetricValue(ctx, promClient, "kubevirt_hco_system_health_status") + operatorHealthMetricValue := getMetricValue(ctx, promClient, "kubevirt_hyperconverged_operator_health_status") expectedOperatorHealthMetricValue := math.Max(alertImpact, systemHealthMetricValue) g.Expect(operatorHealthMetricValue).To(Equal(expectedOperatorHealthMetricValue), @@ -196,11 +195,11 @@ func verifyOperatorHealthMetricValue(promClient promApiv1.API, initialOperatorHe operatorHealthMetricValue, expectedOperatorHealthMetricValue, systemHealthMetricValue) } - }, 60*time.Second, 5*time.Second).Should(Succeed()) + }).WithTimeout(60 * time.Second).WithPolling(5 * time.Second).WithContext(ctx).Should(Succeed()) } -func getMetricValue(promClient promApiv1.API, metricName string) float64 { - queryResult, _, err := promClient.Query(context.TODO(), metricName, time.Now()) +func getMetricValue(ctx context.Context, promClient promApiv1.API, metricName string) float64 { + queryResult, _, err := promClient.Query(ctx, metricName, time.Now()) ExpectWithOffset(1, err).ShouldNot(HaveOccurred()) resultVector := queryResult.(promModel.Vector) @@ -216,7 +215,7 @@ func getMetricValue(promClient promApiv1.API, metricName string) float64 { return metricValue } -func getPrometheusRule(cli rest.Interface) monitoringv1.PrometheusRule { +func getPrometheusRule(ctx context.Context, cli rest.Interface) monitoringv1.PrometheusRule { var prometheusRule monitoringv1.PrometheusRule ExpectWithOffset(1, cli.Get(). @@ -225,7 +224,7 @@ func getPrometheusRule(cli rest.Interface) monitoringv1.PrometheusRule { Namespace(tests.InstallNamespace). AbsPath("/apis", monitoringv1.SchemeGroupVersion.Group, monitoringv1.SchemeGroupVersion.Version). Timeout(10*time.Second). - Do(context.TODO()).Into(&prometheusRule)).Should(Succeed()) + Do(ctx).Into(&prometheusRule)).Should(Succeed()) return prometheusRule } @@ -253,7 +252,7 @@ func initializePromClient(prometheusURL string, token string) promApiv1.API { func getAuthorizationTokenForPrometheus(ctx context.Context, cli *kubernetes.Clientset) string { var token string - Eventually(func() bool { + Eventually(func(ctx context.Context) bool { treq, err := cli.CoreV1().ServiceAccounts("openshift-monitoring").CreateToken( ctx, "prometheus-k8s", @@ -270,27 +269,28 @@ func getAuthorizationTokenForPrometheus(ctx context.Context, cli *kubernetes.Cli } token = treq.Status.Token return true - }, 10*time.Second, time.Second).Should(BeTrue()) + }).WithTimeout(10 * time.Second).WithPolling(time.Second).WithContext(ctx).Should(BeTrue()) return token } -func getPrometheusURL(cli rest.Interface) string { +func getPrometheusURL(ctx context.Context, cli rest.Interface) string { s := scheme.Scheme _ = openshiftroutev1.Install(s) s.AddKnownTypes(openshiftroutev1.GroupVersion) var route openshiftroutev1.Route - Eventually(func() error { + Eventually(func(ctx context.Context) error { return cli.Get(). Resource("routes"). Name("prometheus-k8s"). Namespace("openshift-monitoring"). AbsPath("/apis", openshiftroutev1.GroupVersion.Group, openshiftroutev1.GroupVersion.Version). Timeout(10 * time.Second). - Do(context.TODO()).Into(&route) + Do(ctx).Into(&route) }).WithTimeout(2 * time.Minute). WithPolling(15 * time.Second). // longer than the request timeout + WithContext(ctx). Should(Succeed()) return fmt.Sprintf("https://%s", route.Spec.Host) diff --git a/tests/func-tests/node_placement_test.go b/tests/func-tests/node_placement_test.go index 86cc93af7..dea284894 100644 --- a/tests/func-tests/node_placement_test.go +++ b/tests/func-tests/node_placement_test.go @@ -36,13 +36,11 @@ var _ = Describe("[rfe_id:4356][crit:medium][vendor:cnv-qe@redhat.com][level:sys originalWorkloadSpec hcov1beta1.HyperConvergedConfig cli client.Client cliSet *kubernetes.Clientset - ctx context.Context ) - BeforeAll(func() { + BeforeAll(func(ctx context.Context) { cli = tests.GetControllerRuntimeClient() cliSet = tests.GetK8sClientSet() - ctx = context.Background() nodes := listNodesByLabels(ctx, cliSet, "node-role.kubernetes.io/control-plane!=") tests.FailIfSingleNode(len(nodes.Items) < 2) @@ -50,19 +48,19 @@ var _ = Describe("[rfe_id:4356][crit:medium][vendor:cnv-qe@redhat.com][level:sys // Label all but first node with "node.kubernetes.io/hco-test-node-type=infra" // We are doing this to remove dependency of this Describe block on a shell script that // labels the nodes this way - Eventually(func(g Gomega) { + Eventually(func(g Gomega, ctx context.Context) { for _, node := range nodes.Items[:len(nodes.Items)-1] { done, err := setHcoNodeTypeLabel(ctx, cliSet, &node, infra) g.Expect(err).ToNot(HaveOccurred()) g.Expect(done).To(BeTrue()) } - }).WithTimeout(5 * time.Minute).WithPolling(10 * time.Second).Should(Succeed()) + }).WithTimeout(5 * time.Minute).WithPolling(10 * time.Second).WithContext(ctx).Should(Succeed()) // Label the last node with "node.kubernetes.io/hco-test-node-type=workloads" - Eventually(func(g Gomega) { + Eventually(func(g Gomega, ctx context.Context) { done, err := setHcoNodeTypeLabel(ctx, cliSet, &nodes.Items[len(nodes.Items)-1], workloads) g.Expect(err).ToNot(HaveOccurred()) g.Expect(done).To(BeTrue()) - }).WithTimeout(5 * time.Minute).WithPolling(10 * time.Second).Should(Succeed()) + }).WithTimeout(5 * time.Minute).WithPolling(10 * time.Second).WithContext(ctx).Should(Succeed()) // modify the HCO CR to use the labels we just applied to the nodes originalHco := tests.GetHCO(ctx, cli) @@ -97,7 +95,7 @@ var _ = Describe("[rfe_id:4356][crit:medium][vendor:cnv-qe@redhat.com][level:sys _ = w.Encode(workloadsNode.Labels) }) - AfterAll(func() { + AfterAll(func(ctx context.Context) { // undo the modification to HCO CR done in BeforeAll stage modifiedHco := tests.GetHCO(ctx, cli) @@ -111,7 +109,7 @@ var _ = Describe("[rfe_id:4356][crit:medium][vendor:cnv-qe@redhat.com][level:sys nodes := listNodesByLabels(ctx, cliSet, hcoLabel) // wrap unlabelling in Eventually because for resourceVersion errors - Eventually(func(g Gomega) { + Eventually(func(g Gomega, ctx context.Context) { for _, node := range nodes.Items { n := &node labels := n.GetLabels() @@ -122,15 +120,15 @@ var _ = Describe("[rfe_id:4356][crit:medium][vendor:cnv-qe@redhat.com][level:sys _, err = cliSet.CoreV1().Nodes().Update(ctx, n, k8smetav1.UpdateOptions{}) g.Expect(err).ToNot(HaveOccurred()) } - }).WithTimeout(5 * time.Minute).WithPolling(10 * time.Second).Should(Succeed()) + }).WithTimeout(5 * time.Minute).WithPolling(10 * time.Second).WithContext(ctx).Should(Succeed()) }) - BeforeEach(func() { - tests.BeforeEach() + BeforeEach(func(ctx context.Context) { + tests.BeforeEach(ctx) }) Context("validate node placement in workloads nodes", func() { - It("[test_id:5677] all expected 'workloads' pod must be on infra node", Label("test_id:5677"), func() { + It("[test_id:5677] all expected 'workloads' pod must be on infra node", Label("test_id:5677"), func(ctx context.Context) { expectedWorkloadsPods := map[string]bool{ "bridge-marker": false, "cni-plugins": false, @@ -148,7 +146,7 @@ var _ = Describe("[rfe_id:4356][crit:medium][vendor:cnv-qe@redhat.com][level:sys delete(expectedWorkloadsPods, "secondary-dns") } - Eventually(func(g Gomega) { + Eventually(func(g Gomega, ctx context.Context) { By("Listing pods in infra node") pods := listPodsInNode(ctx, g, cliSet, workloadsNode.Name) @@ -157,12 +155,12 @@ var _ = Describe("[rfe_id:4356][crit:medium][vendor:cnv-qe@redhat.com][level:sys By("Verifying that all expected workload pods exist in workload nodes") g.Expect(expectedWorkloadsPods).ToNot(ContainElement(false)) - }).WithTimeout(5 * time.Minute).WithPolling(10 * time.Second).Should(Succeed()) + }).WithTimeout(5 * time.Minute).WithPolling(10 * time.Second).WithContext(ctx).Should(Succeed()) }) }) Context("validate node placement on infra nodes", func() { - It("[test_id:5678] all expected 'infra' pod must be on infra node", Label("test_id:5678"), func() { + It("[test_id:5678] all expected 'infra' pod must be on infra node", Label("test_id:5678"), func(ctx context.Context) { expectedInfraPods := map[string]bool{ "cdi-apiserver": false, "cdi-deployment": false, @@ -173,7 +171,7 @@ var _ = Describe("[rfe_id:4356][crit:medium][vendor:cnv-qe@redhat.com][level:sys "virt-exportproxy": false, } - Eventually(func(g Gomega) { + Eventually(func(g Gomega, ctx context.Context) { By("Listing infra nodes") infraNodes := listInfraNodes(ctx, cliSet) @@ -187,7 +185,7 @@ var _ = Describe("[rfe_id:4356][crit:medium][vendor:cnv-qe@redhat.com][level:sys By("Verifying that all expected infra pods exist in infra nodes") g.Expect(expectedInfraPods).ToNot(ContainElement(false)) - }).WithTimeout(5 * time.Minute).WithPolling(10 * time.Second).Should(Succeed()) + }).WithTimeout(5 * time.Minute).WithPolling(10 * time.Second).WithContext(ctx).Should(Succeed()) }) }) }) @@ -269,13 +267,14 @@ func setHcoNodeTypeLabel(ctx context.Context, cli *kubernetes.Clientset, node *v func listNodesByLabels(ctx context.Context, cli *kubernetes.Clientset, labelSelector string) *v1.NodeList { var nodes *v1.NodeList - Eventually(func() error { + Eventually(func(ctx context.Context) error { var err error nodes, err = cli.CoreV1().Nodes().List(ctx, k8smetav1.ListOptions{LabelSelector: labelSelector}) return err }).WithTimeout(10 * time.Second). WithPolling(time.Second). WithOffset(1). + WithContext(ctx). Should(Succeed()) return nodes diff --git a/tests/func-tests/quickstart_test.go b/tests/func-tests/quickstart_test.go index c80bc9b8a..bedee0d50 100644 --- a/tests/func-tests/quickstart_test.go +++ b/tests/func-tests/quickstart_test.go @@ -19,17 +19,15 @@ var _ = Describe("[rfe_id:5882][crit:high][vendor:cnv-qe@redhat.com][level:syste var ( cli client.Client - ctx context.Context ) - BeforeEach(func() { - tests.BeforeEach() + BeforeEach(func(ctx context.Context) { + tests.BeforeEach(ctx) cli = tests.GetControllerRuntimeClient() - ctx = context.Background() tests.FailIfNotOpenShift(ctx, cli, "quickstart") }) - It("[test_id:5883]should create ConsoleQuickStart objects", Label("test_id:5883"), func() { + It("[test_id:5883]should create ConsoleQuickStart objects", Label("test_id:5883"), func(ctx context.Context) { By("Checking expected quickstart objects") s := scheme.Scheme _ = consolev1.Install(s) diff --git a/tests/func-tests/tuningpolicy_test.go b/tests/func-tests/tuningpolicy_test.go index c0dd68382..e362a29ba 100644 --- a/tests/func-tests/tuningpolicy_test.go +++ b/tests/func-tests/tuningpolicy_test.go @@ -21,15 +21,13 @@ var _ = Describe("Check that the TuningPolicy annotation is configuring the KV o tests.FlagParse() var ( cli client.Client - ctx context.Context ) BeforeEach(func() { cli = tests.GetControllerRuntimeClient() - ctx = context.Background() }) - AfterEach(func() { + AfterEach(func(ctx context.Context) { hc := tests.GetHCO(ctx, cli) delete(hc.Annotations, common.TuningPolicyAnnotationName) @@ -38,7 +36,7 @@ var _ = Describe("Check that the TuningPolicy annotation is configuring the KV o tests.UpdateHCORetry(ctx, cli, hc) }) - It("should update KV with the tuningPolicy annotation", func() { + It("should update KV with the tuningPolicy annotation", func(ctx context.Context) { hc := tests.GetHCO(ctx, cli) if hc.Annotations == nil { @@ -57,7 +55,7 @@ var _ = Describe("Check that the TuningPolicy annotation is configuring the KV o checkTuningPolicy(ctx, cli, expected) }) - It("should update KV with the highBurst tuningPolicy", func() { + It("should update KV with the highBurst tuningPolicy", func(ctx context.Context) { hc := tests.GetHCO(ctx, cli) delete(hc.Annotations, common.TuningPolicyAnnotationName) @@ -75,7 +73,7 @@ var _ = Describe("Check that the TuningPolicy annotation is configuring the KV o }) func checkTuningPolicy(ctx context.Context, cli client.Client, expected kvv1.TokenBucketRateLimiter) { - Eventually(func(g Gomega) { + Eventually(func(g Gomega, ctx context.Context) { kv := &kvv1.KubeVirt{ ObjectMeta: metav1.ObjectMeta{ Name: "kubevirt-kubevirt-hyperconverged", @@ -90,7 +88,7 @@ func checkTuningPolicy(ctx context.Context, cli client.Client, expected kvv1.Tok checkReloadableComponentConfiguration(g, kv.Spec.Configuration.ControllerConfiguration, expected) checkReloadableComponentConfiguration(g, kv.Spec.Configuration.HandlerConfiguration, expected) checkReloadableComponentConfiguration(g, kv.Spec.Configuration.WebhookConfiguration, expected) - }).WithTimeout(time.Minute * 2).WithPolling(time.Second).Should(Succeed()) + }).WithTimeout(time.Minute * 2).WithPolling(time.Second).WithContext(ctx).Should(Succeed()) } diff --git a/tests/func-tests/update_priority_class_test.go b/tests/func-tests/update_priority_class_test.go index d41f86bdc..1cc5414ab 100644 --- a/tests/func-tests/update_priority_class_test.go +++ b/tests/func-tests/update_priority_class_test.go @@ -20,29 +20,16 @@ var _ = Describe("check update priorityClass", Ordered, Serial, func() { var ( cli client.Client cliSet *kubernetes.Clientset - ctx context.Context oldPriorityClassUID types.UID ) tests.FlagParse() - getPriorityClassHCORef := func() types.UID { - hc := tests.GetHCO(ctx, cli) - - for _, obj := range hc.Status.RelatedObjects { - if obj.Kind == "PriorityClass" && obj.Name == priorityClassName { - return obj.UID - } - } - return "" - } - - BeforeAll(func() { + BeforeAll(func(ctx context.Context) { var err error cli = tests.GetControllerRuntimeClient() cliSet = tests.GetK8sClientSet() - ctx = context.Background() pc, err := cliSet.SchedulingV1().PriorityClasses().Get(ctx, priorityClassName, metav1.GetOptions{}) Expect(err).ToNot(HaveOccurred()) @@ -50,23 +37,23 @@ var _ = Describe("check update priorityClass", Ordered, Serial, func() { oldPriorityClassUID = pc.UID }) - It("should have the right reference for the priorityClass in the HyperConverged CR", func() { - uid := getPriorityClassHCORef() + It("should have the right reference for the priorityClass in the HyperConverged CR", func(ctx context.Context) { + uid := getPriorityClassHCORef(ctx, cli) Expect(uid).To(Equal(oldPriorityClassUID)) }) - It("should recreate the priorityClass on update", func() { + It("should recreate the priorityClass on update", func(ctx context.Context) { GinkgoWriter.Printf("oldPriorityClassUID: %q\n", oldPriorityClassUID) // `~1` is the jsonpatch escapoe sequence for `\` patch := []byte(`[{"op": "replace", "path": "/metadata/labels/app.kubernetes.io~1managed-by", "value": "test"}]`) - Eventually(func() error { + Eventually(func(ctx context.Context) error { _, err := cliSet.SchedulingV1().PriorityClasses().Patch(ctx, priorityClassName, types.JSONPatchType, patch, metav1.PatchOptions{}) return err - }).WithTimeout(time.Second * 5).WithPolling(time.Millisecond * 100).Should(Succeed()) + }).WithTimeout(time.Second * 5).WithPolling(time.Millisecond * 100).WithContext(ctx).Should(Succeed()) var newUID types.UID - Eventually(func(g Gomega) { + Eventually(func(g Gomega, ctx context.Context) { By("make sure a new priority class was created, by checking its UID") pc, err := cliSet.SchedulingV1().PriorityClasses().Get(ctx, priorityClassName, metav1.GetOptions{}) g.Expect(err).ToNot(HaveOccurred()) @@ -76,12 +63,27 @@ var _ = Describe("check update priorityClass", Ordered, Serial, func() { g.Expect(pc.GetLabels()).ToNot(HaveKey("test")) }).WithTimeout(30 * time.Second). WithPolling(100 * time.Millisecond). + WithContext(ctx). Should(Succeed()) GinkgoWriter.Printf("oldPriorityClassUID: %q; newUID: %q\n", oldPriorityClassUID, newUID) - Eventually(getPriorityClassHCORef). + Eventually(func(ctx context.Context) types.UID { + return getPriorityClassHCORef(ctx, cli) + }). WithTimeout(5 * time.Minute). WithPolling(time.Second). + WithContext(ctx). Should(And(Not(BeEmpty()), Equal(newUID))) }) }) + +func getPriorityClassHCORef(ctx context.Context, cli client.Client) types.UID { + hc := tests.GetHCO(ctx, cli) + + for _, obj := range hc.Status.RelatedObjects { + if obj.Kind == "PriorityClass" && obj.Name == priorityClassName { + return obj.UID + } + } + return "" +} diff --git a/tests/func-tests/utils.go b/tests/func-tests/utils.go index 806ffe4e5..3c6de3a0c 100644 --- a/tests/func-tests/utils.go +++ b/tests/func-tests/utils.go @@ -4,7 +4,6 @@ import ( "context" "errors" "flag" - "fmt" "sync" "time" @@ -47,9 +46,8 @@ func FlagParse() { flag.Parse() } -func BeforeEach() { +func BeforeEach(ctx context.Context) { cli := GetK8sClientSet().RESTClient() - ctx := context.Background() deleteAllResources(ctx, cli, "virtualmachines") deleteAllResources(ctx, cli, "virtualmachineinstances") @@ -58,11 +56,11 @@ func BeforeEach() { func FailIfNotOpenShift(ctx context.Context, cli client.Client, testName string) { isOpenShift := false - Eventually(func() error { + Eventually(func(ctx context.Context) error { var err error isOpenShift, err = IsOpenShift(ctx, cli) return err - }).WithTimeout(10*time.Second).WithPolling(time.Second).Should(Succeed(), "failed to check if running on an openshift cluster") + }).WithTimeout(10*time.Second).WithPolling(time.Second).WithContext(ctx).Should(Succeed(), "failed to check if running on an openshift cluster") ExpectWithOffset(1, isOpenShift).To(BeTrue(), `the %q test must run on openshift cluster. Use the "!%s" label filter in order to skip this test`, testName, OpenshiftLabel) } @@ -107,8 +105,6 @@ func (c *cacheIsOpenShift) IsOpenShift(ctx context.Context, cli client.Client) ( return c.isOpenShift, nil } - fmt.Printf("err: %v, %t\n", err, err) - return false, err } @@ -143,7 +139,7 @@ func UpdateHCORetry(ctx context.Context, cli client.Client, input *v1beta1.Hyper var output *v1beta1.HyperConverged var err error - Eventually(func() error { + Eventually(func(ctx context.Context) error { hco := GetHCO(ctx, cli) input.Spec.DeepCopyInto(&hco.Spec) hco.ObjectMeta.Annotations = input.ObjectMeta.Annotations @@ -152,7 +148,7 @@ func UpdateHCORetry(ctx context.Context, cli client.Client, input *v1beta1.Hyper output, err = UpdateHCO(ctx, cli, hco) return err - }, 10*time.Second, time.Second).Should(Succeed()) + }).WithTimeout(10 * time.Second).WithPolling(time.Second).WithContext(ctx).Should(Succeed()) return output } @@ -194,11 +190,13 @@ func PatchHCO(ctx context.Context, cli client.Client, patchBytes []byte) error { } func RestoreDefaults(ctx context.Context, cli client.Client) { - Eventually(PatchHCO). - WithArguments(ctx, cli, []byte(`[{"op": "replace", "path": "/spec", "value": {}}]`)). + Eventually(func(ctx context.Context) error { + return PatchHCO(ctx, cli, []byte(`[{"op": "replace", "path": "/spec", "value": {}}]`)) + }). WithOffset(1). WithTimeout(time.Second * 5). WithPolling(time.Millisecond * 100). + WithContext(ctx). Should(Succeed()) } diff --git a/tests/func-tests/validation_test.go b/tests/func-tests/validation_test.go index 06b610c6f..104012644 100644 --- a/tests/func-tests/validation_test.go +++ b/tests/func-tests/validation_test.go @@ -19,32 +19,29 @@ import ( var _ = Describe("Check CR validation", Label("validation"), Serial, func() { var ( cli client.Client - ctx context.Context ) - BeforeEach(func() { + BeforeEach(func(ctx context.Context) { cli = tests.GetControllerRuntimeClient() - ctx = context.Background() - tests.RestoreDefaults(ctx, cli) }) Context("for AutoCPULimitNamespaceLabelSelector", func() { - DescribeTable("should", func(allocationRatio *int, outcome gomegatypes.GomegaMatcher) { + DescribeTable("should", func(ctx context.Context, allocationRatio *int, outcome gomegatypes.GomegaMatcher) { requirements := &v1beta1.OperandResourceRequirements{ VmiCPUAllocationRatio: allocationRatio, AutoCPULimitNamespaceLabelSelector: &metav1.LabelSelector{ MatchLabels: map[string]string{"someLabel": "true"}, }, } - Eventually(func() error { + Eventually(func(ctx context.Context) error { var err error hc := tests.GetHCO(ctx, cli) hc.Spec.ResourceRequirements = requirements _, err = tests.UpdateHCO(ctx, cli, hc) return err - }).WithTimeout(10 * time.Second).WithPolling(500 * time.Millisecond).Should(outcome) + }).WithTimeout(10 * time.Second).WithPolling(500 * time.Millisecond).WithContext(ctx).Should(outcome) }, Entry("succeed when VMI CPU allocation is nil", nil, Succeed()), Entry("fail when VMI CPU allocation is 1", ptr.To(1), MatchError(ContainSubstring("Automatic CPU limits are incompatible with a VMI CPU allocation ratio of 1"))), diff --git a/tests/func-tests/virtual_machines_test.go b/tests/func-tests/virtual_machines_test.go index 882590e6d..92e527fec 100644 --- a/tests/func-tests/virtual_machines_test.go +++ b/tests/func-tests/virtual_machines_test.go @@ -29,16 +29,14 @@ var _ = Describe("[rfe_id:273][crit:critical][vendor:cnv-qe@redhat.com][level:sy var ( cli client.Client - ctx context.Context ) - BeforeEach(func() { + BeforeEach(func(ctx context.Context) { cli = tests.GetControllerRuntimeClient() - ctx = context.Background() - tests.BeforeEach() + tests.BeforeEach(ctx) }) - It("[test_id:5696] should create, verify and delete VMIs", Label("test_id:5696"), func() { + It("[test_id:5696] should create, verify and delete VMIs", Label("test_id:5696"), func(ctx context.Context) { vmiName := verifyVMICreation(ctx, cli) verifyVMIRunning(ctx, cli, vmiName) verifyVMIDeletion(ctx, cli, vmiName) @@ -68,14 +66,14 @@ func verifyVMICreation(ctx context.Context, cli client.Client) string { func verifyVMIRunning(ctx context.Context, cli client.Client, vmiName string) *kubevirtcorev1.VirtualMachineInstance { By("Verifying VMI is running") var vmi *kubevirtcorev1.VirtualMachineInstance - EventuallyWithOffset(1, func(g Gomega) kubevirtcorev1.VirtualMachineInstancePhase { + EventuallyWithOffset(1, func(g Gomega, ctx context.Context) kubevirtcorev1.VirtualMachineInstancePhase { vmi = createVMIObject(vmiName) g.Expect(cli.Get(ctx, client.ObjectKeyFromObject(vmi), vmi)).To(Succeed()) Expect(vmi.Status.Phase).ToNot(Equal(kubevirtcorev1.Failed), "vmi scheduling failed: %s\n", vmi2JSON(vmi)) return vmi.Status.Phase - }).WithTimeout(timeout).WithPolling(pollingInterval).Should(Equal(kubevirtcorev1.Running), "failed to get the vmi Running") + }).WithTimeout(timeout).WithPolling(pollingInterval).WithContext(ctx).Should(Equal(kubevirtcorev1.Running), "failed to get the vmi Running") return vmi } @@ -84,9 +82,9 @@ func verifyVMIDeletion(ctx context.Context, cli client.Client, vmiName string) { By("Verifying node placement of VMI") vmi := createVMIObject(vmiName) - EventuallyWithOffset(1, func() error { + EventuallyWithOffset(1, func(ctx context.Context) error { return cli.Delete(ctx, vmi) - }).WithTimeout(timeout).WithPolling(pollingInterval).Should(Succeed(), "failed to delete a vmi") + }).WithTimeout(timeout).WithPolling(pollingInterval).WithContext(ctx).Should(Succeed(), "failed to delete a vmi") } func vmi2JSON(vmi *kubevirtcorev1.VirtualMachineInstance) string {