Skip to main content

Testing Bash with Bats

Spectacled Fruit Bat by Shek Graham

Spectacled Fruit Bat by Shek Graham

I quite like unit tests. They give you that quick feedback that things are going to be okay. I can write a test watch it fail. Write some code and watch it fail also. Then learn very quickly what I have done wrong.

At some point last year I read the Clean Code book by Rober C Martin and it opened up to me a lot of the ideas about testing and code that I had not really got to grips with at the time. Martin takes you through the reasoning and process for producing code that, in a years time, you might want to actually look at and feel comfortable editing.

What has this go to do with bash and bats? Well we have been adding more tests to our puppet code and it came time to write a bit of bash for moving some files around. I thought there must be a simple way to check some of this and sure enought that is where bats comes in.

bats is a testing framework for bash scripts. I know it sounds crazy but it really does work. If you start applying some of the lessons from clean code and spliting your work into functions with local varaiables it soon becomes easier to test. You can, as ever, take things too far but this does at least allow you to test a lot of your logic before you roll it out. With the added benifit of makeing the code a little more readable.

I found this blog post by Spike cleared up some of the questions I had about testing functions as well. http://blog.spike.cx/post/60548255435/testing-bash-scripts-with-bats

Some other useful things are the google shell style guide and shUnit2 which I have yet to look at. The Defensive Shell Guide by Kfir Lavi and Better Bash Scripting in 15 Minutes by Robert Muth are also good.

Comments

Comments powered by Disqus
Mastodon: @[email protected] Flattr me