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