Ensure stub can be used multiple times on the same command

Ensures that the original bash function is preserved even if it is
stubbed multiple times before a restore.
This commit is contained in:
2014-03-16 01:57:58 +00:00
parent ef231e420a
commit 0c4a5d11ee
2 changed files with 18 additions and 4 deletions

10
stub.sh
View File

@@ -69,10 +69,12 @@ stub_and_eval() {
# If stubbing a function, store non-stubbed copy of it required for restore.
if [ -n "$(command -v "$cmd")" ]; then
if [[ "$(type "$cmd" | head -1)" == *"is a function" ]]; then
local source="$(type "$cmd" | tail -n +2)"
source="${source/$cmd/non_stubbed_${cmd}}"
eval "$source"
if [ -z "$(command -v "non_stubbed_${cmd}")" ]; then
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
fi
fi

View File

@@ -43,5 +43,17 @@ restore "my-name-is"
assert "my-name-is Edward Elric" "My name is Edward Elric."
# Stubbing the same function multiple times and then restoring it.
my-name-is() { echo "My name is $@."; }
stub "my-name-is"
assert "my-name-is Edward Elric" ""
stub "my-name-is" stdout
assert "my-name-is Edward Elric" "my-name-is stub: Edward Elric"
restore "my-name-is"
assert "my-name-is Edward Elric" "My name is Edward Elric."
# End of tests.
assert_end "restore()"