1

I want to test this functions.sh:

#!/usr/bin/env bash

function func {
    false # bats should ignore this
    return 0
}

with this unit test:

#!/usr/bin/env bats

@test "test func" {
    source ./functions.sh
    func
}

bats fails with

 ✗ test func
   (from function `func' in file ./functions.sh, line 4,
    in test file test.sh, line 5)
     `func' failed

though, despite the function returning 0.

How can I source a script, which has functions with lines, which fail? Instead of false, it could be a test with grep.

elsamuko
  • 668
  • 6
  • 16
  • Related to https://unix.stackexchange.com/questions/235017/set-e-and-grep-idiom-for-preventing-premature-exit-from-shell-script-when-p – elsamuko Apr 04 '23 at 13:03
  • See also https://stackoverflow.com/questions/19622198/what-does-set-e-mean-in-a-bash-script/53612582#53612582 – tripleee Apr 05 '23 at 04:54

1 Answers1

1

I found a solution, here is a related question.

Since bats runs with -e, the sourcing immediately fails, if a line in the sourced script fails.

To solve this, you can either wrap the failing command with if ...;then
or assign it with F=$(...) || true.

functions.sh looks like this now:

#!/usr/bin/env bash

function func {
    if ! false; then
        echo "false"
    fi
    F=$(false) || true
    return 0
}

Docs: https://manpages.org/set

Thanks to larsks for hinting the solution!

elsamuko
  • 668
  • 6
  • 16
  • 1
    Also see [BashFAQ/105 (Why doesn't set -e (or set -o errexit, or trap ERR) do what I expected?)](https://mywiki.wooledge.org/BashFAQ/105), [What is the proper way to detect shell exit code when errexit option set](https://stackoverflow.com/q/9629710/4154375), and [Bash ignoring error for a particular command](https://stackoverflow.com/q/11231937/4154375). – pjh Apr 04 '23 at 13:35
  • Why not `false || true` or `! false` (or `false || :` if you like brevity, but still want to be explicit) to consume the exit code? That would clutter your source a lot less. Where does `F` come from, it is not part of the original question? – knittl Apr 04 '23 at 15:43