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