Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Time out for test cases in googletest

Tags:

googletest

Is there a way in gtest to have a timeout for inline/test cases or even tests. For example I would like to do something like: EXPECT_TIMEOUT(5 seconds, myFunction());

I found this issue googletest issues as 'Type:Enhancement' from Dec 09 2010. https://code.google.com/p/googletest/issues/detail?id=348

Looks like there is no gtest way from this post. I am probably not the first to trying to figure out a way for this.

The only way I can think is to make a child thread run the function, and if it does not return by the time limit the parent thread will kill it and show timeout error.

Is there any way where you don't have to use threads? Or any other ways?

like image 246
Basanta Avatar asked Sep 15 '14 16:09

Basanta


1 Answers

I just came across this situation.

I wanted to add a failing test for my reactor. The reactor never finishes. (it has to fail first). But I don't want the test to run forever.

I followed your link but still not joy there. So I decided to use some of the C++14 features and it makes it relatively simple.

But I implemented the timeout like this:

TEST(Init, run)
{
    // Step 1 Set up my code to run.
    ThorsAnvil::Async::Reactor                      reactor;
    std::unique_ptr<ThorsAnvil::Async::Handler>     handler(new TestHandler("test/data/input"));
    ThorsAnvil::Async::HandlerId                    id = reactor.registerHandler(std::move(handler));

    // Step 2
    // Run the code async.
    auto asyncFuture = std::async(
        std::launch::async, [&reactor]() {
                               reactor.run();   // The TestHandler
                                                // should call reactor.shutDown()
                                                // when it is finished.
                                                // if it does not then 
                                                // the test failed.
                            });

    // Step 3
    // DO your timeout test.
    EXPECT_TRUE(asyncFuture.wait_for(std::chrono::milliseconds(5000)) != std::future_status::timeout);

    // Step 4
    // Clean up your resources.
    reactor.shutDown();             // this will allow run() to exit.
                                    // and the thread to die.
}

Now that I have my failing test I can write the code that fixes the test.

like image 92
Martin York Avatar answered Oct 17 '22 00:10

Martin York