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