Skip to content

[test]: add mock for test #1887

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

Draft
wants to merge 1 commit into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 6 additions & 1 deletion Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -274,7 +274,7 @@ SUDO_TEST_PKGS := $(shell go list -tags $(GO_BUILD_TAGS) ./... | grep pkg/bpftes
##@ testing

.PHONY: test
test: unit-test bpf-test bench ## Run all tests.
test: generatemock unit-test bpf-test bench ## Run all tests.

.PHONY: unit-test
unit-test: generate ginkgo-set tidy-vendor ## Run unit tests.
Expand Down Expand Up @@ -454,3 +454,8 @@ platform-validation: ginkgo-set get-env ## Run Kepler platform validation.

check: tidy-vendor check-govuln format golint test ## Run checks and tests.
.PHONY: check

.PHONY: generatemock
generatemock:
go install go.uber.org/mock/mockgen@latest
go generate ./pkg/...
5 changes: 3 additions & 2 deletions go.mod
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
module github.com/sustainable-computing-io/kepler

go 1.21.0
go 1.22

toolchain go1.21.9
toolchain go1.23.1

require (
github.com/HabanaAI/gohlml v1.16.0
Expand All @@ -22,6 +22,7 @@ require (
github.com/prometheus/prometheus v0.54.1
github.com/shirou/gopsutil v3.21.11+incompatible
github.com/sirupsen/logrus v1.9.3
go.uber.org/mock v0.5.0
golang.org/x/exp v0.0.0-20240719175910-8a7402abbf56
golang.org/x/sys v0.26.0
gopkg.in/yaml.v3 v3.0.1
Expand Down
2 changes: 2 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -166,6 +166,8 @@ go.uber.org/atomic v1.11.0 h1:ZvwS0R+56ePWxUNi+Atn9dWONBPp/AUETXlHW0DxSjE=
go.uber.org/atomic v1.11.0/go.mod h1:LUxbIzbOniOlMKjJjyPfpl4v+PKK2cNJn91OQbhoJI0=
go.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto=
go.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE=
go.uber.org/mock v0.5.0 h1:KAMbZvZPyBPWgD14IrIQ38QCyjwpvVVV6K/bHl1IwQU=
go.uber.org/mock v0.5.0/go.mod h1:ge71pBPLYDk7QIi1LupWxdAykm7KIEFchiOqd6z7qMM=
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI=
golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto=
Expand Down
56 changes: 56 additions & 0 deletions pkg/cgroup/kubelet_mock_test.go

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

8 changes: 1 addition & 7 deletions pkg/cgroup/resolve_container.go
Original file line number Diff line number Diff line change
Expand Up @@ -56,11 +56,6 @@ type cache struct {
byteOrder binary.ByteOrder
}

func Init() (*[]corev1.Pod, error) {
pods := []corev1.Pod{}
return &pods, nil
}

// init() Creates the singleton Config instance
func init() {
instance = newCache()
Expand Down Expand Up @@ -354,8 +349,7 @@ func getPathFromPID(searchPath string, pid uint64) (string, error) {
}

// GetAliveContainers returns a map of alive containers from the provided pods
func GetAliveContainers() (map[string]bool, error) {
podLister := kubelet.KubeletPodLister{}
func GetAliveContainers(podLister kubelet.KubeletPodLister) (map[string]bool, error) {
pods, err := podLister.ListPods()
if err != nil {
return nil, err
Expand Down
48 changes: 47 additions & 1 deletion pkg/cgroup/resolve_container_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,11 +17,13 @@ limitations under the License.
package cgroup

import (
"fmt"
"testing"

. "github.com/onsi/gomega"
"github.com/sustainable-computing-io/kepler/pkg/utils"

gomock "go.uber.org/mock/gomock"
corev1 "k8s.io/api/core/v1"
)

Expand Down Expand Up @@ -99,7 +101,7 @@ var results = map[string]bool{
"c3": true,
}

func TestGetAliveContainers(t *testing.T) {
func TestCacheGetAliveContainers(t *testing.T) {
g := NewWithT(t)

var testcases = []struct {
Expand Down Expand Up @@ -236,3 +238,47 @@ func TestValidContainerID(t *testing.T) {
result := validContainerID("")
g.Expect(result).To(Equal(utils.SystemProcessName))
}

func TestGetAliveContainers(t *testing.T) {
g := NewWithT(t)
controller := gomock.NewController(t)
defer controller.Finish()
mock := NewMockKubeletPodLister(controller)
mock.EXPECT().ListPods().Return(nil, fmt.Errorf("")).AnyTimes()
result, err := GetAliveContainers(mock)
g.Expect(result).To(BeNil())
g.Expect(err).To(HaveOccurred())
}

func TestGetAliveContainersInError(t *testing.T) {
g := NewWithT(t)
controller := gomock.NewController(t)
defer controller.Finish()
mock := NewMockKubeletPodLister(controller)
var testcases = []struct {
name string
pods []corev1.Pod
expectErr bool
expectResults map[string]bool
}{
{
name: "test normal status from kubelet",
pods: normalPods,
expectErr: false,
expectResults: results,
},
}

for _, testcase := range testcases {
t.Run(testcase.name, func(t *testing.T) {
mock.EXPECT().ListPods().Return(&testcase.pods, nil).AnyTimes()
result, err := GetAliveContainers(mock)
g.Expect(result).NotTo(BeNil())
g.Expect(err).NotTo(HaveOccurred())
})
}
}

func TestGetPathFromPID(t *testing.T) {

}
4 changes: 0 additions & 4 deletions pkg/cgroup/suite_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,3 @@ func TestPodLoader(t *testing.T) {
RegisterFailHandler(Fail)
RunSpecs(t, "CGroup Suite")
}

var _ = BeforeSuite(func() {
_, _ = Init()
})
7 changes: 6 additions & 1 deletion pkg/collector/metric_collector.go
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ import (
resourceBpf "github.com/sustainable-computing-io/kepler/pkg/collector/resourceutilization/bpf"
"github.com/sustainable-computing-io/kepler/pkg/collector/stats"
"github.com/sustainable-computing-io/kepler/pkg/config"
"github.com/sustainable-computing-io/kepler/pkg/kubelet"
"github.com/sustainable-computing-io/kepler/pkg/model"
acc "github.com/sustainable-computing-io/kepler/pkg/sensors/accelerator"
"github.com/sustainable-computing-io/kepler/pkg/utils"
Expand Down Expand Up @@ -59,6 +60,9 @@ type Collector struct {
bpfExporter bpf.Exporter
// bpfSupportedMetrics holds the supported metrics by the bpf exporter
bpfSupportedMetrics bpf.SupportedMetrics

// podLister list pod from k8s api
podLister kubelet.KubeletPodLister
}

func NewCollector(bpfExporter bpf.Exporter) *Collector {
Expand All @@ -70,6 +74,7 @@ func NewCollector(bpfExporter bpf.Exporter) *Collector {
VMStats: map[string]*stats.VMStats{},
bpfExporter: bpfExporter,
bpfSupportedMetrics: bpfSupportedMetrics,
podLister: kubelet.KubeletPodListerImpl{},
}
return c
}
Expand Down Expand Up @@ -229,7 +234,7 @@ func (c *Collector) handleIdlingProcess(pStat *stats.ProcessStats) {
func (c *Collector) handleInactiveContainers(foundContainer map[string]bool) {
numOfInactive := len(c.ContainerStats) - len(foundContainer)
if numOfInactive > maxInactiveContainers {
aliveContainers, err := cgroup.GetAliveContainers()
aliveContainers, err := cgroup.GetAliveContainers(c.podLister)
if err != nil {
klog.V(5).Infoln(err)
return
Expand Down
8 changes: 6 additions & 2 deletions pkg/kubelet/kubelet_pod_lister.go
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,11 @@ import (
corev1 "k8s.io/api/core/v1"
)

type KubeletPodLister struct{}
type KubeletPodListerImpl struct{}

type KubeletPodLister interface {
ListPods() (*[]corev1.Pod, error)
}

const (
saPath = "/var/run/secrets/kubernetes.io/serviceaccount/token"
Expand Down Expand Up @@ -75,7 +79,7 @@ func httpGet(url string) (*http.Response, error) {
}

// ListPods obtains PodList
func (k *KubeletPodLister) ListPods() (*[]corev1.Pod, error) {
func (k KubeletPodListerImpl) ListPods() (*[]corev1.Pod, error) {
resp, err := httpGet(podURL)
if err != nil {
return nil, fmt.Errorf("failed to get response: %v", err)
Expand Down
12 changes: 12 additions & 0 deletions vendor/go.uber.org/mock/AUTHORS

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

Loading
Loading