Unit testing bash scripts the cloud-native way

Joachim De Groot
FlowFactor
Published in
2 min readMar 24, 2021

Unit testing?

Unit testing is a type of test used in software programming. Parts of the source code are tested against different tests to determine if that part of the code works and behaves as intended. Unit tests are often ran automatically and written by the same software developer who developed the code. During unit tests certain (external) dependencies are taken away by what is called “mocking”. Mocking is basically faking or simulating the expected behavior or response of a dependency. To do this, testing frameworks are often used but are not necessary. This is done because creating tests that incorporate certain dependencies are impractical or even impossible.

Unit testing bash?

Now, bash scripts are mostly written to automate repetitive and relatively easy actions. While bash scripts can be very powerful, they can also easily become complex and difficult to read. More than once I have started writing a script that started small and simple but became larger and more complex as I accounted for different situations and added more logic and features. In a lot of teams there is the philosophy to test everything that could possibly break. With that in mind, we should also unit test our bash scripts. There are a small number of testing frameworks that work with bash scripts. Some have extra dependencies to Python or Lua, if you want to keep everything simpler there are some that are natively made in bash. Some examples are shUnit2, assert.sh and bats-core.

The cloud-native way?

The method that I am going to show in this blog is even more simple. I am going to use native functionality found in bash to test my script. At FlowFactor we like to work in an automated and Cloud-Native way. That is why I’m going to use Docker and Jenkins. The example in my blog is simplified but still shows the way of working. Imagine that you have a Kubernetes cluster in your company, and you are writing a new component, a container containing a bash script that is going to run as a pod inside your cluster. The pod is going to monitor a persistent volume and sends an email if there are more than three crash dumps.

Do you want to dive in my technical tutorial on how to unit test bash scripts the cloud-native way? Read the full blog on our website here.

--

--