1
0
mirror of https://github.com/sstephenson/bats.git synced 2024-11-17 11:42:33 +01:00

Capture stdout/stderr during tests and display it for failures

This commit is contained in:
Sam Stephenson 2011-12-28 23:50:49 -06:00
parent a4c16fecef
commit e9d3143fdb
3 changed files with 50 additions and 12 deletions

View File

@ -29,11 +29,6 @@ run() {
[ -z "$e" ] || set -e [ -z "$e" ] || set -e
} }
abort() {
[ "$#" -eq 0 ] || echo error: "$@" >&2
exit 1
}
setup() { setup() {
true true
} }
@ -54,19 +49,25 @@ bats_test_function() {
bats_teardown_trap() { bats_teardown_trap() {
trap bats_exit_trap err exit trap bats_exit_trap err exit
teardown teardown >>"$BATS_OUT" 2>&1
bats_exit_trap bats_exit_trap
} }
bats_exit_trap() { bats_exit_trap() {
local status
trap - err exit trap - err exit
if [ -z "$BATS_TEST_COMPLETED" ]; then if [ -z "$BATS_TEST_COMPLETED" ]; then
echo "not ok $BATS_TEST_NUMBER $BATS_TEST_DESCRIPTION" echo "not ok $BATS_TEST_NUMBER $BATS_TEST_DESCRIPTION" >&3
exit 1 sed -e "s/^/ /" < "$BATS_OUT" >&3
status=1
else else
echo "ok $BATS_TEST_NUMBER $BATS_TEST_DESCRIPTION" echo "ok $BATS_TEST_NUMBER $BATS_TEST_DESCRIPTION" >&3
exit 0 status=0
fi fi
rm -f "$BATS_OUT"
exit "$status"
} }
bats_perform_tests() { bats_perform_tests() {
@ -91,8 +92,9 @@ bats_perform_test() {
BATS_TEST_COMPLETED="" BATS_TEST_COMPLETED=""
trap bats_teardown_trap err exit trap bats_teardown_trap err exit
setup { setup
"$BATS_TEST_NAME" "$BATS_TEST_NAME"
} >>"$BATS_OUT" 2>&1
BATS_TEST_COMPLETED=1 BATS_TEST_COMPLETED=1
else else
@ -101,6 +103,15 @@ bats_perform_test() {
fi fi
} }
if [ -z "$TMPDIR" ]; then
BATS_TMPDIR="/tmp"
else
BATS_TMPDIR="${TMPDIR%/}"
fi
BATS_OUT="$BATS_TMPDIR/bats.$(date "+%Y%m%d%H%M%S").$$"
exec 3<&1
eval "$(bats-preprocess < "$BATS_TEST_FILENAME")" eval "$(bats-preprocess < "$BATS_TEST_FILENAME")"
if [ "$#" -eq 0 ]; then if [ "$#" -eq 0 ]; then

View File

@ -72,3 +72,11 @@ teardown() {
run bats "$FIXTURE_ROOT/load.bats" run bats "$FIXTURE_ROOT/load.bats"
[ $status -eq 0 ] [ $status -eq 0 ]
} }
@test "output is discarded for passing tests and printed for failing tests" {
run bats "$FIXTURE_ROOT/output.bats"
[ $status -eq 1 ]
[ "${lines[4]}" = " failure stdout 1" ]
[ "${lines[5]}" = " failure stdout 2" ]
[ "${lines[7]}" = " failure stderr" ]
}

19
test/fixtures/output.bats vendored Normal file
View File

@ -0,0 +1,19 @@
@test "success writing to stdout" {
echo "success stdout 1"
echo "success stdout 2"
}
@test "success writing to stderr" {
echo "success stderr" >&2
}
@test "failure writing to stdout" {
echo "failure stdout 1"
echo "failure stdout 2"
false
}
@test "failure writing to stderr" {
echo "failure stderr" >&2
false
}