Skip to content

Commit 3bf7886

Browse files
jrngitster
authored andcommitted
test-lib: Let tests specify commands to be run at end of test
Certain actions can imply that if the test fails early, recovery from within other tests is too much to expect: - creating unwritable directories, like the EACCESS test in t0001-init - setting unusual configuration, like user.signingkey in t7004-tag - crashing and leaving the index lock held, like t3600-rm once did Some test scripts work around this by running cleanup actions outside the supervision of the test harness, with the unfortunate consequence that those commands are not appropriately echoed and their output not suppressed. Others explicitly save exit status, clean up, and then reset the exit status within the tests, which has excellent behavior but makes the tests hard to read. Still others ignore the problem. Allow tests a fourth option: by calling this function, tests can stack up commands they would like to be run to clean up. Commands passed to test_when_finished during a test are unconditionally run in the test environment immediately before the test is completed, in last-in-first-out order. If some cleanup command fails, then the other cleanup commands are still run before the failure is reported and the test script allowed to continue. Signed-off-by: Jonathan Nieder <[email protected]> Signed-off-by: Junio C Hamano <[email protected]>
1 parent 6b6f5d4 commit 3bf7886

File tree

1 file changed

+27
-1
lines changed

1 file changed

+27
-1
lines changed

t/test-lib.sh

Lines changed: 27 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -366,8 +366,9 @@ test_debug () {
366366
}
367367

368368
test_run_ () {
369+
test_cleanup='eval_ret=$?'
369370
eval >&3 2>&4 "$1"
370-
eval_ret="$?"
371+
eval >&3 2>&4 "$test_cleanup"
371372
return 0
372373
}
373374

@@ -545,6 +546,31 @@ test_cmp() {
545546
$GIT_TEST_CMP "$@"
546547
}
547548

549+
# This function can be used to schedule some commands to be run
550+
# unconditionally at the end of the test to restore sanity:
551+
#
552+
# test_expect_success 'test core.capslock' '
553+
# git config core.capslock true &&
554+
# test_when_finished "git config --unset core.capslock" &&
555+
# hello world
556+
# '
557+
#
558+
# That would be roughly equivalent to
559+
#
560+
# test_expect_success 'test core.capslock' '
561+
# git config core.capslock true &&
562+
# hello world
563+
# git config --unset core.capslock
564+
# '
565+
#
566+
# except that the greeting and config --unset must both succeed for
567+
# the test to pass.
568+
569+
test_when_finished () {
570+
test_cleanup="eval_ret=\$?; { $*
571+
} && (exit \"\$eval_ret\"); $test_cleanup"
572+
}
573+
548574
# Most tests can use the created repository, but some may need to create more.
549575
# Usage: test_create_repo <directory>
550576
test_create_repo () {

0 commit comments

Comments
 (0)