Skip to content

Instantly share code, notes, and snippets.

@renelink
Created March 22, 2024 08:38
Show Gist options
  • Save renelink/cfd809a1be721cdd175de7b90921c13a to your computer and use it in GitHub Desktop.
Save renelink/cfd809a1be721cdd175de7b90921c13a to your computer and use it in GitHub Desktop.
#!/usr/bin/env bash
# runs a bash script test under MSYS2 (e.g. git bash) environment in an isolated directory.
#
# A test is named *.test.sh and passed as argument to this script.
# Since the test will run in an isolated directory (chroot), you
# might have to setup additional files that your test needs. E.g.
# another script that should be tested. Do do that place a script named
# *.before.sh beside your test script. The before script will be called
# with the root of the isolated test directory as it's first argument.
#
# E.g.
# some.sh
# -------
# echo "some test"
# =======
#
# some.test.sh
# -------
# OUTPUT=$(./some.sh)
#
# if [ "${OUTPUT}" != "some test" ]; then
# echo "Expected output should be 'some test', but was '${OUTPUT}'"
# exit 1
#fi
# =======
# some.before.sh
# -------
# cp some.sh $1
# =======
# run-test.sh some.test.sh
TEST_SCRIPT=$1
BEFORE_SCRIPT=${TEST_SCRIPT//\.test\.sh/.before.sh}
TEST_DIR=$(mktemp -d)
bold=$(tput bold)
normal=$(tput sgr0)
FAILED_COLOR='\033[0;31m'
SUCCESS_COLOR='\033[0;32m'
INFO_COLOR="$bold"
NC='\033[0m'
em() {
TEXT=$1
shift
echo -e $* "${bold}$TEXT${NC}"
}
success() {
TEXT=$1
shift
echo -e $* "${SUCCESS_COLOR}$TEXT${NC}"
}
failed() {
TEXT=$1
shift
echo -e $* "${FAILED_COLOR}$TEXT${NC}"
}
echo -e "${INFO_COLOR}Preparing Test${NC} ${TEST_SCRIPT}"
mkdir -p $TEST_DIR/tmp 2> /dev/null
mkdir -p $TEST_DIR/etc 2> /dev/null
cp -r /etc/profile $TEST_DIR/etc
cp -r /etc/msystem $TEST_DIR/etc
mkdir -p $TEST_DIR/bin 2> /dev/null
cp -r /bin/* $TEST_DIR/bin
mkdir -p $TEST_DIR/usr/bin 2> /dev/null
cp -r /usr/bin/* $TEST_DIR/usr/bin
# SHAFAILED_COLOR LIBS
mkdir -p $TEST_DIR/usr/lib 2> /dev/null
cp -r /usr/lib/* $TEST_DIR/usr/lib
# PREPARE USER HOME FOR LOGIN SHELL
mkdir -p $TEST_DIR/home/${USERNAME}
cp ${HOME}/.bashrc $TEST_DIR/home/${USERNAME}
cp ${HOME}/.bash_profile $TEST_DIR/home/${USERNAME}
$(dirname $0)/${BEFORE_SCRIPT} $TEST_DIR
cp $TEST_SCRIPT $TEST_DIR
echo -e "${INFO_COLOR}Run Test${NC} $TEST_SCRIPT${NC}"
chroot $TEST_DIR /bin/bash -l -c /$TEST_SCRIPT
TEST_RESULT=$?
em "======================================="
em "$TEST_SCRIPT " -n
if [ $TEST_RESULT == 0 ]; then
success "SUCCESSFUL"
else
failed "FAILED"
fi
em "======================================="
rm -rf $TEST_DIR
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment