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