sstephenson / bats

Bash Automated Testing System
MIT License
7.13k stars 517 forks source link

Add bats_teardown_trap to existing EXIT trap instead of overwriting. #272

Open mfickett opened 4 years ago

mfickett commented 4 years ago

Please consider adding to any existing signal traps rather than simply replacing them. There are some examples on StackOverflow of how to do this, such as:

trap_add() {
    trap_add_cmd=$1; shift || fatal "${FUNCNAME} usage error"
    new_cmd=
    for trap_add_name in "$@"; do
        # Grab the currently defined trap commands for this trap
        existing_cmd=`trap -p "${trap_add_name}" |  awk -F"'" '{print $2}'`

        # Define default command
        [ -z "${existing_cmd}" ] && existing_cmd="echo exiting @ `date`"

        # Generate the new command
        new_cmd="${existing_cmd};${trap_add_cmd}"

        # Assign the test
         trap   "${new_cmd}" "${trap_add_name}" || \
                fatal "unable to add to trap ${trap_add_name}"
    done
}

This came up for me because I'm starting a local fake backend for my tests to hit. I start it as a background process, and I want to clean it up when tests are done. Within a single test I can do something like trap_add and setup/teardown my local backend within the test, but it would be great if BATS took care of it.

(In the context of a whole test suite it's actually OK, because I set up my local backend outside of BATS and then tests run as subshells with separate traps.)

xmik commented 4 years ago

Just FYI, this project is not maintained anymore, see https://github.com/sstephenson/bats/issues/236