Trying to create some unit tests with EXPECT_EXIT where the error message contains a '*'. The test fails but not with expected error. What am I missing here?
Here a very simple example to reproduce the issue:
void test_Death() {
std::cerr << "*Error\n";
exit(EXIT_FAILURE);
}
TEST(ErrorWithStar, Star) {
EXPECT_EXIT(test_Death(), testing::ExitedWithCode(EXIT_FAILURE), "*Error\n");
}
The result is:
Message:
#1 - Failed
Syntax error at index 0 in simple regular expression "*Error
": '*' can only follow a repeatable token.
Running main() from c:\a\1\s\thirdparty\googletest\googletest\src\gtest_main.cc
#2 - Death test: test_Death()
Result: died but not with expected error.
Expected: *Error
Actual msg:
[ DEATH ] *Error
[ DEATH ]
I am using Microsoft Visual Studio Community 2019 Version 16.11.13. I added a Google Test project to my solution, created all links etc. It is working perfectly for everything else, but not for messages containing a '*'.
What is meant by "'*' can only follow a repeatable token."?
CodePudding user response:
The character * is reserved by the regular expression grammar to indicate matching zero or more of the previous tokens or groups.
Some simple examples:
.*matches zero or more of any charactera*matches zero or more of the charactera[A-F]*matches zero or more of the charactersAthrough toF
The error is occurring because you have a * at the beginning of the string, where there is no preceding character, group etc to be repeated. This is essentially a syntax error in the regular expression grammar, and the error message tells you so.
What you actually want is a literal *, not the one that belongs to the grammar. To achieve this, you must escape it with a \. And because strings in C also use that for an escape character, you must escape the backslash too. So you need two backslashes before the * (or use a raw string literal).
In a pinch, the solution should be:
EXPECT_EXIT(test_Death(), testing::ExitedWithCode(EXIT_FAILURE), "\\*Error\n");
