Skip to content

Commit

Permalink
chore(test): create a struct and interface to allow kube client mocks…
Browse files Browse the repository at this point in the history
… in handlers
  • Loading branch information
JGAntunes committed Nov 13, 2024
1 parent 0fd7af1 commit bb6a671
Show file tree
Hide file tree
Showing 3 changed files with 46 additions and 1 deletion.
2 changes: 1 addition & 1 deletion pkg/apiserver/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -157,7 +157,7 @@ func Start(params *APIServerParams) {
loggingRouter := r.NewRoute().Subrouter()
loggingRouter.Use(handlers.LoggingMiddleware)

handler := &handlers.Handler{}
handler := handlers.NewHandler()

/**********************************************************************
* Unauthenticated routes
Expand Down
10 changes: 10 additions & 0 deletions pkg/handlers/handlers.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand All @@ -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() {
Expand Down
35 changes: 35 additions & 0 deletions pkg/handlers/kubeclient/kubeclient.go
Original file line number Diff line number Diff line change
@@ -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
}

0 comments on commit bb6a671

Please sign in to comment.