Search code examples
c++unit-testinggoogletest

Googletest Explicit FAIL() in child process is not recognized


Does googletest support multiple processes in C++?

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

An example googletest... test:

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);
    }
  }
}

Test output:

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.

It seems that the child successfully sends the failure. At least, the string was piped in and sent to standard output. In the next line, the exits the switch, case statement and the process terminates.

Is the parent process unaware of failures reported in the child process?

(in all cases: child terminates, is sent a kill signal, or is still alive)

  • Is this a limitation of the framework?
  • Am I not using the framework properly?
  • Is this where death tests are used?

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


Solution

  • Googletest doesn't have any explicit mechanism for interprocess communication, so the parent process has no way of detecting that there was a test failure in the child process. You could detect this condition in the parent process manually by checking the return value of the child once it has terminated, as long as your main() method returns the result of RUN_ALL_TESTS(), or otherwise detects a test failure and returns a non-zero value accordingly.

    Regarding death tests, the above is essentially how they are implemented. A death test spawns a separate process which invokes a piece of code, and the parent process simply verifies that the child exits with a non-zero exit code in the case of ASSERT_DEATH and an arbitrary exit code in the case of ASSERT_EXIT.