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