diff --git a/test/stub.sh b/test/stub.sh new file mode 100644 index 0000000..e262fdb --- /dev/null +++ b/test/stub.sh @@ -0,0 +1,35 @@ +# Stub commands for testing purposes. +# +# Arguments: +# - $1: Name of command to stub. +# - $2: Output will go to STDERR when $2 is "STDERR". +# +stub() { + local cmd="$1" + if [ "$2" == "STDERR" ]; then local redirect=" 1>&2"; fi + + if [[ "$(type "$cmd" | head -1)" == *"is a function" ]]; then + local source="$(type "$cmd" | tail -n +2)" + source="${source/$cmd/non_stubbed_${cmd}}" + eval "$source" + fi + eval "$(echo -e "${1}() {\n echo \"$1 stub: \$@\"$redirect\n}")" +} + +# Restore the original command/function that was stubbed with stub(). +# +# Arguments: +# - $1: Name of command to restore. +# +restore() { + local cmd="$1" + unset -f "$cmd" + if type "non_stubbed_${cmd}" &>/dev/null; then + if [[ "$(type "non_stubbed_${cmd}" | head -1)" == *"is a function" ]]; then + local source="$(type "non_stubbed_$cmd" | tail -n +2)" + source="${source/non_stubbed_${cmd}/$cmd}" + eval "$source" + unset -f "non_stubbed_${cmd}" + fi + fi +} diff --git a/test/test-helper.sh b/test/test-helper.sh index 085f44a..f435b12 100644 --- a/test/test-helper.sh +++ b/test/test-helper.sh @@ -3,6 +3,7 @@ testroot="$(dirname "$BASH_SOURCE")" # Include assert.sh testing library. source "$testroot/assert.sh" +source "$testroot/stub.sh" # # Additional test helpers. @@ -12,30 +13,3 @@ source "$testroot/assert.sh" cd-back() { cd - 1>/dev/null } - -# Stub commands printing it's name and arguments to STDOUT or STDERR. -stub() { - local cmd="$1" - if [ "$2" == "STDERR" ]; then local redirect=" 1>&2"; fi - - if [[ "$(type "$cmd" | head -1)" == *"is a function" ]]; then - local source="$(type "$cmd" | tail -n +2)" - source="${source/$cmd/original_${cmd}}" - eval "$source" - fi - eval "$(echo -e "${1}() {\n echo \"$1 stub: \$@\"$redirect\n}")" -} - -# Restore the original command/function that was stubbed with stub. -restore() { - local cmd="$1" - unset -f "$cmd" - if type "original_${cmd}" &>/dev/null; then - if [[ "$(type "original_${cmd}" | head -1)" == *"is a function" ]]; then - local source="$(type "original_$cmd" | tail -n +2)" - source="${source/original_${cmd}/$cmd}" - eval "$source" - unset -f "original_${cmd}" - fi - fi -}