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


libaditof
Author(s):
autogenerated on Wed May 21 2025 02:06:52