Search code examples
c++googletestsigabrt

How run gtest and make sure sigabrt never happens


I need a gtest that will pass if sigabrt doesn't happen, but need to know if it does happen, or fail the test. How would I do that?

I was thinking of this sort of thing:

TEST_F(TestTest, testSigabrtDoesntHappen)
{
   MyObject &myObject = MyObject::instance();
   for(int i=0; i<2; i++){
        myObject.doWork(); //this will sigabrt on the second try, if at all
        ASSERT_TRUE(myObject);
   }
   ASSERT_TRUE(myObject);
}

So assuming a sigabrt would exit out of the test if it occurs, then we would get 3 test passes otherwise. Any other ideas?


Solution

  • Not on Window:

    ::testing::KilledBySignal(signal_number)  // Not available on Windows.
    

    You should look the guide.

    It seems like that for me (not tested) :

    TEST_F(TestTest, testSigabrtDoesntHappen)
    {
       MyObject &myObject = MyObject::instance();
       for(int i=0; i<2; i++){
            EXPECT_EXIT(myObject.doWork(), ::testing::KilledBySignal(SIGBART)), "Regex to match error message");
            ASSERT_TRUE(myObject);
       }
       ASSERT_TRUE(myObject);
    }
    

    On Window:

    You'll have to handle signal yourself with this kind of code:

    // crt_signal.c  
    // compile with: /EHsc /W4  
    // Use signal to attach a signal handler to the abort routine  
    #include <stdlib.h>  
    #include <signal.h>  
    #include <tchar.h>  
    
    void SignalHandler(int signal)  
    {  
        if (signal == SIGABRT) {  
            // abort signal handler code  
        } else {  
            // ...  
        }  
    }  
    
    int main()  
    {  
        typedef void (*SignalHandlerPointer)(int);  
    
        SignalHandlerPointer previousHandler;  
        previousHandler = signal(SIGABRT, SignalHandler);  
    
        abort();  //emit SIGBART ?
    }
    

    doc

    But seriously if you have one time get a SIGBART running your code, there are some problems with your code that you have to remove before release the software.


    But if you really want to debug your code (with googletest), use this with your debugger:

    foo_test --gtest_repeat=1000 --gtest_break_on_failure
    

    You can add others option to it, again : check the doc :)