Search code examples
bashunit-testingbats-core

bats: source script with failing command


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.


Solution

  • 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!