Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

creating a unit test using mocking for the generate SS function #20

Closed
wants to merge 13 commits into from
Closed
5 changes: 4 additions & 1 deletion Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,10 @@ EXECUTABLE := commatrix-gen
.DEFAULT_GOAL := run

build:
go build -o $(EXECUTABLE) $(GO_SRC)
go build -o $(EXECUTABLE) $(GO_SRC)

mock-generate:
go generate ./...

oc:
ifeq (, $(shell which oc))
Expand Down
8 changes: 7 additions & 1 deletion cmd/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@ import (
"os"
"path/filepath"

clientutil "github.com/openshift-kni/commatrix/client"

"github.com/openshift-kni/commatrix/commatrix"
)

Expand Down Expand Up @@ -33,6 +35,10 @@ func main() {
if !ok {
panic("must set the KUBECONFIG environment variable")
}
cs, err := clientutil.New(kubeconfig)
if err != nil {
panic("must set the KUBECONFIG environment variable")
}

var env commatrix.Env
switch envStr {
Expand Down Expand Up @@ -68,7 +74,7 @@ func main() {
panic(fmt.Sprintf("Error while writing the endpoint slice matrix to file :%v", err))
}
// generate the ss matrix and ss raws
ssMat, ssOutTCP, ssOutUDP, err := commatrix.GenerateSS(kubeconfig, customEntriesPath, customEntriesFormat, format, env, deployment, destDir)
ssMat, ssOutTCP, ssOutUDP, err := commatrix.GenerateSS(cs)
if err != nil {
panic(fmt.Sprintf("Error while generating the ss matrix and ss raws :%v", err))
}
Expand Down
82 changes: 81 additions & 1 deletion commatrix/commatrix_test.go
Original file line number Diff line number Diff line change
@@ -1,12 +1,23 @@
package commatrix

import (
"context"
"fmt"
"path/filepath"
"strings"
"testing"
"time"

gomock "go.uber.org/mock/gomock"

"github.com/openshift-kni/commatrix/types"
"github.com/stretchr/testify/assert"
v1 "k8s.io/api/core/v1"
aabughosh marked this conversation as resolved.
Show resolved Hide resolved
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/client-go/kubernetes/fake"

clientutil "github.com/openshift-kni/commatrix/client"
"github.com/openshift-kni/commatrix/debug"
"github.com/openshift-kni/commatrix/types"
)

func TestGetPrintFunction(t *testing.T) {
Expand Down Expand Up @@ -50,3 +61,72 @@ func TestWriteMatrixToFile(t *testing.T) {
assert.NoError(t, err)
assert.FileExists(t, filepath.Join(destDir, "test-matrix.json"))
}

func TestGenerateSS(t *testing.T) {
clientset := fake.NewSimpleClientset()

ctrlTest := gomock.NewController(t)
defer ctrlTest.Finish()

mockDebugPod := debug.NewMockDebugPodInterface(ctrlTest)

tcpOutput := []byte(`LISTEN 0 4096 127.0.0.1:8797 0.0.0.0:* users:(("machine-config-",pid=3534,fd=3))
LISTEN 0 4096 127.0.0.1:8798 0.0.0.0:* users:(("machine-config-",pid=3534,fd=13))
LISTEN 0 4096 127.0.0.1:9100 0.0.0.0:* users:(("node_exporter",pid=4147,fd=3))`)

udpOutput := []byte(`UNCONN 0 0 0.0.0.0:111 0.0.0.0:* users:(("rpcbind",pid=1399,fd=5),("systemd",pid=1,fd=78))
UNCONN 0 0 127.0.0.1:323 0.0.0.0:* users:(("chronyd",pid=1015,fd=5))
UNCONN 0 0 10.46.97.104:500 0.0.0.0:* users:(("pluto",pid=2115,fd=21))`)
Output := []byte(`1: /system.slice/containerd.service
2: /system.slice/kubelet.service
3: /system.slice/sshd.service`)

// Set up the expectations
mockDebugPod.EXPECT().ExecWithRetry(gomock.Any(), gomock.Any(), gomock.Any()).DoAndReturn(
func(cmd string, interval, duration time.Duration) ([]byte, error) {
if strings.HasPrefix(cmd, "cat /proc/") && strings.Contains(cmd, "/cgroup") {
return Output, nil
}
if cmd == "ss -anpltH" {
return tcpOutput, nil
}
if cmd == "ss -anpluH" {
return udpOutput, nil
}
return nil, fmt.Errorf("unknown command")
},
).AnyTimes()

mockDebugPod.EXPECT().Clean().Return(nil).AnyTimes()

mockDebugPod.EXPECT().GetNodeName().Return("test-node").AnyTimes()

originalNew := debug.NewDebugPod
debug.NewDebugPod = func(cs *clientutil.ClientSet, node string, namespace string, image string) (debug.DebugPodInterface, error) {
return mockDebugPod, nil
}
defer func() { debug.NewDebugPod = originalNew }()
aabughosh marked this conversation as resolved.
Show resolved Hide resolved

cs := &clientutil.ClientSet{
CoreV1Interface: clientset.CoreV1(),
}
testNode := &v1.Node{
ObjectMeta: metav1.ObjectMeta{
Name: "test-node",
},
}

_, _ = clientset.CoreV1().Nodes().Create(context.TODO(), testNode, metav1.CreateOptions{})

ssMat, ssOutTCP, ssOutUDP, err := GenerateSS(cs)
expectedSSMat := &types.ComMatrix{
Matrix: []types.ComDetails{
{Direction: "Ingress", Protocol: "UDP", Port: 111, Namespace: "", Service: "rpcbind", Pod: "", Container: "", NodeRole: "", Optional: false},
{Direction: "Ingress", Protocol: "UDP", Port: 500, Namespace: "", Service: "pluto", Pod: "", Container: "", NodeRole: "", Optional: false},
}}

assert.NoError(t, err)
assert.Equal(t, expectedSSMat, ssMat, "Expected and actual ssMat values should match")
assert.Equal(t, "node: test-node\nLISTEN 0 4096 127.0.0.1:8797 0.0.0.0:* users:((\"machine-config-\",pid=3534,fd=3)) \nLISTEN 0 4096 127.0.0.1:8798 0.0.0.0:* users:((\"machine-config-\",pid=3534,fd=13)) \nLISTEN 0 4096 127.0.0.1:9100 0.0.0.0:* users:((\"node_exporter\",pid=4147,fd=3))\n", string(ssOutTCP))
assert.Equal(t, "node: test-node\nUNCONN 0 0 0.0.0.0:111 0.0.0.0:* users:((\"rpcbind\",pid=1399,fd=5),(\"systemd\",pid=1,fd=78))\nUNCONN 0 0 127.0.0.1:323 0.0.0.0:* users:((\"chronyd\",pid=1015,fd=5)) \nUNCONN 0 0 10.46.97.104:500 0.0.0.0:* users:((\"pluto\",pid=2115,fd=21))\n", string(ssOutUDP))
}
9 changes: 2 additions & 7 deletions commatrix/generate.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,12 +18,7 @@ import (
"github.com/openshift-kni/commatrix/types"
)

func GenerateSS(kubeconfig, customEntriesPath, customEntriesFormat, format string, env Env, deployment Deployment, destDir string) (ssMat *types.ComMatrix, ssOutTCP, ssOutUDP []byte, err error) {
cs, err := clientutil.New(kubeconfig)
if err != nil {
return nil, nil, nil, err
}

func GenerateSS(cs *clientutil.ClientSet) (ssMat *types.ComMatrix, ssOutTCP, ssOutUDP []byte, err error) {
nodesList, err := cs.CoreV1Interface.Nodes().List(context.TODO(), metav1.ListOptions{})
if err != nil {
return nil, nil, nil, err
Expand All @@ -46,7 +41,7 @@ func GenerateSS(kubeconfig, customEntriesPath, customEntriesFormat, format strin
for _, n := range nodesList.Items {
node := n
g.Go(func() error {
debugPod, err := debug.New(cs, node.Name, consts.DefaultDebugNamespace, consts.DefaultDebugPodImage)
debugPod, err := debug.NewDebugPod(cs, node.Name, consts.DefaultDebugNamespace, consts.DefaultDebugPodImage)
if err != nil {
return err
}
Expand Down
16 changes: 15 additions & 1 deletion debug/debug.go
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
package debug

//go:generate mockgen -destination=debug_mock.go -package=debug . DebugPodInterface

import (
"context"
"errors"
Expand All @@ -17,20 +19,32 @@ import (
"github.com/openshift-kni/commatrix/client"
)

type DebugPodInterface interface {
aabughosh marked this conversation as resolved.
Show resolved Hide resolved
ExecWithRetry(command string, interval time.Duration, duration time.Duration) ([]byte, error)
Clean() error
GetNodeName() string
}

type DebugPod struct {
Name string
Namespace string
NodeName string
}

func (dp *DebugPod) GetNodeName() string {
return dp.NodeName
}

const (
interval = 1 * time.Second
timeout = 2 * time.Minute
)

var NewDebugPod = New

// New creates debug pod on the given node, puts it in infinite sleep,
// and returns the DebugPod object. Use the Clean() method to delete it.
func New(cs *client.ClientSet, node string, namespace string, image string) (*DebugPod, error) {
func New(cs *client.ClientSet, node string, namespace string, image string) (DebugPodInterface, error) {
if namespace == "" {
return nil, errors.New("failed creating new debug pod: got empty namespace")
}
Expand Down
83 changes: 83 additions & 0 deletions debug/debug_mock.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 3 additions & 0 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,11 @@ go 1.21

require (
github.com/gocarina/gocsv v0.0.0-20231116093920-b87c2d0e983a
github.com/golang/mock v1.6.0
github.com/openshift/client-go v0.0.0-20240415214935-be70f772f157
github.com/sirupsen/logrus v1.9.3
github.com/stretchr/testify v1.8.4
go.uber.org/mock v0.4.0
k8s.io/api v0.29.3
k8s.io/apimachinery v0.29.3
k8s.io/client-go v0.29.3
Expand All @@ -16,6 +18,7 @@ require (
)

require (
github.com/evanphx/json-patch v4.12.0+incompatible // indirect
github.com/openshift/api v0.0.0-20240415161129-d7aff303fa1a // indirect
github.com/pmezard/go-difflib v1.0.0 // indirect
)
Expand Down
13 changes: 13 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,8 @@ github.com/gocarina/gocsv v0.0.0-20231116093920-b87c2d0e983a h1:RYfmiM0zluBJOiPD
github.com/gocarina/gocsv v0.0.0-20231116093920-b87c2d0e983a/go.mod h1:5YoVOkjYAQumqlV356Hj3xeYh4BdZuLE0/nRkf2NKkI=
github.com/gogo/protobuf v1.3.2 h1:Ov1cvc58UF3b5XjBnZv7+opcTcQFZebYjWzi34vdm4Q=
github.com/gogo/protobuf v1.3.2/go.mod h1:P1XiOD3dCwIKUDQYPy72D8LYyHL2YPYrpS2s69NZV8Q=
github.com/golang/mock v1.6.0 h1:ErTB+efbowRARo13NNdxyJji2egdxLGQhRaY+DUumQc=
github.com/golang/mock v1.6.0/go.mod h1:p6yTPP+5HYm5mzsMV8JkE6ZKdX+/wYM6Hr+LicevLPs=
github.com/golang/protobuf v1.3.1/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U=
github.com/golang/protobuf v1.5.4 h1:i7eJL8qZTpSEXOPTxNKhASYpMn+8e5Q6AdndVa1dWek=
github.com/golang/protobuf v1.5.4/go.mod h1:lnTiLA8Wa4RWRcIUkrtSVa5nRhsEGBg48fD6rSs7xps=
Expand Down Expand Up @@ -94,6 +96,9 @@ github.com/stretchr/testify v1.8.4 h1:CcVxjf3Q8PM0mHUKJCdn+eZZtm5yQwehR5yeSVQQcU
github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo=
github.com/yuin/goldmark v1.1.27/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74=
github.com/yuin/goldmark v1.2.1/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74=
github.com/yuin/goldmark v1.3.5/go.mod h1:mwnBkeHKe2W/ZEtQ+71ViKU8L12m81fl3OWwC1Zlc8k=
go.uber.org/mock v0.4.0 h1:VcM4ZOtdbR4f6VXfiOpwpVJDL6lCReaZ6mw31wqh7KU=
go.uber.org/mock v0.4.0/go.mod h1:a6FSlNadKUHUa9IP5Vyt1zh4fC7uAwxMutEAscFbkZc=
go.uber.org/multierr v1.11.0 h1:blXXJkSxSSfBVBlC76pxqeO+LN3aDfLQo+309xJstO0=
go.uber.org/multierr v1.11.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y=
go.uber.org/zap v1.26.0 h1:sI7k6L95XOKS281NhVKOFCUNIvv9e0w4BF8N3u+tCRo=
Expand All @@ -105,26 +110,33 @@ golang.org/x/exp v0.0.0-20220722155223-a9213eeb770e h1:+WEEuIdZHnUeJJmEUjyYC2gfU
golang.org/x/exp v0.0.0-20220722155223-a9213eeb770e/go.mod h1:Kr81I6Kryrl9sr8s2FK3vxD90NdsKWRuOIl2O4CvYbA=
golang.org/x/mod v0.2.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA=
golang.org/x/mod v0.3.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA=
golang.org/x/mod v0.4.2/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA=
golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
golang.org/x/net v0.0.0-20190603091049-60506f45cf65/go.mod h1:HSz+uSET+XFnRR8LxR5pz3Of3rY3CfYBVs4xY44aLks=
golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
golang.org/x/net v0.0.0-20200226121028-0de0cce0169b/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
golang.org/x/net v0.0.0-20201021035429-f5854403a974/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU=
golang.org/x/net v0.0.0-20210405180319-a5a99cb37ef4/go.mod h1:p54w0d4576C0XHj96bSt6lcn1PtDYWL6XObtHCRCNQM=
golang.org/x/net v0.19.0 h1:zTwKpTd2XuCqf8huc7Fo2iSy+4RHPd10s4KzeTnVr1c=
golang.org/x/net v0.19.0/go.mod h1:CfAk/cbD4CthTvqiEl8NpboMuiuOYsAr/7NOjZJtv1U=
golang.org/x/oauth2 v0.12.0 h1:smVPGxink+n1ZI5pkQa8y6fZT0RW0MgCO5bFpepy4B4=
golang.org/x/oauth2 v0.12.0/go.mod h1:A74bZ3aGXgCY0qaIC9Ahg6Lglin4AMAco8cIv9baba4=
golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20190911185100-cd5d95a43a6e/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20201020160332-67f06af15bc9/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20210220032951-036812b2e83c/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.5.0 h1:60k92dhOjHxJkrqnwsfl8KuaHbn/5dl0lUPUklKo3qE=
golang.org/x/sync v0.5.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk=
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20200930185726-fdedc70b468f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20210330210617-4fbd30eecc44/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20210510120138-977fb7262007/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20220715151400-c0bba94af5f8/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.16.0 h1:xWw16ngr6ZMtmxDyKyIgsE93KNKz5HKmMa3b8ALHidU=
golang.org/x/sys v0.16.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
golang.org/x/term v0.15.0 h1:y/Oo/a/q3IXu26lQgl04j/gjuBDOBlx7X6Om1j2CPW4=
golang.org/x/term v0.15.0/go.mod h1:BDl952bC7+uMoWR75FIrCDx79TPU9oHkTZ9yRbYOrX0=
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
Expand All @@ -138,6 +150,7 @@ golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGm
golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
golang.org/x/tools v0.0.0-20200619180055-7c47624df98f/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE=
golang.org/x/tools v0.0.0-20210106214847-113979e3529a/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA=
golang.org/x/tools v0.1.1/go.mod h1:o0xws9oXOQQZyjljx8fwUC0k7L1pTE6eaCbjGeHmOkk=
golang.org/x/tools v0.16.1 h1:TLyB3WofjdOEepBHAU20JdNC1Zbg87elYofWYAY5oZA=
golang.org/x/tools v0.16.1/go.mod h1:kYVVN6I1mBNoB1OX+noeBjbRk4IUEPa7JJ+TJMEooJ0=
golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
Expand Down
Loading
Loading