Example of lightweight approach to writing unit tests for bash scripts.
Consists of:
functions.sh
- set of bash fuctionsfunctions_test.sh
- set of unit tests
- Stubbing calls to external functions
function terraform {
cat terraform_response_vm_list.txt
}
Note: Sometimes might be also useful to export function definitions to sub-shell with:
export -f function_name
- Stopping tests with proper message when any of the assertions is not met
set -e
function validate_status {
if [[ $? != 0 ]]; then
echo "Tests failed"
else
echo "Tests succeeded."
fi
}
trap validate_status EXIT
- Finding out whether the script was sourced or called directly
#if true means that script was not run with "source" command
if [[ "${BASH_SOURCE[0]}" == "${0}" ]]
then
echo "Some action"
fi