google / googletest

GoogleTest - Google Testing and Mocking Framework
https://google.github.io/googletest/
BSD 3-Clause "New" or "Revised" License
33.78k stars 10k forks source link

[FR]: Add support for std::exception_ptr in Throw() action. #4412

Closed deiuch closed 7 months ago

deiuch commented 8 months ago

Does the feature exist in the most recent commit?

No

Why do we need this feature?

It is convenient to be able to properly throw exceptions from std::exception_ptr while using Throw() action in Google Mock.

Such pointers may occur when we want to parametrize tests with different types of exceptions. The only way to achieve such behavior now is to call custom callback with std::rethrow_exception inside, which is verbose, error-prone and can be easily supported on a library level.

std::exception_ptr excPtr = GetParam();

EXPECT_CALL(Mock, Method())
    .WillOnce([&]() -> ReturnType { std::rethrow_exception(excPtr); });

...will become...

std::exception_ptr excPtr = GetParam();

EXPECT_CALL(Mock, Method())
    .WillOnce(Throw(excPtr));

Describe the proposal.

Support for std::exception_ptr can be implemented with a specialization of ThrowAction class template for the type std::exception_ptr. Inside this specialization all the code will be the same as for the current implementation, except the statement with throw should be changed to a call to std::rethrow_exception.

Another approach is to use if constexpr to choose between throw and std::rethrow_exception, but it introduces dependency on a standard version.

As for the backward compatibility, it is very unlikely that people use std::shared_ptr as an actual exception value. And, if they are, it is very questionable to support such constructs in general. Even if that is the case, they can bypass the case with the custom callback that throws std::exception_ptr object, and this will be more explicit. Also, there should be no ABI incompatibility unless someone is using internal::ThrowAction template directly.

Is the feature specific to an operating system, compiler, or build system version?

No

deiuch commented 7 months ago

Thank you!