diff --git a/pkg/apiserver/server.go b/pkg/apiserver/server.go index 7cbf6aaf10..962f40ef5f 100644 --- a/pkg/apiserver/server.go +++ b/pkg/apiserver/server.go @@ -157,7 +157,7 @@ func Start(params *APIServerParams) { loggingRouter := r.NewRoute().Subrouter() loggingRouter.Use(handlers.LoggingMiddleware) - handler := &handlers.Handler{} + handler := handlers.NewHandler() /********************************************************************** * Unauthenticated routes diff --git a/pkg/handlers/handlers.go b/pkg/handlers/handlers.go index 0f368a594a..fa2c7fb08c 100644 --- a/pkg/handlers/handlers.go +++ b/pkg/handlers/handlers.go @@ -6,6 +6,7 @@ import ( "github.com/gorilla/mux" "github.com/gorilla/websocket" + "github.com/replicatedhq/kots/pkg/handlers/kubeclient" "github.com/replicatedhq/kots/pkg/logger" "github.com/replicatedhq/kots/pkg/policy" "github.com/replicatedhq/kots/pkg/store" @@ -20,6 +21,15 @@ import ( var _ KOTSHandler = (*Handler)(nil) type Handler struct { + // KubeClientBuilder is used to get a kube client. It is useful to mock the client in testing scenarios. + kubeclient.KubeClientBuilder +} + +// NewHandler returns a new default Handler +func NewHandler() *Handler { + return &Handler{ + KubeClientBuilder: &kubeclient.Builder{}, + } } func init() { diff --git a/pkg/handlers/kubeclient/kubeclient.go b/pkg/handlers/kubeclient/kubeclient.go new file mode 100644 index 0000000000..8a52cda8ad --- /dev/null +++ b/pkg/handlers/kubeclient/kubeclient.go @@ -0,0 +1,35 @@ +package kubeclient + +import ( + "context" + + "github.com/replicatedhq/kots/pkg/k8sutil" + kbclient "sigs.k8s.io/controller-runtime/pkg/client" +) + +var _ KubeClientBuilder = (*Builder)(nil) +var _ KubeClientBuilder = (*MockBuilder)(nil) + +// KubeClientBuilder interface is used as an abstraction to get a kube client. Useful to mock the client in tests. +type KubeClientBuilder interface { + GetKubeClient(ctx context.Context) (kbclient.Client, error) +} + +// Builder is the default implementation of KubeClientBuilder. It returns a regular kube client. +type Builder struct{} + +// GetKubeClient returns a regular kube client. +func (b *Builder) GetKubeClient(ctx context.Context) (kbclient.Client, error) { + return k8sutil.GetKubeClient(ctx) +} + +// MockBuilder is a mock implementation of KubeClientBuilder. It returns the client that was set in the struct allowing +// you to set a fakeClient for example. +type MockBuilder struct { + client kbclient.Client +} + +// GetKubeClient returns the client that was set in the struct. +func (b *MockBuilder) GetKubeClient(ctx context.Context) (kbclient.Client, error) { + return b.client, nil +}