github.com/jlmucb/cloudproxy@v0.0.0-20170830161738-b5aa0b619bc4/src/third_party/googlemock/test/gmock-matchers_test.cc (about) 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 // Author: wan@google.com (Zhanyong Wan) 31 32 // Google Mock - a framework for writing C++ mock classes. 33 // 34 // This file tests some commonly used argument matchers. 35 36 #include "gmock/gmock-matchers.h" 37 #include "gmock/gmock-more-matchers.h" 38 39 #include <string.h> 40 #include <time.h> 41 #include <deque> 42 #include <functional> 43 #include <iostream> 44 #include <iterator> 45 #include <limits> 46 #include <list> 47 #include <map> 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 namespace testing { 58 59 namespace internal { 60 GTEST_API_ string JoinAsTuple(const Strings& fields); 61 } // namespace internal 62 63 namespace gmock_matchers_test { 64 65 using std::greater; 66 using std::less; 67 using std::list; 68 using std::make_pair; 69 using std::map; 70 using std::multimap; 71 using std::multiset; 72 using std::ostream; 73 using std::pair; 74 using std::set; 75 using std::stringstream; 76 using std::tr1::get; 77 using std::tr1::make_tuple; 78 using std::tr1::tuple; 79 using std::vector; 80 using testing::A; 81 using testing::AllArgs; 82 using testing::AllOf; 83 using testing::An; 84 using testing::AnyOf; 85 using testing::ByRef; 86 using testing::ContainsRegex; 87 using testing::DoubleEq; 88 using testing::DoubleNear; 89 using testing::EndsWith; 90 using testing::Eq; 91 using testing::ExplainMatchResult; 92 using testing::Field; 93 using testing::FloatEq; 94 using testing::FloatNear; 95 using testing::Ge; 96 using testing::Gt; 97 using testing::HasSubstr; 98 using testing::IsEmpty; 99 using testing::IsNull; 100 using testing::Key; 101 using testing::Le; 102 using testing::Lt; 103 using testing::MakeMatcher; 104 using testing::MakePolymorphicMatcher; 105 using testing::MatchResultListener; 106 using testing::Matcher; 107 using testing::MatcherCast; 108 using testing::MatcherInterface; 109 using testing::Matches; 110 using testing::MatchesRegex; 111 using testing::NanSensitiveDoubleEq; 112 using testing::NanSensitiveDoubleNear; 113 using testing::NanSensitiveFloatEq; 114 using testing::NanSensitiveFloatNear; 115 using testing::Ne; 116 using testing::Not; 117 using testing::NotNull; 118 using testing::Pair; 119 using testing::Pointee; 120 using testing::Pointwise; 121 using testing::PolymorphicMatcher; 122 using testing::Property; 123 using testing::Ref; 124 using testing::ResultOf; 125 using testing::SizeIs; 126 using testing::StartsWith; 127 using testing::StringMatchResultListener; 128 using testing::StrCaseEq; 129 using testing::StrCaseNe; 130 using testing::StrEq; 131 using testing::StrNe; 132 using testing::Truly; 133 using testing::TypedEq; 134 using testing::Value; 135 using testing::WhenSorted; 136 using testing::WhenSortedBy; 137 using testing::_; 138 using testing::internal::DummyMatchResultListener; 139 using testing::internal::ElementMatcherPair; 140 using testing::internal::ElementMatcherPairs; 141 using testing::internal::ExplainMatchFailureTupleTo; 142 using testing::internal::FloatingEqMatcher; 143 using testing::internal::FormatMatcherDescription; 144 using testing::internal::IsReadableTypeName; 145 using testing::internal::JoinAsTuple; 146 using testing::internal::MatchMatrix; 147 using testing::internal::RE; 148 using testing::internal::StreamMatchResultListener; 149 using testing::internal::Strings; 150 using testing::internal::linked_ptr; 151 using testing::internal::scoped_ptr; 152 using testing::internal::string; 153 154 // Evaluates to the number of elements in 'array'. 155 #define GMOCK_ARRAY_SIZE_(array) (sizeof(array) / sizeof(array[0])) 156 157 // For testing ExplainMatchResultTo(). 158 class GreaterThanMatcher : public MatcherInterface<int> { 159 public: 160 explicit GreaterThanMatcher(int rhs) : rhs_(rhs) {} 161 162 virtual void DescribeTo(ostream* os) const { 163 *os << "is > " << rhs_; 164 } 165 166 virtual bool MatchAndExplain(int lhs, 167 MatchResultListener* listener) const { 168 const int diff = lhs - rhs_; 169 if (diff > 0) { 170 *listener << "which is " << diff << " more than " << rhs_; 171 } else if (diff == 0) { 172 *listener << "which is the same as " << rhs_; 173 } else { 174 *listener << "which is " << -diff << " less than " << rhs_; 175 } 176 177 return lhs > rhs_; 178 } 179 180 private: 181 int rhs_; 182 }; 183 184 Matcher<int> GreaterThan(int n) { 185 return MakeMatcher(new GreaterThanMatcher(n)); 186 } 187 188 string OfType(const string& type_name) { 189 #if GTEST_HAS_RTTI 190 return " (of type " + type_name + ")"; 191 #else 192 return ""; 193 #endif 194 } 195 196 // Returns the description of the given matcher. 197 template <typename T> 198 string Describe(const Matcher<T>& m) { 199 stringstream ss; 200 m.DescribeTo(&ss); 201 return ss.str(); 202 } 203 204 // Returns the description of the negation of the given matcher. 205 template <typename T> 206 string DescribeNegation(const Matcher<T>& m) { 207 stringstream ss; 208 m.DescribeNegationTo(&ss); 209 return ss.str(); 210 } 211 212 // Returns the reason why x matches, or doesn't match, m. 213 template <typename MatcherType, typename Value> 214 string Explain(const MatcherType& m, const Value& x) { 215 StringMatchResultListener listener; 216 ExplainMatchResult(m, x, &listener); 217 return listener.str(); 218 } 219 220 TEST(MatchResultListenerTest, StreamingWorks) { 221 StringMatchResultListener listener; 222 listener << "hi" << 5; 223 EXPECT_EQ("hi5", listener.str()); 224 225 listener.Clear(); 226 EXPECT_EQ("", listener.str()); 227 228 listener << 42; 229 EXPECT_EQ("42", listener.str()); 230 231 // Streaming shouldn't crash when the underlying ostream is NULL. 232 DummyMatchResultListener dummy; 233 dummy << "hi" << 5; 234 } 235 236 TEST(MatchResultListenerTest, CanAccessUnderlyingStream) { 237 EXPECT_TRUE(DummyMatchResultListener().stream() == NULL); 238 EXPECT_TRUE(StreamMatchResultListener(NULL).stream() == NULL); 239 240 EXPECT_EQ(&std::cout, StreamMatchResultListener(&std::cout).stream()); 241 } 242 243 TEST(MatchResultListenerTest, IsInterestedWorks) { 244 EXPECT_TRUE(StringMatchResultListener().IsInterested()); 245 EXPECT_TRUE(StreamMatchResultListener(&std::cout).IsInterested()); 246 247 EXPECT_FALSE(DummyMatchResultListener().IsInterested()); 248 EXPECT_FALSE(StreamMatchResultListener(NULL).IsInterested()); 249 } 250 251 // Makes sure that the MatcherInterface<T> interface doesn't 252 // change. 253 class EvenMatcherImpl : public MatcherInterface<int> { 254 public: 255 virtual bool MatchAndExplain(int x, 256 MatchResultListener* /* listener */) const { 257 return x % 2 == 0; 258 } 259 260 virtual void DescribeTo(ostream* os) const { 261 *os << "is an even number"; 262 } 263 264 // We deliberately don't define DescribeNegationTo() and 265 // ExplainMatchResultTo() here, to make sure the definition of these 266 // two methods is optional. 267 }; 268 269 // Makes sure that the MatcherInterface API doesn't change. 270 TEST(MatcherInterfaceTest, CanBeImplementedUsingPublishedAPI) { 271 EvenMatcherImpl m; 272 } 273 274 // Tests implementing a monomorphic matcher using MatchAndExplain(). 275 276 class NewEvenMatcherImpl : public MatcherInterface<int> { 277 public: 278 virtual bool MatchAndExplain(int x, MatchResultListener* listener) const { 279 const bool match = x % 2 == 0; 280 // Verifies that we can stream to a listener directly. 281 *listener << "value % " << 2; 282 if (listener->stream() != NULL) { 283 // Verifies that we can stream to a listener's underlying stream 284 // too. 285 *listener->stream() << " == " << (x % 2); 286 } 287 return match; 288 } 289 290 virtual void DescribeTo(ostream* os) const { 291 *os << "is an even number"; 292 } 293 }; 294 295 TEST(MatcherInterfaceTest, CanBeImplementedUsingNewAPI) { 296 Matcher<int> m = MakeMatcher(new NewEvenMatcherImpl); 297 EXPECT_TRUE(m.Matches(2)); 298 EXPECT_FALSE(m.Matches(3)); 299 EXPECT_EQ("value % 2 == 0", Explain(m, 2)); 300 EXPECT_EQ("value % 2 == 1", Explain(m, 3)); 301 } 302 303 // Tests default-constructing a matcher. 304 TEST(MatcherTest, CanBeDefaultConstructed) { 305 Matcher<double> m; 306 } 307 308 // Tests that Matcher<T> can be constructed from a MatcherInterface<T>*. 309 TEST(MatcherTest, CanBeConstructedFromMatcherInterface) { 310 const MatcherInterface<int>* impl = new EvenMatcherImpl; 311 Matcher<int> m(impl); 312 EXPECT_TRUE(m.Matches(4)); 313 EXPECT_FALSE(m.Matches(5)); 314 } 315 316 // Tests that value can be used in place of Eq(value). 317 TEST(MatcherTest, CanBeImplicitlyConstructedFromValue) { 318 Matcher<int> m1 = 5; 319 EXPECT_TRUE(m1.Matches(5)); 320 EXPECT_FALSE(m1.Matches(6)); 321 } 322 323 // Tests that NULL can be used in place of Eq(NULL). 324 TEST(MatcherTest, CanBeImplicitlyConstructedFromNULL) { 325 Matcher<int*> m1 = NULL; 326 EXPECT_TRUE(m1.Matches(NULL)); 327 int n = 0; 328 EXPECT_FALSE(m1.Matches(&n)); 329 } 330 331 // Tests that matchers are copyable. 332 TEST(MatcherTest, IsCopyable) { 333 // Tests the copy constructor. 334 Matcher<bool> m1 = Eq(false); 335 EXPECT_TRUE(m1.Matches(false)); 336 EXPECT_FALSE(m1.Matches(true)); 337 338 // Tests the assignment operator. 339 m1 = Eq(true); 340 EXPECT_TRUE(m1.Matches(true)); 341 EXPECT_FALSE(m1.Matches(false)); 342 } 343 344 // Tests that Matcher<T>::DescribeTo() calls 345 // MatcherInterface<T>::DescribeTo(). 346 TEST(MatcherTest, CanDescribeItself) { 347 EXPECT_EQ("is an even number", 348 Describe(Matcher<int>(new EvenMatcherImpl))); 349 } 350 351 // Tests Matcher<T>::MatchAndExplain(). 352 TEST(MatcherTest, MatchAndExplain) { 353 Matcher<int> m = GreaterThan(0); 354 StringMatchResultListener listener1; 355 EXPECT_TRUE(m.MatchAndExplain(42, &listener1)); 356 EXPECT_EQ("which is 42 more than 0", listener1.str()); 357 358 StringMatchResultListener listener2; 359 EXPECT_FALSE(m.MatchAndExplain(-9, &listener2)); 360 EXPECT_EQ("which is 9 less than 0", listener2.str()); 361 } 362 363 // Tests that a C-string literal can be implicitly converted to a 364 // Matcher<string> or Matcher<const string&>. 365 TEST(StringMatcherTest, CanBeImplicitlyConstructedFromCStringLiteral) { 366 Matcher<string> m1 = "hi"; 367 EXPECT_TRUE(m1.Matches("hi")); 368 EXPECT_FALSE(m1.Matches("hello")); 369 370 Matcher<const string&> m2 = "hi"; 371 EXPECT_TRUE(m2.Matches("hi")); 372 EXPECT_FALSE(m2.Matches("hello")); 373 } 374 375 // Tests that a string object can be implicitly converted to a 376 // Matcher<string> or Matcher<const string&>. 377 TEST(StringMatcherTest, CanBeImplicitlyConstructedFromString) { 378 Matcher<string> m1 = string("hi"); 379 EXPECT_TRUE(m1.Matches("hi")); 380 EXPECT_FALSE(m1.Matches("hello")); 381 382 Matcher<const string&> m2 = string("hi"); 383 EXPECT_TRUE(m2.Matches("hi")); 384 EXPECT_FALSE(m2.Matches("hello")); 385 } 386 387 #if GTEST_HAS_STRING_PIECE_ 388 // Tests that a C-string literal can be implicitly converted to a 389 // Matcher<StringPiece> or Matcher<const StringPiece&>. 390 TEST(StringPieceMatcherTest, CanBeImplicitlyConstructedFromCStringLiteral) { 391 Matcher<StringPiece> m1 = "cats"; 392 EXPECT_TRUE(m1.Matches("cats")); 393 EXPECT_FALSE(m1.Matches("dogs")); 394 395 Matcher<const StringPiece&> m2 = "cats"; 396 EXPECT_TRUE(m2.Matches("cats")); 397 EXPECT_FALSE(m2.Matches("dogs")); 398 } 399 400 // Tests that a string object can be implicitly converted to a 401 // Matcher<StringPiece> or Matcher<const StringPiece&>. 402 TEST(StringPieceMatcherTest, CanBeImplicitlyConstructedFromString) { 403 Matcher<StringPiece> m1 = string("cats"); 404 EXPECT_TRUE(m1.Matches("cats")); 405 EXPECT_FALSE(m1.Matches("dogs")); 406 407 Matcher<const StringPiece&> m2 = string("cats"); 408 EXPECT_TRUE(m2.Matches("cats")); 409 EXPECT_FALSE(m2.Matches("dogs")); 410 } 411 412 // Tests that a StringPiece object can be implicitly converted to a 413 // Matcher<StringPiece> or Matcher<const StringPiece&>. 414 TEST(StringPieceMatcherTest, CanBeImplicitlyConstructedFromStringPiece) { 415 Matcher<StringPiece> m1 = StringPiece("cats"); 416 EXPECT_TRUE(m1.Matches("cats")); 417 EXPECT_FALSE(m1.Matches("dogs")); 418 419 Matcher<const StringPiece&> m2 = StringPiece("cats"); 420 EXPECT_TRUE(m2.Matches("cats")); 421 EXPECT_FALSE(m2.Matches("dogs")); 422 } 423 #endif // GTEST_HAS_STRING_PIECE_ 424 425 // Tests that MakeMatcher() constructs a Matcher<T> from a 426 // MatcherInterface* without requiring the user to explicitly 427 // write the type. 428 TEST(MakeMatcherTest, ConstructsMatcherFromMatcherInterface) { 429 const MatcherInterface<int>* dummy_impl = NULL; 430 Matcher<int> m = MakeMatcher(dummy_impl); 431 } 432 433 // Tests that MakePolymorphicMatcher() can construct a polymorphic 434 // matcher from its implementation using the old API. 435 const int g_bar = 1; 436 class ReferencesBarOrIsZeroImpl { 437 public: 438 template <typename T> 439 bool MatchAndExplain(const T& x, 440 MatchResultListener* /* listener */) const { 441 const void* p = &x; 442 return p == &g_bar || x == 0; 443 } 444 445 void DescribeTo(ostream* os) const { *os << "g_bar or zero"; } 446 447 void DescribeNegationTo(ostream* os) const { 448 *os << "doesn't reference g_bar and is not zero"; 449 } 450 }; 451 452 // This function verifies that MakePolymorphicMatcher() returns a 453 // PolymorphicMatcher<T> where T is the argument's type. 454 PolymorphicMatcher<ReferencesBarOrIsZeroImpl> ReferencesBarOrIsZero() { 455 return MakePolymorphicMatcher(ReferencesBarOrIsZeroImpl()); 456 } 457 458 TEST(MakePolymorphicMatcherTest, ConstructsMatcherUsingOldAPI) { 459 // Using a polymorphic matcher to match a reference type. 460 Matcher<const int&> m1 = ReferencesBarOrIsZero(); 461 EXPECT_TRUE(m1.Matches(0)); 462 // Verifies that the identity of a by-reference argument is preserved. 463 EXPECT_TRUE(m1.Matches(g_bar)); 464 EXPECT_FALSE(m1.Matches(1)); 465 EXPECT_EQ("g_bar or zero", Describe(m1)); 466 467 // Using a polymorphic matcher to match a value type. 468 Matcher<double> m2 = ReferencesBarOrIsZero(); 469 EXPECT_TRUE(m2.Matches(0.0)); 470 EXPECT_FALSE(m2.Matches(0.1)); 471 EXPECT_EQ("g_bar or zero", Describe(m2)); 472 } 473 474 // Tests implementing a polymorphic matcher using MatchAndExplain(). 475 476 class PolymorphicIsEvenImpl { 477 public: 478 void DescribeTo(ostream* os) const { *os << "is even"; } 479 480 void DescribeNegationTo(ostream* os) const { 481 *os << "is odd"; 482 } 483 484 template <typename T> 485 bool MatchAndExplain(const T& x, MatchResultListener* listener) const { 486 // Verifies that we can stream to the listener directly. 487 *listener << "% " << 2; 488 if (listener->stream() != NULL) { 489 // Verifies that we can stream to the listener's underlying stream 490 // too. 491 *listener->stream() << " == " << (x % 2); 492 } 493 return (x % 2) == 0; 494 } 495 }; 496 497 PolymorphicMatcher<PolymorphicIsEvenImpl> PolymorphicIsEven() { 498 return MakePolymorphicMatcher(PolymorphicIsEvenImpl()); 499 } 500 501 TEST(MakePolymorphicMatcherTest, ConstructsMatcherUsingNewAPI) { 502 // Using PolymorphicIsEven() as a Matcher<int>. 503 const Matcher<int> m1 = PolymorphicIsEven(); 504 EXPECT_TRUE(m1.Matches(42)); 505 EXPECT_FALSE(m1.Matches(43)); 506 EXPECT_EQ("is even", Describe(m1)); 507 508 const Matcher<int> not_m1 = Not(m1); 509 EXPECT_EQ("is odd", Describe(not_m1)); 510 511 EXPECT_EQ("% 2 == 0", Explain(m1, 42)); 512 513 // Using PolymorphicIsEven() as a Matcher<char>. 514 const Matcher<char> m2 = PolymorphicIsEven(); 515 EXPECT_TRUE(m2.Matches('\x42')); 516 EXPECT_FALSE(m2.Matches('\x43')); 517 EXPECT_EQ("is even", Describe(m2)); 518 519 const Matcher<char> not_m2 = Not(m2); 520 EXPECT_EQ("is odd", Describe(not_m2)); 521 522 EXPECT_EQ("% 2 == 0", Explain(m2, '\x42')); 523 } 524 525 // Tests that MatcherCast<T>(m) works when m is a polymorphic matcher. 526 TEST(MatcherCastTest, FromPolymorphicMatcher) { 527 Matcher<int> m = MatcherCast<int>(Eq(5)); 528 EXPECT_TRUE(m.Matches(5)); 529 EXPECT_FALSE(m.Matches(6)); 530 } 531 532 // For testing casting matchers between compatible types. 533 class IntValue { 534 public: 535 // An int can be statically (although not implicitly) cast to a 536 // IntValue. 537 explicit IntValue(int a_value) : value_(a_value) {} 538 539 int value() const { return value_; } 540 private: 541 int value_; 542 }; 543 544 // For testing casting matchers between compatible types. 545 bool IsPositiveIntValue(const IntValue& foo) { 546 return foo.value() > 0; 547 } 548 549 // Tests that MatcherCast<T>(m) works when m is a Matcher<U> where T 550 // can be statically converted to U. 551 TEST(MatcherCastTest, FromCompatibleType) { 552 Matcher<double> m1 = Eq(2.0); 553 Matcher<int> m2 = MatcherCast<int>(m1); 554 EXPECT_TRUE(m2.Matches(2)); 555 EXPECT_FALSE(m2.Matches(3)); 556 557 Matcher<IntValue> m3 = Truly(IsPositiveIntValue); 558 Matcher<int> m4 = MatcherCast<int>(m3); 559 // In the following, the arguments 1 and 0 are statically converted 560 // to IntValue objects, and then tested by the IsPositiveIntValue() 561 // predicate. 562 EXPECT_TRUE(m4.Matches(1)); 563 EXPECT_FALSE(m4.Matches(0)); 564 } 565 566 // Tests that MatcherCast<T>(m) works when m is a Matcher<const T&>. 567 TEST(MatcherCastTest, FromConstReferenceToNonReference) { 568 Matcher<const int&> m1 = Eq(0); 569 Matcher<int> m2 = MatcherCast<int>(m1); 570 EXPECT_TRUE(m2.Matches(0)); 571 EXPECT_FALSE(m2.Matches(1)); 572 } 573 574 // Tests that MatcherCast<T>(m) works when m is a Matcher<T&>. 575 TEST(MatcherCastTest, FromReferenceToNonReference) { 576 Matcher<int&> m1 = Eq(0); 577 Matcher<int> m2 = MatcherCast<int>(m1); 578 EXPECT_TRUE(m2.Matches(0)); 579 EXPECT_FALSE(m2.Matches(1)); 580 } 581 582 // Tests that MatcherCast<const T&>(m) works when m is a Matcher<T>. 583 TEST(MatcherCastTest, FromNonReferenceToConstReference) { 584 Matcher<int> m1 = Eq(0); 585 Matcher<const int&> m2 = MatcherCast<const int&>(m1); 586 EXPECT_TRUE(m2.Matches(0)); 587 EXPECT_FALSE(m2.Matches(1)); 588 } 589 590 // Tests that MatcherCast<T&>(m) works when m is a Matcher<T>. 591 TEST(MatcherCastTest, FromNonReferenceToReference) { 592 Matcher<int> m1 = Eq(0); 593 Matcher<int&> m2 = MatcherCast<int&>(m1); 594 int n = 0; 595 EXPECT_TRUE(m2.Matches(n)); 596 n = 1; 597 EXPECT_FALSE(m2.Matches(n)); 598 } 599 600 // Tests that MatcherCast<T>(m) works when m is a Matcher<T>. 601 TEST(MatcherCastTest, FromSameType) { 602 Matcher<int> m1 = Eq(0); 603 Matcher<int> m2 = MatcherCast<int>(m1); 604 EXPECT_TRUE(m2.Matches(0)); 605 EXPECT_FALSE(m2.Matches(1)); 606 } 607 608 // Implicitly convertible form any type. 609 struct ConvertibleFromAny { 610 ConvertibleFromAny(int a_value) : value(a_value) {} 611 template <typename T> 612 ConvertibleFromAny(const T& a_value) : value(-1) { 613 ADD_FAILURE() << "Conversion constructor called"; 614 } 615 int value; 616 }; 617 618 bool operator==(const ConvertibleFromAny& a, const ConvertibleFromAny& b) { 619 return a.value == b.value; 620 } 621 622 ostream& operator<<(ostream& os, const ConvertibleFromAny& a) { 623 return os << a.value; 624 } 625 626 TEST(MatcherCastTest, ConversionConstructorIsUsed) { 627 Matcher<ConvertibleFromAny> m = MatcherCast<ConvertibleFromAny>(1); 628 EXPECT_TRUE(m.Matches(ConvertibleFromAny(1))); 629 EXPECT_FALSE(m.Matches(ConvertibleFromAny(2))); 630 } 631 632 TEST(MatcherCastTest, FromConvertibleFromAny) { 633 Matcher<ConvertibleFromAny> m = 634 MatcherCast<ConvertibleFromAny>(Eq(ConvertibleFromAny(1))); 635 EXPECT_TRUE(m.Matches(ConvertibleFromAny(1))); 636 EXPECT_FALSE(m.Matches(ConvertibleFromAny(2))); 637 } 638 639 class Base {}; 640 class Derived : public Base {}; 641 642 // Tests that SafeMatcherCast<T>(m) works when m is a polymorphic matcher. 643 TEST(SafeMatcherCastTest, FromPolymorphicMatcher) { 644 Matcher<char> m2 = SafeMatcherCast<char>(Eq(32)); 645 EXPECT_TRUE(m2.Matches(' ')); 646 EXPECT_FALSE(m2.Matches('\n')); 647 } 648 649 // Tests that SafeMatcherCast<T>(m) works when m is a Matcher<U> where 650 // T and U are arithmetic types and T can be losslessly converted to 651 // U. 652 TEST(SafeMatcherCastTest, FromLosslesslyConvertibleArithmeticType) { 653 Matcher<double> m1 = DoubleEq(1.0); 654 Matcher<float> m2 = SafeMatcherCast<float>(m1); 655 EXPECT_TRUE(m2.Matches(1.0f)); 656 EXPECT_FALSE(m2.Matches(2.0f)); 657 658 Matcher<char> m3 = SafeMatcherCast<char>(TypedEq<int>('a')); 659 EXPECT_TRUE(m3.Matches('a')); 660 EXPECT_FALSE(m3.Matches('b')); 661 } 662 663 // Tests that SafeMatcherCast<T>(m) works when m is a Matcher<U> where T and U 664 // are pointers or references to a derived and a base class, correspondingly. 665 TEST(SafeMatcherCastTest, FromBaseClass) { 666 Derived d, d2; 667 Matcher<Base*> m1 = Eq(&d); 668 Matcher<Derived*> m2 = SafeMatcherCast<Derived*>(m1); 669 EXPECT_TRUE(m2.Matches(&d)); 670 EXPECT_FALSE(m2.Matches(&d2)); 671 672 Matcher<Base&> m3 = Ref(d); 673 Matcher<Derived&> m4 = SafeMatcherCast<Derived&>(m3); 674 EXPECT_TRUE(m4.Matches(d)); 675 EXPECT_FALSE(m4.Matches(d2)); 676 } 677 678 // Tests that SafeMatcherCast<T&>(m) works when m is a Matcher<const T&>. 679 TEST(SafeMatcherCastTest, FromConstReferenceToReference) { 680 int n = 0; 681 Matcher<const int&> m1 = Ref(n); 682 Matcher<int&> m2 = SafeMatcherCast<int&>(m1); 683 int n1 = 0; 684 EXPECT_TRUE(m2.Matches(n)); 685 EXPECT_FALSE(m2.Matches(n1)); 686 } 687 688 // Tests that MatcherCast<const T&>(m) works when m is a Matcher<T>. 689 TEST(SafeMatcherCastTest, FromNonReferenceToConstReference) { 690 Matcher<int> m1 = Eq(0); 691 Matcher<const int&> m2 = SafeMatcherCast<const int&>(m1); 692 EXPECT_TRUE(m2.Matches(0)); 693 EXPECT_FALSE(m2.Matches(1)); 694 } 695 696 // Tests that SafeMatcherCast<T&>(m) works when m is a Matcher<T>. 697 TEST(SafeMatcherCastTest, FromNonReferenceToReference) { 698 Matcher<int> m1 = Eq(0); 699 Matcher<int&> m2 = SafeMatcherCast<int&>(m1); 700 int n = 0; 701 EXPECT_TRUE(m2.Matches(n)); 702 n = 1; 703 EXPECT_FALSE(m2.Matches(n)); 704 } 705 706 // Tests that SafeMatcherCast<T>(m) works when m is a Matcher<T>. 707 TEST(SafeMatcherCastTest, FromSameType) { 708 Matcher<int> m1 = Eq(0); 709 Matcher<int> m2 = SafeMatcherCast<int>(m1); 710 EXPECT_TRUE(m2.Matches(0)); 711 EXPECT_FALSE(m2.Matches(1)); 712 } 713 714 TEST(SafeMatcherCastTest, ConversionConstructorIsUsed) { 715 Matcher<ConvertibleFromAny> m = SafeMatcherCast<ConvertibleFromAny>(1); 716 EXPECT_TRUE(m.Matches(ConvertibleFromAny(1))); 717 EXPECT_FALSE(m.Matches(ConvertibleFromAny(2))); 718 } 719 720 TEST(SafeMatcherCastTest, FromConvertibleFromAny) { 721 Matcher<ConvertibleFromAny> m = 722 SafeMatcherCast<ConvertibleFromAny>(Eq(ConvertibleFromAny(1))); 723 EXPECT_TRUE(m.Matches(ConvertibleFromAny(1))); 724 EXPECT_FALSE(m.Matches(ConvertibleFromAny(2))); 725 } 726 727 // Tests that A<T>() matches any value of type T. 728 TEST(ATest, MatchesAnyValue) { 729 // Tests a matcher for a value type. 730 Matcher<double> m1 = A<double>(); 731 EXPECT_TRUE(m1.Matches(91.43)); 732 EXPECT_TRUE(m1.Matches(-15.32)); 733 734 // Tests a matcher for a reference type. 735 int a = 2; 736 int b = -6; 737 Matcher<int&> m2 = A<int&>(); 738 EXPECT_TRUE(m2.Matches(a)); 739 EXPECT_TRUE(m2.Matches(b)); 740 } 741 742 TEST(ATest, WorksForDerivedClass) { 743 Base base; 744 Derived derived; 745 EXPECT_THAT(&base, A<Base*>()); 746 // This shouldn't compile: EXPECT_THAT(&base, A<Derived*>()); 747 EXPECT_THAT(&derived, A<Base*>()); 748 EXPECT_THAT(&derived, A<Derived*>()); 749 } 750 751 // Tests that A<T>() describes itself properly. 752 TEST(ATest, CanDescribeSelf) { 753 EXPECT_EQ("is anything", Describe(A<bool>())); 754 } 755 756 // Tests that An<T>() matches any value of type T. 757 TEST(AnTest, MatchesAnyValue) { 758 // Tests a matcher for a value type. 759 Matcher<int> m1 = An<int>(); 760 EXPECT_TRUE(m1.Matches(9143)); 761 EXPECT_TRUE(m1.Matches(-1532)); 762 763 // Tests a matcher for a reference type. 764 int a = 2; 765 int b = -6; 766 Matcher<int&> m2 = An<int&>(); 767 EXPECT_TRUE(m2.Matches(a)); 768 EXPECT_TRUE(m2.Matches(b)); 769 } 770 771 // Tests that An<T>() describes itself properly. 772 TEST(AnTest, CanDescribeSelf) { 773 EXPECT_EQ("is anything", Describe(An<int>())); 774 } 775 776 // Tests that _ can be used as a matcher for any type and matches any 777 // value of that type. 778 TEST(UnderscoreTest, MatchesAnyValue) { 779 // Uses _ as a matcher for a value type. 780 Matcher<int> m1 = _; 781 EXPECT_TRUE(m1.Matches(123)); 782 EXPECT_TRUE(m1.Matches(-242)); 783 784 // Uses _ as a matcher for a reference type. 785 bool a = false; 786 const bool b = true; 787 Matcher<const bool&> m2 = _; 788 EXPECT_TRUE(m2.Matches(a)); 789 EXPECT_TRUE(m2.Matches(b)); 790 } 791 792 // Tests that _ describes itself properly. 793 TEST(UnderscoreTest, CanDescribeSelf) { 794 Matcher<int> m = _; 795 EXPECT_EQ("is anything", Describe(m)); 796 } 797 798 // Tests that Eq(x) matches any value equal to x. 799 TEST(EqTest, MatchesEqualValue) { 800 // 2 C-strings with same content but different addresses. 801 const char a1[] = "hi"; 802 const char a2[] = "hi"; 803 804 Matcher<const char*> m1 = Eq(a1); 805 EXPECT_TRUE(m1.Matches(a1)); 806 EXPECT_FALSE(m1.Matches(a2)); 807 } 808 809 // Tests that Eq(v) describes itself properly. 810 811 class Unprintable { 812 public: 813 Unprintable() : c_('a') {} 814 815 bool operator==(const Unprintable& /* rhs */) { return true; } 816 private: 817 char c_; 818 }; 819 820 TEST(EqTest, CanDescribeSelf) { 821 Matcher<Unprintable> m = Eq(Unprintable()); 822 EXPECT_EQ("is equal to 1-byte object <61>", Describe(m)); 823 } 824 825 // Tests that Eq(v) can be used to match any type that supports 826 // comparing with type T, where T is v's type. 827 TEST(EqTest, IsPolymorphic) { 828 Matcher<int> m1 = Eq(1); 829 EXPECT_TRUE(m1.Matches(1)); 830 EXPECT_FALSE(m1.Matches(2)); 831 832 Matcher<char> m2 = Eq(1); 833 EXPECT_TRUE(m2.Matches('\1')); 834 EXPECT_FALSE(m2.Matches('a')); 835 } 836 837 // Tests that TypedEq<T>(v) matches values of type T that's equal to v. 838 TEST(TypedEqTest, ChecksEqualityForGivenType) { 839 Matcher<char> m1 = TypedEq<char>('a'); 840 EXPECT_TRUE(m1.Matches('a')); 841 EXPECT_FALSE(m1.Matches('b')); 842 843 Matcher<int> m2 = TypedEq<int>(6); 844 EXPECT_TRUE(m2.Matches(6)); 845 EXPECT_FALSE(m2.Matches(7)); 846 } 847 848 // Tests that TypedEq(v) describes itself properly. 849 TEST(TypedEqTest, CanDescribeSelf) { 850 EXPECT_EQ("is equal to 2", Describe(TypedEq<int>(2))); 851 } 852 853 // Tests that TypedEq<T>(v) has type Matcher<T>. 854 855 // Type<T>::IsTypeOf(v) compiles iff the type of value v is T, where T 856 // is a "bare" type (i.e. not in the form of const U or U&). If v's 857 // type is not T, the compiler will generate a message about 858 // "undefined referece". 859 template <typename T> 860 struct Type { 861 static bool IsTypeOf(const T& /* v */) { return true; } 862 863 template <typename T2> 864 static void IsTypeOf(T2 v); 865 }; 866 867 TEST(TypedEqTest, HasSpecifiedType) { 868 // Verfies that the type of TypedEq<T>(v) is Matcher<T>. 869 Type<Matcher<int> >::IsTypeOf(TypedEq<int>(5)); 870 Type<Matcher<double> >::IsTypeOf(TypedEq<double>(5)); 871 } 872 873 // Tests that Ge(v) matches anything >= v. 874 TEST(GeTest, ImplementsGreaterThanOrEqual) { 875 Matcher<int> m1 = Ge(0); 876 EXPECT_TRUE(m1.Matches(1)); 877 EXPECT_TRUE(m1.Matches(0)); 878 EXPECT_FALSE(m1.Matches(-1)); 879 } 880 881 // Tests that Ge(v) describes itself properly. 882 TEST(GeTest, CanDescribeSelf) { 883 Matcher<int> m = Ge(5); 884 EXPECT_EQ("is >= 5", Describe(m)); 885 } 886 887 // Tests that Gt(v) matches anything > v. 888 TEST(GtTest, ImplementsGreaterThan) { 889 Matcher<double> m1 = Gt(0); 890 EXPECT_TRUE(m1.Matches(1.0)); 891 EXPECT_FALSE(m1.Matches(0.0)); 892 EXPECT_FALSE(m1.Matches(-1.0)); 893 } 894 895 // Tests that Gt(v) describes itself properly. 896 TEST(GtTest, CanDescribeSelf) { 897 Matcher<int> m = Gt(5); 898 EXPECT_EQ("is > 5", Describe(m)); 899 } 900 901 // Tests that Le(v) matches anything <= v. 902 TEST(LeTest, ImplementsLessThanOrEqual) { 903 Matcher<char> m1 = Le('b'); 904 EXPECT_TRUE(m1.Matches('a')); 905 EXPECT_TRUE(m1.Matches('b')); 906 EXPECT_FALSE(m1.Matches('c')); 907 } 908 909 // Tests that Le(v) describes itself properly. 910 TEST(LeTest, CanDescribeSelf) { 911 Matcher<int> m = Le(5); 912 EXPECT_EQ("is <= 5", Describe(m)); 913 } 914 915 // Tests that Lt(v) matches anything < v. 916 TEST(LtTest, ImplementsLessThan) { 917 Matcher<const string&> m1 = Lt("Hello"); 918 EXPECT_TRUE(m1.Matches("Abc")); 919 EXPECT_FALSE(m1.Matches("Hello")); 920 EXPECT_FALSE(m1.Matches("Hello, world!")); 921 } 922 923 // Tests that Lt(v) describes itself properly. 924 TEST(LtTest, CanDescribeSelf) { 925 Matcher<int> m = Lt(5); 926 EXPECT_EQ("is < 5", Describe(m)); 927 } 928 929 // Tests that Ne(v) matches anything != v. 930 TEST(NeTest, ImplementsNotEqual) { 931 Matcher<int> m1 = Ne(0); 932 EXPECT_TRUE(m1.Matches(1)); 933 EXPECT_TRUE(m1.Matches(-1)); 934 EXPECT_FALSE(m1.Matches(0)); 935 } 936 937 // Tests that Ne(v) describes itself properly. 938 TEST(NeTest, CanDescribeSelf) { 939 Matcher<int> m = Ne(5); 940 EXPECT_EQ("isn't equal to 5", Describe(m)); 941 } 942 943 // Tests that IsNull() matches any NULL pointer of any type. 944 TEST(IsNullTest, MatchesNullPointer) { 945 Matcher<int*> m1 = IsNull(); 946 int* p1 = NULL; 947 int n = 0; 948 EXPECT_TRUE(m1.Matches(p1)); 949 EXPECT_FALSE(m1.Matches(&n)); 950 951 Matcher<const char*> m2 = IsNull(); 952 const char* p2 = NULL; 953 EXPECT_TRUE(m2.Matches(p2)); 954 EXPECT_FALSE(m2.Matches("hi")); 955 956 #if !GTEST_OS_SYMBIAN 957 // Nokia's Symbian compiler generates: 958 // gmock-matchers.h: ambiguous access to overloaded function 959 // gmock-matchers.h: 'testing::Matcher<void *>::Matcher(void *)' 960 // gmock-matchers.h: 'testing::Matcher<void *>::Matcher(const testing:: 961 // MatcherInterface<void *> *)' 962 // gmock-matchers.h: (point of instantiation: 'testing:: 963 // gmock_matchers_test::IsNullTest_MatchesNullPointer_Test::TestBody()') 964 // gmock-matchers.h: (instantiating: 'testing::PolymorphicMatc 965 Matcher<void*> m3 = IsNull(); 966 void* p3 = NULL; 967 EXPECT_TRUE(m3.Matches(p3)); 968 EXPECT_FALSE(m3.Matches(reinterpret_cast<void*>(0xbeef))); 969 #endif 970 } 971 972 TEST(IsNullTest, LinkedPtr) { 973 const Matcher<linked_ptr<int> > m = IsNull(); 974 const linked_ptr<int> null_p; 975 const linked_ptr<int> non_null_p(new int); 976 977 EXPECT_TRUE(m.Matches(null_p)); 978 EXPECT_FALSE(m.Matches(non_null_p)); 979 } 980 981 TEST(IsNullTest, ReferenceToConstLinkedPtr) { 982 const Matcher<const linked_ptr<double>&> m = IsNull(); 983 const linked_ptr<double> null_p; 984 const linked_ptr<double> non_null_p(new double); 985 986 EXPECT_TRUE(m.Matches(null_p)); 987 EXPECT_FALSE(m.Matches(non_null_p)); 988 } 989 990 TEST(IsNullTest, ReferenceToConstScopedPtr) { 991 const Matcher<const scoped_ptr<double>&> m = IsNull(); 992 const scoped_ptr<double> null_p; 993 const scoped_ptr<double> non_null_p(new double); 994 995 EXPECT_TRUE(m.Matches(null_p)); 996 EXPECT_FALSE(m.Matches(non_null_p)); 997 } 998 999 // Tests that IsNull() describes itself properly. 1000 TEST(IsNullTest, CanDescribeSelf) { 1001 Matcher<int*> m = IsNull(); 1002 EXPECT_EQ("is NULL", Describe(m)); 1003 EXPECT_EQ("isn't NULL", DescribeNegation(m)); 1004 } 1005 1006 // Tests that NotNull() matches any non-NULL pointer of any type. 1007 TEST(NotNullTest, MatchesNonNullPointer) { 1008 Matcher<int*> m1 = NotNull(); 1009 int* p1 = NULL; 1010 int n = 0; 1011 EXPECT_FALSE(m1.Matches(p1)); 1012 EXPECT_TRUE(m1.Matches(&n)); 1013 1014 Matcher<const char*> m2 = NotNull(); 1015 const char* p2 = NULL; 1016 EXPECT_FALSE(m2.Matches(p2)); 1017 EXPECT_TRUE(m2.Matches("hi")); 1018 } 1019 1020 TEST(NotNullTest, LinkedPtr) { 1021 const Matcher<linked_ptr<int> > m = NotNull(); 1022 const linked_ptr<int> null_p; 1023 const linked_ptr<int> non_null_p(new int); 1024 1025 EXPECT_FALSE(m.Matches(null_p)); 1026 EXPECT_TRUE(m.Matches(non_null_p)); 1027 } 1028 1029 TEST(NotNullTest, ReferenceToConstLinkedPtr) { 1030 const Matcher<const linked_ptr<double>&> m = NotNull(); 1031 const linked_ptr<double> null_p; 1032 const linked_ptr<double> non_null_p(new double); 1033 1034 EXPECT_FALSE(m.Matches(null_p)); 1035 EXPECT_TRUE(m.Matches(non_null_p)); 1036 } 1037 1038 TEST(NotNullTest, ReferenceToConstScopedPtr) { 1039 const Matcher<const scoped_ptr<double>&> m = NotNull(); 1040 const scoped_ptr<double> null_p; 1041 const scoped_ptr<double> non_null_p(new double); 1042 1043 EXPECT_FALSE(m.Matches(null_p)); 1044 EXPECT_TRUE(m.Matches(non_null_p)); 1045 } 1046 1047 // Tests that NotNull() describes itself properly. 1048 TEST(NotNullTest, CanDescribeSelf) { 1049 Matcher<int*> m = NotNull(); 1050 EXPECT_EQ("isn't NULL", Describe(m)); 1051 } 1052 1053 // Tests that Ref(variable) matches an argument that references 1054 // 'variable'. 1055 TEST(RefTest, MatchesSameVariable) { 1056 int a = 0; 1057 int b = 0; 1058 Matcher<int&> m = Ref(a); 1059 EXPECT_TRUE(m.Matches(a)); 1060 EXPECT_FALSE(m.Matches(b)); 1061 } 1062 1063 // Tests that Ref(variable) describes itself properly. 1064 TEST(RefTest, CanDescribeSelf) { 1065 int n = 5; 1066 Matcher<int&> m = Ref(n); 1067 stringstream ss; 1068 ss << "references the variable @" << &n << " 5"; 1069 EXPECT_EQ(string(ss.str()), Describe(m)); 1070 } 1071 1072 // Test that Ref(non_const_varialbe) can be used as a matcher for a 1073 // const reference. 1074 TEST(RefTest, CanBeUsedAsMatcherForConstReference) { 1075 int a = 0; 1076 int b = 0; 1077 Matcher<const int&> m = Ref(a); 1078 EXPECT_TRUE(m.Matches(a)); 1079 EXPECT_FALSE(m.Matches(b)); 1080 } 1081 1082 // Tests that Ref(variable) is covariant, i.e. Ref(derived) can be 1083 // used wherever Ref(base) can be used (Ref(derived) is a sub-type 1084 // of Ref(base), but not vice versa. 1085 1086 TEST(RefTest, IsCovariant) { 1087 Base base, base2; 1088 Derived derived; 1089 Matcher<const Base&> m1 = Ref(base); 1090 EXPECT_TRUE(m1.Matches(base)); 1091 EXPECT_FALSE(m1.Matches(base2)); 1092 EXPECT_FALSE(m1.Matches(derived)); 1093 1094 m1 = Ref(derived); 1095 EXPECT_TRUE(m1.Matches(derived)); 1096 EXPECT_FALSE(m1.Matches(base)); 1097 EXPECT_FALSE(m1.Matches(base2)); 1098 } 1099 1100 TEST(RefTest, ExplainsResult) { 1101 int n = 0; 1102 EXPECT_THAT(Explain(Matcher<const int&>(Ref(n)), n), 1103 StartsWith("which is located @")); 1104 1105 int m = 0; 1106 EXPECT_THAT(Explain(Matcher<const int&>(Ref(n)), m), 1107 StartsWith("which is located @")); 1108 } 1109 1110 // Tests string comparison matchers. 1111 1112 TEST(StrEqTest, MatchesEqualString) { 1113 Matcher<const char*> m = StrEq(string("Hello")); 1114 EXPECT_TRUE(m.Matches("Hello")); 1115 EXPECT_FALSE(m.Matches("hello")); 1116 EXPECT_FALSE(m.Matches(NULL)); 1117 1118 Matcher<const string&> m2 = StrEq("Hello"); 1119 EXPECT_TRUE(m2.Matches("Hello")); 1120 EXPECT_FALSE(m2.Matches("Hi")); 1121 } 1122 1123 TEST(StrEqTest, CanDescribeSelf) { 1124 Matcher<string> m = StrEq("Hi-\'\"?\\\a\b\f\n\r\t\v\xD3"); 1125 EXPECT_EQ("is equal to \"Hi-\'\\\"?\\\\\\a\\b\\f\\n\\r\\t\\v\\xD3\"", 1126 Describe(m)); 1127 1128 string str("01204500800"); 1129 str[3] = '\0'; 1130 Matcher<string> m2 = StrEq(str); 1131 EXPECT_EQ("is equal to \"012\\04500800\"", Describe(m2)); 1132 str[0] = str[6] = str[7] = str[9] = str[10] = '\0'; 1133 Matcher<string> m3 = StrEq(str); 1134 EXPECT_EQ("is equal to \"\\012\\045\\0\\08\\0\\0\"", Describe(m3)); 1135 } 1136 1137 TEST(StrNeTest, MatchesUnequalString) { 1138 Matcher<const char*> m = StrNe("Hello"); 1139 EXPECT_TRUE(m.Matches("")); 1140 EXPECT_TRUE(m.Matches(NULL)); 1141 EXPECT_FALSE(m.Matches("Hello")); 1142 1143 Matcher<string> m2 = StrNe(string("Hello")); 1144 EXPECT_TRUE(m2.Matches("hello")); 1145 EXPECT_FALSE(m2.Matches("Hello")); 1146 } 1147 1148 TEST(StrNeTest, CanDescribeSelf) { 1149 Matcher<const char*> m = StrNe("Hi"); 1150 EXPECT_EQ("isn't equal to \"Hi\"", Describe(m)); 1151 } 1152 1153 TEST(StrCaseEqTest, MatchesEqualStringIgnoringCase) { 1154 Matcher<const char*> m = StrCaseEq(string("Hello")); 1155 EXPECT_TRUE(m.Matches("Hello")); 1156 EXPECT_TRUE(m.Matches("hello")); 1157 EXPECT_FALSE(m.Matches("Hi")); 1158 EXPECT_FALSE(m.Matches(NULL)); 1159 1160 Matcher<const string&> m2 = StrCaseEq("Hello"); 1161 EXPECT_TRUE(m2.Matches("hello")); 1162 EXPECT_FALSE(m2.Matches("Hi")); 1163 } 1164 1165 TEST(StrCaseEqTest, MatchesEqualStringWith0IgnoringCase) { 1166 string str1("oabocdooeoo"); 1167 string str2("OABOCDOOEOO"); 1168 Matcher<const string&> m0 = StrCaseEq(str1); 1169 EXPECT_FALSE(m0.Matches(str2 + string(1, '\0'))); 1170 1171 str1[3] = str2[3] = '\0'; 1172 Matcher<const string&> m1 = StrCaseEq(str1); 1173 EXPECT_TRUE(m1.Matches(str2)); 1174 1175 str1[0] = str1[6] = str1[7] = str1[10] = '\0'; 1176 str2[0] = str2[6] = str2[7] = str2[10] = '\0'; 1177 Matcher<const string&> m2 = StrCaseEq(str1); 1178 str1[9] = str2[9] = '\0'; 1179 EXPECT_FALSE(m2.Matches(str2)); 1180 1181 Matcher<const string&> m3 = StrCaseEq(str1); 1182 EXPECT_TRUE(m3.Matches(str2)); 1183 1184 EXPECT_FALSE(m3.Matches(str2 + "x")); 1185 str2.append(1, '\0'); 1186 EXPECT_FALSE(m3.Matches(str2)); 1187 EXPECT_FALSE(m3.Matches(string(str2, 0, 9))); 1188 } 1189 1190 TEST(StrCaseEqTest, CanDescribeSelf) { 1191 Matcher<string> m = StrCaseEq("Hi"); 1192 EXPECT_EQ("is equal to (ignoring case) \"Hi\"", Describe(m)); 1193 } 1194 1195 TEST(StrCaseNeTest, MatchesUnequalStringIgnoringCase) { 1196 Matcher<const char*> m = StrCaseNe("Hello"); 1197 EXPECT_TRUE(m.Matches("Hi")); 1198 EXPECT_TRUE(m.Matches(NULL)); 1199 EXPECT_FALSE(m.Matches("Hello")); 1200 EXPECT_FALSE(m.Matches("hello")); 1201 1202 Matcher<string> m2 = StrCaseNe(string("Hello")); 1203 EXPECT_TRUE(m2.Matches("")); 1204 EXPECT_FALSE(m2.Matches("Hello")); 1205 } 1206 1207 TEST(StrCaseNeTest, CanDescribeSelf) { 1208 Matcher<const char*> m = StrCaseNe("Hi"); 1209 EXPECT_EQ("isn't equal to (ignoring case) \"Hi\"", Describe(m)); 1210 } 1211 1212 // Tests that HasSubstr() works for matching string-typed values. 1213 TEST(HasSubstrTest, WorksForStringClasses) { 1214 const Matcher<string> m1 = HasSubstr("foo"); 1215 EXPECT_TRUE(m1.Matches(string("I love food."))); 1216 EXPECT_FALSE(m1.Matches(string("tofo"))); 1217 1218 const Matcher<const std::string&> m2 = HasSubstr("foo"); 1219 EXPECT_TRUE(m2.Matches(std::string("I love food."))); 1220 EXPECT_FALSE(m2.Matches(std::string("tofo"))); 1221 } 1222 1223 // Tests that HasSubstr() works for matching C-string-typed values. 1224 TEST(HasSubstrTest, WorksForCStrings) { 1225 const Matcher<char*> m1 = HasSubstr("foo"); 1226 EXPECT_TRUE(m1.Matches(const_cast<char*>("I love food."))); 1227 EXPECT_FALSE(m1.Matches(const_cast<char*>("tofo"))); 1228 EXPECT_FALSE(m1.Matches(NULL)); 1229 1230 const Matcher<const char*> m2 = HasSubstr("foo"); 1231 EXPECT_TRUE(m2.Matches("I love food.")); 1232 EXPECT_FALSE(m2.Matches("tofo")); 1233 EXPECT_FALSE(m2.Matches(NULL)); 1234 } 1235 1236 // Tests that HasSubstr(s) describes itself properly. 1237 TEST(HasSubstrTest, CanDescribeSelf) { 1238 Matcher<string> m = HasSubstr("foo\n\""); 1239 EXPECT_EQ("has substring \"foo\\n\\\"\"", Describe(m)); 1240 } 1241 1242 TEST(KeyTest, CanDescribeSelf) { 1243 Matcher<const pair<std::string, int>&> m = Key("foo"); 1244 EXPECT_EQ("has a key that is equal to \"foo\"", Describe(m)); 1245 EXPECT_EQ("doesn't have a key that is equal to \"foo\"", DescribeNegation(m)); 1246 } 1247 1248 TEST(KeyTest, ExplainsResult) { 1249 Matcher<pair<int, bool> > m = Key(GreaterThan(10)); 1250 EXPECT_EQ("whose first field is a value which is 5 less than 10", 1251 Explain(m, make_pair(5, true))); 1252 EXPECT_EQ("whose first field is a value which is 5 more than 10", 1253 Explain(m, make_pair(15, true))); 1254 } 1255 1256 TEST(KeyTest, MatchesCorrectly) { 1257 pair<int, std::string> p(25, "foo"); 1258 EXPECT_THAT(p, Key(25)); 1259 EXPECT_THAT(p, Not(Key(42))); 1260 EXPECT_THAT(p, Key(Ge(20))); 1261 EXPECT_THAT(p, Not(Key(Lt(25)))); 1262 } 1263 1264 TEST(KeyTest, SafelyCastsInnerMatcher) { 1265 Matcher<int> is_positive = Gt(0); 1266 Matcher<int> is_negative = Lt(0); 1267 pair<char, bool> p('a', true); 1268 EXPECT_THAT(p, Key(is_positive)); 1269 EXPECT_THAT(p, Not(Key(is_negative))); 1270 } 1271 1272 TEST(KeyTest, InsideContainsUsingMap) { 1273 map<int, char> container; 1274 container.insert(make_pair(1, 'a')); 1275 container.insert(make_pair(2, 'b')); 1276 container.insert(make_pair(4, 'c')); 1277 EXPECT_THAT(container, Contains(Key(1))); 1278 EXPECT_THAT(container, Not(Contains(Key(3)))); 1279 } 1280 1281 TEST(KeyTest, InsideContainsUsingMultimap) { 1282 multimap<int, char> container; 1283 container.insert(make_pair(1, 'a')); 1284 container.insert(make_pair(2, 'b')); 1285 container.insert(make_pair(4, 'c')); 1286 1287 EXPECT_THAT(container, Not(Contains(Key(25)))); 1288 container.insert(make_pair(25, 'd')); 1289 EXPECT_THAT(container, Contains(Key(25))); 1290 container.insert(make_pair(25, 'e')); 1291 EXPECT_THAT(container, Contains(Key(25))); 1292 1293 EXPECT_THAT(container, Contains(Key(1))); 1294 EXPECT_THAT(container, Not(Contains(Key(3)))); 1295 } 1296 1297 TEST(PairTest, Typing) { 1298 // Test verifies the following type conversions can be compiled. 1299 Matcher<const pair<const char*, int>&> m1 = Pair("foo", 42); 1300 Matcher<const pair<const char*, int> > m2 = Pair("foo", 42); 1301 Matcher<pair<const char*, int> > m3 = Pair("foo", 42); 1302 1303 Matcher<pair<int, const std::string> > m4 = Pair(25, "42"); 1304 Matcher<pair<const std::string, int> > m5 = Pair("25", 42); 1305 } 1306 1307 TEST(PairTest, CanDescribeSelf) { 1308 Matcher<const pair<std::string, int>&> m1 = Pair("foo", 42); 1309 EXPECT_EQ("has a first field that is equal to \"foo\"" 1310 ", and has a second field that is equal to 42", 1311 Describe(m1)); 1312 EXPECT_EQ("has a first field that isn't equal to \"foo\"" 1313 ", or has a second field that isn't equal to 42", 1314 DescribeNegation(m1)); 1315 // Double and triple negation (1 or 2 times not and description of negation). 1316 Matcher<const pair<int, int>&> m2 = Not(Pair(Not(13), 42)); 1317 EXPECT_EQ("has a first field that isn't equal to 13" 1318 ", and has a second field that is equal to 42", 1319 DescribeNegation(m2)); 1320 } 1321 1322 TEST(PairTest, CanExplainMatchResultTo) { 1323 // If neither field matches, Pair() should explain about the first 1324 // field. 1325 const Matcher<pair<int, int> > m = Pair(GreaterThan(0), GreaterThan(0)); 1326 EXPECT_EQ("whose first field does not match, which is 1 less than 0", 1327 Explain(m, make_pair(-1, -2))); 1328 1329 // If the first field matches but the second doesn't, Pair() should 1330 // explain about the second field. 1331 EXPECT_EQ("whose second field does not match, which is 2 less than 0", 1332 Explain(m, make_pair(1, -2))); 1333 1334 // If the first field doesn't match but the second does, Pair() 1335 // should explain about the first field. 1336 EXPECT_EQ("whose first field does not match, which is 1 less than 0", 1337 Explain(m, make_pair(-1, 2))); 1338 1339 // If both fields match, Pair() should explain about them both. 1340 EXPECT_EQ("whose both fields match, where the first field is a value " 1341 "which is 1 more than 0, and the second field is a value " 1342 "which is 2 more than 0", 1343 Explain(m, make_pair(1, 2))); 1344 1345 // If only the first match has an explanation, only this explanation should 1346 // be printed. 1347 const Matcher<pair<int, int> > explain_first = Pair(GreaterThan(0), 0); 1348 EXPECT_EQ("whose both fields match, where the first field is a value " 1349 "which is 1 more than 0", 1350 Explain(explain_first, make_pair(1, 0))); 1351 1352 // If only the second match has an explanation, only this explanation should 1353 // be printed. 1354 const Matcher<pair<int, int> > explain_second = Pair(0, GreaterThan(0)); 1355 EXPECT_EQ("whose both fields match, where the second field is a value " 1356 "which is 1 more than 0", 1357 Explain(explain_second, make_pair(0, 1))); 1358 } 1359 1360 TEST(PairTest, MatchesCorrectly) { 1361 pair<int, std::string> p(25, "foo"); 1362 1363 // Both fields match. 1364 EXPECT_THAT(p, Pair(25, "foo")); 1365 EXPECT_THAT(p, Pair(Ge(20), HasSubstr("o"))); 1366 1367 // 'first' doesnt' match, but 'second' matches. 1368 EXPECT_THAT(p, Not(Pair(42, "foo"))); 1369 EXPECT_THAT(p, Not(Pair(Lt(25), "foo"))); 1370 1371 // 'first' matches, but 'second' doesn't match. 1372 EXPECT_THAT(p, Not(Pair(25, "bar"))); 1373 EXPECT_THAT(p, Not(Pair(25, Not("foo")))); 1374 1375 // Neither field matches. 1376 EXPECT_THAT(p, Not(Pair(13, "bar"))); 1377 EXPECT_THAT(p, Not(Pair(Lt(13), HasSubstr("a")))); 1378 } 1379 1380 TEST(PairTest, SafelyCastsInnerMatchers) { 1381 Matcher<int> is_positive = Gt(0); 1382 Matcher<int> is_negative = Lt(0); 1383 pair<char, bool> p('a', true); 1384 EXPECT_THAT(p, Pair(is_positive, _)); 1385 EXPECT_THAT(p, Not(Pair(is_negative, _))); 1386 EXPECT_THAT(p, Pair(_, is_positive)); 1387 EXPECT_THAT(p, Not(Pair(_, is_negative))); 1388 } 1389 1390 TEST(PairTest, InsideContainsUsingMap) { 1391 map<int, char> container; 1392 container.insert(make_pair(1, 'a')); 1393 container.insert(make_pair(2, 'b')); 1394 container.insert(make_pair(4, 'c')); 1395 EXPECT_THAT(container, Contains(Pair(1, 'a'))); 1396 EXPECT_THAT(container, Contains(Pair(1, _))); 1397 EXPECT_THAT(container, Contains(Pair(_, 'a'))); 1398 EXPECT_THAT(container, Not(Contains(Pair(3, _)))); 1399 } 1400 1401 // Tests StartsWith(s). 1402 1403 TEST(StartsWithTest, MatchesStringWithGivenPrefix) { 1404 const Matcher<const char*> m1 = StartsWith(string("")); 1405 EXPECT_TRUE(m1.Matches("Hi")); 1406 EXPECT_TRUE(m1.Matches("")); 1407 EXPECT_FALSE(m1.Matches(NULL)); 1408 1409 const Matcher<const string&> m2 = StartsWith("Hi"); 1410 EXPECT_TRUE(m2.Matches("Hi")); 1411 EXPECT_TRUE(m2.Matches("Hi Hi!")); 1412 EXPECT_TRUE(m2.Matches("High")); 1413 EXPECT_FALSE(m2.Matches("H")); 1414 EXPECT_FALSE(m2.Matches(" Hi")); 1415 } 1416 1417 TEST(StartsWithTest, CanDescribeSelf) { 1418 Matcher<const std::string> m = StartsWith("Hi"); 1419 EXPECT_EQ("starts with \"Hi\"", Describe(m)); 1420 } 1421 1422 // Tests EndsWith(s). 1423 1424 TEST(EndsWithTest, MatchesStringWithGivenSuffix) { 1425 const Matcher<const char*> m1 = EndsWith(""); 1426 EXPECT_TRUE(m1.Matches("Hi")); 1427 EXPECT_TRUE(m1.Matches("")); 1428 EXPECT_FALSE(m1.Matches(NULL)); 1429 1430 const Matcher<const string&> m2 = EndsWith(string("Hi")); 1431 EXPECT_TRUE(m2.Matches("Hi")); 1432 EXPECT_TRUE(m2.Matches("Wow Hi Hi")); 1433 EXPECT_TRUE(m2.Matches("Super Hi")); 1434 EXPECT_FALSE(m2.Matches("i")); 1435 EXPECT_FALSE(m2.Matches("Hi ")); 1436 } 1437 1438 TEST(EndsWithTest, CanDescribeSelf) { 1439 Matcher<const std::string> m = EndsWith("Hi"); 1440 EXPECT_EQ("ends with \"Hi\"", Describe(m)); 1441 } 1442 1443 // Tests MatchesRegex(). 1444 1445 TEST(MatchesRegexTest, MatchesStringMatchingGivenRegex) { 1446 const Matcher<const char*> m1 = MatchesRegex("a.*z"); 1447 EXPECT_TRUE(m1.Matches("az")); 1448 EXPECT_TRUE(m1.Matches("abcz")); 1449 EXPECT_FALSE(m1.Matches(NULL)); 1450 1451 const Matcher<const string&> m2 = MatchesRegex(new RE("a.*z")); 1452 EXPECT_TRUE(m2.Matches("azbz")); 1453 EXPECT_FALSE(m2.Matches("az1")); 1454 EXPECT_FALSE(m2.Matches("1az")); 1455 } 1456 1457 TEST(MatchesRegexTest, CanDescribeSelf) { 1458 Matcher<const std::string> m1 = MatchesRegex(string("Hi.*")); 1459 EXPECT_EQ("matches regular expression \"Hi.*\"", Describe(m1)); 1460 1461 Matcher<const char*> m2 = MatchesRegex(new RE("a.*")); 1462 EXPECT_EQ("matches regular expression \"a.*\"", Describe(m2)); 1463 } 1464 1465 // Tests ContainsRegex(). 1466 1467 TEST(ContainsRegexTest, MatchesStringContainingGivenRegex) { 1468 const Matcher<const char*> m1 = ContainsRegex(string("a.*z")); 1469 EXPECT_TRUE(m1.Matches("az")); 1470 EXPECT_TRUE(m1.Matches("0abcz1")); 1471 EXPECT_FALSE(m1.Matches(NULL)); 1472 1473 const Matcher<const string&> m2 = ContainsRegex(new RE("a.*z")); 1474 EXPECT_TRUE(m2.Matches("azbz")); 1475 EXPECT_TRUE(m2.Matches("az1")); 1476 EXPECT_FALSE(m2.Matches("1a")); 1477 } 1478 1479 TEST(ContainsRegexTest, CanDescribeSelf) { 1480 Matcher<const std::string> m1 = ContainsRegex("Hi.*"); 1481 EXPECT_EQ("contains regular expression \"Hi.*\"", Describe(m1)); 1482 1483 Matcher<const char*> m2 = ContainsRegex(new RE("a.*")); 1484 EXPECT_EQ("contains regular expression \"a.*\"", Describe(m2)); 1485 } 1486 1487 // Tests for wide strings. 1488 #if GTEST_HAS_STD_WSTRING 1489 TEST(StdWideStrEqTest, MatchesEqual) { 1490 Matcher<const wchar_t*> m = StrEq(::std::wstring(L"Hello")); 1491 EXPECT_TRUE(m.Matches(L"Hello")); 1492 EXPECT_FALSE(m.Matches(L"hello")); 1493 EXPECT_FALSE(m.Matches(NULL)); 1494 1495 Matcher<const ::std::wstring&> m2 = StrEq(L"Hello"); 1496 EXPECT_TRUE(m2.Matches(L"Hello")); 1497 EXPECT_FALSE(m2.Matches(L"Hi")); 1498 1499 Matcher<const ::std::wstring&> m3 = StrEq(L"\xD3\x576\x8D3\xC74D"); 1500 EXPECT_TRUE(m3.Matches(L"\xD3\x576\x8D3\xC74D")); 1501 EXPECT_FALSE(m3.Matches(L"\xD3\x576\x8D3\xC74E")); 1502 1503 ::std::wstring str(L"01204500800"); 1504 str[3] = L'\0'; 1505 Matcher<const ::std::wstring&> m4 = StrEq(str); 1506 EXPECT_TRUE(m4.Matches(str)); 1507 str[0] = str[6] = str[7] = str[9] = str[10] = L'\0'; 1508 Matcher<const ::std::wstring&> m5 = StrEq(str); 1509 EXPECT_TRUE(m5.Matches(str)); 1510 } 1511 1512 TEST(StdWideStrEqTest, CanDescribeSelf) { 1513 Matcher< ::std::wstring> m = StrEq(L"Hi-\'\"?\\\a\b\f\n\r\t\v"); 1514 EXPECT_EQ("is equal to L\"Hi-\'\\\"?\\\\\\a\\b\\f\\n\\r\\t\\v\"", 1515 Describe(m)); 1516 1517 Matcher< ::std::wstring> m2 = StrEq(L"\xD3\x576\x8D3\xC74D"); 1518 EXPECT_EQ("is equal to L\"\\xD3\\x576\\x8D3\\xC74D\"", 1519 Describe(m2)); 1520 1521 ::std::wstring str(L"01204500800"); 1522 str[3] = L'\0'; 1523 Matcher<const ::std::wstring&> m4 = StrEq(str); 1524 EXPECT_EQ("is equal to L\"012\\04500800\"", Describe(m4)); 1525 str[0] = str[6] = str[7] = str[9] = str[10] = L'\0'; 1526 Matcher<const ::std::wstring&> m5 = StrEq(str); 1527 EXPECT_EQ("is equal to L\"\\012\\045\\0\\08\\0\\0\"", Describe(m5)); 1528 } 1529 1530 TEST(StdWideStrNeTest, MatchesUnequalString) { 1531 Matcher<const wchar_t*> m = StrNe(L"Hello"); 1532 EXPECT_TRUE(m.Matches(L"")); 1533 EXPECT_TRUE(m.Matches(NULL)); 1534 EXPECT_FALSE(m.Matches(L"Hello")); 1535 1536 Matcher< ::std::wstring> m2 = StrNe(::std::wstring(L"Hello")); 1537 EXPECT_TRUE(m2.Matches(L"hello")); 1538 EXPECT_FALSE(m2.Matches(L"Hello")); 1539 } 1540 1541 TEST(StdWideStrNeTest, CanDescribeSelf) { 1542 Matcher<const wchar_t*> m = StrNe(L"Hi"); 1543 EXPECT_EQ("isn't equal to L\"Hi\"", Describe(m)); 1544 } 1545 1546 TEST(StdWideStrCaseEqTest, MatchesEqualStringIgnoringCase) { 1547 Matcher<const wchar_t*> m = StrCaseEq(::std::wstring(L"Hello")); 1548 EXPECT_TRUE(m.Matches(L"Hello")); 1549 EXPECT_TRUE(m.Matches(L"hello")); 1550 EXPECT_FALSE(m.Matches(L"Hi")); 1551 EXPECT_FALSE(m.Matches(NULL)); 1552 1553 Matcher<const ::std::wstring&> m2 = StrCaseEq(L"Hello"); 1554 EXPECT_TRUE(m2.Matches(L"hello")); 1555 EXPECT_FALSE(m2.Matches(L"Hi")); 1556 } 1557 1558 TEST(StdWideStrCaseEqTest, MatchesEqualStringWith0IgnoringCase) { 1559 ::std::wstring str1(L"oabocdooeoo"); 1560 ::std::wstring str2(L"OABOCDOOEOO"); 1561 Matcher<const ::std::wstring&> m0 = StrCaseEq(str1); 1562 EXPECT_FALSE(m0.Matches(str2 + ::std::wstring(1, L'\0'))); 1563 1564 str1[3] = str2[3] = L'\0'; 1565 Matcher<const ::std::wstring&> m1 = StrCaseEq(str1); 1566 EXPECT_TRUE(m1.Matches(str2)); 1567 1568 str1[0] = str1[6] = str1[7] = str1[10] = L'\0'; 1569 str2[0] = str2[6] = str2[7] = str2[10] = L'\0'; 1570 Matcher<const ::std::wstring&> m2 = StrCaseEq(str1); 1571 str1[9] = str2[9] = L'\0'; 1572 EXPECT_FALSE(m2.Matches(str2)); 1573 1574 Matcher<const ::std::wstring&> m3 = StrCaseEq(str1); 1575 EXPECT_TRUE(m3.Matches(str2)); 1576 1577 EXPECT_FALSE(m3.Matches(str2 + L"x")); 1578 str2.append(1, L'\0'); 1579 EXPECT_FALSE(m3.Matches(str2)); 1580 EXPECT_FALSE(m3.Matches(::std::wstring(str2, 0, 9))); 1581 } 1582 1583 TEST(StdWideStrCaseEqTest, CanDescribeSelf) { 1584 Matcher< ::std::wstring> m = StrCaseEq(L"Hi"); 1585 EXPECT_EQ("is equal to (ignoring case) L\"Hi\"", Describe(m)); 1586 } 1587 1588 TEST(StdWideStrCaseNeTest, MatchesUnequalStringIgnoringCase) { 1589 Matcher<const wchar_t*> m = StrCaseNe(L"Hello"); 1590 EXPECT_TRUE(m.Matches(L"Hi")); 1591 EXPECT_TRUE(m.Matches(NULL)); 1592 EXPECT_FALSE(m.Matches(L"Hello")); 1593 EXPECT_FALSE(m.Matches(L"hello")); 1594 1595 Matcher< ::std::wstring> m2 = StrCaseNe(::std::wstring(L"Hello")); 1596 EXPECT_TRUE(m2.Matches(L"")); 1597 EXPECT_FALSE(m2.Matches(L"Hello")); 1598 } 1599 1600 TEST(StdWideStrCaseNeTest, CanDescribeSelf) { 1601 Matcher<const wchar_t*> m = StrCaseNe(L"Hi"); 1602 EXPECT_EQ("isn't equal to (ignoring case) L\"Hi\"", Describe(m)); 1603 } 1604 1605 // Tests that HasSubstr() works for matching wstring-typed values. 1606 TEST(StdWideHasSubstrTest, WorksForStringClasses) { 1607 const Matcher< ::std::wstring> m1 = HasSubstr(L"foo"); 1608 EXPECT_TRUE(m1.Matches(::std::wstring(L"I love food."))); 1609 EXPECT_FALSE(m1.Matches(::std::wstring(L"tofo"))); 1610 1611 const Matcher<const ::std::wstring&> m2 = HasSubstr(L"foo"); 1612 EXPECT_TRUE(m2.Matches(::std::wstring(L"I love food."))); 1613 EXPECT_FALSE(m2.Matches(::std::wstring(L"tofo"))); 1614 } 1615 1616 // Tests that HasSubstr() works for matching C-wide-string-typed values. 1617 TEST(StdWideHasSubstrTest, WorksForCStrings) { 1618 const Matcher<wchar_t*> m1 = HasSubstr(L"foo"); 1619 EXPECT_TRUE(m1.Matches(const_cast<wchar_t*>(L"I love food."))); 1620 EXPECT_FALSE(m1.Matches(const_cast<wchar_t*>(L"tofo"))); 1621 EXPECT_FALSE(m1.Matches(NULL)); 1622 1623 const Matcher<const wchar_t*> m2 = HasSubstr(L"foo"); 1624 EXPECT_TRUE(m2.Matches(L"I love food.")); 1625 EXPECT_FALSE(m2.Matches(L"tofo")); 1626 EXPECT_FALSE(m2.Matches(NULL)); 1627 } 1628 1629 // Tests that HasSubstr(s) describes itself properly. 1630 TEST(StdWideHasSubstrTest, CanDescribeSelf) { 1631 Matcher< ::std::wstring> m = HasSubstr(L"foo\n\""); 1632 EXPECT_EQ("has substring L\"foo\\n\\\"\"", Describe(m)); 1633 } 1634 1635 // Tests StartsWith(s). 1636 1637 TEST(StdWideStartsWithTest, MatchesStringWithGivenPrefix) { 1638 const Matcher<const wchar_t*> m1 = StartsWith(::std::wstring(L"")); 1639 EXPECT_TRUE(m1.Matches(L"Hi")); 1640 EXPECT_TRUE(m1.Matches(L"")); 1641 EXPECT_FALSE(m1.Matches(NULL)); 1642 1643 const Matcher<const ::std::wstring&> m2 = StartsWith(L"Hi"); 1644 EXPECT_TRUE(m2.Matches(L"Hi")); 1645 EXPECT_TRUE(m2.Matches(L"Hi Hi!")); 1646 EXPECT_TRUE(m2.Matches(L"High")); 1647 EXPECT_FALSE(m2.Matches(L"H")); 1648 EXPECT_FALSE(m2.Matches(L" Hi")); 1649 } 1650 1651 TEST(StdWideStartsWithTest, CanDescribeSelf) { 1652 Matcher<const ::std::wstring> m = StartsWith(L"Hi"); 1653 EXPECT_EQ("starts with L\"Hi\"", Describe(m)); 1654 } 1655 1656 // Tests EndsWith(s). 1657 1658 TEST(StdWideEndsWithTest, MatchesStringWithGivenSuffix) { 1659 const Matcher<const wchar_t*> m1 = EndsWith(L""); 1660 EXPECT_TRUE(m1.Matches(L"Hi")); 1661 EXPECT_TRUE(m1.Matches(L"")); 1662 EXPECT_FALSE(m1.Matches(NULL)); 1663 1664 const Matcher<const ::std::wstring&> m2 = EndsWith(::std::wstring(L"Hi")); 1665 EXPECT_TRUE(m2.Matches(L"Hi")); 1666 EXPECT_TRUE(m2.Matches(L"Wow Hi Hi")); 1667 EXPECT_TRUE(m2.Matches(L"Super Hi")); 1668 EXPECT_FALSE(m2.Matches(L"i")); 1669 EXPECT_FALSE(m2.Matches(L"Hi ")); 1670 } 1671 1672 TEST(StdWideEndsWithTest, CanDescribeSelf) { 1673 Matcher<const ::std::wstring> m = EndsWith(L"Hi"); 1674 EXPECT_EQ("ends with L\"Hi\"", Describe(m)); 1675 } 1676 1677 #endif // GTEST_HAS_STD_WSTRING 1678 1679 #if GTEST_HAS_GLOBAL_WSTRING 1680 TEST(GlobalWideStrEqTest, MatchesEqual) { 1681 Matcher<const wchar_t*> m = StrEq(::wstring(L"Hello")); 1682 EXPECT_TRUE(m.Matches(L"Hello")); 1683 EXPECT_FALSE(m.Matches(L"hello")); 1684 EXPECT_FALSE(m.Matches(NULL)); 1685 1686 Matcher<const ::wstring&> m2 = StrEq(L"Hello"); 1687 EXPECT_TRUE(m2.Matches(L"Hello")); 1688 EXPECT_FALSE(m2.Matches(L"Hi")); 1689 1690 Matcher<const ::wstring&> m3 = StrEq(L"\xD3\x576\x8D3\xC74D"); 1691 EXPECT_TRUE(m3.Matches(L"\xD3\x576\x8D3\xC74D")); 1692 EXPECT_FALSE(m3.Matches(L"\xD3\x576\x8D3\xC74E")); 1693 1694 ::wstring str(L"01204500800"); 1695 str[3] = L'\0'; 1696 Matcher<const ::wstring&> m4 = StrEq(str); 1697 EXPECT_TRUE(m4.Matches(str)); 1698 str[0] = str[6] = str[7] = str[9] = str[10] = L'\0'; 1699 Matcher<const ::wstring&> m5 = StrEq(str); 1700 EXPECT_TRUE(m5.Matches(str)); 1701 } 1702 1703 TEST(GlobalWideStrEqTest, CanDescribeSelf) { 1704 Matcher< ::wstring> m = StrEq(L"Hi-\'\"?\\\a\b\f\n\r\t\v"); 1705 EXPECT_EQ("is equal to L\"Hi-\'\\\"?\\\\\\a\\b\\f\\n\\r\\t\\v\"", 1706 Describe(m)); 1707 1708 Matcher< ::wstring> m2 = StrEq(L"\xD3\x576\x8D3\xC74D"); 1709 EXPECT_EQ("is equal to L\"\\xD3\\x576\\x8D3\\xC74D\"", 1710 Describe(m2)); 1711 1712 ::wstring str(L"01204500800"); 1713 str[3] = L'\0'; 1714 Matcher<const ::wstring&> m4 = StrEq(str); 1715 EXPECT_EQ("is equal to L\"012\\04500800\"", Describe(m4)); 1716 str[0] = str[6] = str[7] = str[9] = str[10] = L'\0'; 1717 Matcher<const ::wstring&> m5 = StrEq(str); 1718 EXPECT_EQ("is equal to L\"\\012\\045\\0\\08\\0\\0\"", Describe(m5)); 1719 } 1720 1721 TEST(GlobalWideStrNeTest, MatchesUnequalString) { 1722 Matcher<const wchar_t*> m = StrNe(L"Hello"); 1723 EXPECT_TRUE(m.Matches(L"")); 1724 EXPECT_TRUE(m.Matches(NULL)); 1725 EXPECT_FALSE(m.Matches(L"Hello")); 1726 1727 Matcher< ::wstring> m2 = StrNe(::wstring(L"Hello")); 1728 EXPECT_TRUE(m2.Matches(L"hello")); 1729 EXPECT_FALSE(m2.Matches(L"Hello")); 1730 } 1731 1732 TEST(GlobalWideStrNeTest, CanDescribeSelf) { 1733 Matcher<const wchar_t*> m = StrNe(L"Hi"); 1734 EXPECT_EQ("isn't equal to L\"Hi\"", Describe(m)); 1735 } 1736 1737 TEST(GlobalWideStrCaseEqTest, MatchesEqualStringIgnoringCase) { 1738 Matcher<const wchar_t*> m = StrCaseEq(::wstring(L"Hello")); 1739 EXPECT_TRUE(m.Matches(L"Hello")); 1740 EXPECT_TRUE(m.Matches(L"hello")); 1741 EXPECT_FALSE(m.Matches(L"Hi")); 1742 EXPECT_FALSE(m.Matches(NULL)); 1743 1744 Matcher<const ::wstring&> m2 = StrCaseEq(L"Hello"); 1745 EXPECT_TRUE(m2.Matches(L"hello")); 1746 EXPECT_FALSE(m2.Matches(L"Hi")); 1747 } 1748 1749 TEST(GlobalWideStrCaseEqTest, MatchesEqualStringWith0IgnoringCase) { 1750 ::wstring str1(L"oabocdooeoo"); 1751 ::wstring str2(L"OABOCDOOEOO"); 1752 Matcher<const ::wstring&> m0 = StrCaseEq(str1); 1753 EXPECT_FALSE(m0.Matches(str2 + ::wstring(1, L'\0'))); 1754 1755 str1[3] = str2[3] = L'\0'; 1756 Matcher<const ::wstring&> m1 = StrCaseEq(str1); 1757 EXPECT_TRUE(m1.Matches(str2)); 1758 1759 str1[0] = str1[6] = str1[7] = str1[10] = L'\0'; 1760 str2[0] = str2[6] = str2[7] = str2[10] = L'\0'; 1761 Matcher<const ::wstring&> m2 = StrCaseEq(str1); 1762 str1[9] = str2[9] = L'\0'; 1763 EXPECT_FALSE(m2.Matches(str2)); 1764 1765 Matcher<const ::wstring&> m3 = StrCaseEq(str1); 1766 EXPECT_TRUE(m3.Matches(str2)); 1767 1768 EXPECT_FALSE(m3.Matches(str2 + L"x")); 1769 str2.append(1, L'\0'); 1770 EXPECT_FALSE(m3.Matches(str2)); 1771 EXPECT_FALSE(m3.Matches(::wstring(str2, 0, 9))); 1772 } 1773 1774 TEST(GlobalWideStrCaseEqTest, CanDescribeSelf) { 1775 Matcher< ::wstring> m = StrCaseEq(L"Hi"); 1776 EXPECT_EQ("is equal to (ignoring case) L\"Hi\"", Describe(m)); 1777 } 1778 1779 TEST(GlobalWideStrCaseNeTest, MatchesUnequalStringIgnoringCase) { 1780 Matcher<const wchar_t*> m = StrCaseNe(L"Hello"); 1781 EXPECT_TRUE(m.Matches(L"Hi")); 1782 EXPECT_TRUE(m.Matches(NULL)); 1783 EXPECT_FALSE(m.Matches(L"Hello")); 1784 EXPECT_FALSE(m.Matches(L"hello")); 1785 1786 Matcher< ::wstring> m2 = StrCaseNe(::wstring(L"Hello")); 1787 EXPECT_TRUE(m2.Matches(L"")); 1788 EXPECT_FALSE(m2.Matches(L"Hello")); 1789 } 1790 1791 TEST(GlobalWideStrCaseNeTest, CanDescribeSelf) { 1792 Matcher<const wchar_t*> m = StrCaseNe(L"Hi"); 1793 EXPECT_EQ("isn't equal to (ignoring case) L\"Hi\"", Describe(m)); 1794 } 1795 1796 // Tests that HasSubstr() works for matching wstring-typed values. 1797 TEST(GlobalWideHasSubstrTest, WorksForStringClasses) { 1798 const Matcher< ::wstring> m1 = HasSubstr(L"foo"); 1799 EXPECT_TRUE(m1.Matches(::wstring(L"I love food."))); 1800 EXPECT_FALSE(m1.Matches(::wstring(L"tofo"))); 1801 1802 const Matcher<const ::wstring&> m2 = HasSubstr(L"foo"); 1803 EXPECT_TRUE(m2.Matches(::wstring(L"I love food."))); 1804 EXPECT_FALSE(m2.Matches(::wstring(L"tofo"))); 1805 } 1806 1807 // Tests that HasSubstr() works for matching C-wide-string-typed values. 1808 TEST(GlobalWideHasSubstrTest, WorksForCStrings) { 1809 const Matcher<wchar_t*> m1 = HasSubstr(L"foo"); 1810 EXPECT_TRUE(m1.Matches(const_cast<wchar_t*>(L"I love food."))); 1811 EXPECT_FALSE(m1.Matches(const_cast<wchar_t*>(L"tofo"))); 1812 EXPECT_FALSE(m1.Matches(NULL)); 1813 1814 const Matcher<const wchar_t*> m2 = HasSubstr(L"foo"); 1815 EXPECT_TRUE(m2.Matches(L"I love food.")); 1816 EXPECT_FALSE(m2.Matches(L"tofo")); 1817 EXPECT_FALSE(m2.Matches(NULL)); 1818 } 1819 1820 // Tests that HasSubstr(s) describes itself properly. 1821 TEST(GlobalWideHasSubstrTest, CanDescribeSelf) { 1822 Matcher< ::wstring> m = HasSubstr(L"foo\n\""); 1823 EXPECT_EQ("has substring L\"foo\\n\\\"\"", Describe(m)); 1824 } 1825 1826 // Tests StartsWith(s). 1827 1828 TEST(GlobalWideStartsWithTest, MatchesStringWithGivenPrefix) { 1829 const Matcher<const wchar_t*> m1 = StartsWith(::wstring(L"")); 1830 EXPECT_TRUE(m1.Matches(L"Hi")); 1831 EXPECT_TRUE(m1.Matches(L"")); 1832 EXPECT_FALSE(m1.Matches(NULL)); 1833 1834 const Matcher<const ::wstring&> m2 = StartsWith(L"Hi"); 1835 EXPECT_TRUE(m2.Matches(L"Hi")); 1836 EXPECT_TRUE(m2.Matches(L"Hi Hi!")); 1837 EXPECT_TRUE(m2.Matches(L"High")); 1838 EXPECT_FALSE(m2.Matches(L"H")); 1839 EXPECT_FALSE(m2.Matches(L" Hi")); 1840 } 1841 1842 TEST(GlobalWideStartsWithTest, CanDescribeSelf) { 1843 Matcher<const ::wstring> m = StartsWith(L"Hi"); 1844 EXPECT_EQ("starts with L\"Hi\"", Describe(m)); 1845 } 1846 1847 // Tests EndsWith(s). 1848 1849 TEST(GlobalWideEndsWithTest, MatchesStringWithGivenSuffix) { 1850 const Matcher<const wchar_t*> m1 = EndsWith(L""); 1851 EXPECT_TRUE(m1.Matches(L"Hi")); 1852 EXPECT_TRUE(m1.Matches(L"")); 1853 EXPECT_FALSE(m1.Matches(NULL)); 1854 1855 const Matcher<const ::wstring&> m2 = EndsWith(::wstring(L"Hi")); 1856 EXPECT_TRUE(m2.Matches(L"Hi")); 1857 EXPECT_TRUE(m2.Matches(L"Wow Hi Hi")); 1858 EXPECT_TRUE(m2.Matches(L"Super Hi")); 1859 EXPECT_FALSE(m2.Matches(L"i")); 1860 EXPECT_FALSE(m2.Matches(L"Hi ")); 1861 } 1862 1863 TEST(GlobalWideEndsWithTest, CanDescribeSelf) { 1864 Matcher<const ::wstring> m = EndsWith(L"Hi"); 1865 EXPECT_EQ("ends with L\"Hi\"", Describe(m)); 1866 } 1867 1868 #endif // GTEST_HAS_GLOBAL_WSTRING 1869 1870 1871 typedef ::std::tr1::tuple<long, int> Tuple2; // NOLINT 1872 1873 // Tests that Eq() matches a 2-tuple where the first field == the 1874 // second field. 1875 TEST(Eq2Test, MatchesEqualArguments) { 1876 Matcher<const Tuple2&> m = Eq(); 1877 EXPECT_TRUE(m.Matches(Tuple2(5L, 5))); 1878 EXPECT_FALSE(m.Matches(Tuple2(5L, 6))); 1879 } 1880 1881 // Tests that Eq() describes itself properly. 1882 TEST(Eq2Test, CanDescribeSelf) { 1883 Matcher<const Tuple2&> m = Eq(); 1884 EXPECT_EQ("are an equal pair", Describe(m)); 1885 } 1886 1887 // Tests that Ge() matches a 2-tuple where the first field >= the 1888 // second field. 1889 TEST(Ge2Test, MatchesGreaterThanOrEqualArguments) { 1890 Matcher<const Tuple2&> m = Ge(); 1891 EXPECT_TRUE(m.Matches(Tuple2(5L, 4))); 1892 EXPECT_TRUE(m.Matches(Tuple2(5L, 5))); 1893 EXPECT_FALSE(m.Matches(Tuple2(5L, 6))); 1894 } 1895 1896 // Tests that Ge() describes itself properly. 1897 TEST(Ge2Test, CanDescribeSelf) { 1898 Matcher<const Tuple2&> m = Ge(); 1899 EXPECT_EQ("are a pair where the first >= the second", Describe(m)); 1900 } 1901 1902 // Tests that Gt() matches a 2-tuple where the first field > the 1903 // second field. 1904 TEST(Gt2Test, MatchesGreaterThanArguments) { 1905 Matcher<const Tuple2&> m = Gt(); 1906 EXPECT_TRUE(m.Matches(Tuple2(5L, 4))); 1907 EXPECT_FALSE(m.Matches(Tuple2(5L, 5))); 1908 EXPECT_FALSE(m.Matches(Tuple2(5L, 6))); 1909 } 1910 1911 // Tests that Gt() describes itself properly. 1912 TEST(Gt2Test, CanDescribeSelf) { 1913 Matcher<const Tuple2&> m = Gt(); 1914 EXPECT_EQ("are a pair where the first > the second", Describe(m)); 1915 } 1916 1917 // Tests that Le() matches a 2-tuple where the first field <= the 1918 // second field. 1919 TEST(Le2Test, MatchesLessThanOrEqualArguments) { 1920 Matcher<const Tuple2&> m = Le(); 1921 EXPECT_TRUE(m.Matches(Tuple2(5L, 6))); 1922 EXPECT_TRUE(m.Matches(Tuple2(5L, 5))); 1923 EXPECT_FALSE(m.Matches(Tuple2(5L, 4))); 1924 } 1925 1926 // Tests that Le() describes itself properly. 1927 TEST(Le2Test, CanDescribeSelf) { 1928 Matcher<const Tuple2&> m = Le(); 1929 EXPECT_EQ("are a pair where the first <= the second", Describe(m)); 1930 } 1931 1932 // Tests that Lt() matches a 2-tuple where the first field < the 1933 // second field. 1934 TEST(Lt2Test, MatchesLessThanArguments) { 1935 Matcher<const Tuple2&> m = Lt(); 1936 EXPECT_TRUE(m.Matches(Tuple2(5L, 6))); 1937 EXPECT_FALSE(m.Matches(Tuple2(5L, 5))); 1938 EXPECT_FALSE(m.Matches(Tuple2(5L, 4))); 1939 } 1940 1941 // Tests that Lt() describes itself properly. 1942 TEST(Lt2Test, CanDescribeSelf) { 1943 Matcher<const Tuple2&> m = Lt(); 1944 EXPECT_EQ("are a pair where the first < the second", Describe(m)); 1945 } 1946 1947 // Tests that Ne() matches a 2-tuple where the first field != the 1948 // second field. 1949 TEST(Ne2Test, MatchesUnequalArguments) { 1950 Matcher<const Tuple2&> m = Ne(); 1951 EXPECT_TRUE(m.Matches(Tuple2(5L, 6))); 1952 EXPECT_TRUE(m.Matches(Tuple2(5L, 4))); 1953 EXPECT_FALSE(m.Matches(Tuple2(5L, 5))); 1954 } 1955 1956 // Tests that Ne() describes itself properly. 1957 TEST(Ne2Test, CanDescribeSelf) { 1958 Matcher<const Tuple2&> m = Ne(); 1959 EXPECT_EQ("are an unequal pair", Describe(m)); 1960 } 1961 1962 // Tests that Not(m) matches any value that doesn't match m. 1963 TEST(NotTest, NegatesMatcher) { 1964 Matcher<int> m; 1965 m = Not(Eq(2)); 1966 EXPECT_TRUE(m.Matches(3)); 1967 EXPECT_FALSE(m.Matches(2)); 1968 } 1969 1970 // Tests that Not(m) describes itself properly. 1971 TEST(NotTest, CanDescribeSelf) { 1972 Matcher<int> m = Not(Eq(5)); 1973 EXPECT_EQ("isn't equal to 5", Describe(m)); 1974 } 1975 1976 // Tests that monomorphic matchers are safely cast by the Not matcher. 1977 TEST(NotTest, NotMatcherSafelyCastsMonomorphicMatchers) { 1978 // greater_than_5 is a monomorphic matcher. 1979 Matcher<int> greater_than_5 = Gt(5); 1980 1981 Matcher<const int&> m = Not(greater_than_5); 1982 Matcher<int&> m2 = Not(greater_than_5); 1983 Matcher<int&> m3 = Not(m); 1984 } 1985 1986 // Helper to allow easy testing of AllOf matchers with num parameters. 1987 void AllOfMatches(int num, const Matcher<int>& m) { 1988 SCOPED_TRACE(Describe(m)); 1989 EXPECT_TRUE(m.Matches(0)); 1990 for (int i = 1; i <= num; ++i) { 1991 EXPECT_FALSE(m.Matches(i)); 1992 } 1993 EXPECT_TRUE(m.Matches(num + 1)); 1994 } 1995 1996 // Tests that AllOf(m1, ..., mn) matches any value that matches all of 1997 // the given matchers. 1998 TEST(AllOfTest, MatchesWhenAllMatch) { 1999 Matcher<int> m; 2000 m = AllOf(Le(2), Ge(1)); 2001 EXPECT_TRUE(m.Matches(1)); 2002 EXPECT_TRUE(m.Matches(2)); 2003 EXPECT_FALSE(m.Matches(0)); 2004 EXPECT_FALSE(m.Matches(3)); 2005 2006 m = AllOf(Gt(0), Ne(1), Ne(2)); 2007 EXPECT_TRUE(m.Matches(3)); 2008 EXPECT_FALSE(m.Matches(2)); 2009 EXPECT_FALSE(m.Matches(1)); 2010 EXPECT_FALSE(m.Matches(0)); 2011 2012 m = AllOf(Gt(0), Ne(1), Ne(2), Ne(3)); 2013 EXPECT_TRUE(m.Matches(4)); 2014 EXPECT_FALSE(m.Matches(3)); 2015 EXPECT_FALSE(m.Matches(2)); 2016 EXPECT_FALSE(m.Matches(1)); 2017 EXPECT_FALSE(m.Matches(0)); 2018 2019 m = AllOf(Ge(0), Lt(10), Ne(3), Ne(5), Ne(7)); 2020 EXPECT_TRUE(m.Matches(0)); 2021 EXPECT_TRUE(m.Matches(1)); 2022 EXPECT_FALSE(m.Matches(3)); 2023 2024 // The following tests for varying number of sub-matchers. Due to the way 2025 // the sub-matchers are handled it is enough to test every sub-matcher once 2026 // with sub-matchers using the same matcher type. Varying matcher types are 2027 // checked for above. 2028 AllOfMatches(2, AllOf(Ne(1), Ne(2))); 2029 AllOfMatches(3, AllOf(Ne(1), Ne(2), Ne(3))); 2030 AllOfMatches(4, AllOf(Ne(1), Ne(2), Ne(3), Ne(4))); 2031 AllOfMatches(5, AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5))); 2032 AllOfMatches(6, AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5), Ne(6))); 2033 AllOfMatches(7, AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5), Ne(6), Ne(7))); 2034 AllOfMatches(8, AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5), Ne(6), Ne(7), 2035 Ne(8))); 2036 AllOfMatches(9, AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5), Ne(6), Ne(7), 2037 Ne(8), Ne(9))); 2038 AllOfMatches(10, AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5), Ne(6), Ne(7), Ne(8), 2039 Ne(9), Ne(10))); 2040 } 2041 2042 #if GTEST_LANG_CXX11 2043 // Tests the variadic version of the AllOfMatcher. 2044 TEST(AllOfTest, VariadicMatchesWhenAllMatch) { 2045 // Make sure AllOf is defined in the right namespace and does not depend on 2046 // ADL. 2047 ::testing::AllOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11); 2048 Matcher<int> m = AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5), Ne(6), Ne(7), Ne(8), 2049 Ne(9), Ne(10), Ne(11)); 2050 EXPECT_THAT(Describe(m), EndsWith("and (isn't equal to 11))))))))))")); 2051 AllOfMatches(11, m); 2052 AllOfMatches(50, AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5), Ne(6), Ne(7), Ne(8), 2053 Ne(9), Ne(10), Ne(11), Ne(12), Ne(13), Ne(14), Ne(15), 2054 Ne(16), Ne(17), Ne(18), Ne(19), Ne(20), Ne(21), Ne(22), 2055 Ne(23), Ne(24), Ne(25), Ne(26), Ne(27), Ne(28), Ne(29), 2056 Ne(30), Ne(31), Ne(32), Ne(33), Ne(34), Ne(35), Ne(36), 2057 Ne(37), Ne(38), Ne(39), Ne(40), Ne(41), Ne(42), Ne(43), 2058 Ne(44), Ne(45), Ne(46), Ne(47), Ne(48), Ne(49), 2059 Ne(50))); 2060 } 2061 2062 #endif // GTEST_LANG_CXX11 2063 2064 // Tests that AllOf(m1, ..., mn) describes itself properly. 2065 TEST(AllOfTest, CanDescribeSelf) { 2066 Matcher<int> m; 2067 m = AllOf(Le(2), Ge(1)); 2068 EXPECT_EQ("(is <= 2) and (is >= 1)", Describe(m)); 2069 2070 m = AllOf(Gt(0), Ne(1), Ne(2)); 2071 EXPECT_EQ("(is > 0) and " 2072 "((isn't equal to 1) and " 2073 "(isn't equal to 2))", 2074 Describe(m)); 2075 2076 2077 m = AllOf(Gt(0), Ne(1), Ne(2), Ne(3)); 2078 EXPECT_EQ("((is > 0) and " 2079 "(isn't equal to 1)) and " 2080 "((isn't equal to 2) and " 2081 "(isn't equal to 3))", 2082 Describe(m)); 2083 2084 2085 m = AllOf(Ge(0), Lt(10), Ne(3), Ne(5), Ne(7)); 2086 EXPECT_EQ("((is >= 0) and " 2087 "(is < 10)) and " 2088 "((isn't equal to 3) and " 2089 "((isn't equal to 5) and " 2090 "(isn't equal to 7)))", 2091 Describe(m)); 2092 } 2093 2094 // Tests that AllOf(m1, ..., mn) describes its negation properly. 2095 TEST(AllOfTest, CanDescribeNegation) { 2096 Matcher<int> m; 2097 m = AllOf(Le(2), Ge(1)); 2098 EXPECT_EQ("(isn't <= 2) or " 2099 "(isn't >= 1)", 2100 DescribeNegation(m)); 2101 2102 m = AllOf(Gt(0), Ne(1), Ne(2)); 2103 EXPECT_EQ("(isn't > 0) or " 2104 "((is equal to 1) or " 2105 "(is equal to 2))", 2106 DescribeNegation(m)); 2107 2108 2109 m = AllOf(Gt(0), Ne(1), Ne(2), Ne(3)); 2110 EXPECT_EQ("((isn't > 0) or " 2111 "(is equal to 1)) or " 2112 "((is equal to 2) or " 2113 "(is equal to 3))", 2114 DescribeNegation(m)); 2115 2116 2117 m = AllOf(Ge(0), Lt(10), Ne(3), Ne(5), Ne(7)); 2118 EXPECT_EQ("((isn't >= 0) or " 2119 "(isn't < 10)) or " 2120 "((is equal to 3) or " 2121 "((is equal to 5) or " 2122 "(is equal to 7)))", 2123 DescribeNegation(m)); 2124 } 2125 2126 // Tests that monomorphic matchers are safely cast by the AllOf matcher. 2127 TEST(AllOfTest, AllOfMatcherSafelyCastsMonomorphicMatchers) { 2128 // greater_than_5 and less_than_10 are monomorphic matchers. 2129 Matcher<int> greater_than_5 = Gt(5); 2130 Matcher<int> less_than_10 = Lt(10); 2131 2132 Matcher<const int&> m = AllOf(greater_than_5, less_than_10); 2133 Matcher<int&> m2 = AllOf(greater_than_5, less_than_10); 2134 Matcher<int&> m3 = AllOf(greater_than_5, m2); 2135 2136 // Tests that BothOf works when composing itself. 2137 Matcher<const int&> m4 = AllOf(greater_than_5, less_than_10, less_than_10); 2138 Matcher<int&> m5 = AllOf(greater_than_5, less_than_10, less_than_10); 2139 } 2140 2141 TEST(AllOfTest, ExplainsResult) { 2142 Matcher<int> m; 2143 2144 // Successful match. Both matchers need to explain. The second 2145 // matcher doesn't give an explanation, so only the first matcher's 2146 // explanation is printed. 2147 m = AllOf(GreaterThan(10), Lt(30)); 2148 EXPECT_EQ("which is 15 more than 10", Explain(m, 25)); 2149 2150 // Successful match. Both matchers need to explain. 2151 m = AllOf(GreaterThan(10), GreaterThan(20)); 2152 EXPECT_EQ("which is 20 more than 10, and which is 10 more than 20", 2153 Explain(m, 30)); 2154 2155 // Successful match. All matchers need to explain. The second 2156 // matcher doesn't given an explanation. 2157 m = AllOf(GreaterThan(10), Lt(30), GreaterThan(20)); 2158 EXPECT_EQ("which is 15 more than 10, and which is 5 more than 20", 2159 Explain(m, 25)); 2160 2161 // Successful match. All matchers need to explain. 2162 m = AllOf(GreaterThan(10), GreaterThan(20), GreaterThan(30)); 2163 EXPECT_EQ("which is 30 more than 10, and which is 20 more than 20, " 2164 "and which is 10 more than 30", 2165 Explain(m, 40)); 2166 2167 // Failed match. The first matcher, which failed, needs to 2168 // explain. 2169 m = AllOf(GreaterThan(10), GreaterThan(20)); 2170 EXPECT_EQ("which is 5 less than 10", Explain(m, 5)); 2171 2172 // Failed match. The second matcher, which failed, needs to 2173 // explain. Since it doesn't given an explanation, nothing is 2174 // printed. 2175 m = AllOf(GreaterThan(10), Lt(30)); 2176 EXPECT_EQ("", Explain(m, 40)); 2177 2178 // Failed match. The second matcher, which failed, needs to 2179 // explain. 2180 m = AllOf(GreaterThan(10), GreaterThan(20)); 2181 EXPECT_EQ("which is 5 less than 20", Explain(m, 15)); 2182 } 2183 2184 // Helper to allow easy testing of AnyOf matchers with num parameters. 2185 void AnyOfMatches(int num, const Matcher<int>& m) { 2186 SCOPED_TRACE(Describe(m)); 2187 EXPECT_FALSE(m.Matches(0)); 2188 for (int i = 1; i <= num; ++i) { 2189 EXPECT_TRUE(m.Matches(i)); 2190 } 2191 EXPECT_FALSE(m.Matches(num + 1)); 2192 } 2193 2194 // Tests that AnyOf(m1, ..., mn) matches any value that matches at 2195 // least one of the given matchers. 2196 TEST(AnyOfTest, MatchesWhenAnyMatches) { 2197 Matcher<int> m; 2198 m = AnyOf(Le(1), Ge(3)); 2199 EXPECT_TRUE(m.Matches(1)); 2200 EXPECT_TRUE(m.Matches(4)); 2201 EXPECT_FALSE(m.Matches(2)); 2202 2203 m = AnyOf(Lt(0), Eq(1), Eq(2)); 2204 EXPECT_TRUE(m.Matches(-1)); 2205 EXPECT_TRUE(m.Matches(1)); 2206 EXPECT_TRUE(m.Matches(2)); 2207 EXPECT_FALSE(m.Matches(0)); 2208 2209 m = AnyOf(Lt(0), Eq(1), Eq(2), Eq(3)); 2210 EXPECT_TRUE(m.Matches(-1)); 2211 EXPECT_TRUE(m.Matches(1)); 2212 EXPECT_TRUE(m.Matches(2)); 2213 EXPECT_TRUE(m.Matches(3)); 2214 EXPECT_FALSE(m.Matches(0)); 2215 2216 m = AnyOf(Le(0), Gt(10), 3, 5, 7); 2217 EXPECT_TRUE(m.Matches(0)); 2218 EXPECT_TRUE(m.Matches(11)); 2219 EXPECT_TRUE(m.Matches(3)); 2220 EXPECT_FALSE(m.Matches(2)); 2221 2222 // The following tests for varying number of sub-matchers. Due to the way 2223 // the sub-matchers are handled it is enough to test every sub-matcher once 2224 // with sub-matchers using the same matcher type. Varying matcher types are 2225 // checked for above. 2226 AnyOfMatches(2, AnyOf(1, 2)); 2227 AnyOfMatches(3, AnyOf(1, 2, 3)); 2228 AnyOfMatches(4, AnyOf(1, 2, 3, 4)); 2229 AnyOfMatches(5, AnyOf(1, 2, 3, 4, 5)); 2230 AnyOfMatches(6, AnyOf(1, 2, 3, 4, 5, 6)); 2231 AnyOfMatches(7, AnyOf(1, 2, 3, 4, 5, 6, 7)); 2232 AnyOfMatches(8, AnyOf(1, 2, 3, 4, 5, 6, 7, 8)); 2233 AnyOfMatches(9, AnyOf(1, 2, 3, 4, 5, 6, 7, 8, 9)); 2234 AnyOfMatches(10, AnyOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)); 2235 } 2236 2237 #if GTEST_LANG_CXX11 2238 // Tests the variadic version of the AnyOfMatcher. 2239 TEST(AnyOfTest, VariadicMatchesWhenAnyMatches) { 2240 // Also make sure AnyOf is defined in the right namespace and does not depend 2241 // on ADL. 2242 Matcher<int> m = ::testing::AnyOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11); 2243 2244 EXPECT_THAT(Describe(m), EndsWith("or (is equal to 11))))))))))")); 2245 AnyOfMatches(11, m); 2246 AnyOfMatches(50, AnyOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 2247 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 2248 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 2249 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 2250 41, 42, 43, 44, 45, 46, 47, 48, 49, 50)); 2251 } 2252 2253 #endif // GTEST_LANG_CXX11 2254 2255 // Tests that AnyOf(m1, ..., mn) describes itself properly. 2256 TEST(AnyOfTest, CanDescribeSelf) { 2257 Matcher<int> m; 2258 m = AnyOf(Le(1), Ge(3)); 2259 EXPECT_EQ("(is <= 1) or (is >= 3)", 2260 Describe(m)); 2261 2262 m = AnyOf(Lt(0), Eq(1), Eq(2)); 2263 EXPECT_EQ("(is < 0) or " 2264 "((is equal to 1) or (is equal to 2))", 2265 Describe(m)); 2266 2267 m = AnyOf(Lt(0), Eq(1), Eq(2), Eq(3)); 2268 EXPECT_EQ("((is < 0) or " 2269 "(is equal to 1)) or " 2270 "((is equal to 2) or " 2271 "(is equal to 3))", 2272 Describe(m)); 2273 2274 m = AnyOf(Le(0), Gt(10), 3, 5, 7); 2275 EXPECT_EQ("((is <= 0) or " 2276 "(is > 10)) or " 2277 "((is equal to 3) or " 2278 "((is equal to 5) or " 2279 "(is equal to 7)))", 2280 Describe(m)); 2281 } 2282 2283 // Tests that AnyOf(m1, ..., mn) describes its negation properly. 2284 TEST(AnyOfTest, CanDescribeNegation) { 2285 Matcher<int> m; 2286 m = AnyOf(Le(1), Ge(3)); 2287 EXPECT_EQ("(isn't <= 1) and (isn't >= 3)", 2288 DescribeNegation(m)); 2289 2290 m = AnyOf(Lt(0), Eq(1), Eq(2)); 2291 EXPECT_EQ("(isn't < 0) and " 2292 "((isn't equal to 1) and (isn't equal to 2))", 2293 DescribeNegation(m)); 2294 2295 m = AnyOf(Lt(0), Eq(1), Eq(2), Eq(3)); 2296 EXPECT_EQ("((isn't < 0) and " 2297 "(isn't equal to 1)) and " 2298 "((isn't equal to 2) and " 2299 "(isn't equal to 3))", 2300 DescribeNegation(m)); 2301 2302 m = AnyOf(Le(0), Gt(10), 3, 5, 7); 2303 EXPECT_EQ("((isn't <= 0) and " 2304 "(isn't > 10)) and " 2305 "((isn't equal to 3) and " 2306 "((isn't equal to 5) and " 2307 "(isn't equal to 7)))", 2308 DescribeNegation(m)); 2309 } 2310 2311 // Tests that monomorphic matchers are safely cast by the AnyOf matcher. 2312 TEST(AnyOfTest, AnyOfMatcherSafelyCastsMonomorphicMatchers) { 2313 // greater_than_5 and less_than_10 are monomorphic matchers. 2314 Matcher<int> greater_than_5 = Gt(5); 2315 Matcher<int> less_than_10 = Lt(10); 2316 2317 Matcher<const int&> m = AnyOf(greater_than_5, less_than_10); 2318 Matcher<int&> m2 = AnyOf(greater_than_5, less_than_10); 2319 Matcher<int&> m3 = AnyOf(greater_than_5, m2); 2320 2321 // Tests that EitherOf works when composing itself. 2322 Matcher<const int&> m4 = AnyOf(greater_than_5, less_than_10, less_than_10); 2323 Matcher<int&> m5 = AnyOf(greater_than_5, less_than_10, less_than_10); 2324 } 2325 2326 TEST(AnyOfTest, ExplainsResult) { 2327 Matcher<int> m; 2328 2329 // Failed match. Both matchers need to explain. The second 2330 // matcher doesn't give an explanation, so only the first matcher's 2331 // explanation is printed. 2332 m = AnyOf(GreaterThan(10), Lt(0)); 2333 EXPECT_EQ("which is 5 less than 10", Explain(m, 5)); 2334 2335 // Failed match. Both matchers need to explain. 2336 m = AnyOf(GreaterThan(10), GreaterThan(20)); 2337 EXPECT_EQ("which is 5 less than 10, and which is 15 less than 20", 2338 Explain(m, 5)); 2339 2340 // Failed match. All matchers need to explain. The second 2341 // matcher doesn't given an explanation. 2342 m = AnyOf(GreaterThan(10), Gt(20), GreaterThan(30)); 2343 EXPECT_EQ("which is 5 less than 10, and which is 25 less than 30", 2344 Explain(m, 5)); 2345 2346 // Failed match. All matchers need to explain. 2347 m = AnyOf(GreaterThan(10), GreaterThan(20), GreaterThan(30)); 2348 EXPECT_EQ("which is 5 less than 10, and which is 15 less than 20, " 2349 "and which is 25 less than 30", 2350 Explain(m, 5)); 2351 2352 // Successful match. The first matcher, which succeeded, needs to 2353 // explain. 2354 m = AnyOf(GreaterThan(10), GreaterThan(20)); 2355 EXPECT_EQ("which is 5 more than 10", Explain(m, 15)); 2356 2357 // Successful match. The second matcher, which succeeded, needs to 2358 // explain. Since it doesn't given an explanation, nothing is 2359 // printed. 2360 m = AnyOf(GreaterThan(10), Lt(30)); 2361 EXPECT_EQ("", Explain(m, 0)); 2362 2363 // Successful match. The second matcher, which succeeded, needs to 2364 // explain. 2365 m = AnyOf(GreaterThan(30), GreaterThan(20)); 2366 EXPECT_EQ("which is 5 more than 20", Explain(m, 25)); 2367 } 2368 2369 // The following predicate function and predicate functor are for 2370 // testing the Truly(predicate) matcher. 2371 2372 // Returns non-zero if the input is positive. Note that the return 2373 // type of this function is not bool. It's OK as Truly() accepts any 2374 // unary function or functor whose return type can be implicitly 2375 // converted to bool. 2376 int IsPositive(double x) { 2377 return x > 0 ? 1 : 0; 2378 } 2379 2380 // This functor returns true if the input is greater than the given 2381 // number. 2382 class IsGreaterThan { 2383 public: 2384 explicit IsGreaterThan(int threshold) : threshold_(threshold) {} 2385 2386 bool operator()(int n) const { return n > threshold_; } 2387 2388 private: 2389 int threshold_; 2390 }; 2391 2392 // For testing Truly(). 2393 const int foo = 0; 2394 2395 // This predicate returns true iff the argument references foo and has 2396 // a zero value. 2397 bool ReferencesFooAndIsZero(const int& n) { 2398 return (&n == &foo) && (n == 0); 2399 } 2400 2401 // Tests that Truly(predicate) matches what satisfies the given 2402 // predicate. 2403 TEST(TrulyTest, MatchesWhatSatisfiesThePredicate) { 2404 Matcher<double> m = Truly(IsPositive); 2405 EXPECT_TRUE(m.Matches(2.0)); 2406 EXPECT_FALSE(m.Matches(-1.5)); 2407 } 2408 2409 // Tests that Truly(predicate_functor) works too. 2410 TEST(TrulyTest, CanBeUsedWithFunctor) { 2411 Matcher<int> m = Truly(IsGreaterThan(5)); 2412 EXPECT_TRUE(m.Matches(6)); 2413 EXPECT_FALSE(m.Matches(4)); 2414 } 2415 2416 // A class that can be implicitly converted to bool. 2417 class ConvertibleToBool { 2418 public: 2419 explicit ConvertibleToBool(int number) : number_(number) {} 2420 operator bool() const { return number_ != 0; } 2421 2422 private: 2423 int number_; 2424 }; 2425 2426 ConvertibleToBool IsNotZero(int number) { 2427 return ConvertibleToBool(number); 2428 } 2429 2430 // Tests that the predicate used in Truly() may return a class that's 2431 // implicitly convertible to bool, even when the class has no 2432 // operator!(). 2433 TEST(TrulyTest, PredicateCanReturnAClassConvertibleToBool) { 2434 Matcher<int> m = Truly(IsNotZero); 2435 EXPECT_TRUE(m.Matches(1)); 2436 EXPECT_FALSE(m.Matches(0)); 2437 } 2438 2439 // Tests that Truly(predicate) can describe itself properly. 2440 TEST(TrulyTest, CanDescribeSelf) { 2441 Matcher<double> m = Truly(IsPositive); 2442 EXPECT_EQ("satisfies the given predicate", 2443 Describe(m)); 2444 } 2445 2446 // Tests that Truly(predicate) works when the matcher takes its 2447 // argument by reference. 2448 TEST(TrulyTest, WorksForByRefArguments) { 2449 Matcher<const int&> m = Truly(ReferencesFooAndIsZero); 2450 EXPECT_TRUE(m.Matches(foo)); 2451 int n = 0; 2452 EXPECT_FALSE(m.Matches(n)); 2453 } 2454 2455 // Tests that Matches(m) is a predicate satisfied by whatever that 2456 // matches matcher m. 2457 TEST(MatchesTest, IsSatisfiedByWhatMatchesTheMatcher) { 2458 EXPECT_TRUE(Matches(Ge(0))(1)); 2459 EXPECT_FALSE(Matches(Eq('a'))('b')); 2460 } 2461 2462 // Tests that Matches(m) works when the matcher takes its argument by 2463 // reference. 2464 TEST(MatchesTest, WorksOnByRefArguments) { 2465 int m = 0, n = 0; 2466 EXPECT_TRUE(Matches(AllOf(Ref(n), Eq(0)))(n)); 2467 EXPECT_FALSE(Matches(Ref(m))(n)); 2468 } 2469 2470 // Tests that a Matcher on non-reference type can be used in 2471 // Matches(). 2472 TEST(MatchesTest, WorksWithMatcherOnNonRefType) { 2473 Matcher<int> eq5 = Eq(5); 2474 EXPECT_TRUE(Matches(eq5)(5)); 2475 EXPECT_FALSE(Matches(eq5)(2)); 2476 } 2477 2478 // Tests Value(value, matcher). Since Value() is a simple wrapper for 2479 // Matches(), which has been tested already, we don't spend a lot of 2480 // effort on testing Value(). 2481 TEST(ValueTest, WorksWithPolymorphicMatcher) { 2482 EXPECT_TRUE(Value("hi", StartsWith("h"))); 2483 EXPECT_FALSE(Value(5, Gt(10))); 2484 } 2485 2486 TEST(ValueTest, WorksWithMonomorphicMatcher) { 2487 const Matcher<int> is_zero = Eq(0); 2488 EXPECT_TRUE(Value(0, is_zero)); 2489 EXPECT_FALSE(Value('a', is_zero)); 2490 2491 int n = 0; 2492 const Matcher<const int&> ref_n = Ref(n); 2493 EXPECT_TRUE(Value(n, ref_n)); 2494 EXPECT_FALSE(Value(1, ref_n)); 2495 } 2496 2497 TEST(ExplainMatchResultTest, WorksWithPolymorphicMatcher) { 2498 StringMatchResultListener listener1; 2499 EXPECT_TRUE(ExplainMatchResult(PolymorphicIsEven(), 42, &listener1)); 2500 EXPECT_EQ("% 2 == 0", listener1.str()); 2501 2502 StringMatchResultListener listener2; 2503 EXPECT_FALSE(ExplainMatchResult(Ge(42), 1.5, &listener2)); 2504 EXPECT_EQ("", listener2.str()); 2505 } 2506 2507 TEST(ExplainMatchResultTest, WorksWithMonomorphicMatcher) { 2508 const Matcher<int> is_even = PolymorphicIsEven(); 2509 StringMatchResultListener listener1; 2510 EXPECT_TRUE(ExplainMatchResult(is_even, 42, &listener1)); 2511 EXPECT_EQ("% 2 == 0", listener1.str()); 2512 2513 const Matcher<const double&> is_zero = Eq(0); 2514 StringMatchResultListener listener2; 2515 EXPECT_FALSE(ExplainMatchResult(is_zero, 1.5, &listener2)); 2516 EXPECT_EQ("", listener2.str()); 2517 } 2518 2519 MATCHER_P(Really, inner_matcher, "") { 2520 return ExplainMatchResult(inner_matcher, arg, result_listener); 2521 } 2522 2523 TEST(ExplainMatchResultTest, WorksInsideMATCHER) { 2524 EXPECT_THAT(0, Really(Eq(0))); 2525 } 2526 2527 TEST(AllArgsTest, WorksForTuple) { 2528 EXPECT_THAT(make_tuple(1, 2L), AllArgs(Lt())); 2529 EXPECT_THAT(make_tuple(2L, 1), Not(AllArgs(Lt()))); 2530 } 2531 2532 TEST(AllArgsTest, WorksForNonTuple) { 2533 EXPECT_THAT(42, AllArgs(Gt(0))); 2534 EXPECT_THAT('a', Not(AllArgs(Eq('b')))); 2535 } 2536 2537 class AllArgsHelper { 2538 public: 2539 AllArgsHelper() {} 2540 2541 MOCK_METHOD2(Helper, int(char x, int y)); 2542 2543 private: 2544 GTEST_DISALLOW_COPY_AND_ASSIGN_(AllArgsHelper); 2545 }; 2546 2547 TEST(AllArgsTest, WorksInWithClause) { 2548 AllArgsHelper helper; 2549 ON_CALL(helper, Helper(_, _)) 2550 .With(AllArgs(Lt())) 2551 .WillByDefault(Return(1)); 2552 EXPECT_CALL(helper, Helper(_, _)); 2553 EXPECT_CALL(helper, Helper(_, _)) 2554 .With(AllArgs(Gt())) 2555 .WillOnce(Return(2)); 2556 2557 EXPECT_EQ(1, helper.Helper('\1', 2)); 2558 EXPECT_EQ(2, helper.Helper('a', 1)); 2559 } 2560 2561 // Tests that ASSERT_THAT() and EXPECT_THAT() work when the value 2562 // matches the matcher. 2563 TEST(MatcherAssertionTest, WorksWhenMatcherIsSatisfied) { 2564 ASSERT_THAT(5, Ge(2)) << "This should succeed."; 2565 ASSERT_THAT("Foo", EndsWith("oo")); 2566 EXPECT_THAT(2, AllOf(Le(7), Ge(0))) << "This should succeed too."; 2567 EXPECT_THAT("Hello", StartsWith("Hell")); 2568 } 2569 2570 // Tests that ASSERT_THAT() and EXPECT_THAT() work when the value 2571 // doesn't match the matcher. 2572 TEST(MatcherAssertionTest, WorksWhenMatcherIsNotSatisfied) { 2573 // 'n' must be static as it is used in an EXPECT_FATAL_FAILURE(), 2574 // which cannot reference auto variables. 2575 static unsigned short n; // NOLINT 2576 n = 5; 2577 2578 // VC++ prior to version 8.0 SP1 has a bug where it will not see any 2579 // functions declared in the namespace scope from within nested classes. 2580 // EXPECT/ASSERT_(NON)FATAL_FAILURE macros use nested classes so that all 2581 // namespace-level functions invoked inside them need to be explicitly 2582 // resolved. 2583 EXPECT_FATAL_FAILURE(ASSERT_THAT(n, ::testing::Gt(10)), 2584 "Value of: n\n" 2585 "Expected: is > 10\n" 2586 " Actual: 5" + OfType("unsigned short")); 2587 n = 0; 2588 EXPECT_NONFATAL_FAILURE( 2589 EXPECT_THAT(n, ::testing::AllOf(::testing::Le(7), ::testing::Ge(5))), 2590 "Value of: n\n" 2591 "Expected: (is <= 7) and (is >= 5)\n" 2592 " Actual: 0" + OfType("unsigned short")); 2593 } 2594 2595 // Tests that ASSERT_THAT() and EXPECT_THAT() work when the argument 2596 // has a reference type. 2597 TEST(MatcherAssertionTest, WorksForByRefArguments) { 2598 // We use a static variable here as EXPECT_FATAL_FAILURE() cannot 2599 // reference auto variables. 2600 static int n; 2601 n = 0; 2602 EXPECT_THAT(n, AllOf(Le(7), Ref(n))); 2603 EXPECT_FATAL_FAILURE(ASSERT_THAT(n, ::testing::Not(::testing::Ref(n))), 2604 "Value of: n\n" 2605 "Expected: does not reference the variable @"); 2606 // Tests the "Actual" part. 2607 EXPECT_FATAL_FAILURE(ASSERT_THAT(n, ::testing::Not(::testing::Ref(n))), 2608 "Actual: 0" + OfType("int") + ", which is located @"); 2609 } 2610 2611 #if !GTEST_OS_SYMBIAN 2612 // Tests that ASSERT_THAT() and EXPECT_THAT() work when the matcher is 2613 // monomorphic. 2614 2615 // ASSERT_THAT("hello", starts_with_he) fails to compile with Nokia's 2616 // Symbian compiler: it tries to compile 2617 // template<T, U> class MatcherCastImpl { ... 2618 // virtual bool MatchAndExplain(T x, ...) const { 2619 // return source_matcher_.MatchAndExplain(static_cast<U>(x), ...); 2620 // with U == string and T == const char* 2621 // With ASSERT_THAT("hello"...) changed to ASSERT_THAT(string("hello") ... ) 2622 // the compiler silently crashes with no output. 2623 // If MatcherCastImpl is changed to use U(x) instead of static_cast<U>(x) 2624 // the code compiles but the converted string is bogus. 2625 TEST(MatcherAssertionTest, WorksForMonomorphicMatcher) { 2626 Matcher<const char*> starts_with_he = StartsWith("he"); 2627 ASSERT_THAT("hello", starts_with_he); 2628 2629 Matcher<const string&> ends_with_ok = EndsWith("ok"); 2630 ASSERT_THAT("book", ends_with_ok); 2631 const string bad = "bad"; 2632 EXPECT_NONFATAL_FAILURE(EXPECT_THAT(bad, ends_with_ok), 2633 "Value of: bad\n" 2634 "Expected: ends with \"ok\"\n" 2635 " Actual: \"bad\""); 2636 Matcher<int> is_greater_than_5 = Gt(5); 2637 EXPECT_NONFATAL_FAILURE(EXPECT_THAT(5, is_greater_than_5), 2638 "Value of: 5\n" 2639 "Expected: is > 5\n" 2640 " Actual: 5" + OfType("int")); 2641 } 2642 #endif // !GTEST_OS_SYMBIAN 2643 2644 // Tests floating-point matchers. 2645 template <typename RawType> 2646 class FloatingPointTest : public testing::Test { 2647 protected: 2648 typedef testing::internal::FloatingPoint<RawType> Floating; 2649 typedef typename Floating::Bits Bits; 2650 2651 FloatingPointTest() 2652 : max_ulps_(Floating::kMaxUlps), 2653 zero_bits_(Floating(0).bits()), 2654 one_bits_(Floating(1).bits()), 2655 infinity_bits_(Floating(Floating::Infinity()).bits()), 2656 close_to_positive_zero_( 2657 Floating::ReinterpretBits(zero_bits_ + max_ulps_/2)), 2658 close_to_negative_zero_( 2659 -Floating::ReinterpretBits(zero_bits_ + max_ulps_ - max_ulps_/2)), 2660 further_from_negative_zero_(-Floating::ReinterpretBits( 2661 zero_bits_ + max_ulps_ + 1 - max_ulps_/2)), 2662 close_to_one_(Floating::ReinterpretBits(one_bits_ + max_ulps_)), 2663 further_from_one_(Floating::ReinterpretBits(one_bits_ + max_ulps_ + 1)), 2664 infinity_(Floating::Infinity()), 2665 close_to_infinity_( 2666 Floating::ReinterpretBits(infinity_bits_ - max_ulps_)), 2667 further_from_infinity_( 2668 Floating::ReinterpretBits(infinity_bits_ - max_ulps_ - 1)), 2669 max_(Floating::Max()), 2670 nan1_(Floating::ReinterpretBits(Floating::kExponentBitMask | 1)), 2671 nan2_(Floating::ReinterpretBits(Floating::kExponentBitMask | 200)) { 2672 } 2673 2674 void TestSize() { 2675 EXPECT_EQ(sizeof(RawType), sizeof(Bits)); 2676 } 2677 2678 // A battery of tests for FloatingEqMatcher::Matches. 2679 // matcher_maker is a pointer to a function which creates a FloatingEqMatcher. 2680 void TestMatches( 2681 testing::internal::FloatingEqMatcher<RawType> (*matcher_maker)(RawType)) { 2682 Matcher<RawType> m1 = matcher_maker(0.0); 2683 EXPECT_TRUE(m1.Matches(-0.0)); 2684 EXPECT_TRUE(m1.Matches(close_to_positive_zero_)); 2685 EXPECT_TRUE(m1.Matches(close_to_negative_zero_)); 2686 EXPECT_FALSE(m1.Matches(1.0)); 2687 2688 Matcher<RawType> m2 = matcher_maker(close_to_positive_zero_); 2689 EXPECT_FALSE(m2.Matches(further_from_negative_zero_)); 2690 2691 Matcher<RawType> m3 = matcher_maker(1.0); 2692 EXPECT_TRUE(m3.Matches(close_to_one_)); 2693 EXPECT_FALSE(m3.Matches(further_from_one_)); 2694 2695 // Test commutativity: matcher_maker(0.0).Matches(1.0) was tested above. 2696 EXPECT_FALSE(m3.Matches(0.0)); 2697 2698 Matcher<RawType> m4 = matcher_maker(-infinity_); 2699 EXPECT_TRUE(m4.Matches(-close_to_infinity_)); 2700 2701 Matcher<RawType> m5 = matcher_maker(infinity_); 2702 EXPECT_TRUE(m5.Matches(close_to_infinity_)); 2703 2704 // This is interesting as the representations of infinity_ and nan1_ 2705 // are only 1 DLP apart. 2706 EXPECT_FALSE(m5.Matches(nan1_)); 2707 2708 // matcher_maker can produce a Matcher<const RawType&>, which is needed in 2709 // some cases. 2710 Matcher<const RawType&> m6 = matcher_maker(0.0); 2711 EXPECT_TRUE(m6.Matches(-0.0)); 2712 EXPECT_TRUE(m6.Matches(close_to_positive_zero_)); 2713 EXPECT_FALSE(m6.Matches(1.0)); 2714 2715 // matcher_maker can produce a Matcher<RawType&>, which is needed in some 2716 // cases. 2717 Matcher<RawType&> m7 = matcher_maker(0.0); 2718 RawType x = 0.0; 2719 EXPECT_TRUE(m7.Matches(x)); 2720 x = 0.01f; 2721 EXPECT_FALSE(m7.Matches(x)); 2722 } 2723 2724 // Pre-calculated numbers to be used by the tests. 2725 2726 const size_t max_ulps_; 2727 2728 const Bits zero_bits_; // The bits that represent 0.0. 2729 const Bits one_bits_; // The bits that represent 1.0. 2730 const Bits infinity_bits_; // The bits that represent +infinity. 2731 2732 // Some numbers close to 0.0. 2733 const RawType close_to_positive_zero_; 2734 const RawType close_to_negative_zero_; 2735 const RawType further_from_negative_zero_; 2736 2737 // Some numbers close to 1.0. 2738 const RawType close_to_one_; 2739 const RawType further_from_one_; 2740 2741 // Some numbers close to +infinity. 2742 const RawType infinity_; 2743 const RawType close_to_infinity_; 2744 const RawType further_from_infinity_; 2745 2746 // Maximum representable value that's not infinity. 2747 const RawType max_; 2748 2749 // Some NaNs. 2750 const RawType nan1_; 2751 const RawType nan2_; 2752 }; 2753 2754 // Tests floating-point matchers with fixed epsilons. 2755 template <typename RawType> 2756 class FloatingPointNearTest : public FloatingPointTest<RawType> { 2757 protected: 2758 typedef FloatingPointTest<RawType> ParentType; 2759 2760 // A battery of tests for FloatingEqMatcher::Matches with a fixed epsilon. 2761 // matcher_maker is a pointer to a function which creates a FloatingEqMatcher. 2762 void TestNearMatches( 2763 testing::internal::FloatingEqMatcher<RawType> 2764 (*matcher_maker)(RawType, RawType)) { 2765 Matcher<RawType> m1 = matcher_maker(0.0, 0.0); 2766 EXPECT_TRUE(m1.Matches(0.0)); 2767 EXPECT_TRUE(m1.Matches(-0.0)); 2768 EXPECT_FALSE(m1.Matches(ParentType::close_to_positive_zero_)); 2769 EXPECT_FALSE(m1.Matches(ParentType::close_to_negative_zero_)); 2770 EXPECT_FALSE(m1.Matches(1.0)); 2771 2772 Matcher<RawType> m2 = matcher_maker(0.0, 1.0); 2773 EXPECT_TRUE(m2.Matches(0.0)); 2774 EXPECT_TRUE(m2.Matches(-0.0)); 2775 EXPECT_TRUE(m2.Matches(1.0)); 2776 EXPECT_TRUE(m2.Matches(-1.0)); 2777 EXPECT_FALSE(m2.Matches(ParentType::close_to_one_)); 2778 EXPECT_FALSE(m2.Matches(-ParentType::close_to_one_)); 2779 2780 // Check that inf matches inf, regardless of the of the specified max 2781 // absolute error. 2782 Matcher<RawType> m3 = matcher_maker(ParentType::infinity_, 0.0); 2783 EXPECT_TRUE(m3.Matches(ParentType::infinity_)); 2784 EXPECT_FALSE(m3.Matches(ParentType::close_to_infinity_)); 2785 EXPECT_FALSE(m3.Matches(-ParentType::infinity_)); 2786 2787 Matcher<RawType> m4 = matcher_maker(-ParentType::infinity_, 0.0); 2788 EXPECT_TRUE(m4.Matches(-ParentType::infinity_)); 2789 EXPECT_FALSE(m4.Matches(-ParentType::close_to_infinity_)); 2790 EXPECT_FALSE(m4.Matches(ParentType::infinity_)); 2791 2792 // Test various overflow scenarios. 2793 Matcher<RawType> m5 = matcher_maker(ParentType::max_, ParentType::max_); 2794 EXPECT_TRUE(m5.Matches(ParentType::max_)); 2795 EXPECT_FALSE(m5.Matches(-ParentType::max_)); 2796 2797 Matcher<RawType> m6 = matcher_maker(-ParentType::max_, ParentType::max_); 2798 EXPECT_FALSE(m6.Matches(ParentType::max_)); 2799 EXPECT_TRUE(m6.Matches(-ParentType::max_)); 2800 2801 Matcher<RawType> m7 = matcher_maker(ParentType::max_, 0); 2802 EXPECT_TRUE(m7.Matches(ParentType::max_)); 2803 EXPECT_FALSE(m7.Matches(-ParentType::max_)); 2804 2805 Matcher<RawType> m8 = matcher_maker(-ParentType::max_, 0); 2806 EXPECT_FALSE(m8.Matches(ParentType::max_)); 2807 EXPECT_TRUE(m8.Matches(-ParentType::max_)); 2808 2809 // The difference between max() and -max() normally overflows to infinity, 2810 // but it should still match if the max_abs_error is also infinity. 2811 Matcher<RawType> m9 = matcher_maker( 2812 ParentType::max_, ParentType::infinity_); 2813 EXPECT_TRUE(m8.Matches(-ParentType::max_)); 2814 2815 // matcher_maker can produce a Matcher<const RawType&>, which is needed in 2816 // some cases. 2817 Matcher<const RawType&> m10 = matcher_maker(0.0, 1.0); 2818 EXPECT_TRUE(m10.Matches(-0.0)); 2819 EXPECT_TRUE(m10.Matches(ParentType::close_to_positive_zero_)); 2820 EXPECT_FALSE(m10.Matches(ParentType::close_to_one_)); 2821 2822 // matcher_maker can produce a Matcher<RawType&>, which is needed in some 2823 // cases. 2824 Matcher<RawType&> m11 = matcher_maker(0.0, 1.0); 2825 RawType x = 0.0; 2826 EXPECT_TRUE(m11.Matches(x)); 2827 x = 1.0f; 2828 EXPECT_TRUE(m11.Matches(x)); 2829 x = -1.0f; 2830 EXPECT_TRUE(m11.Matches(x)); 2831 x = 1.1f; 2832 EXPECT_FALSE(m11.Matches(x)); 2833 x = -1.1f; 2834 EXPECT_FALSE(m11.Matches(x)); 2835 } 2836 }; 2837 2838 // Instantiate FloatingPointTest for testing floats. 2839 typedef FloatingPointTest<float> FloatTest; 2840 2841 TEST_F(FloatTest, FloatEqApproximatelyMatchesFloats) { 2842 TestMatches(&FloatEq); 2843 } 2844 2845 TEST_F(FloatTest, NanSensitiveFloatEqApproximatelyMatchesFloats) { 2846 TestMatches(&NanSensitiveFloatEq); 2847 } 2848 2849 TEST_F(FloatTest, FloatEqCannotMatchNaN) { 2850 // FloatEq never matches NaN. 2851 Matcher<float> m = FloatEq(nan1_); 2852 EXPECT_FALSE(m.Matches(nan1_)); 2853 EXPECT_FALSE(m.Matches(nan2_)); 2854 EXPECT_FALSE(m.Matches(1.0)); 2855 } 2856 2857 TEST_F(FloatTest, NanSensitiveFloatEqCanMatchNaN) { 2858 // NanSensitiveFloatEq will match NaN. 2859 Matcher<float> m = NanSensitiveFloatEq(nan1_); 2860 EXPECT_TRUE(m.Matches(nan1_)); 2861 EXPECT_TRUE(m.Matches(nan2_)); 2862 EXPECT_FALSE(m.Matches(1.0)); 2863 } 2864 2865 TEST_F(FloatTest, FloatEqCanDescribeSelf) { 2866 Matcher<float> m1 = FloatEq(2.0f); 2867 EXPECT_EQ("is approximately 2", Describe(m1)); 2868 EXPECT_EQ("isn't approximately 2", DescribeNegation(m1)); 2869 2870 Matcher<float> m2 = FloatEq(0.5f); 2871 EXPECT_EQ("is approximately 0.5", Describe(m2)); 2872 EXPECT_EQ("isn't approximately 0.5", DescribeNegation(m2)); 2873 2874 Matcher<float> m3 = FloatEq(nan1_); 2875 EXPECT_EQ("never matches", Describe(m3)); 2876 EXPECT_EQ("is anything", DescribeNegation(m3)); 2877 } 2878 2879 TEST_F(FloatTest, NanSensitiveFloatEqCanDescribeSelf) { 2880 Matcher<float> m1 = NanSensitiveFloatEq(2.0f); 2881 EXPECT_EQ("is approximately 2", Describe(m1)); 2882 EXPECT_EQ("isn't approximately 2", DescribeNegation(m1)); 2883 2884 Matcher<float> m2 = NanSensitiveFloatEq(0.5f); 2885 EXPECT_EQ("is approximately 0.5", Describe(m2)); 2886 EXPECT_EQ("isn't approximately 0.5", DescribeNegation(m2)); 2887 2888 Matcher<float> m3 = NanSensitiveFloatEq(nan1_); 2889 EXPECT_EQ("is NaN", Describe(m3)); 2890 EXPECT_EQ("isn't NaN", DescribeNegation(m3)); 2891 } 2892 2893 // Instantiate FloatingPointTest for testing floats with a user-specified 2894 // max absolute error. 2895 typedef FloatingPointNearTest<float> FloatNearTest; 2896 2897 TEST_F(FloatNearTest, FloatNearMatches) { 2898 TestNearMatches(&FloatNear); 2899 } 2900 2901 TEST_F(FloatNearTest, NanSensitiveFloatNearApproximatelyMatchesFloats) { 2902 TestNearMatches(&NanSensitiveFloatNear); 2903 } 2904 2905 TEST_F(FloatNearTest, FloatNearCanDescribeSelf) { 2906 Matcher<float> m1 = FloatNear(2.0f, 0.5f); 2907 EXPECT_EQ("is approximately 2 (absolute error <= 0.5)", Describe(m1)); 2908 EXPECT_EQ( 2909 "isn't approximately 2 (absolute error > 0.5)", DescribeNegation(m1)); 2910 2911 Matcher<float> m2 = FloatNear(0.5f, 0.5f); 2912 EXPECT_EQ("is approximately 0.5 (absolute error <= 0.5)", Describe(m2)); 2913 EXPECT_EQ( 2914 "isn't approximately 0.5 (absolute error > 0.5)", DescribeNegation(m2)); 2915 2916 Matcher<float> m3 = FloatNear(nan1_, 0.0); 2917 EXPECT_EQ("never matches", Describe(m3)); 2918 EXPECT_EQ("is anything", DescribeNegation(m3)); 2919 } 2920 2921 TEST_F(FloatNearTest, NanSensitiveFloatNearCanDescribeSelf) { 2922 Matcher<float> m1 = NanSensitiveFloatNear(2.0f, 0.5f); 2923 EXPECT_EQ("is approximately 2 (absolute error <= 0.5)", Describe(m1)); 2924 EXPECT_EQ( 2925 "isn't approximately 2 (absolute error > 0.5)", DescribeNegation(m1)); 2926 2927 Matcher<float> m2 = NanSensitiveFloatNear(0.5f, 0.5f); 2928 EXPECT_EQ("is approximately 0.5 (absolute error <= 0.5)", Describe(m2)); 2929 EXPECT_EQ( 2930 "isn't approximately 0.5 (absolute error > 0.5)", DescribeNegation(m2)); 2931 2932 Matcher<float> m3 = NanSensitiveFloatNear(nan1_, 0.1f); 2933 EXPECT_EQ("is NaN", Describe(m3)); 2934 EXPECT_EQ("isn't NaN", DescribeNegation(m3)); 2935 } 2936 2937 TEST_F(FloatNearTest, FloatNearCannotMatchNaN) { 2938 // FloatNear never matches NaN. 2939 Matcher<float> m = FloatNear(ParentType::nan1_, 0.1f); 2940 EXPECT_FALSE(m.Matches(nan1_)); 2941 EXPECT_FALSE(m.Matches(nan2_)); 2942 EXPECT_FALSE(m.Matches(1.0)); 2943 } 2944 2945 TEST_F(FloatNearTest, NanSensitiveFloatNearCanMatchNaN) { 2946 // NanSensitiveFloatNear will match NaN. 2947 Matcher<float> m = NanSensitiveFloatNear(nan1_, 0.1f); 2948 EXPECT_TRUE(m.Matches(nan1_)); 2949 EXPECT_TRUE(m.Matches(nan2_)); 2950 EXPECT_FALSE(m.Matches(1.0)); 2951 } 2952 2953 // Instantiate FloatingPointTest for testing doubles. 2954 typedef FloatingPointTest<double> DoubleTest; 2955 2956 TEST_F(DoubleTest, DoubleEqApproximatelyMatchesDoubles) { 2957 TestMatches(&DoubleEq); 2958 } 2959 2960 TEST_F(DoubleTest, NanSensitiveDoubleEqApproximatelyMatchesDoubles) { 2961 TestMatches(&NanSensitiveDoubleEq); 2962 } 2963 2964 TEST_F(DoubleTest, DoubleEqCannotMatchNaN) { 2965 // DoubleEq never matches NaN. 2966 Matcher<double> m = DoubleEq(nan1_); 2967 EXPECT_FALSE(m.Matches(nan1_)); 2968 EXPECT_FALSE(m.Matches(nan2_)); 2969 EXPECT_FALSE(m.Matches(1.0)); 2970 } 2971 2972 TEST_F(DoubleTest, NanSensitiveDoubleEqCanMatchNaN) { 2973 // NanSensitiveDoubleEq will match NaN. 2974 Matcher<double> m = NanSensitiveDoubleEq(nan1_); 2975 EXPECT_TRUE(m.Matches(nan1_)); 2976 EXPECT_TRUE(m.Matches(nan2_)); 2977 EXPECT_FALSE(m.Matches(1.0)); 2978 } 2979 2980 TEST_F(DoubleTest, DoubleEqCanDescribeSelf) { 2981 Matcher<double> m1 = DoubleEq(2.0); 2982 EXPECT_EQ("is approximately 2", Describe(m1)); 2983 EXPECT_EQ("isn't approximately 2", DescribeNegation(m1)); 2984 2985 Matcher<double> m2 = DoubleEq(0.5); 2986 EXPECT_EQ("is approximately 0.5", Describe(m2)); 2987 EXPECT_EQ("isn't approximately 0.5", DescribeNegation(m2)); 2988 2989 Matcher<double> m3 = DoubleEq(nan1_); 2990 EXPECT_EQ("never matches", Describe(m3)); 2991 EXPECT_EQ("is anything", DescribeNegation(m3)); 2992 } 2993 2994 TEST_F(DoubleTest, NanSensitiveDoubleEqCanDescribeSelf) { 2995 Matcher<double> m1 = NanSensitiveDoubleEq(2.0); 2996 EXPECT_EQ("is approximately 2", Describe(m1)); 2997 EXPECT_EQ("isn't approximately 2", DescribeNegation(m1)); 2998 2999 Matcher<double> m2 = NanSensitiveDoubleEq(0.5); 3000 EXPECT_EQ("is approximately 0.5", Describe(m2)); 3001 EXPECT_EQ("isn't approximately 0.5", DescribeNegation(m2)); 3002 3003 Matcher<double> m3 = NanSensitiveDoubleEq(nan1_); 3004 EXPECT_EQ("is NaN", Describe(m3)); 3005 EXPECT_EQ("isn't NaN", DescribeNegation(m3)); 3006 } 3007 3008 // Instantiate FloatingPointTest for testing floats with a user-specified 3009 // max absolute error. 3010 typedef FloatingPointNearTest<double> DoubleNearTest; 3011 3012 TEST_F(DoubleNearTest, DoubleNearMatches) { 3013 TestNearMatches(&DoubleNear); 3014 } 3015 3016 TEST_F(DoubleNearTest, NanSensitiveDoubleNearApproximatelyMatchesDoubles) { 3017 TestNearMatches(&NanSensitiveDoubleNear); 3018 } 3019 3020 TEST_F(DoubleNearTest, DoubleNearCanDescribeSelf) { 3021 Matcher<double> m1 = DoubleNear(2.0, 0.5); 3022 EXPECT_EQ("is approximately 2 (absolute error <= 0.5)", Describe(m1)); 3023 EXPECT_EQ( 3024 "isn't approximately 2 (absolute error > 0.5)", DescribeNegation(m1)); 3025 3026 Matcher<double> m2 = DoubleNear(0.5, 0.5); 3027 EXPECT_EQ("is approximately 0.5 (absolute error <= 0.5)", Describe(m2)); 3028 EXPECT_EQ( 3029 "isn't approximately 0.5 (absolute error > 0.5)", DescribeNegation(m2)); 3030 3031 Matcher<double> m3 = DoubleNear(nan1_, 0.0); 3032 EXPECT_EQ("never matches", Describe(m3)); 3033 EXPECT_EQ("is anything", DescribeNegation(m3)); 3034 } 3035 3036 TEST_F(DoubleNearTest, NanSensitiveDoubleNearCanDescribeSelf) { 3037 Matcher<double> m1 = NanSensitiveDoubleNear(2.0, 0.5); 3038 EXPECT_EQ("is approximately 2 (absolute error <= 0.5)", Describe(m1)); 3039 EXPECT_EQ( 3040 "isn't approximately 2 (absolute error > 0.5)", DescribeNegation(m1)); 3041 3042 Matcher<double> m2 = NanSensitiveDoubleNear(0.5, 0.5); 3043 EXPECT_EQ("is approximately 0.5 (absolute error <= 0.5)", Describe(m2)); 3044 EXPECT_EQ( 3045 "isn't approximately 0.5 (absolute error > 0.5)", DescribeNegation(m2)); 3046 3047 Matcher<double> m3 = NanSensitiveDoubleNear(nan1_, 0.1); 3048 EXPECT_EQ("is NaN", Describe(m3)); 3049 EXPECT_EQ("isn't NaN", DescribeNegation(m3)); 3050 } 3051 3052 TEST_F(DoubleNearTest, DoubleNearCannotMatchNaN) { 3053 // DoubleNear never matches NaN. 3054 Matcher<double> m = DoubleNear(ParentType::nan1_, 0.1); 3055 EXPECT_FALSE(m.Matches(nan1_)); 3056 EXPECT_FALSE(m.Matches(nan2_)); 3057 EXPECT_FALSE(m.Matches(1.0)); 3058 } 3059 3060 TEST_F(DoubleNearTest, NanSensitiveDoubleNearCanMatchNaN) { 3061 // NanSensitiveDoubleNear will match NaN. 3062 Matcher<double> m = NanSensitiveDoubleNear(nan1_, 0.1); 3063 EXPECT_TRUE(m.Matches(nan1_)); 3064 EXPECT_TRUE(m.Matches(nan2_)); 3065 EXPECT_FALSE(m.Matches(1.0)); 3066 } 3067 3068 TEST(PointeeTest, RawPointer) { 3069 const Matcher<int*> m = Pointee(Ge(0)); 3070 3071 int n = 1; 3072 EXPECT_TRUE(m.Matches(&n)); 3073 n = -1; 3074 EXPECT_FALSE(m.Matches(&n)); 3075 EXPECT_FALSE(m.Matches(NULL)); 3076 } 3077 3078 TEST(PointeeTest, RawPointerToConst) { 3079 const Matcher<const double*> m = Pointee(Ge(0)); 3080 3081 double x = 1; 3082 EXPECT_TRUE(m.Matches(&x)); 3083 x = -1; 3084 EXPECT_FALSE(m.Matches(&x)); 3085 EXPECT_FALSE(m.Matches(NULL)); 3086 } 3087 3088 TEST(PointeeTest, ReferenceToConstRawPointer) { 3089 const Matcher<int* const &> m = Pointee(Ge(0)); 3090 3091 int n = 1; 3092 EXPECT_TRUE(m.Matches(&n)); 3093 n = -1; 3094 EXPECT_FALSE(m.Matches(&n)); 3095 EXPECT_FALSE(m.Matches(NULL)); 3096 } 3097 3098 TEST(PointeeTest, ReferenceToNonConstRawPointer) { 3099 const Matcher<double* &> m = Pointee(Ge(0)); 3100 3101 double x = 1.0; 3102 double* p = &x; 3103 EXPECT_TRUE(m.Matches(p)); 3104 x = -1; 3105 EXPECT_FALSE(m.Matches(p)); 3106 p = NULL; 3107 EXPECT_FALSE(m.Matches(p)); 3108 } 3109 3110 // Minimal const-propagating pointer. 3111 template <typename T> 3112 class ConstPropagatingPtr { 3113 public: 3114 typedef T element_type; 3115 3116 ConstPropagatingPtr() : val_() {} 3117 explicit ConstPropagatingPtr(T* t) : val_(t) {} 3118 ConstPropagatingPtr(const ConstPropagatingPtr& other) : val_(other.val_) {} 3119 3120 T* get() { return val_; } 3121 T& operator*() { return *val_; } 3122 // Most smart pointers return non-const T* and T& from the next methods. 3123 const T* get() const { return val_; } 3124 const T& operator*() const { return *val_; } 3125 3126 private: 3127 T* val_; 3128 }; 3129 3130 TEST(PointeeTest, WorksWithConstPropagatingPointers) { 3131 const Matcher< ConstPropagatingPtr<int> > m = Pointee(Lt(5)); 3132 int three = 3; 3133 const ConstPropagatingPtr<int> co(&three); 3134 ConstPropagatingPtr<int> o(&three); 3135 EXPECT_TRUE(m.Matches(o)); 3136 EXPECT_TRUE(m.Matches(co)); 3137 *o = 6; 3138 EXPECT_FALSE(m.Matches(o)); 3139 EXPECT_FALSE(m.Matches(ConstPropagatingPtr<int>())); 3140 } 3141 3142 TEST(PointeeTest, NeverMatchesNull) { 3143 const Matcher<const char*> m = Pointee(_); 3144 EXPECT_FALSE(m.Matches(NULL)); 3145 } 3146 3147 // Tests that we can write Pointee(value) instead of Pointee(Eq(value)). 3148 TEST(PointeeTest, MatchesAgainstAValue) { 3149 const Matcher<int*> m = Pointee(5); 3150 3151 int n = 5; 3152 EXPECT_TRUE(m.Matches(&n)); 3153 n = -1; 3154 EXPECT_FALSE(m.Matches(&n)); 3155 EXPECT_FALSE(m.Matches(NULL)); 3156 } 3157 3158 TEST(PointeeTest, CanDescribeSelf) { 3159 const Matcher<int*> m = Pointee(Gt(3)); 3160 EXPECT_EQ("points to a value that is > 3", Describe(m)); 3161 EXPECT_EQ("does not point to a value that is > 3", 3162 DescribeNegation(m)); 3163 } 3164 3165 TEST(PointeeTest, CanExplainMatchResult) { 3166 const Matcher<const string*> m = Pointee(StartsWith("Hi")); 3167 3168 EXPECT_EQ("", Explain(m, static_cast<const string*>(NULL))); 3169 3170 const Matcher<long*> m2 = Pointee(GreaterThan(1)); // NOLINT 3171 long n = 3; // NOLINT 3172 EXPECT_EQ("which points to 3" + OfType("long") + ", which is 2 more than 1", 3173 Explain(m2, &n)); 3174 } 3175 3176 TEST(PointeeTest, AlwaysExplainsPointee) { 3177 const Matcher<int*> m = Pointee(0); 3178 int n = 42; 3179 EXPECT_EQ("which points to 42" + OfType("int"), Explain(m, &n)); 3180 } 3181 3182 // An uncopyable class. 3183 class Uncopyable { 3184 public: 3185 explicit Uncopyable(int a_value) : value_(a_value) {} 3186 3187 int value() const { return value_; } 3188 private: 3189 const int value_; 3190 GTEST_DISALLOW_COPY_AND_ASSIGN_(Uncopyable); 3191 }; 3192 3193 // Returns true iff x.value() is positive. 3194 bool ValueIsPositive(const Uncopyable& x) { return x.value() > 0; } 3195 3196 // A user-defined struct for testing Field(). 3197 struct AStruct { 3198 AStruct() : x(0), y(1.0), z(5), p(NULL) {} 3199 AStruct(const AStruct& rhs) 3200 : x(rhs.x), y(rhs.y), z(rhs.z.value()), p(rhs.p) {} 3201 3202 int x; // A non-const field. 3203 const double y; // A const field. 3204 Uncopyable z; // An uncopyable field. 3205 const char* p; // A pointer field. 3206 3207 private: 3208 GTEST_DISALLOW_ASSIGN_(AStruct); 3209 }; 3210 3211 // A derived struct for testing Field(). 3212 struct DerivedStruct : public AStruct { 3213 char ch; 3214 3215 private: 3216 GTEST_DISALLOW_ASSIGN_(DerivedStruct); 3217 }; 3218 3219 // Tests that Field(&Foo::field, ...) works when field is non-const. 3220 TEST(FieldTest, WorksForNonConstField) { 3221 Matcher<AStruct> m = Field(&AStruct::x, Ge(0)); 3222 3223 AStruct a; 3224 EXPECT_TRUE(m.Matches(a)); 3225 a.x = -1; 3226 EXPECT_FALSE(m.Matches(a)); 3227 } 3228 3229 // Tests that Field(&Foo::field, ...) works when field is const. 3230 TEST(FieldTest, WorksForConstField) { 3231 AStruct a; 3232 3233 Matcher<AStruct> m = Field(&AStruct::y, Ge(0.0)); 3234 EXPECT_TRUE(m.Matches(a)); 3235 m = Field(&AStruct::y, Le(0.0)); 3236 EXPECT_FALSE(m.Matches(a)); 3237 } 3238 3239 // Tests that Field(&Foo::field, ...) works when field is not copyable. 3240 TEST(FieldTest, WorksForUncopyableField) { 3241 AStruct a; 3242 3243 Matcher<AStruct> m = Field(&AStruct::z, Truly(ValueIsPositive)); 3244 EXPECT_TRUE(m.Matches(a)); 3245 m = Field(&AStruct::z, Not(Truly(ValueIsPositive))); 3246 EXPECT_FALSE(m.Matches(a)); 3247 } 3248 3249 // Tests that Field(&Foo::field, ...) works when field is a pointer. 3250 TEST(FieldTest, WorksForPointerField) { 3251 // Matching against NULL. 3252 Matcher<AStruct> m = Field(&AStruct::p, static_cast<const char*>(NULL)); 3253 AStruct a; 3254 EXPECT_TRUE(m.Matches(a)); 3255 a.p = "hi"; 3256 EXPECT_FALSE(m.Matches(a)); 3257 3258 // Matching a pointer that is not NULL. 3259 m = Field(&AStruct::p, StartsWith("hi")); 3260 a.p = "hill"; 3261 EXPECT_TRUE(m.Matches(a)); 3262 a.p = "hole"; 3263 EXPECT_FALSE(m.Matches(a)); 3264 } 3265 3266 // Tests that Field() works when the object is passed by reference. 3267 TEST(FieldTest, WorksForByRefArgument) { 3268 Matcher<const AStruct&> m = Field(&AStruct::x, Ge(0)); 3269 3270 AStruct a; 3271 EXPECT_TRUE(m.Matches(a)); 3272 a.x = -1; 3273 EXPECT_FALSE(m.Matches(a)); 3274 } 3275 3276 // Tests that Field(&Foo::field, ...) works when the argument's type 3277 // is a sub-type of Foo. 3278 TEST(FieldTest, WorksForArgumentOfSubType) { 3279 // Note that the matcher expects DerivedStruct but we say AStruct 3280 // inside Field(). 3281 Matcher<const DerivedStruct&> m = Field(&AStruct::x, Ge(0)); 3282 3283 DerivedStruct d; 3284 EXPECT_TRUE(m.Matches(d)); 3285 d.x = -1; 3286 EXPECT_FALSE(m.Matches(d)); 3287 } 3288 3289 // Tests that Field(&Foo::field, m) works when field's type and m's 3290 // argument type are compatible but not the same. 3291 TEST(FieldTest, WorksForCompatibleMatcherType) { 3292 // The field is an int, but the inner matcher expects a signed char. 3293 Matcher<const AStruct&> m = Field(&AStruct::x, 3294 Matcher<signed char>(Ge(0))); 3295 3296 AStruct a; 3297 EXPECT_TRUE(m.Matches(a)); 3298 a.x = -1; 3299 EXPECT_FALSE(m.Matches(a)); 3300 } 3301 3302 // Tests that Field() can describe itself. 3303 TEST(FieldTest, CanDescribeSelf) { 3304 Matcher<const AStruct&> m = Field(&AStruct::x, Ge(0)); 3305 3306 EXPECT_EQ("is an object whose given field is >= 0", Describe(m)); 3307 EXPECT_EQ("is an object whose given field isn't >= 0", DescribeNegation(m)); 3308 } 3309 3310 // Tests that Field() can explain the match result. 3311 TEST(FieldTest, CanExplainMatchResult) { 3312 Matcher<const AStruct&> m = Field(&AStruct::x, Ge(0)); 3313 3314 AStruct a; 3315 a.x = 1; 3316 EXPECT_EQ("whose given field is 1" + OfType("int"), Explain(m, a)); 3317 3318 m = Field(&AStruct::x, GreaterThan(0)); 3319 EXPECT_EQ( 3320 "whose given field is 1" + OfType("int") + ", which is 1 more than 0", 3321 Explain(m, a)); 3322 } 3323 3324 // Tests that Field() works when the argument is a pointer to const. 3325 TEST(FieldForPointerTest, WorksForPointerToConst) { 3326 Matcher<const AStruct*> m = Field(&AStruct::x, Ge(0)); 3327 3328 AStruct a; 3329 EXPECT_TRUE(m.Matches(&a)); 3330 a.x = -1; 3331 EXPECT_FALSE(m.Matches(&a)); 3332 } 3333 3334 // Tests that Field() works when the argument is a pointer to non-const. 3335 TEST(FieldForPointerTest, WorksForPointerToNonConst) { 3336 Matcher<AStruct*> m = Field(&AStruct::x, Ge(0)); 3337 3338 AStruct a; 3339 EXPECT_TRUE(m.Matches(&a)); 3340 a.x = -1; 3341 EXPECT_FALSE(m.Matches(&a)); 3342 } 3343 3344 // Tests that Field() works when the argument is a reference to a const pointer. 3345 TEST(FieldForPointerTest, WorksForReferenceToConstPointer) { 3346 Matcher<AStruct* const&> m = Field(&AStruct::x, Ge(0)); 3347 3348 AStruct a; 3349 EXPECT_TRUE(m.Matches(&a)); 3350 a.x = -1; 3351 EXPECT_FALSE(m.Matches(&a)); 3352 } 3353 3354 // Tests that Field() does not match the NULL pointer. 3355 TEST(FieldForPointerTest, DoesNotMatchNull) { 3356 Matcher<const AStruct*> m = Field(&AStruct::x, _); 3357 EXPECT_FALSE(m.Matches(NULL)); 3358 } 3359 3360 // Tests that Field(&Foo::field, ...) works when the argument's type 3361 // is a sub-type of const Foo*. 3362 TEST(FieldForPointerTest, WorksForArgumentOfSubType) { 3363 // Note that the matcher expects DerivedStruct but we say AStruct 3364 // inside Field(). 3365 Matcher<DerivedStruct*> m = Field(&AStruct::x, Ge(0)); 3366 3367 DerivedStruct d; 3368 EXPECT_TRUE(m.Matches(&d)); 3369 d.x = -1; 3370 EXPECT_FALSE(m.Matches(&d)); 3371 } 3372 3373 // Tests that Field() can describe itself when used to match a pointer. 3374 TEST(FieldForPointerTest, CanDescribeSelf) { 3375 Matcher<const AStruct*> m = Field(&AStruct::x, Ge(0)); 3376 3377 EXPECT_EQ("is an object whose given field is >= 0", Describe(m)); 3378 EXPECT_EQ("is an object whose given field isn't >= 0", DescribeNegation(m)); 3379 } 3380 3381 // Tests that Field() can explain the result of matching a pointer. 3382 TEST(FieldForPointerTest, CanExplainMatchResult) { 3383 Matcher<const AStruct*> m = Field(&AStruct::x, Ge(0)); 3384 3385 AStruct a; 3386 a.x = 1; 3387 EXPECT_EQ("", Explain(m, static_cast<const AStruct*>(NULL))); 3388 EXPECT_EQ("which points to an object whose given field is 1" + OfType("int"), 3389 Explain(m, &a)); 3390 3391 m = Field(&AStruct::x, GreaterThan(0)); 3392 EXPECT_EQ("which points to an object whose given field is 1" + OfType("int") + 3393 ", which is 1 more than 0", Explain(m, &a)); 3394 } 3395 3396 // A user-defined class for testing Property(). 3397 class AClass { 3398 public: 3399 AClass() : n_(0) {} 3400 3401 // A getter that returns a non-reference. 3402 int n() const { return n_; } 3403 3404 void set_n(int new_n) { n_ = new_n; } 3405 3406 // A getter that returns a reference to const. 3407 const string& s() const { return s_; } 3408 3409 void set_s(const string& new_s) { s_ = new_s; } 3410 3411 // A getter that returns a reference to non-const. 3412 double& x() const { return x_; } 3413 private: 3414 int n_; 3415 string s_; 3416 3417 static double x_; 3418 }; 3419 3420 double AClass::x_ = 0.0; 3421 3422 // A derived class for testing Property(). 3423 class DerivedClass : public AClass { 3424 private: 3425 int k_; 3426 }; 3427 3428 // Tests that Property(&Foo::property, ...) works when property() 3429 // returns a non-reference. 3430 TEST(PropertyTest, WorksForNonReferenceProperty) { 3431 Matcher<const AClass&> m = Property(&AClass::n, Ge(0)); 3432 3433 AClass a; 3434 a.set_n(1); 3435 EXPECT_TRUE(m.Matches(a)); 3436 3437 a.set_n(-1); 3438 EXPECT_FALSE(m.Matches(a)); 3439 } 3440 3441 // Tests that Property(&Foo::property, ...) works when property() 3442 // returns a reference to const. 3443 TEST(PropertyTest, WorksForReferenceToConstProperty) { 3444 Matcher<const AClass&> m = Property(&AClass::s, StartsWith("hi")); 3445 3446 AClass a; 3447 a.set_s("hill"); 3448 EXPECT_TRUE(m.Matches(a)); 3449 3450 a.set_s("hole"); 3451 EXPECT_FALSE(m.Matches(a)); 3452 } 3453 3454 // Tests that Property(&Foo::property, ...) works when property() 3455 // returns a reference to non-const. 3456 TEST(PropertyTest, WorksForReferenceToNonConstProperty) { 3457 double x = 0.0; 3458 AClass a; 3459 3460 Matcher<const AClass&> m = Property(&AClass::x, Ref(x)); 3461 EXPECT_FALSE(m.Matches(a)); 3462 3463 m = Property(&AClass::x, Not(Ref(x))); 3464 EXPECT_TRUE(m.Matches(a)); 3465 } 3466 3467 // Tests that Property(&Foo::property, ...) works when the argument is 3468 // passed by value. 3469 TEST(PropertyTest, WorksForByValueArgument) { 3470 Matcher<AClass> m = Property(&AClass::s, StartsWith("hi")); 3471 3472 AClass a; 3473 a.set_s("hill"); 3474 EXPECT_TRUE(m.Matches(a)); 3475 3476 a.set_s("hole"); 3477 EXPECT_FALSE(m.Matches(a)); 3478 } 3479 3480 // Tests that Property(&Foo::property, ...) works when the argument's 3481 // type is a sub-type of Foo. 3482 TEST(PropertyTest, WorksForArgumentOfSubType) { 3483 // The matcher expects a DerivedClass, but inside the Property() we 3484 // say AClass. 3485 Matcher<const DerivedClass&> m = Property(&AClass::n, Ge(0)); 3486 3487 DerivedClass d; 3488 d.set_n(1); 3489 EXPECT_TRUE(m.Matches(d)); 3490 3491 d.set_n(-1); 3492 EXPECT_FALSE(m.Matches(d)); 3493 } 3494 3495 // Tests that Property(&Foo::property, m) works when property()'s type 3496 // and m's argument type are compatible but different. 3497 TEST(PropertyTest, WorksForCompatibleMatcherType) { 3498 // n() returns an int but the inner matcher expects a signed char. 3499 Matcher<const AClass&> m = Property(&AClass::n, 3500 Matcher<signed char>(Ge(0))); 3501 3502 AClass a; 3503 EXPECT_TRUE(m.Matches(a)); 3504 a.set_n(-1); 3505 EXPECT_FALSE(m.Matches(a)); 3506 } 3507 3508 // Tests that Property() can describe itself. 3509 TEST(PropertyTest, CanDescribeSelf) { 3510 Matcher<const AClass&> m = Property(&AClass::n, Ge(0)); 3511 3512 EXPECT_EQ("is an object whose given property is >= 0", Describe(m)); 3513 EXPECT_EQ("is an object whose given property isn't >= 0", 3514 DescribeNegation(m)); 3515 } 3516 3517 // Tests that Property() can explain the match result. 3518 TEST(PropertyTest, CanExplainMatchResult) { 3519 Matcher<const AClass&> m = Property(&AClass::n, Ge(0)); 3520 3521 AClass a; 3522 a.set_n(1); 3523 EXPECT_EQ("whose given property is 1" + OfType("int"), Explain(m, a)); 3524 3525 m = Property(&AClass::n, GreaterThan(0)); 3526 EXPECT_EQ( 3527 "whose given property is 1" + OfType("int") + ", which is 1 more than 0", 3528 Explain(m, a)); 3529 } 3530 3531 // Tests that Property() works when the argument is a pointer to const. 3532 TEST(PropertyForPointerTest, WorksForPointerToConst) { 3533 Matcher<const AClass*> m = Property(&AClass::n, Ge(0)); 3534 3535 AClass a; 3536 a.set_n(1); 3537 EXPECT_TRUE(m.Matches(&a)); 3538 3539 a.set_n(-1); 3540 EXPECT_FALSE(m.Matches(&a)); 3541 } 3542 3543 // Tests that Property() works when the argument is a pointer to non-const. 3544 TEST(PropertyForPointerTest, WorksForPointerToNonConst) { 3545 Matcher<AClass*> m = Property(&AClass::s, StartsWith("hi")); 3546 3547 AClass a; 3548 a.set_s("hill"); 3549 EXPECT_TRUE(m.Matches(&a)); 3550 3551 a.set_s("hole"); 3552 EXPECT_FALSE(m.Matches(&a)); 3553 } 3554 3555 // Tests that Property() works when the argument is a reference to a 3556 // const pointer. 3557 TEST(PropertyForPointerTest, WorksForReferenceToConstPointer) { 3558 Matcher<AClass* const&> m = Property(&AClass::s, StartsWith("hi")); 3559 3560 AClass a; 3561 a.set_s("hill"); 3562 EXPECT_TRUE(m.Matches(&a)); 3563 3564 a.set_s("hole"); 3565 EXPECT_FALSE(m.Matches(&a)); 3566 } 3567 3568 // Tests that Property() does not match the NULL pointer. 3569 TEST(PropertyForPointerTest, WorksForReferenceToNonConstProperty) { 3570 Matcher<const AClass*> m = Property(&AClass::x, _); 3571 EXPECT_FALSE(m.Matches(NULL)); 3572 } 3573 3574 // Tests that Property(&Foo::property, ...) works when the argument's 3575 // type is a sub-type of const Foo*. 3576 TEST(PropertyForPointerTest, WorksForArgumentOfSubType) { 3577 // The matcher expects a DerivedClass, but inside the Property() we 3578 // say AClass. 3579 Matcher<const DerivedClass*> m = Property(&AClass::n, Ge(0)); 3580 3581 DerivedClass d; 3582 d.set_n(1); 3583 EXPECT_TRUE(m.Matches(&d)); 3584 3585 d.set_n(-1); 3586 EXPECT_FALSE(m.Matches(&d)); 3587 } 3588 3589 // Tests that Property() can describe itself when used to match a pointer. 3590 TEST(PropertyForPointerTest, CanDescribeSelf) { 3591 Matcher<const AClass*> m = Property(&AClass::n, Ge(0)); 3592 3593 EXPECT_EQ("is an object whose given property is >= 0", Describe(m)); 3594 EXPECT_EQ("is an object whose given property isn't >= 0", 3595 DescribeNegation(m)); 3596 } 3597 3598 // Tests that Property() can explain the result of matching a pointer. 3599 TEST(PropertyForPointerTest, CanExplainMatchResult) { 3600 Matcher<const AClass*> m = Property(&AClass::n, Ge(0)); 3601 3602 AClass a; 3603 a.set_n(1); 3604 EXPECT_EQ("", Explain(m, static_cast<const AClass*>(NULL))); 3605 EXPECT_EQ( 3606 "which points to an object whose given property is 1" + OfType("int"), 3607 Explain(m, &a)); 3608 3609 m = Property(&AClass::n, GreaterThan(0)); 3610 EXPECT_EQ("which points to an object whose given property is 1" + 3611 OfType("int") + ", which is 1 more than 0", 3612 Explain(m, &a)); 3613 } 3614 3615 // Tests ResultOf. 3616 3617 // Tests that ResultOf(f, ...) compiles and works as expected when f is a 3618 // function pointer. 3619 string IntToStringFunction(int input) { return input == 1 ? "foo" : "bar"; } 3620 3621 TEST(ResultOfTest, WorksForFunctionPointers) { 3622 Matcher<int> matcher = ResultOf(&IntToStringFunction, Eq(string("foo"))); 3623 3624 EXPECT_TRUE(matcher.Matches(1)); 3625 EXPECT_FALSE(matcher.Matches(2)); 3626 } 3627 3628 // Tests that ResultOf() can describe itself. 3629 TEST(ResultOfTest, CanDescribeItself) { 3630 Matcher<int> matcher = ResultOf(&IntToStringFunction, StrEq("foo")); 3631 3632 EXPECT_EQ("is mapped by the given callable to a value that " 3633 "is equal to \"foo\"", Describe(matcher)); 3634 EXPECT_EQ("is mapped by the given callable to a value that " 3635 "isn't equal to \"foo\"", DescribeNegation(matcher)); 3636 } 3637 3638 // Tests that ResultOf() can explain the match result. 3639 int IntFunction(int input) { return input == 42 ? 80 : 90; } 3640 3641 TEST(ResultOfTest, CanExplainMatchResult) { 3642 Matcher<int> matcher = ResultOf(&IntFunction, Ge(85)); 3643 EXPECT_EQ("which is mapped by the given callable to 90" + OfType("int"), 3644 Explain(matcher, 36)); 3645 3646 matcher = ResultOf(&IntFunction, GreaterThan(85)); 3647 EXPECT_EQ("which is mapped by the given callable to 90" + OfType("int") + 3648 ", which is 5 more than 85", Explain(matcher, 36)); 3649 } 3650 3651 // Tests that ResultOf(f, ...) compiles and works as expected when f(x) 3652 // returns a non-reference. 3653 TEST(ResultOfTest, WorksForNonReferenceResults) { 3654 Matcher<int> matcher = ResultOf(&IntFunction, Eq(80)); 3655 3656 EXPECT_TRUE(matcher.Matches(42)); 3657 EXPECT_FALSE(matcher.Matches(36)); 3658 } 3659 3660 // Tests that ResultOf(f, ...) compiles and works as expected when f(x) 3661 // returns a reference to non-const. 3662 double& DoubleFunction(double& input) { return input; } // NOLINT 3663 3664 Uncopyable& RefUncopyableFunction(Uncopyable& obj) { // NOLINT 3665 return obj; 3666 } 3667 3668 TEST(ResultOfTest, WorksForReferenceToNonConstResults) { 3669 double x = 3.14; 3670 double x2 = x; 3671 Matcher<double&> matcher = ResultOf(&DoubleFunction, Ref(x)); 3672 3673 EXPECT_TRUE(matcher.Matches(x)); 3674 EXPECT_FALSE(matcher.Matches(x2)); 3675 3676 // Test that ResultOf works with uncopyable objects 3677 Uncopyable obj(0); 3678 Uncopyable obj2(0); 3679 Matcher<Uncopyable&> matcher2 = 3680 ResultOf(&RefUncopyableFunction, Ref(obj)); 3681 3682 EXPECT_TRUE(matcher2.Matches(obj)); 3683 EXPECT_FALSE(matcher2.Matches(obj2)); 3684 } 3685 3686 // Tests that ResultOf(f, ...) compiles and works as expected when f(x) 3687 // returns a reference to const. 3688 const string& StringFunction(const string& input) { return input; } 3689 3690 TEST(ResultOfTest, WorksForReferenceToConstResults) { 3691 string s = "foo"; 3692 string s2 = s; 3693 Matcher<const string&> matcher = ResultOf(&StringFunction, Ref(s)); 3694 3695 EXPECT_TRUE(matcher.Matches(s)); 3696 EXPECT_FALSE(matcher.Matches(s2)); 3697 } 3698 3699 // Tests that ResultOf(f, m) works when f(x) and m's 3700 // argument types are compatible but different. 3701 TEST(ResultOfTest, WorksForCompatibleMatcherTypes) { 3702 // IntFunction() returns int but the inner matcher expects a signed char. 3703 Matcher<int> matcher = ResultOf(IntFunction, Matcher<signed char>(Ge(85))); 3704 3705 EXPECT_TRUE(matcher.Matches(36)); 3706 EXPECT_FALSE(matcher.Matches(42)); 3707 } 3708 3709 // Tests that the program aborts when ResultOf is passed 3710 // a NULL function pointer. 3711 TEST(ResultOfDeathTest, DiesOnNullFunctionPointers) { 3712 EXPECT_DEATH_IF_SUPPORTED( 3713 ResultOf(static_cast<string(*)(int dummy)>(NULL), Eq(string("foo"))), 3714 "NULL function pointer is passed into ResultOf\\(\\)\\."); 3715 } 3716 3717 // Tests that ResultOf(f, ...) compiles and works as expected when f is a 3718 // function reference. 3719 TEST(ResultOfTest, WorksForFunctionReferences) { 3720 Matcher<int> matcher = ResultOf(IntToStringFunction, StrEq("foo")); 3721 EXPECT_TRUE(matcher.Matches(1)); 3722 EXPECT_FALSE(matcher.Matches(2)); 3723 } 3724 3725 // Tests that ResultOf(f, ...) compiles and works as expected when f is a 3726 // function object. 3727 struct Functor : public ::std::unary_function<int, string> { 3728 result_type operator()(argument_type input) const { 3729 return IntToStringFunction(input); 3730 } 3731 }; 3732 3733 TEST(ResultOfTest, WorksForFunctors) { 3734 Matcher<int> matcher = ResultOf(Functor(), Eq(string("foo"))); 3735 3736 EXPECT_TRUE(matcher.Matches(1)); 3737 EXPECT_FALSE(matcher.Matches(2)); 3738 } 3739 3740 // Tests that ResultOf(f, ...) compiles and works as expected when f is a 3741 // functor with more then one operator() defined. ResultOf() must work 3742 // for each defined operator(). 3743 struct PolymorphicFunctor { 3744 typedef int result_type; 3745 int operator()(int n) { return n; } 3746 int operator()(const char* s) { return static_cast<int>(strlen(s)); } 3747 }; 3748 3749 TEST(ResultOfTest, WorksForPolymorphicFunctors) { 3750 Matcher<int> matcher_int = ResultOf(PolymorphicFunctor(), Ge(5)); 3751 3752 EXPECT_TRUE(matcher_int.Matches(10)); 3753 EXPECT_FALSE(matcher_int.Matches(2)); 3754 3755 Matcher<const char*> matcher_string = ResultOf(PolymorphicFunctor(), Ge(5)); 3756 3757 EXPECT_TRUE(matcher_string.Matches("long string")); 3758 EXPECT_FALSE(matcher_string.Matches("shrt")); 3759 } 3760 3761 const int* ReferencingFunction(const int& n) { return &n; } 3762 3763 struct ReferencingFunctor { 3764 typedef const int* result_type; 3765 result_type operator()(const int& n) { return &n; } 3766 }; 3767 3768 TEST(ResultOfTest, WorksForReferencingCallables) { 3769 const int n = 1; 3770 const int n2 = 1; 3771 Matcher<const int&> matcher2 = ResultOf(ReferencingFunction, Eq(&n)); 3772 EXPECT_TRUE(matcher2.Matches(n)); 3773 EXPECT_FALSE(matcher2.Matches(n2)); 3774 3775 Matcher<const int&> matcher3 = ResultOf(ReferencingFunctor(), Eq(&n)); 3776 EXPECT_TRUE(matcher3.Matches(n)); 3777 EXPECT_FALSE(matcher3.Matches(n2)); 3778 } 3779 3780 class DivisibleByImpl { 3781 public: 3782 explicit DivisibleByImpl(int a_divider) : divider_(a_divider) {} 3783 3784 // For testing using ExplainMatchResultTo() with polymorphic matchers. 3785 template <typename T> 3786 bool MatchAndExplain(const T& n, MatchResultListener* listener) const { 3787 *listener << "which is " << (n % divider_) << " modulo " 3788 << divider_; 3789 return (n % divider_) == 0; 3790 } 3791 3792 void DescribeTo(ostream* os) const { 3793 *os << "is divisible by " << divider_; 3794 } 3795 3796 void DescribeNegationTo(ostream* os) const { 3797 *os << "is not divisible by " << divider_; 3798 } 3799 3800 void set_divider(int a_divider) { divider_ = a_divider; } 3801 int divider() const { return divider_; } 3802 3803 private: 3804 int divider_; 3805 }; 3806 3807 PolymorphicMatcher<DivisibleByImpl> DivisibleBy(int n) { 3808 return MakePolymorphicMatcher(DivisibleByImpl(n)); 3809 } 3810 3811 // Tests that when AllOf() fails, only the first failing matcher is 3812 // asked to explain why. 3813 TEST(ExplainMatchResultTest, AllOf_False_False) { 3814 const Matcher<int> m = AllOf(DivisibleBy(4), DivisibleBy(3)); 3815 EXPECT_EQ("which is 1 modulo 4", Explain(m, 5)); 3816 } 3817 3818 // Tests that when AllOf() fails, only the first failing matcher is 3819 // asked to explain why. 3820 TEST(ExplainMatchResultTest, AllOf_False_True) { 3821 const Matcher<int> m = AllOf(DivisibleBy(4), DivisibleBy(3)); 3822 EXPECT_EQ("which is 2 modulo 4", Explain(m, 6)); 3823 } 3824 3825 // Tests that when AllOf() fails, only the first failing matcher is 3826 // asked to explain why. 3827 TEST(ExplainMatchResultTest, AllOf_True_False) { 3828 const Matcher<int> m = AllOf(Ge(1), DivisibleBy(3)); 3829 EXPECT_EQ("which is 2 modulo 3", Explain(m, 5)); 3830 } 3831 3832 // Tests that when AllOf() succeeds, all matchers are asked to explain 3833 // why. 3834 TEST(ExplainMatchResultTest, AllOf_True_True) { 3835 const Matcher<int> m = AllOf(DivisibleBy(2), DivisibleBy(3)); 3836 EXPECT_EQ("which is 0 modulo 2, and which is 0 modulo 3", Explain(m, 6)); 3837 } 3838 3839 TEST(ExplainMatchResultTest, AllOf_True_True_2) { 3840 const Matcher<int> m = AllOf(Ge(2), Le(3)); 3841 EXPECT_EQ("", Explain(m, 2)); 3842 } 3843 3844 TEST(ExplainmatcherResultTest, MonomorphicMatcher) { 3845 const Matcher<int> m = GreaterThan(5); 3846 EXPECT_EQ("which is 1 more than 5", Explain(m, 6)); 3847 } 3848 3849 // The following two tests verify that values without a public copy 3850 // ctor can be used as arguments to matchers like Eq(), Ge(), and etc 3851 // with the help of ByRef(). 3852 3853 class NotCopyable { 3854 public: 3855 explicit NotCopyable(int a_value) : value_(a_value) {} 3856 3857 int value() const { return value_; } 3858 3859 bool operator==(const NotCopyable& rhs) const { 3860 return value() == rhs.value(); 3861 } 3862 3863 bool operator>=(const NotCopyable& rhs) const { 3864 return value() >= rhs.value(); 3865 } 3866 private: 3867 int value_; 3868 3869 GTEST_DISALLOW_COPY_AND_ASSIGN_(NotCopyable); 3870 }; 3871 3872 TEST(ByRefTest, AllowsNotCopyableConstValueInMatchers) { 3873 const NotCopyable const_value1(1); 3874 const Matcher<const NotCopyable&> m = Eq(ByRef(const_value1)); 3875 3876 const NotCopyable n1(1), n2(2); 3877 EXPECT_TRUE(m.Matches(n1)); 3878 EXPECT_FALSE(m.Matches(n2)); 3879 } 3880 3881 TEST(ByRefTest, AllowsNotCopyableValueInMatchers) { 3882 NotCopyable value2(2); 3883 const Matcher<NotCopyable&> m = Ge(ByRef(value2)); 3884 3885 NotCopyable n1(1), n2(2); 3886 EXPECT_FALSE(m.Matches(n1)); 3887 EXPECT_TRUE(m.Matches(n2)); 3888 } 3889 3890 TEST(IsEmptyTest, ImplementsIsEmpty) { 3891 vector<int> container; 3892 EXPECT_THAT(container, IsEmpty()); 3893 container.push_back(0); 3894 EXPECT_THAT(container, Not(IsEmpty())); 3895 container.push_back(1); 3896 EXPECT_THAT(container, Not(IsEmpty())); 3897 } 3898 3899 TEST(IsEmptyTest, WorksWithString) { 3900 string text; 3901 EXPECT_THAT(text, IsEmpty()); 3902 text = "foo"; 3903 EXPECT_THAT(text, Not(IsEmpty())); 3904 text = string("\0", 1); 3905 EXPECT_THAT(text, Not(IsEmpty())); 3906 } 3907 3908 TEST(IsEmptyTest, CanDescribeSelf) { 3909 Matcher<vector<int> > m = IsEmpty(); 3910 EXPECT_EQ("is empty", Describe(m)); 3911 EXPECT_EQ("isn't empty", DescribeNegation(m)); 3912 } 3913 3914 TEST(IsEmptyTest, ExplainsResult) { 3915 Matcher<vector<int> > m = IsEmpty(); 3916 vector<int> container; 3917 EXPECT_EQ("", Explain(m, container)); 3918 container.push_back(0); 3919 EXPECT_EQ("whose size is 1", Explain(m, container)); 3920 } 3921 3922 TEST(SizeIsTest, ImplementsSizeIs) { 3923 vector<int> container; 3924 EXPECT_THAT(container, SizeIs(0)); 3925 EXPECT_THAT(container, Not(SizeIs(1))); 3926 container.push_back(0); 3927 EXPECT_THAT(container, Not(SizeIs(0))); 3928 EXPECT_THAT(container, SizeIs(1)); 3929 container.push_back(0); 3930 EXPECT_THAT(container, Not(SizeIs(0))); 3931 EXPECT_THAT(container, SizeIs(2)); 3932 } 3933 3934 TEST(SizeIsTest, WorksWithMap) { 3935 map<string, int> container; 3936 EXPECT_THAT(container, SizeIs(0)); 3937 EXPECT_THAT(container, Not(SizeIs(1))); 3938 container.insert(make_pair("foo", 1)); 3939 EXPECT_THAT(container, Not(SizeIs(0))); 3940 EXPECT_THAT(container, SizeIs(1)); 3941 container.insert(make_pair("bar", 2)); 3942 EXPECT_THAT(container, Not(SizeIs(0))); 3943 EXPECT_THAT(container, SizeIs(2)); 3944 } 3945 3946 TEST(SizeIsTest, WorksWithReferences) { 3947 vector<int> container; 3948 Matcher<const vector<int>&> m = SizeIs(1); 3949 EXPECT_THAT(container, Not(m)); 3950 container.push_back(0); 3951 EXPECT_THAT(container, m); 3952 } 3953 3954 TEST(SizeIsTest, CanDescribeSelf) { 3955 Matcher<vector<int> > m = SizeIs(2); 3956 EXPECT_EQ("size is equal to 2", Describe(m)); 3957 EXPECT_EQ("size isn't equal to 2", DescribeNegation(m)); 3958 } 3959 3960 TEST(SizeIsTest, ExplainsResult) { 3961 Matcher<vector<int> > m1 = SizeIs(2); 3962 Matcher<vector<int> > m2 = SizeIs(Lt(2u)); 3963 Matcher<vector<int> > m3 = SizeIs(AnyOf(0, 3)); 3964 Matcher<vector<int> > m4 = SizeIs(GreaterThan(1)); 3965 vector<int> container; 3966 EXPECT_EQ("whose size 0 doesn't match", Explain(m1, container)); 3967 EXPECT_EQ("whose size 0 matches", Explain(m2, container)); 3968 EXPECT_EQ("whose size 0 matches", Explain(m3, container)); 3969 EXPECT_EQ("whose size 0 doesn't match, which is 1 less than 1", 3970 Explain(m4, container)); 3971 container.push_back(0); 3972 container.push_back(0); 3973 EXPECT_EQ("whose size 2 matches", Explain(m1, container)); 3974 EXPECT_EQ("whose size 2 doesn't match", Explain(m2, container)); 3975 EXPECT_EQ("whose size 2 doesn't match", Explain(m3, container)); 3976 EXPECT_EQ("whose size 2 matches, which is 1 more than 1", 3977 Explain(m4, container)); 3978 } 3979 3980 #if GTEST_HAS_TYPED_TEST 3981 // Tests ContainerEq with different container types, and 3982 // different element types. 3983 3984 template <typename T> 3985 class ContainerEqTest : public testing::Test {}; 3986 3987 typedef testing::Types< 3988 set<int>, 3989 vector<size_t>, 3990 multiset<size_t>, 3991 list<int> > 3992 ContainerEqTestTypes; 3993 3994 TYPED_TEST_CASE(ContainerEqTest, ContainerEqTestTypes); 3995 3996 // Tests that the filled container is equal to itself. 3997 TYPED_TEST(ContainerEqTest, EqualsSelf) { 3998 static const int vals[] = {1, 1, 2, 3, 5, 8}; 3999 TypeParam my_set(vals, vals + 6); 4000 const Matcher<TypeParam> m = ContainerEq(my_set); 4001 EXPECT_TRUE(m.Matches(my_set)); 4002 EXPECT_EQ("", Explain(m, my_set)); 4003 } 4004 4005 // Tests that missing values are reported. 4006 TYPED_TEST(ContainerEqTest, ValueMissing) { 4007 static const int vals[] = {1, 1, 2, 3, 5, 8}; 4008 static const int test_vals[] = {2, 1, 8, 5}; 4009 TypeParam my_set(vals, vals + 6); 4010 TypeParam test_set(test_vals, test_vals + 4); 4011 const Matcher<TypeParam> m = ContainerEq(my_set); 4012 EXPECT_FALSE(m.Matches(test_set)); 4013 EXPECT_EQ("which doesn't have these expected elements: 3", 4014 Explain(m, test_set)); 4015 } 4016 4017 // Tests that added values are reported. 4018 TYPED_TEST(ContainerEqTest, ValueAdded) { 4019 static const int vals[] = {1, 1, 2, 3, 5, 8}; 4020 static const int test_vals[] = {1, 2, 3, 5, 8, 46}; 4021 TypeParam my_set(vals, vals + 6); 4022 TypeParam test_set(test_vals, test_vals + 6); 4023 const Matcher<const TypeParam&> m = ContainerEq(my_set); 4024 EXPECT_FALSE(m.Matches(test_set)); 4025 EXPECT_EQ("which has these unexpected elements: 46", Explain(m, test_set)); 4026 } 4027 4028 // Tests that added and missing values are reported together. 4029 TYPED_TEST(ContainerEqTest, ValueAddedAndRemoved) { 4030 static const int vals[] = {1, 1, 2, 3, 5, 8}; 4031 static const int test_vals[] = {1, 2, 3, 8, 46}; 4032 TypeParam my_set(vals, vals + 6); 4033 TypeParam test_set(test_vals, test_vals + 5); 4034 const Matcher<TypeParam> m = ContainerEq(my_set); 4035 EXPECT_FALSE(m.Matches(test_set)); 4036 EXPECT_EQ("which has these unexpected elements: 46,\n" 4037 "and doesn't have these expected elements: 5", 4038 Explain(m, test_set)); 4039 } 4040 4041 // Tests duplicated value -- expect no explanation. 4042 TYPED_TEST(ContainerEqTest, DuplicateDifference) { 4043 static const int vals[] = {1, 1, 2, 3, 5, 8}; 4044 static const int test_vals[] = {1, 2, 3, 5, 8}; 4045 TypeParam my_set(vals, vals + 6); 4046 TypeParam test_set(test_vals, test_vals + 5); 4047 const Matcher<const TypeParam&> m = ContainerEq(my_set); 4048 // Depending on the container, match may be true or false 4049 // But in any case there should be no explanation. 4050 EXPECT_EQ("", Explain(m, test_set)); 4051 } 4052 #endif // GTEST_HAS_TYPED_TEST 4053 4054 // Tests that mutliple missing values are reported. 4055 // Using just vector here, so order is predicatble. 4056 TEST(ContainerEqExtraTest, MultipleValuesMissing) { 4057 static const int vals[] = {1, 1, 2, 3, 5, 8}; 4058 static const int test_vals[] = {2, 1, 5}; 4059 vector<int> my_set(vals, vals + 6); 4060 vector<int> test_set(test_vals, test_vals + 3); 4061 const Matcher<vector<int> > m = ContainerEq(my_set); 4062 EXPECT_FALSE(m.Matches(test_set)); 4063 EXPECT_EQ("which doesn't have these expected elements: 3, 8", 4064 Explain(m, test_set)); 4065 } 4066 4067 // Tests that added values are reported. 4068 // Using just vector here, so order is predicatble. 4069 TEST(ContainerEqExtraTest, MultipleValuesAdded) { 4070 static const int vals[] = {1, 1, 2, 3, 5, 8}; 4071 static const int test_vals[] = {1, 2, 92, 3, 5, 8, 46}; 4072 list<size_t> my_set(vals, vals + 6); 4073 list<size_t> test_set(test_vals, test_vals + 7); 4074 const Matcher<const list<size_t>&> m = ContainerEq(my_set); 4075 EXPECT_FALSE(m.Matches(test_set)); 4076 EXPECT_EQ("which has these unexpected elements: 92, 46", 4077 Explain(m, test_set)); 4078 } 4079 4080 // Tests that added and missing values are reported together. 4081 TEST(ContainerEqExtraTest, MultipleValuesAddedAndRemoved) { 4082 static const int vals[] = {1, 1, 2, 3, 5, 8}; 4083 static const int test_vals[] = {1, 2, 3, 92, 46}; 4084 list<size_t> my_set(vals, vals + 6); 4085 list<size_t> test_set(test_vals, test_vals + 5); 4086 const Matcher<const list<size_t> > m = ContainerEq(my_set); 4087 EXPECT_FALSE(m.Matches(test_set)); 4088 EXPECT_EQ("which has these unexpected elements: 92, 46,\n" 4089 "and doesn't have these expected elements: 5, 8", 4090 Explain(m, test_set)); 4091 } 4092 4093 // Tests to see that duplicate elements are detected, 4094 // but (as above) not reported in the explanation. 4095 TEST(ContainerEqExtraTest, MultiSetOfIntDuplicateDifference) { 4096 static const int vals[] = {1, 1, 2, 3, 5, 8}; 4097 static const int test_vals[] = {1, 2, 3, 5, 8}; 4098 vector<int> my_set(vals, vals + 6); 4099 vector<int> test_set(test_vals, test_vals + 5); 4100 const Matcher<vector<int> > m = ContainerEq(my_set); 4101 EXPECT_TRUE(m.Matches(my_set)); 4102 EXPECT_FALSE(m.Matches(test_set)); 4103 // There is nothing to report when both sets contain all the same values. 4104 EXPECT_EQ("", Explain(m, test_set)); 4105 } 4106 4107 // Tests that ContainerEq works for non-trivial associative containers, 4108 // like maps. 4109 TEST(ContainerEqExtraTest, WorksForMaps) { 4110 map<int, std::string> my_map; 4111 my_map[0] = "a"; 4112 my_map[1] = "b"; 4113 4114 map<int, std::string> test_map; 4115 test_map[0] = "aa"; 4116 test_map[1] = "b"; 4117 4118 const Matcher<const map<int, std::string>&> m = ContainerEq(my_map); 4119 EXPECT_TRUE(m.Matches(my_map)); 4120 EXPECT_FALSE(m.Matches(test_map)); 4121 4122 EXPECT_EQ("which has these unexpected elements: (0, \"aa\"),\n" 4123 "and doesn't have these expected elements: (0, \"a\")", 4124 Explain(m, test_map)); 4125 } 4126 4127 TEST(ContainerEqExtraTest, WorksForNativeArray) { 4128 int a1[] = { 1, 2, 3 }; 4129 int a2[] = { 1, 2, 3 }; 4130 int b[] = { 1, 2, 4 }; 4131 4132 EXPECT_THAT(a1, ContainerEq(a2)); 4133 EXPECT_THAT(a1, Not(ContainerEq(b))); 4134 } 4135 4136 TEST(ContainerEqExtraTest, WorksForTwoDimensionalNativeArray) { 4137 const char a1[][3] = { "hi", "lo" }; 4138 const char a2[][3] = { "hi", "lo" }; 4139 const char b[][3] = { "lo", "hi" }; 4140 4141 // Tests using ContainerEq() in the first dimension. 4142 EXPECT_THAT(a1, ContainerEq(a2)); 4143 EXPECT_THAT(a1, Not(ContainerEq(b))); 4144 4145 // Tests using ContainerEq() in the second dimension. 4146 EXPECT_THAT(a1, ElementsAre(ContainerEq(a2[0]), ContainerEq(a2[1]))); 4147 EXPECT_THAT(a1, ElementsAre(Not(ContainerEq(b[0])), ContainerEq(a2[1]))); 4148 } 4149 4150 TEST(ContainerEqExtraTest, WorksForNativeArrayAsTuple) { 4151 const int a1[] = { 1, 2, 3 }; 4152 const int a2[] = { 1, 2, 3 }; 4153 const int b[] = { 1, 2, 3, 4 }; 4154 4155 const int* const p1 = a1; 4156 EXPECT_THAT(make_tuple(p1, 3), ContainerEq(a2)); 4157 EXPECT_THAT(make_tuple(p1, 3), Not(ContainerEq(b))); 4158 4159 const int c[] = { 1, 3, 2 }; 4160 EXPECT_THAT(make_tuple(p1, 3), Not(ContainerEq(c))); 4161 } 4162 4163 TEST(ContainerEqExtraTest, CopiesNativeArrayParameter) { 4164 std::string a1[][3] = { 4165 { "hi", "hello", "ciao" }, 4166 { "bye", "see you", "ciao" } 4167 }; 4168 4169 std::string a2[][3] = { 4170 { "hi", "hello", "ciao" }, 4171 { "bye", "see you", "ciao" } 4172 }; 4173 4174 const Matcher<const std::string(&)[2][3]> m = ContainerEq(a2); 4175 EXPECT_THAT(a1, m); 4176 4177 a2[0][0] = "ha"; 4178 EXPECT_THAT(a1, m); 4179 } 4180 4181 TEST(WhenSortedByTest, WorksForEmptyContainer) { 4182 const vector<int> numbers; 4183 EXPECT_THAT(numbers, WhenSortedBy(less<int>(), ElementsAre())); 4184 EXPECT_THAT(numbers, Not(WhenSortedBy(less<int>(), ElementsAre(1)))); 4185 } 4186 4187 TEST(WhenSortedByTest, WorksForNonEmptyContainer) { 4188 vector<unsigned> numbers; 4189 numbers.push_back(3); 4190 numbers.push_back(1); 4191 numbers.push_back(2); 4192 numbers.push_back(2); 4193 EXPECT_THAT(numbers, WhenSortedBy(greater<unsigned>(), 4194 ElementsAre(3, 2, 2, 1))); 4195 EXPECT_THAT(numbers, Not(WhenSortedBy(greater<unsigned>(), 4196 ElementsAre(1, 2, 2, 3)))); 4197 } 4198 4199 TEST(WhenSortedByTest, WorksForNonVectorContainer) { 4200 list<string> words; 4201 words.push_back("say"); 4202 words.push_back("hello"); 4203 words.push_back("world"); 4204 EXPECT_THAT(words, WhenSortedBy(less<string>(), 4205 ElementsAre("hello", "say", "world"))); 4206 EXPECT_THAT(words, Not(WhenSortedBy(less<string>(), 4207 ElementsAre("say", "hello", "world")))); 4208 } 4209 4210 TEST(WhenSortedByTest, WorksForNativeArray) { 4211 const int numbers[] = { 1, 3, 2, 4 }; 4212 const int sorted_numbers[] = { 1, 2, 3, 4 }; 4213 EXPECT_THAT(numbers, WhenSortedBy(less<int>(), ElementsAre(1, 2, 3, 4))); 4214 EXPECT_THAT(numbers, WhenSortedBy(less<int>(), 4215 ElementsAreArray(sorted_numbers))); 4216 EXPECT_THAT(numbers, Not(WhenSortedBy(less<int>(), ElementsAre(1, 3, 2, 4)))); 4217 } 4218 4219 TEST(WhenSortedByTest, CanDescribeSelf) { 4220 const Matcher<vector<int> > m = WhenSortedBy(less<int>(), ElementsAre(1, 2)); 4221 EXPECT_EQ("(when sorted) has 2 elements where\n" 4222 "element #0 is equal to 1,\n" 4223 "element #1 is equal to 2", 4224 Describe(m)); 4225 EXPECT_EQ("(when sorted) doesn't have 2 elements, or\n" 4226 "element #0 isn't equal to 1, or\n" 4227 "element #1 isn't equal to 2", 4228 DescribeNegation(m)); 4229 } 4230 4231 TEST(WhenSortedByTest, ExplainsMatchResult) { 4232 const int a[] = { 2, 1 }; 4233 EXPECT_EQ("which is { 1, 2 } when sorted, whose element #0 doesn't match", 4234 Explain(WhenSortedBy(less<int>(), ElementsAre(2, 3)), a)); 4235 EXPECT_EQ("which is { 1, 2 } when sorted", 4236 Explain(WhenSortedBy(less<int>(), ElementsAre(1, 2)), a)); 4237 } 4238 4239 // WhenSorted() is a simple wrapper on WhenSortedBy(). Hence we don't 4240 // need to test it as exhaustively as we test the latter. 4241 4242 TEST(WhenSortedTest, WorksForEmptyContainer) { 4243 const vector<int> numbers; 4244 EXPECT_THAT(numbers, WhenSorted(ElementsAre())); 4245 EXPECT_THAT(numbers, Not(WhenSorted(ElementsAre(1)))); 4246 } 4247 4248 TEST(WhenSortedTest, WorksForNonEmptyContainer) { 4249 list<string> words; 4250 words.push_back("3"); 4251 words.push_back("1"); 4252 words.push_back("2"); 4253 words.push_back("2"); 4254 EXPECT_THAT(words, WhenSorted(ElementsAre("1", "2", "2", "3"))); 4255 EXPECT_THAT(words, Not(WhenSorted(ElementsAre("3", "1", "2", "2")))); 4256 } 4257 4258 TEST(WhenSortedTest, WorksForMapTypes) { 4259 map<string, int> word_counts; 4260 word_counts["and"] = 1; 4261 word_counts["the"] = 1; 4262 word_counts["buffalo"] = 2; 4263 EXPECT_THAT(word_counts, WhenSorted(ElementsAre( 4264 Pair("and", 1), Pair("buffalo", 2), Pair("the", 1)))); 4265 EXPECT_THAT(word_counts, Not(WhenSorted(ElementsAre( 4266 Pair("and", 1), Pair("the", 1), Pair("buffalo", 2))))); 4267 } 4268 4269 TEST(WhenSortedTest, WorksForMultiMapTypes) { 4270 multimap<int, int> ifib; 4271 ifib.insert(make_pair(8, 6)); 4272 ifib.insert(make_pair(2, 3)); 4273 ifib.insert(make_pair(1, 1)); 4274 ifib.insert(make_pair(3, 4)); 4275 ifib.insert(make_pair(1, 2)); 4276 ifib.insert(make_pair(5, 5)); 4277 EXPECT_THAT(ifib, WhenSorted(ElementsAre(Pair(1, 1), 4278 Pair(1, 2), 4279 Pair(2, 3), 4280 Pair(3, 4), 4281 Pair(5, 5), 4282 Pair(8, 6)))); 4283 EXPECT_THAT(ifib, Not(WhenSorted(ElementsAre(Pair(8, 6), 4284 Pair(2, 3), 4285 Pair(1, 1), 4286 Pair(3, 4), 4287 Pair(1, 2), 4288 Pair(5, 5))))); 4289 } 4290 4291 TEST(WhenSortedTest, WorksForPolymorphicMatcher) { 4292 std::deque<int> d; 4293 d.push_back(2); 4294 d.push_back(1); 4295 EXPECT_THAT(d, WhenSorted(ElementsAre(1, 2))); 4296 EXPECT_THAT(d, Not(WhenSorted(ElementsAre(2, 1)))); 4297 } 4298 4299 TEST(WhenSortedTest, WorksForVectorConstRefMatcher) { 4300 std::deque<int> d; 4301 d.push_back(2); 4302 d.push_back(1); 4303 Matcher<const std::vector<int>&> vector_match = ElementsAre(1, 2); 4304 EXPECT_THAT(d, WhenSorted(vector_match)); 4305 Matcher<const std::vector<int>&> not_vector_match = ElementsAre(2, 1); 4306 EXPECT_THAT(d, Not(WhenSorted(not_vector_match))); 4307 } 4308 4309 // Deliberately bare pseudo-container. 4310 // Offers only begin() and end() accessors, yielding InputIterator. 4311 template <typename T> 4312 class Streamlike { 4313 private: 4314 class ConstIter; 4315 public: 4316 typedef ConstIter const_iterator; 4317 typedef T value_type; 4318 4319 template <typename InIter> 4320 Streamlike(InIter first, InIter last) : remainder_(first, last) {} 4321 4322 const_iterator begin() const { 4323 return const_iterator(this, remainder_.begin()); 4324 } 4325 const_iterator end() const { 4326 return const_iterator(this, remainder_.end()); 4327 } 4328 4329 private: 4330 class ConstIter : public std::iterator<std::input_iterator_tag, 4331 value_type, 4332 ptrdiff_t, 4333 const value_type&, 4334 const value_type*> { 4335 public: 4336 ConstIter(const Streamlike* s, 4337 typename std::list<value_type>::iterator pos) 4338 : s_(s), pos_(pos) {} 4339 4340 const value_type& operator*() const { return *pos_; } 4341 const value_type* operator->() const { return &*pos_; } 4342 ConstIter& operator++() { 4343 s_->remainder_.erase(pos_++); 4344 return *this; 4345 } 4346 4347 // *iter++ is required to work (see std::istreambuf_iterator). 4348 // (void)iter++ is also required to work. 4349 class PostIncrProxy { 4350 public: 4351 explicit PostIncrProxy(const value_type& value) : value_(value) {} 4352 value_type operator*() const { return value_; } 4353 private: 4354 value_type value_; 4355 }; 4356 PostIncrProxy operator++(int) { 4357 PostIncrProxy proxy(**this); 4358 ++(*this); 4359 return proxy; 4360 } 4361 4362 friend bool operator==(const ConstIter& a, const ConstIter& b) { 4363 return a.s_ == b.s_ && a.pos_ == b.pos_; 4364 } 4365 friend bool operator!=(const ConstIter& a, const ConstIter& b) { 4366 return !(a == b); 4367 } 4368 4369 private: 4370 const Streamlike* s_; 4371 typename std::list<value_type>::iterator pos_; 4372 }; 4373 4374 friend std::ostream& operator<<(std::ostream& os, const Streamlike& s) { 4375 os << "["; 4376 typedef typename std::list<value_type>::const_iterator Iter; 4377 const char* sep = ""; 4378 for (Iter it = s.remainder_.begin(); it != s.remainder_.end(); ++it) { 4379 os << sep << *it; 4380 sep = ","; 4381 } 4382 os << "]"; 4383 return os; 4384 } 4385 4386 mutable std::list<value_type> remainder_; // modified by iteration 4387 }; 4388 4389 TEST(StreamlikeTest, Iteration) { 4390 const int a[5] = { 2, 1, 4, 5, 3 }; 4391 Streamlike<int> s(a, a + 5); 4392 Streamlike<int>::const_iterator it = s.begin(); 4393 const int* ip = a; 4394 while (it != s.end()) { 4395 SCOPED_TRACE(ip - a); 4396 EXPECT_EQ(*ip++, *it++); 4397 } 4398 } 4399 4400 TEST(WhenSortedTest, WorksForStreamlike) { 4401 // Streamlike 'container' provides only minimal iterator support. 4402 // Its iterators are tagged with input_iterator_tag. 4403 const int a[5] = { 2, 1, 4, 5, 3 }; 4404 Streamlike<int> s(a, a + GMOCK_ARRAY_SIZE_(a)); 4405 EXPECT_THAT(s, WhenSorted(ElementsAre(1, 2, 3, 4, 5))); 4406 EXPECT_THAT(s, Not(WhenSorted(ElementsAre(2, 1, 4, 5, 3)))); 4407 } 4408 4409 TEST(WhenSortedTest, WorksForVectorConstRefMatcherOnStreamlike) { 4410 const int a[] = { 2, 1, 4, 5, 3 }; 4411 Streamlike<int> s(a, a + GMOCK_ARRAY_SIZE_(a)); 4412 Matcher<const std::vector<int>&> vector_match = ElementsAre(1, 2, 3, 4, 5); 4413 EXPECT_THAT(s, WhenSorted(vector_match)); 4414 EXPECT_THAT(s, Not(WhenSorted(ElementsAre(2, 1, 4, 5, 3)))); 4415 } 4416 4417 // Tests using ElementsAre() and ElementsAreArray() with stream-like 4418 // "containers". 4419 4420 TEST(ElemensAreStreamTest, WorksForStreamlike) { 4421 const int a[5] = { 1, 2, 3, 4, 5 }; 4422 Streamlike<int> s(a, a + GMOCK_ARRAY_SIZE_(a)); 4423 EXPECT_THAT(s, ElementsAre(1, 2, 3, 4, 5)); 4424 EXPECT_THAT(s, Not(ElementsAre(2, 1, 4, 5, 3))); 4425 } 4426 4427 TEST(ElemensAreArrayStreamTest, WorksForStreamlike) { 4428 const int a[5] = { 1, 2, 3, 4, 5 }; 4429 Streamlike<int> s(a, a + GMOCK_ARRAY_SIZE_(a)); 4430 4431 vector<int> expected; 4432 expected.push_back(1); 4433 expected.push_back(2); 4434 expected.push_back(3); 4435 expected.push_back(4); 4436 expected.push_back(5); 4437 EXPECT_THAT(s, ElementsAreArray(expected)); 4438 4439 expected[3] = 0; 4440 EXPECT_THAT(s, Not(ElementsAreArray(expected))); 4441 } 4442 4443 // Tests for UnorderedElementsAreArray() 4444 4445 TEST(UnorderedElementsAreArrayTest, SucceedsWhenExpected) { 4446 const int a[] = { 0, 1, 2, 3, 4 }; 4447 std::vector<int> s(a, a + GMOCK_ARRAY_SIZE_(a)); 4448 do { 4449 StringMatchResultListener listener; 4450 EXPECT_TRUE(ExplainMatchResult(UnorderedElementsAreArray(a), 4451 s, &listener)) << listener.str(); 4452 } while (std::next_permutation(s.begin(), s.end())); 4453 } 4454 4455 TEST(UnorderedElementsAreArrayTest, VectorBool) { 4456 const bool a[] = { 0, 1, 0, 1, 1 }; 4457 const bool b[] = { 1, 0, 1, 1, 0 }; 4458 std::vector<bool> expected(a, a + GMOCK_ARRAY_SIZE_(a)); 4459 std::vector<bool> actual(b, b + GMOCK_ARRAY_SIZE_(b)); 4460 StringMatchResultListener listener; 4461 EXPECT_TRUE(ExplainMatchResult(UnorderedElementsAreArray(expected), 4462 actual, &listener)) << listener.str(); 4463 } 4464 4465 TEST(UnorderedElementsAreArrayTest, WorksForStreamlike) { 4466 // Streamlike 'container' provides only minimal iterator support. 4467 // Its iterators are tagged with input_iterator_tag, and it has no 4468 // size() or empty() methods. 4469 const int a[5] = { 2, 1, 4, 5, 3 }; 4470 Streamlike<int> s(a, a + GMOCK_ARRAY_SIZE_(a)); 4471 4472 ::std::vector<int> expected; 4473 expected.push_back(1); 4474 expected.push_back(2); 4475 expected.push_back(3); 4476 expected.push_back(4); 4477 expected.push_back(5); 4478 EXPECT_THAT(s, UnorderedElementsAreArray(expected)); 4479 4480 expected.push_back(6); 4481 EXPECT_THAT(s, Not(UnorderedElementsAreArray(expected))); 4482 } 4483 4484 #if GTEST_LANG_CXX11 4485 4486 TEST(UnorderedElementsAreArrayTest, TakesInitializerList) { 4487 const int a[5] = { 2, 1, 4, 5, 3 }; 4488 EXPECT_THAT(a, UnorderedElementsAreArray({ 1, 2, 3, 4, 5 })); 4489 EXPECT_THAT(a, Not(UnorderedElementsAreArray({ 1, 2, 3, 4, 6 }))); 4490 } 4491 4492 TEST(UnorderedElementsAreArrayTest, TakesInitializerListOfCStrings) { 4493 const string a[5] = { "a", "b", "c", "d", "e" }; 4494 EXPECT_THAT(a, UnorderedElementsAreArray({ "a", "b", "c", "d", "e" })); 4495 EXPECT_THAT(a, Not(UnorderedElementsAreArray({ "a", "b", "c", "d", "ef" }))); 4496 } 4497 4498 TEST(UnorderedElementsAreArrayTest, TakesInitializerListOfSameTypedMatchers) { 4499 const int a[5] = { 2, 1, 4, 5, 3 }; 4500 EXPECT_THAT(a, UnorderedElementsAreArray( 4501 { Eq(1), Eq(2), Eq(3), Eq(4), Eq(5) })); 4502 EXPECT_THAT(a, Not(UnorderedElementsAreArray( 4503 { Eq(1), Eq(2), Eq(3), Eq(4), Eq(6) }))); 4504 } 4505 4506 TEST(UnorderedElementsAreArrayTest, 4507 TakesInitializerListOfDifferentTypedMatchers) { 4508 const int a[5] = { 2, 1, 4, 5, 3 }; 4509 // The compiler cannot infer the type of the initializer list if its 4510 // elements have different types. We must explicitly specify the 4511 // unified element type in this case. 4512 EXPECT_THAT(a, UnorderedElementsAreArray<Matcher<int> >( 4513 { Eq(1), Ne(-2), Ge(3), Le(4), Eq(5) })); 4514 EXPECT_THAT(a, Not(UnorderedElementsAreArray<Matcher<int> >( 4515 { Eq(1), Ne(-2), Ge(3), Le(4), Eq(6) }))); 4516 } 4517 4518 #endif // GTEST_LANG_CXX11 4519 4520 class UnorderedElementsAreTest : public testing::Test { 4521 protected: 4522 typedef std::vector<int> IntVec; 4523 }; 4524 4525 TEST_F(UnorderedElementsAreTest, SucceedsWhenExpected) { 4526 const int a[] = { 1, 2, 3 }; 4527 std::vector<int> s(a, a + GMOCK_ARRAY_SIZE_(a)); 4528 do { 4529 StringMatchResultListener listener; 4530 EXPECT_TRUE(ExplainMatchResult(UnorderedElementsAre(1, 2, 3), 4531 s, &listener)) << listener.str(); 4532 } while (std::next_permutation(s.begin(), s.end())); 4533 } 4534 4535 TEST_F(UnorderedElementsAreTest, FailsWhenAnElementMatchesNoMatcher) { 4536 const int a[] = { 1, 2, 3 }; 4537 std::vector<int> s(a, a + GMOCK_ARRAY_SIZE_(a)); 4538 std::vector<Matcher<int> > mv; 4539 mv.push_back(1); 4540 mv.push_back(2); 4541 mv.push_back(2); 4542 // The element with value '3' matches nothing: fail fast. 4543 StringMatchResultListener listener; 4544 EXPECT_FALSE(ExplainMatchResult(UnorderedElementsAreArray(mv), 4545 s, &listener)) << listener.str(); 4546 } 4547 4548 TEST_F(UnorderedElementsAreTest, WorksForStreamlike) { 4549 // Streamlike 'container' provides only minimal iterator support. 4550 // Its iterators are tagged with input_iterator_tag, and it has no 4551 // size() or empty() methods. 4552 const int a[5] = { 2, 1, 4, 5, 3 }; 4553 Streamlike<int> s(a, a + GMOCK_ARRAY_SIZE_(a)); 4554 4555 EXPECT_THAT(s, UnorderedElementsAre(1, 2, 3, 4, 5)); 4556 EXPECT_THAT(s, Not(UnorderedElementsAre(2, 2, 3, 4, 5))); 4557 } 4558 4559 // One naive implementation of the matcher runs in O(N!) time, which is too 4560 // slow for many real-world inputs. This test shows that our matcher can match 4561 // 100 inputs very quickly (a few milliseconds). An O(100!) is 10^158 4562 // iterations and obviously effectively incomputable. 4563 // [ RUN ] UnorderedElementsAreTest.Performance 4564 // [ OK ] UnorderedElementsAreTest.Performance (4 ms) 4565 TEST_F(UnorderedElementsAreTest, Performance) { 4566 std::vector<int> s; 4567 std::vector<Matcher<int> > mv; 4568 for (int i = 0; i < 100; ++i) { 4569 s.push_back(i); 4570 mv.push_back(_); 4571 } 4572 mv[50] = Eq(0); 4573 StringMatchResultListener listener; 4574 EXPECT_TRUE(ExplainMatchResult(UnorderedElementsAreArray(mv), 4575 s, &listener)) << listener.str(); 4576 } 4577 4578 // Another variant of 'Performance' with similar expectations. 4579 // [ RUN ] UnorderedElementsAreTest.PerformanceHalfStrict 4580 // [ OK ] UnorderedElementsAreTest.PerformanceHalfStrict (4 ms) 4581 TEST_F(UnorderedElementsAreTest, PerformanceHalfStrict) { 4582 std::vector<int> s; 4583 std::vector<Matcher<int> > mv; 4584 for (int i = 0; i < 100; ++i) { 4585 s.push_back(i); 4586 if (i & 1) { 4587 mv.push_back(_); 4588 } else { 4589 mv.push_back(i); 4590 } 4591 } 4592 StringMatchResultListener listener; 4593 EXPECT_TRUE(ExplainMatchResult(UnorderedElementsAreArray(mv), 4594 s, &listener)) << listener.str(); 4595 } 4596 4597 TEST_F(UnorderedElementsAreTest, FailMessageCountWrong) { 4598 std::vector<int> v; 4599 v.push_back(4); 4600 StringMatchResultListener listener; 4601 EXPECT_FALSE(ExplainMatchResult(UnorderedElementsAre(1, 2, 3), 4602 v, &listener)) << listener.str(); 4603 EXPECT_THAT(listener.str(), Eq("which has 1 element")); 4604 } 4605 4606 TEST_F(UnorderedElementsAreTest, FailMessageCountWrongZero) { 4607 std::vector<int> v; 4608 StringMatchResultListener listener; 4609 EXPECT_FALSE(ExplainMatchResult(UnorderedElementsAre(1, 2, 3), 4610 v, &listener)) << listener.str(); 4611 EXPECT_THAT(listener.str(), Eq("")); 4612 } 4613 4614 TEST_F(UnorderedElementsAreTest, FailMessageUnmatchedMatchers) { 4615 std::vector<int> v; 4616 v.push_back(1); 4617 v.push_back(1); 4618 StringMatchResultListener listener; 4619 EXPECT_FALSE(ExplainMatchResult(UnorderedElementsAre(1, 2), 4620 v, &listener)) << listener.str(); 4621 EXPECT_THAT( 4622 listener.str(), 4623 Eq("where the following matchers don't match any elements:\n" 4624 "matcher #1: is equal to 2")); 4625 } 4626 4627 TEST_F(UnorderedElementsAreTest, FailMessageUnmatchedElements) { 4628 std::vector<int> v; 4629 v.push_back(1); 4630 v.push_back(2); 4631 StringMatchResultListener listener; 4632 EXPECT_FALSE(ExplainMatchResult(UnorderedElementsAre(1, 1), 4633 v, &listener)) << listener.str(); 4634 EXPECT_THAT( 4635 listener.str(), 4636 Eq("where the following elements don't match any matchers:\n" 4637 "element #1: 2")); 4638 } 4639 4640 TEST_F(UnorderedElementsAreTest, FailMessageUnmatchedMatcherAndElement) { 4641 std::vector<int> v; 4642 v.push_back(2); 4643 v.push_back(3); 4644 StringMatchResultListener listener; 4645 EXPECT_FALSE(ExplainMatchResult(UnorderedElementsAre(1, 2), 4646 v, &listener)) << listener.str(); 4647 EXPECT_THAT( 4648 listener.str(), 4649 Eq("where" 4650 " the following matchers don't match any elements:\n" 4651 "matcher #0: is equal to 1\n" 4652 "and" 4653 " where" 4654 " the following elements don't match any matchers:\n" 4655 "element #1: 3")); 4656 } 4657 4658 // Test helper for formatting element, matcher index pairs in expectations. 4659 static string EMString(int element, int matcher) { 4660 stringstream ss; 4661 ss << "(element #" << element << ", matcher #" << matcher << ")"; 4662 return ss.str(); 4663 } 4664 4665 TEST_F(UnorderedElementsAreTest, FailMessageImperfectMatchOnly) { 4666 // A situation where all elements and matchers have a match 4667 // associated with them, but the max matching is not perfect. 4668 std::vector<string> v; 4669 v.push_back("a"); 4670 v.push_back("b"); 4671 v.push_back("c"); 4672 StringMatchResultListener listener; 4673 EXPECT_FALSE(ExplainMatchResult( 4674 UnorderedElementsAre("a", "a", AnyOf("b", "c")), v, &listener)) 4675 << listener.str(); 4676 4677 string prefix = 4678 "where no permutation of the elements can satisfy all matchers, " 4679 "and the closest match is 2 of 3 matchers with the " 4680 "pairings:\n"; 4681 4682 // We have to be a bit loose here, because there are 4 valid max matches. 4683 EXPECT_THAT( 4684 listener.str(), 4685 AnyOf(prefix + "{\n " + EMString(0, 0) + 4686 ",\n " + EMString(1, 2) + "\n}", 4687 prefix + "{\n " + EMString(0, 1) + 4688 ",\n " + EMString(1, 2) + "\n}", 4689 prefix + "{\n " + EMString(0, 0) + 4690 ",\n " + EMString(2, 2) + "\n}", 4691 prefix + "{\n " + EMString(0, 1) + 4692 ",\n " + EMString(2, 2) + "\n}")); 4693 } 4694 4695 TEST_F(UnorderedElementsAreTest, Describe) { 4696 EXPECT_THAT(Describe<IntVec>(UnorderedElementsAre()), 4697 Eq("is empty")); 4698 EXPECT_THAT( 4699 Describe<IntVec>(UnorderedElementsAre(345)), 4700 Eq("has 1 element and that element is equal to 345")); 4701 EXPECT_THAT( 4702 Describe<IntVec>(UnorderedElementsAre(111, 222, 333)), 4703 Eq("has 3 elements and there exists some permutation " 4704 "of elements such that:\n" 4705 " - element #0 is equal to 111, and\n" 4706 " - element #1 is equal to 222, and\n" 4707 " - element #2 is equal to 333")); 4708 } 4709 4710 TEST_F(UnorderedElementsAreTest, DescribeNegation) { 4711 EXPECT_THAT(DescribeNegation<IntVec>(UnorderedElementsAre()), 4712 Eq("isn't empty")); 4713 EXPECT_THAT( 4714 DescribeNegation<IntVec>(UnorderedElementsAre(345)), 4715 Eq("doesn't have 1 element, or has 1 element that isn't equal to 345")); 4716 EXPECT_THAT( 4717 DescribeNegation<IntVec>(UnorderedElementsAre(123, 234, 345)), 4718 Eq("doesn't have 3 elements, or there exists no permutation " 4719 "of elements such that:\n" 4720 " - element #0 is equal to 123, and\n" 4721 " - element #1 is equal to 234, and\n" 4722 " - element #2 is equal to 345")); 4723 } 4724 4725 namespace { 4726 4727 // Used as a check on the more complex max flow method used in the 4728 // real testing::internal::FindMaxBipartiteMatching. This method is 4729 // compatible but runs in worst-case factorial time, so we only 4730 // use it in testing for small problem sizes. 4731 template <typename Graph> 4732 class BacktrackingMaxBPMState { 4733 public: 4734 // Does not take ownership of 'g'. 4735 explicit BacktrackingMaxBPMState(const Graph* g) : graph_(g) { } 4736 4737 ElementMatcherPairs Compute() { 4738 if (graph_->LhsSize() == 0 || graph_->RhsSize() == 0) { 4739 return best_so_far_; 4740 } 4741 lhs_used_.assign(graph_->LhsSize(), kUnused); 4742 rhs_used_.assign(graph_->RhsSize(), kUnused); 4743 for (size_t irhs = 0; irhs < graph_->RhsSize(); ++irhs) { 4744 matches_.clear(); 4745 RecurseInto(irhs); 4746 if (best_so_far_.size() == graph_->RhsSize()) 4747 break; 4748 } 4749 return best_so_far_; 4750 } 4751 4752 private: 4753 static const size_t kUnused = static_cast<size_t>(-1); 4754 4755 void PushMatch(size_t lhs, size_t rhs) { 4756 matches_.push_back(ElementMatcherPair(lhs, rhs)); 4757 lhs_used_[lhs] = rhs; 4758 rhs_used_[rhs] = lhs; 4759 if (matches_.size() > best_so_far_.size()) { 4760 best_so_far_ = matches_; 4761 } 4762 } 4763 4764 void PopMatch() { 4765 const ElementMatcherPair& back = matches_.back(); 4766 lhs_used_[back.first] = kUnused; 4767 rhs_used_[back.second] = kUnused; 4768 matches_.pop_back(); 4769 } 4770 4771 bool RecurseInto(size_t irhs) { 4772 if (rhs_used_[irhs] != kUnused) { 4773 return true; 4774 } 4775 for (size_t ilhs = 0; ilhs < graph_->LhsSize(); ++ilhs) { 4776 if (lhs_used_[ilhs] != kUnused) { 4777 continue; 4778 } 4779 if (!graph_->HasEdge(ilhs, irhs)) { 4780 continue; 4781 } 4782 PushMatch(ilhs, irhs); 4783 if (best_so_far_.size() == graph_->RhsSize()) { 4784 return false; 4785 } 4786 for (size_t mi = irhs + 1; mi < graph_->RhsSize(); ++mi) { 4787 if (!RecurseInto(mi)) return false; 4788 } 4789 PopMatch(); 4790 } 4791 return true; 4792 } 4793 4794 const Graph* graph_; // not owned 4795 std::vector<size_t> lhs_used_; 4796 std::vector<size_t> rhs_used_; 4797 ElementMatcherPairs matches_; 4798 ElementMatcherPairs best_so_far_; 4799 }; 4800 4801 template <typename Graph> 4802 const size_t BacktrackingMaxBPMState<Graph>::kUnused; 4803 4804 } // namespace 4805 4806 // Implement a simple backtracking algorithm to determine if it is possible 4807 // to find one element per matcher, without reusing elements. 4808 template <typename Graph> 4809 ElementMatcherPairs 4810 FindBacktrackingMaxBPM(const Graph& g) { 4811 return BacktrackingMaxBPMState<Graph>(&g).Compute(); 4812 } 4813 4814 class BacktrackingBPMTest : public ::testing::Test { }; 4815 4816 // Tests the MaxBipartiteMatching algorithm with square matrices. 4817 // The single int param is the # of nodes on each of the left and right sides. 4818 class BipartiteTest : public ::testing::TestWithParam<int> { }; 4819 4820 // Verify all match graphs up to some moderate number of edges. 4821 TEST_P(BipartiteTest, Exhaustive) { 4822 int nodes = GetParam(); 4823 MatchMatrix graph(nodes, nodes); 4824 do { 4825 ElementMatcherPairs matches = 4826 internal::FindMaxBipartiteMatching(graph); 4827 EXPECT_EQ(FindBacktrackingMaxBPM(graph).size(), matches.size()) 4828 << "graph: " << graph.DebugString(); 4829 // Check that all elements of matches are in the graph. 4830 // Check that elements of first and second are unique. 4831 std::vector<bool> seen_element(graph.LhsSize()); 4832 std::vector<bool> seen_matcher(graph.RhsSize()); 4833 SCOPED_TRACE(PrintToString(matches)); 4834 for (size_t i = 0; i < matches.size(); ++i) { 4835 size_t ilhs = matches[i].first; 4836 size_t irhs = matches[i].second; 4837 EXPECT_TRUE(graph.HasEdge(ilhs, irhs)); 4838 EXPECT_FALSE(seen_element[ilhs]); 4839 EXPECT_FALSE(seen_matcher[irhs]); 4840 seen_element[ilhs] = true; 4841 seen_matcher[irhs] = true; 4842 } 4843 } while (graph.NextGraph()); 4844 } 4845 4846 INSTANTIATE_TEST_CASE_P(AllGraphs, BipartiteTest, 4847 ::testing::Range(0, 5)); 4848 4849 // Parameterized by a pair interpreted as (LhsSize, RhsSize). 4850 class BipartiteNonSquareTest 4851 : public ::testing::TestWithParam<std::pair<size_t, size_t> > { 4852 }; 4853 4854 TEST_F(BipartiteNonSquareTest, SimpleBacktracking) { 4855 // ....... 4856 // 0:-----\ : 4857 // 1:---\ | : 4858 // 2:---\ | : 4859 // 3:-\ | | : 4860 // :.......: 4861 // 0 1 2 4862 MatchMatrix g(4, 3); 4863 static const int kEdges[][2] = { {0, 2}, {1, 1}, {2, 1}, {3, 0} }; 4864 for (size_t i = 0; i < GMOCK_ARRAY_SIZE_(kEdges); ++i) { 4865 g.SetEdge(kEdges[i][0], kEdges[i][1], true); 4866 } 4867 EXPECT_THAT(FindBacktrackingMaxBPM(g), 4868 ElementsAre(Pair(3, 0), 4869 Pair(AnyOf(1, 2), 1), 4870 Pair(0, 2))) << g.DebugString(); 4871 } 4872 4873 // Verify a few nonsquare matrices. 4874 TEST_P(BipartiteNonSquareTest, Exhaustive) { 4875 size_t nlhs = GetParam().first; 4876 size_t nrhs = GetParam().second; 4877 MatchMatrix graph(nlhs, nrhs); 4878 do { 4879 EXPECT_EQ(FindBacktrackingMaxBPM(graph).size(), 4880 internal::FindMaxBipartiteMatching(graph).size()) 4881 << "graph: " << graph.DebugString() 4882 << "\nbacktracking: " 4883 << PrintToString(FindBacktrackingMaxBPM(graph)) 4884 << "\nmax flow: " 4885 << PrintToString(internal::FindMaxBipartiteMatching(graph)); 4886 } while (graph.NextGraph()); 4887 } 4888 4889 INSTANTIATE_TEST_CASE_P(AllGraphs, BipartiteNonSquareTest, 4890 testing::Values( 4891 std::make_pair(1, 2), 4892 std::make_pair(2, 1), 4893 std::make_pair(3, 2), 4894 std::make_pair(2, 3), 4895 std::make_pair(4, 1), 4896 std::make_pair(1, 4), 4897 std::make_pair(4, 3), 4898 std::make_pair(3, 4))); 4899 4900 class BipartiteRandomTest 4901 : public ::testing::TestWithParam<std::pair<int, int> > { 4902 }; 4903 4904 // Verifies a large sample of larger graphs. 4905 TEST_P(BipartiteRandomTest, LargerNets) { 4906 int nodes = GetParam().first; 4907 int iters = GetParam().second; 4908 MatchMatrix graph(nodes, nodes); 4909 4910 testing::internal::Int32 seed = GTEST_FLAG(random_seed); 4911 if (seed == 0) { 4912 seed = static_cast<testing::internal::Int32>(time(NULL)); 4913 } 4914 4915 for (; iters > 0; --iters, ++seed) { 4916 srand(static_cast<int>(seed)); 4917 graph.Randomize(); 4918 EXPECT_EQ(FindBacktrackingMaxBPM(graph).size(), 4919 internal::FindMaxBipartiteMatching(graph).size()) 4920 << " graph: " << graph.DebugString() 4921 << "\nTo reproduce the failure, rerun the test with the flag" 4922 " --" << GTEST_FLAG_PREFIX_ << "random_seed=" << seed; 4923 } 4924 } 4925 4926 // Test argument is a std::pair<int, int> representing (nodes, iters). 4927 INSTANTIATE_TEST_CASE_P(Samples, BipartiteRandomTest, 4928 testing::Values( 4929 std::make_pair(5, 10000), 4930 std::make_pair(6, 5000), 4931 std::make_pair(7, 2000), 4932 std::make_pair(8, 500), 4933 std::make_pair(9, 100))); 4934 4935 // Tests IsReadableTypeName(). 4936 4937 TEST(IsReadableTypeNameTest, ReturnsTrueForShortNames) { 4938 EXPECT_TRUE(IsReadableTypeName("int")); 4939 EXPECT_TRUE(IsReadableTypeName("const unsigned char*")); 4940 EXPECT_TRUE(IsReadableTypeName("MyMap<int, void*>")); 4941 EXPECT_TRUE(IsReadableTypeName("void (*)(int, bool)")); 4942 } 4943 4944 TEST(IsReadableTypeNameTest, ReturnsTrueForLongNonTemplateNonFunctionNames) { 4945 EXPECT_TRUE(IsReadableTypeName("my_long_namespace::MyClassName")); 4946 EXPECT_TRUE(IsReadableTypeName("int [5][6][7][8][9][10][11]")); 4947 EXPECT_TRUE(IsReadableTypeName("my_namespace::MyOuterClass::MyInnerClass")); 4948 } 4949 4950 TEST(IsReadableTypeNameTest, ReturnsFalseForLongTemplateNames) { 4951 EXPECT_FALSE( 4952 IsReadableTypeName("basic_string<char, std::char_traits<char> >")); 4953 EXPECT_FALSE(IsReadableTypeName("std::vector<int, std::alloc_traits<int> >")); 4954 } 4955 4956 TEST(IsReadableTypeNameTest, ReturnsFalseForLongFunctionTypeNames) { 4957 EXPECT_FALSE(IsReadableTypeName("void (&)(int, bool, char, float)")); 4958 } 4959 4960 // Tests JoinAsTuple(). 4961 4962 TEST(JoinAsTupleTest, JoinsEmptyTuple) { 4963 EXPECT_EQ("", JoinAsTuple(Strings())); 4964 } 4965 4966 TEST(JoinAsTupleTest, JoinsOneTuple) { 4967 const char* fields[] = { "1" }; 4968 EXPECT_EQ("1", JoinAsTuple(Strings(fields, fields + 1))); 4969 } 4970 4971 TEST(JoinAsTupleTest, JoinsTwoTuple) { 4972 const char* fields[] = { "1", "a" }; 4973 EXPECT_EQ("(1, a)", JoinAsTuple(Strings(fields, fields + 2))); 4974 } 4975 4976 TEST(JoinAsTupleTest, JoinsTenTuple) { 4977 const char* fields[] = { "1", "2", "3", "4", "5", "6", "7", "8", "9", "10" }; 4978 EXPECT_EQ("(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)", 4979 JoinAsTuple(Strings(fields, fields + 10))); 4980 } 4981 4982 // Tests FormatMatcherDescription(). 4983 4984 TEST(FormatMatcherDescriptionTest, WorksForEmptyDescription) { 4985 EXPECT_EQ("is even", 4986 FormatMatcherDescription(false, "IsEven", Strings())); 4987 EXPECT_EQ("not (is even)", 4988 FormatMatcherDescription(true, "IsEven", Strings())); 4989 4990 const char* params[] = { "5" }; 4991 EXPECT_EQ("equals 5", 4992 FormatMatcherDescription(false, "Equals", 4993 Strings(params, params + 1))); 4994 4995 const char* params2[] = { "5", "8" }; 4996 EXPECT_EQ("is in range (5, 8)", 4997 FormatMatcherDescription(false, "IsInRange", 4998 Strings(params2, params2 + 2))); 4999 } 5000 5001 // Tests PolymorphicMatcher::mutable_impl(). 5002 TEST(PolymorphicMatcherTest, CanAccessMutableImpl) { 5003 PolymorphicMatcher<DivisibleByImpl> m(DivisibleByImpl(42)); 5004 DivisibleByImpl& impl = m.mutable_impl(); 5005 EXPECT_EQ(42, impl.divider()); 5006 5007 impl.set_divider(0); 5008 EXPECT_EQ(0, m.mutable_impl().divider()); 5009 } 5010 5011 // Tests PolymorphicMatcher::impl(). 5012 TEST(PolymorphicMatcherTest, CanAccessImpl) { 5013 const PolymorphicMatcher<DivisibleByImpl> m(DivisibleByImpl(42)); 5014 const DivisibleByImpl& impl = m.impl(); 5015 EXPECT_EQ(42, impl.divider()); 5016 } 5017 5018 TEST(MatcherTupleTest, ExplainsMatchFailure) { 5019 stringstream ss1; 5020 ExplainMatchFailureTupleTo(make_tuple(Matcher<char>(Eq('a')), GreaterThan(5)), 5021 make_tuple('a', 10), &ss1); 5022 EXPECT_EQ("", ss1.str()); // Successful match. 5023 5024 stringstream ss2; 5025 ExplainMatchFailureTupleTo(make_tuple(GreaterThan(5), Matcher<char>(Eq('a'))), 5026 make_tuple(2, 'b'), &ss2); 5027 EXPECT_EQ(" Expected arg #0: is > 5\n" 5028 " Actual: 2, which is 3 less than 5\n" 5029 " Expected arg #1: is equal to 'a' (97, 0x61)\n" 5030 " Actual: 'b' (98, 0x62)\n", 5031 ss2.str()); // Failed match where both arguments need explanation. 5032 5033 stringstream ss3; 5034 ExplainMatchFailureTupleTo(make_tuple(GreaterThan(5), Matcher<char>(Eq('a'))), 5035 make_tuple(2, 'a'), &ss3); 5036 EXPECT_EQ(" Expected arg #0: is > 5\n" 5037 " Actual: 2, which is 3 less than 5\n", 5038 ss3.str()); // Failed match where only one argument needs 5039 // explanation. 5040 } 5041 5042 // Tests Each(). 5043 5044 TEST(EachTest, ExplainsMatchResultCorrectly) { 5045 set<int> a; // empty 5046 5047 Matcher<set<int> > m = Each(2); 5048 EXPECT_EQ("", Explain(m, a)); 5049 5050 Matcher<const int(&)[1]> n = Each(1); // NOLINT 5051 5052 const int b[1] = { 1 }; 5053 EXPECT_EQ("", Explain(n, b)); 5054 5055 n = Each(3); 5056 EXPECT_EQ("whose element #0 doesn't match", Explain(n, b)); 5057 5058 a.insert(1); 5059 a.insert(2); 5060 a.insert(3); 5061 m = Each(GreaterThan(0)); 5062 EXPECT_EQ("", Explain(m, a)); 5063 5064 m = Each(GreaterThan(10)); 5065 EXPECT_EQ("whose element #0 doesn't match, which is 9 less than 10", 5066 Explain(m, a)); 5067 } 5068 5069 TEST(EachTest, DescribesItselfCorrectly) { 5070 Matcher<vector<int> > m = Each(1); 5071 EXPECT_EQ("only contains elements that is equal to 1", Describe(m)); 5072 5073 Matcher<vector<int> > m2 = Not(m); 5074 EXPECT_EQ("contains some element that isn't equal to 1", Describe(m2)); 5075 } 5076 5077 TEST(EachTest, MatchesVectorWhenAllElementsMatch) { 5078 vector<int> some_vector; 5079 EXPECT_THAT(some_vector, Each(1)); 5080 some_vector.push_back(3); 5081 EXPECT_THAT(some_vector, Not(Each(1))); 5082 EXPECT_THAT(some_vector, Each(3)); 5083 some_vector.push_back(1); 5084 some_vector.push_back(2); 5085 EXPECT_THAT(some_vector, Not(Each(3))); 5086 EXPECT_THAT(some_vector, Each(Lt(3.5))); 5087 5088 vector<string> another_vector; 5089 another_vector.push_back("fee"); 5090 EXPECT_THAT(another_vector, Each(string("fee"))); 5091 another_vector.push_back("fie"); 5092 another_vector.push_back("foe"); 5093 another_vector.push_back("fum"); 5094 EXPECT_THAT(another_vector, Not(Each(string("fee")))); 5095 } 5096 5097 TEST(EachTest, MatchesMapWhenAllElementsMatch) { 5098 map<const char*, int> my_map; 5099 const char* bar = "a string"; 5100 my_map[bar] = 2; 5101 EXPECT_THAT(my_map, Each(make_pair(bar, 2))); 5102 5103 map<string, int> another_map; 5104 EXPECT_THAT(another_map, Each(make_pair(string("fee"), 1))); 5105 another_map["fee"] = 1; 5106 EXPECT_THAT(another_map, Each(make_pair(string("fee"), 1))); 5107 another_map["fie"] = 2; 5108 another_map["foe"] = 3; 5109 another_map["fum"] = 4; 5110 EXPECT_THAT(another_map, Not(Each(make_pair(string("fee"), 1)))); 5111 EXPECT_THAT(another_map, Not(Each(make_pair(string("fum"), 1)))); 5112 EXPECT_THAT(another_map, Each(Pair(_, Gt(0)))); 5113 } 5114 5115 TEST(EachTest, AcceptsMatcher) { 5116 const int a[] = { 1, 2, 3 }; 5117 EXPECT_THAT(a, Each(Gt(0))); 5118 EXPECT_THAT(a, Not(Each(Gt(1)))); 5119 } 5120 5121 TEST(EachTest, WorksForNativeArrayAsTuple) { 5122 const int a[] = { 1, 2 }; 5123 const int* const pointer = a; 5124 EXPECT_THAT(make_tuple(pointer, 2), Each(Gt(0))); 5125 EXPECT_THAT(make_tuple(pointer, 2), Not(Each(Gt(1)))); 5126 } 5127 5128 // For testing Pointwise(). 5129 class IsHalfOfMatcher { 5130 public: 5131 template <typename T1, typename T2> 5132 bool MatchAndExplain(const tuple<T1, T2>& a_pair, 5133 MatchResultListener* listener) const { 5134 if (get<0>(a_pair) == get<1>(a_pair)/2) { 5135 *listener << "where the second is " << get<1>(a_pair); 5136 return true; 5137 } else { 5138 *listener << "where the second/2 is " << get<1>(a_pair)/2; 5139 return false; 5140 } 5141 } 5142 5143 void DescribeTo(ostream* os) const { 5144 *os << "are a pair where the first is half of the second"; 5145 } 5146 5147 void DescribeNegationTo(ostream* os) const { 5148 *os << "are a pair where the first isn't half of the second"; 5149 } 5150 }; 5151 5152 PolymorphicMatcher<IsHalfOfMatcher> IsHalfOf() { 5153 return MakePolymorphicMatcher(IsHalfOfMatcher()); 5154 } 5155 5156 TEST(PointwiseTest, DescribesSelf) { 5157 vector<int> rhs; 5158 rhs.push_back(1); 5159 rhs.push_back(2); 5160 rhs.push_back(3); 5161 const Matcher<const vector<int>&> m = Pointwise(IsHalfOf(), rhs); 5162 EXPECT_EQ("contains 3 values, where each value and its corresponding value " 5163 "in { 1, 2, 3 } are a pair where the first is half of the second", 5164 Describe(m)); 5165 EXPECT_EQ("doesn't contain exactly 3 values, or contains a value x at some " 5166 "index i where x and the i-th value of { 1, 2, 3 } are a pair " 5167 "where the first isn't half of the second", 5168 DescribeNegation(m)); 5169 } 5170 5171 TEST(PointwiseTest, MakesCopyOfRhs) { 5172 list<signed char> rhs; 5173 rhs.push_back(2); 5174 rhs.push_back(4); 5175 5176 int lhs[] = { 1, 2 }; 5177 const Matcher<const int (&)[2]> m = Pointwise(IsHalfOf(), rhs); 5178 EXPECT_THAT(lhs, m); 5179 5180 // Changing rhs now shouldn't affect m, which made a copy of rhs. 5181 rhs.push_back(6); 5182 EXPECT_THAT(lhs, m); 5183 } 5184 5185 TEST(PointwiseTest, WorksForLhsNativeArray) { 5186 const int lhs[] = { 1, 2, 3 }; 5187 vector<int> rhs; 5188 rhs.push_back(2); 5189 rhs.push_back(4); 5190 rhs.push_back(6); 5191 EXPECT_THAT(lhs, Pointwise(Lt(), rhs)); 5192 EXPECT_THAT(lhs, Not(Pointwise(Gt(), rhs))); 5193 } 5194 5195 TEST(PointwiseTest, WorksForRhsNativeArray) { 5196 const int rhs[] = { 1, 2, 3 }; 5197 vector<int> lhs; 5198 lhs.push_back(2); 5199 lhs.push_back(4); 5200 lhs.push_back(6); 5201 EXPECT_THAT(lhs, Pointwise(Gt(), rhs)); 5202 EXPECT_THAT(lhs, Not(Pointwise(Lt(), rhs))); 5203 } 5204 5205 TEST(PointwiseTest, RejectsWrongSize) { 5206 const double lhs[2] = { 1, 2 }; 5207 const int rhs[1] = { 0 }; 5208 EXPECT_THAT(lhs, Not(Pointwise(Gt(), rhs))); 5209 EXPECT_EQ("which contains 2 values", 5210 Explain(Pointwise(Gt(), rhs), lhs)); 5211 5212 const int rhs2[3] = { 0, 1, 2 }; 5213 EXPECT_THAT(lhs, Not(Pointwise(Gt(), rhs2))); 5214 } 5215 5216 TEST(PointwiseTest, RejectsWrongContent) { 5217 const double lhs[3] = { 1, 2, 3 }; 5218 const int rhs[3] = { 2, 6, 4 }; 5219 EXPECT_THAT(lhs, Not(Pointwise(IsHalfOf(), rhs))); 5220 EXPECT_EQ("where the value pair (2, 6) at index #1 don't match, " 5221 "where the second/2 is 3", 5222 Explain(Pointwise(IsHalfOf(), rhs), lhs)); 5223 } 5224 5225 TEST(PointwiseTest, AcceptsCorrectContent) { 5226 const double lhs[3] = { 1, 2, 3 }; 5227 const int rhs[3] = { 2, 4, 6 }; 5228 EXPECT_THAT(lhs, Pointwise(IsHalfOf(), rhs)); 5229 EXPECT_EQ("", Explain(Pointwise(IsHalfOf(), rhs), lhs)); 5230 } 5231 5232 TEST(PointwiseTest, AllowsMonomorphicInnerMatcher) { 5233 const double lhs[3] = { 1, 2, 3 }; 5234 const int rhs[3] = { 2, 4, 6 }; 5235 const Matcher<tuple<const double&, const int&> > m1 = IsHalfOf(); 5236 EXPECT_THAT(lhs, Pointwise(m1, rhs)); 5237 EXPECT_EQ("", Explain(Pointwise(m1, rhs), lhs)); 5238 5239 // This type works as a tuple<const double&, const int&> can be 5240 // implicitly cast to tuple<double, int>. 5241 const Matcher<tuple<double, int> > m2 = IsHalfOf(); 5242 EXPECT_THAT(lhs, Pointwise(m2, rhs)); 5243 EXPECT_EQ("", Explain(Pointwise(m2, rhs), lhs)); 5244 } 5245 5246 } // namespace gmock_matchers_test 5247 } // namespace testing