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