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