From 08d651fdabee9a2beec77dacb2558cff149238a6 Mon Sep 17 00:00:00 2001 From: Joshua Duffney Date: Tue, 13 Aug 2024 11:36:06 -0500 Subject: [PATCH] test: improve refresher test coverage --- .../keymanagementprovider_controller_test.go | 90 +++-- .../keymanagementprovider_controller_test.go | 91 ++++-- .../refresh/kubeRefreshNamedspaced_test.go | 308 ++++++++---------- .../refresh/kubeRefresh_test.go | 296 ++++++++--------- 4 files changed, 407 insertions(+), 378 deletions(-) diff --git a/pkg/controllers/clusterresource/keymanagementprovider_controller_test.go b/pkg/controllers/clusterresource/keymanagementprovider_controller_test.go index 45292aa932..d4129e2c6e 100644 --- a/pkg/controllers/clusterresource/keymanagementprovider_controller_test.go +++ b/pkg/controllers/clusterresource/keymanagementprovider_controller_test.go @@ -18,6 +18,7 @@ package clusterresource import ( "context" "errors" + "reflect" "testing" "github.com/ratify-project/ratify/pkg/keymanagementprovider/refresh" @@ -28,26 +29,34 @@ import ( "sigs.k8s.io/controller-runtime/pkg/client/fake" ) -func TestKeyManagementProviderReconciler_Reconcile(t *testing.T) { +func TestKeyManagementProviderReconciler_ReconcileWithConfig(t *testing.T) { tests := []struct { - name string - refresherType string - expectedError bool + name string + refresherType string + createConfigError bool + refreshError bool + expectedError bool }{ { - name: "Successful Reconcile", - refresherType: "mockRefresher", - expectedError: false, + name: "Successful Reconcile", + refresherType: "mockRefresher", + createConfigError: false, + refreshError: false, + expectedError: false, }, { - name: "Refresher Error", - refresherType: "mockRefresher", - expectedError: true, + name: "Refresher Error", + refresherType: "mockRefresher", + createConfigError: false, + refreshError: true, + expectedError: true, }, { - name: "Invalid Refresher Type", - refresherType: "invalidRefresher", - expectedError: true, + name: "Invalid Refresher Type", + refresherType: "invalidRefresher", + createConfigError: true, + refreshError: false, + expectedError: true, }, } for _, tt := range tests { @@ -67,10 +76,12 @@ func TestKeyManagementProviderReconciler_Reconcile(t *testing.T) { } refresherConfig := map[string]interface{}{ - "type": tt.refresherType, - "client": client, - "request": req, - "shouldError": tt.expectedError, + "type": tt.refresherType, + "client": client, + "request": req, + "createConfigError": tt.createConfigError, + "refreshError": tt.refreshError, + "shouldError": tt.expectedError, } _, err := r.ReconcileWithConfig(context.TODO(), refresherConfig) @@ -83,14 +94,45 @@ func TestKeyManagementProviderReconciler_Reconcile(t *testing.T) { }) } } +func TestKeyManagementProviderReconciler_Reconcile(t *testing.T) { + req := ctrl.Request{ + NamespacedName: client.ObjectKey{ + Name: "fake-name", + Namespace: "fake-namespace", + }, + } + + // Create a fake client and scheme + scheme, _ := test.CreateScheme() + client := fake.NewClientBuilder().WithScheme(scheme).Build() + + r := &KeyManagementProviderReconciler{ + Client: client, + Scheme: runtime.NewScheme(), + } + + // Call the Reconcile method + result, err := r.Reconcile(context.TODO(), req) + if err != nil { + t.Errorf("Unexpected error: %v", err) + } + + // Check the result + expectedResult := ctrl.Result{} + if !reflect.DeepEqual(result, expectedResult) { + t.Errorf("Expected result %v, got %v", expectedResult, result) + } +} type MockRefresher struct { - Results ctrl.Result - ShouldError bool + Results ctrl.Result + CreateConfigError bool + RefreshError bool + ShouldError bool } func (mr *MockRefresher) Refresh(_ context.Context) error { - if mr.ShouldError { + if mr.RefreshError { return errors.New("refresh error") } return nil @@ -101,12 +143,14 @@ func (mr *MockRefresher) GetResult() interface{} { } func (mr *MockRefresher) Create(config map[string]interface{}) (refresh.Refresher, error) { - shouldError := config["shouldError"].(bool) - if shouldError { + createConfigError := config["createConfigError"].(bool) + refreshError := config["refreshError"].(bool) + if createConfigError { return nil, errors.New("create error") } return &MockRefresher{ - ShouldError: shouldError, + CreateConfigError: createConfigError, + RefreshError: refreshError, }, nil } diff --git a/pkg/controllers/namespaceresource/keymanagementprovider_controller_test.go b/pkg/controllers/namespaceresource/keymanagementprovider_controller_test.go index 42f85c72f5..7e4717a8e6 100644 --- a/pkg/controllers/namespaceresource/keymanagementprovider_controller_test.go +++ b/pkg/controllers/namespaceresource/keymanagementprovider_controller_test.go @@ -18,6 +18,7 @@ package namespaceresource import ( "context" "errors" + "reflect" "testing" "github.com/ratify-project/ratify/pkg/keymanagementprovider/refresh" @@ -28,26 +29,34 @@ import ( "sigs.k8s.io/controller-runtime/pkg/client/fake" ) -func TestKeyManagementProviderReconciler_Reconcile(t *testing.T) { +func TestKeyManagementProviderReconciler_ReconcileWithConfig(t *testing.T) { tests := []struct { - name string - refresherType string - expectedError bool + name string + refresherType string + createConfigError bool + refreshError bool + expectedError bool }{ { - name: "Successful Reconcile", - refresherType: "mockRefresher", - expectedError: false, + name: "Successful Reconcile", + refresherType: "mockRefresher", + createConfigError: false, + refreshError: false, + expectedError: false, }, { - name: "Refresher Error", - refresherType: "mockRefresher", - expectedError: true, + name: "Refresher Error", + refresherType: "mockRefresher", + createConfigError: false, + refreshError: true, + expectedError: true, }, { - name: "Invalid Refresher Type", - refresherType: "invalidRefresher", - expectedError: true, + name: "Invalid Refresher Type", + refresherType: "invalidRefresher", + createConfigError: true, + refreshError: false, + expectedError: true, }, } for _, tt := range tests { @@ -67,10 +76,12 @@ func TestKeyManagementProviderReconciler_Reconcile(t *testing.T) { } refresherConfig := map[string]interface{}{ - "type": tt.refresherType, - "client": client, - "request": req, - "shouldError": tt.expectedError, + "type": tt.refresherType, + "client": client, + "request": req, + "createConfigError": tt.createConfigError, + "refreshError": tt.refreshError, + "shouldError": tt.expectedError, } _, err := r.ReconcileWithConfig(context.TODO(), refresherConfig) @@ -84,13 +95,45 @@ func TestKeyManagementProviderReconciler_Reconcile(t *testing.T) { } } +func TestKeyManagementProviderReconciler_Reconcile(t *testing.T) { + req := ctrl.Request{ + NamespacedName: client.ObjectKey{ + Name: "fake-name", + Namespace: "fake-namespace", + }, + } + + // Create a fake client and scheme + scheme, _ := test.CreateScheme() + client := fake.NewClientBuilder().WithScheme(scheme).Build() + + r := &KeyManagementProviderReconciler{ + Client: client, + Scheme: runtime.NewScheme(), + } + + // Call the Reconcile method + result, err := r.Reconcile(context.TODO(), req) + if err != nil { + t.Errorf("Unexpected error: %v", err) + } + + // Check the result + expectedResult := ctrl.Result{} + if !reflect.DeepEqual(result, expectedResult) { + t.Errorf("Expected result %v, got %v", expectedResult, result) + } +} + type MockRefresher struct { - Results ctrl.Result - ShouldError bool + Results ctrl.Result + CreateConfigError bool + RefreshError bool + ShouldError bool } func (mr *MockRefresher) Refresh(_ context.Context) error { - if mr.ShouldError { + if mr.RefreshError { return errors.New("refresh error") } return nil @@ -101,12 +144,14 @@ func (mr *MockRefresher) GetResult() interface{} { } func (mr *MockRefresher) Create(config map[string]interface{}) (refresh.Refresher, error) { - shouldError := config["shouldError"].(bool) - if shouldError { + createConfigError := config["shouldError"].(bool) + refreshError := config["refreshError"].(bool) + if createConfigError { return nil, errors.New("create error") } return &MockRefresher{ - ShouldError: shouldError, + CreateConfigError: createConfigError, + RefreshError: refreshError, }, nil } diff --git a/pkg/keymanagementprovider/refresh/kubeRefreshNamedspaced_test.go b/pkg/keymanagementprovider/refresh/kubeRefreshNamedspaced_test.go index ca8691018b..884d94fe3d 100644 --- a/pkg/keymanagementprovider/refresh/kubeRefreshNamedspaced_test.go +++ b/pkg/keymanagementprovider/refresh/kubeRefreshNamedspaced_test.go @@ -18,6 +18,7 @@ package refresh import ( "context" "fmt" + "reflect" "testing" "time" @@ -33,168 +34,24 @@ import ( "sigs.k8s.io/controller-runtime/pkg/client/fake" ) -func TestKubeRefresherNamespaced_Refresh_notRefreshable(t *testing.T) { - provider := &configv1beta1.NamespacedKeyManagementProvider{ - ObjectMeta: metav1.ObjectMeta{ - Namespace: "", - Name: "kmpName", - }, - Spec: configv1beta1.NamespacedKeyManagementProviderSpec{ - Type: "inline", - Parameters: runtime.RawExtension{ - Raw: []byte(`{"type": "inline", "contentType": "certificate", "value": "-----BEGIN CERTIFICATE-----\nMIID2jCCAsKgAwIBAgIQXy2VqtlhSkiZKAGhsnkjbDANBgkqhkiG9w0BAQsFADBvMRswGQYDVQQD\nExJyYXRpZnkuZXhhbXBsZS5jb20xDzANBgNVBAsTBk15IE9yZzETMBEGA1UEChMKTXkgQ29tcGFu\neTEQMA4GA1UEBxMHUmVkbW9uZDELMAkGA1UECBMCV0ExCzAJBgNVBAYTAlVTMB4XDTIzMDIwMTIy\nNDUwMFoXDTI0MDIwMTIyNTUwMFowbzEbMBkGA1UEAxMScmF0aWZ5LmV4YW1wbGUuY29tMQ8wDQYD\nVQQLEwZNeSBPcmcxEzARBgNVBAoTCk15IENvbXBhbnkxEDAOBgNVBAcTB1JlZG1vbmQxCzAJBgNV\nBAgTAldBMQswCQYDVQQGEwJVUzCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAL10bM81\npPAyuraORABsOGS8M76Bi7Guwa3JlM1g2D8CuzSfSTaaT6apy9GsccxUvXd5cmiP1ffna5z+EFmc\nizFQh2aq9kWKWXDvKFXzpQuhyqD1HeVlRlF+V0AfZPvGt3VwUUjNycoUU44ctCWmcUQP/KShZev3\n6SOsJ9q7KLjxxQLsUc4mg55eZUThu8mGB8jugtjsnLUYvIWfHhyjVpGrGVrdkDMoMn+u33scOmrt\nsBljvq9WVo4T/VrTDuiOYlAJFMUae2Ptvo0go8XTN3OjLblKeiK4C+jMn9Dk33oGIT9pmX0vrDJV\nX56w/2SejC1AxCPchHaMuhlwMpftBGkCAwEAAaNyMHAwDgYDVR0PAQH/BAQDAgeAMAkGA1UdEwQC\nMAAwEwYDVR0lBAwwCgYIKwYBBQUHAwMwHwYDVR0jBBgwFoAU0eaKkZj+MS9jCp9Dg1zdv3v/aKww\nHQYDVR0OBBYEFNHmipGY/jEvYwqfQ4Nc3b97/2isMA0GCSqGSIb3DQEBCwUAA4IBAQBNDcmSBizF\nmpJlD8EgNcUCy5tz7W3+AAhEbA3vsHP4D/UyV3UgcESx+L+Nye5uDYtTVm3lQejs3erN2BjW+ds+\nXFnpU/pVimd0aYv6mJfOieRILBF4XFomjhrJOLI55oVwLN/AgX6kuC3CJY2NMyJKlTao9oZgpHhs\nLlxB/r0n9JnUoN0Gq93oc1+OLFjPI7gNuPXYOP1N46oKgEmAEmNkP1etFrEjFRgsdIFHksrmlOlD\nIed9RcQ087VLjmuymLgqMTFX34Q3j7XgN2ENwBSnkHotE9CcuGRW+NuiOeJalL8DBmFXXWwHTKLQ\nPp5g6m1yZXylLJaFLKz7tdMmO355\n-----END CERTIFICATE-----\n"}`), - }, - }, - } - request := ctrl.Request{ - NamespacedName: client.ObjectKey{ - Namespace: "", - Name: "kmpName", - }, - } - scheme, _ := test.CreateScheme() - client := fake.NewClientBuilder().WithScheme(scheme).WithObjects(provider).Build() - kr := &KubeRefresherNamespaced{ - Client: client, - Request: request, - } - err := kr.Refresh(context.Background()) - if kr.Result.RequeueAfter != 0 { - t.Fatalf("Unexpected error: %v", err) - } -} - -func TestKubeRefresherNamespaced_Refresh_Disabled(t *testing.T) { - provider := &configv1beta1.NamespacedKeyManagementProvider{ - ObjectMeta: metav1.ObjectMeta{ - Namespace: "", - Name: "kmpName", - }, - Spec: configv1beta1.NamespacedKeyManagementProviderSpec{ - Type: "test-kmp", - RefreshInterval: "", - Parameters: runtime.RawExtension{ - Raw: []byte(`{"vaultURI": "https://yourkeyvault.vault.azure.net/", "certificates": [{"name": "cert1", "version": "1"}], "tenantID": "yourtenantID", "clientID": "yourclientID"}`), - }, - }, - } - request := ctrl.Request{ - NamespacedName: client.ObjectKey{ - Namespace: "", - Name: "kmpName", - }, - } - scheme, _ := test.CreateScheme() - client := fake.NewClientBuilder().WithScheme(scheme).WithObjects(provider).Build() - kr := &KubeRefresherNamespaced{ - Client: client, - Request: request, - } - err := kr.Refresh(context.Background()) - if kr.Result.RequeueAfter != 0 && kr.Result.Requeue == false { - t.Fatalf("Unexpected error: %v", err) - } -} -func TestKubeRefresherNamespaced_Refresh_refreshable(t *testing.T) { - provider := &configv1beta1.NamespacedKeyManagementProvider{ - ObjectMeta: metav1.ObjectMeta{ - Namespace: "", - Name: "kmpName", - }, - Spec: configv1beta1.NamespacedKeyManagementProviderSpec{ - Type: "test-kmp", - RefreshInterval: "1m", - Parameters: runtime.RawExtension{ - Raw: []byte(`{"vaultURI": "https://yourkeyvault.vault.azure.net/", "certificates": [{"name": "cert1", "version": "1"}], "tenantID": "yourtenantID", "clientID": "yourclientID"}`), - }, - }, - } - request := ctrl.Request{ - NamespacedName: client.ObjectKey{ - Namespace: "", - Name: "kmpName", - }, - } - scheme, _ := test.CreateScheme() - client := fake.NewClientBuilder().WithScheme(scheme).WithObjects(provider).Build() - kr := &KubeRefresherNamespaced{ - Client: client, - Request: request, - } - err := kr.Refresh(context.Background()) - duration, _ := time.ParseDuration("1m") - if kr.Result.RequeueAfter != duration { - t.Fatalf("Unexpected error: %v", err) - } -} - -func TestKubeRefresherNamespaced_Refresh_invalidInterval(t *testing.T) { - provider := &configv1beta1.NamespacedKeyManagementProvider{ - ObjectMeta: metav1.ObjectMeta{ - Namespace: "", - Name: "kmpName", - }, - Spec: configv1beta1.NamespacedKeyManagementProviderSpec{ - Type: "test-kmp", - RefreshInterval: "1mm", - Parameters: runtime.RawExtension{ - Raw: []byte(`{"vaultURI": "https://yourkeyvault.vault.azure.net/", "certificates": [{"name": "cert1", "version": "1"}], "tenantID": "yourtenantID", "clientID": "yourclientID"}`), - }, - }, - } - request := ctrl.Request{ - NamespacedName: client.ObjectKey{ - Namespace: "", - Name: "kmpName", - }, - } - scheme, _ := test.CreateScheme() - client := fake.NewClientBuilder().WithScheme(scheme).WithObjects(provider).Build() - kr := &KubeRefresherNamespaced{ - Client: client, - Request: request, - } - err := kr.Refresh(context.Background()) - if err == nil { - t.Fatalf("Expected error but got nil") - } -} - -func TestKubeRefresherNamespaced_Refresh_UnableToFetchKMP(t *testing.T) { - request := ctrl.Request{ - NamespacedName: client.ObjectKey{ - Namespace: "", - Name: "kmpName", - }, - } - client := mocks.TestClient{} - kr := &KubeRefresherNamespaced{ - Client: client, - Request: request, - } - err := kr.Refresh(context.Background()) - if err == nil { - t.Fatalf("Expected error but got nil") - } -} - func TestKubeRefresherNamespaced_Refresh(t *testing.T) { tests := []struct { - name string - provider *configv1beta1.NamespacedKeyManagementProvider - request ctrl.Request - wantErr bool + name string + provider *configv1beta1.NamespacedKeyManagementProvider + request ctrl.Request + mockClient bool + expectedResult ctrl.Result + expectedError bool }{ { - name: "valid params", + name: "Non-refreshable", provider: &configv1beta1.NamespacedKeyManagementProvider{ ObjectMeta: metav1.ObjectMeta{ - Namespace: "testNamespace", + Namespace: "", Name: "kmpName", }, Spec: configv1beta1.NamespacedKeyManagementProviderSpec{ - Type: "inline", - RefreshInterval: "1m", + Type: "inline", Parameters: runtime.RawExtension{ Raw: []byte(`{"type": "inline", "contentType": "certificate", "value": "-----BEGIN CERTIFICATE-----\nMIID2jCCAsKgAwIBAgIQXy2VqtlhSkiZKAGhsnkjbDANBgkqhkiG9w0BAQsFADBvMRswGQYDVQQD\nExJyYXRpZnkuZXhhbXBsZS5jb20xDzANBgNVBAsTBk15IE9yZzETMBEGA1UEChMKTXkgQ29tcGFu\neTEQMA4GA1UEBxMHUmVkbW9uZDELMAkGA1UECBMCV0ExCzAJBgNVBAYTAlVTMB4XDTIzMDIwMTIy\nNDUwMFoXDTI0MDIwMTIyNTUwMFowbzEbMBkGA1UEAxMScmF0aWZ5LmV4YW1wbGUuY29tMQ8wDQYD\nVQQLEwZNeSBPcmcxEzARBgNVBAoTCk15IENvbXBhbnkxEDAOBgNVBAcTB1JlZG1vbmQxCzAJBgNV\nBAgTAldBMQswCQYDVQQGEwJVUzCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAL10bM81\npPAyuraORABsOGS8M76Bi7Guwa3JlM1g2D8CuzSfSTaaT6apy9GsccxUvXd5cmiP1ffna5z+EFmc\nizFQh2aq9kWKWXDvKFXzpQuhyqD1HeVlRlF+V0AfZPvGt3VwUUjNycoUU44ctCWmcUQP/KShZev3\n6SOsJ9q7KLjxxQLsUc4mg55eZUThu8mGB8jugtjsnLUYvIWfHhyjVpGrGVrdkDMoMn+u33scOmrt\nsBljvq9WVo4T/VrTDuiOYlAJFMUae2Ptvo0go8XTN3OjLblKeiK4C+jMn9Dk33oGIT9pmX0vrDJV\nX56w/2SejC1AxCPchHaMuhlwMpftBGkCAwEAAaNyMHAwDgYDVR0PAQH/BAQDAgeAMAkGA1UdEwQC\nMAAwEwYDVR0lBAwwCgYIKwYBBQUHAwMwHwYDVR0jBBgwFoAU0eaKkZj+MS9jCp9Dg1zdv3v/aKww\nHQYDVR0OBBYEFNHmipGY/jEvYwqfQ4Nc3b97/2isMA0GCSqGSIb3DQEBCwUAA4IBAQBNDcmSBizF\nmpJlD8EgNcUCy5tz7W3+AAhEbA3vsHP4D/UyV3UgcESx+L+Nye5uDYtTVm3lQejs3erN2BjW+ds+\nXFnpU/pVimd0aYv6mJfOieRILBF4XFomjhrJOLI55oVwLN/AgX6kuC3CJY2NMyJKlTao9oZgpHhs\nLlxB/r0n9JnUoN0Gq93oc1+OLFjPI7gNuPXYOP1N46oKgEmAEmNkP1etFrEjFRgsdIFHksrmlOlD\nIed9RcQ087VLjmuymLgqMTFX34Q3j7XgN2ENwBSnkHotE9CcuGRW+NuiOeJalL8DBmFXXWwHTKLQ\nPp5g6m1yZXylLJaFLKz7tdMmO355\n-----END CERTIFICATE-----\n"}`), }, @@ -202,60 +59,173 @@ func TestKubeRefresherNamespaced_Refresh(t *testing.T) { }, request: ctrl.Request{ NamespacedName: client.ObjectKey{ - Namespace: "testNamespace", + Namespace: "", Name: "kmpName", }, }, - wantErr: false, + expectedResult: ctrl.Result{}, + expectedError: false, }, { - name: "nonexistent KMP", + name: "Disabled", provider: &configv1beta1.NamespacedKeyManagementProvider{ ObjectMeta: metav1.ObjectMeta{ - Namespace: "testNamespace", + Namespace: "", Name: "kmpName", }, Spec: configv1beta1.NamespacedKeyManagementProviderSpec{ - Type: "inline", + Type: "test-kmp", + RefreshInterval: "", + Parameters: runtime.RawExtension{ + Raw: []byte(`{"vaultURI": "https://yourkeyvault.vault.azure.net/", "certificates": [{"name": "cert1", "version": "1"}], "tenantID": "yourtenantID", "clientID": "yourclientID"}`), + }, }, }, request: ctrl.Request{ NamespacedName: client.ObjectKey{ - Name: "nonexistent", + Namespace: "", + Name: "kmpName", }, }, - wantErr: false, + expectedResult: ctrl.Result{}, + expectedError: false, }, { - name: "invalid params", + name: "Refreshable", provider: &configv1beta1.NamespacedKeyManagementProvider{ ObjectMeta: metav1.ObjectMeta{ - Namespace: "testNamespace", + Namespace: "", Name: "kmpName", }, Spec: configv1beta1.NamespacedKeyManagementProviderSpec{ - Type: "inline", + Type: "test-kmp", + RefreshInterval: "1m", + Parameters: runtime.RawExtension{ + Raw: []byte(`{"vaultURI": "https://yourkeyvault.vault.azure.net/", "certificates": [{"name": "cert1", "version": "1"}], "tenantID": "yourtenantID", "clientID": "yourclientID"}`), + }, }, }, request: ctrl.Request{ NamespacedName: client.ObjectKey{ - Namespace: "testNamespace", + Namespace: "", Name: "kmpName", }, }, - wantErr: true, + expectedResult: ctrl.Result{RequeueAfter: time.Minute}, + expectedError: false, + }, + { + name: "Invalid Interval", + provider: &configv1beta1.NamespacedKeyManagementProvider{ + ObjectMeta: metav1.ObjectMeta{ + Namespace: "", + Name: "kmpName", + }, + Spec: configv1beta1.NamespacedKeyManagementProviderSpec{ + Type: "", + RefreshInterval: "1mm", + Parameters: runtime.RawExtension{ + Raw: []byte(`{"vaultURI": "https://yourkeyvault.vault.azure.net/", "certificates": [{"name": "cert1", "version": "1"}], "tenantID": "yourtenantID", "clientID": "yourclientID"}`), + }, + }, + }, + request: ctrl.Request{ + NamespacedName: client.ObjectKey{ + Namespace: "", + Name: "kmpName", + }, + }, + expectedResult: ctrl.Result{}, + expectedError: true, + }, + { + name: "IsNotFound", + provider: &configv1beta1.NamespacedKeyManagementProvider{ + ObjectMeta: metav1.ObjectMeta{ + Namespace: "", + Name: "kmpName", + }, + Spec: configv1beta1.NamespacedKeyManagementProviderSpec{ + Type: "", + RefreshInterval: "", + Parameters: runtime.RawExtension{ + Raw: []byte(`{"vaultURI": "https://yourkeyvault.vault.azure.net/", "certificates": [{"name": "cert1", "version": "1"}], "tenantID": "yourtenantID", "clientID": "yourclientID"}`), + }, + }, + }, + expectedResult: ctrl.Result{}, + expectedError: false, + }, + { + name: "UnableToFetchKMP", + mockClient: true, + expectedError: true, }, } + for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - scheme, _ := test.CreateScheme() - client := fake.NewClientBuilder().WithScheme(scheme).WithObjects(tt.provider).Build() + var client client.Client + + if tt.mockClient { + client = mocks.TestClient{} + } else { + scheme, _ := test.CreateScheme() + client = fake.NewClientBuilder().WithScheme(scheme).WithObjects(tt.provider).Build() + } + kr := &KubeRefresherNamespaced{ Client: client, Request: tt.request, } - if err := kr.Refresh(context.Background()); (err != nil) != tt.wantErr { - t.Errorf("KubeRefresherNamespaced.Refresh() error = %v, wantErr %v", err, tt.wantErr) + err := kr.Refresh(context.Background()) + result := kr.GetResult() + if !reflect.DeepEqual(result, tt.expectedResult) { + t.Fatalf("Expected nil but got %v with error %v", result, err) + } + if tt.expectedError && err == nil { + t.Fatalf("Expected error but got nil") + } + }) + } +} + +func TestKubeRefresherNamespaced_Create(t *testing.T) { + tests := []struct { + name string + config map[string]interface{} + expectedError bool + }{ + { + name: "Success", + config: map[string]interface{}{ + "client": &mocks.TestClient{}, + "request": ctrl.Request{}, + }, + expectedError: false, + }, + { + name: "ClientMissing", + config: map[string]interface{}{ + "request": ctrl.Request{}, + }, + expectedError: true, + }, + { + name: "RequestMissing", + config: map[string]interface{}{ + "client": &mocks.TestClient{}, + }, + expectedError: true, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + kr := &KubeRefresherNamespaced{} + _, err := kr.Create(tt.config) + if tt.expectedError && err == nil { + t.Fatalf("Expected error but got nil") } }) } diff --git a/pkg/keymanagementprovider/refresh/kubeRefresh_test.go b/pkg/keymanagementprovider/refresh/kubeRefresh_test.go index 751626dff8..beb503753b 100644 --- a/pkg/keymanagementprovider/refresh/kubeRefresh_test.go +++ b/pkg/keymanagementprovider/refresh/kubeRefresh_test.go @@ -19,6 +19,7 @@ package refresh import ( "context" "fmt" + "reflect" "testing" "time" @@ -35,161 +36,17 @@ import ( "sigs.k8s.io/controller-runtime/pkg/client/fake" ) -func TestKubeRefresher_Refresh_notRefreshable(t *testing.T) { - provider := &configv1beta1.KeyManagementProvider{ - ObjectMeta: metav1.ObjectMeta{ - Namespace: "", - Name: "kmpName", - }, - Spec: configv1beta1.KeyManagementProviderSpec{ - Type: "inline", - Parameters: runtime.RawExtension{ - Raw: []byte(`{"type": "inline", "contentType": "certificate", "value": "-----BEGIN CERTIFICATE-----\nMIID2jCCAsKgAwIBAgIQXy2VqtlhSkiZKAGhsnkjbDANBgkqhkiG9w0BAQsFADBvMRswGQYDVQQD\nExJyYXRpZnkuZXhhbXBsZS5jb20xDzANBgNVBAsTBk15IE9yZzETMBEGA1UEChMKTXkgQ29tcGFu\neTEQMA4GA1UEBxMHUmVkbW9uZDELMAkGA1UECBMCV0ExCzAJBgNVBAYTAlVTMB4XDTIzMDIwMTIy\nNDUwMFoXDTI0MDIwMTIyNTUwMFowbzEbMBkGA1UEAxMScmF0aWZ5LmV4YW1wbGUuY29tMQ8wDQYD\nVQQLEwZNeSBPcmcxEzARBgNVBAoTCk15IENvbXBhbnkxEDAOBgNVBAcTB1JlZG1vbmQxCzAJBgNV\nBAgTAldBMQswCQYDVQQGEwJVUzCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAL10bM81\npPAyuraORABsOGS8M76Bi7Guwa3JlM1g2D8CuzSfSTaaT6apy9GsccxUvXd5cmiP1ffna5z+EFmc\nizFQh2aq9kWKWXDvKFXzpQuhyqD1HeVlRlF+V0AfZPvGt3VwUUjNycoUU44ctCWmcUQP/KShZev3\n6SOsJ9q7KLjxxQLsUc4mg55eZUThu8mGB8jugtjsnLUYvIWfHhyjVpGrGVrdkDMoMn+u33scOmrt\nsBljvq9WVo4T/VrTDuiOYlAJFMUae2Ptvo0go8XTN3OjLblKeiK4C+jMn9Dk33oGIT9pmX0vrDJV\nX56w/2SejC1AxCPchHaMuhlwMpftBGkCAwEAAaNyMHAwDgYDVR0PAQH/BAQDAgeAMAkGA1UdEwQC\nMAAwEwYDVR0lBAwwCgYIKwYBBQUHAwMwHwYDVR0jBBgwFoAU0eaKkZj+MS9jCp9Dg1zdv3v/aKww\nHQYDVR0OBBYEFNHmipGY/jEvYwqfQ4Nc3b97/2isMA0GCSqGSIb3DQEBCwUAA4IBAQBNDcmSBizF\nmpJlD8EgNcUCy5tz7W3+AAhEbA3vsHP4D/UyV3UgcESx+L+Nye5uDYtTVm3lQejs3erN2BjW+ds+\nXFnpU/pVimd0aYv6mJfOieRILBF4XFomjhrJOLI55oVwLN/AgX6kuC3CJY2NMyJKlTao9oZgpHhs\nLlxB/r0n9JnUoN0Gq93oc1+OLFjPI7gNuPXYOP1N46oKgEmAEmNkP1etFrEjFRgsdIFHksrmlOlD\nIed9RcQ087VLjmuymLgqMTFX34Q3j7XgN2ENwBSnkHotE9CcuGRW+NuiOeJalL8DBmFXXWwHTKLQ\nPp5g6m1yZXylLJaFLKz7tdMmO355\n-----END CERTIFICATE-----\n"}`), - }, - }, - } - request := ctrl.Request{ - NamespacedName: client.ObjectKey{ - Namespace: "", - Name: "kmpName", - }, - } - scheme, _ := test.CreateScheme() - client := fake.NewClientBuilder().WithScheme(scheme).WithObjects(provider).Build() - kr := &KubeRefresher{ - Client: client, - Request: request, - } - err := kr.Refresh(context.Background()) - if kr.Result.RequeueAfter != 0 && kr.Result.Requeue == false { - t.Fatalf("Unexpected error: %v", err) - } -} - -func TestKubeRefresher_Refresh_Disabled(t *testing.T) { - provider := &configv1beta1.KeyManagementProvider{ - ObjectMeta: metav1.ObjectMeta{ - Namespace: "", - Name: "kmpName", - }, - Spec: configv1beta1.KeyManagementProviderSpec{ - Type: "test-kmp", - RefreshInterval: "", - Parameters: runtime.RawExtension{ - Raw: []byte(`{"vaultURI": "https://yourkeyvault.vault.azure.net/", "certificates": [{"name": "cert1", "version": "1"}], "tenantID": "yourtenantID", "clientID": "yourclientID"}`), - }, - }, - } - request := ctrl.Request{ - NamespacedName: client.ObjectKey{ - Namespace: "", - Name: "kmpName", - }, - } - scheme, _ := test.CreateScheme() - client := fake.NewClientBuilder().WithScheme(scheme).WithObjects(provider).Build() - kr := &KubeRefresher{ - Client: client, - Request: request, - } - err := kr.Refresh(context.Background()) - if kr.Result.RequeueAfter != 0 && kr.Result.Requeue == false { - t.Fatalf("Unexpected error: %v", err) - } -} - -func TestKubeRefresher_Refresh_refreshable(t *testing.T) { - provider := &configv1beta1.KeyManagementProvider{ - ObjectMeta: metav1.ObjectMeta{ - Namespace: "", - Name: "kmpName", - }, - Spec: configv1beta1.KeyManagementProviderSpec{ - Type: "test-kmp", - RefreshInterval: "1m", - Parameters: runtime.RawExtension{ - Raw: []byte(`{"vaultURI": "https://yourkeyvault.vault.azure.net/", "certificates": [{"name": "cert1", "version": "1"}], "tenantID": "yourtenantID", "clientID": "yourclientID"}`), - }, - }, - } - request := ctrl.Request{ - NamespacedName: client.ObjectKey{ - Namespace: "", - Name: "kmpName", - }, - } - scheme, _ := test.CreateScheme() - client := fake.NewClientBuilder().WithScheme(scheme).WithObjects(provider).Build() - kr := &KubeRefresher{ - Client: client, - Request: request, - } - err := kr.Refresh(context.Background()) - duration, _ := time.ParseDuration("1m") - if kr.Result.RequeueAfter != duration { - t.Fatalf("Unexpected error: %v", err) - } -} - -func TestKubeRefresher_Refresh_invalidInterval(t *testing.T) { - provider := &configv1beta1.KeyManagementProvider{ - ObjectMeta: metav1.ObjectMeta{ - Namespace: "", - Name: "kmpName", - }, - Spec: configv1beta1.KeyManagementProviderSpec{ - Type: "test-kmp", - RefreshInterval: "1mm", - Parameters: runtime.RawExtension{ - Raw: []byte(`{"vaultURI": "https://yourkeyvault.vault.azure.net/", "certificates": [{"name": "cert1", "version": "1"}], "tenantID": "yourtenantID", "clientID": "yourclientID"}`), - }, - }, - } - request := ctrl.Request{ - NamespacedName: client.ObjectKey{ - Namespace: "", - Name: "kmpName", - }, - } - scheme, _ := test.CreateScheme() - client := fake.NewClientBuilder().WithScheme(scheme).WithObjects(provider).Build() - kr := &KubeRefresher{ - Client: client, - Request: request, - } - err := kr.Refresh(context.Background()) - if err == nil { - t.Fatalf("Expected error but got nil") - } -} - -func TestKubeRefresher_Refresh_UnableToFetchKMP(t *testing.T) { - request := ctrl.Request{ - NamespacedName: client.ObjectKey{ - Namespace: "", - Name: "kmpName", - }, - } - client := mocks.TestClient{} - kr := &KubeRefresher{ - Client: client, - Request: request, - } - err := kr.Refresh(context.Background()) - if err == nil { - t.Fatalf("Expected error but got nil") - } -} - func TestKubeRefresher_Refresh(t *testing.T) { tests := []struct { - name string - provider *configv1beta1.KeyManagementProvider - request ctrl.Request - wantErr bool + name string + provider *configv1beta1.KeyManagementProvider + request ctrl.Request + mockClient bool + expectedResult ctrl.Result + expectedError bool }{ { - name: "valid params", + name: "Non-refreshable", provider: &configv1beta1.KeyManagementProvider{ ObjectMeta: metav1.ObjectMeta{ Namespace: "", @@ -208,35 +65,46 @@ func TestKubeRefresher_Refresh(t *testing.T) { Name: "kmpName", }, }, - wantErr: false, + expectedResult: ctrl.Result{}, + expectedError: false, }, { - name: "nonexistent KMP", + name: "Disabled", provider: &configv1beta1.KeyManagementProvider{ ObjectMeta: metav1.ObjectMeta{ Namespace: "", Name: "kmpName", }, Spec: configv1beta1.KeyManagementProviderSpec{ - Type: "inline", + Type: "test-kmp", + RefreshInterval: "", + Parameters: runtime.RawExtension{ + Raw: []byte(`{"vaultURI": "https://yourkeyvault.vault.azure.net/", "certificates": [{"name": "cert1", "version": "1"}], "tenantID": "yourtenantID", "clientID": "yourclientID"}`), + }, }, }, request: ctrl.Request{ NamespacedName: client.ObjectKey{ - Name: "nonexistent", + Namespace: "", + Name: "kmpName", }, }, - wantErr: false, + expectedResult: ctrl.Result{}, + expectedError: false, }, { - name: "invalid params", + name: "Refreshable", provider: &configv1beta1.KeyManagementProvider{ ObjectMeta: metav1.ObjectMeta{ Namespace: "", Name: "kmpName", }, Spec: configv1beta1.KeyManagementProviderSpec{ - Type: "inline", + Type: "test-kmp", + RefreshInterval: "1m", + Parameters: runtime.RawExtension{ + Raw: []byte(`{"vaultURI": "https://yourkeyvault.vault.azure.net/", "certificates": [{"name": "cert1", "version": "1"}], "tenantID": "yourtenantID", "clientID": "yourclientID"}`), + }, }, }, request: ctrl.Request{ @@ -245,19 +113,121 @@ func TestKubeRefresher_Refresh(t *testing.T) { Name: "kmpName", }, }, - wantErr: true, + expectedResult: ctrl.Result{RequeueAfter: time.Minute}, + expectedError: false, + }, + { + name: "Invalid Interval", + provider: &configv1beta1.KeyManagementProvider{ + ObjectMeta: metav1.ObjectMeta{ + Namespace: "", + Name: "kmpName", + }, + Spec: configv1beta1.KeyManagementProviderSpec{ + Type: "", + RefreshInterval: "1mm", + Parameters: runtime.RawExtension{ + Raw: []byte(`{"vaultURI": "https://yourkeyvault.vault.azure.net/", "certificates": [{"name": "cert1", "version": "1"}], "tenantID": "yourtenantID", "clientID": "yourclientID"}`), + }, + }, + }, + request: ctrl.Request{ + NamespacedName: client.ObjectKey{ + Namespace: "", + Name: "kmpName", + }, + }, + expectedResult: ctrl.Result{}, + expectedError: true, + }, + { + name: "IsNotFound", + provider: &configv1beta1.KeyManagementProvider{ + ObjectMeta: metav1.ObjectMeta{ + Namespace: "", + Name: "kmpName", + }, + Spec: configv1beta1.KeyManagementProviderSpec{ + Type: "", + RefreshInterval: "", + Parameters: runtime.RawExtension{ + Raw: []byte(`{"vaultURI": "https://yourkeyvault.vault.azure.net/", "certificates": [{"name": "cert1", "version": "1"}], "tenantID": "yourtenantID", "clientID": "yourclientID"}`), + }, + }, + }, + expectedResult: ctrl.Result{}, + expectedError: false, + }, + { + name: "UnableToFetchKMP", + mockClient: true, + expectedError: true, }, } + for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - scheme, _ := test.CreateScheme() - client := fake.NewClientBuilder().WithScheme(scheme).WithObjects(tt.provider).Build() + var client client.Client + + if tt.mockClient { + client = mocks.TestClient{} + } else { + scheme, _ := test.CreateScheme() + client = fake.NewClientBuilder().WithScheme(scheme).WithObjects(tt.provider).Build() + } + kr := &KubeRefresher{ Client: client, Request: tt.request, } - if err := kr.Refresh(context.Background()); (err != nil) != tt.wantErr { - t.Errorf("KubeRefresher.Refresh() error = %v, wantErr %v", err, tt.wantErr) + err := kr.Refresh(context.Background()) + result := kr.GetResult() + if !reflect.DeepEqual(result, tt.expectedResult) { + t.Fatalf("Expected nil but got %v with error %v", result, err) + } + if tt.expectedError && err == nil { + t.Fatalf("Expected error but got nil") + } + }) + } +} + +func TestKubeRefresher_Create(t *testing.T) { + tests := []struct { + name string + config map[string]interface{} + expectedError bool + }{ + { + name: "Success", + config: map[string]interface{}{ + "client": &mocks.TestClient{}, + "request": ctrl.Request{}, + }, + expectedError: false, + }, + { + name: "ClientMissing", + config: map[string]interface{}{ + "request": ctrl.Request{}, + }, + expectedError: true, + }, + { + name: "RequestMissing", + config: map[string]interface{}{ + "client": &mocks.TestClient{}, + }, + expectedError: true, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + kr := &KubeRefresher{} + _, err := kr.Create(tt.config) + if tt.expectedError && err == nil { + t.Fatalf("Expected error but got nil") } }) }