From 8306020a3e9eceafec65508868d7ab5c63bb41f7 Mon Sep 17 00:00:00 2001 From: Abseil Team Date: Wed, 7 Jul 2021 10:28:06 -0400 Subject: Googletest export Add `Conditional` wrapper to gtest This follows an initial proposal for an 'EqIff` matcher. `Conditional` was considered more precise as an EqIff() matcher may suffer from `Iff` not being universally understood. PiperOrigin-RevId: 383407665 --- CONTRIBUTORS | 1 + docs/reference/matchers.md | 1 + googlemock/include/gmock/gmock-matchers.h | 36 +++++++++++++++++++++++++++++++ googlemock/test/gmock-matchers_test.cc | 28 ++++++++++++++++++++++++ 4 files changed, 66 insertions(+) diff --git a/CONTRIBUTORS b/CONTRIBUTORS index 76db0b4..d9bc587 100644 --- a/CONTRIBUTORS +++ b/CONTRIBUTORS @@ -34,6 +34,7 @@ Manuel Klimek Mario Tanev Mark Paskin Markus Heule +Martijn Vels Matthew Simmons Mika Raento Mike Bland diff --git a/docs/reference/matchers.md b/docs/reference/matchers.md index 0d8f81b..1a60b4c 100644 --- a/docs/reference/matchers.md +++ b/docs/reference/matchers.md @@ -238,6 +238,7 @@ You can make a matcher from one or more other matchers: | `AnyOf(m1, m2, ..., mn)` | `argument` matches at least one of the matchers `m1` to `mn`. | | `AnyOfArray({m0, m1, ..., mn})`, `AnyOfArray(a_container)`, `AnyOfArray(begin, end)`, `AnyOfArray(array)`, or `AnyOfArray(array, count)` | The same as `AnyOf()` except that the matchers come from an initializer list, STL-style container, iterator range, or C-style array. | | `Not(m)` | `argument` doesn't match matcher `m`. | +| `Conditional(cond, m1, m2)` | Matches matcher `m1` if `cond` evalutes to true, else matches `m2`.| ## Adapters for Matchers diff --git a/googlemock/include/gmock/gmock-matchers.h b/googlemock/include/gmock/gmock-matchers.h index e1a7606..f1bb22c 100644 --- a/googlemock/include/gmock/gmock-matchers.h +++ b/googlemock/include/gmock/gmock-matchers.h @@ -1405,6 +1405,30 @@ class AnyOfMatcherImpl : public MatcherInterface { template using AnyOfMatcher = VariadicMatcher; +// ConditionalMatcher is the implementation of Conditional(cond, m1, m2) +template +class ConditionalMatcher { + public: + ConditionalMatcher(bool condition, MatcherTrue matcher_true, + MatcherFalse matcher_false) + : condition_(condition), + matcher_true_(std::move(matcher_true)), + matcher_false_(std::move(matcher_false)) {} + + template + operator Matcher() const { // NOLINT(runtime/explicit) + return condition_ ? SafeMatcherCast(matcher_true_) + : SafeMatcherCast(matcher_false_); + } + + private: + bool condition_; + MatcherTrue matcher_true_; + MatcherFalse matcher_false_; + + GTEST_DISALLOW_ASSIGN_(ConditionalMatcher); +}; + // Wrapper for implementation of Any/AllOfArray(). template