1// Copyright 2008, 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// Google Mock - a framework for writing C++ mock classes.
31//
32// This file tests the built-in matchers generated by a script.
33
34#include "gmock/gmock-generated-matchers.h"
35
36#include <list>
37#include <map>
38#include <set>
39#include <sstream>
40#include <string>
41#include <utility>
42#include <vector>
43
44#include "gmock/gmock.h"
45#include "gtest/gtest.h"
46#include "gtest/gtest-spi.h"
47
48namespace {
49
50using std::list;
51using std::map;
52using std::pair;
53using std::set;
54using std::stringstream;
55using std::vector;
56using testing::get;
57using testing::make_tuple;
58using testing::tuple;
59using testing::_;
60using testing::Args;
61using testing::Contains;
62using testing::ElementsAre;
63using testing::ElementsAreArray;
64using testing::Eq;
65using testing::Ge;
66using testing::Gt;
67using testing::Le;
68using testing::Lt;
69using testing::MakeMatcher;
70using testing::Matcher;
71using testing::MatcherInterface;
72using testing::MatchResultListener;
73using testing::Ne;
74using testing::Not;
75using testing::Pointee;
76using testing::PrintToString;
77using testing::Ref;
78using testing::StaticAssertTypeEq;
79using testing::StrEq;
80using testing::Value;
81using testing::internal::ElementsAreArrayMatcher;
82using testing::internal::string;
83
84// Returns the description of the given matcher.
85template <typename T>
86string Describe(const Matcher<T>& m) {
87  stringstream ss;
88  m.DescribeTo(&ss);
89  return ss.str();
90}
91
92// Returns the description of the negation of the given matcher.
93template <typename T>
94string DescribeNegation(const Matcher<T>& m) {
95  stringstream ss;
96  m.DescribeNegationTo(&ss);
97  return ss.str();
98}
99
100// Returns the reason why x matches, or doesn't match, m.
101template <typename MatcherType, typename Value>
102string Explain(const MatcherType& m, const Value& x) {
103  stringstream ss;
104  m.ExplainMatchResultTo(x, &ss);
105  return ss.str();
106}
107
108// Tests Args<k0, ..., kn>(m).
109
110TEST(ArgsTest, AcceptsZeroTemplateArg) {
111  const tuple<int, bool> t(5, true);
112  EXPECT_THAT(t, Args<>(Eq(tuple<>())));
113  EXPECT_THAT(t, Not(Args<>(Ne(tuple<>()))));
114}
115
116TEST(ArgsTest, AcceptsOneTemplateArg) {
117  const tuple<int, bool> t(5, true);
118  EXPECT_THAT(t, Args<0>(Eq(make_tuple(5))));
119  EXPECT_THAT(t, Args<1>(Eq(make_tuple(true))));
120  EXPECT_THAT(t, Not(Args<1>(Eq(make_tuple(false)))));
121}
122
123TEST(ArgsTest, AcceptsTwoTemplateArgs) {
124  const tuple<short, int, long> t(4, 5, 6L);  // NOLINT
125
126  EXPECT_THAT(t, (Args<0, 1>(Lt())));
127  EXPECT_THAT(t, (Args<1, 2>(Lt())));
128  EXPECT_THAT(t, Not(Args<0, 2>(Gt())));
129}
130
131TEST(ArgsTest, AcceptsRepeatedTemplateArgs) {
132  const tuple<short, int, long> t(4, 5, 6L);  // NOLINT
133  EXPECT_THAT(t, (Args<0, 0>(Eq())));
134  EXPECT_THAT(t, Not(Args<1, 1>(Ne())));
135}
136
137TEST(ArgsTest, AcceptsDecreasingTemplateArgs) {
138  const tuple<short, int, long> t(4, 5, 6L);  // NOLINT
139  EXPECT_THAT(t, (Args<2, 0>(Gt())));
140  EXPECT_THAT(t, Not(Args<2, 1>(Lt())));
141}
142
143// The MATCHER*() macros trigger warning C4100 (unreferenced formal
144// parameter) in MSVC with -W4.  Unfortunately they cannot be fixed in
145// the macro definition, as the warnings are generated when the macro
146// is expanded and macro expansion cannot contain #pragma.  Therefore
147// we suppress them here.
148#ifdef _MSC_VER
149# pragma warning(push)
150# pragma warning(disable:4100)
151#endif
152
153MATCHER(SumIsZero, "") {
154  return get<0>(arg) + get<1>(arg) + get<2>(arg) == 0;
155}
156
157TEST(ArgsTest, AcceptsMoreTemplateArgsThanArityOfOriginalTuple) {
158  EXPECT_THAT(make_tuple(-1, 2), (Args<0, 0, 1>(SumIsZero())));
159  EXPECT_THAT(make_tuple(1, 2), Not(Args<0, 0, 1>(SumIsZero())));
160}
161
162TEST(ArgsTest, CanBeNested) {
163  const tuple<short, int, long, int> t(4, 5, 6L, 6);  // NOLINT
164  EXPECT_THAT(t, (Args<1, 2, 3>(Args<1, 2>(Eq()))));
165  EXPECT_THAT(t, (Args<0, 1, 3>(Args<0, 2>(Lt()))));
166}
167
168TEST(ArgsTest, CanMatchTupleByValue) {
169  typedef tuple<char, int, int> Tuple3;
170  const Matcher<Tuple3> m = Args<1, 2>(Lt());
171  EXPECT_TRUE(m.Matches(Tuple3('a', 1, 2)));
172  EXPECT_FALSE(m.Matches(Tuple3('b', 2, 2)));
173}
174
175TEST(ArgsTest, CanMatchTupleByReference) {
176  typedef tuple<char, char, int> Tuple3;
177  const Matcher<const Tuple3&> m = Args<0, 1>(Lt());
178  EXPECT_TRUE(m.Matches(Tuple3('a', 'b', 2)));
179  EXPECT_FALSE(m.Matches(Tuple3('b', 'b', 2)));
180}
181
182// Validates that arg is printed as str.
183MATCHER_P(PrintsAs, str, "") {
184  return testing::PrintToString(arg) == str;
185}
186
187TEST(ArgsTest, AcceptsTenTemplateArgs) {
188  EXPECT_THAT(make_tuple(0, 1L, 2, 3L, 4, 5, 6, 7, 8, 9),
189              (Args<9, 8, 7, 6, 5, 4, 3, 2, 1, 0>(
190                  PrintsAs("(9, 8, 7, 6, 5, 4, 3, 2, 1, 0)"))));
191  EXPECT_THAT(make_tuple(0, 1L, 2, 3L, 4, 5, 6, 7, 8, 9),
192              Not(Args<9, 8, 7, 6, 5, 4, 3, 2, 1, 0>(
193                      PrintsAs("(0, 8, 7, 6, 5, 4, 3, 2, 1, 0)"))));
194}
195
196TEST(ArgsTest, DescirbesSelfCorrectly) {
197  const Matcher<tuple<int, bool, char> > m = Args<2, 0>(Lt());
198  EXPECT_EQ("are a tuple whose fields (#2, #0) are a pair where "
199            "the first < the second",
200            Describe(m));
201}
202
203TEST(ArgsTest, DescirbesNestedArgsCorrectly) {
204  const Matcher<const tuple<int, bool, char, int>&> m =
205      Args<0, 2, 3>(Args<2, 0>(Lt()));
206  EXPECT_EQ("are a tuple whose fields (#0, #2, #3) are a tuple "
207            "whose fields (#2, #0) are a pair where the first < the second",
208            Describe(m));
209}
210
211TEST(ArgsTest, DescribesNegationCorrectly) {
212  const Matcher<tuple<int, char> > m = Args<1, 0>(Gt());
213  EXPECT_EQ("are a tuple whose fields (#1, #0) aren't a pair "
214            "where the first > the second",
215            DescribeNegation(m));
216}
217
218TEST(ArgsTest, ExplainsMatchResultWithoutInnerExplanation) {
219  const Matcher<tuple<bool, int, int> > m = Args<1, 2>(Eq());
220  EXPECT_EQ("whose fields (#1, #2) are (42, 42)",
221            Explain(m, make_tuple(false, 42, 42)));
222  EXPECT_EQ("whose fields (#1, #2) are (42, 43)",
223            Explain(m, make_tuple(false, 42, 43)));
224}
225
226// For testing Args<>'s explanation.
227class LessThanMatcher : public MatcherInterface<tuple<char, int> > {
228 public:
229  virtual void DescribeTo(::std::ostream* os) const {}
230
231  virtual bool MatchAndExplain(tuple<char, int> value,
232                               MatchResultListener* listener) const {
233    const int diff = get<0>(value) - get<1>(value);
234    if (diff > 0) {
235      *listener << "where the first value is " << diff
236                << " more than the second";
237    }
238    return diff < 0;
239  }
240};
241
242Matcher<tuple<char, int> > LessThan() {
243  return MakeMatcher(new LessThanMatcher);
244}
245
246TEST(ArgsTest, ExplainsMatchResultWithInnerExplanation) {
247  const Matcher<tuple<char, int, int> > m = Args<0, 2>(LessThan());
248  EXPECT_EQ("whose fields (#0, #2) are ('a' (97, 0x61), 42), "
249            "where the first value is 55 more than the second",
250            Explain(m, make_tuple('a', 42, 42)));
251  EXPECT_EQ("whose fields (#0, #2) are ('\\0', 43)",
252            Explain(m, make_tuple('\0', 42, 43)));
253}
254
255// For testing ExplainMatchResultTo().
256class GreaterThanMatcher : public MatcherInterface<int> {
257 public:
258  explicit GreaterThanMatcher(int rhs) : rhs_(rhs) {}
259
260  virtual void DescribeTo(::std::ostream* os) const {
261    *os << "is greater than " << rhs_;
262  }
263
264  virtual bool MatchAndExplain(int lhs,
265                               MatchResultListener* listener) const {
266    const int diff = lhs - rhs_;
267    if (diff > 0) {
268      *listener << "which is " << diff << " more than " << rhs_;
269    } else if (diff == 0) {
270      *listener << "which is the same as " << rhs_;
271    } else {
272      *listener << "which is " << -diff << " less than " << rhs_;
273    }
274
275    return lhs > rhs_;
276  }
277
278 private:
279  int rhs_;
280};
281
282Matcher<int> GreaterThan(int n) {
283  return MakeMatcher(new GreaterThanMatcher(n));
284}
285
286// Tests for ElementsAre().
287
288TEST(ElementsAreTest, CanDescribeExpectingNoElement) {
289  Matcher<const vector<int>&> m = ElementsAre();
290  EXPECT_EQ("is empty", Describe(m));
291}
292
293TEST(ElementsAreTest, CanDescribeExpectingOneElement) {
294  Matcher<vector<int> > m = ElementsAre(Gt(5));
295  EXPECT_EQ("has 1 element that is > 5", Describe(m));
296}
297
298TEST(ElementsAreTest, CanDescribeExpectingManyElements) {
299  Matcher<list<string> > m = ElementsAre(StrEq("one"), "two");
300  EXPECT_EQ("has 2 elements where\n"
301            "element #0 is equal to \"one\",\n"
302            "element #1 is equal to \"two\"", Describe(m));
303}
304
305TEST(ElementsAreTest, CanDescribeNegationOfExpectingNoElement) {
306  Matcher<vector<int> > m = ElementsAre();
307  EXPECT_EQ("isn't empty", DescribeNegation(m));
308}
309
310TEST(ElementsAreTest, CanDescribeNegationOfExpectingOneElment) {
311  Matcher<const list<int>& > m = ElementsAre(Gt(5));
312  EXPECT_EQ("doesn't have 1 element, or\n"
313            "element #0 isn't > 5", DescribeNegation(m));
314}
315
316TEST(ElementsAreTest, CanDescribeNegationOfExpectingManyElements) {
317  Matcher<const list<string>& > m = ElementsAre("one", "two");
318  EXPECT_EQ("doesn't have 2 elements, or\n"
319            "element #0 isn't equal to \"one\", or\n"
320            "element #1 isn't equal to \"two\"", DescribeNegation(m));
321}
322
323TEST(ElementsAreTest, DoesNotExplainTrivialMatch) {
324  Matcher<const list<int>& > m = ElementsAre(1, Ne(2));
325
326  list<int> test_list;
327  test_list.push_back(1);
328  test_list.push_back(3);
329  EXPECT_EQ("", Explain(m, test_list));  // No need to explain anything.
330}
331
332TEST(ElementsAreTest, ExplainsNonTrivialMatch) {
333  Matcher<const vector<int>& > m =
334      ElementsAre(GreaterThan(1), 0, GreaterThan(2));
335
336  const int a[] = { 10, 0, 100 };
337  vector<int> test_vector(a, a + GTEST_ARRAY_SIZE_(a));
338  EXPECT_EQ("whose element #0 matches, which is 9 more than 1,\n"
339            "and whose element #2 matches, which is 98 more than 2",
340            Explain(m, test_vector));
341}
342
343TEST(ElementsAreTest, CanExplainMismatchWrongSize) {
344  Matcher<const list<int>& > m = ElementsAre(1, 3);
345
346  list<int> test_list;
347  // No need to explain when the container is empty.
348  EXPECT_EQ("", Explain(m, test_list));
349
350  test_list.push_back(1);
351  EXPECT_EQ("which has 1 element", Explain(m, test_list));
352}
353
354TEST(ElementsAreTest, CanExplainMismatchRightSize) {
355  Matcher<const vector<int>& > m = ElementsAre(1, GreaterThan(5));
356
357  vector<int> v;
358  v.push_back(2);
359  v.push_back(1);
360  EXPECT_EQ("whose element #0 doesn't match", Explain(m, v));
361
362  v[0] = 1;
363  EXPECT_EQ("whose element #1 doesn't match, which is 4 less than 5",
364            Explain(m, v));
365}
366
367TEST(ElementsAreTest, MatchesOneElementVector) {
368  vector<string> test_vector;
369  test_vector.push_back("test string");
370
371  EXPECT_THAT(test_vector, ElementsAre(StrEq("test string")));
372}
373
374TEST(ElementsAreTest, MatchesOneElementList) {
375  list<string> test_list;
376  test_list.push_back("test string");
377
378  EXPECT_THAT(test_list, ElementsAre("test string"));
379}
380
381TEST(ElementsAreTest, MatchesThreeElementVector) {
382  vector<string> test_vector;
383  test_vector.push_back("one");
384  test_vector.push_back("two");
385  test_vector.push_back("three");
386
387  EXPECT_THAT(test_vector, ElementsAre("one", StrEq("two"), _));
388}
389
390TEST(ElementsAreTest, MatchesOneElementEqMatcher) {
391  vector<int> test_vector;
392  test_vector.push_back(4);
393
394  EXPECT_THAT(test_vector, ElementsAre(Eq(4)));
395}
396
397TEST(ElementsAreTest, MatchesOneElementAnyMatcher) {
398  vector<int> test_vector;
399  test_vector.push_back(4);
400
401  EXPECT_THAT(test_vector, ElementsAre(_));
402}
403
404TEST(ElementsAreTest, MatchesOneElementValue) {
405  vector<int> test_vector;
406  test_vector.push_back(4);
407
408  EXPECT_THAT(test_vector, ElementsAre(4));
409}
410
411TEST(ElementsAreTest, MatchesThreeElementsMixedMatchers) {
412  vector<int> test_vector;
413  test_vector.push_back(1);
414  test_vector.push_back(2);
415  test_vector.push_back(3);
416
417  EXPECT_THAT(test_vector, ElementsAre(1, Eq(2), _));
418}
419
420TEST(ElementsAreTest, MatchesTenElementVector) {
421  const int a[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
422  vector<int> test_vector(a, a + GTEST_ARRAY_SIZE_(a));
423
424  EXPECT_THAT(test_vector,
425              // The element list can contain values and/or matchers
426              // of different types.
427              ElementsAre(0, Ge(0), _, 3, 4, Ne(2), Eq(6), 7, 8, _));
428}
429
430TEST(ElementsAreTest, DoesNotMatchWrongSize) {
431  vector<string> test_vector;
432  test_vector.push_back("test string");
433  test_vector.push_back("test string");
434
435  Matcher<vector<string> > m = ElementsAre(StrEq("test string"));
436  EXPECT_FALSE(m.Matches(test_vector));
437}
438
439TEST(ElementsAreTest, DoesNotMatchWrongValue) {
440  vector<string> test_vector;
441  test_vector.push_back("other string");
442
443  Matcher<vector<string> > m = ElementsAre(StrEq("test string"));
444  EXPECT_FALSE(m.Matches(test_vector));
445}
446
447TEST(ElementsAreTest, DoesNotMatchWrongOrder) {
448  vector<string> test_vector;
449  test_vector.push_back("one");
450  test_vector.push_back("three");
451  test_vector.push_back("two");
452
453  Matcher<vector<string> > m = ElementsAre(
454    StrEq("one"), StrEq("two"), StrEq("three"));
455  EXPECT_FALSE(m.Matches(test_vector));
456}
457
458TEST(ElementsAreTest, WorksForNestedContainer) {
459  const char* strings[] = {
460    "Hi",
461    "world"
462  };
463
464  vector<list<char> > nested;
465  for (size_t i = 0; i < GTEST_ARRAY_SIZE_(strings); i++) {
466    nested.push_back(list<char>(strings[i], strings[i] + strlen(strings[i])));
467  }
468
469  EXPECT_THAT(nested, ElementsAre(ElementsAre('H', Ne('e')),
470                                  ElementsAre('w', 'o', _, _, 'd')));
471  EXPECT_THAT(nested, Not(ElementsAre(ElementsAre('H', 'e'),
472                                      ElementsAre('w', 'o', _, _, 'd'))));
473}
474
475TEST(ElementsAreTest, WorksWithByRefElementMatchers) {
476  int a[] = { 0, 1, 2 };
477  vector<int> v(a, a + GTEST_ARRAY_SIZE_(a));
478
479  EXPECT_THAT(v, ElementsAre(Ref(v[0]), Ref(v[1]), Ref(v[2])));
480  EXPECT_THAT(v, Not(ElementsAre(Ref(v[0]), Ref(v[1]), Ref(a[2]))));
481}
482
483TEST(ElementsAreTest, WorksWithContainerPointerUsingPointee) {
484  int a[] = { 0, 1, 2 };
485  vector<int> v(a, a + GTEST_ARRAY_SIZE_(a));
486
487  EXPECT_THAT(&v, Pointee(ElementsAre(0, 1, _)));
488  EXPECT_THAT(&v, Not(Pointee(ElementsAre(0, _, 3))));
489}
490
491TEST(ElementsAreTest, WorksWithNativeArrayPassedByReference) {
492  int array[] = { 0, 1, 2 };
493  EXPECT_THAT(array, ElementsAre(0, 1, _));
494  EXPECT_THAT(array, Not(ElementsAre(1, _, _)));
495  EXPECT_THAT(array, Not(ElementsAre(0, _)));
496}
497
498class NativeArrayPassedAsPointerAndSize {
499 public:
500  NativeArrayPassedAsPointerAndSize() {}
501
502  MOCK_METHOD2(Helper, void(int* array, int size));
503
504 private:
505  GTEST_DISALLOW_COPY_AND_ASSIGN_(NativeArrayPassedAsPointerAndSize);
506};
507
508TEST(ElementsAreTest, WorksWithNativeArrayPassedAsPointerAndSize) {
509  int array[] = { 0, 1 };
510  ::testing::tuple<int*, size_t> array_as_tuple(array, 2);
511  EXPECT_THAT(array_as_tuple, ElementsAre(0, 1));
512  EXPECT_THAT(array_as_tuple, Not(ElementsAre(0)));
513
514  NativeArrayPassedAsPointerAndSize helper;
515  EXPECT_CALL(helper, Helper(_, _))
516      .With(ElementsAre(0, 1));
517  helper.Helper(array, 2);
518}
519
520TEST(ElementsAreTest, WorksWithTwoDimensionalNativeArray) {
521  const char a2[][3] = { "hi", "lo" };
522  EXPECT_THAT(a2, ElementsAre(ElementsAre('h', 'i', '\0'),
523                              ElementsAre('l', 'o', '\0')));
524  EXPECT_THAT(a2, ElementsAre(StrEq("hi"), StrEq("lo")));
525  EXPECT_THAT(a2, ElementsAre(Not(ElementsAre('h', 'o', '\0')),
526                              ElementsAre('l', 'o', '\0')));
527}
528
529TEST(ElementsAreTest, AcceptsStringLiteral) {
530  string array[] = { "hi", "one", "two" };
531  EXPECT_THAT(array, ElementsAre("hi", "one", "two"));
532  EXPECT_THAT(array, Not(ElementsAre("hi", "one", "too")));
533}
534
535#ifndef _MSC_VER
536
537// The following test passes a value of type const char[] to a
538// function template that expects const T&.  Some versions of MSVC
539// generates a compiler error C2665 for that.  We believe it's a bug
540// in MSVC.  Therefore this test is #if-ed out for MSVC.
541
542// Declared here with the size unknown.  Defined AFTER the following test.
543extern const char kHi[];
544
545TEST(ElementsAreTest, AcceptsArrayWithUnknownSize) {
546  // The size of kHi is not known in this test, but ElementsAre() should
547  // still accept it.
548
549  string array1[] = { "hi" };
550  EXPECT_THAT(array1, ElementsAre(kHi));
551
552  string array2[] = { "ho" };
553  EXPECT_THAT(array2, Not(ElementsAre(kHi)));
554}
555
556const char kHi[] = "hi";
557
558#endif  // _MSC_VER
559
560TEST(ElementsAreTest, MakesCopyOfArguments) {
561  int x = 1;
562  int y = 2;
563  // This should make a copy of x and y.
564  ::testing::internal::ElementsAreMatcher<testing::tuple<int, int> >
565          polymorphic_matcher = ElementsAre(x, y);
566  // Changing x and y now shouldn't affect the meaning of the above matcher.
567  x = y = 0;
568  const int array1[] = { 1, 2 };
569  EXPECT_THAT(array1, polymorphic_matcher);
570  const int array2[] = { 0, 0 };
571  EXPECT_THAT(array2, Not(polymorphic_matcher));
572}
573
574
575// Tests for ElementsAreArray().  Since ElementsAreArray() shares most
576// of the implementation with ElementsAre(), we don't test it as
577// thoroughly here.
578
579TEST(ElementsAreArrayTest, CanBeCreatedWithValueArray) {
580  const int a[] = { 1, 2, 3 };
581
582  vector<int> test_vector(a, a + GTEST_ARRAY_SIZE_(a));
583  EXPECT_THAT(test_vector, ElementsAreArray(a));
584
585  test_vector[2] = 0;
586  EXPECT_THAT(test_vector, Not(ElementsAreArray(a)));
587}
588
589TEST(ElementsAreArrayTest, CanBeCreatedWithArraySize) {
590  const char* a[] = { "one", "two", "three" };
591
592  vector<string> test_vector(a, a + GTEST_ARRAY_SIZE_(a));
593  EXPECT_THAT(test_vector, ElementsAreArray(a, GTEST_ARRAY_SIZE_(a)));
594
595  const char** p = a;
596  test_vector[0] = "1";
597  EXPECT_THAT(test_vector, Not(ElementsAreArray(p, GTEST_ARRAY_SIZE_(a))));
598}
599
600TEST(ElementsAreArrayTest, CanBeCreatedWithoutArraySize) {
601  const char* a[] = { "one", "two", "three" };
602
603  vector<string> test_vector(a, a + GTEST_ARRAY_SIZE_(a));
604  EXPECT_THAT(test_vector, ElementsAreArray(a));
605
606  test_vector[0] = "1";
607  EXPECT_THAT(test_vector, Not(ElementsAreArray(a)));
608}
609
610TEST(ElementsAreArrayTest, CanBeCreatedWithMatcherArray) {
611  const Matcher<string> kMatcherArray[] =
612    { StrEq("one"), StrEq("two"), StrEq("three") };
613
614  vector<string> test_vector;
615  test_vector.push_back("one");
616  test_vector.push_back("two");
617  test_vector.push_back("three");
618  EXPECT_THAT(test_vector, ElementsAreArray(kMatcherArray));
619
620  test_vector.push_back("three");
621  EXPECT_THAT(test_vector, Not(ElementsAreArray(kMatcherArray)));
622}
623
624TEST(ElementsAreArrayTest, CanBeCreatedWithVector) {
625  const int a[] = { 1, 2, 3 };
626  vector<int> test_vector(a, a + GTEST_ARRAY_SIZE_(a));
627  const vector<int> expected(a, a + GTEST_ARRAY_SIZE_(a));
628  EXPECT_THAT(test_vector, ElementsAreArray(expected));
629  test_vector.push_back(4);
630  EXPECT_THAT(test_vector, Not(ElementsAreArray(expected)));
631}
632
633#if GTEST_HAS_STD_INITIALIZER_LIST_
634
635TEST(ElementsAreArrayTest, TakesInitializerList) {
636  const int a[5] = { 1, 2, 3, 4, 5 };
637  EXPECT_THAT(a, ElementsAreArray({ 1, 2, 3, 4, 5 }));
638  EXPECT_THAT(a, Not(ElementsAreArray({ 1, 2, 3, 5, 4 })));
639  EXPECT_THAT(a, Not(ElementsAreArray({ 1, 2, 3, 4, 6 })));
640}
641
642TEST(ElementsAreArrayTest, TakesInitializerListOfCStrings) {
643  const string a[5] = { "a", "b", "c", "d", "e" };
644  EXPECT_THAT(a, ElementsAreArray({ "a", "b", "c", "d", "e" }));
645  EXPECT_THAT(a, Not(ElementsAreArray({ "a", "b", "c", "e", "d" })));
646  EXPECT_THAT(a, Not(ElementsAreArray({ "a", "b", "c", "d", "ef" })));
647}
648
649TEST(ElementsAreArrayTest, TakesInitializerListOfSameTypedMatchers) {
650  const int a[5] = { 1, 2, 3, 4, 5 };
651  EXPECT_THAT(a, ElementsAreArray(
652      { Eq(1), Eq(2), Eq(3), Eq(4), Eq(5) }));
653  EXPECT_THAT(a, Not(ElementsAreArray(
654      { Eq(1), Eq(2), Eq(3), Eq(4), Eq(6) })));
655}
656
657TEST(ElementsAreArrayTest,
658     TakesInitializerListOfDifferentTypedMatchers) {
659  const int a[5] = { 1, 2, 3, 4, 5 };
660  // The compiler cannot infer the type of the initializer list if its
661  // elements have different types.  We must explicitly specify the
662  // unified element type in this case.
663  EXPECT_THAT(a, ElementsAreArray<Matcher<int> >(
664      { Eq(1), Ne(-2), Ge(3), Le(4), Eq(5) }));
665  EXPECT_THAT(a, Not(ElementsAreArray<Matcher<int> >(
666      { Eq(1), Ne(-2), Ge(3), Le(4), Eq(6) })));
667}
668
669#endif  // GTEST_HAS_STD_INITIALIZER_LIST_
670
671TEST(ElementsAreArrayTest, CanBeCreatedWithMatcherVector) {
672  const int a[] = { 1, 2, 3 };
673  const Matcher<int> kMatchers[] = { Eq(1), Eq(2), Eq(3) };
674  vector<int> test_vector(a, a + GTEST_ARRAY_SIZE_(a));
675  const vector<Matcher<int> > expected(
676      kMatchers, kMatchers + GTEST_ARRAY_SIZE_(kMatchers));
677  EXPECT_THAT(test_vector, ElementsAreArray(expected));
678  test_vector.push_back(4);
679  EXPECT_THAT(test_vector, Not(ElementsAreArray(expected)));
680}
681
682TEST(ElementsAreArrayTest, CanBeCreatedWithIteratorRange) {
683  const int a[] = { 1, 2, 3 };
684  const vector<int> test_vector(a, a + GTEST_ARRAY_SIZE_(a));
685  const vector<int> expected(a, a + GTEST_ARRAY_SIZE_(a));
686  EXPECT_THAT(test_vector, ElementsAreArray(expected.begin(), expected.end()));
687  // Pointers are iterators, too.
688  EXPECT_THAT(test_vector, ElementsAreArray(a, a + GTEST_ARRAY_SIZE_(a)));
689  // The empty range of NULL pointers should also be okay.
690  int* const null_int = NULL;
691  EXPECT_THAT(test_vector, Not(ElementsAreArray(null_int, null_int)));
692  EXPECT_THAT((vector<int>()), ElementsAreArray(null_int, null_int));
693}
694
695// Since ElementsAre() and ElementsAreArray() share much of the
696// implementation, we only do a sanity test for native arrays here.
697TEST(ElementsAreArrayTest, WorksWithNativeArray) {
698  ::std::string a[] = { "hi", "ho" };
699  ::std::string b[] = { "hi", "ho" };
700
701  EXPECT_THAT(a, ElementsAreArray(b));
702  EXPECT_THAT(a, ElementsAreArray(b, 2));
703  EXPECT_THAT(a, Not(ElementsAreArray(b, 1)));
704}
705
706TEST(ElementsAreArrayTest, SourceLifeSpan) {
707  const int a[] = { 1, 2, 3 };
708  vector<int> test_vector(a, a + GTEST_ARRAY_SIZE_(a));
709  vector<int> expect(a, a + GTEST_ARRAY_SIZE_(a));
710  ElementsAreArrayMatcher<int> matcher_maker =
711      ElementsAreArray(expect.begin(), expect.end());
712  EXPECT_THAT(test_vector, matcher_maker);
713  // Changing in place the values that initialized matcher_maker should not
714  // affect matcher_maker anymore. It should have made its own copy of them.
715  typedef vector<int>::iterator Iter;
716  for (Iter it = expect.begin(); it != expect.end(); ++it) { *it += 10; }
717  EXPECT_THAT(test_vector, matcher_maker);
718  test_vector.push_back(3);
719  EXPECT_THAT(test_vector, Not(matcher_maker));
720}
721
722// Tests for the MATCHER*() macro family.
723
724// Tests that a simple MATCHER() definition works.
725
726MATCHER(IsEven, "") { return (arg % 2) == 0; }
727
728TEST(MatcherMacroTest, Works) {
729  const Matcher<int> m = IsEven();
730  EXPECT_TRUE(m.Matches(6));
731  EXPECT_FALSE(m.Matches(7));
732
733  EXPECT_EQ("is even", Describe(m));
734  EXPECT_EQ("not (is even)", DescribeNegation(m));
735  EXPECT_EQ("", Explain(m, 6));
736  EXPECT_EQ("", Explain(m, 7));
737}
738
739// This also tests that the description string can reference 'negation'.
740MATCHER(IsEven2, negation ? "is odd" : "is even") {
741  if ((arg % 2) == 0) {
742    // Verifies that we can stream to result_listener, a listener
743    // supplied by the MATCHER macro implicitly.
744    *result_listener << "OK";
745    return true;
746  } else {
747    *result_listener << "% 2 == " << (arg % 2);
748    return false;
749  }
750}
751
752// This also tests that the description string can reference matcher
753// parameters.
754MATCHER_P2(EqSumOf, x, y,
755           string(negation ? "doesn't equal" : "equals") + " the sum of " +
756           PrintToString(x) + " and " + PrintToString(y)) {
757  if (arg == (x + y)) {
758    *result_listener << "OK";
759    return true;
760  } else {
761    // Verifies that we can stream to the underlying stream of
762    // result_listener.
763    if (result_listener->stream() != NULL) {
764      *result_listener->stream() << "diff == " << (x + y - arg);
765    }
766    return false;
767  }
768}
769
770// Tests that the matcher description can reference 'negation' and the
771// matcher parameters.
772TEST(MatcherMacroTest, DescriptionCanReferenceNegationAndParameters) {
773  const Matcher<int> m1 = IsEven2();
774  EXPECT_EQ("is even", Describe(m1));
775  EXPECT_EQ("is odd", DescribeNegation(m1));
776
777  const Matcher<int> m2 = EqSumOf(5, 9);
778  EXPECT_EQ("equals the sum of 5 and 9", Describe(m2));
779  EXPECT_EQ("doesn't equal the sum of 5 and 9", DescribeNegation(m2));
780}
781
782// Tests explaining match result in a MATCHER* macro.
783TEST(MatcherMacroTest, CanExplainMatchResult) {
784  const Matcher<int> m1 = IsEven2();
785  EXPECT_EQ("OK", Explain(m1, 4));
786  EXPECT_EQ("% 2 == 1", Explain(m1, 5));
787
788  const Matcher<int> m2 = EqSumOf(1, 2);
789  EXPECT_EQ("OK", Explain(m2, 3));
790  EXPECT_EQ("diff == -1", Explain(m2, 4));
791}
792
793// Tests that the body of MATCHER() can reference the type of the
794// value being matched.
795
796MATCHER(IsEmptyString, "") {
797  StaticAssertTypeEq< ::std::string, arg_type>();
798  return arg == "";
799}
800
801MATCHER(IsEmptyStringByRef, "") {
802  StaticAssertTypeEq<const ::std::string&, arg_type>();
803  return arg == "";
804}
805
806TEST(MatcherMacroTest, CanReferenceArgType) {
807  const Matcher< ::std::string> m1 = IsEmptyString();
808  EXPECT_TRUE(m1.Matches(""));
809
810  const Matcher<const ::std::string&> m2 = IsEmptyStringByRef();
811  EXPECT_TRUE(m2.Matches(""));
812}
813
814// Tests that MATCHER() can be used in a namespace.
815
816namespace matcher_test {
817MATCHER(IsOdd, "") { return (arg % 2) != 0; }
818}  // namespace matcher_test
819
820TEST(MatcherMacroTest, WorksInNamespace) {
821  Matcher<int> m = matcher_test::IsOdd();
822  EXPECT_FALSE(m.Matches(4));
823  EXPECT_TRUE(m.Matches(5));
824}
825
826// Tests that Value() can be used to compose matchers.
827MATCHER(IsPositiveOdd, "") {
828  return Value(arg, matcher_test::IsOdd()) && arg > 0;
829}
830
831TEST(MatcherMacroTest, CanBeComposedUsingValue) {
832  EXPECT_THAT(3, IsPositiveOdd());
833  EXPECT_THAT(4, Not(IsPositiveOdd()));
834  EXPECT_THAT(-1, Not(IsPositiveOdd()));
835}
836
837// Tests that a simple MATCHER_P() definition works.
838
839MATCHER_P(IsGreaterThan32And, n, "") { return arg > 32 && arg > n; }
840
841TEST(MatcherPMacroTest, Works) {
842  const Matcher<int> m = IsGreaterThan32And(5);
843  EXPECT_TRUE(m.Matches(36));
844  EXPECT_FALSE(m.Matches(5));
845
846  EXPECT_EQ("is greater than 32 and 5", Describe(m));
847  EXPECT_EQ("not (is greater than 32 and 5)", DescribeNegation(m));
848  EXPECT_EQ("", Explain(m, 36));
849  EXPECT_EQ("", Explain(m, 5));
850}
851
852// Tests that the description is calculated correctly from the matcher name.
853MATCHER_P(_is_Greater_Than32and_, n, "") { return arg > 32 && arg > n; }
854
855TEST(MatcherPMacroTest, GeneratesCorrectDescription) {
856  const Matcher<int> m = _is_Greater_Than32and_(5);
857
858  EXPECT_EQ("is greater than 32 and 5", Describe(m));
859  EXPECT_EQ("not (is greater than 32 and 5)", DescribeNegation(m));
860  EXPECT_EQ("", Explain(m, 36));
861  EXPECT_EQ("", Explain(m, 5));
862}
863
864// Tests that a MATCHER_P matcher can be explicitly instantiated with
865// a reference parameter type.
866
867class UncopyableFoo {
868 public:
869  explicit UncopyableFoo(char value) : value_(value) {}
870 private:
871  UncopyableFoo(const UncopyableFoo&);
872  void operator=(const UncopyableFoo&);
873
874  char value_;
875};
876
877MATCHER_P(ReferencesUncopyable, variable, "") { return &arg == &variable; }
878
879TEST(MatcherPMacroTest, WorksWhenExplicitlyInstantiatedWithReference) {
880  UncopyableFoo foo1('1'), foo2('2');
881  const Matcher<const UncopyableFoo&> m =
882      ReferencesUncopyable<const UncopyableFoo&>(foo1);
883
884  EXPECT_TRUE(m.Matches(foo1));
885  EXPECT_FALSE(m.Matches(foo2));
886
887  // We don't want the address of the parameter printed, as most
888  // likely it will just annoy the user.  If the address is
889  // interesting, the user should consider passing the parameter by
890  // pointer instead.
891  EXPECT_EQ("references uncopyable 1-byte object <31>", Describe(m));
892}
893
894
895// Tests that the body of MATCHER_Pn() can reference the parameter
896// types.
897
898MATCHER_P3(ParamTypesAreIntLongAndChar, foo, bar, baz, "") {
899  StaticAssertTypeEq<int, foo_type>();
900  StaticAssertTypeEq<long, bar_type>();  // NOLINT
901  StaticAssertTypeEq<char, baz_type>();
902  return arg == 0;
903}
904
905TEST(MatcherPnMacroTest, CanReferenceParamTypes) {
906  EXPECT_THAT(0, ParamTypesAreIntLongAndChar(10, 20L, 'a'));
907}
908
909// Tests that a MATCHER_Pn matcher can be explicitly instantiated with
910// reference parameter types.
911
912MATCHER_P2(ReferencesAnyOf, variable1, variable2, "") {
913  return &arg == &variable1 || &arg == &variable2;
914}
915
916TEST(MatcherPnMacroTest, WorksWhenExplicitlyInstantiatedWithReferences) {
917  UncopyableFoo foo1('1'), foo2('2'), foo3('3');
918  const Matcher<const UncopyableFoo&> m =
919      ReferencesAnyOf<const UncopyableFoo&, const UncopyableFoo&>(foo1, foo2);
920
921  EXPECT_TRUE(m.Matches(foo1));
922  EXPECT_TRUE(m.Matches(foo2));
923  EXPECT_FALSE(m.Matches(foo3));
924}
925
926TEST(MatcherPnMacroTest,
927     GeneratesCorretDescriptionWhenExplicitlyInstantiatedWithReferences) {
928  UncopyableFoo foo1('1'), foo2('2');
929  const Matcher<const UncopyableFoo&> m =
930      ReferencesAnyOf<const UncopyableFoo&, const UncopyableFoo&>(foo1, foo2);
931
932  // We don't want the addresses of the parameters printed, as most
933  // likely they will just annoy the user.  If the addresses are
934  // interesting, the user should consider passing the parameters by
935  // pointers instead.
936  EXPECT_EQ("references any of (1-byte object <31>, 1-byte object <32>)",
937            Describe(m));
938}
939
940// Tests that a simple MATCHER_P2() definition works.
941
942MATCHER_P2(IsNotInClosedRange, low, hi, "") { return arg < low || arg > hi; }
943
944TEST(MatcherPnMacroTest, Works) {
945  const Matcher<const long&> m = IsNotInClosedRange(10, 20);  // NOLINT
946  EXPECT_TRUE(m.Matches(36L));
947  EXPECT_FALSE(m.Matches(15L));
948
949  EXPECT_EQ("is not in closed range (10, 20)", Describe(m));
950  EXPECT_EQ("not (is not in closed range (10, 20))", DescribeNegation(m));
951  EXPECT_EQ("", Explain(m, 36L));
952  EXPECT_EQ("", Explain(m, 15L));
953}
954
955// Tests that MATCHER*() definitions can be overloaded on the number
956// of parameters; also tests MATCHER_Pn() where n >= 3.
957
958MATCHER(EqualsSumOf, "") { return arg == 0; }
959MATCHER_P(EqualsSumOf, a, "") { return arg == a; }
960MATCHER_P2(EqualsSumOf, a, b, "") { return arg == a + b; }
961MATCHER_P3(EqualsSumOf, a, b, c, "") { return arg == a + b + c; }
962MATCHER_P4(EqualsSumOf, a, b, c, d, "") { return arg == a + b + c + d; }
963MATCHER_P5(EqualsSumOf, a, b, c, d, e, "") { return arg == a + b + c + d + e; }
964MATCHER_P6(EqualsSumOf, a, b, c, d, e, f, "") {
965  return arg == a + b + c + d + e + f;
966}
967MATCHER_P7(EqualsSumOf, a, b, c, d, e, f, g, "") {
968  return arg == a + b + c + d + e + f + g;
969}
970MATCHER_P8(EqualsSumOf, a, b, c, d, e, f, g, h, "") {
971  return arg == a + b + c + d + e + f + g + h;
972}
973MATCHER_P9(EqualsSumOf, a, b, c, d, e, f, g, h, i, "") {
974  return arg == a + b + c + d + e + f + g + h + i;
975}
976MATCHER_P10(EqualsSumOf, a, b, c, d, e, f, g, h, i, j, "") {
977  return arg == a + b + c + d + e + f + g + h + i + j;
978}
979
980TEST(MatcherPnMacroTest, CanBeOverloadedOnNumberOfParameters) {
981  EXPECT_THAT(0, EqualsSumOf());
982  EXPECT_THAT(1, EqualsSumOf(1));
983  EXPECT_THAT(12, EqualsSumOf(10, 2));
984  EXPECT_THAT(123, EqualsSumOf(100, 20, 3));
985  EXPECT_THAT(1234, EqualsSumOf(1000, 200, 30, 4));
986  EXPECT_THAT(12345, EqualsSumOf(10000, 2000, 300, 40, 5));
987  EXPECT_THAT("abcdef",
988              EqualsSumOf(::std::string("a"), 'b', 'c', "d", "e", 'f'));
989  EXPECT_THAT("abcdefg",
990              EqualsSumOf(::std::string("a"), 'b', 'c', "d", "e", 'f', 'g'));
991  EXPECT_THAT("abcdefgh",
992              EqualsSumOf(::std::string("a"), 'b', 'c', "d", "e", 'f', 'g',
993                          "h"));
994  EXPECT_THAT("abcdefghi",
995              EqualsSumOf(::std::string("a"), 'b', 'c', "d", "e", 'f', 'g',
996                          "h", 'i'));
997  EXPECT_THAT("abcdefghij",
998              EqualsSumOf(::std::string("a"), 'b', 'c', "d", "e", 'f', 'g',
999                          "h", 'i', ::std::string("j")));
1000
1001  EXPECT_THAT(1, Not(EqualsSumOf()));
1002  EXPECT_THAT(-1, Not(EqualsSumOf(1)));
1003  EXPECT_THAT(-12, Not(EqualsSumOf(10, 2)));
1004  EXPECT_THAT(-123, Not(EqualsSumOf(100, 20, 3)));
1005  EXPECT_THAT(-1234, Not(EqualsSumOf(1000, 200, 30, 4)));
1006  EXPECT_THAT(-12345, Not(EqualsSumOf(10000, 2000, 300, 40, 5)));
1007  EXPECT_THAT("abcdef ",
1008              Not(EqualsSumOf(::std::string("a"), 'b', 'c', "d", "e", 'f')));
1009  EXPECT_THAT("abcdefg ",
1010              Not(EqualsSumOf(::std::string("a"), 'b', 'c', "d", "e", 'f',
1011                              'g')));
1012  EXPECT_THAT("abcdefgh ",
1013              Not(EqualsSumOf(::std::string("a"), 'b', 'c', "d", "e", 'f', 'g',
1014                              "h")));
1015  EXPECT_THAT("abcdefghi ",
1016              Not(EqualsSumOf(::std::string("a"), 'b', 'c', "d", "e", 'f', 'g',
1017                              "h", 'i')));
1018  EXPECT_THAT("abcdefghij ",
1019              Not(EqualsSumOf(::std::string("a"), 'b', 'c', "d", "e", 'f', 'g',
1020                              "h", 'i', ::std::string("j"))));
1021}
1022
1023// Tests that a MATCHER_Pn() definition can be instantiated with any
1024// compatible parameter types.
1025TEST(MatcherPnMacroTest, WorksForDifferentParameterTypes) {
1026  EXPECT_THAT(123, EqualsSumOf(100L, 20, static_cast<char>(3)));
1027  EXPECT_THAT("abcd", EqualsSumOf(::std::string("a"), "b", 'c', "d"));
1028
1029  EXPECT_THAT(124, Not(EqualsSumOf(100L, 20, static_cast<char>(3))));
1030  EXPECT_THAT("abcde", Not(EqualsSumOf(::std::string("a"), "b", 'c', "d")));
1031}
1032
1033// Tests that the matcher body can promote the parameter types.
1034
1035MATCHER_P2(EqConcat, prefix, suffix, "") {
1036  // The following lines promote the two parameters to desired types.
1037  std::string prefix_str(prefix);
1038  char suffix_char = static_cast<char>(suffix);
1039  return arg == prefix_str + suffix_char;
1040}
1041
1042TEST(MatcherPnMacroTest, SimpleTypePromotion) {
1043  Matcher<std::string> no_promo =
1044      EqConcat(std::string("foo"), 't');
1045  Matcher<const std::string&> promo =
1046      EqConcat("foo", static_cast<int>('t'));
1047  EXPECT_FALSE(no_promo.Matches("fool"));
1048  EXPECT_FALSE(promo.Matches("fool"));
1049  EXPECT_TRUE(no_promo.Matches("foot"));
1050  EXPECT_TRUE(promo.Matches("foot"));
1051}
1052
1053// Verifies the type of a MATCHER*.
1054
1055TEST(MatcherPnMacroTest, TypesAreCorrect) {
1056  // EqualsSumOf() must be assignable to a EqualsSumOfMatcher variable.
1057  EqualsSumOfMatcher a0 = EqualsSumOf();
1058
1059  // EqualsSumOf(1) must be assignable to a EqualsSumOfMatcherP variable.
1060  EqualsSumOfMatcherP<int> a1 = EqualsSumOf(1);
1061
1062  // EqualsSumOf(p1, ..., pk) must be assignable to a EqualsSumOfMatcherPk
1063  // variable, and so on.
1064  EqualsSumOfMatcherP2<int, char> a2 = EqualsSumOf(1, '2');
1065  EqualsSumOfMatcherP3<int, int, char> a3 = EqualsSumOf(1, 2, '3');
1066  EqualsSumOfMatcherP4<int, int, int, char> a4 = EqualsSumOf(1, 2, 3, '4');
1067  EqualsSumOfMatcherP5<int, int, int, int, char> a5 =
1068      EqualsSumOf(1, 2, 3, 4, '5');
1069  EqualsSumOfMatcherP6<int, int, int, int, int, char> a6 =
1070      EqualsSumOf(1, 2, 3, 4, 5, '6');
1071  EqualsSumOfMatcherP7<int, int, int, int, int, int, char> a7 =
1072      EqualsSumOf(1, 2, 3, 4, 5, 6, '7');
1073  EqualsSumOfMatcherP8<int, int, int, int, int, int, int, char> a8 =
1074      EqualsSumOf(1, 2, 3, 4, 5, 6, 7, '8');
1075  EqualsSumOfMatcherP9<int, int, int, int, int, int, int, int, char> a9 =
1076      EqualsSumOf(1, 2, 3, 4, 5, 6, 7, 8, '9');
1077  EqualsSumOfMatcherP10<int, int, int, int, int, int, int, int, int, char> a10 =
1078      EqualsSumOf(1, 2, 3, 4, 5, 6, 7, 8, 9, '0');
1079
1080  // Avoid "unused variable" warnings.
1081  (void)a0;
1082  (void)a1;
1083  (void)a2;
1084  (void)a3;
1085  (void)a4;
1086  (void)a5;
1087  (void)a6;
1088  (void)a7;
1089  (void)a8;
1090  (void)a9;
1091  (void)a10;
1092}
1093
1094// Tests that matcher-typed parameters can be used in Value() inside a
1095// MATCHER_Pn definition.
1096
1097// Succeeds if arg matches exactly 2 of the 3 matchers.
1098MATCHER_P3(TwoOf, m1, m2, m3, "") {
1099  const int count = static_cast<int>(Value(arg, m1))
1100      + static_cast<int>(Value(arg, m2)) + static_cast<int>(Value(arg, m3));
1101  return count == 2;
1102}
1103
1104TEST(MatcherPnMacroTest, CanUseMatcherTypedParameterInValue) {
1105  EXPECT_THAT(42, TwoOf(Gt(0), Lt(50), Eq(10)));
1106  EXPECT_THAT(0, Not(TwoOf(Gt(-1), Lt(1), Eq(0))));
1107}
1108
1109// Tests Contains().
1110
1111TEST(ContainsTest, ListMatchesWhenElementIsInContainer) {
1112  list<int> some_list;
1113  some_list.push_back(3);
1114  some_list.push_back(1);
1115  some_list.push_back(2);
1116  EXPECT_THAT(some_list, Contains(1));
1117  EXPECT_THAT(some_list, Contains(Gt(2.5)));
1118  EXPECT_THAT(some_list, Contains(Eq(2.0f)));
1119
1120  list<string> another_list;
1121  another_list.push_back("fee");
1122  another_list.push_back("fie");
1123  another_list.push_back("foe");
1124  another_list.push_back("fum");
1125  EXPECT_THAT(another_list, Contains(string("fee")));
1126}
1127
1128TEST(ContainsTest, ListDoesNotMatchWhenElementIsNotInContainer) {
1129  list<int> some_list;
1130  some_list.push_back(3);
1131  some_list.push_back(1);
1132  EXPECT_THAT(some_list, Not(Contains(4)));
1133}
1134
1135TEST(ContainsTest, SetMatchesWhenElementIsInContainer) {
1136  set<int> some_set;
1137  some_set.insert(3);
1138  some_set.insert(1);
1139  some_set.insert(2);
1140  EXPECT_THAT(some_set, Contains(Eq(1.0)));
1141  EXPECT_THAT(some_set, Contains(Eq(3.0f)));
1142  EXPECT_THAT(some_set, Contains(2));
1143
1144  set<const char*> another_set;
1145  another_set.insert("fee");
1146  another_set.insert("fie");
1147  another_set.insert("foe");
1148  another_set.insert("fum");
1149  EXPECT_THAT(another_set, Contains(Eq(string("fum"))));
1150}
1151
1152TEST(ContainsTest, SetDoesNotMatchWhenElementIsNotInContainer) {
1153  set<int> some_set;
1154  some_set.insert(3);
1155  some_set.insert(1);
1156  EXPECT_THAT(some_set, Not(Contains(4)));
1157
1158  set<const char*> c_string_set;
1159  c_string_set.insert("hello");
1160  EXPECT_THAT(c_string_set, Not(Contains(string("hello").c_str())));
1161}
1162
1163TEST(ContainsTest, ExplainsMatchResultCorrectly) {
1164  const int a[2] = { 1, 2 };
1165  Matcher<const int (&)[2]> m = Contains(2);
1166  EXPECT_EQ("whose element #1 matches", Explain(m, a));
1167
1168  m = Contains(3);
1169  EXPECT_EQ("", Explain(m, a));
1170
1171  m = Contains(GreaterThan(0));
1172  EXPECT_EQ("whose element #0 matches, which is 1 more than 0", Explain(m, a));
1173
1174  m = Contains(GreaterThan(10));
1175  EXPECT_EQ("", Explain(m, a));
1176}
1177
1178TEST(ContainsTest, DescribesItselfCorrectly) {
1179  Matcher<vector<int> > m = Contains(1);
1180  EXPECT_EQ("contains at least one element that is equal to 1", Describe(m));
1181
1182  Matcher<vector<int> > m2 = Not(m);
1183  EXPECT_EQ("doesn't contain any element that is equal to 1", Describe(m2));
1184}
1185
1186TEST(ContainsTest, MapMatchesWhenElementIsInContainer) {
1187  map<const char*, int> my_map;
1188  const char* bar = "a string";
1189  my_map[bar] = 2;
1190  EXPECT_THAT(my_map, Contains(pair<const char* const, int>(bar, 2)));
1191
1192  map<string, int> another_map;
1193  another_map["fee"] = 1;
1194  another_map["fie"] = 2;
1195  another_map["foe"] = 3;
1196  another_map["fum"] = 4;
1197  EXPECT_THAT(another_map, Contains(pair<const string, int>(string("fee"), 1)));
1198  EXPECT_THAT(another_map, Contains(pair<const string, int>("fie", 2)));
1199}
1200
1201TEST(ContainsTest, MapDoesNotMatchWhenElementIsNotInContainer) {
1202  map<int, int> some_map;
1203  some_map[1] = 11;
1204  some_map[2] = 22;
1205  EXPECT_THAT(some_map, Not(Contains(pair<const int, int>(2, 23))));
1206}
1207
1208TEST(ContainsTest, ArrayMatchesWhenElementIsInContainer) {
1209  const char* string_array[] = { "fee", "fie", "foe", "fum" };
1210  EXPECT_THAT(string_array, Contains(Eq(string("fum"))));
1211}
1212
1213TEST(ContainsTest, ArrayDoesNotMatchWhenElementIsNotInContainer) {
1214  int int_array[] = { 1, 2, 3, 4 };
1215  EXPECT_THAT(int_array, Not(Contains(5)));
1216}
1217
1218TEST(ContainsTest, AcceptsMatcher) {
1219  const int a[] = { 1, 2, 3 };
1220  EXPECT_THAT(a, Contains(Gt(2)));
1221  EXPECT_THAT(a, Not(Contains(Gt(4))));
1222}
1223
1224TEST(ContainsTest, WorksForNativeArrayAsTuple) {
1225  const int a[] = { 1, 2 };
1226  const int* const pointer = a;
1227  EXPECT_THAT(make_tuple(pointer, 2), Contains(1));
1228  EXPECT_THAT(make_tuple(pointer, 2), Not(Contains(Gt(3))));
1229}
1230
1231TEST(ContainsTest, WorksForTwoDimensionalNativeArray) {
1232  int a[][3] = { { 1, 2, 3 }, { 4, 5, 6 } };
1233  EXPECT_THAT(a, Contains(ElementsAre(4, 5, 6)));
1234  EXPECT_THAT(a, Contains(Contains(5)));
1235  EXPECT_THAT(a, Not(Contains(ElementsAre(3, 4, 5))));
1236  EXPECT_THAT(a, Contains(Not(Contains(5))));
1237}
1238
1239TEST(AllOfTest, HugeMatcher) {
1240  // Verify that using AllOf with many arguments doesn't cause
1241  // the compiler to exceed template instantiation depth limit.
1242  EXPECT_THAT(0, testing::AllOf(_, _, _, _, _, _, _, _, _,
1243                                testing::AllOf(_, _, _, _, _, _, _, _, _, _)));
1244}
1245
1246TEST(AnyOfTest, HugeMatcher) {
1247  // Verify that using AnyOf with many arguments doesn't cause
1248  // the compiler to exceed template instantiation depth limit.
1249  EXPECT_THAT(0, testing::AnyOf(_, _, _, _, _, _, _, _, _,
1250                                testing::AnyOf(_, _, _, _, _, _, _, _, _, _)));
1251}
1252
1253namespace adl_test {
1254
1255// Verifies that the implementation of ::testing::AllOf and ::testing::AnyOf
1256// don't issue unqualified recursive calls.  If they do, the argument dependent
1257// name lookup will cause AllOf/AnyOf in the 'adl_test' namespace to be found
1258// as a candidate and the compilation will break due to an ambiguous overload.
1259
1260// The matcher must be in the same namespace as AllOf/AnyOf to make argument
1261// dependent lookup find those.
1262MATCHER(M, "") { return true; }
1263
1264template <typename T1, typename T2>
1265bool AllOf(const T1& t1, const T2& t2) { return true; }
1266
1267TEST(AllOfTest, DoesNotCallAllOfUnqualified) {
1268  EXPECT_THAT(42, testing::AllOf(
1269      M(), M(), M(), M(), M(), M(), M(), M(), M(), M()));
1270}
1271
1272template <typename T1, typename T2> bool
1273AnyOf(const T1& t1, const T2& t2) { return true; }
1274
1275TEST(AnyOfTest, DoesNotCallAnyOfUnqualified) {
1276  EXPECT_THAT(42, testing::AnyOf(
1277      M(), M(), M(), M(), M(), M(), M(), M(), M(), M()));
1278}
1279
1280}  // namespace adl_test
1281
1282#ifdef _MSC_VER
1283# pragma warning(pop)
1284#endif
1285
1286}  // namespace
1287