【问题标题】:Test a "exit process command" in bash script by using shUnit2使用 shUnit2 在 bash 脚本中测试“退出进程命令”
【发布时间】:2015-08-13 17:12:42
【问题描述】:

根据这个问题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 放入另一个进程,然后bla bla bla。但我仍然收到类似shunit2:WARN trapped and now handling the (TERM) signal 的错误。据我了解,这表明我试图杀死我的测试功能进程。

请仔细测试,我不认为只有你的想象力可以解决这个问题,但请测试代码。如果您使用的是OSX,您可以通过brew 安装shUnit2,然后通过./your_test_script.sh 运行它

【问题讨论】:

    标签: bash shell unit-testing shunit2


    【解决方案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
    

    这有帮助吗?

    【讨论】:

      【解决方案2】:

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

      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
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-01-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-09-26
        • 1970-01-01
        相关资源
        最近更新 更多