mirror of
https://github.com/jimeh/stub.sh.git
synced 2026-02-19 05:36:39 +00:00
Add stub_called_times function
This commit is contained in:
36
stub.sh
36
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:
|
||||
|
||||
39
test/stub_called_times-test.sh
Executable file
39
test/stub_called_times-test.sh
Executable file
@@ -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()"
|
||||
Reference in New Issue
Block a user