Skip to content

setup and teardown per test function #91

Open
@pepdiz

Description

@pepdiz

Should be possible to have a setup and teardown functions associated to each test function?

AFAIK actually you have a setup function that is executed previously to each test and a teardown function executed after each test, but the setup and teardown functions are common to all tests.

This way you have to include the cleanup (or setup) for all tests in the same function even when certain cleanup (or setup) is not needed in certain tests.

As an example, supose I have a two tests, one require to create a file and then delete it, the other doesn't require anything:

test_test1 () {
  assert_equals 1 1
}

test_test2 () {
   F=$(mktemp -d)
   assert_status_code 0 "test -f $F"
   rm $F
}

the problem with this pattern is if exit code of assertion is not 0 it never executes the cleanup (here, the rm $F) .

The right way to do this is using setup and teardown functions, but since those functions are common for all tests you end up setting or cleaning things not needed for certain tests:

setup () {
  export F=$(mktemp -d)
}

teardown () {
  [ -f $F ] && rm $F
}

but since setup is executed for all tests it will create a file also for test 1 which is not needed and teardown will delete a file not needed to be created neither deleted.

This way I'm forced to take into account all cases in setup and teardown, for example if I add another test checking for directoy existence I would need a new variable and know in the test which one to use:

setup () {
  export F=$(mktemp)
  export D=$(mktemp -d)
}

teardown () {
  [ -f $F ] && rm $F
  [ -d $D ] && rm -rf $D 
}

test_test1 () {
  assert_equals 1 1
}

test_test2 () {
   assert_status_code 0 "test -f $F"
}

test_test3 () {
   assert_status_code 0 "test -d $D"
}

And everyting gets bloated quickly.

This would be solved if we have a setup and teardow funcion for each test function, maybe using a pattern such as "setup_$testname" and "teardown_$testname" for example:

setup_test2 () {
  export F=$(mktemp)
}

setup_test3 () {
  export F=$(mktemp -d)
}

teardown_test2 () {
  [ -f $F ] && rm $F
}

teardown_test3 () {
  [ -f $F ] && rm -rf $F
}

test_test1 () {
  assert_equals 1 1
}

test_test2 () {
   assert_status_code 0 "test -f $F"
}

test_test3 () {
   assert_status_code 0 "test -d $F"
}

In short what I asking for is setup and teardown functions associated to each individual test, similar to @beforeeach and @AfterEach in jUnit ( current setup and teardown would be similar to @BeforeAll and @afterall in jUnit )

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