From 343128b2cf6b0c7b4bedebd729a1e776a1b0fc5d Mon Sep 17 00:00:00 2001 From: Justin Kulikauskas <44813129+JustinKuli@users.noreply.github.com> Date: Fri, 17 May 2024 05:03:34 +0000 Subject: [PATCH] Add test toolkit and improve tests The test toolkit and courtesies are things that other policies could use in their tests. The remaining functions in the utils.go file are more specifically just for fakepolicy. In preparation for more tests, the existing tests have been moved into a separate package/suite. In particular, since some of them require very specific details in the cluster (exact namespaces, configmaps, and no extras), this lets them be run in a more isolated way. Signed-off-by: Justin Kulikauskas <44813129+JustinKuli@users.noreply.github.com> --- Makefile | 9 ++- pkg/testutils/courtesies.go | 15 ++++ pkg/testutils/toolkit.go | 76 +++++++++++++++++++ .../{ => basic}/namespaceselection_test.go | 16 ++-- .../fakepolicy/test/{ => basic}/suite_test.go | 11 ++- .../test/{ => basic}/target_test.go | 28 +++---- .../test/{ => basic}/validation_test.go | 12 +-- .../test/{ => basic}/yamlformat_test.go | 36 ++++----- .../testdata/empty-match-expressions.yaml | 0 .../testdata/empty-ns-selector.yaml | 0 .../{ => utils}/testdata/extra-field.yaml | 0 .../testdata/fakepolicy-sample.yaml | 0 .../test/{ => utils}/testdata/no-include.yaml | 0 .../{ => utils}/testdata/no-remediation.yaml | 0 .../{ => utils}/testdata/no-severity.yaml | 0 .../{ => utils}/testdata/req-selector.yaml | 0 .../test/{utils_test.go => utils/utils.go} | 40 +--------- 17 files changed, 160 insertions(+), 83 deletions(-) create mode 100644 pkg/testutils/courtesies.go create mode 100644 pkg/testutils/toolkit.go rename test/fakepolicy/test/{ => basic}/namespaceselection_test.go (93%) rename test/fakepolicy/test/{ => basic}/suite_test.go (86%) rename test/fakepolicy/test/{ => basic}/target_test.go (87%) rename test/fakepolicy/test/{ => basic}/validation_test.go (87%) rename test/fakepolicy/test/{ => basic}/yamlformat_test.go (77%) rename test/fakepolicy/test/{ => utils}/testdata/empty-match-expressions.yaml (100%) rename test/fakepolicy/test/{ => utils}/testdata/empty-ns-selector.yaml (100%) rename test/fakepolicy/test/{ => utils}/testdata/extra-field.yaml (100%) rename test/fakepolicy/test/{ => utils}/testdata/fakepolicy-sample.yaml (100%) rename test/fakepolicy/test/{ => utils}/testdata/no-include.yaml (100%) rename test/fakepolicy/test/{ => utils}/testdata/no-remediation.yaml (100%) rename test/fakepolicy/test/{ => utils}/testdata/no-severity.yaml (100%) rename test/fakepolicy/test/{ => utils}/testdata/req-selector.yaml (100%) rename test/fakepolicy/test/{utils_test.go => utils/utils.go} (57%) diff --git a/Makefile b/Makefile index d5f4625..2b23318 100644 --- a/Makefile +++ b/Makefile @@ -106,10 +106,17 @@ lint: $(GOLANGCI) ENVTEST_K8S_VERSION ?= 1.29 .PHONY: test -test: manifests generate $(GINKGO) $(ENVTEST) ## Run tests. +test: manifests generate $(GINKGO) $(ENVTEST) ## Run all the tests KUBEBUILDER_ASSETS="$(shell $(ENVTEST) use $(ENVTEST_K8S_VERSION) -p path)" $(GINKGO) \ --coverpkg=./... --covermode=count --coverprofile=cover.out ./... +test-unit: ## Run only the unit tests + go test --coverpkg=./... --covermode=count --coverprofile=cover-unit.out ./api/... ./pkg/... + +test-basicsuite: manifests generate $(GINKGO) $(ENVTEST) ## Run just the basic suite of tests + KUBEBUILDER_ASSETS="$(shell $(ENVTEST) use $(ENVTEST_K8S_VERSION) -p path)" $(GINKGO) \ + --coverpkg=./... --covermode=count --coverprofile=cover-basic.out ./test/fakepolicy/test/basic + .PHONY: fuzz-test fuzz-test: go test ./api/v1beta1 -fuzz=FuzzMatchesExcludeAll -fuzztime=20s diff --git a/pkg/testutils/courtesies.go b/pkg/testutils/courtesies.go new file mode 100644 index 0000000..797ebc1 --- /dev/null +++ b/pkg/testutils/courtesies.go @@ -0,0 +1,15 @@ +// Copyright Contributors to the Open Cluster Management project + +package testutils + +import ( + "k8s.io/apimachinery/pkg/types" + "sigs.k8s.io/controller-runtime/pkg/client" +) + +func ObjNN(obj client.Object) types.NamespacedName { + return types.NamespacedName{ + Namespace: obj.GetNamespace(), + Name: obj.GetName(), + } +} diff --git a/pkg/testutils/toolkit.go b/pkg/testutils/toolkit.go new file mode 100644 index 0000000..f8ded15 --- /dev/null +++ b/pkg/testutils/toolkit.go @@ -0,0 +1,76 @@ +// Copyright Contributors to the Open Cluster Management project + +package testutils + +import ( + "context" + "fmt" + + "github.com/onsi/ginkgo/v2" + "github.com/onsi/gomega" + gomegaTypes "github.com/onsi/gomega/types" + "k8s.io/apimachinery/pkg/api/errors" + "sigs.k8s.io/controller-runtime/pkg/client" +) + +type Toolkit struct { + client.Client + EventuallyPoll string + EventuallyTimeout string + ConsistentlyPoll string + ConsistentallyTimeout string + BackgroundCtx context.Context //nolint:containedctx +} + +func NewToolkit(client client.Client) Toolkit { + return Toolkit{ + Client: client, + EventuallyPoll: "100ms", + EventuallyTimeout: "1s", + ConsistentlyPoll: "100ms", + ConsistentallyTimeout: "1s", + BackgroundCtx: context.Background(), + } +} + +// cleanlyCreate creates the given object, and registers a callback to delete the object which +// Ginkgo will call at the appropriate time. The error from the `Create` call is returned (so it +// can be checked) and the `Delete` callback handles 'NotFound' errors as a success. +func (tk Toolkit) CleanlyCreate(ctx context.Context, obj client.Object) error { + // Save and then re-set the GVK because the API call removes it + savedGVK := obj.GetObjectKind().GroupVersionKind() + createErr := tk.Create(ctx, obj) + obj.GetObjectKind().SetGroupVersionKind(savedGVK) + + if createErr == nil { + ginkgo.DeferCleanup(func() { + ginkgo.GinkgoWriter.Printf("Deleting %v %v/%v\n", + obj.GetObjectKind().GroupVersionKind().Kind, obj.GetNamespace(), obj.GetName()) + + if err := tk.Delete(tk.BackgroundCtx, obj); err != nil { + if !errors.IsNotFound(err) { + // Use Fail in order to provide a custom message with useful information + ginkgo.Fail(fmt.Sprintf("Expected success or 'NotFound' error, got %v", err), 1) + } + } + }) + } + + return createErr +} + +// EC runs assertions on asynchronous behavior, both *E*ventually and *C*onsistently, +// using the polling and timeout settings of the toolkit. Its usage should feel familiar +// to gomega users, simply skip the `.Should(...)` call and put your matcher as the second +// parameter here. +func (tk Toolkit) EC( + actualOrCtx interface{}, matcher gomegaTypes.GomegaMatcher, optionalDescription ...interface{}, +) bool { + gomega.Eventually( + actualOrCtx, tk.EventuallyTimeout, tk.EventuallyPoll, + ).Should(matcher, optionalDescription...) + + return gomega.Consistently( + actualOrCtx, tk.ConsistentallyTimeout, tk.ConsistentlyPoll, + ).Should(matcher, optionalDescription...) +} diff --git a/test/fakepolicy/test/namespaceselection_test.go b/test/fakepolicy/test/basic/namespaceselection_test.go similarity index 93% rename from test/fakepolicy/test/namespaceselection_test.go rename to test/fakepolicy/test/basic/namespaceselection_test.go index 2800be4..660487f 100644 --- a/test/fakepolicy/test/namespaceselection_test.go +++ b/test/fakepolicy/test/basic/namespaceselection_test.go @@ -1,6 +1,6 @@ // Copyright Contributors to the Open Cluster Management project -package test +package basic import ( "fmt" @@ -12,7 +12,9 @@ import ( metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" nucleusv1beta1 "open-cluster-management.io/governance-policy-nucleus/api/v1beta1" + "open-cluster-management.io/governance-policy-nucleus/pkg/testutils" fakev1beta1 "open-cluster-management.io/governance-policy-nucleus/test/fakepolicy/api/v1beta1" + . "open-cluster-management.io/governance-policy-nucleus/test/fakepolicy/test/utils" ) var _ = Describe("FakePolicy NamespaceSelection", Ordered, func() { @@ -20,14 +22,14 @@ var _ = Describe("FakePolicy NamespaceSelection", Ordered, func() { sampleNamespaces := []string{"foo", "goo", "fake", "faze", "kube-one"} allNamespaces := append(defaultNamespaces, sampleNamespaces...) - BeforeAll(func() { + BeforeAll(func(ctx SpecContext) { By("Creating sample namespaces") for _, ns := range sampleNamespaces { nsObj := &corev1.Namespace{ObjectMeta: metav1.ObjectMeta{ Name: ns, Labels: map[string]string{"sample": ns}, }} - Expect(cleanlyCreate(nsObj)).To(Succeed()) + Expect(tk.CleanlyCreate(ctx, nsObj)).To(Succeed()) } By("Ensuring the allNamespaces list is correct") @@ -45,17 +47,17 @@ var _ = Describe("FakePolicy NamespaceSelection", Ordered, func() { }) DescribeTable("Verifying NamespaceSelector behavior", - func(sel nucleusv1beta1.NamespaceSelector, desiredMatches []string, selErr string) { - policy := sampleFakePolicy() + func(ctx SpecContext, sel nucleusv1beta1.NamespaceSelector, desiredMatches []string, selErr string) { + policy := SampleFakePolicy() policy.Spec.NamespaceSelector = sel - Expect(cleanlyCreate(&policy)).To(Succeed()) + Expect(tk.CleanlyCreate(ctx, &policy)).To(Succeed()) slices.Sort(desiredMatches) Eventually(func(g Gomega) { foundPolicy := fakev1beta1.FakePolicy{} - g.Expect(k8sClient.Get(ctx, getNamespacedName(&policy), &foundPolicy)).To(Succeed()) + g.Expect(k8sClient.Get(ctx, testutils.ObjNN(&policy), &foundPolicy)).To(Succeed()) g.Expect(foundPolicy.Status.SelectionComplete).To(BeTrue()) idx, cond := foundPolicy.Status.GetCondition("NamespaceSelection") diff --git a/test/fakepolicy/test/suite_test.go b/test/fakepolicy/test/basic/suite_test.go similarity index 86% rename from test/fakepolicy/test/suite_test.go rename to test/fakepolicy/test/basic/suite_test.go index 494a32d..0c73761 100644 --- a/test/fakepolicy/test/suite_test.go +++ b/test/fakepolicy/test/basic/suite_test.go @@ -1,6 +1,6 @@ // Copyright Contributors to the Open Cluster Management project -package test +package basic import ( "context" @@ -17,6 +17,7 @@ import ( logf "sigs.k8s.io/controller-runtime/pkg/log" "sigs.k8s.io/controller-runtime/pkg/log/zap" + "open-cluster-management.io/governance-policy-nucleus/pkg/testutils" "open-cluster-management.io/governance-policy-nucleus/test/fakepolicy" fakev1beta1 "open-cluster-management.io/governance-policy-nucleus/test/fakepolicy/api/v1beta1" ) @@ -30,12 +31,13 @@ var ( testEnv *envtest.Environment ctx context.Context cancel context.CancelFunc + tk testutils.Toolkit ) func TestAPIs(t *testing.T) { RegisterFailHandler(Fail) - RunSpecs(t, "Controller Suite") + RunSpecs(t, "Basic Suite") } var _ = BeforeSuite(func() { @@ -46,7 +48,7 @@ var _ = BeforeSuite(func() { By("bootstrapping test environment") testEnv = &envtest.Environment{ - CRDDirectoryPaths: []string{filepath.Join("..", "config", "crd", "bases")}, + CRDDirectoryPaths: []string{filepath.Join("..", "..", "config", "crd", "bases")}, ErrorIfCRDPathMissing: true, } @@ -65,6 +67,9 @@ var _ = BeforeSuite(func() { Expect(err).NotTo(HaveOccurred()) Expect(k8sClient).NotTo(BeNil()) + tk = testutils.NewToolkit(k8sClient) + tk.BackgroundCtx = ctx + go func() { defer GinkgoRecover() Expect(fakepolicy.Run(ctx, cfg)).To(Succeed()) diff --git a/test/fakepolicy/test/target_test.go b/test/fakepolicy/test/basic/target_test.go similarity index 87% rename from test/fakepolicy/test/target_test.go rename to test/fakepolicy/test/basic/target_test.go index 954f904..69baa53 100644 --- a/test/fakepolicy/test/target_test.go +++ b/test/fakepolicy/test/basic/target_test.go @@ -1,6 +1,6 @@ // Copyright Contributors to the Open Cluster Management project -package test +package basic import ( "fmt" @@ -13,7 +13,9 @@ import ( metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" nucleusv1beta1 "open-cluster-management.io/governance-policy-nucleus/api/v1beta1" + "open-cluster-management.io/governance-policy-nucleus/pkg/testutils" fakev1beta1 "open-cluster-management.io/governance-policy-nucleus/test/fakepolicy/api/v1beta1" + . "open-cluster-management.io/governance-policy-nucleus/test/fakepolicy/test/utils" ) var _ = Describe("FakePolicy TargetConfigMaps", func() { @@ -32,7 +34,7 @@ var _ = Describe("FakePolicy TargetConfigMaps", func() { } allConfigMaps := append(defaultConfigMaps, sampleConfigMaps...) - beforeFunc := func() { + beforeFunc := func(ctx SpecContext) { By("Creating sample configmaps") for _, cm := range sampleConfigMaps { ns, name, _ := strings.Cut(cm, "/") @@ -44,7 +46,7 @@ var _ = Describe("FakePolicy TargetConfigMaps", func() { }, Data: map[string]string{"foo": "bar"}, } - Expect(cleanlyCreate(cmObj)).To(Succeed()) + Expect(tk.CleanlyCreate(ctx, cmObj)).To(Succeed()) } By("Ensuring the allConfigMaps list is correct") @@ -136,7 +138,7 @@ var _ = Describe("FakePolicy TargetConfigMaps", func() { checkFunc := func(policy fakev1beta1.FakePolicy, desiredMatches []string, selErr string) func(g Gomega) { return func(g Gomega) { foundPolicy := fakev1beta1.FakePolicy{} - g.Expect(k8sClient.Get(ctx, getNamespacedName(&policy), &foundPolicy)).To(Succeed()) + g.Expect(k8sClient.Get(ctx, testutils.ObjNN(&policy), &foundPolicy)).To(Succeed()) g.Expect(foundPolicy.Status.SelectionComplete).To(BeTrue()) slices.Sort(desiredMatches) @@ -163,11 +165,11 @@ var _ = Describe("FakePolicy TargetConfigMaps", func() { BeforeAll(beforeFunc) DescribeTable("Verifying TargetConfigMaps behavior", - func(sel nucleusv1beta1.Target, desiredMatches []string, selErr string) { - policy := sampleFakePolicy() + func(ctx SpecContext, sel nucleusv1beta1.Target, desiredMatches []string, selErr string) { + policy := SampleFakePolicy() policy.Spec.TargetConfigMaps = sel - Expect(cleanlyCreate(&policy)).To(Succeed()) + Expect(tk.CleanlyCreate(ctx, &policy)).To(Succeed()) Eventually(checkFunc(policy, desiredMatches, selErr)).Should(Succeed()) }, @@ -179,7 +181,7 @@ var _ = Describe("FakePolicy TargetConfigMaps", func() { BeforeAll(beforeFunc) DescribeTable("Verifying TargetConfigMaps behavior", - func(sel nucleusv1beta1.Target, givenDesiredMatches []string, selErr string) { + func(ctx SpecContext, sel nucleusv1beta1.Target, givenDesiredMatches []string, selErr string) { sel.Namespace = "default" desiredMatches := make([]string, 0) @@ -190,10 +192,10 @@ var _ = Describe("FakePolicy TargetConfigMaps", func() { } } - policy := sampleFakePolicy() + policy := SampleFakePolicy() policy.Spec.TargetConfigMaps = sel - Expect(cleanlyCreate(&policy)).To(Succeed()) + Expect(tk.CleanlyCreate(ctx, &policy)).To(Succeed()) Eventually(checkFunc(policy, desiredMatches, selErr)).Should(Succeed()) }, @@ -205,12 +207,12 @@ var _ = Describe("FakePolicy TargetConfigMaps", func() { BeforeAll(beforeFunc) DescribeTable("Verifying TargetConfigMaps behavior", - func(sel nucleusv1beta1.Target, desiredMatches []string, selErr string) { - policy := sampleFakePolicy() + func(ctx SpecContext, sel nucleusv1beta1.Target, desiredMatches []string, selErr string) { + policy := SampleFakePolicy() policy.Spec.TargetConfigMaps = sel policy.Spec.TargetUsingReflection = true - Expect(cleanlyCreate(&policy)).To(Succeed()) + Expect(tk.CleanlyCreate(ctx, &policy)).To(Succeed()) Eventually(checkFunc(policy, desiredMatches, selErr)).Should(Succeed()) }, diff --git a/test/fakepolicy/test/validation_test.go b/test/fakepolicy/test/basic/validation_test.go similarity index 87% rename from test/fakepolicy/test/validation_test.go rename to test/fakepolicy/test/basic/validation_test.go index b41cb5a..4f54892 100644 --- a/test/fakepolicy/test/validation_test.go +++ b/test/fakepolicy/test/basic/validation_test.go @@ -1,18 +1,20 @@ // Copyright Contributors to the Open Cluster Management project -package test +package basic import ( . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" "k8s.io/apimachinery/pkg/api/errors" "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" + + . "open-cluster-management.io/governance-policy-nucleus/test/fakepolicy/test/utils" ) var _ = Describe("FakePolicy CRD Validation", func() { DescribeTable("Validating spec inputs", - func(severity, remediationAction string, include, exclude []string, isValid bool) { - policy := fromTestdata("fakepolicy-sample.yaml") + func(ctx SpecContext, severity, remediationAction string, include, exclude []string, isValid bool) { + policy := FromTestdata("fakepolicy-sample.yaml") Expect(unstructured.SetNestedField(policy.Object, severity, "spec", "severity")).To(Succeed()) @@ -24,8 +26,8 @@ var _ = Describe("FakePolicy CRD Validation", func() { exclude, "spec", "namespaceSelector", "exclude")).To(Succeed()) if isValid { - Expect(cleanlyCreate(&policy)).To(Succeed()) - } else if !errors.IsInvalid(cleanlyCreate(&policy)) { + Expect(tk.CleanlyCreate(ctx, &policy)).To(Succeed()) + } else if !errors.IsInvalid(tk.CleanlyCreate(ctx, &policy)) { Fail("Expected creating the policy to fail with an 'invalid' error") } }, diff --git a/test/fakepolicy/test/yamlformat_test.go b/test/fakepolicy/test/basic/yamlformat_test.go similarity index 77% rename from test/fakepolicy/test/yamlformat_test.go rename to test/fakepolicy/test/basic/yamlformat_test.go index dda1fde..0a4b536 100644 --- a/test/fakepolicy/test/yamlformat_test.go +++ b/test/fakepolicy/test/basic/yamlformat_test.go @@ -1,4 +1,4 @@ -package test +package basic import ( "encoding/json" @@ -10,47 +10,49 @@ import ( "sigs.k8s.io/controller-runtime/pkg/client" nucleusv1beta1 "open-cluster-management.io/governance-policy-nucleus/api/v1beta1" + "open-cluster-management.io/governance-policy-nucleus/pkg/testutils" + . "open-cluster-management.io/governance-policy-nucleus/test/fakepolicy/test/utils" ) var _ = Describe("FakePolicy resource format verification", func() { - sampleYAML := fromTestdata("fakepolicy-sample.yaml") - extraFieldYAML := fromTestdata("extra-field.yaml") - emptyMatchExpressionsYAML := fromTestdata("empty-match-expressions.yaml") + sampleYAML := FromTestdata("fakepolicy-sample.yaml") + extraFieldYAML := FromTestdata("extra-field.yaml") + emptyMatchExpressionsYAML := FromTestdata("empty-match-expressions.yaml") - sample := sampleFakePolicy() + sample := SampleFakePolicy() - emptyInclude := sampleFakePolicy() + emptyInclude := SampleFakePolicy() emptyInclude.Spec.NamespaceSelector.Include = []nucleusv1beta1.NonEmptyString{} - emptyLabelSelector := sampleFakePolicy() + emptyLabelSelector := SampleFakePolicy() emptyLabelSelector.Spec.NamespaceSelector.LabelSelector = &metav1.LabelSelector{} - nilLabelSelector := sampleFakePolicy() + nilLabelSelector := SampleFakePolicy() nilLabelSelector.Spec.NamespaceSelector.LabelSelector = nil - emptyMatchExpressions := sampleFakePolicy() + emptyMatchExpressions := SampleFakePolicy() emptyMatchExpressions.Spec.NamespaceSelector.LabelSelector.MatchExpressions = []metav1.LabelSelectorRequirement{} - emptyNSSelector := sampleFakePolicy() + emptyNSSelector := SampleFakePolicy() emptyNSSelector.Spec.NamespaceSelector = nucleusv1beta1.NamespaceSelector{} - emptySeverity := sampleFakePolicy() + emptySeverity := SampleFakePolicy() emptySeverity.Spec.Severity = "" - emptyRemAction := sampleFakePolicy() + emptyRemAction := SampleFakePolicy() emptyRemAction.Spec.RemediationAction = "" - reqSelector := sampleFakePolicy() + reqSelector := SampleFakePolicy() reqSelector.Spec.NamespaceSelector.LabelSelector.MatchExpressions = []metav1.LabelSelectorRequirement{{ Key: "sample", Operator: metav1.LabelSelectorOpExists, }} // input is a clientObject so that either an Unstructured or the "real" type can be provided. - DescribeTable("Verifying spec stability", func(input client.Object, wantFile string) { - Expect(cleanlyCreate(input)).To(Succeed()) + DescribeTable("Verifying spec stability", func(ctx SpecContext, input client.Object, wantFile string) { + Expect(tk.CleanlyCreate(ctx, input)).To(Succeed()) - nn := getNamespacedName(input) + nn := testutils.ObjNN(input) gotObj := &unstructured.Unstructured{ Object: map[string]interface{}{ "apiVersion": "policy.open-cluster-management.io/v1beta1", @@ -65,7 +67,7 @@ var _ = Describe("FakePolicy resource format verification", func() { gotSpec, err := json.Marshal(gotObj.Object["spec"]) Expect(err).ToNot(HaveOccurred()) - wantUnstruct := fromTestdata(wantFile) + wantUnstruct := FromTestdata(wantFile) wantSpec, err := json.Marshal(wantUnstruct.Object["spec"]) Expect(err).ToNot(HaveOccurred()) diff --git a/test/fakepolicy/test/testdata/empty-match-expressions.yaml b/test/fakepolicy/test/utils/testdata/empty-match-expressions.yaml similarity index 100% rename from test/fakepolicy/test/testdata/empty-match-expressions.yaml rename to test/fakepolicy/test/utils/testdata/empty-match-expressions.yaml diff --git a/test/fakepolicy/test/testdata/empty-ns-selector.yaml b/test/fakepolicy/test/utils/testdata/empty-ns-selector.yaml similarity index 100% rename from test/fakepolicy/test/testdata/empty-ns-selector.yaml rename to test/fakepolicy/test/utils/testdata/empty-ns-selector.yaml diff --git a/test/fakepolicy/test/testdata/extra-field.yaml b/test/fakepolicy/test/utils/testdata/extra-field.yaml similarity index 100% rename from test/fakepolicy/test/testdata/extra-field.yaml rename to test/fakepolicy/test/utils/testdata/extra-field.yaml diff --git a/test/fakepolicy/test/testdata/fakepolicy-sample.yaml b/test/fakepolicy/test/utils/testdata/fakepolicy-sample.yaml similarity index 100% rename from test/fakepolicy/test/testdata/fakepolicy-sample.yaml rename to test/fakepolicy/test/utils/testdata/fakepolicy-sample.yaml diff --git a/test/fakepolicy/test/testdata/no-include.yaml b/test/fakepolicy/test/utils/testdata/no-include.yaml similarity index 100% rename from test/fakepolicy/test/testdata/no-include.yaml rename to test/fakepolicy/test/utils/testdata/no-include.yaml diff --git a/test/fakepolicy/test/testdata/no-remediation.yaml b/test/fakepolicy/test/utils/testdata/no-remediation.yaml similarity index 100% rename from test/fakepolicy/test/testdata/no-remediation.yaml rename to test/fakepolicy/test/utils/testdata/no-remediation.yaml diff --git a/test/fakepolicy/test/testdata/no-severity.yaml b/test/fakepolicy/test/utils/testdata/no-severity.yaml similarity index 100% rename from test/fakepolicy/test/testdata/no-severity.yaml rename to test/fakepolicy/test/utils/testdata/no-severity.yaml diff --git a/test/fakepolicy/test/testdata/req-selector.yaml b/test/fakepolicy/test/utils/testdata/req-selector.yaml similarity index 100% rename from test/fakepolicy/test/testdata/req-selector.yaml rename to test/fakepolicy/test/utils/testdata/req-selector.yaml diff --git a/test/fakepolicy/test/utils_test.go b/test/fakepolicy/test/utils/utils.go similarity index 57% rename from test/fakepolicy/test/utils_test.go rename to test/fakepolicy/test/utils/utils.go index 7f1186f..2400f4d 100644 --- a/test/fakepolicy/test/utils_test.go +++ b/test/fakepolicy/test/utils/utils.go @@ -1,58 +1,24 @@ // Copyright Contributors to the Open Cluster Management project -package test +package utils import ( "embed" - "fmt" - . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" - "k8s.io/apimachinery/pkg/api/errors" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" - "k8s.io/apimachinery/pkg/types" "k8s.io/apimachinery/pkg/util/yaml" - "sigs.k8s.io/controller-runtime/pkg/client" nucleusv1beta1 "open-cluster-management.io/governance-policy-nucleus/api/v1beta1" fakev1beta1 "open-cluster-management.io/governance-policy-nucleus/test/fakepolicy/api/v1beta1" ) -// cleanlyCreate creates the given object, and registers a callback to delete the object which -// Ginkgo will call at the appropriate time. The error from the `Create` call is returned (so it can -// be checked) and the `Delete` callback handles 'NotFound' errors as a success. -func cleanlyCreate(obj client.Object) error { - createErr := k8sClient.Create(ctx, obj) - - if createErr == nil { - DeferCleanup(func() { - GinkgoWriter.Printf("Deleting %v %v/%v\n", obj.GetObjectKind().GroupVersionKind().Kind, - obj.GetNamespace(), obj.GetName()) - if err := k8sClient.Delete(ctx, obj); err != nil { - if !errors.IsNotFound(err) { - // Use Fail in order to provide a custom message with useful information - Fail(fmt.Sprintf("Expected success or 'NotFound' error, got %v", err), 1) - } - } - }) - } - - return createErr -} - -func getNamespacedName(obj client.Object) types.NamespacedName { - return types.NamespacedName{ - Namespace: obj.GetNamespace(), - Name: obj.GetName(), - } -} - //go:embed testdata/* var testfiles embed.FS // Unmarshals the given YAML file in testdata/ into an unstructured.Unstructured -func fromTestdata(name string) unstructured.Unstructured { +func FromTestdata(name string) unstructured.Unstructured { objYAML, err := testfiles.ReadFile("testdata/" + name) ExpectWithOffset(1, err).ToNot(HaveOccurred()) @@ -62,7 +28,7 @@ func fromTestdata(name string) unstructured.Unstructured { return unstructured.Unstructured{Object: m} } -func sampleFakePolicy() fakev1beta1.FakePolicy { +func SampleFakePolicy() fakev1beta1.FakePolicy { return fakev1beta1.FakePolicy{ TypeMeta: metav1.TypeMeta{ APIVersion: "policy.open-cluster-management.io/v1beta1",