Update bundled GoogleTest to current HEAD
[alexxy/gromacs.git] / src / external / googletest / googlemock / test / gmock-matchers_test.cc
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
31 // Google Mock - a framework for writing C++ mock classes.
32 //
33 // This file tests some commonly used argument matchers.
34
35 // Silence warning C4244: 'initializing': conversion from 'int' to 'short',
36 // possible loss of data and C4100, unreferenced local parameter
37 #ifdef _MSC_VER
38 # pragma warning(push)
39 # pragma warning(disable:4244)
40 # pragma warning(disable:4100)
41 #endif
42
43 #include "gmock/gmock-matchers.h"
44
45 #include <string.h>
46 #include <time.h>
47
48 #include <array>
49 #include <cstdint>
50 #include <deque>
51 #include <forward_list>
52 #include <functional>
53 #include <iostream>
54 #include <iterator>
55 #include <limits>
56 #include <list>
57 #include <map>
58 #include <memory>
59 #include <set>
60 #include <sstream>
61 #include <string>
62 #include <type_traits>
63 #include <unordered_map>
64 #include <unordered_set>
65 #include <utility>
66 #include <vector>
67
68 #include "gmock/gmock-more-matchers.h"
69 #include "gmock/gmock.h"
70 #include "gtest/gtest-spi.h"
71 #include "gtest/gtest.h"
72
73 namespace testing {
74 namespace gmock_matchers_test {
75 namespace {
76
77 using std::greater;
78 using std::less;
79 using std::list;
80 using std::make_pair;
81 using std::map;
82 using std::multimap;
83 using std::multiset;
84 using std::ostream;
85 using std::pair;
86 using std::set;
87 using std::stringstream;
88 using std::vector;
89 using testing::internal::DummyMatchResultListener;
90 using testing::internal::ElementMatcherPair;
91 using testing::internal::ElementMatcherPairs;
92 using testing::internal::ElementsAreArrayMatcher;
93 using testing::internal::ExplainMatchFailureTupleTo;
94 using testing::internal::FloatingEqMatcher;
95 using testing::internal::FormatMatcherDescription;
96 using testing::internal::IsReadableTypeName;
97 using testing::internal::MatchMatrix;
98 using testing::internal::PredicateFormatterFromMatcher;
99 using testing::internal::RE;
100 using testing::internal::StreamMatchResultListener;
101 using testing::internal::Strings;
102
103 // Helper for testing container-valued matchers in mock method context. It is
104 // important to test matchers in this context, since it requires additional type
105 // deduction beyond what EXPECT_THAT does, thus making it more restrictive.
106 struct ContainerHelper {
107   MOCK_METHOD1(Call, void(std::vector<std::unique_ptr<int>>));
108 };
109
110 std::vector<std::unique_ptr<int>> MakeUniquePtrs(const std::vector<int>& ints) {
111   std::vector<std::unique_ptr<int>> pointers;
112   for (int i : ints) pointers.emplace_back(new int(i));
113   return pointers;
114 }
115
116 // For testing ExplainMatchResultTo().
117 template <typename T = int>
118 class GreaterThanMatcher : public MatcherInterface<T> {
119  public:
120   explicit GreaterThanMatcher(T rhs) : rhs_(rhs) {}
121
122   void DescribeTo(ostream* os) const override { *os << "is > " << rhs_; }
123
124   bool MatchAndExplain(T lhs, MatchResultListener* listener) const override {
125     if (lhs > rhs_) {
126       *listener << "which is " << (lhs - rhs_) << " more than " << rhs_;
127     } else if (lhs == rhs_) {
128       *listener << "which is the same as " << rhs_;
129     } else {
130       *listener << "which is " << (rhs_ - lhs) << " less than " << rhs_;
131     }
132
133     return lhs > rhs_;
134   }
135
136  private:
137   const T rhs_;
138 };
139
140 template <typename T>
141 Matcher<T> GreaterThan(T n) {
142   return MakeMatcher(new GreaterThanMatcher<T>(n));
143 }
144
145 std::string OfType(const std::string& type_name) {
146 #if GTEST_HAS_RTTI
147   return IsReadableTypeName(type_name) ? " (of type " + type_name + ")" : "";
148 #else
149   return "";
150 #endif
151 }
152
153 // Returns the description of the given matcher.
154 template <typename T>
155 std::string Describe(const Matcher<T>& m) {
156   return DescribeMatcher<T>(m);
157 }
158
159 // Returns the description of the negation of the given matcher.
160 template <typename T>
161 std::string DescribeNegation(const Matcher<T>& m) {
162   return DescribeMatcher<T>(m, true);
163 }
164
165 // Returns the reason why x matches, or doesn't match, m.
166 template <typename MatcherType, typename Value>
167 std::string Explain(const MatcherType& m, const Value& x) {
168   StringMatchResultListener listener;
169   ExplainMatchResult(m, x, &listener);
170   return listener.str();
171 }
172
173 TEST(MonotonicMatcherTest, IsPrintable) {
174   stringstream ss;
175   ss << GreaterThan(5);
176   EXPECT_EQ("is > 5", ss.str());
177 }
178
179 TEST(MatchResultListenerTest, StreamingWorks) {
180   StringMatchResultListener listener;
181   listener << "hi" << 5;
182   EXPECT_EQ("hi5", listener.str());
183
184   listener.Clear();
185   EXPECT_EQ("", listener.str());
186
187   listener << 42;
188   EXPECT_EQ("42", listener.str());
189
190   // Streaming shouldn't crash when the underlying ostream is NULL.
191   DummyMatchResultListener dummy;
192   dummy << "hi" << 5;
193 }
194
195 TEST(MatchResultListenerTest, CanAccessUnderlyingStream) {
196   EXPECT_TRUE(DummyMatchResultListener().stream() == nullptr);
197   EXPECT_TRUE(StreamMatchResultListener(nullptr).stream() == nullptr);
198
199   EXPECT_EQ(&std::cout, StreamMatchResultListener(&std::cout).stream());
200 }
201
202 TEST(MatchResultListenerTest, IsInterestedWorks) {
203   EXPECT_TRUE(StringMatchResultListener().IsInterested());
204   EXPECT_TRUE(StreamMatchResultListener(&std::cout).IsInterested());
205
206   EXPECT_FALSE(DummyMatchResultListener().IsInterested());
207   EXPECT_FALSE(StreamMatchResultListener(nullptr).IsInterested());
208 }
209
210 // Makes sure that the MatcherInterface<T> interface doesn't
211 // change.
212 class EvenMatcherImpl : public MatcherInterface<int> {
213  public:
214   bool MatchAndExplain(int x,
215                        MatchResultListener* /* listener */) const override {
216     return x % 2 == 0;
217   }
218
219   void DescribeTo(ostream* os) const override { *os << "is an even number"; }
220
221   // We deliberately don't define DescribeNegationTo() and
222   // ExplainMatchResultTo() here, to make sure the definition of these
223   // two methods is optional.
224 };
225
226 // Makes sure that the MatcherInterface API doesn't change.
227 TEST(MatcherInterfaceTest, CanBeImplementedUsingPublishedAPI) {
228   EvenMatcherImpl m;
229 }
230
231 // Tests implementing a monomorphic matcher using MatchAndExplain().
232
233 class NewEvenMatcherImpl : public MatcherInterface<int> {
234  public:
235   bool MatchAndExplain(int x, MatchResultListener* listener) const override {
236     const bool match = x % 2 == 0;
237     // Verifies that we can stream to a listener directly.
238     *listener << "value % " << 2;
239     if (listener->stream() != nullptr) {
240       // Verifies that we can stream to a listener's underlying stream
241       // too.
242       *listener->stream() << " == " << (x % 2);
243     }
244     return match;
245   }
246
247   void DescribeTo(ostream* os) const override { *os << "is an even number"; }
248 };
249
250 TEST(MatcherInterfaceTest, CanBeImplementedUsingNewAPI) {
251   Matcher<int> m = MakeMatcher(new NewEvenMatcherImpl);
252   EXPECT_TRUE(m.Matches(2));
253   EXPECT_FALSE(m.Matches(3));
254   EXPECT_EQ("value % 2 == 0", Explain(m, 2));
255   EXPECT_EQ("value % 2 == 1", Explain(m, 3));
256 }
257
258 // Tests default-constructing a matcher.
259 TEST(MatcherTest, CanBeDefaultConstructed) {
260   Matcher<double> m;
261 }
262
263 // Tests that Matcher<T> can be constructed from a MatcherInterface<T>*.
264 TEST(MatcherTest, CanBeConstructedFromMatcherInterface) {
265   const MatcherInterface<int>* impl = new EvenMatcherImpl;
266   Matcher<int> m(impl);
267   EXPECT_TRUE(m.Matches(4));
268   EXPECT_FALSE(m.Matches(5));
269 }
270
271 // Tests that value can be used in place of Eq(value).
272 TEST(MatcherTest, CanBeImplicitlyConstructedFromValue) {
273   Matcher<int> m1 = 5;
274   EXPECT_TRUE(m1.Matches(5));
275   EXPECT_FALSE(m1.Matches(6));
276 }
277
278 // Tests that NULL can be used in place of Eq(NULL).
279 TEST(MatcherTest, CanBeImplicitlyConstructedFromNULL) {
280   Matcher<int*> m1 = nullptr;
281   EXPECT_TRUE(m1.Matches(nullptr));
282   int n = 0;
283   EXPECT_FALSE(m1.Matches(&n));
284 }
285
286 // Tests that matchers can be constructed from a variable that is not properly
287 // defined. This should be illegal, but many users rely on this accidentally.
288 struct Undefined {
289   virtual ~Undefined() = 0;
290   static const int kInt = 1;
291 };
292
293 TEST(MatcherTest, CanBeConstructedFromUndefinedVariable) {
294   Matcher<int> m1 = Undefined::kInt;
295   EXPECT_TRUE(m1.Matches(1));
296   EXPECT_FALSE(m1.Matches(2));
297 }
298
299 // Test that a matcher parameterized with an abstract class compiles.
300 TEST(MatcherTest, CanAcceptAbstractClass) { Matcher<const Undefined&> m = _; }
301
302 // Tests that matchers are copyable.
303 TEST(MatcherTest, IsCopyable) {
304   // Tests the copy constructor.
305   Matcher<bool> m1 = Eq(false);
306   EXPECT_TRUE(m1.Matches(false));
307   EXPECT_FALSE(m1.Matches(true));
308
309   // Tests the assignment operator.
310   m1 = Eq(true);
311   EXPECT_TRUE(m1.Matches(true));
312   EXPECT_FALSE(m1.Matches(false));
313 }
314
315 // Tests that Matcher<T>::DescribeTo() calls
316 // MatcherInterface<T>::DescribeTo().
317 TEST(MatcherTest, CanDescribeItself) {
318   EXPECT_EQ("is an even number",
319             Describe(Matcher<int>(new EvenMatcherImpl)));
320 }
321
322 // Tests Matcher<T>::MatchAndExplain().
323 TEST(MatcherTest, MatchAndExplain) {
324   Matcher<int> m = GreaterThan(0);
325   StringMatchResultListener listener1;
326   EXPECT_TRUE(m.MatchAndExplain(42, &listener1));
327   EXPECT_EQ("which is 42 more than 0", listener1.str());
328
329   StringMatchResultListener listener2;
330   EXPECT_FALSE(m.MatchAndExplain(-9, &listener2));
331   EXPECT_EQ("which is 9 less than 0", listener2.str());
332 }
333
334 // Tests that a C-string literal can be implicitly converted to a
335 // Matcher<std::string> or Matcher<const std::string&>.
336 TEST(StringMatcherTest, CanBeImplicitlyConstructedFromCStringLiteral) {
337   Matcher<std::string> m1 = "hi";
338   EXPECT_TRUE(m1.Matches("hi"));
339   EXPECT_FALSE(m1.Matches("hello"));
340
341   Matcher<const std::string&> m2 = "hi";
342   EXPECT_TRUE(m2.Matches("hi"));
343   EXPECT_FALSE(m2.Matches("hello"));
344 }
345
346 // Tests that a string object can be implicitly converted to a
347 // Matcher<std::string> or Matcher<const std::string&>.
348 TEST(StringMatcherTest, CanBeImplicitlyConstructedFromString) {
349   Matcher<std::string> m1 = std::string("hi");
350   EXPECT_TRUE(m1.Matches("hi"));
351   EXPECT_FALSE(m1.Matches("hello"));
352
353   Matcher<const std::string&> m2 = std::string("hi");
354   EXPECT_TRUE(m2.Matches("hi"));
355   EXPECT_FALSE(m2.Matches("hello"));
356 }
357
358 #if GTEST_INTERNAL_HAS_STRING_VIEW
359 // Tests that a C-string literal can be implicitly converted to a
360 // Matcher<StringView> or Matcher<const StringView&>.
361 TEST(StringViewMatcherTest, CanBeImplicitlyConstructedFromCStringLiteral) {
362   Matcher<internal::StringView> m1 = "cats";
363   EXPECT_TRUE(m1.Matches("cats"));
364   EXPECT_FALSE(m1.Matches("dogs"));
365
366   Matcher<const internal::StringView&> m2 = "cats";
367   EXPECT_TRUE(m2.Matches("cats"));
368   EXPECT_FALSE(m2.Matches("dogs"));
369 }
370
371 // Tests that a std::string object can be implicitly converted to a
372 // Matcher<StringView> or Matcher<const StringView&>.
373 TEST(StringViewMatcherTest, CanBeImplicitlyConstructedFromString) {
374   Matcher<internal::StringView> m1 = std::string("cats");
375   EXPECT_TRUE(m1.Matches("cats"));
376   EXPECT_FALSE(m1.Matches("dogs"));
377
378   Matcher<const internal::StringView&> m2 = std::string("cats");
379   EXPECT_TRUE(m2.Matches("cats"));
380   EXPECT_FALSE(m2.Matches("dogs"));
381 }
382
383 // Tests that a StringView object can be implicitly converted to a
384 // Matcher<StringView> or Matcher<const StringView&>.
385 TEST(StringViewMatcherTest, CanBeImplicitlyConstructedFromStringView) {
386   Matcher<internal::StringView> m1 = internal::StringView("cats");
387   EXPECT_TRUE(m1.Matches("cats"));
388   EXPECT_FALSE(m1.Matches("dogs"));
389
390   Matcher<const internal::StringView&> m2 = internal::StringView("cats");
391   EXPECT_TRUE(m2.Matches("cats"));
392   EXPECT_FALSE(m2.Matches("dogs"));
393 }
394 #endif  // GTEST_INTERNAL_HAS_STRING_VIEW
395
396 // Tests that a std::reference_wrapper<std::string> object can be implicitly
397 // converted to a Matcher<std::string> or Matcher<const std::string&> via Eq().
398 TEST(StringMatcherTest,
399      CanBeImplicitlyConstructedFromEqReferenceWrapperString) {
400   std::string value = "cats";
401   Matcher<std::string> m1 = Eq(std::ref(value));
402   EXPECT_TRUE(m1.Matches("cats"));
403   EXPECT_FALSE(m1.Matches("dogs"));
404
405   Matcher<const std::string&> m2 = Eq(std::ref(value));
406   EXPECT_TRUE(m2.Matches("cats"));
407   EXPECT_FALSE(m2.Matches("dogs"));
408 }
409
410 // Tests that MakeMatcher() constructs a Matcher<T> from a
411 // MatcherInterface* without requiring the user to explicitly
412 // write the type.
413 TEST(MakeMatcherTest, ConstructsMatcherFromMatcherInterface) {
414   const MatcherInterface<int>* dummy_impl = new EvenMatcherImpl;
415   Matcher<int> m = MakeMatcher(dummy_impl);
416 }
417
418 // Tests that MakePolymorphicMatcher() can construct a polymorphic
419 // matcher from its implementation using the old API.
420 const int g_bar = 1;
421 class ReferencesBarOrIsZeroImpl {
422  public:
423   template <typename T>
424   bool MatchAndExplain(const T& x,
425                        MatchResultListener* /* listener */) const {
426     const void* p = &x;
427     return p == &g_bar || x == 0;
428   }
429
430   void DescribeTo(ostream* os) const { *os << "g_bar or zero"; }
431
432   void DescribeNegationTo(ostream* os) const {
433     *os << "doesn't reference g_bar and is not zero";
434   }
435 };
436
437 // This function verifies that MakePolymorphicMatcher() returns a
438 // PolymorphicMatcher<T> where T is the argument's type.
439 PolymorphicMatcher<ReferencesBarOrIsZeroImpl> ReferencesBarOrIsZero() {
440   return MakePolymorphicMatcher(ReferencesBarOrIsZeroImpl());
441 }
442
443 TEST(MakePolymorphicMatcherTest, ConstructsMatcherUsingOldAPI) {
444   // Using a polymorphic matcher to match a reference type.
445   Matcher<const int&> m1 = ReferencesBarOrIsZero();
446   EXPECT_TRUE(m1.Matches(0));
447   // Verifies that the identity of a by-reference argument is preserved.
448   EXPECT_TRUE(m1.Matches(g_bar));
449   EXPECT_FALSE(m1.Matches(1));
450   EXPECT_EQ("g_bar or zero", Describe(m1));
451
452   // Using a polymorphic matcher to match a value type.
453   Matcher<double> m2 = ReferencesBarOrIsZero();
454   EXPECT_TRUE(m2.Matches(0.0));
455   EXPECT_FALSE(m2.Matches(0.1));
456   EXPECT_EQ("g_bar or zero", Describe(m2));
457 }
458
459 // Tests implementing a polymorphic matcher using MatchAndExplain().
460
461 class PolymorphicIsEvenImpl {
462  public:
463   void DescribeTo(ostream* os) const { *os << "is even"; }
464
465   void DescribeNegationTo(ostream* os) const {
466     *os << "is odd";
467   }
468
469   template <typename T>
470   bool MatchAndExplain(const T& x, MatchResultListener* listener) const {
471     // Verifies that we can stream to the listener directly.
472     *listener << "% " << 2;
473     if (listener->stream() != nullptr) {
474       // Verifies that we can stream to the listener's underlying stream
475       // too.
476       *listener->stream() << " == " << (x % 2);
477     }
478     return (x % 2) == 0;
479   }
480 };
481
482 PolymorphicMatcher<PolymorphicIsEvenImpl> PolymorphicIsEven() {
483   return MakePolymorphicMatcher(PolymorphicIsEvenImpl());
484 }
485
486 TEST(MakePolymorphicMatcherTest, ConstructsMatcherUsingNewAPI) {
487   // Using PolymorphicIsEven() as a Matcher<int>.
488   const Matcher<int> m1 = PolymorphicIsEven();
489   EXPECT_TRUE(m1.Matches(42));
490   EXPECT_FALSE(m1.Matches(43));
491   EXPECT_EQ("is even", Describe(m1));
492
493   const Matcher<int> not_m1 = Not(m1);
494   EXPECT_EQ("is odd", Describe(not_m1));
495
496   EXPECT_EQ("% 2 == 0", Explain(m1, 42));
497
498   // Using PolymorphicIsEven() as a Matcher<char>.
499   const Matcher<char> m2 = PolymorphicIsEven();
500   EXPECT_TRUE(m2.Matches('\x42'));
501   EXPECT_FALSE(m2.Matches('\x43'));
502   EXPECT_EQ("is even", Describe(m2));
503
504   const Matcher<char> not_m2 = Not(m2);
505   EXPECT_EQ("is odd", Describe(not_m2));
506
507   EXPECT_EQ("% 2 == 0", Explain(m2, '\x42'));
508 }
509
510 // Tests that MatcherCast<T>(m) works when m is a polymorphic matcher.
511 TEST(MatcherCastTest, FromPolymorphicMatcher) {
512   Matcher<int> m = MatcherCast<int>(Eq(5));
513   EXPECT_TRUE(m.Matches(5));
514   EXPECT_FALSE(m.Matches(6));
515 }
516
517 // For testing casting matchers between compatible types.
518 class IntValue {
519  public:
520   // An int can be statically (although not implicitly) cast to a
521   // IntValue.
522   explicit IntValue(int a_value) : value_(a_value) {}
523
524   int value() const { return value_; }
525  private:
526   int value_;
527 };
528
529 // For testing casting matchers between compatible types.
530 bool IsPositiveIntValue(const IntValue& foo) {
531   return foo.value() > 0;
532 }
533
534 // Tests that MatcherCast<T>(m) works when m is a Matcher<U> where T
535 // can be statically converted to U.
536 TEST(MatcherCastTest, FromCompatibleType) {
537   Matcher<double> m1 = Eq(2.0);
538   Matcher<int> m2 = MatcherCast<int>(m1);
539   EXPECT_TRUE(m2.Matches(2));
540   EXPECT_FALSE(m2.Matches(3));
541
542   Matcher<IntValue> m3 = Truly(IsPositiveIntValue);
543   Matcher<int> m4 = MatcherCast<int>(m3);
544   // In the following, the arguments 1 and 0 are statically converted
545   // to IntValue objects, and then tested by the IsPositiveIntValue()
546   // predicate.
547   EXPECT_TRUE(m4.Matches(1));
548   EXPECT_FALSE(m4.Matches(0));
549 }
550
551 // Tests that MatcherCast<T>(m) works when m is a Matcher<const T&>.
552 TEST(MatcherCastTest, FromConstReferenceToNonReference) {
553   Matcher<const int&> m1 = Eq(0);
554   Matcher<int> m2 = MatcherCast<int>(m1);
555   EXPECT_TRUE(m2.Matches(0));
556   EXPECT_FALSE(m2.Matches(1));
557 }
558
559 // Tests that MatcherCast<T>(m) works when m is a Matcher<T&>.
560 TEST(MatcherCastTest, FromReferenceToNonReference) {
561   Matcher<int&> m1 = Eq(0);
562   Matcher<int> m2 = MatcherCast<int>(m1);
563   EXPECT_TRUE(m2.Matches(0));
564   EXPECT_FALSE(m2.Matches(1));
565 }
566
567 // Tests that MatcherCast<const T&>(m) works when m is a Matcher<T>.
568 TEST(MatcherCastTest, FromNonReferenceToConstReference) {
569   Matcher<int> m1 = Eq(0);
570   Matcher<const int&> m2 = MatcherCast<const int&>(m1);
571   EXPECT_TRUE(m2.Matches(0));
572   EXPECT_FALSE(m2.Matches(1));
573 }
574
575 // Tests that MatcherCast<T&>(m) works when m is a Matcher<T>.
576 TEST(MatcherCastTest, FromNonReferenceToReference) {
577   Matcher<int> m1 = Eq(0);
578   Matcher<int&> m2 = MatcherCast<int&>(m1);
579   int n = 0;
580   EXPECT_TRUE(m2.Matches(n));
581   n = 1;
582   EXPECT_FALSE(m2.Matches(n));
583 }
584
585 // Tests that MatcherCast<T>(m) works when m is a Matcher<T>.
586 TEST(MatcherCastTest, FromSameType) {
587   Matcher<int> m1 = Eq(0);
588   Matcher<int> m2 = MatcherCast<int>(m1);
589   EXPECT_TRUE(m2.Matches(0));
590   EXPECT_FALSE(m2.Matches(1));
591 }
592
593 // Tests that MatcherCast<T>(m) works when m is a value of the same type as the
594 // value type of the Matcher.
595 TEST(MatcherCastTest, FromAValue) {
596   Matcher<int> m = MatcherCast<int>(42);
597   EXPECT_TRUE(m.Matches(42));
598   EXPECT_FALSE(m.Matches(239));
599 }
600
601 // Tests that MatcherCast<T>(m) works when m is a value of the type implicitly
602 // convertible to the value type of the Matcher.
603 TEST(MatcherCastTest, FromAnImplicitlyConvertibleValue) {
604   const int kExpected = 'c';
605   Matcher<int> m = MatcherCast<int>('c');
606   EXPECT_TRUE(m.Matches(kExpected));
607   EXPECT_FALSE(m.Matches(kExpected + 1));
608 }
609
610 struct NonImplicitlyConstructibleTypeWithOperatorEq {
611   friend bool operator==(
612       const NonImplicitlyConstructibleTypeWithOperatorEq& /* ignored */,
613       int rhs) {
614     return 42 == rhs;
615   }
616   friend bool operator==(
617       int lhs,
618       const NonImplicitlyConstructibleTypeWithOperatorEq& /* ignored */) {
619     return lhs == 42;
620   }
621 };
622
623 // Tests that MatcherCast<T>(m) works when m is a neither a matcher nor
624 // implicitly convertible to the value type of the Matcher, but the value type
625 // of the matcher has operator==() overload accepting m.
626 TEST(MatcherCastTest, NonImplicitlyConstructibleTypeWithOperatorEq) {
627   Matcher<NonImplicitlyConstructibleTypeWithOperatorEq> m1 =
628       MatcherCast<NonImplicitlyConstructibleTypeWithOperatorEq>(42);
629   EXPECT_TRUE(m1.Matches(NonImplicitlyConstructibleTypeWithOperatorEq()));
630
631   Matcher<NonImplicitlyConstructibleTypeWithOperatorEq> m2 =
632       MatcherCast<NonImplicitlyConstructibleTypeWithOperatorEq>(239);
633   EXPECT_FALSE(m2.Matches(NonImplicitlyConstructibleTypeWithOperatorEq()));
634
635   // When updating the following lines please also change the comment to
636   // namespace convertible_from_any.
637   Matcher<int> m3 =
638       MatcherCast<int>(NonImplicitlyConstructibleTypeWithOperatorEq());
639   EXPECT_TRUE(m3.Matches(42));
640   EXPECT_FALSE(m3.Matches(239));
641 }
642
643 // ConvertibleFromAny does not work with MSVC. resulting in
644 // error C2440: 'initializing': cannot convert from 'Eq' to 'M'
645 // No constructor could take the source type, or constructor overload
646 // resolution was ambiguous
647
648 #if !defined _MSC_VER
649
650 // The below ConvertibleFromAny struct is implicitly constructible from anything
651 // and when in the same namespace can interact with other tests. In particular,
652 // if it is in the same namespace as other tests and one removes
653 //   NonImplicitlyConstructibleTypeWithOperatorEq::operator==(int lhs, ...);
654 // then the corresponding test still compiles (and it should not!) by implicitly
655 // converting NonImplicitlyConstructibleTypeWithOperatorEq to ConvertibleFromAny
656 // in m3.Matcher().
657 namespace convertible_from_any {
658 // Implicitly convertible from any type.
659 struct ConvertibleFromAny {
660   ConvertibleFromAny(int a_value) : value(a_value) {}
661   template <typename T>
662   ConvertibleFromAny(const T& /*a_value*/) : value(-1) {
663     ADD_FAILURE() << "Conversion constructor called";
664   }
665   int value;
666 };
667
668 bool operator==(const ConvertibleFromAny& a, const ConvertibleFromAny& b) {
669   return a.value == b.value;
670 }
671
672 ostream& operator<<(ostream& os, const ConvertibleFromAny& a) {
673   return os << a.value;
674 }
675
676 TEST(MatcherCastTest, ConversionConstructorIsUsed) {
677   Matcher<ConvertibleFromAny> m = MatcherCast<ConvertibleFromAny>(1);
678   EXPECT_TRUE(m.Matches(ConvertibleFromAny(1)));
679   EXPECT_FALSE(m.Matches(ConvertibleFromAny(2)));
680 }
681
682 TEST(MatcherCastTest, FromConvertibleFromAny) {
683   Matcher<ConvertibleFromAny> m =
684       MatcherCast<ConvertibleFromAny>(Eq(ConvertibleFromAny(1)));
685   EXPECT_TRUE(m.Matches(ConvertibleFromAny(1)));
686   EXPECT_FALSE(m.Matches(ConvertibleFromAny(2)));
687 }
688 }  // namespace convertible_from_any
689
690 #endif  // !defined _MSC_VER
691
692 struct IntReferenceWrapper {
693   IntReferenceWrapper(const int& a_value) : value(&a_value) {}
694   const int* value;
695 };
696
697 bool operator==(const IntReferenceWrapper& a, const IntReferenceWrapper& b) {
698   return a.value == b.value;
699 }
700
701 TEST(MatcherCastTest, ValueIsNotCopied) {
702   int n = 42;
703   Matcher<IntReferenceWrapper> m = MatcherCast<IntReferenceWrapper>(n);
704   // Verify that the matcher holds a reference to n, not to its temporary copy.
705   EXPECT_TRUE(m.Matches(n));
706 }
707
708 class Base {
709  public:
710   virtual ~Base() {}
711   Base() {}
712  private:
713   GTEST_DISALLOW_COPY_AND_ASSIGN_(Base);
714 };
715
716 class Derived : public Base {
717  public:
718   Derived() : Base() {}
719   int i;
720 };
721
722 class OtherDerived : public Base {};
723
724 // Tests that SafeMatcherCast<T>(m) works when m is a polymorphic matcher.
725 TEST(SafeMatcherCastTest, FromPolymorphicMatcher) {
726   Matcher<char> m2 = SafeMatcherCast<char>(Eq(32));
727   EXPECT_TRUE(m2.Matches(' '));
728   EXPECT_FALSE(m2.Matches('\n'));
729 }
730
731 // Tests that SafeMatcherCast<T>(m) works when m is a Matcher<U> where
732 // T and U are arithmetic types and T can be losslessly converted to
733 // U.
734 TEST(SafeMatcherCastTest, FromLosslesslyConvertibleArithmeticType) {
735   Matcher<double> m1 = DoubleEq(1.0);
736   Matcher<float> m2 = SafeMatcherCast<float>(m1);
737   EXPECT_TRUE(m2.Matches(1.0f));
738   EXPECT_FALSE(m2.Matches(2.0f));
739
740   Matcher<char> m3 = SafeMatcherCast<char>(TypedEq<int>('a'));
741   EXPECT_TRUE(m3.Matches('a'));
742   EXPECT_FALSE(m3.Matches('b'));
743 }
744
745 // Tests that SafeMatcherCast<T>(m) works when m is a Matcher<U> where T and U
746 // are pointers or references to a derived and a base class, correspondingly.
747 TEST(SafeMatcherCastTest, FromBaseClass) {
748   Derived d, d2;
749   Matcher<Base*> m1 = Eq(&d);
750   Matcher<Derived*> m2 = SafeMatcherCast<Derived*>(m1);
751   EXPECT_TRUE(m2.Matches(&d));
752   EXPECT_FALSE(m2.Matches(&d2));
753
754   Matcher<Base&> m3 = Ref(d);
755   Matcher<Derived&> m4 = SafeMatcherCast<Derived&>(m3);
756   EXPECT_TRUE(m4.Matches(d));
757   EXPECT_FALSE(m4.Matches(d2));
758 }
759
760 // Tests that SafeMatcherCast<T&>(m) works when m is a Matcher<const T&>.
761 TEST(SafeMatcherCastTest, FromConstReferenceToReference) {
762   int n = 0;
763   Matcher<const int&> m1 = Ref(n);
764   Matcher<int&> m2 = SafeMatcherCast<int&>(m1);
765   int n1 = 0;
766   EXPECT_TRUE(m2.Matches(n));
767   EXPECT_FALSE(m2.Matches(n1));
768 }
769
770 // Tests that MatcherCast<const T&>(m) works when m is a Matcher<T>.
771 TEST(SafeMatcherCastTest, FromNonReferenceToConstReference) {
772   Matcher<std::unique_ptr<int>> m1 = IsNull();
773   Matcher<const std::unique_ptr<int>&> m2 =
774       SafeMatcherCast<const std::unique_ptr<int>&>(m1);
775   EXPECT_TRUE(m2.Matches(std::unique_ptr<int>()));
776   EXPECT_FALSE(m2.Matches(std::unique_ptr<int>(new int)));
777 }
778
779 // Tests that SafeMatcherCast<T&>(m) works when m is a Matcher<T>.
780 TEST(SafeMatcherCastTest, FromNonReferenceToReference) {
781   Matcher<int> m1 = Eq(0);
782   Matcher<int&> m2 = SafeMatcherCast<int&>(m1);
783   int n = 0;
784   EXPECT_TRUE(m2.Matches(n));
785   n = 1;
786   EXPECT_FALSE(m2.Matches(n));
787 }
788
789 // Tests that SafeMatcherCast<T>(m) works when m is a Matcher<T>.
790 TEST(SafeMatcherCastTest, FromSameType) {
791   Matcher<int> m1 = Eq(0);
792   Matcher<int> m2 = SafeMatcherCast<int>(m1);
793   EXPECT_TRUE(m2.Matches(0));
794   EXPECT_FALSE(m2.Matches(1));
795 }
796
797 #if !defined _MSC_VER
798
799 namespace convertible_from_any {
800 TEST(SafeMatcherCastTest, ConversionConstructorIsUsed) {
801   Matcher<ConvertibleFromAny> m = SafeMatcherCast<ConvertibleFromAny>(1);
802   EXPECT_TRUE(m.Matches(ConvertibleFromAny(1)));
803   EXPECT_FALSE(m.Matches(ConvertibleFromAny(2)));
804 }
805
806 TEST(SafeMatcherCastTest, FromConvertibleFromAny) {
807   Matcher<ConvertibleFromAny> m =
808       SafeMatcherCast<ConvertibleFromAny>(Eq(ConvertibleFromAny(1)));
809   EXPECT_TRUE(m.Matches(ConvertibleFromAny(1)));
810   EXPECT_FALSE(m.Matches(ConvertibleFromAny(2)));
811 }
812 }  // namespace convertible_from_any
813
814 #endif  // !defined _MSC_VER
815
816 TEST(SafeMatcherCastTest, ValueIsNotCopied) {
817   int n = 42;
818   Matcher<IntReferenceWrapper> m = SafeMatcherCast<IntReferenceWrapper>(n);
819   // Verify that the matcher holds a reference to n, not to its temporary copy.
820   EXPECT_TRUE(m.Matches(n));
821 }
822
823 TEST(ExpectThat, TakesLiterals) {
824   EXPECT_THAT(1, 1);
825   EXPECT_THAT(1.0, 1.0);
826   EXPECT_THAT(std::string(), "");
827 }
828
829 TEST(ExpectThat, TakesFunctions) {
830   struct Helper {
831     static void Func() {}
832   };
833   void (*func)() = Helper::Func;
834   EXPECT_THAT(func, Helper::Func);
835   EXPECT_THAT(func, &Helper::Func);
836 }
837
838 // Tests that A<T>() matches any value of type T.
839 TEST(ATest, MatchesAnyValue) {
840   // Tests a matcher for a value type.
841   Matcher<double> m1 = A<double>();
842   EXPECT_TRUE(m1.Matches(91.43));
843   EXPECT_TRUE(m1.Matches(-15.32));
844
845   // Tests a matcher for a reference type.
846   int a = 2;
847   int b = -6;
848   Matcher<int&> m2 = A<int&>();
849   EXPECT_TRUE(m2.Matches(a));
850   EXPECT_TRUE(m2.Matches(b));
851 }
852
853 TEST(ATest, WorksForDerivedClass) {
854   Base base;
855   Derived derived;
856   EXPECT_THAT(&base, A<Base*>());
857   // This shouldn't compile: EXPECT_THAT(&base, A<Derived*>());
858   EXPECT_THAT(&derived, A<Base*>());
859   EXPECT_THAT(&derived, A<Derived*>());
860 }
861
862 // Tests that A<T>() describes itself properly.
863 TEST(ATest, CanDescribeSelf) {
864   EXPECT_EQ("is anything", Describe(A<bool>()));
865 }
866
867 // Tests that An<T>() matches any value of type T.
868 TEST(AnTest, MatchesAnyValue) {
869   // Tests a matcher for a value type.
870   Matcher<int> m1 = An<int>();
871   EXPECT_TRUE(m1.Matches(9143));
872   EXPECT_TRUE(m1.Matches(-1532));
873
874   // Tests a matcher for a reference type.
875   int a = 2;
876   int b = -6;
877   Matcher<int&> m2 = An<int&>();
878   EXPECT_TRUE(m2.Matches(a));
879   EXPECT_TRUE(m2.Matches(b));
880 }
881
882 // Tests that An<T>() describes itself properly.
883 TEST(AnTest, CanDescribeSelf) {
884   EXPECT_EQ("is anything", Describe(An<int>()));
885 }
886
887 // Tests that _ can be used as a matcher for any type and matches any
888 // value of that type.
889 TEST(UnderscoreTest, MatchesAnyValue) {
890   // Uses _ as a matcher for a value type.
891   Matcher<int> m1 = _;
892   EXPECT_TRUE(m1.Matches(123));
893   EXPECT_TRUE(m1.Matches(-242));
894
895   // Uses _ as a matcher for a reference type.
896   bool a = false;
897   const bool b = true;
898   Matcher<const bool&> m2 = _;
899   EXPECT_TRUE(m2.Matches(a));
900   EXPECT_TRUE(m2.Matches(b));
901 }
902
903 // Tests that _ describes itself properly.
904 TEST(UnderscoreTest, CanDescribeSelf) {
905   Matcher<int> m = _;
906   EXPECT_EQ("is anything", Describe(m));
907 }
908
909 // Tests that Eq(x) matches any value equal to x.
910 TEST(EqTest, MatchesEqualValue) {
911   // 2 C-strings with same content but different addresses.
912   const char a1[] = "hi";
913   const char a2[] = "hi";
914
915   Matcher<const char*> m1 = Eq(a1);
916   EXPECT_TRUE(m1.Matches(a1));
917   EXPECT_FALSE(m1.Matches(a2));
918 }
919
920 // Tests that Eq(v) describes itself properly.
921
922 class Unprintable {
923  public:
924   Unprintable() : c_('a') {}
925
926   bool operator==(const Unprintable& /* rhs */) const { return true; }
927   // -Wunused-private-field: dummy accessor for `c_`.
928   char dummy_c() { return c_; }
929  private:
930   char c_;
931 };
932
933 TEST(EqTest, CanDescribeSelf) {
934   Matcher<Unprintable> m = Eq(Unprintable());
935   EXPECT_EQ("is equal to 1-byte object <61>", Describe(m));
936 }
937
938 // Tests that Eq(v) can be used to match any type that supports
939 // comparing with type T, where T is v's type.
940 TEST(EqTest, IsPolymorphic) {
941   Matcher<int> m1 = Eq(1);
942   EXPECT_TRUE(m1.Matches(1));
943   EXPECT_FALSE(m1.Matches(2));
944
945   Matcher<char> m2 = Eq(1);
946   EXPECT_TRUE(m2.Matches('\1'));
947   EXPECT_FALSE(m2.Matches('a'));
948 }
949
950 // Tests that TypedEq<T>(v) matches values of type T that's equal to v.
951 TEST(TypedEqTest, ChecksEqualityForGivenType) {
952   Matcher<char> m1 = TypedEq<char>('a');
953   EXPECT_TRUE(m1.Matches('a'));
954   EXPECT_FALSE(m1.Matches('b'));
955
956   Matcher<int> m2 = TypedEq<int>(6);
957   EXPECT_TRUE(m2.Matches(6));
958   EXPECT_FALSE(m2.Matches(7));
959 }
960
961 // Tests that TypedEq(v) describes itself properly.
962 TEST(TypedEqTest, CanDescribeSelf) {
963   EXPECT_EQ("is equal to 2", Describe(TypedEq<int>(2)));
964 }
965
966 // Tests that TypedEq<T>(v) has type Matcher<T>.
967
968 // Type<T>::IsTypeOf(v) compiles if and only if the type of value v is T, where
969 // T is a "bare" type (i.e. not in the form of const U or U&).  If v's type is
970 // not T, the compiler will generate a message about "undefined reference".
971 template <typename T>
972 struct Type {
973   static bool IsTypeOf(const T& /* v */) { return true; }
974
975   template <typename T2>
976   static void IsTypeOf(T2 v);
977 };
978
979 TEST(TypedEqTest, HasSpecifiedType) {
980   // Verfies that the type of TypedEq<T>(v) is Matcher<T>.
981   Type<Matcher<int> >::IsTypeOf(TypedEq<int>(5));
982   Type<Matcher<double> >::IsTypeOf(TypedEq<double>(5));
983 }
984
985 // Tests that Ge(v) matches anything >= v.
986 TEST(GeTest, ImplementsGreaterThanOrEqual) {
987   Matcher<int> m1 = Ge(0);
988   EXPECT_TRUE(m1.Matches(1));
989   EXPECT_TRUE(m1.Matches(0));
990   EXPECT_FALSE(m1.Matches(-1));
991 }
992
993 // Tests that Ge(v) describes itself properly.
994 TEST(GeTest, CanDescribeSelf) {
995   Matcher<int> m = Ge(5);
996   EXPECT_EQ("is >= 5", Describe(m));
997 }
998
999 // Tests that Gt(v) matches anything > v.
1000 TEST(GtTest, ImplementsGreaterThan) {
1001   Matcher<double> m1 = Gt(0);
1002   EXPECT_TRUE(m1.Matches(1.0));
1003   EXPECT_FALSE(m1.Matches(0.0));
1004   EXPECT_FALSE(m1.Matches(-1.0));
1005 }
1006
1007 // Tests that Gt(v) describes itself properly.
1008 TEST(GtTest, CanDescribeSelf) {
1009   Matcher<int> m = Gt(5);
1010   EXPECT_EQ("is > 5", Describe(m));
1011 }
1012
1013 // Tests that Le(v) matches anything <= v.
1014 TEST(LeTest, ImplementsLessThanOrEqual) {
1015   Matcher<char> m1 = Le('b');
1016   EXPECT_TRUE(m1.Matches('a'));
1017   EXPECT_TRUE(m1.Matches('b'));
1018   EXPECT_FALSE(m1.Matches('c'));
1019 }
1020
1021 // Tests that Le(v) describes itself properly.
1022 TEST(LeTest, CanDescribeSelf) {
1023   Matcher<int> m = Le(5);
1024   EXPECT_EQ("is <= 5", Describe(m));
1025 }
1026
1027 // Tests that Lt(v) matches anything < v.
1028 TEST(LtTest, ImplementsLessThan) {
1029   Matcher<const std::string&> m1 = Lt("Hello");
1030   EXPECT_TRUE(m1.Matches("Abc"));
1031   EXPECT_FALSE(m1.Matches("Hello"));
1032   EXPECT_FALSE(m1.Matches("Hello, world!"));
1033 }
1034
1035 // Tests that Lt(v) describes itself properly.
1036 TEST(LtTest, CanDescribeSelf) {
1037   Matcher<int> m = Lt(5);
1038   EXPECT_EQ("is < 5", Describe(m));
1039 }
1040
1041 // Tests that Ne(v) matches anything != v.
1042 TEST(NeTest, ImplementsNotEqual) {
1043   Matcher<int> m1 = Ne(0);
1044   EXPECT_TRUE(m1.Matches(1));
1045   EXPECT_TRUE(m1.Matches(-1));
1046   EXPECT_FALSE(m1.Matches(0));
1047 }
1048
1049 // Tests that Ne(v) describes itself properly.
1050 TEST(NeTest, CanDescribeSelf) {
1051   Matcher<int> m = Ne(5);
1052   EXPECT_EQ("isn't equal to 5", Describe(m));
1053 }
1054
1055 class MoveOnly {
1056  public:
1057   explicit MoveOnly(int i) : i_(i) {}
1058   MoveOnly(const MoveOnly&) = delete;
1059   MoveOnly(MoveOnly&&) = default;
1060   MoveOnly& operator=(const MoveOnly&) = delete;
1061   MoveOnly& operator=(MoveOnly&&) = default;
1062
1063   bool operator==(const MoveOnly& other) const { return i_ == other.i_; }
1064   bool operator!=(const MoveOnly& other) const { return i_ != other.i_; }
1065   bool operator<(const MoveOnly& other) const { return i_ < other.i_; }
1066   bool operator<=(const MoveOnly& other) const { return i_ <= other.i_; }
1067   bool operator>(const MoveOnly& other) const { return i_ > other.i_; }
1068   bool operator>=(const MoveOnly& other) const { return i_ >= other.i_; }
1069
1070  private:
1071   int i_;
1072 };
1073
1074 struct MoveHelper {
1075   MOCK_METHOD1(Call, void(MoveOnly));
1076 };
1077
1078 // Disable this test in VS 2015 (version 14), where it fails when SEH is enabled
1079 #if defined(_MSC_VER) && (_MSC_VER < 1910)
1080 TEST(ComparisonBaseTest, DISABLED_WorksWithMoveOnly) {
1081 #else
1082 TEST(ComparisonBaseTest, WorksWithMoveOnly) {
1083 #endif
1084   MoveOnly m{0};
1085   MoveHelper helper;
1086
1087   EXPECT_CALL(helper, Call(Eq(ByRef(m))));
1088   helper.Call(MoveOnly(0));
1089   EXPECT_CALL(helper, Call(Ne(ByRef(m))));
1090   helper.Call(MoveOnly(1));
1091   EXPECT_CALL(helper, Call(Le(ByRef(m))));
1092   helper.Call(MoveOnly(0));
1093   EXPECT_CALL(helper, Call(Lt(ByRef(m))));
1094   helper.Call(MoveOnly(-1));
1095   EXPECT_CALL(helper, Call(Ge(ByRef(m))));
1096   helper.Call(MoveOnly(0));
1097   EXPECT_CALL(helper, Call(Gt(ByRef(m))));
1098   helper.Call(MoveOnly(1));
1099 }
1100
1101 // Tests that IsNull() matches any NULL pointer of any type.
1102 TEST(IsNullTest, MatchesNullPointer) {
1103   Matcher<int*> m1 = IsNull();
1104   int* p1 = nullptr;
1105   int n = 0;
1106   EXPECT_TRUE(m1.Matches(p1));
1107   EXPECT_FALSE(m1.Matches(&n));
1108
1109   Matcher<const char*> m2 = IsNull();
1110   const char* p2 = nullptr;
1111   EXPECT_TRUE(m2.Matches(p2));
1112   EXPECT_FALSE(m2.Matches("hi"));
1113
1114   Matcher<void*> m3 = IsNull();
1115   void* p3 = nullptr;
1116   EXPECT_TRUE(m3.Matches(p3));
1117   EXPECT_FALSE(m3.Matches(reinterpret_cast<void*>(0xbeef)));
1118 }
1119
1120 TEST(IsNullTest, StdFunction) {
1121   const Matcher<std::function<void()>> m = IsNull();
1122
1123   EXPECT_TRUE(m.Matches(std::function<void()>()));
1124   EXPECT_FALSE(m.Matches([]{}));
1125 }
1126
1127 // Tests that IsNull() describes itself properly.
1128 TEST(IsNullTest, CanDescribeSelf) {
1129   Matcher<int*> m = IsNull();
1130   EXPECT_EQ("is NULL", Describe(m));
1131   EXPECT_EQ("isn't NULL", DescribeNegation(m));
1132 }
1133
1134 // Tests that NotNull() matches any non-NULL pointer of any type.
1135 TEST(NotNullTest, MatchesNonNullPointer) {
1136   Matcher<int*> m1 = NotNull();
1137   int* p1 = nullptr;
1138   int n = 0;
1139   EXPECT_FALSE(m1.Matches(p1));
1140   EXPECT_TRUE(m1.Matches(&n));
1141
1142   Matcher<const char*> m2 = NotNull();
1143   const char* p2 = nullptr;
1144   EXPECT_FALSE(m2.Matches(p2));
1145   EXPECT_TRUE(m2.Matches("hi"));
1146 }
1147
1148 TEST(NotNullTest, LinkedPtr) {
1149   const Matcher<std::shared_ptr<int>> m = NotNull();
1150   const std::shared_ptr<int> null_p;
1151   const std::shared_ptr<int> non_null_p(new int);
1152
1153   EXPECT_FALSE(m.Matches(null_p));
1154   EXPECT_TRUE(m.Matches(non_null_p));
1155 }
1156
1157 TEST(NotNullTest, ReferenceToConstLinkedPtr) {
1158   const Matcher<const std::shared_ptr<double>&> m = NotNull();
1159   const std::shared_ptr<double> null_p;
1160   const std::shared_ptr<double> non_null_p(new double);
1161
1162   EXPECT_FALSE(m.Matches(null_p));
1163   EXPECT_TRUE(m.Matches(non_null_p));
1164 }
1165
1166 TEST(NotNullTest, StdFunction) {
1167   const Matcher<std::function<void()>> m = NotNull();
1168
1169   EXPECT_TRUE(m.Matches([]{}));
1170   EXPECT_FALSE(m.Matches(std::function<void()>()));
1171 }
1172
1173 // Tests that NotNull() describes itself properly.
1174 TEST(NotNullTest, CanDescribeSelf) {
1175   Matcher<int*> m = NotNull();
1176   EXPECT_EQ("isn't NULL", Describe(m));
1177 }
1178
1179 // Tests that Ref(variable) matches an argument that references
1180 // 'variable'.
1181 TEST(RefTest, MatchesSameVariable) {
1182   int a = 0;
1183   int b = 0;
1184   Matcher<int&> m = Ref(a);
1185   EXPECT_TRUE(m.Matches(a));
1186   EXPECT_FALSE(m.Matches(b));
1187 }
1188
1189 // Tests that Ref(variable) describes itself properly.
1190 TEST(RefTest, CanDescribeSelf) {
1191   int n = 5;
1192   Matcher<int&> m = Ref(n);
1193   stringstream ss;
1194   ss << "references the variable @" << &n << " 5";
1195   EXPECT_EQ(ss.str(), Describe(m));
1196 }
1197
1198 // Test that Ref(non_const_varialbe) can be used as a matcher for a
1199 // const reference.
1200 TEST(RefTest, CanBeUsedAsMatcherForConstReference) {
1201   int a = 0;
1202   int b = 0;
1203   Matcher<const int&> m = Ref(a);
1204   EXPECT_TRUE(m.Matches(a));
1205   EXPECT_FALSE(m.Matches(b));
1206 }
1207
1208 // Tests that Ref(variable) is covariant, i.e. Ref(derived) can be
1209 // used wherever Ref(base) can be used (Ref(derived) is a sub-type
1210 // of Ref(base), but not vice versa.
1211
1212 TEST(RefTest, IsCovariant) {
1213   Base base, base2;
1214   Derived derived;
1215   Matcher<const Base&> m1 = Ref(base);
1216   EXPECT_TRUE(m1.Matches(base));
1217   EXPECT_FALSE(m1.Matches(base2));
1218   EXPECT_FALSE(m1.Matches(derived));
1219
1220   m1 = Ref(derived);
1221   EXPECT_TRUE(m1.Matches(derived));
1222   EXPECT_FALSE(m1.Matches(base));
1223   EXPECT_FALSE(m1.Matches(base2));
1224 }
1225
1226 TEST(RefTest, ExplainsResult) {
1227   int n = 0;
1228   EXPECT_THAT(Explain(Matcher<const int&>(Ref(n)), n),
1229               StartsWith("which is located @"));
1230
1231   int m = 0;
1232   EXPECT_THAT(Explain(Matcher<const int&>(Ref(n)), m),
1233               StartsWith("which is located @"));
1234 }
1235
1236 // Tests string comparison matchers.
1237
1238 template <typename T = std::string>
1239 std::string FromStringLike(internal::StringLike<T> str) {
1240   return std::string(str);
1241 }
1242
1243 TEST(StringLike, TestConversions) {
1244   EXPECT_EQ("foo", FromStringLike("foo"));
1245   EXPECT_EQ("foo", FromStringLike(std::string("foo")));
1246 #if GTEST_INTERNAL_HAS_STRING_VIEW
1247   EXPECT_EQ("foo", FromStringLike(internal::StringView("foo")));
1248 #endif  // GTEST_INTERNAL_HAS_STRING_VIEW
1249
1250   // Non deducible types.
1251   EXPECT_EQ("", FromStringLike({}));
1252   EXPECT_EQ("foo", FromStringLike({'f', 'o', 'o'}));
1253   const char buf[] = "foo";
1254   EXPECT_EQ("foo", FromStringLike({buf, buf + 3}));
1255 }
1256
1257 TEST(StrEqTest, MatchesEqualString) {
1258   Matcher<const char*> m = StrEq(std::string("Hello"));
1259   EXPECT_TRUE(m.Matches("Hello"));
1260   EXPECT_FALSE(m.Matches("hello"));
1261   EXPECT_FALSE(m.Matches(nullptr));
1262
1263   Matcher<const std::string&> m2 = StrEq("Hello");
1264   EXPECT_TRUE(m2.Matches("Hello"));
1265   EXPECT_FALSE(m2.Matches("Hi"));
1266
1267 #if GTEST_INTERNAL_HAS_STRING_VIEW
1268   Matcher<const internal::StringView&> m3 =
1269       StrEq(internal::StringView("Hello"));
1270   EXPECT_TRUE(m3.Matches(internal::StringView("Hello")));
1271   EXPECT_FALSE(m3.Matches(internal::StringView("hello")));
1272   EXPECT_FALSE(m3.Matches(internal::StringView()));
1273
1274   Matcher<const internal::StringView&> m_empty = StrEq("");
1275   EXPECT_TRUE(m_empty.Matches(internal::StringView("")));
1276   EXPECT_TRUE(m_empty.Matches(internal::StringView()));
1277   EXPECT_FALSE(m_empty.Matches(internal::StringView("hello")));
1278 #endif  // GTEST_INTERNAL_HAS_STRING_VIEW
1279 }
1280
1281 TEST(StrEqTest, CanDescribeSelf) {
1282   Matcher<std::string> m = StrEq("Hi-\'\"?\\\a\b\f\n\r\t\v\xD3");
1283   EXPECT_EQ("is equal to \"Hi-\'\\\"?\\\\\\a\\b\\f\\n\\r\\t\\v\\xD3\"",
1284       Describe(m));
1285
1286   std::string str("01204500800");
1287   str[3] = '\0';
1288   Matcher<std::string> m2 = StrEq(str);
1289   EXPECT_EQ("is equal to \"012\\04500800\"", Describe(m2));
1290   str[0] = str[6] = str[7] = str[9] = str[10] = '\0';
1291   Matcher<std::string> m3 = StrEq(str);
1292   EXPECT_EQ("is equal to \"\\012\\045\\0\\08\\0\\0\"", Describe(m3));
1293 }
1294
1295 TEST(StrNeTest, MatchesUnequalString) {
1296   Matcher<const char*> m = StrNe("Hello");
1297   EXPECT_TRUE(m.Matches(""));
1298   EXPECT_TRUE(m.Matches(nullptr));
1299   EXPECT_FALSE(m.Matches("Hello"));
1300
1301   Matcher<std::string> m2 = StrNe(std::string("Hello"));
1302   EXPECT_TRUE(m2.Matches("hello"));
1303   EXPECT_FALSE(m2.Matches("Hello"));
1304
1305 #if GTEST_INTERNAL_HAS_STRING_VIEW
1306   Matcher<const internal::StringView> m3 = StrNe(internal::StringView("Hello"));
1307   EXPECT_TRUE(m3.Matches(internal::StringView("")));
1308   EXPECT_TRUE(m3.Matches(internal::StringView()));
1309   EXPECT_FALSE(m3.Matches(internal::StringView("Hello")));
1310 #endif  // GTEST_INTERNAL_HAS_STRING_VIEW
1311 }
1312
1313 TEST(StrNeTest, CanDescribeSelf) {
1314   Matcher<const char*> m = StrNe("Hi");
1315   EXPECT_EQ("isn't equal to \"Hi\"", Describe(m));
1316 }
1317
1318 TEST(StrCaseEqTest, MatchesEqualStringIgnoringCase) {
1319   Matcher<const char*> m = StrCaseEq(std::string("Hello"));
1320   EXPECT_TRUE(m.Matches("Hello"));
1321   EXPECT_TRUE(m.Matches("hello"));
1322   EXPECT_FALSE(m.Matches("Hi"));
1323   EXPECT_FALSE(m.Matches(nullptr));
1324
1325   Matcher<const std::string&> m2 = StrCaseEq("Hello");
1326   EXPECT_TRUE(m2.Matches("hello"));
1327   EXPECT_FALSE(m2.Matches("Hi"));
1328
1329 #if GTEST_INTERNAL_HAS_STRING_VIEW
1330   Matcher<const internal::StringView&> m3 =
1331       StrCaseEq(internal::StringView("Hello"));
1332   EXPECT_TRUE(m3.Matches(internal::StringView("Hello")));
1333   EXPECT_TRUE(m3.Matches(internal::StringView("hello")));
1334   EXPECT_FALSE(m3.Matches(internal::StringView("Hi")));
1335   EXPECT_FALSE(m3.Matches(internal::StringView()));
1336 #endif  // GTEST_INTERNAL_HAS_STRING_VIEW
1337 }
1338
1339 TEST(StrCaseEqTest, MatchesEqualStringWith0IgnoringCase) {
1340   std::string str1("oabocdooeoo");
1341   std::string str2("OABOCDOOEOO");
1342   Matcher<const std::string&> m0 = StrCaseEq(str1);
1343   EXPECT_FALSE(m0.Matches(str2 + std::string(1, '\0')));
1344
1345   str1[3] = str2[3] = '\0';
1346   Matcher<const std::string&> m1 = StrCaseEq(str1);
1347   EXPECT_TRUE(m1.Matches(str2));
1348
1349   str1[0] = str1[6] = str1[7] = str1[10] = '\0';
1350   str2[0] = str2[6] = str2[7] = str2[10] = '\0';
1351   Matcher<const std::string&> m2 = StrCaseEq(str1);
1352   str1[9] = str2[9] = '\0';
1353   EXPECT_FALSE(m2.Matches(str2));
1354
1355   Matcher<const std::string&> m3 = StrCaseEq(str1);
1356   EXPECT_TRUE(m3.Matches(str2));
1357
1358   EXPECT_FALSE(m3.Matches(str2 + "x"));
1359   str2.append(1, '\0');
1360   EXPECT_FALSE(m3.Matches(str2));
1361   EXPECT_FALSE(m3.Matches(std::string(str2, 0, 9)));
1362 }
1363
1364 TEST(StrCaseEqTest, CanDescribeSelf) {
1365   Matcher<std::string> m = StrCaseEq("Hi");
1366   EXPECT_EQ("is equal to (ignoring case) \"Hi\"", Describe(m));
1367 }
1368
1369 TEST(StrCaseNeTest, MatchesUnequalStringIgnoringCase) {
1370   Matcher<const char*> m = StrCaseNe("Hello");
1371   EXPECT_TRUE(m.Matches("Hi"));
1372   EXPECT_TRUE(m.Matches(nullptr));
1373   EXPECT_FALSE(m.Matches("Hello"));
1374   EXPECT_FALSE(m.Matches("hello"));
1375
1376   Matcher<std::string> m2 = StrCaseNe(std::string("Hello"));
1377   EXPECT_TRUE(m2.Matches(""));
1378   EXPECT_FALSE(m2.Matches("Hello"));
1379
1380 #if GTEST_INTERNAL_HAS_STRING_VIEW
1381   Matcher<const internal::StringView> m3 =
1382       StrCaseNe(internal::StringView("Hello"));
1383   EXPECT_TRUE(m3.Matches(internal::StringView("Hi")));
1384   EXPECT_TRUE(m3.Matches(internal::StringView()));
1385   EXPECT_FALSE(m3.Matches(internal::StringView("Hello")));
1386   EXPECT_FALSE(m3.Matches(internal::StringView("hello")));
1387 #endif  // GTEST_INTERNAL_HAS_STRING_VIEW
1388 }
1389
1390 TEST(StrCaseNeTest, CanDescribeSelf) {
1391   Matcher<const char*> m = StrCaseNe("Hi");
1392   EXPECT_EQ("isn't equal to (ignoring case) \"Hi\"", Describe(m));
1393 }
1394
1395 // Tests that HasSubstr() works for matching string-typed values.
1396 TEST(HasSubstrTest, WorksForStringClasses) {
1397   const Matcher<std::string> m1 = HasSubstr("foo");
1398   EXPECT_TRUE(m1.Matches(std::string("I love food.")));
1399   EXPECT_FALSE(m1.Matches(std::string("tofo")));
1400
1401   const Matcher<const std::string&> m2 = HasSubstr("foo");
1402   EXPECT_TRUE(m2.Matches(std::string("I love food.")));
1403   EXPECT_FALSE(m2.Matches(std::string("tofo")));
1404
1405   const Matcher<std::string> m_empty = HasSubstr("");
1406   EXPECT_TRUE(m_empty.Matches(std::string()));
1407   EXPECT_TRUE(m_empty.Matches(std::string("not empty")));
1408 }
1409
1410 // Tests that HasSubstr() works for matching C-string-typed values.
1411 TEST(HasSubstrTest, WorksForCStrings) {
1412   const Matcher<char*> m1 = HasSubstr("foo");
1413   EXPECT_TRUE(m1.Matches(const_cast<char*>("I love food.")));
1414   EXPECT_FALSE(m1.Matches(const_cast<char*>("tofo")));
1415   EXPECT_FALSE(m1.Matches(nullptr));
1416
1417   const Matcher<const char*> m2 = HasSubstr("foo");
1418   EXPECT_TRUE(m2.Matches("I love food."));
1419   EXPECT_FALSE(m2.Matches("tofo"));
1420   EXPECT_FALSE(m2.Matches(nullptr));
1421
1422   const Matcher<const char*> m_empty = HasSubstr("");
1423   EXPECT_TRUE(m_empty.Matches("not empty"));
1424   EXPECT_TRUE(m_empty.Matches(""));
1425   EXPECT_FALSE(m_empty.Matches(nullptr));
1426 }
1427
1428 #if GTEST_INTERNAL_HAS_STRING_VIEW
1429 // Tests that HasSubstr() works for matching StringView-typed values.
1430 TEST(HasSubstrTest, WorksForStringViewClasses) {
1431   const Matcher<internal::StringView> m1 =
1432       HasSubstr(internal::StringView("foo"));
1433   EXPECT_TRUE(m1.Matches(internal::StringView("I love food.")));
1434   EXPECT_FALSE(m1.Matches(internal::StringView("tofo")));
1435   EXPECT_FALSE(m1.Matches(internal::StringView()));
1436
1437   const Matcher<const internal::StringView&> m2 = HasSubstr("foo");
1438   EXPECT_TRUE(m2.Matches(internal::StringView("I love food.")));
1439   EXPECT_FALSE(m2.Matches(internal::StringView("tofo")));
1440   EXPECT_FALSE(m2.Matches(internal::StringView()));
1441
1442   const Matcher<const internal::StringView&> m3 = HasSubstr("");
1443   EXPECT_TRUE(m3.Matches(internal::StringView("foo")));
1444   EXPECT_TRUE(m3.Matches(internal::StringView("")));
1445   EXPECT_TRUE(m3.Matches(internal::StringView()));
1446 }
1447 #endif  // GTEST_INTERNAL_HAS_STRING_VIEW
1448
1449 // Tests that HasSubstr(s) describes itself properly.
1450 TEST(HasSubstrTest, CanDescribeSelf) {
1451   Matcher<std::string> m = HasSubstr("foo\n\"");
1452   EXPECT_EQ("has substring \"foo\\n\\\"\"", Describe(m));
1453 }
1454
1455 TEST(KeyTest, CanDescribeSelf) {
1456   Matcher<const pair<std::string, int>&> m = Key("foo");
1457   EXPECT_EQ("has a key that is equal to \"foo\"", Describe(m));
1458   EXPECT_EQ("doesn't have a key that is equal to \"foo\"", DescribeNegation(m));
1459 }
1460
1461 TEST(KeyTest, ExplainsResult) {
1462   Matcher<pair<int, bool> > m = Key(GreaterThan(10));
1463   EXPECT_EQ("whose first field is a value which is 5 less than 10",
1464             Explain(m, make_pair(5, true)));
1465   EXPECT_EQ("whose first field is a value which is 5 more than 10",
1466             Explain(m, make_pair(15, true)));
1467 }
1468
1469 TEST(KeyTest, MatchesCorrectly) {
1470   pair<int, std::string> p(25, "foo");
1471   EXPECT_THAT(p, Key(25));
1472   EXPECT_THAT(p, Not(Key(42)));
1473   EXPECT_THAT(p, Key(Ge(20)));
1474   EXPECT_THAT(p, Not(Key(Lt(25))));
1475 }
1476
1477 TEST(KeyTest, WorksWithMoveOnly) {
1478   pair<std::unique_ptr<int>, std::unique_ptr<int>> p;
1479   EXPECT_THAT(p, Key(Eq(nullptr)));
1480 }
1481
1482 template <size_t I>
1483 struct Tag {};
1484
1485 struct PairWithGet {
1486   int member_1;
1487   std::string member_2;
1488   using first_type = int;
1489   using second_type = std::string;
1490
1491   const int& GetImpl(Tag<0>) const { return member_1; }
1492   const std::string& GetImpl(Tag<1>) const { return member_2; }
1493 };
1494 template <size_t I>
1495 auto get(const PairWithGet& value) -> decltype(value.GetImpl(Tag<I>())) {
1496   return value.GetImpl(Tag<I>());
1497 }
1498 TEST(PairTest, MatchesPairWithGetCorrectly) {
1499   PairWithGet p{25, "foo"};
1500   EXPECT_THAT(p, Key(25));
1501   EXPECT_THAT(p, Not(Key(42)));
1502   EXPECT_THAT(p, Key(Ge(20)));
1503   EXPECT_THAT(p, Not(Key(Lt(25))));
1504
1505   std::vector<PairWithGet> v = {{11, "Foo"}, {29, "gMockIsBestMock"}};
1506   EXPECT_THAT(v, Contains(Key(29)));
1507 }
1508
1509 TEST(KeyTest, SafelyCastsInnerMatcher) {
1510   Matcher<int> is_positive = Gt(0);
1511   Matcher<int> is_negative = Lt(0);
1512   pair<char, bool> p('a', true);
1513   EXPECT_THAT(p, Key(is_positive));
1514   EXPECT_THAT(p, Not(Key(is_negative)));
1515 }
1516
1517 TEST(KeyTest, InsideContainsUsingMap) {
1518   map<int, char> container;
1519   container.insert(make_pair(1, 'a'));
1520   container.insert(make_pair(2, 'b'));
1521   container.insert(make_pair(4, 'c'));
1522   EXPECT_THAT(container, Contains(Key(1)));
1523   EXPECT_THAT(container, Not(Contains(Key(3))));
1524 }
1525
1526 TEST(KeyTest, InsideContainsUsingMultimap) {
1527   multimap<int, char> container;
1528   container.insert(make_pair(1, 'a'));
1529   container.insert(make_pair(2, 'b'));
1530   container.insert(make_pair(4, 'c'));
1531
1532   EXPECT_THAT(container, Not(Contains(Key(25))));
1533   container.insert(make_pair(25, 'd'));
1534   EXPECT_THAT(container, Contains(Key(25)));
1535   container.insert(make_pair(25, 'e'));
1536   EXPECT_THAT(container, Contains(Key(25)));
1537
1538   EXPECT_THAT(container, Contains(Key(1)));
1539   EXPECT_THAT(container, Not(Contains(Key(3))));
1540 }
1541
1542 TEST(PairTest, Typing) {
1543   // Test verifies the following type conversions can be compiled.
1544   Matcher<const pair<const char*, int>&> m1 = Pair("foo", 42);
1545   Matcher<const pair<const char*, int> > m2 = Pair("foo", 42);
1546   Matcher<pair<const char*, int> > m3 = Pair("foo", 42);
1547
1548   Matcher<pair<int, const std::string> > m4 = Pair(25, "42");
1549   Matcher<pair<const std::string, int> > m5 = Pair("25", 42);
1550 }
1551
1552 TEST(PairTest, CanDescribeSelf) {
1553   Matcher<const pair<std::string, int>&> m1 = Pair("foo", 42);
1554   EXPECT_EQ("has a first field that is equal to \"foo\""
1555             ", and has a second field that is equal to 42",
1556             Describe(m1));
1557   EXPECT_EQ("has a first field that isn't equal to \"foo\""
1558             ", or has a second field that isn't equal to 42",
1559             DescribeNegation(m1));
1560   // Double and triple negation (1 or 2 times not and description of negation).
1561   Matcher<const pair<int, int>&> m2 = Not(Pair(Not(13), 42));
1562   EXPECT_EQ("has a first field that isn't equal to 13"
1563             ", and has a second field that is equal to 42",
1564             DescribeNegation(m2));
1565 }
1566
1567 TEST(PairTest, CanExplainMatchResultTo) {
1568   // If neither field matches, Pair() should explain about the first
1569   // field.
1570   const Matcher<pair<int, int> > m = Pair(GreaterThan(0), GreaterThan(0));
1571   EXPECT_EQ("whose first field does not match, which is 1 less than 0",
1572             Explain(m, make_pair(-1, -2)));
1573
1574   // If the first field matches but the second doesn't, Pair() should
1575   // explain about the second field.
1576   EXPECT_EQ("whose second field does not match, which is 2 less than 0",
1577             Explain(m, make_pair(1, -2)));
1578
1579   // If the first field doesn't match but the second does, Pair()
1580   // should explain about the first field.
1581   EXPECT_EQ("whose first field does not match, which is 1 less than 0",
1582             Explain(m, make_pair(-1, 2)));
1583
1584   // If both fields match, Pair() should explain about them both.
1585   EXPECT_EQ("whose both fields match, where the first field is a value "
1586             "which is 1 more than 0, and the second field is a value "
1587             "which is 2 more than 0",
1588             Explain(m, make_pair(1, 2)));
1589
1590   // If only the first match has an explanation, only this explanation should
1591   // be printed.
1592   const Matcher<pair<int, int> > explain_first = Pair(GreaterThan(0), 0);
1593   EXPECT_EQ("whose both fields match, where the first field is a value "
1594             "which is 1 more than 0",
1595             Explain(explain_first, make_pair(1, 0)));
1596
1597   // If only the second match has an explanation, only this explanation should
1598   // be printed.
1599   const Matcher<pair<int, int> > explain_second = Pair(0, GreaterThan(0));
1600   EXPECT_EQ("whose both fields match, where the second field is a value "
1601             "which is 1 more than 0",
1602             Explain(explain_second, make_pair(0, 1)));
1603 }
1604
1605 TEST(PairTest, MatchesCorrectly) {
1606   pair<int, std::string> p(25, "foo");
1607
1608   // Both fields match.
1609   EXPECT_THAT(p, Pair(25, "foo"));
1610   EXPECT_THAT(p, Pair(Ge(20), HasSubstr("o")));
1611
1612   // 'first' doesnt' match, but 'second' matches.
1613   EXPECT_THAT(p, Not(Pair(42, "foo")));
1614   EXPECT_THAT(p, Not(Pair(Lt(25), "foo")));
1615
1616   // 'first' matches, but 'second' doesn't match.
1617   EXPECT_THAT(p, Not(Pair(25, "bar")));
1618   EXPECT_THAT(p, Not(Pair(25, Not("foo"))));
1619
1620   // Neither field matches.
1621   EXPECT_THAT(p, Not(Pair(13, "bar")));
1622   EXPECT_THAT(p, Not(Pair(Lt(13), HasSubstr("a"))));
1623 }
1624
1625 TEST(PairTest, WorksWithMoveOnly) {
1626   pair<std::unique_ptr<int>, std::unique_ptr<int>> p;
1627   p.second.reset(new int(7));
1628   EXPECT_THAT(p, Pair(Eq(nullptr), Ne(nullptr)));
1629 }
1630
1631 TEST(PairTest, SafelyCastsInnerMatchers) {
1632   Matcher<int> is_positive = Gt(0);
1633   Matcher<int> is_negative = Lt(0);
1634   pair<char, bool> p('a', true);
1635   EXPECT_THAT(p, Pair(is_positive, _));
1636   EXPECT_THAT(p, Not(Pair(is_negative, _)));
1637   EXPECT_THAT(p, Pair(_, is_positive));
1638   EXPECT_THAT(p, Not(Pair(_, is_negative)));
1639 }
1640
1641 TEST(PairTest, InsideContainsUsingMap) {
1642   map<int, char> container;
1643   container.insert(make_pair(1, 'a'));
1644   container.insert(make_pair(2, 'b'));
1645   container.insert(make_pair(4, 'c'));
1646   EXPECT_THAT(container, Contains(Pair(1, 'a')));
1647   EXPECT_THAT(container, Contains(Pair(1, _)));
1648   EXPECT_THAT(container, Contains(Pair(_, 'a')));
1649   EXPECT_THAT(container, Not(Contains(Pair(3, _))));
1650 }
1651
1652 TEST(FieldsAreTest, MatchesCorrectly) {
1653   std::tuple<int, std::string, double> p(25, "foo", .5);
1654
1655   // All fields match.
1656   EXPECT_THAT(p, FieldsAre(25, "foo", .5));
1657   EXPECT_THAT(p, FieldsAre(Ge(20), HasSubstr("o"), DoubleEq(.5)));
1658
1659   // Some don't match.
1660   EXPECT_THAT(p, Not(FieldsAre(26, "foo", .5)));
1661   EXPECT_THAT(p, Not(FieldsAre(25, "fo", .5)));
1662   EXPECT_THAT(p, Not(FieldsAre(25, "foo", .6)));
1663 }
1664
1665 TEST(FieldsAreTest, CanDescribeSelf) {
1666   Matcher<const pair<std::string, int>&> m1 = FieldsAre("foo", 42);
1667   EXPECT_EQ(
1668       "has field #0 that is equal to \"foo\""
1669       ", and has field #1 that is equal to 42",
1670       Describe(m1));
1671   EXPECT_EQ(
1672       "has field #0 that isn't equal to \"foo\""
1673       ", or has field #1 that isn't equal to 42",
1674       DescribeNegation(m1));
1675 }
1676
1677 TEST(FieldsAreTest, CanExplainMatchResultTo) {
1678   // The first one that fails is the one that gives the error.
1679   Matcher<std::tuple<int, int, int>> m =
1680       FieldsAre(GreaterThan(0), GreaterThan(0), GreaterThan(0));
1681
1682   EXPECT_EQ("whose field #0 does not match, which is 1 less than 0",
1683             Explain(m, std::make_tuple(-1, -2, -3)));
1684   EXPECT_EQ("whose field #1 does not match, which is 2 less than 0",
1685             Explain(m, std::make_tuple(1, -2, -3)));
1686   EXPECT_EQ("whose field #2 does not match, which is 3 less than 0",
1687             Explain(m, std::make_tuple(1, 2, -3)));
1688
1689   // If they all match, we get a long explanation of success.
1690   EXPECT_EQ(
1691       "whose all elements match, "
1692       "where field #0 is a value which is 1 more than 0"
1693       ", and field #1 is a value which is 2 more than 0"
1694       ", and field #2 is a value which is 3 more than 0",
1695       Explain(m, std::make_tuple(1, 2, 3)));
1696
1697   // Only print those that have an explanation.
1698   m = FieldsAre(GreaterThan(0), 0, GreaterThan(0));
1699   EXPECT_EQ(
1700       "whose all elements match, "
1701       "where field #0 is a value which is 1 more than 0"
1702       ", and field #2 is a value which is 3 more than 0",
1703       Explain(m, std::make_tuple(1, 0, 3)));
1704
1705   // If only one has an explanation, then print that one.
1706   m = FieldsAre(0, GreaterThan(0), 0);
1707   EXPECT_EQ(
1708       "whose all elements match, "
1709       "where field #1 is a value which is 1 more than 0",
1710       Explain(m, std::make_tuple(0, 1, 0)));
1711 }
1712
1713 #if defined(__cpp_structured_bindings) && __cpp_structured_bindings >= 201606
1714 TEST(FieldsAreTest, StructuredBindings) {
1715   // testing::FieldsAre can also match aggregates and such with C++17 and up.
1716   struct MyType {
1717     int i;
1718     std::string str;
1719   };
1720   EXPECT_THAT((MyType{17, "foo"}), FieldsAre(Eq(17), HasSubstr("oo")));
1721
1722   // Test all the supported arities.
1723   struct MyVarType1 {
1724     int a;
1725   };
1726   EXPECT_THAT(MyVarType1{}, FieldsAre(0));
1727   struct MyVarType2 {
1728     int a, b;
1729   };
1730   EXPECT_THAT(MyVarType2{}, FieldsAre(0, 0));
1731   struct MyVarType3 {
1732     int a, b, c;
1733   };
1734   EXPECT_THAT(MyVarType3{}, FieldsAre(0, 0, 0));
1735   struct MyVarType4 {
1736     int a, b, c, d;
1737   };
1738   EXPECT_THAT(MyVarType4{}, FieldsAre(0, 0, 0, 0));
1739   struct MyVarType5 {
1740     int a, b, c, d, e;
1741   };
1742   EXPECT_THAT(MyVarType5{}, FieldsAre(0, 0, 0, 0, 0));
1743   struct MyVarType6 {
1744     int a, b, c, d, e, f;
1745   };
1746   EXPECT_THAT(MyVarType6{}, FieldsAre(0, 0, 0, 0, 0, 0));
1747   struct MyVarType7 {
1748     int a, b, c, d, e, f, g;
1749   };
1750   EXPECT_THAT(MyVarType7{}, FieldsAre(0, 0, 0, 0, 0, 0, 0));
1751   struct MyVarType8 {
1752     int a, b, c, d, e, f, g, h;
1753   };
1754   EXPECT_THAT(MyVarType8{}, FieldsAre(0, 0, 0, 0, 0, 0, 0, 0));
1755   struct MyVarType9 {
1756     int a, b, c, d, e, f, g, h, i;
1757   };
1758   EXPECT_THAT(MyVarType9{}, FieldsAre(0, 0, 0, 0, 0, 0, 0, 0, 0));
1759   struct MyVarType10 {
1760     int a, b, c, d, e, f, g, h, i, j;
1761   };
1762   EXPECT_THAT(MyVarType10{}, FieldsAre(0, 0, 0, 0, 0, 0, 0, 0, 0, 0));
1763   struct MyVarType11 {
1764     int a, b, c, d, e, f, g, h, i, j, k;
1765   };
1766   EXPECT_THAT(MyVarType11{}, FieldsAre(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0));
1767   struct MyVarType12 {
1768     int a, b, c, d, e, f, g, h, i, j, k, l;
1769   };
1770   EXPECT_THAT(MyVarType12{}, FieldsAre(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0));
1771   struct MyVarType13 {
1772     int a, b, c, d, e, f, g, h, i, j, k, l, m;
1773   };
1774   EXPECT_THAT(MyVarType13{}, FieldsAre(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0));
1775   struct MyVarType14 {
1776     int a, b, c, d, e, f, g, h, i, j, k, l, m, n;
1777   };
1778   EXPECT_THAT(MyVarType14{},
1779               FieldsAre(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0));
1780   struct MyVarType15 {
1781     int a, b, c, d, e, f, g, h, i, j, k, l, m, n, o;
1782   };
1783   EXPECT_THAT(MyVarType15{},
1784               FieldsAre(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0));
1785   struct MyVarType16 {
1786     int a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p;
1787   };
1788   EXPECT_THAT(MyVarType16{},
1789               FieldsAre(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0));
1790 }
1791 #endif
1792
1793 TEST(ContainsTest, WorksWithMoveOnly) {
1794   ContainerHelper helper;
1795   EXPECT_CALL(helper, Call(Contains(Pointee(2))));
1796   helper.Call(MakeUniquePtrs({1, 2}));
1797 }
1798
1799 TEST(PairTest, UseGetInsteadOfMembers) {
1800   PairWithGet pair{7, "ABC"};
1801   EXPECT_THAT(pair, Pair(7, "ABC"));
1802   EXPECT_THAT(pair, Pair(Ge(7), HasSubstr("AB")));
1803   EXPECT_THAT(pair, Not(Pair(Lt(7), "ABC")));
1804
1805   std::vector<PairWithGet> v = {{11, "Foo"}, {29, "gMockIsBestMock"}};
1806   EXPECT_THAT(v,
1807               ElementsAre(Pair(11, std::string("Foo")), Pair(Ge(10), Not(""))));
1808 }
1809
1810 // Tests StartsWith(s).
1811
1812 TEST(StartsWithTest, MatchesStringWithGivenPrefix) {
1813   const Matcher<const char*> m1 = StartsWith(std::string(""));
1814   EXPECT_TRUE(m1.Matches("Hi"));
1815   EXPECT_TRUE(m1.Matches(""));
1816   EXPECT_FALSE(m1.Matches(nullptr));
1817
1818   const Matcher<const std::string&> m2 = StartsWith("Hi");
1819   EXPECT_TRUE(m2.Matches("Hi"));
1820   EXPECT_TRUE(m2.Matches("Hi Hi!"));
1821   EXPECT_TRUE(m2.Matches("High"));
1822   EXPECT_FALSE(m2.Matches("H"));
1823   EXPECT_FALSE(m2.Matches(" Hi"));
1824
1825 #if GTEST_INTERNAL_HAS_STRING_VIEW
1826   const Matcher<internal::StringView> m_empty =
1827       StartsWith(internal::StringView(""));
1828   EXPECT_TRUE(m_empty.Matches(internal::StringView()));
1829   EXPECT_TRUE(m_empty.Matches(internal::StringView("")));
1830   EXPECT_TRUE(m_empty.Matches(internal::StringView("not empty")));
1831 #endif  // GTEST_INTERNAL_HAS_STRING_VIEW
1832 }
1833
1834 TEST(StartsWithTest, CanDescribeSelf) {
1835   Matcher<const std::string> m = StartsWith("Hi");
1836   EXPECT_EQ("starts with \"Hi\"", Describe(m));
1837 }
1838
1839 // Tests EndsWith(s).
1840
1841 TEST(EndsWithTest, MatchesStringWithGivenSuffix) {
1842   const Matcher<const char*> m1 = EndsWith("");
1843   EXPECT_TRUE(m1.Matches("Hi"));
1844   EXPECT_TRUE(m1.Matches(""));
1845   EXPECT_FALSE(m1.Matches(nullptr));
1846
1847   const Matcher<const std::string&> m2 = EndsWith(std::string("Hi"));
1848   EXPECT_TRUE(m2.Matches("Hi"));
1849   EXPECT_TRUE(m2.Matches("Wow Hi Hi"));
1850   EXPECT_TRUE(m2.Matches("Super Hi"));
1851   EXPECT_FALSE(m2.Matches("i"));
1852   EXPECT_FALSE(m2.Matches("Hi "));
1853
1854 #if GTEST_INTERNAL_HAS_STRING_VIEW
1855   const Matcher<const internal::StringView&> m4 =
1856       EndsWith(internal::StringView(""));
1857   EXPECT_TRUE(m4.Matches("Hi"));
1858   EXPECT_TRUE(m4.Matches(""));
1859   EXPECT_TRUE(m4.Matches(internal::StringView()));
1860   EXPECT_TRUE(m4.Matches(internal::StringView("")));
1861 #endif  // GTEST_INTERNAL_HAS_STRING_VIEW
1862 }
1863
1864 TEST(EndsWithTest, CanDescribeSelf) {
1865   Matcher<const std::string> m = EndsWith("Hi");
1866   EXPECT_EQ("ends with \"Hi\"", Describe(m));
1867 }
1868
1869 // Tests MatchesRegex().
1870
1871 TEST(MatchesRegexTest, MatchesStringMatchingGivenRegex) {
1872   const Matcher<const char*> m1 = MatchesRegex("a.*z");
1873   EXPECT_TRUE(m1.Matches("az"));
1874   EXPECT_TRUE(m1.Matches("abcz"));
1875   EXPECT_FALSE(m1.Matches(nullptr));
1876
1877   const Matcher<const std::string&> m2 = MatchesRegex(new RE("a.*z"));
1878   EXPECT_TRUE(m2.Matches("azbz"));
1879   EXPECT_FALSE(m2.Matches("az1"));
1880   EXPECT_FALSE(m2.Matches("1az"));
1881
1882 #if GTEST_INTERNAL_HAS_STRING_VIEW
1883   const Matcher<const internal::StringView&> m3 = MatchesRegex("a.*z");
1884   EXPECT_TRUE(m3.Matches(internal::StringView("az")));
1885   EXPECT_TRUE(m3.Matches(internal::StringView("abcz")));
1886   EXPECT_FALSE(m3.Matches(internal::StringView("1az")));
1887   EXPECT_FALSE(m3.Matches(internal::StringView()));
1888   const Matcher<const internal::StringView&> m4 =
1889       MatchesRegex(internal::StringView(""));
1890   EXPECT_TRUE(m4.Matches(internal::StringView("")));
1891   EXPECT_TRUE(m4.Matches(internal::StringView()));
1892 #endif  // GTEST_INTERNAL_HAS_STRING_VIEW
1893 }
1894
1895 TEST(MatchesRegexTest, CanDescribeSelf) {
1896   Matcher<const std::string> m1 = MatchesRegex(std::string("Hi.*"));
1897   EXPECT_EQ("matches regular expression \"Hi.*\"", Describe(m1));
1898
1899   Matcher<const char*> m2 = MatchesRegex(new RE("a.*"));
1900   EXPECT_EQ("matches regular expression \"a.*\"", Describe(m2));
1901
1902 #if GTEST_INTERNAL_HAS_STRING_VIEW
1903   Matcher<const internal::StringView> m3 = MatchesRegex(new RE("0.*"));
1904   EXPECT_EQ("matches regular expression \"0.*\"", Describe(m3));
1905 #endif  // GTEST_INTERNAL_HAS_STRING_VIEW
1906 }
1907
1908 // Tests ContainsRegex().
1909
1910 TEST(ContainsRegexTest, MatchesStringContainingGivenRegex) {
1911   const Matcher<const char*> m1 = ContainsRegex(std::string("a.*z"));
1912   EXPECT_TRUE(m1.Matches("az"));
1913   EXPECT_TRUE(m1.Matches("0abcz1"));
1914   EXPECT_FALSE(m1.Matches(nullptr));
1915
1916   const Matcher<const std::string&> m2 = ContainsRegex(new RE("a.*z"));
1917   EXPECT_TRUE(m2.Matches("azbz"));
1918   EXPECT_TRUE(m2.Matches("az1"));
1919   EXPECT_FALSE(m2.Matches("1a"));
1920
1921 #if GTEST_INTERNAL_HAS_STRING_VIEW
1922   const Matcher<const internal::StringView&> m3 =
1923       ContainsRegex(new RE("a.*z"));
1924   EXPECT_TRUE(m3.Matches(internal::StringView("azbz")));
1925   EXPECT_TRUE(m3.Matches(internal::StringView("az1")));
1926   EXPECT_FALSE(m3.Matches(internal::StringView("1a")));
1927   EXPECT_FALSE(m3.Matches(internal::StringView()));
1928   const Matcher<const internal::StringView&> m4 =
1929       ContainsRegex(internal::StringView(""));
1930   EXPECT_TRUE(m4.Matches(internal::StringView("")));
1931   EXPECT_TRUE(m4.Matches(internal::StringView()));
1932 #endif  // GTEST_INTERNAL_HAS_STRING_VIEW
1933 }
1934
1935 TEST(ContainsRegexTest, CanDescribeSelf) {
1936   Matcher<const std::string> m1 = ContainsRegex("Hi.*");
1937   EXPECT_EQ("contains regular expression \"Hi.*\"", Describe(m1));
1938
1939   Matcher<const char*> m2 = ContainsRegex(new RE("a.*"));
1940   EXPECT_EQ("contains regular expression \"a.*\"", Describe(m2));
1941
1942 #if GTEST_INTERNAL_HAS_STRING_VIEW
1943   Matcher<const internal::StringView> m3 = ContainsRegex(new RE("0.*"));
1944   EXPECT_EQ("contains regular expression \"0.*\"", Describe(m3));
1945 #endif  // GTEST_INTERNAL_HAS_STRING_VIEW
1946 }
1947
1948 // Tests for wide strings.
1949 #if GTEST_HAS_STD_WSTRING
1950 TEST(StdWideStrEqTest, MatchesEqual) {
1951   Matcher<const wchar_t*> m = StrEq(::std::wstring(L"Hello"));
1952   EXPECT_TRUE(m.Matches(L"Hello"));
1953   EXPECT_FALSE(m.Matches(L"hello"));
1954   EXPECT_FALSE(m.Matches(nullptr));
1955
1956   Matcher<const ::std::wstring&> m2 = StrEq(L"Hello");
1957   EXPECT_TRUE(m2.Matches(L"Hello"));
1958   EXPECT_FALSE(m2.Matches(L"Hi"));
1959
1960   Matcher<const ::std::wstring&> m3 = StrEq(L"\xD3\x576\x8D3\xC74D");
1961   EXPECT_TRUE(m3.Matches(L"\xD3\x576\x8D3\xC74D"));
1962   EXPECT_FALSE(m3.Matches(L"\xD3\x576\x8D3\xC74E"));
1963
1964   ::std::wstring str(L"01204500800");
1965   str[3] = L'\0';
1966   Matcher<const ::std::wstring&> m4 = StrEq(str);
1967   EXPECT_TRUE(m4.Matches(str));
1968   str[0] = str[6] = str[7] = str[9] = str[10] = L'\0';
1969   Matcher<const ::std::wstring&> m5 = StrEq(str);
1970   EXPECT_TRUE(m5.Matches(str));
1971 }
1972
1973 TEST(StdWideStrEqTest, CanDescribeSelf) {
1974   Matcher< ::std::wstring> m = StrEq(L"Hi-\'\"?\\\a\b\f\n\r\t\v");
1975   EXPECT_EQ("is equal to L\"Hi-\'\\\"?\\\\\\a\\b\\f\\n\\r\\t\\v\"",
1976     Describe(m));
1977
1978   Matcher< ::std::wstring> m2 = StrEq(L"\xD3\x576\x8D3\xC74D");
1979   EXPECT_EQ("is equal to L\"\\xD3\\x576\\x8D3\\xC74D\"",
1980     Describe(m2));
1981
1982   ::std::wstring str(L"01204500800");
1983   str[3] = L'\0';
1984   Matcher<const ::std::wstring&> m4 = StrEq(str);
1985   EXPECT_EQ("is equal to L\"012\\04500800\"", Describe(m4));
1986   str[0] = str[6] = str[7] = str[9] = str[10] = L'\0';
1987   Matcher<const ::std::wstring&> m5 = StrEq(str);
1988   EXPECT_EQ("is equal to L\"\\012\\045\\0\\08\\0\\0\"", Describe(m5));
1989 }
1990
1991 TEST(StdWideStrNeTest, MatchesUnequalString) {
1992   Matcher<const wchar_t*> m = StrNe(L"Hello");
1993   EXPECT_TRUE(m.Matches(L""));
1994   EXPECT_TRUE(m.Matches(nullptr));
1995   EXPECT_FALSE(m.Matches(L"Hello"));
1996
1997   Matcher< ::std::wstring> m2 = StrNe(::std::wstring(L"Hello"));
1998   EXPECT_TRUE(m2.Matches(L"hello"));
1999   EXPECT_FALSE(m2.Matches(L"Hello"));
2000 }
2001
2002 TEST(StdWideStrNeTest, CanDescribeSelf) {
2003   Matcher<const wchar_t*> m = StrNe(L"Hi");
2004   EXPECT_EQ("isn't equal to L\"Hi\"", Describe(m));
2005 }
2006
2007 TEST(StdWideStrCaseEqTest, MatchesEqualStringIgnoringCase) {
2008   Matcher<const wchar_t*> m = StrCaseEq(::std::wstring(L"Hello"));
2009   EXPECT_TRUE(m.Matches(L"Hello"));
2010   EXPECT_TRUE(m.Matches(L"hello"));
2011   EXPECT_FALSE(m.Matches(L"Hi"));
2012   EXPECT_FALSE(m.Matches(nullptr));
2013
2014   Matcher<const ::std::wstring&> m2 = StrCaseEq(L"Hello");
2015   EXPECT_TRUE(m2.Matches(L"hello"));
2016   EXPECT_FALSE(m2.Matches(L"Hi"));
2017 }
2018
2019 TEST(StdWideStrCaseEqTest, MatchesEqualStringWith0IgnoringCase) {
2020   ::std::wstring str1(L"oabocdooeoo");
2021   ::std::wstring str2(L"OABOCDOOEOO");
2022   Matcher<const ::std::wstring&> m0 = StrCaseEq(str1);
2023   EXPECT_FALSE(m0.Matches(str2 + ::std::wstring(1, L'\0')));
2024
2025   str1[3] = str2[3] = L'\0';
2026   Matcher<const ::std::wstring&> m1 = StrCaseEq(str1);
2027   EXPECT_TRUE(m1.Matches(str2));
2028
2029   str1[0] = str1[6] = str1[7] = str1[10] = L'\0';
2030   str2[0] = str2[6] = str2[7] = str2[10] = L'\0';
2031   Matcher<const ::std::wstring&> m2 = StrCaseEq(str1);
2032   str1[9] = str2[9] = L'\0';
2033   EXPECT_FALSE(m2.Matches(str2));
2034
2035   Matcher<const ::std::wstring&> m3 = StrCaseEq(str1);
2036   EXPECT_TRUE(m3.Matches(str2));
2037
2038   EXPECT_FALSE(m3.Matches(str2 + L"x"));
2039   str2.append(1, L'\0');
2040   EXPECT_FALSE(m3.Matches(str2));
2041   EXPECT_FALSE(m3.Matches(::std::wstring(str2, 0, 9)));
2042 }
2043
2044 TEST(StdWideStrCaseEqTest, CanDescribeSelf) {
2045   Matcher< ::std::wstring> m = StrCaseEq(L"Hi");
2046   EXPECT_EQ("is equal to (ignoring case) L\"Hi\"", Describe(m));
2047 }
2048
2049 TEST(StdWideStrCaseNeTest, MatchesUnequalStringIgnoringCase) {
2050   Matcher<const wchar_t*> m = StrCaseNe(L"Hello");
2051   EXPECT_TRUE(m.Matches(L"Hi"));
2052   EXPECT_TRUE(m.Matches(nullptr));
2053   EXPECT_FALSE(m.Matches(L"Hello"));
2054   EXPECT_FALSE(m.Matches(L"hello"));
2055
2056   Matcher< ::std::wstring> m2 = StrCaseNe(::std::wstring(L"Hello"));
2057   EXPECT_TRUE(m2.Matches(L""));
2058   EXPECT_FALSE(m2.Matches(L"Hello"));
2059 }
2060
2061 TEST(StdWideStrCaseNeTest, CanDescribeSelf) {
2062   Matcher<const wchar_t*> m = StrCaseNe(L"Hi");
2063   EXPECT_EQ("isn't equal to (ignoring case) L\"Hi\"", Describe(m));
2064 }
2065
2066 // Tests that HasSubstr() works for matching wstring-typed values.
2067 TEST(StdWideHasSubstrTest, WorksForStringClasses) {
2068   const Matcher< ::std::wstring> m1 = HasSubstr(L"foo");
2069   EXPECT_TRUE(m1.Matches(::std::wstring(L"I love food.")));
2070   EXPECT_FALSE(m1.Matches(::std::wstring(L"tofo")));
2071
2072   const Matcher<const ::std::wstring&> m2 = HasSubstr(L"foo");
2073   EXPECT_TRUE(m2.Matches(::std::wstring(L"I love food.")));
2074   EXPECT_FALSE(m2.Matches(::std::wstring(L"tofo")));
2075 }
2076
2077 // Tests that HasSubstr() works for matching C-wide-string-typed values.
2078 TEST(StdWideHasSubstrTest, WorksForCStrings) {
2079   const Matcher<wchar_t*> m1 = HasSubstr(L"foo");
2080   EXPECT_TRUE(m1.Matches(const_cast<wchar_t*>(L"I love food.")));
2081   EXPECT_FALSE(m1.Matches(const_cast<wchar_t*>(L"tofo")));
2082   EXPECT_FALSE(m1.Matches(nullptr));
2083
2084   const Matcher<const wchar_t*> m2 = HasSubstr(L"foo");
2085   EXPECT_TRUE(m2.Matches(L"I love food."));
2086   EXPECT_FALSE(m2.Matches(L"tofo"));
2087   EXPECT_FALSE(m2.Matches(nullptr));
2088 }
2089
2090 // Tests that HasSubstr(s) describes itself properly.
2091 TEST(StdWideHasSubstrTest, CanDescribeSelf) {
2092   Matcher< ::std::wstring> m = HasSubstr(L"foo\n\"");
2093   EXPECT_EQ("has substring L\"foo\\n\\\"\"", Describe(m));
2094 }
2095
2096 // Tests StartsWith(s).
2097
2098 TEST(StdWideStartsWithTest, MatchesStringWithGivenPrefix) {
2099   const Matcher<const wchar_t*> m1 = StartsWith(::std::wstring(L""));
2100   EXPECT_TRUE(m1.Matches(L"Hi"));
2101   EXPECT_TRUE(m1.Matches(L""));
2102   EXPECT_FALSE(m1.Matches(nullptr));
2103
2104   const Matcher<const ::std::wstring&> m2 = StartsWith(L"Hi");
2105   EXPECT_TRUE(m2.Matches(L"Hi"));
2106   EXPECT_TRUE(m2.Matches(L"Hi Hi!"));
2107   EXPECT_TRUE(m2.Matches(L"High"));
2108   EXPECT_FALSE(m2.Matches(L"H"));
2109   EXPECT_FALSE(m2.Matches(L" Hi"));
2110 }
2111
2112 TEST(StdWideStartsWithTest, CanDescribeSelf) {
2113   Matcher<const ::std::wstring> m = StartsWith(L"Hi");
2114   EXPECT_EQ("starts with L\"Hi\"", Describe(m));
2115 }
2116
2117 // Tests EndsWith(s).
2118
2119 TEST(StdWideEndsWithTest, MatchesStringWithGivenSuffix) {
2120   const Matcher<const wchar_t*> m1 = EndsWith(L"");
2121   EXPECT_TRUE(m1.Matches(L"Hi"));
2122   EXPECT_TRUE(m1.Matches(L""));
2123   EXPECT_FALSE(m1.Matches(nullptr));
2124
2125   const Matcher<const ::std::wstring&> m2 = EndsWith(::std::wstring(L"Hi"));
2126   EXPECT_TRUE(m2.Matches(L"Hi"));
2127   EXPECT_TRUE(m2.Matches(L"Wow Hi Hi"));
2128   EXPECT_TRUE(m2.Matches(L"Super Hi"));
2129   EXPECT_FALSE(m2.Matches(L"i"));
2130   EXPECT_FALSE(m2.Matches(L"Hi "));
2131 }
2132
2133 TEST(StdWideEndsWithTest, CanDescribeSelf) {
2134   Matcher<const ::std::wstring> m = EndsWith(L"Hi");
2135   EXPECT_EQ("ends with L\"Hi\"", Describe(m));
2136 }
2137
2138 #endif  // GTEST_HAS_STD_WSTRING
2139
2140 typedef ::std::tuple<long, int> Tuple2;  // NOLINT
2141
2142 // Tests that Eq() matches a 2-tuple where the first field == the
2143 // second field.
2144 TEST(Eq2Test, MatchesEqualArguments) {
2145   Matcher<const Tuple2&> m = Eq();
2146   EXPECT_TRUE(m.Matches(Tuple2(5L, 5)));
2147   EXPECT_FALSE(m.Matches(Tuple2(5L, 6)));
2148 }
2149
2150 // Tests that Eq() describes itself properly.
2151 TEST(Eq2Test, CanDescribeSelf) {
2152   Matcher<const Tuple2&> m = Eq();
2153   EXPECT_EQ("are an equal pair", Describe(m));
2154 }
2155
2156 // Tests that Ge() matches a 2-tuple where the first field >= the
2157 // second field.
2158 TEST(Ge2Test, MatchesGreaterThanOrEqualArguments) {
2159   Matcher<const Tuple2&> m = Ge();
2160   EXPECT_TRUE(m.Matches(Tuple2(5L, 4)));
2161   EXPECT_TRUE(m.Matches(Tuple2(5L, 5)));
2162   EXPECT_FALSE(m.Matches(Tuple2(5L, 6)));
2163 }
2164
2165 // Tests that Ge() describes itself properly.
2166 TEST(Ge2Test, CanDescribeSelf) {
2167   Matcher<const Tuple2&> m = Ge();
2168   EXPECT_EQ("are a pair where the first >= the second", Describe(m));
2169 }
2170
2171 // Tests that Gt() matches a 2-tuple where the first field > the
2172 // second field.
2173 TEST(Gt2Test, MatchesGreaterThanArguments) {
2174   Matcher<const Tuple2&> m = Gt();
2175   EXPECT_TRUE(m.Matches(Tuple2(5L, 4)));
2176   EXPECT_FALSE(m.Matches(Tuple2(5L, 5)));
2177   EXPECT_FALSE(m.Matches(Tuple2(5L, 6)));
2178 }
2179
2180 // Tests that Gt() describes itself properly.
2181 TEST(Gt2Test, CanDescribeSelf) {
2182   Matcher<const Tuple2&> m = Gt();
2183   EXPECT_EQ("are a pair where the first > the second", Describe(m));
2184 }
2185
2186 // Tests that Le() matches a 2-tuple where the first field <= the
2187 // second field.
2188 TEST(Le2Test, MatchesLessThanOrEqualArguments) {
2189   Matcher<const Tuple2&> m = Le();
2190   EXPECT_TRUE(m.Matches(Tuple2(5L, 6)));
2191   EXPECT_TRUE(m.Matches(Tuple2(5L, 5)));
2192   EXPECT_FALSE(m.Matches(Tuple2(5L, 4)));
2193 }
2194
2195 // Tests that Le() describes itself properly.
2196 TEST(Le2Test, CanDescribeSelf) {
2197   Matcher<const Tuple2&> m = Le();
2198   EXPECT_EQ("are a pair where the first <= the second", Describe(m));
2199 }
2200
2201 // Tests that Lt() matches a 2-tuple where the first field < the
2202 // second field.
2203 TEST(Lt2Test, MatchesLessThanArguments) {
2204   Matcher<const Tuple2&> m = Lt();
2205   EXPECT_TRUE(m.Matches(Tuple2(5L, 6)));
2206   EXPECT_FALSE(m.Matches(Tuple2(5L, 5)));
2207   EXPECT_FALSE(m.Matches(Tuple2(5L, 4)));
2208 }
2209
2210 // Tests that Lt() describes itself properly.
2211 TEST(Lt2Test, CanDescribeSelf) {
2212   Matcher<const Tuple2&> m = Lt();
2213   EXPECT_EQ("are a pair where the first < the second", Describe(m));
2214 }
2215
2216 // Tests that Ne() matches a 2-tuple where the first field != the
2217 // second field.
2218 TEST(Ne2Test, MatchesUnequalArguments) {
2219   Matcher<const Tuple2&> m = Ne();
2220   EXPECT_TRUE(m.Matches(Tuple2(5L, 6)));
2221   EXPECT_TRUE(m.Matches(Tuple2(5L, 4)));
2222   EXPECT_FALSE(m.Matches(Tuple2(5L, 5)));
2223 }
2224
2225 // Tests that Ne() describes itself properly.
2226 TEST(Ne2Test, CanDescribeSelf) {
2227   Matcher<const Tuple2&> m = Ne();
2228   EXPECT_EQ("are an unequal pair", Describe(m));
2229 }
2230
2231 TEST(PairMatchBaseTest, WorksWithMoveOnly) {
2232   using Pointers = std::tuple<std::unique_ptr<int>, std::unique_ptr<int>>;
2233   Matcher<Pointers> matcher = Eq();
2234   Pointers pointers;
2235   // Tested values don't matter; the point is that matcher does not copy the
2236   // matched values.
2237   EXPECT_TRUE(matcher.Matches(pointers));
2238 }
2239
2240 // Tests that IsNan() matches a NaN, with float.
2241 TEST(IsNan, FloatMatchesNan) {
2242   float quiet_nan = std::numeric_limits<float>::quiet_NaN();
2243   float other_nan = std::nanf("1");
2244   float real_value = 1.0f;
2245
2246   Matcher<float> m = IsNan();
2247   EXPECT_TRUE(m.Matches(quiet_nan));
2248   EXPECT_TRUE(m.Matches(other_nan));
2249   EXPECT_FALSE(m.Matches(real_value));
2250
2251   Matcher<float&> m_ref = IsNan();
2252   EXPECT_TRUE(m_ref.Matches(quiet_nan));
2253   EXPECT_TRUE(m_ref.Matches(other_nan));
2254   EXPECT_FALSE(m_ref.Matches(real_value));
2255
2256   Matcher<const float&> m_cref = IsNan();
2257   EXPECT_TRUE(m_cref.Matches(quiet_nan));
2258   EXPECT_TRUE(m_cref.Matches(other_nan));
2259   EXPECT_FALSE(m_cref.Matches(real_value));
2260 }
2261
2262 // Tests that IsNan() matches a NaN, with double.
2263 TEST(IsNan, DoubleMatchesNan) {
2264   double quiet_nan = std::numeric_limits<double>::quiet_NaN();
2265   double other_nan = std::nan("1");
2266   double real_value = 1.0;
2267
2268   Matcher<double> m = IsNan();
2269   EXPECT_TRUE(m.Matches(quiet_nan));
2270   EXPECT_TRUE(m.Matches(other_nan));
2271   EXPECT_FALSE(m.Matches(real_value));
2272
2273   Matcher<double&> m_ref = IsNan();
2274   EXPECT_TRUE(m_ref.Matches(quiet_nan));
2275   EXPECT_TRUE(m_ref.Matches(other_nan));
2276   EXPECT_FALSE(m_ref.Matches(real_value));
2277
2278   Matcher<const double&> m_cref = IsNan();
2279   EXPECT_TRUE(m_cref.Matches(quiet_nan));
2280   EXPECT_TRUE(m_cref.Matches(other_nan));
2281   EXPECT_FALSE(m_cref.Matches(real_value));
2282 }
2283
2284 // Tests that IsNan() matches a NaN, with long double.
2285 TEST(IsNan, LongDoubleMatchesNan) {
2286   long double quiet_nan = std::numeric_limits<long double>::quiet_NaN();
2287   long double other_nan = std::nan("1");
2288   long double real_value = 1.0;
2289
2290   Matcher<long double> m = IsNan();
2291   EXPECT_TRUE(m.Matches(quiet_nan));
2292   EXPECT_TRUE(m.Matches(other_nan));
2293   EXPECT_FALSE(m.Matches(real_value));
2294
2295   Matcher<long double&> m_ref = IsNan();
2296   EXPECT_TRUE(m_ref.Matches(quiet_nan));
2297   EXPECT_TRUE(m_ref.Matches(other_nan));
2298   EXPECT_FALSE(m_ref.Matches(real_value));
2299
2300   Matcher<const long double&> m_cref = IsNan();
2301   EXPECT_TRUE(m_cref.Matches(quiet_nan));
2302   EXPECT_TRUE(m_cref.Matches(other_nan));
2303   EXPECT_FALSE(m_cref.Matches(real_value));
2304 }
2305
2306 // Tests that IsNan() works with Not.
2307 TEST(IsNan, NotMatchesNan) {
2308   Matcher<float> mf = Not(IsNan());
2309   EXPECT_FALSE(mf.Matches(std::numeric_limits<float>::quiet_NaN()));
2310   EXPECT_FALSE(mf.Matches(std::nanf("1")));
2311   EXPECT_TRUE(mf.Matches(1.0));
2312
2313   Matcher<double> md = Not(IsNan());
2314   EXPECT_FALSE(md.Matches(std::numeric_limits<double>::quiet_NaN()));
2315   EXPECT_FALSE(md.Matches(std::nan("1")));
2316   EXPECT_TRUE(md.Matches(1.0));
2317
2318   Matcher<long double> mld = Not(IsNan());
2319   EXPECT_FALSE(mld.Matches(std::numeric_limits<long double>::quiet_NaN()));
2320   EXPECT_FALSE(mld.Matches(std::nanl("1")));
2321   EXPECT_TRUE(mld.Matches(1.0));
2322 }
2323
2324 // Tests that IsNan() can describe itself.
2325 TEST(IsNan, CanDescribeSelf) {
2326   Matcher<float> mf = IsNan();
2327   EXPECT_EQ("is NaN", Describe(mf));
2328
2329   Matcher<double> md = IsNan();
2330   EXPECT_EQ("is NaN", Describe(md));
2331
2332   Matcher<long double> mld = IsNan();
2333   EXPECT_EQ("is NaN", Describe(mld));
2334 }
2335
2336 // Tests that IsNan() can describe itself with Not.
2337 TEST(IsNan, CanDescribeSelfWithNot) {
2338   Matcher<float> mf = Not(IsNan());
2339   EXPECT_EQ("isn't NaN", Describe(mf));
2340
2341   Matcher<double> md = Not(IsNan());
2342   EXPECT_EQ("isn't NaN", Describe(md));
2343
2344   Matcher<long double> mld = Not(IsNan());
2345   EXPECT_EQ("isn't NaN", Describe(mld));
2346 }
2347
2348 // Tests that FloatEq() matches a 2-tuple where
2349 // FloatEq(first field) matches the second field.
2350 TEST(FloatEq2Test, MatchesEqualArguments) {
2351   typedef ::std::tuple<float, float> Tpl;
2352   Matcher<const Tpl&> m = FloatEq();
2353   EXPECT_TRUE(m.Matches(Tpl(1.0f, 1.0f)));
2354   EXPECT_TRUE(m.Matches(Tpl(0.3f, 0.1f + 0.1f + 0.1f)));
2355   EXPECT_FALSE(m.Matches(Tpl(1.1f, 1.0f)));
2356 }
2357
2358 // Tests that FloatEq() describes itself properly.
2359 TEST(FloatEq2Test, CanDescribeSelf) {
2360   Matcher<const ::std::tuple<float, float>&> m = FloatEq();
2361   EXPECT_EQ("are an almost-equal pair", Describe(m));
2362 }
2363
2364 // Tests that NanSensitiveFloatEq() matches a 2-tuple where
2365 // NanSensitiveFloatEq(first field) matches the second field.
2366 TEST(NanSensitiveFloatEqTest, MatchesEqualArgumentsWithNaN) {
2367   typedef ::std::tuple<float, float> Tpl;
2368   Matcher<const Tpl&> m = NanSensitiveFloatEq();
2369   EXPECT_TRUE(m.Matches(Tpl(1.0f, 1.0f)));
2370   EXPECT_TRUE(m.Matches(Tpl(std::numeric_limits<float>::quiet_NaN(),
2371                             std::numeric_limits<float>::quiet_NaN())));
2372   EXPECT_FALSE(m.Matches(Tpl(1.1f, 1.0f)));
2373   EXPECT_FALSE(m.Matches(Tpl(1.0f, std::numeric_limits<float>::quiet_NaN())));
2374   EXPECT_FALSE(m.Matches(Tpl(std::numeric_limits<float>::quiet_NaN(), 1.0f)));
2375 }
2376
2377 // Tests that NanSensitiveFloatEq() describes itself properly.
2378 TEST(NanSensitiveFloatEqTest, CanDescribeSelfWithNaNs) {
2379   Matcher<const ::std::tuple<float, float>&> m = NanSensitiveFloatEq();
2380   EXPECT_EQ("are an almost-equal pair", Describe(m));
2381 }
2382
2383 // Tests that DoubleEq() matches a 2-tuple where
2384 // DoubleEq(first field) matches the second field.
2385 TEST(DoubleEq2Test, MatchesEqualArguments) {
2386   typedef ::std::tuple<double, double> Tpl;
2387   Matcher<const Tpl&> m = DoubleEq();
2388   EXPECT_TRUE(m.Matches(Tpl(1.0, 1.0)));
2389   EXPECT_TRUE(m.Matches(Tpl(0.3, 0.1 + 0.1 + 0.1)));
2390   EXPECT_FALSE(m.Matches(Tpl(1.1, 1.0)));
2391 }
2392
2393 // Tests that DoubleEq() describes itself properly.
2394 TEST(DoubleEq2Test, CanDescribeSelf) {
2395   Matcher<const ::std::tuple<double, double>&> m = DoubleEq();
2396   EXPECT_EQ("are an almost-equal pair", Describe(m));
2397 }
2398
2399 // Tests that NanSensitiveDoubleEq() matches a 2-tuple where
2400 // NanSensitiveDoubleEq(first field) matches the second field.
2401 TEST(NanSensitiveDoubleEqTest, MatchesEqualArgumentsWithNaN) {
2402   typedef ::std::tuple<double, double> Tpl;
2403   Matcher<const Tpl&> m = NanSensitiveDoubleEq();
2404   EXPECT_TRUE(m.Matches(Tpl(1.0f, 1.0f)));
2405   EXPECT_TRUE(m.Matches(Tpl(std::numeric_limits<double>::quiet_NaN(),
2406                             std::numeric_limits<double>::quiet_NaN())));
2407   EXPECT_FALSE(m.Matches(Tpl(1.1f, 1.0f)));
2408   EXPECT_FALSE(m.Matches(Tpl(1.0f, std::numeric_limits<double>::quiet_NaN())));
2409   EXPECT_FALSE(m.Matches(Tpl(std::numeric_limits<double>::quiet_NaN(), 1.0f)));
2410 }
2411
2412 // Tests that DoubleEq() describes itself properly.
2413 TEST(NanSensitiveDoubleEqTest, CanDescribeSelfWithNaNs) {
2414   Matcher<const ::std::tuple<double, double>&> m = NanSensitiveDoubleEq();
2415   EXPECT_EQ("are an almost-equal pair", Describe(m));
2416 }
2417
2418 // Tests that FloatEq() matches a 2-tuple where
2419 // FloatNear(first field, max_abs_error) matches the second field.
2420 TEST(FloatNear2Test, MatchesEqualArguments) {
2421   typedef ::std::tuple<float, float> Tpl;
2422   Matcher<const Tpl&> m = FloatNear(0.5f);
2423   EXPECT_TRUE(m.Matches(Tpl(1.0f, 1.0f)));
2424   EXPECT_TRUE(m.Matches(Tpl(1.3f, 1.0f)));
2425   EXPECT_FALSE(m.Matches(Tpl(1.8f, 1.0f)));
2426 }
2427
2428 // Tests that FloatNear() describes itself properly.
2429 TEST(FloatNear2Test, CanDescribeSelf) {
2430   Matcher<const ::std::tuple<float, float>&> m = FloatNear(0.5f);
2431   EXPECT_EQ("are an almost-equal pair", Describe(m));
2432 }
2433
2434 // Tests that NanSensitiveFloatNear() matches a 2-tuple where
2435 // NanSensitiveFloatNear(first field) matches the second field.
2436 TEST(NanSensitiveFloatNearTest, MatchesNearbyArgumentsWithNaN) {
2437   typedef ::std::tuple<float, float> Tpl;
2438   Matcher<const Tpl&> m = NanSensitiveFloatNear(0.5f);
2439   EXPECT_TRUE(m.Matches(Tpl(1.0f, 1.0f)));
2440   EXPECT_TRUE(m.Matches(Tpl(1.1f, 1.0f)));
2441   EXPECT_TRUE(m.Matches(Tpl(std::numeric_limits<float>::quiet_NaN(),
2442                             std::numeric_limits<float>::quiet_NaN())));
2443   EXPECT_FALSE(m.Matches(Tpl(1.6f, 1.0f)));
2444   EXPECT_FALSE(m.Matches(Tpl(1.0f, std::numeric_limits<float>::quiet_NaN())));
2445   EXPECT_FALSE(m.Matches(Tpl(std::numeric_limits<float>::quiet_NaN(), 1.0f)));
2446 }
2447
2448 // Tests that NanSensitiveFloatNear() describes itself properly.
2449 TEST(NanSensitiveFloatNearTest, CanDescribeSelfWithNaNs) {
2450   Matcher<const ::std::tuple<float, float>&> m = NanSensitiveFloatNear(0.5f);
2451   EXPECT_EQ("are an almost-equal pair", Describe(m));
2452 }
2453
2454 // Tests that FloatEq() matches a 2-tuple where
2455 // DoubleNear(first field, max_abs_error) matches the second field.
2456 TEST(DoubleNear2Test, MatchesEqualArguments) {
2457   typedef ::std::tuple<double, double> Tpl;
2458   Matcher<const Tpl&> m = DoubleNear(0.5);
2459   EXPECT_TRUE(m.Matches(Tpl(1.0, 1.0)));
2460   EXPECT_TRUE(m.Matches(Tpl(1.3, 1.0)));
2461   EXPECT_FALSE(m.Matches(Tpl(1.8, 1.0)));
2462 }
2463
2464 // Tests that DoubleNear() describes itself properly.
2465 TEST(DoubleNear2Test, CanDescribeSelf) {
2466   Matcher<const ::std::tuple<double, double>&> m = DoubleNear(0.5);
2467   EXPECT_EQ("are an almost-equal pair", Describe(m));
2468 }
2469
2470 // Tests that NanSensitiveDoubleNear() matches a 2-tuple where
2471 // NanSensitiveDoubleNear(first field) matches the second field.
2472 TEST(NanSensitiveDoubleNearTest, MatchesNearbyArgumentsWithNaN) {
2473   typedef ::std::tuple<double, double> Tpl;
2474   Matcher<const Tpl&> m = NanSensitiveDoubleNear(0.5f);
2475   EXPECT_TRUE(m.Matches(Tpl(1.0f, 1.0f)));
2476   EXPECT_TRUE(m.Matches(Tpl(1.1f, 1.0f)));
2477   EXPECT_TRUE(m.Matches(Tpl(std::numeric_limits<double>::quiet_NaN(),
2478                             std::numeric_limits<double>::quiet_NaN())));
2479   EXPECT_FALSE(m.Matches(Tpl(1.6f, 1.0f)));
2480   EXPECT_FALSE(m.Matches(Tpl(1.0f, std::numeric_limits<double>::quiet_NaN())));
2481   EXPECT_FALSE(m.Matches(Tpl(std::numeric_limits<double>::quiet_NaN(), 1.0f)));
2482 }
2483
2484 // Tests that NanSensitiveDoubleNear() describes itself properly.
2485 TEST(NanSensitiveDoubleNearTest, CanDescribeSelfWithNaNs) {
2486   Matcher<const ::std::tuple<double, double>&> m = NanSensitiveDoubleNear(0.5f);
2487   EXPECT_EQ("are an almost-equal pair", Describe(m));
2488 }
2489
2490 // Tests that Not(m) matches any value that doesn't match m.
2491 TEST(NotTest, NegatesMatcher) {
2492   Matcher<int> m;
2493   m = Not(Eq(2));
2494   EXPECT_TRUE(m.Matches(3));
2495   EXPECT_FALSE(m.Matches(2));
2496 }
2497
2498 // Tests that Not(m) describes itself properly.
2499 TEST(NotTest, CanDescribeSelf) {
2500   Matcher<int> m = Not(Eq(5));
2501   EXPECT_EQ("isn't equal to 5", Describe(m));
2502 }
2503
2504 // Tests that monomorphic matchers are safely cast by the Not matcher.
2505 TEST(NotTest, NotMatcherSafelyCastsMonomorphicMatchers) {
2506   // greater_than_5 is a monomorphic matcher.
2507   Matcher<int> greater_than_5 = Gt(5);
2508
2509   Matcher<const int&> m = Not(greater_than_5);
2510   Matcher<int&> m2 = Not(greater_than_5);
2511   Matcher<int&> m3 = Not(m);
2512 }
2513
2514 // Helper to allow easy testing of AllOf matchers with num parameters.
2515 void AllOfMatches(int num, const Matcher<int>& m) {
2516   SCOPED_TRACE(Describe(m));
2517   EXPECT_TRUE(m.Matches(0));
2518   for (int i = 1; i <= num; ++i) {
2519     EXPECT_FALSE(m.Matches(i));
2520   }
2521   EXPECT_TRUE(m.Matches(num + 1));
2522 }
2523
2524 // Tests that AllOf(m1, ..., mn) matches any value that matches all of
2525 // the given matchers.
2526 TEST(AllOfTest, MatchesWhenAllMatch) {
2527   Matcher<int> m;
2528   m = AllOf(Le(2), Ge(1));
2529   EXPECT_TRUE(m.Matches(1));
2530   EXPECT_TRUE(m.Matches(2));
2531   EXPECT_FALSE(m.Matches(0));
2532   EXPECT_FALSE(m.Matches(3));
2533
2534   m = AllOf(Gt(0), Ne(1), Ne(2));
2535   EXPECT_TRUE(m.Matches(3));
2536   EXPECT_FALSE(m.Matches(2));
2537   EXPECT_FALSE(m.Matches(1));
2538   EXPECT_FALSE(m.Matches(0));
2539
2540   m = AllOf(Gt(0), Ne(1), Ne(2), Ne(3));
2541   EXPECT_TRUE(m.Matches(4));
2542   EXPECT_FALSE(m.Matches(3));
2543   EXPECT_FALSE(m.Matches(2));
2544   EXPECT_FALSE(m.Matches(1));
2545   EXPECT_FALSE(m.Matches(0));
2546
2547   m = AllOf(Ge(0), Lt(10), Ne(3), Ne(5), Ne(7));
2548   EXPECT_TRUE(m.Matches(0));
2549   EXPECT_TRUE(m.Matches(1));
2550   EXPECT_FALSE(m.Matches(3));
2551
2552   // The following tests for varying number of sub-matchers. Due to the way
2553   // the sub-matchers are handled it is enough to test every sub-matcher once
2554   // with sub-matchers using the same matcher type. Varying matcher types are
2555   // checked for above.
2556   AllOfMatches(2, AllOf(Ne(1), Ne(2)));
2557   AllOfMatches(3, AllOf(Ne(1), Ne(2), Ne(3)));
2558   AllOfMatches(4, AllOf(Ne(1), Ne(2), Ne(3), Ne(4)));
2559   AllOfMatches(5, AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5)));
2560   AllOfMatches(6, AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5), Ne(6)));
2561   AllOfMatches(7, AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5), Ne(6), Ne(7)));
2562   AllOfMatches(8, AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5), Ne(6), Ne(7),
2563                         Ne(8)));
2564   AllOfMatches(9, AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5), Ne(6), Ne(7),
2565                         Ne(8), Ne(9)));
2566   AllOfMatches(10, AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5), Ne(6), Ne(7), Ne(8),
2567                          Ne(9), Ne(10)));
2568   AllOfMatches(
2569       50, AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5), Ne(6), Ne(7), Ne(8), Ne(9),
2570                 Ne(10), Ne(11), Ne(12), Ne(13), Ne(14), Ne(15), Ne(16), Ne(17),
2571                 Ne(18), Ne(19), Ne(20), Ne(21), Ne(22), Ne(23), Ne(24), Ne(25),
2572                 Ne(26), Ne(27), Ne(28), Ne(29), Ne(30), Ne(31), Ne(32), Ne(33),
2573                 Ne(34), Ne(35), Ne(36), Ne(37), Ne(38), Ne(39), Ne(40), Ne(41),
2574                 Ne(42), Ne(43), Ne(44), Ne(45), Ne(46), Ne(47), Ne(48), Ne(49),
2575                 Ne(50)));
2576 }
2577
2578
2579 // Tests that AllOf(m1, ..., mn) describes itself properly.
2580 TEST(AllOfTest, CanDescribeSelf) {
2581   Matcher<int> m;
2582   m = AllOf(Le(2), Ge(1));
2583   EXPECT_EQ("(is <= 2) and (is >= 1)", Describe(m));
2584
2585   m = AllOf(Gt(0), Ne(1), Ne(2));
2586   std::string expected_descr1 =
2587       "(is > 0) and (isn't equal to 1) and (isn't equal to 2)";
2588   EXPECT_EQ(expected_descr1, Describe(m));
2589
2590   m = AllOf(Gt(0), Ne(1), Ne(2), Ne(3));
2591   std::string expected_descr2 =
2592       "(is > 0) and (isn't equal to 1) and (isn't equal to 2) and (isn't equal "
2593       "to 3)";
2594   EXPECT_EQ(expected_descr2, Describe(m));
2595
2596   m = AllOf(Ge(0), Lt(10), Ne(3), Ne(5), Ne(7));
2597   std::string expected_descr3 =
2598       "(is >= 0) and (is < 10) and (isn't equal to 3) and (isn't equal to 5) "
2599       "and (isn't equal to 7)";
2600   EXPECT_EQ(expected_descr3, Describe(m));
2601 }
2602
2603 // Tests that AllOf(m1, ..., mn) describes its negation properly.
2604 TEST(AllOfTest, CanDescribeNegation) {
2605   Matcher<int> m;
2606   m = AllOf(Le(2), Ge(1));
2607   std::string expected_descr4 = "(isn't <= 2) or (isn't >= 1)";
2608   EXPECT_EQ(expected_descr4, DescribeNegation(m));
2609
2610   m = AllOf(Gt(0), Ne(1), Ne(2));
2611   std::string expected_descr5 =
2612       "(isn't > 0) or (is equal to 1) or (is equal to 2)";
2613   EXPECT_EQ(expected_descr5, DescribeNegation(m));
2614
2615   m = AllOf(Gt(0), Ne(1), Ne(2), Ne(3));
2616   std::string expected_descr6 =
2617       "(isn't > 0) or (is equal to 1) or (is equal to 2) or (is equal to 3)";
2618   EXPECT_EQ(expected_descr6, DescribeNegation(m));
2619
2620   m = AllOf(Ge(0), Lt(10), Ne(3), Ne(5), Ne(7));
2621   std::string expected_desr7 =
2622       "(isn't >= 0) or (isn't < 10) or (is equal to 3) or (is equal to 5) or "
2623       "(is equal to 7)";
2624   EXPECT_EQ(expected_desr7, DescribeNegation(m));
2625
2626   m = AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5), Ne(6), Ne(7), Ne(8), Ne(9),
2627             Ne(10), Ne(11));
2628   AllOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11);
2629   EXPECT_THAT(Describe(m), EndsWith("and (isn't equal to 11)"));
2630   AllOfMatches(11, m);
2631 }
2632
2633 // Tests that monomorphic matchers are safely cast by the AllOf matcher.
2634 TEST(AllOfTest, AllOfMatcherSafelyCastsMonomorphicMatchers) {
2635   // greater_than_5 and less_than_10 are monomorphic matchers.
2636   Matcher<int> greater_than_5 = Gt(5);
2637   Matcher<int> less_than_10 = Lt(10);
2638
2639   Matcher<const int&> m = AllOf(greater_than_5, less_than_10);
2640   Matcher<int&> m2 = AllOf(greater_than_5, less_than_10);
2641   Matcher<int&> m3 = AllOf(greater_than_5, m2);
2642
2643   // Tests that BothOf works when composing itself.
2644   Matcher<const int&> m4 = AllOf(greater_than_5, less_than_10, less_than_10);
2645   Matcher<int&> m5 = AllOf(greater_than_5, less_than_10, less_than_10);
2646 }
2647
2648 TEST(AllOfTest, ExplainsResult) {
2649   Matcher<int> m;
2650
2651   // Successful match.  Both matchers need to explain.  The second
2652   // matcher doesn't give an explanation, so only the first matcher's
2653   // explanation is printed.
2654   m = AllOf(GreaterThan(10), Lt(30));
2655   EXPECT_EQ("which is 15 more than 10", Explain(m, 25));
2656
2657   // Successful match.  Both matchers need to explain.
2658   m = AllOf(GreaterThan(10), GreaterThan(20));
2659   EXPECT_EQ("which is 20 more than 10, and which is 10 more than 20",
2660             Explain(m, 30));
2661
2662   // Successful match.  All matchers need to explain.  The second
2663   // matcher doesn't given an explanation.
2664   m = AllOf(GreaterThan(10), Lt(30), GreaterThan(20));
2665   EXPECT_EQ("which is 15 more than 10, and which is 5 more than 20",
2666             Explain(m, 25));
2667
2668   // Successful match.  All matchers need to explain.
2669   m = AllOf(GreaterThan(10), GreaterThan(20), GreaterThan(30));
2670   EXPECT_EQ("which is 30 more than 10, and which is 20 more than 20, "
2671             "and which is 10 more than 30",
2672             Explain(m, 40));
2673
2674   // Failed match.  The first matcher, which failed, needs to
2675   // explain.
2676   m = AllOf(GreaterThan(10), GreaterThan(20));
2677   EXPECT_EQ("which is 5 less than 10", Explain(m, 5));
2678
2679   // Failed match.  The second matcher, which failed, needs to
2680   // explain.  Since it doesn't given an explanation, nothing is
2681   // printed.
2682   m = AllOf(GreaterThan(10), Lt(30));
2683   EXPECT_EQ("", Explain(m, 40));
2684
2685   // Failed match.  The second matcher, which failed, needs to
2686   // explain.
2687   m = AllOf(GreaterThan(10), GreaterThan(20));
2688   EXPECT_EQ("which is 5 less than 20", Explain(m, 15));
2689 }
2690
2691 // Helper to allow easy testing of AnyOf matchers with num parameters.
2692 static void AnyOfMatches(int num, const Matcher<int>& m) {
2693   SCOPED_TRACE(Describe(m));
2694   EXPECT_FALSE(m.Matches(0));
2695   for (int i = 1; i <= num; ++i) {
2696     EXPECT_TRUE(m.Matches(i));
2697   }
2698   EXPECT_FALSE(m.Matches(num + 1));
2699 }
2700
2701 static void AnyOfStringMatches(int num, const Matcher<std::string>& m) {
2702   SCOPED_TRACE(Describe(m));
2703   EXPECT_FALSE(m.Matches(std::to_string(0)));
2704
2705   for (int i = 1; i <= num; ++i) {
2706     EXPECT_TRUE(m.Matches(std::to_string(i)));
2707   }
2708   EXPECT_FALSE(m.Matches(std::to_string(num + 1)));
2709 }
2710
2711 // Tests that AnyOf(m1, ..., mn) matches any value that matches at
2712 // least one of the given matchers.
2713 TEST(AnyOfTest, MatchesWhenAnyMatches) {
2714   Matcher<int> m;
2715   m = AnyOf(Le(1), Ge(3));
2716   EXPECT_TRUE(m.Matches(1));
2717   EXPECT_TRUE(m.Matches(4));
2718   EXPECT_FALSE(m.Matches(2));
2719
2720   m = AnyOf(Lt(0), Eq(1), Eq(2));
2721   EXPECT_TRUE(m.Matches(-1));
2722   EXPECT_TRUE(m.Matches(1));
2723   EXPECT_TRUE(m.Matches(2));
2724   EXPECT_FALSE(m.Matches(0));
2725
2726   m = AnyOf(Lt(0), Eq(1), Eq(2), Eq(3));
2727   EXPECT_TRUE(m.Matches(-1));
2728   EXPECT_TRUE(m.Matches(1));
2729   EXPECT_TRUE(m.Matches(2));
2730   EXPECT_TRUE(m.Matches(3));
2731   EXPECT_FALSE(m.Matches(0));
2732
2733   m = AnyOf(Le(0), Gt(10), 3, 5, 7);
2734   EXPECT_TRUE(m.Matches(0));
2735   EXPECT_TRUE(m.Matches(11));
2736   EXPECT_TRUE(m.Matches(3));
2737   EXPECT_FALSE(m.Matches(2));
2738
2739   // The following tests for varying number of sub-matchers. Due to the way
2740   // the sub-matchers are handled it is enough to test every sub-matcher once
2741   // with sub-matchers using the same matcher type. Varying matcher types are
2742   // checked for above.
2743   AnyOfMatches(2, AnyOf(1, 2));
2744   AnyOfMatches(3, AnyOf(1, 2, 3));
2745   AnyOfMatches(4, AnyOf(1, 2, 3, 4));
2746   AnyOfMatches(5, AnyOf(1, 2, 3, 4, 5));
2747   AnyOfMatches(6, AnyOf(1, 2, 3, 4, 5, 6));
2748   AnyOfMatches(7, AnyOf(1, 2, 3, 4, 5, 6, 7));
2749   AnyOfMatches(8, AnyOf(1, 2, 3, 4, 5, 6, 7, 8));
2750   AnyOfMatches(9, AnyOf(1, 2, 3, 4, 5, 6, 7, 8, 9));
2751   AnyOfMatches(10, AnyOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10));
2752 }
2753
2754 // Tests the variadic version of the AnyOfMatcher.
2755 TEST(AnyOfTest, VariadicMatchesWhenAnyMatches) {
2756   // Also make sure AnyOf is defined in the right namespace and does not depend
2757   // on ADL.
2758   Matcher<int> m = ::testing::AnyOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11);
2759
2760   EXPECT_THAT(Describe(m), EndsWith("or (is equal to 11)"));
2761   AnyOfMatches(11, m);
2762   AnyOfMatches(50, AnyOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
2763                          11, 12, 13, 14, 15, 16, 17, 18, 19, 20,
2764                          21, 22, 23, 24, 25, 26, 27, 28, 29, 30,
2765                          31, 32, 33, 34, 35, 36, 37, 38, 39, 40,
2766                          41, 42, 43, 44, 45, 46, 47, 48, 49, 50));
2767   AnyOfStringMatches(
2768       50, AnyOf("1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12",
2769                 "13", "14", "15", "16", "17", "18", "19", "20", "21", "22",
2770                 "23", "24", "25", "26", "27", "28", "29", "30", "31", "32",
2771                 "33", "34", "35", "36", "37", "38", "39", "40", "41", "42",
2772                 "43", "44", "45", "46", "47", "48", "49", "50"));
2773 }
2774
2775 TEST(ConditionalTest, MatchesFirstIfCondition) {
2776   Matcher<std::string> eq_red = Eq("red");
2777   Matcher<std::string> ne_red = Ne("red");
2778   Matcher<std::string> m = Conditional(true, eq_red, ne_red);
2779   EXPECT_TRUE(m.Matches("red"));
2780   EXPECT_FALSE(m.Matches("green"));
2781
2782   StringMatchResultListener listener;
2783   StringMatchResultListener expected;
2784   EXPECT_FALSE(m.MatchAndExplain("green", &listener));
2785   EXPECT_FALSE(eq_red.MatchAndExplain("green", &expected));
2786   EXPECT_THAT(listener.str(), Eq(expected.str()));
2787 }
2788
2789 TEST(ConditionalTest, MatchesSecondIfCondition) {
2790   Matcher<std::string> eq_red = Eq("red");
2791   Matcher<std::string> ne_red = Ne("red");
2792   Matcher<std::string> m = Conditional(false, eq_red, ne_red);
2793   EXPECT_FALSE(m.Matches("red"));
2794   EXPECT_TRUE(m.Matches("green"));
2795
2796   StringMatchResultListener listener;
2797   StringMatchResultListener expected;
2798   EXPECT_FALSE(m.MatchAndExplain("red", &listener));
2799   EXPECT_FALSE(ne_red.MatchAndExplain("red", &expected));
2800   EXPECT_THAT(listener.str(), Eq(expected.str()));
2801 }
2802
2803 // Tests the variadic version of the ElementsAreMatcher
2804 TEST(ElementsAreTest, HugeMatcher) {
2805   vector<int> test_vector{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12};
2806
2807   EXPECT_THAT(test_vector,
2808               ElementsAre(Eq(1), Eq(2), Lt(13), Eq(4), Eq(5), Eq(6), Eq(7),
2809                           Eq(8), Eq(9), Eq(10), Gt(1), Eq(12)));
2810 }
2811
2812 // Tests the variadic version of the UnorderedElementsAreMatcher
2813 TEST(ElementsAreTest, HugeMatcherStr) {
2814   vector<std::string> test_vector{
2815       "literal_string", "", "", "", "", "", "", "", "", "", "", ""};
2816
2817   EXPECT_THAT(test_vector, UnorderedElementsAre("literal_string", _, _, _, _, _,
2818                                                 _, _, _, _, _, _));
2819 }
2820
2821 // Tests the variadic version of the UnorderedElementsAreMatcher
2822 TEST(ElementsAreTest, HugeMatcherUnordered) {
2823   vector<int> test_vector{2, 1, 8, 5, 4, 6, 7, 3, 9, 12, 11, 10};
2824
2825   EXPECT_THAT(test_vector, UnorderedElementsAre(
2826                                Eq(2), Eq(1), Gt(7), Eq(5), Eq(4), Eq(6), Eq(7),
2827                                Eq(3), Eq(9), Eq(12), Eq(11), Ne(122)));
2828 }
2829
2830
2831 // Tests that AnyOf(m1, ..., mn) describes itself properly.
2832 TEST(AnyOfTest, CanDescribeSelf) {
2833   Matcher<int> m;
2834   m = AnyOf(Le(1), Ge(3));
2835
2836   EXPECT_EQ("(is <= 1) or (is >= 3)",
2837             Describe(m));
2838
2839   m = AnyOf(Lt(0), Eq(1), Eq(2));
2840   EXPECT_EQ("(is < 0) or (is equal to 1) or (is equal to 2)", Describe(m));
2841
2842   m = AnyOf(Lt(0), Eq(1), Eq(2), Eq(3));
2843   EXPECT_EQ("(is < 0) or (is equal to 1) or (is equal to 2) or (is equal to 3)",
2844             Describe(m));
2845
2846   m = AnyOf(Le(0), Gt(10), 3, 5, 7);
2847   EXPECT_EQ(
2848       "(is <= 0) or (is > 10) or (is equal to 3) or (is equal to 5) or (is "
2849       "equal to 7)",
2850       Describe(m));
2851 }
2852
2853 // Tests that AnyOf(m1, ..., mn) describes its negation properly.
2854 TEST(AnyOfTest, CanDescribeNegation) {
2855   Matcher<int> m;
2856   m = AnyOf(Le(1), Ge(3));
2857   EXPECT_EQ("(isn't <= 1) and (isn't >= 3)",
2858             DescribeNegation(m));
2859
2860   m = AnyOf(Lt(0), Eq(1), Eq(2));
2861   EXPECT_EQ("(isn't < 0) and (isn't equal to 1) and (isn't equal to 2)",
2862             DescribeNegation(m));
2863
2864   m = AnyOf(Lt(0), Eq(1), Eq(2), Eq(3));
2865   EXPECT_EQ(
2866       "(isn't < 0) and (isn't equal to 1) and (isn't equal to 2) and (isn't "
2867       "equal to 3)",
2868       DescribeNegation(m));
2869
2870   m = AnyOf(Le(0), Gt(10), 3, 5, 7);
2871   EXPECT_EQ(
2872       "(isn't <= 0) and (isn't > 10) and (isn't equal to 3) and (isn't equal "
2873       "to 5) and (isn't equal to 7)",
2874       DescribeNegation(m));
2875 }
2876
2877 // Tests that monomorphic matchers are safely cast by the AnyOf matcher.
2878 TEST(AnyOfTest, AnyOfMatcherSafelyCastsMonomorphicMatchers) {
2879   // greater_than_5 and less_than_10 are monomorphic matchers.
2880   Matcher<int> greater_than_5 = Gt(5);
2881   Matcher<int> less_than_10 = Lt(10);
2882
2883   Matcher<const int&> m = AnyOf(greater_than_5, less_than_10);
2884   Matcher<int&> m2 = AnyOf(greater_than_5, less_than_10);
2885   Matcher<int&> m3 = AnyOf(greater_than_5, m2);
2886
2887   // Tests that EitherOf works when composing itself.
2888   Matcher<const int&> m4 = AnyOf(greater_than_5, less_than_10, less_than_10);
2889   Matcher<int&> m5 = AnyOf(greater_than_5, less_than_10, less_than_10);
2890 }
2891
2892 TEST(AnyOfTest, ExplainsResult) {
2893   Matcher<int> m;
2894
2895   // Failed match.  Both matchers need to explain.  The second
2896   // matcher doesn't give an explanation, so only the first matcher's
2897   // explanation is printed.
2898   m = AnyOf(GreaterThan(10), Lt(0));
2899   EXPECT_EQ("which is 5 less than 10", Explain(m, 5));
2900
2901   // Failed match.  Both matchers need to explain.
2902   m = AnyOf(GreaterThan(10), GreaterThan(20));
2903   EXPECT_EQ("which is 5 less than 10, and which is 15 less than 20",
2904             Explain(m, 5));
2905
2906   // Failed match.  All matchers need to explain.  The second
2907   // matcher doesn't given an explanation.
2908   m = AnyOf(GreaterThan(10), Gt(20), GreaterThan(30));
2909   EXPECT_EQ("which is 5 less than 10, and which is 25 less than 30",
2910             Explain(m, 5));
2911
2912   // Failed match.  All matchers need to explain.
2913   m = AnyOf(GreaterThan(10), GreaterThan(20), GreaterThan(30));
2914   EXPECT_EQ("which is 5 less than 10, and which is 15 less than 20, "
2915             "and which is 25 less than 30",
2916             Explain(m, 5));
2917
2918   // Successful match.  The first matcher, which succeeded, needs to
2919   // explain.
2920   m = AnyOf(GreaterThan(10), GreaterThan(20));
2921   EXPECT_EQ("which is 5 more than 10", Explain(m, 15));
2922
2923   // Successful match.  The second matcher, which succeeded, needs to
2924   // explain.  Since it doesn't given an explanation, nothing is
2925   // printed.
2926   m = AnyOf(GreaterThan(10), Lt(30));
2927   EXPECT_EQ("", Explain(m, 0));
2928
2929   // Successful match.  The second matcher, which succeeded, needs to
2930   // explain.
2931   m = AnyOf(GreaterThan(30), GreaterThan(20));
2932   EXPECT_EQ("which is 5 more than 20", Explain(m, 25));
2933 }
2934
2935 // The following predicate function and predicate functor are for
2936 // testing the Truly(predicate) matcher.
2937
2938 // Returns non-zero if the input is positive.  Note that the return
2939 // type of this function is not bool.  It's OK as Truly() accepts any
2940 // unary function or functor whose return type can be implicitly
2941 // converted to bool.
2942 int IsPositive(double x) {
2943   return x > 0 ? 1 : 0;
2944 }
2945
2946 // This functor returns true if the input is greater than the given
2947 // number.
2948 class IsGreaterThan {
2949  public:
2950   explicit IsGreaterThan(int threshold) : threshold_(threshold) {}
2951
2952   bool operator()(int n) const { return n > threshold_; }
2953
2954  private:
2955   int threshold_;
2956 };
2957
2958 // For testing Truly().
2959 const int foo = 0;
2960
2961 // This predicate returns true if and only if the argument references foo and
2962 // has a zero value.
2963 bool ReferencesFooAndIsZero(const int& n) {
2964   return (&n == &foo) && (n == 0);
2965 }
2966
2967 // Tests that Truly(predicate) matches what satisfies the given
2968 // predicate.
2969 TEST(TrulyTest, MatchesWhatSatisfiesThePredicate) {
2970   Matcher<double> m = Truly(IsPositive);
2971   EXPECT_TRUE(m.Matches(2.0));
2972   EXPECT_FALSE(m.Matches(-1.5));
2973 }
2974
2975 // Tests that Truly(predicate_functor) works too.
2976 TEST(TrulyTest, CanBeUsedWithFunctor) {
2977   Matcher<int> m = Truly(IsGreaterThan(5));
2978   EXPECT_TRUE(m.Matches(6));
2979   EXPECT_FALSE(m.Matches(4));
2980 }
2981
2982 // A class that can be implicitly converted to bool.
2983 class ConvertibleToBool {
2984  public:
2985   explicit ConvertibleToBool(int number) : number_(number) {}
2986   operator bool() const { return number_ != 0; }
2987
2988  private:
2989   int number_;
2990 };
2991
2992 ConvertibleToBool IsNotZero(int number) {
2993   return ConvertibleToBool(number);
2994 }
2995
2996 // Tests that the predicate used in Truly() may return a class that's
2997 // implicitly convertible to bool, even when the class has no
2998 // operator!().
2999 TEST(TrulyTest, PredicateCanReturnAClassConvertibleToBool) {
3000   Matcher<int> m = Truly(IsNotZero);
3001   EXPECT_TRUE(m.Matches(1));
3002   EXPECT_FALSE(m.Matches(0));
3003 }
3004
3005 // Tests that Truly(predicate) can describe itself properly.
3006 TEST(TrulyTest, CanDescribeSelf) {
3007   Matcher<double> m = Truly(IsPositive);
3008   EXPECT_EQ("satisfies the given predicate",
3009             Describe(m));
3010 }
3011
3012 // Tests that Truly(predicate) works when the matcher takes its
3013 // argument by reference.
3014 TEST(TrulyTest, WorksForByRefArguments) {
3015   Matcher<const int&> m = Truly(ReferencesFooAndIsZero);
3016   EXPECT_TRUE(m.Matches(foo));
3017   int n = 0;
3018   EXPECT_FALSE(m.Matches(n));
3019 }
3020
3021 // Tests that Truly(predicate) provides a helpful reason when it fails.
3022 TEST(TrulyTest, ExplainsFailures) {
3023   StringMatchResultListener listener;
3024   EXPECT_FALSE(ExplainMatchResult(Truly(IsPositive), -1, &listener));
3025   EXPECT_EQ(listener.str(), "didn't satisfy the given predicate");
3026 }
3027
3028 // Tests that Matches(m) is a predicate satisfied by whatever that
3029 // matches matcher m.
3030 TEST(MatchesTest, IsSatisfiedByWhatMatchesTheMatcher) {
3031   EXPECT_TRUE(Matches(Ge(0))(1));
3032   EXPECT_FALSE(Matches(Eq('a'))('b'));
3033 }
3034
3035 // Tests that Matches(m) works when the matcher takes its argument by
3036 // reference.
3037 TEST(MatchesTest, WorksOnByRefArguments) {
3038   int m = 0, n = 0;
3039   EXPECT_TRUE(Matches(AllOf(Ref(n), Eq(0)))(n));
3040   EXPECT_FALSE(Matches(Ref(m))(n));
3041 }
3042
3043 // Tests that a Matcher on non-reference type can be used in
3044 // Matches().
3045 TEST(MatchesTest, WorksWithMatcherOnNonRefType) {
3046   Matcher<int> eq5 = Eq(5);
3047   EXPECT_TRUE(Matches(eq5)(5));
3048   EXPECT_FALSE(Matches(eq5)(2));
3049 }
3050
3051 // Tests Value(value, matcher).  Since Value() is a simple wrapper for
3052 // Matches(), which has been tested already, we don't spend a lot of
3053 // effort on testing Value().
3054 TEST(ValueTest, WorksWithPolymorphicMatcher) {
3055   EXPECT_TRUE(Value("hi", StartsWith("h")));
3056   EXPECT_FALSE(Value(5, Gt(10)));
3057 }
3058
3059 TEST(ValueTest, WorksWithMonomorphicMatcher) {
3060   const Matcher<int> is_zero = Eq(0);
3061   EXPECT_TRUE(Value(0, is_zero));
3062   EXPECT_FALSE(Value('a', is_zero));
3063
3064   int n = 0;
3065   const Matcher<const int&> ref_n = Ref(n);
3066   EXPECT_TRUE(Value(n, ref_n));
3067   EXPECT_FALSE(Value(1, ref_n));
3068 }
3069
3070 TEST(ExplainMatchResultTest, WorksWithPolymorphicMatcher) {
3071   StringMatchResultListener listener1;
3072   EXPECT_TRUE(ExplainMatchResult(PolymorphicIsEven(), 42, &listener1));
3073   EXPECT_EQ("% 2 == 0", listener1.str());
3074
3075   StringMatchResultListener listener2;
3076   EXPECT_FALSE(ExplainMatchResult(Ge(42), 1.5, &listener2));
3077   EXPECT_EQ("", listener2.str());
3078 }
3079
3080 TEST(ExplainMatchResultTest, WorksWithMonomorphicMatcher) {
3081   const Matcher<int> is_even = PolymorphicIsEven();
3082   StringMatchResultListener listener1;
3083   EXPECT_TRUE(ExplainMatchResult(is_even, 42, &listener1));
3084   EXPECT_EQ("% 2 == 0", listener1.str());
3085
3086   const Matcher<const double&> is_zero = Eq(0);
3087   StringMatchResultListener listener2;
3088   EXPECT_FALSE(ExplainMatchResult(is_zero, 1.5, &listener2));
3089   EXPECT_EQ("", listener2.str());
3090 }
3091
3092 MATCHER(ConstructNoArg, "") { return true; }
3093 MATCHER_P(Construct1Arg, arg1, "") { return true; }
3094 MATCHER_P2(Construct2Args, arg1, arg2, "") { return true; }
3095
3096 TEST(MatcherConstruct, ExplicitVsImplicit) {
3097   {
3098     // No arg constructor can be constructed with empty brace.
3099     ConstructNoArgMatcher m = {};
3100     (void)m;
3101     // And with no args
3102     ConstructNoArgMatcher m2;
3103     (void)m2;
3104   }
3105   {
3106     // The one arg constructor has an explicit constructor.
3107     // This is to prevent the implicit conversion.
3108     using M = Construct1ArgMatcherP<int>;
3109     EXPECT_TRUE((std::is_constructible<M, int>::value));
3110     EXPECT_FALSE((std::is_convertible<int, M>::value));
3111   }
3112   {
3113     // Multiple arg matchers can be constructed with an implicit construction.
3114     Construct2ArgsMatcherP2<int, double> m = {1, 2.2};
3115     (void)m;
3116   }
3117 }
3118
3119 MATCHER_P(Really, inner_matcher, "") {
3120   return ExplainMatchResult(inner_matcher, arg, result_listener);
3121 }
3122
3123 TEST(ExplainMatchResultTest, WorksInsideMATCHER) {
3124   EXPECT_THAT(0, Really(Eq(0)));
3125 }
3126
3127 TEST(DescribeMatcherTest, WorksWithValue) {
3128   EXPECT_EQ("is equal to 42", DescribeMatcher<int>(42));
3129   EXPECT_EQ("isn't equal to 42", DescribeMatcher<int>(42, true));
3130 }
3131
3132 TEST(DescribeMatcherTest, WorksWithMonomorphicMatcher) {
3133   const Matcher<int> monomorphic = Le(0);
3134   EXPECT_EQ("is <= 0", DescribeMatcher<int>(monomorphic));
3135   EXPECT_EQ("isn't <= 0", DescribeMatcher<int>(monomorphic, true));
3136 }
3137
3138 TEST(DescribeMatcherTest, WorksWithPolymorphicMatcher) {
3139   EXPECT_EQ("is even", DescribeMatcher<int>(PolymorphicIsEven()));
3140   EXPECT_EQ("is odd", DescribeMatcher<int>(PolymorphicIsEven(), true));
3141 }
3142
3143 TEST(AllArgsTest, WorksForTuple) {
3144   EXPECT_THAT(std::make_tuple(1, 2L), AllArgs(Lt()));
3145   EXPECT_THAT(std::make_tuple(2L, 1), Not(AllArgs(Lt())));
3146 }
3147
3148 TEST(AllArgsTest, WorksForNonTuple) {
3149   EXPECT_THAT(42, AllArgs(Gt(0)));
3150   EXPECT_THAT('a', Not(AllArgs(Eq('b'))));
3151 }
3152
3153 class AllArgsHelper {
3154  public:
3155   AllArgsHelper() {}
3156
3157   MOCK_METHOD2(Helper, int(char x, int y));
3158
3159  private:
3160   GTEST_DISALLOW_COPY_AND_ASSIGN_(AllArgsHelper);
3161 };
3162
3163 TEST(AllArgsTest, WorksInWithClause) {
3164   AllArgsHelper helper;
3165   ON_CALL(helper, Helper(_, _))
3166       .With(AllArgs(Lt()))
3167       .WillByDefault(Return(1));
3168   EXPECT_CALL(helper, Helper(_, _));
3169   EXPECT_CALL(helper, Helper(_, _))
3170       .With(AllArgs(Gt()))
3171       .WillOnce(Return(2));
3172
3173   EXPECT_EQ(1, helper.Helper('\1', 2));
3174   EXPECT_EQ(2, helper.Helper('a', 1));
3175 }
3176
3177 class OptionalMatchersHelper {
3178  public:
3179   OptionalMatchersHelper() {}
3180
3181   MOCK_METHOD0(NoArgs, int());
3182
3183   MOCK_METHOD1(OneArg, int(int y));
3184
3185   MOCK_METHOD2(TwoArgs, int(char x, int y));
3186
3187   MOCK_METHOD1(Overloaded, int(char x));
3188   MOCK_METHOD2(Overloaded, int(char x, int y));
3189
3190  private:
3191   GTEST_DISALLOW_COPY_AND_ASSIGN_(OptionalMatchersHelper);
3192 };
3193
3194 TEST(AllArgsTest, WorksWithoutMatchers) {
3195   OptionalMatchersHelper helper;
3196
3197   ON_CALL(helper, NoArgs).WillByDefault(Return(10));
3198   ON_CALL(helper, OneArg).WillByDefault(Return(20));
3199   ON_CALL(helper, TwoArgs).WillByDefault(Return(30));
3200
3201   EXPECT_EQ(10, helper.NoArgs());
3202   EXPECT_EQ(20, helper.OneArg(1));
3203   EXPECT_EQ(30, helper.TwoArgs('\1', 2));
3204
3205   EXPECT_CALL(helper, NoArgs).Times(1);
3206   EXPECT_CALL(helper, OneArg).WillOnce(Return(100));
3207   EXPECT_CALL(helper, OneArg(17)).WillOnce(Return(200));
3208   EXPECT_CALL(helper, TwoArgs).Times(0);
3209
3210   EXPECT_EQ(10, helper.NoArgs());
3211   EXPECT_EQ(100, helper.OneArg(1));
3212   EXPECT_EQ(200, helper.OneArg(17));
3213 }
3214
3215 // Tests that ASSERT_THAT() and EXPECT_THAT() work when the value
3216 // matches the matcher.
3217 TEST(MatcherAssertionTest, WorksWhenMatcherIsSatisfied) {
3218   ASSERT_THAT(5, Ge(2)) << "This should succeed.";
3219   ASSERT_THAT("Foo", EndsWith("oo"));
3220   EXPECT_THAT(2, AllOf(Le(7), Ge(0))) << "This should succeed too.";
3221   EXPECT_THAT("Hello", StartsWith("Hell"));
3222 }
3223
3224 // Tests that ASSERT_THAT() and EXPECT_THAT() work when the value
3225 // doesn't match the matcher.
3226 TEST(MatcherAssertionTest, WorksWhenMatcherIsNotSatisfied) {
3227   // 'n' must be static as it is used in an EXPECT_FATAL_FAILURE(),
3228   // which cannot reference auto variables.
3229   static unsigned short n;  // NOLINT
3230   n = 5;
3231
3232   EXPECT_FATAL_FAILURE(ASSERT_THAT(n, Gt(10)),
3233                        "Value of: n\n"
3234                        "Expected: is > 10\n"
3235                        "  Actual: 5" + OfType("unsigned short"));
3236   n = 0;
3237   EXPECT_NONFATAL_FAILURE(
3238       EXPECT_THAT(n, AllOf(Le(7), Ge(5))),
3239       "Value of: n\n"
3240       "Expected: (is <= 7) and (is >= 5)\n"
3241       "  Actual: 0" + OfType("unsigned short"));
3242 }
3243
3244 // Tests that ASSERT_THAT() and EXPECT_THAT() work when the argument
3245 // has a reference type.
3246 TEST(MatcherAssertionTest, WorksForByRefArguments) {
3247   // We use a static variable here as EXPECT_FATAL_FAILURE() cannot
3248   // reference auto variables.
3249   static int n;
3250   n = 0;
3251   EXPECT_THAT(n, AllOf(Le(7), Ref(n)));
3252   EXPECT_FATAL_FAILURE(ASSERT_THAT(n, Not(Ref(n))),
3253                        "Value of: n\n"
3254                        "Expected: does not reference the variable @");
3255   // Tests the "Actual" part.
3256   EXPECT_FATAL_FAILURE(ASSERT_THAT(n, Not(Ref(n))),
3257                        "Actual: 0" + OfType("int") + ", which is located @");
3258 }
3259
3260 // Tests that ASSERT_THAT() and EXPECT_THAT() work when the matcher is
3261 // monomorphic.
3262 TEST(MatcherAssertionTest, WorksForMonomorphicMatcher) {
3263   Matcher<const char*> starts_with_he = StartsWith("he");
3264   ASSERT_THAT("hello", starts_with_he);
3265
3266   Matcher<const std::string&> ends_with_ok = EndsWith("ok");
3267   ASSERT_THAT("book", ends_with_ok);
3268   const std::string bad = "bad";
3269   EXPECT_NONFATAL_FAILURE(EXPECT_THAT(bad, ends_with_ok),
3270                           "Value of: bad\n"
3271                           "Expected: ends with \"ok\"\n"
3272                           "  Actual: \"bad\"");
3273   Matcher<int> is_greater_than_5 = Gt(5);
3274   EXPECT_NONFATAL_FAILURE(EXPECT_THAT(5, is_greater_than_5),
3275                           "Value of: 5\n"
3276                           "Expected: is > 5\n"
3277                           "  Actual: 5" + OfType("int"));
3278 }
3279
3280 // Tests floating-point matchers.
3281 template <typename RawType>
3282 class FloatingPointTest : public testing::Test {
3283  protected:
3284   typedef testing::internal::FloatingPoint<RawType> Floating;
3285   typedef typename Floating::Bits Bits;
3286
3287   FloatingPointTest()
3288       : max_ulps_(Floating::kMaxUlps),
3289         zero_bits_(Floating(0).bits()),
3290         one_bits_(Floating(1).bits()),
3291         infinity_bits_(Floating(Floating::Infinity()).bits()),
3292         close_to_positive_zero_(
3293             Floating::ReinterpretBits(zero_bits_ + max_ulps_/2)),
3294         close_to_negative_zero_(
3295             -Floating::ReinterpretBits(zero_bits_ + max_ulps_ - max_ulps_/2)),
3296         further_from_negative_zero_(-Floating::ReinterpretBits(
3297             zero_bits_ + max_ulps_ + 1 - max_ulps_/2)),
3298         close_to_one_(Floating::ReinterpretBits(one_bits_ + max_ulps_)),
3299         further_from_one_(Floating::ReinterpretBits(one_bits_ + max_ulps_ + 1)),
3300         infinity_(Floating::Infinity()),
3301         close_to_infinity_(
3302             Floating::ReinterpretBits(infinity_bits_ - max_ulps_)),
3303         further_from_infinity_(
3304             Floating::ReinterpretBits(infinity_bits_ - max_ulps_ - 1)),
3305         max_(Floating::Max()),
3306         nan1_(Floating::ReinterpretBits(Floating::kExponentBitMask | 1)),
3307         nan2_(Floating::ReinterpretBits(Floating::kExponentBitMask | 200)) {
3308   }
3309
3310   void TestSize() {
3311     EXPECT_EQ(sizeof(RawType), sizeof(Bits));
3312   }
3313
3314   // A battery of tests for FloatingEqMatcher::Matches.
3315   // matcher_maker is a pointer to a function which creates a FloatingEqMatcher.
3316   void TestMatches(
3317       testing::internal::FloatingEqMatcher<RawType> (*matcher_maker)(RawType)) {
3318     Matcher<RawType> m1 = matcher_maker(0.0);
3319     EXPECT_TRUE(m1.Matches(-0.0));
3320     EXPECT_TRUE(m1.Matches(close_to_positive_zero_));
3321     EXPECT_TRUE(m1.Matches(close_to_negative_zero_));
3322     EXPECT_FALSE(m1.Matches(1.0));
3323
3324     Matcher<RawType> m2 = matcher_maker(close_to_positive_zero_);
3325     EXPECT_FALSE(m2.Matches(further_from_negative_zero_));
3326
3327     Matcher<RawType> m3 = matcher_maker(1.0);
3328     EXPECT_TRUE(m3.Matches(close_to_one_));
3329     EXPECT_FALSE(m3.Matches(further_from_one_));
3330
3331     // Test commutativity: matcher_maker(0.0).Matches(1.0) was tested above.
3332     EXPECT_FALSE(m3.Matches(0.0));
3333
3334     Matcher<RawType> m4 = matcher_maker(-infinity_);
3335     EXPECT_TRUE(m4.Matches(-close_to_infinity_));
3336
3337     Matcher<RawType> m5 = matcher_maker(infinity_);
3338     EXPECT_TRUE(m5.Matches(close_to_infinity_));
3339
3340     // This is interesting as the representations of infinity_ and nan1_
3341     // are only 1 DLP apart.
3342     EXPECT_FALSE(m5.Matches(nan1_));
3343
3344     // matcher_maker can produce a Matcher<const RawType&>, which is needed in
3345     // some cases.
3346     Matcher<const RawType&> m6 = matcher_maker(0.0);
3347     EXPECT_TRUE(m6.Matches(-0.0));
3348     EXPECT_TRUE(m6.Matches(close_to_positive_zero_));
3349     EXPECT_FALSE(m6.Matches(1.0));
3350
3351     // matcher_maker can produce a Matcher<RawType&>, which is needed in some
3352     // cases.
3353     Matcher<RawType&> m7 = matcher_maker(0.0);
3354     RawType x = 0.0;
3355     EXPECT_TRUE(m7.Matches(x));
3356     x = 0.01f;
3357     EXPECT_FALSE(m7.Matches(x));
3358   }
3359
3360   // Pre-calculated numbers to be used by the tests.
3361
3362   const Bits max_ulps_;
3363
3364   const Bits zero_bits_;  // The bits that represent 0.0.
3365   const Bits one_bits_;  // The bits that represent 1.0.
3366   const Bits infinity_bits_;  // The bits that represent +infinity.
3367
3368   // Some numbers close to 0.0.
3369   const RawType close_to_positive_zero_;
3370   const RawType close_to_negative_zero_;
3371   const RawType further_from_negative_zero_;
3372
3373   // Some numbers close to 1.0.
3374   const RawType close_to_one_;
3375   const RawType further_from_one_;
3376
3377   // Some numbers close to +infinity.
3378   const RawType infinity_;
3379   const RawType close_to_infinity_;
3380   const RawType further_from_infinity_;
3381
3382   // Maximum representable value that's not infinity.
3383   const RawType max_;
3384
3385   // Some NaNs.
3386   const RawType nan1_;
3387   const RawType nan2_;
3388 };
3389
3390 // Tests floating-point matchers with fixed epsilons.
3391 template <typename RawType>
3392 class FloatingPointNearTest : public FloatingPointTest<RawType> {
3393  protected:
3394   typedef FloatingPointTest<RawType> ParentType;
3395
3396   // A battery of tests for FloatingEqMatcher::Matches with a fixed epsilon.
3397   // matcher_maker is a pointer to a function which creates a FloatingEqMatcher.
3398   void TestNearMatches(
3399       testing::internal::FloatingEqMatcher<RawType>
3400           (*matcher_maker)(RawType, RawType)) {
3401     Matcher<RawType> m1 = matcher_maker(0.0, 0.0);
3402     EXPECT_TRUE(m1.Matches(0.0));
3403     EXPECT_TRUE(m1.Matches(-0.0));
3404     EXPECT_FALSE(m1.Matches(ParentType::close_to_positive_zero_));
3405     EXPECT_FALSE(m1.Matches(ParentType::close_to_negative_zero_));
3406     EXPECT_FALSE(m1.Matches(1.0));
3407
3408     Matcher<RawType> m2 = matcher_maker(0.0, 1.0);
3409     EXPECT_TRUE(m2.Matches(0.0));
3410     EXPECT_TRUE(m2.Matches(-0.0));
3411     EXPECT_TRUE(m2.Matches(1.0));
3412     EXPECT_TRUE(m2.Matches(-1.0));
3413     EXPECT_FALSE(m2.Matches(ParentType::close_to_one_));
3414     EXPECT_FALSE(m2.Matches(-ParentType::close_to_one_));
3415
3416     // Check that inf matches inf, regardless of the of the specified max
3417     // absolute error.
3418     Matcher<RawType> m3 = matcher_maker(ParentType::infinity_, 0.0);
3419     EXPECT_TRUE(m3.Matches(ParentType::infinity_));
3420     EXPECT_FALSE(m3.Matches(ParentType::close_to_infinity_));
3421     EXPECT_FALSE(m3.Matches(-ParentType::infinity_));
3422
3423     Matcher<RawType> m4 = matcher_maker(-ParentType::infinity_, 0.0);
3424     EXPECT_TRUE(m4.Matches(-ParentType::infinity_));
3425     EXPECT_FALSE(m4.Matches(-ParentType::close_to_infinity_));
3426     EXPECT_FALSE(m4.Matches(ParentType::infinity_));
3427
3428     // Test various overflow scenarios.
3429     Matcher<RawType> m5 = matcher_maker(ParentType::max_, ParentType::max_);
3430     EXPECT_TRUE(m5.Matches(ParentType::max_));
3431     EXPECT_FALSE(m5.Matches(-ParentType::max_));
3432
3433     Matcher<RawType> m6 = matcher_maker(-ParentType::max_, ParentType::max_);
3434     EXPECT_FALSE(m6.Matches(ParentType::max_));
3435     EXPECT_TRUE(m6.Matches(-ParentType::max_));
3436
3437     Matcher<RawType> m7 = matcher_maker(ParentType::max_, 0);
3438     EXPECT_TRUE(m7.Matches(ParentType::max_));
3439     EXPECT_FALSE(m7.Matches(-ParentType::max_));
3440
3441     Matcher<RawType> m8 = matcher_maker(-ParentType::max_, 0);
3442     EXPECT_FALSE(m8.Matches(ParentType::max_));
3443     EXPECT_TRUE(m8.Matches(-ParentType::max_));
3444
3445     // The difference between max() and -max() normally overflows to infinity,
3446     // but it should still match if the max_abs_error is also infinity.
3447     Matcher<RawType> m9 = matcher_maker(
3448         ParentType::max_, ParentType::infinity_);
3449     EXPECT_TRUE(m8.Matches(-ParentType::max_));
3450
3451     // matcher_maker can produce a Matcher<const RawType&>, which is needed in
3452     // some cases.
3453     Matcher<const RawType&> m10 = matcher_maker(0.0, 1.0);
3454     EXPECT_TRUE(m10.Matches(-0.0));
3455     EXPECT_TRUE(m10.Matches(ParentType::close_to_positive_zero_));
3456     EXPECT_FALSE(m10.Matches(ParentType::close_to_one_));
3457
3458     // matcher_maker can produce a Matcher<RawType&>, which is needed in some
3459     // cases.
3460     Matcher<RawType&> m11 = matcher_maker(0.0, 1.0);
3461     RawType x = 0.0;
3462     EXPECT_TRUE(m11.Matches(x));
3463     x = 1.0f;
3464     EXPECT_TRUE(m11.Matches(x));
3465     x = -1.0f;
3466     EXPECT_TRUE(m11.Matches(x));
3467     x = 1.1f;
3468     EXPECT_FALSE(m11.Matches(x));
3469     x = -1.1f;
3470     EXPECT_FALSE(m11.Matches(x));
3471   }
3472 };
3473
3474 // Instantiate FloatingPointTest for testing floats.
3475 typedef FloatingPointTest<float> FloatTest;
3476
3477 TEST_F(FloatTest, FloatEqApproximatelyMatchesFloats) {
3478   TestMatches(&FloatEq);
3479 }
3480
3481 TEST_F(FloatTest, NanSensitiveFloatEqApproximatelyMatchesFloats) {
3482   TestMatches(&NanSensitiveFloatEq);
3483 }
3484
3485 TEST_F(FloatTest, FloatEqCannotMatchNaN) {
3486   // FloatEq never matches NaN.
3487   Matcher<float> m = FloatEq(nan1_);
3488   EXPECT_FALSE(m.Matches(nan1_));
3489   EXPECT_FALSE(m.Matches(nan2_));
3490   EXPECT_FALSE(m.Matches(1.0));
3491 }
3492
3493 TEST_F(FloatTest, NanSensitiveFloatEqCanMatchNaN) {
3494   // NanSensitiveFloatEq will match NaN.
3495   Matcher<float> m = NanSensitiveFloatEq(nan1_);
3496   EXPECT_TRUE(m.Matches(nan1_));
3497   EXPECT_TRUE(m.Matches(nan2_));
3498   EXPECT_FALSE(m.Matches(1.0));
3499 }
3500
3501 TEST_F(FloatTest, FloatEqCanDescribeSelf) {
3502   Matcher<float> m1 = FloatEq(2.0f);
3503   EXPECT_EQ("is approximately 2", Describe(m1));
3504   EXPECT_EQ("isn't approximately 2", DescribeNegation(m1));
3505
3506   Matcher<float> m2 = FloatEq(0.5f);
3507   EXPECT_EQ("is approximately 0.5", Describe(m2));
3508   EXPECT_EQ("isn't approximately 0.5", DescribeNegation(m2));
3509
3510   Matcher<float> m3 = FloatEq(nan1_);
3511   EXPECT_EQ("never matches", Describe(m3));
3512   EXPECT_EQ("is anything", DescribeNegation(m3));
3513 }
3514
3515 TEST_F(FloatTest, NanSensitiveFloatEqCanDescribeSelf) {
3516   Matcher<float> m1 = NanSensitiveFloatEq(2.0f);
3517   EXPECT_EQ("is approximately 2", Describe(m1));
3518   EXPECT_EQ("isn't approximately 2", DescribeNegation(m1));
3519
3520   Matcher<float> m2 = NanSensitiveFloatEq(0.5f);
3521   EXPECT_EQ("is approximately 0.5", Describe(m2));
3522   EXPECT_EQ("isn't approximately 0.5", DescribeNegation(m2));
3523
3524   Matcher<float> m3 = NanSensitiveFloatEq(nan1_);
3525   EXPECT_EQ("is NaN", Describe(m3));
3526   EXPECT_EQ("isn't NaN", DescribeNegation(m3));
3527 }
3528
3529 // Instantiate FloatingPointTest for testing floats with a user-specified
3530 // max absolute error.
3531 typedef FloatingPointNearTest<float> FloatNearTest;
3532
3533 TEST_F(FloatNearTest, FloatNearMatches) {
3534   TestNearMatches(&FloatNear);
3535 }
3536
3537 TEST_F(FloatNearTest, NanSensitiveFloatNearApproximatelyMatchesFloats) {
3538   TestNearMatches(&NanSensitiveFloatNear);
3539 }
3540
3541 TEST_F(FloatNearTest, FloatNearCanDescribeSelf) {
3542   Matcher<float> m1 = FloatNear(2.0f, 0.5f);
3543   EXPECT_EQ("is approximately 2 (absolute error <= 0.5)", Describe(m1));
3544   EXPECT_EQ(
3545       "isn't approximately 2 (absolute error > 0.5)", DescribeNegation(m1));
3546
3547   Matcher<float> m2 = FloatNear(0.5f, 0.5f);
3548   EXPECT_EQ("is approximately 0.5 (absolute error <= 0.5)", Describe(m2));
3549   EXPECT_EQ(
3550       "isn't approximately 0.5 (absolute error > 0.5)", DescribeNegation(m2));
3551
3552   Matcher<float> m3 = FloatNear(nan1_, 0.0);
3553   EXPECT_EQ("never matches", Describe(m3));
3554   EXPECT_EQ("is anything", DescribeNegation(m3));
3555 }
3556
3557 TEST_F(FloatNearTest, NanSensitiveFloatNearCanDescribeSelf) {
3558   Matcher<float> m1 = NanSensitiveFloatNear(2.0f, 0.5f);
3559   EXPECT_EQ("is approximately 2 (absolute error <= 0.5)", Describe(m1));
3560   EXPECT_EQ(
3561       "isn't approximately 2 (absolute error > 0.5)", DescribeNegation(m1));
3562
3563   Matcher<float> m2 = NanSensitiveFloatNear(0.5f, 0.5f);
3564   EXPECT_EQ("is approximately 0.5 (absolute error <= 0.5)", Describe(m2));
3565   EXPECT_EQ(
3566       "isn't approximately 0.5 (absolute error > 0.5)", DescribeNegation(m2));
3567
3568   Matcher<float> m3 = NanSensitiveFloatNear(nan1_, 0.1f);
3569   EXPECT_EQ("is NaN", Describe(m3));
3570   EXPECT_EQ("isn't NaN", DescribeNegation(m3));
3571 }
3572
3573 TEST_F(FloatNearTest, FloatNearCannotMatchNaN) {
3574   // FloatNear never matches NaN.
3575   Matcher<float> m = FloatNear(ParentType::nan1_, 0.1f);
3576   EXPECT_FALSE(m.Matches(nan1_));
3577   EXPECT_FALSE(m.Matches(nan2_));
3578   EXPECT_FALSE(m.Matches(1.0));
3579 }
3580
3581 TEST_F(FloatNearTest, NanSensitiveFloatNearCanMatchNaN) {
3582   // NanSensitiveFloatNear will match NaN.
3583   Matcher<float> m = NanSensitiveFloatNear(nan1_, 0.1f);
3584   EXPECT_TRUE(m.Matches(nan1_));
3585   EXPECT_TRUE(m.Matches(nan2_));
3586   EXPECT_FALSE(m.Matches(1.0));
3587 }
3588
3589 // Instantiate FloatingPointTest for testing doubles.
3590 typedef FloatingPointTest<double> DoubleTest;
3591
3592 TEST_F(DoubleTest, DoubleEqApproximatelyMatchesDoubles) {
3593   TestMatches(&DoubleEq);
3594 }
3595
3596 TEST_F(DoubleTest, NanSensitiveDoubleEqApproximatelyMatchesDoubles) {
3597   TestMatches(&NanSensitiveDoubleEq);
3598 }
3599
3600 TEST_F(DoubleTest, DoubleEqCannotMatchNaN) {
3601   // DoubleEq never matches NaN.
3602   Matcher<double> m = DoubleEq(nan1_);
3603   EXPECT_FALSE(m.Matches(nan1_));
3604   EXPECT_FALSE(m.Matches(nan2_));
3605   EXPECT_FALSE(m.Matches(1.0));
3606 }
3607
3608 TEST_F(DoubleTest, NanSensitiveDoubleEqCanMatchNaN) {
3609   // NanSensitiveDoubleEq will match NaN.
3610   Matcher<double> m = NanSensitiveDoubleEq(nan1_);
3611   EXPECT_TRUE(m.Matches(nan1_));
3612   EXPECT_TRUE(m.Matches(nan2_));
3613   EXPECT_FALSE(m.Matches(1.0));
3614 }
3615
3616 TEST_F(DoubleTest, DoubleEqCanDescribeSelf) {
3617   Matcher<double> m1 = DoubleEq(2.0);
3618   EXPECT_EQ("is approximately 2", Describe(m1));
3619   EXPECT_EQ("isn't approximately 2", DescribeNegation(m1));
3620
3621   Matcher<double> m2 = DoubleEq(0.5);
3622   EXPECT_EQ("is approximately 0.5", Describe(m2));
3623   EXPECT_EQ("isn't approximately 0.5", DescribeNegation(m2));
3624
3625   Matcher<double> m3 = DoubleEq(nan1_);
3626   EXPECT_EQ("never matches", Describe(m3));
3627   EXPECT_EQ("is anything", DescribeNegation(m3));
3628 }
3629
3630 TEST_F(DoubleTest, NanSensitiveDoubleEqCanDescribeSelf) {
3631   Matcher<double> m1 = NanSensitiveDoubleEq(2.0);
3632   EXPECT_EQ("is approximately 2", Describe(m1));
3633   EXPECT_EQ("isn't approximately 2", DescribeNegation(m1));
3634
3635   Matcher<double> m2 = NanSensitiveDoubleEq(0.5);
3636   EXPECT_EQ("is approximately 0.5", Describe(m2));
3637   EXPECT_EQ("isn't approximately 0.5", DescribeNegation(m2));
3638
3639   Matcher<double> m3 = NanSensitiveDoubleEq(nan1_);
3640   EXPECT_EQ("is NaN", Describe(m3));
3641   EXPECT_EQ("isn't NaN", DescribeNegation(m3));
3642 }
3643
3644 // Instantiate FloatingPointTest for testing floats with a user-specified
3645 // max absolute error.
3646 typedef FloatingPointNearTest<double> DoubleNearTest;
3647
3648 TEST_F(DoubleNearTest, DoubleNearMatches) {
3649   TestNearMatches(&DoubleNear);
3650 }
3651
3652 TEST_F(DoubleNearTest, NanSensitiveDoubleNearApproximatelyMatchesDoubles) {
3653   TestNearMatches(&NanSensitiveDoubleNear);
3654 }
3655
3656 TEST_F(DoubleNearTest, DoubleNearCanDescribeSelf) {
3657   Matcher<double> m1 = DoubleNear(2.0, 0.5);
3658   EXPECT_EQ("is approximately 2 (absolute error <= 0.5)", Describe(m1));
3659   EXPECT_EQ(
3660       "isn't approximately 2 (absolute error > 0.5)", DescribeNegation(m1));
3661
3662   Matcher<double> m2 = DoubleNear(0.5, 0.5);
3663   EXPECT_EQ("is approximately 0.5 (absolute error <= 0.5)", Describe(m2));
3664   EXPECT_EQ(
3665       "isn't approximately 0.5 (absolute error > 0.5)", DescribeNegation(m2));
3666
3667   Matcher<double> m3 = DoubleNear(nan1_, 0.0);
3668   EXPECT_EQ("never matches", Describe(m3));
3669   EXPECT_EQ("is anything", DescribeNegation(m3));
3670 }
3671
3672 TEST_F(DoubleNearTest, ExplainsResultWhenMatchFails) {
3673   EXPECT_EQ("", Explain(DoubleNear(2.0, 0.1), 2.05));
3674   EXPECT_EQ("which is 0.2 from 2", Explain(DoubleNear(2.0, 0.1), 2.2));
3675   EXPECT_EQ("which is -0.3 from 2", Explain(DoubleNear(2.0, 0.1), 1.7));
3676
3677   const std::string explanation =
3678       Explain(DoubleNear(2.1, 1e-10), 2.1 + 1.2e-10);
3679   // Different C++ implementations may print floating-point numbers
3680   // slightly differently.
3681   EXPECT_TRUE(explanation == "which is 1.2e-10 from 2.1" ||  // GCC
3682               explanation == "which is 1.2e-010 from 2.1")   // MSVC
3683       << " where explanation is \"" << explanation << "\".";
3684 }
3685
3686 TEST_F(DoubleNearTest, NanSensitiveDoubleNearCanDescribeSelf) {
3687   Matcher<double> m1 = NanSensitiveDoubleNear(2.0, 0.5);
3688   EXPECT_EQ("is approximately 2 (absolute error <= 0.5)", Describe(m1));
3689   EXPECT_EQ(
3690       "isn't approximately 2 (absolute error > 0.5)", DescribeNegation(m1));
3691
3692   Matcher<double> m2 = NanSensitiveDoubleNear(0.5, 0.5);
3693   EXPECT_EQ("is approximately 0.5 (absolute error <= 0.5)", Describe(m2));
3694   EXPECT_EQ(
3695       "isn't approximately 0.5 (absolute error > 0.5)", DescribeNegation(m2));
3696
3697   Matcher<double> m3 = NanSensitiveDoubleNear(nan1_, 0.1);
3698   EXPECT_EQ("is NaN", Describe(m3));
3699   EXPECT_EQ("isn't NaN", DescribeNegation(m3));
3700 }
3701
3702 TEST_F(DoubleNearTest, DoubleNearCannotMatchNaN) {
3703   // DoubleNear never matches NaN.
3704   Matcher<double> m = DoubleNear(ParentType::nan1_, 0.1);
3705   EXPECT_FALSE(m.Matches(nan1_));
3706   EXPECT_FALSE(m.Matches(nan2_));
3707   EXPECT_FALSE(m.Matches(1.0));
3708 }
3709
3710 TEST_F(DoubleNearTest, NanSensitiveDoubleNearCanMatchNaN) {
3711   // NanSensitiveDoubleNear will match NaN.
3712   Matcher<double> m = NanSensitiveDoubleNear(nan1_, 0.1);
3713   EXPECT_TRUE(m.Matches(nan1_));
3714   EXPECT_TRUE(m.Matches(nan2_));
3715   EXPECT_FALSE(m.Matches(1.0));
3716 }
3717
3718 TEST(PointeeTest, RawPointer) {
3719   const Matcher<int*> m = Pointee(Ge(0));
3720
3721   int n = 1;
3722   EXPECT_TRUE(m.Matches(&n));
3723   n = -1;
3724   EXPECT_FALSE(m.Matches(&n));
3725   EXPECT_FALSE(m.Matches(nullptr));
3726 }
3727
3728 TEST(PointeeTest, RawPointerToConst) {
3729   const Matcher<const double*> m = Pointee(Ge(0));
3730
3731   double x = 1;
3732   EXPECT_TRUE(m.Matches(&x));
3733   x = -1;
3734   EXPECT_FALSE(m.Matches(&x));
3735   EXPECT_FALSE(m.Matches(nullptr));
3736 }
3737
3738 TEST(PointeeTest, ReferenceToConstRawPointer) {
3739   const Matcher<int* const &> m = Pointee(Ge(0));
3740
3741   int n = 1;
3742   EXPECT_TRUE(m.Matches(&n));
3743   n = -1;
3744   EXPECT_FALSE(m.Matches(&n));
3745   EXPECT_FALSE(m.Matches(nullptr));
3746 }
3747
3748 TEST(PointeeTest, ReferenceToNonConstRawPointer) {
3749   const Matcher<double* &> m = Pointee(Ge(0));
3750
3751   double x = 1.0;
3752   double* p = &x;
3753   EXPECT_TRUE(m.Matches(p));
3754   x = -1;
3755   EXPECT_FALSE(m.Matches(p));
3756   p = nullptr;
3757   EXPECT_FALSE(m.Matches(p));
3758 }
3759
3760 TEST(PointeeTest, SmartPointer) {
3761   const Matcher<std::unique_ptr<int>> m = Pointee(Ge(0));
3762
3763   std::unique_ptr<int> n(new int(1));
3764   EXPECT_TRUE(m.Matches(n));
3765 }
3766
3767 TEST(PointeeTest, SmartPointerToConst) {
3768   const Matcher<std::unique_ptr<const int>> m = Pointee(Ge(0));
3769
3770   // There's no implicit conversion from unique_ptr<int> to const
3771   // unique_ptr<const int>, so we must pass a unique_ptr<const int> into the
3772   // matcher.
3773   std::unique_ptr<const int> n(new int(1));
3774   EXPECT_TRUE(m.Matches(n));
3775 }
3776
3777 TEST(PointerTest, RawPointer) {
3778   int n = 1;
3779   const Matcher<int*> m = Pointer(Eq(&n));
3780
3781   EXPECT_TRUE(m.Matches(&n));
3782
3783   int* p = nullptr;
3784   EXPECT_FALSE(m.Matches(p));
3785   EXPECT_FALSE(m.Matches(nullptr));
3786 }
3787
3788 TEST(PointerTest, RawPointerToConst) {
3789   int n = 1;
3790   const Matcher<const int*> m = Pointer(Eq(&n));
3791
3792   EXPECT_TRUE(m.Matches(&n));
3793
3794   int* p = nullptr;
3795   EXPECT_FALSE(m.Matches(p));
3796   EXPECT_FALSE(m.Matches(nullptr));
3797 }
3798
3799 TEST(PointerTest, SmartPointer) {
3800   std::unique_ptr<int> n(new int(10));
3801   int* raw_n = n.get();
3802   const Matcher<std::unique_ptr<int>> m = Pointer(Eq(raw_n));
3803
3804   EXPECT_TRUE(m.Matches(n));
3805 }
3806
3807 TEST(PointerTest, SmartPointerToConst) {
3808   std::unique_ptr<const int> n(new int(10));
3809   const int* raw_n = n.get();
3810   const Matcher<std::unique_ptr<const int>> m = Pointer(Eq(raw_n));
3811
3812   // There's no implicit conversion from unique_ptr<int> to const
3813   // unique_ptr<const int>, so we must pass a unique_ptr<const int> into the
3814   // matcher.
3815   std::unique_ptr<const int> p(new int(10));
3816   EXPECT_FALSE(m.Matches(p));
3817 }
3818
3819 TEST(AddressTest, NonConst) {
3820   int n = 1;
3821   const Matcher<int> m = Address(Eq(&n));
3822
3823   EXPECT_TRUE(m.Matches(n));
3824
3825   int other = 5;
3826
3827   EXPECT_FALSE(m.Matches(other));
3828
3829   int& n_ref = n;
3830
3831   EXPECT_TRUE(m.Matches(n_ref));
3832 }
3833
3834 TEST(AddressTest, Const) {
3835   const int n = 1;
3836   const Matcher<int> m = Address(Eq(&n));
3837
3838   EXPECT_TRUE(m.Matches(n));
3839
3840   int other = 5;
3841
3842   EXPECT_FALSE(m.Matches(other));
3843 }
3844
3845 TEST(AddressTest, MatcherDoesntCopy) {
3846   std::unique_ptr<int> n(new int(1));
3847   const Matcher<std::unique_ptr<int>> m = Address(Eq(&n));
3848
3849   EXPECT_TRUE(m.Matches(n));
3850 }
3851
3852 TEST(AddressTest, Describe) {
3853   Matcher<int> matcher = Address(_);
3854   EXPECT_EQ("has address that is anything", Describe(matcher));
3855   EXPECT_EQ("does not have address that is anything",
3856             DescribeNegation(matcher));
3857 }
3858
3859 MATCHER_P(FieldIIs, inner_matcher, "") {
3860   return ExplainMatchResult(inner_matcher, arg.i, result_listener);
3861 }
3862
3863 #if GTEST_HAS_RTTI
3864 TEST(WhenDynamicCastToTest, SameType) {
3865   Derived derived;
3866   derived.i = 4;
3867
3868   // Right type. A pointer is passed down.
3869   Base* as_base_ptr = &derived;
3870   EXPECT_THAT(as_base_ptr, WhenDynamicCastTo<Derived*>(Not(IsNull())));
3871   EXPECT_THAT(as_base_ptr, WhenDynamicCastTo<Derived*>(Pointee(FieldIIs(4))));
3872   EXPECT_THAT(as_base_ptr,
3873               Not(WhenDynamicCastTo<Derived*>(Pointee(FieldIIs(5)))));
3874 }
3875
3876 TEST(WhenDynamicCastToTest, WrongTypes) {
3877   Base base;
3878   Derived derived;
3879   OtherDerived other_derived;
3880
3881   // Wrong types. NULL is passed.
3882   EXPECT_THAT(&base, Not(WhenDynamicCastTo<Derived*>(Pointee(_))));
3883   EXPECT_THAT(&base, WhenDynamicCastTo<Derived*>(IsNull()));
3884   Base* as_base_ptr = &derived;
3885   EXPECT_THAT(as_base_ptr, Not(WhenDynamicCastTo<OtherDerived*>(Pointee(_))));
3886   EXPECT_THAT(as_base_ptr, WhenDynamicCastTo<OtherDerived*>(IsNull()));
3887   as_base_ptr = &other_derived;
3888   EXPECT_THAT(as_base_ptr, Not(WhenDynamicCastTo<Derived*>(Pointee(_))));
3889   EXPECT_THAT(as_base_ptr, WhenDynamicCastTo<Derived*>(IsNull()));
3890 }
3891
3892 TEST(WhenDynamicCastToTest, AlreadyNull) {
3893   // Already NULL.
3894   Base* as_base_ptr = nullptr;
3895   EXPECT_THAT(as_base_ptr, WhenDynamicCastTo<Derived*>(IsNull()));
3896 }
3897
3898 struct AmbiguousCastTypes {
3899   class VirtualDerived : public virtual Base {};
3900   class DerivedSub1 : public VirtualDerived {};
3901   class DerivedSub2 : public VirtualDerived {};
3902   class ManyDerivedInHierarchy : public DerivedSub1, public DerivedSub2 {};
3903 };
3904
3905 TEST(WhenDynamicCastToTest, AmbiguousCast) {
3906   AmbiguousCastTypes::DerivedSub1 sub1;
3907   AmbiguousCastTypes::ManyDerivedInHierarchy many_derived;
3908   // Multiply derived from Base. dynamic_cast<> returns NULL.
3909   Base* as_base_ptr =
3910       static_cast<AmbiguousCastTypes::DerivedSub1*>(&many_derived);
3911   EXPECT_THAT(as_base_ptr,
3912               WhenDynamicCastTo<AmbiguousCastTypes::VirtualDerived*>(IsNull()));
3913   as_base_ptr = &sub1;
3914   EXPECT_THAT(
3915       as_base_ptr,
3916       WhenDynamicCastTo<AmbiguousCastTypes::VirtualDerived*>(Not(IsNull())));
3917 }
3918
3919 TEST(WhenDynamicCastToTest, Describe) {
3920   Matcher<Base*> matcher = WhenDynamicCastTo<Derived*>(Pointee(_));
3921   const std::string prefix =
3922       "when dynamic_cast to " + internal::GetTypeName<Derived*>() + ", ";
3923   EXPECT_EQ(prefix + "points to a value that is anything", Describe(matcher));
3924   EXPECT_EQ(prefix + "does not point to a value that is anything",
3925             DescribeNegation(matcher));
3926 }
3927
3928 TEST(WhenDynamicCastToTest, Explain) {
3929   Matcher<Base*> matcher = WhenDynamicCastTo<Derived*>(Pointee(_));
3930   Base* null = nullptr;
3931   EXPECT_THAT(Explain(matcher, null), HasSubstr("NULL"));
3932   Derived derived;
3933   EXPECT_TRUE(matcher.Matches(&derived));
3934   EXPECT_THAT(Explain(matcher, &derived), HasSubstr("which points to "));
3935
3936   // With references, the matcher itself can fail. Test for that one.
3937   Matcher<const Base&> ref_matcher = WhenDynamicCastTo<const OtherDerived&>(_);
3938   EXPECT_THAT(Explain(ref_matcher, derived),
3939               HasSubstr("which cannot be dynamic_cast"));
3940 }
3941
3942 TEST(WhenDynamicCastToTest, GoodReference) {
3943   Derived derived;
3944   derived.i = 4;
3945   Base& as_base_ref = derived;
3946   EXPECT_THAT(as_base_ref, WhenDynamicCastTo<const Derived&>(FieldIIs(4)));
3947   EXPECT_THAT(as_base_ref, WhenDynamicCastTo<const Derived&>(Not(FieldIIs(5))));
3948 }
3949
3950 TEST(WhenDynamicCastToTest, BadReference) {
3951   Derived derived;
3952   Base& as_base_ref = derived;
3953   EXPECT_THAT(as_base_ref, Not(WhenDynamicCastTo<const OtherDerived&>(_)));
3954 }
3955 #endif  // GTEST_HAS_RTTI
3956
3957 // Minimal const-propagating pointer.
3958 template <typename T>
3959 class ConstPropagatingPtr {
3960  public:
3961   typedef T element_type;
3962
3963   ConstPropagatingPtr() : val_() {}
3964   explicit ConstPropagatingPtr(T* t) : val_(t) {}
3965   ConstPropagatingPtr(const ConstPropagatingPtr& other) : val_(other.val_) {}
3966
3967   T* get() { return val_; }
3968   T& operator*() { return *val_; }
3969   // Most smart pointers return non-const T* and T& from the next methods.
3970   const T* get() const { return val_; }
3971   const T& operator*() const { return *val_; }
3972
3973  private:
3974   T* val_;
3975 };
3976
3977 TEST(PointeeTest, WorksWithConstPropagatingPointers) {
3978   const Matcher< ConstPropagatingPtr<int> > m = Pointee(Lt(5));
3979   int three = 3;
3980   const ConstPropagatingPtr<int> co(&three);
3981   ConstPropagatingPtr<int> o(&three);
3982   EXPECT_TRUE(m.Matches(o));
3983   EXPECT_TRUE(m.Matches(co));
3984   *o = 6;
3985   EXPECT_FALSE(m.Matches(o));
3986   EXPECT_FALSE(m.Matches(ConstPropagatingPtr<int>()));
3987 }
3988
3989 TEST(PointeeTest, NeverMatchesNull) {
3990   const Matcher<const char*> m = Pointee(_);
3991   EXPECT_FALSE(m.Matches(nullptr));
3992 }
3993
3994 // Tests that we can write Pointee(value) instead of Pointee(Eq(value)).
3995 TEST(PointeeTest, MatchesAgainstAValue) {
3996   const Matcher<int*> m = Pointee(5);
3997
3998   int n = 5;
3999   EXPECT_TRUE(m.Matches(&n));
4000   n = -1;
4001   EXPECT_FALSE(m.Matches(&n));
4002   EXPECT_FALSE(m.Matches(nullptr));
4003 }
4004
4005 TEST(PointeeTest, CanDescribeSelf) {
4006   const Matcher<int*> m = Pointee(Gt(3));
4007   EXPECT_EQ("points to a value that is > 3", Describe(m));
4008   EXPECT_EQ("does not point to a value that is > 3",
4009             DescribeNegation(m));
4010 }
4011
4012 TEST(PointeeTest, CanExplainMatchResult) {
4013   const Matcher<const std::string*> m = Pointee(StartsWith("Hi"));
4014
4015   EXPECT_EQ("", Explain(m, static_cast<const std::string*>(nullptr)));
4016
4017   const Matcher<long*> m2 = Pointee(GreaterThan(1));  // NOLINT
4018   long n = 3;  // NOLINT
4019   EXPECT_EQ("which points to 3" + OfType("long") + ", which is 2 more than 1",
4020             Explain(m2, &n));
4021 }
4022
4023 TEST(PointeeTest, AlwaysExplainsPointee) {
4024   const Matcher<int*> m = Pointee(0);
4025   int n = 42;
4026   EXPECT_EQ("which points to 42" + OfType("int"), Explain(m, &n));
4027 }
4028
4029 // An uncopyable class.
4030 class Uncopyable {
4031  public:
4032   Uncopyable() : value_(-1) {}
4033   explicit Uncopyable(int a_value) : value_(a_value) {}
4034
4035   int value() const { return value_; }
4036   void set_value(int i) { value_ = i; }
4037
4038  private:
4039   int value_;
4040   GTEST_DISALLOW_COPY_AND_ASSIGN_(Uncopyable);
4041 };
4042
4043 // Returns true if and only if x.value() is positive.
4044 bool ValueIsPositive(const Uncopyable& x) { return x.value() > 0; }
4045
4046 MATCHER_P(UncopyableIs, inner_matcher, "") {
4047   return ExplainMatchResult(inner_matcher, arg.value(), result_listener);
4048 }
4049
4050 // A user-defined struct for testing Field().
4051 struct AStruct {
4052   AStruct() : x(0), y(1.0), z(5), p(nullptr) {}
4053   AStruct(const AStruct& rhs)
4054       : x(rhs.x), y(rhs.y), z(rhs.z.value()), p(rhs.p) {}
4055
4056   int x;           // A non-const field.
4057   const double y;  // A const field.
4058   Uncopyable z;    // An uncopyable field.
4059   const char* p;   // A pointer field.
4060 };
4061
4062 // A derived struct for testing Field().
4063 struct DerivedStruct : public AStruct {
4064   char ch;
4065 };
4066
4067 // Tests that Field(&Foo::field, ...) works when field is non-const.
4068 TEST(FieldTest, WorksForNonConstField) {
4069   Matcher<AStruct> m = Field(&AStruct::x, Ge(0));
4070   Matcher<AStruct> m_with_name = Field("x", &AStruct::x, Ge(0));
4071
4072   AStruct a;
4073   EXPECT_TRUE(m.Matches(a));
4074   EXPECT_TRUE(m_with_name.Matches(a));
4075   a.x = -1;
4076   EXPECT_FALSE(m.Matches(a));
4077   EXPECT_FALSE(m_with_name.Matches(a));
4078 }
4079
4080 // Tests that Field(&Foo::field, ...) works when field is const.
4081 TEST(FieldTest, WorksForConstField) {
4082   AStruct a;
4083
4084   Matcher<AStruct> m = Field(&AStruct::y, Ge(0.0));
4085   Matcher<AStruct> m_with_name = Field("y", &AStruct::y, Ge(0.0));
4086   EXPECT_TRUE(m.Matches(a));
4087   EXPECT_TRUE(m_with_name.Matches(a));
4088   m = Field(&AStruct::y, Le(0.0));
4089   m_with_name = Field("y", &AStruct::y, Le(0.0));
4090   EXPECT_FALSE(m.Matches(a));
4091   EXPECT_FALSE(m_with_name.Matches(a));
4092 }
4093
4094 // Tests that Field(&Foo::field, ...) works when field is not copyable.
4095 TEST(FieldTest, WorksForUncopyableField) {
4096   AStruct a;
4097
4098   Matcher<AStruct> m = Field(&AStruct::z, Truly(ValueIsPositive));
4099   EXPECT_TRUE(m.Matches(a));
4100   m = Field(&AStruct::z, Not(Truly(ValueIsPositive)));
4101   EXPECT_FALSE(m.Matches(a));
4102 }
4103
4104 // Tests that Field(&Foo::field, ...) works when field is a pointer.
4105 TEST(FieldTest, WorksForPointerField) {
4106   // Matching against NULL.
4107   Matcher<AStruct> m = Field(&AStruct::p, static_cast<const char*>(nullptr));
4108   AStruct a;
4109   EXPECT_TRUE(m.Matches(a));
4110   a.p = "hi";
4111   EXPECT_FALSE(m.Matches(a));
4112
4113   // Matching a pointer that is not NULL.
4114   m = Field(&AStruct::p, StartsWith("hi"));
4115   a.p = "hill";
4116   EXPECT_TRUE(m.Matches(a));
4117   a.p = "hole";
4118   EXPECT_FALSE(m.Matches(a));
4119 }
4120
4121 // Tests that Field() works when the object is passed by reference.
4122 TEST(FieldTest, WorksForByRefArgument) {
4123   Matcher<const AStruct&> m = Field(&AStruct::x, Ge(0));
4124
4125   AStruct a;
4126   EXPECT_TRUE(m.Matches(a));
4127   a.x = -1;
4128   EXPECT_FALSE(m.Matches(a));
4129 }
4130
4131 // Tests that Field(&Foo::field, ...) works when the argument's type
4132 // is a sub-type of Foo.
4133 TEST(FieldTest, WorksForArgumentOfSubType) {
4134   // Note that the matcher expects DerivedStruct but we say AStruct
4135   // inside Field().
4136   Matcher<const DerivedStruct&> m = Field(&AStruct::x, Ge(0));
4137
4138   DerivedStruct d;
4139   EXPECT_TRUE(m.Matches(d));
4140   d.x = -1;
4141   EXPECT_FALSE(m.Matches(d));
4142 }
4143
4144 // Tests that Field(&Foo::field, m) works when field's type and m's
4145 // argument type are compatible but not the same.
4146 TEST(FieldTest, WorksForCompatibleMatcherType) {
4147   // The field is an int, but the inner matcher expects a signed char.
4148   Matcher<const AStruct&> m = Field(&AStruct::x,
4149                                     Matcher<signed char>(Ge(0)));
4150
4151   AStruct a;
4152   EXPECT_TRUE(m.Matches(a));
4153   a.x = -1;
4154   EXPECT_FALSE(m.Matches(a));
4155 }
4156
4157 // Tests that Field() can describe itself.
4158 TEST(FieldTest, CanDescribeSelf) {
4159   Matcher<const AStruct&> m = Field(&AStruct::x, Ge(0));
4160
4161   EXPECT_EQ("is an object whose given field is >= 0", Describe(m));
4162   EXPECT_EQ("is an object whose given field isn't >= 0", DescribeNegation(m));
4163 }
4164
4165 TEST(FieldTest, CanDescribeSelfWithFieldName) {
4166   Matcher<const AStruct&> m = Field("field_name", &AStruct::x, Ge(0));
4167
4168   EXPECT_EQ("is an object whose field `field_name` is >= 0", Describe(m));
4169   EXPECT_EQ("is an object whose field `field_name` isn't >= 0",
4170             DescribeNegation(m));
4171 }
4172
4173 // Tests that Field() can explain the match result.
4174 TEST(FieldTest, CanExplainMatchResult) {
4175   Matcher<const AStruct&> m = Field(&AStruct::x, Ge(0));
4176
4177   AStruct a;
4178   a.x = 1;
4179   EXPECT_EQ("whose given field is 1" + OfType("int"), Explain(m, a));
4180
4181   m = Field(&AStruct::x, GreaterThan(0));
4182   EXPECT_EQ(
4183       "whose given field is 1" + OfType("int") + ", which is 1 more than 0",
4184       Explain(m, a));
4185 }
4186
4187 TEST(FieldTest, CanExplainMatchResultWithFieldName) {
4188   Matcher<const AStruct&> m = Field("field_name", &AStruct::x, Ge(0));
4189
4190   AStruct a;
4191   a.x = 1;
4192   EXPECT_EQ("whose field `field_name` is 1" + OfType("int"), Explain(m, a));
4193
4194   m = Field("field_name", &AStruct::x, GreaterThan(0));
4195   EXPECT_EQ("whose field `field_name` is 1" + OfType("int") +
4196                 ", which is 1 more than 0",
4197             Explain(m, a));
4198 }
4199
4200 // Tests that Field() works when the argument is a pointer to const.
4201 TEST(FieldForPointerTest, WorksForPointerToConst) {
4202   Matcher<const AStruct*> m = Field(&AStruct::x, Ge(0));
4203
4204   AStruct a;
4205   EXPECT_TRUE(m.Matches(&a));
4206   a.x = -1;
4207   EXPECT_FALSE(m.Matches(&a));
4208 }
4209
4210 // Tests that Field() works when the argument is a pointer to non-const.
4211 TEST(FieldForPointerTest, WorksForPointerToNonConst) {
4212   Matcher<AStruct*> m = Field(&AStruct::x, Ge(0));
4213
4214   AStruct a;
4215   EXPECT_TRUE(m.Matches(&a));
4216   a.x = -1;
4217   EXPECT_FALSE(m.Matches(&a));
4218 }
4219
4220 // Tests that Field() works when the argument is a reference to a const pointer.
4221 TEST(FieldForPointerTest, WorksForReferenceToConstPointer) {
4222   Matcher<AStruct* const&> m = Field(&AStruct::x, Ge(0));
4223
4224   AStruct a;
4225   EXPECT_TRUE(m.Matches(&a));
4226   a.x = -1;
4227   EXPECT_FALSE(m.Matches(&a));
4228 }
4229
4230 // Tests that Field() does not match the NULL pointer.
4231 TEST(FieldForPointerTest, DoesNotMatchNull) {
4232   Matcher<const AStruct*> m = Field(&AStruct::x, _);
4233   EXPECT_FALSE(m.Matches(nullptr));
4234 }
4235
4236 // Tests that Field(&Foo::field, ...) works when the argument's type
4237 // is a sub-type of const Foo*.
4238 TEST(FieldForPointerTest, WorksForArgumentOfSubType) {
4239   // Note that the matcher expects DerivedStruct but we say AStruct
4240   // inside Field().
4241   Matcher<DerivedStruct*> m = Field(&AStruct::x, Ge(0));
4242
4243   DerivedStruct d;
4244   EXPECT_TRUE(m.Matches(&d));
4245   d.x = -1;
4246   EXPECT_FALSE(m.Matches(&d));
4247 }
4248
4249 // Tests that Field() can describe itself when used to match a pointer.
4250 TEST(FieldForPointerTest, CanDescribeSelf) {
4251   Matcher<const AStruct*> m = Field(&AStruct::x, Ge(0));
4252
4253   EXPECT_EQ("is an object whose given field is >= 0", Describe(m));
4254   EXPECT_EQ("is an object whose given field isn't >= 0", DescribeNegation(m));
4255 }
4256
4257 TEST(FieldForPointerTest, CanDescribeSelfWithFieldName) {
4258   Matcher<const AStruct*> m = Field("field_name", &AStruct::x, Ge(0));
4259
4260   EXPECT_EQ("is an object whose field `field_name` is >= 0", Describe(m));
4261   EXPECT_EQ("is an object whose field `field_name` isn't >= 0",
4262             DescribeNegation(m));
4263 }
4264
4265 // Tests that Field() can explain the result of matching a pointer.
4266 TEST(FieldForPointerTest, CanExplainMatchResult) {
4267   Matcher<const AStruct*> m = Field(&AStruct::x, Ge(0));
4268
4269   AStruct a;
4270   a.x = 1;
4271   EXPECT_EQ("", Explain(m, static_cast<const AStruct*>(nullptr)));
4272   EXPECT_EQ("which points to an object whose given field is 1" + OfType("int"),
4273             Explain(m, &a));
4274
4275   m = Field(&AStruct::x, GreaterThan(0));
4276   EXPECT_EQ("which points to an object whose given field is 1" + OfType("int") +
4277             ", which is 1 more than 0", Explain(m, &a));
4278 }
4279
4280 TEST(FieldForPointerTest, CanExplainMatchResultWithFieldName) {
4281   Matcher<const AStruct*> m = Field("field_name", &AStruct::x, Ge(0));
4282
4283   AStruct a;
4284   a.x = 1;
4285   EXPECT_EQ("", Explain(m, static_cast<const AStruct*>(nullptr)));
4286   EXPECT_EQ(
4287       "which points to an object whose field `field_name` is 1" + OfType("int"),
4288       Explain(m, &a));
4289
4290   m = Field("field_name", &AStruct::x, GreaterThan(0));
4291   EXPECT_EQ("which points to an object whose field `field_name` is 1" +
4292                 OfType("int") + ", which is 1 more than 0",
4293             Explain(m, &a));
4294 }
4295
4296 // A user-defined class for testing Property().
4297 class AClass {
4298  public:
4299   AClass() : n_(0) {}
4300
4301   // A getter that returns a non-reference.
4302   int n() const { return n_; }
4303
4304   void set_n(int new_n) { n_ = new_n; }
4305
4306   // A getter that returns a reference to const.
4307   const std::string& s() const { return s_; }
4308
4309   const std::string& s_ref() const & { return s_; }
4310
4311   void set_s(const std::string& new_s) { s_ = new_s; }
4312
4313   // A getter that returns a reference to non-const.
4314   double& x() const { return x_; }
4315
4316  private:
4317   int n_;
4318   std::string s_;
4319
4320   static double x_;
4321 };
4322
4323 double AClass::x_ = 0.0;
4324
4325 // A derived class for testing Property().
4326 class DerivedClass : public AClass {
4327  public:
4328   int k() const { return k_; }
4329  private:
4330   int k_;
4331 };
4332
4333 // Tests that Property(&Foo::property, ...) works when property()
4334 // returns a non-reference.
4335 TEST(PropertyTest, WorksForNonReferenceProperty) {
4336   Matcher<const AClass&> m = Property(&AClass::n, Ge(0));
4337   Matcher<const AClass&> m_with_name = Property("n", &AClass::n, Ge(0));
4338
4339   AClass a;
4340   a.set_n(1);
4341   EXPECT_TRUE(m.Matches(a));
4342   EXPECT_TRUE(m_with_name.Matches(a));
4343
4344   a.set_n(-1);
4345   EXPECT_FALSE(m.Matches(a));
4346   EXPECT_FALSE(m_with_name.Matches(a));
4347 }
4348
4349 // Tests that Property(&Foo::property, ...) works when property()
4350 // returns a reference to const.
4351 TEST(PropertyTest, WorksForReferenceToConstProperty) {
4352   Matcher<const AClass&> m = Property(&AClass::s, StartsWith("hi"));
4353   Matcher<const AClass&> m_with_name =
4354       Property("s", &AClass::s, StartsWith("hi"));
4355
4356   AClass a;
4357   a.set_s("hill");
4358   EXPECT_TRUE(m.Matches(a));
4359   EXPECT_TRUE(m_with_name.Matches(a));
4360
4361   a.set_s("hole");
4362   EXPECT_FALSE(m.Matches(a));
4363   EXPECT_FALSE(m_with_name.Matches(a));
4364 }
4365
4366 // Tests that Property(&Foo::property, ...) works when property() is
4367 // ref-qualified.
4368 TEST(PropertyTest, WorksForRefQualifiedProperty) {
4369   Matcher<const AClass&> m = Property(&AClass::s_ref, StartsWith("hi"));
4370   Matcher<const AClass&> m_with_name =
4371       Property("s", &AClass::s_ref, StartsWith("hi"));
4372
4373   AClass a;
4374   a.set_s("hill");
4375   EXPECT_TRUE(m.Matches(a));
4376   EXPECT_TRUE(m_with_name.Matches(a));
4377
4378   a.set_s("hole");
4379   EXPECT_FALSE(m.Matches(a));
4380   EXPECT_FALSE(m_with_name.Matches(a));
4381 }
4382
4383 // Tests that Property(&Foo::property, ...) works when property()
4384 // returns a reference to non-const.
4385 TEST(PropertyTest, WorksForReferenceToNonConstProperty) {
4386   double x = 0.0;
4387   AClass a;
4388
4389   Matcher<const AClass&> m = Property(&AClass::x, Ref(x));
4390   EXPECT_FALSE(m.Matches(a));
4391
4392   m = Property(&AClass::x, Not(Ref(x)));
4393   EXPECT_TRUE(m.Matches(a));
4394 }
4395
4396 // Tests that Property(&Foo::property, ...) works when the argument is
4397 // passed by value.
4398 TEST(PropertyTest, WorksForByValueArgument) {
4399   Matcher<AClass> m = Property(&AClass::s, StartsWith("hi"));
4400
4401   AClass a;
4402   a.set_s("hill");
4403   EXPECT_TRUE(m.Matches(a));
4404
4405   a.set_s("hole");
4406   EXPECT_FALSE(m.Matches(a));
4407 }
4408
4409 // Tests that Property(&Foo::property, ...) works when the argument's
4410 // type is a sub-type of Foo.
4411 TEST(PropertyTest, WorksForArgumentOfSubType) {
4412   // The matcher expects a DerivedClass, but inside the Property() we
4413   // say AClass.
4414   Matcher<const DerivedClass&> m = Property(&AClass::n, Ge(0));
4415
4416   DerivedClass d;
4417   d.set_n(1);
4418   EXPECT_TRUE(m.Matches(d));
4419
4420   d.set_n(-1);
4421   EXPECT_FALSE(m.Matches(d));
4422 }
4423
4424 // Tests that Property(&Foo::property, m) works when property()'s type
4425 // and m's argument type are compatible but different.
4426 TEST(PropertyTest, WorksForCompatibleMatcherType) {
4427   // n() returns an int but the inner matcher expects a signed char.
4428   Matcher<const AClass&> m = Property(&AClass::n,
4429                                       Matcher<signed char>(Ge(0)));
4430
4431   Matcher<const AClass&> m_with_name =
4432       Property("n", &AClass::n, Matcher<signed char>(Ge(0)));
4433
4434   AClass a;
4435   EXPECT_TRUE(m.Matches(a));
4436   EXPECT_TRUE(m_with_name.Matches(a));
4437   a.set_n(-1);
4438   EXPECT_FALSE(m.Matches(a));
4439   EXPECT_FALSE(m_with_name.Matches(a));
4440 }
4441
4442 // Tests that Property() can describe itself.
4443 TEST(PropertyTest, CanDescribeSelf) {
4444   Matcher<const AClass&> m = Property(&AClass::n, Ge(0));
4445
4446   EXPECT_EQ("is an object whose given property is >= 0", Describe(m));
4447   EXPECT_EQ("is an object whose given property isn't >= 0",
4448             DescribeNegation(m));
4449 }
4450
4451 TEST(PropertyTest, CanDescribeSelfWithPropertyName) {
4452   Matcher<const AClass&> m = Property("fancy_name", &AClass::n, Ge(0));
4453
4454   EXPECT_EQ("is an object whose property `fancy_name` is >= 0", Describe(m));
4455   EXPECT_EQ("is an object whose property `fancy_name` isn't >= 0",
4456             DescribeNegation(m));
4457 }
4458
4459 // Tests that Property() can explain the match result.
4460 TEST(PropertyTest, CanExplainMatchResult) {
4461   Matcher<const AClass&> m = Property(&AClass::n, Ge(0));
4462
4463   AClass a;
4464   a.set_n(1);
4465   EXPECT_EQ("whose given property is 1" + OfType("int"), Explain(m, a));
4466
4467   m = Property(&AClass::n, GreaterThan(0));
4468   EXPECT_EQ(
4469       "whose given property is 1" + OfType("int") + ", which is 1 more than 0",
4470       Explain(m, a));
4471 }
4472
4473 TEST(PropertyTest, CanExplainMatchResultWithPropertyName) {
4474   Matcher<const AClass&> m = Property("fancy_name", &AClass::n, Ge(0));
4475
4476   AClass a;
4477   a.set_n(1);
4478   EXPECT_EQ("whose property `fancy_name` is 1" + OfType("int"), Explain(m, a));
4479
4480   m = Property("fancy_name", &AClass::n, GreaterThan(0));
4481   EXPECT_EQ("whose property `fancy_name` is 1" + OfType("int") +
4482                 ", which is 1 more than 0",
4483             Explain(m, a));
4484 }
4485
4486 // Tests that Property() works when the argument is a pointer to const.
4487 TEST(PropertyForPointerTest, WorksForPointerToConst) {
4488   Matcher<const AClass*> m = Property(&AClass::n, Ge(0));
4489
4490   AClass a;
4491   a.set_n(1);
4492   EXPECT_TRUE(m.Matches(&a));
4493
4494   a.set_n(-1);
4495   EXPECT_FALSE(m.Matches(&a));
4496 }
4497
4498 // Tests that Property() works when the argument is a pointer to non-const.
4499 TEST(PropertyForPointerTest, WorksForPointerToNonConst) {
4500   Matcher<AClass*> m = Property(&AClass::s, StartsWith("hi"));
4501
4502   AClass a;
4503   a.set_s("hill");
4504   EXPECT_TRUE(m.Matches(&a));
4505
4506   a.set_s("hole");
4507   EXPECT_FALSE(m.Matches(&a));
4508 }
4509
4510 // Tests that Property() works when the argument is a reference to a
4511 // const pointer.
4512 TEST(PropertyForPointerTest, WorksForReferenceToConstPointer) {
4513   Matcher<AClass* const&> m = Property(&AClass::s, StartsWith("hi"));
4514
4515   AClass a;
4516   a.set_s("hill");
4517   EXPECT_TRUE(m.Matches(&a));
4518
4519   a.set_s("hole");
4520   EXPECT_FALSE(m.Matches(&a));
4521 }
4522
4523 // Tests that Property() does not match the NULL pointer.
4524 TEST(PropertyForPointerTest, WorksForReferenceToNonConstProperty) {
4525   Matcher<const AClass*> m = Property(&AClass::x, _);
4526   EXPECT_FALSE(m.Matches(nullptr));
4527 }
4528
4529 // Tests that Property(&Foo::property, ...) works when the argument's
4530 // type is a sub-type of const Foo*.
4531 TEST(PropertyForPointerTest, WorksForArgumentOfSubType) {
4532   // The matcher expects a DerivedClass, but inside the Property() we
4533   // say AClass.
4534   Matcher<const DerivedClass*> m = Property(&AClass::n, Ge(0));
4535
4536   DerivedClass d;
4537   d.set_n(1);
4538   EXPECT_TRUE(m.Matches(&d));
4539
4540   d.set_n(-1);
4541   EXPECT_FALSE(m.Matches(&d));
4542 }
4543
4544 // Tests that Property() can describe itself when used to match a pointer.
4545 TEST(PropertyForPointerTest, CanDescribeSelf) {
4546   Matcher<const AClass*> m = Property(&AClass::n, Ge(0));
4547
4548   EXPECT_EQ("is an object whose given property is >= 0", Describe(m));
4549   EXPECT_EQ("is an object whose given property isn't >= 0",
4550             DescribeNegation(m));
4551 }
4552
4553 TEST(PropertyForPointerTest, CanDescribeSelfWithPropertyDescription) {
4554   Matcher<const AClass*> m = Property("fancy_name", &AClass::n, Ge(0));
4555
4556   EXPECT_EQ("is an object whose property `fancy_name` is >= 0", Describe(m));
4557   EXPECT_EQ("is an object whose property `fancy_name` isn't >= 0",
4558             DescribeNegation(m));
4559 }
4560
4561 // Tests that Property() can explain the result of matching a pointer.
4562 TEST(PropertyForPointerTest, CanExplainMatchResult) {
4563   Matcher<const AClass*> m = Property(&AClass::n, Ge(0));
4564
4565   AClass a;
4566   a.set_n(1);
4567   EXPECT_EQ("", Explain(m, static_cast<const AClass*>(nullptr)));
4568   EXPECT_EQ(
4569       "which points to an object whose given property is 1" + OfType("int"),
4570       Explain(m, &a));
4571
4572   m = Property(&AClass::n, GreaterThan(0));
4573   EXPECT_EQ("which points to an object whose given property is 1" +
4574             OfType("int") + ", which is 1 more than 0",
4575             Explain(m, &a));
4576 }
4577
4578 TEST(PropertyForPointerTest, CanExplainMatchResultWithPropertyName) {
4579   Matcher<const AClass*> m = Property("fancy_name", &AClass::n, Ge(0));
4580
4581   AClass a;
4582   a.set_n(1);
4583   EXPECT_EQ("", Explain(m, static_cast<const AClass*>(nullptr)));
4584   EXPECT_EQ("which points to an object whose property `fancy_name` is 1" +
4585                 OfType("int"),
4586             Explain(m, &a));
4587
4588   m = Property("fancy_name", &AClass::n, GreaterThan(0));
4589   EXPECT_EQ("which points to an object whose property `fancy_name` is 1" +
4590                 OfType("int") + ", which is 1 more than 0",
4591             Explain(m, &a));
4592 }
4593
4594 // Tests ResultOf.
4595
4596 // Tests that ResultOf(f, ...) compiles and works as expected when f is a
4597 // function pointer.
4598 std::string IntToStringFunction(int input) {
4599   return input == 1 ? "foo" : "bar";
4600 }
4601
4602 TEST(ResultOfTest, WorksForFunctionPointers) {
4603   Matcher<int> matcher = ResultOf(&IntToStringFunction, Eq(std::string("foo")));
4604
4605   EXPECT_TRUE(matcher.Matches(1));
4606   EXPECT_FALSE(matcher.Matches(2));
4607 }
4608
4609 // Tests that ResultOf() can describe itself.
4610 TEST(ResultOfTest, CanDescribeItself) {
4611   Matcher<int> matcher = ResultOf(&IntToStringFunction, StrEq("foo"));
4612
4613   EXPECT_EQ("is mapped by the given callable to a value that "
4614             "is equal to \"foo\"", Describe(matcher));
4615   EXPECT_EQ("is mapped by the given callable to a value that "
4616             "isn't equal to \"foo\"", DescribeNegation(matcher));
4617 }
4618
4619 // Tests that ResultOf() can explain the match result.
4620 int IntFunction(int input) { return input == 42 ? 80 : 90; }
4621
4622 TEST(ResultOfTest, CanExplainMatchResult) {
4623   Matcher<int> matcher = ResultOf(&IntFunction, Ge(85));
4624   EXPECT_EQ("which is mapped by the given callable to 90" + OfType("int"),
4625             Explain(matcher, 36));
4626
4627   matcher = ResultOf(&IntFunction, GreaterThan(85));
4628   EXPECT_EQ("which is mapped by the given callable to 90" + OfType("int") +
4629             ", which is 5 more than 85", Explain(matcher, 36));
4630 }
4631
4632 // Tests that ResultOf(f, ...) compiles and works as expected when f(x)
4633 // returns a non-reference.
4634 TEST(ResultOfTest, WorksForNonReferenceResults) {
4635   Matcher<int> matcher = ResultOf(&IntFunction, Eq(80));
4636
4637   EXPECT_TRUE(matcher.Matches(42));
4638   EXPECT_FALSE(matcher.Matches(36));
4639 }
4640
4641 // Tests that ResultOf(f, ...) compiles and works as expected when f(x)
4642 // returns a reference to non-const.
4643 double& DoubleFunction(double& input) { return input; }  // NOLINT
4644
4645 Uncopyable& RefUncopyableFunction(Uncopyable& obj) {  // NOLINT
4646   return obj;
4647 }
4648
4649 TEST(ResultOfTest, WorksForReferenceToNonConstResults) {
4650   double x = 3.14;
4651   double x2 = x;
4652   Matcher<double&> matcher = ResultOf(&DoubleFunction, Ref(x));
4653
4654   EXPECT_TRUE(matcher.Matches(x));
4655   EXPECT_FALSE(matcher.Matches(x2));
4656
4657   // Test that ResultOf works with uncopyable objects
4658   Uncopyable obj(0);
4659   Uncopyable obj2(0);
4660   Matcher<Uncopyable&> matcher2 =
4661       ResultOf(&RefUncopyableFunction, Ref(obj));
4662
4663   EXPECT_TRUE(matcher2.Matches(obj));
4664   EXPECT_FALSE(matcher2.Matches(obj2));
4665 }
4666
4667 // Tests that ResultOf(f, ...) compiles and works as expected when f(x)
4668 // returns a reference to const.
4669 const std::string& StringFunction(const std::string& input) { return input; }
4670
4671 TEST(ResultOfTest, WorksForReferenceToConstResults) {
4672   std::string s = "foo";
4673   std::string s2 = s;
4674   Matcher<const std::string&> matcher = ResultOf(&StringFunction, Ref(s));
4675
4676   EXPECT_TRUE(matcher.Matches(s));
4677   EXPECT_FALSE(matcher.Matches(s2));
4678 }
4679
4680 // Tests that ResultOf(f, m) works when f(x) and m's
4681 // argument types are compatible but different.
4682 TEST(ResultOfTest, WorksForCompatibleMatcherTypes) {
4683   // IntFunction() returns int but the inner matcher expects a signed char.
4684   Matcher<int> matcher = ResultOf(IntFunction, Matcher<signed char>(Ge(85)));
4685
4686   EXPECT_TRUE(matcher.Matches(36));
4687   EXPECT_FALSE(matcher.Matches(42));
4688 }
4689
4690 // Tests that the program aborts when ResultOf is passed
4691 // a NULL function pointer.
4692 TEST(ResultOfDeathTest, DiesOnNullFunctionPointers) {
4693   EXPECT_DEATH_IF_SUPPORTED(
4694       ResultOf(static_cast<std::string (*)(int dummy)>(nullptr),
4695                Eq(std::string("foo"))),
4696       "NULL function pointer is passed into ResultOf\\(\\)\\.");
4697 }
4698
4699 // Tests that ResultOf(f, ...) compiles and works as expected when f is a
4700 // function reference.
4701 TEST(ResultOfTest, WorksForFunctionReferences) {
4702   Matcher<int> matcher = ResultOf(IntToStringFunction, StrEq("foo"));
4703   EXPECT_TRUE(matcher.Matches(1));
4704   EXPECT_FALSE(matcher.Matches(2));
4705 }
4706
4707 // Tests that ResultOf(f, ...) compiles and works as expected when f is a
4708 // function object.
4709 struct Functor {
4710   std::string operator()(int input) const {
4711     return IntToStringFunction(input);
4712   }
4713 };
4714
4715 TEST(ResultOfTest, WorksForFunctors) {
4716   Matcher<int> matcher = ResultOf(Functor(), Eq(std::string("foo")));
4717
4718   EXPECT_TRUE(matcher.Matches(1));
4719   EXPECT_FALSE(matcher.Matches(2));
4720 }
4721
4722 // Tests that ResultOf(f, ...) compiles and works as expected when f is a
4723 // functor with more than one operator() defined. ResultOf() must work
4724 // for each defined operator().
4725 struct PolymorphicFunctor {
4726   typedef int result_type;
4727   int operator()(int n) { return n; }
4728   int operator()(const char* s) { return static_cast<int>(strlen(s)); }
4729   std::string operator()(int *p) { return p ? "good ptr" : "null"; }
4730 };
4731
4732 TEST(ResultOfTest, WorksForPolymorphicFunctors) {
4733   Matcher<int> matcher_int = ResultOf(PolymorphicFunctor(), Ge(5));
4734
4735   EXPECT_TRUE(matcher_int.Matches(10));
4736   EXPECT_FALSE(matcher_int.Matches(2));
4737
4738   Matcher<const char*> matcher_string = ResultOf(PolymorphicFunctor(), Ge(5));
4739
4740   EXPECT_TRUE(matcher_string.Matches("long string"));
4741   EXPECT_FALSE(matcher_string.Matches("shrt"));
4742 }
4743
4744 TEST(ResultOfTest, WorksForPolymorphicFunctorsIgnoringResultType) {
4745   Matcher<int*> matcher = ResultOf(PolymorphicFunctor(), "good ptr");
4746
4747   int n = 0;
4748   EXPECT_TRUE(matcher.Matches(&n));
4749   EXPECT_FALSE(matcher.Matches(nullptr));
4750 }
4751
4752 TEST(ResultOfTest, WorksForLambdas) {
4753   Matcher<int> matcher = ResultOf(
4754       [](int str_len) {
4755         return std::string(static_cast<size_t>(str_len), 'x');
4756       },
4757       "xxx");
4758   EXPECT_TRUE(matcher.Matches(3));
4759   EXPECT_FALSE(matcher.Matches(1));
4760 }
4761
4762 TEST(ResultOfTest, WorksForNonCopyableArguments) {
4763   Matcher<std::unique_ptr<int>> matcher = ResultOf(
4764       [](const std::unique_ptr<int>& str_len) {
4765         return std::string(static_cast<size_t>(*str_len), 'x');
4766       },
4767       "xxx");
4768   EXPECT_TRUE(matcher.Matches(std::unique_ptr<int>(new int(3))));
4769   EXPECT_FALSE(matcher.Matches(std::unique_ptr<int>(new int(1))));
4770 }
4771
4772 const int* ReferencingFunction(const int& n) { return &n; }
4773
4774 struct ReferencingFunctor {
4775   typedef const int* result_type;
4776   result_type operator()(const int& n) { return &n; }
4777 };
4778
4779 TEST(ResultOfTest, WorksForReferencingCallables) {
4780   const int n = 1;
4781   const int n2 = 1;
4782   Matcher<const int&> matcher2 = ResultOf(ReferencingFunction, Eq(&n));
4783   EXPECT_TRUE(matcher2.Matches(n));
4784   EXPECT_FALSE(matcher2.Matches(n2));
4785
4786   Matcher<const int&> matcher3 = ResultOf(ReferencingFunctor(), Eq(&n));
4787   EXPECT_TRUE(matcher3.Matches(n));
4788   EXPECT_FALSE(matcher3.Matches(n2));
4789 }
4790
4791 class DivisibleByImpl {
4792  public:
4793   explicit DivisibleByImpl(int a_divider) : divider_(a_divider) {}
4794
4795   // For testing using ExplainMatchResultTo() with polymorphic matchers.
4796   template <typename T>
4797   bool MatchAndExplain(const T& n, MatchResultListener* listener) const {
4798     *listener << "which is " << (n % divider_) << " modulo "
4799               << divider_;
4800     return (n % divider_) == 0;
4801   }
4802
4803   void DescribeTo(ostream* os) const {
4804     *os << "is divisible by " << divider_;
4805   }
4806
4807   void DescribeNegationTo(ostream* os) const {
4808     *os << "is not divisible by " << divider_;
4809   }
4810
4811   void set_divider(int a_divider) { divider_ = a_divider; }
4812   int divider() const { return divider_; }
4813
4814  private:
4815   int divider_;
4816 };
4817
4818 PolymorphicMatcher<DivisibleByImpl> DivisibleBy(int n) {
4819   return MakePolymorphicMatcher(DivisibleByImpl(n));
4820 }
4821
4822 // Tests that when AllOf() fails, only the first failing matcher is
4823 // asked to explain why.
4824 TEST(ExplainMatchResultTest, AllOf_False_False) {
4825   const Matcher<int> m = AllOf(DivisibleBy(4), DivisibleBy(3));
4826   EXPECT_EQ("which is 1 modulo 4", Explain(m, 5));
4827 }
4828
4829 // Tests that when AllOf() fails, only the first failing matcher is
4830 // asked to explain why.
4831 TEST(ExplainMatchResultTest, AllOf_False_True) {
4832   const Matcher<int> m = AllOf(DivisibleBy(4), DivisibleBy(3));
4833   EXPECT_EQ("which is 2 modulo 4", Explain(m, 6));
4834 }
4835
4836 // Tests that when AllOf() fails, only the first failing matcher is
4837 // asked to explain why.
4838 TEST(ExplainMatchResultTest, AllOf_True_False) {
4839   const Matcher<int> m = AllOf(Ge(1), DivisibleBy(3));
4840   EXPECT_EQ("which is 2 modulo 3", Explain(m, 5));
4841 }
4842
4843 // Tests that when AllOf() succeeds, all matchers are asked to explain
4844 // why.
4845 TEST(ExplainMatchResultTest, AllOf_True_True) {
4846   const Matcher<int> m = AllOf(DivisibleBy(2), DivisibleBy(3));
4847   EXPECT_EQ("which is 0 modulo 2, and which is 0 modulo 3", Explain(m, 6));
4848 }
4849
4850 TEST(ExplainMatchResultTest, AllOf_True_True_2) {
4851   const Matcher<int> m = AllOf(Ge(2), Le(3));
4852   EXPECT_EQ("", Explain(m, 2));
4853 }
4854
4855 TEST(ExplainmatcherResultTest, MonomorphicMatcher) {
4856   const Matcher<int> m = GreaterThan(5);
4857   EXPECT_EQ("which is 1 more than 5", Explain(m, 6));
4858 }
4859
4860 // The following two tests verify that values without a public copy
4861 // ctor can be used as arguments to matchers like Eq(), Ge(), and etc
4862 // with the help of ByRef().
4863
4864 class NotCopyable {
4865  public:
4866   explicit NotCopyable(int a_value) : value_(a_value) {}
4867
4868   int value() const { return value_; }
4869
4870   bool operator==(const NotCopyable& rhs) const {
4871     return value() == rhs.value();
4872   }
4873
4874   bool operator>=(const NotCopyable& rhs) const {
4875     return value() >= rhs.value();
4876   }
4877  private:
4878   int value_;
4879
4880   GTEST_DISALLOW_COPY_AND_ASSIGN_(NotCopyable);
4881 };
4882
4883 TEST(ByRefTest, AllowsNotCopyableConstValueInMatchers) {
4884   const NotCopyable const_value1(1);
4885   const Matcher<const NotCopyable&> m = Eq(ByRef(const_value1));
4886
4887   const NotCopyable n1(1), n2(2);
4888   EXPECT_TRUE(m.Matches(n1));
4889   EXPECT_FALSE(m.Matches(n2));
4890 }
4891
4892 TEST(ByRefTest, AllowsNotCopyableValueInMatchers) {
4893   NotCopyable value2(2);
4894   const Matcher<NotCopyable&> m = Ge(ByRef(value2));
4895
4896   NotCopyable n1(1), n2(2);
4897   EXPECT_FALSE(m.Matches(n1));
4898   EXPECT_TRUE(m.Matches(n2));
4899 }
4900
4901 TEST(IsEmptyTest, ImplementsIsEmpty) {
4902   vector<int> container;
4903   EXPECT_THAT(container, IsEmpty());
4904   container.push_back(0);
4905   EXPECT_THAT(container, Not(IsEmpty()));
4906   container.push_back(1);
4907   EXPECT_THAT(container, Not(IsEmpty()));
4908 }
4909
4910 TEST(IsEmptyTest, WorksWithString) {
4911   std::string text;
4912   EXPECT_THAT(text, IsEmpty());
4913   text = "foo";
4914   EXPECT_THAT(text, Not(IsEmpty()));
4915   text = std::string("\0", 1);
4916   EXPECT_THAT(text, Not(IsEmpty()));
4917 }
4918
4919 TEST(IsEmptyTest, CanDescribeSelf) {
4920   Matcher<vector<int> > m = IsEmpty();
4921   EXPECT_EQ("is empty", Describe(m));
4922   EXPECT_EQ("isn't empty", DescribeNegation(m));
4923 }
4924
4925 TEST(IsEmptyTest, ExplainsResult) {
4926   Matcher<vector<int> > m = IsEmpty();
4927   vector<int> container;
4928   EXPECT_EQ("", Explain(m, container));
4929   container.push_back(0);
4930   EXPECT_EQ("whose size is 1", Explain(m, container));
4931 }
4932
4933 TEST(IsEmptyTest, WorksWithMoveOnly) {
4934   ContainerHelper helper;
4935   EXPECT_CALL(helper, Call(IsEmpty()));
4936   helper.Call({});
4937 }
4938
4939 TEST(IsTrueTest, IsTrueIsFalse) {
4940   EXPECT_THAT(true, IsTrue());
4941   EXPECT_THAT(false, IsFalse());
4942   EXPECT_THAT(true, Not(IsFalse()));
4943   EXPECT_THAT(false, Not(IsTrue()));
4944   EXPECT_THAT(0, Not(IsTrue()));
4945   EXPECT_THAT(0, IsFalse());
4946   EXPECT_THAT(nullptr, Not(IsTrue()));
4947   EXPECT_THAT(nullptr, IsFalse());
4948   EXPECT_THAT(-1, IsTrue());
4949   EXPECT_THAT(-1, Not(IsFalse()));
4950   EXPECT_THAT(1, IsTrue());
4951   EXPECT_THAT(1, Not(IsFalse()));
4952   EXPECT_THAT(2, IsTrue());
4953   EXPECT_THAT(2, Not(IsFalse()));
4954   int a = 42;
4955   EXPECT_THAT(a, IsTrue());
4956   EXPECT_THAT(a, Not(IsFalse()));
4957   EXPECT_THAT(&a, IsTrue());
4958   EXPECT_THAT(&a, Not(IsFalse()));
4959   EXPECT_THAT(false, Not(IsTrue()));
4960   EXPECT_THAT(true, Not(IsFalse()));
4961   EXPECT_THAT(std::true_type(), IsTrue());
4962   EXPECT_THAT(std::true_type(), Not(IsFalse()));
4963   EXPECT_THAT(std::false_type(), IsFalse());
4964   EXPECT_THAT(std::false_type(), Not(IsTrue()));
4965   EXPECT_THAT(nullptr, Not(IsTrue()));
4966   EXPECT_THAT(nullptr, IsFalse());
4967   std::unique_ptr<int> null_unique;
4968   std::unique_ptr<int> nonnull_unique(new int(0));
4969   EXPECT_THAT(null_unique, Not(IsTrue()));
4970   EXPECT_THAT(null_unique, IsFalse());
4971   EXPECT_THAT(nonnull_unique, IsTrue());
4972   EXPECT_THAT(nonnull_unique, Not(IsFalse()));
4973 }
4974
4975 TEST(SizeIsTest, ImplementsSizeIs) {
4976   vector<int> container;
4977   EXPECT_THAT(container, SizeIs(0));
4978   EXPECT_THAT(container, Not(SizeIs(1)));
4979   container.push_back(0);
4980   EXPECT_THAT(container, Not(SizeIs(0)));
4981   EXPECT_THAT(container, SizeIs(1));
4982   container.push_back(0);
4983   EXPECT_THAT(container, Not(SizeIs(0)));
4984   EXPECT_THAT(container, SizeIs(2));
4985 }
4986
4987 TEST(SizeIsTest, WorksWithMap) {
4988   map<std::string, int> container;
4989   EXPECT_THAT(container, SizeIs(0));
4990   EXPECT_THAT(container, Not(SizeIs(1)));
4991   container.insert(make_pair("foo", 1));
4992   EXPECT_THAT(container, Not(SizeIs(0)));
4993   EXPECT_THAT(container, SizeIs(1));
4994   container.insert(make_pair("bar", 2));
4995   EXPECT_THAT(container, Not(SizeIs(0)));
4996   EXPECT_THAT(container, SizeIs(2));
4997 }
4998
4999 TEST(SizeIsTest, WorksWithReferences) {
5000   vector<int> container;
5001   Matcher<const vector<int>&> m = SizeIs(1);
5002   EXPECT_THAT(container, Not(m));
5003   container.push_back(0);
5004   EXPECT_THAT(container, m);
5005 }
5006
5007 TEST(SizeIsTest, WorksWithMoveOnly) {
5008   ContainerHelper helper;
5009   EXPECT_CALL(helper, Call(SizeIs(3)));
5010   helper.Call(MakeUniquePtrs({1, 2, 3}));
5011 }
5012
5013 // SizeIs should work for any type that provides a size() member function.
5014 // For example, a size_type member type should not need to be provided.
5015 struct MinimalistCustomType {
5016   int size() const { return 1; }
5017 };
5018 TEST(SizeIsTest, WorksWithMinimalistCustomType) {
5019   MinimalistCustomType container;
5020   EXPECT_THAT(container, SizeIs(1));
5021   EXPECT_THAT(container, Not(SizeIs(0)));
5022 }
5023
5024 TEST(SizeIsTest, CanDescribeSelf) {
5025   Matcher<vector<int> > m = SizeIs(2);
5026   EXPECT_EQ("size is equal to 2", Describe(m));
5027   EXPECT_EQ("size isn't equal to 2", DescribeNegation(m));
5028 }
5029
5030 TEST(SizeIsTest, ExplainsResult) {
5031   Matcher<vector<int> > m1 = SizeIs(2);
5032   Matcher<vector<int> > m2 = SizeIs(Lt(2u));
5033   Matcher<vector<int> > m3 = SizeIs(AnyOf(0, 3));
5034   Matcher<vector<int> > m4 = SizeIs(Gt(1u));
5035   vector<int> container;
5036   EXPECT_EQ("whose size 0 doesn't match", Explain(m1, container));
5037   EXPECT_EQ("whose size 0 matches", Explain(m2, container));
5038   EXPECT_EQ("whose size 0 matches", Explain(m3, container));
5039   EXPECT_EQ("whose size 0 doesn't match", Explain(m4, container));
5040   container.push_back(0);
5041   container.push_back(0);
5042   EXPECT_EQ("whose size 2 matches", Explain(m1, container));
5043   EXPECT_EQ("whose size 2 doesn't match", Explain(m2, container));
5044   EXPECT_EQ("whose size 2 doesn't match", Explain(m3, container));
5045   EXPECT_EQ("whose size 2 matches", Explain(m4, container));
5046 }
5047
5048 #if GTEST_HAS_TYPED_TEST
5049 // Tests ContainerEq with different container types, and
5050 // different element types.
5051
5052 template <typename T>
5053 class ContainerEqTest : public testing::Test {};
5054
5055 typedef testing::Types<
5056     set<int>,
5057     vector<size_t>,
5058     multiset<size_t>,
5059     list<int> >
5060     ContainerEqTestTypes;
5061
5062 TYPED_TEST_SUITE(ContainerEqTest, ContainerEqTestTypes);
5063
5064 // Tests that the filled container is equal to itself.
5065 TYPED_TEST(ContainerEqTest, EqualsSelf) {
5066   static const int vals[] = {1, 1, 2, 3, 5, 8};
5067   TypeParam my_set(vals, vals + 6);
5068   const Matcher<TypeParam> m = ContainerEq(my_set);
5069   EXPECT_TRUE(m.Matches(my_set));
5070   EXPECT_EQ("", Explain(m, my_set));
5071 }
5072
5073 // Tests that missing values are reported.
5074 TYPED_TEST(ContainerEqTest, ValueMissing) {
5075   static const int vals[] = {1, 1, 2, 3, 5, 8};
5076   static const int test_vals[] = {2, 1, 8, 5};
5077   TypeParam my_set(vals, vals + 6);
5078   TypeParam test_set(test_vals, test_vals + 4);
5079   const Matcher<TypeParam> m = ContainerEq(my_set);
5080   EXPECT_FALSE(m.Matches(test_set));
5081   EXPECT_EQ("which doesn't have these expected elements: 3",
5082             Explain(m, test_set));
5083 }
5084
5085 // Tests that added values are reported.
5086 TYPED_TEST(ContainerEqTest, ValueAdded) {
5087   static const int vals[] = {1, 1, 2, 3, 5, 8};
5088   static const int test_vals[] = {1, 2, 3, 5, 8, 46};
5089   TypeParam my_set(vals, vals + 6);
5090   TypeParam test_set(test_vals, test_vals + 6);
5091   const Matcher<const TypeParam&> m = ContainerEq(my_set);
5092   EXPECT_FALSE(m.Matches(test_set));
5093   EXPECT_EQ("which has these unexpected elements: 46", Explain(m, test_set));
5094 }
5095
5096 // Tests that added and missing values are reported together.
5097 TYPED_TEST(ContainerEqTest, ValueAddedAndRemoved) {
5098   static const int vals[] = {1, 1, 2, 3, 5, 8};
5099   static const int test_vals[] = {1, 2, 3, 8, 46};
5100   TypeParam my_set(vals, vals + 6);
5101   TypeParam test_set(test_vals, test_vals + 5);
5102   const Matcher<TypeParam> m = ContainerEq(my_set);
5103   EXPECT_FALSE(m.Matches(test_set));
5104   EXPECT_EQ("which has these unexpected elements: 46,\n"
5105             "and doesn't have these expected elements: 5",
5106             Explain(m, test_set));
5107 }
5108
5109 // Tests duplicated value -- expect no explanation.
5110 TYPED_TEST(ContainerEqTest, DuplicateDifference) {
5111   static const int vals[] = {1, 1, 2, 3, 5, 8};
5112   static const int test_vals[] = {1, 2, 3, 5, 8};
5113   TypeParam my_set(vals, vals + 6);
5114   TypeParam test_set(test_vals, test_vals + 5);
5115   const Matcher<const TypeParam&> m = ContainerEq(my_set);
5116   // Depending on the container, match may be true or false
5117   // But in any case there should be no explanation.
5118   EXPECT_EQ("", Explain(m, test_set));
5119 }
5120 #endif  // GTEST_HAS_TYPED_TEST
5121
5122 // Tests that multiple missing values are reported.
5123 // Using just vector here, so order is predictable.
5124 TEST(ContainerEqExtraTest, MultipleValuesMissing) {
5125   static const int vals[] = {1, 1, 2, 3, 5, 8};
5126   static const int test_vals[] = {2, 1, 5};
5127   vector<int> my_set(vals, vals + 6);
5128   vector<int> test_set(test_vals, test_vals + 3);
5129   const Matcher<vector<int> > m = ContainerEq(my_set);
5130   EXPECT_FALSE(m.Matches(test_set));
5131   EXPECT_EQ("which doesn't have these expected elements: 3, 8",
5132             Explain(m, test_set));
5133 }
5134
5135 // Tests that added values are reported.
5136 // Using just vector here, so order is predictable.
5137 TEST(ContainerEqExtraTest, MultipleValuesAdded) {
5138   static const int vals[] = {1, 1, 2, 3, 5, 8};
5139   static const int test_vals[] = {1, 2, 92, 3, 5, 8, 46};
5140   list<size_t> my_set(vals, vals + 6);
5141   list<size_t> test_set(test_vals, test_vals + 7);
5142   const Matcher<const list<size_t>&> m = ContainerEq(my_set);
5143   EXPECT_FALSE(m.Matches(test_set));
5144   EXPECT_EQ("which has these unexpected elements: 92, 46",
5145             Explain(m, test_set));
5146 }
5147
5148 // Tests that added and missing values are reported together.
5149 TEST(ContainerEqExtraTest, MultipleValuesAddedAndRemoved) {
5150   static const int vals[] = {1, 1, 2, 3, 5, 8};
5151   static const int test_vals[] = {1, 2, 3, 92, 46};
5152   list<size_t> my_set(vals, vals + 6);
5153   list<size_t> test_set(test_vals, test_vals + 5);
5154   const Matcher<const list<size_t> > m = ContainerEq(my_set);
5155   EXPECT_FALSE(m.Matches(test_set));
5156   EXPECT_EQ("which has these unexpected elements: 92, 46,\n"
5157             "and doesn't have these expected elements: 5, 8",
5158             Explain(m, test_set));
5159 }
5160
5161 // Tests to see that duplicate elements are detected,
5162 // but (as above) not reported in the explanation.
5163 TEST(ContainerEqExtraTest, MultiSetOfIntDuplicateDifference) {
5164   static const int vals[] = {1, 1, 2, 3, 5, 8};
5165   static const int test_vals[] = {1, 2, 3, 5, 8};
5166   vector<int> my_set(vals, vals + 6);
5167   vector<int> test_set(test_vals, test_vals + 5);
5168   const Matcher<vector<int> > m = ContainerEq(my_set);
5169   EXPECT_TRUE(m.Matches(my_set));
5170   EXPECT_FALSE(m.Matches(test_set));
5171   // There is nothing to report when both sets contain all the same values.
5172   EXPECT_EQ("", Explain(m, test_set));
5173 }
5174
5175 // Tests that ContainerEq works for non-trivial associative containers,
5176 // like maps.
5177 TEST(ContainerEqExtraTest, WorksForMaps) {
5178   map<int, std::string> my_map;
5179   my_map[0] = "a";
5180   my_map[1] = "b";
5181
5182   map<int, std::string> test_map;
5183   test_map[0] = "aa";
5184   test_map[1] = "b";
5185
5186   const Matcher<const map<int, std::string>&> m = ContainerEq(my_map);
5187   EXPECT_TRUE(m.Matches(my_map));
5188   EXPECT_FALSE(m.Matches(test_map));
5189
5190   EXPECT_EQ("which has these unexpected elements: (0, \"aa\"),\n"
5191             "and doesn't have these expected elements: (0, \"a\")",
5192             Explain(m, test_map));
5193 }
5194
5195 TEST(ContainerEqExtraTest, WorksForNativeArray) {
5196   int a1[] = {1, 2, 3};
5197   int a2[] = {1, 2, 3};
5198   int b[] = {1, 2, 4};
5199
5200   EXPECT_THAT(a1, ContainerEq(a2));
5201   EXPECT_THAT(a1, Not(ContainerEq(b)));
5202 }
5203
5204 TEST(ContainerEqExtraTest, WorksForTwoDimensionalNativeArray) {
5205   const char a1[][3] = {"hi", "lo"};
5206   const char a2[][3] = {"hi", "lo"};
5207   const char b[][3] = {"lo", "hi"};
5208
5209   // Tests using ContainerEq() in the first dimension.
5210   EXPECT_THAT(a1, ContainerEq(a2));
5211   EXPECT_THAT(a1, Not(ContainerEq(b)));
5212
5213   // Tests using ContainerEq() in the second dimension.
5214   EXPECT_THAT(a1, ElementsAre(ContainerEq(a2[0]), ContainerEq(a2[1])));
5215   EXPECT_THAT(a1, ElementsAre(Not(ContainerEq(b[0])), ContainerEq(a2[1])));
5216 }
5217
5218 TEST(ContainerEqExtraTest, WorksForNativeArrayAsTuple) {
5219   const int a1[] = {1, 2, 3};
5220   const int a2[] = {1, 2, 3};
5221   const int b[] = {1, 2, 3, 4};
5222
5223   const int* const p1 = a1;
5224   EXPECT_THAT(std::make_tuple(p1, 3), ContainerEq(a2));
5225   EXPECT_THAT(std::make_tuple(p1, 3), Not(ContainerEq(b)));
5226
5227   const int c[] = {1, 3, 2};
5228   EXPECT_THAT(std::make_tuple(p1, 3), Not(ContainerEq(c)));
5229 }
5230
5231 TEST(ContainerEqExtraTest, CopiesNativeArrayParameter) {
5232   std::string a1[][3] = {
5233     {"hi", "hello", "ciao"},
5234     {"bye", "see you", "ciao"}
5235   };
5236
5237   std::string a2[][3] = {
5238     {"hi", "hello", "ciao"},
5239     {"bye", "see you", "ciao"}
5240   };
5241
5242   const Matcher<const std::string(&)[2][3]> m = ContainerEq(a2);
5243   EXPECT_THAT(a1, m);
5244
5245   a2[0][0] = "ha";
5246   EXPECT_THAT(a1, m);
5247 }
5248
5249 TEST(WhenSortedByTest, WorksForEmptyContainer) {
5250   const vector<int> numbers;
5251   EXPECT_THAT(numbers, WhenSortedBy(less<int>(), ElementsAre()));
5252   EXPECT_THAT(numbers, Not(WhenSortedBy(less<int>(), ElementsAre(1))));
5253 }
5254
5255 TEST(WhenSortedByTest, WorksForNonEmptyContainer) {
5256   vector<unsigned> numbers;
5257   numbers.push_back(3);
5258   numbers.push_back(1);
5259   numbers.push_back(2);
5260   numbers.push_back(2);
5261   EXPECT_THAT(numbers, WhenSortedBy(greater<unsigned>(),
5262                                     ElementsAre(3, 2, 2, 1)));
5263   EXPECT_THAT(numbers, Not(WhenSortedBy(greater<unsigned>(),
5264                                         ElementsAre(1, 2, 2, 3))));
5265 }
5266
5267 TEST(WhenSortedByTest, WorksForNonVectorContainer) {
5268   list<std::string> words;
5269   words.push_back("say");
5270   words.push_back("hello");
5271   words.push_back("world");
5272   EXPECT_THAT(words, WhenSortedBy(less<std::string>(),
5273                                   ElementsAre("hello", "say", "world")));
5274   EXPECT_THAT(words, Not(WhenSortedBy(less<std::string>(),
5275                                       ElementsAre("say", "hello", "world"))));
5276 }
5277
5278 TEST(WhenSortedByTest, WorksForNativeArray) {
5279   const int numbers[] = {1, 3, 2, 4};
5280   const int sorted_numbers[] = {1, 2, 3, 4};
5281   EXPECT_THAT(numbers, WhenSortedBy(less<int>(), ElementsAre(1, 2, 3, 4)));
5282   EXPECT_THAT(numbers, WhenSortedBy(less<int>(),
5283                                     ElementsAreArray(sorted_numbers)));
5284   EXPECT_THAT(numbers, Not(WhenSortedBy(less<int>(), ElementsAre(1, 3, 2, 4))));
5285 }
5286
5287 TEST(WhenSortedByTest, CanDescribeSelf) {
5288   const Matcher<vector<int> > m = WhenSortedBy(less<int>(), ElementsAre(1, 2));
5289   EXPECT_EQ("(when sorted) has 2 elements where\n"
5290             "element #0 is equal to 1,\n"
5291             "element #1 is equal to 2",
5292             Describe(m));
5293   EXPECT_EQ("(when sorted) doesn't have 2 elements, or\n"
5294             "element #0 isn't equal to 1, or\n"
5295             "element #1 isn't equal to 2",
5296             DescribeNegation(m));
5297 }
5298
5299 TEST(WhenSortedByTest, ExplainsMatchResult) {
5300   const int a[] = {2, 1};
5301   EXPECT_EQ("which is { 1, 2 } when sorted, whose element #0 doesn't match",
5302             Explain(WhenSortedBy(less<int>(), ElementsAre(2, 3)), a));
5303   EXPECT_EQ("which is { 1, 2 } when sorted",
5304             Explain(WhenSortedBy(less<int>(), ElementsAre(1, 2)), a));
5305 }
5306
5307 // WhenSorted() is a simple wrapper on WhenSortedBy().  Hence we don't
5308 // need to test it as exhaustively as we test the latter.
5309
5310 TEST(WhenSortedTest, WorksForEmptyContainer) {
5311   const vector<int> numbers;
5312   EXPECT_THAT(numbers, WhenSorted(ElementsAre()));
5313   EXPECT_THAT(numbers, Not(WhenSorted(ElementsAre(1))));
5314 }
5315
5316 TEST(WhenSortedTest, WorksForNonEmptyContainer) {
5317   list<std::string> words;
5318   words.push_back("3");
5319   words.push_back("1");
5320   words.push_back("2");
5321   words.push_back("2");
5322   EXPECT_THAT(words, WhenSorted(ElementsAre("1", "2", "2", "3")));
5323   EXPECT_THAT(words, Not(WhenSorted(ElementsAre("3", "1", "2", "2"))));
5324 }
5325
5326 TEST(WhenSortedTest, WorksForMapTypes) {
5327   map<std::string, int> word_counts;
5328   word_counts["and"] = 1;
5329   word_counts["the"] = 1;
5330   word_counts["buffalo"] = 2;
5331   EXPECT_THAT(word_counts,
5332               WhenSorted(ElementsAre(Pair("and", 1), Pair("buffalo", 2),
5333                                      Pair("the", 1))));
5334   EXPECT_THAT(word_counts,
5335               Not(WhenSorted(ElementsAre(Pair("and", 1), Pair("the", 1),
5336                                          Pair("buffalo", 2)))));
5337 }
5338
5339 TEST(WhenSortedTest, WorksForMultiMapTypes) {
5340     multimap<int, int> ifib;
5341     ifib.insert(make_pair(8, 6));
5342     ifib.insert(make_pair(2, 3));
5343     ifib.insert(make_pair(1, 1));
5344     ifib.insert(make_pair(3, 4));
5345     ifib.insert(make_pair(1, 2));
5346     ifib.insert(make_pair(5, 5));
5347     EXPECT_THAT(ifib, WhenSorted(ElementsAre(Pair(1, 1),
5348                                              Pair(1, 2),
5349                                              Pair(2, 3),
5350                                              Pair(3, 4),
5351                                              Pair(5, 5),
5352                                              Pair(8, 6))));
5353     EXPECT_THAT(ifib, Not(WhenSorted(ElementsAre(Pair(8, 6),
5354                                                  Pair(2, 3),
5355                                                  Pair(1, 1),
5356                                                  Pair(3, 4),
5357                                                  Pair(1, 2),
5358                                                  Pair(5, 5)))));
5359 }
5360
5361 TEST(WhenSortedTest, WorksForPolymorphicMatcher) {
5362     std::deque<int> d;
5363     d.push_back(2);
5364     d.push_back(1);
5365     EXPECT_THAT(d, WhenSorted(ElementsAre(1, 2)));
5366     EXPECT_THAT(d, Not(WhenSorted(ElementsAre(2, 1))));
5367 }
5368
5369 TEST(WhenSortedTest, WorksForVectorConstRefMatcher) {
5370     std::deque<int> d;
5371     d.push_back(2);
5372     d.push_back(1);
5373     Matcher<const std::vector<int>&> vector_match = ElementsAre(1, 2);
5374     EXPECT_THAT(d, WhenSorted(vector_match));
5375     Matcher<const std::vector<int>&> not_vector_match = ElementsAre(2, 1);
5376     EXPECT_THAT(d, Not(WhenSorted(not_vector_match)));
5377 }
5378
5379 // Deliberately bare pseudo-container.
5380 // Offers only begin() and end() accessors, yielding InputIterator.
5381 template <typename T>
5382 class Streamlike {
5383  private:
5384   class ConstIter;
5385  public:
5386   typedef ConstIter const_iterator;
5387   typedef T value_type;
5388
5389   template <typename InIter>
5390   Streamlike(InIter first, InIter last) : remainder_(first, last) {}
5391
5392   const_iterator begin() const {
5393     return const_iterator(this, remainder_.begin());
5394   }
5395   const_iterator end() const {
5396     return const_iterator(this, remainder_.end());
5397   }
5398
5399  private:
5400   class ConstIter : public std::iterator<std::input_iterator_tag,
5401                                          value_type,
5402                                          ptrdiff_t,
5403                                          const value_type*,
5404                                          const value_type&> {
5405    public:
5406     ConstIter(const Streamlike* s,
5407               typename std::list<value_type>::iterator pos)
5408         : s_(s), pos_(pos) {}
5409
5410     const value_type& operator*() const { return *pos_; }
5411     const value_type* operator->() const { return &*pos_; }
5412     ConstIter& operator++() {
5413       s_->remainder_.erase(pos_++);
5414       return *this;
5415     }
5416
5417     // *iter++ is required to work (see std::istreambuf_iterator).
5418     // (void)iter++ is also required to work.
5419     class PostIncrProxy {
5420      public:
5421       explicit PostIncrProxy(const value_type& value) : value_(value) {}
5422       value_type operator*() const { return value_; }
5423      private:
5424       value_type value_;
5425     };
5426     PostIncrProxy operator++(int) {
5427       PostIncrProxy proxy(**this);
5428       ++(*this);
5429       return proxy;
5430     }
5431
5432     friend bool operator==(const ConstIter& a, const ConstIter& b) {
5433       return a.s_ == b.s_ && a.pos_ == b.pos_;
5434     }
5435     friend bool operator!=(const ConstIter& a, const ConstIter& b) {
5436       return !(a == b);
5437     }
5438
5439    private:
5440     const Streamlike* s_;
5441     typename std::list<value_type>::iterator pos_;
5442   };
5443
5444   friend std::ostream& operator<<(std::ostream& os, const Streamlike& s) {
5445     os << "[";
5446     typedef typename std::list<value_type>::const_iterator Iter;
5447     const char* sep = "";
5448     for (Iter it = s.remainder_.begin(); it != s.remainder_.end(); ++it) {
5449       os << sep << *it;
5450       sep = ",";
5451     }
5452     os << "]";
5453     return os;
5454   }
5455
5456   mutable std::list<value_type> remainder_;  // modified by iteration
5457 };
5458
5459 TEST(StreamlikeTest, Iteration) {
5460   const int a[5] = {2, 1, 4, 5, 3};
5461   Streamlike<int> s(a, a + 5);
5462   Streamlike<int>::const_iterator it = s.begin();
5463   const int* ip = a;
5464   while (it != s.end()) {
5465     SCOPED_TRACE(ip - a);
5466     EXPECT_EQ(*ip++, *it++);
5467   }
5468 }
5469
5470 TEST(BeginEndDistanceIsTest, WorksWithForwardList) {
5471   std::forward_list<int> container;
5472   EXPECT_THAT(container, BeginEndDistanceIs(0));
5473   EXPECT_THAT(container, Not(BeginEndDistanceIs(1)));
5474   container.push_front(0);
5475   EXPECT_THAT(container, Not(BeginEndDistanceIs(0)));
5476   EXPECT_THAT(container, BeginEndDistanceIs(1));
5477   container.push_front(0);
5478   EXPECT_THAT(container, Not(BeginEndDistanceIs(0)));
5479   EXPECT_THAT(container, BeginEndDistanceIs(2));
5480 }
5481
5482 TEST(BeginEndDistanceIsTest, WorksWithNonStdList) {
5483   const int a[5] = {1, 2, 3, 4, 5};
5484   Streamlike<int> s(a, a + 5);
5485   EXPECT_THAT(s, BeginEndDistanceIs(5));
5486 }
5487
5488 TEST(BeginEndDistanceIsTest, CanDescribeSelf) {
5489   Matcher<vector<int> > m = BeginEndDistanceIs(2);
5490   EXPECT_EQ("distance between begin() and end() is equal to 2", Describe(m));
5491   EXPECT_EQ("distance between begin() and end() isn't equal to 2",
5492             DescribeNegation(m));
5493 }
5494
5495 TEST(BeginEndDistanceIsTest, WorksWithMoveOnly) {
5496   ContainerHelper helper;
5497   EXPECT_CALL(helper, Call(BeginEndDistanceIs(2)));
5498   helper.Call(MakeUniquePtrs({1, 2}));
5499 }
5500
5501 TEST(BeginEndDistanceIsTest, ExplainsResult) {
5502   Matcher<vector<int> > m1 = BeginEndDistanceIs(2);
5503   Matcher<vector<int> > m2 = BeginEndDistanceIs(Lt(2));
5504   Matcher<vector<int> > m3 = BeginEndDistanceIs(AnyOf(0, 3));
5505   Matcher<vector<int> > m4 = BeginEndDistanceIs(GreaterThan(1));
5506   vector<int> container;
5507   EXPECT_EQ("whose distance between begin() and end() 0 doesn't match",
5508             Explain(m1, container));
5509   EXPECT_EQ("whose distance between begin() and end() 0 matches",
5510             Explain(m2, container));
5511   EXPECT_EQ("whose distance between begin() and end() 0 matches",
5512             Explain(m3, container));
5513   EXPECT_EQ(
5514       "whose distance between begin() and end() 0 doesn't match, which is 1 "
5515       "less than 1",
5516       Explain(m4, container));
5517   container.push_back(0);
5518   container.push_back(0);
5519   EXPECT_EQ("whose distance between begin() and end() 2 matches",
5520             Explain(m1, container));
5521   EXPECT_EQ("whose distance between begin() and end() 2 doesn't match",
5522             Explain(m2, container));
5523   EXPECT_EQ("whose distance between begin() and end() 2 doesn't match",
5524             Explain(m3, container));
5525   EXPECT_EQ(
5526       "whose distance between begin() and end() 2 matches, which is 1 more "
5527       "than 1",
5528       Explain(m4, container));
5529 }
5530
5531 TEST(WhenSortedTest, WorksForStreamlike) {
5532   // Streamlike 'container' provides only minimal iterator support.
5533   // Its iterators are tagged with input_iterator_tag.
5534   const int a[5] = {2, 1, 4, 5, 3};
5535   Streamlike<int> s(std::begin(a), std::end(a));
5536   EXPECT_THAT(s, WhenSorted(ElementsAre(1, 2, 3, 4, 5)));
5537   EXPECT_THAT(s, Not(WhenSorted(ElementsAre(2, 1, 4, 5, 3))));
5538 }
5539
5540 TEST(WhenSortedTest, WorksForVectorConstRefMatcherOnStreamlike) {
5541   const int a[] = {2, 1, 4, 5, 3};
5542   Streamlike<int> s(std::begin(a), std::end(a));
5543   Matcher<const std::vector<int>&> vector_match = ElementsAre(1, 2, 3, 4, 5);
5544   EXPECT_THAT(s, WhenSorted(vector_match));
5545   EXPECT_THAT(s, Not(WhenSorted(ElementsAre(2, 1, 4, 5, 3))));
5546 }
5547
5548 TEST(IsSupersetOfTest, WorksForNativeArray) {
5549   const int subset[] = {1, 4};
5550   const int superset[] = {1, 2, 4};
5551   const int disjoint[] = {1, 0, 3};
5552   EXPECT_THAT(subset, IsSupersetOf(subset));
5553   EXPECT_THAT(subset, Not(IsSupersetOf(superset)));
5554   EXPECT_THAT(superset, IsSupersetOf(subset));
5555   EXPECT_THAT(subset, Not(IsSupersetOf(disjoint)));
5556   EXPECT_THAT(disjoint, Not(IsSupersetOf(subset)));
5557 }
5558
5559 TEST(IsSupersetOfTest, WorksWithDuplicates) {
5560   const int not_enough[] = {1, 2};
5561   const int enough[] = {1, 1, 2};
5562   const int expected[] = {1, 1};
5563   EXPECT_THAT(not_enough, Not(IsSupersetOf(expected)));
5564   EXPECT_THAT(enough, IsSupersetOf(expected));
5565 }
5566
5567 TEST(IsSupersetOfTest, WorksForEmpty) {
5568   vector<int> numbers;
5569   vector<int> expected;
5570   EXPECT_THAT(numbers, IsSupersetOf(expected));
5571   expected.push_back(1);
5572   EXPECT_THAT(numbers, Not(IsSupersetOf(expected)));
5573   expected.clear();
5574   numbers.push_back(1);
5575   numbers.push_back(2);
5576   EXPECT_THAT(numbers, IsSupersetOf(expected));
5577   expected.push_back(1);
5578   EXPECT_THAT(numbers, IsSupersetOf(expected));
5579   expected.push_back(2);
5580   EXPECT_THAT(numbers, IsSupersetOf(expected));
5581   expected.push_back(3);
5582   EXPECT_THAT(numbers, Not(IsSupersetOf(expected)));
5583 }
5584
5585 TEST(IsSupersetOfTest, WorksForStreamlike) {
5586   const int a[5] = {1, 2, 3, 4, 5};
5587   Streamlike<int> s(std::begin(a), std::end(a));
5588
5589   vector<int> expected;
5590   expected.push_back(1);
5591   expected.push_back(2);
5592   expected.push_back(5);
5593   EXPECT_THAT(s, IsSupersetOf(expected));
5594
5595   expected.push_back(0);
5596   EXPECT_THAT(s, Not(IsSupersetOf(expected)));
5597 }
5598
5599 TEST(IsSupersetOfTest, TakesStlContainer) {
5600   const int actual[] = {3, 1, 2};
5601
5602   ::std::list<int> expected;
5603   expected.push_back(1);
5604   expected.push_back(3);
5605   EXPECT_THAT(actual, IsSupersetOf(expected));
5606
5607   expected.push_back(4);
5608   EXPECT_THAT(actual, Not(IsSupersetOf(expected)));
5609 }
5610
5611 TEST(IsSupersetOfTest, Describe) {
5612   typedef std::vector<int> IntVec;
5613   IntVec expected;
5614   expected.push_back(111);
5615   expected.push_back(222);
5616   expected.push_back(333);
5617   EXPECT_THAT(
5618       Describe<IntVec>(IsSupersetOf(expected)),
5619       Eq("a surjection from elements to requirements exists such that:\n"
5620          " - an element is equal to 111\n"
5621          " - an element is equal to 222\n"
5622          " - an element is equal to 333"));
5623 }
5624
5625 TEST(IsSupersetOfTest, DescribeNegation) {
5626   typedef std::vector<int> IntVec;
5627   IntVec expected;
5628   expected.push_back(111);
5629   expected.push_back(222);
5630   expected.push_back(333);
5631   EXPECT_THAT(
5632       DescribeNegation<IntVec>(IsSupersetOf(expected)),
5633       Eq("no surjection from elements to requirements exists such that:\n"
5634          " - an element is equal to 111\n"
5635          " - an element is equal to 222\n"
5636          " - an element is equal to 333"));
5637 }
5638
5639 TEST(IsSupersetOfTest, MatchAndExplain) {
5640   std::vector<int> v;
5641   v.push_back(2);
5642   v.push_back(3);
5643   std::vector<int> expected;
5644   expected.push_back(1);
5645   expected.push_back(2);
5646   StringMatchResultListener listener;
5647   ASSERT_FALSE(ExplainMatchResult(IsSupersetOf(expected), v, &listener))
5648       << listener.str();
5649   EXPECT_THAT(listener.str(),
5650               Eq("where the following matchers don't match any elements:\n"
5651                  "matcher #0: is equal to 1"));
5652
5653   v.push_back(1);
5654   listener.Clear();
5655   ASSERT_TRUE(ExplainMatchResult(IsSupersetOf(expected), v, &listener))
5656       << listener.str();
5657   EXPECT_THAT(listener.str(), Eq("where:\n"
5658                                  " - element #0 is matched by matcher #1,\n"
5659                                  " - element #2 is matched by matcher #0"));
5660 }
5661
5662 TEST(IsSupersetOfTest, WorksForRhsInitializerList) {
5663   const int numbers[] = {1, 3, 6, 2, 4, 5};
5664   EXPECT_THAT(numbers, IsSupersetOf({1, 2}));
5665   EXPECT_THAT(numbers, Not(IsSupersetOf({3, 0})));
5666 }
5667
5668 TEST(IsSupersetOfTest, WorksWithMoveOnly) {
5669   ContainerHelper helper;
5670   EXPECT_CALL(helper, Call(IsSupersetOf({Pointee(1)})));
5671   helper.Call(MakeUniquePtrs({1, 2}));
5672   EXPECT_CALL(helper, Call(Not(IsSupersetOf({Pointee(1), Pointee(2)}))));
5673   helper.Call(MakeUniquePtrs({2}));
5674 }
5675
5676 TEST(IsSubsetOfTest, WorksForNativeArray) {
5677   const int subset[] = {1, 4};
5678   const int superset[] = {1, 2, 4};
5679   const int disjoint[] = {1, 0, 3};
5680   EXPECT_THAT(subset, IsSubsetOf(subset));
5681   EXPECT_THAT(subset, IsSubsetOf(superset));
5682   EXPECT_THAT(superset, Not(IsSubsetOf(subset)));
5683   EXPECT_THAT(subset, Not(IsSubsetOf(disjoint)));
5684   EXPECT_THAT(disjoint, Not(IsSubsetOf(subset)));
5685 }
5686
5687 TEST(IsSubsetOfTest, WorksWithDuplicates) {
5688   const int not_enough[] = {1, 2};
5689   const int enough[] = {1, 1, 2};
5690   const int actual[] = {1, 1};
5691   EXPECT_THAT(actual, Not(IsSubsetOf(not_enough)));
5692   EXPECT_THAT(actual, IsSubsetOf(enough));
5693 }
5694
5695 TEST(IsSubsetOfTest, WorksForEmpty) {
5696   vector<int> numbers;
5697   vector<int> expected;
5698   EXPECT_THAT(numbers, IsSubsetOf(expected));
5699   expected.push_back(1);
5700   EXPECT_THAT(numbers, IsSubsetOf(expected));
5701   expected.clear();
5702   numbers.push_back(1);
5703   numbers.push_back(2);
5704   EXPECT_THAT(numbers, Not(IsSubsetOf(expected)));
5705   expected.push_back(1);
5706   EXPECT_THAT(numbers, Not(IsSubsetOf(expected)));
5707   expected.push_back(2);
5708   EXPECT_THAT(numbers, IsSubsetOf(expected));
5709   expected.push_back(3);
5710   EXPECT_THAT(numbers, IsSubsetOf(expected));
5711 }
5712
5713 TEST(IsSubsetOfTest, WorksForStreamlike) {
5714   const int a[5] = {1, 2};
5715   Streamlike<int> s(std::begin(a), std::end(a));
5716
5717   vector<int> expected;
5718   expected.push_back(1);
5719   EXPECT_THAT(s, Not(IsSubsetOf(expected)));
5720   expected.push_back(2);
5721   expected.push_back(5);
5722   EXPECT_THAT(s, IsSubsetOf(expected));
5723 }
5724
5725 TEST(IsSubsetOfTest, TakesStlContainer) {
5726   const int actual[] = {3, 1, 2};
5727
5728   ::std::list<int> expected;
5729   expected.push_back(1);
5730   expected.push_back(3);
5731   EXPECT_THAT(actual, Not(IsSubsetOf(expected)));
5732
5733   expected.push_back(2);
5734   expected.push_back(4);
5735   EXPECT_THAT(actual, IsSubsetOf(expected));
5736 }
5737
5738 TEST(IsSubsetOfTest, Describe) {
5739   typedef std::vector<int> IntVec;
5740   IntVec expected;
5741   expected.push_back(111);
5742   expected.push_back(222);
5743   expected.push_back(333);
5744
5745   EXPECT_THAT(
5746       Describe<IntVec>(IsSubsetOf(expected)),
5747       Eq("an injection from elements to requirements exists such that:\n"
5748          " - an element is equal to 111\n"
5749          " - an element is equal to 222\n"
5750          " - an element is equal to 333"));
5751 }
5752
5753 TEST(IsSubsetOfTest, DescribeNegation) {
5754   typedef std::vector<int> IntVec;
5755   IntVec expected;
5756   expected.push_back(111);
5757   expected.push_back(222);
5758   expected.push_back(333);
5759   EXPECT_THAT(
5760       DescribeNegation<IntVec>(IsSubsetOf(expected)),
5761       Eq("no injection from elements to requirements exists such that:\n"
5762          " - an element is equal to 111\n"
5763          " - an element is equal to 222\n"
5764          " - an element is equal to 333"));
5765 }
5766
5767 TEST(IsSubsetOfTest, MatchAndExplain) {
5768   std::vector<int> v;
5769   v.push_back(2);
5770   v.push_back(3);
5771   std::vector<int> expected;
5772   expected.push_back(1);
5773   expected.push_back(2);
5774   StringMatchResultListener listener;
5775   ASSERT_FALSE(ExplainMatchResult(IsSubsetOf(expected), v, &listener))
5776       << listener.str();
5777   EXPECT_THAT(listener.str(),
5778               Eq("where the following elements don't match any matchers:\n"
5779                  "element #1: 3"));
5780
5781   expected.push_back(3);
5782   listener.Clear();
5783   ASSERT_TRUE(ExplainMatchResult(IsSubsetOf(expected), v, &listener))
5784       << listener.str();
5785   EXPECT_THAT(listener.str(), Eq("where:\n"
5786                                  " - element #0 is matched by matcher #1,\n"
5787                                  " - element #1 is matched by matcher #2"));
5788 }
5789
5790 TEST(IsSubsetOfTest, WorksForRhsInitializerList) {
5791   const int numbers[] = {1, 2, 3};
5792   EXPECT_THAT(numbers, IsSubsetOf({1, 2, 3, 4}));
5793   EXPECT_THAT(numbers, Not(IsSubsetOf({1, 2})));
5794 }
5795
5796 TEST(IsSubsetOfTest, WorksWithMoveOnly) {
5797   ContainerHelper helper;
5798   EXPECT_CALL(helper, Call(IsSubsetOf({Pointee(1), Pointee(2)})));
5799   helper.Call(MakeUniquePtrs({1}));
5800   EXPECT_CALL(helper, Call(Not(IsSubsetOf({Pointee(1)}))));
5801   helper.Call(MakeUniquePtrs({2}));
5802 }
5803
5804 // Tests using ElementsAre() and ElementsAreArray() with stream-like
5805 // "containers".
5806
5807 TEST(ElemensAreStreamTest, WorksForStreamlike) {
5808   const int a[5] = {1, 2, 3, 4, 5};
5809   Streamlike<int> s(std::begin(a), std::end(a));
5810   EXPECT_THAT(s, ElementsAre(1, 2, 3, 4, 5));
5811   EXPECT_THAT(s, Not(ElementsAre(2, 1, 4, 5, 3)));
5812 }
5813
5814 TEST(ElemensAreArrayStreamTest, WorksForStreamlike) {
5815   const int a[5] = {1, 2, 3, 4, 5};
5816   Streamlike<int> s(std::begin(a), std::end(a));
5817
5818   vector<int> expected;
5819   expected.push_back(1);
5820   expected.push_back(2);
5821   expected.push_back(3);
5822   expected.push_back(4);
5823   expected.push_back(5);
5824   EXPECT_THAT(s, ElementsAreArray(expected));
5825
5826   expected[3] = 0;
5827   EXPECT_THAT(s, Not(ElementsAreArray(expected)));
5828 }
5829
5830 TEST(ElementsAreTest, WorksWithUncopyable) {
5831   Uncopyable objs[2];
5832   objs[0].set_value(-3);
5833   objs[1].set_value(1);
5834   EXPECT_THAT(objs, ElementsAre(UncopyableIs(-3), Truly(ValueIsPositive)));
5835 }
5836
5837 TEST(ElementsAreTest, WorksWithMoveOnly) {
5838   ContainerHelper helper;
5839   EXPECT_CALL(helper, Call(ElementsAre(Pointee(1), Pointee(2))));
5840   helper.Call(MakeUniquePtrs({1, 2}));
5841
5842   EXPECT_CALL(helper, Call(ElementsAreArray({Pointee(3), Pointee(4)})));
5843   helper.Call(MakeUniquePtrs({3, 4}));
5844 }
5845
5846 TEST(ElementsAreTest, TakesStlContainer) {
5847   const int actual[] = {3, 1, 2};
5848
5849   ::std::list<int> expected;
5850   expected.push_back(3);
5851   expected.push_back(1);
5852   expected.push_back(2);
5853   EXPECT_THAT(actual, ElementsAreArray(expected));
5854
5855   expected.push_back(4);
5856   EXPECT_THAT(actual, Not(ElementsAreArray(expected)));
5857 }
5858
5859 // Tests for UnorderedElementsAreArray()
5860
5861 TEST(UnorderedElementsAreArrayTest, SucceedsWhenExpected) {
5862   const int a[] = {0, 1, 2, 3, 4};
5863   std::vector<int> s(std::begin(a), std::end(a));
5864   do {
5865     StringMatchResultListener listener;
5866     EXPECT_TRUE(ExplainMatchResult(UnorderedElementsAreArray(a),
5867                                    s, &listener)) << listener.str();
5868   } while (std::next_permutation(s.begin(), s.end()));
5869 }
5870
5871 TEST(UnorderedElementsAreArrayTest, VectorBool) {
5872   const bool a[] = {0, 1, 0, 1, 1};
5873   const bool b[] = {1, 0, 1, 1, 0};
5874   std::vector<bool> expected(std::begin(a), std::end(a));
5875   std::vector<bool> actual(std::begin(b), std::end(b));
5876   StringMatchResultListener listener;
5877   EXPECT_TRUE(ExplainMatchResult(UnorderedElementsAreArray(expected),
5878                                  actual, &listener)) << listener.str();
5879 }
5880
5881 TEST(UnorderedElementsAreArrayTest, WorksForStreamlike) {
5882   // Streamlike 'container' provides only minimal iterator support.
5883   // Its iterators are tagged with input_iterator_tag, and it has no
5884   // size() or empty() methods.
5885   const int a[5] = {2, 1, 4, 5, 3};
5886   Streamlike<int> s(std::begin(a), std::end(a));
5887
5888   ::std::vector<int> expected;
5889   expected.push_back(1);
5890   expected.push_back(2);
5891   expected.push_back(3);
5892   expected.push_back(4);
5893   expected.push_back(5);
5894   EXPECT_THAT(s, UnorderedElementsAreArray(expected));
5895
5896   expected.push_back(6);
5897   EXPECT_THAT(s, Not(UnorderedElementsAreArray(expected)));
5898 }
5899
5900 TEST(UnorderedElementsAreArrayTest, TakesStlContainer) {
5901   const int actual[] = {3, 1, 2};
5902
5903   ::std::list<int> expected;
5904   expected.push_back(1);
5905   expected.push_back(2);
5906   expected.push_back(3);
5907   EXPECT_THAT(actual, UnorderedElementsAreArray(expected));
5908
5909   expected.push_back(4);
5910   EXPECT_THAT(actual, Not(UnorderedElementsAreArray(expected)));
5911 }
5912
5913
5914 TEST(UnorderedElementsAreArrayTest, TakesInitializerList) {
5915   const int a[5] = {2, 1, 4, 5, 3};
5916   EXPECT_THAT(a, UnorderedElementsAreArray({1, 2, 3, 4, 5}));
5917   EXPECT_THAT(a, Not(UnorderedElementsAreArray({1, 2, 3, 4, 6})));
5918 }
5919
5920 TEST(UnorderedElementsAreArrayTest, TakesInitializerListOfCStrings) {
5921   const std::string a[5] = {"a", "b", "c", "d", "e"};
5922   EXPECT_THAT(a, UnorderedElementsAreArray({"a", "b", "c", "d", "e"}));
5923   EXPECT_THAT(a, Not(UnorderedElementsAreArray({"a", "b", "c", "d", "ef"})));
5924 }
5925
5926 TEST(UnorderedElementsAreArrayTest, TakesInitializerListOfSameTypedMatchers) {
5927   const int a[5] = {2, 1, 4, 5, 3};
5928   EXPECT_THAT(a, UnorderedElementsAreArray(
5929       {Eq(1), Eq(2), Eq(3), Eq(4), Eq(5)}));
5930   EXPECT_THAT(a, Not(UnorderedElementsAreArray(
5931       {Eq(1), Eq(2), Eq(3), Eq(4), Eq(6)})));
5932 }
5933
5934 TEST(UnorderedElementsAreArrayTest,
5935      TakesInitializerListOfDifferentTypedMatchers) {
5936   const int a[5] = {2, 1, 4, 5, 3};
5937   // The compiler cannot infer the type of the initializer list if its
5938   // elements have different types.  We must explicitly specify the
5939   // unified element type in this case.
5940   EXPECT_THAT(a, UnorderedElementsAreArray<Matcher<int> >(
5941       {Eq(1), Ne(-2), Ge(3), Le(4), Eq(5)}));
5942   EXPECT_THAT(a, Not(UnorderedElementsAreArray<Matcher<int> >(
5943       {Eq(1), Ne(-2), Ge(3), Le(4), Eq(6)})));
5944 }
5945
5946
5947 TEST(UnorderedElementsAreArrayTest, WorksWithMoveOnly) {
5948   ContainerHelper helper;
5949   EXPECT_CALL(helper,
5950               Call(UnorderedElementsAreArray({Pointee(1), Pointee(2)})));
5951   helper.Call(MakeUniquePtrs({2, 1}));
5952 }
5953
5954 class UnorderedElementsAreTest : public testing::Test {
5955  protected:
5956   typedef std::vector<int> IntVec;
5957 };
5958
5959 TEST_F(UnorderedElementsAreTest, WorksWithUncopyable) {
5960   Uncopyable objs[2];
5961   objs[0].set_value(-3);
5962   objs[1].set_value(1);
5963   EXPECT_THAT(objs,
5964               UnorderedElementsAre(Truly(ValueIsPositive), UncopyableIs(-3)));
5965 }
5966
5967 TEST_F(UnorderedElementsAreTest, SucceedsWhenExpected) {
5968   const int a[] = {1, 2, 3};
5969   std::vector<int> s(std::begin(a), std::end(a));
5970   do {
5971     StringMatchResultListener listener;
5972     EXPECT_TRUE(ExplainMatchResult(UnorderedElementsAre(1, 2, 3),
5973                                    s, &listener)) << listener.str();
5974   } while (std::next_permutation(s.begin(), s.end()));
5975 }
5976
5977 TEST_F(UnorderedElementsAreTest, FailsWhenAnElementMatchesNoMatcher) {
5978   const int a[] = {1, 2, 3};
5979   std::vector<int> s(std::begin(a), std::end(a));
5980   std::vector<Matcher<int> > mv;
5981   mv.push_back(1);
5982   mv.push_back(2);
5983   mv.push_back(2);
5984   // The element with value '3' matches nothing: fail fast.
5985   StringMatchResultListener listener;
5986   EXPECT_FALSE(ExplainMatchResult(UnorderedElementsAreArray(mv),
5987                                   s, &listener)) << listener.str();
5988 }
5989
5990 TEST_F(UnorderedElementsAreTest, WorksForStreamlike) {
5991   // Streamlike 'container' provides only minimal iterator support.
5992   // Its iterators are tagged with input_iterator_tag, and it has no
5993   // size() or empty() methods.
5994   const int a[5] = {2, 1, 4, 5, 3};
5995   Streamlike<int> s(std::begin(a), std::end(a));
5996
5997   EXPECT_THAT(s, UnorderedElementsAre(1, 2, 3, 4, 5));
5998   EXPECT_THAT(s, Not(UnorderedElementsAre(2, 2, 3, 4, 5)));
5999 }
6000
6001 TEST_F(UnorderedElementsAreTest, WorksWithMoveOnly) {
6002   ContainerHelper helper;
6003   EXPECT_CALL(helper, Call(UnorderedElementsAre(Pointee(1), Pointee(2))));
6004   helper.Call(MakeUniquePtrs({2, 1}));
6005 }
6006
6007 // One naive implementation of the matcher runs in O(N!) time, which is too
6008 // slow for many real-world inputs. This test shows that our matcher can match
6009 // 100 inputs very quickly (a few milliseconds).  An O(100!) is 10^158
6010 // iterations and obviously effectively incomputable.
6011 // [ RUN      ] UnorderedElementsAreTest.Performance
6012 // [       OK ] UnorderedElementsAreTest.Performance (4 ms)
6013 TEST_F(UnorderedElementsAreTest, Performance) {
6014   std::vector<int> s;
6015   std::vector<Matcher<int> > mv;
6016   for (int i = 0; i < 100; ++i) {
6017     s.push_back(i);
6018     mv.push_back(_);
6019   }
6020   mv[50] = Eq(0);
6021   StringMatchResultListener listener;
6022   EXPECT_TRUE(ExplainMatchResult(UnorderedElementsAreArray(mv),
6023                                  s, &listener)) << listener.str();
6024 }
6025
6026 // Another variant of 'Performance' with similar expectations.
6027 // [ RUN      ] UnorderedElementsAreTest.PerformanceHalfStrict
6028 // [       OK ] UnorderedElementsAreTest.PerformanceHalfStrict (4 ms)
6029 TEST_F(UnorderedElementsAreTest, PerformanceHalfStrict) {
6030   std::vector<int> s;
6031   std::vector<Matcher<int> > mv;
6032   for (int i = 0; i < 100; ++i) {
6033     s.push_back(i);
6034     if (i & 1) {
6035       mv.push_back(_);
6036     } else {
6037       mv.push_back(i);
6038     }
6039   }
6040   StringMatchResultListener listener;
6041   EXPECT_TRUE(ExplainMatchResult(UnorderedElementsAreArray(mv),
6042                                  s, &listener)) << listener.str();
6043 }
6044
6045 TEST_F(UnorderedElementsAreTest, FailMessageCountWrong) {
6046   std::vector<int> v;
6047   v.push_back(4);
6048   StringMatchResultListener listener;
6049   EXPECT_FALSE(ExplainMatchResult(UnorderedElementsAre(1, 2, 3),
6050                                   v, &listener)) << listener.str();
6051   EXPECT_THAT(listener.str(), Eq("which has 1 element"));
6052 }
6053
6054 TEST_F(UnorderedElementsAreTest, FailMessageCountWrongZero) {
6055   std::vector<int> v;
6056   StringMatchResultListener listener;
6057   EXPECT_FALSE(ExplainMatchResult(UnorderedElementsAre(1, 2, 3),
6058                                   v, &listener)) << listener.str();
6059   EXPECT_THAT(listener.str(), Eq(""));
6060 }
6061
6062 TEST_F(UnorderedElementsAreTest, FailMessageUnmatchedMatchers) {
6063   std::vector<int> v;
6064   v.push_back(1);
6065   v.push_back(1);
6066   StringMatchResultListener listener;
6067   EXPECT_FALSE(ExplainMatchResult(UnorderedElementsAre(1, 2),
6068                                   v, &listener)) << listener.str();
6069   EXPECT_THAT(
6070       listener.str(),
6071       Eq("where the following matchers don't match any elements:\n"
6072          "matcher #1: is equal to 2"));
6073 }
6074
6075 TEST_F(UnorderedElementsAreTest, FailMessageUnmatchedElements) {
6076   std::vector<int> v;
6077   v.push_back(1);
6078   v.push_back(2);
6079   StringMatchResultListener listener;
6080   EXPECT_FALSE(ExplainMatchResult(UnorderedElementsAre(1, 1),
6081                                   v, &listener)) << listener.str();
6082   EXPECT_THAT(
6083       listener.str(),
6084       Eq("where the following elements don't match any matchers:\n"
6085          "element #1: 2"));
6086 }
6087
6088 TEST_F(UnorderedElementsAreTest, FailMessageUnmatchedMatcherAndElement) {
6089   std::vector<int> v;
6090   v.push_back(2);
6091   v.push_back(3);
6092   StringMatchResultListener listener;
6093   EXPECT_FALSE(ExplainMatchResult(UnorderedElementsAre(1, 2),
6094                                   v, &listener)) << listener.str();
6095   EXPECT_THAT(
6096       listener.str(),
6097       Eq("where"
6098          " the following matchers don't match any elements:\n"
6099          "matcher #0: is equal to 1\n"
6100          "and"
6101          " where"
6102          " the following elements don't match any matchers:\n"
6103          "element #1: 3"));
6104 }
6105
6106 // Test helper for formatting element, matcher index pairs in expectations.
6107 static std::string EMString(int element, int matcher) {
6108   stringstream ss;
6109   ss << "(element #" << element << ", matcher #" << matcher << ")";
6110   return ss.str();
6111 }
6112
6113 TEST_F(UnorderedElementsAreTest, FailMessageImperfectMatchOnly) {
6114   // A situation where all elements and matchers have a match
6115   // associated with them, but the max matching is not perfect.
6116   std::vector<std::string> v;
6117   v.push_back("a");
6118   v.push_back("b");
6119   v.push_back("c");
6120   StringMatchResultListener listener;
6121   EXPECT_FALSE(ExplainMatchResult(
6122       UnorderedElementsAre("a", "a", AnyOf("b", "c")), v, &listener))
6123       << listener.str();
6124
6125   std::string prefix =
6126       "where no permutation of the elements can satisfy all matchers, "
6127       "and the closest match is 2 of 3 matchers with the "
6128       "pairings:\n";
6129
6130   // We have to be a bit loose here, because there are 4 valid max matches.
6131   EXPECT_THAT(
6132       listener.str(),
6133       AnyOf(prefix + "{\n  " + EMString(0, 0) +
6134                      ",\n  " + EMString(1, 2) + "\n}",
6135             prefix + "{\n  " + EMString(0, 1) +
6136                      ",\n  " + EMString(1, 2) + "\n}",
6137             prefix + "{\n  " + EMString(0, 0) +
6138                      ",\n  " + EMString(2, 2) + "\n}",
6139             prefix + "{\n  " + EMString(0, 1) +
6140                      ",\n  " + EMString(2, 2) + "\n}"));
6141 }
6142
6143 TEST_F(UnorderedElementsAreTest, Describe) {
6144   EXPECT_THAT(Describe<IntVec>(UnorderedElementsAre()),
6145               Eq("is empty"));
6146   EXPECT_THAT(
6147       Describe<IntVec>(UnorderedElementsAre(345)),
6148       Eq("has 1 element and that element is equal to 345"));
6149   EXPECT_THAT(
6150       Describe<IntVec>(UnorderedElementsAre(111, 222, 333)),
6151       Eq("has 3 elements and there exists some permutation "
6152          "of elements such that:\n"
6153          " - element #0 is equal to 111, and\n"
6154          " - element #1 is equal to 222, and\n"
6155          " - element #2 is equal to 333"));
6156 }
6157
6158 TEST_F(UnorderedElementsAreTest, DescribeNegation) {
6159   EXPECT_THAT(DescribeNegation<IntVec>(UnorderedElementsAre()),
6160               Eq("isn't empty"));
6161   EXPECT_THAT(
6162       DescribeNegation<IntVec>(UnorderedElementsAre(345)),
6163       Eq("doesn't have 1 element, or has 1 element that isn't equal to 345"));
6164   EXPECT_THAT(
6165       DescribeNegation<IntVec>(UnorderedElementsAre(123, 234, 345)),
6166       Eq("doesn't have 3 elements, or there exists no permutation "
6167          "of elements such that:\n"
6168          " - element #0 is equal to 123, and\n"
6169          " - element #1 is equal to 234, and\n"
6170          " - element #2 is equal to 345"));
6171 }
6172
6173 namespace {
6174
6175 // Used as a check on the more complex max flow method used in the
6176 // real testing::internal::FindMaxBipartiteMatching. This method is
6177 // compatible but runs in worst-case factorial time, so we only
6178 // use it in testing for small problem sizes.
6179 template <typename Graph>
6180 class BacktrackingMaxBPMState {
6181  public:
6182   // Does not take ownership of 'g'.
6183   explicit BacktrackingMaxBPMState(const Graph* g) : graph_(g) { }
6184
6185   ElementMatcherPairs Compute() {
6186     if (graph_->LhsSize() == 0 || graph_->RhsSize() == 0) {
6187       return best_so_far_;
6188     }
6189     lhs_used_.assign(graph_->LhsSize(), kUnused);
6190     rhs_used_.assign(graph_->RhsSize(), kUnused);
6191     for (size_t irhs = 0; irhs < graph_->RhsSize(); ++irhs) {
6192       matches_.clear();
6193       RecurseInto(irhs);
6194       if (best_so_far_.size() == graph_->RhsSize())
6195         break;
6196     }
6197     return best_so_far_;
6198   }
6199
6200  private:
6201   static const size_t kUnused = static_cast<size_t>(-1);
6202
6203   void PushMatch(size_t lhs, size_t rhs) {
6204     matches_.push_back(ElementMatcherPair(lhs, rhs));
6205     lhs_used_[lhs] = rhs;
6206     rhs_used_[rhs] = lhs;
6207     if (matches_.size() > best_so_far_.size()) {
6208       best_so_far_ = matches_;
6209     }
6210   }
6211
6212   void PopMatch() {
6213     const ElementMatcherPair& back = matches_.back();
6214     lhs_used_[back.first] = kUnused;
6215     rhs_used_[back.second] = kUnused;
6216     matches_.pop_back();
6217   }
6218
6219   bool RecurseInto(size_t irhs) {
6220     if (rhs_used_[irhs] != kUnused) {
6221       return true;
6222     }
6223     for (size_t ilhs = 0; ilhs < graph_->LhsSize(); ++ilhs) {
6224       if (lhs_used_[ilhs] != kUnused) {
6225         continue;
6226       }
6227       if (!graph_->HasEdge(ilhs, irhs)) {
6228         continue;
6229       }
6230       PushMatch(ilhs, irhs);
6231       if (best_so_far_.size() == graph_->RhsSize()) {
6232         return false;
6233       }
6234       for (size_t mi = irhs + 1; mi < graph_->RhsSize(); ++mi) {
6235         if (!RecurseInto(mi)) return false;
6236       }
6237       PopMatch();
6238     }
6239     return true;
6240   }
6241
6242   const Graph* graph_;  // not owned
6243   std::vector<size_t> lhs_used_;
6244   std::vector<size_t> rhs_used_;
6245   ElementMatcherPairs matches_;
6246   ElementMatcherPairs best_so_far_;
6247 };
6248
6249 template <typename Graph>
6250 const size_t BacktrackingMaxBPMState<Graph>::kUnused;
6251
6252 }  // namespace
6253
6254 // Implement a simple backtracking algorithm to determine if it is possible
6255 // to find one element per matcher, without reusing elements.
6256 template <typename Graph>
6257 ElementMatcherPairs
6258 FindBacktrackingMaxBPM(const Graph& g) {
6259   return BacktrackingMaxBPMState<Graph>(&g).Compute();
6260 }
6261
6262 class BacktrackingBPMTest : public ::testing::Test { };
6263
6264 // Tests the MaxBipartiteMatching algorithm with square matrices.
6265 // The single int param is the # of nodes on each of the left and right sides.
6266 class BipartiteTest : public ::testing::TestWithParam<size_t> {};
6267
6268 // Verify all match graphs up to some moderate number of edges.
6269 TEST_P(BipartiteTest, Exhaustive) {
6270   size_t nodes = GetParam();
6271   MatchMatrix graph(nodes, nodes);
6272   do {
6273     ElementMatcherPairs matches =
6274         internal::FindMaxBipartiteMatching(graph);
6275     EXPECT_EQ(FindBacktrackingMaxBPM(graph).size(), matches.size())
6276         << "graph: " << graph.DebugString();
6277     // Check that all elements of matches are in the graph.
6278     // Check that elements of first and second are unique.
6279     std::vector<bool> seen_element(graph.LhsSize());
6280     std::vector<bool> seen_matcher(graph.RhsSize());
6281     SCOPED_TRACE(PrintToString(matches));
6282     for (size_t i = 0; i < matches.size(); ++i) {
6283       size_t ilhs = matches[i].first;
6284       size_t irhs = matches[i].second;
6285       EXPECT_TRUE(graph.HasEdge(ilhs, irhs));
6286       EXPECT_FALSE(seen_element[ilhs]);
6287       EXPECT_FALSE(seen_matcher[irhs]);
6288       seen_element[ilhs] = true;
6289       seen_matcher[irhs] = true;
6290     }
6291   } while (graph.NextGraph());
6292 }
6293
6294 INSTANTIATE_TEST_SUITE_P(AllGraphs, BipartiteTest,
6295                          ::testing::Range(size_t{0}, size_t{5}));
6296
6297 // Parameterized by a pair interpreted as (LhsSize, RhsSize).
6298 class BipartiteNonSquareTest
6299     : public ::testing::TestWithParam<std::pair<size_t, size_t> > {
6300 };
6301
6302 TEST_F(BipartiteNonSquareTest, SimpleBacktracking) {
6303   //   .......
6304   // 0:-----\ :
6305   // 1:---\ | :
6306   // 2:---\ | :
6307   // 3:-\ | | :
6308   //  :.......:
6309   //    0 1 2
6310   MatchMatrix g(4, 3);
6311   constexpr std::array<std::array<size_t, 2>, 4> kEdges = {
6312       {{{0, 2}}, {{1, 1}}, {{2, 1}}, {{3, 0}}}};
6313   for (size_t i = 0; i < kEdges.size(); ++i) {
6314     g.SetEdge(kEdges[i][0], kEdges[i][1], true);
6315   }
6316   EXPECT_THAT(FindBacktrackingMaxBPM(g),
6317               ElementsAre(Pair(3, 0),
6318                           Pair(AnyOf(1, 2), 1),
6319                           Pair(0, 2))) << g.DebugString();
6320 }
6321
6322 // Verify a few nonsquare matrices.
6323 TEST_P(BipartiteNonSquareTest, Exhaustive) {
6324   size_t nlhs = GetParam().first;
6325   size_t nrhs = GetParam().second;
6326   MatchMatrix graph(nlhs, nrhs);
6327   do {
6328     EXPECT_EQ(FindBacktrackingMaxBPM(graph).size(),
6329               internal::FindMaxBipartiteMatching(graph).size())
6330         << "graph: " << graph.DebugString()
6331         << "\nbacktracking: "
6332         << PrintToString(FindBacktrackingMaxBPM(graph))
6333         << "\nmax flow: "
6334         << PrintToString(internal::FindMaxBipartiteMatching(graph));
6335   } while (graph.NextGraph());
6336 }
6337
6338 INSTANTIATE_TEST_SUITE_P(AllGraphs, BipartiteNonSquareTest,
6339     testing::Values(
6340         std::make_pair(1, 2),
6341         std::make_pair(2, 1),
6342         std::make_pair(3, 2),
6343         std::make_pair(2, 3),
6344         std::make_pair(4, 1),
6345         std::make_pair(1, 4),
6346         std::make_pair(4, 3),
6347         std::make_pair(3, 4)));
6348
6349 class BipartiteRandomTest
6350     : public ::testing::TestWithParam<std::pair<int, int> > {
6351 };
6352
6353 // Verifies a large sample of larger graphs.
6354 TEST_P(BipartiteRandomTest, LargerNets) {
6355   int nodes = GetParam().first;
6356   int iters = GetParam().second;
6357   MatchMatrix graph(static_cast<size_t>(nodes), static_cast<size_t>(nodes));
6358
6359   auto seed = static_cast<uint32_t>(GTEST_FLAG_GET(random_seed));
6360   if (seed == 0) {
6361     seed = static_cast<uint32_t>(time(nullptr));
6362   }
6363
6364   for (; iters > 0; --iters, ++seed) {
6365     srand(static_cast<unsigned int>(seed));
6366     graph.Randomize();
6367     EXPECT_EQ(FindBacktrackingMaxBPM(graph).size(),
6368               internal::FindMaxBipartiteMatching(graph).size())
6369         << " graph: " << graph.DebugString()
6370         << "\nTo reproduce the failure, rerun the test with the flag"
6371            " --" << GTEST_FLAG_PREFIX_ << "random_seed=" << seed;
6372   }
6373 }
6374
6375 // Test argument is a std::pair<int, int> representing (nodes, iters).
6376 INSTANTIATE_TEST_SUITE_P(Samples, BipartiteRandomTest,
6377     testing::Values(
6378         std::make_pair(5, 10000),
6379         std::make_pair(6, 5000),
6380         std::make_pair(7, 2000),
6381         std::make_pair(8, 500),
6382         std::make_pair(9, 100)));
6383
6384 // Tests IsReadableTypeName().
6385
6386 TEST(IsReadableTypeNameTest, ReturnsTrueForShortNames) {
6387   EXPECT_TRUE(IsReadableTypeName("int"));
6388   EXPECT_TRUE(IsReadableTypeName("const unsigned char*"));
6389   EXPECT_TRUE(IsReadableTypeName("MyMap<int, void*>"));
6390   EXPECT_TRUE(IsReadableTypeName("void (*)(int, bool)"));
6391 }
6392
6393 TEST(IsReadableTypeNameTest, ReturnsTrueForLongNonTemplateNonFunctionNames) {
6394   EXPECT_TRUE(IsReadableTypeName("my_long_namespace::MyClassName"));
6395   EXPECT_TRUE(IsReadableTypeName("int [5][6][7][8][9][10][11]"));
6396   EXPECT_TRUE(IsReadableTypeName("my_namespace::MyOuterClass::MyInnerClass"));
6397 }
6398
6399 TEST(IsReadableTypeNameTest, ReturnsFalseForLongTemplateNames) {
6400   EXPECT_FALSE(
6401       IsReadableTypeName("basic_string<char, std::char_traits<char> >"));
6402   EXPECT_FALSE(IsReadableTypeName("std::vector<int, std::alloc_traits<int> >"));
6403 }
6404
6405 TEST(IsReadableTypeNameTest, ReturnsFalseForLongFunctionTypeNames) {
6406   EXPECT_FALSE(IsReadableTypeName("void (&)(int, bool, char, float)"));
6407 }
6408
6409 // Tests FormatMatcherDescription().
6410
6411 TEST(FormatMatcherDescriptionTest, WorksForEmptyDescription) {
6412   EXPECT_EQ("is even",
6413             FormatMatcherDescription(false, "IsEven", Strings()));
6414   EXPECT_EQ("not (is even)",
6415             FormatMatcherDescription(true, "IsEven", Strings()));
6416
6417   const char* params[] = {"5"};
6418   EXPECT_EQ("equals 5",
6419             FormatMatcherDescription(false, "Equals",
6420                                      Strings(params, params + 1)));
6421
6422   const char* params2[] = {"5", "8"};
6423   EXPECT_EQ("is in range (5, 8)",
6424             FormatMatcherDescription(false, "IsInRange",
6425                                      Strings(params2, params2 + 2)));
6426 }
6427
6428 // Tests PolymorphicMatcher::mutable_impl().
6429 TEST(PolymorphicMatcherTest, CanAccessMutableImpl) {
6430   PolymorphicMatcher<DivisibleByImpl> m(DivisibleByImpl(42));
6431   DivisibleByImpl& impl = m.mutable_impl();
6432   EXPECT_EQ(42, impl.divider());
6433
6434   impl.set_divider(0);
6435   EXPECT_EQ(0, m.mutable_impl().divider());
6436 }
6437
6438 // Tests PolymorphicMatcher::impl().
6439 TEST(PolymorphicMatcherTest, CanAccessImpl) {
6440   const PolymorphicMatcher<DivisibleByImpl> m(DivisibleByImpl(42));
6441   const DivisibleByImpl& impl = m.impl();
6442   EXPECT_EQ(42, impl.divider());
6443 }
6444
6445 TEST(MatcherTupleTest, ExplainsMatchFailure) {
6446   stringstream ss1;
6447   ExplainMatchFailureTupleTo(
6448       std::make_tuple(Matcher<char>(Eq('a')), GreaterThan(5)),
6449       std::make_tuple('a', 10), &ss1);
6450   EXPECT_EQ("", ss1.str());  // Successful match.
6451
6452   stringstream ss2;
6453   ExplainMatchFailureTupleTo(
6454       std::make_tuple(GreaterThan(5), Matcher<char>(Eq('a'))),
6455       std::make_tuple(2, 'b'), &ss2);
6456   EXPECT_EQ("  Expected arg #0: is > 5\n"
6457             "           Actual: 2, which is 3 less than 5\n"
6458             "  Expected arg #1: is equal to 'a' (97, 0x61)\n"
6459             "           Actual: 'b' (98, 0x62)\n",
6460             ss2.str());  // Failed match where both arguments need explanation.
6461
6462   stringstream ss3;
6463   ExplainMatchFailureTupleTo(
6464       std::make_tuple(GreaterThan(5), Matcher<char>(Eq('a'))),
6465       std::make_tuple(2, 'a'), &ss3);
6466   EXPECT_EQ("  Expected arg #0: is > 5\n"
6467             "           Actual: 2, which is 3 less than 5\n",
6468             ss3.str());  // Failed match where only one argument needs
6469                          // explanation.
6470 }
6471
6472 // Tests Each().
6473
6474 TEST(EachTest, ExplainsMatchResultCorrectly) {
6475   set<int> a;  // empty
6476
6477   Matcher<set<int> > m = Each(2);
6478   EXPECT_EQ("", Explain(m, a));
6479
6480   Matcher<const int(&)[1]> n = Each(1);  // NOLINT
6481
6482   const int b[1] = {1};
6483   EXPECT_EQ("", Explain(n, b));
6484
6485   n = Each(3);
6486   EXPECT_EQ("whose element #0 doesn't match", Explain(n, b));
6487
6488   a.insert(1);
6489   a.insert(2);
6490   a.insert(3);
6491   m = Each(GreaterThan(0));
6492   EXPECT_EQ("", Explain(m, a));
6493
6494   m = Each(GreaterThan(10));
6495   EXPECT_EQ("whose element #0 doesn't match, which is 9 less than 10",
6496             Explain(m, a));
6497 }
6498
6499 TEST(EachTest, DescribesItselfCorrectly) {
6500   Matcher<vector<int> > m = Each(1);
6501   EXPECT_EQ("only contains elements that is equal to 1", Describe(m));
6502
6503   Matcher<vector<int> > m2 = Not(m);
6504   EXPECT_EQ("contains some element that isn't equal to 1", Describe(m2));
6505 }
6506
6507 TEST(EachTest, MatchesVectorWhenAllElementsMatch) {
6508   vector<int> some_vector;
6509   EXPECT_THAT(some_vector, Each(1));
6510   some_vector.push_back(3);
6511   EXPECT_THAT(some_vector, Not(Each(1)));
6512   EXPECT_THAT(some_vector, Each(3));
6513   some_vector.push_back(1);
6514   some_vector.push_back(2);
6515   EXPECT_THAT(some_vector, Not(Each(3)));
6516   EXPECT_THAT(some_vector, Each(Lt(3.5)));
6517
6518   vector<std::string> another_vector;
6519   another_vector.push_back("fee");
6520   EXPECT_THAT(another_vector, Each(std::string("fee")));
6521   another_vector.push_back("fie");
6522   another_vector.push_back("foe");
6523   another_vector.push_back("fum");
6524   EXPECT_THAT(another_vector, Not(Each(std::string("fee"))));
6525 }
6526
6527 TEST(EachTest, MatchesMapWhenAllElementsMatch) {
6528   map<const char*, int> my_map;
6529   const char* bar = "a string";
6530   my_map[bar] = 2;
6531   EXPECT_THAT(my_map, Each(make_pair(bar, 2)));
6532
6533   map<std::string, int> another_map;
6534   EXPECT_THAT(another_map, Each(make_pair(std::string("fee"), 1)));
6535   another_map["fee"] = 1;
6536   EXPECT_THAT(another_map, Each(make_pair(std::string("fee"), 1)));
6537   another_map["fie"] = 2;
6538   another_map["foe"] = 3;
6539   another_map["fum"] = 4;
6540   EXPECT_THAT(another_map, Not(Each(make_pair(std::string("fee"), 1))));
6541   EXPECT_THAT(another_map, Not(Each(make_pair(std::string("fum"), 1))));
6542   EXPECT_THAT(another_map, Each(Pair(_, Gt(0))));
6543 }
6544
6545 TEST(EachTest, AcceptsMatcher) {
6546   const int a[] = {1, 2, 3};
6547   EXPECT_THAT(a, Each(Gt(0)));
6548   EXPECT_THAT(a, Not(Each(Gt(1))));
6549 }
6550
6551 TEST(EachTest, WorksForNativeArrayAsTuple) {
6552   const int a[] = {1, 2};
6553   const int* const pointer = a;
6554   EXPECT_THAT(std::make_tuple(pointer, 2), Each(Gt(0)));
6555   EXPECT_THAT(std::make_tuple(pointer, 2), Not(Each(Gt(1))));
6556 }
6557
6558 TEST(EachTest, WorksWithMoveOnly) {
6559   ContainerHelper helper;
6560   EXPECT_CALL(helper, Call(Each(Pointee(Gt(0)))));
6561   helper.Call(MakeUniquePtrs({1, 2}));
6562 }
6563
6564 // For testing Pointwise().
6565 class IsHalfOfMatcher {
6566  public:
6567   template <typename T1, typename T2>
6568   bool MatchAndExplain(const std::tuple<T1, T2>& a_pair,
6569                        MatchResultListener* listener) const {
6570     if (std::get<0>(a_pair) == std::get<1>(a_pair) / 2) {
6571       *listener << "where the second is " << std::get<1>(a_pair);
6572       return true;
6573     } else {
6574       *listener << "where the second/2 is " << std::get<1>(a_pair) / 2;
6575       return false;
6576     }
6577   }
6578
6579   void DescribeTo(ostream* os) const {
6580     *os << "are a pair where the first is half of the second";
6581   }
6582
6583   void DescribeNegationTo(ostream* os) const {
6584     *os << "are a pair where the first isn't half of the second";
6585   }
6586 };
6587
6588 PolymorphicMatcher<IsHalfOfMatcher> IsHalfOf() {
6589   return MakePolymorphicMatcher(IsHalfOfMatcher());
6590 }
6591
6592 TEST(PointwiseTest, DescribesSelf) {
6593   vector<int> rhs;
6594   rhs.push_back(1);
6595   rhs.push_back(2);
6596   rhs.push_back(3);
6597   const Matcher<const vector<int>&> m = Pointwise(IsHalfOf(), rhs);
6598   EXPECT_EQ("contains 3 values, where each value and its corresponding value "
6599             "in { 1, 2, 3 } are a pair where the first is half of the second",
6600             Describe(m));
6601   EXPECT_EQ("doesn't contain exactly 3 values, or contains a value x at some "
6602             "index i where x and the i-th value of { 1, 2, 3 } are a pair "
6603             "where the first isn't half of the second",
6604             DescribeNegation(m));
6605 }
6606
6607 TEST(PointwiseTest, MakesCopyOfRhs) {
6608   list<signed char> rhs;
6609   rhs.push_back(2);
6610   rhs.push_back(4);
6611
6612   int lhs[] = {1, 2};
6613   const Matcher<const int (&)[2]> m = Pointwise(IsHalfOf(), rhs);
6614   EXPECT_THAT(lhs, m);
6615
6616   // Changing rhs now shouldn't affect m, which made a copy of rhs.
6617   rhs.push_back(6);
6618   EXPECT_THAT(lhs, m);
6619 }
6620
6621 TEST(PointwiseTest, WorksForLhsNativeArray) {
6622   const int lhs[] = {1, 2, 3};
6623   vector<int> rhs;
6624   rhs.push_back(2);
6625   rhs.push_back(4);
6626   rhs.push_back(6);
6627   EXPECT_THAT(lhs, Pointwise(Lt(), rhs));
6628   EXPECT_THAT(lhs, Not(Pointwise(Gt(), rhs)));
6629 }
6630
6631 TEST(PointwiseTest, WorksForRhsNativeArray) {
6632   const int rhs[] = {1, 2, 3};
6633   vector<int> lhs;
6634   lhs.push_back(2);
6635   lhs.push_back(4);
6636   lhs.push_back(6);
6637   EXPECT_THAT(lhs, Pointwise(Gt(), rhs));
6638   EXPECT_THAT(lhs, Not(Pointwise(Lt(), rhs)));
6639 }
6640
6641 // Test is effective only with sanitizers.
6642 TEST(PointwiseTest, WorksForVectorOfBool) {
6643   vector<bool> rhs(3, false);
6644   rhs[1] = true;
6645   vector<bool> lhs = rhs;
6646   EXPECT_THAT(lhs, Pointwise(Eq(), rhs));
6647   rhs[0] = true;
6648   EXPECT_THAT(lhs, Not(Pointwise(Eq(), rhs)));
6649 }
6650
6651
6652 TEST(PointwiseTest, WorksForRhsInitializerList) {
6653   const vector<int> lhs{2, 4, 6};
6654   EXPECT_THAT(lhs, Pointwise(Gt(), {1, 2, 3}));
6655   EXPECT_THAT(lhs, Not(Pointwise(Lt(), {3, 3, 7})));
6656 }
6657
6658
6659 TEST(PointwiseTest, RejectsWrongSize) {
6660   const double lhs[2] = {1, 2};
6661   const int rhs[1] = {0};
6662   EXPECT_THAT(lhs, Not(Pointwise(Gt(), rhs)));
6663   EXPECT_EQ("which contains 2 values",
6664             Explain(Pointwise(Gt(), rhs), lhs));
6665
6666   const int rhs2[3] = {0, 1, 2};
6667   EXPECT_THAT(lhs, Not(Pointwise(Gt(), rhs2)));
6668 }
6669
6670 TEST(PointwiseTest, RejectsWrongContent) {
6671   const double lhs[3] = {1, 2, 3};
6672   const int rhs[3] = {2, 6, 4};
6673   EXPECT_THAT(lhs, Not(Pointwise(IsHalfOf(), rhs)));
6674   EXPECT_EQ("where the value pair (2, 6) at index #1 don't match, "
6675             "where the second/2 is 3",
6676             Explain(Pointwise(IsHalfOf(), rhs), lhs));
6677 }
6678
6679 TEST(PointwiseTest, AcceptsCorrectContent) {
6680   const double lhs[3] = {1, 2, 3};
6681   const int rhs[3] = {2, 4, 6};
6682   EXPECT_THAT(lhs, Pointwise(IsHalfOf(), rhs));
6683   EXPECT_EQ("", Explain(Pointwise(IsHalfOf(), rhs), lhs));
6684 }
6685
6686 TEST(PointwiseTest, AllowsMonomorphicInnerMatcher) {
6687   const double lhs[3] = {1, 2, 3};
6688   const int rhs[3] = {2, 4, 6};
6689   const Matcher<std::tuple<const double&, const int&>> m1 = IsHalfOf();
6690   EXPECT_THAT(lhs, Pointwise(m1, rhs));
6691   EXPECT_EQ("", Explain(Pointwise(m1, rhs), lhs));
6692
6693   // This type works as a std::tuple<const double&, const int&> can be
6694   // implicitly cast to std::tuple<double, int>.
6695   const Matcher<std::tuple<double, int>> m2 = IsHalfOf();
6696   EXPECT_THAT(lhs, Pointwise(m2, rhs));
6697   EXPECT_EQ("", Explain(Pointwise(m2, rhs), lhs));
6698 }
6699
6700 MATCHER(PointeeEquals, "Points to an equal value") {
6701   return ExplainMatchResult(::testing::Pointee(::testing::get<1>(arg)),
6702                             ::testing::get<0>(arg), result_listener);
6703 }
6704
6705 TEST(PointwiseTest, WorksWithMoveOnly) {
6706   ContainerHelper helper;
6707   EXPECT_CALL(helper, Call(Pointwise(PointeeEquals(), std::vector<int>{1, 2})));
6708   helper.Call(MakeUniquePtrs({1, 2}));
6709 }
6710
6711 TEST(UnorderedPointwiseTest, DescribesSelf) {
6712   vector<int> rhs;
6713   rhs.push_back(1);
6714   rhs.push_back(2);
6715   rhs.push_back(3);
6716   const Matcher<const vector<int>&> m = UnorderedPointwise(IsHalfOf(), rhs);
6717   EXPECT_EQ(
6718       "has 3 elements and there exists some permutation of elements such "
6719       "that:\n"
6720       " - element #0 and 1 are a pair where the first is half of the second, "
6721       "and\n"
6722       " - element #1 and 2 are a pair where the first is half of the second, "
6723       "and\n"
6724       " - element #2 and 3 are a pair where the first is half of the second",
6725       Describe(m));
6726   EXPECT_EQ(
6727       "doesn't have 3 elements, or there exists no permutation of elements "
6728       "such that:\n"
6729       " - element #0 and 1 are a pair where the first is half of the second, "
6730       "and\n"
6731       " - element #1 and 2 are a pair where the first is half of the second, "
6732       "and\n"
6733       " - element #2 and 3 are a pair where the first is half of the second",
6734       DescribeNegation(m));
6735 }
6736
6737 TEST(UnorderedPointwiseTest, MakesCopyOfRhs) {
6738   list<signed char> rhs;
6739   rhs.push_back(2);
6740   rhs.push_back(4);
6741
6742   int lhs[] = {2, 1};
6743   const Matcher<const int (&)[2]> m = UnorderedPointwise(IsHalfOf(), rhs);
6744   EXPECT_THAT(lhs, m);
6745
6746   // Changing rhs now shouldn't affect m, which made a copy of rhs.
6747   rhs.push_back(6);
6748   EXPECT_THAT(lhs, m);
6749 }
6750
6751 TEST(UnorderedPointwiseTest, WorksForLhsNativeArray) {
6752   const int lhs[] = {1, 2, 3};
6753   vector<int> rhs;
6754   rhs.push_back(4);
6755   rhs.push_back(6);
6756   rhs.push_back(2);
6757   EXPECT_THAT(lhs, UnorderedPointwise(Lt(), rhs));
6758   EXPECT_THAT(lhs, Not(UnorderedPointwise(Gt(), rhs)));
6759 }
6760
6761 TEST(UnorderedPointwiseTest, WorksForRhsNativeArray) {
6762   const int rhs[] = {1, 2, 3};
6763   vector<int> lhs;
6764   lhs.push_back(4);
6765   lhs.push_back(2);
6766   lhs.push_back(6);
6767   EXPECT_THAT(lhs, UnorderedPointwise(Gt(), rhs));
6768   EXPECT_THAT(lhs, Not(UnorderedPointwise(Lt(), rhs)));
6769 }
6770
6771
6772 TEST(UnorderedPointwiseTest, WorksForRhsInitializerList) {
6773   const vector<int> lhs{2, 4, 6};
6774   EXPECT_THAT(lhs, UnorderedPointwise(Gt(), {5, 1, 3}));
6775   EXPECT_THAT(lhs, Not(UnorderedPointwise(Lt(), {1, 1, 7})));
6776 }
6777
6778
6779 TEST(UnorderedPointwiseTest, RejectsWrongSize) {
6780   const double lhs[2] = {1, 2};
6781   const int rhs[1] = {0};
6782   EXPECT_THAT(lhs, Not(UnorderedPointwise(Gt(), rhs)));
6783   EXPECT_EQ("which has 2 elements",
6784             Explain(UnorderedPointwise(Gt(), rhs), lhs));
6785
6786   const int rhs2[3] = {0, 1, 2};
6787   EXPECT_THAT(lhs, Not(UnorderedPointwise(Gt(), rhs2)));
6788 }
6789
6790 TEST(UnorderedPointwiseTest, RejectsWrongContent) {
6791   const double lhs[3] = {1, 2, 3};
6792   const int rhs[3] = {2, 6, 6};
6793   EXPECT_THAT(lhs, Not(UnorderedPointwise(IsHalfOf(), rhs)));
6794   EXPECT_EQ("where the following elements don't match any matchers:\n"
6795             "element #1: 2",
6796             Explain(UnorderedPointwise(IsHalfOf(), rhs), lhs));
6797 }
6798
6799 TEST(UnorderedPointwiseTest, AcceptsCorrectContentInSameOrder) {
6800   const double lhs[3] = {1, 2, 3};
6801   const int rhs[3] = {2, 4, 6};
6802   EXPECT_THAT(lhs, UnorderedPointwise(IsHalfOf(), rhs));
6803 }
6804
6805 TEST(UnorderedPointwiseTest, AcceptsCorrectContentInDifferentOrder) {
6806   const double lhs[3] = {1, 2, 3};
6807   const int rhs[3] = {6, 4, 2};
6808   EXPECT_THAT(lhs, UnorderedPointwise(IsHalfOf(), rhs));
6809 }
6810
6811 TEST(UnorderedPointwiseTest, AllowsMonomorphicInnerMatcher) {
6812   const double lhs[3] = {1, 2, 3};
6813   const int rhs[3] = {4, 6, 2};
6814   const Matcher<std::tuple<const double&, const int&>> m1 = IsHalfOf();
6815   EXPECT_THAT(lhs, UnorderedPointwise(m1, rhs));
6816
6817   // This type works as a std::tuple<const double&, const int&> can be
6818   // implicitly cast to std::tuple<double, int>.
6819   const Matcher<std::tuple<double, int>> m2 = IsHalfOf();
6820   EXPECT_THAT(lhs, UnorderedPointwise(m2, rhs));
6821 }
6822
6823 TEST(UnorderedPointwiseTest, WorksWithMoveOnly) {
6824   ContainerHelper helper;
6825   EXPECT_CALL(helper, Call(UnorderedPointwise(PointeeEquals(),
6826                                               std::vector<int>{1, 2})));
6827   helper.Call(MakeUniquePtrs({2, 1}));
6828 }
6829
6830 // Sample optional type implementation with minimal requirements for use with
6831 // Optional matcher.
6832 template <typename T>
6833 class SampleOptional {
6834  public:
6835   using value_type = T;
6836   explicit SampleOptional(T value)
6837       : value_(std::move(value)), has_value_(true) {}
6838   SampleOptional() : value_(), has_value_(false) {}
6839   operator bool() const { return has_value_; }
6840   const T& operator*() const { return value_; }
6841
6842  private:
6843   T value_;
6844   bool has_value_;
6845 };
6846
6847 TEST(OptionalTest, DescribesSelf) {
6848   const Matcher<SampleOptional<int>> m = Optional(Eq(1));
6849   EXPECT_EQ("value is equal to 1", Describe(m));
6850 }
6851
6852 TEST(OptionalTest, ExplainsSelf) {
6853   const Matcher<SampleOptional<int>> m = Optional(Eq(1));
6854   EXPECT_EQ("whose value 1 matches", Explain(m, SampleOptional<int>(1)));
6855   EXPECT_EQ("whose value 2 doesn't match", Explain(m, SampleOptional<int>(2)));
6856 }
6857
6858 TEST(OptionalTest, MatchesNonEmptyOptional) {
6859   const Matcher<SampleOptional<int>> m1 = Optional(1);
6860   const Matcher<SampleOptional<int>> m2 = Optional(Eq(2));
6861   const Matcher<SampleOptional<int>> m3 = Optional(Lt(3));
6862   SampleOptional<int> opt(1);
6863   EXPECT_TRUE(m1.Matches(opt));
6864   EXPECT_FALSE(m2.Matches(opt));
6865   EXPECT_TRUE(m3.Matches(opt));
6866 }
6867
6868 TEST(OptionalTest, DoesNotMatchNullopt) {
6869   const Matcher<SampleOptional<int>> m = Optional(1);
6870   SampleOptional<int> empty;
6871   EXPECT_FALSE(m.Matches(empty));
6872 }
6873
6874 TEST(OptionalTest, WorksWithMoveOnly) {
6875   Matcher<SampleOptional<std::unique_ptr<int>>> m = Optional(Eq(nullptr));
6876   EXPECT_TRUE(m.Matches(SampleOptional<std::unique_ptr<int>>(nullptr)));
6877 }
6878
6879 class SampleVariantIntString {
6880  public:
6881   SampleVariantIntString(int i) : i_(i), has_int_(true) {}
6882   SampleVariantIntString(const std::string& s) : s_(s), has_int_(false) {}
6883
6884   template <typename T>
6885   friend bool holds_alternative(const SampleVariantIntString& value) {
6886     return value.has_int_ == std::is_same<T, int>::value;
6887   }
6888
6889   template <typename T>
6890   friend const T& get(const SampleVariantIntString& value) {
6891     return value.get_impl(static_cast<T*>(nullptr));
6892   }
6893
6894  private:
6895   const int& get_impl(int*) const { return i_; }
6896   const std::string& get_impl(std::string*) const { return s_; }
6897
6898   int i_;
6899   std::string s_;
6900   bool has_int_;
6901 };
6902
6903 TEST(VariantTest, DescribesSelf) {
6904   const Matcher<SampleVariantIntString> m = VariantWith<int>(Eq(1));
6905   EXPECT_THAT(Describe(m), ContainsRegex("is a variant<> with value of type "
6906                                          "'.*' and the value is equal to 1"));
6907 }
6908
6909 TEST(VariantTest, ExplainsSelf) {
6910   const Matcher<SampleVariantIntString> m = VariantWith<int>(Eq(1));
6911   EXPECT_THAT(Explain(m, SampleVariantIntString(1)),
6912               ContainsRegex("whose value 1"));
6913   EXPECT_THAT(Explain(m, SampleVariantIntString("A")),
6914               HasSubstr("whose value is not of type '"));
6915   EXPECT_THAT(Explain(m, SampleVariantIntString(2)),
6916               "whose value 2 doesn't match");
6917 }
6918
6919 TEST(VariantTest, FullMatch) {
6920   Matcher<SampleVariantIntString> m = VariantWith<int>(Eq(1));
6921   EXPECT_TRUE(m.Matches(SampleVariantIntString(1)));
6922
6923   m = VariantWith<std::string>(Eq("1"));
6924   EXPECT_TRUE(m.Matches(SampleVariantIntString("1")));
6925 }
6926
6927 TEST(VariantTest, TypeDoesNotMatch) {
6928   Matcher<SampleVariantIntString> m = VariantWith<int>(Eq(1));
6929   EXPECT_FALSE(m.Matches(SampleVariantIntString("1")));
6930
6931   m = VariantWith<std::string>(Eq("1"));
6932   EXPECT_FALSE(m.Matches(SampleVariantIntString(1)));
6933 }
6934
6935 TEST(VariantTest, InnerDoesNotMatch) {
6936   Matcher<SampleVariantIntString> m = VariantWith<int>(Eq(1));
6937   EXPECT_FALSE(m.Matches(SampleVariantIntString(2)));
6938
6939   m = VariantWith<std::string>(Eq("1"));
6940   EXPECT_FALSE(m.Matches(SampleVariantIntString("2")));
6941 }
6942
6943 class SampleAnyType {
6944  public:
6945   explicit SampleAnyType(int i) : index_(0), i_(i) {}
6946   explicit SampleAnyType(const std::string& s) : index_(1), s_(s) {}
6947
6948   template <typename T>
6949   friend const T* any_cast(const SampleAnyType* any) {
6950     return any->get_impl(static_cast<T*>(nullptr));
6951   }
6952
6953  private:
6954   int index_;
6955   int i_;
6956   std::string s_;
6957
6958   const int* get_impl(int*) const { return index_ == 0 ? &i_ : nullptr; }
6959   const std::string* get_impl(std::string*) const {
6960     return index_ == 1 ? &s_ : nullptr;
6961   }
6962 };
6963
6964 TEST(AnyWithTest, FullMatch) {
6965   Matcher<SampleAnyType> m = AnyWith<int>(Eq(1));
6966   EXPECT_TRUE(m.Matches(SampleAnyType(1)));
6967 }
6968
6969 TEST(AnyWithTest, TestBadCastType) {
6970   Matcher<SampleAnyType> m = AnyWith<std::string>(Eq("fail"));
6971   EXPECT_FALSE(m.Matches(SampleAnyType(1)));
6972 }
6973
6974 TEST(AnyWithTest, TestUseInContainers) {
6975   std::vector<SampleAnyType> a;
6976   a.emplace_back(1);
6977   a.emplace_back(2);
6978   a.emplace_back(3);
6979   EXPECT_THAT(
6980       a, ElementsAreArray({AnyWith<int>(1), AnyWith<int>(2), AnyWith<int>(3)}));
6981
6982   std::vector<SampleAnyType> b;
6983   b.emplace_back("hello");
6984   b.emplace_back("merhaba");
6985   b.emplace_back("salut");
6986   EXPECT_THAT(b, ElementsAreArray({AnyWith<std::string>("hello"),
6987                                    AnyWith<std::string>("merhaba"),
6988                                    AnyWith<std::string>("salut")}));
6989 }
6990 TEST(AnyWithTest, TestCompare) {
6991   EXPECT_THAT(SampleAnyType(1), AnyWith<int>(Gt(0)));
6992 }
6993
6994 TEST(AnyWithTest, DescribesSelf) {
6995   const Matcher<const SampleAnyType&> m = AnyWith<int>(Eq(1));
6996   EXPECT_THAT(Describe(m), ContainsRegex("is an 'any' type with value of type "
6997                                          "'.*' and the value is equal to 1"));
6998 }
6999
7000 TEST(AnyWithTest, ExplainsSelf) {
7001   const Matcher<const SampleAnyType&> m = AnyWith<int>(Eq(1));
7002
7003   EXPECT_THAT(Explain(m, SampleAnyType(1)), ContainsRegex("whose value 1"));
7004   EXPECT_THAT(Explain(m, SampleAnyType("A")),
7005               HasSubstr("whose value is not of type '"));
7006   EXPECT_THAT(Explain(m, SampleAnyType(2)), "whose value 2 doesn't match");
7007 }
7008
7009 TEST(PointeeTest, WorksOnMoveOnlyType) {
7010   std::unique_ptr<int> p(new int(3));
7011   EXPECT_THAT(p, Pointee(Eq(3)));
7012   EXPECT_THAT(p, Not(Pointee(Eq(2))));
7013 }
7014
7015 TEST(NotTest, WorksOnMoveOnlyType) {
7016   std::unique_ptr<int> p(new int(3));
7017   EXPECT_THAT(p, Pointee(Eq(3)));
7018   EXPECT_THAT(p, Not(Pointee(Eq(2))));
7019 }
7020
7021 // Tests Args<k0, ..., kn>(m).
7022
7023 TEST(ArgsTest, AcceptsZeroTemplateArg) {
7024   const std::tuple<int, bool> t(5, true);
7025   EXPECT_THAT(t, Args<>(Eq(std::tuple<>())));
7026   EXPECT_THAT(t, Not(Args<>(Ne(std::tuple<>()))));
7027 }
7028
7029 TEST(ArgsTest, AcceptsOneTemplateArg) {
7030   const std::tuple<int, bool> t(5, true);
7031   EXPECT_THAT(t, Args<0>(Eq(std::make_tuple(5))));
7032   EXPECT_THAT(t, Args<1>(Eq(std::make_tuple(true))));
7033   EXPECT_THAT(t, Not(Args<1>(Eq(std::make_tuple(false)))));
7034 }
7035
7036 TEST(ArgsTest, AcceptsTwoTemplateArgs) {
7037   const std::tuple<short, int, long> t(4, 5, 6L);  // NOLINT
7038
7039   EXPECT_THAT(t, (Args<0, 1>(Lt())));
7040   EXPECT_THAT(t, (Args<1, 2>(Lt())));
7041   EXPECT_THAT(t, Not(Args<0, 2>(Gt())));
7042 }
7043
7044 TEST(ArgsTest, AcceptsRepeatedTemplateArgs) {
7045   const std::tuple<short, int, long> t(4, 5, 6L);  // NOLINT
7046   EXPECT_THAT(t, (Args<0, 0>(Eq())));
7047   EXPECT_THAT(t, Not(Args<1, 1>(Ne())));
7048 }
7049
7050 TEST(ArgsTest, AcceptsDecreasingTemplateArgs) {
7051   const std::tuple<short, int, long> t(4, 5, 6L);  // NOLINT
7052   EXPECT_THAT(t, (Args<2, 0>(Gt())));
7053   EXPECT_THAT(t, Not(Args<2, 1>(Lt())));
7054 }
7055
7056 MATCHER(SumIsZero, "") {
7057   return std::get<0>(arg) + std::get<1>(arg) + std::get<2>(arg) == 0;
7058 }
7059
7060 TEST(ArgsTest, AcceptsMoreTemplateArgsThanArityOfOriginalTuple) {
7061   EXPECT_THAT(std::make_tuple(-1, 2), (Args<0, 0, 1>(SumIsZero())));
7062   EXPECT_THAT(std::make_tuple(1, 2), Not(Args<0, 0, 1>(SumIsZero())));
7063 }
7064
7065 TEST(ArgsTest, CanBeNested) {
7066   const std::tuple<short, int, long, int> t(4, 5, 6L, 6);  // NOLINT
7067   EXPECT_THAT(t, (Args<1, 2, 3>(Args<1, 2>(Eq()))));
7068   EXPECT_THAT(t, (Args<0, 1, 3>(Args<0, 2>(Lt()))));
7069 }
7070
7071 TEST(ArgsTest, CanMatchTupleByValue) {
7072   typedef std::tuple<char, int, int> Tuple3;
7073   const Matcher<Tuple3> m = Args<1, 2>(Lt());
7074   EXPECT_TRUE(m.Matches(Tuple3('a', 1, 2)));
7075   EXPECT_FALSE(m.Matches(Tuple3('b', 2, 2)));
7076 }
7077
7078 TEST(ArgsTest, CanMatchTupleByReference) {
7079   typedef std::tuple<char, char, int> Tuple3;
7080   const Matcher<const Tuple3&> m = Args<0, 1>(Lt());
7081   EXPECT_TRUE(m.Matches(Tuple3('a', 'b', 2)));
7082   EXPECT_FALSE(m.Matches(Tuple3('b', 'b', 2)));
7083 }
7084
7085 // Validates that arg is printed as str.
7086 MATCHER_P(PrintsAs, str, "") {
7087   return testing::PrintToString(arg) == str;
7088 }
7089
7090 TEST(ArgsTest, AcceptsTenTemplateArgs) {
7091   EXPECT_THAT(std::make_tuple(0, 1L, 2, 3L, 4, 5, 6, 7, 8, 9),
7092               (Args<9, 8, 7, 6, 5, 4, 3, 2, 1, 0>(
7093                   PrintsAs("(9, 8, 7, 6, 5, 4, 3, 2, 1, 0)"))));
7094   EXPECT_THAT(std::make_tuple(0, 1L, 2, 3L, 4, 5, 6, 7, 8, 9),
7095               Not(Args<9, 8, 7, 6, 5, 4, 3, 2, 1, 0>(
7096                   PrintsAs("(0, 8, 7, 6, 5, 4, 3, 2, 1, 0)"))));
7097 }
7098
7099 TEST(ArgsTest, DescirbesSelfCorrectly) {
7100   const Matcher<std::tuple<int, bool, char> > m = Args<2, 0>(Lt());
7101   EXPECT_EQ("are a tuple whose fields (#2, #0) are a pair where "
7102             "the first < the second",
7103             Describe(m));
7104 }
7105
7106 TEST(ArgsTest, DescirbesNestedArgsCorrectly) {
7107   const Matcher<const std::tuple<int, bool, char, int>&> m =
7108       Args<0, 2, 3>(Args<2, 0>(Lt()));
7109   EXPECT_EQ("are a tuple whose fields (#0, #2, #3) are a tuple "
7110             "whose fields (#2, #0) are a pair where the first < the second",
7111             Describe(m));
7112 }
7113
7114 TEST(ArgsTest, DescribesNegationCorrectly) {
7115   const Matcher<std::tuple<int, char> > m = Args<1, 0>(Gt());
7116   EXPECT_EQ("are a tuple whose fields (#1, #0) aren't a pair "
7117             "where the first > the second",
7118             DescribeNegation(m));
7119 }
7120
7121 TEST(ArgsTest, ExplainsMatchResultWithoutInnerExplanation) {
7122   const Matcher<std::tuple<bool, int, int> > m = Args<1, 2>(Eq());
7123   EXPECT_EQ("whose fields (#1, #2) are (42, 42)",
7124             Explain(m, std::make_tuple(false, 42, 42)));
7125   EXPECT_EQ("whose fields (#1, #2) are (42, 43)",
7126             Explain(m, std::make_tuple(false, 42, 43)));
7127 }
7128
7129 // For testing Args<>'s explanation.
7130 class LessThanMatcher : public MatcherInterface<std::tuple<char, int> > {
7131  public:
7132   void DescribeTo(::std::ostream* /*os*/) const override {}
7133
7134   bool MatchAndExplain(std::tuple<char, int> value,
7135                        MatchResultListener* listener) const override {
7136     const int diff = std::get<0>(value) - std::get<1>(value);
7137     if (diff > 0) {
7138       *listener << "where the first value is " << diff
7139                 << " more than the second";
7140     }
7141     return diff < 0;
7142   }
7143 };
7144
7145 Matcher<std::tuple<char, int> > LessThan() {
7146   return MakeMatcher(new LessThanMatcher);
7147 }
7148
7149 TEST(ArgsTest, ExplainsMatchResultWithInnerExplanation) {
7150   const Matcher<std::tuple<char, int, int> > m = Args<0, 2>(LessThan());
7151   EXPECT_EQ(
7152       "whose fields (#0, #2) are ('a' (97, 0x61), 42), "
7153       "where the first value is 55 more than the second",
7154       Explain(m, std::make_tuple('a', 42, 42)));
7155   EXPECT_EQ("whose fields (#0, #2) are ('\\0', 43)",
7156             Explain(m, std::make_tuple('\0', 42, 43)));
7157 }
7158
7159 class PredicateFormatterFromMatcherTest : public ::testing::Test {
7160  protected:
7161   enum Behavior { kInitialSuccess, kAlwaysFail, kFlaky };
7162
7163   // A matcher that can return different results when used multiple times on the
7164   // same input. No real matcher should do this; but this lets us test that we
7165   // detect such behavior and fail appropriately.
7166   class MockMatcher : public MatcherInterface<Behavior> {
7167    public:
7168     bool MatchAndExplain(Behavior behavior,
7169                          MatchResultListener* listener) const override {
7170       *listener << "[MatchAndExplain]";
7171       switch (behavior) {
7172         case kInitialSuccess:
7173           // The first call to MatchAndExplain should use a "not interested"
7174           // listener; so this is expected to return |true|. There should be no
7175           // subsequent calls.
7176           return !listener->IsInterested();
7177
7178         case kAlwaysFail:
7179           return false;
7180
7181         case kFlaky:
7182           // The first call to MatchAndExplain should use a "not interested"
7183           // listener; so this will return |false|. Subsequent calls should have
7184           // an "interested" listener; so this will return |true|, thus
7185           // simulating a flaky matcher.
7186           return listener->IsInterested();
7187       }
7188
7189       GTEST_LOG_(FATAL) << "This should never be reached";
7190       return false;
7191     }
7192
7193     void DescribeTo(ostream* os) const override { *os << "[DescribeTo]"; }
7194
7195     void DescribeNegationTo(ostream* os) const override {
7196       *os << "[DescribeNegationTo]";
7197     }
7198   };
7199
7200   AssertionResult RunPredicateFormatter(Behavior behavior) {
7201     auto matcher = MakeMatcher(new MockMatcher);
7202     PredicateFormatterFromMatcher<Matcher<Behavior>> predicate_formatter(
7203         matcher);
7204     return predicate_formatter("dummy-name", behavior);
7205   }
7206 };
7207
7208 TEST_F(PredicateFormatterFromMatcherTest, ShortCircuitOnSuccess) {
7209   AssertionResult result = RunPredicateFormatter(kInitialSuccess);
7210   EXPECT_TRUE(result);  // Implicit cast to bool.
7211   std::string expect;
7212   EXPECT_EQ(expect, result.message());
7213 }
7214
7215 TEST_F(PredicateFormatterFromMatcherTest, NoShortCircuitOnFailure) {
7216   AssertionResult result = RunPredicateFormatter(kAlwaysFail);
7217   EXPECT_FALSE(result);  // Implicit cast to bool.
7218   std::string expect =
7219       "Value of: dummy-name\nExpected: [DescribeTo]\n"
7220       "  Actual: 1" +
7221       OfType(internal::GetTypeName<Behavior>()) + ", [MatchAndExplain]";
7222   EXPECT_EQ(expect, result.message());
7223 }
7224
7225 TEST_F(PredicateFormatterFromMatcherTest, DetectsFlakyShortCircuit) {
7226   AssertionResult result = RunPredicateFormatter(kFlaky);
7227   EXPECT_FALSE(result);  // Implicit cast to bool.
7228   std::string expect =
7229       "Value of: dummy-name\nExpected: [DescribeTo]\n"
7230       "  The matcher failed on the initial attempt; but passed when rerun to "
7231       "generate the explanation.\n"
7232       "  Actual: 2" +
7233       OfType(internal::GetTypeName<Behavior>()) + ", [MatchAndExplain]";
7234   EXPECT_EQ(expect, result.message());
7235 }
7236
7237 // Tests for ElementsAre().
7238
7239 TEST(ElementsAreTest, CanDescribeExpectingNoElement) {
7240   Matcher<const vector<int>&> m = ElementsAre();
7241   EXPECT_EQ("is empty", Describe(m));
7242 }
7243
7244 TEST(ElementsAreTest, CanDescribeExpectingOneElement) {
7245   Matcher<vector<int>> m = ElementsAre(Gt(5));
7246   EXPECT_EQ("has 1 element that is > 5", Describe(m));
7247 }
7248
7249 TEST(ElementsAreTest, CanDescribeExpectingManyElements) {
7250   Matcher<list<std::string>> m = ElementsAre(StrEq("one"), "two");
7251   EXPECT_EQ(
7252       "has 2 elements where\n"
7253       "element #0 is equal to \"one\",\n"
7254       "element #1 is equal to \"two\"",
7255       Describe(m));
7256 }
7257
7258 TEST(ElementsAreTest, CanDescribeNegationOfExpectingNoElement) {
7259   Matcher<vector<int>> m = ElementsAre();
7260   EXPECT_EQ("isn't empty", DescribeNegation(m));
7261 }
7262
7263 TEST(ElementsAreTest, CanDescribeNegationOfExpectingOneElment) {
7264   Matcher<const list<int>&> m = ElementsAre(Gt(5));
7265   EXPECT_EQ(
7266       "doesn't have 1 element, or\n"
7267       "element #0 isn't > 5",
7268       DescribeNegation(m));
7269 }
7270
7271 TEST(ElementsAreTest, CanDescribeNegationOfExpectingManyElements) {
7272   Matcher<const list<std::string>&> m = ElementsAre("one", "two");
7273   EXPECT_EQ(
7274       "doesn't have 2 elements, or\n"
7275       "element #0 isn't equal to \"one\", or\n"
7276       "element #1 isn't equal to \"two\"",
7277       DescribeNegation(m));
7278 }
7279
7280 TEST(ElementsAreTest, DoesNotExplainTrivialMatch) {
7281   Matcher<const list<int>&> m = ElementsAre(1, Ne(2));
7282
7283   list<int> test_list;
7284   test_list.push_back(1);
7285   test_list.push_back(3);
7286   EXPECT_EQ("", Explain(m, test_list));  // No need to explain anything.
7287 }
7288
7289 TEST(ElementsAreTest, ExplainsNonTrivialMatch) {
7290   Matcher<const vector<int>&> m =
7291       ElementsAre(GreaterThan(1), 0, GreaterThan(2));
7292
7293   const int a[] = {10, 0, 100};
7294   vector<int> test_vector(std::begin(a), std::end(a));
7295   EXPECT_EQ(
7296       "whose element #0 matches, which is 9 more than 1,\n"
7297       "and whose element #2 matches, which is 98 more than 2",
7298       Explain(m, test_vector));
7299 }
7300
7301 TEST(ElementsAreTest, CanExplainMismatchWrongSize) {
7302   Matcher<const list<int>&> m = ElementsAre(1, 3);
7303
7304   list<int> test_list;
7305   // No need to explain when the container is empty.
7306   EXPECT_EQ("", Explain(m, test_list));
7307
7308   test_list.push_back(1);
7309   EXPECT_EQ("which has 1 element", Explain(m, test_list));
7310 }
7311
7312 TEST(ElementsAreTest, CanExplainMismatchRightSize) {
7313   Matcher<const vector<int>&> m = ElementsAre(1, GreaterThan(5));
7314
7315   vector<int> v;
7316   v.push_back(2);
7317   v.push_back(1);
7318   EXPECT_EQ("whose element #0 doesn't match", Explain(m, v));
7319
7320   v[0] = 1;
7321   EXPECT_EQ("whose element #1 doesn't match, which is 4 less than 5",
7322             Explain(m, v));
7323 }
7324
7325 TEST(ElementsAreTest, MatchesOneElementVector) {
7326   vector<std::string> test_vector;
7327   test_vector.push_back("test string");
7328
7329   EXPECT_THAT(test_vector, ElementsAre(StrEq("test string")));
7330 }
7331
7332 TEST(ElementsAreTest, MatchesOneElementList) {
7333   list<std::string> test_list;
7334   test_list.push_back("test string");
7335
7336   EXPECT_THAT(test_list, ElementsAre("test string"));
7337 }
7338
7339 TEST(ElementsAreTest, MatchesThreeElementVector) {
7340   vector<std::string> test_vector;
7341   test_vector.push_back("one");
7342   test_vector.push_back("two");
7343   test_vector.push_back("three");
7344
7345   EXPECT_THAT(test_vector, ElementsAre("one", StrEq("two"), _));
7346 }
7347
7348 TEST(ElementsAreTest, MatchesOneElementEqMatcher) {
7349   vector<int> test_vector;
7350   test_vector.push_back(4);
7351
7352   EXPECT_THAT(test_vector, ElementsAre(Eq(4)));
7353 }
7354
7355 TEST(ElementsAreTest, MatchesOneElementAnyMatcher) {
7356   vector<int> test_vector;
7357   test_vector.push_back(4);
7358
7359   EXPECT_THAT(test_vector, ElementsAre(_));
7360 }
7361
7362 TEST(ElementsAreTest, MatchesOneElementValue) {
7363   vector<int> test_vector;
7364   test_vector.push_back(4);
7365
7366   EXPECT_THAT(test_vector, ElementsAre(4));
7367 }
7368
7369 TEST(ElementsAreTest, MatchesThreeElementsMixedMatchers) {
7370   vector<int> test_vector;
7371   test_vector.push_back(1);
7372   test_vector.push_back(2);
7373   test_vector.push_back(3);
7374
7375   EXPECT_THAT(test_vector, ElementsAre(1, Eq(2), _));
7376 }
7377
7378 TEST(ElementsAreTest, MatchesTenElementVector) {
7379   const int a[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
7380   vector<int> test_vector(std::begin(a), std::end(a));
7381
7382   EXPECT_THAT(test_vector,
7383               // The element list can contain values and/or matchers
7384               // of different types.
7385               ElementsAre(0, Ge(0), _, 3, 4, Ne(2), Eq(6), 7, 8, _));
7386 }
7387
7388 TEST(ElementsAreTest, DoesNotMatchWrongSize) {
7389   vector<std::string> test_vector;
7390   test_vector.push_back("test string");
7391   test_vector.push_back("test string");
7392
7393   Matcher<vector<std::string>> m = ElementsAre(StrEq("test string"));
7394   EXPECT_FALSE(m.Matches(test_vector));
7395 }
7396
7397 TEST(ElementsAreTest, DoesNotMatchWrongValue) {
7398   vector<std::string> test_vector;
7399   test_vector.push_back("other string");
7400
7401   Matcher<vector<std::string>> m = ElementsAre(StrEq("test string"));
7402   EXPECT_FALSE(m.Matches(test_vector));
7403 }
7404
7405 TEST(ElementsAreTest, DoesNotMatchWrongOrder) {
7406   vector<std::string> test_vector;
7407   test_vector.push_back("one");
7408   test_vector.push_back("three");
7409   test_vector.push_back("two");
7410
7411   Matcher<vector<std::string>> m =
7412       ElementsAre(StrEq("one"), StrEq("two"), StrEq("three"));
7413   EXPECT_FALSE(m.Matches(test_vector));
7414 }
7415
7416 TEST(ElementsAreTest, WorksForNestedContainer) {
7417   constexpr std::array<const char*, 2> strings = {{"Hi", "world"}};
7418
7419   vector<list<char>> nested;
7420   for (const auto& s : strings) {
7421     nested.emplace_back(s, s + strlen(s));
7422   }
7423
7424   EXPECT_THAT(nested, ElementsAre(ElementsAre('H', Ne('e')),
7425                                   ElementsAre('w', 'o', _, _, 'd')));
7426   EXPECT_THAT(nested, Not(ElementsAre(ElementsAre('H', 'e'),
7427                                       ElementsAre('w', 'o', _, _, 'd'))));
7428 }
7429
7430 TEST(ElementsAreTest, WorksWithByRefElementMatchers) {
7431   int a[] = {0, 1, 2};
7432   vector<int> v(std::begin(a), std::end(a));
7433
7434   EXPECT_THAT(v, ElementsAre(Ref(v[0]), Ref(v[1]), Ref(v[2])));
7435   EXPECT_THAT(v, Not(ElementsAre(Ref(v[0]), Ref(v[1]), Ref(a[2]))));
7436 }
7437
7438 TEST(ElementsAreTest, WorksWithContainerPointerUsingPointee) {
7439   int a[] = {0, 1, 2};
7440   vector<int> v(std::begin(a), std::end(a));
7441
7442   EXPECT_THAT(&v, Pointee(ElementsAre(0, 1, _)));
7443   EXPECT_THAT(&v, Not(Pointee(ElementsAre(0, _, 3))));
7444 }
7445
7446 TEST(ElementsAreTest, WorksWithNativeArrayPassedByReference) {
7447   int array[] = {0, 1, 2};
7448   EXPECT_THAT(array, ElementsAre(0, 1, _));
7449   EXPECT_THAT(array, Not(ElementsAre(1, _, _)));
7450   EXPECT_THAT(array, Not(ElementsAre(0, _)));
7451 }
7452
7453 class NativeArrayPassedAsPointerAndSize {
7454  public:
7455   NativeArrayPassedAsPointerAndSize() {}
7456
7457   MOCK_METHOD(void, Helper, (int* array, int size));
7458
7459  private:
7460   GTEST_DISALLOW_COPY_AND_ASSIGN_(NativeArrayPassedAsPointerAndSize);
7461 };
7462
7463 TEST(ElementsAreTest, WorksWithNativeArrayPassedAsPointerAndSize) {
7464   int array[] = {0, 1};
7465   ::std::tuple<int*, size_t> array_as_tuple(array, 2);
7466   EXPECT_THAT(array_as_tuple, ElementsAre(0, 1));
7467   EXPECT_THAT(array_as_tuple, Not(ElementsAre(0)));
7468
7469   NativeArrayPassedAsPointerAndSize helper;
7470   EXPECT_CALL(helper, Helper(_, _)).With(ElementsAre(0, 1));
7471   helper.Helper(array, 2);
7472 }
7473
7474 TEST(ElementsAreTest, WorksWithTwoDimensionalNativeArray) {
7475   const char a2[][3] = {"hi", "lo"};
7476   EXPECT_THAT(a2, ElementsAre(ElementsAre('h', 'i', '\0'),
7477                               ElementsAre('l', 'o', '\0')));
7478   EXPECT_THAT(a2, ElementsAre(StrEq("hi"), StrEq("lo")));
7479   EXPECT_THAT(a2, ElementsAre(Not(ElementsAre('h', 'o', '\0')),
7480                               ElementsAre('l', 'o', '\0')));
7481 }
7482
7483 TEST(ElementsAreTest, AcceptsStringLiteral) {
7484   std::string array[] = {"hi", "one", "two"};
7485   EXPECT_THAT(array, ElementsAre("hi", "one", "two"));
7486   EXPECT_THAT(array, Not(ElementsAre("hi", "one", "too")));
7487 }
7488
7489 // Declared here with the size unknown.  Defined AFTER the following test.
7490 extern const char kHi[];
7491
7492 TEST(ElementsAreTest, AcceptsArrayWithUnknownSize) {
7493   // The size of kHi is not known in this test, but ElementsAre() should
7494   // still accept it.
7495
7496   std::string array1[] = {"hi"};
7497   EXPECT_THAT(array1, ElementsAre(kHi));
7498
7499   std::string array2[] = {"ho"};
7500   EXPECT_THAT(array2, Not(ElementsAre(kHi)));
7501 }
7502
7503 const char kHi[] = "hi";
7504
7505 TEST(ElementsAreTest, MakesCopyOfArguments) {
7506   int x = 1;
7507   int y = 2;
7508   // This should make a copy of x and y.
7509   ::testing::internal::ElementsAreMatcher<std::tuple<int, int>>
7510       polymorphic_matcher = ElementsAre(x, y);
7511   // Changing x and y now shouldn't affect the meaning of the above matcher.
7512   x = y = 0;
7513   const int array1[] = {1, 2};
7514   EXPECT_THAT(array1, polymorphic_matcher);
7515   const int array2[] = {0, 0};
7516   EXPECT_THAT(array2, Not(polymorphic_matcher));
7517 }
7518
7519 // Tests for ElementsAreArray().  Since ElementsAreArray() shares most
7520 // of the implementation with ElementsAre(), we don't test it as
7521 // thoroughly here.
7522
7523 TEST(ElementsAreArrayTest, CanBeCreatedWithValueArray) {
7524   const int a[] = {1, 2, 3};
7525
7526   vector<int> test_vector(std::begin(a), std::end(a));
7527   EXPECT_THAT(test_vector, ElementsAreArray(a));
7528
7529   test_vector[2] = 0;
7530   EXPECT_THAT(test_vector, Not(ElementsAreArray(a)));
7531 }
7532
7533 TEST(ElementsAreArrayTest, CanBeCreatedWithArraySize) {
7534   std::array<const char*, 3> a = {{"one", "two", "three"}};
7535
7536   vector<std::string> test_vector(std::begin(a), std::end(a));
7537   EXPECT_THAT(test_vector, ElementsAreArray(a.data(), a.size()));
7538
7539   const char** p = a.data();
7540   test_vector[0] = "1";
7541   EXPECT_THAT(test_vector, Not(ElementsAreArray(p, a.size())));
7542 }
7543
7544 TEST(ElementsAreArrayTest, CanBeCreatedWithoutArraySize) {
7545   const char* a[] = {"one", "two", "three"};
7546
7547   vector<std::string> test_vector(std::begin(a), std::end(a));
7548   EXPECT_THAT(test_vector, ElementsAreArray(a));
7549
7550   test_vector[0] = "1";
7551   EXPECT_THAT(test_vector, Not(ElementsAreArray(a)));
7552 }
7553
7554 TEST(ElementsAreArrayTest, CanBeCreatedWithMatcherArray) {
7555   const Matcher<std::string> kMatcherArray[] = {StrEq("one"), StrEq("two"),
7556                                                 StrEq("three")};
7557
7558   vector<std::string> test_vector;
7559   test_vector.push_back("one");
7560   test_vector.push_back("two");
7561   test_vector.push_back("three");
7562   EXPECT_THAT(test_vector, ElementsAreArray(kMatcherArray));
7563
7564   test_vector.push_back("three");
7565   EXPECT_THAT(test_vector, Not(ElementsAreArray(kMatcherArray)));
7566 }
7567
7568 TEST(ElementsAreArrayTest, CanBeCreatedWithVector) {
7569   const int a[] = {1, 2, 3};
7570   vector<int> test_vector(std::begin(a), std::end(a));
7571   const vector<int> expected(std::begin(a), std::end(a));
7572   EXPECT_THAT(test_vector, ElementsAreArray(expected));
7573   test_vector.push_back(4);
7574   EXPECT_THAT(test_vector, Not(ElementsAreArray(expected)));
7575 }
7576
7577 TEST(ElementsAreArrayTest, TakesInitializerList) {
7578   const int a[5] = {1, 2, 3, 4, 5};
7579   EXPECT_THAT(a, ElementsAreArray({1, 2, 3, 4, 5}));
7580   EXPECT_THAT(a, Not(ElementsAreArray({1, 2, 3, 5, 4})));
7581   EXPECT_THAT(a, Not(ElementsAreArray({1, 2, 3, 4, 6})));
7582 }
7583
7584 TEST(ElementsAreArrayTest, TakesInitializerListOfCStrings) {
7585   const std::string a[5] = {"a", "b", "c", "d", "e"};
7586   EXPECT_THAT(a, ElementsAreArray({"a", "b", "c", "d", "e"}));
7587   EXPECT_THAT(a, Not(ElementsAreArray({"a", "b", "c", "e", "d"})));
7588   EXPECT_THAT(a, Not(ElementsAreArray({"a", "b", "c", "d", "ef"})));
7589 }
7590
7591 TEST(ElementsAreArrayTest, TakesInitializerListOfSameTypedMatchers) {
7592   const int a[5] = {1, 2, 3, 4, 5};
7593   EXPECT_THAT(a, ElementsAreArray({Eq(1), Eq(2), Eq(3), Eq(4), Eq(5)}));
7594   EXPECT_THAT(a, Not(ElementsAreArray({Eq(1), Eq(2), Eq(3), Eq(4), Eq(6)})));
7595 }
7596
7597 TEST(ElementsAreArrayTest, TakesInitializerListOfDifferentTypedMatchers) {
7598   const int a[5] = {1, 2, 3, 4, 5};
7599   // The compiler cannot infer the type of the initializer list if its
7600   // elements have different types.  We must explicitly specify the
7601   // unified element type in this case.
7602   EXPECT_THAT(
7603       a, ElementsAreArray<Matcher<int>>({Eq(1), Ne(-2), Ge(3), Le(4), Eq(5)}));
7604   EXPECT_THAT(a, Not(ElementsAreArray<Matcher<int>>(
7605                      {Eq(1), Ne(-2), Ge(3), Le(4), Eq(6)})));
7606 }
7607
7608 TEST(ElementsAreArrayTest, CanBeCreatedWithMatcherVector) {
7609   const int a[] = {1, 2, 3};
7610   const Matcher<int> kMatchers[] = {Eq(1), Eq(2), Eq(3)};
7611   vector<int> test_vector(std::begin(a), std::end(a));
7612   const vector<Matcher<int>> expected(std::begin(kMatchers),
7613                                       std::end(kMatchers));
7614   EXPECT_THAT(test_vector, ElementsAreArray(expected));
7615   test_vector.push_back(4);
7616   EXPECT_THAT(test_vector, Not(ElementsAreArray(expected)));
7617 }
7618
7619 TEST(ElementsAreArrayTest, CanBeCreatedWithIteratorRange) {
7620   const int a[] = {1, 2, 3};
7621   const vector<int> test_vector(std::begin(a), std::end(a));
7622   const vector<int> expected(std::begin(a), std::end(a));
7623   EXPECT_THAT(test_vector, ElementsAreArray(expected.begin(), expected.end()));
7624   // Pointers are iterators, too.
7625   EXPECT_THAT(test_vector, ElementsAreArray(std::begin(a), std::end(a)));
7626   // The empty range of NULL pointers should also be okay.
7627   int* const null_int = nullptr;
7628   EXPECT_THAT(test_vector, Not(ElementsAreArray(null_int, null_int)));
7629   EXPECT_THAT((vector<int>()), ElementsAreArray(null_int, null_int));
7630 }
7631
7632 // Since ElementsAre() and ElementsAreArray() share much of the
7633 // implementation, we only do a sanity test for native arrays here.
7634 TEST(ElementsAreArrayTest, WorksWithNativeArray) {
7635   ::std::string a[] = {"hi", "ho"};
7636   ::std::string b[] = {"hi", "ho"};
7637
7638   EXPECT_THAT(a, ElementsAreArray(b));
7639   EXPECT_THAT(a, ElementsAreArray(b, 2));
7640   EXPECT_THAT(a, Not(ElementsAreArray(b, 1)));
7641 }
7642
7643 TEST(ElementsAreArrayTest, SourceLifeSpan) {
7644   const int a[] = {1, 2, 3};
7645   vector<int> test_vector(std::begin(a), std::end(a));
7646   vector<int> expect(std::begin(a), std::end(a));
7647   ElementsAreArrayMatcher<int> matcher_maker =
7648       ElementsAreArray(expect.begin(), expect.end());
7649   EXPECT_THAT(test_vector, matcher_maker);
7650   // Changing in place the values that initialized matcher_maker should not
7651   // affect matcher_maker anymore. It should have made its own copy of them.
7652   for (int& i : expect) {
7653     i += 10;
7654   }
7655   EXPECT_THAT(test_vector, matcher_maker);
7656   test_vector.push_back(3);
7657   EXPECT_THAT(test_vector, Not(matcher_maker));
7658 }
7659
7660 // Tests for the MATCHER*() macro family.
7661
7662 // Tests that a simple MATCHER() definition works.
7663
7664 MATCHER(IsEven, "") { return (arg % 2) == 0; }
7665
7666 TEST(MatcherMacroTest, Works) {
7667   const Matcher<int> m = IsEven();
7668   EXPECT_TRUE(m.Matches(6));
7669   EXPECT_FALSE(m.Matches(7));
7670
7671   EXPECT_EQ("is even", Describe(m));
7672   EXPECT_EQ("not (is even)", DescribeNegation(m));
7673   EXPECT_EQ("", Explain(m, 6));
7674   EXPECT_EQ("", Explain(m, 7));
7675 }
7676
7677 // This also tests that the description string can reference 'negation'.
7678 MATCHER(IsEven2, negation ? "is odd" : "is even") {
7679   if ((arg % 2) == 0) {
7680     // Verifies that we can stream to result_listener, a listener
7681     // supplied by the MATCHER macro implicitly.
7682     *result_listener << "OK";
7683     return true;
7684   } else {
7685     *result_listener << "% 2 == " << (arg % 2);
7686     return false;
7687   }
7688 }
7689
7690 // This also tests that the description string can reference matcher
7691 // parameters.
7692 MATCHER_P2(EqSumOf, x, y,
7693            std::string(negation ? "doesn't equal" : "equals") + " the sum of " +
7694                PrintToString(x) + " and " + PrintToString(y)) {
7695   if (arg == (x + y)) {
7696     *result_listener << "OK";
7697     return true;
7698   } else {
7699     // Verifies that we can stream to the underlying stream of
7700     // result_listener.
7701     if (result_listener->stream() != nullptr) {
7702       *result_listener->stream() << "diff == " << (x + y - arg);
7703     }
7704     return false;
7705   }
7706 }
7707
7708 // Tests that the matcher description can reference 'negation' and the
7709 // matcher parameters.
7710 TEST(MatcherMacroTest, DescriptionCanReferenceNegationAndParameters) {
7711   const Matcher<int> m1 = IsEven2();
7712   EXPECT_EQ("is even", Describe(m1));
7713   EXPECT_EQ("is odd", DescribeNegation(m1));
7714
7715   const Matcher<int> m2 = EqSumOf(5, 9);
7716   EXPECT_EQ("equals the sum of 5 and 9", Describe(m2));
7717   EXPECT_EQ("doesn't equal the sum of 5 and 9", DescribeNegation(m2));
7718 }
7719
7720 // Tests explaining match result in a MATCHER* macro.
7721 TEST(MatcherMacroTest, CanExplainMatchResult) {
7722   const Matcher<int> m1 = IsEven2();
7723   EXPECT_EQ("OK", Explain(m1, 4));
7724   EXPECT_EQ("% 2 == 1", Explain(m1, 5));
7725
7726   const Matcher<int> m2 = EqSumOf(1, 2);
7727   EXPECT_EQ("OK", Explain(m2, 3));
7728   EXPECT_EQ("diff == -1", Explain(m2, 4));
7729 }
7730
7731 // Tests that the body of MATCHER() can reference the type of the
7732 // value being matched.
7733
7734 MATCHER(IsEmptyString, "") {
7735   StaticAssertTypeEq<::std::string, arg_type>();
7736   return arg.empty();
7737 }
7738
7739 MATCHER(IsEmptyStringByRef, "") {
7740   StaticAssertTypeEq<const ::std::string&, arg_type>();
7741   return arg.empty();
7742 }
7743
7744 TEST(MatcherMacroTest, CanReferenceArgType) {
7745   const Matcher<::std::string> m1 = IsEmptyString();
7746   EXPECT_TRUE(m1.Matches(""));
7747
7748   const Matcher<const ::std::string&> m2 = IsEmptyStringByRef();
7749   EXPECT_TRUE(m2.Matches(""));
7750 }
7751
7752 // Tests that MATCHER() can be used in a namespace.
7753
7754 namespace matcher_test {
7755 MATCHER(IsOdd, "") { return (arg % 2) != 0; }
7756 }  // namespace matcher_test
7757
7758 TEST(MatcherMacroTest, WorksInNamespace) {
7759   Matcher<int> m = matcher_test::IsOdd();
7760   EXPECT_FALSE(m.Matches(4));
7761   EXPECT_TRUE(m.Matches(5));
7762 }
7763
7764 // Tests that Value() can be used to compose matchers.
7765 MATCHER(IsPositiveOdd, "") {
7766   return Value(arg, matcher_test::IsOdd()) && arg > 0;
7767 }
7768
7769 TEST(MatcherMacroTest, CanBeComposedUsingValue) {
7770   EXPECT_THAT(3, IsPositiveOdd());
7771   EXPECT_THAT(4, Not(IsPositiveOdd()));
7772   EXPECT_THAT(-1, Not(IsPositiveOdd()));
7773 }
7774
7775 // Tests that a simple MATCHER_P() definition works.
7776
7777 MATCHER_P(IsGreaterThan32And, n, "") { return arg > 32 && arg > n; }
7778
7779 TEST(MatcherPMacroTest, Works) {
7780   const Matcher<int> m = IsGreaterThan32And(5);
7781   EXPECT_TRUE(m.Matches(36));
7782   EXPECT_FALSE(m.Matches(5));
7783
7784   EXPECT_EQ("is greater than 32 and 5", Describe(m));
7785   EXPECT_EQ("not (is greater than 32 and 5)", DescribeNegation(m));
7786   EXPECT_EQ("", Explain(m, 36));
7787   EXPECT_EQ("", Explain(m, 5));
7788 }
7789
7790 // Tests that the description is calculated correctly from the matcher name.
7791 MATCHER_P(_is_Greater_Than32and_, n, "") { return arg > 32 && arg > n; }
7792
7793 TEST(MatcherPMacroTest, GeneratesCorrectDescription) {
7794   const Matcher<int> m = _is_Greater_Than32and_(5);
7795
7796   EXPECT_EQ("is greater than 32 and 5", Describe(m));
7797   EXPECT_EQ("not (is greater than 32 and 5)", DescribeNegation(m));
7798   EXPECT_EQ("", Explain(m, 36));
7799   EXPECT_EQ("", Explain(m, 5));
7800 }
7801
7802 // Tests that a MATCHER_P matcher can be explicitly instantiated with
7803 // a reference parameter type.
7804
7805 class UncopyableFoo {
7806  public:
7807   explicit UncopyableFoo(char value) : value_(value) { (void)value_; }
7808
7809   UncopyableFoo(const UncopyableFoo&) = delete;
7810   void operator=(const UncopyableFoo&) = delete;
7811
7812  private:
7813   char value_;
7814 };
7815
7816 MATCHER_P(ReferencesUncopyable, variable, "") { return &arg == &variable; }
7817
7818 TEST(MatcherPMacroTest, WorksWhenExplicitlyInstantiatedWithReference) {
7819   UncopyableFoo foo1('1'), foo2('2');
7820   const Matcher<const UncopyableFoo&> m =
7821       ReferencesUncopyable<const UncopyableFoo&>(foo1);
7822
7823   EXPECT_TRUE(m.Matches(foo1));
7824   EXPECT_FALSE(m.Matches(foo2));
7825
7826   // We don't want the address of the parameter printed, as most
7827   // likely it will just annoy the user.  If the address is
7828   // interesting, the user should consider passing the parameter by
7829   // pointer instead.
7830   EXPECT_EQ("references uncopyable 1-byte object <31>", Describe(m));
7831 }
7832
7833 // Tests that the body of MATCHER_Pn() can reference the parameter
7834 // types.
7835
7836 MATCHER_P3(ParamTypesAreIntLongAndChar, foo, bar, baz, "") {
7837   StaticAssertTypeEq<int, foo_type>();
7838   StaticAssertTypeEq<long, bar_type>();  // NOLINT
7839   StaticAssertTypeEq<char, baz_type>();
7840   return arg == 0;
7841 }
7842
7843 TEST(MatcherPnMacroTest, CanReferenceParamTypes) {
7844   EXPECT_THAT(0, ParamTypesAreIntLongAndChar(10, 20L, 'a'));
7845 }
7846
7847 // Tests that a MATCHER_Pn matcher can be explicitly instantiated with
7848 // reference parameter types.
7849
7850 MATCHER_P2(ReferencesAnyOf, variable1, variable2, "") {
7851   return &arg == &variable1 || &arg == &variable2;
7852 }
7853
7854 TEST(MatcherPnMacroTest, WorksWhenExplicitlyInstantiatedWithReferences) {
7855   UncopyableFoo foo1('1'), foo2('2'), foo3('3');
7856   const Matcher<const UncopyableFoo&> const_m =
7857       ReferencesAnyOf<const UncopyableFoo&, const UncopyableFoo&>(foo1, foo2);
7858
7859   EXPECT_TRUE(const_m.Matches(foo1));
7860   EXPECT_TRUE(const_m.Matches(foo2));
7861   EXPECT_FALSE(const_m.Matches(foo3));
7862
7863   const Matcher<UncopyableFoo&> m =
7864       ReferencesAnyOf<UncopyableFoo&, UncopyableFoo&>(foo1, foo2);
7865
7866   EXPECT_TRUE(m.Matches(foo1));
7867   EXPECT_TRUE(m.Matches(foo2));
7868   EXPECT_FALSE(m.Matches(foo3));
7869 }
7870
7871 TEST(MatcherPnMacroTest,
7872      GeneratesCorretDescriptionWhenExplicitlyInstantiatedWithReferences) {
7873   UncopyableFoo foo1('1'), foo2('2');
7874   const Matcher<const UncopyableFoo&> m =
7875       ReferencesAnyOf<const UncopyableFoo&, const UncopyableFoo&>(foo1, foo2);
7876
7877   // We don't want the addresses of the parameters printed, as most
7878   // likely they will just annoy the user.  If the addresses are
7879   // interesting, the user should consider passing the parameters by
7880   // pointers instead.
7881   EXPECT_EQ("references any of (1-byte object <31>, 1-byte object <32>)",
7882             Describe(m));
7883 }
7884
7885 // Tests that a simple MATCHER_P2() definition works.
7886
7887 MATCHER_P2(IsNotInClosedRange, low, hi, "") { return arg < low || arg > hi; }
7888
7889 TEST(MatcherPnMacroTest, Works) {
7890   const Matcher<const long&> m = IsNotInClosedRange(10, 20);  // NOLINT
7891   EXPECT_TRUE(m.Matches(36L));
7892   EXPECT_FALSE(m.Matches(15L));
7893
7894   EXPECT_EQ("is not in closed range (10, 20)", Describe(m));
7895   EXPECT_EQ("not (is not in closed range (10, 20))", DescribeNegation(m));
7896   EXPECT_EQ("", Explain(m, 36L));
7897   EXPECT_EQ("", Explain(m, 15L));
7898 }
7899
7900 // Tests that MATCHER*() definitions can be overloaded on the number
7901 // of parameters; also tests MATCHER_Pn() where n >= 3.
7902
7903 MATCHER(EqualsSumOf, "") { return arg == 0; }
7904 MATCHER_P(EqualsSumOf, a, "") { return arg == a; }
7905 MATCHER_P2(EqualsSumOf, a, b, "") { return arg == a + b; }
7906 MATCHER_P3(EqualsSumOf, a, b, c, "") { return arg == a + b + c; }
7907 MATCHER_P4(EqualsSumOf, a, b, c, d, "") { return arg == a + b + c + d; }
7908 MATCHER_P5(EqualsSumOf, a, b, c, d, e, "") { return arg == a + b + c + d + e; }
7909 MATCHER_P6(EqualsSumOf, a, b, c, d, e, f, "") {
7910   return arg == a + b + c + d + e + f;
7911 }
7912 MATCHER_P7(EqualsSumOf, a, b, c, d, e, f, g, "") {
7913   return arg == a + b + c + d + e + f + g;
7914 }
7915 MATCHER_P8(EqualsSumOf, a, b, c, d, e, f, g, h, "") {
7916   return arg == a + b + c + d + e + f + g + h;
7917 }
7918 MATCHER_P9(EqualsSumOf, a, b, c, d, e, f, g, h, i, "") {
7919   return arg == a + b + c + d + e + f + g + h + i;
7920 }
7921 MATCHER_P10(EqualsSumOf, a, b, c, d, e, f, g, h, i, j, "") {
7922   return arg == a + b + c + d + e + f + g + h + i + j;
7923 }
7924
7925 TEST(MatcherPnMacroTest, CanBeOverloadedOnNumberOfParameters) {
7926   EXPECT_THAT(0, EqualsSumOf());
7927   EXPECT_THAT(1, EqualsSumOf(1));
7928   EXPECT_THAT(12, EqualsSumOf(10, 2));
7929   EXPECT_THAT(123, EqualsSumOf(100, 20, 3));
7930   EXPECT_THAT(1234, EqualsSumOf(1000, 200, 30, 4));
7931   EXPECT_THAT(12345, EqualsSumOf(10000, 2000, 300, 40, 5));
7932   EXPECT_THAT("abcdef",
7933               EqualsSumOf(::std::string("a"), 'b', 'c', "d", "e", 'f'));
7934   EXPECT_THAT("abcdefg",
7935               EqualsSumOf(::std::string("a"), 'b', 'c', "d", "e", 'f', 'g'));
7936   EXPECT_THAT("abcdefgh", EqualsSumOf(::std::string("a"), 'b', 'c', "d", "e",
7937                                       'f', 'g', "h"));
7938   EXPECT_THAT("abcdefghi", EqualsSumOf(::std::string("a"), 'b', 'c', "d", "e",
7939                                        'f', 'g', "h", 'i'));
7940   EXPECT_THAT("abcdefghij",
7941               EqualsSumOf(::std::string("a"), 'b', 'c', "d", "e", 'f', 'g', "h",
7942                           'i', ::std::string("j")));
7943
7944   EXPECT_THAT(1, Not(EqualsSumOf()));
7945   EXPECT_THAT(-1, Not(EqualsSumOf(1)));
7946   EXPECT_THAT(-12, Not(EqualsSumOf(10, 2)));
7947   EXPECT_THAT(-123, Not(EqualsSumOf(100, 20, 3)));
7948   EXPECT_THAT(-1234, Not(EqualsSumOf(1000, 200, 30, 4)));
7949   EXPECT_THAT(-12345, Not(EqualsSumOf(10000, 2000, 300, 40, 5)));
7950   EXPECT_THAT("abcdef ",
7951               Not(EqualsSumOf(::std::string("a"), 'b', 'c', "d", "e", 'f')));
7952   EXPECT_THAT("abcdefg ", Not(EqualsSumOf(::std::string("a"), 'b', 'c', "d",
7953                                           "e", 'f', 'g')));
7954   EXPECT_THAT("abcdefgh ", Not(EqualsSumOf(::std::string("a"), 'b', 'c', "d",
7955                                            "e", 'f', 'g', "h")));
7956   EXPECT_THAT("abcdefghi ", Not(EqualsSumOf(::std::string("a"), 'b', 'c', "d",
7957                                             "e", 'f', 'g', "h", 'i')));
7958   EXPECT_THAT("abcdefghij ",
7959               Not(EqualsSumOf(::std::string("a"), 'b', 'c', "d", "e", 'f', 'g',
7960                               "h", 'i', ::std::string("j"))));
7961 }
7962
7963 // Tests that a MATCHER_Pn() definition can be instantiated with any
7964 // compatible parameter types.
7965 TEST(MatcherPnMacroTest, WorksForDifferentParameterTypes) {
7966   EXPECT_THAT(123, EqualsSumOf(100L, 20, static_cast<char>(3)));
7967   EXPECT_THAT("abcd", EqualsSumOf(::std::string("a"), "b", 'c', "d"));
7968
7969   EXPECT_THAT(124, Not(EqualsSumOf(100L, 20, static_cast<char>(3))));
7970   EXPECT_THAT("abcde", Not(EqualsSumOf(::std::string("a"), "b", 'c', "d")));
7971 }
7972
7973 // Tests that the matcher body can promote the parameter types.
7974
7975 MATCHER_P2(EqConcat, prefix, suffix, "") {
7976   // The following lines promote the two parameters to desired types.
7977   std::string prefix_str(prefix);
7978   char suffix_char = static_cast<char>(suffix);
7979   return arg == prefix_str + suffix_char;
7980 }
7981
7982 TEST(MatcherPnMacroTest, SimpleTypePromotion) {
7983   Matcher<std::string> no_promo = EqConcat(std::string("foo"), 't');
7984   Matcher<const std::string&> promo = EqConcat("foo", static_cast<int>('t'));
7985   EXPECT_FALSE(no_promo.Matches("fool"));
7986   EXPECT_FALSE(promo.Matches("fool"));
7987   EXPECT_TRUE(no_promo.Matches("foot"));
7988   EXPECT_TRUE(promo.Matches("foot"));
7989 }
7990
7991 // Verifies the type of a MATCHER*.
7992
7993 TEST(MatcherPnMacroTest, TypesAreCorrect) {
7994   // EqualsSumOf() must be assignable to a EqualsSumOfMatcher variable.
7995   EqualsSumOfMatcher a0 = EqualsSumOf();
7996
7997   // EqualsSumOf(1) must be assignable to a EqualsSumOfMatcherP variable.
7998   EqualsSumOfMatcherP<int> a1 = EqualsSumOf(1);
7999
8000   // EqualsSumOf(p1, ..., pk) must be assignable to a EqualsSumOfMatcherPk
8001   // variable, and so on.
8002   EqualsSumOfMatcherP2<int, char> a2 = EqualsSumOf(1, '2');
8003   EqualsSumOfMatcherP3<int, int, char> a3 = EqualsSumOf(1, 2, '3');
8004   EqualsSumOfMatcherP4<int, int, int, char> a4 = EqualsSumOf(1, 2, 3, '4');
8005   EqualsSumOfMatcherP5<int, int, int, int, char> a5 =
8006       EqualsSumOf(1, 2, 3, 4, '5');
8007   EqualsSumOfMatcherP6<int, int, int, int, int, char> a6 =
8008       EqualsSumOf(1, 2, 3, 4, 5, '6');
8009   EqualsSumOfMatcherP7<int, int, int, int, int, int, char> a7 =
8010       EqualsSumOf(1, 2, 3, 4, 5, 6, '7');
8011   EqualsSumOfMatcherP8<int, int, int, int, int, int, int, char> a8 =
8012       EqualsSumOf(1, 2, 3, 4, 5, 6, 7, '8');
8013   EqualsSumOfMatcherP9<int, int, int, int, int, int, int, int, char> a9 =
8014       EqualsSumOf(1, 2, 3, 4, 5, 6, 7, 8, '9');
8015   EqualsSumOfMatcherP10<int, int, int, int, int, int, int, int, int, char> a10 =
8016       EqualsSumOf(1, 2, 3, 4, 5, 6, 7, 8, 9, '0');
8017
8018   // Avoid "unused variable" warnings.
8019   (void)a0;
8020   (void)a1;
8021   (void)a2;
8022   (void)a3;
8023   (void)a4;
8024   (void)a5;
8025   (void)a6;
8026   (void)a7;
8027   (void)a8;
8028   (void)a9;
8029   (void)a10;
8030 }
8031
8032 // Tests that matcher-typed parameters can be used in Value() inside a
8033 // MATCHER_Pn definition.
8034
8035 // Succeeds if arg matches exactly 2 of the 3 matchers.
8036 MATCHER_P3(TwoOf, m1, m2, m3, "") {
8037   const int count = static_cast<int>(Value(arg, m1)) +
8038                     static_cast<int>(Value(arg, m2)) +
8039                     static_cast<int>(Value(arg, m3));
8040   return count == 2;
8041 }
8042
8043 TEST(MatcherPnMacroTest, CanUseMatcherTypedParameterInValue) {
8044   EXPECT_THAT(42, TwoOf(Gt(0), Lt(50), Eq(10)));
8045   EXPECT_THAT(0, Not(TwoOf(Gt(-1), Lt(1), Eq(0))));
8046 }
8047
8048 // Tests Contains().
8049
8050 TEST(ContainsTest, ListMatchesWhenElementIsInContainer) {
8051   list<int> some_list;
8052   some_list.push_back(3);
8053   some_list.push_back(1);
8054   some_list.push_back(2);
8055   some_list.push_back(3);
8056   EXPECT_THAT(some_list, Contains(1));
8057   EXPECT_THAT(some_list, Contains(Gt(2.5)));
8058   EXPECT_THAT(some_list, Contains(Eq(2.0f)));
8059
8060   list<std::string> another_list;
8061   another_list.push_back("fee");
8062   another_list.push_back("fie");
8063   another_list.push_back("foe");
8064   another_list.push_back("fum");
8065   EXPECT_THAT(another_list, Contains(std::string("fee")));
8066 }
8067
8068 TEST(ContainsTest, ListDoesNotMatchWhenElementIsNotInContainer) {
8069   list<int> some_list;
8070   some_list.push_back(3);
8071   some_list.push_back(1);
8072   EXPECT_THAT(some_list, Not(Contains(4)));
8073 }
8074
8075 TEST(ContainsTest, SetMatchesWhenElementIsInContainer) {
8076   set<int> some_set;
8077   some_set.insert(3);
8078   some_set.insert(1);
8079   some_set.insert(2);
8080   EXPECT_THAT(some_set, Contains(Eq(1.0)));
8081   EXPECT_THAT(some_set, Contains(Eq(3.0f)));
8082   EXPECT_THAT(some_set, Contains(2));
8083
8084   set<std::string> another_set;
8085   another_set.insert("fee");
8086   another_set.insert("fie");
8087   another_set.insert("foe");
8088   another_set.insert("fum");
8089   EXPECT_THAT(another_set, Contains(Eq(std::string("fum"))));
8090 }
8091
8092 TEST(ContainsTest, SetDoesNotMatchWhenElementIsNotInContainer) {
8093   set<int> some_set;
8094   some_set.insert(3);
8095   some_set.insert(1);
8096   EXPECT_THAT(some_set, Not(Contains(4)));
8097
8098   set<std::string> c_string_set;
8099   c_string_set.insert("hello");
8100   EXPECT_THAT(c_string_set, Not(Contains(std::string("goodbye"))));
8101 }
8102
8103 TEST(ContainsTest, ExplainsMatchResultCorrectly) {
8104   const int a[2] = {1, 2};
8105   Matcher<const int(&)[2]> m = Contains(2);
8106   EXPECT_EQ("whose element #1 matches", Explain(m, a));
8107
8108   m = Contains(3);
8109   EXPECT_EQ("", Explain(m, a));
8110
8111   m = Contains(GreaterThan(0));
8112   EXPECT_EQ("whose element #0 matches, which is 1 more than 0", Explain(m, a));
8113
8114   m = Contains(GreaterThan(10));
8115   EXPECT_EQ("", Explain(m, a));
8116 }
8117
8118 TEST(ContainsTest, DescribesItselfCorrectly) {
8119   Matcher<vector<int>> m = Contains(1);
8120   EXPECT_EQ("contains at least one element that is equal to 1", Describe(m));
8121
8122   Matcher<vector<int>> m2 = Not(m);
8123   EXPECT_EQ("doesn't contain any element that is equal to 1", Describe(m2));
8124 }
8125
8126 TEST(ContainsTest, MapMatchesWhenElementIsInContainer) {
8127   map<std::string, int> my_map;
8128   const char* bar = "a string";
8129   my_map[bar] = 2;
8130   EXPECT_THAT(my_map, Contains(pair<const char* const, int>(bar, 2)));
8131
8132   map<std::string, int> another_map;
8133   another_map["fee"] = 1;
8134   another_map["fie"] = 2;
8135   another_map["foe"] = 3;
8136   another_map["fum"] = 4;
8137   EXPECT_THAT(another_map,
8138               Contains(pair<const std::string, int>(std::string("fee"), 1)));
8139   EXPECT_THAT(another_map, Contains(pair<const std::string, int>("fie", 2)));
8140 }
8141
8142 TEST(ContainsTest, MapDoesNotMatchWhenElementIsNotInContainer) {
8143   map<int, int> some_map;
8144   some_map[1] = 11;
8145   some_map[2] = 22;
8146   EXPECT_THAT(some_map, Not(Contains(pair<const int, int>(2, 23))));
8147 }
8148
8149 TEST(ContainsTest, ArrayMatchesWhenElementIsInContainer) {
8150   const char* string_array[] = {"fee", "fie", "foe", "fum"};
8151   EXPECT_THAT(string_array, Contains(Eq(std::string("fum"))));
8152 }
8153
8154 TEST(ContainsTest, ArrayDoesNotMatchWhenElementIsNotInContainer) {
8155   int int_array[] = {1, 2, 3, 4};
8156   EXPECT_THAT(int_array, Not(Contains(5)));
8157 }
8158
8159 TEST(ContainsTest, AcceptsMatcher) {
8160   const int a[] = {1, 2, 3};
8161   EXPECT_THAT(a, Contains(Gt(2)));
8162   EXPECT_THAT(a, Not(Contains(Gt(4))));
8163 }
8164
8165 TEST(ContainsTest, WorksForNativeArrayAsTuple) {
8166   const int a[] = {1, 2};
8167   const int* const pointer = a;
8168   EXPECT_THAT(std::make_tuple(pointer, 2), Contains(1));
8169   EXPECT_THAT(std::make_tuple(pointer, 2), Not(Contains(Gt(3))));
8170 }
8171
8172 TEST(ContainsTest, WorksForTwoDimensionalNativeArray) {
8173   int a[][3] = {{1, 2, 3}, {4, 5, 6}};
8174   EXPECT_THAT(a, Contains(ElementsAre(4, 5, 6)));
8175   EXPECT_THAT(a, Contains(Contains(5)));
8176   EXPECT_THAT(a, Not(Contains(ElementsAre(3, 4, 5))));
8177   EXPECT_THAT(a, Contains(Not(Contains(5))));
8178 }
8179
8180 // Tests Contains().Times().
8181
8182 TEST(ContainsTimes, ListMatchesWhenElementQuantityMatches) {
8183   list<int> some_list;
8184   some_list.push_back(3);
8185   some_list.push_back(1);
8186   some_list.push_back(2);
8187   some_list.push_back(3);
8188   EXPECT_THAT(some_list, Contains(3).Times(2));
8189   EXPECT_THAT(some_list, Contains(2).Times(1));
8190   EXPECT_THAT(some_list, Contains(Ge(2)).Times(3));
8191   EXPECT_THAT(some_list, Contains(Ge(2)).Times(Gt(2)));
8192   EXPECT_THAT(some_list, Contains(4).Times(0));
8193   EXPECT_THAT(some_list, Contains(_).Times(4));
8194   EXPECT_THAT(some_list, Not(Contains(5).Times(1)));
8195   EXPECT_THAT(some_list, Contains(5).Times(_));  // Times(_) always matches
8196   EXPECT_THAT(some_list, Not(Contains(3).Times(1)));
8197   EXPECT_THAT(some_list, Contains(3).Times(Not(1)));
8198   EXPECT_THAT(list<int>{}, Not(Contains(_)));
8199 }
8200
8201 TEST(ContainsTimes, ExplainsMatchResultCorrectly) {
8202   const int a[2] = {1, 2};
8203   Matcher<const int(&)[2]> m = Contains(2).Times(3);
8204   EXPECT_EQ(
8205       "whose element #1 matches but whose match quantity of 1 does not match",
8206       Explain(m, a));
8207
8208   m = Contains(3).Times(0);
8209   EXPECT_EQ("has no element that matches and whose match quantity of 0 matches",
8210             Explain(m, a));
8211
8212   m = Contains(3).Times(4);
8213   EXPECT_EQ(
8214       "has no element that matches and whose match quantity of 0 does not "
8215       "match",
8216       Explain(m, a));
8217
8218   m = Contains(2).Times(4);
8219   EXPECT_EQ(
8220       "whose element #1 matches but whose match quantity of 1 does not "
8221       "match",
8222       Explain(m, a));
8223
8224   m = Contains(GreaterThan(0)).Times(2);
8225   EXPECT_EQ("whose elements (0, 1) match and whose match quantity of 2 matches",
8226             Explain(m, a));
8227
8228   m = Contains(GreaterThan(10)).Times(Gt(1));
8229   EXPECT_EQ(
8230       "has no element that matches and whose match quantity of 0 does not "
8231       "match",
8232       Explain(m, a));
8233
8234   m = Contains(GreaterThan(0)).Times(GreaterThan<size_t>(5));
8235   EXPECT_EQ(
8236       "whose elements (0, 1) match but whose match quantity of 2 does not "
8237       "match, which is 3 less than 5",
8238       Explain(m, a));
8239 }
8240
8241 TEST(ContainsTimes, DescribesItselfCorrectly) {
8242   Matcher<vector<int>> m = Contains(1).Times(2);
8243   EXPECT_EQ("quantity of elements that match is equal to 1 is equal to 2",
8244             Describe(m));
8245
8246   Matcher<vector<int>> m2 = Not(m);
8247   EXPECT_EQ("quantity of elements that match is equal to 1 isn't equal to 2",
8248             Describe(m2));
8249 }
8250
8251 // Tests AllOfArray()
8252
8253 TEST(AllOfArrayTest, BasicForms) {
8254   // Iterator
8255   std::vector<int> v0{};
8256   std::vector<int> v1{1};
8257   std::vector<int> v2{2, 3};
8258   std::vector<int> v3{4, 4, 4};
8259   EXPECT_THAT(0, AllOfArray(v0.begin(), v0.end()));
8260   EXPECT_THAT(1, AllOfArray(v1.begin(), v1.end()));
8261   EXPECT_THAT(2, Not(AllOfArray(v1.begin(), v1.end())));
8262   EXPECT_THAT(3, Not(AllOfArray(v2.begin(), v2.end())));
8263   EXPECT_THAT(4, AllOfArray(v3.begin(), v3.end()));
8264   // Pointer +  size
8265   int ar[6] = {1, 2, 3, 4, 4, 4};
8266   EXPECT_THAT(0, AllOfArray(ar, 0));
8267   EXPECT_THAT(1, AllOfArray(ar, 1));
8268   EXPECT_THAT(2, Not(AllOfArray(ar, 1)));
8269   EXPECT_THAT(3, Not(AllOfArray(ar + 1, 3)));
8270   EXPECT_THAT(4, AllOfArray(ar + 3, 3));
8271   // Array
8272   // int ar0[0];  Not usable
8273   int ar1[1] = {1};
8274   int ar2[2] = {2, 3};
8275   int ar3[3] = {4, 4, 4};
8276   // EXPECT_THAT(0, Not(AllOfArray(ar0)));  // Cannot work
8277   EXPECT_THAT(1, AllOfArray(ar1));
8278   EXPECT_THAT(2, Not(AllOfArray(ar1)));
8279   EXPECT_THAT(3, Not(AllOfArray(ar2)));
8280   EXPECT_THAT(4, AllOfArray(ar3));
8281   // Container
8282   EXPECT_THAT(0, AllOfArray(v0));
8283   EXPECT_THAT(1, AllOfArray(v1));
8284   EXPECT_THAT(2, Not(AllOfArray(v1)));
8285   EXPECT_THAT(3, Not(AllOfArray(v2)));
8286   EXPECT_THAT(4, AllOfArray(v3));
8287   // Initializer
8288   EXPECT_THAT(0, AllOfArray<int>({}));  // Requires template arg.
8289   EXPECT_THAT(1, AllOfArray({1}));
8290   EXPECT_THAT(2, Not(AllOfArray({1})));
8291   EXPECT_THAT(3, Not(AllOfArray({2, 3})));
8292   EXPECT_THAT(4, AllOfArray({4, 4, 4}));
8293 }
8294
8295 TEST(AllOfArrayTest, Matchers) {
8296   // vector
8297   std::vector<Matcher<int>> matchers{Ge(1), Lt(2)};
8298   EXPECT_THAT(0, Not(AllOfArray(matchers)));
8299   EXPECT_THAT(1, AllOfArray(matchers));
8300   EXPECT_THAT(2, Not(AllOfArray(matchers)));
8301   // initializer_list
8302   EXPECT_THAT(0, Not(AllOfArray({Ge(0), Ge(1)})));
8303   EXPECT_THAT(1, AllOfArray({Ge(0), Ge(1)}));
8304 }
8305
8306 TEST(AnyOfArrayTest, BasicForms) {
8307   // Iterator
8308   std::vector<int> v0{};
8309   std::vector<int> v1{1};
8310   std::vector<int> v2{2, 3};
8311   EXPECT_THAT(0, Not(AnyOfArray(v0.begin(), v0.end())));
8312   EXPECT_THAT(1, AnyOfArray(v1.begin(), v1.end()));
8313   EXPECT_THAT(2, Not(AnyOfArray(v1.begin(), v1.end())));
8314   EXPECT_THAT(3, AnyOfArray(v2.begin(), v2.end()));
8315   EXPECT_THAT(4, Not(AnyOfArray(v2.begin(), v2.end())));
8316   // Pointer +  size
8317   int ar[3] = {1, 2, 3};
8318   EXPECT_THAT(0, Not(AnyOfArray(ar, 0)));
8319   EXPECT_THAT(1, AnyOfArray(ar, 1));
8320   EXPECT_THAT(2, Not(AnyOfArray(ar, 1)));
8321   EXPECT_THAT(3, AnyOfArray(ar + 1, 2));
8322   EXPECT_THAT(4, Not(AnyOfArray(ar + 1, 2)));
8323   // Array
8324   // int ar0[0];  Not usable
8325   int ar1[1] = {1};
8326   int ar2[2] = {2, 3};
8327   // EXPECT_THAT(0, Not(AnyOfArray(ar0)));  // Cannot work
8328   EXPECT_THAT(1, AnyOfArray(ar1));
8329   EXPECT_THAT(2, Not(AnyOfArray(ar1)));
8330   EXPECT_THAT(3, AnyOfArray(ar2));
8331   EXPECT_THAT(4, Not(AnyOfArray(ar2)));
8332   // Container
8333   EXPECT_THAT(0, Not(AnyOfArray(v0)));
8334   EXPECT_THAT(1, AnyOfArray(v1));
8335   EXPECT_THAT(2, Not(AnyOfArray(v1)));
8336   EXPECT_THAT(3, AnyOfArray(v2));
8337   EXPECT_THAT(4, Not(AnyOfArray(v2)));
8338   // Initializer
8339   EXPECT_THAT(0, Not(AnyOfArray<int>({})));  // Requires template arg.
8340   EXPECT_THAT(1, AnyOfArray({1}));
8341   EXPECT_THAT(2, Not(AnyOfArray({1})));
8342   EXPECT_THAT(3, AnyOfArray({2, 3}));
8343   EXPECT_THAT(4, Not(AnyOfArray({2, 3})));
8344 }
8345
8346 TEST(AnyOfArrayTest, Matchers) {
8347   // We negate test AllOfArrayTest.Matchers.
8348   // vector
8349   std::vector<Matcher<int>> matchers{Lt(1), Ge(2)};
8350   EXPECT_THAT(0, AnyOfArray(matchers));
8351   EXPECT_THAT(1, Not(AnyOfArray(matchers)));
8352   EXPECT_THAT(2, AnyOfArray(matchers));
8353   // initializer_list
8354   EXPECT_THAT(0, AnyOfArray({Lt(0), Lt(1)}));
8355   EXPECT_THAT(1, Not(AllOfArray({Lt(0), Lt(1)})));
8356 }
8357
8358 TEST(AnyOfArrayTest, ExplainsMatchResultCorrectly) {
8359   // AnyOfArray and AllOfArry use the same underlying template-template,
8360   // thus it is sufficient to test one here.
8361   const std::vector<int> v0{};
8362   const std::vector<int> v1{1};
8363   const std::vector<int> v2{2, 3};
8364   const Matcher<int> m0 = AnyOfArray(v0);
8365   const Matcher<int> m1 = AnyOfArray(v1);
8366   const Matcher<int> m2 = AnyOfArray(v2);
8367   EXPECT_EQ("", Explain(m0, 0));
8368   EXPECT_EQ("", Explain(m1, 1));
8369   EXPECT_EQ("", Explain(m1, 2));
8370   EXPECT_EQ("", Explain(m2, 3));
8371   EXPECT_EQ("", Explain(m2, 4));
8372   EXPECT_EQ("()", Describe(m0));
8373   EXPECT_EQ("(is equal to 1)", Describe(m1));
8374   EXPECT_EQ("(is equal to 2) or (is equal to 3)", Describe(m2));
8375   EXPECT_EQ("()", DescribeNegation(m0));
8376   EXPECT_EQ("(isn't equal to 1)", DescribeNegation(m1));
8377   EXPECT_EQ("(isn't equal to 2) and (isn't equal to 3)", DescribeNegation(m2));
8378   // Explain with matchers
8379   const Matcher<int> g1 = AnyOfArray({GreaterThan(1)});
8380   const Matcher<int> g2 = AnyOfArray({GreaterThan(1), GreaterThan(2)});
8381   // Explains the first positiv match and all prior negative matches...
8382   EXPECT_EQ("which is 1 less than 1", Explain(g1, 0));
8383   EXPECT_EQ("which is the same as 1", Explain(g1, 1));
8384   EXPECT_EQ("which is 1 more than 1", Explain(g1, 2));
8385   EXPECT_EQ("which is 1 less than 1, and which is 2 less than 2",
8386             Explain(g2, 0));
8387   EXPECT_EQ("which is the same as 1, and which is 1 less than 2",
8388             Explain(g2, 1));
8389   EXPECT_EQ("which is 1 more than 1",  // Only the first
8390             Explain(g2, 2));
8391 }
8392
8393 TEST(AllOfTest, HugeMatcher) {
8394   // Verify that using AllOf with many arguments doesn't cause
8395   // the compiler to exceed template instantiation depth limit.
8396   EXPECT_THAT(0, testing::AllOf(_, _, _, _, _, _, _, _, _,
8397                                 testing::AllOf(_, _, _, _, _, _, _, _, _, _)));
8398 }
8399
8400 TEST(AnyOfTest, HugeMatcher) {
8401   // Verify that using AnyOf with many arguments doesn't cause
8402   // the compiler to exceed template instantiation depth limit.
8403   EXPECT_THAT(0, testing::AnyOf(_, _, _, _, _, _, _, _, _,
8404                                 testing::AnyOf(_, _, _, _, _, _, _, _, _, _)));
8405 }
8406
8407 namespace adl_test {
8408
8409 // Verifies that the implementation of ::testing::AllOf and ::testing::AnyOf
8410 // don't issue unqualified recursive calls.  If they do, the argument dependent
8411 // name lookup will cause AllOf/AnyOf in the 'adl_test' namespace to be found
8412 // as a candidate and the compilation will break due to an ambiguous overload.
8413
8414 // The matcher must be in the same namespace as AllOf/AnyOf to make argument
8415 // dependent lookup find those.
8416 MATCHER(M, "") {
8417   (void)arg;
8418   return true;
8419 }
8420
8421 template <typename T1, typename T2>
8422 bool AllOf(const T1& /*t1*/, const T2& /*t2*/) {
8423   return true;
8424 }
8425
8426 TEST(AllOfTest, DoesNotCallAllOfUnqualified) {
8427   EXPECT_THAT(42,
8428               testing::AllOf(M(), M(), M(), M(), M(), M(), M(), M(), M(), M()));
8429 }
8430
8431 template <typename T1, typename T2>
8432 bool AnyOf(const T1&, const T2&) {
8433   return true;
8434 }
8435
8436 TEST(AnyOfTest, DoesNotCallAnyOfUnqualified) {
8437   EXPECT_THAT(42,
8438               testing::AnyOf(M(), M(), M(), M(), M(), M(), M(), M(), M(), M()));
8439 }
8440
8441 }  // namespace adl_test
8442
8443 TEST(AllOfTest, WorksOnMoveOnlyType) {
8444   std::unique_ptr<int> p(new int(3));
8445   EXPECT_THAT(p, AllOf(Pointee(Eq(3)), Pointee(Gt(0)), Pointee(Lt(5))));
8446   EXPECT_THAT(p, Not(AllOf(Pointee(Eq(3)), Pointee(Gt(0)), Pointee(Lt(3)))));
8447 }
8448
8449 TEST(AnyOfTest, WorksOnMoveOnlyType) {
8450   std::unique_ptr<int> p(new int(3));
8451   EXPECT_THAT(p, AnyOf(Pointee(Eq(5)), Pointee(Lt(0)), Pointee(Lt(5))));
8452   EXPECT_THAT(p, Not(AnyOf(Pointee(Eq(5)), Pointee(Lt(0)), Pointee(Gt(5)))));
8453 }
8454
8455 MATCHER(IsNotNull, "") { return arg != nullptr; }
8456
8457 // Verifies that a matcher defined using MATCHER() can work on
8458 // move-only types.
8459 TEST(MatcherMacroTest, WorksOnMoveOnlyType) {
8460   std::unique_ptr<int> p(new int(3));
8461   EXPECT_THAT(p, IsNotNull());
8462   EXPECT_THAT(std::unique_ptr<int>(), Not(IsNotNull()));
8463 }
8464
8465 MATCHER_P(UniquePointee, pointee, "") { return *arg == pointee; }
8466
8467 // Verifies that a matcher defined using MATCHER_P*() can work on
8468 // move-only types.
8469 TEST(MatcherPMacroTest, WorksOnMoveOnlyType) {
8470   std::unique_ptr<int> p(new int(3));
8471   EXPECT_THAT(p, UniquePointee(3));
8472   EXPECT_THAT(p, Not(UniquePointee(2)));
8473 }
8474
8475 #if GTEST_HAS_EXCEPTIONS
8476
8477 // std::function<void()> is used below for compatibility with older copies of
8478 // GCC. Normally, a raw lambda is all that is needed.
8479
8480 // Test that examples from documentation compile
8481 TEST(ThrowsTest, Examples) {
8482   EXPECT_THAT(
8483       std::function<void()>([]() { throw std::runtime_error("message"); }),
8484       Throws<std::runtime_error>());
8485
8486   EXPECT_THAT(
8487       std::function<void()>([]() { throw std::runtime_error("message"); }),
8488       ThrowsMessage<std::runtime_error>(HasSubstr("message")));
8489 }
8490
8491 TEST(ThrowsTest, DoesNotGenerateDuplicateCatchClauseWarning) {
8492   EXPECT_THAT(std::function<void()>([]() { throw std::exception(); }),
8493               Throws<std::exception>());
8494 }
8495
8496 TEST(ThrowsTest, CallableExecutedExactlyOnce) {
8497   size_t a = 0;
8498
8499   EXPECT_THAT(std::function<void()>([&a]() {
8500                 a++;
8501                 throw 10;
8502               }),
8503               Throws<int>());
8504   EXPECT_EQ(a, 1u);
8505
8506   EXPECT_THAT(std::function<void()>([&a]() {
8507                 a++;
8508                 throw std::runtime_error("message");
8509               }),
8510               Throws<std::runtime_error>());
8511   EXPECT_EQ(a, 2u);
8512
8513   EXPECT_THAT(std::function<void()>([&a]() {
8514                 a++;
8515                 throw std::runtime_error("message");
8516               }),
8517               ThrowsMessage<std::runtime_error>(HasSubstr("message")));
8518   EXPECT_EQ(a, 3u);
8519
8520   EXPECT_THAT(std::function<void()>([&a]() {
8521                 a++;
8522                 throw std::runtime_error("message");
8523               }),
8524               Throws<std::runtime_error>(
8525                   Property(&std::runtime_error::what, HasSubstr("message"))));
8526   EXPECT_EQ(a, 4u);
8527 }
8528
8529 TEST(ThrowsTest, Describe) {
8530   Matcher<std::function<void()>> matcher = Throws<std::runtime_error>();
8531   std::stringstream ss;
8532   matcher.DescribeTo(&ss);
8533   auto explanation = ss.str();
8534   EXPECT_THAT(explanation, HasSubstr("std::runtime_error"));
8535 }
8536
8537 TEST(ThrowsTest, Success) {
8538   Matcher<std::function<void()>> matcher = Throws<std::runtime_error>();
8539   StringMatchResultListener listener;
8540   EXPECT_TRUE(matcher.MatchAndExplain(
8541       []() { throw std::runtime_error("error message"); }, &listener));
8542   EXPECT_THAT(listener.str(), HasSubstr("std::runtime_error"));
8543 }
8544
8545 TEST(ThrowsTest, FailWrongType) {
8546   Matcher<std::function<void()>> matcher = Throws<std::runtime_error>();
8547   StringMatchResultListener listener;
8548   EXPECT_FALSE(matcher.MatchAndExplain(
8549       []() { throw std::logic_error("error message"); }, &listener));
8550   EXPECT_THAT(listener.str(), HasSubstr("std::logic_error"));
8551   EXPECT_THAT(listener.str(), HasSubstr("\"error message\""));
8552 }
8553
8554 TEST(ThrowsTest, FailWrongTypeNonStd) {
8555   Matcher<std::function<void()>> matcher = Throws<std::runtime_error>();
8556   StringMatchResultListener listener;
8557   EXPECT_FALSE(matcher.MatchAndExplain([]() { throw 10; }, &listener));
8558   EXPECT_THAT(listener.str(),
8559               HasSubstr("throws an exception of an unknown type"));
8560 }
8561
8562 TEST(ThrowsTest, FailNoThrow) {
8563   Matcher<std::function<void()>> matcher = Throws<std::runtime_error>();
8564   StringMatchResultListener listener;
8565   EXPECT_FALSE(matcher.MatchAndExplain([]() { (void)0; }, &listener));
8566   EXPECT_THAT(listener.str(), HasSubstr("does not throw any exception"));
8567 }
8568
8569 class ThrowsPredicateTest
8570     : public TestWithParam<Matcher<std::function<void()>>> {};
8571
8572 TEST_P(ThrowsPredicateTest, Describe) {
8573   Matcher<std::function<void()>> matcher = GetParam();
8574   std::stringstream ss;
8575   matcher.DescribeTo(&ss);
8576   auto explanation = ss.str();
8577   EXPECT_THAT(explanation, HasSubstr("std::runtime_error"));
8578   EXPECT_THAT(explanation, HasSubstr("error message"));
8579 }
8580
8581 TEST_P(ThrowsPredicateTest, Success) {
8582   Matcher<std::function<void()>> matcher = GetParam();
8583   StringMatchResultListener listener;
8584   EXPECT_TRUE(matcher.MatchAndExplain(
8585       []() { throw std::runtime_error("error message"); }, &listener));
8586   EXPECT_THAT(listener.str(), HasSubstr("std::runtime_error"));
8587 }
8588
8589 TEST_P(ThrowsPredicateTest, FailWrongType) {
8590   Matcher<std::function<void()>> matcher = GetParam();
8591   StringMatchResultListener listener;
8592   EXPECT_FALSE(matcher.MatchAndExplain(
8593       []() { throw std::logic_error("error message"); }, &listener));
8594   EXPECT_THAT(listener.str(), HasSubstr("std::logic_error"));
8595   EXPECT_THAT(listener.str(), HasSubstr("\"error message\""));
8596 }
8597
8598 TEST_P(ThrowsPredicateTest, FailWrongTypeNonStd) {
8599   Matcher<std::function<void()>> matcher = GetParam();
8600   StringMatchResultListener listener;
8601   EXPECT_FALSE(matcher.MatchAndExplain([]() { throw 10; }, &listener));
8602   EXPECT_THAT(listener.str(),
8603               HasSubstr("throws an exception of an unknown type"));
8604 }
8605
8606 TEST_P(ThrowsPredicateTest, FailWrongMessage) {
8607   Matcher<std::function<void()>> matcher = GetParam();
8608   StringMatchResultListener listener;
8609   EXPECT_FALSE(matcher.MatchAndExplain(
8610       []() { throw std::runtime_error("wrong message"); }, &listener));
8611   EXPECT_THAT(listener.str(), HasSubstr("std::runtime_error"));
8612   EXPECT_THAT(listener.str(), Not(HasSubstr("wrong message")));
8613 }
8614
8615 TEST_P(ThrowsPredicateTest, FailNoThrow) {
8616   Matcher<std::function<void()>> matcher = GetParam();
8617   StringMatchResultListener listener;
8618   EXPECT_FALSE(matcher.MatchAndExplain([]() {}, &listener));
8619   EXPECT_THAT(listener.str(), HasSubstr("does not throw any exception"));
8620 }
8621
8622 INSTANTIATE_TEST_SUITE_P(
8623     AllMessagePredicates, ThrowsPredicateTest,
8624     Values(Matcher<std::function<void()>>(
8625         ThrowsMessage<std::runtime_error>(HasSubstr("error message")))));
8626
8627 // Tests that Throws<E1>(Matcher<E2>{}) compiles even when E2 != const E1&.
8628 TEST(ThrowsPredicateCompilesTest, ExceptionMatcherAcceptsBroadType) {
8629   {
8630     Matcher<std::function<void()>> matcher =
8631         ThrowsMessage<std::runtime_error>(HasSubstr("error message"));
8632     EXPECT_TRUE(
8633         matcher.Matches([]() { throw std::runtime_error("error message"); }));
8634     EXPECT_FALSE(
8635         matcher.Matches([]() { throw std::runtime_error("wrong message"); }));
8636   }
8637
8638   {
8639     Matcher<uint64_t> inner = Eq(10);
8640     Matcher<std::function<void()>> matcher = Throws<uint32_t>(inner);
8641     EXPECT_TRUE(matcher.Matches([]() { throw(uint32_t) 10; }));
8642     EXPECT_FALSE(matcher.Matches([]() { throw(uint32_t) 11; }));
8643   }
8644 }
8645
8646 // Tests that ThrowsMessage("message") is equivalent
8647 // to ThrowsMessage(Eq<std::string>("message")).
8648 TEST(ThrowsPredicateCompilesTest, MessageMatcherAcceptsNonMatcher) {
8649   Matcher<std::function<void()>> matcher =
8650       ThrowsMessage<std::runtime_error>("error message");
8651   EXPECT_TRUE(
8652       matcher.Matches([]() { throw std::runtime_error("error message"); }));
8653   EXPECT_FALSE(matcher.Matches(
8654       []() { throw std::runtime_error("wrong error message"); }));
8655 }
8656
8657 #endif  // GTEST_HAS_EXCEPTIONS
8658
8659 }  // namespace
8660 }  // namespace gmock_matchers_test
8661 }  // namespace testing
8662
8663 #ifdef _MSC_VER
8664 # pragma warning(pop)
8665 #endif