1

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
  • 307
  • 4
  • 15
  • If you’re using the standard generated test code, you need to check the reconcile request channel or the controller stays blocked. – coderanger Dec 31 '18 at 05:15
  • I am not using the default `TestReconcile` function generated by kubebuilder. My tests (with the sample code above) are in a separate file. – Shri Javadekar Jan 02 '19 at 03:08

1 Answers1

1

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
  • 307
  • 4
  • 15