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