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
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
$ ./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