根据这个问题的技巧is-there-a-way-to-write-a-bash-function-which-aborts-the-whole-execution...。
我的示例代码(example.sh):
如果我输入
测试文件:
我的示例代码(example.sh):
trap "exit 0" TERM
top_pid=$$
evalInput(){
cmd=$1
if [[ $cmd =~ ^\ *exit\ *$ ]]; then
kill -s TERM $top_pid
elif [another command]
...
fi
}
如果我输入
evalInput "exit"
,那么这个进程将被杀死,并返回退出状态为零。测试文件:
testExitCmd(){
. ./example.sh
...
evalInput "exit"
ps [PID of `evalInput` function]
# `ps` command is failed if evalInput is killed.
assertNotEquals "0" "$?"
}
. shunit2
我对测试evalInput
函数的想法非常简单,只需使用ps
命令确保evalInput
函数被杀死,但问题是我该如何完成这个过程?重要的问题在于当您尝试执行evalInput
时,这意味着您也会杀死testExitCmd
函数。
我已经尝试了许多方法,例如使用&
将evalInput
放到另一个进程中等等。但我仍然会收到类似于shunit2:WARN trapped and now handling the (TERM) signal
的错误。据我所知,这表明我尝试杀死我的测试函数进程。
请仔细测试,我认为仅凭想象力无法解决此问题,请测试一下代码。如果您正在使用OSX
,您可以通过brew
轻松安装shUnit2
,并通过./your_test_script.sh
运行它。