BATS: make variable persistent across all tests
I am writing a BATS (Bash Automated Testing System) script and I would like a variable to be persisted across all tests. For example:
#!/usr/bin/env bats
# Generate random port number
port_num=$(shuf -i 2000-65000 -n 1)
@test "Test number one" {
a = $port_num
}
@test "Test number two" {
b = $port_num
}
When evaluating a and b must be equal to each other. However, this won't work because (according to the docs) the entire file is evaluated after every test run. This means that $ port_num is restored between tests. Is there a way / place to store variables that will persist for all tests?
source to share
Export it as an environment variable.
# If ENV Var $port_num doesn't exist, set it.
if [ -z "$port_num" ]; then
export port_num=$(shuf -i 2000-65000 -n 1)
fi
As BATS
you must call load
in order to download the file.
Place the above code in a file named port.bash
in the directory you are executing from.
Then call before your functions load port
. This will create yours $port_num
once and won't change it.
load port
@test "Test number one" {
a = $port_num
}
@test "Test number two" {
b = $port_num
}
source to share