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