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