Unit Testing with Kubernetes client-go
I recently started working on a project that required me to use the Kubernetes client-go
package. I had used it before but ignored unit tests for that section code. When I started working on this project I decided to dive into unit testing my interactions with Kubernetes. Unfortunately, I wasn’t able to find any direct tutorials on the subject but was able to find enough of an example from the nginx-ingress-controller
project and thought I’d write about my findings.
For this post we’ll be testing a simple function that creates a Kubernetes Namespace with a suffix. Our function will take a namespace
argument and create a Namespace using that argument and appending a configured suffix.
For example, given the name test-namespace
and the suffix blog-post
our function should create a Namespace with the name test-namespace-blog-post
. While contrived, this example will demonstrate how we should construct our code in such a way that it’s easily testable.
In the above example, we create a new type KubernetesAPI
that has a method NewNamespaceWithSuffix
. This is the method we’ll be testing. Before we continue, notice that we’re using kubernetes.Interface
instead of kubernetes.Clientset
. We do this because using kubernetes.Clientset
would force us into using that specific type. By using the interface, we can mock the Kubernetes API such that our tests don’t depend on an actual Kubernetes cluster. Fortunately, k8s.io/client-go/kubernetes/fake
exposes a ready to use mock that we’ll be able to use in our unit tests.
Our test case is simple: We’ll create an instance of KubernetesAPI
using the suffix unit-test
and a NewSimpleClientset
from the fake
package. This Clientset
conforms to the the kubernetes.Interface
so we’ll be able to use it for our tests. First, we use our method NewNamespaceWithSuffix
and then verify that the namespace was created by using the same Clientset
to query the API. In this case, if we don’t get an error then our test was successful.
This is a simple example but it shows that we can easily write and test applications that interact with Kubernetes and be sure that our logic is sound. Of course, you may experience some edge cases while using k8s.io/client-go/kubernetes/fake
, but for simple interactions it should be enough to validate your code!
Thanks for reading!