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