diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 1c6955f..76bfa9d 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -36,7 +36,9 @@ jobs: # TODO coverage report - name: Go linters - run: make lint + uses: golangci/golangci-lint-action@v4 + with: + version: v1.55.2 container-check: runs-on: ubuntu-latest diff --git a/.golangci.yml b/.golangci.yml index a3ad43a..7d6bbd8 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -2,7 +2,12 @@ run: skip-dirs-use-default: false modules-download-mode: readonly - allow-parallel-runners: false + allow-parallel-runners: true + skip-dirs: + - test/* + skip-files: + - internal/controller/velerobackup_controller.go + - internal/controller/velerobackup_controller_test.go output: format: colored-line-number @@ -107,8 +112,14 @@ issues: - revive text: "^struct-tag: unknown option 'inline' in JSON tag$" - linters: - - stylecheck - text: "ST1000:|ST1020:|ST1021:|ST1022:" + - revive + text: "^add-constant: avoid magic numbers like '0', create a named constant for it$" + - linters: + - revive + text: "^add-constant: avoid magic numbers like '1', create a named constant for it$" + # - linters: + # - stylecheck + # text: "ST1000:|ST1020:|ST1021:|ST1022:" max-issues-per-linter: 0 max-same-issues: 0 diff --git a/Makefile b/Makefile index 5195038..a76479a 100644 --- a/Makefile +++ b/Makefile @@ -166,7 +166,7 @@ GOLANGCI_LINT = $(LOCALBIN)/golangci-lint-$(GOLANGCI_LINT_VERSION) KUSTOMIZE_VERSION ?= v5.3.0 CONTROLLER_TOOLS_VERSION ?= v0.14.0 ENVTEST_VERSION ?= latest -GOLANGCI_LINT_VERSION ?= v1.56.2 +GOLANGCI_LINT_VERSION ?= v1.55.2 .PHONY: kustomize kustomize: $(KUSTOMIZE) ## Download kustomize locally if necessary. diff --git a/api/v1alpha1/nonadminbackup_types.go b/api/v1alpha1/nonadminbackup_types.go index 56bb58e..10fb806 100644 --- a/api/v1alpha1/nonadminbackup_types.go +++ b/api/v1alpha1/nonadminbackup_types.go @@ -23,11 +23,6 @@ import ( // NonAdminBackupSpec defines the desired state of NonAdminBackup type NonAdminBackupSpec struct { - // NonAdminBackup log level (use debug for the most logging, leave unset for default) - // +optional - // +kubebuilder:validation:Enum=trace;debug;info;warning;error;fatal;panic - LogLevel string `json:"logLevel,omitempty"` - // https://github.com/vmware-tanzu/velero/blob/main/pkg/apis/velero/v1/backup_types.go // BackupSpec defines the specification for a Velero backup. @@ -35,6 +30,11 @@ type NonAdminBackupSpec struct { // BackupStatus captures the current status of a Velero backup. BackupStatus *velerov1api.BackupStatus `json:"backupStatus,omitempty"` + + // NonAdminBackup log level (use debug for the most logging, leave unset for default) + // +optional + // +kubebuilder:validation:Enum=trace;debug;info;warning;error;fatal;panic + LogLevel string `json:"logLevel,omitempty"` } // NonAdminBackupStatus defines the observed state of NonAdminBackup @@ -42,8 +42,8 @@ type NonAdminBackupStatus struct { Conditions []metav1.Condition `json:"conditions,omitempty"` } -//+kubebuilder:object:root=true -//+kubebuilder:subresource:status +// +kubebuilder:object:root=true +// +kubebuilder:subresource:status // NonAdminBackup is the Schema for the nonadminbackups API type NonAdminBackup struct { @@ -54,7 +54,7 @@ type NonAdminBackup struct { Status NonAdminBackupStatus `json:"status,omitempty"` } -//+kubebuilder:object:root=true +// +kubebuilder:object:root=true // NonAdminBackupList contains a list of NonAdminBackup type NonAdminBackupList struct { diff --git a/cmd/main.go b/cmd/main.go index dc5984f..cc2d2ea 100644 --- a/cmd/main.go +++ b/cmd/main.go @@ -49,7 +49,7 @@ func init() { utilruntime.Must(nacv1alpha1.AddToScheme(scheme)) utilruntime.Must(velerov1api.AddToScheme(scheme)) - //+kubebuilder:scaffold:scheme + // +kubebuilder:scaffold:scheme } func main() { @@ -130,7 +130,7 @@ func main() { setupLog.Error(err, "unable to create controller", "controller", "NonAdminBackup") os.Exit(1) } - //+kubebuilder:scaffold:builder + // +kubebuilder:scaffold:builder if err = (&controller.VeleroBackupReconciler{ Client: mgr.GetClient(), diff --git a/internal/controller/common_k8s.go b/internal/controller/common_k8s.go index 9d9ad40..361c157 100644 --- a/internal/controller/common_k8s.go +++ b/internal/controller/common_k8s.go @@ -1,3 +1,19 @@ +/* +Copyright 2024. + +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 controller import ( @@ -14,7 +30,7 @@ const ( ManagedByLabelValue = "oadp-nac-controller" NabOriginNameAnnotation = "openshift.io/oadp-nab-origin-name" NabOriginNamespaceAnnotation = "openshift.io/oadp-nab-origin-namespace" - NabOriginUuidAnnotation = "openshift.io/oadp-nab-origin-uuid" + NabOriginUUIDAnnotation = "openshift.io/oadp-nab-origin-uuid" ) const ( @@ -29,22 +45,24 @@ func CreateLabelsForNac(labels map[string]string) map[string]string { mergedLabels, err := mergeUniqueKeyTOfTMaps(defaultLabels, labels) if err != nil { - fmt.Println("Error merging labels:", err) + // TODO logger + _, _ = fmt.Println("Error merging labels:", err) return defaultLabels } return mergedLabels } -func CreateAnnotationsForNac(ownerNamespace string, ownerName string, ownerUuid string, existingAnnotations map[string]string) map[string]string { +func CreateAnnotationsForNac(ownerNamespace string, ownerName string, ownerUUID string, existingAnnotations map[string]string) map[string]string { defaultAnnotations := map[string]string{ NabOriginNamespaceAnnotation: ownerNamespace, NabOriginNameAnnotation: ownerName, - NabOriginUuidAnnotation: ownerUuid, + NabOriginUUIDAnnotation: ownerUUID, } mergedAnnotations, err := mergeUniqueKeyTOfTMaps(defaultAnnotations, existingAnnotations) if err != nil { - fmt.Println("Error merging annotations:", err) + // TODO logger + _, _ = fmt.Println("Error merging annotations:", err) return defaultAnnotations } return mergedAnnotations diff --git a/internal/controller/common_k8s_test.go b/internal/controller/common_k8s_test.go index 9f98817..efabe76 100644 --- a/internal/controller/common_k8s_test.go +++ b/internal/controller/common_k8s_test.go @@ -1,3 +1,19 @@ +/* +Copyright 2024. + +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 controller import ( @@ -8,63 +24,56 @@ import ( ) func TestMergeUniqueKeyTOfTMaps(t *testing.T) { - type args struct { - userLabels []map[string]string - } + const ( + d = "d" + delta = "delta" + ) tests := []struct { name string - args args want map[string]string + args []map[string]string wantErr bool }{ { name: "append unique labels together", - args: args{ - userLabels: []map[string]string{ - {"a": "a"}, - {"b": "b"}, - }, + args: []map[string]string{ + {"a": "alpha"}, + {"b": "beta"}, }, want: map[string]string{ - "a": "a", - "b": "b", + "a": "alpha", + "b": "beta", }, }, { name: "append unique labels together, with valid duplicates", - args: args{ - userLabels: []map[string]string{ - {"a": "a"}, - {"b": "b"}, - {"b": "b"}, - }, + args: []map[string]string{ + {"c": "gamma"}, + {d: delta}, + {d: delta}, }, want: map[string]string{ - "a": "a", - "b": "b", + "c": "gamma", + d: delta, }, }, { name: "append unique labels together - nil sandwich", - args: args{ - userLabels: []map[string]string{ - {"a": "a"}, - nil, - {"b": "b"}, - }, + args: []map[string]string{ + {"x": "chi"}, + nil, + {"y": "psi"}, }, want: map[string]string{ - "a": "a", - "b": "b", + "x": "chi", + "y": "psi", }, }, { name: "should error when append duplicate label keys with different value together", - args: args{ - userLabels: []map[string]string{ - {"a": "a"}, - {"a": "b"}, - }, + args: []map[string]string{ + {"key": "value-1"}, + {"key": "value-2"}, }, want: nil, wantErr: true, @@ -72,7 +81,7 @@ func TestMergeUniqueKeyTOfTMaps(t *testing.T) { } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - got, err := mergeUniqueKeyTOfTMaps(tt.args.userLabels...) + got, err := mergeUniqueKeyTOfTMaps(tt.args...) if (err != nil) != tt.wantErr { t.Errorf("mergeUniqueKeyTOfTMaps() error = %v, wantErr %v", err, tt.wantErr) return @@ -111,17 +120,17 @@ func TestCreateAnnotationsForNac(t *testing.T) { ownerName := "testOwner" ownerNamespace := "testNamespace" - ownerUuid := "f2c4d2c3-58d3-46ec-bf03-5940f567f7f8" + ownerUUID := "f2c4d2c3-58d3-46ec-bf03-5940f567f7f8" expectedAnnotations := map[string]string{ NabOriginNamespaceAnnotation: ownerNamespace, NabOriginNameAnnotation: ownerName, - NabOriginUuidAnnotation: ownerUuid, + NabOriginUUIDAnnotation: ownerUUID, "existingKey1": "existingValue1", "existingKey2": "existingValue2", } - mergedAnnotations := CreateAnnotationsForNac(ownerNamespace, ownerName, ownerUuid, existingAnnotations) + mergedAnnotations := CreateAnnotationsForNac(ownerNamespace, ownerName, ownerUUID, existingAnnotations) assert.Equal(t, expectedAnnotations, mergedAnnotations, "Merged annotations should match expected annotations") // Merging annotations with conflicts @@ -132,9 +141,9 @@ func TestCreateAnnotationsForNac(t *testing.T) { expectedAnnotationsWithConflict := map[string]string{ NabOriginNameAnnotation: ownerName, NabOriginNamespaceAnnotation: ownerNamespace, - NabOriginUuidAnnotation: ownerUuid, + NabOriginUUIDAnnotation: ownerUUID, } - mergedAnnotationsWithConflict := CreateAnnotationsForNac(ownerNamespace, ownerName, ownerUuid, existingAnnotationsWithConflict) + mergedAnnotationsWithConflict := CreateAnnotationsForNac(ownerNamespace, ownerName, ownerUUID, existingAnnotationsWithConflict) assert.Equal(t, expectedAnnotationsWithConflict, mergedAnnotationsWithConflict, "Merged annotations should match expected annotations with conflict") } diff --git a/internal/controller/common_nab.go b/internal/controller/common_nab.go index 2a6d23a..5fc25dc 100644 --- a/internal/controller/common_nab.go +++ b/internal/controller/common_nab.go @@ -1,3 +1,19 @@ +/* +Copyright 2024. + +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 controller import ( @@ -11,7 +27,6 @@ import ( ) func GetVeleroBackupSpecFromNonAdminBackup(nonAdminBackup *nacv1alpha1.NonAdminBackup) (*velerov1api.BackupSpec, error) { - if nonAdminBackup == nil { return nil, fmt.Errorf("nonAdminBackup is nil") } diff --git a/internal/controller/common_nab_test.go b/internal/controller/common_nab_test.go index 788bee3..1f98eef 100644 --- a/internal/controller/common_nab_test.go +++ b/internal/controller/common_nab_test.go @@ -1,3 +1,19 @@ +/* +Copyright 2024. + +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 controller import ( diff --git a/internal/controller/common_velero.go b/internal/controller/common_velero.go index 6c9a6f6..e455481 100644 --- a/internal/controller/common_velero.go +++ b/internal/controller/common_velero.go @@ -1,3 +1,19 @@ +/* +Copyright 2024. + +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 controller import ( @@ -12,20 +28,22 @@ import ( nacv1alpha1 "github.com/migtools/oadp-non-admin/api/v1alpha1" ) +const requiredAnnotationError = "backup does not have the required annotation '%s'" + func HasRequiredLabel(backup *velerov1api.Backup) bool { labels := backup.GetLabels() value, exists := labels[ManagedByLabel] return exists && value == ManagedByLabelValue } -func GetNonAdminFromBackup(ctx context.Context, client client.Client, backup *velerov1api.Backup) (*nacv1alpha1.NonAdminBackup, error) { +func GetNonAdminFromBackup(ctx context.Context, clientInstance client.Client, backup *velerov1api.Backup) (*nacv1alpha1.NonAdminBackup, error) { // Check if the backup has the required annotations to identify the associated NonAdminBackup object - log := log.FromContext(ctx) + logger := log.FromContext(ctx) annotations := backup.GetAnnotations() annotationsStr := fmt.Sprintf("%v", annotations) - log.V(1).Info("Velero Backup Annotations", "annotations", annotationsStr) + logger.V(1).Info("Velero Backup Annotations", "annotations", annotationsStr) if annotations == nil { return nil, fmt.Errorf("backup has no annotations") @@ -33,12 +51,12 @@ func GetNonAdminFromBackup(ctx context.Context, client client.Client, backup *ve nabOriginNamespace, ok := annotations[NabOriginNamespaceAnnotation] if !ok { - return nil, fmt.Errorf("backup does not have the required annotation '%s'", NabOriginNamespaceAnnotation) + return nil, fmt.Errorf(requiredAnnotationError, NabOriginNamespaceAnnotation) } nabOriginName, ok := annotations[NabOriginNameAnnotation] if !ok { - return nil, fmt.Errorf("backup does not have the required annotation '%s'", NabOriginNameAnnotation) + return nil, fmt.Errorf(requiredAnnotationError, NabOriginNameAnnotation) } nonAdminBackupKey := types.NamespacedName{ @@ -47,17 +65,17 @@ func GetNonAdminFromBackup(ctx context.Context, client client.Client, backup *ve } nonAdminBackup := &nacv1alpha1.NonAdminBackup{} - err := client.Get(ctx, nonAdminBackupKey, nonAdminBackup) + err := clientInstance.Get(ctx, nonAdminBackupKey, nonAdminBackup) if err != nil { return nil, fmt.Errorf("failed to fetch NonAdminBackup object: %v", err) } - nabOriginUuid, ok := annotations[NabOriginUuidAnnotation] + nabOriginUUID, ok := annotations[NabOriginUUIDAnnotation] if !ok { - return nil, fmt.Errorf("backup does not have the required annotation '%s'", NabOriginUuidAnnotation) + return nil, fmt.Errorf(requiredAnnotationError, NabOriginUUIDAnnotation) } // Ensure UID matches - if nonAdminBackup.ObjectMeta.UID != types.UID(nabOriginUuid) { + if nonAdminBackup.ObjectMeta.UID != types.UID(nabOriginUUID) { return nil, fmt.Errorf("UID from annotation does not match UID of fetched NonAdminBackup object") } diff --git a/internal/controller/common_velero_test.go b/internal/controller/common_velero_test.go index a488668..d8570d9 100644 --- a/internal/controller/common_velero_test.go +++ b/internal/controller/common_velero_test.go @@ -1,3 +1,19 @@ +/* +Copyright 2024. + +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 controller import ( @@ -33,7 +49,7 @@ func TestGetNonAdminFromBackup(t *testing.T) { Annotations: map[string]string{ NabOriginNamespaceAnnotation: "non-admin-backup-namespace", NabOriginNameAnnotation: "non-admin-backup-name", - NabOriginUuidAnnotation: "12345678-1234-1234-1234-123456789abc", + NabOriginUUIDAnnotation: "12345678-1234-1234-1234-123456789abc", }, }, } diff --git a/internal/controller/nonadminbackup_controller.go b/internal/controller/nonadminbackup_controller.go index 20e3d74..33c552b 100644 --- a/internal/controller/nonadminbackup_controller.go +++ b/internal/controller/nonadminbackup_controller.go @@ -42,9 +42,11 @@ type NonAdminBackupReconciler struct { NamespacedName types.NamespacedName } -//+kubebuilder:rbac:groups=nac.oadp.openshift.io,resources=nonadminbackups,verbs=get;list;watch;create;update;patch;delete -//+kubebuilder:rbac:groups=nac.oadp.openshift.io,resources=nonadminbackups/status,verbs=get;update;patch -//+kubebuilder:rbac:groups=nac.oadp.openshift.io,resources=nonadminbackups/finalizers,verbs=update +const nameField = "Name" + +// +kubebuilder:rbac:groups=nac.oadp.openshift.io,resources=nonadminbackups,verbs=get;list;watch;create;update;patch;delete +// +kubebuilder:rbac:groups=nac.oadp.openshift.io,resources=nonadminbackups/status,verbs=get;update;patch +// +kubebuilder:rbac:groups=nac.oadp.openshift.io,resources=nonadminbackups/finalizers,verbs=update // Reconcile is part of the main kubernetes reconciliation loop which aims to // move the current state of the cluster closer to the desired state. @@ -57,7 +59,7 @@ type NonAdminBackupReconciler struct { // - https://pkg.go.dev/sigs.k8s.io/controller-runtime@v0.17.0/pkg/reconcile func (r *NonAdminBackupReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) { r.Log = log.FromContext(ctx) - log := r.Log.WithValues("NonAdminBackup", req.NamespacedName) + logger := r.Log.WithValues("NonAdminBackup", req.NamespacedName) r.Context = ctx r.NamespacedName = req.NamespacedName @@ -66,28 +68,28 @@ func (r *NonAdminBackupReconciler) Reconcile(ctx context.Context, req ctrl.Reque err := r.Get(ctx, req.NamespacedName, &nab) if err != nil && errors.IsNotFound(err) { - log.V(1).Info("Deleted NonAdminBackup CR", "Name", req.Name, "Namespace", req.Namespace) + logger.V(1).Info("Deleted NonAdminBackup CR", nameField, req.Name, "Namespace", req.Namespace) return ctrl.Result{}, nil } if err != nil { - log.Error(err, "Unable to fetch NonAdminBackup CR", "Name", req.Name, "Namespace", req.Namespace) + logger.Error(err, "Unable to fetch NonAdminBackup CR", nameField, req.Name, "Namespace", req.Namespace) return ctrl.Result{}, err } veleroBackupSpec, err := GetVeleroBackupSpecFromNonAdminBackup(&nab) if veleroBackupSpec == nil { - log.Error(err, "unable to fetch VeleroBackupSpec from NonAdminBackup") + logger.Error(err, "unable to fetch VeleroBackupSpec from NonAdminBackup") return ctrl.Result{}, nil } if err != nil { - log.Error(err, "Error while performing NonAdminBackup reconcile") + logger.Error(err, "Error while performing NonAdminBackup reconcile") return ctrl.Result{}, err } - log.Info("NonAdminBackup Reconcile loop") + logger.Info("NonAdminBackup Reconcile loop") veleroBackupName := GenerateVeleroBackupName(nab.Namespace, nab.Name) @@ -96,7 +98,7 @@ func (r *NonAdminBackupReconciler) Reconcile(ctx context.Context, req ctrl.Reque if err != nil && errors.IsNotFound(err) { // Create backup - log.Info("No backup found", "Name", veleroBackupName) + logger.Info("No backup found", nameField, veleroBackupName) veleroBackup = velerov1api.Backup{ ObjectMeta: metav1.ObjectMeta{ Name: veleroBackupName, @@ -105,10 +107,10 @@ func (r *NonAdminBackupReconciler) Reconcile(ctx context.Context, req ctrl.Reque Spec: *veleroBackupSpec, } } else if err != nil && !errors.IsNotFound(err) { - log.Error(err, "unable to fetch VeleroBackup") + logger.Error(err, "unable to fetch VeleroBackup") return ctrl.Result{}, err } else { - log.Info("Backup already exists", "Name", veleroBackupName) + logger.Info("Backup already exists", nameField, veleroBackupName) return ctrl.Result{}, nil } @@ -126,13 +128,13 @@ func (r *NonAdminBackupReconciler) Reconcile(ctx context.Context, req ctrl.Reque _, err = controllerutil.CreateOrPatch(ctx, r.Client, &veleroBackup, nil) if err != nil { - log.Error(err, "Failed to create backup", "Name", veleroBackupName) + logger.Error(err, "Failed to create backup", nameField, veleroBackupName) return ctrl.Result{}, err - } else { - log.Info("Backup successfully created", "Name", veleroBackupName) } - log.Info("NonAdminBackup Reconcile loop end") + logger.Info("Backup successfully created", nameField, veleroBackupName) + + logger.Info("NonAdminBackup Reconcile loop end") return ctrl.Result{}, nil } diff --git a/internal/controller/nonadminbackup_controller_test.go b/internal/controller/nonadminbackup_controller_test.go index 6f58d45..551e3e4 100644 --- a/internal/controller/nonadminbackup_controller_test.go +++ b/internal/controller/nonadminbackup_controller_test.go @@ -19,8 +19,8 @@ package controller import ( "context" - . "github.com/onsi/ginkgo/v2" - . "github.com/onsi/gomega" + ginkgov2 "github.com/onsi/ginkgo/v2" + "github.com/onsi/gomega" "k8s.io/apimachinery/pkg/api/errors" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/types" @@ -29,8 +29,8 @@ import ( nacv1alpha1 "github.com/migtools/oadp-non-admin/api/v1alpha1" ) -var _ = Describe("NonAdminBackup Controller", func() { - Context("When reconciling a resource", func() { +var _ = ginkgov2.Describe("NonAdminBackup Controller", func() { + ginkgov2.Context("When reconciling a resource", func() { const resourceName = "test-resource" ctx := context.Background() @@ -41,8 +41,8 @@ var _ = Describe("NonAdminBackup Controller", func() { } nonadminbackup := &nacv1alpha1.NonAdminBackup{} - BeforeEach(func() { - By("creating the custom resource for the Kind NonAdminBackup") + ginkgov2.BeforeEach(func() { + ginkgov2.By("creating the custom resource for the Kind NonAdminBackup") err := k8sClient.Get(ctx, typeNamespacedName, nonadminbackup) if err != nil && errors.IsNotFound(err) { resource := &nacv1alpha1.NonAdminBackup{ @@ -52,21 +52,21 @@ var _ = Describe("NonAdminBackup Controller", func() { }, // TODO(user): Specify other spec details if needed. } - Expect(k8sClient.Create(ctx, resource)).To(Succeed()) + gomega.Expect(k8sClient.Create(ctx, resource)).To(gomega.Succeed()) } }) - AfterEach(func() { + ginkgov2.AfterEach(func() { // TODO(user): Cleanup logic after each test, like removing the resource instance. resource := &nacv1alpha1.NonAdminBackup{} err := k8sClient.Get(ctx, typeNamespacedName, resource) - Expect(err).NotTo(HaveOccurred()) + gomega.Expect(err).NotTo(gomega.HaveOccurred()) - By("Cleanup the specific resource instance NonAdminBackup") - Expect(k8sClient.Delete(ctx, resource)).To(Succeed()) + ginkgov2.By("Cleanup the specific resource instance NonAdminBackup") + gomega.Expect(k8sClient.Delete(ctx, resource)).To(gomega.Succeed()) }) - It("should successfully reconcile the resource", func() { - By("Reconciling the created resource") + ginkgov2.It("should successfully reconcile the resource", func() { + ginkgov2.By("Reconciling the created resource") controllerReconciler := &NonAdminBackupReconciler{ Client: k8sClient, Scheme: k8sClient.Scheme(), @@ -75,7 +75,7 @@ var _ = Describe("NonAdminBackup Controller", func() { _, err := controllerReconciler.Reconcile(ctx, reconcile.Request{ NamespacedName: typeNamespacedName, }) - Expect(err).NotTo(HaveOccurred()) + gomega.Expect(err).NotTo(gomega.HaveOccurred()) // TODO(user): Add more specific assertions depending on your controller's reconciliation logic. // Example: If you expect a certain status condition after reconciliation, verify it here. }) diff --git a/internal/controller/suite_test.go b/internal/controller/suite_test.go index b419fdc..e1510ba 100644 --- a/internal/controller/suite_test.go +++ b/internal/controller/suite_test.go @@ -22,8 +22,8 @@ import ( "runtime" "testing" - . "github.com/onsi/ginkgo/v2" - . "github.com/onsi/gomega" + ginkgov2 "github.com/onsi/ginkgo/v2" + "github.com/onsi/gomega" "k8s.io/client-go/kubernetes/scheme" "k8s.io/client-go/rest" "sigs.k8s.io/controller-runtime/pkg/client" @@ -42,15 +42,15 @@ var k8sClient client.Client var testEnv *envtest.Environment func TestControllers(t *testing.T) { - RegisterFailHandler(Fail) + gomega.RegisterFailHandler(ginkgov2.Fail) - RunSpecs(t, "Controller Suite") + ginkgov2.RunSpecs(t, "Controller Suite") } -var _ = BeforeSuite(func() { - logf.SetLogger(zap.New(zap.WriteTo(GinkgoWriter), zap.UseDevMode(true))) +var _ = ginkgov2.BeforeSuite(func() { + logf.SetLogger(zap.New(zap.WriteTo(ginkgov2.GinkgoWriter), zap.UseDevMode(true))) - By("bootstrapping test environment") + ginkgov2.By("bootstrapping test environment") testEnv = &envtest.Environment{ CRDDirectoryPaths: []string{filepath.Join("..", "..", "config", "crd", "bases")}, ErrorIfCRDPathMissing: true, @@ -67,22 +67,21 @@ var _ = BeforeSuite(func() { var err error // cfg is defined in this file globally. cfg, err = testEnv.Start() - Expect(err).NotTo(HaveOccurred()) - Expect(cfg).NotTo(BeNil()) + gomega.Expect(err).NotTo(gomega.HaveOccurred()) + gomega.Expect(cfg).NotTo(gomega.BeNil()) err = nacv1alpha1.AddToScheme(scheme.Scheme) - Expect(err).NotTo(HaveOccurred()) + gomega.Expect(err).NotTo(gomega.HaveOccurred()) - //+kubebuilder:scaffold:scheme + // +kubebuilder:scaffold:scheme k8sClient, err = client.New(cfg, client.Options{Scheme: scheme.Scheme}) - Expect(err).NotTo(HaveOccurred()) - Expect(k8sClient).NotTo(BeNil()) - + gomega.Expect(err).NotTo(gomega.HaveOccurred()) + gomega.Expect(k8sClient).NotTo(gomega.BeNil()) }) -var _ = AfterSuite(func() { - By("tearing down the test environment") +var _ = ginkgov2.AfterSuite(func() { + ginkgov2.By("tearing down the test environment") err := testEnv.Stop() - Expect(err).NotTo(HaveOccurred()) + gomega.Expect(err).NotTo(gomega.HaveOccurred()) })