diff --git a/CHANGELOG.md b/CHANGELOG.md index 3e5b926a..605cdc3f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,8 @@ ## [Unreleased](https://github.com/TypedDevs/bashunit/compare/0.11.0...main) +- Add `fail()` function + ## [0.11.0](https://github.com/TypedDevs/bashunit/compare/0.10.1...0.11.0) - 2024-03-02 - Add `--upgrade` option to `./bashunit` diff --git a/docs/assertions.md b/docs/assertions.md index bda8b60f..ee9990c1 100644 --- a/docs/assertions.md +++ b/docs/assertions.md @@ -856,3 +856,24 @@ function test_failure() { } ``` ::: + +## fail +> `fail "failure message"` + +Unambiguously reports an error message. Useful for reporting specific message +when testing situations not covered by any `assert_*` functions. + +::: code-group +```bash [Example] +function test_success() { + if [ "$(date +%-H)" -gt 25 ]; then + fail "Something is very wrong with your clock" + fi +} +function test_failure() { + if [ "$(date +%-H)" -lt 25 ]; then + fail "This test will always fail" + fi +} +``` +::: diff --git a/src/assert.sh b/src/assert.sh index 0dc5969f..c3448352 100755 --- a/src/assert.sh +++ b/src/assert.sh @@ -1,5 +1,13 @@ #!/bin/bash +function fail() { + local message=$1 + local label="${2:-$(helper::normalize_test_function_name "${FUNCNAME[1]}")}" + + state::add_assertions_failed + console_results::print_failure_message "${label}" "$message" +} + function assert_equals() { local expected="$1" local actual="$2" diff --git a/src/console_results.sh b/src/console_results.sh index c3deb958..0a45f96a 100644 --- a/src/console_results.sh +++ b/src/console_results.sh @@ -131,6 +131,16 @@ function console_results::print_successful_test() { fi } +function console_results::print_failure_message() { + local test_name=$1 + local failure_message=$2 + + printf "\ +${_COLOR_FAILED}✗ Failed${_COLOR_DEFAULT}: %s + ${_COLOR_FAINT}Message:${_COLOR_DEFAULT} ${_COLOR_BOLD}'%s'${_COLOR_DEFAULT}\n"\ + "${test_name}" "${failure_message}" +} + function console_results::print_failed_test() { local test_name=$1 local expected=$2 diff --git a/tests/unit/assert_test.sh b/tests/unit/assert_test.sh index 34d48a05..f55466ed 100644 --- a/tests/unit/assert_test.sh +++ b/tests/unit/assert_test.sh @@ -1,5 +1,15 @@ #!/bin/bash +function test_successful_fail() { + true || fail "This cannot fail" +} + +function test_unsuccessful_fail() { + assert_equals\ + "$(console_results::print_failure_message "Unsuccessful fail" "Failure message")"\ + "$(fail "Failure message")" +} + function test_successful_assert_equals() { assert_empty "$(assert_equals "1" "1")" }