#!/usr/bin/env bash
#
# @file    junit-failing-stderr.bash.failing - Tests the junit reporter's
#          ability to propogate the stdout and stderr of failing `.bash` tests.
#
#          `.failing`: the JUnit reporter prints a vauge and misleading failure
#          message for failing `.bash` tests, ignoring both its stdout and
#          stderr.
#
# @author  Bryan Hoang <bryan@distributive.network>
# @date    Nov. 2023

set -e
set -u

### Arrange

cd "$(dirname "$0")"

TEST_FILE_NAME="$(basename "$0")"
TEST_NAME=${TEST_FILE_NAME%.*}
JUNIT_FILE_NAME=${TMPDIR:-/tmp}/${TEST_NAME}-$$-report.xml
FAILURE_OPENING_TAG='<failure message="failure" type="ERROR">'
# See the test fixture `../../tests-libexec/this-better-not-pass.bash`.
EXPECTED_STDERR='This message is logged to stderr.'

### Act

../../peter --junit="$JUNIT_FILE_NAME" ../../tests-libexec/this-better-not-pass.bash \
	>/dev/null 2>&1 || true

### Assert

set +e
grep --fixed-strings "$EXPECTED_STDERR" "$JUNIT_FILE_NAME" >/dev/null
STDERR_TEST_RESULT=$?
[[ $STDERR_TEST_RESULT == 0 ]]
TEST_RESULT=$?
set -e

if [[ $STDERR_TEST_RESULT != 0 ]]; then
	echo "Test failed to find expected stderr in $JUNIT_FILE_NAME" >&2
	actual_text=$(grep "^stderr: " "$JUNIT_FILE_NAME" >&2 || true)
	expected_text="$EXPECTED_STDERR"
	diff --unified --label=Actual <(echo "$actual_text") --label=Expected <(echo "$expected_text") \
    >&2 || true
fi

if [[ $TEST_RESULT == 0 ]]; then
	echo 'Test passed!'
fi

# Preserve the test artifact while debugging the test.
if [[ -z ${DEBUG:-} ]]; then
	rm "$JUNIT_FILE_NAME"
fi

exit "$TEST_RESULT"
