From f904b0c65b66356d129be96ca235a61406e0dfa1 Mon Sep 17 00:00:00 2001 From: cassapi Date: Sun, 7 Jul 2024 19:09:25 +0200 Subject: [PATCH] feat: allow a forced unstub mode without plans validation --- README.md | 3 +++ stub.bash | 5 ++++- test/stub.bats | 37 +++++++++++++++++++++++++++++++++++++ 3 files changed, 44 insertions(+), 1 deletion(-) create mode 100644 test/stub.bats diff --git a/README.md b/README.md index 2d738ee..d738601 100644 --- a/README.md +++ b/README.md @@ -107,6 +107,9 @@ Finally, when the stub is removed with `unstub`, there is a final check to ensure there are no remaining un-met plans (which would indicated an expected invocation that did not occur). +You can force to `unstub` without validation of expected plans with +`unstub true`. + ### Unstubbing Once the test case is done, diff --git a/stub.bash b/stub.bash index 0a71cf4..ff2d82d 100644 --- a/stub.bash +++ b/stub.bash @@ -32,6 +32,7 @@ stub_repeated() { unstub() { local program="$1" + local force="${2:-false}" local prefix prefix="$(echo "$program" | tr a-z- A-Z_)" local path="${BATS_MOCK_BINDIR}/${program}" @@ -39,7 +40,9 @@ unstub() { export "${prefix}_STUB_END"=1 local STATUS=0 - "$path" || STATUS="$?" + if [ "$force" != 'true' ]; then + "$path" || STATUS="$?" + fi rm -f "$path" rm -f "${BATS_MOCK_TMPDIR}/${program}-stub-plan" "${BATS_MOCK_TMPDIR}/${program}-stub-run" diff --git a/test/stub.bats b/test/stub.bats new file mode 100644 index 0000000..93f2ba5 --- /dev/null +++ b/test/stub.bats @@ -0,0 +1,37 @@ +#!/usr/bin/env bats + +# this is the "code under test" +# it would normally be in another file +format_date() { + date -r 222 +} + +setup() { + load '../load' + _DATE_ARGS='-r 222' +} + +@test "date format util formats date with expected arguments" { + stub date \ + "${_DATE_ARGS} : echo 'I am stubbed!'" \ + "${_DATE_ARGS} : echo 'Wed Dec 31 18:03:42 CST 1969'" + + result="$(format_date)" + [ "$result" == 'I am stubbed!' ] + + result="$(format_date)" + [ "$result" == 'Wed Dec 31 18:03:42 CST 1969' ] + + unstub date +} + +@test "unstub forced not enough invocations" { + stub date \ + "${_DATE_ARGS} : echo 'I am stubbed!'" \ + "${_DATE_ARGS} : echo 'Wed Dec 31 18:03:42 CST 1969'" + + result="$(format_date)" + [ "$result" == 'I am stubbed!' ] + + unstub date true +}