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