1

I am writing the simplest fxn possible using client-go that justs performs in-cluster authentication and returns a pointer to the kubernetes.Clientset object

// getInClusterAuth performs in cluster authentication and returns the clientset
func getInClusterAuth() (*kubernetes.Clientset, error) {
    // creates the in-cluster config
    config, err := rest.InClusterConfig()
    if err != nil {
        return nil, err
    }
    // create the clientset
    clientset, err := kubernetes.NewForConfig(config)
    if err != nil {
        return nil, err
    }

    return clientset, nil
}

Since this is sth that not only does it run against an external system (a k8s api server) but it is also supposed to be running from within a Pod once deployed, what is the appropriate way of unit-testing it?

Could it be that it is an acceptable practice to cover the case in e2e or integration tests?

pkaramol
  • 16,451
  • 43
  • 149
  • 324

1 Answers1

2

you can use k8s.io/client-go/kubernetes/fake.NewSimpleClientset to mock a clientSet in your unit test .


import (
        "context"
        "testing"

        v1 "k8s.io/api/core/v1"
        "k8s.io/apimachinery/pkg/api/errors"
        metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
        "k8s.io/client-go/kubernetes/fake"
)

func TestHelloWorld(t *testing.T) {
        clientset := fake.NewSimpleClientset(&v1.Pod{
                ObjectMeta: metav1.ObjectMeta{
                        Name:        "influxdb-v2",
                        Namespace:   "default",
                        Annotations: map[string]string{},
                },
        }, &v1.Pod{
                ObjectMeta: metav1.ObjectMeta{
                        Name:        "chronograf",
                        Namespace:   "default",
                        Annotations: map[string]string{},
                },
        })

        _, err := clientset.CoreV1().Pods(v1.NamespaceDefault).Get(context.Background(), "influxdb-v2", metav1.GetOptions{})
        if err != nil {
                if errors.IsNotFound(err) {
                        t.Error(err)
                } else {
                        t.Errorf("failed to get service from apiserver: %s", err)
                }
        }

        p := &v1.Pod{ObjectMeta: metav1.ObjectMeta{Name: "helloooooo"}}
        _, err = clientset.CoreV1().Pods(v1.NamespaceDefault).Create(context.Background(), p, metav1.CreateOptions{})
        if err != nil {
            t.Fatalf("error injecting pod add: %v", err)
        }
}

this is a sample: a fakeclient case

Miffa Young
  • 107
  • 4
  • 1
    I guess I can later on mock the requests made to this `clientset`, however I cannot (via the above example) mock/unit test the client creation itself, right? – pkaramol Aug 09 '21 at 15:22