• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright 2008, Google Inc.
2 // All rights reserved.
3 //
4 // Redistribution and use in source and binary forms, with or without
5 // modification, are permitted provided that the following conditions are
6 // met:
7 //
8 //     * Redistributions of source code must retain the above copyright
9 // notice, this list of conditions and the following disclaimer.
10 //     * Redistributions in binary form must reproduce the above
11 // copyright notice, this list of conditions and the following disclaimer
12 // in the documentation and/or other materials provided with the
13 // distribution.
14 //     * Neither the name of Google Inc. nor the names of its
15 // contributors may be used to endorse or promote products derived from
16 // this software without specific prior written permission.
17 //
18 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29 
30 // Google Mock - a framework for writing C++ mock classes.
31 //
32 // This file tests the built-in matchers generated by a script.
33 
34 // 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-generated-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&> m =
768       ReferencesAnyOf<const UncopyableFoo&, const UncopyableFoo&>(foo1, foo2);
769 
770   EXPECT_TRUE(m.Matches(foo1));
771   EXPECT_TRUE(m.Matches(foo2));
772   EXPECT_FALSE(m.Matches(foo3));
773 }
774 
TEST(MatcherPnMacroTest,GeneratesCorretDescriptionWhenExplicitlyInstantiatedWithReferences)775 TEST(MatcherPnMacroTest,
776      GeneratesCorretDescriptionWhenExplicitlyInstantiatedWithReferences) {
777   UncopyableFoo foo1('1'), foo2('2');
778   const Matcher<const UncopyableFoo&> m =
779       ReferencesAnyOf<const UncopyableFoo&, const UncopyableFoo&>(foo1, foo2);
780 
781   // We don't want the addresses of the parameters printed, as most
782   // likely they will just annoy the user.  If the addresses are
783   // interesting, the user should consider passing the parameters by
784   // pointers instead.
785   EXPECT_EQ("references any of (1-byte object <31>, 1-byte object <32>)",
786             Describe(m));
787 }
788 
789 // Tests that a simple MATCHER_P2() definition works.
790 
791 MATCHER_P2(IsNotInClosedRange, low, hi, "") { return arg < low || arg > hi; }
792 
TEST(MatcherPnMacroTest,Works)793 TEST(MatcherPnMacroTest, Works) {
794   const Matcher<const long&> m = IsNotInClosedRange(10, 20);  // NOLINT
795   EXPECT_TRUE(m.Matches(36L));
796   EXPECT_FALSE(m.Matches(15L));
797 
798   EXPECT_EQ("is not in closed range (10, 20)", Describe(m));
799   EXPECT_EQ("not (is not in closed range (10, 20))", DescribeNegation(m));
800   EXPECT_EQ("", Explain(m, 36L));
801   EXPECT_EQ("", Explain(m, 15L));
802 }
803 
804 // Tests that MATCHER*() definitions can be overloaded on the number
805 // of parameters; also tests MATCHER_Pn() where n >= 3.
806 
807 MATCHER(EqualsSumOf, "") { return arg == 0; }
808 MATCHER_P(EqualsSumOf, a, "") { return arg == a; }
809 MATCHER_P2(EqualsSumOf, a, b, "") { return arg == a + b; }
810 MATCHER_P3(EqualsSumOf, a, b, c, "") { return arg == a + b + c; }
811 MATCHER_P4(EqualsSumOf, a, b, c, d, "") { return arg == a + b + c + d; }
812 MATCHER_P5(EqualsSumOf, a, b, c, d, e, "") { return arg == a + b + c + d + e; }
813 MATCHER_P6(EqualsSumOf, a, b, c, d, e, f, "") {
814   return arg == a + b + c + d + e + f;
815 }
816 MATCHER_P7(EqualsSumOf, a, b, c, d, e, f, g, "") {
817   return arg == a + b + c + d + e + f + g;
818 }
819 MATCHER_P8(EqualsSumOf, a, b, c, d, e, f, g, h, "") {
820   return arg == a + b + c + d + e + f + g + h;
821 }
822 MATCHER_P9(EqualsSumOf, a, b, c, d, e, f, g, h, i, "") {
823   return arg == a + b + c + d + e + f + g + h + i;
824 }
825 MATCHER_P10(EqualsSumOf, a, b, c, d, e, f, g, h, i, j, "") {
826   return arg == a + b + c + d + e + f + g + h + i + j;
827 }
828 
TEST(MatcherPnMacroTest,CanBeOverloadedOnNumberOfParameters)829 TEST(MatcherPnMacroTest, CanBeOverloadedOnNumberOfParameters) {
830   EXPECT_THAT(0, EqualsSumOf());
831   EXPECT_THAT(1, EqualsSumOf(1));
832   EXPECT_THAT(12, EqualsSumOf(10, 2));
833   EXPECT_THAT(123, EqualsSumOf(100, 20, 3));
834   EXPECT_THAT(1234, EqualsSumOf(1000, 200, 30, 4));
835   EXPECT_THAT(12345, EqualsSumOf(10000, 2000, 300, 40, 5));
836   EXPECT_THAT("abcdef",
837               EqualsSumOf(::std::string("a"), 'b', 'c', "d", "e", 'f'));
838   EXPECT_THAT("abcdefg",
839               EqualsSumOf(::std::string("a"), 'b', 'c', "d", "e", 'f', 'g'));
840   EXPECT_THAT("abcdefgh",
841               EqualsSumOf(::std::string("a"), 'b', 'c', "d", "e", 'f', 'g',
842                           "h"));
843   EXPECT_THAT("abcdefghi",
844               EqualsSumOf(::std::string("a"), 'b', 'c', "d", "e", 'f', 'g',
845                           "h", 'i'));
846   EXPECT_THAT("abcdefghij",
847               EqualsSumOf(::std::string("a"), 'b', 'c', "d", "e", 'f', 'g',
848                           "h", 'i', ::std::string("j")));
849 
850   EXPECT_THAT(1, Not(EqualsSumOf()));
851   EXPECT_THAT(-1, Not(EqualsSumOf(1)));
852   EXPECT_THAT(-12, Not(EqualsSumOf(10, 2)));
853   EXPECT_THAT(-123, Not(EqualsSumOf(100, 20, 3)));
854   EXPECT_THAT(-1234, Not(EqualsSumOf(1000, 200, 30, 4)));
855   EXPECT_THAT(-12345, Not(EqualsSumOf(10000, 2000, 300, 40, 5)));
856   EXPECT_THAT("abcdef ",
857               Not(EqualsSumOf(::std::string("a"), 'b', 'c', "d", "e", 'f')));
858   EXPECT_THAT("abcdefg ",
859               Not(EqualsSumOf(::std::string("a"), 'b', 'c', "d", "e", 'f',
860                               'g')));
861   EXPECT_THAT("abcdefgh ",
862               Not(EqualsSumOf(::std::string("a"), 'b', 'c', "d", "e", 'f', 'g',
863                               "h")));
864   EXPECT_THAT("abcdefghi ",
865               Not(EqualsSumOf(::std::string("a"), 'b', 'c', "d", "e", 'f', 'g',
866                               "h", 'i')));
867   EXPECT_THAT("abcdefghij ",
868               Not(EqualsSumOf(::std::string("a"), 'b', 'c', "d", "e", 'f', 'g',
869                               "h", 'i', ::std::string("j"))));
870 }
871 
872 // Tests that a MATCHER_Pn() definition can be instantiated with any
873 // compatible parameter types.
TEST(MatcherPnMacroTest,WorksForDifferentParameterTypes)874 TEST(MatcherPnMacroTest, WorksForDifferentParameterTypes) {
875   EXPECT_THAT(123, EqualsSumOf(100L, 20, static_cast<char>(3)));
876   EXPECT_THAT("abcd", EqualsSumOf(::std::string("a"), "b", 'c', "d"));
877 
878   EXPECT_THAT(124, Not(EqualsSumOf(100L, 20, static_cast<char>(3))));
879   EXPECT_THAT("abcde", Not(EqualsSumOf(::std::string("a"), "b", 'c', "d")));
880 }
881 
882 // Tests that the matcher body can promote the parameter types.
883 
884 MATCHER_P2(EqConcat, prefix, suffix, "") {
885   // The following lines promote the two parameters to desired types.
886   std::string prefix_str(prefix);
887   char suffix_char = static_cast<char>(suffix);
888   return arg == prefix_str + suffix_char;
889 }
890 
TEST(MatcherPnMacroTest,SimpleTypePromotion)891 TEST(MatcherPnMacroTest, SimpleTypePromotion) {
892   Matcher<std::string> no_promo =
893       EqConcat(std::string("foo"), 't');
894   Matcher<const std::string&> promo =
895       EqConcat("foo", static_cast<int>('t'));
896   EXPECT_FALSE(no_promo.Matches("fool"));
897   EXPECT_FALSE(promo.Matches("fool"));
898   EXPECT_TRUE(no_promo.Matches("foot"));
899   EXPECT_TRUE(promo.Matches("foot"));
900 }
901 
902 // Verifies the type of a MATCHER*.
903 
TEST(MatcherPnMacroTest,TypesAreCorrect)904 TEST(MatcherPnMacroTest, TypesAreCorrect) {
905   // EqualsSumOf() must be assignable to a EqualsSumOfMatcher variable.
906   EqualsSumOfMatcher a0 = EqualsSumOf();
907 
908   // EqualsSumOf(1) must be assignable to a EqualsSumOfMatcherP variable.
909   EqualsSumOfMatcherP<int> a1 = EqualsSumOf(1);
910 
911   // EqualsSumOf(p1, ..., pk) must be assignable to a EqualsSumOfMatcherPk
912   // variable, and so on.
913   EqualsSumOfMatcherP2<int, char> a2 = EqualsSumOf(1, '2');
914   EqualsSumOfMatcherP3<int, int, char> a3 = EqualsSumOf(1, 2, '3');
915   EqualsSumOfMatcherP4<int, int, int, char> a4 = EqualsSumOf(1, 2, 3, '4');
916   EqualsSumOfMatcherP5<int, int, int, int, char> a5 =
917       EqualsSumOf(1, 2, 3, 4, '5');
918   EqualsSumOfMatcherP6<int, int, int, int, int, char> a6 =
919       EqualsSumOf(1, 2, 3, 4, 5, '6');
920   EqualsSumOfMatcherP7<int, int, int, int, int, int, char> a7 =
921       EqualsSumOf(1, 2, 3, 4, 5, 6, '7');
922   EqualsSumOfMatcherP8<int, int, int, int, int, int, int, char> a8 =
923       EqualsSumOf(1, 2, 3, 4, 5, 6, 7, '8');
924   EqualsSumOfMatcherP9<int, int, int, int, int, int, int, int, char> a9 =
925       EqualsSumOf(1, 2, 3, 4, 5, 6, 7, 8, '9');
926   EqualsSumOfMatcherP10<int, int, int, int, int, int, int, int, int, char> a10 =
927       EqualsSumOf(1, 2, 3, 4, 5, 6, 7, 8, 9, '0');
928 
929   // Avoid "unused variable" warnings.
930   (void)a0;
931   (void)a1;
932   (void)a2;
933   (void)a3;
934   (void)a4;
935   (void)a5;
936   (void)a6;
937   (void)a7;
938   (void)a8;
939   (void)a9;
940   (void)a10;
941 }
942 
943 // Tests that matcher-typed parameters can be used in Value() inside a
944 // MATCHER_Pn definition.
945 
946 // Succeeds if arg matches exactly 2 of the 3 matchers.
947 MATCHER_P3(TwoOf, m1, m2, m3, "") {
948   const int count = static_cast<int>(Value(arg, m1))
949       + static_cast<int>(Value(arg, m2)) + static_cast<int>(Value(arg, m3));
950   return count == 2;
951 }
952 
TEST(MatcherPnMacroTest,CanUseMatcherTypedParameterInValue)953 TEST(MatcherPnMacroTest, CanUseMatcherTypedParameterInValue) {
954   EXPECT_THAT(42, TwoOf(Gt(0), Lt(50), Eq(10)));
955   EXPECT_THAT(0, Not(TwoOf(Gt(-1), Lt(1), Eq(0))));
956 }
957 
958 // Tests Contains().
959 
TEST(ContainsTest,ListMatchesWhenElementIsInContainer)960 TEST(ContainsTest, ListMatchesWhenElementIsInContainer) {
961   list<int> some_list;
962   some_list.push_back(3);
963   some_list.push_back(1);
964   some_list.push_back(2);
965   EXPECT_THAT(some_list, Contains(1));
966   EXPECT_THAT(some_list, Contains(Gt(2.5)));
967   EXPECT_THAT(some_list, Contains(Eq(2.0f)));
968 
969   list<std::string> another_list;
970   another_list.push_back("fee");
971   another_list.push_back("fie");
972   another_list.push_back("foe");
973   another_list.push_back("fum");
974   EXPECT_THAT(another_list, Contains(std::string("fee")));
975 }
976 
TEST(ContainsTest,ListDoesNotMatchWhenElementIsNotInContainer)977 TEST(ContainsTest, ListDoesNotMatchWhenElementIsNotInContainer) {
978   list<int> some_list;
979   some_list.push_back(3);
980   some_list.push_back(1);
981   EXPECT_THAT(some_list, Not(Contains(4)));
982 }
983 
TEST(ContainsTest,SetMatchesWhenElementIsInContainer)984 TEST(ContainsTest, SetMatchesWhenElementIsInContainer) {
985   set<int> some_set;
986   some_set.insert(3);
987   some_set.insert(1);
988   some_set.insert(2);
989   EXPECT_THAT(some_set, Contains(Eq(1.0)));
990   EXPECT_THAT(some_set, Contains(Eq(3.0f)));
991   EXPECT_THAT(some_set, Contains(2));
992 
993   set<const char*> another_set;
994   another_set.insert("fee");
995   another_set.insert("fie");
996   another_set.insert("foe");
997   another_set.insert("fum");
998   EXPECT_THAT(another_set, Contains(Eq(std::string("fum"))));
999 }
1000 
TEST(ContainsTest,SetDoesNotMatchWhenElementIsNotInContainer)1001 TEST(ContainsTest, SetDoesNotMatchWhenElementIsNotInContainer) {
1002   set<int> some_set;
1003   some_set.insert(3);
1004   some_set.insert(1);
1005   EXPECT_THAT(some_set, Not(Contains(4)));
1006 
1007   set<const char*> c_string_set;
1008   c_string_set.insert("hello");
1009   EXPECT_THAT(c_string_set, Not(Contains(std::string("hello").c_str())));
1010 }
1011 
TEST(ContainsTest,ExplainsMatchResultCorrectly)1012 TEST(ContainsTest, ExplainsMatchResultCorrectly) {
1013   const int a[2] = { 1, 2 };
1014   Matcher<const int (&)[2]> m = Contains(2);
1015   EXPECT_EQ("whose element #1 matches", Explain(m, a));
1016 
1017   m = Contains(3);
1018   EXPECT_EQ("", Explain(m, a));
1019 
1020   m = Contains(GreaterThan(0));
1021   EXPECT_EQ("whose element #0 matches, which is 1 more than 0", Explain(m, a));
1022 
1023   m = Contains(GreaterThan(10));
1024   EXPECT_EQ("", Explain(m, a));
1025 }
1026 
TEST(ContainsTest,DescribesItselfCorrectly)1027 TEST(ContainsTest, DescribesItselfCorrectly) {
1028   Matcher<vector<int> > m = Contains(1);
1029   EXPECT_EQ("contains at least one element that is equal to 1", Describe(m));
1030 
1031   Matcher<vector<int> > m2 = Not(m);
1032   EXPECT_EQ("doesn't contain any element that is equal to 1", Describe(m2));
1033 }
1034 
TEST(ContainsTest,MapMatchesWhenElementIsInContainer)1035 TEST(ContainsTest, MapMatchesWhenElementIsInContainer) {
1036   map<const char*, int> my_map;
1037   const char* bar = "a string";
1038   my_map[bar] = 2;
1039   EXPECT_THAT(my_map, Contains(pair<const char* const, int>(bar, 2)));
1040 
1041   map<std::string, int> another_map;
1042   another_map["fee"] = 1;
1043   another_map["fie"] = 2;
1044   another_map["foe"] = 3;
1045   another_map["fum"] = 4;
1046   EXPECT_THAT(another_map,
1047               Contains(pair<const std::string, int>(std::string("fee"), 1)));
1048   EXPECT_THAT(another_map, Contains(pair<const std::string, int>("fie", 2)));
1049 }
1050 
TEST(ContainsTest,MapDoesNotMatchWhenElementIsNotInContainer)1051 TEST(ContainsTest, MapDoesNotMatchWhenElementIsNotInContainer) {
1052   map<int, int> some_map;
1053   some_map[1] = 11;
1054   some_map[2] = 22;
1055   EXPECT_THAT(some_map, Not(Contains(pair<const int, int>(2, 23))));
1056 }
1057 
TEST(ContainsTest,ArrayMatchesWhenElementIsInContainer)1058 TEST(ContainsTest, ArrayMatchesWhenElementIsInContainer) {
1059   const char* string_array[] = { "fee", "fie", "foe", "fum" };
1060   EXPECT_THAT(string_array, Contains(Eq(std::string("fum"))));
1061 }
1062 
TEST(ContainsTest,ArrayDoesNotMatchWhenElementIsNotInContainer)1063 TEST(ContainsTest, ArrayDoesNotMatchWhenElementIsNotInContainer) {
1064   int int_array[] = { 1, 2, 3, 4 };
1065   EXPECT_THAT(int_array, Not(Contains(5)));
1066 }
1067 
TEST(ContainsTest,AcceptsMatcher)1068 TEST(ContainsTest, AcceptsMatcher) {
1069   const int a[] = { 1, 2, 3 };
1070   EXPECT_THAT(a, Contains(Gt(2)));
1071   EXPECT_THAT(a, Not(Contains(Gt(4))));
1072 }
1073 
TEST(ContainsTest,WorksForNativeArrayAsTuple)1074 TEST(ContainsTest, WorksForNativeArrayAsTuple) {
1075   const int a[] = { 1, 2 };
1076   const int* const pointer = a;
1077   EXPECT_THAT(std::make_tuple(pointer, 2), Contains(1));
1078   EXPECT_THAT(std::make_tuple(pointer, 2), Not(Contains(Gt(3))));
1079 }
1080 
TEST(ContainsTest,WorksForTwoDimensionalNativeArray)1081 TEST(ContainsTest, WorksForTwoDimensionalNativeArray) {
1082   int a[][3] = { { 1, 2, 3 }, { 4, 5, 6 } };
1083   EXPECT_THAT(a, Contains(ElementsAre(4, 5, 6)));
1084   EXPECT_THAT(a, Contains(Contains(5)));
1085   EXPECT_THAT(a, Not(Contains(ElementsAre(3, 4, 5))));
1086   EXPECT_THAT(a, Contains(Not(Contains(5))));
1087 }
1088 
TEST(AllOfArrayTest,BasicForms)1089 TEST(AllOfArrayTest, BasicForms) {
1090   // Iterator
1091   std::vector<int> v0{};
1092   std::vector<int> v1{1};
1093   std::vector<int> v2{2, 3};
1094   std::vector<int> v3{4, 4, 4};
1095   EXPECT_THAT(0, AllOfArray(v0.begin(), v0.end()));
1096   EXPECT_THAT(1, AllOfArray(v1.begin(), v1.end()));
1097   EXPECT_THAT(2, Not(AllOfArray(v1.begin(), v1.end())));
1098   EXPECT_THAT(3, Not(AllOfArray(v2.begin(), v2.end())));
1099   EXPECT_THAT(4, AllOfArray(v3.begin(), v3.end()));
1100   // Pointer +  size
1101   int ar[6] = {1, 2, 3, 4, 4, 4};
1102   EXPECT_THAT(0, AllOfArray(ar, 0));
1103   EXPECT_THAT(1, AllOfArray(ar, 1));
1104   EXPECT_THAT(2, Not(AllOfArray(ar, 1)));
1105   EXPECT_THAT(3, Not(AllOfArray(ar + 1, 3)));
1106   EXPECT_THAT(4, AllOfArray(ar + 3, 3));
1107   // Array
1108   // int ar0[0];  Not usable
1109   int ar1[1] = {1};
1110   int ar2[2] = {2, 3};
1111   int ar3[3] = {4, 4, 4};
1112   // EXPECT_THAT(0, Not(AllOfArray(ar0)));  // Cannot work
1113   EXPECT_THAT(1, AllOfArray(ar1));
1114   EXPECT_THAT(2, Not(AllOfArray(ar1)));
1115   EXPECT_THAT(3, Not(AllOfArray(ar2)));
1116   EXPECT_THAT(4, AllOfArray(ar3));
1117   // Container
1118   EXPECT_THAT(0, AllOfArray(v0));
1119   EXPECT_THAT(1, AllOfArray(v1));
1120   EXPECT_THAT(2, Not(AllOfArray(v1)));
1121   EXPECT_THAT(3, Not(AllOfArray(v2)));
1122   EXPECT_THAT(4, AllOfArray(v3));
1123   // Initializer
1124   EXPECT_THAT(0, AllOfArray<int>({}));  // Requires template arg.
1125   EXPECT_THAT(1, AllOfArray({1}));
1126   EXPECT_THAT(2, Not(AllOfArray({1})));
1127   EXPECT_THAT(3, Not(AllOfArray({2, 3})));
1128   EXPECT_THAT(4, AllOfArray({4, 4, 4}));
1129 }
1130 
TEST(AllOfArrayTest,Matchers)1131 TEST(AllOfArrayTest, Matchers) {
1132   // vector
1133   std::vector<Matcher<int>> matchers{Ge(1), Lt(2)};
1134   EXPECT_THAT(0, Not(AllOfArray(matchers)));
1135   EXPECT_THAT(1, AllOfArray(matchers));
1136   EXPECT_THAT(2, Not(AllOfArray(matchers)));
1137   // initializer_list
1138   EXPECT_THAT(0, Not(AllOfArray({Ge(0), Ge(1)})));
1139   EXPECT_THAT(1, AllOfArray({Ge(0), Ge(1)}));
1140 }
1141 
TEST(AnyOfArrayTest,BasicForms)1142 TEST(AnyOfArrayTest, BasicForms) {
1143   // Iterator
1144   std::vector<int> v0{};
1145   std::vector<int> v1{1};
1146   std::vector<int> v2{2, 3};
1147   EXPECT_THAT(0, Not(AnyOfArray(v0.begin(), v0.end())));
1148   EXPECT_THAT(1, AnyOfArray(v1.begin(), v1.end()));
1149   EXPECT_THAT(2, Not(AnyOfArray(v1.begin(), v1.end())));
1150   EXPECT_THAT(3, AnyOfArray(v2.begin(), v2.end()));
1151   EXPECT_THAT(4, Not(AnyOfArray(v2.begin(), v2.end())));
1152   // Pointer +  size
1153   int ar[3] = {1, 2, 3};
1154   EXPECT_THAT(0, Not(AnyOfArray(ar, 0)));
1155   EXPECT_THAT(1, AnyOfArray(ar, 1));
1156   EXPECT_THAT(2, Not(AnyOfArray(ar, 1)));
1157   EXPECT_THAT(3, AnyOfArray(ar + 1, 2));
1158   EXPECT_THAT(4, Not(AnyOfArray(ar + 1, 2)));
1159   // Array
1160   // int ar0[0];  Not usable
1161   int ar1[1] = {1};
1162   int ar2[2] = {2, 3};
1163   // EXPECT_THAT(0, Not(AnyOfArray(ar0)));  // Cannot work
1164   EXPECT_THAT(1, AnyOfArray(ar1));
1165   EXPECT_THAT(2, Not(AnyOfArray(ar1)));
1166   EXPECT_THAT(3, AnyOfArray(ar2));
1167   EXPECT_THAT(4, Not(AnyOfArray(ar2)));
1168   // Container
1169   EXPECT_THAT(0, Not(AnyOfArray(v0)));
1170   EXPECT_THAT(1, AnyOfArray(v1));
1171   EXPECT_THAT(2, Not(AnyOfArray(v1)));
1172   EXPECT_THAT(3, AnyOfArray(v2));
1173   EXPECT_THAT(4, Not(AnyOfArray(v2)));
1174   // Initializer
1175   EXPECT_THAT(0, Not(AnyOfArray<int>({})));  // Requires template arg.
1176   EXPECT_THAT(1, AnyOfArray({1}));
1177   EXPECT_THAT(2, Not(AnyOfArray({1})));
1178   EXPECT_THAT(3, AnyOfArray({2, 3}));
1179   EXPECT_THAT(4, Not(AnyOfArray({2, 3})));
1180 }
1181 
TEST(AnyOfArrayTest,Matchers)1182 TEST(AnyOfArrayTest, Matchers) {
1183   // We negate test AllOfArrayTest.Matchers.
1184   // vector
1185   std::vector<Matcher<int>> matchers{Lt(1), Ge(2)};
1186   EXPECT_THAT(0, AnyOfArray(matchers));
1187   EXPECT_THAT(1, Not(AnyOfArray(matchers)));
1188   EXPECT_THAT(2, AnyOfArray(matchers));
1189   // initializer_list
1190   EXPECT_THAT(0, AnyOfArray({Lt(0), Lt(1)}));
1191   EXPECT_THAT(1, Not(AllOfArray({Lt(0), Lt(1)})));
1192 }
1193 
TEST(AnyOfArrayTest,ExplainsMatchResultCorrectly)1194 TEST(AnyOfArrayTest, ExplainsMatchResultCorrectly) {
1195   // AnyOfArray and AllOfArry use the same underlying template-template,
1196   // thus it is sufficient to test one here.
1197   const std::vector<int> v0{};
1198   const std::vector<int> v1{1};
1199   const std::vector<int> v2{2, 3};
1200   const Matcher<int> m0 = AnyOfArray(v0);
1201   const Matcher<int> m1 = AnyOfArray(v1);
1202   const Matcher<int> m2 = AnyOfArray(v2);
1203   EXPECT_EQ("", Explain(m0, 0));
1204   EXPECT_EQ("", Explain(m1, 1));
1205   EXPECT_EQ("", Explain(m1, 2));
1206   EXPECT_EQ("", Explain(m2, 3));
1207   EXPECT_EQ("", Explain(m2, 4));
1208   EXPECT_EQ("()", Describe(m0));
1209   EXPECT_EQ("(is equal to 1)", Describe(m1));
1210   EXPECT_EQ("(is equal to 2) or (is equal to 3)", Describe(m2));
1211   EXPECT_EQ("()", DescribeNegation(m0));
1212   EXPECT_EQ("(isn't equal to 1)", DescribeNegation(m1));
1213   EXPECT_EQ("(isn't equal to 2) and (isn't equal to 3)", DescribeNegation(m2));
1214   // Explain with matchers
1215   const Matcher<int> g1 = AnyOfArray({GreaterThan(1)});
1216   const Matcher<int> g2 = AnyOfArray({GreaterThan(1), GreaterThan(2)});
1217   // Explains the first positiv match and all prior negative matches...
1218   EXPECT_EQ("which is 1 less than 1", Explain(g1, 0));
1219   EXPECT_EQ("which is the same as 1", Explain(g1, 1));
1220   EXPECT_EQ("which is 1 more than 1", Explain(g1, 2));
1221   EXPECT_EQ("which is 1 less than 1, and which is 2 less than 2",
1222             Explain(g2, 0));
1223   EXPECT_EQ("which is the same as 1, and which is 1 less than 2",
1224             Explain(g2, 1));
1225   EXPECT_EQ("which is 1 more than 1",  // Only the first
1226             Explain(g2, 2));
1227 }
1228 
TEST(AllOfTest,HugeMatcher)1229 TEST(AllOfTest, HugeMatcher) {
1230   // Verify that using AllOf with many arguments doesn't cause
1231   // the compiler to exceed template instantiation depth limit.
1232   EXPECT_THAT(0, testing::AllOf(_, _, _, _, _, _, _, _, _,
1233                                 testing::AllOf(_, _, _, _, _, _, _, _, _, _)));
1234 }
1235 
TEST(AnyOfTest,HugeMatcher)1236 TEST(AnyOfTest, HugeMatcher) {
1237   // Verify that using AnyOf with many arguments doesn't cause
1238   // the compiler to exceed template instantiation depth limit.
1239   EXPECT_THAT(0, testing::AnyOf(_, _, _, _, _, _, _, _, _,
1240                                 testing::AnyOf(_, _, _, _, _, _, _, _, _, _)));
1241 }
1242 
1243 namespace adl_test {
1244 
1245 // Verifies that the implementation of ::testing::AllOf and ::testing::AnyOf
1246 // don't issue unqualified recursive calls.  If they do, the argument dependent
1247 // name lookup will cause AllOf/AnyOf in the 'adl_test' namespace to be found
1248 // as a candidate and the compilation will break due to an ambiguous overload.
1249 
1250 // The matcher must be in the same namespace as AllOf/AnyOf to make argument
1251 // dependent lookup find those.
1252 MATCHER(M, "") { return true; }
1253 
1254 template <typename T1, typename T2>
AllOf(const T1 &,const T2 &)1255 bool AllOf(const T1& /*t1*/, const T2& /*t2*/) { return true; }
1256 
TEST(AllOfTest,DoesNotCallAllOfUnqualified)1257 TEST(AllOfTest, DoesNotCallAllOfUnqualified) {
1258   EXPECT_THAT(42, testing::AllOf(
1259       M(), M(), M(), M(), M(), M(), M(), M(), M(), M()));
1260 }
1261 
1262 template <typename T1, typename T2> bool
AnyOf(const T1 & t1,const T2 & t2)1263 AnyOf(const T1& t1, const T2& t2) { return true; }
1264 
TEST(AnyOfTest,DoesNotCallAnyOfUnqualified)1265 TEST(AnyOfTest, DoesNotCallAnyOfUnqualified) {
1266   EXPECT_THAT(42, testing::AnyOf(
1267       M(), M(), M(), M(), M(), M(), M(), M(), M(), M()));
1268 }
1269 
1270 }  // namespace adl_test
1271 
1272 
TEST(AllOfTest,WorksOnMoveOnlyType)1273 TEST(AllOfTest, WorksOnMoveOnlyType) {
1274   std::unique_ptr<int> p(new int(3));
1275   EXPECT_THAT(p, AllOf(Pointee(Eq(3)), Pointee(Gt(0)), Pointee(Lt(5))));
1276   EXPECT_THAT(p, Not(AllOf(Pointee(Eq(3)), Pointee(Gt(0)), Pointee(Lt(3)))));
1277 }
1278 
TEST(AnyOfTest,WorksOnMoveOnlyType)1279 TEST(AnyOfTest, WorksOnMoveOnlyType) {
1280   std::unique_ptr<int> p(new int(3));
1281   EXPECT_THAT(p, AnyOf(Pointee(Eq(5)), Pointee(Lt(0)), Pointee(Lt(5))));
1282   EXPECT_THAT(p, Not(AnyOf(Pointee(Eq(5)), Pointee(Lt(0)), Pointee(Gt(5)))));
1283 }
1284 
1285 MATCHER(IsNotNull, "") {
1286   return arg != nullptr;
1287 }
1288 
1289 // Verifies that a matcher defined using MATCHER() can work on
1290 // move-only types.
TEST(MatcherMacroTest,WorksOnMoveOnlyType)1291 TEST(MatcherMacroTest, WorksOnMoveOnlyType) {
1292   std::unique_ptr<int> p(new int(3));
1293   EXPECT_THAT(p, IsNotNull());
1294   EXPECT_THAT(std::unique_ptr<int>(), Not(IsNotNull()));
1295 }
1296 
1297 MATCHER_P(UniquePointee, pointee, "") {
1298   return *arg == pointee;
1299 }
1300 
1301 // Verifies that a matcher defined using MATCHER_P*() can work on
1302 // move-only types.
TEST(MatcherPMacroTest,WorksOnMoveOnlyType)1303 TEST(MatcherPMacroTest, WorksOnMoveOnlyType) {
1304   std::unique_ptr<int> p(new int(3));
1305   EXPECT_THAT(p, UniquePointee(3));
1306   EXPECT_THAT(p, Not(UniquePointee(2)));
1307 }
1308 
1309 
1310 }  // namespace
1311 
1312 #ifdef _MSC_VER
1313 # pragma warning(pop)
1314 #endif
1315