使用 shUnit2 在 bash 脚本中测试"exit process command"



根据这个问题中的一个技巧,是否有一种方法来编写一个bash函数,该函数会终止整个执行…

我的示例代码(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",那么这个进程将被终止,退出状态为0。

测试文件:

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运行它

trap "exit 0" TERM
top_pid=$$
evalInput(){
    cmd=$1
    echo "CMD: $cmd"
    if [[ $cmd =~ ^ *exit *$ ]]; then
        kill -s TERM $top_pid
    fi
}
testExitCmd(){
    evalInput "exit" &
    echo "Test evalInput"
    ps [PID of `evalInput` function]
    # `ps` command is failed if evalInput is killed. 
    assertNotEquals "0" "$?"
}
testExitCmd

输出
 Test evalInput
 CMD: exit

这有帮助吗?

让我来回答我自己的问题,我发现了一些棘手的方法,程序是

  1. 生成目标程序作为子进程并将其放到后台,
  2. 运行子进程,然后停止1秒,
  3. 在父进程中,将子进程的PID保存到文件tmp
  4. 子进程被唤醒,然后读取PID从tmp$top_pid
  5. 子进程现在知道它的PID,那么运行kill命令应该可以工作。
我的示例代码(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",那么这个进程将被终止,退出状态为0。

测试文件:

testExitCmd(){
    (
        . ./example.sh
        sleep 1 # 1) wait for parent process save PID to file `temp`
        top_pid=`cat tmp` # 4) save PID to `top_pid`
        evalInput "exit" # 5) kill itself
    )&
    echo "$!" > tmp # 2) save PID of background process to file `tmp`
    sleep 2 # 3) wait for child process kill itself
    child_pid=$!
    ps $child_pid # `ps` command is failed if evalInput is killed. 
    assertNotEquals "0" "$?"
}
. shunit2

相关内容

最新更新