diff --git a/.devcontainer/devcontainer.json b/.devcontainer/devcontainer.json index 4b6828cc..b35fe79e 100644 --- a/.devcontainer/devcontainer.json +++ b/.devcontainer/devcontainer.json @@ -8,7 +8,7 @@ "dockerfile": "${localWorkspaceFolder}/.devcontainer/Dockerfile", "context": "${localWorkspaceFolder}", "args": { - "GO_VERSION": "1.26.3", + "GO_VERSION": "1.26.4", "KUBECTX_VERSION": "0.9.5", "SVELTOSCTL_VERSION": "0.53.0" } diff --git a/.github/workflows/main.yaml b/.github/workflows/main.yaml index 17c83c17..6c2cd2e0 100644 --- a/.github/workflows/main.yaml +++ b/.github/workflows/main.yaml @@ -14,7 +14,7 @@ jobs: - name: Set up Go uses: actions/setup-go@4a3601121dd01d1626a1e23e37211e3254c1c06c # v6.4.0 with: - go-version: 1.26.3 + go-version: 1.26.4 - name: Build run: make build - name: FMT @@ -33,7 +33,7 @@ jobs: - name: Set up Go uses: actions/setup-go@4a3601121dd01d1626a1e23e37211e3254c1c06c # v6.4.0 with: - go-version: 1.26.3 + go-version: 1.26.4 - name: ut run: make test env: @@ -46,7 +46,7 @@ jobs: - name: Set up Go uses: actions/setup-go@4a3601121dd01d1626a1e23e37211e3254c1c06c # v6.4.0 with: - go-version: 1.26.3 + go-version: 1.26.4 - name: Free Disk Space (Ubuntu) uses: jlumbroso/free-disk-space@main with: @@ -74,7 +74,7 @@ jobs: - name: Set up Go uses: actions/setup-go@4a3601121dd01d1626a1e23e37211e3254c1c06c # v6.4.0 with: - go-version: 1.26.3 + go-version: 1.26.4 - name: Free Disk Space (Ubuntu) uses: jlumbroso/free-disk-space@main with: @@ -102,7 +102,7 @@ jobs: - name: Set up Go uses: actions/setup-go@4a3601121dd01d1626a1e23e37211e3254c1c06c # v6.4.0 with: - go-version: 1.26.3 + go-version: 1.26.4 - name: Free Disk Space (Ubuntu) uses: jlumbroso/free-disk-space@main with: @@ -130,7 +130,7 @@ jobs: - name: Set up Go uses: actions/setup-go@4a3601121dd01d1626a1e23e37211e3254c1c06c # v6.4.0 with: - go-version: 1.26.3 + go-version: 1.26.4 - name: Free Disk Space (Ubuntu) uses: jlumbroso/free-disk-space@main with: @@ -158,7 +158,7 @@ jobs: - name: Set up Go uses: actions/setup-go@4a3601121dd01d1626a1e23e37211e3254c1c06c # v6.4.0 with: - go-version: 1.26.3 + go-version: 1.26.4 - name: Free Disk Space (Ubuntu) uses: jlumbroso/free-disk-space@main with: @@ -186,7 +186,7 @@ jobs: - name: Set up Go uses: actions/setup-go@4a3601121dd01d1626a1e23e37211e3254c1c06c # v6.4.0 with: - go-version: 1.26.3 + go-version: 1.26.4 - name: Free Disk Space (Ubuntu) uses: jlumbroso/free-disk-space@main with: @@ -214,7 +214,7 @@ jobs: - name: Set up Go uses: actions/setup-go@4a3601121dd01d1626a1e23e37211e3254c1c06c # v6.4.0 with: - go-version: 1.26.3 + go-version: 1.26.4 - name: Free Disk Space (Ubuntu) uses: jlumbroso/free-disk-space@main with: diff --git a/.golangci.yaml b/.golangci.yaml index a7f8c71f..585e559b 100644 --- a/.golangci.yaml +++ b/.golangci.yaml @@ -20,7 +20,7 @@ linters: - goconst - gocritic - gocyclo - - gomodguard + - gomodguard_v2 - goprintffuncname - gosec - govet @@ -72,12 +72,10 @@ linters: - style gocyclo: min-complexity: 20 - gomodguard: + gomodguard_v2: blocked: - modules: - - k8s.io/kubernetes: - reason: There is no good, avoidable reason to use this package and often leads to issues such as https://bit.ly/3dlKScY. However, if you disagree please include @ravchama in code review highlighting the reason. - local-replace-directives: true + - module: k8s.io/kubernetes + local-replace-directives: true govet: settings: printf: @@ -132,6 +130,7 @@ linters: - third_party$ - builtin$ - examples$ + - internal/test/helpers issues: max-issues-per-linter: 0 max-same-issues: 0 @@ -149,3 +148,4 @@ formatters: - third_party$ - builtin$ - examples$ + - internal/test/helpers diff --git a/Dockerfile b/Dockerfile index 79a5f95d..e1ba1a5c 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,5 +1,5 @@ # Build the manager binary -FROM golang:1.26.3 AS builder +FROM golang:1.26.4 AS builder ARG BUILDOS ARG TARGETARCH diff --git a/Dockerfile_WithGit b/Dockerfile_WithGit index adb12208..9fb44c95 100644 --- a/Dockerfile_WithGit +++ b/Dockerfile_WithGit @@ -1,5 +1,5 @@ # Build the manager binary -FROM golang:1.26.3 AS builder +FROM golang:1.26.4 AS builder ARG BUILDOS ARG TARGETARCH diff --git a/Makefile b/Makefile index 29c0796e..9675a8b8 100644 --- a/Makefile +++ b/Makefile @@ -79,7 +79,7 @@ KIND := $(TOOLS_BIN_DIR)/kind KUBECTL := $(TOOLS_BIN_DIR)/kubectl GOVULNCHECK_VERSION := "v1.1.4" -GOLANGCI_LINT_VERSION := "v2.11.4" +GOLANGCI_LINT_VERSION := "v2.12.1" CLUSTERCTL_VERSION := v1.13.2 KIND_VERSION := v0.32.0 diff --git a/api/v1beta1/zz_generated.deepcopy.go b/api/v1beta1/zz_generated.deepcopy.go index 39a311bd..2da29d03 100644 --- a/api/v1beta1/zz_generated.deepcopy.go +++ b/api/v1beta1/zz_generated.deepcopy.go @@ -21,11 +21,12 @@ limitations under the License. package v1beta1 import ( - apiv1beta1 "github.com/projectsveltos/libsveltos/api/v1beta1" corev1 "k8s.io/api/core/v1" - "k8s.io/apimachinery/pkg/apis/meta/v1" + v1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/util/intstr" + + apiv1beta1 "github.com/projectsveltos/libsveltos/api/v1beta1" ) // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. diff --git a/controllers/chartmanager/chartmanager_test.go b/controllers/chartmanager/chartmanager_test.go index a3ef4fcf..a48a1c8e 100644 --- a/controllers/chartmanager/chartmanager_test.go +++ b/controllers/chartmanager/chartmanager_test.go @@ -60,11 +60,11 @@ var _ = Describe("Chart manager", func() { HelmCharts: []configv1beta1.HelmChart{ { RepositoryURL: "https://kyverno.github.io/kyverno/", - RepositoryName: "kyverno", + RepositoryName: testKyvernoName, ChartName: "kyverno/kyverno", ChartVersion: "v3.0.1", ReleaseName: "kyverno-latest", - ReleaseNamespace: "kyverno", + ReleaseNamespace: testKyvernoName, HelmChartAction: configv1beta1.HelmChartActionInstall, }, { @@ -219,12 +219,12 @@ var _ = Describe("Chart manager", func() { } prometheusChart := configv1beta1.HelmChart{ - RepositoryURL: "https://prometheus-community.github.io/helm-charts", - RepositoryName: "prometheus-community", - ChartName: "prometheus-community/kube-prometheus-stack", - ChartVersion: "40.0.0", - ReleaseName: "prometheus-latest", - ReleaseNamespace: "prometheus", + RepositoryURL: testPrometheusCommunityURL, + RepositoryName: testPrometheusCommunityName, + ChartName: testPrometheusKubeStackChart, + ChartVersion: testPrometheusKubeStackVersion, + ReleaseName: testPrometheusLatestRelease, + ReleaseNamespace: testPrometheusNamespace, HelmChartAction: configv1beta1.HelmChartActionInstall, } @@ -271,12 +271,12 @@ var _ = Describe("Chart manager", func() { } prometheusChart := configv1beta1.HelmChart{ - RepositoryURL: "https://prometheus-community.github.io/helm-charts", - RepositoryName: "prometheus-community", - ChartName: "prometheus-community/kube-prometheus-stack", - ChartVersion: "40.0.0", - ReleaseName: "prometheus-latest", - ReleaseNamespace: "prometheus", + RepositoryURL: testPrometheusCommunityURL, + RepositoryName: testPrometheusCommunityName, + ChartName: testPrometheusKubeStackChart, + ChartVersion: testPrometheusKubeStackVersion, + ReleaseName: testPrometheusLatestRelease, + ReleaseNamespace: testPrometheusNamespace, HelmChartAction: configv1beta1.HelmChartActionInstall, } diff --git a/controllers/chartmanager/test_constants_test.go b/controllers/chartmanager/test_constants_test.go new file mode 100644 index 00000000..5be11d4b --- /dev/null +++ b/controllers/chartmanager/test_constants_test.go @@ -0,0 +1,27 @@ +/* +Copyright 2025. projectsveltos.io. All rights reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package chartmanager_test + +const ( + testKyvernoName = "kyverno" + testPrometheusCommunityURL = "https://prometheus-community.github.io/helm-charts" + testPrometheusCommunityName = "prometheus-community" + testPrometheusKubeStackChart = "prometheus-community/kube-prometheus-stack" + testPrometheusKubeStackVersion = "40.0.0" + testPrometheusLatestRelease = "prometheus-latest" + testPrometheusNamespace = "prometheus" +) diff --git a/controllers/clustercache/cluster_cache_test.go b/controllers/clustercache/cluster_cache_test.go index 206926a9..d94c79ca 100644 --- a/controllers/clustercache/cluster_cache_test.go +++ b/controllers/clustercache/cluster_cache_test.go @@ -74,7 +74,7 @@ var _ = Describe("Clustercache", func() { secretObj := &corev1.ObjectReference{ Namespace: secret.Namespace, Name: secret.Name, - Kind: "Secret", + Kind: testKindSecret, APIVersion: corev1.SchemeGroupVersion.String(), } storedCluster := cacheMgr.GetClusterFromSecret(secretObj) @@ -107,7 +107,7 @@ var _ = Describe("Clustercache", func() { secretObj := &corev1.ObjectReference{ Namespace: secret.Namespace, Name: secret.Name, - Kind: "Secret", + Kind: testKindSecret, APIVersion: corev1.SchemeGroupVersion.String(), } cacheMgr.RemoveSecret(secretObj) diff --git a/controllers/clustercache/test_constants_test.go b/controllers/clustercache/test_constants_test.go new file mode 100644 index 00000000..13781968 --- /dev/null +++ b/controllers/clustercache/test_constants_test.go @@ -0,0 +1,21 @@ +/* +Copyright 2025. projectsveltos.io. All rights reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package clustercache_test + +const ( + testKindSecret = "Secret" +) diff --git a/controllers/clusterprofile_controller_test.go b/controllers/clusterprofile_controller_test.go index 6c0243f6..8924a12f 100644 --- a/controllers/clusterprofile_controller_test.go +++ b/controllers/clusterprofile_controller_test.go @@ -342,7 +342,7 @@ var _ = Describe("ClusterProfileReconciler: requeue methods", func() { ClusterSelector: libsveltosv1beta1.Selector{ LabelSelector: metav1.LabelSelector{ MatchLabels: map[string]string{ - "env": "production", + testEnvLabelKey: testProductionValue, }, }, }, diff --git a/controllers/clusterprofile_transformations_test.go b/controllers/clusterprofile_transformations_test.go index d60de9b7..d9c10b6a 100644 --- a/controllers/clusterprofile_transformations_test.go +++ b/controllers/clusterprofile_transformations_test.go @@ -50,7 +50,7 @@ var _ = Describe("ClusterProfileReconciler map functions", func() { Name: upstreamClusterNamePrefix + randomString(), Namespace: namespace, Labels: map[string]string{ - "env": "production", + testEnvLabelKey: testProductionValue, }, }, } @@ -63,7 +63,7 @@ var _ = Describe("ClusterProfileReconciler map functions", func() { ClusterSelector: libsveltosv1beta1.Selector{ LabelSelector: metav1.LabelSelector{ MatchLabels: map[string]string{ - "env": "production", + testEnvLabelKey: testProductionValue, }, }, }, @@ -78,7 +78,7 @@ var _ = Describe("ClusterProfileReconciler map functions", func() { ClusterSelector: libsveltosv1beta1.Selector{ LabelSelector: metav1.LabelSelector{ MatchLabels: map[string]string{ - "env": "qa", + testEnvLabelKey: testQAValue, }, }, }, @@ -138,7 +138,7 @@ var _ = Describe("ClusterProfileReconciler map functions", func() { matchingClusterProfile.Spec.ClusterSelector = libsveltosv1beta1.Selector{ LabelSelector: metav1.LabelSelector{ MatchLabels: map[string]string{ - "env": "qa", + testEnvLabelKey: testQAValue, }, }, } diff --git a/controllers/clusterpromotion_controller.go b/controllers/clusterpromotion_controller.go index d3ae51d6..58ecb659 100644 --- a/controllers/clusterpromotion_controller.go +++ b/controllers/clusterpromotion_controller.go @@ -561,7 +561,7 @@ func (r *ClusterPromotionReconciler) reconcileStageProfile(ctx context.Context, forceConflict := true options := metav1.PatchOptions{ - FieldManager: "application/apply-patch", + FieldManager: applyPatchFieldManager, Force: &forceConflict, } @@ -667,7 +667,7 @@ func getPreCheckDeploymentClusterProfileLabels(clusterPromotion *configv1beta1.C return map[string]string{ clusterPromotionNameLabel: clusterPromotion.Name, // Adding a distinct label to easily identify this ClusterProfile as part of the pre-verification step. - preVerificationClusterProfileLabel: "true", + preVerificationClusterProfileLabel: stringTrue, } } @@ -1086,7 +1086,7 @@ func (r *ClusterPromotionReconciler) reconcilePreHealthCheckDeployment(ctx conte forceConflict := true options := metav1.PatchOptions{ - FieldManager: "application/apply-patch", + FieldManager: applyPatchFieldManager, Force: &forceConflict, } diff --git a/controllers/clusterpromotion_controller_test.go b/controllers/clusterpromotion_controller_test.go index 7b37adc9..56fe4114 100644 --- a/controllers/clusterpromotion_controller_test.go +++ b/controllers/clusterpromotion_controller_test.go @@ -440,7 +440,7 @@ var _ = Describe("ClusterPromotionController", func() { check := libsveltosv1beta1.ValidateHealth{ Group: "", - Version: "v1", + Version: testV1APIVersion, Kind: "Pod", LabelFilters: []libsveltosv1beta1.LabelFilter{ {Key: randomString(), Value: randomString(), Operation: libsveltosv1beta1.OperationEqual}, diff --git a/controllers/clustersummary_controller.go b/controllers/clustersummary_controller.go index 6b24f6b6..99f9db6d 100644 --- a/controllers/clustersummary_controller.go +++ b/controllers/clustersummary_controller.go @@ -1233,7 +1233,7 @@ func getPolicyRefGroupVersionKind(ref *configv1beta1.PolicyRef) *schema.GroupVer switch ref.Kind { case string(libsveltosv1beta1.SecretReferencedResourceKind), string(libsveltosv1beta1.ConfigMapReferencedResourceKind): - return &schema.GroupVersionKind{Group: "", Version: "v1", Kind: ref.Kind} + return &schema.GroupVersionKind{Group: "", Version: coreAPIVersion, Kind: ref.Kind} case sourcev1.GitRepositoryKind: return &schema.GroupVersionKind{Group: sourcev1.GroupVersion.Group, Version: sourcev1.GroupVersion.Version, Kind: ref.Kind} @@ -1919,7 +1919,7 @@ func (r *ClusterSummaryReconciler) getClusterSummaryScope(ctx context.Context, Logger: logger, ClusterSummary: clusterSummary, Profile: profile, - ControllerName: "clustersummary", + ControllerName: controllerNameClusterSummary, }) return clusterSummaryScope, err diff --git a/controllers/clustersummary_controller_test.go b/controllers/clustersummary_controller_test.go index b1e9b5fa..fe85c230 100644 --- a/controllers/clustersummary_controller_test.go +++ b/controllers/clustersummary_controller_test.go @@ -66,7 +66,7 @@ var _ = Describe("ClustersummaryController", func() { Name: clusterName, Namespace: namespace, Labels: map[string]string{ - "dc": "eng", + testDCLabelKey: testEngValue, }, }, Status: clusterv1.ClusterStatus{ @@ -177,7 +177,7 @@ var _ = Describe("ClustersummaryController", func() { It("isPaused returns false when Cluster does not exist", func() { clusterSummary.Annotations = map[string]string{ - "cluster.x-k8s.io/paused": "ok", + "cluster.x-k8s.io/paused": testOkValue, } initObjects := []client.Object{ @@ -214,7 +214,7 @@ var _ = Describe("ClustersummaryController", func() { Client: c, Logger: textlogger.NewLogger(textlogger.NewConfig()), ClusterSummary: clusterSummary, - ControllerName: "clustersummary", + ControllerName: testControllerNameSummary, }) Expect(err).To(BeNil()) @@ -250,7 +250,7 @@ var _ = Describe("ClustersummaryController", func() { Client: c, Logger: textlogger.NewLogger(textlogger.NewConfig()), ClusterSummary: clusterSummary, - ControllerName: "clustersummary", + ControllerName: testControllerNameSummary, }) Expect(err).To(BeNil()) @@ -319,7 +319,7 @@ var _ = Describe("ClustersummaryController", func() { Client: c, Logger: textlogger.NewLogger(textlogger.NewConfig()), ClusterSummary: clusterSummary, - ControllerName: "clustersummary", + ControllerName: testControllerNameSummary, }) Expect(err).To(BeNil()) @@ -370,7 +370,7 @@ var _ = Describe("ClustersummaryController", func() { Client: c, Logger: textlogger.NewLogger(textlogger.NewConfig()), ClusterSummary: clusterSummary, - ControllerName: "clustersummary", + ControllerName: testControllerNameSummary, }) Expect(err).To(BeNil()) @@ -453,7 +453,7 @@ var _ = Describe("ClustersummaryController", func() { Client: c, Logger: textlogger.NewLogger(textlogger.NewConfig()), ClusterSummary: clusterSummary, - ControllerName: "clustersummary", + ControllerName: testControllerNameSummary, }) Expect(err).To(BeNil()) @@ -515,7 +515,7 @@ var _ = Describe("ClustersummaryController", func() { Client: c, Logger: textlogger.NewLogger(textlogger.NewConfig()), ClusterSummary: clusterSummary, - ControllerName: "clustersummary", + ControllerName: testControllerNameSummary, }) Expect(err).To(BeNil()) @@ -557,7 +557,7 @@ var _ = Describe("ClustersummaryController", func() { Client: c, Logger: textlogger.NewLogger(textlogger.NewConfig()), ClusterSummary: clusterSummary, - ControllerName: "clustersummary", + ControllerName: testControllerNameSummary, }) Expect(err).To(BeNil()) @@ -643,7 +643,7 @@ var _ = Describe("ClustersummaryController", func() { Client: c, Logger: textlogger.NewLogger(textlogger.NewConfig()), ClusterSummary: clusterSummary, - ControllerName: "clustersummary", + ControllerName: testControllerNameSummary, }) Expect(err).To(BeNil()) @@ -701,7 +701,7 @@ var _ = Describe("ClustersummaryController", func() { Client: c, Logger: textlogger.NewLogger(textlogger.NewConfig()), ClusterSummary: clusterSummary, - ControllerName: "clustersummary", + ControllerName: testControllerNameSummary, }) Expect(err).To(BeNil()) @@ -764,7 +764,7 @@ var _ = Describe("ClustersummaryController", func() { Client: c, Logger: textlogger.NewLogger(textlogger.NewConfig()), ClusterSummary: clusterSummary, - ControllerName: "clustersummary", + ControllerName: testControllerNameSummary, }) Expect(err).To(BeNil()) @@ -825,7 +825,7 @@ var _ = Describe("ClustersummaryController", func() { Client: c, Logger: textlogger.NewLogger(textlogger.NewConfig()), ClusterSummary: clusterSummary, - ControllerName: "clustersummary", + ControllerName: testControllerNameSummary, }) Expect(err).To(BeNil()) @@ -896,7 +896,7 @@ var _ = Describe("ClustersummaryController", func() { Expect(set.Len()).To(Equal(5)) Expect(set.Items()).To(ContainElement(corev1.ObjectReference{ - APIVersion: "v1", + APIVersion: testV1APIVersion, Kind: string(libsveltosv1beta1.ConfigMapReferencedResourceKind), Namespace: referencedResourceNamespace, Name: cmName, @@ -954,7 +954,7 @@ var _ = Describe("ClustersummaryController", func() { Client: c, Logger: textlogger.NewLogger(textlogger.NewConfig()), ClusterSummary: clusterSummary, - ControllerName: "clustersummary", + ControllerName: testControllerNameSummary, }) Expect(err).To(BeNil()) @@ -1058,7 +1058,7 @@ var _ = Describe("ClustersummaryController", func() { Client: c, Logger: textlogger.NewLogger(textlogger.NewConfig()), ClusterSummary: clusterSummary, - ControllerName: "clustersummary", + ControllerName: testControllerNameSummary, }) Expect(err).To(BeNil()) @@ -1120,7 +1120,7 @@ var _ = Describe("ClustersummaryController", func() { Client: c, Logger: textlogger.NewLogger(textlogger.NewConfig()), ClusterSummary: clusterSummary, - ControllerName: "clustersummary", + ControllerName: testControllerNameSummary, }) Expect(err).To(BeNil()) @@ -1396,13 +1396,13 @@ var _ = Describe("ClusterSummaryReconciler: requeue methods", func() { PatchesFrom: []configv1beta1.ValueFrom{ { Kind: string(libsveltosv1beta1.ConfigMapReferencedResourceKind), - Namespace: "{{ .Cluster.metadata.name }}", - Name: "{{ .Cluster.metadata.name }}-patch", + Namespace: testClusterNameTemplate, + Name: testClusterNamePatchTemplate, }, { Kind: string(libsveltosv1beta1.SecretReferencedResourceKind), - Namespace: "{{ .Cluster.metadata.name }}", - Name: "{{ .Cluster.metadata.name }}-patch", + Namespace: testClusterNameTemplate, + Name: testClusterNamePatchTemplate, }, }, }, diff --git a/controllers/clustersummary_deployer.go b/controllers/clustersummary_deployer.go index f8413986..eeeb94f7 100644 --- a/controllers/clustersummary_deployer.go +++ b/controllers/clustersummary_deployer.go @@ -221,7 +221,7 @@ func (r *ClusterSummaryReconciler) proceedDeployingFeature(ctx context.Context, // Feature must be (re)deployed. options := deployer.Options{HandlerOptions: make(map[string]any)} if getAgentInMgmtCluster() { - options.HandlerOptions[driftDetectionInMgtmCluster] = "ok" + options.HandlerOptions[driftDetectionInMgtmCluster] = annotationValueOk } options.HandlerOptions[configurationHash] = currentHash logger.V(logs.LogDebug).Info("queueing request to deploy") diff --git a/controllers/clustersummary_deployer_test.go b/controllers/clustersummary_deployer_test.go index a1f58289..2650d8e7 100644 --- a/controllers/clustersummary_deployer_test.go +++ b/controllers/clustersummary_deployer_test.go @@ -273,8 +273,8 @@ var _ = Describe("ClustersummaryDeployer", func() { Name: randomString(), }, Rules: []rbacv1.PolicyRule{ - {Verbs: []string{"create", "get"}, APIGroups: []string{"cert-manager.io"}, Resources: []string{"certificaterequests"}}, - {Verbs: []string{"create", "delete"}, APIGroups: []string{""}, Resources: []string{"namespaces", "deployments"}}, + {Verbs: []string{testCreateVerb, testGetVerb}, APIGroups: []string{testCertManagerGroup}, Resources: []string{testCertificateRequestsResource}}, + {Verbs: []string{testCreateVerb, testDeleteVerb}, APIGroups: []string{""}, Resources: []string{testNamespacesResource, testDeploymentsResource}}, }, } Expect(addTypeInformationToObject(scheme, clusterRole)).To(Succeed()) @@ -641,7 +641,7 @@ func getClusterSummaryScope(c client.Client, logger logr.Logger, Logger: logger, Profile: clusterProfile, ClusterSummary: clusterSummary, - ControllerName: "clustersummary", + ControllerName: testControllerNameSummary, }) Expect(err).To(BeNil()) return clusterSummaryScope diff --git a/controllers/clustersummary_predicates_test.go b/controllers/clustersummary_predicates_test.go index 24ccd5d5..3fbfae89 100644 --- a/controllers/clustersummary_predicates_test.go +++ b/controllers/clustersummary_predicates_test.go @@ -72,7 +72,7 @@ var _ = Describe("Clustersummary Predicates: ConfigMapPredicates", func() { It("Update returns true when data has changed", func() { configMapPredicate := controllers.ConfigMapPredicates(logger) - configMap.Data = map[string]string{"change": "now"} + configMap.Data = map[string]string{testChangeKey: "now"} oldConfigMap := &corev1.ConfigMap{ ObjectMeta: metav1.ObjectMeta{ @@ -96,7 +96,7 @@ var _ = Describe("Clustersummary Predicates: ConfigMapPredicates", func() { oldConfigMap := &corev1.ConfigMap{ ObjectMeta: metav1.ObjectMeta{ Name: configMap.Name, - Labels: map[string]string{"env": "testing"}, + Labels: map[string]string{testEnvLabelKey: testTestingValue}, }, Data: configMap.Data, } @@ -136,7 +136,7 @@ var _ = Describe("Clustersummary Predicates: ConfigMapPredicates", func() { oldConfigMap := &corev1.ConfigMap{ ObjectMeta: metav1.ObjectMeta{ Name: configMap.Name, - Labels: map[string]string{"env": "testing"}, + Labels: map[string]string{testEnvLabelKey: testTestingValue}, }, BinaryData: configMap.BinaryData, } @@ -153,7 +153,7 @@ var _ = Describe("Clustersummary Predicates: ConfigMapPredicates", func() { It("Update returns true when annotations changed", func() { configMapPredicate := controllers.ConfigMapPredicates(logger) configMap.Annotations = map[string]string{ - libsveltosv1beta1.PolicyTemplateAnnotation: "true", + libsveltosv1beta1.PolicyTemplateAnnotation: testTrueValue, } oldConfigMap := &corev1.ConfigMap{ @@ -210,7 +210,7 @@ var _ = Describe("Clustersummary Predicates: SecretPredicates", func() { It("Update returns true when data has changed", func() { secretPredicate := controllers.SecretPredicates(logger) str := base64.StdEncoding.EncodeToString([]byte("password")) - secret.Data = map[string][]byte{"change": []byte(str)} + secret.Data = map[string][]byte{testChangeKey: []byte(str)} oldSecret := &corev1.Secret{ ObjectMeta: metav1.ObjectMeta{ @@ -233,7 +233,7 @@ var _ = Describe("Clustersummary Predicates: SecretPredicates", func() { oldSecret := &corev1.Secret{ ObjectMeta: metav1.ObjectMeta{ Name: secret.Name, - Labels: map[string]string{"env": "testing"}, + Labels: map[string]string{testEnvLabelKey: testTestingValue}, }, } @@ -249,7 +249,7 @@ var _ = Describe("Clustersummary Predicates: SecretPredicates", func() { It("Update returns true when annotations changed", func() { secretPredicate := controllers.SecretPredicates(logger) secret.Annotations = map[string]string{ - libsveltosv1beta1.PolicyTemplateAnnotation: "true", + libsveltosv1beta1.PolicyTemplateAnnotation: testTrueValue, } oldSecret := &corev1.Secret{ diff --git a/controllers/conflicts.go b/controllers/conflicts.go index be6a5d01..01e71667 100644 --- a/controllers/conflicts.go +++ b/controllers/conflicts.go @@ -70,7 +70,7 @@ func requeueClusterSummary(ctx context.Context, featureID libsveltosv1beta1.Feat Client: c, Logger: logger, ClusterSummary: clusterSummary, - ControllerName: "clustersummary", + ControllerName: controllerNameClusterSummary, }) if err != nil { diff --git a/controllers/drift_detection_upgrade.go b/controllers/drift_detection_upgrade.go index d9e43839..60e4ed12 100644 --- a/controllers/drift_detection_upgrade.go +++ b/controllers/drift_detection_upgrade.go @@ -310,7 +310,7 @@ func skipUpgrading(ctx context.Context, c client.Client, cluster client.Object, func isDriftDetectionManagerDeployedInCluster(ctx context.Context, c client.Client) (bool, error) { deployment := &appsv1.Deployment{} // A test in pkg/drift-detection makes sure this name is correct - err := c.Get(ctx, types.NamespacedName{Namespace: getSveltosNamespace(), Name: "drift-detection-manager"}, deployment) + err := c.Get(ctx, types.NamespacedName{Namespace: getSveltosNamespace(), Name: driftDetectionManagerDeploymentName}, deployment) if err != nil { if apierrors.IsNotFound(err) { diff --git a/controllers/drift_detection_upgrade_test.go b/controllers/drift_detection_upgrade_test.go index c441c7cb..6a11c4ec 100644 --- a/controllers/drift_detection_upgrade_test.go +++ b/controllers/drift_detection_upgrade_test.go @@ -104,7 +104,7 @@ var _ = Describe("Drift Detection Upgrade", func() { Name: sveltosClusterPaused.Name + sveltosKubeconfigPostfix, }, Data: map[string][]byte{ - "value": testEnv.Kubeconfig, + testValueKey: testEnv.Kubeconfig, }, } Expect(testEnv.Create(context.TODO(), secret)).To(Succeed()) @@ -116,7 +116,7 @@ var _ = Describe("Drift Detection Upgrade", func() { Name: sveltosClusterNotReady.Name + sveltosKubeconfigPostfix, }, Data: map[string][]byte{ - "value": testEnv.Kubeconfig, + testValueKey: testEnv.Kubeconfig, }, } Expect(testEnv.Create(context.TODO(), secret)).To(Succeed()) @@ -128,7 +128,7 @@ var _ = Describe("Drift Detection Upgrade", func() { Name: capiClusterPaused.Name + kubeconfigPostfix, }, Data: map[string][]byte{ - "value": testEnv.Kubeconfig, + testValueKey: testEnv.Kubeconfig, }, } Expect(testEnv.Create(context.TODO(), secret)).To(Succeed()) @@ -156,10 +156,10 @@ var _ = Describe("Drift Detection Upgrade", func() { It("isDriftDetectionManagerDeployedInCluster returns true when drift-detection-manager deployment exists", func() { depl := &appsv1.Deployment{ ObjectMeta: metav1.ObjectMeta{ - Name: "drift-detection-manager", + Name: testDriftDetectionManagerName, Namespace: sveltosNamespace, Labels: map[string]string{ - "control-plane": "drift-detection-manager", + testControlPlaneLabel: testDriftDetectionManagerName, }, }, } @@ -173,7 +173,7 @@ var _ = Describe("Drift Detection Upgrade", func() { Name: "some-other-deployment", Namespace: sveltosNamespace, Labels: map[string]string{ - "control-plane": "drift-detection-manager", + testControlPlaneLabel: testDriftDetectionManagerName, }, }, } @@ -184,10 +184,10 @@ var _ = Describe("Drift Detection Upgrade", func() { It("isDriftDetectionManagerDeployedInCluster returns false when deployment is in wrong namespace", func() { depl := &appsv1.Deployment{ ObjectMeta: metav1.ObjectMeta{ - Name: "drift-detection-manager", - Namespace: "default", + Name: testDriftDetectionManagerName, + Namespace: defaultNamespace, Labels: map[string]string{ - "control-plane": "drift-detection-manager", + testControlPlaneLabel: testDriftDetectionManagerName, }, }, } diff --git a/controllers/handlers_helm.go b/controllers/handlers_helm.go index 37804fc5..ee2a49c4 100644 --- a/controllers/handlers_helm.go +++ b/controllers/handlers_helm.go @@ -1531,7 +1531,6 @@ func handleInstall(ctx context.Context, dCtx *deploymentContext, logger.V(logs.LogDebug).Info("install helm release") - //nolint: gosec // maxHistory is guaranteed to be non-negative maxHistory := uint(getMaxHistoryValue(currentChart.Options)) if !isPullMode { @@ -2293,7 +2292,7 @@ func upgradeCRDsInFile(ctx context.Context, dr dynamic.ResourceInterface, chartF forceConflict := true options := metav1.PatchOptions{ - FieldManager: "application/apply-patch", + FieldManager: applyPatchFieldManager, Force: &forceConflict, } @@ -3815,7 +3814,7 @@ func parseAndAppendResources(yamlStr string, logger logr.Logger) ([]*unstructure return nil, err } - if policy.GetKind() == "List" && policy.GetAPIVersion() == "v1" { + if policy.GetKind() == "List" && policy.GetAPIVersion() == coreAPIVersion { list := &corev1.List{} if err := runtime.DefaultUnstructuredConverter.FromUnstructured(policy.Object, list); err != nil { return nil, err @@ -4271,7 +4270,7 @@ func getHelmUpgradeClient(requestedChart *configv1beta1.HelmChart, actionConfig upgradeClient.CaFile = registryOptions.caPath upgradeClient.PassCredentialsAll = getPassCredentialsToAllValue(requestedChart.Options) upgradeClient.TakeOwnership = getTakeOwnershipHelmValue(requestedChart.Options, true) - upgradeClient.ServerSideApply = "true" + upgradeClient.ServerSideApply = stringTrue upgradeClient.ForceConflicts = true if actionConfig.RegistryClient != nil { diff --git a/controllers/handlers_helm_test.go b/controllers/handlers_helm_test.go index 86d84b53..e0ee4c2a 100644 --- a/controllers/handlers_helm_test.go +++ b/controllers/handlers_helm_test.go @@ -53,8 +53,6 @@ var _ = Describe("HandlersHelm", func() { var clusterProfile *configv1beta1.ClusterProfile var clusterSummary *configv1beta1.ClusterSummary - const defaultNamespace = "default" - BeforeEach(func() { clusterNamespace := randomString() @@ -81,7 +79,7 @@ var _ = Describe("HandlersHelm", func() { { Kind: configv1beta1.ClusterProfileKind, Name: clusterProfile.Name, - APIVersion: "config.projectsveltos.io/v1beta1", + APIVersion: testConfigAPIVersion, UID: types.UID(randomString()), }, }, @@ -97,10 +95,10 @@ var _ = Describe("HandlersHelm", func() { It("shouldInstall returns false when requested version does not match installed version", func() { currentRelease := &controllers.ReleaseInfo{ Status: releasecommon.StatusDeployed.String(), - ChartVersion: "v2.5.0", + ChartVersion: testChartVersion250, } requestChart := &configv1beta1.HelmChart{ - ChartVersion: "v2.5.3", + ChartVersion: testChartVersion253, HelmChartAction: configv1beta1.HelmChartActionInstall, } Expect(controllers.ShouldInstall(currentRelease, requestChart)).To(BeFalse()) @@ -110,10 +108,10 @@ var _ = Describe("HandlersHelm", func() { func() { currentRelease := &controllers.ReleaseInfo{ Status: releasecommon.StatusDeployed.String(), - ChartVersion: "v2.5.3", + ChartVersion: testChartVersion253, } requestChart := &configv1beta1.HelmChart{ - ChartVersion: "v2.5.3", + ChartVersion: testChartVersion253, HelmChartAction: configv1beta1.HelmChartActionInstall, } Expect(controllers.ShouldInstall(currentRelease, requestChart)).To(BeFalse()) @@ -121,7 +119,7 @@ var _ = Describe("HandlersHelm", func() { It("shouldInstall returns true when there is no current installed version", func() { requestChart := &configv1beta1.HelmChart{ - ChartVersion: "v2.5.3", + ChartVersion: testChartVersion253, HelmChartAction: configv1beta1.HelmChartActionInstall, } Expect(controllers.ShouldInstall(nil, requestChart)).To(BeTrue()) @@ -129,7 +127,7 @@ var _ = Describe("HandlersHelm", func() { It("shouldInstall returns false action is uninstall", func() { requestChart := &configv1beta1.HelmChart{ - ChartVersion: "v2.5.3", + ChartVersion: testChartVersion253, HelmChartAction: configv1beta1.HelmChartActionUninstall, } Expect(controllers.ShouldInstall(nil, requestChart)).To(BeFalse()) @@ -137,7 +135,7 @@ var _ = Describe("HandlersHelm", func() { It("shouldUninstall returns false when there is no current release installed", func() { requestChart := &configv1beta1.HelmChart{ - ChartVersion: "v2.5.3", + ChartVersion: testChartVersion253, HelmChartAction: configv1beta1.HelmChartActionUninstall, } Expect(controllers.ShouldUninstall(nil, requestChart)).To(BeFalse()) @@ -146,10 +144,10 @@ var _ = Describe("HandlersHelm", func() { It("shouldUninstall returns false when action is not Uninstall", func() { currentRelease := &controllers.ReleaseInfo{ Status: releasecommon.StatusDeployed.String(), - ChartVersion: "v2.5.3", + ChartVersion: testChartVersion253, } requestChart := &configv1beta1.HelmChart{ - ChartVersion: "v2.5.3", + ChartVersion: testChartVersion253, HelmChartAction: configv1beta1.HelmChartActionInstall, } Expect(controllers.ShouldUninstall(currentRelease, requestChart)).To(BeFalse()) @@ -158,10 +156,10 @@ var _ = Describe("HandlersHelm", func() { It("shouldUpgrade returns true when installed release is different than requested release", func() { currentRelease := &controllers.ReleaseInfo{ Status: releasecommon.StatusDeployed.String(), - ChartVersion: "v2.5.0", + ChartVersion: testChartVersion250, } requestChart := &configv1beta1.HelmChart{ - ChartVersion: "v2.5.3", + ChartVersion: testChartVersion253, HelmChartAction: configv1beta1.HelmChartActionInstall, } Expect(controllers.ShouldUpgrade(context.TODO(), currentRelease, requestChart, @@ -171,21 +169,21 @@ var _ = Describe("HandlersHelm", func() { It("desiredValuesAreSubset returns true when desired is a subset of full values", func() { full := map[string]interface{}{ - "replicaCount": 2, - "image": map[string]interface{}{ - "repository": "nginx", - "tag": "1.21", - "pullPolicy": "IfNotPresent", + testReplicaCountKey: 2, + testImageKey: map[string]interface{}{ + testRepositoryKey: testNginxRepo, + testTagKey: "1.21", + "pullPolicy": "IfNotPresent", }, - "service": map[string]interface{}{ - "port": 80, + testServiceKey: map[string]interface{}{ + testPortKey: 80, }, } // Desired only sets a subset — tag and pullPolicy come from chart defaults. desired := map[string]interface{}{ - "replicaCount": 2, - "image": map[string]interface{}{ - "repository": "nginx", + testReplicaCountKey: 2, + testImageKey: map[string]interface{}{ + testRepositoryKey: testNginxRepo, }, } Expect(controllers.DesiredValuesAreSubset(desired, full)).To(BeTrue()) @@ -193,32 +191,32 @@ var _ = Describe("HandlersHelm", func() { It("desiredValuesAreSubset returns false when a desired value differs from full", func() { full := map[string]interface{}{ - "replicaCount": 2, + testReplicaCountKey: 2, } desired := map[string]interface{}{ - "replicaCount": 3, + testReplicaCountKey: 3, } Expect(controllers.DesiredValuesAreSubset(desired, full)).To(BeFalse()) }) It("desiredValuesAreSubset returns false when a desired key is absent from full", func() { full := map[string]interface{}{ - "replicaCount": 2, + testReplicaCountKey: 2, } desired := map[string]interface{}{ - "replicaCount": 2, - "extraKey": "value", + testReplicaCountKey: 2, + "extraKey": testValueKey, } Expect(controllers.DesiredValuesAreSubset(desired, full)).To(BeFalse()) }) It("desiredValuesAreSubset returns false when desired value is a map but full value is a scalar", func() { full := map[string]interface{}{ - "image": "nginx:latest", // scalar, not a map + testImageKey: testNginxLatestImage, // scalar, not a map } desired := map[string]interface{}{ - "image": map[string]interface{}{ - "repository": "nginx", + testImageKey: map[string]interface{}{ + testRepositoryKey: testNginxRepo, }, } Expect(controllers.DesiredValuesAreSubset(desired, full)).To(BeFalse()) @@ -226,12 +224,12 @@ var _ = Describe("HandlersHelm", func() { It("desiredValuesAreSubset returns false when desired value is a scalar but full value is a map", func() { full := map[string]interface{}{ - "image": map[string]interface{}{ - "repository": "nginx", + testImageKey: map[string]interface{}{ + testRepositoryKey: testNginxRepo, }, } desired := map[string]interface{}{ - "image": "nginx:latest", // scalar, not a map + testImageKey: testNginxLatestImage, // scalar, not a map } Expect(controllers.DesiredValuesAreSubset(desired, full)).To(BeFalse()) }) @@ -257,12 +255,12 @@ var _ = Describe("HandlersHelm", func() { // Sveltos desires no values (empty), which is a subset of anything. currentRelease := &controllers.ReleaseInfo{ Status: releasecommon.StatusDeployed.String(), - ChartVersion: "v1.0.0", + ChartVersion: testChartVersion100, Values: map[string]interface{}{}, - FullValues: map[string]interface{}{"replicaCount": 1, "service": map[string]interface{}{"port": 80}}, + FullValues: map[string]interface{}{testReplicaCountKey: 1, testServiceKey: map[string]interface{}{testPortKey: 80}}, } requestChart := &configv1beta1.HelmChart{ - ChartVersion: "v1.0.0", + ChartVersion: testChartVersion100, HelmChartAction: configv1beta1.HelmChartActionInstall, } @@ -289,11 +287,11 @@ var _ = Describe("HandlersHelm", func() { currentRelease := &controllers.ReleaseInfo{ Status: releasecommon.StatusDeployed.String(), - ChartVersion: "v1.0.0", - FullValues: map[string]interface{}{"replicaCount": 1}, + ChartVersion: testChartVersion100, + FullValues: map[string]interface{}{testReplicaCountKey: 1}, } requestChart := &configv1beta1.HelmChart{ - ChartVersion: "v1.0.0", + ChartVersion: testChartVersion100, HelmChartAction: configv1beta1.HelmChartActionInstall, Values: "replicaCount: 3\n", // desired differs from live } @@ -319,7 +317,7 @@ var _ = Describe("HandlersHelm", func() { currentRelease := &controllers.ReleaseInfo{ Status: releasecommon.StatusDeployed.String(), - ChartVersion: "v1.0.0", + ChartVersion: testChartVersion100, FullValues: map[string]interface{}{}, } requestChart := &configv1beta1.HelmChart{ @@ -355,11 +353,11 @@ var _ = Describe("HandlersHelm", func() { currentRelease := &controllers.ReleaseInfo{ Status: releasecommon.StatusDeployed.String(), - ChartVersion: "v1.0.0", - FullValues: map[string]interface{}{"replicaCount": 1}, + ChartVersion: testChartVersion100, + FullValues: map[string]interface{}{testReplicaCountKey: 1}, } requestChart := &configv1beta1.HelmChart{ - ChartVersion: "v1.0.0", + ChartVersion: testChartVersion100, HelmChartAction: configv1beta1.HelmChartActionInstall, } @@ -387,8 +385,8 @@ var _ = Describe("HandlersHelm", func() { clusterSummary.Spec.ClusterProfileSpec.SyncMode = configv1beta1.SyncModeContinuousWithDriftDetection clusterSummary.Status.HelmReleaseSummaries = []configv1beta1.HelmChartSummary{ { - ReleaseName: "nginx-latest", - ReleaseNamespace: "nginx", + ReleaseName: testReleaseNameNginxLatest, + ReleaseNamespace: testNginxRepo, ValuesHash: []byte("previously-stored-hash"), Status: configv1beta1.HelmChartStatusManaging, }, @@ -396,13 +394,13 @@ var _ = Describe("HandlersHelm", func() { currentRelease := &controllers.ReleaseInfo{ Status: releasecommon.StatusDeployed.String(), - ChartVersion: "v1.0.0", - FullValues: map[string]interface{}{"replicaCount": 1}, + ChartVersion: testChartVersion100, + FullValues: map[string]interface{}{testReplicaCountKey: 1}, } requestChart := &configv1beta1.HelmChart{ - ReleaseName: "nginx-latest", - ReleaseNamespace: "nginx", - ChartVersion: "v1.0.0", + ReleaseName: testReleaseNameNginxLatest, + ReleaseNamespace: testNginxRepo, + ChartVersion: testChartVersion100, HelmChartAction: configv1beta1.HelmChartActionInstall, } @@ -435,7 +433,7 @@ var _ = Describe("HandlersHelm", func() { path: /metadata/annotations/projectsveltos.io~1managed value: "true"`, Target: &libsveltosv1beta1.PatchSelector{ - Kind: "Deployment", + Kind: testKindDeployment, }, }, } @@ -444,11 +442,11 @@ var _ = Describe("HandlersHelm", func() { // first-reconciliation skip would fire if there were no patches. currentRelease := &controllers.ReleaseInfo{ Status: releasecommon.StatusDeployed.String(), - ChartVersion: "v1.0.0", - FullValues: map[string]interface{}{"replicaCount": 1}, + ChartVersion: testChartVersion100, + FullValues: map[string]interface{}{testReplicaCountKey: 1}, } requestChart := &configv1beta1.HelmChart{ - ChartVersion: "v1.0.0", + ChartVersion: testChartVersion100, HelmChartAction: configv1beta1.HelmChartActionInstall, } @@ -463,14 +461,14 @@ var _ = Describe("HandlersHelm", func() { RepositoryName: "projectcalico", ChartName: "projectcalico/tigera-operator", ChartVersion: "v3.24.1", - ReleaseName: "calico", - ReleaseNamespace: "calico", + ReleaseName: testReleaseNameCalico, + ReleaseNamespace: testReleaseNameCalico, HelmChartAction: configv1beta1.HelmChartActionInstall, } kyvernoSummary := configv1beta1.HelmChartSummary{ - ReleaseName: "kyverno", - ReleaseNamespace: "kyverno", + ReleaseName: testReleaseNameKyverno, + ReleaseNamespace: testReleaseNameKyverno, Status: configv1beta1.HelmChartStatusManaging, } @@ -584,18 +582,18 @@ var _ = Describe("HandlersHelm", func() { It("UpdateStatusForNonReferencedHelmReleases updates ClusterSummary.Status.HelmReleaseSummaries", func() { contourChart := &configv1beta1.HelmChart{ - RepositoryURL: "https://charts.bitnami.com/bitnami", + RepositoryURL: testRepoURLBitnami, RepositoryName: "bitnami/contour", - ChartName: "bitnami/contour", - ChartVersion: "21.1.4", - ReleaseName: "contour-latest", + ChartName: testChartNameBitnamiContour, + ChartVersion: testChartVersion2114, + ReleaseName: testReleaseNameContour, ReleaseNamespace: "contour", HelmChartAction: configv1beta1.HelmChartActionInstall, } kyvernoSummary := configv1beta1.HelmChartSummary{ - ReleaseName: "kyverno", - ReleaseNamespace: "kyverno", + ReleaseName: testReleaseNameKyverno, + ReleaseNamespace: testReleaseNameKyverno, Status: configv1beta1.HelmChartStatusManaging, } @@ -688,8 +686,8 @@ var _ = Describe("HandlersHelm", func() { chartDeployed := []configv1beta1.Chart{ { RepoURL: "https://charts.bitnami.com/bitnami", - ReleaseName: "contour-latest", - ChartVersion: "21.1.4", + ReleaseName: testReleaseNameContour, + ChartVersion: testChartVersion2114, Namespace: "projectcontour", }, } @@ -749,15 +747,15 @@ var _ = Describe("HandlersHelm", func() { chartsDeployed := []configv1beta1.Chart{ { RepoURL: "https://prometheus-community.github.io/helm-charts", - ReleaseName: "prometheus", - Namespace: "prometheus", + ReleaseName: testReleaseNamePrometheus, + Namespace: testReleaseNamePrometheus, ChartVersion: "26.0.0", AppVersion: "v3.0.0", }, { RepoURL: "https://grafana-community.github.io/helm-charts", - ReleaseName: "grafana", - Namespace: "grafana", + ReleaseName: testReleaseNameGrafana, + Namespace: testReleaseNameGrafana, ChartVersion: "11.3.6", AppVersion: "12.4.2", }, @@ -1031,7 +1029,7 @@ var _ = Describe("HandlersHelm", func() { { Kind: configv1beta1.ClusterProfileKind, Name: clusterProfile.Name, - APIVersion: "config.projectsveltos.io/v1beta1", + APIVersion: testConfigAPIVersion, UID: clusterProfile.UID, }, } @@ -1102,11 +1100,11 @@ var _ = Describe("Hash methods", func() { It("HelmHash returns hash considering all referenced helm charts", func() { kyvernoChart := configv1beta1.HelmChart{ RepositoryURL: "https://kyverno.github.io/kyverno/", - RepositoryName: "kyverno", + RepositoryName: testReleaseNameKyverno, ChartName: "kyverno/kyverno", ChartVersion: "v3.0.1", ReleaseName: "kyverno-latest", - ReleaseNamespace: "kyverno", + ReleaseNamespace: testReleaseNameKyverno, HelmChartAction: configv1beta1.HelmChartActionInstall, } @@ -1115,8 +1113,8 @@ var _ = Describe("Hash methods", func() { RepositoryName: "nginx-stable", ChartName: "nginx-stable/nginx-ingress", ChartVersion: "0.17.1", - ReleaseName: "nginx-latest", - ReleaseNamespace: "nginx", + ReleaseName: testReleaseNameNginxLatest, + ReleaseNamespace: testNginxRepo, HelmChartAction: configv1beta1.HelmChartActionInstall, } @@ -1154,9 +1152,7 @@ var _ = Describe("Hash methods", func() { }, Patches: []libsveltosv1beta1.Patch{ { - Patch: `- op: add - path: /metadata/labels/environment - value: production`, + Patch: testEnvLabelPatch, }, }, Tier: 100, @@ -1170,7 +1166,7 @@ var _ = Describe("Hash methods", func() { Client: testEnv, Logger: textlogger.NewLogger(textlogger.NewConfig()), ClusterSummary: clusterSummary, - ControllerName: "clustersummary", + ControllerName: testControllerNameSummary, }) Expect(err).To(BeNil()) @@ -1224,7 +1220,7 @@ var _ = Describe("Hash methods", func() { Namespace: namespace, Name: randomString(), Annotations: map[string]string{ - "projectsveltos.io/template": "ok", + libsveltosv1beta1.PolicyTemplateAnnotation: testOkValue, }, }, Data: map[string]string{ @@ -1334,7 +1330,7 @@ resources: Namespace: namespace, Name: randomString(), Annotations: map[string]string{ - "projectsveltos.io/template": "ok", + libsveltosv1beta1.PolicyTemplateAnnotation: testOkValue, }, }, Data: map[string]string{ @@ -1455,7 +1451,7 @@ resources: { Kind: configv1beta1.ClusterProfileKind, Name: randomString(), - APIVersion: "config.projectsveltos.io/v1beta1", + APIVersion: testConfigAPIVersion, UID: types.UID(randomString()), }, }, @@ -1529,7 +1525,7 @@ resources: Namespace: ns.Name, }, Data: map[string]string{ - "value": readyToUse, + testValueKey: readyToUse, }, } @@ -1538,11 +1534,11 @@ resources: Name: randomString(), Namespace: ns.Name, Annotations: map[string]string{ - "projectsveltos.io/template": "ok", + libsveltosv1beta1.PolicyTemplateAnnotation: testOkValue, }, }, Data: map[string]string{ - "value": toInstantiate, + testValueKey: toInstantiate, }, } @@ -1610,7 +1606,7 @@ resources: cached := &configv1beta1.HelmChart{ ReleaseName: chart.ReleaseName, ReleaseNamespace: chart.ReleaseNamespace, - ChartVersion: "1.19.0", + ChartVersion: testChartVersion119, } manager.RegisterVersionForChart(cs.Spec.ClusterNamespace, cs.Spec.ClusterName, cached) @@ -1628,7 +1624,7 @@ resources: cached := &configv1beta1.HelmChart{ ReleaseName: chart.ReleaseName, ReleaseNamespace: chart.ReleaseNamespace, - ChartVersion: "1.19.0", + ChartVersion: testChartVersion119, } manager.RegisterVersionForChart(cs.Spec.ClusterNamespace, cs.Spec.ClusterName, cached) @@ -1885,7 +1881,7 @@ var _ = Describe("allMatchingProfilesProcessed", func() { ObjectMeta: metav1.ObjectMeta{ Name: clusterName, Namespace: clusterNamespace, - Labels: map[string]string{"env": "production"}, + Labels: map[string]string{testEnvLabelKey: testProductionValue}, }, } @@ -1917,7 +1913,7 @@ var _ = Describe("allMatchingProfilesProcessed", func() { Spec: configv1beta1.Spec{ ClusterSelector: libsveltosv1beta1.Selector{ LabelSelector: metav1.LabelSelector{ - MatchLabels: map[string]string{"env": "staging"}, + MatchLabels: map[string]string{testEnvLabelKey: "staging"}, }, }, HelmCharts: []configv1beta1.HelmChart{ @@ -1958,7 +1954,7 @@ var _ = Describe("allMatchingProfilesProcessed", func() { Spec: configv1beta1.Spec{ ClusterSelector: libsveltosv1beta1.Selector{ LabelSelector: metav1.LabelSelector{ - MatchLabels: map[string]string{"env": "production"}, + MatchLabels: map[string]string{testEnvLabelKey: testProductionValue}, }, }, HelmCharts: []configv1beta1.HelmChart{ @@ -1986,7 +1982,7 @@ var _ = Describe("allMatchingProfilesProcessed", func() { Spec: configv1beta1.Spec{ ClusterSelector: libsveltosv1beta1.Selector{ LabelSelector: metav1.LabelSelector{ - MatchLabels: map[string]string{"env": "production"}, + MatchLabels: map[string]string{testEnvLabelKey: testProductionValue}, }, }, HelmCharts: []configv1beta1.HelmChart{ diff --git a/controllers/handlers_kustomize_test.go b/controllers/handlers_kustomize_test.go index c577908e..70be9017 100644 --- a/controllers/handlers_kustomize_test.go +++ b/controllers/handlers_kustomize_test.go @@ -63,7 +63,7 @@ var _ = Describe("KustomizeRefs", func() { Name: upstreamClusterNamePrefix + randomString(), Namespace: namespace, Labels: map[string]string{ - "dc": "eng", + testDCLabelKey: testEngValue, }, }, } @@ -170,7 +170,7 @@ var _ = Describe("KustomizeRefs", func() { DeployedGroupVersionKind: []string{ "ServiceAccount.v1.", "ConfigMaps.v1.", - "ClusterRole.v1.rbac.authorization.k8s.io", + testClusterRoleKindV1, }, }, } @@ -266,8 +266,8 @@ var _ = Describe("Hash methods", func() { Name: randomString(), }, Data: map[string]string{ - "cluster-name": "{{ .Cluster.metadata.namespace }}-{{ .Cluster.metadata.name }}", - "region": "west", + testClusterNameKey: "{{ .Cluster.metadata.namespace }}-{{ .Cluster.metadata.name }}", + testRegionKey: "west", }, } Expect(testEnv.Create(context.TODO(), configMap)).To(Succeed()) @@ -278,8 +278,8 @@ var _ = Describe("Hash methods", func() { Name: randomString(), }, Data: map[string][]byte{ - "tag": []byte("a-tag"), - "version": []byte("a-version"), + "tag": []byte("a-tag"), + testVersionKey: []byte("a-version"), }, Type: libsveltosv1beta1.ClusterProfileSecretType, } @@ -287,7 +287,7 @@ var _ = Describe("Hash methods", func() { Expect(waitForObject(context.TODO(), testEnv, secret)).To(Succeed()) kustomizationRef := configv1beta1.KustomizationRef{ - Namespace: "default", + Namespace: defaultNamespace, Name: "kustomization", Kind: sourcev1.GitRepositoryKind, ValuesFrom: []configv1beta1.ValueFrom{ @@ -380,7 +380,7 @@ var _ = Describe("Hash methods", func() { Namespace: clusterSummary.Spec.ClusterNamespace, Name: clusterSummary.Spec.ClusterName, Labels: map[string]string{ - "region": region, + testRegionKey: region, }, }, Spec: clusterv1.ClusterSpec{ @@ -405,12 +405,12 @@ var _ = Describe("Hash methods", func() { uCluster.SetUnstructuredContent(content) mgmtResources := map[string]*unstructured.Unstructured{ - "Cluster": &uCluster, + clusterKind: &uCluster, } values := map[string]string{ - `region`: `{{ index .Cluster.metadata.labels "region" }}`, - `version`: `{{ .Cluster.spec.topology.version }}`, + testRegionKey: testRegionLabelTemplate, + testVersionKey: `{{ .Cluster.spec.topology.version }}`, `cidrs`: `{{ range $cidr := .Cluster.spec.clusterNetwork.pods.cidrBlocks }} - cidr: {{ $cidr }} encapsulation: VXLAN @@ -426,11 +426,11 @@ var _ = Describe("Hash methods", func() { controllers.NewDeploymentContext(clusterSummary, clusterObjects, mgmtResources), values, textlogger.NewLogger(textlogger.NewConfig())) Expect(err).To(BeNil()) - v, ok := result["region"] + v, ok := result[testRegionKey] Expect(ok).To(BeTrue()) Expect(v).To(Equal(region)) - v, ok = result["version"] + v, ok = result[testVersionKey] Expect(ok).To(BeTrue()) Expect(v).To(Equal(k8sVersion)) diff --git a/controllers/handlers_resources_test.go b/controllers/handlers_resources_test.go index 9bd1b315..a9c884bf 100644 --- a/controllers/handlers_resources_test.go +++ b/controllers/handlers_resources_test.go @@ -55,7 +55,7 @@ var _ = Describe("HandlersResource", func() { Name: upstreamClusterNamePrefix + randomString(), Namespace: namespace, Labels: map[string]string{ - "dc": "eng", + testDCLabelKey: testEngValue, }, }, } @@ -219,7 +219,7 @@ var _ = Describe("HandlersResource", func() { { FeatureID: libsveltosv1beta1.FeatureResources, DeployedGroupVersionKind: []string{ - "ClusterRole.v1.rbac.authorization.k8s.io", + testClusterRoleKindV1, "Role.v1.rbac.authorization.k8s.io", }, }, @@ -323,8 +323,8 @@ var _ = Describe("Hash methods", func() { Name: "clusterrole1", }, Rules: []rbacv1.PolicyRule{ - {Verbs: []string{"create", "get"}, APIGroups: []string{"cert-manager.io"}, Resources: []string{"certificaterequests"}}, - {Verbs: []string{"create", "delete"}, APIGroups: []string{""}, Resources: []string{"namespaces", "deployments"}}, + {Verbs: []string{testCreateVerb, testGetVerb}, APIGroups: []string{testCertManagerGroup}, Resources: []string{testCertificateRequestsResource}}, + {Verbs: []string{testCreateVerb, testDeleteVerb}, APIGroups: []string{""}, Resources: []string{testNamespacesResource, testDeploymentsResource}}, }, } @@ -374,15 +374,13 @@ var _ = Describe("Hash methods", func() { Kind: string(libsveltosv1beta1.ConfigMapReferencedResourceKind), }, { - Namespace: "default", Name: "non-existing", + Namespace: defaultNamespace, Name: "non-existing", Kind: string(libsveltosv1beta1.ConfigMapReferencedResourceKind), }, }, Patches: []libsveltosv1beta1.Patch{ { - Patch: `- op: add - path: /metadata/labels/environment - value: production`, + Patch: testEnvLabelPatch, }, }, Tier: 100, @@ -405,7 +403,7 @@ var _ = Describe("Hash methods", func() { Client: testEnv, Logger: textlogger.NewLogger(textlogger.NewConfig()), ClusterSummary: clusterSummary, - ControllerName: "clustersummary", + ControllerName: testControllerNameSummary, }) Expect(err).To(BeNil()) diff --git a/controllers/handlers_utils.go b/controllers/handlers_utils.go index d22e7d9a..47b28226 100644 --- a/controllers/handlers_utils.go +++ b/controllers/handlers_utils.go @@ -759,7 +759,7 @@ func collectReferencedObjects(references []configv1beta1.PolicyRef) (local, remo switch reference.Kind { case string(libsveltosv1beta1.ConfigMapReferencedResourceKind): object.ObjectReference = corev1.ObjectReference{ - APIVersion: "v1", + APIVersion: coreAPIVersion, Kind: string(libsveltosv1beta1.ConfigMapReferencedResourceKind), Namespace: reference.Namespace, Name: reference.Name, @@ -769,7 +769,7 @@ func collectReferencedObjects(references []configv1beta1.PolicyRef) (local, remo object.SkipNamespaceCreation = reference.SkipNamespaceCreation case string(libsveltosv1beta1.SecretReferencedResourceKind): object.ObjectReference = corev1.ObjectReference{ - APIVersion: "v1", + APIVersion: coreAPIVersion, Kind: string(libsveltosv1beta1.SecretReferencedResourceKind), Namespace: reference.Namespace, Name: reference.Name, diff --git a/controllers/handlers_utils_test.go b/controllers/handlers_utils_test.go index e4709058..a6b50ccd 100644 --- a/controllers/handlers_utils_test.go +++ b/controllers/handlers_utils_test.go @@ -225,7 +225,7 @@ var _ = Describe("HandlersUtils", func() { Expect(role.Labels[k]).To(Equal(clusterSummary.Name)) } - role.Labels = map[string]string{"reader": "ok"} + role.Labels = map[string]string{"reader": testOkValue} deployer.AddLabel(role, clusterops.ClusterSummaryLabelName, clusterSummary.Name) Expect(role.Labels).ToNot(BeNil()) Expect(len(role.Labels)).To(Equal(2)) @@ -308,11 +308,11 @@ var _ = Describe("HandlersUtils", func() { clusterSummary.Spec.ClusterProfileSpec.DriftExclusions = []libsveltosv1beta1.DriftExclusion{ { Target: &libsveltosv1beta1.PatchSelector{ - Kind: "Deployment", - Group: "apps", - Version: "v1", + Kind: testKindDeployment, + Group: testAppsGroup, + Version: testV1APIVersion, }, - Paths: []string{"/spec/replicas"}, + Paths: []string{testSpecReplicasPath}, }, } @@ -378,11 +378,11 @@ var _ = Describe("HandlersUtils", func() { clusterSummary.Spec.ClusterProfileSpec.DriftExclusions = []libsveltosv1beta1.DriftExclusion{ { Target: &libsveltosv1beta1.PatchSelector{ - Kind: "Deployment", - Group: "apps", - Version: "v1", + Kind: testKindDeployment, + Group: testAppsGroup, + Version: testV1APIVersion, }, - Paths: []string{"/spec/replicas"}, + Paths: []string{testSpecReplicasPath}, }, } @@ -445,11 +445,11 @@ var _ = Describe("HandlersUtils", func() { clusterSummary.Spec.ClusterProfileSpec.DriftExclusions = []libsveltosv1beta1.DriftExclusion{ { Target: &libsveltosv1beta1.PatchSelector{ - Kind: "Deployment", - Group: "apps", - Version: "v1", + Kind: testKindDeployment, + Group: testAppsGroup, + Version: testV1APIVersion, }, - Paths: []string{"/spec/replicas"}, + Paths: []string{testSpecReplicasPath}, }, } @@ -482,7 +482,7 @@ var _ = Describe("HandlersUtils", func() { isDriftDetection = clusterSummary.Spec.ClusterProfileSpec.SyncMode == configv1beta1.SyncModeContinuousWithDriftDetection // New deploy will not override replicas _, err = deployer.UpdateResource(context.TODO(), dr, isDriftDetection, isDryRun, clusterSummary.Spec.ClusterProfileSpec.DriftExclusions, - u, []string{"status"}, textlogger.NewLogger(textlogger.NewConfig())) + u, []string{testStatusField}, textlogger.NewLogger(textlogger.NewConfig())) Expect(err).To(BeNil()) Eventually(func() bool { @@ -560,7 +560,7 @@ var _ = Describe("HandlersUtils", func() { // as created (if the ClusterProfile were to be changed from DryRun, both services would be // created) resourceReports, err := controllers.DeployContent(context.TODO(), false, - testEnv.Config, testEnv.Client, secret, map[string]string{"service": services}, + testEnv.Config, testEnv.Client, secret, map[string]string{testServiceKey: services}, defaultTier, false, controllers.NewDeploymentContext(clusterSummary, clusterObjects, nil), textlogger.NewLogger(textlogger.NewConfig())) Expect(err).To(BeNil()) @@ -592,7 +592,7 @@ var _ = Describe("HandlersUtils", func() { // the secret referenced by ClusterProfile, both obejcts will be reported as no action // ( if the ClusterProfile were to be changed from DryRun, nothing would happen). resourceReports, err = controllers.DeployContent(context.TODO(), false, - testEnv.Config, testEnv.Client, secret, map[string]string{"service": services}, + testEnv.Config, testEnv.Client, secret, map[string]string{testServiceKey: services}, defaultTier, false, controllers.NewDeploymentContext(clusterSummary, clusterObjects, nil), textlogger.NewLogger(textlogger.NewConfig())) Expect(err).To(BeNil()) @@ -630,7 +630,7 @@ var _ = Describe("HandlersUtils", func() { // in the secret referenced by ClusterProfile, both services will be reported as updated // (if the ClusterProfile were to be changed from DryRun, both service would be updated). resourceReports, err = controllers.DeployContent(context.TODO(), false, - testEnv.Config, testEnv.Client, secret, map[string]string{"service": newContent}, + testEnv.Config, testEnv.Client, secret, map[string]string{testServiceKey: newContent}, defaultTier, false, controllers.NewDeploymentContext(clusterSummary, clusterObjects, nil), textlogger.NewLogger(textlogger.NewConfig())) Expect(err).To(BeNil()) @@ -641,7 +641,7 @@ var _ = Describe("HandlersUtils", func() { // and that is the one referenced by ClusterSummary. DeployContent will report conflicts in this case. tmpSecret := &corev1.Secret{ObjectMeta: metav1.ObjectMeta{Namespace: randomString(), Name: randomString()}} resourceReports, err = controllers.DeployContent(context.TODO(), false, - testEnv.Config, testEnv.Client, tmpSecret, map[string]string{"service": services}, + testEnv.Config, testEnv.Client, tmpSecret, map[string]string{testServiceKey: services}, defaultTier, false, controllers.NewDeploymentContext(clusterSummary, clusterObjects, nil), textlogger.NewLogger(textlogger.NewConfig())) Expect(err).To(BeNil()) @@ -746,7 +746,7 @@ var _ = Describe("HandlersUtils", func() { { FeatureID: libsveltosv1beta1.FeatureResources, DeployedGroupVersionKind: []string{ - "ClusterRole.v1.rbac.authorization.k8s.io", + testClusterRoleKindV1, }, }, } @@ -773,7 +773,7 @@ var _ = Describe("HandlersUtils", func() { }) clusterRole.SetOwnerReferences([]metav1.OwnerReference{ {Kind: configv1beta1.ClusterProfileKind, Name: clusterProfile.Name, - UID: clusterProfile.UID, APIVersion: "config.projectsveltos.io/v1beta1"}, + UID: clusterProfile.UID, APIVersion: testConfigAPIVersion}, }) Expect(testEnv.Create(context.TODO(), clusterRole)).To(Succeed()) Expect(waitForObject(ctx, testEnv.Client, clusterRole)).To(Succeed()) @@ -847,7 +847,7 @@ var _ = Describe("HandlersUtils", func() { clusterRole2 := &rbacv1.ClusterRole{ ObjectMeta: metav1.ObjectMeta{ Name: clusterRoleName2, - Namespace: "default", + Namespace: defaultNamespace, Labels: map[string]string{ deployer.ReasonLabel: string(libsveltosv1beta1.FeatureResources), }, @@ -871,7 +871,7 @@ var _ = Describe("HandlersUtils", func() { { FeatureID: libsveltosv1beta1.FeatureResources, DeployedGroupVersionKind: []string{ - "ClusterRole.v1.rbac.authorization.k8s.io", + testClusterRoleKindV1, }, }, } @@ -1018,7 +1018,6 @@ var _ = Describe("HandlersUtils", func() { It("adjustNamespace adjusts namespace for both namespaced and cluster wide resources", func() { logger := textlogger.NewLogger(textlogger.NewConfig()) - const defaultNamespace = "default" clusterName := randomString() cluster := &clusterv1.Cluster{ @@ -1036,7 +1035,7 @@ var _ = Describe("HandlersUtils", func() { Name: clusterName + kubeconfigPostfix, }, Data: map[string][]byte{ - "value": testEnv.Kubeconfig, + testValueKey: testEnv.Kubeconfig, }, } Expect(testEnv.Create(context.TODO(), secret)).To(Succeed()) @@ -1059,7 +1058,7 @@ metadata: libsveltosv1beta1.ClusterTypeCapi, false, textlogger.NewLogger(textlogger.NewConfig()))).To(BeNil()) // For namespaced resources if namespace is not set, namespace gets set to default - Expect(u.GetNamespace()).To(Equal("default")) + Expect(u.GetNamespace()).To(Equal(defaultNamespace)) clusterIssuer := `apiVersion: rbac.authorization.k8s.io/v1 kind: ClusterRole @@ -1261,7 +1260,7 @@ status: configMap := createConfigMapWithPolicy(namespace, randomString(), fmt.Sprintf(servicePatch, serviceName, namespace, key, value, key, value)) configMap.Annotations = map[string]string{ - "projectsveltos.io/subresources": "status"} + "projectsveltos.io/subresources": testStatusField} reference := &controllers.ReferencedObject{Tier: defaultTier, SkipNamespaceCreation: false} _, err := controllers.DeployContentOfConfigMap(context.TODO(), false, testEnv.Config, testEnv.Client, @@ -1351,7 +1350,7 @@ status: templateResourceRef := configv1beta1.TemplateResourceRef{ Resource: corev1.ObjectReference{ APIVersion: "apps/v1", - Kind: "Deployment", + Kind: testKindDeployment, Namespace: namespace, Name: name, }, @@ -1380,8 +1379,8 @@ status: Namespace: namespace, }, Data: map[string]string{ - "watched": "value1", - "unwatched": "value2", + testWatchedKey: testValue1, + "unwatched": testValue2, }, } Expect(testEnv.Create(context.TODO(), cm)).To(Succeed()) @@ -1390,13 +1389,13 @@ status: clusterSummary.Spec.ClusterProfileSpec.TemplateResourceRefs = []configv1beta1.TemplateResourceRef{ { Resource: corev1.ObjectReference{ - APIVersion: "v1", - Kind: "ConfigMap", + APIVersion: testV1APIVersion, + Kind: testKindConfigMap, Namespace: namespace, Name: cm.Name, }, Identifier: randomString(), - WatchFields: []string{"data.watched"}, + WatchFields: []string{testDataWatchedField}, }, } @@ -1425,7 +1424,7 @@ status: Namespace: namespace, }, Data: map[string]string{ - "watched": "value1", + testWatchedKey: testValue1, }, } Expect(testEnv.Create(context.TODO(), cm)).To(Succeed()) @@ -1434,13 +1433,13 @@ status: clusterSummary.Spec.ClusterProfileSpec.TemplateResourceRefs = []configv1beta1.TemplateResourceRef{ { Resource: corev1.ObjectReference{ - APIVersion: "v1", - Kind: "ConfigMap", + APIVersion: testV1APIVersion, + Kind: testKindConfigMap, Namespace: namespace, Name: cm.Name, }, Identifier: randomString(), - WatchFields: []string{"data.watched"}, + WatchFields: []string{testDataWatchedField}, }, } @@ -1453,7 +1452,7 @@ status: types.NamespacedName{Namespace: namespace, Name: cm.Name}, cm); err != nil { return err } - cm.Data["watched"] = randomString() + cm.Data[testWatchedKey] = randomString() return testEnv.Client.Update(context.TODO(), cm) })).To(Succeed()) @@ -1469,16 +1468,16 @@ status: Namespace: namespace, }, Data: map[string]string{ - "watched": "value1", - "other": "value2", + testWatchedKey: testValue1, + "other": testValue2, }, } Expect(testEnv.Create(context.TODO(), cm)).To(Succeed()) Expect(waitForObject(context.TODO(), testEnv.Client, cm)).To(Succeed()) ref := corev1.ObjectReference{ - APIVersion: "v1", - Kind: "ConfigMap", + APIVersion: testV1APIVersion, + Kind: testKindConfigMap, Namespace: namespace, Name: cm.Name, } @@ -1488,7 +1487,7 @@ status: { Resource: ref, Identifier: randomString(), - WatchFields: []string{"data.watched"}, + WatchFields: []string{testDataWatchedField}, IgnoreStatusChanges: true, }, } diff --git a/controllers/metrics.go b/controllers/metrics.go index 8a0d1459..c4d780dc 100644 --- a/controllers/metrics.go +++ b/controllers/metrics.go @@ -27,12 +27,22 @@ import ( logs "github.com/projectsveltos/libsveltos/lib/logsettings" ) +const ( + metricProgramResourcesName = "program_resources_time_seconds" + metricProgramResourcesHelp = "Program Resources on a workload cluster duration distribution" + metricProgramChartsName = "program_charts_time_seconds" + metricClusterNameLabel = "cluster_name" + metricClusterNamespaceLabel = "cluster_namespace" + metricClusterTypeLabel = "cluster_type" + metricFeatureLabel = "feature" +) + var ( programResourceDurationHistogram = prometheus.NewHistogram( prometheus.HistogramOpts{ Namespace: getSveltosNamespace(), - Name: "program_resources_time_seconds", - Help: "Program Resources on a workload cluster duration distribution", + Name: metricProgramResourcesName, + Help: metricProgramResourcesHelp, Buckets: []float64{0.5, 1, 1.5, 2, 3, 5, 10, 30, 60, 90, 120}, }, ) @@ -40,7 +50,7 @@ var ( programChartDurationHistogram = prometheus.NewHistogram( prometheus.HistogramOpts{ Namespace: getSveltosNamespace(), - Name: "program_charts_time_seconds", + Name: metricProgramChartsName, Help: "Program Helm charts on a workload cluster duration distribution", Buckets: []float64{0.5, 1, 1.5, 2, 3, 5, 10, 30, 60, 90, 120}, }, @@ -52,7 +62,7 @@ var ( Name: "reconcile_operations_total", Help: "Total number of reconcile operations for Helm, Resources, and Kustomization", }, - []string{"cluster_type", "cluster_namespace", "cluster_name", "feature"}, + []string{metricClusterTypeLabel, metricClusterNamespaceLabel, metricClusterNameLabel, metricFeatureLabel}, ) driftCounter = prometheus.NewCounterVec( @@ -61,7 +71,7 @@ var ( Name: "total_drifts", Help: "Total number of drifts for a given cluster indexed via type, namespace/name and feature id", }, - []string{"cluster_type", "cluster_namespace", "cluster_name", "feature"}, + []string{metricClusterTypeLabel, metricClusterNamespaceLabel, metricClusterNameLabel, metricFeatureLabel}, ) ) @@ -78,8 +88,8 @@ func newResourceHistogram(clusterNamespace, clusterName string, clusterType libs histogram := prometheus.NewHistogram( prometheus.HistogramOpts{ Namespace: clusterInfo, - Name: "program_resources_time_seconds", - Help: "Program Resources on a workload cluster duration distribution", + Name: metricProgramResourcesName, + Help: metricProgramResourcesHelp, Buckets: []float64{0.5, 1, 1.5, 2, 3, 5, 10, 30, 60, 90, 120}, }, ) @@ -110,7 +120,7 @@ func newChartHistogram(clusterNamespace, clusterName string, clusterType libsvel histogram := prometheus.NewHistogram( prometheus.HistogramOpts{ Namespace: clusterInfo, - Name: "program_charts_time_seconds", + Name: metricProgramChartsName, Help: "Program Helm Charts on a workload cluster duration distribution", Buckets: []float64{0.5, 1, 1.5, 2, 3, 5, 10, 30, 60, 90, 120}, }, @@ -170,10 +180,10 @@ func programDeployMetrics(elapsed time.Duration, clusterNamespace, clusterName, func trackReconciliation(clusterNamespace, clusterName, featureID string, clusterType libsveltosv1beta1.ClusterType, logger logr.Logger) { reconciliationCounter.With(prometheus.Labels{ - "cluster_type": string(clusterType), - "cluster_namespace": clusterNamespace, - "cluster_name": clusterName, - "feature": featureID, + metricClusterTypeLabel: string(clusterType), + metricClusterNamespaceLabel: clusterNamespace, + metricClusterNameLabel: clusterName, + metricFeatureLabel: featureID, }).Inc() logger.V(logs.LogVerbose).Info(fmt.Sprintf("Tracking reconciliation for %s %s/%s %s", @@ -182,10 +192,10 @@ func trackReconciliation(clusterNamespace, clusterName, featureID string, cluste func trackDrifts(clusterNamespace, clusterName, featureID, clusterType string, logger logr.Logger) { driftCounter.With(prometheus.Labels{ - "cluster_type": clusterType, - "cluster_namespace": clusterNamespace, - "cluster_name": clusterName, - "feature": featureID, + metricClusterTypeLabel: clusterType, + metricClusterNamespaceLabel: clusterNamespace, + metricClusterNameLabel: clusterName, + metricFeatureLabel: featureID, }).Inc() logger.V(logs.LogVerbose).Info(fmt.Sprintf("Tracking drifts for %s %s/%s %s", diff --git a/controllers/profile_utils_test.go b/controllers/profile_utils_test.go index db0dfd36..a94aad53 100644 --- a/controllers/profile_utils_test.go +++ b/controllers/profile_utils_test.go @@ -124,21 +124,21 @@ var _ = Describe("Profile: Reconciler", func() { Client: c, Logger: logger, Profile: clusterProfile, - ControllerName: "clusterprofile", + ControllerName: testControllerNameProfile, }) Expect(err).To(BeNil()) Expect(controllers.IsProfilePaused(profileScope)).To(BeFalse()) clusterProfile.Annotations = map[string]string{ - configv1beta1.ProfilePausedAnnotation: "true", + configv1beta1.ProfilePausedAnnotation: testTrueValue, } profileScope, err = scope.NewProfileScope(scope.ProfileScopeParams{ Client: c, Logger: logger, Profile: clusterProfile, - ControllerName: "clusterprofile", + ControllerName: testControllerNameProfile, }) Expect(err).To(BeNil()) @@ -161,7 +161,7 @@ var _ = Describe("Profile: Reconciler", func() { Client: c, Logger: logger, Profile: clusterProfile, - ControllerName: "clusterprofile", + ControllerName: testControllerNameProfile, }) Expect(err).To(BeNil()) @@ -364,7 +364,7 @@ var _ = Describe("Profile: Reconciler", func() { Client: c, Logger: logger, Profile: clusterProfile, - ControllerName: "clusterprofile", + ControllerName: testControllerNameProfile, }) Expect(err).To(BeNil()) @@ -449,7 +449,7 @@ var _ = Describe("Profile: Reconciler", func() { Client: c, Logger: logger, Profile: clusterProfile, - ControllerName: "clusterprofile", + ControllerName: testControllerNameProfile, }) Expect(err).To(BeNil()) @@ -521,7 +521,7 @@ var _ = Describe("Profile: Reconciler", func() { Client: c, Logger: logger, Profile: clusterProfile, - ControllerName: "clusterprofile", + ControllerName: testControllerNameProfile, }) Expect(err).To(BeNil()) @@ -590,7 +590,7 @@ var _ = Describe("Profile: Reconciler", func() { Client: c, Logger: logger, Profile: clusterProfile, - ControllerName: "clusterprofile", + ControllerName: testControllerNameProfile, }) Expect(err).To(BeNil()) @@ -653,7 +653,7 @@ var _ = Describe("Profile: Reconciler", func() { Client: c, Logger: logger, Profile: clusterProfile, - ControllerName: "clusterprofile", + ControllerName: testControllerNameProfile, }) Expect(err).To(BeNil()) @@ -709,7 +709,7 @@ var _ = Describe("Profile: Reconciler", func() { Client: c, Logger: logger, Profile: clusterProfile, - ControllerName: "clusterprofile", + ControllerName: testControllerNameProfile, }) Expect(err).To(BeNil()) @@ -800,7 +800,7 @@ var _ = Describe("Profile: Reconciler", func() { Client: c, Logger: logger, Profile: clusterProfile, - ControllerName: "clusterprofile", + ControllerName: testControllerNameProfile, }) Expect(err).To(BeNil()) @@ -841,7 +841,7 @@ var _ = Describe("Profile: Reconciler", func() { Client: c, Logger: logger, Profile: clusterProfile, - ControllerName: "clusterprofile", + ControllerName: testControllerNameProfile, }) Expect(err).To(BeNil()) @@ -878,7 +878,7 @@ var _ = Describe("Profile: Reconciler", func() { Client: c, Logger: logger, Profile: clusterProfile, - ControllerName: "clusterprofile", + ControllerName: testControllerNameProfile, }) Expect(err).To(BeNil()) @@ -951,7 +951,7 @@ var _ = Describe("Profile: Reconciler", func() { Client: c, Logger: logger, Profile: clusterProfile, - ControllerName: "clusterprofile", + ControllerName: testControllerNameProfile, }) Expect(err).To(BeNil()) @@ -988,7 +988,7 @@ var _ = Describe("Profile: Reconciler", func() { Client: c, Logger: logger, Profile: clusterProfile, - ControllerName: "clusterprofile", + ControllerName: testControllerNameProfile, }) Expect(err).To(BeNil()) @@ -1029,7 +1029,7 @@ var _ = Describe("Profile: Reconciler", func() { Client: c, Logger: logger, Profile: clusterProfile, - ControllerName: "clusterprofile", + ControllerName: testControllerNameProfile, }) Expect(err).To(BeNil()) @@ -1073,7 +1073,7 @@ var _ = Describe("Profile: Reconciler", func() { Client: c, Logger: logger, Profile: clusterProfile, - ControllerName: "clusterprofile", + ControllerName: testControllerNameProfile, }) Expect(err).To(BeNil()) @@ -1163,7 +1163,7 @@ var _ = Describe("Profile: Reconciler", func() { Client: c, Logger: logger, Profile: &profile, - ControllerName: "profile", + ControllerName: testControllerNameProfileShort, }) Expect(err).To(BeNil()) @@ -1260,7 +1260,7 @@ var _ = Describe("Profile: Reconciler", func() { Client: c, Logger: logger, Profile: &profile, - ControllerName: "profile", + ControllerName: testControllerNameProfileShort, }) Expect(err).To(BeNil()) @@ -1299,7 +1299,7 @@ var _ = Describe("Profile: Reconciler", func() { Client: c, Logger: logger, Profile: clusterProfile, - ControllerName: "clusterprofile", + ControllerName: testControllerNameProfile, }) Expect(err).To(BeNil()) @@ -1322,7 +1322,7 @@ var _ = Describe("Profile: Reconciler", func() { Client: c, Logger: logger, Profile: clusterProfile, - ControllerName: "clusterprofile", + ControllerName: testControllerNameProfile, }) Expect(err).To(BeNil()) @@ -1343,7 +1343,7 @@ var _ = Describe("Profile: Reconciler", func() { Client: c, Logger: logger, Profile: clusterProfile, - ControllerName: "clusterprofile", + ControllerName: testControllerNameProfile, }) Expect(err).To(BeNil()) @@ -1401,7 +1401,7 @@ var _ = Describe("Profile: Reconciler", func() { Client: c, Logger: logger, Profile: clusterProfile, - ControllerName: "clusterprofile", + ControllerName: testControllerNameProfile, }) Expect(err).To(BeNil()) controllers.ReviseUpdatedAndUpdatingClusters(clusterProfileScope) @@ -1448,7 +1448,7 @@ var _ = Describe("Profile: Reconciler", func() { Client: c, Logger: logger, Profile: clusterProfile, - ControllerName: "clusterprofile", + ControllerName: testControllerNameProfile, }) Expect(err).To(BeNil()) @@ -1511,7 +1511,7 @@ var _ = Describe("Profile: Reconciler", func() { Client: c, Logger: logger, Profile: clusterProfile, - ControllerName: "clusterprofile", + ControllerName: testControllerNameProfile, }) Expect(err).To(BeNil()) @@ -1559,7 +1559,7 @@ var _ = Describe("Profile: Reconciler", func() { Client: c, Logger: logger, Profile: clusterProfile, - ControllerName: "clusterprofile", + ControllerName: testControllerNameProfile, }) Expect(err).To(BeNil()) diff --git a/controllers/resourcesummary.go b/controllers/resourcesummary.go index fa785e13..e717e2d6 100644 --- a/controllers/resourcesummary.go +++ b/controllers/resourcesummary.go @@ -305,7 +305,7 @@ func deployDriftDetectionManagerResources(ctx context.Context, restConfig *rest. lbls map[string]string, patches []libsveltosv1beta1.Patch, logger logr.Logger) error { resources := make(map[string][]unstructured.Unstructured) - index := "drift-detection-manager" + index := driftDetectionManagerDeploymentName resources[index] = []unstructured.Unstructured{} elements, err := deployer.CustomSplit(driftDetectionManagerYAML) @@ -394,7 +394,7 @@ func deployUnstructuredResources(ctx context.Context, restConfig *rest.Config, } options := metav1.ApplyOptions{ - FieldManager: "application/apply-patch", + FieldManager: applyPatchFieldManager, Force: true, } @@ -429,7 +429,7 @@ func unDeployResourceSummaryInstance(ctx context.Context, clusterNamespace, clus resourceSummaryCRD := &apiextensionsv1.CustomResourceDefinition{} err = clusterClient.Get(ctx, - types.NamespacedName{Name: "resourcesummaries.lib.projectsveltos.io"}, resourceSummaryCRD) + types.NamespacedName{Name: resourceSummaryCRDName}, resourceSummaryCRD) if err != nil { if apierrors.IsNotFound(err) { logger.V(logs.LogVerbose).Info("resourceSummary CRD not present.") @@ -660,7 +660,7 @@ func getDriftDetectionManagerPatchesOld(ctx context.Context, c client.Client, Patch: configMap.Data[k], Target: &libsveltosv1beta1.PatchSelector{ Kind: deploymentKind, - Group: "apps", + Group: appsGroupName, }, } patches = append(patches, patch) @@ -777,7 +777,7 @@ func getPatchesFromConfigMap(configMap *corev1.ConfigMap, logger logr.Logger, if patch.Target == nil { patch.Target = &libsveltosv1beta1.PatchSelector{ Kind: "Deployment", - Group: "apps", + Group: appsGroupName, } } diff --git a/controllers/resourcesummary_collection.go b/controllers/resourcesummary_collection.go index 9e6832a8..ed53d9ef 100644 --- a/controllers/resourcesummary_collection.go +++ b/controllers/resourcesummary_collection.go @@ -416,7 +416,7 @@ func isResourceSummaryInstalledCached(ctx context.Context, c client.Client, func isResourceSummaryInstalled(ctx context.Context, c client.Client) (bool, error) { clusterCRD := &apiextensionsv1.CustomResourceDefinition{} - err := c.Get(ctx, types.NamespacedName{Name: "resourcesummaries.lib.projectsveltos.io"}, clusterCRD) + err := c.Get(ctx, types.NamespacedName{Name: resourceSummaryCRDName}, clusterCRD) if err != nil { if apierrors.IsNotFound(err) { return false, nil diff --git a/controllers/resourcesummary_collection_test.go b/controllers/resourcesummary_collection_test.go index 3b94a4dc..bb7589c9 100644 --- a/controllers/resourcesummary_collection_test.go +++ b/controllers/resourcesummary_collection_test.go @@ -156,7 +156,7 @@ var _ = Describe("ResourceSummary Collection", func() { crd := &apiextensionsv1.CustomResourceDefinition{ ObjectMeta: metav1.ObjectMeta{ - Name: "resourcesummaries.lib.projectsveltos.io", + Name: testResourceSummaryCRDName, }, } withCRD := fake.NewClientBuilder().WithScheme(scheme).WithObjects(crd).Build() @@ -179,7 +179,7 @@ var _ = Describe("ResourceSummary Collection", func() { crd := &apiextensionsv1.CustomResourceDefinition{ ObjectMeta: metav1.ObjectMeta{ - Name: "resourcesummaries.lib.projectsveltos.io", + Name: testResourceSummaryCRDName, }, } withCRD := fake.NewClientBuilder().WithScheme(scheme).WithObjects(crd).Build() @@ -275,7 +275,7 @@ var _ = Describe("ResourceSummary Collection", func() { capiClusterRef := corev1.ObjectReference{ Namespace: capiCluster.Namespace, Name: capiCluster.Name, - Kind: "Cluster", + Kind: clusterKind, APIVersion: clusterv1.GroupVersion.String(), } clustersWithDD := map[corev1.ObjectReference]bool{capiClusterRef: true} diff --git a/controllers/resourcesummary_test.go b/controllers/resourcesummary_test.go index 0e38f49a..c2f9017b 100644 --- a/controllers/resourcesummary_test.go +++ b/controllers/resourcesummary_test.go @@ -67,7 +67,7 @@ var _ = Describe("ResourceSummary Deployer", func() { Eventually(func() error { classifierCRD := &apiextensionsv1.CustomResourceDefinition{} return testEnv.Get(context.TODO(), - types.NamespacedName{Name: "resourcesummaries.lib.projectsveltos.io"}, classifierCRD) + types.NamespacedName{Name: testResourceSummaryCRDName}, classifierCRD) }, timeout, pollingInterval).Should(BeNil()) }) @@ -85,7 +85,7 @@ var _ = Describe("ResourceSummary Deployer", func() { Eventually(func() error { resourceSummaryCRD := &apiextensionsv1.CustomResourceDefinition{} return testEnv.Get(context.TODO(), - types.NamespacedName{Name: "resourcesummaries.lib.projectsveltos.io"}, resourceSummaryCRD) + types.NamespacedName{Name: testResourceSummaryCRDName}, resourceSummaryCRD) }, timeout, pollingInterval).Should(BeNil()) }) @@ -243,7 +243,7 @@ metadata: found = false for i := range patches { - if patches[i].Target.Kind == "Deployment" { + if patches[i].Target.Kind == testKindDeployment { found = true } } @@ -274,7 +274,7 @@ func prepareCluster() *clusterv1.Cluster { Name: randomString(), Labels: map[string]string{ clusterv1.ClusterNameLabel: cluster.Name, - clusterv1.MachineControlPlaneLabel: "ok", + clusterv1.MachineControlPlaneLabel: testOkValue, }, }, } @@ -303,7 +303,7 @@ func prepareCluster() *clusterv1.Cluster { Name: cluster.Name + kubeconfigPostfix, }, Data: map[string][]byte{ - "value": testEnv.Kubeconfig, + testValueKey: testEnv.Kubeconfig, }, } Expect(testEnv.Create(context.TODO(), secret)).To(Succeed()) @@ -316,7 +316,7 @@ func prepareCluster() *clusterv1.Cluster { Name: "drift-detection-version", }, Data: map[string]string{ - "version": version, + testVersionKey: version, }, } err := testEnv.Create(context.TODO(), cm) diff --git a/controllers/suite_helpers_test.go b/controllers/suite_helpers_test.go index 32bd4f3b..9d2046f6 100644 --- a/controllers/suite_helpers_test.go +++ b/controllers/suite_helpers_test.go @@ -246,7 +246,7 @@ func prepareForDeployment(clusterProfile *configv1beta1.ClusterProfile, //nolint Name: clusterSummary.Spec.ClusterName + kubeconfigPostfix, }, Data: map[string][]byte{ - "value": testEnv.Kubeconfig, + testValueKey: testEnv.Kubeconfig, }, } diff --git a/controllers/template_instantiation.go b/controllers/template_instantiation.go index 9657bc5d..0b70f4d9 100644 --- a/controllers/template_instantiation.go +++ b/controllers/template_instantiation.go @@ -162,7 +162,7 @@ func instantiateStructFields(ctx context.Context, config *rest.Config, c client. value := reflect.ValueOf(s) - if value.Kind() == reflect.Ptr { + if value.Kind() == reflect.Pointer { value = value.Elem() } diff --git a/controllers/template_instantiation_test.go b/controllers/template_instantiation_test.go index 3e58c73a..5de64d9b 100644 --- a/controllers/template_instantiation_test.go +++ b/controllers/template_instantiation_test.go @@ -63,7 +63,7 @@ var _ = Describe("Template instantiation", func() { Name: upstreamClusterNamePrefix + randomString(), Namespace: namespace, Labels: map[string]string{ - "dc": "eng", + testDCLabelKey: testEngValue, }, }, Spec: clusterv1.ClusterSpec{ @@ -135,7 +135,7 @@ var _ = Describe("Template instantiation", func() { u.SetUnstructuredContent(content) mgmtResources := map[string]*unstructured.Unstructured{ - "Deployment": u, + testKindDeployment: u, } logger := textlogger.NewLogger(textlogger.NewConfig()) @@ -172,7 +172,7 @@ var _ = Describe("Template instantiation", func() { u.SetUnstructuredContent(content) mgmtResources := map[string]*unstructured.Unstructured{ - "Deployment": u, + testKindDeployment: u, } logger := textlogger.NewLogger(textlogger.NewConfig()) @@ -252,7 +252,7 @@ var _ = Describe("Template instantiation", func() { u.SetUnstructuredContent(content) mgmtResources := map[string]*unstructured.Unstructured{ - "Deployment": u, + testKindDeployment: u, } logger := textlogger.NewLogger(textlogger.NewConfig()) @@ -293,7 +293,7 @@ var _ = Describe("Template instantiation", func() { u.SetUnstructuredContent(content) mgmtResources := map[string]*unstructured.Unstructured{ - "ConfigMap": u, + testKindConfigMap: u, } logger := textlogger.NewLogger(textlogger.NewConfig()) @@ -334,7 +334,7 @@ var _ = Describe("Template instantiation", func() { u.SetUnstructuredContent(content) mgmtResources := map[string]*unstructured.Unstructured{ - "Deployment": u, + testKindDeployment: u, } logger := textlogger.NewLogger(textlogger.NewConfig()) @@ -390,7 +390,7 @@ var _ = Describe("Template instantiation", func() { u.SetUnstructuredContent(content) mgmtResources := map[string]*unstructured.Unstructured{ - "Deployment": u, + testKindDeployment: u, } logger := textlogger.NewLogger(textlogger.NewConfig()) @@ -455,7 +455,7 @@ var _ = Describe("Template instantiation", func() { Name: randomString(), }, Data: map[string][]byte{ - "password": []byte(pwd), + testPasswordKey: []byte(pwd), }, } Expect(testEnv.Create(context.TODO(), secret)).To(Succeed()) @@ -472,7 +472,7 @@ valuesTemplate: | u.SetUnstructuredContent(content) mgmtResources := map[string]*unstructured.Unstructured{ - "Secret": &u, + testKindSecret: &u, } logger := textlogger.NewLogger(textlogger.NewConfig()) @@ -508,7 +508,7 @@ valuesTemplate: | Name: randomString(), }, Data: map[string][]byte{ - "password": []byte(pwd), + testPasswordKey: []byte(pwd), }, } Expect(testEnv.Create(context.TODO(), secret)).To(Succeed()) @@ -525,7 +525,7 @@ valuesTemplate: | u.SetUnstructuredContent(content) mgmtResources := map[string]*unstructured.Unstructured{ - "Secret": &u, + testKindSecret: &u, } logger := textlogger.NewLogger(textlogger.NewConfig()) diff --git a/controllers/templateresourcedef_utils_test.go b/controllers/templateresourcedef_utils_test.go index 7a8e47b7..9f91b705 100644 --- a/controllers/templateresourcedef_utils_test.go +++ b/controllers/templateresourcedef_utils_test.go @@ -130,7 +130,7 @@ var _ = Describe("TemplateResourceDef utils ", func() { It("GetTemplateResourceNamespace returns the correct namespace (uses Cluster)", func() { ref := &configv1beta1.TemplateResourceRef{ Resource: corev1.ObjectReference{ - Name: "{{ .Cluster.metadata.namespace }}-{{ .Cluster.metadata.name }}", + Name: testClusterFullNameTemplate, }, Identifier: randomString(), } @@ -287,8 +287,8 @@ var _ = Describe("collectTemplateResourceRefs", func() { clusterSummary.Spec.ClusterProfileSpec.TemplateResourceRefs = []configv1beta1.TemplateResourceRef{ { Resource: corev1.ObjectReference{ - Kind: "ConfigMap", - APIVersion: "v1", + Kind: testKindConfigMap, + APIVersion: testV1APIVersion, Namespace: nsName, Name: "does-not-exist-" + randomString(), }, @@ -309,8 +309,8 @@ var _ = Describe("collectTemplateResourceRefs", func() { clusterSummary.Spec.ClusterProfileSpec.TemplateResourceRefs = []configv1beta1.TemplateResourceRef{ { Resource: corev1.ObjectReference{ - Kind: "ConfigMap", - APIVersion: "v1", + Kind: testKindConfigMap, + APIVersion: testV1APIVersion, Namespace: nsName, Name: "does-not-exist-" + randomString(), }, @@ -330,7 +330,7 @@ var _ = Describe("collectTemplateResourceRefs", func() { Namespace: nsName, Name: randomString(), }, - Data: map[string]string{"key": "value"}, + Data: map[string]string{"key": testValueKey}, } Expect(testEnv.Create(context.TODO(), cm)).To(Succeed()) Expect(waitForObject(context.TODO(), testEnv.Client, cm)).To(Succeed()) @@ -339,8 +339,8 @@ var _ = Describe("collectTemplateResourceRefs", func() { clusterSummary.Spec.ClusterProfileSpec.TemplateResourceRefs = []configv1beta1.TemplateResourceRef{ { Resource: corev1.ObjectReference{ - Kind: "ConfigMap", - APIVersion: "v1", + Kind: testKindConfigMap, + APIVersion: testV1APIVersion, Namespace: nsName, Name: cm.Name, }, @@ -358,51 +358,51 @@ var _ = Describe("collectTemplateResourceRefs", func() { var _ = Describe("extractWatchedFields", func() { It("returns only the listed top-level field", func() { u := &unstructured.Unstructured{Object: map[string]interface{}{ - "spec": map[string]interface{}{"replicas": int64(3)}, - "status": map[string]interface{}{"readyReplicas": int64(3)}, + testSpecKey: map[string]interface{}{testReplicasKey: int64(3)}, + testStatusField: map[string]interface{}{testReadyReplicasKey: int64(3)}, }} - result := controllers.ExtractWatchedFields(u, []string{"status"}) + result := controllers.ExtractWatchedFields(u, []string{testStatusField}) - _, found, err := unstructured.NestedMap(result.Object, "status") + _, found, err := unstructured.NestedMap(result.Object, testStatusField) Expect(err).ToNot(HaveOccurred()) Expect(found).To(BeTrue()) - _, found, err = unstructured.NestedMap(result.Object, "spec") + _, found, err = unstructured.NestedMap(result.Object, testSpecKey) Expect(err).ToNot(HaveOccurred()) Expect(found).To(BeFalse()) }) It("extracts a specific nested field, excluding sibling fields", func() { u := &unstructured.Unstructured{Object: map[string]interface{}{ - "status": map[string]interface{}{ - "readyReplicas": int64(2), - "conditions": []interface{}{"cond1", "cond2"}, + testStatusField: map[string]interface{}{ + testReadyReplicasKey: int64(2), + "conditions": []interface{}{"cond1", "cond2"}, }, }} - result := controllers.ExtractWatchedFields(u, []string{"status.readyReplicas"}) + result := controllers.ExtractWatchedFields(u, []string{testStatusReadyReplicas}) - val, found, err := unstructured.NestedInt64(result.Object, "status", "readyReplicas") + val, found, err := unstructured.NestedInt64(result.Object, testStatusField, testReadyReplicasKey) Expect(err).ToNot(HaveOccurred()) Expect(found).To(BeTrue()) Expect(val).To(Equal(int64(2))) - _, found, err = unstructured.NestedSlice(result.Object, "status", "conditions") + _, found, err = unstructured.NestedSlice(result.Object, testStatusField, "conditions") Expect(err).ToNot(HaveOccurred()) Expect(found).To(BeFalse()) }) It("handles multiple fields across different sections", func() { u := &unstructured.Unstructured{Object: map[string]interface{}{ - "metadata": map[string]interface{}{"labels": map[string]interface{}{"env": "prod"}}, - "spec": map[string]interface{}{"replicas": int64(3)}, - "status": map[string]interface{}{"readyReplicas": int64(3)}, + "metadata": map[string]interface{}{"labels": map[string]interface{}{testEnvLabelKey: "prod"}}, + testSpecKey: map[string]interface{}{testReplicasKey: int64(3)}, + testStatusField: map[string]interface{}{testReadyReplicasKey: int64(3)}, }} - result := controllers.ExtractWatchedFields(u, []string{"status.readyReplicas", "metadata.labels"}) + result := controllers.ExtractWatchedFields(u, []string{testStatusReadyReplicas, "metadata.labels"}) - _, found, err := unstructured.NestedInt64(result.Object, "status", "readyReplicas") + _, found, err := unstructured.NestedInt64(result.Object, testStatusField, testReadyReplicasKey) Expect(err).ToNot(HaveOccurred()) Expect(found).To(BeTrue()) @@ -410,33 +410,33 @@ var _ = Describe("extractWatchedFields", func() { Expect(err).ToNot(HaveOccurred()) Expect(found).To(BeTrue()) - _, found, err = unstructured.NestedMap(result.Object, "spec") + _, found, err = unstructured.NestedMap(result.Object, testSpecKey) Expect(err).ToNot(HaveOccurred()) Expect(found).To(BeFalse()) }) It("returns an empty object when all paths are missing", func() { u := &unstructured.Unstructured{Object: map[string]interface{}{ - "status": map[string]interface{}{"readyReplicas": int64(3)}, + testStatusField: map[string]interface{}{testReadyReplicasKey: int64(3)}, }} - result := controllers.ExtractWatchedFields(u, []string{"status.nonExistent"}) + result := controllers.ExtractWatchedFields(u, []string{testStatusNonExistent}) Expect(result.Object).To(BeEmpty()) }) It("includes existing paths and silently skips missing ones", func() { u := &unstructured.Unstructured{Object: map[string]interface{}{ - "status": map[string]interface{}{"readyReplicas": int64(3)}, + testStatusField: map[string]interface{}{testReadyReplicasKey: int64(3)}, }} - result := controllers.ExtractWatchedFields(u, []string{"status.readyReplicas", "status.nonExistent"}) + result := controllers.ExtractWatchedFields(u, []string{testStatusReadyReplicas, testStatusNonExistent}) - val, found, err := unstructured.NestedInt64(result.Object, "status", "readyReplicas") + val, found, err := unstructured.NestedInt64(result.Object, testStatusField, testReadyReplicasKey) Expect(err).ToNot(HaveOccurred()) Expect(found).To(BeTrue()) Expect(val).To(Equal(int64(3))) - _, found, _ = unstructured.NestedFieldNoCopy(result.Object, "status", "nonExistent") + _, found, _ = unstructured.NestedFieldNoCopy(result.Object, testStatusField, "nonExistent") Expect(found).To(BeFalse()) }) }) diff --git a/controllers/test_constants_test.go b/controllers/test_constants_test.go new file mode 100644 index 00000000..e565ba56 --- /dev/null +++ b/controllers/test_constants_test.go @@ -0,0 +1,125 @@ +/* +Copyright 2025. projectsveltos.io. All rights reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package controllers_test + +const ( + // Controller names + testControllerNameSummary = "clustersummary" + testControllerNameProfile = "clusterprofile" + testControllerNameProfileShort = "profile" + + // Kubernetes API versions and kinds + testV1APIVersion = "v1" + testConfigAPIVersion = "config.projectsveltos.io/v1beta1" + testKindDeployment = "Deployment" + testKindConfigMap = "ConfigMap" + testKindSecret = "Secret" + + // Helm chart versions and releases + testChartVersion100 = "v1.0.0" + testChartVersion250 = "v2.5.0" + testChartVersion253 = "v2.5.3" + testChartVersion119 = "1.19.0" + testChartVersion2114 = "21.1.4" + testReleaseNameNginxLatest = "nginx-latest" + testReleaseNameCalico = "calico" + testReleaseNameKyverno = "kyverno" + testReleaseNamePrometheus = "prometheus" + testReleaseNameGrafana = "grafana" + testReleaseNameContour = "contour-latest" + testRepoURLBitnami = "https://charts.bitnami.com/bitnami" + testChartNameBitnamiContour = "bitnami/contour" + + // Label keys and values + testEnvLabelKey = "env" + testQAValue = "qa" + testDCLabelKey = "dc" + testRegionKey = "region" + testClusterNameKey = "cluster-name" + + // Annotation values + testOkValue = "ok" + testTrueValue = "true" + + // Field and map key names + testValueKey = "value" + testValue1 = "value1" + testValue2 = "value2" + testStatusField = "status" + testServiceKey = "service" + testImageKey = "image" + testRepositoryKey = "repository" + testNginxRepo = "nginx" + testNginxLatestImage = "nginx:latest" + testReplicaCountKey = "replicaCount" + testTagKey = "tag" + testPortKey = "port" + testPasswordKey = "password" + testChangeKey = "change" + testVersionKey = "version" + testAppsGroup = "apps" + testCertManagerGroup = "cert-manager.io" + testDeleteVerb = "delete" + testReadyReplicasKey = "readyReplicas" + testReplicasKey = "replicas" + + // Label values + testProductionValue = "production" + testEngValue = "eng" + testTestingValue = "testing" + + // Kubernetes resource names + testCertificateRequestsResource = "certificaterequests" + testDeploymentsResource = "deployments" + testResourceSummaryCRDName = "resourcesummaries.lib.projectsveltos.io" + testWatchedKey = "watched" + + // JSON paths and watch fields + testSpecReplicasPath = "/spec/replicas" + testDataWatchedField = "data.watched" + testStatusReadyReplicas = "status.readyReplicas" + testStatusNonExistent = "status.nonExistent" + + // Drift detection + testDriftDetectionManagerName = "drift-detection-manager" + testControlPlaneLabel = "control-plane" + + // Namespace + defaultNamespace = "default" + + // Template strings + testClusterNameTemplate = "{{ .Cluster.metadata.name }}" + testClusterNamePatchTemplate = "{{ .Cluster.metadata.name }}-patch" + testClusterFullNameTemplate = "{{ .Cluster.metadata.namespace }}-{{ .Cluster.metadata.name }}" + testRegionLabelTemplate = `{{ index .Cluster.metadata.labels "region" }}` + + // Misc + testClusterRoleKindV1 = "ClusterRole.v1.rbac.authorization.k8s.io" + + // Multiline patch + testEnvLabelPatch = `- op: add + path: /metadata/labels/environment + value: production` + + // Verbs and resources + testCreateVerb = "create" + testGetVerb = "get" + testNamespacesResource = "namespaces" + + // Field keys + testSpecKey = "spec" +) diff --git a/controllers/url_source.go b/controllers/url_source.go index 403d5e1c..f2ccb561 100644 --- a/controllers/url_source.go +++ b/controllers/url_source.go @@ -133,7 +133,7 @@ func deployContentOfURL(ctx context.Context, deployingToMgmtCluster bool, destCo } if ref.IsTemplate { syntheticSource.Annotations = map[string]string{ - libsveltosv1beta1.PolicyTemplateAnnotation: "ok", + libsveltosv1beta1.PolicyTemplateAnnotation: annotationValueOk, } } diff --git a/controllers/utils.go b/controllers/utils.go index ebb9feb7..f38af64b 100644 --- a/controllers/utils.go +++ b/controllers/utils.go @@ -58,6 +58,15 @@ import ( const ( nameSeparator = "--" clusterKind = "Cluster" + + applyPatchFieldManager = "application/apply-patch" + resourceSummaryCRDName = "resourcesummaries.lib.projectsveltos.io" + driftDetectionManagerDeploymentName = "drift-detection-manager" + coreAPIVersion = "v1" + controllerNameClusterSummary = "clustersummary" + appsGroupName = "apps" + stringTrue = "true" + annotationValueOk = "ok" ) func InitScheme() (*runtime.Scheme, error) { diff --git a/controllers/utils_test.go b/controllers/utils_test.go index 1129f058..9a7035f6 100644 --- a/controllers/utils_test.go +++ b/controllers/utils_test.go @@ -285,7 +285,7 @@ var _ = Describe("getClusterProfileOwner ", func() { It("isNamespaced returns true for namespaced resources", func() { logger := textlogger.NewLogger(textlogger.NewConfig()) - clusterNamespace := "default" + clusterNamespace := defaultNamespace clusterName := randomString() cluster := &clusterv1.Cluster{ @@ -303,7 +303,7 @@ var _ = Describe("getClusterProfileOwner ", func() { Name: clusterName + kubeconfigPostfix, }, Data: map[string][]byte{ - "value": testEnv.Kubeconfig, + testValueKey: testEnv.Kubeconfig, }, } Expect(testEnv.Create(context.TODO(), secret)).To(Succeed()) @@ -419,7 +419,7 @@ var _ = Describe("getClusterProfileOwner ", func() { randomString(): fmt.Sprintf("{{ %s }}", randomString()), randomString(): `{{ .Cluster.spec.clusterNetwork.pods.cidrBlocks }}`, randomString(): `{{ (index .MgmtResources "AutoscalerSecret").data.token }}`, - randomString(): `{{ index .Cluster.metadata.labels "region" }}`, + randomString(): testRegionLabelTemplate, randomString(): `{{ .Cluster.metadata.spec.topology.version }}`, randomString(): randomString() + randomString(), } @@ -577,7 +577,7 @@ metadata: lbls := map[string]string{ "cluster-namespace": namespace, - "cluster-name": clusterName, + testClusterNameKey: clusterName, "cluster-type": strings.ToLower(string(libsveltosv1beta1.ClusterTypeSveltos)), "feature": "drift-detection", } diff --git a/go.mod b/go.mod index cd14e4b7..b916f075 100644 --- a/go.mod +++ b/go.mod @@ -1,6 +1,6 @@ module github.com/projectsveltos/addon-controller -go 1.26.3 +go 1.26.4 require ( dario.cat/mergo v1.0.2 @@ -18,7 +18,7 @@ require ( github.com/onsi/ginkgo/v2 v2.29.0 github.com/onsi/gomega v1.41.0 github.com/pkg/errors v0.9.1 - github.com/projectsveltos/libsveltos v1.10.1-0.20260601130048-ace88648a3f5 + github.com/projectsveltos/libsveltos v1.10.1-0.20260608095342-7d10ad02760d github.com/prometheus/client_golang v1.23.2 github.com/robfig/cron v1.2.0 github.com/spf13/pflag v1.0.10 diff --git a/go.sum b/go.sum index 2fe7780e..1ae07877 100644 --- a/go.sum +++ b/go.sum @@ -273,8 +273,8 @@ github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 h1:Jamvg5psRI github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= github.com/poy/onpar v1.1.2 h1:QaNrNiZx0+Nar5dLgTVp5mXkyoVFIbepjyEoGSnhbAY= github.com/poy/onpar v1.1.2/go.mod h1:6X8FLNoxyr9kkmnlqpK6LSoiOtrO6MICtWwEuWkLjzg= -github.com/projectsveltos/libsveltos v1.10.1-0.20260601130048-ace88648a3f5 h1:eRrg+zo7Gna3AGvunD/r4XCQxwkNUyQ0xzesEF+6Ayo= -github.com/projectsveltos/libsveltos v1.10.1-0.20260601130048-ace88648a3f5/go.mod h1:AzKBiyMTL3KSTLYMii5QdR3ieWyUKBHZCMFWIVCfm6A= +github.com/projectsveltos/libsveltos v1.10.1-0.20260608095342-7d10ad02760d h1:21X65lDwH/6Iig1s355umi+xdNQlT3qU5B/6hTNvrl4= +github.com/projectsveltos/libsveltos v1.10.1-0.20260608095342-7d10ad02760d/go.mod h1:bhViY4kIzvO04HUECrsPbI/6wd7DNQyvDTZLMtm8hiM= github.com/projectsveltos/lua-utils/glua-json v0.0.0-20251212200258-2b3cdcb7c0f5 h1:khnc+994UszxZYu69J+R5FKiLA/Nk1JQj0EYAkwTWz0= github.com/projectsveltos/lua-utils/glua-json v0.0.0-20251212200258-2b3cdcb7c0f5/go.mod h1:yVL8KQFa9tmcxgwl9nwIMtKgtmIVC1zaFRSCfOwYvPY= github.com/projectsveltos/lua-utils/glua-runes v0.0.0-20251212200258-2b3cdcb7c0f5 h1:YbsebwRwTRhV8QacvEAdFqxcxHdeu7JTVtsBovbkgos= diff --git a/hack/tools/get-golangci-lint.sh b/hack/tools/get-golangci-lint.sh index 97945d12..d753eb80 100755 --- a/hack/tools/get-golangci-lint.sh +++ b/hack/tools/get-golangci-lint.sh @@ -2,5 +2,23 @@ set -euo pipefail -# Define the URL for downloading the golangci-lint archive -curl -sSfL https://raw.githubusercontent.com/golangci/golangci-lint/master/install.sh | sh -s -- -b $(pwd)/bin "$1" \ No newline at end of file +VERSION="$1" +BINARY="$(pwd)/bin/golangci-lint" + +# Skip download if the binary already exists at the requested version. +if [[ -x "$BINARY" ]] && "$BINARY" --version 2>/dev/null | grep -qF "${VERSION#v}"; then + echo "golangci-lint ${VERSION} already installed, skipping download" + exit 0 +fi + +# Retry up to 3 times — the GitHub CDN occasionally returns 504. +for attempt in 1 2 3; do + if curl -sSfL https://golangci-lint.run/install.sh | sh -s -- -b "$(pwd)/bin" "$VERSION"; then + exit 0 + fi + echo "golangci-lint download attempt ${attempt} failed, retrying..." >&2 + sleep $((attempt * 5)) +done + +echo "golangci-lint download failed after 3 attempts" >&2 +exit 1 diff --git a/hack/tools/go.mod b/hack/tools/go.mod index 52cf7f7d..a4acaabd 100644 --- a/hack/tools/go.mod +++ b/hack/tools/go.mod @@ -1,6 +1,6 @@ module github.com/projectsveltos/addon-controller/hack/tools -go 1.26.3 +go 1.26.4 require ( github.com/a8m/envsubst v1.4.3 diff --git a/internal/telemetry/report.go b/internal/telemetry/report.go index 492e837e..663fac44 100644 --- a/internal/telemetry/report.go +++ b/internal/telemetry/report.go @@ -60,8 +60,10 @@ var ( ) const ( - contentTypeJSON = "application/json" - domain = "http://telemetry.projectsveltos.io/" + contentTypeJSON = "application/json" + domain = "http://telemetry.projectsveltos.io/" + libSveltosGroup = "lib.projectsveltos.io" + libSveltosAPIVersion = "v1beta1" providerEKS = "eks" providerGKE = "gke" @@ -237,8 +239,8 @@ func (m *instance) collectEventData(ctx context.Context) (eventTriggers, cluster // Count EventTriggers eventTriggerGVR := schema.GroupVersionResource{ - Group: "lib.projectsveltos.io", - Version: "v1beta1", + Group: libSveltosGroup, + Version: libSveltosAPIVersion, Resource: "eventtriggers", } @@ -251,8 +253,8 @@ func (m *instance) collectEventData(ctx context.Context) (eventTriggers, cluster // Count ClusterHealthChecks chcGVR := schema.GroupVersionResource{ - Group: "lib.projectsveltos.io", - Version: "v1beta1", + Group: libSveltosGroup, + Version: libSveltosAPIVersion, Resource: "clusterhealthchecks", } diff --git a/lib/clusterops/reloader_utils_test.go b/lib/clusterops/reloader_utils_test.go index c0a6b52c..b428f45c 100644 --- a/lib/clusterops/reloader_utils_test.go +++ b/lib/clusterops/reloader_utils_test.go @@ -54,15 +54,15 @@ var _ = Describe("Reloader utils", func() { testData := []resourceData{ { - resource: &corev1.ObjectReference{Kind: "Deployment", Namespace: randomString(), Name: randomString()}, + resource: &corev1.ObjectReference{Kind: testKindDeployment, Namespace: randomString(), Name: randomString()}, result: true, }, { - resource: &corev1.ObjectReference{Kind: "StatefulSet", Namespace: randomString(), Name: randomString()}, + resource: &corev1.ObjectReference{Kind: testKindStatefulSet, Namespace: randomString(), Name: randomString()}, result: true, }, { - resource: &corev1.ObjectReference{Kind: "DaemonSet", Namespace: randomString(), Name: randomString()}, + resource: &corev1.ObjectReference{Kind: testKindDaemonSet, Namespace: randomString(), Name: randomString()}, result: true, }, { @@ -81,8 +81,8 @@ var _ = Describe("Reloader utils", func() { c := fake.NewClientBuilder().WithScheme(scheme).Build() reloaderInfo := []libsveltosv1beta1.ReloaderInfo{ - {Kind: "Deployment", Namespace: randomString(), Name: randomString()}, - {Kind: "Deployment", Namespace: randomString(), Name: randomString()}, + {Kind: testKindDeployment, Namespace: randomString(), Name: randomString()}, + {Kind: testKindDeployment, Namespace: randomString(), Name: randomString()}, } clusterProfileName := randomString() @@ -102,9 +102,9 @@ var _ = Describe("Reloader utils", func() { c := fake.NewClientBuilder().WithScheme(scheme).Build() resources := []corev1.ObjectReference{ - {Kind: "Deployment", Namespace: randomString(), Name: randomString()}, - {Kind: "Deployment", Namespace: "", Name: randomString()}, - {Kind: "DaemonSet", Namespace: "", Name: randomString()}, + {Kind: testKindDeployment, Namespace: randomString(), Name: randomString()}, + {Kind: testKindDeployment, Namespace: "", Name: randomString()}, + {Kind: testKindDaemonSet, Namespace: "", Name: randomString()}, } clusterProfileName := randomString() @@ -123,9 +123,9 @@ var _ = Describe("Reloader utils", func() { c := fake.NewClientBuilder().WithScheme(scheme).Build() resources := []corev1.ObjectReference{ - {Kind: "Deployment", Namespace: randomString(), Name: randomString()}, - {Kind: "StatefulSet", Namespace: randomString(), Name: randomString()}, - {Kind: "DaemonSet", Namespace: randomString(), Name: randomString()}, + {Kind: testKindDeployment, Namespace: randomString(), Name: randomString()}, + {Kind: testKindStatefulSet, Namespace: randomString(), Name: randomString()}, + {Kind: testKindDaemonSet, Namespace: randomString(), Name: randomString()}, } clusterProfileName := randomString() @@ -151,10 +151,10 @@ var _ = Describe("Reloader utils", func() { } resources = []corev1.ObjectReference{ - {Kind: "Deployment", Namespace: randomString(), Name: randomString()}, - {Kind: "Deployment", Namespace: randomString(), Name: randomString()}, - {Kind: "StatefulSet", Namespace: randomString(), Name: randomString()}, - {Kind: "DaemonSet", Namespace: randomString(), Name: randomString()}, + {Kind: testKindDeployment, Namespace: randomString(), Name: randomString()}, + {Kind: testKindDeployment, Namespace: randomString(), Name: randomString()}, + {Kind: testKindStatefulSet, Namespace: randomString(), Name: randomString()}, + {Kind: testKindDaemonSet, Namespace: randomString(), Name: randomString()}, } // Reloader Spec.ReloaderInfo is updated now @@ -211,12 +211,12 @@ var _ = Describe("Reloader utils", func() { It("updateReloaderWithDeployedResources creates reloader instance", func() { resources := []corev1.ObjectReference{ { - Kind: "Deployment", + Kind: testKindDeployment, Name: randomString(), Namespace: randomString(), }, { - Kind: "DaemonSet", + Kind: testKindDaemonSet, Name: randomString(), Namespace: randomString(), }, @@ -269,21 +269,21 @@ var _ = Describe("Reloader utils", func() { resourceReports := []libsveltosv1beta1.ResourceReport{ { Resource: libsveltosv1beta1.Resource{ - Kind: "StatefulSet", + Kind: testKindStatefulSet, Name: randomString(), Namespace: randomString(), }, }, { Resource: libsveltosv1beta1.Resource{ - Kind: "DaemonSet", + Kind: testKindDaemonSet, Name: randomString(), Namespace: randomString(), }, }, { Resource: libsveltosv1beta1.Resource{ - Kind: "Deployment", + Kind: testKindDeployment, Name: randomString(), Namespace: randomString(), }, @@ -307,12 +307,12 @@ var _ = Describe("Reloader utils", func() { { Resources: []libsveltosv1beta1.ResourceSummaryResource{ { - Kind: "StatefulSet", + Kind: testKindStatefulSet, Name: randomString(), Namespace: randomString(), }, { - Kind: "StatefulSet", + Kind: testKindStatefulSet, Name: randomString(), Namespace: randomString(), }, @@ -321,12 +321,12 @@ var _ = Describe("Reloader utils", func() { { Resources: []libsveltosv1beta1.ResourceSummaryResource{ { - Kind: "Deployment", + Kind: testKindDeployment, Name: randomString(), Namespace: randomString(), }, { - Kind: "DaemonSet", + Kind: testKindDaemonSet, Name: randomString(), Namespace: randomString(), }, diff --git a/lib/clusterops/test_constants_test.go b/lib/clusterops/test_constants_test.go new file mode 100644 index 00000000..0d38240a --- /dev/null +++ b/lib/clusterops/test_constants_test.go @@ -0,0 +1,25 @@ +/* +Copyright 2025. projectsveltos.io. All rights reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package clusterops_test + +const ( + testKindDeployment = "Deployment" + testKindStatefulSet = "StatefulSet" + testKindDaemonSet = "DaemonSet" + testResultTypeVector = "vector" + testErrorRateKey = "errorRate" +) diff --git a/lib/clusterops/validate_health_test.go b/lib/clusterops/validate_health_test.go index 1c9bc4f6..76658957 100644 --- a/lib/clusterops/validate_health_test.go +++ b/lib/clusterops/validate_health_test.go @@ -232,7 +232,7 @@ var _ = Describe("Metric health checks", func() { It("extracts value from single-element vector", func() { data := clusterops.PrometheusData{ - ResultType: "vector", + ResultType: testResultTypeVector, Result: json.RawMessage(`[{"metric":{"job":"app"},"value":[1234567890.123,"2.0"]}]`), } v, err := clusterops.ExtractScalar(data) @@ -242,7 +242,7 @@ var _ = Describe("Metric health checks", func() { It("returns error for empty vector", func() { data := clusterops.PrometheusData{ - ResultType: "vector", + ResultType: testResultTypeVector, Result: json.RawMessage(`[]`), } _, err := clusterops.ExtractScalar(data) @@ -251,7 +251,7 @@ var _ = Describe("Metric health checks", func() { It("returns error for multi-element vector", func() { data := clusterops.PrometheusData{ - ResultType: "vector", + ResultType: testResultTypeVector, Result: json.RawMessage( `[{"metric":{},"value":[1,"1"]},{"metric":{},"value":[2,"2"]}]`), } @@ -280,14 +280,14 @@ end` It("evaluates metrics-only check as healthy", func() { healthy, _, err := clusterops.IsHealthy(nil, errorRateScript, - map[string]float64{"errorRate": 0.01}, logger) + map[string]float64{testErrorRateKey: 0.01}, logger) Expect(err).To(BeNil()) Expect(healthy).To(BeTrue()) }) It("evaluates metrics-only check as unhealthy when threshold exceeded", func() { healthy, msg, err := clusterops.IsHealthy(nil, errorRateScript, - map[string]float64{"errorRate": 0.10}, logger) + map[string]float64{testErrorRateKey: 0.10}, logger) Expect(err).To(BeNil()) Expect(healthy).To(BeFalse()) Expect(msg).NotTo(BeEmpty()) diff --git a/pkg/scope/clusterprofile_test.go b/pkg/scope/clusterprofile_test.go index 700d553f..9a93c34b 100644 --- a/pkg/scope/clusterprofile_test.go +++ b/pkg/scope/clusterprofile_test.go @@ -177,7 +177,7 @@ var _ = Describe("ProfileScope/ClusterProfileScope", func() { clusterProfile.Spec.ClusterSelector = libsveltosv1beta1.Selector{ LabelSelector: metav1.LabelSelector{ MatchLabels: map[string]string{ - "zone": "east", + testZoneKey: testZoneEastValue, }, }, } diff --git a/pkg/scope/set_test.go b/pkg/scope/set_test.go index 8e6bb762..827b0d9d 100644 --- a/pkg/scope/set_test.go +++ b/pkg/scope/set_test.go @@ -117,7 +117,7 @@ var _ = Describe("SetScope/ClusterSetScope", func() { clusterSet.Spec.ClusterSelector = libsveltosv1beta1.Selector{ LabelSelector: metav1.LabelSelector{ MatchLabels: map[string]string{ - "zone": "east", + testZoneKey: testZoneEastValue, }, }, } diff --git a/pkg/scope/test_constants_test.go b/pkg/scope/test_constants_test.go new file mode 100644 index 00000000..f65f4b80 --- /dev/null +++ b/pkg/scope/test_constants_test.go @@ -0,0 +1,22 @@ +/* +Copyright 2025. projectsveltos.io. All rights reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package scope_test + +const ( + testZoneEastValue = "east" + testZoneKey = "zone" +) diff --git a/test/fv/auto_deploy_dependencies_test.go b/test/fv/auto_deploy_dependencies_test.go index fc210454..bc7ea359 100644 --- a/test/fv/auto_deploy_dependencies_test.go +++ b/test/fv/auto_deploy_dependencies_test.go @@ -102,12 +102,12 @@ var _ = Describe("Feature", func() { Byf("Create ClusterProfile %s to deploy Kyverno helm chart", helmClusterProfile.Name) helmClusterProfile.Spec.HelmCharts = []configv1beta1.HelmChart{ { - RepositoryURL: "https://kyverno.github.io/kyverno/", - RepositoryName: "kyverno", - ChartName: "kyverno/kyverno", - ChartVersion: "v3.5.2", - ReleaseName: "kyverno-latest", - ReleaseNamespace: "kyverno", + RepositoryURL: kyvernoRepoURL, + RepositoryName: kyvernoNamespace, + ChartName: kyvernoChartName, + ChartVersion: kyvernoVersion352, + ReleaseName: kyvernoLatestRelease, + ReleaseNamespace: kyvernoNamespace, HelmChartAction: configv1beta1.HelmChartActionInstall, }, } @@ -167,7 +167,7 @@ var _ = Describe("Feature", func() { kindWorkloadCluster.GetNamespace(), kindWorkloadCluster.GetName(), getClusterType()) charts := []configv1beta1.Chart{ - {ReleaseName: "kyverno-latest", ChartVersion: "3.5.2", Namespace: "kyverno"}, + {ReleaseName: kyvernoLatestRelease, ChartVersion: kyvernoVersion352S, Namespace: kyvernoNamespace}, } verifyClusterConfiguration(configv1beta1.ClusterProfileKind, helmClusterProfile.Name, helmClusterSummary.Spec.ClusterNamespace, helmClusterSummary.Spec.ClusterName, libsveltosv1beta1.FeatureHelm, diff --git a/test/fv/autoscaler_test.go b/test/fv/autoscaler_test.go index 84c631de..1333e37d 100644 --- a/test/fv/autoscaler_test.go +++ b/test/fv/autoscaler_test.go @@ -77,9 +77,9 @@ var _ = Describe("Feature", func() { err := retry.RetryOnConflict(retry.DefaultRetry, func() error { clusterRole := &rbacv1.ClusterRole{} Expect(k8sClient.Get(context.TODO(), - types.NamespacedName{Name: "addon-controller-role-extra"}, clusterRole)).To(Succeed()) + types.NamespacedName{Name: addonControllerRoleExtra}, clusterRole)).To(Succeed()) clusterRole.Rules = []rbacv1.PolicyRule{ - {Verbs: []string{"*"}, APIGroups: []string{""}, Resources: []string{"serviceaccounts", "secrets"}}, + {Verbs: []string{"*"}, APIGroups: []string{""}, Resources: []string{serviceAccountsResource, "secrets"}}, } return k8sClient.Update(context.TODO(), clusterRole) }) @@ -106,7 +106,7 @@ var _ = Describe("Feature", func() { types.NamespacedName{Namespace: configMap.Namespace, Name: configMap.Name}, currentConfigMap)).To(Succeed()) // Define it as template as content of autoscalerServiceAccount and autoscalerSecret is a template currentConfigMap.Annotations = map[string]string{ - libsveltosv1beta1.PolicyTemplateAnnotation: "true", + libsveltosv1beta1.PolicyTemplateAnnotation: annotationTrueValue, } Expect(k8sClient.Update(context.TODO(), currentConfigMap)).To(Succeed()) @@ -118,7 +118,7 @@ var _ = Describe("Feature", func() { types.NamespacedName{Namespace: configMap.Namespace, Name: configMap.Name}, currentConfigMap)).To(Succeed()) // Defined it as template as content of autoscalerInfo is a template currentConfigMap.Annotations = map[string]string{ - libsveltosv1beta1.PolicyTemplateAnnotation: "true", + libsveltosv1beta1.PolicyTemplateAnnotation: annotationTrueValue, } Expect(k8sClient.Update(context.TODO(), currentConfigMap)).To(Succeed()) @@ -131,7 +131,7 @@ var _ = Describe("Feature", func() { currentClusterProfile.Spec.TemplateResourceRefs = []configv1beta1.TemplateResourceRef{ { Resource: corev1.ObjectReference{ - Kind: "Secret", + Kind: kindSecret, Name: autoscaler, }, Identifier: "AutoscalerSecret", diff --git a/test/fv/capi_onboard_annotation_test.go b/test/fv/capi_onboard_annotation_test.go index ea16eb4b..f4a6d089 100644 --- a/test/fv/capi_onboard_annotation_test.go +++ b/test/fv/capi_onboard_annotation_test.go @@ -41,8 +41,6 @@ var _ = Describe("Helm", Serial, func() { const ( namePrefix = "onboard-" onboardAnnotation = "onboard-capi" - - addonDeplName = "addon-controller" ) BeforeEach(func() { @@ -71,21 +69,21 @@ var _ = Describe("Helm", Serial, func() { Expect(k8sClient.Get(context.TODO(), types.NamespacedName{Name: clusterProfile.Name}, currentClusterProfile)).To(Succeed()) currentClusterProfile.Spec.HelmCharts = []configv1beta1.HelmChart{ { - RepositoryURL: "https://prometheus-community.github.io/helm-charts", - RepositoryName: "prometheus-community", - ChartName: "prometheus-community/prometheus", - ChartVersion: "25.24.0", - ReleaseName: "prometheus", - ReleaseNamespace: "prometheus", + RepositoryURL: prometheusCommunityURL, + RepositoryName: prometheusCommunityName, + ChartName: prometheusChartName, + ChartVersion: prometheusVersion2524, + ReleaseName: prometheusRelease, + ReleaseNamespace: prometheusRelease, HelmChartAction: configv1beta1.HelmChartActionInstall, }, { RepositoryURL: "https://grafana-community.github.io/helm-charts", - RepositoryName: "grafana", - ChartName: "grafana/grafana", - ChartVersion: "11.3.6", - ReleaseName: "grafana", - ReleaseNamespace: "grafana", + RepositoryName: grafanaRepoName, + ChartName: grafanaChartName, + ChartVersion: grafanaVersion1136, + ReleaseName: grafanaRepoName, + ReleaseNamespace: grafanaRepoName, HelmChartAction: configv1beta1.HelmChartActionInstall, Options: &configv1beta1.HelmOptions{ RunTests: true, @@ -147,8 +145,8 @@ var _ = Describe("Helm", Serial, func() { libsveltosv1beta1.FeatureHelm) charts := []configv1beta1.Chart{ - {ReleaseName: "grafana", ChartVersion: "11.3.6", Namespace: "grafana"}, - {ReleaseName: "prometheus", ChartVersion: "25.24.0", Namespace: "prometheus"}, + {ReleaseName: grafanaRepoName, ChartVersion: grafanaVersion1136, Namespace: grafanaRepoName}, + {ReleaseName: prometheusRelease, ChartVersion: prometheusVersion2524, Namespace: prometheusRelease}, } verifyClusterConfiguration(configv1beta1.ClusterProfileKind, clusterProfile.Name, diff --git a/test/fv/continue_on_error_test.go b/test/fv/continue_on_error_test.go index 2589a63d..51c7236c 100644 --- a/test/fv/continue_on_error_test.go +++ b/test/fv/continue_on_error_test.go @@ -122,20 +122,20 @@ var _ = Describe("Feature", Serial, func() { currentClusterProfile.Spec.HelmCharts = []configv1beta1.HelmChart{ { RepositoryURL: "https://charts.konghq.com", - RepositoryName: "kong", + RepositoryName: kongRepoName, ChartName: "kong/kong", - ChartVersion: "2.51.0", - ReleaseName: "kong", - ReleaseNamespace: "kong", + ChartVersion: kongVersion2510, + ReleaseName: kongRepoName, + ReleaseNamespace: kongRepoName, HelmChartAction: configv1beta1.HelmChartActionInstall, }, { - RepositoryURL: "https://charts.jetstack.io", - RepositoryName: "jetstack", - ChartName: "jetstack/cert-manager", + RepositoryURL: jetstackURL, + RepositoryName: jetstackName, + ChartName: jetstackCertManagerChart, ChartVersion: "v1.16.2", - ReleaseName: "cert-manager", - ReleaseNamespace: "cert-manager", + ReleaseName: certManager, + ReleaseNamespace: certManager, HelmChartAction: configv1beta1.HelmChartActionInstall, Options: &configv1beta1.HelmOptions{ Timeout: &helmTimeout, @@ -145,9 +145,9 @@ var _ = Describe("Feature", Serial, func() { RepositoryURL: "https://helm.nginx.com/stable/", RepositoryName: "nginx-stable", ChartName: "nginx-stable/nginx-ingress", - ChartVersion: "2.2.2", - ReleaseName: "nginx-latest", - ReleaseNamespace: "nginx", + ChartVersion: nginxVersion222, + ReleaseName: nginxLatestRelease, + ReleaseNamespace: nginxNamespace, HelmChartAction: configv1beta1.HelmChartActionInstall, Options: &configv1beta1.HelmOptions{ SkipSchemaValidation: true, @@ -175,8 +175,8 @@ var _ = Describe("Feature", Serial, func() { kindWorkloadCluster.GetNamespace(), kindWorkloadCluster.GetName(), getClusterType()) charts := []configv1beta1.Chart{ - {ReleaseName: "kong", ChartVersion: "2.51.0", Namespace: "kong"}, - {ReleaseName: "nginx-latest", ChartVersion: "2.2.2", Namespace: "nginx"}, + {ReleaseName: kongRepoName, ChartVersion: kongVersion2510, Namespace: kongRepoName}, + {ReleaseName: nginxLatestRelease, ChartVersion: nginxVersion222, Namespace: nginxNamespace}, } verifyClusterConfiguration(configv1beta1.ClusterProfileKind, clusterProfile.Name, @@ -184,8 +184,8 @@ var _ = Describe("Feature", Serial, func() { nil, charts) policies := []policy{ - {kind: "Namespace", name: resourceNamespace, namespace: "", group: ""}, - {kind: "Deployment", name: "nginx-deployment", namespace: resourceNamespace, group: "apps"}, + {kind: kindNamespace, name: resourceNamespace, namespace: "", group: ""}, + {kind: kindDeployment, name: nginxDeploymentName, namespace: resourceNamespace, group: appsGroupName}, } verifyClusterConfiguration(configv1beta1.ClusterProfileKind, clusterProfile.Name, diff --git a/test/fv/delete_check_test.go b/test/fv/delete_check_test.go index 24955329..0adadc15 100644 --- a/test/fv/delete_check_test.go +++ b/test/fv/delete_check_test.go @@ -101,12 +101,12 @@ spec: types.NamespacedName{Name: clusterProfile.Name}, currentClusterProfile)).To(Succeed()) currentClusterProfile.Spec.HelmCharts = []configv1beta1.HelmChart{ { - RepositoryURL: "https://kubernetes-sigs.github.io/external-dns/", - RepositoryName: "external-dns", - ChartName: "external-dns/external-dns", - ChartVersion: "1.20.0", - ReleaseName: "external-dns", - ReleaseNamespace: "external-dns", + RepositoryURL: externalDNSURL, + RepositoryName: externalDNSRepoName, + ChartName: externalDNSChartName, + ChartVersion: externalDNSVersion, + ReleaseName: externalDNSRepoName, + ReleaseNamespace: externalDNSRepoName, HelmChartAction: configv1beta1.HelmChartActionInstall, Options: &configv1beta1.HelmOptions{ DependencyUpdate: true, @@ -120,8 +120,8 @@ spec: { Name: "dns-endpoint-gone", FeatureID: libsveltosv1beta1.FeatureHelm, - Group: "externaldns.k8s.io", - Version: "v1alpha1", + Group: externaldnsGroup, + Version: apiVersionV1alpha1, Kind: "DNSEndpoint", Script: luaEvaluateDNSEndpointHealth, }, @@ -140,7 +140,7 @@ spec: Eventually(func() error { depl := &appsv1.Deployment{} return workloadClient.Get(context.TODO(), - types.NamespacedName{Namespace: "external-dns", Name: "external-dns"}, depl) + types.NamespacedName{Namespace: externalDNSRepoName, Name: externalDNSRepoName}, depl) }, timeout, pollingInterval).Should(BeNil()) Expect(k8sClient.Get(context.TODO(), @@ -206,8 +206,8 @@ spec: Expect(dynamicClient).ToNot(BeNil()) gvr := schema.GroupVersionResource{ - Group: "externaldns.k8s.io", - Version: "v1alpha1", + Group: externaldnsGroup, + Version: apiVersionV1alpha1, Resource: "dnsendpoints", } dnsEndpointList, err := dynamicClient.Resource(gvr).Namespace("").List(context.TODO(), metav1.ListOptions{}) @@ -257,7 +257,7 @@ spec: Eventually(func() bool { depl := &appsv1.Deployment{} err = workloadClient.Get(context.TODO(), - types.NamespacedName{Namespace: "external-dns", Name: "external-dns"}, depl) + types.NamespacedName{Namespace: externalDNSRepoName, Name: externalDNSRepoName}, depl) return apierrors.IsNotFound(err) }, timeout, pollingInterval).Should(BeTrue()) diff --git a/test/fv/dependencies_test.go b/test/fv/dependencies_test.go index f29082cc..a7011d2a 100644 --- a/test/fv/dependencies_test.go +++ b/test/fv/dependencies_test.go @@ -70,8 +70,8 @@ var _ = Describe("Dependencies", func() { RepositoryName: "apache-airflow", ChartName: "apache-airflow/airflow", ChartVersion: "1.15.0", - ReleaseName: "airflow", - ReleaseNamespace: "airflow", + ReleaseName: airflowRelease, + ReleaseNamespace: airflowRelease, HelmChartAction: configv1beta1.HelmChartActionInstall, Values: `createUserJob: useHelmHooks: false @@ -98,12 +98,12 @@ migrateDatabaseJob: types.NamespacedName{Name: clusterProfile.Name}, currentClusterProfile)).To(Succeed()) currentClusterProfile.Spec.HelmCharts = []configv1beta1.HelmChart{ { - RepositoryURL: "https://charts.bitnami.com/bitnami", - RepositoryName: "bitnami", + RepositoryURL: bitnamiURL, + RepositoryName: bitnamiName, ChartName: "bitnami/flink", ChartVersion: "1.4.0", - ReleaseName: "flink", - ReleaseNamespace: "flink", + ReleaseName: flinkRelease, + ReleaseNamespace: flinkRelease, HelmChartAction: configv1beta1.HelmChartActionInstall, }, } diff --git a/test/fv/drift_test.go b/test/fv/drift_test.go index 0918c210..9a0ab0a9 100644 --- a/test/fv/drift_test.go +++ b/test/fv/drift_test.go @@ -103,9 +103,8 @@ const ( var _ = Describe("Helm", Serial, func() { const ( - namePrefix = "drift-" - kyvernoAdmissionImageName = "kyverno" - kyvernoCleanupImageName = "controller" + namePrefix = "drift-" + kyvernoCleanupImageName = "controller" ) It("React to configuration drift and verifies Values/ValuesFrom", Label("FV", "PULLMODE", "EXTENDED"), func() { @@ -126,8 +125,8 @@ var _ = Describe("Helm", Serial, func() { Resource: corev1.ObjectReference{ Kind: kindWorkloadCluster.GetKind(), APIVersion: kindWorkloadCluster.GetAPIVersion(), - Name: "{{ .Cluster.metadata.name }}", - Namespace: "{{ .Cluster.metadata.namespace }}", + Name: clusterNameTemplate, + Namespace: clusterNamespaceTemplate, }, IgnoreStatusChanges: true, }, @@ -164,7 +163,7 @@ var _ = Describe("Helm", Serial, func() { labelsConfigMap := createConfigMapWithPolicy(configMapNamespace, randomString(), fmt.Sprintf(labelsValues, clusterKey)) labelsConfigMap.Annotations = map[string]string{ - libsveltosv1beta1.PolicyTemplateAnnotation: "ok", + libsveltosv1beta1.PolicyTemplateAnnotation: annotationOkValue, } Expect(k8sClient.Create(context.TODO(), labelsConfigMap)).To(Succeed()) @@ -179,12 +178,12 @@ var _ = Describe("Helm", Serial, func() { types.NamespacedName{Name: clusterProfile.Name}, currentClusterProfile)).To(Succeed()) currentClusterProfile.Spec.HelmCharts = []configv1beta1.HelmChart{ { - RepositoryURL: "https://kyverno.github.io/kyverno/", - RepositoryName: "kyverno", - ChartName: "kyverno/kyverno", - ChartVersion: "v3.5.2", - ReleaseName: "kyverno-latest", - ReleaseNamespace: "kyverno", + RepositoryURL: kyvernoRepoURL, + RepositoryName: kyvernoNamespace, + ChartName: kyvernoChartName, + ChartVersion: kyvernoVersion352, + ReleaseName: kyvernoLatestRelease, + ReleaseNamespace: kyvernoNamespace, HelmChartAction: configv1beta1.HelmChartActionInstall, Values: `admissionController: replicas: 1 @@ -219,9 +218,9 @@ reportsController: { Paths: []string{"/spec/replicas"}, Target: &libsveltosv1beta1.PatchSelector{ - Kind: "Deployment", - Group: "apps", - Version: "v1", + Kind: kindDeployment, + Group: appsGroupName, + Version: apiVersionV1, Namespace: kyvernoNamespace, Name: cleanupControllerDeplName, }, @@ -234,9 +233,9 @@ reportsController: path: /metadata/annotations/projectsveltos.io~1driftDetectionIgnore value: ok`, Target: &libsveltosv1beta1.PatchSelector{ - Group: "apps", - Version: "v1", - Kind: "Deployment", + Group: appsGroupName, + Version: apiVersionV1, + Kind: kindDeployment, Namespace: kyvernoNamespace, Name: admissionControllerDeplName, }, @@ -290,7 +289,7 @@ reportsController: listOptions := []client.ListOption{ client.MatchingLabels( map[string]string{ - "cluster-name": kindWorkloadCluster.GetName(), + clusterNameKey: kindWorkloadCluster.GetName(), "cluster-namespace": kindWorkloadCluster.GetNamespace(), }, ), @@ -323,7 +322,7 @@ reportsController: verifyFeatureStatusIsProvisioned(kindWorkloadCluster.GetNamespace(), clusterSummary.Name, libsveltosv1beta1.FeatureHelm) charts := []configv1beta1.Chart{ - {ReleaseName: "kyverno-latest", ChartVersion: "3.5.2", Namespace: "kyverno"}, + {ReleaseName: kyvernoLatestRelease, ChartVersion: kyvernoVersion352S, Namespace: kyvernoNamespace}, } verifyClusterConfiguration(configv1beta1.ClusterProfileKind, clusterProfile.Name, @@ -344,7 +343,7 @@ reportsController: // Change Kyverno image depl := &appsv1.Deployment{} Expect(workloadClient.Get(context.TODO(), - types.NamespacedName{Namespace: "kyverno", Name: "kyverno-cleanup-controller"}, depl)).To(Succeed()) + types.NamespacedName{Namespace: kyvernoNamespace, Name: cleanupControllerDeplName}, depl)).To(Succeed()) imageChanged := false for i := range depl.Spec.Template.Spec.Containers { if depl.Spec.Template.Spec.Containers[i].Name == kyvernoCleanupImageName { @@ -356,7 +355,7 @@ reportsController: Expect(workloadClient.Update(context.TODO(), depl)).To(Succeed()) Expect(workloadClient.Get(context.TODO(), - types.NamespacedName{Namespace: "kyverno", Name: "kyverno-cleanup-controller"}, depl)).To(Succeed()) + types.NamespacedName{Namespace: kyvernoNamespace, Name: cleanupControllerDeplName}, depl)).To(Succeed()) for i := range depl.Spec.Template.Spec.Containers { if depl.Spec.Template.Spec.Containers[i].Name == kyvernoCleanupImageName { By("Kyverno image is set to v1.15.1") @@ -368,7 +367,7 @@ reportsController: Eventually(func() bool { depl := &appsv1.Deployment{} err = workloadClient.Get(context.TODO(), - types.NamespacedName{Namespace: "kyverno", Name: "kyverno-cleanup-controller"}, depl) + types.NamespacedName{Namespace: kyvernoNamespace, Name: cleanupControllerDeplName}, depl) if err != nil { return false } @@ -386,10 +385,10 @@ reportsController: // Change Kyverno image for admission controller Expect(workloadClient.Get(context.TODO(), - types.NamespacedName{Namespace: "kyverno", Name: "kyverno-admission-controller"}, depl)).To(Succeed()) + types.NamespacedName{Namespace: kyvernoNamespace, Name: admissionControllerDeplName}, depl)).To(Succeed()) imageChanged = false for i := range depl.Spec.Template.Spec.Containers { - if depl.Spec.Template.Spec.Containers[i].Name == kyvernoAdmissionImageName { + if depl.Spec.Template.Spec.Containers[i].Name == kyvernoNamespace { imageChanged = true depl.Spec.Template.Spec.Containers[i].Image = admissionImage } @@ -399,12 +398,12 @@ reportsController: Eventually(func() bool { err = workloadClient.Get(context.TODO(), - types.NamespacedName{Namespace: "kyverno", Name: "kyverno-admission-controller"}, depl) + types.NamespacedName{Namespace: kyvernoNamespace, Name: admissionControllerDeplName}, depl) if err != nil { return false } for i := range depl.Spec.Template.Spec.Containers { - if depl.Spec.Template.Spec.Containers[i].Name == kyvernoAdmissionImageName { + if depl.Spec.Template.Spec.Containers[i].Name == kyvernoNamespace { By("Kyverno image is set to v1.15.1") return depl.Spec.Template.Spec.Containers[i].Image == admissionImage } @@ -419,12 +418,12 @@ reportsController: Consistently(func() bool { depl := &appsv1.Deployment{} err = workloadClient.Get(context.TODO(), - types.NamespacedName{Namespace: "kyverno", Name: "kyverno-admission-controller"}, depl) + types.NamespacedName{Namespace: kyvernoNamespace, Name: admissionControllerDeplName}, depl) if err != nil { return false } for i := range depl.Spec.Template.Spec.Containers { - if depl.Spec.Template.Spec.Containers[i].Name == kyvernoAdmissionImageName { + if depl.Spec.Template.Spec.Containers[i].Name == kyvernoNamespace { return depl.Spec.Template.Spec.Containers[i].Image == admissionImage } } @@ -438,12 +437,12 @@ reportsController: currentClusterProfile)).To(Succeed()) currentClusterProfile.Spec.HelmCharts = []configv1beta1.HelmChart{ { - RepositoryURL: "https://kyverno.github.io/kyverno/", - RepositoryName: "kyverno", - ChartName: "kyverno/kyverno", - ChartVersion: "v3.5.1", - ReleaseName: "kyverno-latest", - ReleaseNamespace: "kyverno", + RepositoryURL: kyvernoRepoURL, + RepositoryName: kyvernoNamespace, + ChartName: kyvernoChartName, + ChartVersion: kyvernoVersion351, + ReleaseName: kyvernoLatestRelease, + ReleaseNamespace: kyvernoNamespace, HelmChartAction: configv1beta1.HelmChartActionInstall, Values: `admissionController: replicas: 3 @@ -479,7 +478,7 @@ reportsController: expectedReplicas := int32(3) depl := &appsv1.Deployment{} err = workloadClient.Get(context.TODO(), - types.NamespacedName{Namespace: "kyverno", Name: "kyverno-admission-controller"}, depl) + types.NamespacedName{Namespace: kyvernoNamespace, Name: admissionControllerDeplName}, depl) if err != nil { return false } @@ -515,7 +514,7 @@ reportsController: Eventually(func() bool { depl := &appsv1.Deployment{} err = workloadClient.Get(context.TODO(), - types.NamespacedName{Namespace: "kyverno", Name: "kyverno-latest"}, depl) + types.NamespacedName{Namespace: kyvernoNamespace, Name: kyvernoLatestRelease}, depl) return apierrors.IsNotFound(err) }, timeout, pollingInterval).Should(BeTrue()) @@ -529,7 +528,7 @@ func isAgentLessMode() bool { By("Getting addon-controller pod") addonControllerDepl := &appsv1.Deployment{} Expect(k8sClient.Get(context.TODO(), - types.NamespacedName{Namespace: sveltosNamespace, Name: "addon-controller"}, + types.NamespacedName{Namespace: sveltosNamespace, Name: addonDeplName}, addonControllerDepl)).To(Succeed()) Expect(len(addonControllerDepl.Spec.Template.Spec.Containers)).To(Equal(1)) @@ -627,10 +626,9 @@ func verifyResourceSummary(c client.Client, clusterSummary *configv1beta1.Cluste Expect(currentResourceSummary).ToNot(BeNil()) - deploymentKind := "Deployment" - verifyAdmissionControllerDeployment(c, currentResourceSummary, deploymentKind) + verifyAdmissionControllerDeployment(c, currentResourceSummary, kindDeployment) - verifySpecReplicas(currentResourceSummary, deploymentKind) + verifySpecReplicas(currentResourceSummary, kindDeployment) } func verifyAdmissionControllerDeployment(c client.Client, diff --git a/test/fv/dryrun_test.go b/test/fv/dryrun_test.go index 5c018801..6069c28c 100644 --- a/test/fv/dryrun_test.go +++ b/test/fv/dryrun_test.go @@ -74,10 +74,7 @@ rules: ) var _ = Describe("DryRun", Serial, func() { - const ( - namePrefix = "dry-run-" - certManager = "cert-manager" - ) + const namePrefix = "dry-run-" It("Correctly reports helm chart that would be installed, uninstalled or have conflicts", Label("NEW-FV", "NEW-FV-PULLMODE", "EXTENDED"), func() { @@ -134,7 +131,7 @@ var _ = Describe("DryRun", Serial, func() { verifyFeatureStatusIsProvisioned(kindWorkloadCluster.GetNamespace(), clusterSummary.Name, libsveltosv1beta1.FeatureResources) policies := []policy{ - {kind: "ServiceAccount", name: "kong-serviceaccount", namespace: "kong", group: ""}, + {kind: kindServiceAccount, name: kongServiceAccountName, namespace: kongRepoName, group: ""}, } verifyClusterConfiguration(configv1beta1.ClusterProfileKind, clusterProfile.Name, clusterSummary.Spec.ClusterNamespace, clusterSummary.Spec.ClusterName, libsveltosv1beta1.FeatureResources, @@ -148,12 +145,12 @@ var _ = Describe("DryRun", Serial, func() { types.NamespacedName{Name: clusterProfile.Name}, currentClusterProfile)).To(Succeed()) currentClusterProfile.Spec.HelmCharts = []configv1beta1.HelmChart{ { - RepositoryURL: "https://helm.mariadb.com/mariadb-operator", - RepositoryName: "mariadb-operator", - ChartName: "mariadb-operator/mariadb-operator", - ChartVersion: "0.35.1", - ReleaseName: "mariadb", - ReleaseNamespace: "mariadb", + RepositoryURL: mariadbOperatorURL, + RepositoryName: mariadbOperatorName, + ChartName: mariadbOperatorChart, + ChartVersion: mariadbVersion0351, + ReleaseName: mariadbRelease, + ReleaseNamespace: mariadbRelease, HelmChartAction: configv1beta1.HelmChartActionInstall, }, } @@ -175,7 +172,7 @@ var _ = Describe("DryRun", Serial, func() { verifyFeatureStatusIsProvisioned(kindWorkloadCluster.GetNamespace(), clusterSummary.Name, libsveltosv1beta1.FeatureResources) charts := []configv1beta1.Chart{ - {ReleaseName: "mariadb", ChartVersion: "0.35.1", Namespace: "mariadb"}, + {ReleaseName: mariadbRelease, ChartVersion: mariadbVersion0351, Namespace: mariadbRelease}, } verifyClusterConfiguration(configv1beta1.ClusterProfileKind, clusterProfile.Name, @@ -229,32 +226,31 @@ var _ = Describe("DryRun", Serial, func() { currentClusterProfile)).To(Succeed()) currentClusterProfile.Spec.HelmCharts = []configv1beta1.HelmChart{ { - RepositoryURL: "https://helm.mariadb.com/mariadb-operator", - RepositoryName: "mariadb-operator", - ChartName: "mariadb-operator/mariadb-operator", - ChartVersion: "25.8.4", - ReleaseName: "mariadb", - ReleaseNamespace: "mariadb", + RepositoryURL: mariadbOperatorURL, + RepositoryName: mariadbOperatorName, + ChartName: mariadbOperatorChart, + ChartVersion: prometheusVersion2584, + ReleaseName: mariadbRelease, + ReleaseNamespace: mariadbRelease, HelmChartAction: configv1beta1.HelmChartActionInstall, }, { - RepositoryURL: "https://charts.jetstack.io", - RepositoryName: "jetstack", - ChartName: "jetstack/cert-manager", - ChartVersion: "v1.18.2", + RepositoryURL: jetstackURL, + RepositoryName: jetstackName, + ChartName: jetstackCertManagerChart, + ChartVersion: externalDNSVersion1182, ReleaseName: certManager, ReleaseNamespace: certManager, HelmChartAction: configv1beta1.HelmChartActionInstall, - Values: `crds: - enabled: true`, + Values: crdsEnabledValues, }, { - RepositoryURL: "https://cloudnative-pg.github.io/charts", - RepositoryName: "cloudnative-pg", - ChartName: "cloudnative-pg/cloudnative-pg", - ChartVersion: "0.26.0", - ReleaseName: "cnpg", - ReleaseNamespace: "cnpg-system", + RepositoryURL: cloudnativePGURL, + RepositoryName: cloudnativePGName, + ChartName: cloudnativePGChart, + ChartVersion: cloudnativePGVersion, + ReleaseName: cnpgRelease, + ReleaseNamespace: cnpgSystem, HelmChartAction: configv1beta1.HelmChartActionUninstall, }, } @@ -281,12 +277,12 @@ var _ = Describe("DryRun", Serial, func() { } // If not in DryRun, it would create Kong Role err = verifyResourceReport(currentClusterReport, "kong2", "kong-leader-election", - "Role", "rbac.authorization.k8s.io", string(libsveltosv1beta1.CreateResourceAction)) + "Role", rbacAuthGroup, string(libsveltosv1beta1.CreateResourceAction)) if err != nil { return err } // Another ClusterProfile is managing this, even though by referencing same ConfigMap this ClusterProfile is, so conflict. - err = verifyResourceReport(currentClusterReport, "kong", "kong-serviceaccount", + err = verifyResourceReport(currentClusterReport, kongRepoName, kongServiceAccountName, "ServiceAccount", "", string(libsveltosv1beta1.ConflictResourceAction)) if err != nil { return err @@ -319,12 +315,12 @@ var _ = Describe("DryRun", Serial, func() { } // If not in DryRun, it would create Kong Role err = verifyResourceReport(currentClusterReport, "kong2", "kong-leader-election", - "Role", "rbac.authorization.k8s.io", string(libsveltosv1beta1.CreateResourceAction)) + "Role", rbacAuthGroup, string(libsveltosv1beta1.CreateResourceAction)) if err != nil { return err } // Another ClusterProfile is managing this, even though by referencing same ConfigMap this ClusterProfile is, so conflict. - err = verifyResourceReport(currentClusterReport, "kong", "kong-serviceaccount", + err = verifyResourceReport(currentClusterReport, kongRepoName, kongServiceAccountName, "ServiceAccount", "", string(libsveltosv1beta1.UpdateResourceAction)) if err != nil { return err @@ -342,7 +338,7 @@ var _ = Describe("DryRun", Serial, func() { currentServiceAccount := &corev1.ServiceAccount{} err = workloadClient.Get(context.TODO(), - types.NamespacedName{Namespace: "kong", Name: "kong-serviceaccount"}, currentServiceAccount) + types.NamespacedName{Namespace: kongRepoName, Name: kongServiceAccountName}, currentServiceAccount) Expect(err).ToNot(BeNil()) Expect(apierrors.IsNotFound(err)).To(BeTrue()) @@ -351,32 +347,31 @@ var _ = Describe("DryRun", Serial, func() { currentClusterProfile.Spec.SyncMode = configv1beta1.SyncModeContinuous currentClusterProfile.Spec.HelmCharts = []configv1beta1.HelmChart{ { - RepositoryURL: "https://helm.mariadb.com/mariadb-operator", - RepositoryName: "mariadb-operator", - ChartName: "mariadb-operator/mariadb-operator", - ChartVersion: "25.8.4", - ReleaseName: "mariadb", - ReleaseNamespace: "mariadb", + RepositoryURL: mariadbOperatorURL, + RepositoryName: mariadbOperatorName, + ChartName: mariadbOperatorChart, + ChartVersion: prometheusVersion2584, + ReleaseName: mariadbRelease, + ReleaseNamespace: mariadbRelease, HelmChartAction: configv1beta1.HelmChartActionInstall, }, { - RepositoryURL: "https://charts.jetstack.io", - RepositoryName: "jetstack", - ChartName: "jetstack/cert-manager", - ChartVersion: "v1.18.2", + RepositoryURL: jetstackURL, + RepositoryName: jetstackName, + ChartName: jetstackCertManagerChart, + ChartVersion: externalDNSVersion1182, ReleaseName: certManager, ReleaseNamespace: certManager, HelmChartAction: configv1beta1.HelmChartActionInstall, - Values: `crds: - enabled: true`, + Values: crdsEnabledValues, }, { - RepositoryURL: "https://cloudnative-pg.github.io/charts", - RepositoryName: "cloudnative-pg", - ChartName: "cloudnative-pg/cloudnative-pg", - ChartVersion: "0.26.0", - ReleaseName: "cnpg", - ReleaseNamespace: "cnpg-system", + RepositoryURL: cloudnativePGURL, + RepositoryName: cloudnativePGName, + ChartName: cloudnativePGChart, + ChartVersion: cloudnativePGVersion, + ReleaseName: cnpgRelease, + ReleaseNamespace: cnpgSystem, HelmChartAction: configv1beta1.HelmChartActionInstall, }, } @@ -390,7 +385,7 @@ var _ = Describe("DryRun", Serial, func() { Eventually(func() bool { Byf("Verifying ServiceAccount kong/kong-serviceaccount is deployed managed cluster") err = workloadClient.Get(context.TODO(), - types.NamespacedName{Namespace: "kong", Name: "kong-serviceaccount"}, currentServiceAccount) + types.NamespacedName{Namespace: kongRepoName, Name: kongServiceAccountName}, currentServiceAccount) if err != nil { return false } @@ -404,14 +399,14 @@ var _ = Describe("DryRun", Serial, func() { Byf("Verifying Deployment mariadb/mariadb-mariadb-operator is deployed managed cluster") err = workloadClient.Get(context.TODO(), - types.NamespacedName{Namespace: "mariadb", Name: "mariadb-mariadb-operator"}, currentDepl) + types.NamespacedName{Namespace: mariadbRelease, Name: mariadbOperatorDeployName}, currentDepl) if err != nil { return false } Byf("Verifying Deployment cnpg-system/cnpg-cloudnative-pg is deployed managed cluster") err = workloadClient.Get(context.TODO(), - types.NamespacedName{Namespace: "cnpg-system", Name: "cnpg-cloudnative-pg"}, currentDepl) + types.NamespacedName{Namespace: cnpgSystem, Name: cnpgDeployName}, currentDepl) return err == nil }, timeout, pollingInterval).Should(BeTrue()) @@ -432,34 +427,32 @@ var _ = Describe("DryRun", Serial, func() { } currentClusterProfile.Spec.HelmCharts = []configv1beta1.HelmChart{ { - RepositoryURL: "https://helm.mariadb.com/mariadb-operator", - RepositoryName: "mariadb-operator", - ChartName: "mariadb-operator/mariadb-operator", - ChartVersion: "25.8.4", - ReleaseName: "mariadb", - ReleaseNamespace: "mariadb", + RepositoryURL: mariadbOperatorURL, + RepositoryName: mariadbOperatorName, + ChartName: mariadbOperatorChart, + ChartVersion: prometheusVersion2584, + ReleaseName: mariadbRelease, + ReleaseNamespace: mariadbRelease, HelmChartAction: configv1beta1.HelmChartActionInstall, - Values: `crds: - enabled: true`, + Values: crdsEnabledValues, }, { - RepositoryURL: "https://charts.jetstack.io", - RepositoryName: "jetstack", - ChartName: "jetstack/cert-manager", - ChartVersion: "v1.18.2", + RepositoryURL: jetstackURL, + RepositoryName: jetstackName, + ChartName: jetstackCertManagerChart, + ChartVersion: externalDNSVersion1182, ReleaseName: certManager, ReleaseNamespace: certManager, HelmChartAction: configv1beta1.HelmChartActionInstall, - Values: `crds: - enabled: true`, + Values: crdsEnabledValues, }, { - RepositoryURL: "https://cloudnative-pg.github.io/charts", - RepositoryName: "cloudnative-pg", - ChartName: "cloudnative-pg/cloudnative-pg", - ChartVersion: "0.26.0", - ReleaseName: "cnpg", - ReleaseNamespace: "cnpg-system", + RepositoryURL: cloudnativePGURL, + RepositoryName: cloudnativePGName, + ChartName: cloudnativePGChart, + ChartVersion: cloudnativePGVersion, + ReleaseName: cnpgRelease, + ReleaseNamespace: cnpgSystem, HelmChartAction: configv1beta1.HelmChartActionUninstall, }, } @@ -479,7 +472,7 @@ var _ = Describe("DryRun", Serial, func() { certManagerRR := &libsveltosv1beta1.ResourceReport{ Resource: libsveltosv1beta1.Resource{ - Kind: "ServiceAccount", + Kind: kindServiceAccount, Name: certManager, }, Action: string(libsveltosv1beta1.NoResourceAction), @@ -536,13 +529,13 @@ var _ = Describe("DryRun", Serial, func() { } // If not in DryRun, it would create Kong Role err = verifyResourceReport(currentClusterReport, "kong2", "kong-leader-election", - "Role", "rbac.authorization.k8s.io", string(libsveltosv1beta1.NoResourceAction)) + "Role", rbacAuthGroup, string(libsveltosv1beta1.NoResourceAction)) if err != nil { return err } // Previously installed this resource. Now not referencing the ConfigMap with this resource anymore. // So action would be delete - err = verifyResourceReport(currentClusterReport, "kong", "kong-serviceaccount", + err = verifyResourceReport(currentClusterReport, kongRepoName, kongServiceAccountName, "ServiceAccount", "", string(libsveltosv1beta1.DeleteResourceAction)) if err != nil { return err @@ -552,7 +545,7 @@ var _ = Describe("DryRun", Serial, func() { Byf("Verifying ServiceAccount kong/kong-serviceaccount is still on managed cluster") err = workloadClient.Get(context.TODO(), - types.NamespacedName{Namespace: "kong", Name: "kong-serviceaccount"}, currentServiceAccount) + types.NamespacedName{Namespace: kongRepoName, Name: kongServiceAccountName}, currentServiceAccount) Expect(err).To(BeNil()) Byf("Verifying ServiceAccount cert-manager/cert-manager is still on managed cluster") @@ -562,12 +555,12 @@ var _ = Describe("DryRun", Serial, func() { Byf("Verifying Deployment mariadb/mariadb-mariadb-operator is still on managed cluster") err = workloadClient.Get(context.TODO(), - types.NamespacedName{Namespace: "mariadb", Name: "mariadb-mariadb-operator"}, currentDepl) + types.NamespacedName{Namespace: mariadbRelease, Name: mariadbOperatorDeployName}, currentDepl) Expect(err).To(BeNil()) Byf("Verifying Deployment cnpg-system/cnpg-cloudnative-pg is still on managed cluster") err = workloadClient.Get(context.TODO(), - types.NamespacedName{Namespace: "cnpg-system", Name: "cnpg-cloudnative-pg"}, currentDepl) + types.NamespacedName{Namespace: cnpgSystem, Name: cnpgDeployName}, currentDepl) Expect(err).To(BeNil()) Byf("Changing clusterSelector for ClusterProfile %s so to not match any cluster", dryRunClusterProfile.Name) @@ -611,8 +604,8 @@ var _ = Describe("DryRun", Serial, func() { mariadDBRR = &libsveltosv1beta1.ResourceReport{ Resource: libsveltosv1beta1.Resource{ - Kind: "ServiceAccount", - Name: "mariadb-mariadb-operator", + Kind: kindServiceAccount, + Name: mariadbOperatorDeployName, }, Action: string(libsveltosv1beta1.DeleteResourceAction), } @@ -663,13 +656,13 @@ var _ = Describe("DryRun", Serial, func() { } // If not in DryRun, it would create Kong Role err = verifyResourceReport(currentClusterReport, "kong2", "kong-leader-election", - "Role", "rbac.authorization.k8s.io", string(libsveltosv1beta1.DeleteResourceAction)) + "Role", rbacAuthGroup, string(libsveltosv1beta1.DeleteResourceAction)) if err != nil { return err } // Previously installed this resource. Now not referencing the ConfigMap with this resource anymore. // So action would be delete - err = verifyResourceReport(currentClusterReport, "kong", "kong-serviceaccount", + err = verifyResourceReport(currentClusterReport, kongRepoName, kongServiceAccountName, "ServiceAccount", "", string(libsveltosv1beta1.DeleteResourceAction)) if err != nil { return err @@ -691,7 +684,7 @@ var _ = Describe("DryRun", Serial, func() { Byf("Verifying ServiceAccount kong/kong-serviceaccount is removed from managed cluster") err = workloadClient.Get(context.TODO(), - types.NamespacedName{Namespace: "kong", Name: "kong-serviceaccount"}, currentServiceAccount) + types.NamespacedName{Namespace: kongRepoName, Name: kongServiceAccountName}, currentServiceAccount) Expect(err).ToNot(BeNil()) Expect(apierrors.IsNotFound(err)).To(BeTrue()) @@ -703,13 +696,13 @@ var _ = Describe("DryRun", Serial, func() { Byf("Verifying Deployment mariadb/mariadb-mariadb-operator is removed from managed cluster") err = workloadClient.Get(context.TODO(), - types.NamespacedName{Namespace: "mariadb", Name: "mariadb-mariadb-operator"}, currentDepl) + types.NamespacedName{Namespace: mariadbRelease, Name: mariadbOperatorDeployName}, currentDepl) Expect(err).ToNot(BeNil()) Expect(apierrors.IsNotFound(err)).To(BeTrue()) Byf("Verifying Deployment cnpg-system/cnpg-cloudnative-pg is removed from managed cluster") err = workloadClient.Get(context.TODO(), - types.NamespacedName{Namespace: "cnpg-system", Name: "cnpg-cloudnative-pg"}, currentDepl) + types.NamespacedName{Namespace: cnpgSystem, Name: cnpgDeployName}, currentDepl) Expect(err).ToNot(BeNil()) Expect(apierrors.IsNotFound(err)).To(BeTrue()) }) diff --git a/test/fv/fv_suite_test.go b/test/fv/fv_suite_test.go index 7933c466..36f9b4a5 100644 --- a/test/fv/fv_suite_test.go +++ b/test/fv/fv_suite_test.go @@ -56,7 +56,7 @@ var ( func init() { sveltosNamespace = os.Getenv("SVELTOS_NAMESPACE") if sveltosNamespace == "" { - sveltosNamespace = "projectsveltos" + sveltosNamespace = defaultSveltosNamespace } } @@ -159,7 +159,7 @@ func verifyCAPICluster() { clusterList := &clusterv1.ClusterList{} listOptions := []client.ListOption{ client.MatchingLabels( - map[string]string{clusterv1.ClusterNameLabel: "clusterapi-workload"}, + map[string]string{clusterv1.ClusterNameLabel: clusterapiWorkloadName}, ), } @@ -227,7 +227,7 @@ func verifySveltosCluster() { clusterList := &libsveltosv1beta1.SveltosClusterList{} listOptions := []client.ListOption{ client.MatchingLabels( - map[string]string{"cluster-name": "clusterapi-workload"}, // This label is added by Makefile + map[string]string{clusterNameKey: clusterapiWorkloadName}, // This label is added by Makefile ), } diff --git a/test/fv/helm_conflict_test.go b/test/fv/helm_conflict_test.go index 5d30a813..2690c27d 100644 --- a/test/fv/helm_conflict_test.go +++ b/test/fv/helm_conflict_test.go @@ -72,11 +72,11 @@ var _ = Describe("Helm with conflicts", func() { Eventually(func() error { statefulSet := &appsv1.StatefulSet{} return workloadClient.Get(context.TODO(), - types.NamespacedName{Namespace: "spark", Name: "spark-master"}, statefulSet) + types.NamespacedName{Namespace: sparkName, Name: sparkMasterName}, statefulSet) }, timeout, pollingInterval).Should(BeNil()) charts := []configv1beta1.Chart{ - {ReleaseName: "spark", ChartVersion: sparkVersion, Namespace: "spark"}, + {ReleaseName: sparkName, ChartVersion: sparkVersion, Namespace: sparkName}, } verifyClusterConfiguration(configv1beta1.ClusterProfileKind, clusterProfile.Name, clusterSummary.Spec.ClusterNamespace, clusterSummary.Spec.ClusterName, libsveltosv1beta1.FeatureHelm, @@ -127,7 +127,7 @@ var _ = Describe("Helm with conflicts", func() { Eventually(func() error { statefulSet := &appsv1.StatefulSet{} return workloadClient.Get(context.TODO(), - types.NamespacedName{Namespace: "spark", Name: "spark-master"}, statefulSet) + types.NamespacedName{Namespace: sparkName, Name: sparkMasterName}, statefulSet) }, timeout/2, pollingInterval).Should(BeNil()) } else { // Since second ClusterProfile is waiting to manage same helm chart, it should not be ever @@ -136,12 +136,12 @@ var _ = Describe("Helm with conflicts", func() { Consistently(func() error { statefulSet := &appsv1.StatefulSet{} return workloadClient.Get(context.TODO(), - types.NamespacedName{Namespace: "spark", Name: "spark-master"}, statefulSet) + types.NamespacedName{Namespace: sparkName, Name: sparkMasterName}, statefulSet) }, timeout/2, pollingInterval).Should(BeNil()) } charts = []configv1beta1.Chart{ - {ReleaseName: "spark", ChartVersion: sparkVersion, Namespace: "spark"}, + {ReleaseName: sparkName, ChartVersion: sparkVersion, Namespace: sparkName}, } verifyClusterConfiguration(configv1beta1.ClusterProfileKind, clusterProfile2.Name, clusterSummary.Spec.ClusterNamespace, clusterSummary.Spec.ClusterName, libsveltosv1beta1.FeatureHelm, @@ -154,7 +154,7 @@ var _ = Describe("Helm with conflicts", func() { Eventually(func() bool { statefulSet := &appsv1.StatefulSet{} err = workloadClient.Get(context.TODO(), - types.NamespacedName{Namespace: "spark", Name: "spark-master"}, statefulSet) + types.NamespacedName{Namespace: sparkName, Name: sparkMasterName}, statefulSet) if err == nil { return !statefulSet.DeletionTimestamp.IsZero() } @@ -171,12 +171,12 @@ func addSparkHelmChart(clusterProfileName, version string) { Expect(k8sClient.Get(context.TODO(), types.NamespacedName{Name: clusterProfileName}, currentClusterProfile)).To(Succeed()) currentClusterProfile.Spec.HelmCharts = []configv1beta1.HelmChart{ { - RepositoryURL: "https://charts.bitnami.com/bitnami", - RepositoryName: "bitnami", + RepositoryURL: bitnamiURL, + RepositoryName: bitnamiName, ChartName: "bitnami/spark", ChartVersion: version, - ReleaseName: "spark", - ReleaseNamespace: "spark", + ReleaseName: sparkName, + ReleaseNamespace: sparkName, HelmChartAction: configv1beta1.HelmChartActionInstall, }, } diff --git a/test/fv/helm_error_test.go b/test/fv/helm_error_test.go index 86e197b4..dc3effa2 100644 --- a/test/fv/helm_error_test.go +++ b/test/fv/helm_error_test.go @@ -58,10 +58,7 @@ data: ) var _ = Describe("Feature", Serial, func() { - const ( - namePrefix = "helm-error-" - certManager = "cert-manager" - ) + const namePrefix = "helm-error-" It("An error in helm values does not remove helm chart", Label("FV", "PULLMODE"), func() { Byf("Create a configMap with valid helm values") @@ -91,12 +88,12 @@ var _ = Describe("Feature", Serial, func() { currentClusterProfile.Spec.HelmCharts = []configv1beta1.HelmChart{ { - RepositoryURL: "https://charts.jetstack.io", - RepositoryName: "jetstack", - ChartName: "jetstack/cert-manager", + RepositoryURL: jetstackURL, + RepositoryName: jetstackName, + ChartName: jetstackCertManagerChart, ChartVersion: "v1.19.4", - ReleaseName: "cert-manager", - ReleaseNamespace: "cert-manager", + ReleaseName: certManager, + ReleaseNamespace: certManager, HelmChartAction: configv1beta1.HelmChartActionInstall, ValuesFrom: []configv1beta1.ValueFrom{ { diff --git a/test/fv/helm_failure_message_test.go b/test/fv/helm_failure_message_test.go index c1906aa6..fd60004d 100644 --- a/test/fv/helm_failure_message_test.go +++ b/test/fv/helm_failure_message_test.go @@ -73,12 +73,12 @@ var _ = Describe("Helm with conflicts", func() { currentClusterProfile.Spec.ContinueOnConflict = true currentClusterProfile.Spec.HelmCharts = []configv1beta1.HelmChart{ { - RepositoryURL: "oci://ghcr.io/k0rdent/catalog/charts", - RepositoryName: "ingress-nginx", - ChartName: "ingress-nginx", + RepositoryURL: k0rdentCatalogURL, + RepositoryName: ingressNginxName, + ChartName: ingressNginxName, ChartVersion: "4.13.0", - ReleaseName: "nginx", - ReleaseNamespace: "nginx", + ReleaseName: nginxNamespace, + ReleaseNamespace: nginxNamespace, HelmChartAction: configv1beta1.HelmChartActionInstall, Options: &configv1beta1.HelmOptions{ InstallOptions: configv1beta1.HelmInstallOptions{ @@ -96,12 +96,12 @@ var _ = Describe("Helm with conflicts", func() { registry: this.does.not.exist.com`, }, { - RepositoryURL: "oci://ghcr.io/k0rdent/catalog/charts", - RepositoryName: "postgres-operator", - ChartName: "postgres-operator", + RepositoryURL: k0rdentCatalogURL, + RepositoryName: postgresOperatorName, + ChartName: postgresOperatorName, ChartVersion: "1.15.1", - ReleaseName: "postgres-operator", - ReleaseNamespace: "postgres-operator", + ReleaseName: postgresOperatorName, + ReleaseNamespace: postgresOperatorName, HelmChartAction: configv1beta1.HelmChartActionInstall, RegistryCredentialsConfig: &configv1beta1.RegistryCredentialsConfig{ PlainHTTP: true, diff --git a/test/fv/helm_options_test.go b/test/fv/helm_options_test.go index fcc2744a..136e62e1 100644 --- a/test/fv/helm_options_test.go +++ b/test/fv/helm_options_test.go @@ -59,12 +59,12 @@ var _ = Describe("HelmOptions", func() { types.NamespacedName{Name: clusterProfile.Name}, currentClusterProfile)).To(Succeed()) currentClusterProfile.Spec.HelmCharts = []configv1beta1.HelmChart{ { - RepositoryURL: "https://kubernetes-sigs.github.io/external-dns/", - RepositoryName: "external-dns", - ChartName: "external-dns/external-dns", - ChartVersion: "1.20.0", - ReleaseName: "external-dns", - ReleaseNamespace: "external-dns", + RepositoryURL: externalDNSURL, + RepositoryName: externalDNSRepoName, + ChartName: externalDNSChartName, + ChartVersion: externalDNSVersion, + ReleaseName: externalDNSRepoName, + ReleaseNamespace: externalDNSRepoName, HelmChartAction: configv1beta1.HelmChartActionInstall, Options: &configv1beta1.HelmOptions{ DependencyUpdate: true, @@ -95,18 +95,18 @@ var _ = Describe("HelmOptions", func() { Eventually(func() error { depl := &appsv1.Deployment{} return workloadClient.Get(context.TODO(), - types.NamespacedName{Namespace: "external-dns", Name: "external-dns"}, depl) + types.NamespacedName{Namespace: externalDNSRepoName, Name: externalDNSRepoName}, depl) }, timeout, pollingInterval).Should(BeNil()) Byf("Verifying external-dns deployment image") depl := &appsv1.Deployment{} Expect(workloadClient.Get(context.TODO(), - types.NamespacedName{Namespace: "external-dns", Name: "external-dns"}, depl)).To(Succeed()) + types.NamespacedName{Namespace: externalDNSRepoName, Name: externalDNSRepoName}, depl)).To(Succeed()) Expect(len(depl.Spec.Template.Spec.Containers)).To(Equal(1)) Expect(depl.Spec.Template.Spec.Containers[0].Image).To(ContainSubstring("v0.20.0")) charts := []configv1beta1.Chart{ - {ReleaseName: "external-dns", ChartVersion: "1.20.0", Namespace: "external-dns"}, + {ReleaseName: externalDNSRepoName, ChartVersion: externalDNSVersion, Namespace: externalDNSRepoName}, } verifyClusterConfiguration(configv1beta1.ClusterProfileKind, clusterProfile.Name, @@ -120,12 +120,12 @@ var _ = Describe("HelmOptions", func() { types.NamespacedName{Name: clusterProfile.Name}, currentClusterProfile)).To(Succeed()) currentClusterProfile.Spec.HelmCharts = []configv1beta1.HelmChart{ { - RepositoryURL: "https://kubernetes-sigs.github.io/external-dns/", - RepositoryName: "external-dns", - ChartName: "external-dns/external-dns", - ChartVersion: "1.17.0", - ReleaseName: "external-dns", - ReleaseNamespace: "external-dns", + RepositoryURL: externalDNSURL, + RepositoryName: externalDNSRepoName, + ChartName: externalDNSChartName, + ChartVersion: externalDNSVersion1170, + ReleaseName: externalDNSRepoName, + ReleaseNamespace: externalDNSRepoName, HelmChartAction: configv1beta1.HelmChartActionInstall, Options: &configv1beta1.HelmOptions{ DependencyUpdate: true, @@ -152,7 +152,7 @@ var _ = Describe("HelmOptions", func() { Eventually(func() bool { depl := &appsv1.Deployment{} err = workloadClient.Get(context.TODO(), - types.NamespacedName{Namespace: "external-dns", Name: "external-dns"}, depl) + types.NamespacedName{Namespace: externalDNSRepoName, Name: externalDNSRepoName}, depl) if err != nil { return false } @@ -169,12 +169,12 @@ var _ = Describe("HelmOptions", func() { types.NamespacedName{Name: clusterProfile.Name}, currentClusterProfile)).To(Succeed()) currentClusterProfile.Spec.HelmCharts = []configv1beta1.HelmChart{ { - RepositoryURL: "https://kubernetes-sigs.github.io/external-dns/", - RepositoryName: "external-dns", - ChartName: "external-dns/external-dns", - ChartVersion: "1.17.0", - ReleaseName: "external-dns", - ReleaseNamespace: "external-dns", + RepositoryURL: externalDNSURL, + RepositoryName: externalDNSRepoName, + ChartName: externalDNSChartName, + ChartVersion: externalDNSVersion1170, + ReleaseName: externalDNSRepoName, + ReleaseNamespace: externalDNSRepoName, HelmChartAction: configv1beta1.HelmChartActionUninstall, Options: &configv1beta1.HelmOptions{ DependencyUpdate: true, @@ -194,7 +194,7 @@ var _ = Describe("HelmOptions", func() { Eventually(func() bool { depl := &appsv1.Deployment{} err = workloadClient.Get(context.TODO(), - types.NamespacedName{Namespace: "external-dns", Name: "external-dns"}, depl) + types.NamespacedName{Namespace: externalDNSRepoName, Name: externalDNSRepoName}, depl) return apierrors.IsNotFound(err) }, timeout, pollingInterval).Should(BeTrue()) diff --git a/test/fv/helm_patches_test.go b/test/fv/helm_patches_test.go index 9aa24356..1ad2a353 100644 --- a/test/fv/helm_patches_test.go +++ b/test/fv/helm_patches_test.go @@ -59,9 +59,9 @@ var _ = Describe("Helm with patches", func() { RepositoryURL: "https://argoproj.github.io/argo-helm", RepositoryName: "argo", ChartName: "argo/argo-cd", - ChartVersion: "3.35.4", - ReleaseName: "argocd", - ReleaseNamespace: "argocd", + ChartVersion: argocdChartVersion, + ReleaseName: argocdName, + ReleaseNamespace: argocdName, HelmChartAction: configv1beta1.HelmChartActionInstall, }, } @@ -69,9 +69,9 @@ var _ = Describe("Helm with patches", func() { currentClusterProfile.Spec.Patches = []libsveltosv1beta1.Patch{ { Target: &libsveltosv1beta1.PatchSelector{ - Kind: "Deployment", - Group: "apps", - Version: "v1", + Kind: kindDeployment, + Group: appsGroupName, + Version: apiVersionV1, }, Patch: `- op: add path: /metadata/annotations/test @@ -98,7 +98,7 @@ var _ = Describe("Helm with patches", func() { Eventually(func() bool { depl := &appsv1.Deployment{} err = workloadClient.Get(context.TODO(), - types.NamespacedName{Namespace: "argocd", Name: "argocd-server"}, depl) + types.NamespacedName{Namespace: argocdName, Name: argocdServerName}, depl) if err != nil { return false } @@ -109,7 +109,7 @@ var _ = Describe("Helm with patches", func() { }, timeout, pollingInterval).Should(BeTrue()) charts := []configv1beta1.Chart{ - {ReleaseName: "argocd", ChartVersion: "3.35.4", Namespace: "argocd"}, + {ReleaseName: argocdName, ChartVersion: argocdChartVersion, Namespace: argocdName}, } verifyClusterConfiguration(configv1beta1.ClusterProfileKind, clusterProfile.Name, @@ -124,9 +124,9 @@ var _ = Describe("Helm with patches", func() { currentClusterProfile.Spec.Patches = []libsveltosv1beta1.Patch{ { Target: &libsveltosv1beta1.PatchSelector{ - Kind: "Deployment", - Group: "apps", - Version: "v1", + Kind: kindDeployment, + Group: appsGroupName, + Version: apiVersionV1, }, Patch: `- op: add path: /metadata/annotations/test2 @@ -149,7 +149,7 @@ var _ = Describe("Helm with patches", func() { Eventually(func() bool { depl := &appsv1.Deployment{} err = workloadClient.Get(context.TODO(), - types.NamespacedName{Namespace: "argocd", Name: "argocd-server"}, depl) + types.NamespacedName{Namespace: argocdName, Name: argocdServerName}, depl) if err != nil { return false } diff --git a/test/fv/helm_test.go b/test/fv/helm_test.go index 6ec1b7e3..fa8f427f 100644 --- a/test/fv/helm_test.go +++ b/test/fv/helm_test.go @@ -75,24 +75,24 @@ var _ = Describe("Helm", func() { types.NamespacedName{Name: clusterProfile.Name}, currentClusterProfile)).To(Succeed()) currentClusterProfile.Spec.HelmCharts = []configv1beta1.HelmChart{ { - RepositoryURL: "https://kyverno.github.io/kyverno/", - RepositoryName: "kyverno", - ChartName: "kyverno/kyverno", + RepositoryURL: kyvernoRepoURL, + RepositoryName: kyvernoNamespace, + ChartName: kyvernoChartName, ChartVersion: "v3.7.1", - ReleaseName: "kyverno-latest", - ReleaseNamespace: "kyverno", + ReleaseName: kyvernoLatestRelease, + ReleaseNamespace: kyvernoNamespace, HelmChartAction: configv1beta1.HelmChartActionInstall, Options: &configv1beta1.HelmOptions{ RunTests: true, }, }, { - RepositoryURL: "https://docs.wildfly.org/wildfly-charts/", - RepositoryName: "wildfly", - ChartName: "wildfly/wildfly", - ChartVersion: "2.4.0", - ReleaseName: "wildfly", - ReleaseNamespace: "wildfly", + RepositoryURL: wildflyRepoURL, + RepositoryName: wildflyName, + ChartName: wildflyChartName, + ChartVersion: wildflyVersion, + ReleaseName: wildflyName, + ReleaseNamespace: wildflyName, HelmChartAction: configv1beta1.HelmChartActionInstall, }, } @@ -101,10 +101,10 @@ var _ = Describe("Helm", func() { { Name: "kyverno-deployment-health", FeatureID: libsveltosv1beta1.FeatureHelm, - Namespace: "kyverno", - Group: "apps", - Version: "v1", - Kind: "Deployment", + Namespace: kyvernoNamespace, + Group: appsGroupName, + Version: apiVersionV1, + Kind: kindDeployment, Script: luaEvaluateDeploymentHealth, }, } @@ -129,13 +129,13 @@ var _ = Describe("Helm", func() { Eventually(func() error { depl := &appsv1.Deployment{} return workloadClient.Get(context.TODO(), - types.NamespacedName{Namespace: "kyverno", Name: "kyverno-admission-controller"}, depl) + types.NamespacedName{Namespace: kyvernoNamespace, Name: admissionControllerDeplName}, depl) }, timeout, pollingInterval).Should(BeNil()) Byf("Verifying kyverno deployment has proper labels/annotations") depl := &appsv1.Deployment{} Expect(workloadClient.Get(context.TODO(), - types.NamespacedName{Namespace: "kyverno", Name: "kyverno-admission-controller"}, depl)) + types.NamespacedName{Namespace: kyvernoNamespace, Name: admissionControllerDeplName}, depl)) content, err := runtime.DefaultUnstructuredConverter.ToUnstructured(depl) Expect(err).To(BeNil()) var u unstructured.Unstructured @@ -145,15 +145,15 @@ var _ = Describe("Helm", func() { Eventually(func() error { depl = &appsv1.Deployment{} return workloadClient.Get(context.TODO(), - types.NamespacedName{Namespace: "wildfly", Name: "wildfly"}, depl) + types.NamespacedName{Namespace: wildflyName, Name: wildflyName}, depl) }, timeout, pollingInterval).Should(BeNil()) Byf("Verifying ClusterSummary %s status is set to Deployed for Helm feature", clusterSummary.Name) verifyFeatureStatusIsProvisioned(kindWorkloadCluster.GetNamespace(), clusterSummary.Name, libsveltosv1beta1.FeatureHelm) charts := []configv1beta1.Chart{ - {ReleaseName: "kyverno-latest", ChartVersion: "3.7.1", Namespace: "kyverno"}, - {ReleaseName: "wildfly", ChartVersion: "2.4.0", Namespace: "wildfly"}, + {ReleaseName: kyvernoLatestRelease, ChartVersion: "3.7.1", Namespace: kyvernoNamespace}, + {ReleaseName: wildflyName, ChartVersion: wildflyVersion, Namespace: wildflyName}, } verifyClusterConfiguration(configv1beta1.ClusterProfileKind, clusterProfile.Name, @@ -164,21 +164,21 @@ var _ = Describe("Helm", func() { Expect(k8sClient.Get(context.TODO(), types.NamespacedName{Name: clusterProfile.Name}, currentClusterProfile)).To(Succeed()) currentClusterProfile.Spec.HelmCharts = []configv1beta1.HelmChart{ { - RepositoryURL: "https://kyverno.github.io/kyverno/", - RepositoryName: "kyverno", - ChartName: "kyverno/kyverno", - ChartVersion: "v3.7.0", - ReleaseName: "kyverno-latest", - ReleaseNamespace: "kyverno", + RepositoryURL: kyvernoRepoURL, + RepositoryName: kyvernoNamespace, + ChartName: kyvernoChartName, + ChartVersion: kyvernoVersion370, + ReleaseName: kyvernoLatestRelease, + ReleaseNamespace: kyvernoNamespace, HelmChartAction: configv1beta1.HelmChartActionInstall, }, { - RepositoryURL: "https://docs.wildfly.org/wildfly-charts/", - RepositoryName: "wildfly", - ChartName: "wildfly/wildfly", - ChartVersion: "2.4.0", - ReleaseName: "wildfly", - ReleaseNamespace: "wildfly", + RepositoryURL: wildflyRepoURL, + RepositoryName: wildflyName, + ChartName: wildflyChartName, + ChartVersion: wildflyVersion, + ReleaseName: wildflyName, + ReleaseNamespace: wildflyName, HelmChartAction: configv1beta1.HelmChartActionInstall, }, } @@ -189,8 +189,8 @@ var _ = Describe("Helm", func() { currentClusterProfile.Spec.Patches = []libsveltosv1beta1.Patch{ { Target: &libsveltosv1beta1.PatchSelector{ - Kind: "Deployment", - Name: ".*", + Kind: kindDeployment, + Name: matchAllPattern, }, Patch: fmt.Sprintf(`- op: add path: /metadata/labels/%s @@ -208,22 +208,22 @@ var _ = Describe("Helm", func() { Eventually(func() error { depl = &appsv1.Deployment{} return workloadClient.Get(context.TODO(), - types.NamespacedName{Namespace: "kyverno", Name: "kyverno-admission-controller"}, depl) + types.NamespacedName{Namespace: kyvernoNamespace, Name: admissionControllerDeplName}, depl) }, timeout, pollingInterval).Should(BeNil()) Byf("Verifying wildfly deployment is still in the workload cluster") Eventually(func() error { depl = &appsv1.Deployment{} return workloadClient.Get(context.TODO(), - types.NamespacedName{Namespace: "wildfly", Name: "wildfly"}, depl) + types.NamespacedName{Namespace: wildflyName, Name: wildflyName}, depl) }, timeout, pollingInterval).Should(BeNil()) Byf("Verifying ClusterSummary %s status is set to Deployed for Helm feature", clusterSummary.Name) verifyFeatureStatusIsProvisioned(kindWorkloadCluster.GetNamespace(), clusterSummary.Name, libsveltosv1beta1.FeatureHelm) charts = []configv1beta1.Chart{ - {ReleaseName: "kyverno-latest", ChartVersion: "3.7.0", Namespace: "kyverno"}, - {ReleaseName: "wildfly", ChartVersion: "2.4.0", Namespace: "wildfly"}, + {ReleaseName: kyvernoLatestRelease, ChartVersion: kyvernoVersion370S, Namespace: kyvernoNamespace}, + {ReleaseName: wildflyName, ChartVersion: wildflyVersion, Namespace: wildflyName}, } verifyClusterConfiguration(configv1beta1.ClusterProfileKind, clusterProfile.Name, @@ -232,7 +232,7 @@ var _ = Describe("Helm", func() { Byf("Verifying kyverno deployment has proper labels/annotations") Expect(workloadClient.Get(context.TODO(), - types.NamespacedName{Namespace: "kyverno", Name: "kyverno-admission-controller"}, depl)) + types.NamespacedName{Namespace: kyvernoNamespace, Name: admissionControllerDeplName}, depl)) content, err = runtime.DefaultUnstructuredConverter.ToUnstructured(depl) Expect(err).To(BeNil()) u.SetUnstructuredContent(content) @@ -245,12 +245,12 @@ var _ = Describe("Helm", func() { Expect(k8sClient.Get(context.TODO(), types.NamespacedName{Name: clusterProfile.Name}, currentClusterProfile)).To(Succeed()) currentClusterProfile.Spec.HelmCharts = []configv1beta1.HelmChart{ { - RepositoryURL: "https://kyverno.github.io/kyverno/", - RepositoryName: "kyverno", - ChartName: "kyverno/kyverno", - ChartVersion: "v3.7.0", - ReleaseName: "kyverno-latest", - ReleaseNamespace: "kyverno", + RepositoryURL: kyvernoRepoURL, + RepositoryName: kyvernoNamespace, + ChartName: kyvernoChartName, + ChartVersion: kyvernoVersion370, + ReleaseName: kyvernoLatestRelease, + ReleaseNamespace: kyvernoNamespace, HelmChartAction: configv1beta1.HelmChartActionInstall, }, } @@ -264,19 +264,19 @@ var _ = Describe("Helm", func() { Eventually(func() error { depl := &appsv1.Deployment{} return workloadClient.Get(context.TODO(), - types.NamespacedName{Namespace: "kyverno", Name: "kyverno-admission-controller"}, depl) + types.NamespacedName{Namespace: kyvernoNamespace, Name: admissionControllerDeplName}, depl) }, timeout, pollingInterval).Should(BeNil()) Byf("Verifying wildfly deployment is removed from workload cluster") Eventually(func() bool { depl := &appsv1.Deployment{} err = workloadClient.Get(context.TODO(), - types.NamespacedName{Namespace: "wildfly", Name: "wildfly"}, depl) + types.NamespacedName{Namespace: wildflyName, Name: wildflyName}, depl) return apierrors.IsNotFound(err) }, timeout, pollingInterval).Should(BeTrue()) charts = []configv1beta1.Chart{ - {ReleaseName: "kyverno-latest", ChartVersion: "3.7.0", Namespace: "kyverno"}, + {ReleaseName: kyvernoLatestRelease, ChartVersion: kyvernoVersion370S, Namespace: kyvernoNamespace}, } verifyClusterConfiguration(configv1beta1.ClusterProfileKind, clusterProfile.Name, @@ -292,7 +292,7 @@ var _ = Describe("Helm", func() { Eventually(func() bool { depl := &appsv1.Deployment{} err = workloadClient.Get(context.TODO(), - types.NamespacedName{Namespace: "kyverno", Name: "kyverno-latest"}, depl) + types.NamespacedName{Namespace: kyvernoNamespace, Name: kyvernoLatestRelease}, depl) return apierrors.IsNotFound(err) }, timeout, pollingInterval).Should(BeTrue()) }) diff --git a/test/fv/helm_with_corev1list_test.go b/test/fv/helm_with_corev1list_test.go index b8afdeb1..32b5376a 100644 --- a/test/fv/helm_with_corev1list_test.go +++ b/test/fv/helm_with_corev1list_test.go @@ -80,12 +80,12 @@ var _ = Describe("Feature", func() { Byf("Create ClusterProfile %s to deploy kube-prometheus-stack helm chart", clusterProfile.Name) clusterProfile.Spec.HelmCharts = []configv1beta1.HelmChart{ { - RepositoryURL: "https://prometheus-community.github.io/helm-charts", - RepositoryName: "prometheus-community", + RepositoryURL: prometheusCommunityURL, + RepositoryName: prometheusCommunityName, ChartName: "prometheus-community/kube-prometheus-stack", - ChartVersion: "75.9.0", - ReleaseName: "kube-prometheus-stack", - ReleaseNamespace: "kube-prometheus-stack", + ChartVersion: kubePrometheusVersion, + ReleaseName: deplNamespace, + ReleaseNamespace: deplNamespace, HelmChartAction: configv1beta1.HelmChartActionInstall, Values: values, }, @@ -102,7 +102,7 @@ var _ = Describe("Feature", func() { verifyFeatureStatusIsProvisioned(kindWorkloadCluster.GetNamespace(), clusterSummary.Name, libsveltosv1beta1.FeatureHelm) charts := []configv1beta1.Chart{ - {ReleaseName: "kube-prometheus-stack", ChartVersion: "75.9.0", Namespace: "kube-prometheus-stack"}, + {ReleaseName: deplNamespace, ChartVersion: kubePrometheusVersion, Namespace: deplNamespace}, } verifyClusterConfiguration(configv1beta1.ClusterProfileKind, clusterProfile.Name, diff --git a/test/fv/kustomize_test.go b/test/fv/kustomize_test.go index 236eed53..f12005b0 100644 --- a/test/fv/kustomize_test.go +++ b/test/fv/kustomize_test.go @@ -48,7 +48,7 @@ var _ = Describe("Kustomize with GitRepository", func() { It("Deploy Kustomize resources with Flux", Serial, Label("FV", "PULLMODE", "EXTENDED"), func() { Byf("Create a ClusterProfile matching mgmt Cluster") - gitRepositoryNamespace := "flux2" + gitRepositoryNamespace := flux2Name mgmtClusterProfile := &configv1beta1.ClusterProfile{ ObjectMeta: metav1.ObjectMeta{ Name: namePrefix + randomString(), @@ -89,10 +89,10 @@ installCRDs: true` currentClusterProfile.Spec.HelmCharts = []configv1beta1.HelmChart{ { RepositoryURL: "https://fluxcd-community.github.io/helm-charts", - RepositoryName: "flux2", + RepositoryName: flux2Name, ChartName: "flux2/flux2", ChartVersion: "2.18.2", - ReleaseName: "flux2", + ReleaseName: flux2Name, ReleaseNamespace: gitRepositoryNamespace, HelmChartAction: configv1beta1.HelmChartActionInstall, Values: fluxValues, @@ -120,7 +120,7 @@ installCRDs: true` Eventually(func() bool { deployment := &appsv1.Deployment{} err := k8sClient.Get(context.TODO(), - types.NamespacedName{Namespace: sveltosNamespace, Name: "addon-controller"}, + types.NamespacedName{Namespace: sveltosNamespace, Name: addonDeplName}, deployment) return err == nil && deployment.Status.AvailableReplicas == 1 }, timeout, pollingInterval).Should(BeTrue()) @@ -129,7 +129,7 @@ installCRDs: true` Eventually(func() bool { deployment := &appsv1.Deployment{} err := k8sClient.Get(context.TODO(), - types.NamespacedName{Namespace: "projectsveltos", Name: "addon-controller-shard1"}, + types.NamespacedName{Namespace: sveltosNamespace, Name: "addon-controller-shard1"}, deployment) if err != nil { return apierrors.IsNotFound(err) @@ -244,7 +244,7 @@ installCRDs: true` Eventually(func() bool { currentService := &corev1.Service{} err = workloadClient.Get(context.TODO(), - types.NamespacedName{Namespace: targetNamespace, Name: "the-service"}, currentService) + types.NamespacedName{Namespace: targetNamespace, Name: kustomizeServiceName}, currentService) return err == nil }, timeout, pollingInterval).Should(BeTrue()) @@ -260,7 +260,7 @@ installCRDs: true` Eventually(func() bool { currentConfigMap := &corev1.ConfigMap{} err = workloadClient.Get(context.TODO(), - types.NamespacedName{Namespace: targetNamespace, Name: "the-map"}, currentConfigMap) + types.NamespacedName{Namespace: targetNamespace, Name: kustomizeMapName}, currentConfigMap) return err == nil }, timeout, pollingInterval).Should(BeTrue()) @@ -269,20 +269,20 @@ installCRDs: true` currentConfigMap := &corev1.ConfigMap{} Expect(workloadClient.Get(context.TODO(), - types.NamespacedName{Namespace: targetNamespace, Name: "the-map"}, currentConfigMap)).To(Succeed()) + types.NamespacedName{Namespace: targetNamespace, Name: kustomizeMapName}, currentConfigMap)).To(Succeed()) currentService := &corev1.Service{} Expect(workloadClient.Get(context.TODO(), - types.NamespacedName{Namespace: targetNamespace, Name: "the-service"}, currentService)).To(Succeed()) + types.NamespacedName{Namespace: targetNamespace, Name: kustomizeServiceName}, currentService)).To(Succeed()) currentDeployment := &appsv1.Deployment{} Expect(workloadClient.Get(context.TODO(), types.NamespacedName{Namespace: targetNamespace, Name: deploymentName}, currentDeployment)).To(Succeed()) policies := []policy{ - {kind: "Service", name: currentService.Name, namespace: targetNamespace, group: ""}, - {kind: "ConfigMap", name: currentConfigMap.Name, namespace: targetNamespace, group: ""}, - {kind: "Deployment", name: currentDeployment.Name, namespace: targetNamespace, group: "apps"}, + {kind: kindService, name: currentService.Name, namespace: targetNamespace, group: ""}, + {kind: kindConfigMap, name: currentConfigMap.Name, namespace: targetNamespace, group: ""}, + {kind: kindDeployment, name: currentDeployment.Name, namespace: targetNamespace, group: appsGroupName}, } verifyClusterConfiguration(configv1beta1.ClusterProfileKind, managedClusterProfile.Name, clusterSummary.Spec.ClusterNamespace, clusterSummary.Spec.ClusterName, libsveltosv1beta1.FeatureKustomize, @@ -316,7 +316,7 @@ installCRDs: true` Eventually(func() bool { currentService := &corev1.Service{} err = workloadClient.Get(context.TODO(), - types.NamespacedName{Namespace: targetNamespace, Name: "the-service"}, currentService) + types.NamespacedName{Namespace: targetNamespace, Name: kustomizeServiceName}, currentService) return err != nil && apierrors.IsNotFound(err) }, timeout, pollingInterval).Should(BeTrue()) @@ -334,7 +334,7 @@ installCRDs: true` Eventually(func() bool { currentConfigMap := &corev1.ConfigMap{} err = workloadClient.Get(context.TODO(), - types.NamespacedName{Namespace: targetNamespace, Name: "the-map"}, currentConfigMap) + types.NamespacedName{Namespace: targetNamespace, Name: kustomizeMapName}, currentConfigMap) return err != nil && apierrors.IsNotFound(err) }, timeout, pollingInterval).Should(BeTrue()) diff --git a/test/fv/kustomize_with_configmap_test.go b/test/fv/kustomize_with_configmap_test.go index 3c6ca377..6198728c 100644 --- a/test/fv/kustomize_with_configmap_test.go +++ b/test/fv/kustomize_with_configmap_test.go @@ -74,7 +74,7 @@ var _ = Describe("Kustomize with ConfigMap", func() { labelsConfigMap := createConfigMapWithPolicy(configMapNamespace, randomString(), fmt.Sprintf(labelsValues, clusterKey)) labelsConfigMap.Annotations = map[string]string{ - libsveltosv1beta1.PolicyTemplateAnnotation: "ok", + libsveltosv1beta1.PolicyTemplateAnnotation: annotationOkValue, } Expect(k8sClient.Create(context.TODO(), labelsConfigMap)).To(Succeed()) @@ -132,7 +132,7 @@ var _ = Describe("Kustomize with ConfigMap", func() { Eventually(func() bool { currentService := &corev1.Service{} err = workloadClient.Get(context.TODO(), - types.NamespacedName{Namespace: targetNamespace, Name: "production-the-service"}, currentService) + types.NamespacedName{Namespace: targetNamespace, Name: kustomizeProdServiceName}, currentService) return err == nil }, timeout, pollingInterval).Should(BeTrue()) @@ -140,7 +140,7 @@ var _ = Describe("Kustomize with ConfigMap", func() { Eventually(func() bool { currentDeployment := &appsv1.Deployment{} err = workloadClient.Get(context.TODO(), - types.NamespacedName{Namespace: targetNamespace, Name: "production-the-deployment"}, currentDeployment) + types.NamespacedName{Namespace: targetNamespace, Name: kustomizeProdDeployName}, currentDeployment) return err == nil }, timeout, pollingInterval).Should(BeTrue()) @@ -148,7 +148,7 @@ var _ = Describe("Kustomize with ConfigMap", func() { Eventually(func() bool { currentConfigMap := &corev1.ConfigMap{} err = workloadClient.Get(context.TODO(), - types.NamespacedName{Namespace: targetNamespace, Name: "production-the-map"}, currentConfigMap) + types.NamespacedName{Namespace: targetNamespace, Name: kustomizeProdMapName}, currentConfigMap) return err == nil }, timeout, pollingInterval).Should(BeTrue()) @@ -157,20 +157,20 @@ var _ = Describe("Kustomize with ConfigMap", func() { currentConfigMap := &corev1.ConfigMap{} Expect(workloadClient.Get(context.TODO(), - types.NamespacedName{Namespace: targetNamespace, Name: "production-the-map"}, currentConfigMap)).To(Succeed()) + types.NamespacedName{Namespace: targetNamespace, Name: kustomizeProdMapName}, currentConfigMap)).To(Succeed()) currentService := &corev1.Service{} Expect(workloadClient.Get(context.TODO(), - types.NamespacedName{Namespace: targetNamespace, Name: "production-the-service"}, currentService)).To(Succeed()) + types.NamespacedName{Namespace: targetNamespace, Name: kustomizeProdServiceName}, currentService)).To(Succeed()) currentDeployment := &appsv1.Deployment{} Expect(workloadClient.Get(context.TODO(), - types.NamespacedName{Namespace: targetNamespace, Name: "production-the-deployment"}, currentDeployment)).To(Succeed()) + types.NamespacedName{Namespace: targetNamespace, Name: kustomizeProdDeployName}, currentDeployment)).To(Succeed()) policies := []policy{ - {kind: "Service", name: currentService.Name, namespace: targetNamespace, group: ""}, - {kind: "ConfigMap", name: currentConfigMap.Name, namespace: targetNamespace, group: ""}, - {kind: "Deployment", name: currentDeployment.Name, namespace: targetNamespace, group: "apps"}, + {kind: kindService, name: currentService.Name, namespace: targetNamespace, group: ""}, + {kind: kindConfigMap, name: currentConfigMap.Name, namespace: targetNamespace, group: ""}, + {kind: kindDeployment, name: currentDeployment.Name, namespace: targetNamespace, group: appsGroupName}, } verifyClusterConfiguration(configv1beta1.ClusterProfileKind, clusterProfile.Name, clusterSummary.Spec.ClusterNamespace, clusterSummary.Spec.ClusterName, libsveltosv1beta1.FeatureKustomize, @@ -189,7 +189,7 @@ var _ = Describe("Kustomize with ConfigMap", func() { Eventually(func() bool { currentService := &corev1.Service{} err = workloadClient.Get(context.TODO(), - types.NamespacedName{Namespace: targetNamespace, Name: "production-the-service"}, currentService) + types.NamespacedName{Namespace: targetNamespace, Name: kustomizeProdServiceName}, currentService) return err != nil && apierrors.IsNotFound(err) }, timeout, pollingInterval).Should(BeTrue()) @@ -198,7 +198,7 @@ var _ = Describe("Kustomize with ConfigMap", func() { Eventually(func() bool { currentDeployment := &appsv1.Deployment{} err = workloadClient.Get(context.TODO(), - types.NamespacedName{Namespace: targetNamespace, Name: "production-the-deployment"}, currentDeployment) + types.NamespacedName{Namespace: targetNamespace, Name: kustomizeProdDeployName}, currentDeployment) return err != nil && apierrors.IsNotFound(err) }, timeout, pollingInterval).Should(BeTrue()) @@ -207,7 +207,7 @@ var _ = Describe("Kustomize with ConfigMap", func() { Eventually(func() bool { currentConfigMap := &corev1.ConfigMap{} err = workloadClient.Get(context.TODO(), - types.NamespacedName{Namespace: targetNamespace, Name: "production-the-map"}, currentConfigMap) + types.NamespacedName{Namespace: targetNamespace, Name: kustomizeProdMapName}, currentConfigMap) return err != nil && apierrors.IsNotFound(err) }, timeout, pollingInterval).Should(BeTrue()) diff --git a/test/fv/kyaml_test.go b/test/fv/kyaml_test.go index f38b0974..4fd13b22 100644 --- a/test/fv/kyaml_test.go +++ b/test/fv/kyaml_test.go @@ -36,7 +36,7 @@ import ( const ( serviceKYAML = `{ apiVersion: "v1", - kind: "Service", + kind: Service, metadata: { name: "%s", namespace: "%s", @@ -139,7 +139,7 @@ var _ = Describe("Deploy Kyaml resources", func() { verifyFeatureStatusIsProvisioned(kindWorkloadCluster.GetNamespace(), clusterSummary.Name, libsveltosv1beta1.FeatureResources) policies := []policy{ - {kind: "Service", name: name, namespace: namespace, group: ""}, + {kind: kindService, name: name, namespace: namespace, group: ""}, } verifyClusterConfiguration(configv1beta1.ClusterProfileKind, clusterProfile.Name, clusterSummary.Spec.ClusterNamespace, clusterSummary.Spec.ClusterName, libsveltosv1beta1.FeatureResources, diff --git a/test/fv/leave_helm_charts_test.go b/test/fv/leave_helm_charts_test.go index dd4a516f..39eaa101 100644 --- a/test/fv/leave_helm_charts_test.go +++ b/test/fv/leave_helm_charts_test.go @@ -71,7 +71,7 @@ var _ = Describe("Helm", func() { RepositoryURL: "https://operator.min.io", RepositoryName: "minio-operator", ChartName: "minio-operator/operator", - ChartVersion: "7.1.1", + ChartVersion: leaveHelmVersion, ReleaseName: minioReleaseName, ReleaseNamespace: minioNamespace, HelmChartAction: configv1beta1.HelmChartActionInstall, @@ -104,7 +104,7 @@ var _ = Describe("Helm", func() { verifyFeatureStatusIsProvisioned(kindWorkloadCluster.GetNamespace(), clusterSummary.Name, libsveltosv1beta1.FeatureHelm) charts := []configv1beta1.Chart{ - {ReleaseName: minioReleaseName, ChartVersion: "7.1.1", Namespace: minioNamespace}, + {ReleaseName: minioReleaseName, ChartVersion: leaveHelmVersion, Namespace: minioNamespace}, } verifyClusterConfiguration(configv1beta1.ClusterProfileKind, clusterProfile.Name, diff --git a/test/fv/leave_policies_test.go b/test/fv/leave_policies_test.go index 2c89ecf7..8f5280f6 100644 --- a/test/fv/leave_policies_test.go +++ b/test/fv/leave_policies_test.go @@ -138,7 +138,7 @@ var _ = Describe("LeavePolicies", func() { verifyFeatureStatusIsProvisioned(kindWorkloadCluster.GetNamespace(), clusterSummary.Name, libsveltosv1beta1.FeatureResources) policies := []policy{ - {kind: "Deployment", name: deploymentName, namespace: deploymentNamespace, group: "apps"}, + {kind: kindDeployment, name: deploymentName, namespace: deploymentNamespace, group: appsGroupName}, } verifyClusterConfiguration(configv1beta1.ClusterProfileKind, clusterProfile.Name, clusterSummary.Spec.ClusterNamespace, clusterSummary.Spec.ClusterName, libsveltosv1beta1.FeatureResources, diff --git a/test/fv/lua_instantiation_test.go b/test/fv/lua_instantiation_test.go index c6a3d9c9..5ab05881 100644 --- a/test/fv/lua_instantiation_test.go +++ b/test/fv/lua_instantiation_test.go @@ -61,7 +61,7 @@ var _ = Describe("ConfigMap with Lua", func() { ObjectMeta: metav1.ObjectMeta{ Name: namePrefix + randomString(), Labels: map[string]string{ - "env": envKey, + key: envKey, }, }, } @@ -84,7 +84,7 @@ var _ = Describe("ConfigMap with Lua", func() { Byf("Create a configMap with a Lua code (with annotation projectsveltos.io/lua)") configMap := createConfigMapWithPolicy(ns.Name, namePrefix+randomString(), luaCode) configMap.Annotations = map[string]string{ - libsveltosv1beta1.PolicyLuaAnnotation: "ok", + libsveltosv1beta1.PolicyLuaAnnotation: annotationOkValue, } Expect(k8sClient.Create(context.TODO(), configMap)).To(Succeed()) currentConfigMap := &corev1.ConfigMap{} @@ -100,11 +100,11 @@ var _ = Describe("ConfigMap with Lua", func() { types.NamespacedName{Name: clusterProfile.Name}, currentClusterProfile)).To(Succeed()) currentClusterProfile.Spec.TemplateResourceRefs = []configv1beta1.TemplateResourceRef{ { - Identifier: "Namespace", // this is used in luaCode. Must match + Identifier: kindNamespace, // this is used in luaCode. Must match Resource: corev1.ObjectReference{ Kind: ns.Kind, Name: ns.Name, - APIVersion: "v1", + APIVersion: apiVersionV1, }, }, } diff --git a/test/fv/missing_reference_test.go b/test/fv/missing_reference_test.go index 8bf94f0b..7dc5c218 100644 --- a/test/fv/missing_reference_test.go +++ b/test/fv/missing_reference_test.go @@ -135,7 +135,7 @@ var _ = Describe("Missing Reference", func() { verifyFeatureStatusIsProvisioned(kindWorkloadCluster.GetNamespace(), clusterSummary.Name, libsveltosv1beta1.FeatureResources) policies := []policy{ - {kind: "Namespace", name: namespaceName, namespace: "", group: ""}, + {kind: kindNamespace, name: namespaceName, namespace: "", group: ""}, } verifyClusterConfiguration(configv1beta1.ClusterProfileKind, clusterProfile.Name, clusterSummary.Spec.ClusterNamespace, clusterSummary.Spec.ClusterName, libsveltosv1beta1.FeatureResources, diff --git a/test/fv/missing_template_resource_ref_test.go b/test/fv/missing_template_resource_ref_test.go index 983458fe..b7f279e8 100644 --- a/test/fv/missing_template_resource_ref_test.go +++ b/test/fv/missing_template_resource_ref_test.go @@ -81,8 +81,8 @@ var _ = Describe("Missing TemplateResourceRef", func() { currentClusterProfile.Spec.TemplateResourceRefs = []configv1beta1.TemplateResourceRef{ { Resource: corev1.ObjectReference{ - Kind: "Secret", - APIVersion: "v1", + Kind: kindSecret, + APIVersion: apiVersionV1, Namespace: secretNsName, Name: secretName, }, diff --git a/test/fv/oci_test.go b/test/fv/oci_test.go index 6f4d4d7b..24285392 100644 --- a/test/fv/oci_test.go +++ b/test/fv/oci_test.go @@ -56,12 +56,12 @@ var _ = Describe("Helm", func() { types.NamespacedName{Name: clusterProfile.Name}, currentClusterProfile)).To(Succeed()) currentClusterProfile.Spec.HelmCharts = []configv1beta1.HelmChart{ { - RepositoryURL: "oci://registry-1.docker.io/bitnamicharts", - RepositoryName: "oci-vault", - ChartName: "vault", - ChartVersion: "1.6.0", - ReleaseName: "vault", - ReleaseNamespace: "vault", + RepositoryURL: ociVaultURL, + RepositoryName: ociVaultRepoName, + ChartName: vaultChartName, + ChartVersion: vaultVersion160, + ReleaseName: vaultChartName, + ReleaseNamespace: vaultChartName, HelmChartAction: configv1beta1.HelmChartActionInstall, }, } @@ -86,14 +86,14 @@ var _ = Describe("Helm", func() { Eventually(func() error { depl := &appsv1.Deployment{} return workloadClient.Get(context.TODO(), - types.NamespacedName{Namespace: "vault", Name: "vault-injector"}, depl) + types.NamespacedName{Namespace: vaultChartName, Name: vaultInjectorName}, depl) }, timeout, pollingInterval).Should(BeNil()) Byf("Verifying ClusterSummary %s status is set to Deployed for Helm feature", clusterSummary.Name) verifyFeatureStatusIsProvisioned(kindWorkloadCluster.GetNamespace(), clusterSummary.Name, libsveltosv1beta1.FeatureHelm) charts := []configv1beta1.Chart{ - {ReleaseName: "vault", ChartVersion: "1.6.0", Namespace: "vault"}, + {ReleaseName: vaultChartName, ChartVersion: vaultVersion160, Namespace: vaultChartName}, } verifyClusterConfiguration(configv1beta1.ClusterProfileKind, clusterProfile.Name, @@ -104,12 +104,12 @@ var _ = Describe("Helm", func() { Expect(k8sClient.Get(context.TODO(), types.NamespacedName{Name: clusterProfile.Name}, currentClusterProfile)).To(Succeed()) currentClusterProfile.Spec.HelmCharts = []configv1beta1.HelmChart{ { - RepositoryURL: "oci://registry-1.docker.io/bitnamicharts", - RepositoryName: "oci-vault", - ChartName: "vault", - ChartVersion: "1.5.0", - ReleaseName: "vault", - ReleaseNamespace: "vault", + RepositoryURL: ociVaultURL, + RepositoryName: ociVaultRepoName, + ChartName: vaultChartName, + ChartVersion: vaultVersion150, + ReleaseName: vaultChartName, + ReleaseNamespace: vaultChartName, HelmChartAction: configv1beta1.HelmChartActionInstall, }, } @@ -123,14 +123,14 @@ var _ = Describe("Helm", func() { Eventually(func() error { depl := &appsv1.Deployment{} return workloadClient.Get(context.TODO(), - types.NamespacedName{Namespace: "vault", Name: "vault-injector"}, depl) + types.NamespacedName{Namespace: vaultChartName, Name: vaultInjectorName}, depl) }, timeout, pollingInterval).Should(BeNil()) Byf("Verifying ClusterSummary %s status is set to Deployed for Helm feature", clusterSummary.Name) verifyFeatureStatusIsProvisioned(kindWorkloadCluster.GetNamespace(), clusterSummary.Name, libsveltosv1beta1.FeatureHelm) charts = []configv1beta1.Chart{ - {ReleaseName: "vault", ChartVersion: "1.5.0", Namespace: "vault"}, + {ReleaseName: vaultChartName, ChartVersion: vaultVersion150, Namespace: vaultChartName}, } verifyClusterConfiguration(configv1beta1.ClusterProfileKind, clusterProfile.Name, @@ -143,7 +143,7 @@ var _ = Describe("Helm", func() { Eventually(func() bool { depl := &appsv1.Deployment{} err = workloadClient.Get(context.TODO(), - types.NamespacedName{Namespace: "vault", Name: "vault-injector"}, depl) + types.NamespacedName{Namespace: vaultChartName, Name: vaultInjectorName}, depl) return apierrors.IsNotFound(err) }, timeout, pollingInterval).Should(BeTrue()) }) diff --git a/test/fv/onetime_test.go b/test/fv/onetime_test.go index 3138243c..fc3c798a 100644 --- a/test/fv/onetime_test.go +++ b/test/fv/onetime_test.go @@ -108,7 +108,7 @@ var _ = Describe("SyncMode one time", func() { verifyFeatureStatusIsProvisioned(kindWorkloadCluster.GetNamespace(), clusterSummary.Name, libsveltosv1beta1.FeatureResources) policies := []policy{ - {kind: "Namespace", name: oneTimeNamespaceName, namespace: "", group: ""}, + {kind: kindNamespace, name: oneTimeNamespaceName, namespace: "", group: ""}, } verifyClusterConfiguration(configv1beta1.ClusterProfileKind, clusterProfile.Name, clusterSummary.Spec.ClusterNamespace, clusterSummary.Spec.ClusterName, libsveltosv1beta1.FeatureResources, diff --git a/test/fv/optional_referenced_resource_test.go b/test/fv/optional_referenced_resource_test.go index 79b0d515..b7147594 100644 --- a/test/fv/optional_referenced_resource_test.go +++ b/test/fv/optional_referenced_resource_test.go @@ -86,12 +86,12 @@ metadata: currentClusterProfile.Spec.HelmCharts = []configv1beta1.HelmChart{ { - RepositoryURL: "https://prometheus-community.github.io/helm-charts", - RepositoryName: "prometheus-community", - ChartName: "prometheus-community/prometheus", - ChartVersion: "25.24.0", - ReleaseName: "prometheus", - ReleaseNamespace: "prometheus", + RepositoryURL: prometheusCommunityURL, + RepositoryName: prometheusCommunityName, + ChartName: prometheusChartName, + ChartVersion: prometheusVersion2524, + ReleaseName: prometheusRelease, + ReleaseNamespace: prometheusRelease, HelmChartAction: configv1beta1.HelmChartActionInstall, ValuesFrom: []configv1beta1.ValueFrom{ { @@ -130,7 +130,7 @@ metadata: kindWorkloadCluster.GetNamespace(), kindWorkloadCluster.GetName(), getClusterType()) charts := []configv1beta1.Chart{ - {ReleaseName: "prometheus", ChartVersion: "25.24.0", Namespace: "prometheus"}, + {ReleaseName: prometheusRelease, ChartVersion: prometheusVersion2524, Namespace: prometheusRelease}, } verifyClusterConfiguration(configv1beta1.ClusterProfileKind, clusterProfile.Name, @@ -138,7 +138,7 @@ metadata: nil, charts) policies := []policy{ - {kind: "Namespace", name: resourceNamespace, namespace: "", group: ""}, + {kind: kindNamespace, name: resourceNamespace, namespace: "", group: ""}, } verifyClusterConfiguration(configv1beta1.ClusterProfileKind, clusterProfile.Name, diff --git a/test/fv/patch_multiple_resources_test.go b/test/fv/patch_multiple_resources_test.go index 34423ec1..778b2229 100644 --- a/test/fv/patch_multiple_resources_test.go +++ b/test/fv/patch_multiple_resources_test.go @@ -74,7 +74,7 @@ var _ = Describe("Patch with multiple resources in ConfigMap", func() { { Target: &libsveltosv1beta1.PatchSelector{ Kind: "Namespace", - Name: ".*", + Name: matchAllPattern, }, Patch: `- op: add path: /metadata/labels/type @@ -101,7 +101,7 @@ var _ = Describe("Patch with multiple resources in ConfigMap", func() { Byf("Verifying proper Namespace is created in the workload cluster") Eventually(func() bool { currentNamespace := &corev1.Namespace{} - err = workloadClient.Get(context.TODO(), types.NamespacedName{Name: "flux-system"}, currentNamespace) + err = workloadClient.Get(context.TODO(), types.NamespacedName{Name: fluxSystemName}, currentNamespace) if err != nil { return false } @@ -129,7 +129,7 @@ var _ = Describe("Patch with multiple resources in ConfigMap", func() { Byf("Verifying Namespace is removed in the workload cluster") Eventually(func() bool { currentNamespace := &corev1.Namespace{} - err = workloadClient.Get(context.TODO(), types.NamespacedName{Name: "flux-system"}, currentNamespace) + err = workloadClient.Get(context.TODO(), types.NamespacedName{Name: fluxSystemName}, currentNamespace) if err != nil { return err != nil && apierrors.IsNotFound(err) } diff --git a/test/fv/patchesfrom_test.go b/test/fv/patchesfrom_test.go index 560a8ba9..11450590 100644 --- a/test/fv/patchesfrom_test.go +++ b/test/fv/patchesfrom_test.go @@ -222,8 +222,8 @@ target: } currentClusterProfile.Spec.PatchesFrom = []configv1beta1.ValueFrom{ { - Namespace: "{{ .Cluster.metadata.namespace}}", - Name: "{{ .Cluster.metadata.name}}-patches", + Namespace: clusterNamespaceTrimTemplate, + Name: patchesCMNameTemplate, Kind: string(libsveltosv1beta1.ConfigMapReferencedResourceKind), }, } @@ -247,13 +247,13 @@ target: Eventually(func() error { currentDeployment := &appsv1.Deployment{} return workloadClient.Get(context.TODO(), - types.NamespacedName{Namespace: resourceNamespace, Name: "nginx-deployment"}, + types.NamespacedName{Namespace: resourceNamespace, Name: nginxDeploymentName}, currentDeployment) }, timeout, pollingInterval).Should(BeNil()) currentDeployment := &appsv1.Deployment{} Expect(workloadClient.Get(context.TODO(), - types.NamespacedName{Namespace: resourceNamespace, Name: "nginx-deployment"}, + types.NamespacedName{Namespace: resourceNamespace, Name: nginxDeploymentName}, currentDeployment)).To(Succeed()) Byf("Verifying Deployment %s/nginx-deployment has label %s:%s", resourceNamespace, key, value) @@ -270,7 +270,7 @@ target: currentService := &corev1.Service{} Expect(workloadClient.Get(context.TODO(), - types.NamespacedName{Namespace: resourceNamespace, Name: "nginx-service"}, + types.NamespacedName{Namespace: resourceNamespace, Name: nginxServiceName}, currentService)).To(Succeed()) Byf("Verifying Service %s/nginx-service has label %s:%s", resourceNamespace, key, value) @@ -298,7 +298,7 @@ target: Eventually(func() bool { currentDeployment := &appsv1.Deployment{} err = workloadClient.Get(context.TODO(), - types.NamespacedName{Namespace: resourceNamespace, Name: "nginx-deployment"}, + types.NamespacedName{Namespace: resourceNamespace, Name: nginxDeploymentName}, currentDeployment) if err != nil { return false @@ -311,7 +311,7 @@ target: }, timeout, pollingInterval).Should(BeTrue()) Expect(workloadClient.Get(context.TODO(), - types.NamespacedName{Namespace: resourceNamespace, Name: "nginx-deployment"}, + types.NamespacedName{Namespace: resourceNamespace, Name: nginxDeploymentName}, currentDeployment)).To(Succeed()) Byf("Verifying Deployment %s/nginx-deployment has label %s:%s", resourceNamespace, key, value) @@ -327,7 +327,7 @@ target: Expect(currentDeployment.Spec.Template.Spec.Tolerations[0].Key).To(Equal(tolerationKey)) Expect(workloadClient.Get(context.TODO(), - types.NamespacedName{Namespace: resourceNamespace, Name: "nginx-service"}, + types.NamespacedName{Namespace: resourceNamespace, Name: nginxServiceName}, currentService)).To(Succeed()) Byf("Verifying Service %s/nginx-service has label %s:%s", resourceNamespace, key, value) @@ -361,12 +361,12 @@ target: } currentClusterProfile.Spec.PatchesFrom = []configv1beta1.ValueFrom{ { - Namespace: "{{ .Cluster.metadata.namespace}}", - Name: "{{ .Cluster.metadata.name}}-patches", + Namespace: clusterNamespaceTrimTemplate, + Name: patchesCMNameTemplate, Kind: string(libsveltosv1beta1.ConfigMapReferencedResourceKind), }, { - Namespace: "{{ .Cluster.metadata.namespace}}", + Namespace: clusterNamespaceTrimTemplate, Name: "{{ .Cluster.metadata.name}}-jsonpatch", Kind: string(libsveltosv1beta1.ConfigMapReferencedResourceKind), }, @@ -379,7 +379,7 @@ target: Eventually(func() bool { currentDeployment := &appsv1.Deployment{} err = workloadClient.Get(context.TODO(), - types.NamespacedName{Namespace: resourceNamespace, Name: "nginx-deployment"}, + types.NamespacedName{Namespace: resourceNamespace, Name: nginxDeploymentName}, currentDeployment) if err != nil { return false @@ -392,7 +392,7 @@ target: }, timeout, pollingInterval).Should(BeTrue()) Expect(workloadClient.Get(context.TODO(), - types.NamespacedName{Namespace: resourceNamespace, Name: "nginx-deployment"}, + types.NamespacedName{Namespace: resourceNamespace, Name: nginxDeploymentName}, currentDeployment)).To(Succeed()) Byf("Verifying Deployment %s/nginx-deployment has label %s:%s", resourceNamespace, key, value) diff --git a/test/fv/paused_profile_test.go b/test/fv/paused_profile_test.go index d90fd487..3b555779 100644 --- a/test/fv/paused_profile_test.go +++ b/test/fv/paused_profile_test.go @@ -37,7 +37,7 @@ var _ = Describe("Paused Profile", func() { kindWorkloadCluster.GetNamespace(), kindWorkloadCluster.GetName()) clusterProfile := getClusterProfile(namePrefix, map[string]string{key: value}) clusterProfile.Annotations = map[string]string{ - configv1beta1.ProfilePausedAnnotation: "true", + configv1beta1.ProfilePausedAnnotation: annotationTrueValue, } Expect(k8sClient.Create(context.TODO(), clusterProfile)).To(Succeed()) diff --git a/test/fv/pre_deploy_checks_test.go b/test/fv/pre_deploy_checks_test.go index 1906d4d5..68b3f5d4 100644 --- a/test/fv/pre_deploy_checks_test.go +++ b/test/fv/pre_deploy_checks_test.go @@ -108,8 +108,8 @@ var _ = Describe("PreDeployChecks", func() { Name: "sa-exists", FeatureID: libsveltosv1beta1.FeatureResources, Group: "", - Version: "v1", - Kind: "ServiceAccount", + Version: apiVersionV1, + Kind: kindServiceAccount, Namespace: deployNs, LabelFilters: []libsveltosv1beta1.LabelFilter{ { diff --git a/test/fv/profile_local_test.go b/test/fv/profile_local_test.go index 280b35fd..1293750b 100644 --- a/test/fv/profile_local_test.go +++ b/test/fv/profile_local_test.go @@ -51,13 +51,13 @@ metadata: By("Grant addon-controller permission to create/delete ServiceAccount in the management cluster") err := retry.RetryOnConflict(retry.DefaultRetry, func() error { clusterRole := &rbacv1.ClusterRole{} - Expect(k8sClient.Get(context.TODO(), types.NamespacedName{Name: "addon-controller-role-extra"}, + Expect(k8sClient.Get(context.TODO(), types.NamespacedName{Name: addonControllerRoleExtra}, clusterRole)).To(Succeed()) clusterRole.Rules = append(clusterRole.Rules, rbacv1.PolicyRule{ Verbs: []string{"*"}, APIGroups: []string{""}, - Resources: []string{"serviceaccounts"}, + Resources: []string{serviceAccountsResource}, }) return k8sClient.Update(context.TODO(), clusterRole) }) diff --git a/test/fv/promotion_test.go b/test/fv/promotion_test.go index 9948a39d..1e1ad7c5 100644 --- a/test/fv/promotion_test.go +++ b/test/fv/promotion_test.go @@ -130,9 +130,9 @@ end` Name: "job-completion-check", FeatureID: libsveltosv1beta1.FeatureResources, Namespace: configMapNs, - Group: "batch", - Version: "v1", - Kind: "Job", + Group: batchGroupName, + Version: apiVersionV1, + Kind: kindJob, Script: luaEvaluateJobCompleted, }, }, @@ -141,10 +141,10 @@ end` } stage2 := configv1beta1.Stage{ - Name: "production", + Name: productionValue, ClusterSelector: libsveltosv1beta1.Selector{ LabelSelector: metav1.LabelSelector{ - MatchLabels: map[string]string{"env": "production"}, + MatchLabels: map[string]string{key: productionValue}, }, }, } @@ -159,12 +159,12 @@ end` Tier: 90, HelmCharts: []configv1beta1.HelmChart{ { - RepositoryURL: "https://charts.bitnami.com/bitnami", - RepositoryName: "bitnami", + RepositoryURL: bitnamiURL, + RepositoryName: bitnamiName, ChartName: "bitnami/contour", ChartVersion: "21.1.4", - ReleaseName: "contour", - ReleaseNamespace: "contour", + ReleaseName: contourRelease, + ReleaseNamespace: contourRelease, Values: contourValues, }, }, @@ -185,7 +185,7 @@ end` listOptions := []client.ListOption{ client.MatchingLabels{ - "config.projectsveltos.io/promotionname": clusterPromotion.Name, + promotionNameAnnotation: clusterPromotion.Name, }, } Byf("Verify ClusterProfile for stage %s is created", stage1.Name) @@ -234,8 +234,8 @@ end` Eventually(func() bool { listOptions := []client.ListOption{ client.MatchingLabels{ - "config.projectsveltos.io/promotionname": clusterPromotion.Name, - "config.projectsveltos.io/promotion-verification": "true", + promotionNameAnnotation: clusterPromotion.Name, + promotionVerifAnnotation: annotationTrueValue, }, } clusterProfileList := &configv1beta1.ClusterProfileList{} @@ -258,8 +258,8 @@ end` Eventually(func() bool { listOptions := []client.ListOption{ client.MatchingLabels{ - "config.projectsveltos.io/promotionname": clusterPromotion.Name, - "config.projectsveltos.io/promotion-verification": "true", + promotionNameAnnotation: clusterPromotion.Name, + promotionVerifAnnotation: annotationTrueValue, }, } clusterProfileList := &configv1beta1.ClusterProfileList{} @@ -301,8 +301,8 @@ end` Eventually(func() bool { listOptions := []client.ListOption{ client.MatchingLabels{ - "config.projectsveltos.io/promotionname": clusterPromotion.Name, - "config.projectsveltos.io/promotion-verification": "true", + promotionNameAnnotation: clusterPromotion.Name, + promotionVerifAnnotation: annotationTrueValue, }, } clusterProfileList := &configv1beta1.ClusterProfileList{} diff --git a/test/fv/reloader_test.go b/test/fv/reloader_test.go index 13f7afb8..768696eb 100644 --- a/test/fv/reloader_test.go +++ b/test/fv/reloader_test.go @@ -152,7 +152,7 @@ var _ = Describe("Reloader", func() { Expect(len(currentReloader.Spec.ReloaderInfo)).To(Equal(1)) Expect(currentReloader.Spec.ReloaderInfo).To(ContainElement( libsveltosv1beta1.ReloaderInfo{ - Kind: "Deployment", + Kind: kindDeployment, Namespace: ns, Name: deploymentName, }, @@ -167,7 +167,7 @@ var _ = Describe("Reloader", func() { Expect(len(currentReloader.Spec.ReloaderInfo)).To(Equal(1)) Expect(currentReloader.Spec.ReloaderInfo).To(ContainElement( libsveltosv1beta1.ReloaderInfo{ - Kind: "Deployment", + Kind: kindDeployment, Namespace: ns, Name: deploymentName, }, diff --git a/test/fv/remote_url_test.go b/test/fv/remote_url_test.go index 1649ba7b..0df65ce3 100644 --- a/test/fv/remote_url_test.go +++ b/test/fv/remote_url_test.go @@ -117,9 +117,9 @@ var _ = Describe("Remote URL", func() { verifyFeatureStatusIsProvisioned(kindWorkloadCluster.GetNamespace(), clusterSummary.Name, libsveltosv1beta1.FeatureResources) policies := []policy{ - {kind: "ClusterRole", name: clusterRoleName, namespace: "", group: "rbac.authorization.k8s.io"}, - {kind: "Deployment", name: deploymentName, namespace: deploymentNamespace, group: "apps"}, - {kind: "ServiceAccount", name: saName, namespace: saNamespace, group: ""}, + {kind: kindClusterRole, name: clusterRoleName, namespace: "", group: rbacAuthGroup}, + {kind: kindDeployment, name: deploymentName, namespace: deploymentNamespace, group: appsGroupName}, + {kind: kindServiceAccount, name: saName, namespace: saNamespace, group: ""}, } verifyClusterConfiguration(configv1beta1.ClusterProfileKind, clusterProfile.Name, clusterSummary.Spec.ClusterNamespace, clusterSummary.Spec.ClusterName, libsveltosv1beta1.FeatureResources, diff --git a/test/fv/resource_per_cluster_test.go b/test/fv/resource_per_cluster_test.go index bbfcbcd3..07ec7e03 100644 --- a/test/fv/resource_per_cluster_test.go +++ b/test/fv/resource_per_cluster_test.go @@ -122,8 +122,8 @@ var _ = Describe("Feature", func() { verifyFeatureStatusIsProvisioned(kindWorkloadCluster.GetNamespace(), clusterSummary.Name, libsveltosv1beta1.FeatureResources) policies := []policy{ - {kind: "ClusterRole", name: updateClusterRoleName, namespace: "", group: "rbac.authorization.k8s.io"}, - {kind: "Pod", name: podName, namespace: defaultNamespace, group: ""}, + {kind: kindClusterRole, name: updateClusterRoleName, namespace: "", group: rbacAuthGroup}, + {kind: kindPod, name: podName, namespace: defaultNamespace, group: ""}, } verifyClusterConfiguration(configv1beta1.ClusterProfileKind, clusterProfile.Name, clusterSummary.Spec.ClusterNamespace, clusterSummary.Spec.ClusterName, libsveltosv1beta1.FeatureResources, @@ -154,8 +154,8 @@ var _ = Describe("Feature", func() { }, timeout, pollingInterval).Should(BeTrue()) policies = []policy{ - {kind: "ClusterRole", name: allClusterRoleName, namespace: "", group: "rbac.authorization.k8s.io"}, - {kind: "Pod", name: podName, namespace: defaultNamespace, group: ""}, + {kind: kindClusterRole, name: allClusterRoleName, namespace: "", group: rbacAuthGroup}, + {kind: kindPod, name: podName, namespace: defaultNamespace, group: ""}, } verifyClusterConfiguration(configv1beta1.ClusterProfileKind, clusterProfile.Name, clusterSummary.Spec.ClusterNamespace, clusterSummary.Spec.ClusterName, libsveltosv1beta1.FeatureResources, @@ -187,8 +187,8 @@ var _ = Describe("Feature", func() { }, timeout, pollingInterval).Should(BeTrue()) policies = []policy{ - {kind: "ClusterRole", name: allClusterRoleName, namespace: "", group: "rbac.authorization.k8s.io"}, - {kind: "Pod", name: newPodName, namespace: defaultNamespace, group: ""}, + {kind: kindClusterRole, name: allClusterRoleName, namespace: "", group: rbacAuthGroup}, + {kind: kindPod, name: newPodName, namespace: defaultNamespace, group: ""}, } verifyClusterConfiguration(configv1beta1.ClusterProfileKind, clusterProfile.Name, clusterSummary.Spec.ClusterNamespace, clusterSummary.Spec.ClusterName, libsveltosv1beta1.FeatureResources, diff --git a/test/fv/resource_test.go b/test/fv/resource_test.go index 25330aae..ca0f011b 100644 --- a/test/fv/resource_test.go +++ b/test/fv/resource_test.go @@ -192,8 +192,8 @@ var _ = Describe("Feature", func() { verifyFeatureStatusIsProvisioned(kindWorkloadCluster.GetNamespace(), clusterSummary.Name, libsveltosv1beta1.FeatureResources) policies := []policy{ - {kind: "ClusterRole", name: updateClusterRoleName, namespace: "", group: "rbac.authorization.k8s.io"}, - {kind: "Pod", name: podName, namespace: defaultNamespace, group: ""}, + {kind: kindClusterRole, name: updateClusterRoleName, namespace: "", group: rbacAuthGroup}, + {kind: kindPod, name: podName, namespace: defaultNamespace, group: ""}, } verifyClusterConfiguration(configv1beta1.ClusterProfileKind, clusterProfile.Name, clusterSummary.Spec.ClusterNamespace, clusterSummary.Spec.ClusterName, libsveltosv1beta1.FeatureResources, @@ -221,8 +221,8 @@ var _ = Describe("Feature", func() { }, timeout, pollingInterval).Should(BeTrue()) policies = []policy{ - {kind: "ClusterRole", name: allClusterRoleName, namespace: "", group: "rbac.authorization.k8s.io"}, - {kind: "Pod", name: podName, namespace: defaultNamespace, group: ""}, + {kind: kindClusterRole, name: allClusterRoleName, namespace: "", group: rbacAuthGroup}, + {kind: kindPod, name: podName, namespace: defaultNamespace, group: ""}, } verifyClusterConfiguration(configv1beta1.ClusterProfileKind, clusterProfile.Name, clusterSummary.Spec.ClusterNamespace, clusterSummary.Spec.ClusterName, libsveltosv1beta1.FeatureResources, @@ -254,8 +254,8 @@ var _ = Describe("Feature", func() { }, timeout, pollingInterval).Should(BeTrue()) policies = []policy{ - {kind: "ClusterRole", name: allClusterRoleName, namespace: "", group: "rbac.authorization.k8s.io"}, - {kind: "Pod", name: newPodName, namespace: defaultNamespace, group: ""}, + {kind: kindClusterRole, name: allClusterRoleName, namespace: "", group: rbacAuthGroup}, + {kind: kindPod, name: newPodName, namespace: defaultNamespace, group: ""}, } verifyClusterConfiguration(configv1beta1.ClusterProfileKind, clusterProfile.Name, clusterSummary.Spec.ClusterNamespace, clusterSummary.Spec.ClusterName, libsveltosv1beta1.FeatureResources, diff --git a/test/fv/second_tier_test.go b/test/fv/second_tier_test.go index ecf356f1..4d4f30db 100644 --- a/test/fv/second_tier_test.go +++ b/test/fv/second_tier_test.go @@ -264,8 +264,8 @@ var _ = Describe("PolicyRef Tier", func() { verifyFeatureStatusIsProvisioned(clusterSummary.Namespace, clusterSummary.Name, libsveltosv1beta1.FeatureResources) policies := []policy{ - {kind: "ServiceAccount", name: saName, namespace: saNamespace, group: ""}, - {kind: "ServiceAccount", name: saName, namespace: newSaNamespace, group: ""}, + {kind: kindServiceAccount, name: saName, namespace: saNamespace, group: ""}, + {kind: kindServiceAccount, name: saName, namespace: newSaNamespace, group: ""}, } verifyClusterConfiguration(configv1beta1.ClusterProfileKind, clusterProfile.Name, clusterSummary.Spec.ClusterNamespace, clusterSummary.Spec.ClusterName, libsveltosv1beta1.FeatureResources, diff --git a/test/fv/template_clone_test.go b/test/fv/template_clone_test.go index b534d9a0..9a596123 100644 --- a/test/fv/template_clone_test.go +++ b/test/fv/template_clone_test.go @@ -65,7 +65,7 @@ var _ = Describe("Template with copy", func() { Byf("Add configMap containing a template policy with copy function.") configMap := createConfigMapWithPolicy(ns.Name, namePrefix+randomString(), `{{ (copy "ExternalSecret") }}`) configMap.Annotations = map[string]string{ - libsveltosv1beta1.PolicyTemplateAnnotation: "ok", + libsveltosv1beta1.PolicyTemplateAnnotation: annotationOkValue, } Expect(k8sClient.Create(context.TODO(), configMap)).To(Succeed()) @@ -75,8 +75,8 @@ var _ = Describe("Template with copy", func() { clusterProfile.Spec.TemplateResourceRefs = []configv1beta1.TemplateResourceRef{ { Resource: corev1.ObjectReference{ - Kind: "Secret", - APIVersion: "v1", + Kind: kindSecret, + APIVersion: apiVersionV1, Namespace: secret.Namespace, Name: secret.Name, }, diff --git a/test/fv/template_test.go b/test/fv/template_test.go index 03bfd369..5c063307 100644 --- a/test/fv/template_test.go +++ b/test/fv/template_test.go @@ -63,7 +63,7 @@ var _ = Describe("Template", func() { Byf("Add configMap containing a template policy. Policy has annotation to indicate it is a template") configMap := createConfigMapWithPolicy(configMapNs, namePrefix+randomString(), templatePolicy) configMap.Annotations = map[string]string{ - libsveltosv1beta1.PolicyTemplateAnnotation: "ok", + libsveltosv1beta1.PolicyTemplateAnnotation: annotationOkValue, } Expect(k8sClient.Create(context.TODO(), configMap)).To(Succeed()) @@ -101,7 +101,7 @@ var _ = Describe("Template", func() { Eventually(func() bool { cm := &corev1.ConfigMap{} err = workloadClient.Get(context.TODO(), - types.NamespacedName{Namespace: defaultNamespace, Name: "template"}, cm) + types.NamespacedName{Namespace: defaultNamespace, Name: templateCMName}, cm) return err == nil && strings.Contains(cm.Data["info"], currentCluster.Spec.ClusterNetwork.Pods.CIDRBlocks[0]) }, timeout, pollingInterval).Should(BeTrue()) @@ -123,7 +123,7 @@ var _ = Describe("Template", func() { Eventually(func() bool { cm := &corev1.ConfigMap{} err = workloadClient.Get(context.TODO(), - types.NamespacedName{Namespace: defaultNamespace, Name: "template"}, cm) + types.NamespacedName{Namespace: defaultNamespace, Name: templateCMName}, cm) return err != nil && apierrors.IsNotFound(err) }, timeout, pollingInterval).Should(BeTrue()) diff --git a/test/fv/templated_valuesfrom_test.go b/test/fv/templated_valuesfrom_test.go index 975b3bea..74105dae 100644 --- a/test/fv/templated_valuesfrom_test.go +++ b/test/fv/templated_valuesfrom_test.go @@ -77,7 +77,7 @@ var _ = Describe("Helm", func() { authMethodConfigMap := createConfigMapWithPolicy(namespace, fmt.Sprintf("%s-vso-ns-values", kindWorkloadCluster.GetName()), authMethod) authMethodConfigMap.Annotations = map[string]string{ - libsveltosv1beta1.PolicyTemplateAnnotation: "ok", + libsveltosv1beta1.PolicyTemplateAnnotation: annotationOkValue, } Expect(k8sClient.Create(context.TODO(), authMethodConfigMap)).To(Succeed()) @@ -91,8 +91,8 @@ var _ = Describe("Helm", func() { Resource: corev1.ObjectReference{ Kind: kindWorkloadCluster.GetKind(), APIVersion: kindWorkloadCluster.GetAPIVersion(), - Name: "{{ .Cluster.metadata.name }}", - Namespace: "{{ .Cluster.metadata.namespace }}", + Name: clusterNameTemplate, + Namespace: clusterNamespaceTemplate, }, IgnoreStatusChanges: true, }, diff --git a/test/fv/tenant-admin_test.go b/test/fv/tenant-admin_test.go index fab0eb25..20e236c3 100644 --- a/test/fv/tenant-admin_test.go +++ b/test/fv/tenant-admin_test.go @@ -102,7 +102,7 @@ var _ = Describe("Feature", func() { }, Rules: []rbacv1.PolicyRule{ { - APIGroups: []string{"apps"}, + APIGroups: []string{appsGroupName}, Resources: []string{"deployments"}, Verbs: []string{"*"}, }, @@ -117,13 +117,13 @@ var _ = Describe("Feature", func() { Name: randomString(), }, RoleRef: rbacv1.RoleRef{ - APIGroup: "rbac.authorization.k8s.io", - Kind: "ClusterRole", + APIGroup: rbacAuthGroup, + Kind: kindClusterRole, Name: clusterRole.Name, }, Subjects: []rbacv1.Subject{ { - Kind: "ServiceAccount", + Kind: kindServiceAccount, Namespace: tenantServiceAccount.Namespace, Name: tenantServiceAccount.Name, }, @@ -225,7 +225,7 @@ var _ = Describe("Feature", func() { Expect(k8sClient.Get(context.TODO(), types.NamespacedName{Name: clusterRole.Name}, currentClusterRole)).To(Succeed()) currentClusterRole.Rules = append(currentClusterRole.Rules, rbacv1.PolicyRule{ APIGroups: []string{""}, - Resources: []string{"secrets"}, + Resources: []string{resourceTypeSecrets}, Verbs: []string{"*"}, }) diff --git a/test/fv/test_constants_test.go b/test/fv/test_constants_test.go new file mode 100644 index 00000000..c518f3a4 --- /dev/null +++ b/test/fv/test_constants_test.go @@ -0,0 +1,210 @@ +/* +Copyright 2025. projectsveltos.io. All rights reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package fv_test + +const ( + // Kyverno chart details + kyvernoRepoURL = "https://kyverno.github.io/kyverno/" + kyvernoChartName = "kyverno/kyverno" + kyvernoVersion352 = "v3.5.2" + kyvernoVersion352S = "3.5.2" + kyvernoVersion351 = "v3.5.1" + kyvernoLatestRelease = "kyverno-latest" + + // Prometheus community chart details + prometheusCommunityURL = "https://prometheus-community.github.io/helm-charts" + prometheusCommunityName = "prometheus-community" + prometheusChartName = "prometheus-community/prometheus" + prometheusVersion2524 = "25.24.0" + prometheusVersion2739 = "27.39.0" + prometheusRelease = "prometheus" + + // Grafana chart details + grafanaRepoName = "grafana" + grafanaChartName = "grafana/grafana" + grafanaVersion1136 = "11.3.6" + grafanaVersion1000 = "10.0.0" + + // Jetstack/cert-manager chart details + jetstackURL = "https://charts.jetstack.io" + jetstackName = "jetstack" + jetstackCertManagerChart = "jetstack/cert-manager" + certManager = "cert-manager" + + // Kong chart details + kongRepoName = "kong" + kongVersion2510 = "2.51.0" + + // External-DNS chart details + externalDNSURL = "https://kubernetes-sigs.github.io/external-dns/" + externalDNSRepoName = "external-dns" + externalDNSChartName = "external-dns/external-dns" + externalDNSVersion = "1.20.0" + externaldnsGroup = "externaldns.k8s.io" + + // Bitnami chart details + bitnamiURL = "https://charts.bitnami.com/bitnami" + bitnamiName = "bitnami" + + // NGINX chart details + nginxLatestRelease = "nginx-latest" + nginxNamespace = "nginx" + nginxVersion222 = "2.2.2" + + // Release names + airflowRelease = "airflow" + flinkRelease = "flink" + + // Kubernetes API versions + apiVersionV1 = "v1" + apiVersionV1alpha1 = "v1alpha1" + + // Kubernetes kinds + kindDeployment = "Deployment" + kindNamespace = "Namespace" + kindSecret = "Secret" + kindConfigMap = "ConfigMap" + kindClusterRole = "ClusterRole" + kindServiceAccount = "ServiceAccount" + kindPod = "Pod" + + // Kubernetes groups + appsGroupName = "apps" + rbacAuthGroup = "rbac.authorization.k8s.io" + + // Annotation values + annotationOkValue = "ok" + annotationTrueValue = "true" + + // Template strings + clusterNameTemplate = "{{ .Cluster.metadata.name }}" + clusterNamespaceTemplate = "{{ .Cluster.metadata.namespace }}" + + // Resource types + resourceTypeSecrets = "secrets" + + // MariaDB chart details + mariadbOperatorURL = "https://helm.mariadb.com/mariadb-operator" + mariadbOperatorName = "mariadb-operator" + mariadbOperatorChart = "mariadb-operator/mariadb-operator" + mariadbVersion0351 = "0.35.1" + mariadbRelease = "mariadb" + prometheusVersion2584 = "25.8.4" + externalDNSVersion1182 = "v1.18.2" + crdsEnabledValues = "crds:\n enabled: true" + + // CloudNative-PG chart details + cloudnativePGURL = "https://cloudnative-pg.github.io/charts" + cloudnativePGName = "cloudnative-pg" + cloudnativePGChart = "cloudnative-pg/cloudnative-pg" + cloudnativePGVersion = "0.26.0" + cnpgRelease = "cnpg" + cnpgSystem = "cnpg-system" + + // Vault OCI chart details + ociVaultURL = "oci://registry-1.docker.io/bitnamicharts" + ociVaultRepoName = "oci-vault" + vaultChartName = "vault" + vaultVersion160 = "1.6.0" + vaultVersion150 = "1.5.0" + vaultInjectorName = "vault-injector" + + // Resource names + nginxDeploymentName = "nginx-deployment" + nginxServiceName = "nginx-service" + kongServiceAccountName = "kong-serviceaccount" + + // Kubernetes resource types + serviceAccountsResource = "serviceaccounts" + + // Kubernetes kinds + kindService = "Service" + kindJob = "Job" + + // Kubernetes groups + batchGroupName = "batch" + + // Label/annotation keys + clusterNameKey = "cluster-name" + + // Annotation values for profile + productionValue = "production" + promotionNameAnnotation = "config.projectsveltos.io/promotionname" + promotionVerifAnnotation = "config.projectsveltos.io/promotion-verification" + + // Helm chart versions + leaveHelmVersion = "7.1.1" + + // Other names + fluxSystemName = "flux-system" + contourRelease = "contour" + matchAllPattern = ".*" + + // Template patterns (without spaces before }}) + clusterNamespaceTrimTemplate = "{{ .Cluster.metadata.namespace}}" + patchesCMNameTemplate = "{{ .Cluster.metadata.name}}-patches" + + // Misc + addonDeplName = "addon-controller" + addonControllerRoleExtra = "addon-controller-role-extra" + templateCMName = "template" + watchfieldsResultName = "watchfields-result" + testValue1 = "value1" + watchedFieldKey = "watched" + + // Sveltos/cluster management + defaultSveltosNamespace = "projectsveltos" + clusterapiWorkloadName = "clusterapi-workload" + + // MariaDB/CNPG deployment names + mariadbOperatorDeployName = "mariadb-mariadb-operator" + cnpgDeployName = "cnpg-cloudnative-pg" + + // Spark chart + sparkName = "spark" + sparkMasterName = "spark-master" + + // k0rdent catalog / ingress-nginx / postgres + k0rdentCatalogURL = "oci://ghcr.io/k0rdent/catalog/charts" + ingressNginxName = "ingress-nginx" + postgresOperatorName = "postgres-operator" + + // Helm chart versions + externalDNSVersion1170 = "1.17.0" + argocdChartVersion = "3.35.4" + wildflyVersion = "2.4.0" + kyvernoVersion370 = "v3.7.0" + kyvernoVersion370S = "3.7.0" + kubePrometheusVersion = "75.9.0" + + // ArgoCD chart + argocdName = "argocd" + argocdServerName = "argocd-server" + + // Wildfly chart + wildflyRepoURL = "https://docs.wildfly.org/wildfly-charts/" + wildflyName = "wildfly" + wildflyChartName = "wildfly/wildfly" + + // Kustomize resources + flux2Name = "flux2" + kustomizeServiceName = "the-service" + kustomizeMapName = "the-map" + kustomizeProdServiceName = "production-the-service" + kustomizeProdDeployName = "production-the-deployment" + kustomizeProdMapName = "production-the-map" +) diff --git a/test/fv/tier_test.go b/test/fv/tier_test.go index 451f2a16..2c491589 100644 --- a/test/fv/tier_test.go +++ b/test/fv/tier_test.go @@ -56,30 +56,30 @@ var _ = Describe("Helm", Serial, func() { types.NamespacedName{Name: clusterProfile.Name}, currentClusterProfile)).To(Succeed()) currentClusterProfile.Spec.HelmCharts = []configv1beta1.HelmChart{ { - RepositoryURL: "https://kyverno.github.io/kyverno/", - RepositoryName: "kyverno", - ChartName: "kyverno/kyverno", - ChartVersion: "v3.5.2", - ReleaseName: "kyverno-latest", - ReleaseNamespace: "kyverno", + RepositoryURL: kyvernoRepoURL, + RepositoryName: kyvernoNamespace, + ChartName: kyvernoChartName, + ChartVersion: kyvernoVersion352, + ReleaseName: kyvernoLatestRelease, + ReleaseNamespace: kyvernoNamespace, HelmChartAction: configv1beta1.HelmChartActionInstall, }, { - RepositoryURL: "https://prometheus-community.github.io/helm-charts", - RepositoryName: "prometheus-community", - ChartName: "prometheus-community/prometheus", - ChartVersion: "27.39.0", - ReleaseName: "prometheus", - ReleaseNamespace: "prometheus", + RepositoryURL: prometheusCommunityURL, + RepositoryName: prometheusCommunityName, + ChartName: prometheusChartName, + ChartVersion: prometheusVersion2739, + ReleaseName: prometheusRelease, + ReleaseNamespace: prometheusRelease, HelmChartAction: configv1beta1.HelmChartActionInstall, }, { RepositoryURL: "https://grafana.github.io/helm-charts", - RepositoryName: "grafana", - ChartName: "grafana/grafana", - ChartVersion: "10.0.0", - ReleaseName: "grafana", - ReleaseNamespace: "grafana", + RepositoryName: grafanaRepoName, + ChartName: grafanaChartName, + ChartVersion: grafanaVersion1000, + ReleaseName: grafanaRepoName, + ReleaseNamespace: grafanaRepoName, HelmChartAction: configv1beta1.HelmChartActionInstall, }, } @@ -106,16 +106,16 @@ var _ = Describe("Helm", Serial, func() { Eventually(func() error { depl := &appsv1.Deployment{} return workloadClient.Get(context.TODO(), - types.NamespacedName{Namespace: "kyverno", Name: "kyverno-admission-controller"}, depl) + types.NamespacedName{Namespace: kyvernoNamespace, Name: admissionControllerDeplName}, depl) }, timeout, pollingInterval).Should(BeNil()) Byf("Verifying ClusterSummary %s status is set to Deployed for Helm feature", clusterSummary.Name) verifyFeatureStatusIsProvisioned(kindWorkloadCluster.GetNamespace(), clusterSummary.Name, libsveltosv1beta1.FeatureHelm) charts := []configv1beta1.Chart{ - {ReleaseName: "kyverno-latest", ChartVersion: "3.5.2", Namespace: "kyverno"}, - {ReleaseName: "grafana", ChartVersion: "10.0.0", Namespace: "grafana"}, - {ReleaseName: "prometheus", ChartVersion: "27.39.0", Namespace: "prometheus"}, + {ReleaseName: kyvernoLatestRelease, ChartVersion: kyvernoVersion352S, Namespace: kyvernoNamespace}, + {ReleaseName: grafanaRepoName, ChartVersion: grafanaVersion1000, Namespace: grafanaRepoName}, + {ReleaseName: prometheusRelease, ChartVersion: prometheusVersion2739, Namespace: prometheusRelease}, } verifyClusterConfiguration(configv1beta1.ClusterProfileKind, clusterProfile.Name, @@ -133,12 +133,12 @@ var _ = Describe("Helm", Serial, func() { Expect(k8sClient.Get(context.TODO(), types.NamespacedName{Name: newClusterProfile.Name}, currentClusterProfile)).To(Succeed()) currentClusterProfile.Spec.HelmCharts = []configv1beta1.HelmChart{ { - RepositoryURL: "https://kyverno.github.io/kyverno/", - RepositoryName: "kyverno", - ChartName: "kyverno/kyverno", - ChartVersion: "v3.5.1", - ReleaseName: "kyverno-latest", - ReleaseNamespace: "kyverno", + RepositoryURL: kyvernoRepoURL, + RepositoryName: kyvernoNamespace, + ChartName: kyvernoChartName, + ChartVersion: kyvernoVersion351, + ReleaseName: kyvernoLatestRelease, + ReleaseNamespace: kyvernoNamespace, HelmChartAction: configv1beta1.HelmChartActionInstall, }, } @@ -190,8 +190,8 @@ var _ = Describe("Helm", Serial, func() { }, timeout, pollingInterval).Should(BeTrue()) charts = []configv1beta1.Chart{ - {ReleaseName: "grafana", ChartVersion: "10.0.0", Namespace: "grafana"}, - {ReleaseName: "prometheus", ChartVersion: "27.39.0", Namespace: "prometheus"}, + {ReleaseName: grafanaRepoName, ChartVersion: grafanaVersion1000, Namespace: grafanaRepoName}, + {ReleaseName: prometheusRelease, ChartVersion: prometheusVersion2739, Namespace: prometheusRelease}, } verifyClusterConfiguration(configv1beta1.ClusterProfileKind, clusterProfile.Name, @@ -199,7 +199,7 @@ var _ = Describe("Helm", Serial, func() { nil, charts) charts = []configv1beta1.Chart{ - {ReleaseName: "kyverno-latest", ChartVersion: "3.5.1", Namespace: "kyverno"}, + {ReleaseName: kyvernoLatestRelease, ChartVersion: "3.5.1", Namespace: kyvernoNamespace}, } verifyClusterConfiguration(configv1beta1.ClusterProfileKind, newClusterProfile.Name, @@ -213,7 +213,7 @@ var _ = Describe("Helm", Serial, func() { Eventually(func() bool { depl := &appsv1.Deployment{} err = workloadClient.Get(context.TODO(), - types.NamespacedName{Namespace: "kyverno", Name: "kyverno-latest"}, depl) + types.NamespacedName{Namespace: kyvernoNamespace, Name: kyvernoLatestRelease}, depl) return apierrors.IsNotFound(err) }, timeout, pollingInterval).Should(BeTrue()) }) diff --git a/test/fv/validate_health_metrics_test.go b/test/fv/validate_health_metrics_test.go index 75247f46..05491139 100644 --- a/test/fv/validate_health_metrics_test.go +++ b/test/fv/validate_health_metrics_test.go @@ -110,9 +110,9 @@ var _ = Describe("ValidateHealth metric-based checks", func() { cpPrometheus.Spec.SyncMode = configv1beta1.SyncModeContinuous cpPrometheus.Spec.HelmCharts = []configv1beta1.HelmChart{ { - RepositoryURL: "https://prometheus-community.github.io/helm-charts", - RepositoryName: "prometheus-community", - ChartName: "prometheus-community/prometheus", + RepositoryURL: prometheusCommunityURL, + RepositoryName: prometheusCommunityName, + ChartName: prometheusChartName, ChartVersion: "25.27.0", ReleaseName: prometheusRelease, ReleaseNamespace: monitoringNs, @@ -124,9 +124,9 @@ var _ = Describe("ValidateHealth metric-based checks", func() { { Name: "prometheus-server-ready", FeatureID: libsveltosv1beta1.FeatureHelm, - Group: "apps", - Version: "v1", - Kind: "Deployment", + Group: appsGroupName, + Version: apiVersionV1, + Kind: kindDeployment, Namespace: monitoringNs, Script: luaDeploymentHealthScript, }, diff --git a/test/fv/watchfields_test.go b/test/fv/watchfields_test.go index 55a27347..f3c3d858 100644 --- a/test/fv/watchfields_test.go +++ b/test/fv/watchfields_test.go @@ -64,8 +64,8 @@ var _ = Describe("WatchFields", func() { Namespace: ns.Name, }, Data: map[string]string{ - "watched": "value1", - "unwatched": "extra", + watchedFieldKey: testValue1, + "unwatched": "extra", }, } Expect(k8sClient.Create(context.TODO(), refCM)).To(Succeed()) @@ -73,7 +73,7 @@ var _ = Describe("WatchFields", func() { Byf("Create policy ConfigMap containing a template that references the watched field") policyConfigMap := createConfigMapWithPolicy(ns.Name, namePrefix+randomString(), watchFieldsPolicy) policyConfigMap.Annotations = map[string]string{ - libsveltosv1beta1.PolicyTemplateAnnotation: "ok", + libsveltosv1beta1.PolicyTemplateAnnotation: annotationOkValue, } Expect(k8sClient.Create(context.TODO(), policyConfigMap)).To(Succeed()) @@ -83,8 +83,8 @@ var _ = Describe("WatchFields", func() { clusterProfile.Spec.TemplateResourceRefs = []configv1beta1.TemplateResourceRef{ { Resource: corev1.ObjectReference{ - APIVersion: "v1", - Kind: "ConfigMap", + APIVersion: apiVersionV1, + Kind: kindConfigMap, Namespace: refCM.Namespace, Name: refCM.Name, }, @@ -120,8 +120,8 @@ var _ = Describe("WatchFields", func() { Eventually(func() bool { result := &corev1.ConfigMap{} err := workloadClient.Get(context.TODO(), - types.NamespacedName{Namespace: defaultNamespace, Name: "watchfields-result"}, result) - return err == nil && result.Data["watchedValue"] == "value1" + types.NamespacedName{Namespace: defaultNamespace, Name: watchfieldsResultName}, result) + return err == nil && result.Data["watchedValue"] == testValue1 }, timeout, pollingInterval).Should(BeTrue()) Byf("Updating non-watched field in the referenced ConfigMap") @@ -154,8 +154,8 @@ var _ = Describe("WatchFields", func() { Byf("Verifying workload cluster ConfigMap still shows the original watched value") result := &corev1.ConfigMap{} Expect(workloadClient.Get(context.TODO(), - types.NamespacedName{Namespace: defaultNamespace, Name: "watchfields-result"}, result)).To(Succeed()) - Expect(result.Data["watchedValue"]).To(Equal("value1")) + types.NamespacedName{Namespace: defaultNamespace, Name: watchfieldsResultName}, result)).To(Succeed()) + Expect(result.Data["watchedValue"]).To(Equal(testValue1)) deleteClusterProfile(clusterProfile) })