Where to modify Bats (Bash Automated Testing System) Variables

130 Views Asked by At

I'm using Bats (Bash Automated Testing System) to automate some bash unit testing. Some of these bash tests might hang forever, so I want some global timeout on my tests. I want to achieve this in my .bats file.

I'm trying set a timeout on all of my tests in my .bats file. I read the documentation provided by the bats wiki and found the $BATS_TEST_TIMEOUT variable, which is exactly what I need. I set the variable in my setup_file() as follows:

setup_file(){
    BATS_TEST_TIMEOUT=5
}

@test "Dummy Loop test" {
    ./loop.sh
}

but my dummy infinite loop test still ran forever. Blocked by this, I tried setting other variables, like $BATS_TEST_RETRIES, and that didn't work either. I've drawn the conclusion that I must be setting them incorrectly somehow. Any ideas?

2

There are 2 best solutions below

3
On BEST ANSWER

Those variables must be set in the environment of the bats process itself, so you can:

export BATS_TEST_TIMEOUT=5
bats .

Or:

BATS_TEST_TIMEOUT=5 bats .

Etc.

For example, given this test in mytest.bats:

@test "Dummy sleep test" {
    sleep 30
}

If I run bats like this:

BATS_TEST_TIMEOUT=5 bats .

I see:

./mytest.bats
 ✗ Dummy sleep test [timeout: 5s]
   (in test file ./mytest.bats, line 6)
     `sleep 30' failed due to timeout
   Terminated

1 test, 0 failures, 1 timed out

If you don't want to have to set this every time, add some sort of run-tests.sh script to your project that sets whatever variables you want and then calls bats.

0
On

On top of @larsks' answer, I found that bats variables can indeed be set in the setup_file(), they just need to be exported also.

For example:

setup_file(){
    export BATS_TEST_TIMEOUT=5
}

@test "Dummy Loop" {
    ./dummy.sh # This will timeout after 5 seconds
}