Newer
Older
dub_jkp / test / common.sh
  1. SOURCE_FILE=$_
  2.  
  3. set -ueEo pipefail
  4.  
  5. function log() {
  6. echo -e "\033[0;33m[INFO] $@\033[0m"
  7. echo "[INFO] $@" >> $(dirname "${BASH_SOURCE[0]}")/test.log
  8. }
  9.  
  10. # lineno[, msg]
  11. function die() {
  12. local line=$1
  13. local msg=${2:-command failed}
  14. local supplemental=${3:-}
  15. echo "[ERROR] $SOURCE_FILE:$1 $msg" | tee -a $(dirname "${BASH_SOURCE[0]}")/test.log | cat 1>&2
  16. if [ ! -z "$supplemental" ]; then
  17. echo "$supplemental" | >&2 sed 's|^| |g'
  18. fi
  19. exit 1
  20. }
  21. trap 'die $LINENO' ERR
  22.  
  23. # Get a random port for the test to use
  24. # This isn't foolproof but should fail less than handcrafted approaches
  25. function getRandomPort() {
  26. # Get the PID of this script as a way to get a random port,
  27. # and make sure the value is > 1024, as ports < 1024 are priviledged
  28. # and require root priviledges.
  29. # We also need to make sure the value is not > ushort.max
  30. PORT=$(($$ % 65536))
  31. if [ $PORT -le 1024 ]; then
  32. PORT=$(($PORT + 1025))
  33. fi
  34. echo $PORT
  35. }
  36.  
  37. # Emulate GNU readlink's behavior on non-GNU readlink (e.g. MacOSX / BSD's)
  38. # Credit to https://stackoverflow.com/a/1116890
  39. function gnureadlink() {
  40. TARGET_FILE=$1
  41.  
  42. cd `dirname $TARGET_FILE`
  43. TARGET_FILE=`basename $TARGET_FILE`
  44.  
  45. # Iterate down a (possible) chain of symlinks
  46. while [ -L "$TARGET_FILE" ]
  47. do
  48. TARGET_FILE=`readlink $TARGET_FILE`
  49. cd `dirname $TARGET_FILE`
  50. TARGET_FILE=`basename $TARGET_FILE`
  51. done
  52.  
  53. # Compute the canonicalized name by finding the physical path
  54. # for the directory we're in and appending the target file.
  55. PHYS_DIR=`pwd -P`
  56. RESULT=$PHYS_DIR/$TARGET_FILE
  57. echo $RESULT
  58. }