Skip to content

Commit

Permalink
Add unit tests for secret controllers
Browse files Browse the repository at this point in the history
Signed-off-by: vbadrina <[email protected]>
  • Loading branch information
vbnrh committed Jul 11, 2024
1 parent 652c5ef commit e2d1abe
Show file tree
Hide file tree
Showing 3 changed files with 460 additions and 0 deletions.
143 changes: 143 additions & 0 deletions addons/blue_secret_controller_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,143 @@
package addons

import (
"context"
"testing"

ocsv1 "github.com/red-hat-storage/ocs-operator/api/v1"
"github.com/red-hat-storage/odf-multicluster-orchestrator/controllers/utils"
rookv1 "github.com/rook/rook/pkg/apis/ceph.rook.io/v1"
corev1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/types"
ctrl "sigs.k8s.io/controller-runtime"
"sigs.k8s.io/controller-runtime/pkg/client/fake"
)

// Define the test secret and related data
var (
spokeClusterName = "test-cluster"
sData = map[string][]byte{
"token": []byte("ZXlKbWMybGtJam9pTjJFelpEWmlPREV0WVRVMVpDMDBOR1psTFRnMFpEQXRORFpqTmpkalpETTVOV05oSWl3aVkyeHBaVzUwWDJsa0lqb2ljbUprTFcxcGNuSnZjaTF3WldWeUlpd2lhMlY1SWpvaVFWRkJXRmRaT1cxcU56STJTMmhCUVdWWFMyWXdaMkpSWjBkQlpVbDNUR3RJVmtaaU5HYzlQU0lzSW0xdmJsOW9iM04wSWpvaU1UY3lMak14TGpFek1TNHhPRE02TXpNd01Dd3hOekl1TXpFdU1UWTNMakUwTXpvek16QXdMREUzTWk0ek1TNDFPUzR4TlRFNk16TXdNQ0lzSW01aGJXVnpjR0ZqWlNJNkltOXdaVzV6YUdsbWRDMXpkRzl5WVdkbEluMD0="),
"cluster": []byte("b2NzLXN0b3JhZ2VjbHVzdGVyLWNlcGhjbHVzdGVy"),
}

managedClusterSecret = &corev1.Secret{
ObjectMeta: metav1.ObjectMeta{
Name: "cluster-peer-token-ocs-storagecluster-cephcluster",
Namespace: "openshift-storage",
Labels: map[string]string{
"app": "rook",
},
OwnerReferences: []metav1.OwnerReference{
{
APIVersion: "ceph.rook.io/v1",
Kind: "CephCluster",
Name: "ocs-storagecluster-cephcluster",
UID: "390fa888-59c0-4212-8e3b-e426e52c800e",
},
},
},
Data: sData,
Type: "kubernetes.io/rook",
}

storageCluster = &ocsv1.StorageCluster{
ObjectMeta: metav1.ObjectMeta{
Name: "ocs-storagecluster",
Namespace: "openshift-storage",
UID: "12345678-1234-1234-1234-123456789012",
},
}

cephCluster = &rookv1.CephCluster{
ObjectMeta: metav1.ObjectMeta{
Name: "ocs-storagecluster-cephcluster",
Namespace: "openshift-storage",
OwnerReferences: []metav1.OwnerReference{
{
APIVersion: "ocs.openshift.io/v1",
Kind: "StorageCluster",
Name: "ocs-storagecluster",
UID: "12345678-1234-1234-1234-123456789012",
},
},
},
Spec: rookv1.ClusterSpec{},
Status: rookv1.ClusterStatus{},
}
hubClusterSecret = &corev1.Secret{
ObjectMeta: metav1.ObjectMeta{
Name: utils.CreateUniqueSecretName(spokeClusterName, managedClusterSecret.Namespace, storageCluster.Name),
Namespace: spokeClusterName,
Labels: map[string]string{
utils.SecretLabelTypeKey: string(utils.SourceLabel),
},
},
Data: sData,
Type: "kubernetes.io/rook",
}
)

func TestBlueSecretReconciler_Reconcile(t *testing.T) {
ctx := context.TODO()
scheme := runtime.NewScheme()
_ = corev1.AddToScheme(scheme)

Check failure on line 86 in addons/blue_secret_controller_test.go

View workflow job for this annotation

GitHub Actions / Go 1.21 Lint

Error return value is not checked (errcheck)

Check failure on line 86 in addons/blue_secret_controller_test.go

View workflow job for this annotation

GitHub Actions / Build Operator Image (1.21)

Error return value is not checked (errcheck)
_ = ocsv1.AddToScheme(scheme)

Check failure on line 87 in addons/blue_secret_controller_test.go

View workflow job for this annotation

GitHub Actions / Go 1.21 Lint

Error return value is not checked (errcheck)

Check failure on line 87 in addons/blue_secret_controller_test.go

View workflow job for this annotation

GitHub Actions / Build Operator Image (1.21)

Error return value is not checked (errcheck)
_ = rookv1.AddToScheme(scheme)

Check failure on line 88 in addons/blue_secret_controller_test.go

View workflow job for this annotation

GitHub Actions / Go 1.21 Lint

Error return value is not checked (errcheck)

Check failure on line 88 in addons/blue_secret_controller_test.go

View workflow job for this annotation

GitHub Actions / Build Operator Image (1.21)

Error return value is not checked (errcheck)

// Create fake clients
fakeHubClient := fake.NewClientBuilder().WithScheme(scheme).WithObjects().Build()
fakeSpokeClient := fake.NewClientBuilder().WithScheme(scheme).WithObjects(managedClusterSecret, storageCluster, cephCluster).Build()

logger := utils.GetLogger(utils.GetZapLogger(true))
reconciler := &BlueSecretReconciler{
HubClient: fakeHubClient,
SpokeClient: fakeSpokeClient,
SpokeClusterName: "test-cluster",
Logger: logger,
}

req := ctrl.Request{
NamespacedName: types.NamespacedName{
Name: managedClusterSecret.Name,
Namespace: managedClusterSecret.Namespace,
},
}

// Test cases
tests := []struct {
name string
req ctrl.Request
wantErr bool
}{
{
name: "Reconcile BlueSecret successfully",
req: req,
wantErr: false,
},
}

for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
_, err := reconciler.Reconcile(ctx, tt.req)
if (err != nil) != tt.wantErr {
t.Errorf("Reconcile() error = %v, wantErr %v", err, tt.wantErr)
}

reconciledSecret := &corev1.Secret{}
err = fakeHubClient.Get(ctx, types.NamespacedName{
Name: hubClusterSecret.Name,
Namespace: hubClusterSecret.Namespace,
}, reconciledSecret)
if err != nil {
t.Errorf("Fetching the secret on hub failed %v", err)
}
if reconciledSecret.Labels[utils.SecretLabelTypeKey] != string(utils.SourceLabel) {
t.Errorf("expected label %s to be %s", utils.SecretLabelTypeKey, string(utils.SourceLabel))
}

})
}
}
149 changes: 149 additions & 0 deletions addons/green_secret_controller_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,149 @@
package addons

import (
"context"
"encoding/json"
"testing"

ocsv1 "github.com/red-hat-storage/ocs-operator/api/v1"
"github.com/red-hat-storage/odf-multicluster-orchestrator/addons/setup"
"github.com/red-hat-storage/odf-multicluster-orchestrator/controllers/utils"
corev1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/types"
ctrl "sigs.k8s.io/controller-runtime"
"sigs.k8s.io/controller-runtime/pkg/client/fake"
)

var (
greenSecretName = "d8433b8cb5b6d99c4d785ebd6082efd19cad50c"
greenSecretNamespace = "local-cluster"
greenSecretData = map[string][]byte{
"namespace": []byte("openshift-storage"),
"secret-origin": []byte("rook"),
"storage-cluster-name": []byte("ocs-storagecluster"),
}

secretDataContent = map[string]string{
"cluster": "b2NzLXN0b3JhZ2VjbHVzdGVyLWNlcGhjbHVzdGVy",
"token": "ZXlKbWMybGtJam9pTjJFelpEWmlPREV0WVRVMVpDMDBOR1psTFRnMFpEQXRORFpqTmpkalpETTVOV05oSWl3aVkyeHBaVzUwWDJsa0lqb2ljbUprTFcxcGNuSnZjaTF3WldWeUlpd2lhMlY1SWpvaVFWRkJXRmRaT1cxcU56STJTMmhCUVdWWFMyWXdaMkpSWjBkQlpVbDNUR3RJVmtaaU5HYzlQU0lzSW0xdmJsOW9iM04wSWpvaU1UY3lMak14TGpFek1TNHhPRE02TXpNd01Dd3hOekl1TXpFdU1UWTNMakUwTXpvek16QXdMREUzTWk0ek1TNDFPUzR4TlRFNk16TXdNQ0lzSW01aGJXVnpjR0ZqWlNJNkltOXdaVzV6YUdsbWRDMXpkRzl5WVdkbEluMD0=",
}

encodedSecretData, _ = json.Marshal(secretDataContent)

Check failure on line 33 in addons/green_secret_controller_test.go

View workflow job for this annotation

GitHub Actions / Go 1.21 Lint

Error return value of `json.Marshal` is not checked (errcheck)

Check failure on line 33 in addons/green_secret_controller_test.go

View workflow job for this annotation

GitHub Actions / Build Operator Image (1.21)

Error return value of `json.Marshal` is not checked (errcheck)

greenSecretOnHub = &corev1.Secret{
ObjectMeta: metav1.ObjectMeta{
Name: greenSecretName,
Namespace: greenSecretNamespace,
Labels: map[string]string{
utils.SecretLabelTypeKey: string(utils.DestinationLabel),
},
},
Data: map[string][]byte{
"namespace": greenSecretData["namespace"],
"secret-data": encodedSecretData,
"secret-origin": greenSecretData["secret-origin"],
"storage-cluster-name": greenSecretData["storage-cluster-name"],
},
Type: corev1.SecretTypeOpaque,
}

storageClusterToUpdate = &ocsv1.StorageCluster{
ObjectMeta: metav1.ObjectMeta{
Name: "ocs-storagecluster",
Namespace: "openshift-storage",
},
Spec: ocsv1.StorageClusterSpec{
Mirroring: ocsv1.MirroringSpec{
PeerSecretNames: []string{},
},
},
}

syncedGreenSecret = &corev1.Secret{
ObjectMeta: metav1.ObjectMeta{
Name: greenSecretName,
Namespace: "openshift-storage",
Labels: map[string]string{
utils.CreatedByLabelKey: setup.TokenExchangeName,
},
},
Data: map[string][]byte{},
}
)

func TestGreenSecretReconciler_Reconcile(t *testing.T) {
ctx := context.TODO()
scheme := runtime.NewScheme()
_ = corev1.AddToScheme(scheme)
_ = ocsv1.AddToScheme(scheme)

fakeHubClient := fake.NewClientBuilder().WithScheme(scheme).WithObjects(greenSecretOnHub).Build()
fakeSpokeClient := fake.NewClientBuilder().WithScheme(scheme).WithObjects(storageClusterToUpdate).Build()

logger := utils.GetLogger(utils.GetZapLogger(true))
reconciler := &GreenSecretReconciler{
HubClient: fakeHubClient,
SpokeClient: fakeSpokeClient,
Logger: logger,
}

req := ctrl.Request{
NamespacedName: types.NamespacedName{
Name: greenSecretOnHub.Name,
Namespace: greenSecretOnHub.Namespace,
},
}

// Test cases
tests := []struct {
name string
req ctrl.Request

wantErr bool
}{
{
name: "Reconcile GreenSecret successfully",
req: req,

wantErr: false,
},
}

for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
_, err := reconciler.Reconcile(ctx, tt.req)
if (err != nil) != tt.wantErr {
t.Errorf("Reconcile() error = %v, wantErr %v", err, tt.wantErr)
}

if tt.name == "Reconcile GreenSecret successfully" {
reconciledSecret := &corev1.Secret{}
err = fakeSpokeClient.Get(ctx, types.NamespacedName{
Name: syncedGreenSecret.Name,
Namespace: syncedGreenSecret.Namespace,
}, reconciledSecret)
if err != nil {
t.Errorf("Fetching the secret on spoke cluster failed %v", err)
}
if reconciledSecret.Labels[utils.CreatedByLabelKey] != setup.TokenExchangeName {
t.Errorf("expected label %s to be %s", utils.CreatedByLabelKey, setup.TokenExchangeName)
}

// Verify storage cluster update
updatedStorageCluster := &ocsv1.StorageCluster{}
err = fakeSpokeClient.Get(ctx, types.NamespacedName{
Name: storageClusterToUpdate.Name,
Namespace: storageClusterToUpdate.Namespace,
}, updatedStorageCluster)
if err != nil {
t.Errorf("Fetching the storage cluster failed %v", err)
}
if !utils.ContainsString(updatedStorageCluster.Spec.Mirroring.PeerSecretNames, syncedGreenSecret.Name) {
t.Errorf("expected storage cluster to be updated with secret name %s", syncedGreenSecret.Name)
}
}
})
}
}
Loading

0 comments on commit e2d1abe

Please sign in to comment.