Home > Back-end >  Google test using C 11/14, how to fix the invalid POSIX Extended error
Google test using C 11/14, how to fix the invalid POSIX Extended error

Time:01-13

I am using gtest to do unit test and trying to use the function MatchesRegexto match the pattern a string contains multiple substrings using look around. e.g

Verifying the statement The team members are Tom, Jerry and a Terminator contains all three keywords Tom, Jerry and Term

std::string target = "The team members are Tom, Jerry and a Terminator";
EXPECT_THAT(target, MatchesRegex("(?=.*(Tom))(?=.*(Jerry))(?=.*(Term))"));

But I am getting an error

Regular expression "((?=.*(Tom))(?=.*(Jerry))(?=.*(Term)))" is not a valid POSIX Extended regular expression.

Any suggestion to fix the regexp?

The test code can be found here

CodePudding user response:

POSIX regular expressions in C are very limited. Fortunately, you may combine expectations logically.

#include <iostream>
#include <string>
#include <gmock/gmock.h>

using testing::AllOf;
using testing::MatchesRegex;

TEST(RegexTest, Simple_Regex_Matcher) {
  std::string target = "The team members are Tom, Jerry and a Terminator";
  EXPECT_THAT(target, AllOf(MatchesRegex(".*Tom.*"), MatchesRegex(".*Jerry.*"), MatchesRegex(".*Term.*")));
}

int main(int argc, char*argv[]) {
  testing::InitGoogleTest(&argc, argv);
  return RUN_ALL_TESTS();
}

Output:

[==========] Running 1 test from 1 test suite.
[----------] Global test environment set-up.
[----------] 1 test from RegexTest
[ RUN      ] RegexTest.Simple_Regex_Matcher
[       OK ] RegexTest.Simple_Regex_Matcher (0 ms)
[----------] 1 test from RegexTest (0 ms total)

[----------] Global test environment tear-down
[==========] 1 test from 1 test suite ran. (0 ms total)
[  PASSED  ] 1 test.

CodePudding user response:

I marked @273k's answer as the accepted answer. But in my final solution, I use something like

EXPECT_THAT(target, AllOf(HasSubstr("Tom"), HasSubstr("Jerry"), HasSubstr("Term")));

Which is inspired by @273k's answer. Regexp is much shorter and slow but AllOf HasSubstr has better readablility.

  •  Tags:  
  • Related