From 5af71ab2fd782d1471a6a841253ee18fd5674c9f Mon Sep 17 00:00:00 2001 From: Jim Myhrberg Date: Wed, 19 Mar 2014 23:27:03 +0000 Subject: [PATCH] Add stub_called_times function --- stub.sh | 36 +++++++++++++++++++++++++++++++ test/stub_called_times-test.sh | 39 ++++++++++++++++++++++++++++++++++ 2 files changed, 75 insertions(+) create mode 100755 test/stub_called_times-test.sh diff --git a/stub.sh b/stub.sh index bc077ff..55fb9d5 100644 --- a/stub.sh +++ b/stub.sh @@ -114,6 +114,42 @@ stub_called() { } +# Public: Find out how many times a stub has been called. +# +# Arguments: +# - $1: Name of stubbed command. +# - $2: When specified, will check if stub was called exactly the given +# number of times (optional). +# +# Examples: +# stub_called_times "uname" # Echoes "2" if stub has been called twice. +# stub_called_times "uname" 2 # Returns value of 0 (success). +# stub_called_times "uname" 3 # Returns value of 1 (error). +# +# Echoes number of times stub has been called if $2 is not given, otherwise +# echoes nothing. +# Returns 0 (success) if $2 is not given, or if it is given and it matches the +# number of times the stub has been called. Otherwise 1 (error) is returned if +# it doesn't match.. +stub_called_times() { + local count=0 + + for called in ${STUB_CALLED_STUBS[@]}; do + if [ "$called" == "$1" ]; then + ((count++)) + fi + done + + if [ -n "$2" ]; then + if [ "$2" != "$count" ]; then + return 1 + fi + else + echo $count + fi +} + + # Public: Restore the original command/function that was stubbed. # # Arguments: diff --git a/test/stub_called_times-test.sh b/test/stub_called_times-test.sh new file mode 100755 index 0000000..b214d55 --- /dev/null +++ b/test/stub_called_times-test.sh @@ -0,0 +1,39 @@ +#! /usr/bin/env bash +source "test-helper.sh" + +# +# stub_called_times() tests. +# + +# Echoes 0 if the command isn't stubed. +assert 'stub_called_times "top"' "0" + +# Echoes the number of times a stub was called. +stub "uname" +assert 'stub_called_times "uname"' "0" +uname +assert 'stub_called_times "uname"' "1" +uname +assert 'stub_called_times "uname"' "2" +uname +assert 'stub_called_times "uname"' "3" +restore "uname" + +# Echoes 0 after a called stub has been restored. +stub "uname" +uname +assert 'stub_called_times "uname"' "1" +restore "uname" +assert 'stub_called_times "uname"' "0" + +# When given a second argument, asserts stub called X number of times. +stub "uname" +uname +assert_raises 'stub_called_times "uname" 1' 0 +assert 'stub_called_times "uname" 1' "" +assert_raises 'stub_called_times "uname" 3' 1 +assert 'stub_called_times "uname" 3' "" +restore "uname" + +# End of tests. +assert_end "stub_called_times()"