Skip to content

Instantly share code, notes, and snippets.

@mantoni
Last active February 9, 2024 15:00
Show Gist options
  • Save mantoni/6162595 to your computer and use it in GitHub Desktop.
Save mantoni/6162595 to your computer and use it in GitHub Desktop.
Minimal bash unit testing framework
#!/bin/bash
#
# Copyright (c) 2013 Maximilian Antoni
#
export TEST_COLOR_GREEN="\033[1m\033[32m"
export TEST_COLOR_RED="\033[1m\033[31m"
export TEST_COLOR_TITLE="\033[1m\033[36m"
export TEST_COLOR_OFF="\033[0m"
export TEST_SPACES=" "
export TEST_LINE="-----------------------------------------------------"
pass() {
echo -n " $1${TEST_SPACES:${#1}}"
echo -e "\t[$TEST_COLOR_GREEN OK $TEST_COLOR_OFF]"
}
fail() {
echo -n " $1${TEST_SPACES:${#1}}"
echo -e "\t[$TEST_COLOR_RED""FAILED$TEST_COLOR_OFF]"
echo -e "$TEST_COLOR_RED $2$TEST_COLOR_OFF"
}
assertEqual() {
TEST_EVALUATED=`(eval $2) 2>&1`
if [[ "$TEST_EVALUATED" == "$3" ]]; then
pass "$1"
else
fail "$1" "Expected $3\n Actual $TEST_EVALUATED"
fi
}
assert() {
(eval "if $2; then pass \"$1\"; else fail \"$1\" \"$2\"; fi")
}
assertNot() {
(eval "if $2; then fail \"$1\" \"$2\"; else pass \"$1\"; fi")
}
reset() {
. tear-down.sh
. setup.sh
}
export -f pass
export -f fail
export -f assertEqual
export -f assert
export -f assertNot
export -f reset
# Run test scripts:
cd test
if [ $1 ]; then
TEST_TESTS=($1)
else
TEST_TESTS=`ls test-*.sh`
fi
for TEST_TEST in $TEST_TESTS; do
echo -e $TEST_COLOR_TITLE"# "$TEST_TEST" "${TEST_LINE:${#TEST_TEST}}$TEST_COLOR_OFF
. setup.sh
./$TEST_TEST
. tear-down.sh
echo
done
# Declare variables so that they can be overridden like this
: ${SOME_VARIABLE:="the/default/value"}
# In the test code, for example in setup.sh, override the variable
export SOME_VARIABLE="the/test/override"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment