I'm working on a project that used BOOST_CHECK_EXCEPTION in unit tests. The first argument is a code block. It works well when the code under test has no commas. Once the code gets a comma that is not inside parentheses (e.g. constructor call with braces and multiple arguments), BOOST_CHECK_EXCEPTION stops working. The preprocessor treats the comma as an argument separator. The preprocessor is aware of parentheses, but not of braces.
So the code blocks that contain unparenthesized commas are defined as a lambdas outside BOOST_CHECK_EXCEPTION. That works, but I'm looking for a solution that keeps BOOST_CHECK_EXCEPTION invocations more uniform. After all, commas can appear and disappear from the expressions as the code is being developed.
First of all, just delaying comma expansion after BOOST_CHECK_EXCEPTION expansion doesn't work. The implementation of BOOST_CHECK_EXCEPTION (BOOST_CHECK_THROW_IMPL) would still reject the extra arguments. It means BOOST_PP_COMMA is not going to help.
One approach I considered is having a CODE_WRAPPER macro that would take the code block and wrap it into code that includes parentheses. Those parentheses need to survive all preprocessor expansion. for
and while
use parentheses about code, but I was unable to put code blocks inside them. Likewise, I could not get a code block inside a function call. They all expect an expression.
One approach that works is a statement expression. It is a GNU extension, so it limits the code to gcc and clang, which is undesirable.
Boost documentation recommends do {...} while(0)
, but it doesn't fix the issue with commas. https://www.boost.org/doc/libs/1_68_0/libs/test/doc/html/boost_test/utf_reference/testing_tool_ref/assertion_boost_level_exception.html
Now I'm thinking of wrapping BOOST_CHECK_EXCEPTION inside a macro that would define a lambda transparently for the caller. And I'm surprised that I don't see much help online. I feel I'm missing something obvious.
Is there any easy way to use BOOST_CHECK_EXCEPTION with code blocks that include unparenthesized commas?