Add refute assertion
diff --git a/README.md b/README.md index b341a8b..5636351 100644 --- a/README.md +++ b/README.md
@@ -73,6 +73,30 @@ ``` +### `refute` + +Fail if the given expression evaluates to true. + +***Note:*** *The expression must be a simple command. [Compound +commands][bash-comp-cmd], such as `[[`, can be used only when executed +with `bash -c`.* + +```bash +@test 'refute()' { + rm -f '/var/log/test.log' + refute [ -e '/var/log/test.log' ] +} +``` + +On failure, the successful expression is displayed. + +``` +-- assertion succeeded, but it was expected to fail -- +expression : [ -e /var/log/test.log ] +-- +``` + + ### `assert_equal` Fail if the two parameters, actual and expected value respectively, do
diff --git a/src/assert.bash b/src/assert.bash index 7f87dc6..78b8416 100644 --- a/src/assert.bash +++ b/src/assert.bash
@@ -71,6 +71,28 @@ fi } +# Fail and display the expression if it evaluates to true. +# +# NOTE: The expression must be a simple command. Compound commands, such +# as `[[', can be used only when executed with `bash -c'. +# +# Globals: +# none +# Arguments: +# $1 - expression +# Returns: +# 0 - expression evaluates to FALSE +# 1 - otherwise +# Outputs: +# STDERR - details, on failure +refute() { + if "$@"; then + batslib_print_kv_single 10 'expression' "$*" \ + | batslib_decorate 'assertion succeeded, but it was expected to fail' \ + | fail + fi +} + # Fail and display details if the expected and actual values do not # equal. Details include both values. #
diff --git a/test/50-assert-19-refute.bats b/test/50-assert-19-refute.bats new file mode 100755 index 0000000..191dc73 --- /dev/null +++ b/test/50-assert-19-refute.bats
@@ -0,0 +1,18 @@ +#!/usr/bin/env bats + +load test_helper + +@test 'refute() <expression>: returns 0 if <expression> evaluates to FALSE' { + run refute false + [ "$status" -eq 0 ] + [ "${#lines[@]}" -eq 0 ] +} + +@test 'refute() <expression>: returns 1 and displays <expression> if it evaluates to TRUE' { + run refute true + [ "$status" -eq 1 ] + [ "${#lines[@]}" -eq 3 ] + [ "${lines[0]}" == '-- assertion succeeded, but it was expected to fail --' ] + [ "${lines[1]}" == 'expression : true' ] + [ "${lines[2]}" == '--' ] +}