#!/bin/sh
name="unittest"
version="1.1"
help_message=$(/usr/bin/cat <<-EOF
Wrapper around Python's 'unittest' module
Usage: unittest TARGET [OPTIONS]
Options:
-c, --color print with color
-h, --help print this message and exit
-v, --verbose show verbose 'unittest' output
-V, --version print version number and exit
-d, --working-directory working directory for tests
EOF
)
target=""
single_target=0
color=0
verbose=0
working_directory="."
python_executable="/usr/bin/env python3"
while [ "$#" -gt 0 ]; do
case "$1" in
-c|--color)
color=1
shift
;;
-h|--help)
/usr/bin/printf "%s\n" "$help_message"
exit 0
;;
-d|--working-directory)
working_directory="$2"
shift
shift
;;
-v|--verbose)
verbose=1
shift
;;
-V|--version)
/usr/bin/printf "%s %s\n" "$name" "$version"
exit 0
;;
*)
if [ -z "$target" ]; then
target="$1"
fi
shift
;;
esac
done
# unittest subroutine
unittest_subroutine() {
if [ "$single_target" -eq 1 ]; then
unittest_single_subroutine
else
unittest_discover_subroutine
fi
}
# unittest single subroutine
unittest_single_subroutine() {
if [ "$verbose" -eq 1 ]; then
if ! $python_executable -m unittest -v "$target" 2>&1; then
code=1
fi
else
if ! $python_executable -m unittest "$target" 2>&1 \
| /usr/bin/tail -n 1; then
code=1
fi
fi
}
# unittest discover subroutine
unittest_discover_subroutine() {
if [ "$verbose" -eq 1 ]; then
if ! $python_executable -m unittest discover -v \
-s "$target" -t "$working_directory" 2>&1; then
code=1
fi
else
if ! $python_executable -m unittest discover \
-s "$target" -t "$working_directory" 2>&1 \
| /usr/bin/tail -n 1; then
code=1
fi
fi
}
error_msg() {
(>&2 /usr/bin/printf "%s: %s\n" "$name" "$1")
}
# check directory
if [ -z "${target+x}" ]; then
(>&2 /usr/bin/printf "Usage: unittest TARGET [OPTIONS]\n")
exit 1
elif [ ! -d "$target" ]; then
if /usr/bin/printf "%s\n" "$target" | grep -q -e ".*\.py"; then
single_target=1
else
error_msg "No such directory '${target}'"
exit 1
fi
elif [ ! -d "$working_directory" ]; then
error_msg "No such directory '${working_directory}'"
exit 1
fi
# main routine
code=0
if [ "$color" -eq 0 ] || { [ -n "${NO_COLOR+x}" ] && [ "$NO_COLOR" -eq 1 ]; }; then
unittest_subroutine
else
unittest_subroutine | /usr/local/lib/unittest-color.awk
fi
# return stored code
exit "$code"