0

I am using client-go to read Kubernetes objects. There are some calls where I am reading custom resources as well. Following is the code snippet :

func GetComCR(kubeClient *v1alpha1.ExampleV1Alpha1Client) []byte {

    compute, err := kubeClient.ComputeMons("default").List(context.TODO(), metav1.ListOptions{})

    if err != nil {
        panic(err)
    }
    json_data, err := json.Marshal(compute)
    if err != nil {
        panic(err)
    }
    fmt.Println("compute_data: ", string(json_data))

    return json_data
}

func GetClusterclient() *v1alpha1.ExampleV1Alpha1Client {
    config := GetClusterConfig()

    config.ContentConfig.GroupVersion = &schema.GroupVersion{Group: "acme.com", Version: "v1alpha1"}
    config.APIPath = "/apis"
    config.NegotiatedSerializer = scheme.Codecs.WithoutConversion()
    config.UserAgent = rest.DefaultKubernetesUserAgent()

    monitoringv1alpha1.AddToScheme(scheme.Scheme)

    clientSet, _ := v1alpha1.NewForConfig(config)
    return clientSet
}

func (this *ComputeController) Get() {
    kubeclient := GetClusterclient()
    json_data := GetComCR(kubeclient)
    var resp interface{}
    json.Unmarshal(json_data, &resp)
    this.Data["json"] = resp
    this.ServeJSON()
    this.StopRun()
}

type ExampleV1Alpha1Client struct {
    restClient rest.Interface
}

Now I want to write UT for GetComCR method here. I found one thread here about UT :

How to write simple tests for client-go using a fake client?

But it didn't help me. It asks kubeClient kubernetes.Interface but in my case its ExampleV1Alpha1Client.

Can someone help me with how do I fake the client?

I tried the following test :

func TestCRRead(t *testing.T) {

    kubeClient := fake.NewSimpleClientset()
    resp := GetComCR(kubeClient)

    logs.Info("resp >>>", resp)

}

But compile fails as NewSimpleClientset gives *fake.Clientset.

saraf.gahl
  • 1,429
  • 1
  • 10
  • 13
  • What exactly are you trying to test here? – Riwen May 18 '21 at 17:52
  • trying to test the GetComCR method which actually reads the custom resource from the cluster. – OMKAR HINGMIRE May 19 '21 at 06:06
  • But what are you trying to *unit* test here? The function is extremely simple in terms of unit testable logic. Basically, it's all about error handling. Hardly a worthy candidate for unit testing, really. Rather, it may be a right fit for *integration* testing, but that's an entirely different subject. – Riwen May 19 '21 at 16:30
  • ok..I have already written some UTs for functions like GetClusterConfig, GetClusterclient, etc but how do I test GetComCR where kubeClient.ComputeMons is actually connecting to the cluster and reading the CR data. How do I mock the cluster itself. – OMKAR HINGMIRE May 19 '21 at 18:01

0 Answers0