Assertion framework in shell script
A little lib that helps us checking our scripts with a unit test-like way.
The Missing Tool
Unit testing is part of a lot of projects’ toolset. Though some part of the source code requires more attention than it gets payed. Shell scripts belong to them.
How can we make sure that our scripts do what we expect they do?
How can we make sure they are valid, return the right result…?
We have to write unit test-like code. To achieve this, let us see a tool that
can give a very elegant and handy way, let us see assert.sh
.
assert_...
Plenty of assert functions available, just naming a few of them.
assert_eq
takes two strings and checks whether they are the same based on the character strings.assert_not_eq
is the opposite ofassert_eq
.assert_true
takes a parameter and returns0
confirming the parameter is true.assert_false
takes a parameter and decides whether it is false.assert_array_eq
takes two arrays and compare them by items.assert_contain
checks wether the second parameter is contained by the first one
Usage
source "./assert.sh"
local expected actual
expected="Hello"
actual="Hello"
assert_eq "$expected" "$actual"
if [ "$?" == 0 ]; then
log_success "assert_eq returns 0 if two words are equal"
else
log_failure "assert_eq should return 0"
fi
Source code is available here: https://github.com/torokmark/assert.sh