Skip to content

Commit

Permalink
Merge pull request #249 from ceejatec/add-fail
Browse files Browse the repository at this point in the history
chore: add fail() function
  • Loading branch information
Chemaclass authored Apr 25, 2024
2 parents 675fd42 + fc2be50 commit 8021b2f
Show file tree
Hide file tree
Showing 5 changed files with 51 additions and 0 deletions.
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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`
Expand Down
21 changes: 21 additions & 0 deletions docs/assertions.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
```
:::
8 changes: 8 additions & 0 deletions src/assert.sh
Original file line number Diff line number Diff line change
@@ -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"
Expand Down
10 changes: 10 additions & 0 deletions src/console_results.sh
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
10 changes: 10 additions & 0 deletions tests/unit/assert_test.sh
Original file line number Diff line number Diff line change
@@ -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")"
}
Expand Down

0 comments on commit 8021b2f

Please sign in to comment.