From 0c4a5d11ee4dd296ae57f5b0a60e88265267faa7 Mon Sep 17 00:00:00 2001 From: Jim Myhrberg Date: Sun, 16 Mar 2014 01:57:58 +0000 Subject: [PATCH] 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. --- stub.sh | 10 ++++++---- test/restore-test.sh | 12 ++++++++++++ 2 files changed, 18 insertions(+), 4 deletions(-) diff --git a/stub.sh b/stub.sh index 2288174..1061601 100644 --- a/stub.sh +++ b/stub.sh @@ -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 diff --git a/test/restore-test.sh b/test/restore-test.sh index 6eb9101..bd889d1 100755 --- a/test/restore-test.sh +++ b/test/restore-test.sh @@ -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()"