sstephenson / bats

Bash Automated Testing System
MIT License
7.12k stars 518 forks source link

Fail to test the return string #198

Open Aludirk opened 7 years ago

Aludirk commented 7 years ago

I have a function that return a string:

function say_hi() {
  eval "${1}=HI"
}

First, I test it with directly call the function:

@test "Test return value - success" {
  say_hi result
  [ "${result}" = "HI" ]
}

The test passes.

Then, I try to test it by using run:

@test "Test return value - fail" {
  run say_hi result
  [ "${result}" = "HI" ]
}

The test fails and I find that ${result} is empty.

What's wrong with that ?

dimo414 commented 7 years ago

Note say_hi doesn't "return a string", it sets the given variable to HI. If you set result you'll conflict with the behavior of run, which invokes your command in a subshell (thereby not setting the variable in the test's environment).

A simple example:

$ say_hi result

$ echo $result
HI

$ unset result

$ ( say_hi result )

$ echo $result # no output - $result isn't even set