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 // Google Mock - a framework for writing C++ mock classes. 31 // 32 // This file tests some commonly used argument matchers. 33 34 #include <algorithm> 35 #include <array> 36 #include <deque> 37 #include <forward_list> 38 #include <iterator> 39 #include <list> 40 #include <memory> 41 #include <ostream> 42 #include <string> 43 #include <tuple> 44 #include <vector> 45 46 #include "gtest/gtest.h" 47 48 // Silence warning C4244: 'initializing': conversion from 'int' to 'short', 49 // possible loss of data and C4100, unreferenced local parameter 50 GTEST_DISABLE_MSC_WARNINGS_PUSH_(4244 4100) 51 52 #include "test/gmock-matchers_test.h" 53 54 namespace testing { 55 namespace gmock_matchers_test { 56 namespace { 57 58 std::vector<std::unique_ptr<int>> MakeUniquePtrs(const std::vector<int>& ints) { 59 std::vector<std::unique_ptr<int>> pointers; 60 for (int i : ints) pointers.emplace_back(new int(i)); 61 return pointers; 62 } 63 64 std::string OfType(const std::string& type_name) { 65 #if GTEST_HAS_RTTI 66 return IsReadableTypeName(type_name) ? " (of type " + type_name + ")" : ""; 67 #else 68 return ""; 69 #endif 70 } 71 72 TEST(ContainsTest, WorksWithMoveOnly) { 73 ContainerHelper helper; 74 EXPECT_CALL(helper, Call(Contains(Pointee(2)))); 75 helper.Call(MakeUniquePtrs({1, 2})); 76 } 77 78 INSTANTIATE_GTEST_MATCHER_TEST_P(ElementsAreTest); 79 80 // Tests the variadic version of the ElementsAreMatcher 81 TEST(ElementsAreTest, HugeMatcher) { 82 vector<int> test_vector{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}; 83 84 EXPECT_THAT(test_vector, 85 ElementsAre(Eq(1), Eq(2), Lt(13), Eq(4), Eq(5), Eq(6), Eq(7), 86 Eq(8), Eq(9), Eq(10), Gt(1), Eq(12))); 87 } 88 89 // Tests the variadic version of the UnorderedElementsAreMatcher 90 TEST(ElementsAreTest, HugeMatcherStr) { 91 vector<std::string> test_vector{ 92 "literal_string", "", "", "", "", "", "", "", "", "", "", ""}; 93 94 EXPECT_THAT(test_vector, UnorderedElementsAre("literal_string", _, _, _, _, _, 95 _, _, _, _, _, _)); 96 } 97 98 // Tests the variadic version of the UnorderedElementsAreMatcher 99 TEST(ElementsAreTest, HugeMatcherUnordered) { 100 vector<int> test_vector{2, 1, 8, 5, 4, 6, 7, 3, 9, 12, 11, 10}; 101 102 EXPECT_THAT(test_vector, UnorderedElementsAre( 103 Eq(2), Eq(1), Gt(7), Eq(5), Eq(4), Eq(6), Eq(7), 104 Eq(3), Eq(9), Eq(12), Eq(11), Ne(122))); 105 } 106 107 // Tests that ASSERT_THAT() and EXPECT_THAT() work when the value 108 // matches the matcher. 109 TEST(MatcherAssertionTest, WorksWhenMatcherIsSatisfied) { 110 ASSERT_THAT(5, Ge(2)) << "This should succeed."; 111 ASSERT_THAT("Foo", EndsWith("oo")); 112 EXPECT_THAT(2, AllOf(Le(7), Ge(0))) << "This should succeed too."; 113 EXPECT_THAT("Hello", StartsWith("Hell")); 114 } 115 116 // Tests that ASSERT_THAT() and EXPECT_THAT() work when the value 117 // doesn't match the matcher. 118 TEST(MatcherAssertionTest, WorksWhenMatcherIsNotSatisfied) { 119 // 'n' must be static as it is used in an EXPECT_FATAL_FAILURE(), 120 // which cannot reference auto variables. 121 static unsigned short n; // NOLINT 122 n = 5; 123 124 EXPECT_FATAL_FAILURE(ASSERT_THAT(n, Gt(10)), 125 "Value of: n\n" 126 "Expected: is > 10\n" 127 " Actual: 5" + 128 OfType("unsigned short")); 129 n = 0; 130 EXPECT_NONFATAL_FAILURE(EXPECT_THAT(n, AllOf(Le(7), Ge(5))), 131 "Value of: n\n" 132 "Expected: (is <= 7) and (is >= 5)\n" 133 " Actual: 0" + 134 OfType("unsigned short")); 135 } 136 137 // Tests that ASSERT_THAT() and EXPECT_THAT() work when the argument 138 // has a reference type. 139 TEST(MatcherAssertionTest, WorksForByRefArguments) { 140 // We use a static variable here as EXPECT_FATAL_FAILURE() cannot 141 // reference auto variables. 142 static int n; 143 n = 0; 144 EXPECT_THAT(n, AllOf(Le(7), Ref(n))); 145 EXPECT_FATAL_FAILURE(ASSERT_THAT(n, Not(Ref(n))), 146 "Value of: n\n" 147 "Expected: does not reference the variable @"); 148 // Tests the "Actual" part. 149 EXPECT_FATAL_FAILURE(ASSERT_THAT(n, Not(Ref(n))), 150 "Actual: 0" + OfType("int") + ", which is located @"); 151 } 152 153 // Tests that ASSERT_THAT() and EXPECT_THAT() work when the matcher is 154 // monomorphic. 155 TEST(MatcherAssertionTest, WorksForMonomorphicMatcher) { 156 Matcher<const char*> starts_with_he = StartsWith("he"); 157 ASSERT_THAT("hello", starts_with_he); 158 159 Matcher<const std::string&> ends_with_ok = EndsWith("ok"); 160 ASSERT_THAT("book", ends_with_ok); 161 const std::string bad = "bad"; 162 EXPECT_NONFATAL_FAILURE(EXPECT_THAT(bad, ends_with_ok), 163 "Value of: bad\n" 164 "Expected: ends with \"ok\"\n" 165 " Actual: \"bad\""); 166 Matcher<int> is_greater_than_5 = Gt(5); 167 EXPECT_NONFATAL_FAILURE(EXPECT_THAT(5, is_greater_than_5), 168 "Value of: 5\n" 169 "Expected: is > 5\n" 170 " Actual: 5" + 171 OfType("int")); 172 } 173 174 TEST(PointeeTest, RawPointer) { 175 const Matcher<int*> m = Pointee(Ge(0)); 176 177 int n = 1; 178 EXPECT_TRUE(m.Matches(&n)); 179 n = -1; 180 EXPECT_FALSE(m.Matches(&n)); 181 EXPECT_FALSE(m.Matches(nullptr)); 182 } 183 184 TEST(PointeeTest, RawPointerToConst) { 185 const Matcher<const double*> m = Pointee(Ge(0)); 186 187 double x = 1; 188 EXPECT_TRUE(m.Matches(&x)); 189 x = -1; 190 EXPECT_FALSE(m.Matches(&x)); 191 EXPECT_FALSE(m.Matches(nullptr)); 192 } 193 194 TEST(PointeeTest, ReferenceToConstRawPointer) { 195 const Matcher<int* const&> m = Pointee(Ge(0)); 196 197 int n = 1; 198 EXPECT_TRUE(m.Matches(&n)); 199 n = -1; 200 EXPECT_FALSE(m.Matches(&n)); 201 EXPECT_FALSE(m.Matches(nullptr)); 202 } 203 204 TEST(PointeeTest, ReferenceToNonConstRawPointer) { 205 const Matcher<double*&> m = Pointee(Ge(0)); 206 207 double x = 1.0; 208 double* p = &x; 209 EXPECT_TRUE(m.Matches(p)); 210 x = -1; 211 EXPECT_FALSE(m.Matches(p)); 212 p = nullptr; 213 EXPECT_FALSE(m.Matches(p)); 214 } 215 216 TEST(PointeeTest, SmartPointer) { 217 const Matcher<std::unique_ptr<int>> m = Pointee(Ge(0)); 218 219 std::unique_ptr<int> n(new int(1)); 220 EXPECT_TRUE(m.Matches(n)); 221 } 222 223 TEST(PointeeTest, SmartPointerToConst) { 224 const Matcher<std::unique_ptr<const int>> m = Pointee(Ge(0)); 225 226 // There's no implicit conversion from unique_ptr<int> to const 227 // unique_ptr<const int>, so we must pass a unique_ptr<const int> into the 228 // matcher. 229 std::unique_ptr<const int> n(new int(1)); 230 EXPECT_TRUE(m.Matches(n)); 231 } 232 233 TEST(PointerTest, RawPointer) { 234 int n = 1; 235 const Matcher<int*> m = Pointer(Eq(&n)); 236 237 EXPECT_TRUE(m.Matches(&n)); 238 239 int* p = nullptr; 240 EXPECT_FALSE(m.Matches(p)); 241 EXPECT_FALSE(m.Matches(nullptr)); 242 } 243 244 TEST(PointerTest, RawPointerToConst) { 245 int n = 1; 246 const Matcher<const int*> m = Pointer(Eq(&n)); 247 248 EXPECT_TRUE(m.Matches(&n)); 249 250 int* p = nullptr; 251 EXPECT_FALSE(m.Matches(p)); 252 EXPECT_FALSE(m.Matches(nullptr)); 253 } 254 255 TEST(PointerTest, SmartPointer) { 256 std::unique_ptr<int> n(new int(10)); 257 int* raw_n = n.get(); 258 const Matcher<std::unique_ptr<int>> m = Pointer(Eq(raw_n)); 259 260 EXPECT_TRUE(m.Matches(n)); 261 } 262 263 TEST(PointerTest, SmartPointerToConst) { 264 std::unique_ptr<const int> n(new int(10)); 265 const int* raw_n = n.get(); 266 const Matcher<std::unique_ptr<const int>> m = Pointer(Eq(raw_n)); 267 268 // There's no implicit conversion from unique_ptr<int> to const 269 // unique_ptr<const int>, so we must pass a unique_ptr<const int> into the 270 // matcher. 271 std::unique_ptr<const int> p(new int(10)); 272 EXPECT_FALSE(m.Matches(p)); 273 } 274 275 // Minimal const-propagating pointer. 276 template <typename T> 277 class ConstPropagatingPtr { 278 public: 279 typedef T element_type; 280 281 ConstPropagatingPtr() : val_() {} 282 explicit ConstPropagatingPtr(T* t) : val_(t) {} 283 ConstPropagatingPtr(const ConstPropagatingPtr& other) : val_(other.val_) {} 284 285 T* get() { return val_; } 286 T& operator*() { return *val_; } 287 // Most smart pointers return non-const T* and T& from the next methods. 288 const T* get() const { return val_; } 289 const T& operator*() const { return *val_; } 290 291 private: 292 T* val_; 293 }; 294 295 INSTANTIATE_GTEST_MATCHER_TEST_P(PointeeTest); 296 297 TEST(PointeeTest, WorksWithConstPropagatingPointers) { 298 const Matcher<ConstPropagatingPtr<int>> m = Pointee(Lt(5)); 299 int three = 3; 300 const ConstPropagatingPtr<int> co(&three); 301 ConstPropagatingPtr<int> o(&three); 302 EXPECT_TRUE(m.Matches(o)); 303 EXPECT_TRUE(m.Matches(co)); 304 *o = 6; 305 EXPECT_FALSE(m.Matches(o)); 306 EXPECT_FALSE(m.Matches(ConstPropagatingPtr<int>())); 307 } 308 309 TEST(PointeeTest, NeverMatchesNull) { 310 const Matcher<const char*> m = Pointee(_); 311 EXPECT_FALSE(m.Matches(nullptr)); 312 } 313 314 // Tests that we can write Pointee(value) instead of Pointee(Eq(value)). 315 TEST(PointeeTest, MatchesAgainstAValue) { 316 const Matcher<int*> m = Pointee(5); 317 318 int n = 5; 319 EXPECT_TRUE(m.Matches(&n)); 320 n = -1; 321 EXPECT_FALSE(m.Matches(&n)); 322 EXPECT_FALSE(m.Matches(nullptr)); 323 } 324 325 TEST(PointeeTest, CanDescribeSelf) { 326 const Matcher<int*> m = Pointee(Gt(3)); 327 EXPECT_EQ("points to a value that is > 3", Describe(m)); 328 EXPECT_EQ("does not point to a value that is > 3", DescribeNegation(m)); 329 } 330 331 TEST_P(PointeeTestP, CanExplainMatchResult) { 332 const Matcher<const std::string*> m = Pointee(StartsWith("Hi")); 333 334 EXPECT_EQ("", Explain(m, static_cast<const std::string*>(nullptr))); 335 336 const Matcher<long*> m2 = Pointee(GreaterThan(1)); // NOLINT 337 long n = 3; // NOLINT 338 EXPECT_EQ("which points to 3" + OfType("long") + ", which is 2 more than 1", 339 Explain(m2, &n)); 340 } 341 342 TEST(PointeeTest, AlwaysExplainsPointee) { 343 const Matcher<int*> m = Pointee(0); 344 int n = 42; 345 EXPECT_EQ("which points to 42" + OfType("int"), Explain(m, &n)); 346 } 347 348 // An uncopyable class. 349 class Uncopyable { 350 public: 351 Uncopyable() : value_(-1) {} 352 explicit Uncopyable(int a_value) : value_(a_value) {} 353 354 int value() const { return value_; } 355 void set_value(int i) { value_ = i; } 356 357 private: 358 int value_; 359 Uncopyable(const Uncopyable&) = delete; 360 Uncopyable& operator=(const Uncopyable&) = delete; 361 }; 362 363 // Returns true if and only if x.value() is positive. 364 bool ValueIsPositive(const Uncopyable& x) { return x.value() > 0; } 365 366 MATCHER_P(UncopyableIs, inner_matcher, "") { 367 return ExplainMatchResult(inner_matcher, arg.value(), result_listener); 368 } 369 370 // A user-defined struct for testing Field(). 371 struct AStruct { 372 AStruct() : x(0), y(1.0), z(5), p(nullptr) {} 373 AStruct(const AStruct& rhs) 374 : x(rhs.x), y(rhs.y), z(rhs.z.value()), p(rhs.p) {} 375 376 int x; // A non-const field. 377 const double y; // A const field. 378 Uncopyable z; // An uncopyable field. 379 const char* p; // A pointer field. 380 }; 381 382 // A derived struct for testing Field(). 383 struct DerivedStruct : public AStruct { 384 char ch; 385 }; 386 387 INSTANTIATE_GTEST_MATCHER_TEST_P(FieldTest); 388 389 // Tests that Field(&Foo::field, ...) works when field is non-const. 390 TEST(FieldTest, WorksForNonConstField) { 391 Matcher<AStruct> m = Field(&AStruct::x, Ge(0)); 392 Matcher<AStruct> m_with_name = Field("x", &AStruct::x, Ge(0)); 393 394 AStruct a; 395 EXPECT_TRUE(m.Matches(a)); 396 EXPECT_TRUE(m_with_name.Matches(a)); 397 a.x = -1; 398 EXPECT_FALSE(m.Matches(a)); 399 EXPECT_FALSE(m_with_name.Matches(a)); 400 } 401 402 // Tests that Field(&Foo::field, ...) works when field is const. 403 TEST(FieldTest, WorksForConstField) { 404 AStruct a; 405 406 Matcher<AStruct> m = Field(&AStruct::y, Ge(0.0)); 407 Matcher<AStruct> m_with_name = Field("y", &AStruct::y, Ge(0.0)); 408 EXPECT_TRUE(m.Matches(a)); 409 EXPECT_TRUE(m_with_name.Matches(a)); 410 m = Field(&AStruct::y, Le(0.0)); 411 m_with_name = Field("y", &AStruct::y, Le(0.0)); 412 EXPECT_FALSE(m.Matches(a)); 413 EXPECT_FALSE(m_with_name.Matches(a)); 414 } 415 416 // Tests that Field(&Foo::field, ...) works when field is not copyable. 417 TEST(FieldTest, WorksForUncopyableField) { 418 AStruct a; 419 420 Matcher<AStruct> m = Field(&AStruct::z, Truly(ValueIsPositive)); 421 EXPECT_TRUE(m.Matches(a)); 422 m = Field(&AStruct::z, Not(Truly(ValueIsPositive))); 423 EXPECT_FALSE(m.Matches(a)); 424 } 425 426 // Tests that Field(&Foo::field, ...) works when field is a pointer. 427 TEST(FieldTest, WorksForPointerField) { 428 // Matching against NULL. 429 Matcher<AStruct> m = Field(&AStruct::p, static_cast<const char*>(nullptr)); 430 AStruct a; 431 EXPECT_TRUE(m.Matches(a)); 432 a.p = "hi"; 433 EXPECT_FALSE(m.Matches(a)); 434 435 // Matching a pointer that is not NULL. 436 m = Field(&AStruct::p, StartsWith("hi")); 437 a.p = "hill"; 438 EXPECT_TRUE(m.Matches(a)); 439 a.p = "hole"; 440 EXPECT_FALSE(m.Matches(a)); 441 } 442 443 // Tests that Field() works when the object is passed by reference. 444 TEST(FieldTest, WorksForByRefArgument) { 445 Matcher<const AStruct&> m = Field(&AStruct::x, Ge(0)); 446 447 AStruct a; 448 EXPECT_TRUE(m.Matches(a)); 449 a.x = -1; 450 EXPECT_FALSE(m.Matches(a)); 451 } 452 453 // Tests that Field(&Foo::field, ...) works when the argument's type 454 // is a sub-type of Foo. 455 TEST(FieldTest, WorksForArgumentOfSubType) { 456 // Note that the matcher expects DerivedStruct but we say AStruct 457 // inside Field(). 458 Matcher<const DerivedStruct&> m = Field(&AStruct::x, Ge(0)); 459 460 DerivedStruct d; 461 EXPECT_TRUE(m.Matches(d)); 462 d.x = -1; 463 EXPECT_FALSE(m.Matches(d)); 464 } 465 466 // Tests that Field(&Foo::field, m) works when field's type and m's 467 // argument type are compatible but not the same. 468 TEST(FieldTest, WorksForCompatibleMatcherType) { 469 // The field is an int, but the inner matcher expects a signed char. 470 Matcher<const AStruct&> m = Field(&AStruct::x, Matcher<signed char>(Ge(0))); 471 472 AStruct a; 473 EXPECT_TRUE(m.Matches(a)); 474 a.x = -1; 475 EXPECT_FALSE(m.Matches(a)); 476 } 477 478 // Tests that Field() can describe itself. 479 TEST(FieldTest, CanDescribeSelf) { 480 Matcher<const AStruct&> m = Field(&AStruct::x, Ge(0)); 481 482 EXPECT_EQ("is an object whose given field is >= 0", Describe(m)); 483 EXPECT_EQ("is an object whose given field isn't >= 0", DescribeNegation(m)); 484 } 485 486 TEST(FieldTest, CanDescribeSelfWithFieldName) { 487 Matcher<const AStruct&> m = Field("field_name", &AStruct::x, Ge(0)); 488 489 EXPECT_EQ("is an object whose field `field_name` is >= 0", Describe(m)); 490 EXPECT_EQ("is an object whose field `field_name` isn't >= 0", 491 DescribeNegation(m)); 492 } 493 494 // Tests that Field() can explain the match result. 495 TEST_P(FieldTestP, CanExplainMatchResult) { 496 Matcher<const AStruct&> m = Field(&AStruct::x, Ge(0)); 497 498 AStruct a; 499 a.x = 1; 500 EXPECT_EQ("whose given field is 1" + OfType("int"), Explain(m, a)); 501 502 m = Field(&AStruct::x, GreaterThan(0)); 503 EXPECT_EQ( 504 "whose given field is 1" + OfType("int") + ", which is 1 more than 0", 505 Explain(m, a)); 506 } 507 508 TEST_P(FieldTestP, CanExplainMatchResultWithFieldName) { 509 Matcher<const AStruct&> m = Field("field_name", &AStruct::x, Ge(0)); 510 511 AStruct a; 512 a.x = 1; 513 EXPECT_EQ("whose field `field_name` is 1" + OfType("int"), Explain(m, a)); 514 515 m = Field("field_name", &AStruct::x, GreaterThan(0)); 516 EXPECT_EQ("whose field `field_name` is 1" + OfType("int") + 517 ", which is 1 more than 0", 518 Explain(m, a)); 519 } 520 521 INSTANTIATE_GTEST_MATCHER_TEST_P(FieldForPointerTest); 522 523 // Tests that Field() works when the argument is a pointer to const. 524 TEST(FieldForPointerTest, WorksForPointerToConst) { 525 Matcher<const AStruct*> m = Field(&AStruct::x, Ge(0)); 526 527 AStruct a; 528 EXPECT_TRUE(m.Matches(&a)); 529 a.x = -1; 530 EXPECT_FALSE(m.Matches(&a)); 531 } 532 533 // Tests that Field() works when the argument is a pointer to non-const. 534 TEST(FieldForPointerTest, WorksForPointerToNonConst) { 535 Matcher<AStruct*> m = Field(&AStruct::x, Ge(0)); 536 537 AStruct a; 538 EXPECT_TRUE(m.Matches(&a)); 539 a.x = -1; 540 EXPECT_FALSE(m.Matches(&a)); 541 } 542 543 // Tests that Field() works when the argument is a reference to a const pointer. 544 TEST(FieldForPointerTest, WorksForReferenceToConstPointer) { 545 Matcher<AStruct* const&> m = Field(&AStruct::x, Ge(0)); 546 547 AStruct a; 548 EXPECT_TRUE(m.Matches(&a)); 549 a.x = -1; 550 EXPECT_FALSE(m.Matches(&a)); 551 } 552 553 // Tests that Field() does not match the NULL pointer. 554 TEST(FieldForPointerTest, DoesNotMatchNull) { 555 Matcher<const AStruct*> m = Field(&AStruct::x, _); 556 EXPECT_FALSE(m.Matches(nullptr)); 557 } 558 559 // Tests that Field(&Foo::field, ...) works when the argument's type 560 // is a sub-type of const Foo*. 561 TEST(FieldForPointerTest, WorksForArgumentOfSubType) { 562 // Note that the matcher expects DerivedStruct but we say AStruct 563 // inside Field(). 564 Matcher<DerivedStruct*> m = Field(&AStruct::x, Ge(0)); 565 566 DerivedStruct d; 567 EXPECT_TRUE(m.Matches(&d)); 568 d.x = -1; 569 EXPECT_FALSE(m.Matches(&d)); 570 } 571 572 // Tests that Field() can describe itself when used to match a pointer. 573 TEST(FieldForPointerTest, CanDescribeSelf) { 574 Matcher<const AStruct*> m = Field(&AStruct::x, Ge(0)); 575 576 EXPECT_EQ("is an object whose given field is >= 0", Describe(m)); 577 EXPECT_EQ("is an object whose given field isn't >= 0", DescribeNegation(m)); 578 } 579 580 TEST(FieldForPointerTest, CanDescribeSelfWithFieldName) { 581 Matcher<const AStruct*> m = Field("field_name", &AStruct::x, Ge(0)); 582 583 EXPECT_EQ("is an object whose field `field_name` is >= 0", Describe(m)); 584 EXPECT_EQ("is an object whose field `field_name` isn't >= 0", 585 DescribeNegation(m)); 586 } 587 588 // Tests that Field() can explain the result of matching a pointer. 589 TEST_P(FieldForPointerTestP, CanExplainMatchResult) { 590 Matcher<const AStruct*> m = Field(&AStruct::x, Ge(0)); 591 592 AStruct a; 593 a.x = 1; 594 EXPECT_EQ("", Explain(m, static_cast<const AStruct*>(nullptr))); 595 EXPECT_EQ("which points to an object whose given field is 1" + OfType("int"), 596 Explain(m, &a)); 597 598 m = Field(&AStruct::x, GreaterThan(0)); 599 EXPECT_EQ("which points to an object whose given field is 1" + OfType("int") + 600 ", which is 1 more than 0", 601 Explain(m, &a)); 602 } 603 604 TEST_P(FieldForPointerTestP, CanExplainMatchResultWithFieldName) { 605 Matcher<const AStruct*> m = Field("field_name", &AStruct::x, Ge(0)); 606 607 AStruct a; 608 a.x = 1; 609 EXPECT_EQ("", Explain(m, static_cast<const AStruct*>(nullptr))); 610 EXPECT_EQ( 611 "which points to an object whose field `field_name` is 1" + OfType("int"), 612 Explain(m, &a)); 613 614 m = Field("field_name", &AStruct::x, GreaterThan(0)); 615 EXPECT_EQ("which points to an object whose field `field_name` is 1" + 616 OfType("int") + ", which is 1 more than 0", 617 Explain(m, &a)); 618 } 619 620 // A user-defined class for testing Property(). 621 class AClass { 622 public: 623 AClass() : n_(0) {} 624 625 // A getter that returns a non-reference. 626 int n() const { return n_; } 627 628 void set_n(int new_n) { n_ = new_n; } 629 630 // A getter that returns a reference to const. 631 const std::string& s() const { return s_; } 632 633 const std::string& s_ref() const& { return s_; } 634 635 void set_s(const std::string& new_s) { s_ = new_s; } 636 637 // A getter that returns a reference to non-const. 638 double& x() const { return x_; } 639 640 private: 641 int n_; 642 std::string s_; 643 644 static double x_; 645 }; 646 647 double AClass::x_ = 0.0; 648 649 // A derived class for testing Property(). 650 class DerivedClass : public AClass { 651 public: 652 int k() const { return k_; } 653 654 private: 655 int k_; 656 }; 657 658 INSTANTIATE_GTEST_MATCHER_TEST_P(PropertyTest); 659 660 // Tests that Property(&Foo::property, ...) works when property() 661 // returns a non-reference. 662 TEST(PropertyTest, WorksForNonReferenceProperty) { 663 Matcher<const AClass&> m = Property(&AClass::n, Ge(0)); 664 Matcher<const AClass&> m_with_name = Property("n", &AClass::n, Ge(0)); 665 666 AClass a; 667 a.set_n(1); 668 EXPECT_TRUE(m.Matches(a)); 669 EXPECT_TRUE(m_with_name.Matches(a)); 670 671 a.set_n(-1); 672 EXPECT_FALSE(m.Matches(a)); 673 EXPECT_FALSE(m_with_name.Matches(a)); 674 } 675 676 // Tests that Property(&Foo::property, ...) works when property() 677 // returns a reference to const. 678 TEST(PropertyTest, WorksForReferenceToConstProperty) { 679 Matcher<const AClass&> m = Property(&AClass::s, StartsWith("hi")); 680 Matcher<const AClass&> m_with_name = 681 Property("s", &AClass::s, StartsWith("hi")); 682 683 AClass a; 684 a.set_s("hill"); 685 EXPECT_TRUE(m.Matches(a)); 686 EXPECT_TRUE(m_with_name.Matches(a)); 687 688 a.set_s("hole"); 689 EXPECT_FALSE(m.Matches(a)); 690 EXPECT_FALSE(m_with_name.Matches(a)); 691 } 692 693 // Tests that Property(&Foo::property, ...) works when property() is 694 // ref-qualified. 695 TEST(PropertyTest, WorksForRefQualifiedProperty) { 696 Matcher<const AClass&> m = Property(&AClass::s_ref, StartsWith("hi")); 697 Matcher<const AClass&> m_with_name = 698 Property("s", &AClass::s_ref, StartsWith("hi")); 699 700 AClass a; 701 a.set_s("hill"); 702 EXPECT_TRUE(m.Matches(a)); 703 EXPECT_TRUE(m_with_name.Matches(a)); 704 705 a.set_s("hole"); 706 EXPECT_FALSE(m.Matches(a)); 707 EXPECT_FALSE(m_with_name.Matches(a)); 708 } 709 710 // Tests that Property(&Foo::property, ...) works when property() 711 // returns a reference to non-const. 712 TEST(PropertyTest, WorksForReferenceToNonConstProperty) { 713 double x = 0.0; 714 AClass a; 715 716 Matcher<const AClass&> m = Property(&AClass::x, Ref(x)); 717 EXPECT_FALSE(m.Matches(a)); 718 719 m = Property(&AClass::x, Not(Ref(x))); 720 EXPECT_TRUE(m.Matches(a)); 721 } 722 723 // Tests that Property(&Foo::property, ...) works when the argument is 724 // passed by value. 725 TEST(PropertyTest, WorksForByValueArgument) { 726 Matcher<AClass> m = Property(&AClass::s, StartsWith("hi")); 727 728 AClass a; 729 a.set_s("hill"); 730 EXPECT_TRUE(m.Matches(a)); 731 732 a.set_s("hole"); 733 EXPECT_FALSE(m.Matches(a)); 734 } 735 736 // Tests that Property(&Foo::property, ...) works when the argument's 737 // type is a sub-type of Foo. 738 TEST(PropertyTest, WorksForArgumentOfSubType) { 739 // The matcher expects a DerivedClass, but inside the Property() we 740 // say AClass. 741 Matcher<const DerivedClass&> m = Property(&AClass::n, Ge(0)); 742 743 DerivedClass d; 744 d.set_n(1); 745 EXPECT_TRUE(m.Matches(d)); 746 747 d.set_n(-1); 748 EXPECT_FALSE(m.Matches(d)); 749 } 750 751 // Tests that Property(&Foo::property, m) works when property()'s type 752 // and m's argument type are compatible but different. 753 TEST(PropertyTest, WorksForCompatibleMatcherType) { 754 // n() returns an int but the inner matcher expects a signed char. 755 Matcher<const AClass&> m = Property(&AClass::n, Matcher<signed char>(Ge(0))); 756 757 Matcher<const AClass&> m_with_name = 758 Property("n", &AClass::n, Matcher<signed char>(Ge(0))); 759 760 AClass a; 761 EXPECT_TRUE(m.Matches(a)); 762 EXPECT_TRUE(m_with_name.Matches(a)); 763 a.set_n(-1); 764 EXPECT_FALSE(m.Matches(a)); 765 EXPECT_FALSE(m_with_name.Matches(a)); 766 } 767 768 // Tests that Property() can describe itself. 769 TEST(PropertyTest, CanDescribeSelf) { 770 Matcher<const AClass&> m = Property(&AClass::n, Ge(0)); 771 772 EXPECT_EQ("is an object whose given property is >= 0", Describe(m)); 773 EXPECT_EQ("is an object whose given property isn't >= 0", 774 DescribeNegation(m)); 775 } 776 777 TEST(PropertyTest, CanDescribeSelfWithPropertyName) { 778 Matcher<const AClass&> m = Property("fancy_name", &AClass::n, Ge(0)); 779 780 EXPECT_EQ("is an object whose property `fancy_name` is >= 0", Describe(m)); 781 EXPECT_EQ("is an object whose property `fancy_name` isn't >= 0", 782 DescribeNegation(m)); 783 } 784 785 // Tests that Property() can explain the match result. 786 TEST_P(PropertyTestP, CanExplainMatchResult) { 787 Matcher<const AClass&> m = Property(&AClass::n, Ge(0)); 788 789 AClass a; 790 a.set_n(1); 791 EXPECT_EQ("whose given property is 1" + OfType("int"), Explain(m, a)); 792 793 m = Property(&AClass::n, GreaterThan(0)); 794 EXPECT_EQ( 795 "whose given property is 1" + OfType("int") + ", which is 1 more than 0", 796 Explain(m, a)); 797 } 798 799 TEST_P(PropertyTestP, CanExplainMatchResultWithPropertyName) { 800 Matcher<const AClass&> m = Property("fancy_name", &AClass::n, Ge(0)); 801 802 AClass a; 803 a.set_n(1); 804 EXPECT_EQ("whose property `fancy_name` is 1" + OfType("int"), Explain(m, a)); 805 806 m = Property("fancy_name", &AClass::n, GreaterThan(0)); 807 EXPECT_EQ("whose property `fancy_name` is 1" + OfType("int") + 808 ", which is 1 more than 0", 809 Explain(m, a)); 810 } 811 812 INSTANTIATE_GTEST_MATCHER_TEST_P(PropertyForPointerTest); 813 814 // Tests that Property() works when the argument is a pointer to const. 815 TEST(PropertyForPointerTest, WorksForPointerToConst) { 816 Matcher<const AClass*> m = Property(&AClass::n, Ge(0)); 817 818 AClass a; 819 a.set_n(1); 820 EXPECT_TRUE(m.Matches(&a)); 821 822 a.set_n(-1); 823 EXPECT_FALSE(m.Matches(&a)); 824 } 825 826 // Tests that Property() works when the argument is a pointer to non-const. 827 TEST(PropertyForPointerTest, WorksForPointerToNonConst) { 828 Matcher<AClass*> m = Property(&AClass::s, StartsWith("hi")); 829 830 AClass a; 831 a.set_s("hill"); 832 EXPECT_TRUE(m.Matches(&a)); 833 834 a.set_s("hole"); 835 EXPECT_FALSE(m.Matches(&a)); 836 } 837 838 // Tests that Property() works when the argument is a reference to a 839 // const pointer. 840 TEST(PropertyForPointerTest, WorksForReferenceToConstPointer) { 841 Matcher<AClass* const&> m = Property(&AClass::s, StartsWith("hi")); 842 843 AClass a; 844 a.set_s("hill"); 845 EXPECT_TRUE(m.Matches(&a)); 846 847 a.set_s("hole"); 848 EXPECT_FALSE(m.Matches(&a)); 849 } 850 851 // Tests that Property() does not match the NULL pointer. 852 TEST(PropertyForPointerTest, WorksForReferenceToNonConstProperty) { 853 Matcher<const AClass*> m = Property(&AClass::x, _); 854 EXPECT_FALSE(m.Matches(nullptr)); 855 } 856 857 // Tests that Property(&Foo::property, ...) works when the argument's 858 // type is a sub-type of const Foo*. 859 TEST(PropertyForPointerTest, WorksForArgumentOfSubType) { 860 // The matcher expects a DerivedClass, but inside the Property() we 861 // say AClass. 862 Matcher<const DerivedClass*> m = Property(&AClass::n, Ge(0)); 863 864 DerivedClass d; 865 d.set_n(1); 866 EXPECT_TRUE(m.Matches(&d)); 867 868 d.set_n(-1); 869 EXPECT_FALSE(m.Matches(&d)); 870 } 871 872 // Tests that Property() can describe itself when used to match a pointer. 873 TEST(PropertyForPointerTest, CanDescribeSelf) { 874 Matcher<const AClass*> m = Property(&AClass::n, Ge(0)); 875 876 EXPECT_EQ("is an object whose given property is >= 0", Describe(m)); 877 EXPECT_EQ("is an object whose given property isn't >= 0", 878 DescribeNegation(m)); 879 } 880 881 TEST(PropertyForPointerTest, CanDescribeSelfWithPropertyDescription) { 882 Matcher<const AClass*> m = Property("fancy_name", &AClass::n, Ge(0)); 883 884 EXPECT_EQ("is an object whose property `fancy_name` is >= 0", Describe(m)); 885 EXPECT_EQ("is an object whose property `fancy_name` isn't >= 0", 886 DescribeNegation(m)); 887 } 888 889 // Tests that Property() can explain the result of matching a pointer. 890 TEST_P(PropertyForPointerTestP, CanExplainMatchResult) { 891 Matcher<const AClass*> m = Property(&AClass::n, Ge(0)); 892 893 AClass a; 894 a.set_n(1); 895 EXPECT_EQ("", Explain(m, static_cast<const AClass*>(nullptr))); 896 EXPECT_EQ( 897 "which points to an object whose given property is 1" + OfType("int"), 898 Explain(m, &a)); 899 900 m = Property(&AClass::n, GreaterThan(0)); 901 EXPECT_EQ("which points to an object whose given property is 1" + 902 OfType("int") + ", which is 1 more than 0", 903 Explain(m, &a)); 904 } 905 906 TEST_P(PropertyForPointerTestP, CanExplainMatchResultWithPropertyName) { 907 Matcher<const AClass*> m = Property("fancy_name", &AClass::n, Ge(0)); 908 909 AClass a; 910 a.set_n(1); 911 EXPECT_EQ("", Explain(m, static_cast<const AClass*>(nullptr))); 912 EXPECT_EQ("which points to an object whose property `fancy_name` is 1" + 913 OfType("int"), 914 Explain(m, &a)); 915 916 m = Property("fancy_name", &AClass::n, GreaterThan(0)); 917 EXPECT_EQ("which points to an object whose property `fancy_name` is 1" + 918 OfType("int") + ", which is 1 more than 0", 919 Explain(m, &a)); 920 } 921 922 // Tests ResultOf. 923 924 // Tests that ResultOf(f, ...) compiles and works as expected when f is a 925 // function pointer. 926 std::string IntToStringFunction(int input) { 927 return input == 1 ? "foo" : "bar"; 928 } 929 930 INSTANTIATE_GTEST_MATCHER_TEST_P(ResultOfTest); 931 932 TEST(ResultOfTest, WorksForFunctionPointers) { 933 Matcher<int> matcher = ResultOf(&IntToStringFunction, Eq(std::string("foo"))); 934 935 EXPECT_TRUE(matcher.Matches(1)); 936 EXPECT_FALSE(matcher.Matches(2)); 937 } 938 939 // Tests that ResultOf() can describe itself. 940 TEST(ResultOfTest, CanDescribeItself) { 941 Matcher<int> matcher = ResultOf(&IntToStringFunction, StrEq("foo")); 942 943 EXPECT_EQ( 944 "is mapped by the given callable to a value that " 945 "is equal to \"foo\"", 946 Describe(matcher)); 947 EXPECT_EQ( 948 "is mapped by the given callable to a value that " 949 "isn't equal to \"foo\"", 950 DescribeNegation(matcher)); 951 } 952 953 // Tests that ResultOf() can describe itself when provided a result description. 954 TEST(ResultOfTest, CanDescribeItselfWithResultDescription) { 955 Matcher<int> matcher = 956 ResultOf("string conversion", &IntToStringFunction, StrEq("foo")); 957 958 EXPECT_EQ("whose string conversion is equal to \"foo\"", Describe(matcher)); 959 EXPECT_EQ("whose string conversion isn't equal to \"foo\"", 960 DescribeNegation(matcher)); 961 } 962 963 // Tests that ResultOf() can explain the match result. 964 int IntFunction(int input) { return input == 42 ? 80 : 90; } 965 966 TEST_P(ResultOfTestP, CanExplainMatchResult) { 967 Matcher<int> matcher = ResultOf(&IntFunction, Ge(85)); 968 EXPECT_EQ("which is mapped by the given callable to 90" + OfType("int"), 969 Explain(matcher, 36)); 970 971 matcher = ResultOf(&IntFunction, GreaterThan(85)); 972 EXPECT_EQ("which is mapped by the given callable to 90" + OfType("int") + 973 ", which is 5 more than 85", 974 Explain(matcher, 36)); 975 } 976 977 TEST_P(ResultOfTestP, CanExplainMatchResultWithResultDescription) { 978 Matcher<int> matcher = ResultOf("magic int conversion", &IntFunction, Ge(85)); 979 EXPECT_EQ("whose magic int conversion is 90" + OfType("int"), 980 Explain(matcher, 36)); 981 982 matcher = ResultOf("magic int conversion", &IntFunction, GreaterThan(85)); 983 EXPECT_EQ("whose magic int conversion is 90" + OfType("int") + 984 ", which is 5 more than 85", 985 Explain(matcher, 36)); 986 } 987 988 // Tests that ResultOf(f, ...) compiles and works as expected when f(x) 989 // returns a non-reference. 990 TEST(ResultOfTest, WorksForNonReferenceResults) { 991 Matcher<int> matcher = ResultOf(&IntFunction, Eq(80)); 992 993 EXPECT_TRUE(matcher.Matches(42)); 994 EXPECT_FALSE(matcher.Matches(36)); 995 } 996 997 // Tests that ResultOf(f, ...) compiles and works as expected when f(x) 998 // returns a reference to non-const. 999 double& DoubleFunction(double& input) { return input; } // NOLINT 1000 1001 Uncopyable& RefUncopyableFunction(Uncopyable& obj) { // NOLINT 1002 return obj; 1003 } 1004 1005 TEST(ResultOfTest, WorksForReferenceToNonConstResults) { 1006 double x = 3.14; 1007 double x2 = x; 1008 Matcher<double&> matcher = ResultOf(&DoubleFunction, Ref(x)); 1009 1010 EXPECT_TRUE(matcher.Matches(x)); 1011 EXPECT_FALSE(matcher.Matches(x2)); 1012 1013 // Test that ResultOf works with uncopyable objects 1014 Uncopyable obj(0); 1015 Uncopyable obj2(0); 1016 Matcher<Uncopyable&> matcher2 = ResultOf(&RefUncopyableFunction, Ref(obj)); 1017 1018 EXPECT_TRUE(matcher2.Matches(obj)); 1019 EXPECT_FALSE(matcher2.Matches(obj2)); 1020 } 1021 1022 // Tests that ResultOf(f, ...) compiles and works as expected when f(x) 1023 // returns a reference to const. 1024 const std::string& StringFunction(const std::string& input) { return input; } 1025 1026 TEST(ResultOfTest, WorksForReferenceToConstResults) { 1027 std::string s = "foo"; 1028 std::string s2 = s; 1029 Matcher<const std::string&> matcher = ResultOf(&StringFunction, Ref(s)); 1030 1031 EXPECT_TRUE(matcher.Matches(s)); 1032 EXPECT_FALSE(matcher.Matches(s2)); 1033 } 1034 1035 // Tests that ResultOf(f, m) works when f(x) and m's 1036 // argument types are compatible but different. 1037 TEST(ResultOfTest, WorksForCompatibleMatcherTypes) { 1038 // IntFunction() returns int but the inner matcher expects a signed char. 1039 Matcher<int> matcher = ResultOf(IntFunction, Matcher<signed char>(Ge(85))); 1040 1041 EXPECT_TRUE(matcher.Matches(36)); 1042 EXPECT_FALSE(matcher.Matches(42)); 1043 } 1044 1045 // Tests that the program aborts when ResultOf is passed 1046 // a NULL function pointer. 1047 TEST(ResultOfDeathTest, DiesOnNullFunctionPointers) { 1048 EXPECT_DEATH_IF_SUPPORTED( 1049 ResultOf(static_cast<std::string (*)(int dummy)>(nullptr), 1050 Eq(std::string("foo"))), 1051 "NULL function pointer is passed into ResultOf\\(\\)\\."); 1052 } 1053 1054 // Tests that ResultOf(f, ...) compiles and works as expected when f is a 1055 // function reference. 1056 TEST(ResultOfTest, WorksForFunctionReferences) { 1057 Matcher<int> matcher = ResultOf(IntToStringFunction, StrEq("foo")); 1058 EXPECT_TRUE(matcher.Matches(1)); 1059 EXPECT_FALSE(matcher.Matches(2)); 1060 } 1061 1062 // Tests that ResultOf(f, ...) compiles and works as expected when f is a 1063 // function object. 1064 struct Functor { 1065 std::string operator()(int input) const { return IntToStringFunction(input); } 1066 }; 1067 1068 TEST(ResultOfTest, WorksForFunctors) { 1069 Matcher<int> matcher = ResultOf(Functor(), Eq(std::string("foo"))); 1070 1071 EXPECT_TRUE(matcher.Matches(1)); 1072 EXPECT_FALSE(matcher.Matches(2)); 1073 } 1074 1075 // Tests that ResultOf(f, ...) compiles and works as expected when f is a 1076 // functor with more than one operator() defined. ResultOf() must work 1077 // for each defined operator(). 1078 struct PolymorphicFunctor { 1079 typedef int result_type; 1080 int operator()(int n) { return n; } 1081 int operator()(const char* s) { return static_cast<int>(strlen(s)); } 1082 std::string operator()(int* p) { return p ? "good ptr" : "null"; } 1083 }; 1084 1085 TEST(ResultOfTest, WorksForPolymorphicFunctors) { 1086 Matcher<int> matcher_int = ResultOf(PolymorphicFunctor(), Ge(5)); 1087 1088 EXPECT_TRUE(matcher_int.Matches(10)); 1089 EXPECT_FALSE(matcher_int.Matches(2)); 1090 1091 Matcher<const char*> matcher_string = ResultOf(PolymorphicFunctor(), Ge(5)); 1092 1093 EXPECT_TRUE(matcher_string.Matches("long string")); 1094 EXPECT_FALSE(matcher_string.Matches("shrt")); 1095 } 1096 1097 TEST(ResultOfTest, WorksForPolymorphicFunctorsIgnoringResultType) { 1098 Matcher<int*> matcher = ResultOf(PolymorphicFunctor(), "good ptr"); 1099 1100 int n = 0; 1101 EXPECT_TRUE(matcher.Matches(&n)); 1102 EXPECT_FALSE(matcher.Matches(nullptr)); 1103 } 1104 1105 TEST(ResultOfTest, WorksForLambdas) { 1106 Matcher<int> matcher = ResultOf( 1107 [](int str_len) { 1108 return std::string(static_cast<size_t>(str_len), 'x'); 1109 }, 1110 "xxx"); 1111 EXPECT_TRUE(matcher.Matches(3)); 1112 EXPECT_FALSE(matcher.Matches(1)); 1113 } 1114 1115 TEST(ResultOfTest, WorksForNonCopyableArguments) { 1116 Matcher<std::unique_ptr<int>> matcher = ResultOf( 1117 [](const std::unique_ptr<int>& str_len) { 1118 return std::string(static_cast<size_t>(*str_len), 'x'); 1119 }, 1120 "xxx"); 1121 EXPECT_TRUE(matcher.Matches(std::unique_ptr<int>(new int(3)))); 1122 EXPECT_FALSE(matcher.Matches(std::unique_ptr<int>(new int(1)))); 1123 } 1124 1125 const int* ReferencingFunction(const int& n) { return &n; } 1126 1127 struct ReferencingFunctor { 1128 typedef const int* result_type; 1129 result_type operator()(const int& n) { return &n; } 1130 }; 1131 1132 TEST(ResultOfTest, WorksForReferencingCallables) { 1133 const int n = 1; 1134 const int n2 = 1; 1135 Matcher<const int&> matcher2 = ResultOf(ReferencingFunction, Eq(&n)); 1136 EXPECT_TRUE(matcher2.Matches(n)); 1137 EXPECT_FALSE(matcher2.Matches(n2)); 1138 1139 Matcher<const int&> matcher3 = ResultOf(ReferencingFunctor(), Eq(&n)); 1140 EXPECT_TRUE(matcher3.Matches(n)); 1141 EXPECT_FALSE(matcher3.Matches(n2)); 1142 } 1143 1144 TEST(SizeIsTest, ImplementsSizeIs) { 1145 vector<int> container; 1146 EXPECT_THAT(container, SizeIs(0)); 1147 EXPECT_THAT(container, Not(SizeIs(1))); 1148 container.push_back(0); 1149 EXPECT_THAT(container, Not(SizeIs(0))); 1150 EXPECT_THAT(container, SizeIs(1)); 1151 container.push_back(0); 1152 EXPECT_THAT(container, Not(SizeIs(0))); 1153 EXPECT_THAT(container, SizeIs(2)); 1154 } 1155 1156 TEST(SizeIsTest, WorksWithMap) { 1157 map<std::string, int> container; 1158 EXPECT_THAT(container, SizeIs(0)); 1159 EXPECT_THAT(container, Not(SizeIs(1))); 1160 container.insert(make_pair("foo", 1)); 1161 EXPECT_THAT(container, Not(SizeIs(0))); 1162 EXPECT_THAT(container, SizeIs(1)); 1163 container.insert(make_pair("bar", 2)); 1164 EXPECT_THAT(container, Not(SizeIs(0))); 1165 EXPECT_THAT(container, SizeIs(2)); 1166 } 1167 1168 TEST(SizeIsTest, WorksWithReferences) { 1169 vector<int> container; 1170 Matcher<const vector<int>&> m = SizeIs(1); 1171 EXPECT_THAT(container, Not(m)); 1172 container.push_back(0); 1173 EXPECT_THAT(container, m); 1174 } 1175 1176 TEST(SizeIsTest, WorksWithMoveOnly) { 1177 ContainerHelper helper; 1178 EXPECT_CALL(helper, Call(SizeIs(3))); 1179 helper.Call(MakeUniquePtrs({1, 2, 3})); 1180 } 1181 1182 // SizeIs should work for any type that provides a size() member function. 1183 // For example, a size_type member type should not need to be provided. 1184 struct MinimalistCustomType { 1185 int size() const { return 1; } 1186 }; 1187 TEST(SizeIsTest, WorksWithMinimalistCustomType) { 1188 MinimalistCustomType container; 1189 EXPECT_THAT(container, SizeIs(1)); 1190 EXPECT_THAT(container, Not(SizeIs(0))); 1191 } 1192 1193 TEST(SizeIsTest, CanDescribeSelf) { 1194 Matcher<vector<int>> m = SizeIs(2); 1195 EXPECT_EQ("has a size that is equal to 2", Describe(m)); 1196 EXPECT_EQ("has a size that isn't equal to 2", DescribeNegation(m)); 1197 } 1198 1199 TEST(SizeIsTest, ExplainsResult) { 1200 Matcher<vector<int>> m1 = SizeIs(2); 1201 Matcher<vector<int>> m2 = SizeIs(Lt(2u)); 1202 Matcher<vector<int>> m3 = SizeIs(AnyOf(0, 3)); 1203 Matcher<vector<int>> m4 = SizeIs(Gt(1u)); 1204 vector<int> container; 1205 EXPECT_EQ("whose size 0 doesn't match", Explain(m1, container)); 1206 EXPECT_EQ("whose size 0 matches", Explain(m2, container)); 1207 EXPECT_EQ("whose size 0 matches", Explain(m3, container)); 1208 EXPECT_EQ("whose size 0 doesn't match", Explain(m4, container)); 1209 container.push_back(0); 1210 container.push_back(0); 1211 EXPECT_EQ("whose size 2 matches", Explain(m1, container)); 1212 EXPECT_EQ("whose size 2 doesn't match", Explain(m2, container)); 1213 EXPECT_EQ("whose size 2 doesn't match", Explain(m3, container)); 1214 EXPECT_EQ("whose size 2 matches", Explain(m4, container)); 1215 } 1216 1217 TEST(WhenSortedByTest, WorksForEmptyContainer) { 1218 const vector<int> numbers; 1219 EXPECT_THAT(numbers, WhenSortedBy(less<int>(), ElementsAre())); 1220 EXPECT_THAT(numbers, Not(WhenSortedBy(less<int>(), ElementsAre(1)))); 1221 } 1222 1223 TEST(WhenSortedByTest, WorksForNonEmptyContainer) { 1224 vector<unsigned> numbers; 1225 numbers.push_back(3); 1226 numbers.push_back(1); 1227 numbers.push_back(2); 1228 numbers.push_back(2); 1229 EXPECT_THAT(numbers, 1230 WhenSortedBy(greater<unsigned>(), ElementsAre(3, 2, 2, 1))); 1231 EXPECT_THAT(numbers, 1232 Not(WhenSortedBy(greater<unsigned>(), ElementsAre(1, 2, 2, 3)))); 1233 } 1234 1235 TEST(WhenSortedByTest, WorksForNonVectorContainer) { 1236 list<std::string> words; 1237 words.push_back("say"); 1238 words.push_back("hello"); 1239 words.push_back("world"); 1240 EXPECT_THAT(words, WhenSortedBy(less<std::string>(), 1241 ElementsAre("hello", "say", "world"))); 1242 EXPECT_THAT(words, Not(WhenSortedBy(less<std::string>(), 1243 ElementsAre("say", "hello", "world")))); 1244 } 1245 1246 TEST(WhenSortedByTest, WorksForNativeArray) { 1247 const int numbers[] = {1, 3, 2, 4}; 1248 const int sorted_numbers[] = {1, 2, 3, 4}; 1249 EXPECT_THAT(numbers, WhenSortedBy(less<int>(), ElementsAre(1, 2, 3, 4))); 1250 EXPECT_THAT(numbers, 1251 WhenSortedBy(less<int>(), ElementsAreArray(sorted_numbers))); 1252 EXPECT_THAT(numbers, Not(WhenSortedBy(less<int>(), ElementsAre(1, 3, 2, 4)))); 1253 } 1254 1255 TEST(WhenSortedByTest, CanDescribeSelf) { 1256 const Matcher<vector<int>> m = WhenSortedBy(less<int>(), ElementsAre(1, 2)); 1257 EXPECT_EQ( 1258 "(when sorted) has 2 elements where\n" 1259 "element #0 is equal to 1,\n" 1260 "element #1 is equal to 2", 1261 Describe(m)); 1262 EXPECT_EQ( 1263 "(when sorted) doesn't have 2 elements, or\n" 1264 "element #0 isn't equal to 1, or\n" 1265 "element #1 isn't equal to 2", 1266 DescribeNegation(m)); 1267 } 1268 1269 TEST(WhenSortedByTest, ExplainsMatchResult) { 1270 const int a[] = {2, 1}; 1271 EXPECT_EQ("which is { 1, 2 } when sorted, whose element #0 doesn't match", 1272 Explain(WhenSortedBy(less<int>(), ElementsAre(2, 3)), a)); 1273 EXPECT_EQ("which is { 1, 2 } when sorted", 1274 Explain(WhenSortedBy(less<int>(), ElementsAre(1, 2)), a)); 1275 } 1276 1277 // WhenSorted() is a simple wrapper on WhenSortedBy(). Hence we don't 1278 // need to test it as exhaustively as we test the latter. 1279 1280 TEST(WhenSortedTest, WorksForEmptyContainer) { 1281 const vector<int> numbers; 1282 EXPECT_THAT(numbers, WhenSorted(ElementsAre())); 1283 EXPECT_THAT(numbers, Not(WhenSorted(ElementsAre(1)))); 1284 } 1285 1286 TEST(WhenSortedTest, WorksForNonEmptyContainer) { 1287 list<std::string> words; 1288 words.push_back("3"); 1289 words.push_back("1"); 1290 words.push_back("2"); 1291 words.push_back("2"); 1292 EXPECT_THAT(words, WhenSorted(ElementsAre("1", "2", "2", "3"))); 1293 EXPECT_THAT(words, Not(WhenSorted(ElementsAre("3", "1", "2", "2")))); 1294 } 1295 1296 TEST(WhenSortedTest, WorksForMapTypes) { 1297 map<std::string, int> word_counts; 1298 word_counts["and"] = 1; 1299 word_counts["the"] = 1; 1300 word_counts["buffalo"] = 2; 1301 EXPECT_THAT(word_counts, 1302 WhenSorted(ElementsAre(Pair("and", 1), Pair("buffalo", 2), 1303 Pair("the", 1)))); 1304 EXPECT_THAT(word_counts, 1305 Not(WhenSorted(ElementsAre(Pair("and", 1), Pair("the", 1), 1306 Pair("buffalo", 2))))); 1307 } 1308 1309 TEST(WhenSortedTest, WorksForMultiMapTypes) { 1310 multimap<int, int> ifib; 1311 ifib.insert(make_pair(8, 6)); 1312 ifib.insert(make_pair(2, 3)); 1313 ifib.insert(make_pair(1, 1)); 1314 ifib.insert(make_pair(3, 4)); 1315 ifib.insert(make_pair(1, 2)); 1316 ifib.insert(make_pair(5, 5)); 1317 EXPECT_THAT(ifib, 1318 WhenSorted(ElementsAre(Pair(1, 1), Pair(1, 2), Pair(2, 3), 1319 Pair(3, 4), Pair(5, 5), Pair(8, 6)))); 1320 EXPECT_THAT(ifib, 1321 Not(WhenSorted(ElementsAre(Pair(8, 6), Pair(2, 3), Pair(1, 1), 1322 Pair(3, 4), Pair(1, 2), Pair(5, 5))))); 1323 } 1324 1325 TEST(WhenSortedTest, WorksForPolymorphicMatcher) { 1326 std::deque<int> d; 1327 d.push_back(2); 1328 d.push_back(1); 1329 EXPECT_THAT(d, WhenSorted(ElementsAre(1, 2))); 1330 EXPECT_THAT(d, Not(WhenSorted(ElementsAre(2, 1)))); 1331 } 1332 1333 TEST(WhenSortedTest, WorksForVectorConstRefMatcher) { 1334 std::deque<int> d; 1335 d.push_back(2); 1336 d.push_back(1); 1337 Matcher<const std::vector<int>&> vector_match = ElementsAre(1, 2); 1338 EXPECT_THAT(d, WhenSorted(vector_match)); 1339 Matcher<const std::vector<int>&> not_vector_match = ElementsAre(2, 1); 1340 EXPECT_THAT(d, Not(WhenSorted(not_vector_match))); 1341 } 1342 1343 // Deliberately bare pseudo-container. 1344 // Offers only begin() and end() accessors, yielding InputIterator. 1345 template <typename T> 1346 class Streamlike { 1347 private: 1348 class ConstIter; 1349 1350 public: 1351 typedef ConstIter const_iterator; 1352 typedef T value_type; 1353 1354 template <typename InIter> 1355 Streamlike(InIter first, InIter last) : remainder_(first, last) {} 1356 1357 const_iterator begin() const { 1358 return const_iterator(this, remainder_.begin()); 1359 } 1360 const_iterator end() const { return const_iterator(this, remainder_.end()); } 1361 1362 private: 1363 class ConstIter { 1364 public: 1365 using iterator_category = std::input_iterator_tag; 1366 using value_type = T; 1367 using difference_type = ptrdiff_t; 1368 using pointer = const value_type*; 1369 using reference = const value_type&; 1370 1371 ConstIter(const Streamlike* s, typename std::list<value_type>::iterator pos) 1372 : s_(s), pos_(pos) {} 1373 1374 const value_type& operator*() const { return *pos_; } 1375 const value_type* operator->() const { return &*pos_; } 1376 ConstIter& operator++() { 1377 s_->remainder_.erase(pos_++); 1378 return *this; 1379 } 1380 1381 // *iter++ is required to work (see std::istreambuf_iterator). 1382 // (void)iter++ is also required to work. 1383 class PostIncrProxy { 1384 public: 1385 explicit PostIncrProxy(const value_type& value) : value_(value) {} 1386 value_type operator*() const { return value_; } 1387 1388 private: 1389 value_type value_; 1390 }; 1391 PostIncrProxy operator++(int) { 1392 PostIncrProxy proxy(**this); 1393 ++(*this); 1394 return proxy; 1395 } 1396 1397 friend bool operator==(const ConstIter& a, const ConstIter& b) { 1398 return a.s_ == b.s_ && a.pos_ == b.pos_; 1399 } 1400 friend bool operator!=(const ConstIter& a, const ConstIter& b) { 1401 return !(a == b); 1402 } 1403 1404 private: 1405 const Streamlike* s_; 1406 typename std::list<value_type>::iterator pos_; 1407 }; 1408 1409 friend std::ostream& operator<<(std::ostream& os, const Streamlike& s) { 1410 os << "["; 1411 typedef typename std::list<value_type>::const_iterator Iter; 1412 const char* sep = ""; 1413 for (Iter it = s.remainder_.begin(); it != s.remainder_.end(); ++it) { 1414 os << sep << *it; 1415 sep = ","; 1416 } 1417 os << "]"; 1418 return os; 1419 } 1420 1421 mutable std::list<value_type> remainder_; // modified by iteration 1422 }; 1423 1424 TEST(StreamlikeTest, Iteration) { 1425 const int a[5] = {2, 1, 4, 5, 3}; 1426 Streamlike<int> s(a, a + 5); 1427 Streamlike<int>::const_iterator it = s.begin(); 1428 const int* ip = a; 1429 while (it != s.end()) { 1430 SCOPED_TRACE(ip - a); 1431 EXPECT_EQ(*ip++, *it++); 1432 } 1433 } 1434 1435 INSTANTIATE_GTEST_MATCHER_TEST_P(BeginEndDistanceIsTest); 1436 1437 TEST(BeginEndDistanceIsTest, WorksWithForwardList) { 1438 std::forward_list<int> container; 1439 EXPECT_THAT(container, BeginEndDistanceIs(0)); 1440 EXPECT_THAT(container, Not(BeginEndDistanceIs(1))); 1441 container.push_front(0); 1442 EXPECT_THAT(container, Not(BeginEndDistanceIs(0))); 1443 EXPECT_THAT(container, BeginEndDistanceIs(1)); 1444 container.push_front(0); 1445 EXPECT_THAT(container, Not(BeginEndDistanceIs(0))); 1446 EXPECT_THAT(container, BeginEndDistanceIs(2)); 1447 } 1448 1449 TEST(BeginEndDistanceIsTest, WorksWithNonStdList) { 1450 const int a[5] = {1, 2, 3, 4, 5}; 1451 Streamlike<int> s(a, a + 5); 1452 EXPECT_THAT(s, BeginEndDistanceIs(5)); 1453 } 1454 1455 TEST(BeginEndDistanceIsTest, CanDescribeSelf) { 1456 Matcher<vector<int>> m = BeginEndDistanceIs(2); 1457 EXPECT_EQ("distance between begin() and end() is equal to 2", Describe(m)); 1458 EXPECT_EQ("distance between begin() and end() isn't equal to 2", 1459 DescribeNegation(m)); 1460 } 1461 1462 TEST(BeginEndDistanceIsTest, WorksWithMoveOnly) { 1463 ContainerHelper helper; 1464 EXPECT_CALL(helper, Call(BeginEndDistanceIs(2))); 1465 helper.Call(MakeUniquePtrs({1, 2})); 1466 } 1467 1468 TEST_P(BeginEndDistanceIsTestP, ExplainsResult) { 1469 Matcher<vector<int>> m1 = BeginEndDistanceIs(2); 1470 Matcher<vector<int>> m2 = BeginEndDistanceIs(Lt(2)); 1471 Matcher<vector<int>> m3 = BeginEndDistanceIs(AnyOf(0, 3)); 1472 Matcher<vector<int>> m4 = BeginEndDistanceIs(GreaterThan(1)); 1473 vector<int> container; 1474 EXPECT_EQ("whose distance between begin() and end() 0 doesn't match", 1475 Explain(m1, container)); 1476 EXPECT_EQ("whose distance between begin() and end() 0 matches", 1477 Explain(m2, container)); 1478 EXPECT_EQ("whose distance between begin() and end() 0 matches", 1479 Explain(m3, container)); 1480 EXPECT_EQ( 1481 "whose distance between begin() and end() 0 doesn't match, which is 1 " 1482 "less than 1", 1483 Explain(m4, container)); 1484 container.push_back(0); 1485 container.push_back(0); 1486 EXPECT_EQ("whose distance between begin() and end() 2 matches", 1487 Explain(m1, container)); 1488 EXPECT_EQ("whose distance between begin() and end() 2 doesn't match", 1489 Explain(m2, container)); 1490 EXPECT_EQ("whose distance between begin() and end() 2 doesn't match", 1491 Explain(m3, container)); 1492 EXPECT_EQ( 1493 "whose distance between begin() and end() 2 matches, which is 1 more " 1494 "than 1", 1495 Explain(m4, container)); 1496 } 1497 1498 TEST(WhenSortedTest, WorksForStreamlike) { 1499 // Streamlike 'container' provides only minimal iterator support. 1500 // Its iterators are tagged with input_iterator_tag. 1501 const int a[5] = {2, 1, 4, 5, 3}; 1502 Streamlike<int> s(std::begin(a), std::end(a)); 1503 EXPECT_THAT(s, WhenSorted(ElementsAre(1, 2, 3, 4, 5))); 1504 EXPECT_THAT(s, Not(WhenSorted(ElementsAre(2, 1, 4, 5, 3)))); 1505 } 1506 1507 TEST(WhenSortedTest, WorksForVectorConstRefMatcherOnStreamlike) { 1508 const int a[] = {2, 1, 4, 5, 3}; 1509 Streamlike<int> s(std::begin(a), std::end(a)); 1510 Matcher<const std::vector<int>&> vector_match = ElementsAre(1, 2, 3, 4, 5); 1511 EXPECT_THAT(s, WhenSorted(vector_match)); 1512 EXPECT_THAT(s, Not(WhenSorted(ElementsAre(2, 1, 4, 5, 3)))); 1513 } 1514 1515 TEST(IsSupersetOfTest, WorksForNativeArray) { 1516 const int subset[] = {1, 4}; 1517 const int superset[] = {1, 2, 4}; 1518 const int disjoint[] = {1, 0, 3}; 1519 EXPECT_THAT(subset, IsSupersetOf(subset)); 1520 EXPECT_THAT(subset, Not(IsSupersetOf(superset))); 1521 EXPECT_THAT(superset, IsSupersetOf(subset)); 1522 EXPECT_THAT(subset, Not(IsSupersetOf(disjoint))); 1523 EXPECT_THAT(disjoint, Not(IsSupersetOf(subset))); 1524 } 1525 1526 TEST(IsSupersetOfTest, WorksWithDuplicates) { 1527 const int not_enough[] = {1, 2}; 1528 const int enough[] = {1, 1, 2}; 1529 const int expected[] = {1, 1}; 1530 EXPECT_THAT(not_enough, Not(IsSupersetOf(expected))); 1531 EXPECT_THAT(enough, IsSupersetOf(expected)); 1532 } 1533 1534 TEST(IsSupersetOfTest, WorksForEmpty) { 1535 vector<int> numbers; 1536 vector<int> expected; 1537 EXPECT_THAT(numbers, IsSupersetOf(expected)); 1538 expected.push_back(1); 1539 EXPECT_THAT(numbers, Not(IsSupersetOf(expected))); 1540 expected.clear(); 1541 numbers.push_back(1); 1542 numbers.push_back(2); 1543 EXPECT_THAT(numbers, IsSupersetOf(expected)); 1544 expected.push_back(1); 1545 EXPECT_THAT(numbers, IsSupersetOf(expected)); 1546 expected.push_back(2); 1547 EXPECT_THAT(numbers, IsSupersetOf(expected)); 1548 expected.push_back(3); 1549 EXPECT_THAT(numbers, Not(IsSupersetOf(expected))); 1550 } 1551 1552 TEST(IsSupersetOfTest, WorksForStreamlike) { 1553 const int a[5] = {1, 2, 3, 4, 5}; 1554 Streamlike<int> s(std::begin(a), std::end(a)); 1555 1556 vector<int> expected; 1557 expected.push_back(1); 1558 expected.push_back(2); 1559 expected.push_back(5); 1560 EXPECT_THAT(s, IsSupersetOf(expected)); 1561 1562 expected.push_back(0); 1563 EXPECT_THAT(s, Not(IsSupersetOf(expected))); 1564 } 1565 1566 TEST(IsSupersetOfTest, TakesStlContainer) { 1567 const int actual[] = {3, 1, 2}; 1568 1569 ::std::list<int> expected; 1570 expected.push_back(1); 1571 expected.push_back(3); 1572 EXPECT_THAT(actual, IsSupersetOf(expected)); 1573 1574 expected.push_back(4); 1575 EXPECT_THAT(actual, Not(IsSupersetOf(expected))); 1576 } 1577 1578 TEST(IsSupersetOfTest, Describe) { 1579 typedef std::vector<int> IntVec; 1580 IntVec expected; 1581 expected.push_back(111); 1582 expected.push_back(222); 1583 expected.push_back(333); 1584 EXPECT_THAT( 1585 Describe<IntVec>(IsSupersetOf(expected)), 1586 Eq("a surjection from elements to requirements exists such that:\n" 1587 " - an element is equal to 111\n" 1588 " - an element is equal to 222\n" 1589 " - an element is equal to 333")); 1590 } 1591 1592 TEST(IsSupersetOfTest, DescribeNegation) { 1593 typedef std::vector<int> IntVec; 1594 IntVec expected; 1595 expected.push_back(111); 1596 expected.push_back(222); 1597 expected.push_back(333); 1598 EXPECT_THAT( 1599 DescribeNegation<IntVec>(IsSupersetOf(expected)), 1600 Eq("no surjection from elements to requirements exists such that:\n" 1601 " - an element is equal to 111\n" 1602 " - an element is equal to 222\n" 1603 " - an element is equal to 333")); 1604 } 1605 1606 TEST(IsSupersetOfTest, MatchAndExplain) { 1607 std::vector<int> v; 1608 v.push_back(2); 1609 v.push_back(3); 1610 std::vector<int> expected; 1611 expected.push_back(1); 1612 expected.push_back(2); 1613 StringMatchResultListener listener; 1614 ASSERT_FALSE(ExplainMatchResult(IsSupersetOf(expected), v, &listener)) 1615 << listener.str(); 1616 EXPECT_THAT(listener.str(), 1617 Eq("where the following matchers don't match any elements:\n" 1618 "matcher #0: is equal to 1")); 1619 1620 v.push_back(1); 1621 listener.Clear(); 1622 ASSERT_TRUE(ExplainMatchResult(IsSupersetOf(expected), v, &listener)) 1623 << listener.str(); 1624 EXPECT_THAT(listener.str(), Eq("where:\n" 1625 " - element #0 is matched by matcher #1,\n" 1626 " - element #2 is matched by matcher #0")); 1627 } 1628 1629 TEST(IsSupersetOfTest, WorksForRhsInitializerList) { 1630 const int numbers[] = {1, 3, 6, 2, 4, 5}; 1631 EXPECT_THAT(numbers, IsSupersetOf({1, 2})); 1632 EXPECT_THAT(numbers, Not(IsSupersetOf({3, 0}))); 1633 } 1634 1635 TEST(IsSupersetOfTest, WorksWithMoveOnly) { 1636 ContainerHelper helper; 1637 EXPECT_CALL(helper, Call(IsSupersetOf({Pointee(1)}))); 1638 helper.Call(MakeUniquePtrs({1, 2})); 1639 EXPECT_CALL(helper, Call(Not(IsSupersetOf({Pointee(1), Pointee(2)})))); 1640 helper.Call(MakeUniquePtrs({2})); 1641 } 1642 1643 TEST(IsSubsetOfTest, WorksForNativeArray) { 1644 const int subset[] = {1, 4}; 1645 const int superset[] = {1, 2, 4}; 1646 const int disjoint[] = {1, 0, 3}; 1647 EXPECT_THAT(subset, IsSubsetOf(subset)); 1648 EXPECT_THAT(subset, IsSubsetOf(superset)); 1649 EXPECT_THAT(superset, Not(IsSubsetOf(subset))); 1650 EXPECT_THAT(subset, Not(IsSubsetOf(disjoint))); 1651 EXPECT_THAT(disjoint, Not(IsSubsetOf(subset))); 1652 } 1653 1654 TEST(IsSubsetOfTest, WorksWithDuplicates) { 1655 const int not_enough[] = {1, 2}; 1656 const int enough[] = {1, 1, 2}; 1657 const int actual[] = {1, 1}; 1658 EXPECT_THAT(actual, Not(IsSubsetOf(not_enough))); 1659 EXPECT_THAT(actual, IsSubsetOf(enough)); 1660 } 1661 1662 TEST(IsSubsetOfTest, WorksForEmpty) { 1663 vector<int> numbers; 1664 vector<int> expected; 1665 EXPECT_THAT(numbers, IsSubsetOf(expected)); 1666 expected.push_back(1); 1667 EXPECT_THAT(numbers, IsSubsetOf(expected)); 1668 expected.clear(); 1669 numbers.push_back(1); 1670 numbers.push_back(2); 1671 EXPECT_THAT(numbers, Not(IsSubsetOf(expected))); 1672 expected.push_back(1); 1673 EXPECT_THAT(numbers, Not(IsSubsetOf(expected))); 1674 expected.push_back(2); 1675 EXPECT_THAT(numbers, IsSubsetOf(expected)); 1676 expected.push_back(3); 1677 EXPECT_THAT(numbers, IsSubsetOf(expected)); 1678 } 1679 1680 TEST(IsSubsetOfTest, WorksForStreamlike) { 1681 const int a[5] = {1, 2}; 1682 Streamlike<int> s(std::begin(a), std::end(a)); 1683 1684 vector<int> expected; 1685 expected.push_back(1); 1686 EXPECT_THAT(s, Not(IsSubsetOf(expected))); 1687 expected.push_back(2); 1688 expected.push_back(5); 1689 EXPECT_THAT(s, IsSubsetOf(expected)); 1690 } 1691 1692 TEST(IsSubsetOfTest, TakesStlContainer) { 1693 const int actual[] = {3, 1, 2}; 1694 1695 ::std::list<int> expected; 1696 expected.push_back(1); 1697 expected.push_back(3); 1698 EXPECT_THAT(actual, Not(IsSubsetOf(expected))); 1699 1700 expected.push_back(2); 1701 expected.push_back(4); 1702 EXPECT_THAT(actual, IsSubsetOf(expected)); 1703 } 1704 1705 TEST(IsSubsetOfTest, Describe) { 1706 typedef std::vector<int> IntVec; 1707 IntVec expected; 1708 expected.push_back(111); 1709 expected.push_back(222); 1710 expected.push_back(333); 1711 1712 EXPECT_THAT( 1713 Describe<IntVec>(IsSubsetOf(expected)), 1714 Eq("an injection from elements to requirements exists such that:\n" 1715 " - an element is equal to 111\n" 1716 " - an element is equal to 222\n" 1717 " - an element is equal to 333")); 1718 } 1719 1720 TEST(IsSubsetOfTest, DescribeNegation) { 1721 typedef std::vector<int> IntVec; 1722 IntVec expected; 1723 expected.push_back(111); 1724 expected.push_back(222); 1725 expected.push_back(333); 1726 EXPECT_THAT( 1727 DescribeNegation<IntVec>(IsSubsetOf(expected)), 1728 Eq("no injection from elements to requirements exists such that:\n" 1729 " - an element is equal to 111\n" 1730 " - an element is equal to 222\n" 1731 " - an element is equal to 333")); 1732 } 1733 1734 TEST(IsSubsetOfTest, MatchAndExplain) { 1735 std::vector<int> v; 1736 v.push_back(2); 1737 v.push_back(3); 1738 std::vector<int> expected; 1739 expected.push_back(1); 1740 expected.push_back(2); 1741 StringMatchResultListener listener; 1742 ASSERT_FALSE(ExplainMatchResult(IsSubsetOf(expected), v, &listener)) 1743 << listener.str(); 1744 EXPECT_THAT(listener.str(), 1745 Eq("where the following elements don't match any matchers:\n" 1746 "element #1: 3")); 1747 1748 expected.push_back(3); 1749 listener.Clear(); 1750 ASSERT_TRUE(ExplainMatchResult(IsSubsetOf(expected), v, &listener)) 1751 << listener.str(); 1752 EXPECT_THAT(listener.str(), Eq("where:\n" 1753 " - element #0 is matched by matcher #1,\n" 1754 " - element #1 is matched by matcher #2")); 1755 } 1756 1757 TEST(IsSubsetOfTest, WorksForRhsInitializerList) { 1758 const int numbers[] = {1, 2, 3}; 1759 EXPECT_THAT(numbers, IsSubsetOf({1, 2, 3, 4})); 1760 EXPECT_THAT(numbers, Not(IsSubsetOf({1, 2}))); 1761 } 1762 1763 TEST(IsSubsetOfTest, WorksWithMoveOnly) { 1764 ContainerHelper helper; 1765 EXPECT_CALL(helper, Call(IsSubsetOf({Pointee(1), Pointee(2)}))); 1766 helper.Call(MakeUniquePtrs({1})); 1767 EXPECT_CALL(helper, Call(Not(IsSubsetOf({Pointee(1)})))); 1768 helper.Call(MakeUniquePtrs({2})); 1769 } 1770 1771 // Tests using ElementsAre() and ElementsAreArray() with stream-like 1772 // "containers". 1773 1774 TEST(ElemensAreStreamTest, WorksForStreamlike) { 1775 const int a[5] = {1, 2, 3, 4, 5}; 1776 Streamlike<int> s(std::begin(a), std::end(a)); 1777 EXPECT_THAT(s, ElementsAre(1, 2, 3, 4, 5)); 1778 EXPECT_THAT(s, Not(ElementsAre(2, 1, 4, 5, 3))); 1779 } 1780 1781 TEST(ElemensAreArrayStreamTest, WorksForStreamlike) { 1782 const int a[5] = {1, 2, 3, 4, 5}; 1783 Streamlike<int> s(std::begin(a), std::end(a)); 1784 1785 vector<int> expected; 1786 expected.push_back(1); 1787 expected.push_back(2); 1788 expected.push_back(3); 1789 expected.push_back(4); 1790 expected.push_back(5); 1791 EXPECT_THAT(s, ElementsAreArray(expected)); 1792 1793 expected[3] = 0; 1794 EXPECT_THAT(s, Not(ElementsAreArray(expected))); 1795 } 1796 1797 TEST(ElementsAreTest, WorksWithUncopyable) { 1798 Uncopyable objs[2]; 1799 objs[0].set_value(-3); 1800 objs[1].set_value(1); 1801 EXPECT_THAT(objs, ElementsAre(UncopyableIs(-3), Truly(ValueIsPositive))); 1802 } 1803 1804 TEST(ElementsAreTest, WorksWithMoveOnly) { 1805 ContainerHelper helper; 1806 EXPECT_CALL(helper, Call(ElementsAre(Pointee(1), Pointee(2)))); 1807 helper.Call(MakeUniquePtrs({1, 2})); 1808 1809 EXPECT_CALL(helper, Call(ElementsAreArray({Pointee(3), Pointee(4)}))); 1810 helper.Call(MakeUniquePtrs({3, 4})); 1811 } 1812 1813 TEST(ElementsAreTest, TakesStlContainer) { 1814 const int actual[] = {3, 1, 2}; 1815 1816 ::std::list<int> expected; 1817 expected.push_back(3); 1818 expected.push_back(1); 1819 expected.push_back(2); 1820 EXPECT_THAT(actual, ElementsAreArray(expected)); 1821 1822 expected.push_back(4); 1823 EXPECT_THAT(actual, Not(ElementsAreArray(expected))); 1824 } 1825 1826 // Tests for UnorderedElementsAreArray() 1827 1828 TEST(UnorderedElementsAreArrayTest, SucceedsWhenExpected) { 1829 const int a[] = {0, 1, 2, 3, 4}; 1830 std::vector<int> s(std::begin(a), std::end(a)); 1831 do { 1832 StringMatchResultListener listener; 1833 EXPECT_TRUE(ExplainMatchResult(UnorderedElementsAreArray(a), s, &listener)) 1834 << listener.str(); 1835 } while (std::next_permutation(s.begin(), s.end())); 1836 } 1837 1838 TEST(UnorderedElementsAreArrayTest, VectorBool) { 1839 const bool a[] = {false, true, false, true, true}; 1840 const bool b[] = {true, false, true, true, false}; 1841 std::vector<bool> expected(std::begin(a), std::end(a)); 1842 std::vector<bool> actual(std::begin(b), std::end(b)); 1843 StringMatchResultListener listener; 1844 EXPECT_TRUE(ExplainMatchResult(UnorderedElementsAreArray(expected), actual, 1845 &listener)) 1846 << listener.str(); 1847 } 1848 1849 TEST(UnorderedElementsAreArrayTest, WorksForStreamlike) { 1850 // Streamlike 'container' provides only minimal iterator support. 1851 // Its iterators are tagged with input_iterator_tag, and it has no 1852 // size() or empty() methods. 1853 const int a[5] = {2, 1, 4, 5, 3}; 1854 Streamlike<int> s(std::begin(a), std::end(a)); 1855 1856 ::std::vector<int> expected; 1857 expected.push_back(1); 1858 expected.push_back(2); 1859 expected.push_back(3); 1860 expected.push_back(4); 1861 expected.push_back(5); 1862 EXPECT_THAT(s, UnorderedElementsAreArray(expected)); 1863 1864 expected.push_back(6); 1865 EXPECT_THAT(s, Not(UnorderedElementsAreArray(expected))); 1866 } 1867 1868 TEST(UnorderedElementsAreArrayTest, TakesStlContainer) { 1869 const int actual[] = {3, 1, 2}; 1870 1871 ::std::list<int> expected; 1872 expected.push_back(1); 1873 expected.push_back(2); 1874 expected.push_back(3); 1875 EXPECT_THAT(actual, UnorderedElementsAreArray(expected)); 1876 1877 expected.push_back(4); 1878 EXPECT_THAT(actual, Not(UnorderedElementsAreArray(expected))); 1879 } 1880 1881 TEST(UnorderedElementsAreArrayTest, TakesInitializerList) { 1882 const int a[5] = {2, 1, 4, 5, 3}; 1883 EXPECT_THAT(a, UnorderedElementsAreArray({1, 2, 3, 4, 5})); 1884 EXPECT_THAT(a, Not(UnorderedElementsAreArray({1, 2, 3, 4, 6}))); 1885 } 1886 1887 TEST(UnorderedElementsAreArrayTest, TakesInitializerListOfCStrings) { 1888 const std::string a[5] = {"a", "b", "c", "d", "e"}; 1889 EXPECT_THAT(a, UnorderedElementsAreArray({"a", "b", "c", "d", "e"})); 1890 EXPECT_THAT(a, Not(UnorderedElementsAreArray({"a", "b", "c", "d", "ef"}))); 1891 } 1892 1893 TEST(UnorderedElementsAreArrayTest, TakesInitializerListOfSameTypedMatchers) { 1894 const int a[5] = {2, 1, 4, 5, 3}; 1895 EXPECT_THAT(a, 1896 UnorderedElementsAreArray({Eq(1), Eq(2), Eq(3), Eq(4), Eq(5)})); 1897 EXPECT_THAT( 1898 a, Not(UnorderedElementsAreArray({Eq(1), Eq(2), Eq(3), Eq(4), Eq(6)}))); 1899 } 1900 1901 TEST(UnorderedElementsAreArrayTest, 1902 TakesInitializerListOfDifferentTypedMatchers) { 1903 const int a[5] = {2, 1, 4, 5, 3}; 1904 // The compiler cannot infer the type of the initializer list if its 1905 // elements have different types. We must explicitly specify the 1906 // unified element type in this case. 1907 EXPECT_THAT(a, UnorderedElementsAreArray<Matcher<int>>( 1908 {Eq(1), Ne(-2), Ge(3), Le(4), Eq(5)})); 1909 EXPECT_THAT(a, Not(UnorderedElementsAreArray<Matcher<int>>( 1910 {Eq(1), Ne(-2), Ge(3), Le(4), Eq(6)}))); 1911 } 1912 1913 TEST(UnorderedElementsAreArrayTest, WorksWithMoveOnly) { 1914 ContainerHelper helper; 1915 EXPECT_CALL(helper, 1916 Call(UnorderedElementsAreArray({Pointee(1), Pointee(2)}))); 1917 helper.Call(MakeUniquePtrs({2, 1})); 1918 } 1919 1920 class UnorderedElementsAreTest : public testing::Test { 1921 protected: 1922 typedef std::vector<int> IntVec; 1923 }; 1924 1925 TEST_F(UnorderedElementsAreTest, WorksWithUncopyable) { 1926 Uncopyable objs[2]; 1927 objs[0].set_value(-3); 1928 objs[1].set_value(1); 1929 EXPECT_THAT(objs, 1930 UnorderedElementsAre(Truly(ValueIsPositive), UncopyableIs(-3))); 1931 } 1932 1933 TEST_F(UnorderedElementsAreTest, SucceedsWhenExpected) { 1934 const int a[] = {1, 2, 3}; 1935 std::vector<int> s(std::begin(a), std::end(a)); 1936 do { 1937 StringMatchResultListener listener; 1938 EXPECT_TRUE(ExplainMatchResult(UnorderedElementsAre(1, 2, 3), s, &listener)) 1939 << listener.str(); 1940 } while (std::next_permutation(s.begin(), s.end())); 1941 } 1942 1943 TEST_F(UnorderedElementsAreTest, FailsWhenAnElementMatchesNoMatcher) { 1944 const int a[] = {1, 2, 3}; 1945 std::vector<int> s(std::begin(a), std::end(a)); 1946 std::vector<Matcher<int>> mv; 1947 mv.push_back(1); 1948 mv.push_back(2); 1949 mv.push_back(2); 1950 // The element with value '3' matches nothing: fail fast. 1951 StringMatchResultListener listener; 1952 EXPECT_FALSE(ExplainMatchResult(UnorderedElementsAreArray(mv), s, &listener)) 1953 << listener.str(); 1954 } 1955 1956 TEST_F(UnorderedElementsAreTest, WorksForStreamlike) { 1957 // Streamlike 'container' provides only minimal iterator support. 1958 // Its iterators are tagged with input_iterator_tag, and it has no 1959 // size() or empty() methods. 1960 const int a[5] = {2, 1, 4, 5, 3}; 1961 Streamlike<int> s(std::begin(a), std::end(a)); 1962 1963 EXPECT_THAT(s, UnorderedElementsAre(1, 2, 3, 4, 5)); 1964 EXPECT_THAT(s, Not(UnorderedElementsAre(2, 2, 3, 4, 5))); 1965 } 1966 1967 TEST_F(UnorderedElementsAreTest, WorksWithMoveOnly) { 1968 ContainerHelper helper; 1969 EXPECT_CALL(helper, Call(UnorderedElementsAre(Pointee(1), Pointee(2)))); 1970 helper.Call(MakeUniquePtrs({2, 1})); 1971 } 1972 1973 // One naive implementation of the matcher runs in O(N!) time, which is too 1974 // slow for many real-world inputs. This test shows that our matcher can match 1975 // 100 inputs very quickly (a few milliseconds). An O(100!) is 10^158 1976 // iterations and obviously effectively incomputable. 1977 // [ RUN ] UnorderedElementsAreTest.Performance 1978 // [ OK ] UnorderedElementsAreTest.Performance (4 ms) 1979 TEST_F(UnorderedElementsAreTest, Performance) { 1980 std::vector<int> s; 1981 std::vector<Matcher<int>> mv; 1982 for (int i = 0; i < 100; ++i) { 1983 s.push_back(i); 1984 mv.push_back(_); 1985 } 1986 mv[50] = Eq(0); 1987 StringMatchResultListener listener; 1988 EXPECT_TRUE(ExplainMatchResult(UnorderedElementsAreArray(mv), s, &listener)) 1989 << listener.str(); 1990 } 1991 1992 // Another variant of 'Performance' with similar expectations. 1993 // [ RUN ] UnorderedElementsAreTest.PerformanceHalfStrict 1994 // [ OK ] UnorderedElementsAreTest.PerformanceHalfStrict (4 ms) 1995 TEST_F(UnorderedElementsAreTest, PerformanceHalfStrict) { 1996 std::vector<int> s; 1997 std::vector<Matcher<int>> mv; 1998 for (int i = 0; i < 100; ++i) { 1999 s.push_back(i); 2000 if (i & 1) { 2001 mv.push_back(_); 2002 } else { 2003 mv.push_back(i); 2004 } 2005 } 2006 StringMatchResultListener listener; 2007 EXPECT_TRUE(ExplainMatchResult(UnorderedElementsAreArray(mv), s, &listener)) 2008 << listener.str(); 2009 } 2010 2011 TEST_F(UnorderedElementsAreTest, FailMessageCountWrong) { 2012 std::vector<int> v; 2013 v.push_back(4); 2014 StringMatchResultListener listener; 2015 EXPECT_FALSE(ExplainMatchResult(UnorderedElementsAre(1, 2, 3), v, &listener)) 2016 << listener.str(); 2017 EXPECT_THAT(listener.str(), Eq("which has 1 element")); 2018 } 2019 2020 TEST_F(UnorderedElementsAreTest, FailMessageCountWrongZero) { 2021 std::vector<int> v; 2022 StringMatchResultListener listener; 2023 EXPECT_FALSE(ExplainMatchResult(UnorderedElementsAre(1, 2, 3), v, &listener)) 2024 << listener.str(); 2025 EXPECT_THAT(listener.str(), Eq("")); 2026 } 2027 2028 TEST_F(UnorderedElementsAreTest, FailMessageUnmatchedMatchers) { 2029 std::vector<int> v; 2030 v.push_back(1); 2031 v.push_back(1); 2032 StringMatchResultListener listener; 2033 EXPECT_FALSE(ExplainMatchResult(UnorderedElementsAre(1, 2), v, &listener)) 2034 << listener.str(); 2035 EXPECT_THAT(listener.str(), 2036 Eq("where the following matchers don't match any elements:\n" 2037 "matcher #1: is equal to 2")); 2038 } 2039 2040 TEST_F(UnorderedElementsAreTest, FailMessageUnmatchedElements) { 2041 std::vector<int> v; 2042 v.push_back(1); 2043 v.push_back(2); 2044 StringMatchResultListener listener; 2045 EXPECT_FALSE(ExplainMatchResult(UnorderedElementsAre(1, 1), v, &listener)) 2046 << listener.str(); 2047 EXPECT_THAT(listener.str(), 2048 Eq("where the following elements don't match any matchers:\n" 2049 "element #1: 2")); 2050 } 2051 2052 TEST_F(UnorderedElementsAreTest, FailMessageUnmatchedMatcherAndElement) { 2053 std::vector<int> v; 2054 v.push_back(2); 2055 v.push_back(3); 2056 StringMatchResultListener listener; 2057 EXPECT_FALSE(ExplainMatchResult(UnorderedElementsAre(1, 2), v, &listener)) 2058 << listener.str(); 2059 EXPECT_THAT(listener.str(), 2060 Eq("where" 2061 " the following matchers don't match any elements:\n" 2062 "matcher #0: is equal to 1\n" 2063 "and" 2064 " where" 2065 " the following elements don't match any matchers:\n" 2066 "element #1: 3")); 2067 } 2068 2069 // Test helper for formatting element, matcher index pairs in expectations. 2070 static std::string EMString(int element, int matcher) { 2071 stringstream ss; 2072 ss << "(element #" << element << ", matcher #" << matcher << ")"; 2073 return ss.str(); 2074 } 2075 2076 TEST_F(UnorderedElementsAreTest, FailMessageImperfectMatchOnly) { 2077 // A situation where all elements and matchers have a match 2078 // associated with them, but the max matching is not perfect. 2079 std::vector<std::string> v; 2080 v.push_back("a"); 2081 v.push_back("b"); 2082 v.push_back("c"); 2083 StringMatchResultListener listener; 2084 EXPECT_FALSE(ExplainMatchResult( 2085 UnorderedElementsAre("a", "a", AnyOf("b", "c")), v, &listener)) 2086 << listener.str(); 2087 2088 std::string prefix = 2089 "where no permutation of the elements can satisfy all matchers, " 2090 "and the closest match is 2 of 3 matchers with the " 2091 "pairings:\n"; 2092 2093 // We have to be a bit loose here, because there are 4 valid max matches. 2094 EXPECT_THAT( 2095 listener.str(), 2096 AnyOf( 2097 prefix + "{\n " + EMString(0, 0) + ",\n " + EMString(1, 2) + "\n}", 2098 prefix + "{\n " + EMString(0, 1) + ",\n " + EMString(1, 2) + "\n}", 2099 prefix + "{\n " + EMString(0, 0) + ",\n " + EMString(2, 2) + "\n}", 2100 prefix + "{\n " + EMString(0, 1) + ",\n " + EMString(2, 2) + 2101 "\n}")); 2102 } 2103 2104 TEST_F(UnorderedElementsAreTest, Describe) { 2105 EXPECT_THAT(Describe<IntVec>(UnorderedElementsAre()), Eq("is empty")); 2106 EXPECT_THAT(Describe<IntVec>(UnorderedElementsAre(345)), 2107 Eq("has 1 element and that element is equal to 345")); 2108 EXPECT_THAT(Describe<IntVec>(UnorderedElementsAre(111, 222, 333)), 2109 Eq("has 3 elements and there exists some permutation " 2110 "of elements such that:\n" 2111 " - element #0 is equal to 111, and\n" 2112 " - element #1 is equal to 222, and\n" 2113 " - element #2 is equal to 333")); 2114 } 2115 2116 TEST_F(UnorderedElementsAreTest, DescribeNegation) { 2117 EXPECT_THAT(DescribeNegation<IntVec>(UnorderedElementsAre()), 2118 Eq("isn't empty")); 2119 EXPECT_THAT( 2120 DescribeNegation<IntVec>(UnorderedElementsAre(345)), 2121 Eq("doesn't have 1 element, or has 1 element that isn't equal to 345")); 2122 EXPECT_THAT(DescribeNegation<IntVec>(UnorderedElementsAre(123, 234, 345)), 2123 Eq("doesn't have 3 elements, or there exists no permutation " 2124 "of elements such that:\n" 2125 " - element #0 is equal to 123, and\n" 2126 " - element #1 is equal to 234, and\n" 2127 " - element #2 is equal to 345")); 2128 } 2129 2130 // Tests Each(). 2131 2132 INSTANTIATE_GTEST_MATCHER_TEST_P(EachTest); 2133 2134 TEST_P(EachTestP, ExplainsMatchResultCorrectly) { 2135 set<int> a; // empty 2136 2137 Matcher<set<int>> m = Each(2); 2138 EXPECT_EQ("", Explain(m, a)); 2139 2140 Matcher<const int(&)[1]> n = Each(1); // NOLINT 2141 2142 const int b[1] = {1}; 2143 EXPECT_EQ("", Explain(n, b)); 2144 2145 n = Each(3); 2146 EXPECT_EQ("whose element #0 doesn't match", Explain(n, b)); 2147 2148 a.insert(1); 2149 a.insert(2); 2150 a.insert(3); 2151 m = Each(GreaterThan(0)); 2152 EXPECT_EQ("", Explain(m, a)); 2153 2154 m = Each(GreaterThan(10)); 2155 EXPECT_EQ("whose element #0 doesn't match, which is 9 less than 10", 2156 Explain(m, a)); 2157 } 2158 2159 TEST(EachTest, DescribesItselfCorrectly) { 2160 Matcher<vector<int>> m = Each(1); 2161 EXPECT_EQ("only contains elements that is equal to 1", Describe(m)); 2162 2163 Matcher<vector<int>> m2 = Not(m); 2164 EXPECT_EQ("contains some element that isn't equal to 1", Describe(m2)); 2165 } 2166 2167 TEST(EachTest, MatchesVectorWhenAllElementsMatch) { 2168 vector<int> some_vector; 2169 EXPECT_THAT(some_vector, Each(1)); 2170 some_vector.push_back(3); 2171 EXPECT_THAT(some_vector, Not(Each(1))); 2172 EXPECT_THAT(some_vector, Each(3)); 2173 some_vector.push_back(1); 2174 some_vector.push_back(2); 2175 EXPECT_THAT(some_vector, Not(Each(3))); 2176 EXPECT_THAT(some_vector, Each(Lt(3.5))); 2177 2178 vector<std::string> another_vector; 2179 another_vector.push_back("fee"); 2180 EXPECT_THAT(another_vector, Each(std::string("fee"))); 2181 another_vector.push_back("fie"); 2182 another_vector.push_back("foe"); 2183 another_vector.push_back("fum"); 2184 EXPECT_THAT(another_vector, Not(Each(std::string("fee")))); 2185 } 2186 2187 TEST(EachTest, MatchesMapWhenAllElementsMatch) { 2188 map<const char*, int> my_map; 2189 const char* bar = "a string"; 2190 my_map[bar] = 2; 2191 EXPECT_THAT(my_map, Each(make_pair(bar, 2))); 2192 2193 map<std::string, int> another_map; 2194 EXPECT_THAT(another_map, Each(make_pair(std::string("fee"), 1))); 2195 another_map["fee"] = 1; 2196 EXPECT_THAT(another_map, Each(make_pair(std::string("fee"), 1))); 2197 another_map["fie"] = 2; 2198 another_map["foe"] = 3; 2199 another_map["fum"] = 4; 2200 EXPECT_THAT(another_map, Not(Each(make_pair(std::string("fee"), 1)))); 2201 EXPECT_THAT(another_map, Not(Each(make_pair(std::string("fum"), 1)))); 2202 EXPECT_THAT(another_map, Each(Pair(_, Gt(0)))); 2203 } 2204 2205 TEST(EachTest, AcceptsMatcher) { 2206 const int a[] = {1, 2, 3}; 2207 EXPECT_THAT(a, Each(Gt(0))); 2208 EXPECT_THAT(a, Not(Each(Gt(1)))); 2209 } 2210 2211 TEST(EachTest, WorksForNativeArrayAsTuple) { 2212 const int a[] = {1, 2}; 2213 const int* const pointer = a; 2214 EXPECT_THAT(std::make_tuple(pointer, 2), Each(Gt(0))); 2215 EXPECT_THAT(std::make_tuple(pointer, 2), Not(Each(Gt(1)))); 2216 } 2217 2218 TEST(EachTest, WorksWithMoveOnly) { 2219 ContainerHelper helper; 2220 EXPECT_CALL(helper, Call(Each(Pointee(Gt(0))))); 2221 helper.Call(MakeUniquePtrs({1, 2})); 2222 } 2223 2224 // For testing Pointwise(). 2225 class IsHalfOfMatcher { 2226 public: 2227 template <typename T1, typename T2> 2228 bool MatchAndExplain(const std::tuple<T1, T2>& a_pair, 2229 MatchResultListener* listener) const { 2230 if (std::get<0>(a_pair) == std::get<1>(a_pair) / 2) { 2231 *listener << "where the second is " << std::get<1>(a_pair); 2232 return true; 2233 } else { 2234 *listener << "where the second/2 is " << std::get<1>(a_pair) / 2; 2235 return false; 2236 } 2237 } 2238 2239 void DescribeTo(ostream* os) const { 2240 *os << "are a pair where the first is half of the second"; 2241 } 2242 2243 void DescribeNegationTo(ostream* os) const { 2244 *os << "are a pair where the first isn't half of the second"; 2245 } 2246 }; 2247 2248 PolymorphicMatcher<IsHalfOfMatcher> IsHalfOf() { 2249 return MakePolymorphicMatcher(IsHalfOfMatcher()); 2250 } 2251 2252 TEST(PointwiseTest, DescribesSelf) { 2253 vector<int> rhs; 2254 rhs.push_back(1); 2255 rhs.push_back(2); 2256 rhs.push_back(3); 2257 const Matcher<const vector<int>&> m = Pointwise(IsHalfOf(), rhs); 2258 EXPECT_EQ( 2259 "contains 3 values, where each value and its corresponding value " 2260 "in { 1, 2, 3 } are a pair where the first is half of the second", 2261 Describe(m)); 2262 EXPECT_EQ( 2263 "doesn't contain exactly 3 values, or contains a value x at some " 2264 "index i where x and the i-th value of { 1, 2, 3 } are a pair " 2265 "where the first isn't half of the second", 2266 DescribeNegation(m)); 2267 } 2268 2269 TEST(PointwiseTest, MakesCopyOfRhs) { 2270 list<signed char> rhs; 2271 rhs.push_back(2); 2272 rhs.push_back(4); 2273 2274 int lhs[] = {1, 2}; 2275 const Matcher<const int(&)[2]> m = Pointwise(IsHalfOf(), rhs); 2276 EXPECT_THAT(lhs, m); 2277 2278 // Changing rhs now shouldn't affect m, which made a copy of rhs. 2279 rhs.push_back(6); 2280 EXPECT_THAT(lhs, m); 2281 } 2282 2283 TEST(PointwiseTest, WorksForLhsNativeArray) { 2284 const int lhs[] = {1, 2, 3}; 2285 vector<int> rhs; 2286 rhs.push_back(2); 2287 rhs.push_back(4); 2288 rhs.push_back(6); 2289 EXPECT_THAT(lhs, Pointwise(Lt(), rhs)); 2290 EXPECT_THAT(lhs, Not(Pointwise(Gt(), rhs))); 2291 } 2292 2293 TEST(PointwiseTest, WorksForRhsNativeArray) { 2294 const int rhs[] = {1, 2, 3}; 2295 vector<int> lhs; 2296 lhs.push_back(2); 2297 lhs.push_back(4); 2298 lhs.push_back(6); 2299 EXPECT_THAT(lhs, Pointwise(Gt(), rhs)); 2300 EXPECT_THAT(lhs, Not(Pointwise(Lt(), rhs))); 2301 } 2302 2303 // Test is effective only with sanitizers. 2304 TEST(PointwiseTest, WorksForVectorOfBool) { 2305 vector<bool> rhs(3, false); 2306 rhs[1] = true; 2307 vector<bool> lhs = rhs; 2308 EXPECT_THAT(lhs, Pointwise(Eq(), rhs)); 2309 rhs[0] = true; 2310 EXPECT_THAT(lhs, Not(Pointwise(Eq(), rhs))); 2311 } 2312 2313 TEST(PointwiseTest, WorksForRhsInitializerList) { 2314 const vector<int> lhs{2, 4, 6}; 2315 EXPECT_THAT(lhs, Pointwise(Gt(), {1, 2, 3})); 2316 EXPECT_THAT(lhs, Not(Pointwise(Lt(), {3, 3, 7}))); 2317 } 2318 2319 TEST(PointwiseTest, RejectsWrongSize) { 2320 const double lhs[2] = {1, 2}; 2321 const int rhs[1] = {0}; 2322 EXPECT_THAT(lhs, Not(Pointwise(Gt(), rhs))); 2323 EXPECT_EQ("which contains 2 values", Explain(Pointwise(Gt(), rhs), lhs)); 2324 2325 const int rhs2[3] = {0, 1, 2}; 2326 EXPECT_THAT(lhs, Not(Pointwise(Gt(), rhs2))); 2327 } 2328 2329 TEST(PointwiseTest, RejectsWrongContent) { 2330 const double lhs[3] = {1, 2, 3}; 2331 const int rhs[3] = {2, 6, 4}; 2332 EXPECT_THAT(lhs, Not(Pointwise(IsHalfOf(), rhs))); 2333 EXPECT_EQ( 2334 "where the value pair (2, 6) at index #1 don't match, " 2335 "where the second/2 is 3", 2336 Explain(Pointwise(IsHalfOf(), rhs), lhs)); 2337 } 2338 2339 TEST(PointwiseTest, AcceptsCorrectContent) { 2340 const double lhs[3] = {1, 2, 3}; 2341 const int rhs[3] = {2, 4, 6}; 2342 EXPECT_THAT(lhs, Pointwise(IsHalfOf(), rhs)); 2343 EXPECT_EQ("", Explain(Pointwise(IsHalfOf(), rhs), lhs)); 2344 } 2345 2346 TEST(PointwiseTest, AllowsMonomorphicInnerMatcher) { 2347 const double lhs[3] = {1, 2, 3}; 2348 const int rhs[3] = {2, 4, 6}; 2349 const Matcher<std::tuple<const double&, const int&>> m1 = IsHalfOf(); 2350 EXPECT_THAT(lhs, Pointwise(m1, rhs)); 2351 EXPECT_EQ("", Explain(Pointwise(m1, rhs), lhs)); 2352 2353 // This type works as a std::tuple<const double&, const int&> can be 2354 // implicitly cast to std::tuple<double, int>. 2355 const Matcher<std::tuple<double, int>> m2 = IsHalfOf(); 2356 EXPECT_THAT(lhs, Pointwise(m2, rhs)); 2357 EXPECT_EQ("", Explain(Pointwise(m2, rhs), lhs)); 2358 } 2359 2360 MATCHER(PointeeEquals, "Points to an equal value") { 2361 return ExplainMatchResult(::testing::Pointee(::testing::get<1>(arg)), 2362 ::testing::get<0>(arg), result_listener); 2363 } 2364 2365 TEST(PointwiseTest, WorksWithMoveOnly) { 2366 ContainerHelper helper; 2367 EXPECT_CALL(helper, Call(Pointwise(PointeeEquals(), std::vector<int>{1, 2}))); 2368 helper.Call(MakeUniquePtrs({1, 2})); 2369 } 2370 2371 TEST(UnorderedPointwiseTest, DescribesSelf) { 2372 vector<int> rhs; 2373 rhs.push_back(1); 2374 rhs.push_back(2); 2375 rhs.push_back(3); 2376 const Matcher<const vector<int>&> m = UnorderedPointwise(IsHalfOf(), rhs); 2377 EXPECT_EQ( 2378 "has 3 elements and there exists some permutation of elements such " 2379 "that:\n" 2380 " - element #0 and 1 are a pair where the first is half of the second, " 2381 "and\n" 2382 " - element #1 and 2 are a pair where the first is half of the second, " 2383 "and\n" 2384 " - element #2 and 3 are a pair where the first is half of the second", 2385 Describe(m)); 2386 EXPECT_EQ( 2387 "doesn't have 3 elements, or there exists no permutation of elements " 2388 "such that:\n" 2389 " - element #0 and 1 are a pair where the first is half of the second, " 2390 "and\n" 2391 " - element #1 and 2 are a pair where the first is half of the second, " 2392 "and\n" 2393 " - element #2 and 3 are a pair where the first is half of the second", 2394 DescribeNegation(m)); 2395 } 2396 2397 TEST(UnorderedPointwiseTest, MakesCopyOfRhs) { 2398 list<signed char> rhs; 2399 rhs.push_back(2); 2400 rhs.push_back(4); 2401 2402 int lhs[] = {2, 1}; 2403 const Matcher<const int(&)[2]> m = UnorderedPointwise(IsHalfOf(), rhs); 2404 EXPECT_THAT(lhs, m); 2405 2406 // Changing rhs now shouldn't affect m, which made a copy of rhs. 2407 rhs.push_back(6); 2408 EXPECT_THAT(lhs, m); 2409 } 2410 2411 TEST(UnorderedPointwiseTest, WorksForLhsNativeArray) { 2412 const int lhs[] = {1, 2, 3}; 2413 vector<int> rhs; 2414 rhs.push_back(4); 2415 rhs.push_back(6); 2416 rhs.push_back(2); 2417 EXPECT_THAT(lhs, UnorderedPointwise(Lt(), rhs)); 2418 EXPECT_THAT(lhs, Not(UnorderedPointwise(Gt(), rhs))); 2419 } 2420 2421 TEST(UnorderedPointwiseTest, WorksForRhsNativeArray) { 2422 const int rhs[] = {1, 2, 3}; 2423 vector<int> lhs; 2424 lhs.push_back(4); 2425 lhs.push_back(2); 2426 lhs.push_back(6); 2427 EXPECT_THAT(lhs, UnorderedPointwise(Gt(), rhs)); 2428 EXPECT_THAT(lhs, Not(UnorderedPointwise(Lt(), rhs))); 2429 } 2430 2431 TEST(UnorderedPointwiseTest, WorksForRhsInitializerList) { 2432 const vector<int> lhs{2, 4, 6}; 2433 EXPECT_THAT(lhs, UnorderedPointwise(Gt(), {5, 1, 3})); 2434 EXPECT_THAT(lhs, Not(UnorderedPointwise(Lt(), {1, 1, 7}))); 2435 } 2436 2437 TEST(UnorderedPointwiseTest, RejectsWrongSize) { 2438 const double lhs[2] = {1, 2}; 2439 const int rhs[1] = {0}; 2440 EXPECT_THAT(lhs, Not(UnorderedPointwise(Gt(), rhs))); 2441 EXPECT_EQ("which has 2 elements", 2442 Explain(UnorderedPointwise(Gt(), rhs), lhs)); 2443 2444 const int rhs2[3] = {0, 1, 2}; 2445 EXPECT_THAT(lhs, Not(UnorderedPointwise(Gt(), rhs2))); 2446 } 2447 2448 TEST(UnorderedPointwiseTest, RejectsWrongContent) { 2449 const double lhs[3] = {1, 2, 3}; 2450 const int rhs[3] = {2, 6, 6}; 2451 EXPECT_THAT(lhs, Not(UnorderedPointwise(IsHalfOf(), rhs))); 2452 EXPECT_EQ( 2453 "where the following elements don't match any matchers:\n" 2454 "element #1: 2", 2455 Explain(UnorderedPointwise(IsHalfOf(), rhs), lhs)); 2456 } 2457 2458 TEST(UnorderedPointwiseTest, AcceptsCorrectContentInSameOrder) { 2459 const double lhs[3] = {1, 2, 3}; 2460 const int rhs[3] = {2, 4, 6}; 2461 EXPECT_THAT(lhs, UnorderedPointwise(IsHalfOf(), rhs)); 2462 } 2463 2464 TEST(UnorderedPointwiseTest, AcceptsCorrectContentInDifferentOrder) { 2465 const double lhs[3] = {1, 2, 3}; 2466 const int rhs[3] = {6, 4, 2}; 2467 EXPECT_THAT(lhs, UnorderedPointwise(IsHalfOf(), rhs)); 2468 } 2469 2470 TEST(UnorderedPointwiseTest, AllowsMonomorphicInnerMatcher) { 2471 const double lhs[3] = {1, 2, 3}; 2472 const int rhs[3] = {4, 6, 2}; 2473 const Matcher<std::tuple<const double&, const int&>> m1 = IsHalfOf(); 2474 EXPECT_THAT(lhs, UnorderedPointwise(m1, rhs)); 2475 2476 // This type works as a std::tuple<const double&, const int&> can be 2477 // implicitly cast to std::tuple<double, int>. 2478 const Matcher<std::tuple<double, int>> m2 = IsHalfOf(); 2479 EXPECT_THAT(lhs, UnorderedPointwise(m2, rhs)); 2480 } 2481 2482 TEST(UnorderedPointwiseTest, WorksWithMoveOnly) { 2483 ContainerHelper helper; 2484 EXPECT_CALL(helper, Call(UnorderedPointwise(PointeeEquals(), 2485 std::vector<int>{1, 2}))); 2486 helper.Call(MakeUniquePtrs({2, 1})); 2487 } 2488 2489 TEST(PointeeTest, WorksOnMoveOnlyType) { 2490 std::unique_ptr<int> p(new int(3)); 2491 EXPECT_THAT(p, Pointee(Eq(3))); 2492 EXPECT_THAT(p, Not(Pointee(Eq(2)))); 2493 } 2494 2495 class PredicateFormatterFromMatcherTest : public ::testing::Test { 2496 protected: 2497 enum Behavior { kInitialSuccess, kAlwaysFail, kFlaky }; 2498 2499 // A matcher that can return different results when used multiple times on the 2500 // same input. No real matcher should do this; but this lets us test that we 2501 // detect such behavior and fail appropriately. 2502 class MockMatcher : public MatcherInterface<Behavior> { 2503 public: 2504 bool MatchAndExplain(Behavior behavior, 2505 MatchResultListener* listener) const override { 2506 *listener << "[MatchAndExplain]"; 2507 switch (behavior) { 2508 case kInitialSuccess: 2509 // The first call to MatchAndExplain should use a "not interested" 2510 // listener; so this is expected to return |true|. There should be no 2511 // subsequent calls. 2512 return !listener->IsInterested(); 2513 2514 case kAlwaysFail: 2515 return false; 2516 2517 case kFlaky: 2518 // The first call to MatchAndExplain should use a "not interested" 2519 // listener; so this will return |false|. Subsequent calls should have 2520 // an "interested" listener; so this will return |true|, thus 2521 // simulating a flaky matcher. 2522 return listener->IsInterested(); 2523 } 2524 2525 GTEST_LOG_(FATAL) << "This should never be reached"; 2526 return false; 2527 } 2528 2529 void DescribeTo(ostream* os) const override { *os << "[DescribeTo]"; } 2530 2531 void DescribeNegationTo(ostream* os) const override { 2532 *os << "[DescribeNegationTo]"; 2533 } 2534 }; 2535 2536 AssertionResult RunPredicateFormatter(Behavior behavior) { 2537 auto matcher = MakeMatcher(new MockMatcher); 2538 PredicateFormatterFromMatcher<Matcher<Behavior>> predicate_formatter( 2539 matcher); 2540 return predicate_formatter("dummy-name", behavior); 2541 } 2542 }; 2543 2544 TEST_F(PredicateFormatterFromMatcherTest, ShortCircuitOnSuccess) { 2545 AssertionResult result = RunPredicateFormatter(kInitialSuccess); 2546 EXPECT_TRUE(result); // Implicit cast to bool. 2547 std::string expect; 2548 EXPECT_EQ(expect, result.message()); 2549 } 2550 2551 TEST_F(PredicateFormatterFromMatcherTest, NoShortCircuitOnFailure) { 2552 AssertionResult result = RunPredicateFormatter(kAlwaysFail); 2553 EXPECT_FALSE(result); // Implicit cast to bool. 2554 std::string expect = 2555 "Value of: dummy-name\nExpected: [DescribeTo]\n" 2556 " Actual: 1" + 2557 OfType(internal::GetTypeName<Behavior>()) + ", [MatchAndExplain]"; 2558 EXPECT_EQ(expect, result.message()); 2559 } 2560 2561 TEST_F(PredicateFormatterFromMatcherTest, DetectsFlakyShortCircuit) { 2562 AssertionResult result = RunPredicateFormatter(kFlaky); 2563 EXPECT_FALSE(result); // Implicit cast to bool. 2564 std::string expect = 2565 "Value of: dummy-name\nExpected: [DescribeTo]\n" 2566 " The matcher failed on the initial attempt; but passed when rerun to " 2567 "generate the explanation.\n" 2568 " Actual: 2" + 2569 OfType(internal::GetTypeName<Behavior>()) + ", [MatchAndExplain]"; 2570 EXPECT_EQ(expect, result.message()); 2571 } 2572 2573 // Tests for ElementsAre(). 2574 2575 TEST(ElementsAreTest, CanDescribeExpectingNoElement) { 2576 Matcher<const vector<int>&> m = ElementsAre(); 2577 EXPECT_EQ("is empty", Describe(m)); 2578 } 2579 2580 TEST(ElementsAreTest, CanDescribeExpectingOneElement) { 2581 Matcher<vector<int>> m = ElementsAre(Gt(5)); 2582 EXPECT_EQ("has 1 element that is > 5", Describe(m)); 2583 } 2584 2585 TEST(ElementsAreTest, CanDescribeExpectingManyElements) { 2586 Matcher<list<std::string>> m = ElementsAre(StrEq("one"), "two"); 2587 EXPECT_EQ( 2588 "has 2 elements where\n" 2589 "element #0 is equal to \"one\",\n" 2590 "element #1 is equal to \"two\"", 2591 Describe(m)); 2592 } 2593 2594 TEST(ElementsAreTest, CanDescribeNegationOfExpectingNoElement) { 2595 Matcher<vector<int>> m = ElementsAre(); 2596 EXPECT_EQ("isn't empty", DescribeNegation(m)); 2597 } 2598 2599 TEST(ElementsAreTest, CanDescribeNegationOfExpectingOneElement) { 2600 Matcher<const list<int>&> m = ElementsAre(Gt(5)); 2601 EXPECT_EQ( 2602 "doesn't have 1 element, or\n" 2603 "element #0 isn't > 5", 2604 DescribeNegation(m)); 2605 } 2606 2607 TEST(ElementsAreTest, CanDescribeNegationOfExpectingManyElements) { 2608 Matcher<const list<std::string>&> m = ElementsAre("one", "two"); 2609 EXPECT_EQ( 2610 "doesn't have 2 elements, or\n" 2611 "element #0 isn't equal to \"one\", or\n" 2612 "element #1 isn't equal to \"two\"", 2613 DescribeNegation(m)); 2614 } 2615 2616 TEST(ElementsAreTest, DoesNotExplainTrivialMatch) { 2617 Matcher<const list<int>&> m = ElementsAre(1, Ne(2)); 2618 2619 list<int> test_list; 2620 test_list.push_back(1); 2621 test_list.push_back(3); 2622 EXPECT_EQ("", Explain(m, test_list)); // No need to explain anything. 2623 } 2624 2625 TEST_P(ElementsAreTestP, ExplainsNonTrivialMatch) { 2626 Matcher<const vector<int>&> m = 2627 ElementsAre(GreaterThan(1), 0, GreaterThan(2)); 2628 2629 const int a[] = {10, 0, 100}; 2630 vector<int> test_vector(std::begin(a), std::end(a)); 2631 EXPECT_EQ( 2632 "whose element #0 matches, which is 9 more than 1,\n" 2633 "and whose element #2 matches, which is 98 more than 2", 2634 Explain(m, test_vector)); 2635 } 2636 2637 TEST(ElementsAreTest, CanExplainMismatchWrongSize) { 2638 Matcher<const list<int>&> m = ElementsAre(1, 3); 2639 2640 list<int> test_list; 2641 // No need to explain when the container is empty. 2642 EXPECT_EQ("", Explain(m, test_list)); 2643 2644 test_list.push_back(1); 2645 EXPECT_EQ("which has 1 element", Explain(m, test_list)); 2646 } 2647 2648 TEST_P(ElementsAreTestP, CanExplainMismatchRightSize) { 2649 Matcher<const vector<int>&> m = ElementsAre(1, GreaterThan(5)); 2650 2651 vector<int> v; 2652 v.push_back(2); 2653 v.push_back(1); 2654 EXPECT_EQ("whose element #0 doesn't match", Explain(m, v)); 2655 2656 v[0] = 1; 2657 EXPECT_EQ("whose element #1 doesn't match, which is 4 less than 5", 2658 Explain(m, v)); 2659 } 2660 2661 TEST(ElementsAreTest, MatchesOneElementVector) { 2662 vector<std::string> test_vector; 2663 test_vector.push_back("test string"); 2664 2665 EXPECT_THAT(test_vector, ElementsAre(StrEq("test string"))); 2666 } 2667 2668 TEST(ElementsAreTest, MatchesOneElementList) { 2669 list<std::string> test_list; 2670 test_list.push_back("test string"); 2671 2672 EXPECT_THAT(test_list, ElementsAre("test string")); 2673 } 2674 2675 TEST(ElementsAreTest, MatchesThreeElementVector) { 2676 vector<std::string> test_vector; 2677 test_vector.push_back("one"); 2678 test_vector.push_back("two"); 2679 test_vector.push_back("three"); 2680 2681 EXPECT_THAT(test_vector, ElementsAre("one", StrEq("two"), _)); 2682 } 2683 2684 TEST(ElementsAreTest, MatchesOneElementEqMatcher) { 2685 vector<int> test_vector; 2686 test_vector.push_back(4); 2687 2688 EXPECT_THAT(test_vector, ElementsAre(Eq(4))); 2689 } 2690 2691 TEST(ElementsAreTest, MatchesOneElementAnyMatcher) { 2692 vector<int> test_vector; 2693 test_vector.push_back(4); 2694 2695 EXPECT_THAT(test_vector, ElementsAre(_)); 2696 } 2697 2698 TEST(ElementsAreTest, MatchesOneElementValue) { 2699 vector<int> test_vector; 2700 test_vector.push_back(4); 2701 2702 EXPECT_THAT(test_vector, ElementsAre(4)); 2703 } 2704 2705 TEST(ElementsAreTest, MatchesThreeElementsMixedMatchers) { 2706 vector<int> test_vector; 2707 test_vector.push_back(1); 2708 test_vector.push_back(2); 2709 test_vector.push_back(3); 2710 2711 EXPECT_THAT(test_vector, ElementsAre(1, Eq(2), _)); 2712 } 2713 2714 TEST(ElementsAreTest, MatchesTenElementVector) { 2715 const int a[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; 2716 vector<int> test_vector(std::begin(a), std::end(a)); 2717 2718 EXPECT_THAT(test_vector, 2719 // The element list can contain values and/or matchers 2720 // of different types. 2721 ElementsAre(0, Ge(0), _, 3, 4, Ne(2), Eq(6), 7, 8, _)); 2722 } 2723 2724 TEST(ElementsAreTest, DoesNotMatchWrongSize) { 2725 vector<std::string> test_vector; 2726 test_vector.push_back("test string"); 2727 test_vector.push_back("test string"); 2728 2729 Matcher<vector<std::string>> m = ElementsAre(StrEq("test string")); 2730 EXPECT_FALSE(m.Matches(test_vector)); 2731 } 2732 2733 TEST(ElementsAreTest, DoesNotMatchWrongValue) { 2734 vector<std::string> test_vector; 2735 test_vector.push_back("other string"); 2736 2737 Matcher<vector<std::string>> m = ElementsAre(StrEq("test string")); 2738 EXPECT_FALSE(m.Matches(test_vector)); 2739 } 2740 2741 TEST(ElementsAreTest, DoesNotMatchWrongOrder) { 2742 vector<std::string> test_vector; 2743 test_vector.push_back("one"); 2744 test_vector.push_back("three"); 2745 test_vector.push_back("two"); 2746 2747 Matcher<vector<std::string>> m = 2748 ElementsAre(StrEq("one"), StrEq("two"), StrEq("three")); 2749 EXPECT_FALSE(m.Matches(test_vector)); 2750 } 2751 2752 TEST(ElementsAreTest, WorksForNestedContainer) { 2753 constexpr std::array<const char*, 2> strings = {{"Hi", "world"}}; 2754 2755 vector<list<char>> nested; 2756 for (const auto& s : strings) { 2757 nested.emplace_back(s, s + strlen(s)); 2758 } 2759 2760 EXPECT_THAT(nested, ElementsAre(ElementsAre('H', Ne('e')), 2761 ElementsAre('w', 'o', _, _, 'd'))); 2762 EXPECT_THAT(nested, Not(ElementsAre(ElementsAre('H', 'e'), 2763 ElementsAre('w', 'o', _, _, 'd')))); 2764 } 2765 2766 TEST(ElementsAreTest, WorksWithByRefElementMatchers) { 2767 int a[] = {0, 1, 2}; 2768 vector<int> v(std::begin(a), std::end(a)); 2769 2770 EXPECT_THAT(v, ElementsAre(Ref(v[0]), Ref(v[1]), Ref(v[2]))); 2771 EXPECT_THAT(v, Not(ElementsAre(Ref(v[0]), Ref(v[1]), Ref(a[2])))); 2772 } 2773 2774 TEST(ElementsAreTest, WorksWithContainerPointerUsingPointee) { 2775 int a[] = {0, 1, 2}; 2776 vector<int> v(std::begin(a), std::end(a)); 2777 2778 EXPECT_THAT(&v, Pointee(ElementsAre(0, 1, _))); 2779 EXPECT_THAT(&v, Not(Pointee(ElementsAre(0, _, 3)))); 2780 } 2781 2782 TEST(ElementsAreTest, WorksWithNativeArrayPassedByReference) { 2783 int array[] = {0, 1, 2}; 2784 EXPECT_THAT(array, ElementsAre(0, 1, _)); 2785 EXPECT_THAT(array, Not(ElementsAre(1, _, _))); 2786 EXPECT_THAT(array, Not(ElementsAre(0, _))); 2787 } 2788 2789 class NativeArrayPassedAsPointerAndSize { 2790 public: 2791 NativeArrayPassedAsPointerAndSize() = default; 2792 2793 MOCK_METHOD(void, Helper, (int* array, int size)); 2794 2795 private: 2796 NativeArrayPassedAsPointerAndSize(const NativeArrayPassedAsPointerAndSize&) = 2797 delete; 2798 NativeArrayPassedAsPointerAndSize& operator=( 2799 const NativeArrayPassedAsPointerAndSize&) = delete; 2800 }; 2801 2802 TEST(ElementsAreTest, WorksWithNativeArrayPassedAsPointerAndSize) { 2803 int array[] = {0, 1}; 2804 ::std::tuple<int*, size_t> array_as_tuple(array, 2); 2805 EXPECT_THAT(array_as_tuple, ElementsAre(0, 1)); 2806 EXPECT_THAT(array_as_tuple, Not(ElementsAre(0))); 2807 2808 NativeArrayPassedAsPointerAndSize helper; 2809 EXPECT_CALL(helper, Helper(_, _)).With(ElementsAre(0, 1)); 2810 helper.Helper(array, 2); 2811 } 2812 2813 TEST(ElementsAreTest, WorksWithTwoDimensionalNativeArray) { 2814 const char a2[][3] = {"hi", "lo"}; 2815 EXPECT_THAT(a2, ElementsAre(ElementsAre('h', 'i', '\0'), 2816 ElementsAre('l', 'o', '\0'))); 2817 EXPECT_THAT(a2, ElementsAre(StrEq("hi"), StrEq("lo"))); 2818 EXPECT_THAT(a2, ElementsAre(Not(ElementsAre('h', 'o', '\0')), 2819 ElementsAre('l', 'o', '\0'))); 2820 } 2821 2822 TEST(ElementsAreTest, AcceptsStringLiteral) { 2823 std::string array[] = {"hi", "one", "two"}; 2824 EXPECT_THAT(array, ElementsAre("hi", "one", "two")); 2825 EXPECT_THAT(array, Not(ElementsAre("hi", "one", "too"))); 2826 } 2827 2828 // Declared here with the size unknown. Defined AFTER the following test. 2829 extern const char kHi[]; 2830 2831 TEST(ElementsAreTest, AcceptsArrayWithUnknownSize) { 2832 // The size of kHi is not known in this test, but ElementsAre() should 2833 // still accept it. 2834 2835 std::string array1[] = {"hi"}; 2836 EXPECT_THAT(array1, ElementsAre(kHi)); 2837 2838 std::string array2[] = {"ho"}; 2839 EXPECT_THAT(array2, Not(ElementsAre(kHi))); 2840 } 2841 2842 const char kHi[] = "hi"; 2843 2844 TEST(ElementsAreTest, MakesCopyOfArguments) { 2845 int x = 1; 2846 int y = 2; 2847 // This should make a copy of x and y. 2848 ::testing::internal::ElementsAreMatcher<std::tuple<int, int>> 2849 polymorphic_matcher = ElementsAre(x, y); 2850 // Changing x and y now shouldn't affect the meaning of the above matcher. 2851 x = y = 0; 2852 const int array1[] = {1, 2}; 2853 EXPECT_THAT(array1, polymorphic_matcher); 2854 const int array2[] = {0, 0}; 2855 EXPECT_THAT(array2, Not(polymorphic_matcher)); 2856 } 2857 2858 // Tests for ElementsAreArray(). Since ElementsAreArray() shares most 2859 // of the implementation with ElementsAre(), we don't test it as 2860 // thoroughly here. 2861 2862 TEST(ElementsAreArrayTest, CanBeCreatedWithValueArray) { 2863 const int a[] = {1, 2, 3}; 2864 2865 vector<int> test_vector(std::begin(a), std::end(a)); 2866 EXPECT_THAT(test_vector, ElementsAreArray(a)); 2867 2868 test_vector[2] = 0; 2869 EXPECT_THAT(test_vector, Not(ElementsAreArray(a))); 2870 } 2871 2872 TEST(ElementsAreArrayTest, CanBeCreatedWithArraySize) { 2873 std::array<const char*, 3> a = {{"one", "two", "three"}}; 2874 2875 vector<std::string> test_vector(std::begin(a), std::end(a)); 2876 EXPECT_THAT(test_vector, ElementsAreArray(a.data(), a.size())); 2877 2878 const char** p = a.data(); 2879 test_vector[0] = "1"; 2880 EXPECT_THAT(test_vector, Not(ElementsAreArray(p, a.size()))); 2881 } 2882 2883 TEST(ElementsAreArrayTest, CanBeCreatedWithoutArraySize) { 2884 const char* a[] = {"one", "two", "three"}; 2885 2886 vector<std::string> test_vector(std::begin(a), std::end(a)); 2887 EXPECT_THAT(test_vector, ElementsAreArray(a)); 2888 2889 test_vector[0] = "1"; 2890 EXPECT_THAT(test_vector, Not(ElementsAreArray(a))); 2891 } 2892 2893 TEST(ElementsAreArrayTest, CanBeCreatedWithMatcherArray) { 2894 const Matcher<std::string> kMatcherArray[] = {StrEq("one"), StrEq("two"), 2895 StrEq("three")}; 2896 2897 vector<std::string> test_vector; 2898 test_vector.push_back("one"); 2899 test_vector.push_back("two"); 2900 test_vector.push_back("three"); 2901 EXPECT_THAT(test_vector, ElementsAreArray(kMatcherArray)); 2902 2903 test_vector.push_back("three"); 2904 EXPECT_THAT(test_vector, Not(ElementsAreArray(kMatcherArray))); 2905 } 2906 2907 TEST(ElementsAreArrayTest, CanBeCreatedWithVector) { 2908 const int a[] = {1, 2, 3}; 2909 vector<int> test_vector(std::begin(a), std::end(a)); 2910 const vector<int> expected(std::begin(a), std::end(a)); 2911 EXPECT_THAT(test_vector, ElementsAreArray(expected)); 2912 test_vector.push_back(4); 2913 EXPECT_THAT(test_vector, Not(ElementsAreArray(expected))); 2914 } 2915 2916 TEST(ElementsAreArrayTest, TakesInitializerList) { 2917 const int a[5] = {1, 2, 3, 4, 5}; 2918 EXPECT_THAT(a, ElementsAreArray({1, 2, 3, 4, 5})); 2919 EXPECT_THAT(a, Not(ElementsAreArray({1, 2, 3, 5, 4}))); 2920 EXPECT_THAT(a, Not(ElementsAreArray({1, 2, 3, 4, 6}))); 2921 } 2922 2923 TEST(ElementsAreArrayTest, TakesInitializerListOfCStrings) { 2924 const std::string a[5] = {"a", "b", "c", "d", "e"}; 2925 EXPECT_THAT(a, ElementsAreArray({"a", "b", "c", "d", "e"})); 2926 EXPECT_THAT(a, Not(ElementsAreArray({"a", "b", "c", "e", "d"}))); 2927 EXPECT_THAT(a, Not(ElementsAreArray({"a", "b", "c", "d", "ef"}))); 2928 } 2929 2930 TEST(ElementsAreArrayTest, TakesInitializerListOfSameTypedMatchers) { 2931 const int a[5] = {1, 2, 3, 4, 5}; 2932 EXPECT_THAT(a, ElementsAreArray({Eq(1), Eq(2), Eq(3), Eq(4), Eq(5)})); 2933 EXPECT_THAT(a, Not(ElementsAreArray({Eq(1), Eq(2), Eq(3), Eq(4), Eq(6)}))); 2934 } 2935 2936 TEST(ElementsAreArrayTest, TakesInitializerListOfDifferentTypedMatchers) { 2937 const int a[5] = {1, 2, 3, 4, 5}; 2938 // The compiler cannot infer the type of the initializer list if its 2939 // elements have different types. We must explicitly specify the 2940 // unified element type in this case. 2941 EXPECT_THAT( 2942 a, ElementsAreArray<Matcher<int>>({Eq(1), Ne(-2), Ge(3), Le(4), Eq(5)})); 2943 EXPECT_THAT(a, Not(ElementsAreArray<Matcher<int>>( 2944 {Eq(1), Ne(-2), Ge(3), Le(4), Eq(6)}))); 2945 } 2946 2947 TEST(ElementsAreArrayTest, CanBeCreatedWithMatcherVector) { 2948 const int a[] = {1, 2, 3}; 2949 const Matcher<int> kMatchers[] = {Eq(1), Eq(2), Eq(3)}; 2950 vector<int> test_vector(std::begin(a), std::end(a)); 2951 const vector<Matcher<int>> expected(std::begin(kMatchers), 2952 std::end(kMatchers)); 2953 EXPECT_THAT(test_vector, ElementsAreArray(expected)); 2954 test_vector.push_back(4); 2955 EXPECT_THAT(test_vector, Not(ElementsAreArray(expected))); 2956 } 2957 2958 TEST(ElementsAreArrayTest, CanBeCreatedWithIteratorRange) { 2959 const int a[] = {1, 2, 3}; 2960 const vector<int> test_vector(std::begin(a), std::end(a)); 2961 const vector<int> expected(std::begin(a), std::end(a)); 2962 EXPECT_THAT(test_vector, ElementsAreArray(expected.begin(), expected.end())); 2963 // Pointers are iterators, too. 2964 EXPECT_THAT(test_vector, ElementsAreArray(std::begin(a), std::end(a))); 2965 // The empty range of NULL pointers should also be okay. 2966 int* const null_int = nullptr; 2967 EXPECT_THAT(test_vector, Not(ElementsAreArray(null_int, null_int))); 2968 EXPECT_THAT((vector<int>()), ElementsAreArray(null_int, null_int)); 2969 } 2970 2971 // Since ElementsAre() and ElementsAreArray() share much of the 2972 // implementation, we only do a test for native arrays here. 2973 TEST(ElementsAreArrayTest, WorksWithNativeArray) { 2974 ::std::string a[] = {"hi", "ho"}; 2975 ::std::string b[] = {"hi", "ho"}; 2976 2977 EXPECT_THAT(a, ElementsAreArray(b)); 2978 EXPECT_THAT(a, ElementsAreArray(b, 2)); 2979 EXPECT_THAT(a, Not(ElementsAreArray(b, 1))); 2980 } 2981 2982 TEST(ElementsAreArrayTest, SourceLifeSpan) { 2983 const int a[] = {1, 2, 3}; 2984 vector<int> test_vector(std::begin(a), std::end(a)); 2985 vector<int> expect(std::begin(a), std::end(a)); 2986 ElementsAreArrayMatcher<int> matcher_maker = 2987 ElementsAreArray(expect.begin(), expect.end()); 2988 EXPECT_THAT(test_vector, matcher_maker); 2989 // Changing in place the values that initialized matcher_maker should not 2990 // affect matcher_maker anymore. It should have made its own copy of them. 2991 for (int& i : expect) { 2992 i += 10; 2993 } 2994 EXPECT_THAT(test_vector, matcher_maker); 2995 test_vector.push_back(3); 2996 EXPECT_THAT(test_vector, Not(matcher_maker)); 2997 } 2998 2999 // Tests Contains(). 3000 3001 INSTANTIATE_GTEST_MATCHER_TEST_P(ContainsTest); 3002 3003 TEST(ContainsTest, ListMatchesWhenElementIsInContainer) { 3004 list<int> some_list; 3005 some_list.push_back(3); 3006 some_list.push_back(1); 3007 some_list.push_back(2); 3008 some_list.push_back(3); 3009 EXPECT_THAT(some_list, Contains(1)); 3010 EXPECT_THAT(some_list, Contains(Gt(2.5))); 3011 EXPECT_THAT(some_list, Contains(Eq(2.0f))); 3012 3013 list<std::string> another_list; 3014 another_list.push_back("fee"); 3015 another_list.push_back("fie"); 3016 another_list.push_back("foe"); 3017 another_list.push_back("fum"); 3018 EXPECT_THAT(another_list, Contains(std::string("fee"))); 3019 } 3020 3021 TEST(ContainsTest, ListDoesNotMatchWhenElementIsNotInContainer) { 3022 list<int> some_list; 3023 some_list.push_back(3); 3024 some_list.push_back(1); 3025 EXPECT_THAT(some_list, Not(Contains(4))); 3026 } 3027 3028 TEST(ContainsTest, SetMatchesWhenElementIsInContainer) { 3029 set<int> some_set; 3030 some_set.insert(3); 3031 some_set.insert(1); 3032 some_set.insert(2); 3033 EXPECT_THAT(some_set, Contains(Eq(1.0))); 3034 EXPECT_THAT(some_set, Contains(Eq(3.0f))); 3035 EXPECT_THAT(some_set, Contains(2)); 3036 3037 set<std::string> another_set; 3038 another_set.insert("fee"); 3039 another_set.insert("fie"); 3040 another_set.insert("foe"); 3041 another_set.insert("fum"); 3042 EXPECT_THAT(another_set, Contains(Eq(std::string("fum")))); 3043 } 3044 3045 TEST(ContainsTest, SetDoesNotMatchWhenElementIsNotInContainer) { 3046 set<int> some_set; 3047 some_set.insert(3); 3048 some_set.insert(1); 3049 EXPECT_THAT(some_set, Not(Contains(4))); 3050 3051 set<std::string> c_string_set; 3052 c_string_set.insert("hello"); 3053 EXPECT_THAT(c_string_set, Not(Contains(std::string("goodbye")))); 3054 } 3055 3056 TEST_P(ContainsTestP, ExplainsMatchResultCorrectly) { 3057 const int a[2] = {1, 2}; 3058 Matcher<const int(&)[2]> m = Contains(2); 3059 EXPECT_EQ("whose element #1 matches", Explain(m, a)); 3060 3061 m = Contains(3); 3062 EXPECT_EQ("", Explain(m, a)); 3063 3064 m = Contains(GreaterThan(0)); 3065 EXPECT_EQ("whose element #0 matches, which is 1 more than 0", Explain(m, a)); 3066 3067 m = Contains(GreaterThan(10)); 3068 EXPECT_EQ("", Explain(m, a)); 3069 } 3070 3071 TEST(ContainsTest, DescribesItselfCorrectly) { 3072 Matcher<vector<int>> m = Contains(1); 3073 EXPECT_EQ("contains at least one element that is equal to 1", Describe(m)); 3074 3075 Matcher<vector<int>> m2 = Not(m); 3076 EXPECT_EQ("doesn't contain any element that is equal to 1", Describe(m2)); 3077 } 3078 3079 TEST(ContainsTest, MapMatchesWhenElementIsInContainer) { 3080 map<std::string, int> my_map; 3081 const char* bar = "a string"; 3082 my_map[bar] = 2; 3083 EXPECT_THAT(my_map, Contains(pair<const char* const, int>(bar, 2))); 3084 3085 map<std::string, int> another_map; 3086 another_map["fee"] = 1; 3087 another_map["fie"] = 2; 3088 another_map["foe"] = 3; 3089 another_map["fum"] = 4; 3090 EXPECT_THAT(another_map, 3091 Contains(pair<const std::string, int>(std::string("fee"), 1))); 3092 EXPECT_THAT(another_map, Contains(pair<const std::string, int>("fie", 2))); 3093 } 3094 3095 TEST(ContainsTest, MapDoesNotMatchWhenElementIsNotInContainer) { 3096 map<int, int> some_map; 3097 some_map[1] = 11; 3098 some_map[2] = 22; 3099 EXPECT_THAT(some_map, Not(Contains(pair<const int, int>(2, 23)))); 3100 } 3101 3102 TEST(ContainsTest, ArrayMatchesWhenElementIsInContainer) { 3103 const char* string_array[] = {"fee", "fie", "foe", "fum"}; 3104 EXPECT_THAT(string_array, Contains(Eq(std::string("fum")))); 3105 } 3106 3107 TEST(ContainsTest, ArrayDoesNotMatchWhenElementIsNotInContainer) { 3108 int int_array[] = {1, 2, 3, 4}; 3109 EXPECT_THAT(int_array, Not(Contains(5))); 3110 } 3111 3112 TEST(ContainsTest, AcceptsMatcher) { 3113 const int a[] = {1, 2, 3}; 3114 EXPECT_THAT(a, Contains(Gt(2))); 3115 EXPECT_THAT(a, Not(Contains(Gt(4)))); 3116 } 3117 3118 TEST(ContainsTest, WorksForNativeArrayAsTuple) { 3119 const int a[] = {1, 2}; 3120 const int* const pointer = a; 3121 EXPECT_THAT(std::make_tuple(pointer, 2), Contains(1)); 3122 EXPECT_THAT(std::make_tuple(pointer, 2), Not(Contains(Gt(3)))); 3123 } 3124 3125 TEST(ContainsTest, WorksForTwoDimensionalNativeArray) { 3126 int a[][3] = {{1, 2, 3}, {4, 5, 6}}; 3127 EXPECT_THAT(a, Contains(ElementsAre(4, 5, 6))); 3128 EXPECT_THAT(a, Contains(Contains(5))); 3129 EXPECT_THAT(a, Not(Contains(ElementsAre(3, 4, 5)))); 3130 EXPECT_THAT(a, Contains(Not(Contains(5)))); 3131 } 3132 3133 } // namespace 3134 } // namespace gmock_matchers_test 3135 } // namespace testing 3136 3137 GTEST_DISABLE_MSC_WARNINGS_POP_() // 4244 4100 3138