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// Author: wan@google.com (Zhanyong Wan)
31
32// Google Mock - a framework for writing C++ mock classes.
33//
34// This file tests some commonly used argument matchers.
35
36#include "gmock/gmock-matchers.h"
37#include "gmock/gmock-more-matchers.h"
38
39#include <string.h>
40#include <time.h>
41#include <deque>
42#include <functional>
43#include <iostream>
44#include <iterator>
45#include <limits>
46#include <list>
47#include <map>
48#include <set>
49#include <sstream>
50#include <string>
51#include <utility>
52#include <vector>
53#include "gmock/gmock.h"
54#include "gtest/gtest.h"
55#include "gtest/gtest-spi.h"
56
57#if GTEST_HAS_STD_FORWARD_LIST_
58# include <forward_list>  // NOLINT
59#endif
60
61// Disable MSVC2015 warning for std::pair: "decorated name length exceeded, name was truncated".
62#if defined(_MSC_VER) && (_MSC_VER == 1900)
63# pragma warning(disable:4503)
64#endif
65
66namespace testing {
67
68namespace internal {
69GTEST_API_ string JoinAsTuple(const Strings& fields);
70}  // namespace internal
71
72namespace gmock_matchers_test {
73
74using std::greater;
75using std::less;
76using std::list;
77using std::make_pair;
78using std::map;
79using std::multimap;
80using std::multiset;
81using std::ostream;
82using std::pair;
83using std::set;
84using std::stringstream;
85using std::vector;
86using testing::A;
87using testing::AllArgs;
88using testing::AllOf;
89using testing::An;
90using testing::AnyOf;
91using testing::ByRef;
92using testing::ContainsRegex;
93using testing::DoubleEq;
94using testing::DoubleNear;
95using testing::EndsWith;
96using testing::Eq;
97using testing::ExplainMatchResult;
98using testing::Field;
99using testing::FloatEq;
100using testing::FloatNear;
101using testing::Ge;
102using testing::Gt;
103using testing::HasSubstr;
104using testing::IsEmpty;
105using testing::IsNull;
106using testing::Key;
107using testing::Le;
108using testing::Lt;
109using testing::MakeMatcher;
110using testing::MakePolymorphicMatcher;
111using testing::MatchResultListener;
112using testing::Matcher;
113using testing::MatcherCast;
114using testing::MatcherInterface;
115using testing::Matches;
116using testing::MatchesRegex;
117using testing::NanSensitiveDoubleEq;
118using testing::NanSensitiveDoubleNear;
119using testing::NanSensitiveFloatEq;
120using testing::NanSensitiveFloatNear;
121using testing::Ne;
122using testing::Not;
123using testing::NotNull;
124using testing::Pair;
125using testing::Pointee;
126using testing::Pointwise;
127using testing::PolymorphicMatcher;
128using testing::Property;
129using testing::Ref;
130using testing::ResultOf;
131using testing::SizeIs;
132using testing::StartsWith;
133using testing::StrCaseEq;
134using testing::StrCaseNe;
135using testing::StrEq;
136using testing::StrNe;
137using testing::StringMatchResultListener;
138using testing::Truly;
139using testing::TypedEq;
140using testing::UnorderedPointwise;
141using testing::Value;
142using testing::WhenSorted;
143using testing::WhenSortedBy;
144using testing::_;
145using testing::get;
146using testing::internal::DummyMatchResultListener;
147using testing::internal::ElementMatcherPair;
148using testing::internal::ElementMatcherPairs;
149using testing::internal::ExplainMatchFailureTupleTo;
150using testing::internal::FloatingEqMatcher;
151using testing::internal::FormatMatcherDescription;
152using testing::internal::IsReadableTypeName;
153using testing::internal::JoinAsTuple;
154using testing::internal::linked_ptr;
155using testing::internal::MatchMatrix;
156using testing::internal::RE;
157using testing::internal::scoped_ptr;
158using testing::internal::StreamMatchResultListener;
159using testing::internal::Strings;
160using testing::internal::linked_ptr;
161using testing::internal::scoped_ptr;
162using testing::internal::string;
163using testing::make_tuple;
164using testing::tuple;
165
166// For testing ExplainMatchResultTo().
167class GreaterThanMatcher : public MatcherInterface<int> {
168 public:
169  explicit GreaterThanMatcher(int rhs) : rhs_(rhs) {}
170
171  virtual void DescribeTo(ostream* os) const {
172    *os << "is > " << rhs_;
173  }
174
175  virtual bool MatchAndExplain(int lhs,
176                               MatchResultListener* listener) const {
177    const int diff = lhs - rhs_;
178    if (diff > 0) {
179      *listener << "which is " << diff << " more than " << rhs_;
180    } else if (diff == 0) {
181      *listener << "which is the same as " << rhs_;
182    } else {
183      *listener << "which is " << -diff << " less than " << rhs_;
184    }
185
186    return lhs > rhs_;
187  }
188
189 private:
190  int rhs_;
191};
192
193Matcher<int> GreaterThan(int n) {
194  return MakeMatcher(new GreaterThanMatcher(n));
195}
196
197std::string OfType(const std::string& type_name) {
198#if GTEST_HAS_RTTI
199  return " (of type " + type_name + ")";
200#else
201  return "";
202#endif
203}
204
205// Returns the description of the given matcher.
206template <typename T>
207std::string Describe(const Matcher<T>& m) {
208  stringstream ss;
209  m.DescribeTo(&ss);
210  return ss.str();
211}
212
213// Returns the description of the negation of the given matcher.
214template <typename T>
215std::string DescribeNegation(const Matcher<T>& m) {
216  stringstream ss;
217  m.DescribeNegationTo(&ss);
218  return ss.str();
219}
220
221// Returns the reason why x matches, or doesn't match, m.
222template <typename MatcherType, typename Value>
223std::string Explain(const MatcherType& m, const Value& x) {
224  StringMatchResultListener listener;
225  ExplainMatchResult(m, x, &listener);
226  return listener.str();
227}
228
229TEST(MatchResultListenerTest, StreamingWorks) {
230  StringMatchResultListener listener;
231  listener << "hi" << 5;
232  EXPECT_EQ("hi5", listener.str());
233
234  listener.Clear();
235  EXPECT_EQ("", listener.str());
236
237  listener << 42;
238  EXPECT_EQ("42", listener.str());
239
240  // Streaming shouldn't crash when the underlying ostream is NULL.
241  DummyMatchResultListener dummy;
242  dummy << "hi" << 5;
243}
244
245TEST(MatchResultListenerTest, CanAccessUnderlyingStream) {
246  EXPECT_TRUE(DummyMatchResultListener().stream() == NULL);
247  EXPECT_TRUE(StreamMatchResultListener(NULL).stream() == NULL);
248
249  EXPECT_EQ(&std::cout, StreamMatchResultListener(&std::cout).stream());
250}
251
252TEST(MatchResultListenerTest, IsInterestedWorks) {
253  EXPECT_TRUE(StringMatchResultListener().IsInterested());
254  EXPECT_TRUE(StreamMatchResultListener(&std::cout).IsInterested());
255
256  EXPECT_FALSE(DummyMatchResultListener().IsInterested());
257  EXPECT_FALSE(StreamMatchResultListener(NULL).IsInterested());
258}
259
260// Makes sure that the MatcherInterface<T> interface doesn't
261// change.
262class EvenMatcherImpl : public MatcherInterface<int> {
263 public:
264  virtual bool MatchAndExplain(int x,
265                               MatchResultListener* /* listener */) const {
266    return x % 2 == 0;
267  }
268
269  virtual void DescribeTo(ostream* os) const {
270    *os << "is an even number";
271  }
272
273  // We deliberately don't define DescribeNegationTo() and
274  // ExplainMatchResultTo() here, to make sure the definition of these
275  // two methods is optional.
276};
277
278// Makes sure that the MatcherInterface API doesn't change.
279TEST(MatcherInterfaceTest, CanBeImplementedUsingPublishedAPI) {
280  EvenMatcherImpl m;
281}
282
283// Tests implementing a monomorphic matcher using MatchAndExplain().
284
285class NewEvenMatcherImpl : public MatcherInterface<int> {
286 public:
287  virtual bool MatchAndExplain(int x, MatchResultListener* listener) const {
288    const bool match = x % 2 == 0;
289    // Verifies that we can stream to a listener directly.
290    *listener << "value % " << 2;
291    if (listener->stream() != NULL) {
292      // Verifies that we can stream to a listener's underlying stream
293      // too.
294      *listener->stream() << " == " << (x % 2);
295    }
296    return match;
297  }
298
299  virtual void DescribeTo(ostream* os) const {
300    *os << "is an even number";
301  }
302};
303
304TEST(MatcherInterfaceTest, CanBeImplementedUsingNewAPI) {
305  Matcher<int> m = MakeMatcher(new NewEvenMatcherImpl);
306  EXPECT_TRUE(m.Matches(2));
307  EXPECT_FALSE(m.Matches(3));
308  EXPECT_EQ("value % 2 == 0", Explain(m, 2));
309  EXPECT_EQ("value % 2 == 1", Explain(m, 3));
310}
311
312// Tests default-constructing a matcher.
313TEST(MatcherTest, CanBeDefaultConstructed) {
314  Matcher<double> m;
315}
316
317// Tests that Matcher<T> can be constructed from a MatcherInterface<T>*.
318TEST(MatcherTest, CanBeConstructedFromMatcherInterface) {
319  const MatcherInterface<int>* impl = new EvenMatcherImpl;
320  Matcher<int> m(impl);
321  EXPECT_TRUE(m.Matches(4));
322  EXPECT_FALSE(m.Matches(5));
323}
324
325// Tests that value can be used in place of Eq(value).
326TEST(MatcherTest, CanBeImplicitlyConstructedFromValue) {
327  Matcher<int> m1 = 5;
328  EXPECT_TRUE(m1.Matches(5));
329  EXPECT_FALSE(m1.Matches(6));
330}
331
332// Tests that NULL can be used in place of Eq(NULL).
333TEST(MatcherTest, CanBeImplicitlyConstructedFromNULL) {
334  Matcher<int*> m1 = NULL;
335  EXPECT_TRUE(m1.Matches(NULL));
336  int n = 0;
337  EXPECT_FALSE(m1.Matches(&n));
338}
339
340// Tests that matchers are copyable.
341TEST(MatcherTest, IsCopyable) {
342  // Tests the copy constructor.
343  Matcher<bool> m1 = Eq(false);
344  EXPECT_TRUE(m1.Matches(false));
345  EXPECT_FALSE(m1.Matches(true));
346
347  // Tests the assignment operator.
348  m1 = Eq(true);
349  EXPECT_TRUE(m1.Matches(true));
350  EXPECT_FALSE(m1.Matches(false));
351}
352
353// Tests that Matcher<T>::DescribeTo() calls
354// MatcherInterface<T>::DescribeTo().
355TEST(MatcherTest, CanDescribeItself) {
356  EXPECT_EQ("is an even number",
357            Describe(Matcher<int>(new EvenMatcherImpl)));
358}
359
360// Tests Matcher<T>::MatchAndExplain().
361TEST(MatcherTest, MatchAndExplain) {
362  Matcher<int> m = GreaterThan(0);
363  StringMatchResultListener listener1;
364  EXPECT_TRUE(m.MatchAndExplain(42, &listener1));
365  EXPECT_EQ("which is 42 more than 0", listener1.str());
366
367  StringMatchResultListener listener2;
368  EXPECT_FALSE(m.MatchAndExplain(-9, &listener2));
369  EXPECT_EQ("which is 9 less than 0", listener2.str());
370}
371
372// Tests that a C-string literal can be implicitly converted to a
373// Matcher<string> or Matcher<const string&>.
374TEST(StringMatcherTest, CanBeImplicitlyConstructedFromCStringLiteral) {
375  Matcher<string> m1 = "hi";
376  EXPECT_TRUE(m1.Matches("hi"));
377  EXPECT_FALSE(m1.Matches("hello"));
378
379  Matcher<const string&> m2 = "hi";
380  EXPECT_TRUE(m2.Matches("hi"));
381  EXPECT_FALSE(m2.Matches("hello"));
382}
383
384// Tests that a string object can be implicitly converted to a
385// Matcher<string> or Matcher<const string&>.
386TEST(StringMatcherTest, CanBeImplicitlyConstructedFromString) {
387  Matcher<string> m1 = string("hi");
388  EXPECT_TRUE(m1.Matches("hi"));
389  EXPECT_FALSE(m1.Matches("hello"));
390
391  Matcher<const string&> m2 = string("hi");
392  EXPECT_TRUE(m2.Matches("hi"));
393  EXPECT_FALSE(m2.Matches("hello"));
394}
395
396#if GTEST_HAS_STRING_PIECE_
397// Tests that a C-string literal can be implicitly converted to a
398// Matcher<StringPiece> or Matcher<const StringPiece&>.
399TEST(StringPieceMatcherTest, CanBeImplicitlyConstructedFromCStringLiteral) {
400  Matcher<StringPiece> m1 = "cats";
401  EXPECT_TRUE(m1.Matches("cats"));
402  EXPECT_FALSE(m1.Matches("dogs"));
403
404  Matcher<const StringPiece&> m2 = "cats";
405  EXPECT_TRUE(m2.Matches("cats"));
406  EXPECT_FALSE(m2.Matches("dogs"));
407}
408
409// Tests that a string object can be implicitly converted to a
410// Matcher<StringPiece> or Matcher<const StringPiece&>.
411TEST(StringPieceMatcherTest, CanBeImplicitlyConstructedFromString) {
412  Matcher<StringPiece> m1 = string("cats");
413  EXPECT_TRUE(m1.Matches("cats"));
414  EXPECT_FALSE(m1.Matches("dogs"));
415
416  Matcher<const StringPiece&> m2 = string("cats");
417  EXPECT_TRUE(m2.Matches("cats"));
418  EXPECT_FALSE(m2.Matches("dogs"));
419}
420
421// Tests that a StringPiece object can be implicitly converted to a
422// Matcher<StringPiece> or Matcher<const StringPiece&>.
423TEST(StringPieceMatcherTest, CanBeImplicitlyConstructedFromStringPiece) {
424  Matcher<StringPiece> m1 = StringPiece("cats");
425  EXPECT_TRUE(m1.Matches("cats"));
426  EXPECT_FALSE(m1.Matches("dogs"));
427
428  Matcher<const StringPiece&> m2 = StringPiece("cats");
429  EXPECT_TRUE(m2.Matches("cats"));
430  EXPECT_FALSE(m2.Matches("dogs"));
431}
432#endif  // GTEST_HAS_STRING_PIECE_
433
434// Tests that MakeMatcher() constructs a Matcher<T> from a
435// MatcherInterface* without requiring the user to explicitly
436// write the type.
437TEST(MakeMatcherTest, ConstructsMatcherFromMatcherInterface) {
438  const MatcherInterface<int>* dummy_impl = NULL;
439  Matcher<int> m = MakeMatcher(dummy_impl);
440}
441
442// Tests that MakePolymorphicMatcher() can construct a polymorphic
443// matcher from its implementation using the old API.
444const int g_bar = 1;
445class ReferencesBarOrIsZeroImpl {
446 public:
447  template <typename T>
448  bool MatchAndExplain(const T& x,
449                       MatchResultListener* /* listener */) const {
450    const void* p = &x;
451    return p == &g_bar || x == 0;
452  }
453
454  void DescribeTo(ostream* os) const { *os << "g_bar or zero"; }
455
456  void DescribeNegationTo(ostream* os) const {
457    *os << "doesn't reference g_bar and is not zero";
458  }
459};
460
461// This function verifies that MakePolymorphicMatcher() returns a
462// PolymorphicMatcher<T> where T is the argument's type.
463PolymorphicMatcher<ReferencesBarOrIsZeroImpl> ReferencesBarOrIsZero() {
464  return MakePolymorphicMatcher(ReferencesBarOrIsZeroImpl());
465}
466
467TEST(MakePolymorphicMatcherTest, ConstructsMatcherUsingOldAPI) {
468  // Using a polymorphic matcher to match a reference type.
469  Matcher<const int&> m1 = ReferencesBarOrIsZero();
470  EXPECT_TRUE(m1.Matches(0));
471  // Verifies that the identity of a by-reference argument is preserved.
472  EXPECT_TRUE(m1.Matches(g_bar));
473  EXPECT_FALSE(m1.Matches(1));
474  EXPECT_EQ("g_bar or zero", Describe(m1));
475
476  // Using a polymorphic matcher to match a value type.
477  Matcher<double> m2 = ReferencesBarOrIsZero();
478  EXPECT_TRUE(m2.Matches(0.0));
479  EXPECT_FALSE(m2.Matches(0.1));
480  EXPECT_EQ("g_bar or zero", Describe(m2));
481}
482
483// Tests implementing a polymorphic matcher using MatchAndExplain().
484
485class PolymorphicIsEvenImpl {
486 public:
487  void DescribeTo(ostream* os) const { *os << "is even"; }
488
489  void DescribeNegationTo(ostream* os) const {
490    *os << "is odd";
491  }
492
493  template <typename T>
494  bool MatchAndExplain(const T& x, MatchResultListener* listener) const {
495    // Verifies that we can stream to the listener directly.
496    *listener << "% " << 2;
497    if (listener->stream() != NULL) {
498      // Verifies that we can stream to the listener's underlying stream
499      // too.
500      *listener->stream() << " == " << (x % 2);
501    }
502    return (x % 2) == 0;
503  }
504};
505
506PolymorphicMatcher<PolymorphicIsEvenImpl> PolymorphicIsEven() {
507  return MakePolymorphicMatcher(PolymorphicIsEvenImpl());
508}
509
510TEST(MakePolymorphicMatcherTest, ConstructsMatcherUsingNewAPI) {
511  // Using PolymorphicIsEven() as a Matcher<int>.
512  const Matcher<int> m1 = PolymorphicIsEven();
513  EXPECT_TRUE(m1.Matches(42));
514  EXPECT_FALSE(m1.Matches(43));
515  EXPECT_EQ("is even", Describe(m1));
516
517  const Matcher<int> not_m1 = Not(m1);
518  EXPECT_EQ("is odd", Describe(not_m1));
519
520  EXPECT_EQ("% 2 == 0", Explain(m1, 42));
521
522  // Using PolymorphicIsEven() as a Matcher<char>.
523  const Matcher<char> m2 = PolymorphicIsEven();
524  EXPECT_TRUE(m2.Matches('\x42'));
525  EXPECT_FALSE(m2.Matches('\x43'));
526  EXPECT_EQ("is even", Describe(m2));
527
528  const Matcher<char> not_m2 = Not(m2);
529  EXPECT_EQ("is odd", Describe(not_m2));
530
531  EXPECT_EQ("% 2 == 0", Explain(m2, '\x42'));
532}
533
534// Tests that MatcherCast<T>(m) works when m is a polymorphic matcher.
535TEST(MatcherCastTest, FromPolymorphicMatcher) {
536  Matcher<int> m = MatcherCast<int>(Eq(5));
537  EXPECT_TRUE(m.Matches(5));
538  EXPECT_FALSE(m.Matches(6));
539}
540
541// For testing casting matchers between compatible types.
542class IntValue {
543 public:
544  // An int can be statically (although not implicitly) cast to a
545  // IntValue.
546  explicit IntValue(int a_value) : value_(a_value) {}
547
548  int value() const { return value_; }
549 private:
550  int value_;
551};
552
553// For testing casting matchers between compatible types.
554bool IsPositiveIntValue(const IntValue& foo) {
555  return foo.value() > 0;
556}
557
558// Tests that MatcherCast<T>(m) works when m is a Matcher<U> where T
559// can be statically converted to U.
560TEST(MatcherCastTest, FromCompatibleType) {
561  Matcher<double> m1 = Eq(2.0);
562  Matcher<int> m2 = MatcherCast<int>(m1);
563  EXPECT_TRUE(m2.Matches(2));
564  EXPECT_FALSE(m2.Matches(3));
565
566  Matcher<IntValue> m3 = Truly(IsPositiveIntValue);
567  Matcher<int> m4 = MatcherCast<int>(m3);
568  // In the following, the arguments 1 and 0 are statically converted
569  // to IntValue objects, and then tested by the IsPositiveIntValue()
570  // predicate.
571  EXPECT_TRUE(m4.Matches(1));
572  EXPECT_FALSE(m4.Matches(0));
573}
574
575// Tests that MatcherCast<T>(m) works when m is a Matcher<const T&>.
576TEST(MatcherCastTest, FromConstReferenceToNonReference) {
577  Matcher<const int&> m1 = Eq(0);
578  Matcher<int> m2 = MatcherCast<int>(m1);
579  EXPECT_TRUE(m2.Matches(0));
580  EXPECT_FALSE(m2.Matches(1));
581}
582
583// Tests that MatcherCast<T>(m) works when m is a Matcher<T&>.
584TEST(MatcherCastTest, FromReferenceToNonReference) {
585  Matcher<int&> m1 = Eq(0);
586  Matcher<int> m2 = MatcherCast<int>(m1);
587  EXPECT_TRUE(m2.Matches(0));
588  EXPECT_FALSE(m2.Matches(1));
589}
590
591// Tests that MatcherCast<const T&>(m) works when m is a Matcher<T>.
592TEST(MatcherCastTest, FromNonReferenceToConstReference) {
593  Matcher<int> m1 = Eq(0);
594  Matcher<const int&> m2 = MatcherCast<const int&>(m1);
595  EXPECT_TRUE(m2.Matches(0));
596  EXPECT_FALSE(m2.Matches(1));
597}
598
599// Tests that MatcherCast<T&>(m) works when m is a Matcher<T>.
600TEST(MatcherCastTest, FromNonReferenceToReference) {
601  Matcher<int> m1 = Eq(0);
602  Matcher<int&> m2 = MatcherCast<int&>(m1);
603  int n = 0;
604  EXPECT_TRUE(m2.Matches(n));
605  n = 1;
606  EXPECT_FALSE(m2.Matches(n));
607}
608
609// Tests that MatcherCast<T>(m) works when m is a Matcher<T>.
610TEST(MatcherCastTest, FromSameType) {
611  Matcher<int> m1 = Eq(0);
612  Matcher<int> m2 = MatcherCast<int>(m1);
613  EXPECT_TRUE(m2.Matches(0));
614  EXPECT_FALSE(m2.Matches(1));
615}
616
617// Implicitly convertible from any type.
618struct ConvertibleFromAny {
619  ConvertibleFromAny(int a_value) : value(a_value) {}
620  template <typename T>
621  explicit ConvertibleFromAny(const T& /*a_value*/) : value(-1) {
622    ADD_FAILURE() << "Conversion constructor called";
623  }
624  int value;
625};
626
627bool operator==(const ConvertibleFromAny& a, const ConvertibleFromAny& b) {
628  return a.value == b.value;
629}
630
631ostream& operator<<(ostream& os, const ConvertibleFromAny& a) {
632  return os << a.value;
633}
634
635TEST(MatcherCastTest, ConversionConstructorIsUsed) {
636  Matcher<ConvertibleFromAny> m = MatcherCast<ConvertibleFromAny>(1);
637  EXPECT_TRUE(m.Matches(ConvertibleFromAny(1)));
638  EXPECT_FALSE(m.Matches(ConvertibleFromAny(2)));
639}
640
641TEST(MatcherCastTest, FromConvertibleFromAny) {
642  Matcher<ConvertibleFromAny> m =
643      MatcherCast<ConvertibleFromAny>(Eq(ConvertibleFromAny(1)));
644  EXPECT_TRUE(m.Matches(ConvertibleFromAny(1)));
645  EXPECT_FALSE(m.Matches(ConvertibleFromAny(2)));
646}
647
648struct IntReferenceWrapper {
649  IntReferenceWrapper(const int& a_value) : value(&a_value) {}
650  const int* value;
651};
652
653bool operator==(const IntReferenceWrapper& a, const IntReferenceWrapper& b) {
654  return a.value == b.value;
655}
656
657TEST(MatcherCastTest, ValueIsNotCopied) {
658  int n = 42;
659  Matcher<IntReferenceWrapper> m = MatcherCast<IntReferenceWrapper>(n);
660  // Verify that the matcher holds a reference to n, not to its temporary copy.
661  EXPECT_TRUE(m.Matches(n));
662}
663
664class Base {
665 public:
666  virtual ~Base() {}
667  Base() {}
668 private:
669  GTEST_DISALLOW_COPY_AND_ASSIGN_(Base);
670};
671
672class Derived : public Base {
673 public:
674  Derived() : Base() {}
675  int i;
676};
677
678class OtherDerived : public Base {};
679
680// Tests that SafeMatcherCast<T>(m) works when m is a polymorphic matcher.
681TEST(SafeMatcherCastTest, FromPolymorphicMatcher) {
682  Matcher<char> m2 = SafeMatcherCast<char>(Eq(32));
683  EXPECT_TRUE(m2.Matches(' '));
684  EXPECT_FALSE(m2.Matches('\n'));
685}
686
687// Tests that SafeMatcherCast<T>(m) works when m is a Matcher<U> where
688// T and U are arithmetic types and T can be losslessly converted to
689// U.
690TEST(SafeMatcherCastTest, FromLosslesslyConvertibleArithmeticType) {
691  Matcher<double> m1 = DoubleEq(1.0);
692  Matcher<float> m2 = SafeMatcherCast<float>(m1);
693  EXPECT_TRUE(m2.Matches(1.0f));
694  EXPECT_FALSE(m2.Matches(2.0f));
695
696  Matcher<char> m3 = SafeMatcherCast<char>(TypedEq<int>('a'));
697  EXPECT_TRUE(m3.Matches('a'));
698  EXPECT_FALSE(m3.Matches('b'));
699}
700
701// Tests that SafeMatcherCast<T>(m) works when m is a Matcher<U> where T and U
702// are pointers or references to a derived and a base class, correspondingly.
703TEST(SafeMatcherCastTest, FromBaseClass) {
704  Derived d, d2;
705  Matcher<Base*> m1 = Eq(&d);
706  Matcher<Derived*> m2 = SafeMatcherCast<Derived*>(m1);
707  EXPECT_TRUE(m2.Matches(&d));
708  EXPECT_FALSE(m2.Matches(&d2));
709
710  Matcher<Base&> m3 = Ref(d);
711  Matcher<Derived&> m4 = SafeMatcherCast<Derived&>(m3);
712  EXPECT_TRUE(m4.Matches(d));
713  EXPECT_FALSE(m4.Matches(d2));
714}
715
716// Tests that SafeMatcherCast<T&>(m) works when m is a Matcher<const T&>.
717TEST(SafeMatcherCastTest, FromConstReferenceToReference) {
718  int n = 0;
719  Matcher<const int&> m1 = Ref(n);
720  Matcher<int&> m2 = SafeMatcherCast<int&>(m1);
721  int n1 = 0;
722  EXPECT_TRUE(m2.Matches(n));
723  EXPECT_FALSE(m2.Matches(n1));
724}
725
726// Tests that MatcherCast<const T&>(m) works when m is a Matcher<T>.
727TEST(SafeMatcherCastTest, FromNonReferenceToConstReference) {
728  Matcher<int> m1 = Eq(0);
729  Matcher<const int&> m2 = SafeMatcherCast<const int&>(m1);
730  EXPECT_TRUE(m2.Matches(0));
731  EXPECT_FALSE(m2.Matches(1));
732}
733
734// Tests that SafeMatcherCast<T&>(m) works when m is a Matcher<T>.
735TEST(SafeMatcherCastTest, FromNonReferenceToReference) {
736  Matcher<int> m1 = Eq(0);
737  Matcher<int&> m2 = SafeMatcherCast<int&>(m1);
738  int n = 0;
739  EXPECT_TRUE(m2.Matches(n));
740  n = 1;
741  EXPECT_FALSE(m2.Matches(n));
742}
743
744// Tests that SafeMatcherCast<T>(m) works when m is a Matcher<T>.
745TEST(SafeMatcherCastTest, FromSameType) {
746  Matcher<int> m1 = Eq(0);
747  Matcher<int> m2 = SafeMatcherCast<int>(m1);
748  EXPECT_TRUE(m2.Matches(0));
749  EXPECT_FALSE(m2.Matches(1));
750}
751
752TEST(SafeMatcherCastTest, ConversionConstructorIsUsed) {
753  Matcher<ConvertibleFromAny> m = SafeMatcherCast<ConvertibleFromAny>(1);
754  EXPECT_TRUE(m.Matches(ConvertibleFromAny(1)));
755  EXPECT_FALSE(m.Matches(ConvertibleFromAny(2)));
756}
757
758TEST(SafeMatcherCastTest, FromConvertibleFromAny) {
759  Matcher<ConvertibleFromAny> m =
760      SafeMatcherCast<ConvertibleFromAny>(Eq(ConvertibleFromAny(1)));
761  EXPECT_TRUE(m.Matches(ConvertibleFromAny(1)));
762  EXPECT_FALSE(m.Matches(ConvertibleFromAny(2)));
763}
764
765TEST(SafeMatcherCastTest, ValueIsNotCopied) {
766  int n = 42;
767  Matcher<IntReferenceWrapper> m = SafeMatcherCast<IntReferenceWrapper>(n);
768  // Verify that the matcher holds a reference to n, not to its temporary copy.
769  EXPECT_TRUE(m.Matches(n));
770}
771
772TEST(ExpectThat, TakesLiterals) {
773  EXPECT_THAT(1, 1);
774  EXPECT_THAT(1.0, 1.0);
775  EXPECT_THAT(string(), "");
776}
777
778TEST(ExpectThat, TakesFunctions) {
779  struct Helper {
780    static void Func() {}
781  };
782  void (*func)() = Helper::Func;
783  EXPECT_THAT(func, Helper::Func);
784  EXPECT_THAT(func, &Helper::Func);
785}
786
787// Tests that A<T>() matches any value of type T.
788TEST(ATest, MatchesAnyValue) {
789  // Tests a matcher for a value type.
790  Matcher<double> m1 = A<double>();
791  EXPECT_TRUE(m1.Matches(91.43));
792  EXPECT_TRUE(m1.Matches(-15.32));
793
794  // Tests a matcher for a reference type.
795  int a = 2;
796  int b = -6;
797  Matcher<int&> m2 = A<int&>();
798  EXPECT_TRUE(m2.Matches(a));
799  EXPECT_TRUE(m2.Matches(b));
800}
801
802TEST(ATest, WorksForDerivedClass) {
803  Base base;
804  Derived derived;
805  EXPECT_THAT(&base, A<Base*>());
806  // This shouldn't compile: EXPECT_THAT(&base, A<Derived*>());
807  EXPECT_THAT(&derived, A<Base*>());
808  EXPECT_THAT(&derived, A<Derived*>());
809}
810
811// Tests that A<T>() describes itself properly.
812TEST(ATest, CanDescribeSelf) {
813  EXPECT_EQ("is anything", Describe(A<bool>()));
814}
815
816// Tests that An<T>() matches any value of type T.
817TEST(AnTest, MatchesAnyValue) {
818  // Tests a matcher for a value type.
819  Matcher<int> m1 = An<int>();
820  EXPECT_TRUE(m1.Matches(9143));
821  EXPECT_TRUE(m1.Matches(-1532));
822
823  // Tests a matcher for a reference type.
824  int a = 2;
825  int b = -6;
826  Matcher<int&> m2 = An<int&>();
827  EXPECT_TRUE(m2.Matches(a));
828  EXPECT_TRUE(m2.Matches(b));
829}
830
831// Tests that An<T>() describes itself properly.
832TEST(AnTest, CanDescribeSelf) {
833  EXPECT_EQ("is anything", Describe(An<int>()));
834}
835
836// Tests that _ can be used as a matcher for any type and matches any
837// value of that type.
838TEST(UnderscoreTest, MatchesAnyValue) {
839  // Uses _ as a matcher for a value type.
840  Matcher<int> m1 = _;
841  EXPECT_TRUE(m1.Matches(123));
842  EXPECT_TRUE(m1.Matches(-242));
843
844  // Uses _ as a matcher for a reference type.
845  bool a = false;
846  const bool b = true;
847  Matcher<const bool&> m2 = _;
848  EXPECT_TRUE(m2.Matches(a));
849  EXPECT_TRUE(m2.Matches(b));
850}
851
852// Tests that _ describes itself properly.
853TEST(UnderscoreTest, CanDescribeSelf) {
854  Matcher<int> m = _;
855  EXPECT_EQ("is anything", Describe(m));
856}
857
858// Tests that Eq(x) matches any value equal to x.
859TEST(EqTest, MatchesEqualValue) {
860  // 2 C-strings with same content but different addresses.
861  const char a1[] = "hi";
862  const char a2[] = "hi";
863
864  Matcher<const char*> m1 = Eq(a1);
865  EXPECT_TRUE(m1.Matches(a1));
866  EXPECT_FALSE(m1.Matches(a2));
867}
868
869// Tests that Eq(v) describes itself properly.
870
871class Unprintable {
872 public:
873  Unprintable() : c_('a') {}
874
875 private:
876  char c_;
877};
878
879inline bool operator==(const Unprintable& /* lhs */,
880                       const Unprintable& /* rhs */) {
881    return true;
882}
883
884TEST(EqTest, CanDescribeSelf) {
885  Matcher<Unprintable> m = Eq(Unprintable());
886  EXPECT_EQ("is equal to 1-byte object <61>", Describe(m));
887}
888
889// Tests that Eq(v) can be used to match any type that supports
890// comparing with type T, where T is v's type.
891TEST(EqTest, IsPolymorphic) {
892  Matcher<int> m1 = Eq(1);
893  EXPECT_TRUE(m1.Matches(1));
894  EXPECT_FALSE(m1.Matches(2));
895
896  Matcher<char> m2 = Eq(1);
897  EXPECT_TRUE(m2.Matches('\1'));
898  EXPECT_FALSE(m2.Matches('a'));
899}
900
901// Tests that TypedEq<T>(v) matches values of type T that's equal to v.
902TEST(TypedEqTest, ChecksEqualityForGivenType) {
903  Matcher<char> m1 = TypedEq<char>('a');
904  EXPECT_TRUE(m1.Matches('a'));
905  EXPECT_FALSE(m1.Matches('b'));
906
907  Matcher<int> m2 = TypedEq<int>(6);
908  EXPECT_TRUE(m2.Matches(6));
909  EXPECT_FALSE(m2.Matches(7));
910}
911
912// Tests that TypedEq(v) describes itself properly.
913TEST(TypedEqTest, CanDescribeSelf) {
914  EXPECT_EQ("is equal to 2", Describe(TypedEq<int>(2)));
915}
916
917// Tests that TypedEq<T>(v) has type Matcher<T>.
918
919// Type<T>::IsTypeOf(v) compiles iff the type of value v is T, where T
920// is a "bare" type (i.e. not in the form of const U or U&).  If v's
921// type is not T, the compiler will generate a message about
922// "undefined referece".
923template <typename T>
924struct Type {
925  static bool IsTypeOf(const T& /* v */) { return true; }
926
927  template <typename T2>
928  static void IsTypeOf(T2 v);
929};
930
931TEST(TypedEqTest, HasSpecifiedType) {
932  // Verfies that the type of TypedEq<T>(v) is Matcher<T>.
933  Type<Matcher<int> >::IsTypeOf(TypedEq<int>(5));
934  Type<Matcher<double> >::IsTypeOf(TypedEq<double>(5));
935}
936
937// Tests that Ge(v) matches anything >= v.
938TEST(GeTest, ImplementsGreaterThanOrEqual) {
939  Matcher<int> m1 = Ge(0);
940  EXPECT_TRUE(m1.Matches(1));
941  EXPECT_TRUE(m1.Matches(0));
942  EXPECT_FALSE(m1.Matches(-1));
943}
944
945// Tests that Ge(v) describes itself properly.
946TEST(GeTest, CanDescribeSelf) {
947  Matcher<int> m = Ge(5);
948  EXPECT_EQ("is >= 5", Describe(m));
949}
950
951// Tests that Gt(v) matches anything > v.
952TEST(GtTest, ImplementsGreaterThan) {
953  Matcher<double> m1 = Gt(0);
954  EXPECT_TRUE(m1.Matches(1.0));
955  EXPECT_FALSE(m1.Matches(0.0));
956  EXPECT_FALSE(m1.Matches(-1.0));
957}
958
959// Tests that Gt(v) describes itself properly.
960TEST(GtTest, CanDescribeSelf) {
961  Matcher<int> m = Gt(5);
962  EXPECT_EQ("is > 5", Describe(m));
963}
964
965// Tests that Le(v) matches anything <= v.
966TEST(LeTest, ImplementsLessThanOrEqual) {
967  Matcher<char> m1 = Le('b');
968  EXPECT_TRUE(m1.Matches('a'));
969  EXPECT_TRUE(m1.Matches('b'));
970  EXPECT_FALSE(m1.Matches('c'));
971}
972
973// Tests that Le(v) describes itself properly.
974TEST(LeTest, CanDescribeSelf) {
975  Matcher<int> m = Le(5);
976  EXPECT_EQ("is <= 5", Describe(m));
977}
978
979// Tests that Lt(v) matches anything < v.
980TEST(LtTest, ImplementsLessThan) {
981  Matcher<const std::string&> m1 = Lt("Hello");
982  EXPECT_TRUE(m1.Matches("Abc"));
983  EXPECT_FALSE(m1.Matches("Hello"));
984  EXPECT_FALSE(m1.Matches("Hello, world!"));
985}
986
987// Tests that Lt(v) describes itself properly.
988TEST(LtTest, CanDescribeSelf) {
989  Matcher<int> m = Lt(5);
990  EXPECT_EQ("is < 5", Describe(m));
991}
992
993// Tests that Ne(v) matches anything != v.
994TEST(NeTest, ImplementsNotEqual) {
995  Matcher<int> m1 = Ne(0);
996  EXPECT_TRUE(m1.Matches(1));
997  EXPECT_TRUE(m1.Matches(-1));
998  EXPECT_FALSE(m1.Matches(0));
999}
1000
1001// Tests that Ne(v) describes itself properly.
1002TEST(NeTest, CanDescribeSelf) {
1003  Matcher<int> m = Ne(5);
1004  EXPECT_EQ("isn't equal to 5", Describe(m));
1005}
1006
1007// Tests that IsNull() matches any NULL pointer of any type.
1008TEST(IsNullTest, MatchesNullPointer) {
1009  Matcher<int*> m1 = IsNull();
1010  int* p1 = NULL;
1011  int n = 0;
1012  EXPECT_TRUE(m1.Matches(p1));
1013  EXPECT_FALSE(m1.Matches(&n));
1014
1015  Matcher<const char*> m2 = IsNull();
1016  const char* p2 = NULL;
1017  EXPECT_TRUE(m2.Matches(p2));
1018  EXPECT_FALSE(m2.Matches("hi"));
1019
1020#if !GTEST_OS_SYMBIAN
1021  // Nokia's Symbian compiler generates:
1022  // gmock-matchers.h: ambiguous access to overloaded function
1023  // gmock-matchers.h: 'testing::Matcher<void *>::Matcher(void *)'
1024  // gmock-matchers.h: 'testing::Matcher<void *>::Matcher(const testing::
1025  //     MatcherInterface<void *> *)'
1026  // gmock-matchers.h:  (point of instantiation: 'testing::
1027  //     gmock_matchers_test::IsNullTest_MatchesNullPointer_Test::TestBody()')
1028  // gmock-matchers.h:   (instantiating: 'testing::PolymorphicMatc
1029  Matcher<void*> m3 = IsNull();
1030  void* p3 = NULL;
1031  EXPECT_TRUE(m3.Matches(p3));
1032  EXPECT_FALSE(m3.Matches(reinterpret_cast<void*>(0xbeef)));
1033#endif
1034}
1035
1036TEST(IsNullTest, LinkedPtr) {
1037  const Matcher<linked_ptr<int> > m = IsNull();
1038  const linked_ptr<int> null_p;
1039  const linked_ptr<int> non_null_p(new int);
1040
1041  EXPECT_TRUE(m.Matches(null_p));
1042  EXPECT_FALSE(m.Matches(non_null_p));
1043}
1044
1045TEST(IsNullTest, ReferenceToConstLinkedPtr) {
1046  const Matcher<const linked_ptr<double>&> m = IsNull();
1047  const linked_ptr<double> null_p;
1048  const linked_ptr<double> non_null_p(new double);
1049
1050  EXPECT_TRUE(m.Matches(null_p));
1051  EXPECT_FALSE(m.Matches(non_null_p));
1052}
1053
1054#if GTEST_HAS_STD_FUNCTION_
1055TEST(IsNullTest, StdFunction) {
1056  const Matcher<std::function<void()>> m = IsNull();
1057
1058  EXPECT_TRUE(m.Matches(std::function<void()>()));
1059  EXPECT_FALSE(m.Matches([]{}));
1060}
1061#endif  // GTEST_HAS_STD_FUNCTION_
1062
1063// Tests that IsNull() describes itself properly.
1064TEST(IsNullTest, CanDescribeSelf) {
1065  Matcher<int*> m = IsNull();
1066  EXPECT_EQ("is NULL", Describe(m));
1067  EXPECT_EQ("isn't NULL", DescribeNegation(m));
1068}
1069
1070// Tests that NotNull() matches any non-NULL pointer of any type.
1071TEST(NotNullTest, MatchesNonNullPointer) {
1072  Matcher<int*> m1 = NotNull();
1073  int* p1 = NULL;
1074  int n = 0;
1075  EXPECT_FALSE(m1.Matches(p1));
1076  EXPECT_TRUE(m1.Matches(&n));
1077
1078  Matcher<const char*> m2 = NotNull();
1079  const char* p2 = NULL;
1080  EXPECT_FALSE(m2.Matches(p2));
1081  EXPECT_TRUE(m2.Matches("hi"));
1082}
1083
1084TEST(NotNullTest, LinkedPtr) {
1085  const Matcher<linked_ptr<int> > m = NotNull();
1086  const linked_ptr<int> null_p;
1087  const linked_ptr<int> non_null_p(new int);
1088
1089  EXPECT_FALSE(m.Matches(null_p));
1090  EXPECT_TRUE(m.Matches(non_null_p));
1091}
1092
1093TEST(NotNullTest, ReferenceToConstLinkedPtr) {
1094  const Matcher<const linked_ptr<double>&> m = NotNull();
1095  const linked_ptr<double> null_p;
1096  const linked_ptr<double> non_null_p(new double);
1097
1098  EXPECT_FALSE(m.Matches(null_p));
1099  EXPECT_TRUE(m.Matches(non_null_p));
1100}
1101
1102#if GTEST_HAS_STD_FUNCTION_
1103TEST(NotNullTest, StdFunction) {
1104  const Matcher<std::function<void()>> m = NotNull();
1105
1106  EXPECT_TRUE(m.Matches([]{}));
1107  EXPECT_FALSE(m.Matches(std::function<void()>()));
1108}
1109#endif  // GTEST_HAS_STD_FUNCTION_
1110
1111// Tests that NotNull() describes itself properly.
1112TEST(NotNullTest, CanDescribeSelf) {
1113  Matcher<int*> m = NotNull();
1114  EXPECT_EQ("isn't NULL", Describe(m));
1115}
1116
1117// Tests that Ref(variable) matches an argument that references
1118// 'variable'.
1119TEST(RefTest, MatchesSameVariable) {
1120  int a = 0;
1121  int b = 0;
1122  Matcher<int&> m = Ref(a);
1123  EXPECT_TRUE(m.Matches(a));
1124  EXPECT_FALSE(m.Matches(b));
1125}
1126
1127// Tests that Ref(variable) describes itself properly.
1128TEST(RefTest, CanDescribeSelf) {
1129  int n = 5;
1130  Matcher<int&> m = Ref(n);
1131  stringstream ss;
1132  ss << "references the variable @" << &n << " 5";
1133  EXPECT_EQ(ss.str(), Describe(m));
1134}
1135
1136// Test that Ref(non_const_varialbe) can be used as a matcher for a
1137// const reference.
1138TEST(RefTest, CanBeUsedAsMatcherForConstReference) {
1139  int a = 0;
1140  int b = 0;
1141  Matcher<const int&> m = Ref(a);
1142  EXPECT_TRUE(m.Matches(a));
1143  EXPECT_FALSE(m.Matches(b));
1144}
1145
1146// Tests that Ref(variable) is covariant, i.e. Ref(derived) can be
1147// used wherever Ref(base) can be used (Ref(derived) is a sub-type
1148// of Ref(base), but not vice versa.
1149
1150TEST(RefTest, IsCovariant) {
1151  Base base, base2;
1152  Derived derived;
1153  Matcher<const Base&> m1 = Ref(base);
1154  EXPECT_TRUE(m1.Matches(base));
1155  EXPECT_FALSE(m1.Matches(base2));
1156  EXPECT_FALSE(m1.Matches(derived));
1157
1158  m1 = Ref(derived);
1159  EXPECT_TRUE(m1.Matches(derived));
1160  EXPECT_FALSE(m1.Matches(base));
1161  EXPECT_FALSE(m1.Matches(base2));
1162}
1163
1164TEST(RefTest, ExplainsResult) {
1165  int n = 0;
1166  EXPECT_THAT(Explain(Matcher<const int&>(Ref(n)), n),
1167              StartsWith("which is located @"));
1168
1169  int m = 0;
1170  EXPECT_THAT(Explain(Matcher<const int&>(Ref(n)), m),
1171              StartsWith("which is located @"));
1172}
1173
1174// Tests string comparison matchers.
1175
1176TEST(StrEqTest, MatchesEqualString) {
1177  Matcher<const char*> m = StrEq(std::string("Hello"));
1178  EXPECT_TRUE(m.Matches("Hello"));
1179  EXPECT_FALSE(m.Matches("hello"));
1180  EXPECT_FALSE(m.Matches(NULL));
1181
1182  Matcher<const std::string&> m2 = StrEq("Hello");
1183  EXPECT_TRUE(m2.Matches("Hello"));
1184  EXPECT_FALSE(m2.Matches("Hi"));
1185}
1186
1187TEST(StrEqTest, CanDescribeSelf) {
1188  Matcher<std::string> m = StrEq("Hi-\'\"?\\\a\b\f\n\r\t\v\xD3");
1189  EXPECT_EQ("is equal to \"Hi-\'\\\"?\\\\\\a\\b\\f\\n\\r\\t\\v\\xD3\"",
1190      Describe(m));
1191
1192  std::string str("01204500800");
1193  str[3] = '\0';
1194  Matcher<std::string> m2 = StrEq(str);
1195  EXPECT_EQ("is equal to \"012\\04500800\"", Describe(m2));
1196  str[0] = str[6] = str[7] = str[9] = str[10] = '\0';
1197  Matcher<std::string> m3 = StrEq(str);
1198  EXPECT_EQ("is equal to \"\\012\\045\\0\\08\\0\\0\"", Describe(m3));
1199}
1200
1201TEST(StrNeTest, MatchesUnequalString) {
1202  Matcher<const char*> m = StrNe("Hello");
1203  EXPECT_TRUE(m.Matches(""));
1204  EXPECT_TRUE(m.Matches(NULL));
1205  EXPECT_FALSE(m.Matches("Hello"));
1206
1207  Matcher<std::string> m2 = StrNe(std::string("Hello"));
1208  EXPECT_TRUE(m2.Matches("hello"));
1209  EXPECT_FALSE(m2.Matches("Hello"));
1210}
1211
1212TEST(StrNeTest, CanDescribeSelf) {
1213  Matcher<const char*> m = StrNe("Hi");
1214  EXPECT_EQ("isn't equal to \"Hi\"", Describe(m));
1215}
1216
1217TEST(StrCaseEqTest, MatchesEqualStringIgnoringCase) {
1218  Matcher<const char*> m = StrCaseEq(string("Hello"));
1219  EXPECT_TRUE(m.Matches("Hello"));
1220  EXPECT_TRUE(m.Matches("hello"));
1221  EXPECT_FALSE(m.Matches("Hi"));
1222  EXPECT_FALSE(m.Matches(NULL));
1223
1224  Matcher<const string&> m2 = StrCaseEq("Hello");
1225  EXPECT_TRUE(m2.Matches("hello"));
1226  EXPECT_FALSE(m2.Matches("Hi"));
1227}
1228
1229TEST(StrCaseEqTest, MatchesEqualStringWith0IgnoringCase) {
1230  std::string str1("oabocdooeoo");
1231  std::string str2("OABOCDOOEOO");
1232  Matcher<const std::string&> m0 = StrCaseEq(str1);
1233  EXPECT_FALSE(m0.Matches(str2 + std::string(1, '\0')));
1234
1235  str1[3] = str2[3] = '\0';
1236  Matcher<const std::string&> m1 = StrCaseEq(str1);
1237  EXPECT_TRUE(m1.Matches(str2));
1238
1239  str1[0] = str1[6] = str1[7] = str1[10] = '\0';
1240  str2[0] = str2[6] = str2[7] = str2[10] = '\0';
1241  Matcher<const std::string&> m2 = StrCaseEq(str1);
1242  str1[9] = str2[9] = '\0';
1243  EXPECT_FALSE(m2.Matches(str2));
1244
1245  Matcher<const std::string&> m3 = StrCaseEq(str1);
1246  EXPECT_TRUE(m3.Matches(str2));
1247
1248  EXPECT_FALSE(m3.Matches(str2 + "x"));
1249  str2.append(1, '\0');
1250  EXPECT_FALSE(m3.Matches(str2));
1251  EXPECT_FALSE(m3.Matches(std::string(str2, 0, 9)));
1252}
1253
1254TEST(StrCaseEqTest, CanDescribeSelf) {
1255  Matcher<std::string> m = StrCaseEq("Hi");
1256  EXPECT_EQ("is equal to (ignoring case) \"Hi\"", Describe(m));
1257}
1258
1259TEST(StrCaseNeTest, MatchesUnequalStringIgnoringCase) {
1260  Matcher<const char*> m = StrCaseNe("Hello");
1261  EXPECT_TRUE(m.Matches("Hi"));
1262  EXPECT_TRUE(m.Matches(NULL));
1263  EXPECT_FALSE(m.Matches("Hello"));
1264  EXPECT_FALSE(m.Matches("hello"));
1265
1266  Matcher<std::string> m2 = StrCaseNe(std::string("Hello"));
1267  EXPECT_TRUE(m2.Matches(""));
1268  EXPECT_FALSE(m2.Matches("Hello"));
1269}
1270
1271TEST(StrCaseNeTest, CanDescribeSelf) {
1272  Matcher<const char*> m = StrCaseNe("Hi");
1273  EXPECT_EQ("isn't equal to (ignoring case) \"Hi\"", Describe(m));
1274}
1275
1276// Tests that HasSubstr() works for matching string-typed values.
1277TEST(HasSubstrTest, WorksForStringClasses) {
1278  const Matcher<std::string> m1 = HasSubstr("foo");
1279  EXPECT_TRUE(m1.Matches(std::string("I love food.")));
1280  EXPECT_FALSE(m1.Matches(std::string("tofo")));
1281
1282  const Matcher<const std::string&> m2 = HasSubstr("foo");
1283  EXPECT_TRUE(m2.Matches(std::string("I love food.")));
1284  EXPECT_FALSE(m2.Matches(std::string("tofo")));
1285}
1286
1287// Tests that HasSubstr() works for matching C-string-typed values.
1288TEST(HasSubstrTest, WorksForCStrings) {
1289  const Matcher<char*> m1 = HasSubstr("foo");
1290  EXPECT_TRUE(m1.Matches(const_cast<char*>("I love food.")));
1291  EXPECT_FALSE(m1.Matches(const_cast<char*>("tofo")));
1292  EXPECT_FALSE(m1.Matches(NULL));
1293
1294  const Matcher<const char*> m2 = HasSubstr("foo");
1295  EXPECT_TRUE(m2.Matches("I love food."));
1296  EXPECT_FALSE(m2.Matches("tofo"));
1297  EXPECT_FALSE(m2.Matches(NULL));
1298}
1299
1300// Tests that HasSubstr(s) describes itself properly.
1301TEST(HasSubstrTest, CanDescribeSelf) {
1302  Matcher<std::string> m = HasSubstr("foo\n\"");
1303  EXPECT_EQ("has substring \"foo\\n\\\"\"", Describe(m));
1304}
1305
1306TEST(KeyTest, CanDescribeSelf) {
1307  Matcher<const pair<std::string, int>&> m = Key("foo");
1308  EXPECT_EQ("has a key that is equal to \"foo\"", Describe(m));
1309  EXPECT_EQ("doesn't have a key that is equal to \"foo\"", DescribeNegation(m));
1310}
1311
1312TEST(KeyTest, ExplainsResult) {
1313  Matcher<pair<int, bool> > m = Key(GreaterThan(10));
1314  EXPECT_EQ("whose first field is a value which is 5 less than 10",
1315            Explain(m, make_pair(5, true)));
1316  EXPECT_EQ("whose first field is a value which is 5 more than 10",
1317            Explain(m, make_pair(15, true)));
1318}
1319
1320TEST(KeyTest, MatchesCorrectly) {
1321  pair<int, std::string> p(25, "foo");
1322  EXPECT_THAT(p, Key(25));
1323  EXPECT_THAT(p, Not(Key(42)));
1324  EXPECT_THAT(p, Key(Ge(20)));
1325  EXPECT_THAT(p, Not(Key(Lt(25))));
1326}
1327
1328TEST(KeyTest, SafelyCastsInnerMatcher) {
1329  Matcher<int> is_positive = Gt(0);
1330  Matcher<int> is_negative = Lt(0);
1331  pair<char, bool> p('a', true);
1332  EXPECT_THAT(p, Key(is_positive));
1333  EXPECT_THAT(p, Not(Key(is_negative)));
1334}
1335
1336TEST(KeyTest, InsideContainsUsingMap) {
1337  map<int, char> container;
1338  container.insert(make_pair(1, 'a'));
1339  container.insert(make_pair(2, 'b'));
1340  container.insert(make_pair(4, 'c'));
1341  EXPECT_THAT(container, Contains(Key(1)));
1342  EXPECT_THAT(container, Not(Contains(Key(3))));
1343}
1344
1345TEST(KeyTest, InsideContainsUsingMultimap) {
1346  multimap<int, char> container;
1347  container.insert(make_pair(1, 'a'));
1348  container.insert(make_pair(2, 'b'));
1349  container.insert(make_pair(4, 'c'));
1350
1351  EXPECT_THAT(container, Not(Contains(Key(25))));
1352  container.insert(make_pair(25, 'd'));
1353  EXPECT_THAT(container, Contains(Key(25)));
1354  container.insert(make_pair(25, 'e'));
1355  EXPECT_THAT(container, Contains(Key(25)));
1356
1357  EXPECT_THAT(container, Contains(Key(1)));
1358  EXPECT_THAT(container, Not(Contains(Key(3))));
1359}
1360
1361TEST(PairTest, Typing) {
1362  // Test verifies the following type conversions can be compiled.
1363  Matcher<const pair<const char*, int>&> m1 = Pair("foo", 42);
1364  Matcher<const pair<const char*, int> > m2 = Pair("foo", 42);
1365  Matcher<pair<const char*, int> > m3 = Pair("foo", 42);
1366
1367  Matcher<pair<int, const std::string> > m4 = Pair(25, "42");
1368  Matcher<pair<const std::string, int> > m5 = Pair("25", 42);
1369}
1370
1371TEST(PairTest, CanDescribeSelf) {
1372  Matcher<const pair<std::string, int>&> m1 = Pair("foo", 42);
1373  EXPECT_EQ("has a first field that is equal to \"foo\""
1374            ", and has a second field that is equal to 42",
1375            Describe(m1));
1376  EXPECT_EQ("has a first field that isn't equal to \"foo\""
1377            ", or has a second field that isn't equal to 42",
1378            DescribeNegation(m1));
1379  // Double and triple negation (1 or 2 times not and description of negation).
1380  Matcher<const pair<int, int>&> m2 = Not(Pair(Not(13), 42));
1381  EXPECT_EQ("has a first field that isn't equal to 13"
1382            ", and has a second field that is equal to 42",
1383            DescribeNegation(m2));
1384}
1385
1386TEST(PairTest, CanExplainMatchResultTo) {
1387  // If neither field matches, Pair() should explain about the first
1388  // field.
1389  const Matcher<pair<int, int> > m = Pair(GreaterThan(0), GreaterThan(0));
1390  EXPECT_EQ("whose first field does not match, which is 1 less than 0",
1391            Explain(m, make_pair(-1, -2)));
1392
1393  // If the first field matches but the second doesn't, Pair() should
1394  // explain about the second field.
1395  EXPECT_EQ("whose second field does not match, which is 2 less than 0",
1396            Explain(m, make_pair(1, -2)));
1397
1398  // If the first field doesn't match but the second does, Pair()
1399  // should explain about the first field.
1400  EXPECT_EQ("whose first field does not match, which is 1 less than 0",
1401            Explain(m, make_pair(-1, 2)));
1402
1403  // If both fields match, Pair() should explain about them both.
1404  EXPECT_EQ("whose both fields match, where the first field is a value "
1405            "which is 1 more than 0, and the second field is a value "
1406            "which is 2 more than 0",
1407            Explain(m, make_pair(1, 2)));
1408
1409  // If only the first match has an explanation, only this explanation should
1410  // be printed.
1411  const Matcher<pair<int, int> > explain_first = Pair(GreaterThan(0), 0);
1412  EXPECT_EQ("whose both fields match, where the first field is a value "
1413            "which is 1 more than 0",
1414            Explain(explain_first, make_pair(1, 0)));
1415
1416  // If only the second match has an explanation, only this explanation should
1417  // be printed.
1418  const Matcher<pair<int, int> > explain_second = Pair(0, GreaterThan(0));
1419  EXPECT_EQ("whose both fields match, where the second field is a value "
1420            "which is 1 more than 0",
1421            Explain(explain_second, make_pair(0, 1)));
1422}
1423
1424TEST(PairTest, MatchesCorrectly) {
1425  pair<int, std::string> p(25, "foo");
1426
1427  // Both fields match.
1428  EXPECT_THAT(p, Pair(25, "foo"));
1429  EXPECT_THAT(p, Pair(Ge(20), HasSubstr("o")));
1430
1431  // 'first' doesnt' match, but 'second' matches.
1432  EXPECT_THAT(p, Not(Pair(42, "foo")));
1433  EXPECT_THAT(p, Not(Pair(Lt(25), "foo")));
1434
1435  // 'first' matches, but 'second' doesn't match.
1436  EXPECT_THAT(p, Not(Pair(25, "bar")));
1437  EXPECT_THAT(p, Not(Pair(25, Not("foo"))));
1438
1439  // Neither field matches.
1440  EXPECT_THAT(p, Not(Pair(13, "bar")));
1441  EXPECT_THAT(p, Not(Pair(Lt(13), HasSubstr("a"))));
1442}
1443
1444TEST(PairTest, SafelyCastsInnerMatchers) {
1445  Matcher<int> is_positive = Gt(0);
1446  Matcher<int> is_negative = Lt(0);
1447  pair<char, bool> p('a', true);
1448  EXPECT_THAT(p, Pair(is_positive, _));
1449  EXPECT_THAT(p, Not(Pair(is_negative, _)));
1450  EXPECT_THAT(p, Pair(_, is_positive));
1451  EXPECT_THAT(p, Not(Pair(_, is_negative)));
1452}
1453
1454TEST(PairTest, InsideContainsUsingMap) {
1455  map<int, char> container;
1456  container.insert(make_pair(1, 'a'));
1457  container.insert(make_pair(2, 'b'));
1458  container.insert(make_pair(4, 'c'));
1459  EXPECT_THAT(container, Contains(Pair(1, 'a')));
1460  EXPECT_THAT(container, Contains(Pair(1, _)));
1461  EXPECT_THAT(container, Contains(Pair(_, 'a')));
1462  EXPECT_THAT(container, Not(Contains(Pair(3, _))));
1463}
1464
1465// Tests StartsWith(s).
1466
1467TEST(StartsWithTest, MatchesStringWithGivenPrefix) {
1468  const Matcher<const char*> m1 = StartsWith(std::string(""));
1469  EXPECT_TRUE(m1.Matches("Hi"));
1470  EXPECT_TRUE(m1.Matches(""));
1471  EXPECT_FALSE(m1.Matches(NULL));
1472
1473  const Matcher<const std::string&> m2 = StartsWith("Hi");
1474  EXPECT_TRUE(m2.Matches("Hi"));
1475  EXPECT_TRUE(m2.Matches("Hi Hi!"));
1476  EXPECT_TRUE(m2.Matches("High"));
1477  EXPECT_FALSE(m2.Matches("H"));
1478  EXPECT_FALSE(m2.Matches(" Hi"));
1479}
1480
1481TEST(StartsWithTest, CanDescribeSelf) {
1482  Matcher<const std::string> m = StartsWith("Hi");
1483  EXPECT_EQ("starts with \"Hi\"", Describe(m));
1484}
1485
1486// Tests EndsWith(s).
1487
1488TEST(EndsWithTest, MatchesStringWithGivenSuffix) {
1489  const Matcher<const char*> m1 = EndsWith("");
1490  EXPECT_TRUE(m1.Matches("Hi"));
1491  EXPECT_TRUE(m1.Matches(""));
1492  EXPECT_FALSE(m1.Matches(NULL));
1493
1494  const Matcher<const string&> m2 = EndsWith(string("Hi"));
1495  EXPECT_TRUE(m2.Matches("Hi"));
1496  EXPECT_TRUE(m2.Matches("Wow Hi Hi"));
1497  EXPECT_TRUE(m2.Matches("Super Hi"));
1498  EXPECT_FALSE(m2.Matches("i"));
1499  EXPECT_FALSE(m2.Matches("Hi "));
1500}
1501
1502TEST(EndsWithTest, CanDescribeSelf) {
1503  Matcher<const std::string> m = EndsWith("Hi");
1504  EXPECT_EQ("ends with \"Hi\"", Describe(m));
1505}
1506
1507// Tests MatchesRegex().
1508
1509TEST(MatchesRegexTest, MatchesStringMatchingGivenRegex) {
1510  const Matcher<const char*> m1 = MatchesRegex("a.*z");
1511  EXPECT_TRUE(m1.Matches("az"));
1512  EXPECT_TRUE(m1.Matches("abcz"));
1513  EXPECT_FALSE(m1.Matches(NULL));
1514
1515  const Matcher<const std::string&> m2 = MatchesRegex(new RE("a.*z"));
1516  EXPECT_TRUE(m2.Matches("azbz"));
1517  EXPECT_FALSE(m2.Matches("az1"));
1518  EXPECT_FALSE(m2.Matches("1az"));
1519}
1520
1521TEST(MatchesRegexTest, CanDescribeSelf) {
1522  Matcher<const std::string> m1 = MatchesRegex(std::string("Hi.*"));
1523  EXPECT_EQ("matches regular expression \"Hi.*\"", Describe(m1));
1524
1525  Matcher<const char*> m2 = MatchesRegex(new RE("a.*"));
1526  EXPECT_EQ("matches regular expression \"a.*\"", Describe(m2));
1527}
1528
1529// Tests ContainsRegex().
1530
1531TEST(ContainsRegexTest, MatchesStringContainingGivenRegex) {
1532  const Matcher<const char*> m1 = ContainsRegex(std::string("a.*z"));
1533  EXPECT_TRUE(m1.Matches("az"));
1534  EXPECT_TRUE(m1.Matches("0abcz1"));
1535  EXPECT_FALSE(m1.Matches(NULL));
1536
1537  const Matcher<const std::string&> m2 = ContainsRegex(new RE("a.*z"));
1538  EXPECT_TRUE(m2.Matches("azbz"));
1539  EXPECT_TRUE(m2.Matches("az1"));
1540  EXPECT_FALSE(m2.Matches("1a"));
1541}
1542
1543TEST(ContainsRegexTest, CanDescribeSelf) {
1544  Matcher<const std::string> m1 = ContainsRegex("Hi.*");
1545  EXPECT_EQ("contains regular expression \"Hi.*\"", Describe(m1));
1546
1547  Matcher<const char*> m2 = ContainsRegex(new RE("a.*"));
1548  EXPECT_EQ("contains regular expression \"a.*\"", Describe(m2));
1549}
1550
1551// Tests for wide strings.
1552#if GTEST_HAS_STD_WSTRING
1553TEST(StdWideStrEqTest, MatchesEqual) {
1554  Matcher<const wchar_t*> m = StrEq(::std::wstring(L"Hello"));
1555  EXPECT_TRUE(m.Matches(L"Hello"));
1556  EXPECT_FALSE(m.Matches(L"hello"));
1557  EXPECT_FALSE(m.Matches(NULL));
1558
1559  Matcher<const ::std::wstring&> m2 = StrEq(L"Hello");
1560  EXPECT_TRUE(m2.Matches(L"Hello"));
1561  EXPECT_FALSE(m2.Matches(L"Hi"));
1562
1563  Matcher<const ::std::wstring&> m3 = StrEq(L"\xD3\x576\x8D3\xC74D");
1564  EXPECT_TRUE(m3.Matches(L"\xD3\x576\x8D3\xC74D"));
1565  EXPECT_FALSE(m3.Matches(L"\xD3\x576\x8D3\xC74E"));
1566
1567  ::std::wstring str(L"01204500800");
1568  str[3] = L'\0';
1569  Matcher<const ::std::wstring&> m4 = StrEq(str);
1570  EXPECT_TRUE(m4.Matches(str));
1571  str[0] = str[6] = str[7] = str[9] = str[10] = L'\0';
1572  Matcher<const ::std::wstring&> m5 = StrEq(str);
1573  EXPECT_TRUE(m5.Matches(str));
1574}
1575
1576TEST(StdWideStrEqTest, CanDescribeSelf) {
1577  Matcher< ::std::wstring> m = StrEq(L"Hi-\'\"?\\\a\b\f\n\r\t\v");
1578  EXPECT_EQ("is equal to L\"Hi-\'\\\"?\\\\\\a\\b\\f\\n\\r\\t\\v\"",
1579    Describe(m));
1580
1581  Matcher< ::std::wstring> m2 = StrEq(L"\xD3\x576\x8D3\xC74D");
1582  EXPECT_EQ("is equal to L\"\\xD3\\x576\\x8D3\\xC74D\"",
1583    Describe(m2));
1584
1585  ::std::wstring str(L"01204500800");
1586  str[3] = L'\0';
1587  Matcher<const ::std::wstring&> m4 = StrEq(str);
1588  EXPECT_EQ("is equal to L\"012\\04500800\"", Describe(m4));
1589  str[0] = str[6] = str[7] = str[9] = str[10] = L'\0';
1590  Matcher<const ::std::wstring&> m5 = StrEq(str);
1591  EXPECT_EQ("is equal to L\"\\012\\045\\0\\08\\0\\0\"", Describe(m5));
1592}
1593
1594TEST(StdWideStrNeTest, MatchesUnequalString) {
1595  Matcher<const wchar_t*> m = StrNe(L"Hello");
1596  EXPECT_TRUE(m.Matches(L""));
1597  EXPECT_TRUE(m.Matches(NULL));
1598  EXPECT_FALSE(m.Matches(L"Hello"));
1599
1600  Matcher< ::std::wstring> m2 = StrNe(::std::wstring(L"Hello"));
1601  EXPECT_TRUE(m2.Matches(L"hello"));
1602  EXPECT_FALSE(m2.Matches(L"Hello"));
1603}
1604
1605TEST(StdWideStrNeTest, CanDescribeSelf) {
1606  Matcher<const wchar_t*> m = StrNe(L"Hi");
1607  EXPECT_EQ("isn't equal to L\"Hi\"", Describe(m));
1608}
1609
1610TEST(StdWideStrCaseEqTest, MatchesEqualStringIgnoringCase) {
1611  Matcher<const wchar_t*> m = StrCaseEq(::std::wstring(L"Hello"));
1612  EXPECT_TRUE(m.Matches(L"Hello"));
1613  EXPECT_TRUE(m.Matches(L"hello"));
1614  EXPECT_FALSE(m.Matches(L"Hi"));
1615  EXPECT_FALSE(m.Matches(NULL));
1616
1617  Matcher<const ::std::wstring&> m2 = StrCaseEq(L"Hello");
1618  EXPECT_TRUE(m2.Matches(L"hello"));
1619  EXPECT_FALSE(m2.Matches(L"Hi"));
1620}
1621
1622TEST(StdWideStrCaseEqTest, MatchesEqualStringWith0IgnoringCase) {
1623  ::std::wstring str1(L"oabocdooeoo");
1624  ::std::wstring str2(L"OABOCDOOEOO");
1625  Matcher<const ::std::wstring&> m0 = StrCaseEq(str1);
1626  EXPECT_FALSE(m0.Matches(str2 + ::std::wstring(1, L'\0')));
1627
1628  str1[3] = str2[3] = L'\0';
1629  Matcher<const ::std::wstring&> m1 = StrCaseEq(str1);
1630  EXPECT_TRUE(m1.Matches(str2));
1631
1632  str1[0] = str1[6] = str1[7] = str1[10] = L'\0';
1633  str2[0] = str2[6] = str2[7] = str2[10] = L'\0';
1634  Matcher<const ::std::wstring&> m2 = StrCaseEq(str1);
1635  str1[9] = str2[9] = L'\0';
1636  EXPECT_FALSE(m2.Matches(str2));
1637
1638  Matcher<const ::std::wstring&> m3 = StrCaseEq(str1);
1639  EXPECT_TRUE(m3.Matches(str2));
1640
1641  EXPECT_FALSE(m3.Matches(str2 + L"x"));
1642  str2.append(1, L'\0');
1643  EXPECT_FALSE(m3.Matches(str2));
1644  EXPECT_FALSE(m3.Matches(::std::wstring(str2, 0, 9)));
1645}
1646
1647TEST(StdWideStrCaseEqTest, CanDescribeSelf) {
1648  Matcher< ::std::wstring> m = StrCaseEq(L"Hi");
1649  EXPECT_EQ("is equal to (ignoring case) L\"Hi\"", Describe(m));
1650}
1651
1652TEST(StdWideStrCaseNeTest, MatchesUnequalStringIgnoringCase) {
1653  Matcher<const wchar_t*> m = StrCaseNe(L"Hello");
1654  EXPECT_TRUE(m.Matches(L"Hi"));
1655  EXPECT_TRUE(m.Matches(NULL));
1656  EXPECT_FALSE(m.Matches(L"Hello"));
1657  EXPECT_FALSE(m.Matches(L"hello"));
1658
1659  Matcher< ::std::wstring> m2 = StrCaseNe(::std::wstring(L"Hello"));
1660  EXPECT_TRUE(m2.Matches(L""));
1661  EXPECT_FALSE(m2.Matches(L"Hello"));
1662}
1663
1664TEST(StdWideStrCaseNeTest, CanDescribeSelf) {
1665  Matcher<const wchar_t*> m = StrCaseNe(L"Hi");
1666  EXPECT_EQ("isn't equal to (ignoring case) L\"Hi\"", Describe(m));
1667}
1668
1669// Tests that HasSubstr() works for matching wstring-typed values.
1670TEST(StdWideHasSubstrTest, WorksForStringClasses) {
1671  const Matcher< ::std::wstring> m1 = HasSubstr(L"foo");
1672  EXPECT_TRUE(m1.Matches(::std::wstring(L"I love food.")));
1673  EXPECT_FALSE(m1.Matches(::std::wstring(L"tofo")));
1674
1675  const Matcher<const ::std::wstring&> m2 = HasSubstr(L"foo");
1676  EXPECT_TRUE(m2.Matches(::std::wstring(L"I love food.")));
1677  EXPECT_FALSE(m2.Matches(::std::wstring(L"tofo")));
1678}
1679
1680// Tests that HasSubstr() works for matching C-wide-string-typed values.
1681TEST(StdWideHasSubstrTest, WorksForCStrings) {
1682  const Matcher<wchar_t*> m1 = HasSubstr(L"foo");
1683  EXPECT_TRUE(m1.Matches(const_cast<wchar_t*>(L"I love food.")));
1684  EXPECT_FALSE(m1.Matches(const_cast<wchar_t*>(L"tofo")));
1685  EXPECT_FALSE(m1.Matches(NULL));
1686
1687  const Matcher<const wchar_t*> m2 = HasSubstr(L"foo");
1688  EXPECT_TRUE(m2.Matches(L"I love food."));
1689  EXPECT_FALSE(m2.Matches(L"tofo"));
1690  EXPECT_FALSE(m2.Matches(NULL));
1691}
1692
1693// Tests that HasSubstr(s) describes itself properly.
1694TEST(StdWideHasSubstrTest, CanDescribeSelf) {
1695  Matcher< ::std::wstring> m = HasSubstr(L"foo\n\"");
1696  EXPECT_EQ("has substring L\"foo\\n\\\"\"", Describe(m));
1697}
1698
1699// Tests StartsWith(s).
1700
1701TEST(StdWideStartsWithTest, MatchesStringWithGivenPrefix) {
1702  const Matcher<const wchar_t*> m1 = StartsWith(::std::wstring(L""));
1703  EXPECT_TRUE(m1.Matches(L"Hi"));
1704  EXPECT_TRUE(m1.Matches(L""));
1705  EXPECT_FALSE(m1.Matches(NULL));
1706
1707  const Matcher<const ::std::wstring&> m2 = StartsWith(L"Hi");
1708  EXPECT_TRUE(m2.Matches(L"Hi"));
1709  EXPECT_TRUE(m2.Matches(L"Hi Hi!"));
1710  EXPECT_TRUE(m2.Matches(L"High"));
1711  EXPECT_FALSE(m2.Matches(L"H"));
1712  EXPECT_FALSE(m2.Matches(L" Hi"));
1713}
1714
1715TEST(StdWideStartsWithTest, CanDescribeSelf) {
1716  Matcher<const ::std::wstring> m = StartsWith(L"Hi");
1717  EXPECT_EQ("starts with L\"Hi\"", Describe(m));
1718}
1719
1720// Tests EndsWith(s).
1721
1722TEST(StdWideEndsWithTest, MatchesStringWithGivenSuffix) {
1723  const Matcher<const wchar_t*> m1 = EndsWith(L"");
1724  EXPECT_TRUE(m1.Matches(L"Hi"));
1725  EXPECT_TRUE(m1.Matches(L""));
1726  EXPECT_FALSE(m1.Matches(NULL));
1727
1728  const Matcher<const ::std::wstring&> m2 = EndsWith(::std::wstring(L"Hi"));
1729  EXPECT_TRUE(m2.Matches(L"Hi"));
1730  EXPECT_TRUE(m2.Matches(L"Wow Hi Hi"));
1731  EXPECT_TRUE(m2.Matches(L"Super Hi"));
1732  EXPECT_FALSE(m2.Matches(L"i"));
1733  EXPECT_FALSE(m2.Matches(L"Hi "));
1734}
1735
1736TEST(StdWideEndsWithTest, CanDescribeSelf) {
1737  Matcher<const ::std::wstring> m = EndsWith(L"Hi");
1738  EXPECT_EQ("ends with L\"Hi\"", Describe(m));
1739}
1740
1741#endif  // GTEST_HAS_STD_WSTRING
1742
1743#if GTEST_HAS_GLOBAL_WSTRING
1744TEST(GlobalWideStrEqTest, MatchesEqual) {
1745  Matcher<const wchar_t*> m = StrEq(::wstring(L"Hello"));
1746  EXPECT_TRUE(m.Matches(L"Hello"));
1747  EXPECT_FALSE(m.Matches(L"hello"));
1748  EXPECT_FALSE(m.Matches(NULL));
1749
1750  Matcher<const ::wstring&> m2 = StrEq(L"Hello");
1751  EXPECT_TRUE(m2.Matches(L"Hello"));
1752  EXPECT_FALSE(m2.Matches(L"Hi"));
1753
1754  Matcher<const ::wstring&> m3 = StrEq(L"\xD3\x576\x8D3\xC74D");
1755  EXPECT_TRUE(m3.Matches(L"\xD3\x576\x8D3\xC74D"));
1756  EXPECT_FALSE(m3.Matches(L"\xD3\x576\x8D3\xC74E"));
1757
1758  ::wstring str(L"01204500800");
1759  str[3] = L'\0';
1760  Matcher<const ::wstring&> m4 = StrEq(str);
1761  EXPECT_TRUE(m4.Matches(str));
1762  str[0] = str[6] = str[7] = str[9] = str[10] = L'\0';
1763  Matcher<const ::wstring&> m5 = StrEq(str);
1764  EXPECT_TRUE(m5.Matches(str));
1765}
1766
1767TEST(GlobalWideStrEqTest, CanDescribeSelf) {
1768  Matcher< ::wstring> m = StrEq(L"Hi-\'\"?\\\a\b\f\n\r\t\v");
1769  EXPECT_EQ("is equal to L\"Hi-\'\\\"?\\\\\\a\\b\\f\\n\\r\\t\\v\"",
1770    Describe(m));
1771
1772  Matcher< ::wstring> m2 = StrEq(L"\xD3\x576\x8D3\xC74D");
1773  EXPECT_EQ("is equal to L\"\\xD3\\x576\\x8D3\\xC74D\"",
1774    Describe(m2));
1775
1776  ::wstring str(L"01204500800");
1777  str[3] = L'\0';
1778  Matcher<const ::wstring&> m4 = StrEq(str);
1779  EXPECT_EQ("is equal to L\"012\\04500800\"", Describe(m4));
1780  str[0] = str[6] = str[7] = str[9] = str[10] = L'\0';
1781  Matcher<const ::wstring&> m5 = StrEq(str);
1782  EXPECT_EQ("is equal to L\"\\012\\045\\0\\08\\0\\0\"", Describe(m5));
1783}
1784
1785TEST(GlobalWideStrNeTest, MatchesUnequalString) {
1786  Matcher<const wchar_t*> m = StrNe(L"Hello");
1787  EXPECT_TRUE(m.Matches(L""));
1788  EXPECT_TRUE(m.Matches(NULL));
1789  EXPECT_FALSE(m.Matches(L"Hello"));
1790
1791  Matcher< ::wstring> m2 = StrNe(::wstring(L"Hello"));
1792  EXPECT_TRUE(m2.Matches(L"hello"));
1793  EXPECT_FALSE(m2.Matches(L"Hello"));
1794}
1795
1796TEST(GlobalWideStrNeTest, CanDescribeSelf) {
1797  Matcher<const wchar_t*> m = StrNe(L"Hi");
1798  EXPECT_EQ("isn't equal to L\"Hi\"", Describe(m));
1799}
1800
1801TEST(GlobalWideStrCaseEqTest, MatchesEqualStringIgnoringCase) {
1802  Matcher<const wchar_t*> m = StrCaseEq(::wstring(L"Hello"));
1803  EXPECT_TRUE(m.Matches(L"Hello"));
1804  EXPECT_TRUE(m.Matches(L"hello"));
1805  EXPECT_FALSE(m.Matches(L"Hi"));
1806  EXPECT_FALSE(m.Matches(NULL));
1807
1808  Matcher<const ::wstring&> m2 = StrCaseEq(L"Hello");
1809  EXPECT_TRUE(m2.Matches(L"hello"));
1810  EXPECT_FALSE(m2.Matches(L"Hi"));
1811}
1812
1813TEST(GlobalWideStrCaseEqTest, MatchesEqualStringWith0IgnoringCase) {
1814  ::wstring str1(L"oabocdooeoo");
1815  ::wstring str2(L"OABOCDOOEOO");
1816  Matcher<const ::wstring&> m0 = StrCaseEq(str1);
1817  EXPECT_FALSE(m0.Matches(str2 + ::wstring(1, L'\0')));
1818
1819  str1[3] = str2[3] = L'\0';
1820  Matcher<const ::wstring&> m1 = StrCaseEq(str1);
1821  EXPECT_TRUE(m1.Matches(str2));
1822
1823  str1[0] = str1[6] = str1[7] = str1[10] = L'\0';
1824  str2[0] = str2[6] = str2[7] = str2[10] = L'\0';
1825  Matcher<const ::wstring&> m2 = StrCaseEq(str1);
1826  str1[9] = str2[9] = L'\0';
1827  EXPECT_FALSE(m2.Matches(str2));
1828
1829  Matcher<const ::wstring&> m3 = StrCaseEq(str1);
1830  EXPECT_TRUE(m3.Matches(str2));
1831
1832  EXPECT_FALSE(m3.Matches(str2 + L"x"));
1833  str2.append(1, L'\0');
1834  EXPECT_FALSE(m3.Matches(str2));
1835  EXPECT_FALSE(m3.Matches(::wstring(str2, 0, 9)));
1836}
1837
1838TEST(GlobalWideStrCaseEqTest, CanDescribeSelf) {
1839  Matcher< ::wstring> m = StrCaseEq(L"Hi");
1840  EXPECT_EQ("is equal to (ignoring case) L\"Hi\"", Describe(m));
1841}
1842
1843TEST(GlobalWideStrCaseNeTest, MatchesUnequalStringIgnoringCase) {
1844  Matcher<const wchar_t*> m = StrCaseNe(L"Hello");
1845  EXPECT_TRUE(m.Matches(L"Hi"));
1846  EXPECT_TRUE(m.Matches(NULL));
1847  EXPECT_FALSE(m.Matches(L"Hello"));
1848  EXPECT_FALSE(m.Matches(L"hello"));
1849
1850  Matcher< ::wstring> m2 = StrCaseNe(::wstring(L"Hello"));
1851  EXPECT_TRUE(m2.Matches(L""));
1852  EXPECT_FALSE(m2.Matches(L"Hello"));
1853}
1854
1855TEST(GlobalWideStrCaseNeTest, CanDescribeSelf) {
1856  Matcher<const wchar_t*> m = StrCaseNe(L"Hi");
1857  EXPECT_EQ("isn't equal to (ignoring case) L\"Hi\"", Describe(m));
1858}
1859
1860// Tests that HasSubstr() works for matching wstring-typed values.
1861TEST(GlobalWideHasSubstrTest, WorksForStringClasses) {
1862  const Matcher< ::wstring> m1 = HasSubstr(L"foo");
1863  EXPECT_TRUE(m1.Matches(::wstring(L"I love food.")));
1864  EXPECT_FALSE(m1.Matches(::wstring(L"tofo")));
1865
1866  const Matcher<const ::wstring&> m2 = HasSubstr(L"foo");
1867  EXPECT_TRUE(m2.Matches(::wstring(L"I love food.")));
1868  EXPECT_FALSE(m2.Matches(::wstring(L"tofo")));
1869}
1870
1871// Tests that HasSubstr() works for matching C-wide-string-typed values.
1872TEST(GlobalWideHasSubstrTest, WorksForCStrings) {
1873  const Matcher<wchar_t*> m1 = HasSubstr(L"foo");
1874  EXPECT_TRUE(m1.Matches(const_cast<wchar_t*>(L"I love food.")));
1875  EXPECT_FALSE(m1.Matches(const_cast<wchar_t*>(L"tofo")));
1876  EXPECT_FALSE(m1.Matches(NULL));
1877
1878  const Matcher<const wchar_t*> m2 = HasSubstr(L"foo");
1879  EXPECT_TRUE(m2.Matches(L"I love food."));
1880  EXPECT_FALSE(m2.Matches(L"tofo"));
1881  EXPECT_FALSE(m2.Matches(NULL));
1882}
1883
1884// Tests that HasSubstr(s) describes itself properly.
1885TEST(GlobalWideHasSubstrTest, CanDescribeSelf) {
1886  Matcher< ::wstring> m = HasSubstr(L"foo\n\"");
1887  EXPECT_EQ("has substring L\"foo\\n\\\"\"", Describe(m));
1888}
1889
1890// Tests StartsWith(s).
1891
1892TEST(GlobalWideStartsWithTest, MatchesStringWithGivenPrefix) {
1893  const Matcher<const wchar_t*> m1 = StartsWith(::wstring(L""));
1894  EXPECT_TRUE(m1.Matches(L"Hi"));
1895  EXPECT_TRUE(m1.Matches(L""));
1896  EXPECT_FALSE(m1.Matches(NULL));
1897
1898  const Matcher<const ::wstring&> m2 = StartsWith(L"Hi");
1899  EXPECT_TRUE(m2.Matches(L"Hi"));
1900  EXPECT_TRUE(m2.Matches(L"Hi Hi!"));
1901  EXPECT_TRUE(m2.Matches(L"High"));
1902  EXPECT_FALSE(m2.Matches(L"H"));
1903  EXPECT_FALSE(m2.Matches(L" Hi"));
1904}
1905
1906TEST(GlobalWideStartsWithTest, CanDescribeSelf) {
1907  Matcher<const ::wstring> m = StartsWith(L"Hi");
1908  EXPECT_EQ("starts with L\"Hi\"", Describe(m));
1909}
1910
1911// Tests EndsWith(s).
1912
1913TEST(GlobalWideEndsWithTest, MatchesStringWithGivenSuffix) {
1914  const Matcher<const wchar_t*> m1 = EndsWith(L"");
1915  EXPECT_TRUE(m1.Matches(L"Hi"));
1916  EXPECT_TRUE(m1.Matches(L""));
1917  EXPECT_FALSE(m1.Matches(NULL));
1918
1919  const Matcher<const ::wstring&> m2 = EndsWith(::wstring(L"Hi"));
1920  EXPECT_TRUE(m2.Matches(L"Hi"));
1921  EXPECT_TRUE(m2.Matches(L"Wow Hi Hi"));
1922  EXPECT_TRUE(m2.Matches(L"Super Hi"));
1923  EXPECT_FALSE(m2.Matches(L"i"));
1924  EXPECT_FALSE(m2.Matches(L"Hi "));
1925}
1926
1927TEST(GlobalWideEndsWithTest, CanDescribeSelf) {
1928  Matcher<const ::wstring> m = EndsWith(L"Hi");
1929  EXPECT_EQ("ends with L\"Hi\"", Describe(m));
1930}
1931
1932#endif  // GTEST_HAS_GLOBAL_WSTRING
1933
1934
1935typedef ::testing::tuple<long, int> Tuple2;  // NOLINT
1936
1937// Tests that Eq() matches a 2-tuple where the first field == the
1938// second field.
1939TEST(Eq2Test, MatchesEqualArguments) {
1940  Matcher<const Tuple2&> m = Eq();
1941  EXPECT_TRUE(m.Matches(Tuple2(5L, 5)));
1942  EXPECT_FALSE(m.Matches(Tuple2(5L, 6)));
1943}
1944
1945// Tests that Eq() describes itself properly.
1946TEST(Eq2Test, CanDescribeSelf) {
1947  Matcher<const Tuple2&> m = Eq();
1948  EXPECT_EQ("are an equal pair", Describe(m));
1949}
1950
1951// Tests that Ge() matches a 2-tuple where the first field >= the
1952// second field.
1953TEST(Ge2Test, MatchesGreaterThanOrEqualArguments) {
1954  Matcher<const Tuple2&> m = Ge();
1955  EXPECT_TRUE(m.Matches(Tuple2(5L, 4)));
1956  EXPECT_TRUE(m.Matches(Tuple2(5L, 5)));
1957  EXPECT_FALSE(m.Matches(Tuple2(5L, 6)));
1958}
1959
1960// Tests that Ge() describes itself properly.
1961TEST(Ge2Test, CanDescribeSelf) {
1962  Matcher<const Tuple2&> m = Ge();
1963  EXPECT_EQ("are a pair where the first >= the second", Describe(m));
1964}
1965
1966// Tests that Gt() matches a 2-tuple where the first field > the
1967// second field.
1968TEST(Gt2Test, MatchesGreaterThanArguments) {
1969  Matcher<const Tuple2&> m = Gt();
1970  EXPECT_TRUE(m.Matches(Tuple2(5L, 4)));
1971  EXPECT_FALSE(m.Matches(Tuple2(5L, 5)));
1972  EXPECT_FALSE(m.Matches(Tuple2(5L, 6)));
1973}
1974
1975// Tests that Gt() describes itself properly.
1976TEST(Gt2Test, CanDescribeSelf) {
1977  Matcher<const Tuple2&> m = Gt();
1978  EXPECT_EQ("are a pair where the first > the second", Describe(m));
1979}
1980
1981// Tests that Le() matches a 2-tuple where the first field <= the
1982// second field.
1983TEST(Le2Test, MatchesLessThanOrEqualArguments) {
1984  Matcher<const Tuple2&> m = Le();
1985  EXPECT_TRUE(m.Matches(Tuple2(5L, 6)));
1986  EXPECT_TRUE(m.Matches(Tuple2(5L, 5)));
1987  EXPECT_FALSE(m.Matches(Tuple2(5L, 4)));
1988}
1989
1990// Tests that Le() describes itself properly.
1991TEST(Le2Test, CanDescribeSelf) {
1992  Matcher<const Tuple2&> m = Le();
1993  EXPECT_EQ("are a pair where the first <= the second", Describe(m));
1994}
1995
1996// Tests that Lt() matches a 2-tuple where the first field < the
1997// second field.
1998TEST(Lt2Test, MatchesLessThanArguments) {
1999  Matcher<const Tuple2&> m = Lt();
2000  EXPECT_TRUE(m.Matches(Tuple2(5L, 6)));
2001  EXPECT_FALSE(m.Matches(Tuple2(5L, 5)));
2002  EXPECT_FALSE(m.Matches(Tuple2(5L, 4)));
2003}
2004
2005// Tests that Lt() describes itself properly.
2006TEST(Lt2Test, CanDescribeSelf) {
2007  Matcher<const Tuple2&> m = Lt();
2008  EXPECT_EQ("are a pair where the first < the second", Describe(m));
2009}
2010
2011// Tests that Ne() matches a 2-tuple where the first field != the
2012// second field.
2013TEST(Ne2Test, MatchesUnequalArguments) {
2014  Matcher<const Tuple2&> m = Ne();
2015  EXPECT_TRUE(m.Matches(Tuple2(5L, 6)));
2016  EXPECT_TRUE(m.Matches(Tuple2(5L, 4)));
2017  EXPECT_FALSE(m.Matches(Tuple2(5L, 5)));
2018}
2019
2020// Tests that Ne() describes itself properly.
2021TEST(Ne2Test, CanDescribeSelf) {
2022  Matcher<const Tuple2&> m = Ne();
2023  EXPECT_EQ("are an unequal pair", Describe(m));
2024}
2025
2026// Tests that Not(m) matches any value that doesn't match m.
2027TEST(NotTest, NegatesMatcher) {
2028  Matcher<int> m;
2029  m = Not(Eq(2));
2030  EXPECT_TRUE(m.Matches(3));
2031  EXPECT_FALSE(m.Matches(2));
2032}
2033
2034// Tests that Not(m) describes itself properly.
2035TEST(NotTest, CanDescribeSelf) {
2036  Matcher<int> m = Not(Eq(5));
2037  EXPECT_EQ("isn't equal to 5", Describe(m));
2038}
2039
2040// Tests that monomorphic matchers are safely cast by the Not matcher.
2041TEST(NotTest, NotMatcherSafelyCastsMonomorphicMatchers) {
2042  // greater_than_5 is a monomorphic matcher.
2043  Matcher<int> greater_than_5 = Gt(5);
2044
2045  Matcher<const int&> m = Not(greater_than_5);
2046  Matcher<int&> m2 = Not(greater_than_5);
2047  Matcher<int&> m3 = Not(m);
2048}
2049
2050// Helper to allow easy testing of AllOf matchers with num parameters.
2051void AllOfMatches(int num, const Matcher<int>& m) {
2052  SCOPED_TRACE(Describe(m));
2053  EXPECT_TRUE(m.Matches(0));
2054  for (int i = 1; i <= num; ++i) {
2055    EXPECT_FALSE(m.Matches(i));
2056  }
2057  EXPECT_TRUE(m.Matches(num + 1));
2058}
2059
2060// Tests that AllOf(m1, ..., mn) matches any value that matches all of
2061// the given matchers.
2062TEST(AllOfTest, MatchesWhenAllMatch) {
2063  Matcher<int> m;
2064  m = AllOf(Le(2), Ge(1));
2065  EXPECT_TRUE(m.Matches(1));
2066  EXPECT_TRUE(m.Matches(2));
2067  EXPECT_FALSE(m.Matches(0));
2068  EXPECT_FALSE(m.Matches(3));
2069
2070  m = AllOf(Gt(0), Ne(1), Ne(2));
2071  EXPECT_TRUE(m.Matches(3));
2072  EXPECT_FALSE(m.Matches(2));
2073  EXPECT_FALSE(m.Matches(1));
2074  EXPECT_FALSE(m.Matches(0));
2075
2076  m = AllOf(Gt(0), Ne(1), Ne(2), Ne(3));
2077  EXPECT_TRUE(m.Matches(4));
2078  EXPECT_FALSE(m.Matches(3));
2079  EXPECT_FALSE(m.Matches(2));
2080  EXPECT_FALSE(m.Matches(1));
2081  EXPECT_FALSE(m.Matches(0));
2082
2083  m = AllOf(Ge(0), Lt(10), Ne(3), Ne(5), Ne(7));
2084  EXPECT_TRUE(m.Matches(0));
2085  EXPECT_TRUE(m.Matches(1));
2086  EXPECT_FALSE(m.Matches(3));
2087
2088  // The following tests for varying number of sub-matchers. Due to the way
2089  // the sub-matchers are handled it is enough to test every sub-matcher once
2090  // with sub-matchers using the same matcher type. Varying matcher types are
2091  // checked for above.
2092  AllOfMatches(2, AllOf(Ne(1), Ne(2)));
2093  AllOfMatches(3, AllOf(Ne(1), Ne(2), Ne(3)));
2094  AllOfMatches(4, AllOf(Ne(1), Ne(2), Ne(3), Ne(4)));
2095  AllOfMatches(5, AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5)));
2096  AllOfMatches(6, AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5), Ne(6)));
2097  AllOfMatches(7, AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5), Ne(6), Ne(7)));
2098  AllOfMatches(8, AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5), Ne(6), Ne(7),
2099                        Ne(8)));
2100  AllOfMatches(9, AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5), Ne(6), Ne(7),
2101                        Ne(8), Ne(9)));
2102  AllOfMatches(10, AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5), Ne(6), Ne(7), Ne(8),
2103                         Ne(9), Ne(10)));
2104}
2105
2106#if GTEST_LANG_CXX11
2107// Tests the variadic version of the AllOfMatcher.
2108TEST(AllOfTest, VariadicMatchesWhenAllMatch) {
2109  // Make sure AllOf is defined in the right namespace and does not depend on
2110  // ADL.
2111  ::testing::AllOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11);
2112  Matcher<int> m = AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5), Ne(6), Ne(7), Ne(8),
2113                         Ne(9), Ne(10), Ne(11));
2114  EXPECT_THAT(Describe(m), EndsWith("and (isn't equal to 11))))))))))"));
2115  AllOfMatches(11, m);
2116  AllOfMatches(50, AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5), Ne(6), Ne(7), Ne(8),
2117                         Ne(9), Ne(10), Ne(11), Ne(12), Ne(13), Ne(14), Ne(15),
2118                         Ne(16), Ne(17), Ne(18), Ne(19), Ne(20), Ne(21), Ne(22),
2119                         Ne(23), Ne(24), Ne(25), Ne(26), Ne(27), Ne(28), Ne(29),
2120                         Ne(30), Ne(31), Ne(32), Ne(33), Ne(34), Ne(35), Ne(36),
2121                         Ne(37), Ne(38), Ne(39), Ne(40), Ne(41), Ne(42), Ne(43),
2122                         Ne(44), Ne(45), Ne(46), Ne(47), Ne(48), Ne(49),
2123                         Ne(50)));
2124}
2125
2126#endif  // GTEST_LANG_CXX11
2127
2128// Tests that AllOf(m1, ..., mn) describes itself properly.
2129TEST(AllOfTest, CanDescribeSelf) {
2130  Matcher<int> m;
2131  m = AllOf(Le(2), Ge(1));
2132  EXPECT_EQ("(is <= 2) and (is >= 1)", Describe(m));
2133
2134  m = AllOf(Gt(0), Ne(1), Ne(2));
2135  EXPECT_EQ("(is > 0) and "
2136            "((isn't equal to 1) and "
2137            "(isn't equal to 2))",
2138            Describe(m));
2139
2140
2141  m = AllOf(Gt(0), Ne(1), Ne(2), Ne(3));
2142  EXPECT_EQ("((is > 0) and "
2143            "(isn't equal to 1)) and "
2144            "((isn't equal to 2) and "
2145            "(isn't equal to 3))",
2146            Describe(m));
2147
2148
2149  m = AllOf(Ge(0), Lt(10), Ne(3), Ne(5), Ne(7));
2150  EXPECT_EQ("((is >= 0) and "
2151            "(is < 10)) and "
2152            "((isn't equal to 3) and "
2153            "((isn't equal to 5) and "
2154            "(isn't equal to 7)))",
2155            Describe(m));
2156}
2157
2158// Tests that AllOf(m1, ..., mn) describes its negation properly.
2159TEST(AllOfTest, CanDescribeNegation) {
2160  Matcher<int> m;
2161  m = AllOf(Le(2), Ge(1));
2162  EXPECT_EQ("(isn't <= 2) or "
2163            "(isn't >= 1)",
2164            DescribeNegation(m));
2165
2166  m = AllOf(Gt(0), Ne(1), Ne(2));
2167  EXPECT_EQ("(isn't > 0) or "
2168            "((is equal to 1) or "
2169            "(is equal to 2))",
2170            DescribeNegation(m));
2171
2172
2173  m = AllOf(Gt(0), Ne(1), Ne(2), Ne(3));
2174  EXPECT_EQ("((isn't > 0) or "
2175            "(is equal to 1)) or "
2176            "((is equal to 2) or "
2177            "(is equal to 3))",
2178            DescribeNegation(m));
2179
2180
2181  m = AllOf(Ge(0), Lt(10), Ne(3), Ne(5), Ne(7));
2182  EXPECT_EQ("((isn't >= 0) or "
2183            "(isn't < 10)) or "
2184            "((is equal to 3) or "
2185            "((is equal to 5) or "
2186            "(is equal to 7)))",
2187            DescribeNegation(m));
2188}
2189
2190// Tests that monomorphic matchers are safely cast by the AllOf matcher.
2191TEST(AllOfTest, AllOfMatcherSafelyCastsMonomorphicMatchers) {
2192  // greater_than_5 and less_than_10 are monomorphic matchers.
2193  Matcher<int> greater_than_5 = Gt(5);
2194  Matcher<int> less_than_10 = Lt(10);
2195
2196  Matcher<const int&> m = AllOf(greater_than_5, less_than_10);
2197  Matcher<int&> m2 = AllOf(greater_than_5, less_than_10);
2198  Matcher<int&> m3 = AllOf(greater_than_5, m2);
2199
2200  // Tests that BothOf works when composing itself.
2201  Matcher<const int&> m4 = AllOf(greater_than_5, less_than_10, less_than_10);
2202  Matcher<int&> m5 = AllOf(greater_than_5, less_than_10, less_than_10);
2203}
2204
2205TEST(AllOfTest, ExplainsResult) {
2206  Matcher<int> m;
2207
2208  // Successful match.  Both matchers need to explain.  The second
2209  // matcher doesn't give an explanation, so only the first matcher's
2210  // explanation is printed.
2211  m = AllOf(GreaterThan(10), Lt(30));
2212  EXPECT_EQ("which is 15 more than 10", Explain(m, 25));
2213
2214  // Successful match.  Both matchers need to explain.
2215  m = AllOf(GreaterThan(10), GreaterThan(20));
2216  EXPECT_EQ("which is 20 more than 10, and which is 10 more than 20",
2217            Explain(m, 30));
2218
2219  // Successful match.  All matchers need to explain.  The second
2220  // matcher doesn't given an explanation.
2221  m = AllOf(GreaterThan(10), Lt(30), GreaterThan(20));
2222  EXPECT_EQ("which is 15 more than 10, and which is 5 more than 20",
2223            Explain(m, 25));
2224
2225  // Successful match.  All matchers need to explain.
2226  m = AllOf(GreaterThan(10), GreaterThan(20), GreaterThan(30));
2227  EXPECT_EQ("which is 30 more than 10, and which is 20 more than 20, "
2228            "and which is 10 more than 30",
2229            Explain(m, 40));
2230
2231  // Failed match.  The first matcher, which failed, needs to
2232  // explain.
2233  m = AllOf(GreaterThan(10), GreaterThan(20));
2234  EXPECT_EQ("which is 5 less than 10", Explain(m, 5));
2235
2236  // Failed match.  The second matcher, which failed, needs to
2237  // explain.  Since it doesn't given an explanation, nothing is
2238  // printed.
2239  m = AllOf(GreaterThan(10), Lt(30));
2240  EXPECT_EQ("", Explain(m, 40));
2241
2242  // Failed match.  The second matcher, which failed, needs to
2243  // explain.
2244  m = AllOf(GreaterThan(10), GreaterThan(20));
2245  EXPECT_EQ("which is 5 less than 20", Explain(m, 15));
2246}
2247
2248// Helper to allow easy testing of AnyOf matchers with num parameters.
2249void AnyOfMatches(int num, const Matcher<int>& m) {
2250  SCOPED_TRACE(Describe(m));
2251  EXPECT_FALSE(m.Matches(0));
2252  for (int i = 1; i <= num; ++i) {
2253    EXPECT_TRUE(m.Matches(i));
2254  }
2255  EXPECT_FALSE(m.Matches(num + 1));
2256}
2257
2258// Tests that AnyOf(m1, ..., mn) matches any value that matches at
2259// least one of the given matchers.
2260TEST(AnyOfTest, MatchesWhenAnyMatches) {
2261  Matcher<int> m;
2262  m = AnyOf(Le(1), Ge(3));
2263  EXPECT_TRUE(m.Matches(1));
2264  EXPECT_TRUE(m.Matches(4));
2265  EXPECT_FALSE(m.Matches(2));
2266
2267  m = AnyOf(Lt(0), Eq(1), Eq(2));
2268  EXPECT_TRUE(m.Matches(-1));
2269  EXPECT_TRUE(m.Matches(1));
2270  EXPECT_TRUE(m.Matches(2));
2271  EXPECT_FALSE(m.Matches(0));
2272
2273  m = AnyOf(Lt(0), Eq(1), Eq(2), Eq(3));
2274  EXPECT_TRUE(m.Matches(-1));
2275  EXPECT_TRUE(m.Matches(1));
2276  EXPECT_TRUE(m.Matches(2));
2277  EXPECT_TRUE(m.Matches(3));
2278  EXPECT_FALSE(m.Matches(0));
2279
2280  m = AnyOf(Le(0), Gt(10), 3, 5, 7);
2281  EXPECT_TRUE(m.Matches(0));
2282  EXPECT_TRUE(m.Matches(11));
2283  EXPECT_TRUE(m.Matches(3));
2284  EXPECT_FALSE(m.Matches(2));
2285
2286  // The following tests for varying number of sub-matchers. Due to the way
2287  // the sub-matchers are handled it is enough to test every sub-matcher once
2288  // with sub-matchers using the same matcher type. Varying matcher types are
2289  // checked for above.
2290  AnyOfMatches(2, AnyOf(1, 2));
2291  AnyOfMatches(3, AnyOf(1, 2, 3));
2292  AnyOfMatches(4, AnyOf(1, 2, 3, 4));
2293  AnyOfMatches(5, AnyOf(1, 2, 3, 4, 5));
2294  AnyOfMatches(6, AnyOf(1, 2, 3, 4, 5, 6));
2295  AnyOfMatches(7, AnyOf(1, 2, 3, 4, 5, 6, 7));
2296  AnyOfMatches(8, AnyOf(1, 2, 3, 4, 5, 6, 7, 8));
2297  AnyOfMatches(9, AnyOf(1, 2, 3, 4, 5, 6, 7, 8, 9));
2298  AnyOfMatches(10, AnyOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10));
2299}
2300
2301#if GTEST_LANG_CXX11
2302// Tests the variadic version of the AnyOfMatcher.
2303TEST(AnyOfTest, VariadicMatchesWhenAnyMatches) {
2304  // Also make sure AnyOf is defined in the right namespace and does not depend
2305  // on ADL.
2306  Matcher<int> m = ::testing::AnyOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11);
2307
2308  EXPECT_THAT(Describe(m), EndsWith("or (is equal to 11))))))))))"));
2309  AnyOfMatches(11, m);
2310  AnyOfMatches(50, AnyOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
2311                         11, 12, 13, 14, 15, 16, 17, 18, 19, 20,
2312                         21, 22, 23, 24, 25, 26, 27, 28, 29, 30,
2313                         31, 32, 33, 34, 35, 36, 37, 38, 39, 40,
2314                         41, 42, 43, 44, 45, 46, 47, 48, 49, 50));
2315}
2316
2317#endif  // GTEST_LANG_CXX11
2318
2319// Tests that AnyOf(m1, ..., mn) describes itself properly.
2320TEST(AnyOfTest, CanDescribeSelf) {
2321  Matcher<int> m;
2322  m = AnyOf(Le(1), Ge(3));
2323  EXPECT_EQ("(is <= 1) or (is >= 3)",
2324            Describe(m));
2325
2326  m = AnyOf(Lt(0), Eq(1), Eq(2));
2327  EXPECT_EQ("(is < 0) or "
2328            "((is equal to 1) or (is equal to 2))",
2329            Describe(m));
2330
2331  m = AnyOf(Lt(0), Eq(1), Eq(2), Eq(3));
2332  EXPECT_EQ("((is < 0) or "
2333            "(is equal to 1)) or "
2334            "((is equal to 2) or "
2335            "(is equal to 3))",
2336            Describe(m));
2337
2338  m = AnyOf(Le(0), Gt(10), 3, 5, 7);
2339  EXPECT_EQ("((is <= 0) or "
2340            "(is > 10)) or "
2341            "((is equal to 3) or "
2342            "((is equal to 5) or "
2343            "(is equal to 7)))",
2344            Describe(m));
2345}
2346
2347// Tests that AnyOf(m1, ..., mn) describes its negation properly.
2348TEST(AnyOfTest, CanDescribeNegation) {
2349  Matcher<int> m;
2350  m = AnyOf(Le(1), Ge(3));
2351  EXPECT_EQ("(isn't <= 1) and (isn't >= 3)",
2352            DescribeNegation(m));
2353
2354  m = AnyOf(Lt(0), Eq(1), Eq(2));
2355  EXPECT_EQ("(isn't < 0) and "
2356            "((isn't equal to 1) and (isn't equal to 2))",
2357            DescribeNegation(m));
2358
2359  m = AnyOf(Lt(0), Eq(1), Eq(2), Eq(3));
2360  EXPECT_EQ("((isn't < 0) and "
2361            "(isn't equal to 1)) and "
2362            "((isn't equal to 2) and "
2363            "(isn't equal to 3))",
2364            DescribeNegation(m));
2365
2366  m = AnyOf(Le(0), Gt(10), 3, 5, 7);
2367  EXPECT_EQ("((isn't <= 0) and "
2368            "(isn't > 10)) and "
2369            "((isn't equal to 3) and "
2370            "((isn't equal to 5) and "
2371            "(isn't equal to 7)))",
2372            DescribeNegation(m));
2373}
2374
2375// Tests that monomorphic matchers are safely cast by the AnyOf matcher.
2376TEST(AnyOfTest, AnyOfMatcherSafelyCastsMonomorphicMatchers) {
2377  // greater_than_5 and less_than_10 are monomorphic matchers.
2378  Matcher<int> greater_than_5 = Gt(5);
2379  Matcher<int> less_than_10 = Lt(10);
2380
2381  Matcher<const int&> m = AnyOf(greater_than_5, less_than_10);
2382  Matcher<int&> m2 = AnyOf(greater_than_5, less_than_10);
2383  Matcher<int&> m3 = AnyOf(greater_than_5, m2);
2384
2385  // Tests that EitherOf works when composing itself.
2386  Matcher<const int&> m4 = AnyOf(greater_than_5, less_than_10, less_than_10);
2387  Matcher<int&> m5 = AnyOf(greater_than_5, less_than_10, less_than_10);
2388}
2389
2390TEST(AnyOfTest, ExplainsResult) {
2391  Matcher<int> m;
2392
2393  // Failed match.  Both matchers need to explain.  The second
2394  // matcher doesn't give an explanation, so only the first matcher's
2395  // explanation is printed.
2396  m = AnyOf(GreaterThan(10), Lt(0));
2397  EXPECT_EQ("which is 5 less than 10", Explain(m, 5));
2398
2399  // Failed match.  Both matchers need to explain.
2400  m = AnyOf(GreaterThan(10), GreaterThan(20));
2401  EXPECT_EQ("which is 5 less than 10, and which is 15 less than 20",
2402            Explain(m, 5));
2403
2404  // Failed match.  All matchers need to explain.  The second
2405  // matcher doesn't given an explanation.
2406  m = AnyOf(GreaterThan(10), Gt(20), GreaterThan(30));
2407  EXPECT_EQ("which is 5 less than 10, and which is 25 less than 30",
2408            Explain(m, 5));
2409
2410  // Failed match.  All matchers need to explain.
2411  m = AnyOf(GreaterThan(10), GreaterThan(20), GreaterThan(30));
2412  EXPECT_EQ("which is 5 less than 10, and which is 15 less than 20, "
2413            "and which is 25 less than 30",
2414            Explain(m, 5));
2415
2416  // Successful match.  The first matcher, which succeeded, needs to
2417  // explain.
2418  m = AnyOf(GreaterThan(10), GreaterThan(20));
2419  EXPECT_EQ("which is 5 more than 10", Explain(m, 15));
2420
2421  // Successful match.  The second matcher, which succeeded, needs to
2422  // explain.  Since it doesn't given an explanation, nothing is
2423  // printed.
2424  m = AnyOf(GreaterThan(10), Lt(30));
2425  EXPECT_EQ("", Explain(m, 0));
2426
2427  // Successful match.  The second matcher, which succeeded, needs to
2428  // explain.
2429  m = AnyOf(GreaterThan(30), GreaterThan(20));
2430  EXPECT_EQ("which is 5 more than 20", Explain(m, 25));
2431}
2432
2433// The following predicate function and predicate functor are for
2434// testing the Truly(predicate) matcher.
2435
2436// Returns non-zero if the input is positive.  Note that the return
2437// type of this function is not bool.  It's OK as Truly() accepts any
2438// unary function or functor whose return type can be implicitly
2439// converted to bool.
2440int IsPositive(double x) {
2441  return x > 0 ? 1 : 0;
2442}
2443
2444// This functor returns true if the input is greater than the given
2445// number.
2446class IsGreaterThan {
2447 public:
2448  explicit IsGreaterThan(int threshold) : threshold_(threshold) {}
2449
2450  bool operator()(int n) const { return n > threshold_; }
2451
2452 private:
2453  int threshold_;
2454};
2455
2456// For testing Truly().
2457const int foo = 0;
2458
2459// This predicate returns true iff the argument references foo and has
2460// a zero value.
2461bool ReferencesFooAndIsZero(const int& n) {
2462  return (&n == &foo) && (n == 0);
2463}
2464
2465// Tests that Truly(predicate) matches what satisfies the given
2466// predicate.
2467TEST(TrulyTest, MatchesWhatSatisfiesThePredicate) {
2468  Matcher<double> m = Truly(IsPositive);
2469  EXPECT_TRUE(m.Matches(2.0));
2470  EXPECT_FALSE(m.Matches(-1.5));
2471}
2472
2473// Tests that Truly(predicate_functor) works too.
2474TEST(TrulyTest, CanBeUsedWithFunctor) {
2475  Matcher<int> m = Truly(IsGreaterThan(5));
2476  EXPECT_TRUE(m.Matches(6));
2477  EXPECT_FALSE(m.Matches(4));
2478}
2479
2480// A class that can be implicitly converted to bool.
2481class ConvertibleToBool {
2482 public:
2483  explicit ConvertibleToBool(int number) : number_(number) {}
2484  operator bool() const { return number_ != 0; }
2485
2486 private:
2487  int number_;
2488};
2489
2490ConvertibleToBool IsNotZero(int number) {
2491  return ConvertibleToBool(number);
2492}
2493
2494// Tests that the predicate used in Truly() may return a class that's
2495// implicitly convertible to bool, even when the class has no
2496// operator!().
2497TEST(TrulyTest, PredicateCanReturnAClassConvertibleToBool) {
2498  Matcher<int> m = Truly(IsNotZero);
2499  EXPECT_TRUE(m.Matches(1));
2500  EXPECT_FALSE(m.Matches(0));
2501}
2502
2503// Tests that Truly(predicate) can describe itself properly.
2504TEST(TrulyTest, CanDescribeSelf) {
2505  Matcher<double> m = Truly(IsPositive);
2506  EXPECT_EQ("satisfies the given predicate",
2507            Describe(m));
2508}
2509
2510// Tests that Truly(predicate) works when the matcher takes its
2511// argument by reference.
2512TEST(TrulyTest, WorksForByRefArguments) {
2513  Matcher<const int&> m = Truly(ReferencesFooAndIsZero);
2514  EXPECT_TRUE(m.Matches(foo));
2515  int n = 0;
2516  EXPECT_FALSE(m.Matches(n));
2517}
2518
2519// Tests that Matches(m) is a predicate satisfied by whatever that
2520// matches matcher m.
2521TEST(MatchesTest, IsSatisfiedByWhatMatchesTheMatcher) {
2522  EXPECT_TRUE(Matches(Ge(0))(1));
2523  EXPECT_FALSE(Matches(Eq('a'))('b'));
2524}
2525
2526// Tests that Matches(m) works when the matcher takes its argument by
2527// reference.
2528TEST(MatchesTest, WorksOnByRefArguments) {
2529  int m = 0, n = 0;
2530  EXPECT_TRUE(Matches(AllOf(Ref(n), Eq(0)))(n));
2531  EXPECT_FALSE(Matches(Ref(m))(n));
2532}
2533
2534// Tests that a Matcher on non-reference type can be used in
2535// Matches().
2536TEST(MatchesTest, WorksWithMatcherOnNonRefType) {
2537  Matcher<int> eq5 = Eq(5);
2538  EXPECT_TRUE(Matches(eq5)(5));
2539  EXPECT_FALSE(Matches(eq5)(2));
2540}
2541
2542// Tests Value(value, matcher).  Since Value() is a simple wrapper for
2543// Matches(), which has been tested already, we don't spend a lot of
2544// effort on testing Value().
2545TEST(ValueTest, WorksWithPolymorphicMatcher) {
2546  EXPECT_TRUE(Value("hi", StartsWith("h")));
2547  EXPECT_FALSE(Value(5, Gt(10)));
2548}
2549
2550TEST(ValueTest, WorksWithMonomorphicMatcher) {
2551  const Matcher<int> is_zero = Eq(0);
2552  EXPECT_TRUE(Value(0, is_zero));
2553  EXPECT_FALSE(Value('a', is_zero));
2554
2555  int n = 0;
2556  const Matcher<const int&> ref_n = Ref(n);
2557  EXPECT_TRUE(Value(n, ref_n));
2558  EXPECT_FALSE(Value(1, ref_n));
2559}
2560
2561TEST(ExplainMatchResultTest, WorksWithPolymorphicMatcher) {
2562  StringMatchResultListener listener1;
2563  EXPECT_TRUE(ExplainMatchResult(PolymorphicIsEven(), 42, &listener1));
2564  EXPECT_EQ("% 2 == 0", listener1.str());
2565
2566  StringMatchResultListener listener2;
2567  EXPECT_FALSE(ExplainMatchResult(Ge(42), 1.5, &listener2));
2568  EXPECT_EQ("", listener2.str());
2569}
2570
2571TEST(ExplainMatchResultTest, WorksWithMonomorphicMatcher) {
2572  const Matcher<int> is_even = PolymorphicIsEven();
2573  StringMatchResultListener listener1;
2574  EXPECT_TRUE(ExplainMatchResult(is_even, 42, &listener1));
2575  EXPECT_EQ("% 2 == 0", listener1.str());
2576
2577  const Matcher<const double&> is_zero = Eq(0);
2578  StringMatchResultListener listener2;
2579  EXPECT_FALSE(ExplainMatchResult(is_zero, 1.5, &listener2));
2580  EXPECT_EQ("", listener2.str());
2581}
2582
2583MATCHER_P(Really, inner_matcher, "") {
2584  return ExplainMatchResult(inner_matcher, arg, result_listener);
2585}
2586
2587TEST(ExplainMatchResultTest, WorksInsideMATCHER) {
2588  EXPECT_THAT(0, Really(Eq(0)));
2589}
2590
2591TEST(AllArgsTest, WorksForTuple) {
2592  EXPECT_THAT(make_tuple(1, 2L), AllArgs(Lt()));
2593  EXPECT_THAT(make_tuple(2L, 1), Not(AllArgs(Lt())));
2594}
2595
2596TEST(AllArgsTest, WorksForNonTuple) {
2597  EXPECT_THAT(42, AllArgs(Gt(0)));
2598  EXPECT_THAT('a', Not(AllArgs(Eq('b'))));
2599}
2600
2601class AllArgsHelper {
2602 public:
2603  AllArgsHelper() {}
2604
2605  MOCK_METHOD2(Helper, int(char x, int y));
2606
2607 private:
2608  GTEST_DISALLOW_COPY_AND_ASSIGN_(AllArgsHelper);
2609};
2610
2611TEST(AllArgsTest, WorksInWithClause) {
2612  AllArgsHelper helper;
2613  ON_CALL(helper, Helper(_, _))
2614      .With(AllArgs(Lt()))
2615      .WillByDefault(Return(1));
2616  EXPECT_CALL(helper, Helper(_, _));
2617  EXPECT_CALL(helper, Helper(_, _))
2618      .With(AllArgs(Gt()))
2619      .WillOnce(Return(2));
2620
2621  EXPECT_EQ(1, helper.Helper('\1', 2));
2622  EXPECT_EQ(2, helper.Helper('a', 1));
2623}
2624
2625// Tests that ASSERT_THAT() and EXPECT_THAT() work when the value
2626// matches the matcher.
2627TEST(MatcherAssertionTest, WorksWhenMatcherIsSatisfied) {
2628  ASSERT_THAT(5, Ge(2)) << "This should succeed.";
2629  ASSERT_THAT("Foo", EndsWith("oo"));
2630  EXPECT_THAT(2, AllOf(Le(7), Ge(0))) << "This should succeed too.";
2631  EXPECT_THAT("Hello", StartsWith("Hell"));
2632}
2633
2634// Tests that ASSERT_THAT() and EXPECT_THAT() work when the value
2635// doesn't match the matcher.
2636TEST(MatcherAssertionTest, WorksWhenMatcherIsNotSatisfied) {
2637  // 'n' must be static as it is used in an EXPECT_FATAL_FAILURE(),
2638  // which cannot reference auto variables.
2639  static unsigned short n;  // NOLINT
2640  n = 5;
2641
2642  // VC++ prior to version 8.0 SP1 has a bug where it will not see any
2643  // functions declared in the namespace scope from within nested classes.
2644  // EXPECT/ASSERT_(NON)FATAL_FAILURE macros use nested classes so that all
2645  // namespace-level functions invoked inside them need to be explicitly
2646  // resolved.
2647  EXPECT_FATAL_FAILURE(ASSERT_THAT(n, ::testing::Gt(10)),
2648                       "Value of: n\n"
2649                       "Expected: is > 10\n"
2650                       "  Actual: 5" + OfType("unsigned short"));
2651  n = 0;
2652  EXPECT_NONFATAL_FAILURE(
2653      EXPECT_THAT(n, ::testing::AllOf(::testing::Le(7), ::testing::Ge(5))),
2654      "Value of: n\n"
2655      "Expected: (is <= 7) and (is >= 5)\n"
2656      "  Actual: 0" + OfType("unsigned short"));
2657}
2658
2659// Tests that ASSERT_THAT() and EXPECT_THAT() work when the argument
2660// has a reference type.
2661TEST(MatcherAssertionTest, WorksForByRefArguments) {
2662  // We use a static variable here as EXPECT_FATAL_FAILURE() cannot
2663  // reference auto variables.
2664  static int n;
2665  n = 0;
2666  EXPECT_THAT(n, AllOf(Le(7), Ref(n)));
2667  EXPECT_FATAL_FAILURE(ASSERT_THAT(n, ::testing::Not(::testing::Ref(n))),
2668                       "Value of: n\n"
2669                       "Expected: does not reference the variable @");
2670  // Tests the "Actual" part.
2671  EXPECT_FATAL_FAILURE(ASSERT_THAT(n, ::testing::Not(::testing::Ref(n))),
2672                       "Actual: 0" + OfType("int") + ", which is located @");
2673}
2674
2675#if !GTEST_OS_SYMBIAN
2676// Tests that ASSERT_THAT() and EXPECT_THAT() work when the matcher is
2677// monomorphic.
2678
2679// ASSERT_THAT("hello", starts_with_he) fails to compile with Nokia's
2680// Symbian compiler: it tries to compile
2681// template<T, U> class MatcherCastImpl { ...
2682//   virtual bool MatchAndExplain(T x, ...) const {
2683//     return source_matcher_.MatchAndExplain(static_cast<U>(x), ...);
2684// with U == string and T == const char*
2685// With ASSERT_THAT("hello"...) changed to ASSERT_THAT(string("hello") ... )
2686// the compiler silently crashes with no output.
2687// If MatcherCastImpl is changed to use U(x) instead of static_cast<U>(x)
2688// the code compiles but the converted string is bogus.
2689TEST(MatcherAssertionTest, WorksForMonomorphicMatcher) {
2690  Matcher<const char*> starts_with_he = StartsWith("he");
2691  ASSERT_THAT("hello", starts_with_he);
2692
2693  Matcher<const std::string&> ends_with_ok = EndsWith("ok");
2694  ASSERT_THAT("book", ends_with_ok);
2695  const std::string bad = "bad";
2696  EXPECT_NONFATAL_FAILURE(EXPECT_THAT(bad, ends_with_ok),
2697                          "Value of: bad\n"
2698                          "Expected: ends with \"ok\"\n"
2699                          "  Actual: \"bad\"");
2700  Matcher<int> is_greater_than_5 = Gt(5);
2701  EXPECT_NONFATAL_FAILURE(EXPECT_THAT(5, is_greater_than_5),
2702                          "Value of: 5\n"
2703                          "Expected: is > 5\n"
2704                          "  Actual: 5" + OfType("int"));
2705}
2706#endif  // !GTEST_OS_SYMBIAN
2707
2708// Tests floating-point matchers.
2709template <typename RawType>
2710class FloatingPointTest : public testing::Test {
2711 protected:
2712  typedef testing::internal::FloatingPoint<RawType> Floating;
2713  typedef typename Floating::Bits Bits;
2714
2715  FloatingPointTest()
2716      : max_ulps_(Floating::kMaxUlps),
2717        zero_bits_(Floating(0).bits()),
2718        one_bits_(Floating(1).bits()),
2719        infinity_bits_(Floating(Floating::Infinity()).bits()),
2720        close_to_positive_zero_(AsBits(zero_bits_ + max_ulps_/2)),
2721        close_to_negative_zero_(AsBits(zero_bits_ + max_ulps_ - max_ulps_/2)),
2722        further_from_negative_zero_(-AsBits(
2723            zero_bits_ + max_ulps_ + 1 - max_ulps_/2)),
2724        close_to_one_(AsBits(one_bits_ + max_ulps_)),
2725        further_from_one_(AsBits(one_bits_ + max_ulps_ + 1)),
2726        infinity_(Floating::Infinity()),
2727        close_to_infinity_(AsBits(infinity_bits_ - max_ulps_)),
2728        further_from_infinity_(AsBits(infinity_bits_ - max_ulps_ - 1)),
2729        max_(Floating::Max()),
2730        nan1_(AsBits(Floating::kExponentBitMask | 1)),
2731        nan2_(AsBits(Floating::kExponentBitMask | 200)) {
2732  }
2733
2734  void TestSize() {
2735    EXPECT_EQ(sizeof(RawType), sizeof(Bits));
2736  }
2737
2738  // A battery of tests for FloatingEqMatcher::Matches.
2739  // matcher_maker is a pointer to a function which creates a FloatingEqMatcher.
2740  void TestMatches(
2741      testing::internal::FloatingEqMatcher<RawType> (*matcher_maker)(RawType)) {
2742    Matcher<RawType> m1 = matcher_maker(0.0);
2743    EXPECT_TRUE(m1.Matches(-0.0));
2744    EXPECT_TRUE(m1.Matches(close_to_positive_zero_));
2745    EXPECT_TRUE(m1.Matches(close_to_negative_zero_));
2746    EXPECT_FALSE(m1.Matches(1.0));
2747
2748    Matcher<RawType> m2 = matcher_maker(close_to_positive_zero_);
2749    EXPECT_FALSE(m2.Matches(further_from_negative_zero_));
2750
2751    Matcher<RawType> m3 = matcher_maker(1.0);
2752    EXPECT_TRUE(m3.Matches(close_to_one_));
2753    EXPECT_FALSE(m3.Matches(further_from_one_));
2754
2755    // Test commutativity: matcher_maker(0.0).Matches(1.0) was tested above.
2756    EXPECT_FALSE(m3.Matches(0.0));
2757
2758    Matcher<RawType> m4 = matcher_maker(-infinity_);
2759    EXPECT_TRUE(m4.Matches(-close_to_infinity_));
2760
2761    Matcher<RawType> m5 = matcher_maker(infinity_);
2762    EXPECT_TRUE(m5.Matches(close_to_infinity_));
2763
2764    // This is interesting as the representations of infinity_ and nan1_
2765    // are only 1 DLP apart.
2766    EXPECT_FALSE(m5.Matches(nan1_));
2767
2768    // matcher_maker can produce a Matcher<const RawType&>, which is needed in
2769    // some cases.
2770    Matcher<const RawType&> m6 = matcher_maker(0.0);
2771    EXPECT_TRUE(m6.Matches(-0.0));
2772    EXPECT_TRUE(m6.Matches(close_to_positive_zero_));
2773    EXPECT_FALSE(m6.Matches(1.0));
2774
2775    // matcher_maker can produce a Matcher<RawType&>, which is needed in some
2776    // cases.
2777    Matcher<RawType&> m7 = matcher_maker(0.0);
2778    RawType x = 0.0;
2779    EXPECT_TRUE(m7.Matches(x));
2780    x = 0.01f;
2781    EXPECT_FALSE(m7.Matches(x));
2782  }
2783
2784  // Pre-calculated numbers to be used by the tests.
2785
2786  const size_t max_ulps_;
2787
2788  const Bits zero_bits_;  // The bits that represent 0.0.
2789  const Bits one_bits_;  // The bits that represent 1.0.
2790  const Bits infinity_bits_;  // The bits that represent +infinity.
2791
2792  // Some numbers close to 0.0.
2793  const RawType close_to_positive_zero_;
2794  const RawType close_to_negative_zero_;
2795  const RawType further_from_negative_zero_;
2796
2797  // Some numbers close to 1.0.
2798  const RawType close_to_one_;
2799  const RawType further_from_one_;
2800
2801  // Some numbers close to +infinity.
2802  const RawType infinity_;
2803  const RawType close_to_infinity_;
2804  const RawType further_from_infinity_;
2805
2806  // Maximum representable value that's not infinity.
2807  const RawType max_;
2808
2809  // Some NaNs.
2810  const RawType nan1_;
2811  const RawType nan2_;
2812
2813 private:
2814  template <typename T>
2815  static RawType AsBits(T value) {
2816    return Floating::ReinterpretBits(static_cast<Bits>(value));
2817  }
2818};
2819
2820// Tests floating-point matchers with fixed epsilons.
2821template <typename RawType>
2822class FloatingPointNearTest : public FloatingPointTest<RawType> {
2823 protected:
2824  typedef FloatingPointTest<RawType> ParentType;
2825
2826  // A battery of tests for FloatingEqMatcher::Matches with a fixed epsilon.
2827  // matcher_maker is a pointer to a function which creates a FloatingEqMatcher.
2828  void TestNearMatches(
2829      testing::internal::FloatingEqMatcher<RawType>
2830          (*matcher_maker)(RawType, RawType)) {
2831    Matcher<RawType> m1 = matcher_maker(0.0, 0.0);
2832    EXPECT_TRUE(m1.Matches(0.0));
2833    EXPECT_TRUE(m1.Matches(-0.0));
2834    EXPECT_FALSE(m1.Matches(ParentType::close_to_positive_zero_));
2835    EXPECT_FALSE(m1.Matches(ParentType::close_to_negative_zero_));
2836    EXPECT_FALSE(m1.Matches(1.0));
2837
2838    Matcher<RawType> m2 = matcher_maker(0.0, 1.0);
2839    EXPECT_TRUE(m2.Matches(0.0));
2840    EXPECT_TRUE(m2.Matches(-0.0));
2841    EXPECT_TRUE(m2.Matches(1.0));
2842    EXPECT_TRUE(m2.Matches(-1.0));
2843    EXPECT_FALSE(m2.Matches(ParentType::close_to_one_));
2844    EXPECT_FALSE(m2.Matches(-ParentType::close_to_one_));
2845
2846    // Check that inf matches inf, regardless of the of the specified max
2847    // absolute error.
2848    Matcher<RawType> m3 = matcher_maker(ParentType::infinity_, 0.0);
2849    EXPECT_TRUE(m3.Matches(ParentType::infinity_));
2850    EXPECT_FALSE(m3.Matches(ParentType::close_to_infinity_));
2851    EXPECT_FALSE(m3.Matches(-ParentType::infinity_));
2852
2853    Matcher<RawType> m4 = matcher_maker(-ParentType::infinity_, 0.0);
2854    EXPECT_TRUE(m4.Matches(-ParentType::infinity_));
2855    EXPECT_FALSE(m4.Matches(-ParentType::close_to_infinity_));
2856    EXPECT_FALSE(m4.Matches(ParentType::infinity_));
2857
2858    // Test various overflow scenarios.
2859    Matcher<RawType> m5 = matcher_maker(ParentType::max_, ParentType::max_);
2860    EXPECT_TRUE(m5.Matches(ParentType::max_));
2861    EXPECT_FALSE(m5.Matches(-ParentType::max_));
2862
2863    Matcher<RawType> m6 = matcher_maker(-ParentType::max_, ParentType::max_);
2864    EXPECT_FALSE(m6.Matches(ParentType::max_));
2865    EXPECT_TRUE(m6.Matches(-ParentType::max_));
2866
2867    Matcher<RawType> m7 = matcher_maker(ParentType::max_, 0);
2868    EXPECT_TRUE(m7.Matches(ParentType::max_));
2869    EXPECT_FALSE(m7.Matches(-ParentType::max_));
2870
2871    Matcher<RawType> m8 = matcher_maker(-ParentType::max_, 0);
2872    EXPECT_FALSE(m8.Matches(ParentType::max_));
2873    EXPECT_TRUE(m8.Matches(-ParentType::max_));
2874
2875    // The difference between max() and -max() normally overflows to infinity,
2876    // but it should still match if the max_abs_error is also infinity.
2877    Matcher<RawType> m9 = matcher_maker(
2878        ParentType::max_, ParentType::infinity_);
2879    EXPECT_TRUE(m8.Matches(-ParentType::max_));
2880
2881    // matcher_maker can produce a Matcher<const RawType&>, which is needed in
2882    // some cases.
2883    Matcher<const RawType&> m10 = matcher_maker(0.0, 1.0);
2884    EXPECT_TRUE(m10.Matches(-0.0));
2885    EXPECT_TRUE(m10.Matches(ParentType::close_to_positive_zero_));
2886    EXPECT_FALSE(m10.Matches(ParentType::close_to_one_));
2887
2888    // matcher_maker can produce a Matcher<RawType&>, which is needed in some
2889    // cases.
2890    Matcher<RawType&> m11 = matcher_maker(0.0, 1.0);
2891    RawType x = 0.0;
2892    EXPECT_TRUE(m11.Matches(x));
2893    x = 1.0f;
2894    EXPECT_TRUE(m11.Matches(x));
2895    x = -1.0f;
2896    EXPECT_TRUE(m11.Matches(x));
2897    x = 1.1f;
2898    EXPECT_FALSE(m11.Matches(x));
2899    x = -1.1f;
2900    EXPECT_FALSE(m11.Matches(x));
2901  }
2902};
2903
2904// Instantiate FloatingPointTest for testing floats.
2905typedef FloatingPointTest<float> FloatTest;
2906
2907TEST_F(FloatTest, FloatEqApproximatelyMatchesFloats) {
2908  TestMatches(&FloatEq);
2909}
2910
2911TEST_F(FloatTest, NanSensitiveFloatEqApproximatelyMatchesFloats) {
2912  TestMatches(&NanSensitiveFloatEq);
2913}
2914
2915TEST_F(FloatTest, FloatEqCannotMatchNaN) {
2916  // FloatEq never matches NaN.
2917  Matcher<float> m = FloatEq(nan1_);
2918  EXPECT_FALSE(m.Matches(nan1_));
2919  EXPECT_FALSE(m.Matches(nan2_));
2920  EXPECT_FALSE(m.Matches(1.0));
2921}
2922
2923TEST_F(FloatTest, NanSensitiveFloatEqCanMatchNaN) {
2924  // NanSensitiveFloatEq will match NaN.
2925  Matcher<float> m = NanSensitiveFloatEq(nan1_);
2926  EXPECT_TRUE(m.Matches(nan1_));
2927  EXPECT_TRUE(m.Matches(nan2_));
2928  EXPECT_FALSE(m.Matches(1.0));
2929}
2930
2931TEST_F(FloatTest, FloatEqCanDescribeSelf) {
2932  Matcher<float> m1 = FloatEq(2.0f);
2933  EXPECT_EQ("is approximately 2", Describe(m1));
2934  EXPECT_EQ("isn't approximately 2", DescribeNegation(m1));
2935
2936  Matcher<float> m2 = FloatEq(0.5f);
2937  EXPECT_EQ("is approximately 0.5", Describe(m2));
2938  EXPECT_EQ("isn't approximately 0.5", DescribeNegation(m2));
2939
2940  Matcher<float> m3 = FloatEq(nan1_);
2941  EXPECT_EQ("never matches", Describe(m3));
2942  EXPECT_EQ("is anything", DescribeNegation(m3));
2943}
2944
2945TEST_F(FloatTest, NanSensitiveFloatEqCanDescribeSelf) {
2946  Matcher<float> m1 = NanSensitiveFloatEq(2.0f);
2947  EXPECT_EQ("is approximately 2", Describe(m1));
2948  EXPECT_EQ("isn't approximately 2", DescribeNegation(m1));
2949
2950  Matcher<float> m2 = NanSensitiveFloatEq(0.5f);
2951  EXPECT_EQ("is approximately 0.5", Describe(m2));
2952  EXPECT_EQ("isn't approximately 0.5", DescribeNegation(m2));
2953
2954  Matcher<float> m3 = NanSensitiveFloatEq(nan1_);
2955  EXPECT_EQ("is NaN", Describe(m3));
2956  EXPECT_EQ("isn't NaN", DescribeNegation(m3));
2957}
2958
2959// Instantiate FloatingPointTest for testing floats with a user-specified
2960// max absolute error.
2961typedef FloatingPointNearTest<float> FloatNearTest;
2962
2963TEST_F(FloatNearTest, FloatNearMatches) {
2964  TestNearMatches(&FloatNear);
2965}
2966
2967TEST_F(FloatNearTest, NanSensitiveFloatNearApproximatelyMatchesFloats) {
2968  TestNearMatches(&NanSensitiveFloatNear);
2969}
2970
2971TEST_F(FloatNearTest, FloatNearCanDescribeSelf) {
2972  Matcher<float> m1 = FloatNear(2.0f, 0.5f);
2973  EXPECT_EQ("is approximately 2 (absolute error <= 0.5)", Describe(m1));
2974  EXPECT_EQ(
2975      "isn't approximately 2 (absolute error > 0.5)", DescribeNegation(m1));
2976
2977  Matcher<float> m2 = FloatNear(0.5f, 0.5f);
2978  EXPECT_EQ("is approximately 0.5 (absolute error <= 0.5)", Describe(m2));
2979  EXPECT_EQ(
2980      "isn't approximately 0.5 (absolute error > 0.5)", DescribeNegation(m2));
2981
2982  Matcher<float> m3 = FloatNear(nan1_, 0.0);
2983  EXPECT_EQ("never matches", Describe(m3));
2984  EXPECT_EQ("is anything", DescribeNegation(m3));
2985}
2986
2987TEST_F(FloatNearTest, NanSensitiveFloatNearCanDescribeSelf) {
2988  Matcher<float> m1 = NanSensitiveFloatNear(2.0f, 0.5f);
2989  EXPECT_EQ("is approximately 2 (absolute error <= 0.5)", Describe(m1));
2990  EXPECT_EQ(
2991      "isn't approximately 2 (absolute error > 0.5)", DescribeNegation(m1));
2992
2993  Matcher<float> m2 = NanSensitiveFloatNear(0.5f, 0.5f);
2994  EXPECT_EQ("is approximately 0.5 (absolute error <= 0.5)", Describe(m2));
2995  EXPECT_EQ(
2996      "isn't approximately 0.5 (absolute error > 0.5)", DescribeNegation(m2));
2997
2998  Matcher<float> m3 = NanSensitiveFloatNear(nan1_, 0.1f);
2999  EXPECT_EQ("is NaN", Describe(m3));
3000  EXPECT_EQ("isn't NaN", DescribeNegation(m3));
3001}
3002
3003TEST_F(FloatNearTest, FloatNearCannotMatchNaN) {
3004  // FloatNear never matches NaN.
3005  Matcher<float> m = FloatNear(ParentType::nan1_, 0.1f);
3006  EXPECT_FALSE(m.Matches(nan1_));
3007  EXPECT_FALSE(m.Matches(nan2_));
3008  EXPECT_FALSE(m.Matches(1.0));
3009}
3010
3011TEST_F(FloatNearTest, NanSensitiveFloatNearCanMatchNaN) {
3012  // NanSensitiveFloatNear will match NaN.
3013  Matcher<float> m = NanSensitiveFloatNear(nan1_, 0.1f);
3014  EXPECT_TRUE(m.Matches(nan1_));
3015  EXPECT_TRUE(m.Matches(nan2_));
3016  EXPECT_FALSE(m.Matches(1.0));
3017}
3018
3019// Instantiate FloatingPointTest for testing doubles.
3020typedef FloatingPointTest<double> DoubleTest;
3021
3022TEST_F(DoubleTest, DoubleEqApproximatelyMatchesDoubles) {
3023  TestMatches(&DoubleEq);
3024}
3025
3026TEST_F(DoubleTest, NanSensitiveDoubleEqApproximatelyMatchesDoubles) {
3027  TestMatches(&NanSensitiveDoubleEq);
3028}
3029
3030TEST_F(DoubleTest, DoubleEqCannotMatchNaN) {
3031  // DoubleEq never matches NaN.
3032  Matcher<double> m = DoubleEq(nan1_);
3033  EXPECT_FALSE(m.Matches(nan1_));
3034  EXPECT_FALSE(m.Matches(nan2_));
3035  EXPECT_FALSE(m.Matches(1.0));
3036}
3037
3038TEST_F(DoubleTest, NanSensitiveDoubleEqCanMatchNaN) {
3039  // NanSensitiveDoubleEq will match NaN.
3040  Matcher<double> m = NanSensitiveDoubleEq(nan1_);
3041  EXPECT_TRUE(m.Matches(nan1_));
3042  EXPECT_TRUE(m.Matches(nan2_));
3043  EXPECT_FALSE(m.Matches(1.0));
3044}
3045
3046TEST_F(DoubleTest, DoubleEqCanDescribeSelf) {
3047  Matcher<double> m1 = DoubleEq(2.0);
3048  EXPECT_EQ("is approximately 2", Describe(m1));
3049  EXPECT_EQ("isn't approximately 2", DescribeNegation(m1));
3050
3051  Matcher<double> m2 = DoubleEq(0.5);
3052  EXPECT_EQ("is approximately 0.5", Describe(m2));
3053  EXPECT_EQ("isn't approximately 0.5", DescribeNegation(m2));
3054
3055  Matcher<double> m3 = DoubleEq(nan1_);
3056  EXPECT_EQ("never matches", Describe(m3));
3057  EXPECT_EQ("is anything", DescribeNegation(m3));
3058}
3059
3060TEST_F(DoubleTest, NanSensitiveDoubleEqCanDescribeSelf) {
3061  Matcher<double> m1 = NanSensitiveDoubleEq(2.0);
3062  EXPECT_EQ("is approximately 2", Describe(m1));
3063  EXPECT_EQ("isn't approximately 2", DescribeNegation(m1));
3064
3065  Matcher<double> m2 = NanSensitiveDoubleEq(0.5);
3066  EXPECT_EQ("is approximately 0.5", Describe(m2));
3067  EXPECT_EQ("isn't approximately 0.5", DescribeNegation(m2));
3068
3069  Matcher<double> m3 = NanSensitiveDoubleEq(nan1_);
3070  EXPECT_EQ("is NaN", Describe(m3));
3071  EXPECT_EQ("isn't NaN", DescribeNegation(m3));
3072}
3073
3074// Instantiate FloatingPointTest for testing floats with a user-specified
3075// max absolute error.
3076typedef FloatingPointNearTest<double> DoubleNearTest;
3077
3078TEST_F(DoubleNearTest, DoubleNearMatches) {
3079  TestNearMatches(&DoubleNear);
3080}
3081
3082TEST_F(DoubleNearTest, NanSensitiveDoubleNearApproximatelyMatchesDoubles) {
3083  TestNearMatches(&NanSensitiveDoubleNear);
3084}
3085
3086TEST_F(DoubleNearTest, DoubleNearCanDescribeSelf) {
3087  Matcher<double> m1 = DoubleNear(2.0, 0.5);
3088  EXPECT_EQ("is approximately 2 (absolute error <= 0.5)", Describe(m1));
3089  EXPECT_EQ(
3090      "isn't approximately 2 (absolute error > 0.5)", DescribeNegation(m1));
3091
3092  Matcher<double> m2 = DoubleNear(0.5, 0.5);
3093  EXPECT_EQ("is approximately 0.5 (absolute error <= 0.5)", Describe(m2));
3094  EXPECT_EQ(
3095      "isn't approximately 0.5 (absolute error > 0.5)", DescribeNegation(m2));
3096
3097  Matcher<double> m3 = DoubleNear(nan1_, 0.0);
3098  EXPECT_EQ("never matches", Describe(m3));
3099  EXPECT_EQ("is anything", DescribeNegation(m3));
3100}
3101
3102TEST_F(DoubleNearTest, ExplainsResultWhenMatchFails) {
3103  EXPECT_EQ("", Explain(DoubleNear(2.0, 0.1), 2.05));
3104  EXPECT_EQ("which is 0.2 from 2", Explain(DoubleNear(2.0, 0.1), 2.2));
3105  EXPECT_EQ("which is -0.3 from 2", Explain(DoubleNear(2.0, 0.1), 1.7));
3106
3107  const std::string explanation =
3108      Explain(DoubleNear(2.1, 1e-10), 2.1 + 1.2e-10);
3109  // Different C++ implementations may print floating-point numbers
3110  // slightly differently.
3111  EXPECT_TRUE(explanation == "which is 1.2e-10 from 2.1" ||  // GCC
3112              explanation == "which is 1.2e-010 from 2.1")   // MSVC
3113      << " where explanation is \"" << explanation << "\".";
3114}
3115
3116TEST_F(DoubleNearTest, NanSensitiveDoubleNearCanDescribeSelf) {
3117  Matcher<double> m1 = NanSensitiveDoubleNear(2.0, 0.5);
3118  EXPECT_EQ("is approximately 2 (absolute error <= 0.5)", Describe(m1));
3119  EXPECT_EQ(
3120      "isn't approximately 2 (absolute error > 0.5)", DescribeNegation(m1));
3121
3122  Matcher<double> m2 = NanSensitiveDoubleNear(0.5, 0.5);
3123  EXPECT_EQ("is approximately 0.5 (absolute error <= 0.5)", Describe(m2));
3124  EXPECT_EQ(
3125      "isn't approximately 0.5 (absolute error > 0.5)", DescribeNegation(m2));
3126
3127  Matcher<double> m3 = NanSensitiveDoubleNear(nan1_, 0.1);
3128  EXPECT_EQ("is NaN", Describe(m3));
3129  EXPECT_EQ("isn't NaN", DescribeNegation(m3));
3130}
3131
3132TEST_F(DoubleNearTest, DoubleNearCannotMatchNaN) {
3133  // DoubleNear never matches NaN.
3134  Matcher<double> m = DoubleNear(ParentType::nan1_, 0.1);
3135  EXPECT_FALSE(m.Matches(nan1_));
3136  EXPECT_FALSE(m.Matches(nan2_));
3137  EXPECT_FALSE(m.Matches(1.0));
3138}
3139
3140TEST_F(DoubleNearTest, NanSensitiveDoubleNearCanMatchNaN) {
3141  // NanSensitiveDoubleNear will match NaN.
3142  Matcher<double> m = NanSensitiveDoubleNear(nan1_, 0.1);
3143  EXPECT_TRUE(m.Matches(nan1_));
3144  EXPECT_TRUE(m.Matches(nan2_));
3145  EXPECT_FALSE(m.Matches(1.0));
3146}
3147
3148TEST(PointeeTest, RawPointer) {
3149  const Matcher<int*> m = Pointee(Ge(0));
3150
3151  int n = 1;
3152  EXPECT_TRUE(m.Matches(&n));
3153  n = -1;
3154  EXPECT_FALSE(m.Matches(&n));
3155  EXPECT_FALSE(m.Matches(NULL));
3156}
3157
3158TEST(PointeeTest, RawPointerToConst) {
3159  const Matcher<const double*> m = Pointee(Ge(0));
3160
3161  double x = 1;
3162  EXPECT_TRUE(m.Matches(&x));
3163  x = -1;
3164  EXPECT_FALSE(m.Matches(&x));
3165  EXPECT_FALSE(m.Matches(NULL));
3166}
3167
3168TEST(PointeeTest, ReferenceToConstRawPointer) {
3169  const Matcher<int* const &> m = Pointee(Ge(0));
3170
3171  int n = 1;
3172  EXPECT_TRUE(m.Matches(&n));
3173  n = -1;
3174  EXPECT_FALSE(m.Matches(&n));
3175  EXPECT_FALSE(m.Matches(NULL));
3176}
3177
3178TEST(PointeeTest, ReferenceToNonConstRawPointer) {
3179  const Matcher<double* &> m = Pointee(Ge(0));
3180
3181  double x = 1.0;
3182  double* p = &x;
3183  EXPECT_TRUE(m.Matches(p));
3184  x = -1;
3185  EXPECT_FALSE(m.Matches(p));
3186  p = NULL;
3187  EXPECT_FALSE(m.Matches(p));
3188}
3189
3190MATCHER_P(FieldIIs, inner_matcher, "") {
3191  return ExplainMatchResult(inner_matcher, arg.i, result_listener);
3192}
3193
3194#if GTEST_HAS_RTTI
3195
3196TEST(WhenDynamicCastToTest, SameType) {
3197  Derived derived;
3198  derived.i = 4;
3199
3200  // Right type. A pointer is passed down.
3201  Base* as_base_ptr = &derived;
3202  EXPECT_THAT(as_base_ptr, WhenDynamicCastTo<Derived*>(Not(IsNull())));
3203  EXPECT_THAT(as_base_ptr, WhenDynamicCastTo<Derived*>(Pointee(FieldIIs(4))));
3204  EXPECT_THAT(as_base_ptr,
3205              Not(WhenDynamicCastTo<Derived*>(Pointee(FieldIIs(5)))));
3206}
3207
3208TEST(WhenDynamicCastToTest, WrongTypes) {
3209  Base base;
3210  Derived derived;
3211  OtherDerived other_derived;
3212
3213  // Wrong types. NULL is passed.
3214  EXPECT_THAT(&base, Not(WhenDynamicCastTo<Derived*>(Pointee(_))));
3215  EXPECT_THAT(&base, WhenDynamicCastTo<Derived*>(IsNull()));
3216  Base* as_base_ptr = &derived;
3217  EXPECT_THAT(as_base_ptr, Not(WhenDynamicCastTo<OtherDerived*>(Pointee(_))));
3218  EXPECT_THAT(as_base_ptr, WhenDynamicCastTo<OtherDerived*>(IsNull()));
3219  as_base_ptr = &other_derived;
3220  EXPECT_THAT(as_base_ptr, Not(WhenDynamicCastTo<Derived*>(Pointee(_))));
3221  EXPECT_THAT(as_base_ptr, WhenDynamicCastTo<Derived*>(IsNull()));
3222}
3223
3224TEST(WhenDynamicCastToTest, AlreadyNull) {
3225  // Already NULL.
3226  Base* as_base_ptr = NULL;
3227  EXPECT_THAT(as_base_ptr, WhenDynamicCastTo<Derived*>(IsNull()));
3228}
3229
3230struct AmbiguousCastTypes {
3231  class VirtualDerived : public virtual Base {};
3232  class DerivedSub1 : public VirtualDerived {};
3233  class DerivedSub2 : public VirtualDerived {};
3234  class ManyDerivedInHierarchy : public DerivedSub1, public DerivedSub2 {};
3235};
3236
3237TEST(WhenDynamicCastToTest, AmbiguousCast) {
3238  AmbiguousCastTypes::DerivedSub1 sub1;
3239  AmbiguousCastTypes::ManyDerivedInHierarchy many_derived;
3240  // Multiply derived from Base. dynamic_cast<> returns NULL.
3241  Base* as_base_ptr =
3242      static_cast<AmbiguousCastTypes::DerivedSub1*>(&many_derived);
3243  EXPECT_THAT(as_base_ptr,
3244              WhenDynamicCastTo<AmbiguousCastTypes::VirtualDerived*>(IsNull()));
3245  as_base_ptr = &sub1;
3246  EXPECT_THAT(
3247      as_base_ptr,
3248      WhenDynamicCastTo<AmbiguousCastTypes::VirtualDerived*>(Not(IsNull())));
3249}
3250
3251TEST(WhenDynamicCastToTest, Describe) {
3252  Matcher<Base*> matcher = WhenDynamicCastTo<Derived*>(Pointee(_));
3253  const string prefix =
3254      "when dynamic_cast to " + internal::GetTypeName<Derived*>() + ", ";
3255  EXPECT_EQ(prefix + "points to a value that is anything", Describe(matcher));
3256  EXPECT_EQ(prefix + "does not point to a value that is anything",
3257            DescribeNegation(matcher));
3258}
3259
3260TEST(WhenDynamicCastToTest, Explain) {
3261  Matcher<Base*> matcher = WhenDynamicCastTo<Derived*>(Pointee(_));
3262  Base* null = NULL;
3263  EXPECT_THAT(Explain(matcher, null), HasSubstr("NULL"));
3264  Derived derived;
3265  EXPECT_TRUE(matcher.Matches(&derived));
3266  EXPECT_THAT(Explain(matcher, &derived), HasSubstr("which points to "));
3267
3268  // With references, the matcher itself can fail. Test for that one.
3269  Matcher<const Base&> ref_matcher = WhenDynamicCastTo<const OtherDerived&>(_);
3270  EXPECT_THAT(Explain(ref_matcher, derived),
3271              HasSubstr("which cannot be dynamic_cast"));
3272}
3273
3274TEST(WhenDynamicCastToTest, GoodReference) {
3275  Derived derived;
3276  derived.i = 4;
3277  Base& as_base_ref = derived;
3278  EXPECT_THAT(as_base_ref, WhenDynamicCastTo<const Derived&>(FieldIIs(4)));
3279  EXPECT_THAT(as_base_ref, WhenDynamicCastTo<const Derived&>(Not(FieldIIs(5))));
3280}
3281
3282TEST(WhenDynamicCastToTest, BadReference) {
3283  Derived derived;
3284  Base& as_base_ref = derived;
3285  EXPECT_THAT(as_base_ref, Not(WhenDynamicCastTo<const OtherDerived&>(_)));
3286}
3287
3288#endif  // GTEST_HAS_RTTI
3289
3290// Minimal const-propagating pointer.
3291template <typename T>
3292class ConstPropagatingPtr {
3293 public:
3294  typedef T element_type;
3295
3296  ConstPropagatingPtr() : val_() {}
3297  explicit ConstPropagatingPtr(T* t) : val_(t) {}
3298  ConstPropagatingPtr(const ConstPropagatingPtr& other) : val_(other.val_) {}
3299
3300  T* get() { return val_; }
3301  T& operator*() { return *val_; }
3302  // Most smart pointers return non-const T* and T& from the next methods.
3303  const T* get() const { return val_; }
3304  const T& operator*() const { return *val_; }
3305
3306 private:
3307  T* val_;
3308};
3309
3310TEST(PointeeTest, WorksWithConstPropagatingPointers) {
3311  const Matcher< ConstPropagatingPtr<int> > m = Pointee(Lt(5));
3312  int three = 3;
3313  const ConstPropagatingPtr<int> co(&three);
3314  ConstPropagatingPtr<int> o(&three);
3315  EXPECT_TRUE(m.Matches(o));
3316  EXPECT_TRUE(m.Matches(co));
3317  *o = 6;
3318  EXPECT_FALSE(m.Matches(o));
3319  EXPECT_FALSE(m.Matches(ConstPropagatingPtr<int>()));
3320}
3321
3322TEST(PointeeTest, NeverMatchesNull) {
3323  const Matcher<const char*> m = Pointee(_);
3324  EXPECT_FALSE(m.Matches(NULL));
3325}
3326
3327// Tests that we can write Pointee(value) instead of Pointee(Eq(value)).
3328TEST(PointeeTest, MatchesAgainstAValue) {
3329  const Matcher<int*> m = Pointee(5);
3330
3331  int n = 5;
3332  EXPECT_TRUE(m.Matches(&n));
3333  n = -1;
3334  EXPECT_FALSE(m.Matches(&n));
3335  EXPECT_FALSE(m.Matches(NULL));
3336}
3337
3338TEST(PointeeTest, CanDescribeSelf) {
3339  const Matcher<int*> m = Pointee(Gt(3));
3340  EXPECT_EQ("points to a value that is > 3", Describe(m));
3341  EXPECT_EQ("does not point to a value that is > 3",
3342            DescribeNegation(m));
3343}
3344
3345TEST(PointeeTest, CanExplainMatchResult) {
3346  const Matcher<const std::string*> m = Pointee(StartsWith("Hi"));
3347
3348  EXPECT_EQ("", Explain(m, static_cast<const std::string*>(NULL)));
3349
3350  const Matcher<long*> m2 = Pointee(GreaterThan(1));  // NOLINT
3351  long n = 3;  // NOLINT
3352  EXPECT_EQ("which points to 3" + OfType("long") + ", which is 2 more than 1",
3353            Explain(m2, &n));
3354}
3355
3356TEST(PointeeTest, AlwaysExplainsPointee) {
3357  const Matcher<int*> m = Pointee(0);
3358  int n = 42;
3359  EXPECT_EQ("which points to 42" + OfType("int"), Explain(m, &n));
3360}
3361
3362// An uncopyable class.
3363class Uncopyable {
3364 public:
3365  Uncopyable() : value_(-1) {}
3366  explicit Uncopyable(int a_value) : value_(a_value) {}
3367
3368  int value() const { return value_; }
3369  void set_value(int i) { value_ = i; }
3370
3371 private:
3372  int value_;
3373  GTEST_DISALLOW_COPY_AND_ASSIGN_(Uncopyable);
3374};
3375
3376// Returns true iff x.value() is positive.
3377bool ValueIsPositive(const Uncopyable& x) { return x.value() > 0; }
3378
3379MATCHER_P(UncopyableIs, inner_matcher, "") {
3380  return ExplainMatchResult(inner_matcher, arg.value(), result_listener);
3381}
3382
3383// A user-defined struct for testing Field().
3384struct AStruct {
3385  AStruct() : x(0), y(1.0), z(5), p(NULL) {}
3386  AStruct(const AStruct& rhs)
3387      : x(rhs.x), y(rhs.y), z(rhs.z.value()), p(rhs.p) {}
3388
3389  int x;           // A non-const field.
3390  const double y;  // A const field.
3391  Uncopyable z;    // An uncopyable field.
3392  const char* p;   // A pointer field.
3393
3394 private:
3395  GTEST_DISALLOW_ASSIGN_(AStruct);
3396};
3397
3398// A derived struct for testing Field().
3399struct DerivedStruct : public AStruct {
3400  char ch;
3401
3402 private:
3403  GTEST_DISALLOW_ASSIGN_(DerivedStruct);
3404};
3405
3406// Tests that Field(&Foo::field, ...) works when field is non-const.
3407TEST(FieldTest, WorksForNonConstField) {
3408  Matcher<AStruct> m = Field(&AStruct::x, Ge(0));
3409
3410  AStruct a;
3411  EXPECT_TRUE(m.Matches(a));
3412  a.x = -1;
3413  EXPECT_FALSE(m.Matches(a));
3414}
3415
3416// Tests that Field(&Foo::field, ...) works when field is const.
3417TEST(FieldTest, WorksForConstField) {
3418  AStruct a;
3419
3420  Matcher<AStruct> m = Field(&AStruct::y, Ge(0.0));
3421  EXPECT_TRUE(m.Matches(a));
3422  m = Field(&AStruct::y, Le(0.0));
3423  EXPECT_FALSE(m.Matches(a));
3424}
3425
3426// Tests that Field(&Foo::field, ...) works when field is not copyable.
3427TEST(FieldTest, WorksForUncopyableField) {
3428  AStruct a;
3429
3430  Matcher<AStruct> m = Field(&AStruct::z, Truly(ValueIsPositive));
3431  EXPECT_TRUE(m.Matches(a));
3432  m = Field(&AStruct::z, Not(Truly(ValueIsPositive)));
3433  EXPECT_FALSE(m.Matches(a));
3434}
3435
3436// Tests that Field(&Foo::field, ...) works when field is a pointer.
3437TEST(FieldTest, WorksForPointerField) {
3438  // Matching against NULL.
3439  Matcher<AStruct> m = Field(&AStruct::p, static_cast<const char*>(NULL));
3440  AStruct a;
3441  EXPECT_TRUE(m.Matches(a));
3442  a.p = "hi";
3443  EXPECT_FALSE(m.Matches(a));
3444
3445  // Matching a pointer that is not NULL.
3446  m = Field(&AStruct::p, StartsWith("hi"));
3447  a.p = "hill";
3448  EXPECT_TRUE(m.Matches(a));
3449  a.p = "hole";
3450  EXPECT_FALSE(m.Matches(a));
3451}
3452
3453// Tests that Field() works when the object is passed by reference.
3454TEST(FieldTest, WorksForByRefArgument) {
3455  Matcher<const AStruct&> m = Field(&AStruct::x, Ge(0));
3456
3457  AStruct a;
3458  EXPECT_TRUE(m.Matches(a));
3459  a.x = -1;
3460  EXPECT_FALSE(m.Matches(a));
3461}
3462
3463// Tests that Field(&Foo::field, ...) works when the argument's type
3464// is a sub-type of Foo.
3465TEST(FieldTest, WorksForArgumentOfSubType) {
3466  // Note that the matcher expects DerivedStruct but we say AStruct
3467  // inside Field().
3468  Matcher<const DerivedStruct&> m = Field(&AStruct::x, Ge(0));
3469
3470  DerivedStruct d;
3471  EXPECT_TRUE(m.Matches(d));
3472  d.x = -1;
3473  EXPECT_FALSE(m.Matches(d));
3474}
3475
3476// Tests that Field(&Foo::field, m) works when field's type and m's
3477// argument type are compatible but not the same.
3478TEST(FieldTest, WorksForCompatibleMatcherType) {
3479  // The field is an int, but the inner matcher expects a signed char.
3480  Matcher<const AStruct&> m = Field(&AStruct::x,
3481                                    Matcher<signed char>(Ge(0)));
3482
3483  AStruct a;
3484  EXPECT_TRUE(m.Matches(a));
3485  a.x = -1;
3486  EXPECT_FALSE(m.Matches(a));
3487}
3488
3489// Tests that Field() can describe itself.
3490TEST(FieldTest, CanDescribeSelf) {
3491  Matcher<const AStruct&> m = Field(&AStruct::x, Ge(0));
3492
3493  EXPECT_EQ("is an object whose given field is >= 0", Describe(m));
3494  EXPECT_EQ("is an object whose given field isn't >= 0", DescribeNegation(m));
3495}
3496
3497// Tests that Field() can explain the match result.
3498TEST(FieldTest, CanExplainMatchResult) {
3499  Matcher<const AStruct&> m = Field(&AStruct::x, Ge(0));
3500
3501  AStruct a;
3502  a.x = 1;
3503  EXPECT_EQ("whose given field is 1" + OfType("int"), Explain(m, a));
3504
3505  m = Field(&AStruct::x, GreaterThan(0));
3506  EXPECT_EQ(
3507      "whose given field is 1" + OfType("int") + ", which is 1 more than 0",
3508      Explain(m, a));
3509}
3510
3511// Tests that Field() works when the argument is a pointer to const.
3512TEST(FieldForPointerTest, WorksForPointerToConst) {
3513  Matcher<const AStruct*> m = Field(&AStruct::x, Ge(0));
3514
3515  AStruct a;
3516  EXPECT_TRUE(m.Matches(&a));
3517  a.x = -1;
3518  EXPECT_FALSE(m.Matches(&a));
3519}
3520
3521// Tests that Field() works when the argument is a pointer to non-const.
3522TEST(FieldForPointerTest, WorksForPointerToNonConst) {
3523  Matcher<AStruct*> m = Field(&AStruct::x, Ge(0));
3524
3525  AStruct a;
3526  EXPECT_TRUE(m.Matches(&a));
3527  a.x = -1;
3528  EXPECT_FALSE(m.Matches(&a));
3529}
3530
3531// Tests that Field() works when the argument is a reference to a const pointer.
3532TEST(FieldForPointerTest, WorksForReferenceToConstPointer) {
3533  Matcher<AStruct* const&> m = Field(&AStruct::x, Ge(0));
3534
3535  AStruct a;
3536  EXPECT_TRUE(m.Matches(&a));
3537  a.x = -1;
3538  EXPECT_FALSE(m.Matches(&a));
3539}
3540
3541// Tests that Field() does not match the NULL pointer.
3542TEST(FieldForPointerTest, DoesNotMatchNull) {
3543  Matcher<const AStruct*> m = Field(&AStruct::x, _);
3544  EXPECT_FALSE(m.Matches(NULL));
3545}
3546
3547// Tests that Field(&Foo::field, ...) works when the argument's type
3548// is a sub-type of const Foo*.
3549TEST(FieldForPointerTest, WorksForArgumentOfSubType) {
3550  // Note that the matcher expects DerivedStruct but we say AStruct
3551  // inside Field().
3552  Matcher<DerivedStruct*> m = Field(&AStruct::x, Ge(0));
3553
3554  DerivedStruct d;
3555  EXPECT_TRUE(m.Matches(&d));
3556  d.x = -1;
3557  EXPECT_FALSE(m.Matches(&d));
3558}
3559
3560// Tests that Field() can describe itself when used to match a pointer.
3561TEST(FieldForPointerTest, CanDescribeSelf) {
3562  Matcher<const AStruct*> m = Field(&AStruct::x, Ge(0));
3563
3564  EXPECT_EQ("is an object whose given field is >= 0", Describe(m));
3565  EXPECT_EQ("is an object whose given field isn't >= 0", DescribeNegation(m));
3566}
3567
3568// Tests that Field() can explain the result of matching a pointer.
3569TEST(FieldForPointerTest, CanExplainMatchResult) {
3570  Matcher<const AStruct*> m = Field(&AStruct::x, Ge(0));
3571
3572  AStruct a;
3573  a.x = 1;
3574  EXPECT_EQ("", Explain(m, static_cast<const AStruct*>(NULL)));
3575  EXPECT_EQ("which points to an object whose given field is 1" + OfType("int"),
3576            Explain(m, &a));
3577
3578  m = Field(&AStruct::x, GreaterThan(0));
3579  EXPECT_EQ("which points to an object whose given field is 1" + OfType("int") +
3580            ", which is 1 more than 0", Explain(m, &a));
3581}
3582
3583// A user-defined class for testing Property().
3584class AClass {
3585 public:
3586  AClass() : n_(0) {}
3587
3588  // A getter that returns a non-reference.
3589  int n() const { return n_; }
3590
3591  void set_n(int new_n) { n_ = new_n; }
3592
3593  // A getter that returns a reference to const.
3594  const std::string& s() const { return s_; }
3595
3596#if GTEST_LANG_CXX11
3597  const std::string& s_ref() const & { return s_; }
3598#endif
3599
3600  void set_s(const std::string& new_s) { s_ = new_s; }
3601
3602  // A getter that returns a reference to non-const.
3603  double& x() const { return x_; }
3604
3605 private:
3606  int n_;
3607  std::string s_;
3608
3609  static double x_;
3610};
3611
3612double AClass::x_ = 0.0;
3613
3614// A derived class for testing Property().
3615class DerivedClass : public AClass {
3616 public:
3617  int k() const { return k_; }
3618 private:
3619  int k_;
3620};
3621
3622// Tests that Property(&Foo::property, ...) works when property()
3623// returns a non-reference.
3624TEST(PropertyTest, WorksForNonReferenceProperty) {
3625  Matcher<const AClass&> m = Property(&AClass::n, Ge(0));
3626
3627  AClass a;
3628  a.set_n(1);
3629  EXPECT_TRUE(m.Matches(a));
3630
3631  a.set_n(-1);
3632  EXPECT_FALSE(m.Matches(a));
3633}
3634
3635// Tests that Property(&Foo::property, ...) works when property()
3636// returns a reference to const.
3637TEST(PropertyTest, WorksForReferenceToConstProperty) {
3638  Matcher<const AClass&> m = Property(&AClass::s, StartsWith("hi"));
3639
3640  AClass a;
3641  a.set_s("hill");
3642  EXPECT_TRUE(m.Matches(a));
3643
3644  a.set_s("hole");
3645  EXPECT_FALSE(m.Matches(a));
3646}
3647
3648#if GTEST_LANG_CXX11
3649// Tests that Property(&Foo::property, ...) works when property() is
3650// ref-qualified.
3651TEST(PropertyTest, WorksForRefQualifiedProperty) {
3652  Matcher<const AClass&> m = Property(&AClass::s_ref, StartsWith("hi"));
3653
3654  AClass a;
3655  a.set_s("hill");
3656  EXPECT_TRUE(m.Matches(a));
3657
3658  a.set_s("hole");
3659  EXPECT_FALSE(m.Matches(a));
3660}
3661#endif
3662
3663// Tests that Property(&Foo::property, ...) works when property()
3664// returns a reference to non-const.
3665TEST(PropertyTest, WorksForReferenceToNonConstProperty) {
3666  double x = 0.0;
3667  AClass a;
3668
3669  Matcher<const AClass&> m = Property(&AClass::x, Ref(x));
3670  EXPECT_FALSE(m.Matches(a));
3671
3672  m = Property(&AClass::x, Not(Ref(x)));
3673  EXPECT_TRUE(m.Matches(a));
3674}
3675
3676// Tests that Property(&Foo::property, ...) works when the argument is
3677// passed by value.
3678TEST(PropertyTest, WorksForByValueArgument) {
3679  Matcher<AClass> m = Property(&AClass::s, StartsWith("hi"));
3680
3681  AClass a;
3682  a.set_s("hill");
3683  EXPECT_TRUE(m.Matches(a));
3684
3685  a.set_s("hole");
3686  EXPECT_FALSE(m.Matches(a));
3687}
3688
3689// Tests that Property(&Foo::property, ...) works when the argument's
3690// type is a sub-type of Foo.
3691TEST(PropertyTest, WorksForArgumentOfSubType) {
3692  // The matcher expects a DerivedClass, but inside the Property() we
3693  // say AClass.
3694  Matcher<const DerivedClass&> m = Property(&AClass::n, Ge(0));
3695
3696  DerivedClass d;
3697  d.set_n(1);
3698  EXPECT_TRUE(m.Matches(d));
3699
3700  d.set_n(-1);
3701  EXPECT_FALSE(m.Matches(d));
3702}
3703
3704// Tests that Property(&Foo::property, m) works when property()'s type
3705// and m's argument type are compatible but different.
3706TEST(PropertyTest, WorksForCompatibleMatcherType) {
3707  // n() returns an int but the inner matcher expects a signed char.
3708  Matcher<const AClass&> m = Property(&AClass::n,
3709                                      Matcher<signed char>(Ge(0)));
3710
3711  AClass a;
3712  EXPECT_TRUE(m.Matches(a));
3713  a.set_n(-1);
3714  EXPECT_FALSE(m.Matches(a));
3715}
3716
3717// Tests that Property() can describe itself.
3718TEST(PropertyTest, CanDescribeSelf) {
3719  Matcher<const AClass&> m = Property(&AClass::n, Ge(0));
3720
3721  EXPECT_EQ("is an object whose given property is >= 0", Describe(m));
3722  EXPECT_EQ("is an object whose given property isn't >= 0",
3723            DescribeNegation(m));
3724}
3725
3726// Tests that Property() can explain the match result.
3727TEST(PropertyTest, CanExplainMatchResult) {
3728  Matcher<const AClass&> m = Property(&AClass::n, Ge(0));
3729
3730  AClass a;
3731  a.set_n(1);
3732  EXPECT_EQ("whose given property is 1" + OfType("int"), Explain(m, a));
3733
3734  m = Property(&AClass::n, GreaterThan(0));
3735  EXPECT_EQ(
3736      "whose given property is 1" + OfType("int") + ", which is 1 more than 0",
3737      Explain(m, a));
3738}
3739
3740// Tests that Property() works when the argument is a pointer to const.
3741TEST(PropertyForPointerTest, WorksForPointerToConst) {
3742  Matcher<const AClass*> m = Property(&AClass::n, Ge(0));
3743
3744  AClass a;
3745  a.set_n(1);
3746  EXPECT_TRUE(m.Matches(&a));
3747
3748  a.set_n(-1);
3749  EXPECT_FALSE(m.Matches(&a));
3750}
3751
3752// Tests that Property() works when the argument is a pointer to non-const.
3753TEST(PropertyForPointerTest, WorksForPointerToNonConst) {
3754  Matcher<AClass*> m = Property(&AClass::s, StartsWith("hi"));
3755
3756  AClass a;
3757  a.set_s("hill");
3758  EXPECT_TRUE(m.Matches(&a));
3759
3760  a.set_s("hole");
3761  EXPECT_FALSE(m.Matches(&a));
3762}
3763
3764// Tests that Property() works when the argument is a reference to a
3765// const pointer.
3766TEST(PropertyForPointerTest, WorksForReferenceToConstPointer) {
3767  Matcher<AClass* const&> m = Property(&AClass::s, StartsWith("hi"));
3768
3769  AClass a;
3770  a.set_s("hill");
3771  EXPECT_TRUE(m.Matches(&a));
3772
3773  a.set_s("hole");
3774  EXPECT_FALSE(m.Matches(&a));
3775}
3776
3777// Tests that Property() does not match the NULL pointer.
3778TEST(PropertyForPointerTest, WorksForReferenceToNonConstProperty) {
3779  Matcher<const AClass*> m = Property(&AClass::x, _);
3780  EXPECT_FALSE(m.Matches(NULL));
3781}
3782
3783// Tests that Property(&Foo::property, ...) works when the argument's
3784// type is a sub-type of const Foo*.
3785TEST(PropertyForPointerTest, WorksForArgumentOfSubType) {
3786  // The matcher expects a DerivedClass, but inside the Property() we
3787  // say AClass.
3788  Matcher<const DerivedClass*> m = Property(&AClass::n, Ge(0));
3789
3790  DerivedClass d;
3791  d.set_n(1);
3792  EXPECT_TRUE(m.Matches(&d));
3793
3794  d.set_n(-1);
3795  EXPECT_FALSE(m.Matches(&d));
3796}
3797
3798// Tests that Property() can describe itself when used to match a pointer.
3799TEST(PropertyForPointerTest, CanDescribeSelf) {
3800  Matcher<const AClass*> m = Property(&AClass::n, Ge(0));
3801
3802  EXPECT_EQ("is an object whose given property is >= 0", Describe(m));
3803  EXPECT_EQ("is an object whose given property isn't >= 0",
3804            DescribeNegation(m));
3805}
3806
3807// Tests that Property() can explain the result of matching a pointer.
3808TEST(PropertyForPointerTest, CanExplainMatchResult) {
3809  Matcher<const AClass*> m = Property(&AClass::n, Ge(0));
3810
3811  AClass a;
3812  a.set_n(1);
3813  EXPECT_EQ("", Explain(m, static_cast<const AClass*>(NULL)));
3814  EXPECT_EQ(
3815      "which points to an object whose given property is 1" + OfType("int"),
3816      Explain(m, &a));
3817
3818  m = Property(&AClass::n, GreaterThan(0));
3819  EXPECT_EQ("which points to an object whose given property is 1" +
3820            OfType("int") + ", which is 1 more than 0",
3821            Explain(m, &a));
3822}
3823
3824// Tests ResultOf.
3825
3826// Tests that ResultOf(f, ...) compiles and works as expected when f is a
3827// function pointer.
3828std::string IntToStringFunction(int input) {
3829  return input == 1 ? "foo" : "bar";
3830}
3831
3832TEST(ResultOfTest, WorksForFunctionPointers) {
3833  Matcher<int> matcher = ResultOf(&IntToStringFunction, Eq(std::string("foo")));
3834
3835  EXPECT_TRUE(matcher.Matches(1));
3836  EXPECT_FALSE(matcher.Matches(2));
3837}
3838
3839// Tests that ResultOf() can describe itself.
3840TEST(ResultOfTest, CanDescribeItself) {
3841  Matcher<int> matcher = ResultOf(&IntToStringFunction, StrEq("foo"));
3842
3843  EXPECT_EQ("is mapped by the given callable to a value that "
3844            "is equal to \"foo\"", Describe(matcher));
3845  EXPECT_EQ("is mapped by the given callable to a value that "
3846            "isn't equal to \"foo\"", DescribeNegation(matcher));
3847}
3848
3849// Tests that ResultOf() can explain the match result.
3850int IntFunction(int input) { return input == 42 ? 80 : 90; }
3851
3852TEST(ResultOfTest, CanExplainMatchResult) {
3853  Matcher<int> matcher = ResultOf(&IntFunction, Ge(85));
3854  EXPECT_EQ("which is mapped by the given callable to 90" + OfType("int"),
3855            Explain(matcher, 36));
3856
3857  matcher = ResultOf(&IntFunction, GreaterThan(85));
3858  EXPECT_EQ("which is mapped by the given callable to 90" + OfType("int") +
3859            ", which is 5 more than 85", Explain(matcher, 36));
3860}
3861
3862// Tests that ResultOf(f, ...) compiles and works as expected when f(x)
3863// returns a non-reference.
3864TEST(ResultOfTest, WorksForNonReferenceResults) {
3865  Matcher<int> matcher = ResultOf(&IntFunction, Eq(80));
3866
3867  EXPECT_TRUE(matcher.Matches(42));
3868  EXPECT_FALSE(matcher.Matches(36));
3869}
3870
3871// Tests that ResultOf(f, ...) compiles and works as expected when f(x)
3872// returns a reference to non-const.
3873double& DoubleFunction(double& input) { return input; }  // NOLINT
3874
3875Uncopyable& RefUncopyableFunction(Uncopyable& obj) {  // NOLINT
3876  return obj;
3877}
3878
3879TEST(ResultOfTest, WorksForReferenceToNonConstResults) {
3880  double x = 3.14;
3881  double x2 = x;
3882  Matcher<double&> matcher = ResultOf(&DoubleFunction, Ref(x));
3883
3884  EXPECT_TRUE(matcher.Matches(x));
3885  EXPECT_FALSE(matcher.Matches(x2));
3886
3887  // Test that ResultOf works with uncopyable objects
3888  Uncopyable obj(0);
3889  Uncopyable obj2(0);
3890  Matcher<Uncopyable&> matcher2 =
3891      ResultOf(&RefUncopyableFunction, Ref(obj));
3892
3893  EXPECT_TRUE(matcher2.Matches(obj));
3894  EXPECT_FALSE(matcher2.Matches(obj2));
3895}
3896
3897// Tests that ResultOf(f, ...) compiles and works as expected when f(x)
3898// returns a reference to const.
3899const std::string& StringFunction(const std::string& input) { return input; }
3900
3901TEST(ResultOfTest, WorksForReferenceToConstResults) {
3902  std::string s = "foo";
3903  std::string s2 = s;
3904  Matcher<const std::string&> matcher = ResultOf(&StringFunction, Ref(s));
3905
3906  EXPECT_TRUE(matcher.Matches(s));
3907  EXPECT_FALSE(matcher.Matches(s2));
3908}
3909
3910// Tests that ResultOf(f, m) works when f(x) and m's
3911// argument types are compatible but different.
3912TEST(ResultOfTest, WorksForCompatibleMatcherTypes) {
3913  // IntFunction() returns int but the inner matcher expects a signed char.
3914  Matcher<int> matcher = ResultOf(IntFunction, Matcher<signed char>(Ge(85)));
3915
3916  EXPECT_TRUE(matcher.Matches(36));
3917  EXPECT_FALSE(matcher.Matches(42));
3918}
3919
3920// Tests that the program aborts when ResultOf is passed
3921// a NULL function pointer.
3922TEST(ResultOfDeathTest, DiesOnNullFunctionPointers) {
3923  EXPECT_DEATH_IF_SUPPORTED(
3924      ResultOf(static_cast<std::string (*)(int dummy)>(NULL),
3925               Eq(std::string("foo"))),
3926      "NULL function pointer is passed into ResultOf\\(\\)\\.");
3927}
3928
3929// Tests that ResultOf(f, ...) compiles and works as expected when f is a
3930// function reference.
3931TEST(ResultOfTest, WorksForFunctionReferences) {
3932  Matcher<int> matcher = ResultOf(IntToStringFunction, StrEq("foo"));
3933  EXPECT_TRUE(matcher.Matches(1));
3934  EXPECT_FALSE(matcher.Matches(2));
3935}
3936
3937// Tests that ResultOf(f, ...) compiles and works as expected when f is a
3938// function object.
3939struct Functor {
3940  typedef std::string result_type;
3941  typedef int argument_type;
3942
3943  std::string operator()(int input) const {
3944    return IntToStringFunction(input);
3945  }
3946};
3947
3948TEST(ResultOfTest, WorksForFunctors) {
3949  Matcher<int> matcher = ResultOf(Functor(), Eq(std::string("foo")));
3950
3951  EXPECT_TRUE(matcher.Matches(1));
3952  EXPECT_FALSE(matcher.Matches(2));
3953}
3954
3955// Tests that ResultOf(f, ...) compiles and works as expected when f is a
3956// functor with more then one operator() defined. ResultOf() must work
3957// for each defined operator().
3958struct PolymorphicFunctor {
3959  typedef int result_type;
3960  int operator()(int n) { return n; }
3961  int operator()(const char* s) { return static_cast<int>(strlen(s)); }
3962};
3963
3964TEST(ResultOfTest, WorksForPolymorphicFunctors) {
3965  Matcher<int> matcher_int = ResultOf(PolymorphicFunctor(), Ge(5));
3966
3967  EXPECT_TRUE(matcher_int.Matches(10));
3968  EXPECT_FALSE(matcher_int.Matches(2));
3969
3970  Matcher<const char*> matcher_string = ResultOf(PolymorphicFunctor(), Ge(5));
3971
3972  EXPECT_TRUE(matcher_string.Matches("long string"));
3973  EXPECT_FALSE(matcher_string.Matches("shrt"));
3974}
3975
3976const int* ReferencingFunction(const int& n) { return &n; }
3977
3978struct ReferencingFunctor {
3979  typedef const int* result_type;
3980  result_type operator()(const int& n) { return &n; }
3981};
3982
3983TEST(ResultOfTest, WorksForReferencingCallables) {
3984  const int n = 1;
3985  const int n2 = 1;
3986  Matcher<const int&> matcher2 = ResultOf(ReferencingFunction, Eq(&n));
3987  EXPECT_TRUE(matcher2.Matches(n));
3988  EXPECT_FALSE(matcher2.Matches(n2));
3989
3990  Matcher<const int&> matcher3 = ResultOf(ReferencingFunctor(), Eq(&n));
3991  EXPECT_TRUE(matcher3.Matches(n));
3992  EXPECT_FALSE(matcher3.Matches(n2));
3993}
3994
3995class DivisibleByImpl {
3996 public:
3997  explicit DivisibleByImpl(int a_divider) : divider_(a_divider) {}
3998
3999  // For testing using ExplainMatchResultTo() with polymorphic matchers.
4000  template <typename T>
4001  bool MatchAndExplain(const T& n, MatchResultListener* listener) const {
4002    *listener << "which is " << (n % divider_) << " modulo "
4003              << divider_;
4004    return (n % divider_) == 0;
4005  }
4006
4007  void DescribeTo(ostream* os) const {
4008    *os << "is divisible by " << divider_;
4009  }
4010
4011  void DescribeNegationTo(ostream* os) const {
4012    *os << "is not divisible by " << divider_;
4013  }
4014
4015  void set_divider(int a_divider) { divider_ = a_divider; }
4016  int divider() const { return divider_; }
4017
4018 private:
4019  int divider_;
4020};
4021
4022PolymorphicMatcher<DivisibleByImpl> DivisibleBy(int n) {
4023  return MakePolymorphicMatcher(DivisibleByImpl(n));
4024}
4025
4026// Tests that when AllOf() fails, only the first failing matcher is
4027// asked to explain why.
4028TEST(ExplainMatchResultTest, AllOf_False_False) {
4029  const Matcher<int> m = AllOf(DivisibleBy(4), DivisibleBy(3));
4030  EXPECT_EQ("which is 1 modulo 4", Explain(m, 5));
4031}
4032
4033// Tests that when AllOf() fails, only the first failing matcher is
4034// asked to explain why.
4035TEST(ExplainMatchResultTest, AllOf_False_True) {
4036  const Matcher<int> m = AllOf(DivisibleBy(4), DivisibleBy(3));
4037  EXPECT_EQ("which is 2 modulo 4", Explain(m, 6));
4038}
4039
4040// Tests that when AllOf() fails, only the first failing matcher is
4041// asked to explain why.
4042TEST(ExplainMatchResultTest, AllOf_True_False) {
4043  const Matcher<int> m = AllOf(Ge(1), DivisibleBy(3));
4044  EXPECT_EQ("which is 2 modulo 3", Explain(m, 5));
4045}
4046
4047// Tests that when AllOf() succeeds, all matchers are asked to explain
4048// why.
4049TEST(ExplainMatchResultTest, AllOf_True_True) {
4050  const Matcher<int> m = AllOf(DivisibleBy(2), DivisibleBy(3));
4051  EXPECT_EQ("which is 0 modulo 2, and which is 0 modulo 3", Explain(m, 6));
4052}
4053
4054TEST(ExplainMatchResultTest, AllOf_True_True_2) {
4055  const Matcher<int> m = AllOf(Ge(2), Le(3));
4056  EXPECT_EQ("", Explain(m, 2));
4057}
4058
4059TEST(ExplainmatcherResultTest, MonomorphicMatcher) {
4060  const Matcher<int> m = GreaterThan(5);
4061  EXPECT_EQ("which is 1 more than 5", Explain(m, 6));
4062}
4063
4064// The following two tests verify that values without a public copy
4065// ctor can be used as arguments to matchers like Eq(), Ge(), and etc
4066// with the help of ByRef().
4067
4068class NotCopyable {
4069 public:
4070  explicit NotCopyable(int a_value) : value_(a_value) {}
4071
4072  int value() const { return value_; }
4073
4074  bool operator==(const NotCopyable& rhs) const {
4075    return value() == rhs.value();
4076  }
4077
4078  bool operator>=(const NotCopyable& rhs) const {
4079    return value() >= rhs.value();
4080  }
4081 private:
4082  int value_;
4083
4084  GTEST_DISALLOW_COPY_AND_ASSIGN_(NotCopyable);
4085};
4086
4087TEST(ByRefTest, AllowsNotCopyableConstValueInMatchers) {
4088  const NotCopyable const_value1(1);
4089  const Matcher<const NotCopyable&> m = Eq(ByRef(const_value1));
4090
4091  const NotCopyable n1(1), n2(2);
4092  EXPECT_TRUE(m.Matches(n1));
4093  EXPECT_FALSE(m.Matches(n2));
4094}
4095
4096TEST(ByRefTest, AllowsNotCopyableValueInMatchers) {
4097  NotCopyable value2(2);
4098  const Matcher<NotCopyable&> m = Ge(ByRef(value2));
4099
4100  NotCopyable n1(1), n2(2);
4101  EXPECT_FALSE(m.Matches(n1));
4102  EXPECT_TRUE(m.Matches(n2));
4103}
4104
4105TEST(IsEmptyTest, ImplementsIsEmpty) {
4106  vector<int> container;
4107  EXPECT_THAT(container, IsEmpty());
4108  container.push_back(0);
4109  EXPECT_THAT(container, Not(IsEmpty()));
4110  container.push_back(1);
4111  EXPECT_THAT(container, Not(IsEmpty()));
4112}
4113
4114TEST(IsEmptyTest, WorksWithString) {
4115  std::string text;
4116  EXPECT_THAT(text, IsEmpty());
4117  text = "foo";
4118  EXPECT_THAT(text, Not(IsEmpty()));
4119  text = std::string("\0", 1);
4120  EXPECT_THAT(text, Not(IsEmpty()));
4121}
4122
4123TEST(IsEmptyTest, CanDescribeSelf) {
4124  Matcher<vector<int> > m = IsEmpty();
4125  EXPECT_EQ("is empty", Describe(m));
4126  EXPECT_EQ("isn't empty", DescribeNegation(m));
4127}
4128
4129TEST(IsEmptyTest, ExplainsResult) {
4130  Matcher<vector<int> > m = IsEmpty();
4131  vector<int> container;
4132  EXPECT_EQ("", Explain(m, container));
4133  container.push_back(0);
4134  EXPECT_EQ("whose size is 1", Explain(m, container));
4135}
4136
4137TEST(SizeIsTest, ImplementsSizeIs) {
4138  vector<int> container;
4139  EXPECT_THAT(container, SizeIs(0));
4140  EXPECT_THAT(container, Not(SizeIs(1)));
4141  container.push_back(0);
4142  EXPECT_THAT(container, Not(SizeIs(0)));
4143  EXPECT_THAT(container, SizeIs(1));
4144  container.push_back(0);
4145  EXPECT_THAT(container, Not(SizeIs(0)));
4146  EXPECT_THAT(container, SizeIs(2));
4147}
4148
4149TEST(SizeIsTest, WorksWithMap) {
4150  map<std::string, int> container;
4151  EXPECT_THAT(container, SizeIs(0));
4152  EXPECT_THAT(container, Not(SizeIs(1)));
4153  container.insert(make_pair("foo", 1));
4154  EXPECT_THAT(container, Not(SizeIs(0)));
4155  EXPECT_THAT(container, SizeIs(1));
4156  container.insert(make_pair("bar", 2));
4157  EXPECT_THAT(container, Not(SizeIs(0)));
4158  EXPECT_THAT(container, SizeIs(2));
4159}
4160
4161TEST(SizeIsTest, WorksWithReferences) {
4162  vector<int> container;
4163  Matcher<const vector<int>&> m = SizeIs(1);
4164  EXPECT_THAT(container, Not(m));
4165  container.push_back(0);
4166  EXPECT_THAT(container, m);
4167}
4168
4169TEST(SizeIsTest, CanDescribeSelf) {
4170  Matcher<vector<int> > m = SizeIs(2);
4171  EXPECT_EQ("size is equal to 2", Describe(m));
4172  EXPECT_EQ("size isn't equal to 2", DescribeNegation(m));
4173}
4174
4175TEST(SizeIsTest, ExplainsResult) {
4176  Matcher<vector<int> > m1 = SizeIs(2);
4177  Matcher<vector<int> > m2 = SizeIs(Lt(2u));
4178  Matcher<vector<int> > m3 = SizeIs(AnyOf(0, 3));
4179  Matcher<vector<int> > m4 = SizeIs(GreaterThan(1));
4180  vector<int> container;
4181  EXPECT_EQ("whose size 0 doesn't match", Explain(m1, container));
4182  EXPECT_EQ("whose size 0 matches", Explain(m2, container));
4183  EXPECT_EQ("whose size 0 matches", Explain(m3, container));
4184  EXPECT_EQ("whose size 0 doesn't match, which is 1 less than 1",
4185            Explain(m4, container));
4186  container.push_back(0);
4187  container.push_back(0);
4188  EXPECT_EQ("whose size 2 matches", Explain(m1, container));
4189  EXPECT_EQ("whose size 2 doesn't match", Explain(m2, container));
4190  EXPECT_EQ("whose size 2 doesn't match", Explain(m3, container));
4191  EXPECT_EQ("whose size 2 matches, which is 1 more than 1",
4192            Explain(m4, container));
4193}
4194
4195#if GTEST_HAS_TYPED_TEST
4196// Tests ContainerEq with different container types, and
4197// different element types.
4198
4199template <typename T>
4200class ContainerEqTest : public testing::Test {};
4201
4202typedef testing::Types<
4203    set<int>,
4204    vector<size_t>,
4205    multiset<size_t>,
4206    list<int> >
4207    ContainerEqTestTypes;
4208
4209TYPED_TEST_CASE(ContainerEqTest, ContainerEqTestTypes);
4210
4211// Tests that the filled container is equal to itself.
4212TYPED_TEST(ContainerEqTest, EqualsSelf) {
4213  static const int vals[] = {1, 1, 2, 3, 5, 8};
4214  TypeParam my_set(vals, vals + 6);
4215  const Matcher<TypeParam> m = ContainerEq(my_set);
4216  EXPECT_TRUE(m.Matches(my_set));
4217  EXPECT_EQ("", Explain(m, my_set));
4218}
4219
4220// Tests that missing values are reported.
4221TYPED_TEST(ContainerEqTest, ValueMissing) {
4222  static const int vals[] = {1, 1, 2, 3, 5, 8};
4223  static const int test_vals[] = {2, 1, 8, 5};
4224  TypeParam my_set(vals, vals + 6);
4225  TypeParam test_set(test_vals, test_vals + 4);
4226  const Matcher<TypeParam> m = ContainerEq(my_set);
4227  EXPECT_FALSE(m.Matches(test_set));
4228  EXPECT_EQ("which doesn't have these expected elements: 3",
4229            Explain(m, test_set));
4230}
4231
4232// Tests that added values are reported.
4233TYPED_TEST(ContainerEqTest, ValueAdded) {
4234  static const int vals[] = {1, 1, 2, 3, 5, 8};
4235  static const int test_vals[] = {1, 2, 3, 5, 8, 46};
4236  TypeParam my_set(vals, vals + 6);
4237  TypeParam test_set(test_vals, test_vals + 6);
4238  const Matcher<const TypeParam&> m = ContainerEq(my_set);
4239  EXPECT_FALSE(m.Matches(test_set));
4240  EXPECT_EQ("which has these unexpected elements: 46", Explain(m, test_set));
4241}
4242
4243// Tests that added and missing values are reported together.
4244TYPED_TEST(ContainerEqTest, ValueAddedAndRemoved) {
4245  static const int vals[] = {1, 1, 2, 3, 5, 8};
4246  static const int test_vals[] = {1, 2, 3, 8, 46};
4247  TypeParam my_set(vals, vals + 6);
4248  TypeParam test_set(test_vals, test_vals + 5);
4249  const Matcher<TypeParam> m = ContainerEq(my_set);
4250  EXPECT_FALSE(m.Matches(test_set));
4251  EXPECT_EQ("which has these unexpected elements: 46,\n"
4252            "and doesn't have these expected elements: 5",
4253            Explain(m, test_set));
4254}
4255
4256// Tests duplicated value -- expect no explanation.
4257TYPED_TEST(ContainerEqTest, DuplicateDifference) {
4258  static const int vals[] = {1, 1, 2, 3, 5, 8};
4259  static const int test_vals[] = {1, 2, 3, 5, 8};
4260  TypeParam my_set(vals, vals + 6);
4261  TypeParam test_set(test_vals, test_vals + 5);
4262  const Matcher<const TypeParam&> m = ContainerEq(my_set);
4263  // Depending on the container, match may be true or false
4264  // But in any case there should be no explanation.
4265  EXPECT_EQ("", Explain(m, test_set));
4266}
4267#endif  // GTEST_HAS_TYPED_TEST
4268
4269// Tests that mutliple missing values are reported.
4270// Using just vector here, so order is predicatble.
4271TEST(ContainerEqExtraTest, MultipleValuesMissing) {
4272  static const int vals[] = {1, 1, 2, 3, 5, 8};
4273  static const int test_vals[] = {2, 1, 5};
4274  vector<int> my_set(vals, vals + 6);
4275  vector<int> test_set(test_vals, test_vals + 3);
4276  const Matcher<vector<int> > m = ContainerEq(my_set);
4277  EXPECT_FALSE(m.Matches(test_set));
4278  EXPECT_EQ("which doesn't have these expected elements: 3, 8",
4279            Explain(m, test_set));
4280}
4281
4282// Tests that added values are reported.
4283// Using just vector here, so order is predicatble.
4284TEST(ContainerEqExtraTest, MultipleValuesAdded) {
4285  static const int vals[] = {1, 1, 2, 3, 5, 8};
4286  static const int test_vals[] = {1, 2, 92, 3, 5, 8, 46};
4287  list<size_t> my_set(vals, vals + 6);
4288  list<size_t> test_set(test_vals, test_vals + 7);
4289  const Matcher<const list<size_t>&> m = ContainerEq(my_set);
4290  EXPECT_FALSE(m.Matches(test_set));
4291  EXPECT_EQ("which has these unexpected elements: 92, 46",
4292            Explain(m, test_set));
4293}
4294
4295// Tests that added and missing values are reported together.
4296TEST(ContainerEqExtraTest, MultipleValuesAddedAndRemoved) {
4297  static const int vals[] = {1, 1, 2, 3, 5, 8};
4298  static const int test_vals[] = {1, 2, 3, 92, 46};
4299  list<size_t> my_set(vals, vals + 6);
4300  list<size_t> test_set(test_vals, test_vals + 5);
4301  const Matcher<const list<size_t> > m = ContainerEq(my_set);
4302  EXPECT_FALSE(m.Matches(test_set));
4303  EXPECT_EQ("which has these unexpected elements: 92, 46,\n"
4304            "and doesn't have these expected elements: 5, 8",
4305            Explain(m, test_set));
4306}
4307
4308// Tests to see that duplicate elements are detected,
4309// but (as above) not reported in the explanation.
4310TEST(ContainerEqExtraTest, MultiSetOfIntDuplicateDifference) {
4311  static const int vals[] = {1, 1, 2, 3, 5, 8};
4312  static const int test_vals[] = {1, 2, 3, 5, 8};
4313  vector<int> my_set(vals, vals + 6);
4314  vector<int> test_set(test_vals, test_vals + 5);
4315  const Matcher<vector<int> > m = ContainerEq(my_set);
4316  EXPECT_TRUE(m.Matches(my_set));
4317  EXPECT_FALSE(m.Matches(test_set));
4318  // There is nothing to report when both sets contain all the same values.
4319  EXPECT_EQ("", Explain(m, test_set));
4320}
4321
4322// Tests that ContainerEq works for non-trivial associative containers,
4323// like maps.
4324TEST(ContainerEqExtraTest, WorksForMaps) {
4325  map<int, std::string> my_map;
4326  my_map[0] = "a";
4327  my_map[1] = "b";
4328
4329  map<int, std::string> test_map;
4330  test_map[0] = "aa";
4331  test_map[1] = "b";
4332
4333  const Matcher<const map<int, std::string>&> m = ContainerEq(my_map);
4334  EXPECT_TRUE(m.Matches(my_map));
4335  EXPECT_FALSE(m.Matches(test_map));
4336
4337  EXPECT_EQ("which has these unexpected elements: (0, \"aa\"),\n"
4338            "and doesn't have these expected elements: (0, \"a\")",
4339            Explain(m, test_map));
4340}
4341
4342TEST(ContainerEqExtraTest, WorksForNativeArray) {
4343  int a1[] = {1, 2, 3};
4344  int a2[] = {1, 2, 3};
4345  int b[] = {1, 2, 4};
4346
4347  EXPECT_THAT(a1, ContainerEq(a2));
4348  EXPECT_THAT(a1, Not(ContainerEq(b)));
4349}
4350
4351TEST(ContainerEqExtraTest, WorksForTwoDimensionalNativeArray) {
4352  const char a1[][3] = {"hi", "lo"};
4353  const char a2[][3] = {"hi", "lo"};
4354  const char b[][3] = {"lo", "hi"};
4355
4356  // Tests using ContainerEq() in the first dimension.
4357  EXPECT_THAT(a1, ContainerEq(a2));
4358  EXPECT_THAT(a1, Not(ContainerEq(b)));
4359
4360  // Tests using ContainerEq() in the second dimension.
4361  EXPECT_THAT(a1, ElementsAre(ContainerEq(a2[0]), ContainerEq(a2[1])));
4362  EXPECT_THAT(a1, ElementsAre(Not(ContainerEq(b[0])), ContainerEq(a2[1])));
4363}
4364
4365TEST(ContainerEqExtraTest, WorksForNativeArrayAsTuple) {
4366  const int a1[] = {1, 2, 3};
4367  const int a2[] = {1, 2, 3};
4368  const int b[] = {1, 2, 3, 4};
4369
4370  const int* const p1 = a1;
4371  EXPECT_THAT(make_tuple(p1, 3), ContainerEq(a2));
4372  EXPECT_THAT(make_tuple(p1, 3), Not(ContainerEq(b)));
4373
4374  const int c[] = {1, 3, 2};
4375  EXPECT_THAT(make_tuple(p1, 3), Not(ContainerEq(c)));
4376}
4377
4378TEST(ContainerEqExtraTest, CopiesNativeArrayParameter) {
4379  std::string a1[][3] = {
4380    {"hi", "hello", "ciao"},
4381    {"bye", "see you", "ciao"}
4382  };
4383
4384  std::string a2[][3] = {
4385    {"hi", "hello", "ciao"},
4386    {"bye", "see you", "ciao"}
4387  };
4388
4389  const Matcher<const std::string(&)[2][3]> m = ContainerEq(a2);
4390  EXPECT_THAT(a1, m);
4391
4392  a2[0][0] = "ha";
4393  EXPECT_THAT(a1, m);
4394}
4395
4396TEST(WhenSortedByTest, WorksForEmptyContainer) {
4397  const vector<int> numbers;
4398  EXPECT_THAT(numbers, WhenSortedBy(less<int>(), ElementsAre()));
4399  EXPECT_THAT(numbers, Not(WhenSortedBy(less<int>(), ElementsAre(1))));
4400}
4401
4402TEST(WhenSortedByTest, WorksForNonEmptyContainer) {
4403  vector<unsigned> numbers;
4404  numbers.push_back(3);
4405  numbers.push_back(1);
4406  numbers.push_back(2);
4407  numbers.push_back(2);
4408  EXPECT_THAT(numbers, WhenSortedBy(greater<unsigned>(),
4409                                    ElementsAre(3, 2, 2, 1)));
4410  EXPECT_THAT(numbers, Not(WhenSortedBy(greater<unsigned>(),
4411                                        ElementsAre(1, 2, 2, 3))));
4412}
4413
4414TEST(WhenSortedByTest, WorksForNonVectorContainer) {
4415  list<std::string> words;
4416  words.push_back("say");
4417  words.push_back("hello");
4418  words.push_back("world");
4419  EXPECT_THAT(words, WhenSortedBy(less<std::string>(),
4420                                  ElementsAre("hello", "say", "world")));
4421  EXPECT_THAT(words, Not(WhenSortedBy(less<std::string>(),
4422                                      ElementsAre("say", "hello", "world"))));
4423}
4424
4425TEST(WhenSortedByTest, WorksForNativeArray) {
4426  const int numbers[] = {1, 3, 2, 4};
4427  const int sorted_numbers[] = {1, 2, 3, 4};
4428  EXPECT_THAT(numbers, WhenSortedBy(less<int>(), ElementsAre(1, 2, 3, 4)));
4429  EXPECT_THAT(numbers, WhenSortedBy(less<int>(),
4430                                    ElementsAreArray(sorted_numbers)));
4431  EXPECT_THAT(numbers, Not(WhenSortedBy(less<int>(), ElementsAre(1, 3, 2, 4))));
4432}
4433
4434TEST(WhenSortedByTest, CanDescribeSelf) {
4435  const Matcher<vector<int> > m = WhenSortedBy(less<int>(), ElementsAre(1, 2));
4436  EXPECT_EQ("(when sorted) has 2 elements where\n"
4437            "element #0 is equal to 1,\n"
4438            "element #1 is equal to 2",
4439            Describe(m));
4440  EXPECT_EQ("(when sorted) doesn't have 2 elements, or\n"
4441            "element #0 isn't equal to 1, or\n"
4442            "element #1 isn't equal to 2",
4443            DescribeNegation(m));
4444}
4445
4446TEST(WhenSortedByTest, ExplainsMatchResult) {
4447  const int a[] = {2, 1};
4448  EXPECT_EQ("which is { 1, 2 } when sorted, whose element #0 doesn't match",
4449            Explain(WhenSortedBy(less<int>(), ElementsAre(2, 3)), a));
4450  EXPECT_EQ("which is { 1, 2 } when sorted",
4451            Explain(WhenSortedBy(less<int>(), ElementsAre(1, 2)), a));
4452}
4453
4454// WhenSorted() is a simple wrapper on WhenSortedBy().  Hence we don't
4455// need to test it as exhaustively as we test the latter.
4456
4457TEST(WhenSortedTest, WorksForEmptyContainer) {
4458  const vector<int> numbers;
4459  EXPECT_THAT(numbers, WhenSorted(ElementsAre()));
4460  EXPECT_THAT(numbers, Not(WhenSorted(ElementsAre(1))));
4461}
4462
4463TEST(WhenSortedTest, WorksForNonEmptyContainer) {
4464  list<std::string> words;
4465  words.push_back("3");
4466  words.push_back("1");
4467  words.push_back("2");
4468  words.push_back("2");
4469  EXPECT_THAT(words, WhenSorted(ElementsAre("1", "2", "2", "3")));
4470  EXPECT_THAT(words, Not(WhenSorted(ElementsAre("3", "1", "2", "2"))));
4471}
4472
4473TEST(WhenSortedTest, WorksForMapTypes) {
4474  map<std::string, int> word_counts;
4475  word_counts["and"] = 1;
4476  word_counts["the"] = 1;
4477  word_counts["buffalo"] = 2;
4478  EXPECT_THAT(word_counts,
4479              WhenSorted(ElementsAre(Pair("and", 1), Pair("buffalo", 2),
4480                                     Pair("the", 1))));
4481  EXPECT_THAT(word_counts,
4482              Not(WhenSorted(ElementsAre(Pair("and", 1), Pair("the", 1),
4483                                         Pair("buffalo", 2)))));
4484}
4485
4486TEST(WhenSortedTest, WorksForMultiMapTypes) {
4487    multimap<int, int> ifib;
4488    ifib.insert(make_pair(8, 6));
4489    ifib.insert(make_pair(2, 3));
4490    ifib.insert(make_pair(1, 1));
4491    ifib.insert(make_pair(3, 4));
4492    ifib.insert(make_pair(1, 2));
4493    ifib.insert(make_pair(5, 5));
4494    EXPECT_THAT(ifib, WhenSorted(ElementsAre(Pair(1, 1),
4495                                             Pair(1, 2),
4496                                             Pair(2, 3),
4497                                             Pair(3, 4),
4498                                             Pair(5, 5),
4499                                             Pair(8, 6))));
4500    EXPECT_THAT(ifib, Not(WhenSorted(ElementsAre(Pair(8, 6),
4501                                                 Pair(2, 3),
4502                                                 Pair(1, 1),
4503                                                 Pair(3, 4),
4504                                                 Pair(1, 2),
4505                                                 Pair(5, 5)))));
4506}
4507
4508TEST(WhenSortedTest, WorksForPolymorphicMatcher) {
4509    std::deque<int> d;
4510    d.push_back(2);
4511    d.push_back(1);
4512    EXPECT_THAT(d, WhenSorted(ElementsAre(1, 2)));
4513    EXPECT_THAT(d, Not(WhenSorted(ElementsAre(2, 1))));
4514}
4515
4516TEST(WhenSortedTest, WorksForVectorConstRefMatcher) {
4517    std::deque<int> d;
4518    d.push_back(2);
4519    d.push_back(1);
4520    Matcher<const std::vector<int>&> vector_match = ElementsAre(1, 2);
4521    EXPECT_THAT(d, WhenSorted(vector_match));
4522    Matcher<const std::vector<int>&> not_vector_match = ElementsAre(2, 1);
4523    EXPECT_THAT(d, Not(WhenSorted(not_vector_match)));
4524}
4525
4526// Deliberately bare pseudo-container.
4527// Offers only begin() and end() accessors, yielding InputIterator.
4528template <typename T>
4529class Streamlike {
4530 private:
4531  class ConstIter;
4532 public:
4533  typedef ConstIter const_iterator;
4534  typedef T value_type;
4535
4536  template <typename InIter>
4537  Streamlike(InIter first, InIter last) : remainder_(first, last) {}
4538
4539  const_iterator begin() const {
4540    return const_iterator(this, remainder_.begin());
4541  }
4542  const_iterator end() const {
4543    return const_iterator(this, remainder_.end());
4544  }
4545
4546 private:
4547  class ConstIter : public std::iterator<std::input_iterator_tag,
4548                                         value_type,
4549                                         ptrdiff_t,
4550                                         const value_type*,
4551                                         const value_type&> {
4552   public:
4553    ConstIter(const Streamlike* s,
4554              typename std::list<value_type>::iterator pos)
4555        : s_(s), pos_(pos) {}
4556
4557    const value_type& operator*() const { return *pos_; }
4558    const value_type* operator->() const { return &*pos_; }
4559    ConstIter& operator++() {
4560      s_->remainder_.erase(pos_++);
4561      return *this;
4562    }
4563
4564    // *iter++ is required to work (see std::istreambuf_iterator).
4565    // (void)iter++ is also required to work.
4566    class PostIncrProxy {
4567     public:
4568      explicit PostIncrProxy(const value_type& value) : value_(value) {}
4569      value_type operator*() const { return value_; }
4570     private:
4571      value_type value_;
4572    };
4573    PostIncrProxy operator++(int) {
4574      PostIncrProxy proxy(**this);
4575      ++(*this);
4576      return proxy;
4577    }
4578
4579    friend bool operator==(const ConstIter& a, const ConstIter& b) {
4580      return a.s_ == b.s_ && a.pos_ == b.pos_;
4581    }
4582    friend bool operator!=(const ConstIter& a, const ConstIter& b) {
4583      return !(a == b);
4584    }
4585
4586   private:
4587    const Streamlike* s_;
4588    typename std::list<value_type>::iterator pos_;
4589  };
4590
4591  friend std::ostream& operator<<(std::ostream& os, const Streamlike& s) {
4592    os << "[";
4593    typedef typename std::list<value_type>::const_iterator Iter;
4594    const char* sep = "";
4595    for (Iter it = s.remainder_.begin(); it != s.remainder_.end(); ++it) {
4596      os << sep << *it;
4597      sep = ",";
4598    }
4599    os << "]";
4600    return os;
4601  }
4602
4603  mutable std::list<value_type> remainder_;  // modified by iteration
4604};
4605
4606TEST(StreamlikeTest, Iteration) {
4607  const int a[5] = {2, 1, 4, 5, 3};
4608  Streamlike<int> s(a, a + 5);
4609  Streamlike<int>::const_iterator it = s.begin();
4610  const int* ip = a;
4611  while (it != s.end()) {
4612    SCOPED_TRACE(ip - a);
4613    EXPECT_EQ(*ip++, *it++);
4614  }
4615}
4616
4617#if GTEST_HAS_STD_FORWARD_LIST_
4618TEST(BeginEndDistanceIsTest, WorksWithForwardList) {
4619  std::forward_list<int> container;
4620  EXPECT_THAT(container, BeginEndDistanceIs(0));
4621  EXPECT_THAT(container, Not(BeginEndDistanceIs(1)));
4622  container.push_front(0);
4623  EXPECT_THAT(container, Not(BeginEndDistanceIs(0)));
4624  EXPECT_THAT(container, BeginEndDistanceIs(1));
4625  container.push_front(0);
4626  EXPECT_THAT(container, Not(BeginEndDistanceIs(0)));
4627  EXPECT_THAT(container, BeginEndDistanceIs(2));
4628}
4629#endif  // GTEST_HAS_STD_FORWARD_LIST_
4630
4631TEST(BeginEndDistanceIsTest, WorksWithNonStdList) {
4632  const int a[5] = {1, 2, 3, 4, 5};
4633  Streamlike<int> s(a, a + 5);
4634  EXPECT_THAT(s, BeginEndDistanceIs(5));
4635}
4636
4637TEST(BeginEndDistanceIsTest, CanDescribeSelf) {
4638  Matcher<vector<int> > m = BeginEndDistanceIs(2);
4639  EXPECT_EQ("distance between begin() and end() is equal to 2", Describe(m));
4640  EXPECT_EQ("distance between begin() and end() isn't equal to 2",
4641            DescribeNegation(m));
4642}
4643
4644TEST(BeginEndDistanceIsTest, ExplainsResult) {
4645  Matcher<vector<int> > m1 = BeginEndDistanceIs(2);
4646  Matcher<vector<int> > m2 = BeginEndDistanceIs(Lt(2));
4647  Matcher<vector<int> > m3 = BeginEndDistanceIs(AnyOf(0, 3));
4648  Matcher<vector<int> > m4 = BeginEndDistanceIs(GreaterThan(1));
4649  vector<int> container;
4650  EXPECT_EQ("whose distance between begin() and end() 0 doesn't match",
4651            Explain(m1, container));
4652  EXPECT_EQ("whose distance between begin() and end() 0 matches",
4653            Explain(m2, container));
4654  EXPECT_EQ("whose distance between begin() and end() 0 matches",
4655            Explain(m3, container));
4656  EXPECT_EQ(
4657      "whose distance between begin() and end() 0 doesn't match, which is 1 "
4658      "less than 1",
4659      Explain(m4, container));
4660  container.push_back(0);
4661  container.push_back(0);
4662  EXPECT_EQ("whose distance between begin() and end() 2 matches",
4663            Explain(m1, container));
4664  EXPECT_EQ("whose distance between begin() and end() 2 doesn't match",
4665            Explain(m2, container));
4666  EXPECT_EQ("whose distance between begin() and end() 2 doesn't match",
4667            Explain(m3, container));
4668  EXPECT_EQ(
4669      "whose distance between begin() and end() 2 matches, which is 1 more "
4670      "than 1",
4671      Explain(m4, container));
4672}
4673
4674TEST(WhenSortedTest, WorksForStreamlike) {
4675  // Streamlike 'container' provides only minimal iterator support.
4676  // Its iterators are tagged with input_iterator_tag.
4677  const int a[5] = {2, 1, 4, 5, 3};
4678  Streamlike<int> s(a, a + GTEST_ARRAY_SIZE_(a));
4679  EXPECT_THAT(s, WhenSorted(ElementsAre(1, 2, 3, 4, 5)));
4680  EXPECT_THAT(s, Not(WhenSorted(ElementsAre(2, 1, 4, 5, 3))));
4681}
4682
4683TEST(WhenSortedTest, WorksForVectorConstRefMatcherOnStreamlike) {
4684  const int a[] = {2, 1, 4, 5, 3};
4685  Streamlike<int> s(a, a + GTEST_ARRAY_SIZE_(a));
4686  Matcher<const std::vector<int>&> vector_match = ElementsAre(1, 2, 3, 4, 5);
4687  EXPECT_THAT(s, WhenSorted(vector_match));
4688  EXPECT_THAT(s, Not(WhenSorted(ElementsAre(2, 1, 4, 5, 3))));
4689}
4690
4691// Tests using ElementsAre() and ElementsAreArray() with stream-like
4692// "containers".
4693
4694TEST(ElemensAreStreamTest, WorksForStreamlike) {
4695  const int a[5] = {1, 2, 3, 4, 5};
4696  Streamlike<int> s(a, a + GTEST_ARRAY_SIZE_(a));
4697  EXPECT_THAT(s, ElementsAre(1, 2, 3, 4, 5));
4698  EXPECT_THAT(s, Not(ElementsAre(2, 1, 4, 5, 3)));
4699}
4700
4701TEST(ElemensAreArrayStreamTest, WorksForStreamlike) {
4702  const int a[5] = {1, 2, 3, 4, 5};
4703  Streamlike<int> s(a, a + GTEST_ARRAY_SIZE_(a));
4704
4705  vector<int> expected;
4706  expected.push_back(1);
4707  expected.push_back(2);
4708  expected.push_back(3);
4709  expected.push_back(4);
4710  expected.push_back(5);
4711  EXPECT_THAT(s, ElementsAreArray(expected));
4712
4713  expected[3] = 0;
4714  EXPECT_THAT(s, Not(ElementsAreArray(expected)));
4715}
4716
4717TEST(ElementsAreTest, WorksWithUncopyable) {
4718  Uncopyable objs[2];
4719  objs[0].set_value(-3);
4720  objs[1].set_value(1);
4721  EXPECT_THAT(objs, ElementsAre(UncopyableIs(-3), Truly(ValueIsPositive)));
4722}
4723
4724TEST(ElementsAreTest, TakesStlContainer) {
4725  const int actual[] = {3, 1, 2};
4726
4727  ::std::list<int> expected;
4728  expected.push_back(3);
4729  expected.push_back(1);
4730  expected.push_back(2);
4731  EXPECT_THAT(actual, ElementsAreArray(expected));
4732
4733  expected.push_back(4);
4734  EXPECT_THAT(actual, Not(ElementsAreArray(expected)));
4735}
4736
4737// Tests for UnorderedElementsAreArray()
4738
4739TEST(UnorderedElementsAreArrayTest, SucceedsWhenExpected) {
4740  const int a[] = {0, 1, 2, 3, 4};
4741  std::vector<int> s(a, a + GTEST_ARRAY_SIZE_(a));
4742  do {
4743    StringMatchResultListener listener;
4744    EXPECT_TRUE(ExplainMatchResult(UnorderedElementsAreArray(a),
4745                                   s, &listener)) << listener.str();
4746  } while (std::next_permutation(s.begin(), s.end()));
4747}
4748
4749TEST(UnorderedElementsAreArrayTest, VectorBool) {
4750  const bool a[] = {0, 1, 0, 1, 1};
4751  const bool b[] = {1, 0, 1, 1, 0};
4752  std::vector<bool> expected(a, a + GTEST_ARRAY_SIZE_(a));
4753  std::vector<bool> actual(b, b + GTEST_ARRAY_SIZE_(b));
4754  StringMatchResultListener listener;
4755  EXPECT_TRUE(ExplainMatchResult(UnorderedElementsAreArray(expected),
4756                                 actual, &listener)) << listener.str();
4757}
4758
4759TEST(UnorderedElementsAreArrayTest, WorksForStreamlike) {
4760  // Streamlike 'container' provides only minimal iterator support.
4761  // Its iterators are tagged with input_iterator_tag, and it has no
4762  // size() or empty() methods.
4763  const int a[5] = {2, 1, 4, 5, 3};
4764  Streamlike<int> s(a, a + GTEST_ARRAY_SIZE_(a));
4765
4766  ::std::vector<int> expected;
4767  expected.push_back(1);
4768  expected.push_back(2);
4769  expected.push_back(3);
4770  expected.push_back(4);
4771  expected.push_back(5);
4772  EXPECT_THAT(s, UnorderedElementsAreArray(expected));
4773
4774  expected.push_back(6);
4775  EXPECT_THAT(s, Not(UnorderedElementsAreArray(expected)));
4776}
4777
4778TEST(UnorderedElementsAreArrayTest, TakesStlContainer) {
4779  const int actual[] = {3, 1, 2};
4780
4781  ::std::list<int> expected;
4782  expected.push_back(1);
4783  expected.push_back(2);
4784  expected.push_back(3);
4785  EXPECT_THAT(actual, UnorderedElementsAreArray(expected));
4786
4787  expected.push_back(4);
4788  EXPECT_THAT(actual, Not(UnorderedElementsAreArray(expected)));
4789}
4790
4791#if GTEST_HAS_STD_INITIALIZER_LIST_
4792
4793TEST(UnorderedElementsAreArrayTest, TakesInitializerList) {
4794  const int a[5] = {2, 1, 4, 5, 3};
4795  EXPECT_THAT(a, UnorderedElementsAreArray({1, 2, 3, 4, 5}));
4796  EXPECT_THAT(a, Not(UnorderedElementsAreArray({1, 2, 3, 4, 6})));
4797}
4798
4799TEST(UnorderedElementsAreArrayTest, TakesInitializerListOfCStrings) {
4800  const std::string a[5] = {"a", "b", "c", "d", "e"};
4801  EXPECT_THAT(a, UnorderedElementsAreArray({"a", "b", "c", "d", "e"}));
4802  EXPECT_THAT(a, Not(UnorderedElementsAreArray({"a", "b", "c", "d", "ef"})));
4803}
4804
4805TEST(UnorderedElementsAreArrayTest, TakesInitializerListOfSameTypedMatchers) {
4806  const int a[5] = {2, 1, 4, 5, 3};
4807  EXPECT_THAT(a, UnorderedElementsAreArray(
4808      {Eq(1), Eq(2), Eq(3), Eq(4), Eq(5)}));
4809  EXPECT_THAT(a, Not(UnorderedElementsAreArray(
4810      {Eq(1), Eq(2), Eq(3), Eq(4), Eq(6)})));
4811}
4812
4813TEST(UnorderedElementsAreArrayTest,
4814     TakesInitializerListOfDifferentTypedMatchers) {
4815  const int a[5] = {2, 1, 4, 5, 3};
4816  // The compiler cannot infer the type of the initializer list if its
4817  // elements have different types.  We must explicitly specify the
4818  // unified element type in this case.
4819  EXPECT_THAT(a, UnorderedElementsAreArray<Matcher<int> >(
4820      {Eq(1), Ne(-2), Ge(3), Le(4), Eq(5)}));
4821  EXPECT_THAT(a, Not(UnorderedElementsAreArray<Matcher<int> >(
4822      {Eq(1), Ne(-2), Ge(3), Le(4), Eq(6)})));
4823}
4824
4825#endif  // GTEST_HAS_STD_INITIALIZER_LIST_
4826
4827class UnorderedElementsAreTest : public testing::Test {
4828 protected:
4829  typedef std::vector<int> IntVec;
4830};
4831
4832TEST_F(UnorderedElementsAreTest, WorksWithUncopyable) {
4833  Uncopyable objs[2];
4834  objs[0].set_value(-3);
4835  objs[1].set_value(1);
4836  EXPECT_THAT(objs,
4837              UnorderedElementsAre(Truly(ValueIsPositive), UncopyableIs(-3)));
4838}
4839
4840TEST_F(UnorderedElementsAreTest, SucceedsWhenExpected) {
4841  const int a[] = {1, 2, 3};
4842  std::vector<int> s(a, a + GTEST_ARRAY_SIZE_(a));
4843  do {
4844    StringMatchResultListener listener;
4845    EXPECT_TRUE(ExplainMatchResult(UnorderedElementsAre(1, 2, 3),
4846                                   s, &listener)) << listener.str();
4847  } while (std::next_permutation(s.begin(), s.end()));
4848}
4849
4850TEST_F(UnorderedElementsAreTest, FailsWhenAnElementMatchesNoMatcher) {
4851  const int a[] = {1, 2, 3};
4852  std::vector<int> s(a, a + GTEST_ARRAY_SIZE_(a));
4853  std::vector<Matcher<int> > mv;
4854  mv.push_back(1);
4855  mv.push_back(2);
4856  mv.push_back(2);
4857  // The element with value '3' matches nothing: fail fast.
4858  StringMatchResultListener listener;
4859  EXPECT_FALSE(ExplainMatchResult(UnorderedElementsAreArray(mv),
4860                                  s, &listener)) << listener.str();
4861}
4862
4863TEST_F(UnorderedElementsAreTest, WorksForStreamlike) {
4864  // Streamlike 'container' provides only minimal iterator support.
4865  // Its iterators are tagged with input_iterator_tag, and it has no
4866  // size() or empty() methods.
4867  const int a[5] = {2, 1, 4, 5, 3};
4868  Streamlike<int> s(a, a + GTEST_ARRAY_SIZE_(a));
4869
4870  EXPECT_THAT(s, UnorderedElementsAre(1, 2, 3, 4, 5));
4871  EXPECT_THAT(s, Not(UnorderedElementsAre(2, 2, 3, 4, 5)));
4872}
4873
4874// One naive implementation of the matcher runs in O(N!) time, which is too
4875// slow for many real-world inputs. This test shows that our matcher can match
4876// 100 inputs very quickly (a few milliseconds).  An O(100!) is 10^158
4877// iterations and obviously effectively incomputable.
4878// [ RUN      ] UnorderedElementsAreTest.Performance
4879// [       OK ] UnorderedElementsAreTest.Performance (4 ms)
4880TEST_F(UnorderedElementsAreTest, Performance) {
4881  std::vector<int> s;
4882  std::vector<Matcher<int> > mv;
4883  for (int i = 0; i < 100; ++i) {
4884    s.push_back(i);
4885    mv.push_back(_);
4886  }
4887  mv[50] = Eq(0);
4888  StringMatchResultListener listener;
4889  EXPECT_TRUE(ExplainMatchResult(UnorderedElementsAreArray(mv),
4890                                 s, &listener)) << listener.str();
4891}
4892
4893// Another variant of 'Performance' with similar expectations.
4894// [ RUN      ] UnorderedElementsAreTest.PerformanceHalfStrict
4895// [       OK ] UnorderedElementsAreTest.PerformanceHalfStrict (4 ms)
4896TEST_F(UnorderedElementsAreTest, PerformanceHalfStrict) {
4897  std::vector<int> s;
4898  std::vector<Matcher<int> > mv;
4899  for (int i = 0; i < 100; ++i) {
4900    s.push_back(i);
4901    if (i & 1) {
4902      mv.push_back(_);
4903    } else {
4904      mv.push_back(i);
4905    }
4906  }
4907  StringMatchResultListener listener;
4908  EXPECT_TRUE(ExplainMatchResult(UnorderedElementsAreArray(mv),
4909                                 s, &listener)) << listener.str();
4910}
4911
4912TEST_F(UnorderedElementsAreTest, FailMessageCountWrong) {
4913  std::vector<int> v;
4914  v.push_back(4);
4915  StringMatchResultListener listener;
4916  EXPECT_FALSE(ExplainMatchResult(UnorderedElementsAre(1, 2, 3),
4917                                  v, &listener)) << listener.str();
4918  EXPECT_THAT(listener.str(), Eq("which has 1 element"));
4919}
4920
4921TEST_F(UnorderedElementsAreTest, FailMessageCountWrongZero) {
4922  std::vector<int> v;
4923  StringMatchResultListener listener;
4924  EXPECT_FALSE(ExplainMatchResult(UnorderedElementsAre(1, 2, 3),
4925                                  v, &listener)) << listener.str();
4926  EXPECT_THAT(listener.str(), Eq(""));
4927}
4928
4929TEST_F(UnorderedElementsAreTest, FailMessageUnmatchedMatchers) {
4930  std::vector<int> v;
4931  v.push_back(1);
4932  v.push_back(1);
4933  StringMatchResultListener listener;
4934  EXPECT_FALSE(ExplainMatchResult(UnorderedElementsAre(1, 2),
4935                                  v, &listener)) << listener.str();
4936  EXPECT_THAT(
4937      listener.str(),
4938      Eq("where the following matchers don't match any elements:\n"
4939         "matcher #1: is equal to 2"));
4940}
4941
4942TEST_F(UnorderedElementsAreTest, FailMessageUnmatchedElements) {
4943  std::vector<int> v;
4944  v.push_back(1);
4945  v.push_back(2);
4946  StringMatchResultListener listener;
4947  EXPECT_FALSE(ExplainMatchResult(UnorderedElementsAre(1, 1),
4948                                  v, &listener)) << listener.str();
4949  EXPECT_THAT(
4950      listener.str(),
4951      Eq("where the following elements don't match any matchers:\n"
4952         "element #1: 2"));
4953}
4954
4955TEST_F(UnorderedElementsAreTest, FailMessageUnmatchedMatcherAndElement) {
4956  std::vector<int> v;
4957  v.push_back(2);
4958  v.push_back(3);
4959  StringMatchResultListener listener;
4960  EXPECT_FALSE(ExplainMatchResult(UnorderedElementsAre(1, 2),
4961                                  v, &listener)) << listener.str();
4962  EXPECT_THAT(
4963      listener.str(),
4964      Eq("where"
4965         " the following matchers don't match any elements:\n"
4966         "matcher #0: is equal to 1\n"
4967         "and"
4968         " where"
4969         " the following elements don't match any matchers:\n"
4970         "element #1: 3"));
4971}
4972
4973// Test helper for formatting element, matcher index pairs in expectations.
4974static std::string EMString(int element, int matcher) {
4975  stringstream ss;
4976  ss << "(element #" << element << ", matcher #" << matcher << ")";
4977  return ss.str();
4978}
4979
4980TEST_F(UnorderedElementsAreTest, FailMessageImperfectMatchOnly) {
4981  // A situation where all elements and matchers have a match
4982  // associated with them, but the max matching is not perfect.
4983  std::vector<std::string> v;
4984  v.push_back("a");
4985  v.push_back("b");
4986  v.push_back("c");
4987  StringMatchResultListener listener;
4988  EXPECT_FALSE(ExplainMatchResult(
4989      UnorderedElementsAre("a", "a", AnyOf("b", "c")), v, &listener))
4990      << listener.str();
4991
4992  std::string prefix =
4993      "where no permutation of the elements can satisfy all matchers, "
4994      "and the closest match is 2 of 3 matchers with the "
4995      "pairings:\n";
4996
4997  // We have to be a bit loose here, because there are 4 valid max matches.
4998  EXPECT_THAT(
4999      listener.str(),
5000      AnyOf(prefix + "{\n  " + EMString(0, 0) +
5001                     ",\n  " + EMString(1, 2) + "\n}",
5002            prefix + "{\n  " + EMString(0, 1) +
5003                     ",\n  " + EMString(1, 2) + "\n}",
5004            prefix + "{\n  " + EMString(0, 0) +
5005                     ",\n  " + EMString(2, 2) + "\n}",
5006            prefix + "{\n  " + EMString(0, 1) +
5007                     ",\n  " + EMString(2, 2) + "\n}"));
5008}
5009
5010TEST_F(UnorderedElementsAreTest, Describe) {
5011  EXPECT_THAT(Describe<IntVec>(UnorderedElementsAre()),
5012              Eq("is empty"));
5013  EXPECT_THAT(
5014      Describe<IntVec>(UnorderedElementsAre(345)),
5015      Eq("has 1 element and that element is equal to 345"));
5016  EXPECT_THAT(
5017      Describe<IntVec>(UnorderedElementsAre(111, 222, 333)),
5018      Eq("has 3 elements and there exists some permutation "
5019         "of elements such that:\n"
5020         " - element #0 is equal to 111, and\n"
5021         " - element #1 is equal to 222, and\n"
5022         " - element #2 is equal to 333"));
5023}
5024
5025TEST_F(UnorderedElementsAreTest, DescribeNegation) {
5026  EXPECT_THAT(DescribeNegation<IntVec>(UnorderedElementsAre()),
5027              Eq("isn't empty"));
5028  EXPECT_THAT(
5029      DescribeNegation<IntVec>(UnorderedElementsAre(345)),
5030      Eq("doesn't have 1 element, or has 1 element that isn't equal to 345"));
5031  EXPECT_THAT(
5032      DescribeNegation<IntVec>(UnorderedElementsAre(123, 234, 345)),
5033      Eq("doesn't have 3 elements, or there exists no permutation "
5034         "of elements such that:\n"
5035         " - element #0 is equal to 123, and\n"
5036         " - element #1 is equal to 234, and\n"
5037         " - element #2 is equal to 345"));
5038}
5039
5040namespace {
5041
5042// Used as a check on the more complex max flow method used in the
5043// real testing::internal::FindMaxBipartiteMatching. This method is
5044// compatible but runs in worst-case factorial time, so we only
5045// use it in testing for small problem sizes.
5046template <typename Graph>
5047class BacktrackingMaxBPMState {
5048 public:
5049  // Does not take ownership of 'g'.
5050  explicit BacktrackingMaxBPMState(const Graph* g) : graph_(g) { }
5051
5052  ElementMatcherPairs Compute() {
5053    if (graph_->LhsSize() == 0 || graph_->RhsSize() == 0) {
5054      return best_so_far_;
5055    }
5056    lhs_used_.assign(graph_->LhsSize(), kUnused);
5057    rhs_used_.assign(graph_->RhsSize(), kUnused);
5058    for (size_t irhs = 0; irhs < graph_->RhsSize(); ++irhs) {
5059      matches_.clear();
5060      RecurseInto(irhs);
5061      if (best_so_far_.size() == graph_->RhsSize())
5062        break;
5063    }
5064    return best_so_far_;
5065  }
5066
5067 private:
5068  static const size_t kUnused = static_cast<size_t>(-1);
5069
5070  void PushMatch(size_t lhs, size_t rhs) {
5071    matches_.push_back(ElementMatcherPair(lhs, rhs));
5072    lhs_used_[lhs] = rhs;
5073    rhs_used_[rhs] = lhs;
5074    if (matches_.size() > best_so_far_.size()) {
5075      best_so_far_ = matches_;
5076    }
5077  }
5078
5079  void PopMatch() {
5080    const ElementMatcherPair& back = matches_.back();
5081    lhs_used_[back.first] = kUnused;
5082    rhs_used_[back.second] = kUnused;
5083    matches_.pop_back();
5084  }
5085
5086  bool RecurseInto(size_t irhs) {
5087    if (rhs_used_[irhs] != kUnused) {
5088      return true;
5089    }
5090    for (size_t ilhs = 0; ilhs < graph_->LhsSize(); ++ilhs) {
5091      if (lhs_used_[ilhs] != kUnused) {
5092        continue;
5093      }
5094      if (!graph_->HasEdge(ilhs, irhs)) {
5095        continue;
5096      }
5097      PushMatch(ilhs, irhs);
5098      if (best_so_far_.size() == graph_->RhsSize()) {
5099        return false;
5100      }
5101      for (size_t mi = irhs + 1; mi < graph_->RhsSize(); ++mi) {
5102        if (!RecurseInto(mi)) return false;
5103      }
5104      PopMatch();
5105    }
5106    return true;
5107  }
5108
5109  const Graph* graph_;  // not owned
5110  std::vector<size_t> lhs_used_;
5111  std::vector<size_t> rhs_used_;
5112  ElementMatcherPairs matches_;
5113  ElementMatcherPairs best_so_far_;
5114};
5115
5116template <typename Graph>
5117const size_t BacktrackingMaxBPMState<Graph>::kUnused;
5118
5119}  // namespace
5120
5121// Implement a simple backtracking algorithm to determine if it is possible
5122// to find one element per matcher, without reusing elements.
5123template <typename Graph>
5124ElementMatcherPairs
5125FindBacktrackingMaxBPM(const Graph& g) {
5126  return BacktrackingMaxBPMState<Graph>(&g).Compute();
5127}
5128
5129class BacktrackingBPMTest : public ::testing::Test { };
5130
5131// Tests the MaxBipartiteMatching algorithm with square matrices.
5132// The single int param is the # of nodes on each of the left and right sides.
5133class BipartiteTest : public ::testing::TestWithParam<int> { };
5134
5135// Verify all match graphs up to some moderate number of edges.
5136TEST_P(BipartiteTest, Exhaustive) {
5137  int nodes = GetParam();
5138  MatchMatrix graph(nodes, nodes);
5139  do {
5140    ElementMatcherPairs matches =
5141        internal::FindMaxBipartiteMatching(graph);
5142    EXPECT_EQ(FindBacktrackingMaxBPM(graph).size(), matches.size())
5143        << "graph: " << graph.DebugString();
5144    // Check that all elements of matches are in the graph.
5145    // Check that elements of first and second are unique.
5146    std::vector<bool> seen_element(graph.LhsSize());
5147    std::vector<bool> seen_matcher(graph.RhsSize());
5148    SCOPED_TRACE(PrintToString(matches));
5149    for (size_t i = 0; i < matches.size(); ++i) {
5150      size_t ilhs = matches[i].first;
5151      size_t irhs = matches[i].second;
5152      EXPECT_TRUE(graph.HasEdge(ilhs, irhs));
5153      EXPECT_FALSE(seen_element[ilhs]);
5154      EXPECT_FALSE(seen_matcher[irhs]);
5155      seen_element[ilhs] = true;
5156      seen_matcher[irhs] = true;
5157    }
5158  } while (graph.NextGraph());
5159}
5160
5161INSTANTIATE_TEST_CASE_P(AllGraphs, BipartiteTest,
5162                        ::testing::Range(0, 5));
5163
5164// Parameterized by a pair interpreted as (LhsSize, RhsSize).
5165class BipartiteNonSquareTest
5166    : public ::testing::TestWithParam<std::pair<size_t, size_t> > {
5167};
5168
5169TEST_F(BipartiteNonSquareTest, SimpleBacktracking) {
5170  //   .......
5171  // 0:-----\ :
5172  // 1:---\ | :
5173  // 2:---\ | :
5174  // 3:-\ | | :
5175  //  :.......:
5176  //    0 1 2
5177  MatchMatrix g(4, 3);
5178  static const int kEdges[][2] = {{0, 2}, {1, 1}, {2, 1}, {3, 0}};
5179  for (size_t i = 0; i < GTEST_ARRAY_SIZE_(kEdges); ++i) {
5180    g.SetEdge(kEdges[i][0], kEdges[i][1], true);
5181  }
5182  EXPECT_THAT(FindBacktrackingMaxBPM(g),
5183              ElementsAre(Pair(3, 0),
5184                          Pair(AnyOf(1, 2), 1),
5185                          Pair(0, 2))) << g.DebugString();
5186}
5187
5188// Verify a few nonsquare matrices.
5189TEST_P(BipartiteNonSquareTest, Exhaustive) {
5190  size_t nlhs = GetParam().first;
5191  size_t nrhs = GetParam().second;
5192  MatchMatrix graph(nlhs, nrhs);
5193  do {
5194    EXPECT_EQ(FindBacktrackingMaxBPM(graph).size(),
5195              internal::FindMaxBipartiteMatching(graph).size())
5196        << "graph: " << graph.DebugString()
5197        << "\nbacktracking: "
5198        << PrintToString(FindBacktrackingMaxBPM(graph))
5199        << "\nmax flow: "
5200        << PrintToString(internal::FindMaxBipartiteMatching(graph));
5201  } while (graph.NextGraph());
5202}
5203
5204INSTANTIATE_TEST_CASE_P(AllGraphs, BipartiteNonSquareTest,
5205    testing::Values(
5206        std::make_pair(1, 2),
5207        std::make_pair(2, 1),
5208        std::make_pair(3, 2),
5209        std::make_pair(2, 3),
5210        std::make_pair(4, 1),
5211        std::make_pair(1, 4),
5212        std::make_pair(4, 3),
5213        std::make_pair(3, 4)));
5214
5215class BipartiteRandomTest
5216    : public ::testing::TestWithParam<std::pair<int, int> > {
5217};
5218
5219// Verifies a large sample of larger graphs.
5220TEST_P(BipartiteRandomTest, LargerNets) {
5221  int nodes = GetParam().first;
5222  int iters = GetParam().second;
5223  MatchMatrix graph(nodes, nodes);
5224
5225  testing::internal::Int32 seed = GTEST_FLAG(random_seed);
5226  if (seed == 0) {
5227    seed = static_cast<testing::internal::Int32>(time(NULL));
5228  }
5229
5230  for (; iters > 0; --iters, ++seed) {
5231    srand(static_cast<int>(seed));
5232    graph.Randomize();
5233    EXPECT_EQ(FindBacktrackingMaxBPM(graph).size(),
5234              internal::FindMaxBipartiteMatching(graph).size())
5235        << " graph: " << graph.DebugString()
5236        << "\nTo reproduce the failure, rerun the test with the flag"
5237           " --" << GTEST_FLAG_PREFIX_ << "random_seed=" << seed;
5238  }
5239}
5240
5241// Test argument is a std::pair<int, int> representing (nodes, iters).
5242INSTANTIATE_TEST_CASE_P(Samples, BipartiteRandomTest,
5243    testing::Values(
5244        std::make_pair(5, 10000),
5245        std::make_pair(6, 5000),
5246        std::make_pair(7, 2000),
5247        std::make_pair(8, 500),
5248        std::make_pair(9, 100)));
5249
5250// Tests IsReadableTypeName().
5251
5252TEST(IsReadableTypeNameTest, ReturnsTrueForShortNames) {
5253  EXPECT_TRUE(IsReadableTypeName("int"));
5254  EXPECT_TRUE(IsReadableTypeName("const unsigned char*"));
5255  EXPECT_TRUE(IsReadableTypeName("MyMap<int, void*>"));
5256  EXPECT_TRUE(IsReadableTypeName("void (*)(int, bool)"));
5257}
5258
5259TEST(IsReadableTypeNameTest, ReturnsTrueForLongNonTemplateNonFunctionNames) {
5260  EXPECT_TRUE(IsReadableTypeName("my_long_namespace::MyClassName"));
5261  EXPECT_TRUE(IsReadableTypeName("int [5][6][7][8][9][10][11]"));
5262  EXPECT_TRUE(IsReadableTypeName("my_namespace::MyOuterClass::MyInnerClass"));
5263}
5264
5265TEST(IsReadableTypeNameTest, ReturnsFalseForLongTemplateNames) {
5266  EXPECT_FALSE(
5267      IsReadableTypeName("basic_string<char, std::char_traits<char> >"));
5268  EXPECT_FALSE(IsReadableTypeName("std::vector<int, std::alloc_traits<int> >"));
5269}
5270
5271TEST(IsReadableTypeNameTest, ReturnsFalseForLongFunctionTypeNames) {
5272  EXPECT_FALSE(IsReadableTypeName("void (&)(int, bool, char, float)"));
5273}
5274
5275// Tests JoinAsTuple().
5276
5277TEST(JoinAsTupleTest, JoinsEmptyTuple) {
5278  EXPECT_EQ("", JoinAsTuple(Strings()));
5279}
5280
5281TEST(JoinAsTupleTest, JoinsOneTuple) {
5282  const char* fields[] = {"1"};
5283  EXPECT_EQ("1", JoinAsTuple(Strings(fields, fields + 1)));
5284}
5285
5286TEST(JoinAsTupleTest, JoinsTwoTuple) {
5287  const char* fields[] = {"1", "a"};
5288  EXPECT_EQ("(1, a)", JoinAsTuple(Strings(fields, fields + 2)));
5289}
5290
5291TEST(JoinAsTupleTest, JoinsTenTuple) {
5292  const char* fields[] = {"1", "2", "3", "4", "5", "6", "7", "8", "9", "10"};
5293  EXPECT_EQ("(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)",
5294            JoinAsTuple(Strings(fields, fields + 10)));
5295}
5296
5297// Tests FormatMatcherDescription().
5298
5299TEST(FormatMatcherDescriptionTest, WorksForEmptyDescription) {
5300  EXPECT_EQ("is even",
5301            FormatMatcherDescription(false, "IsEven", Strings()));
5302  EXPECT_EQ("not (is even)",
5303            FormatMatcherDescription(true, "IsEven", Strings()));
5304
5305  const char* params[] = {"5"};
5306  EXPECT_EQ("equals 5",
5307            FormatMatcherDescription(false, "Equals",
5308                                     Strings(params, params + 1)));
5309
5310  const char* params2[] = {"5", "8"};
5311  EXPECT_EQ("is in range (5, 8)",
5312            FormatMatcherDescription(false, "IsInRange",
5313                                     Strings(params2, params2 + 2)));
5314}
5315
5316// Tests PolymorphicMatcher::mutable_impl().
5317TEST(PolymorphicMatcherTest, CanAccessMutableImpl) {
5318  PolymorphicMatcher<DivisibleByImpl> m(DivisibleByImpl(42));
5319  DivisibleByImpl& impl = m.mutable_impl();
5320  EXPECT_EQ(42, impl.divider());
5321
5322  impl.set_divider(0);
5323  EXPECT_EQ(0, m.mutable_impl().divider());
5324}
5325
5326// Tests PolymorphicMatcher::impl().
5327TEST(PolymorphicMatcherTest, CanAccessImpl) {
5328  const PolymorphicMatcher<DivisibleByImpl> m(DivisibleByImpl(42));
5329  const DivisibleByImpl& impl = m.impl();
5330  EXPECT_EQ(42, impl.divider());
5331}
5332
5333TEST(MatcherTupleTest, ExplainsMatchFailure) {
5334  stringstream ss1;
5335  ExplainMatchFailureTupleTo(make_tuple(Matcher<char>(Eq('a')), GreaterThan(5)),
5336                             make_tuple('a', 10), &ss1);
5337  EXPECT_EQ("", ss1.str());  // Successful match.
5338
5339  stringstream ss2;
5340  ExplainMatchFailureTupleTo(make_tuple(GreaterThan(5), Matcher<char>(Eq('a'))),
5341                             make_tuple(2, 'b'), &ss2);
5342  EXPECT_EQ("  Expected arg #0: is > 5\n"
5343            "           Actual: 2, which is 3 less than 5\n"
5344            "  Expected arg #1: is equal to 'a' (97, 0x61)\n"
5345            "           Actual: 'b' (98, 0x62)\n",
5346            ss2.str());  // Failed match where both arguments need explanation.
5347
5348  stringstream ss3;
5349  ExplainMatchFailureTupleTo(make_tuple(GreaterThan(5), Matcher<char>(Eq('a'))),
5350                             make_tuple(2, 'a'), &ss3);
5351  EXPECT_EQ("  Expected arg #0: is > 5\n"
5352            "           Actual: 2, which is 3 less than 5\n",
5353            ss3.str());  // Failed match where only one argument needs
5354                         // explanation.
5355}
5356
5357// Tests Each().
5358
5359TEST(EachTest, ExplainsMatchResultCorrectly) {
5360  set<int> a;  // empty
5361
5362  Matcher<set<int> > m = Each(2);
5363  EXPECT_EQ("", Explain(m, a));
5364
5365  Matcher<const int(&)[1]> n = Each(1);  // NOLINT
5366
5367  const int b[1] = {1};
5368  EXPECT_EQ("", Explain(n, b));
5369
5370  n = Each(3);
5371  EXPECT_EQ("whose element #0 doesn't match", Explain(n, b));
5372
5373  a.insert(1);
5374  a.insert(2);
5375  a.insert(3);
5376  m = Each(GreaterThan(0));
5377  EXPECT_EQ("", Explain(m, a));
5378
5379  m = Each(GreaterThan(10));
5380  EXPECT_EQ("whose element #0 doesn't match, which is 9 less than 10",
5381            Explain(m, a));
5382}
5383
5384TEST(EachTest, DescribesItselfCorrectly) {
5385  Matcher<vector<int> > m = Each(1);
5386  EXPECT_EQ("only contains elements that is equal to 1", Describe(m));
5387
5388  Matcher<vector<int> > m2 = Not(m);
5389  EXPECT_EQ("contains some element that isn't equal to 1", Describe(m2));
5390}
5391
5392TEST(EachTest, MatchesVectorWhenAllElementsMatch) {
5393  vector<int> some_vector;
5394  EXPECT_THAT(some_vector, Each(1));
5395  some_vector.push_back(3);
5396  EXPECT_THAT(some_vector, Not(Each(1)));
5397  EXPECT_THAT(some_vector, Each(3));
5398  some_vector.push_back(1);
5399  some_vector.push_back(2);
5400  EXPECT_THAT(some_vector, Not(Each(3)));
5401  EXPECT_THAT(some_vector, Each(Lt(3.5)));
5402
5403  vector<std::string> another_vector;
5404  another_vector.push_back("fee");
5405  EXPECT_THAT(another_vector, Each(std::string("fee")));
5406  another_vector.push_back("fie");
5407  another_vector.push_back("foe");
5408  another_vector.push_back("fum");
5409  EXPECT_THAT(another_vector, Not(Each(std::string("fee"))));
5410}
5411
5412TEST(EachTest, MatchesMapWhenAllElementsMatch) {
5413  map<const char*, int> my_map;
5414  const char* bar = "a string";
5415  my_map[bar] = 2;
5416  EXPECT_THAT(my_map, Each(make_pair(bar, 2)));
5417
5418  map<std::string, int> another_map;
5419  EXPECT_THAT(another_map, Each(make_pair(std::string("fee"), 1)));
5420  another_map["fee"] = 1;
5421  EXPECT_THAT(another_map, Each(make_pair(std::string("fee"), 1)));
5422  another_map["fie"] = 2;
5423  another_map["foe"] = 3;
5424  another_map["fum"] = 4;
5425  EXPECT_THAT(another_map, Not(Each(make_pair(std::string("fee"), 1))));
5426  EXPECT_THAT(another_map, Not(Each(make_pair(std::string("fum"), 1))));
5427  EXPECT_THAT(another_map, Each(Pair(_, Gt(0))));
5428}
5429
5430TEST(EachTest, AcceptsMatcher) {
5431  const int a[] = {1, 2, 3};
5432  EXPECT_THAT(a, Each(Gt(0)));
5433  EXPECT_THAT(a, Not(Each(Gt(1))));
5434}
5435
5436TEST(EachTest, WorksForNativeArrayAsTuple) {
5437  const int a[] = {1, 2};
5438  const int* const pointer = a;
5439  EXPECT_THAT(make_tuple(pointer, 2), Each(Gt(0)));
5440  EXPECT_THAT(make_tuple(pointer, 2), Not(Each(Gt(1))));
5441}
5442
5443// For testing Pointwise().
5444class IsHalfOfMatcher {
5445 public:
5446  template <typename T1, typename T2>
5447  bool MatchAndExplain(const tuple<T1, T2>& a_pair,
5448                       MatchResultListener* listener) const {
5449    if (get<0>(a_pair) == get<1>(a_pair)/2) {
5450      *listener << "where the second is " << get<1>(a_pair);
5451      return true;
5452    } else {
5453      *listener << "where the second/2 is " << get<1>(a_pair)/2;
5454      return false;
5455    }
5456  }
5457
5458  void DescribeTo(ostream* os) const {
5459    *os << "are a pair where the first is half of the second";
5460  }
5461
5462  void DescribeNegationTo(ostream* os) const {
5463    *os << "are a pair where the first isn't half of the second";
5464  }
5465};
5466
5467PolymorphicMatcher<IsHalfOfMatcher> IsHalfOf() {
5468  return MakePolymorphicMatcher(IsHalfOfMatcher());
5469}
5470
5471TEST(PointwiseTest, DescribesSelf) {
5472  vector<int> rhs;
5473  rhs.push_back(1);
5474  rhs.push_back(2);
5475  rhs.push_back(3);
5476  const Matcher<const vector<int>&> m = Pointwise(IsHalfOf(), rhs);
5477  EXPECT_EQ("contains 3 values, where each value and its corresponding value "
5478            "in { 1, 2, 3 } are a pair where the first is half of the second",
5479            Describe(m));
5480  EXPECT_EQ("doesn't contain exactly 3 values, or contains a value x at some "
5481            "index i where x and the i-th value of { 1, 2, 3 } are a pair "
5482            "where the first isn't half of the second",
5483            DescribeNegation(m));
5484}
5485
5486TEST(PointwiseTest, MakesCopyOfRhs) {
5487  list<signed char> rhs;
5488  rhs.push_back(2);
5489  rhs.push_back(4);
5490
5491  int lhs[] = {1, 2};
5492  const Matcher<const int (&)[2]> m = Pointwise(IsHalfOf(), rhs);
5493  EXPECT_THAT(lhs, m);
5494
5495  // Changing rhs now shouldn't affect m, which made a copy of rhs.
5496  rhs.push_back(6);
5497  EXPECT_THAT(lhs, m);
5498}
5499
5500TEST(PointwiseTest, WorksForLhsNativeArray) {
5501  const int lhs[] = {1, 2, 3};
5502  vector<int> rhs;
5503  rhs.push_back(2);
5504  rhs.push_back(4);
5505  rhs.push_back(6);
5506  EXPECT_THAT(lhs, Pointwise(Lt(), rhs));
5507  EXPECT_THAT(lhs, Not(Pointwise(Gt(), rhs)));
5508}
5509
5510TEST(PointwiseTest, WorksForRhsNativeArray) {
5511  const int rhs[] = {1, 2, 3};
5512  vector<int> lhs;
5513  lhs.push_back(2);
5514  lhs.push_back(4);
5515  lhs.push_back(6);
5516  EXPECT_THAT(lhs, Pointwise(Gt(), rhs));
5517  EXPECT_THAT(lhs, Not(Pointwise(Lt(), rhs)));
5518}
5519
5520#if GTEST_HAS_STD_INITIALIZER_LIST_
5521
5522TEST(PointwiseTest, WorksForRhsInitializerList) {
5523  const vector<int> lhs{2, 4, 6};
5524  EXPECT_THAT(lhs, Pointwise(Gt(), {1, 2, 3}));
5525  EXPECT_THAT(lhs, Not(Pointwise(Lt(), {3, 3, 7})));
5526}
5527
5528#endif  // GTEST_HAS_STD_INITIALIZER_LIST_
5529
5530TEST(PointwiseTest, RejectsWrongSize) {
5531  const double lhs[2] = {1, 2};
5532  const int rhs[1] = {0};
5533  EXPECT_THAT(lhs, Not(Pointwise(Gt(), rhs)));
5534  EXPECT_EQ("which contains 2 values",
5535            Explain(Pointwise(Gt(), rhs), lhs));
5536
5537  const int rhs2[3] = {0, 1, 2};
5538  EXPECT_THAT(lhs, Not(Pointwise(Gt(), rhs2)));
5539}
5540
5541TEST(PointwiseTest, RejectsWrongContent) {
5542  const double lhs[3] = {1, 2, 3};
5543  const int rhs[3] = {2, 6, 4};
5544  EXPECT_THAT(lhs, Not(Pointwise(IsHalfOf(), rhs)));
5545  EXPECT_EQ("where the value pair (2, 6) at index #1 don't match, "
5546            "where the second/2 is 3",
5547            Explain(Pointwise(IsHalfOf(), rhs), lhs));
5548}
5549
5550TEST(PointwiseTest, AcceptsCorrectContent) {
5551  const double lhs[3] = {1, 2, 3};
5552  const int rhs[3] = {2, 4, 6};
5553  EXPECT_THAT(lhs, Pointwise(IsHalfOf(), rhs));
5554  EXPECT_EQ("", Explain(Pointwise(IsHalfOf(), rhs), lhs));
5555}
5556
5557TEST(PointwiseTest, AllowsMonomorphicInnerMatcher) {
5558  const double lhs[3] = {1, 2, 3};
5559  const int rhs[3] = {2, 4, 6};
5560  const Matcher<tuple<const double&, const int&> > m1 = IsHalfOf();
5561  EXPECT_THAT(lhs, Pointwise(m1, rhs));
5562  EXPECT_EQ("", Explain(Pointwise(m1, rhs), lhs));
5563
5564  // This type works as a tuple<const double&, const int&> can be
5565  // implicitly cast to tuple<double, int>.
5566  const Matcher<tuple<double, int> > m2 = IsHalfOf();
5567  EXPECT_THAT(lhs, Pointwise(m2, rhs));
5568  EXPECT_EQ("", Explain(Pointwise(m2, rhs), lhs));
5569}
5570
5571TEST(UnorderedPointwiseTest, DescribesSelf) {
5572  vector<int> rhs;
5573  rhs.push_back(1);
5574  rhs.push_back(2);
5575  rhs.push_back(3);
5576  const Matcher<const vector<int>&> m = UnorderedPointwise(IsHalfOf(), rhs);
5577  EXPECT_EQ(
5578      "has 3 elements and there exists some permutation of elements such "
5579      "that:\n"
5580      " - element #0 and 1 are a pair where the first is half of the second, "
5581      "and\n"
5582      " - element #1 and 2 are a pair where the first is half of the second, "
5583      "and\n"
5584      " - element #2 and 3 are a pair where the first is half of the second",
5585      Describe(m));
5586  EXPECT_EQ(
5587      "doesn't have 3 elements, or there exists no permutation of elements "
5588      "such that:\n"
5589      " - element #0 and 1 are a pair where the first is half of the second, "
5590      "and\n"
5591      " - element #1 and 2 are a pair where the first is half of the second, "
5592      "and\n"
5593      " - element #2 and 3 are a pair where the first is half of the second",
5594      DescribeNegation(m));
5595}
5596
5597TEST(UnorderedPointwiseTest, MakesCopyOfRhs) {
5598  list<signed char> rhs;
5599  rhs.push_back(2);
5600  rhs.push_back(4);
5601
5602  int lhs[] = {2, 1};
5603  const Matcher<const int (&)[2]> m = UnorderedPointwise(IsHalfOf(), rhs);
5604  EXPECT_THAT(lhs, m);
5605
5606  // Changing rhs now shouldn't affect m, which made a copy of rhs.
5607  rhs.push_back(6);
5608  EXPECT_THAT(lhs, m);
5609}
5610
5611TEST(UnorderedPointwiseTest, WorksForLhsNativeArray) {
5612  const int lhs[] = {1, 2, 3};
5613  vector<int> rhs;
5614  rhs.push_back(4);
5615  rhs.push_back(6);
5616  rhs.push_back(2);
5617  EXPECT_THAT(lhs, UnorderedPointwise(Lt(), rhs));
5618  EXPECT_THAT(lhs, Not(UnorderedPointwise(Gt(), rhs)));
5619}
5620
5621TEST(UnorderedPointwiseTest, WorksForRhsNativeArray) {
5622  const int rhs[] = {1, 2, 3};
5623  vector<int> lhs;
5624  lhs.push_back(4);
5625  lhs.push_back(2);
5626  lhs.push_back(6);
5627  EXPECT_THAT(lhs, UnorderedPointwise(Gt(), rhs));
5628  EXPECT_THAT(lhs, Not(UnorderedPointwise(Lt(), rhs)));
5629}
5630
5631#if GTEST_HAS_STD_INITIALIZER_LIST_
5632
5633TEST(UnorderedPointwiseTest, WorksForRhsInitializerList) {
5634  const vector<int> lhs{2, 4, 6};
5635  EXPECT_THAT(lhs, UnorderedPointwise(Gt(), {5, 1, 3}));
5636  EXPECT_THAT(lhs, Not(UnorderedPointwise(Lt(), {1, 1, 7})));
5637}
5638
5639#endif  // GTEST_HAS_STD_INITIALIZER_LIST_
5640
5641TEST(UnorderedPointwiseTest, RejectsWrongSize) {
5642  const double lhs[2] = {1, 2};
5643  const int rhs[1] = {0};
5644  EXPECT_THAT(lhs, Not(UnorderedPointwise(Gt(), rhs)));
5645  EXPECT_EQ("which has 2 elements",
5646            Explain(UnorderedPointwise(Gt(), rhs), lhs));
5647
5648  const int rhs2[3] = {0, 1, 2};
5649  EXPECT_THAT(lhs, Not(UnorderedPointwise(Gt(), rhs2)));
5650}
5651
5652TEST(UnorderedPointwiseTest, RejectsWrongContent) {
5653  const double lhs[3] = {1, 2, 3};
5654  const int rhs[3] = {2, 6, 6};
5655  EXPECT_THAT(lhs, Not(UnorderedPointwise(IsHalfOf(), rhs)));
5656  EXPECT_EQ("where the following elements don't match any matchers:\n"
5657            "element #1: 2",
5658            Explain(UnorderedPointwise(IsHalfOf(), rhs), lhs));
5659}
5660
5661TEST(UnorderedPointwiseTest, AcceptsCorrectContentInSameOrder) {
5662  const double lhs[3] = {1, 2, 3};
5663  const int rhs[3] = {2, 4, 6};
5664  EXPECT_THAT(lhs, UnorderedPointwise(IsHalfOf(), rhs));
5665}
5666
5667TEST(UnorderedPointwiseTest, AcceptsCorrectContentInDifferentOrder) {
5668  const double lhs[3] = {1, 2, 3};
5669  const int rhs[3] = {6, 4, 2};
5670  EXPECT_THAT(lhs, UnorderedPointwise(IsHalfOf(), rhs));
5671}
5672
5673TEST(UnorderedPointwiseTest, AllowsMonomorphicInnerMatcher) {
5674  const double lhs[3] = {1, 2, 3};
5675  const int rhs[3] = {4, 6, 2};
5676  const Matcher<tuple<const double&, const int&> > m1 = IsHalfOf();
5677  EXPECT_THAT(lhs, UnorderedPointwise(m1, rhs));
5678
5679  // This type works as a tuple<const double&, const int&> can be
5680  // implicitly cast to tuple<double, int>.
5681  const Matcher<tuple<double, int> > m2 = IsHalfOf();
5682  EXPECT_THAT(lhs, UnorderedPointwise(m2, rhs));
5683}
5684
5685}  // namespace gmock_matchers_test
5686}  // namespace testing
5687