Add PredicateMatcher that takes an arbitrary predicate functions

Also adds `Predicate` helper function to create `PredicateMatcher`.
Because of limitations in type inference it needs to be explicitly
typed, like so
`Predicate<std::string>([](std::string const& str) { ... })`.
It also takes an optional second argument for description of the
predicate.

It is possible to infer the argument with sufficient TMP, see
https://stackoverflow.com/questions/43560492/how-to-extract-lambdas-return-type-and-variadic-parameters-pack-back-from-gener/43561563#43561563
but I don't think that the magic is worth introducing ATM.

Closes #1236
This commit is contained in:
Martin Hořeňovský
2018-04-03 23:28:14 +02:00
parent dfb83f20e9
commit 1ca8f43b01
11 changed files with 204 additions and 7 deletions

View File

@@ -32,6 +32,9 @@ namespace { namespace MatchersTests {
return "some completely different text that contains one common word";
}
inline bool alwaysTrue(int) { return true; }
inline bool alwaysFalse(int) { return false; }
#ifdef _MSC_VER
#pragma warning(disable:4702) // Unreachable code -- MSVC 19 (VS 2015) sees right through the indirection
@@ -396,6 +399,26 @@ namespace { namespace MatchersTests {
}
}
TEST_CASE("Arbitrary predicate matcher", "[matchers][generic]") {
SECTION("Function pointer") {
REQUIRE_THAT(1, Predicate<int>(alwaysTrue, "always true"));
REQUIRE_THAT(1, !Predicate<int>(alwaysFalse, "always false"));
}
SECTION("Lambdas + different type") {
REQUIRE_THAT("Hello olleH",
Predicate<std::string>(
[] (std::string const& str) -> bool { return str.front() == str.back(); },
"First and last character should be equal")
);
REQUIRE_THAT("This wouldn't pass",
!Predicate<std::string>(
[] (std::string const& str) -> bool { return str.front() == str.back(); }
)
);
}
}
} } // namespace MatchersTests
#endif // CATCH_CONFIG_DISABLE_MATCHERS