Skip to content

How to manage inter-test global variables? #60

Open
@marco-brandizi

Description

@marco-brandizi

I've just discovered bash_unit and it's great!

However, I've a problem: how to manage stateful variables, which keep their value across tests?
For instance, this isn't working:

echo "Code outside functions"
# Neither this works: export CTR=1

function setup_suite () {
  echo "All tests begin here"
  CTR=1
}

function teardown_suite () {
  echo "That's all, Folks!"
}

function setup () {
  CTR=$(($CTR+1))
  echo "--- Test Count $CTR"
}

function test_ctr () {
  echo "CTR is $CTR"
  assert_equals 2 $CTR "Wrong test counter!"
}

function test_ctr_1 () {
  echo "CTR is $CTR"
  assert_equals 3 $CTR "Wrong test counter!"
}

Results are:

$ bash_unit test_globals.sh
Running tests in test_globals.sh
Code outside functions
All tests begin here
--- Test Count 2
Running test_ctr... CTR is 2
SUCCESS ✓
--- Test Count 2
Running test_ctr_1... CTR is 2
FAILURE ✗
Wrong test counter!
 expected [3] but was [2]
test_globals.sh:25:test_ctr_1()
That's all, Folks!
$ 

What I would like to do is to see that CTR counts the tests. I know interfering tests are bad practice, but there might be cases like this (keeping a counter of done things, keeping a timestamp of the last operation, etc) and it would be good to have them working, somehow (some set_env function managed by bash_unit?). The only way I've found so far is to use temp files to store the values of variables like CTR, which is not exactly practical.

Note that this can be done shunit2 (but I prefer bash_unit, mainly cause it supports TAP format).

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions