diff --git a/tests/func-tests/aaq_test.go b/tests/func-tests/aaq_test.go index 8440d1c1a..c0333cffd 100644 --- a/tests/func-tests/aaq_test.go +++ b/tests/func-tests/aaq_test.go @@ -19,6 +19,7 @@ import ( "kubevirt.io/kubevirt/tests/flags" hcoutil "github.com/kubevirt/hyperconverged-cluster-operator/pkg/util" + tests "github.com/kubevirt/hyperconverged-cluster-operator/tests/func-tests" ) @@ -30,39 +31,36 @@ var _ = Describe("Test AAQ", Label("AAQ"), Serial, Ordered, func() { tests.FlagParse() var ( cli kubecli.KubevirtClient - ctx context.Context ) - BeforeEach(func() { + BeforeEach(func(ctx context.Context) { var err error cli, err = kubecli.GetKubevirtClient() Expect(cli).ToNot(BeNil()) Expect(err).ToNot(HaveOccurred()) - ctx = context.Background() - disableAAQFeatureGate(ctx, cli) }) - AfterAll(func() { + AfterAll(func(ctx context.Context) { disableAAQFeatureGate(ctx, cli) }) 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, cli) By("check the AAQ CR") - Eventually(func(g Gomega) bool { + Eventually(func(g Gomega, ctx context.Context) bool { aaq := getAAQ(ctx, cli, g) 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, err := cli.AppsV1().Deployments(flags.KubeVirtInstallNamespace).List(ctx, metav1.ListOptions{LabelSelector: "app.kubernetes.io/managed-by=aaq-operator"}) g.Expect(err).ToNot(HaveOccurred()) g.Expect(deps.Items).To(HaveLen(2)) @@ -78,6 +76,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()) }) }) @@ -110,21 +109,24 @@ func disableAAQFeatureGate(ctx context.Context, cli kubecli.KubevirtClient) { setAAQFeatureGate(ctx, cli, false) By("make sure the AAQ CR was removed") - Eventually(func() error { + Eventually(func(ctx context.Context) error { _, err := getAAQResource(ctx, cli) return err }).WithTimeout(5 * time.Minute). WithPolling(100 * time.Millisecond). WithOffset(1). + WithContext(ctx). Should(MatchError(errors.IsNotFound, "not found error")) } func setAAQFeatureGate(ctx context.Context, cli kubecli.KubevirtClient, fgState bool) { patch := []byte(fmt.Sprintf(setAAQFGPatchTemplate, fgState)) - Eventually(tests.PatchHCO). - WithArguments(ctx, cli, patch). + Eventually(func(ctx context.Context) error { + return tests.PatchHCO(ctx, cli, patch) + }). 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 4134d4a50..e01fdaf87 100644 --- a/tests/func-tests/cli_download_test.go +++ b/tests/func-tests/cli_download_test.go @@ -22,17 +22,17 @@ var _ = Describe("[rfe_id:5100][crit:medium][vendor:cnv-qe@redhat.com][level:sys flag.Parse() var cli kubecli.KubevirtClient - BeforeEach(func() { + BeforeEach(func(ctx context.Context) { tests.BeforeEach() virtCli, err := kubecli.GetKubevirtClient() Expect(err).ToNot(HaveOccurred()) cli, err = kubecli.GetKubevirtClientFromRESTConfig(virtCli.Config()) Expect(err).ToNot(HaveOccurred()) - tests.FailIfNotOpenShift(cli, "ConsoleCliDownload") + 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") s := scheme.Scheme _ = consolev1.Install(s) @@ -44,7 +44,7 @@ var _ = Describe("[rfe_id:5100][crit:medium][vendor:cnv-qe@redhat.com][level:sys Name("virtctl-clidownloads-kubevirt-hyperconverged"). AbsPath("/apis", consolev1.GroupVersion.Group, consolev1.GroupVersion.Version). Timeout(10*time.Second). - Do(context.TODO()).Into(&ccd)).To(Succeed()) + Do(ctx).Into(&ccd)).To(Succeed()) ExpectWithOffset(1, ccd.Spec.Links).Should(HaveLen(6)) diff --git a/tests/func-tests/cluster_eviction_strategy_test.go b/tests/func-tests/cluster_eviction_strategy_test.go index 37e129388..efa625935 100644 --- a/tests/func-tests/cluster_eviction_strategy_test.go +++ b/tests/func-tests/cluster_eviction_strategy_test.go @@ -16,20 +16,19 @@ import ( var _ = Describe("Cluster level evictionStrategy default value", Serial, Ordered, func() { tests.FlagParse() var cli kubecli.KubevirtClient - ctx := context.TODO() var ( initialEvictionStrategy *v1.EvictionStrategy singleWorkerCluster bool ) - BeforeEach(func() { + BeforeEach(func(ctx context.Context) { var err error cli, err = kubecli.GetKubevirtClient() Expect(cli).ToNot(BeNil()) Expect(err).ToNot(HaveOccurred()) - singleWorkerCluster, err = isSingleWorkerCluster(cli) + singleWorkerCluster, err = isSingleWorkerCluster(ctx, cli) Expect(err).ToNot(HaveOccurred()) tests.BeforeEach() @@ -37,13 +36,13 @@ var _ = Describe("Cluster level evictionStrategy default value", Serial, Ordered 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 +53,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 @@ -66,8 +65,8 @@ var _ = Describe("Cluster level evictionStrategy default value", Serial, Ordered }) -func isSingleWorkerCluster(cli kubecli.KubevirtClient) (bool, error) { - workerNodes, err := cli.CoreV1().Nodes().List(context.TODO(), k8smetav1.ListOptions{LabelSelector: "node-role.kubernetes.io/worker"}) +func isSingleWorkerCluster(ctx context.Context, cli kubecli.KubevirtClient) (bool, error) { + workerNodes, err := cli.CoreV1().Nodes().List(ctx, k8smetav1.ListOptions{LabelSelector: "node-role.kubernetes.io/worker"}) if err != nil { return false, err } diff --git a/tests/func-tests/console_plugin_test.go b/tests/func-tests/console_plugin_test.go index 1273b679e..d0b3a1980 100644 --- a/tests/func-tests/console_plugin_test.go +++ b/tests/func-tests/console_plugin_test.go @@ -32,7 +32,6 @@ const ( var _ = Describe("kubevirt console plugin", Label(tests.OpenshiftLabel), func() { var ( cli kubecli.KubevirtClient - ctx context.Context expectedKubevirtConsolePluginName = "kubevirt-plugin" consoleGVR = schema.GroupVersionResource{ Group: "console.openshift.io", @@ -43,23 +42,22 @@ var _ = Describe("kubevirt console plugin", Label(tests.OpenshiftLabel), func() tests.FlagParse() - BeforeEach(func() { + BeforeEach(func(ctx context.Context) { var err error cli, err = kubecli.GetKubevirtClient() Expect(err).ToNot(HaveOccurred()) - tests.FailIfNotOpenShift(cli, "kubevirt console plugin") - ctx = context.Background() + tests.FailIfNotOpenShift(ctx, cli, "kubevirt console plugin") hco := tests.GetHCO(ctx, cli) originalInfra := hco.Spec.Infra - 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) { unstructured, err := cli.DynamicClient().Resource(consoleGVR).Get(ctx, expectedKubevirtConsolePluginName, metav1.GetOptions{}) Expect(err).ToNot(HaveOccurred()) @@ -94,7 +92,7 @@ var _ = Describe("kubevirt console plugin", Label(tests.OpenshiftLabel), func() 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", @@ -104,52 +102,58 @@ var _ = Describe("kubevirt console plugin", Label(tests.OpenshiftLabel), func() 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, err := cli.AppsV1().Deployments(flags.KubeVirtInstallNamespace).Get(ctx, string(hcoutil.AppComponentUIPlugin), metav1.GetOptions{}) g.Expect(err).ToNot(HaveOccurred()) 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, err := cli.AppsV1().Deployments(flags.KubeVirtInstallNamespace).Get(ctx, string(hcoutil.AppComponentUIProxy), metav1.GetOptions{}) g.Expect(err).ToNot(HaveOccurred()) 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, err := cli.AppsV1().Deployments(flags.KubeVirtInstallNamespace).Get(ctx, string(hcoutil.AppComponentUIPlugin), metav1.GetOptions{}) g.Expect(err).ToNot(HaveOccurred()) 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, err := cli.AppsV1().Deployments(flags.KubeVirtInstallNamespace).Get(ctx, string(hcoutil.AppComponentUIProxy), metav1.GetOptions{}) g.Expect(err).ToNot(HaveOccurred()) 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 9b4c548e3..c61141ac8 100644 --- a/tests/func-tests/dashboard_test.go +++ b/tests/func-tests/dashboard_test.go @@ -20,19 +20,19 @@ var _ = Describe("[rfe_id:5108][crit:medium][vendor:cnv-qe@redhat.com][level:sys var cli kubecli.KubevirtClient - BeforeEach(func() { + BeforeEach(func(ctx context.Context) { tests.BeforeEach() virtCli, err := kubecli.GetKubevirtClient() Expect(err).ToNot(HaveOccurred()) - tests.FailIfNotOpenShift(virtCli, "Dashboard configmaps") + tests.FailIfNotOpenShift(ctx, virtCli, "Dashboard configmaps") cli, err = kubecli.GetKubevirtClientFromRESTConfig(virtCli.Config()) Expect(err).ToNot(HaveOccurred()) }) - 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") s := scheme.Scheme _ = consolev1.Install(s) @@ -45,7 +45,7 @@ var _ = Describe("[rfe_id:5108][crit:medium][vendor:cnv-qe@redhat.com][level:sys } for _, item := range items { - cm, err := cli.CoreV1().ConfigMaps(item.Namespace).Get(context.TODO(), item.Name, v1.GetOptions{}) + cm, err := cli.CoreV1().ConfigMaps(item.Namespace).Get(ctx, item.Name, v1.GetOptions{}) ExpectWithOffset(1, err).ToNot(HaveOccurred()) for _, key := range item.Keys { _, ok := cm.Data[key] diff --git a/tests/func-tests/defaults_test.go b/tests/func-tests/defaults_test.go index c84ff0b33..d1dbb8c3c 100644 --- a/tests/func-tests/defaults_test.go +++ b/tests/func-tests/defaults_test.go @@ -14,6 +14,7 @@ import ( "kubevirt.io/client-go/kubecli" "github.com/kubevirt/hyperconverged-cluster-operator/api/v1beta1" + tests "github.com/kubevirt/hyperconverged-cluster-operator/tests/func-tests" ) @@ -24,18 +25,15 @@ const ( var _ = Describe("Check Default values", Label("defaults"), Serial, func() { var ( cli kubecli.KubevirtClient - ctx context.Context ) - BeforeEach(func() { + BeforeEach(func(ctx context.Context) { var err error cli, err = kubecli.GetKubevirtClient() Expect(cli).ToNot(BeNil()) Expect(err).ToNot(HaveOccurred()) - ctx = context.Background() - tests.RestoreDefaults(ctx, cli) }) @@ -51,16 +49,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"), @@ -90,16 +88,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"), @@ -128,16 +126,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"), @@ -155,16 +153,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"), @@ -179,16 +177,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"), @@ -201,16 +199,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"), @@ -223,16 +221,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"), @@ -246,16 +244,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 835505737..91ff8ac79 100644 --- a/tests/func-tests/dependency_objects_test.go +++ b/tests/func-tests/dependency_objects_test.go @@ -27,10 +27,10 @@ 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) { virtCli, err := kubecli.GetKubevirtClient() Expect(err).ToNot(HaveOccurred()) - _, err = virtCli.SchedulingV1().PriorityClasses().Get(context.TODO(), priorityClassName, v1.GetOptions{}) + _, err = virtCli.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 4911a2ed1..f00be7c67 100644 --- a/tests/func-tests/golden_image_test.go +++ b/tests/func-tests/golden_image_test.go @@ -68,7 +68,6 @@ var ( var _ = Describe("golden image test", Label("data-import-cron"), Serial, Ordered, Label(tests.OpenshiftLabel), func() { var ( cli kubecli.KubevirtClient - ctx context.Context ) tests.FlagParse() @@ -90,14 +89,12 @@ var _ = Describe("golden image test", Label("data-import-cron"), Serial, Ordered expectedImageStreams = expectedISFromConfig } - BeforeEach(func() { + BeforeEach(func(ctx context.Context) { var err error cli, err = kubecli.GetKubevirtClient() Expect(err).ToNot(HaveOccurred()) - tests.FailIfNotOpenShift(cli, "golden image test") - - ctx = context.Background() + tests.FailIfNotOpenShift(ctx, cli, "golden image test") }) Context("test image-streams", func() { @@ -106,7 +103,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) { unstructured, err := cli.DynamicClient().Resource(isGVR).Namespace(imageNamespace).Get(ctx, expectedIS.Name, metav1.GetOptions{}) Expect(err).ToNot(HaveOccurred()) @@ -120,7 +117,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 := &v1.ImageStream{} unstructured, err := cli.DynamicClient().Resource(isGVR).Namespace(imageNamespace).Get(ctx, expectedIS.Name, metav1.GetOptions{}) Expect(err).ToNot(HaveOccurred()) @@ -130,32 +127,32 @@ var _ = Describe("golden image test", Label("data-import-cron"), Serial, Ordered Expect(expectedValue).ToNot(Equal("wrongValue")) patchOp := []byte(`[{"op": "replace", "path": "/metadata/labels/app.kubernetes.io~1part-of", "value": "wrong-value"}]`) - Eventually(func() error { + Eventually(func(ctx context.Context) error { _, err := cli.DynamicClient().Resource(isGVR).Namespace(imageNamespace).Patch(ctx, expectedIS.Name, types.JSONPatchType, patchOp, 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()) is = &v1.ImageStream{} - Eventually(func(g Gomega) string { + Eventually(func(g Gomega, ctx context.Context) string { unstructured, err := cli.DynamicClient().Resource(isGVR).Namespace(imageNamespace).Get(ctx, expectedIS.Name, metav1.GetOptions{}) g.Expect(err).ToNot(HaveOccurred()) g.Expect(runtime.DefaultUnstructuredConverter.FromUnstructured(unstructured.Object, is)).To(Succeed()) 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 { unstructured, err := cli.DynamicClient().Resource(sspGVR).Namespace(flags.KubeVirtInstallNamespace).Get(ctx, "ssp-kubevirt-hyperconverged", metav1.GetOptions{}) g.Expect(err).ToNot(HaveOccurred()) @@ -170,11 +167,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))) @@ -186,11 +183,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 { unstructured, err := cli.DynamicClient().Resource(dicGVR).Namespace(imageNamespace).List(ctx, metav1.ListOptions{}) g.Expect(err).ToNot(HaveOccurred()) @@ -209,7 +206,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)) }) }) @@ -221,7 +218,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{} unstructured, err := cli.DynamicClient().Resource(dicGVR).Namespace(imageNamespace).Get(ctx, imageName, metav1.GetOptions{}) Expect(err).ToNot(HaveOccurred()) @@ -235,9 +232,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 @@ -246,46 +245,48 @@ 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 { _, err := cli.DynamicClient().Resource(isGVR).Namespace(imageNamespace).Get(ctx, expectedIS.Name, metav1.GetOptions{}) return err - }).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 { unstructured, err := cli.DynamicClient().Resource(sspGVR).Namespace(flags.KubeVirtInstallNamespace).Get(ctx, "ssp-kubevirt-hyperconverged", metav1.GetOptions{}) g.Expect(err).ToNot(HaveOccurred()) ssp := &v1beta2.SSP{} g.Expect(runtime.DefaultUnstructuredConverter.FromUnstructured(unstructured.Object, ssp)).To(Succeed()) 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() { + It("should have no images", func(ctx context.Context) { - Eventually(func(g Gomega) []unstructured.Unstructured { + Eventually(func(g Gomega, ctx context.Context) []unstructured.Unstructured { list, err := cli.DynamicClient().Resource(dicGVR).Namespace(imageNamespace).List(ctx, metav1.ListOptions{}) g.Expect(err).ToNot(HaveOccurred()) return list.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 @@ -294,45 +295,45 @@ 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 { _, err := cli.DynamicClient().Resource(isGVR).Namespace(imageNamespace).Get(ctx, expectedIS.Name, metav1.GetOptions{}) return err - }).WithTimeout(5 * time.Second).WithPolling(100 * time.Millisecond).ShouldNot(HaveOccurred()) + }).WithTimeout(5 * time.Second).WithPolling(100 * time.Millisecond).WithContext(ctx).Should(Succeed()) }, 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 { unstructured, err := cli.DynamicClient().Resource(sspGVR).Namespace(flags.KubeVirtInstallNamespace).Get(ctx, "ssp-kubevirt-hyperconverged", metav1.GetOptions{}) g.Expect(err).ToNot(HaveOccurred()) ssp := &v1beta2.SSP{} g.Expect(runtime.DefaultUnstructuredConverter.FromUnstructured(unstructured.Object, ssp)).To(Succeed()) 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) []unstructured.Unstructured { + It("should restore all the DataImportCron resources", func(ctx context.Context) { + Eventually(func(g Gomega, ctx context.Context) []unstructured.Unstructured { list, err := cli.DynamicClient().Resource(dicGVR).Namespace(imageNamespace).List(ctx, metav1.ListOptions{}) g.Expect(err).ToNot(HaveOccurred()) return list.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 @@ -344,11 +345,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{ @@ -360,11 +361,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{ @@ -380,7 +381,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 280a236fb..c77dd9604 100644 --- a/tests/func-tests/labels_test.go +++ b/tests/func-tests/labels_test.go @@ -25,18 +25,15 @@ var _ = Describe("Check that all the sub-resources have the required labels", La tests.FlagParse() var ( cli kubecli.KubevirtClient - ctx context.Context ) BeforeEach(func() { var err error cli, err = kubecli.GetKubevirtClient() Expect(err).ToNot(HaveOccurred()) - - 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 kv_name = "kubevirt-kubevirt-hyperconverged" @@ -47,16 +44,16 @@ var _ = Describe("Check that all the sub-resources have the required labels", La expectedVersion := kv.Labels[hcoutil.AppLabelVersion] patch := []byte(`[{"op": "remove", "path": "/metadata/labels/app.kubernetes.io~1version"}]`) - Eventually(func() error { + Eventually(func(ctx context.Context) error { _, err := cli.KubeVirt(hc.Namespace).Patch(kv_name, 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()) - Eventually(func(g Gomega) { + Eventually(func(g Gomega, ctx context.Context) { kv, err := cli.KubeVirt(hc.Namespace).Get(kv_name, &metav1.GetOptions{}) g.Expect(err).ToNot(HaveOccurred()) 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 9eddfef37..d7793424f 100644 --- a/tests/func-tests/main_test.go +++ b/tests/func-tests/main_test.go @@ -21,7 +21,7 @@ func TestTests(t *testing.T) { RunSpecs(t, "HyperConverged cluster E2E Test suite") } -var _ = BeforeSuite(func() { +var _ = BeforeSuite(func(ctx context.Context) { virtCli, err := kubecli.GetKubevirtClient() Expect(err).ToNot(HaveOccurred()) @@ -32,7 +32,7 @@ var _ = BeforeSuite(func() { }, } opt := metav1.CreateOptions{} - _, err = virtCli.CoreV1().Namespaces().Create(context.TODO(), ns, opt) + _, err = virtCli.CoreV1().Namespaces().Create(ctx, ns, opt) if !errors.IsAlreadyExists(err) { kvtutil.PanicOnError(err) } @@ -40,9 +40,9 @@ var _ = BeforeSuite(func() { tests.BeforeEach() }) -var _ = AfterSuite(func() { +var _ = AfterSuite(func(ctx context.Context) { virtCli, err := kubecli.GetKubevirtClient() Expect(err).ToNot(HaveOccurred()) opt := metav1.DeleteOptions{} - kvtutil.PanicOnError(virtCli.CoreV1().Namespaces().Delete(context.TODO(), kvtutil.NamespaceTestDefault, opt)) + kvtutil.PanicOnError(virtCli.CoreV1().Namespaces().Delete(ctx, kvtutil.NamespaceTestDefault, opt)) }) diff --git a/tests/func-tests/mediateddevices_mediateddevice_test.go b/tests/func-tests/mediateddevices_mediateddevice_test.go index af3b83925..b6a2eae8c 100644 --- a/tests/func-tests/mediateddevices_mediateddevice_test.go +++ b/tests/func-tests/mediateddevices_mediateddevice_test.go @@ -14,9 +14,10 @@ import ( "github.com/kubevirt/hyperconverged-cluster-operator/pkg/util" "github.com/kubevirt/hyperconverged-cluster-operator/api/v1beta1" - tests "github.com/kubevirt/hyperconverged-cluster-operator/tests/func-tests" "kubevirt.io/client-go/kubecli" + tests "github.com/kubevirt/hyperconverged-cluster-operator/tests/func-tests" + kubevirtcorev1 "kubevirt.io/api/core/v1" apiservererrors "k8s.io/apiserver/pkg/admission/plugin/webhook/errors" @@ -25,7 +26,6 @@ import ( var _ = Describe("MediatedDevicesTypes -> MediatedDeviceTypes", func() { tests.FlagParse() var cli kubecli.KubevirtClient - ctx := context.TODO() var initialMDC *v1beta1.MediatedDevicesConfiguration @@ -39,7 +39,7 @@ var _ = Describe("MediatedDevicesTypes -> MediatedDeviceTypes", func() { apiServerError.ErrStatus.APIVersion = "v1" apiServerError.ErrStatus.Kind = "Status" - BeforeEach(func() { + BeforeEach(func(ctx context.Context) { var err error cli, err = kubecli.GetKubevirtClient() Expect(cli).ToNot(BeNil()) @@ -52,31 +52,37 @@ var _ = Describe("MediatedDevicesTypes -> MediatedDeviceTypes", func() { } }) - 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 { kubevirt, err := cli.KubeVirt(flags.KubeVirtInstallNamespace).Get("kubevirt-kubevirt-hyperconverged", &metav1.GetOptions{}) - Expect(err).ToNot(HaveOccurred()) + g.Expect(err).ToNot(HaveOccurred()) return kubevirt.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 0450f62b6..0b466ffc5 100644 --- a/tests/func-tests/monitoring_test.go +++ b/tests/func-tests/monitoring_test.go @@ -45,19 +45,18 @@ var _ = Describe("[crit:high][vendor:cnv-qe@redhat.com][level:system]Monitoring" var promClient promApiv1.API var prometheusRule monitoringv1.PrometheusRule var initialOperatorHealthMetricValue float64 - ctx := context.TODO() runbookClient.Timeout = time.Second * 3 - BeforeEach(func() { + BeforeEach(func(ctx context.Context) { virtCli, err = kubecli.GetKubevirtClient() Expect(err).ToNot(HaveOccurred()) - tests.FailIfNotOpenShift(virtCli, "Prometheus") - promClient = initializePromClient(getPrometheusURL(virtCli), getAuthorizationTokenForPrometheus(virtCli)) - prometheusRule = getPrometheusRule(virtCli) + tests.FailIfNotOpenShift(ctx, virtCli, "Prometheus") + promClient = initializePromClient(getPrometheusURL(ctx, virtCli), getAuthorizationTokenForPrometheus(ctx, virtCli)) + prometheusRule = getPrometheusRule(ctx, virtCli) - 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() { @@ -93,7 +92,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" @@ -101,9 +100,9 @@ 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()) Eventually(func(g Gomega) []string { patch := []byte(fmt.Sprintf(`[{"op": "add", "path": "/spec/configuration/developerConfiguration/featureGates/-", "value": %q}]`, fakeFG)) @@ -114,21 +113,21 @@ var _ = Describe("[crit:high][vendor:cnv-qe@redhat.com][level:system]Monitoring" WithPolling(100 * time.Millisecond). Should(ContainElement(fakeFG)) - Eventually(func(g Gomega) float64 { - return getMetricValue(promClient, query) - }).WithTimeout(60 * time.Second).WithPolling(time.Second).Should(Equal(valueBefore + 1)) + 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 + 1)) - 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, "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, virtCli) @@ -137,13 +136,13 @@ var _ = Describe("[crit:high][vendor:cnv-qe@redhat.com][level:system]Monitoring" } tests.UpdateHCORetry(ctx, virtCli, 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) }) }) @@ -156,11 +155,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), @@ -169,11 +168,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) @@ -189,7 +188,7 @@ func getMetricValue(promClient promApiv1.API, metricName string) float64 { return metricValue } -func getPrometheusRule(client kubecli.KubevirtClient) monitoringv1.PrometheusRule { +func getPrometheusRule(ctx context.Context, client kubecli.KubevirtClient) monitoringv1.PrometheusRule { s := scheme.Scheme _ = monitoringv1.AddToScheme(s) s.AddKnownTypes(monitoringv1.SchemeGroupVersion) @@ -202,7 +201,7 @@ func getPrometheusRule(client kubecli.KubevirtClient) monitoringv1.PrometheusRul Namespace(flags.KubeVirtInstallNamespace). 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 } @@ -228,11 +227,11 @@ func initializePromClient(prometheusURL string, token string) promApiv1.API { return promClient } -func getAuthorizationTokenForPrometheus(cli kubecli.KubevirtClient) string { +func getAuthorizationTokenForPrometheus(ctx context.Context, cli kubecli.KubevirtClient) string { var token string - Eventually(func() bool { + Eventually(func(ctx context.Context) bool { treq, err := cli.CoreV1().ServiceAccounts("openshift-monitoring").CreateToken( - context.TODO(), + ctx, "prometheus-k8s", &authenticationv1.TokenRequest{ Spec: authenticationv1.TokenRequestSpec{ @@ -247,27 +246,28 @@ func getAuthorizationTokenForPrometheus(cli kubecli.KubevirtClient) string { } 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 kubecli.KubevirtClient) string { +func getPrometheusURL(ctx context.Context, cli kubecli.KubevirtClient) 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.RestClient().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 0d1af1bf0..db55be3c5 100644 --- a/tests/func-tests/node_placement_test.go +++ b/tests/func-tests/node_placement_test.go @@ -28,7 +28,6 @@ const ( ) var _ = Describe("[rfe_id:4356][crit:medium][vendor:cnv-qe@redhat.com][level:system]Node Placement", Ordered, Serial, Label(tests.HighlyAvailableClusterLabel), func() { - ctx := context.TODO() tests.FlagParse() hco := &hcov1beta1.HyperConverged{} var ( @@ -38,30 +37,30 @@ var _ = Describe("[rfe_id:4356][crit:medium][vendor:cnv-qe@redhat.com][level:sys cli kubecli.KubevirtClient ) - BeforeAll(func() { + BeforeAll(func(ctx context.Context) { var err error cli, err = kubecli.GetKubevirtClient() Expect(err).ToNot(HaveOccurred()) - nodes := listNodesByLabels(cli, "node-role.kubernetes.io/control-plane!=") + nodes := listNodesByLabels(ctx, cli, "node-role.kubernetes.io/control-plane!=") tests.FailIfSingleNode(len(nodes.Items) < 2) // 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(cli, &node, infra) + done, err := setHcoNodeTypeLabel(ctx, cli, &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) { - done, err := setHcoNodeTypeLabel(cli, &nodes.Items[len(nodes.Items)-1], workloads) + Eventually(func(g Gomega, ctx context.Context) { + done, err := setHcoNodeTypeLabel(ctx, cli, &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) @@ -86,7 +85,7 @@ var _ = Describe("[rfe_id:4356][crit:medium][vendor:cnv-qe@redhat.com][level:sys tests.UpdateHCORetry(ctx, cli, hco) - workloadsNodes := listNodesByLabels(cli, "node.kubernetes.io/hco-test-node-type==workloads") + workloadsNodes := listNodesByLabels(ctx, cli, "node.kubernetes.io/hco-test-node-type==workloads") Expect(workloadsNodes.Items).To(HaveLen(1)) workloadsNode = &workloadsNodes.Items[0] @@ -96,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) @@ -107,21 +106,21 @@ var _ = Describe("[rfe_id:4356][crit:medium][vendor:cnv-qe@redhat.com][level:sys tests.UpdateHCORetry(ctx, cli, hco) // unlabel the nodes - nodes := listNodesByLabels(cli, hcoLabel) + nodes := listNodesByLabels(ctx, cli, 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() delete(labels, hcoLabel) - n, err := cli.CoreV1().Nodes().Get(context.TODO(), n.Name, k8smetav1.GetOptions{}) + n, err := cli.CoreV1().Nodes().Get(ctx, n.Name, k8smetav1.GetOptions{}) g.Expect(err).ToNot(HaveOccurred()) n.SetLabels(labels) - _, err = cli.CoreV1().Nodes().Update(context.TODO(), n, k8smetav1.UpdateOptions{}) + _, err = cli.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() { @@ -129,7 +128,7 @@ var _ = Describe("[rfe_id:4356][crit:medium][vendor:cnv-qe@redhat.com][level:sys }) 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, @@ -139,7 +138,7 @@ var _ = Describe("[rfe_id:4356][crit:medium][vendor:cnv-qe@redhat.com][level:sys } By("Getting Network Addons Configs") - cnaoCR := getNetworkAddonsConfigs(cli) + cnaoCR := getNetworkAddonsConfigs(ctx, cli) if cnaoCR.Spec.Ovs == nil { delete(expectedWorkloadsPods, "ovs-cni-marker") } @@ -147,21 +146,21 @@ 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(g, cli, workloadsNode.Name) + pods := listPodsInNode(ctx, g, cli, workloadsNode.Name) By("Collecting nodes of pods") updatePodAssignments(pods, expectedWorkloadsPods, "workload", workloadsNode.Name) 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, @@ -172,13 +171,13 @@ 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(cli) + infraNodes := listInfraNodes(ctx, cli) for _, node := range infraNodes.Items { By("Listing pods in " + node.Name) - pods := listPodsInNode(g, cli, node.Name) + pods := listPodsInNode(ctx, g, cli, node.Name) By("Collecting nodes of pods") updatePodAssignments(pods, expectedInfraPods, "infra", node.Name) @@ -186,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()) }) }) }) @@ -216,8 +215,8 @@ func updatePodAssignments(pods []v1.Pod, podMap map[string]bool, nodeType string } } -func listPodsInNode(g Gomega, client kubecli.KubevirtClient, nodeName string) []v1.Pod { - pods, err := client.CoreV1().Pods(flags.KubeVirtInstallNamespace).List(context.TODO(), k8smetav1.ListOptions{ +func listPodsInNode(ctx context.Context, g Gomega, client kubecli.KubevirtClient, nodeName string) []v1.Pod { + pods, err := client.CoreV1().Pods(flags.KubeVirtInstallNamespace).List(ctx, k8smetav1.ListOptions{ FieldSelector: fmt.Sprintf("spec.nodeName=%s,status.phase=Running", nodeName), }) g.ExpectWithOffset(1, err).ToNot(HaveOccurred()) @@ -225,8 +224,8 @@ func listPodsInNode(g Gomega, client kubecli.KubevirtClient, nodeName string) [] return pods.Items } -func listInfraNodes(client kubecli.KubevirtClient) *v1.NodeList { - infraNodes, err := client.CoreV1().Nodes().List(context.TODO(), k8smetav1.ListOptions{ +func listInfraNodes(ctx context.Context, client kubecli.KubevirtClient) *v1.NodeList { + infraNodes, err := client.CoreV1().Nodes().List(ctx, k8smetav1.ListOptions{ LabelSelector: "node.kubernetes.io/hco-test-node-type==infra", }) ExpectWithOffset(1, err).ShouldNot(HaveOccurred()) @@ -234,7 +233,7 @@ func listInfraNodes(client kubecli.KubevirtClient) *v1.NodeList { return infraNodes } -func getNetworkAddonsConfigs(client kubecli.KubevirtClient) *networkaddonsv1.NetworkAddonsConfig { +func getNetworkAddonsConfigs(ctx context.Context, client kubecli.KubevirtClient) *networkaddonsv1.NetworkAddonsConfig { var cnaoCR networkaddonsv1.NetworkAddonsConfig s := scheme.Scheme @@ -246,35 +245,36 @@ func getNetworkAddonsConfigs(client kubecli.KubevirtClient) *networkaddonsv1.Net Name("cluster"). AbsPath("/apis", networkaddonsv1.GroupVersion.Group, networkaddonsv1.GroupVersion.Version). Timeout(10*time.Second). - Do(context.TODO()).Into(&cnaoCR)).To(Succeed()) + Do(ctx).Into(&cnaoCR)).To(Succeed()) return &cnaoCR } -func setHcoNodeTypeLabel(client kubecli.KubevirtClient, node *v1.Node, value string) (bool, error) { +func setHcoNodeTypeLabel(ctx context.Context, client kubecli.KubevirtClient, node *v1.Node, value string) (bool, error) { labels := node.GetLabels() labels[hcoLabel] = value - node, err := client.CoreV1().Nodes().Get(context.TODO(), node.Name, k8smetav1.GetOptions{}) + node, err := client.CoreV1().Nodes().Get(ctx, node.Name, k8smetav1.GetOptions{}) if err != nil { return false, err } node.SetLabels(labels) - _, err = client.CoreV1().Nodes().Update(context.TODO(), node, k8smetav1.UpdateOptions{}) + _, err = client.CoreV1().Nodes().Update(ctx, node, k8smetav1.UpdateOptions{}) if err != nil { return false, err } return true, nil } -func listNodesByLabels(cli kubecli.KubevirtClient, labelSelector string) *v1.NodeList { +func listNodesByLabels(ctx context.Context, cli kubecli.KubevirtClient, 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(context.TODO(), k8smetav1.ListOptions{LabelSelector: labelSelector}) + 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 645ccf4d0..4cdf1aec3 100644 --- a/tests/func-tests/quickstart_test.go +++ b/tests/func-tests/quickstart_test.go @@ -19,18 +19,18 @@ var _ = Describe("[rfe_id:5882][crit:high][vendor:cnv-qe@redhat.com][level:syste flag.Parse() var cli kubecli.KubevirtClient - BeforeEach(func() { + BeforeEach(func(ctx context.Context) { tests.BeforeEach() virtCli, err := kubecli.GetKubevirtClient() Expect(err).ToNot(HaveOccurred()) - tests.FailIfNotOpenShift(virtCli, "quickstart") + tests.FailIfNotOpenShift(ctx, virtCli, "quickstart") cli, err = kubecli.GetKubevirtClientFromRESTConfig(virtCli.Config()) Expect(err).ToNot(HaveOccurred()) }) - 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) @@ -50,7 +50,7 @@ var _ = Describe("[rfe_id:5882][crit:high][vendor:cnv-qe@redhat.com][level:syste Name(qs.Name). AbsPath("/apis", consolev1.GroupVersion.Group, consolev1.GroupVersion.Version). Timeout(10*time.Second). - Do(context.TODO()).Into(&cqs)).To(Succeed()) + Do(ctx).Into(&cqs)).To(Succeed()) ExpectWithOffset(1, cqs.Spec.DisplayName).Should(Equal(qs.DisplayName)) } diff --git a/tests/func-tests/tuningpolicy_test.go b/tests/func-tests/tuningpolicy_test.go index 9637733f2..1f60cc031 100644 --- a/tests/func-tests/tuningpolicy_test.go +++ b/tests/func-tests/tuningpolicy_test.go @@ -15,6 +15,7 @@ import ( "github.com/kubevirt/hyperconverged-cluster-operator/api/v1beta1" "github.com/kubevirt/hyperconverged-cluster-operator/controllers/common" + tests "github.com/kubevirt/hyperconverged-cluster-operator/tests/func-tests" ) @@ -22,7 +23,6 @@ var _ = Describe("Check that the TuningPolicy annotation is configuring the KV o tests.FlagParse() var ( cli kubecli.KubevirtClient - ctx context.Context ) BeforeEach(func() { @@ -30,11 +30,9 @@ var _ = Describe("Check that the TuningPolicy annotation is configuring the KV o cli, err = kubecli.GetKubevirtClient() Expect(cli).ToNot(BeNil()) Expect(err).ToNot(HaveOccurred()) - - ctx = context.Background() }) - AfterEach(func() { + AfterEach(func(ctx context.Context) { hc := tests.GetHCO(ctx, cli) delete(hc.Annotations, common.TuningPolicyAnnotationName) @@ -43,7 +41,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 { @@ -62,7 +60,7 @@ var _ = Describe("Check that the TuningPolicy annotation is configuring the KV o checkTuningPolicy(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) diff --git a/tests/func-tests/update_priority_class_test.go b/tests/func-tests/update_priority_class_test.go index ea8876935..408f941a0 100644 --- a/tests/func-tests/update_priority_class_test.go +++ b/tests/func-tests/update_priority_class_test.go @@ -19,29 +19,16 @@ const priorityClassName = "kubevirt-cluster-critical" var _ = Describe("check update priorityClass", Ordered, Serial, func() { var ( cli kubecli.KubevirtClient - 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, err = kubecli.GetKubevirtClient() Expect(err).ToNot(HaveOccurred()) - ctx = context.Background() pc, err := cli.SchedulingV1().PriorityClasses().Get(ctx, priorityClassName, metav1.GetOptions{}) Expect(err).ToNot(HaveOccurred()) @@ -49,23 +36,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 := cli.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 := cli.SchedulingV1().PriorityClasses().Get(ctx, priorityClassName, metav1.GetOptions{}) g.Expect(err).ToNot(HaveOccurred()) @@ -75,12 +62,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 kubecli.KubevirtClient) 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 70e57b00b..ec5ca6063 100644 --- a/tests/func-tests/utils.go +++ b/tests/func-tests/utils.go @@ -18,7 +18,6 @@ import ( "k8s.io/apimachinery/pkg/types" "k8s.io/client-go/kubernetes/scheme" "k8s.io/client-go/rest" - "k8s.io/utils/net" "kubevirt.io/client-go/kubecli" "kubevirt.io/kubevirt/tests/flags" @@ -61,13 +60,13 @@ func BeforeEach() { deleteAllResources(virtClient.CoreV1().RESTClient(), "persistentvolumeclaims") } -func FailIfNotOpenShift(cli kubecli.KubevirtClient, testName string) { +func FailIfNotOpenShift(ctx context.Context, cli kubecli.KubevirtClient, testName string) { isOpenShift := false - Eventually(func() error { + Eventually(func(ctx context.Context) error { var err error - isOpenShift, err = IsOpenShift(cli) + 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) } @@ -86,7 +85,7 @@ type cacheIsOpenShift struct { lock sync.Mutex } -func (c *cacheIsOpenShift) IsOpenShift(cli kubecli.KubevirtClient) (bool, error) { +func (c *cacheIsOpenShift) IsOpenShift(ctx context.Context, cli kubecli.KubevirtClient) (bool, error) { c.lock.Lock() defer c.lock.Unlock() @@ -109,7 +108,7 @@ func (c *cacheIsOpenShift) IsOpenShift(cli kubecli.KubevirtClient) (bool, error) Name("version"). AbsPath("/apis", openshiftconfigv1.GroupVersion.Group, openshiftconfigv1.GroupVersion.Version). Timeout(10 * time.Second). - Do(context.TODO()).Into(clusterVersion) + Do(ctx).Into(clusterVersion) if err == nil { c.isOpenShift = true @@ -126,53 +125,10 @@ func (c *cacheIsOpenShift) IsOpenShift(cli kubecli.KubevirtClient) (bool, error) return false, err } -func (c *cacheIsOpenShift) IsOpenShiftSingleStackIPv6(cli kubecli.KubevirtClient) (bool, error) { - // confirm we are on OpenShift - isOpenShift, err := c.IsOpenShift(cli) - if err != nil || !isOpenShift { - return false, err - } - - s := scheme.Scheme - _ = openshiftconfigv1.Install(s) - s.AddKnownTypes(openshiftconfigv1.GroupVersion) - - clusterNetwork := &openshiftconfigv1.Network{ - ObjectMeta: metav1.ObjectMeta{ - Name: "cluster", - }, - } - gvr := schema.GroupVersionResource{ - Group: openshiftconfigv1.GroupVersion.Group, - Version: openshiftconfigv1.GroupVersion.Version, - Resource: "networks", - } - - clustnet, err := cli.DynamicClient(). - Resource(gvr). - Get(context.TODO(), "cluster", metav1.GetOptions{}) - if err != nil { - return false, err - } - - err = runtime.DefaultUnstructuredConverter.FromUnstructured(clustnet.Object, clusterNetwork) - if err != nil { - return false, err - } - - cn := clusterNetwork.Status.ClusterNetwork - isSingleStackIPv6 := len(cn) == 1 && net.IsIPv6CIDRString(cn[0].CIDR) - return isSingleStackIPv6, nil -} - var isOpenShiftCache cacheIsOpenShift -func IsOpenShift(cli kubecli.KubevirtClient) (bool, error) { - return isOpenShiftCache.IsOpenShift(cli) -} - -func IsOpenShiftSingleStackIPv6(cli kubecli.KubevirtClient) (bool, error) { - return isOpenShiftCache.IsOpenShiftSingleStackIPv6(cli) +func IsOpenShift(ctx context.Context, cli kubecli.KubevirtClient) (bool, error) { + return isOpenShiftCache.IsOpenShift(ctx, cli) } // GetHCO reads the HCO CR from the APIServer with a DynamicClient @@ -199,7 +155,7 @@ func UpdateHCORetry(ctx context.Context, client kubecli.KubevirtClient, input *v var output *v1beta1.HyperConverged var err error - Eventually(func() error { + Eventually(func(ctx context.Context) error { hco := GetHCO(ctx, client) input.Spec.DeepCopyInto(&hco.Spec) hco.ObjectMeta.Annotations = input.ObjectMeta.Annotations @@ -208,7 +164,7 @@ func UpdateHCORetry(ctx context.Context, client kubecli.KubevirtClient, input *v output, err = UpdateHCO(ctx, client, hco) return err - }, 10*time.Second, time.Second).Should(Succeed()) + }).WithTimeout(10 * time.Second).WithPolling(time.Second).WithContext(ctx).Should(Succeed()) return output } @@ -255,11 +211,13 @@ func PatchHCO(ctx context.Context, cl kubecli.KubevirtClient, patch []byte) erro } func RestoreDefaults(ctx context.Context, cli kubecli.KubevirtClient) { - 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 f3a94ecf2..fa0a993dc 100644 --- a/tests/func-tests/validation_test.go +++ b/tests/func-tests/validation_test.go @@ -12,8 +12,9 @@ import ( metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "github.com/kubevirt/hyperconverged-cluster-operator/api/v1beta1" - tests "github.com/kubevirt/hyperconverged-cluster-operator/tests/func-tests" "kubevirt.io/client-go/kubecli" + + tests "github.com/kubevirt/hyperconverged-cluster-operator/tests/func-tests" ) var _ = Describe("Check CR validation", Label("validation"), Serial, func() { @@ -35,20 +36,20 @@ var _ = Describe("Check CR validation", Label("validation"), Serial, func() { }) 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"))),