|
| 1 | +package controller_test |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + "errors" |
| 6 | + "testing" |
| 7 | + |
| 8 | + "github.com/openmfp/kubernetes-graphql-gateway/gateway/resolver/mocks" |
| 9 | + "github.com/openmfp/kubernetes-graphql-gateway/listener/apischema" |
| 10 | + "github.com/openmfp/kubernetes-graphql-gateway/listener/controller" |
| 11 | + workspacefileMocks "github.com/openmfp/kubernetes-graphql-gateway/listener/workspacefile/mocks" |
| 12 | + |
| 13 | + "github.com/openmfp/golang-commons/logger/testlogger" |
| 14 | + "github.com/stretchr/testify/assert" |
| 15 | + "github.com/stretchr/testify/mock" |
| 16 | + apierrors "k8s.io/apimachinery/pkg/api/errors" |
| 17 | + "k8s.io/apimachinery/pkg/runtime/schema" |
| 18 | + "sigs.k8s.io/controller-runtime/pkg/client" |
| 19 | + "sigs.k8s.io/controller-runtime/pkg/reconcile" |
| 20 | +) |
| 21 | + |
| 22 | +// TestCRDReconciler tests the CRDReconciler's Reconcile method. |
| 23 | +// It checks if the method handles different scenarios correctly, including |
| 24 | +// errors when getting the CRD and reading the JSON schema. |
| 25 | +func TestCRDReconciler(t *testing.T) { |
| 26 | + log := testlogger.New().HideLogOutput().Logger |
| 27 | + type scenario struct { |
| 28 | + name string |
| 29 | + getErr error |
| 30 | + readErr error |
| 31 | + wantErr error |
| 32 | + } |
| 33 | + tests := []scenario{ |
| 34 | + { |
| 35 | + name: "get error", |
| 36 | + getErr: errors.New("get-error"), |
| 37 | + readErr: nil, |
| 38 | + wantErr: controller.ErrGetReconciledObj, |
| 39 | + }, |
| 40 | + { |
| 41 | + name: "not found read error", |
| 42 | + getErr: apierrors.NewNotFound(schema.GroupResource{Group: "", Resource: "crds"}, "my-crd"), |
| 43 | + readErr: errors.New("read-error"), |
| 44 | + wantErr: controller.ErrReadJSON, |
| 45 | + }, |
| 46 | + } |
| 47 | + |
| 48 | + for _, tc := range tests { |
| 49 | + t.Run(tc.name, func(t *testing.T) { |
| 50 | + ioHandler := workspacefileMocks.NewMockIOHandler(t) |
| 51 | + fakeClient := mocks.NewMockClient(t) |
| 52 | + crdResolver := &apischema.CRDResolver{} |
| 53 | + |
| 54 | + r := controller.NewCRDReconciler( |
| 55 | + "cluster1", |
| 56 | + fakeClient, |
| 57 | + crdResolver, |
| 58 | + ioHandler, |
| 59 | + log, |
| 60 | + ) |
| 61 | + |
| 62 | + req := reconcile.Request{NamespacedName: client.ObjectKey{Name: "my-crd"}} |
| 63 | + fakeClient.EXPECT().Get( |
| 64 | + mock.Anything, |
| 65 | + req.NamespacedName, |
| 66 | + mock.Anything, |
| 67 | + ).Return(tc.getErr) |
| 68 | + |
| 69 | + if apierrors.IsNotFound(tc.getErr) { |
| 70 | + ioHandler.EXPECT().Read("cluster1").Return(nil, tc.readErr) |
| 71 | + } |
| 72 | + |
| 73 | + _, err := r.Reconcile(context.Background(), req) |
| 74 | + if tc.wantErr != nil { |
| 75 | + assert.Error(t, err) |
| 76 | + assert.ErrorIs(t, err, tc.wantErr) |
| 77 | + } else { |
| 78 | + assert.NoError(t, err) |
| 79 | + } |
| 80 | + }) |
| 81 | + } |
| 82 | +} |
0 commit comments