I really like to add some unit tests when creating Helm Charts, especially when the number of conditional statements increases the complexity grows. So IMHO, it’s crucial to have a safety net to protect your future self from making any mistakes.
You already have helm lint and tools like helm/chart-testing, which are valuable tools when developing Helm Charts. However, they don’t cover all the aspects of a chart, and testing all the conditionals is quite tricky and convoluted.
To my surprise, I couldn’t find a lot of existing projects who try to solve unit testing for Helm Charts. And to be honest, none of the existing solutions were viable alternatives that satisfied me, so I’ve set up a test suite using MiniTest Ruby Test framework instead.
Without the actual tests, the boilerplate code is less than a hundred lines of code, which makes our lives easier. In three easy steps, I’ll walk you through how you will be able to use the same setup yourself.
The Chart Class
The below snippet shows the meat of the
Chart class created to abstract away the necessities to gather input values
for the Helm chart and to execute the helm template command. It will capture and parse the command’s output to quickly
lookup Kubernetes resources to compare them in our unit tests.
Chart class, I’ve also extended the
MiniTest::Spec class to make it easier to interact directly with
the “subject” chart. A convenience helper is the
jq method, which uses jq to look up specific values using a JSON
Writing a first test
We start the test by first defining which Helm Chart we are testing. In this case, we are testing a simple
see line 1.
In our tests, we can refer to the chart object, which gives us the option to define custom values. As you can see in
the replica’s test where we define a custom
replicaCount of three on line 4.
And on line 6, we use the
jq helper to retrieve the
replicas field from the
Deployment resource to validate the
custom replica count in configured. Calling the
resource method will implicitly trigger the
helm template action to
be performed with the configured values.
For a complete example, I’ve set up an example repository, including the
chart/web I refer to above and some more unit
tests. Have a look at niels-s/helm-chart-unit-test-example.
And let’s give credit where credit’s due to my former colleague Jean Mertz who started with this idea in the first place.