Unable to get K8S resources in kubebuilder's client.Client for unit test

12/31/2018

I am writing some unit-tests for a sample Kubernetes CRD and controller created using Kubebuilder. The main code in the controller creates Kubernetes resources (a namespace and a ResourceQuota inside it). In my unit-tests, I want to verify that the controller actually created these. I use a client.Client object created using the default sigs.k8s.io/controller-runtime/pkg/manager object.

mgr, _ := manager.New(cfg, manager.Options{})
cl := mgr.GetClient()
rq := &corev1.ResourceQuota{}
err = cl.Get(ctx, types.NamespacedName{Name: "my-quota", Namespace: 
        "my-namespace"}, rq)

I know that the main code works fine because I tested it in a real, live environment. I see that the main code gets called from the unit tests. However, the above code in the unit tests does not work; i.e. the call to Get() does the return the ResourceQuota I expect. I've also tried the List() api but that too does not return anything. There is no error either. Just an empty response.

Do I have to do something special/different for getting the K8S control plane in Kubebuilder to run unit tests?

-- Shri Javadekar
kubebuilder
kubernetes
unit-testing

1 Answer

1/2/2019

Posting this in case others find it useful. If you want to access other K8S resources, you would need to use the standard clientSet object from Kubernetes' client-go. For e.g. if you want to confirm that a specific namespace called targetNamespace exists:

mgr, _ := manager.New(cfg, manager.Options{})
generatedClient := kubernetes.NewForConfigOrDie(mgr.GetConfig())

nsFound := false
namespaces := generatedClient.CoreV1().Namespaces()
namespaceList, _ := namespaces.List(metav1.ListOptions{})
for _, ns := range namespaceList.Items {
    if ns.Name == targetNamespace {
        nsFound = true
        break
    }
}
g.Expect(nsFound).To(gomega.BeTrue())
log.Printf("Namespace %s verified", targetNamespace)
-- Shri Javadekar
Source: StackOverflow