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 <array> 35 #include <cstdint> 36 #include <memory> 37 #include <ostream> 38 #include <string> 39 #include <tuple> 40 #include <utility> 41 #include <vector> 42 43 #include "gmock/gmock.h" 44 #include "test/gmock-matchers_test.h" 45 #include "gtest/gtest.h" 46 47 // Silence warning C4244: 'initializing': conversion from 'int' to 'short', 48 // possible loss of data and C4100, unreferenced local parameter 49 GTEST_DISABLE_MSC_WARNINGS_PUSH_(4244 4100) 50 51 namespace testing { 52 namespace gmock_matchers_test { 53 namespace { 54 55 TEST(AddressTest, NonConst) { 56 int n = 1; 57 const Matcher<int> m = Address(Eq(&n)); 58 59 EXPECT_TRUE(m.Matches(n)); 60 61 int other = 5; 62 63 EXPECT_FALSE(m.Matches(other)); 64 65 int& n_ref = n; 66 67 EXPECT_TRUE(m.Matches(n_ref)); 68 } 69 70 TEST(AddressTest, Const) { 71 const int n = 1; 72 const Matcher<int> m = Address(Eq(&n)); 73 74 EXPECT_TRUE(m.Matches(n)); 75 76 int other = 5; 77 78 EXPECT_FALSE(m.Matches(other)); 79 } 80 81 TEST(AddressTest, MatcherDoesntCopy) { 82 std::unique_ptr<int> n(new int(1)); 83 const Matcher<std::unique_ptr<int>> m = Address(Eq(&n)); 84 85 EXPECT_TRUE(m.Matches(n)); 86 } 87 88 TEST(AddressTest, Describe) { 89 Matcher<int> matcher = Address(_); 90 EXPECT_EQ("has address that is anything", Describe(matcher)); 91 EXPECT_EQ("does not have address that is anything", 92 DescribeNegation(matcher)); 93 } 94 95 // The following two tests verify that values without a public copy 96 // ctor can be used as arguments to matchers like Eq(), Ge(), and etc 97 // with the help of ByRef(). 98 99 class NotCopyable { 100 public: 101 explicit NotCopyable(int a_value) : value_(a_value) {} 102 103 int value() const { return value_; } 104 105 bool operator==(const NotCopyable& rhs) const { 106 return value() == rhs.value(); 107 } 108 109 bool operator>=(const NotCopyable& rhs) const { 110 return value() >= rhs.value(); 111 } 112 113 private: 114 int value_; 115 116 NotCopyable(const NotCopyable&) = delete; 117 NotCopyable& operator=(const NotCopyable&) = delete; 118 }; 119 120 TEST(ByRefTest, AllowsNotCopyableConstValueInMatchers) { 121 const NotCopyable const_value1(1); 122 const Matcher<const NotCopyable&> m = Eq(ByRef(const_value1)); 123 124 const NotCopyable n1(1), n2(2); 125 EXPECT_TRUE(m.Matches(n1)); 126 EXPECT_FALSE(m.Matches(n2)); 127 } 128 129 TEST(ByRefTest, AllowsNotCopyableValueInMatchers) { 130 NotCopyable value2(2); 131 const Matcher<NotCopyable&> m = Ge(ByRef(value2)); 132 133 NotCopyable n1(1), n2(2); 134 EXPECT_FALSE(m.Matches(n1)); 135 EXPECT_TRUE(m.Matches(n2)); 136 } 137 138 TEST(IsEmptyTest, ImplementsIsEmpty) { 139 vector<int> container; 140 EXPECT_THAT(container, IsEmpty()); 141 container.push_back(0); 142 EXPECT_THAT(container, Not(IsEmpty())); 143 container.push_back(1); 144 EXPECT_THAT(container, Not(IsEmpty())); 145 } 146 147 TEST(IsEmptyTest, WorksWithString) { 148 std::string text; 149 EXPECT_THAT(text, IsEmpty()); 150 text = "foo"; 151 EXPECT_THAT(text, Not(IsEmpty())); 152 text = std::string("\0", 1); 153 EXPECT_THAT(text, Not(IsEmpty())); 154 } 155 156 TEST(IsEmptyTest, CanDescribeSelf) { 157 Matcher<vector<int>> m = IsEmpty(); 158 EXPECT_EQ("is empty", Describe(m)); 159 EXPECT_EQ("isn't empty", DescribeNegation(m)); 160 } 161 162 TEST(IsEmptyTest, ExplainsResult) { 163 Matcher<vector<int>> m = IsEmpty(); 164 vector<int> container; 165 EXPECT_EQ("", Explain(m, container)); 166 container.push_back(0); 167 EXPECT_EQ("whose size is 1", Explain(m, container)); 168 } 169 170 TEST(IsEmptyTest, WorksWithMoveOnly) { 171 ContainerHelper helper; 172 EXPECT_CALL(helper, Call(IsEmpty())); 173 helper.Call({}); 174 } 175 176 TEST(IsTrueTest, IsTrueIsFalse) { 177 EXPECT_THAT(true, IsTrue()); 178 EXPECT_THAT(false, IsFalse()); 179 EXPECT_THAT(true, Not(IsFalse())); 180 EXPECT_THAT(false, Not(IsTrue())); 181 EXPECT_THAT(0, Not(IsTrue())); 182 EXPECT_THAT(0, IsFalse()); 183 EXPECT_THAT(nullptr, Not(IsTrue())); 184 EXPECT_THAT(nullptr, IsFalse()); 185 EXPECT_THAT(-1, IsTrue()); 186 EXPECT_THAT(-1, Not(IsFalse())); 187 EXPECT_THAT(1, IsTrue()); 188 EXPECT_THAT(1, Not(IsFalse())); 189 EXPECT_THAT(2, IsTrue()); 190 EXPECT_THAT(2, Not(IsFalse())); 191 int a = 42; 192 EXPECT_THAT(a, IsTrue()); 193 EXPECT_THAT(a, Not(IsFalse())); 194 EXPECT_THAT(&a, IsTrue()); 195 EXPECT_THAT(&a, Not(IsFalse())); 196 EXPECT_THAT(false, Not(IsTrue())); 197 EXPECT_THAT(true, Not(IsFalse())); 198 EXPECT_THAT(std::true_type(), IsTrue()); 199 EXPECT_THAT(std::true_type(), Not(IsFalse())); 200 EXPECT_THAT(std::false_type(), IsFalse()); 201 EXPECT_THAT(std::false_type(), Not(IsTrue())); 202 EXPECT_THAT(nullptr, Not(IsTrue())); 203 EXPECT_THAT(nullptr, IsFalse()); 204 std::unique_ptr<int> null_unique; 205 std::unique_ptr<int> nonnull_unique(new int(0)); 206 EXPECT_THAT(null_unique, Not(IsTrue())); 207 EXPECT_THAT(null_unique, IsFalse()); 208 EXPECT_THAT(nonnull_unique, IsTrue()); 209 EXPECT_THAT(nonnull_unique, Not(IsFalse())); 210 } 211 212 #ifdef GTEST_HAS_TYPED_TEST 213 // Tests ContainerEq with different container types, and 214 // different element types. 215 216 template <typename T> 217 class ContainerEqTest : public testing::Test {}; 218 219 typedef testing::Types<set<int>, vector<size_t>, multiset<size_t>, list<int>> 220 ContainerEqTestTypes; 221 222 TYPED_TEST_SUITE(ContainerEqTest, ContainerEqTestTypes); 223 224 // Tests that the filled container is equal to itself. 225 TYPED_TEST(ContainerEqTest, EqualsSelf) { 226 static const int vals[] = {1, 1, 2, 3, 5, 8}; 227 TypeParam my_set(vals, vals + 6); 228 const Matcher<TypeParam> m = ContainerEq(my_set); 229 EXPECT_TRUE(m.Matches(my_set)); 230 EXPECT_EQ("", Explain(m, my_set)); 231 } 232 233 // Tests that missing values are reported. 234 TYPED_TEST(ContainerEqTest, ValueMissing) { 235 static const int vals[] = {1, 1, 2, 3, 5, 8}; 236 static const int test_vals[] = {2, 1, 8, 5}; 237 TypeParam my_set(vals, vals + 6); 238 TypeParam test_set(test_vals, test_vals + 4); 239 const Matcher<TypeParam> m = ContainerEq(my_set); 240 EXPECT_FALSE(m.Matches(test_set)); 241 EXPECT_EQ("which doesn't have these expected elements: 3", 242 Explain(m, test_set)); 243 } 244 245 // Tests that added values are reported. 246 TYPED_TEST(ContainerEqTest, ValueAdded) { 247 static const int vals[] = {1, 1, 2, 3, 5, 8}; 248 static const int test_vals[] = {1, 2, 3, 5, 8, 46}; 249 TypeParam my_set(vals, vals + 6); 250 TypeParam test_set(test_vals, test_vals + 6); 251 const Matcher<const TypeParam&> m = ContainerEq(my_set); 252 EXPECT_FALSE(m.Matches(test_set)); 253 EXPECT_EQ("which has these unexpected elements: 46", Explain(m, test_set)); 254 } 255 256 // Tests that added and missing values are reported together. 257 TYPED_TEST(ContainerEqTest, ValueAddedAndRemoved) { 258 static const int vals[] = {1, 1, 2, 3, 5, 8}; 259 static const int test_vals[] = {1, 2, 3, 8, 46}; 260 TypeParam my_set(vals, vals + 6); 261 TypeParam test_set(test_vals, test_vals + 5); 262 const Matcher<TypeParam> m = ContainerEq(my_set); 263 EXPECT_FALSE(m.Matches(test_set)); 264 EXPECT_EQ( 265 "which has these unexpected elements: 46,\n" 266 "and doesn't have these expected elements: 5", 267 Explain(m, test_set)); 268 } 269 270 // Tests duplicated value -- expect no explanation. 271 TYPED_TEST(ContainerEqTest, DuplicateDifference) { 272 static const int vals[] = {1, 1, 2, 3, 5, 8}; 273 static const int test_vals[] = {1, 2, 3, 5, 8}; 274 TypeParam my_set(vals, vals + 6); 275 TypeParam test_set(test_vals, test_vals + 5); 276 const Matcher<const TypeParam&> m = ContainerEq(my_set); 277 // Depending on the container, match may be true or false 278 // But in any case there should be no explanation. 279 EXPECT_EQ("", Explain(m, test_set)); 280 } 281 #endif // GTEST_HAS_TYPED_TEST 282 283 // Tests that multiple missing values are reported. 284 // Using just vector here, so order is predictable. 285 TEST(ContainerEqExtraTest, MultipleValuesMissing) { 286 static const int vals[] = {1, 1, 2, 3, 5, 8}; 287 static const int test_vals[] = {2, 1, 5}; 288 vector<int> my_set(vals, vals + 6); 289 vector<int> test_set(test_vals, test_vals + 3); 290 const Matcher<vector<int>> m = ContainerEq(my_set); 291 EXPECT_FALSE(m.Matches(test_set)); 292 EXPECT_EQ("which doesn't have these expected elements: 3, 8", 293 Explain(m, test_set)); 294 } 295 296 // Tests that added values are reported. 297 // Using just vector here, so order is predictable. 298 TEST(ContainerEqExtraTest, MultipleValuesAdded) { 299 static const int vals[] = {1, 1, 2, 3, 5, 8}; 300 static const int test_vals[] = {1, 2, 92, 3, 5, 8, 46}; 301 list<size_t> my_set(vals, vals + 6); 302 list<size_t> test_set(test_vals, test_vals + 7); 303 const Matcher<const list<size_t>&> m = ContainerEq(my_set); 304 EXPECT_FALSE(m.Matches(test_set)); 305 EXPECT_EQ("which has these unexpected elements: 92, 46", 306 Explain(m, test_set)); 307 } 308 309 // Tests that added and missing values are reported together. 310 TEST(ContainerEqExtraTest, MultipleValuesAddedAndRemoved) { 311 static const int vals[] = {1, 1, 2, 3, 5, 8}; 312 static const int test_vals[] = {1, 2, 3, 92, 46}; 313 list<size_t> my_set(vals, vals + 6); 314 list<size_t> test_set(test_vals, test_vals + 5); 315 const Matcher<const list<size_t>> m = ContainerEq(my_set); 316 EXPECT_FALSE(m.Matches(test_set)); 317 EXPECT_EQ( 318 "which has these unexpected elements: 92, 46,\n" 319 "and doesn't have these expected elements: 5, 8", 320 Explain(m, test_set)); 321 } 322 323 // Tests to see that duplicate elements are detected, 324 // but (as above) not reported in the explanation. 325 TEST(ContainerEqExtraTest, MultiSetOfIntDuplicateDifference) { 326 static const int vals[] = {1, 1, 2, 3, 5, 8}; 327 static const int test_vals[] = {1, 2, 3, 5, 8}; 328 vector<int> my_set(vals, vals + 6); 329 vector<int> test_set(test_vals, test_vals + 5); 330 const Matcher<vector<int>> m = ContainerEq(my_set); 331 EXPECT_TRUE(m.Matches(my_set)); 332 EXPECT_FALSE(m.Matches(test_set)); 333 // There is nothing to report when both sets contain all the same values. 334 EXPECT_EQ("", Explain(m, test_set)); 335 } 336 337 // Tests that ContainerEq works for non-trivial associative containers, 338 // like maps. 339 TEST(ContainerEqExtraTest, WorksForMaps) { 340 map<int, std::string> my_map; 341 my_map[0] = "a"; 342 my_map[1] = "b"; 343 344 map<int, std::string> test_map; 345 test_map[0] = "aa"; 346 test_map[1] = "b"; 347 348 const Matcher<const map<int, std::string>&> m = ContainerEq(my_map); 349 EXPECT_TRUE(m.Matches(my_map)); 350 EXPECT_FALSE(m.Matches(test_map)); 351 352 EXPECT_EQ( 353 "which has these unexpected elements: (0, \"aa\"),\n" 354 "and doesn't have these expected elements: (0, \"a\")", 355 Explain(m, test_map)); 356 } 357 358 TEST(ContainerEqExtraTest, WorksForNativeArray) { 359 int a1[] = {1, 2, 3}; 360 int a2[] = {1, 2, 3}; 361 int b[] = {1, 2, 4}; 362 363 EXPECT_THAT(a1, ContainerEq(a2)); 364 EXPECT_THAT(a1, Not(ContainerEq(b))); 365 } 366 367 TEST(ContainerEqExtraTest, WorksForTwoDimensionalNativeArray) { 368 const char a1[][3] = {"hi", "lo"}; 369 const char a2[][3] = {"hi", "lo"}; 370 const char b[][3] = {"lo", "hi"}; 371 372 // Tests using ContainerEq() in the first dimension. 373 EXPECT_THAT(a1, ContainerEq(a2)); 374 EXPECT_THAT(a1, Not(ContainerEq(b))); 375 376 // Tests using ContainerEq() in the second dimension. 377 EXPECT_THAT(a1, ElementsAre(ContainerEq(a2[0]), ContainerEq(a2[1]))); 378 EXPECT_THAT(a1, ElementsAre(Not(ContainerEq(b[0])), ContainerEq(a2[1]))); 379 } 380 381 TEST(ContainerEqExtraTest, WorksForNativeArrayAsTuple) { 382 const int a1[] = {1, 2, 3}; 383 const int a2[] = {1, 2, 3}; 384 const int b[] = {1, 2, 3, 4}; 385 386 const int* const p1 = a1; 387 EXPECT_THAT(std::make_tuple(p1, 3), ContainerEq(a2)); 388 EXPECT_THAT(std::make_tuple(p1, 3), Not(ContainerEq(b))); 389 390 const int c[] = {1, 3, 2}; 391 EXPECT_THAT(std::make_tuple(p1, 3), Not(ContainerEq(c))); 392 } 393 394 TEST(ContainerEqExtraTest, CopiesNativeArrayParameter) { 395 std::string a1[][3] = {{"hi", "hello", "ciao"}, {"bye", "see you", "ciao"}}; 396 397 std::string a2[][3] = {{"hi", "hello", "ciao"}, {"bye", "see you", "ciao"}}; 398 399 const Matcher<const std::string(&)[2][3]> m = ContainerEq(a2); 400 EXPECT_THAT(a1, m); 401 402 a2[0][0] = "ha"; 403 EXPECT_THAT(a1, m); 404 } 405 406 namespace { 407 408 // Used as a check on the more complex max flow method used in the 409 // real testing::internal::FindMaxBipartiteMatching. This method is 410 // compatible but runs in worst-case factorial time, so we only 411 // use it in testing for small problem sizes. 412 template <typename Graph> 413 class BacktrackingMaxBPMState { 414 public: 415 // Does not take ownership of 'g'. 416 explicit BacktrackingMaxBPMState(const Graph* g) : graph_(g) {} 417 418 ElementMatcherPairs Compute() { 419 if (graph_->LhsSize() == 0 || graph_->RhsSize() == 0) { 420 return best_so_far_; 421 } 422 lhs_used_.assign(graph_->LhsSize(), kUnused); 423 rhs_used_.assign(graph_->RhsSize(), kUnused); 424 for (size_t irhs = 0; irhs < graph_->RhsSize(); ++irhs) { 425 matches_.clear(); 426 RecurseInto(irhs); 427 if (best_so_far_.size() == graph_->RhsSize()) break; 428 } 429 return best_so_far_; 430 } 431 432 private: 433 static const size_t kUnused = static_cast<size_t>(-1); 434 435 void PushMatch(size_t lhs, size_t rhs) { 436 matches_.push_back(ElementMatcherPair(lhs, rhs)); 437 lhs_used_[lhs] = rhs; 438 rhs_used_[rhs] = lhs; 439 if (matches_.size() > best_so_far_.size()) { 440 best_so_far_ = matches_; 441 } 442 } 443 444 void PopMatch() { 445 const ElementMatcherPair& back = matches_.back(); 446 lhs_used_[back.first] = kUnused; 447 rhs_used_[back.second] = kUnused; 448 matches_.pop_back(); 449 } 450 451 bool RecurseInto(size_t irhs) { 452 if (rhs_used_[irhs] != kUnused) { 453 return true; 454 } 455 for (size_t ilhs = 0; ilhs < graph_->LhsSize(); ++ilhs) { 456 if (lhs_used_[ilhs] != kUnused) { 457 continue; 458 } 459 if (!graph_->HasEdge(ilhs, irhs)) { 460 continue; 461 } 462 PushMatch(ilhs, irhs); 463 if (best_so_far_.size() == graph_->RhsSize()) { 464 return false; 465 } 466 for (size_t mi = irhs + 1; mi < graph_->RhsSize(); ++mi) { 467 if (!RecurseInto(mi)) return false; 468 } 469 PopMatch(); 470 } 471 return true; 472 } 473 474 const Graph* graph_; // not owned 475 std::vector<size_t> lhs_used_; 476 std::vector<size_t> rhs_used_; 477 ElementMatcherPairs matches_; 478 ElementMatcherPairs best_so_far_; 479 }; 480 481 template <typename Graph> 482 const size_t BacktrackingMaxBPMState<Graph>::kUnused; 483 484 } // namespace 485 486 // Implement a simple backtracking algorithm to determine if it is possible 487 // to find one element per matcher, without reusing elements. 488 template <typename Graph> 489 ElementMatcherPairs FindBacktrackingMaxBPM(const Graph& g) { 490 return BacktrackingMaxBPMState<Graph>(&g).Compute(); 491 } 492 493 class BacktrackingBPMTest : public ::testing::Test {}; 494 495 // Tests the MaxBipartiteMatching algorithm with square matrices. 496 // The single int param is the # of nodes on each of the left and right sides. 497 class BipartiteTest : public ::testing::TestWithParam<size_t> {}; 498 499 // Verify all match graphs up to some moderate number of edges. 500 TEST_P(BipartiteTest, Exhaustive) { 501 size_t nodes = GetParam(); 502 MatchMatrix graph(nodes, nodes); 503 do { 504 ElementMatcherPairs matches = internal::FindMaxBipartiteMatching(graph); 505 EXPECT_EQ(FindBacktrackingMaxBPM(graph).size(), matches.size()) 506 << "graph: " << graph.DebugString(); 507 // Check that all elements of matches are in the graph. 508 // Check that elements of first and second are unique. 509 std::vector<bool> seen_element(graph.LhsSize()); 510 std::vector<bool> seen_matcher(graph.RhsSize()); 511 SCOPED_TRACE(PrintToString(matches)); 512 for (size_t i = 0; i < matches.size(); ++i) { 513 size_t ilhs = matches[i].first; 514 size_t irhs = matches[i].second; 515 EXPECT_TRUE(graph.HasEdge(ilhs, irhs)); 516 EXPECT_FALSE(seen_element[ilhs]); 517 EXPECT_FALSE(seen_matcher[irhs]); 518 seen_element[ilhs] = true; 519 seen_matcher[irhs] = true; 520 } 521 } while (graph.NextGraph()); 522 } 523 524 INSTANTIATE_TEST_SUITE_P(AllGraphs, BipartiteTest, 525 ::testing::Range(size_t{0}, size_t{5})); 526 527 // Parameterized by a pair interpreted as (LhsSize, RhsSize). 528 class BipartiteNonSquareTest 529 : public ::testing::TestWithParam<std::pair<size_t, size_t>> {}; 530 531 TEST_F(BipartiteNonSquareTest, SimpleBacktracking) { 532 // ....... 533 // 0:-----\ : 534 // 1:---\ | : 535 // 2:---\ | : 536 // 3:-\ | | : 537 // :.......: 538 // 0 1 2 539 MatchMatrix g(4, 3); 540 constexpr std::array<std::array<size_t, 2>, 4> kEdges = { 541 {{{0, 2}}, {{1, 1}}, {{2, 1}}, {{3, 0}}}}; 542 for (size_t i = 0; i < kEdges.size(); ++i) { 543 g.SetEdge(kEdges[i][0], kEdges[i][1], true); 544 } 545 EXPECT_THAT(FindBacktrackingMaxBPM(g), 546 ElementsAre(Pair(3, 0), Pair(AnyOf(1, 2), 1), Pair(0, 2))) 547 << g.DebugString(); 548 } 549 550 // Verify a few nonsquare matrices. 551 TEST_P(BipartiteNonSquareTest, Exhaustive) { 552 size_t nlhs = GetParam().first; 553 size_t nrhs = GetParam().second; 554 MatchMatrix graph(nlhs, nrhs); 555 do { 556 EXPECT_EQ(FindBacktrackingMaxBPM(graph).size(), 557 internal::FindMaxBipartiteMatching(graph).size()) 558 << "graph: " << graph.DebugString() 559 << "\nbacktracking: " << PrintToString(FindBacktrackingMaxBPM(graph)) 560 << "\nmax flow: " 561 << PrintToString(internal::FindMaxBipartiteMatching(graph)); 562 } while (graph.NextGraph()); 563 } 564 565 INSTANTIATE_TEST_SUITE_P( 566 AllGraphs, BipartiteNonSquareTest, 567 testing::Values(std::make_pair(1, 2), std::make_pair(2, 1), 568 std::make_pair(3, 2), std::make_pair(2, 3), 569 std::make_pair(4, 1), std::make_pair(1, 4), 570 std::make_pair(4, 3), std::make_pair(3, 4))); 571 572 class BipartiteRandomTest 573 : public ::testing::TestWithParam<std::pair<int, int>> {}; 574 575 // Verifies a large sample of larger graphs. 576 TEST_P(BipartiteRandomTest, LargerNets) { 577 int nodes = GetParam().first; 578 int iters = GetParam().second; 579 MatchMatrix graph(static_cast<size_t>(nodes), static_cast<size_t>(nodes)); 580 581 auto seed = static_cast<uint32_t>(GTEST_FLAG_GET(random_seed)); 582 if (seed == 0) { 583 seed = static_cast<uint32_t>(time(nullptr)); 584 } 585 586 for (; iters > 0; --iters, ++seed) { 587 srand(static_cast<unsigned int>(seed)); 588 graph.Randomize(); 589 EXPECT_EQ(FindBacktrackingMaxBPM(graph).size(), 590 internal::FindMaxBipartiteMatching(graph).size()) 591 << " graph: " << graph.DebugString() 592 << "\nTo reproduce the failure, rerun the test with the flag" 593 " --" 594 << GTEST_FLAG_PREFIX_ << "random_seed=" << seed; 595 } 596 } 597 598 // Test argument is a std::pair<int, int> representing (nodes, iters). 599 INSTANTIATE_TEST_SUITE_P(Samples, BipartiteRandomTest, 600 testing::Values(std::make_pair(5, 10000), 601 std::make_pair(6, 5000), 602 std::make_pair(7, 2000), 603 std::make_pair(8, 500), 604 std::make_pair(9, 100))); 605 606 // Tests IsReadableTypeName(). 607 608 TEST(IsReadableTypeNameTest, ReturnsTrueForShortNames) { 609 EXPECT_TRUE(IsReadableTypeName("int")); 610 EXPECT_TRUE(IsReadableTypeName("const unsigned char*")); 611 EXPECT_TRUE(IsReadableTypeName("MyMap<int, void*>")); 612 EXPECT_TRUE(IsReadableTypeName("void (*)(int, bool)")); 613 } 614 615 TEST(IsReadableTypeNameTest, ReturnsTrueForLongNonTemplateNonFunctionNames) { 616 EXPECT_TRUE(IsReadableTypeName("my_long_namespace::MyClassName")); 617 EXPECT_TRUE(IsReadableTypeName("int [5][6][7][8][9][10][11]")); 618 EXPECT_TRUE(IsReadableTypeName("my_namespace::MyOuterClass::MyInnerClass")); 619 } 620 621 TEST(IsReadableTypeNameTest, ReturnsFalseForLongTemplateNames) { 622 EXPECT_FALSE( 623 IsReadableTypeName("basic_string<char, std::char_traits<char> >")); 624 EXPECT_FALSE(IsReadableTypeName("std::vector<int, std::alloc_traits<int> >")); 625 } 626 627 TEST(IsReadableTypeNameTest, ReturnsFalseForLongFunctionTypeNames) { 628 EXPECT_FALSE(IsReadableTypeName("void (&)(int, bool, char, float)")); 629 } 630 631 // Tests FormatMatcherDescription(). 632 633 TEST(FormatMatcherDescriptionTest, WorksForEmptyDescription) { 634 EXPECT_EQ("is even", 635 FormatMatcherDescription(false, "IsEven", {}, Strings())); 636 EXPECT_EQ("not (is even)", 637 FormatMatcherDescription(true, "IsEven", {}, Strings())); 638 639 EXPECT_EQ("equals (a: 5)", 640 FormatMatcherDescription(false, "Equals", {"a"}, {"5"})); 641 642 EXPECT_EQ( 643 "is in range (a: 5, b: 8)", 644 FormatMatcherDescription(false, "IsInRange", {"a", "b"}, {"5", "8"})); 645 } 646 647 INSTANTIATE_GTEST_MATCHER_TEST_P(MatcherTupleTest); 648 649 TEST_P(MatcherTupleTestP, ExplainsMatchFailure) { 650 stringstream ss1; 651 ExplainMatchFailureTupleTo( 652 std::make_tuple(Matcher<char>(Eq('a')), GreaterThan(5)), 653 std::make_tuple('a', 10), &ss1); 654 EXPECT_EQ("", ss1.str()); // Successful match. 655 656 stringstream ss2; 657 ExplainMatchFailureTupleTo( 658 std::make_tuple(GreaterThan(5), Matcher<char>(Eq('a'))), 659 std::make_tuple(2, 'b'), &ss2); 660 EXPECT_EQ( 661 " Expected arg #0: is > 5\n" 662 " Actual: 2, which is 3 less than 5\n" 663 " Expected arg #1: is equal to 'a' (97, 0x61)\n" 664 " Actual: 'b' (98, 0x62)\n", 665 ss2.str()); // Failed match where both arguments need explanation. 666 667 stringstream ss3; 668 ExplainMatchFailureTupleTo( 669 std::make_tuple(GreaterThan(5), Matcher<char>(Eq('a'))), 670 std::make_tuple(2, 'a'), &ss3); 671 EXPECT_EQ( 672 " Expected arg #0: is > 5\n" 673 " Actual: 2, which is 3 less than 5\n", 674 ss3.str()); // Failed match where only one argument needs 675 // explanation. 676 } 677 678 #if GTEST_HAS_TYPED_TEST 679 680 // Sample optional type implementation with minimal requirements for use with 681 // Optional matcher. 682 template <typename T> 683 class SampleOptional { 684 public: 685 using value_type = T; 686 explicit SampleOptional(T value) 687 : value_(std::move(value)), has_value_(true) {} 688 SampleOptional() : value_(), has_value_(false) {} 689 operator bool() const { return has_value_; } 690 const T& operator*() const { return value_; } 691 692 private: 693 T value_; 694 bool has_value_; 695 }; 696 697 // Sample optional type implementation with alternative minimal requirements for 698 // use with Optional matcher. In particular, while it doesn't have a bool 699 // conversion operator, it does have a has_value() method. 700 template <typename T> 701 class SampleOptionalWithoutBoolConversion { 702 public: 703 using value_type = T; 704 explicit SampleOptionalWithoutBoolConversion(T value) 705 : value_(std::move(value)), has_value_(true) {} 706 SampleOptionalWithoutBoolConversion() : value_(), has_value_(false) {} 707 bool has_value() const { return has_value_; } 708 const T& operator*() const { return value_; } 709 710 private: 711 T value_; 712 bool has_value_; 713 }; 714 715 template <typename T> 716 class OptionalTest : public testing::Test {}; 717 718 using OptionalTestTypes = 719 testing::Types<SampleOptional<int>, 720 SampleOptionalWithoutBoolConversion<int>>; 721 722 TYPED_TEST_SUITE(OptionalTest, OptionalTestTypes); 723 724 TYPED_TEST(OptionalTest, DescribesSelf) { 725 const Matcher<TypeParam> m = Optional(Eq(1)); 726 EXPECT_EQ("value is equal to 1", Describe(m)); 727 } 728 729 TYPED_TEST(OptionalTest, ExplainsSelf) { 730 const Matcher<TypeParam> m = Optional(Eq(1)); 731 EXPECT_EQ("whose value 1 matches", Explain(m, TypeParam(1))); 732 EXPECT_EQ("whose value 2 doesn't match", Explain(m, TypeParam(2))); 733 } 734 735 TYPED_TEST(OptionalTest, MatchesNonEmptyOptional) { 736 const Matcher<TypeParam> m1 = Optional(1); 737 const Matcher<TypeParam> m2 = Optional(Eq(2)); 738 const Matcher<TypeParam> m3 = Optional(Lt(3)); 739 TypeParam opt(1); 740 EXPECT_TRUE(m1.Matches(opt)); 741 EXPECT_FALSE(m2.Matches(opt)); 742 EXPECT_TRUE(m3.Matches(opt)); 743 } 744 745 TYPED_TEST(OptionalTest, DoesNotMatchNullopt) { 746 const Matcher<TypeParam> m = Optional(1); 747 TypeParam empty; 748 EXPECT_FALSE(m.Matches(empty)); 749 } 750 751 TYPED_TEST(OptionalTest, ComposesWithMonomorphicMatchersTakingReferences) { 752 const Matcher<const int&> eq1 = Eq(1); 753 const Matcher<const int&> eq2 = Eq(2); 754 TypeParam opt(1); 755 EXPECT_THAT(opt, Optional(eq1)); 756 EXPECT_THAT(opt, Optional(Not(eq2))); 757 EXPECT_THAT(opt, Optional(AllOf(eq1, Not(eq2)))); 758 } 759 760 TYPED_TEST(OptionalTest, ComposesWithMonomorphicMatchersRequiringConversion) { 761 const Matcher<int64_t> eq1 = Eq(1); 762 const Matcher<int64_t> eq2 = Eq(2); 763 TypeParam opt(1); 764 EXPECT_THAT(opt, Optional(eq1)); 765 EXPECT_THAT(opt, Optional(Not(eq2))); 766 EXPECT_THAT(opt, Optional(AllOf(eq1, Not(eq2)))); 767 } 768 769 template <typename T> 770 class MoveOnlyOptionalTest : public testing::Test {}; 771 772 using MoveOnlyOptionalTestTypes = 773 testing::Types<SampleOptional<std::unique_ptr<int>>, 774 SampleOptionalWithoutBoolConversion<std::unique_ptr<int>>>; 775 776 TYPED_TEST_SUITE(MoveOnlyOptionalTest, MoveOnlyOptionalTestTypes); 777 778 TYPED_TEST(MoveOnlyOptionalTest, WorksWithMoveOnly) { 779 Matcher<TypeParam> m = Optional(Eq(nullptr)); 780 EXPECT_TRUE(m.Matches(TypeParam(nullptr))); 781 } 782 783 #endif // GTEST_HAS_TYPED_TEST 784 785 class SampleVariantIntString { 786 public: 787 SampleVariantIntString(int i) : i_(i), has_int_(true) {} 788 SampleVariantIntString(const std::string& s) : s_(s), has_int_(false) {} 789 790 template <typename T> 791 friend bool holds_alternative(const SampleVariantIntString& value) { 792 return value.has_int_ == std::is_same<T, int>::value; 793 } 794 795 template <typename T> 796 friend const T& get(const SampleVariantIntString& value) { 797 return value.get_impl(static_cast<T*>(nullptr)); 798 } 799 800 private: 801 const int& get_impl(int*) const { return i_; } 802 const std::string& get_impl(std::string*) const { return s_; } 803 804 int i_; 805 std::string s_; 806 bool has_int_; 807 }; 808 809 TEST(VariantTest, DescribesSelf) { 810 const Matcher<SampleVariantIntString> m = VariantWith<int>(Eq(1)); 811 EXPECT_THAT(Describe(m), ContainsRegex("is a variant<> with value of type " 812 "'.*' and the value is equal to 1")); 813 } 814 815 TEST(VariantTest, ExplainsSelf) { 816 const Matcher<SampleVariantIntString> m = VariantWith<int>(Eq(1)); 817 EXPECT_THAT(Explain(m, SampleVariantIntString(1)), 818 ContainsRegex("whose value 1")); 819 EXPECT_THAT(Explain(m, SampleVariantIntString("A")), 820 HasSubstr("whose value is not of type '")); 821 EXPECT_THAT(Explain(m, SampleVariantIntString(2)), 822 "whose value 2 doesn't match"); 823 } 824 825 TEST(VariantTest, FullMatch) { 826 Matcher<SampleVariantIntString> m = VariantWith<int>(Eq(1)); 827 EXPECT_TRUE(m.Matches(SampleVariantIntString(1))); 828 829 m = VariantWith<std::string>(Eq("1")); 830 EXPECT_TRUE(m.Matches(SampleVariantIntString("1"))); 831 } 832 833 TEST(VariantTest, TypeDoesNotMatch) { 834 Matcher<SampleVariantIntString> m = VariantWith<int>(Eq(1)); 835 EXPECT_FALSE(m.Matches(SampleVariantIntString("1"))); 836 837 m = VariantWith<std::string>(Eq("1")); 838 EXPECT_FALSE(m.Matches(SampleVariantIntString(1))); 839 } 840 841 TEST(VariantTest, InnerDoesNotMatch) { 842 Matcher<SampleVariantIntString> m = VariantWith<int>(Eq(1)); 843 EXPECT_FALSE(m.Matches(SampleVariantIntString(2))); 844 845 m = VariantWith<std::string>(Eq("1")); 846 EXPECT_FALSE(m.Matches(SampleVariantIntString("2"))); 847 } 848 849 class SampleAnyType { 850 public: 851 explicit SampleAnyType(int i) : index_(0), i_(i) {} 852 explicit SampleAnyType(const std::string& s) : index_(1), s_(s) {} 853 854 template <typename T> 855 friend const T* any_cast(const SampleAnyType* any) { 856 return any->get_impl(static_cast<T*>(nullptr)); 857 } 858 859 private: 860 int index_; 861 int i_; 862 std::string s_; 863 864 const int* get_impl(int*) const { return index_ == 0 ? &i_ : nullptr; } 865 const std::string* get_impl(std::string*) const { 866 return index_ == 1 ? &s_ : nullptr; 867 } 868 }; 869 870 TEST(AnyWithTest, FullMatch) { 871 Matcher<SampleAnyType> m = AnyWith<int>(Eq(1)); 872 EXPECT_TRUE(m.Matches(SampleAnyType(1))); 873 } 874 875 TEST(AnyWithTest, TestBadCastType) { 876 Matcher<SampleAnyType> m = AnyWith<std::string>(Eq("fail")); 877 EXPECT_FALSE(m.Matches(SampleAnyType(1))); 878 } 879 880 TEST(AnyWithTest, TestUseInContainers) { 881 std::vector<SampleAnyType> a; 882 a.emplace_back(1); 883 a.emplace_back(2); 884 a.emplace_back(3); 885 EXPECT_THAT( 886 a, ElementsAreArray({AnyWith<int>(1), AnyWith<int>(2), AnyWith<int>(3)})); 887 888 std::vector<SampleAnyType> b; 889 b.emplace_back("hello"); 890 b.emplace_back("merhaba"); 891 b.emplace_back("salut"); 892 EXPECT_THAT(b, ElementsAreArray({AnyWith<std::string>("hello"), 893 AnyWith<std::string>("merhaba"), 894 AnyWith<std::string>("salut")})); 895 } 896 TEST(AnyWithTest, TestCompare) { 897 EXPECT_THAT(SampleAnyType(1), AnyWith<int>(Gt(0))); 898 } 899 900 TEST(AnyWithTest, DescribesSelf) { 901 const Matcher<const SampleAnyType&> m = AnyWith<int>(Eq(1)); 902 EXPECT_THAT(Describe(m), ContainsRegex("is an 'any' type with value of type " 903 "'.*' and the value is equal to 1")); 904 } 905 906 TEST(AnyWithTest, ExplainsSelf) { 907 const Matcher<const SampleAnyType&> m = AnyWith<int>(Eq(1)); 908 909 EXPECT_THAT(Explain(m, SampleAnyType(1)), ContainsRegex("whose value 1")); 910 EXPECT_THAT(Explain(m, SampleAnyType("A")), 911 HasSubstr("whose value is not of type '")); 912 EXPECT_THAT(Explain(m, SampleAnyType(2)), "whose value 2 doesn't match"); 913 } 914 915 // Tests Args<k0, ..., kn>(m). 916 917 TEST(ArgsTest, AcceptsZeroTemplateArg) { 918 const std::tuple<int, bool> t(5, true); 919 EXPECT_THAT(t, Args<>(Eq(std::tuple<>()))); 920 EXPECT_THAT(t, Not(Args<>(Ne(std::tuple<>())))); 921 } 922 923 TEST(ArgsTest, AcceptsOneTemplateArg) { 924 const std::tuple<int, bool> t(5, true); 925 EXPECT_THAT(t, Args<0>(Eq(std::make_tuple(5)))); 926 EXPECT_THAT(t, Args<1>(Eq(std::make_tuple(true)))); 927 EXPECT_THAT(t, Not(Args<1>(Eq(std::make_tuple(false))))); 928 } 929 930 TEST(ArgsTest, AcceptsTwoTemplateArgs) { 931 const std::tuple<short, int, long> t(short{4}, 5, 6L); // NOLINT 932 933 EXPECT_THAT(t, (Args<0, 1>(Lt()))); 934 EXPECT_THAT(t, (Args<1, 2>(Lt()))); 935 EXPECT_THAT(t, Not(Args<0, 2>(Gt()))); 936 } 937 938 TEST(ArgsTest, AcceptsRepeatedTemplateArgs) { 939 const std::tuple<short, int, long> t(short{4}, 5, 6L); // NOLINT 940 EXPECT_THAT(t, (Args<0, 0>(Eq()))); 941 EXPECT_THAT(t, Not(Args<1, 1>(Ne()))); 942 } 943 944 TEST(ArgsTest, AcceptsDecreasingTemplateArgs) { 945 const std::tuple<short, int, long> t(short{4}, 5, 6L); // NOLINT 946 EXPECT_THAT(t, (Args<2, 0>(Gt()))); 947 EXPECT_THAT(t, Not(Args<2, 1>(Lt()))); 948 } 949 950 MATCHER(SumIsZero, "") { 951 return std::get<0>(arg) + std::get<1>(arg) + std::get<2>(arg) == 0; 952 } 953 954 TEST(ArgsTest, AcceptsMoreTemplateArgsThanArityOfOriginalTuple) { 955 EXPECT_THAT(std::make_tuple(-1, 2), (Args<0, 0, 1>(SumIsZero()))); 956 EXPECT_THAT(std::make_tuple(1, 2), Not(Args<0, 0, 1>(SumIsZero()))); 957 } 958 959 TEST(ArgsTest, CanBeNested) { 960 const std::tuple<short, int, long, int> t(short{4}, 5, 6L, 6); // NOLINT 961 EXPECT_THAT(t, (Args<1, 2, 3>(Args<1, 2>(Eq())))); 962 EXPECT_THAT(t, (Args<0, 1, 3>(Args<0, 2>(Lt())))); 963 } 964 965 TEST(ArgsTest, CanMatchTupleByValue) { 966 typedef std::tuple<char, int, int> Tuple3; 967 const Matcher<Tuple3> m = Args<1, 2>(Lt()); 968 EXPECT_TRUE(m.Matches(Tuple3('a', 1, 2))); 969 EXPECT_FALSE(m.Matches(Tuple3('b', 2, 2))); 970 } 971 972 TEST(ArgsTest, CanMatchTupleByReference) { 973 typedef std::tuple<char, char, int> Tuple3; 974 const Matcher<const Tuple3&> m = Args<0, 1>(Lt()); 975 EXPECT_TRUE(m.Matches(Tuple3('a', 'b', 2))); 976 EXPECT_FALSE(m.Matches(Tuple3('b', 'b', 2))); 977 } 978 979 // Validates that arg is printed as str. 980 MATCHER_P(PrintsAs, str, "") { return testing::PrintToString(arg) == str; } 981 982 TEST(ArgsTest, AcceptsTenTemplateArgs) { 983 EXPECT_THAT(std::make_tuple(0, 1L, 2, 3L, 4, 5, 6, 7, 8, 9), 984 (Args<9, 8, 7, 6, 5, 4, 3, 2, 1, 0>( 985 PrintsAs("(9, 8, 7, 6, 5, 4, 3, 2, 1, 0)")))); 986 EXPECT_THAT(std::make_tuple(0, 1L, 2, 3L, 4, 5, 6, 7, 8, 9), 987 Not(Args<9, 8, 7, 6, 5, 4, 3, 2, 1, 0>( 988 PrintsAs("(0, 8, 7, 6, 5, 4, 3, 2, 1, 0)")))); 989 } 990 991 TEST(ArgsTest, DescirbesSelfCorrectly) { 992 const Matcher<std::tuple<int, bool, char>> m = Args<2, 0>(Lt()); 993 EXPECT_EQ( 994 "are a tuple whose fields (#2, #0) are a pair where " 995 "the first < the second", 996 Describe(m)); 997 } 998 999 TEST(ArgsTest, DescirbesNestedArgsCorrectly) { 1000 const Matcher<const std::tuple<int, bool, char, int>&> m = 1001 Args<0, 2, 3>(Args<2, 0>(Lt())); 1002 EXPECT_EQ( 1003 "are a tuple whose fields (#0, #2, #3) are a tuple " 1004 "whose fields (#2, #0) are a pair where the first < the second", 1005 Describe(m)); 1006 } 1007 1008 TEST(ArgsTest, DescribesNegationCorrectly) { 1009 const Matcher<std::tuple<int, char>> m = Args<1, 0>(Gt()); 1010 EXPECT_EQ( 1011 "are a tuple whose fields (#1, #0) aren't a pair " 1012 "where the first > the second", 1013 DescribeNegation(m)); 1014 } 1015 1016 TEST(ArgsTest, ExplainsMatchResultWithoutInnerExplanation) { 1017 const Matcher<std::tuple<bool, int, int>> m = Args<1, 2>(Eq()); 1018 EXPECT_EQ("whose fields (#1, #2) are (42, 42)", 1019 Explain(m, std::make_tuple(false, 42, 42))); 1020 EXPECT_EQ("whose fields (#1, #2) are (42, 43)", 1021 Explain(m, std::make_tuple(false, 42, 43))); 1022 } 1023 1024 // For testing Args<>'s explanation. 1025 class LessThanMatcher : public MatcherInterface<std::tuple<char, int>> { 1026 public: 1027 void DescribeTo(::std::ostream* /*os*/) const override {} 1028 1029 bool MatchAndExplain(std::tuple<char, int> value, 1030 MatchResultListener* listener) const override { 1031 const int diff = std::get<0>(value) - std::get<1>(value); 1032 if (diff > 0) { 1033 *listener << "where the first value is " << diff 1034 << " more than the second"; 1035 } 1036 return diff < 0; 1037 } 1038 }; 1039 1040 Matcher<std::tuple<char, int>> LessThan() { 1041 return MakeMatcher(new LessThanMatcher); 1042 } 1043 1044 TEST(ArgsTest, ExplainsMatchResultWithInnerExplanation) { 1045 const Matcher<std::tuple<char, int, int>> m = Args<0, 2>(LessThan()); 1046 EXPECT_EQ( 1047 "whose fields (#0, #2) are ('a' (97, 0x61), 42), " 1048 "where the first value is 55 more than the second", 1049 Explain(m, std::make_tuple('a', 42, 42))); 1050 EXPECT_EQ("whose fields (#0, #2) are ('\\0', 43)", 1051 Explain(m, std::make_tuple('\0', 42, 43))); 1052 } 1053 1054 // Tests for the MATCHER*() macro family. 1055 1056 // Tests that a simple MATCHER() definition works. 1057 1058 MATCHER(IsEven, "") { return (arg % 2) == 0; } 1059 1060 TEST(MatcherMacroTest, Works) { 1061 const Matcher<int> m = IsEven(); 1062 EXPECT_TRUE(m.Matches(6)); 1063 EXPECT_FALSE(m.Matches(7)); 1064 1065 EXPECT_EQ("is even", Describe(m)); 1066 EXPECT_EQ("not (is even)", DescribeNegation(m)); 1067 EXPECT_EQ("", Explain(m, 6)); 1068 EXPECT_EQ("", Explain(m, 7)); 1069 } 1070 1071 // This also tests that the description string can reference 'negation'. 1072 MATCHER(IsEven2, negation ? "is odd" : "is even") { 1073 if ((arg % 2) == 0) { 1074 // Verifies that we can stream to result_listener, a listener 1075 // supplied by the MATCHER macro implicitly. 1076 *result_listener << "OK"; 1077 return true; 1078 } else { 1079 *result_listener << "% 2 == " << (arg % 2); 1080 return false; 1081 } 1082 } 1083 1084 // This also tests that the description string can reference matcher 1085 // parameters. 1086 MATCHER_P2(EqSumOf, x, y, 1087 std::string(negation ? "doesn't equal" : "equals") + " the sum of " + 1088 PrintToString(x) + " and " + PrintToString(y)) { 1089 if (arg == (x + y)) { 1090 *result_listener << "OK"; 1091 return true; 1092 } else { 1093 // Verifies that we can stream to the underlying stream of 1094 // result_listener. 1095 if (result_listener->stream() != nullptr) { 1096 *result_listener->stream() << "diff == " << (x + y - arg); 1097 } 1098 return false; 1099 } 1100 } 1101 1102 // Tests that the matcher description can reference 'negation' and the 1103 // matcher parameters. 1104 TEST(MatcherMacroTest, DescriptionCanReferenceNegationAndParameters) { 1105 const Matcher<int> m1 = IsEven2(); 1106 EXPECT_EQ("is even", Describe(m1)); 1107 EXPECT_EQ("is odd", DescribeNegation(m1)); 1108 1109 const Matcher<int> m2 = EqSumOf(5, 9); 1110 EXPECT_EQ("equals the sum of 5 and 9", Describe(m2)); 1111 EXPECT_EQ("doesn't equal the sum of 5 and 9", DescribeNegation(m2)); 1112 } 1113 1114 // Tests explaining match result in a MATCHER* macro. 1115 TEST(MatcherMacroTest, CanExplainMatchResult) { 1116 const Matcher<int> m1 = IsEven2(); 1117 EXPECT_EQ("OK", Explain(m1, 4)); 1118 EXPECT_EQ("% 2 == 1", Explain(m1, 5)); 1119 1120 const Matcher<int> m2 = EqSumOf(1, 2); 1121 EXPECT_EQ("OK", Explain(m2, 3)); 1122 EXPECT_EQ("diff == -1", Explain(m2, 4)); 1123 } 1124 1125 // Tests that the body of MATCHER() can reference the type of the 1126 // value being matched. 1127 1128 MATCHER(IsEmptyString, "") { 1129 StaticAssertTypeEq<::std::string, arg_type>(); 1130 return arg.empty(); 1131 } 1132 1133 MATCHER(IsEmptyStringByRef, "") { 1134 StaticAssertTypeEq<const ::std::string&, arg_type>(); 1135 return arg.empty(); 1136 } 1137 1138 TEST(MatcherMacroTest, CanReferenceArgType) { 1139 const Matcher<::std::string> m1 = IsEmptyString(); 1140 EXPECT_TRUE(m1.Matches("")); 1141 1142 const Matcher<const ::std::string&> m2 = IsEmptyStringByRef(); 1143 EXPECT_TRUE(m2.Matches("")); 1144 } 1145 1146 // Tests that MATCHER() can be used in a namespace. 1147 1148 namespace matcher_test { 1149 MATCHER(IsOdd, "") { return (arg % 2) != 0; } 1150 } // namespace matcher_test 1151 1152 TEST(MatcherMacroTest, WorksInNamespace) { 1153 Matcher<int> m = matcher_test::IsOdd(); 1154 EXPECT_FALSE(m.Matches(4)); 1155 EXPECT_TRUE(m.Matches(5)); 1156 } 1157 1158 // Tests that Value() can be used to compose matchers. 1159 MATCHER(IsPositiveOdd, "") { 1160 return Value(arg, matcher_test::IsOdd()) && arg > 0; 1161 } 1162 1163 TEST(MatcherMacroTest, CanBeComposedUsingValue) { 1164 EXPECT_THAT(3, IsPositiveOdd()); 1165 EXPECT_THAT(4, Not(IsPositiveOdd())); 1166 EXPECT_THAT(-1, Not(IsPositiveOdd())); 1167 } 1168 1169 // Tests that a simple MATCHER_P() definition works. 1170 1171 MATCHER_P(IsGreaterThan32And, n, "") { return arg > 32 && arg > n; } 1172 1173 TEST(MatcherPMacroTest, Works) { 1174 const Matcher<int> m = IsGreaterThan32And(5); 1175 EXPECT_TRUE(m.Matches(36)); 1176 EXPECT_FALSE(m.Matches(5)); 1177 1178 EXPECT_EQ("is greater than 32 and (n: 5)", Describe(m)); 1179 EXPECT_EQ("not (is greater than 32 and (n: 5))", DescribeNegation(m)); 1180 EXPECT_EQ("", Explain(m, 36)); 1181 EXPECT_EQ("", Explain(m, 5)); 1182 } 1183 1184 // Tests that the description is calculated correctly from the matcher name. 1185 MATCHER_P(_is_Greater_Than32and_, n, "") { return arg > 32 && arg > n; } 1186 1187 TEST(MatcherPMacroTest, GeneratesCorrectDescription) { 1188 const Matcher<int> m = _is_Greater_Than32and_(5); 1189 1190 EXPECT_EQ("is greater than 32 and (n: 5)", Describe(m)); 1191 EXPECT_EQ("not (is greater than 32 and (n: 5))", DescribeNegation(m)); 1192 EXPECT_EQ("", Explain(m, 36)); 1193 EXPECT_EQ("", Explain(m, 5)); 1194 } 1195 1196 // Tests that a MATCHER_P matcher can be explicitly instantiated with 1197 // a reference parameter type. 1198 1199 class UncopyableFoo { 1200 public: 1201 explicit UncopyableFoo(char value) : value_(value) { (void)value_; } 1202 1203 UncopyableFoo(const UncopyableFoo&) = delete; 1204 void operator=(const UncopyableFoo&) = delete; 1205 1206 private: 1207 char value_; 1208 }; 1209 1210 MATCHER_P(ReferencesUncopyable, variable, "") { return &arg == &variable; } 1211 1212 TEST(MatcherPMacroTest, WorksWhenExplicitlyInstantiatedWithReference) { 1213 UncopyableFoo foo1('1'), foo2('2'); 1214 const Matcher<const UncopyableFoo&> m = 1215 ReferencesUncopyable<const UncopyableFoo&>(foo1); 1216 1217 EXPECT_TRUE(m.Matches(foo1)); 1218 EXPECT_FALSE(m.Matches(foo2)); 1219 1220 // We don't want the address of the parameter printed, as most 1221 // likely it will just annoy the user. If the address is 1222 // interesting, the user should consider passing the parameter by 1223 // pointer instead. 1224 EXPECT_EQ("references uncopyable (variable: 1-byte object <31>)", 1225 Describe(m)); 1226 } 1227 1228 // Tests that the body of MATCHER_Pn() can reference the parameter 1229 // types. 1230 1231 MATCHER_P3(ParamTypesAreIntLongAndChar, foo, bar, baz, "") { 1232 StaticAssertTypeEq<int, foo_type>(); 1233 StaticAssertTypeEq<long, bar_type>(); // NOLINT 1234 StaticAssertTypeEq<char, baz_type>(); 1235 return arg == 0; 1236 } 1237 1238 TEST(MatcherPnMacroTest, CanReferenceParamTypes) { 1239 EXPECT_THAT(0, ParamTypesAreIntLongAndChar(10, 20L, 'a')); 1240 } 1241 1242 // Tests that a MATCHER_Pn matcher can be explicitly instantiated with 1243 // reference parameter types. 1244 1245 MATCHER_P2(ReferencesAnyOf, variable1, variable2, "") { 1246 return &arg == &variable1 || &arg == &variable2; 1247 } 1248 1249 TEST(MatcherPnMacroTest, WorksWhenExplicitlyInstantiatedWithReferences) { 1250 UncopyableFoo foo1('1'), foo2('2'), foo3('3'); 1251 const Matcher<const UncopyableFoo&> const_m = 1252 ReferencesAnyOf<const UncopyableFoo&, const UncopyableFoo&>(foo1, foo2); 1253 1254 EXPECT_TRUE(const_m.Matches(foo1)); 1255 EXPECT_TRUE(const_m.Matches(foo2)); 1256 EXPECT_FALSE(const_m.Matches(foo3)); 1257 1258 const Matcher<UncopyableFoo&> m = 1259 ReferencesAnyOf<UncopyableFoo&, UncopyableFoo&>(foo1, foo2); 1260 1261 EXPECT_TRUE(m.Matches(foo1)); 1262 EXPECT_TRUE(m.Matches(foo2)); 1263 EXPECT_FALSE(m.Matches(foo3)); 1264 } 1265 1266 TEST(MatcherPnMacroTest, 1267 GeneratesCorretDescriptionWhenExplicitlyInstantiatedWithReferences) { 1268 UncopyableFoo foo1('1'), foo2('2'); 1269 const Matcher<const UncopyableFoo&> m = 1270 ReferencesAnyOf<const UncopyableFoo&, const UncopyableFoo&>(foo1, foo2); 1271 1272 // We don't want the addresses of the parameters printed, as most 1273 // likely they will just annoy the user. If the addresses are 1274 // interesting, the user should consider passing the parameters by 1275 // pointers instead. 1276 EXPECT_EQ( 1277 "references any of (variable1: 1-byte object <31>, variable2: 1-byte " 1278 "object <32>)", 1279 Describe(m)); 1280 } 1281 1282 // Tests that a simple MATCHER_P2() definition works. 1283 1284 MATCHER_P2(IsNotInClosedRange, low, hi, "") { return arg < low || arg > hi; } 1285 1286 TEST(MatcherPnMacroTest, Works) { 1287 const Matcher<const long&> m = IsNotInClosedRange(10, 20); // NOLINT 1288 EXPECT_TRUE(m.Matches(36L)); 1289 EXPECT_FALSE(m.Matches(15L)); 1290 1291 EXPECT_EQ("is not in closed range (low: 10, hi: 20)", Describe(m)); 1292 EXPECT_EQ("not (is not in closed range (low: 10, hi: 20))", 1293 DescribeNegation(m)); 1294 EXPECT_EQ("", Explain(m, 36L)); 1295 EXPECT_EQ("", Explain(m, 15L)); 1296 } 1297 1298 // Tests that MATCHER*() definitions can be overloaded on the number 1299 // of parameters; also tests MATCHER_Pn() where n >= 3. 1300 1301 MATCHER(EqualsSumOf, "") { return arg == 0; } 1302 MATCHER_P(EqualsSumOf, a, "") { return arg == a; } 1303 MATCHER_P2(EqualsSumOf, a, b, "") { return arg == a + b; } 1304 MATCHER_P3(EqualsSumOf, a, b, c, "") { return arg == a + b + c; } 1305 MATCHER_P4(EqualsSumOf, a, b, c, d, "") { return arg == a + b + c + d; } 1306 MATCHER_P5(EqualsSumOf, a, b, c, d, e, "") { return arg == a + b + c + d + e; } 1307 MATCHER_P6(EqualsSumOf, a, b, c, d, e, f, "") { 1308 return arg == a + b + c + d + e + f; 1309 } 1310 MATCHER_P7(EqualsSumOf, a, b, c, d, e, f, g, "") { 1311 return arg == a + b + c + d + e + f + g; 1312 } 1313 MATCHER_P8(EqualsSumOf, a, b, c, d, e, f, g, h, "") { 1314 return arg == a + b + c + d + e + f + g + h; 1315 } 1316 MATCHER_P9(EqualsSumOf, a, b, c, d, e, f, g, h, i, "") { 1317 return arg == a + b + c + d + e + f + g + h + i; 1318 } 1319 MATCHER_P10(EqualsSumOf, a, b, c, d, e, f, g, h, i, j, "") { 1320 return arg == a + b + c + d + e + f + g + h + i + j; 1321 } 1322 1323 TEST(MatcherPnMacroTest, CanBeOverloadedOnNumberOfParameters) { 1324 EXPECT_THAT(0, EqualsSumOf()); 1325 EXPECT_THAT(1, EqualsSumOf(1)); 1326 EXPECT_THAT(12, EqualsSumOf(10, 2)); 1327 EXPECT_THAT(123, EqualsSumOf(100, 20, 3)); 1328 EXPECT_THAT(1234, EqualsSumOf(1000, 200, 30, 4)); 1329 EXPECT_THAT(12345, EqualsSumOf(10000, 2000, 300, 40, 5)); 1330 EXPECT_THAT("abcdef", 1331 EqualsSumOf(::std::string("a"), 'b', 'c', "d", "e", 'f')); 1332 EXPECT_THAT("abcdefg", 1333 EqualsSumOf(::std::string("a"), 'b', 'c', "d", "e", 'f', 'g')); 1334 EXPECT_THAT("abcdefgh", EqualsSumOf(::std::string("a"), 'b', 'c', "d", "e", 1335 'f', 'g', "h")); 1336 EXPECT_THAT("abcdefghi", EqualsSumOf(::std::string("a"), 'b', 'c', "d", "e", 1337 'f', 'g', "h", 'i')); 1338 EXPECT_THAT("abcdefghij", 1339 EqualsSumOf(::std::string("a"), 'b', 'c', "d", "e", 'f', 'g', "h", 1340 'i', ::std::string("j"))); 1341 1342 EXPECT_THAT(1, Not(EqualsSumOf())); 1343 EXPECT_THAT(-1, Not(EqualsSumOf(1))); 1344 EXPECT_THAT(-12, Not(EqualsSumOf(10, 2))); 1345 EXPECT_THAT(-123, Not(EqualsSumOf(100, 20, 3))); 1346 EXPECT_THAT(-1234, Not(EqualsSumOf(1000, 200, 30, 4))); 1347 EXPECT_THAT(-12345, Not(EqualsSumOf(10000, 2000, 300, 40, 5))); 1348 EXPECT_THAT("abcdef ", 1349 Not(EqualsSumOf(::std::string("a"), 'b', 'c', "d", "e", 'f'))); 1350 EXPECT_THAT("abcdefg ", Not(EqualsSumOf(::std::string("a"), 'b', 'c', "d", 1351 "e", 'f', 'g'))); 1352 EXPECT_THAT("abcdefgh ", Not(EqualsSumOf(::std::string("a"), 'b', 'c', "d", 1353 "e", 'f', 'g', "h"))); 1354 EXPECT_THAT("abcdefghi ", Not(EqualsSumOf(::std::string("a"), 'b', 'c', "d", 1355 "e", 'f', 'g', "h", 'i'))); 1356 EXPECT_THAT("abcdefghij ", 1357 Not(EqualsSumOf(::std::string("a"), 'b', 'c', "d", "e", 'f', 'g', 1358 "h", 'i', ::std::string("j")))); 1359 } 1360 1361 // Tests that a MATCHER_Pn() definition can be instantiated with any 1362 // compatible parameter types. 1363 TEST(MatcherPnMacroTest, WorksForDifferentParameterTypes) { 1364 EXPECT_THAT(123, EqualsSumOf(100L, 20, static_cast<char>(3))); 1365 EXPECT_THAT("abcd", EqualsSumOf(::std::string("a"), "b", 'c', "d")); 1366 1367 EXPECT_THAT(124, Not(EqualsSumOf(100L, 20, static_cast<char>(3)))); 1368 EXPECT_THAT("abcde", Not(EqualsSumOf(::std::string("a"), "b", 'c', "d"))); 1369 } 1370 1371 // Tests that the matcher body can promote the parameter types. 1372 1373 MATCHER_P2(EqConcat, prefix, suffix, "") { 1374 // The following lines promote the two parameters to desired types. 1375 std::string prefix_str(prefix); 1376 char suffix_char = static_cast<char>(suffix); 1377 return arg == prefix_str + suffix_char; 1378 } 1379 1380 TEST(MatcherPnMacroTest, SimpleTypePromotion) { 1381 Matcher<std::string> no_promo = EqConcat(std::string("foo"), 't'); 1382 Matcher<const std::string&> promo = EqConcat("foo", static_cast<int>('t')); 1383 EXPECT_FALSE(no_promo.Matches("fool")); 1384 EXPECT_FALSE(promo.Matches("fool")); 1385 EXPECT_TRUE(no_promo.Matches("foot")); 1386 EXPECT_TRUE(promo.Matches("foot")); 1387 } 1388 1389 // Verifies the type of a MATCHER*. 1390 1391 TEST(MatcherPnMacroTest, TypesAreCorrect) { 1392 // EqualsSumOf() must be assignable to a EqualsSumOfMatcher variable. 1393 EqualsSumOfMatcher a0 = EqualsSumOf(); 1394 1395 // EqualsSumOf(1) must be assignable to a EqualsSumOfMatcherP variable. 1396 EqualsSumOfMatcherP<int> a1 = EqualsSumOf(1); 1397 1398 // EqualsSumOf(p1, ..., pk) must be assignable to a EqualsSumOfMatcherPk 1399 // variable, and so on. 1400 EqualsSumOfMatcherP2<int, char> a2 = EqualsSumOf(1, '2'); 1401 EqualsSumOfMatcherP3<int, int, char> a3 = EqualsSumOf(1, 2, '3'); 1402 EqualsSumOfMatcherP4<int, int, int, char> a4 = EqualsSumOf(1, 2, 3, '4'); 1403 EqualsSumOfMatcherP5<int, int, int, int, char> a5 = 1404 EqualsSumOf(1, 2, 3, 4, '5'); 1405 EqualsSumOfMatcherP6<int, int, int, int, int, char> a6 = 1406 EqualsSumOf(1, 2, 3, 4, 5, '6'); 1407 EqualsSumOfMatcherP7<int, int, int, int, int, int, char> a7 = 1408 EqualsSumOf(1, 2, 3, 4, 5, 6, '7'); 1409 EqualsSumOfMatcherP8<int, int, int, int, int, int, int, char> a8 = 1410 EqualsSumOf(1, 2, 3, 4, 5, 6, 7, '8'); 1411 EqualsSumOfMatcherP9<int, int, int, int, int, int, int, int, char> a9 = 1412 EqualsSumOf(1, 2, 3, 4, 5, 6, 7, 8, '9'); 1413 EqualsSumOfMatcherP10<int, int, int, int, int, int, int, int, int, char> a10 = 1414 EqualsSumOf(1, 2, 3, 4, 5, 6, 7, 8, 9, '0'); 1415 1416 // Avoid "unused variable" warnings. 1417 (void)a0; 1418 (void)a1; 1419 (void)a2; 1420 (void)a3; 1421 (void)a4; 1422 (void)a5; 1423 (void)a6; 1424 (void)a7; 1425 (void)a8; 1426 (void)a9; 1427 (void)a10; 1428 } 1429 1430 // Tests that matcher-typed parameters can be used in Value() inside a 1431 // MATCHER_Pn definition. 1432 1433 // Succeeds if arg matches exactly 2 of the 3 matchers. 1434 MATCHER_P3(TwoOf, m1, m2, m3, "") { 1435 const int count = static_cast<int>(Value(arg, m1)) + 1436 static_cast<int>(Value(arg, m2)) + 1437 static_cast<int>(Value(arg, m3)); 1438 return count == 2; 1439 } 1440 1441 TEST(MatcherPnMacroTest, CanUseMatcherTypedParameterInValue) { 1442 EXPECT_THAT(42, TwoOf(Gt(0), Lt(50), Eq(10))); 1443 EXPECT_THAT(0, Not(TwoOf(Gt(-1), Lt(1), Eq(0)))); 1444 } 1445 1446 // Tests Contains().Times(). 1447 1448 INSTANTIATE_GTEST_MATCHER_TEST_P(ContainsTimes); 1449 1450 TEST(ContainsTimes, ListMatchesWhenElementQuantityMatches) { 1451 list<int> some_list; 1452 some_list.push_back(3); 1453 some_list.push_back(1); 1454 some_list.push_back(2); 1455 some_list.push_back(3); 1456 EXPECT_THAT(some_list, Contains(3).Times(2)); 1457 EXPECT_THAT(some_list, Contains(2).Times(1)); 1458 EXPECT_THAT(some_list, Contains(Ge(2)).Times(3)); 1459 EXPECT_THAT(some_list, Contains(Ge(2)).Times(Gt(2))); 1460 EXPECT_THAT(some_list, Contains(4).Times(0)); 1461 EXPECT_THAT(some_list, Contains(_).Times(4)); 1462 EXPECT_THAT(some_list, Not(Contains(5).Times(1))); 1463 EXPECT_THAT(some_list, Contains(5).Times(_)); // Times(_) always matches 1464 EXPECT_THAT(some_list, Not(Contains(3).Times(1))); 1465 EXPECT_THAT(some_list, Contains(3).Times(Not(1))); 1466 EXPECT_THAT(list<int>{}, Not(Contains(_))); 1467 } 1468 1469 TEST_P(ContainsTimesP, ExplainsMatchResultCorrectly) { 1470 const int a[2] = {1, 2}; 1471 Matcher<const int(&)[2]> m = Contains(2).Times(3); 1472 EXPECT_EQ( 1473 "whose element #1 matches but whose match quantity of 1 does not match", 1474 Explain(m, a)); 1475 1476 m = Contains(3).Times(0); 1477 EXPECT_EQ("has no element that matches and whose match quantity of 0 matches", 1478 Explain(m, a)); 1479 1480 m = Contains(3).Times(4); 1481 EXPECT_EQ( 1482 "has no element that matches and whose match quantity of 0 does not " 1483 "match", 1484 Explain(m, a)); 1485 1486 m = Contains(2).Times(4); 1487 EXPECT_EQ( 1488 "whose element #1 matches but whose match quantity of 1 does not " 1489 "match", 1490 Explain(m, a)); 1491 1492 m = Contains(GreaterThan(0)).Times(2); 1493 EXPECT_EQ("whose elements (0, 1) match and whose match quantity of 2 matches", 1494 Explain(m, a)); 1495 1496 m = Contains(GreaterThan(10)).Times(Gt(1)); 1497 EXPECT_EQ( 1498 "has no element that matches and whose match quantity of 0 does not " 1499 "match", 1500 Explain(m, a)); 1501 1502 m = Contains(GreaterThan(0)).Times(GreaterThan<size_t>(5)); 1503 EXPECT_EQ( 1504 "whose elements (0, 1) match but whose match quantity of 2 does not " 1505 "match, which is 3 less than 5", 1506 Explain(m, a)); 1507 } 1508 1509 TEST(ContainsTimes, DescribesItselfCorrectly) { 1510 Matcher<vector<int>> m = Contains(1).Times(2); 1511 EXPECT_EQ("quantity of elements that match is equal to 1 is equal to 2", 1512 Describe(m)); 1513 1514 Matcher<vector<int>> m2 = Not(m); 1515 EXPECT_EQ("quantity of elements that match is equal to 1 isn't equal to 2", 1516 Describe(m2)); 1517 } 1518 1519 // Tests AllOfArray() 1520 1521 TEST(AllOfArrayTest, BasicForms) { 1522 // Iterator 1523 std::vector<int> v0{}; 1524 std::vector<int> v1{1}; 1525 std::vector<int> v2{2, 3}; 1526 std::vector<int> v3{4, 4, 4}; 1527 EXPECT_THAT(0, AllOfArray(v0.begin(), v0.end())); 1528 EXPECT_THAT(1, AllOfArray(v1.begin(), v1.end())); 1529 EXPECT_THAT(2, Not(AllOfArray(v1.begin(), v1.end()))); 1530 EXPECT_THAT(3, Not(AllOfArray(v2.begin(), v2.end()))); 1531 EXPECT_THAT(4, AllOfArray(v3.begin(), v3.end())); 1532 // Pointer + size 1533 int ar[6] = {1, 2, 3, 4, 4, 4}; 1534 EXPECT_THAT(0, AllOfArray(ar, 0)); 1535 EXPECT_THAT(1, AllOfArray(ar, 1)); 1536 EXPECT_THAT(2, Not(AllOfArray(ar, 1))); 1537 EXPECT_THAT(3, Not(AllOfArray(ar + 1, 3))); 1538 EXPECT_THAT(4, AllOfArray(ar + 3, 3)); 1539 // Array 1540 // int ar0[0]; Not usable 1541 int ar1[1] = {1}; 1542 int ar2[2] = {2, 3}; 1543 int ar3[3] = {4, 4, 4}; 1544 // EXPECT_THAT(0, Not(AllOfArray(ar0))); // Cannot work 1545 EXPECT_THAT(1, AllOfArray(ar1)); 1546 EXPECT_THAT(2, Not(AllOfArray(ar1))); 1547 EXPECT_THAT(3, Not(AllOfArray(ar2))); 1548 EXPECT_THAT(4, AllOfArray(ar3)); 1549 // Container 1550 EXPECT_THAT(0, AllOfArray(v0)); 1551 EXPECT_THAT(1, AllOfArray(v1)); 1552 EXPECT_THAT(2, Not(AllOfArray(v1))); 1553 EXPECT_THAT(3, Not(AllOfArray(v2))); 1554 EXPECT_THAT(4, AllOfArray(v3)); 1555 // Initializer 1556 EXPECT_THAT(0, AllOfArray<int>({})); // Requires template arg. 1557 EXPECT_THAT(1, AllOfArray({1})); 1558 EXPECT_THAT(2, Not(AllOfArray({1}))); 1559 EXPECT_THAT(3, Not(AllOfArray({2, 3}))); 1560 EXPECT_THAT(4, AllOfArray({4, 4, 4})); 1561 } 1562 1563 TEST(AllOfArrayTest, Matchers) { 1564 // vector 1565 std::vector<Matcher<int>> matchers{Ge(1), Lt(2)}; 1566 EXPECT_THAT(0, Not(AllOfArray(matchers))); 1567 EXPECT_THAT(1, AllOfArray(matchers)); 1568 EXPECT_THAT(2, Not(AllOfArray(matchers))); 1569 // initializer_list 1570 EXPECT_THAT(0, Not(AllOfArray({Ge(0), Ge(1)}))); 1571 EXPECT_THAT(1, AllOfArray({Ge(0), Ge(1)})); 1572 } 1573 1574 INSTANTIATE_GTEST_MATCHER_TEST_P(AnyOfArrayTest); 1575 1576 TEST(AnyOfArrayTest, BasicForms) { 1577 // Iterator 1578 std::vector<int> v0{}; 1579 std::vector<int> v1{1}; 1580 std::vector<int> v2{2, 3}; 1581 EXPECT_THAT(0, Not(AnyOfArray(v0.begin(), v0.end()))); 1582 EXPECT_THAT(1, AnyOfArray(v1.begin(), v1.end())); 1583 EXPECT_THAT(2, Not(AnyOfArray(v1.begin(), v1.end()))); 1584 EXPECT_THAT(3, AnyOfArray(v2.begin(), v2.end())); 1585 EXPECT_THAT(4, Not(AnyOfArray(v2.begin(), v2.end()))); 1586 // Pointer + size 1587 int ar[3] = {1, 2, 3}; 1588 EXPECT_THAT(0, Not(AnyOfArray(ar, 0))); 1589 EXPECT_THAT(1, AnyOfArray(ar, 1)); 1590 EXPECT_THAT(2, Not(AnyOfArray(ar, 1))); 1591 EXPECT_THAT(3, AnyOfArray(ar + 1, 2)); 1592 EXPECT_THAT(4, Not(AnyOfArray(ar + 1, 2))); 1593 // Array 1594 // int ar0[0]; Not usable 1595 int ar1[1] = {1}; 1596 int ar2[2] = {2, 3}; 1597 // EXPECT_THAT(0, Not(AnyOfArray(ar0))); // Cannot work 1598 EXPECT_THAT(1, AnyOfArray(ar1)); 1599 EXPECT_THAT(2, Not(AnyOfArray(ar1))); 1600 EXPECT_THAT(3, AnyOfArray(ar2)); 1601 EXPECT_THAT(4, Not(AnyOfArray(ar2))); 1602 // Container 1603 EXPECT_THAT(0, Not(AnyOfArray(v0))); 1604 EXPECT_THAT(1, AnyOfArray(v1)); 1605 EXPECT_THAT(2, Not(AnyOfArray(v1))); 1606 EXPECT_THAT(3, AnyOfArray(v2)); 1607 EXPECT_THAT(4, Not(AnyOfArray(v2))); 1608 // Initializer 1609 EXPECT_THAT(0, Not(AnyOfArray<int>({}))); // Requires template arg. 1610 EXPECT_THAT(1, AnyOfArray({1})); 1611 EXPECT_THAT(2, Not(AnyOfArray({1}))); 1612 EXPECT_THAT(3, AnyOfArray({2, 3})); 1613 EXPECT_THAT(4, Not(AnyOfArray({2, 3}))); 1614 } 1615 1616 TEST(AnyOfArrayTest, Matchers) { 1617 // We negate test AllOfArrayTest.Matchers. 1618 // vector 1619 std::vector<Matcher<int>> matchers{Lt(1), Ge(2)}; 1620 EXPECT_THAT(0, AnyOfArray(matchers)); 1621 EXPECT_THAT(1, Not(AnyOfArray(matchers))); 1622 EXPECT_THAT(2, AnyOfArray(matchers)); 1623 // initializer_list 1624 EXPECT_THAT(0, AnyOfArray({Lt(0), Lt(1)})); 1625 EXPECT_THAT(1, Not(AllOfArray({Lt(0), Lt(1)}))); 1626 } 1627 1628 TEST_P(AnyOfArrayTestP, ExplainsMatchResultCorrectly) { 1629 // AnyOfArray and AllOfArray use the same underlying template-template, 1630 // thus it is sufficient to test one here. 1631 const std::vector<int> v0{}; 1632 const std::vector<int> v1{1}; 1633 const std::vector<int> v2{2, 3}; 1634 const Matcher<int> m0 = AnyOfArray(v0); 1635 const Matcher<int> m1 = AnyOfArray(v1); 1636 const Matcher<int> m2 = AnyOfArray(v2); 1637 EXPECT_EQ("", Explain(m0, 0)); 1638 EXPECT_EQ("which matches (is equal to 1)", Explain(m1, 1)); 1639 EXPECT_EQ("isn't equal to 1", Explain(m1, 2)); 1640 EXPECT_EQ("which matches (is equal to 3)", Explain(m2, 3)); 1641 EXPECT_EQ("isn't equal to 2, and isn't equal to 3", Explain(m2, 4)); 1642 EXPECT_EQ("()", Describe(m0)); 1643 EXPECT_EQ("(is equal to 1)", Describe(m1)); 1644 EXPECT_EQ("(is equal to 2) or (is equal to 3)", Describe(m2)); 1645 EXPECT_EQ("()", DescribeNegation(m0)); 1646 EXPECT_EQ("(isn't equal to 1)", DescribeNegation(m1)); 1647 EXPECT_EQ("(isn't equal to 2) and (isn't equal to 3)", DescribeNegation(m2)); 1648 // Explain with matchers 1649 const Matcher<int> g1 = AnyOfArray({GreaterThan(1)}); 1650 const Matcher<int> g2 = AnyOfArray({GreaterThan(1), GreaterThan(2)}); 1651 // Explains the first positive match and all prior negative matches... 1652 EXPECT_EQ("which is 1 less than 1", Explain(g1, 0)); 1653 EXPECT_EQ("which is the same as 1", Explain(g1, 1)); 1654 EXPECT_EQ("which is 1 more than 1", Explain(g1, 2)); 1655 EXPECT_EQ("which is 1 less than 1, and which is 2 less than 2", 1656 Explain(g2, 0)); 1657 EXPECT_EQ("which is the same as 1, and which is 1 less than 2", 1658 Explain(g2, 1)); 1659 EXPECT_EQ("which is 1 more than 1", // Only the first 1660 Explain(g2, 2)); 1661 } 1662 1663 MATCHER(IsNotNull, "") { return arg != nullptr; } 1664 1665 // Verifies that a matcher defined using MATCHER() can work on 1666 // move-only types. 1667 TEST(MatcherMacroTest, WorksOnMoveOnlyType) { 1668 std::unique_ptr<int> p(new int(3)); 1669 EXPECT_THAT(p, IsNotNull()); 1670 EXPECT_THAT(std::unique_ptr<int>(), Not(IsNotNull())); 1671 } 1672 1673 MATCHER_P(UniquePointee, pointee, "") { return *arg == pointee; } 1674 1675 // Verifies that a matcher defined using MATCHER_P*() can work on 1676 // move-only types. 1677 TEST(MatcherPMacroTest, WorksOnMoveOnlyType) { 1678 std::unique_ptr<int> p(new int(3)); 1679 EXPECT_THAT(p, UniquePointee(3)); 1680 EXPECT_THAT(p, Not(UniquePointee(2))); 1681 } 1682 1683 MATCHER(EnsureNoUnusedButMarkedUnusedWarning, "") { return (arg % 2) == 0; } 1684 1685 TEST(MockMethodMockFunctionTest, EnsureNoUnusedButMarkedUnusedWarning) { 1686 #ifdef __clang__ 1687 #pragma clang diagnostic push 1688 #pragma clang diagnostic error "-Wused-but-marked-unused" 1689 #endif 1690 // https://github.com/google/googletest/issues/4055 1691 EXPECT_THAT(0, EnsureNoUnusedButMarkedUnusedWarning()); 1692 #ifdef __clang__ 1693 #pragma clang diagnostic pop 1694 #endif 1695 } 1696 1697 #if GTEST_HAS_EXCEPTIONS 1698 1699 // std::function<void()> is used below for compatibility with older copies of 1700 // GCC. Normally, a raw lambda is all that is needed. 1701 1702 // Test that examples from documentation compile 1703 TEST(ThrowsTest, Examples) { 1704 EXPECT_THAT( 1705 std::function<void()>([]() { throw std::runtime_error("message"); }), 1706 Throws<std::runtime_error>()); 1707 1708 EXPECT_THAT( 1709 std::function<void()>([]() { throw std::runtime_error("message"); }), 1710 ThrowsMessage<std::runtime_error>(HasSubstr("message"))); 1711 } 1712 1713 TEST(ThrowsTest, PrintsExceptionWhat) { 1714 EXPECT_THAT( 1715 std::function<void()>([]() { throw std::runtime_error("ABC123XYZ"); }), 1716 ThrowsMessage<std::runtime_error>(HasSubstr("ABC123XYZ"))); 1717 } 1718 1719 TEST(ThrowsTest, DoesNotGenerateDuplicateCatchClauseWarning) { 1720 EXPECT_THAT(std::function<void()>([]() { throw std::exception(); }), 1721 Throws<std::exception>()); 1722 } 1723 1724 TEST(ThrowsTest, CallableExecutedExactlyOnce) { 1725 size_t a = 0; 1726 1727 EXPECT_THAT(std::function<void()>([&a]() { 1728 a++; 1729 throw 10; 1730 }), 1731 Throws<int>()); 1732 EXPECT_EQ(a, 1u); 1733 1734 EXPECT_THAT(std::function<void()>([&a]() { 1735 a++; 1736 throw std::runtime_error("message"); 1737 }), 1738 Throws<std::runtime_error>()); 1739 EXPECT_EQ(a, 2u); 1740 1741 EXPECT_THAT(std::function<void()>([&a]() { 1742 a++; 1743 throw std::runtime_error("message"); 1744 }), 1745 ThrowsMessage<std::runtime_error>(HasSubstr("message"))); 1746 EXPECT_EQ(a, 3u); 1747 1748 EXPECT_THAT(std::function<void()>([&a]() { 1749 a++; 1750 throw std::runtime_error("message"); 1751 }), 1752 Throws<std::runtime_error>( 1753 Property(&std::runtime_error::what, HasSubstr("message")))); 1754 EXPECT_EQ(a, 4u); 1755 } 1756 1757 TEST(ThrowsTest, Describe) { 1758 Matcher<std::function<void()>> matcher = Throws<std::runtime_error>(); 1759 std::stringstream ss; 1760 matcher.DescribeTo(&ss); 1761 auto explanation = ss.str(); 1762 EXPECT_THAT(explanation, HasSubstr("std::runtime_error")); 1763 } 1764 1765 TEST(ThrowsTest, Success) { 1766 Matcher<std::function<void()>> matcher = Throws<std::runtime_error>(); 1767 StringMatchResultListener listener; 1768 EXPECT_TRUE(matcher.MatchAndExplain( 1769 []() { throw std::runtime_error("error message"); }, &listener)); 1770 EXPECT_THAT(listener.str(), HasSubstr("std::runtime_error")); 1771 } 1772 1773 TEST(ThrowsTest, FailWrongType) { 1774 Matcher<std::function<void()>> matcher = Throws<std::runtime_error>(); 1775 StringMatchResultListener listener; 1776 EXPECT_FALSE(matcher.MatchAndExplain( 1777 []() { throw std::logic_error("error message"); }, &listener)); 1778 EXPECT_THAT(listener.str(), HasSubstr("std::logic_error")); 1779 EXPECT_THAT(listener.str(), HasSubstr("\"error message\"")); 1780 } 1781 1782 TEST(ThrowsTest, FailWrongTypeNonStd) { 1783 Matcher<std::function<void()>> matcher = Throws<std::runtime_error>(); 1784 StringMatchResultListener listener; 1785 EXPECT_FALSE(matcher.MatchAndExplain([]() { throw 10; }, &listener)); 1786 EXPECT_THAT(listener.str(), 1787 HasSubstr("throws an exception of an unknown type")); 1788 } 1789 1790 TEST(ThrowsTest, FailNoThrow) { 1791 Matcher<std::function<void()>> matcher = Throws<std::runtime_error>(); 1792 StringMatchResultListener listener; 1793 EXPECT_FALSE(matcher.MatchAndExplain([]() { (void)0; }, &listener)); 1794 EXPECT_THAT(listener.str(), HasSubstr("does not throw any exception")); 1795 } 1796 1797 class ThrowsPredicateTest 1798 : public TestWithParam<Matcher<std::function<void()>>> {}; 1799 1800 TEST_P(ThrowsPredicateTest, Describe) { 1801 Matcher<std::function<void()>> matcher = GetParam(); 1802 std::stringstream ss; 1803 matcher.DescribeTo(&ss); 1804 auto explanation = ss.str(); 1805 EXPECT_THAT(explanation, HasSubstr("std::runtime_error")); 1806 EXPECT_THAT(explanation, HasSubstr("error message")); 1807 } 1808 1809 TEST_P(ThrowsPredicateTest, Success) { 1810 Matcher<std::function<void()>> matcher = GetParam(); 1811 StringMatchResultListener listener; 1812 EXPECT_TRUE(matcher.MatchAndExplain( 1813 []() { throw std::runtime_error("error message"); }, &listener)); 1814 EXPECT_THAT(listener.str(), HasSubstr("std::runtime_error")); 1815 } 1816 1817 TEST_P(ThrowsPredicateTest, FailWrongType) { 1818 Matcher<std::function<void()>> matcher = GetParam(); 1819 StringMatchResultListener listener; 1820 EXPECT_FALSE(matcher.MatchAndExplain( 1821 []() { throw std::logic_error("error message"); }, &listener)); 1822 EXPECT_THAT(listener.str(), HasSubstr("std::logic_error")); 1823 EXPECT_THAT(listener.str(), HasSubstr("\"error message\"")); 1824 } 1825 1826 TEST_P(ThrowsPredicateTest, FailWrongTypeNonStd) { 1827 Matcher<std::function<void()>> matcher = GetParam(); 1828 StringMatchResultListener listener; 1829 EXPECT_FALSE(matcher.MatchAndExplain([]() { throw 10; }, &listener)); 1830 EXPECT_THAT(listener.str(), 1831 HasSubstr("throws an exception of an unknown type")); 1832 } 1833 1834 TEST_P(ThrowsPredicateTest, FailNoThrow) { 1835 Matcher<std::function<void()>> matcher = GetParam(); 1836 StringMatchResultListener listener; 1837 EXPECT_FALSE(matcher.MatchAndExplain([]() {}, &listener)); 1838 EXPECT_THAT(listener.str(), HasSubstr("does not throw any exception")); 1839 } 1840 1841 INSTANTIATE_TEST_SUITE_P( 1842 AllMessagePredicates, ThrowsPredicateTest, 1843 Values(Matcher<std::function<void()>>( 1844 ThrowsMessage<std::runtime_error>(HasSubstr("error message"))))); 1845 1846 // Tests that Throws<E1>(Matcher<E2>{}) compiles even when E2 != const E1&. 1847 TEST(ThrowsPredicateCompilesTest, ExceptionMatcherAcceptsBroadType) { 1848 { 1849 Matcher<std::function<void()>> matcher = 1850 ThrowsMessage<std::runtime_error>(HasSubstr("error message")); 1851 EXPECT_TRUE( 1852 matcher.Matches([]() { throw std::runtime_error("error message"); })); 1853 EXPECT_FALSE( 1854 matcher.Matches([]() { throw std::runtime_error("wrong message"); })); 1855 } 1856 1857 { 1858 Matcher<uint64_t> inner = Eq(10); 1859 Matcher<std::function<void()>> matcher = Throws<uint32_t>(inner); 1860 EXPECT_TRUE(matcher.Matches([]() { throw (uint32_t)10; })); 1861 EXPECT_FALSE(matcher.Matches([]() { throw (uint32_t)11; })); 1862 } 1863 } 1864 1865 // Tests that ThrowsMessage("message") is equivalent 1866 // to ThrowsMessage(Eq<std::string>("message")). 1867 TEST(ThrowsPredicateCompilesTest, MessageMatcherAcceptsNonMatcher) { 1868 Matcher<std::function<void()>> matcher = 1869 ThrowsMessage<std::runtime_error>("error message"); 1870 EXPECT_TRUE( 1871 matcher.Matches([]() { throw std::runtime_error("error message"); })); 1872 EXPECT_FALSE(matcher.Matches( 1873 []() { throw std::runtime_error("wrong error message"); })); 1874 } 1875 1876 #endif // GTEST_HAS_EXCEPTIONS 1877 1878 } // namespace 1879 } // namespace gmock_matchers_test 1880 } // namespace testing 1881 1882 GTEST_DISABLE_MSC_WARNINGS_POP_() // 4244 4100 1883