How to mock Kubernetes Custom Resources for writing unit tests for Kubernetes client Read API in golang?

633 Views Asked by At

I have a use case where I am reading the custom resources. Below is a sample code for that

type Image Struct {
    metav1.TypeMeta   `json:",inline"`
    metav1.ObjectMeta `json:"metadata,omitempty"`

    Spec   ImageSpec   `json:"spec,omitempty"`
    Status ImageStatus `json:"status,omitempty"`
}

list := v1alpha1.ImageList{}
err := srv.restClient.
    Get().
    Resource("images").
    Do(ctx).
    Into(&list)

How can I mock these images CR for testing the function? I am using fake clientSet for creating a fake RestClient. I went through documentation of ClientSet and explored a couple of Interfaces but was not able to find any API which I can use for creating fake resources.

Documentation link: https://pkg.go.dev/k8s.io/client-go/kubernetes/fake

Does anyone know how can I achieve this?

I explored a couple of ClientSet APIs but was not able to find one using which I can create.

1

There are 1 best solutions below

0
Matteo On

you could initialize fakeclient like:

    objects := []runtime.Object{
        &yourapiv1. Image{
            TypeMeta:   metav1.TypeMeta{},
            ObjectMeta: metav1.ObjectMeta{},
            Spec:       yourapiv1.ImageSpec{},
            Status:     yourapiv1.ImageStatus{},
        },
        &yourapiv1. Image{
            TypeMeta:   metav1.TypeMeta{},
            ObjectMeta: metav1.ObjectMeta{},
            Spec:       yourapiv1.ImageSpec{},
            Status:     yourapiv1.ImageStatus{},
        },
    }

    sc := runtime.NewScheme()
    utilruntime.Must(yourapiv1.AddToScheme(sc))

            fakeClientBuilder := fake.NewClientBuilder().WithScheme(sc)
            fakeClient := fakeClientBuilder.WithRuntimeObjects(objects...).Build()