Skip to content

Commit 09ea300

Browse files
committed
Ensure @teardown function is run when a test fails or errors
1 parent 55c35c7 commit 09ea300

File tree

2 files changed

+13
-11
lines changed

2 files changed

+13
-11
lines changed

src/commands/run.zsh

Lines changed: 13 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -77,14 +77,22 @@ function _zunit_execute_test() {
7777
# and the error will be reported back to the test runner
7878
setopt ERR_EXIT
7979
80+
# Add an exit handler which calls the teardown function if it is
81+
# defined and the test exits early
82+
if (( \$+functions[__zunit_test_teardown] )); then
83+
zshexit() {
84+
__zunit_test_teardown >/dev/null 2>&1
85+
}
86+
fi
87+
8088
# Create some local variables to store test state in
8189
integer _zunit_assertion_count=0
8290
integer state
8391
local output
8492
typeset -a lines
8593
8694
# If a setup function is defined, run it now
87-
if (( $+functions[__zunit_test_setup] )); then
95+
if (( \$+functions[__zunit_test_setup] )); then
8896
__zunit_test_setup >/dev/null 2>&1
8997
fi
9098
@@ -93,10 +101,13 @@ function _zunit_execute_test() {
93101
${body}
94102
95103
# If a teardown function is defined, run it now
96-
if (( $+functions[__zunit_test_teardown] )); then
104+
if (( \$+functions[__zunit_test_teardown] )); then
97105
__zunit_test_teardown >/dev/null 2>&1
98106
fi
99107
108+
# Remove the error handler
109+
zshexit() {}
110+
100111
# Check the assertion count, and if it is 0, return
101112
# the warning exit code
102113
[[ \$_zunit_assertion_count -gt 0 ]] || return 248
@@ -127,7 +138,6 @@ function _zunit_execute_test() {
127138
return 126
128139
fi
129140

130-
131141
# Check if a time limit has been specified. We only do this if
132142
# the ZSH version is at least 5.1.0, since older versions of ZSH
133143
# are unable to handle asynchronous processes in the way we need

tests/run.zunit

Lines changed: 0 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,5 @@
11
#!/usr/bin/env zunit
22

3-
@setup {
4-
echo 'Testing setup method'
5-
}
6-
7-
@teardown {
8-
echo 'Testing teardown method'
9-
}
10-
113
@test 'Test successful command' {
124
run return 0
135

0 commit comments

Comments
 (0)