Monday, September 8, 2014

Updated bash testing suite

As a followup to last week's testing post I wanted to expand from a test script, to a testing suite.

Anyone familiar with TDD will often see something like a `tests` directory and a simple `run_tests` script. I wanted to do this in bash.

Using the same style trapping as before, with a simple change, we can achieve a nice result.

#!/usr/local/bin/bash
set -o pipefail

# Begin tests

function error_exit() {
  echo -e "\E[31mTest $TEST failed\E[0m"
  exit 1
}

function success_exit() {
  echo -e "\E[32m $TEST OK\E[0m"
}

trap "error_exit" ERR
trap "success_exit" RETURN

for i in `ls tests/*`; do
  source $i
done

Any file in the tests directory will be evaluated and the results will be reported through the run_tests script
Here's some sample tests:

ls tests/
01-file.sh 02-cows
looking at tests/01-file.sh
export TEST="File exists"
find . -name file &>/dev/null
looking at tests/02-cows:
export TEST="File has cows"
grep -q cows file

Super simple, no shebang interpreter needed, not even an executable file. All we need is to set the value of $TEST to something meaningful. Here's what the test run looks like:


 $ ./run_tests.sh 
 File exists OK

Test File has cows failed

Lets see what's wrong with this...
cat file 
Cows

Ah... wrong case, lets fix that:
 cat file 
cows
$ ./run_tests.sh 
 File exists OK
 File has cows OK

No comments:

Post a Comment