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