• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright 2007, Google Inc.
2 // All rights reserved.
3 //
4 // Redistribution and use in source and binary forms, with or without
5 // modification, are permitted provided that the following conditions are
6 // met:
7 //
8 //     * Redistributions of source code must retain the above copyright
9 // notice, this list of conditions and the following disclaimer.
10 //     * Redistributions in binary form must reproduce the above
11 // copyright notice, this list of conditions and the following disclaimer
12 // in the documentation and/or other materials provided with the
13 // distribution.
14 //     * Neither the name of Google Inc. nor the names of its
15 // contributors may be used to endorse or promote products derived from
16 // this software without specific prior written permission.
17 //
18 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29 
30 
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 <utility>
64 #include <vector>
65 
66 #include "gmock/gmock-more-matchers.h"
67 #include "gmock/gmock.h"
68 #include "gtest/gtest-spi.h"
69 #include "gtest/gtest.h"
70 
71 namespace testing {
72 namespace gmock_matchers_test {
73 namespace {
74 
75 using std::greater;
76 using std::less;
77 using std::list;
78 using std::make_pair;
79 using std::map;
80 using std::multimap;
81 using std::multiset;
82 using std::ostream;
83 using std::pair;
84 using std::set;
85 using std::stringstream;
86 using std::vector;
87 using testing::internal::DummyMatchResultListener;
88 using testing::internal::ElementMatcherPair;
89 using testing::internal::ElementMatcherPairs;
90 using testing::internal::ExplainMatchFailureTupleTo;
91 using testing::internal::FloatingEqMatcher;
92 using testing::internal::FormatMatcherDescription;
93 using testing::internal::IsReadableTypeName;
94 using testing::internal::MatchMatrix;
95 using testing::internal::PredicateFormatterFromMatcher;
96 using testing::internal::RE;
97 using testing::internal::StreamMatchResultListener;
98 using testing::internal::Strings;
99 
100 // Helper for testing container-valued matchers in mock method context. It is
101 // important to test matchers in this context, since it requires additional type
102 // deduction beyond what EXPECT_THAT does, thus making it more restrictive.
103 struct ContainerHelper {
104   MOCK_METHOD1(Call, void(std::vector<std::unique_ptr<int>>));
105 };
106 
MakeUniquePtrs(const std::vector<int> & ints)107 std::vector<std::unique_ptr<int>> MakeUniquePtrs(const std::vector<int>& ints) {
108   std::vector<std::unique_ptr<int>> pointers;
109   for (int i : ints) pointers.emplace_back(new int(i));
110   return pointers;
111 }
112 
113 // For testing ExplainMatchResultTo().
114 class GreaterThanMatcher : public MatcherInterface<int> {
115  public:
GreaterThanMatcher(int rhs)116   explicit GreaterThanMatcher(int rhs) : rhs_(rhs) {}
117 
DescribeTo(ostream * os) const118   void DescribeTo(ostream* os) const override { *os << "is > " << rhs_; }
119 
MatchAndExplain(int lhs,MatchResultListener * listener) const120   bool MatchAndExplain(int lhs, MatchResultListener* listener) const override {
121     const int diff = lhs - rhs_;
122     if (diff > 0) {
123       *listener << "which is " << diff << " more than " << rhs_;
124     } else if (diff == 0) {
125       *listener << "which is the same as " << rhs_;
126     } else {
127       *listener << "which is " << -diff << " less than " << rhs_;
128     }
129 
130     return lhs > rhs_;
131   }
132 
133  private:
134   int rhs_;
135 };
136 
GreaterThan(int n)137 Matcher<int> GreaterThan(int n) {
138   return MakeMatcher(new GreaterThanMatcher(n));
139 }
140 
OfType(const std::string & type_name)141 std::string OfType(const std::string& type_name) {
142 #if GTEST_HAS_RTTI
143   return " (of type " + type_name + ")";
144 #else
145   return "";
146 #endif
147 }
148 
149 // Returns the description of the given matcher.
150 template <typename T>
Describe(const Matcher<T> & m)151 std::string Describe(const Matcher<T>& m) {
152   return DescribeMatcher<T>(m);
153 }
154 
155 // Returns the description of the negation of the given matcher.
156 template <typename T>
DescribeNegation(const Matcher<T> & m)157 std::string DescribeNegation(const Matcher<T>& m) {
158   return DescribeMatcher<T>(m, true);
159 }
160 
161 // Returns the reason why x matches, or doesn't match, m.
162 template <typename MatcherType, typename Value>
Explain(const MatcherType & m,const Value & x)163 std::string Explain(const MatcherType& m, const Value& x) {
164   StringMatchResultListener listener;
165   ExplainMatchResult(m, x, &listener);
166   return listener.str();
167 }
168 
TEST(MonotonicMatcherTest,IsPrintable)169 TEST(MonotonicMatcherTest, IsPrintable) {
170   stringstream ss;
171   ss << GreaterThan(5);
172   EXPECT_EQ("is > 5", ss.str());
173 }
174 
TEST(MatchResultListenerTest,StreamingWorks)175 TEST(MatchResultListenerTest, StreamingWorks) {
176   StringMatchResultListener listener;
177   listener << "hi" << 5;
178   EXPECT_EQ("hi5", listener.str());
179 
180   listener.Clear();
181   EXPECT_EQ("", listener.str());
182 
183   listener << 42;
184   EXPECT_EQ("42", listener.str());
185 
186   // Streaming shouldn't crash when the underlying ostream is NULL.
187   DummyMatchResultListener dummy;
188   dummy << "hi" << 5;
189 }
190 
TEST(MatchResultListenerTest,CanAccessUnderlyingStream)191 TEST(MatchResultListenerTest, CanAccessUnderlyingStream) {
192   EXPECT_TRUE(DummyMatchResultListener().stream() == nullptr);
193   EXPECT_TRUE(StreamMatchResultListener(nullptr).stream() == nullptr);
194 
195   EXPECT_EQ(&std::cout, StreamMatchResultListener(&std::cout).stream());
196 }
197 
TEST(MatchResultListenerTest,IsInterestedWorks)198 TEST(MatchResultListenerTest, IsInterestedWorks) {
199   EXPECT_TRUE(StringMatchResultListener().IsInterested());
200   EXPECT_TRUE(StreamMatchResultListener(&std::cout).IsInterested());
201 
202   EXPECT_FALSE(DummyMatchResultListener().IsInterested());
203   EXPECT_FALSE(StreamMatchResultListener(nullptr).IsInterested());
204 }
205 
206 // Makes sure that the MatcherInterface<T> interface doesn't
207 // change.
208 class EvenMatcherImpl : public MatcherInterface<int> {
209  public:
MatchAndExplain(int x,MatchResultListener *) const210   bool MatchAndExplain(int x,
211                        MatchResultListener* /* listener */) const override {
212     return x % 2 == 0;
213   }
214 
DescribeTo(ostream * os) const215   void DescribeTo(ostream* os) const override { *os << "is an even number"; }
216 
217   // We deliberately don't define DescribeNegationTo() and
218   // ExplainMatchResultTo() here, to make sure the definition of these
219   // two methods is optional.
220 };
221 
222 // Makes sure that the MatcherInterface API doesn't change.
TEST(MatcherInterfaceTest,CanBeImplementedUsingPublishedAPI)223 TEST(MatcherInterfaceTest, CanBeImplementedUsingPublishedAPI) {
224   EvenMatcherImpl m;
225 }
226 
227 // Tests implementing a monomorphic matcher using MatchAndExplain().
228 
229 class NewEvenMatcherImpl : public MatcherInterface<int> {
230  public:
MatchAndExplain(int x,MatchResultListener * listener) const231   bool MatchAndExplain(int x, MatchResultListener* listener) const override {
232     const bool match = x % 2 == 0;
233     // Verifies that we can stream to a listener directly.
234     *listener << "value % " << 2;
235     if (listener->stream() != nullptr) {
236       // Verifies that we can stream to a listener's underlying stream
237       // too.
238       *listener->stream() << " == " << (x % 2);
239     }
240     return match;
241   }
242 
DescribeTo(ostream * os) const243   void DescribeTo(ostream* os) const override { *os << "is an even number"; }
244 };
245 
TEST(MatcherInterfaceTest,CanBeImplementedUsingNewAPI)246 TEST(MatcherInterfaceTest, CanBeImplementedUsingNewAPI) {
247   Matcher<int> m = MakeMatcher(new NewEvenMatcherImpl);
248   EXPECT_TRUE(m.Matches(2));
249   EXPECT_FALSE(m.Matches(3));
250   EXPECT_EQ("value % 2 == 0", Explain(m, 2));
251   EXPECT_EQ("value % 2 == 1", Explain(m, 3));
252 }
253 
254 // Tests default-constructing a matcher.
TEST(MatcherTest,CanBeDefaultConstructed)255 TEST(MatcherTest, CanBeDefaultConstructed) {
256   Matcher<double> m;
257 }
258 
259 // Tests that Matcher<T> can be constructed from a MatcherInterface<T>*.
TEST(MatcherTest,CanBeConstructedFromMatcherInterface)260 TEST(MatcherTest, CanBeConstructedFromMatcherInterface) {
261   const MatcherInterface<int>* impl = new EvenMatcherImpl;
262   Matcher<int> m(impl);
263   EXPECT_TRUE(m.Matches(4));
264   EXPECT_FALSE(m.Matches(5));
265 }
266 
267 // Tests that value can be used in place of Eq(value).
TEST(MatcherTest,CanBeImplicitlyConstructedFromValue)268 TEST(MatcherTest, CanBeImplicitlyConstructedFromValue) {
269   Matcher<int> m1 = 5;
270   EXPECT_TRUE(m1.Matches(5));
271   EXPECT_FALSE(m1.Matches(6));
272 }
273 
274 // Tests that NULL can be used in place of Eq(NULL).
TEST(MatcherTest,CanBeImplicitlyConstructedFromNULL)275 TEST(MatcherTest, CanBeImplicitlyConstructedFromNULL) {
276   Matcher<int*> m1 = nullptr;
277   EXPECT_TRUE(m1.Matches(nullptr));
278   int n = 0;
279   EXPECT_FALSE(m1.Matches(&n));
280 }
281 
282 // Tests that matchers can be constructed from a variable that is not properly
283 // defined. This should be illegal, but many users rely on this accidentally.
284 struct Undefined {
285   virtual ~Undefined() = 0;
286   static const int kInt = 1;
287 };
288 
TEST(MatcherTest,CanBeConstructedFromUndefinedVariable)289 TEST(MatcherTest, CanBeConstructedFromUndefinedVariable) {
290   Matcher<int> m1 = Undefined::kInt;
291   EXPECT_TRUE(m1.Matches(1));
292   EXPECT_FALSE(m1.Matches(2));
293 }
294 
295 // Test that a matcher parameterized with an abstract class compiles.
TEST(MatcherTest,CanAcceptAbstractClass)296 TEST(MatcherTest, CanAcceptAbstractClass) { Matcher<const Undefined&> m = _; }
297 
298 // Tests that matchers are copyable.
TEST(MatcherTest,IsCopyable)299 TEST(MatcherTest, IsCopyable) {
300   // Tests the copy constructor.
301   Matcher<bool> m1 = Eq(false);
302   EXPECT_TRUE(m1.Matches(false));
303   EXPECT_FALSE(m1.Matches(true));
304 
305   // Tests the assignment operator.
306   m1 = Eq(true);
307   EXPECT_TRUE(m1.Matches(true));
308   EXPECT_FALSE(m1.Matches(false));
309 }
310 
311 // Tests that Matcher<T>::DescribeTo() calls
312 // MatcherInterface<T>::DescribeTo().
TEST(MatcherTest,CanDescribeItself)313 TEST(MatcherTest, CanDescribeItself) {
314   EXPECT_EQ("is an even number",
315             Describe(Matcher<int>(new EvenMatcherImpl)));
316 }
317 
318 // Tests Matcher<T>::MatchAndExplain().
TEST(MatcherTest,MatchAndExplain)319 TEST(MatcherTest, MatchAndExplain) {
320   Matcher<int> m = GreaterThan(0);
321   StringMatchResultListener listener1;
322   EXPECT_TRUE(m.MatchAndExplain(42, &listener1));
323   EXPECT_EQ("which is 42 more than 0", listener1.str());
324 
325   StringMatchResultListener listener2;
326   EXPECT_FALSE(m.MatchAndExplain(-9, &listener2));
327   EXPECT_EQ("which is 9 less than 0", listener2.str());
328 }
329 
330 // Tests that a C-string literal can be implicitly converted to a
331 // Matcher<std::string> or Matcher<const std::string&>.
TEST(StringMatcherTest,CanBeImplicitlyConstructedFromCStringLiteral)332 TEST(StringMatcherTest, CanBeImplicitlyConstructedFromCStringLiteral) {
333   Matcher<std::string> m1 = "hi";
334   EXPECT_TRUE(m1.Matches("hi"));
335   EXPECT_FALSE(m1.Matches("hello"));
336 
337   Matcher<const std::string&> m2 = "hi";
338   EXPECT_TRUE(m2.Matches("hi"));
339   EXPECT_FALSE(m2.Matches("hello"));
340 }
341 
342 // Tests that a string object can be implicitly converted to a
343 // Matcher<std::string> or Matcher<const std::string&>.
TEST(StringMatcherTest,CanBeImplicitlyConstructedFromString)344 TEST(StringMatcherTest, CanBeImplicitlyConstructedFromString) {
345   Matcher<std::string> m1 = std::string("hi");
346   EXPECT_TRUE(m1.Matches("hi"));
347   EXPECT_FALSE(m1.Matches("hello"));
348 
349   Matcher<const std::string&> m2 = std::string("hi");
350   EXPECT_TRUE(m2.Matches("hi"));
351   EXPECT_FALSE(m2.Matches("hello"));
352 }
353 
354 #if GTEST_HAS_ABSL
355 // Tests that a C-string literal can be implicitly converted to a
356 // Matcher<absl::string_view> or Matcher<const absl::string_view&>.
TEST(StringViewMatcherTest,CanBeImplicitlyConstructedFromCStringLiteral)357 TEST(StringViewMatcherTest, CanBeImplicitlyConstructedFromCStringLiteral) {
358   Matcher<absl::string_view> m1 = "cats";
359   EXPECT_TRUE(m1.Matches("cats"));
360   EXPECT_FALSE(m1.Matches("dogs"));
361 
362   Matcher<const absl::string_view&> m2 = "cats";
363   EXPECT_TRUE(m2.Matches("cats"));
364   EXPECT_FALSE(m2.Matches("dogs"));
365 }
366 
367 // Tests that a std::string object can be implicitly converted to a
368 // Matcher<absl::string_view> or Matcher<const absl::string_view&>.
TEST(StringViewMatcherTest,CanBeImplicitlyConstructedFromString)369 TEST(StringViewMatcherTest, CanBeImplicitlyConstructedFromString) {
370   Matcher<absl::string_view> m1 = std::string("cats");
371   EXPECT_TRUE(m1.Matches("cats"));
372   EXPECT_FALSE(m1.Matches("dogs"));
373 
374   Matcher<const absl::string_view&> m2 = std::string("cats");
375   EXPECT_TRUE(m2.Matches("cats"));
376   EXPECT_FALSE(m2.Matches("dogs"));
377 }
378 
379 // Tests that a absl::string_view object can be implicitly converted to a
380 // Matcher<absl::string_view> or Matcher<const absl::string_view&>.
TEST(StringViewMatcherTest,CanBeImplicitlyConstructedFromStringView)381 TEST(StringViewMatcherTest, CanBeImplicitlyConstructedFromStringView) {
382   Matcher<absl::string_view> m1 = absl::string_view("cats");
383   EXPECT_TRUE(m1.Matches("cats"));
384   EXPECT_FALSE(m1.Matches("dogs"));
385 
386   Matcher<const absl::string_view&> m2 = absl::string_view("cats");
387   EXPECT_TRUE(m2.Matches("cats"));
388   EXPECT_FALSE(m2.Matches("dogs"));
389 }
390 #endif  // GTEST_HAS_ABSL
391 
392 // Tests that a std::reference_wrapper<std::string> object can be implicitly
393 // converted to a Matcher<std::string> or Matcher<const std::string&> via Eq().
TEST(StringMatcherTest,CanBeImplicitlyConstructedFromEqReferenceWrapperString)394 TEST(StringMatcherTest,
395      CanBeImplicitlyConstructedFromEqReferenceWrapperString) {
396   std::string value = "cats";
397   Matcher<std::string> m1 = Eq(std::ref(value));
398   EXPECT_TRUE(m1.Matches("cats"));
399   EXPECT_FALSE(m1.Matches("dogs"));
400 
401   Matcher<const std::string&> m2 = Eq(std::ref(value));
402   EXPECT_TRUE(m2.Matches("cats"));
403   EXPECT_FALSE(m2.Matches("dogs"));
404 }
405 
406 // Tests that MakeMatcher() constructs a Matcher<T> from a
407 // MatcherInterface* without requiring the user to explicitly
408 // write the type.
TEST(MakeMatcherTest,ConstructsMatcherFromMatcherInterface)409 TEST(MakeMatcherTest, ConstructsMatcherFromMatcherInterface) {
410   const MatcherInterface<int>* dummy_impl = nullptr;
411   Matcher<int> m = MakeMatcher(dummy_impl);
412 }
413 
414 // Tests that MakePolymorphicMatcher() can construct a polymorphic
415 // matcher from its implementation using the old API.
416 const int g_bar = 1;
417 class ReferencesBarOrIsZeroImpl {
418  public:
419   template <typename T>
MatchAndExplain(const T & x,MatchResultListener *) const420   bool MatchAndExplain(const T& x,
421                        MatchResultListener* /* listener */) const {
422     const void* p = &x;
423     return p == &g_bar || x == 0;
424   }
425 
DescribeTo(ostream * os) const426   void DescribeTo(ostream* os) const { *os << "g_bar or zero"; }
427 
DescribeNegationTo(ostream * os) const428   void DescribeNegationTo(ostream* os) const {
429     *os << "doesn't reference g_bar and is not zero";
430   }
431 };
432 
433 // This function verifies that MakePolymorphicMatcher() returns a
434 // PolymorphicMatcher<T> where T is the argument's type.
ReferencesBarOrIsZero()435 PolymorphicMatcher<ReferencesBarOrIsZeroImpl> ReferencesBarOrIsZero() {
436   return MakePolymorphicMatcher(ReferencesBarOrIsZeroImpl());
437 }
438 
TEST(MakePolymorphicMatcherTest,ConstructsMatcherUsingOldAPI)439 TEST(MakePolymorphicMatcherTest, ConstructsMatcherUsingOldAPI) {
440   // Using a polymorphic matcher to match a reference type.
441   Matcher<const int&> m1 = ReferencesBarOrIsZero();
442   EXPECT_TRUE(m1.Matches(0));
443   // Verifies that the identity of a by-reference argument is preserved.
444   EXPECT_TRUE(m1.Matches(g_bar));
445   EXPECT_FALSE(m1.Matches(1));
446   EXPECT_EQ("g_bar or zero", Describe(m1));
447 
448   // Using a polymorphic matcher to match a value type.
449   Matcher<double> m2 = ReferencesBarOrIsZero();
450   EXPECT_TRUE(m2.Matches(0.0));
451   EXPECT_FALSE(m2.Matches(0.1));
452   EXPECT_EQ("g_bar or zero", Describe(m2));
453 }
454 
455 // Tests implementing a polymorphic matcher using MatchAndExplain().
456 
457 class PolymorphicIsEvenImpl {
458  public:
DescribeTo(ostream * os) const459   void DescribeTo(ostream* os) const { *os << "is even"; }
460 
DescribeNegationTo(ostream * os) const461   void DescribeNegationTo(ostream* os) const {
462     *os << "is odd";
463   }
464 
465   template <typename T>
MatchAndExplain(const T & x,MatchResultListener * listener) const466   bool MatchAndExplain(const T& x, MatchResultListener* listener) const {
467     // Verifies that we can stream to the listener directly.
468     *listener << "% " << 2;
469     if (listener->stream() != nullptr) {
470       // Verifies that we can stream to the listener's underlying stream
471       // too.
472       *listener->stream() << " == " << (x % 2);
473     }
474     return (x % 2) == 0;
475   }
476 };
477 
PolymorphicIsEven()478 PolymorphicMatcher<PolymorphicIsEvenImpl> PolymorphicIsEven() {
479   return MakePolymorphicMatcher(PolymorphicIsEvenImpl());
480 }
481 
TEST(MakePolymorphicMatcherTest,ConstructsMatcherUsingNewAPI)482 TEST(MakePolymorphicMatcherTest, ConstructsMatcherUsingNewAPI) {
483   // Using PolymorphicIsEven() as a Matcher<int>.
484   const Matcher<int> m1 = PolymorphicIsEven();
485   EXPECT_TRUE(m1.Matches(42));
486   EXPECT_FALSE(m1.Matches(43));
487   EXPECT_EQ("is even", Describe(m1));
488 
489   const Matcher<int> not_m1 = Not(m1);
490   EXPECT_EQ("is odd", Describe(not_m1));
491 
492   EXPECT_EQ("% 2 == 0", Explain(m1, 42));
493 
494   // Using PolymorphicIsEven() as a Matcher<char>.
495   const Matcher<char> m2 = PolymorphicIsEven();
496   EXPECT_TRUE(m2.Matches('\x42'));
497   EXPECT_FALSE(m2.Matches('\x43'));
498   EXPECT_EQ("is even", Describe(m2));
499 
500   const Matcher<char> not_m2 = Not(m2);
501   EXPECT_EQ("is odd", Describe(not_m2));
502 
503   EXPECT_EQ("% 2 == 0", Explain(m2, '\x42'));
504 }
505 
506 // Tests that MatcherCast<T>(m) works when m is a polymorphic matcher.
TEST(MatcherCastTest,FromPolymorphicMatcher)507 TEST(MatcherCastTest, FromPolymorphicMatcher) {
508   Matcher<int> m = MatcherCast<int>(Eq(5));
509   EXPECT_TRUE(m.Matches(5));
510   EXPECT_FALSE(m.Matches(6));
511 }
512 
513 // For testing casting matchers between compatible types.
514 class IntValue {
515  public:
516   // An int can be statically (although not implicitly) cast to a
517   // IntValue.
IntValue(int a_value)518   explicit IntValue(int a_value) : value_(a_value) {}
519 
value() const520   int value() const { return value_; }
521  private:
522   int value_;
523 };
524 
525 // For testing casting matchers between compatible types.
IsPositiveIntValue(const IntValue & foo)526 bool IsPositiveIntValue(const IntValue& foo) {
527   return foo.value() > 0;
528 }
529 
530 // Tests that MatcherCast<T>(m) works when m is a Matcher<U> where T
531 // can be statically converted to U.
TEST(MatcherCastTest,FromCompatibleType)532 TEST(MatcherCastTest, FromCompatibleType) {
533   Matcher<double> m1 = Eq(2.0);
534   Matcher<int> m2 = MatcherCast<int>(m1);
535   EXPECT_TRUE(m2.Matches(2));
536   EXPECT_FALSE(m2.Matches(3));
537 
538   Matcher<IntValue> m3 = Truly(IsPositiveIntValue);
539   Matcher<int> m4 = MatcherCast<int>(m3);
540   // In the following, the arguments 1 and 0 are statically converted
541   // to IntValue objects, and then tested by the IsPositiveIntValue()
542   // predicate.
543   EXPECT_TRUE(m4.Matches(1));
544   EXPECT_FALSE(m4.Matches(0));
545 }
546 
547 // Tests that MatcherCast<T>(m) works when m is a Matcher<const T&>.
TEST(MatcherCastTest,FromConstReferenceToNonReference)548 TEST(MatcherCastTest, FromConstReferenceToNonReference) {
549   Matcher<const int&> m1 = Eq(0);
550   Matcher<int> m2 = MatcherCast<int>(m1);
551   EXPECT_TRUE(m2.Matches(0));
552   EXPECT_FALSE(m2.Matches(1));
553 }
554 
555 // Tests that MatcherCast<T>(m) works when m is a Matcher<T&>.
TEST(MatcherCastTest,FromReferenceToNonReference)556 TEST(MatcherCastTest, FromReferenceToNonReference) {
557   Matcher<int&> m1 = Eq(0);
558   Matcher<int> m2 = MatcherCast<int>(m1);
559   EXPECT_TRUE(m2.Matches(0));
560   EXPECT_FALSE(m2.Matches(1));
561 }
562 
563 // Tests that MatcherCast<const T&>(m) works when m is a Matcher<T>.
TEST(MatcherCastTest,FromNonReferenceToConstReference)564 TEST(MatcherCastTest, FromNonReferenceToConstReference) {
565   Matcher<int> m1 = Eq(0);
566   Matcher<const int&> m2 = MatcherCast<const int&>(m1);
567   EXPECT_TRUE(m2.Matches(0));
568   EXPECT_FALSE(m2.Matches(1));
569 }
570 
571 // Tests that MatcherCast<T&>(m) works when m is a Matcher<T>.
TEST(MatcherCastTest,FromNonReferenceToReference)572 TEST(MatcherCastTest, FromNonReferenceToReference) {
573   Matcher<int> m1 = Eq(0);
574   Matcher<int&> m2 = MatcherCast<int&>(m1);
575   int n = 0;
576   EXPECT_TRUE(m2.Matches(n));
577   n = 1;
578   EXPECT_FALSE(m2.Matches(n));
579 }
580 
581 // Tests that MatcherCast<T>(m) works when m is a Matcher<T>.
TEST(MatcherCastTest,FromSameType)582 TEST(MatcherCastTest, FromSameType) {
583   Matcher<int> m1 = Eq(0);
584   Matcher<int> m2 = MatcherCast<int>(m1);
585   EXPECT_TRUE(m2.Matches(0));
586   EXPECT_FALSE(m2.Matches(1));
587 }
588 
589 // Tests that MatcherCast<T>(m) works when m is a value of the same type as the
590 // value type of the Matcher.
TEST(MatcherCastTest,FromAValue)591 TEST(MatcherCastTest, FromAValue) {
592   Matcher<int> m = MatcherCast<int>(42);
593   EXPECT_TRUE(m.Matches(42));
594   EXPECT_FALSE(m.Matches(239));
595 }
596 
597 // Tests that MatcherCast<T>(m) works when m is a value of the type implicitly
598 // convertible to the value type of the Matcher.
TEST(MatcherCastTest,FromAnImplicitlyConvertibleValue)599 TEST(MatcherCastTest, FromAnImplicitlyConvertibleValue) {
600   const int kExpected = 'c';
601   Matcher<int> m = MatcherCast<int>('c');
602   EXPECT_TRUE(m.Matches(kExpected));
603   EXPECT_FALSE(m.Matches(kExpected + 1));
604 }
605 
606 struct NonImplicitlyConstructibleTypeWithOperatorEq {
operator ==(const NonImplicitlyConstructibleTypeWithOperatorEq &,int rhs)607   friend bool operator==(
608       const NonImplicitlyConstructibleTypeWithOperatorEq& /* ignored */,
609       int rhs) {
610     return 42 == rhs;
611   }
operator ==(int lhs,const NonImplicitlyConstructibleTypeWithOperatorEq &)612   friend bool operator==(
613       int lhs,
614       const NonImplicitlyConstructibleTypeWithOperatorEq& /* ignored */) {
615     return lhs == 42;
616   }
617 };
618 
619 // Tests that MatcherCast<T>(m) works when m is a neither a matcher nor
620 // implicitly convertible to the value type of the Matcher, but the value type
621 // of the matcher has operator==() overload accepting m.
TEST(MatcherCastTest,NonImplicitlyConstructibleTypeWithOperatorEq)622 TEST(MatcherCastTest, NonImplicitlyConstructibleTypeWithOperatorEq) {
623   Matcher<NonImplicitlyConstructibleTypeWithOperatorEq> m1 =
624       MatcherCast<NonImplicitlyConstructibleTypeWithOperatorEq>(42);
625   EXPECT_TRUE(m1.Matches(NonImplicitlyConstructibleTypeWithOperatorEq()));
626 
627   Matcher<NonImplicitlyConstructibleTypeWithOperatorEq> m2 =
628       MatcherCast<NonImplicitlyConstructibleTypeWithOperatorEq>(239);
629   EXPECT_FALSE(m2.Matches(NonImplicitlyConstructibleTypeWithOperatorEq()));
630 
631   // When updating the following lines please also change the comment to
632   // namespace convertible_from_any.
633   Matcher<int> m3 =
634       MatcherCast<int>(NonImplicitlyConstructibleTypeWithOperatorEq());
635   EXPECT_TRUE(m3.Matches(42));
636   EXPECT_FALSE(m3.Matches(239));
637 }
638 
639 // ConvertibleFromAny does not work with MSVC. resulting in
640 // error C2440: 'initializing': cannot convert from 'Eq' to 'M'
641 // No constructor could take the source type, or constructor overload
642 // resolution was ambiguous
643 
644 #if !defined _MSC_VER
645 
646 // The below ConvertibleFromAny struct is implicitly constructible from anything
647 // and when in the same namespace can interact with other tests. In particular,
648 // if it is in the same namespace as other tests and one removes
649 //   NonImplicitlyConstructibleTypeWithOperatorEq::operator==(int lhs, ...);
650 // then the corresponding test still compiles (and it should not!) by implicitly
651 // converting NonImplicitlyConstructibleTypeWithOperatorEq to ConvertibleFromAny
652 // in m3.Matcher().
653 namespace convertible_from_any {
654 // Implicitly convertible from any type.
655 struct ConvertibleFromAny {
ConvertibleFromAnytesting::gmock_matchers_test::__anon86e4b7b50111::convertible_from_any::ConvertibleFromAny656   ConvertibleFromAny(int a_value) : value(a_value) {}
657   template <typename T>
ConvertibleFromAnytesting::gmock_matchers_test::__anon86e4b7b50111::convertible_from_any::ConvertibleFromAny658   ConvertibleFromAny(const T& /*a_value*/) : value(-1) {
659     ADD_FAILURE() << "Conversion constructor called";
660   }
661   int value;
662 };
663 
operator ==(const ConvertibleFromAny & a,const ConvertibleFromAny & b)664 bool operator==(const ConvertibleFromAny& a, const ConvertibleFromAny& b) {
665   return a.value == b.value;
666 }
667 
operator <<(ostream & os,const ConvertibleFromAny & a)668 ostream& operator<<(ostream& os, const ConvertibleFromAny& a) {
669   return os << a.value;
670 }
671 
TEST(MatcherCastTest,ConversionConstructorIsUsed)672 TEST(MatcherCastTest, ConversionConstructorIsUsed) {
673   Matcher<ConvertibleFromAny> m = MatcherCast<ConvertibleFromAny>(1);
674   EXPECT_TRUE(m.Matches(ConvertibleFromAny(1)));
675   EXPECT_FALSE(m.Matches(ConvertibleFromAny(2)));
676 }
677 
TEST(MatcherCastTest,FromConvertibleFromAny)678 TEST(MatcherCastTest, FromConvertibleFromAny) {
679   Matcher<ConvertibleFromAny> m =
680       MatcherCast<ConvertibleFromAny>(Eq(ConvertibleFromAny(1)));
681   EXPECT_TRUE(m.Matches(ConvertibleFromAny(1)));
682   EXPECT_FALSE(m.Matches(ConvertibleFromAny(2)));
683 }
684 }  // namespace convertible_from_any
685 
686 #endif  // !defined _MSC_VER
687 
688 struct IntReferenceWrapper {
IntReferenceWrappertesting::gmock_matchers_test::__anon86e4b7b50111::IntReferenceWrapper689   IntReferenceWrapper(const int& a_value) : value(&a_value) {}
690   const int* value;
691 };
692 
operator ==(const IntReferenceWrapper & a,const IntReferenceWrapper & b)693 bool operator==(const IntReferenceWrapper& a, const IntReferenceWrapper& b) {
694   return a.value == b.value;
695 }
696 
TEST(MatcherCastTest,ValueIsNotCopied)697 TEST(MatcherCastTest, ValueIsNotCopied) {
698   int n = 42;
699   Matcher<IntReferenceWrapper> m = MatcherCast<IntReferenceWrapper>(n);
700   // Verify that the matcher holds a reference to n, not to its temporary copy.
701   EXPECT_TRUE(m.Matches(n));
702 }
703 
704 class Base {
705  public:
~Base()706   virtual ~Base() {}
Base()707   Base() {}
708  private:
709   GTEST_DISALLOW_COPY_AND_ASSIGN_(Base);
710 };
711 
712 class Derived : public Base {
713  public:
Derived()714   Derived() : Base() {}
715   int i;
716 };
717 
718 class OtherDerived : public Base {};
719 
720 // Tests that SafeMatcherCast<T>(m) works when m is a polymorphic matcher.
TEST(SafeMatcherCastTest,FromPolymorphicMatcher)721 TEST(SafeMatcherCastTest, FromPolymorphicMatcher) {
722   Matcher<char> m2 = SafeMatcherCast<char>(Eq(32));
723   EXPECT_TRUE(m2.Matches(' '));
724   EXPECT_FALSE(m2.Matches('\n'));
725 }
726 
727 // Tests that SafeMatcherCast<T>(m) works when m is a Matcher<U> where
728 // T and U are arithmetic types and T can be losslessly converted to
729 // U.
TEST(SafeMatcherCastTest,FromLosslesslyConvertibleArithmeticType)730 TEST(SafeMatcherCastTest, FromLosslesslyConvertibleArithmeticType) {
731   Matcher<double> m1 = DoubleEq(1.0);
732   Matcher<float> m2 = SafeMatcherCast<float>(m1);
733   EXPECT_TRUE(m2.Matches(1.0f));
734   EXPECT_FALSE(m2.Matches(2.0f));
735 
736   Matcher<char> m3 = SafeMatcherCast<char>(TypedEq<int>('a'));
737   EXPECT_TRUE(m3.Matches('a'));
738   EXPECT_FALSE(m3.Matches('b'));
739 }
740 
741 // Tests that SafeMatcherCast<T>(m) works when m is a Matcher<U> where T and U
742 // are pointers or references to a derived and a base class, correspondingly.
TEST(SafeMatcherCastTest,FromBaseClass)743 TEST(SafeMatcherCastTest, FromBaseClass) {
744   Derived d, d2;
745   Matcher<Base*> m1 = Eq(&d);
746   Matcher<Derived*> m2 = SafeMatcherCast<Derived*>(m1);
747   EXPECT_TRUE(m2.Matches(&d));
748   EXPECT_FALSE(m2.Matches(&d2));
749 
750   Matcher<Base&> m3 = Ref(d);
751   Matcher<Derived&> m4 = SafeMatcherCast<Derived&>(m3);
752   EXPECT_TRUE(m4.Matches(d));
753   EXPECT_FALSE(m4.Matches(d2));
754 }
755 
756 // Tests that SafeMatcherCast<T&>(m) works when m is a Matcher<const T&>.
TEST(SafeMatcherCastTest,FromConstReferenceToReference)757 TEST(SafeMatcherCastTest, FromConstReferenceToReference) {
758   int n = 0;
759   Matcher<const int&> m1 = Ref(n);
760   Matcher<int&> m2 = SafeMatcherCast<int&>(m1);
761   int n1 = 0;
762   EXPECT_TRUE(m2.Matches(n));
763   EXPECT_FALSE(m2.Matches(n1));
764 }
765 
766 // Tests that MatcherCast<const T&>(m) works when m is a Matcher<T>.
TEST(SafeMatcherCastTest,FromNonReferenceToConstReference)767 TEST(SafeMatcherCastTest, FromNonReferenceToConstReference) {
768   Matcher<int> m1 = Eq(0);
769   Matcher<const int&> m2 = SafeMatcherCast<const int&>(m1);
770   EXPECT_TRUE(m2.Matches(0));
771   EXPECT_FALSE(m2.Matches(1));
772 }
773 
774 // Tests that SafeMatcherCast<T&>(m) works when m is a Matcher<T>.
TEST(SafeMatcherCastTest,FromNonReferenceToReference)775 TEST(SafeMatcherCastTest, FromNonReferenceToReference) {
776   Matcher<int> m1 = Eq(0);
777   Matcher<int&> m2 = SafeMatcherCast<int&>(m1);
778   int n = 0;
779   EXPECT_TRUE(m2.Matches(n));
780   n = 1;
781   EXPECT_FALSE(m2.Matches(n));
782 }
783 
784 // Tests that SafeMatcherCast<T>(m) works when m is a Matcher<T>.
TEST(SafeMatcherCastTest,FromSameType)785 TEST(SafeMatcherCastTest, FromSameType) {
786   Matcher<int> m1 = Eq(0);
787   Matcher<int> m2 = SafeMatcherCast<int>(m1);
788   EXPECT_TRUE(m2.Matches(0));
789   EXPECT_FALSE(m2.Matches(1));
790 }
791 
792 #if !defined _MSC_VER
793 
794 namespace convertible_from_any {
TEST(SafeMatcherCastTest,ConversionConstructorIsUsed)795 TEST(SafeMatcherCastTest, ConversionConstructorIsUsed) {
796   Matcher<ConvertibleFromAny> m = SafeMatcherCast<ConvertibleFromAny>(1);
797   EXPECT_TRUE(m.Matches(ConvertibleFromAny(1)));
798   EXPECT_FALSE(m.Matches(ConvertibleFromAny(2)));
799 }
800 
TEST(SafeMatcherCastTest,FromConvertibleFromAny)801 TEST(SafeMatcherCastTest, FromConvertibleFromAny) {
802   Matcher<ConvertibleFromAny> m =
803       SafeMatcherCast<ConvertibleFromAny>(Eq(ConvertibleFromAny(1)));
804   EXPECT_TRUE(m.Matches(ConvertibleFromAny(1)));
805   EXPECT_FALSE(m.Matches(ConvertibleFromAny(2)));
806 }
807 }  // namespace convertible_from_any
808 
809 #endif  // !defined _MSC_VER
810 
TEST(SafeMatcherCastTest,ValueIsNotCopied)811 TEST(SafeMatcherCastTest, ValueIsNotCopied) {
812   int n = 42;
813   Matcher<IntReferenceWrapper> m = SafeMatcherCast<IntReferenceWrapper>(n);
814   // Verify that the matcher holds a reference to n, not to its temporary copy.
815   EXPECT_TRUE(m.Matches(n));
816 }
817 
TEST(ExpectThat,TakesLiterals)818 TEST(ExpectThat, TakesLiterals) {
819   EXPECT_THAT(1, 1);
820   EXPECT_THAT(1.0, 1.0);
821   EXPECT_THAT(std::string(), "");
822 }
823 
TEST(ExpectThat,TakesFunctions)824 TEST(ExpectThat, TakesFunctions) {
825   struct Helper {
826     static void Func() {}
827   };
828   void (*func)() = Helper::Func;
829   EXPECT_THAT(func, Helper::Func);
830   EXPECT_THAT(func, &Helper::Func);
831 }
832 
833 // Tests that A<T>() matches any value of type T.
TEST(ATest,MatchesAnyValue)834 TEST(ATest, MatchesAnyValue) {
835   // Tests a matcher for a value type.
836   Matcher<double> m1 = A<double>();
837   EXPECT_TRUE(m1.Matches(91.43));
838   EXPECT_TRUE(m1.Matches(-15.32));
839 
840   // Tests a matcher for a reference type.
841   int a = 2;
842   int b = -6;
843   Matcher<int&> m2 = A<int&>();
844   EXPECT_TRUE(m2.Matches(a));
845   EXPECT_TRUE(m2.Matches(b));
846 }
847 
TEST(ATest,WorksForDerivedClass)848 TEST(ATest, WorksForDerivedClass) {
849   Base base;
850   Derived derived;
851   EXPECT_THAT(&base, A<Base*>());
852   // This shouldn't compile: EXPECT_THAT(&base, A<Derived*>());
853   EXPECT_THAT(&derived, A<Base*>());
854   EXPECT_THAT(&derived, A<Derived*>());
855 }
856 
857 // Tests that A<T>() describes itself properly.
TEST(ATest,CanDescribeSelf)858 TEST(ATest, CanDescribeSelf) {
859   EXPECT_EQ("is anything", Describe(A<bool>()));
860 }
861 
862 // Tests that An<T>() matches any value of type T.
TEST(AnTest,MatchesAnyValue)863 TEST(AnTest, MatchesAnyValue) {
864   // Tests a matcher for a value type.
865   Matcher<int> m1 = An<int>();
866   EXPECT_TRUE(m1.Matches(9143));
867   EXPECT_TRUE(m1.Matches(-1532));
868 
869   // Tests a matcher for a reference type.
870   int a = 2;
871   int b = -6;
872   Matcher<int&> m2 = An<int&>();
873   EXPECT_TRUE(m2.Matches(a));
874   EXPECT_TRUE(m2.Matches(b));
875 }
876 
877 // Tests that An<T>() describes itself properly.
TEST(AnTest,CanDescribeSelf)878 TEST(AnTest, CanDescribeSelf) {
879   EXPECT_EQ("is anything", Describe(An<int>()));
880 }
881 
882 // Tests that _ can be used as a matcher for any type and matches any
883 // value of that type.
TEST(UnderscoreTest,MatchesAnyValue)884 TEST(UnderscoreTest, MatchesAnyValue) {
885   // Uses _ as a matcher for a value type.
886   Matcher<int> m1 = _;
887   EXPECT_TRUE(m1.Matches(123));
888   EXPECT_TRUE(m1.Matches(-242));
889 
890   // Uses _ as a matcher for a reference type.
891   bool a = false;
892   const bool b = true;
893   Matcher<const bool&> m2 = _;
894   EXPECT_TRUE(m2.Matches(a));
895   EXPECT_TRUE(m2.Matches(b));
896 }
897 
898 // Tests that _ describes itself properly.
TEST(UnderscoreTest,CanDescribeSelf)899 TEST(UnderscoreTest, CanDescribeSelf) {
900   Matcher<int> m = _;
901   EXPECT_EQ("is anything", Describe(m));
902 }
903 
904 // Tests that Eq(x) matches any value equal to x.
TEST(EqTest,MatchesEqualValue)905 TEST(EqTest, MatchesEqualValue) {
906   // 2 C-strings with same content but different addresses.
907   const char a1[] = "hi";
908   const char a2[] = "hi";
909 
910   Matcher<const char*> m1 = Eq(a1);
911   EXPECT_TRUE(m1.Matches(a1));
912   EXPECT_FALSE(m1.Matches(a2));
913 }
914 
915 // Tests that Eq(v) describes itself properly.
916 
917 class Unprintable {
918  public:
Unprintable()919   Unprintable() : c_('a') {}
920 
operator ==(const Unprintable &) const921   bool operator==(const Unprintable& /* rhs */) const { return true; }
922   // -Wunused-private-field: dummy accessor for `c_`.
dummy_c()923   char dummy_c() { return c_; }
924  private:
925   char c_;
926 };
927 
TEST(EqTest,CanDescribeSelf)928 TEST(EqTest, CanDescribeSelf) {
929   Matcher<Unprintable> m = Eq(Unprintable());
930   EXPECT_EQ("is equal to 1-byte object <61>", Describe(m));
931 }
932 
933 // Tests that Eq(v) can be used to match any type that supports
934 // comparing with type T, where T is v's type.
TEST(EqTest,IsPolymorphic)935 TEST(EqTest, IsPolymorphic) {
936   Matcher<int> m1 = Eq(1);
937   EXPECT_TRUE(m1.Matches(1));
938   EXPECT_FALSE(m1.Matches(2));
939 
940   Matcher<char> m2 = Eq(1);
941   EXPECT_TRUE(m2.Matches('\1'));
942   EXPECT_FALSE(m2.Matches('a'));
943 }
944 
945 // Tests that TypedEq<T>(v) matches values of type T that's equal to v.
TEST(TypedEqTest,ChecksEqualityForGivenType)946 TEST(TypedEqTest, ChecksEqualityForGivenType) {
947   Matcher<char> m1 = TypedEq<char>('a');
948   EXPECT_TRUE(m1.Matches('a'));
949   EXPECT_FALSE(m1.Matches('b'));
950 
951   Matcher<int> m2 = TypedEq<int>(6);
952   EXPECT_TRUE(m2.Matches(6));
953   EXPECT_FALSE(m2.Matches(7));
954 }
955 
956 // Tests that TypedEq(v) describes itself properly.
TEST(TypedEqTest,CanDescribeSelf)957 TEST(TypedEqTest, CanDescribeSelf) {
958   EXPECT_EQ("is equal to 2", Describe(TypedEq<int>(2)));
959 }
960 
961 // Tests that TypedEq<T>(v) has type Matcher<T>.
962 
963 // Type<T>::IsTypeOf(v) compiles if and only if the type of value v is T, where
964 // T is a "bare" type (i.e. not in the form of const U or U&).  If v's type is
965 // not T, the compiler will generate a message about "undefined reference".
966 template <typename T>
967 struct Type {
IsTypeOftesting::gmock_matchers_test::__anon86e4b7b50111::Type968   static bool IsTypeOf(const T& /* v */) { return true; }
969 
970   template <typename T2>
971   static void IsTypeOf(T2 v);
972 };
973 
TEST(TypedEqTest,HasSpecifiedType)974 TEST(TypedEqTest, HasSpecifiedType) {
975   // Verfies that the type of TypedEq<T>(v) is Matcher<T>.
976   Type<Matcher<int> >::IsTypeOf(TypedEq<int>(5));
977   Type<Matcher<double> >::IsTypeOf(TypedEq<double>(5));
978 }
979 
980 // Tests that Ge(v) matches anything >= v.
TEST(GeTest,ImplementsGreaterThanOrEqual)981 TEST(GeTest, ImplementsGreaterThanOrEqual) {
982   Matcher<int> m1 = Ge(0);
983   EXPECT_TRUE(m1.Matches(1));
984   EXPECT_TRUE(m1.Matches(0));
985   EXPECT_FALSE(m1.Matches(-1));
986 }
987 
988 // Tests that Ge(v) describes itself properly.
TEST(GeTest,CanDescribeSelf)989 TEST(GeTest, CanDescribeSelf) {
990   Matcher<int> m = Ge(5);
991   EXPECT_EQ("is >= 5", Describe(m));
992 }
993 
994 // Tests that Gt(v) matches anything > v.
TEST(GtTest,ImplementsGreaterThan)995 TEST(GtTest, ImplementsGreaterThan) {
996   Matcher<double> m1 = Gt(0);
997   EXPECT_TRUE(m1.Matches(1.0));
998   EXPECT_FALSE(m1.Matches(0.0));
999   EXPECT_FALSE(m1.Matches(-1.0));
1000 }
1001 
1002 // Tests that Gt(v) describes itself properly.
TEST(GtTest,CanDescribeSelf)1003 TEST(GtTest, CanDescribeSelf) {
1004   Matcher<int> m = Gt(5);
1005   EXPECT_EQ("is > 5", Describe(m));
1006 }
1007 
1008 // Tests that Le(v) matches anything <= v.
TEST(LeTest,ImplementsLessThanOrEqual)1009 TEST(LeTest, ImplementsLessThanOrEqual) {
1010   Matcher<char> m1 = Le('b');
1011   EXPECT_TRUE(m1.Matches('a'));
1012   EXPECT_TRUE(m1.Matches('b'));
1013   EXPECT_FALSE(m1.Matches('c'));
1014 }
1015 
1016 // Tests that Le(v) describes itself properly.
TEST(LeTest,CanDescribeSelf)1017 TEST(LeTest, CanDescribeSelf) {
1018   Matcher<int> m = Le(5);
1019   EXPECT_EQ("is <= 5", Describe(m));
1020 }
1021 
1022 // Tests that Lt(v) matches anything < v.
TEST(LtTest,ImplementsLessThan)1023 TEST(LtTest, ImplementsLessThan) {
1024   Matcher<const std::string&> m1 = Lt("Hello");
1025   EXPECT_TRUE(m1.Matches("Abc"));
1026   EXPECT_FALSE(m1.Matches("Hello"));
1027   EXPECT_FALSE(m1.Matches("Hello, world!"));
1028 }
1029 
1030 // Tests that Lt(v) describes itself properly.
TEST(LtTest,CanDescribeSelf)1031 TEST(LtTest, CanDescribeSelf) {
1032   Matcher<int> m = Lt(5);
1033   EXPECT_EQ("is < 5", Describe(m));
1034 }
1035 
1036 // Tests that Ne(v) matches anything != v.
TEST(NeTest,ImplementsNotEqual)1037 TEST(NeTest, ImplementsNotEqual) {
1038   Matcher<int> m1 = Ne(0);
1039   EXPECT_TRUE(m1.Matches(1));
1040   EXPECT_TRUE(m1.Matches(-1));
1041   EXPECT_FALSE(m1.Matches(0));
1042 }
1043 
1044 // Tests that Ne(v) describes itself properly.
TEST(NeTest,CanDescribeSelf)1045 TEST(NeTest, CanDescribeSelf) {
1046   Matcher<int> m = Ne(5);
1047   EXPECT_EQ("isn't equal to 5", Describe(m));
1048 }
1049 
1050 class MoveOnly {
1051  public:
MoveOnly(int i)1052   explicit MoveOnly(int i) : i_(i) {}
1053   MoveOnly(const MoveOnly&) = delete;
1054   MoveOnly(MoveOnly&&) = default;
1055   MoveOnly& operator=(const MoveOnly&) = delete;
1056   MoveOnly& operator=(MoveOnly&&) = default;
1057 
operator ==(const MoveOnly & other) const1058   bool operator==(const MoveOnly& other) const { return i_ == other.i_; }
operator !=(const MoveOnly & other) const1059   bool operator!=(const MoveOnly& other) const { return i_ != other.i_; }
operator <(const MoveOnly & other) const1060   bool operator<(const MoveOnly& other) const { return i_ < other.i_; }
operator <=(const MoveOnly & other) const1061   bool operator<=(const MoveOnly& other) const { return i_ <= other.i_; }
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_; }
1064 
1065  private:
1066   int i_;
1067 };
1068 
1069 struct MoveHelper {
1070   MOCK_METHOD1(Call, void(MoveOnly));
1071 };
1072 
TEST(ComparisonBaseTest,WorksWithMoveOnly)1073 TEST(ComparisonBaseTest, WorksWithMoveOnly) {
1074   MoveOnly m{0};
1075   MoveHelper helper;
1076 
1077   EXPECT_CALL(helper, Call(Eq(ByRef(m))));
1078   helper.Call(MoveOnly(0));
1079   EXPECT_CALL(helper, Call(Ne(ByRef(m))));
1080   helper.Call(MoveOnly(1));
1081   EXPECT_CALL(helper, Call(Le(ByRef(m))));
1082   helper.Call(MoveOnly(0));
1083   EXPECT_CALL(helper, Call(Lt(ByRef(m))));
1084   helper.Call(MoveOnly(-1));
1085   EXPECT_CALL(helper, Call(Ge(ByRef(m))));
1086   helper.Call(MoveOnly(0));
1087   EXPECT_CALL(helper, Call(Gt(ByRef(m))));
1088   helper.Call(MoveOnly(1));
1089 }
1090 
1091 // Tests that IsNull() matches any NULL pointer of any type.
TEST(IsNullTest,MatchesNullPointer)1092 TEST(IsNullTest, MatchesNullPointer) {
1093   Matcher<int*> m1 = IsNull();
1094   int* p1 = nullptr;
1095   int n = 0;
1096   EXPECT_TRUE(m1.Matches(p1));
1097   EXPECT_FALSE(m1.Matches(&n));
1098 
1099   Matcher<const char*> m2 = IsNull();
1100   const char* p2 = nullptr;
1101   EXPECT_TRUE(m2.Matches(p2));
1102   EXPECT_FALSE(m2.Matches("hi"));
1103 
1104   Matcher<void*> m3 = IsNull();
1105   void* p3 = nullptr;
1106   EXPECT_TRUE(m3.Matches(p3));
1107   EXPECT_FALSE(m3.Matches(reinterpret_cast<void*>(0xbeef)));
1108 }
1109 
TEST(IsNullTest,StdFunction)1110 TEST(IsNullTest, StdFunction) {
1111   const Matcher<std::function<void()>> m = IsNull();
1112 
1113   EXPECT_TRUE(m.Matches(std::function<void()>()));
1114   EXPECT_FALSE(m.Matches([]{}));
1115 }
1116 
1117 // Tests that IsNull() describes itself properly.
TEST(IsNullTest,CanDescribeSelf)1118 TEST(IsNullTest, CanDescribeSelf) {
1119   Matcher<int*> m = IsNull();
1120   EXPECT_EQ("is NULL", Describe(m));
1121   EXPECT_EQ("isn't NULL", DescribeNegation(m));
1122 }
1123 
1124 // Tests that NotNull() matches any non-NULL pointer of any type.
TEST(NotNullTest,MatchesNonNullPointer)1125 TEST(NotNullTest, MatchesNonNullPointer) {
1126   Matcher<int*> m1 = NotNull();
1127   int* p1 = nullptr;
1128   int n = 0;
1129   EXPECT_FALSE(m1.Matches(p1));
1130   EXPECT_TRUE(m1.Matches(&n));
1131 
1132   Matcher<const char*> m2 = NotNull();
1133   const char* p2 = nullptr;
1134   EXPECT_FALSE(m2.Matches(p2));
1135   EXPECT_TRUE(m2.Matches("hi"));
1136 }
1137 
TEST(NotNullTest,LinkedPtr)1138 TEST(NotNullTest, LinkedPtr) {
1139   const Matcher<std::shared_ptr<int>> m = NotNull();
1140   const std::shared_ptr<int> null_p;
1141   const std::shared_ptr<int> non_null_p(new int);
1142 
1143   EXPECT_FALSE(m.Matches(null_p));
1144   EXPECT_TRUE(m.Matches(non_null_p));
1145 }
1146 
TEST(NotNullTest,ReferenceToConstLinkedPtr)1147 TEST(NotNullTest, ReferenceToConstLinkedPtr) {
1148   const Matcher<const std::shared_ptr<double>&> m = NotNull();
1149   const std::shared_ptr<double> null_p;
1150   const std::shared_ptr<double> non_null_p(new double);
1151 
1152   EXPECT_FALSE(m.Matches(null_p));
1153   EXPECT_TRUE(m.Matches(non_null_p));
1154 }
1155 
TEST(NotNullTest,StdFunction)1156 TEST(NotNullTest, StdFunction) {
1157   const Matcher<std::function<void()>> m = NotNull();
1158 
1159   EXPECT_TRUE(m.Matches([]{}));
1160   EXPECT_FALSE(m.Matches(std::function<void()>()));
1161 }
1162 
1163 // Tests that NotNull() describes itself properly.
TEST(NotNullTest,CanDescribeSelf)1164 TEST(NotNullTest, CanDescribeSelf) {
1165   Matcher<int*> m = NotNull();
1166   EXPECT_EQ("isn't NULL", Describe(m));
1167 }
1168 
1169 // Tests that Ref(variable) matches an argument that references
1170 // 'variable'.
TEST(RefTest,MatchesSameVariable)1171 TEST(RefTest, MatchesSameVariable) {
1172   int a = 0;
1173   int b = 0;
1174   Matcher<int&> m = Ref(a);
1175   EXPECT_TRUE(m.Matches(a));
1176   EXPECT_FALSE(m.Matches(b));
1177 }
1178 
1179 // Tests that Ref(variable) describes itself properly.
TEST(RefTest,CanDescribeSelf)1180 TEST(RefTest, CanDescribeSelf) {
1181   int n = 5;
1182   Matcher<int&> m = Ref(n);
1183   stringstream ss;
1184   ss << "references the variable @" << &n << " 5";
1185   EXPECT_EQ(ss.str(), Describe(m));
1186 }
1187 
1188 // Test that Ref(non_const_varialbe) can be used as a matcher for a
1189 // const reference.
TEST(RefTest,CanBeUsedAsMatcherForConstReference)1190 TEST(RefTest, CanBeUsedAsMatcherForConstReference) {
1191   int a = 0;
1192   int b = 0;
1193   Matcher<const int&> m = Ref(a);
1194   EXPECT_TRUE(m.Matches(a));
1195   EXPECT_FALSE(m.Matches(b));
1196 }
1197 
1198 // Tests that Ref(variable) is covariant, i.e. Ref(derived) can be
1199 // used wherever Ref(base) can be used (Ref(derived) is a sub-type
1200 // of Ref(base), but not vice versa.
1201 
TEST(RefTest,IsCovariant)1202 TEST(RefTest, IsCovariant) {
1203   Base base, base2;
1204   Derived derived;
1205   Matcher<const Base&> m1 = Ref(base);
1206   EXPECT_TRUE(m1.Matches(base));
1207   EXPECT_FALSE(m1.Matches(base2));
1208   EXPECT_FALSE(m1.Matches(derived));
1209 
1210   m1 = Ref(derived);
1211   EXPECT_TRUE(m1.Matches(derived));
1212   EXPECT_FALSE(m1.Matches(base));
1213   EXPECT_FALSE(m1.Matches(base2));
1214 }
1215 
TEST(RefTest,ExplainsResult)1216 TEST(RefTest, ExplainsResult) {
1217   int n = 0;
1218   EXPECT_THAT(Explain(Matcher<const int&>(Ref(n)), n),
1219               StartsWith("which is located @"));
1220 
1221   int m = 0;
1222   EXPECT_THAT(Explain(Matcher<const int&>(Ref(n)), m),
1223               StartsWith("which is located @"));
1224 }
1225 
1226 // Tests string comparison matchers.
1227 
TEST(StrEqTest,MatchesEqualString)1228 TEST(StrEqTest, MatchesEqualString) {
1229   Matcher<const char*> m = StrEq(std::string("Hello"));
1230   EXPECT_TRUE(m.Matches("Hello"));
1231   EXPECT_FALSE(m.Matches("hello"));
1232   EXPECT_FALSE(m.Matches(nullptr));
1233 
1234   Matcher<const std::string&> m2 = StrEq("Hello");
1235   EXPECT_TRUE(m2.Matches("Hello"));
1236   EXPECT_FALSE(m2.Matches("Hi"));
1237 
1238 #if GTEST_HAS_ABSL
1239   Matcher<const absl::string_view&> m3 = StrEq("Hello");
1240   EXPECT_TRUE(m3.Matches(absl::string_view("Hello")));
1241   EXPECT_FALSE(m3.Matches(absl::string_view("hello")));
1242   EXPECT_FALSE(m3.Matches(absl::string_view()));
1243 
1244   Matcher<const absl::string_view&> m_empty = StrEq("");
1245   EXPECT_TRUE(m_empty.Matches(absl::string_view("")));
1246   EXPECT_TRUE(m_empty.Matches(absl::string_view()));
1247   EXPECT_FALSE(m_empty.Matches(absl::string_view("hello")));
1248 #endif  // GTEST_HAS_ABSL
1249 }
1250 
TEST(StrEqTest,CanDescribeSelf)1251 TEST(StrEqTest, CanDescribeSelf) {
1252   Matcher<std::string> m = StrEq("Hi-\'\"?\\\a\b\f\n\r\t\v\xD3");
1253   EXPECT_EQ("is equal to \"Hi-\'\\\"?\\\\\\a\\b\\f\\n\\r\\t\\v\\xD3\"",
1254       Describe(m));
1255 
1256   std::string str("01204500800");
1257   str[3] = '\0';
1258   Matcher<std::string> m2 = StrEq(str);
1259   EXPECT_EQ("is equal to \"012\\04500800\"", Describe(m2));
1260   str[0] = str[6] = str[7] = str[9] = str[10] = '\0';
1261   Matcher<std::string> m3 = StrEq(str);
1262   EXPECT_EQ("is equal to \"\\012\\045\\0\\08\\0\\0\"", Describe(m3));
1263 }
1264 
TEST(StrNeTest,MatchesUnequalString)1265 TEST(StrNeTest, MatchesUnequalString) {
1266   Matcher<const char*> m = StrNe("Hello");
1267   EXPECT_TRUE(m.Matches(""));
1268   EXPECT_TRUE(m.Matches(nullptr));
1269   EXPECT_FALSE(m.Matches("Hello"));
1270 
1271   Matcher<std::string> m2 = StrNe(std::string("Hello"));
1272   EXPECT_TRUE(m2.Matches("hello"));
1273   EXPECT_FALSE(m2.Matches("Hello"));
1274 
1275 #if GTEST_HAS_ABSL
1276   Matcher<const absl::string_view> m3 = StrNe("Hello");
1277   EXPECT_TRUE(m3.Matches(absl::string_view("")));
1278   EXPECT_TRUE(m3.Matches(absl::string_view()));
1279   EXPECT_FALSE(m3.Matches(absl::string_view("Hello")));
1280 #endif  // GTEST_HAS_ABSL
1281 }
1282 
TEST(StrNeTest,CanDescribeSelf)1283 TEST(StrNeTest, CanDescribeSelf) {
1284   Matcher<const char*> m = StrNe("Hi");
1285   EXPECT_EQ("isn't equal to \"Hi\"", Describe(m));
1286 }
1287 
TEST(StrCaseEqTest,MatchesEqualStringIgnoringCase)1288 TEST(StrCaseEqTest, MatchesEqualStringIgnoringCase) {
1289   Matcher<const char*> m = StrCaseEq(std::string("Hello"));
1290   EXPECT_TRUE(m.Matches("Hello"));
1291   EXPECT_TRUE(m.Matches("hello"));
1292   EXPECT_FALSE(m.Matches("Hi"));
1293   EXPECT_FALSE(m.Matches(nullptr));
1294 
1295   Matcher<const std::string&> m2 = StrCaseEq("Hello");
1296   EXPECT_TRUE(m2.Matches("hello"));
1297   EXPECT_FALSE(m2.Matches("Hi"));
1298 
1299 #if GTEST_HAS_ABSL
1300   Matcher<const absl::string_view&> m3 = StrCaseEq(std::string("Hello"));
1301   EXPECT_TRUE(m3.Matches(absl::string_view("Hello")));
1302   EXPECT_TRUE(m3.Matches(absl::string_view("hello")));
1303   EXPECT_FALSE(m3.Matches(absl::string_view("Hi")));
1304   EXPECT_FALSE(m3.Matches(absl::string_view()));
1305 #endif  // GTEST_HAS_ABSL
1306 }
1307 
TEST(StrCaseEqTest,MatchesEqualStringWith0IgnoringCase)1308 TEST(StrCaseEqTest, MatchesEqualStringWith0IgnoringCase) {
1309   std::string str1("oabocdooeoo");
1310   std::string str2("OABOCDOOEOO");
1311   Matcher<const std::string&> m0 = StrCaseEq(str1);
1312   EXPECT_FALSE(m0.Matches(str2 + std::string(1, '\0')));
1313 
1314   str1[3] = str2[3] = '\0';
1315   Matcher<const std::string&> m1 = StrCaseEq(str1);
1316   EXPECT_TRUE(m1.Matches(str2));
1317 
1318   str1[0] = str1[6] = str1[7] = str1[10] = '\0';
1319   str2[0] = str2[6] = str2[7] = str2[10] = '\0';
1320   Matcher<const std::string&> m2 = StrCaseEq(str1);
1321   str1[9] = str2[9] = '\0';
1322   EXPECT_FALSE(m2.Matches(str2));
1323 
1324   Matcher<const std::string&> m3 = StrCaseEq(str1);
1325   EXPECT_TRUE(m3.Matches(str2));
1326 
1327   EXPECT_FALSE(m3.Matches(str2 + "x"));
1328   str2.append(1, '\0');
1329   EXPECT_FALSE(m3.Matches(str2));
1330   EXPECT_FALSE(m3.Matches(std::string(str2, 0, 9)));
1331 }
1332 
TEST(StrCaseEqTest,CanDescribeSelf)1333 TEST(StrCaseEqTest, CanDescribeSelf) {
1334   Matcher<std::string> m = StrCaseEq("Hi");
1335   EXPECT_EQ("is equal to (ignoring case) \"Hi\"", Describe(m));
1336 }
1337 
TEST(StrCaseNeTest,MatchesUnequalStringIgnoringCase)1338 TEST(StrCaseNeTest, MatchesUnequalStringIgnoringCase) {
1339   Matcher<const char*> m = StrCaseNe("Hello");
1340   EXPECT_TRUE(m.Matches("Hi"));
1341   EXPECT_TRUE(m.Matches(nullptr));
1342   EXPECT_FALSE(m.Matches("Hello"));
1343   EXPECT_FALSE(m.Matches("hello"));
1344 
1345   Matcher<std::string> m2 = StrCaseNe(std::string("Hello"));
1346   EXPECT_TRUE(m2.Matches(""));
1347   EXPECT_FALSE(m2.Matches("Hello"));
1348 
1349 #if GTEST_HAS_ABSL
1350   Matcher<const absl::string_view> m3 = StrCaseNe("Hello");
1351   EXPECT_TRUE(m3.Matches(absl::string_view("Hi")));
1352   EXPECT_TRUE(m3.Matches(absl::string_view()));
1353   EXPECT_FALSE(m3.Matches(absl::string_view("Hello")));
1354   EXPECT_FALSE(m3.Matches(absl::string_view("hello")));
1355 #endif  // GTEST_HAS_ABSL
1356 }
1357 
TEST(StrCaseNeTest,CanDescribeSelf)1358 TEST(StrCaseNeTest, CanDescribeSelf) {
1359   Matcher<const char*> m = StrCaseNe("Hi");
1360   EXPECT_EQ("isn't equal to (ignoring case) \"Hi\"", Describe(m));
1361 }
1362 
1363 // Tests that HasSubstr() works for matching string-typed values.
TEST(HasSubstrTest,WorksForStringClasses)1364 TEST(HasSubstrTest, WorksForStringClasses) {
1365   const Matcher<std::string> m1 = HasSubstr("foo");
1366   EXPECT_TRUE(m1.Matches(std::string("I love food.")));
1367   EXPECT_FALSE(m1.Matches(std::string("tofo")));
1368 
1369   const Matcher<const std::string&> m2 = HasSubstr("foo");
1370   EXPECT_TRUE(m2.Matches(std::string("I love food.")));
1371   EXPECT_FALSE(m2.Matches(std::string("tofo")));
1372 
1373   const Matcher<std::string> m_empty = HasSubstr("");
1374   EXPECT_TRUE(m_empty.Matches(std::string()));
1375   EXPECT_TRUE(m_empty.Matches(std::string("not empty")));
1376 }
1377 
1378 // Tests that HasSubstr() works for matching C-string-typed values.
TEST(HasSubstrTest,WorksForCStrings)1379 TEST(HasSubstrTest, WorksForCStrings) {
1380   const Matcher<char*> m1 = HasSubstr("foo");
1381   EXPECT_TRUE(m1.Matches(const_cast<char*>("I love food.")));
1382   EXPECT_FALSE(m1.Matches(const_cast<char*>("tofo")));
1383   EXPECT_FALSE(m1.Matches(nullptr));
1384 
1385   const Matcher<const char*> m2 = HasSubstr("foo");
1386   EXPECT_TRUE(m2.Matches("I love food."));
1387   EXPECT_FALSE(m2.Matches("tofo"));
1388   EXPECT_FALSE(m2.Matches(nullptr));
1389 
1390   const Matcher<const char*> m_empty = HasSubstr("");
1391   EXPECT_TRUE(m_empty.Matches("not empty"));
1392   EXPECT_TRUE(m_empty.Matches(""));
1393   EXPECT_FALSE(m_empty.Matches(nullptr));
1394 }
1395 
1396 #if GTEST_HAS_ABSL
1397 // Tests that HasSubstr() works for matching absl::string_view-typed values.
TEST(HasSubstrTest,WorksForStringViewClasses)1398 TEST(HasSubstrTest, WorksForStringViewClasses) {
1399   const Matcher<absl::string_view> m1 = HasSubstr("foo");
1400   EXPECT_TRUE(m1.Matches(absl::string_view("I love food.")));
1401   EXPECT_FALSE(m1.Matches(absl::string_view("tofo")));
1402   EXPECT_FALSE(m1.Matches(absl::string_view()));
1403 
1404   const Matcher<const absl::string_view&> m2 = HasSubstr("foo");
1405   EXPECT_TRUE(m2.Matches(absl::string_view("I love food.")));
1406   EXPECT_FALSE(m2.Matches(absl::string_view("tofo")));
1407   EXPECT_FALSE(m2.Matches(absl::string_view()));
1408 
1409   const Matcher<const absl::string_view&> m3 = HasSubstr("");
1410   EXPECT_TRUE(m3.Matches(absl::string_view("foo")));
1411   EXPECT_TRUE(m3.Matches(absl::string_view("")));
1412   EXPECT_TRUE(m3.Matches(absl::string_view()));
1413 }
1414 #endif  // GTEST_HAS_ABSL
1415 
1416 // Tests that HasSubstr(s) describes itself properly.
TEST(HasSubstrTest,CanDescribeSelf)1417 TEST(HasSubstrTest, CanDescribeSelf) {
1418   Matcher<std::string> m = HasSubstr("foo\n\"");
1419   EXPECT_EQ("has substring \"foo\\n\\\"\"", Describe(m));
1420 }
1421 
TEST(KeyTest,CanDescribeSelf)1422 TEST(KeyTest, CanDescribeSelf) {
1423   Matcher<const pair<std::string, int>&> m = Key("foo");
1424   EXPECT_EQ("has a key that is equal to \"foo\"", Describe(m));
1425   EXPECT_EQ("doesn't have a key that is equal to \"foo\"", DescribeNegation(m));
1426 }
1427 
TEST(KeyTest,ExplainsResult)1428 TEST(KeyTest, ExplainsResult) {
1429   Matcher<pair<int, bool> > m = Key(GreaterThan(10));
1430   EXPECT_EQ("whose first field is a value which is 5 less than 10",
1431             Explain(m, make_pair(5, true)));
1432   EXPECT_EQ("whose first field is a value which is 5 more than 10",
1433             Explain(m, make_pair(15, true)));
1434 }
1435 
TEST(KeyTest,MatchesCorrectly)1436 TEST(KeyTest, MatchesCorrectly) {
1437   pair<int, std::string> p(25, "foo");
1438   EXPECT_THAT(p, Key(25));
1439   EXPECT_THAT(p, Not(Key(42)));
1440   EXPECT_THAT(p, Key(Ge(20)));
1441   EXPECT_THAT(p, Not(Key(Lt(25))));
1442 }
1443 
TEST(KeyTest,WorksWithMoveOnly)1444 TEST(KeyTest, WorksWithMoveOnly) {
1445   pair<std::unique_ptr<int>, std::unique_ptr<int>> p;
1446   EXPECT_THAT(p, Key(Eq(nullptr)));
1447 }
1448 
1449 template <size_t I>
1450 struct Tag {};
1451 
1452 struct PairWithGet {
1453   int member_1;
1454   std::string member_2;
1455   using first_type = int;
1456   using second_type = std::string;
1457 
GetImpltesting::gmock_matchers_test::__anon86e4b7b50111::PairWithGet1458   const int& GetImpl(Tag<0>) const { return member_1; }
GetImpltesting::gmock_matchers_test::__anon86e4b7b50111::PairWithGet1459   const std::string& GetImpl(Tag<1>) const { return member_2; }
1460 };
1461 template <size_t I>
get(const PairWithGet & value)1462 auto get(const PairWithGet& value) -> decltype(value.GetImpl(Tag<I>())) {
1463   return value.GetImpl(Tag<I>());
1464 }
TEST(PairTest,MatchesPairWithGetCorrectly)1465 TEST(PairTest, MatchesPairWithGetCorrectly) {
1466   PairWithGet p{25, "foo"};
1467   EXPECT_THAT(p, Key(25));
1468   EXPECT_THAT(p, Not(Key(42)));
1469   EXPECT_THAT(p, Key(Ge(20)));
1470   EXPECT_THAT(p, Not(Key(Lt(25))));
1471 
1472   std::vector<PairWithGet> v = {{11, "Foo"}, {29, "gMockIsBestMock"}};
1473   EXPECT_THAT(v, Contains(Key(29)));
1474 }
1475 
TEST(KeyTest,SafelyCastsInnerMatcher)1476 TEST(KeyTest, SafelyCastsInnerMatcher) {
1477   Matcher<int> is_positive = Gt(0);
1478   Matcher<int> is_negative = Lt(0);
1479   pair<char, bool> p('a', true);
1480   EXPECT_THAT(p, Key(is_positive));
1481   EXPECT_THAT(p, Not(Key(is_negative)));
1482 }
1483 
TEST(KeyTest,InsideContainsUsingMap)1484 TEST(KeyTest, InsideContainsUsingMap) {
1485   map<int, char> container;
1486   container.insert(make_pair(1, 'a'));
1487   container.insert(make_pair(2, 'b'));
1488   container.insert(make_pair(4, 'c'));
1489   EXPECT_THAT(container, Contains(Key(1)));
1490   EXPECT_THAT(container, Not(Contains(Key(3))));
1491 }
1492 
TEST(KeyTest,InsideContainsUsingMultimap)1493 TEST(KeyTest, InsideContainsUsingMultimap) {
1494   multimap<int, char> container;
1495   container.insert(make_pair(1, 'a'));
1496   container.insert(make_pair(2, 'b'));
1497   container.insert(make_pair(4, 'c'));
1498 
1499   EXPECT_THAT(container, Not(Contains(Key(25))));
1500   container.insert(make_pair(25, 'd'));
1501   EXPECT_THAT(container, Contains(Key(25)));
1502   container.insert(make_pair(25, 'e'));
1503   EXPECT_THAT(container, Contains(Key(25)));
1504 
1505   EXPECT_THAT(container, Contains(Key(1)));
1506   EXPECT_THAT(container, Not(Contains(Key(3))));
1507 }
1508 
TEST(PairTest,Typing)1509 TEST(PairTest, Typing) {
1510   // Test verifies the following type conversions can be compiled.
1511   Matcher<const pair<const char*, int>&> m1 = Pair("foo", 42);
1512   Matcher<const pair<const char*, int> > m2 = Pair("foo", 42);
1513   Matcher<pair<const char*, int> > m3 = Pair("foo", 42);
1514 
1515   Matcher<pair<int, const std::string> > m4 = Pair(25, "42");
1516   Matcher<pair<const std::string, int> > m5 = Pair("25", 42);
1517 }
1518 
TEST(PairTest,CanDescribeSelf)1519 TEST(PairTest, CanDescribeSelf) {
1520   Matcher<const pair<std::string, int>&> m1 = Pair("foo", 42);
1521   EXPECT_EQ("has a first field that is equal to \"foo\""
1522             ", and has a second field that is equal to 42",
1523             Describe(m1));
1524   EXPECT_EQ("has a first field that isn't equal to \"foo\""
1525             ", or has a second field that isn't equal to 42",
1526             DescribeNegation(m1));
1527   // Double and triple negation (1 or 2 times not and description of negation).
1528   Matcher<const pair<int, int>&> m2 = Not(Pair(Not(13), 42));
1529   EXPECT_EQ("has a first field that isn't equal to 13"
1530             ", and has a second field that is equal to 42",
1531             DescribeNegation(m2));
1532 }
1533 
TEST(PairTest,CanExplainMatchResultTo)1534 TEST(PairTest, CanExplainMatchResultTo) {
1535   // If neither field matches, Pair() should explain about the first
1536   // field.
1537   const Matcher<pair<int, int> > m = Pair(GreaterThan(0), GreaterThan(0));
1538   EXPECT_EQ("whose first field does not match, which is 1 less than 0",
1539             Explain(m, make_pair(-1, -2)));
1540 
1541   // If the first field matches but the second doesn't, Pair() should
1542   // explain about the second field.
1543   EXPECT_EQ("whose second field does not match, which is 2 less than 0",
1544             Explain(m, make_pair(1, -2)));
1545 
1546   // If the first field doesn't match but the second does, Pair()
1547   // should explain about the first field.
1548   EXPECT_EQ("whose first field does not match, which is 1 less than 0",
1549             Explain(m, make_pair(-1, 2)));
1550 
1551   // If both fields match, Pair() should explain about them both.
1552   EXPECT_EQ("whose both fields match, where the first field is a value "
1553             "which is 1 more than 0, and the second field is a value "
1554             "which is 2 more than 0",
1555             Explain(m, make_pair(1, 2)));
1556 
1557   // If only the first match has an explanation, only this explanation should
1558   // be printed.
1559   const Matcher<pair<int, int> > explain_first = Pair(GreaterThan(0), 0);
1560   EXPECT_EQ("whose both fields match, where the first field is a value "
1561             "which is 1 more than 0",
1562             Explain(explain_first, make_pair(1, 0)));
1563 
1564   // If only the second match has an explanation, only this explanation should
1565   // be printed.
1566   const Matcher<pair<int, int> > explain_second = Pair(0, GreaterThan(0));
1567   EXPECT_EQ("whose both fields match, where the second field is a value "
1568             "which is 1 more than 0",
1569             Explain(explain_second, make_pair(0, 1)));
1570 }
1571 
TEST(PairTest,MatchesCorrectly)1572 TEST(PairTest, MatchesCorrectly) {
1573   pair<int, std::string> p(25, "foo");
1574 
1575   // Both fields match.
1576   EXPECT_THAT(p, Pair(25, "foo"));
1577   EXPECT_THAT(p, Pair(Ge(20), HasSubstr("o")));
1578 
1579   // 'first' doesnt' match, but 'second' matches.
1580   EXPECT_THAT(p, Not(Pair(42, "foo")));
1581   EXPECT_THAT(p, Not(Pair(Lt(25), "foo")));
1582 
1583   // 'first' matches, but 'second' doesn't match.
1584   EXPECT_THAT(p, Not(Pair(25, "bar")));
1585   EXPECT_THAT(p, Not(Pair(25, Not("foo"))));
1586 
1587   // Neither field matches.
1588   EXPECT_THAT(p, Not(Pair(13, "bar")));
1589   EXPECT_THAT(p, Not(Pair(Lt(13), HasSubstr("a"))));
1590 }
1591 
TEST(PairTest,WorksWithMoveOnly)1592 TEST(PairTest, WorksWithMoveOnly) {
1593   pair<std::unique_ptr<int>, std::unique_ptr<int>> p;
1594   p.second.reset(new int(7));
1595   EXPECT_THAT(p, Pair(Eq(nullptr), Ne(nullptr)));
1596 }
1597 
TEST(PairTest,SafelyCastsInnerMatchers)1598 TEST(PairTest, SafelyCastsInnerMatchers) {
1599   Matcher<int> is_positive = Gt(0);
1600   Matcher<int> is_negative = Lt(0);
1601   pair<char, bool> p('a', true);
1602   EXPECT_THAT(p, Pair(is_positive, _));
1603   EXPECT_THAT(p, Not(Pair(is_negative, _)));
1604   EXPECT_THAT(p, Pair(_, is_positive));
1605   EXPECT_THAT(p, Not(Pair(_, is_negative)));
1606 }
1607 
TEST(PairTest,InsideContainsUsingMap)1608 TEST(PairTest, InsideContainsUsingMap) {
1609   map<int, char> container;
1610   container.insert(make_pair(1, 'a'));
1611   container.insert(make_pair(2, 'b'));
1612   container.insert(make_pair(4, 'c'));
1613   EXPECT_THAT(container, Contains(Pair(1, 'a')));
1614   EXPECT_THAT(container, Contains(Pair(1, _)));
1615   EXPECT_THAT(container, Contains(Pair(_, 'a')));
1616   EXPECT_THAT(container, Not(Contains(Pair(3, _))));
1617 }
1618 
TEST(ContainsTest,WorksWithMoveOnly)1619 TEST(ContainsTest, WorksWithMoveOnly) {
1620   ContainerHelper helper;
1621   EXPECT_CALL(helper, Call(Contains(Pointee(2))));
1622   helper.Call(MakeUniquePtrs({1, 2}));
1623 }
1624 
TEST(PairTest,UseGetInsteadOfMembers)1625 TEST(PairTest, UseGetInsteadOfMembers) {
1626   PairWithGet pair{7, "ABC"};
1627   EXPECT_THAT(pair, Pair(7, "ABC"));
1628   EXPECT_THAT(pair, Pair(Ge(7), HasSubstr("AB")));
1629   EXPECT_THAT(pair, Not(Pair(Lt(7), "ABC")));
1630 
1631   std::vector<PairWithGet> v = {{11, "Foo"}, {29, "gMockIsBestMock"}};
1632   EXPECT_THAT(v,
1633               ElementsAre(Pair(11, std::string("Foo")), Pair(Ge(10), Not(""))));
1634 }
1635 
1636 // Tests StartsWith(s).
1637 
TEST(StartsWithTest,MatchesStringWithGivenPrefix)1638 TEST(StartsWithTest, MatchesStringWithGivenPrefix) {
1639   const Matcher<const char*> m1 = StartsWith(std::string(""));
1640   EXPECT_TRUE(m1.Matches("Hi"));
1641   EXPECT_TRUE(m1.Matches(""));
1642   EXPECT_FALSE(m1.Matches(nullptr));
1643 
1644   const Matcher<const std::string&> m2 = StartsWith("Hi");
1645   EXPECT_TRUE(m2.Matches("Hi"));
1646   EXPECT_TRUE(m2.Matches("Hi Hi!"));
1647   EXPECT_TRUE(m2.Matches("High"));
1648   EXPECT_FALSE(m2.Matches("H"));
1649   EXPECT_FALSE(m2.Matches(" Hi"));
1650 
1651 #if GTEST_HAS_ABSL
1652   const Matcher<absl::string_view> m_empty = StartsWith("");
1653   EXPECT_TRUE(m_empty.Matches(absl::string_view()));
1654   EXPECT_TRUE(m_empty.Matches(absl::string_view("")));
1655   EXPECT_TRUE(m_empty.Matches(absl::string_view("not empty")));
1656 #endif  // GTEST_HAS_ABSL
1657 }
1658 
TEST(StartsWithTest,CanDescribeSelf)1659 TEST(StartsWithTest, CanDescribeSelf) {
1660   Matcher<const std::string> m = StartsWith("Hi");
1661   EXPECT_EQ("starts with \"Hi\"", Describe(m));
1662 }
1663 
1664 // Tests EndsWith(s).
1665 
TEST(EndsWithTest,MatchesStringWithGivenSuffix)1666 TEST(EndsWithTest, MatchesStringWithGivenSuffix) {
1667   const Matcher<const char*> m1 = EndsWith("");
1668   EXPECT_TRUE(m1.Matches("Hi"));
1669   EXPECT_TRUE(m1.Matches(""));
1670   EXPECT_FALSE(m1.Matches(nullptr));
1671 
1672   const Matcher<const std::string&> m2 = EndsWith(std::string("Hi"));
1673   EXPECT_TRUE(m2.Matches("Hi"));
1674   EXPECT_TRUE(m2.Matches("Wow Hi Hi"));
1675   EXPECT_TRUE(m2.Matches("Super Hi"));
1676   EXPECT_FALSE(m2.Matches("i"));
1677   EXPECT_FALSE(m2.Matches("Hi "));
1678 
1679 #if GTEST_HAS_ABSL
1680   const Matcher<const absl::string_view&> m4 = EndsWith("");
1681   EXPECT_TRUE(m4.Matches("Hi"));
1682   EXPECT_TRUE(m4.Matches(""));
1683   EXPECT_TRUE(m4.Matches(absl::string_view()));
1684   EXPECT_TRUE(m4.Matches(absl::string_view("")));
1685 #endif  // GTEST_HAS_ABSL
1686 }
1687 
TEST(EndsWithTest,CanDescribeSelf)1688 TEST(EndsWithTest, CanDescribeSelf) {
1689   Matcher<const std::string> m = EndsWith("Hi");
1690   EXPECT_EQ("ends with \"Hi\"", Describe(m));
1691 }
1692 
1693 // Tests MatchesRegex().
1694 
TEST(MatchesRegexTest,MatchesStringMatchingGivenRegex)1695 TEST(MatchesRegexTest, MatchesStringMatchingGivenRegex) {
1696   const Matcher<const char*> m1 = MatchesRegex("a.*z");
1697   EXPECT_TRUE(m1.Matches("az"));
1698   EXPECT_TRUE(m1.Matches("abcz"));
1699   EXPECT_FALSE(m1.Matches(nullptr));
1700 
1701   const Matcher<const std::string&> m2 = MatchesRegex(new RE("a.*z"));
1702   EXPECT_TRUE(m2.Matches("azbz"));
1703   EXPECT_FALSE(m2.Matches("az1"));
1704   EXPECT_FALSE(m2.Matches("1az"));
1705 
1706 #if GTEST_HAS_ABSL
1707   const Matcher<const absl::string_view&> m3 = MatchesRegex("a.*z");
1708   EXPECT_TRUE(m3.Matches(absl::string_view("az")));
1709   EXPECT_TRUE(m3.Matches(absl::string_view("abcz")));
1710   EXPECT_FALSE(m3.Matches(absl::string_view("1az")));
1711   EXPECT_FALSE(m3.Matches(absl::string_view()));
1712   const Matcher<const absl::string_view&> m4 = MatchesRegex("");
1713   EXPECT_TRUE(m4.Matches(absl::string_view("")));
1714   EXPECT_TRUE(m4.Matches(absl::string_view()));
1715 #endif  // GTEST_HAS_ABSL
1716 }
1717 
TEST(MatchesRegexTest,CanDescribeSelf)1718 TEST(MatchesRegexTest, CanDescribeSelf) {
1719   Matcher<const std::string> m1 = MatchesRegex(std::string("Hi.*"));
1720   EXPECT_EQ("matches regular expression \"Hi.*\"", Describe(m1));
1721 
1722   Matcher<const char*> m2 = MatchesRegex(new RE("a.*"));
1723   EXPECT_EQ("matches regular expression \"a.*\"", Describe(m2));
1724 
1725 #if GTEST_HAS_ABSL
1726   Matcher<const absl::string_view> m3 = MatchesRegex(new RE("0.*"));
1727   EXPECT_EQ("matches regular expression \"0.*\"", Describe(m3));
1728 #endif  // GTEST_HAS_ABSL
1729 }
1730 
1731 // Tests ContainsRegex().
1732 
TEST(ContainsRegexTest,MatchesStringContainingGivenRegex)1733 TEST(ContainsRegexTest, MatchesStringContainingGivenRegex) {
1734   const Matcher<const char*> m1 = ContainsRegex(std::string("a.*z"));
1735   EXPECT_TRUE(m1.Matches("az"));
1736   EXPECT_TRUE(m1.Matches("0abcz1"));
1737   EXPECT_FALSE(m1.Matches(nullptr));
1738 
1739   const Matcher<const std::string&> m2 = ContainsRegex(new RE("a.*z"));
1740   EXPECT_TRUE(m2.Matches("azbz"));
1741   EXPECT_TRUE(m2.Matches("az1"));
1742   EXPECT_FALSE(m2.Matches("1a"));
1743 
1744 #if GTEST_HAS_ABSL
1745   const Matcher<const absl::string_view&> m3 = ContainsRegex(new RE("a.*z"));
1746   EXPECT_TRUE(m3.Matches(absl::string_view("azbz")));
1747   EXPECT_TRUE(m3.Matches(absl::string_view("az1")));
1748   EXPECT_FALSE(m3.Matches(absl::string_view("1a")));
1749   EXPECT_FALSE(m3.Matches(absl::string_view()));
1750   const Matcher<const absl::string_view&> m4 = ContainsRegex("");
1751   EXPECT_TRUE(m4.Matches(absl::string_view("")));
1752   EXPECT_TRUE(m4.Matches(absl::string_view()));
1753 #endif  // GTEST_HAS_ABSL
1754 }
1755 
TEST(ContainsRegexTest,CanDescribeSelf)1756 TEST(ContainsRegexTest, CanDescribeSelf) {
1757   Matcher<const std::string> m1 = ContainsRegex("Hi.*");
1758   EXPECT_EQ("contains regular expression \"Hi.*\"", Describe(m1));
1759 
1760   Matcher<const char*> m2 = ContainsRegex(new RE("a.*"));
1761   EXPECT_EQ("contains regular expression \"a.*\"", Describe(m2));
1762 
1763 #if GTEST_HAS_ABSL
1764   Matcher<const absl::string_view> m3 = ContainsRegex(new RE("0.*"));
1765   EXPECT_EQ("contains regular expression \"0.*\"", Describe(m3));
1766 #endif  // GTEST_HAS_ABSL
1767 }
1768 
1769 // Tests for wide strings.
1770 #if GTEST_HAS_STD_WSTRING
TEST(StdWideStrEqTest,MatchesEqual)1771 TEST(StdWideStrEqTest, MatchesEqual) {
1772   Matcher<const wchar_t*> m = StrEq(::std::wstring(L"Hello"));
1773   EXPECT_TRUE(m.Matches(L"Hello"));
1774   EXPECT_FALSE(m.Matches(L"hello"));
1775   EXPECT_FALSE(m.Matches(nullptr));
1776 
1777   Matcher<const ::std::wstring&> m2 = StrEq(L"Hello");
1778   EXPECT_TRUE(m2.Matches(L"Hello"));
1779   EXPECT_FALSE(m2.Matches(L"Hi"));
1780 
1781   Matcher<const ::std::wstring&> m3 = StrEq(L"\xD3\x576\x8D3\xC74D");
1782   EXPECT_TRUE(m3.Matches(L"\xD3\x576\x8D3\xC74D"));
1783   EXPECT_FALSE(m3.Matches(L"\xD3\x576\x8D3\xC74E"));
1784 
1785   ::std::wstring str(L"01204500800");
1786   str[3] = L'\0';
1787   Matcher<const ::std::wstring&> m4 = StrEq(str);
1788   EXPECT_TRUE(m4.Matches(str));
1789   str[0] = str[6] = str[7] = str[9] = str[10] = L'\0';
1790   Matcher<const ::std::wstring&> m5 = StrEq(str);
1791   EXPECT_TRUE(m5.Matches(str));
1792 }
1793 
TEST(StdWideStrEqTest,CanDescribeSelf)1794 TEST(StdWideStrEqTest, CanDescribeSelf) {
1795   Matcher< ::std::wstring> m = StrEq(L"Hi-\'\"?\\\a\b\f\n\r\t\v");
1796   EXPECT_EQ("is equal to L\"Hi-\'\\\"?\\\\\\a\\b\\f\\n\\r\\t\\v\"",
1797     Describe(m));
1798 
1799   Matcher< ::std::wstring> m2 = StrEq(L"\xD3\x576\x8D3\xC74D");
1800   EXPECT_EQ("is equal to L\"\\xD3\\x576\\x8D3\\xC74D\"",
1801     Describe(m2));
1802 
1803   ::std::wstring str(L"01204500800");
1804   str[3] = L'\0';
1805   Matcher<const ::std::wstring&> m4 = StrEq(str);
1806   EXPECT_EQ("is equal to L\"012\\04500800\"", Describe(m4));
1807   str[0] = str[6] = str[7] = str[9] = str[10] = L'\0';
1808   Matcher<const ::std::wstring&> m5 = StrEq(str);
1809   EXPECT_EQ("is equal to L\"\\012\\045\\0\\08\\0\\0\"", Describe(m5));
1810 }
1811 
TEST(StdWideStrNeTest,MatchesUnequalString)1812 TEST(StdWideStrNeTest, MatchesUnequalString) {
1813   Matcher<const wchar_t*> m = StrNe(L"Hello");
1814   EXPECT_TRUE(m.Matches(L""));
1815   EXPECT_TRUE(m.Matches(nullptr));
1816   EXPECT_FALSE(m.Matches(L"Hello"));
1817 
1818   Matcher< ::std::wstring> m2 = StrNe(::std::wstring(L"Hello"));
1819   EXPECT_TRUE(m2.Matches(L"hello"));
1820   EXPECT_FALSE(m2.Matches(L"Hello"));
1821 }
1822 
TEST(StdWideStrNeTest,CanDescribeSelf)1823 TEST(StdWideStrNeTest, CanDescribeSelf) {
1824   Matcher<const wchar_t*> m = StrNe(L"Hi");
1825   EXPECT_EQ("isn't equal to L\"Hi\"", Describe(m));
1826 }
1827 
TEST(StdWideStrCaseEqTest,MatchesEqualStringIgnoringCase)1828 TEST(StdWideStrCaseEqTest, MatchesEqualStringIgnoringCase) {
1829   Matcher<const wchar_t*> m = StrCaseEq(::std::wstring(L"Hello"));
1830   EXPECT_TRUE(m.Matches(L"Hello"));
1831   EXPECT_TRUE(m.Matches(L"hello"));
1832   EXPECT_FALSE(m.Matches(L"Hi"));
1833   EXPECT_FALSE(m.Matches(nullptr));
1834 
1835   Matcher<const ::std::wstring&> m2 = StrCaseEq(L"Hello");
1836   EXPECT_TRUE(m2.Matches(L"hello"));
1837   EXPECT_FALSE(m2.Matches(L"Hi"));
1838 }
1839 
TEST(StdWideStrCaseEqTest,MatchesEqualStringWith0IgnoringCase)1840 TEST(StdWideStrCaseEqTest, MatchesEqualStringWith0IgnoringCase) {
1841   ::std::wstring str1(L"oabocdooeoo");
1842   ::std::wstring str2(L"OABOCDOOEOO");
1843   Matcher<const ::std::wstring&> m0 = StrCaseEq(str1);
1844   EXPECT_FALSE(m0.Matches(str2 + ::std::wstring(1, L'\0')));
1845 
1846   str1[3] = str2[3] = L'\0';
1847   Matcher<const ::std::wstring&> m1 = StrCaseEq(str1);
1848   EXPECT_TRUE(m1.Matches(str2));
1849 
1850   str1[0] = str1[6] = str1[7] = str1[10] = L'\0';
1851   str2[0] = str2[6] = str2[7] = str2[10] = L'\0';
1852   Matcher<const ::std::wstring&> m2 = StrCaseEq(str1);
1853   str1[9] = str2[9] = L'\0';
1854   EXPECT_FALSE(m2.Matches(str2));
1855 
1856   Matcher<const ::std::wstring&> m3 = StrCaseEq(str1);
1857   EXPECT_TRUE(m3.Matches(str2));
1858 
1859   EXPECT_FALSE(m3.Matches(str2 + L"x"));
1860   str2.append(1, L'\0');
1861   EXPECT_FALSE(m3.Matches(str2));
1862   EXPECT_FALSE(m3.Matches(::std::wstring(str2, 0, 9)));
1863 }
1864 
TEST(StdWideStrCaseEqTest,CanDescribeSelf)1865 TEST(StdWideStrCaseEqTest, CanDescribeSelf) {
1866   Matcher< ::std::wstring> m = StrCaseEq(L"Hi");
1867   EXPECT_EQ("is equal to (ignoring case) L\"Hi\"", Describe(m));
1868 }
1869 
TEST(StdWideStrCaseNeTest,MatchesUnequalStringIgnoringCase)1870 TEST(StdWideStrCaseNeTest, MatchesUnequalStringIgnoringCase) {
1871   Matcher<const wchar_t*> m = StrCaseNe(L"Hello");
1872   EXPECT_TRUE(m.Matches(L"Hi"));
1873   EXPECT_TRUE(m.Matches(nullptr));
1874   EXPECT_FALSE(m.Matches(L"Hello"));
1875   EXPECT_FALSE(m.Matches(L"hello"));
1876 
1877   Matcher< ::std::wstring> m2 = StrCaseNe(::std::wstring(L"Hello"));
1878   EXPECT_TRUE(m2.Matches(L""));
1879   EXPECT_FALSE(m2.Matches(L"Hello"));
1880 }
1881 
TEST(StdWideStrCaseNeTest,CanDescribeSelf)1882 TEST(StdWideStrCaseNeTest, CanDescribeSelf) {
1883   Matcher<const wchar_t*> m = StrCaseNe(L"Hi");
1884   EXPECT_EQ("isn't equal to (ignoring case) L\"Hi\"", Describe(m));
1885 }
1886 
1887 // Tests that HasSubstr() works for matching wstring-typed values.
TEST(StdWideHasSubstrTest,WorksForStringClasses)1888 TEST(StdWideHasSubstrTest, WorksForStringClasses) {
1889   const Matcher< ::std::wstring> m1 = HasSubstr(L"foo");
1890   EXPECT_TRUE(m1.Matches(::std::wstring(L"I love food.")));
1891   EXPECT_FALSE(m1.Matches(::std::wstring(L"tofo")));
1892 
1893   const Matcher<const ::std::wstring&> m2 = HasSubstr(L"foo");
1894   EXPECT_TRUE(m2.Matches(::std::wstring(L"I love food.")));
1895   EXPECT_FALSE(m2.Matches(::std::wstring(L"tofo")));
1896 }
1897 
1898 // Tests that HasSubstr() works for matching C-wide-string-typed values.
TEST(StdWideHasSubstrTest,WorksForCStrings)1899 TEST(StdWideHasSubstrTest, WorksForCStrings) {
1900   const Matcher<wchar_t*> m1 = HasSubstr(L"foo");
1901   EXPECT_TRUE(m1.Matches(const_cast<wchar_t*>(L"I love food.")));
1902   EXPECT_FALSE(m1.Matches(const_cast<wchar_t*>(L"tofo")));
1903   EXPECT_FALSE(m1.Matches(nullptr));
1904 
1905   const Matcher<const wchar_t*> m2 = HasSubstr(L"foo");
1906   EXPECT_TRUE(m2.Matches(L"I love food."));
1907   EXPECT_FALSE(m2.Matches(L"tofo"));
1908   EXPECT_FALSE(m2.Matches(nullptr));
1909 }
1910 
1911 // Tests that HasSubstr(s) describes itself properly.
TEST(StdWideHasSubstrTest,CanDescribeSelf)1912 TEST(StdWideHasSubstrTest, CanDescribeSelf) {
1913   Matcher< ::std::wstring> m = HasSubstr(L"foo\n\"");
1914   EXPECT_EQ("has substring L\"foo\\n\\\"\"", Describe(m));
1915 }
1916 
1917 // Tests StartsWith(s).
1918 
TEST(StdWideStartsWithTest,MatchesStringWithGivenPrefix)1919 TEST(StdWideStartsWithTest, MatchesStringWithGivenPrefix) {
1920   const Matcher<const wchar_t*> m1 = StartsWith(::std::wstring(L""));
1921   EXPECT_TRUE(m1.Matches(L"Hi"));
1922   EXPECT_TRUE(m1.Matches(L""));
1923   EXPECT_FALSE(m1.Matches(nullptr));
1924 
1925   const Matcher<const ::std::wstring&> m2 = StartsWith(L"Hi");
1926   EXPECT_TRUE(m2.Matches(L"Hi"));
1927   EXPECT_TRUE(m2.Matches(L"Hi Hi!"));
1928   EXPECT_TRUE(m2.Matches(L"High"));
1929   EXPECT_FALSE(m2.Matches(L"H"));
1930   EXPECT_FALSE(m2.Matches(L" Hi"));
1931 }
1932 
TEST(StdWideStartsWithTest,CanDescribeSelf)1933 TEST(StdWideStartsWithTest, CanDescribeSelf) {
1934   Matcher<const ::std::wstring> m = StartsWith(L"Hi");
1935   EXPECT_EQ("starts with L\"Hi\"", Describe(m));
1936 }
1937 
1938 // Tests EndsWith(s).
1939 
TEST(StdWideEndsWithTest,MatchesStringWithGivenSuffix)1940 TEST(StdWideEndsWithTest, MatchesStringWithGivenSuffix) {
1941   const Matcher<const wchar_t*> m1 = EndsWith(L"");
1942   EXPECT_TRUE(m1.Matches(L"Hi"));
1943   EXPECT_TRUE(m1.Matches(L""));
1944   EXPECT_FALSE(m1.Matches(nullptr));
1945 
1946   const Matcher<const ::std::wstring&> m2 = EndsWith(::std::wstring(L"Hi"));
1947   EXPECT_TRUE(m2.Matches(L"Hi"));
1948   EXPECT_TRUE(m2.Matches(L"Wow Hi Hi"));
1949   EXPECT_TRUE(m2.Matches(L"Super Hi"));
1950   EXPECT_FALSE(m2.Matches(L"i"));
1951   EXPECT_FALSE(m2.Matches(L"Hi "));
1952 }
1953 
TEST(StdWideEndsWithTest,CanDescribeSelf)1954 TEST(StdWideEndsWithTest, CanDescribeSelf) {
1955   Matcher<const ::std::wstring> m = EndsWith(L"Hi");
1956   EXPECT_EQ("ends with L\"Hi\"", Describe(m));
1957 }
1958 
1959 #endif  // GTEST_HAS_STD_WSTRING
1960 
1961 typedef ::std::tuple<long, int> Tuple2;  // NOLINT
1962 
1963 // Tests that Eq() matches a 2-tuple where the first field == the
1964 // second field.
TEST(Eq2Test,MatchesEqualArguments)1965 TEST(Eq2Test, MatchesEqualArguments) {
1966   Matcher<const Tuple2&> m = Eq();
1967   EXPECT_TRUE(m.Matches(Tuple2(5L, 5)));
1968   EXPECT_FALSE(m.Matches(Tuple2(5L, 6)));
1969 }
1970 
1971 // Tests that Eq() describes itself properly.
TEST(Eq2Test,CanDescribeSelf)1972 TEST(Eq2Test, CanDescribeSelf) {
1973   Matcher<const Tuple2&> m = Eq();
1974   EXPECT_EQ("are an equal pair", Describe(m));
1975 }
1976 
1977 // Tests that Ge() matches a 2-tuple where the first field >= the
1978 // second field.
TEST(Ge2Test,MatchesGreaterThanOrEqualArguments)1979 TEST(Ge2Test, MatchesGreaterThanOrEqualArguments) {
1980   Matcher<const Tuple2&> m = Ge();
1981   EXPECT_TRUE(m.Matches(Tuple2(5L, 4)));
1982   EXPECT_TRUE(m.Matches(Tuple2(5L, 5)));
1983   EXPECT_FALSE(m.Matches(Tuple2(5L, 6)));
1984 }
1985 
1986 // Tests that Ge() describes itself properly.
TEST(Ge2Test,CanDescribeSelf)1987 TEST(Ge2Test, CanDescribeSelf) {
1988   Matcher<const Tuple2&> m = Ge();
1989   EXPECT_EQ("are a pair where the first >= the second", Describe(m));
1990 }
1991 
1992 // Tests that Gt() matches a 2-tuple where the first field > the
1993 // second field.
TEST(Gt2Test,MatchesGreaterThanArguments)1994 TEST(Gt2Test, MatchesGreaterThanArguments) {
1995   Matcher<const Tuple2&> m = Gt();
1996   EXPECT_TRUE(m.Matches(Tuple2(5L, 4)));
1997   EXPECT_FALSE(m.Matches(Tuple2(5L, 5)));
1998   EXPECT_FALSE(m.Matches(Tuple2(5L, 6)));
1999 }
2000 
2001 // Tests that Gt() describes itself properly.
TEST(Gt2Test,CanDescribeSelf)2002 TEST(Gt2Test, CanDescribeSelf) {
2003   Matcher<const Tuple2&> m = Gt();
2004   EXPECT_EQ("are a pair where the first > the second", Describe(m));
2005 }
2006 
2007 // Tests that Le() matches a 2-tuple where the first field <= the
2008 // second field.
TEST(Le2Test,MatchesLessThanOrEqualArguments)2009 TEST(Le2Test, MatchesLessThanOrEqualArguments) {
2010   Matcher<const Tuple2&> m = Le();
2011   EXPECT_TRUE(m.Matches(Tuple2(5L, 6)));
2012   EXPECT_TRUE(m.Matches(Tuple2(5L, 5)));
2013   EXPECT_FALSE(m.Matches(Tuple2(5L, 4)));
2014 }
2015 
2016 // Tests that Le() describes itself properly.
TEST(Le2Test,CanDescribeSelf)2017 TEST(Le2Test, CanDescribeSelf) {
2018   Matcher<const Tuple2&> m = Le();
2019   EXPECT_EQ("are a pair where the first <= the second", Describe(m));
2020 }
2021 
2022 // Tests that Lt() matches a 2-tuple where the first field < the
2023 // second field.
TEST(Lt2Test,MatchesLessThanArguments)2024 TEST(Lt2Test, MatchesLessThanArguments) {
2025   Matcher<const Tuple2&> m = Lt();
2026   EXPECT_TRUE(m.Matches(Tuple2(5L, 6)));
2027   EXPECT_FALSE(m.Matches(Tuple2(5L, 5)));
2028   EXPECT_FALSE(m.Matches(Tuple2(5L, 4)));
2029 }
2030 
2031 // Tests that Lt() describes itself properly.
TEST(Lt2Test,CanDescribeSelf)2032 TEST(Lt2Test, CanDescribeSelf) {
2033   Matcher<const Tuple2&> m = Lt();
2034   EXPECT_EQ("are a pair where the first < the second", Describe(m));
2035 }
2036 
2037 // Tests that Ne() matches a 2-tuple where the first field != the
2038 // second field.
TEST(Ne2Test,MatchesUnequalArguments)2039 TEST(Ne2Test, MatchesUnequalArguments) {
2040   Matcher<const Tuple2&> m = Ne();
2041   EXPECT_TRUE(m.Matches(Tuple2(5L, 6)));
2042   EXPECT_TRUE(m.Matches(Tuple2(5L, 4)));
2043   EXPECT_FALSE(m.Matches(Tuple2(5L, 5)));
2044 }
2045 
2046 // Tests that Ne() describes itself properly.
TEST(Ne2Test,CanDescribeSelf)2047 TEST(Ne2Test, CanDescribeSelf) {
2048   Matcher<const Tuple2&> m = Ne();
2049   EXPECT_EQ("are an unequal pair", Describe(m));
2050 }
2051 
TEST(PairMatchBaseTest,WorksWithMoveOnly)2052 TEST(PairMatchBaseTest, WorksWithMoveOnly) {
2053   using Pointers = std::tuple<std::unique_ptr<int>, std::unique_ptr<int>>;
2054   Matcher<Pointers> matcher = Eq();
2055   Pointers pointers;
2056   // Tested values don't matter; the point is that matcher does not copy the
2057   // matched values.
2058   EXPECT_TRUE(matcher.Matches(pointers));
2059 }
2060 
2061 // Tests that IsNan() matches a NaN, with float.
TEST(IsNan,FloatMatchesNan)2062 TEST(IsNan, FloatMatchesNan) {
2063   float quiet_nan = std::numeric_limits<float>::quiet_NaN();
2064   float other_nan = std::nanf("1");
2065   float real_value = 1.0f;
2066 
2067   Matcher<float> m = IsNan();
2068   EXPECT_TRUE(m.Matches(quiet_nan));
2069   EXPECT_TRUE(m.Matches(other_nan));
2070   EXPECT_FALSE(m.Matches(real_value));
2071 
2072   Matcher<float&> m_ref = IsNan();
2073   EXPECT_TRUE(m_ref.Matches(quiet_nan));
2074   EXPECT_TRUE(m_ref.Matches(other_nan));
2075   EXPECT_FALSE(m_ref.Matches(real_value));
2076 
2077   Matcher<const float&> m_cref = IsNan();
2078   EXPECT_TRUE(m_cref.Matches(quiet_nan));
2079   EXPECT_TRUE(m_cref.Matches(other_nan));
2080   EXPECT_FALSE(m_cref.Matches(real_value));
2081 }
2082 
2083 // Tests that IsNan() matches a NaN, with double.
TEST(IsNan,DoubleMatchesNan)2084 TEST(IsNan, DoubleMatchesNan) {
2085   double quiet_nan = std::numeric_limits<double>::quiet_NaN();
2086   double other_nan = std::nan("1");
2087   double real_value = 1.0;
2088 
2089   Matcher<double> m = IsNan();
2090   EXPECT_TRUE(m.Matches(quiet_nan));
2091   EXPECT_TRUE(m.Matches(other_nan));
2092   EXPECT_FALSE(m.Matches(real_value));
2093 
2094   Matcher<double&> m_ref = IsNan();
2095   EXPECT_TRUE(m_ref.Matches(quiet_nan));
2096   EXPECT_TRUE(m_ref.Matches(other_nan));
2097   EXPECT_FALSE(m_ref.Matches(real_value));
2098 
2099   Matcher<const double&> m_cref = IsNan();
2100   EXPECT_TRUE(m_cref.Matches(quiet_nan));
2101   EXPECT_TRUE(m_cref.Matches(other_nan));
2102   EXPECT_FALSE(m_cref.Matches(real_value));
2103 }
2104 
2105 // Tests that IsNan() matches a NaN, with long double.
TEST(IsNan,LongDoubleMatchesNan)2106 TEST(IsNan, LongDoubleMatchesNan) {
2107   long double quiet_nan = std::numeric_limits<long double>::quiet_NaN();
2108   long double other_nan = std::nan("1");
2109   long double real_value = 1.0;
2110 
2111   Matcher<long double> m = IsNan();
2112   EXPECT_TRUE(m.Matches(quiet_nan));
2113   EXPECT_TRUE(m.Matches(other_nan));
2114   EXPECT_FALSE(m.Matches(real_value));
2115 
2116   Matcher<long double&> m_ref = IsNan();
2117   EXPECT_TRUE(m_ref.Matches(quiet_nan));
2118   EXPECT_TRUE(m_ref.Matches(other_nan));
2119   EXPECT_FALSE(m_ref.Matches(real_value));
2120 
2121   Matcher<const long double&> m_cref = IsNan();
2122   EXPECT_TRUE(m_cref.Matches(quiet_nan));
2123   EXPECT_TRUE(m_cref.Matches(other_nan));
2124   EXPECT_FALSE(m_cref.Matches(real_value));
2125 }
2126 
2127 // Tests that IsNan() works with Not.
TEST(IsNan,NotMatchesNan)2128 TEST(IsNan, NotMatchesNan) {
2129   Matcher<float> mf = Not(IsNan());
2130   EXPECT_FALSE(mf.Matches(std::numeric_limits<float>::quiet_NaN()));
2131   EXPECT_FALSE(mf.Matches(std::nanf("1")));
2132   EXPECT_TRUE(mf.Matches(1.0));
2133 
2134   Matcher<double> md = Not(IsNan());
2135   EXPECT_FALSE(md.Matches(std::numeric_limits<double>::quiet_NaN()));
2136   EXPECT_FALSE(md.Matches(std::nan("1")));
2137   EXPECT_TRUE(md.Matches(1.0));
2138 
2139   Matcher<long double> mld = Not(IsNan());
2140   EXPECT_FALSE(mld.Matches(std::numeric_limits<long double>::quiet_NaN()));
2141   EXPECT_FALSE(mld.Matches(std::nanl("1")));
2142   EXPECT_TRUE(mld.Matches(1.0));
2143 }
2144 
2145 // Tests that IsNan() can describe itself.
TEST(IsNan,CanDescribeSelf)2146 TEST(IsNan, CanDescribeSelf) {
2147   Matcher<float> mf = IsNan();
2148   EXPECT_EQ("is NaN", Describe(mf));
2149 
2150   Matcher<double> md = IsNan();
2151   EXPECT_EQ("is NaN", Describe(md));
2152 
2153   Matcher<long double> mld = IsNan();
2154   EXPECT_EQ("is NaN", Describe(mld));
2155 }
2156 
2157 // Tests that IsNan() can describe itself with Not.
TEST(IsNan,CanDescribeSelfWithNot)2158 TEST(IsNan, CanDescribeSelfWithNot) {
2159   Matcher<float> mf = Not(IsNan());
2160   EXPECT_EQ("isn't NaN", Describe(mf));
2161 
2162   Matcher<double> md = Not(IsNan());
2163   EXPECT_EQ("isn't NaN", Describe(md));
2164 
2165   Matcher<long double> mld = Not(IsNan());
2166   EXPECT_EQ("isn't NaN", Describe(mld));
2167 }
2168 
2169 // Tests that FloatEq() matches a 2-tuple where
2170 // FloatEq(first field) matches the second field.
TEST(FloatEq2Test,MatchesEqualArguments)2171 TEST(FloatEq2Test, MatchesEqualArguments) {
2172   typedef ::std::tuple<float, float> Tpl;
2173   Matcher<const Tpl&> m = FloatEq();
2174   EXPECT_TRUE(m.Matches(Tpl(1.0f, 1.0f)));
2175   EXPECT_TRUE(m.Matches(Tpl(0.3f, 0.1f + 0.1f + 0.1f)));
2176   EXPECT_FALSE(m.Matches(Tpl(1.1f, 1.0f)));
2177 }
2178 
2179 // Tests that FloatEq() describes itself properly.
TEST(FloatEq2Test,CanDescribeSelf)2180 TEST(FloatEq2Test, CanDescribeSelf) {
2181   Matcher<const ::std::tuple<float, float>&> m = FloatEq();
2182   EXPECT_EQ("are an almost-equal pair", Describe(m));
2183 }
2184 
2185 // Tests that NanSensitiveFloatEq() matches a 2-tuple where
2186 // NanSensitiveFloatEq(first field) matches the second field.
TEST(NanSensitiveFloatEqTest,MatchesEqualArgumentsWithNaN)2187 TEST(NanSensitiveFloatEqTest, MatchesEqualArgumentsWithNaN) {
2188   typedef ::std::tuple<float, float> Tpl;
2189   Matcher<const Tpl&> m = NanSensitiveFloatEq();
2190   EXPECT_TRUE(m.Matches(Tpl(1.0f, 1.0f)));
2191   EXPECT_TRUE(m.Matches(Tpl(std::numeric_limits<float>::quiet_NaN(),
2192                             std::numeric_limits<float>::quiet_NaN())));
2193   EXPECT_FALSE(m.Matches(Tpl(1.1f, 1.0f)));
2194   EXPECT_FALSE(m.Matches(Tpl(1.0f, std::numeric_limits<float>::quiet_NaN())));
2195   EXPECT_FALSE(m.Matches(Tpl(std::numeric_limits<float>::quiet_NaN(), 1.0f)));
2196 }
2197 
2198 // Tests that NanSensitiveFloatEq() describes itself properly.
TEST(NanSensitiveFloatEqTest,CanDescribeSelfWithNaNs)2199 TEST(NanSensitiveFloatEqTest, CanDescribeSelfWithNaNs) {
2200   Matcher<const ::std::tuple<float, float>&> m = NanSensitiveFloatEq();
2201   EXPECT_EQ("are an almost-equal pair", Describe(m));
2202 }
2203 
2204 // Tests that DoubleEq() matches a 2-tuple where
2205 // DoubleEq(first field) matches the second field.
TEST(DoubleEq2Test,MatchesEqualArguments)2206 TEST(DoubleEq2Test, MatchesEqualArguments) {
2207   typedef ::std::tuple<double, double> Tpl;
2208   Matcher<const Tpl&> m = DoubleEq();
2209   EXPECT_TRUE(m.Matches(Tpl(1.0, 1.0)));
2210   EXPECT_TRUE(m.Matches(Tpl(0.3, 0.1 + 0.1 + 0.1)));
2211   EXPECT_FALSE(m.Matches(Tpl(1.1, 1.0)));
2212 }
2213 
2214 // Tests that DoubleEq() describes itself properly.
TEST(DoubleEq2Test,CanDescribeSelf)2215 TEST(DoubleEq2Test, CanDescribeSelf) {
2216   Matcher<const ::std::tuple<double, double>&> m = DoubleEq();
2217   EXPECT_EQ("are an almost-equal pair", Describe(m));
2218 }
2219 
2220 // Tests that NanSensitiveDoubleEq() matches a 2-tuple where
2221 // NanSensitiveDoubleEq(first field) matches the second field.
TEST(NanSensitiveDoubleEqTest,MatchesEqualArgumentsWithNaN)2222 TEST(NanSensitiveDoubleEqTest, MatchesEqualArgumentsWithNaN) {
2223   typedef ::std::tuple<double, double> Tpl;
2224   Matcher<const Tpl&> m = NanSensitiveDoubleEq();
2225   EXPECT_TRUE(m.Matches(Tpl(1.0f, 1.0f)));
2226   EXPECT_TRUE(m.Matches(Tpl(std::numeric_limits<double>::quiet_NaN(),
2227                             std::numeric_limits<double>::quiet_NaN())));
2228   EXPECT_FALSE(m.Matches(Tpl(1.1f, 1.0f)));
2229   EXPECT_FALSE(m.Matches(Tpl(1.0f, std::numeric_limits<double>::quiet_NaN())));
2230   EXPECT_FALSE(m.Matches(Tpl(std::numeric_limits<double>::quiet_NaN(), 1.0f)));
2231 }
2232 
2233 // Tests that DoubleEq() describes itself properly.
TEST(NanSensitiveDoubleEqTest,CanDescribeSelfWithNaNs)2234 TEST(NanSensitiveDoubleEqTest, CanDescribeSelfWithNaNs) {
2235   Matcher<const ::std::tuple<double, double>&> m = NanSensitiveDoubleEq();
2236   EXPECT_EQ("are an almost-equal pair", Describe(m));
2237 }
2238 
2239 // Tests that FloatEq() matches a 2-tuple where
2240 // FloatNear(first field, max_abs_error) matches the second field.
TEST(FloatNear2Test,MatchesEqualArguments)2241 TEST(FloatNear2Test, MatchesEqualArguments) {
2242   typedef ::std::tuple<float, float> Tpl;
2243   Matcher<const Tpl&> m = FloatNear(0.5f);
2244   EXPECT_TRUE(m.Matches(Tpl(1.0f, 1.0f)));
2245   EXPECT_TRUE(m.Matches(Tpl(1.3f, 1.0f)));
2246   EXPECT_FALSE(m.Matches(Tpl(1.8f, 1.0f)));
2247 }
2248 
2249 // Tests that FloatNear() describes itself properly.
TEST(FloatNear2Test,CanDescribeSelf)2250 TEST(FloatNear2Test, CanDescribeSelf) {
2251   Matcher<const ::std::tuple<float, float>&> m = FloatNear(0.5f);
2252   EXPECT_EQ("are an almost-equal pair", Describe(m));
2253 }
2254 
2255 // Tests that NanSensitiveFloatNear() matches a 2-tuple where
2256 // NanSensitiveFloatNear(first field) matches the second field.
TEST(NanSensitiveFloatNearTest,MatchesNearbyArgumentsWithNaN)2257 TEST(NanSensitiveFloatNearTest, MatchesNearbyArgumentsWithNaN) {
2258   typedef ::std::tuple<float, float> Tpl;
2259   Matcher<const Tpl&> m = NanSensitiveFloatNear(0.5f);
2260   EXPECT_TRUE(m.Matches(Tpl(1.0f, 1.0f)));
2261   EXPECT_TRUE(m.Matches(Tpl(1.1f, 1.0f)));
2262   EXPECT_TRUE(m.Matches(Tpl(std::numeric_limits<float>::quiet_NaN(),
2263                             std::numeric_limits<float>::quiet_NaN())));
2264   EXPECT_FALSE(m.Matches(Tpl(1.6f, 1.0f)));
2265   EXPECT_FALSE(m.Matches(Tpl(1.0f, std::numeric_limits<float>::quiet_NaN())));
2266   EXPECT_FALSE(m.Matches(Tpl(std::numeric_limits<float>::quiet_NaN(), 1.0f)));
2267 }
2268 
2269 // Tests that NanSensitiveFloatNear() describes itself properly.
TEST(NanSensitiveFloatNearTest,CanDescribeSelfWithNaNs)2270 TEST(NanSensitiveFloatNearTest, CanDescribeSelfWithNaNs) {
2271   Matcher<const ::std::tuple<float, float>&> m = NanSensitiveFloatNear(0.5f);
2272   EXPECT_EQ("are an almost-equal pair", Describe(m));
2273 }
2274 
2275 // Tests that FloatEq() matches a 2-tuple where
2276 // DoubleNear(first field, max_abs_error) matches the second field.
TEST(DoubleNear2Test,MatchesEqualArguments)2277 TEST(DoubleNear2Test, MatchesEqualArguments) {
2278   typedef ::std::tuple<double, double> Tpl;
2279   Matcher<const Tpl&> m = DoubleNear(0.5);
2280   EXPECT_TRUE(m.Matches(Tpl(1.0, 1.0)));
2281   EXPECT_TRUE(m.Matches(Tpl(1.3, 1.0)));
2282   EXPECT_FALSE(m.Matches(Tpl(1.8, 1.0)));
2283 }
2284 
2285 // Tests that DoubleNear() describes itself properly.
TEST(DoubleNear2Test,CanDescribeSelf)2286 TEST(DoubleNear2Test, CanDescribeSelf) {
2287   Matcher<const ::std::tuple<double, double>&> m = DoubleNear(0.5);
2288   EXPECT_EQ("are an almost-equal pair", Describe(m));
2289 }
2290 
2291 // Tests that NanSensitiveDoubleNear() matches a 2-tuple where
2292 // NanSensitiveDoubleNear(first field) matches the second field.
TEST(NanSensitiveDoubleNearTest,MatchesNearbyArgumentsWithNaN)2293 TEST(NanSensitiveDoubleNearTest, MatchesNearbyArgumentsWithNaN) {
2294   typedef ::std::tuple<double, double> Tpl;
2295   Matcher<const Tpl&> m = NanSensitiveDoubleNear(0.5f);
2296   EXPECT_TRUE(m.Matches(Tpl(1.0f, 1.0f)));
2297   EXPECT_TRUE(m.Matches(Tpl(1.1f, 1.0f)));
2298   EXPECT_TRUE(m.Matches(Tpl(std::numeric_limits<double>::quiet_NaN(),
2299                             std::numeric_limits<double>::quiet_NaN())));
2300   EXPECT_FALSE(m.Matches(Tpl(1.6f, 1.0f)));
2301   EXPECT_FALSE(m.Matches(Tpl(1.0f, std::numeric_limits<double>::quiet_NaN())));
2302   EXPECT_FALSE(m.Matches(Tpl(std::numeric_limits<double>::quiet_NaN(), 1.0f)));
2303 }
2304 
2305 // Tests that NanSensitiveDoubleNear() describes itself properly.
TEST(NanSensitiveDoubleNearTest,CanDescribeSelfWithNaNs)2306 TEST(NanSensitiveDoubleNearTest, CanDescribeSelfWithNaNs) {
2307   Matcher<const ::std::tuple<double, double>&> m = NanSensitiveDoubleNear(0.5f);
2308   EXPECT_EQ("are an almost-equal pair", Describe(m));
2309 }
2310 
2311 // Tests that Not(m) matches any value that doesn't match m.
TEST(NotTest,NegatesMatcher)2312 TEST(NotTest, NegatesMatcher) {
2313   Matcher<int> m;
2314   m = Not(Eq(2));
2315   EXPECT_TRUE(m.Matches(3));
2316   EXPECT_FALSE(m.Matches(2));
2317 }
2318 
2319 // Tests that Not(m) describes itself properly.
TEST(NotTest,CanDescribeSelf)2320 TEST(NotTest, CanDescribeSelf) {
2321   Matcher<int> m = Not(Eq(5));
2322   EXPECT_EQ("isn't equal to 5", Describe(m));
2323 }
2324 
2325 // Tests that monomorphic matchers are safely cast by the Not matcher.
TEST(NotTest,NotMatcherSafelyCastsMonomorphicMatchers)2326 TEST(NotTest, NotMatcherSafelyCastsMonomorphicMatchers) {
2327   // greater_than_5 is a monomorphic matcher.
2328   Matcher<int> greater_than_5 = Gt(5);
2329 
2330   Matcher<const int&> m = Not(greater_than_5);
2331   Matcher<int&> m2 = Not(greater_than_5);
2332   Matcher<int&> m3 = Not(m);
2333 }
2334 
2335 // Helper to allow easy testing of AllOf matchers with num parameters.
AllOfMatches(int num,const Matcher<int> & m)2336 void AllOfMatches(int num, const Matcher<int>& m) {
2337   SCOPED_TRACE(Describe(m));
2338   EXPECT_TRUE(m.Matches(0));
2339   for (int i = 1; i <= num; ++i) {
2340     EXPECT_FALSE(m.Matches(i));
2341   }
2342   EXPECT_TRUE(m.Matches(num + 1));
2343 }
2344 
2345 // Tests that AllOf(m1, ..., mn) matches any value that matches all of
2346 // the given matchers.
TEST(AllOfTest,MatchesWhenAllMatch)2347 TEST(AllOfTest, MatchesWhenAllMatch) {
2348   Matcher<int> m;
2349   m = AllOf(Le(2), Ge(1));
2350   EXPECT_TRUE(m.Matches(1));
2351   EXPECT_TRUE(m.Matches(2));
2352   EXPECT_FALSE(m.Matches(0));
2353   EXPECT_FALSE(m.Matches(3));
2354 
2355   m = AllOf(Gt(0), Ne(1), Ne(2));
2356   EXPECT_TRUE(m.Matches(3));
2357   EXPECT_FALSE(m.Matches(2));
2358   EXPECT_FALSE(m.Matches(1));
2359   EXPECT_FALSE(m.Matches(0));
2360 
2361   m = AllOf(Gt(0), Ne(1), Ne(2), Ne(3));
2362   EXPECT_TRUE(m.Matches(4));
2363   EXPECT_FALSE(m.Matches(3));
2364   EXPECT_FALSE(m.Matches(2));
2365   EXPECT_FALSE(m.Matches(1));
2366   EXPECT_FALSE(m.Matches(0));
2367 
2368   m = AllOf(Ge(0), Lt(10), Ne(3), Ne(5), Ne(7));
2369   EXPECT_TRUE(m.Matches(0));
2370   EXPECT_TRUE(m.Matches(1));
2371   EXPECT_FALSE(m.Matches(3));
2372 
2373   // The following tests for varying number of sub-matchers. Due to the way
2374   // the sub-matchers are handled it is enough to test every sub-matcher once
2375   // with sub-matchers using the same matcher type. Varying matcher types are
2376   // checked for above.
2377   AllOfMatches(2, AllOf(Ne(1), Ne(2)));
2378   AllOfMatches(3, AllOf(Ne(1), Ne(2), Ne(3)));
2379   AllOfMatches(4, AllOf(Ne(1), Ne(2), Ne(3), Ne(4)));
2380   AllOfMatches(5, AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5)));
2381   AllOfMatches(6, AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5), Ne(6)));
2382   AllOfMatches(7, AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5), Ne(6), Ne(7)));
2383   AllOfMatches(8, AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5), Ne(6), Ne(7),
2384                         Ne(8)));
2385   AllOfMatches(9, AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5), Ne(6), Ne(7),
2386                         Ne(8), Ne(9)));
2387   AllOfMatches(10, AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5), Ne(6), Ne(7), Ne(8),
2388                          Ne(9), Ne(10)));
2389   AllOfMatches(
2390       50, AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5), Ne(6), Ne(7), Ne(8), Ne(9),
2391                 Ne(10), Ne(11), Ne(12), Ne(13), Ne(14), Ne(15), Ne(16), Ne(17),
2392                 Ne(18), Ne(19), Ne(20), Ne(21), Ne(22), Ne(23), Ne(24), Ne(25),
2393                 Ne(26), Ne(27), Ne(28), Ne(29), Ne(30), Ne(31), Ne(32), Ne(33),
2394                 Ne(34), Ne(35), Ne(36), Ne(37), Ne(38), Ne(39), Ne(40), Ne(41),
2395                 Ne(42), Ne(43), Ne(44), Ne(45), Ne(46), Ne(47), Ne(48), Ne(49),
2396                 Ne(50)));
2397 }
2398 
2399 
2400 // Tests that AllOf(m1, ..., mn) describes itself properly.
TEST(AllOfTest,CanDescribeSelf)2401 TEST(AllOfTest, CanDescribeSelf) {
2402   Matcher<int> m;
2403   m = AllOf(Le(2), Ge(1));
2404   EXPECT_EQ("(is <= 2) and (is >= 1)", Describe(m));
2405 
2406   m = AllOf(Gt(0), Ne(1), Ne(2));
2407   std::string expected_descr1 =
2408       "(is > 0) and (isn't equal to 1) and (isn't equal to 2)";
2409   EXPECT_EQ(expected_descr1, Describe(m));
2410 
2411   m = AllOf(Gt(0), Ne(1), Ne(2), Ne(3));
2412   std::string expected_descr2 =
2413       "(is > 0) and (isn't equal to 1) and (isn't equal to 2) and (isn't equal "
2414       "to 3)";
2415   EXPECT_EQ(expected_descr2, Describe(m));
2416 
2417   m = AllOf(Ge(0), Lt(10), Ne(3), Ne(5), Ne(7));
2418   std::string expected_descr3 =
2419       "(is >= 0) and (is < 10) and (isn't equal to 3) and (isn't equal to 5) "
2420       "and (isn't equal to 7)";
2421   EXPECT_EQ(expected_descr3, Describe(m));
2422 }
2423 
2424 // Tests that AllOf(m1, ..., mn) describes its negation properly.
TEST(AllOfTest,CanDescribeNegation)2425 TEST(AllOfTest, CanDescribeNegation) {
2426   Matcher<int> m;
2427   m = AllOf(Le(2), Ge(1));
2428   std::string expected_descr4 = "(isn't <= 2) or (isn't >= 1)";
2429   EXPECT_EQ(expected_descr4, DescribeNegation(m));
2430 
2431   m = AllOf(Gt(0), Ne(1), Ne(2));
2432   std::string expected_descr5 =
2433       "(isn't > 0) or (is equal to 1) or (is equal to 2)";
2434   EXPECT_EQ(expected_descr5, DescribeNegation(m));
2435 
2436   m = AllOf(Gt(0), Ne(1), Ne(2), Ne(3));
2437   std::string expected_descr6 =
2438       "(isn't > 0) or (is equal to 1) or (is equal to 2) or (is equal to 3)";
2439   EXPECT_EQ(expected_descr6, DescribeNegation(m));
2440 
2441   m = AllOf(Ge(0), Lt(10), Ne(3), Ne(5), Ne(7));
2442   std::string expected_desr7 =
2443       "(isn't >= 0) or (isn't < 10) or (is equal to 3) or (is equal to 5) or "
2444       "(is equal to 7)";
2445   EXPECT_EQ(expected_desr7, DescribeNegation(m));
2446 
2447   m = AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5), Ne(6), Ne(7), Ne(8), Ne(9),
2448             Ne(10), Ne(11));
2449   AllOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11);
2450   EXPECT_THAT(Describe(m), EndsWith("and (isn't equal to 11)"));
2451   AllOfMatches(11, m);
2452 }
2453 
2454 // Tests that monomorphic matchers are safely cast by the AllOf matcher.
TEST(AllOfTest,AllOfMatcherSafelyCastsMonomorphicMatchers)2455 TEST(AllOfTest, AllOfMatcherSafelyCastsMonomorphicMatchers) {
2456   // greater_than_5 and less_than_10 are monomorphic matchers.
2457   Matcher<int> greater_than_5 = Gt(5);
2458   Matcher<int> less_than_10 = Lt(10);
2459 
2460   Matcher<const int&> m = AllOf(greater_than_5, less_than_10);
2461   Matcher<int&> m2 = AllOf(greater_than_5, less_than_10);
2462   Matcher<int&> m3 = AllOf(greater_than_5, m2);
2463 
2464   // Tests that BothOf works when composing itself.
2465   Matcher<const int&> m4 = AllOf(greater_than_5, less_than_10, less_than_10);
2466   Matcher<int&> m5 = AllOf(greater_than_5, less_than_10, less_than_10);
2467 }
2468 
TEST(AllOfTest,ExplainsResult)2469 TEST(AllOfTest, ExplainsResult) {
2470   Matcher<int> m;
2471 
2472   // Successful match.  Both matchers need to explain.  The second
2473   // matcher doesn't give an explanation, so only the first matcher's
2474   // explanation is printed.
2475   m = AllOf(GreaterThan(10), Lt(30));
2476   EXPECT_EQ("which is 15 more than 10", Explain(m, 25));
2477 
2478   // Successful match.  Both matchers need to explain.
2479   m = AllOf(GreaterThan(10), GreaterThan(20));
2480   EXPECT_EQ("which is 20 more than 10, and which is 10 more than 20",
2481             Explain(m, 30));
2482 
2483   // Successful match.  All matchers need to explain.  The second
2484   // matcher doesn't given an explanation.
2485   m = AllOf(GreaterThan(10), Lt(30), GreaterThan(20));
2486   EXPECT_EQ("which is 15 more than 10, and which is 5 more than 20",
2487             Explain(m, 25));
2488 
2489   // Successful match.  All matchers need to explain.
2490   m = AllOf(GreaterThan(10), GreaterThan(20), GreaterThan(30));
2491   EXPECT_EQ("which is 30 more than 10, and which is 20 more than 20, "
2492             "and which is 10 more than 30",
2493             Explain(m, 40));
2494 
2495   // Failed match.  The first matcher, which failed, needs to
2496   // explain.
2497   m = AllOf(GreaterThan(10), GreaterThan(20));
2498   EXPECT_EQ("which is 5 less than 10", Explain(m, 5));
2499 
2500   // Failed match.  The second matcher, which failed, needs to
2501   // explain.  Since it doesn't given an explanation, nothing is
2502   // printed.
2503   m = AllOf(GreaterThan(10), Lt(30));
2504   EXPECT_EQ("", Explain(m, 40));
2505 
2506   // Failed match.  The second matcher, which failed, needs to
2507   // explain.
2508   m = AllOf(GreaterThan(10), GreaterThan(20));
2509   EXPECT_EQ("which is 5 less than 20", Explain(m, 15));
2510 }
2511 
2512 // Helper to allow easy testing of AnyOf matchers with num parameters.
AnyOfMatches(int num,const Matcher<int> & m)2513 static void AnyOfMatches(int num, const Matcher<int>& m) {
2514   SCOPED_TRACE(Describe(m));
2515   EXPECT_FALSE(m.Matches(0));
2516   for (int i = 1; i <= num; ++i) {
2517     EXPECT_TRUE(m.Matches(i));
2518   }
2519   EXPECT_FALSE(m.Matches(num + 1));
2520 }
2521 
AnyOfStringMatches(int num,const Matcher<std::string> & m)2522 static void AnyOfStringMatches(int num, const Matcher<std::string>& m) {
2523   SCOPED_TRACE(Describe(m));
2524   EXPECT_FALSE(m.Matches(std::to_string(0)));
2525 
2526   for (int i = 1; i <= num; ++i) {
2527     EXPECT_TRUE(m.Matches(std::to_string(i)));
2528   }
2529   EXPECT_FALSE(m.Matches(std::to_string(num + 1)));
2530 }
2531 
2532 // Tests that AnyOf(m1, ..., mn) matches any value that matches at
2533 // least one of the given matchers.
TEST(AnyOfTest,MatchesWhenAnyMatches)2534 TEST(AnyOfTest, MatchesWhenAnyMatches) {
2535   Matcher<int> m;
2536   m = AnyOf(Le(1), Ge(3));
2537   EXPECT_TRUE(m.Matches(1));
2538   EXPECT_TRUE(m.Matches(4));
2539   EXPECT_FALSE(m.Matches(2));
2540 
2541   m = AnyOf(Lt(0), Eq(1), Eq(2));
2542   EXPECT_TRUE(m.Matches(-1));
2543   EXPECT_TRUE(m.Matches(1));
2544   EXPECT_TRUE(m.Matches(2));
2545   EXPECT_FALSE(m.Matches(0));
2546 
2547   m = AnyOf(Lt(0), Eq(1), Eq(2), Eq(3));
2548   EXPECT_TRUE(m.Matches(-1));
2549   EXPECT_TRUE(m.Matches(1));
2550   EXPECT_TRUE(m.Matches(2));
2551   EXPECT_TRUE(m.Matches(3));
2552   EXPECT_FALSE(m.Matches(0));
2553 
2554   m = AnyOf(Le(0), Gt(10), 3, 5, 7);
2555   EXPECT_TRUE(m.Matches(0));
2556   EXPECT_TRUE(m.Matches(11));
2557   EXPECT_TRUE(m.Matches(3));
2558   EXPECT_FALSE(m.Matches(2));
2559 
2560   // The following tests for varying number of sub-matchers. Due to the way
2561   // the sub-matchers are handled it is enough to test every sub-matcher once
2562   // with sub-matchers using the same matcher type. Varying matcher types are
2563   // checked for above.
2564   AnyOfMatches(2, AnyOf(1, 2));
2565   AnyOfMatches(3, AnyOf(1, 2, 3));
2566   AnyOfMatches(4, AnyOf(1, 2, 3, 4));
2567   AnyOfMatches(5, AnyOf(1, 2, 3, 4, 5));
2568   AnyOfMatches(6, AnyOf(1, 2, 3, 4, 5, 6));
2569   AnyOfMatches(7, AnyOf(1, 2, 3, 4, 5, 6, 7));
2570   AnyOfMatches(8, AnyOf(1, 2, 3, 4, 5, 6, 7, 8));
2571   AnyOfMatches(9, AnyOf(1, 2, 3, 4, 5, 6, 7, 8, 9));
2572   AnyOfMatches(10, AnyOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10));
2573 }
2574 
2575 // Tests the variadic version of the AnyOfMatcher.
TEST(AnyOfTest,VariadicMatchesWhenAnyMatches)2576 TEST(AnyOfTest, VariadicMatchesWhenAnyMatches) {
2577   // Also make sure AnyOf is defined in the right namespace and does not depend
2578   // on ADL.
2579   Matcher<int> m = ::testing::AnyOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11);
2580 
2581   EXPECT_THAT(Describe(m), EndsWith("or (is equal to 11)"));
2582   AnyOfMatches(11, m);
2583   AnyOfMatches(50, AnyOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
2584                          11, 12, 13, 14, 15, 16, 17, 18, 19, 20,
2585                          21, 22, 23, 24, 25, 26, 27, 28, 29, 30,
2586                          31, 32, 33, 34, 35, 36, 37, 38, 39, 40,
2587                          41, 42, 43, 44, 45, 46, 47, 48, 49, 50));
2588   AnyOfStringMatches(
2589       50, AnyOf("1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12",
2590                 "13", "14", "15", "16", "17", "18", "19", "20", "21", "22",
2591                 "23", "24", "25", "26", "27", "28", "29", "30", "31", "32",
2592                 "33", "34", "35", "36", "37", "38", "39", "40", "41", "42",
2593                 "43", "44", "45", "46", "47", "48", "49", "50"));
2594 }
2595 
2596 // Tests the variadic version of the ElementsAreMatcher
TEST(ElementsAreTest,HugeMatcher)2597 TEST(ElementsAreTest, HugeMatcher) {
2598   vector<int> test_vector{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12};
2599 
2600   EXPECT_THAT(test_vector,
2601               ElementsAre(Eq(1), Eq(2), Lt(13), Eq(4), Eq(5), Eq(6), Eq(7),
2602                           Eq(8), Eq(9), Eq(10), Gt(1), Eq(12)));
2603 }
2604 
2605 // Tests the variadic version of the UnorderedElementsAreMatcher
TEST(ElementsAreTest,HugeMatcherStr)2606 TEST(ElementsAreTest, HugeMatcherStr) {
2607   vector<std::string> test_vector{
2608       "literal_string", "", "", "", "", "", "", "", "", "", "", ""};
2609 
2610   EXPECT_THAT(test_vector, UnorderedElementsAre("literal_string", _, _, _, _, _,
2611                                                 _, _, _, _, _, _));
2612 }
2613 
2614 // Tests the variadic version of the UnorderedElementsAreMatcher
TEST(ElementsAreTest,HugeMatcherUnordered)2615 TEST(ElementsAreTest, HugeMatcherUnordered) {
2616   vector<int> test_vector{2, 1, 8, 5, 4, 6, 7, 3, 9, 12, 11, 10};
2617 
2618   EXPECT_THAT(test_vector, UnorderedElementsAre(
2619                                Eq(2), Eq(1), Gt(7), Eq(5), Eq(4), Eq(6), Eq(7),
2620                                Eq(3), Eq(9), Eq(12), Eq(11), Ne(122)));
2621 }
2622 
2623 
2624 // Tests that AnyOf(m1, ..., mn) describes itself properly.
TEST(AnyOfTest,CanDescribeSelf)2625 TEST(AnyOfTest, CanDescribeSelf) {
2626   Matcher<int> m;
2627   m = AnyOf(Le(1), Ge(3));
2628 
2629   EXPECT_EQ("(is <= 1) or (is >= 3)",
2630             Describe(m));
2631 
2632   m = AnyOf(Lt(0), Eq(1), Eq(2));
2633   EXPECT_EQ("(is < 0) or (is equal to 1) or (is equal to 2)", Describe(m));
2634 
2635   m = AnyOf(Lt(0), Eq(1), Eq(2), Eq(3));
2636   EXPECT_EQ("(is < 0) or (is equal to 1) or (is equal to 2) or (is equal to 3)",
2637             Describe(m));
2638 
2639   m = AnyOf(Le(0), Gt(10), 3, 5, 7);
2640   EXPECT_EQ(
2641       "(is <= 0) or (is > 10) or (is equal to 3) or (is equal to 5) or (is "
2642       "equal to 7)",
2643       Describe(m));
2644 }
2645 
2646 // Tests that AnyOf(m1, ..., mn) describes its negation properly.
TEST(AnyOfTest,CanDescribeNegation)2647 TEST(AnyOfTest, CanDescribeNegation) {
2648   Matcher<int> m;
2649   m = AnyOf(Le(1), Ge(3));
2650   EXPECT_EQ("(isn't <= 1) and (isn't >= 3)",
2651             DescribeNegation(m));
2652 
2653   m = AnyOf(Lt(0), Eq(1), Eq(2));
2654   EXPECT_EQ("(isn't < 0) and (isn't equal to 1) and (isn't equal to 2)",
2655             DescribeNegation(m));
2656 
2657   m = AnyOf(Lt(0), Eq(1), Eq(2), Eq(3));
2658   EXPECT_EQ(
2659       "(isn't < 0) and (isn't equal to 1) and (isn't equal to 2) and (isn't "
2660       "equal to 3)",
2661       DescribeNegation(m));
2662 
2663   m = AnyOf(Le(0), Gt(10), 3, 5, 7);
2664   EXPECT_EQ(
2665       "(isn't <= 0) and (isn't > 10) and (isn't equal to 3) and (isn't equal "
2666       "to 5) and (isn't equal to 7)",
2667       DescribeNegation(m));
2668 }
2669 
2670 // Tests that monomorphic matchers are safely cast by the AnyOf matcher.
TEST(AnyOfTest,AnyOfMatcherSafelyCastsMonomorphicMatchers)2671 TEST(AnyOfTest, AnyOfMatcherSafelyCastsMonomorphicMatchers) {
2672   // greater_than_5 and less_than_10 are monomorphic matchers.
2673   Matcher<int> greater_than_5 = Gt(5);
2674   Matcher<int> less_than_10 = Lt(10);
2675 
2676   Matcher<const int&> m = AnyOf(greater_than_5, less_than_10);
2677   Matcher<int&> m2 = AnyOf(greater_than_5, less_than_10);
2678   Matcher<int&> m3 = AnyOf(greater_than_5, m2);
2679 
2680   // Tests that EitherOf works when composing itself.
2681   Matcher<const int&> m4 = AnyOf(greater_than_5, less_than_10, less_than_10);
2682   Matcher<int&> m5 = AnyOf(greater_than_5, less_than_10, less_than_10);
2683 }
2684 
TEST(AnyOfTest,ExplainsResult)2685 TEST(AnyOfTest, ExplainsResult) {
2686   Matcher<int> m;
2687 
2688   // Failed match.  Both matchers need to explain.  The second
2689   // matcher doesn't give an explanation, so only the first matcher's
2690   // explanation is printed.
2691   m = AnyOf(GreaterThan(10), Lt(0));
2692   EXPECT_EQ("which is 5 less than 10", Explain(m, 5));
2693 
2694   // Failed match.  Both matchers need to explain.
2695   m = AnyOf(GreaterThan(10), GreaterThan(20));
2696   EXPECT_EQ("which is 5 less than 10, and which is 15 less than 20",
2697             Explain(m, 5));
2698 
2699   // Failed match.  All matchers need to explain.  The second
2700   // matcher doesn't given an explanation.
2701   m = AnyOf(GreaterThan(10), Gt(20), GreaterThan(30));
2702   EXPECT_EQ("which is 5 less than 10, and which is 25 less than 30",
2703             Explain(m, 5));
2704 
2705   // Failed match.  All matchers need to explain.
2706   m = AnyOf(GreaterThan(10), GreaterThan(20), GreaterThan(30));
2707   EXPECT_EQ("which is 5 less than 10, and which is 15 less than 20, "
2708             "and which is 25 less than 30",
2709             Explain(m, 5));
2710 
2711   // Successful match.  The first matcher, which succeeded, needs to
2712   // explain.
2713   m = AnyOf(GreaterThan(10), GreaterThan(20));
2714   EXPECT_EQ("which is 5 more than 10", Explain(m, 15));
2715 
2716   // Successful match.  The second matcher, which succeeded, needs to
2717   // explain.  Since it doesn't given an explanation, nothing is
2718   // printed.
2719   m = AnyOf(GreaterThan(10), Lt(30));
2720   EXPECT_EQ("", Explain(m, 0));
2721 
2722   // Successful match.  The second matcher, which succeeded, needs to
2723   // explain.
2724   m = AnyOf(GreaterThan(30), GreaterThan(20));
2725   EXPECT_EQ("which is 5 more than 20", Explain(m, 25));
2726 }
2727 
2728 // The following predicate function and predicate functor are for
2729 // testing the Truly(predicate) matcher.
2730 
2731 // Returns non-zero if the input is positive.  Note that the return
2732 // type of this function is not bool.  It's OK as Truly() accepts any
2733 // unary function or functor whose return type can be implicitly
2734 // converted to bool.
IsPositive(double x)2735 int IsPositive(double x) {
2736   return x > 0 ? 1 : 0;
2737 }
2738 
2739 // This functor returns true if the input is greater than the given
2740 // number.
2741 class IsGreaterThan {
2742  public:
IsGreaterThan(int threshold)2743   explicit IsGreaterThan(int threshold) : threshold_(threshold) {}
2744 
operator ()(int n) const2745   bool operator()(int n) const { return n > threshold_; }
2746 
2747  private:
2748   int threshold_;
2749 };
2750 
2751 // For testing Truly().
2752 const int foo = 0;
2753 
2754 // This predicate returns true if and only if the argument references foo and
2755 // has a zero value.
ReferencesFooAndIsZero(const int & n)2756 bool ReferencesFooAndIsZero(const int& n) {
2757   return (&n == &foo) && (n == 0);
2758 }
2759 
2760 // Tests that Truly(predicate) matches what satisfies the given
2761 // predicate.
TEST(TrulyTest,MatchesWhatSatisfiesThePredicate)2762 TEST(TrulyTest, MatchesWhatSatisfiesThePredicate) {
2763   Matcher<double> m = Truly(IsPositive);
2764   EXPECT_TRUE(m.Matches(2.0));
2765   EXPECT_FALSE(m.Matches(-1.5));
2766 }
2767 
2768 // Tests that Truly(predicate_functor) works too.
TEST(TrulyTest,CanBeUsedWithFunctor)2769 TEST(TrulyTest, CanBeUsedWithFunctor) {
2770   Matcher<int> m = Truly(IsGreaterThan(5));
2771   EXPECT_TRUE(m.Matches(6));
2772   EXPECT_FALSE(m.Matches(4));
2773 }
2774 
2775 // A class that can be implicitly converted to bool.
2776 class ConvertibleToBool {
2777  public:
ConvertibleToBool(int number)2778   explicit ConvertibleToBool(int number) : number_(number) {}
operator bool() const2779   operator bool() const { return number_ != 0; }
2780 
2781  private:
2782   int number_;
2783 };
2784 
IsNotZero(int number)2785 ConvertibleToBool IsNotZero(int number) {
2786   return ConvertibleToBool(number);
2787 }
2788 
2789 // Tests that the predicate used in Truly() may return a class that's
2790 // implicitly convertible to bool, even when the class has no
2791 // operator!().
TEST(TrulyTest,PredicateCanReturnAClassConvertibleToBool)2792 TEST(TrulyTest, PredicateCanReturnAClassConvertibleToBool) {
2793   Matcher<int> m = Truly(IsNotZero);
2794   EXPECT_TRUE(m.Matches(1));
2795   EXPECT_FALSE(m.Matches(0));
2796 }
2797 
2798 // Tests that Truly(predicate) can describe itself properly.
TEST(TrulyTest,CanDescribeSelf)2799 TEST(TrulyTest, CanDescribeSelf) {
2800   Matcher<double> m = Truly(IsPositive);
2801   EXPECT_EQ("satisfies the given predicate",
2802             Describe(m));
2803 }
2804 
2805 // Tests that Truly(predicate) works when the matcher takes its
2806 // argument by reference.
TEST(TrulyTest,WorksForByRefArguments)2807 TEST(TrulyTest, WorksForByRefArguments) {
2808   Matcher<const int&> m = Truly(ReferencesFooAndIsZero);
2809   EXPECT_TRUE(m.Matches(foo));
2810   int n = 0;
2811   EXPECT_FALSE(m.Matches(n));
2812 }
2813 
2814 // Tests that Matches(m) is a predicate satisfied by whatever that
2815 // matches matcher m.
TEST(MatchesTest,IsSatisfiedByWhatMatchesTheMatcher)2816 TEST(MatchesTest, IsSatisfiedByWhatMatchesTheMatcher) {
2817   EXPECT_TRUE(Matches(Ge(0))(1));
2818   EXPECT_FALSE(Matches(Eq('a'))('b'));
2819 }
2820 
2821 // Tests that Matches(m) works when the matcher takes its argument by
2822 // reference.
TEST(MatchesTest,WorksOnByRefArguments)2823 TEST(MatchesTest, WorksOnByRefArguments) {
2824   int m = 0, n = 0;
2825   EXPECT_TRUE(Matches(AllOf(Ref(n), Eq(0)))(n));
2826   EXPECT_FALSE(Matches(Ref(m))(n));
2827 }
2828 
2829 // Tests that a Matcher on non-reference type can be used in
2830 // Matches().
TEST(MatchesTest,WorksWithMatcherOnNonRefType)2831 TEST(MatchesTest, WorksWithMatcherOnNonRefType) {
2832   Matcher<int> eq5 = Eq(5);
2833   EXPECT_TRUE(Matches(eq5)(5));
2834   EXPECT_FALSE(Matches(eq5)(2));
2835 }
2836 
2837 // Tests Value(value, matcher).  Since Value() is a simple wrapper for
2838 // Matches(), which has been tested already, we don't spend a lot of
2839 // effort on testing Value().
TEST(ValueTest,WorksWithPolymorphicMatcher)2840 TEST(ValueTest, WorksWithPolymorphicMatcher) {
2841   EXPECT_TRUE(Value("hi", StartsWith("h")));
2842   EXPECT_FALSE(Value(5, Gt(10)));
2843 }
2844 
TEST(ValueTest,WorksWithMonomorphicMatcher)2845 TEST(ValueTest, WorksWithMonomorphicMatcher) {
2846   const Matcher<int> is_zero = Eq(0);
2847   EXPECT_TRUE(Value(0, is_zero));
2848   EXPECT_FALSE(Value('a', is_zero));
2849 
2850   int n = 0;
2851   const Matcher<const int&> ref_n = Ref(n);
2852   EXPECT_TRUE(Value(n, ref_n));
2853   EXPECT_FALSE(Value(1, ref_n));
2854 }
2855 
TEST(ExplainMatchResultTest,WorksWithPolymorphicMatcher)2856 TEST(ExplainMatchResultTest, WorksWithPolymorphicMatcher) {
2857   StringMatchResultListener listener1;
2858   EXPECT_TRUE(ExplainMatchResult(PolymorphicIsEven(), 42, &listener1));
2859   EXPECT_EQ("% 2 == 0", listener1.str());
2860 
2861   StringMatchResultListener listener2;
2862   EXPECT_FALSE(ExplainMatchResult(Ge(42), 1.5, &listener2));
2863   EXPECT_EQ("", listener2.str());
2864 }
2865 
TEST(ExplainMatchResultTest,WorksWithMonomorphicMatcher)2866 TEST(ExplainMatchResultTest, WorksWithMonomorphicMatcher) {
2867   const Matcher<int> is_even = PolymorphicIsEven();
2868   StringMatchResultListener listener1;
2869   EXPECT_TRUE(ExplainMatchResult(is_even, 42, &listener1));
2870   EXPECT_EQ("% 2 == 0", listener1.str());
2871 
2872   const Matcher<const double&> is_zero = Eq(0);
2873   StringMatchResultListener listener2;
2874   EXPECT_FALSE(ExplainMatchResult(is_zero, 1.5, &listener2));
2875   EXPECT_EQ("", listener2.str());
2876 }
2877 
2878 MATCHER_P(Really, inner_matcher, "") {
2879   return ExplainMatchResult(inner_matcher, arg, result_listener);
2880 }
2881 
TEST(ExplainMatchResultTest,WorksInsideMATCHER)2882 TEST(ExplainMatchResultTest, WorksInsideMATCHER) {
2883   EXPECT_THAT(0, Really(Eq(0)));
2884 }
2885 
TEST(DescribeMatcherTest,WorksWithValue)2886 TEST(DescribeMatcherTest, WorksWithValue) {
2887   EXPECT_EQ("is equal to 42", DescribeMatcher<int>(42));
2888   EXPECT_EQ("isn't equal to 42", DescribeMatcher<int>(42, true));
2889 }
2890 
TEST(DescribeMatcherTest,WorksWithMonomorphicMatcher)2891 TEST(DescribeMatcherTest, WorksWithMonomorphicMatcher) {
2892   const Matcher<int> monomorphic = Le(0);
2893   EXPECT_EQ("is <= 0", DescribeMatcher<int>(monomorphic));
2894   EXPECT_EQ("isn't <= 0", DescribeMatcher<int>(monomorphic, true));
2895 }
2896 
TEST(DescribeMatcherTest,WorksWithPolymorphicMatcher)2897 TEST(DescribeMatcherTest, WorksWithPolymorphicMatcher) {
2898   EXPECT_EQ("is even", DescribeMatcher<int>(PolymorphicIsEven()));
2899   EXPECT_EQ("is odd", DescribeMatcher<int>(PolymorphicIsEven(), true));
2900 }
2901 
TEST(AllArgsTest,WorksForTuple)2902 TEST(AllArgsTest, WorksForTuple) {
2903   EXPECT_THAT(std::make_tuple(1, 2L), AllArgs(Lt()));
2904   EXPECT_THAT(std::make_tuple(2L, 1), Not(AllArgs(Lt())));
2905 }
2906 
TEST(AllArgsTest,WorksForNonTuple)2907 TEST(AllArgsTest, WorksForNonTuple) {
2908   EXPECT_THAT(42, AllArgs(Gt(0)));
2909   EXPECT_THAT('a', Not(AllArgs(Eq('b'))));
2910 }
2911 
2912 class AllArgsHelper {
2913  public:
AllArgsHelper()2914   AllArgsHelper() {}
2915 
2916   MOCK_METHOD2(Helper, int(char x, int y));
2917 
2918  private:
2919   GTEST_DISALLOW_COPY_AND_ASSIGN_(AllArgsHelper);
2920 };
2921 
TEST(AllArgsTest,WorksInWithClause)2922 TEST(AllArgsTest, WorksInWithClause) {
2923   AllArgsHelper helper;
2924   ON_CALL(helper, Helper(_, _))
2925       .With(AllArgs(Lt()))
2926       .WillByDefault(Return(1));
2927   EXPECT_CALL(helper, Helper(_, _));
2928   EXPECT_CALL(helper, Helper(_, _))
2929       .With(AllArgs(Gt()))
2930       .WillOnce(Return(2));
2931 
2932   EXPECT_EQ(1, helper.Helper('\1', 2));
2933   EXPECT_EQ(2, helper.Helper('a', 1));
2934 }
2935 
2936 class OptionalMatchersHelper {
2937  public:
OptionalMatchersHelper()2938   OptionalMatchersHelper() {}
2939 
2940   MOCK_METHOD0(NoArgs, int());
2941 
2942   MOCK_METHOD1(OneArg, int(int y));
2943 
2944   MOCK_METHOD2(TwoArgs, int(char x, int y));
2945 
2946   MOCK_METHOD1(Overloaded, int(char x));
2947   MOCK_METHOD2(Overloaded, int(char x, int y));
2948 
2949  private:
2950   GTEST_DISALLOW_COPY_AND_ASSIGN_(OptionalMatchersHelper);
2951 };
2952 
TEST(AllArgsTest,WorksWithoutMatchers)2953 TEST(AllArgsTest, WorksWithoutMatchers) {
2954   OptionalMatchersHelper helper;
2955 
2956   ON_CALL(helper, NoArgs).WillByDefault(Return(10));
2957   ON_CALL(helper, OneArg).WillByDefault(Return(20));
2958   ON_CALL(helper, TwoArgs).WillByDefault(Return(30));
2959 
2960   EXPECT_EQ(10, helper.NoArgs());
2961   EXPECT_EQ(20, helper.OneArg(1));
2962   EXPECT_EQ(30, helper.TwoArgs('\1', 2));
2963 
2964   EXPECT_CALL(helper, NoArgs).Times(1);
2965   EXPECT_CALL(helper, OneArg).WillOnce(Return(100));
2966   EXPECT_CALL(helper, OneArg(17)).WillOnce(Return(200));
2967   EXPECT_CALL(helper, TwoArgs).Times(0);
2968 
2969   EXPECT_EQ(10, helper.NoArgs());
2970   EXPECT_EQ(100, helper.OneArg(1));
2971   EXPECT_EQ(200, helper.OneArg(17));
2972 }
2973 
2974 // Tests that ASSERT_THAT() and EXPECT_THAT() work when the value
2975 // matches the matcher.
TEST(MatcherAssertionTest,WorksWhenMatcherIsSatisfied)2976 TEST(MatcherAssertionTest, WorksWhenMatcherIsSatisfied) {
2977   ASSERT_THAT(5, Ge(2)) << "This should succeed.";
2978   ASSERT_THAT("Foo", EndsWith("oo"));
2979   EXPECT_THAT(2, AllOf(Le(7), Ge(0))) << "This should succeed too.";
2980   EXPECT_THAT("Hello", StartsWith("Hell"));
2981 }
2982 
2983 // Tests that ASSERT_THAT() and EXPECT_THAT() work when the value
2984 // doesn't match the matcher.
TEST(MatcherAssertionTest,WorksWhenMatcherIsNotSatisfied)2985 TEST(MatcherAssertionTest, WorksWhenMatcherIsNotSatisfied) {
2986   // 'n' must be static as it is used in an EXPECT_FATAL_FAILURE(),
2987   // which cannot reference auto variables.
2988   static unsigned short n;  // NOLINT
2989   n = 5;
2990 
2991   EXPECT_FATAL_FAILURE(ASSERT_THAT(n, Gt(10)),
2992                        "Value of: n\n"
2993                        "Expected: is > 10\n"
2994                        "  Actual: 5" + OfType("unsigned short"));
2995   n = 0;
2996   EXPECT_NONFATAL_FAILURE(
2997       EXPECT_THAT(n, AllOf(Le(7), Ge(5))),
2998       "Value of: n\n"
2999       "Expected: (is <= 7) and (is >= 5)\n"
3000       "  Actual: 0" + OfType("unsigned short"));
3001 }
3002 
3003 // Tests that ASSERT_THAT() and EXPECT_THAT() work when the argument
3004 // has a reference type.
TEST(MatcherAssertionTest,WorksForByRefArguments)3005 TEST(MatcherAssertionTest, WorksForByRefArguments) {
3006   // We use a static variable here as EXPECT_FATAL_FAILURE() cannot
3007   // reference auto variables.
3008   static int n;
3009   n = 0;
3010   EXPECT_THAT(n, AllOf(Le(7), Ref(n)));
3011   EXPECT_FATAL_FAILURE(ASSERT_THAT(n, Not(Ref(n))),
3012                        "Value of: n\n"
3013                        "Expected: does not reference the variable @");
3014   // Tests the "Actual" part.
3015   EXPECT_FATAL_FAILURE(ASSERT_THAT(n, Not(Ref(n))),
3016                        "Actual: 0" + OfType("int") + ", which is located @");
3017 }
3018 
3019 // Tests that ASSERT_THAT() and EXPECT_THAT() work when the matcher is
3020 // monomorphic.
TEST(MatcherAssertionTest,WorksForMonomorphicMatcher)3021 TEST(MatcherAssertionTest, WorksForMonomorphicMatcher) {
3022   Matcher<const char*> starts_with_he = StartsWith("he");
3023   ASSERT_THAT("hello", starts_with_he);
3024 
3025   Matcher<const std::string&> ends_with_ok = EndsWith("ok");
3026   ASSERT_THAT("book", ends_with_ok);
3027   const std::string bad = "bad";
3028   EXPECT_NONFATAL_FAILURE(EXPECT_THAT(bad, ends_with_ok),
3029                           "Value of: bad\n"
3030                           "Expected: ends with \"ok\"\n"
3031                           "  Actual: \"bad\"");
3032   Matcher<int> is_greater_than_5 = Gt(5);
3033   EXPECT_NONFATAL_FAILURE(EXPECT_THAT(5, is_greater_than_5),
3034                           "Value of: 5\n"
3035                           "Expected: is > 5\n"
3036                           "  Actual: 5" + OfType("int"));
3037 }
3038 
3039 // Tests floating-point matchers.
3040 template <typename RawType>
3041 class FloatingPointTest : public testing::Test {
3042  protected:
3043   typedef testing::internal::FloatingPoint<RawType> Floating;
3044   typedef typename Floating::Bits Bits;
3045 
FloatingPointTest()3046   FloatingPointTest()
3047       : max_ulps_(Floating::kMaxUlps),
3048         zero_bits_(Floating(0).bits()),
3049         one_bits_(Floating(1).bits()),
3050         infinity_bits_(Floating(Floating::Infinity()).bits()),
3051         close_to_positive_zero_(
3052             Floating::ReinterpretBits(zero_bits_ + max_ulps_/2)),
3053         close_to_negative_zero_(
3054             -Floating::ReinterpretBits(zero_bits_ + max_ulps_ - max_ulps_/2)),
3055         further_from_negative_zero_(-Floating::ReinterpretBits(
3056             zero_bits_ + max_ulps_ + 1 - max_ulps_/2)),
3057         close_to_one_(Floating::ReinterpretBits(one_bits_ + max_ulps_)),
3058         further_from_one_(Floating::ReinterpretBits(one_bits_ + max_ulps_ + 1)),
3059         infinity_(Floating::Infinity()),
3060         close_to_infinity_(
3061             Floating::ReinterpretBits(infinity_bits_ - max_ulps_)),
3062         further_from_infinity_(
3063             Floating::ReinterpretBits(infinity_bits_ - max_ulps_ - 1)),
3064         max_(Floating::Max()),
3065         nan1_(Floating::ReinterpretBits(Floating::kExponentBitMask | 1)),
3066         nan2_(Floating::ReinterpretBits(Floating::kExponentBitMask | 200)) {
3067   }
3068 
TestSize()3069   void TestSize() {
3070     EXPECT_EQ(sizeof(RawType), sizeof(Bits));
3071   }
3072 
3073   // A battery of tests for FloatingEqMatcher::Matches.
3074   // matcher_maker is a pointer to a function which creates a FloatingEqMatcher.
TestMatches(testing::internal::FloatingEqMatcher<RawType> (* matcher_maker)(RawType))3075   void TestMatches(
3076       testing::internal::FloatingEqMatcher<RawType> (*matcher_maker)(RawType)) {
3077     Matcher<RawType> m1 = matcher_maker(0.0);
3078     EXPECT_TRUE(m1.Matches(-0.0));
3079     EXPECT_TRUE(m1.Matches(close_to_positive_zero_));
3080     EXPECT_TRUE(m1.Matches(close_to_negative_zero_));
3081     EXPECT_FALSE(m1.Matches(1.0));
3082 
3083     Matcher<RawType> m2 = matcher_maker(close_to_positive_zero_);
3084     EXPECT_FALSE(m2.Matches(further_from_negative_zero_));
3085 
3086     Matcher<RawType> m3 = matcher_maker(1.0);
3087     EXPECT_TRUE(m3.Matches(close_to_one_));
3088     EXPECT_FALSE(m3.Matches(further_from_one_));
3089 
3090     // Test commutativity: matcher_maker(0.0).Matches(1.0) was tested above.
3091     EXPECT_FALSE(m3.Matches(0.0));
3092 
3093     Matcher<RawType> m4 = matcher_maker(-infinity_);
3094     EXPECT_TRUE(m4.Matches(-close_to_infinity_));
3095 
3096     Matcher<RawType> m5 = matcher_maker(infinity_);
3097     EXPECT_TRUE(m5.Matches(close_to_infinity_));
3098 
3099     // This is interesting as the representations of infinity_ and nan1_
3100     // are only 1 DLP apart.
3101     EXPECT_FALSE(m5.Matches(nan1_));
3102 
3103     // matcher_maker can produce a Matcher<const RawType&>, which is needed in
3104     // some cases.
3105     Matcher<const RawType&> m6 = matcher_maker(0.0);
3106     EXPECT_TRUE(m6.Matches(-0.0));
3107     EXPECT_TRUE(m6.Matches(close_to_positive_zero_));
3108     EXPECT_FALSE(m6.Matches(1.0));
3109 
3110     // matcher_maker can produce a Matcher<RawType&>, which is needed in some
3111     // cases.
3112     Matcher<RawType&> m7 = matcher_maker(0.0);
3113     RawType x = 0.0;
3114     EXPECT_TRUE(m7.Matches(x));
3115     x = 0.01f;
3116     EXPECT_FALSE(m7.Matches(x));
3117   }
3118 
3119   // Pre-calculated numbers to be used by the tests.
3120 
3121   const Bits max_ulps_;
3122 
3123   const Bits zero_bits_;  // The bits that represent 0.0.
3124   const Bits one_bits_;  // The bits that represent 1.0.
3125   const Bits infinity_bits_;  // The bits that represent +infinity.
3126 
3127   // Some numbers close to 0.0.
3128   const RawType close_to_positive_zero_;
3129   const RawType close_to_negative_zero_;
3130   const RawType further_from_negative_zero_;
3131 
3132   // Some numbers close to 1.0.
3133   const RawType close_to_one_;
3134   const RawType further_from_one_;
3135 
3136   // Some numbers close to +infinity.
3137   const RawType infinity_;
3138   const RawType close_to_infinity_;
3139   const RawType further_from_infinity_;
3140 
3141   // Maximum representable value that's not infinity.
3142   const RawType max_;
3143 
3144   // Some NaNs.
3145   const RawType nan1_;
3146   const RawType nan2_;
3147 };
3148 
3149 // Tests floating-point matchers with fixed epsilons.
3150 template <typename RawType>
3151 class FloatingPointNearTest : public FloatingPointTest<RawType> {
3152  protected:
3153   typedef FloatingPointTest<RawType> ParentType;
3154 
3155   // A battery of tests for FloatingEqMatcher::Matches with a fixed epsilon.
3156   // matcher_maker is a pointer to a function which creates a FloatingEqMatcher.
TestNearMatches(testing::internal::FloatingEqMatcher<RawType> (* matcher_maker)(RawType,RawType))3157   void TestNearMatches(
3158       testing::internal::FloatingEqMatcher<RawType>
3159           (*matcher_maker)(RawType, RawType)) {
3160     Matcher<RawType> m1 = matcher_maker(0.0, 0.0);
3161     EXPECT_TRUE(m1.Matches(0.0));
3162     EXPECT_TRUE(m1.Matches(-0.0));
3163     EXPECT_FALSE(m1.Matches(ParentType::close_to_positive_zero_));
3164     EXPECT_FALSE(m1.Matches(ParentType::close_to_negative_zero_));
3165     EXPECT_FALSE(m1.Matches(1.0));
3166 
3167     Matcher<RawType> m2 = matcher_maker(0.0, 1.0);
3168     EXPECT_TRUE(m2.Matches(0.0));
3169     EXPECT_TRUE(m2.Matches(-0.0));
3170     EXPECT_TRUE(m2.Matches(1.0));
3171     EXPECT_TRUE(m2.Matches(-1.0));
3172     EXPECT_FALSE(m2.Matches(ParentType::close_to_one_));
3173     EXPECT_FALSE(m2.Matches(-ParentType::close_to_one_));
3174 
3175     // Check that inf matches inf, regardless of the of the specified max
3176     // absolute error.
3177     Matcher<RawType> m3 = matcher_maker(ParentType::infinity_, 0.0);
3178     EXPECT_TRUE(m3.Matches(ParentType::infinity_));
3179     EXPECT_FALSE(m3.Matches(ParentType::close_to_infinity_));
3180     EXPECT_FALSE(m3.Matches(-ParentType::infinity_));
3181 
3182     Matcher<RawType> m4 = matcher_maker(-ParentType::infinity_, 0.0);
3183     EXPECT_TRUE(m4.Matches(-ParentType::infinity_));
3184     EXPECT_FALSE(m4.Matches(-ParentType::close_to_infinity_));
3185     EXPECT_FALSE(m4.Matches(ParentType::infinity_));
3186 
3187     // Test various overflow scenarios.
3188     Matcher<RawType> m5 = matcher_maker(ParentType::max_, ParentType::max_);
3189     EXPECT_TRUE(m5.Matches(ParentType::max_));
3190     EXPECT_FALSE(m5.Matches(-ParentType::max_));
3191 
3192     Matcher<RawType> m6 = matcher_maker(-ParentType::max_, ParentType::max_);
3193     EXPECT_FALSE(m6.Matches(ParentType::max_));
3194     EXPECT_TRUE(m6.Matches(-ParentType::max_));
3195 
3196     Matcher<RawType> m7 = matcher_maker(ParentType::max_, 0);
3197     EXPECT_TRUE(m7.Matches(ParentType::max_));
3198     EXPECT_FALSE(m7.Matches(-ParentType::max_));
3199 
3200     Matcher<RawType> m8 = matcher_maker(-ParentType::max_, 0);
3201     EXPECT_FALSE(m8.Matches(ParentType::max_));
3202     EXPECT_TRUE(m8.Matches(-ParentType::max_));
3203 
3204     // The difference between max() and -max() normally overflows to infinity,
3205     // but it should still match if the max_abs_error is also infinity.
3206     Matcher<RawType> m9 = matcher_maker(
3207         ParentType::max_, ParentType::infinity_);
3208     EXPECT_TRUE(m8.Matches(-ParentType::max_));
3209 
3210     // matcher_maker can produce a Matcher<const RawType&>, which is needed in
3211     // some cases.
3212     Matcher<const RawType&> m10 = matcher_maker(0.0, 1.0);
3213     EXPECT_TRUE(m10.Matches(-0.0));
3214     EXPECT_TRUE(m10.Matches(ParentType::close_to_positive_zero_));
3215     EXPECT_FALSE(m10.Matches(ParentType::close_to_one_));
3216 
3217     // matcher_maker can produce a Matcher<RawType&>, which is needed in some
3218     // cases.
3219     Matcher<RawType&> m11 = matcher_maker(0.0, 1.0);
3220     RawType x = 0.0;
3221     EXPECT_TRUE(m11.Matches(x));
3222     x = 1.0f;
3223     EXPECT_TRUE(m11.Matches(x));
3224     x = -1.0f;
3225     EXPECT_TRUE(m11.Matches(x));
3226     x = 1.1f;
3227     EXPECT_FALSE(m11.Matches(x));
3228     x = -1.1f;
3229     EXPECT_FALSE(m11.Matches(x));
3230   }
3231 };
3232 
3233 // Instantiate FloatingPointTest for testing floats.
3234 typedef FloatingPointTest<float> FloatTest;
3235 
TEST_F(FloatTest,FloatEqApproximatelyMatchesFloats)3236 TEST_F(FloatTest, FloatEqApproximatelyMatchesFloats) {
3237   TestMatches(&FloatEq);
3238 }
3239 
TEST_F(FloatTest,NanSensitiveFloatEqApproximatelyMatchesFloats)3240 TEST_F(FloatTest, NanSensitiveFloatEqApproximatelyMatchesFloats) {
3241   TestMatches(&NanSensitiveFloatEq);
3242 }
3243 
TEST_F(FloatTest,FloatEqCannotMatchNaN)3244 TEST_F(FloatTest, FloatEqCannotMatchNaN) {
3245   // FloatEq never matches NaN.
3246   Matcher<float> m = FloatEq(nan1_);
3247   EXPECT_FALSE(m.Matches(nan1_));
3248   EXPECT_FALSE(m.Matches(nan2_));
3249   EXPECT_FALSE(m.Matches(1.0));
3250 }
3251 
TEST_F(FloatTest,NanSensitiveFloatEqCanMatchNaN)3252 TEST_F(FloatTest, NanSensitiveFloatEqCanMatchNaN) {
3253   // NanSensitiveFloatEq will match NaN.
3254   Matcher<float> m = NanSensitiveFloatEq(nan1_);
3255   EXPECT_TRUE(m.Matches(nan1_));
3256   EXPECT_TRUE(m.Matches(nan2_));
3257   EXPECT_FALSE(m.Matches(1.0));
3258 }
3259 
TEST_F(FloatTest,FloatEqCanDescribeSelf)3260 TEST_F(FloatTest, FloatEqCanDescribeSelf) {
3261   Matcher<float> m1 = FloatEq(2.0f);
3262   EXPECT_EQ("is approximately 2", Describe(m1));
3263   EXPECT_EQ("isn't approximately 2", DescribeNegation(m1));
3264 
3265   Matcher<float> m2 = FloatEq(0.5f);
3266   EXPECT_EQ("is approximately 0.5", Describe(m2));
3267   EXPECT_EQ("isn't approximately 0.5", DescribeNegation(m2));
3268 
3269   Matcher<float> m3 = FloatEq(nan1_);
3270   EXPECT_EQ("never matches", Describe(m3));
3271   EXPECT_EQ("is anything", DescribeNegation(m3));
3272 }
3273 
TEST_F(FloatTest,NanSensitiveFloatEqCanDescribeSelf)3274 TEST_F(FloatTest, NanSensitiveFloatEqCanDescribeSelf) {
3275   Matcher<float> m1 = NanSensitiveFloatEq(2.0f);
3276   EXPECT_EQ("is approximately 2", Describe(m1));
3277   EXPECT_EQ("isn't approximately 2", DescribeNegation(m1));
3278 
3279   Matcher<float> m2 = NanSensitiveFloatEq(0.5f);
3280   EXPECT_EQ("is approximately 0.5", Describe(m2));
3281   EXPECT_EQ("isn't approximately 0.5", DescribeNegation(m2));
3282 
3283   Matcher<float> m3 = NanSensitiveFloatEq(nan1_);
3284   EXPECT_EQ("is NaN", Describe(m3));
3285   EXPECT_EQ("isn't NaN", DescribeNegation(m3));
3286 }
3287 
3288 // Instantiate FloatingPointTest for testing floats with a user-specified
3289 // max absolute error.
3290 typedef FloatingPointNearTest<float> FloatNearTest;
3291 
TEST_F(FloatNearTest,FloatNearMatches)3292 TEST_F(FloatNearTest, FloatNearMatches) {
3293   TestNearMatches(&FloatNear);
3294 }
3295 
TEST_F(FloatNearTest,NanSensitiveFloatNearApproximatelyMatchesFloats)3296 TEST_F(FloatNearTest, NanSensitiveFloatNearApproximatelyMatchesFloats) {
3297   TestNearMatches(&NanSensitiveFloatNear);
3298 }
3299 
TEST_F(FloatNearTest,FloatNearCanDescribeSelf)3300 TEST_F(FloatNearTest, FloatNearCanDescribeSelf) {
3301   Matcher<float> m1 = FloatNear(2.0f, 0.5f);
3302   EXPECT_EQ("is approximately 2 (absolute error <= 0.5)", Describe(m1));
3303   EXPECT_EQ(
3304       "isn't approximately 2 (absolute error > 0.5)", DescribeNegation(m1));
3305 
3306   Matcher<float> m2 = FloatNear(0.5f, 0.5f);
3307   EXPECT_EQ("is approximately 0.5 (absolute error <= 0.5)", Describe(m2));
3308   EXPECT_EQ(
3309       "isn't approximately 0.5 (absolute error > 0.5)", DescribeNegation(m2));
3310 
3311   Matcher<float> m3 = FloatNear(nan1_, 0.0);
3312   EXPECT_EQ("never matches", Describe(m3));
3313   EXPECT_EQ("is anything", DescribeNegation(m3));
3314 }
3315 
TEST_F(FloatNearTest,NanSensitiveFloatNearCanDescribeSelf)3316 TEST_F(FloatNearTest, NanSensitiveFloatNearCanDescribeSelf) {
3317   Matcher<float> m1 = NanSensitiveFloatNear(2.0f, 0.5f);
3318   EXPECT_EQ("is approximately 2 (absolute error <= 0.5)", Describe(m1));
3319   EXPECT_EQ(
3320       "isn't approximately 2 (absolute error > 0.5)", DescribeNegation(m1));
3321 
3322   Matcher<float> m2 = NanSensitiveFloatNear(0.5f, 0.5f);
3323   EXPECT_EQ("is approximately 0.5 (absolute error <= 0.5)", Describe(m2));
3324   EXPECT_EQ(
3325       "isn't approximately 0.5 (absolute error > 0.5)", DescribeNegation(m2));
3326 
3327   Matcher<float> m3 = NanSensitiveFloatNear(nan1_, 0.1f);
3328   EXPECT_EQ("is NaN", Describe(m3));
3329   EXPECT_EQ("isn't NaN", DescribeNegation(m3));
3330 }
3331 
TEST_F(FloatNearTest,FloatNearCannotMatchNaN)3332 TEST_F(FloatNearTest, FloatNearCannotMatchNaN) {
3333   // FloatNear never matches NaN.
3334   Matcher<float> m = FloatNear(ParentType::nan1_, 0.1f);
3335   EXPECT_FALSE(m.Matches(nan1_));
3336   EXPECT_FALSE(m.Matches(nan2_));
3337   EXPECT_FALSE(m.Matches(1.0));
3338 }
3339 
TEST_F(FloatNearTest,NanSensitiveFloatNearCanMatchNaN)3340 TEST_F(FloatNearTest, NanSensitiveFloatNearCanMatchNaN) {
3341   // NanSensitiveFloatNear will match NaN.
3342   Matcher<float> m = NanSensitiveFloatNear(nan1_, 0.1f);
3343   EXPECT_TRUE(m.Matches(nan1_));
3344   EXPECT_TRUE(m.Matches(nan2_));
3345   EXPECT_FALSE(m.Matches(1.0));
3346 }
3347 
3348 // Instantiate FloatingPointTest for testing doubles.
3349 typedef FloatingPointTest<double> DoubleTest;
3350 
TEST_F(DoubleTest,DoubleEqApproximatelyMatchesDoubles)3351 TEST_F(DoubleTest, DoubleEqApproximatelyMatchesDoubles) {
3352   TestMatches(&DoubleEq);
3353 }
3354 
TEST_F(DoubleTest,NanSensitiveDoubleEqApproximatelyMatchesDoubles)3355 TEST_F(DoubleTest, NanSensitiveDoubleEqApproximatelyMatchesDoubles) {
3356   TestMatches(&NanSensitiveDoubleEq);
3357 }
3358 
TEST_F(DoubleTest,DoubleEqCannotMatchNaN)3359 TEST_F(DoubleTest, DoubleEqCannotMatchNaN) {
3360   // DoubleEq never matches NaN.
3361   Matcher<double> m = DoubleEq(nan1_);
3362   EXPECT_FALSE(m.Matches(nan1_));
3363   EXPECT_FALSE(m.Matches(nan2_));
3364   EXPECT_FALSE(m.Matches(1.0));
3365 }
3366 
TEST_F(DoubleTest,NanSensitiveDoubleEqCanMatchNaN)3367 TEST_F(DoubleTest, NanSensitiveDoubleEqCanMatchNaN) {
3368   // NanSensitiveDoubleEq will match NaN.
3369   Matcher<double> m = NanSensitiveDoubleEq(nan1_);
3370   EXPECT_TRUE(m.Matches(nan1_));
3371   EXPECT_TRUE(m.Matches(nan2_));
3372   EXPECT_FALSE(m.Matches(1.0));
3373 }
3374 
TEST_F(DoubleTest,DoubleEqCanDescribeSelf)3375 TEST_F(DoubleTest, DoubleEqCanDescribeSelf) {
3376   Matcher<double> m1 = DoubleEq(2.0);
3377   EXPECT_EQ("is approximately 2", Describe(m1));
3378   EXPECT_EQ("isn't approximately 2", DescribeNegation(m1));
3379 
3380   Matcher<double> m2 = DoubleEq(0.5);
3381   EXPECT_EQ("is approximately 0.5", Describe(m2));
3382   EXPECT_EQ("isn't approximately 0.5", DescribeNegation(m2));
3383 
3384   Matcher<double> m3 = DoubleEq(nan1_);
3385   EXPECT_EQ("never matches", Describe(m3));
3386   EXPECT_EQ("is anything", DescribeNegation(m3));
3387 }
3388 
TEST_F(DoubleTest,NanSensitiveDoubleEqCanDescribeSelf)3389 TEST_F(DoubleTest, NanSensitiveDoubleEqCanDescribeSelf) {
3390   Matcher<double> m1 = NanSensitiveDoubleEq(2.0);
3391   EXPECT_EQ("is approximately 2", Describe(m1));
3392   EXPECT_EQ("isn't approximately 2", DescribeNegation(m1));
3393 
3394   Matcher<double> m2 = NanSensitiveDoubleEq(0.5);
3395   EXPECT_EQ("is approximately 0.5", Describe(m2));
3396   EXPECT_EQ("isn't approximately 0.5", DescribeNegation(m2));
3397 
3398   Matcher<double> m3 = NanSensitiveDoubleEq(nan1_);
3399   EXPECT_EQ("is NaN", Describe(m3));
3400   EXPECT_EQ("isn't NaN", DescribeNegation(m3));
3401 }
3402 
3403 // Instantiate FloatingPointTest for testing floats with a user-specified
3404 // max absolute error.
3405 typedef FloatingPointNearTest<double> DoubleNearTest;
3406 
TEST_F(DoubleNearTest,DoubleNearMatches)3407 TEST_F(DoubleNearTest, DoubleNearMatches) {
3408   TestNearMatches(&DoubleNear);
3409 }
3410 
TEST_F(DoubleNearTest,NanSensitiveDoubleNearApproximatelyMatchesDoubles)3411 TEST_F(DoubleNearTest, NanSensitiveDoubleNearApproximatelyMatchesDoubles) {
3412   TestNearMatches(&NanSensitiveDoubleNear);
3413 }
3414 
TEST_F(DoubleNearTest,DoubleNearCanDescribeSelf)3415 TEST_F(DoubleNearTest, DoubleNearCanDescribeSelf) {
3416   Matcher<double> m1 = DoubleNear(2.0, 0.5);
3417   EXPECT_EQ("is approximately 2 (absolute error <= 0.5)", Describe(m1));
3418   EXPECT_EQ(
3419       "isn't approximately 2 (absolute error > 0.5)", DescribeNegation(m1));
3420 
3421   Matcher<double> m2 = DoubleNear(0.5, 0.5);
3422   EXPECT_EQ("is approximately 0.5 (absolute error <= 0.5)", Describe(m2));
3423   EXPECT_EQ(
3424       "isn't approximately 0.5 (absolute error > 0.5)", DescribeNegation(m2));
3425 
3426   Matcher<double> m3 = DoubleNear(nan1_, 0.0);
3427   EXPECT_EQ("never matches", Describe(m3));
3428   EXPECT_EQ("is anything", DescribeNegation(m3));
3429 }
3430 
TEST_F(DoubleNearTest,ExplainsResultWhenMatchFails)3431 TEST_F(DoubleNearTest, ExplainsResultWhenMatchFails) {
3432   EXPECT_EQ("", Explain(DoubleNear(2.0, 0.1), 2.05));
3433   EXPECT_EQ("which is 0.2 from 2", Explain(DoubleNear(2.0, 0.1), 2.2));
3434   EXPECT_EQ("which is -0.3 from 2", Explain(DoubleNear(2.0, 0.1), 1.7));
3435 
3436   const std::string explanation =
3437       Explain(DoubleNear(2.1, 1e-10), 2.1 + 1.2e-10);
3438   // Different C++ implementations may print floating-point numbers
3439   // slightly differently.
3440   EXPECT_TRUE(explanation == "which is 1.2e-10 from 2.1" ||  // GCC
3441               explanation == "which is 1.2e-010 from 2.1")   // MSVC
3442       << " where explanation is \"" << explanation << "\".";
3443 }
3444 
TEST_F(DoubleNearTest,NanSensitiveDoubleNearCanDescribeSelf)3445 TEST_F(DoubleNearTest, NanSensitiveDoubleNearCanDescribeSelf) {
3446   Matcher<double> m1 = NanSensitiveDoubleNear(2.0, 0.5);
3447   EXPECT_EQ("is approximately 2 (absolute error <= 0.5)", Describe(m1));
3448   EXPECT_EQ(
3449       "isn't approximately 2 (absolute error > 0.5)", DescribeNegation(m1));
3450 
3451   Matcher<double> m2 = NanSensitiveDoubleNear(0.5, 0.5);
3452   EXPECT_EQ("is approximately 0.5 (absolute error <= 0.5)", Describe(m2));
3453   EXPECT_EQ(
3454       "isn't approximately 0.5 (absolute error > 0.5)", DescribeNegation(m2));
3455 
3456   Matcher<double> m3 = NanSensitiveDoubleNear(nan1_, 0.1);
3457   EXPECT_EQ("is NaN", Describe(m3));
3458   EXPECT_EQ("isn't NaN", DescribeNegation(m3));
3459 }
3460 
TEST_F(DoubleNearTest,DoubleNearCannotMatchNaN)3461 TEST_F(DoubleNearTest, DoubleNearCannotMatchNaN) {
3462   // DoubleNear never matches NaN.
3463   Matcher<double> m = DoubleNear(ParentType::nan1_, 0.1);
3464   EXPECT_FALSE(m.Matches(nan1_));
3465   EXPECT_FALSE(m.Matches(nan2_));
3466   EXPECT_FALSE(m.Matches(1.0));
3467 }
3468 
TEST_F(DoubleNearTest,NanSensitiveDoubleNearCanMatchNaN)3469 TEST_F(DoubleNearTest, NanSensitiveDoubleNearCanMatchNaN) {
3470   // NanSensitiveDoubleNear will match NaN.
3471   Matcher<double> m = NanSensitiveDoubleNear(nan1_, 0.1);
3472   EXPECT_TRUE(m.Matches(nan1_));
3473   EXPECT_TRUE(m.Matches(nan2_));
3474   EXPECT_FALSE(m.Matches(1.0));
3475 }
3476 
TEST(PointeeTest,RawPointer)3477 TEST(PointeeTest, RawPointer) {
3478   const Matcher<int*> m = Pointee(Ge(0));
3479 
3480   int n = 1;
3481   EXPECT_TRUE(m.Matches(&n));
3482   n = -1;
3483   EXPECT_FALSE(m.Matches(&n));
3484   EXPECT_FALSE(m.Matches(nullptr));
3485 }
3486 
TEST(PointeeTest,RawPointerToConst)3487 TEST(PointeeTest, RawPointerToConst) {
3488   const Matcher<const double*> m = Pointee(Ge(0));
3489 
3490   double x = 1;
3491   EXPECT_TRUE(m.Matches(&x));
3492   x = -1;
3493   EXPECT_FALSE(m.Matches(&x));
3494   EXPECT_FALSE(m.Matches(nullptr));
3495 }
3496 
TEST(PointeeTest,ReferenceToConstRawPointer)3497 TEST(PointeeTest, ReferenceToConstRawPointer) {
3498   const Matcher<int* const &> m = Pointee(Ge(0));
3499 
3500   int n = 1;
3501   EXPECT_TRUE(m.Matches(&n));
3502   n = -1;
3503   EXPECT_FALSE(m.Matches(&n));
3504   EXPECT_FALSE(m.Matches(nullptr));
3505 }
3506 
TEST(PointeeTest,ReferenceToNonConstRawPointer)3507 TEST(PointeeTest, ReferenceToNonConstRawPointer) {
3508   const Matcher<double* &> m = Pointee(Ge(0));
3509 
3510   double x = 1.0;
3511   double* p = &x;
3512   EXPECT_TRUE(m.Matches(p));
3513   x = -1;
3514   EXPECT_FALSE(m.Matches(p));
3515   p = nullptr;
3516   EXPECT_FALSE(m.Matches(p));
3517 }
3518 
3519 MATCHER_P(FieldIIs, inner_matcher, "") {
3520   return ExplainMatchResult(inner_matcher, arg.i, result_listener);
3521 }
3522 
3523 #if GTEST_HAS_RTTI
TEST(WhenDynamicCastToTest,SameType)3524 TEST(WhenDynamicCastToTest, SameType) {
3525   Derived derived;
3526   derived.i = 4;
3527 
3528   // Right type. A pointer is passed down.
3529   Base* as_base_ptr = &derived;
3530   EXPECT_THAT(as_base_ptr, WhenDynamicCastTo<Derived*>(Not(IsNull())));
3531   EXPECT_THAT(as_base_ptr, WhenDynamicCastTo<Derived*>(Pointee(FieldIIs(4))));
3532   EXPECT_THAT(as_base_ptr,
3533               Not(WhenDynamicCastTo<Derived*>(Pointee(FieldIIs(5)))));
3534 }
3535 
TEST(WhenDynamicCastToTest,WrongTypes)3536 TEST(WhenDynamicCastToTest, WrongTypes) {
3537   Base base;
3538   Derived derived;
3539   OtherDerived other_derived;
3540 
3541   // Wrong types. NULL is passed.
3542   EXPECT_THAT(&base, Not(WhenDynamicCastTo<Derived*>(Pointee(_))));
3543   EXPECT_THAT(&base, WhenDynamicCastTo<Derived*>(IsNull()));
3544   Base* as_base_ptr = &derived;
3545   EXPECT_THAT(as_base_ptr, Not(WhenDynamicCastTo<OtherDerived*>(Pointee(_))));
3546   EXPECT_THAT(as_base_ptr, WhenDynamicCastTo<OtherDerived*>(IsNull()));
3547   as_base_ptr = &other_derived;
3548   EXPECT_THAT(as_base_ptr, Not(WhenDynamicCastTo<Derived*>(Pointee(_))));
3549   EXPECT_THAT(as_base_ptr, WhenDynamicCastTo<Derived*>(IsNull()));
3550 }
3551 
TEST(WhenDynamicCastToTest,AlreadyNull)3552 TEST(WhenDynamicCastToTest, AlreadyNull) {
3553   // Already NULL.
3554   Base* as_base_ptr = nullptr;
3555   EXPECT_THAT(as_base_ptr, WhenDynamicCastTo<Derived*>(IsNull()));
3556 }
3557 
3558 struct AmbiguousCastTypes {
3559   class VirtualDerived : public virtual Base {};
3560   class DerivedSub1 : public VirtualDerived {};
3561   class DerivedSub2 : public VirtualDerived {};
3562   class ManyDerivedInHierarchy : public DerivedSub1, public DerivedSub2 {};
3563 };
3564 
TEST(WhenDynamicCastToTest,AmbiguousCast)3565 TEST(WhenDynamicCastToTest, AmbiguousCast) {
3566   AmbiguousCastTypes::DerivedSub1 sub1;
3567   AmbiguousCastTypes::ManyDerivedInHierarchy many_derived;
3568   // Multiply derived from Base. dynamic_cast<> returns NULL.
3569   Base* as_base_ptr =
3570       static_cast<AmbiguousCastTypes::DerivedSub1*>(&many_derived);
3571   EXPECT_THAT(as_base_ptr,
3572               WhenDynamicCastTo<AmbiguousCastTypes::VirtualDerived*>(IsNull()));
3573   as_base_ptr = &sub1;
3574   EXPECT_THAT(
3575       as_base_ptr,
3576       WhenDynamicCastTo<AmbiguousCastTypes::VirtualDerived*>(Not(IsNull())));
3577 }
3578 
TEST(WhenDynamicCastToTest,Describe)3579 TEST(WhenDynamicCastToTest, Describe) {
3580   Matcher<Base*> matcher = WhenDynamicCastTo<Derived*>(Pointee(_));
3581   const std::string prefix =
3582       "when dynamic_cast to " + internal::GetTypeName<Derived*>() + ", ";
3583   EXPECT_EQ(prefix + "points to a value that is anything", Describe(matcher));
3584   EXPECT_EQ(prefix + "does not point to a value that is anything",
3585             DescribeNegation(matcher));
3586 }
3587 
TEST(WhenDynamicCastToTest,Explain)3588 TEST(WhenDynamicCastToTest, Explain) {
3589   Matcher<Base*> matcher = WhenDynamicCastTo<Derived*>(Pointee(_));
3590   Base* null = nullptr;
3591   EXPECT_THAT(Explain(matcher, null), HasSubstr("NULL"));
3592   Derived derived;
3593   EXPECT_TRUE(matcher.Matches(&derived));
3594   EXPECT_THAT(Explain(matcher, &derived), HasSubstr("which points to "));
3595 
3596   // With references, the matcher itself can fail. Test for that one.
3597   Matcher<const Base&> ref_matcher = WhenDynamicCastTo<const OtherDerived&>(_);
3598   EXPECT_THAT(Explain(ref_matcher, derived),
3599               HasSubstr("which cannot be dynamic_cast"));
3600 }
3601 
TEST(WhenDynamicCastToTest,GoodReference)3602 TEST(WhenDynamicCastToTest, GoodReference) {
3603   Derived derived;
3604   derived.i = 4;
3605   Base& as_base_ref = derived;
3606   EXPECT_THAT(as_base_ref, WhenDynamicCastTo<const Derived&>(FieldIIs(4)));
3607   EXPECT_THAT(as_base_ref, WhenDynamicCastTo<const Derived&>(Not(FieldIIs(5))));
3608 }
3609 
TEST(WhenDynamicCastToTest,BadReference)3610 TEST(WhenDynamicCastToTest, BadReference) {
3611   Derived derived;
3612   Base& as_base_ref = derived;
3613   EXPECT_THAT(as_base_ref, Not(WhenDynamicCastTo<const OtherDerived&>(_)));
3614 }
3615 #endif  // GTEST_HAS_RTTI
3616 
3617 // Minimal const-propagating pointer.
3618 template <typename T>
3619 class ConstPropagatingPtr {
3620  public:
3621   typedef T element_type;
3622 
ConstPropagatingPtr()3623   ConstPropagatingPtr() : val_() {}
ConstPropagatingPtr(T * t)3624   explicit ConstPropagatingPtr(T* t) : val_(t) {}
ConstPropagatingPtr(const ConstPropagatingPtr & other)3625   ConstPropagatingPtr(const ConstPropagatingPtr& other) : val_(other.val_) {}
3626 
get()3627   T* get() { return val_; }
operator *()3628   T& operator*() { return *val_; }
3629   // Most smart pointers return non-const T* and T& from the next methods.
get() const3630   const T* get() const { return val_; }
operator *() const3631   const T& operator*() const { return *val_; }
3632 
3633  private:
3634   T* val_;
3635 };
3636 
TEST(PointeeTest,WorksWithConstPropagatingPointers)3637 TEST(PointeeTest, WorksWithConstPropagatingPointers) {
3638   const Matcher< ConstPropagatingPtr<int> > m = Pointee(Lt(5));
3639   int three = 3;
3640   const ConstPropagatingPtr<int> co(&three);
3641   ConstPropagatingPtr<int> o(&three);
3642   EXPECT_TRUE(m.Matches(o));
3643   EXPECT_TRUE(m.Matches(co));
3644   *o = 6;
3645   EXPECT_FALSE(m.Matches(o));
3646   EXPECT_FALSE(m.Matches(ConstPropagatingPtr<int>()));
3647 }
3648 
TEST(PointeeTest,NeverMatchesNull)3649 TEST(PointeeTest, NeverMatchesNull) {
3650   const Matcher<const char*> m = Pointee(_);
3651   EXPECT_FALSE(m.Matches(nullptr));
3652 }
3653 
3654 // Tests that we can write Pointee(value) instead of Pointee(Eq(value)).
TEST(PointeeTest,MatchesAgainstAValue)3655 TEST(PointeeTest, MatchesAgainstAValue) {
3656   const Matcher<int*> m = Pointee(5);
3657 
3658   int n = 5;
3659   EXPECT_TRUE(m.Matches(&n));
3660   n = -1;
3661   EXPECT_FALSE(m.Matches(&n));
3662   EXPECT_FALSE(m.Matches(nullptr));
3663 }
3664 
TEST(PointeeTest,CanDescribeSelf)3665 TEST(PointeeTest, CanDescribeSelf) {
3666   const Matcher<int*> m = Pointee(Gt(3));
3667   EXPECT_EQ("points to a value that is > 3", Describe(m));
3668   EXPECT_EQ("does not point to a value that is > 3",
3669             DescribeNegation(m));
3670 }
3671 
TEST(PointeeTest,CanExplainMatchResult)3672 TEST(PointeeTest, CanExplainMatchResult) {
3673   const Matcher<const std::string*> m = Pointee(StartsWith("Hi"));
3674 
3675   EXPECT_EQ("", Explain(m, static_cast<const std::string*>(nullptr)));
3676 
3677   const Matcher<long*> m2 = Pointee(GreaterThan(1));  // NOLINT
3678   long n = 3;  // NOLINT
3679   EXPECT_EQ("which points to 3" + OfType("long") + ", which is 2 more than 1",
3680             Explain(m2, &n));
3681 }
3682 
TEST(PointeeTest,AlwaysExplainsPointee)3683 TEST(PointeeTest, AlwaysExplainsPointee) {
3684   const Matcher<int*> m = Pointee(0);
3685   int n = 42;
3686   EXPECT_EQ("which points to 42" + OfType("int"), Explain(m, &n));
3687 }
3688 
3689 // An uncopyable class.
3690 class Uncopyable {
3691  public:
Uncopyable()3692   Uncopyable() : value_(-1) {}
Uncopyable(int a_value)3693   explicit Uncopyable(int a_value) : value_(a_value) {}
3694 
value() const3695   int value() const { return value_; }
set_value(int i)3696   void set_value(int i) { value_ = i; }
3697 
3698  private:
3699   int value_;
3700   GTEST_DISALLOW_COPY_AND_ASSIGN_(Uncopyable);
3701 };
3702 
3703 // Returns true if and only if x.value() is positive.
ValueIsPositive(const Uncopyable & x)3704 bool ValueIsPositive(const Uncopyable& x) { return x.value() > 0; }
3705 
3706 MATCHER_P(UncopyableIs, inner_matcher, "") {
3707   return ExplainMatchResult(inner_matcher, arg.value(), result_listener);
3708 }
3709 
3710 // A user-defined struct for testing Field().
3711 struct AStruct {
AStructtesting::gmock_matchers_test::__anon86e4b7b50111::AStruct3712   AStruct() : x(0), y(1.0), z(5), p(nullptr) {}
AStructtesting::gmock_matchers_test::__anon86e4b7b50111::AStruct3713   AStruct(const AStruct& rhs)
3714       : x(rhs.x), y(rhs.y), z(rhs.z.value()), p(rhs.p) {}
3715 
3716   int x;           // A non-const field.
3717   const double y;  // A const field.
3718   Uncopyable z;    // An uncopyable field.
3719   const char* p;   // A pointer field.
3720 
3721  private:
3722   GTEST_DISALLOW_ASSIGN_(AStruct);
3723 };
3724 
3725 // A derived struct for testing Field().
3726 struct DerivedStruct : public AStruct {
3727   char ch;
3728 
3729  private:
3730   GTEST_DISALLOW_ASSIGN_(DerivedStruct);
3731 };
3732 
3733 // Tests that Field(&Foo::field, ...) works when field is non-const.
TEST(FieldTest,WorksForNonConstField)3734 TEST(FieldTest, WorksForNonConstField) {
3735   Matcher<AStruct> m = Field(&AStruct::x, Ge(0));
3736   Matcher<AStruct> m_with_name = Field("x", &AStruct::x, Ge(0));
3737 
3738   AStruct a;
3739   EXPECT_TRUE(m.Matches(a));
3740   EXPECT_TRUE(m_with_name.Matches(a));
3741   a.x = -1;
3742   EXPECT_FALSE(m.Matches(a));
3743   EXPECT_FALSE(m_with_name.Matches(a));
3744 }
3745 
3746 // Tests that Field(&Foo::field, ...) works when field is const.
TEST(FieldTest,WorksForConstField)3747 TEST(FieldTest, WorksForConstField) {
3748   AStruct a;
3749 
3750   Matcher<AStruct> m = Field(&AStruct::y, Ge(0.0));
3751   Matcher<AStruct> m_with_name = Field("y", &AStruct::y, Ge(0.0));
3752   EXPECT_TRUE(m.Matches(a));
3753   EXPECT_TRUE(m_with_name.Matches(a));
3754   m = Field(&AStruct::y, Le(0.0));
3755   m_with_name = Field("y", &AStruct::y, Le(0.0));
3756   EXPECT_FALSE(m.Matches(a));
3757   EXPECT_FALSE(m_with_name.Matches(a));
3758 }
3759 
3760 // Tests that Field(&Foo::field, ...) works when field is not copyable.
TEST(FieldTest,WorksForUncopyableField)3761 TEST(FieldTest, WorksForUncopyableField) {
3762   AStruct a;
3763 
3764   Matcher<AStruct> m = Field(&AStruct::z, Truly(ValueIsPositive));
3765   EXPECT_TRUE(m.Matches(a));
3766   m = Field(&AStruct::z, Not(Truly(ValueIsPositive)));
3767   EXPECT_FALSE(m.Matches(a));
3768 }
3769 
3770 // Tests that Field(&Foo::field, ...) works when field is a pointer.
TEST(FieldTest,WorksForPointerField)3771 TEST(FieldTest, WorksForPointerField) {
3772   // Matching against NULL.
3773   Matcher<AStruct> m = Field(&AStruct::p, static_cast<const char*>(nullptr));
3774   AStruct a;
3775   EXPECT_TRUE(m.Matches(a));
3776   a.p = "hi";
3777   EXPECT_FALSE(m.Matches(a));
3778 
3779   // Matching a pointer that is not NULL.
3780   m = Field(&AStruct::p, StartsWith("hi"));
3781   a.p = "hill";
3782   EXPECT_TRUE(m.Matches(a));
3783   a.p = "hole";
3784   EXPECT_FALSE(m.Matches(a));
3785 }
3786 
3787 // Tests that Field() works when the object is passed by reference.
TEST(FieldTest,WorksForByRefArgument)3788 TEST(FieldTest, WorksForByRefArgument) {
3789   Matcher<const AStruct&> m = Field(&AStruct::x, Ge(0));
3790 
3791   AStruct a;
3792   EXPECT_TRUE(m.Matches(a));
3793   a.x = -1;
3794   EXPECT_FALSE(m.Matches(a));
3795 }
3796 
3797 // Tests that Field(&Foo::field, ...) works when the argument's type
3798 // is a sub-type of Foo.
TEST(FieldTest,WorksForArgumentOfSubType)3799 TEST(FieldTest, WorksForArgumentOfSubType) {
3800   // Note that the matcher expects DerivedStruct but we say AStruct
3801   // inside Field().
3802   Matcher<const DerivedStruct&> m = Field(&AStruct::x, Ge(0));
3803 
3804   DerivedStruct d;
3805   EXPECT_TRUE(m.Matches(d));
3806   d.x = -1;
3807   EXPECT_FALSE(m.Matches(d));
3808 }
3809 
3810 // Tests that Field(&Foo::field, m) works when field's type and m's
3811 // argument type are compatible but not the same.
TEST(FieldTest,WorksForCompatibleMatcherType)3812 TEST(FieldTest, WorksForCompatibleMatcherType) {
3813   // The field is an int, but the inner matcher expects a signed char.
3814   Matcher<const AStruct&> m = Field(&AStruct::x,
3815                                     Matcher<signed char>(Ge(0)));
3816 
3817   AStruct a;
3818   EXPECT_TRUE(m.Matches(a));
3819   a.x = -1;
3820   EXPECT_FALSE(m.Matches(a));
3821 }
3822 
3823 // Tests that Field() can describe itself.
TEST(FieldTest,CanDescribeSelf)3824 TEST(FieldTest, CanDescribeSelf) {
3825   Matcher<const AStruct&> m = Field(&AStruct::x, Ge(0));
3826 
3827   EXPECT_EQ("is an object whose given field is >= 0", Describe(m));
3828   EXPECT_EQ("is an object whose given field isn't >= 0", DescribeNegation(m));
3829 }
3830 
TEST(FieldTest,CanDescribeSelfWithFieldName)3831 TEST(FieldTest, CanDescribeSelfWithFieldName) {
3832   Matcher<const AStruct&> m = Field("field_name", &AStruct::x, Ge(0));
3833 
3834   EXPECT_EQ("is an object whose field `field_name` is >= 0", Describe(m));
3835   EXPECT_EQ("is an object whose field `field_name` isn't >= 0",
3836             DescribeNegation(m));
3837 }
3838 
3839 // Tests that Field() can explain the match result.
TEST(FieldTest,CanExplainMatchResult)3840 TEST(FieldTest, CanExplainMatchResult) {
3841   Matcher<const AStruct&> m = Field(&AStruct::x, Ge(0));
3842 
3843   AStruct a;
3844   a.x = 1;
3845   EXPECT_EQ("whose given field is 1" + OfType("int"), Explain(m, a));
3846 
3847   m = Field(&AStruct::x, GreaterThan(0));
3848   EXPECT_EQ(
3849       "whose given field is 1" + OfType("int") + ", which is 1 more than 0",
3850       Explain(m, a));
3851 }
3852 
TEST(FieldTest,CanExplainMatchResultWithFieldName)3853 TEST(FieldTest, CanExplainMatchResultWithFieldName) {
3854   Matcher<const AStruct&> m = Field("field_name", &AStruct::x, Ge(0));
3855 
3856   AStruct a;
3857   a.x = 1;
3858   EXPECT_EQ("whose field `field_name` is 1" + OfType("int"), Explain(m, a));
3859 
3860   m = Field("field_name", &AStruct::x, GreaterThan(0));
3861   EXPECT_EQ("whose field `field_name` is 1" + OfType("int") +
3862                 ", which is 1 more than 0",
3863             Explain(m, a));
3864 }
3865 
3866 // Tests that Field() works when the argument is a pointer to const.
TEST(FieldForPointerTest,WorksForPointerToConst)3867 TEST(FieldForPointerTest, WorksForPointerToConst) {
3868   Matcher<const AStruct*> m = Field(&AStruct::x, Ge(0));
3869 
3870   AStruct a;
3871   EXPECT_TRUE(m.Matches(&a));
3872   a.x = -1;
3873   EXPECT_FALSE(m.Matches(&a));
3874 }
3875 
3876 // Tests that Field() works when the argument is a pointer to non-const.
TEST(FieldForPointerTest,WorksForPointerToNonConst)3877 TEST(FieldForPointerTest, WorksForPointerToNonConst) {
3878   Matcher<AStruct*> m = Field(&AStruct::x, Ge(0));
3879 
3880   AStruct a;
3881   EXPECT_TRUE(m.Matches(&a));
3882   a.x = -1;
3883   EXPECT_FALSE(m.Matches(&a));
3884 }
3885 
3886 // Tests that Field() works when the argument is a reference to a const pointer.
TEST(FieldForPointerTest,WorksForReferenceToConstPointer)3887 TEST(FieldForPointerTest, WorksForReferenceToConstPointer) {
3888   Matcher<AStruct* const&> m = Field(&AStruct::x, Ge(0));
3889 
3890   AStruct a;
3891   EXPECT_TRUE(m.Matches(&a));
3892   a.x = -1;
3893   EXPECT_FALSE(m.Matches(&a));
3894 }
3895 
3896 // Tests that Field() does not match the NULL pointer.
TEST(FieldForPointerTest,DoesNotMatchNull)3897 TEST(FieldForPointerTest, DoesNotMatchNull) {
3898   Matcher<const AStruct*> m = Field(&AStruct::x, _);
3899   EXPECT_FALSE(m.Matches(nullptr));
3900 }
3901 
3902 // Tests that Field(&Foo::field, ...) works when the argument's type
3903 // is a sub-type of const Foo*.
TEST(FieldForPointerTest,WorksForArgumentOfSubType)3904 TEST(FieldForPointerTest, WorksForArgumentOfSubType) {
3905   // Note that the matcher expects DerivedStruct but we say AStruct
3906   // inside Field().
3907   Matcher<DerivedStruct*> m = Field(&AStruct::x, Ge(0));
3908 
3909   DerivedStruct d;
3910   EXPECT_TRUE(m.Matches(&d));
3911   d.x = -1;
3912   EXPECT_FALSE(m.Matches(&d));
3913 }
3914 
3915 // Tests that Field() can describe itself when used to match a pointer.
TEST(FieldForPointerTest,CanDescribeSelf)3916 TEST(FieldForPointerTest, CanDescribeSelf) {
3917   Matcher<const AStruct*> m = Field(&AStruct::x, Ge(0));
3918 
3919   EXPECT_EQ("is an object whose given field is >= 0", Describe(m));
3920   EXPECT_EQ("is an object whose given field isn't >= 0", DescribeNegation(m));
3921 }
3922 
TEST(FieldForPointerTest,CanDescribeSelfWithFieldName)3923 TEST(FieldForPointerTest, CanDescribeSelfWithFieldName) {
3924   Matcher<const AStruct*> m = Field("field_name", &AStruct::x, Ge(0));
3925 
3926   EXPECT_EQ("is an object whose field `field_name` is >= 0", Describe(m));
3927   EXPECT_EQ("is an object whose field `field_name` isn't >= 0",
3928             DescribeNegation(m));
3929 }
3930 
3931 // Tests that Field() can explain the result of matching a pointer.
TEST(FieldForPointerTest,CanExplainMatchResult)3932 TEST(FieldForPointerTest, CanExplainMatchResult) {
3933   Matcher<const AStruct*> m = Field(&AStruct::x, Ge(0));
3934 
3935   AStruct a;
3936   a.x = 1;
3937   EXPECT_EQ("", Explain(m, static_cast<const AStruct*>(nullptr)));
3938   EXPECT_EQ("which points to an object whose given field is 1" + OfType("int"),
3939             Explain(m, &a));
3940 
3941   m = Field(&AStruct::x, GreaterThan(0));
3942   EXPECT_EQ("which points to an object whose given field is 1" + OfType("int") +
3943             ", which is 1 more than 0", Explain(m, &a));
3944 }
3945 
TEST(FieldForPointerTest,CanExplainMatchResultWithFieldName)3946 TEST(FieldForPointerTest, CanExplainMatchResultWithFieldName) {
3947   Matcher<const AStruct*> m = Field("field_name", &AStruct::x, Ge(0));
3948 
3949   AStruct a;
3950   a.x = 1;
3951   EXPECT_EQ("", Explain(m, static_cast<const AStruct*>(nullptr)));
3952   EXPECT_EQ(
3953       "which points to an object whose field `field_name` is 1" + OfType("int"),
3954       Explain(m, &a));
3955 
3956   m = Field("field_name", &AStruct::x, GreaterThan(0));
3957   EXPECT_EQ("which points to an object whose field `field_name` is 1" +
3958                 OfType("int") + ", which is 1 more than 0",
3959             Explain(m, &a));
3960 }
3961 
3962 // A user-defined class for testing Property().
3963 class AClass {
3964  public:
AClass()3965   AClass() : n_(0) {}
3966 
3967   // A getter that returns a non-reference.
n() const3968   int n() const { return n_; }
3969 
set_n(int new_n)3970   void set_n(int new_n) { n_ = new_n; }
3971 
3972   // A getter that returns a reference to const.
s() const3973   const std::string& s() const { return s_; }
3974 
s_ref() const3975   const std::string& s_ref() const & { return s_; }
3976 
set_s(const std::string & new_s)3977   void set_s(const std::string& new_s) { s_ = new_s; }
3978 
3979   // A getter that returns a reference to non-const.
x() const3980   double& x() const { return x_; }
3981 
3982  private:
3983   int n_;
3984   std::string s_;
3985 
3986   static double x_;
3987 };
3988 
3989 double AClass::x_ = 0.0;
3990 
3991 // A derived class for testing Property().
3992 class DerivedClass : public AClass {
3993  public:
k() const3994   int k() const { return k_; }
3995  private:
3996   int k_;
3997 };
3998 
3999 // Tests that Property(&Foo::property, ...) works when property()
4000 // returns a non-reference.
TEST(PropertyTest,WorksForNonReferenceProperty)4001 TEST(PropertyTest, WorksForNonReferenceProperty) {
4002   Matcher<const AClass&> m = Property(&AClass::n, Ge(0));
4003   Matcher<const AClass&> m_with_name = Property("n", &AClass::n, Ge(0));
4004 
4005   AClass a;
4006   a.set_n(1);
4007   EXPECT_TRUE(m.Matches(a));
4008   EXPECT_TRUE(m_with_name.Matches(a));
4009 
4010   a.set_n(-1);
4011   EXPECT_FALSE(m.Matches(a));
4012   EXPECT_FALSE(m_with_name.Matches(a));
4013 }
4014 
4015 // Tests that Property(&Foo::property, ...) works when property()
4016 // returns a reference to const.
TEST(PropertyTest,WorksForReferenceToConstProperty)4017 TEST(PropertyTest, WorksForReferenceToConstProperty) {
4018   Matcher<const AClass&> m = Property(&AClass::s, StartsWith("hi"));
4019   Matcher<const AClass&> m_with_name =
4020       Property("s", &AClass::s, StartsWith("hi"));
4021 
4022   AClass a;
4023   a.set_s("hill");
4024   EXPECT_TRUE(m.Matches(a));
4025   EXPECT_TRUE(m_with_name.Matches(a));
4026 
4027   a.set_s("hole");
4028   EXPECT_FALSE(m.Matches(a));
4029   EXPECT_FALSE(m_with_name.Matches(a));
4030 }
4031 
4032 // Tests that Property(&Foo::property, ...) works when property() is
4033 // ref-qualified.
TEST(PropertyTest,WorksForRefQualifiedProperty)4034 TEST(PropertyTest, WorksForRefQualifiedProperty) {
4035   Matcher<const AClass&> m = Property(&AClass::s_ref, StartsWith("hi"));
4036   Matcher<const AClass&> m_with_name =
4037       Property("s", &AClass::s_ref, StartsWith("hi"));
4038 
4039   AClass a;
4040   a.set_s("hill");
4041   EXPECT_TRUE(m.Matches(a));
4042   EXPECT_TRUE(m_with_name.Matches(a));
4043 
4044   a.set_s("hole");
4045   EXPECT_FALSE(m.Matches(a));
4046   EXPECT_FALSE(m_with_name.Matches(a));
4047 }
4048 
4049 // Tests that Property(&Foo::property, ...) works when property()
4050 // returns a reference to non-const.
TEST(PropertyTest,WorksForReferenceToNonConstProperty)4051 TEST(PropertyTest, WorksForReferenceToNonConstProperty) {
4052   double x = 0.0;
4053   AClass a;
4054 
4055   Matcher<const AClass&> m = Property(&AClass::x, Ref(x));
4056   EXPECT_FALSE(m.Matches(a));
4057 
4058   m = Property(&AClass::x, Not(Ref(x)));
4059   EXPECT_TRUE(m.Matches(a));
4060 }
4061 
4062 // Tests that Property(&Foo::property, ...) works when the argument is
4063 // passed by value.
TEST(PropertyTest,WorksForByValueArgument)4064 TEST(PropertyTest, WorksForByValueArgument) {
4065   Matcher<AClass> m = Property(&AClass::s, StartsWith("hi"));
4066 
4067   AClass a;
4068   a.set_s("hill");
4069   EXPECT_TRUE(m.Matches(a));
4070 
4071   a.set_s("hole");
4072   EXPECT_FALSE(m.Matches(a));
4073 }
4074 
4075 // Tests that Property(&Foo::property, ...) works when the argument's
4076 // type is a sub-type of Foo.
TEST(PropertyTest,WorksForArgumentOfSubType)4077 TEST(PropertyTest, WorksForArgumentOfSubType) {
4078   // The matcher expects a DerivedClass, but inside the Property() we
4079   // say AClass.
4080   Matcher<const DerivedClass&> m = Property(&AClass::n, Ge(0));
4081 
4082   DerivedClass d;
4083   d.set_n(1);
4084   EXPECT_TRUE(m.Matches(d));
4085 
4086   d.set_n(-1);
4087   EXPECT_FALSE(m.Matches(d));
4088 }
4089 
4090 // Tests that Property(&Foo::property, m) works when property()'s type
4091 // and m's argument type are compatible but different.
TEST(PropertyTest,WorksForCompatibleMatcherType)4092 TEST(PropertyTest, WorksForCompatibleMatcherType) {
4093   // n() returns an int but the inner matcher expects a signed char.
4094   Matcher<const AClass&> m = Property(&AClass::n,
4095                                       Matcher<signed char>(Ge(0)));
4096 
4097   Matcher<const AClass&> m_with_name =
4098       Property("n", &AClass::n, Matcher<signed char>(Ge(0)));
4099 
4100   AClass a;
4101   EXPECT_TRUE(m.Matches(a));
4102   EXPECT_TRUE(m_with_name.Matches(a));
4103   a.set_n(-1);
4104   EXPECT_FALSE(m.Matches(a));
4105   EXPECT_FALSE(m_with_name.Matches(a));
4106 }
4107 
4108 // Tests that Property() can describe itself.
TEST(PropertyTest,CanDescribeSelf)4109 TEST(PropertyTest, CanDescribeSelf) {
4110   Matcher<const AClass&> m = Property(&AClass::n, Ge(0));
4111 
4112   EXPECT_EQ("is an object whose given property is >= 0", Describe(m));
4113   EXPECT_EQ("is an object whose given property isn't >= 0",
4114             DescribeNegation(m));
4115 }
4116 
TEST(PropertyTest,CanDescribeSelfWithPropertyName)4117 TEST(PropertyTest, CanDescribeSelfWithPropertyName) {
4118   Matcher<const AClass&> m = Property("fancy_name", &AClass::n, Ge(0));
4119 
4120   EXPECT_EQ("is an object whose property `fancy_name` is >= 0", Describe(m));
4121   EXPECT_EQ("is an object whose property `fancy_name` isn't >= 0",
4122             DescribeNegation(m));
4123 }
4124 
4125 // Tests that Property() can explain the match result.
TEST(PropertyTest,CanExplainMatchResult)4126 TEST(PropertyTest, CanExplainMatchResult) {
4127   Matcher<const AClass&> m = Property(&AClass::n, Ge(0));
4128 
4129   AClass a;
4130   a.set_n(1);
4131   EXPECT_EQ("whose given property is 1" + OfType("int"), Explain(m, a));
4132 
4133   m = Property(&AClass::n, GreaterThan(0));
4134   EXPECT_EQ(
4135       "whose given property is 1" + OfType("int") + ", which is 1 more than 0",
4136       Explain(m, a));
4137 }
4138 
TEST(PropertyTest,CanExplainMatchResultWithPropertyName)4139 TEST(PropertyTest, CanExplainMatchResultWithPropertyName) {
4140   Matcher<const AClass&> m = Property("fancy_name", &AClass::n, Ge(0));
4141 
4142   AClass a;
4143   a.set_n(1);
4144   EXPECT_EQ("whose property `fancy_name` is 1" + OfType("int"), Explain(m, a));
4145 
4146   m = Property("fancy_name", &AClass::n, GreaterThan(0));
4147   EXPECT_EQ("whose property `fancy_name` is 1" + OfType("int") +
4148                 ", which is 1 more than 0",
4149             Explain(m, a));
4150 }
4151 
4152 // Tests that Property() works when the argument is a pointer to const.
TEST(PropertyForPointerTest,WorksForPointerToConst)4153 TEST(PropertyForPointerTest, WorksForPointerToConst) {
4154   Matcher<const AClass*> m = Property(&AClass::n, Ge(0));
4155 
4156   AClass a;
4157   a.set_n(1);
4158   EXPECT_TRUE(m.Matches(&a));
4159 
4160   a.set_n(-1);
4161   EXPECT_FALSE(m.Matches(&a));
4162 }
4163 
4164 // Tests that Property() works when the argument is a pointer to non-const.
TEST(PropertyForPointerTest,WorksForPointerToNonConst)4165 TEST(PropertyForPointerTest, WorksForPointerToNonConst) {
4166   Matcher<AClass*> m = Property(&AClass::s, StartsWith("hi"));
4167 
4168   AClass a;
4169   a.set_s("hill");
4170   EXPECT_TRUE(m.Matches(&a));
4171 
4172   a.set_s("hole");
4173   EXPECT_FALSE(m.Matches(&a));
4174 }
4175 
4176 // Tests that Property() works when the argument is a reference to a
4177 // const pointer.
TEST(PropertyForPointerTest,WorksForReferenceToConstPointer)4178 TEST(PropertyForPointerTest, WorksForReferenceToConstPointer) {
4179   Matcher<AClass* const&> m = Property(&AClass::s, StartsWith("hi"));
4180 
4181   AClass a;
4182   a.set_s("hill");
4183   EXPECT_TRUE(m.Matches(&a));
4184 
4185   a.set_s("hole");
4186   EXPECT_FALSE(m.Matches(&a));
4187 }
4188 
4189 // Tests that Property() does not match the NULL pointer.
TEST(PropertyForPointerTest,WorksForReferenceToNonConstProperty)4190 TEST(PropertyForPointerTest, WorksForReferenceToNonConstProperty) {
4191   Matcher<const AClass*> m = Property(&AClass::x, _);
4192   EXPECT_FALSE(m.Matches(nullptr));
4193 }
4194 
4195 // Tests that Property(&Foo::property, ...) works when the argument's
4196 // type is a sub-type of const Foo*.
TEST(PropertyForPointerTest,WorksForArgumentOfSubType)4197 TEST(PropertyForPointerTest, WorksForArgumentOfSubType) {
4198   // The matcher expects a DerivedClass, but inside the Property() we
4199   // say AClass.
4200   Matcher<const DerivedClass*> m = Property(&AClass::n, Ge(0));
4201 
4202   DerivedClass d;
4203   d.set_n(1);
4204   EXPECT_TRUE(m.Matches(&d));
4205 
4206   d.set_n(-1);
4207   EXPECT_FALSE(m.Matches(&d));
4208 }
4209 
4210 // Tests that Property() can describe itself when used to match a pointer.
TEST(PropertyForPointerTest,CanDescribeSelf)4211 TEST(PropertyForPointerTest, CanDescribeSelf) {
4212   Matcher<const AClass*> m = Property(&AClass::n, Ge(0));
4213 
4214   EXPECT_EQ("is an object whose given property is >= 0", Describe(m));
4215   EXPECT_EQ("is an object whose given property isn't >= 0",
4216             DescribeNegation(m));
4217 }
4218 
TEST(PropertyForPointerTest,CanDescribeSelfWithPropertyDescription)4219 TEST(PropertyForPointerTest, CanDescribeSelfWithPropertyDescription) {
4220   Matcher<const AClass*> m = Property("fancy_name", &AClass::n, Ge(0));
4221 
4222   EXPECT_EQ("is an object whose property `fancy_name` is >= 0", Describe(m));
4223   EXPECT_EQ("is an object whose property `fancy_name` isn't >= 0",
4224             DescribeNegation(m));
4225 }
4226 
4227 // Tests that Property() can explain the result of matching a pointer.
TEST(PropertyForPointerTest,CanExplainMatchResult)4228 TEST(PropertyForPointerTest, CanExplainMatchResult) {
4229   Matcher<const AClass*> m = Property(&AClass::n, Ge(0));
4230 
4231   AClass a;
4232   a.set_n(1);
4233   EXPECT_EQ("", Explain(m, static_cast<const AClass*>(nullptr)));
4234   EXPECT_EQ(
4235       "which points to an object whose given property is 1" + OfType("int"),
4236       Explain(m, &a));
4237 
4238   m = Property(&AClass::n, GreaterThan(0));
4239   EXPECT_EQ("which points to an object whose given property is 1" +
4240             OfType("int") + ", which is 1 more than 0",
4241             Explain(m, &a));
4242 }
4243 
TEST(PropertyForPointerTest,CanExplainMatchResultWithPropertyName)4244 TEST(PropertyForPointerTest, CanExplainMatchResultWithPropertyName) {
4245   Matcher<const AClass*> m = Property("fancy_name", &AClass::n, Ge(0));
4246 
4247   AClass a;
4248   a.set_n(1);
4249   EXPECT_EQ("", Explain(m, static_cast<const AClass*>(nullptr)));
4250   EXPECT_EQ("which points to an object whose property `fancy_name` is 1" +
4251                 OfType("int"),
4252             Explain(m, &a));
4253 
4254   m = Property("fancy_name", &AClass::n, GreaterThan(0));
4255   EXPECT_EQ("which points to an object whose property `fancy_name` is 1" +
4256                 OfType("int") + ", which is 1 more than 0",
4257             Explain(m, &a));
4258 }
4259 
4260 // Tests ResultOf.
4261 
4262 // Tests that ResultOf(f, ...) compiles and works as expected when f is a
4263 // function pointer.
IntToStringFunction(int input)4264 std::string IntToStringFunction(int input) {
4265   return input == 1 ? "foo" : "bar";
4266 }
4267 
TEST(ResultOfTest,WorksForFunctionPointers)4268 TEST(ResultOfTest, WorksForFunctionPointers) {
4269   Matcher<int> matcher = ResultOf(&IntToStringFunction, Eq(std::string("foo")));
4270 
4271   EXPECT_TRUE(matcher.Matches(1));
4272   EXPECT_FALSE(matcher.Matches(2));
4273 }
4274 
4275 // Tests that ResultOf() can describe itself.
TEST(ResultOfTest,CanDescribeItself)4276 TEST(ResultOfTest, CanDescribeItself) {
4277   Matcher<int> matcher = ResultOf(&IntToStringFunction, StrEq("foo"));
4278 
4279   EXPECT_EQ("is mapped by the given callable to a value that "
4280             "is equal to \"foo\"", Describe(matcher));
4281   EXPECT_EQ("is mapped by the given callable to a value that "
4282             "isn't equal to \"foo\"", DescribeNegation(matcher));
4283 }
4284 
4285 // Tests that ResultOf() can explain the match result.
IntFunction(int input)4286 int IntFunction(int input) { return input == 42 ? 80 : 90; }
4287 
TEST(ResultOfTest,CanExplainMatchResult)4288 TEST(ResultOfTest, CanExplainMatchResult) {
4289   Matcher<int> matcher = ResultOf(&IntFunction, Ge(85));
4290   EXPECT_EQ("which is mapped by the given callable to 90" + OfType("int"),
4291             Explain(matcher, 36));
4292 
4293   matcher = ResultOf(&IntFunction, GreaterThan(85));
4294   EXPECT_EQ("which is mapped by the given callable to 90" + OfType("int") +
4295             ", which is 5 more than 85", Explain(matcher, 36));
4296 }
4297 
4298 // Tests that ResultOf(f, ...) compiles and works as expected when f(x)
4299 // returns a non-reference.
TEST(ResultOfTest,WorksForNonReferenceResults)4300 TEST(ResultOfTest, WorksForNonReferenceResults) {
4301   Matcher<int> matcher = ResultOf(&IntFunction, Eq(80));
4302 
4303   EXPECT_TRUE(matcher.Matches(42));
4304   EXPECT_FALSE(matcher.Matches(36));
4305 }
4306 
4307 // Tests that ResultOf(f, ...) compiles and works as expected when f(x)
4308 // returns a reference to non-const.
DoubleFunction(double & input)4309 double& DoubleFunction(double& input) { return input; }  // NOLINT
4310 
RefUncopyableFunction(Uncopyable & obj)4311 Uncopyable& RefUncopyableFunction(Uncopyable& obj) {  // NOLINT
4312   return obj;
4313 }
4314 
TEST(ResultOfTest,WorksForReferenceToNonConstResults)4315 TEST(ResultOfTest, WorksForReferenceToNonConstResults) {
4316   double x = 3.14;
4317   double x2 = x;
4318   Matcher<double&> matcher = ResultOf(&DoubleFunction, Ref(x));
4319 
4320   EXPECT_TRUE(matcher.Matches(x));
4321   EXPECT_FALSE(matcher.Matches(x2));
4322 
4323   // Test that ResultOf works with uncopyable objects
4324   Uncopyable obj(0);
4325   Uncopyable obj2(0);
4326   Matcher<Uncopyable&> matcher2 =
4327       ResultOf(&RefUncopyableFunction, Ref(obj));
4328 
4329   EXPECT_TRUE(matcher2.Matches(obj));
4330   EXPECT_FALSE(matcher2.Matches(obj2));
4331 }
4332 
4333 // Tests that ResultOf(f, ...) compiles and works as expected when f(x)
4334 // returns a reference to const.
StringFunction(const std::string & input)4335 const std::string& StringFunction(const std::string& input) { return input; }
4336 
TEST(ResultOfTest,WorksForReferenceToConstResults)4337 TEST(ResultOfTest, WorksForReferenceToConstResults) {
4338   std::string s = "foo";
4339   std::string s2 = s;
4340   Matcher<const std::string&> matcher = ResultOf(&StringFunction, Ref(s));
4341 
4342   EXPECT_TRUE(matcher.Matches(s));
4343   EXPECT_FALSE(matcher.Matches(s2));
4344 }
4345 
4346 // Tests that ResultOf(f, m) works when f(x) and m's
4347 // argument types are compatible but different.
TEST(ResultOfTest,WorksForCompatibleMatcherTypes)4348 TEST(ResultOfTest, WorksForCompatibleMatcherTypes) {
4349   // IntFunction() returns int but the inner matcher expects a signed char.
4350   Matcher<int> matcher = ResultOf(IntFunction, Matcher<signed char>(Ge(85)));
4351 
4352   EXPECT_TRUE(matcher.Matches(36));
4353   EXPECT_FALSE(matcher.Matches(42));
4354 }
4355 
4356 // Tests that the program aborts when ResultOf is passed
4357 // a NULL function pointer.
TEST(ResultOfDeathTest,DiesOnNullFunctionPointers)4358 TEST(ResultOfDeathTest, DiesOnNullFunctionPointers) {
4359   EXPECT_DEATH_IF_SUPPORTED(
4360       ResultOf(static_cast<std::string (*)(int dummy)>(nullptr),
4361                Eq(std::string("foo"))),
4362       "NULL function pointer is passed into ResultOf\\(\\)\\.");
4363 }
4364 
4365 // Tests that ResultOf(f, ...) compiles and works as expected when f is a
4366 // function reference.
TEST(ResultOfTest,WorksForFunctionReferences)4367 TEST(ResultOfTest, WorksForFunctionReferences) {
4368   Matcher<int> matcher = ResultOf(IntToStringFunction, StrEq("foo"));
4369   EXPECT_TRUE(matcher.Matches(1));
4370   EXPECT_FALSE(matcher.Matches(2));
4371 }
4372 
4373 // Tests that ResultOf(f, ...) compiles and works as expected when f is a
4374 // function object.
4375 struct Functor {
operator ()testing::gmock_matchers_test::__anon86e4b7b50111::Functor4376   std::string operator()(int input) const {
4377     return IntToStringFunction(input);
4378   }
4379 };
4380 
TEST(ResultOfTest,WorksForFunctors)4381 TEST(ResultOfTest, WorksForFunctors) {
4382   Matcher<int> matcher = ResultOf(Functor(), Eq(std::string("foo")));
4383 
4384   EXPECT_TRUE(matcher.Matches(1));
4385   EXPECT_FALSE(matcher.Matches(2));
4386 }
4387 
4388 // Tests that ResultOf(f, ...) compiles and works as expected when f is a
4389 // functor with more than one operator() defined. ResultOf() must work
4390 // for each defined operator().
4391 struct PolymorphicFunctor {
4392   typedef int result_type;
operator ()testing::gmock_matchers_test::__anon86e4b7b50111::PolymorphicFunctor4393   int operator()(int n) { return n; }
operator ()testing::gmock_matchers_test::__anon86e4b7b50111::PolymorphicFunctor4394   int operator()(const char* s) { return static_cast<int>(strlen(s)); }
operator ()testing::gmock_matchers_test::__anon86e4b7b50111::PolymorphicFunctor4395   std::string operator()(int *p) { return p ? "good ptr" : "null"; }
4396 };
4397 
TEST(ResultOfTest,WorksForPolymorphicFunctors)4398 TEST(ResultOfTest, WorksForPolymorphicFunctors) {
4399   Matcher<int> matcher_int = ResultOf(PolymorphicFunctor(), Ge(5));
4400 
4401   EXPECT_TRUE(matcher_int.Matches(10));
4402   EXPECT_FALSE(matcher_int.Matches(2));
4403 
4404   Matcher<const char*> matcher_string = ResultOf(PolymorphicFunctor(), Ge(5));
4405 
4406   EXPECT_TRUE(matcher_string.Matches("long string"));
4407   EXPECT_FALSE(matcher_string.Matches("shrt"));
4408 }
4409 
TEST(ResultOfTest,WorksForPolymorphicFunctorsIgnoringResultType)4410 TEST(ResultOfTest, WorksForPolymorphicFunctorsIgnoringResultType) {
4411   Matcher<int*> matcher = ResultOf(PolymorphicFunctor(), "good ptr");
4412 
4413   int n = 0;
4414   EXPECT_TRUE(matcher.Matches(&n));
4415   EXPECT_FALSE(matcher.Matches(nullptr));
4416 }
4417 
TEST(ResultOfTest,WorksForLambdas)4418 TEST(ResultOfTest, WorksForLambdas) {
4419   Matcher<int> matcher = ResultOf(
4420       [](int str_len) {
4421         return std::string(static_cast<size_t>(str_len), 'x');
4422       },
4423       "xxx");
4424   EXPECT_TRUE(matcher.Matches(3));
4425   EXPECT_FALSE(matcher.Matches(1));
4426 }
4427 
TEST(ResultOfTest,WorksForNonCopyableArguments)4428 TEST(ResultOfTest, WorksForNonCopyableArguments) {
4429   Matcher<std::unique_ptr<int>> matcher = ResultOf(
4430       [](const std::unique_ptr<int>& str_len) {
4431         return std::string(static_cast<size_t>(*str_len), 'x');
4432       },
4433       "xxx");
4434   EXPECT_TRUE(matcher.Matches(std::unique_ptr<int>(new int(3))));
4435   EXPECT_FALSE(matcher.Matches(std::unique_ptr<int>(new int(1))));
4436 }
4437 
ReferencingFunction(const int & n)4438 const int* ReferencingFunction(const int& n) { return &n; }
4439 
4440 struct ReferencingFunctor {
4441   typedef const int* result_type;
operator ()testing::gmock_matchers_test::__anon86e4b7b50111::ReferencingFunctor4442   result_type operator()(const int& n) { return &n; }
4443 };
4444 
TEST(ResultOfTest,WorksForReferencingCallables)4445 TEST(ResultOfTest, WorksForReferencingCallables) {
4446   const int n = 1;
4447   const int n2 = 1;
4448   Matcher<const int&> matcher2 = ResultOf(ReferencingFunction, Eq(&n));
4449   EXPECT_TRUE(matcher2.Matches(n));
4450   EXPECT_FALSE(matcher2.Matches(n2));
4451 
4452   Matcher<const int&> matcher3 = ResultOf(ReferencingFunctor(), Eq(&n));
4453   EXPECT_TRUE(matcher3.Matches(n));
4454   EXPECT_FALSE(matcher3.Matches(n2));
4455 }
4456 
4457 class DivisibleByImpl {
4458  public:
DivisibleByImpl(int a_divider)4459   explicit DivisibleByImpl(int a_divider) : divider_(a_divider) {}
4460 
4461   // For testing using ExplainMatchResultTo() with polymorphic matchers.
4462   template <typename T>
MatchAndExplain(const T & n,MatchResultListener * listener) const4463   bool MatchAndExplain(const T& n, MatchResultListener* listener) const {
4464     *listener << "which is " << (n % divider_) << " modulo "
4465               << divider_;
4466     return (n % divider_) == 0;
4467   }
4468 
DescribeTo(ostream * os) const4469   void DescribeTo(ostream* os) const {
4470     *os << "is divisible by " << divider_;
4471   }
4472 
DescribeNegationTo(ostream * os) const4473   void DescribeNegationTo(ostream* os) const {
4474     *os << "is not divisible by " << divider_;
4475   }
4476 
set_divider(int a_divider)4477   void set_divider(int a_divider) { divider_ = a_divider; }
divider() const4478   int divider() const { return divider_; }
4479 
4480  private:
4481   int divider_;
4482 };
4483 
DivisibleBy(int n)4484 PolymorphicMatcher<DivisibleByImpl> DivisibleBy(int n) {
4485   return MakePolymorphicMatcher(DivisibleByImpl(n));
4486 }
4487 
4488 // Tests that when AllOf() fails, only the first failing matcher is
4489 // asked to explain why.
TEST(ExplainMatchResultTest,AllOf_False_False)4490 TEST(ExplainMatchResultTest, AllOf_False_False) {
4491   const Matcher<int> m = AllOf(DivisibleBy(4), DivisibleBy(3));
4492   EXPECT_EQ("which is 1 modulo 4", Explain(m, 5));
4493 }
4494 
4495 // Tests that when AllOf() fails, only the first failing matcher is
4496 // asked to explain why.
TEST(ExplainMatchResultTest,AllOf_False_True)4497 TEST(ExplainMatchResultTest, AllOf_False_True) {
4498   const Matcher<int> m = AllOf(DivisibleBy(4), DivisibleBy(3));
4499   EXPECT_EQ("which is 2 modulo 4", Explain(m, 6));
4500 }
4501 
4502 // Tests that when AllOf() fails, only the first failing matcher is
4503 // asked to explain why.
TEST(ExplainMatchResultTest,AllOf_True_False)4504 TEST(ExplainMatchResultTest, AllOf_True_False) {
4505   const Matcher<int> m = AllOf(Ge(1), DivisibleBy(3));
4506   EXPECT_EQ("which is 2 modulo 3", Explain(m, 5));
4507 }
4508 
4509 // Tests that when AllOf() succeeds, all matchers are asked to explain
4510 // why.
TEST(ExplainMatchResultTest,AllOf_True_True)4511 TEST(ExplainMatchResultTest, AllOf_True_True) {
4512   const Matcher<int> m = AllOf(DivisibleBy(2), DivisibleBy(3));
4513   EXPECT_EQ("which is 0 modulo 2, and which is 0 modulo 3", Explain(m, 6));
4514 }
4515 
TEST(ExplainMatchResultTest,AllOf_True_True_2)4516 TEST(ExplainMatchResultTest, AllOf_True_True_2) {
4517   const Matcher<int> m = AllOf(Ge(2), Le(3));
4518   EXPECT_EQ("", Explain(m, 2));
4519 }
4520 
TEST(ExplainmatcherResultTest,MonomorphicMatcher)4521 TEST(ExplainmatcherResultTest, MonomorphicMatcher) {
4522   const Matcher<int> m = GreaterThan(5);
4523   EXPECT_EQ("which is 1 more than 5", Explain(m, 6));
4524 }
4525 
4526 // The following two tests verify that values without a public copy
4527 // ctor can be used as arguments to matchers like Eq(), Ge(), and etc
4528 // with the help of ByRef().
4529 
4530 class NotCopyable {
4531  public:
NotCopyable(int a_value)4532   explicit NotCopyable(int a_value) : value_(a_value) {}
4533 
value() const4534   int value() const { return value_; }
4535 
operator ==(const NotCopyable & rhs) const4536   bool operator==(const NotCopyable& rhs) const {
4537     return value() == rhs.value();
4538   }
4539 
operator >=(const NotCopyable & rhs) const4540   bool operator>=(const NotCopyable& rhs) const {
4541     return value() >= rhs.value();
4542   }
4543  private:
4544   int value_;
4545 
4546   GTEST_DISALLOW_COPY_AND_ASSIGN_(NotCopyable);
4547 };
4548 
TEST(ByRefTest,AllowsNotCopyableConstValueInMatchers)4549 TEST(ByRefTest, AllowsNotCopyableConstValueInMatchers) {
4550   const NotCopyable const_value1(1);
4551   const Matcher<const NotCopyable&> m = Eq(ByRef(const_value1));
4552 
4553   const NotCopyable n1(1), n2(2);
4554   EXPECT_TRUE(m.Matches(n1));
4555   EXPECT_FALSE(m.Matches(n2));
4556 }
4557 
TEST(ByRefTest,AllowsNotCopyableValueInMatchers)4558 TEST(ByRefTest, AllowsNotCopyableValueInMatchers) {
4559   NotCopyable value2(2);
4560   const Matcher<NotCopyable&> m = Ge(ByRef(value2));
4561 
4562   NotCopyable n1(1), n2(2);
4563   EXPECT_FALSE(m.Matches(n1));
4564   EXPECT_TRUE(m.Matches(n2));
4565 }
4566 
TEST(IsEmptyTest,ImplementsIsEmpty)4567 TEST(IsEmptyTest, ImplementsIsEmpty) {
4568   vector<int> container;
4569   EXPECT_THAT(container, IsEmpty());
4570   container.push_back(0);
4571   EXPECT_THAT(container, Not(IsEmpty()));
4572   container.push_back(1);
4573   EXPECT_THAT(container, Not(IsEmpty()));
4574 }
4575 
TEST(IsEmptyTest,WorksWithString)4576 TEST(IsEmptyTest, WorksWithString) {
4577   std::string text;
4578   EXPECT_THAT(text, IsEmpty());
4579   text = "foo";
4580   EXPECT_THAT(text, Not(IsEmpty()));
4581   text = std::string("\0", 1);
4582   EXPECT_THAT(text, Not(IsEmpty()));
4583 }
4584 
TEST(IsEmptyTest,CanDescribeSelf)4585 TEST(IsEmptyTest, CanDescribeSelf) {
4586   Matcher<vector<int> > m = IsEmpty();
4587   EXPECT_EQ("is empty", Describe(m));
4588   EXPECT_EQ("isn't empty", DescribeNegation(m));
4589 }
4590 
TEST(IsEmptyTest,ExplainsResult)4591 TEST(IsEmptyTest, ExplainsResult) {
4592   Matcher<vector<int> > m = IsEmpty();
4593   vector<int> container;
4594   EXPECT_EQ("", Explain(m, container));
4595   container.push_back(0);
4596   EXPECT_EQ("whose size is 1", Explain(m, container));
4597 }
4598 
TEST(IsEmptyTest,WorksWithMoveOnly)4599 TEST(IsEmptyTest, WorksWithMoveOnly) {
4600   ContainerHelper helper;
4601   EXPECT_CALL(helper, Call(IsEmpty()));
4602   helper.Call({});
4603 }
4604 
TEST(IsTrueTest,IsTrueIsFalse)4605 TEST(IsTrueTest, IsTrueIsFalse) {
4606   EXPECT_THAT(true, IsTrue());
4607   EXPECT_THAT(false, IsFalse());
4608   EXPECT_THAT(true, Not(IsFalse()));
4609   EXPECT_THAT(false, Not(IsTrue()));
4610   EXPECT_THAT(0, Not(IsTrue()));
4611   EXPECT_THAT(0, IsFalse());
4612   EXPECT_THAT(nullptr, Not(IsTrue()));
4613   EXPECT_THAT(nullptr, IsFalse());
4614   EXPECT_THAT(-1, IsTrue());
4615   EXPECT_THAT(-1, Not(IsFalse()));
4616   EXPECT_THAT(1, IsTrue());
4617   EXPECT_THAT(1, Not(IsFalse()));
4618   EXPECT_THAT(2, IsTrue());
4619   EXPECT_THAT(2, Not(IsFalse()));
4620   int a = 42;
4621   EXPECT_THAT(a, IsTrue());
4622   EXPECT_THAT(a, Not(IsFalse()));
4623   EXPECT_THAT(&a, IsTrue());
4624   EXPECT_THAT(&a, Not(IsFalse()));
4625   EXPECT_THAT(false, Not(IsTrue()));
4626   EXPECT_THAT(true, Not(IsFalse()));
4627   EXPECT_THAT(std::true_type(), IsTrue());
4628   EXPECT_THAT(std::true_type(), Not(IsFalse()));
4629   EXPECT_THAT(std::false_type(), IsFalse());
4630   EXPECT_THAT(std::false_type(), Not(IsTrue()));
4631   EXPECT_THAT(nullptr, Not(IsTrue()));
4632   EXPECT_THAT(nullptr, IsFalse());
4633   std::unique_ptr<int> null_unique;
4634   std::unique_ptr<int> nonnull_unique(new int(0));
4635   EXPECT_THAT(null_unique, Not(IsTrue()));
4636   EXPECT_THAT(null_unique, IsFalse());
4637   EXPECT_THAT(nonnull_unique, IsTrue());
4638   EXPECT_THAT(nonnull_unique, Not(IsFalse()));
4639 }
4640 
TEST(SizeIsTest,ImplementsSizeIs)4641 TEST(SizeIsTest, ImplementsSizeIs) {
4642   vector<int> container;
4643   EXPECT_THAT(container, SizeIs(0));
4644   EXPECT_THAT(container, Not(SizeIs(1)));
4645   container.push_back(0);
4646   EXPECT_THAT(container, Not(SizeIs(0)));
4647   EXPECT_THAT(container, SizeIs(1));
4648   container.push_back(0);
4649   EXPECT_THAT(container, Not(SizeIs(0)));
4650   EXPECT_THAT(container, SizeIs(2));
4651 }
4652 
TEST(SizeIsTest,WorksWithMap)4653 TEST(SizeIsTest, WorksWithMap) {
4654   map<std::string, int> container;
4655   EXPECT_THAT(container, SizeIs(0));
4656   EXPECT_THAT(container, Not(SizeIs(1)));
4657   container.insert(make_pair("foo", 1));
4658   EXPECT_THAT(container, Not(SizeIs(0)));
4659   EXPECT_THAT(container, SizeIs(1));
4660   container.insert(make_pair("bar", 2));
4661   EXPECT_THAT(container, Not(SizeIs(0)));
4662   EXPECT_THAT(container, SizeIs(2));
4663 }
4664 
TEST(SizeIsTest,WorksWithReferences)4665 TEST(SizeIsTest, WorksWithReferences) {
4666   vector<int> container;
4667   Matcher<const vector<int>&> m = SizeIs(1);
4668   EXPECT_THAT(container, Not(m));
4669   container.push_back(0);
4670   EXPECT_THAT(container, m);
4671 }
4672 
TEST(SizeIsTest,WorksWithMoveOnly)4673 TEST(SizeIsTest, WorksWithMoveOnly) {
4674   ContainerHelper helper;
4675   EXPECT_CALL(helper, Call(SizeIs(3)));
4676   helper.Call(MakeUniquePtrs({1, 2, 3}));
4677 }
4678 
4679 // SizeIs should work for any type that provides a size() member function.
4680 // For example, a size_type member type should not need to be provided.
4681 struct MinimalistCustomType {
sizetesting::gmock_matchers_test::__anon86e4b7b50111::MinimalistCustomType4682   int size() const { return 1; }
4683 };
TEST(SizeIsTest,WorksWithMinimalistCustomType)4684 TEST(SizeIsTest, WorksWithMinimalistCustomType) {
4685   MinimalistCustomType container;
4686   EXPECT_THAT(container, SizeIs(1));
4687   EXPECT_THAT(container, Not(SizeIs(0)));
4688 }
4689 
TEST(SizeIsTest,CanDescribeSelf)4690 TEST(SizeIsTest, CanDescribeSelf) {
4691   Matcher<vector<int> > m = SizeIs(2);
4692   EXPECT_EQ("size is equal to 2", Describe(m));
4693   EXPECT_EQ("size isn't equal to 2", DescribeNegation(m));
4694 }
4695 
TEST(SizeIsTest,ExplainsResult)4696 TEST(SizeIsTest, ExplainsResult) {
4697   Matcher<vector<int> > m1 = SizeIs(2);
4698   Matcher<vector<int> > m2 = SizeIs(Lt(2u));
4699   Matcher<vector<int> > m3 = SizeIs(AnyOf(0, 3));
4700   Matcher<vector<int> > m4 = SizeIs(GreaterThan(1));
4701   vector<int> container;
4702   EXPECT_EQ("whose size 0 doesn't match", Explain(m1, container));
4703   EXPECT_EQ("whose size 0 matches", Explain(m2, container));
4704   EXPECT_EQ("whose size 0 matches", Explain(m3, container));
4705   EXPECT_EQ("whose size 0 doesn't match, which is 1 less than 1",
4706             Explain(m4, container));
4707   container.push_back(0);
4708   container.push_back(0);
4709   EXPECT_EQ("whose size 2 matches", Explain(m1, container));
4710   EXPECT_EQ("whose size 2 doesn't match", Explain(m2, container));
4711   EXPECT_EQ("whose size 2 doesn't match", Explain(m3, container));
4712   EXPECT_EQ("whose size 2 matches, which is 1 more than 1",
4713             Explain(m4, container));
4714 }
4715 
4716 #if GTEST_HAS_TYPED_TEST
4717 // Tests ContainerEq with different container types, and
4718 // different element types.
4719 
4720 template <typename T>
4721 class ContainerEqTest : public testing::Test {};
4722 
4723 typedef testing::Types<
4724     set<int>,
4725     vector<size_t>,
4726     multiset<size_t>,
4727     list<int> >
4728     ContainerEqTestTypes;
4729 
4730 TYPED_TEST_SUITE(ContainerEqTest, ContainerEqTestTypes);
4731 
4732 // Tests that the filled container is equal to itself.
TYPED_TEST(ContainerEqTest,EqualsSelf)4733 TYPED_TEST(ContainerEqTest, EqualsSelf) {
4734   static const int vals[] = {1, 1, 2, 3, 5, 8};
4735   TypeParam my_set(vals, vals + 6);
4736   const Matcher<TypeParam> m = ContainerEq(my_set);
4737   EXPECT_TRUE(m.Matches(my_set));
4738   EXPECT_EQ("", Explain(m, my_set));
4739 }
4740 
4741 // Tests that missing values are reported.
TYPED_TEST(ContainerEqTest,ValueMissing)4742 TYPED_TEST(ContainerEqTest, ValueMissing) {
4743   static const int vals[] = {1, 1, 2, 3, 5, 8};
4744   static const int test_vals[] = {2, 1, 8, 5};
4745   TypeParam my_set(vals, vals + 6);
4746   TypeParam test_set(test_vals, test_vals + 4);
4747   const Matcher<TypeParam> m = ContainerEq(my_set);
4748   EXPECT_FALSE(m.Matches(test_set));
4749   EXPECT_EQ("which doesn't have these expected elements: 3",
4750             Explain(m, test_set));
4751 }
4752 
4753 // Tests that added values are reported.
TYPED_TEST(ContainerEqTest,ValueAdded)4754 TYPED_TEST(ContainerEqTest, ValueAdded) {
4755   static const int vals[] = {1, 1, 2, 3, 5, 8};
4756   static const int test_vals[] = {1, 2, 3, 5, 8, 46};
4757   TypeParam my_set(vals, vals + 6);
4758   TypeParam test_set(test_vals, test_vals + 6);
4759   const Matcher<const TypeParam&> m = ContainerEq(my_set);
4760   EXPECT_FALSE(m.Matches(test_set));
4761   EXPECT_EQ("which has these unexpected elements: 46", Explain(m, test_set));
4762 }
4763 
4764 // Tests that added and missing values are reported together.
TYPED_TEST(ContainerEqTest,ValueAddedAndRemoved)4765 TYPED_TEST(ContainerEqTest, ValueAddedAndRemoved) {
4766   static const int vals[] = {1, 1, 2, 3, 5, 8};
4767   static const int test_vals[] = {1, 2, 3, 8, 46};
4768   TypeParam my_set(vals, vals + 6);
4769   TypeParam test_set(test_vals, test_vals + 5);
4770   const Matcher<TypeParam> m = ContainerEq(my_set);
4771   EXPECT_FALSE(m.Matches(test_set));
4772   EXPECT_EQ("which has these unexpected elements: 46,\n"
4773             "and doesn't have these expected elements: 5",
4774             Explain(m, test_set));
4775 }
4776 
4777 // Tests duplicated value -- expect no explanation.
TYPED_TEST(ContainerEqTest,DuplicateDifference)4778 TYPED_TEST(ContainerEqTest, DuplicateDifference) {
4779   static const int vals[] = {1, 1, 2, 3, 5, 8};
4780   static const int test_vals[] = {1, 2, 3, 5, 8};
4781   TypeParam my_set(vals, vals + 6);
4782   TypeParam test_set(test_vals, test_vals + 5);
4783   const Matcher<const TypeParam&> m = ContainerEq(my_set);
4784   // Depending on the container, match may be true or false
4785   // But in any case there should be no explanation.
4786   EXPECT_EQ("", Explain(m, test_set));
4787 }
4788 #endif  // GTEST_HAS_TYPED_TEST
4789 
4790 // Tests that multiple missing values are reported.
4791 // Using just vector here, so order is predictable.
TEST(ContainerEqExtraTest,MultipleValuesMissing)4792 TEST(ContainerEqExtraTest, MultipleValuesMissing) {
4793   static const int vals[] = {1, 1, 2, 3, 5, 8};
4794   static const int test_vals[] = {2, 1, 5};
4795   vector<int> my_set(vals, vals + 6);
4796   vector<int> test_set(test_vals, test_vals + 3);
4797   const Matcher<vector<int> > m = ContainerEq(my_set);
4798   EXPECT_FALSE(m.Matches(test_set));
4799   EXPECT_EQ("which doesn't have these expected elements: 3, 8",
4800             Explain(m, test_set));
4801 }
4802 
4803 // Tests that added values are reported.
4804 // Using just vector here, so order is predictable.
TEST(ContainerEqExtraTest,MultipleValuesAdded)4805 TEST(ContainerEqExtraTest, MultipleValuesAdded) {
4806   static const int vals[] = {1, 1, 2, 3, 5, 8};
4807   static const int test_vals[] = {1, 2, 92, 3, 5, 8, 46};
4808   list<size_t> my_set(vals, vals + 6);
4809   list<size_t> test_set(test_vals, test_vals + 7);
4810   const Matcher<const list<size_t>&> m = ContainerEq(my_set);
4811   EXPECT_FALSE(m.Matches(test_set));
4812   EXPECT_EQ("which has these unexpected elements: 92, 46",
4813             Explain(m, test_set));
4814 }
4815 
4816 // Tests that added and missing values are reported together.
TEST(ContainerEqExtraTest,MultipleValuesAddedAndRemoved)4817 TEST(ContainerEqExtraTest, MultipleValuesAddedAndRemoved) {
4818   static const int vals[] = {1, 1, 2, 3, 5, 8};
4819   static const int test_vals[] = {1, 2, 3, 92, 46};
4820   list<size_t> my_set(vals, vals + 6);
4821   list<size_t> test_set(test_vals, test_vals + 5);
4822   const Matcher<const list<size_t> > m = ContainerEq(my_set);
4823   EXPECT_FALSE(m.Matches(test_set));
4824   EXPECT_EQ("which has these unexpected elements: 92, 46,\n"
4825             "and doesn't have these expected elements: 5, 8",
4826             Explain(m, test_set));
4827 }
4828 
4829 // Tests to see that duplicate elements are detected,
4830 // but (as above) not reported in the explanation.
TEST(ContainerEqExtraTest,MultiSetOfIntDuplicateDifference)4831 TEST(ContainerEqExtraTest, MultiSetOfIntDuplicateDifference) {
4832   static const int vals[] = {1, 1, 2, 3, 5, 8};
4833   static const int test_vals[] = {1, 2, 3, 5, 8};
4834   vector<int> my_set(vals, vals + 6);
4835   vector<int> test_set(test_vals, test_vals + 5);
4836   const Matcher<vector<int> > m = ContainerEq(my_set);
4837   EXPECT_TRUE(m.Matches(my_set));
4838   EXPECT_FALSE(m.Matches(test_set));
4839   // There is nothing to report when both sets contain all the same values.
4840   EXPECT_EQ("", Explain(m, test_set));
4841 }
4842 
4843 // Tests that ContainerEq works for non-trivial associative containers,
4844 // like maps.
TEST(ContainerEqExtraTest,WorksForMaps)4845 TEST(ContainerEqExtraTest, WorksForMaps) {
4846   map<int, std::string> my_map;
4847   my_map[0] = "a";
4848   my_map[1] = "b";
4849 
4850   map<int, std::string> test_map;
4851   test_map[0] = "aa";
4852   test_map[1] = "b";
4853 
4854   const Matcher<const map<int, std::string>&> m = ContainerEq(my_map);
4855   EXPECT_TRUE(m.Matches(my_map));
4856   EXPECT_FALSE(m.Matches(test_map));
4857 
4858   EXPECT_EQ("which has these unexpected elements: (0, \"aa\"),\n"
4859             "and doesn't have these expected elements: (0, \"a\")",
4860             Explain(m, test_map));
4861 }
4862 
TEST(ContainerEqExtraTest,WorksForNativeArray)4863 TEST(ContainerEqExtraTest, WorksForNativeArray) {
4864   int a1[] = {1, 2, 3};
4865   int a2[] = {1, 2, 3};
4866   int b[] = {1, 2, 4};
4867 
4868   EXPECT_THAT(a1, ContainerEq(a2));
4869   EXPECT_THAT(a1, Not(ContainerEq(b)));
4870 }
4871 
TEST(ContainerEqExtraTest,WorksForTwoDimensionalNativeArray)4872 TEST(ContainerEqExtraTest, WorksForTwoDimensionalNativeArray) {
4873   const char a1[][3] = {"hi", "lo"};
4874   const char a2[][3] = {"hi", "lo"};
4875   const char b[][3] = {"lo", "hi"};
4876 
4877   // Tests using ContainerEq() in the first dimension.
4878   EXPECT_THAT(a1, ContainerEq(a2));
4879   EXPECT_THAT(a1, Not(ContainerEq(b)));
4880 
4881   // Tests using ContainerEq() in the second dimension.
4882   EXPECT_THAT(a1, ElementsAre(ContainerEq(a2[0]), ContainerEq(a2[1])));
4883   EXPECT_THAT(a1, ElementsAre(Not(ContainerEq(b[0])), ContainerEq(a2[1])));
4884 }
4885 
TEST(ContainerEqExtraTest,WorksForNativeArrayAsTuple)4886 TEST(ContainerEqExtraTest, WorksForNativeArrayAsTuple) {
4887   const int a1[] = {1, 2, 3};
4888   const int a2[] = {1, 2, 3};
4889   const int b[] = {1, 2, 3, 4};
4890 
4891   const int* const p1 = a1;
4892   EXPECT_THAT(std::make_tuple(p1, 3), ContainerEq(a2));
4893   EXPECT_THAT(std::make_tuple(p1, 3), Not(ContainerEq(b)));
4894 
4895   const int c[] = {1, 3, 2};
4896   EXPECT_THAT(std::make_tuple(p1, 3), Not(ContainerEq(c)));
4897 }
4898 
TEST(ContainerEqExtraTest,CopiesNativeArrayParameter)4899 TEST(ContainerEqExtraTest, CopiesNativeArrayParameter) {
4900   std::string a1[][3] = {
4901     {"hi", "hello", "ciao"},
4902     {"bye", "see you", "ciao"}
4903   };
4904 
4905   std::string a2[][3] = {
4906     {"hi", "hello", "ciao"},
4907     {"bye", "see you", "ciao"}
4908   };
4909 
4910   const Matcher<const std::string(&)[2][3]> m = ContainerEq(a2);
4911   EXPECT_THAT(a1, m);
4912 
4913   a2[0][0] = "ha";
4914   EXPECT_THAT(a1, m);
4915 }
4916 
TEST(WhenSortedByTest,WorksForEmptyContainer)4917 TEST(WhenSortedByTest, WorksForEmptyContainer) {
4918   const vector<int> numbers;
4919   EXPECT_THAT(numbers, WhenSortedBy(less<int>(), ElementsAre()));
4920   EXPECT_THAT(numbers, Not(WhenSortedBy(less<int>(), ElementsAre(1))));
4921 }
4922 
TEST(WhenSortedByTest,WorksForNonEmptyContainer)4923 TEST(WhenSortedByTest, WorksForNonEmptyContainer) {
4924   vector<unsigned> numbers;
4925   numbers.push_back(3);
4926   numbers.push_back(1);
4927   numbers.push_back(2);
4928   numbers.push_back(2);
4929   EXPECT_THAT(numbers, WhenSortedBy(greater<unsigned>(),
4930                                     ElementsAre(3, 2, 2, 1)));
4931   EXPECT_THAT(numbers, Not(WhenSortedBy(greater<unsigned>(),
4932                                         ElementsAre(1, 2, 2, 3))));
4933 }
4934 
TEST(WhenSortedByTest,WorksForNonVectorContainer)4935 TEST(WhenSortedByTest, WorksForNonVectorContainer) {
4936   list<std::string> words;
4937   words.push_back("say");
4938   words.push_back("hello");
4939   words.push_back("world");
4940   EXPECT_THAT(words, WhenSortedBy(less<std::string>(),
4941                                   ElementsAre("hello", "say", "world")));
4942   EXPECT_THAT(words, Not(WhenSortedBy(less<std::string>(),
4943                                       ElementsAre("say", "hello", "world"))));
4944 }
4945 
TEST(WhenSortedByTest,WorksForNativeArray)4946 TEST(WhenSortedByTest, WorksForNativeArray) {
4947   const int numbers[] = {1, 3, 2, 4};
4948   const int sorted_numbers[] = {1, 2, 3, 4};
4949   EXPECT_THAT(numbers, WhenSortedBy(less<int>(), ElementsAre(1, 2, 3, 4)));
4950   EXPECT_THAT(numbers, WhenSortedBy(less<int>(),
4951                                     ElementsAreArray(sorted_numbers)));
4952   EXPECT_THAT(numbers, Not(WhenSortedBy(less<int>(), ElementsAre(1, 3, 2, 4))));
4953 }
4954 
TEST(WhenSortedByTest,CanDescribeSelf)4955 TEST(WhenSortedByTest, CanDescribeSelf) {
4956   const Matcher<vector<int> > m = WhenSortedBy(less<int>(), ElementsAre(1, 2));
4957   EXPECT_EQ("(when sorted) has 2 elements where\n"
4958             "element #0 is equal to 1,\n"
4959             "element #1 is equal to 2",
4960             Describe(m));
4961   EXPECT_EQ("(when sorted) doesn't have 2 elements, or\n"
4962             "element #0 isn't equal to 1, or\n"
4963             "element #1 isn't equal to 2",
4964             DescribeNegation(m));
4965 }
4966 
TEST(WhenSortedByTest,ExplainsMatchResult)4967 TEST(WhenSortedByTest, ExplainsMatchResult) {
4968   const int a[] = {2, 1};
4969   EXPECT_EQ("which is { 1, 2 } when sorted, whose element #0 doesn't match",
4970             Explain(WhenSortedBy(less<int>(), ElementsAre(2, 3)), a));
4971   EXPECT_EQ("which is { 1, 2 } when sorted",
4972             Explain(WhenSortedBy(less<int>(), ElementsAre(1, 2)), a));
4973 }
4974 
4975 // WhenSorted() is a simple wrapper on WhenSortedBy().  Hence we don't
4976 // need to test it as exhaustively as we test the latter.
4977 
TEST(WhenSortedTest,WorksForEmptyContainer)4978 TEST(WhenSortedTest, WorksForEmptyContainer) {
4979   const vector<int> numbers;
4980   EXPECT_THAT(numbers, WhenSorted(ElementsAre()));
4981   EXPECT_THAT(numbers, Not(WhenSorted(ElementsAre(1))));
4982 }
4983 
TEST(WhenSortedTest,WorksForNonEmptyContainer)4984 TEST(WhenSortedTest, WorksForNonEmptyContainer) {
4985   list<std::string> words;
4986   words.push_back("3");
4987   words.push_back("1");
4988   words.push_back("2");
4989   words.push_back("2");
4990   EXPECT_THAT(words, WhenSorted(ElementsAre("1", "2", "2", "3")));
4991   EXPECT_THAT(words, Not(WhenSorted(ElementsAre("3", "1", "2", "2"))));
4992 }
4993 
TEST(WhenSortedTest,WorksForMapTypes)4994 TEST(WhenSortedTest, WorksForMapTypes) {
4995   map<std::string, int> word_counts;
4996   word_counts["and"] = 1;
4997   word_counts["the"] = 1;
4998   word_counts["buffalo"] = 2;
4999   EXPECT_THAT(word_counts,
5000               WhenSorted(ElementsAre(Pair("and", 1), Pair("buffalo", 2),
5001                                      Pair("the", 1))));
5002   EXPECT_THAT(word_counts,
5003               Not(WhenSorted(ElementsAre(Pair("and", 1), Pair("the", 1),
5004                                          Pair("buffalo", 2)))));
5005 }
5006 
TEST(WhenSortedTest,WorksForMultiMapTypes)5007 TEST(WhenSortedTest, WorksForMultiMapTypes) {
5008     multimap<int, int> ifib;
5009     ifib.insert(make_pair(8, 6));
5010     ifib.insert(make_pair(2, 3));
5011     ifib.insert(make_pair(1, 1));
5012     ifib.insert(make_pair(3, 4));
5013     ifib.insert(make_pair(1, 2));
5014     ifib.insert(make_pair(5, 5));
5015     EXPECT_THAT(ifib, WhenSorted(ElementsAre(Pair(1, 1),
5016                                              Pair(1, 2),
5017                                              Pair(2, 3),
5018                                              Pair(3, 4),
5019                                              Pair(5, 5),
5020                                              Pair(8, 6))));
5021     EXPECT_THAT(ifib, Not(WhenSorted(ElementsAre(Pair(8, 6),
5022                                                  Pair(2, 3),
5023                                                  Pair(1, 1),
5024                                                  Pair(3, 4),
5025                                                  Pair(1, 2),
5026                                                  Pair(5, 5)))));
5027 }
5028 
TEST(WhenSortedTest,WorksForPolymorphicMatcher)5029 TEST(WhenSortedTest, WorksForPolymorphicMatcher) {
5030     std::deque<int> d;
5031     d.push_back(2);
5032     d.push_back(1);
5033     EXPECT_THAT(d, WhenSorted(ElementsAre(1, 2)));
5034     EXPECT_THAT(d, Not(WhenSorted(ElementsAre(2, 1))));
5035 }
5036 
TEST(WhenSortedTest,WorksForVectorConstRefMatcher)5037 TEST(WhenSortedTest, WorksForVectorConstRefMatcher) {
5038     std::deque<int> d;
5039     d.push_back(2);
5040     d.push_back(1);
5041     Matcher<const std::vector<int>&> vector_match = ElementsAre(1, 2);
5042     EXPECT_THAT(d, WhenSorted(vector_match));
5043     Matcher<const std::vector<int>&> not_vector_match = ElementsAre(2, 1);
5044     EXPECT_THAT(d, Not(WhenSorted(not_vector_match)));
5045 }
5046 
5047 // Deliberately bare pseudo-container.
5048 // Offers only begin() and end() accessors, yielding InputIterator.
5049 template <typename T>
5050 class Streamlike {
5051  private:
5052   class ConstIter;
5053  public:
5054   typedef ConstIter const_iterator;
5055   typedef T value_type;
5056 
5057   template <typename InIter>
Streamlike(InIter first,InIter last)5058   Streamlike(InIter first, InIter last) : remainder_(first, last) {}
5059 
begin() const5060   const_iterator begin() const {
5061     return const_iterator(this, remainder_.begin());
5062   }
end() const5063   const_iterator end() const {
5064     return const_iterator(this, remainder_.end());
5065   }
5066 
5067  private:
5068   class ConstIter : public std::iterator<std::input_iterator_tag,
5069                                          value_type,
5070                                          ptrdiff_t,
5071                                          const value_type*,
5072                                          const value_type&> {
5073    public:
ConstIter(const Streamlike * s,typename std::list<value_type>::iterator pos)5074     ConstIter(const Streamlike* s,
5075               typename std::list<value_type>::iterator pos)
5076         : s_(s), pos_(pos) {}
5077 
operator *() const5078     const value_type& operator*() const { return *pos_; }
operator ->() const5079     const value_type* operator->() const { return &*pos_; }
operator ++()5080     ConstIter& operator++() {
5081       s_->remainder_.erase(pos_++);
5082       return *this;
5083     }
5084 
5085     // *iter++ is required to work (see std::istreambuf_iterator).
5086     // (void)iter++ is also required to work.
5087     class PostIncrProxy {
5088      public:
PostIncrProxy(const value_type & value)5089       explicit PostIncrProxy(const value_type& value) : value_(value) {}
operator *() const5090       value_type operator*() const { return value_; }
5091      private:
5092       value_type value_;
5093     };
operator ++(int)5094     PostIncrProxy operator++(int) {
5095       PostIncrProxy proxy(**this);
5096       ++(*this);
5097       return proxy;
5098     }
5099 
operator ==(const ConstIter & a,const ConstIter & b)5100     friend bool operator==(const ConstIter& a, const ConstIter& b) {
5101       return a.s_ == b.s_ && a.pos_ == b.pos_;
5102     }
operator !=(const ConstIter & a,const ConstIter & b)5103     friend bool operator!=(const ConstIter& a, const ConstIter& b) {
5104       return !(a == b);
5105     }
5106 
5107    private:
5108     const Streamlike* s_;
5109     typename std::list<value_type>::iterator pos_;
5110   };
5111 
operator <<(std::ostream & os,const Streamlike & s)5112   friend std::ostream& operator<<(std::ostream& os, const Streamlike& s) {
5113     os << "[";
5114     typedef typename std::list<value_type>::const_iterator Iter;
5115     const char* sep = "";
5116     for (Iter it = s.remainder_.begin(); it != s.remainder_.end(); ++it) {
5117       os << sep << *it;
5118       sep = ",";
5119     }
5120     os << "]";
5121     return os;
5122   }
5123 
5124   mutable std::list<value_type> remainder_;  // modified by iteration
5125 };
5126 
TEST(StreamlikeTest,Iteration)5127 TEST(StreamlikeTest, Iteration) {
5128   const int a[5] = {2, 1, 4, 5, 3};
5129   Streamlike<int> s(a, a + 5);
5130   Streamlike<int>::const_iterator it = s.begin();
5131   const int* ip = a;
5132   while (it != s.end()) {
5133     SCOPED_TRACE(ip - a);
5134     EXPECT_EQ(*ip++, *it++);
5135   }
5136 }
5137 
TEST(BeginEndDistanceIsTest,WorksWithForwardList)5138 TEST(BeginEndDistanceIsTest, WorksWithForwardList) {
5139   std::forward_list<int> container;
5140   EXPECT_THAT(container, BeginEndDistanceIs(0));
5141   EXPECT_THAT(container, Not(BeginEndDistanceIs(1)));
5142   container.push_front(0);
5143   EXPECT_THAT(container, Not(BeginEndDistanceIs(0)));
5144   EXPECT_THAT(container, BeginEndDistanceIs(1));
5145   container.push_front(0);
5146   EXPECT_THAT(container, Not(BeginEndDistanceIs(0)));
5147   EXPECT_THAT(container, BeginEndDistanceIs(2));
5148 }
5149 
TEST(BeginEndDistanceIsTest,WorksWithNonStdList)5150 TEST(BeginEndDistanceIsTest, WorksWithNonStdList) {
5151   const int a[5] = {1, 2, 3, 4, 5};
5152   Streamlike<int> s(a, a + 5);
5153   EXPECT_THAT(s, BeginEndDistanceIs(5));
5154 }
5155 
TEST(BeginEndDistanceIsTest,CanDescribeSelf)5156 TEST(BeginEndDistanceIsTest, CanDescribeSelf) {
5157   Matcher<vector<int> > m = BeginEndDistanceIs(2);
5158   EXPECT_EQ("distance between begin() and end() is equal to 2", Describe(m));
5159   EXPECT_EQ("distance between begin() and end() isn't equal to 2",
5160             DescribeNegation(m));
5161 }
5162 
TEST(BeginEndDistanceIsTest,WorksWithMoveOnly)5163 TEST(BeginEndDistanceIsTest, WorksWithMoveOnly) {
5164   ContainerHelper helper;
5165   EXPECT_CALL(helper, Call(BeginEndDistanceIs(2)));
5166   helper.Call(MakeUniquePtrs({1, 2}));
5167 }
5168 
TEST(BeginEndDistanceIsTest,ExplainsResult)5169 TEST(BeginEndDistanceIsTest, ExplainsResult) {
5170   Matcher<vector<int> > m1 = BeginEndDistanceIs(2);
5171   Matcher<vector<int> > m2 = BeginEndDistanceIs(Lt(2));
5172   Matcher<vector<int> > m3 = BeginEndDistanceIs(AnyOf(0, 3));
5173   Matcher<vector<int> > m4 = BeginEndDistanceIs(GreaterThan(1));
5174   vector<int> container;
5175   EXPECT_EQ("whose distance between begin() and end() 0 doesn't match",
5176             Explain(m1, container));
5177   EXPECT_EQ("whose distance between begin() and end() 0 matches",
5178             Explain(m2, container));
5179   EXPECT_EQ("whose distance between begin() and end() 0 matches",
5180             Explain(m3, container));
5181   EXPECT_EQ(
5182       "whose distance between begin() and end() 0 doesn't match, which is 1 "
5183       "less than 1",
5184       Explain(m4, container));
5185   container.push_back(0);
5186   container.push_back(0);
5187   EXPECT_EQ("whose distance between begin() and end() 2 matches",
5188             Explain(m1, container));
5189   EXPECT_EQ("whose distance between begin() and end() 2 doesn't match",
5190             Explain(m2, container));
5191   EXPECT_EQ("whose distance between begin() and end() 2 doesn't match",
5192             Explain(m3, container));
5193   EXPECT_EQ(
5194       "whose distance between begin() and end() 2 matches, which is 1 more "
5195       "than 1",
5196       Explain(m4, container));
5197 }
5198 
TEST(WhenSortedTest,WorksForStreamlike)5199 TEST(WhenSortedTest, WorksForStreamlike) {
5200   // Streamlike 'container' provides only minimal iterator support.
5201   // Its iterators are tagged with input_iterator_tag.
5202   const int a[5] = {2, 1, 4, 5, 3};
5203   Streamlike<int> s(std::begin(a), std::end(a));
5204   EXPECT_THAT(s, WhenSorted(ElementsAre(1, 2, 3, 4, 5)));
5205   EXPECT_THAT(s, Not(WhenSorted(ElementsAre(2, 1, 4, 5, 3))));
5206 }
5207 
TEST(WhenSortedTest,WorksForVectorConstRefMatcherOnStreamlike)5208 TEST(WhenSortedTest, WorksForVectorConstRefMatcherOnStreamlike) {
5209   const int a[] = {2, 1, 4, 5, 3};
5210   Streamlike<int> s(std::begin(a), std::end(a));
5211   Matcher<const std::vector<int>&> vector_match = ElementsAre(1, 2, 3, 4, 5);
5212   EXPECT_THAT(s, WhenSorted(vector_match));
5213   EXPECT_THAT(s, Not(WhenSorted(ElementsAre(2, 1, 4, 5, 3))));
5214 }
5215 
TEST(IsSupersetOfTest,WorksForNativeArray)5216 TEST(IsSupersetOfTest, WorksForNativeArray) {
5217   const int subset[] = {1, 4};
5218   const int superset[] = {1, 2, 4};
5219   const int disjoint[] = {1, 0, 3};
5220   EXPECT_THAT(subset, IsSupersetOf(subset));
5221   EXPECT_THAT(subset, Not(IsSupersetOf(superset)));
5222   EXPECT_THAT(superset, IsSupersetOf(subset));
5223   EXPECT_THAT(subset, Not(IsSupersetOf(disjoint)));
5224   EXPECT_THAT(disjoint, Not(IsSupersetOf(subset)));
5225 }
5226 
TEST(IsSupersetOfTest,WorksWithDuplicates)5227 TEST(IsSupersetOfTest, WorksWithDuplicates) {
5228   const int not_enough[] = {1, 2};
5229   const int enough[] = {1, 1, 2};
5230   const int expected[] = {1, 1};
5231   EXPECT_THAT(not_enough, Not(IsSupersetOf(expected)));
5232   EXPECT_THAT(enough, IsSupersetOf(expected));
5233 }
5234 
TEST(IsSupersetOfTest,WorksForEmpty)5235 TEST(IsSupersetOfTest, WorksForEmpty) {
5236   vector<int> numbers;
5237   vector<int> expected;
5238   EXPECT_THAT(numbers, IsSupersetOf(expected));
5239   expected.push_back(1);
5240   EXPECT_THAT(numbers, Not(IsSupersetOf(expected)));
5241   expected.clear();
5242   numbers.push_back(1);
5243   numbers.push_back(2);
5244   EXPECT_THAT(numbers, IsSupersetOf(expected));
5245   expected.push_back(1);
5246   EXPECT_THAT(numbers, IsSupersetOf(expected));
5247   expected.push_back(2);
5248   EXPECT_THAT(numbers, IsSupersetOf(expected));
5249   expected.push_back(3);
5250   EXPECT_THAT(numbers, Not(IsSupersetOf(expected)));
5251 }
5252 
TEST(IsSupersetOfTest,WorksForStreamlike)5253 TEST(IsSupersetOfTest, WorksForStreamlike) {
5254   const int a[5] = {1, 2, 3, 4, 5};
5255   Streamlike<int> s(std::begin(a), std::end(a));
5256 
5257   vector<int> expected;
5258   expected.push_back(1);
5259   expected.push_back(2);
5260   expected.push_back(5);
5261   EXPECT_THAT(s, IsSupersetOf(expected));
5262 
5263   expected.push_back(0);
5264   EXPECT_THAT(s, Not(IsSupersetOf(expected)));
5265 }
5266 
TEST(IsSupersetOfTest,TakesStlContainer)5267 TEST(IsSupersetOfTest, TakesStlContainer) {
5268   const int actual[] = {3, 1, 2};
5269 
5270   ::std::list<int> expected;
5271   expected.push_back(1);
5272   expected.push_back(3);
5273   EXPECT_THAT(actual, IsSupersetOf(expected));
5274 
5275   expected.push_back(4);
5276   EXPECT_THAT(actual, Not(IsSupersetOf(expected)));
5277 }
5278 
TEST(IsSupersetOfTest,Describe)5279 TEST(IsSupersetOfTest, Describe) {
5280   typedef std::vector<int> IntVec;
5281   IntVec expected;
5282   expected.push_back(111);
5283   expected.push_back(222);
5284   expected.push_back(333);
5285   EXPECT_THAT(
5286       Describe<IntVec>(IsSupersetOf(expected)),
5287       Eq("a surjection from elements to requirements exists such that:\n"
5288          " - an element is equal to 111\n"
5289          " - an element is equal to 222\n"
5290          " - an element is equal to 333"));
5291 }
5292 
TEST(IsSupersetOfTest,DescribeNegation)5293 TEST(IsSupersetOfTest, DescribeNegation) {
5294   typedef std::vector<int> IntVec;
5295   IntVec expected;
5296   expected.push_back(111);
5297   expected.push_back(222);
5298   expected.push_back(333);
5299   EXPECT_THAT(
5300       DescribeNegation<IntVec>(IsSupersetOf(expected)),
5301       Eq("no surjection from elements to requirements exists such that:\n"
5302          " - an element is equal to 111\n"
5303          " - an element is equal to 222\n"
5304          " - an element is equal to 333"));
5305 }
5306 
TEST(IsSupersetOfTest,MatchAndExplain)5307 TEST(IsSupersetOfTest, MatchAndExplain) {
5308   std::vector<int> v;
5309   v.push_back(2);
5310   v.push_back(3);
5311   std::vector<int> expected;
5312   expected.push_back(1);
5313   expected.push_back(2);
5314   StringMatchResultListener listener;
5315   ASSERT_FALSE(ExplainMatchResult(IsSupersetOf(expected), v, &listener))
5316       << listener.str();
5317   EXPECT_THAT(listener.str(),
5318               Eq("where the following matchers don't match any elements:\n"
5319                  "matcher #0: is equal to 1"));
5320 
5321   v.push_back(1);
5322   listener.Clear();
5323   ASSERT_TRUE(ExplainMatchResult(IsSupersetOf(expected), v, &listener))
5324       << listener.str();
5325   EXPECT_THAT(listener.str(), Eq("where:\n"
5326                                  " - element #0 is matched by matcher #1,\n"
5327                                  " - element #2 is matched by matcher #0"));
5328 }
5329 
TEST(IsSupersetOfTest,WorksForRhsInitializerList)5330 TEST(IsSupersetOfTest, WorksForRhsInitializerList) {
5331   const int numbers[] = {1, 3, 6, 2, 4, 5};
5332   EXPECT_THAT(numbers, IsSupersetOf({1, 2}));
5333   EXPECT_THAT(numbers, Not(IsSupersetOf({3, 0})));
5334 }
5335 
TEST(IsSupersetOfTest,WorksWithMoveOnly)5336 TEST(IsSupersetOfTest, WorksWithMoveOnly) {
5337   ContainerHelper helper;
5338   EXPECT_CALL(helper, Call(IsSupersetOf({Pointee(1)})));
5339   helper.Call(MakeUniquePtrs({1, 2}));
5340   EXPECT_CALL(helper, Call(Not(IsSupersetOf({Pointee(1), Pointee(2)}))));
5341   helper.Call(MakeUniquePtrs({2}));
5342 }
5343 
TEST(IsSubsetOfTest,WorksForNativeArray)5344 TEST(IsSubsetOfTest, WorksForNativeArray) {
5345   const int subset[] = {1, 4};
5346   const int superset[] = {1, 2, 4};
5347   const int disjoint[] = {1, 0, 3};
5348   EXPECT_THAT(subset, IsSubsetOf(subset));
5349   EXPECT_THAT(subset, IsSubsetOf(superset));
5350   EXPECT_THAT(superset, Not(IsSubsetOf(subset)));
5351   EXPECT_THAT(subset, Not(IsSubsetOf(disjoint)));
5352   EXPECT_THAT(disjoint, Not(IsSubsetOf(subset)));
5353 }
5354 
TEST(IsSubsetOfTest,WorksWithDuplicates)5355 TEST(IsSubsetOfTest, WorksWithDuplicates) {
5356   const int not_enough[] = {1, 2};
5357   const int enough[] = {1, 1, 2};
5358   const int actual[] = {1, 1};
5359   EXPECT_THAT(actual, Not(IsSubsetOf(not_enough)));
5360   EXPECT_THAT(actual, IsSubsetOf(enough));
5361 }
5362 
TEST(IsSubsetOfTest,WorksForEmpty)5363 TEST(IsSubsetOfTest, WorksForEmpty) {
5364   vector<int> numbers;
5365   vector<int> expected;
5366   EXPECT_THAT(numbers, IsSubsetOf(expected));
5367   expected.push_back(1);
5368   EXPECT_THAT(numbers, IsSubsetOf(expected));
5369   expected.clear();
5370   numbers.push_back(1);
5371   numbers.push_back(2);
5372   EXPECT_THAT(numbers, Not(IsSubsetOf(expected)));
5373   expected.push_back(1);
5374   EXPECT_THAT(numbers, Not(IsSubsetOf(expected)));
5375   expected.push_back(2);
5376   EXPECT_THAT(numbers, IsSubsetOf(expected));
5377   expected.push_back(3);
5378   EXPECT_THAT(numbers, IsSubsetOf(expected));
5379 }
5380 
TEST(IsSubsetOfTest,WorksForStreamlike)5381 TEST(IsSubsetOfTest, WorksForStreamlike) {
5382   const int a[5] = {1, 2};
5383   Streamlike<int> s(std::begin(a), std::end(a));
5384 
5385   vector<int> expected;
5386   expected.push_back(1);
5387   EXPECT_THAT(s, Not(IsSubsetOf(expected)));
5388   expected.push_back(2);
5389   expected.push_back(5);
5390   EXPECT_THAT(s, IsSubsetOf(expected));
5391 }
5392 
TEST(IsSubsetOfTest,TakesStlContainer)5393 TEST(IsSubsetOfTest, TakesStlContainer) {
5394   const int actual[] = {3, 1, 2};
5395 
5396   ::std::list<int> expected;
5397   expected.push_back(1);
5398   expected.push_back(3);
5399   EXPECT_THAT(actual, Not(IsSubsetOf(expected)));
5400 
5401   expected.push_back(2);
5402   expected.push_back(4);
5403   EXPECT_THAT(actual, IsSubsetOf(expected));
5404 }
5405 
TEST(IsSubsetOfTest,Describe)5406 TEST(IsSubsetOfTest, Describe) {
5407   typedef std::vector<int> IntVec;
5408   IntVec expected;
5409   expected.push_back(111);
5410   expected.push_back(222);
5411   expected.push_back(333);
5412 
5413   EXPECT_THAT(
5414       Describe<IntVec>(IsSubsetOf(expected)),
5415       Eq("an injection from elements to requirements exists such that:\n"
5416          " - an element is equal to 111\n"
5417          " - an element is equal to 222\n"
5418          " - an element is equal to 333"));
5419 }
5420 
TEST(IsSubsetOfTest,DescribeNegation)5421 TEST(IsSubsetOfTest, DescribeNegation) {
5422   typedef std::vector<int> IntVec;
5423   IntVec expected;
5424   expected.push_back(111);
5425   expected.push_back(222);
5426   expected.push_back(333);
5427   EXPECT_THAT(
5428       DescribeNegation<IntVec>(IsSubsetOf(expected)),
5429       Eq("no injection from elements to requirements exists such that:\n"
5430          " - an element is equal to 111\n"
5431          " - an element is equal to 222\n"
5432          " - an element is equal to 333"));
5433 }
5434 
TEST(IsSubsetOfTest,MatchAndExplain)5435 TEST(IsSubsetOfTest, MatchAndExplain) {
5436   std::vector<int> v;
5437   v.push_back(2);
5438   v.push_back(3);
5439   std::vector<int> expected;
5440   expected.push_back(1);
5441   expected.push_back(2);
5442   StringMatchResultListener listener;
5443   ASSERT_FALSE(ExplainMatchResult(IsSubsetOf(expected), v, &listener))
5444       << listener.str();
5445   EXPECT_THAT(listener.str(),
5446               Eq("where the following elements don't match any matchers:\n"
5447                  "element #1: 3"));
5448 
5449   expected.push_back(3);
5450   listener.Clear();
5451   ASSERT_TRUE(ExplainMatchResult(IsSubsetOf(expected), v, &listener))
5452       << listener.str();
5453   EXPECT_THAT(listener.str(), Eq("where:\n"
5454                                  " - element #0 is matched by matcher #1,\n"
5455                                  " - element #1 is matched by matcher #2"));
5456 }
5457 
TEST(IsSubsetOfTest,WorksForRhsInitializerList)5458 TEST(IsSubsetOfTest, WorksForRhsInitializerList) {
5459   const int numbers[] = {1, 2, 3};
5460   EXPECT_THAT(numbers, IsSubsetOf({1, 2, 3, 4}));
5461   EXPECT_THAT(numbers, Not(IsSubsetOf({1, 2})));
5462 }
5463 
TEST(IsSubsetOfTest,WorksWithMoveOnly)5464 TEST(IsSubsetOfTest, WorksWithMoveOnly) {
5465   ContainerHelper helper;
5466   EXPECT_CALL(helper, Call(IsSubsetOf({Pointee(1), Pointee(2)})));
5467   helper.Call(MakeUniquePtrs({1}));
5468   EXPECT_CALL(helper, Call(Not(IsSubsetOf({Pointee(1)}))));
5469   helper.Call(MakeUniquePtrs({2}));
5470 }
5471 
5472 // Tests using ElementsAre() and ElementsAreArray() with stream-like
5473 // "containers".
5474 
TEST(ElemensAreStreamTest,WorksForStreamlike)5475 TEST(ElemensAreStreamTest, WorksForStreamlike) {
5476   const int a[5] = {1, 2, 3, 4, 5};
5477   Streamlike<int> s(std::begin(a), std::end(a));
5478   EXPECT_THAT(s, ElementsAre(1, 2, 3, 4, 5));
5479   EXPECT_THAT(s, Not(ElementsAre(2, 1, 4, 5, 3)));
5480 }
5481 
TEST(ElemensAreArrayStreamTest,WorksForStreamlike)5482 TEST(ElemensAreArrayStreamTest, WorksForStreamlike) {
5483   const int a[5] = {1, 2, 3, 4, 5};
5484   Streamlike<int> s(std::begin(a), std::end(a));
5485 
5486   vector<int> expected;
5487   expected.push_back(1);
5488   expected.push_back(2);
5489   expected.push_back(3);
5490   expected.push_back(4);
5491   expected.push_back(5);
5492   EXPECT_THAT(s, ElementsAreArray(expected));
5493 
5494   expected[3] = 0;
5495   EXPECT_THAT(s, Not(ElementsAreArray(expected)));
5496 }
5497 
TEST(ElementsAreTest,WorksWithUncopyable)5498 TEST(ElementsAreTest, WorksWithUncopyable) {
5499   Uncopyable objs[2];
5500   objs[0].set_value(-3);
5501   objs[1].set_value(1);
5502   EXPECT_THAT(objs, ElementsAre(UncopyableIs(-3), Truly(ValueIsPositive)));
5503 }
5504 
TEST(ElementsAreTest,WorksWithMoveOnly)5505 TEST(ElementsAreTest, WorksWithMoveOnly) {
5506   ContainerHelper helper;
5507   EXPECT_CALL(helper, Call(ElementsAre(Pointee(1), Pointee(2))));
5508   helper.Call(MakeUniquePtrs({1, 2}));
5509 
5510   EXPECT_CALL(helper, Call(ElementsAreArray({Pointee(3), Pointee(4)})));
5511   helper.Call(MakeUniquePtrs({3, 4}));
5512 }
5513 
TEST(ElementsAreTest,TakesStlContainer)5514 TEST(ElementsAreTest, TakesStlContainer) {
5515   const int actual[] = {3, 1, 2};
5516 
5517   ::std::list<int> expected;
5518   expected.push_back(3);
5519   expected.push_back(1);
5520   expected.push_back(2);
5521   EXPECT_THAT(actual, ElementsAreArray(expected));
5522 
5523   expected.push_back(4);
5524   EXPECT_THAT(actual, Not(ElementsAreArray(expected)));
5525 }
5526 
5527 // Tests for UnorderedElementsAreArray()
5528 
TEST(UnorderedElementsAreArrayTest,SucceedsWhenExpected)5529 TEST(UnorderedElementsAreArrayTest, SucceedsWhenExpected) {
5530   const int a[] = {0, 1, 2, 3, 4};
5531   std::vector<int> s(std::begin(a), std::end(a));
5532   do {
5533     StringMatchResultListener listener;
5534     EXPECT_TRUE(ExplainMatchResult(UnorderedElementsAreArray(a),
5535                                    s, &listener)) << listener.str();
5536   } while (std::next_permutation(s.begin(), s.end()));
5537 }
5538 
TEST(UnorderedElementsAreArrayTest,VectorBool)5539 TEST(UnorderedElementsAreArrayTest, VectorBool) {
5540   const bool a[] = {0, 1, 0, 1, 1};
5541   const bool b[] = {1, 0, 1, 1, 0};
5542   std::vector<bool> expected(std::begin(a), std::end(a));
5543   std::vector<bool> actual(std::begin(b), std::end(b));
5544   StringMatchResultListener listener;
5545   EXPECT_TRUE(ExplainMatchResult(UnorderedElementsAreArray(expected),
5546                                  actual, &listener)) << listener.str();
5547 }
5548 
TEST(UnorderedElementsAreArrayTest,WorksForStreamlike)5549 TEST(UnorderedElementsAreArrayTest, WorksForStreamlike) {
5550   // Streamlike 'container' provides only minimal iterator support.
5551   // Its iterators are tagged with input_iterator_tag, and it has no
5552   // size() or empty() methods.
5553   const int a[5] = {2, 1, 4, 5, 3};
5554   Streamlike<int> s(std::begin(a), std::end(a));
5555 
5556   ::std::vector<int> expected;
5557   expected.push_back(1);
5558   expected.push_back(2);
5559   expected.push_back(3);
5560   expected.push_back(4);
5561   expected.push_back(5);
5562   EXPECT_THAT(s, UnorderedElementsAreArray(expected));
5563 
5564   expected.push_back(6);
5565   EXPECT_THAT(s, Not(UnorderedElementsAreArray(expected)));
5566 }
5567 
TEST(UnorderedElementsAreArrayTest,TakesStlContainer)5568 TEST(UnorderedElementsAreArrayTest, TakesStlContainer) {
5569   const int actual[] = {3, 1, 2};
5570 
5571   ::std::list<int> expected;
5572   expected.push_back(1);
5573   expected.push_back(2);
5574   expected.push_back(3);
5575   EXPECT_THAT(actual, UnorderedElementsAreArray(expected));
5576 
5577   expected.push_back(4);
5578   EXPECT_THAT(actual, Not(UnorderedElementsAreArray(expected)));
5579 }
5580 
5581 
TEST(UnorderedElementsAreArrayTest,TakesInitializerList)5582 TEST(UnorderedElementsAreArrayTest, TakesInitializerList) {
5583   const int a[5] = {2, 1, 4, 5, 3};
5584   EXPECT_THAT(a, UnorderedElementsAreArray({1, 2, 3, 4, 5}));
5585   EXPECT_THAT(a, Not(UnorderedElementsAreArray({1, 2, 3, 4, 6})));
5586 }
5587 
TEST(UnorderedElementsAreArrayTest,TakesInitializerListOfCStrings)5588 TEST(UnorderedElementsAreArrayTest, TakesInitializerListOfCStrings) {
5589   const std::string a[5] = {"a", "b", "c", "d", "e"};
5590   EXPECT_THAT(a, UnorderedElementsAreArray({"a", "b", "c", "d", "e"}));
5591   EXPECT_THAT(a, Not(UnorderedElementsAreArray({"a", "b", "c", "d", "ef"})));
5592 }
5593 
TEST(UnorderedElementsAreArrayTest,TakesInitializerListOfSameTypedMatchers)5594 TEST(UnorderedElementsAreArrayTest, TakesInitializerListOfSameTypedMatchers) {
5595   const int a[5] = {2, 1, 4, 5, 3};
5596   EXPECT_THAT(a, UnorderedElementsAreArray(
5597       {Eq(1), Eq(2), Eq(3), Eq(4), Eq(5)}));
5598   EXPECT_THAT(a, Not(UnorderedElementsAreArray(
5599       {Eq(1), Eq(2), Eq(3), Eq(4), Eq(6)})));
5600 }
5601 
TEST(UnorderedElementsAreArrayTest,TakesInitializerListOfDifferentTypedMatchers)5602 TEST(UnorderedElementsAreArrayTest,
5603      TakesInitializerListOfDifferentTypedMatchers) {
5604   const int a[5] = {2, 1, 4, 5, 3};
5605   // The compiler cannot infer the type of the initializer list if its
5606   // elements have different types.  We must explicitly specify the
5607   // unified element type in this case.
5608   EXPECT_THAT(a, UnorderedElementsAreArray<Matcher<int> >(
5609       {Eq(1), Ne(-2), Ge(3), Le(4), Eq(5)}));
5610   EXPECT_THAT(a, Not(UnorderedElementsAreArray<Matcher<int> >(
5611       {Eq(1), Ne(-2), Ge(3), Le(4), Eq(6)})));
5612 }
5613 
5614 
TEST(UnorderedElementsAreArrayTest,WorksWithMoveOnly)5615 TEST(UnorderedElementsAreArrayTest, WorksWithMoveOnly) {
5616   ContainerHelper helper;
5617   EXPECT_CALL(helper,
5618               Call(UnorderedElementsAreArray({Pointee(1), Pointee(2)})));
5619   helper.Call(MakeUniquePtrs({2, 1}));
5620 }
5621 
5622 class UnorderedElementsAreTest : public testing::Test {
5623  protected:
5624   typedef std::vector<int> IntVec;
5625 };
5626 
TEST_F(UnorderedElementsAreTest,WorksWithUncopyable)5627 TEST_F(UnorderedElementsAreTest, WorksWithUncopyable) {
5628   Uncopyable objs[2];
5629   objs[0].set_value(-3);
5630   objs[1].set_value(1);
5631   EXPECT_THAT(objs,
5632               UnorderedElementsAre(Truly(ValueIsPositive), UncopyableIs(-3)));
5633 }
5634 
TEST_F(UnorderedElementsAreTest,SucceedsWhenExpected)5635 TEST_F(UnorderedElementsAreTest, SucceedsWhenExpected) {
5636   const int a[] = {1, 2, 3};
5637   std::vector<int> s(std::begin(a), std::end(a));
5638   do {
5639     StringMatchResultListener listener;
5640     EXPECT_TRUE(ExplainMatchResult(UnorderedElementsAre(1, 2, 3),
5641                                    s, &listener)) << listener.str();
5642   } while (std::next_permutation(s.begin(), s.end()));
5643 }
5644 
TEST_F(UnorderedElementsAreTest,FailsWhenAnElementMatchesNoMatcher)5645 TEST_F(UnorderedElementsAreTest, FailsWhenAnElementMatchesNoMatcher) {
5646   const int a[] = {1, 2, 3};
5647   std::vector<int> s(std::begin(a), std::end(a));
5648   std::vector<Matcher<int> > mv;
5649   mv.push_back(1);
5650   mv.push_back(2);
5651   mv.push_back(2);
5652   // The element with value '3' matches nothing: fail fast.
5653   StringMatchResultListener listener;
5654   EXPECT_FALSE(ExplainMatchResult(UnorderedElementsAreArray(mv),
5655                                   s, &listener)) << listener.str();
5656 }
5657 
TEST_F(UnorderedElementsAreTest,WorksForStreamlike)5658 TEST_F(UnorderedElementsAreTest, WorksForStreamlike) {
5659   // Streamlike 'container' provides only minimal iterator support.
5660   // Its iterators are tagged with input_iterator_tag, and it has no
5661   // size() or empty() methods.
5662   const int a[5] = {2, 1, 4, 5, 3};
5663   Streamlike<int> s(std::begin(a), std::end(a));
5664 
5665   EXPECT_THAT(s, UnorderedElementsAre(1, 2, 3, 4, 5));
5666   EXPECT_THAT(s, Not(UnorderedElementsAre(2, 2, 3, 4, 5)));
5667 }
5668 
TEST_F(UnorderedElementsAreTest,WorksWithMoveOnly)5669 TEST_F(UnorderedElementsAreTest, WorksWithMoveOnly) {
5670   ContainerHelper helper;
5671   EXPECT_CALL(helper, Call(UnorderedElementsAre(Pointee(1), Pointee(2))));
5672   helper.Call(MakeUniquePtrs({2, 1}));
5673 }
5674 
5675 // One naive implementation of the matcher runs in O(N!) time, which is too
5676 // slow for many real-world inputs. This test shows that our matcher can match
5677 // 100 inputs very quickly (a few milliseconds).  An O(100!) is 10^158
5678 // iterations and obviously effectively incomputable.
5679 // [ RUN      ] UnorderedElementsAreTest.Performance
5680 // [       OK ] UnorderedElementsAreTest.Performance (4 ms)
TEST_F(UnorderedElementsAreTest,Performance)5681 TEST_F(UnorderedElementsAreTest, Performance) {
5682   std::vector<int> s;
5683   std::vector<Matcher<int> > mv;
5684   for (int i = 0; i < 100; ++i) {
5685     s.push_back(i);
5686     mv.push_back(_);
5687   }
5688   mv[50] = Eq(0);
5689   StringMatchResultListener listener;
5690   EXPECT_TRUE(ExplainMatchResult(UnorderedElementsAreArray(mv),
5691                                  s, &listener)) << listener.str();
5692 }
5693 
5694 // Another variant of 'Performance' with similar expectations.
5695 // [ RUN      ] UnorderedElementsAreTest.PerformanceHalfStrict
5696 // [       OK ] UnorderedElementsAreTest.PerformanceHalfStrict (4 ms)
TEST_F(UnorderedElementsAreTest,PerformanceHalfStrict)5697 TEST_F(UnorderedElementsAreTest, PerformanceHalfStrict) {
5698   std::vector<int> s;
5699   std::vector<Matcher<int> > mv;
5700   for (int i = 0; i < 100; ++i) {
5701     s.push_back(i);
5702     if (i & 1) {
5703       mv.push_back(_);
5704     } else {
5705       mv.push_back(i);
5706     }
5707   }
5708   StringMatchResultListener listener;
5709   EXPECT_TRUE(ExplainMatchResult(UnorderedElementsAreArray(mv),
5710                                  s, &listener)) << listener.str();
5711 }
5712 
TEST_F(UnorderedElementsAreTest,FailMessageCountWrong)5713 TEST_F(UnorderedElementsAreTest, FailMessageCountWrong) {
5714   std::vector<int> v;
5715   v.push_back(4);
5716   StringMatchResultListener listener;
5717   EXPECT_FALSE(ExplainMatchResult(UnorderedElementsAre(1, 2, 3),
5718                                   v, &listener)) << listener.str();
5719   EXPECT_THAT(listener.str(), Eq("which has 1 element"));
5720 }
5721 
TEST_F(UnorderedElementsAreTest,FailMessageCountWrongZero)5722 TEST_F(UnorderedElementsAreTest, FailMessageCountWrongZero) {
5723   std::vector<int> v;
5724   StringMatchResultListener listener;
5725   EXPECT_FALSE(ExplainMatchResult(UnorderedElementsAre(1, 2, 3),
5726                                   v, &listener)) << listener.str();
5727   EXPECT_THAT(listener.str(), Eq(""));
5728 }
5729 
TEST_F(UnorderedElementsAreTest,FailMessageUnmatchedMatchers)5730 TEST_F(UnorderedElementsAreTest, FailMessageUnmatchedMatchers) {
5731   std::vector<int> v;
5732   v.push_back(1);
5733   v.push_back(1);
5734   StringMatchResultListener listener;
5735   EXPECT_FALSE(ExplainMatchResult(UnorderedElementsAre(1, 2),
5736                                   v, &listener)) << listener.str();
5737   EXPECT_THAT(
5738       listener.str(),
5739       Eq("where the following matchers don't match any elements:\n"
5740          "matcher #1: is equal to 2"));
5741 }
5742 
TEST_F(UnorderedElementsAreTest,FailMessageUnmatchedElements)5743 TEST_F(UnorderedElementsAreTest, FailMessageUnmatchedElements) {
5744   std::vector<int> v;
5745   v.push_back(1);
5746   v.push_back(2);
5747   StringMatchResultListener listener;
5748   EXPECT_FALSE(ExplainMatchResult(UnorderedElementsAre(1, 1),
5749                                   v, &listener)) << listener.str();
5750   EXPECT_THAT(
5751       listener.str(),
5752       Eq("where the following elements don't match any matchers:\n"
5753          "element #1: 2"));
5754 }
5755 
TEST_F(UnorderedElementsAreTest,FailMessageUnmatchedMatcherAndElement)5756 TEST_F(UnorderedElementsAreTest, FailMessageUnmatchedMatcherAndElement) {
5757   std::vector<int> v;
5758   v.push_back(2);
5759   v.push_back(3);
5760   StringMatchResultListener listener;
5761   EXPECT_FALSE(ExplainMatchResult(UnorderedElementsAre(1, 2),
5762                                   v, &listener)) << listener.str();
5763   EXPECT_THAT(
5764       listener.str(),
5765       Eq("where"
5766          " the following matchers don't match any elements:\n"
5767          "matcher #0: is equal to 1\n"
5768          "and"
5769          " where"
5770          " the following elements don't match any matchers:\n"
5771          "element #1: 3"));
5772 }
5773 
5774 // Test helper for formatting element, matcher index pairs in expectations.
EMString(int element,int matcher)5775 static std::string EMString(int element, int matcher) {
5776   stringstream ss;
5777   ss << "(element #" << element << ", matcher #" << matcher << ")";
5778   return ss.str();
5779 }
5780 
TEST_F(UnorderedElementsAreTest,FailMessageImperfectMatchOnly)5781 TEST_F(UnorderedElementsAreTest, FailMessageImperfectMatchOnly) {
5782   // A situation where all elements and matchers have a match
5783   // associated with them, but the max matching is not perfect.
5784   std::vector<std::string> v;
5785   v.push_back("a");
5786   v.push_back("b");
5787   v.push_back("c");
5788   StringMatchResultListener listener;
5789   EXPECT_FALSE(ExplainMatchResult(
5790       UnorderedElementsAre("a", "a", AnyOf("b", "c")), v, &listener))
5791       << listener.str();
5792 
5793   std::string prefix =
5794       "where no permutation of the elements can satisfy all matchers, "
5795       "and the closest match is 2 of 3 matchers with the "
5796       "pairings:\n";
5797 
5798   // We have to be a bit loose here, because there are 4 valid max matches.
5799   EXPECT_THAT(
5800       listener.str(),
5801       AnyOf(prefix + "{\n  " + EMString(0, 0) +
5802                      ",\n  " + EMString(1, 2) + "\n}",
5803             prefix + "{\n  " + EMString(0, 1) +
5804                      ",\n  " + EMString(1, 2) + "\n}",
5805             prefix + "{\n  " + EMString(0, 0) +
5806                      ",\n  " + EMString(2, 2) + "\n}",
5807             prefix + "{\n  " + EMString(0, 1) +
5808                      ",\n  " + EMString(2, 2) + "\n}"));
5809 }
5810 
TEST_F(UnorderedElementsAreTest,Describe)5811 TEST_F(UnorderedElementsAreTest, Describe) {
5812   EXPECT_THAT(Describe<IntVec>(UnorderedElementsAre()),
5813               Eq("is empty"));
5814   EXPECT_THAT(
5815       Describe<IntVec>(UnorderedElementsAre(345)),
5816       Eq("has 1 element and that element is equal to 345"));
5817   EXPECT_THAT(
5818       Describe<IntVec>(UnorderedElementsAre(111, 222, 333)),
5819       Eq("has 3 elements and there exists some permutation "
5820          "of elements such that:\n"
5821          " - element #0 is equal to 111, and\n"
5822          " - element #1 is equal to 222, and\n"
5823          " - element #2 is equal to 333"));
5824 }
5825 
TEST_F(UnorderedElementsAreTest,DescribeNegation)5826 TEST_F(UnorderedElementsAreTest, DescribeNegation) {
5827   EXPECT_THAT(DescribeNegation<IntVec>(UnorderedElementsAre()),
5828               Eq("isn't empty"));
5829   EXPECT_THAT(
5830       DescribeNegation<IntVec>(UnorderedElementsAre(345)),
5831       Eq("doesn't have 1 element, or has 1 element that isn't equal to 345"));
5832   EXPECT_THAT(
5833       DescribeNegation<IntVec>(UnorderedElementsAre(123, 234, 345)),
5834       Eq("doesn't have 3 elements, or there exists no permutation "
5835          "of elements such that:\n"
5836          " - element #0 is equal to 123, and\n"
5837          " - element #1 is equal to 234, and\n"
5838          " - element #2 is equal to 345"));
5839 }
5840 
5841 namespace {
5842 
5843 // Used as a check on the more complex max flow method used in the
5844 // real testing::internal::FindMaxBipartiteMatching. This method is
5845 // compatible but runs in worst-case factorial time, so we only
5846 // use it in testing for small problem sizes.
5847 template <typename Graph>
5848 class BacktrackingMaxBPMState {
5849  public:
5850   // Does not take ownership of 'g'.
BacktrackingMaxBPMState(const Graph * g)5851   explicit BacktrackingMaxBPMState(const Graph* g) : graph_(g) { }
5852 
Compute()5853   ElementMatcherPairs Compute() {
5854     if (graph_->LhsSize() == 0 || graph_->RhsSize() == 0) {
5855       return best_so_far_;
5856     }
5857     lhs_used_.assign(graph_->LhsSize(), kUnused);
5858     rhs_used_.assign(graph_->RhsSize(), kUnused);
5859     for (size_t irhs = 0; irhs < graph_->RhsSize(); ++irhs) {
5860       matches_.clear();
5861       RecurseInto(irhs);
5862       if (best_so_far_.size() == graph_->RhsSize())
5863         break;
5864     }
5865     return best_so_far_;
5866   }
5867 
5868  private:
5869   static const size_t kUnused = static_cast<size_t>(-1);
5870 
PushMatch(size_t lhs,size_t rhs)5871   void PushMatch(size_t lhs, size_t rhs) {
5872     matches_.push_back(ElementMatcherPair(lhs, rhs));
5873     lhs_used_[lhs] = rhs;
5874     rhs_used_[rhs] = lhs;
5875     if (matches_.size() > best_so_far_.size()) {
5876       best_so_far_ = matches_;
5877     }
5878   }
5879 
PopMatch()5880   void PopMatch() {
5881     const ElementMatcherPair& back = matches_.back();
5882     lhs_used_[back.first] = kUnused;
5883     rhs_used_[back.second] = kUnused;
5884     matches_.pop_back();
5885   }
5886 
RecurseInto(size_t irhs)5887   bool RecurseInto(size_t irhs) {
5888     if (rhs_used_[irhs] != kUnused) {
5889       return true;
5890     }
5891     for (size_t ilhs = 0; ilhs < graph_->LhsSize(); ++ilhs) {
5892       if (lhs_used_[ilhs] != kUnused) {
5893         continue;
5894       }
5895       if (!graph_->HasEdge(ilhs, irhs)) {
5896         continue;
5897       }
5898       PushMatch(ilhs, irhs);
5899       if (best_so_far_.size() == graph_->RhsSize()) {
5900         return false;
5901       }
5902       for (size_t mi = irhs + 1; mi < graph_->RhsSize(); ++mi) {
5903         if (!RecurseInto(mi)) return false;
5904       }
5905       PopMatch();
5906     }
5907     return true;
5908   }
5909 
5910   const Graph* graph_;  // not owned
5911   std::vector<size_t> lhs_used_;
5912   std::vector<size_t> rhs_used_;
5913   ElementMatcherPairs matches_;
5914   ElementMatcherPairs best_so_far_;
5915 };
5916 
5917 template <typename Graph>
5918 const size_t BacktrackingMaxBPMState<Graph>::kUnused;
5919 
5920 }  // namespace
5921 
5922 // Implement a simple backtracking algorithm to determine if it is possible
5923 // to find one element per matcher, without reusing elements.
5924 template <typename Graph>
5925 ElementMatcherPairs
FindBacktrackingMaxBPM(const Graph & g)5926 FindBacktrackingMaxBPM(const Graph& g) {
5927   return BacktrackingMaxBPMState<Graph>(&g).Compute();
5928 }
5929 
5930 class BacktrackingBPMTest : public ::testing::Test { };
5931 
5932 // Tests the MaxBipartiteMatching algorithm with square matrices.
5933 // The single int param is the # of nodes on each of the left and right sides.
5934 class BipartiteTest : public ::testing::TestWithParam<size_t> {};
5935 
5936 // Verify all match graphs up to some moderate number of edges.
TEST_P(BipartiteTest,Exhaustive)5937 TEST_P(BipartiteTest, Exhaustive) {
5938   size_t nodes = GetParam();
5939   MatchMatrix graph(nodes, nodes);
5940   do {
5941     ElementMatcherPairs matches =
5942         internal::FindMaxBipartiteMatching(graph);
5943     EXPECT_EQ(FindBacktrackingMaxBPM(graph).size(), matches.size())
5944         << "graph: " << graph.DebugString();
5945     // Check that all elements of matches are in the graph.
5946     // Check that elements of first and second are unique.
5947     std::vector<bool> seen_element(graph.LhsSize());
5948     std::vector<bool> seen_matcher(graph.RhsSize());
5949     SCOPED_TRACE(PrintToString(matches));
5950     for (size_t i = 0; i < matches.size(); ++i) {
5951       size_t ilhs = matches[i].first;
5952       size_t irhs = matches[i].second;
5953       EXPECT_TRUE(graph.HasEdge(ilhs, irhs));
5954       EXPECT_FALSE(seen_element[ilhs]);
5955       EXPECT_FALSE(seen_matcher[irhs]);
5956       seen_element[ilhs] = true;
5957       seen_matcher[irhs] = true;
5958     }
5959   } while (graph.NextGraph());
5960 }
5961 
5962 INSTANTIATE_TEST_SUITE_P(AllGraphs, BipartiteTest,
5963                          ::testing::Range(size_t{0}, size_t{5}));
5964 
5965 // Parameterized by a pair interpreted as (LhsSize, RhsSize).
5966 class BipartiteNonSquareTest
5967     : public ::testing::TestWithParam<std::pair<size_t, size_t> > {
5968 };
5969 
TEST_F(BipartiteNonSquareTest,SimpleBacktracking)5970 TEST_F(BipartiteNonSquareTest, SimpleBacktracking) {
5971   //   .......
5972   // 0:-----\ :
5973   // 1:---\ | :
5974   // 2:---\ | :
5975   // 3:-\ | | :
5976   //  :.......:
5977   //    0 1 2
5978   MatchMatrix g(4, 3);
5979   constexpr std::array<std::array<size_t, 2>, 4> kEdges = {
5980       {{{0, 2}}, {{1, 1}}, {{2, 1}}, {{3, 0}}}};
5981   for (size_t i = 0; i < kEdges.size(); ++i) {
5982     g.SetEdge(kEdges[i][0], kEdges[i][1], true);
5983   }
5984   EXPECT_THAT(FindBacktrackingMaxBPM(g),
5985               ElementsAre(Pair(3, 0),
5986                           Pair(AnyOf(1, 2), 1),
5987                           Pair(0, 2))) << g.DebugString();
5988 }
5989 
5990 // Verify a few nonsquare matrices.
TEST_P(BipartiteNonSquareTest,Exhaustive)5991 TEST_P(BipartiteNonSquareTest, Exhaustive) {
5992   size_t nlhs = GetParam().first;
5993   size_t nrhs = GetParam().second;
5994   MatchMatrix graph(nlhs, nrhs);
5995   do {
5996     EXPECT_EQ(FindBacktrackingMaxBPM(graph).size(),
5997               internal::FindMaxBipartiteMatching(graph).size())
5998         << "graph: " << graph.DebugString()
5999         << "\nbacktracking: "
6000         << PrintToString(FindBacktrackingMaxBPM(graph))
6001         << "\nmax flow: "
6002         << PrintToString(internal::FindMaxBipartiteMatching(graph));
6003   } while (graph.NextGraph());
6004 }
6005 
6006 INSTANTIATE_TEST_SUITE_P(AllGraphs, BipartiteNonSquareTest,
6007     testing::Values(
6008         std::make_pair(1, 2),
6009         std::make_pair(2, 1),
6010         std::make_pair(3, 2),
6011         std::make_pair(2, 3),
6012         std::make_pair(4, 1),
6013         std::make_pair(1, 4),
6014         std::make_pair(4, 3),
6015         std::make_pair(3, 4)));
6016 
6017 class BipartiteRandomTest
6018     : public ::testing::TestWithParam<std::pair<int, int> > {
6019 };
6020 
6021 // Verifies a large sample of larger graphs.
TEST_P(BipartiteRandomTest,LargerNets)6022 TEST_P(BipartiteRandomTest, LargerNets) {
6023   int nodes = GetParam().first;
6024   int iters = GetParam().second;
6025   MatchMatrix graph(static_cast<size_t>(nodes), static_cast<size_t>(nodes));
6026 
6027   auto seed = static_cast<uint32_t>(GTEST_FLAG(random_seed));
6028   if (seed == 0) {
6029     seed = static_cast<uint32_t>(time(nullptr));
6030   }
6031 
6032   for (; iters > 0; --iters, ++seed) {
6033     srand(static_cast<unsigned int>(seed));
6034     graph.Randomize();
6035     EXPECT_EQ(FindBacktrackingMaxBPM(graph).size(),
6036               internal::FindMaxBipartiteMatching(graph).size())
6037         << " graph: " << graph.DebugString()
6038         << "\nTo reproduce the failure, rerun the test with the flag"
6039            " --" << GTEST_FLAG_PREFIX_ << "random_seed=" << seed;
6040   }
6041 }
6042 
6043 // Test argument is a std::pair<int, int> representing (nodes, iters).
6044 INSTANTIATE_TEST_SUITE_P(Samples, BipartiteRandomTest,
6045     testing::Values(
6046         std::make_pair(5, 10000),
6047         std::make_pair(6, 5000),
6048         std::make_pair(7, 2000),
6049         std::make_pair(8, 500),
6050         std::make_pair(9, 100)));
6051 
6052 // Tests IsReadableTypeName().
6053 
TEST(IsReadableTypeNameTest,ReturnsTrueForShortNames)6054 TEST(IsReadableTypeNameTest, ReturnsTrueForShortNames) {
6055   EXPECT_TRUE(IsReadableTypeName("int"));
6056   EXPECT_TRUE(IsReadableTypeName("const unsigned char*"));
6057   EXPECT_TRUE(IsReadableTypeName("MyMap<int, void*>"));
6058   EXPECT_TRUE(IsReadableTypeName("void (*)(int, bool)"));
6059 }
6060 
TEST(IsReadableTypeNameTest,ReturnsTrueForLongNonTemplateNonFunctionNames)6061 TEST(IsReadableTypeNameTest, ReturnsTrueForLongNonTemplateNonFunctionNames) {
6062   EXPECT_TRUE(IsReadableTypeName("my_long_namespace::MyClassName"));
6063   EXPECT_TRUE(IsReadableTypeName("int [5][6][7][8][9][10][11]"));
6064   EXPECT_TRUE(IsReadableTypeName("my_namespace::MyOuterClass::MyInnerClass"));
6065 }
6066 
TEST(IsReadableTypeNameTest,ReturnsFalseForLongTemplateNames)6067 TEST(IsReadableTypeNameTest, ReturnsFalseForLongTemplateNames) {
6068   EXPECT_FALSE(
6069       IsReadableTypeName("basic_string<char, std::char_traits<char> >"));
6070   EXPECT_FALSE(IsReadableTypeName("std::vector<int, std::alloc_traits<int> >"));
6071 }
6072 
TEST(IsReadableTypeNameTest,ReturnsFalseForLongFunctionTypeNames)6073 TEST(IsReadableTypeNameTest, ReturnsFalseForLongFunctionTypeNames) {
6074   EXPECT_FALSE(IsReadableTypeName("void (&)(int, bool, char, float)"));
6075 }
6076 
6077 // Tests FormatMatcherDescription().
6078 
TEST(FormatMatcherDescriptionTest,WorksForEmptyDescription)6079 TEST(FormatMatcherDescriptionTest, WorksForEmptyDescription) {
6080   EXPECT_EQ("is even",
6081             FormatMatcherDescription(false, "IsEven", Strings()));
6082   EXPECT_EQ("not (is even)",
6083             FormatMatcherDescription(true, "IsEven", Strings()));
6084 
6085   const char* params[] = {"5"};
6086   EXPECT_EQ("equals 5",
6087             FormatMatcherDescription(false, "Equals",
6088                                      Strings(params, params + 1)));
6089 
6090   const char* params2[] = {"5", "8"};
6091   EXPECT_EQ("is in range (5, 8)",
6092             FormatMatcherDescription(false, "IsInRange",
6093                                      Strings(params2, params2 + 2)));
6094 }
6095 
6096 // Tests PolymorphicMatcher::mutable_impl().
TEST(PolymorphicMatcherTest,CanAccessMutableImpl)6097 TEST(PolymorphicMatcherTest, CanAccessMutableImpl) {
6098   PolymorphicMatcher<DivisibleByImpl> m(DivisibleByImpl(42));
6099   DivisibleByImpl& impl = m.mutable_impl();
6100   EXPECT_EQ(42, impl.divider());
6101 
6102   impl.set_divider(0);
6103   EXPECT_EQ(0, m.mutable_impl().divider());
6104 }
6105 
6106 // Tests PolymorphicMatcher::impl().
TEST(PolymorphicMatcherTest,CanAccessImpl)6107 TEST(PolymorphicMatcherTest, CanAccessImpl) {
6108   const PolymorphicMatcher<DivisibleByImpl> m(DivisibleByImpl(42));
6109   const DivisibleByImpl& impl = m.impl();
6110   EXPECT_EQ(42, impl.divider());
6111 }
6112 
TEST(MatcherTupleTest,ExplainsMatchFailure)6113 TEST(MatcherTupleTest, ExplainsMatchFailure) {
6114   stringstream ss1;
6115   ExplainMatchFailureTupleTo(
6116       std::make_tuple(Matcher<char>(Eq('a')), GreaterThan(5)),
6117       std::make_tuple('a', 10), &ss1);
6118   EXPECT_EQ("", ss1.str());  // Successful match.
6119 
6120   stringstream ss2;
6121   ExplainMatchFailureTupleTo(
6122       std::make_tuple(GreaterThan(5), Matcher<char>(Eq('a'))),
6123       std::make_tuple(2, 'b'), &ss2);
6124   EXPECT_EQ("  Expected arg #0: is > 5\n"
6125             "           Actual: 2, which is 3 less than 5\n"
6126             "  Expected arg #1: is equal to 'a' (97, 0x61)\n"
6127             "           Actual: 'b' (98, 0x62)\n",
6128             ss2.str());  // Failed match where both arguments need explanation.
6129 
6130   stringstream ss3;
6131   ExplainMatchFailureTupleTo(
6132       std::make_tuple(GreaterThan(5), Matcher<char>(Eq('a'))),
6133       std::make_tuple(2, 'a'), &ss3);
6134   EXPECT_EQ("  Expected arg #0: is > 5\n"
6135             "           Actual: 2, which is 3 less than 5\n",
6136             ss3.str());  // Failed match where only one argument needs
6137                          // explanation.
6138 }
6139 
6140 // Tests Each().
6141 
TEST(EachTest,ExplainsMatchResultCorrectly)6142 TEST(EachTest, ExplainsMatchResultCorrectly) {
6143   set<int> a;  // empty
6144 
6145   Matcher<set<int> > m = Each(2);
6146   EXPECT_EQ("", Explain(m, a));
6147 
6148   Matcher<const int(&)[1]> n = Each(1);  // NOLINT
6149 
6150   const int b[1] = {1};
6151   EXPECT_EQ("", Explain(n, b));
6152 
6153   n = Each(3);
6154   EXPECT_EQ("whose element #0 doesn't match", Explain(n, b));
6155 
6156   a.insert(1);
6157   a.insert(2);
6158   a.insert(3);
6159   m = Each(GreaterThan(0));
6160   EXPECT_EQ("", Explain(m, a));
6161 
6162   m = Each(GreaterThan(10));
6163   EXPECT_EQ("whose element #0 doesn't match, which is 9 less than 10",
6164             Explain(m, a));
6165 }
6166 
TEST(EachTest,DescribesItselfCorrectly)6167 TEST(EachTest, DescribesItselfCorrectly) {
6168   Matcher<vector<int> > m = Each(1);
6169   EXPECT_EQ("only contains elements that is equal to 1", Describe(m));
6170 
6171   Matcher<vector<int> > m2 = Not(m);
6172   EXPECT_EQ("contains some element that isn't equal to 1", Describe(m2));
6173 }
6174 
TEST(EachTest,MatchesVectorWhenAllElementsMatch)6175 TEST(EachTest, MatchesVectorWhenAllElementsMatch) {
6176   vector<int> some_vector;
6177   EXPECT_THAT(some_vector, Each(1));
6178   some_vector.push_back(3);
6179   EXPECT_THAT(some_vector, Not(Each(1)));
6180   EXPECT_THAT(some_vector, Each(3));
6181   some_vector.push_back(1);
6182   some_vector.push_back(2);
6183   EXPECT_THAT(some_vector, Not(Each(3)));
6184   EXPECT_THAT(some_vector, Each(Lt(3.5)));
6185 
6186   vector<std::string> another_vector;
6187   another_vector.push_back("fee");
6188   EXPECT_THAT(another_vector, Each(std::string("fee")));
6189   another_vector.push_back("fie");
6190   another_vector.push_back("foe");
6191   another_vector.push_back("fum");
6192   EXPECT_THAT(another_vector, Not(Each(std::string("fee"))));
6193 }
6194 
TEST(EachTest,MatchesMapWhenAllElementsMatch)6195 TEST(EachTest, MatchesMapWhenAllElementsMatch) {
6196   map<const char*, int> my_map;
6197   const char* bar = "a string";
6198   my_map[bar] = 2;
6199   EXPECT_THAT(my_map, Each(make_pair(bar, 2)));
6200 
6201   map<std::string, int> another_map;
6202   EXPECT_THAT(another_map, Each(make_pair(std::string("fee"), 1)));
6203   another_map["fee"] = 1;
6204   EXPECT_THAT(another_map, Each(make_pair(std::string("fee"), 1)));
6205   another_map["fie"] = 2;
6206   another_map["foe"] = 3;
6207   another_map["fum"] = 4;
6208   EXPECT_THAT(another_map, Not(Each(make_pair(std::string("fee"), 1))));
6209   EXPECT_THAT(another_map, Not(Each(make_pair(std::string("fum"), 1))));
6210   EXPECT_THAT(another_map, Each(Pair(_, Gt(0))));
6211 }
6212 
TEST(EachTest,AcceptsMatcher)6213 TEST(EachTest, AcceptsMatcher) {
6214   const int a[] = {1, 2, 3};
6215   EXPECT_THAT(a, Each(Gt(0)));
6216   EXPECT_THAT(a, Not(Each(Gt(1))));
6217 }
6218 
TEST(EachTest,WorksForNativeArrayAsTuple)6219 TEST(EachTest, WorksForNativeArrayAsTuple) {
6220   const int a[] = {1, 2};
6221   const int* const pointer = a;
6222   EXPECT_THAT(std::make_tuple(pointer, 2), Each(Gt(0)));
6223   EXPECT_THAT(std::make_tuple(pointer, 2), Not(Each(Gt(1))));
6224 }
6225 
TEST(EachTest,WorksWithMoveOnly)6226 TEST(EachTest, WorksWithMoveOnly) {
6227   ContainerHelper helper;
6228   EXPECT_CALL(helper, Call(Each(Pointee(Gt(0)))));
6229   helper.Call(MakeUniquePtrs({1, 2}));
6230 }
6231 
6232 // For testing Pointwise().
6233 class IsHalfOfMatcher {
6234  public:
6235   template <typename T1, typename T2>
MatchAndExplain(const std::tuple<T1,T2> & a_pair,MatchResultListener * listener) const6236   bool MatchAndExplain(const std::tuple<T1, T2>& a_pair,
6237                        MatchResultListener* listener) const {
6238     if (std::get<0>(a_pair) == std::get<1>(a_pair) / 2) {
6239       *listener << "where the second is " << std::get<1>(a_pair);
6240       return true;
6241     } else {
6242       *listener << "where the second/2 is " << std::get<1>(a_pair) / 2;
6243       return false;
6244     }
6245   }
6246 
DescribeTo(ostream * os) const6247   void DescribeTo(ostream* os) const {
6248     *os << "are a pair where the first is half of the second";
6249   }
6250 
DescribeNegationTo(ostream * os) const6251   void DescribeNegationTo(ostream* os) const {
6252     *os << "are a pair where the first isn't half of the second";
6253   }
6254 };
6255 
IsHalfOf()6256 PolymorphicMatcher<IsHalfOfMatcher> IsHalfOf() {
6257   return MakePolymorphicMatcher(IsHalfOfMatcher());
6258 }
6259 
TEST(PointwiseTest,DescribesSelf)6260 TEST(PointwiseTest, DescribesSelf) {
6261   vector<int> rhs;
6262   rhs.push_back(1);
6263   rhs.push_back(2);
6264   rhs.push_back(3);
6265   const Matcher<const vector<int>&> m = Pointwise(IsHalfOf(), rhs);
6266   EXPECT_EQ("contains 3 values, where each value and its corresponding value "
6267             "in { 1, 2, 3 } are a pair where the first is half of the second",
6268             Describe(m));
6269   EXPECT_EQ("doesn't contain exactly 3 values, or contains a value x at some "
6270             "index i where x and the i-th value of { 1, 2, 3 } are a pair "
6271             "where the first isn't half of the second",
6272             DescribeNegation(m));
6273 }
6274 
TEST(PointwiseTest,MakesCopyOfRhs)6275 TEST(PointwiseTest, MakesCopyOfRhs) {
6276   list<signed char> rhs;
6277   rhs.push_back(2);
6278   rhs.push_back(4);
6279 
6280   int lhs[] = {1, 2};
6281   const Matcher<const int (&)[2]> m = Pointwise(IsHalfOf(), rhs);
6282   EXPECT_THAT(lhs, m);
6283 
6284   // Changing rhs now shouldn't affect m, which made a copy of rhs.
6285   rhs.push_back(6);
6286   EXPECT_THAT(lhs, m);
6287 }
6288 
TEST(PointwiseTest,WorksForLhsNativeArray)6289 TEST(PointwiseTest, WorksForLhsNativeArray) {
6290   const int lhs[] = {1, 2, 3};
6291   vector<int> rhs;
6292   rhs.push_back(2);
6293   rhs.push_back(4);
6294   rhs.push_back(6);
6295   EXPECT_THAT(lhs, Pointwise(Lt(), rhs));
6296   EXPECT_THAT(lhs, Not(Pointwise(Gt(), rhs)));
6297 }
6298 
TEST(PointwiseTest,WorksForRhsNativeArray)6299 TEST(PointwiseTest, WorksForRhsNativeArray) {
6300   const int rhs[] = {1, 2, 3};
6301   vector<int> lhs;
6302   lhs.push_back(2);
6303   lhs.push_back(4);
6304   lhs.push_back(6);
6305   EXPECT_THAT(lhs, Pointwise(Gt(), rhs));
6306   EXPECT_THAT(lhs, Not(Pointwise(Lt(), rhs)));
6307 }
6308 
6309 // Test is effective only with sanitizers.
TEST(PointwiseTest,WorksForVectorOfBool)6310 TEST(PointwiseTest, WorksForVectorOfBool) {
6311   vector<bool> rhs(3, false);
6312   rhs[1] = true;
6313   vector<bool> lhs = rhs;
6314   EXPECT_THAT(lhs, Pointwise(Eq(), rhs));
6315   rhs[0] = true;
6316   EXPECT_THAT(lhs, Not(Pointwise(Eq(), rhs)));
6317 }
6318 
6319 
TEST(PointwiseTest,WorksForRhsInitializerList)6320 TEST(PointwiseTest, WorksForRhsInitializerList) {
6321   const vector<int> lhs{2, 4, 6};
6322   EXPECT_THAT(lhs, Pointwise(Gt(), {1, 2, 3}));
6323   EXPECT_THAT(lhs, Not(Pointwise(Lt(), {3, 3, 7})));
6324 }
6325 
6326 
TEST(PointwiseTest,RejectsWrongSize)6327 TEST(PointwiseTest, RejectsWrongSize) {
6328   const double lhs[2] = {1, 2};
6329   const int rhs[1] = {0};
6330   EXPECT_THAT(lhs, Not(Pointwise(Gt(), rhs)));
6331   EXPECT_EQ("which contains 2 values",
6332             Explain(Pointwise(Gt(), rhs), lhs));
6333 
6334   const int rhs2[3] = {0, 1, 2};
6335   EXPECT_THAT(lhs, Not(Pointwise(Gt(), rhs2)));
6336 }
6337 
TEST(PointwiseTest,RejectsWrongContent)6338 TEST(PointwiseTest, RejectsWrongContent) {
6339   const double lhs[3] = {1, 2, 3};
6340   const int rhs[3] = {2, 6, 4};
6341   EXPECT_THAT(lhs, Not(Pointwise(IsHalfOf(), rhs)));
6342   EXPECT_EQ("where the value pair (2, 6) at index #1 don't match, "
6343             "where the second/2 is 3",
6344             Explain(Pointwise(IsHalfOf(), rhs), lhs));
6345 }
6346 
TEST(PointwiseTest,AcceptsCorrectContent)6347 TEST(PointwiseTest, AcceptsCorrectContent) {
6348   const double lhs[3] = {1, 2, 3};
6349   const int rhs[3] = {2, 4, 6};
6350   EXPECT_THAT(lhs, Pointwise(IsHalfOf(), rhs));
6351   EXPECT_EQ("", Explain(Pointwise(IsHalfOf(), rhs), lhs));
6352 }
6353 
TEST(PointwiseTest,AllowsMonomorphicInnerMatcher)6354 TEST(PointwiseTest, AllowsMonomorphicInnerMatcher) {
6355   const double lhs[3] = {1, 2, 3};
6356   const int rhs[3] = {2, 4, 6};
6357   const Matcher<std::tuple<const double&, const int&>> m1 = IsHalfOf();
6358   EXPECT_THAT(lhs, Pointwise(m1, rhs));
6359   EXPECT_EQ("", Explain(Pointwise(m1, rhs), lhs));
6360 
6361   // This type works as a std::tuple<const double&, const int&> can be
6362   // implicitly cast to std::tuple<double, int>.
6363   const Matcher<std::tuple<double, int>> m2 = IsHalfOf();
6364   EXPECT_THAT(lhs, Pointwise(m2, rhs));
6365   EXPECT_EQ("", Explain(Pointwise(m2, rhs), lhs));
6366 }
6367 
6368 MATCHER(PointeeEquals, "Points to an equal value") {
6369   return ExplainMatchResult(::testing::Pointee(::testing::get<1>(arg)),
6370                             ::testing::get<0>(arg), result_listener);
6371 }
6372 
TEST(PointwiseTest,WorksWithMoveOnly)6373 TEST(PointwiseTest, WorksWithMoveOnly) {
6374   ContainerHelper helper;
6375   EXPECT_CALL(helper, Call(Pointwise(PointeeEquals(), std::vector<int>{1, 2})));
6376   helper.Call(MakeUniquePtrs({1, 2}));
6377 }
6378 
TEST(UnorderedPointwiseTest,DescribesSelf)6379 TEST(UnorderedPointwiseTest, DescribesSelf) {
6380   vector<int> rhs;
6381   rhs.push_back(1);
6382   rhs.push_back(2);
6383   rhs.push_back(3);
6384   const Matcher<const vector<int>&> m = UnorderedPointwise(IsHalfOf(), rhs);
6385   EXPECT_EQ(
6386       "has 3 elements and there exists some permutation of elements such "
6387       "that:\n"
6388       " - element #0 and 1 are a pair where the first is half of the second, "
6389       "and\n"
6390       " - element #1 and 2 are a pair where the first is half of the second, "
6391       "and\n"
6392       " - element #2 and 3 are a pair where the first is half of the second",
6393       Describe(m));
6394   EXPECT_EQ(
6395       "doesn't have 3 elements, or there exists no permutation of elements "
6396       "such that:\n"
6397       " - element #0 and 1 are a pair where the first is half of the second, "
6398       "and\n"
6399       " - element #1 and 2 are a pair where the first is half of the second, "
6400       "and\n"
6401       " - element #2 and 3 are a pair where the first is half of the second",
6402       DescribeNegation(m));
6403 }
6404 
TEST(UnorderedPointwiseTest,MakesCopyOfRhs)6405 TEST(UnorderedPointwiseTest, MakesCopyOfRhs) {
6406   list<signed char> rhs;
6407   rhs.push_back(2);
6408   rhs.push_back(4);
6409 
6410   int lhs[] = {2, 1};
6411   const Matcher<const int (&)[2]> m = UnorderedPointwise(IsHalfOf(), rhs);
6412   EXPECT_THAT(lhs, m);
6413 
6414   // Changing rhs now shouldn't affect m, which made a copy of rhs.
6415   rhs.push_back(6);
6416   EXPECT_THAT(lhs, m);
6417 }
6418 
TEST(UnorderedPointwiseTest,WorksForLhsNativeArray)6419 TEST(UnorderedPointwiseTest, WorksForLhsNativeArray) {
6420   const int lhs[] = {1, 2, 3};
6421   vector<int> rhs;
6422   rhs.push_back(4);
6423   rhs.push_back(6);
6424   rhs.push_back(2);
6425   EXPECT_THAT(lhs, UnorderedPointwise(Lt(), rhs));
6426   EXPECT_THAT(lhs, Not(UnorderedPointwise(Gt(), rhs)));
6427 }
6428 
TEST(UnorderedPointwiseTest,WorksForRhsNativeArray)6429 TEST(UnorderedPointwiseTest, WorksForRhsNativeArray) {
6430   const int rhs[] = {1, 2, 3};
6431   vector<int> lhs;
6432   lhs.push_back(4);
6433   lhs.push_back(2);
6434   lhs.push_back(6);
6435   EXPECT_THAT(lhs, UnorderedPointwise(Gt(), rhs));
6436   EXPECT_THAT(lhs, Not(UnorderedPointwise(Lt(), rhs)));
6437 }
6438 
6439 
TEST(UnorderedPointwiseTest,WorksForRhsInitializerList)6440 TEST(UnorderedPointwiseTest, WorksForRhsInitializerList) {
6441   const vector<int> lhs{2, 4, 6};
6442   EXPECT_THAT(lhs, UnorderedPointwise(Gt(), {5, 1, 3}));
6443   EXPECT_THAT(lhs, Not(UnorderedPointwise(Lt(), {1, 1, 7})));
6444 }
6445 
6446 
TEST(UnorderedPointwiseTest,RejectsWrongSize)6447 TEST(UnorderedPointwiseTest, RejectsWrongSize) {
6448   const double lhs[2] = {1, 2};
6449   const int rhs[1] = {0};
6450   EXPECT_THAT(lhs, Not(UnorderedPointwise(Gt(), rhs)));
6451   EXPECT_EQ("which has 2 elements",
6452             Explain(UnorderedPointwise(Gt(), rhs), lhs));
6453 
6454   const int rhs2[3] = {0, 1, 2};
6455   EXPECT_THAT(lhs, Not(UnorderedPointwise(Gt(), rhs2)));
6456 }
6457 
TEST(UnorderedPointwiseTest,RejectsWrongContent)6458 TEST(UnorderedPointwiseTest, RejectsWrongContent) {
6459   const double lhs[3] = {1, 2, 3};
6460   const int rhs[3] = {2, 6, 6};
6461   EXPECT_THAT(lhs, Not(UnorderedPointwise(IsHalfOf(), rhs)));
6462   EXPECT_EQ("where the following elements don't match any matchers:\n"
6463             "element #1: 2",
6464             Explain(UnorderedPointwise(IsHalfOf(), rhs), lhs));
6465 }
6466 
TEST(UnorderedPointwiseTest,AcceptsCorrectContentInSameOrder)6467 TEST(UnorderedPointwiseTest, AcceptsCorrectContentInSameOrder) {
6468   const double lhs[3] = {1, 2, 3};
6469   const int rhs[3] = {2, 4, 6};
6470   EXPECT_THAT(lhs, UnorderedPointwise(IsHalfOf(), rhs));
6471 }
6472 
TEST(UnorderedPointwiseTest,AcceptsCorrectContentInDifferentOrder)6473 TEST(UnorderedPointwiseTest, AcceptsCorrectContentInDifferentOrder) {
6474   const double lhs[3] = {1, 2, 3};
6475   const int rhs[3] = {6, 4, 2};
6476   EXPECT_THAT(lhs, UnorderedPointwise(IsHalfOf(), rhs));
6477 }
6478 
TEST(UnorderedPointwiseTest,AllowsMonomorphicInnerMatcher)6479 TEST(UnorderedPointwiseTest, AllowsMonomorphicInnerMatcher) {
6480   const double lhs[3] = {1, 2, 3};
6481   const int rhs[3] = {4, 6, 2};
6482   const Matcher<std::tuple<const double&, const int&>> m1 = IsHalfOf();
6483   EXPECT_THAT(lhs, UnorderedPointwise(m1, rhs));
6484 
6485   // This type works as a std::tuple<const double&, const int&> can be
6486   // implicitly cast to std::tuple<double, int>.
6487   const Matcher<std::tuple<double, int>> m2 = IsHalfOf();
6488   EXPECT_THAT(lhs, UnorderedPointwise(m2, rhs));
6489 }
6490 
TEST(UnorderedPointwiseTest,WorksWithMoveOnly)6491 TEST(UnorderedPointwiseTest, WorksWithMoveOnly) {
6492   ContainerHelper helper;
6493   EXPECT_CALL(helper, Call(UnorderedPointwise(PointeeEquals(),
6494                                               std::vector<int>{1, 2})));
6495   helper.Call(MakeUniquePtrs({2, 1}));
6496 }
6497 
6498 // Sample optional type implementation with minimal requirements for use with
6499 // Optional matcher.
6500 template <typename T>
6501 class SampleOptional {
6502  public:
6503   using value_type = T;
SampleOptional(T value)6504   explicit SampleOptional(T value)
6505       : value_(std::move(value)), has_value_(true) {}
SampleOptional()6506   SampleOptional() : value_(), has_value_(false) {}
operator bool() const6507   operator bool() const { return has_value_; }
operator *() const6508   const T& operator*() const { return value_; }
6509 
6510  private:
6511   T value_;
6512   bool has_value_;
6513 };
6514 
TEST(OptionalTest,DescribesSelf)6515 TEST(OptionalTest, DescribesSelf) {
6516   const Matcher<SampleOptional<int>> m = Optional(Eq(1));
6517   EXPECT_EQ("value is equal to 1", Describe(m));
6518 }
6519 
TEST(OptionalTest,ExplainsSelf)6520 TEST(OptionalTest, ExplainsSelf) {
6521   const Matcher<SampleOptional<int>> m = Optional(Eq(1));
6522   EXPECT_EQ("whose value 1 matches", Explain(m, SampleOptional<int>(1)));
6523   EXPECT_EQ("whose value 2 doesn't match", Explain(m, SampleOptional<int>(2)));
6524 }
6525 
TEST(OptionalTest,MatchesNonEmptyOptional)6526 TEST(OptionalTest, MatchesNonEmptyOptional) {
6527   const Matcher<SampleOptional<int>> m1 = Optional(1);
6528   const Matcher<SampleOptional<int>> m2 = Optional(Eq(2));
6529   const Matcher<SampleOptional<int>> m3 = Optional(Lt(3));
6530   SampleOptional<int> opt(1);
6531   EXPECT_TRUE(m1.Matches(opt));
6532   EXPECT_FALSE(m2.Matches(opt));
6533   EXPECT_TRUE(m3.Matches(opt));
6534 }
6535 
TEST(OptionalTest,DoesNotMatchNullopt)6536 TEST(OptionalTest, DoesNotMatchNullopt) {
6537   const Matcher<SampleOptional<int>> m = Optional(1);
6538   SampleOptional<int> empty;
6539   EXPECT_FALSE(m.Matches(empty));
6540 }
6541 
TEST(OptionalTest,WorksWithMoveOnly)6542 TEST(OptionalTest, WorksWithMoveOnly) {
6543   Matcher<SampleOptional<std::unique_ptr<int>>> m = Optional(Eq(nullptr));
6544   EXPECT_TRUE(m.Matches(SampleOptional<std::unique_ptr<int>>(nullptr)));
6545 }
6546 
6547 class SampleVariantIntString {
6548  public:
SampleVariantIntString(int i)6549   SampleVariantIntString(int i) : i_(i), has_int_(true) {}
SampleVariantIntString(const std::string & s)6550   SampleVariantIntString(const std::string& s) : s_(s), has_int_(false) {}
6551 
6552   template <typename T>
holds_alternative(const SampleVariantIntString & value)6553   friend bool holds_alternative(const SampleVariantIntString& value) {
6554     return value.has_int_ == std::is_same<T, int>::value;
6555   }
6556 
6557   template <typename T>
get(const SampleVariantIntString & value)6558   friend const T& get(const SampleVariantIntString& value) {
6559     return value.get_impl(static_cast<T*>(nullptr));
6560   }
6561 
6562  private:
get_impl(int *) const6563   const int& get_impl(int*) const { return i_; }
get_impl(std::string *) const6564   const std::string& get_impl(std::string*) const { return s_; }
6565 
6566   int i_;
6567   std::string s_;
6568   bool has_int_;
6569 };
6570 
TEST(VariantTest,DescribesSelf)6571 TEST(VariantTest, DescribesSelf) {
6572   const Matcher<SampleVariantIntString> m = VariantWith<int>(Eq(1));
6573   EXPECT_THAT(Describe(m), ContainsRegex("is a variant<> with value of type "
6574                                          "'.*' and the value is equal to 1"));
6575 }
6576 
TEST(VariantTest,ExplainsSelf)6577 TEST(VariantTest, ExplainsSelf) {
6578   const Matcher<SampleVariantIntString> m = VariantWith<int>(Eq(1));
6579   EXPECT_THAT(Explain(m, SampleVariantIntString(1)),
6580               ContainsRegex("whose value 1"));
6581   EXPECT_THAT(Explain(m, SampleVariantIntString("A")),
6582               HasSubstr("whose value is not of type '"));
6583   EXPECT_THAT(Explain(m, SampleVariantIntString(2)),
6584               "whose value 2 doesn't match");
6585 }
6586 
TEST(VariantTest,FullMatch)6587 TEST(VariantTest, FullMatch) {
6588   Matcher<SampleVariantIntString> m = VariantWith<int>(Eq(1));
6589   EXPECT_TRUE(m.Matches(SampleVariantIntString(1)));
6590 
6591   m = VariantWith<std::string>(Eq("1"));
6592   EXPECT_TRUE(m.Matches(SampleVariantIntString("1")));
6593 }
6594 
TEST(VariantTest,TypeDoesNotMatch)6595 TEST(VariantTest, TypeDoesNotMatch) {
6596   Matcher<SampleVariantIntString> m = VariantWith<int>(Eq(1));
6597   EXPECT_FALSE(m.Matches(SampleVariantIntString("1")));
6598 
6599   m = VariantWith<std::string>(Eq("1"));
6600   EXPECT_FALSE(m.Matches(SampleVariantIntString(1)));
6601 }
6602 
TEST(VariantTest,InnerDoesNotMatch)6603 TEST(VariantTest, InnerDoesNotMatch) {
6604   Matcher<SampleVariantIntString> m = VariantWith<int>(Eq(1));
6605   EXPECT_FALSE(m.Matches(SampleVariantIntString(2)));
6606 
6607   m = VariantWith<std::string>(Eq("1"));
6608   EXPECT_FALSE(m.Matches(SampleVariantIntString("2")));
6609 }
6610 
6611 class SampleAnyType {
6612  public:
SampleAnyType(int i)6613   explicit SampleAnyType(int i) : index_(0), i_(i) {}
SampleAnyType(const std::string & s)6614   explicit SampleAnyType(const std::string& s) : index_(1), s_(s) {}
6615 
6616   template <typename T>
any_cast(const SampleAnyType * any)6617   friend const T* any_cast(const SampleAnyType* any) {
6618     return any->get_impl(static_cast<T*>(nullptr));
6619   }
6620 
6621  private:
6622   int index_;
6623   int i_;
6624   std::string s_;
6625 
get_impl(int *) const6626   const int* get_impl(int*) const { return index_ == 0 ? &i_ : nullptr; }
get_impl(std::string *) const6627   const std::string* get_impl(std::string*) const {
6628     return index_ == 1 ? &s_ : nullptr;
6629   }
6630 };
6631 
TEST(AnyWithTest,FullMatch)6632 TEST(AnyWithTest, FullMatch) {
6633   Matcher<SampleAnyType> m = AnyWith<int>(Eq(1));
6634   EXPECT_TRUE(m.Matches(SampleAnyType(1)));
6635 }
6636 
TEST(AnyWithTest,TestBadCastType)6637 TEST(AnyWithTest, TestBadCastType) {
6638   Matcher<SampleAnyType> m = AnyWith<std::string>(Eq("fail"));
6639   EXPECT_FALSE(m.Matches(SampleAnyType(1)));
6640 }
6641 
TEST(AnyWithTest,TestUseInContainers)6642 TEST(AnyWithTest, TestUseInContainers) {
6643   std::vector<SampleAnyType> a;
6644   a.emplace_back(1);
6645   a.emplace_back(2);
6646   a.emplace_back(3);
6647   EXPECT_THAT(
6648       a, ElementsAreArray({AnyWith<int>(1), AnyWith<int>(2), AnyWith<int>(3)}));
6649 
6650   std::vector<SampleAnyType> b;
6651   b.emplace_back("hello");
6652   b.emplace_back("merhaba");
6653   b.emplace_back("salut");
6654   EXPECT_THAT(b, ElementsAreArray({AnyWith<std::string>("hello"),
6655                                    AnyWith<std::string>("merhaba"),
6656                                    AnyWith<std::string>("salut")}));
6657 }
TEST(AnyWithTest,TestCompare)6658 TEST(AnyWithTest, TestCompare) {
6659   EXPECT_THAT(SampleAnyType(1), AnyWith<int>(Gt(0)));
6660 }
6661 
TEST(AnyWithTest,DescribesSelf)6662 TEST(AnyWithTest, DescribesSelf) {
6663   const Matcher<const SampleAnyType&> m = AnyWith<int>(Eq(1));
6664   EXPECT_THAT(Describe(m), ContainsRegex("is an 'any' type with value of type "
6665                                          "'.*' and the value is equal to 1"));
6666 }
6667 
TEST(AnyWithTest,ExplainsSelf)6668 TEST(AnyWithTest, ExplainsSelf) {
6669   const Matcher<const SampleAnyType&> m = AnyWith<int>(Eq(1));
6670 
6671   EXPECT_THAT(Explain(m, SampleAnyType(1)), ContainsRegex("whose value 1"));
6672   EXPECT_THAT(Explain(m, SampleAnyType("A")),
6673               HasSubstr("whose value is not of type '"));
6674   EXPECT_THAT(Explain(m, SampleAnyType(2)), "whose value 2 doesn't match");
6675 }
6676 
TEST(PointeeTest,WorksOnMoveOnlyType)6677 TEST(PointeeTest, WorksOnMoveOnlyType) {
6678   std::unique_ptr<int> p(new int(3));
6679   EXPECT_THAT(p, Pointee(Eq(3)));
6680   EXPECT_THAT(p, Not(Pointee(Eq(2))));
6681 }
6682 
TEST(NotTest,WorksOnMoveOnlyType)6683 TEST(NotTest, WorksOnMoveOnlyType) {
6684   std::unique_ptr<int> p(new int(3));
6685   EXPECT_THAT(p, Pointee(Eq(3)));
6686   EXPECT_THAT(p, Not(Pointee(Eq(2))));
6687 }
6688 
6689 // Tests Args<k0, ..., kn>(m).
6690 
TEST(ArgsTest,AcceptsZeroTemplateArg)6691 TEST(ArgsTest, AcceptsZeroTemplateArg) {
6692   const std::tuple<int, bool> t(5, true);
6693   EXPECT_THAT(t, Args<>(Eq(std::tuple<>())));
6694   EXPECT_THAT(t, Not(Args<>(Ne(std::tuple<>()))));
6695 }
6696 
TEST(ArgsTest,AcceptsOneTemplateArg)6697 TEST(ArgsTest, AcceptsOneTemplateArg) {
6698   const std::tuple<int, bool> t(5, true);
6699   EXPECT_THAT(t, Args<0>(Eq(std::make_tuple(5))));
6700   EXPECT_THAT(t, Args<1>(Eq(std::make_tuple(true))));
6701   EXPECT_THAT(t, Not(Args<1>(Eq(std::make_tuple(false)))));
6702 }
6703 
TEST(ArgsTest,AcceptsTwoTemplateArgs)6704 TEST(ArgsTest, AcceptsTwoTemplateArgs) {
6705   const std::tuple<short, int, long> t(4, 5, 6L);  // NOLINT
6706 
6707   EXPECT_THAT(t, (Args<0, 1>(Lt())));
6708   EXPECT_THAT(t, (Args<1, 2>(Lt())));
6709   EXPECT_THAT(t, Not(Args<0, 2>(Gt())));
6710 }
6711 
TEST(ArgsTest,AcceptsRepeatedTemplateArgs)6712 TEST(ArgsTest, AcceptsRepeatedTemplateArgs) {
6713   const std::tuple<short, int, long> t(4, 5, 6L);  // NOLINT
6714   EXPECT_THAT(t, (Args<0, 0>(Eq())));
6715   EXPECT_THAT(t, Not(Args<1, 1>(Ne())));
6716 }
6717 
TEST(ArgsTest,AcceptsDecreasingTemplateArgs)6718 TEST(ArgsTest, AcceptsDecreasingTemplateArgs) {
6719   const std::tuple<short, int, long> t(4, 5, 6L);  // NOLINT
6720   EXPECT_THAT(t, (Args<2, 0>(Gt())));
6721   EXPECT_THAT(t, Not(Args<2, 1>(Lt())));
6722 }
6723 
6724 MATCHER(SumIsZero, "") {
6725   return std::get<0>(arg) + std::get<1>(arg) + std::get<2>(arg) == 0;
6726 }
6727 
TEST(ArgsTest,AcceptsMoreTemplateArgsThanArityOfOriginalTuple)6728 TEST(ArgsTest, AcceptsMoreTemplateArgsThanArityOfOriginalTuple) {
6729   EXPECT_THAT(std::make_tuple(-1, 2), (Args<0, 0, 1>(SumIsZero())));
6730   EXPECT_THAT(std::make_tuple(1, 2), Not(Args<0, 0, 1>(SumIsZero())));
6731 }
6732 
TEST(ArgsTest,CanBeNested)6733 TEST(ArgsTest, CanBeNested) {
6734   const std::tuple<short, int, long, int> t(4, 5, 6L, 6);  // NOLINT
6735   EXPECT_THAT(t, (Args<1, 2, 3>(Args<1, 2>(Eq()))));
6736   EXPECT_THAT(t, (Args<0, 1, 3>(Args<0, 2>(Lt()))));
6737 }
6738 
TEST(ArgsTest,CanMatchTupleByValue)6739 TEST(ArgsTest, CanMatchTupleByValue) {
6740   typedef std::tuple<char, int, int> Tuple3;
6741   const Matcher<Tuple3> m = Args<1, 2>(Lt());
6742   EXPECT_TRUE(m.Matches(Tuple3('a', 1, 2)));
6743   EXPECT_FALSE(m.Matches(Tuple3('b', 2, 2)));
6744 }
6745 
TEST(ArgsTest,CanMatchTupleByReference)6746 TEST(ArgsTest, CanMatchTupleByReference) {
6747   typedef std::tuple<char, char, int> Tuple3;
6748   const Matcher<const Tuple3&> m = Args<0, 1>(Lt());
6749   EXPECT_TRUE(m.Matches(Tuple3('a', 'b', 2)));
6750   EXPECT_FALSE(m.Matches(Tuple3('b', 'b', 2)));
6751 }
6752 
6753 // Validates that arg is printed as str.
6754 MATCHER_P(PrintsAs, str, "") {
6755   return testing::PrintToString(arg) == str;
6756 }
6757 
TEST(ArgsTest,AcceptsTenTemplateArgs)6758 TEST(ArgsTest, AcceptsTenTemplateArgs) {
6759   EXPECT_THAT(std::make_tuple(0, 1L, 2, 3L, 4, 5, 6, 7, 8, 9),
6760               (Args<9, 8, 7, 6, 5, 4, 3, 2, 1, 0>(
6761                   PrintsAs("(9, 8, 7, 6, 5, 4, 3, 2, 1, 0)"))));
6762   EXPECT_THAT(std::make_tuple(0, 1L, 2, 3L, 4, 5, 6, 7, 8, 9),
6763               Not(Args<9, 8, 7, 6, 5, 4, 3, 2, 1, 0>(
6764                   PrintsAs("(0, 8, 7, 6, 5, 4, 3, 2, 1, 0)"))));
6765 }
6766 
TEST(ArgsTest,DescirbesSelfCorrectly)6767 TEST(ArgsTest, DescirbesSelfCorrectly) {
6768   const Matcher<std::tuple<int, bool, char> > m = Args<2, 0>(Lt());
6769   EXPECT_EQ("are a tuple whose fields (#2, #0) are a pair where "
6770             "the first < the second",
6771             Describe(m));
6772 }
6773 
TEST(ArgsTest,DescirbesNestedArgsCorrectly)6774 TEST(ArgsTest, DescirbesNestedArgsCorrectly) {
6775   const Matcher<const std::tuple<int, bool, char, int>&> m =
6776       Args<0, 2, 3>(Args<2, 0>(Lt()));
6777   EXPECT_EQ("are a tuple whose fields (#0, #2, #3) are a tuple "
6778             "whose fields (#2, #0) are a pair where the first < the second",
6779             Describe(m));
6780 }
6781 
TEST(ArgsTest,DescribesNegationCorrectly)6782 TEST(ArgsTest, DescribesNegationCorrectly) {
6783   const Matcher<std::tuple<int, char> > m = Args<1, 0>(Gt());
6784   EXPECT_EQ("are a tuple whose fields (#1, #0) aren't a pair "
6785             "where the first > the second",
6786             DescribeNegation(m));
6787 }
6788 
TEST(ArgsTest,ExplainsMatchResultWithoutInnerExplanation)6789 TEST(ArgsTest, ExplainsMatchResultWithoutInnerExplanation) {
6790   const Matcher<std::tuple<bool, int, int> > m = Args<1, 2>(Eq());
6791   EXPECT_EQ("whose fields (#1, #2) are (42, 42)",
6792             Explain(m, std::make_tuple(false, 42, 42)));
6793   EXPECT_EQ("whose fields (#1, #2) are (42, 43)",
6794             Explain(m, std::make_tuple(false, 42, 43)));
6795 }
6796 
6797 // For testing Args<>'s explanation.
6798 class LessThanMatcher : public MatcherInterface<std::tuple<char, int> > {
6799  public:
DescribeTo(::std::ostream *) const6800   void DescribeTo(::std::ostream* /*os*/) const override {}
6801 
MatchAndExplain(std::tuple<char,int> value,MatchResultListener * listener) const6802   bool MatchAndExplain(std::tuple<char, int> value,
6803                        MatchResultListener* listener) const override {
6804     const int diff = std::get<0>(value) - std::get<1>(value);
6805     if (diff > 0) {
6806       *listener << "where the first value is " << diff
6807                 << " more than the second";
6808     }
6809     return diff < 0;
6810   }
6811 };
6812 
LessThan()6813 Matcher<std::tuple<char, int> > LessThan() {
6814   return MakeMatcher(new LessThanMatcher);
6815 }
6816 
TEST(ArgsTest,ExplainsMatchResultWithInnerExplanation)6817 TEST(ArgsTest, ExplainsMatchResultWithInnerExplanation) {
6818   const Matcher<std::tuple<char, int, int> > m = Args<0, 2>(LessThan());
6819   EXPECT_EQ(
6820       "whose fields (#0, #2) are ('a' (97, 0x61), 42), "
6821       "where the first value is 55 more than the second",
6822       Explain(m, std::make_tuple('a', 42, 42)));
6823   EXPECT_EQ("whose fields (#0, #2) are ('\\0', 43)",
6824             Explain(m, std::make_tuple('\0', 42, 43)));
6825 }
6826 
6827 class PredicateFormatterFromMatcherTest : public ::testing::Test {
6828  protected:
6829   enum Behavior { kInitialSuccess, kAlwaysFail, kFlaky };
6830 
6831   // A matcher that can return different results when used multiple times on the
6832   // same input. No real matcher should do this; but this lets us test that we
6833   // detect such behavior and fail appropriately.
6834   class MockMatcher : public MatcherInterface<Behavior> {
6835    public:
MatchAndExplain(Behavior behavior,MatchResultListener * listener) const6836     bool MatchAndExplain(Behavior behavior,
6837                          MatchResultListener* listener) const override {
6838       *listener << "[MatchAndExplain]";
6839       switch (behavior) {
6840         case kInitialSuccess:
6841           // The first call to MatchAndExplain should use a "not interested"
6842           // listener; so this is expected to return |true|. There should be no
6843           // subsequent calls.
6844           return !listener->IsInterested();
6845 
6846         case kAlwaysFail:
6847           return false;
6848 
6849         case kFlaky:
6850           // The first call to MatchAndExplain should use a "not interested"
6851           // listener; so this will return |false|. Subsequent calls should have
6852           // an "interested" listener; so this will return |true|, thus
6853           // simulating a flaky matcher.
6854           return listener->IsInterested();
6855       }
6856 
6857       GTEST_LOG_(FATAL) << "This should never be reached";
6858       return false;
6859     }
6860 
DescribeTo(ostream * os) const6861     void DescribeTo(ostream* os) const override { *os << "[DescribeTo]"; }
6862 
DescribeNegationTo(ostream * os) const6863     void DescribeNegationTo(ostream* os) const override {
6864       *os << "[DescribeNegationTo]";
6865     }
6866   };
6867 
RunPredicateFormatter(Behavior behavior)6868   AssertionResult RunPredicateFormatter(Behavior behavior) {
6869     auto matcher = MakeMatcher(new MockMatcher);
6870     PredicateFormatterFromMatcher<Matcher<Behavior>> predicate_formatter(
6871         matcher);
6872     return predicate_formatter("dummy-name", behavior);
6873   }
6874 };
6875 
TEST_F(PredicateFormatterFromMatcherTest,ShortCircuitOnSuccess)6876 TEST_F(PredicateFormatterFromMatcherTest, ShortCircuitOnSuccess) {
6877   AssertionResult result = RunPredicateFormatter(kInitialSuccess);
6878   EXPECT_TRUE(result);  // Implicit cast to bool.
6879   std::string expect;
6880   EXPECT_EQ(expect, result.message());
6881 }
6882 
TEST_F(PredicateFormatterFromMatcherTest,NoShortCircuitOnFailure)6883 TEST_F(PredicateFormatterFromMatcherTest, NoShortCircuitOnFailure) {
6884   AssertionResult result = RunPredicateFormatter(kAlwaysFail);
6885   EXPECT_FALSE(result);  // Implicit cast to bool.
6886   std::string expect =
6887       "Value of: dummy-name\nExpected: [DescribeTo]\n"
6888       "  Actual: 1, [MatchAndExplain]";
6889   EXPECT_EQ(expect, result.message());
6890 }
6891 
TEST_F(PredicateFormatterFromMatcherTest,DetectsFlakyShortCircuit)6892 TEST_F(PredicateFormatterFromMatcherTest, DetectsFlakyShortCircuit) {
6893   AssertionResult result = RunPredicateFormatter(kFlaky);
6894   EXPECT_FALSE(result);  // Implicit cast to bool.
6895   std::string expect =
6896       "Value of: dummy-name\nExpected: [DescribeTo]\n"
6897       "  The matcher failed on the initial attempt; but passed when rerun to "
6898       "generate the explanation.\n"
6899       "  Actual: 2, [MatchAndExplain]";
6900   EXPECT_EQ(expect, result.message());
6901 }
6902 
6903 }  // namespace
6904 }  // namespace gmock_matchers_test
6905 }  // namespace testing
6906 
6907 #ifdef _MSC_VER
6908 # pragma warning(pop)
6909 #endif
6910