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 tests some commonly used argument matchers. 34 35#include "gmock/gmock-matchers.h" 36#include "gmock/gmock-more-matchers.h" 37 38#include <string.h> 39#include <time.h> 40#include <deque> 41#include <functional> 42#include <iostream> 43#include <iterator> 44#include <limits> 45#include <list> 46#include <map> 47#include <memory> 48#include <set> 49#include <sstream> 50#include <string> 51#include <utility> 52#include <vector> 53#include "gmock/gmock.h" 54#include "gtest/gtest.h" 55#include "gtest/gtest-spi.h" 56 57#if GTEST_HAS_STD_FORWARD_LIST_ 58# include <forward_list> // NOLINT 59#endif 60 61#if GTEST_LANG_CXX11 62# include <type_traits> 63#endif 64 65namespace testing { 66namespace gmock_matchers_test { 67 68using std::greater; 69using std::less; 70using std::list; 71using std::make_pair; 72using std::map; 73using std::multimap; 74using std::multiset; 75using std::ostream; 76using std::pair; 77using std::set; 78using std::stringstream; 79using std::vector; 80using testing::A; 81using testing::AllArgs; 82using testing::AllOf; 83using testing::An; 84using testing::AnyOf; 85using testing::ByRef; 86using testing::ContainsRegex; 87using testing::DoubleEq; 88using testing::DoubleNear; 89using testing::EndsWith; 90using testing::Eq; 91using testing::ExplainMatchResult; 92using testing::Field; 93using testing::FloatEq; 94using testing::FloatNear; 95using testing::Ge; 96using testing::Gt; 97using testing::HasSubstr; 98using testing::IsEmpty; 99using testing::IsNull; 100using testing::Key; 101using testing::Le; 102using testing::Lt; 103using testing::MakeMatcher; 104using testing::MakePolymorphicMatcher; 105using testing::MatchResultListener; 106using testing::Matcher; 107using testing::MatcherCast; 108using testing::MatcherInterface; 109using testing::Matches; 110using testing::MatchesRegex; 111using testing::NanSensitiveDoubleEq; 112using testing::NanSensitiveDoubleNear; 113using testing::NanSensitiveFloatEq; 114using testing::NanSensitiveFloatNear; 115using testing::Ne; 116using testing::Not; 117using testing::NotNull; 118using testing::Pair; 119using testing::Pointee; 120using testing::Pointwise; 121using testing::PolymorphicMatcher; 122using testing::Property; 123using testing::Ref; 124using testing::ResultOf; 125using testing::SizeIs; 126using testing::StartsWith; 127using testing::StrCaseEq; 128using testing::StrCaseNe; 129using testing::StrEq; 130using testing::StrNe; 131using testing::StringMatchResultListener; 132using testing::Truly; 133using testing::TypedEq; 134using testing::UnorderedPointwise; 135using testing::Value; 136using testing::WhenSorted; 137using testing::WhenSortedBy; 138using testing::_; 139using testing::get; 140using testing::internal::DummyMatchResultListener; 141using testing::internal::ElementMatcherPair; 142using testing::internal::ElementMatcherPairs; 143using testing::internal::ExplainMatchFailureTupleTo; 144using testing::internal::FloatingEqMatcher; 145using testing::internal::FormatMatcherDescription; 146using testing::internal::IsReadableTypeName; 147using testing::internal::linked_ptr; 148using testing::internal::MatchMatrix; 149using testing::internal::RE; 150using testing::internal::scoped_ptr; 151using testing::internal::StreamMatchResultListener; 152using testing::internal::Strings; 153using testing::internal::linked_ptr; 154using testing::internal::scoped_ptr; 155using testing::internal::string; 156using testing::make_tuple; 157using testing::tuple; 158 159// For testing ExplainMatchResultTo(). 160class GreaterThanMatcher : public MatcherInterface<int> { 161 public: 162 explicit GreaterThanMatcher(int rhs) : rhs_(rhs) {} 163 164 virtual void DescribeTo(ostream* os) const { 165 *os << "is > " << rhs_; 166 } 167 168 virtual bool MatchAndExplain(int lhs, 169 MatchResultListener* listener) const { 170 const int diff = lhs - rhs_; 171 if (diff > 0) { 172 *listener << "which is " << diff << " more than " << rhs_; 173 } else if (diff == 0) { 174 *listener << "which is the same as " << rhs_; 175 } else { 176 *listener << "which is " << -diff << " less than " << rhs_; 177 } 178 179 return lhs > rhs_; 180 } 181 182 private: 183 int rhs_; 184}; 185 186Matcher<int> GreaterThan(int n) { 187 return MakeMatcher(new GreaterThanMatcher(n)); 188} 189 190std::string OfType(const std::string& type_name) { 191#if GTEST_HAS_RTTI 192 return " (of type " + type_name + ")"; 193#else 194 return ""; 195#endif 196} 197 198// Returns the description of the given matcher. 199template <typename T> 200std::string Describe(const Matcher<T>& m) { 201 return DescribeMatcher<T>(m); 202} 203 204// Returns the description of the negation of the given matcher. 205template <typename T> 206std::string DescribeNegation(const Matcher<T>& m) { 207 return DescribeMatcher<T>(m, true); 208} 209 210// Returns the reason why x matches, or doesn't match, m. 211template <typename MatcherType, typename Value> 212std::string Explain(const MatcherType& m, const Value& x) { 213 StringMatchResultListener listener; 214 ExplainMatchResult(m, x, &listener); 215 return listener.str(); 216} 217 218TEST(MonotonicMatcherTest, IsPrintable) { 219 stringstream ss; 220 ss << GreaterThan(5); 221 EXPECT_EQ("is > 5", ss.str()); 222} 223 224TEST(MatchResultListenerTest, StreamingWorks) { 225 StringMatchResultListener listener; 226 listener << "hi" << 5; 227 EXPECT_EQ("hi5", listener.str()); 228 229 listener.Clear(); 230 EXPECT_EQ("", listener.str()); 231 232 listener << 42; 233 EXPECT_EQ("42", listener.str()); 234 235 // Streaming shouldn't crash when the underlying ostream is NULL. 236 DummyMatchResultListener dummy; 237 dummy << "hi" << 5; 238} 239 240TEST(MatchResultListenerTest, CanAccessUnderlyingStream) { 241 EXPECT_TRUE(DummyMatchResultListener().stream() == NULL); 242 EXPECT_TRUE(StreamMatchResultListener(NULL).stream() == NULL); 243 244 EXPECT_EQ(&std::cout, StreamMatchResultListener(&std::cout).stream()); 245} 246 247TEST(MatchResultListenerTest, IsInterestedWorks) { 248 EXPECT_TRUE(StringMatchResultListener().IsInterested()); 249 EXPECT_TRUE(StreamMatchResultListener(&std::cout).IsInterested()); 250 251 EXPECT_FALSE(DummyMatchResultListener().IsInterested()); 252 EXPECT_FALSE(StreamMatchResultListener(NULL).IsInterested()); 253} 254 255// Makes sure that the MatcherInterface<T> interface doesn't 256// change. 257class EvenMatcherImpl : public MatcherInterface<int> { 258 public: 259 virtual bool MatchAndExplain(int x, 260 MatchResultListener* /* listener */) const { 261 return x % 2 == 0; 262 } 263 264 virtual void DescribeTo(ostream* os) const { 265 *os << "is an even number"; 266 } 267 268 // We deliberately don't define DescribeNegationTo() and 269 // ExplainMatchResultTo() here, to make sure the definition of these 270 // two methods is optional. 271}; 272 273// Makes sure that the MatcherInterface API doesn't change. 274TEST(MatcherInterfaceTest, CanBeImplementedUsingPublishedAPI) { 275 EvenMatcherImpl m; 276} 277 278// Tests implementing a monomorphic matcher using MatchAndExplain(). 279 280class NewEvenMatcherImpl : public MatcherInterface<int> { 281 public: 282 virtual bool MatchAndExplain(int x, MatchResultListener* listener) const { 283 const bool match = x % 2 == 0; 284 // Verifies that we can stream to a listener directly. 285 *listener << "value % " << 2; 286 if (listener->stream() != NULL) { 287 // Verifies that we can stream to a listener's underlying stream 288 // too. 289 *listener->stream() << " == " << (x % 2); 290 } 291 return match; 292 } 293 294 virtual void DescribeTo(ostream* os) const { 295 *os << "is an even number"; 296 } 297}; 298 299TEST(MatcherInterfaceTest, CanBeImplementedUsingNewAPI) { 300 Matcher<int> m = MakeMatcher(new NewEvenMatcherImpl); 301 EXPECT_TRUE(m.Matches(2)); 302 EXPECT_FALSE(m.Matches(3)); 303 EXPECT_EQ("value % 2 == 0", Explain(m, 2)); 304 EXPECT_EQ("value % 2 == 1", Explain(m, 3)); 305} 306 307// Tests default-constructing a matcher. 308TEST(MatcherTest, CanBeDefaultConstructed) { 309 Matcher<double> m; 310} 311 312// Tests that Matcher<T> can be constructed from a MatcherInterface<T>*. 313TEST(MatcherTest, CanBeConstructedFromMatcherInterface) { 314 const MatcherInterface<int>* impl = new EvenMatcherImpl; 315 Matcher<int> m(impl); 316 EXPECT_TRUE(m.Matches(4)); 317 EXPECT_FALSE(m.Matches(5)); 318} 319 320// Tests that value can be used in place of Eq(value). 321TEST(MatcherTest, CanBeImplicitlyConstructedFromValue) { 322 Matcher<int> m1 = 5; 323 EXPECT_TRUE(m1.Matches(5)); 324 EXPECT_FALSE(m1.Matches(6)); 325} 326 327// Tests that NULL can be used in place of Eq(NULL). 328TEST(MatcherTest, CanBeImplicitlyConstructedFromNULL) { 329 Matcher<int*> m1 = NULL; 330 EXPECT_TRUE(m1.Matches(NULL)); 331 int n = 0; 332 EXPECT_FALSE(m1.Matches(&n)); 333} 334 335// Tests that matchers can be constructed from a variable that is not properly 336// defined. This should be illegal, but many users rely on this accidentally. 337struct Undefined { 338 virtual ~Undefined() = 0; 339 static const int kInt = 1; 340}; 341 342TEST(MatcherTest, CanBeConstructedFromUndefinedVariable) { 343 Matcher<int> m1 = Undefined::kInt; 344 EXPECT_TRUE(m1.Matches(1)); 345 EXPECT_FALSE(m1.Matches(2)); 346} 347 348// Test that a matcher parameterized with an abstract class compiles. 349TEST(MatcherTest, CanAcceptAbstractClass) { Matcher<const Undefined&> m = _; } 350 351// Tests that matchers are copyable. 352TEST(MatcherTest, IsCopyable) { 353 // Tests the copy constructor. 354 Matcher<bool> m1 = Eq(false); 355 EXPECT_TRUE(m1.Matches(false)); 356 EXPECT_FALSE(m1.Matches(true)); 357 358 // Tests the assignment operator. 359 m1 = Eq(true); 360 EXPECT_TRUE(m1.Matches(true)); 361 EXPECT_FALSE(m1.Matches(false)); 362} 363 364// Tests that Matcher<T>::DescribeTo() calls 365// MatcherInterface<T>::DescribeTo(). 366TEST(MatcherTest, CanDescribeItself) { 367 EXPECT_EQ("is an even number", 368 Describe(Matcher<int>(new EvenMatcherImpl))); 369} 370 371// Tests Matcher<T>::MatchAndExplain(). 372TEST(MatcherTest, MatchAndExplain) { 373 Matcher<int> m = GreaterThan(0); 374 StringMatchResultListener listener1; 375 EXPECT_TRUE(m.MatchAndExplain(42, &listener1)); 376 EXPECT_EQ("which is 42 more than 0", listener1.str()); 377 378 StringMatchResultListener listener2; 379 EXPECT_FALSE(m.MatchAndExplain(-9, &listener2)); 380 EXPECT_EQ("which is 9 less than 0", listener2.str()); 381} 382 383// Tests that a C-string literal can be implicitly converted to a 384// Matcher<std::string> or Matcher<const std::string&>. 385TEST(StringMatcherTest, CanBeImplicitlyConstructedFromCStringLiteral) { 386 Matcher<std::string> m1 = "hi"; 387 EXPECT_TRUE(m1.Matches("hi")); 388 EXPECT_FALSE(m1.Matches("hello")); 389 390 Matcher<const std::string&> m2 = "hi"; 391 EXPECT_TRUE(m2.Matches("hi")); 392 EXPECT_FALSE(m2.Matches("hello")); 393} 394 395// Tests that a string object can be implicitly converted to a 396// Matcher<std::string> or Matcher<const std::string&>. 397TEST(StringMatcherTest, CanBeImplicitlyConstructedFromString) { 398 Matcher<std::string> m1 = std::string("hi"); 399 EXPECT_TRUE(m1.Matches("hi")); 400 EXPECT_FALSE(m1.Matches("hello")); 401 402 Matcher<const std::string&> m2 = std::string("hi"); 403 EXPECT_TRUE(m2.Matches("hi")); 404 EXPECT_FALSE(m2.Matches("hello")); 405} 406 407#if GTEST_HAS_GLOBAL_STRING 408// Tests that a ::string object can be implicitly converted to a 409// Matcher<std::string> or Matcher<const std::string&>. 410TEST(StringMatcherTest, CanBeImplicitlyConstructedFromGlobalString) { 411 Matcher<std::string> m1 = ::string("hi"); 412 EXPECT_TRUE(m1.Matches("hi")); 413 EXPECT_FALSE(m1.Matches("hello")); 414 415 Matcher<const std::string&> m2 = ::string("hi"); 416 EXPECT_TRUE(m2.Matches("hi")); 417 EXPECT_FALSE(m2.Matches("hello")); 418} 419#endif // GTEST_HAS_GLOBAL_STRING 420 421#if GTEST_HAS_GLOBAL_STRING 422// Tests that a C-string literal can be implicitly converted to a 423// Matcher<::string> or Matcher<const ::string&>. 424TEST(GlobalStringMatcherTest, CanBeImplicitlyConstructedFromCStringLiteral) { 425 Matcher< ::string> m1 = "hi"; 426 EXPECT_TRUE(m1.Matches("hi")); 427 EXPECT_FALSE(m1.Matches("hello")); 428 429 Matcher<const ::string&> m2 = "hi"; 430 EXPECT_TRUE(m2.Matches("hi")); 431 EXPECT_FALSE(m2.Matches("hello")); 432} 433 434// Tests that a std::string object can be implicitly converted to a 435// Matcher<::string> or Matcher<const ::string&>. 436TEST(GlobalStringMatcherTest, CanBeImplicitlyConstructedFromString) { 437 Matcher< ::string> m1 = std::string("hi"); 438 EXPECT_TRUE(m1.Matches("hi")); 439 EXPECT_FALSE(m1.Matches("hello")); 440 441 Matcher<const ::string&> m2 = std::string("hi"); 442 EXPECT_TRUE(m2.Matches("hi")); 443 EXPECT_FALSE(m2.Matches("hello")); 444} 445 446// Tests that a ::string object can be implicitly converted to a 447// Matcher<::string> or Matcher<const ::string&>. 448TEST(GlobalStringMatcherTest, CanBeImplicitlyConstructedFromGlobalString) { 449 Matcher< ::string> m1 = ::string("hi"); 450 EXPECT_TRUE(m1.Matches("hi")); 451 EXPECT_FALSE(m1.Matches("hello")); 452 453 Matcher<const ::string&> m2 = ::string("hi"); 454 EXPECT_TRUE(m2.Matches("hi")); 455 EXPECT_FALSE(m2.Matches("hello")); 456} 457#endif // GTEST_HAS_GLOBAL_STRING 458 459#if GTEST_HAS_ABSL 460// Tests that a C-string literal can be implicitly converted to a 461// Matcher<absl::string_view> or Matcher<const absl::string_view&>. 462TEST(StringViewMatcherTest, CanBeImplicitlyConstructedFromCStringLiteral) { 463 Matcher<absl::string_view> m1 = "cats"; 464 EXPECT_TRUE(m1.Matches("cats")); 465 EXPECT_FALSE(m1.Matches("dogs")); 466 467 Matcher<const absl::string_view&> m2 = "cats"; 468 EXPECT_TRUE(m2.Matches("cats")); 469 EXPECT_FALSE(m2.Matches("dogs")); 470} 471 472// Tests that a std::string object can be implicitly converted to a 473// Matcher<absl::string_view> or Matcher<const absl::string_view&>. 474TEST(StringViewMatcherTest, CanBeImplicitlyConstructedFromString) { 475 Matcher<absl::string_view> m1 = std::string("cats"); 476 EXPECT_TRUE(m1.Matches("cats")); 477 EXPECT_FALSE(m1.Matches("dogs")); 478 479 Matcher<const absl::string_view&> m2 = std::string("cats"); 480 EXPECT_TRUE(m2.Matches("cats")); 481 EXPECT_FALSE(m2.Matches("dogs")); 482} 483 484#if GTEST_HAS_GLOBAL_STRING 485// Tests that a ::string object can be implicitly converted to a 486// Matcher<absl::string_view> or Matcher<const absl::string_view&>. 487TEST(StringViewMatcherTest, CanBeImplicitlyConstructedFromGlobalString) { 488 Matcher<absl::string_view> m1 = ::string("cats"); 489 EXPECT_TRUE(m1.Matches("cats")); 490 EXPECT_FALSE(m1.Matches("dogs")); 491 492 Matcher<const absl::string_view&> m2 = ::string("cats"); 493 EXPECT_TRUE(m2.Matches("cats")); 494 EXPECT_FALSE(m2.Matches("dogs")); 495} 496#endif // GTEST_HAS_GLOBAL_STRING 497 498// Tests that a absl::string_view object can be implicitly converted to a 499// Matcher<absl::string_view> or Matcher<const absl::string_view&>. 500TEST(StringViewMatcherTest, CanBeImplicitlyConstructedFromStringView) { 501 Matcher<absl::string_view> m1 = absl::string_view("cats"); 502 EXPECT_TRUE(m1.Matches("cats")); 503 EXPECT_FALSE(m1.Matches("dogs")); 504 505 Matcher<const absl::string_view&> m2 = absl::string_view("cats"); 506 EXPECT_TRUE(m2.Matches("cats")); 507 EXPECT_FALSE(m2.Matches("dogs")); 508} 509#endif // GTEST_HAS_ABSL 510 511// Tests that MakeMatcher() constructs a Matcher<T> from a 512// MatcherInterface* without requiring the user to explicitly 513// write the type. 514TEST(MakeMatcherTest, ConstructsMatcherFromMatcherInterface) { 515 const MatcherInterface<int>* dummy_impl = NULL; 516 Matcher<int> m = MakeMatcher(dummy_impl); 517} 518 519// Tests that MakePolymorphicMatcher() can construct a polymorphic 520// matcher from its implementation using the old API. 521const int g_bar = 1; 522class ReferencesBarOrIsZeroImpl { 523 public: 524 template <typename T> 525 bool MatchAndExplain(const T& x, 526 MatchResultListener* /* listener */) const { 527 const void* p = &x; 528 return p == &g_bar || x == 0; 529 } 530 531 void DescribeTo(ostream* os) const { *os << "g_bar or zero"; } 532 533 void DescribeNegationTo(ostream* os) const { 534 *os << "doesn't reference g_bar and is not zero"; 535 } 536}; 537 538// This function verifies that MakePolymorphicMatcher() returns a 539// PolymorphicMatcher<T> where T is the argument's type. 540PolymorphicMatcher<ReferencesBarOrIsZeroImpl> ReferencesBarOrIsZero() { 541 return MakePolymorphicMatcher(ReferencesBarOrIsZeroImpl()); 542} 543 544TEST(MakePolymorphicMatcherTest, ConstructsMatcherUsingOldAPI) { 545 // Using a polymorphic matcher to match a reference type. 546 Matcher<const int&> m1 = ReferencesBarOrIsZero(); 547 EXPECT_TRUE(m1.Matches(0)); 548 // Verifies that the identity of a by-reference argument is preserved. 549 EXPECT_TRUE(m1.Matches(g_bar)); 550 EXPECT_FALSE(m1.Matches(1)); 551 EXPECT_EQ("g_bar or zero", Describe(m1)); 552 553 // Using a polymorphic matcher to match a value type. 554 Matcher<double> m2 = ReferencesBarOrIsZero(); 555 EXPECT_TRUE(m2.Matches(0.0)); 556 EXPECT_FALSE(m2.Matches(0.1)); 557 EXPECT_EQ("g_bar or zero", Describe(m2)); 558} 559 560// Tests implementing a polymorphic matcher using MatchAndExplain(). 561 562class PolymorphicIsEvenImpl { 563 public: 564 void DescribeTo(ostream* os) const { *os << "is even"; } 565 566 void DescribeNegationTo(ostream* os) const { 567 *os << "is odd"; 568 } 569 570 template <typename T> 571 bool MatchAndExplain(const T& x, MatchResultListener* listener) const { 572 // Verifies that we can stream to the listener directly. 573 *listener << "% " << 2; 574 if (listener->stream() != NULL) { 575 // Verifies that we can stream to the listener's underlying stream 576 // too. 577 *listener->stream() << " == " << (x % 2); 578 } 579 return (x % 2) == 0; 580 } 581}; 582 583PolymorphicMatcher<PolymorphicIsEvenImpl> PolymorphicIsEven() { 584 return MakePolymorphicMatcher(PolymorphicIsEvenImpl()); 585} 586 587TEST(MakePolymorphicMatcherTest, ConstructsMatcherUsingNewAPI) { 588 // Using PolymorphicIsEven() as a Matcher<int>. 589 const Matcher<int> m1 = PolymorphicIsEven(); 590 EXPECT_TRUE(m1.Matches(42)); 591 EXPECT_FALSE(m1.Matches(43)); 592 EXPECT_EQ("is even", Describe(m1)); 593 594 const Matcher<int> not_m1 = Not(m1); 595 EXPECT_EQ("is odd", Describe(not_m1)); 596 597 EXPECT_EQ("% 2 == 0", Explain(m1, 42)); 598 599 // Using PolymorphicIsEven() as a Matcher<char>. 600 const Matcher<char> m2 = PolymorphicIsEven(); 601 EXPECT_TRUE(m2.Matches('\x42')); 602 EXPECT_FALSE(m2.Matches('\x43')); 603 EXPECT_EQ("is even", Describe(m2)); 604 605 const Matcher<char> not_m2 = Not(m2); 606 EXPECT_EQ("is odd", Describe(not_m2)); 607 608 EXPECT_EQ("% 2 == 0", Explain(m2, '\x42')); 609} 610 611// Tests that MatcherCast<T>(m) works when m is a polymorphic matcher. 612TEST(MatcherCastTest, FromPolymorphicMatcher) { 613 Matcher<int> m = MatcherCast<int>(Eq(5)); 614 EXPECT_TRUE(m.Matches(5)); 615 EXPECT_FALSE(m.Matches(6)); 616} 617 618// For testing casting matchers between compatible types. 619class IntValue { 620 public: 621 // An int can be statically (although not implicitly) cast to a 622 // IntValue. 623 explicit IntValue(int a_value) : value_(a_value) {} 624 625 int value() const { return value_; } 626 private: 627 int value_; 628}; 629 630// For testing casting matchers between compatible types. 631bool IsPositiveIntValue(const IntValue& foo) { 632 return foo.value() > 0; 633} 634 635// Tests that MatcherCast<T>(m) works when m is a Matcher<U> where T 636// can be statically converted to U. 637TEST(MatcherCastTest, FromCompatibleType) { 638 Matcher<double> m1 = Eq(2.0); 639 Matcher<int> m2 = MatcherCast<int>(m1); 640 EXPECT_TRUE(m2.Matches(2)); 641 EXPECT_FALSE(m2.Matches(3)); 642 643 Matcher<IntValue> m3 = Truly(IsPositiveIntValue); 644 Matcher<int> m4 = MatcherCast<int>(m3); 645 // In the following, the arguments 1 and 0 are statically converted 646 // to IntValue objects, and then tested by the IsPositiveIntValue() 647 // predicate. 648 EXPECT_TRUE(m4.Matches(1)); 649 EXPECT_FALSE(m4.Matches(0)); 650} 651 652// Tests that MatcherCast<T>(m) works when m is a Matcher<const T&>. 653TEST(MatcherCastTest, FromConstReferenceToNonReference) { 654 Matcher<const int&> m1 = Eq(0); 655 Matcher<int> m2 = MatcherCast<int>(m1); 656 EXPECT_TRUE(m2.Matches(0)); 657 EXPECT_FALSE(m2.Matches(1)); 658} 659 660// Tests that MatcherCast<T>(m) works when m is a Matcher<T&>. 661TEST(MatcherCastTest, FromReferenceToNonReference) { 662 Matcher<int&> m1 = Eq(0); 663 Matcher<int> m2 = MatcherCast<int>(m1); 664 EXPECT_TRUE(m2.Matches(0)); 665 EXPECT_FALSE(m2.Matches(1)); 666} 667 668// Tests that MatcherCast<const T&>(m) works when m is a Matcher<T>. 669TEST(MatcherCastTest, FromNonReferenceToConstReference) { 670 Matcher<int> m1 = Eq(0); 671 Matcher<const int&> m2 = MatcherCast<const int&>(m1); 672 EXPECT_TRUE(m2.Matches(0)); 673 EXPECT_FALSE(m2.Matches(1)); 674} 675 676// Tests that MatcherCast<T&>(m) works when m is a Matcher<T>. 677TEST(MatcherCastTest, FromNonReferenceToReference) { 678 Matcher<int> m1 = Eq(0); 679 Matcher<int&> m2 = MatcherCast<int&>(m1); 680 int n = 0; 681 EXPECT_TRUE(m2.Matches(n)); 682 n = 1; 683 EXPECT_FALSE(m2.Matches(n)); 684} 685 686// Tests that MatcherCast<T>(m) works when m is a Matcher<T>. 687TEST(MatcherCastTest, FromSameType) { 688 Matcher<int> m1 = Eq(0); 689 Matcher<int> m2 = MatcherCast<int>(m1); 690 EXPECT_TRUE(m2.Matches(0)); 691 EXPECT_FALSE(m2.Matches(1)); 692} 693 694// Tests that MatcherCast<T>(m) works when m is a value of the same type as the 695// value type of the Matcher. 696TEST(MatcherCastTest, FromAValue) { 697 Matcher<int> m = MatcherCast<int>(42); 698 EXPECT_TRUE(m.Matches(42)); 699 EXPECT_FALSE(m.Matches(239)); 700} 701 702// Tests that MatcherCast<T>(m) works when m is a value of the type implicitly 703// convertible to the value type of the Matcher. 704TEST(MatcherCastTest, FromAnImplicitlyConvertibleValue) { 705 const int kExpected = 'c'; 706 Matcher<int> m = MatcherCast<int>('c'); 707 EXPECT_TRUE(m.Matches(kExpected)); 708 EXPECT_FALSE(m.Matches(kExpected + 1)); 709} 710 711struct NonImplicitlyConstructibleTypeWithOperatorEq { 712 friend bool operator==( 713 const NonImplicitlyConstructibleTypeWithOperatorEq& /* ignored */, 714 int rhs) { 715 return 42 == rhs; 716 } 717 friend bool operator==( 718 int lhs, 719 const NonImplicitlyConstructibleTypeWithOperatorEq& /* ignored */) { 720 return lhs == 42; 721 } 722}; 723 724// Tests that MatcherCast<T>(m) works when m is a neither a matcher nor 725// implicitly convertible to the value type of the Matcher, but the value type 726// of the matcher has operator==() overload accepting m. 727TEST(MatcherCastTest, NonImplicitlyConstructibleTypeWithOperatorEq) { 728 Matcher<NonImplicitlyConstructibleTypeWithOperatorEq> m1 = 729 MatcherCast<NonImplicitlyConstructibleTypeWithOperatorEq>(42); 730 EXPECT_TRUE(m1.Matches(NonImplicitlyConstructibleTypeWithOperatorEq())); 731 732 Matcher<NonImplicitlyConstructibleTypeWithOperatorEq> m2 = 733 MatcherCast<NonImplicitlyConstructibleTypeWithOperatorEq>(239); 734 EXPECT_FALSE(m2.Matches(NonImplicitlyConstructibleTypeWithOperatorEq())); 735 736 // When updating the following lines please also change the comment to 737 // namespace convertible_from_any. 738 Matcher<int> m3 = 739 MatcherCast<int>(NonImplicitlyConstructibleTypeWithOperatorEq()); 740 EXPECT_TRUE(m3.Matches(42)); 741 EXPECT_FALSE(m3.Matches(239)); 742} 743 744// ConvertibleFromAny does not work with MSVC. resulting in 745// error C2440: 'initializing': cannot convert from 'Eq' to 'M' 746// No constructor could take the source type, or constructor overload 747// resolution was ambiguous 748 749#if !defined _MSC_VER 750 751// The below ConvertibleFromAny struct is implicitly constructible from anything 752// and when in the same namespace can interact with other tests. In particular, 753// if it is in the same namespace as other tests and one removes 754// NonImplicitlyConstructibleTypeWithOperatorEq::operator==(int lhs, ...); 755// then the corresponding test still compiles (and it should not!) by implicitly 756// converting NonImplicitlyConstructibleTypeWithOperatorEq to ConvertibleFromAny 757// in m3.Matcher(). 758namespace convertible_from_any { 759// Implicitly convertible from any type. 760struct ConvertibleFromAny { 761 ConvertibleFromAny(int a_value) : value(a_value) {} 762 template <typename T> 763 ConvertibleFromAny(const T& /*a_value*/) : value(-1) { 764 ADD_FAILURE() << "Conversion constructor called"; 765 } 766 int value; 767}; 768 769bool operator==(const ConvertibleFromAny& a, const ConvertibleFromAny& b) { 770 return a.value == b.value; 771} 772 773ostream& operator<<(ostream& os, const ConvertibleFromAny& a) { 774 return os << a.value; 775} 776 777TEST(MatcherCastTest, ConversionConstructorIsUsed) { 778 Matcher<ConvertibleFromAny> m = MatcherCast<ConvertibleFromAny>(1); 779 EXPECT_TRUE(m.Matches(ConvertibleFromAny(1))); 780 EXPECT_FALSE(m.Matches(ConvertibleFromAny(2))); 781} 782 783TEST(MatcherCastTest, FromConvertibleFromAny) { 784 Matcher<ConvertibleFromAny> m = 785 MatcherCast<ConvertibleFromAny>(Eq(ConvertibleFromAny(1))); 786 EXPECT_TRUE(m.Matches(ConvertibleFromAny(1))); 787 EXPECT_FALSE(m.Matches(ConvertibleFromAny(2))); 788} 789} // namespace convertible_from_any 790 791#endif // !defined _MSC_VER 792 793struct IntReferenceWrapper { 794 IntReferenceWrapper(const int& a_value) : value(&a_value) {} 795 const int* value; 796}; 797 798bool operator==(const IntReferenceWrapper& a, const IntReferenceWrapper& b) { 799 return a.value == b.value; 800} 801 802TEST(MatcherCastTest, ValueIsNotCopied) { 803 int n = 42; 804 Matcher<IntReferenceWrapper> m = MatcherCast<IntReferenceWrapper>(n); 805 // Verify that the matcher holds a reference to n, not to its temporary copy. 806 EXPECT_TRUE(m.Matches(n)); 807} 808 809class Base { 810 public: 811 virtual ~Base() {} 812 Base() {} 813 private: 814 GTEST_DISALLOW_COPY_AND_ASSIGN_(Base); 815}; 816 817class Derived : public Base { 818 public: 819 Derived() : Base() {} 820 int i; 821}; 822 823class OtherDerived : public Base {}; 824 825// Tests that SafeMatcherCast<T>(m) works when m is a polymorphic matcher. 826TEST(SafeMatcherCastTest, FromPolymorphicMatcher) { 827 Matcher<char> m2 = SafeMatcherCast<char>(Eq(32)); 828 EXPECT_TRUE(m2.Matches(' ')); 829 EXPECT_FALSE(m2.Matches('\n')); 830} 831 832// Tests that SafeMatcherCast<T>(m) works when m is a Matcher<U> where 833// T and U are arithmetic types and T can be losslessly converted to 834// U. 835TEST(SafeMatcherCastTest, FromLosslesslyConvertibleArithmeticType) { 836 Matcher<double> m1 = DoubleEq(1.0); 837 Matcher<float> m2 = SafeMatcherCast<float>(m1); 838 EXPECT_TRUE(m2.Matches(1.0f)); 839 EXPECT_FALSE(m2.Matches(2.0f)); 840 841 Matcher<char> m3 = SafeMatcherCast<char>(TypedEq<int>('a')); 842 EXPECT_TRUE(m3.Matches('a')); 843 EXPECT_FALSE(m3.Matches('b')); 844} 845 846// Tests that SafeMatcherCast<T>(m) works when m is a Matcher<U> where T and U 847// are pointers or references to a derived and a base class, correspondingly. 848TEST(SafeMatcherCastTest, FromBaseClass) { 849 Derived d, d2; 850 Matcher<Base*> m1 = Eq(&d); 851 Matcher<Derived*> m2 = SafeMatcherCast<Derived*>(m1); 852 EXPECT_TRUE(m2.Matches(&d)); 853 EXPECT_FALSE(m2.Matches(&d2)); 854 855 Matcher<Base&> m3 = Ref(d); 856 Matcher<Derived&> m4 = SafeMatcherCast<Derived&>(m3); 857 EXPECT_TRUE(m4.Matches(d)); 858 EXPECT_FALSE(m4.Matches(d2)); 859} 860 861// Tests that SafeMatcherCast<T&>(m) works when m is a Matcher<const T&>. 862TEST(SafeMatcherCastTest, FromConstReferenceToReference) { 863 int n = 0; 864 Matcher<const int&> m1 = Ref(n); 865 Matcher<int&> m2 = SafeMatcherCast<int&>(m1); 866 int n1 = 0; 867 EXPECT_TRUE(m2.Matches(n)); 868 EXPECT_FALSE(m2.Matches(n1)); 869} 870 871// Tests that MatcherCast<const T&>(m) works when m is a Matcher<T>. 872TEST(SafeMatcherCastTest, FromNonReferenceToConstReference) { 873 Matcher<int> m1 = Eq(0); 874 Matcher<const int&> m2 = SafeMatcherCast<const int&>(m1); 875 EXPECT_TRUE(m2.Matches(0)); 876 EXPECT_FALSE(m2.Matches(1)); 877} 878 879// Tests that SafeMatcherCast<T&>(m) works when m is a Matcher<T>. 880TEST(SafeMatcherCastTest, FromNonReferenceToReference) { 881 Matcher<int> m1 = Eq(0); 882 Matcher<int&> m2 = SafeMatcherCast<int&>(m1); 883 int n = 0; 884 EXPECT_TRUE(m2.Matches(n)); 885 n = 1; 886 EXPECT_FALSE(m2.Matches(n)); 887} 888 889// Tests that SafeMatcherCast<T>(m) works when m is a Matcher<T>. 890TEST(SafeMatcherCastTest, FromSameType) { 891 Matcher<int> m1 = Eq(0); 892 Matcher<int> m2 = SafeMatcherCast<int>(m1); 893 EXPECT_TRUE(m2.Matches(0)); 894 EXPECT_FALSE(m2.Matches(1)); 895} 896 897#if !defined _MSC_VER 898 899namespace convertible_from_any { 900TEST(SafeMatcherCastTest, ConversionConstructorIsUsed) { 901 Matcher<ConvertibleFromAny> m = SafeMatcherCast<ConvertibleFromAny>(1); 902 EXPECT_TRUE(m.Matches(ConvertibleFromAny(1))); 903 EXPECT_FALSE(m.Matches(ConvertibleFromAny(2))); 904} 905 906TEST(SafeMatcherCastTest, FromConvertibleFromAny) { 907 Matcher<ConvertibleFromAny> m = 908 SafeMatcherCast<ConvertibleFromAny>(Eq(ConvertibleFromAny(1))); 909 EXPECT_TRUE(m.Matches(ConvertibleFromAny(1))); 910 EXPECT_FALSE(m.Matches(ConvertibleFromAny(2))); 911} 912} // namespace convertible_from_any 913 914#endif // !defined _MSC_VER 915 916TEST(SafeMatcherCastTest, ValueIsNotCopied) { 917 int n = 42; 918 Matcher<IntReferenceWrapper> m = SafeMatcherCast<IntReferenceWrapper>(n); 919 // Verify that the matcher holds a reference to n, not to its temporary copy. 920 EXPECT_TRUE(m.Matches(n)); 921} 922 923TEST(ExpectThat, TakesLiterals) { 924 EXPECT_THAT(1, 1); 925 EXPECT_THAT(1.0, 1.0); 926 EXPECT_THAT(std::string(), ""); 927} 928 929TEST(ExpectThat, TakesFunctions) { 930 struct Helper { 931 static void Func() {} 932 }; 933 void (*func)() = Helper::Func; 934 EXPECT_THAT(func, Helper::Func); 935 EXPECT_THAT(func, &Helper::Func); 936} 937 938// Tests that A<T>() matches any value of type T. 939TEST(ATest, MatchesAnyValue) { 940 // Tests a matcher for a value type. 941 Matcher<double> m1 = A<double>(); 942 EXPECT_TRUE(m1.Matches(91.43)); 943 EXPECT_TRUE(m1.Matches(-15.32)); 944 945 // Tests a matcher for a reference type. 946 int a = 2; 947 int b = -6; 948 Matcher<int&> m2 = A<int&>(); 949 EXPECT_TRUE(m2.Matches(a)); 950 EXPECT_TRUE(m2.Matches(b)); 951} 952 953TEST(ATest, WorksForDerivedClass) { 954 Base base; 955 Derived derived; 956 EXPECT_THAT(&base, A<Base*>()); 957 // This shouldn't compile: EXPECT_THAT(&base, A<Derived*>()); 958 EXPECT_THAT(&derived, A<Base*>()); 959 EXPECT_THAT(&derived, A<Derived*>()); 960} 961 962// Tests that A<T>() describes itself properly. 963TEST(ATest, CanDescribeSelf) { 964 EXPECT_EQ("is anything", Describe(A<bool>())); 965} 966 967// Tests that An<T>() matches any value of type T. 968TEST(AnTest, MatchesAnyValue) { 969 // Tests a matcher for a value type. 970 Matcher<int> m1 = An<int>(); 971 EXPECT_TRUE(m1.Matches(9143)); 972 EXPECT_TRUE(m1.Matches(-1532)); 973 974 // Tests a matcher for a reference type. 975 int a = 2; 976 int b = -6; 977 Matcher<int&> m2 = An<int&>(); 978 EXPECT_TRUE(m2.Matches(a)); 979 EXPECT_TRUE(m2.Matches(b)); 980} 981 982// Tests that An<T>() describes itself properly. 983TEST(AnTest, CanDescribeSelf) { 984 EXPECT_EQ("is anything", Describe(An<int>())); 985} 986 987// Tests that _ can be used as a matcher for any type and matches any 988// value of that type. 989TEST(UnderscoreTest, MatchesAnyValue) { 990 // Uses _ as a matcher for a value type. 991 Matcher<int> m1 = _; 992 EXPECT_TRUE(m1.Matches(123)); 993 EXPECT_TRUE(m1.Matches(-242)); 994 995 // Uses _ as a matcher for a reference type. 996 bool a = false; 997 const bool b = true; 998 Matcher<const bool&> m2 = _; 999 EXPECT_TRUE(m2.Matches(a)); 1000 EXPECT_TRUE(m2.Matches(b)); 1001} 1002 1003// Tests that _ describes itself properly. 1004TEST(UnderscoreTest, CanDescribeSelf) { 1005 Matcher<int> m = _; 1006 EXPECT_EQ("is anything", Describe(m)); 1007} 1008 1009// Tests that Eq(x) matches any value equal to x. 1010TEST(EqTest, MatchesEqualValue) { 1011 // 2 C-strings with same content but different addresses. 1012 const char a1[] = "hi"; 1013 const char a2[] = "hi"; 1014 1015 Matcher<const char*> m1 = Eq(a1); 1016 EXPECT_TRUE(m1.Matches(a1)); 1017 EXPECT_FALSE(m1.Matches(a2)); 1018} 1019 1020// Tests that Eq(v) describes itself properly. 1021 1022class Unprintable { 1023 public: 1024 Unprintable() : c_('a') {} 1025 1026 bool operator==(const Unprintable& /* rhs */) const { return true; } 1027 private: 1028 char c_; 1029}; 1030 1031TEST(EqTest, CanDescribeSelf) { 1032 Matcher<Unprintable> m = Eq(Unprintable()); 1033 EXPECT_EQ("is equal to 1-byte object <61>", Describe(m)); 1034} 1035 1036// Tests that Eq(v) can be used to match any type that supports 1037// comparing with type T, where T is v's type. 1038TEST(EqTest, IsPolymorphic) { 1039 Matcher<int> m1 = Eq(1); 1040 EXPECT_TRUE(m1.Matches(1)); 1041 EXPECT_FALSE(m1.Matches(2)); 1042 1043 Matcher<char> m2 = Eq(1); 1044 EXPECT_TRUE(m2.Matches('\1')); 1045 EXPECT_FALSE(m2.Matches('a')); 1046} 1047 1048// Tests that TypedEq<T>(v) matches values of type T that's equal to v. 1049TEST(TypedEqTest, ChecksEqualityForGivenType) { 1050 Matcher<char> m1 = TypedEq<char>('a'); 1051 EXPECT_TRUE(m1.Matches('a')); 1052 EXPECT_FALSE(m1.Matches('b')); 1053 1054 Matcher<int> m2 = TypedEq<int>(6); 1055 EXPECT_TRUE(m2.Matches(6)); 1056 EXPECT_FALSE(m2.Matches(7)); 1057} 1058 1059// Tests that TypedEq(v) describes itself properly. 1060TEST(TypedEqTest, CanDescribeSelf) { 1061 EXPECT_EQ("is equal to 2", Describe(TypedEq<int>(2))); 1062} 1063 1064// Tests that TypedEq<T>(v) has type Matcher<T>. 1065 1066// Type<T>::IsTypeOf(v) compiles iff the type of value v is T, where T 1067// is a "bare" type (i.e. not in the form of const U or U&). If v's 1068// type is not T, the compiler will generate a message about 1069// "undefined reference". 1070template <typename T> 1071struct Type { 1072 static bool IsTypeOf(const T& /* v */) { return true; } 1073 1074 template <typename T2> 1075 static void IsTypeOf(T2 v); 1076}; 1077 1078TEST(TypedEqTest, HasSpecifiedType) { 1079 // Verfies that the type of TypedEq<T>(v) is Matcher<T>. 1080 Type<Matcher<int> >::IsTypeOf(TypedEq<int>(5)); 1081 Type<Matcher<double> >::IsTypeOf(TypedEq<double>(5)); 1082} 1083 1084// Tests that Ge(v) matches anything >= v. 1085TEST(GeTest, ImplementsGreaterThanOrEqual) { 1086 Matcher<int> m1 = Ge(0); 1087 EXPECT_TRUE(m1.Matches(1)); 1088 EXPECT_TRUE(m1.Matches(0)); 1089 EXPECT_FALSE(m1.Matches(-1)); 1090} 1091 1092// Tests that Ge(v) describes itself properly. 1093TEST(GeTest, CanDescribeSelf) { 1094 Matcher<int> m = Ge(5); 1095 EXPECT_EQ("is >= 5", Describe(m)); 1096} 1097 1098// Tests that Gt(v) matches anything > v. 1099TEST(GtTest, ImplementsGreaterThan) { 1100 Matcher<double> m1 = Gt(0); 1101 EXPECT_TRUE(m1.Matches(1.0)); 1102 EXPECT_FALSE(m1.Matches(0.0)); 1103 EXPECT_FALSE(m1.Matches(-1.0)); 1104} 1105 1106// Tests that Gt(v) describes itself properly. 1107TEST(GtTest, CanDescribeSelf) { 1108 Matcher<int> m = Gt(5); 1109 EXPECT_EQ("is > 5", Describe(m)); 1110} 1111 1112// Tests that Le(v) matches anything <= v. 1113TEST(LeTest, ImplementsLessThanOrEqual) { 1114 Matcher<char> m1 = Le('b'); 1115 EXPECT_TRUE(m1.Matches('a')); 1116 EXPECT_TRUE(m1.Matches('b')); 1117 EXPECT_FALSE(m1.Matches('c')); 1118} 1119 1120// Tests that Le(v) describes itself properly. 1121TEST(LeTest, CanDescribeSelf) { 1122 Matcher<int> m = Le(5); 1123 EXPECT_EQ("is <= 5", Describe(m)); 1124} 1125 1126// Tests that Lt(v) matches anything < v. 1127TEST(LtTest, ImplementsLessThan) { 1128 Matcher<const std::string&> m1 = Lt("Hello"); 1129 EXPECT_TRUE(m1.Matches("Abc")); 1130 EXPECT_FALSE(m1.Matches("Hello")); 1131 EXPECT_FALSE(m1.Matches("Hello, world!")); 1132} 1133 1134// Tests that Lt(v) describes itself properly. 1135TEST(LtTest, CanDescribeSelf) { 1136 Matcher<int> m = Lt(5); 1137 EXPECT_EQ("is < 5", Describe(m)); 1138} 1139 1140// Tests that Ne(v) matches anything != v. 1141TEST(NeTest, ImplementsNotEqual) { 1142 Matcher<int> m1 = Ne(0); 1143 EXPECT_TRUE(m1.Matches(1)); 1144 EXPECT_TRUE(m1.Matches(-1)); 1145 EXPECT_FALSE(m1.Matches(0)); 1146} 1147 1148// Tests that Ne(v) describes itself properly. 1149TEST(NeTest, CanDescribeSelf) { 1150 Matcher<int> m = Ne(5); 1151 EXPECT_EQ("isn't equal to 5", Describe(m)); 1152} 1153 1154// Tests that IsNull() matches any NULL pointer of any type. 1155TEST(IsNullTest, MatchesNullPointer) { 1156 Matcher<int*> m1 = IsNull(); 1157 int* p1 = NULL; 1158 int n = 0; 1159 EXPECT_TRUE(m1.Matches(p1)); 1160 EXPECT_FALSE(m1.Matches(&n)); 1161 1162 Matcher<const char*> m2 = IsNull(); 1163 const char* p2 = NULL; 1164 EXPECT_TRUE(m2.Matches(p2)); 1165 EXPECT_FALSE(m2.Matches("hi")); 1166 1167#if !GTEST_OS_SYMBIAN 1168 // Nokia's Symbian compiler generates: 1169 // gmock-matchers.h: ambiguous access to overloaded function 1170 // gmock-matchers.h: 'testing::Matcher<void *>::Matcher(void *)' 1171 // gmock-matchers.h: 'testing::Matcher<void *>::Matcher(const testing:: 1172 // MatcherInterface<void *> *)' 1173 // gmock-matchers.h: (point of instantiation: 'testing:: 1174 // gmock_matchers_test::IsNullTest_MatchesNullPointer_Test::TestBody()') 1175 // gmock-matchers.h: (instantiating: 'testing::PolymorphicMatc 1176 Matcher<void*> m3 = IsNull(); 1177 void* p3 = NULL; 1178 EXPECT_TRUE(m3.Matches(p3)); 1179 EXPECT_FALSE(m3.Matches(reinterpret_cast<void*>(0xbeef))); 1180#endif 1181} 1182 1183TEST(IsNullTest, LinkedPtr) { 1184 const Matcher<linked_ptr<int> > m = IsNull(); 1185 const linked_ptr<int> null_p; 1186 const linked_ptr<int> non_null_p(new int); 1187 1188 EXPECT_TRUE(m.Matches(null_p)); 1189 EXPECT_FALSE(m.Matches(non_null_p)); 1190} 1191 1192TEST(IsNullTest, ReferenceToConstLinkedPtr) { 1193 const Matcher<const linked_ptr<double>&> m = IsNull(); 1194 const linked_ptr<double> null_p; 1195 const linked_ptr<double> non_null_p(new double); 1196 1197 EXPECT_TRUE(m.Matches(null_p)); 1198 EXPECT_FALSE(m.Matches(non_null_p)); 1199} 1200 1201#if GTEST_LANG_CXX11 1202TEST(IsNullTest, StdFunction) { 1203 const Matcher<std::function<void()>> m = IsNull(); 1204 1205 EXPECT_TRUE(m.Matches(std::function<void()>())); 1206 EXPECT_FALSE(m.Matches([]{})); 1207} 1208#endif // GTEST_LANG_CXX11 1209 1210// Tests that IsNull() describes itself properly. 1211TEST(IsNullTest, CanDescribeSelf) { 1212 Matcher<int*> m = IsNull(); 1213 EXPECT_EQ("is NULL", Describe(m)); 1214 EXPECT_EQ("isn't NULL", DescribeNegation(m)); 1215} 1216 1217// Tests that NotNull() matches any non-NULL pointer of any type. 1218TEST(NotNullTest, MatchesNonNullPointer) { 1219 Matcher<int*> m1 = NotNull(); 1220 int* p1 = NULL; 1221 int n = 0; 1222 EXPECT_FALSE(m1.Matches(p1)); 1223 EXPECT_TRUE(m1.Matches(&n)); 1224 1225 Matcher<const char*> m2 = NotNull(); 1226 const char* p2 = NULL; 1227 EXPECT_FALSE(m2.Matches(p2)); 1228 EXPECT_TRUE(m2.Matches("hi")); 1229} 1230 1231TEST(NotNullTest, LinkedPtr) { 1232 const Matcher<linked_ptr<int> > m = NotNull(); 1233 const linked_ptr<int> null_p; 1234 const linked_ptr<int> non_null_p(new int); 1235 1236 EXPECT_FALSE(m.Matches(null_p)); 1237 EXPECT_TRUE(m.Matches(non_null_p)); 1238} 1239 1240TEST(NotNullTest, ReferenceToConstLinkedPtr) { 1241 const Matcher<const linked_ptr<double>&> m = NotNull(); 1242 const linked_ptr<double> null_p; 1243 const linked_ptr<double> non_null_p(new double); 1244 1245 EXPECT_FALSE(m.Matches(null_p)); 1246 EXPECT_TRUE(m.Matches(non_null_p)); 1247} 1248 1249#if GTEST_LANG_CXX11 1250TEST(NotNullTest, StdFunction) { 1251 const Matcher<std::function<void()>> m = NotNull(); 1252 1253 EXPECT_TRUE(m.Matches([]{})); 1254 EXPECT_FALSE(m.Matches(std::function<void()>())); 1255} 1256#endif // GTEST_LANG_CXX11 1257 1258// Tests that NotNull() describes itself properly. 1259TEST(NotNullTest, CanDescribeSelf) { 1260 Matcher<int*> m = NotNull(); 1261 EXPECT_EQ("isn't NULL", Describe(m)); 1262} 1263 1264// Tests that Ref(variable) matches an argument that references 1265// 'variable'. 1266TEST(RefTest, MatchesSameVariable) { 1267 int a = 0; 1268 int b = 0; 1269 Matcher<int&> m = Ref(a); 1270 EXPECT_TRUE(m.Matches(a)); 1271 EXPECT_FALSE(m.Matches(b)); 1272} 1273 1274// Tests that Ref(variable) describes itself properly. 1275TEST(RefTest, CanDescribeSelf) { 1276 int n = 5; 1277 Matcher<int&> m = Ref(n); 1278 stringstream ss; 1279 ss << "references the variable @" << &n << " 5"; 1280 EXPECT_EQ(ss.str(), Describe(m)); 1281} 1282 1283// Test that Ref(non_const_varialbe) can be used as a matcher for a 1284// const reference. 1285TEST(RefTest, CanBeUsedAsMatcherForConstReference) { 1286 int a = 0; 1287 int b = 0; 1288 Matcher<const int&> m = Ref(a); 1289 EXPECT_TRUE(m.Matches(a)); 1290 EXPECT_FALSE(m.Matches(b)); 1291} 1292 1293// Tests that Ref(variable) is covariant, i.e. Ref(derived) can be 1294// used wherever Ref(base) can be used (Ref(derived) is a sub-type 1295// of Ref(base), but not vice versa. 1296 1297TEST(RefTest, IsCovariant) { 1298 Base base, base2; 1299 Derived derived; 1300 Matcher<const Base&> m1 = Ref(base); 1301 EXPECT_TRUE(m1.Matches(base)); 1302 EXPECT_FALSE(m1.Matches(base2)); 1303 EXPECT_FALSE(m1.Matches(derived)); 1304 1305 m1 = Ref(derived); 1306 EXPECT_TRUE(m1.Matches(derived)); 1307 EXPECT_FALSE(m1.Matches(base)); 1308 EXPECT_FALSE(m1.Matches(base2)); 1309} 1310 1311TEST(RefTest, ExplainsResult) { 1312 int n = 0; 1313 EXPECT_THAT(Explain(Matcher<const int&>(Ref(n)), n), 1314 StartsWith("which is located @")); 1315 1316 int m = 0; 1317 EXPECT_THAT(Explain(Matcher<const int&>(Ref(n)), m), 1318 StartsWith("which is located @")); 1319} 1320 1321// Tests string comparison matchers. 1322 1323TEST(StrEqTest, MatchesEqualString) { 1324 Matcher<const char*> m = StrEq(std::string("Hello")); 1325 EXPECT_TRUE(m.Matches("Hello")); 1326 EXPECT_FALSE(m.Matches("hello")); 1327 EXPECT_FALSE(m.Matches(NULL)); 1328 1329 Matcher<const std::string&> m2 = StrEq("Hello"); 1330 EXPECT_TRUE(m2.Matches("Hello")); 1331 EXPECT_FALSE(m2.Matches("Hi")); 1332 1333#if GTEST_HAS_ABSL 1334 Matcher<const absl::string_view&> m3 = StrEq("Hello"); 1335 EXPECT_TRUE(m3.Matches(absl::string_view("Hello"))); 1336 EXPECT_FALSE(m3.Matches(absl::string_view("hello"))); 1337 EXPECT_FALSE(m3.Matches(absl::string_view())); 1338#endif // GTEST_HAS_ABSL 1339} 1340 1341TEST(StrEqTest, CanDescribeSelf) { 1342 Matcher<std::string> m = StrEq("Hi-\'\"?\\\a\b\f\n\r\t\v\xD3"); 1343 EXPECT_EQ("is equal to \"Hi-\'\\\"?\\\\\\a\\b\\f\\n\\r\\t\\v\\xD3\"", 1344 Describe(m)); 1345 1346 std::string str("01204500800"); 1347 str[3] = '\0'; 1348 Matcher<std::string> m2 = StrEq(str); 1349 EXPECT_EQ("is equal to \"012\\04500800\"", Describe(m2)); 1350 str[0] = str[6] = str[7] = str[9] = str[10] = '\0'; 1351 Matcher<std::string> m3 = StrEq(str); 1352 EXPECT_EQ("is equal to \"\\012\\045\\0\\08\\0\\0\"", Describe(m3)); 1353} 1354 1355TEST(StrNeTest, MatchesUnequalString) { 1356 Matcher<const char*> m = StrNe("Hello"); 1357 EXPECT_TRUE(m.Matches("")); 1358 EXPECT_TRUE(m.Matches(NULL)); 1359 EXPECT_FALSE(m.Matches("Hello")); 1360 1361 Matcher<std::string> m2 = StrNe(std::string("Hello")); 1362 EXPECT_TRUE(m2.Matches("hello")); 1363 EXPECT_FALSE(m2.Matches("Hello")); 1364 1365#if GTEST_HAS_ABSL 1366 Matcher<const absl::string_view> m3 = StrNe("Hello"); 1367 EXPECT_TRUE(m3.Matches(absl::string_view(""))); 1368 EXPECT_TRUE(m3.Matches(absl::string_view())); 1369 EXPECT_FALSE(m3.Matches(absl::string_view("Hello"))); 1370#endif // GTEST_HAS_ABSL 1371} 1372 1373TEST(StrNeTest, CanDescribeSelf) { 1374 Matcher<const char*> m = StrNe("Hi"); 1375 EXPECT_EQ("isn't equal to \"Hi\"", Describe(m)); 1376} 1377 1378TEST(StrCaseEqTest, MatchesEqualStringIgnoringCase) { 1379 Matcher<const char*> m = StrCaseEq(std::string("Hello")); 1380 EXPECT_TRUE(m.Matches("Hello")); 1381 EXPECT_TRUE(m.Matches("hello")); 1382 EXPECT_FALSE(m.Matches("Hi")); 1383 EXPECT_FALSE(m.Matches(NULL)); 1384 1385 Matcher<const std::string&> m2 = StrCaseEq("Hello"); 1386 EXPECT_TRUE(m2.Matches("hello")); 1387 EXPECT_FALSE(m2.Matches("Hi")); 1388 1389#if GTEST_HAS_ABSL 1390 Matcher<const absl::string_view&> m3 = StrCaseEq(std::string("Hello")); 1391 EXPECT_TRUE(m3.Matches(absl::string_view("Hello"))); 1392 EXPECT_TRUE(m3.Matches(absl::string_view("hello"))); 1393 EXPECT_FALSE(m3.Matches(absl::string_view("Hi"))); 1394 EXPECT_FALSE(m3.Matches(absl::string_view())); 1395#endif // GTEST_HAS_ABSL 1396} 1397 1398TEST(StrCaseEqTest, MatchesEqualStringWith0IgnoringCase) { 1399 std::string str1("oabocdooeoo"); 1400 std::string str2("OABOCDOOEOO"); 1401 Matcher<const std::string&> m0 = StrCaseEq(str1); 1402 EXPECT_FALSE(m0.Matches(str2 + std::string(1, '\0'))); 1403 1404 str1[3] = str2[3] = '\0'; 1405 Matcher<const std::string&> m1 = StrCaseEq(str1); 1406 EXPECT_TRUE(m1.Matches(str2)); 1407 1408 str1[0] = str1[6] = str1[7] = str1[10] = '\0'; 1409 str2[0] = str2[6] = str2[7] = str2[10] = '\0'; 1410 Matcher<const std::string&> m2 = StrCaseEq(str1); 1411 str1[9] = str2[9] = '\0'; 1412 EXPECT_FALSE(m2.Matches(str2)); 1413 1414 Matcher<const std::string&> m3 = StrCaseEq(str1); 1415 EXPECT_TRUE(m3.Matches(str2)); 1416 1417 EXPECT_FALSE(m3.Matches(str2 + "x")); 1418 str2.append(1, '\0'); 1419 EXPECT_FALSE(m3.Matches(str2)); 1420 EXPECT_FALSE(m3.Matches(std::string(str2, 0, 9))); 1421} 1422 1423TEST(StrCaseEqTest, CanDescribeSelf) { 1424 Matcher<std::string> m = StrCaseEq("Hi"); 1425 EXPECT_EQ("is equal to (ignoring case) \"Hi\"", Describe(m)); 1426} 1427 1428TEST(StrCaseNeTest, MatchesUnequalStringIgnoringCase) { 1429 Matcher<const char*> m = StrCaseNe("Hello"); 1430 EXPECT_TRUE(m.Matches("Hi")); 1431 EXPECT_TRUE(m.Matches(NULL)); 1432 EXPECT_FALSE(m.Matches("Hello")); 1433 EXPECT_FALSE(m.Matches("hello")); 1434 1435 Matcher<std::string> m2 = StrCaseNe(std::string("Hello")); 1436 EXPECT_TRUE(m2.Matches("")); 1437 EXPECT_FALSE(m2.Matches("Hello")); 1438 1439#if GTEST_HAS_ABSL 1440 Matcher<const absl::string_view> m3 = StrCaseNe("Hello"); 1441 EXPECT_TRUE(m3.Matches(absl::string_view("Hi"))); 1442 EXPECT_TRUE(m3.Matches(absl::string_view())); 1443 EXPECT_FALSE(m3.Matches(absl::string_view("Hello"))); 1444 EXPECT_FALSE(m3.Matches(absl::string_view("hello"))); 1445#endif // GTEST_HAS_ABSL 1446} 1447 1448TEST(StrCaseNeTest, CanDescribeSelf) { 1449 Matcher<const char*> m = StrCaseNe("Hi"); 1450 EXPECT_EQ("isn't equal to (ignoring case) \"Hi\"", Describe(m)); 1451} 1452 1453// Tests that HasSubstr() works for matching string-typed values. 1454TEST(HasSubstrTest, WorksForStringClasses) { 1455 const Matcher<std::string> m1 = HasSubstr("foo"); 1456 EXPECT_TRUE(m1.Matches(std::string("I love food."))); 1457 EXPECT_FALSE(m1.Matches(std::string("tofo"))); 1458 1459 const Matcher<const std::string&> m2 = HasSubstr("foo"); 1460 EXPECT_TRUE(m2.Matches(std::string("I love food."))); 1461 EXPECT_FALSE(m2.Matches(std::string("tofo"))); 1462} 1463 1464// Tests that HasSubstr() works for matching C-string-typed values. 1465TEST(HasSubstrTest, WorksForCStrings) { 1466 const Matcher<char*> m1 = HasSubstr("foo"); 1467 EXPECT_TRUE(m1.Matches(const_cast<char*>("I love food."))); 1468 EXPECT_FALSE(m1.Matches(const_cast<char*>("tofo"))); 1469 EXPECT_FALSE(m1.Matches(NULL)); 1470 1471 const Matcher<const char*> m2 = HasSubstr("foo"); 1472 EXPECT_TRUE(m2.Matches("I love food.")); 1473 EXPECT_FALSE(m2.Matches("tofo")); 1474 EXPECT_FALSE(m2.Matches(NULL)); 1475} 1476 1477#if GTEST_HAS_ABSL 1478// Tests that HasSubstr() works for matching absl::string_view-typed values. 1479TEST(HasSubstrTest, WorksForStringViewClasses) { 1480 const Matcher<absl::string_view> m1 = HasSubstr("foo"); 1481 EXPECT_TRUE(m1.Matches(absl::string_view("I love food."))); 1482 EXPECT_FALSE(m1.Matches(absl::string_view("tofo"))); 1483 EXPECT_FALSE(m1.Matches(absl::string_view())); 1484 1485 const Matcher<const absl::string_view&> m2 = HasSubstr("foo"); 1486 EXPECT_TRUE(m2.Matches(absl::string_view("I love food."))); 1487 EXPECT_FALSE(m2.Matches(absl::string_view("tofo"))); 1488 EXPECT_FALSE(m2.Matches(absl::string_view())); 1489 1490 const Matcher<const absl::string_view&> m3 = HasSubstr(""); 1491 EXPECT_TRUE(m3.Matches(absl::string_view("foo"))); 1492 EXPECT_FALSE(m3.Matches(absl::string_view())); 1493} 1494#endif // GTEST_HAS_ABSL 1495 1496// Tests that HasSubstr(s) describes itself properly. 1497TEST(HasSubstrTest, CanDescribeSelf) { 1498 Matcher<std::string> m = HasSubstr("foo\n\""); 1499 EXPECT_EQ("has substring \"foo\\n\\\"\"", Describe(m)); 1500} 1501 1502TEST(KeyTest, CanDescribeSelf) { 1503 Matcher<const pair<std::string, int>&> m = Key("foo"); 1504 EXPECT_EQ("has a key that is equal to \"foo\"", Describe(m)); 1505 EXPECT_EQ("doesn't have a key that is equal to \"foo\"", DescribeNegation(m)); 1506} 1507 1508TEST(KeyTest, ExplainsResult) { 1509 Matcher<pair<int, bool> > m = Key(GreaterThan(10)); 1510 EXPECT_EQ("whose first field is a value which is 5 less than 10", 1511 Explain(m, make_pair(5, true))); 1512 EXPECT_EQ("whose first field is a value which is 5 more than 10", 1513 Explain(m, make_pair(15, true))); 1514} 1515 1516TEST(KeyTest, MatchesCorrectly) { 1517 pair<int, std::string> p(25, "foo"); 1518 EXPECT_THAT(p, Key(25)); 1519 EXPECT_THAT(p, Not(Key(42))); 1520 EXPECT_THAT(p, Key(Ge(20))); 1521 EXPECT_THAT(p, Not(Key(Lt(25)))); 1522} 1523 1524#if GTEST_LANG_CXX11 1525template <size_t I> 1526struct Tag {}; 1527 1528struct PairWithGet { 1529 int member_1; 1530 string member_2; 1531 using first_type = int; 1532 using second_type = string; 1533 1534 const int& GetImpl(Tag<0>) const { return member_1; } 1535 const string& GetImpl(Tag<1>) const { return member_2; } 1536}; 1537template <size_t I> 1538auto get(const PairWithGet& value) -> decltype(value.GetImpl(Tag<I>())) { 1539 return value.GetImpl(Tag<I>()); 1540} 1541TEST(PairTest, MatchesPairWithGetCorrectly) { 1542 PairWithGet p{25, "foo"}; 1543 EXPECT_THAT(p, Key(25)); 1544 EXPECT_THAT(p, Not(Key(42))); 1545 EXPECT_THAT(p, Key(Ge(20))); 1546 EXPECT_THAT(p, Not(Key(Lt(25)))); 1547 1548 std::vector<PairWithGet> v = {{11, "Foo"}, {29, "gMockIsBestMock"}}; 1549 EXPECT_THAT(v, Contains(Key(29))); 1550} 1551#endif // GTEST_LANG_CXX11 1552 1553TEST(KeyTest, SafelyCastsInnerMatcher) { 1554 Matcher<int> is_positive = Gt(0); 1555 Matcher<int> is_negative = Lt(0); 1556 pair<char, bool> p('a', true); 1557 EXPECT_THAT(p, Key(is_positive)); 1558 EXPECT_THAT(p, Not(Key(is_negative))); 1559} 1560 1561TEST(KeyTest, InsideContainsUsingMap) { 1562 map<int, char> container; 1563 container.insert(make_pair(1, 'a')); 1564 container.insert(make_pair(2, 'b')); 1565 container.insert(make_pair(4, 'c')); 1566 EXPECT_THAT(container, Contains(Key(1))); 1567 EXPECT_THAT(container, Not(Contains(Key(3)))); 1568} 1569 1570TEST(KeyTest, InsideContainsUsingMultimap) { 1571 multimap<int, char> container; 1572 container.insert(make_pair(1, 'a')); 1573 container.insert(make_pair(2, 'b')); 1574 container.insert(make_pair(4, 'c')); 1575 1576 EXPECT_THAT(container, Not(Contains(Key(25)))); 1577 container.insert(make_pair(25, 'd')); 1578 EXPECT_THAT(container, Contains(Key(25))); 1579 container.insert(make_pair(25, 'e')); 1580 EXPECT_THAT(container, Contains(Key(25))); 1581 1582 EXPECT_THAT(container, Contains(Key(1))); 1583 EXPECT_THAT(container, Not(Contains(Key(3)))); 1584} 1585 1586TEST(PairTest, Typing) { 1587 // Test verifies the following type conversions can be compiled. 1588 Matcher<const pair<const char*, int>&> m1 = Pair("foo", 42); 1589 Matcher<const pair<const char*, int> > m2 = Pair("foo", 42); 1590 Matcher<pair<const char*, int> > m3 = Pair("foo", 42); 1591 1592 Matcher<pair<int, const std::string> > m4 = Pair(25, "42"); 1593 Matcher<pair<const std::string, int> > m5 = Pair("25", 42); 1594} 1595 1596TEST(PairTest, CanDescribeSelf) { 1597 Matcher<const pair<std::string, int>&> m1 = Pair("foo", 42); 1598 EXPECT_EQ("has a first field that is equal to \"foo\"" 1599 ", and has a second field that is equal to 42", 1600 Describe(m1)); 1601 EXPECT_EQ("has a first field that isn't equal to \"foo\"" 1602 ", or has a second field that isn't equal to 42", 1603 DescribeNegation(m1)); 1604 // Double and triple negation (1 or 2 times not and description of negation). 1605 Matcher<const pair<int, int>&> m2 = Not(Pair(Not(13), 42)); 1606 EXPECT_EQ("has a first field that isn't equal to 13" 1607 ", and has a second field that is equal to 42", 1608 DescribeNegation(m2)); 1609} 1610 1611TEST(PairTest, CanExplainMatchResultTo) { 1612 // If neither field matches, Pair() should explain about the first 1613 // field. 1614 const Matcher<pair<int, int> > m = Pair(GreaterThan(0), GreaterThan(0)); 1615 EXPECT_EQ("whose first field does not match, which is 1 less than 0", 1616 Explain(m, make_pair(-1, -2))); 1617 1618 // If the first field matches but the second doesn't, Pair() should 1619 // explain about the second field. 1620 EXPECT_EQ("whose second field does not match, which is 2 less than 0", 1621 Explain(m, make_pair(1, -2))); 1622 1623 // If the first field doesn't match but the second does, Pair() 1624 // should explain about the first field. 1625 EXPECT_EQ("whose first field does not match, which is 1 less than 0", 1626 Explain(m, make_pair(-1, 2))); 1627 1628 // If both fields match, Pair() should explain about them both. 1629 EXPECT_EQ("whose both fields match, where the first field is a value " 1630 "which is 1 more than 0, and the second field is a value " 1631 "which is 2 more than 0", 1632 Explain(m, make_pair(1, 2))); 1633 1634 // If only the first match has an explanation, only this explanation should 1635 // be printed. 1636 const Matcher<pair<int, int> > explain_first = Pair(GreaterThan(0), 0); 1637 EXPECT_EQ("whose both fields match, where the first field is a value " 1638 "which is 1 more than 0", 1639 Explain(explain_first, make_pair(1, 0))); 1640 1641 // If only the second match has an explanation, only this explanation should 1642 // be printed. 1643 const Matcher<pair<int, int> > explain_second = Pair(0, GreaterThan(0)); 1644 EXPECT_EQ("whose both fields match, where the second field is a value " 1645 "which is 1 more than 0", 1646 Explain(explain_second, make_pair(0, 1))); 1647} 1648 1649TEST(PairTest, MatchesCorrectly) { 1650 pair<int, std::string> p(25, "foo"); 1651 1652 // Both fields match. 1653 EXPECT_THAT(p, Pair(25, "foo")); 1654 EXPECT_THAT(p, Pair(Ge(20), HasSubstr("o"))); 1655 1656 // 'first' doesnt' match, but 'second' matches. 1657 EXPECT_THAT(p, Not(Pair(42, "foo"))); 1658 EXPECT_THAT(p, Not(Pair(Lt(25), "foo"))); 1659 1660 // 'first' matches, but 'second' doesn't match. 1661 EXPECT_THAT(p, Not(Pair(25, "bar"))); 1662 EXPECT_THAT(p, Not(Pair(25, Not("foo")))); 1663 1664 // Neither field matches. 1665 EXPECT_THAT(p, Not(Pair(13, "bar"))); 1666 EXPECT_THAT(p, Not(Pair(Lt(13), HasSubstr("a")))); 1667} 1668 1669TEST(PairTest, SafelyCastsInnerMatchers) { 1670 Matcher<int> is_positive = Gt(0); 1671 Matcher<int> is_negative = Lt(0); 1672 pair<char, bool> p('a', true); 1673 EXPECT_THAT(p, Pair(is_positive, _)); 1674 EXPECT_THAT(p, Not(Pair(is_negative, _))); 1675 EXPECT_THAT(p, Pair(_, is_positive)); 1676 EXPECT_THAT(p, Not(Pair(_, is_negative))); 1677} 1678 1679TEST(PairTest, InsideContainsUsingMap) { 1680 map<int, char> container; 1681 container.insert(make_pair(1, 'a')); 1682 container.insert(make_pair(2, 'b')); 1683 container.insert(make_pair(4, 'c')); 1684 EXPECT_THAT(container, Contains(Pair(1, 'a'))); 1685 EXPECT_THAT(container, Contains(Pair(1, _))); 1686 EXPECT_THAT(container, Contains(Pair(_, 'a'))); 1687 EXPECT_THAT(container, Not(Contains(Pair(3, _)))); 1688} 1689 1690#if GTEST_LANG_CXX11 1691TEST(PairTest, UseGetInsteadOfMembers) { 1692 PairWithGet pair{7, "ABC"}; 1693 EXPECT_THAT(pair, Pair(7, "ABC")); 1694 EXPECT_THAT(pair, Pair(Ge(7), HasSubstr("AB"))); 1695 EXPECT_THAT(pair, Not(Pair(Lt(7), "ABC"))); 1696 1697 std::vector<PairWithGet> v = {{11, "Foo"}, {29, "gMockIsBestMock"}}; 1698 EXPECT_THAT(v, ElementsAre(Pair(11, string("Foo")), Pair(Ge(10), Not("")))); 1699} 1700#endif // GTEST_LANG_CXX11 1701 1702// Tests StartsWith(s). 1703 1704TEST(StartsWithTest, MatchesStringWithGivenPrefix) { 1705 const Matcher<const char*> m1 = StartsWith(std::string("")); 1706 EXPECT_TRUE(m1.Matches("Hi")); 1707 EXPECT_TRUE(m1.Matches("")); 1708 EXPECT_FALSE(m1.Matches(NULL)); 1709 1710 const Matcher<const std::string&> m2 = StartsWith("Hi"); 1711 EXPECT_TRUE(m2.Matches("Hi")); 1712 EXPECT_TRUE(m2.Matches("Hi Hi!")); 1713 EXPECT_TRUE(m2.Matches("High")); 1714 EXPECT_FALSE(m2.Matches("H")); 1715 EXPECT_FALSE(m2.Matches(" Hi")); 1716} 1717 1718TEST(StartsWithTest, CanDescribeSelf) { 1719 Matcher<const std::string> m = StartsWith("Hi"); 1720 EXPECT_EQ("starts with \"Hi\"", Describe(m)); 1721} 1722 1723// Tests EndsWith(s). 1724 1725TEST(EndsWithTest, MatchesStringWithGivenSuffix) { 1726 const Matcher<const char*> m1 = EndsWith(""); 1727 EXPECT_TRUE(m1.Matches("Hi")); 1728 EXPECT_TRUE(m1.Matches("")); 1729 EXPECT_FALSE(m1.Matches(NULL)); 1730 1731 const Matcher<const std::string&> m2 = EndsWith(std::string("Hi")); 1732 EXPECT_TRUE(m2.Matches("Hi")); 1733 EXPECT_TRUE(m2.Matches("Wow Hi Hi")); 1734 EXPECT_TRUE(m2.Matches("Super Hi")); 1735 EXPECT_FALSE(m2.Matches("i")); 1736 EXPECT_FALSE(m2.Matches("Hi ")); 1737 1738#if GTEST_HAS_GLOBAL_STRING 1739 const Matcher<const ::string&> m3 = EndsWith(::string("Hi")); 1740 EXPECT_TRUE(m3.Matches("Hi")); 1741 EXPECT_TRUE(m3.Matches("Wow Hi Hi")); 1742 EXPECT_TRUE(m3.Matches("Super Hi")); 1743 EXPECT_FALSE(m3.Matches("i")); 1744 EXPECT_FALSE(m3.Matches("Hi ")); 1745#endif // GTEST_HAS_GLOBAL_STRING 1746 1747#if GTEST_HAS_ABSL 1748 const Matcher<const absl::string_view&> m4 = EndsWith(""); 1749 EXPECT_TRUE(m4.Matches("Hi")); 1750 EXPECT_TRUE(m4.Matches("")); 1751 // Default-constructed absl::string_view should not match anything, in order 1752 // to distinguish it from an empty string. 1753 EXPECT_FALSE(m4.Matches(absl::string_view())); 1754#endif // GTEST_HAS_ABSL 1755} 1756 1757TEST(EndsWithTest, CanDescribeSelf) { 1758 Matcher<const std::string> m = EndsWith("Hi"); 1759 EXPECT_EQ("ends with \"Hi\"", Describe(m)); 1760} 1761 1762// Tests MatchesRegex(). 1763 1764TEST(MatchesRegexTest, MatchesStringMatchingGivenRegex) { 1765 const Matcher<const char*> m1 = MatchesRegex("a.*z"); 1766 EXPECT_TRUE(m1.Matches("az")); 1767 EXPECT_TRUE(m1.Matches("abcz")); 1768 EXPECT_FALSE(m1.Matches(NULL)); 1769 1770 const Matcher<const std::string&> m2 = MatchesRegex(new RE("a.*z")); 1771 EXPECT_TRUE(m2.Matches("azbz")); 1772 EXPECT_FALSE(m2.Matches("az1")); 1773 EXPECT_FALSE(m2.Matches("1az")); 1774 1775#if GTEST_HAS_ABSL 1776 const Matcher<const absl::string_view&> m3 = MatchesRegex("a.*z"); 1777 EXPECT_TRUE(m3.Matches(absl::string_view("az"))); 1778 EXPECT_TRUE(m3.Matches(absl::string_view("abcz"))); 1779 EXPECT_FALSE(m3.Matches(absl::string_view("1az"))); 1780 // Default-constructed absl::string_view should not match anything, in order 1781 // to distinguish it from an empty string. 1782 EXPECT_FALSE(m3.Matches(absl::string_view())); 1783 const Matcher<const absl::string_view&> m4 = MatchesRegex(""); 1784 EXPECT_FALSE(m4.Matches(absl::string_view())); 1785#endif // GTEST_HAS_ABSL 1786} 1787 1788TEST(MatchesRegexTest, CanDescribeSelf) { 1789 Matcher<const std::string> m1 = MatchesRegex(std::string("Hi.*")); 1790 EXPECT_EQ("matches regular expression \"Hi.*\"", Describe(m1)); 1791 1792 Matcher<const char*> m2 = MatchesRegex(new RE("a.*")); 1793 EXPECT_EQ("matches regular expression \"a.*\"", Describe(m2)); 1794 1795#if GTEST_HAS_ABSL 1796 Matcher<const absl::string_view> m3 = MatchesRegex(new RE("0.*")); 1797 EXPECT_EQ("matches regular expression \"0.*\"", Describe(m3)); 1798#endif // GTEST_HAS_ABSL 1799} 1800 1801// Tests ContainsRegex(). 1802 1803TEST(ContainsRegexTest, MatchesStringContainingGivenRegex) { 1804 const Matcher<const char*> m1 = ContainsRegex(std::string("a.*z")); 1805 EXPECT_TRUE(m1.Matches("az")); 1806 EXPECT_TRUE(m1.Matches("0abcz1")); 1807 EXPECT_FALSE(m1.Matches(NULL)); 1808 1809 const Matcher<const std::string&> m2 = ContainsRegex(new RE("a.*z")); 1810 EXPECT_TRUE(m2.Matches("azbz")); 1811 EXPECT_TRUE(m2.Matches("az1")); 1812 EXPECT_FALSE(m2.Matches("1a")); 1813 1814#if GTEST_HAS_ABSL 1815 const Matcher<const absl::string_view&> m3 = ContainsRegex(new RE("a.*z")); 1816 EXPECT_TRUE(m3.Matches(absl::string_view("azbz"))); 1817 EXPECT_TRUE(m3.Matches(absl::string_view("az1"))); 1818 EXPECT_FALSE(m3.Matches(absl::string_view("1a"))); 1819 // Default-constructed absl::string_view should not match anything, in order 1820 // to distinguish it from an empty string. 1821 EXPECT_FALSE(m3.Matches(absl::string_view())); 1822 const Matcher<const absl::string_view&> m4 = ContainsRegex(""); 1823 EXPECT_FALSE(m4.Matches(absl::string_view())); 1824#endif // GTEST_HAS_ABSL 1825} 1826 1827TEST(ContainsRegexTest, CanDescribeSelf) { 1828 Matcher<const std::string> m1 = ContainsRegex("Hi.*"); 1829 EXPECT_EQ("contains regular expression \"Hi.*\"", Describe(m1)); 1830 1831 Matcher<const char*> m2 = ContainsRegex(new RE("a.*")); 1832 EXPECT_EQ("contains regular expression \"a.*\"", Describe(m2)); 1833 1834#if GTEST_HAS_ABSL 1835 Matcher<const absl::string_view> m3 = ContainsRegex(new RE("0.*")); 1836 EXPECT_EQ("contains regular expression \"0.*\"", Describe(m3)); 1837#endif // GTEST_HAS_ABSL 1838} 1839 1840// Tests for wide strings. 1841#if GTEST_HAS_STD_WSTRING 1842TEST(StdWideStrEqTest, MatchesEqual) { 1843 Matcher<const wchar_t*> m = StrEq(::std::wstring(L"Hello")); 1844 EXPECT_TRUE(m.Matches(L"Hello")); 1845 EXPECT_FALSE(m.Matches(L"hello")); 1846 EXPECT_FALSE(m.Matches(NULL)); 1847 1848 Matcher<const ::std::wstring&> m2 = StrEq(L"Hello"); 1849 EXPECT_TRUE(m2.Matches(L"Hello")); 1850 EXPECT_FALSE(m2.Matches(L"Hi")); 1851 1852 Matcher<const ::std::wstring&> m3 = StrEq(L"\xD3\x576\x8D3\xC74D"); 1853 EXPECT_TRUE(m3.Matches(L"\xD3\x576\x8D3\xC74D")); 1854 EXPECT_FALSE(m3.Matches(L"\xD3\x576\x8D3\xC74E")); 1855 1856 ::std::wstring str(L"01204500800"); 1857 str[3] = L'\0'; 1858 Matcher<const ::std::wstring&> m4 = StrEq(str); 1859 EXPECT_TRUE(m4.Matches(str)); 1860 str[0] = str[6] = str[7] = str[9] = str[10] = L'\0'; 1861 Matcher<const ::std::wstring&> m5 = StrEq(str); 1862 EXPECT_TRUE(m5.Matches(str)); 1863} 1864 1865TEST(StdWideStrEqTest, CanDescribeSelf) { 1866 Matcher< ::std::wstring> m = StrEq(L"Hi-\'\"?\\\a\b\f\n\r\t\v"); 1867 EXPECT_EQ("is equal to L\"Hi-\'\\\"?\\\\\\a\\b\\f\\n\\r\\t\\v\"", 1868 Describe(m)); 1869 1870 Matcher< ::std::wstring> m2 = StrEq(L"\xD3\x576\x8D3\xC74D"); 1871 EXPECT_EQ("is equal to L\"\\xD3\\x576\\x8D3\\xC74D\"", 1872 Describe(m2)); 1873 1874 ::std::wstring str(L"01204500800"); 1875 str[3] = L'\0'; 1876 Matcher<const ::std::wstring&> m4 = StrEq(str); 1877 EXPECT_EQ("is equal to L\"012\\04500800\"", Describe(m4)); 1878 str[0] = str[6] = str[7] = str[9] = str[10] = L'\0'; 1879 Matcher<const ::std::wstring&> m5 = StrEq(str); 1880 EXPECT_EQ("is equal to L\"\\012\\045\\0\\08\\0\\0\"", Describe(m5)); 1881} 1882 1883TEST(StdWideStrNeTest, MatchesUnequalString) { 1884 Matcher<const wchar_t*> m = StrNe(L"Hello"); 1885 EXPECT_TRUE(m.Matches(L"")); 1886 EXPECT_TRUE(m.Matches(NULL)); 1887 EXPECT_FALSE(m.Matches(L"Hello")); 1888 1889 Matcher< ::std::wstring> m2 = StrNe(::std::wstring(L"Hello")); 1890 EXPECT_TRUE(m2.Matches(L"hello")); 1891 EXPECT_FALSE(m2.Matches(L"Hello")); 1892} 1893 1894TEST(StdWideStrNeTest, CanDescribeSelf) { 1895 Matcher<const wchar_t*> m = StrNe(L"Hi"); 1896 EXPECT_EQ("isn't equal to L\"Hi\"", Describe(m)); 1897} 1898 1899TEST(StdWideStrCaseEqTest, MatchesEqualStringIgnoringCase) { 1900 Matcher<const wchar_t*> m = StrCaseEq(::std::wstring(L"Hello")); 1901 EXPECT_TRUE(m.Matches(L"Hello")); 1902 EXPECT_TRUE(m.Matches(L"hello")); 1903 EXPECT_FALSE(m.Matches(L"Hi")); 1904 EXPECT_FALSE(m.Matches(NULL)); 1905 1906 Matcher<const ::std::wstring&> m2 = StrCaseEq(L"Hello"); 1907 EXPECT_TRUE(m2.Matches(L"hello")); 1908 EXPECT_FALSE(m2.Matches(L"Hi")); 1909} 1910 1911TEST(StdWideStrCaseEqTest, MatchesEqualStringWith0IgnoringCase) { 1912 ::std::wstring str1(L"oabocdooeoo"); 1913 ::std::wstring str2(L"OABOCDOOEOO"); 1914 Matcher<const ::std::wstring&> m0 = StrCaseEq(str1); 1915 EXPECT_FALSE(m0.Matches(str2 + ::std::wstring(1, L'\0'))); 1916 1917 str1[3] = str2[3] = L'\0'; 1918 Matcher<const ::std::wstring&> m1 = StrCaseEq(str1); 1919 EXPECT_TRUE(m1.Matches(str2)); 1920 1921 str1[0] = str1[6] = str1[7] = str1[10] = L'\0'; 1922 str2[0] = str2[6] = str2[7] = str2[10] = L'\0'; 1923 Matcher<const ::std::wstring&> m2 = StrCaseEq(str1); 1924 str1[9] = str2[9] = L'\0'; 1925 EXPECT_FALSE(m2.Matches(str2)); 1926 1927 Matcher<const ::std::wstring&> m3 = StrCaseEq(str1); 1928 EXPECT_TRUE(m3.Matches(str2)); 1929 1930 EXPECT_FALSE(m3.Matches(str2 + L"x")); 1931 str2.append(1, L'\0'); 1932 EXPECT_FALSE(m3.Matches(str2)); 1933 EXPECT_FALSE(m3.Matches(::std::wstring(str2, 0, 9))); 1934} 1935 1936TEST(StdWideStrCaseEqTest, CanDescribeSelf) { 1937 Matcher< ::std::wstring> m = StrCaseEq(L"Hi"); 1938 EXPECT_EQ("is equal to (ignoring case) L\"Hi\"", Describe(m)); 1939} 1940 1941TEST(StdWideStrCaseNeTest, MatchesUnequalStringIgnoringCase) { 1942 Matcher<const wchar_t*> m = StrCaseNe(L"Hello"); 1943 EXPECT_TRUE(m.Matches(L"Hi")); 1944 EXPECT_TRUE(m.Matches(NULL)); 1945 EXPECT_FALSE(m.Matches(L"Hello")); 1946 EXPECT_FALSE(m.Matches(L"hello")); 1947 1948 Matcher< ::std::wstring> m2 = StrCaseNe(::std::wstring(L"Hello")); 1949 EXPECT_TRUE(m2.Matches(L"")); 1950 EXPECT_FALSE(m2.Matches(L"Hello")); 1951} 1952 1953TEST(StdWideStrCaseNeTest, CanDescribeSelf) { 1954 Matcher<const wchar_t*> m = StrCaseNe(L"Hi"); 1955 EXPECT_EQ("isn't equal to (ignoring case) L\"Hi\"", Describe(m)); 1956} 1957 1958// Tests that HasSubstr() works for matching wstring-typed values. 1959TEST(StdWideHasSubstrTest, WorksForStringClasses) { 1960 const Matcher< ::std::wstring> m1 = HasSubstr(L"foo"); 1961 EXPECT_TRUE(m1.Matches(::std::wstring(L"I love food."))); 1962 EXPECT_FALSE(m1.Matches(::std::wstring(L"tofo"))); 1963 1964 const Matcher<const ::std::wstring&> m2 = HasSubstr(L"foo"); 1965 EXPECT_TRUE(m2.Matches(::std::wstring(L"I love food."))); 1966 EXPECT_FALSE(m2.Matches(::std::wstring(L"tofo"))); 1967} 1968 1969// Tests that HasSubstr() works for matching C-wide-string-typed values. 1970TEST(StdWideHasSubstrTest, WorksForCStrings) { 1971 const Matcher<wchar_t*> m1 = HasSubstr(L"foo"); 1972 EXPECT_TRUE(m1.Matches(const_cast<wchar_t*>(L"I love food."))); 1973 EXPECT_FALSE(m1.Matches(const_cast<wchar_t*>(L"tofo"))); 1974 EXPECT_FALSE(m1.Matches(NULL)); 1975 1976 const Matcher<const wchar_t*> m2 = HasSubstr(L"foo"); 1977 EXPECT_TRUE(m2.Matches(L"I love food.")); 1978 EXPECT_FALSE(m2.Matches(L"tofo")); 1979 EXPECT_FALSE(m2.Matches(NULL)); 1980} 1981 1982// Tests that HasSubstr(s) describes itself properly. 1983TEST(StdWideHasSubstrTest, CanDescribeSelf) { 1984 Matcher< ::std::wstring> m = HasSubstr(L"foo\n\""); 1985 EXPECT_EQ("has substring L\"foo\\n\\\"\"", Describe(m)); 1986} 1987 1988// Tests StartsWith(s). 1989 1990TEST(StdWideStartsWithTest, MatchesStringWithGivenPrefix) { 1991 const Matcher<const wchar_t*> m1 = StartsWith(::std::wstring(L"")); 1992 EXPECT_TRUE(m1.Matches(L"Hi")); 1993 EXPECT_TRUE(m1.Matches(L"")); 1994 EXPECT_FALSE(m1.Matches(NULL)); 1995 1996 const Matcher<const ::std::wstring&> m2 = StartsWith(L"Hi"); 1997 EXPECT_TRUE(m2.Matches(L"Hi")); 1998 EXPECT_TRUE(m2.Matches(L"Hi Hi!")); 1999 EXPECT_TRUE(m2.Matches(L"High")); 2000 EXPECT_FALSE(m2.Matches(L"H")); 2001 EXPECT_FALSE(m2.Matches(L" Hi")); 2002} 2003 2004TEST(StdWideStartsWithTest, CanDescribeSelf) { 2005 Matcher<const ::std::wstring> m = StartsWith(L"Hi"); 2006 EXPECT_EQ("starts with L\"Hi\"", Describe(m)); 2007} 2008 2009// Tests EndsWith(s). 2010 2011TEST(StdWideEndsWithTest, MatchesStringWithGivenSuffix) { 2012 const Matcher<const wchar_t*> m1 = EndsWith(L""); 2013 EXPECT_TRUE(m1.Matches(L"Hi")); 2014 EXPECT_TRUE(m1.Matches(L"")); 2015 EXPECT_FALSE(m1.Matches(NULL)); 2016 2017 const Matcher<const ::std::wstring&> m2 = EndsWith(::std::wstring(L"Hi")); 2018 EXPECT_TRUE(m2.Matches(L"Hi")); 2019 EXPECT_TRUE(m2.Matches(L"Wow Hi Hi")); 2020 EXPECT_TRUE(m2.Matches(L"Super Hi")); 2021 EXPECT_FALSE(m2.Matches(L"i")); 2022 EXPECT_FALSE(m2.Matches(L"Hi ")); 2023} 2024 2025TEST(StdWideEndsWithTest, CanDescribeSelf) { 2026 Matcher<const ::std::wstring> m = EndsWith(L"Hi"); 2027 EXPECT_EQ("ends with L\"Hi\"", Describe(m)); 2028} 2029 2030#endif // GTEST_HAS_STD_WSTRING 2031 2032#if GTEST_HAS_GLOBAL_WSTRING 2033TEST(GlobalWideStrEqTest, MatchesEqual) { 2034 Matcher<const wchar_t*> m = StrEq(::wstring(L"Hello")); 2035 EXPECT_TRUE(m.Matches(L"Hello")); 2036 EXPECT_FALSE(m.Matches(L"hello")); 2037 EXPECT_FALSE(m.Matches(NULL)); 2038 2039 Matcher<const ::wstring&> m2 = StrEq(L"Hello"); 2040 EXPECT_TRUE(m2.Matches(L"Hello")); 2041 EXPECT_FALSE(m2.Matches(L"Hi")); 2042 2043 Matcher<const ::wstring&> m3 = StrEq(L"\xD3\x576\x8D3\xC74D"); 2044 EXPECT_TRUE(m3.Matches(L"\xD3\x576\x8D3\xC74D")); 2045 EXPECT_FALSE(m3.Matches(L"\xD3\x576\x8D3\xC74E")); 2046 2047 ::wstring str(L"01204500800"); 2048 str[3] = L'\0'; 2049 Matcher<const ::wstring&> m4 = StrEq(str); 2050 EXPECT_TRUE(m4.Matches(str)); 2051 str[0] = str[6] = str[7] = str[9] = str[10] = L'\0'; 2052 Matcher<const ::wstring&> m5 = StrEq(str); 2053 EXPECT_TRUE(m5.Matches(str)); 2054} 2055 2056TEST(GlobalWideStrEqTest, CanDescribeSelf) { 2057 Matcher< ::wstring> m = StrEq(L"Hi-\'\"?\\\a\b\f\n\r\t\v"); 2058 EXPECT_EQ("is equal to L\"Hi-\'\\\"?\\\\\\a\\b\\f\\n\\r\\t\\v\"", 2059 Describe(m)); 2060 2061 Matcher< ::wstring> m2 = StrEq(L"\xD3\x576\x8D3\xC74D"); 2062 EXPECT_EQ("is equal to L\"\\xD3\\x576\\x8D3\\xC74D\"", 2063 Describe(m2)); 2064 2065 ::wstring str(L"01204500800"); 2066 str[3] = L'\0'; 2067 Matcher<const ::wstring&> m4 = StrEq(str); 2068 EXPECT_EQ("is equal to L\"012\\04500800\"", Describe(m4)); 2069 str[0] = str[6] = str[7] = str[9] = str[10] = L'\0'; 2070 Matcher<const ::wstring&> m5 = StrEq(str); 2071 EXPECT_EQ("is equal to L\"\\012\\045\\0\\08\\0\\0\"", Describe(m5)); 2072} 2073 2074TEST(GlobalWideStrNeTest, MatchesUnequalString) { 2075 Matcher<const wchar_t*> m = StrNe(L"Hello"); 2076 EXPECT_TRUE(m.Matches(L"")); 2077 EXPECT_TRUE(m.Matches(NULL)); 2078 EXPECT_FALSE(m.Matches(L"Hello")); 2079 2080 Matcher< ::wstring> m2 = StrNe(::wstring(L"Hello")); 2081 EXPECT_TRUE(m2.Matches(L"hello")); 2082 EXPECT_FALSE(m2.Matches(L"Hello")); 2083} 2084 2085TEST(GlobalWideStrNeTest, CanDescribeSelf) { 2086 Matcher<const wchar_t*> m = StrNe(L"Hi"); 2087 EXPECT_EQ("isn't equal to L\"Hi\"", Describe(m)); 2088} 2089 2090TEST(GlobalWideStrCaseEqTest, MatchesEqualStringIgnoringCase) { 2091 Matcher<const wchar_t*> m = StrCaseEq(::wstring(L"Hello")); 2092 EXPECT_TRUE(m.Matches(L"Hello")); 2093 EXPECT_TRUE(m.Matches(L"hello")); 2094 EXPECT_FALSE(m.Matches(L"Hi")); 2095 EXPECT_FALSE(m.Matches(NULL)); 2096 2097 Matcher<const ::wstring&> m2 = StrCaseEq(L"Hello"); 2098 EXPECT_TRUE(m2.Matches(L"hello")); 2099 EXPECT_FALSE(m2.Matches(L"Hi")); 2100} 2101 2102TEST(GlobalWideStrCaseEqTest, MatchesEqualStringWith0IgnoringCase) { 2103 ::wstring str1(L"oabocdooeoo"); 2104 ::wstring str2(L"OABOCDOOEOO"); 2105 Matcher<const ::wstring&> m0 = StrCaseEq(str1); 2106 EXPECT_FALSE(m0.Matches(str2 + ::wstring(1, L'\0'))); 2107 2108 str1[3] = str2[3] = L'\0'; 2109 Matcher<const ::wstring&> m1 = StrCaseEq(str1); 2110 EXPECT_TRUE(m1.Matches(str2)); 2111 2112 str1[0] = str1[6] = str1[7] = str1[10] = L'\0'; 2113 str2[0] = str2[6] = str2[7] = str2[10] = L'\0'; 2114 Matcher<const ::wstring&> m2 = StrCaseEq(str1); 2115 str1[9] = str2[9] = L'\0'; 2116 EXPECT_FALSE(m2.Matches(str2)); 2117 2118 Matcher<const ::wstring&> m3 = StrCaseEq(str1); 2119 EXPECT_TRUE(m3.Matches(str2)); 2120 2121 EXPECT_FALSE(m3.Matches(str2 + L"x")); 2122 str2.append(1, L'\0'); 2123 EXPECT_FALSE(m3.Matches(str2)); 2124 EXPECT_FALSE(m3.Matches(::wstring(str2, 0, 9))); 2125} 2126 2127TEST(GlobalWideStrCaseEqTest, CanDescribeSelf) { 2128 Matcher< ::wstring> m = StrCaseEq(L"Hi"); 2129 EXPECT_EQ("is equal to (ignoring case) L\"Hi\"", Describe(m)); 2130} 2131 2132TEST(GlobalWideStrCaseNeTest, MatchesUnequalStringIgnoringCase) { 2133 Matcher<const wchar_t*> m = StrCaseNe(L"Hello"); 2134 EXPECT_TRUE(m.Matches(L"Hi")); 2135 EXPECT_TRUE(m.Matches(NULL)); 2136 EXPECT_FALSE(m.Matches(L"Hello")); 2137 EXPECT_FALSE(m.Matches(L"hello")); 2138 2139 Matcher< ::wstring> m2 = StrCaseNe(::wstring(L"Hello")); 2140 EXPECT_TRUE(m2.Matches(L"")); 2141 EXPECT_FALSE(m2.Matches(L"Hello")); 2142} 2143 2144TEST(GlobalWideStrCaseNeTest, CanDescribeSelf) { 2145 Matcher<const wchar_t*> m = StrCaseNe(L"Hi"); 2146 EXPECT_EQ("isn't equal to (ignoring case) L\"Hi\"", Describe(m)); 2147} 2148 2149// Tests that HasSubstr() works for matching wstring-typed values. 2150TEST(GlobalWideHasSubstrTest, WorksForStringClasses) { 2151 const Matcher< ::wstring> m1 = HasSubstr(L"foo"); 2152 EXPECT_TRUE(m1.Matches(::wstring(L"I love food."))); 2153 EXPECT_FALSE(m1.Matches(::wstring(L"tofo"))); 2154 2155 const Matcher<const ::wstring&> m2 = HasSubstr(L"foo"); 2156 EXPECT_TRUE(m2.Matches(::wstring(L"I love food."))); 2157 EXPECT_FALSE(m2.Matches(::wstring(L"tofo"))); 2158} 2159 2160// Tests that HasSubstr() works for matching C-wide-string-typed values. 2161TEST(GlobalWideHasSubstrTest, WorksForCStrings) { 2162 const Matcher<wchar_t*> m1 = HasSubstr(L"foo"); 2163 EXPECT_TRUE(m1.Matches(const_cast<wchar_t*>(L"I love food."))); 2164 EXPECT_FALSE(m1.Matches(const_cast<wchar_t*>(L"tofo"))); 2165 EXPECT_FALSE(m1.Matches(NULL)); 2166 2167 const Matcher<const wchar_t*> m2 = HasSubstr(L"foo"); 2168 EXPECT_TRUE(m2.Matches(L"I love food.")); 2169 EXPECT_FALSE(m2.Matches(L"tofo")); 2170 EXPECT_FALSE(m2.Matches(NULL)); 2171} 2172 2173// Tests that HasSubstr(s) describes itself properly. 2174TEST(GlobalWideHasSubstrTest, CanDescribeSelf) { 2175 Matcher< ::wstring> m = HasSubstr(L"foo\n\""); 2176 EXPECT_EQ("has substring L\"foo\\n\\\"\"", Describe(m)); 2177} 2178 2179// Tests StartsWith(s). 2180 2181TEST(GlobalWideStartsWithTest, MatchesStringWithGivenPrefix) { 2182 const Matcher<const wchar_t*> m1 = StartsWith(::wstring(L"")); 2183 EXPECT_TRUE(m1.Matches(L"Hi")); 2184 EXPECT_TRUE(m1.Matches(L"")); 2185 EXPECT_FALSE(m1.Matches(NULL)); 2186 2187 const Matcher<const ::wstring&> m2 = StartsWith(L"Hi"); 2188 EXPECT_TRUE(m2.Matches(L"Hi")); 2189 EXPECT_TRUE(m2.Matches(L"Hi Hi!")); 2190 EXPECT_TRUE(m2.Matches(L"High")); 2191 EXPECT_FALSE(m2.Matches(L"H")); 2192 EXPECT_FALSE(m2.Matches(L" Hi")); 2193} 2194 2195TEST(GlobalWideStartsWithTest, CanDescribeSelf) { 2196 Matcher<const ::wstring> m = StartsWith(L"Hi"); 2197 EXPECT_EQ("starts with L\"Hi\"", Describe(m)); 2198} 2199 2200// Tests EndsWith(s). 2201 2202TEST(GlobalWideEndsWithTest, MatchesStringWithGivenSuffix) { 2203 const Matcher<const wchar_t*> m1 = EndsWith(L""); 2204 EXPECT_TRUE(m1.Matches(L"Hi")); 2205 EXPECT_TRUE(m1.Matches(L"")); 2206 EXPECT_FALSE(m1.Matches(NULL)); 2207 2208 const Matcher<const ::wstring&> m2 = EndsWith(::wstring(L"Hi")); 2209 EXPECT_TRUE(m2.Matches(L"Hi")); 2210 EXPECT_TRUE(m2.Matches(L"Wow Hi Hi")); 2211 EXPECT_TRUE(m2.Matches(L"Super Hi")); 2212 EXPECT_FALSE(m2.Matches(L"i")); 2213 EXPECT_FALSE(m2.Matches(L"Hi ")); 2214} 2215 2216TEST(GlobalWideEndsWithTest, CanDescribeSelf) { 2217 Matcher<const ::wstring> m = EndsWith(L"Hi"); 2218 EXPECT_EQ("ends with L\"Hi\"", Describe(m)); 2219} 2220 2221#endif // GTEST_HAS_GLOBAL_WSTRING 2222 2223 2224typedef ::testing::tuple<long, int> Tuple2; // NOLINT 2225 2226// Tests that Eq() matches a 2-tuple where the first field == the 2227// second field. 2228TEST(Eq2Test, MatchesEqualArguments) { 2229 Matcher<const Tuple2&> m = Eq(); 2230 EXPECT_TRUE(m.Matches(Tuple2(5L, 5))); 2231 EXPECT_FALSE(m.Matches(Tuple2(5L, 6))); 2232} 2233 2234// Tests that Eq() describes itself properly. 2235TEST(Eq2Test, CanDescribeSelf) { 2236 Matcher<const Tuple2&> m = Eq(); 2237 EXPECT_EQ("are an equal pair", Describe(m)); 2238} 2239 2240// Tests that Ge() matches a 2-tuple where the first field >= the 2241// second field. 2242TEST(Ge2Test, MatchesGreaterThanOrEqualArguments) { 2243 Matcher<const Tuple2&> m = Ge(); 2244 EXPECT_TRUE(m.Matches(Tuple2(5L, 4))); 2245 EXPECT_TRUE(m.Matches(Tuple2(5L, 5))); 2246 EXPECT_FALSE(m.Matches(Tuple2(5L, 6))); 2247} 2248 2249// Tests that Ge() describes itself properly. 2250TEST(Ge2Test, CanDescribeSelf) { 2251 Matcher<const Tuple2&> m = Ge(); 2252 EXPECT_EQ("are a pair where the first >= the second", Describe(m)); 2253} 2254 2255// Tests that Gt() matches a 2-tuple where the first field > the 2256// second field. 2257TEST(Gt2Test, MatchesGreaterThanArguments) { 2258 Matcher<const Tuple2&> m = Gt(); 2259 EXPECT_TRUE(m.Matches(Tuple2(5L, 4))); 2260 EXPECT_FALSE(m.Matches(Tuple2(5L, 5))); 2261 EXPECT_FALSE(m.Matches(Tuple2(5L, 6))); 2262} 2263 2264// Tests that Gt() describes itself properly. 2265TEST(Gt2Test, CanDescribeSelf) { 2266 Matcher<const Tuple2&> m = Gt(); 2267 EXPECT_EQ("are a pair where the first > the second", Describe(m)); 2268} 2269 2270// Tests that Le() matches a 2-tuple where the first field <= the 2271// second field. 2272TEST(Le2Test, MatchesLessThanOrEqualArguments) { 2273 Matcher<const Tuple2&> m = Le(); 2274 EXPECT_TRUE(m.Matches(Tuple2(5L, 6))); 2275 EXPECT_TRUE(m.Matches(Tuple2(5L, 5))); 2276 EXPECT_FALSE(m.Matches(Tuple2(5L, 4))); 2277} 2278 2279// Tests that Le() describes itself properly. 2280TEST(Le2Test, CanDescribeSelf) { 2281 Matcher<const Tuple2&> m = Le(); 2282 EXPECT_EQ("are a pair where the first <= the second", Describe(m)); 2283} 2284 2285// Tests that Lt() matches a 2-tuple where the first field < the 2286// second field. 2287TEST(Lt2Test, MatchesLessThanArguments) { 2288 Matcher<const Tuple2&> m = Lt(); 2289 EXPECT_TRUE(m.Matches(Tuple2(5L, 6))); 2290 EXPECT_FALSE(m.Matches(Tuple2(5L, 5))); 2291 EXPECT_FALSE(m.Matches(Tuple2(5L, 4))); 2292} 2293 2294// Tests that Lt() describes itself properly. 2295TEST(Lt2Test, CanDescribeSelf) { 2296 Matcher<const Tuple2&> m = Lt(); 2297 EXPECT_EQ("are a pair where the first < the second", Describe(m)); 2298} 2299 2300// Tests that Ne() matches a 2-tuple where the first field != the 2301// second field. 2302TEST(Ne2Test, MatchesUnequalArguments) { 2303 Matcher<const Tuple2&> m = Ne(); 2304 EXPECT_TRUE(m.Matches(Tuple2(5L, 6))); 2305 EXPECT_TRUE(m.Matches(Tuple2(5L, 4))); 2306 EXPECT_FALSE(m.Matches(Tuple2(5L, 5))); 2307} 2308 2309// Tests that Ne() describes itself properly. 2310TEST(Ne2Test, CanDescribeSelf) { 2311 Matcher<const Tuple2&> m = Ne(); 2312 EXPECT_EQ("are an unequal pair", Describe(m)); 2313} 2314 2315// Tests that FloatEq() matches a 2-tuple where 2316// FloatEq(first field) matches the second field. 2317TEST(FloatEq2Test, MatchesEqualArguments) { 2318 typedef ::testing::tuple<float, float> Tpl; 2319 Matcher<const Tpl&> m = FloatEq(); 2320 EXPECT_TRUE(m.Matches(Tpl(1.0f, 1.0f))); 2321 EXPECT_TRUE(m.Matches(Tpl(0.3f, 0.1f + 0.1f + 0.1f))); 2322 EXPECT_FALSE(m.Matches(Tpl(1.1f, 1.0f))); 2323} 2324 2325// Tests that FloatEq() describes itself properly. 2326TEST(FloatEq2Test, CanDescribeSelf) { 2327 Matcher<const ::testing::tuple<float, float>&> m = FloatEq(); 2328 EXPECT_EQ("are an almost-equal pair", Describe(m)); 2329} 2330 2331// Tests that NanSensitiveFloatEq() matches a 2-tuple where 2332// NanSensitiveFloatEq(first field) matches the second field. 2333TEST(NanSensitiveFloatEqTest, MatchesEqualArgumentsWithNaN) { 2334 typedef ::testing::tuple<float, float> Tpl; 2335 Matcher<const Tpl&> m = NanSensitiveFloatEq(); 2336 EXPECT_TRUE(m.Matches(Tpl(1.0f, 1.0f))); 2337 EXPECT_TRUE(m.Matches(Tpl(std::numeric_limits<float>::quiet_NaN(), 2338 std::numeric_limits<float>::quiet_NaN()))); 2339 EXPECT_FALSE(m.Matches(Tpl(1.1f, 1.0f))); 2340 EXPECT_FALSE(m.Matches(Tpl(1.0f, std::numeric_limits<float>::quiet_NaN()))); 2341 EXPECT_FALSE(m.Matches(Tpl(std::numeric_limits<float>::quiet_NaN(), 1.0f))); 2342} 2343 2344// Tests that NanSensitiveFloatEq() describes itself properly. 2345TEST(NanSensitiveFloatEqTest, CanDescribeSelfWithNaNs) { 2346 Matcher<const ::testing::tuple<float, float>&> m = NanSensitiveFloatEq(); 2347 EXPECT_EQ("are an almost-equal pair", Describe(m)); 2348} 2349 2350// Tests that DoubleEq() matches a 2-tuple where 2351// DoubleEq(first field) matches the second field. 2352TEST(DoubleEq2Test, MatchesEqualArguments) { 2353 typedef ::testing::tuple<double, double> Tpl; 2354 Matcher<const Tpl&> m = DoubleEq(); 2355 EXPECT_TRUE(m.Matches(Tpl(1.0, 1.0))); 2356 EXPECT_TRUE(m.Matches(Tpl(0.3, 0.1 + 0.1 + 0.1))); 2357 EXPECT_FALSE(m.Matches(Tpl(1.1, 1.0))); 2358} 2359 2360// Tests that DoubleEq() describes itself properly. 2361TEST(DoubleEq2Test, CanDescribeSelf) { 2362 Matcher<const ::testing::tuple<double, double>&> m = DoubleEq(); 2363 EXPECT_EQ("are an almost-equal pair", Describe(m)); 2364} 2365 2366// Tests that NanSensitiveDoubleEq() matches a 2-tuple where 2367// NanSensitiveDoubleEq(first field) matches the second field. 2368TEST(NanSensitiveDoubleEqTest, MatchesEqualArgumentsWithNaN) { 2369 typedef ::testing::tuple<double, double> Tpl; 2370 Matcher<const Tpl&> m = NanSensitiveDoubleEq(); 2371 EXPECT_TRUE(m.Matches(Tpl(1.0f, 1.0f))); 2372 EXPECT_TRUE(m.Matches(Tpl(std::numeric_limits<double>::quiet_NaN(), 2373 std::numeric_limits<double>::quiet_NaN()))); 2374 EXPECT_FALSE(m.Matches(Tpl(1.1f, 1.0f))); 2375 EXPECT_FALSE(m.Matches(Tpl(1.0f, std::numeric_limits<double>::quiet_NaN()))); 2376 EXPECT_FALSE(m.Matches(Tpl(std::numeric_limits<double>::quiet_NaN(), 1.0f))); 2377} 2378 2379// Tests that DoubleEq() describes itself properly. 2380TEST(NanSensitiveDoubleEqTest, CanDescribeSelfWithNaNs) { 2381 Matcher<const ::testing::tuple<double, double>&> m = NanSensitiveDoubleEq(); 2382 EXPECT_EQ("are an almost-equal pair", Describe(m)); 2383} 2384 2385// Tests that FloatEq() matches a 2-tuple where 2386// FloatNear(first field, max_abs_error) matches the second field. 2387TEST(FloatNear2Test, MatchesEqualArguments) { 2388 typedef ::testing::tuple<float, float> Tpl; 2389 Matcher<const Tpl&> m = FloatNear(0.5f); 2390 EXPECT_TRUE(m.Matches(Tpl(1.0f, 1.0f))); 2391 EXPECT_TRUE(m.Matches(Tpl(1.3f, 1.0f))); 2392 EXPECT_FALSE(m.Matches(Tpl(1.8f, 1.0f))); 2393} 2394 2395// Tests that FloatNear() describes itself properly. 2396TEST(FloatNear2Test, CanDescribeSelf) { 2397 Matcher<const ::testing::tuple<float, float>&> m = FloatNear(0.5f); 2398 EXPECT_EQ("are an almost-equal pair", Describe(m)); 2399} 2400 2401// Tests that NanSensitiveFloatNear() matches a 2-tuple where 2402// NanSensitiveFloatNear(first field) matches the second field. 2403TEST(NanSensitiveFloatNearTest, MatchesNearbyArgumentsWithNaN) { 2404 typedef ::testing::tuple<float, float> Tpl; 2405 Matcher<const Tpl&> m = NanSensitiveFloatNear(0.5f); 2406 EXPECT_TRUE(m.Matches(Tpl(1.0f, 1.0f))); 2407 EXPECT_TRUE(m.Matches(Tpl(1.1f, 1.0f))); 2408 EXPECT_TRUE(m.Matches(Tpl(std::numeric_limits<float>::quiet_NaN(), 2409 std::numeric_limits<float>::quiet_NaN()))); 2410 EXPECT_FALSE(m.Matches(Tpl(1.6f, 1.0f))); 2411 EXPECT_FALSE(m.Matches(Tpl(1.0f, std::numeric_limits<float>::quiet_NaN()))); 2412 EXPECT_FALSE(m.Matches(Tpl(std::numeric_limits<float>::quiet_NaN(), 1.0f))); 2413} 2414 2415// Tests that NanSensitiveFloatNear() describes itself properly. 2416TEST(NanSensitiveFloatNearTest, CanDescribeSelfWithNaNs) { 2417 Matcher<const ::testing::tuple<float, float>&> m = 2418 NanSensitiveFloatNear(0.5f); 2419 EXPECT_EQ("are an almost-equal pair", Describe(m)); 2420} 2421 2422// Tests that FloatEq() matches a 2-tuple where 2423// DoubleNear(first field, max_abs_error) matches the second field. 2424TEST(DoubleNear2Test, MatchesEqualArguments) { 2425 typedef ::testing::tuple<double, double> Tpl; 2426 Matcher<const Tpl&> m = DoubleNear(0.5); 2427 EXPECT_TRUE(m.Matches(Tpl(1.0, 1.0))); 2428 EXPECT_TRUE(m.Matches(Tpl(1.3, 1.0))); 2429 EXPECT_FALSE(m.Matches(Tpl(1.8, 1.0))); 2430} 2431 2432// Tests that DoubleNear() describes itself properly. 2433TEST(DoubleNear2Test, CanDescribeSelf) { 2434 Matcher<const ::testing::tuple<double, double>&> m = DoubleNear(0.5); 2435 EXPECT_EQ("are an almost-equal pair", Describe(m)); 2436} 2437 2438// Tests that NanSensitiveDoubleNear() matches a 2-tuple where 2439// NanSensitiveDoubleNear(first field) matches the second field. 2440TEST(NanSensitiveDoubleNearTest, MatchesNearbyArgumentsWithNaN) { 2441 typedef ::testing::tuple<double, double> Tpl; 2442 Matcher<const Tpl&> m = NanSensitiveDoubleNear(0.5f); 2443 EXPECT_TRUE(m.Matches(Tpl(1.0f, 1.0f))); 2444 EXPECT_TRUE(m.Matches(Tpl(1.1f, 1.0f))); 2445 EXPECT_TRUE(m.Matches(Tpl(std::numeric_limits<double>::quiet_NaN(), 2446 std::numeric_limits<double>::quiet_NaN()))); 2447 EXPECT_FALSE(m.Matches(Tpl(1.6f, 1.0f))); 2448 EXPECT_FALSE(m.Matches(Tpl(1.0f, std::numeric_limits<double>::quiet_NaN()))); 2449 EXPECT_FALSE(m.Matches(Tpl(std::numeric_limits<double>::quiet_NaN(), 1.0f))); 2450} 2451 2452// Tests that NanSensitiveDoubleNear() describes itself properly. 2453TEST(NanSensitiveDoubleNearTest, CanDescribeSelfWithNaNs) { 2454 Matcher<const ::testing::tuple<double, double>&> m = 2455 NanSensitiveDoubleNear(0.5f); 2456 EXPECT_EQ("are an almost-equal pair", Describe(m)); 2457} 2458 2459// Tests that Not(m) matches any value that doesn't match m. 2460TEST(NotTest, NegatesMatcher) { 2461 Matcher<int> m; 2462 m = Not(Eq(2)); 2463 EXPECT_TRUE(m.Matches(3)); 2464 EXPECT_FALSE(m.Matches(2)); 2465} 2466 2467// Tests that Not(m) describes itself properly. 2468TEST(NotTest, CanDescribeSelf) { 2469 Matcher<int> m = Not(Eq(5)); 2470 EXPECT_EQ("isn't equal to 5", Describe(m)); 2471} 2472 2473// Tests that monomorphic matchers are safely cast by the Not matcher. 2474TEST(NotTest, NotMatcherSafelyCastsMonomorphicMatchers) { 2475 // greater_than_5 is a monomorphic matcher. 2476 Matcher<int> greater_than_5 = Gt(5); 2477 2478 Matcher<const int&> m = Not(greater_than_5); 2479 Matcher<int&> m2 = Not(greater_than_5); 2480 Matcher<int&> m3 = Not(m); 2481} 2482 2483// Helper to allow easy testing of AllOf matchers with num parameters. 2484void AllOfMatches(int num, const Matcher<int>& m) { 2485 SCOPED_TRACE(Describe(m)); 2486 EXPECT_TRUE(m.Matches(0)); 2487 for (int i = 1; i <= num; ++i) { 2488 EXPECT_FALSE(m.Matches(i)); 2489 } 2490 EXPECT_TRUE(m.Matches(num + 1)); 2491} 2492 2493// Tests that AllOf(m1, ..., mn) matches any value that matches all of 2494// the given matchers. 2495TEST(AllOfTest, MatchesWhenAllMatch) { 2496 Matcher<int> m; 2497 m = AllOf(Le(2), Ge(1)); 2498 EXPECT_TRUE(m.Matches(1)); 2499 EXPECT_TRUE(m.Matches(2)); 2500 EXPECT_FALSE(m.Matches(0)); 2501 EXPECT_FALSE(m.Matches(3)); 2502 2503 m = AllOf(Gt(0), Ne(1), Ne(2)); 2504 EXPECT_TRUE(m.Matches(3)); 2505 EXPECT_FALSE(m.Matches(2)); 2506 EXPECT_FALSE(m.Matches(1)); 2507 EXPECT_FALSE(m.Matches(0)); 2508 2509 m = AllOf(Gt(0), Ne(1), Ne(2), Ne(3)); 2510 EXPECT_TRUE(m.Matches(4)); 2511 EXPECT_FALSE(m.Matches(3)); 2512 EXPECT_FALSE(m.Matches(2)); 2513 EXPECT_FALSE(m.Matches(1)); 2514 EXPECT_FALSE(m.Matches(0)); 2515 2516 m = AllOf(Ge(0), Lt(10), Ne(3), Ne(5), Ne(7)); 2517 EXPECT_TRUE(m.Matches(0)); 2518 EXPECT_TRUE(m.Matches(1)); 2519 EXPECT_FALSE(m.Matches(3)); 2520 2521 // The following tests for varying number of sub-matchers. Due to the way 2522 // the sub-matchers are handled it is enough to test every sub-matcher once 2523 // with sub-matchers using the same matcher type. Varying matcher types are 2524 // checked for above. 2525 AllOfMatches(2, AllOf(Ne(1), Ne(2))); 2526 AllOfMatches(3, AllOf(Ne(1), Ne(2), Ne(3))); 2527 AllOfMatches(4, AllOf(Ne(1), Ne(2), Ne(3), Ne(4))); 2528 AllOfMatches(5, AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5))); 2529 AllOfMatches(6, AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5), Ne(6))); 2530 AllOfMatches(7, AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5), Ne(6), Ne(7))); 2531 AllOfMatches(8, AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5), Ne(6), Ne(7), 2532 Ne(8))); 2533 AllOfMatches(9, AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5), Ne(6), Ne(7), 2534 Ne(8), Ne(9))); 2535 AllOfMatches(10, AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5), Ne(6), Ne(7), Ne(8), 2536 Ne(9), Ne(10))); 2537} 2538 2539#if GTEST_LANG_CXX11 2540// Tests the variadic version of the AllOfMatcher. 2541TEST(AllOfTest, VariadicMatchesWhenAllMatch) { 2542 // Make sure AllOf is defined in the right namespace and does not depend on 2543 // ADL. 2544 ::testing::AllOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11); 2545 Matcher<int> m = AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5), Ne(6), Ne(7), Ne(8), 2546 Ne(9), Ne(10), Ne(11)); 2547 EXPECT_THAT(Describe(m), EndsWith("and (isn't equal to 11)")); 2548 AllOfMatches(11, m); 2549 AllOfMatches(50, AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5), Ne(6), Ne(7), Ne(8), 2550 Ne(9), Ne(10), Ne(11), Ne(12), Ne(13), Ne(14), Ne(15), 2551 Ne(16), Ne(17), Ne(18), Ne(19), Ne(20), Ne(21), Ne(22), 2552 Ne(23), Ne(24), Ne(25), Ne(26), Ne(27), Ne(28), Ne(29), 2553 Ne(30), Ne(31), Ne(32), Ne(33), Ne(34), Ne(35), Ne(36), 2554 Ne(37), Ne(38), Ne(39), Ne(40), Ne(41), Ne(42), Ne(43), 2555 Ne(44), Ne(45), Ne(46), Ne(47), Ne(48), Ne(49), 2556 Ne(50))); 2557} 2558 2559#endif // GTEST_LANG_CXX11 2560 2561// Tests that AllOf(m1, ..., mn) describes itself properly. 2562TEST(AllOfTest, CanDescribeSelf) { 2563 Matcher<int> m; 2564 m = AllOf(Le(2), Ge(1)); 2565 EXPECT_EQ("(is <= 2) and (is >= 1)", Describe(m)); 2566 2567 m = AllOf(Gt(0), Ne(1), Ne(2)); 2568 EXPECT_EQ("(is > 0) and " 2569 "((isn't equal to 1) and " 2570 "(isn't equal to 2))", 2571 Describe(m)); 2572 2573 2574 m = AllOf(Gt(0), Ne(1), Ne(2), Ne(3)); 2575 EXPECT_EQ("((is > 0) and " 2576 "(isn't equal to 1)) and " 2577 "((isn't equal to 2) and " 2578 "(isn't equal to 3))", 2579 Describe(m)); 2580 2581 2582 m = AllOf(Ge(0), Lt(10), Ne(3), Ne(5), Ne(7)); 2583 EXPECT_EQ("((is >= 0) and " 2584 "(is < 10)) and " 2585 "((isn't equal to 3) and " 2586 "((isn't equal to 5) and " 2587 "(isn't equal to 7)))", 2588 Describe(m)); 2589} 2590 2591// Tests that AllOf(m1, ..., mn) describes its negation properly. 2592TEST(AllOfTest, CanDescribeNegation) { 2593 Matcher<int> m; 2594 m = AllOf(Le(2), Ge(1)); 2595 EXPECT_EQ("(isn't <= 2) or " 2596 "(isn't >= 1)", 2597 DescribeNegation(m)); 2598 2599 m = AllOf(Gt(0), Ne(1), Ne(2)); 2600 EXPECT_EQ("(isn't > 0) or " 2601 "((is equal to 1) or " 2602 "(is equal to 2))", 2603 DescribeNegation(m)); 2604 2605 2606 m = AllOf(Gt(0), Ne(1), Ne(2), Ne(3)); 2607 EXPECT_EQ("((isn't > 0) or " 2608 "(is equal to 1)) or " 2609 "((is equal to 2) or " 2610 "(is equal to 3))", 2611 DescribeNegation(m)); 2612 2613 2614 m = AllOf(Ge(0), Lt(10), Ne(3), Ne(5), Ne(7)); 2615 EXPECT_EQ("((isn't >= 0) or " 2616 "(isn't < 10)) or " 2617 "((is equal to 3) or " 2618 "((is equal to 5) or " 2619 "(is equal to 7)))", 2620 DescribeNegation(m)); 2621} 2622 2623// Tests that monomorphic matchers are safely cast by the AllOf matcher. 2624TEST(AllOfTest, AllOfMatcherSafelyCastsMonomorphicMatchers) { 2625 // greater_than_5 and less_than_10 are monomorphic matchers. 2626 Matcher<int> greater_than_5 = Gt(5); 2627 Matcher<int> less_than_10 = Lt(10); 2628 2629 Matcher<const int&> m = AllOf(greater_than_5, less_than_10); 2630 Matcher<int&> m2 = AllOf(greater_than_5, less_than_10); 2631 Matcher<int&> m3 = AllOf(greater_than_5, m2); 2632 2633 // Tests that BothOf works when composing itself. 2634 Matcher<const int&> m4 = AllOf(greater_than_5, less_than_10, less_than_10); 2635 Matcher<int&> m5 = AllOf(greater_than_5, less_than_10, less_than_10); 2636} 2637 2638TEST(AllOfTest, ExplainsResult) { 2639 Matcher<int> m; 2640 2641 // Successful match. Both matchers need to explain. The second 2642 // matcher doesn't give an explanation, so only the first matcher's 2643 // explanation is printed. 2644 m = AllOf(GreaterThan(10), Lt(30)); 2645 EXPECT_EQ("which is 15 more than 10", Explain(m, 25)); 2646 2647 // Successful match. Both matchers need to explain. 2648 m = AllOf(GreaterThan(10), GreaterThan(20)); 2649 EXPECT_EQ("which is 20 more than 10, and which is 10 more than 20", 2650 Explain(m, 30)); 2651 2652 // Successful match. All matchers need to explain. The second 2653 // matcher doesn't given an explanation. 2654 m = AllOf(GreaterThan(10), Lt(30), GreaterThan(20)); 2655 EXPECT_EQ("which is 15 more than 10, and which is 5 more than 20", 2656 Explain(m, 25)); 2657 2658 // Successful match. All matchers need to explain. 2659 m = AllOf(GreaterThan(10), GreaterThan(20), GreaterThan(30)); 2660 EXPECT_EQ("which is 30 more than 10, and which is 20 more than 20, " 2661 "and which is 10 more than 30", 2662 Explain(m, 40)); 2663 2664 // Failed match. The first matcher, which failed, needs to 2665 // explain. 2666 m = AllOf(GreaterThan(10), GreaterThan(20)); 2667 EXPECT_EQ("which is 5 less than 10", Explain(m, 5)); 2668 2669 // Failed match. The second matcher, which failed, needs to 2670 // explain. Since it doesn't given an explanation, nothing is 2671 // printed. 2672 m = AllOf(GreaterThan(10), Lt(30)); 2673 EXPECT_EQ("", Explain(m, 40)); 2674 2675 // Failed match. The second matcher, which failed, needs to 2676 // explain. 2677 m = AllOf(GreaterThan(10), GreaterThan(20)); 2678 EXPECT_EQ("which is 5 less than 20", Explain(m, 15)); 2679} 2680 2681// Helper to allow easy testing of AnyOf matchers with num parameters. 2682static void AnyOfMatches(int num, const Matcher<int>& m) { 2683 SCOPED_TRACE(Describe(m)); 2684 EXPECT_FALSE(m.Matches(0)); 2685 for (int i = 1; i <= num; ++i) { 2686 EXPECT_TRUE(m.Matches(i)); 2687 } 2688 EXPECT_FALSE(m.Matches(num + 1)); 2689} 2690 2691#if GTEST_LANG_CXX11 2692static void AnyOfStringMatches(int num, const Matcher<std::string>& m) { 2693 SCOPED_TRACE(Describe(m)); 2694 EXPECT_FALSE(m.Matches(std::to_string(0))); 2695 2696 for (int i = 1; i <= num; ++i) { 2697 EXPECT_TRUE(m.Matches(std::to_string(i))); 2698 } 2699 EXPECT_FALSE(m.Matches(std::to_string(num + 1))); 2700} 2701#endif 2702 2703// Tests that AnyOf(m1, ..., mn) matches any value that matches at 2704// least one of the given matchers. 2705TEST(AnyOfTest, MatchesWhenAnyMatches) { 2706 Matcher<int> m; 2707 m = AnyOf(Le(1), Ge(3)); 2708 EXPECT_TRUE(m.Matches(1)); 2709 EXPECT_TRUE(m.Matches(4)); 2710 EXPECT_FALSE(m.Matches(2)); 2711 2712 m = AnyOf(Lt(0), Eq(1), Eq(2)); 2713 EXPECT_TRUE(m.Matches(-1)); 2714 EXPECT_TRUE(m.Matches(1)); 2715 EXPECT_TRUE(m.Matches(2)); 2716 EXPECT_FALSE(m.Matches(0)); 2717 2718 m = AnyOf(Lt(0), Eq(1), Eq(2), Eq(3)); 2719 EXPECT_TRUE(m.Matches(-1)); 2720 EXPECT_TRUE(m.Matches(1)); 2721 EXPECT_TRUE(m.Matches(2)); 2722 EXPECT_TRUE(m.Matches(3)); 2723 EXPECT_FALSE(m.Matches(0)); 2724 2725 m = AnyOf(Le(0), Gt(10), 3, 5, 7); 2726 EXPECT_TRUE(m.Matches(0)); 2727 EXPECT_TRUE(m.Matches(11)); 2728 EXPECT_TRUE(m.Matches(3)); 2729 EXPECT_FALSE(m.Matches(2)); 2730 2731 // The following tests for varying number of sub-matchers. Due to the way 2732 // the sub-matchers are handled it is enough to test every sub-matcher once 2733 // with sub-matchers using the same matcher type. Varying matcher types are 2734 // checked for above. 2735 AnyOfMatches(2, AnyOf(1, 2)); 2736 AnyOfMatches(3, AnyOf(1, 2, 3)); 2737 AnyOfMatches(4, AnyOf(1, 2, 3, 4)); 2738 AnyOfMatches(5, AnyOf(1, 2, 3, 4, 5)); 2739 AnyOfMatches(6, AnyOf(1, 2, 3, 4, 5, 6)); 2740 AnyOfMatches(7, AnyOf(1, 2, 3, 4, 5, 6, 7)); 2741 AnyOfMatches(8, AnyOf(1, 2, 3, 4, 5, 6, 7, 8)); 2742 AnyOfMatches(9, AnyOf(1, 2, 3, 4, 5, 6, 7, 8, 9)); 2743 AnyOfMatches(10, AnyOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)); 2744} 2745 2746#if GTEST_LANG_CXX11 2747// Tests the variadic version of the AnyOfMatcher. 2748TEST(AnyOfTest, VariadicMatchesWhenAnyMatches) { 2749 // Also make sure AnyOf is defined in the right namespace and does not depend 2750 // on ADL. 2751 Matcher<int> m = ::testing::AnyOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11); 2752 2753 EXPECT_THAT(Describe(m), EndsWith("or (is equal to 11)")); 2754 AnyOfMatches(11, m); 2755 AnyOfMatches(50, AnyOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 2756 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 2757 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 2758 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 2759 41, 42, 43, 44, 45, 46, 47, 48, 49, 50)); 2760 AnyOfStringMatches( 2761 50, AnyOf("1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", 2762 "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", 2763 "23", "24", "25", "26", "27", "28", "29", "30", "31", "32", 2764 "33", "34", "35", "36", "37", "38", "39", "40", "41", "42", 2765 "43", "44", "45", "46", "47", "48", "49", "50")); 2766} 2767 2768// Tests the variadic version of the ElementsAreMatcher 2769TEST(ElementsAreTest, HugeMatcher) { 2770 vector<int> test_vector{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}; 2771 2772 EXPECT_THAT(test_vector, 2773 ElementsAre(Eq(1), Eq(2), Lt(13), Eq(4), Eq(5), Eq(6), Eq(7), 2774 Eq(8), Eq(9), Eq(10), Gt(1), Eq(12))); 2775} 2776 2777// Tests the variadic version of the UnorderedElementsAreMatcher 2778TEST(ElementsAreTest, HugeMatcherStr) { 2779 vector<string> test_vector{ 2780 "literal_string", "", "", "", "", "", "", "", "", "", "", ""}; 2781 2782 EXPECT_THAT(test_vector, UnorderedElementsAre("literal_string", _, _, _, _, _, 2783 _, _, _, _, _, _)); 2784} 2785 2786// Tests the variadic version of the UnorderedElementsAreMatcher 2787TEST(ElementsAreTest, HugeMatcherUnordered) { 2788 vector<int> test_vector{2, 1, 8, 5, 4, 6, 7, 3, 9, 12, 11, 10}; 2789 2790 EXPECT_THAT(test_vector, UnorderedElementsAre( 2791 Eq(2), Eq(1), Gt(7), Eq(5), Eq(4), Eq(6), Eq(7), 2792 Eq(3), Eq(9), Eq(12), Eq(11), Ne(122))); 2793} 2794 2795#endif // GTEST_LANG_CXX11 2796 2797// Tests that AnyOf(m1, ..., mn) describes itself properly. 2798TEST(AnyOfTest, CanDescribeSelf) { 2799 Matcher<int> m; 2800 m = AnyOf(Le(1), Ge(3)); 2801 EXPECT_EQ("(is <= 1) or (is >= 3)", 2802 Describe(m)); 2803 2804 m = AnyOf(Lt(0), Eq(1), Eq(2)); 2805 EXPECT_EQ("(is < 0) or " 2806 "((is equal to 1) or (is equal to 2))", 2807 Describe(m)); 2808 2809 m = AnyOf(Lt(0), Eq(1), Eq(2), Eq(3)); 2810 EXPECT_EQ("((is < 0) or " 2811 "(is equal to 1)) or " 2812 "((is equal to 2) or " 2813 "(is equal to 3))", 2814 Describe(m)); 2815 2816 m = AnyOf(Le(0), Gt(10), 3, 5, 7); 2817 EXPECT_EQ("((is <= 0) or " 2818 "(is > 10)) or " 2819 "((is equal to 3) or " 2820 "((is equal to 5) or " 2821 "(is equal to 7)))", 2822 Describe(m)); 2823} 2824 2825// Tests that AnyOf(m1, ..., mn) describes its negation properly. 2826TEST(AnyOfTest, CanDescribeNegation) { 2827 Matcher<int> m; 2828 m = AnyOf(Le(1), Ge(3)); 2829 EXPECT_EQ("(isn't <= 1) and (isn't >= 3)", 2830 DescribeNegation(m)); 2831 2832 m = AnyOf(Lt(0), Eq(1), Eq(2)); 2833 EXPECT_EQ("(isn't < 0) and " 2834 "((isn't equal to 1) and (isn't equal to 2))", 2835 DescribeNegation(m)); 2836 2837 m = AnyOf(Lt(0), Eq(1), Eq(2), Eq(3)); 2838 EXPECT_EQ("((isn't < 0) and " 2839 "(isn't equal to 1)) and " 2840 "((isn't equal to 2) and " 2841 "(isn't equal to 3))", 2842 DescribeNegation(m)); 2843 2844 m = AnyOf(Le(0), Gt(10), 3, 5, 7); 2845 EXPECT_EQ("((isn't <= 0) and " 2846 "(isn't > 10)) and " 2847 "((isn't equal to 3) and " 2848 "((isn't equal to 5) and " 2849 "(isn't equal to 7)))", 2850 DescribeNegation(m)); 2851} 2852 2853// Tests that monomorphic matchers are safely cast by the AnyOf matcher. 2854TEST(AnyOfTest, AnyOfMatcherSafelyCastsMonomorphicMatchers) { 2855 // greater_than_5 and less_than_10 are monomorphic matchers. 2856 Matcher<int> greater_than_5 = Gt(5); 2857 Matcher<int> less_than_10 = Lt(10); 2858 2859 Matcher<const int&> m = AnyOf(greater_than_5, less_than_10); 2860 Matcher<int&> m2 = AnyOf(greater_than_5, less_than_10); 2861 Matcher<int&> m3 = AnyOf(greater_than_5, m2); 2862 2863 // Tests that EitherOf works when composing itself. 2864 Matcher<const int&> m4 = AnyOf(greater_than_5, less_than_10, less_than_10); 2865 Matcher<int&> m5 = AnyOf(greater_than_5, less_than_10, less_than_10); 2866} 2867 2868TEST(AnyOfTest, ExplainsResult) { 2869 Matcher<int> m; 2870 2871 // Failed match. Both matchers need to explain. The second 2872 // matcher doesn't give an explanation, so only the first matcher's 2873 // explanation is printed. 2874 m = AnyOf(GreaterThan(10), Lt(0)); 2875 EXPECT_EQ("which is 5 less than 10", Explain(m, 5)); 2876 2877 // Failed match. Both matchers need to explain. 2878 m = AnyOf(GreaterThan(10), GreaterThan(20)); 2879 EXPECT_EQ("which is 5 less than 10, and which is 15 less than 20", 2880 Explain(m, 5)); 2881 2882 // Failed match. All matchers need to explain. The second 2883 // matcher doesn't given an explanation. 2884 m = AnyOf(GreaterThan(10), Gt(20), GreaterThan(30)); 2885 EXPECT_EQ("which is 5 less than 10, and which is 25 less than 30", 2886 Explain(m, 5)); 2887 2888 // Failed match. All matchers need to explain. 2889 m = AnyOf(GreaterThan(10), GreaterThan(20), GreaterThan(30)); 2890 EXPECT_EQ("which is 5 less than 10, and which is 15 less than 20, " 2891 "and which is 25 less than 30", 2892 Explain(m, 5)); 2893 2894 // Successful match. The first matcher, which succeeded, needs to 2895 // explain. 2896 m = AnyOf(GreaterThan(10), GreaterThan(20)); 2897 EXPECT_EQ("which is 5 more than 10", Explain(m, 15)); 2898 2899 // Successful match. The second matcher, which succeeded, needs to 2900 // explain. Since it doesn't given an explanation, nothing is 2901 // printed. 2902 m = AnyOf(GreaterThan(10), Lt(30)); 2903 EXPECT_EQ("", Explain(m, 0)); 2904 2905 // Successful match. The second matcher, which succeeded, needs to 2906 // explain. 2907 m = AnyOf(GreaterThan(30), GreaterThan(20)); 2908 EXPECT_EQ("which is 5 more than 20", Explain(m, 25)); 2909} 2910 2911// The following predicate function and predicate functor are for 2912// testing the Truly(predicate) matcher. 2913 2914// Returns non-zero if the input is positive. Note that the return 2915// type of this function is not bool. It's OK as Truly() accepts any 2916// unary function or functor whose return type can be implicitly 2917// converted to bool. 2918int IsPositive(double x) { 2919 return x > 0 ? 1 : 0; 2920} 2921 2922// This functor returns true if the input is greater than the given 2923// number. 2924class IsGreaterThan { 2925 public: 2926 explicit IsGreaterThan(int threshold) : threshold_(threshold) {} 2927 2928 bool operator()(int n) const { return n > threshold_; } 2929 2930 private: 2931 int threshold_; 2932}; 2933 2934// For testing Truly(). 2935const int foo = 0; 2936 2937// This predicate returns true iff the argument references foo and has 2938// a zero value. 2939bool ReferencesFooAndIsZero(const int& n) { 2940 return (&n == &foo) && (n == 0); 2941} 2942 2943// Tests that Truly(predicate) matches what satisfies the given 2944// predicate. 2945TEST(TrulyTest, MatchesWhatSatisfiesThePredicate) { 2946 Matcher<double> m = Truly(IsPositive); 2947 EXPECT_TRUE(m.Matches(2.0)); 2948 EXPECT_FALSE(m.Matches(-1.5)); 2949} 2950 2951// Tests that Truly(predicate_functor) works too. 2952TEST(TrulyTest, CanBeUsedWithFunctor) { 2953 Matcher<int> m = Truly(IsGreaterThan(5)); 2954 EXPECT_TRUE(m.Matches(6)); 2955 EXPECT_FALSE(m.Matches(4)); 2956} 2957 2958// A class that can be implicitly converted to bool. 2959class ConvertibleToBool { 2960 public: 2961 explicit ConvertibleToBool(int number) : number_(number) {} 2962 operator bool() const { return number_ != 0; } 2963 2964 private: 2965 int number_; 2966}; 2967 2968ConvertibleToBool IsNotZero(int number) { 2969 return ConvertibleToBool(number); 2970} 2971 2972// Tests that the predicate used in Truly() may return a class that's 2973// implicitly convertible to bool, even when the class has no 2974// operator!(). 2975TEST(TrulyTest, PredicateCanReturnAClassConvertibleToBool) { 2976 Matcher<int> m = Truly(IsNotZero); 2977 EXPECT_TRUE(m.Matches(1)); 2978 EXPECT_FALSE(m.Matches(0)); 2979} 2980 2981// Tests that Truly(predicate) can describe itself properly. 2982TEST(TrulyTest, CanDescribeSelf) { 2983 Matcher<double> m = Truly(IsPositive); 2984 EXPECT_EQ("satisfies the given predicate", 2985 Describe(m)); 2986} 2987 2988// Tests that Truly(predicate) works when the matcher takes its 2989// argument by reference. 2990TEST(TrulyTest, WorksForByRefArguments) { 2991 Matcher<const int&> m = Truly(ReferencesFooAndIsZero); 2992 EXPECT_TRUE(m.Matches(foo)); 2993 int n = 0; 2994 EXPECT_FALSE(m.Matches(n)); 2995} 2996 2997// Tests that Matches(m) is a predicate satisfied by whatever that 2998// matches matcher m. 2999TEST(MatchesTest, IsSatisfiedByWhatMatchesTheMatcher) { 3000 EXPECT_TRUE(Matches(Ge(0))(1)); 3001 EXPECT_FALSE(Matches(Eq('a'))('b')); 3002} 3003 3004// Tests that Matches(m) works when the matcher takes its argument by 3005// reference. 3006TEST(MatchesTest, WorksOnByRefArguments) { 3007 int m = 0, n = 0; 3008 EXPECT_TRUE(Matches(AllOf(Ref(n), Eq(0)))(n)); 3009 EXPECT_FALSE(Matches(Ref(m))(n)); 3010} 3011 3012// Tests that a Matcher on non-reference type can be used in 3013// Matches(). 3014TEST(MatchesTest, WorksWithMatcherOnNonRefType) { 3015 Matcher<int> eq5 = Eq(5); 3016 EXPECT_TRUE(Matches(eq5)(5)); 3017 EXPECT_FALSE(Matches(eq5)(2)); 3018} 3019 3020// Tests Value(value, matcher). Since Value() is a simple wrapper for 3021// Matches(), which has been tested already, we don't spend a lot of 3022// effort on testing Value(). 3023TEST(ValueTest, WorksWithPolymorphicMatcher) { 3024 EXPECT_TRUE(Value("hi", StartsWith("h"))); 3025 EXPECT_FALSE(Value(5, Gt(10))); 3026} 3027 3028TEST(ValueTest, WorksWithMonomorphicMatcher) { 3029 const Matcher<int> is_zero = Eq(0); 3030 EXPECT_TRUE(Value(0, is_zero)); 3031 EXPECT_FALSE(Value('a', is_zero)); 3032 3033 int n = 0; 3034 const Matcher<const int&> ref_n = Ref(n); 3035 EXPECT_TRUE(Value(n, ref_n)); 3036 EXPECT_FALSE(Value(1, ref_n)); 3037} 3038 3039TEST(ExplainMatchResultTest, WorksWithPolymorphicMatcher) { 3040 StringMatchResultListener listener1; 3041 EXPECT_TRUE(ExplainMatchResult(PolymorphicIsEven(), 42, &listener1)); 3042 EXPECT_EQ("% 2 == 0", listener1.str()); 3043 3044 StringMatchResultListener listener2; 3045 EXPECT_FALSE(ExplainMatchResult(Ge(42), 1.5, &listener2)); 3046 EXPECT_EQ("", listener2.str()); 3047} 3048 3049TEST(ExplainMatchResultTest, WorksWithMonomorphicMatcher) { 3050 const Matcher<int> is_even = PolymorphicIsEven(); 3051 StringMatchResultListener listener1; 3052 EXPECT_TRUE(ExplainMatchResult(is_even, 42, &listener1)); 3053 EXPECT_EQ("% 2 == 0", listener1.str()); 3054 3055 const Matcher<const double&> is_zero = Eq(0); 3056 StringMatchResultListener listener2; 3057 EXPECT_FALSE(ExplainMatchResult(is_zero, 1.5, &listener2)); 3058 EXPECT_EQ("", listener2.str()); 3059} 3060 3061MATCHER_P(Really, inner_matcher, "") { 3062 return ExplainMatchResult(inner_matcher, arg, result_listener); 3063} 3064 3065TEST(ExplainMatchResultTest, WorksInsideMATCHER) { 3066 EXPECT_THAT(0, Really(Eq(0))); 3067} 3068 3069TEST(DescribeMatcherTest, WorksWithValue) { 3070 EXPECT_EQ("is equal to 42", DescribeMatcher<int>(42)); 3071 EXPECT_EQ("isn't equal to 42", DescribeMatcher<int>(42, true)); 3072} 3073 3074TEST(DescribeMatcherTest, WorksWithMonomorphicMatcher) { 3075 const Matcher<int> monomorphic = Le(0); 3076 EXPECT_EQ("is <= 0", DescribeMatcher<int>(monomorphic)); 3077 EXPECT_EQ("isn't <= 0", DescribeMatcher<int>(monomorphic, true)); 3078} 3079 3080TEST(DescribeMatcherTest, WorksWithPolymorphicMatcher) { 3081 EXPECT_EQ("is even", DescribeMatcher<int>(PolymorphicIsEven())); 3082 EXPECT_EQ("is odd", DescribeMatcher<int>(PolymorphicIsEven(), true)); 3083} 3084 3085TEST(AllArgsTest, WorksForTuple) { 3086 EXPECT_THAT(make_tuple(1, 2L), AllArgs(Lt())); 3087 EXPECT_THAT(make_tuple(2L, 1), Not(AllArgs(Lt()))); 3088} 3089 3090TEST(AllArgsTest, WorksForNonTuple) { 3091 EXPECT_THAT(42, AllArgs(Gt(0))); 3092 EXPECT_THAT('a', Not(AllArgs(Eq('b')))); 3093} 3094 3095class AllArgsHelper { 3096 public: 3097 AllArgsHelper() {} 3098 3099 MOCK_METHOD2(Helper, int(char x, int y)); 3100 3101 private: 3102 GTEST_DISALLOW_COPY_AND_ASSIGN_(AllArgsHelper); 3103}; 3104 3105TEST(AllArgsTest, WorksInWithClause) { 3106 AllArgsHelper helper; 3107 ON_CALL(helper, Helper(_, _)) 3108 .With(AllArgs(Lt())) 3109 .WillByDefault(Return(1)); 3110 EXPECT_CALL(helper, Helper(_, _)); 3111 EXPECT_CALL(helper, Helper(_, _)) 3112 .With(AllArgs(Gt())) 3113 .WillOnce(Return(2)); 3114 3115 EXPECT_EQ(1, helper.Helper('\1', 2)); 3116 EXPECT_EQ(2, helper.Helper('a', 1)); 3117} 3118 3119class OptionalMatchersHelper { 3120 public: 3121 OptionalMatchersHelper() {} 3122 3123 MOCK_METHOD0(NoArgs, int()); 3124 3125 MOCK_METHOD1(OneArg, int(int y)); 3126 3127 MOCK_METHOD2(TwoArgs, int(char x, int y)); 3128 3129 MOCK_METHOD1(Overloaded, int(char x)); 3130 MOCK_METHOD2(Overloaded, int(char x, int y)); 3131 3132 private: 3133 GTEST_DISALLOW_COPY_AND_ASSIGN_(OptionalMatchersHelper); 3134}; 3135 3136TEST(AllArgsTest, WorksWithoutMatchers) { 3137 OptionalMatchersHelper helper; 3138 3139 ON_CALL(helper, NoArgs).WillByDefault(Return(10)); 3140 ON_CALL(helper, OneArg).WillByDefault(Return(20)); 3141 ON_CALL(helper, TwoArgs).WillByDefault(Return(30)); 3142 3143 EXPECT_EQ(10, helper.NoArgs()); 3144 EXPECT_EQ(20, helper.OneArg(1)); 3145 EXPECT_EQ(30, helper.TwoArgs('\1', 2)); 3146 3147 EXPECT_CALL(helper, NoArgs).Times(1); 3148 EXPECT_CALL(helper, OneArg).WillOnce(Return(100)); 3149 EXPECT_CALL(helper, OneArg(17)).WillOnce(Return(200)); 3150 EXPECT_CALL(helper, TwoArgs).Times(0); 3151 3152 EXPECT_EQ(10, helper.NoArgs()); 3153 EXPECT_EQ(100, helper.OneArg(1)); 3154 EXPECT_EQ(200, helper.OneArg(17)); 3155} 3156 3157// Tests that ASSERT_THAT() and EXPECT_THAT() work when the value 3158// matches the matcher. 3159TEST(MatcherAssertionTest, WorksWhenMatcherIsSatisfied) { 3160 ASSERT_THAT(5, Ge(2)) << "This should succeed."; 3161 ASSERT_THAT("Foo", EndsWith("oo")); 3162 EXPECT_THAT(2, AllOf(Le(7), Ge(0))) << "This should succeed too."; 3163 EXPECT_THAT("Hello", StartsWith("Hell")); 3164} 3165 3166// Tests that ASSERT_THAT() and EXPECT_THAT() work when the value 3167// doesn't match the matcher. 3168TEST(MatcherAssertionTest, WorksWhenMatcherIsNotSatisfied) { 3169 // 'n' must be static as it is used in an EXPECT_FATAL_FAILURE(), 3170 // which cannot reference auto variables. 3171 static unsigned short n; // NOLINT 3172 n = 5; 3173 3174 // VC++ prior to version 8.0 SP1 has a bug where it will not see any 3175 // functions declared in the namespace scope from within nested classes. 3176 // EXPECT/ASSERT_(NON)FATAL_FAILURE macros use nested classes so that all 3177 // namespace-level functions invoked inside them need to be explicitly 3178 // resolved. 3179 EXPECT_FATAL_FAILURE(ASSERT_THAT(n, ::testing::Gt(10)), 3180 "Value of: n\n" 3181 "Expected: is > 10\n" 3182 " Actual: 5" + OfType("unsigned short")); 3183 n = 0; 3184 EXPECT_NONFATAL_FAILURE( 3185 EXPECT_THAT(n, ::testing::AllOf(::testing::Le(7), ::testing::Ge(5))), 3186 "Value of: n\n" 3187 "Expected: (is <= 7) and (is >= 5)\n" 3188 " Actual: 0" + OfType("unsigned short")); 3189} 3190 3191// Tests that ASSERT_THAT() and EXPECT_THAT() work when the argument 3192// has a reference type. 3193TEST(MatcherAssertionTest, WorksForByRefArguments) { 3194 // We use a static variable here as EXPECT_FATAL_FAILURE() cannot 3195 // reference auto variables. 3196 static int n; 3197 n = 0; 3198 EXPECT_THAT(n, AllOf(Le(7), Ref(n))); 3199 EXPECT_FATAL_FAILURE(ASSERT_THAT(n, ::testing::Not(::testing::Ref(n))), 3200 "Value of: n\n" 3201 "Expected: does not reference the variable @"); 3202 // Tests the "Actual" part. 3203 EXPECT_FATAL_FAILURE(ASSERT_THAT(n, ::testing::Not(::testing::Ref(n))), 3204 "Actual: 0" + OfType("int") + ", which is located @"); 3205} 3206 3207#if !GTEST_OS_SYMBIAN 3208// Tests that ASSERT_THAT() and EXPECT_THAT() work when the matcher is 3209// monomorphic. 3210 3211// ASSERT_THAT("hello", starts_with_he) fails to compile with Nokia's 3212// Symbian compiler: it tries to compile 3213// template<T, U> class MatcherCastImpl { ... 3214// virtual bool MatchAndExplain(T x, ...) const { 3215// return source_matcher_.MatchAndExplain(static_cast<U>(x), ...); 3216// with U == string and T == const char* 3217// With ASSERT_THAT("hello"...) changed to ASSERT_THAT(string("hello") ... ) 3218// the compiler silently crashes with no output. 3219// If MatcherCastImpl is changed to use U(x) instead of static_cast<U>(x) 3220// the code compiles but the converted string is bogus. 3221TEST(MatcherAssertionTest, WorksForMonomorphicMatcher) { 3222 Matcher<const char*> starts_with_he = StartsWith("he"); 3223 ASSERT_THAT("hello", starts_with_he); 3224 3225 Matcher<const std::string&> ends_with_ok = EndsWith("ok"); 3226 ASSERT_THAT("book", ends_with_ok); 3227 const std::string bad = "bad"; 3228 EXPECT_NONFATAL_FAILURE(EXPECT_THAT(bad, ends_with_ok), 3229 "Value of: bad\n" 3230 "Expected: ends with \"ok\"\n" 3231 " Actual: \"bad\""); 3232 Matcher<int> is_greater_than_5 = Gt(5); 3233 EXPECT_NONFATAL_FAILURE(EXPECT_THAT(5, is_greater_than_5), 3234 "Value of: 5\n" 3235 "Expected: is > 5\n" 3236 " Actual: 5" + OfType("int")); 3237} 3238#endif // !GTEST_OS_SYMBIAN 3239 3240// Tests floating-point matchers. 3241template <typename RawType> 3242class FloatingPointTest : public testing::Test { 3243 protected: 3244 typedef testing::internal::FloatingPoint<RawType> Floating; 3245 typedef typename Floating::Bits Bits; 3246 3247 FloatingPointTest() 3248 : max_ulps_(Floating::kMaxUlps), 3249 zero_bits_(Floating(0).bits()), 3250 one_bits_(Floating(1).bits()), 3251 infinity_bits_(Floating(Floating::Infinity()).bits()), 3252 close_to_positive_zero_( 3253 Floating::ReinterpretBits(zero_bits_ + max_ulps_/2)), 3254 close_to_negative_zero_( 3255 -Floating::ReinterpretBits(zero_bits_ + max_ulps_ - max_ulps_/2)), 3256 further_from_negative_zero_(-Floating::ReinterpretBits( 3257 zero_bits_ + max_ulps_ + 1 - max_ulps_/2)), 3258 close_to_one_(Floating::ReinterpretBits(one_bits_ + max_ulps_)), 3259 further_from_one_(Floating::ReinterpretBits(one_bits_ + max_ulps_ + 1)), 3260 infinity_(Floating::Infinity()), 3261 close_to_infinity_( 3262 Floating::ReinterpretBits(infinity_bits_ - max_ulps_)), 3263 further_from_infinity_( 3264 Floating::ReinterpretBits(infinity_bits_ - max_ulps_ - 1)), 3265 max_(Floating::Max()), 3266 nan1_(Floating::ReinterpretBits(Floating::kExponentBitMask | 1)), 3267 nan2_(Floating::ReinterpretBits(Floating::kExponentBitMask | 200)) { 3268 } 3269 3270 void TestSize() { 3271 EXPECT_EQ(sizeof(RawType), sizeof(Bits)); 3272 } 3273 3274 // A battery of tests for FloatingEqMatcher::Matches. 3275 // matcher_maker is a pointer to a function which creates a FloatingEqMatcher. 3276 void TestMatches( 3277 testing::internal::FloatingEqMatcher<RawType> (*matcher_maker)(RawType)) { 3278 Matcher<RawType> m1 = matcher_maker(0.0); 3279 EXPECT_TRUE(m1.Matches(-0.0)); 3280 EXPECT_TRUE(m1.Matches(close_to_positive_zero_)); 3281 EXPECT_TRUE(m1.Matches(close_to_negative_zero_)); 3282 EXPECT_FALSE(m1.Matches(1.0)); 3283 3284 Matcher<RawType> m2 = matcher_maker(close_to_positive_zero_); 3285 EXPECT_FALSE(m2.Matches(further_from_negative_zero_)); 3286 3287 Matcher<RawType> m3 = matcher_maker(1.0); 3288 EXPECT_TRUE(m3.Matches(close_to_one_)); 3289 EXPECT_FALSE(m3.Matches(further_from_one_)); 3290 3291 // Test commutativity: matcher_maker(0.0).Matches(1.0) was tested above. 3292 EXPECT_FALSE(m3.Matches(0.0)); 3293 3294 Matcher<RawType> m4 = matcher_maker(-infinity_); 3295 EXPECT_TRUE(m4.Matches(-close_to_infinity_)); 3296 3297 Matcher<RawType> m5 = matcher_maker(infinity_); 3298 EXPECT_TRUE(m5.Matches(close_to_infinity_)); 3299 3300 // This is interesting as the representations of infinity_ and nan1_ 3301 // are only 1 DLP apart. 3302 EXPECT_FALSE(m5.Matches(nan1_)); 3303 3304 // matcher_maker can produce a Matcher<const RawType&>, which is needed in 3305 // some cases. 3306 Matcher<const RawType&> m6 = matcher_maker(0.0); 3307 EXPECT_TRUE(m6.Matches(-0.0)); 3308 EXPECT_TRUE(m6.Matches(close_to_positive_zero_)); 3309 EXPECT_FALSE(m6.Matches(1.0)); 3310 3311 // matcher_maker can produce a Matcher<RawType&>, which is needed in some 3312 // cases. 3313 Matcher<RawType&> m7 = matcher_maker(0.0); 3314 RawType x = 0.0; 3315 EXPECT_TRUE(m7.Matches(x)); 3316 x = 0.01f; 3317 EXPECT_FALSE(m7.Matches(x)); 3318 } 3319 3320 // Pre-calculated numbers to be used by the tests. 3321 3322 const Bits max_ulps_; 3323 3324 const Bits zero_bits_; // The bits that represent 0.0. 3325 const Bits one_bits_; // The bits that represent 1.0. 3326 const Bits infinity_bits_; // The bits that represent +infinity. 3327 3328 // Some numbers close to 0.0. 3329 const RawType close_to_positive_zero_; 3330 const RawType close_to_negative_zero_; 3331 const RawType further_from_negative_zero_; 3332 3333 // Some numbers close to 1.0. 3334 const RawType close_to_one_; 3335 const RawType further_from_one_; 3336 3337 // Some numbers close to +infinity. 3338 const RawType infinity_; 3339 const RawType close_to_infinity_; 3340 const RawType further_from_infinity_; 3341 3342 // Maximum representable value that's not infinity. 3343 const RawType max_; 3344 3345 // Some NaNs. 3346 const RawType nan1_; 3347 const RawType nan2_; 3348}; 3349 3350// Tests floating-point matchers with fixed epsilons. 3351template <typename RawType> 3352class FloatingPointNearTest : public FloatingPointTest<RawType> { 3353 protected: 3354 typedef FloatingPointTest<RawType> ParentType; 3355 3356 // A battery of tests for FloatingEqMatcher::Matches with a fixed epsilon. 3357 // matcher_maker is a pointer to a function which creates a FloatingEqMatcher. 3358 void TestNearMatches( 3359 testing::internal::FloatingEqMatcher<RawType> 3360 (*matcher_maker)(RawType, RawType)) { 3361 Matcher<RawType> m1 = matcher_maker(0.0, 0.0); 3362 EXPECT_TRUE(m1.Matches(0.0)); 3363 EXPECT_TRUE(m1.Matches(-0.0)); 3364 EXPECT_FALSE(m1.Matches(ParentType::close_to_positive_zero_)); 3365 EXPECT_FALSE(m1.Matches(ParentType::close_to_negative_zero_)); 3366 EXPECT_FALSE(m1.Matches(1.0)); 3367 3368 Matcher<RawType> m2 = matcher_maker(0.0, 1.0); 3369 EXPECT_TRUE(m2.Matches(0.0)); 3370 EXPECT_TRUE(m2.Matches(-0.0)); 3371 EXPECT_TRUE(m2.Matches(1.0)); 3372 EXPECT_TRUE(m2.Matches(-1.0)); 3373 EXPECT_FALSE(m2.Matches(ParentType::close_to_one_)); 3374 EXPECT_FALSE(m2.Matches(-ParentType::close_to_one_)); 3375 3376 // Check that inf matches inf, regardless of the of the specified max 3377 // absolute error. 3378 Matcher<RawType> m3 = matcher_maker(ParentType::infinity_, 0.0); 3379 EXPECT_TRUE(m3.Matches(ParentType::infinity_)); 3380 EXPECT_FALSE(m3.Matches(ParentType::close_to_infinity_)); 3381 EXPECT_FALSE(m3.Matches(-ParentType::infinity_)); 3382 3383 Matcher<RawType> m4 = matcher_maker(-ParentType::infinity_, 0.0); 3384 EXPECT_TRUE(m4.Matches(-ParentType::infinity_)); 3385 EXPECT_FALSE(m4.Matches(-ParentType::close_to_infinity_)); 3386 EXPECT_FALSE(m4.Matches(ParentType::infinity_)); 3387 3388 // Test various overflow scenarios. 3389 Matcher<RawType> m5 = matcher_maker(ParentType::max_, ParentType::max_); 3390 EXPECT_TRUE(m5.Matches(ParentType::max_)); 3391 EXPECT_FALSE(m5.Matches(-ParentType::max_)); 3392 3393 Matcher<RawType> m6 = matcher_maker(-ParentType::max_, ParentType::max_); 3394 EXPECT_FALSE(m6.Matches(ParentType::max_)); 3395 EXPECT_TRUE(m6.Matches(-ParentType::max_)); 3396 3397 Matcher<RawType> m7 = matcher_maker(ParentType::max_, 0); 3398 EXPECT_TRUE(m7.Matches(ParentType::max_)); 3399 EXPECT_FALSE(m7.Matches(-ParentType::max_)); 3400 3401 Matcher<RawType> m8 = matcher_maker(-ParentType::max_, 0); 3402 EXPECT_FALSE(m8.Matches(ParentType::max_)); 3403 EXPECT_TRUE(m8.Matches(-ParentType::max_)); 3404 3405 // The difference between max() and -max() normally overflows to infinity, 3406 // but it should still match if the max_abs_error is also infinity. 3407 Matcher<RawType> m9 = matcher_maker( 3408 ParentType::max_, ParentType::infinity_); 3409 EXPECT_TRUE(m8.Matches(-ParentType::max_)); 3410 3411 // matcher_maker can produce a Matcher<const RawType&>, which is needed in 3412 // some cases. 3413 Matcher<const RawType&> m10 = matcher_maker(0.0, 1.0); 3414 EXPECT_TRUE(m10.Matches(-0.0)); 3415 EXPECT_TRUE(m10.Matches(ParentType::close_to_positive_zero_)); 3416 EXPECT_FALSE(m10.Matches(ParentType::close_to_one_)); 3417 3418 // matcher_maker can produce a Matcher<RawType&>, which is needed in some 3419 // cases. 3420 Matcher<RawType&> m11 = matcher_maker(0.0, 1.0); 3421 RawType x = 0.0; 3422 EXPECT_TRUE(m11.Matches(x)); 3423 x = 1.0f; 3424 EXPECT_TRUE(m11.Matches(x)); 3425 x = -1.0f; 3426 EXPECT_TRUE(m11.Matches(x)); 3427 x = 1.1f; 3428 EXPECT_FALSE(m11.Matches(x)); 3429 x = -1.1f; 3430 EXPECT_FALSE(m11.Matches(x)); 3431 } 3432}; 3433 3434// Instantiate FloatingPointTest for testing floats. 3435typedef FloatingPointTest<float> FloatTest; 3436 3437TEST_F(FloatTest, FloatEqApproximatelyMatchesFloats) { 3438 TestMatches(&FloatEq); 3439} 3440 3441TEST_F(FloatTest, NanSensitiveFloatEqApproximatelyMatchesFloats) { 3442 TestMatches(&NanSensitiveFloatEq); 3443} 3444 3445TEST_F(FloatTest, FloatEqCannotMatchNaN) { 3446 // FloatEq never matches NaN. 3447 Matcher<float> m = FloatEq(nan1_); 3448 EXPECT_FALSE(m.Matches(nan1_)); 3449 EXPECT_FALSE(m.Matches(nan2_)); 3450 EXPECT_FALSE(m.Matches(1.0)); 3451} 3452 3453TEST_F(FloatTest, NanSensitiveFloatEqCanMatchNaN) { 3454 // NanSensitiveFloatEq will match NaN. 3455 Matcher<float> m = NanSensitiveFloatEq(nan1_); 3456 EXPECT_TRUE(m.Matches(nan1_)); 3457 EXPECT_TRUE(m.Matches(nan2_)); 3458 EXPECT_FALSE(m.Matches(1.0)); 3459} 3460 3461TEST_F(FloatTest, FloatEqCanDescribeSelf) { 3462 Matcher<float> m1 = FloatEq(2.0f); 3463 EXPECT_EQ("is approximately 2", Describe(m1)); 3464 EXPECT_EQ("isn't approximately 2", DescribeNegation(m1)); 3465 3466 Matcher<float> m2 = FloatEq(0.5f); 3467 EXPECT_EQ("is approximately 0.5", Describe(m2)); 3468 EXPECT_EQ("isn't approximately 0.5", DescribeNegation(m2)); 3469 3470 Matcher<float> m3 = FloatEq(nan1_); 3471 EXPECT_EQ("never matches", Describe(m3)); 3472 EXPECT_EQ("is anything", DescribeNegation(m3)); 3473} 3474 3475TEST_F(FloatTest, NanSensitiveFloatEqCanDescribeSelf) { 3476 Matcher<float> m1 = NanSensitiveFloatEq(2.0f); 3477 EXPECT_EQ("is approximately 2", Describe(m1)); 3478 EXPECT_EQ("isn't approximately 2", DescribeNegation(m1)); 3479 3480 Matcher<float> m2 = NanSensitiveFloatEq(0.5f); 3481 EXPECT_EQ("is approximately 0.5", Describe(m2)); 3482 EXPECT_EQ("isn't approximately 0.5", DescribeNegation(m2)); 3483 3484 Matcher<float> m3 = NanSensitiveFloatEq(nan1_); 3485 EXPECT_EQ("is NaN", Describe(m3)); 3486 EXPECT_EQ("isn't NaN", DescribeNegation(m3)); 3487} 3488 3489// Instantiate FloatingPointTest for testing floats with a user-specified 3490// max absolute error. 3491typedef FloatingPointNearTest<float> FloatNearTest; 3492 3493TEST_F(FloatNearTest, FloatNearMatches) { 3494 TestNearMatches(&FloatNear); 3495} 3496 3497TEST_F(FloatNearTest, NanSensitiveFloatNearApproximatelyMatchesFloats) { 3498 TestNearMatches(&NanSensitiveFloatNear); 3499} 3500 3501TEST_F(FloatNearTest, FloatNearCanDescribeSelf) { 3502 Matcher<float> m1 = FloatNear(2.0f, 0.5f); 3503 EXPECT_EQ("is approximately 2 (absolute error <= 0.5)", Describe(m1)); 3504 EXPECT_EQ( 3505 "isn't approximately 2 (absolute error > 0.5)", DescribeNegation(m1)); 3506 3507 Matcher<float> m2 = FloatNear(0.5f, 0.5f); 3508 EXPECT_EQ("is approximately 0.5 (absolute error <= 0.5)", Describe(m2)); 3509 EXPECT_EQ( 3510 "isn't approximately 0.5 (absolute error > 0.5)", DescribeNegation(m2)); 3511 3512 Matcher<float> m3 = FloatNear(nan1_, 0.0); 3513 EXPECT_EQ("never matches", Describe(m3)); 3514 EXPECT_EQ("is anything", DescribeNegation(m3)); 3515} 3516 3517TEST_F(FloatNearTest, NanSensitiveFloatNearCanDescribeSelf) { 3518 Matcher<float> m1 = NanSensitiveFloatNear(2.0f, 0.5f); 3519 EXPECT_EQ("is approximately 2 (absolute error <= 0.5)", Describe(m1)); 3520 EXPECT_EQ( 3521 "isn't approximately 2 (absolute error > 0.5)", DescribeNegation(m1)); 3522 3523 Matcher<float> m2 = NanSensitiveFloatNear(0.5f, 0.5f); 3524 EXPECT_EQ("is approximately 0.5 (absolute error <= 0.5)", Describe(m2)); 3525 EXPECT_EQ( 3526 "isn't approximately 0.5 (absolute error > 0.5)", DescribeNegation(m2)); 3527 3528 Matcher<float> m3 = NanSensitiveFloatNear(nan1_, 0.1f); 3529 EXPECT_EQ("is NaN", Describe(m3)); 3530 EXPECT_EQ("isn't NaN", DescribeNegation(m3)); 3531} 3532 3533TEST_F(FloatNearTest, FloatNearCannotMatchNaN) { 3534 // FloatNear never matches NaN. 3535 Matcher<float> m = FloatNear(ParentType::nan1_, 0.1f); 3536 EXPECT_FALSE(m.Matches(nan1_)); 3537 EXPECT_FALSE(m.Matches(nan2_)); 3538 EXPECT_FALSE(m.Matches(1.0)); 3539} 3540 3541TEST_F(FloatNearTest, NanSensitiveFloatNearCanMatchNaN) { 3542 // NanSensitiveFloatNear will match NaN. 3543 Matcher<float> m = NanSensitiveFloatNear(nan1_, 0.1f); 3544 EXPECT_TRUE(m.Matches(nan1_)); 3545 EXPECT_TRUE(m.Matches(nan2_)); 3546 EXPECT_FALSE(m.Matches(1.0)); 3547} 3548 3549// Instantiate FloatingPointTest for testing doubles. 3550typedef FloatingPointTest<double> DoubleTest; 3551 3552TEST_F(DoubleTest, DoubleEqApproximatelyMatchesDoubles) { 3553 TestMatches(&DoubleEq); 3554} 3555 3556TEST_F(DoubleTest, NanSensitiveDoubleEqApproximatelyMatchesDoubles) { 3557 TestMatches(&NanSensitiveDoubleEq); 3558} 3559 3560TEST_F(DoubleTest, DoubleEqCannotMatchNaN) { 3561 // DoubleEq never matches NaN. 3562 Matcher<double> m = DoubleEq(nan1_); 3563 EXPECT_FALSE(m.Matches(nan1_)); 3564 EXPECT_FALSE(m.Matches(nan2_)); 3565 EXPECT_FALSE(m.Matches(1.0)); 3566} 3567 3568TEST_F(DoubleTest, NanSensitiveDoubleEqCanMatchNaN) { 3569 // NanSensitiveDoubleEq will match NaN. 3570 Matcher<double> m = NanSensitiveDoubleEq(nan1_); 3571 EXPECT_TRUE(m.Matches(nan1_)); 3572 EXPECT_TRUE(m.Matches(nan2_)); 3573 EXPECT_FALSE(m.Matches(1.0)); 3574} 3575 3576TEST_F(DoubleTest, DoubleEqCanDescribeSelf) { 3577 Matcher<double> m1 = DoubleEq(2.0); 3578 EXPECT_EQ("is approximately 2", Describe(m1)); 3579 EXPECT_EQ("isn't approximately 2", DescribeNegation(m1)); 3580 3581 Matcher<double> m2 = DoubleEq(0.5); 3582 EXPECT_EQ("is approximately 0.5", Describe(m2)); 3583 EXPECT_EQ("isn't approximately 0.5", DescribeNegation(m2)); 3584 3585 Matcher<double> m3 = DoubleEq(nan1_); 3586 EXPECT_EQ("never matches", Describe(m3)); 3587 EXPECT_EQ("is anything", DescribeNegation(m3)); 3588} 3589 3590TEST_F(DoubleTest, NanSensitiveDoubleEqCanDescribeSelf) { 3591 Matcher<double> m1 = NanSensitiveDoubleEq(2.0); 3592 EXPECT_EQ("is approximately 2", Describe(m1)); 3593 EXPECT_EQ("isn't approximately 2", DescribeNegation(m1)); 3594 3595 Matcher<double> m2 = NanSensitiveDoubleEq(0.5); 3596 EXPECT_EQ("is approximately 0.5", Describe(m2)); 3597 EXPECT_EQ("isn't approximately 0.5", DescribeNegation(m2)); 3598 3599 Matcher<double> m3 = NanSensitiveDoubleEq(nan1_); 3600 EXPECT_EQ("is NaN", Describe(m3)); 3601 EXPECT_EQ("isn't NaN", DescribeNegation(m3)); 3602} 3603 3604// Instantiate FloatingPointTest for testing floats with a user-specified 3605// max absolute error. 3606typedef FloatingPointNearTest<double> DoubleNearTest; 3607 3608TEST_F(DoubleNearTest, DoubleNearMatches) { 3609 TestNearMatches(&DoubleNear); 3610} 3611 3612TEST_F(DoubleNearTest, NanSensitiveDoubleNearApproximatelyMatchesDoubles) { 3613 TestNearMatches(&NanSensitiveDoubleNear); 3614} 3615 3616TEST_F(DoubleNearTest, DoubleNearCanDescribeSelf) { 3617 Matcher<double> m1 = DoubleNear(2.0, 0.5); 3618 EXPECT_EQ("is approximately 2 (absolute error <= 0.5)", Describe(m1)); 3619 EXPECT_EQ( 3620 "isn't approximately 2 (absolute error > 0.5)", DescribeNegation(m1)); 3621 3622 Matcher<double> m2 = DoubleNear(0.5, 0.5); 3623 EXPECT_EQ("is approximately 0.5 (absolute error <= 0.5)", Describe(m2)); 3624 EXPECT_EQ( 3625 "isn't approximately 0.5 (absolute error > 0.5)", DescribeNegation(m2)); 3626 3627 Matcher<double> m3 = DoubleNear(nan1_, 0.0); 3628 EXPECT_EQ("never matches", Describe(m3)); 3629 EXPECT_EQ("is anything", DescribeNegation(m3)); 3630} 3631 3632TEST_F(DoubleNearTest, ExplainsResultWhenMatchFails) { 3633 EXPECT_EQ("", Explain(DoubleNear(2.0, 0.1), 2.05)); 3634 EXPECT_EQ("which is 0.2 from 2", Explain(DoubleNear(2.0, 0.1), 2.2)); 3635 EXPECT_EQ("which is -0.3 from 2", Explain(DoubleNear(2.0, 0.1), 1.7)); 3636 3637 const std::string explanation = 3638 Explain(DoubleNear(2.1, 1e-10), 2.1 + 1.2e-10); 3639 // Different C++ implementations may print floating-point numbers 3640 // slightly differently. 3641 EXPECT_TRUE(explanation == "which is 1.2e-10 from 2.1" || // GCC 3642 explanation == "which is 1.2e-010 from 2.1") // MSVC 3643 << " where explanation is \"" << explanation << "\"."; 3644} 3645 3646TEST_F(DoubleNearTest, NanSensitiveDoubleNearCanDescribeSelf) { 3647 Matcher<double> m1 = NanSensitiveDoubleNear(2.0, 0.5); 3648 EXPECT_EQ("is approximately 2 (absolute error <= 0.5)", Describe(m1)); 3649 EXPECT_EQ( 3650 "isn't approximately 2 (absolute error > 0.5)", DescribeNegation(m1)); 3651 3652 Matcher<double> m2 = NanSensitiveDoubleNear(0.5, 0.5); 3653 EXPECT_EQ("is approximately 0.5 (absolute error <= 0.5)", Describe(m2)); 3654 EXPECT_EQ( 3655 "isn't approximately 0.5 (absolute error > 0.5)", DescribeNegation(m2)); 3656 3657 Matcher<double> m3 = NanSensitiveDoubleNear(nan1_, 0.1); 3658 EXPECT_EQ("is NaN", Describe(m3)); 3659 EXPECT_EQ("isn't NaN", DescribeNegation(m3)); 3660} 3661 3662TEST_F(DoubleNearTest, DoubleNearCannotMatchNaN) { 3663 // DoubleNear never matches NaN. 3664 Matcher<double> m = DoubleNear(ParentType::nan1_, 0.1); 3665 EXPECT_FALSE(m.Matches(nan1_)); 3666 EXPECT_FALSE(m.Matches(nan2_)); 3667 EXPECT_FALSE(m.Matches(1.0)); 3668} 3669 3670TEST_F(DoubleNearTest, NanSensitiveDoubleNearCanMatchNaN) { 3671 // NanSensitiveDoubleNear will match NaN. 3672 Matcher<double> m = NanSensitiveDoubleNear(nan1_, 0.1); 3673 EXPECT_TRUE(m.Matches(nan1_)); 3674 EXPECT_TRUE(m.Matches(nan2_)); 3675 EXPECT_FALSE(m.Matches(1.0)); 3676} 3677 3678TEST(PointeeTest, RawPointer) { 3679 const Matcher<int*> m = Pointee(Ge(0)); 3680 3681 int n = 1; 3682 EXPECT_TRUE(m.Matches(&n)); 3683 n = -1; 3684 EXPECT_FALSE(m.Matches(&n)); 3685 EXPECT_FALSE(m.Matches(NULL)); 3686} 3687 3688TEST(PointeeTest, RawPointerToConst) { 3689 const Matcher<const double*> m = Pointee(Ge(0)); 3690 3691 double x = 1; 3692 EXPECT_TRUE(m.Matches(&x)); 3693 x = -1; 3694 EXPECT_FALSE(m.Matches(&x)); 3695 EXPECT_FALSE(m.Matches(NULL)); 3696} 3697 3698TEST(PointeeTest, ReferenceToConstRawPointer) { 3699 const Matcher<int* const &> m = Pointee(Ge(0)); 3700 3701 int n = 1; 3702 EXPECT_TRUE(m.Matches(&n)); 3703 n = -1; 3704 EXPECT_FALSE(m.Matches(&n)); 3705 EXPECT_FALSE(m.Matches(NULL)); 3706} 3707 3708TEST(PointeeTest, ReferenceToNonConstRawPointer) { 3709 const Matcher<double* &> m = Pointee(Ge(0)); 3710 3711 double x = 1.0; 3712 double* p = &x; 3713 EXPECT_TRUE(m.Matches(p)); 3714 x = -1; 3715 EXPECT_FALSE(m.Matches(p)); 3716 p = NULL; 3717 EXPECT_FALSE(m.Matches(p)); 3718} 3719 3720MATCHER_P(FieldIIs, inner_matcher, "") { 3721 return ExplainMatchResult(inner_matcher, arg.i, result_listener); 3722} 3723 3724#if GTEST_HAS_RTTI 3725TEST(WhenDynamicCastToTest, SameType) { 3726 Derived derived; 3727 derived.i = 4; 3728 3729 // Right type. A pointer is passed down. 3730 Base* as_base_ptr = &derived; 3731 EXPECT_THAT(as_base_ptr, WhenDynamicCastTo<Derived*>(Not(IsNull()))); 3732 EXPECT_THAT(as_base_ptr, WhenDynamicCastTo<Derived*>(Pointee(FieldIIs(4)))); 3733 EXPECT_THAT(as_base_ptr, 3734 Not(WhenDynamicCastTo<Derived*>(Pointee(FieldIIs(5))))); 3735} 3736 3737TEST(WhenDynamicCastToTest, WrongTypes) { 3738 Base base; 3739 Derived derived; 3740 OtherDerived other_derived; 3741 3742 // Wrong types. NULL is passed. 3743 EXPECT_THAT(&base, Not(WhenDynamicCastTo<Derived*>(Pointee(_)))); 3744 EXPECT_THAT(&base, WhenDynamicCastTo<Derived*>(IsNull())); 3745 Base* as_base_ptr = &derived; 3746 EXPECT_THAT(as_base_ptr, Not(WhenDynamicCastTo<OtherDerived*>(Pointee(_)))); 3747 EXPECT_THAT(as_base_ptr, WhenDynamicCastTo<OtherDerived*>(IsNull())); 3748 as_base_ptr = &other_derived; 3749 EXPECT_THAT(as_base_ptr, Not(WhenDynamicCastTo<Derived*>(Pointee(_)))); 3750 EXPECT_THAT(as_base_ptr, WhenDynamicCastTo<Derived*>(IsNull())); 3751} 3752 3753TEST(WhenDynamicCastToTest, AlreadyNull) { 3754 // Already NULL. 3755 Base* as_base_ptr = NULL; 3756 EXPECT_THAT(as_base_ptr, WhenDynamicCastTo<Derived*>(IsNull())); 3757} 3758 3759struct AmbiguousCastTypes { 3760 class VirtualDerived : public virtual Base {}; 3761 class DerivedSub1 : public VirtualDerived {}; 3762 class DerivedSub2 : public VirtualDerived {}; 3763 class ManyDerivedInHierarchy : public DerivedSub1, public DerivedSub2 {}; 3764}; 3765 3766TEST(WhenDynamicCastToTest, AmbiguousCast) { 3767 AmbiguousCastTypes::DerivedSub1 sub1; 3768 AmbiguousCastTypes::ManyDerivedInHierarchy many_derived; 3769 // Multiply derived from Base. dynamic_cast<> returns NULL. 3770 3771 // This testcase fails on FreeBSD. See this GitHub issue for more details: 3772 // https://github.com/google/googletest/issues/2172 3773#ifdef __FreeBSD__ 3774 EXPECT_NONFATAL_FAILURE({ 3775#endif 3776 Base* as_base_ptr = 3777 static_cast<AmbiguousCastTypes::DerivedSub1*>(&many_derived); 3778 EXPECT_THAT(as_base_ptr, 3779 WhenDynamicCastTo<AmbiguousCastTypes::VirtualDerived*>(IsNull())); 3780 as_base_ptr = &sub1; 3781 EXPECT_THAT( 3782 as_base_ptr, 3783 WhenDynamicCastTo<AmbiguousCastTypes::VirtualDerived*>(Not(IsNull()))); 3784#ifdef __FreeBSD__ 3785 }, ""); 3786#endif 3787} 3788 3789TEST(WhenDynamicCastToTest, Describe) { 3790 Matcher<Base*> matcher = WhenDynamicCastTo<Derived*>(Pointee(_)); 3791 const std::string prefix = 3792 "when dynamic_cast to " + internal::GetTypeName<Derived*>() + ", "; 3793 EXPECT_EQ(prefix + "points to a value that is anything", Describe(matcher)); 3794 EXPECT_EQ(prefix + "does not point to a value that is anything", 3795 DescribeNegation(matcher)); 3796} 3797 3798TEST(WhenDynamicCastToTest, Explain) { 3799 Matcher<Base*> matcher = WhenDynamicCastTo<Derived*>(Pointee(_)); 3800 Base* null = NULL; 3801 EXPECT_THAT(Explain(matcher, null), HasSubstr("NULL")); 3802 Derived derived; 3803 EXPECT_TRUE(matcher.Matches(&derived)); 3804 EXPECT_THAT(Explain(matcher, &derived), HasSubstr("which points to ")); 3805 3806 // With references, the matcher itself can fail. Test for that one. 3807 Matcher<const Base&> ref_matcher = WhenDynamicCastTo<const OtherDerived&>(_); 3808 EXPECT_THAT(Explain(ref_matcher, derived), 3809 HasSubstr("which cannot be dynamic_cast")); 3810} 3811 3812TEST(WhenDynamicCastToTest, GoodReference) { 3813 Derived derived; 3814 derived.i = 4; 3815 Base& as_base_ref = derived; 3816 EXPECT_THAT(as_base_ref, WhenDynamicCastTo<const Derived&>(FieldIIs(4))); 3817 EXPECT_THAT(as_base_ref, WhenDynamicCastTo<const Derived&>(Not(FieldIIs(5)))); 3818} 3819 3820TEST(WhenDynamicCastToTest, BadReference) { 3821 Derived derived; 3822 Base& as_base_ref = derived; 3823 EXPECT_THAT(as_base_ref, Not(WhenDynamicCastTo<const OtherDerived&>(_))); 3824} 3825#endif // GTEST_HAS_RTTI 3826 3827// Minimal const-propagating pointer. 3828template <typename T> 3829class ConstPropagatingPtr { 3830 public: 3831 typedef T element_type; 3832 3833 ConstPropagatingPtr() : val_() {} 3834 explicit ConstPropagatingPtr(T* t) : val_(t) {} 3835 ConstPropagatingPtr(const ConstPropagatingPtr& other) : val_(other.val_) {} 3836 3837 T* get() { return val_; } 3838 T& operator*() { return *val_; } 3839 // Most smart pointers return non-const T* and T& from the next methods. 3840 const T* get() const { return val_; } 3841 const T& operator*() const { return *val_; } 3842 3843 private: 3844 T* val_; 3845}; 3846 3847TEST(PointeeTest, WorksWithConstPropagatingPointers) { 3848 const Matcher< ConstPropagatingPtr<int> > m = Pointee(Lt(5)); 3849 int three = 3; 3850 const ConstPropagatingPtr<int> co(&three); 3851 ConstPropagatingPtr<int> o(&three); 3852 EXPECT_TRUE(m.Matches(o)); 3853 EXPECT_TRUE(m.Matches(co)); 3854 *o = 6; 3855 EXPECT_FALSE(m.Matches(o)); 3856 EXPECT_FALSE(m.Matches(ConstPropagatingPtr<int>())); 3857} 3858 3859TEST(PointeeTest, NeverMatchesNull) { 3860 const Matcher<const char*> m = Pointee(_); 3861 EXPECT_FALSE(m.Matches(NULL)); 3862} 3863 3864// Tests that we can write Pointee(value) instead of Pointee(Eq(value)). 3865TEST(PointeeTest, MatchesAgainstAValue) { 3866 const Matcher<int*> m = Pointee(5); 3867 3868 int n = 5; 3869 EXPECT_TRUE(m.Matches(&n)); 3870 n = -1; 3871 EXPECT_FALSE(m.Matches(&n)); 3872 EXPECT_FALSE(m.Matches(NULL)); 3873} 3874 3875TEST(PointeeTest, CanDescribeSelf) { 3876 const Matcher<int*> m = Pointee(Gt(3)); 3877 EXPECT_EQ("points to a value that is > 3", Describe(m)); 3878 EXPECT_EQ("does not point to a value that is > 3", 3879 DescribeNegation(m)); 3880} 3881 3882TEST(PointeeTest, CanExplainMatchResult) { 3883 const Matcher<const std::string*> m = Pointee(StartsWith("Hi")); 3884 3885 EXPECT_EQ("", Explain(m, static_cast<const std::string*>(NULL))); 3886 3887 const Matcher<long*> m2 = Pointee(GreaterThan(1)); // NOLINT 3888 long n = 3; // NOLINT 3889 EXPECT_EQ("which points to 3" + OfType("long") + ", which is 2 more than 1", 3890 Explain(m2, &n)); 3891} 3892 3893TEST(PointeeTest, AlwaysExplainsPointee) { 3894 const Matcher<int*> m = Pointee(0); 3895 int n = 42; 3896 EXPECT_EQ("which points to 42" + OfType("int"), Explain(m, &n)); 3897} 3898 3899// An uncopyable class. 3900class Uncopyable { 3901 public: 3902 Uncopyable() : value_(-1) {} 3903 explicit Uncopyable(int a_value) : value_(a_value) {} 3904 3905 int value() const { return value_; } 3906 void set_value(int i) { value_ = i; } 3907 3908 private: 3909 int value_; 3910 GTEST_DISALLOW_COPY_AND_ASSIGN_(Uncopyable); 3911}; 3912 3913// Returns true iff x.value() is positive. 3914bool ValueIsPositive(const Uncopyable& x) { return x.value() > 0; } 3915 3916MATCHER_P(UncopyableIs, inner_matcher, "") { 3917 return ExplainMatchResult(inner_matcher, arg.value(), result_listener); 3918} 3919 3920// A user-defined struct for testing Field(). 3921struct AStruct { 3922 AStruct() : x(0), y(1.0), z(5), p(NULL) {} 3923 AStruct(const AStruct& rhs) 3924 : x(rhs.x), y(rhs.y), z(rhs.z.value()), p(rhs.p) {} 3925 3926 int x; // A non-const field. 3927 const double y; // A const field. 3928 Uncopyable z; // An uncopyable field. 3929 const char* p; // A pointer field. 3930 3931 private: 3932 GTEST_DISALLOW_ASSIGN_(AStruct); 3933}; 3934 3935// A derived struct for testing Field(). 3936struct DerivedStruct : public AStruct { 3937 char ch; 3938 3939 private: 3940 GTEST_DISALLOW_ASSIGN_(DerivedStruct); 3941}; 3942 3943// Tests that Field(&Foo::field, ...) works when field is non-const. 3944TEST(FieldTest, WorksForNonConstField) { 3945 Matcher<AStruct> m = Field(&AStruct::x, Ge(0)); 3946 Matcher<AStruct> m_with_name = Field("x", &AStruct::x, Ge(0)); 3947 3948 AStruct a; 3949 EXPECT_TRUE(m.Matches(a)); 3950 EXPECT_TRUE(m_with_name.Matches(a)); 3951 a.x = -1; 3952 EXPECT_FALSE(m.Matches(a)); 3953 EXPECT_FALSE(m_with_name.Matches(a)); 3954} 3955 3956// Tests that Field(&Foo::field, ...) works when field is const. 3957TEST(FieldTest, WorksForConstField) { 3958 AStruct a; 3959 3960 Matcher<AStruct> m = Field(&AStruct::y, Ge(0.0)); 3961 Matcher<AStruct> m_with_name = Field("y", &AStruct::y, Ge(0.0)); 3962 EXPECT_TRUE(m.Matches(a)); 3963 EXPECT_TRUE(m_with_name.Matches(a)); 3964 m = Field(&AStruct::y, Le(0.0)); 3965 m_with_name = Field("y", &AStruct::y, Le(0.0)); 3966 EXPECT_FALSE(m.Matches(a)); 3967 EXPECT_FALSE(m_with_name.Matches(a)); 3968} 3969 3970// Tests that Field(&Foo::field, ...) works when field is not copyable. 3971TEST(FieldTest, WorksForUncopyableField) { 3972 AStruct a; 3973 3974 Matcher<AStruct> m = Field(&AStruct::z, Truly(ValueIsPositive)); 3975 EXPECT_TRUE(m.Matches(a)); 3976 m = Field(&AStruct::z, Not(Truly(ValueIsPositive))); 3977 EXPECT_FALSE(m.Matches(a)); 3978} 3979 3980// Tests that Field(&Foo::field, ...) works when field is a pointer. 3981TEST(FieldTest, WorksForPointerField) { 3982 // Matching against NULL. 3983 Matcher<AStruct> m = Field(&AStruct::p, static_cast<const char*>(NULL)); 3984 AStruct a; 3985 EXPECT_TRUE(m.Matches(a)); 3986 a.p = "hi"; 3987 EXPECT_FALSE(m.Matches(a)); 3988 3989 // Matching a pointer that is not NULL. 3990 m = Field(&AStruct::p, StartsWith("hi")); 3991 a.p = "hill"; 3992 EXPECT_TRUE(m.Matches(a)); 3993 a.p = "hole"; 3994 EXPECT_FALSE(m.Matches(a)); 3995} 3996 3997// Tests that Field() works when the object is passed by reference. 3998TEST(FieldTest, WorksForByRefArgument) { 3999 Matcher<const AStruct&> m = Field(&AStruct::x, Ge(0)); 4000 4001 AStruct a; 4002 EXPECT_TRUE(m.Matches(a)); 4003 a.x = -1; 4004 EXPECT_FALSE(m.Matches(a)); 4005} 4006 4007// Tests that Field(&Foo::field, ...) works when the argument's type 4008// is a sub-type of Foo. 4009TEST(FieldTest, WorksForArgumentOfSubType) { 4010 // Note that the matcher expects DerivedStruct but we say AStruct 4011 // inside Field(). 4012 Matcher<const DerivedStruct&> m = Field(&AStruct::x, Ge(0)); 4013 4014 DerivedStruct d; 4015 EXPECT_TRUE(m.Matches(d)); 4016 d.x = -1; 4017 EXPECT_FALSE(m.Matches(d)); 4018} 4019 4020// Tests that Field(&Foo::field, m) works when field's type and m's 4021// argument type are compatible but not the same. 4022TEST(FieldTest, WorksForCompatibleMatcherType) { 4023 // The field is an int, but the inner matcher expects a signed char. 4024 Matcher<const AStruct&> m = Field(&AStruct::x, 4025 Matcher<signed char>(Ge(0))); 4026 4027 AStruct a; 4028 EXPECT_TRUE(m.Matches(a)); 4029 a.x = -1; 4030 EXPECT_FALSE(m.Matches(a)); 4031} 4032 4033// Tests that Field() can describe itself. 4034TEST(FieldTest, CanDescribeSelf) { 4035 Matcher<const AStruct&> m = Field(&AStruct::x, Ge(0)); 4036 4037 EXPECT_EQ("is an object whose given field is >= 0", Describe(m)); 4038 EXPECT_EQ("is an object whose given field isn't >= 0", DescribeNegation(m)); 4039} 4040 4041TEST(FieldTest, CanDescribeSelfWithFieldName) { 4042 Matcher<const AStruct&> m = Field("field_name", &AStruct::x, Ge(0)); 4043 4044 EXPECT_EQ("is an object whose field `field_name` is >= 0", Describe(m)); 4045 EXPECT_EQ("is an object whose field `field_name` isn't >= 0", 4046 DescribeNegation(m)); 4047} 4048 4049// Tests that Field() can explain the match result. 4050TEST(FieldTest, CanExplainMatchResult) { 4051 Matcher<const AStruct&> m = Field(&AStruct::x, Ge(0)); 4052 4053 AStruct a; 4054 a.x = 1; 4055 EXPECT_EQ("whose given field is 1" + OfType("int"), Explain(m, a)); 4056 4057 m = Field(&AStruct::x, GreaterThan(0)); 4058 EXPECT_EQ( 4059 "whose given field is 1" + OfType("int") + ", which is 1 more than 0", 4060 Explain(m, a)); 4061} 4062 4063TEST(FieldTest, CanExplainMatchResultWithFieldName) { 4064 Matcher<const AStruct&> m = Field("field_name", &AStruct::x, Ge(0)); 4065 4066 AStruct a; 4067 a.x = 1; 4068 EXPECT_EQ("whose field `field_name` is 1" + OfType("int"), Explain(m, a)); 4069 4070 m = Field("field_name", &AStruct::x, GreaterThan(0)); 4071 EXPECT_EQ("whose field `field_name` is 1" + OfType("int") + 4072 ", which is 1 more than 0", 4073 Explain(m, a)); 4074} 4075 4076// Tests that Field() works when the argument is a pointer to const. 4077TEST(FieldForPointerTest, WorksForPointerToConst) { 4078 Matcher<const AStruct*> m = Field(&AStruct::x, Ge(0)); 4079 4080 AStruct a; 4081 EXPECT_TRUE(m.Matches(&a)); 4082 a.x = -1; 4083 EXPECT_FALSE(m.Matches(&a)); 4084} 4085 4086// Tests that Field() works when the argument is a pointer to non-const. 4087TEST(FieldForPointerTest, WorksForPointerToNonConst) { 4088 Matcher<AStruct*> m = Field(&AStruct::x, Ge(0)); 4089 4090 AStruct a; 4091 EXPECT_TRUE(m.Matches(&a)); 4092 a.x = -1; 4093 EXPECT_FALSE(m.Matches(&a)); 4094} 4095 4096// Tests that Field() works when the argument is a reference to a const pointer. 4097TEST(FieldForPointerTest, WorksForReferenceToConstPointer) { 4098 Matcher<AStruct* const&> m = Field(&AStruct::x, Ge(0)); 4099 4100 AStruct a; 4101 EXPECT_TRUE(m.Matches(&a)); 4102 a.x = -1; 4103 EXPECT_FALSE(m.Matches(&a)); 4104} 4105 4106// Tests that Field() does not match the NULL pointer. 4107TEST(FieldForPointerTest, DoesNotMatchNull) { 4108 Matcher<const AStruct*> m = Field(&AStruct::x, _); 4109 EXPECT_FALSE(m.Matches(NULL)); 4110} 4111 4112// Tests that Field(&Foo::field, ...) works when the argument's type 4113// is a sub-type of const Foo*. 4114TEST(FieldForPointerTest, WorksForArgumentOfSubType) { 4115 // Note that the matcher expects DerivedStruct but we say AStruct 4116 // inside Field(). 4117 Matcher<DerivedStruct*> m = Field(&AStruct::x, Ge(0)); 4118 4119 DerivedStruct d; 4120 EXPECT_TRUE(m.Matches(&d)); 4121 d.x = -1; 4122 EXPECT_FALSE(m.Matches(&d)); 4123} 4124 4125// Tests that Field() can describe itself when used to match a pointer. 4126TEST(FieldForPointerTest, CanDescribeSelf) { 4127 Matcher<const AStruct*> m = Field(&AStruct::x, Ge(0)); 4128 4129 EXPECT_EQ("is an object whose given field is >= 0", Describe(m)); 4130 EXPECT_EQ("is an object whose given field isn't >= 0", DescribeNegation(m)); 4131} 4132 4133TEST(FieldForPointerTest, CanDescribeSelfWithFieldName) { 4134 Matcher<const AStruct*> m = Field("field_name", &AStruct::x, Ge(0)); 4135 4136 EXPECT_EQ("is an object whose field `field_name` is >= 0", Describe(m)); 4137 EXPECT_EQ("is an object whose field `field_name` isn't >= 0", 4138 DescribeNegation(m)); 4139} 4140 4141// Tests that Field() can explain the result of matching a pointer. 4142TEST(FieldForPointerTest, CanExplainMatchResult) { 4143 Matcher<const AStruct*> m = Field(&AStruct::x, Ge(0)); 4144 4145 AStruct a; 4146 a.x = 1; 4147 EXPECT_EQ("", Explain(m, static_cast<const AStruct*>(NULL))); 4148 EXPECT_EQ("which points to an object whose given field is 1" + OfType("int"), 4149 Explain(m, &a)); 4150 4151 m = Field(&AStruct::x, GreaterThan(0)); 4152 EXPECT_EQ("which points to an object whose given field is 1" + OfType("int") + 4153 ", which is 1 more than 0", Explain(m, &a)); 4154} 4155 4156TEST(FieldForPointerTest, CanExplainMatchResultWithFieldName) { 4157 Matcher<const AStruct*> m = Field("field_name", &AStruct::x, Ge(0)); 4158 4159 AStruct a; 4160 a.x = 1; 4161 EXPECT_EQ("", Explain(m, static_cast<const AStruct*>(NULL))); 4162 EXPECT_EQ( 4163 "which points to an object whose field `field_name` is 1" + OfType("int"), 4164 Explain(m, &a)); 4165 4166 m = Field("field_name", &AStruct::x, GreaterThan(0)); 4167 EXPECT_EQ("which points to an object whose field `field_name` is 1" + 4168 OfType("int") + ", which is 1 more than 0", 4169 Explain(m, &a)); 4170} 4171 4172// A user-defined class for testing Property(). 4173class AClass { 4174 public: 4175 AClass() : n_(0) {} 4176 4177 // A getter that returns a non-reference. 4178 int n() const { return n_; } 4179 4180 void set_n(int new_n) { n_ = new_n; } 4181 4182 // A getter that returns a reference to const. 4183 const std::string& s() const { return s_; } 4184 4185#if GTEST_LANG_CXX11 4186 const std::string& s_ref() const & { return s_; } 4187#endif 4188 4189 void set_s(const std::string& new_s) { s_ = new_s; } 4190 4191 // A getter that returns a reference to non-const. 4192 double& x() const { return x_; } 4193 4194 private: 4195 int n_; 4196 std::string s_; 4197 4198 static double x_; 4199}; 4200 4201double AClass::x_ = 0.0; 4202 4203// A derived class for testing Property(). 4204class DerivedClass : public AClass { 4205 public: 4206 int k() const { return k_; } 4207 private: 4208 int k_; 4209}; 4210 4211// Tests that Property(&Foo::property, ...) works when property() 4212// returns a non-reference. 4213TEST(PropertyTest, WorksForNonReferenceProperty) { 4214 Matcher<const AClass&> m = Property(&AClass::n, Ge(0)); 4215 Matcher<const AClass&> m_with_name = Property("n", &AClass::n, Ge(0)); 4216 4217 AClass a; 4218 a.set_n(1); 4219 EXPECT_TRUE(m.Matches(a)); 4220 EXPECT_TRUE(m_with_name.Matches(a)); 4221 4222 a.set_n(-1); 4223 EXPECT_FALSE(m.Matches(a)); 4224 EXPECT_FALSE(m_with_name.Matches(a)); 4225} 4226 4227// Tests that Property(&Foo::property, ...) works when property() 4228// returns a reference to const. 4229TEST(PropertyTest, WorksForReferenceToConstProperty) { 4230 Matcher<const AClass&> m = Property(&AClass::s, StartsWith("hi")); 4231 Matcher<const AClass&> m_with_name = 4232 Property("s", &AClass::s, StartsWith("hi")); 4233 4234 AClass a; 4235 a.set_s("hill"); 4236 EXPECT_TRUE(m.Matches(a)); 4237 EXPECT_TRUE(m_with_name.Matches(a)); 4238 4239 a.set_s("hole"); 4240 EXPECT_FALSE(m.Matches(a)); 4241 EXPECT_FALSE(m_with_name.Matches(a)); 4242} 4243 4244#if GTEST_LANG_CXX11 4245// Tests that Property(&Foo::property, ...) works when property() is 4246// ref-qualified. 4247TEST(PropertyTest, WorksForRefQualifiedProperty) { 4248 Matcher<const AClass&> m = Property(&AClass::s_ref, StartsWith("hi")); 4249 Matcher<const AClass&> m_with_name = 4250 Property("s", &AClass::s_ref, StartsWith("hi")); 4251 4252 AClass a; 4253 a.set_s("hill"); 4254 EXPECT_TRUE(m.Matches(a)); 4255 EXPECT_TRUE(m_with_name.Matches(a)); 4256 4257 a.set_s("hole"); 4258 EXPECT_FALSE(m.Matches(a)); 4259 EXPECT_FALSE(m_with_name.Matches(a)); 4260} 4261#endif 4262 4263// Tests that Property(&Foo::property, ...) works when property() 4264// returns a reference to non-const. 4265TEST(PropertyTest, WorksForReferenceToNonConstProperty) { 4266 double x = 0.0; 4267 AClass a; 4268 4269 Matcher<const AClass&> m = Property(&AClass::x, Ref(x)); 4270 EXPECT_FALSE(m.Matches(a)); 4271 4272 m = Property(&AClass::x, Not(Ref(x))); 4273 EXPECT_TRUE(m.Matches(a)); 4274} 4275 4276// Tests that Property(&Foo::property, ...) works when the argument is 4277// passed by value. 4278TEST(PropertyTest, WorksForByValueArgument) { 4279 Matcher<AClass> m = Property(&AClass::s, StartsWith("hi")); 4280 4281 AClass a; 4282 a.set_s("hill"); 4283 EXPECT_TRUE(m.Matches(a)); 4284 4285 a.set_s("hole"); 4286 EXPECT_FALSE(m.Matches(a)); 4287} 4288 4289// Tests that Property(&Foo::property, ...) works when the argument's 4290// type is a sub-type of Foo. 4291TEST(PropertyTest, WorksForArgumentOfSubType) { 4292 // The matcher expects a DerivedClass, but inside the Property() we 4293 // say AClass. 4294 Matcher<const DerivedClass&> m = Property(&AClass::n, Ge(0)); 4295 4296 DerivedClass d; 4297 d.set_n(1); 4298 EXPECT_TRUE(m.Matches(d)); 4299 4300 d.set_n(-1); 4301 EXPECT_FALSE(m.Matches(d)); 4302} 4303 4304// Tests that Property(&Foo::property, m) works when property()'s type 4305// and m's argument type are compatible but different. 4306TEST(PropertyTest, WorksForCompatibleMatcherType) { 4307 // n() returns an int but the inner matcher expects a signed char. 4308 Matcher<const AClass&> m = Property(&AClass::n, 4309 Matcher<signed char>(Ge(0))); 4310 4311 Matcher<const AClass&> m_with_name = 4312 Property("n", &AClass::n, Matcher<signed char>(Ge(0))); 4313 4314 AClass a; 4315 EXPECT_TRUE(m.Matches(a)); 4316 EXPECT_TRUE(m_with_name.Matches(a)); 4317 a.set_n(-1); 4318 EXPECT_FALSE(m.Matches(a)); 4319 EXPECT_FALSE(m_with_name.Matches(a)); 4320} 4321 4322// Tests that Property() can describe itself. 4323TEST(PropertyTest, CanDescribeSelf) { 4324 Matcher<const AClass&> m = Property(&AClass::n, Ge(0)); 4325 4326 EXPECT_EQ("is an object whose given property is >= 0", Describe(m)); 4327 EXPECT_EQ("is an object whose given property isn't >= 0", 4328 DescribeNegation(m)); 4329} 4330 4331TEST(PropertyTest, CanDescribeSelfWithPropertyName) { 4332 Matcher<const AClass&> m = Property("fancy_name", &AClass::n, Ge(0)); 4333 4334 EXPECT_EQ("is an object whose property `fancy_name` is >= 0", Describe(m)); 4335 EXPECT_EQ("is an object whose property `fancy_name` isn't >= 0", 4336 DescribeNegation(m)); 4337} 4338 4339// Tests that Property() can explain the match result. 4340TEST(PropertyTest, CanExplainMatchResult) { 4341 Matcher<const AClass&> m = Property(&AClass::n, Ge(0)); 4342 4343 AClass a; 4344 a.set_n(1); 4345 EXPECT_EQ("whose given property is 1" + OfType("int"), Explain(m, a)); 4346 4347 m = Property(&AClass::n, GreaterThan(0)); 4348 EXPECT_EQ( 4349 "whose given property is 1" + OfType("int") + ", which is 1 more than 0", 4350 Explain(m, a)); 4351} 4352 4353TEST(PropertyTest, CanExplainMatchResultWithPropertyName) { 4354 Matcher<const AClass&> m = Property("fancy_name", &AClass::n, Ge(0)); 4355 4356 AClass a; 4357 a.set_n(1); 4358 EXPECT_EQ("whose property `fancy_name` is 1" + OfType("int"), Explain(m, a)); 4359 4360 m = Property("fancy_name", &AClass::n, GreaterThan(0)); 4361 EXPECT_EQ("whose property `fancy_name` is 1" + OfType("int") + 4362 ", which is 1 more than 0", 4363 Explain(m, a)); 4364} 4365 4366// Tests that Property() works when the argument is a pointer to const. 4367TEST(PropertyForPointerTest, WorksForPointerToConst) { 4368 Matcher<const AClass*> m = Property(&AClass::n, Ge(0)); 4369 4370 AClass a; 4371 a.set_n(1); 4372 EXPECT_TRUE(m.Matches(&a)); 4373 4374 a.set_n(-1); 4375 EXPECT_FALSE(m.Matches(&a)); 4376} 4377 4378// Tests that Property() works when the argument is a pointer to non-const. 4379TEST(PropertyForPointerTest, WorksForPointerToNonConst) { 4380 Matcher<AClass*> m = Property(&AClass::s, StartsWith("hi")); 4381 4382 AClass a; 4383 a.set_s("hill"); 4384 EXPECT_TRUE(m.Matches(&a)); 4385 4386 a.set_s("hole"); 4387 EXPECT_FALSE(m.Matches(&a)); 4388} 4389 4390// Tests that Property() works when the argument is a reference to a 4391// const pointer. 4392TEST(PropertyForPointerTest, WorksForReferenceToConstPointer) { 4393 Matcher<AClass* const&> m = Property(&AClass::s, StartsWith("hi")); 4394 4395 AClass a; 4396 a.set_s("hill"); 4397 EXPECT_TRUE(m.Matches(&a)); 4398 4399 a.set_s("hole"); 4400 EXPECT_FALSE(m.Matches(&a)); 4401} 4402 4403// Tests that Property() does not match the NULL pointer. 4404TEST(PropertyForPointerTest, WorksForReferenceToNonConstProperty) { 4405 Matcher<const AClass*> m = Property(&AClass::x, _); 4406 EXPECT_FALSE(m.Matches(NULL)); 4407} 4408 4409// Tests that Property(&Foo::property, ...) works when the argument's 4410// type is a sub-type of const Foo*. 4411TEST(PropertyForPointerTest, WorksForArgumentOfSubType) { 4412 // The matcher expects a DerivedClass, but inside the Property() we 4413 // say AClass. 4414 Matcher<const DerivedClass*> m = Property(&AClass::n, Ge(0)); 4415 4416 DerivedClass d; 4417 d.set_n(1); 4418 EXPECT_TRUE(m.Matches(&d)); 4419 4420 d.set_n(-1); 4421 EXPECT_FALSE(m.Matches(&d)); 4422} 4423 4424// Tests that Property() can describe itself when used to match a pointer. 4425TEST(PropertyForPointerTest, CanDescribeSelf) { 4426 Matcher<const AClass*> m = Property(&AClass::n, Ge(0)); 4427 4428 EXPECT_EQ("is an object whose given property is >= 0", Describe(m)); 4429 EXPECT_EQ("is an object whose given property isn't >= 0", 4430 DescribeNegation(m)); 4431} 4432 4433TEST(PropertyForPointerTest, CanDescribeSelfWithPropertyDescription) { 4434 Matcher<const AClass*> m = Property("fancy_name", &AClass::n, Ge(0)); 4435 4436 EXPECT_EQ("is an object whose property `fancy_name` is >= 0", Describe(m)); 4437 EXPECT_EQ("is an object whose property `fancy_name` isn't >= 0", 4438 DescribeNegation(m)); 4439} 4440 4441// Tests that Property() can explain the result of matching a pointer. 4442TEST(PropertyForPointerTest, CanExplainMatchResult) { 4443 Matcher<const AClass*> m = Property(&AClass::n, Ge(0)); 4444 4445 AClass a; 4446 a.set_n(1); 4447 EXPECT_EQ("", Explain(m, static_cast<const AClass*>(NULL))); 4448 EXPECT_EQ( 4449 "which points to an object whose given property is 1" + OfType("int"), 4450 Explain(m, &a)); 4451 4452 m = Property(&AClass::n, GreaterThan(0)); 4453 EXPECT_EQ("which points to an object whose given property is 1" + 4454 OfType("int") + ", which is 1 more than 0", 4455 Explain(m, &a)); 4456} 4457 4458TEST(PropertyForPointerTest, CanExplainMatchResultWithPropertyName) { 4459 Matcher<const AClass*> m = Property("fancy_name", &AClass::n, Ge(0)); 4460 4461 AClass a; 4462 a.set_n(1); 4463 EXPECT_EQ("", Explain(m, static_cast<const AClass*>(NULL))); 4464 EXPECT_EQ("which points to an object whose property `fancy_name` is 1" + 4465 OfType("int"), 4466 Explain(m, &a)); 4467 4468 m = Property("fancy_name", &AClass::n, GreaterThan(0)); 4469 EXPECT_EQ("which points to an object whose property `fancy_name` is 1" + 4470 OfType("int") + ", which is 1 more than 0", 4471 Explain(m, &a)); 4472} 4473 4474// Tests ResultOf. 4475 4476// Tests that ResultOf(f, ...) compiles and works as expected when f is a 4477// function pointer. 4478std::string IntToStringFunction(int input) { 4479 return input == 1 ? "foo" : "bar"; 4480} 4481 4482TEST(ResultOfTest, WorksForFunctionPointers) { 4483 Matcher<int> matcher = ResultOf(&IntToStringFunction, Eq(std::string("foo"))); 4484 4485 EXPECT_TRUE(matcher.Matches(1)); 4486 EXPECT_FALSE(matcher.Matches(2)); 4487} 4488 4489// Tests that ResultOf() can describe itself. 4490TEST(ResultOfTest, CanDescribeItself) { 4491 Matcher<int> matcher = ResultOf(&IntToStringFunction, StrEq("foo")); 4492 4493 EXPECT_EQ("is mapped by the given callable to a value that " 4494 "is equal to \"foo\"", Describe(matcher)); 4495 EXPECT_EQ("is mapped by the given callable to a value that " 4496 "isn't equal to \"foo\"", DescribeNegation(matcher)); 4497} 4498 4499// Tests that ResultOf() can explain the match result. 4500int IntFunction(int input) { return input == 42 ? 80 : 90; } 4501 4502TEST(ResultOfTest, CanExplainMatchResult) { 4503 Matcher<int> matcher = ResultOf(&IntFunction, Ge(85)); 4504 EXPECT_EQ("which is mapped by the given callable to 90" + OfType("int"), 4505 Explain(matcher, 36)); 4506 4507 matcher = ResultOf(&IntFunction, GreaterThan(85)); 4508 EXPECT_EQ("which is mapped by the given callable to 90" + OfType("int") + 4509 ", which is 5 more than 85", Explain(matcher, 36)); 4510} 4511 4512// Tests that ResultOf(f, ...) compiles and works as expected when f(x) 4513// returns a non-reference. 4514TEST(ResultOfTest, WorksForNonReferenceResults) { 4515 Matcher<int> matcher = ResultOf(&IntFunction, Eq(80)); 4516 4517 EXPECT_TRUE(matcher.Matches(42)); 4518 EXPECT_FALSE(matcher.Matches(36)); 4519} 4520 4521// Tests that ResultOf(f, ...) compiles and works as expected when f(x) 4522// returns a reference to non-const. 4523double& DoubleFunction(double& input) { return input; } // NOLINT 4524 4525Uncopyable& RefUncopyableFunction(Uncopyable& obj) { // NOLINT 4526 return obj; 4527} 4528 4529TEST(ResultOfTest, WorksForReferenceToNonConstResults) { 4530 double x = 3.14; 4531 double x2 = x; 4532 Matcher<double&> matcher = ResultOf(&DoubleFunction, Ref(x)); 4533 4534 EXPECT_TRUE(matcher.Matches(x)); 4535 EXPECT_FALSE(matcher.Matches(x2)); 4536 4537 // Test that ResultOf works with uncopyable objects 4538 Uncopyable obj(0); 4539 Uncopyable obj2(0); 4540 Matcher<Uncopyable&> matcher2 = 4541 ResultOf(&RefUncopyableFunction, Ref(obj)); 4542 4543 EXPECT_TRUE(matcher2.Matches(obj)); 4544 EXPECT_FALSE(matcher2.Matches(obj2)); 4545} 4546 4547// Tests that ResultOf(f, ...) compiles and works as expected when f(x) 4548// returns a reference to const. 4549const std::string& StringFunction(const std::string& input) { return input; } 4550 4551TEST(ResultOfTest, WorksForReferenceToConstResults) { 4552 std::string s = "foo"; 4553 std::string s2 = s; 4554 Matcher<const std::string&> matcher = ResultOf(&StringFunction, Ref(s)); 4555 4556 EXPECT_TRUE(matcher.Matches(s)); 4557 EXPECT_FALSE(matcher.Matches(s2)); 4558} 4559 4560// Tests that ResultOf(f, m) works when f(x) and m's 4561// argument types are compatible but different. 4562TEST(ResultOfTest, WorksForCompatibleMatcherTypes) { 4563 // IntFunction() returns int but the inner matcher expects a signed char. 4564 Matcher<int> matcher = ResultOf(IntFunction, Matcher<signed char>(Ge(85))); 4565 4566 EXPECT_TRUE(matcher.Matches(36)); 4567 EXPECT_FALSE(matcher.Matches(42)); 4568} 4569 4570// Tests that the program aborts when ResultOf is passed 4571// a NULL function pointer. 4572TEST(ResultOfDeathTest, DiesOnNullFunctionPointers) { 4573 EXPECT_DEATH_IF_SUPPORTED( 4574 ResultOf(static_cast<std::string (*)(int dummy)>(NULL), 4575 Eq(std::string("foo"))), 4576 "NULL function pointer is passed into ResultOf\\(\\)\\."); 4577} 4578 4579// Tests that ResultOf(f, ...) compiles and works as expected when f is a 4580// function reference. 4581TEST(ResultOfTest, WorksForFunctionReferences) { 4582 Matcher<int> matcher = ResultOf(IntToStringFunction, StrEq("foo")); 4583 EXPECT_TRUE(matcher.Matches(1)); 4584 EXPECT_FALSE(matcher.Matches(2)); 4585} 4586 4587// Tests that ResultOf(f, ...) compiles and works as expected when f is a 4588// function object. 4589struct Functor : public ::std::unary_function<int, std::string> { 4590 result_type operator()(argument_type input) const { 4591 return IntToStringFunction(input); 4592 } 4593}; 4594 4595TEST(ResultOfTest, WorksForFunctors) { 4596 Matcher<int> matcher = ResultOf(Functor(), Eq(std::string("foo"))); 4597 4598 EXPECT_TRUE(matcher.Matches(1)); 4599 EXPECT_FALSE(matcher.Matches(2)); 4600} 4601 4602// Tests that ResultOf(f, ...) compiles and works as expected when f is a 4603// functor with more than one operator() defined. ResultOf() must work 4604// for each defined operator(). 4605struct PolymorphicFunctor { 4606 typedef int result_type; 4607 int operator()(int n) { return n; } 4608 int operator()(const char* s) { return static_cast<int>(strlen(s)); } 4609 std::string operator()(int *p) { return p ? "good ptr" : "null"; } 4610}; 4611 4612TEST(ResultOfTest, WorksForPolymorphicFunctors) { 4613 Matcher<int> matcher_int = ResultOf(PolymorphicFunctor(), Ge(5)); 4614 4615 EXPECT_TRUE(matcher_int.Matches(10)); 4616 EXPECT_FALSE(matcher_int.Matches(2)); 4617 4618 Matcher<const char*> matcher_string = ResultOf(PolymorphicFunctor(), Ge(5)); 4619 4620 EXPECT_TRUE(matcher_string.Matches("long string")); 4621 EXPECT_FALSE(matcher_string.Matches("shrt")); 4622} 4623 4624#if GTEST_LANG_CXX11 4625TEST(ResultOfTest, WorksForPolymorphicFunctorsIgnoringResultType) { 4626 Matcher<int*> matcher = ResultOf(PolymorphicFunctor(), "good ptr"); 4627 4628 int n = 0; 4629 EXPECT_TRUE(matcher.Matches(&n)); 4630 EXPECT_FALSE(matcher.Matches(nullptr)); 4631} 4632 4633TEST(ResultOfTest, WorksForLambdas) { 4634 Matcher<int> matcher = 4635 ResultOf([](int str_len) { return std::string(str_len, 'x'); }, "xxx"); 4636 EXPECT_TRUE(matcher.Matches(3)); 4637 EXPECT_FALSE(matcher.Matches(1)); 4638} 4639#endif 4640 4641const int* ReferencingFunction(const int& n) { return &n; } 4642 4643struct ReferencingFunctor { 4644 typedef const int* result_type; 4645 result_type operator()(const int& n) { return &n; } 4646}; 4647 4648TEST(ResultOfTest, WorksForReferencingCallables) { 4649 const int n = 1; 4650 const int n2 = 1; 4651 Matcher<const int&> matcher2 = ResultOf(ReferencingFunction, Eq(&n)); 4652 EXPECT_TRUE(matcher2.Matches(n)); 4653 EXPECT_FALSE(matcher2.Matches(n2)); 4654 4655 Matcher<const int&> matcher3 = ResultOf(ReferencingFunctor(), Eq(&n)); 4656 EXPECT_TRUE(matcher3.Matches(n)); 4657 EXPECT_FALSE(matcher3.Matches(n2)); 4658} 4659 4660class DivisibleByImpl { 4661 public: 4662 explicit DivisibleByImpl(int a_divider) : divider_(a_divider) {} 4663 4664 // For testing using ExplainMatchResultTo() with polymorphic matchers. 4665 template <typename T> 4666 bool MatchAndExplain(const T& n, MatchResultListener* listener) const { 4667 *listener << "which is " << (n % divider_) << " modulo " 4668 << divider_; 4669 return (n % divider_) == 0; 4670 } 4671 4672 void DescribeTo(ostream* os) const { 4673 *os << "is divisible by " << divider_; 4674 } 4675 4676 void DescribeNegationTo(ostream* os) const { 4677 *os << "is not divisible by " << divider_; 4678 } 4679 4680 void set_divider(int a_divider) { divider_ = a_divider; } 4681 int divider() const { return divider_; } 4682 4683 private: 4684 int divider_; 4685}; 4686 4687PolymorphicMatcher<DivisibleByImpl> DivisibleBy(int n) { 4688 return MakePolymorphicMatcher(DivisibleByImpl(n)); 4689} 4690 4691// Tests that when AllOf() fails, only the first failing matcher is 4692// asked to explain why. 4693TEST(ExplainMatchResultTest, AllOf_False_False) { 4694 const Matcher<int> m = AllOf(DivisibleBy(4), DivisibleBy(3)); 4695 EXPECT_EQ("which is 1 modulo 4", Explain(m, 5)); 4696} 4697 4698// Tests that when AllOf() fails, only the first failing matcher is 4699// asked to explain why. 4700TEST(ExplainMatchResultTest, AllOf_False_True) { 4701 const Matcher<int> m = AllOf(DivisibleBy(4), DivisibleBy(3)); 4702 EXPECT_EQ("which is 2 modulo 4", Explain(m, 6)); 4703} 4704 4705// Tests that when AllOf() fails, only the first failing matcher is 4706// asked to explain why. 4707TEST(ExplainMatchResultTest, AllOf_True_False) { 4708 const Matcher<int> m = AllOf(Ge(1), DivisibleBy(3)); 4709 EXPECT_EQ("which is 2 modulo 3", Explain(m, 5)); 4710} 4711 4712// Tests that when AllOf() succeeds, all matchers are asked to explain 4713// why. 4714TEST(ExplainMatchResultTest, AllOf_True_True) { 4715 const Matcher<int> m = AllOf(DivisibleBy(2), DivisibleBy(3)); 4716 EXPECT_EQ("which is 0 modulo 2, and which is 0 modulo 3", Explain(m, 6)); 4717} 4718 4719TEST(ExplainMatchResultTest, AllOf_True_True_2) { 4720 const Matcher<int> m = AllOf(Ge(2), Le(3)); 4721 EXPECT_EQ("", Explain(m, 2)); 4722} 4723 4724TEST(ExplainmatcherResultTest, MonomorphicMatcher) { 4725 const Matcher<int> m = GreaterThan(5); 4726 EXPECT_EQ("which is 1 more than 5", Explain(m, 6)); 4727} 4728 4729// The following two tests verify that values without a public copy 4730// ctor can be used as arguments to matchers like Eq(), Ge(), and etc 4731// with the help of ByRef(). 4732 4733class NotCopyable { 4734 public: 4735 explicit NotCopyable(int a_value) : value_(a_value) {} 4736 4737 int value() const { return value_; } 4738 4739 bool operator==(const NotCopyable& rhs) const { 4740 return value() == rhs.value(); 4741 } 4742 4743 bool operator>=(const NotCopyable& rhs) const { 4744 return value() >= rhs.value(); 4745 } 4746 private: 4747 int value_; 4748 4749 GTEST_DISALLOW_COPY_AND_ASSIGN_(NotCopyable); 4750}; 4751 4752TEST(ByRefTest, AllowsNotCopyableConstValueInMatchers) { 4753 const NotCopyable const_value1(1); 4754 const Matcher<const NotCopyable&> m = Eq(ByRef(const_value1)); 4755 4756 const NotCopyable n1(1), n2(2); 4757 EXPECT_TRUE(m.Matches(n1)); 4758 EXPECT_FALSE(m.Matches(n2)); 4759} 4760 4761TEST(ByRefTest, AllowsNotCopyableValueInMatchers) { 4762 NotCopyable value2(2); 4763 const Matcher<NotCopyable&> m = Ge(ByRef(value2)); 4764 4765 NotCopyable n1(1), n2(2); 4766 EXPECT_FALSE(m.Matches(n1)); 4767 EXPECT_TRUE(m.Matches(n2)); 4768} 4769 4770TEST(IsEmptyTest, ImplementsIsEmpty) { 4771 vector<int> container; 4772 EXPECT_THAT(container, IsEmpty()); 4773 container.push_back(0); 4774 EXPECT_THAT(container, Not(IsEmpty())); 4775 container.push_back(1); 4776 EXPECT_THAT(container, Not(IsEmpty())); 4777} 4778 4779TEST(IsEmptyTest, WorksWithString) { 4780 std::string text; 4781 EXPECT_THAT(text, IsEmpty()); 4782 text = "foo"; 4783 EXPECT_THAT(text, Not(IsEmpty())); 4784 text = std::string("\0", 1); 4785 EXPECT_THAT(text, Not(IsEmpty())); 4786} 4787 4788TEST(IsEmptyTest, CanDescribeSelf) { 4789 Matcher<vector<int> > m = IsEmpty(); 4790 EXPECT_EQ("is empty", Describe(m)); 4791 EXPECT_EQ("isn't empty", DescribeNegation(m)); 4792} 4793 4794TEST(IsEmptyTest, ExplainsResult) { 4795 Matcher<vector<int> > m = IsEmpty(); 4796 vector<int> container; 4797 EXPECT_EQ("", Explain(m, container)); 4798 container.push_back(0); 4799 EXPECT_EQ("whose size is 1", Explain(m, container)); 4800} 4801 4802TEST(IsTrueTest, IsTrueIsFalse) { 4803 EXPECT_THAT(true, IsTrue()); 4804 EXPECT_THAT(false, IsFalse()); 4805 EXPECT_THAT(true, Not(IsFalse())); 4806 EXPECT_THAT(false, Not(IsTrue())); 4807 EXPECT_THAT(0, Not(IsTrue())); 4808 EXPECT_THAT(0, IsFalse()); 4809 EXPECT_THAT(NULL, Not(IsTrue())); 4810 EXPECT_THAT(NULL, IsFalse()); 4811 EXPECT_THAT(-1, IsTrue()); 4812 EXPECT_THAT(-1, Not(IsFalse())); 4813 EXPECT_THAT(1, IsTrue()); 4814 EXPECT_THAT(1, Not(IsFalse())); 4815 EXPECT_THAT(2, IsTrue()); 4816 EXPECT_THAT(2, Not(IsFalse())); 4817 int a = 42; 4818 EXPECT_THAT(a, IsTrue()); 4819 EXPECT_THAT(a, Not(IsFalse())); 4820 EXPECT_THAT(&a, IsTrue()); 4821 EXPECT_THAT(&a, Not(IsFalse())); 4822 EXPECT_THAT(false, Not(IsTrue())); 4823 EXPECT_THAT(true, Not(IsFalse())); 4824#if GTEST_LANG_CXX11 4825 EXPECT_THAT(std::true_type(), IsTrue()); 4826 EXPECT_THAT(std::true_type(), Not(IsFalse())); 4827 EXPECT_THAT(std::false_type(), IsFalse()); 4828 EXPECT_THAT(std::false_type(), Not(IsTrue())); 4829 EXPECT_THAT(nullptr, Not(IsTrue())); 4830 EXPECT_THAT(nullptr, IsFalse()); 4831 std::unique_ptr<int> null_unique; 4832 std::unique_ptr<int> nonnull_unique(new int(0)); 4833 EXPECT_THAT(null_unique, Not(IsTrue())); 4834 EXPECT_THAT(null_unique, IsFalse()); 4835 EXPECT_THAT(nonnull_unique, IsTrue()); 4836 EXPECT_THAT(nonnull_unique, Not(IsFalse())); 4837#endif // GTEST_LANG_CXX11 4838} 4839 4840TEST(SizeIsTest, ImplementsSizeIs) { 4841 vector<int> container; 4842 EXPECT_THAT(container, SizeIs(0)); 4843 EXPECT_THAT(container, Not(SizeIs(1))); 4844 container.push_back(0); 4845 EXPECT_THAT(container, Not(SizeIs(0))); 4846 EXPECT_THAT(container, SizeIs(1)); 4847 container.push_back(0); 4848 EXPECT_THAT(container, Not(SizeIs(0))); 4849 EXPECT_THAT(container, SizeIs(2)); 4850} 4851 4852TEST(SizeIsTest, WorksWithMap) { 4853 map<std::string, int> container; 4854 EXPECT_THAT(container, SizeIs(0)); 4855 EXPECT_THAT(container, Not(SizeIs(1))); 4856 container.insert(make_pair("foo", 1)); 4857 EXPECT_THAT(container, Not(SizeIs(0))); 4858 EXPECT_THAT(container, SizeIs(1)); 4859 container.insert(make_pair("bar", 2)); 4860 EXPECT_THAT(container, Not(SizeIs(0))); 4861 EXPECT_THAT(container, SizeIs(2)); 4862} 4863 4864TEST(SizeIsTest, WorksWithReferences) { 4865 vector<int> container; 4866 Matcher<const vector<int>&> m = SizeIs(1); 4867 EXPECT_THAT(container, Not(m)); 4868 container.push_back(0); 4869 EXPECT_THAT(container, m); 4870} 4871 4872TEST(SizeIsTest, CanDescribeSelf) { 4873 Matcher<vector<int> > m = SizeIs(2); 4874 EXPECT_EQ("size is equal to 2", Describe(m)); 4875 EXPECT_EQ("size isn't equal to 2", DescribeNegation(m)); 4876} 4877 4878TEST(SizeIsTest, ExplainsResult) { 4879 Matcher<vector<int> > m1 = SizeIs(2); 4880 Matcher<vector<int> > m2 = SizeIs(Lt(2u)); 4881 Matcher<vector<int> > m3 = SizeIs(AnyOf(0, 3)); 4882 Matcher<vector<int> > m4 = SizeIs(GreaterThan(1)); 4883 vector<int> container; 4884 EXPECT_EQ("whose size 0 doesn't match", Explain(m1, container)); 4885 EXPECT_EQ("whose size 0 matches", Explain(m2, container)); 4886 EXPECT_EQ("whose size 0 matches", Explain(m3, container)); 4887 EXPECT_EQ("whose size 0 doesn't match, which is 1 less than 1", 4888 Explain(m4, container)); 4889 container.push_back(0); 4890 container.push_back(0); 4891 EXPECT_EQ("whose size 2 matches", Explain(m1, container)); 4892 EXPECT_EQ("whose size 2 doesn't match", Explain(m2, container)); 4893 EXPECT_EQ("whose size 2 doesn't match", Explain(m3, container)); 4894 EXPECT_EQ("whose size 2 matches, which is 1 more than 1", 4895 Explain(m4, container)); 4896} 4897 4898#if GTEST_HAS_TYPED_TEST 4899// Tests ContainerEq with different container types, and 4900// different element types. 4901 4902template <typename T> 4903class ContainerEqTest : public testing::Test {}; 4904 4905typedef testing::Types< 4906 set<int>, 4907 vector<size_t>, 4908 multiset<size_t>, 4909 list<int> > 4910 ContainerEqTestTypes; 4911 4912TYPED_TEST_CASE(ContainerEqTest, ContainerEqTestTypes); 4913 4914// Tests that the filled container is equal to itself. 4915TYPED_TEST(ContainerEqTest, EqualsSelf) { 4916 static const int vals[] = {1, 1, 2, 3, 5, 8}; 4917 TypeParam my_set(vals, vals + 6); 4918 const Matcher<TypeParam> m = ContainerEq(my_set); 4919 EXPECT_TRUE(m.Matches(my_set)); 4920 EXPECT_EQ("", Explain(m, my_set)); 4921} 4922 4923// Tests that missing values are reported. 4924TYPED_TEST(ContainerEqTest, ValueMissing) { 4925 static const int vals[] = {1, 1, 2, 3, 5, 8}; 4926 static const int test_vals[] = {2, 1, 8, 5}; 4927 TypeParam my_set(vals, vals + 6); 4928 TypeParam test_set(test_vals, test_vals + 4); 4929 const Matcher<TypeParam> m = ContainerEq(my_set); 4930 EXPECT_FALSE(m.Matches(test_set)); 4931 EXPECT_EQ("which doesn't have these expected elements: 3", 4932 Explain(m, test_set)); 4933} 4934 4935// Tests that added values are reported. 4936TYPED_TEST(ContainerEqTest, ValueAdded) { 4937 static const int vals[] = {1, 1, 2, 3, 5, 8}; 4938 static const int test_vals[] = {1, 2, 3, 5, 8, 46}; 4939 TypeParam my_set(vals, vals + 6); 4940 TypeParam test_set(test_vals, test_vals + 6); 4941 const Matcher<const TypeParam&> m = ContainerEq(my_set); 4942 EXPECT_FALSE(m.Matches(test_set)); 4943 EXPECT_EQ("which has these unexpected elements: 46", Explain(m, test_set)); 4944} 4945 4946// Tests that added and missing values are reported together. 4947TYPED_TEST(ContainerEqTest, ValueAddedAndRemoved) { 4948 static const int vals[] = {1, 1, 2, 3, 5, 8}; 4949 static const int test_vals[] = {1, 2, 3, 8, 46}; 4950 TypeParam my_set(vals, vals + 6); 4951 TypeParam test_set(test_vals, test_vals + 5); 4952 const Matcher<TypeParam> m = ContainerEq(my_set); 4953 EXPECT_FALSE(m.Matches(test_set)); 4954 EXPECT_EQ("which has these unexpected elements: 46,\n" 4955 "and doesn't have these expected elements: 5", 4956 Explain(m, test_set)); 4957} 4958 4959// Tests duplicated value -- expect no explanation. 4960TYPED_TEST(ContainerEqTest, DuplicateDifference) { 4961 static const int vals[] = {1, 1, 2, 3, 5, 8}; 4962 static const int test_vals[] = {1, 2, 3, 5, 8}; 4963 TypeParam my_set(vals, vals + 6); 4964 TypeParam test_set(test_vals, test_vals + 5); 4965 const Matcher<const TypeParam&> m = ContainerEq(my_set); 4966 // Depending on the container, match may be true or false 4967 // But in any case there should be no explanation. 4968 EXPECT_EQ("", Explain(m, test_set)); 4969} 4970#endif // GTEST_HAS_TYPED_TEST 4971 4972// Tests that mutliple missing values are reported. 4973// Using just vector here, so order is predictable. 4974TEST(ContainerEqExtraTest, MultipleValuesMissing) { 4975 static const int vals[] = {1, 1, 2, 3, 5, 8}; 4976 static const int test_vals[] = {2, 1, 5}; 4977 vector<int> my_set(vals, vals + 6); 4978 vector<int> test_set(test_vals, test_vals + 3); 4979 const Matcher<vector<int> > m = ContainerEq(my_set); 4980 EXPECT_FALSE(m.Matches(test_set)); 4981 EXPECT_EQ("which doesn't have these expected elements: 3, 8", 4982 Explain(m, test_set)); 4983} 4984 4985// Tests that added values are reported. 4986// Using just vector here, so order is predictable. 4987TEST(ContainerEqExtraTest, MultipleValuesAdded) { 4988 static const int vals[] = {1, 1, 2, 3, 5, 8}; 4989 static const int test_vals[] = {1, 2, 92, 3, 5, 8, 46}; 4990 list<size_t> my_set(vals, vals + 6); 4991 list<size_t> test_set(test_vals, test_vals + 7); 4992 const Matcher<const list<size_t>&> m = ContainerEq(my_set); 4993 EXPECT_FALSE(m.Matches(test_set)); 4994 EXPECT_EQ("which has these unexpected elements: 92, 46", 4995 Explain(m, test_set)); 4996} 4997 4998// Tests that added and missing values are reported together. 4999TEST(ContainerEqExtraTest, MultipleValuesAddedAndRemoved) { 5000 static const int vals[] = {1, 1, 2, 3, 5, 8}; 5001 static const int test_vals[] = {1, 2, 3, 92, 46}; 5002 list<size_t> my_set(vals, vals + 6); 5003 list<size_t> test_set(test_vals, test_vals + 5); 5004 const Matcher<const list<size_t> > m = ContainerEq(my_set); 5005 EXPECT_FALSE(m.Matches(test_set)); 5006 EXPECT_EQ("which has these unexpected elements: 92, 46,\n" 5007 "and doesn't have these expected elements: 5, 8", 5008 Explain(m, test_set)); 5009} 5010 5011// Tests to see that duplicate elements are detected, 5012// but (as above) not reported in the explanation. 5013TEST(ContainerEqExtraTest, MultiSetOfIntDuplicateDifference) { 5014 static const int vals[] = {1, 1, 2, 3, 5, 8}; 5015 static const int test_vals[] = {1, 2, 3, 5, 8}; 5016 vector<int> my_set(vals, vals + 6); 5017 vector<int> test_set(test_vals, test_vals + 5); 5018 const Matcher<vector<int> > m = ContainerEq(my_set); 5019 EXPECT_TRUE(m.Matches(my_set)); 5020 EXPECT_FALSE(m.Matches(test_set)); 5021 // There is nothing to report when both sets contain all the same values. 5022 EXPECT_EQ("", Explain(m, test_set)); 5023} 5024 5025// Tests that ContainerEq works for non-trivial associative containers, 5026// like maps. 5027TEST(ContainerEqExtraTest, WorksForMaps) { 5028 map<int, std::string> my_map; 5029 my_map[0] = "a"; 5030 my_map[1] = "b"; 5031 5032 map<int, std::string> test_map; 5033 test_map[0] = "aa"; 5034 test_map[1] = "b"; 5035 5036 const Matcher<const map<int, std::string>&> m = ContainerEq(my_map); 5037 EXPECT_TRUE(m.Matches(my_map)); 5038 EXPECT_FALSE(m.Matches(test_map)); 5039 5040 EXPECT_EQ("which has these unexpected elements: (0, \"aa\"),\n" 5041 "and doesn't have these expected elements: (0, \"a\")", 5042 Explain(m, test_map)); 5043} 5044 5045TEST(ContainerEqExtraTest, WorksForNativeArray) { 5046 int a1[] = {1, 2, 3}; 5047 int a2[] = {1, 2, 3}; 5048 int b[] = {1, 2, 4}; 5049 5050 EXPECT_THAT(a1, ContainerEq(a2)); 5051 EXPECT_THAT(a1, Not(ContainerEq(b))); 5052} 5053 5054TEST(ContainerEqExtraTest, WorksForTwoDimensionalNativeArray) { 5055 const char a1[][3] = {"hi", "lo"}; 5056 const char a2[][3] = {"hi", "lo"}; 5057 const char b[][3] = {"lo", "hi"}; 5058 5059 // Tests using ContainerEq() in the first dimension. 5060 EXPECT_THAT(a1, ContainerEq(a2)); 5061 EXPECT_THAT(a1, Not(ContainerEq(b))); 5062 5063 // Tests using ContainerEq() in the second dimension. 5064 EXPECT_THAT(a1, ElementsAre(ContainerEq(a2[0]), ContainerEq(a2[1]))); 5065 EXPECT_THAT(a1, ElementsAre(Not(ContainerEq(b[0])), ContainerEq(a2[1]))); 5066} 5067 5068TEST(ContainerEqExtraTest, WorksForNativeArrayAsTuple) { 5069 const int a1[] = {1, 2, 3}; 5070 const int a2[] = {1, 2, 3}; 5071 const int b[] = {1, 2, 3, 4}; 5072 5073 const int* const p1 = a1; 5074 EXPECT_THAT(make_tuple(p1, 3), ContainerEq(a2)); 5075 EXPECT_THAT(make_tuple(p1, 3), Not(ContainerEq(b))); 5076 5077 const int c[] = {1, 3, 2}; 5078 EXPECT_THAT(make_tuple(p1, 3), Not(ContainerEq(c))); 5079} 5080 5081TEST(ContainerEqExtraTest, CopiesNativeArrayParameter) { 5082 std::string a1[][3] = { 5083 {"hi", "hello", "ciao"}, 5084 {"bye", "see you", "ciao"} 5085 }; 5086 5087 std::string a2[][3] = { 5088 {"hi", "hello", "ciao"}, 5089 {"bye", "see you", "ciao"} 5090 }; 5091 5092 const Matcher<const std::string(&)[2][3]> m = ContainerEq(a2); 5093 EXPECT_THAT(a1, m); 5094 5095 a2[0][0] = "ha"; 5096 EXPECT_THAT(a1, m); 5097} 5098 5099TEST(WhenSortedByTest, WorksForEmptyContainer) { 5100 const vector<int> numbers; 5101 EXPECT_THAT(numbers, WhenSortedBy(less<int>(), ElementsAre())); 5102 EXPECT_THAT(numbers, Not(WhenSortedBy(less<int>(), ElementsAre(1)))); 5103} 5104 5105TEST(WhenSortedByTest, WorksForNonEmptyContainer) { 5106 vector<unsigned> numbers; 5107 numbers.push_back(3); 5108 numbers.push_back(1); 5109 numbers.push_back(2); 5110 numbers.push_back(2); 5111 EXPECT_THAT(numbers, WhenSortedBy(greater<unsigned>(), 5112 ElementsAre(3, 2, 2, 1))); 5113 EXPECT_THAT(numbers, Not(WhenSortedBy(greater<unsigned>(), 5114 ElementsAre(1, 2, 2, 3)))); 5115} 5116 5117TEST(WhenSortedByTest, WorksForNonVectorContainer) { 5118 list<std::string> words; 5119 words.push_back("say"); 5120 words.push_back("hello"); 5121 words.push_back("world"); 5122 EXPECT_THAT(words, WhenSortedBy(less<std::string>(), 5123 ElementsAre("hello", "say", "world"))); 5124 EXPECT_THAT(words, Not(WhenSortedBy(less<std::string>(), 5125 ElementsAre("say", "hello", "world")))); 5126} 5127 5128TEST(WhenSortedByTest, WorksForNativeArray) { 5129 const int numbers[] = {1, 3, 2, 4}; 5130 const int sorted_numbers[] = {1, 2, 3, 4}; 5131 EXPECT_THAT(numbers, WhenSortedBy(less<int>(), ElementsAre(1, 2, 3, 4))); 5132 EXPECT_THAT(numbers, WhenSortedBy(less<int>(), 5133 ElementsAreArray(sorted_numbers))); 5134 EXPECT_THAT(numbers, Not(WhenSortedBy(less<int>(), ElementsAre(1, 3, 2, 4)))); 5135} 5136 5137TEST(WhenSortedByTest, CanDescribeSelf) { 5138 const Matcher<vector<int> > m = WhenSortedBy(less<int>(), ElementsAre(1, 2)); 5139 EXPECT_EQ("(when sorted) has 2 elements where\n" 5140 "element #0 is equal to 1,\n" 5141 "element #1 is equal to 2", 5142 Describe(m)); 5143 EXPECT_EQ("(when sorted) doesn't have 2 elements, or\n" 5144 "element #0 isn't equal to 1, or\n" 5145 "element #1 isn't equal to 2", 5146 DescribeNegation(m)); 5147} 5148 5149TEST(WhenSortedByTest, ExplainsMatchResult) { 5150 const int a[] = {2, 1}; 5151 EXPECT_EQ("which is { 1, 2 } when sorted, whose element #0 doesn't match", 5152 Explain(WhenSortedBy(less<int>(), ElementsAre(2, 3)), a)); 5153 EXPECT_EQ("which is { 1, 2 } when sorted", 5154 Explain(WhenSortedBy(less<int>(), ElementsAre(1, 2)), a)); 5155} 5156 5157// WhenSorted() is a simple wrapper on WhenSortedBy(). Hence we don't 5158// need to test it as exhaustively as we test the latter. 5159 5160TEST(WhenSortedTest, WorksForEmptyContainer) { 5161 const vector<int> numbers; 5162 EXPECT_THAT(numbers, WhenSorted(ElementsAre())); 5163 EXPECT_THAT(numbers, Not(WhenSorted(ElementsAre(1)))); 5164} 5165 5166TEST(WhenSortedTest, WorksForNonEmptyContainer) { 5167 list<std::string> words; 5168 words.push_back("3"); 5169 words.push_back("1"); 5170 words.push_back("2"); 5171 words.push_back("2"); 5172 EXPECT_THAT(words, WhenSorted(ElementsAre("1", "2", "2", "3"))); 5173 EXPECT_THAT(words, Not(WhenSorted(ElementsAre("3", "1", "2", "2")))); 5174} 5175 5176TEST(WhenSortedTest, WorksForMapTypes) { 5177 map<std::string, int> word_counts; 5178 word_counts["and"] = 1; 5179 word_counts["the"] = 1; 5180 word_counts["buffalo"] = 2; 5181 EXPECT_THAT(word_counts, 5182 WhenSorted(ElementsAre(Pair("and", 1), Pair("buffalo", 2), 5183 Pair("the", 1)))); 5184 EXPECT_THAT(word_counts, 5185 Not(WhenSorted(ElementsAre(Pair("and", 1), Pair("the", 1), 5186 Pair("buffalo", 2))))); 5187} 5188 5189TEST(WhenSortedTest, WorksForMultiMapTypes) { 5190 multimap<int, int> ifib; 5191 ifib.insert(make_pair(8, 6)); 5192 ifib.insert(make_pair(2, 3)); 5193 ifib.insert(make_pair(1, 1)); 5194 ifib.insert(make_pair(3, 4)); 5195 ifib.insert(make_pair(1, 2)); 5196 ifib.insert(make_pair(5, 5)); 5197 EXPECT_THAT(ifib, WhenSorted(ElementsAre(Pair(1, 1), 5198 Pair(1, 2), 5199 Pair(2, 3), 5200 Pair(3, 4), 5201 Pair(5, 5), 5202 Pair(8, 6)))); 5203 EXPECT_THAT(ifib, Not(WhenSorted(ElementsAre(Pair(8, 6), 5204 Pair(2, 3), 5205 Pair(1, 1), 5206 Pair(3, 4), 5207 Pair(1, 2), 5208 Pair(5, 5))))); 5209} 5210 5211TEST(WhenSortedTest, WorksForPolymorphicMatcher) { 5212 std::deque<int> d; 5213 d.push_back(2); 5214 d.push_back(1); 5215 EXPECT_THAT(d, WhenSorted(ElementsAre(1, 2))); 5216 EXPECT_THAT(d, Not(WhenSorted(ElementsAre(2, 1)))); 5217} 5218 5219TEST(WhenSortedTest, WorksForVectorConstRefMatcher) { 5220 std::deque<int> d; 5221 d.push_back(2); 5222 d.push_back(1); 5223 Matcher<const std::vector<int>&> vector_match = ElementsAre(1, 2); 5224 EXPECT_THAT(d, WhenSorted(vector_match)); 5225 Matcher<const std::vector<int>&> not_vector_match = ElementsAre(2, 1); 5226 EXPECT_THAT(d, Not(WhenSorted(not_vector_match))); 5227} 5228 5229// Deliberately bare pseudo-container. 5230// Offers only begin() and end() accessors, yielding InputIterator. 5231template <typename T> 5232class Streamlike { 5233 private: 5234 class ConstIter; 5235 public: 5236 typedef ConstIter const_iterator; 5237 typedef T value_type; 5238 5239 template <typename InIter> 5240 Streamlike(InIter first, InIter last) : remainder_(first, last) {} 5241 5242 const_iterator begin() const { 5243 return const_iterator(this, remainder_.begin()); 5244 } 5245 const_iterator end() const { 5246 return const_iterator(this, remainder_.end()); 5247 } 5248 5249 private: 5250 class ConstIter : public std::iterator<std::input_iterator_tag, 5251 value_type, 5252 ptrdiff_t, 5253 const value_type*, 5254 const value_type&> { 5255 public: 5256 ConstIter(const Streamlike* s, 5257 typename std::list<value_type>::iterator pos) 5258 : s_(s), pos_(pos) {} 5259 5260 const value_type& operator*() const { return *pos_; } 5261 const value_type* operator->() const { return &*pos_; } 5262 ConstIter& operator++() { 5263 s_->remainder_.erase(pos_++); 5264 return *this; 5265 } 5266 5267 // *iter++ is required to work (see std::istreambuf_iterator). 5268 // (void)iter++ is also required to work. 5269 class PostIncrProxy { 5270 public: 5271 explicit PostIncrProxy(const value_type& value) : value_(value) {} 5272 value_type operator*() const { return value_; } 5273 private: 5274 value_type value_; 5275 }; 5276 PostIncrProxy operator++(int) { 5277 PostIncrProxy proxy(**this); 5278 ++(*this); 5279 return proxy; 5280 } 5281 5282 friend bool operator==(const ConstIter& a, const ConstIter& b) { 5283 return a.s_ == b.s_ && a.pos_ == b.pos_; 5284 } 5285 friend bool operator!=(const ConstIter& a, const ConstIter& b) { 5286 return !(a == b); 5287 } 5288 5289 private: 5290 const Streamlike* s_; 5291 typename std::list<value_type>::iterator pos_; 5292 }; 5293 5294 friend std::ostream& operator<<(std::ostream& os, const Streamlike& s) { 5295 os << "["; 5296 typedef typename std::list<value_type>::const_iterator Iter; 5297 const char* sep = ""; 5298 for (Iter it = s.remainder_.begin(); it != s.remainder_.end(); ++it) { 5299 os << sep << *it; 5300 sep = ","; 5301 } 5302 os << "]"; 5303 return os; 5304 } 5305 5306 mutable std::list<value_type> remainder_; // modified by iteration 5307}; 5308 5309TEST(StreamlikeTest, Iteration) { 5310 const int a[5] = {2, 1, 4, 5, 3}; 5311 Streamlike<int> s(a, a + 5); 5312 Streamlike<int>::const_iterator it = s.begin(); 5313 const int* ip = a; 5314 while (it != s.end()) { 5315 SCOPED_TRACE(ip - a); 5316 EXPECT_EQ(*ip++, *it++); 5317 } 5318} 5319 5320#if GTEST_HAS_STD_FORWARD_LIST_ 5321TEST(BeginEndDistanceIsTest, WorksWithForwardList) { 5322 std::forward_list<int> container; 5323 EXPECT_THAT(container, BeginEndDistanceIs(0)); 5324 EXPECT_THAT(container, Not(BeginEndDistanceIs(1))); 5325 container.push_front(0); 5326 EXPECT_THAT(container, Not(BeginEndDistanceIs(0))); 5327 EXPECT_THAT(container, BeginEndDistanceIs(1)); 5328 container.push_front(0); 5329 EXPECT_THAT(container, Not(BeginEndDistanceIs(0))); 5330 EXPECT_THAT(container, BeginEndDistanceIs(2)); 5331} 5332#endif // GTEST_HAS_STD_FORWARD_LIST_ 5333 5334TEST(BeginEndDistanceIsTest, WorksWithNonStdList) { 5335 const int a[5] = {1, 2, 3, 4, 5}; 5336 Streamlike<int> s(a, a + 5); 5337 EXPECT_THAT(s, BeginEndDistanceIs(5)); 5338} 5339 5340TEST(BeginEndDistanceIsTest, CanDescribeSelf) { 5341 Matcher<vector<int> > m = BeginEndDistanceIs(2); 5342 EXPECT_EQ("distance between begin() and end() is equal to 2", Describe(m)); 5343 EXPECT_EQ("distance between begin() and end() isn't equal to 2", 5344 DescribeNegation(m)); 5345} 5346 5347TEST(BeginEndDistanceIsTest, ExplainsResult) { 5348 Matcher<vector<int> > m1 = BeginEndDistanceIs(2); 5349 Matcher<vector<int> > m2 = BeginEndDistanceIs(Lt(2)); 5350 Matcher<vector<int> > m3 = BeginEndDistanceIs(AnyOf(0, 3)); 5351 Matcher<vector<int> > m4 = BeginEndDistanceIs(GreaterThan(1)); 5352 vector<int> container; 5353 EXPECT_EQ("whose distance between begin() and end() 0 doesn't match", 5354 Explain(m1, container)); 5355 EXPECT_EQ("whose distance between begin() and end() 0 matches", 5356 Explain(m2, container)); 5357 EXPECT_EQ("whose distance between begin() and end() 0 matches", 5358 Explain(m3, container)); 5359 EXPECT_EQ( 5360 "whose distance between begin() and end() 0 doesn't match, which is 1 " 5361 "less than 1", 5362 Explain(m4, container)); 5363 container.push_back(0); 5364 container.push_back(0); 5365 EXPECT_EQ("whose distance between begin() and end() 2 matches", 5366 Explain(m1, container)); 5367 EXPECT_EQ("whose distance between begin() and end() 2 doesn't match", 5368 Explain(m2, container)); 5369 EXPECT_EQ("whose distance between begin() and end() 2 doesn't match", 5370 Explain(m3, container)); 5371 EXPECT_EQ( 5372 "whose distance between begin() and end() 2 matches, which is 1 more " 5373 "than 1", 5374 Explain(m4, container)); 5375} 5376 5377TEST(WhenSortedTest, WorksForStreamlike) { 5378 // Streamlike 'container' provides only minimal iterator support. 5379 // Its iterators are tagged with input_iterator_tag. 5380 const int a[5] = {2, 1, 4, 5, 3}; 5381 Streamlike<int> s(a, a + GTEST_ARRAY_SIZE_(a)); 5382 EXPECT_THAT(s, WhenSorted(ElementsAre(1, 2, 3, 4, 5))); 5383 EXPECT_THAT(s, Not(WhenSorted(ElementsAre(2, 1, 4, 5, 3)))); 5384} 5385 5386TEST(WhenSortedTest, WorksForVectorConstRefMatcherOnStreamlike) { 5387 const int a[] = {2, 1, 4, 5, 3}; 5388 Streamlike<int> s(a, a + GTEST_ARRAY_SIZE_(a)); 5389 Matcher<const std::vector<int>&> vector_match = ElementsAre(1, 2, 3, 4, 5); 5390 EXPECT_THAT(s, WhenSorted(vector_match)); 5391 EXPECT_THAT(s, Not(WhenSorted(ElementsAre(2, 1, 4, 5, 3)))); 5392} 5393 5394TEST(IsSupersetOfTest, WorksForNativeArray) { 5395 const int subset[] = {1, 4}; 5396 const int superset[] = {1, 2, 4}; 5397 const int disjoint[] = {1, 0, 3}; 5398 EXPECT_THAT(subset, IsSupersetOf(subset)); 5399 EXPECT_THAT(subset, Not(IsSupersetOf(superset))); 5400 EXPECT_THAT(superset, IsSupersetOf(subset)); 5401 EXPECT_THAT(subset, Not(IsSupersetOf(disjoint))); 5402 EXPECT_THAT(disjoint, Not(IsSupersetOf(subset))); 5403} 5404 5405TEST(IsSupersetOfTest, WorksWithDuplicates) { 5406 const int not_enough[] = {1, 2}; 5407 const int enough[] = {1, 1, 2}; 5408 const int expected[] = {1, 1}; 5409 EXPECT_THAT(not_enough, Not(IsSupersetOf(expected))); 5410 EXPECT_THAT(enough, IsSupersetOf(expected)); 5411} 5412 5413TEST(IsSupersetOfTest, WorksForEmpty) { 5414 vector<int> numbers; 5415 vector<int> expected; 5416 EXPECT_THAT(numbers, IsSupersetOf(expected)); 5417 expected.push_back(1); 5418 EXPECT_THAT(numbers, Not(IsSupersetOf(expected))); 5419 expected.clear(); 5420 numbers.push_back(1); 5421 numbers.push_back(2); 5422 EXPECT_THAT(numbers, IsSupersetOf(expected)); 5423 expected.push_back(1); 5424 EXPECT_THAT(numbers, IsSupersetOf(expected)); 5425 expected.push_back(2); 5426 EXPECT_THAT(numbers, IsSupersetOf(expected)); 5427 expected.push_back(3); 5428 EXPECT_THAT(numbers, Not(IsSupersetOf(expected))); 5429} 5430 5431TEST(IsSupersetOfTest, WorksForStreamlike) { 5432 const int a[5] = {1, 2, 3, 4, 5}; 5433 Streamlike<int> s(a, a + GTEST_ARRAY_SIZE_(a)); 5434 5435 vector<int> expected; 5436 expected.push_back(1); 5437 expected.push_back(2); 5438 expected.push_back(5); 5439 EXPECT_THAT(s, IsSupersetOf(expected)); 5440 5441 expected.push_back(0); 5442 EXPECT_THAT(s, Not(IsSupersetOf(expected))); 5443} 5444 5445TEST(IsSupersetOfTest, TakesStlContainer) { 5446 const int actual[] = {3, 1, 2}; 5447 5448 ::std::list<int> expected; 5449 expected.push_back(1); 5450 expected.push_back(3); 5451 EXPECT_THAT(actual, IsSupersetOf(expected)); 5452 5453 expected.push_back(4); 5454 EXPECT_THAT(actual, Not(IsSupersetOf(expected))); 5455} 5456 5457TEST(IsSupersetOfTest, Describe) { 5458 typedef std::vector<int> IntVec; 5459 IntVec expected; 5460 expected.push_back(111); 5461 expected.push_back(222); 5462 expected.push_back(333); 5463 EXPECT_THAT( 5464 Describe<IntVec>(IsSupersetOf(expected)), 5465 Eq("a surjection from elements to requirements exists such that:\n" 5466 " - an element is equal to 111\n" 5467 " - an element is equal to 222\n" 5468 " - an element is equal to 333")); 5469} 5470 5471TEST(IsSupersetOfTest, DescribeNegation) { 5472 typedef std::vector<int> IntVec; 5473 IntVec expected; 5474 expected.push_back(111); 5475 expected.push_back(222); 5476 expected.push_back(333); 5477 EXPECT_THAT( 5478 DescribeNegation<IntVec>(IsSupersetOf(expected)), 5479 Eq("no surjection from elements to requirements exists such that:\n" 5480 " - an element is equal to 111\n" 5481 " - an element is equal to 222\n" 5482 " - an element is equal to 333")); 5483} 5484 5485TEST(IsSupersetOfTest, MatchAndExplain) { 5486 std::vector<int> v; 5487 v.push_back(2); 5488 v.push_back(3); 5489 std::vector<int> expected; 5490 expected.push_back(1); 5491 expected.push_back(2); 5492 StringMatchResultListener listener; 5493 ASSERT_FALSE(ExplainMatchResult(IsSupersetOf(expected), v, &listener)) 5494 << listener.str(); 5495 EXPECT_THAT(listener.str(), 5496 Eq("where the following matchers don't match any elements:\n" 5497 "matcher #0: is equal to 1")); 5498 5499 v.push_back(1); 5500 listener.Clear(); 5501 ASSERT_TRUE(ExplainMatchResult(IsSupersetOf(expected), v, &listener)) 5502 << listener.str(); 5503 EXPECT_THAT(listener.str(), Eq("where:\n" 5504 " - element #0 is matched by matcher #1,\n" 5505 " - element #2 is matched by matcher #0")); 5506} 5507 5508#if GTEST_HAS_STD_INITIALIZER_LIST_ 5509TEST(IsSupersetOfTest, WorksForRhsInitializerList) { 5510 const int numbers[] = {1, 3, 6, 2, 4, 5}; 5511 EXPECT_THAT(numbers, IsSupersetOf({1, 2})); 5512 EXPECT_THAT(numbers, Not(IsSupersetOf({3, 0}))); 5513} 5514#endif 5515 5516TEST(IsSubsetOfTest, WorksForNativeArray) { 5517 const int subset[] = {1, 4}; 5518 const int superset[] = {1, 2, 4}; 5519 const int disjoint[] = {1, 0, 3}; 5520 EXPECT_THAT(subset, IsSubsetOf(subset)); 5521 EXPECT_THAT(subset, IsSubsetOf(superset)); 5522 EXPECT_THAT(superset, Not(IsSubsetOf(subset))); 5523 EXPECT_THAT(subset, Not(IsSubsetOf(disjoint))); 5524 EXPECT_THAT(disjoint, Not(IsSubsetOf(subset))); 5525} 5526 5527TEST(IsSubsetOfTest, WorksWithDuplicates) { 5528 const int not_enough[] = {1, 2}; 5529 const int enough[] = {1, 1, 2}; 5530 const int actual[] = {1, 1}; 5531 EXPECT_THAT(actual, Not(IsSubsetOf(not_enough))); 5532 EXPECT_THAT(actual, IsSubsetOf(enough)); 5533} 5534 5535TEST(IsSubsetOfTest, WorksForEmpty) { 5536 vector<int> numbers; 5537 vector<int> expected; 5538 EXPECT_THAT(numbers, IsSubsetOf(expected)); 5539 expected.push_back(1); 5540 EXPECT_THAT(numbers, IsSubsetOf(expected)); 5541 expected.clear(); 5542 numbers.push_back(1); 5543 numbers.push_back(2); 5544 EXPECT_THAT(numbers, Not(IsSubsetOf(expected))); 5545 expected.push_back(1); 5546 EXPECT_THAT(numbers, Not(IsSubsetOf(expected))); 5547 expected.push_back(2); 5548 EXPECT_THAT(numbers, IsSubsetOf(expected)); 5549 expected.push_back(3); 5550 EXPECT_THAT(numbers, IsSubsetOf(expected)); 5551} 5552 5553TEST(IsSubsetOfTest, WorksForStreamlike) { 5554 const int a[5] = {1, 2}; 5555 Streamlike<int> s(a, a + GTEST_ARRAY_SIZE_(a)); 5556 5557 vector<int> expected; 5558 expected.push_back(1); 5559 EXPECT_THAT(s, Not(IsSubsetOf(expected))); 5560 expected.push_back(2); 5561 expected.push_back(5); 5562 EXPECT_THAT(s, IsSubsetOf(expected)); 5563} 5564 5565TEST(IsSubsetOfTest, TakesStlContainer) { 5566 const int actual[] = {3, 1, 2}; 5567 5568 ::std::list<int> expected; 5569 expected.push_back(1); 5570 expected.push_back(3); 5571 EXPECT_THAT(actual, Not(IsSubsetOf(expected))); 5572 5573 expected.push_back(2); 5574 expected.push_back(4); 5575 EXPECT_THAT(actual, IsSubsetOf(expected)); 5576} 5577 5578TEST(IsSubsetOfTest, Describe) { 5579 typedef std::vector<int> IntVec; 5580 IntVec expected; 5581 expected.push_back(111); 5582 expected.push_back(222); 5583 expected.push_back(333); 5584 5585 EXPECT_THAT( 5586 Describe<IntVec>(IsSubsetOf(expected)), 5587 Eq("an injection from elements to requirements exists such that:\n" 5588 " - an element is equal to 111\n" 5589 " - an element is equal to 222\n" 5590 " - an element is equal to 333")); 5591} 5592 5593TEST(IsSubsetOfTest, DescribeNegation) { 5594 typedef std::vector<int> IntVec; 5595 IntVec expected; 5596 expected.push_back(111); 5597 expected.push_back(222); 5598 expected.push_back(333); 5599 EXPECT_THAT( 5600 DescribeNegation<IntVec>(IsSubsetOf(expected)), 5601 Eq("no injection from elements to requirements exists such that:\n" 5602 " - an element is equal to 111\n" 5603 " - an element is equal to 222\n" 5604 " - an element is equal to 333")); 5605} 5606 5607TEST(IsSubsetOfTest, MatchAndExplain) { 5608 std::vector<int> v; 5609 v.push_back(2); 5610 v.push_back(3); 5611 std::vector<int> expected; 5612 expected.push_back(1); 5613 expected.push_back(2); 5614 StringMatchResultListener listener; 5615 ASSERT_FALSE(ExplainMatchResult(IsSubsetOf(expected), v, &listener)) 5616 << listener.str(); 5617 EXPECT_THAT(listener.str(), 5618 Eq("where the following elements don't match any matchers:\n" 5619 "element #1: 3")); 5620 5621 expected.push_back(3); 5622 listener.Clear(); 5623 ASSERT_TRUE(ExplainMatchResult(IsSubsetOf(expected), v, &listener)) 5624 << listener.str(); 5625 EXPECT_THAT(listener.str(), Eq("where:\n" 5626 " - element #0 is matched by matcher #1,\n" 5627 " - element #1 is matched by matcher #2")); 5628} 5629 5630#if GTEST_HAS_STD_INITIALIZER_LIST_ 5631TEST(IsSubsetOfTest, WorksForRhsInitializerList) { 5632 const int numbers[] = {1, 2, 3}; 5633 EXPECT_THAT(numbers, IsSubsetOf({1, 2, 3, 4})); 5634 EXPECT_THAT(numbers, Not(IsSubsetOf({1, 2}))); 5635} 5636#endif 5637 5638// Tests using ElementsAre() and ElementsAreArray() with stream-like 5639// "containers". 5640 5641TEST(ElemensAreStreamTest, WorksForStreamlike) { 5642 const int a[5] = {1, 2, 3, 4, 5}; 5643 Streamlike<int> s(a, a + GTEST_ARRAY_SIZE_(a)); 5644 EXPECT_THAT(s, ElementsAre(1, 2, 3, 4, 5)); 5645 EXPECT_THAT(s, Not(ElementsAre(2, 1, 4, 5, 3))); 5646} 5647 5648TEST(ElemensAreArrayStreamTest, WorksForStreamlike) { 5649 const int a[5] = {1, 2, 3, 4, 5}; 5650 Streamlike<int> s(a, a + GTEST_ARRAY_SIZE_(a)); 5651 5652 vector<int> expected; 5653 expected.push_back(1); 5654 expected.push_back(2); 5655 expected.push_back(3); 5656 expected.push_back(4); 5657 expected.push_back(5); 5658 EXPECT_THAT(s, ElementsAreArray(expected)); 5659 5660 expected[3] = 0; 5661 EXPECT_THAT(s, Not(ElementsAreArray(expected))); 5662} 5663 5664TEST(ElementsAreTest, WorksWithUncopyable) { 5665 Uncopyable objs[2]; 5666 objs[0].set_value(-3); 5667 objs[1].set_value(1); 5668 EXPECT_THAT(objs, ElementsAre(UncopyableIs(-3), Truly(ValueIsPositive))); 5669} 5670 5671TEST(ElementsAreTest, TakesStlContainer) { 5672 const int actual[] = {3, 1, 2}; 5673 5674 ::std::list<int> expected; 5675 expected.push_back(3); 5676 expected.push_back(1); 5677 expected.push_back(2); 5678 EXPECT_THAT(actual, ElementsAreArray(expected)); 5679 5680 expected.push_back(4); 5681 EXPECT_THAT(actual, Not(ElementsAreArray(expected))); 5682} 5683 5684// Tests for UnorderedElementsAreArray() 5685 5686TEST(UnorderedElementsAreArrayTest, SucceedsWhenExpected) { 5687 const int a[] = {0, 1, 2, 3, 4}; 5688 std::vector<int> s(a, a + GTEST_ARRAY_SIZE_(a)); 5689 do { 5690 StringMatchResultListener listener; 5691 EXPECT_TRUE(ExplainMatchResult(UnorderedElementsAreArray(a), 5692 s, &listener)) << listener.str(); 5693 } while (std::next_permutation(s.begin(), s.end())); 5694} 5695 5696TEST(UnorderedElementsAreArrayTest, VectorBool) { 5697 const bool a[] = {0, 1, 0, 1, 1}; 5698 const bool b[] = {1, 0, 1, 1, 0}; 5699 std::vector<bool> expected(a, a + GTEST_ARRAY_SIZE_(a)); 5700 std::vector<bool> actual(b, b + GTEST_ARRAY_SIZE_(b)); 5701 StringMatchResultListener listener; 5702 EXPECT_TRUE(ExplainMatchResult(UnorderedElementsAreArray(expected), 5703 actual, &listener)) << listener.str(); 5704} 5705 5706TEST(UnorderedElementsAreArrayTest, WorksForStreamlike) { 5707 // Streamlike 'container' provides only minimal iterator support. 5708 // Its iterators are tagged with input_iterator_tag, and it has no 5709 // size() or empty() methods. 5710 const int a[5] = {2, 1, 4, 5, 3}; 5711 Streamlike<int> s(a, a + GTEST_ARRAY_SIZE_(a)); 5712 5713 ::std::vector<int> expected; 5714 expected.push_back(1); 5715 expected.push_back(2); 5716 expected.push_back(3); 5717 expected.push_back(4); 5718 expected.push_back(5); 5719 EXPECT_THAT(s, UnorderedElementsAreArray(expected)); 5720 5721 expected.push_back(6); 5722 EXPECT_THAT(s, Not(UnorderedElementsAreArray(expected))); 5723} 5724 5725TEST(UnorderedElementsAreArrayTest, TakesStlContainer) { 5726 const int actual[] = {3, 1, 2}; 5727 5728 ::std::list<int> expected; 5729 expected.push_back(1); 5730 expected.push_back(2); 5731 expected.push_back(3); 5732 EXPECT_THAT(actual, UnorderedElementsAreArray(expected)); 5733 5734 expected.push_back(4); 5735 EXPECT_THAT(actual, Not(UnorderedElementsAreArray(expected))); 5736} 5737 5738#if GTEST_HAS_STD_INITIALIZER_LIST_ 5739 5740TEST(UnorderedElementsAreArrayTest, TakesInitializerList) { 5741 const int a[5] = {2, 1, 4, 5, 3}; 5742 EXPECT_THAT(a, UnorderedElementsAreArray({1, 2, 3, 4, 5})); 5743 EXPECT_THAT(a, Not(UnorderedElementsAreArray({1, 2, 3, 4, 6}))); 5744} 5745 5746TEST(UnorderedElementsAreArrayTest, TakesInitializerListOfCStrings) { 5747 const std::string a[5] = {"a", "b", "c", "d", "e"}; 5748 EXPECT_THAT(a, UnorderedElementsAreArray({"a", "b", "c", "d", "e"})); 5749 EXPECT_THAT(a, Not(UnorderedElementsAreArray({"a", "b", "c", "d", "ef"}))); 5750} 5751 5752TEST(UnorderedElementsAreArrayTest, TakesInitializerListOfSameTypedMatchers) { 5753 const int a[5] = {2, 1, 4, 5, 3}; 5754 EXPECT_THAT(a, UnorderedElementsAreArray( 5755 {Eq(1), Eq(2), Eq(3), Eq(4), Eq(5)})); 5756 EXPECT_THAT(a, Not(UnorderedElementsAreArray( 5757 {Eq(1), Eq(2), Eq(3), Eq(4), Eq(6)}))); 5758} 5759 5760TEST(UnorderedElementsAreArrayTest, 5761 TakesInitializerListOfDifferentTypedMatchers) { 5762 const int a[5] = {2, 1, 4, 5, 3}; 5763 // The compiler cannot infer the type of the initializer list if its 5764 // elements have different types. We must explicitly specify the 5765 // unified element type in this case. 5766 EXPECT_THAT(a, UnorderedElementsAreArray<Matcher<int> >( 5767 {Eq(1), Ne(-2), Ge(3), Le(4), Eq(5)})); 5768 EXPECT_THAT(a, Not(UnorderedElementsAreArray<Matcher<int> >( 5769 {Eq(1), Ne(-2), Ge(3), Le(4), Eq(6)}))); 5770} 5771 5772#endif // GTEST_HAS_STD_INITIALIZER_LIST_ 5773 5774class UnorderedElementsAreTest : public testing::Test { 5775 protected: 5776 typedef std::vector<int> IntVec; 5777}; 5778 5779TEST_F(UnorderedElementsAreTest, WorksWithUncopyable) { 5780 Uncopyable objs[2]; 5781 objs[0].set_value(-3); 5782 objs[1].set_value(1); 5783 EXPECT_THAT(objs, 5784 UnorderedElementsAre(Truly(ValueIsPositive), UncopyableIs(-3))); 5785} 5786 5787TEST_F(UnorderedElementsAreTest, SucceedsWhenExpected) { 5788 const int a[] = {1, 2, 3}; 5789 std::vector<int> s(a, a + GTEST_ARRAY_SIZE_(a)); 5790 do { 5791 StringMatchResultListener listener; 5792 EXPECT_TRUE(ExplainMatchResult(UnorderedElementsAre(1, 2, 3), 5793 s, &listener)) << listener.str(); 5794 } while (std::next_permutation(s.begin(), s.end())); 5795} 5796 5797TEST_F(UnorderedElementsAreTest, FailsWhenAnElementMatchesNoMatcher) { 5798 const int a[] = {1, 2, 3}; 5799 std::vector<int> s(a, a + GTEST_ARRAY_SIZE_(a)); 5800 std::vector<Matcher<int> > mv; 5801 mv.push_back(1); 5802 mv.push_back(2); 5803 mv.push_back(2); 5804 // The element with value '3' matches nothing: fail fast. 5805 StringMatchResultListener listener; 5806 EXPECT_FALSE(ExplainMatchResult(UnorderedElementsAreArray(mv), 5807 s, &listener)) << listener.str(); 5808} 5809 5810TEST_F(UnorderedElementsAreTest, WorksForStreamlike) { 5811 // Streamlike 'container' provides only minimal iterator support. 5812 // Its iterators are tagged with input_iterator_tag, and it has no 5813 // size() or empty() methods. 5814 const int a[5] = {2, 1, 4, 5, 3}; 5815 Streamlike<int> s(a, a + GTEST_ARRAY_SIZE_(a)); 5816 5817 EXPECT_THAT(s, UnorderedElementsAre(1, 2, 3, 4, 5)); 5818 EXPECT_THAT(s, Not(UnorderedElementsAre(2, 2, 3, 4, 5))); 5819} 5820 5821// One naive implementation of the matcher runs in O(N!) time, which is too 5822// slow for many real-world inputs. This test shows that our matcher can match 5823// 100 inputs very quickly (a few milliseconds). An O(100!) is 10^158 5824// iterations and obviously effectively incomputable. 5825// [ RUN ] UnorderedElementsAreTest.Performance 5826// [ OK ] UnorderedElementsAreTest.Performance (4 ms) 5827TEST_F(UnorderedElementsAreTest, Performance) { 5828 std::vector<int> s; 5829 std::vector<Matcher<int> > mv; 5830 for (int i = 0; i < 100; ++i) { 5831 s.push_back(i); 5832 mv.push_back(_); 5833 } 5834 mv[50] = Eq(0); 5835 StringMatchResultListener listener; 5836 EXPECT_TRUE(ExplainMatchResult(UnorderedElementsAreArray(mv), 5837 s, &listener)) << listener.str(); 5838} 5839 5840// Another variant of 'Performance' with similar expectations. 5841// [ RUN ] UnorderedElementsAreTest.PerformanceHalfStrict 5842// [ OK ] UnorderedElementsAreTest.PerformanceHalfStrict (4 ms) 5843TEST_F(UnorderedElementsAreTest, PerformanceHalfStrict) { 5844 std::vector<int> s; 5845 std::vector<Matcher<int> > mv; 5846 for (int i = 0; i < 100; ++i) { 5847 s.push_back(i); 5848 if (i & 1) { 5849 mv.push_back(_); 5850 } else { 5851 mv.push_back(i); 5852 } 5853 } 5854 StringMatchResultListener listener; 5855 EXPECT_TRUE(ExplainMatchResult(UnorderedElementsAreArray(mv), 5856 s, &listener)) << listener.str(); 5857} 5858 5859TEST_F(UnorderedElementsAreTest, FailMessageCountWrong) { 5860 std::vector<int> v; 5861 v.push_back(4); 5862 StringMatchResultListener listener; 5863 EXPECT_FALSE(ExplainMatchResult(UnorderedElementsAre(1, 2, 3), 5864 v, &listener)) << listener.str(); 5865 EXPECT_THAT(listener.str(), Eq("which has 1 element")); 5866} 5867 5868TEST_F(UnorderedElementsAreTest, FailMessageCountWrongZero) { 5869 std::vector<int> v; 5870 StringMatchResultListener listener; 5871 EXPECT_FALSE(ExplainMatchResult(UnorderedElementsAre(1, 2, 3), 5872 v, &listener)) << listener.str(); 5873 EXPECT_THAT(listener.str(), Eq("")); 5874} 5875 5876TEST_F(UnorderedElementsAreTest, FailMessageUnmatchedMatchers) { 5877 std::vector<int> v; 5878 v.push_back(1); 5879 v.push_back(1); 5880 StringMatchResultListener listener; 5881 EXPECT_FALSE(ExplainMatchResult(UnorderedElementsAre(1, 2), 5882 v, &listener)) << listener.str(); 5883 EXPECT_THAT( 5884 listener.str(), 5885 Eq("where the following matchers don't match any elements:\n" 5886 "matcher #1: is equal to 2")); 5887} 5888 5889TEST_F(UnorderedElementsAreTest, FailMessageUnmatchedElements) { 5890 std::vector<int> v; 5891 v.push_back(1); 5892 v.push_back(2); 5893 StringMatchResultListener listener; 5894 EXPECT_FALSE(ExplainMatchResult(UnorderedElementsAre(1, 1), 5895 v, &listener)) << listener.str(); 5896 EXPECT_THAT( 5897 listener.str(), 5898 Eq("where the following elements don't match any matchers:\n" 5899 "element #1: 2")); 5900} 5901 5902TEST_F(UnorderedElementsAreTest, FailMessageUnmatchedMatcherAndElement) { 5903 std::vector<int> v; 5904 v.push_back(2); 5905 v.push_back(3); 5906 StringMatchResultListener listener; 5907 EXPECT_FALSE(ExplainMatchResult(UnorderedElementsAre(1, 2), 5908 v, &listener)) << listener.str(); 5909 EXPECT_THAT( 5910 listener.str(), 5911 Eq("where" 5912 " the following matchers don't match any elements:\n" 5913 "matcher #0: is equal to 1\n" 5914 "and" 5915 " where" 5916 " the following elements don't match any matchers:\n" 5917 "element #1: 3")); 5918} 5919 5920// Test helper for formatting element, matcher index pairs in expectations. 5921static std::string EMString(int element, int matcher) { 5922 stringstream ss; 5923 ss << "(element #" << element << ", matcher #" << matcher << ")"; 5924 return ss.str(); 5925} 5926 5927TEST_F(UnorderedElementsAreTest, FailMessageImperfectMatchOnly) { 5928 // A situation where all elements and matchers have a match 5929 // associated with them, but the max matching is not perfect. 5930 std::vector<std::string> v; 5931 v.push_back("a"); 5932 v.push_back("b"); 5933 v.push_back("c"); 5934 StringMatchResultListener listener; 5935 EXPECT_FALSE(ExplainMatchResult( 5936 UnorderedElementsAre("a", "a", AnyOf("b", "c")), v, &listener)) 5937 << listener.str(); 5938 5939 std::string prefix = 5940 "where no permutation of the elements can satisfy all matchers, " 5941 "and the closest match is 2 of 3 matchers with the " 5942 "pairings:\n"; 5943 5944 // We have to be a bit loose here, because there are 4 valid max matches. 5945 EXPECT_THAT( 5946 listener.str(), 5947 AnyOf(prefix + "{\n " + EMString(0, 0) + 5948 ",\n " + EMString(1, 2) + "\n}", 5949 prefix + "{\n " + EMString(0, 1) + 5950 ",\n " + EMString(1, 2) + "\n}", 5951 prefix + "{\n " + EMString(0, 0) + 5952 ",\n " + EMString(2, 2) + "\n}", 5953 prefix + "{\n " + EMString(0, 1) + 5954 ",\n " + EMString(2, 2) + "\n}")); 5955} 5956 5957TEST_F(UnorderedElementsAreTest, Describe) { 5958 EXPECT_THAT(Describe<IntVec>(UnorderedElementsAre()), 5959 Eq("is empty")); 5960 EXPECT_THAT( 5961 Describe<IntVec>(UnorderedElementsAre(345)), 5962 Eq("has 1 element and that element is equal to 345")); 5963 EXPECT_THAT( 5964 Describe<IntVec>(UnorderedElementsAre(111, 222, 333)), 5965 Eq("has 3 elements and there exists some permutation " 5966 "of elements such that:\n" 5967 " - element #0 is equal to 111, and\n" 5968 " - element #1 is equal to 222, and\n" 5969 " - element #2 is equal to 333")); 5970} 5971 5972TEST_F(UnorderedElementsAreTest, DescribeNegation) { 5973 EXPECT_THAT(DescribeNegation<IntVec>(UnorderedElementsAre()), 5974 Eq("isn't empty")); 5975 EXPECT_THAT( 5976 DescribeNegation<IntVec>(UnorderedElementsAre(345)), 5977 Eq("doesn't have 1 element, or has 1 element that isn't equal to 345")); 5978 EXPECT_THAT( 5979 DescribeNegation<IntVec>(UnorderedElementsAre(123, 234, 345)), 5980 Eq("doesn't have 3 elements, or there exists no permutation " 5981 "of elements such that:\n" 5982 " - element #0 is equal to 123, and\n" 5983 " - element #1 is equal to 234, and\n" 5984 " - element #2 is equal to 345")); 5985} 5986 5987namespace { 5988 5989// Used as a check on the more complex max flow method used in the 5990// real testing::internal::FindMaxBipartiteMatching. This method is 5991// compatible but runs in worst-case factorial time, so we only 5992// use it in testing for small problem sizes. 5993template <typename Graph> 5994class BacktrackingMaxBPMState { 5995 public: 5996 // Does not take ownership of 'g'. 5997 explicit BacktrackingMaxBPMState(const Graph* g) : graph_(g) { } 5998 5999 ElementMatcherPairs Compute() { 6000 if (graph_->LhsSize() == 0 || graph_->RhsSize() == 0) { 6001 return best_so_far_; 6002 } 6003 lhs_used_.assign(graph_->LhsSize(), kUnused); 6004 rhs_used_.assign(graph_->RhsSize(), kUnused); 6005 for (size_t irhs = 0; irhs < graph_->RhsSize(); ++irhs) { 6006 matches_.clear(); 6007 RecurseInto(irhs); 6008 if (best_so_far_.size() == graph_->RhsSize()) 6009 break; 6010 } 6011 return best_so_far_; 6012 } 6013 6014 private: 6015 static const size_t kUnused = static_cast<size_t>(-1); 6016 6017 void PushMatch(size_t lhs, size_t rhs) { 6018 matches_.push_back(ElementMatcherPair(lhs, rhs)); 6019 lhs_used_[lhs] = rhs; 6020 rhs_used_[rhs] = lhs; 6021 if (matches_.size() > best_so_far_.size()) { 6022 best_so_far_ = matches_; 6023 } 6024 } 6025 6026 void PopMatch() { 6027 const ElementMatcherPair& back = matches_.back(); 6028 lhs_used_[back.first] = kUnused; 6029 rhs_used_[back.second] = kUnused; 6030 matches_.pop_back(); 6031 } 6032 6033 bool RecurseInto(size_t irhs) { 6034 if (rhs_used_[irhs] != kUnused) { 6035 return true; 6036 } 6037 for (size_t ilhs = 0; ilhs < graph_->LhsSize(); ++ilhs) { 6038 if (lhs_used_[ilhs] != kUnused) { 6039 continue; 6040 } 6041 if (!graph_->HasEdge(ilhs, irhs)) { 6042 continue; 6043 } 6044 PushMatch(ilhs, irhs); 6045 if (best_so_far_.size() == graph_->RhsSize()) { 6046 return false; 6047 } 6048 for (size_t mi = irhs + 1; mi < graph_->RhsSize(); ++mi) { 6049 if (!RecurseInto(mi)) return false; 6050 } 6051 PopMatch(); 6052 } 6053 return true; 6054 } 6055 6056 const Graph* graph_; // not owned 6057 std::vector<size_t> lhs_used_; 6058 std::vector<size_t> rhs_used_; 6059 ElementMatcherPairs matches_; 6060 ElementMatcherPairs best_so_far_; 6061}; 6062 6063template <typename Graph> 6064const size_t BacktrackingMaxBPMState<Graph>::kUnused; 6065 6066} // namespace 6067 6068// Implement a simple backtracking algorithm to determine if it is possible 6069// to find one element per matcher, without reusing elements. 6070template <typename Graph> 6071ElementMatcherPairs 6072FindBacktrackingMaxBPM(const Graph& g) { 6073 return BacktrackingMaxBPMState<Graph>(&g).Compute(); 6074} 6075 6076class BacktrackingBPMTest : public ::testing::Test { }; 6077 6078// Tests the MaxBipartiteMatching algorithm with square matrices. 6079// The single int param is the # of nodes on each of the left and right sides. 6080class BipartiteTest : public ::testing::TestWithParam<int> { }; 6081 6082// Verify all match graphs up to some moderate number of edges. 6083TEST_P(BipartiteTest, Exhaustive) { 6084 int nodes = GetParam(); 6085 MatchMatrix graph(nodes, nodes); 6086 do { 6087 ElementMatcherPairs matches = 6088 internal::FindMaxBipartiteMatching(graph); 6089 EXPECT_EQ(FindBacktrackingMaxBPM(graph).size(), matches.size()) 6090 << "graph: " << graph.DebugString(); 6091 // Check that all elements of matches are in the graph. 6092 // Check that elements of first and second are unique. 6093 std::vector<bool> seen_element(graph.LhsSize()); 6094 std::vector<bool> seen_matcher(graph.RhsSize()); 6095 SCOPED_TRACE(PrintToString(matches)); 6096 for (size_t i = 0; i < matches.size(); ++i) { 6097 size_t ilhs = matches[i].first; 6098 size_t irhs = matches[i].second; 6099 EXPECT_TRUE(graph.HasEdge(ilhs, irhs)); 6100 EXPECT_FALSE(seen_element[ilhs]); 6101 EXPECT_FALSE(seen_matcher[irhs]); 6102 seen_element[ilhs] = true; 6103 seen_matcher[irhs] = true; 6104 } 6105 } while (graph.NextGraph()); 6106} 6107 6108INSTANTIATE_TEST_CASE_P(AllGraphs, BipartiteTest, 6109 ::testing::Range(0, 5)); 6110 6111// Parameterized by a pair interpreted as (LhsSize, RhsSize). 6112class BipartiteNonSquareTest 6113 : public ::testing::TestWithParam<std::pair<size_t, size_t> > { 6114}; 6115 6116TEST_F(BipartiteNonSquareTest, SimpleBacktracking) { 6117 // ....... 6118 // 0:-----\ : 6119 // 1:---\ | : 6120 // 2:---\ | : 6121 // 3:-\ | | : 6122 // :.......: 6123 // 0 1 2 6124 MatchMatrix g(4, 3); 6125 static const int kEdges[][2] = {{0, 2}, {1, 1}, {2, 1}, {3, 0}}; 6126 for (size_t i = 0; i < GTEST_ARRAY_SIZE_(kEdges); ++i) { 6127 g.SetEdge(kEdges[i][0], kEdges[i][1], true); 6128 } 6129 EXPECT_THAT(FindBacktrackingMaxBPM(g), 6130 ElementsAre(Pair(3, 0), 6131 Pair(AnyOf(1, 2), 1), 6132 Pair(0, 2))) << g.DebugString(); 6133} 6134 6135// Verify a few nonsquare matrices. 6136TEST_P(BipartiteNonSquareTest, Exhaustive) { 6137 size_t nlhs = GetParam().first; 6138 size_t nrhs = GetParam().second; 6139 MatchMatrix graph(nlhs, nrhs); 6140 do { 6141 EXPECT_EQ(FindBacktrackingMaxBPM(graph).size(), 6142 internal::FindMaxBipartiteMatching(graph).size()) 6143 << "graph: " << graph.DebugString() 6144 << "\nbacktracking: " 6145 << PrintToString(FindBacktrackingMaxBPM(graph)) 6146 << "\nmax flow: " 6147 << PrintToString(internal::FindMaxBipartiteMatching(graph)); 6148 } while (graph.NextGraph()); 6149} 6150 6151INSTANTIATE_TEST_CASE_P(AllGraphs, BipartiteNonSquareTest, 6152 testing::Values( 6153 std::make_pair(1, 2), 6154 std::make_pair(2, 1), 6155 std::make_pair(3, 2), 6156 std::make_pair(2, 3), 6157 std::make_pair(4, 1), 6158 std::make_pair(1, 4), 6159 std::make_pair(4, 3), 6160 std::make_pair(3, 4))); 6161 6162class BipartiteRandomTest 6163 : public ::testing::TestWithParam<std::pair<int, int> > { 6164}; 6165 6166// Verifies a large sample of larger graphs. 6167TEST_P(BipartiteRandomTest, LargerNets) { 6168 int nodes = GetParam().first; 6169 int iters = GetParam().second; 6170 MatchMatrix graph(nodes, nodes); 6171 6172 testing::internal::Int32 seed = GTEST_FLAG(random_seed); 6173 if (seed == 0) { 6174 seed = static_cast<testing::internal::Int32>(time(NULL)); 6175 } 6176 6177 for (; iters > 0; --iters, ++seed) { 6178 srand(static_cast<int>(seed)); 6179 graph.Randomize(); 6180 EXPECT_EQ(FindBacktrackingMaxBPM(graph).size(), 6181 internal::FindMaxBipartiteMatching(graph).size()) 6182 << " graph: " << graph.DebugString() 6183 << "\nTo reproduce the failure, rerun the test with the flag" 6184 " --" << GTEST_FLAG_PREFIX_ << "random_seed=" << seed; 6185 } 6186} 6187 6188// Test argument is a std::pair<int, int> representing (nodes, iters). 6189INSTANTIATE_TEST_CASE_P(Samples, BipartiteRandomTest, 6190 testing::Values( 6191 std::make_pair(5, 10000), 6192 std::make_pair(6, 5000), 6193 std::make_pair(7, 2000), 6194 std::make_pair(8, 500), 6195 std::make_pair(9, 100))); 6196 6197// Tests IsReadableTypeName(). 6198 6199TEST(IsReadableTypeNameTest, ReturnsTrueForShortNames) { 6200 EXPECT_TRUE(IsReadableTypeName("int")); 6201 EXPECT_TRUE(IsReadableTypeName("const unsigned char*")); 6202 EXPECT_TRUE(IsReadableTypeName("MyMap<int, void*>")); 6203 EXPECT_TRUE(IsReadableTypeName("void (*)(int, bool)")); 6204} 6205 6206TEST(IsReadableTypeNameTest, ReturnsTrueForLongNonTemplateNonFunctionNames) { 6207 EXPECT_TRUE(IsReadableTypeName("my_long_namespace::MyClassName")); 6208 EXPECT_TRUE(IsReadableTypeName("int [5][6][7][8][9][10][11]")); 6209 EXPECT_TRUE(IsReadableTypeName("my_namespace::MyOuterClass::MyInnerClass")); 6210} 6211 6212TEST(IsReadableTypeNameTest, ReturnsFalseForLongTemplateNames) { 6213 EXPECT_FALSE( 6214 IsReadableTypeName("basic_string<char, std::char_traits<char> >")); 6215 EXPECT_FALSE(IsReadableTypeName("std::vector<int, std::alloc_traits<int> >")); 6216} 6217 6218TEST(IsReadableTypeNameTest, ReturnsFalseForLongFunctionTypeNames) { 6219 EXPECT_FALSE(IsReadableTypeName("void (&)(int, bool, char, float)")); 6220} 6221 6222// Tests FormatMatcherDescription(). 6223 6224TEST(FormatMatcherDescriptionTest, WorksForEmptyDescription) { 6225 EXPECT_EQ("is even", 6226 FormatMatcherDescription(false, "IsEven", Strings())); 6227 EXPECT_EQ("not (is even)", 6228 FormatMatcherDescription(true, "IsEven", Strings())); 6229 6230 const char* params[] = {"5"}; 6231 EXPECT_EQ("equals 5", 6232 FormatMatcherDescription(false, "Equals", 6233 Strings(params, params + 1))); 6234 6235 const char* params2[] = {"5", "8"}; 6236 EXPECT_EQ("is in range (5, 8)", 6237 FormatMatcherDescription(false, "IsInRange", 6238 Strings(params2, params2 + 2))); 6239} 6240 6241// Tests PolymorphicMatcher::mutable_impl(). 6242TEST(PolymorphicMatcherTest, CanAccessMutableImpl) { 6243 PolymorphicMatcher<DivisibleByImpl> m(DivisibleByImpl(42)); 6244 DivisibleByImpl& impl = m.mutable_impl(); 6245 EXPECT_EQ(42, impl.divider()); 6246 6247 impl.set_divider(0); 6248 EXPECT_EQ(0, m.mutable_impl().divider()); 6249} 6250 6251// Tests PolymorphicMatcher::impl(). 6252TEST(PolymorphicMatcherTest, CanAccessImpl) { 6253 const PolymorphicMatcher<DivisibleByImpl> m(DivisibleByImpl(42)); 6254 const DivisibleByImpl& impl = m.impl(); 6255 EXPECT_EQ(42, impl.divider()); 6256} 6257 6258TEST(MatcherTupleTest, ExplainsMatchFailure) { 6259 stringstream ss1; 6260 ExplainMatchFailureTupleTo(make_tuple(Matcher<char>(Eq('a')), GreaterThan(5)), 6261 make_tuple('a', 10), &ss1); 6262 EXPECT_EQ("", ss1.str()); // Successful match. 6263 6264 stringstream ss2; 6265 ExplainMatchFailureTupleTo(make_tuple(GreaterThan(5), Matcher<char>(Eq('a'))), 6266 make_tuple(2, 'b'), &ss2); 6267 EXPECT_EQ(" Expected arg #0: is > 5\n" 6268 " Actual: 2, which is 3 less than 5\n" 6269 " Expected arg #1: is equal to 'a' (97, 0x61)\n" 6270 " Actual: 'b' (98, 0x62)\n", 6271 ss2.str()); // Failed match where both arguments need explanation. 6272 6273 stringstream ss3; 6274 ExplainMatchFailureTupleTo(make_tuple(GreaterThan(5), Matcher<char>(Eq('a'))), 6275 make_tuple(2, 'a'), &ss3); 6276 EXPECT_EQ(" Expected arg #0: is > 5\n" 6277 " Actual: 2, which is 3 less than 5\n", 6278 ss3.str()); // Failed match where only one argument needs 6279 // explanation. 6280} 6281 6282// Tests Each(). 6283 6284TEST(EachTest, ExplainsMatchResultCorrectly) { 6285 set<int> a; // empty 6286 6287 Matcher<set<int> > m = Each(2); 6288 EXPECT_EQ("", Explain(m, a)); 6289 6290 Matcher<const int(&)[1]> n = Each(1); // NOLINT 6291 6292 const int b[1] = {1}; 6293 EXPECT_EQ("", Explain(n, b)); 6294 6295 n = Each(3); 6296 EXPECT_EQ("whose element #0 doesn't match", Explain(n, b)); 6297 6298 a.insert(1); 6299 a.insert(2); 6300 a.insert(3); 6301 m = Each(GreaterThan(0)); 6302 EXPECT_EQ("", Explain(m, a)); 6303 6304 m = Each(GreaterThan(10)); 6305 EXPECT_EQ("whose element #0 doesn't match, which is 9 less than 10", 6306 Explain(m, a)); 6307} 6308 6309TEST(EachTest, DescribesItselfCorrectly) { 6310 Matcher<vector<int> > m = Each(1); 6311 EXPECT_EQ("only contains elements that is equal to 1", Describe(m)); 6312 6313 Matcher<vector<int> > m2 = Not(m); 6314 EXPECT_EQ("contains some element that isn't equal to 1", Describe(m2)); 6315} 6316 6317TEST(EachTest, MatchesVectorWhenAllElementsMatch) { 6318 vector<int> some_vector; 6319 EXPECT_THAT(some_vector, Each(1)); 6320 some_vector.push_back(3); 6321 EXPECT_THAT(some_vector, Not(Each(1))); 6322 EXPECT_THAT(some_vector, Each(3)); 6323 some_vector.push_back(1); 6324 some_vector.push_back(2); 6325 EXPECT_THAT(some_vector, Not(Each(3))); 6326 EXPECT_THAT(some_vector, Each(Lt(3.5))); 6327 6328 vector<std::string> another_vector; 6329 another_vector.push_back("fee"); 6330 EXPECT_THAT(another_vector, Each(std::string("fee"))); 6331 another_vector.push_back("fie"); 6332 another_vector.push_back("foe"); 6333 another_vector.push_back("fum"); 6334 EXPECT_THAT(another_vector, Not(Each(std::string("fee")))); 6335} 6336 6337TEST(EachTest, MatchesMapWhenAllElementsMatch) { 6338 map<const char*, int> my_map; 6339 const char* bar = "a string"; 6340 my_map[bar] = 2; 6341 EXPECT_THAT(my_map, Each(make_pair(bar, 2))); 6342 6343 map<std::string, int> another_map; 6344 EXPECT_THAT(another_map, Each(make_pair(std::string("fee"), 1))); 6345 another_map["fee"] = 1; 6346 EXPECT_THAT(another_map, Each(make_pair(std::string("fee"), 1))); 6347 another_map["fie"] = 2; 6348 another_map["foe"] = 3; 6349 another_map["fum"] = 4; 6350 EXPECT_THAT(another_map, Not(Each(make_pair(std::string("fee"), 1)))); 6351 EXPECT_THAT(another_map, Not(Each(make_pair(std::string("fum"), 1)))); 6352 EXPECT_THAT(another_map, Each(Pair(_, Gt(0)))); 6353} 6354 6355TEST(EachTest, AcceptsMatcher) { 6356 const int a[] = {1, 2, 3}; 6357 EXPECT_THAT(a, Each(Gt(0))); 6358 EXPECT_THAT(a, Not(Each(Gt(1)))); 6359} 6360 6361TEST(EachTest, WorksForNativeArrayAsTuple) { 6362 const int a[] = {1, 2}; 6363 const int* const pointer = a; 6364 EXPECT_THAT(make_tuple(pointer, 2), Each(Gt(0))); 6365 EXPECT_THAT(make_tuple(pointer, 2), Not(Each(Gt(1)))); 6366} 6367 6368// For testing Pointwise(). 6369class IsHalfOfMatcher { 6370 public: 6371 template <typename T1, typename T2> 6372 bool MatchAndExplain(const tuple<T1, T2>& a_pair, 6373 MatchResultListener* listener) const { 6374 if (get<0>(a_pair) == get<1>(a_pair)/2) { 6375 *listener << "where the second is " << get<1>(a_pair); 6376 return true; 6377 } else { 6378 *listener << "where the second/2 is " << get<1>(a_pair)/2; 6379 return false; 6380 } 6381 } 6382 6383 void DescribeTo(ostream* os) const { 6384 *os << "are a pair where the first is half of the second"; 6385 } 6386 6387 void DescribeNegationTo(ostream* os) const { 6388 *os << "are a pair where the first isn't half of the second"; 6389 } 6390}; 6391 6392PolymorphicMatcher<IsHalfOfMatcher> IsHalfOf() { 6393 return MakePolymorphicMatcher(IsHalfOfMatcher()); 6394} 6395 6396TEST(PointwiseTest, DescribesSelf) { 6397 vector<int> rhs; 6398 rhs.push_back(1); 6399 rhs.push_back(2); 6400 rhs.push_back(3); 6401 const Matcher<const vector<int>&> m = Pointwise(IsHalfOf(), rhs); 6402 EXPECT_EQ("contains 3 values, where each value and its corresponding value " 6403 "in { 1, 2, 3 } are a pair where the first is half of the second", 6404 Describe(m)); 6405 EXPECT_EQ("doesn't contain exactly 3 values, or contains a value x at some " 6406 "index i where x and the i-th value of { 1, 2, 3 } are a pair " 6407 "where the first isn't half of the second", 6408 DescribeNegation(m)); 6409} 6410 6411TEST(PointwiseTest, MakesCopyOfRhs) { 6412 list<signed char> rhs; 6413 rhs.push_back(2); 6414 rhs.push_back(4); 6415 6416 int lhs[] = {1, 2}; 6417 const Matcher<const int (&)[2]> m = Pointwise(IsHalfOf(), rhs); 6418 EXPECT_THAT(lhs, m); 6419 6420 // Changing rhs now shouldn't affect m, which made a copy of rhs. 6421 rhs.push_back(6); 6422 EXPECT_THAT(lhs, m); 6423} 6424 6425TEST(PointwiseTest, WorksForLhsNativeArray) { 6426 const int lhs[] = {1, 2, 3}; 6427 vector<int> rhs; 6428 rhs.push_back(2); 6429 rhs.push_back(4); 6430 rhs.push_back(6); 6431 EXPECT_THAT(lhs, Pointwise(Lt(), rhs)); 6432 EXPECT_THAT(lhs, Not(Pointwise(Gt(), rhs))); 6433} 6434 6435TEST(PointwiseTest, WorksForRhsNativeArray) { 6436 const int rhs[] = {1, 2, 3}; 6437 vector<int> lhs; 6438 lhs.push_back(2); 6439 lhs.push_back(4); 6440 lhs.push_back(6); 6441 EXPECT_THAT(lhs, Pointwise(Gt(), rhs)); 6442 EXPECT_THAT(lhs, Not(Pointwise(Lt(), rhs))); 6443} 6444 6445// Test is effective only with sanitizers. 6446TEST(PointwiseTest, WorksForVectorOfBool) { 6447 vector<bool> rhs(3, false); 6448 rhs[1] = true; 6449 vector<bool> lhs = rhs; 6450 EXPECT_THAT(lhs, Pointwise(Eq(), rhs)); 6451 rhs[0] = true; 6452 EXPECT_THAT(lhs, Not(Pointwise(Eq(), rhs))); 6453} 6454 6455#if GTEST_HAS_STD_INITIALIZER_LIST_ 6456 6457TEST(PointwiseTest, WorksForRhsInitializerList) { 6458 const vector<int> lhs{2, 4, 6}; 6459 EXPECT_THAT(lhs, Pointwise(Gt(), {1, 2, 3})); 6460 EXPECT_THAT(lhs, Not(Pointwise(Lt(), {3, 3, 7}))); 6461} 6462 6463#endif // GTEST_HAS_STD_INITIALIZER_LIST_ 6464 6465TEST(PointwiseTest, RejectsWrongSize) { 6466 const double lhs[2] = {1, 2}; 6467 const int rhs[1] = {0}; 6468 EXPECT_THAT(lhs, Not(Pointwise(Gt(), rhs))); 6469 EXPECT_EQ("which contains 2 values", 6470 Explain(Pointwise(Gt(), rhs), lhs)); 6471 6472 const int rhs2[3] = {0, 1, 2}; 6473 EXPECT_THAT(lhs, Not(Pointwise(Gt(), rhs2))); 6474} 6475 6476TEST(PointwiseTest, RejectsWrongContent) { 6477 const double lhs[3] = {1, 2, 3}; 6478 const int rhs[3] = {2, 6, 4}; 6479 EXPECT_THAT(lhs, Not(Pointwise(IsHalfOf(), rhs))); 6480 EXPECT_EQ("where the value pair (2, 6) at index #1 don't match, " 6481 "where the second/2 is 3", 6482 Explain(Pointwise(IsHalfOf(), rhs), lhs)); 6483} 6484 6485TEST(PointwiseTest, AcceptsCorrectContent) { 6486 const double lhs[3] = {1, 2, 3}; 6487 const int rhs[3] = {2, 4, 6}; 6488 EXPECT_THAT(lhs, Pointwise(IsHalfOf(), rhs)); 6489 EXPECT_EQ("", Explain(Pointwise(IsHalfOf(), rhs), lhs)); 6490} 6491 6492TEST(PointwiseTest, AllowsMonomorphicInnerMatcher) { 6493 const double lhs[3] = {1, 2, 3}; 6494 const int rhs[3] = {2, 4, 6}; 6495 const Matcher<tuple<const double&, const int&> > m1 = IsHalfOf(); 6496 EXPECT_THAT(lhs, Pointwise(m1, rhs)); 6497 EXPECT_EQ("", Explain(Pointwise(m1, rhs), lhs)); 6498 6499 // This type works as a tuple<const double&, const int&> can be 6500 // implicitly cast to tuple<double, int>. 6501 const Matcher<tuple<double, int> > m2 = IsHalfOf(); 6502 EXPECT_THAT(lhs, Pointwise(m2, rhs)); 6503 EXPECT_EQ("", Explain(Pointwise(m2, rhs), lhs)); 6504} 6505 6506TEST(UnorderedPointwiseTest, DescribesSelf) { 6507 vector<int> rhs; 6508 rhs.push_back(1); 6509 rhs.push_back(2); 6510 rhs.push_back(3); 6511 const Matcher<const vector<int>&> m = UnorderedPointwise(IsHalfOf(), rhs); 6512 EXPECT_EQ( 6513 "has 3 elements and there exists some permutation of elements such " 6514 "that:\n" 6515 " - element #0 and 1 are a pair where the first is half of the second, " 6516 "and\n" 6517 " - element #1 and 2 are a pair where the first is half of the second, " 6518 "and\n" 6519 " - element #2 and 3 are a pair where the first is half of the second", 6520 Describe(m)); 6521 EXPECT_EQ( 6522 "doesn't have 3 elements, or there exists no permutation of elements " 6523 "such that:\n" 6524 " - element #0 and 1 are a pair where the first is half of the second, " 6525 "and\n" 6526 " - element #1 and 2 are a pair where the first is half of the second, " 6527 "and\n" 6528 " - element #2 and 3 are a pair where the first is half of the second", 6529 DescribeNegation(m)); 6530} 6531 6532TEST(UnorderedPointwiseTest, MakesCopyOfRhs) { 6533 list<signed char> rhs; 6534 rhs.push_back(2); 6535 rhs.push_back(4); 6536 6537 int lhs[] = {2, 1}; 6538 const Matcher<const int (&)[2]> m = UnorderedPointwise(IsHalfOf(), rhs); 6539 EXPECT_THAT(lhs, m); 6540 6541 // Changing rhs now shouldn't affect m, which made a copy of rhs. 6542 rhs.push_back(6); 6543 EXPECT_THAT(lhs, m); 6544} 6545 6546TEST(UnorderedPointwiseTest, WorksForLhsNativeArray) { 6547 const int lhs[] = {1, 2, 3}; 6548 vector<int> rhs; 6549 rhs.push_back(4); 6550 rhs.push_back(6); 6551 rhs.push_back(2); 6552 EXPECT_THAT(lhs, UnorderedPointwise(Lt(), rhs)); 6553 EXPECT_THAT(lhs, Not(UnorderedPointwise(Gt(), rhs))); 6554} 6555 6556TEST(UnorderedPointwiseTest, WorksForRhsNativeArray) { 6557 const int rhs[] = {1, 2, 3}; 6558 vector<int> lhs; 6559 lhs.push_back(4); 6560 lhs.push_back(2); 6561 lhs.push_back(6); 6562 EXPECT_THAT(lhs, UnorderedPointwise(Gt(), rhs)); 6563 EXPECT_THAT(lhs, Not(UnorderedPointwise(Lt(), rhs))); 6564} 6565 6566#if GTEST_HAS_STD_INITIALIZER_LIST_ 6567 6568TEST(UnorderedPointwiseTest, WorksForRhsInitializerList) { 6569 const vector<int> lhs{2, 4, 6}; 6570 EXPECT_THAT(lhs, UnorderedPointwise(Gt(), {5, 1, 3})); 6571 EXPECT_THAT(lhs, Not(UnorderedPointwise(Lt(), {1, 1, 7}))); 6572} 6573 6574#endif // GTEST_HAS_STD_INITIALIZER_LIST_ 6575 6576TEST(UnorderedPointwiseTest, RejectsWrongSize) { 6577 const double lhs[2] = {1, 2}; 6578 const int rhs[1] = {0}; 6579 EXPECT_THAT(lhs, Not(UnorderedPointwise(Gt(), rhs))); 6580 EXPECT_EQ("which has 2 elements", 6581 Explain(UnorderedPointwise(Gt(), rhs), lhs)); 6582 6583 const int rhs2[3] = {0, 1, 2}; 6584 EXPECT_THAT(lhs, Not(UnorderedPointwise(Gt(), rhs2))); 6585} 6586 6587TEST(UnorderedPointwiseTest, RejectsWrongContent) { 6588 const double lhs[3] = {1, 2, 3}; 6589 const int rhs[3] = {2, 6, 6}; 6590 EXPECT_THAT(lhs, Not(UnorderedPointwise(IsHalfOf(), rhs))); 6591 EXPECT_EQ("where the following elements don't match any matchers:\n" 6592 "element #1: 2", 6593 Explain(UnorderedPointwise(IsHalfOf(), rhs), lhs)); 6594} 6595 6596TEST(UnorderedPointwiseTest, AcceptsCorrectContentInSameOrder) { 6597 const double lhs[3] = {1, 2, 3}; 6598 const int rhs[3] = {2, 4, 6}; 6599 EXPECT_THAT(lhs, UnorderedPointwise(IsHalfOf(), rhs)); 6600} 6601 6602TEST(UnorderedPointwiseTest, AcceptsCorrectContentInDifferentOrder) { 6603 const double lhs[3] = {1, 2, 3}; 6604 const int rhs[3] = {6, 4, 2}; 6605 EXPECT_THAT(lhs, UnorderedPointwise(IsHalfOf(), rhs)); 6606} 6607 6608TEST(UnorderedPointwiseTest, AllowsMonomorphicInnerMatcher) { 6609 const double lhs[3] = {1, 2, 3}; 6610 const int rhs[3] = {4, 6, 2}; 6611 const Matcher<tuple<const double&, const int&> > m1 = IsHalfOf(); 6612 EXPECT_THAT(lhs, UnorderedPointwise(m1, rhs)); 6613 6614 // This type works as a tuple<const double&, const int&> can be 6615 // implicitly cast to tuple<double, int>. 6616 const Matcher<tuple<double, int> > m2 = IsHalfOf(); 6617 EXPECT_THAT(lhs, UnorderedPointwise(m2, rhs)); 6618} 6619 6620// Sample optional type implementation with minimal requirements for use with 6621// Optional matcher. 6622class SampleOptionalInt { 6623 public: 6624 typedef int value_type; 6625 explicit SampleOptionalInt(int value) : value_(value), has_value_(true) {} 6626 SampleOptionalInt() : value_(0), has_value_(false) {} 6627 operator bool() const { 6628 return has_value_; 6629 } 6630 const int& operator*() const { 6631 return value_; 6632 } 6633 private: 6634 int value_; 6635 bool has_value_; 6636}; 6637 6638TEST(OptionalTest, DescribesSelf) { 6639 const Matcher<SampleOptionalInt> m = Optional(Eq(1)); 6640 EXPECT_EQ("value is equal to 1", Describe(m)); 6641} 6642 6643TEST(OptionalTest, ExplainsSelf) { 6644 const Matcher<SampleOptionalInt> m = Optional(Eq(1)); 6645 EXPECT_EQ("whose value 1 matches", Explain(m, SampleOptionalInt(1))); 6646 EXPECT_EQ("whose value 2 doesn't match", Explain(m, SampleOptionalInt(2))); 6647} 6648 6649TEST(OptionalTest, MatchesNonEmptyOptional) { 6650 const Matcher<SampleOptionalInt> m1 = Optional(1); 6651 const Matcher<SampleOptionalInt> m2 = Optional(Eq(2)); 6652 const Matcher<SampleOptionalInt> m3 = Optional(Lt(3)); 6653 SampleOptionalInt opt(1); 6654 EXPECT_TRUE(m1.Matches(opt)); 6655 EXPECT_FALSE(m2.Matches(opt)); 6656 EXPECT_TRUE(m3.Matches(opt)); 6657} 6658 6659TEST(OptionalTest, DoesNotMatchNullopt) { 6660 const Matcher<SampleOptionalInt> m = Optional(1); 6661 SampleOptionalInt empty; 6662 EXPECT_FALSE(m.Matches(empty)); 6663} 6664 6665class SampleVariantIntString { 6666 public: 6667 SampleVariantIntString(int i) : i_(i), has_int_(true) {} 6668 SampleVariantIntString(const std::string& s) : s_(s), has_int_(false) {} 6669 6670 template <typename T> 6671 friend bool holds_alternative(const SampleVariantIntString& value) { 6672 return value.has_int_ == internal::IsSame<T, int>::value; 6673 } 6674 6675 template <typename T> 6676 friend const T& get(const SampleVariantIntString& value) { 6677 return value.get_impl(static_cast<T*>(NULL)); 6678 } 6679 6680 private: 6681 const int& get_impl(int*) const { return i_; } 6682 const std::string& get_impl(std::string*) const { return s_; } 6683 6684 int i_; 6685 std::string s_; 6686 bool has_int_; 6687}; 6688 6689TEST(VariantTest, DescribesSelf) { 6690 const Matcher<SampleVariantIntString> m = VariantWith<int>(Eq(1)); 6691 EXPECT_THAT(Describe(m), ContainsRegex("is a variant<> with value of type " 6692 "'.*' and the value is equal to 1")); 6693} 6694 6695TEST(VariantTest, ExplainsSelf) { 6696 const Matcher<SampleVariantIntString> m = VariantWith<int>(Eq(1)); 6697 EXPECT_THAT(Explain(m, SampleVariantIntString(1)), 6698 ContainsRegex("whose value 1")); 6699 EXPECT_THAT(Explain(m, SampleVariantIntString("A")), 6700 HasSubstr("whose value is not of type '")); 6701 EXPECT_THAT(Explain(m, SampleVariantIntString(2)), 6702 "whose value 2 doesn't match"); 6703} 6704 6705TEST(VariantTest, FullMatch) { 6706 Matcher<SampleVariantIntString> m = VariantWith<int>(Eq(1)); 6707 EXPECT_TRUE(m.Matches(SampleVariantIntString(1))); 6708 6709 m = VariantWith<std::string>(Eq("1")); 6710 EXPECT_TRUE(m.Matches(SampleVariantIntString("1"))); 6711} 6712 6713TEST(VariantTest, TypeDoesNotMatch) { 6714 Matcher<SampleVariantIntString> m = VariantWith<int>(Eq(1)); 6715 EXPECT_FALSE(m.Matches(SampleVariantIntString("1"))); 6716 6717 m = VariantWith<std::string>(Eq("1")); 6718 EXPECT_FALSE(m.Matches(SampleVariantIntString(1))); 6719} 6720 6721TEST(VariantTest, InnerDoesNotMatch) { 6722 Matcher<SampleVariantIntString> m = VariantWith<int>(Eq(1)); 6723 EXPECT_FALSE(m.Matches(SampleVariantIntString(2))); 6724 6725 m = VariantWith<std::string>(Eq("1")); 6726 EXPECT_FALSE(m.Matches(SampleVariantIntString("2"))); 6727} 6728 6729class SampleAnyType { 6730 public: 6731 explicit SampleAnyType(int i) : index_(0), i_(i) {} 6732 explicit SampleAnyType(const std::string& s) : index_(1), s_(s) {} 6733 6734 template <typename T> 6735 friend const T* any_cast(const SampleAnyType* any) { 6736 return any->get_impl(static_cast<T*>(NULL)); 6737 } 6738 6739 private: 6740 int index_; 6741 int i_; 6742 std::string s_; 6743 6744 const int* get_impl(int*) const { return index_ == 0 ? &i_ : NULL; } 6745 const std::string* get_impl(std::string*) const { 6746 return index_ == 1 ? &s_ : NULL; 6747 } 6748}; 6749 6750TEST(AnyWithTest, FullMatch) { 6751 Matcher<SampleAnyType> m = AnyWith<int>(Eq(1)); 6752 EXPECT_TRUE(m.Matches(SampleAnyType(1))); 6753} 6754 6755TEST(AnyWithTest, TestBadCastType) { 6756 Matcher<SampleAnyType> m = AnyWith<std::string>(Eq("fail")); 6757 EXPECT_FALSE(m.Matches(SampleAnyType(1))); 6758} 6759 6760#if GTEST_LANG_CXX11 6761TEST(AnyWithTest, TestUseInContainers) { 6762 std::vector<SampleAnyType> a; 6763 a.emplace_back(1); 6764 a.emplace_back(2); 6765 a.emplace_back(3); 6766 EXPECT_THAT( 6767 a, ElementsAreArray({AnyWith<int>(1), AnyWith<int>(2), AnyWith<int>(3)})); 6768 6769 std::vector<SampleAnyType> b; 6770 b.emplace_back("hello"); 6771 b.emplace_back("merhaba"); 6772 b.emplace_back("salut"); 6773 EXPECT_THAT(b, ElementsAreArray({AnyWith<std::string>("hello"), 6774 AnyWith<std::string>("merhaba"), 6775 AnyWith<std::string>("salut")})); 6776} 6777#endif // GTEST_LANG_CXX11 6778TEST(AnyWithTest, TestCompare) { 6779 EXPECT_THAT(SampleAnyType(1), AnyWith<int>(Gt(0))); 6780} 6781 6782TEST(AnyWithTest, DescribesSelf) { 6783 const Matcher<const SampleAnyType&> m = AnyWith<int>(Eq(1)); 6784 EXPECT_THAT(Describe(m), ContainsRegex("is an 'any' type with value of type " 6785 "'.*' and the value is equal to 1")); 6786} 6787 6788TEST(AnyWithTest, ExplainsSelf) { 6789 const Matcher<const SampleAnyType&> m = AnyWith<int>(Eq(1)); 6790 6791 EXPECT_THAT(Explain(m, SampleAnyType(1)), ContainsRegex("whose value 1")); 6792 EXPECT_THAT(Explain(m, SampleAnyType("A")), 6793 HasSubstr("whose value is not of type '")); 6794 EXPECT_THAT(Explain(m, SampleAnyType(2)), "whose value 2 doesn't match"); 6795} 6796 6797#if GTEST_LANG_CXX11 6798 6799TEST(PointeeTest, WorksOnMoveOnlyType) { 6800 std::unique_ptr<int> p(new int(3)); 6801 EXPECT_THAT(p, Pointee(Eq(3))); 6802 EXPECT_THAT(p, Not(Pointee(Eq(2)))); 6803} 6804 6805TEST(NotTest, WorksOnMoveOnlyType) { 6806 std::unique_ptr<int> p(new int(3)); 6807 EXPECT_THAT(p, Pointee(Eq(3))); 6808 EXPECT_THAT(p, Not(Pointee(Eq(2)))); 6809} 6810 6811#endif // GTEST_LANG_CXX11 6812 6813} // namespace gmock_matchers_test 6814} // namespace testing 6815