Skip to content

Instantly share code, notes, and snippets.

@photonxp
Last active October 28, 2018 08:35
Show Gist options
  • Save photonxp/0ecb2fa47801b1055f940d52c6d06dc7 to your computer and use it in GitHub Desktop.
Save photonxp/0ecb2fa47801b1055f940d52c6d06dc7 to your computer and use it in GitHub Desktop.
demo unit test for bash, just personal usage
#!/bin/bash
source ./testf.bash
test1(){
echo "hello world"
}
test_init_dir_unexist(){
[ -e ./test9 ] && rm -r ./test9
init_dir
rslt="$(ls -d ./test9)"
assert_equal_str "./test9" "$rslt"
}
test_init_dir_exist_no_op(){
[ ! -e ./test9 ] && mkdir ./test9
rslt=$(init_dir)
n_words=$(get_first_n_words_by_space "$rslt" 3)
assert_equal_str "Cannot create dir::" "$n_words"
}
test_init_dir_exist_op(){
[ ! -e ./test9 ] && mkdir ./test9
opt="-o"
rslt=$(init_dir)
assert_equal_str "" "$rslt"
opt=""
}
set -- -o
opt="$1"
#run_tests test_init_dir_exist
tests="test1 test_init_dir_unexist test_init_dir_exist_op test_init_dir_exist_no_op"
run_tests $(echo $tests)
#!/bin/bash
# ####test_demo_testf.bash
# #!/bin/bash
#
# source ./testf.bash
#
# test1(){
# echo "hello"
# }
#
# test2(){
# echo "world"
# }
#
# opt="$1"
# run_tests "test1" "test2"
echo_start(){
echo "$1 ============================="
}
init_time_log(){
fpath_log=./time.log
if [ -f $fpath_log ]
then
# if ! -o, exit
rm $fpath_log
fi
touch $fpath_log
}
log_datetime(){
datef=`date '+%Y%m%d.%H%M%S'`
echo "$1$datef" >> $fpath_log
}
init_dir(){
if [ -e ./test9 ]
then
if [ "-o" != "$opt" ]
then
echo "Cannot create dir:: Dir (or file) test9 exists. Exit."
exit 1
fi
rm -r ./test9
fi
mkdir ./test9
}
init_script(){
echo_start "Start script $0"
init_time_log
log_datetime "Start script $0 : "
init_dir
}
finish_script(){
echo_start "Finish script $0"
log_datetime "Finish script $0 : "
}
init_test(){
echo_start "Start $1 : "
log_datetime "Start $1 : "
}
finish_test(){
log_datetime "Finish $1 : "
}
run_tests(){
init_script
for test in "$@"
do
init_test "$test"
$test
finish_test "$test"
done
finish_script
}
get_first_n_words_by_space(){
line="$1"
n="$2"
echo $(printf "$line" | cut -d " " -f 1-"$n")
}
assert_equal_str(){
expected="$1"
actual="$2"
if [ "$expected" == "$actual" ]
then
echo Pass
else
echo "Fail: $expected != $actual"
fi
}
test1(){
# call the tested script
:
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment