How to `trap` in `bats`?

140 Views Asked by At

I have the following in some of my tests:

tmpdir=$(mktemp -d)
trap 'echo @@@@@@@@@@@@@@@@@@@ >&3' INT TERM HUP EXIT # trap is really meant to `rm -rf ${tmpdir}`

I'm expecting the echo to be executed but not seeing the output.

What do my tests need to do to clean up after themselves?

2

There are 2 best solutions below

0
On

bats does not support tests with trap.

What can be done is:

setup() {
  BATS_TMPDIR="$(mktemp -d)"
}

teardown() {
  rm -rf "${BATS_TMPDIR}"
}

If you're like me and have temporary directories that are created inside functions, the following can then be used: tmpdir="$(mktemp -d --tmpdir="${BATS_TMPDIR}")". That will get cleaned up when ${BATS_TMPDIR} is cleaned up in the teardown function.

0
On

I just did this with the desired outcome:

trap '[ "${FUNCNAME[0]}" == "$BATS_TEST_NAME" ] && echo yo' ERR

Where the echo yo does cleanup and is also present in the code, as this just gets error cases. The check on function name excludes traps firing early, e.g. in anything under run or calls to underlying functions.

RETURN didn't execute in case of errors. EXIT caused the test not to run at all.

:S