child 进程中的 Googletest Explicit FAIL() 无法识别

Googletest Explicit FAIL() in child process is not recognized

googletest 是否支持 C++ 中的多进程?

文档: https://github.com/google/googletest/blob/master/docs/advanced.md#explicit-success-and-failure

一个示例 googletest... 测试:

TEST_F(TCPConnectionTest, killServerDuringWrite) {
  pid_t childProcessID;
  switch (childProcessID = fork()) { //A somewhat elegant way to split into two processes
    case -1: break; //Something went wrong, should report error here
    case 0: { //Child process
      // Should be busy in a loop when parent process sends kill signal
      // Else, I want the test to report a fail so I am aware my test is not working properly
      FAIL() << "Shouldn't get to this line."; //Pipe in a message to FAIL()
      break; //Don't need because child process won't get here?
    }
    default:  { //Parent process
      // Some other code goes here, then send kill signal
      kill(childProcessID, SIGKILL);
      pid_t result; int status; //Used for getting result
      //Keep checking result until child process returns dead
      while (result <= 0) result = waitpid(childProcessID, &status, WNOHANG);
      EXPECT_GT(result, 0);
    }
  }
}

测试输出:

tcptests.cpp:722: Failure
Failed
Shouldn't get to this line.
[       OK ] TCPConnectionTest.killServerDuringWrite (64 ms)
[----------] 1 test from TCPConnectionTest (64 ms total)

[----------] Global test environment tear-down
[==========] 1 test from 1 test case ran. (64 ms total)
[  PASSED  ] 1 test.

看来child成功发送失败。至少,字符串通过管道输入并发送到标准输出。在下一行中,退出 switch、case 语句并且进程终止。

parent 进程是否不知道 child 进程中报告的故障?

(在所有情况下:child 终止、发送终止信号或仍然存在)

https://github.com/google/googletest/blob/master/googletest/docs/advanced.md#death-tests

Googletest 没有任何明确的进程间通信机制,因此父进程无法检测到子进程中存在测试失败。只要您的 main() 方法 return 是 RUN_ALL_TESTS( ),或以其他方式检测到测试失败,并相应地 returns 一个非零值。

关于死亡测试,以上就是它们的基本实现方式。死亡测试产生一个单独的进程,该进程调用一段代码,父进程简单地验证子进程在 ASSERT_DEATH 的情况下以非零退出代码退出,在 [= 的情况下以任意退出代码退出。 =11=]。