使用shUnit2测试Bash脚本中的“退出流程命令”

3
根据这个问题的技巧is-there-a-way-to-write-a-bash-function-which-aborts-the-whole-execution...
我的示例代码(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运行它。

2个回答

1
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

那有帮助吗?


(保留HTML标签)

1
让我来回答自己的问题,我找到了一些巧妙的方法,步骤如下:
  1. 将目标程序作为子进程生成并放入后台;
  2. 运行子进程,然后暂停1秒;
  3. 在父进程中,将子进程的PID保存到文件tmp中;
  4. 子进程被唤醒后,从tmp中读取PID到$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",那么这个进程将被杀死,退出状态为零。
测试文件:
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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接