diff --git a/CHANGELOG.md b/CHANGELOG.md index 15809500..b811f34d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,7 @@ - Add multi-invokers; consolidate parameterized-testing documentation - Add `fail()` function +- Remove all test mocks after each test case ## [0.11.0](https://github.com/TypedDevs/bashunit/compare/0.10.1...0.11.0) - 2024-03-02 diff --git a/docs/test-doubles.md b/docs/test-doubles.md index c74bd1df..d8008453 100644 --- a/docs/test-doubles.md +++ b/docs/test-doubles.md @@ -25,7 +25,7 @@ Allows you to override the output of a callable. ```bash [Example] function test_example() { function code() { - ps a | grep bash + ps a | grep bash } mock ps<&1 1>&3 runner::run_tear_down + runner::clear_mocks state::export_assertions_count ) @@ -228,6 +230,12 @@ function runner::run_tear_down() { helper::execute_function_if_exists 'tear_down' } +function runner::clear_mocks() { + for i in "${!MOCKED_FUNCTIONS[@]}"; do + unmock "${MOCKED_FUNCTIONS[$i]}" + done +} + function runner::run_tear_down_after_script() { helper::execute_function_if_exists 'tear_down_after_script' } diff --git a/src/test_doubles.sh b/src/test_doubles.sh index e59ffdff..5a624983 100644 --- a/src/test_doubles.sh +++ b/src/test_doubles.sh @@ -1,5 +1,19 @@ #!/bin/bash +declare -a MOCKED_FUNCTIONS=() + +function unmock() { + local command=$1 + + for i in "${!MOCKED_FUNCTIONS[@]}"; do + if [[ "${MOCKED_FUNCTIONS[$i]}" == "$command" ]]; then + unset "MOCKED_FUNCTIONS[$i]" + unset -f "$command" + break + fi + done +} + function mock() { local command=$1 shift @@ -11,6 +25,8 @@ function mock() { fi export -f "${command?}" + + MOCKED_FUNCTIONS+=("$command") } function spy() { @@ -24,6 +40,8 @@ function spy() { eval "function $command() { ${variable}_params=(\"\$*\"); ((${variable}_times++)) || true; }" export -f "${command?}" + + MOCKED_FUNCTIONS+=("$command") } function assert_have_been_called() { diff --git a/tests/acceptance/mock_test.sh b/tests/acceptance/mock_test.sh new file mode 100644 index 00000000..fab44b83 --- /dev/null +++ b/tests/acceptance/mock_test.sh @@ -0,0 +1,19 @@ +#!/bin/bash + +# +# Make sure that the `runner::clear_mocks()` is being called, +# removing the mocks and spies from the first test +# +function test_runner_clear_mocks_first() { + mock ls echo foo + assert_equals "foo" "$(ls)" + + spy ps + ps foo bar + assert_have_been_called_times 1 ps +} + +function test_runner_clear_mocks_second() { + assert_not_equals "foo" "$(ls)" + assert_have_been_called_times 0 ps +}