Skip to content

Instantly share code, notes, and snippets.

@dansimau
Created April 10, 2017 07:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dansimau/9582eb1d415bbc74dc0e9bc37c4ac4b2 to your computer and use it in GitHub Desktop.
Save dansimau/9582eb1d415bbc74dc0e9bc37c4ac4b2 to your computer and use it in GitHub Desktop.
Run `go test`, only displaying error output, plus print counts of all tests passed/failed/etc.
#!/bin/bash
#
# Runs `go test -v`, parses the output and only displays errors. Also displays
# a summary of tests passed/failed/skipped/etc.
#
set -o pipefail
declare buffer=
declare test_error=false
declare -a go_args
declare -i run=0
declare -i passed=0
declare -i failed=0
declare -i skipped=0
declare -i errors=0
declare -i races=0
#
# Add lines to the buffer.
#
_add_to_buffer() {
for data in "$@"; do
buffer="$buffer"$'\n'"$data"
done
}
#
# Print the contents of the current buffer if there was a test error.
#
_print_last_test_error() {
if $test_error; then
echo "$buffer" >&2
fi
}
#
# Print counts of all tests run and their results.
#
_print_tests_summary() {
echo
echo "# tests: $run"
[ $passed -ne 0 ] && echo "# passed: $passed"
[ $failed -ne 0 ] && echo "# failed: $failed"
[ $skipped -ne 0 ] && echo "# skipped: $skipped"
[ $errors -ne 0 ] && echo "# errors: $errors"
[ $races -ne 0 ] && echo "# races: $races"
echo
}
#
# Takes the output of "go test -v" but only capture errors.
#
_capture() {
while IFS= read -r line; do
case $line in
"=== RUN"*)
# Beginning of new test...
run=$(($run+1))
# If there was an error during the last test, print the error
# before resetting.
_print_last_test_error
test_error=false
buffer=
;;
"--- PASS:"*)
passed=$(($passed+1))
;;
"--- FAIL:"*)
failed=$(($failed+1))
test_error=true
;;
"--- SKIP:"*)
skipped=$(($skipped+1))
;;
# Compile errors
"FAIL"*"[setup failed]")
errors=$(($errors+1))
test_error=true
;;
# Data races
"WARNING: DATA RACE"*)
races=$(($races+1))
test_error=true
;;
ok*)
echo "$line"
;;
esac
_add_to_buffer "$line"
done
# Case where compile errors cause no tests to run at all; we want to see
# the complete output.
if [ $run -eq 0 ]; then
test_error=true
fi
_print_last_test_error
_print_tests_summary
}
# Collect extra args to pass to go, except for -v, which we are already passing
for arg in "$@"; do
if [ "$arg" == "-v" ]; then
continue
fi
go_args+=("$arg")
done
go test -v "${go_args[@]}" 2>&1 |_capture
# Exit with return code from go
exit $PIPESTATUS
@YZSY520
Copy link

YZSY520 commented Apr 10, 2017

Very good.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment