Skip to content

Commit

Permalink
kubescore testing
Browse files Browse the repository at this point in the history
  • Loading branch information
Nithunikzz committed May 28, 2024
1 parent 8f416f4 commit 6dbb948
Show file tree
Hide file tree
Showing 7 changed files with 191 additions and 110 deletions.
3 changes: 1 addition & 2 deletions agent/kubviz/plugins/ketall/ketall_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -187,10 +187,9 @@ func TestGetAllResources(t *testing.T) {
patchPublish := gomonkey.ApplyMethod(
reflect.TypeOf(natsCli),
"Publish",
func(*sdk.NATSClient,string, []byte) error {
func(*sdk.NATSClient, string, []byte) error {
return nil
},

)
defer patchPublish.Reset()

Expand Down
6 changes: 3 additions & 3 deletions agent/kubviz/plugins/kubescore/kube_score.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ import (

var ClusterName string = os.Getenv("CLUSTER_NAME")

func RunKubeScore(clientset *kubernetes.Clientset, natsCli *sdk.NATSClient) error {
func RunKubeScore(clientset *kubernetes.Clientset, natsCli sdk.NATSClientInterface) error {
nsList, err := clientset.CoreV1().
Namespaces().
List(context.Background(), metav1.ListOptions{})
Expand All @@ -38,7 +38,7 @@ func RunKubeScore(clientset *kubernetes.Clientset, natsCli *sdk.NATSClient) erro
return nil
}

func publish(ns string, natsCli *sdk.NATSClient) error {
func publish(ns string, natsCli sdk.NATSClientInterface) error {
var report []json_v2.ScoredObject
cmd := "kubectl api-resources --verbs=list --namespaced -o name | xargs -n1 -I{} sh -c \"kubectl get {} -n " + ns + " -oyaml && echo ---\" | kube-score score - -o json"
log.Printf("Command: %#v,", cmd)
Expand All @@ -62,7 +62,7 @@ func publish(ns string, natsCli *sdk.NATSClient) error {
return nil
}

func publishKubescoreMetrics(report []json_v2.ScoredObject, natsCli *sdk.NATSClient) error {
func publishKubescoreMetrics(report []json_v2.ScoredObject, natsCli sdk.NATSClientInterface) error {

ctx := context.Background()
tracer := otel.Tracer("kubescore")
Expand Down
81 changes: 46 additions & 35 deletions agent/kubviz/plugins/kubescore/kubescore_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,14 @@ import (
"errors"
"testing"

"bou.ke/monkey"
"github.com/agiledragon/gomonkey"
"github.com/golang/mock/gomock"

//"github.com/intelops/kubviz/mocks"

"github.com/intelops/kubviz/constants"
"github.com/intelops/kubviz/mocks"
"github.com/intelops/kubviz/pkg/nats/sdk"
mocks "github.com/intelops/kubviz/pkg/nats/sdk/mocks"
"github.com/stretchr/testify/assert"
"github.com/zegl/kube-score/renderer/json_v2"
)
Expand All @@ -29,14 +33,14 @@ func TestPublishKubescoreMetrics(t *testing.T) {
ctrl := gomock.NewController(t)
defer ctrl.Finish()

js := mocks.NewMockJetStreamContextInterface(ctrl)
js := mocks.NewMockNATSClientInterface(ctrl)

// Test case: Testing successful publishing of kube-score metrics
t.Run("Successful publishing", func(t *testing.T) {

// Set the mock expectation for Publish
js.EXPECT().Publish(constants.KUBESCORE_SUBJECT, gomock.Any()).Return(nil, nil)

js.EXPECT().Publish(constants.KUBESCORE_SUBJECT, gomock.Any()).Return(nil)
//natsCli := &sdk.NATSClient{}
// Call the function under test
err := publishKubescoreMetrics(report, js)

Expand All @@ -45,23 +49,24 @@ func TestPublishKubescoreMetrics(t *testing.T) {
})
// Test case: Error handling for Publish failure
t.Run("Error handling for Publish failure", func(t *testing.T) {
js.EXPECT().Publish(constants.KUBESCORE_SUBJECT, gomock.Any()).Return(nil, errors.New("publish error"))
js.EXPECT().Publish(constants.KUBESCORE_SUBJECT, gomock.Any()).Return(errors.New("publish error"))
//natsCli := &sdk.NATSClient{}
err := publishKubescoreMetrics(report, js)
assert.Error(t, err)
})

// Test case: Nil input report
t.Run("Nil input report", func(t *testing.T) {
js.EXPECT().Publish(constants.KUBESCORE_SUBJECT, gomock.Any()).Return(nil, errors.New("publish error"))

js.EXPECT().Publish(constants.KUBESCORE_SUBJECT, gomock.Any()).Return(errors.New("publish error"))
//natsCli := &sdk.NATSClient{}
err := publishKubescoreMetrics(nil, js)
assert.Error(t, err) // Assuming this is the desired behavior for nil input
})

// Test case: Empty report
t.Run("Empty report", func(t *testing.T) {
js.EXPECT().Publish(constants.KUBESCORE_SUBJECT, gomock.Any()).Return(nil, errors.New("publish error"))

js.EXPECT().Publish(constants.KUBESCORE_SUBJECT, gomock.Any()).Return(errors.New("publish error"))
//natsCli := &sdk.NATSClient{}
err := publishKubescoreMetrics([]json_v2.ScoredObject{}, js)
assert.Error(t, err) // Assuming this is the desired behavior for an empty report
})
Expand All @@ -76,55 +81,61 @@ func TestExecuteCommand(t *testing.T) {
assert.Equal(t, "Hello, World!\n", output)
})

t.Run("Command execution error", func(t *testing.T) {
command := "non_existing_command"
_, err := ExecuteCommand(command)

assert.Error(t, err)
})

}

func TestPublish(t *testing.T) {
// Mock the ExecuteCommand function
var mockOutput = []byte(`[{"ObjectName":"test-object","TypeMeta":{"Kind":"Pod"},"ObjectMeta":{"Name":"test-pod"},"Checks":[{"ID":"check-id","Severity":"info","Message":"test message"}],"FileName":"test-file","FileRow":1}]`)
monkey.Patch(ExecuteCommand, func(command string) (string, error) {
gomonkey.ApplyFunc(ExecuteCommand, func(command string) (string, error) {
return string(mockOutput), nil
})
defer monkey.Unpatch(ExecuteCommand)
defer gomonkey.NewPatches().Reset()

// Create a new gomock controller
ctrl := gomock.NewController(t)
defer ctrl.Finish()

// Create a JetStreamContext mock
jsMock := mocks.NewMockJetStreamContextInterface(ctrl)
// Create a NATSClient mock
natsCliMock := mocks.NewMockNATSClientInterface(ctrl)

// Patch the Publish method of NATSClient
// patches := gomonkey.ApplyMethod(reflect.TypeOf(&sdk.NATSClient{}), "Publish", func(_ *sdk.NATSClient, subject string, data []byte) error {
// return natsCliMock.Publish(subject, data)
// })
// defer patches.Reset()

// Subtest for successful publish
t.Run("Successful publish", func(t *testing.T) {
jsMock.EXPECT().Publish(gomock.Any(), gomock.Any()).Return(nil, nil)
natsCliMock.EXPECT().Publish(gomock.Any(), gomock.Any()).Return(nil)
ns := "test-namespace"
err := publish(ns, jsMock)
if err != nil {
t.Errorf("publish returned an error: %v", err)
}
//natsCli := &sdk.NATSClient{} // Use the actual NATSClient
err := publish(ns, natsCliMock)
assert.NoError(t, err, "publish returned an error")
})

// Subtest for error in ExecuteCommand
t.Run("Error in ExecuteCommand", func(t *testing.T) {
// Mock ExecuteCommand to return an error
monkey.Patch(ExecuteCommand, func(command string) (string, error) {
gomonkey.ApplyFunc(ExecuteCommand, func(command string) (string, error) {
return "", errors.New("command execution error")
})
defer monkey.Unpatch(ExecuteCommand)
defer gomonkey.NewPatches().Reset()

ns := "test-namespace"
err := publish(ns, jsMock)
if err == nil {
t.Errorf("publish did not return an error")
}

// Since ExecuteCommand failed, Publish should not be called
jsMock.EXPECT().Publish(gomock.Any(), gomock.Any()).Times(0)
natsCli := &sdk.NATSClient{} // Use the actual NATSClient
err := publish(ns, natsCli)
assert.Error(t, err, "publish did not return an error")
})
}

type NATSClientWrapper struct {
mock *mocks.MockNATSClientInterface
}

func (w *NATSClientWrapper) CreateStream(streamName string) error {
return w.mock.CreateStream(streamName)
}

func (w *NATSClientWrapper) Publish(subject string, data []byte) error {
return w.mock.Publish(subject, data)
}
4 changes: 4 additions & 0 deletions agent/kubviz/plugins/trivy/trivy_image.go
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,10 @@ type JetStreamContextInterface interface {
nats.ObjectStoreManager
AccountInfo(opts ...nats.JSOpt) (*nats.AccountInfo, error)
}
type NATSClientInterface interface {
CreateStream(streamName string) error
Publish(subject string, data []byte) error
}

func RunTrivyImageScans(config *rest.Config, natsCli *sdk.NATSClient) error {
pvcMountPath := "/mnt/agent/kbz"
Expand Down
Loading

0 comments on commit 6dbb948

Please sign in to comment.