1 // Copyright 2007, Google Inc. 2 // All rights reserved. 3 // 4 // Redistribution and use in source and binary forms, with or without 5 // modification, are permitted provided that the following conditions are 6 // met: 7 // 8 // * Redistributions of source code must retain the above copyright 9 // notice, this list of conditions and the following disclaimer. 10 // * Redistributions in binary form must reproduce the above 11 // copyright notice, this list of conditions and the following disclaimer 12 // in the documentation and/or other materials provided with the 13 // distribution. 14 // * Neither the name of Google Inc. nor the names of its 15 // contributors may be used to endorse or promote products derived from 16 // this software without specific prior written permission. 17 // 18 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 19 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 20 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 21 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 22 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 23 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 24 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 25 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 26 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 27 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 28 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 29 30 31 // Google Mock - a framework for writing C++ mock classes. 32 // 33 // This file implements some commonly used argument matchers. More 34 // matchers can be defined by the user implementing the 35 // MatcherInterface<T> interface if necessary. 36 // 37 // See googletest/include/gtest/gtest-matchers.h for the definition of class 38 // Matcher, class MatcherInterface, and others. 39 40 // GOOGLETEST_CM0002 DO NOT DELETE 41 42 // IWYU pragma: private, include "gmock/gmock.h" 43 44 #ifndef GMOCK_INCLUDE_GMOCK_GMOCK_MATCHERS_H_ 45 #define GMOCK_INCLUDE_GMOCK_GMOCK_MATCHERS_H_ 46 47 #include <math.h> 48 #include <algorithm> 49 #include <initializer_list> 50 #include <iterator> 51 #include <limits> 52 #include <memory> 53 #include <ostream> // NOLINT 54 #include <sstream> 55 #include <string> 56 #include <type_traits> 57 #include <utility> 58 #include <vector> 59 #include "gmock/internal/gmock-internal-utils.h" 60 #include "gmock/internal/gmock-port.h" 61 #include "gtest/gtest.h" 62 63 // MSVC warning C5046 is new as of VS2017 version 15.8. 64 #if defined(_MSC_VER) && _MSC_VER >= 1915 65 #define GMOCK_MAYBE_5046_ 5046 66 #else 67 #define GMOCK_MAYBE_5046_ 68 #endif 69 70 GTEST_DISABLE_MSC_WARNINGS_PUSH_( 71 4251 GMOCK_MAYBE_5046_ /* class A needs to have dll-interface to be used by 72 clients of class B */ 73 /* Symbol involving type with internal linkage not defined */) 74 75 #ifdef __clang__ 76 #if __has_warning("-Wdeprecated-copy") 77 #pragma clang diagnostic push 78 #pragma clang diagnostic ignored "-Wdeprecated-copy" 79 #endif 80 #endif 81 82 namespace testing { 83 84 // To implement a matcher Foo for type T, define: 85 // 1. a class FooMatcherImpl that implements the 86 // MatcherInterface<T> interface, and 87 // 2. a factory function that creates a Matcher<T> object from a 88 // FooMatcherImpl*. 89 // 90 // The two-level delegation design makes it possible to allow a user 91 // to write "v" instead of "Eq(v)" where a Matcher is expected, which 92 // is impossible if we pass matchers by pointers. It also eases 93 // ownership management as Matcher objects can now be copied like 94 // plain values. 95 96 // A match result listener that stores the explanation in a string. 97 class StringMatchResultListener : public MatchResultListener { 98 public: 99 StringMatchResultListener() : MatchResultListener(&ss_) {} 100 101 // Returns the explanation accumulated so far. 102 std::string str() const { return ss_.str(); } 103 104 // Clears the explanation accumulated so far. 105 void Clear() { ss_.str(""); } 106 107 private: 108 ::std::stringstream ss_; 109 110 GTEST_DISALLOW_COPY_AND_ASSIGN_(StringMatchResultListener); 111 }; 112 113 // Anything inside the 'internal' namespace IS INTERNAL IMPLEMENTATION 114 // and MUST NOT BE USED IN USER CODE!!! 115 namespace internal { 116 117 // The MatcherCastImpl class template is a helper for implementing 118 // MatcherCast(). We need this helper in order to partially 119 // specialize the implementation of MatcherCast() (C++ allows 120 // class/struct templates to be partially specialized, but not 121 // function templates.). 122 123 // This general version is used when MatcherCast()'s argument is a 124 // polymorphic matcher (i.e. something that can be converted to a 125 // Matcher but is not one yet; for example, Eq(value)) or a value (for 126 // example, "hello"). 127 template <typename T, typename M> 128 class MatcherCastImpl { 129 public: 130 static Matcher<T> Cast(const M& polymorphic_matcher_or_value) { 131 // M can be a polymorphic matcher, in which case we want to use 132 // its conversion operator to create Matcher<T>. Or it can be a value 133 // that should be passed to the Matcher<T>'s constructor. 134 // 135 // We can't call Matcher<T>(polymorphic_matcher_or_value) when M is a 136 // polymorphic matcher because it'll be ambiguous if T has an implicit 137 // constructor from M (this usually happens when T has an implicit 138 // constructor from any type). 139 // 140 // It won't work to unconditionally implict_cast 141 // polymorphic_matcher_or_value to Matcher<T> because it won't trigger 142 // a user-defined conversion from M to T if one exists (assuming M is 143 // a value). 144 return CastImpl(polymorphic_matcher_or_value, 145 std::is_convertible<M, Matcher<T>>{}, 146 std::is_convertible<M, T>{}); 147 } 148 149 private: 150 template <bool Ignore> 151 static Matcher<T> CastImpl(const M& polymorphic_matcher_or_value, 152 std::true_type /* convertible_to_matcher */, 153 bool_constant<Ignore>) { 154 // M is implicitly convertible to Matcher<T>, which means that either 155 // M is a polymorphic matcher or Matcher<T> has an implicit constructor 156 // from M. In both cases using the implicit conversion will produce a 157 // matcher. 158 // 159 // Even if T has an implicit constructor from M, it won't be called because 160 // creating Matcher<T> would require a chain of two user-defined conversions 161 // (first to create T from M and then to create Matcher<T> from T). 162 return polymorphic_matcher_or_value; 163 } 164 165 // M can't be implicitly converted to Matcher<T>, so M isn't a polymorphic 166 // matcher. It's a value of a type implicitly convertible to T. Use direct 167 // initialization to create a matcher. 168 static Matcher<T> CastImpl(const M& value, 169 std::false_type /* convertible_to_matcher */, 170 std::true_type /* convertible_to_T */) { 171 return Matcher<T>(ImplicitCast_<T>(value)); 172 } 173 174 // M can't be implicitly converted to either Matcher<T> or T. Attempt to use 175 // polymorphic matcher Eq(value) in this case. 176 // 177 // Note that we first attempt to perform an implicit cast on the value and 178 // only fall back to the polymorphic Eq() matcher afterwards because the 179 // latter calls bool operator==(const Lhs& lhs, const Rhs& rhs) in the end 180 // which might be undefined even when Rhs is implicitly convertible to Lhs 181 // (e.g. std::pair<const int, int> vs. std::pair<int, int>). 182 // 183 // We don't define this method inline as we need the declaration of Eq(). 184 static Matcher<T> CastImpl(const M& value, 185 std::false_type /* convertible_to_matcher */, 186 std::false_type /* convertible_to_T */); 187 }; 188 189 // This more specialized version is used when MatcherCast()'s argument 190 // is already a Matcher. This only compiles when type T can be 191 // statically converted to type U. 192 template <typename T, typename U> 193 class MatcherCastImpl<T, Matcher<U> > { 194 public: 195 static Matcher<T> Cast(const Matcher<U>& source_matcher) { 196 return Matcher<T>(new Impl(source_matcher)); 197 } 198 199 private: 200 class Impl : public MatcherInterface<T> { 201 public: 202 explicit Impl(const Matcher<U>& source_matcher) 203 : source_matcher_(source_matcher) {} 204 205 // We delegate the matching logic to the source matcher. 206 bool MatchAndExplain(T x, MatchResultListener* listener) const override { 207 using FromType = typename std::remove_cv<typename std::remove_pointer< 208 typename std::remove_reference<T>::type>::type>::type; 209 using ToType = typename std::remove_cv<typename std::remove_pointer< 210 typename std::remove_reference<U>::type>::type>::type; 211 // Do not allow implicitly converting base*/& to derived*/&. 212 static_assert( 213 // Do not trigger if only one of them is a pointer. That implies a 214 // regular conversion and not a down_cast. 215 (std::is_pointer<typename std::remove_reference<T>::type>::value != 216 std::is_pointer<typename std::remove_reference<U>::type>::value) || 217 std::is_same<FromType, ToType>::value || 218 !std::is_base_of<FromType, ToType>::value, 219 "Can't implicitly convert from <base> to <derived>"); 220 221 return source_matcher_.MatchAndExplain(static_cast<U>(x), listener); 222 } 223 224 void DescribeTo(::std::ostream* os) const override { 225 source_matcher_.DescribeTo(os); 226 } 227 228 void DescribeNegationTo(::std::ostream* os) const override { 229 source_matcher_.DescribeNegationTo(os); 230 } 231 232 private: 233 const Matcher<U> source_matcher_; 234 235 GTEST_DISALLOW_ASSIGN_(Impl); 236 }; 237 }; 238 239 // This even more specialized version is used for efficiently casting 240 // a matcher to its own type. 241 template <typename T> 242 class MatcherCastImpl<T, Matcher<T> > { 243 public: 244 static Matcher<T> Cast(const Matcher<T>& matcher) { return matcher; } 245 }; 246 247 } // namespace internal 248 249 // In order to be safe and clear, casting between different matcher 250 // types is done explicitly via MatcherCast<T>(m), which takes a 251 // matcher m and returns a Matcher<T>. It compiles only when T can be 252 // statically converted to the argument type of m. 253 template <typename T, typename M> 254 inline Matcher<T> MatcherCast(const M& matcher) { 255 return internal::MatcherCastImpl<T, M>::Cast(matcher); 256 } 257 258 // Implements SafeMatcherCast(). 259 // 260 // FIXME: The intermediate SafeMatcherCastImpl class was introduced as a 261 // workaround for a compiler bug, and can now be removed. 262 template <typename T> 263 class SafeMatcherCastImpl { 264 public: 265 // This overload handles polymorphic matchers and values only since 266 // monomorphic matchers are handled by the next one. 267 template <typename M> 268 static inline Matcher<T> Cast(const M& polymorphic_matcher_or_value) { 269 return internal::MatcherCastImpl<T, M>::Cast(polymorphic_matcher_or_value); 270 } 271 272 // This overload handles monomorphic matchers. 273 // 274 // In general, if type T can be implicitly converted to type U, we can 275 // safely convert a Matcher<U> to a Matcher<T> (i.e. Matcher is 276 // contravariant): just keep a copy of the original Matcher<U>, convert the 277 // argument from type T to U, and then pass it to the underlying Matcher<U>. 278 // The only exception is when U is a reference and T is not, as the 279 // underlying Matcher<U> may be interested in the argument's address, which 280 // is not preserved in the conversion from T to U. 281 template <typename U> 282 static inline Matcher<T> Cast(const Matcher<U>& matcher) { 283 // Enforce that T can be implicitly converted to U. 284 GTEST_COMPILE_ASSERT_((std::is_convertible<T, U>::value), 285 "T must be implicitly convertible to U"); 286 // Enforce that we are not converting a non-reference type T to a reference 287 // type U. 288 GTEST_COMPILE_ASSERT_( 289 std::is_reference<T>::value || !std::is_reference<U>::value, 290 cannot_convert_non_reference_arg_to_reference); 291 // In case both T and U are arithmetic types, enforce that the 292 // conversion is not lossy. 293 typedef GTEST_REMOVE_REFERENCE_AND_CONST_(T) RawT; 294 typedef GTEST_REMOVE_REFERENCE_AND_CONST_(U) RawU; 295 const bool kTIsOther = GMOCK_KIND_OF_(RawT) == internal::kOther; 296 const bool kUIsOther = GMOCK_KIND_OF_(RawU) == internal::kOther; 297 GTEST_COMPILE_ASSERT_( 298 kTIsOther || kUIsOther || 299 (internal::LosslessArithmeticConvertible<RawT, RawU>::value), 300 conversion_of_arithmetic_types_must_be_lossless); 301 return MatcherCast<T>(matcher); 302 } 303 }; 304 305 template <typename T, typename M> 306 inline Matcher<T> SafeMatcherCast(const M& polymorphic_matcher) { 307 return SafeMatcherCastImpl<T>::Cast(polymorphic_matcher); 308 } 309 310 // A<T>() returns a matcher that matches any value of type T. 311 template <typename T> 312 Matcher<T> A(); 313 314 // Anything inside the 'internal' namespace IS INTERNAL IMPLEMENTATION 315 // and MUST NOT BE USED IN USER CODE!!! 316 namespace internal { 317 318 // If the explanation is not empty, prints it to the ostream. 319 inline void PrintIfNotEmpty(const std::string& explanation, 320 ::std::ostream* os) { 321 if (explanation != "" && os != nullptr) { 322 *os << ", " << explanation; 323 } 324 } 325 326 // Returns true if the given type name is easy to read by a human. 327 // This is used to decide whether printing the type of a value might 328 // be helpful. 329 inline bool IsReadableTypeName(const std::string& type_name) { 330 // We consider a type name readable if it's short or doesn't contain 331 // a template or function type. 332 return (type_name.length() <= 20 || 333 type_name.find_first_of("<(") == std::string::npos); 334 } 335 336 // Matches the value against the given matcher, prints the value and explains 337 // the match result to the listener. Returns the match result. 338 // 'listener' must not be NULL. 339 // Value cannot be passed by const reference, because some matchers take a 340 // non-const argument. 341 template <typename Value, typename T> 342 bool MatchPrintAndExplain(Value& value, const Matcher<T>& matcher, 343 MatchResultListener* listener) { 344 if (!listener->IsInterested()) { 345 // If the listener is not interested, we do not need to construct the 346 // inner explanation. 347 return matcher.Matches(value); 348 } 349 350 StringMatchResultListener inner_listener; 351 const bool match = matcher.MatchAndExplain(value, &inner_listener); 352 353 UniversalPrint(value, listener->stream()); 354 #if GTEST_HAS_RTTI 355 const std::string& type_name = GetTypeName<Value>(); 356 if (IsReadableTypeName(type_name)) 357 *listener->stream() << " (of type " << type_name << ")"; 358 #endif 359 PrintIfNotEmpty(inner_listener.str(), listener->stream()); 360 361 return match; 362 } 363 364 // An internal helper class for doing compile-time loop on a tuple's 365 // fields. 366 template <size_t N> 367 class TuplePrefix { 368 public: 369 // TuplePrefix<N>::Matches(matcher_tuple, value_tuple) returns true 370 // if and only if the first N fields of matcher_tuple matches 371 // the first N fields of value_tuple, respectively. 372 template <typename MatcherTuple, typename ValueTuple> 373 static bool Matches(const MatcherTuple& matcher_tuple, 374 const ValueTuple& value_tuple) { 375 return TuplePrefix<N - 1>::Matches(matcher_tuple, value_tuple) && 376 std::get<N - 1>(matcher_tuple).Matches(std::get<N - 1>(value_tuple)); 377 } 378 379 // TuplePrefix<N>::ExplainMatchFailuresTo(matchers, values, os) 380 // describes failures in matching the first N fields of matchers 381 // against the first N fields of values. If there is no failure, 382 // nothing will be streamed to os. 383 template <typename MatcherTuple, typename ValueTuple> 384 static void ExplainMatchFailuresTo(const MatcherTuple& matchers, 385 const ValueTuple& values, 386 ::std::ostream* os) { 387 // First, describes failures in the first N - 1 fields. 388 TuplePrefix<N - 1>::ExplainMatchFailuresTo(matchers, values, os); 389 390 // Then describes the failure (if any) in the (N - 1)-th (0-based) 391 // field. 392 typename std::tuple_element<N - 1, MatcherTuple>::type matcher = 393 std::get<N - 1>(matchers); 394 typedef typename std::tuple_element<N - 1, ValueTuple>::type Value; 395 const Value& value = std::get<N - 1>(values); 396 StringMatchResultListener listener; 397 if (!matcher.MatchAndExplain(value, &listener)) { 398 *os << " Expected arg #" << N - 1 << ": "; 399 std::get<N - 1>(matchers).DescribeTo(os); 400 *os << "\n Actual: "; 401 // We remove the reference in type Value to prevent the 402 // universal printer from printing the address of value, which 403 // isn't interesting to the user most of the time. The 404 // matcher's MatchAndExplain() method handles the case when 405 // the address is interesting. 406 internal::UniversalPrint(value, os); 407 PrintIfNotEmpty(listener.str(), os); 408 *os << "\n"; 409 } 410 } 411 }; 412 413 // The base case. 414 template <> 415 class TuplePrefix<0> { 416 public: 417 template <typename MatcherTuple, typename ValueTuple> 418 static bool Matches(const MatcherTuple& /* matcher_tuple */, 419 const ValueTuple& /* value_tuple */) { 420 return true; 421 } 422 423 template <typename MatcherTuple, typename ValueTuple> 424 static void ExplainMatchFailuresTo(const MatcherTuple& /* matchers */, 425 const ValueTuple& /* values */, 426 ::std::ostream* /* os */) {} 427 }; 428 429 // TupleMatches(matcher_tuple, value_tuple) returns true if and only if 430 // all matchers in matcher_tuple match the corresponding fields in 431 // value_tuple. It is a compiler error if matcher_tuple and 432 // value_tuple have different number of fields or incompatible field 433 // types. 434 template <typename MatcherTuple, typename ValueTuple> 435 bool TupleMatches(const MatcherTuple& matcher_tuple, 436 const ValueTuple& value_tuple) { 437 // Makes sure that matcher_tuple and value_tuple have the same 438 // number of fields. 439 GTEST_COMPILE_ASSERT_(std::tuple_size<MatcherTuple>::value == 440 std::tuple_size<ValueTuple>::value, 441 matcher_and_value_have_different_numbers_of_fields); 442 return TuplePrefix<std::tuple_size<ValueTuple>::value>::Matches(matcher_tuple, 443 value_tuple); 444 } 445 446 // Describes failures in matching matchers against values. If there 447 // is no failure, nothing will be streamed to os. 448 template <typename MatcherTuple, typename ValueTuple> 449 void ExplainMatchFailureTupleTo(const MatcherTuple& matchers, 450 const ValueTuple& values, 451 ::std::ostream* os) { 452 TuplePrefix<std::tuple_size<MatcherTuple>::value>::ExplainMatchFailuresTo( 453 matchers, values, os); 454 } 455 456 // TransformTupleValues and its helper. 457 // 458 // TransformTupleValuesHelper hides the internal machinery that 459 // TransformTupleValues uses to implement a tuple traversal. 460 template <typename Tuple, typename Func, typename OutIter> 461 class TransformTupleValuesHelper { 462 private: 463 typedef ::std::tuple_size<Tuple> TupleSize; 464 465 public: 466 // For each member of tuple 't', taken in order, evaluates '*out++ = f(t)'. 467 // Returns the final value of 'out' in case the caller needs it. 468 static OutIter Run(Func f, const Tuple& t, OutIter out) { 469 return IterateOverTuple<Tuple, TupleSize::value>()(f, t, out); 470 } 471 472 private: 473 template <typename Tup, size_t kRemainingSize> 474 struct IterateOverTuple { 475 OutIter operator() (Func f, const Tup& t, OutIter out) const { 476 *out++ = f(::std::get<TupleSize::value - kRemainingSize>(t)); 477 return IterateOverTuple<Tup, kRemainingSize - 1>()(f, t, out); 478 } 479 }; 480 template <typename Tup> 481 struct IterateOverTuple<Tup, 0> { 482 OutIter operator() (Func /* f */, const Tup& /* t */, OutIter out) const { 483 return out; 484 } 485 }; 486 }; 487 488 // Successively invokes 'f(element)' on each element of the tuple 't', 489 // appending each result to the 'out' iterator. Returns the final value 490 // of 'out'. 491 template <typename Tuple, typename Func, typename OutIter> 492 OutIter TransformTupleValues(Func f, const Tuple& t, OutIter out) { 493 return TransformTupleValuesHelper<Tuple, Func, OutIter>::Run(f, t, out); 494 } 495 496 // Implements A<T>(). 497 template <typename T> 498 class AnyMatcherImpl : public MatcherInterface<const T&> { 499 public: 500 bool MatchAndExplain(const T& /* x */, 501 MatchResultListener* /* listener */) const override { 502 return true; 503 } 504 void DescribeTo(::std::ostream* os) const override { *os << "is anything"; } 505 void DescribeNegationTo(::std::ostream* os) const override { 506 // This is mostly for completeness' safe, as it's not very useful 507 // to write Not(A<bool>()). However we cannot completely rule out 508 // such a possibility, and it doesn't hurt to be prepared. 509 *os << "never matches"; 510 } 511 }; 512 513 // Implements _, a matcher that matches any value of any 514 // type. This is a polymorphic matcher, so we need a template type 515 // conversion operator to make it appearing as a Matcher<T> for any 516 // type T. 517 class AnythingMatcher { 518 public: 519 template <typename T> 520 operator Matcher<T>() const { return A<T>(); } 521 }; 522 523 // Implements the polymorphic IsNull() matcher, which matches any raw or smart 524 // pointer that is NULL. 525 class IsNullMatcher { 526 public: 527 template <typename Pointer> 528 bool MatchAndExplain(const Pointer& p, 529 MatchResultListener* /* listener */) const { 530 return p == nullptr; 531 } 532 533 void DescribeTo(::std::ostream* os) const { *os << "is NULL"; } 534 void DescribeNegationTo(::std::ostream* os) const { 535 *os << "isn't NULL"; 536 } 537 }; 538 539 // Implements the polymorphic NotNull() matcher, which matches any raw or smart 540 // pointer that is not NULL. 541 class NotNullMatcher { 542 public: 543 template <typename Pointer> 544 bool MatchAndExplain(const Pointer& p, 545 MatchResultListener* /* listener */) const { 546 return p != nullptr; 547 } 548 549 void DescribeTo(::std::ostream* os) const { *os << "isn't NULL"; } 550 void DescribeNegationTo(::std::ostream* os) const { 551 *os << "is NULL"; 552 } 553 }; 554 555 // Ref(variable) matches any argument that is a reference to 556 // 'variable'. This matcher is polymorphic as it can match any 557 // super type of the type of 'variable'. 558 // 559 // The RefMatcher template class implements Ref(variable). It can 560 // only be instantiated with a reference type. This prevents a user 561 // from mistakenly using Ref(x) to match a non-reference function 562 // argument. For example, the following will righteously cause a 563 // compiler error: 564 // 565 // int n; 566 // Matcher<int> m1 = Ref(n); // This won't compile. 567 // Matcher<int&> m2 = Ref(n); // This will compile. 568 template <typename T> 569 class RefMatcher; 570 571 template <typename T> 572 class RefMatcher<T&> { 573 // Google Mock is a generic framework and thus needs to support 574 // mocking any function types, including those that take non-const 575 // reference arguments. Therefore the template parameter T (and 576 // Super below) can be instantiated to either a const type or a 577 // non-const type. 578 public: 579 // RefMatcher() takes a T& instead of const T&, as we want the 580 // compiler to catch using Ref(const_value) as a matcher for a 581 // non-const reference. 582 explicit RefMatcher(T& x) : object_(x) {} // NOLINT 583 584 template <typename Super> 585 operator Matcher<Super&>() const { 586 // By passing object_ (type T&) to Impl(), which expects a Super&, 587 // we make sure that Super is a super type of T. In particular, 588 // this catches using Ref(const_value) as a matcher for a 589 // non-const reference, as you cannot implicitly convert a const 590 // reference to a non-const reference. 591 return MakeMatcher(new Impl<Super>(object_)); 592 } 593 594 private: 595 template <typename Super> 596 class Impl : public MatcherInterface<Super&> { 597 public: 598 explicit Impl(Super& x) : object_(x) {} // NOLINT 599 600 // MatchAndExplain() takes a Super& (as opposed to const Super&) 601 // in order to match the interface MatcherInterface<Super&>. 602 bool MatchAndExplain(Super& x, 603 MatchResultListener* listener) const override { 604 *listener << "which is located @" << static_cast<const void*>(&x); 605 return &x == &object_; 606 } 607 608 void DescribeTo(::std::ostream* os) const override { 609 *os << "references the variable "; 610 UniversalPrinter<Super&>::Print(object_, os); 611 } 612 613 void DescribeNegationTo(::std::ostream* os) const override { 614 *os << "does not reference the variable "; 615 UniversalPrinter<Super&>::Print(object_, os); 616 } 617 618 private: 619 const Super& object_; 620 621 GTEST_DISALLOW_ASSIGN_(Impl); 622 }; 623 624 T& object_; 625 626 GTEST_DISALLOW_ASSIGN_(RefMatcher); 627 }; 628 629 // Polymorphic helper functions for narrow and wide string matchers. 630 inline bool CaseInsensitiveCStringEquals(const char* lhs, const char* rhs) { 631 return String::CaseInsensitiveCStringEquals(lhs, rhs); 632 } 633 634 inline bool CaseInsensitiveCStringEquals(const wchar_t* lhs, 635 const wchar_t* rhs) { 636 return String::CaseInsensitiveWideCStringEquals(lhs, rhs); 637 } 638 639 // String comparison for narrow or wide strings that can have embedded NUL 640 // characters. 641 template <typename StringType> 642 bool CaseInsensitiveStringEquals(const StringType& s1, 643 const StringType& s2) { 644 // Are the heads equal? 645 if (!CaseInsensitiveCStringEquals(s1.c_str(), s2.c_str())) { 646 return false; 647 } 648 649 // Skip the equal heads. 650 const typename StringType::value_type nul = 0; 651 const size_t i1 = s1.find(nul), i2 = s2.find(nul); 652 653 // Are we at the end of either s1 or s2? 654 if (i1 == StringType::npos || i2 == StringType::npos) { 655 return i1 == i2; 656 } 657 658 // Are the tails equal? 659 return CaseInsensitiveStringEquals(s1.substr(i1 + 1), s2.substr(i2 + 1)); 660 } 661 662 // String matchers. 663 664 // Implements equality-based string matchers like StrEq, StrCaseNe, and etc. 665 template <typename StringType> 666 class StrEqualityMatcher { 667 public: 668 StrEqualityMatcher(const StringType& str, bool expect_eq, 669 bool case_sensitive) 670 : string_(str), expect_eq_(expect_eq), case_sensitive_(case_sensitive) {} 671 672 #if GTEST_HAS_ABSL 673 bool MatchAndExplain(const absl::string_view& s, 674 MatchResultListener* listener) const { 675 // This should fail to compile if absl::string_view is used with wide 676 // strings. 677 const StringType& str = std::string(s); 678 return MatchAndExplain(str, listener); 679 } 680 #endif // GTEST_HAS_ABSL 681 682 // Accepts pointer types, particularly: 683 // const char* 684 // char* 685 // const wchar_t* 686 // wchar_t* 687 template <typename CharType> 688 bool MatchAndExplain(CharType* s, MatchResultListener* listener) const { 689 if (s == nullptr) { 690 return !expect_eq_; 691 } 692 return MatchAndExplain(StringType(s), listener); 693 } 694 695 // Matches anything that can convert to StringType. 696 // 697 // This is a template, not just a plain function with const StringType&, 698 // because absl::string_view has some interfering non-explicit constructors. 699 template <typename MatcheeStringType> 700 bool MatchAndExplain(const MatcheeStringType& s, 701 MatchResultListener* /* listener */) const { 702 const StringType& s2(s); 703 const bool eq = case_sensitive_ ? s2 == string_ : 704 CaseInsensitiveStringEquals(s2, string_); 705 return expect_eq_ == eq; 706 } 707 708 void DescribeTo(::std::ostream* os) const { 709 DescribeToHelper(expect_eq_, os); 710 } 711 712 void DescribeNegationTo(::std::ostream* os) const { 713 DescribeToHelper(!expect_eq_, os); 714 } 715 716 private: 717 void DescribeToHelper(bool expect_eq, ::std::ostream* os) const { 718 *os << (expect_eq ? "is " : "isn't "); 719 *os << "equal to "; 720 if (!case_sensitive_) { 721 *os << "(ignoring case) "; 722 } 723 UniversalPrint(string_, os); 724 } 725 726 const StringType string_; 727 const bool expect_eq_; 728 const bool case_sensitive_; 729 730 GTEST_DISALLOW_ASSIGN_(StrEqualityMatcher); 731 }; 732 733 // Implements the polymorphic HasSubstr(substring) matcher, which 734 // can be used as a Matcher<T> as long as T can be converted to a 735 // string. 736 template <typename StringType> 737 class HasSubstrMatcher { 738 public: 739 explicit HasSubstrMatcher(const StringType& substring) 740 : substring_(substring) {} 741 742 #if GTEST_HAS_ABSL 743 bool MatchAndExplain(const absl::string_view& s, 744 MatchResultListener* listener) const { 745 // This should fail to compile if absl::string_view is used with wide 746 // strings. 747 const StringType& str = std::string(s); 748 return MatchAndExplain(str, listener); 749 } 750 #endif // GTEST_HAS_ABSL 751 752 // Accepts pointer types, particularly: 753 // const char* 754 // char* 755 // const wchar_t* 756 // wchar_t* 757 template <typename CharType> 758 bool MatchAndExplain(CharType* s, MatchResultListener* listener) const { 759 return s != nullptr && MatchAndExplain(StringType(s), listener); 760 } 761 762 // Matches anything that can convert to StringType. 763 // 764 // This is a template, not just a plain function with const StringType&, 765 // because absl::string_view has some interfering non-explicit constructors. 766 template <typename MatcheeStringType> 767 bool MatchAndExplain(const MatcheeStringType& s, 768 MatchResultListener* /* listener */) const { 769 const StringType& s2(s); 770 return s2.find(substring_) != StringType::npos; 771 } 772 773 // Describes what this matcher matches. 774 void DescribeTo(::std::ostream* os) const { 775 *os << "has substring "; 776 UniversalPrint(substring_, os); 777 } 778 779 void DescribeNegationTo(::std::ostream* os) const { 780 *os << "has no substring "; 781 UniversalPrint(substring_, os); 782 } 783 784 private: 785 const StringType substring_; 786 787 GTEST_DISALLOW_ASSIGN_(HasSubstrMatcher); 788 }; 789 790 // Implements the polymorphic StartsWith(substring) matcher, which 791 // can be used as a Matcher<T> as long as T can be converted to a 792 // string. 793 template <typename StringType> 794 class StartsWithMatcher { 795 public: 796 explicit StartsWithMatcher(const StringType& prefix) : prefix_(prefix) { 797 } 798 799 #if GTEST_HAS_ABSL 800 bool MatchAndExplain(const absl::string_view& s, 801 MatchResultListener* listener) const { 802 // This should fail to compile if absl::string_view is used with wide 803 // strings. 804 const StringType& str = std::string(s); 805 return MatchAndExplain(str, listener); 806 } 807 #endif // GTEST_HAS_ABSL 808 809 // Accepts pointer types, particularly: 810 // const char* 811 // char* 812 // const wchar_t* 813 // wchar_t* 814 template <typename CharType> 815 bool MatchAndExplain(CharType* s, MatchResultListener* listener) const { 816 return s != nullptr && MatchAndExplain(StringType(s), listener); 817 } 818 819 // Matches anything that can convert to StringType. 820 // 821 // This is a template, not just a plain function with const StringType&, 822 // because absl::string_view has some interfering non-explicit constructors. 823 template <typename MatcheeStringType> 824 bool MatchAndExplain(const MatcheeStringType& s, 825 MatchResultListener* /* listener */) const { 826 const StringType& s2(s); 827 return s2.length() >= prefix_.length() && 828 s2.substr(0, prefix_.length()) == prefix_; 829 } 830 831 void DescribeTo(::std::ostream* os) const { 832 *os << "starts with "; 833 UniversalPrint(prefix_, os); 834 } 835 836 void DescribeNegationTo(::std::ostream* os) const { 837 *os << "doesn't start with "; 838 UniversalPrint(prefix_, os); 839 } 840 841 private: 842 const StringType prefix_; 843 844 GTEST_DISALLOW_ASSIGN_(StartsWithMatcher); 845 }; 846 847 // Implements the polymorphic EndsWith(substring) matcher, which 848 // can be used as a Matcher<T> as long as T can be converted to a 849 // string. 850 template <typename StringType> 851 class EndsWithMatcher { 852 public: 853 explicit EndsWithMatcher(const StringType& suffix) : suffix_(suffix) {} 854 855 #if GTEST_HAS_ABSL 856 bool MatchAndExplain(const absl::string_view& s, 857 MatchResultListener* listener) const { 858 // This should fail to compile if absl::string_view is used with wide 859 // strings. 860 const StringType& str = std::string(s); 861 return MatchAndExplain(str, listener); 862 } 863 #endif // GTEST_HAS_ABSL 864 865 // Accepts pointer types, particularly: 866 // const char* 867 // char* 868 // const wchar_t* 869 // wchar_t* 870 template <typename CharType> 871 bool MatchAndExplain(CharType* s, MatchResultListener* listener) const { 872 return s != nullptr && MatchAndExplain(StringType(s), listener); 873 } 874 875 // Matches anything that can convert to StringType. 876 // 877 // This is a template, not just a plain function with const StringType&, 878 // because absl::string_view has some interfering non-explicit constructors. 879 template <typename MatcheeStringType> 880 bool MatchAndExplain(const MatcheeStringType& s, 881 MatchResultListener* /* listener */) const { 882 const StringType& s2(s); 883 return s2.length() >= suffix_.length() && 884 s2.substr(s2.length() - suffix_.length()) == suffix_; 885 } 886 887 void DescribeTo(::std::ostream* os) const { 888 *os << "ends with "; 889 UniversalPrint(suffix_, os); 890 } 891 892 void DescribeNegationTo(::std::ostream* os) const { 893 *os << "doesn't end with "; 894 UniversalPrint(suffix_, os); 895 } 896 897 private: 898 const StringType suffix_; 899 900 GTEST_DISALLOW_ASSIGN_(EndsWithMatcher); 901 }; 902 903 // Implements a matcher that compares the two fields of a 2-tuple 904 // using one of the ==, <=, <, etc, operators. The two fields being 905 // compared don't have to have the same type. 906 // 907 // The matcher defined here is polymorphic (for example, Eq() can be 908 // used to match a std::tuple<int, short>, a std::tuple<const long&, double>, 909 // etc). Therefore we use a template type conversion operator in the 910 // implementation. 911 template <typename D, typename Op> 912 class PairMatchBase { 913 public: 914 template <typename T1, typename T2> 915 operator Matcher<::std::tuple<T1, T2>>() const { 916 return Matcher<::std::tuple<T1, T2>>(new Impl<const ::std::tuple<T1, T2>&>); 917 } 918 template <typename T1, typename T2> 919 operator Matcher<const ::std::tuple<T1, T2>&>() const { 920 return MakeMatcher(new Impl<const ::std::tuple<T1, T2>&>); 921 } 922 923 private: 924 static ::std::ostream& GetDesc(::std::ostream& os) { // NOLINT 925 return os << D::Desc(); 926 } 927 928 template <typename Tuple> 929 class Impl : public MatcherInterface<Tuple> { 930 public: 931 bool MatchAndExplain(Tuple args, 932 MatchResultListener* /* listener */) const override { 933 return Op()(::std::get<0>(args), ::std::get<1>(args)); 934 } 935 void DescribeTo(::std::ostream* os) const override { 936 *os << "are " << GetDesc; 937 } 938 void DescribeNegationTo(::std::ostream* os) const override { 939 *os << "aren't " << GetDesc; 940 } 941 }; 942 }; 943 944 class Eq2Matcher : public PairMatchBase<Eq2Matcher, AnyEq> { 945 public: 946 static const char* Desc() { return "an equal pair"; } 947 }; 948 class Ne2Matcher : public PairMatchBase<Ne2Matcher, AnyNe> { 949 public: 950 static const char* Desc() { return "an unequal pair"; } 951 }; 952 class Lt2Matcher : public PairMatchBase<Lt2Matcher, AnyLt> { 953 public: 954 static const char* Desc() { return "a pair where the first < the second"; } 955 }; 956 class Gt2Matcher : public PairMatchBase<Gt2Matcher, AnyGt> { 957 public: 958 static const char* Desc() { return "a pair where the first > the second"; } 959 }; 960 class Le2Matcher : public PairMatchBase<Le2Matcher, AnyLe> { 961 public: 962 static const char* Desc() { return "a pair where the first <= the second"; } 963 }; 964 class Ge2Matcher : public PairMatchBase<Ge2Matcher, AnyGe> { 965 public: 966 static const char* Desc() { return "a pair where the first >= the second"; } 967 }; 968 969 // Implements the Not(...) matcher for a particular argument type T. 970 // We do not nest it inside the NotMatcher class template, as that 971 // will prevent different instantiations of NotMatcher from sharing 972 // the same NotMatcherImpl<T> class. 973 template <typename T> 974 class NotMatcherImpl : public MatcherInterface<const T&> { 975 public: 976 explicit NotMatcherImpl(const Matcher<T>& matcher) 977 : matcher_(matcher) {} 978 979 bool MatchAndExplain(const T& x, 980 MatchResultListener* listener) const override { 981 return !matcher_.MatchAndExplain(x, listener); 982 } 983 984 void DescribeTo(::std::ostream* os) const override { 985 matcher_.DescribeNegationTo(os); 986 } 987 988 void DescribeNegationTo(::std::ostream* os) const override { 989 matcher_.DescribeTo(os); 990 } 991 992 private: 993 const Matcher<T> matcher_; 994 995 GTEST_DISALLOW_ASSIGN_(NotMatcherImpl); 996 }; 997 998 // Implements the Not(m) matcher, which matches a value that doesn't 999 // match matcher m. 1000 template <typename InnerMatcher> 1001 class NotMatcher { 1002 public: 1003 explicit NotMatcher(InnerMatcher matcher) : matcher_(matcher) {} 1004 1005 // This template type conversion operator allows Not(m) to be used 1006 // to match any type m can match. 1007 template <typename T> 1008 operator Matcher<T>() const { 1009 return Matcher<T>(new NotMatcherImpl<T>(SafeMatcherCast<T>(matcher_))); 1010 } 1011 1012 private: 1013 InnerMatcher matcher_; 1014 1015 GTEST_DISALLOW_ASSIGN_(NotMatcher); 1016 }; 1017 1018 // Implements the AllOf(m1, m2) matcher for a particular argument type 1019 // T. We do not nest it inside the BothOfMatcher class template, as 1020 // that will prevent different instantiations of BothOfMatcher from 1021 // sharing the same BothOfMatcherImpl<T> class. 1022 template <typename T> 1023 class AllOfMatcherImpl : public MatcherInterface<const T&> { 1024 public: 1025 explicit AllOfMatcherImpl(std::vector<Matcher<T> > matchers) 1026 : matchers_(std::move(matchers)) {} 1027 1028 void DescribeTo(::std::ostream* os) const override { 1029 *os << "("; 1030 for (size_t i = 0; i < matchers_.size(); ++i) { 1031 if (i != 0) *os << ") and ("; 1032 matchers_[i].DescribeTo(os); 1033 } 1034 *os << ")"; 1035 } 1036 1037 void DescribeNegationTo(::std::ostream* os) const override { 1038 *os << "("; 1039 for (size_t i = 0; i < matchers_.size(); ++i) { 1040 if (i != 0) *os << ") or ("; 1041 matchers_[i].DescribeNegationTo(os); 1042 } 1043 *os << ")"; 1044 } 1045 1046 bool MatchAndExplain(const T& x, 1047 MatchResultListener* listener) const override { 1048 // If either matcher1_ or matcher2_ doesn't match x, we only need 1049 // to explain why one of them fails. 1050 std::string all_match_result; 1051 1052 for (size_t i = 0; i < matchers_.size(); ++i) { 1053 StringMatchResultListener slistener; 1054 if (matchers_[i].MatchAndExplain(x, &slistener)) { 1055 if (all_match_result.empty()) { 1056 all_match_result = slistener.str(); 1057 } else { 1058 std::string result = slistener.str(); 1059 if (!result.empty()) { 1060 all_match_result += ", and "; 1061 all_match_result += result; 1062 } 1063 } 1064 } else { 1065 *listener << slistener.str(); 1066 return false; 1067 } 1068 } 1069 1070 // Otherwise we need to explain why *both* of them match. 1071 *listener << all_match_result; 1072 return true; 1073 } 1074 1075 private: 1076 const std::vector<Matcher<T> > matchers_; 1077 1078 GTEST_DISALLOW_ASSIGN_(AllOfMatcherImpl); 1079 }; 1080 1081 // VariadicMatcher is used for the variadic implementation of 1082 // AllOf(m_1, m_2, ...) and AnyOf(m_1, m_2, ...). 1083 // CombiningMatcher<T> is used to recursively combine the provided matchers 1084 // (of type Args...). 1085 template <template <typename T> class CombiningMatcher, typename... Args> 1086 class VariadicMatcher { 1087 public: 1088 VariadicMatcher(const Args&... matchers) // NOLINT 1089 : matchers_(matchers...) { 1090 static_assert(sizeof...(Args) > 0, "Must have at least one matcher."); 1091 } 1092 1093 // This template type conversion operator allows an 1094 // VariadicMatcher<Matcher1, Matcher2...> object to match any type that 1095 // all of the provided matchers (Matcher1, Matcher2, ...) can match. 1096 template <typename T> 1097 operator Matcher<T>() const { 1098 std::vector<Matcher<T> > values; 1099 CreateVariadicMatcher<T>(&values, std::integral_constant<size_t, 0>()); 1100 return Matcher<T>(new CombiningMatcher<T>(std::move(values))); 1101 } 1102 1103 private: 1104 template <typename T, size_t I> 1105 void CreateVariadicMatcher(std::vector<Matcher<T> >* values, 1106 std::integral_constant<size_t, I>) const { 1107 values->push_back(SafeMatcherCast<T>(std::get<I>(matchers_))); 1108 CreateVariadicMatcher<T>(values, std::integral_constant<size_t, I + 1>()); 1109 } 1110 1111 template <typename T> 1112 void CreateVariadicMatcher( 1113 std::vector<Matcher<T> >*, 1114 std::integral_constant<size_t, sizeof...(Args)>) const {} 1115 1116 std::tuple<Args...> matchers_; 1117 1118 GTEST_DISALLOW_ASSIGN_(VariadicMatcher); 1119 }; 1120 1121 template <typename... Args> 1122 using AllOfMatcher = VariadicMatcher<AllOfMatcherImpl, Args...>; 1123 1124 // Implements the AnyOf(m1, m2) matcher for a particular argument type 1125 // T. We do not nest it inside the AnyOfMatcher class template, as 1126 // that will prevent different instantiations of AnyOfMatcher from 1127 // sharing the same EitherOfMatcherImpl<T> class. 1128 template <typename T> 1129 class AnyOfMatcherImpl : public MatcherInterface<const T&> { 1130 public: 1131 explicit AnyOfMatcherImpl(std::vector<Matcher<T> > matchers) 1132 : matchers_(std::move(matchers)) {} 1133 1134 void DescribeTo(::std::ostream* os) const override { 1135 *os << "("; 1136 for (size_t i = 0; i < matchers_.size(); ++i) { 1137 if (i != 0) *os << ") or ("; 1138 matchers_[i].DescribeTo(os); 1139 } 1140 *os << ")"; 1141 } 1142 1143 void DescribeNegationTo(::std::ostream* os) const override { 1144 *os << "("; 1145 for (size_t i = 0; i < matchers_.size(); ++i) { 1146 if (i != 0) *os << ") and ("; 1147 matchers_[i].DescribeNegationTo(os); 1148 } 1149 *os << ")"; 1150 } 1151 1152 bool MatchAndExplain(const T& x, 1153 MatchResultListener* listener) const override { 1154 std::string no_match_result; 1155 1156 // If either matcher1_ or matcher2_ matches x, we just need to 1157 // explain why *one* of them matches. 1158 for (size_t i = 0; i < matchers_.size(); ++i) { 1159 StringMatchResultListener slistener; 1160 if (matchers_[i].MatchAndExplain(x, &slistener)) { 1161 *listener << slistener.str(); 1162 return true; 1163 } else { 1164 if (no_match_result.empty()) { 1165 no_match_result = slistener.str(); 1166 } else { 1167 std::string result = slistener.str(); 1168 if (!result.empty()) { 1169 no_match_result += ", and "; 1170 no_match_result += result; 1171 } 1172 } 1173 } 1174 } 1175 1176 // Otherwise we need to explain why *both* of them fail. 1177 *listener << no_match_result; 1178 return false; 1179 } 1180 1181 private: 1182 const std::vector<Matcher<T> > matchers_; 1183 1184 GTEST_DISALLOW_ASSIGN_(AnyOfMatcherImpl); 1185 }; 1186 1187 // AnyOfMatcher is used for the variadic implementation of AnyOf(m_1, m_2, ...). 1188 template <typename... Args> 1189 using AnyOfMatcher = VariadicMatcher<AnyOfMatcherImpl, Args...>; 1190 1191 // Wrapper for implementation of Any/AllOfArray(). 1192 template <template <class> class MatcherImpl, typename T> 1193 class SomeOfArrayMatcher { 1194 public: 1195 // Constructs the matcher from a sequence of element values or 1196 // element matchers. 1197 template <typename Iter> 1198 SomeOfArrayMatcher(Iter first, Iter last) : matchers_(first, last) {} 1199 1200 template <typename U> 1201 operator Matcher<U>() const { // NOLINT 1202 using RawU = typename std::decay<U>::type; 1203 std::vector<Matcher<RawU>> matchers; 1204 for (const auto& matcher : matchers_) { 1205 matchers.push_back(MatcherCast<RawU>(matcher)); 1206 } 1207 return Matcher<U>(new MatcherImpl<RawU>(std::move(matchers))); 1208 } 1209 1210 private: 1211 const ::std::vector<T> matchers_; 1212 1213 GTEST_DISALLOW_ASSIGN_(SomeOfArrayMatcher); 1214 }; 1215 1216 template <typename T> 1217 using AllOfArrayMatcher = SomeOfArrayMatcher<AllOfMatcherImpl, T>; 1218 1219 template <typename T> 1220 using AnyOfArrayMatcher = SomeOfArrayMatcher<AnyOfMatcherImpl, T>; 1221 1222 // Used for implementing Truly(pred), which turns a predicate into a 1223 // matcher. 1224 template <typename Predicate> 1225 class TrulyMatcher { 1226 public: 1227 explicit TrulyMatcher(Predicate pred) : predicate_(pred) {} 1228 1229 // This method template allows Truly(pred) to be used as a matcher 1230 // for type T where T is the argument type of predicate 'pred'. The 1231 // argument is passed by reference as the predicate may be 1232 // interested in the address of the argument. 1233 template <typename T> 1234 bool MatchAndExplain(T& x, // NOLINT 1235 MatchResultListener* /* listener */) const { 1236 // Without the if-statement, MSVC sometimes warns about converting 1237 // a value to bool (warning 4800). 1238 // 1239 // We cannot write 'return !!predicate_(x);' as that doesn't work 1240 // when predicate_(x) returns a class convertible to bool but 1241 // having no operator!(). 1242 if (predicate_(x)) 1243 return true; 1244 return false; 1245 } 1246 1247 void DescribeTo(::std::ostream* os) const { 1248 *os << "satisfies the given predicate"; 1249 } 1250 1251 void DescribeNegationTo(::std::ostream* os) const { 1252 *os << "doesn't satisfy the given predicate"; 1253 } 1254 1255 private: 1256 Predicate predicate_; 1257 1258 GTEST_DISALLOW_ASSIGN_(TrulyMatcher); 1259 }; 1260 1261 // Used for implementing Matches(matcher), which turns a matcher into 1262 // a predicate. 1263 template <typename M> 1264 class MatcherAsPredicate { 1265 public: 1266 explicit MatcherAsPredicate(M matcher) : matcher_(matcher) {} 1267 1268 // This template operator() allows Matches(m) to be used as a 1269 // predicate on type T where m is a matcher on type T. 1270 // 1271 // The argument x is passed by reference instead of by value, as 1272 // some matcher may be interested in its address (e.g. as in 1273 // Matches(Ref(n))(x)). 1274 template <typename T> 1275 bool operator()(const T& x) const { 1276 // We let matcher_ commit to a particular type here instead of 1277 // when the MatcherAsPredicate object was constructed. This 1278 // allows us to write Matches(m) where m is a polymorphic matcher 1279 // (e.g. Eq(5)). 1280 // 1281 // If we write Matcher<T>(matcher_).Matches(x) here, it won't 1282 // compile when matcher_ has type Matcher<const T&>; if we write 1283 // Matcher<const T&>(matcher_).Matches(x) here, it won't compile 1284 // when matcher_ has type Matcher<T>; if we just write 1285 // matcher_.Matches(x), it won't compile when matcher_ is 1286 // polymorphic, e.g. Eq(5). 1287 // 1288 // MatcherCast<const T&>() is necessary for making the code work 1289 // in all of the above situations. 1290 return MatcherCast<const T&>(matcher_).Matches(x); 1291 } 1292 1293 private: 1294 M matcher_; 1295 1296 GTEST_DISALLOW_ASSIGN_(MatcherAsPredicate); 1297 }; 1298 1299 // For implementing ASSERT_THAT() and EXPECT_THAT(). The template 1300 // argument M must be a type that can be converted to a matcher. 1301 template <typename M> 1302 class PredicateFormatterFromMatcher { 1303 public: 1304 explicit PredicateFormatterFromMatcher(M m) : matcher_(std::move(m)) {} 1305 1306 // This template () operator allows a PredicateFormatterFromMatcher 1307 // object to act as a predicate-formatter suitable for using with 1308 // Google Test's EXPECT_PRED_FORMAT1() macro. 1309 template <typename T> 1310 AssertionResult operator()(const char* value_text, const T& x) const { 1311 // We convert matcher_ to a Matcher<const T&> *now* instead of 1312 // when the PredicateFormatterFromMatcher object was constructed, 1313 // as matcher_ may be polymorphic (e.g. NotNull()) and we won't 1314 // know which type to instantiate it to until we actually see the 1315 // type of x here. 1316 // 1317 // We write SafeMatcherCast<const T&>(matcher_) instead of 1318 // Matcher<const T&>(matcher_), as the latter won't compile when 1319 // matcher_ has type Matcher<T> (e.g. An<int>()). 1320 // We don't write MatcherCast<const T&> either, as that allows 1321 // potentially unsafe downcasting of the matcher argument. 1322 const Matcher<const T&> matcher = SafeMatcherCast<const T&>(matcher_); 1323 1324 // The expected path here is that the matcher should match (i.e. that most 1325 // tests pass) so optimize for this case. 1326 if (matcher.Matches(x)) { 1327 return AssertionSuccess(); 1328 } 1329 1330 ::std::stringstream ss; 1331 ss << "Value of: " << value_text << "\n" 1332 << "Expected: "; 1333 matcher.DescribeTo(&ss); 1334 1335 // Rerun the matcher to "PrintAndExain" the failure. 1336 StringMatchResultListener listener; 1337 if (MatchPrintAndExplain(x, matcher, &listener)) { 1338 ss << "\n The matcher failed on the initial attempt; but passed when " 1339 "rerun to generate the explanation."; 1340 } 1341 ss << "\n Actual: " << listener.str(); 1342 return AssertionFailure() << ss.str(); 1343 } 1344 1345 private: 1346 const M matcher_; 1347 1348 GTEST_DISALLOW_ASSIGN_(PredicateFormatterFromMatcher); 1349 }; 1350 1351 // A helper function for converting a matcher to a predicate-formatter 1352 // without the user needing to explicitly write the type. This is 1353 // used for implementing ASSERT_THAT() and EXPECT_THAT(). 1354 // Implementation detail: 'matcher' is received by-value to force decaying. 1355 template <typename M> 1356 inline PredicateFormatterFromMatcher<M> 1357 MakePredicateFormatterFromMatcher(M matcher) { 1358 return PredicateFormatterFromMatcher<M>(std::move(matcher)); 1359 } 1360 1361 // Implements the polymorphic floating point equality matcher, which matches 1362 // two float values using ULP-based approximation or, optionally, a 1363 // user-specified epsilon. The template is meant to be instantiated with 1364 // FloatType being either float or double. 1365 template <typename FloatType> 1366 class FloatingEqMatcher { 1367 public: 1368 // Constructor for FloatingEqMatcher. 1369 // The matcher's input will be compared with expected. The matcher treats two 1370 // NANs as equal if nan_eq_nan is true. Otherwise, under IEEE standards, 1371 // equality comparisons between NANs will always return false. We specify a 1372 // negative max_abs_error_ term to indicate that ULP-based approximation will 1373 // be used for comparison. 1374 FloatingEqMatcher(FloatType expected, bool nan_eq_nan) : 1375 expected_(expected), nan_eq_nan_(nan_eq_nan), max_abs_error_(-1) { 1376 } 1377 1378 // Constructor that supports a user-specified max_abs_error that will be used 1379 // for comparison instead of ULP-based approximation. The max absolute 1380 // should be non-negative. 1381 FloatingEqMatcher(FloatType expected, bool nan_eq_nan, 1382 FloatType max_abs_error) 1383 : expected_(expected), 1384 nan_eq_nan_(nan_eq_nan), 1385 max_abs_error_(max_abs_error) { 1386 GTEST_CHECK_(max_abs_error >= 0) 1387 << ", where max_abs_error is" << max_abs_error; 1388 } 1389 1390 // Implements floating point equality matcher as a Matcher<T>. 1391 template <typename T> 1392 class Impl : public MatcherInterface<T> { 1393 public: 1394 Impl(FloatType expected, bool nan_eq_nan, FloatType max_abs_error) 1395 : expected_(expected), 1396 nan_eq_nan_(nan_eq_nan), 1397 max_abs_error_(max_abs_error) {} 1398 1399 bool MatchAndExplain(T value, 1400 MatchResultListener* listener) const override { 1401 const FloatingPoint<FloatType> actual(value), expected(expected_); 1402 1403 // Compares NaNs first, if nan_eq_nan_ is true. 1404 if (actual.is_nan() || expected.is_nan()) { 1405 if (actual.is_nan() && expected.is_nan()) { 1406 return nan_eq_nan_; 1407 } 1408 // One is nan; the other is not nan. 1409 return false; 1410 } 1411 if (HasMaxAbsError()) { 1412 // We perform an equality check so that inf will match inf, regardless 1413 // of error bounds. If the result of value - expected_ would result in 1414 // overflow or if either value is inf, the default result is infinity, 1415 // which should only match if max_abs_error_ is also infinity. 1416 if (value == expected_) { 1417 return true; 1418 } 1419 1420 const FloatType diff = value - expected_; 1421 if (fabs(diff) <= max_abs_error_) { 1422 return true; 1423 } 1424 1425 if (listener->IsInterested()) { 1426 *listener << "which is " << diff << " from " << expected_; 1427 } 1428 return false; 1429 } else { 1430 return actual.AlmostEquals(expected); 1431 } 1432 } 1433 1434 void DescribeTo(::std::ostream* os) const override { 1435 // os->precision() returns the previously set precision, which we 1436 // store to restore the ostream to its original configuration 1437 // after outputting. 1438 const ::std::streamsize old_precision = os->precision( 1439 ::std::numeric_limits<FloatType>::digits10 + 2); 1440 if (FloatingPoint<FloatType>(expected_).is_nan()) { 1441 if (nan_eq_nan_) { 1442 *os << "is NaN"; 1443 } else { 1444 *os << "never matches"; 1445 } 1446 } else { 1447 *os << "is approximately " << expected_; 1448 if (HasMaxAbsError()) { 1449 *os << " (absolute error <= " << max_abs_error_ << ")"; 1450 } 1451 } 1452 os->precision(old_precision); 1453 } 1454 1455 void DescribeNegationTo(::std::ostream* os) const override { 1456 // As before, get original precision. 1457 const ::std::streamsize old_precision = os->precision( 1458 ::std::numeric_limits<FloatType>::digits10 + 2); 1459 if (FloatingPoint<FloatType>(expected_).is_nan()) { 1460 if (nan_eq_nan_) { 1461 *os << "isn't NaN"; 1462 } else { 1463 *os << "is anything"; 1464 } 1465 } else { 1466 *os << "isn't approximately " << expected_; 1467 if (HasMaxAbsError()) { 1468 *os << " (absolute error > " << max_abs_error_ << ")"; 1469 } 1470 } 1471 // Restore original precision. 1472 os->precision(old_precision); 1473 } 1474 1475 private: 1476 bool HasMaxAbsError() const { 1477 return max_abs_error_ >= 0; 1478 } 1479 1480 const FloatType expected_; 1481 const bool nan_eq_nan_; 1482 // max_abs_error will be used for value comparison when >= 0. 1483 const FloatType max_abs_error_; 1484 1485 GTEST_DISALLOW_ASSIGN_(Impl); 1486 }; 1487 1488 // The following 3 type conversion operators allow FloatEq(expected) and 1489 // NanSensitiveFloatEq(expected) to be used as a Matcher<float>, a 1490 // Matcher<const float&>, or a Matcher<float&>, but nothing else. 1491 // (While Google's C++ coding style doesn't allow arguments passed 1492 // by non-const reference, we may see them in code not conforming to 1493 // the style. Therefore Google Mock needs to support them.) 1494 operator Matcher<FloatType>() const { 1495 return MakeMatcher( 1496 new Impl<FloatType>(expected_, nan_eq_nan_, max_abs_error_)); 1497 } 1498 1499 operator Matcher<const FloatType&>() const { 1500 return MakeMatcher( 1501 new Impl<const FloatType&>(expected_, nan_eq_nan_, max_abs_error_)); 1502 } 1503 1504 operator Matcher<FloatType&>() const { 1505 return MakeMatcher( 1506 new Impl<FloatType&>(expected_, nan_eq_nan_, max_abs_error_)); 1507 } 1508 1509 private: 1510 const FloatType expected_; 1511 const bool nan_eq_nan_; 1512 // max_abs_error will be used for value comparison when >= 0. 1513 const FloatType max_abs_error_; 1514 1515 GTEST_DISALLOW_ASSIGN_(FloatingEqMatcher); 1516 }; 1517 1518 // A 2-tuple ("binary") wrapper around FloatingEqMatcher: 1519 // FloatingEq2Matcher() matches (x, y) by matching FloatingEqMatcher(x, false) 1520 // against y, and FloatingEq2Matcher(e) matches FloatingEqMatcher(x, false, e) 1521 // against y. The former implements "Eq", the latter "Near". At present, there 1522 // is no version that compares NaNs as equal. 1523 template <typename FloatType> 1524 class FloatingEq2Matcher { 1525 public: 1526 FloatingEq2Matcher() { Init(-1, false); } 1527 1528 explicit FloatingEq2Matcher(bool nan_eq_nan) { Init(-1, nan_eq_nan); } 1529 1530 explicit FloatingEq2Matcher(FloatType max_abs_error) { 1531 Init(max_abs_error, false); 1532 } 1533 1534 FloatingEq2Matcher(FloatType max_abs_error, bool nan_eq_nan) { 1535 Init(max_abs_error, nan_eq_nan); 1536 } 1537 1538 template <typename T1, typename T2> 1539 operator Matcher<::std::tuple<T1, T2>>() const { 1540 return MakeMatcher( 1541 new Impl<::std::tuple<T1, T2>>(max_abs_error_, nan_eq_nan_)); 1542 } 1543 template <typename T1, typename T2> 1544 operator Matcher<const ::std::tuple<T1, T2>&>() const { 1545 return MakeMatcher( 1546 new Impl<const ::std::tuple<T1, T2>&>(max_abs_error_, nan_eq_nan_)); 1547 } 1548 1549 private: 1550 static ::std::ostream& GetDesc(::std::ostream& os) { // NOLINT 1551 return os << "an almost-equal pair"; 1552 } 1553 1554 template <typename Tuple> 1555 class Impl : public MatcherInterface<Tuple> { 1556 public: 1557 Impl(FloatType max_abs_error, bool nan_eq_nan) : 1558 max_abs_error_(max_abs_error), 1559 nan_eq_nan_(nan_eq_nan) {} 1560 1561 bool MatchAndExplain(Tuple args, 1562 MatchResultListener* listener) const override { 1563 if (max_abs_error_ == -1) { 1564 FloatingEqMatcher<FloatType> fm(::std::get<0>(args), nan_eq_nan_); 1565 return static_cast<Matcher<FloatType>>(fm).MatchAndExplain( 1566 ::std::get<1>(args), listener); 1567 } else { 1568 FloatingEqMatcher<FloatType> fm(::std::get<0>(args), nan_eq_nan_, 1569 max_abs_error_); 1570 return static_cast<Matcher<FloatType>>(fm).MatchAndExplain( 1571 ::std::get<1>(args), listener); 1572 } 1573 } 1574 void DescribeTo(::std::ostream* os) const override { 1575 *os << "are " << GetDesc; 1576 } 1577 void DescribeNegationTo(::std::ostream* os) const override { 1578 *os << "aren't " << GetDesc; 1579 } 1580 1581 private: 1582 FloatType max_abs_error_; 1583 const bool nan_eq_nan_; 1584 }; 1585 1586 void Init(FloatType max_abs_error_val, bool nan_eq_nan_val) { 1587 max_abs_error_ = max_abs_error_val; 1588 nan_eq_nan_ = nan_eq_nan_val; 1589 } 1590 FloatType max_abs_error_; 1591 bool nan_eq_nan_; 1592 }; 1593 1594 // Implements the Pointee(m) matcher for matching a pointer whose 1595 // pointee matches matcher m. The pointer can be either raw or smart. 1596 template <typename InnerMatcher> 1597 class PointeeMatcher { 1598 public: 1599 explicit PointeeMatcher(const InnerMatcher& matcher) : matcher_(matcher) {} 1600 1601 // This type conversion operator template allows Pointee(m) to be 1602 // used as a matcher for any pointer type whose pointee type is 1603 // compatible with the inner matcher, where type Pointer can be 1604 // either a raw pointer or a smart pointer. 1605 // 1606 // The reason we do this instead of relying on 1607 // MakePolymorphicMatcher() is that the latter is not flexible 1608 // enough for implementing the DescribeTo() method of Pointee(). 1609 template <typename Pointer> 1610 operator Matcher<Pointer>() const { 1611 return Matcher<Pointer>(new Impl<const Pointer&>(matcher_)); 1612 } 1613 1614 private: 1615 // The monomorphic implementation that works for a particular pointer type. 1616 template <typename Pointer> 1617 class Impl : public MatcherInterface<Pointer> { 1618 public: 1619 typedef typename PointeeOf<typename std::remove_const< 1620 typename std::remove_reference<Pointer>::type>::type>::type Pointee; 1621 1622 explicit Impl(const InnerMatcher& matcher) 1623 : matcher_(MatcherCast<const Pointee&>(matcher)) {} 1624 1625 void DescribeTo(::std::ostream* os) const override { 1626 *os << "points to a value that "; 1627 matcher_.DescribeTo(os); 1628 } 1629 1630 void DescribeNegationTo(::std::ostream* os) const override { 1631 *os << "does not point to a value that "; 1632 matcher_.DescribeTo(os); 1633 } 1634 1635 bool MatchAndExplain(Pointer pointer, 1636 MatchResultListener* listener) const override { 1637 if (GetRawPointer(pointer) == nullptr) return false; 1638 1639 *listener << "which points to "; 1640 return MatchPrintAndExplain(*pointer, matcher_, listener); 1641 } 1642 1643 private: 1644 const Matcher<const Pointee&> matcher_; 1645 1646 GTEST_DISALLOW_ASSIGN_(Impl); 1647 }; 1648 1649 const InnerMatcher matcher_; 1650 1651 GTEST_DISALLOW_ASSIGN_(PointeeMatcher); 1652 }; 1653 1654 #if GTEST_HAS_RTTI 1655 // Implements the WhenDynamicCastTo<T>(m) matcher that matches a pointer or 1656 // reference that matches inner_matcher when dynamic_cast<T> is applied. 1657 // The result of dynamic_cast<To> is forwarded to the inner matcher. 1658 // If To is a pointer and the cast fails, the inner matcher will receive NULL. 1659 // If To is a reference and the cast fails, this matcher returns false 1660 // immediately. 1661 template <typename To> 1662 class WhenDynamicCastToMatcherBase { 1663 public: 1664 explicit WhenDynamicCastToMatcherBase(const Matcher<To>& matcher) 1665 : matcher_(matcher) {} 1666 1667 void DescribeTo(::std::ostream* os) const { 1668 GetCastTypeDescription(os); 1669 matcher_.DescribeTo(os); 1670 } 1671 1672 void DescribeNegationTo(::std::ostream* os) const { 1673 GetCastTypeDescription(os); 1674 matcher_.DescribeNegationTo(os); 1675 } 1676 1677 protected: 1678 const Matcher<To> matcher_; 1679 1680 static std::string GetToName() { 1681 return GetTypeName<To>(); 1682 } 1683 1684 private: 1685 static void GetCastTypeDescription(::std::ostream* os) { 1686 *os << "when dynamic_cast to " << GetToName() << ", "; 1687 } 1688 1689 GTEST_DISALLOW_ASSIGN_(WhenDynamicCastToMatcherBase); 1690 }; 1691 1692 // Primary template. 1693 // To is a pointer. Cast and forward the result. 1694 template <typename To> 1695 class WhenDynamicCastToMatcher : public WhenDynamicCastToMatcherBase<To> { 1696 public: 1697 explicit WhenDynamicCastToMatcher(const Matcher<To>& matcher) 1698 : WhenDynamicCastToMatcherBase<To>(matcher) {} 1699 1700 template <typename From> 1701 bool MatchAndExplain(From from, MatchResultListener* listener) const { 1702 To to = dynamic_cast<To>(from); 1703 return MatchPrintAndExplain(to, this->matcher_, listener); 1704 } 1705 }; 1706 1707 // Specialize for references. 1708 // In this case we return false if the dynamic_cast fails. 1709 template <typename To> 1710 class WhenDynamicCastToMatcher<To&> : public WhenDynamicCastToMatcherBase<To&> { 1711 public: 1712 explicit WhenDynamicCastToMatcher(const Matcher<To&>& matcher) 1713 : WhenDynamicCastToMatcherBase<To&>(matcher) {} 1714 1715 template <typename From> 1716 bool MatchAndExplain(From& from, MatchResultListener* listener) const { 1717 // We don't want an std::bad_cast here, so do the cast with pointers. 1718 To* to = dynamic_cast<To*>(&from); 1719 if (to == nullptr) { 1720 *listener << "which cannot be dynamic_cast to " << this->GetToName(); 1721 return false; 1722 } 1723 return MatchPrintAndExplain(*to, this->matcher_, listener); 1724 } 1725 }; 1726 #endif // GTEST_HAS_RTTI 1727 1728 // Implements the Field() matcher for matching a field (i.e. member 1729 // variable) of an object. 1730 template <typename Class, typename FieldType> 1731 class FieldMatcher { 1732 public: 1733 FieldMatcher(FieldType Class::*field, 1734 const Matcher<const FieldType&>& matcher) 1735 : field_(field), matcher_(matcher), whose_field_("whose given field ") {} 1736 1737 FieldMatcher(const std::string& field_name, FieldType Class::*field, 1738 const Matcher<const FieldType&>& matcher) 1739 : field_(field), 1740 matcher_(matcher), 1741 whose_field_("whose field `" + field_name + "` ") {} 1742 1743 void DescribeTo(::std::ostream* os) const { 1744 *os << "is an object " << whose_field_; 1745 matcher_.DescribeTo(os); 1746 } 1747 1748 void DescribeNegationTo(::std::ostream* os) const { 1749 *os << "is an object " << whose_field_; 1750 matcher_.DescribeNegationTo(os); 1751 } 1752 1753 template <typename T> 1754 bool MatchAndExplain(const T& value, MatchResultListener* listener) const { 1755 // FIXME: The dispatch on std::is_pointer was introduced as a workaround for 1756 // a compiler bug, and can now be removed. 1757 return MatchAndExplainImpl( 1758 typename std::is_pointer<typename std::remove_const<T>::type>::type(), 1759 value, listener); 1760 } 1761 1762 private: 1763 bool MatchAndExplainImpl(std::false_type /* is_not_pointer */, 1764 const Class& obj, 1765 MatchResultListener* listener) const { 1766 *listener << whose_field_ << "is "; 1767 return MatchPrintAndExplain(obj.*field_, matcher_, listener); 1768 } 1769 1770 bool MatchAndExplainImpl(std::true_type /* is_pointer */, const Class* p, 1771 MatchResultListener* listener) const { 1772 if (p == nullptr) return false; 1773 1774 *listener << "which points to an object "; 1775 // Since *p has a field, it must be a class/struct/union type and 1776 // thus cannot be a pointer. Therefore we pass false_type() as 1777 // the first argument. 1778 return MatchAndExplainImpl(std::false_type(), *p, listener); 1779 } 1780 1781 const FieldType Class::*field_; 1782 const Matcher<const FieldType&> matcher_; 1783 1784 // Contains either "whose given field " if the name of the field is unknown 1785 // or "whose field `name_of_field` " if the name is known. 1786 const std::string whose_field_; 1787 1788 GTEST_DISALLOW_ASSIGN_(FieldMatcher); 1789 }; 1790 1791 // Implements the Property() matcher for matching a property 1792 // (i.e. return value of a getter method) of an object. 1793 // 1794 // Property is a const-qualified member function of Class returning 1795 // PropertyType. 1796 template <typename Class, typename PropertyType, typename Property> 1797 class PropertyMatcher { 1798 public: 1799 typedef const PropertyType& RefToConstProperty; 1800 1801 PropertyMatcher(Property property, const Matcher<RefToConstProperty>& matcher) 1802 : property_(property), 1803 matcher_(matcher), 1804 whose_property_("whose given property ") {} 1805 1806 PropertyMatcher(const std::string& property_name, Property property, 1807 const Matcher<RefToConstProperty>& matcher) 1808 : property_(property), 1809 matcher_(matcher), 1810 whose_property_("whose property `" + property_name + "` ") {} 1811 1812 void DescribeTo(::std::ostream* os) const { 1813 *os << "is an object " << whose_property_; 1814 matcher_.DescribeTo(os); 1815 } 1816 1817 void DescribeNegationTo(::std::ostream* os) const { 1818 *os << "is an object " << whose_property_; 1819 matcher_.DescribeNegationTo(os); 1820 } 1821 1822 template <typename T> 1823 bool MatchAndExplain(const T&value, MatchResultListener* listener) const { 1824 return MatchAndExplainImpl( 1825 typename std::is_pointer<typename std::remove_const<T>::type>::type(), 1826 value, listener); 1827 } 1828 1829 private: 1830 bool MatchAndExplainImpl(std::false_type /* is_not_pointer */, 1831 const Class& obj, 1832 MatchResultListener* listener) const { 1833 *listener << whose_property_ << "is "; 1834 // Cannot pass the return value (for example, int) to MatchPrintAndExplain, 1835 // which takes a non-const reference as argument. 1836 RefToConstProperty result = (obj.*property_)(); 1837 return MatchPrintAndExplain(result, matcher_, listener); 1838 } 1839 1840 bool MatchAndExplainImpl(std::true_type /* is_pointer */, const Class* p, 1841 MatchResultListener* listener) const { 1842 if (p == nullptr) return false; 1843 1844 *listener << "which points to an object "; 1845 // Since *p has a property method, it must be a class/struct/union 1846 // type and thus cannot be a pointer. Therefore we pass 1847 // false_type() as the first argument. 1848 return MatchAndExplainImpl(std::false_type(), *p, listener); 1849 } 1850 1851 Property property_; 1852 const Matcher<RefToConstProperty> matcher_; 1853 1854 // Contains either "whose given property " if the name of the property is 1855 // unknown or "whose property `name_of_property` " if the name is known. 1856 const std::string whose_property_; 1857 1858 GTEST_DISALLOW_ASSIGN_(PropertyMatcher); 1859 }; 1860 1861 // Type traits specifying various features of different functors for ResultOf. 1862 // The default template specifies features for functor objects. 1863 template <typename Functor> 1864 struct CallableTraits { 1865 typedef Functor StorageType; 1866 1867 static void CheckIsValid(Functor /* functor */) {} 1868 1869 template <typename T> 1870 static auto Invoke(Functor f, const T& arg) -> decltype(f(arg)) { 1871 return f(arg); 1872 } 1873 }; 1874 1875 // Specialization for function pointers. 1876 template <typename ArgType, typename ResType> 1877 struct CallableTraits<ResType(*)(ArgType)> { 1878 typedef ResType ResultType; 1879 typedef ResType(*StorageType)(ArgType); 1880 1881 static void CheckIsValid(ResType(*f)(ArgType)) { 1882 GTEST_CHECK_(f != nullptr) 1883 << "NULL function pointer is passed into ResultOf()."; 1884 } 1885 template <typename T> 1886 static ResType Invoke(ResType(*f)(ArgType), T arg) { 1887 return (*f)(arg); 1888 } 1889 }; 1890 1891 // Implements the ResultOf() matcher for matching a return value of a 1892 // unary function of an object. 1893 template <typename Callable, typename InnerMatcher> 1894 class ResultOfMatcher { 1895 public: 1896 ResultOfMatcher(Callable callable, InnerMatcher matcher) 1897 : callable_(std::move(callable)), matcher_(std::move(matcher)) { 1898 CallableTraits<Callable>::CheckIsValid(callable_); 1899 } 1900 1901 template <typename T> 1902 operator Matcher<T>() const { 1903 return Matcher<T>(new Impl<const T&>(callable_, matcher_)); 1904 } 1905 1906 private: 1907 typedef typename CallableTraits<Callable>::StorageType CallableStorageType; 1908 1909 template <typename T> 1910 class Impl : public MatcherInterface<T> { 1911 using ResultType = decltype(CallableTraits<Callable>::template Invoke<T>( 1912 std::declval<CallableStorageType>(), std::declval<T>())); 1913 1914 public: 1915 template <typename M> 1916 Impl(const CallableStorageType& callable, const M& matcher) 1917 : callable_(callable), matcher_(MatcherCast<ResultType>(matcher)) {} 1918 1919 void DescribeTo(::std::ostream* os) const override { 1920 *os << "is mapped by the given callable to a value that "; 1921 matcher_.DescribeTo(os); 1922 } 1923 1924 void DescribeNegationTo(::std::ostream* os) const override { 1925 *os << "is mapped by the given callable to a value that "; 1926 matcher_.DescribeNegationTo(os); 1927 } 1928 1929 bool MatchAndExplain(T obj, MatchResultListener* listener) const override { 1930 *listener << "which is mapped by the given callable to "; 1931 // Cannot pass the return value directly to MatchPrintAndExplain, which 1932 // takes a non-const reference as argument. 1933 // Also, specifying template argument explicitly is needed because T could 1934 // be a non-const reference (e.g. Matcher<Uncopyable&>). 1935 ResultType result = 1936 CallableTraits<Callable>::template Invoke<T>(callable_, obj); 1937 return MatchPrintAndExplain(result, matcher_, listener); 1938 } 1939 1940 private: 1941 // Functors often define operator() as non-const method even though 1942 // they are actually stateless. But we need to use them even when 1943 // 'this' is a const pointer. It's the user's responsibility not to 1944 // use stateful callables with ResultOf(), which doesn't guarantee 1945 // how many times the callable will be invoked. 1946 mutable CallableStorageType callable_; 1947 const Matcher<ResultType> matcher_; 1948 1949 GTEST_DISALLOW_ASSIGN_(Impl); 1950 }; // class Impl 1951 1952 const CallableStorageType callable_; 1953 const InnerMatcher matcher_; 1954 1955 GTEST_DISALLOW_ASSIGN_(ResultOfMatcher); 1956 }; 1957 1958 // Implements a matcher that checks the size of an STL-style container. 1959 template <typename SizeMatcher> 1960 class SizeIsMatcher { 1961 public: 1962 explicit SizeIsMatcher(const SizeMatcher& size_matcher) 1963 : size_matcher_(size_matcher) { 1964 } 1965 1966 template <typename Container> 1967 operator Matcher<Container>() const { 1968 return Matcher<Container>(new Impl<const Container&>(size_matcher_)); 1969 } 1970 1971 template <typename Container> 1972 class Impl : public MatcherInterface<Container> { 1973 public: 1974 using SizeType = decltype(std::declval<Container>().size()); 1975 explicit Impl(const SizeMatcher& size_matcher) 1976 : size_matcher_(MatcherCast<SizeType>(size_matcher)) {} 1977 1978 void DescribeTo(::std::ostream* os) const override { 1979 *os << "size "; 1980 size_matcher_.DescribeTo(os); 1981 } 1982 void DescribeNegationTo(::std::ostream* os) const override { 1983 *os << "size "; 1984 size_matcher_.DescribeNegationTo(os); 1985 } 1986 1987 bool MatchAndExplain(Container container, 1988 MatchResultListener* listener) const override { 1989 SizeType size = container.size(); 1990 StringMatchResultListener size_listener; 1991 const bool result = size_matcher_.MatchAndExplain(size, &size_listener); 1992 *listener 1993 << "whose size " << size << (result ? " matches" : " doesn't match"); 1994 PrintIfNotEmpty(size_listener.str(), listener->stream()); 1995 return result; 1996 } 1997 1998 private: 1999 const Matcher<SizeType> size_matcher_; 2000 GTEST_DISALLOW_ASSIGN_(Impl); 2001 }; 2002 2003 private: 2004 const SizeMatcher size_matcher_; 2005 GTEST_DISALLOW_ASSIGN_(SizeIsMatcher); 2006 }; 2007 2008 // Implements a matcher that checks the begin()..end() distance of an STL-style 2009 // container. 2010 template <typename DistanceMatcher> 2011 class BeginEndDistanceIsMatcher { 2012 public: 2013 explicit BeginEndDistanceIsMatcher(const DistanceMatcher& distance_matcher) 2014 : distance_matcher_(distance_matcher) {} 2015 2016 template <typename Container> 2017 operator Matcher<Container>() const { 2018 return Matcher<Container>(new Impl<const Container&>(distance_matcher_)); 2019 } 2020 2021 template <typename Container> 2022 class Impl : public MatcherInterface<Container> { 2023 public: 2024 typedef GTEST_REMOVE_REFERENCE_AND_CONST_(Container) RawContainer; 2025 typedef internal::StlContainerView<RawContainer> View; 2026 typedef typename View::type StlContainer; 2027 typedef typename View::const_reference StlContainerReference; 2028 typedef decltype(std::begin( 2029 std::declval<StlContainerReference>())) StlContainerConstIterator; 2030 typedef typename std::iterator_traits< 2031 StlContainerConstIterator>::difference_type DistanceType; 2032 explicit Impl(const DistanceMatcher& distance_matcher) 2033 : distance_matcher_(MatcherCast<DistanceType>(distance_matcher)) {} 2034 2035 void DescribeTo(::std::ostream* os) const override { 2036 *os << "distance between begin() and end() "; 2037 distance_matcher_.DescribeTo(os); 2038 } 2039 void DescribeNegationTo(::std::ostream* os) const override { 2040 *os << "distance between begin() and end() "; 2041 distance_matcher_.DescribeNegationTo(os); 2042 } 2043 2044 bool MatchAndExplain(Container container, 2045 MatchResultListener* listener) const override { 2046 using std::begin; 2047 using std::end; 2048 DistanceType distance = std::distance(begin(container), end(container)); 2049 StringMatchResultListener distance_listener; 2050 const bool result = 2051 distance_matcher_.MatchAndExplain(distance, &distance_listener); 2052 *listener << "whose distance between begin() and end() " << distance 2053 << (result ? " matches" : " doesn't match"); 2054 PrintIfNotEmpty(distance_listener.str(), listener->stream()); 2055 return result; 2056 } 2057 2058 private: 2059 const Matcher<DistanceType> distance_matcher_; 2060 GTEST_DISALLOW_ASSIGN_(Impl); 2061 }; 2062 2063 private: 2064 const DistanceMatcher distance_matcher_; 2065 GTEST_DISALLOW_ASSIGN_(BeginEndDistanceIsMatcher); 2066 }; 2067 2068 // Implements an equality matcher for any STL-style container whose elements 2069 // support ==. This matcher is like Eq(), but its failure explanations provide 2070 // more detailed information that is useful when the container is used as a set. 2071 // The failure message reports elements that are in one of the operands but not 2072 // the other. The failure messages do not report duplicate or out-of-order 2073 // elements in the containers (which don't properly matter to sets, but can 2074 // occur if the containers are vectors or lists, for example). 2075 // 2076 // Uses the container's const_iterator, value_type, operator ==, 2077 // begin(), and end(). 2078 template <typename Container> 2079 class ContainerEqMatcher { 2080 public: 2081 typedef internal::StlContainerView<Container> View; 2082 typedef typename View::type StlContainer; 2083 typedef typename View::const_reference StlContainerReference; 2084 2085 static_assert(!std::is_const<Container>::value, 2086 "Container type must not be const"); 2087 static_assert(!std::is_reference<Container>::value, 2088 "Container type must not be a reference"); 2089 2090 // We make a copy of expected in case the elements in it are modified 2091 // after this matcher is created. 2092 explicit ContainerEqMatcher(const Container& expected) 2093 : expected_(View::Copy(expected)) {} 2094 2095 void DescribeTo(::std::ostream* os) const { 2096 *os << "equals "; 2097 UniversalPrint(expected_, os); 2098 } 2099 void DescribeNegationTo(::std::ostream* os) const { 2100 *os << "does not equal "; 2101 UniversalPrint(expected_, os); 2102 } 2103 2104 template <typename LhsContainer> 2105 bool MatchAndExplain(const LhsContainer& lhs, 2106 MatchResultListener* listener) const { 2107 typedef internal::StlContainerView< 2108 typename std::remove_const<LhsContainer>::type> 2109 LhsView; 2110 typedef typename LhsView::type LhsStlContainer; 2111 StlContainerReference lhs_stl_container = LhsView::ConstReference(lhs); 2112 if (lhs_stl_container == expected_) 2113 return true; 2114 2115 ::std::ostream* const os = listener->stream(); 2116 if (os != nullptr) { 2117 // Something is different. Check for extra values first. 2118 bool printed_header = false; 2119 for (typename LhsStlContainer::const_iterator it = 2120 lhs_stl_container.begin(); 2121 it != lhs_stl_container.end(); ++it) { 2122 if (internal::ArrayAwareFind(expected_.begin(), expected_.end(), *it) == 2123 expected_.end()) { 2124 if (printed_header) { 2125 *os << ", "; 2126 } else { 2127 *os << "which has these unexpected elements: "; 2128 printed_header = true; 2129 } 2130 UniversalPrint(*it, os); 2131 } 2132 } 2133 2134 // Now check for missing values. 2135 bool printed_header2 = false; 2136 for (typename StlContainer::const_iterator it = expected_.begin(); 2137 it != expected_.end(); ++it) { 2138 if (internal::ArrayAwareFind( 2139 lhs_stl_container.begin(), lhs_stl_container.end(), *it) == 2140 lhs_stl_container.end()) { 2141 if (printed_header2) { 2142 *os << ", "; 2143 } else { 2144 *os << (printed_header ? ",\nand" : "which") 2145 << " doesn't have these expected elements: "; 2146 printed_header2 = true; 2147 } 2148 UniversalPrint(*it, os); 2149 } 2150 } 2151 } 2152 2153 return false; 2154 } 2155 2156 private: 2157 const StlContainer expected_; 2158 2159 GTEST_DISALLOW_ASSIGN_(ContainerEqMatcher); 2160 }; 2161 2162 // A comparator functor that uses the < operator to compare two values. 2163 struct LessComparator { 2164 template <typename T, typename U> 2165 bool operator()(const T& lhs, const U& rhs) const { return lhs < rhs; } 2166 }; 2167 2168 // Implements WhenSortedBy(comparator, container_matcher). 2169 template <typename Comparator, typename ContainerMatcher> 2170 class WhenSortedByMatcher { 2171 public: 2172 WhenSortedByMatcher(const Comparator& comparator, 2173 const ContainerMatcher& matcher) 2174 : comparator_(comparator), matcher_(matcher) {} 2175 2176 template <typename LhsContainer> 2177 operator Matcher<LhsContainer>() const { 2178 return MakeMatcher(new Impl<LhsContainer>(comparator_, matcher_)); 2179 } 2180 2181 template <typename LhsContainer> 2182 class Impl : public MatcherInterface<LhsContainer> { 2183 public: 2184 typedef internal::StlContainerView< 2185 GTEST_REMOVE_REFERENCE_AND_CONST_(LhsContainer)> LhsView; 2186 typedef typename LhsView::type LhsStlContainer; 2187 typedef typename LhsView::const_reference LhsStlContainerReference; 2188 // Transforms std::pair<const Key, Value> into std::pair<Key, Value> 2189 // so that we can match associative containers. 2190 typedef typename RemoveConstFromKey< 2191 typename LhsStlContainer::value_type>::type LhsValue; 2192 2193 Impl(const Comparator& comparator, const ContainerMatcher& matcher) 2194 : comparator_(comparator), matcher_(matcher) {} 2195 2196 void DescribeTo(::std::ostream* os) const override { 2197 *os << "(when sorted) "; 2198 matcher_.DescribeTo(os); 2199 } 2200 2201 void DescribeNegationTo(::std::ostream* os) const override { 2202 *os << "(when sorted) "; 2203 matcher_.DescribeNegationTo(os); 2204 } 2205 2206 bool MatchAndExplain(LhsContainer lhs, 2207 MatchResultListener* listener) const override { 2208 LhsStlContainerReference lhs_stl_container = LhsView::ConstReference(lhs); 2209 ::std::vector<LhsValue> sorted_container(lhs_stl_container.begin(), 2210 lhs_stl_container.end()); 2211 ::std::sort( 2212 sorted_container.begin(), sorted_container.end(), comparator_); 2213 2214 if (!listener->IsInterested()) { 2215 // If the listener is not interested, we do not need to 2216 // construct the inner explanation. 2217 return matcher_.Matches(sorted_container); 2218 } 2219 2220 *listener << "which is "; 2221 UniversalPrint(sorted_container, listener->stream()); 2222 *listener << " when sorted"; 2223 2224 StringMatchResultListener inner_listener; 2225 const bool match = matcher_.MatchAndExplain(sorted_container, 2226 &inner_listener); 2227 PrintIfNotEmpty(inner_listener.str(), listener->stream()); 2228 return match; 2229 } 2230 2231 private: 2232 const Comparator comparator_; 2233 const Matcher<const ::std::vector<LhsValue>&> matcher_; 2234 2235 GTEST_DISALLOW_COPY_AND_ASSIGN_(Impl); 2236 }; 2237 2238 private: 2239 const Comparator comparator_; 2240 const ContainerMatcher matcher_; 2241 2242 GTEST_DISALLOW_ASSIGN_(WhenSortedByMatcher); 2243 }; 2244 2245 // Implements Pointwise(tuple_matcher, rhs_container). tuple_matcher 2246 // must be able to be safely cast to Matcher<std::tuple<const T1&, const 2247 // T2&> >, where T1 and T2 are the types of elements in the LHS 2248 // container and the RHS container respectively. 2249 template <typename TupleMatcher, typename RhsContainer> 2250 class PointwiseMatcher { 2251 GTEST_COMPILE_ASSERT_( 2252 !IsHashTable<GTEST_REMOVE_REFERENCE_AND_CONST_(RhsContainer)>::value, 2253 use_UnorderedPointwise_with_hash_tables); 2254 2255 public: 2256 typedef internal::StlContainerView<RhsContainer> RhsView; 2257 typedef typename RhsView::type RhsStlContainer; 2258 typedef typename RhsStlContainer::value_type RhsValue; 2259 2260 static_assert(!std::is_const<RhsContainer>::value, 2261 "RhsContainer type must not be const"); 2262 static_assert(!std::is_reference<RhsContainer>::value, 2263 "RhsContainer type must not be a reference"); 2264 2265 // Like ContainerEq, we make a copy of rhs in case the elements in 2266 // it are modified after this matcher is created. 2267 PointwiseMatcher(const TupleMatcher& tuple_matcher, const RhsContainer& rhs) 2268 : tuple_matcher_(tuple_matcher), rhs_(RhsView::Copy(rhs)) {} 2269 2270 template <typename LhsContainer> 2271 operator Matcher<LhsContainer>() const { 2272 GTEST_COMPILE_ASSERT_( 2273 !IsHashTable<GTEST_REMOVE_REFERENCE_AND_CONST_(LhsContainer)>::value, 2274 use_UnorderedPointwise_with_hash_tables); 2275 2276 return Matcher<LhsContainer>( 2277 new Impl<const LhsContainer&>(tuple_matcher_, rhs_)); 2278 } 2279 2280 template <typename LhsContainer> 2281 class Impl : public MatcherInterface<LhsContainer> { 2282 public: 2283 typedef internal::StlContainerView< 2284 GTEST_REMOVE_REFERENCE_AND_CONST_(LhsContainer)> LhsView; 2285 typedef typename LhsView::type LhsStlContainer; 2286 typedef typename LhsView::const_reference LhsStlContainerReference; 2287 typedef typename LhsStlContainer::value_type LhsValue; 2288 // We pass the LHS value and the RHS value to the inner matcher by 2289 // reference, as they may be expensive to copy. We must use tuple 2290 // instead of pair here, as a pair cannot hold references (C++ 98, 2291 // 20.2.2 [lib.pairs]). 2292 typedef ::std::tuple<const LhsValue&, const RhsValue&> InnerMatcherArg; 2293 2294 Impl(const TupleMatcher& tuple_matcher, const RhsStlContainer& rhs) 2295 // mono_tuple_matcher_ holds a monomorphic version of the tuple matcher. 2296 : mono_tuple_matcher_(SafeMatcherCast<InnerMatcherArg>(tuple_matcher)), 2297 rhs_(rhs) {} 2298 2299 void DescribeTo(::std::ostream* os) const override { 2300 *os << "contains " << rhs_.size() 2301 << " values, where each value and its corresponding value in "; 2302 UniversalPrinter<RhsStlContainer>::Print(rhs_, os); 2303 *os << " "; 2304 mono_tuple_matcher_.DescribeTo(os); 2305 } 2306 void DescribeNegationTo(::std::ostream* os) const override { 2307 *os << "doesn't contain exactly " << rhs_.size() 2308 << " values, or contains a value x at some index i" 2309 << " where x and the i-th value of "; 2310 UniversalPrint(rhs_, os); 2311 *os << " "; 2312 mono_tuple_matcher_.DescribeNegationTo(os); 2313 } 2314 2315 bool MatchAndExplain(LhsContainer lhs, 2316 MatchResultListener* listener) const override { 2317 LhsStlContainerReference lhs_stl_container = LhsView::ConstReference(lhs); 2318 const size_t actual_size = lhs_stl_container.size(); 2319 if (actual_size != rhs_.size()) { 2320 *listener << "which contains " << actual_size << " values"; 2321 return false; 2322 } 2323 2324 typename LhsStlContainer::const_iterator left = lhs_stl_container.begin(); 2325 typename RhsStlContainer::const_iterator right = rhs_.begin(); 2326 for (size_t i = 0; i != actual_size; ++i, ++left, ++right) { 2327 if (listener->IsInterested()) { 2328 StringMatchResultListener inner_listener; 2329 // Create InnerMatcherArg as a temporarily object to avoid it outlives 2330 // *left and *right. Dereference or the conversion to `const T&` may 2331 // return temp objects, e.g for vector<bool>. 2332 if (!mono_tuple_matcher_.MatchAndExplain( 2333 InnerMatcherArg(ImplicitCast_<const LhsValue&>(*left), 2334 ImplicitCast_<const RhsValue&>(*right)), 2335 &inner_listener)) { 2336 *listener << "where the value pair ("; 2337 UniversalPrint(*left, listener->stream()); 2338 *listener << ", "; 2339 UniversalPrint(*right, listener->stream()); 2340 *listener << ") at index #" << i << " don't match"; 2341 PrintIfNotEmpty(inner_listener.str(), listener->stream()); 2342 return false; 2343 } 2344 } else { 2345 if (!mono_tuple_matcher_.Matches( 2346 InnerMatcherArg(ImplicitCast_<const LhsValue&>(*left), 2347 ImplicitCast_<const RhsValue&>(*right)))) 2348 return false; 2349 } 2350 } 2351 2352 return true; 2353 } 2354 2355 private: 2356 const Matcher<InnerMatcherArg> mono_tuple_matcher_; 2357 const RhsStlContainer rhs_; 2358 2359 GTEST_DISALLOW_ASSIGN_(Impl); 2360 }; 2361 2362 private: 2363 const TupleMatcher tuple_matcher_; 2364 const RhsStlContainer rhs_; 2365 2366 GTEST_DISALLOW_ASSIGN_(PointwiseMatcher); 2367 }; 2368 2369 // Holds the logic common to ContainsMatcherImpl and EachMatcherImpl. 2370 template <typename Container> 2371 class QuantifierMatcherImpl : public MatcherInterface<Container> { 2372 public: 2373 typedef GTEST_REMOVE_REFERENCE_AND_CONST_(Container) RawContainer; 2374 typedef StlContainerView<RawContainer> View; 2375 typedef typename View::type StlContainer; 2376 typedef typename View::const_reference StlContainerReference; 2377 typedef typename StlContainer::value_type Element; 2378 2379 template <typename InnerMatcher> 2380 explicit QuantifierMatcherImpl(InnerMatcher inner_matcher) 2381 : inner_matcher_( 2382 testing::SafeMatcherCast<const Element&>(inner_matcher)) {} 2383 2384 // Checks whether: 2385 // * All elements in the container match, if all_elements_should_match. 2386 // * Any element in the container matches, if !all_elements_should_match. 2387 bool MatchAndExplainImpl(bool all_elements_should_match, 2388 Container container, 2389 MatchResultListener* listener) const { 2390 StlContainerReference stl_container = View::ConstReference(container); 2391 size_t i = 0; 2392 for (typename StlContainer::const_iterator it = stl_container.begin(); 2393 it != stl_container.end(); ++it, ++i) { 2394 StringMatchResultListener inner_listener; 2395 const bool matches = inner_matcher_.MatchAndExplain(*it, &inner_listener); 2396 2397 if (matches != all_elements_should_match) { 2398 *listener << "whose element #" << i 2399 << (matches ? " matches" : " doesn't match"); 2400 PrintIfNotEmpty(inner_listener.str(), listener->stream()); 2401 return !all_elements_should_match; 2402 } 2403 } 2404 return all_elements_should_match; 2405 } 2406 2407 protected: 2408 const Matcher<const Element&> inner_matcher_; 2409 2410 GTEST_DISALLOW_ASSIGN_(QuantifierMatcherImpl); 2411 }; 2412 2413 // Implements Contains(element_matcher) for the given argument type Container. 2414 // Symmetric to EachMatcherImpl. 2415 template <typename Container> 2416 class ContainsMatcherImpl : public QuantifierMatcherImpl<Container> { 2417 public: 2418 template <typename InnerMatcher> 2419 explicit ContainsMatcherImpl(InnerMatcher inner_matcher) 2420 : QuantifierMatcherImpl<Container>(inner_matcher) {} 2421 2422 // Describes what this matcher does. 2423 void DescribeTo(::std::ostream* os) const override { 2424 *os << "contains at least one element that "; 2425 this->inner_matcher_.DescribeTo(os); 2426 } 2427 2428 void DescribeNegationTo(::std::ostream* os) const override { 2429 *os << "doesn't contain any element that "; 2430 this->inner_matcher_.DescribeTo(os); 2431 } 2432 2433 bool MatchAndExplain(Container container, 2434 MatchResultListener* listener) const override { 2435 return this->MatchAndExplainImpl(false, container, listener); 2436 } 2437 2438 private: 2439 GTEST_DISALLOW_ASSIGN_(ContainsMatcherImpl); 2440 }; 2441 2442 // Implements Each(element_matcher) for the given argument type Container. 2443 // Symmetric to ContainsMatcherImpl. 2444 template <typename Container> 2445 class EachMatcherImpl : public QuantifierMatcherImpl<Container> { 2446 public: 2447 template <typename InnerMatcher> 2448 explicit EachMatcherImpl(InnerMatcher inner_matcher) 2449 : QuantifierMatcherImpl<Container>(inner_matcher) {} 2450 2451 // Describes what this matcher does. 2452 void DescribeTo(::std::ostream* os) const override { 2453 *os << "only contains elements that "; 2454 this->inner_matcher_.DescribeTo(os); 2455 } 2456 2457 void DescribeNegationTo(::std::ostream* os) const override { 2458 *os << "contains some element that "; 2459 this->inner_matcher_.DescribeNegationTo(os); 2460 } 2461 2462 bool MatchAndExplain(Container container, 2463 MatchResultListener* listener) const override { 2464 return this->MatchAndExplainImpl(true, container, listener); 2465 } 2466 2467 private: 2468 GTEST_DISALLOW_ASSIGN_(EachMatcherImpl); 2469 }; 2470 2471 // Implements polymorphic Contains(element_matcher). 2472 template <typename M> 2473 class ContainsMatcher { 2474 public: 2475 explicit ContainsMatcher(M m) : inner_matcher_(m) {} 2476 2477 template <typename Container> 2478 operator Matcher<Container>() const { 2479 return Matcher<Container>( 2480 new ContainsMatcherImpl<const Container&>(inner_matcher_)); 2481 } 2482 2483 private: 2484 const M inner_matcher_; 2485 2486 GTEST_DISALLOW_ASSIGN_(ContainsMatcher); 2487 }; 2488 2489 // Implements polymorphic Each(element_matcher). 2490 template <typename M> 2491 class EachMatcher { 2492 public: 2493 explicit EachMatcher(M m) : inner_matcher_(m) {} 2494 2495 template <typename Container> 2496 operator Matcher<Container>() const { 2497 return Matcher<Container>( 2498 new EachMatcherImpl<const Container&>(inner_matcher_)); 2499 } 2500 2501 private: 2502 const M inner_matcher_; 2503 2504 GTEST_DISALLOW_ASSIGN_(EachMatcher); 2505 }; 2506 2507 struct Rank1 {}; 2508 struct Rank0 : Rank1 {}; 2509 2510 namespace pair_getters { 2511 using std::get; 2512 template <typename T> 2513 auto First(T& x, Rank1) -> decltype(get<0>(x)) { // NOLINT 2514 return get<0>(x); 2515 } 2516 template <typename T> 2517 auto First(T& x, Rank0) -> decltype((x.first)) { // NOLINT 2518 return x.first; 2519 } 2520 2521 template <typename T> 2522 auto Second(T& x, Rank1) -> decltype(get<1>(x)) { // NOLINT 2523 return get<1>(x); 2524 } 2525 template <typename T> 2526 auto Second(T& x, Rank0) -> decltype((x.second)) { // NOLINT 2527 return x.second; 2528 } 2529 } // namespace pair_getters 2530 2531 // Implements Key(inner_matcher) for the given argument pair type. 2532 // Key(inner_matcher) matches an std::pair whose 'first' field matches 2533 // inner_matcher. For example, Contains(Key(Ge(5))) can be used to match an 2534 // std::map that contains at least one element whose key is >= 5. 2535 template <typename PairType> 2536 class KeyMatcherImpl : public MatcherInterface<PairType> { 2537 public: 2538 typedef GTEST_REMOVE_REFERENCE_AND_CONST_(PairType) RawPairType; 2539 typedef typename RawPairType::first_type KeyType; 2540 2541 template <typename InnerMatcher> 2542 explicit KeyMatcherImpl(InnerMatcher inner_matcher) 2543 : inner_matcher_( 2544 testing::SafeMatcherCast<const KeyType&>(inner_matcher)) { 2545 } 2546 2547 // Returns true if and only if 'key_value.first' (the key) matches the inner 2548 // matcher. 2549 bool MatchAndExplain(PairType key_value, 2550 MatchResultListener* listener) const override { 2551 StringMatchResultListener inner_listener; 2552 const bool match = inner_matcher_.MatchAndExplain( 2553 pair_getters::First(key_value, Rank0()), &inner_listener); 2554 const std::string explanation = inner_listener.str(); 2555 if (explanation != "") { 2556 *listener << "whose first field is a value " << explanation; 2557 } 2558 return match; 2559 } 2560 2561 // Describes what this matcher does. 2562 void DescribeTo(::std::ostream* os) const override { 2563 *os << "has a key that "; 2564 inner_matcher_.DescribeTo(os); 2565 } 2566 2567 // Describes what the negation of this matcher does. 2568 void DescribeNegationTo(::std::ostream* os) const override { 2569 *os << "doesn't have a key that "; 2570 inner_matcher_.DescribeTo(os); 2571 } 2572 2573 private: 2574 const Matcher<const KeyType&> inner_matcher_; 2575 2576 GTEST_DISALLOW_ASSIGN_(KeyMatcherImpl); 2577 }; 2578 2579 // Implements polymorphic Key(matcher_for_key). 2580 template <typename M> 2581 class KeyMatcher { 2582 public: 2583 explicit KeyMatcher(M m) : matcher_for_key_(m) {} 2584 2585 template <typename PairType> 2586 operator Matcher<PairType>() const { 2587 return Matcher<PairType>( 2588 new KeyMatcherImpl<const PairType&>(matcher_for_key_)); 2589 } 2590 2591 private: 2592 const M matcher_for_key_; 2593 2594 GTEST_DISALLOW_ASSIGN_(KeyMatcher); 2595 }; 2596 2597 // Implements Pair(first_matcher, second_matcher) for the given argument pair 2598 // type with its two matchers. See Pair() function below. 2599 template <typename PairType> 2600 class PairMatcherImpl : public MatcherInterface<PairType> { 2601 public: 2602 typedef GTEST_REMOVE_REFERENCE_AND_CONST_(PairType) RawPairType; 2603 typedef typename RawPairType::first_type FirstType; 2604 typedef typename RawPairType::second_type SecondType; 2605 2606 template <typename FirstMatcher, typename SecondMatcher> 2607 PairMatcherImpl(FirstMatcher first_matcher, SecondMatcher second_matcher) 2608 : first_matcher_( 2609 testing::SafeMatcherCast<const FirstType&>(first_matcher)), 2610 second_matcher_( 2611 testing::SafeMatcherCast<const SecondType&>(second_matcher)) { 2612 } 2613 2614 // Describes what this matcher does. 2615 void DescribeTo(::std::ostream* os) const override { 2616 *os << "has a first field that "; 2617 first_matcher_.DescribeTo(os); 2618 *os << ", and has a second field that "; 2619 second_matcher_.DescribeTo(os); 2620 } 2621 2622 // Describes what the negation of this matcher does. 2623 void DescribeNegationTo(::std::ostream* os) const override { 2624 *os << "has a first field that "; 2625 first_matcher_.DescribeNegationTo(os); 2626 *os << ", or has a second field that "; 2627 second_matcher_.DescribeNegationTo(os); 2628 } 2629 2630 // Returns true if and only if 'a_pair.first' matches first_matcher and 2631 // 'a_pair.second' matches second_matcher. 2632 bool MatchAndExplain(PairType a_pair, 2633 MatchResultListener* listener) const override { 2634 if (!listener->IsInterested()) { 2635 // If the listener is not interested, we don't need to construct the 2636 // explanation. 2637 return first_matcher_.Matches(pair_getters::First(a_pair, Rank0())) && 2638 second_matcher_.Matches(pair_getters::Second(a_pair, Rank0())); 2639 } 2640 StringMatchResultListener first_inner_listener; 2641 if (!first_matcher_.MatchAndExplain(pair_getters::First(a_pair, Rank0()), 2642 &first_inner_listener)) { 2643 *listener << "whose first field does not match"; 2644 PrintIfNotEmpty(first_inner_listener.str(), listener->stream()); 2645 return false; 2646 } 2647 StringMatchResultListener second_inner_listener; 2648 if (!second_matcher_.MatchAndExplain(pair_getters::Second(a_pair, Rank0()), 2649 &second_inner_listener)) { 2650 *listener << "whose second field does not match"; 2651 PrintIfNotEmpty(second_inner_listener.str(), listener->stream()); 2652 return false; 2653 } 2654 ExplainSuccess(first_inner_listener.str(), second_inner_listener.str(), 2655 listener); 2656 return true; 2657 } 2658 2659 private: 2660 void ExplainSuccess(const std::string& first_explanation, 2661 const std::string& second_explanation, 2662 MatchResultListener* listener) const { 2663 *listener << "whose both fields match"; 2664 if (first_explanation != "") { 2665 *listener << ", where the first field is a value " << first_explanation; 2666 } 2667 if (second_explanation != "") { 2668 *listener << ", "; 2669 if (first_explanation != "") { 2670 *listener << "and "; 2671 } else { 2672 *listener << "where "; 2673 } 2674 *listener << "the second field is a value " << second_explanation; 2675 } 2676 } 2677 2678 const Matcher<const FirstType&> first_matcher_; 2679 const Matcher<const SecondType&> second_matcher_; 2680 2681 GTEST_DISALLOW_ASSIGN_(PairMatcherImpl); 2682 }; 2683 2684 // Implements polymorphic Pair(first_matcher, second_matcher). 2685 template <typename FirstMatcher, typename SecondMatcher> 2686 class PairMatcher { 2687 public: 2688 PairMatcher(FirstMatcher first_matcher, SecondMatcher second_matcher) 2689 : first_matcher_(first_matcher), second_matcher_(second_matcher) {} 2690 2691 template <typename PairType> 2692 operator Matcher<PairType> () const { 2693 return Matcher<PairType>( 2694 new PairMatcherImpl<const PairType&>(first_matcher_, second_matcher_)); 2695 } 2696 2697 private: 2698 const FirstMatcher first_matcher_; 2699 const SecondMatcher second_matcher_; 2700 2701 GTEST_DISALLOW_ASSIGN_(PairMatcher); 2702 }; 2703 2704 // Implements ElementsAre() and ElementsAreArray(). 2705 template <typename Container> 2706 class ElementsAreMatcherImpl : public MatcherInterface<Container> { 2707 public: 2708 typedef GTEST_REMOVE_REFERENCE_AND_CONST_(Container) RawContainer; 2709 typedef internal::StlContainerView<RawContainer> View; 2710 typedef typename View::type StlContainer; 2711 typedef typename View::const_reference StlContainerReference; 2712 typedef decltype(std::begin( 2713 std::declval<StlContainerReference>())) StlContainerConstIterator; 2714 typedef typename std::remove_reference< 2715 decltype(*std::declval<StlContainerConstIterator &>())>::type Element; 2716 2717 // Constructs the matcher from a sequence of element values or 2718 // element matchers. 2719 template <typename InputIter> 2720 ElementsAreMatcherImpl(InputIter first, InputIter last) { 2721 while (first != last) { 2722 matchers_.push_back(MatcherCast<const Element&>(*first++)); 2723 } 2724 } 2725 2726 // Describes what this matcher does. 2727 void DescribeTo(::std::ostream* os) const override { 2728 if (count() == 0) { 2729 *os << "is empty"; 2730 } else if (count() == 1) { 2731 *os << "has 1 element that "; 2732 matchers_[0].DescribeTo(os); 2733 } else { 2734 *os << "has " << Elements(count()) << " where\n"; 2735 for (size_t i = 0; i != count(); ++i) { 2736 *os << "element #" << i << " "; 2737 matchers_[i].DescribeTo(os); 2738 if (i + 1 < count()) { 2739 *os << ",\n"; 2740 } 2741 } 2742 } 2743 } 2744 2745 // Describes what the negation of this matcher does. 2746 void DescribeNegationTo(::std::ostream* os) const override { 2747 if (count() == 0) { 2748 *os << "isn't empty"; 2749 return; 2750 } 2751 2752 *os << "doesn't have " << Elements(count()) << ", or\n"; 2753 for (size_t i = 0; i != count(); ++i) { 2754 *os << "element #" << i << " "; 2755 matchers_[i].DescribeNegationTo(os); 2756 if (i + 1 < count()) { 2757 *os << ", or\n"; 2758 } 2759 } 2760 } 2761 2762 bool MatchAndExplain(Container container, 2763 MatchResultListener* listener) const override { 2764 // To work with stream-like "containers", we must only walk 2765 // through the elements in one pass. 2766 2767 const bool listener_interested = listener->IsInterested(); 2768 2769 // explanations[i] is the explanation of the element at index i. 2770 ::std::vector<std::string> explanations(count()); 2771 StlContainerReference stl_container = View::ConstReference(container); 2772 StlContainerConstIterator it = stl_container.begin(); 2773 size_t exam_pos = 0; 2774 bool mismatch_found = false; // Have we found a mismatched element yet? 2775 2776 // Go through the elements and matchers in pairs, until we reach 2777 // the end of either the elements or the matchers, or until we find a 2778 // mismatch. 2779 for (; it != stl_container.end() && exam_pos != count(); ++it, ++exam_pos) { 2780 bool match; // Does the current element match the current matcher? 2781 if (listener_interested) { 2782 StringMatchResultListener s; 2783 match = matchers_[exam_pos].MatchAndExplain(*it, &s); 2784 explanations[exam_pos] = s.str(); 2785 } else { 2786 match = matchers_[exam_pos].Matches(*it); 2787 } 2788 2789 if (!match) { 2790 mismatch_found = true; 2791 break; 2792 } 2793 } 2794 // If mismatch_found is true, 'exam_pos' is the index of the mismatch. 2795 2796 // Find how many elements the actual container has. We avoid 2797 // calling size() s.t. this code works for stream-like "containers" 2798 // that don't define size(). 2799 size_t actual_count = exam_pos; 2800 for (; it != stl_container.end(); ++it) { 2801 ++actual_count; 2802 } 2803 2804 if (actual_count != count()) { 2805 // The element count doesn't match. If the container is empty, 2806 // there's no need to explain anything as Google Mock already 2807 // prints the empty container. Otherwise we just need to show 2808 // how many elements there actually are. 2809 if (listener_interested && (actual_count != 0)) { 2810 *listener << "which has " << Elements(actual_count); 2811 } 2812 return false; 2813 } 2814 2815 if (mismatch_found) { 2816 // The element count matches, but the exam_pos-th element doesn't match. 2817 if (listener_interested) { 2818 *listener << "whose element #" << exam_pos << " doesn't match"; 2819 PrintIfNotEmpty(explanations[exam_pos], listener->stream()); 2820 } 2821 return false; 2822 } 2823 2824 // Every element matches its expectation. We need to explain why 2825 // (the obvious ones can be skipped). 2826 if (listener_interested) { 2827 bool reason_printed = false; 2828 for (size_t i = 0; i != count(); ++i) { 2829 const std::string& s = explanations[i]; 2830 if (!s.empty()) { 2831 if (reason_printed) { 2832 *listener << ",\nand "; 2833 } 2834 *listener << "whose element #" << i << " matches, " << s; 2835 reason_printed = true; 2836 } 2837 } 2838 } 2839 return true; 2840 } 2841 2842 private: 2843 static Message Elements(size_t count) { 2844 return Message() << count << (count == 1 ? " element" : " elements"); 2845 } 2846 2847 size_t count() const { return matchers_.size(); } 2848 2849 ::std::vector<Matcher<const Element&> > matchers_; 2850 2851 GTEST_DISALLOW_ASSIGN_(ElementsAreMatcherImpl); 2852 }; 2853 2854 // Connectivity matrix of (elements X matchers), in element-major order. 2855 // Initially, there are no edges. 2856 // Use NextGraph() to iterate over all possible edge configurations. 2857 // Use Randomize() to generate a random edge configuration. 2858 class GTEST_API_ MatchMatrix { 2859 public: 2860 MatchMatrix(size_t num_elements, size_t num_matchers) 2861 : num_elements_(num_elements), 2862 num_matchers_(num_matchers), 2863 matched_(num_elements_* num_matchers_, 0) { 2864 } 2865 2866 size_t LhsSize() const { return num_elements_; } 2867 size_t RhsSize() const { return num_matchers_; } 2868 bool HasEdge(size_t ilhs, size_t irhs) const { 2869 return matched_[SpaceIndex(ilhs, irhs)] == 1; 2870 } 2871 void SetEdge(size_t ilhs, size_t irhs, bool b) { 2872 matched_[SpaceIndex(ilhs, irhs)] = b ? 1 : 0; 2873 } 2874 2875 // Treating the connectivity matrix as a (LhsSize()*RhsSize())-bit number, 2876 // adds 1 to that number; returns false if incrementing the graph left it 2877 // empty. 2878 bool NextGraph(); 2879 2880 void Randomize(); 2881 2882 std::string DebugString() const; 2883 2884 private: 2885 size_t SpaceIndex(size_t ilhs, size_t irhs) const { 2886 return ilhs * num_matchers_ + irhs; 2887 } 2888 2889 size_t num_elements_; 2890 size_t num_matchers_; 2891 2892 // Each element is a char interpreted as bool. They are stored as a 2893 // flattened array in lhs-major order, use 'SpaceIndex()' to translate 2894 // a (ilhs, irhs) matrix coordinate into an offset. 2895 ::std::vector<char> matched_; 2896 }; 2897 2898 typedef ::std::pair<size_t, size_t> ElementMatcherPair; 2899 typedef ::std::vector<ElementMatcherPair> ElementMatcherPairs; 2900 2901 // Returns a maximum bipartite matching for the specified graph 'g'. 2902 // The matching is represented as a vector of {element, matcher} pairs. 2903 GTEST_API_ ElementMatcherPairs 2904 FindMaxBipartiteMatching(const MatchMatrix& g); 2905 2906 struct UnorderedMatcherRequire { 2907 enum Flags { 2908 Superset = 1 << 0, 2909 Subset = 1 << 1, 2910 ExactMatch = Superset | Subset, 2911 }; 2912 }; 2913 2914 // Untyped base class for implementing UnorderedElementsAre. By 2915 // putting logic that's not specific to the element type here, we 2916 // reduce binary bloat and increase compilation speed. 2917 class GTEST_API_ UnorderedElementsAreMatcherImplBase { 2918 protected: 2919 explicit UnorderedElementsAreMatcherImplBase( 2920 UnorderedMatcherRequire::Flags matcher_flags) 2921 : match_flags_(matcher_flags) {} 2922 2923 // A vector of matcher describers, one for each element matcher. 2924 // Does not own the describers (and thus can be used only when the 2925 // element matchers are alive). 2926 typedef ::std::vector<const MatcherDescriberInterface*> MatcherDescriberVec; 2927 2928 // Describes this UnorderedElementsAre matcher. 2929 void DescribeToImpl(::std::ostream* os) const; 2930 2931 // Describes the negation of this UnorderedElementsAre matcher. 2932 void DescribeNegationToImpl(::std::ostream* os) const; 2933 2934 bool VerifyMatchMatrix(const ::std::vector<std::string>& element_printouts, 2935 const MatchMatrix& matrix, 2936 MatchResultListener* listener) const; 2937 2938 bool FindPairing(const MatchMatrix& matrix, 2939 MatchResultListener* listener) const; 2940 2941 MatcherDescriberVec& matcher_describers() { 2942 return matcher_describers_; 2943 } 2944 2945 static Message Elements(size_t n) { 2946 return Message() << n << " element" << (n == 1 ? "" : "s"); 2947 } 2948 2949 UnorderedMatcherRequire::Flags match_flags() const { return match_flags_; } 2950 2951 private: 2952 UnorderedMatcherRequire::Flags match_flags_; 2953 MatcherDescriberVec matcher_describers_; 2954 2955 GTEST_DISALLOW_ASSIGN_(UnorderedElementsAreMatcherImplBase); 2956 }; 2957 2958 // Implements UnorderedElementsAre, UnorderedElementsAreArray, IsSubsetOf, and 2959 // IsSupersetOf. 2960 template <typename Container> 2961 class UnorderedElementsAreMatcherImpl 2962 : public MatcherInterface<Container>, 2963 public UnorderedElementsAreMatcherImplBase { 2964 public: 2965 typedef GTEST_REMOVE_REFERENCE_AND_CONST_(Container) RawContainer; 2966 typedef internal::StlContainerView<RawContainer> View; 2967 typedef typename View::type StlContainer; 2968 typedef typename View::const_reference StlContainerReference; 2969 typedef decltype(std::begin( 2970 std::declval<StlContainerReference>())) StlContainerConstIterator; 2971 typedef typename std::remove_reference< 2972 decltype(*std::declval<StlContainerConstIterator &>())>::type Element; 2973 2974 template <typename InputIter> 2975 UnorderedElementsAreMatcherImpl(UnorderedMatcherRequire::Flags matcher_flags, 2976 InputIter first, InputIter last) 2977 : UnorderedElementsAreMatcherImplBase(matcher_flags) { 2978 for (; first != last; ++first) { 2979 matchers_.push_back(MatcherCast<const Element&>(*first)); 2980 matcher_describers().push_back(matchers_.back().GetDescriber()); 2981 } 2982 } 2983 2984 // Describes what this matcher does. 2985 void DescribeTo(::std::ostream* os) const override { 2986 return UnorderedElementsAreMatcherImplBase::DescribeToImpl(os); 2987 } 2988 2989 // Describes what the negation of this matcher does. 2990 void DescribeNegationTo(::std::ostream* os) const override { 2991 return UnorderedElementsAreMatcherImplBase::DescribeNegationToImpl(os); 2992 } 2993 2994 bool MatchAndExplain(Container container, 2995 MatchResultListener* listener) const override { 2996 StlContainerReference stl_container = View::ConstReference(container); 2997 ::std::vector<std::string> element_printouts; 2998 MatchMatrix matrix = 2999 AnalyzeElements(stl_container.begin(), stl_container.end(), 3000 &element_printouts, listener); 3001 3002 if (matrix.LhsSize() == 0 && matrix.RhsSize() == 0) { 3003 return true; 3004 } 3005 3006 if (match_flags() == UnorderedMatcherRequire::ExactMatch) { 3007 if (matrix.LhsSize() != matrix.RhsSize()) { 3008 // The element count doesn't match. If the container is empty, 3009 // there's no need to explain anything as Google Mock already 3010 // prints the empty container. Otherwise we just need to show 3011 // how many elements there actually are. 3012 if (matrix.LhsSize() != 0 && listener->IsInterested()) { 3013 *listener << "which has " << Elements(matrix.LhsSize()); 3014 } 3015 return false; 3016 } 3017 } 3018 3019 return VerifyMatchMatrix(element_printouts, matrix, listener) && 3020 FindPairing(matrix, listener); 3021 } 3022 3023 private: 3024 template <typename ElementIter> 3025 MatchMatrix AnalyzeElements(ElementIter elem_first, ElementIter elem_last, 3026 ::std::vector<std::string>* element_printouts, 3027 MatchResultListener* listener) const { 3028 element_printouts->clear(); 3029 ::std::vector<char> did_match; 3030 size_t num_elements = 0; 3031 for (; elem_first != elem_last; ++num_elements, ++elem_first) { 3032 if (listener->IsInterested()) { 3033 element_printouts->push_back(PrintToString(*elem_first)); 3034 } 3035 for (size_t irhs = 0; irhs != matchers_.size(); ++irhs) { 3036 did_match.push_back(Matches(matchers_[irhs])(*elem_first)); 3037 } 3038 } 3039 3040 MatchMatrix matrix(num_elements, matchers_.size()); 3041 ::std::vector<char>::const_iterator did_match_iter = did_match.begin(); 3042 for (size_t ilhs = 0; ilhs != num_elements; ++ilhs) { 3043 for (size_t irhs = 0; irhs != matchers_.size(); ++irhs) { 3044 matrix.SetEdge(ilhs, irhs, *did_match_iter++ != 0); 3045 } 3046 } 3047 return matrix; 3048 } 3049 3050 ::std::vector<Matcher<const Element&> > matchers_; 3051 3052 GTEST_DISALLOW_ASSIGN_(UnorderedElementsAreMatcherImpl); 3053 }; 3054 3055 // Functor for use in TransformTuple. 3056 // Performs MatcherCast<Target> on an input argument of any type. 3057 template <typename Target> 3058 struct CastAndAppendTransform { 3059 template <typename Arg> 3060 Matcher<Target> operator()(const Arg& a) const { 3061 return MatcherCast<Target>(a); 3062 } 3063 }; 3064 3065 // Implements UnorderedElementsAre. 3066 template <typename MatcherTuple> 3067 class UnorderedElementsAreMatcher { 3068 public: 3069 explicit UnorderedElementsAreMatcher(const MatcherTuple& args) 3070 : matchers_(args) {} 3071 3072 template <typename Container> 3073 operator Matcher<Container>() const { 3074 typedef GTEST_REMOVE_REFERENCE_AND_CONST_(Container) RawContainer; 3075 typedef internal::StlContainerView<RawContainer> View; 3076 typedef typename View::const_reference StlContainerReference; 3077 typedef decltype(std::begin( 3078 std::declval<StlContainerReference>())) StlContainerConstIterator; 3079 typedef typename std::remove_reference< 3080 decltype(*std::declval<StlContainerConstIterator &>())>::type Element; 3081 typedef ::std::vector<Matcher<const Element&> > MatcherVec; 3082 MatcherVec matchers; 3083 matchers.reserve(::std::tuple_size<MatcherTuple>::value); 3084 TransformTupleValues(CastAndAppendTransform<const Element&>(), matchers_, 3085 ::std::back_inserter(matchers)); 3086 return Matcher<Container>( 3087 new UnorderedElementsAreMatcherImpl<const Container&>( 3088 UnorderedMatcherRequire::ExactMatch, matchers.begin(), 3089 matchers.end())); 3090 } 3091 3092 private: 3093 const MatcherTuple matchers_; 3094 GTEST_DISALLOW_ASSIGN_(UnorderedElementsAreMatcher); 3095 }; 3096 3097 // Implements ElementsAre. 3098 template <typename MatcherTuple> 3099 class ElementsAreMatcher { 3100 public: 3101 explicit ElementsAreMatcher(const MatcherTuple& args) : matchers_(args) {} 3102 3103 template <typename Container> 3104 operator Matcher<Container>() const { 3105 GTEST_COMPILE_ASSERT_( 3106 !IsHashTable<GTEST_REMOVE_REFERENCE_AND_CONST_(Container)>::value || 3107 ::std::tuple_size<MatcherTuple>::value < 2, 3108 use_UnorderedElementsAre_with_hash_tables); 3109 3110 typedef GTEST_REMOVE_REFERENCE_AND_CONST_(Container) RawContainer; 3111 typedef internal::StlContainerView<RawContainer> View; 3112 typedef typename View::const_reference StlContainerReference; 3113 typedef decltype(std::begin( 3114 std::declval<StlContainerReference>())) StlContainerConstIterator; 3115 typedef typename std::remove_reference< 3116 decltype(*std::declval<StlContainerConstIterator &>())>::type Element; 3117 typedef ::std::vector<Matcher<const Element&> > MatcherVec; 3118 MatcherVec matchers; 3119 matchers.reserve(::std::tuple_size<MatcherTuple>::value); 3120 TransformTupleValues(CastAndAppendTransform<const Element&>(), matchers_, 3121 ::std::back_inserter(matchers)); 3122 return Matcher<Container>(new ElementsAreMatcherImpl<const Container&>( 3123 matchers.begin(), matchers.end())); 3124 } 3125 3126 private: 3127 const MatcherTuple matchers_; 3128 GTEST_DISALLOW_ASSIGN_(ElementsAreMatcher); 3129 }; 3130 3131 // Implements UnorderedElementsAreArray(), IsSubsetOf(), and IsSupersetOf(). 3132 template <typename T> 3133 class UnorderedElementsAreArrayMatcher { 3134 public: 3135 template <typename Iter> 3136 UnorderedElementsAreArrayMatcher(UnorderedMatcherRequire::Flags match_flags, 3137 Iter first, Iter last) 3138 : match_flags_(match_flags), matchers_(first, last) {} 3139 3140 template <typename Container> 3141 operator Matcher<Container>() const { 3142 return Matcher<Container>( 3143 new UnorderedElementsAreMatcherImpl<const Container&>( 3144 match_flags_, matchers_.begin(), matchers_.end())); 3145 } 3146 3147 private: 3148 UnorderedMatcherRequire::Flags match_flags_; 3149 ::std::vector<T> matchers_; 3150 3151 GTEST_DISALLOW_ASSIGN_(UnorderedElementsAreArrayMatcher); 3152 }; 3153 3154 // Implements ElementsAreArray(). 3155 template <typename T> 3156 class ElementsAreArrayMatcher { 3157 public: 3158 template <typename Iter> 3159 ElementsAreArrayMatcher(Iter first, Iter last) : matchers_(first, last) {} 3160 3161 template <typename Container> 3162 operator Matcher<Container>() const { 3163 GTEST_COMPILE_ASSERT_( 3164 !IsHashTable<GTEST_REMOVE_REFERENCE_AND_CONST_(Container)>::value, 3165 use_UnorderedElementsAreArray_with_hash_tables); 3166 3167 return Matcher<Container>(new ElementsAreMatcherImpl<const Container&>( 3168 matchers_.begin(), matchers_.end())); 3169 } 3170 3171 private: 3172 const ::std::vector<T> matchers_; 3173 3174 GTEST_DISALLOW_ASSIGN_(ElementsAreArrayMatcher); 3175 }; 3176 3177 // Given a 2-tuple matcher tm of type Tuple2Matcher and a value second 3178 // of type Second, BoundSecondMatcher<Tuple2Matcher, Second>(tm, 3179 // second) is a polymorphic matcher that matches a value x if and only if 3180 // tm matches tuple (x, second). Useful for implementing 3181 // UnorderedPointwise() in terms of UnorderedElementsAreArray(). 3182 // 3183 // BoundSecondMatcher is copyable and assignable, as we need to put 3184 // instances of this class in a vector when implementing 3185 // UnorderedPointwise(). 3186 template <typename Tuple2Matcher, typename Second> 3187 class BoundSecondMatcher { 3188 public: 3189 BoundSecondMatcher(const Tuple2Matcher& tm, const Second& second) 3190 : tuple2_matcher_(tm), second_value_(second) {} 3191 3192 template <typename T> 3193 operator Matcher<T>() const { 3194 return MakeMatcher(new Impl<T>(tuple2_matcher_, second_value_)); 3195 } 3196 3197 // We have to define this for UnorderedPointwise() to compile in 3198 // C++98 mode, as it puts BoundSecondMatcher instances in a vector, 3199 // which requires the elements to be assignable in C++98. The 3200 // compiler cannot generate the operator= for us, as Tuple2Matcher 3201 // and Second may not be assignable. 3202 // 3203 // However, this should never be called, so the implementation just 3204 // need to assert. 3205 void operator=(const BoundSecondMatcher& /*rhs*/) { 3206 GTEST_LOG_(FATAL) << "BoundSecondMatcher should never be assigned."; 3207 } 3208 3209 private: 3210 template <typename T> 3211 class Impl : public MatcherInterface<T> { 3212 public: 3213 typedef ::std::tuple<T, Second> ArgTuple; 3214 3215 Impl(const Tuple2Matcher& tm, const Second& second) 3216 : mono_tuple2_matcher_(SafeMatcherCast<const ArgTuple&>(tm)), 3217 second_value_(second) {} 3218 3219 void DescribeTo(::std::ostream* os) const override { 3220 *os << "and "; 3221 UniversalPrint(second_value_, os); 3222 *os << " "; 3223 mono_tuple2_matcher_.DescribeTo(os); 3224 } 3225 3226 bool MatchAndExplain(T x, MatchResultListener* listener) const override { 3227 return mono_tuple2_matcher_.MatchAndExplain(ArgTuple(x, second_value_), 3228 listener); 3229 } 3230 3231 private: 3232 const Matcher<const ArgTuple&> mono_tuple2_matcher_; 3233 const Second second_value_; 3234 3235 GTEST_DISALLOW_ASSIGN_(Impl); 3236 }; 3237 3238 const Tuple2Matcher tuple2_matcher_; 3239 const Second second_value_; 3240 }; 3241 3242 // Given a 2-tuple matcher tm and a value second, 3243 // MatcherBindSecond(tm, second) returns a matcher that matches a 3244 // value x if and only if tm matches tuple (x, second). Useful for 3245 // implementing UnorderedPointwise() in terms of UnorderedElementsAreArray(). 3246 template <typename Tuple2Matcher, typename Second> 3247 BoundSecondMatcher<Tuple2Matcher, Second> MatcherBindSecond( 3248 const Tuple2Matcher& tm, const Second& second) { 3249 return BoundSecondMatcher<Tuple2Matcher, Second>(tm, second); 3250 } 3251 3252 // Returns the description for a matcher defined using the MATCHER*() 3253 // macro where the user-supplied description string is "", if 3254 // 'negation' is false; otherwise returns the description of the 3255 // negation of the matcher. 'param_values' contains a list of strings 3256 // that are the print-out of the matcher's parameters. 3257 GTEST_API_ std::string FormatMatcherDescription(bool negation, 3258 const char* matcher_name, 3259 const Strings& param_values); 3260 3261 // Implements a matcher that checks the value of a optional<> type variable. 3262 template <typename ValueMatcher> 3263 class OptionalMatcher { 3264 public: 3265 explicit OptionalMatcher(const ValueMatcher& value_matcher) 3266 : value_matcher_(value_matcher) {} 3267 3268 template <typename Optional> 3269 operator Matcher<Optional>() const { 3270 return Matcher<Optional>(new Impl<const Optional&>(value_matcher_)); 3271 } 3272 3273 template <typename Optional> 3274 class Impl : public MatcherInterface<Optional> { 3275 public: 3276 typedef GTEST_REMOVE_REFERENCE_AND_CONST_(Optional) OptionalView; 3277 typedef typename OptionalView::value_type ValueType; 3278 explicit Impl(const ValueMatcher& value_matcher) 3279 : value_matcher_(MatcherCast<ValueType>(value_matcher)) {} 3280 3281 void DescribeTo(::std::ostream* os) const override { 3282 *os << "value "; 3283 value_matcher_.DescribeTo(os); 3284 } 3285 3286 void DescribeNegationTo(::std::ostream* os) const override { 3287 *os << "value "; 3288 value_matcher_.DescribeNegationTo(os); 3289 } 3290 3291 bool MatchAndExplain(Optional optional, 3292 MatchResultListener* listener) const override { 3293 if (!optional) { 3294 *listener << "which is not engaged"; 3295 return false; 3296 } 3297 const ValueType& value = *optional; 3298 StringMatchResultListener value_listener; 3299 const bool match = value_matcher_.MatchAndExplain(value, &value_listener); 3300 *listener << "whose value " << PrintToString(value) 3301 << (match ? " matches" : " doesn't match"); 3302 PrintIfNotEmpty(value_listener.str(), listener->stream()); 3303 return match; 3304 } 3305 3306 private: 3307 const Matcher<ValueType> value_matcher_; 3308 GTEST_DISALLOW_ASSIGN_(Impl); 3309 }; 3310 3311 private: 3312 const ValueMatcher value_matcher_; 3313 GTEST_DISALLOW_ASSIGN_(OptionalMatcher); 3314 }; 3315 3316 namespace variant_matcher { 3317 // Overloads to allow VariantMatcher to do proper ADL lookup. 3318 template <typename T> 3319 void holds_alternative() {} 3320 template <typename T> 3321 void get() {} 3322 3323 // Implements a matcher that checks the value of a variant<> type variable. 3324 template <typename T> 3325 class VariantMatcher { 3326 public: 3327 explicit VariantMatcher(::testing::Matcher<const T&> matcher) 3328 : matcher_(std::move(matcher)) {} 3329 3330 template <typename Variant> 3331 bool MatchAndExplain(const Variant& value, 3332 ::testing::MatchResultListener* listener) const { 3333 using std::get; 3334 if (!listener->IsInterested()) { 3335 return holds_alternative<T>(value) && matcher_.Matches(get<T>(value)); 3336 } 3337 3338 if (!holds_alternative<T>(value)) { 3339 *listener << "whose value is not of type '" << GetTypeName() << "'"; 3340 return false; 3341 } 3342 3343 const T& elem = get<T>(value); 3344 StringMatchResultListener elem_listener; 3345 const bool match = matcher_.MatchAndExplain(elem, &elem_listener); 3346 *listener << "whose value " << PrintToString(elem) 3347 << (match ? " matches" : " doesn't match"); 3348 PrintIfNotEmpty(elem_listener.str(), listener->stream()); 3349 return match; 3350 } 3351 3352 void DescribeTo(std::ostream* os) const { 3353 *os << "is a variant<> with value of type '" << GetTypeName() 3354 << "' and the value "; 3355 matcher_.DescribeTo(os); 3356 } 3357 3358 void DescribeNegationTo(std::ostream* os) const { 3359 *os << "is a variant<> with value of type other than '" << GetTypeName() 3360 << "' or the value "; 3361 matcher_.DescribeNegationTo(os); 3362 } 3363 3364 private: 3365 static std::string GetTypeName() { 3366 #if GTEST_HAS_RTTI 3367 GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_( 3368 return internal::GetTypeName<T>()); 3369 #endif 3370 return "the element type"; 3371 } 3372 3373 const ::testing::Matcher<const T&> matcher_; 3374 }; 3375 3376 } // namespace variant_matcher 3377 3378 namespace any_cast_matcher { 3379 3380 // Overloads to allow AnyCastMatcher to do proper ADL lookup. 3381 template <typename T> 3382 void any_cast() {} 3383 3384 // Implements a matcher that any_casts the value. 3385 template <typename T> 3386 class AnyCastMatcher { 3387 public: 3388 explicit AnyCastMatcher(const ::testing::Matcher<const T&>& matcher) 3389 : matcher_(matcher) {} 3390 3391 template <typename AnyType> 3392 bool MatchAndExplain(const AnyType& value, 3393 ::testing::MatchResultListener* listener) const { 3394 if (!listener->IsInterested()) { 3395 const T* ptr = any_cast<T>(&value); 3396 return ptr != nullptr && matcher_.Matches(*ptr); 3397 } 3398 3399 const T* elem = any_cast<T>(&value); 3400 if (elem == nullptr) { 3401 *listener << "whose value is not of type '" << GetTypeName() << "'"; 3402 return false; 3403 } 3404 3405 StringMatchResultListener elem_listener; 3406 const bool match = matcher_.MatchAndExplain(*elem, &elem_listener); 3407 *listener << "whose value " << PrintToString(*elem) 3408 << (match ? " matches" : " doesn't match"); 3409 PrintIfNotEmpty(elem_listener.str(), listener->stream()); 3410 return match; 3411 } 3412 3413 void DescribeTo(std::ostream* os) const { 3414 *os << "is an 'any' type with value of type '" << GetTypeName() 3415 << "' and the value "; 3416 matcher_.DescribeTo(os); 3417 } 3418 3419 void DescribeNegationTo(std::ostream* os) const { 3420 *os << "is an 'any' type with value of type other than '" << GetTypeName() 3421 << "' or the value "; 3422 matcher_.DescribeNegationTo(os); 3423 } 3424 3425 private: 3426 static std::string GetTypeName() { 3427 #if GTEST_HAS_RTTI 3428 GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_( 3429 return internal::GetTypeName<T>()); 3430 #endif 3431 return "the element type"; 3432 } 3433 3434 const ::testing::Matcher<const T&> matcher_; 3435 }; 3436 3437 } // namespace any_cast_matcher 3438 3439 // Implements the Args() matcher. 3440 template <class ArgsTuple, size_t... k> 3441 class ArgsMatcherImpl : public MatcherInterface<ArgsTuple> { 3442 public: 3443 using RawArgsTuple = typename std::decay<ArgsTuple>::type; 3444 using SelectedArgs = 3445 std::tuple<typename std::tuple_element<k, RawArgsTuple>::type...>; 3446 using MonomorphicInnerMatcher = Matcher<const SelectedArgs&>; 3447 3448 template <typename InnerMatcher> 3449 explicit ArgsMatcherImpl(const InnerMatcher& inner_matcher) 3450 : inner_matcher_(SafeMatcherCast<const SelectedArgs&>(inner_matcher)) {} 3451 3452 bool MatchAndExplain(ArgsTuple args, 3453 MatchResultListener* listener) const override { 3454 // Workaround spurious C4100 on MSVC<=15.7 when k is empty. 3455 (void)args; 3456 const SelectedArgs& selected_args = 3457 std::forward_as_tuple(std::get<k>(args)...); 3458 if (!listener->IsInterested()) return inner_matcher_.Matches(selected_args); 3459 3460 PrintIndices(listener->stream()); 3461 *listener << "are " << PrintToString(selected_args); 3462 3463 StringMatchResultListener inner_listener; 3464 const bool match = 3465 inner_matcher_.MatchAndExplain(selected_args, &inner_listener); 3466 PrintIfNotEmpty(inner_listener.str(), listener->stream()); 3467 return match; 3468 } 3469 3470 void DescribeTo(::std::ostream* os) const override { 3471 *os << "are a tuple "; 3472 PrintIndices(os); 3473 inner_matcher_.DescribeTo(os); 3474 } 3475 3476 void DescribeNegationTo(::std::ostream* os) const override { 3477 *os << "are a tuple "; 3478 PrintIndices(os); 3479 inner_matcher_.DescribeNegationTo(os); 3480 } 3481 3482 private: 3483 // Prints the indices of the selected fields. 3484 static void PrintIndices(::std::ostream* os) { 3485 *os << "whose fields ("; 3486 const char* sep = ""; 3487 // Workaround spurious C4189 on MSVC<=15.7 when k is empty. 3488 (void)sep; 3489 const char* dummy[] = {"", (*os << sep << "#" << k, sep = ", ")...}; 3490 (void)dummy; 3491 *os << ") "; 3492 } 3493 3494 MonomorphicInnerMatcher inner_matcher_; 3495 }; 3496 3497 template <class InnerMatcher, size_t... k> 3498 class ArgsMatcher { 3499 public: 3500 explicit ArgsMatcher(InnerMatcher inner_matcher) 3501 : inner_matcher_(std::move(inner_matcher)) {} 3502 3503 template <typename ArgsTuple> 3504 operator Matcher<ArgsTuple>() const { // NOLINT 3505 return MakeMatcher(new ArgsMatcherImpl<ArgsTuple, k...>(inner_matcher_)); 3506 } 3507 3508 private: 3509 InnerMatcher inner_matcher_; 3510 }; 3511 3512 } // namespace internal 3513 3514 // ElementsAreArray(iterator_first, iterator_last) 3515 // ElementsAreArray(pointer, count) 3516 // ElementsAreArray(array) 3517 // ElementsAreArray(container) 3518 // ElementsAreArray({ e1, e2, ..., en }) 3519 // 3520 // The ElementsAreArray() functions are like ElementsAre(...), except 3521 // that they are given a homogeneous sequence rather than taking each 3522 // element as a function argument. The sequence can be specified as an 3523 // array, a pointer and count, a vector, an initializer list, or an 3524 // STL iterator range. In each of these cases, the underlying sequence 3525 // can be either a sequence of values or a sequence of matchers. 3526 // 3527 // All forms of ElementsAreArray() make a copy of the input matcher sequence. 3528 3529 template <typename Iter> 3530 inline internal::ElementsAreArrayMatcher< 3531 typename ::std::iterator_traits<Iter>::value_type> 3532 ElementsAreArray(Iter first, Iter last) { 3533 typedef typename ::std::iterator_traits<Iter>::value_type T; 3534 return internal::ElementsAreArrayMatcher<T>(first, last); 3535 } 3536 3537 template <typename T> 3538 inline internal::ElementsAreArrayMatcher<T> ElementsAreArray( 3539 const T* pointer, size_t count) { 3540 return ElementsAreArray(pointer, pointer + count); 3541 } 3542 3543 template <typename T, size_t N> 3544 inline internal::ElementsAreArrayMatcher<T> ElementsAreArray( 3545 const T (&array)[N]) { 3546 return ElementsAreArray(array, N); 3547 } 3548 3549 template <typename Container> 3550 inline internal::ElementsAreArrayMatcher<typename Container::value_type> 3551 ElementsAreArray(const Container& container) { 3552 return ElementsAreArray(container.begin(), container.end()); 3553 } 3554 3555 template <typename T> 3556 inline internal::ElementsAreArrayMatcher<T> 3557 ElementsAreArray(::std::initializer_list<T> xs) { 3558 return ElementsAreArray(xs.begin(), xs.end()); 3559 } 3560 3561 // UnorderedElementsAreArray(iterator_first, iterator_last) 3562 // UnorderedElementsAreArray(pointer, count) 3563 // UnorderedElementsAreArray(array) 3564 // UnorderedElementsAreArray(container) 3565 // UnorderedElementsAreArray({ e1, e2, ..., en }) 3566 // 3567 // UnorderedElementsAreArray() verifies that a bijective mapping onto a 3568 // collection of matchers exists. 3569 // 3570 // The matchers can be specified as an array, a pointer and count, a container, 3571 // an initializer list, or an STL iterator range. In each of these cases, the 3572 // underlying matchers can be either values or matchers. 3573 3574 template <typename Iter> 3575 inline internal::UnorderedElementsAreArrayMatcher< 3576 typename ::std::iterator_traits<Iter>::value_type> 3577 UnorderedElementsAreArray(Iter first, Iter last) { 3578 typedef typename ::std::iterator_traits<Iter>::value_type T; 3579 return internal::UnorderedElementsAreArrayMatcher<T>( 3580 internal::UnorderedMatcherRequire::ExactMatch, first, last); 3581 } 3582 3583 template <typename T> 3584 inline internal::UnorderedElementsAreArrayMatcher<T> 3585 UnorderedElementsAreArray(const T* pointer, size_t count) { 3586 return UnorderedElementsAreArray(pointer, pointer + count); 3587 } 3588 3589 template <typename T, size_t N> 3590 inline internal::UnorderedElementsAreArrayMatcher<T> 3591 UnorderedElementsAreArray(const T (&array)[N]) { 3592 return UnorderedElementsAreArray(array, N); 3593 } 3594 3595 template <typename Container> 3596 inline internal::UnorderedElementsAreArrayMatcher< 3597 typename Container::value_type> 3598 UnorderedElementsAreArray(const Container& container) { 3599 return UnorderedElementsAreArray(container.begin(), container.end()); 3600 } 3601 3602 template <typename T> 3603 inline internal::UnorderedElementsAreArrayMatcher<T> 3604 UnorderedElementsAreArray(::std::initializer_list<T> xs) { 3605 return UnorderedElementsAreArray(xs.begin(), xs.end()); 3606 } 3607 3608 // _ is a matcher that matches anything of any type. 3609 // 3610 // This definition is fine as: 3611 // 3612 // 1. The C++ standard permits using the name _ in a namespace that 3613 // is not the global namespace or ::std. 3614 // 2. The AnythingMatcher class has no data member or constructor, 3615 // so it's OK to create global variables of this type. 3616 // 3. c-style has approved of using _ in this case. 3617 const internal::AnythingMatcher _ = {}; 3618 // Creates a matcher that matches any value of the given type T. 3619 template <typename T> 3620 inline Matcher<T> A() { 3621 return Matcher<T>(new internal::AnyMatcherImpl<T>()); 3622 } 3623 3624 // Creates a matcher that matches any value of the given type T. 3625 template <typename T> 3626 inline Matcher<T> An() { return A<T>(); } 3627 3628 template <typename T, typename M> 3629 Matcher<T> internal::MatcherCastImpl<T, M>::CastImpl( 3630 const M& value, std::false_type /* convertible_to_matcher */, 3631 std::false_type /* convertible_to_T */) { 3632 return Eq(value); 3633 } 3634 3635 // Creates a polymorphic matcher that matches any NULL pointer. 3636 inline PolymorphicMatcher<internal::IsNullMatcher > IsNull() { 3637 return MakePolymorphicMatcher(internal::IsNullMatcher()); 3638 } 3639 3640 // Creates a polymorphic matcher that matches any non-NULL pointer. 3641 // This is convenient as Not(NULL) doesn't compile (the compiler 3642 // thinks that that expression is comparing a pointer with an integer). 3643 inline PolymorphicMatcher<internal::NotNullMatcher > NotNull() { 3644 return MakePolymorphicMatcher(internal::NotNullMatcher()); 3645 } 3646 3647 // Creates a polymorphic matcher that matches any argument that 3648 // references variable x. 3649 template <typename T> 3650 inline internal::RefMatcher<T&> Ref(T& x) { // NOLINT 3651 return internal::RefMatcher<T&>(x); 3652 } 3653 3654 // Creates a matcher that matches any double argument approximately 3655 // equal to rhs, where two NANs are considered unequal. 3656 inline internal::FloatingEqMatcher<double> DoubleEq(double rhs) { 3657 return internal::FloatingEqMatcher<double>(rhs, false); 3658 } 3659 3660 // Creates a matcher that matches any double argument approximately 3661 // equal to rhs, including NaN values when rhs is NaN. 3662 inline internal::FloatingEqMatcher<double> NanSensitiveDoubleEq(double rhs) { 3663 return internal::FloatingEqMatcher<double>(rhs, true); 3664 } 3665 3666 // Creates a matcher that matches any double argument approximately equal to 3667 // rhs, up to the specified max absolute error bound, where two NANs are 3668 // considered unequal. The max absolute error bound must be non-negative. 3669 inline internal::FloatingEqMatcher<double> DoubleNear( 3670 double rhs, double max_abs_error) { 3671 return internal::FloatingEqMatcher<double>(rhs, false, max_abs_error); 3672 } 3673 3674 // Creates a matcher that matches any double argument approximately equal to 3675 // rhs, up to the specified max absolute error bound, including NaN values when 3676 // rhs is NaN. The max absolute error bound must be non-negative. 3677 inline internal::FloatingEqMatcher<double> NanSensitiveDoubleNear( 3678 double rhs, double max_abs_error) { 3679 return internal::FloatingEqMatcher<double>(rhs, true, max_abs_error); 3680 } 3681 3682 // Creates a matcher that matches any float argument approximately 3683 // equal to rhs, where two NANs are considered unequal. 3684 inline internal::FloatingEqMatcher<float> FloatEq(float rhs) { 3685 return internal::FloatingEqMatcher<float>(rhs, false); 3686 } 3687 3688 // Creates a matcher that matches any float argument approximately 3689 // equal to rhs, including NaN values when rhs is NaN. 3690 inline internal::FloatingEqMatcher<float> NanSensitiveFloatEq(float rhs) { 3691 return internal::FloatingEqMatcher<float>(rhs, true); 3692 } 3693 3694 // Creates a matcher that matches any float argument approximately equal to 3695 // rhs, up to the specified max absolute error bound, where two NANs are 3696 // considered unequal. The max absolute error bound must be non-negative. 3697 inline internal::FloatingEqMatcher<float> FloatNear( 3698 float rhs, float max_abs_error) { 3699 return internal::FloatingEqMatcher<float>(rhs, false, max_abs_error); 3700 } 3701 3702 // Creates a matcher that matches any float argument approximately equal to 3703 // rhs, up to the specified max absolute error bound, including NaN values when 3704 // rhs is NaN. The max absolute error bound must be non-negative. 3705 inline internal::FloatingEqMatcher<float> NanSensitiveFloatNear( 3706 float rhs, float max_abs_error) { 3707 return internal::FloatingEqMatcher<float>(rhs, true, max_abs_error); 3708 } 3709 3710 // Creates a matcher that matches a pointer (raw or smart) that points 3711 // to a value that matches inner_matcher. 3712 template <typename InnerMatcher> 3713 inline internal::PointeeMatcher<InnerMatcher> Pointee( 3714 const InnerMatcher& inner_matcher) { 3715 return internal::PointeeMatcher<InnerMatcher>(inner_matcher); 3716 } 3717 3718 #if GTEST_HAS_RTTI 3719 // Creates a matcher that matches a pointer or reference that matches 3720 // inner_matcher when dynamic_cast<To> is applied. 3721 // The result of dynamic_cast<To> is forwarded to the inner matcher. 3722 // If To is a pointer and the cast fails, the inner matcher will receive NULL. 3723 // If To is a reference and the cast fails, this matcher returns false 3724 // immediately. 3725 template <typename To> 3726 inline PolymorphicMatcher<internal::WhenDynamicCastToMatcher<To> > 3727 WhenDynamicCastTo(const Matcher<To>& inner_matcher) { 3728 return MakePolymorphicMatcher( 3729 internal::WhenDynamicCastToMatcher<To>(inner_matcher)); 3730 } 3731 #endif // GTEST_HAS_RTTI 3732 3733 // Creates a matcher that matches an object whose given field matches 3734 // 'matcher'. For example, 3735 // Field(&Foo::number, Ge(5)) 3736 // matches a Foo object x if and only if x.number >= 5. 3737 template <typename Class, typename FieldType, typename FieldMatcher> 3738 inline PolymorphicMatcher< 3739 internal::FieldMatcher<Class, FieldType> > Field( 3740 FieldType Class::*field, const FieldMatcher& matcher) { 3741 return MakePolymorphicMatcher( 3742 internal::FieldMatcher<Class, FieldType>( 3743 field, MatcherCast<const FieldType&>(matcher))); 3744 // The call to MatcherCast() is required for supporting inner 3745 // matchers of compatible types. For example, it allows 3746 // Field(&Foo::bar, m) 3747 // to compile where bar is an int32 and m is a matcher for int64. 3748 } 3749 3750 // Same as Field() but also takes the name of the field to provide better error 3751 // messages. 3752 template <typename Class, typename FieldType, typename FieldMatcher> 3753 inline PolymorphicMatcher<internal::FieldMatcher<Class, FieldType> > Field( 3754 const std::string& field_name, FieldType Class::*field, 3755 const FieldMatcher& matcher) { 3756 return MakePolymorphicMatcher(internal::FieldMatcher<Class, FieldType>( 3757 field_name, field, MatcherCast<const FieldType&>(matcher))); 3758 } 3759 3760 // Creates a matcher that matches an object whose given property 3761 // matches 'matcher'. For example, 3762 // Property(&Foo::str, StartsWith("hi")) 3763 // matches a Foo object x if and only if x.str() starts with "hi". 3764 template <typename Class, typename PropertyType, typename PropertyMatcher> 3765 inline PolymorphicMatcher<internal::PropertyMatcher< 3766 Class, PropertyType, PropertyType (Class::*)() const> > 3767 Property(PropertyType (Class::*property)() const, 3768 const PropertyMatcher& matcher) { 3769 return MakePolymorphicMatcher( 3770 internal::PropertyMatcher<Class, PropertyType, 3771 PropertyType (Class::*)() const>( 3772 property, MatcherCast<const PropertyType&>(matcher))); 3773 // The call to MatcherCast() is required for supporting inner 3774 // matchers of compatible types. For example, it allows 3775 // Property(&Foo::bar, m) 3776 // to compile where bar() returns an int32 and m is a matcher for int64. 3777 } 3778 3779 // Same as Property() above, but also takes the name of the property to provide 3780 // better error messages. 3781 template <typename Class, typename PropertyType, typename PropertyMatcher> 3782 inline PolymorphicMatcher<internal::PropertyMatcher< 3783 Class, PropertyType, PropertyType (Class::*)() const> > 3784 Property(const std::string& property_name, 3785 PropertyType (Class::*property)() const, 3786 const PropertyMatcher& matcher) { 3787 return MakePolymorphicMatcher( 3788 internal::PropertyMatcher<Class, PropertyType, 3789 PropertyType (Class::*)() const>( 3790 property_name, property, MatcherCast<const PropertyType&>(matcher))); 3791 } 3792 3793 // The same as above but for reference-qualified member functions. 3794 template <typename Class, typename PropertyType, typename PropertyMatcher> 3795 inline PolymorphicMatcher<internal::PropertyMatcher< 3796 Class, PropertyType, PropertyType (Class::*)() const &> > 3797 Property(PropertyType (Class::*property)() const &, 3798 const PropertyMatcher& matcher) { 3799 return MakePolymorphicMatcher( 3800 internal::PropertyMatcher<Class, PropertyType, 3801 PropertyType (Class::*)() const&>( 3802 property, MatcherCast<const PropertyType&>(matcher))); 3803 } 3804 3805 // Three-argument form for reference-qualified member functions. 3806 template <typename Class, typename PropertyType, typename PropertyMatcher> 3807 inline PolymorphicMatcher<internal::PropertyMatcher< 3808 Class, PropertyType, PropertyType (Class::*)() const &> > 3809 Property(const std::string& property_name, 3810 PropertyType (Class::*property)() const &, 3811 const PropertyMatcher& matcher) { 3812 return MakePolymorphicMatcher( 3813 internal::PropertyMatcher<Class, PropertyType, 3814 PropertyType (Class::*)() const&>( 3815 property_name, property, MatcherCast<const PropertyType&>(matcher))); 3816 } 3817 3818 // Creates a matcher that matches an object if and only if the result of 3819 // applying a callable to x matches 'matcher'. For example, 3820 // ResultOf(f, StartsWith("hi")) 3821 // matches a Foo object x if and only if f(x) starts with "hi". 3822 // `callable` parameter can be a function, function pointer, or a functor. It is 3823 // required to keep no state affecting the results of the calls on it and make 3824 // no assumptions about how many calls will be made. Any state it keeps must be 3825 // protected from the concurrent access. 3826 template <typename Callable, typename InnerMatcher> 3827 internal::ResultOfMatcher<Callable, InnerMatcher> ResultOf( 3828 Callable callable, InnerMatcher matcher) { 3829 return internal::ResultOfMatcher<Callable, InnerMatcher>( 3830 std::move(callable), std::move(matcher)); 3831 } 3832 3833 // String matchers. 3834 3835 // Matches a string equal to str. 3836 inline PolymorphicMatcher<internal::StrEqualityMatcher<std::string> > StrEq( 3837 const std::string& str) { 3838 return MakePolymorphicMatcher( 3839 internal::StrEqualityMatcher<std::string>(str, true, true)); 3840 } 3841 3842 // Matches a string not equal to str. 3843 inline PolymorphicMatcher<internal::StrEqualityMatcher<std::string> > StrNe( 3844 const std::string& str) { 3845 return MakePolymorphicMatcher( 3846 internal::StrEqualityMatcher<std::string>(str, false, true)); 3847 } 3848 3849 // Matches a string equal to str, ignoring case. 3850 inline PolymorphicMatcher<internal::StrEqualityMatcher<std::string> > StrCaseEq( 3851 const std::string& str) { 3852 return MakePolymorphicMatcher( 3853 internal::StrEqualityMatcher<std::string>(str, true, false)); 3854 } 3855 3856 // Matches a string not equal to str, ignoring case. 3857 inline PolymorphicMatcher<internal::StrEqualityMatcher<std::string> > StrCaseNe( 3858 const std::string& str) { 3859 return MakePolymorphicMatcher( 3860 internal::StrEqualityMatcher<std::string>(str, false, false)); 3861 } 3862 3863 // Creates a matcher that matches any string, std::string, or C string 3864 // that contains the given substring. 3865 inline PolymorphicMatcher<internal::HasSubstrMatcher<std::string> > HasSubstr( 3866 const std::string& substring) { 3867 return MakePolymorphicMatcher( 3868 internal::HasSubstrMatcher<std::string>(substring)); 3869 } 3870 3871 // Matches a string that starts with 'prefix' (case-sensitive). 3872 inline PolymorphicMatcher<internal::StartsWithMatcher<std::string> > StartsWith( 3873 const std::string& prefix) { 3874 return MakePolymorphicMatcher( 3875 internal::StartsWithMatcher<std::string>(prefix)); 3876 } 3877 3878 // Matches a string that ends with 'suffix' (case-sensitive). 3879 inline PolymorphicMatcher<internal::EndsWithMatcher<std::string> > EndsWith( 3880 const std::string& suffix) { 3881 return MakePolymorphicMatcher(internal::EndsWithMatcher<std::string>(suffix)); 3882 } 3883 3884 #if GTEST_HAS_STD_WSTRING 3885 // Wide string matchers. 3886 3887 // Matches a string equal to str. 3888 inline PolymorphicMatcher<internal::StrEqualityMatcher<std::wstring> > StrEq( 3889 const std::wstring& str) { 3890 return MakePolymorphicMatcher( 3891 internal::StrEqualityMatcher<std::wstring>(str, true, true)); 3892 } 3893 3894 // Matches a string not equal to str. 3895 inline PolymorphicMatcher<internal::StrEqualityMatcher<std::wstring> > StrNe( 3896 const std::wstring& str) { 3897 return MakePolymorphicMatcher( 3898 internal::StrEqualityMatcher<std::wstring>(str, false, true)); 3899 } 3900 3901 // Matches a string equal to str, ignoring case. 3902 inline PolymorphicMatcher<internal::StrEqualityMatcher<std::wstring> > 3903 StrCaseEq(const std::wstring& str) { 3904 return MakePolymorphicMatcher( 3905 internal::StrEqualityMatcher<std::wstring>(str, true, false)); 3906 } 3907 3908 // Matches a string not equal to str, ignoring case. 3909 inline PolymorphicMatcher<internal::StrEqualityMatcher<std::wstring> > 3910 StrCaseNe(const std::wstring& str) { 3911 return MakePolymorphicMatcher( 3912 internal::StrEqualityMatcher<std::wstring>(str, false, false)); 3913 } 3914 3915 // Creates a matcher that matches any ::wstring, std::wstring, or C wide string 3916 // that contains the given substring. 3917 inline PolymorphicMatcher<internal::HasSubstrMatcher<std::wstring> > HasSubstr( 3918 const std::wstring& substring) { 3919 return MakePolymorphicMatcher( 3920 internal::HasSubstrMatcher<std::wstring>(substring)); 3921 } 3922 3923 // Matches a string that starts with 'prefix' (case-sensitive). 3924 inline PolymorphicMatcher<internal::StartsWithMatcher<std::wstring> > 3925 StartsWith(const std::wstring& prefix) { 3926 return MakePolymorphicMatcher( 3927 internal::StartsWithMatcher<std::wstring>(prefix)); 3928 } 3929 3930 // Matches a string that ends with 'suffix' (case-sensitive). 3931 inline PolymorphicMatcher<internal::EndsWithMatcher<std::wstring> > EndsWith( 3932 const std::wstring& suffix) { 3933 return MakePolymorphicMatcher( 3934 internal::EndsWithMatcher<std::wstring>(suffix)); 3935 } 3936 3937 #endif // GTEST_HAS_STD_WSTRING 3938 3939 // Creates a polymorphic matcher that matches a 2-tuple where the 3940 // first field == the second field. 3941 inline internal::Eq2Matcher Eq() { return internal::Eq2Matcher(); } 3942 3943 // Creates a polymorphic matcher that matches a 2-tuple where the 3944 // first field >= the second field. 3945 inline internal::Ge2Matcher Ge() { return internal::Ge2Matcher(); } 3946 3947 // Creates a polymorphic matcher that matches a 2-tuple where the 3948 // first field > the second field. 3949 inline internal::Gt2Matcher Gt() { return internal::Gt2Matcher(); } 3950 3951 // Creates a polymorphic matcher that matches a 2-tuple where the 3952 // first field <= the second field. 3953 inline internal::Le2Matcher Le() { return internal::Le2Matcher(); } 3954 3955 // Creates a polymorphic matcher that matches a 2-tuple where the 3956 // first field < the second field. 3957 inline internal::Lt2Matcher Lt() { return internal::Lt2Matcher(); } 3958 3959 // Creates a polymorphic matcher that matches a 2-tuple where the 3960 // first field != the second field. 3961 inline internal::Ne2Matcher Ne() { return internal::Ne2Matcher(); } 3962 3963 // Creates a polymorphic matcher that matches a 2-tuple where 3964 // FloatEq(first field) matches the second field. 3965 inline internal::FloatingEq2Matcher<float> FloatEq() { 3966 return internal::FloatingEq2Matcher<float>(); 3967 } 3968 3969 // Creates a polymorphic matcher that matches a 2-tuple where 3970 // DoubleEq(first field) matches the second field. 3971 inline internal::FloatingEq2Matcher<double> DoubleEq() { 3972 return internal::FloatingEq2Matcher<double>(); 3973 } 3974 3975 // Creates a polymorphic matcher that matches a 2-tuple where 3976 // FloatEq(first field) matches the second field with NaN equality. 3977 inline internal::FloatingEq2Matcher<float> NanSensitiveFloatEq() { 3978 return internal::FloatingEq2Matcher<float>(true); 3979 } 3980 3981 // Creates a polymorphic matcher that matches a 2-tuple where 3982 // DoubleEq(first field) matches the second field with NaN equality. 3983 inline internal::FloatingEq2Matcher<double> NanSensitiveDoubleEq() { 3984 return internal::FloatingEq2Matcher<double>(true); 3985 } 3986 3987 // Creates a polymorphic matcher that matches a 2-tuple where 3988 // FloatNear(first field, max_abs_error) matches the second field. 3989 inline internal::FloatingEq2Matcher<float> FloatNear(float max_abs_error) { 3990 return internal::FloatingEq2Matcher<float>(max_abs_error); 3991 } 3992 3993 // Creates a polymorphic matcher that matches a 2-tuple where 3994 // DoubleNear(first field, max_abs_error) matches the second field. 3995 inline internal::FloatingEq2Matcher<double> DoubleNear(double max_abs_error) { 3996 return internal::FloatingEq2Matcher<double>(max_abs_error); 3997 } 3998 3999 // Creates a polymorphic matcher that matches a 2-tuple where 4000 // FloatNear(first field, max_abs_error) matches the second field with NaN 4001 // equality. 4002 inline internal::FloatingEq2Matcher<float> NanSensitiveFloatNear( 4003 float max_abs_error) { 4004 return internal::FloatingEq2Matcher<float>(max_abs_error, true); 4005 } 4006 4007 // Creates a polymorphic matcher that matches a 2-tuple where 4008 // DoubleNear(first field, max_abs_error) matches the second field with NaN 4009 // equality. 4010 inline internal::FloatingEq2Matcher<double> NanSensitiveDoubleNear( 4011 double max_abs_error) { 4012 return internal::FloatingEq2Matcher<double>(max_abs_error, true); 4013 } 4014 4015 // Creates a matcher that matches any value of type T that m doesn't 4016 // match. 4017 template <typename InnerMatcher> 4018 inline internal::NotMatcher<InnerMatcher> Not(InnerMatcher m) { 4019 return internal::NotMatcher<InnerMatcher>(m); 4020 } 4021 4022 // Returns a matcher that matches anything that satisfies the given 4023 // predicate. The predicate can be any unary function or functor 4024 // whose return type can be implicitly converted to bool. 4025 template <typename Predicate> 4026 inline PolymorphicMatcher<internal::TrulyMatcher<Predicate> > 4027 Truly(Predicate pred) { 4028 return MakePolymorphicMatcher(internal::TrulyMatcher<Predicate>(pred)); 4029 } 4030 4031 // Returns a matcher that matches the container size. The container must 4032 // support both size() and size_type which all STL-like containers provide. 4033 // Note that the parameter 'size' can be a value of type size_type as well as 4034 // matcher. For instance: 4035 // EXPECT_THAT(container, SizeIs(2)); // Checks container has 2 elements. 4036 // EXPECT_THAT(container, SizeIs(Le(2)); // Checks container has at most 2. 4037 template <typename SizeMatcher> 4038 inline internal::SizeIsMatcher<SizeMatcher> 4039 SizeIs(const SizeMatcher& size_matcher) { 4040 return internal::SizeIsMatcher<SizeMatcher>(size_matcher); 4041 } 4042 4043 // Returns a matcher that matches the distance between the container's begin() 4044 // iterator and its end() iterator, i.e. the size of the container. This matcher 4045 // can be used instead of SizeIs with containers such as std::forward_list which 4046 // do not implement size(). The container must provide const_iterator (with 4047 // valid iterator_traits), begin() and end(). 4048 template <typename DistanceMatcher> 4049 inline internal::BeginEndDistanceIsMatcher<DistanceMatcher> 4050 BeginEndDistanceIs(const DistanceMatcher& distance_matcher) { 4051 return internal::BeginEndDistanceIsMatcher<DistanceMatcher>(distance_matcher); 4052 } 4053 4054 // Returns a matcher that matches an equal container. 4055 // This matcher behaves like Eq(), but in the event of mismatch lists the 4056 // values that are included in one container but not the other. (Duplicate 4057 // values and order differences are not explained.) 4058 template <typename Container> 4059 inline PolymorphicMatcher<internal::ContainerEqMatcher< 4060 typename std::remove_const<Container>::type>> 4061 ContainerEq(const Container& rhs) { 4062 // This following line is for working around a bug in MSVC 8.0, 4063 // which causes Container to be a const type sometimes. 4064 typedef typename std::remove_const<Container>::type RawContainer; 4065 return MakePolymorphicMatcher( 4066 internal::ContainerEqMatcher<RawContainer>(rhs)); 4067 } 4068 4069 // Returns a matcher that matches a container that, when sorted using 4070 // the given comparator, matches container_matcher. 4071 template <typename Comparator, typename ContainerMatcher> 4072 inline internal::WhenSortedByMatcher<Comparator, ContainerMatcher> 4073 WhenSortedBy(const Comparator& comparator, 4074 const ContainerMatcher& container_matcher) { 4075 return internal::WhenSortedByMatcher<Comparator, ContainerMatcher>( 4076 comparator, container_matcher); 4077 } 4078 4079 // Returns a matcher that matches a container that, when sorted using 4080 // the < operator, matches container_matcher. 4081 template <typename ContainerMatcher> 4082 inline internal::WhenSortedByMatcher<internal::LessComparator, ContainerMatcher> 4083 WhenSorted(const ContainerMatcher& container_matcher) { 4084 return 4085 internal::WhenSortedByMatcher<internal::LessComparator, ContainerMatcher>( 4086 internal::LessComparator(), container_matcher); 4087 } 4088 4089 // Matches an STL-style container or a native array that contains the 4090 // same number of elements as in rhs, where its i-th element and rhs's 4091 // i-th element (as a pair) satisfy the given pair matcher, for all i. 4092 // TupleMatcher must be able to be safely cast to Matcher<std::tuple<const 4093 // T1&, const T2&> >, where T1 and T2 are the types of elements in the 4094 // LHS container and the RHS container respectively. 4095 template <typename TupleMatcher, typename Container> 4096 inline internal::PointwiseMatcher<TupleMatcher, 4097 typename std::remove_const<Container>::type> 4098 Pointwise(const TupleMatcher& tuple_matcher, const Container& rhs) { 4099 // This following line is for working around a bug in MSVC 8.0, 4100 // which causes Container to be a const type sometimes (e.g. when 4101 // rhs is a const int[]).. 4102 typedef typename std::remove_const<Container>::type RawContainer; 4103 return internal::PointwiseMatcher<TupleMatcher, RawContainer>( 4104 tuple_matcher, rhs); 4105 } 4106 4107 4108 // Supports the Pointwise(m, {a, b, c}) syntax. 4109 template <typename TupleMatcher, typename T> 4110 inline internal::PointwiseMatcher<TupleMatcher, std::vector<T> > Pointwise( 4111 const TupleMatcher& tuple_matcher, std::initializer_list<T> rhs) { 4112 return Pointwise(tuple_matcher, std::vector<T>(rhs)); 4113 } 4114 4115 4116 // UnorderedPointwise(pair_matcher, rhs) matches an STL-style 4117 // container or a native array that contains the same number of 4118 // elements as in rhs, where in some permutation of the container, its 4119 // i-th element and rhs's i-th element (as a pair) satisfy the given 4120 // pair matcher, for all i. Tuple2Matcher must be able to be safely 4121 // cast to Matcher<std::tuple<const T1&, const T2&> >, where T1 and T2 are 4122 // the types of elements in the LHS container and the RHS container 4123 // respectively. 4124 // 4125 // This is like Pointwise(pair_matcher, rhs), except that the element 4126 // order doesn't matter. 4127 template <typename Tuple2Matcher, typename RhsContainer> 4128 inline internal::UnorderedElementsAreArrayMatcher< 4129 typename internal::BoundSecondMatcher< 4130 Tuple2Matcher, 4131 typename internal::StlContainerView< 4132 typename std::remove_const<RhsContainer>::type>::type::value_type>> 4133 UnorderedPointwise(const Tuple2Matcher& tuple2_matcher, 4134 const RhsContainer& rhs_container) { 4135 // This following line is for working around a bug in MSVC 8.0, 4136 // which causes RhsContainer to be a const type sometimes (e.g. when 4137 // rhs_container is a const int[]). 4138 typedef typename std::remove_const<RhsContainer>::type RawRhsContainer; 4139 4140 // RhsView allows the same code to handle RhsContainer being a 4141 // STL-style container and it being a native C-style array. 4142 typedef typename internal::StlContainerView<RawRhsContainer> RhsView; 4143 typedef typename RhsView::type RhsStlContainer; 4144 typedef typename RhsStlContainer::value_type Second; 4145 const RhsStlContainer& rhs_stl_container = 4146 RhsView::ConstReference(rhs_container); 4147 4148 // Create a matcher for each element in rhs_container. 4149 ::std::vector<internal::BoundSecondMatcher<Tuple2Matcher, Second> > matchers; 4150 for (typename RhsStlContainer::const_iterator it = rhs_stl_container.begin(); 4151 it != rhs_stl_container.end(); ++it) { 4152 matchers.push_back( 4153 internal::MatcherBindSecond(tuple2_matcher, *it)); 4154 } 4155 4156 // Delegate the work to UnorderedElementsAreArray(). 4157 return UnorderedElementsAreArray(matchers); 4158 } 4159 4160 4161 // Supports the UnorderedPointwise(m, {a, b, c}) syntax. 4162 template <typename Tuple2Matcher, typename T> 4163 inline internal::UnorderedElementsAreArrayMatcher< 4164 typename internal::BoundSecondMatcher<Tuple2Matcher, T> > 4165 UnorderedPointwise(const Tuple2Matcher& tuple2_matcher, 4166 std::initializer_list<T> rhs) { 4167 return UnorderedPointwise(tuple2_matcher, std::vector<T>(rhs)); 4168 } 4169 4170 4171 // Matches an STL-style container or a native array that contains at 4172 // least one element matching the given value or matcher. 4173 // 4174 // Examples: 4175 // ::std::set<int> page_ids; 4176 // page_ids.insert(3); 4177 // page_ids.insert(1); 4178 // EXPECT_THAT(page_ids, Contains(1)); 4179 // EXPECT_THAT(page_ids, Contains(Gt(2))); 4180 // EXPECT_THAT(page_ids, Not(Contains(4))); 4181 // 4182 // ::std::map<int, size_t> page_lengths; 4183 // page_lengths[1] = 100; 4184 // EXPECT_THAT(page_lengths, 4185 // Contains(::std::pair<const int, size_t>(1, 100))); 4186 // 4187 // const char* user_ids[] = { "joe", "mike", "tom" }; 4188 // EXPECT_THAT(user_ids, Contains(Eq(::std::string("tom")))); 4189 template <typename M> 4190 inline internal::ContainsMatcher<M> Contains(M matcher) { 4191 return internal::ContainsMatcher<M>(matcher); 4192 } 4193 4194 // IsSupersetOf(iterator_first, iterator_last) 4195 // IsSupersetOf(pointer, count) 4196 // IsSupersetOf(array) 4197 // IsSupersetOf(container) 4198 // IsSupersetOf({e1, e2, ..., en}) 4199 // 4200 // IsSupersetOf() verifies that a surjective partial mapping onto a collection 4201 // of matchers exists. In other words, a container matches 4202 // IsSupersetOf({e1, ..., en}) if and only if there is a permutation 4203 // {y1, ..., yn} of some of the container's elements where y1 matches e1, 4204 // ..., and yn matches en. Obviously, the size of the container must be >= n 4205 // in order to have a match. Examples: 4206 // 4207 // - {1, 2, 3} matches IsSupersetOf({Ge(3), Ne(0)}), as 3 matches Ge(3) and 4208 // 1 matches Ne(0). 4209 // - {1, 2} doesn't match IsSupersetOf({Eq(1), Lt(2)}), even though 1 matches 4210 // both Eq(1) and Lt(2). The reason is that different matchers must be used 4211 // for elements in different slots of the container. 4212 // - {1, 1, 2} matches IsSupersetOf({Eq(1), Lt(2)}), as (the first) 1 matches 4213 // Eq(1) and (the second) 1 matches Lt(2). 4214 // - {1, 2, 3} matches IsSupersetOf(Gt(1), Gt(1)), as 2 matches (the first) 4215 // Gt(1) and 3 matches (the second) Gt(1). 4216 // 4217 // The matchers can be specified as an array, a pointer and count, a container, 4218 // an initializer list, or an STL iterator range. In each of these cases, the 4219 // underlying matchers can be either values or matchers. 4220 4221 template <typename Iter> 4222 inline internal::UnorderedElementsAreArrayMatcher< 4223 typename ::std::iterator_traits<Iter>::value_type> 4224 IsSupersetOf(Iter first, Iter last) { 4225 typedef typename ::std::iterator_traits<Iter>::value_type T; 4226 return internal::UnorderedElementsAreArrayMatcher<T>( 4227 internal::UnorderedMatcherRequire::Superset, first, last); 4228 } 4229 4230 template <typename T> 4231 inline internal::UnorderedElementsAreArrayMatcher<T> IsSupersetOf( 4232 const T* pointer, size_t count) { 4233 return IsSupersetOf(pointer, pointer + count); 4234 } 4235 4236 template <typename T, size_t N> 4237 inline internal::UnorderedElementsAreArrayMatcher<T> IsSupersetOf( 4238 const T (&array)[N]) { 4239 return IsSupersetOf(array, N); 4240 } 4241 4242 template <typename Container> 4243 inline internal::UnorderedElementsAreArrayMatcher< 4244 typename Container::value_type> 4245 IsSupersetOf(const Container& container) { 4246 return IsSupersetOf(container.begin(), container.end()); 4247 } 4248 4249 template <typename T> 4250 inline internal::UnorderedElementsAreArrayMatcher<T> IsSupersetOf( 4251 ::std::initializer_list<T> xs) { 4252 return IsSupersetOf(xs.begin(), xs.end()); 4253 } 4254 4255 // IsSubsetOf(iterator_first, iterator_last) 4256 // IsSubsetOf(pointer, count) 4257 // IsSubsetOf(array) 4258 // IsSubsetOf(container) 4259 // IsSubsetOf({e1, e2, ..., en}) 4260 // 4261 // IsSubsetOf() verifies that an injective mapping onto a collection of matchers 4262 // exists. In other words, a container matches IsSubsetOf({e1, ..., en}) if and 4263 // only if there is a subset of matchers {m1, ..., mk} which would match the 4264 // container using UnorderedElementsAre. Obviously, the size of the container 4265 // must be <= n in order to have a match. Examples: 4266 // 4267 // - {1} matches IsSubsetOf({Gt(0), Lt(0)}), as 1 matches Gt(0). 4268 // - {1, -1} matches IsSubsetOf({Lt(0), Gt(0)}), as 1 matches Gt(0) and -1 4269 // matches Lt(0). 4270 // - {1, 2} doesn't matches IsSubsetOf({Gt(0), Lt(0)}), even though 1 and 2 both 4271 // match Gt(0). The reason is that different matchers must be used for 4272 // elements in different slots of the container. 4273 // 4274 // The matchers can be specified as an array, a pointer and count, a container, 4275 // an initializer list, or an STL iterator range. In each of these cases, the 4276 // underlying matchers can be either values or matchers. 4277 4278 template <typename Iter> 4279 inline internal::UnorderedElementsAreArrayMatcher< 4280 typename ::std::iterator_traits<Iter>::value_type> 4281 IsSubsetOf(Iter first, Iter last) { 4282 typedef typename ::std::iterator_traits<Iter>::value_type T; 4283 return internal::UnorderedElementsAreArrayMatcher<T>( 4284 internal::UnorderedMatcherRequire::Subset, first, last); 4285 } 4286 4287 template <typename T> 4288 inline internal::UnorderedElementsAreArrayMatcher<T> IsSubsetOf( 4289 const T* pointer, size_t count) { 4290 return IsSubsetOf(pointer, pointer + count); 4291 } 4292 4293 template <typename T, size_t N> 4294 inline internal::UnorderedElementsAreArrayMatcher<T> IsSubsetOf( 4295 const T (&array)[N]) { 4296 return IsSubsetOf(array, N); 4297 } 4298 4299 template <typename Container> 4300 inline internal::UnorderedElementsAreArrayMatcher< 4301 typename Container::value_type> 4302 IsSubsetOf(const Container& container) { 4303 return IsSubsetOf(container.begin(), container.end()); 4304 } 4305 4306 template <typename T> 4307 inline internal::UnorderedElementsAreArrayMatcher<T> IsSubsetOf( 4308 ::std::initializer_list<T> xs) { 4309 return IsSubsetOf(xs.begin(), xs.end()); 4310 } 4311 4312 // Matches an STL-style container or a native array that contains only 4313 // elements matching the given value or matcher. 4314 // 4315 // Each(m) is semantically equivalent to Not(Contains(Not(m))). Only 4316 // the messages are different. 4317 // 4318 // Examples: 4319 // ::std::set<int> page_ids; 4320 // // Each(m) matches an empty container, regardless of what m is. 4321 // EXPECT_THAT(page_ids, Each(Eq(1))); 4322 // EXPECT_THAT(page_ids, Each(Eq(77))); 4323 // 4324 // page_ids.insert(3); 4325 // EXPECT_THAT(page_ids, Each(Gt(0))); 4326 // EXPECT_THAT(page_ids, Not(Each(Gt(4)))); 4327 // page_ids.insert(1); 4328 // EXPECT_THAT(page_ids, Not(Each(Lt(2)))); 4329 // 4330 // ::std::map<int, size_t> page_lengths; 4331 // page_lengths[1] = 100; 4332 // page_lengths[2] = 200; 4333 // page_lengths[3] = 300; 4334 // EXPECT_THAT(page_lengths, Not(Each(Pair(1, 100)))); 4335 // EXPECT_THAT(page_lengths, Each(Key(Le(3)))); 4336 // 4337 // const char* user_ids[] = { "joe", "mike", "tom" }; 4338 // EXPECT_THAT(user_ids, Not(Each(Eq(::std::string("tom"))))); 4339 template <typename M> 4340 inline internal::EachMatcher<M> Each(M matcher) { 4341 return internal::EachMatcher<M>(matcher); 4342 } 4343 4344 // Key(inner_matcher) matches an std::pair whose 'first' field matches 4345 // inner_matcher. For example, Contains(Key(Ge(5))) can be used to match an 4346 // std::map that contains at least one element whose key is >= 5. 4347 template <typename M> 4348 inline internal::KeyMatcher<M> Key(M inner_matcher) { 4349 return internal::KeyMatcher<M>(inner_matcher); 4350 } 4351 4352 // Pair(first_matcher, second_matcher) matches a std::pair whose 'first' field 4353 // matches first_matcher and whose 'second' field matches second_matcher. For 4354 // example, EXPECT_THAT(map_type, ElementsAre(Pair(Ge(5), "foo"))) can be used 4355 // to match a std::map<int, string> that contains exactly one element whose key 4356 // is >= 5 and whose value equals "foo". 4357 template <typename FirstMatcher, typename SecondMatcher> 4358 inline internal::PairMatcher<FirstMatcher, SecondMatcher> 4359 Pair(FirstMatcher first_matcher, SecondMatcher second_matcher) { 4360 return internal::PairMatcher<FirstMatcher, SecondMatcher>( 4361 first_matcher, second_matcher); 4362 } 4363 4364 // Returns a predicate that is satisfied by anything that matches the 4365 // given matcher. 4366 template <typename M> 4367 inline internal::MatcherAsPredicate<M> Matches(M matcher) { 4368 return internal::MatcherAsPredicate<M>(matcher); 4369 } 4370 4371 // Returns true if and only if the value matches the matcher. 4372 template <typename T, typename M> 4373 inline bool Value(const T& value, M matcher) { 4374 return testing::Matches(matcher)(value); 4375 } 4376 4377 // Matches the value against the given matcher and explains the match 4378 // result to listener. 4379 template <typename T, typename M> 4380 inline bool ExplainMatchResult( 4381 M matcher, const T& value, MatchResultListener* listener) { 4382 return SafeMatcherCast<const T&>(matcher).MatchAndExplain(value, listener); 4383 } 4384 4385 // Returns a string representation of the given matcher. Useful for description 4386 // strings of matchers defined using MATCHER_P* macros that accept matchers as 4387 // their arguments. For example: 4388 // 4389 // MATCHER_P(XAndYThat, matcher, 4390 // "X that " + DescribeMatcher<int>(matcher, negation) + 4391 // " and Y that " + DescribeMatcher<double>(matcher, negation)) { 4392 // return ExplainMatchResult(matcher, arg.x(), result_listener) && 4393 // ExplainMatchResult(matcher, arg.y(), result_listener); 4394 // } 4395 template <typename T, typename M> 4396 std::string DescribeMatcher(const M& matcher, bool negation = false) { 4397 ::std::stringstream ss; 4398 Matcher<T> monomorphic_matcher = SafeMatcherCast<T>(matcher); 4399 if (negation) { 4400 monomorphic_matcher.DescribeNegationTo(&ss); 4401 } else { 4402 monomorphic_matcher.DescribeTo(&ss); 4403 } 4404 return ss.str(); 4405 } 4406 4407 template <typename... Args> 4408 internal::ElementsAreMatcher< 4409 std::tuple<typename std::decay<const Args&>::type...>> 4410 ElementsAre(const Args&... matchers) { 4411 return internal::ElementsAreMatcher< 4412 std::tuple<typename std::decay<const Args&>::type...>>( 4413 std::make_tuple(matchers...)); 4414 } 4415 4416 template <typename... Args> 4417 internal::UnorderedElementsAreMatcher< 4418 std::tuple<typename std::decay<const Args&>::type...>> 4419 UnorderedElementsAre(const Args&... matchers) { 4420 return internal::UnorderedElementsAreMatcher< 4421 std::tuple<typename std::decay<const Args&>::type...>>( 4422 std::make_tuple(matchers...)); 4423 } 4424 4425 // Define variadic matcher versions. 4426 template <typename... Args> 4427 internal::AllOfMatcher<typename std::decay<const Args&>::type...> AllOf( 4428 const Args&... matchers) { 4429 return internal::AllOfMatcher<typename std::decay<const Args&>::type...>( 4430 matchers...); 4431 } 4432 4433 template <typename... Args> 4434 internal::AnyOfMatcher<typename std::decay<const Args&>::type...> AnyOf( 4435 const Args&... matchers) { 4436 return internal::AnyOfMatcher<typename std::decay<const Args&>::type...>( 4437 matchers...); 4438 } 4439 4440 // AnyOfArray(array) 4441 // AnyOfArray(pointer, count) 4442 // AnyOfArray(container) 4443 // AnyOfArray({ e1, e2, ..., en }) 4444 // AnyOfArray(iterator_first, iterator_last) 4445 // 4446 // AnyOfArray() verifies whether a given value matches any member of a 4447 // collection of matchers. 4448 // 4449 // AllOfArray(array) 4450 // AllOfArray(pointer, count) 4451 // AllOfArray(container) 4452 // AllOfArray({ e1, e2, ..., en }) 4453 // AllOfArray(iterator_first, iterator_last) 4454 // 4455 // AllOfArray() verifies whether a given value matches all members of a 4456 // collection of matchers. 4457 // 4458 // The matchers can be specified as an array, a pointer and count, a container, 4459 // an initializer list, or an STL iterator range. In each of these cases, the 4460 // underlying matchers can be either values or matchers. 4461 4462 template <typename Iter> 4463 inline internal::AnyOfArrayMatcher< 4464 typename ::std::iterator_traits<Iter>::value_type> 4465 AnyOfArray(Iter first, Iter last) { 4466 return internal::AnyOfArrayMatcher< 4467 typename ::std::iterator_traits<Iter>::value_type>(first, last); 4468 } 4469 4470 template <typename Iter> 4471 inline internal::AllOfArrayMatcher< 4472 typename ::std::iterator_traits<Iter>::value_type> 4473 AllOfArray(Iter first, Iter last) { 4474 return internal::AllOfArrayMatcher< 4475 typename ::std::iterator_traits<Iter>::value_type>(first, last); 4476 } 4477 4478 template <typename T> 4479 inline internal::AnyOfArrayMatcher<T> AnyOfArray(const T* ptr, size_t count) { 4480 return AnyOfArray(ptr, ptr + count); 4481 } 4482 4483 template <typename T> 4484 inline internal::AllOfArrayMatcher<T> AllOfArray(const T* ptr, size_t count) { 4485 return AllOfArray(ptr, ptr + count); 4486 } 4487 4488 template <typename T, size_t N> 4489 inline internal::AnyOfArrayMatcher<T> AnyOfArray(const T (&array)[N]) { 4490 return AnyOfArray(array, N); 4491 } 4492 4493 template <typename T, size_t N> 4494 inline internal::AllOfArrayMatcher<T> AllOfArray(const T (&array)[N]) { 4495 return AllOfArray(array, N); 4496 } 4497 4498 template <typename Container> 4499 inline internal::AnyOfArrayMatcher<typename Container::value_type> AnyOfArray( 4500 const Container& container) { 4501 return AnyOfArray(container.begin(), container.end()); 4502 } 4503 4504 template <typename Container> 4505 inline internal::AllOfArrayMatcher<typename Container::value_type> AllOfArray( 4506 const Container& container) { 4507 return AllOfArray(container.begin(), container.end()); 4508 } 4509 4510 template <typename T> 4511 inline internal::AnyOfArrayMatcher<T> AnyOfArray( 4512 ::std::initializer_list<T> xs) { 4513 return AnyOfArray(xs.begin(), xs.end()); 4514 } 4515 4516 template <typename T> 4517 inline internal::AllOfArrayMatcher<T> AllOfArray( 4518 ::std::initializer_list<T> xs) { 4519 return AllOfArray(xs.begin(), xs.end()); 4520 } 4521 4522 // Args<N1, N2, ..., Nk>(a_matcher) matches a tuple if the selected 4523 // fields of it matches a_matcher. C++ doesn't support default 4524 // arguments for function templates, so we have to overload it. 4525 template <size_t... k, typename InnerMatcher> 4526 internal::ArgsMatcher<typename std::decay<InnerMatcher>::type, k...> Args( 4527 InnerMatcher&& matcher) { 4528 return internal::ArgsMatcher<typename std::decay<InnerMatcher>::type, k...>( 4529 std::forward<InnerMatcher>(matcher)); 4530 } 4531 4532 // AllArgs(m) is a synonym of m. This is useful in 4533 // 4534 // EXPECT_CALL(foo, Bar(_, _)).With(AllArgs(Eq())); 4535 // 4536 // which is easier to read than 4537 // 4538 // EXPECT_CALL(foo, Bar(_, _)).With(Eq()); 4539 template <typename InnerMatcher> 4540 inline InnerMatcher AllArgs(const InnerMatcher& matcher) { return matcher; } 4541 4542 // Returns a matcher that matches the value of an optional<> type variable. 4543 // The matcher implementation only uses '!arg' and requires that the optional<> 4544 // type has a 'value_type' member type and that '*arg' is of type 'value_type' 4545 // and is printable using 'PrintToString'. It is compatible with 4546 // std::optional/std::experimental::optional. 4547 // Note that to compare an optional type variable against nullopt you should 4548 // use Eq(nullopt) and not Optional(Eq(nullopt)). The latter implies that the 4549 // optional value contains an optional itself. 4550 template <typename ValueMatcher> 4551 inline internal::OptionalMatcher<ValueMatcher> Optional( 4552 const ValueMatcher& value_matcher) { 4553 return internal::OptionalMatcher<ValueMatcher>(value_matcher); 4554 } 4555 4556 // Returns a matcher that matches the value of a absl::any type variable. 4557 template <typename T> 4558 PolymorphicMatcher<internal::any_cast_matcher::AnyCastMatcher<T> > AnyWith( 4559 const Matcher<const T&>& matcher) { 4560 return MakePolymorphicMatcher( 4561 internal::any_cast_matcher::AnyCastMatcher<T>(matcher)); 4562 } 4563 4564 // Returns a matcher that matches the value of a variant<> type variable. 4565 // The matcher implementation uses ADL to find the holds_alternative and get 4566 // functions. 4567 // It is compatible with std::variant. 4568 template <typename T> 4569 PolymorphicMatcher<internal::variant_matcher::VariantMatcher<T> > VariantWith( 4570 const Matcher<const T&>& matcher) { 4571 return MakePolymorphicMatcher( 4572 internal::variant_matcher::VariantMatcher<T>(matcher)); 4573 } 4574 4575 // These macros allow using matchers to check values in Google Test 4576 // tests. ASSERT_THAT(value, matcher) and EXPECT_THAT(value, matcher) 4577 // succeed if and only if the value matches the matcher. If the assertion 4578 // fails, the value and the description of the matcher will be printed. 4579 #define ASSERT_THAT(value, matcher) ASSERT_PRED_FORMAT1(\ 4580 ::testing::internal::MakePredicateFormatterFromMatcher(matcher), value) 4581 #define EXPECT_THAT(value, matcher) EXPECT_PRED_FORMAT1(\ 4582 ::testing::internal::MakePredicateFormatterFromMatcher(matcher), value) 4583 4584 } // namespace testing 4585 4586 #ifdef __clang__ 4587 #if __has_warning("-Wdeprecated-copy") 4588 #pragma clang diagnostic pop 4589 #endif 4590 #endif 4591 4592 GTEST_DISABLE_MSC_WARNINGS_POP_() // 4251 5046 4593 4594 // Include any custom callback matchers added by the local installation. 4595 // We must include this header at the end to make sure it can use the 4596 // declarations from this file. 4597 #include "gmock/internal/custom/gmock-matchers.h" 4598 4599 #endif // GMOCK_INCLUDE_GMOCK_GMOCK_MATCHERS_H_ 4600