Index: ext/googletest/googlemock/include/gmock/gmock-matchers.h =================================================================== diff -u -N -r4a481bbe77043e0bda2435c6d62a02700b3e46c5 -r2e4eacb299f21d06196fe13140b4b0d095abdca9 --- ext/googletest/googlemock/include/gmock/gmock-matchers.h (.../gmock-matchers.h) (revision 4a481bbe77043e0bda2435c6d62a02700b3e46c5) +++ ext/googletest/googlemock/include/gmock/gmock-matchers.h (.../gmock-matchers.h) (revision 2e4eacb299f21d06196fe13140b4b0d095abdca9) @@ -26,15 +26,16 @@ // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -// -// Author: wan@google.com (Zhanyong Wan) + // Google Mock - a framework for writing C++ mock classes. // // This file implements some commonly used argument matchers. More // matchers can be defined by the user implementing the // MatcherInterface interface if necessary. +// GOOGLETEST_CM0002 DO NOT DELETE + #ifndef GMOCK_INCLUDE_GMOCK_GMOCK_MATCHERS_H_ #define GMOCK_INCLUDE_GMOCK_GMOCK_MATCHERS_H_ @@ -47,15 +48,19 @@ #include #include #include - +#include "gtest/gtest.h" #include "gmock/internal/gmock-internal-utils.h" #include "gmock/internal/gmock-port.h" -#include "gtest/gtest.h" #if GTEST_HAS_STD_INITIALIZER_LIST_ # include // NOLINT -- must be after gtest.h #endif +GTEST_DISABLE_MSC_WARNINGS_PUSH_( + 4251 5046 /* class A needs to have dll-interface to be used by clients of + class B */ + /* Symbol involving type with internal linkage not defined */) + namespace testing { // To implement a matcher Foo for type T, define: @@ -73,7 +78,7 @@ // MatchResultListener is an abstract class. Its << operator can be // used by a matcher to explain why a value matches or doesn't match. // -// TODO(wan@google.com): add method +// FIXME: add method // bool InterestedInWhy(bool result) const; // to indicate whether the listener is interested in why the match // result is 'result'. @@ -180,13 +185,42 @@ // virtual void DescribeNegationTo(::std::ostream* os) const; }; +namespace internal { + +// Converts a MatcherInterface to a MatcherInterface. +template +class MatcherInterfaceAdapter : public MatcherInterface { + public: + explicit MatcherInterfaceAdapter(const MatcherInterface* impl) + : impl_(impl) {} + virtual ~MatcherInterfaceAdapter() { delete impl_; } + + virtual void DescribeTo(::std::ostream* os) const { impl_->DescribeTo(os); } + + virtual void DescribeNegationTo(::std::ostream* os) const { + impl_->DescribeNegationTo(os); + } + + virtual bool MatchAndExplain(const T& x, + MatchResultListener* listener) const { + return impl_->MatchAndExplain(x, listener); + } + + private: + const MatcherInterface* const impl_; + + GTEST_DISALLOW_COPY_AND_ASSIGN_(MatcherInterfaceAdapter); +}; + +} // namespace internal + // A match result listener that stores the explanation in a string. class StringMatchResultListener : public MatchResultListener { public: StringMatchResultListener() : MatchResultListener(&ss_) {} // Returns the explanation accumulated so far. - internal::string str() const { return ss_.str(); } + std::string str() const { return ss_.str(); } // Clears the explanation accumulated so far. void Clear() { ss_.str(""); } @@ -253,12 +287,13 @@ public: // Returns true iff the matcher matches x; also explains the match // result to 'listener'. - bool MatchAndExplain(T x, MatchResultListener* listener) const { + bool MatchAndExplain(GTEST_REFERENCE_TO_CONST_(T) x, + MatchResultListener* listener) const { return impl_->MatchAndExplain(x, listener); } // Returns true iff this matcher matches x. - bool Matches(T x) const { + bool Matches(GTEST_REFERENCE_TO_CONST_(T) x) const { DummyMatchResultListener dummy; return MatchAndExplain(x, &dummy); } @@ -272,7 +307,8 @@ } // Explains why x matches, or doesn't match, the matcher. - void ExplainMatchResultTo(T x, ::std::ostream* os) const { + void ExplainMatchResultTo(GTEST_REFERENCE_TO_CONST_(T) x, + ::std::ostream* os) const { StreamMatchResultListener listener(os); MatchAndExplain(x, &listener); } @@ -288,9 +324,18 @@ MatcherBase() {} // Constructs a matcher from its implementation. - explicit MatcherBase(const MatcherInterface* impl) + explicit MatcherBase( + const MatcherInterface* impl) : impl_(impl) {} + template + explicit MatcherBase( + const MatcherInterface* impl, + typename internal::EnableIf< + !internal::IsSame::value>::type* = + NULL) + : impl_(new internal::MatcherInterfaceAdapter(impl)) {} + virtual ~MatcherBase() {} private: @@ -305,7 +350,9 @@ // // If performance becomes a problem, we should see if using // shared_ptr helps. - ::testing::internal::linked_ptr > impl_; + ::testing::internal::linked_ptr< + const MatcherInterface > + impl_; }; } // namespace internal @@ -324,96 +371,186 @@ explicit Matcher() {} // NOLINT // Constructs a matcher from its implementation. - explicit Matcher(const MatcherInterface* impl) + explicit Matcher(const MatcherInterface* impl) : internal::MatcherBase(impl) {} + template + explicit Matcher(const MatcherInterface* impl, + typename internal::EnableIf::value>::type* = NULL) + : internal::MatcherBase(impl) {} + // Implicit constructor here allows people to write // EXPECT_CALL(foo, Bar(5)) instead of EXPECT_CALL(foo, Bar(Eq(5))) sometimes Matcher(T value); // NOLINT }; // The following two specializations allow the user to write str -// instead of Eq(str) and "foo" instead of Eq("foo") when a string +// instead of Eq(str) and "foo" instead of Eq("foo") when a std::string // matcher is expected. template <> -class GTEST_API_ Matcher - : public internal::MatcherBase { +class GTEST_API_ Matcher + : public internal::MatcherBase { public: Matcher() {} - explicit Matcher(const MatcherInterface* impl) - : internal::MatcherBase(impl) {} + explicit Matcher(const MatcherInterface* impl) + : internal::MatcherBase(impl) {} // Allows the user to write str instead of Eq(str) sometimes, where - // str is a string object. - Matcher(const internal::string& s); // NOLINT + // str is a std::string object. + Matcher(const std::string& s); // NOLINT +#if GTEST_HAS_GLOBAL_STRING + // Allows the user to write str instead of Eq(str) sometimes, where + // str is a ::string object. + Matcher(const ::string& s); // NOLINT +#endif // GTEST_HAS_GLOBAL_STRING + // Allows the user to write "foo" instead of Eq("foo") sometimes. Matcher(const char* s); // NOLINT }; template <> -class GTEST_API_ Matcher - : public internal::MatcherBase { +class GTEST_API_ Matcher + : public internal::MatcherBase { public: Matcher() {} - explicit Matcher(const MatcherInterface* impl) - : internal::MatcherBase(impl) {} + explicit Matcher(const MatcherInterface* impl) + : internal::MatcherBase(impl) {} + explicit Matcher(const MatcherInterface* impl) + : internal::MatcherBase(impl) {} // Allows the user to write str instead of Eq(str) sometimes, where // str is a string object. - Matcher(const internal::string& s); // NOLINT + Matcher(const std::string& s); // NOLINT +#if GTEST_HAS_GLOBAL_STRING + // Allows the user to write str instead of Eq(str) sometimes, where + // str is a ::string object. + Matcher(const ::string& s); // NOLINT +#endif // GTEST_HAS_GLOBAL_STRING + // Allows the user to write "foo" instead of Eq("foo") sometimes. Matcher(const char* s); // NOLINT }; -#if GTEST_HAS_STRING_PIECE_ +#if GTEST_HAS_GLOBAL_STRING // The following two specializations allow the user to write str -// instead of Eq(str) and "foo" instead of Eq("foo") when a StringPiece +// instead of Eq(str) and "foo" instead of Eq("foo") when a ::string // matcher is expected. template <> -class GTEST_API_ Matcher - : public internal::MatcherBase { +class GTEST_API_ Matcher + : public internal::MatcherBase { public: Matcher() {} - explicit Matcher(const MatcherInterface* impl) - : internal::MatcherBase(impl) {} + explicit Matcher(const MatcherInterface* impl) + : internal::MatcherBase(impl) {} // Allows the user to write str instead of Eq(str) sometimes, where - // str is a string object. - Matcher(const internal::string& s); // NOLINT + // str is a std::string object. + Matcher(const std::string& s); // NOLINT + // Allows the user to write str instead of Eq(str) sometimes, where + // str is a ::string object. + Matcher(const ::string& s); // NOLINT + // Allows the user to write "foo" instead of Eq("foo") sometimes. Matcher(const char* s); // NOLINT +}; - // Allows the user to pass StringPieces directly. - Matcher(StringPiece s); // NOLINT +template <> +class GTEST_API_ Matcher< ::string> + : public internal::MatcherBase< ::string> { + public: + Matcher() {} + + explicit Matcher(const MatcherInterface* impl) + : internal::MatcherBase< ::string>(impl) {} + explicit Matcher(const MatcherInterface< ::string>* impl) + : internal::MatcherBase< ::string>(impl) {} + + // Allows the user to write str instead of Eq(str) sometimes, where + // str is a std::string object. + Matcher(const std::string& s); // NOLINT + + // Allows the user to write str instead of Eq(str) sometimes, where + // str is a ::string object. + Matcher(const ::string& s); // NOLINT + + // Allows the user to write "foo" instead of Eq("foo") sometimes. + Matcher(const char* s); // NOLINT }; +#endif // GTEST_HAS_GLOBAL_STRING +#if GTEST_HAS_ABSL +// The following two specializations allow the user to write str +// instead of Eq(str) and "foo" instead of Eq("foo") when a absl::string_view +// matcher is expected. template <> -class GTEST_API_ Matcher - : public internal::MatcherBase { +class GTEST_API_ Matcher + : public internal::MatcherBase { public: Matcher() {} - explicit Matcher(const MatcherInterface* impl) - : internal::MatcherBase(impl) {} + explicit Matcher(const MatcherInterface* impl) + : internal::MatcherBase(impl) {} // Allows the user to write str instead of Eq(str) sometimes, where - // str is a string object. - Matcher(const internal::string& s); // NOLINT + // str is a std::string object. + Matcher(const std::string& s); // NOLINT +#if GTEST_HAS_GLOBAL_STRING + // Allows the user to write str instead of Eq(str) sometimes, where + // str is a ::string object. + Matcher(const ::string& s); // NOLINT +#endif // GTEST_HAS_GLOBAL_STRING + // Allows the user to write "foo" instead of Eq("foo") sometimes. Matcher(const char* s); // NOLINT - // Allows the user to pass StringPieces directly. - Matcher(StringPiece s); // NOLINT + // Allows the user to pass absl::string_views directly. + Matcher(absl::string_view s); // NOLINT }; -#endif // GTEST_HAS_STRING_PIECE_ +template <> +class GTEST_API_ Matcher + : public internal::MatcherBase { + public: + Matcher() {} + + explicit Matcher(const MatcherInterface* impl) + : internal::MatcherBase(impl) {} + explicit Matcher(const MatcherInterface* impl) + : internal::MatcherBase(impl) {} + + // Allows the user to write str instead of Eq(str) sometimes, where + // str is a std::string object. + Matcher(const std::string& s); // NOLINT + +#if GTEST_HAS_GLOBAL_STRING + // Allows the user to write str instead of Eq(str) sometimes, where + // str is a ::string object. + Matcher(const ::string& s); // NOLINT +#endif // GTEST_HAS_GLOBAL_STRING + + // Allows the user to write "foo" instead of Eq("foo") sometimes. + Matcher(const char* s); // NOLINT + + // Allows the user to pass absl::string_views directly. + Matcher(absl::string_view s); // NOLINT +}; +#endif // GTEST_HAS_ABSL + +// Prints a matcher in a human-readable format. +template +std::ostream& operator<<(std::ostream& os, const Matcher& matcher) { + matcher.DescribeTo(&os); + return os; +} + // The PolymorphicMatcher class template makes it easy to implement a // polymorphic matcher (i.e. a matcher that can match values of more // than one type, e.g. Eq(n) and NotNull()). @@ -441,7 +578,7 @@ template operator Matcher() const { - return Matcher(new MonomorphicImpl(impl_)); + return Matcher(new MonomorphicImpl(impl_)); } private: @@ -515,7 +652,7 @@ class MatcherCastImpl { public: static Matcher Cast(const M& polymorphic_matcher_or_value) { - // M can be a polymorhic matcher, in which case we want to use + // M can be a polymorphic matcher, in which case we want to use // its conversion operator to create Matcher. Or it can be a value // that should be passed to the Matcher's constructor. // @@ -531,21 +668,18 @@ return CastImpl( polymorphic_matcher_or_value, BooleanConstant< - internal::ImplicitlyConvertible >::value>()); + internal::ImplicitlyConvertible >::value>(), + BooleanConstant< + internal::ImplicitlyConvertible::value>()); } private: - static Matcher CastImpl(const M& value, BooleanConstant) { - // M can't be implicitly converted to Matcher, so M isn't a polymorphic - // matcher. It must be a value then. Use direct initialization to create - // a matcher. - return Matcher(ImplicitCast_(value)); - } - + template static Matcher CastImpl(const M& polymorphic_matcher_or_value, - BooleanConstant) { + BooleanConstant /* convertible_to_matcher */, + BooleanConstant) { // M is implicitly convertible to Matcher, which means that either - // M is a polymorhpic matcher or Matcher has an implicit constructor + // M is a polymorphic matcher or Matcher has an implicit constructor // from M. In both cases using the implicit conversion will produce a // matcher. // @@ -554,6 +688,29 @@ // (first to create T from M and then to create Matcher from T). return polymorphic_matcher_or_value; } + + // M can't be implicitly converted to Matcher, so M isn't a polymorphic + // matcher. It's a value of a type implicitly convertible to T. Use direct + // initialization to create a matcher. + static Matcher CastImpl( + const M& value, BooleanConstant /* convertible_to_matcher */, + BooleanConstant /* convertible_to_T */) { + return Matcher(ImplicitCast_(value)); + } + + // M can't be implicitly converted to either Matcher or T. Attempt to use + // polymorphic matcher Eq(value) in this case. + // + // Note that we first attempt to perform an implicit cast on the value and + // only fall back to the polymorphic Eq() matcher afterwards because the + // latter calls bool operator==(const Lhs& lhs, const Rhs& rhs) in the end + // which might be undefined even when Rhs is implicitly convertible to Lhs + // (e.g. std::pair vs. std::pair). + // + // We don't define this method inline as we need the declaration of Eq(). + static Matcher CastImpl( + const M& value, BooleanConstant /* convertible_to_matcher */, + BooleanConstant /* convertible_to_T */); }; // This more specialized version is used when MatcherCast()'s argument @@ -574,6 +731,22 @@ // We delegate the matching logic to the source matcher. virtual bool MatchAndExplain(T x, MatchResultListener* listener) const { +#if GTEST_LANG_CXX11 + using FromType = typename std::remove_cv::type>::type>::type; + using ToType = typename std::remove_cv::type>::type>::type; + // Do not allow implicitly converting base*/& to derived*/&. + static_assert( + // Do not trigger if only one of them is a pointer. That implies a + // regular conversion and not a down_cast. + (std::is_pointer::type>::value != + std::is_pointer::type>::value) || + std::is_same::value || + !std::is_base_of::value, + "Can't implicitly convert from to "); +#endif // GTEST_LANG_CXX11 + return source_matcher_.MatchAndExplain(static_cast(x), listener); } @@ -646,7 +819,7 @@ // type U. GTEST_COMPILE_ASSERT_( internal::is_reference::value || !internal::is_reference::value, - cannot_convert_non_referentce_arg_to_reference); + cannot_convert_non_reference_arg_to_reference); // In case both T and U are arithmetic types, enforce that the // conversion is not lossy. typedef GTEST_REMOVE_REFERENCE_AND_CONST_(T) RawT; @@ -675,7 +848,7 @@ namespace internal { // If the explanation is not empty, prints it to the ostream. -inline void PrintIfNotEmpty(const internal::string& explanation, +inline void PrintIfNotEmpty(const std::string& explanation, ::std::ostream* os) { if (explanation != "" && os != NULL) { *os << ", " << explanation; @@ -685,11 +858,11 @@ // Returns true if the given type name is easy to read by a human. // This is used to decide whether printing the type of a value might // be helpful. -inline bool IsReadableTypeName(const string& type_name) { +inline bool IsReadableTypeName(const std::string& type_name) { // We consider a type name readable if it's short or doesn't contain // a template or function type. return (type_name.length() <= 20 || - type_name.find_first_of("<(") == string::npos); + type_name.find_first_of("<(") == std::string::npos); } // Matches the value against the given matcher, prints the value and explains @@ -711,7 +884,7 @@ UniversalPrint(value, listener->stream()); #if GTEST_HAS_RTTI - const string& type_name = GetTypeName(); + const std::string& type_name = GetTypeName(); if (IsReadableTypeName(type_name)) *listener->stream() << " (of type " << type_name << ")"; #endif @@ -751,10 +924,10 @@ typename tuple_element::type matcher = get(matchers); typedef typename tuple_element::type Value; - Value value = get(values); + GTEST_REFERENCE_TO_CONST_(Value) value = get(values); StringMatchResultListener listener; if (!matcher.MatchAndExplain(value, &listener)) { - // TODO(wan): include in the message the name of the parameter + // FIXME: include in the message the name of the parameter // as used in MOCK_METHOD*() when possible. *os << " Expected arg #" << N - 1 << ": "; get(matchers).DescribeTo(os); @@ -856,10 +1029,12 @@ // Implements A(). template -class AnyMatcherImpl : public MatcherInterface { +class AnyMatcherImpl : public MatcherInterface { public: - virtual bool MatchAndExplain( - T /* x */, MatchResultListener* /* listener */) const { return true; } + virtual bool MatchAndExplain(GTEST_REFERENCE_TO_CONST_(T) /* x */, + MatchResultListener* /* listener */) const { + return true; + } virtual void DescribeTo(::std::ostream* os) const { *os << "is anything"; } virtual void DescribeNegationTo(::std::ostream* os) const { // This is mostly for completeness' safe, as it's not very useful @@ -1129,6 +1304,19 @@ bool case_sensitive) : string_(str), expect_eq_(expect_eq), case_sensitive_(case_sensitive) {} +#if GTEST_HAS_ABSL + bool MatchAndExplain(const absl::string_view& s, + MatchResultListener* listener) const { + if (s.data() == NULL) { + return !expect_eq_; + } + // This should fail to compile if absl::string_view is used with wide + // strings. + const StringType& str = string(s); + return MatchAndExplain(str, listener); + } +#endif // GTEST_HAS_ABSL + // Accepts pointer types, particularly: // const char* // char* @@ -1145,7 +1333,7 @@ // Matches anything that can convert to StringType. // // This is a template, not just a plain function with const StringType&, - // because StringPiece has some interfering non-explicit constructors. + // because absl::string_view has some interfering non-explicit constructors. template bool MatchAndExplain(const MatcheeStringType& s, MatchResultListener* /* listener */) const { @@ -1189,6 +1377,19 @@ explicit HasSubstrMatcher(const StringType& substring) : substring_(substring) {} +#if GTEST_HAS_ABSL + bool MatchAndExplain(const absl::string_view& s, + MatchResultListener* listener) const { + if (s.data() == NULL) { + return false; + } + // This should fail to compile if absl::string_view is used with wide + // strings. + const StringType& str = string(s); + return MatchAndExplain(str, listener); + } +#endif // GTEST_HAS_ABSL + // Accepts pointer types, particularly: // const char* // char* @@ -1202,7 +1403,7 @@ // Matches anything that can convert to StringType. // // This is a template, not just a plain function with const StringType&, - // because StringPiece has some interfering non-explicit constructors. + // because absl::string_view has some interfering non-explicit constructors. template bool MatchAndExplain(const MatcheeStringType& s, MatchResultListener* /* listener */) const { @@ -1236,6 +1437,19 @@ explicit StartsWithMatcher(const StringType& prefix) : prefix_(prefix) { } +#if GTEST_HAS_ABSL + bool MatchAndExplain(const absl::string_view& s, + MatchResultListener* listener) const { + if (s.data() == NULL) { + return false; + } + // This should fail to compile if absl::string_view is used with wide + // strings. + const StringType& str = string(s); + return MatchAndExplain(str, listener); + } +#endif // GTEST_HAS_ABSL + // Accepts pointer types, particularly: // const char* // char* @@ -1249,7 +1463,7 @@ // Matches anything that can convert to StringType. // // This is a template, not just a plain function with const StringType&, - // because StringPiece has some interfering non-explicit constructors. + // because absl::string_view has some interfering non-explicit constructors. template bool MatchAndExplain(const MatcheeStringType& s, MatchResultListener* /* listener */) const { @@ -1282,6 +1496,19 @@ public: explicit EndsWithMatcher(const StringType& suffix) : suffix_(suffix) {} +#if GTEST_HAS_ABSL + bool MatchAndExplain(const absl::string_view& s, + MatchResultListener* listener) const { + if (s.data() == NULL) { + return false; + } + // This should fail to compile if absl::string_view is used with wide + // strings. + const StringType& str = string(s); + return MatchAndExplain(str, listener); + } +#endif // GTEST_HAS_ABSL + // Accepts pointer types, particularly: // const char* // char* @@ -1295,7 +1522,7 @@ // Matches anything that can convert to StringType. // // This is a template, not just a plain function with const StringType&, - // because StringPiece has some interfering non-explicit constructors. + // because absl::string_view has some interfering non-explicit constructors. template bool MatchAndExplain(const MatcheeStringType& s, MatchResultListener* /* listener */) const { @@ -1328,38 +1555,45 @@ MatchesRegexMatcher(const RE* regex, bool full_match) : regex_(regex), full_match_(full_match) {} +#if GTEST_HAS_ABSL + bool MatchAndExplain(const absl::string_view& s, + MatchResultListener* listener) const { + return s.data() && MatchAndExplain(string(s), listener); + } +#endif // GTEST_HAS_ABSL + // Accepts pointer types, particularly: // const char* // char* // const wchar_t* // wchar_t* template bool MatchAndExplain(CharType* s, MatchResultListener* listener) const { - return s != NULL && MatchAndExplain(internal::string(s), listener); + return s != NULL && MatchAndExplain(std::string(s), listener); } - // Matches anything that can convert to internal::string. + // Matches anything that can convert to std::string. // - // This is a template, not just a plain function with const internal::string&, - // because StringPiece has some interfering non-explicit constructors. + // This is a template, not just a plain function with const std::string&, + // because absl::string_view has some interfering non-explicit constructors. template bool MatchAndExplain(const MatcheeStringType& s, MatchResultListener* /* listener */) const { - const internal::string& s2(s); + const std::string& s2(s); return full_match_ ? RE::FullMatch(s2, *regex_) : RE::PartialMatch(s2, *regex_); } void DescribeTo(::std::ostream* os) const { *os << (full_match_ ? "matches" : "contains") << " regular expression "; - UniversalPrinter::Print(regex_->pattern(), os); + UniversalPrinter::Print(regex_->pattern(), os); } void DescribeNegationTo(::std::ostream* os) const { *os << "doesn't " << (full_match_ ? "match" : "contain") << " regular expression "; - UniversalPrinter::Print(regex_->pattern(), os); + UniversalPrinter::Print(regex_->pattern(), os); } private: @@ -1441,12 +1675,13 @@ // will prevent different instantiations of NotMatcher from sharing // the same NotMatcherImpl class. template -class NotMatcherImpl : public MatcherInterface { +class NotMatcherImpl : public MatcherInterface { public: explicit NotMatcherImpl(const Matcher& matcher) : matcher_(matcher) {} - virtual bool MatchAndExplain(T x, MatchResultListener* listener) const { + virtual bool MatchAndExplain(GTEST_REFERENCE_TO_CONST_(T) x, + MatchResultListener* listener) const { return !matcher_.MatchAndExplain(x, listener); } @@ -1489,117 +1724,66 @@ // that will prevent different instantiations of BothOfMatcher from // sharing the same BothOfMatcherImpl class. template -class BothOfMatcherImpl : public MatcherInterface { +class AllOfMatcherImpl + : public MatcherInterface { public: - BothOfMatcherImpl(const Matcher& matcher1, const Matcher& matcher2) - : matcher1_(matcher1), matcher2_(matcher2) {} + explicit AllOfMatcherImpl(std::vector > matchers) + : matchers_(internal::move(matchers)) {} virtual void DescribeTo(::std::ostream* os) const { *os << "("; - matcher1_.DescribeTo(os); - *os << ") and ("; - matcher2_.DescribeTo(os); + for (size_t i = 0; i < matchers_.size(); ++i) { + if (i != 0) *os << ") and ("; + matchers_[i].DescribeTo(os); + } *os << ")"; } virtual void DescribeNegationTo(::std::ostream* os) const { *os << "("; - matcher1_.DescribeNegationTo(os); - *os << ") or ("; - matcher2_.DescribeNegationTo(os); + for (size_t i = 0; i < matchers_.size(); ++i) { + if (i != 0) *os << ") or ("; + matchers_[i].DescribeNegationTo(os); + } *os << ")"; } - virtual bool MatchAndExplain(T x, MatchResultListener* listener) const { + virtual bool MatchAndExplain(GTEST_REFERENCE_TO_CONST_(T) x, + MatchResultListener* listener) const { // If either matcher1_ or matcher2_ doesn't match x, we only need // to explain why one of them fails. - StringMatchResultListener listener1; - if (!matcher1_.MatchAndExplain(x, &listener1)) { - *listener << listener1.str(); - return false; - } + std::string all_match_result; - StringMatchResultListener listener2; - if (!matcher2_.MatchAndExplain(x, &listener2)) { - *listener << listener2.str(); - return false; + for (size_t i = 0; i < matchers_.size(); ++i) { + StringMatchResultListener slistener; + if (matchers_[i].MatchAndExplain(x, &slistener)) { + if (all_match_result.empty()) { + all_match_result = slistener.str(); + } else { + std::string result = slistener.str(); + if (!result.empty()) { + all_match_result += ", and "; + all_match_result += result; + } + } + } else { + *listener << slistener.str(); + return false; + } } // Otherwise we need to explain why *both* of them match. - const internal::string s1 = listener1.str(); - const internal::string s2 = listener2.str(); - - if (s1 == "") { - *listener << s2; - } else { - *listener << s1; - if (s2 != "") { - *listener << ", and " << s2; - } - } + *listener << all_match_result; return true; } private: - const Matcher matcher1_; - const Matcher matcher2_; + const std::vector > matchers_; - GTEST_DISALLOW_ASSIGN_(BothOfMatcherImpl); + GTEST_DISALLOW_ASSIGN_(AllOfMatcherImpl); }; #if GTEST_LANG_CXX11 -// MatcherList provides mechanisms for storing a variable number of matchers in -// a list structure (ListType) and creating a combining matcher from such a -// list. -// The template is defined recursively using the following template paramters: -// * kSize is the length of the MatcherList. -// * Head is the type of the first matcher of the list. -// * Tail denotes the types of the remaining matchers of the list. -template -struct MatcherList { - typedef MatcherList MatcherListTail; - typedef ::std::pair ListType; - - // BuildList stores variadic type values in a nested pair structure. - // Example: - // MatcherList<3, int, string, float>::BuildList(5, "foo", 2.0) will return - // the corresponding result of type pair>. - static ListType BuildList(const Head& matcher, const Tail&... tail) { - return ListType(matcher, MatcherListTail::BuildList(tail...)); - } - - // CreateMatcher creates a Matcher from a given list of matchers (built - // by BuildList()). CombiningMatcher is used to combine the matchers of the - // list. CombiningMatcher must implement MatcherInterface and have a - // constructor taking two Matchers as input. - template class CombiningMatcher> - static Matcher CreateMatcher(const ListType& matchers) { - return Matcher(new CombiningMatcher( - SafeMatcherCast(matchers.first), - MatcherListTail::template CreateMatcher( - matchers.second))); - } -}; - -// The following defines the base case for the recursive definition of -// MatcherList. -template -struct MatcherList<2, Matcher1, Matcher2> { - typedef ::std::pair ListType; - - static ListType BuildList(const Matcher1& matcher1, - const Matcher2& matcher2) { - return ::std::pair(matcher1, matcher2); - } - - template class CombiningMatcher> - static Matcher CreateMatcher(const ListType& matchers) { - return Matcher(new CombiningMatcher( - SafeMatcherCast(matchers.first), - SafeMatcherCast(matchers.second))); - } -}; - // VariadicMatcher is used for the variadic implementation of // AllOf(m_1, m_2, ...) and AnyOf(m_1, m_2, ...). // CombiningMatcher is used to recursively combine the provided matchers @@ -1608,27 +1792,40 @@ class VariadicMatcher { public: VariadicMatcher(const Args&... matchers) // NOLINT - : matchers_(MatcherListType::BuildList(matchers...)) {} + : matchers_(matchers...) { + static_assert(sizeof...(Args) > 0, "Must have at least one matcher."); + } // This template type conversion operator allows an // VariadicMatcher object to match any type that // all of the provided matchers (Matcher1, Matcher2, ...) can match. template operator Matcher() const { - return MatcherListType::template CreateMatcher( - matchers_); + std::vector > values; + CreateVariadicMatcher(&values, std::integral_constant()); + return Matcher(new CombiningMatcher(internal::move(values))); } private: - typedef MatcherList MatcherListType; + template + void CreateVariadicMatcher(std::vector >* values, + std::integral_constant) const { + values->push_back(SafeMatcherCast(std::get(matchers_))); + CreateVariadicMatcher(values, std::integral_constant()); + } - const typename MatcherListType::ListType matchers_; + template + void CreateVariadicMatcher( + std::vector >*, + std::integral_constant) const {} + tuple matchers_; + GTEST_DISALLOW_ASSIGN_(VariadicMatcher); }; template -using AllOfMatcher = VariadicMatcher; +using AllOfMatcher = VariadicMatcher; #endif // GTEST_LANG_CXX11 @@ -1645,8 +1842,10 @@ // both Matcher1 and Matcher2 can match. template operator Matcher() const { - return Matcher(new BothOfMatcherImpl(SafeMatcherCast(matcher1_), - SafeMatcherCast(matcher2_))); + std::vector > values; + values.push_back(SafeMatcherCast(matcher1_)); + values.push_back(SafeMatcherCast(matcher2_)); + return Matcher(new AllOfMatcherImpl(internal::move(values))); } private: @@ -1661,68 +1860,69 @@ // that will prevent different instantiations of AnyOfMatcher from // sharing the same EitherOfMatcherImpl class. template -class EitherOfMatcherImpl : public MatcherInterface { +class AnyOfMatcherImpl + : public MatcherInterface { public: - EitherOfMatcherImpl(const Matcher& matcher1, const Matcher& matcher2) - : matcher1_(matcher1), matcher2_(matcher2) {} + explicit AnyOfMatcherImpl(std::vector > matchers) + : matchers_(internal::move(matchers)) {} virtual void DescribeTo(::std::ostream* os) const { *os << "("; - matcher1_.DescribeTo(os); - *os << ") or ("; - matcher2_.DescribeTo(os); + for (size_t i = 0; i < matchers_.size(); ++i) { + if (i != 0) *os << ") or ("; + matchers_[i].DescribeTo(os); + } *os << ")"; } virtual void DescribeNegationTo(::std::ostream* os) const { *os << "("; - matcher1_.DescribeNegationTo(os); - *os << ") and ("; - matcher2_.DescribeNegationTo(os); + for (size_t i = 0; i < matchers_.size(); ++i) { + if (i != 0) *os << ") and ("; + matchers_[i].DescribeNegationTo(os); + } *os << ")"; } - virtual bool MatchAndExplain(T x, MatchResultListener* listener) const { + virtual bool MatchAndExplain(GTEST_REFERENCE_TO_CONST_(T) x, + MatchResultListener* listener) const { + std::string no_match_result; + // If either matcher1_ or matcher2_ matches x, we just need to // explain why *one* of them matches. - StringMatchResultListener listener1; - if (matcher1_.MatchAndExplain(x, &listener1)) { - *listener << listener1.str(); - return true; + for (size_t i = 0; i < matchers_.size(); ++i) { + StringMatchResultListener slistener; + if (matchers_[i].MatchAndExplain(x, &slistener)) { + *listener << slistener.str(); + return true; + } else { + if (no_match_result.empty()) { + no_match_result = slistener.str(); + } else { + std::string result = slistener.str(); + if (!result.empty()) { + no_match_result += ", and "; + no_match_result += result; + } + } + } } - StringMatchResultListener listener2; - if (matcher2_.MatchAndExplain(x, &listener2)) { - *listener << listener2.str(); - return true; - } - // Otherwise we need to explain why *both* of them fail. - const internal::string s1 = listener1.str(); - const internal::string s2 = listener2.str(); - - if (s1 == "") { - *listener << s2; - } else { - *listener << s1; - if (s2 != "") { - *listener << ", and " << s2; - } - } + *listener << no_match_result; return false; } private: - const Matcher matcher1_; - const Matcher matcher2_; + const std::vector > matchers_; - GTEST_DISALLOW_ASSIGN_(EitherOfMatcherImpl); + GTEST_DISALLOW_ASSIGN_(AnyOfMatcherImpl); }; #if GTEST_LANG_CXX11 // AnyOfMatcher is used for the variadic implementation of AnyOf(m_1, m_2, ...). template -using AnyOfMatcher = VariadicMatcher; +using AnyOfMatcher = VariadicMatcher; #endif // GTEST_LANG_CXX11 @@ -1740,8 +1940,10 @@ // both Matcher1 and Matcher2 can match. template operator Matcher() const { - return Matcher(new EitherOfMatcherImpl( - SafeMatcherCast(matcher1_), SafeMatcherCast(matcher2_))); + std::vector > values; + values.push_back(SafeMatcherCast(matcher1_)); + values.push_back(SafeMatcherCast(matcher2_)); + return Matcher(new AnyOfMatcherImpl(internal::move(values))); } private: @@ -2037,6 +2239,82 @@ GTEST_DISALLOW_ASSIGN_(FloatingEqMatcher); }; +// A 2-tuple ("binary") wrapper around FloatingEqMatcher: +// FloatingEq2Matcher() matches (x, y) by matching FloatingEqMatcher(x, false) +// against y, and FloatingEq2Matcher(e) matches FloatingEqMatcher(x, false, e) +// against y. The former implements "Eq", the latter "Near". At present, there +// is no version that compares NaNs as equal. +template +class FloatingEq2Matcher { + public: + FloatingEq2Matcher() { Init(-1, false); } + + explicit FloatingEq2Matcher(bool nan_eq_nan) { Init(-1, nan_eq_nan); } + + explicit FloatingEq2Matcher(FloatType max_abs_error) { + Init(max_abs_error, false); + } + + FloatingEq2Matcher(FloatType max_abs_error, bool nan_eq_nan) { + Init(max_abs_error, nan_eq_nan); + } + + template + operator Matcher< ::testing::tuple >() const { + return MakeMatcher( + new Impl< ::testing::tuple >(max_abs_error_, nan_eq_nan_)); + } + template + operator Matcher&>() const { + return MakeMatcher( + new Impl&>(max_abs_error_, nan_eq_nan_)); + } + + private: + static ::std::ostream& GetDesc(::std::ostream& os) { // NOLINT + return os << "an almost-equal pair"; + } + + template + class Impl : public MatcherInterface { + public: + Impl(FloatType max_abs_error, bool nan_eq_nan) : + max_abs_error_(max_abs_error), + nan_eq_nan_(nan_eq_nan) {} + + virtual bool MatchAndExplain(Tuple args, + MatchResultListener* listener) const { + if (max_abs_error_ == -1) { + FloatingEqMatcher fm(::testing::get<0>(args), nan_eq_nan_); + return static_cast >(fm).MatchAndExplain( + ::testing::get<1>(args), listener); + } else { + FloatingEqMatcher fm(::testing::get<0>(args), nan_eq_nan_, + max_abs_error_); + return static_cast >(fm).MatchAndExplain( + ::testing::get<1>(args), listener); + } + } + virtual void DescribeTo(::std::ostream* os) const { + *os << "are " << GetDesc; + } + virtual void DescribeNegationTo(::std::ostream* os) const { + *os << "aren't " << GetDesc; + } + + private: + FloatType max_abs_error_; + const bool nan_eq_nan_; + }; + + void Init(FloatType max_abs_error_val, bool nan_eq_nan_val) { + max_abs_error_ = max_abs_error_val; + nan_eq_nan_ = nan_eq_nan_val; + } + FloatType max_abs_error_; + bool nan_eq_nan_; +}; + // Implements the Pointee(m) matcher for matching a pointer whose // pointee matches matcher m. The pointer can be either raw or smart. template @@ -2054,7 +2332,8 @@ // enough for implementing the DescribeTo() method of Pointee(). template operator Matcher() const { - return MakeMatcher(new Impl(matcher_)); + return Matcher( + new Impl(matcher_)); } private: @@ -2098,6 +2377,7 @@ GTEST_DISALLOW_ASSIGN_(PointeeMatcher); }; +#if GTEST_HAS_RTTI // Implements the WhenDynamicCastTo(m) matcher that matches a pointer or // reference that matches inner_matcher when dynamic_cast is applied. // The result of dynamic_cast is forwarded to the inner matcher. @@ -2123,12 +2403,8 @@ protected: const Matcher matcher_; - static string GetToName() { -#if GTEST_HAS_RTTI + static std::string GetToName() { return GetTypeName(); -#else // GTEST_HAS_RTTI - return "the target type"; -#endif // GTEST_HAS_RTTI } private: @@ -2149,7 +2425,7 @@ template bool MatchAndExplain(From from, MatchResultListener* listener) const { - // TODO(sbenza): Add more detail on failures. ie did the dyn_cast fail? + // FIXME: Add more detail on failures. ie did the dyn_cast fail? To to = dynamic_cast(from); return MatchPrintAndExplain(to, this->matcher_, listener); } @@ -2174,6 +2450,7 @@ return MatchPrintAndExplain(*to, this->matcher_, listener); } }; +#endif // GTEST_HAS_RTTI // Implements the Field() matcher for matching a field (i.e. member // variable) of an object. @@ -2182,15 +2459,21 @@ public: FieldMatcher(FieldType Class::*field, const Matcher& matcher) - : field_(field), matcher_(matcher) {} + : field_(field), matcher_(matcher), whose_field_("whose given field ") {} + FieldMatcher(const std::string& field_name, FieldType Class::*field, + const Matcher& matcher) + : field_(field), + matcher_(matcher), + whose_field_("whose field `" + field_name + "` ") {} + void DescribeTo(::std::ostream* os) const { - *os << "is an object whose given field "; + *os << "is an object " << whose_field_; matcher_.DescribeTo(os); } void DescribeNegationTo(::std::ostream* os) const { - *os << "is an object whose given field "; + *os << "is an object " << whose_field_; matcher_.DescribeNegationTo(os); } @@ -2208,7 +2491,7 @@ // true_type iff the Field() matcher is used to match a pointer. bool MatchAndExplainImpl(false_type /* is_not_pointer */, const Class& obj, MatchResultListener* listener) const { - *listener << "whose given field is "; + *listener << whose_field_ << "is "; return MatchPrintAndExplain(obj.*field_, matcher_, listener); } @@ -2227,12 +2510,19 @@ const FieldType Class::*field_; const Matcher matcher_; + // Contains either "whose given field " if the name of the field is unknown + // or "whose field `name_of_field` " if the name is known. + const std::string whose_field_; + GTEST_DISALLOW_ASSIGN_(FieldMatcher); }; // Implements the Property() matcher for matching a property // (i.e. return value of a getter method) of an object. -template +// +// Property is a const-qualified member function of Class returning +// PropertyType. +template class PropertyMatcher { public: // The property may have a reference type, so 'const PropertyType&' @@ -2241,17 +2531,24 @@ // PropertyType being a reference or not. typedef GTEST_REFERENCE_TO_CONST_(PropertyType) RefToConstProperty; - PropertyMatcher(PropertyType (Class::*property)() const, + PropertyMatcher(Property property, const Matcher& matcher) + : property_(property), + matcher_(matcher), + whose_property_("whose given property ") {} + + PropertyMatcher(const std::string& property_name, Property property, const Matcher& matcher) - : property_(property), matcher_(matcher) {} + : property_(property), + matcher_(matcher), + whose_property_("whose property `" + property_name + "` ") {} void DescribeTo(::std::ostream* os) const { - *os << "is an object whose given property "; + *os << "is an object " << whose_property_; matcher_.DescribeTo(os); } void DescribeNegationTo(::std::ostream* os) const { - *os << "is an object whose given property "; + *os << "is an object " << whose_property_; matcher_.DescribeNegationTo(os); } @@ -2269,7 +2566,7 @@ // true_type iff the Property() matcher is used to match a pointer. bool MatchAndExplainImpl(false_type /* is_not_pointer */, const Class& obj, MatchResultListener* listener) const { - *listener << "whose given property is "; + *listener << whose_property_ << "is "; // Cannot pass the return value (for example, int) to MatchPrintAndExplain, // which takes a non-const reference as argument. #if defined(_PREFAST_ ) && _MSC_VER == 1800 @@ -2295,24 +2592,32 @@ return MatchAndExplainImpl(false_type(), *p, listener); } - PropertyType (Class::*property_)() const; + Property property_; const Matcher matcher_; + // Contains either "whose given property " if the name of the property is + // unknown or "whose property `name_of_property` " if the name is known. + const std::string whose_property_; + GTEST_DISALLOW_ASSIGN_(PropertyMatcher); }; // Type traits specifying various features of different functors for ResultOf. // The default template specifies features for functor objects. -// Functor classes have to typedef argument_type and result_type -// to be compatible with ResultOf. template struct CallableTraits { - typedef typename Functor::result_type ResultType; typedef Functor StorageType; static void CheckIsValid(Functor /* functor */) {} + +#if GTEST_LANG_CXX11 template + static auto Invoke(Functor f, T arg) -> decltype(f(arg)) { return f(arg); } +#else + typedef typename Functor::result_type ResultType; + template static ResultType Invoke(Functor f, T arg) { return f(arg); } +#endif }; // Specialization for function pointers. @@ -2333,13 +2638,11 @@ // Implements the ResultOf() matcher for matching a return value of a // unary function of an object. -template +template class ResultOfMatcher { public: - typedef typename CallableTraits::ResultType ResultType; - - ResultOfMatcher(Callable callable, const Matcher& matcher) - : callable_(callable), matcher_(matcher) { + ResultOfMatcher(Callable callable, InnerMatcher matcher) + : callable_(internal::move(callable)), matcher_(internal::move(matcher)) { CallableTraits::CheckIsValid(callable_); } @@ -2353,9 +2656,17 @@ template class Impl : public MatcherInterface { +#if GTEST_LANG_CXX11 + using ResultType = decltype(CallableTraits::template Invoke( + std::declval(), std::declval())); +#else + typedef typename CallableTraits::ResultType ResultType; +#endif + public: - Impl(CallableStorageType callable, const Matcher& matcher) - : callable_(callable), matcher_(matcher) {} + template + Impl(const CallableStorageType& callable, const M& matcher) + : callable_(callable), matcher_(MatcherCast(matcher)) {} virtual void DescribeTo(::std::ostream* os) const { *os << "is mapped by the given callable to a value that "; @@ -2369,18 +2680,20 @@ virtual bool MatchAndExplain(T obj, MatchResultListener* listener) const { *listener << "which is mapped by the given callable to "; - // Cannot pass the return value (for example, int) to - // MatchPrintAndExplain, which takes a non-const reference as argument. + // Cannot pass the return value directly to MatchPrintAndExplain, which + // takes a non-const reference as argument. + // Also, specifying template argument explicitly is needed because T could + // be a non-const reference (e.g. Matcher). ResultType result = CallableTraits::template Invoke(callable_, obj); return MatchPrintAndExplain(result, matcher_, listener); } private: // Functors often define operator() as non-const method even though - // they are actualy stateless. But we need to use them even when + // they are actually stateless. But we need to use them even when // 'this' is a const pointer. It's the user's responsibility not to - // use stateful callables with ResultOf(), which does't guarantee + // use stateful callables with ResultOf(), which doesn't guarantee // how many times the callable will be invoked. mutable CallableStorageType callable_; const Matcher matcher_; @@ -2389,7 +2702,7 @@ }; // class Impl const CallableStorageType callable_; - const Matcher matcher_; + const InnerMatcher matcher_; GTEST_DISALLOW_ASSIGN_(ResultOfMatcher); }; @@ -2691,6 +3004,10 @@ // container and the RHS container respectively. template class PointwiseMatcher { + GTEST_COMPILE_ASSERT_( + !IsHashTable::value, + use_UnorderedPointwise_with_hash_tables); + public: typedef internal::StlContainerView RhsView; typedef typename RhsView::type RhsStlContainer; @@ -2708,6 +3025,10 @@ template operator Matcher() const { + GTEST_COMPILE_ASSERT_( + !IsHashTable::value, + use_UnorderedPointwise_with_hash_tables); + return MakeMatcher(new Impl(tuple_matcher_, rhs_)); } @@ -2758,12 +3079,15 @@ typename LhsStlContainer::const_iterator left = lhs_stl_container.begin(); typename RhsStlContainer::const_iterator right = rhs_.begin(); for (size_t i = 0; i != actual_size; ++i, ++left, ++right) { - const InnerMatcherArg value_pair(*left, *right); - if (listener->IsInterested()) { StringMatchResultListener inner_listener; + // Create InnerMatcherArg as a temporarily object to avoid it outlives + // *left and *right. Dereference or the conversion to `const T&` may + // return temp objects, e.g for vector. if (!mono_tuple_matcher_.MatchAndExplain( - value_pair, &inner_listener)) { + InnerMatcherArg(ImplicitCast_(*left), + ImplicitCast_(*right)), + &inner_listener)) { *listener << "where the value pair ("; UniversalPrint(*left, listener->stream()); *listener << ", "; @@ -2773,7 +3097,9 @@ return false; } } else { - if (!mono_tuple_matcher_.Matches(value_pair)) + if (!mono_tuple_matcher_.Matches( + InnerMatcherArg(ImplicitCast_(*left), + ImplicitCast_(*right)))) return false; } } @@ -2931,6 +3257,50 @@ GTEST_DISALLOW_ASSIGN_(EachMatcher); }; +struct Rank1 {}; +struct Rank0 : Rank1 {}; + +namespace pair_getters { +#if GTEST_LANG_CXX11 +using std::get; +template +auto First(T& x, Rank1) -> decltype(get<0>(x)) { // NOLINT + return get<0>(x); +} +template +auto First(T& x, Rank0) -> decltype((x.first)) { // NOLINT + return x.first; +} + +template +auto Second(T& x, Rank1) -> decltype(get<1>(x)) { // NOLINT + return get<1>(x); +} +template +auto Second(T& x, Rank0) -> decltype((x.second)) { // NOLINT + return x.second; +} +#else +template +typename T::first_type& First(T& x, Rank0) { // NOLINT + return x.first; +} +template +const typename T::first_type& First(const T& x, Rank0) { + return x.first; +} + +template +typename T::second_type& Second(T& x, Rank0) { // NOLINT + return x.second; +} +template +const typename T::second_type& Second(const T& x, Rank0) { + return x.second; +} +#endif // GTEST_LANG_CXX11 +} // namespace pair_getters + // Implements Key(inner_matcher) for the given argument pair type. // Key(inner_matcher) matches an std::pair whose 'first' field matches // inner_matcher. For example, Contains(Key(Ge(5))) can be used to match an @@ -2951,9 +3321,9 @@ virtual bool MatchAndExplain(PairType key_value, MatchResultListener* listener) const { StringMatchResultListener inner_listener; - const bool match = inner_matcher_.MatchAndExplain(key_value.first, - &inner_listener); - const internal::string explanation = inner_listener.str(); + const bool match = inner_matcher_.MatchAndExplain( + pair_getters::First(key_value, Rank0()), &inner_listener); + const std::string explanation = inner_listener.str(); if (explanation != "") { *listener << "whose first field is a value " << explanation; } @@ -3035,18 +3405,18 @@ if (!listener->IsInterested()) { // If the listener is not interested, we don't need to construct the // explanation. - return first_matcher_.Matches(a_pair.first) && - second_matcher_.Matches(a_pair.second); + return first_matcher_.Matches(pair_getters::First(a_pair, Rank0())) && + second_matcher_.Matches(pair_getters::Second(a_pair, Rank0())); } StringMatchResultListener first_inner_listener; - if (!first_matcher_.MatchAndExplain(a_pair.first, + if (!first_matcher_.MatchAndExplain(pair_getters::First(a_pair, Rank0()), &first_inner_listener)) { *listener << "whose first field does not match"; PrintIfNotEmpty(first_inner_listener.str(), listener->stream()); return false; } StringMatchResultListener second_inner_listener; - if (!second_matcher_.MatchAndExplain(a_pair.second, + if (!second_matcher_.MatchAndExplain(pair_getters::Second(a_pair, Rank0()), &second_inner_listener)) { *listener << "whose second field does not match"; PrintIfNotEmpty(second_inner_listener.str(), listener->stream()); @@ -3058,8 +3428,8 @@ } private: - void ExplainSuccess(const internal::string& first_explanation, - const internal::string& second_explanation, + void ExplainSuccess(const std::string& first_explanation, + const std::string& second_explanation, MatchResultListener* listener) const { *listener << "whose both fields match"; if (first_explanation != "") { @@ -3166,7 +3536,7 @@ const bool listener_interested = listener->IsInterested(); // explanations[i] is the explanation of the element at index i. - ::std::vector explanations(count()); + ::std::vector explanations(count()); StlContainerReference stl_container = View::ConstReference(container); typename StlContainer::const_iterator it = stl_container.begin(); size_t exam_pos = 0; @@ -3225,7 +3595,7 @@ if (listener_interested) { bool reason_printed = false; for (size_t i = 0; i != count(); ++i) { - const internal::string& s = explanations[i]; + const std::string& s = explanations[i]; if (!s.empty()) { if (reason_printed) { *listener << ",\nand "; @@ -3278,7 +3648,7 @@ void Randomize(); - string DebugString() const; + std::string DebugString() const; private: size_t SpaceIndex(size_t ilhs, size_t irhs) const { @@ -3302,14 +3672,23 @@ GTEST_API_ ElementMatcherPairs FindMaxBipartiteMatching(const MatchMatrix& g); -GTEST_API_ bool FindPairing(const MatchMatrix& matrix, - MatchResultListener* listener); +struct UnorderedMatcherRequire { + enum Flags { + Superset = 1 << 0, + Subset = 1 << 1, + ExactMatch = Superset | Subset, + }; +}; // Untyped base class for implementing UnorderedElementsAre. By // putting logic that's not specific to the element type here, we // reduce binary bloat and increase compilation speed. class GTEST_API_ UnorderedElementsAreMatcherImplBase { protected: + explicit UnorderedElementsAreMatcherImplBase( + UnorderedMatcherRequire::Flags matcher_flags) + : match_flags_(matcher_flags) {} + // A vector of matcher describers, one for each element matcher. // Does not own the describers (and thus can be used only when the // element matchers are alive). @@ -3321,11 +3700,13 @@ // Describes the negation of this UnorderedElementsAre matcher. void DescribeNegationToImpl(::std::ostream* os) const; - bool VerifyAllElementsAndMatchersAreMatched( - const ::std::vector& element_printouts, - const MatchMatrix& matrix, - MatchResultListener* listener) const; + bool VerifyMatchMatrix(const ::std::vector& element_printouts, + const MatchMatrix& matrix, + MatchResultListener* listener) const; + bool FindPairing(const MatchMatrix& matrix, + MatchResultListener* listener) const; + MatcherDescriberVec& matcher_describers() { return matcher_describers_; } @@ -3334,13 +3715,17 @@ return Message() << n << " element" << (n == 1 ? "" : "s"); } + UnorderedMatcherRequire::Flags match_flags() const { return match_flags_; } + private: + UnorderedMatcherRequire::Flags match_flags_; MatcherDescriberVec matcher_describers_; GTEST_DISALLOW_ASSIGN_(UnorderedElementsAreMatcherImplBase); }; -// Implements unordered ElementsAre and unordered ElementsAreArray. +// Implements UnorderedElementsAre, UnorderedElementsAreArray, IsSubsetOf, and +// IsSupersetOf. template class UnorderedElementsAreMatcherImpl : public MatcherInterface, @@ -3353,10 +3738,10 @@ typedef typename StlContainer::const_iterator StlContainerConstIterator; typedef typename StlContainer::value_type Element; - // Constructs the matcher from a sequence of element values or - // element matchers. template - UnorderedElementsAreMatcherImpl(InputIter first, InputIter last) { + UnorderedElementsAreMatcherImpl(UnorderedMatcherRequire::Flags matcher_flags, + InputIter first, InputIter last) + : UnorderedElementsAreMatcherImplBase(matcher_flags) { for (; first != last; ++first) { matchers_.push_back(MatcherCast(*first)); matcher_describers().push_back(matchers_.back().GetDescriber()); @@ -3376,38 +3761,36 @@ virtual bool MatchAndExplain(Container container, MatchResultListener* listener) const { StlContainerReference stl_container = View::ConstReference(container); - ::std::vector element_printouts; - MatchMatrix matrix = AnalyzeElements(stl_container.begin(), - stl_container.end(), - &element_printouts, - listener); + ::std::vector element_printouts; + MatchMatrix matrix = + AnalyzeElements(stl_container.begin(), stl_container.end(), + &element_printouts, listener); - const size_t actual_count = matrix.LhsSize(); - if (actual_count == 0 && matchers_.empty()) { + if (matrix.LhsSize() == 0 && matrix.RhsSize() == 0) { return true; } - if (actual_count != matchers_.size()) { - // The element count doesn't match. If the container is empty, - // there's no need to explain anything as Google Mock already - // prints the empty container. Otherwise we just need to show - // how many elements there actually are. - if (actual_count != 0 && listener->IsInterested()) { - *listener << "which has " << Elements(actual_count); + + if (match_flags() == UnorderedMatcherRequire::ExactMatch) { + if (matrix.LhsSize() != matrix.RhsSize()) { + // The element count doesn't match. If the container is empty, + // there's no need to explain anything as Google Mock already + // prints the empty container. Otherwise we just need to show + // how many elements there actually are. + if (matrix.LhsSize() != 0 && listener->IsInterested()) { + *listener << "which has " << Elements(matrix.LhsSize()); + } + return false; } - return false; } - return VerifyAllElementsAndMatchersAreMatched(element_printouts, - matrix, listener) && + return VerifyMatchMatrix(element_printouts, matrix, listener) && FindPairing(matrix, listener); } private: - typedef ::std::vector > MatcherVec; - template MatchMatrix AnalyzeElements(ElementIter elem_first, ElementIter elem_last, - ::std::vector* element_printouts, + ::std::vector* element_printouts, MatchResultListener* listener) const { element_printouts->clear(); ::std::vector did_match; @@ -3431,7 +3814,7 @@ return matrix; } - MatcherVec matchers_; + ::std::vector > matchers_; GTEST_DISALLOW_ASSIGN_(UnorderedElementsAreMatcherImpl); }; @@ -3464,7 +3847,7 @@ TransformTupleValues(CastAndAppendTransform(), matchers_, ::std::back_inserter(matchers)); return MakeMatcher(new UnorderedElementsAreMatcherImpl( - matchers.begin(), matchers.end())); + UnorderedMatcherRequire::ExactMatch, matchers.begin(), matchers.end())); } private: @@ -3480,6 +3863,11 @@ template operator Matcher() const { + GTEST_COMPILE_ASSERT_( + !IsHashTable::value || + ::testing::tuple_size::value < 2, + use_UnorderedElementsAre_with_hash_tables); + typedef GTEST_REMOVE_REFERENCE_AND_CONST_(Container) RawContainer; typedef typename internal::StlContainerView::type View; typedef typename View::value_type Element; @@ -3497,24 +3885,23 @@ GTEST_DISALLOW_ASSIGN_(ElementsAreMatcher); }; -// Implements UnorderedElementsAreArray(). +// Implements UnorderedElementsAreArray(), IsSubsetOf(), and IsSupersetOf(). template class UnorderedElementsAreArrayMatcher { public: - UnorderedElementsAreArrayMatcher() {} - template - UnorderedElementsAreArrayMatcher(Iter first, Iter last) - : matchers_(first, last) {} + UnorderedElementsAreArrayMatcher(UnorderedMatcherRequire::Flags match_flags, + Iter first, Iter last) + : match_flags_(match_flags), matchers_(first, last) {} template operator Matcher() const { - return MakeMatcher( - new UnorderedElementsAreMatcherImpl(matchers_.begin(), - matchers_.end())); + return MakeMatcher(new UnorderedElementsAreMatcherImpl( + match_flags_, matchers_.begin(), matchers_.end())); } private: + UnorderedMatcherRequire::Flags match_flags_; ::std::vector matchers_; GTEST_DISALLOW_ASSIGN_(UnorderedElementsAreArrayMatcher); @@ -3529,6 +3916,10 @@ template operator Matcher() const { + GTEST_COMPILE_ASSERT_( + !IsHashTable::value, + use_UnorderedElementsAreArray_with_hash_tables); + return MakeMatcher(new ElementsAreMatcherImpl( matchers_.begin(), matchers_.end())); } @@ -3619,13 +4010,189 @@ // 'negation' is false; otherwise returns the description of the // negation of the matcher. 'param_values' contains a list of strings // that are the print-out of the matcher's parameters. -GTEST_API_ string FormatMatcherDescription(bool negation, - const char* matcher_name, - const Strings& param_values); +GTEST_API_ std::string FormatMatcherDescription(bool negation, + const char* matcher_name, + const Strings& param_values); +// Implements a matcher that checks the value of a optional<> type variable. +template +class OptionalMatcher { + public: + explicit OptionalMatcher(const ValueMatcher& value_matcher) + : value_matcher_(value_matcher) {} + + template + operator Matcher() const { + return MakeMatcher(new Impl(value_matcher_)); + } + + template + class Impl : public MatcherInterface { + public: + typedef GTEST_REMOVE_REFERENCE_AND_CONST_(Optional) OptionalView; + typedef typename OptionalView::value_type ValueType; + explicit Impl(const ValueMatcher& value_matcher) + : value_matcher_(MatcherCast(value_matcher)) {} + + virtual void DescribeTo(::std::ostream* os) const { + *os << "value "; + value_matcher_.DescribeTo(os); + } + + virtual void DescribeNegationTo(::std::ostream* os) const { + *os << "value "; + value_matcher_.DescribeNegationTo(os); + } + + virtual bool MatchAndExplain(Optional optional, + MatchResultListener* listener) const { + if (!optional) { + *listener << "which is not engaged"; + return false; + } + const ValueType& value = *optional; + StringMatchResultListener value_listener; + const bool match = value_matcher_.MatchAndExplain(value, &value_listener); + *listener << "whose value " << PrintToString(value) + << (match ? " matches" : " doesn't match"); + PrintIfNotEmpty(value_listener.str(), listener->stream()); + return match; + } + + private: + const Matcher value_matcher_; + GTEST_DISALLOW_ASSIGN_(Impl); + }; + + private: + const ValueMatcher value_matcher_; + GTEST_DISALLOW_ASSIGN_(OptionalMatcher); +}; + +namespace variant_matcher { +// Overloads to allow VariantMatcher to do proper ADL lookup. +template +void holds_alternative() {} +template +void get() {} + +// Implements a matcher that checks the value of a variant<> type variable. +template +class VariantMatcher { + public: + explicit VariantMatcher(::testing::Matcher matcher) + : matcher_(internal::move(matcher)) {} + + template + bool MatchAndExplain(const Variant& value, + ::testing::MatchResultListener* listener) const { + if (!listener->IsInterested()) { + return holds_alternative(value) && matcher_.Matches(get(value)); + } + + if (!holds_alternative(value)) { + *listener << "whose value is not of type '" << GetTypeName() << "'"; + return false; + } + + const T& elem = get(value); + StringMatchResultListener elem_listener; + const bool match = matcher_.MatchAndExplain(elem, &elem_listener); + *listener << "whose value " << PrintToString(elem) + << (match ? " matches" : " doesn't match"); + PrintIfNotEmpty(elem_listener.str(), listener->stream()); + return match; + } + + void DescribeTo(std::ostream* os) const { + *os << "is a variant<> with value of type '" << GetTypeName() + << "' and the value "; + matcher_.DescribeTo(os); + } + + void DescribeNegationTo(std::ostream* os) const { + *os << "is a variant<> with value of type other than '" << GetTypeName() + << "' or the value "; + matcher_.DescribeNegationTo(os); + } + + private: + static std::string GetTypeName() { +#if GTEST_HAS_RTTI + GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_( + return internal::GetTypeName()); +#endif + return "the element type"; + } + + const ::testing::Matcher matcher_; +}; + +} // namespace variant_matcher + +namespace any_cast_matcher { + +// Overloads to allow AnyCastMatcher to do proper ADL lookup. +template +void any_cast() {} + +// Implements a matcher that any_casts the value. +template +class AnyCastMatcher { + public: + explicit AnyCastMatcher(const ::testing::Matcher& matcher) + : matcher_(matcher) {} + + template + bool MatchAndExplain(const AnyType& value, + ::testing::MatchResultListener* listener) const { + if (!listener->IsInterested()) { + const T* ptr = any_cast(&value); + return ptr != NULL && matcher_.Matches(*ptr); + } + + const T* elem = any_cast(&value); + if (elem == NULL) { + *listener << "whose value is not of type '" << GetTypeName() << "'"; + return false; + } + + StringMatchResultListener elem_listener; + const bool match = matcher_.MatchAndExplain(*elem, &elem_listener); + *listener << "whose value " << PrintToString(*elem) + << (match ? " matches" : " doesn't match"); + PrintIfNotEmpty(elem_listener.str(), listener->stream()); + return match; + } + + void DescribeTo(std::ostream* os) const { + *os << "is an 'any' type with value of type '" << GetTypeName() + << "' and the value "; + matcher_.DescribeTo(os); + } + + void DescribeNegationTo(std::ostream* os) const { + *os << "is an 'any' type with value of type other than '" << GetTypeName() + << "' or the value "; + matcher_.DescribeNegationTo(os); + } + + private: + static std::string GetTypeName() { +#if GTEST_HAS_RTTI + GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_( + return internal::GetTypeName()); +#endif + return "the element type"; + } + + const ::testing::Matcher matcher_; +}; + +} // namespace any_cast_matcher } // namespace internal -// ElementsAreArray(first, last) +// ElementsAreArray(iterator_first, iterator_last) // ElementsAreArray(pointer, count) // ElementsAreArray(array) // ElementsAreArray(container) @@ -3674,20 +4241,26 @@ } #endif -// UnorderedElementsAreArray(first, last) +// UnorderedElementsAreArray(iterator_first, iterator_last) // UnorderedElementsAreArray(pointer, count) // UnorderedElementsAreArray(array) // UnorderedElementsAreArray(container) // UnorderedElementsAreArray({ e1, e2, ..., en }) // -// The UnorderedElementsAreArray() functions are like -// ElementsAreArray(...), but allow matching the elements in any order. +// UnorderedElementsAreArray() verifies that a bijective mapping onto a +// collection of matchers exists. +// +// The matchers can be specified as an array, a pointer and count, a container, +// an initializer list, or an STL iterator range. In each of these cases, the +// underlying matchers can be either values or matchers. + template inline internal::UnorderedElementsAreArrayMatcher< typename ::std::iterator_traits::value_type> UnorderedElementsAreArray(Iter first, Iter last) { typedef typename ::std::iterator_traits::value_type T; - return internal::UnorderedElementsAreArrayMatcher(first, last); + return internal::UnorderedElementsAreArrayMatcher( + internal::UnorderedMatcherRequire::ExactMatch, first, last); } template @@ -3729,7 +4302,9 @@ const internal::AnythingMatcher _ = {}; // Creates a matcher that matches any value of the given type T. template -inline Matcher A() { return MakeMatcher(new internal::AnyMatcherImpl()); } +inline Matcher A() { + return Matcher(new internal::AnyMatcherImpl()); +} // Creates a matcher that matches any value of the given type T. template @@ -3746,6 +4321,14 @@ template Matcher::Matcher(T value) { *this = Eq(value); } +template +Matcher internal::MatcherCastImpl::CastImpl( + const M& value, + internal::BooleanConstant /* convertible_to_matcher */, + internal::BooleanConstant /* convertible_to_T */) { + return Eq(value); +} + // Creates a monomorphic matcher that matches anything with type Lhs // and equal to rhs. A user may need to use this instead of Eq(...) // in order to resolve an overloading ambiguity. @@ -3874,6 +4457,7 @@ return internal::PointeeMatcher(inner_matcher); } +#if GTEST_HAS_RTTI // Creates a matcher that matches a pointer or reference that matches // inner_matcher when dynamic_cast is applied. // The result of dynamic_cast is forwarded to the inner matcher. @@ -3886,6 +4470,7 @@ return MakePolymorphicMatcher( internal::WhenDynamicCastToMatcher(inner_matcher)); } +#endif // GTEST_HAS_RTTI // Creates a matcher that matches an object whose given field matches // 'matcher'. For example, @@ -3904,16 +4489,28 @@ // to compile where bar is an int32 and m is a matcher for int64. } +// Same as Field() but also takes the name of the field to provide better error +// messages. +template +inline PolymorphicMatcher > Field( + const std::string& field_name, FieldType Class::*field, + const FieldMatcher& matcher) { + return MakePolymorphicMatcher(internal::FieldMatcher( + field_name, field, MatcherCast(matcher))); +} + // Creates a matcher that matches an object whose given property // matches 'matcher'. For example, // Property(&Foo::str, StartsWith("hi")) // matches a Foo object x iff x.str() starts with "hi". template -inline PolymorphicMatcher< - internal::PropertyMatcher > Property( - PropertyType (Class::*property)() const, const PropertyMatcher& matcher) { +inline PolymorphicMatcher > +Property(PropertyType (Class::*property)() const, + const PropertyMatcher& matcher) { return MakePolymorphicMatcher( - internal::PropertyMatcher( + internal::PropertyMatcher( property, MatcherCast(matcher))); // The call to MatcherCast() is required for supporting inner @@ -3922,82 +4519,115 @@ // to compile where bar() returns an int32 and m is a matcher for int64. } +// Same as Property() above, but also takes the name of the property to provide +// better error messages. +template +inline PolymorphicMatcher > +Property(const std::string& property_name, + PropertyType (Class::*property)() const, + const PropertyMatcher& matcher) { + return MakePolymorphicMatcher( + internal::PropertyMatcher( + property_name, property, + MatcherCast(matcher))); +} + +#if GTEST_LANG_CXX11 +// The same as above but for reference-qualified member functions. +template +inline PolymorphicMatcher > +Property(PropertyType (Class::*property)() const &, + const PropertyMatcher& matcher) { + return MakePolymorphicMatcher( + internal::PropertyMatcher( + property, + MatcherCast(matcher))); +} + +// Three-argument form for reference-qualified member functions. +template +inline PolymorphicMatcher > +Property(const std::string& property_name, + PropertyType (Class::*property)() const &, + const PropertyMatcher& matcher) { + return MakePolymorphicMatcher( + internal::PropertyMatcher( + property_name, property, + MatcherCast(matcher))); +} +#endif + // Creates a matcher that matches an object iff the result of applying // a callable to x matches 'matcher'. // For example, // ResultOf(f, StartsWith("hi")) // matches a Foo object x iff f(x) starts with "hi". -// callable parameter can be a function, function pointer, or a functor. -// Callable has to satisfy the following conditions: -// * It is required to keep no state affecting the results of -// the calls on it and make no assumptions about how many calls -// will be made. Any state it keeps must be protected from the -// concurrent access. -// * If it is a function object, it has to define type result_type. -// We recommend deriving your functor classes from std::unary_function. -template -internal::ResultOfMatcher ResultOf( - Callable callable, const ResultOfMatcher& matcher) { - return internal::ResultOfMatcher( - callable, - MatcherCast::ResultType>( - matcher)); - // The call to MatcherCast() is required for supporting inner - // matchers of compatible types. For example, it allows - // ResultOf(Function, m) - // to compile where Function() returns an int32 and m is a matcher for int64. +// `callable` parameter can be a function, function pointer, or a functor. It is +// required to keep no state affecting the results of the calls on it and make +// no assumptions about how many calls will be made. Any state it keeps must be +// protected from the concurrent access. +template +internal::ResultOfMatcher ResultOf( + Callable callable, InnerMatcher matcher) { + return internal::ResultOfMatcher( + internal::move(callable), internal::move(matcher)); } // String matchers. // Matches a string equal to str. -inline PolymorphicMatcher > - StrEq(const internal::string& str) { - return MakePolymorphicMatcher(internal::StrEqualityMatcher( - str, true, true)); +inline PolymorphicMatcher > StrEq( + const std::string& str) { + return MakePolymorphicMatcher( + internal::StrEqualityMatcher(str, true, true)); } // Matches a string not equal to str. -inline PolymorphicMatcher > - StrNe(const internal::string& str) { - return MakePolymorphicMatcher(internal::StrEqualityMatcher( - str, false, true)); +inline PolymorphicMatcher > StrNe( + const std::string& str) { + return MakePolymorphicMatcher( + internal::StrEqualityMatcher(str, false, true)); } // Matches a string equal to str, ignoring case. -inline PolymorphicMatcher > - StrCaseEq(const internal::string& str) { - return MakePolymorphicMatcher(internal::StrEqualityMatcher( - str, true, false)); +inline PolymorphicMatcher > StrCaseEq( + const std::string& str) { + return MakePolymorphicMatcher( + internal::StrEqualityMatcher(str, true, false)); } // Matches a string not equal to str, ignoring case. -inline PolymorphicMatcher > - StrCaseNe(const internal::string& str) { - return MakePolymorphicMatcher(internal::StrEqualityMatcher( - str, false, false)); +inline PolymorphicMatcher > StrCaseNe( + const std::string& str) { + return MakePolymorphicMatcher( + internal::StrEqualityMatcher(str, false, false)); } // Creates a matcher that matches any string, std::string, or C string // that contains the given substring. -inline PolymorphicMatcher > - HasSubstr(const internal::string& substring) { - return MakePolymorphicMatcher(internal::HasSubstrMatcher( - substring)); +inline PolymorphicMatcher > HasSubstr( + const std::string& substring) { + return MakePolymorphicMatcher( + internal::HasSubstrMatcher(substring)); } // Matches a string that starts with 'prefix' (case-sensitive). -inline PolymorphicMatcher > - StartsWith(const internal::string& prefix) { - return MakePolymorphicMatcher(internal::StartsWithMatcher( - prefix)); +inline PolymorphicMatcher > StartsWith( + const std::string& prefix) { + return MakePolymorphicMatcher( + internal::StartsWithMatcher(prefix)); } // Matches a string that ends with 'suffix' (case-sensitive). -inline PolymorphicMatcher > - EndsWith(const internal::string& suffix) { - return MakePolymorphicMatcher(internal::EndsWithMatcher( - suffix)); +inline PolymorphicMatcher > EndsWith( + const std::string& suffix) { + return MakePolymorphicMatcher(internal::EndsWithMatcher(suffix)); } // Matches a string that fully matches regular expression 'regex'. @@ -4007,7 +4637,7 @@ return MakePolymorphicMatcher(internal::MatchesRegexMatcher(regex, true)); } inline PolymorphicMatcher MatchesRegex( - const internal::string& regex) { + const std::string& regex) { return MatchesRegex(new internal::RE(regex)); } @@ -4018,61 +4648,61 @@ return MakePolymorphicMatcher(internal::MatchesRegexMatcher(regex, false)); } inline PolymorphicMatcher ContainsRegex( - const internal::string& regex) { + const std::string& regex) { return ContainsRegex(new internal::RE(regex)); } #if GTEST_HAS_GLOBAL_WSTRING || GTEST_HAS_STD_WSTRING // Wide string matchers. // Matches a string equal to str. -inline PolymorphicMatcher > - StrEq(const internal::wstring& str) { - return MakePolymorphicMatcher(internal::StrEqualityMatcher( - str, true, true)); +inline PolymorphicMatcher > StrEq( + const std::wstring& str) { + return MakePolymorphicMatcher( + internal::StrEqualityMatcher(str, true, true)); } // Matches a string not equal to str. -inline PolymorphicMatcher > - StrNe(const internal::wstring& str) { - return MakePolymorphicMatcher(internal::StrEqualityMatcher( - str, false, true)); +inline PolymorphicMatcher > StrNe( + const std::wstring& str) { + return MakePolymorphicMatcher( + internal::StrEqualityMatcher(str, false, true)); } // Matches a string equal to str, ignoring case. -inline PolymorphicMatcher > - StrCaseEq(const internal::wstring& str) { - return MakePolymorphicMatcher(internal::StrEqualityMatcher( - str, true, false)); +inline PolymorphicMatcher > +StrCaseEq(const std::wstring& str) { + return MakePolymorphicMatcher( + internal::StrEqualityMatcher(str, true, false)); } // Matches a string not equal to str, ignoring case. -inline PolymorphicMatcher > - StrCaseNe(const internal::wstring& str) { - return MakePolymorphicMatcher(internal::StrEqualityMatcher( - str, false, false)); +inline PolymorphicMatcher > +StrCaseNe(const std::wstring& str) { + return MakePolymorphicMatcher( + internal::StrEqualityMatcher(str, false, false)); } -// Creates a matcher that matches any wstring, std::wstring, or C wide string +// Creates a matcher that matches any ::wstring, std::wstring, or C wide string // that contains the given substring. -inline PolymorphicMatcher > - HasSubstr(const internal::wstring& substring) { - return MakePolymorphicMatcher(internal::HasSubstrMatcher( - substring)); +inline PolymorphicMatcher > HasSubstr( + const std::wstring& substring) { + return MakePolymorphicMatcher( + internal::HasSubstrMatcher(substring)); } // Matches a string that starts with 'prefix' (case-sensitive). -inline PolymorphicMatcher > - StartsWith(const internal::wstring& prefix) { - return MakePolymorphicMatcher(internal::StartsWithMatcher( - prefix)); +inline PolymorphicMatcher > +StartsWith(const std::wstring& prefix) { + return MakePolymorphicMatcher( + internal::StartsWithMatcher(prefix)); } // Matches a string that ends with 'suffix' (case-sensitive). -inline PolymorphicMatcher > - EndsWith(const internal::wstring& suffix) { - return MakePolymorphicMatcher(internal::EndsWithMatcher( - suffix)); +inline PolymorphicMatcher > EndsWith( + const std::wstring& suffix) { + return MakePolymorphicMatcher( + internal::EndsWithMatcher(suffix)); } #endif // GTEST_HAS_GLOBAL_WSTRING || GTEST_HAS_STD_WSTRING @@ -4101,6 +4731,58 @@ // first field != the second field. inline internal::Ne2Matcher Ne() { return internal::Ne2Matcher(); } +// Creates a polymorphic matcher that matches a 2-tuple where +// FloatEq(first field) matches the second field. +inline internal::FloatingEq2Matcher FloatEq() { + return internal::FloatingEq2Matcher(); +} + +// Creates a polymorphic matcher that matches a 2-tuple where +// DoubleEq(first field) matches the second field. +inline internal::FloatingEq2Matcher DoubleEq() { + return internal::FloatingEq2Matcher(); +} + +// Creates a polymorphic matcher that matches a 2-tuple where +// FloatEq(first field) matches the second field with NaN equality. +inline internal::FloatingEq2Matcher NanSensitiveFloatEq() { + return internal::FloatingEq2Matcher(true); +} + +// Creates a polymorphic matcher that matches a 2-tuple where +// DoubleEq(first field) matches the second field with NaN equality. +inline internal::FloatingEq2Matcher NanSensitiveDoubleEq() { + return internal::FloatingEq2Matcher(true); +} + +// Creates a polymorphic matcher that matches a 2-tuple where +// FloatNear(first field, max_abs_error) matches the second field. +inline internal::FloatingEq2Matcher FloatNear(float max_abs_error) { + return internal::FloatingEq2Matcher(max_abs_error); +} + +// Creates a polymorphic matcher that matches a 2-tuple where +// DoubleNear(first field, max_abs_error) matches the second field. +inline internal::FloatingEq2Matcher DoubleNear(double max_abs_error) { + return internal::FloatingEq2Matcher(max_abs_error); +} + +// Creates a polymorphic matcher that matches a 2-tuple where +// FloatNear(first field, max_abs_error) matches the second field with NaN +// equality. +inline internal::FloatingEq2Matcher NanSensitiveFloatNear( + float max_abs_error) { + return internal::FloatingEq2Matcher(max_abs_error, true); +} + +// Creates a polymorphic matcher that matches a 2-tuple where +// DoubleNear(first field, max_abs_error) matches the second field with NaN +// equality. +inline internal::FloatingEq2Matcher NanSensitiveDoubleNear( + double max_abs_error) { + return internal::FloatingEq2Matcher(max_abs_error, true); +} + // Creates a matcher that matches any value of type T that m doesn't // match. template @@ -4283,6 +4965,128 @@ return internal::ContainsMatcher(matcher); } +// IsSupersetOf(iterator_first, iterator_last) +// IsSupersetOf(pointer, count) +// IsSupersetOf(array) +// IsSupersetOf(container) +// IsSupersetOf({e1, e2, ..., en}) +// +// IsSupersetOf() verifies that a surjective partial mapping onto a collection +// of matchers exists. In other words, a container matches +// IsSupersetOf({e1, ..., en}) if and only if there is a permutation +// {y1, ..., yn} of some of the container's elements where y1 matches e1, +// ..., and yn matches en. Obviously, the size of the container must be >= n +// in order to have a match. Examples: +// +// - {1, 2, 3} matches IsSupersetOf({Ge(3), Ne(0)}), as 3 matches Ge(3) and +// 1 matches Ne(0). +// - {1, 2} doesn't match IsSupersetOf({Eq(1), Lt(2)}), even though 1 matches +// both Eq(1) and Lt(2). The reason is that different matchers must be used +// for elements in different slots of the container. +// - {1, 1, 2} matches IsSupersetOf({Eq(1), Lt(2)}), as (the first) 1 matches +// Eq(1) and (the second) 1 matches Lt(2). +// - {1, 2, 3} matches IsSupersetOf(Gt(1), Gt(1)), as 2 matches (the first) +// Gt(1) and 3 matches (the second) Gt(1). +// +// The matchers can be specified as an array, a pointer and count, a container, +// an initializer list, or an STL iterator range. In each of these cases, the +// underlying matchers can be either values or matchers. + +template +inline internal::UnorderedElementsAreArrayMatcher< + typename ::std::iterator_traits::value_type> +IsSupersetOf(Iter first, Iter last) { + typedef typename ::std::iterator_traits::value_type T; + return internal::UnorderedElementsAreArrayMatcher( + internal::UnorderedMatcherRequire::Superset, first, last); +} + +template +inline internal::UnorderedElementsAreArrayMatcher IsSupersetOf( + const T* pointer, size_t count) { + return IsSupersetOf(pointer, pointer + count); +} + +template +inline internal::UnorderedElementsAreArrayMatcher IsSupersetOf( + const T (&array)[N]) { + return IsSupersetOf(array, N); +} + +template +inline internal::UnorderedElementsAreArrayMatcher< + typename Container::value_type> +IsSupersetOf(const Container& container) { + return IsSupersetOf(container.begin(), container.end()); +} + +#if GTEST_HAS_STD_INITIALIZER_LIST_ +template +inline internal::UnorderedElementsAreArrayMatcher IsSupersetOf( + ::std::initializer_list xs) { + return IsSupersetOf(xs.begin(), xs.end()); +} +#endif + +// IsSubsetOf(iterator_first, iterator_last) +// IsSubsetOf(pointer, count) +// IsSubsetOf(array) +// IsSubsetOf(container) +// IsSubsetOf({e1, e2, ..., en}) +// +// IsSubsetOf() verifies that an injective mapping onto a collection of matchers +// exists. In other words, a container matches IsSubsetOf({e1, ..., en}) if and +// only if there is a subset of matchers {m1, ..., mk} which would match the +// container using UnorderedElementsAre. Obviously, the size of the container +// must be <= n in order to have a match. Examples: +// +// - {1} matches IsSubsetOf({Gt(0), Lt(0)}), as 1 matches Gt(0). +// - {1, -1} matches IsSubsetOf({Lt(0), Gt(0)}), as 1 matches Gt(0) and -1 +// matches Lt(0). +// - {1, 2} doesn't matches IsSubsetOf({Gt(0), Lt(0)}), even though 1 and 2 both +// match Gt(0). The reason is that different matchers must be used for +// elements in different slots of the container. +// +// The matchers can be specified as an array, a pointer and count, a container, +// an initializer list, or an STL iterator range. In each of these cases, the +// underlying matchers can be either values or matchers. + +template +inline internal::UnorderedElementsAreArrayMatcher< + typename ::std::iterator_traits::value_type> +IsSubsetOf(Iter first, Iter last) { + typedef typename ::std::iterator_traits::value_type T; + return internal::UnorderedElementsAreArrayMatcher( + internal::UnorderedMatcherRequire::Subset, first, last); +} + +template +inline internal::UnorderedElementsAreArrayMatcher IsSubsetOf( + const T* pointer, size_t count) { + return IsSubsetOf(pointer, pointer + count); +} + +template +inline internal::UnorderedElementsAreArrayMatcher IsSubsetOf( + const T (&array)[N]) { + return IsSubsetOf(array, N); +} + +template +inline internal::UnorderedElementsAreArrayMatcher< + typename Container::value_type> +IsSubsetOf(const Container& container) { + return IsSubsetOf(container.begin(), container.end()); +} + +#if GTEST_HAS_STD_INITIALIZER_LIST_ +template +inline internal::UnorderedElementsAreArrayMatcher IsSubsetOf( + ::std::initializer_list xs) { + return IsSubsetOf(xs.begin(), xs.end()); +} +#endif + // Matches an STL-style container or a native array that contains only // elements matching the given value or matcher. // @@ -4356,19 +5160,62 @@ return SafeMatcherCast(matcher).MatchAndExplain(value, listener); } +// Returns a string representation of the given matcher. Useful for description +// strings of matchers defined using MATCHER_P* macros that accept matchers as +// their arguments. For example: +// +// MATCHER_P(XAndYThat, matcher, +// "X that " + DescribeMatcher(matcher, negation) + +// " and Y that " + DescribeMatcher(matcher, negation)) { +// return ExplainMatchResult(matcher, arg.x(), result_listener) && +// ExplainMatchResult(matcher, arg.y(), result_listener); +// } +template +std::string DescribeMatcher(const M& matcher, bool negation = false) { + ::std::stringstream ss; + Matcher monomorphic_matcher = SafeMatcherCast(matcher); + if (negation) { + monomorphic_matcher.DescribeNegationTo(&ss); + } else { + monomorphic_matcher.DescribeTo(&ss); + } + return ss.str(); +} + #if GTEST_LANG_CXX11 // Define variadic matcher versions. They are overloaded in // gmock-generated-matchers.h for the cases supported by pre C++11 compilers. template -inline internal::AllOfMatcher AllOf(const Args&... matchers) { - return internal::AllOfMatcher(matchers...); +internal::AllOfMatcher::type...> AllOf( + const Args&... matchers) { + return internal::AllOfMatcher::type...>( + matchers...); } template -inline internal::AnyOfMatcher AnyOf(const Args&... matchers) { - return internal::AnyOfMatcher(matchers...); +internal::AnyOfMatcher::type...> AnyOf( + const Args&... matchers) { + return internal::AnyOfMatcher::type...>( + matchers...); } +template +internal::ElementsAreMatcher::type...>> +ElementsAre(const Args&... matchers) { + return internal::ElementsAreMatcher< + tuple::type...>>( + make_tuple(matchers...)); +} + +template +internal::UnorderedElementsAreMatcher< + tuple::type...>> +UnorderedElementsAre(const Args&... matchers) { + return internal::UnorderedElementsAreMatcher< + tuple::type...>>( + make_tuple(matchers...)); +} + #endif // GTEST_LANG_CXX11 // AllArgs(m) is a synonym of m. This is useful in @@ -4381,6 +5228,39 @@ template inline InnerMatcher AllArgs(const InnerMatcher& matcher) { return matcher; } +// Returns a matcher that matches the value of an optional<> type variable. +// The matcher implementation only uses '!arg' and requires that the optional<> +// type has a 'value_type' member type and that '*arg' is of type 'value_type' +// and is printable using 'PrintToString'. It is compatible with +// std::optional/std::experimental::optional. +// Note that to compare an optional type variable against nullopt you should +// use Eq(nullopt) and not Optional(Eq(nullopt)). The latter implies that the +// optional value contains an optional itself. +template +inline internal::OptionalMatcher Optional( + const ValueMatcher& value_matcher) { + return internal::OptionalMatcher(value_matcher); +} + +// Returns a matcher that matches the value of a absl::any type variable. +template +PolymorphicMatcher > AnyWith( + const Matcher& matcher) { + return MakePolymorphicMatcher( + internal::any_cast_matcher::AnyCastMatcher(matcher)); +} + +// Returns a matcher that matches the value of a variant<> type variable. +// The matcher implementation uses ADL to find the holds_alternative and get +// functions. +// It is compatible with std::variant. +template +PolymorphicMatcher > VariantWith( + const Matcher& matcher) { + return MakePolymorphicMatcher( + internal::variant_matcher::VariantMatcher(matcher)); +} + // These macros allow using matchers to check values in Google Test // tests. ASSERT_THAT(value, matcher) and EXPECT_THAT(value, matcher) // succeed iff the value matches the matcher. If the assertion fails, @@ -4392,8 +5272,11 @@ } // namespace testing +GTEST_DISABLE_MSC_WARNINGS_POP_() // 4251 5046 + // Include any custom callback matchers added by the local installation. // We must include this header at the end to make sure it can use the // declarations from this file. #include "gmock/internal/custom/gmock-matchers.h" + #endif // GMOCK_INCLUDE_GMOCK_GMOCK_MATCHERS_H_