How to unit test Kubernetes operator controller

Image for post
Image for post

The core logic of Kubernetes operator controller is reconciliation that adjust the actual state to the desired state of CR(Custom Resource). In this post, I’ll investigate typical reconciliation logic and how to unit test it.

What this post covers

  • Reconciliation logic of operator controller that leverages Golang (not Helm or Ansible)

What this post doesn’t cover

  • The basic concept of Kubernetes, Custom Resource, Operator

I assume you understand above concepts, but you never have to be a master of them to understand this post. (I don’t know much neither)

Operator controller reconciliation logic

Operator controller should have reconciliation logic for the CR it manages. It adjust the actual state of the child resources of CR to the desired state declared in CR manifest.

Let’s see sample code from Opearor-SDK official sample code.

Reconciliation logic of sample code goes like this

  1. Retrieve CR object from cluster using name, namespace given via request parameter. Note that the controller already knows resource type, obviously CR, in this case Memchached.(Line 1:6)

Reconciliation logic is pretty simple. Just fetch CR object and create or update child objects(e.g., deployment, service, secret, …) and update status accordingly.

How to unit test controller

Disclaimer about “good” unit testing

What is good unit testing is one of the most controversial topic among software engineers who matter software quality, refactoring, and agile manifesto. Now I carefully talk about my “opinionated” point of view.

  • Unit test is all about assumption and result. It’s just same as A -> B proposition. “If A is given, then this module returns B”. We call A test fixture, and B test result.

Just IMO.

Mock k8s client

Since controller heavily use k8s client, we need to mock this object efficiently. Thanks to k8s fake client library, we can easily inject CRD and CR object as constructor parameters of k8s client.

Unit test cases

We need test cases to write tests. So what’s core business logic of controller? Of course reconciliation. We can derive three test cases from the logic.

  • If the CR object doesn’t exist, then this module should do nothing and return success

I want to add unit test codes for above sample controller but i have no time for it. If someone needs it i’ll update this post later. Just comment.

Thanks :D

Written by

A software engineer developing cloud native platform. See more information at https://www.linkedin.com/in/yuminkimdev/

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store