grayhemp / bats-mock

Mocking for Bats
The Unlicense
43 stars 10 forks source link

`set -u` is not supported #8

Closed srcbucket closed 3 years ago

srcbucket commented 3 years ago

bats-mock fails if optional arguments to getter or setter functions are omitted and the expansion of unset variables / parameters is not allowed (that is, when set -u is used).

Some people are using set -euo pipefail in scripts to enforce a clean coding style. Sourcing such a script for testing may break tests using bats-mock.

How to reproduce:

#!/usr/bin/env bats

load bats-mock/src/bats-mock

setup() {
        mock="$(mock_create)"
        "${mock}"
}

@test "mock_get_call_args() with omitted optional argument succeeds when expansion of unset arguments is allowed" {
        set +u

        run mock_get_call_args "${mock}"

        [[ "${status}" -eq 0 ]]
}

@test "mock_get_call_args() with omitted optional argument fails with unbound variable error when expansion of unset arguments is not allowed" {
        set -u

        run mock_get_call_args "${mock}"

        [[ "${status}" -ne 0 ]]
        [[ "${output}" =~ '/bats-mock.bash: line '[0-9]*': $2: unbound variable' ]]
}

Workaround:

Instead of

        [[ "$(mock_get_call_args "${mock}")" -ne 0 ]]

use

        [[ "$(set +u; mock_get_call_args "${mock}")" -ne 0 ]]

Possible Solution: Use ${2-} instead of $2 (provided $2 is optional).

Example (from mock_get_call_args):

  n="$(mock_default_n ${mock} ${2-})" || exit "$?"