1 // Copyright 2007, 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 some commonly used argument matchers.
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 "test/gmock-matchers_test.h"
43
44 namespace testing {
45 namespace gmock_matchers_test {
46 namespace {
47
MakeUniquePtrs(const std::vector<int> & ints)48 std::vector<std::unique_ptr<int>> MakeUniquePtrs(const std::vector<int>& ints) {
49 std::vector<std::unique_ptr<int>> pointers;
50 for (int i : ints) pointers.emplace_back(new int(i));
51 return pointers;
52 }
53
OfType(const std::string & type_name)54 std::string OfType(const std::string& type_name) {
55 #if GTEST_HAS_RTTI
56 return IsReadableTypeName(type_name) ? " (of type " + type_name + ")" : "";
57 #else
58 return "";
59 #endif
60 }
61
TEST(ContainsTest,WorksWithMoveOnly)62 TEST(ContainsTest, WorksWithMoveOnly) {
63 ContainerHelper helper;
64 EXPECT_CALL(helper, Call(Contains(Pointee(2))));
65 helper.Call(MakeUniquePtrs({1, 2}));
66 }
67
68 // Tests the variadic version of the ElementsAreMatcher
TEST(ElementsAreTest,HugeMatcher)69 TEST(ElementsAreTest, HugeMatcher) {
70 vector<int> test_vector{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12};
71
72 EXPECT_THAT(test_vector,
73 ElementsAre(Eq(1), Eq(2), Lt(13), Eq(4), Eq(5), Eq(6), Eq(7),
74 Eq(8), Eq(9), Eq(10), Gt(1), Eq(12)));
75 }
76
77 // Tests the variadic version of the UnorderedElementsAreMatcher
TEST(ElementsAreTest,HugeMatcherStr)78 TEST(ElementsAreTest, HugeMatcherStr) {
79 vector<std::string> test_vector{
80 "literal_string", "", "", "", "", "", "", "", "", "", "", ""};
81
82 EXPECT_THAT(test_vector, UnorderedElementsAre("literal_string", _, _, _, _, _,
83 _, _, _, _, _, _));
84 }
85
86 // Tests the variadic version of the UnorderedElementsAreMatcher
TEST(ElementsAreTest,HugeMatcherUnordered)87 TEST(ElementsAreTest, HugeMatcherUnordered) {
88 vector<int> test_vector{2, 1, 8, 5, 4, 6, 7, 3, 9, 12, 11, 10};
89
90 EXPECT_THAT(test_vector, UnorderedElementsAre(
91 Eq(2), Eq(1), Gt(7), Eq(5), Eq(4), Eq(6), Eq(7),
92 Eq(3), Eq(9), Eq(12), Eq(11), Ne(122)));
93 }
94
95 // Tests that ASSERT_THAT() and EXPECT_THAT() work when the value
96 // matches the matcher.
TEST(MatcherAssertionTest,WorksWhenMatcherIsSatisfied)97 TEST(MatcherAssertionTest, WorksWhenMatcherIsSatisfied) {
98 ASSERT_THAT(5, Ge(2)) << "This should succeed.";
99 ASSERT_THAT("Foo", EndsWith("oo"));
100 EXPECT_THAT(2, AllOf(Le(7), Ge(0))) << "This should succeed too.";
101 EXPECT_THAT("Hello", StartsWith("Hell"));
102 }
103
104 // Tests that ASSERT_THAT() and EXPECT_THAT() work when the value
105 // doesn't match the matcher.
TEST(MatcherAssertionTest,WorksWhenMatcherIsNotSatisfied)106 TEST(MatcherAssertionTest, WorksWhenMatcherIsNotSatisfied) {
107 // 'n' must be static as it is used in an EXPECT_FATAL_FAILURE(),
108 // which cannot reference auto variables.
109 static unsigned short n; // NOLINT
110 n = 5;
111
112 EXPECT_FATAL_FAILURE(ASSERT_THAT(n, Gt(10)),
113 "Value of: n\n"
114 "Expected: is > 10\n"
115 " Actual: 5" +
116 OfType("unsigned short"));
117 n = 0;
118 EXPECT_NONFATAL_FAILURE(EXPECT_THAT(n, AllOf(Le(7), Ge(5))),
119 "Value of: n\n"
120 "Expected: (is <= 7) and (is >= 5)\n"
121 " Actual: 0" +
122 OfType("unsigned short"));
123 }
124
125 // Tests that ASSERT_THAT() and EXPECT_THAT() work when the argument
126 // has a reference type.
TEST(MatcherAssertionTest,WorksForByRefArguments)127 TEST(MatcherAssertionTest, WorksForByRefArguments) {
128 // We use a static variable here as EXPECT_FATAL_FAILURE() cannot
129 // reference auto variables.
130 static int n;
131 n = 0;
132 EXPECT_THAT(n, AllOf(Le(7), Ref(n)));
133 EXPECT_FATAL_FAILURE(ASSERT_THAT(n, Not(Ref(n))),
134 "Value of: n\n"
135 "Expected: does not reference the variable @");
136 // Tests the "Actual" part.
137 EXPECT_FATAL_FAILURE(ASSERT_THAT(n, Not(Ref(n))),
138 "Actual: 0" + OfType("int") + ", which is located @");
139 }
140
141 // Tests that ASSERT_THAT() and EXPECT_THAT() work when the matcher is
142 // monomorphic.
TEST(MatcherAssertionTest,WorksForMonomorphicMatcher)143 TEST(MatcherAssertionTest, WorksForMonomorphicMatcher) {
144 Matcher<const char*> starts_with_he = StartsWith("he");
145 ASSERT_THAT("hello", starts_with_he);
146
147 Matcher<const std::string&> ends_with_ok = EndsWith("ok");
148 ASSERT_THAT("book", ends_with_ok);
149 const std::string bad = "bad";
150 EXPECT_NONFATAL_FAILURE(EXPECT_THAT(bad, ends_with_ok),
151 "Value of: bad\n"
152 "Expected: ends with \"ok\"\n"
153 " Actual: \"bad\"");
154 Matcher<int> is_greater_than_5 = Gt(5);
155 EXPECT_NONFATAL_FAILURE(EXPECT_THAT(5, is_greater_than_5),
156 "Value of: 5\n"
157 "Expected: is > 5\n"
158 " Actual: 5" +
159 OfType("int"));
160 }
161
TEST(PointeeTest,RawPointer)162 TEST(PointeeTest, RawPointer) {
163 const Matcher<int*> m = Pointee(Ge(0));
164
165 int n = 1;
166 EXPECT_TRUE(m.Matches(&n));
167 n = -1;
168 EXPECT_FALSE(m.Matches(&n));
169 EXPECT_FALSE(m.Matches(nullptr));
170 }
171
TEST(PointeeTest,RawPointerToConst)172 TEST(PointeeTest, RawPointerToConst) {
173 const Matcher<const double*> m = Pointee(Ge(0));
174
175 double x = 1;
176 EXPECT_TRUE(m.Matches(&x));
177 x = -1;
178 EXPECT_FALSE(m.Matches(&x));
179 EXPECT_FALSE(m.Matches(nullptr));
180 }
181
TEST(PointeeTest,ReferenceToConstRawPointer)182 TEST(PointeeTest, ReferenceToConstRawPointer) {
183 const Matcher<int* const&> m = Pointee(Ge(0));
184
185 int n = 1;
186 EXPECT_TRUE(m.Matches(&n));
187 n = -1;
188 EXPECT_FALSE(m.Matches(&n));
189 EXPECT_FALSE(m.Matches(nullptr));
190 }
191
TEST(PointeeTest,ReferenceToNonConstRawPointer)192 TEST(PointeeTest, ReferenceToNonConstRawPointer) {
193 const Matcher<double*&> m = Pointee(Ge(0));
194
195 double x = 1.0;
196 double* p = &x;
197 EXPECT_TRUE(m.Matches(p));
198 x = -1;
199 EXPECT_FALSE(m.Matches(p));
200 p = nullptr;
201 EXPECT_FALSE(m.Matches(p));
202 }
203
TEST(PointeeTest,SmartPointer)204 TEST(PointeeTest, SmartPointer) {
205 const Matcher<std::unique_ptr<int>> m = Pointee(Ge(0));
206
207 std::unique_ptr<int> n(new int(1));
208 EXPECT_TRUE(m.Matches(n));
209 }
210
TEST(PointeeTest,SmartPointerToConst)211 TEST(PointeeTest, SmartPointerToConst) {
212 const Matcher<std::unique_ptr<const int>> m = Pointee(Ge(0));
213
214 // There's no implicit conversion from unique_ptr<int> to const
215 // unique_ptr<const int>, so we must pass a unique_ptr<const int> into the
216 // matcher.
217 std::unique_ptr<const int> n(new int(1));
218 EXPECT_TRUE(m.Matches(n));
219 }
220
TEST(PointerTest,RawPointer)221 TEST(PointerTest, RawPointer) {
222 int n = 1;
223 const Matcher<int*> m = Pointer(Eq(&n));
224
225 EXPECT_TRUE(m.Matches(&n));
226
227 int* p = nullptr;
228 EXPECT_FALSE(m.Matches(p));
229 EXPECT_FALSE(m.Matches(nullptr));
230 }
231
TEST(PointerTest,RawPointerToConst)232 TEST(PointerTest, RawPointerToConst) {
233 int n = 1;
234 const Matcher<const int*> m = Pointer(Eq(&n));
235
236 EXPECT_TRUE(m.Matches(&n));
237
238 int* p = nullptr;
239 EXPECT_FALSE(m.Matches(p));
240 EXPECT_FALSE(m.Matches(nullptr));
241 }
242
TEST(PointerTest,SmartPointer)243 TEST(PointerTest, SmartPointer) {
244 std::unique_ptr<int> n(new int(10));
245 int* raw_n = n.get();
246 const Matcher<std::unique_ptr<int>> m = Pointer(Eq(raw_n));
247
248 EXPECT_TRUE(m.Matches(n));
249 }
250
TEST(PointerTest,SmartPointerToConst)251 TEST(PointerTest, SmartPointerToConst) {
252 std::unique_ptr<const int> n(new int(10));
253 const int* raw_n = n.get();
254 const Matcher<std::unique_ptr<const int>> m = Pointer(Eq(raw_n));
255
256 // There's no implicit conversion from unique_ptr<int> to const
257 // unique_ptr<const int>, so we must pass a unique_ptr<const int> into the
258 // matcher.
259 std::unique_ptr<const int> p(new int(10));
260 EXPECT_FALSE(m.Matches(p));
261 }
262
263 // Minimal const-propagating pointer.
264 template <typename T>
265 class ConstPropagatingPtr {
266 public:
267 typedef T element_type;
268
ConstPropagatingPtr()269 ConstPropagatingPtr() : val_() {}
ConstPropagatingPtr(T * t)270 explicit ConstPropagatingPtr(T* t) : val_(t) {}
ConstPropagatingPtr(const ConstPropagatingPtr & other)271 ConstPropagatingPtr(const ConstPropagatingPtr& other) : val_(other.val_) {}
272
get()273 T* get() { return val_; }
operator *()274 T& operator*() { return *val_; }
275 // Most smart pointers return non-const T* and T& from the next methods.
get() const276 const T* get() const { return val_; }
operator *() const277 const T& operator*() const { return *val_; }
278
279 private:
280 T* val_;
281 };
282
TEST(PointeeTest,WorksWithConstPropagatingPointers)283 TEST(PointeeTest, WorksWithConstPropagatingPointers) {
284 const Matcher<ConstPropagatingPtr<int>> m = Pointee(Lt(5));
285 int three = 3;
286 const ConstPropagatingPtr<int> co(&three);
287 ConstPropagatingPtr<int> o(&three);
288 EXPECT_TRUE(m.Matches(o));
289 EXPECT_TRUE(m.Matches(co));
290 *o = 6;
291 EXPECT_FALSE(m.Matches(o));
292 EXPECT_FALSE(m.Matches(ConstPropagatingPtr<int>()));
293 }
294
TEST(PointeeTest,NeverMatchesNull)295 TEST(PointeeTest, NeverMatchesNull) {
296 const Matcher<const char*> m = Pointee(_);
297 EXPECT_FALSE(m.Matches(nullptr));
298 }
299
300 // Tests that we can write Pointee(value) instead of Pointee(Eq(value)).
TEST(PointeeTest,MatchesAgainstAValue)301 TEST(PointeeTest, MatchesAgainstAValue) {
302 const Matcher<int*> m = Pointee(5);
303
304 int n = 5;
305 EXPECT_TRUE(m.Matches(&n));
306 n = -1;
307 EXPECT_FALSE(m.Matches(&n));
308 EXPECT_FALSE(m.Matches(nullptr));
309 }
310
TEST(PointeeTest,CanDescribeSelf)311 TEST(PointeeTest, CanDescribeSelf) {
312 const Matcher<int*> m = Pointee(Gt(3));
313 EXPECT_EQ("points to a value that is > 3", Describe(m));
314 EXPECT_EQ("does not point to a value that is > 3", DescribeNegation(m));
315 }
316
TEST(PointeeTest,CanExplainMatchResult)317 TEST(PointeeTest, CanExplainMatchResult) {
318 const Matcher<const std::string*> m = Pointee(StartsWith("Hi"));
319
320 EXPECT_EQ("", Explain(m, static_cast<const std::string*>(nullptr)));
321
322 const Matcher<long*> m2 = Pointee(GreaterThan(1)); // NOLINT
323 long n = 3; // NOLINT
324 EXPECT_EQ("which points to 3" + OfType("long") + ", which is 2 more than 1",
325 Explain(m2, &n));
326 }
327
TEST(PointeeTest,AlwaysExplainsPointee)328 TEST(PointeeTest, AlwaysExplainsPointee) {
329 const Matcher<int*> m = Pointee(0);
330 int n = 42;
331 EXPECT_EQ("which points to 42" + OfType("int"), Explain(m, &n));
332 }
333
334 // An uncopyable class.
335 class Uncopyable {
336 public:
Uncopyable()337 Uncopyable() : value_(-1) {}
Uncopyable(int a_value)338 explicit Uncopyable(int a_value) : value_(a_value) {}
339
value() const340 int value() const { return value_; }
set_value(int i)341 void set_value(int i) { value_ = i; }
342
343 private:
344 int value_;
345 GTEST_DISALLOW_COPY_AND_ASSIGN_(Uncopyable);
346 };
347
348 // Returns true if and only if x.value() is positive.
ValueIsPositive(const Uncopyable & x)349 bool ValueIsPositive(const Uncopyable& x) { return x.value() > 0; }
350
351 MATCHER_P(UncopyableIs, inner_matcher, "") {
352 return ExplainMatchResult(inner_matcher, arg.value(), result_listener);
353 }
354
355 // A user-defined struct for testing Field().
356 struct AStruct {
AStructtesting::gmock_matchers_test::__anon0ad92c4b0111::AStruct357 AStruct() : x(0), y(1.0), z(5), p(nullptr) {}
AStructtesting::gmock_matchers_test::__anon0ad92c4b0111::AStruct358 AStruct(const AStruct& rhs)
359 : x(rhs.x), y(rhs.y), z(rhs.z.value()), p(rhs.p) {}
360
361 int x; // A non-const field.
362 const double y; // A const field.
363 Uncopyable z; // An uncopyable field.
364 const char* p; // A pointer field.
365 };
366
367 // A derived struct for testing Field().
368 struct DerivedStruct : public AStruct {
369 char ch;
370 };
371
372 // Tests that Field(&Foo::field, ...) works when field is non-const.
TEST(FieldTest,WorksForNonConstField)373 TEST(FieldTest, WorksForNonConstField) {
374 Matcher<AStruct> m = Field(&AStruct::x, Ge(0));
375 Matcher<AStruct> m_with_name = Field("x", &AStruct::x, Ge(0));
376
377 AStruct a;
378 EXPECT_TRUE(m.Matches(a));
379 EXPECT_TRUE(m_with_name.Matches(a));
380 a.x = -1;
381 EXPECT_FALSE(m.Matches(a));
382 EXPECT_FALSE(m_with_name.Matches(a));
383 }
384
385 // Tests that Field(&Foo::field, ...) works when field is const.
TEST(FieldTest,WorksForConstField)386 TEST(FieldTest, WorksForConstField) {
387 AStruct a;
388
389 Matcher<AStruct> m = Field(&AStruct::y, Ge(0.0));
390 Matcher<AStruct> m_with_name = Field("y", &AStruct::y, Ge(0.0));
391 EXPECT_TRUE(m.Matches(a));
392 EXPECT_TRUE(m_with_name.Matches(a));
393 m = Field(&AStruct::y, Le(0.0));
394 m_with_name = Field("y", &AStruct::y, Le(0.0));
395 EXPECT_FALSE(m.Matches(a));
396 EXPECT_FALSE(m_with_name.Matches(a));
397 }
398
399 // Tests that Field(&Foo::field, ...) works when field is not copyable.
TEST(FieldTest,WorksForUncopyableField)400 TEST(FieldTest, WorksForUncopyableField) {
401 AStruct a;
402
403 Matcher<AStruct> m = Field(&AStruct::z, Truly(ValueIsPositive));
404 EXPECT_TRUE(m.Matches(a));
405 m = Field(&AStruct::z, Not(Truly(ValueIsPositive)));
406 EXPECT_FALSE(m.Matches(a));
407 }
408
409 // Tests that Field(&Foo::field, ...) works when field is a pointer.
TEST(FieldTest,WorksForPointerField)410 TEST(FieldTest, WorksForPointerField) {
411 // Matching against NULL.
412 Matcher<AStruct> m = Field(&AStruct::p, static_cast<const char*>(nullptr));
413 AStruct a;
414 EXPECT_TRUE(m.Matches(a));
415 a.p = "hi";
416 EXPECT_FALSE(m.Matches(a));
417
418 // Matching a pointer that is not NULL.
419 m = Field(&AStruct::p, StartsWith("hi"));
420 a.p = "hill";
421 EXPECT_TRUE(m.Matches(a));
422 a.p = "hole";
423 EXPECT_FALSE(m.Matches(a));
424 }
425
426 // Tests that Field() works when the object is passed by reference.
TEST(FieldTest,WorksForByRefArgument)427 TEST(FieldTest, WorksForByRefArgument) {
428 Matcher<const AStruct&> m = Field(&AStruct::x, Ge(0));
429
430 AStruct a;
431 EXPECT_TRUE(m.Matches(a));
432 a.x = -1;
433 EXPECT_FALSE(m.Matches(a));
434 }
435
436 // Tests that Field(&Foo::field, ...) works when the argument's type
437 // is a sub-type of Foo.
TEST(FieldTest,WorksForArgumentOfSubType)438 TEST(FieldTest, WorksForArgumentOfSubType) {
439 // Note that the matcher expects DerivedStruct but we say AStruct
440 // inside Field().
441 Matcher<const DerivedStruct&> m = Field(&AStruct::x, Ge(0));
442
443 DerivedStruct d;
444 EXPECT_TRUE(m.Matches(d));
445 d.x = -1;
446 EXPECT_FALSE(m.Matches(d));
447 }
448
449 // Tests that Field(&Foo::field, m) works when field's type and m's
450 // argument type are compatible but not the same.
TEST(FieldTest,WorksForCompatibleMatcherType)451 TEST(FieldTest, WorksForCompatibleMatcherType) {
452 // The field is an int, but the inner matcher expects a signed char.
453 Matcher<const AStruct&> m = Field(&AStruct::x, Matcher<signed char>(Ge(0)));
454
455 AStruct a;
456 EXPECT_TRUE(m.Matches(a));
457 a.x = -1;
458 EXPECT_FALSE(m.Matches(a));
459 }
460
461 // Tests that Field() can describe itself.
TEST(FieldTest,CanDescribeSelf)462 TEST(FieldTest, CanDescribeSelf) {
463 Matcher<const AStruct&> m = Field(&AStruct::x, Ge(0));
464
465 EXPECT_EQ("is an object whose given field is >= 0", Describe(m));
466 EXPECT_EQ("is an object whose given field isn't >= 0", DescribeNegation(m));
467 }
468
TEST(FieldTest,CanDescribeSelfWithFieldName)469 TEST(FieldTest, CanDescribeSelfWithFieldName) {
470 Matcher<const AStruct&> m = Field("field_name", &AStruct::x, Ge(0));
471
472 EXPECT_EQ("is an object whose field `field_name` is >= 0", Describe(m));
473 EXPECT_EQ("is an object whose field `field_name` isn't >= 0",
474 DescribeNegation(m));
475 }
476
477 // Tests that Field() can explain the match result.
TEST(FieldTest,CanExplainMatchResult)478 TEST(FieldTest, CanExplainMatchResult) {
479 Matcher<const AStruct&> m = Field(&AStruct::x, Ge(0));
480
481 AStruct a;
482 a.x = 1;
483 EXPECT_EQ("whose given field is 1" + OfType("int"), Explain(m, a));
484
485 m = Field(&AStruct::x, GreaterThan(0));
486 EXPECT_EQ(
487 "whose given field is 1" + OfType("int") + ", which is 1 more than 0",
488 Explain(m, a));
489 }
490
TEST(FieldTest,CanExplainMatchResultWithFieldName)491 TEST(FieldTest, CanExplainMatchResultWithFieldName) {
492 Matcher<const AStruct&> m = Field("field_name", &AStruct::x, Ge(0));
493
494 AStruct a;
495 a.x = 1;
496 EXPECT_EQ("whose field `field_name` is 1" + OfType("int"), Explain(m, a));
497
498 m = Field("field_name", &AStruct::x, GreaterThan(0));
499 EXPECT_EQ("whose field `field_name` is 1" + OfType("int") +
500 ", which is 1 more than 0",
501 Explain(m, a));
502 }
503
504 // Tests that Field() works when the argument is a pointer to const.
TEST(FieldForPointerTest,WorksForPointerToConst)505 TEST(FieldForPointerTest, WorksForPointerToConst) {
506 Matcher<const AStruct*> m = Field(&AStruct::x, Ge(0));
507
508 AStruct a;
509 EXPECT_TRUE(m.Matches(&a));
510 a.x = -1;
511 EXPECT_FALSE(m.Matches(&a));
512 }
513
514 // Tests that Field() works when the argument is a pointer to non-const.
TEST(FieldForPointerTest,WorksForPointerToNonConst)515 TEST(FieldForPointerTest, WorksForPointerToNonConst) {
516 Matcher<AStruct*> m = Field(&AStruct::x, Ge(0));
517
518 AStruct a;
519 EXPECT_TRUE(m.Matches(&a));
520 a.x = -1;
521 EXPECT_FALSE(m.Matches(&a));
522 }
523
524 // Tests that Field() works when the argument is a reference to a const pointer.
TEST(FieldForPointerTest,WorksForReferenceToConstPointer)525 TEST(FieldForPointerTest, WorksForReferenceToConstPointer) {
526 Matcher<AStruct* const&> m = Field(&AStruct::x, Ge(0));
527
528 AStruct a;
529 EXPECT_TRUE(m.Matches(&a));
530 a.x = -1;
531 EXPECT_FALSE(m.Matches(&a));
532 }
533
534 // Tests that Field() does not match the NULL pointer.
TEST(FieldForPointerTest,DoesNotMatchNull)535 TEST(FieldForPointerTest, DoesNotMatchNull) {
536 Matcher<const AStruct*> m = Field(&AStruct::x, _);
537 EXPECT_FALSE(m.Matches(nullptr));
538 }
539
540 // Tests that Field(&Foo::field, ...) works when the argument's type
541 // is a sub-type of const Foo*.
TEST(FieldForPointerTest,WorksForArgumentOfSubType)542 TEST(FieldForPointerTest, WorksForArgumentOfSubType) {
543 // Note that the matcher expects DerivedStruct but we say AStruct
544 // inside Field().
545 Matcher<DerivedStruct*> m = Field(&AStruct::x, Ge(0));
546
547 DerivedStruct d;
548 EXPECT_TRUE(m.Matches(&d));
549 d.x = -1;
550 EXPECT_FALSE(m.Matches(&d));
551 }
552
553 // Tests that Field() can describe itself when used to match a pointer.
TEST(FieldForPointerTest,CanDescribeSelf)554 TEST(FieldForPointerTest, CanDescribeSelf) {
555 Matcher<const AStruct*> m = Field(&AStruct::x, Ge(0));
556
557 EXPECT_EQ("is an object whose given field is >= 0", Describe(m));
558 EXPECT_EQ("is an object whose given field isn't >= 0", DescribeNegation(m));
559 }
560
TEST(FieldForPointerTest,CanDescribeSelfWithFieldName)561 TEST(FieldForPointerTest, CanDescribeSelfWithFieldName) {
562 Matcher<const AStruct*> m = Field("field_name", &AStruct::x, Ge(0));
563
564 EXPECT_EQ("is an object whose field `field_name` is >= 0", Describe(m));
565 EXPECT_EQ("is an object whose field `field_name` isn't >= 0",
566 DescribeNegation(m));
567 }
568
569 // Tests that Field() can explain the result of matching a pointer.
TEST(FieldForPointerTest,CanExplainMatchResult)570 TEST(FieldForPointerTest, CanExplainMatchResult) {
571 Matcher<const AStruct*> m = Field(&AStruct::x, Ge(0));
572
573 AStruct a;
574 a.x = 1;
575 EXPECT_EQ("", Explain(m, static_cast<const AStruct*>(nullptr)));
576 EXPECT_EQ("which points to an object whose given field is 1" + OfType("int"),
577 Explain(m, &a));
578
579 m = Field(&AStruct::x, GreaterThan(0));
580 EXPECT_EQ("which points to an object whose given field is 1" + OfType("int") +
581 ", which is 1 more than 0",
582 Explain(m, &a));
583 }
584
TEST(FieldForPointerTest,CanExplainMatchResultWithFieldName)585 TEST(FieldForPointerTest, CanExplainMatchResultWithFieldName) {
586 Matcher<const AStruct*> m = Field("field_name", &AStruct::x, Ge(0));
587
588 AStruct a;
589 a.x = 1;
590 EXPECT_EQ("", Explain(m, static_cast<const AStruct*>(nullptr)));
591 EXPECT_EQ(
592 "which points to an object whose field `field_name` is 1" + OfType("int"),
593 Explain(m, &a));
594
595 m = Field("field_name", &AStruct::x, GreaterThan(0));
596 EXPECT_EQ("which points to an object whose field `field_name` is 1" +
597 OfType("int") + ", which is 1 more than 0",
598 Explain(m, &a));
599 }
600
601 // A user-defined class for testing Property().
602 class AClass {
603 public:
AClass()604 AClass() : n_(0) {}
605
606 // A getter that returns a non-reference.
n() const607 int n() const { return n_; }
608
set_n(int new_n)609 void set_n(int new_n) { n_ = new_n; }
610
611 // A getter that returns a reference to const.
s() const612 const std::string& s() const { return s_; }
613
s_ref() const614 const std::string& s_ref() const& { return s_; }
615
set_s(const std::string & new_s)616 void set_s(const std::string& new_s) { s_ = new_s; }
617
618 // A getter that returns a reference to non-const.
x() const619 double& x() const { return x_; }
620
621 private:
622 int n_;
623 std::string s_;
624
625 static double x_;
626 };
627
628 double AClass::x_ = 0.0;
629
630 // A derived class for testing Property().
631 class DerivedClass : public AClass {
632 public:
k() const633 int k() const { return k_; }
634
635 private:
636 int k_;
637 };
638
639 // Tests that Property(&Foo::property, ...) works when property()
640 // returns a non-reference.
TEST(PropertyTest,WorksForNonReferenceProperty)641 TEST(PropertyTest, WorksForNonReferenceProperty) {
642 Matcher<const AClass&> m = Property(&AClass::n, Ge(0));
643 Matcher<const AClass&> m_with_name = Property("n", &AClass::n, Ge(0));
644
645 AClass a;
646 a.set_n(1);
647 EXPECT_TRUE(m.Matches(a));
648 EXPECT_TRUE(m_with_name.Matches(a));
649
650 a.set_n(-1);
651 EXPECT_FALSE(m.Matches(a));
652 EXPECT_FALSE(m_with_name.Matches(a));
653 }
654
655 // Tests that Property(&Foo::property, ...) works when property()
656 // returns a reference to const.
TEST(PropertyTest,WorksForReferenceToConstProperty)657 TEST(PropertyTest, WorksForReferenceToConstProperty) {
658 Matcher<const AClass&> m = Property(&AClass::s, StartsWith("hi"));
659 Matcher<const AClass&> m_with_name =
660 Property("s", &AClass::s, StartsWith("hi"));
661
662 AClass a;
663 a.set_s("hill");
664 EXPECT_TRUE(m.Matches(a));
665 EXPECT_TRUE(m_with_name.Matches(a));
666
667 a.set_s("hole");
668 EXPECT_FALSE(m.Matches(a));
669 EXPECT_FALSE(m_with_name.Matches(a));
670 }
671
672 // Tests that Property(&Foo::property, ...) works when property() is
673 // ref-qualified.
TEST(PropertyTest,WorksForRefQualifiedProperty)674 TEST(PropertyTest, WorksForRefQualifiedProperty) {
675 Matcher<const AClass&> m = Property(&AClass::s_ref, StartsWith("hi"));
676 Matcher<const AClass&> m_with_name =
677 Property("s", &AClass::s_ref, StartsWith("hi"));
678
679 AClass a;
680 a.set_s("hill");
681 EXPECT_TRUE(m.Matches(a));
682 EXPECT_TRUE(m_with_name.Matches(a));
683
684 a.set_s("hole");
685 EXPECT_FALSE(m.Matches(a));
686 EXPECT_FALSE(m_with_name.Matches(a));
687 }
688
689 // Tests that Property(&Foo::property, ...) works when property()
690 // returns a reference to non-const.
TEST(PropertyTest,WorksForReferenceToNonConstProperty)691 TEST(PropertyTest, WorksForReferenceToNonConstProperty) {
692 double x = 0.0;
693 AClass a;
694
695 Matcher<const AClass&> m = Property(&AClass::x, Ref(x));
696 EXPECT_FALSE(m.Matches(a));
697
698 m = Property(&AClass::x, Not(Ref(x)));
699 EXPECT_TRUE(m.Matches(a));
700 }
701
702 // Tests that Property(&Foo::property, ...) works when the argument is
703 // passed by value.
TEST(PropertyTest,WorksForByValueArgument)704 TEST(PropertyTest, WorksForByValueArgument) {
705 Matcher<AClass> m = Property(&AClass::s, StartsWith("hi"));
706
707 AClass a;
708 a.set_s("hill");
709 EXPECT_TRUE(m.Matches(a));
710
711 a.set_s("hole");
712 EXPECT_FALSE(m.Matches(a));
713 }
714
715 // Tests that Property(&Foo::property, ...) works when the argument's
716 // type is a sub-type of Foo.
TEST(PropertyTest,WorksForArgumentOfSubType)717 TEST(PropertyTest, WorksForArgumentOfSubType) {
718 // The matcher expects a DerivedClass, but inside the Property() we
719 // say AClass.
720 Matcher<const DerivedClass&> m = Property(&AClass::n, Ge(0));
721
722 DerivedClass d;
723 d.set_n(1);
724 EXPECT_TRUE(m.Matches(d));
725
726 d.set_n(-1);
727 EXPECT_FALSE(m.Matches(d));
728 }
729
730 // Tests that Property(&Foo::property, m) works when property()'s type
731 // and m's argument type are compatible but different.
TEST(PropertyTest,WorksForCompatibleMatcherType)732 TEST(PropertyTest, WorksForCompatibleMatcherType) {
733 // n() returns an int but the inner matcher expects a signed char.
734 Matcher<const AClass&> m = Property(&AClass::n, Matcher<signed char>(Ge(0)));
735
736 Matcher<const AClass&> m_with_name =
737 Property("n", &AClass::n, Matcher<signed char>(Ge(0)));
738
739 AClass a;
740 EXPECT_TRUE(m.Matches(a));
741 EXPECT_TRUE(m_with_name.Matches(a));
742 a.set_n(-1);
743 EXPECT_FALSE(m.Matches(a));
744 EXPECT_FALSE(m_with_name.Matches(a));
745 }
746
747 // Tests that Property() can describe itself.
TEST(PropertyTest,CanDescribeSelf)748 TEST(PropertyTest, CanDescribeSelf) {
749 Matcher<const AClass&> m = Property(&AClass::n, Ge(0));
750
751 EXPECT_EQ("is an object whose given property is >= 0", Describe(m));
752 EXPECT_EQ("is an object whose given property isn't >= 0",
753 DescribeNegation(m));
754 }
755
TEST(PropertyTest,CanDescribeSelfWithPropertyName)756 TEST(PropertyTest, CanDescribeSelfWithPropertyName) {
757 Matcher<const AClass&> m = Property("fancy_name", &AClass::n, Ge(0));
758
759 EXPECT_EQ("is an object whose property `fancy_name` is >= 0", Describe(m));
760 EXPECT_EQ("is an object whose property `fancy_name` isn't >= 0",
761 DescribeNegation(m));
762 }
763
764 // Tests that Property() can explain the match result.
TEST(PropertyTest,CanExplainMatchResult)765 TEST(PropertyTest, CanExplainMatchResult) {
766 Matcher<const AClass&> m = Property(&AClass::n, Ge(0));
767
768 AClass a;
769 a.set_n(1);
770 EXPECT_EQ("whose given property is 1" + OfType("int"), Explain(m, a));
771
772 m = Property(&AClass::n, GreaterThan(0));
773 EXPECT_EQ(
774 "whose given property is 1" + OfType("int") + ", which is 1 more than 0",
775 Explain(m, a));
776 }
777
TEST(PropertyTest,CanExplainMatchResultWithPropertyName)778 TEST(PropertyTest, CanExplainMatchResultWithPropertyName) {
779 Matcher<const AClass&> m = Property("fancy_name", &AClass::n, Ge(0));
780
781 AClass a;
782 a.set_n(1);
783 EXPECT_EQ("whose property `fancy_name` is 1" + OfType("int"), Explain(m, a));
784
785 m = Property("fancy_name", &AClass::n, GreaterThan(0));
786 EXPECT_EQ("whose property `fancy_name` is 1" + OfType("int") +
787 ", which is 1 more than 0",
788 Explain(m, a));
789 }
790
791 // Tests that Property() works when the argument is a pointer to const.
TEST(PropertyForPointerTest,WorksForPointerToConst)792 TEST(PropertyForPointerTest, WorksForPointerToConst) {
793 Matcher<const AClass*> m = Property(&AClass::n, Ge(0));
794
795 AClass a;
796 a.set_n(1);
797 EXPECT_TRUE(m.Matches(&a));
798
799 a.set_n(-1);
800 EXPECT_FALSE(m.Matches(&a));
801 }
802
803 // Tests that Property() works when the argument is a pointer to non-const.
TEST(PropertyForPointerTest,WorksForPointerToNonConst)804 TEST(PropertyForPointerTest, WorksForPointerToNonConst) {
805 Matcher<AClass*> m = Property(&AClass::s, StartsWith("hi"));
806
807 AClass a;
808 a.set_s("hill");
809 EXPECT_TRUE(m.Matches(&a));
810
811 a.set_s("hole");
812 EXPECT_FALSE(m.Matches(&a));
813 }
814
815 // Tests that Property() works when the argument is a reference to a
816 // const pointer.
TEST(PropertyForPointerTest,WorksForReferenceToConstPointer)817 TEST(PropertyForPointerTest, WorksForReferenceToConstPointer) {
818 Matcher<AClass* const&> m = Property(&AClass::s, StartsWith("hi"));
819
820 AClass a;
821 a.set_s("hill");
822 EXPECT_TRUE(m.Matches(&a));
823
824 a.set_s("hole");
825 EXPECT_FALSE(m.Matches(&a));
826 }
827
828 // Tests that Property() does not match the NULL pointer.
TEST(PropertyForPointerTest,WorksForReferenceToNonConstProperty)829 TEST(PropertyForPointerTest, WorksForReferenceToNonConstProperty) {
830 Matcher<const AClass*> m = Property(&AClass::x, _);
831 EXPECT_FALSE(m.Matches(nullptr));
832 }
833
834 // Tests that Property(&Foo::property, ...) works when the argument's
835 // type is a sub-type of const Foo*.
TEST(PropertyForPointerTest,WorksForArgumentOfSubType)836 TEST(PropertyForPointerTest, WorksForArgumentOfSubType) {
837 // The matcher expects a DerivedClass, but inside the Property() we
838 // say AClass.
839 Matcher<const DerivedClass*> m = Property(&AClass::n, Ge(0));
840
841 DerivedClass d;
842 d.set_n(1);
843 EXPECT_TRUE(m.Matches(&d));
844
845 d.set_n(-1);
846 EXPECT_FALSE(m.Matches(&d));
847 }
848
849 // Tests that Property() can describe itself when used to match a pointer.
TEST(PropertyForPointerTest,CanDescribeSelf)850 TEST(PropertyForPointerTest, CanDescribeSelf) {
851 Matcher<const AClass*> m = Property(&AClass::n, Ge(0));
852
853 EXPECT_EQ("is an object whose given property is >= 0", Describe(m));
854 EXPECT_EQ("is an object whose given property isn't >= 0",
855 DescribeNegation(m));
856 }
857
TEST(PropertyForPointerTest,CanDescribeSelfWithPropertyDescription)858 TEST(PropertyForPointerTest, CanDescribeSelfWithPropertyDescription) {
859 Matcher<const AClass*> m = Property("fancy_name", &AClass::n, Ge(0));
860
861 EXPECT_EQ("is an object whose property `fancy_name` is >= 0", Describe(m));
862 EXPECT_EQ("is an object whose property `fancy_name` isn't >= 0",
863 DescribeNegation(m));
864 }
865
866 // Tests that Property() can explain the result of matching a pointer.
TEST(PropertyForPointerTest,CanExplainMatchResult)867 TEST(PropertyForPointerTest, CanExplainMatchResult) {
868 Matcher<const AClass*> m = Property(&AClass::n, Ge(0));
869
870 AClass a;
871 a.set_n(1);
872 EXPECT_EQ("", Explain(m, static_cast<const AClass*>(nullptr)));
873 EXPECT_EQ(
874 "which points to an object whose given property is 1" + OfType("int"),
875 Explain(m, &a));
876
877 m = Property(&AClass::n, GreaterThan(0));
878 EXPECT_EQ("which points to an object whose given property is 1" +
879 OfType("int") + ", which is 1 more than 0",
880 Explain(m, &a));
881 }
882
TEST(PropertyForPointerTest,CanExplainMatchResultWithPropertyName)883 TEST(PropertyForPointerTest, CanExplainMatchResultWithPropertyName) {
884 Matcher<const AClass*> m = Property("fancy_name", &AClass::n, Ge(0));
885
886 AClass a;
887 a.set_n(1);
888 EXPECT_EQ("", Explain(m, static_cast<const AClass*>(nullptr)));
889 EXPECT_EQ("which points to an object whose property `fancy_name` is 1" +
890 OfType("int"),
891 Explain(m, &a));
892
893 m = Property("fancy_name", &AClass::n, GreaterThan(0));
894 EXPECT_EQ("which points to an object whose property `fancy_name` is 1" +
895 OfType("int") + ", which is 1 more than 0",
896 Explain(m, &a));
897 }
898
899 // Tests ResultOf.
900
901 // Tests that ResultOf(f, ...) compiles and works as expected when f is a
902 // function pointer.
IntToStringFunction(int input)903 std::string IntToStringFunction(int input) {
904 return input == 1 ? "foo" : "bar";
905 }
906
TEST(ResultOfTest,WorksForFunctionPointers)907 TEST(ResultOfTest, WorksForFunctionPointers) {
908 Matcher<int> matcher = ResultOf(&IntToStringFunction, Eq(std::string("foo")));
909
910 EXPECT_TRUE(matcher.Matches(1));
911 EXPECT_FALSE(matcher.Matches(2));
912 }
913
914 // Tests that ResultOf() can describe itself.
TEST(ResultOfTest,CanDescribeItself)915 TEST(ResultOfTest, CanDescribeItself) {
916 Matcher<int> matcher = ResultOf(&IntToStringFunction, StrEq("foo"));
917
918 EXPECT_EQ(
919 "is mapped by the given callable to a value that "
920 "is equal to \"foo\"",
921 Describe(matcher));
922 EXPECT_EQ(
923 "is mapped by the given callable to a value that "
924 "isn't equal to \"foo\"",
925 DescribeNegation(matcher));
926 }
927
928 // Tests that ResultOf() can describe itself when provided a result description.
TEST(ResultOfTest,CanDescribeItselfWithResultDescription)929 TEST(ResultOfTest, CanDescribeItselfWithResultDescription) {
930 Matcher<int> matcher =
931 ResultOf("string conversion", &IntToStringFunction, StrEq("foo"));
932
933 EXPECT_EQ("whose string conversion is equal to \"foo\"", Describe(matcher));
934 EXPECT_EQ("whose string conversion isn't equal to \"foo\"",
935 DescribeNegation(matcher));
936 }
937
938 // Tests that ResultOf() can explain the match result.
IntFunction(int input)939 int IntFunction(int input) { return input == 42 ? 80 : 90; }
940
TEST(ResultOfTest,CanExplainMatchResult)941 TEST(ResultOfTest, CanExplainMatchResult) {
942 Matcher<int> matcher = ResultOf(&IntFunction, Ge(85));
943 EXPECT_EQ("which is mapped by the given callable to 90" + OfType("int"),
944 Explain(matcher, 36));
945
946 matcher = ResultOf(&IntFunction, GreaterThan(85));
947 EXPECT_EQ("which is mapped by the given callable to 90" + OfType("int") +
948 ", which is 5 more than 85",
949 Explain(matcher, 36));
950 }
951
952 // Tests that ResultOf(f, ...) compiles and works as expected when f(x)
953 // returns a non-reference.
TEST(ResultOfTest,WorksForNonReferenceResults)954 TEST(ResultOfTest, WorksForNonReferenceResults) {
955 Matcher<int> matcher = ResultOf(&IntFunction, Eq(80));
956
957 EXPECT_TRUE(matcher.Matches(42));
958 EXPECT_FALSE(matcher.Matches(36));
959 }
960
961 // Tests that ResultOf(f, ...) compiles and works as expected when f(x)
962 // returns a reference to non-const.
DoubleFunction(double & input)963 double& DoubleFunction(double& input) { return input; } // NOLINT
964
RefUncopyableFunction(Uncopyable & obj)965 Uncopyable& RefUncopyableFunction(Uncopyable& obj) { // NOLINT
966 return obj;
967 }
968
TEST(ResultOfTest,WorksForReferenceToNonConstResults)969 TEST(ResultOfTest, WorksForReferenceToNonConstResults) {
970 double x = 3.14;
971 double x2 = x;
972 Matcher<double&> matcher = ResultOf(&DoubleFunction, Ref(x));
973
974 EXPECT_TRUE(matcher.Matches(x));
975 EXPECT_FALSE(matcher.Matches(x2));
976
977 // Test that ResultOf works with uncopyable objects
978 Uncopyable obj(0);
979 Uncopyable obj2(0);
980 Matcher<Uncopyable&> matcher2 = ResultOf(&RefUncopyableFunction, Ref(obj));
981
982 EXPECT_TRUE(matcher2.Matches(obj));
983 EXPECT_FALSE(matcher2.Matches(obj2));
984 }
985
986 // Tests that ResultOf(f, ...) compiles and works as expected when f(x)
987 // returns a reference to const.
StringFunction(const std::string & input)988 const std::string& StringFunction(const std::string& input) { return input; }
989
TEST(ResultOfTest,WorksForReferenceToConstResults)990 TEST(ResultOfTest, WorksForReferenceToConstResults) {
991 std::string s = "foo";
992 std::string s2 = s;
993 Matcher<const std::string&> matcher = ResultOf(&StringFunction, Ref(s));
994
995 EXPECT_TRUE(matcher.Matches(s));
996 EXPECT_FALSE(matcher.Matches(s2));
997 }
998
999 // Tests that ResultOf(f, m) works when f(x) and m's
1000 // argument types are compatible but different.
TEST(ResultOfTest,WorksForCompatibleMatcherTypes)1001 TEST(ResultOfTest, WorksForCompatibleMatcherTypes) {
1002 // IntFunction() returns int but the inner matcher expects a signed char.
1003 Matcher<int> matcher = ResultOf(IntFunction, Matcher<signed char>(Ge(85)));
1004
1005 EXPECT_TRUE(matcher.Matches(36));
1006 EXPECT_FALSE(matcher.Matches(42));
1007 }
1008
1009 // Tests that the program aborts when ResultOf is passed
1010 // a NULL function pointer.
TEST(ResultOfDeathTest,DiesOnNullFunctionPointers)1011 TEST(ResultOfDeathTest, DiesOnNullFunctionPointers) {
1012 EXPECT_DEATH_IF_SUPPORTED(
1013 ResultOf(static_cast<std::string (*)(int dummy)>(nullptr),
1014 Eq(std::string("foo"))),
1015 "NULL function pointer is passed into ResultOf\\(\\)\\.");
1016 }
1017
1018 // Tests that ResultOf(f, ...) compiles and works as expected when f is a
1019 // function reference.
TEST(ResultOfTest,WorksForFunctionReferences)1020 TEST(ResultOfTest, WorksForFunctionReferences) {
1021 Matcher<int> matcher = ResultOf(IntToStringFunction, StrEq("foo"));
1022 EXPECT_TRUE(matcher.Matches(1));
1023 EXPECT_FALSE(matcher.Matches(2));
1024 }
1025
1026 // Tests that ResultOf(f, ...) compiles and works as expected when f is a
1027 // function object.
1028 struct Functor {
operator ()testing::gmock_matchers_test::__anon0ad92c4b0111::Functor1029 std::string operator()(int input) const { return IntToStringFunction(input); }
1030 };
1031
TEST(ResultOfTest,WorksForFunctors)1032 TEST(ResultOfTest, WorksForFunctors) {
1033 Matcher<int> matcher = ResultOf(Functor(), Eq(std::string("foo")));
1034
1035 EXPECT_TRUE(matcher.Matches(1));
1036 EXPECT_FALSE(matcher.Matches(2));
1037 }
1038
1039 // Tests that ResultOf(f, ...) compiles and works as expected when f is a
1040 // functor with more than one operator() defined. ResultOf() must work
1041 // for each defined operator().
1042 struct PolymorphicFunctor {
1043 typedef int result_type;
operator ()testing::gmock_matchers_test::__anon0ad92c4b0111::PolymorphicFunctor1044 int operator()(int n) { return n; }
operator ()testing::gmock_matchers_test::__anon0ad92c4b0111::PolymorphicFunctor1045 int operator()(const char* s) { return static_cast<int>(strlen(s)); }
operator ()testing::gmock_matchers_test::__anon0ad92c4b0111::PolymorphicFunctor1046 std::string operator()(int* p) { return p ? "good ptr" : "null"; }
1047 };
1048
TEST(ResultOfTest,WorksForPolymorphicFunctors)1049 TEST(ResultOfTest, WorksForPolymorphicFunctors) {
1050 Matcher<int> matcher_int = ResultOf(PolymorphicFunctor(), Ge(5));
1051
1052 EXPECT_TRUE(matcher_int.Matches(10));
1053 EXPECT_FALSE(matcher_int.Matches(2));
1054
1055 Matcher<const char*> matcher_string = ResultOf(PolymorphicFunctor(), Ge(5));
1056
1057 EXPECT_TRUE(matcher_string.Matches("long string"));
1058 EXPECT_FALSE(matcher_string.Matches("shrt"));
1059 }
1060
TEST(ResultOfTest,WorksForPolymorphicFunctorsIgnoringResultType)1061 TEST(ResultOfTest, WorksForPolymorphicFunctorsIgnoringResultType) {
1062 Matcher<int*> matcher = ResultOf(PolymorphicFunctor(), "good ptr");
1063
1064 int n = 0;
1065 EXPECT_TRUE(matcher.Matches(&n));
1066 EXPECT_FALSE(matcher.Matches(nullptr));
1067 }
1068
TEST(ResultOfTest,WorksForLambdas)1069 TEST(ResultOfTest, WorksForLambdas) {
1070 Matcher<int> matcher = ResultOf(
1071 [](int str_len) {
1072 return std::string(static_cast<size_t>(str_len), 'x');
1073 },
1074 "xxx");
1075 EXPECT_TRUE(matcher.Matches(3));
1076 EXPECT_FALSE(matcher.Matches(1));
1077 }
1078
TEST(ResultOfTest,WorksForNonCopyableArguments)1079 TEST(ResultOfTest, WorksForNonCopyableArguments) {
1080 Matcher<std::unique_ptr<int>> matcher = ResultOf(
1081 [](const std::unique_ptr<int>& str_len) {
1082 return std::string(static_cast<size_t>(*str_len), 'x');
1083 },
1084 "xxx");
1085 EXPECT_TRUE(matcher.Matches(std::unique_ptr<int>(new int(3))));
1086 EXPECT_FALSE(matcher.Matches(std::unique_ptr<int>(new int(1))));
1087 }
1088
ReferencingFunction(const int & n)1089 const int* ReferencingFunction(const int& n) { return &n; }
1090
1091 struct ReferencingFunctor {
1092 typedef const int* result_type;
operator ()testing::gmock_matchers_test::__anon0ad92c4b0111::ReferencingFunctor1093 result_type operator()(const int& n) { return &n; }
1094 };
1095
TEST(ResultOfTest,WorksForReferencingCallables)1096 TEST(ResultOfTest, WorksForReferencingCallables) {
1097 const int n = 1;
1098 const int n2 = 1;
1099 Matcher<const int&> matcher2 = ResultOf(ReferencingFunction, Eq(&n));
1100 EXPECT_TRUE(matcher2.Matches(n));
1101 EXPECT_FALSE(matcher2.Matches(n2));
1102
1103 Matcher<const int&> matcher3 = ResultOf(ReferencingFunctor(), Eq(&n));
1104 EXPECT_TRUE(matcher3.Matches(n));
1105 EXPECT_FALSE(matcher3.Matches(n2));
1106 }
1107
TEST(SizeIsTest,ImplementsSizeIs)1108 TEST(SizeIsTest, ImplementsSizeIs) {
1109 vector<int> container;
1110 EXPECT_THAT(container, SizeIs(0));
1111 EXPECT_THAT(container, Not(SizeIs(1)));
1112 container.push_back(0);
1113 EXPECT_THAT(container, Not(SizeIs(0)));
1114 EXPECT_THAT(container, SizeIs(1));
1115 container.push_back(0);
1116 EXPECT_THAT(container, Not(SizeIs(0)));
1117 EXPECT_THAT(container, SizeIs(2));
1118 }
1119
TEST(SizeIsTest,WorksWithMap)1120 TEST(SizeIsTest, WorksWithMap) {
1121 map<std::string, int> container;
1122 EXPECT_THAT(container, SizeIs(0));
1123 EXPECT_THAT(container, Not(SizeIs(1)));
1124 container.insert(make_pair("foo", 1));
1125 EXPECT_THAT(container, Not(SizeIs(0)));
1126 EXPECT_THAT(container, SizeIs(1));
1127 container.insert(make_pair("bar", 2));
1128 EXPECT_THAT(container, Not(SizeIs(0)));
1129 EXPECT_THAT(container, SizeIs(2));
1130 }
1131
TEST(SizeIsTest,WorksWithReferences)1132 TEST(SizeIsTest, WorksWithReferences) {
1133 vector<int> container;
1134 Matcher<const vector<int>&> m = SizeIs(1);
1135 EXPECT_THAT(container, Not(m));
1136 container.push_back(0);
1137 EXPECT_THAT(container, m);
1138 }
1139
TEST(SizeIsTest,WorksWithMoveOnly)1140 TEST(SizeIsTest, WorksWithMoveOnly) {
1141 ContainerHelper helper;
1142 EXPECT_CALL(helper, Call(SizeIs(3)));
1143 helper.Call(MakeUniquePtrs({1, 2, 3}));
1144 }
1145
1146 // SizeIs should work for any type that provides a size() member function.
1147 // For example, a size_type member type should not need to be provided.
1148 struct MinimalistCustomType {
sizetesting::gmock_matchers_test::__anon0ad92c4b0111::MinimalistCustomType1149 int size() const { return 1; }
1150 };
TEST(SizeIsTest,WorksWithMinimalistCustomType)1151 TEST(SizeIsTest, WorksWithMinimalistCustomType) {
1152 MinimalistCustomType container;
1153 EXPECT_THAT(container, SizeIs(1));
1154 EXPECT_THAT(container, Not(SizeIs(0)));
1155 }
1156
TEST(SizeIsTest,CanDescribeSelf)1157 TEST(SizeIsTest, CanDescribeSelf) {
1158 Matcher<vector<int>> m = SizeIs(2);
1159 EXPECT_EQ("size is equal to 2", Describe(m));
1160 EXPECT_EQ("size isn't equal to 2", DescribeNegation(m));
1161 }
1162
TEST(SizeIsTest,ExplainsResult)1163 TEST(SizeIsTest, ExplainsResult) {
1164 Matcher<vector<int>> m1 = SizeIs(2);
1165 Matcher<vector<int>> m2 = SizeIs(Lt(2u));
1166 Matcher<vector<int>> m3 = SizeIs(AnyOf(0, 3));
1167 Matcher<vector<int>> m4 = SizeIs(Gt(1u));
1168 vector<int> container;
1169 EXPECT_EQ("whose size 0 doesn't match", Explain(m1, container));
1170 EXPECT_EQ("whose size 0 matches", Explain(m2, container));
1171 EXPECT_EQ("whose size 0 matches", Explain(m3, container));
1172 EXPECT_EQ("whose size 0 doesn't match", Explain(m4, container));
1173 container.push_back(0);
1174 container.push_back(0);
1175 EXPECT_EQ("whose size 2 matches", Explain(m1, container));
1176 EXPECT_EQ("whose size 2 doesn't match", Explain(m2, container));
1177 EXPECT_EQ("whose size 2 doesn't match", Explain(m3, container));
1178 EXPECT_EQ("whose size 2 matches", Explain(m4, container));
1179 }
1180
TEST(WhenSortedByTest,WorksForEmptyContainer)1181 TEST(WhenSortedByTest, WorksForEmptyContainer) {
1182 const vector<int> numbers;
1183 EXPECT_THAT(numbers, WhenSortedBy(less<int>(), ElementsAre()));
1184 EXPECT_THAT(numbers, Not(WhenSortedBy(less<int>(), ElementsAre(1))));
1185 }
1186
TEST(WhenSortedByTest,WorksForNonEmptyContainer)1187 TEST(WhenSortedByTest, WorksForNonEmptyContainer) {
1188 vector<unsigned> numbers;
1189 numbers.push_back(3);
1190 numbers.push_back(1);
1191 numbers.push_back(2);
1192 numbers.push_back(2);
1193 EXPECT_THAT(numbers,
1194 WhenSortedBy(greater<unsigned>(), ElementsAre(3, 2, 2, 1)));
1195 EXPECT_THAT(numbers,
1196 Not(WhenSortedBy(greater<unsigned>(), ElementsAre(1, 2, 2, 3))));
1197 }
1198
TEST(WhenSortedByTest,WorksForNonVectorContainer)1199 TEST(WhenSortedByTest, WorksForNonVectorContainer) {
1200 list<std::string> words;
1201 words.push_back("say");
1202 words.push_back("hello");
1203 words.push_back("world");
1204 EXPECT_THAT(words, WhenSortedBy(less<std::string>(),
1205 ElementsAre("hello", "say", "world")));
1206 EXPECT_THAT(words, Not(WhenSortedBy(less<std::string>(),
1207 ElementsAre("say", "hello", "world"))));
1208 }
1209
TEST(WhenSortedByTest,WorksForNativeArray)1210 TEST(WhenSortedByTest, WorksForNativeArray) {
1211 const int numbers[] = {1, 3, 2, 4};
1212 const int sorted_numbers[] = {1, 2, 3, 4};
1213 EXPECT_THAT(numbers, WhenSortedBy(less<int>(), ElementsAre(1, 2, 3, 4)));
1214 EXPECT_THAT(numbers,
1215 WhenSortedBy(less<int>(), ElementsAreArray(sorted_numbers)));
1216 EXPECT_THAT(numbers, Not(WhenSortedBy(less<int>(), ElementsAre(1, 3, 2, 4))));
1217 }
1218
TEST(WhenSortedByTest,CanDescribeSelf)1219 TEST(WhenSortedByTest, CanDescribeSelf) {
1220 const Matcher<vector<int>> m = WhenSortedBy(less<int>(), ElementsAre(1, 2));
1221 EXPECT_EQ(
1222 "(when sorted) has 2 elements where\n"
1223 "element #0 is equal to 1,\n"
1224 "element #1 is equal to 2",
1225 Describe(m));
1226 EXPECT_EQ(
1227 "(when sorted) doesn't have 2 elements, or\n"
1228 "element #0 isn't equal to 1, or\n"
1229 "element #1 isn't equal to 2",
1230 DescribeNegation(m));
1231 }
1232
TEST(WhenSortedByTest,ExplainsMatchResult)1233 TEST(WhenSortedByTest, ExplainsMatchResult) {
1234 const int a[] = {2, 1};
1235 EXPECT_EQ("which is { 1, 2 } when sorted, whose element #0 doesn't match",
1236 Explain(WhenSortedBy(less<int>(), ElementsAre(2, 3)), a));
1237 EXPECT_EQ("which is { 1, 2 } when sorted",
1238 Explain(WhenSortedBy(less<int>(), ElementsAre(1, 2)), a));
1239 }
1240
1241 // WhenSorted() is a simple wrapper on WhenSortedBy(). Hence we don't
1242 // need to test it as exhaustively as we test the latter.
1243
TEST(WhenSortedTest,WorksForEmptyContainer)1244 TEST(WhenSortedTest, WorksForEmptyContainer) {
1245 const vector<int> numbers;
1246 EXPECT_THAT(numbers, WhenSorted(ElementsAre()));
1247 EXPECT_THAT(numbers, Not(WhenSorted(ElementsAre(1))));
1248 }
1249
TEST(WhenSortedTest,WorksForNonEmptyContainer)1250 TEST(WhenSortedTest, WorksForNonEmptyContainer) {
1251 list<std::string> words;
1252 words.push_back("3");
1253 words.push_back("1");
1254 words.push_back("2");
1255 words.push_back("2");
1256 EXPECT_THAT(words, WhenSorted(ElementsAre("1", "2", "2", "3")));
1257 EXPECT_THAT(words, Not(WhenSorted(ElementsAre("3", "1", "2", "2"))));
1258 }
1259
TEST(WhenSortedTest,WorksForMapTypes)1260 TEST(WhenSortedTest, WorksForMapTypes) {
1261 map<std::string, int> word_counts;
1262 word_counts["and"] = 1;
1263 word_counts["the"] = 1;
1264 word_counts["buffalo"] = 2;
1265 EXPECT_THAT(word_counts,
1266 WhenSorted(ElementsAre(Pair("and", 1), Pair("buffalo", 2),
1267 Pair("the", 1))));
1268 EXPECT_THAT(word_counts,
1269 Not(WhenSorted(ElementsAre(Pair("and", 1), Pair("the", 1),
1270 Pair("buffalo", 2)))));
1271 }
1272
TEST(WhenSortedTest,WorksForMultiMapTypes)1273 TEST(WhenSortedTest, WorksForMultiMapTypes) {
1274 multimap<int, int> ifib;
1275 ifib.insert(make_pair(8, 6));
1276 ifib.insert(make_pair(2, 3));
1277 ifib.insert(make_pair(1, 1));
1278 ifib.insert(make_pair(3, 4));
1279 ifib.insert(make_pair(1, 2));
1280 ifib.insert(make_pair(5, 5));
1281 EXPECT_THAT(ifib,
1282 WhenSorted(ElementsAre(Pair(1, 1), Pair(1, 2), Pair(2, 3),
1283 Pair(3, 4), Pair(5, 5), Pair(8, 6))));
1284 EXPECT_THAT(ifib,
1285 Not(WhenSorted(ElementsAre(Pair(8, 6), Pair(2, 3), Pair(1, 1),
1286 Pair(3, 4), Pair(1, 2), Pair(5, 5)))));
1287 }
1288
TEST(WhenSortedTest,WorksForPolymorphicMatcher)1289 TEST(WhenSortedTest, WorksForPolymorphicMatcher) {
1290 std::deque<int> d;
1291 d.push_back(2);
1292 d.push_back(1);
1293 EXPECT_THAT(d, WhenSorted(ElementsAre(1, 2)));
1294 EXPECT_THAT(d, Not(WhenSorted(ElementsAre(2, 1))));
1295 }
1296
TEST(WhenSortedTest,WorksForVectorConstRefMatcher)1297 TEST(WhenSortedTest, WorksForVectorConstRefMatcher) {
1298 std::deque<int> d;
1299 d.push_back(2);
1300 d.push_back(1);
1301 Matcher<const std::vector<int>&> vector_match = ElementsAre(1, 2);
1302 EXPECT_THAT(d, WhenSorted(vector_match));
1303 Matcher<const std::vector<int>&> not_vector_match = ElementsAre(2, 1);
1304 EXPECT_THAT(d, Not(WhenSorted(not_vector_match)));
1305 }
1306
1307 // Deliberately bare pseudo-container.
1308 // Offers only begin() and end() accessors, yielding InputIterator.
1309 template <typename T>
1310 class Streamlike {
1311 private:
1312 class ConstIter;
1313
1314 public:
1315 typedef ConstIter const_iterator;
1316 typedef T value_type;
1317
1318 template <typename InIter>
Streamlike(InIter first,InIter last)1319 Streamlike(InIter first, InIter last) : remainder_(first, last) {}
1320
begin() const1321 const_iterator begin() const {
1322 return const_iterator(this, remainder_.begin());
1323 }
end() const1324 const_iterator end() const { return const_iterator(this, remainder_.end()); }
1325
1326 private:
1327 class ConstIter {
1328 public:
1329 using iterator_category = std::input_iterator_tag;
1330 using value_type = T;
1331 using difference_type = ptrdiff_t;
1332 using pointer = const value_type*;
1333 using reference = const value_type&;
1334
ConstIter(const Streamlike * s,typename std::list<value_type>::iterator pos)1335 ConstIter(const Streamlike* s, typename std::list<value_type>::iterator pos)
1336 : s_(s), pos_(pos) {}
1337
operator *() const1338 const value_type& operator*() const { return *pos_; }
operator ->() const1339 const value_type* operator->() const { return &*pos_; }
operator ++()1340 ConstIter& operator++() {
1341 s_->remainder_.erase(pos_++);
1342 return *this;
1343 }
1344
1345 // *iter++ is required to work (see std::istreambuf_iterator).
1346 // (void)iter++ is also required to work.
1347 class PostIncrProxy {
1348 public:
PostIncrProxy(const value_type & value)1349 explicit PostIncrProxy(const value_type& value) : value_(value) {}
operator *() const1350 value_type operator*() const { return value_; }
1351
1352 private:
1353 value_type value_;
1354 };
operator ++(int)1355 PostIncrProxy operator++(int) {
1356 PostIncrProxy proxy(**this);
1357 ++(*this);
1358 return proxy;
1359 }
1360
operator ==(const ConstIter & a,const ConstIter & b)1361 friend bool operator==(const ConstIter& a, const ConstIter& b) {
1362 return a.s_ == b.s_ && a.pos_ == b.pos_;
1363 }
operator !=(const ConstIter & a,const ConstIter & b)1364 friend bool operator!=(const ConstIter& a, const ConstIter& b) {
1365 return !(a == b);
1366 }
1367
1368 private:
1369 const Streamlike* s_;
1370 typename std::list<value_type>::iterator pos_;
1371 };
1372
operator <<(std::ostream & os,const Streamlike & s)1373 friend std::ostream& operator<<(std::ostream& os, const Streamlike& s) {
1374 os << "[";
1375 typedef typename std::list<value_type>::const_iterator Iter;
1376 const char* sep = "";
1377 for (Iter it = s.remainder_.begin(); it != s.remainder_.end(); ++it) {
1378 os << sep << *it;
1379 sep = ",";
1380 }
1381 os << "]";
1382 return os;
1383 }
1384
1385 mutable std::list<value_type> remainder_; // modified by iteration
1386 };
1387
TEST(StreamlikeTest,Iteration)1388 TEST(StreamlikeTest, Iteration) {
1389 const int a[5] = {2, 1, 4, 5, 3};
1390 Streamlike<int> s(a, a + 5);
1391 Streamlike<int>::const_iterator it = s.begin();
1392 const int* ip = a;
1393 while (it != s.end()) {
1394 SCOPED_TRACE(ip - a);
1395 EXPECT_EQ(*ip++, *it++);
1396 }
1397 }
1398
TEST(BeginEndDistanceIsTest,WorksWithForwardList)1399 TEST(BeginEndDistanceIsTest, WorksWithForwardList) {
1400 std::forward_list<int> container;
1401 EXPECT_THAT(container, BeginEndDistanceIs(0));
1402 EXPECT_THAT(container, Not(BeginEndDistanceIs(1)));
1403 container.push_front(0);
1404 EXPECT_THAT(container, Not(BeginEndDistanceIs(0)));
1405 EXPECT_THAT(container, BeginEndDistanceIs(1));
1406 container.push_front(0);
1407 EXPECT_THAT(container, Not(BeginEndDistanceIs(0)));
1408 EXPECT_THAT(container, BeginEndDistanceIs(2));
1409 }
1410
TEST(BeginEndDistanceIsTest,WorksWithNonStdList)1411 TEST(BeginEndDistanceIsTest, WorksWithNonStdList) {
1412 const int a[5] = {1, 2, 3, 4, 5};
1413 Streamlike<int> s(a, a + 5);
1414 EXPECT_THAT(s, BeginEndDistanceIs(5));
1415 }
1416
TEST(BeginEndDistanceIsTest,CanDescribeSelf)1417 TEST(BeginEndDistanceIsTest, CanDescribeSelf) {
1418 Matcher<vector<int>> m = BeginEndDistanceIs(2);
1419 EXPECT_EQ("distance between begin() and end() is equal to 2", Describe(m));
1420 EXPECT_EQ("distance between begin() and end() isn't equal to 2",
1421 DescribeNegation(m));
1422 }
1423
TEST(BeginEndDistanceIsTest,WorksWithMoveOnly)1424 TEST(BeginEndDistanceIsTest, WorksWithMoveOnly) {
1425 ContainerHelper helper;
1426 EXPECT_CALL(helper, Call(BeginEndDistanceIs(2)));
1427 helper.Call(MakeUniquePtrs({1, 2}));
1428 }
1429
TEST(BeginEndDistanceIsTest,ExplainsResult)1430 TEST(BeginEndDistanceIsTest, ExplainsResult) {
1431 Matcher<vector<int>> m1 = BeginEndDistanceIs(2);
1432 Matcher<vector<int>> m2 = BeginEndDistanceIs(Lt(2));
1433 Matcher<vector<int>> m3 = BeginEndDistanceIs(AnyOf(0, 3));
1434 Matcher<vector<int>> m4 = BeginEndDistanceIs(GreaterThan(1));
1435 vector<int> container;
1436 EXPECT_EQ("whose distance between begin() and end() 0 doesn't match",
1437 Explain(m1, container));
1438 EXPECT_EQ("whose distance between begin() and end() 0 matches",
1439 Explain(m2, container));
1440 EXPECT_EQ("whose distance between begin() and end() 0 matches",
1441 Explain(m3, container));
1442 EXPECT_EQ(
1443 "whose distance between begin() and end() 0 doesn't match, which is 1 "
1444 "less than 1",
1445 Explain(m4, container));
1446 container.push_back(0);
1447 container.push_back(0);
1448 EXPECT_EQ("whose distance between begin() and end() 2 matches",
1449 Explain(m1, container));
1450 EXPECT_EQ("whose distance between begin() and end() 2 doesn't match",
1451 Explain(m2, container));
1452 EXPECT_EQ("whose distance between begin() and end() 2 doesn't match",
1453 Explain(m3, container));
1454 EXPECT_EQ(
1455 "whose distance between begin() and end() 2 matches, which is 1 more "
1456 "than 1",
1457 Explain(m4, container));
1458 }
1459
TEST(WhenSortedTest,WorksForStreamlike)1460 TEST(WhenSortedTest, WorksForStreamlike) {
1461 // Streamlike 'container' provides only minimal iterator support.
1462 // Its iterators are tagged with input_iterator_tag.
1463 const int a[5] = {2, 1, 4, 5, 3};
1464 Streamlike<int> s(std::begin(a), std::end(a));
1465 EXPECT_THAT(s, WhenSorted(ElementsAre(1, 2, 3, 4, 5)));
1466 EXPECT_THAT(s, Not(WhenSorted(ElementsAre(2, 1, 4, 5, 3))));
1467 }
1468
TEST(WhenSortedTest,WorksForVectorConstRefMatcherOnStreamlike)1469 TEST(WhenSortedTest, WorksForVectorConstRefMatcherOnStreamlike) {
1470 const int a[] = {2, 1, 4, 5, 3};
1471 Streamlike<int> s(std::begin(a), std::end(a));
1472 Matcher<const std::vector<int>&> vector_match = ElementsAre(1, 2, 3, 4, 5);
1473 EXPECT_THAT(s, WhenSorted(vector_match));
1474 EXPECT_THAT(s, Not(WhenSorted(ElementsAre(2, 1, 4, 5, 3))));
1475 }
1476
TEST(IsSupersetOfTest,WorksForNativeArray)1477 TEST(IsSupersetOfTest, WorksForNativeArray) {
1478 const int subset[] = {1, 4};
1479 const int superset[] = {1, 2, 4};
1480 const int disjoint[] = {1, 0, 3};
1481 EXPECT_THAT(subset, IsSupersetOf(subset));
1482 EXPECT_THAT(subset, Not(IsSupersetOf(superset)));
1483 EXPECT_THAT(superset, IsSupersetOf(subset));
1484 EXPECT_THAT(subset, Not(IsSupersetOf(disjoint)));
1485 EXPECT_THAT(disjoint, Not(IsSupersetOf(subset)));
1486 }
1487
TEST(IsSupersetOfTest,WorksWithDuplicates)1488 TEST(IsSupersetOfTest, WorksWithDuplicates) {
1489 const int not_enough[] = {1, 2};
1490 const int enough[] = {1, 1, 2};
1491 const int expected[] = {1, 1};
1492 EXPECT_THAT(not_enough, Not(IsSupersetOf(expected)));
1493 EXPECT_THAT(enough, IsSupersetOf(expected));
1494 }
1495
TEST(IsSupersetOfTest,WorksForEmpty)1496 TEST(IsSupersetOfTest, WorksForEmpty) {
1497 vector<int> numbers;
1498 vector<int> expected;
1499 EXPECT_THAT(numbers, IsSupersetOf(expected));
1500 expected.push_back(1);
1501 EXPECT_THAT(numbers, Not(IsSupersetOf(expected)));
1502 expected.clear();
1503 numbers.push_back(1);
1504 numbers.push_back(2);
1505 EXPECT_THAT(numbers, IsSupersetOf(expected));
1506 expected.push_back(1);
1507 EXPECT_THAT(numbers, IsSupersetOf(expected));
1508 expected.push_back(2);
1509 EXPECT_THAT(numbers, IsSupersetOf(expected));
1510 expected.push_back(3);
1511 EXPECT_THAT(numbers, Not(IsSupersetOf(expected)));
1512 }
1513
TEST(IsSupersetOfTest,WorksForStreamlike)1514 TEST(IsSupersetOfTest, WorksForStreamlike) {
1515 const int a[5] = {1, 2, 3, 4, 5};
1516 Streamlike<int> s(std::begin(a), std::end(a));
1517
1518 vector<int> expected;
1519 expected.push_back(1);
1520 expected.push_back(2);
1521 expected.push_back(5);
1522 EXPECT_THAT(s, IsSupersetOf(expected));
1523
1524 expected.push_back(0);
1525 EXPECT_THAT(s, Not(IsSupersetOf(expected)));
1526 }
1527
TEST(IsSupersetOfTest,TakesStlContainer)1528 TEST(IsSupersetOfTest, TakesStlContainer) {
1529 const int actual[] = {3, 1, 2};
1530
1531 ::std::list<int> expected;
1532 expected.push_back(1);
1533 expected.push_back(3);
1534 EXPECT_THAT(actual, IsSupersetOf(expected));
1535
1536 expected.push_back(4);
1537 EXPECT_THAT(actual, Not(IsSupersetOf(expected)));
1538 }
1539
TEST(IsSupersetOfTest,Describe)1540 TEST(IsSupersetOfTest, Describe) {
1541 typedef std::vector<int> IntVec;
1542 IntVec expected;
1543 expected.push_back(111);
1544 expected.push_back(222);
1545 expected.push_back(333);
1546 EXPECT_THAT(
1547 Describe<IntVec>(IsSupersetOf(expected)),
1548 Eq("a surjection from elements to requirements exists such that:\n"
1549 " - an element is equal to 111\n"
1550 " - an element is equal to 222\n"
1551 " - an element is equal to 333"));
1552 }
1553
TEST(IsSupersetOfTest,DescribeNegation)1554 TEST(IsSupersetOfTest, DescribeNegation) {
1555 typedef std::vector<int> IntVec;
1556 IntVec expected;
1557 expected.push_back(111);
1558 expected.push_back(222);
1559 expected.push_back(333);
1560 EXPECT_THAT(
1561 DescribeNegation<IntVec>(IsSupersetOf(expected)),
1562 Eq("no surjection from elements to requirements exists such that:\n"
1563 " - an element is equal to 111\n"
1564 " - an element is equal to 222\n"
1565 " - an element is equal to 333"));
1566 }
1567
TEST(IsSupersetOfTest,MatchAndExplain)1568 TEST(IsSupersetOfTest, MatchAndExplain) {
1569 std::vector<int> v;
1570 v.push_back(2);
1571 v.push_back(3);
1572 std::vector<int> expected;
1573 expected.push_back(1);
1574 expected.push_back(2);
1575 StringMatchResultListener listener;
1576 ASSERT_FALSE(ExplainMatchResult(IsSupersetOf(expected), v, &listener))
1577 << listener.str();
1578 EXPECT_THAT(listener.str(),
1579 Eq("where the following matchers don't match any elements:\n"
1580 "matcher #0: is equal to 1"));
1581
1582 v.push_back(1);
1583 listener.Clear();
1584 ASSERT_TRUE(ExplainMatchResult(IsSupersetOf(expected), v, &listener))
1585 << listener.str();
1586 EXPECT_THAT(listener.str(), Eq("where:\n"
1587 " - element #0 is matched by matcher #1,\n"
1588 " - element #2 is matched by matcher #0"));
1589 }
1590
TEST(IsSupersetOfTest,WorksForRhsInitializerList)1591 TEST(IsSupersetOfTest, WorksForRhsInitializerList) {
1592 const int numbers[] = {1, 3, 6, 2, 4, 5};
1593 EXPECT_THAT(numbers, IsSupersetOf({1, 2}));
1594 EXPECT_THAT(numbers, Not(IsSupersetOf({3, 0})));
1595 }
1596
TEST(IsSupersetOfTest,WorksWithMoveOnly)1597 TEST(IsSupersetOfTest, WorksWithMoveOnly) {
1598 ContainerHelper helper;
1599 EXPECT_CALL(helper, Call(IsSupersetOf({Pointee(1)})));
1600 helper.Call(MakeUniquePtrs({1, 2}));
1601 EXPECT_CALL(helper, Call(Not(IsSupersetOf({Pointee(1), Pointee(2)}))));
1602 helper.Call(MakeUniquePtrs({2}));
1603 }
1604
TEST(IsSubsetOfTest,WorksForNativeArray)1605 TEST(IsSubsetOfTest, WorksForNativeArray) {
1606 const int subset[] = {1, 4};
1607 const int superset[] = {1, 2, 4};
1608 const int disjoint[] = {1, 0, 3};
1609 EXPECT_THAT(subset, IsSubsetOf(subset));
1610 EXPECT_THAT(subset, IsSubsetOf(superset));
1611 EXPECT_THAT(superset, Not(IsSubsetOf(subset)));
1612 EXPECT_THAT(subset, Not(IsSubsetOf(disjoint)));
1613 EXPECT_THAT(disjoint, Not(IsSubsetOf(subset)));
1614 }
1615
TEST(IsSubsetOfTest,WorksWithDuplicates)1616 TEST(IsSubsetOfTest, WorksWithDuplicates) {
1617 const int not_enough[] = {1, 2};
1618 const int enough[] = {1, 1, 2};
1619 const int actual[] = {1, 1};
1620 EXPECT_THAT(actual, Not(IsSubsetOf(not_enough)));
1621 EXPECT_THAT(actual, IsSubsetOf(enough));
1622 }
1623
TEST(IsSubsetOfTest,WorksForEmpty)1624 TEST(IsSubsetOfTest, WorksForEmpty) {
1625 vector<int> numbers;
1626 vector<int> expected;
1627 EXPECT_THAT(numbers, IsSubsetOf(expected));
1628 expected.push_back(1);
1629 EXPECT_THAT(numbers, IsSubsetOf(expected));
1630 expected.clear();
1631 numbers.push_back(1);
1632 numbers.push_back(2);
1633 EXPECT_THAT(numbers, Not(IsSubsetOf(expected)));
1634 expected.push_back(1);
1635 EXPECT_THAT(numbers, Not(IsSubsetOf(expected)));
1636 expected.push_back(2);
1637 EXPECT_THAT(numbers, IsSubsetOf(expected));
1638 expected.push_back(3);
1639 EXPECT_THAT(numbers, IsSubsetOf(expected));
1640 }
1641
TEST(IsSubsetOfTest,WorksForStreamlike)1642 TEST(IsSubsetOfTest, WorksForStreamlike) {
1643 const int a[5] = {1, 2};
1644 Streamlike<int> s(std::begin(a), std::end(a));
1645
1646 vector<int> expected;
1647 expected.push_back(1);
1648 EXPECT_THAT(s, Not(IsSubsetOf(expected)));
1649 expected.push_back(2);
1650 expected.push_back(5);
1651 EXPECT_THAT(s, IsSubsetOf(expected));
1652 }
1653
TEST(IsSubsetOfTest,TakesStlContainer)1654 TEST(IsSubsetOfTest, TakesStlContainer) {
1655 const int actual[] = {3, 1, 2};
1656
1657 ::std::list<int> expected;
1658 expected.push_back(1);
1659 expected.push_back(3);
1660 EXPECT_THAT(actual, Not(IsSubsetOf(expected)));
1661
1662 expected.push_back(2);
1663 expected.push_back(4);
1664 EXPECT_THAT(actual, IsSubsetOf(expected));
1665 }
1666
TEST(IsSubsetOfTest,Describe)1667 TEST(IsSubsetOfTest, Describe) {
1668 typedef std::vector<int> IntVec;
1669 IntVec expected;
1670 expected.push_back(111);
1671 expected.push_back(222);
1672 expected.push_back(333);
1673
1674 EXPECT_THAT(
1675 Describe<IntVec>(IsSubsetOf(expected)),
1676 Eq("an injection from elements to requirements exists such that:\n"
1677 " - an element is equal to 111\n"
1678 " - an element is equal to 222\n"
1679 " - an element is equal to 333"));
1680 }
1681
TEST(IsSubsetOfTest,DescribeNegation)1682 TEST(IsSubsetOfTest, DescribeNegation) {
1683 typedef std::vector<int> IntVec;
1684 IntVec expected;
1685 expected.push_back(111);
1686 expected.push_back(222);
1687 expected.push_back(333);
1688 EXPECT_THAT(
1689 DescribeNegation<IntVec>(IsSubsetOf(expected)),
1690 Eq("no injection from elements to requirements exists such that:\n"
1691 " - an element is equal to 111\n"
1692 " - an element is equal to 222\n"
1693 " - an element is equal to 333"));
1694 }
1695
TEST(IsSubsetOfTest,MatchAndExplain)1696 TEST(IsSubsetOfTest, MatchAndExplain) {
1697 std::vector<int> v;
1698 v.push_back(2);
1699 v.push_back(3);
1700 std::vector<int> expected;
1701 expected.push_back(1);
1702 expected.push_back(2);
1703 StringMatchResultListener listener;
1704 ASSERT_FALSE(ExplainMatchResult(IsSubsetOf(expected), v, &listener))
1705 << listener.str();
1706 EXPECT_THAT(listener.str(),
1707 Eq("where the following elements don't match any matchers:\n"
1708 "element #1: 3"));
1709
1710 expected.push_back(3);
1711 listener.Clear();
1712 ASSERT_TRUE(ExplainMatchResult(IsSubsetOf(expected), v, &listener))
1713 << listener.str();
1714 EXPECT_THAT(listener.str(), Eq("where:\n"
1715 " - element #0 is matched by matcher #1,\n"
1716 " - element #1 is matched by matcher #2"));
1717 }
1718
TEST(IsSubsetOfTest,WorksForRhsInitializerList)1719 TEST(IsSubsetOfTest, WorksForRhsInitializerList) {
1720 const int numbers[] = {1, 2, 3};
1721 EXPECT_THAT(numbers, IsSubsetOf({1, 2, 3, 4}));
1722 EXPECT_THAT(numbers, Not(IsSubsetOf({1, 2})));
1723 }
1724
TEST(IsSubsetOfTest,WorksWithMoveOnly)1725 TEST(IsSubsetOfTest, WorksWithMoveOnly) {
1726 ContainerHelper helper;
1727 EXPECT_CALL(helper, Call(IsSubsetOf({Pointee(1), Pointee(2)})));
1728 helper.Call(MakeUniquePtrs({1}));
1729 EXPECT_CALL(helper, Call(Not(IsSubsetOf({Pointee(1)}))));
1730 helper.Call(MakeUniquePtrs({2}));
1731 }
1732
1733 // Tests using ElementsAre() and ElementsAreArray() with stream-like
1734 // "containers".
1735
TEST(ElemensAreStreamTest,WorksForStreamlike)1736 TEST(ElemensAreStreamTest, WorksForStreamlike) {
1737 const int a[5] = {1, 2, 3, 4, 5};
1738 Streamlike<int> s(std::begin(a), std::end(a));
1739 EXPECT_THAT(s, ElementsAre(1, 2, 3, 4, 5));
1740 EXPECT_THAT(s, Not(ElementsAre(2, 1, 4, 5, 3)));
1741 }
1742
TEST(ElemensAreArrayStreamTest,WorksForStreamlike)1743 TEST(ElemensAreArrayStreamTest, WorksForStreamlike) {
1744 const int a[5] = {1, 2, 3, 4, 5};
1745 Streamlike<int> s(std::begin(a), std::end(a));
1746
1747 vector<int> expected;
1748 expected.push_back(1);
1749 expected.push_back(2);
1750 expected.push_back(3);
1751 expected.push_back(4);
1752 expected.push_back(5);
1753 EXPECT_THAT(s, ElementsAreArray(expected));
1754
1755 expected[3] = 0;
1756 EXPECT_THAT(s, Not(ElementsAreArray(expected)));
1757 }
1758
TEST(ElementsAreTest,WorksWithUncopyable)1759 TEST(ElementsAreTest, WorksWithUncopyable) {
1760 Uncopyable objs[2];
1761 objs[0].set_value(-3);
1762 objs[1].set_value(1);
1763 EXPECT_THAT(objs, ElementsAre(UncopyableIs(-3), Truly(ValueIsPositive)));
1764 }
1765
TEST(ElementsAreTest,WorksWithMoveOnly)1766 TEST(ElementsAreTest, WorksWithMoveOnly) {
1767 ContainerHelper helper;
1768 EXPECT_CALL(helper, Call(ElementsAre(Pointee(1), Pointee(2))));
1769 helper.Call(MakeUniquePtrs({1, 2}));
1770
1771 EXPECT_CALL(helper, Call(ElementsAreArray({Pointee(3), Pointee(4)})));
1772 helper.Call(MakeUniquePtrs({3, 4}));
1773 }
1774
TEST(ElementsAreTest,TakesStlContainer)1775 TEST(ElementsAreTest, TakesStlContainer) {
1776 const int actual[] = {3, 1, 2};
1777
1778 ::std::list<int> expected;
1779 expected.push_back(3);
1780 expected.push_back(1);
1781 expected.push_back(2);
1782 EXPECT_THAT(actual, ElementsAreArray(expected));
1783
1784 expected.push_back(4);
1785 EXPECT_THAT(actual, Not(ElementsAreArray(expected)));
1786 }
1787
1788 // Tests for UnorderedElementsAreArray()
1789
TEST(UnorderedElementsAreArrayTest,SucceedsWhenExpected)1790 TEST(UnorderedElementsAreArrayTest, SucceedsWhenExpected) {
1791 const int a[] = {0, 1, 2, 3, 4};
1792 std::vector<int> s(std::begin(a), std::end(a));
1793 do {
1794 StringMatchResultListener listener;
1795 EXPECT_TRUE(ExplainMatchResult(UnorderedElementsAreArray(a), s, &listener))
1796 << listener.str();
1797 } while (std::next_permutation(s.begin(), s.end()));
1798 }
1799
TEST(UnorderedElementsAreArrayTest,VectorBool)1800 TEST(UnorderedElementsAreArrayTest, VectorBool) {
1801 const bool a[] = {0, 1, 0, 1, 1};
1802 const bool b[] = {1, 0, 1, 1, 0};
1803 std::vector<bool> expected(std::begin(a), std::end(a));
1804 std::vector<bool> actual(std::begin(b), std::end(b));
1805 StringMatchResultListener listener;
1806 EXPECT_TRUE(ExplainMatchResult(UnorderedElementsAreArray(expected), actual,
1807 &listener))
1808 << listener.str();
1809 }
1810
TEST(UnorderedElementsAreArrayTest,WorksForStreamlike)1811 TEST(UnorderedElementsAreArrayTest, WorksForStreamlike) {
1812 // Streamlike 'container' provides only minimal iterator support.
1813 // Its iterators are tagged with input_iterator_tag, and it has no
1814 // size() or empty() methods.
1815 const int a[5] = {2, 1, 4, 5, 3};
1816 Streamlike<int> s(std::begin(a), std::end(a));
1817
1818 ::std::vector<int> expected;
1819 expected.push_back(1);
1820 expected.push_back(2);
1821 expected.push_back(3);
1822 expected.push_back(4);
1823 expected.push_back(5);
1824 EXPECT_THAT(s, UnorderedElementsAreArray(expected));
1825
1826 expected.push_back(6);
1827 EXPECT_THAT(s, Not(UnorderedElementsAreArray(expected)));
1828 }
1829
TEST(UnorderedElementsAreArrayTest,TakesStlContainer)1830 TEST(UnorderedElementsAreArrayTest, TakesStlContainer) {
1831 const int actual[] = {3, 1, 2};
1832
1833 ::std::list<int> expected;
1834 expected.push_back(1);
1835 expected.push_back(2);
1836 expected.push_back(3);
1837 EXPECT_THAT(actual, UnorderedElementsAreArray(expected));
1838
1839 expected.push_back(4);
1840 EXPECT_THAT(actual, Not(UnorderedElementsAreArray(expected)));
1841 }
1842
TEST(UnorderedElementsAreArrayTest,TakesInitializerList)1843 TEST(UnorderedElementsAreArrayTest, TakesInitializerList) {
1844 const int a[5] = {2, 1, 4, 5, 3};
1845 EXPECT_THAT(a, UnorderedElementsAreArray({1, 2, 3, 4, 5}));
1846 EXPECT_THAT(a, Not(UnorderedElementsAreArray({1, 2, 3, 4, 6})));
1847 }
1848
TEST(UnorderedElementsAreArrayTest,TakesInitializerListOfCStrings)1849 TEST(UnorderedElementsAreArrayTest, TakesInitializerListOfCStrings) {
1850 const std::string a[5] = {"a", "b", "c", "d", "e"};
1851 EXPECT_THAT(a, UnorderedElementsAreArray({"a", "b", "c", "d", "e"}));
1852 EXPECT_THAT(a, Not(UnorderedElementsAreArray({"a", "b", "c", "d", "ef"})));
1853 }
1854
TEST(UnorderedElementsAreArrayTest,TakesInitializerListOfSameTypedMatchers)1855 TEST(UnorderedElementsAreArrayTest, TakesInitializerListOfSameTypedMatchers) {
1856 const int a[5] = {2, 1, 4, 5, 3};
1857 EXPECT_THAT(a,
1858 UnorderedElementsAreArray({Eq(1), Eq(2), Eq(3), Eq(4), Eq(5)}));
1859 EXPECT_THAT(
1860 a, Not(UnorderedElementsAreArray({Eq(1), Eq(2), Eq(3), Eq(4), Eq(6)})));
1861 }
1862
TEST(UnorderedElementsAreArrayTest,TakesInitializerListOfDifferentTypedMatchers)1863 TEST(UnorderedElementsAreArrayTest,
1864 TakesInitializerListOfDifferentTypedMatchers) {
1865 const int a[5] = {2, 1, 4, 5, 3};
1866 // The compiler cannot infer the type of the initializer list if its
1867 // elements have different types. We must explicitly specify the
1868 // unified element type in this case.
1869 EXPECT_THAT(a, UnorderedElementsAreArray<Matcher<int>>(
1870 {Eq(1), Ne(-2), Ge(3), Le(4), Eq(5)}));
1871 EXPECT_THAT(a, Not(UnorderedElementsAreArray<Matcher<int>>(
1872 {Eq(1), Ne(-2), Ge(3), Le(4), Eq(6)})));
1873 }
1874
TEST(UnorderedElementsAreArrayTest,WorksWithMoveOnly)1875 TEST(UnorderedElementsAreArrayTest, WorksWithMoveOnly) {
1876 ContainerHelper helper;
1877 EXPECT_CALL(helper,
1878 Call(UnorderedElementsAreArray({Pointee(1), Pointee(2)})));
1879 helper.Call(MakeUniquePtrs({2, 1}));
1880 }
1881
1882 class UnorderedElementsAreTest : public testing::Test {
1883 protected:
1884 typedef std::vector<int> IntVec;
1885 };
1886
TEST_F(UnorderedElementsAreTest,WorksWithUncopyable)1887 TEST_F(UnorderedElementsAreTest, WorksWithUncopyable) {
1888 Uncopyable objs[2];
1889 objs[0].set_value(-3);
1890 objs[1].set_value(1);
1891 EXPECT_THAT(objs,
1892 UnorderedElementsAre(Truly(ValueIsPositive), UncopyableIs(-3)));
1893 }
1894
TEST_F(UnorderedElementsAreTest,SucceedsWhenExpected)1895 TEST_F(UnorderedElementsAreTest, SucceedsWhenExpected) {
1896 const int a[] = {1, 2, 3};
1897 std::vector<int> s(std::begin(a), std::end(a));
1898 do {
1899 StringMatchResultListener listener;
1900 EXPECT_TRUE(ExplainMatchResult(UnorderedElementsAre(1, 2, 3), s, &listener))
1901 << listener.str();
1902 } while (std::next_permutation(s.begin(), s.end()));
1903 }
1904
TEST_F(UnorderedElementsAreTest,FailsWhenAnElementMatchesNoMatcher)1905 TEST_F(UnorderedElementsAreTest, FailsWhenAnElementMatchesNoMatcher) {
1906 const int a[] = {1, 2, 3};
1907 std::vector<int> s(std::begin(a), std::end(a));
1908 std::vector<Matcher<int>> mv;
1909 mv.push_back(1);
1910 mv.push_back(2);
1911 mv.push_back(2);
1912 // The element with value '3' matches nothing: fail fast.
1913 StringMatchResultListener listener;
1914 EXPECT_FALSE(ExplainMatchResult(UnorderedElementsAreArray(mv), s, &listener))
1915 << listener.str();
1916 }
1917
TEST_F(UnorderedElementsAreTest,WorksForStreamlike)1918 TEST_F(UnorderedElementsAreTest, WorksForStreamlike) {
1919 // Streamlike 'container' provides only minimal iterator support.
1920 // Its iterators are tagged with input_iterator_tag, and it has no
1921 // size() or empty() methods.
1922 const int a[5] = {2, 1, 4, 5, 3};
1923 Streamlike<int> s(std::begin(a), std::end(a));
1924
1925 EXPECT_THAT(s, UnorderedElementsAre(1, 2, 3, 4, 5));
1926 EXPECT_THAT(s, Not(UnorderedElementsAre(2, 2, 3, 4, 5)));
1927 }
1928
TEST_F(UnorderedElementsAreTest,WorksWithMoveOnly)1929 TEST_F(UnorderedElementsAreTest, WorksWithMoveOnly) {
1930 ContainerHelper helper;
1931 EXPECT_CALL(helper, Call(UnorderedElementsAre(Pointee(1), Pointee(2))));
1932 helper.Call(MakeUniquePtrs({2, 1}));
1933 }
1934
1935 // One naive implementation of the matcher runs in O(N!) time, which is too
1936 // slow for many real-world inputs. This test shows that our matcher can match
1937 // 100 inputs very quickly (a few milliseconds). An O(100!) is 10^158
1938 // iterations and obviously effectively incomputable.
1939 // [ RUN ] UnorderedElementsAreTest.Performance
1940 // [ OK ] UnorderedElementsAreTest.Performance (4 ms)
TEST_F(UnorderedElementsAreTest,Performance)1941 TEST_F(UnorderedElementsAreTest, Performance) {
1942 std::vector<int> s;
1943 std::vector<Matcher<int>> mv;
1944 for (int i = 0; i < 100; ++i) {
1945 s.push_back(i);
1946 mv.push_back(_);
1947 }
1948 mv[50] = Eq(0);
1949 StringMatchResultListener listener;
1950 EXPECT_TRUE(ExplainMatchResult(UnorderedElementsAreArray(mv), s, &listener))
1951 << listener.str();
1952 }
1953
1954 // Another variant of 'Performance' with similar expectations.
1955 // [ RUN ] UnorderedElementsAreTest.PerformanceHalfStrict
1956 // [ OK ] UnorderedElementsAreTest.PerformanceHalfStrict (4 ms)
TEST_F(UnorderedElementsAreTest,PerformanceHalfStrict)1957 TEST_F(UnorderedElementsAreTest, PerformanceHalfStrict) {
1958 std::vector<int> s;
1959 std::vector<Matcher<int>> mv;
1960 for (int i = 0; i < 100; ++i) {
1961 s.push_back(i);
1962 if (i & 1) {
1963 mv.push_back(_);
1964 } else {
1965 mv.push_back(i);
1966 }
1967 }
1968 StringMatchResultListener listener;
1969 EXPECT_TRUE(ExplainMatchResult(UnorderedElementsAreArray(mv), s, &listener))
1970 << listener.str();
1971 }
1972
TEST_F(UnorderedElementsAreTest,FailMessageCountWrong)1973 TEST_F(UnorderedElementsAreTest, FailMessageCountWrong) {
1974 std::vector<int> v;
1975 v.push_back(4);
1976 StringMatchResultListener listener;
1977 EXPECT_FALSE(ExplainMatchResult(UnorderedElementsAre(1, 2, 3), v, &listener))
1978 << listener.str();
1979 EXPECT_THAT(listener.str(), Eq("which has 1 element"));
1980 }
1981
TEST_F(UnorderedElementsAreTest,FailMessageCountWrongZero)1982 TEST_F(UnorderedElementsAreTest, FailMessageCountWrongZero) {
1983 std::vector<int> v;
1984 StringMatchResultListener listener;
1985 EXPECT_FALSE(ExplainMatchResult(UnorderedElementsAre(1, 2, 3), v, &listener))
1986 << listener.str();
1987 EXPECT_THAT(listener.str(), Eq(""));
1988 }
1989
TEST_F(UnorderedElementsAreTest,FailMessageUnmatchedMatchers)1990 TEST_F(UnorderedElementsAreTest, FailMessageUnmatchedMatchers) {
1991 std::vector<int> v;
1992 v.push_back(1);
1993 v.push_back(1);
1994 StringMatchResultListener listener;
1995 EXPECT_FALSE(ExplainMatchResult(UnorderedElementsAre(1, 2), v, &listener))
1996 << listener.str();
1997 EXPECT_THAT(listener.str(),
1998 Eq("where the following matchers don't match any elements:\n"
1999 "matcher #1: is equal to 2"));
2000 }
2001
TEST_F(UnorderedElementsAreTest,FailMessageUnmatchedElements)2002 TEST_F(UnorderedElementsAreTest, FailMessageUnmatchedElements) {
2003 std::vector<int> v;
2004 v.push_back(1);
2005 v.push_back(2);
2006 StringMatchResultListener listener;
2007 EXPECT_FALSE(ExplainMatchResult(UnorderedElementsAre(1, 1), v, &listener))
2008 << listener.str();
2009 EXPECT_THAT(listener.str(),
2010 Eq("where the following elements don't match any matchers:\n"
2011 "element #1: 2"));
2012 }
2013
TEST_F(UnorderedElementsAreTest,FailMessageUnmatchedMatcherAndElement)2014 TEST_F(UnorderedElementsAreTest, FailMessageUnmatchedMatcherAndElement) {
2015 std::vector<int> v;
2016 v.push_back(2);
2017 v.push_back(3);
2018 StringMatchResultListener listener;
2019 EXPECT_FALSE(ExplainMatchResult(UnorderedElementsAre(1, 2), v, &listener))
2020 << listener.str();
2021 EXPECT_THAT(listener.str(),
2022 Eq("where"
2023 " the following matchers don't match any elements:\n"
2024 "matcher #0: is equal to 1\n"
2025 "and"
2026 " where"
2027 " the following elements don't match any matchers:\n"
2028 "element #1: 3"));
2029 }
2030
2031 // Test helper for formatting element, matcher index pairs in expectations.
EMString(int element,int matcher)2032 static std::string EMString(int element, int matcher) {
2033 stringstream ss;
2034 ss << "(element #" << element << ", matcher #" << matcher << ")";
2035 return ss.str();
2036 }
2037
TEST_F(UnorderedElementsAreTest,FailMessageImperfectMatchOnly)2038 TEST_F(UnorderedElementsAreTest, FailMessageImperfectMatchOnly) {
2039 // A situation where all elements and matchers have a match
2040 // associated with them, but the max matching is not perfect.
2041 std::vector<std::string> v;
2042 v.push_back("a");
2043 v.push_back("b");
2044 v.push_back("c");
2045 StringMatchResultListener listener;
2046 EXPECT_FALSE(ExplainMatchResult(
2047 UnorderedElementsAre("a", "a", AnyOf("b", "c")), v, &listener))
2048 << listener.str();
2049
2050 std::string prefix =
2051 "where no permutation of the elements can satisfy all matchers, "
2052 "and the closest match is 2 of 3 matchers with the "
2053 "pairings:\n";
2054
2055 // We have to be a bit loose here, because there are 4 valid max matches.
2056 EXPECT_THAT(
2057 listener.str(),
2058 AnyOf(
2059 prefix + "{\n " + EMString(0, 0) + ",\n " + EMString(1, 2) + "\n}",
2060 prefix + "{\n " + EMString(0, 1) + ",\n " + EMString(1, 2) + "\n}",
2061 prefix + "{\n " + EMString(0, 0) + ",\n " + EMString(2, 2) + "\n}",
2062 prefix + "{\n " + EMString(0, 1) + ",\n " + EMString(2, 2) +
2063 "\n}"));
2064 }
2065
TEST_F(UnorderedElementsAreTest,Describe)2066 TEST_F(UnorderedElementsAreTest, Describe) {
2067 EXPECT_THAT(Describe<IntVec>(UnorderedElementsAre()), Eq("is empty"));
2068 EXPECT_THAT(Describe<IntVec>(UnorderedElementsAre(345)),
2069 Eq("has 1 element and that element is equal to 345"));
2070 EXPECT_THAT(Describe<IntVec>(UnorderedElementsAre(111, 222, 333)),
2071 Eq("has 3 elements and there exists some permutation "
2072 "of elements such that:\n"
2073 " - element #0 is equal to 111, and\n"
2074 " - element #1 is equal to 222, and\n"
2075 " - element #2 is equal to 333"));
2076 }
2077
TEST_F(UnorderedElementsAreTest,DescribeNegation)2078 TEST_F(UnorderedElementsAreTest, DescribeNegation) {
2079 EXPECT_THAT(DescribeNegation<IntVec>(UnorderedElementsAre()),
2080 Eq("isn't empty"));
2081 EXPECT_THAT(
2082 DescribeNegation<IntVec>(UnorderedElementsAre(345)),
2083 Eq("doesn't have 1 element, or has 1 element that isn't equal to 345"));
2084 EXPECT_THAT(DescribeNegation<IntVec>(UnorderedElementsAre(123, 234, 345)),
2085 Eq("doesn't have 3 elements, or there exists no permutation "
2086 "of elements such that:\n"
2087 " - element #0 is equal to 123, and\n"
2088 " - element #1 is equal to 234, and\n"
2089 " - element #2 is equal to 345"));
2090 }
2091
2092 // Tests Each().
2093
TEST(EachTest,ExplainsMatchResultCorrectly)2094 TEST(EachTest, ExplainsMatchResultCorrectly) {
2095 set<int> a; // empty
2096
2097 Matcher<set<int>> m = Each(2);
2098 EXPECT_EQ("", Explain(m, a));
2099
2100 Matcher<const int(&)[1]> n = Each(1); // NOLINT
2101
2102 const int b[1] = {1};
2103 EXPECT_EQ("", Explain(n, b));
2104
2105 n = Each(3);
2106 EXPECT_EQ("whose element #0 doesn't match", Explain(n, b));
2107
2108 a.insert(1);
2109 a.insert(2);
2110 a.insert(3);
2111 m = Each(GreaterThan(0));
2112 EXPECT_EQ("", Explain(m, a));
2113
2114 m = Each(GreaterThan(10));
2115 EXPECT_EQ("whose element #0 doesn't match, which is 9 less than 10",
2116 Explain(m, a));
2117 }
2118
TEST(EachTest,DescribesItselfCorrectly)2119 TEST(EachTest, DescribesItselfCorrectly) {
2120 Matcher<vector<int>> m = Each(1);
2121 EXPECT_EQ("only contains elements that is equal to 1", Describe(m));
2122
2123 Matcher<vector<int>> m2 = Not(m);
2124 EXPECT_EQ("contains some element that isn't equal to 1", Describe(m2));
2125 }
2126
TEST(EachTest,MatchesVectorWhenAllElementsMatch)2127 TEST(EachTest, MatchesVectorWhenAllElementsMatch) {
2128 vector<int> some_vector;
2129 EXPECT_THAT(some_vector, Each(1));
2130 some_vector.push_back(3);
2131 EXPECT_THAT(some_vector, Not(Each(1)));
2132 EXPECT_THAT(some_vector, Each(3));
2133 some_vector.push_back(1);
2134 some_vector.push_back(2);
2135 EXPECT_THAT(some_vector, Not(Each(3)));
2136 EXPECT_THAT(some_vector, Each(Lt(3.5)));
2137
2138 vector<std::string> another_vector;
2139 another_vector.push_back("fee");
2140 EXPECT_THAT(another_vector, Each(std::string("fee")));
2141 another_vector.push_back("fie");
2142 another_vector.push_back("foe");
2143 another_vector.push_back("fum");
2144 EXPECT_THAT(another_vector, Not(Each(std::string("fee"))));
2145 }
2146
TEST(EachTest,MatchesMapWhenAllElementsMatch)2147 TEST(EachTest, MatchesMapWhenAllElementsMatch) {
2148 map<const char*, int> my_map;
2149 const char* bar = "a string";
2150 my_map[bar] = 2;
2151 EXPECT_THAT(my_map, Each(make_pair(bar, 2)));
2152
2153 map<std::string, int> another_map;
2154 EXPECT_THAT(another_map, Each(make_pair(std::string("fee"), 1)));
2155 another_map["fee"] = 1;
2156 EXPECT_THAT(another_map, Each(make_pair(std::string("fee"), 1)));
2157 another_map["fie"] = 2;
2158 another_map["foe"] = 3;
2159 another_map["fum"] = 4;
2160 EXPECT_THAT(another_map, Not(Each(make_pair(std::string("fee"), 1))));
2161 EXPECT_THAT(another_map, Not(Each(make_pair(std::string("fum"), 1))));
2162 EXPECT_THAT(another_map, Each(Pair(_, Gt(0))));
2163 }
2164
TEST(EachTest,AcceptsMatcher)2165 TEST(EachTest, AcceptsMatcher) {
2166 const int a[] = {1, 2, 3};
2167 EXPECT_THAT(a, Each(Gt(0)));
2168 EXPECT_THAT(a, Not(Each(Gt(1))));
2169 }
2170
TEST(EachTest,WorksForNativeArrayAsTuple)2171 TEST(EachTest, WorksForNativeArrayAsTuple) {
2172 const int a[] = {1, 2};
2173 const int* const pointer = a;
2174 EXPECT_THAT(std::make_tuple(pointer, 2), Each(Gt(0)));
2175 EXPECT_THAT(std::make_tuple(pointer, 2), Not(Each(Gt(1))));
2176 }
2177
TEST(EachTest,WorksWithMoveOnly)2178 TEST(EachTest, WorksWithMoveOnly) {
2179 ContainerHelper helper;
2180 EXPECT_CALL(helper, Call(Each(Pointee(Gt(0)))));
2181 helper.Call(MakeUniquePtrs({1, 2}));
2182 }
2183
2184 // For testing Pointwise().
2185 class IsHalfOfMatcher {
2186 public:
2187 template <typename T1, typename T2>
MatchAndExplain(const std::tuple<T1,T2> & a_pair,MatchResultListener * listener) const2188 bool MatchAndExplain(const std::tuple<T1, T2>& a_pair,
2189 MatchResultListener* listener) const {
2190 if (std::get<0>(a_pair) == std::get<1>(a_pair) / 2) {
2191 *listener << "where the second is " << std::get<1>(a_pair);
2192 return true;
2193 } else {
2194 *listener << "where the second/2 is " << std::get<1>(a_pair) / 2;
2195 return false;
2196 }
2197 }
2198
DescribeTo(ostream * os) const2199 void DescribeTo(ostream* os) const {
2200 *os << "are a pair where the first is half of the second";
2201 }
2202
DescribeNegationTo(ostream * os) const2203 void DescribeNegationTo(ostream* os) const {
2204 *os << "are a pair where the first isn't half of the second";
2205 }
2206 };
2207
IsHalfOf()2208 PolymorphicMatcher<IsHalfOfMatcher> IsHalfOf() {
2209 return MakePolymorphicMatcher(IsHalfOfMatcher());
2210 }
2211
TEST(PointwiseTest,DescribesSelf)2212 TEST(PointwiseTest, DescribesSelf) {
2213 vector<int> rhs;
2214 rhs.push_back(1);
2215 rhs.push_back(2);
2216 rhs.push_back(3);
2217 const Matcher<const vector<int>&> m = Pointwise(IsHalfOf(), rhs);
2218 EXPECT_EQ(
2219 "contains 3 values, where each value and its corresponding value "
2220 "in { 1, 2, 3 } are a pair where the first is half of the second",
2221 Describe(m));
2222 EXPECT_EQ(
2223 "doesn't contain exactly 3 values, or contains a value x at some "
2224 "index i where x and the i-th value of { 1, 2, 3 } are a pair "
2225 "where the first isn't half of the second",
2226 DescribeNegation(m));
2227 }
2228
TEST(PointwiseTest,MakesCopyOfRhs)2229 TEST(PointwiseTest, MakesCopyOfRhs) {
2230 list<signed char> rhs;
2231 rhs.push_back(2);
2232 rhs.push_back(4);
2233
2234 int lhs[] = {1, 2};
2235 const Matcher<const int(&)[2]> m = Pointwise(IsHalfOf(), rhs);
2236 EXPECT_THAT(lhs, m);
2237
2238 // Changing rhs now shouldn't affect m, which made a copy of rhs.
2239 rhs.push_back(6);
2240 EXPECT_THAT(lhs, m);
2241 }
2242
TEST(PointwiseTest,WorksForLhsNativeArray)2243 TEST(PointwiseTest, WorksForLhsNativeArray) {
2244 const int lhs[] = {1, 2, 3};
2245 vector<int> rhs;
2246 rhs.push_back(2);
2247 rhs.push_back(4);
2248 rhs.push_back(6);
2249 EXPECT_THAT(lhs, Pointwise(Lt(), rhs));
2250 EXPECT_THAT(lhs, Not(Pointwise(Gt(), rhs)));
2251 }
2252
TEST(PointwiseTest,WorksForRhsNativeArray)2253 TEST(PointwiseTest, WorksForRhsNativeArray) {
2254 const int rhs[] = {1, 2, 3};
2255 vector<int> lhs;
2256 lhs.push_back(2);
2257 lhs.push_back(4);
2258 lhs.push_back(6);
2259 EXPECT_THAT(lhs, Pointwise(Gt(), rhs));
2260 EXPECT_THAT(lhs, Not(Pointwise(Lt(), rhs)));
2261 }
2262
2263 // Test is effective only with sanitizers.
TEST(PointwiseTest,WorksForVectorOfBool)2264 TEST(PointwiseTest, WorksForVectorOfBool) {
2265 vector<bool> rhs(3, false);
2266 rhs[1] = true;
2267 vector<bool> lhs = rhs;
2268 EXPECT_THAT(lhs, Pointwise(Eq(), rhs));
2269 rhs[0] = true;
2270 EXPECT_THAT(lhs, Not(Pointwise(Eq(), rhs)));
2271 }
2272
TEST(PointwiseTest,WorksForRhsInitializerList)2273 TEST(PointwiseTest, WorksForRhsInitializerList) {
2274 const vector<int> lhs{2, 4, 6};
2275 EXPECT_THAT(lhs, Pointwise(Gt(), {1, 2, 3}));
2276 EXPECT_THAT(lhs, Not(Pointwise(Lt(), {3, 3, 7})));
2277 }
2278
TEST(PointwiseTest,RejectsWrongSize)2279 TEST(PointwiseTest, RejectsWrongSize) {
2280 const double lhs[2] = {1, 2};
2281 const int rhs[1] = {0};
2282 EXPECT_THAT(lhs, Not(Pointwise(Gt(), rhs)));
2283 EXPECT_EQ("which contains 2 values", Explain(Pointwise(Gt(), rhs), lhs));
2284
2285 const int rhs2[3] = {0, 1, 2};
2286 EXPECT_THAT(lhs, Not(Pointwise(Gt(), rhs2)));
2287 }
2288
TEST(PointwiseTest,RejectsWrongContent)2289 TEST(PointwiseTest, RejectsWrongContent) {
2290 const double lhs[3] = {1, 2, 3};
2291 const int rhs[3] = {2, 6, 4};
2292 EXPECT_THAT(lhs, Not(Pointwise(IsHalfOf(), rhs)));
2293 EXPECT_EQ(
2294 "where the value pair (2, 6) at index #1 don't match, "
2295 "where the second/2 is 3",
2296 Explain(Pointwise(IsHalfOf(), rhs), lhs));
2297 }
2298
TEST(PointwiseTest,AcceptsCorrectContent)2299 TEST(PointwiseTest, AcceptsCorrectContent) {
2300 const double lhs[3] = {1, 2, 3};
2301 const int rhs[3] = {2, 4, 6};
2302 EXPECT_THAT(lhs, Pointwise(IsHalfOf(), rhs));
2303 EXPECT_EQ("", Explain(Pointwise(IsHalfOf(), rhs), lhs));
2304 }
2305
TEST(PointwiseTest,AllowsMonomorphicInnerMatcher)2306 TEST(PointwiseTest, AllowsMonomorphicInnerMatcher) {
2307 const double lhs[3] = {1, 2, 3};
2308 const int rhs[3] = {2, 4, 6};
2309 const Matcher<std::tuple<const double&, const int&>> m1 = IsHalfOf();
2310 EXPECT_THAT(lhs, Pointwise(m1, rhs));
2311 EXPECT_EQ("", Explain(Pointwise(m1, rhs), lhs));
2312
2313 // This type works as a std::tuple<const double&, const int&> can be
2314 // implicitly cast to std::tuple<double, int>.
2315 const Matcher<std::tuple<double, int>> m2 = IsHalfOf();
2316 EXPECT_THAT(lhs, Pointwise(m2, rhs));
2317 EXPECT_EQ("", Explain(Pointwise(m2, rhs), lhs));
2318 }
2319
2320 MATCHER(PointeeEquals, "Points to an equal value") {
2321 return ExplainMatchResult(::testing::Pointee(::testing::get<1>(arg)),
2322 ::testing::get<0>(arg), result_listener);
2323 }
2324
TEST(PointwiseTest,WorksWithMoveOnly)2325 TEST(PointwiseTest, WorksWithMoveOnly) {
2326 ContainerHelper helper;
2327 EXPECT_CALL(helper, Call(Pointwise(PointeeEquals(), std::vector<int>{1, 2})));
2328 helper.Call(MakeUniquePtrs({1, 2}));
2329 }
2330
TEST(UnorderedPointwiseTest,DescribesSelf)2331 TEST(UnorderedPointwiseTest, DescribesSelf) {
2332 vector<int> rhs;
2333 rhs.push_back(1);
2334 rhs.push_back(2);
2335 rhs.push_back(3);
2336 const Matcher<const vector<int>&> m = UnorderedPointwise(IsHalfOf(), rhs);
2337 EXPECT_EQ(
2338 "has 3 elements and there exists some permutation of elements such "
2339 "that:\n"
2340 " - element #0 and 1 are a pair where the first is half of the second, "
2341 "and\n"
2342 " - element #1 and 2 are a pair where the first is half of the second, "
2343 "and\n"
2344 " - element #2 and 3 are a pair where the first is half of the second",
2345 Describe(m));
2346 EXPECT_EQ(
2347 "doesn't have 3 elements, or there exists no permutation of elements "
2348 "such that:\n"
2349 " - element #0 and 1 are a pair where the first is half of the second, "
2350 "and\n"
2351 " - element #1 and 2 are a pair where the first is half of the second, "
2352 "and\n"
2353 " - element #2 and 3 are a pair where the first is half of the second",
2354 DescribeNegation(m));
2355 }
2356
TEST(UnorderedPointwiseTest,MakesCopyOfRhs)2357 TEST(UnorderedPointwiseTest, MakesCopyOfRhs) {
2358 list<signed char> rhs;
2359 rhs.push_back(2);
2360 rhs.push_back(4);
2361
2362 int lhs[] = {2, 1};
2363 const Matcher<const int(&)[2]> m = UnorderedPointwise(IsHalfOf(), rhs);
2364 EXPECT_THAT(lhs, m);
2365
2366 // Changing rhs now shouldn't affect m, which made a copy of rhs.
2367 rhs.push_back(6);
2368 EXPECT_THAT(lhs, m);
2369 }
2370
TEST(UnorderedPointwiseTest,WorksForLhsNativeArray)2371 TEST(UnorderedPointwiseTest, WorksForLhsNativeArray) {
2372 const int lhs[] = {1, 2, 3};
2373 vector<int> rhs;
2374 rhs.push_back(4);
2375 rhs.push_back(6);
2376 rhs.push_back(2);
2377 EXPECT_THAT(lhs, UnorderedPointwise(Lt(), rhs));
2378 EXPECT_THAT(lhs, Not(UnorderedPointwise(Gt(), rhs)));
2379 }
2380
TEST(UnorderedPointwiseTest,WorksForRhsNativeArray)2381 TEST(UnorderedPointwiseTest, WorksForRhsNativeArray) {
2382 const int rhs[] = {1, 2, 3};
2383 vector<int> lhs;
2384 lhs.push_back(4);
2385 lhs.push_back(2);
2386 lhs.push_back(6);
2387 EXPECT_THAT(lhs, UnorderedPointwise(Gt(), rhs));
2388 EXPECT_THAT(lhs, Not(UnorderedPointwise(Lt(), rhs)));
2389 }
2390
TEST(UnorderedPointwiseTest,WorksForRhsInitializerList)2391 TEST(UnorderedPointwiseTest, WorksForRhsInitializerList) {
2392 const vector<int> lhs{2, 4, 6};
2393 EXPECT_THAT(lhs, UnorderedPointwise(Gt(), {5, 1, 3}));
2394 EXPECT_THAT(lhs, Not(UnorderedPointwise(Lt(), {1, 1, 7})));
2395 }
2396
TEST(UnorderedPointwiseTest,RejectsWrongSize)2397 TEST(UnorderedPointwiseTest, RejectsWrongSize) {
2398 const double lhs[2] = {1, 2};
2399 const int rhs[1] = {0};
2400 EXPECT_THAT(lhs, Not(UnorderedPointwise(Gt(), rhs)));
2401 EXPECT_EQ("which has 2 elements",
2402 Explain(UnorderedPointwise(Gt(), rhs), lhs));
2403
2404 const int rhs2[3] = {0, 1, 2};
2405 EXPECT_THAT(lhs, Not(UnorderedPointwise(Gt(), rhs2)));
2406 }
2407
TEST(UnorderedPointwiseTest,RejectsWrongContent)2408 TEST(UnorderedPointwiseTest, RejectsWrongContent) {
2409 const double lhs[3] = {1, 2, 3};
2410 const int rhs[3] = {2, 6, 6};
2411 EXPECT_THAT(lhs, Not(UnorderedPointwise(IsHalfOf(), rhs)));
2412 EXPECT_EQ(
2413 "where the following elements don't match any matchers:\n"
2414 "element #1: 2",
2415 Explain(UnorderedPointwise(IsHalfOf(), rhs), lhs));
2416 }
2417
TEST(UnorderedPointwiseTest,AcceptsCorrectContentInSameOrder)2418 TEST(UnorderedPointwiseTest, AcceptsCorrectContentInSameOrder) {
2419 const double lhs[3] = {1, 2, 3};
2420 const int rhs[3] = {2, 4, 6};
2421 EXPECT_THAT(lhs, UnorderedPointwise(IsHalfOf(), rhs));
2422 }
2423
TEST(UnorderedPointwiseTest,AcceptsCorrectContentInDifferentOrder)2424 TEST(UnorderedPointwiseTest, AcceptsCorrectContentInDifferentOrder) {
2425 const double lhs[3] = {1, 2, 3};
2426 const int rhs[3] = {6, 4, 2};
2427 EXPECT_THAT(lhs, UnorderedPointwise(IsHalfOf(), rhs));
2428 }
2429
TEST(UnorderedPointwiseTest,AllowsMonomorphicInnerMatcher)2430 TEST(UnorderedPointwiseTest, AllowsMonomorphicInnerMatcher) {
2431 const double lhs[3] = {1, 2, 3};
2432 const int rhs[3] = {4, 6, 2};
2433 const Matcher<std::tuple<const double&, const int&>> m1 = IsHalfOf();
2434 EXPECT_THAT(lhs, UnorderedPointwise(m1, rhs));
2435
2436 // This type works as a std::tuple<const double&, const int&> can be
2437 // implicitly cast to std::tuple<double, int>.
2438 const Matcher<std::tuple<double, int>> m2 = IsHalfOf();
2439 EXPECT_THAT(lhs, UnorderedPointwise(m2, rhs));
2440 }
2441
TEST(UnorderedPointwiseTest,WorksWithMoveOnly)2442 TEST(UnorderedPointwiseTest, WorksWithMoveOnly) {
2443 ContainerHelper helper;
2444 EXPECT_CALL(helper, Call(UnorderedPointwise(PointeeEquals(),
2445 std::vector<int>{1, 2})));
2446 helper.Call(MakeUniquePtrs({2, 1}));
2447 }
2448
TEST(PointeeTest,WorksOnMoveOnlyType)2449 TEST(PointeeTest, WorksOnMoveOnlyType) {
2450 std::unique_ptr<int> p(new int(3));
2451 EXPECT_THAT(p, Pointee(Eq(3)));
2452 EXPECT_THAT(p, Not(Pointee(Eq(2))));
2453 }
2454
2455 class PredicateFormatterFromMatcherTest : public ::testing::Test {
2456 protected:
2457 enum Behavior { kInitialSuccess, kAlwaysFail, kFlaky };
2458
2459 // A matcher that can return different results when used multiple times on the
2460 // same input. No real matcher should do this; but this lets us test that we
2461 // detect such behavior and fail appropriately.
2462 class MockMatcher : public MatcherInterface<Behavior> {
2463 public:
MatchAndExplain(Behavior behavior,MatchResultListener * listener) const2464 bool MatchAndExplain(Behavior behavior,
2465 MatchResultListener* listener) const override {
2466 *listener << "[MatchAndExplain]";
2467 switch (behavior) {
2468 case kInitialSuccess:
2469 // The first call to MatchAndExplain should use a "not interested"
2470 // listener; so this is expected to return |true|. There should be no
2471 // subsequent calls.
2472 return !listener->IsInterested();
2473
2474 case kAlwaysFail:
2475 return false;
2476
2477 case kFlaky:
2478 // The first call to MatchAndExplain should use a "not interested"
2479 // listener; so this will return |false|. Subsequent calls should have
2480 // an "interested" listener; so this will return |true|, thus
2481 // simulating a flaky matcher.
2482 return listener->IsInterested();
2483 }
2484
2485 GTEST_LOG_(FATAL) << "This should never be reached";
2486 return false;
2487 }
2488
DescribeTo(ostream * os) const2489 void DescribeTo(ostream* os) const override { *os << "[DescribeTo]"; }
2490
DescribeNegationTo(ostream * os) const2491 void DescribeNegationTo(ostream* os) const override {
2492 *os << "[DescribeNegationTo]";
2493 }
2494 };
2495
RunPredicateFormatter(Behavior behavior)2496 AssertionResult RunPredicateFormatter(Behavior behavior) {
2497 auto matcher = MakeMatcher(new MockMatcher);
2498 PredicateFormatterFromMatcher<Matcher<Behavior>> predicate_formatter(
2499 matcher);
2500 return predicate_formatter("dummy-name", behavior);
2501 }
2502 };
2503
TEST_F(PredicateFormatterFromMatcherTest,ShortCircuitOnSuccess)2504 TEST_F(PredicateFormatterFromMatcherTest, ShortCircuitOnSuccess) {
2505 AssertionResult result = RunPredicateFormatter(kInitialSuccess);
2506 EXPECT_TRUE(result); // Implicit cast to bool.
2507 std::string expect;
2508 EXPECT_EQ(expect, result.message());
2509 }
2510
TEST_F(PredicateFormatterFromMatcherTest,NoShortCircuitOnFailure)2511 TEST_F(PredicateFormatterFromMatcherTest, NoShortCircuitOnFailure) {
2512 AssertionResult result = RunPredicateFormatter(kAlwaysFail);
2513 EXPECT_FALSE(result); // Implicit cast to bool.
2514 std::string expect =
2515 "Value of: dummy-name\nExpected: [DescribeTo]\n"
2516 " Actual: 1" +
2517 OfType(internal::GetTypeName<Behavior>()) + ", [MatchAndExplain]";
2518 EXPECT_EQ(expect, result.message());
2519 }
2520
TEST_F(PredicateFormatterFromMatcherTest,DetectsFlakyShortCircuit)2521 TEST_F(PredicateFormatterFromMatcherTest, DetectsFlakyShortCircuit) {
2522 AssertionResult result = RunPredicateFormatter(kFlaky);
2523 EXPECT_FALSE(result); // Implicit cast to bool.
2524 std::string expect =
2525 "Value of: dummy-name\nExpected: [DescribeTo]\n"
2526 " The matcher failed on the initial attempt; but passed when rerun to "
2527 "generate the explanation.\n"
2528 " Actual: 2" +
2529 OfType(internal::GetTypeName<Behavior>()) + ", [MatchAndExplain]";
2530 EXPECT_EQ(expect, result.message());
2531 }
2532
2533 // Tests for ElementsAre().
2534
TEST(ElementsAreTest,CanDescribeExpectingNoElement)2535 TEST(ElementsAreTest, CanDescribeExpectingNoElement) {
2536 Matcher<const vector<int>&> m = ElementsAre();
2537 EXPECT_EQ("is empty", Describe(m));
2538 }
2539
TEST(ElementsAreTest,CanDescribeExpectingOneElement)2540 TEST(ElementsAreTest, CanDescribeExpectingOneElement) {
2541 Matcher<vector<int>> m = ElementsAre(Gt(5));
2542 EXPECT_EQ("has 1 element that is > 5", Describe(m));
2543 }
2544
TEST(ElementsAreTest,CanDescribeExpectingManyElements)2545 TEST(ElementsAreTest, CanDescribeExpectingManyElements) {
2546 Matcher<list<std::string>> m = ElementsAre(StrEq("one"), "two");
2547 EXPECT_EQ(
2548 "has 2 elements where\n"
2549 "element #0 is equal to \"one\",\n"
2550 "element #1 is equal to \"two\"",
2551 Describe(m));
2552 }
2553
TEST(ElementsAreTest,CanDescribeNegationOfExpectingNoElement)2554 TEST(ElementsAreTest, CanDescribeNegationOfExpectingNoElement) {
2555 Matcher<vector<int>> m = ElementsAre();
2556 EXPECT_EQ("isn't empty", DescribeNegation(m));
2557 }
2558
TEST(ElementsAreTest,CanDescribeNegationOfExpectingOneElement)2559 TEST(ElementsAreTest, CanDescribeNegationOfExpectingOneElement) {
2560 Matcher<const list<int>&> m = ElementsAre(Gt(5));
2561 EXPECT_EQ(
2562 "doesn't have 1 element, or\n"
2563 "element #0 isn't > 5",
2564 DescribeNegation(m));
2565 }
2566
TEST(ElementsAreTest,CanDescribeNegationOfExpectingManyElements)2567 TEST(ElementsAreTest, CanDescribeNegationOfExpectingManyElements) {
2568 Matcher<const list<std::string>&> m = ElementsAre("one", "two");
2569 EXPECT_EQ(
2570 "doesn't have 2 elements, or\n"
2571 "element #0 isn't equal to \"one\", or\n"
2572 "element #1 isn't equal to \"two\"",
2573 DescribeNegation(m));
2574 }
2575
TEST(ElementsAreTest,DoesNotExplainTrivialMatch)2576 TEST(ElementsAreTest, DoesNotExplainTrivialMatch) {
2577 Matcher<const list<int>&> m = ElementsAre(1, Ne(2));
2578
2579 list<int> test_list;
2580 test_list.push_back(1);
2581 test_list.push_back(3);
2582 EXPECT_EQ("", Explain(m, test_list)); // No need to explain anything.
2583 }
2584
TEST(ElementsAreTest,ExplainsNonTrivialMatch)2585 TEST(ElementsAreTest, ExplainsNonTrivialMatch) {
2586 Matcher<const vector<int>&> m =
2587 ElementsAre(GreaterThan(1), 0, GreaterThan(2));
2588
2589 const int a[] = {10, 0, 100};
2590 vector<int> test_vector(std::begin(a), std::end(a));
2591 EXPECT_EQ(
2592 "whose element #0 matches, which is 9 more than 1,\n"
2593 "and whose element #2 matches, which is 98 more than 2",
2594 Explain(m, test_vector));
2595 }
2596
TEST(ElementsAreTest,CanExplainMismatchWrongSize)2597 TEST(ElementsAreTest, CanExplainMismatchWrongSize) {
2598 Matcher<const list<int>&> m = ElementsAre(1, 3);
2599
2600 list<int> test_list;
2601 // No need to explain when the container is empty.
2602 EXPECT_EQ("", Explain(m, test_list));
2603
2604 test_list.push_back(1);
2605 EXPECT_EQ("which has 1 element", Explain(m, test_list));
2606 }
2607
TEST(ElementsAreTest,CanExplainMismatchRightSize)2608 TEST(ElementsAreTest, CanExplainMismatchRightSize) {
2609 Matcher<const vector<int>&> m = ElementsAre(1, GreaterThan(5));
2610
2611 vector<int> v;
2612 v.push_back(2);
2613 v.push_back(1);
2614 EXPECT_EQ("whose element #0 doesn't match", Explain(m, v));
2615
2616 v[0] = 1;
2617 EXPECT_EQ("whose element #1 doesn't match, which is 4 less than 5",
2618 Explain(m, v));
2619 }
2620
TEST(ElementsAreTest,MatchesOneElementVector)2621 TEST(ElementsAreTest, MatchesOneElementVector) {
2622 vector<std::string> test_vector;
2623 test_vector.push_back("test string");
2624
2625 EXPECT_THAT(test_vector, ElementsAre(StrEq("test string")));
2626 }
2627
TEST(ElementsAreTest,MatchesOneElementList)2628 TEST(ElementsAreTest, MatchesOneElementList) {
2629 list<std::string> test_list;
2630 test_list.push_back("test string");
2631
2632 EXPECT_THAT(test_list, ElementsAre("test string"));
2633 }
2634
TEST(ElementsAreTest,MatchesThreeElementVector)2635 TEST(ElementsAreTest, MatchesThreeElementVector) {
2636 vector<std::string> test_vector;
2637 test_vector.push_back("one");
2638 test_vector.push_back("two");
2639 test_vector.push_back("three");
2640
2641 EXPECT_THAT(test_vector, ElementsAre("one", StrEq("two"), _));
2642 }
2643
TEST(ElementsAreTest,MatchesOneElementEqMatcher)2644 TEST(ElementsAreTest, MatchesOneElementEqMatcher) {
2645 vector<int> test_vector;
2646 test_vector.push_back(4);
2647
2648 EXPECT_THAT(test_vector, ElementsAre(Eq(4)));
2649 }
2650
TEST(ElementsAreTest,MatchesOneElementAnyMatcher)2651 TEST(ElementsAreTest, MatchesOneElementAnyMatcher) {
2652 vector<int> test_vector;
2653 test_vector.push_back(4);
2654
2655 EXPECT_THAT(test_vector, ElementsAre(_));
2656 }
2657
TEST(ElementsAreTest,MatchesOneElementValue)2658 TEST(ElementsAreTest, MatchesOneElementValue) {
2659 vector<int> test_vector;
2660 test_vector.push_back(4);
2661
2662 EXPECT_THAT(test_vector, ElementsAre(4));
2663 }
2664
TEST(ElementsAreTest,MatchesThreeElementsMixedMatchers)2665 TEST(ElementsAreTest, MatchesThreeElementsMixedMatchers) {
2666 vector<int> test_vector;
2667 test_vector.push_back(1);
2668 test_vector.push_back(2);
2669 test_vector.push_back(3);
2670
2671 EXPECT_THAT(test_vector, ElementsAre(1, Eq(2), _));
2672 }
2673
TEST(ElementsAreTest,MatchesTenElementVector)2674 TEST(ElementsAreTest, MatchesTenElementVector) {
2675 const int a[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
2676 vector<int> test_vector(std::begin(a), std::end(a));
2677
2678 EXPECT_THAT(test_vector,
2679 // The element list can contain values and/or matchers
2680 // of different types.
2681 ElementsAre(0, Ge(0), _, 3, 4, Ne(2), Eq(6), 7, 8, _));
2682 }
2683
TEST(ElementsAreTest,DoesNotMatchWrongSize)2684 TEST(ElementsAreTest, DoesNotMatchWrongSize) {
2685 vector<std::string> test_vector;
2686 test_vector.push_back("test string");
2687 test_vector.push_back("test string");
2688
2689 Matcher<vector<std::string>> m = ElementsAre(StrEq("test string"));
2690 EXPECT_FALSE(m.Matches(test_vector));
2691 }
2692
TEST(ElementsAreTest,DoesNotMatchWrongValue)2693 TEST(ElementsAreTest, DoesNotMatchWrongValue) {
2694 vector<std::string> test_vector;
2695 test_vector.push_back("other string");
2696
2697 Matcher<vector<std::string>> m = ElementsAre(StrEq("test string"));
2698 EXPECT_FALSE(m.Matches(test_vector));
2699 }
2700
TEST(ElementsAreTest,DoesNotMatchWrongOrder)2701 TEST(ElementsAreTest, DoesNotMatchWrongOrder) {
2702 vector<std::string> test_vector;
2703 test_vector.push_back("one");
2704 test_vector.push_back("three");
2705 test_vector.push_back("two");
2706
2707 Matcher<vector<std::string>> m =
2708 ElementsAre(StrEq("one"), StrEq("two"), StrEq("three"));
2709 EXPECT_FALSE(m.Matches(test_vector));
2710 }
2711
TEST(ElementsAreTest,WorksForNestedContainer)2712 TEST(ElementsAreTest, WorksForNestedContainer) {
2713 constexpr std::array<const char*, 2> strings = {{"Hi", "world"}};
2714
2715 vector<list<char>> nested;
2716 for (const auto& s : strings) {
2717 nested.emplace_back(s, s + strlen(s));
2718 }
2719
2720 EXPECT_THAT(nested, ElementsAre(ElementsAre('H', Ne('e')),
2721 ElementsAre('w', 'o', _, _, 'd')));
2722 EXPECT_THAT(nested, Not(ElementsAre(ElementsAre('H', 'e'),
2723 ElementsAre('w', 'o', _, _, 'd'))));
2724 }
2725
TEST(ElementsAreTest,WorksWithByRefElementMatchers)2726 TEST(ElementsAreTest, WorksWithByRefElementMatchers) {
2727 int a[] = {0, 1, 2};
2728 vector<int> v(std::begin(a), std::end(a));
2729
2730 EXPECT_THAT(v, ElementsAre(Ref(v[0]), Ref(v[1]), Ref(v[2])));
2731 EXPECT_THAT(v, Not(ElementsAre(Ref(v[0]), Ref(v[1]), Ref(a[2]))));
2732 }
2733
TEST(ElementsAreTest,WorksWithContainerPointerUsingPointee)2734 TEST(ElementsAreTest, WorksWithContainerPointerUsingPointee) {
2735 int a[] = {0, 1, 2};
2736 vector<int> v(std::begin(a), std::end(a));
2737
2738 EXPECT_THAT(&v, Pointee(ElementsAre(0, 1, _)));
2739 EXPECT_THAT(&v, Not(Pointee(ElementsAre(0, _, 3))));
2740 }
2741
TEST(ElementsAreTest,WorksWithNativeArrayPassedByReference)2742 TEST(ElementsAreTest, WorksWithNativeArrayPassedByReference) {
2743 int array[] = {0, 1, 2};
2744 EXPECT_THAT(array, ElementsAre(0, 1, _));
2745 EXPECT_THAT(array, Not(ElementsAre(1, _, _)));
2746 EXPECT_THAT(array, Not(ElementsAre(0, _)));
2747 }
2748
2749 class NativeArrayPassedAsPointerAndSize {
2750 public:
NativeArrayPassedAsPointerAndSize()2751 NativeArrayPassedAsPointerAndSize() {}
2752
2753 MOCK_METHOD(void, Helper, (int* array, int size));
2754
2755 private:
2756 GTEST_DISALLOW_COPY_AND_ASSIGN_(NativeArrayPassedAsPointerAndSize);
2757 };
2758
TEST(ElementsAreTest,WorksWithNativeArrayPassedAsPointerAndSize)2759 TEST(ElementsAreTest, WorksWithNativeArrayPassedAsPointerAndSize) {
2760 int array[] = {0, 1};
2761 ::std::tuple<int*, size_t> array_as_tuple(array, 2);
2762 EXPECT_THAT(array_as_tuple, ElementsAre(0, 1));
2763 EXPECT_THAT(array_as_tuple, Not(ElementsAre(0)));
2764
2765 NativeArrayPassedAsPointerAndSize helper;
2766 EXPECT_CALL(helper, Helper(_, _)).With(ElementsAre(0, 1));
2767 helper.Helper(array, 2);
2768 }
2769
TEST(ElementsAreTest,WorksWithTwoDimensionalNativeArray)2770 TEST(ElementsAreTest, WorksWithTwoDimensionalNativeArray) {
2771 const char a2[][3] = {"hi", "lo"};
2772 EXPECT_THAT(a2, ElementsAre(ElementsAre('h', 'i', '\0'),
2773 ElementsAre('l', 'o', '\0')));
2774 EXPECT_THAT(a2, ElementsAre(StrEq("hi"), StrEq("lo")));
2775 EXPECT_THAT(a2, ElementsAre(Not(ElementsAre('h', 'o', '\0')),
2776 ElementsAre('l', 'o', '\0')));
2777 }
2778
TEST(ElementsAreTest,AcceptsStringLiteral)2779 TEST(ElementsAreTest, AcceptsStringLiteral) {
2780 std::string array[] = {"hi", "one", "two"};
2781 EXPECT_THAT(array, ElementsAre("hi", "one", "two"));
2782 EXPECT_THAT(array, Not(ElementsAre("hi", "one", "too")));
2783 }
2784
2785 // Declared here with the size unknown. Defined AFTER the following test.
2786 extern const char kHi[];
2787
TEST(ElementsAreTest,AcceptsArrayWithUnknownSize)2788 TEST(ElementsAreTest, AcceptsArrayWithUnknownSize) {
2789 // The size of kHi is not known in this test, but ElementsAre() should
2790 // still accept it.
2791
2792 std::string array1[] = {"hi"};
2793 EXPECT_THAT(array1, ElementsAre(kHi));
2794
2795 std::string array2[] = {"ho"};
2796 EXPECT_THAT(array2, Not(ElementsAre(kHi)));
2797 }
2798
2799 const char kHi[] = "hi";
2800
TEST(ElementsAreTest,MakesCopyOfArguments)2801 TEST(ElementsAreTest, MakesCopyOfArguments) {
2802 int x = 1;
2803 int y = 2;
2804 // This should make a copy of x and y.
2805 ::testing::internal::ElementsAreMatcher<std::tuple<int, int>>
2806 polymorphic_matcher = ElementsAre(x, y);
2807 // Changing x and y now shouldn't affect the meaning of the above matcher.
2808 x = y = 0;
2809 const int array1[] = {1, 2};
2810 EXPECT_THAT(array1, polymorphic_matcher);
2811 const int array2[] = {0, 0};
2812 EXPECT_THAT(array2, Not(polymorphic_matcher));
2813 }
2814
2815 // Tests for ElementsAreArray(). Since ElementsAreArray() shares most
2816 // of the implementation with ElementsAre(), we don't test it as
2817 // thoroughly here.
2818
TEST(ElementsAreArrayTest,CanBeCreatedWithValueArray)2819 TEST(ElementsAreArrayTest, CanBeCreatedWithValueArray) {
2820 const int a[] = {1, 2, 3};
2821
2822 vector<int> test_vector(std::begin(a), std::end(a));
2823 EXPECT_THAT(test_vector, ElementsAreArray(a));
2824
2825 test_vector[2] = 0;
2826 EXPECT_THAT(test_vector, Not(ElementsAreArray(a)));
2827 }
2828
TEST(ElementsAreArrayTest,CanBeCreatedWithArraySize)2829 TEST(ElementsAreArrayTest, CanBeCreatedWithArraySize) {
2830 std::array<const char*, 3> a = {{"one", "two", "three"}};
2831
2832 vector<std::string> test_vector(std::begin(a), std::end(a));
2833 EXPECT_THAT(test_vector, ElementsAreArray(a.data(), a.size()));
2834
2835 const char** p = a.data();
2836 test_vector[0] = "1";
2837 EXPECT_THAT(test_vector, Not(ElementsAreArray(p, a.size())));
2838 }
2839
TEST(ElementsAreArrayTest,CanBeCreatedWithoutArraySize)2840 TEST(ElementsAreArrayTest, CanBeCreatedWithoutArraySize) {
2841 const char* a[] = {"one", "two", "three"};
2842
2843 vector<std::string> test_vector(std::begin(a), std::end(a));
2844 EXPECT_THAT(test_vector, ElementsAreArray(a));
2845
2846 test_vector[0] = "1";
2847 EXPECT_THAT(test_vector, Not(ElementsAreArray(a)));
2848 }
2849
TEST(ElementsAreArrayTest,CanBeCreatedWithMatcherArray)2850 TEST(ElementsAreArrayTest, CanBeCreatedWithMatcherArray) {
2851 const Matcher<std::string> kMatcherArray[] = {StrEq("one"), StrEq("two"),
2852 StrEq("three")};
2853
2854 vector<std::string> test_vector;
2855 test_vector.push_back("one");
2856 test_vector.push_back("two");
2857 test_vector.push_back("three");
2858 EXPECT_THAT(test_vector, ElementsAreArray(kMatcherArray));
2859
2860 test_vector.push_back("three");
2861 EXPECT_THAT(test_vector, Not(ElementsAreArray(kMatcherArray)));
2862 }
2863
TEST(ElementsAreArrayTest,CanBeCreatedWithVector)2864 TEST(ElementsAreArrayTest, CanBeCreatedWithVector) {
2865 const int a[] = {1, 2, 3};
2866 vector<int> test_vector(std::begin(a), std::end(a));
2867 const vector<int> expected(std::begin(a), std::end(a));
2868 EXPECT_THAT(test_vector, ElementsAreArray(expected));
2869 test_vector.push_back(4);
2870 EXPECT_THAT(test_vector, Not(ElementsAreArray(expected)));
2871 }
2872
TEST(ElementsAreArrayTest,TakesInitializerList)2873 TEST(ElementsAreArrayTest, TakesInitializerList) {
2874 const int a[5] = {1, 2, 3, 4, 5};
2875 EXPECT_THAT(a, ElementsAreArray({1, 2, 3, 4, 5}));
2876 EXPECT_THAT(a, Not(ElementsAreArray({1, 2, 3, 5, 4})));
2877 EXPECT_THAT(a, Not(ElementsAreArray({1, 2, 3, 4, 6})));
2878 }
2879
TEST(ElementsAreArrayTest,TakesInitializerListOfCStrings)2880 TEST(ElementsAreArrayTest, TakesInitializerListOfCStrings) {
2881 const std::string a[5] = {"a", "b", "c", "d", "e"};
2882 EXPECT_THAT(a, ElementsAreArray({"a", "b", "c", "d", "e"}));
2883 EXPECT_THAT(a, Not(ElementsAreArray({"a", "b", "c", "e", "d"})));
2884 EXPECT_THAT(a, Not(ElementsAreArray({"a", "b", "c", "d", "ef"})));
2885 }
2886
TEST(ElementsAreArrayTest,TakesInitializerListOfSameTypedMatchers)2887 TEST(ElementsAreArrayTest, TakesInitializerListOfSameTypedMatchers) {
2888 const int a[5] = {1, 2, 3, 4, 5};
2889 EXPECT_THAT(a, ElementsAreArray({Eq(1), Eq(2), Eq(3), Eq(4), Eq(5)}));
2890 EXPECT_THAT(a, Not(ElementsAreArray({Eq(1), Eq(2), Eq(3), Eq(4), Eq(6)})));
2891 }
2892
TEST(ElementsAreArrayTest,TakesInitializerListOfDifferentTypedMatchers)2893 TEST(ElementsAreArrayTest, TakesInitializerListOfDifferentTypedMatchers) {
2894 const int a[5] = {1, 2, 3, 4, 5};
2895 // The compiler cannot infer the type of the initializer list if its
2896 // elements have different types. We must explicitly specify the
2897 // unified element type in this case.
2898 EXPECT_THAT(
2899 a, ElementsAreArray<Matcher<int>>({Eq(1), Ne(-2), Ge(3), Le(4), Eq(5)}));
2900 EXPECT_THAT(a, Not(ElementsAreArray<Matcher<int>>(
2901 {Eq(1), Ne(-2), Ge(3), Le(4), Eq(6)})));
2902 }
2903
TEST(ElementsAreArrayTest,CanBeCreatedWithMatcherVector)2904 TEST(ElementsAreArrayTest, CanBeCreatedWithMatcherVector) {
2905 const int a[] = {1, 2, 3};
2906 const Matcher<int> kMatchers[] = {Eq(1), Eq(2), Eq(3)};
2907 vector<int> test_vector(std::begin(a), std::end(a));
2908 const vector<Matcher<int>> expected(std::begin(kMatchers),
2909 std::end(kMatchers));
2910 EXPECT_THAT(test_vector, ElementsAreArray(expected));
2911 test_vector.push_back(4);
2912 EXPECT_THAT(test_vector, Not(ElementsAreArray(expected)));
2913 }
2914
TEST(ElementsAreArrayTest,CanBeCreatedWithIteratorRange)2915 TEST(ElementsAreArrayTest, CanBeCreatedWithIteratorRange) {
2916 const int a[] = {1, 2, 3};
2917 const vector<int> test_vector(std::begin(a), std::end(a));
2918 const vector<int> expected(std::begin(a), std::end(a));
2919 EXPECT_THAT(test_vector, ElementsAreArray(expected.begin(), expected.end()));
2920 // Pointers are iterators, too.
2921 EXPECT_THAT(test_vector, ElementsAreArray(std::begin(a), std::end(a)));
2922 // The empty range of NULL pointers should also be okay.
2923 int* const null_int = nullptr;
2924 EXPECT_THAT(test_vector, Not(ElementsAreArray(null_int, null_int)));
2925 EXPECT_THAT((vector<int>()), ElementsAreArray(null_int, null_int));
2926 }
2927
2928 // Since ElementsAre() and ElementsAreArray() share much of the
2929 // implementation, we only do a test for native arrays here.
TEST(ElementsAreArrayTest,WorksWithNativeArray)2930 TEST(ElementsAreArrayTest, WorksWithNativeArray) {
2931 ::std::string a[] = {"hi", "ho"};
2932 ::std::string b[] = {"hi", "ho"};
2933
2934 EXPECT_THAT(a, ElementsAreArray(b));
2935 EXPECT_THAT(a, ElementsAreArray(b, 2));
2936 EXPECT_THAT(a, Not(ElementsAreArray(b, 1)));
2937 }
2938
TEST(ElementsAreArrayTest,SourceLifeSpan)2939 TEST(ElementsAreArrayTest, SourceLifeSpan) {
2940 const int a[] = {1, 2, 3};
2941 vector<int> test_vector(std::begin(a), std::end(a));
2942 vector<int> expect(std::begin(a), std::end(a));
2943 ElementsAreArrayMatcher<int> matcher_maker =
2944 ElementsAreArray(expect.begin(), expect.end());
2945 EXPECT_THAT(test_vector, matcher_maker);
2946 // Changing in place the values that initialized matcher_maker should not
2947 // affect matcher_maker anymore. It should have made its own copy of them.
2948 for (int& i : expect) {
2949 i += 10;
2950 }
2951 EXPECT_THAT(test_vector, matcher_maker);
2952 test_vector.push_back(3);
2953 EXPECT_THAT(test_vector, Not(matcher_maker));
2954 }
2955
2956 // Tests Contains().
2957
TEST(ContainsTest,ListMatchesWhenElementIsInContainer)2958 TEST(ContainsTest, ListMatchesWhenElementIsInContainer) {
2959 list<int> some_list;
2960 some_list.push_back(3);
2961 some_list.push_back(1);
2962 some_list.push_back(2);
2963 some_list.push_back(3);
2964 EXPECT_THAT(some_list, Contains(1));
2965 EXPECT_THAT(some_list, Contains(Gt(2.5)));
2966 EXPECT_THAT(some_list, Contains(Eq(2.0f)));
2967
2968 list<std::string> another_list;
2969 another_list.push_back("fee");
2970 another_list.push_back("fie");
2971 another_list.push_back("foe");
2972 another_list.push_back("fum");
2973 EXPECT_THAT(another_list, Contains(std::string("fee")));
2974 }
2975
TEST(ContainsTest,ListDoesNotMatchWhenElementIsNotInContainer)2976 TEST(ContainsTest, ListDoesNotMatchWhenElementIsNotInContainer) {
2977 list<int> some_list;
2978 some_list.push_back(3);
2979 some_list.push_back(1);
2980 EXPECT_THAT(some_list, Not(Contains(4)));
2981 }
2982
TEST(ContainsTest,SetMatchesWhenElementIsInContainer)2983 TEST(ContainsTest, SetMatchesWhenElementIsInContainer) {
2984 set<int> some_set;
2985 some_set.insert(3);
2986 some_set.insert(1);
2987 some_set.insert(2);
2988 EXPECT_THAT(some_set, Contains(Eq(1.0)));
2989 EXPECT_THAT(some_set, Contains(Eq(3.0f)));
2990 EXPECT_THAT(some_set, Contains(2));
2991
2992 set<std::string> another_set;
2993 another_set.insert("fee");
2994 another_set.insert("fie");
2995 another_set.insert("foe");
2996 another_set.insert("fum");
2997 EXPECT_THAT(another_set, Contains(Eq(std::string("fum"))));
2998 }
2999
TEST(ContainsTest,SetDoesNotMatchWhenElementIsNotInContainer)3000 TEST(ContainsTest, SetDoesNotMatchWhenElementIsNotInContainer) {
3001 set<int> some_set;
3002 some_set.insert(3);
3003 some_set.insert(1);
3004 EXPECT_THAT(some_set, Not(Contains(4)));
3005
3006 set<std::string> c_string_set;
3007 c_string_set.insert("hello");
3008 EXPECT_THAT(c_string_set, Not(Contains(std::string("goodbye"))));
3009 }
3010
TEST(ContainsTest,ExplainsMatchResultCorrectly)3011 TEST(ContainsTest, ExplainsMatchResultCorrectly) {
3012 const int a[2] = {1, 2};
3013 Matcher<const int(&)[2]> m = Contains(2);
3014 EXPECT_EQ("whose element #1 matches", Explain(m, a));
3015
3016 m = Contains(3);
3017 EXPECT_EQ("", Explain(m, a));
3018
3019 m = Contains(GreaterThan(0));
3020 EXPECT_EQ("whose element #0 matches, which is 1 more than 0", Explain(m, a));
3021
3022 m = Contains(GreaterThan(10));
3023 EXPECT_EQ("", Explain(m, a));
3024 }
3025
TEST(ContainsTest,DescribesItselfCorrectly)3026 TEST(ContainsTest, DescribesItselfCorrectly) {
3027 Matcher<vector<int>> m = Contains(1);
3028 EXPECT_EQ("contains at least one element that is equal to 1", Describe(m));
3029
3030 Matcher<vector<int>> m2 = Not(m);
3031 EXPECT_EQ("doesn't contain any element that is equal to 1", Describe(m2));
3032 }
3033
TEST(ContainsTest,MapMatchesWhenElementIsInContainer)3034 TEST(ContainsTest, MapMatchesWhenElementIsInContainer) {
3035 map<std::string, int> my_map;
3036 const char* bar = "a string";
3037 my_map[bar] = 2;
3038 EXPECT_THAT(my_map, Contains(pair<const char* const, int>(bar, 2)));
3039
3040 map<std::string, int> another_map;
3041 another_map["fee"] = 1;
3042 another_map["fie"] = 2;
3043 another_map["foe"] = 3;
3044 another_map["fum"] = 4;
3045 EXPECT_THAT(another_map,
3046 Contains(pair<const std::string, int>(std::string("fee"), 1)));
3047 EXPECT_THAT(another_map, Contains(pair<const std::string, int>("fie", 2)));
3048 }
3049
TEST(ContainsTest,MapDoesNotMatchWhenElementIsNotInContainer)3050 TEST(ContainsTest, MapDoesNotMatchWhenElementIsNotInContainer) {
3051 map<int, int> some_map;
3052 some_map[1] = 11;
3053 some_map[2] = 22;
3054 EXPECT_THAT(some_map, Not(Contains(pair<const int, int>(2, 23))));
3055 }
3056
TEST(ContainsTest,ArrayMatchesWhenElementIsInContainer)3057 TEST(ContainsTest, ArrayMatchesWhenElementIsInContainer) {
3058 const char* string_array[] = {"fee", "fie", "foe", "fum"};
3059 EXPECT_THAT(string_array, Contains(Eq(std::string("fum"))));
3060 }
3061
TEST(ContainsTest,ArrayDoesNotMatchWhenElementIsNotInContainer)3062 TEST(ContainsTest, ArrayDoesNotMatchWhenElementIsNotInContainer) {
3063 int int_array[] = {1, 2, 3, 4};
3064 EXPECT_THAT(int_array, Not(Contains(5)));
3065 }
3066
TEST(ContainsTest,AcceptsMatcher)3067 TEST(ContainsTest, AcceptsMatcher) {
3068 const int a[] = {1, 2, 3};
3069 EXPECT_THAT(a, Contains(Gt(2)));
3070 EXPECT_THAT(a, Not(Contains(Gt(4))));
3071 }
3072
TEST(ContainsTest,WorksForNativeArrayAsTuple)3073 TEST(ContainsTest, WorksForNativeArrayAsTuple) {
3074 const int a[] = {1, 2};
3075 const int* const pointer = a;
3076 EXPECT_THAT(std::make_tuple(pointer, 2), Contains(1));
3077 EXPECT_THAT(std::make_tuple(pointer, 2), Not(Contains(Gt(3))));
3078 }
3079
TEST(ContainsTest,WorksForTwoDimensionalNativeArray)3080 TEST(ContainsTest, WorksForTwoDimensionalNativeArray) {
3081 int a[][3] = {{1, 2, 3}, {4, 5, 6}};
3082 EXPECT_THAT(a, Contains(ElementsAre(4, 5, 6)));
3083 EXPECT_THAT(a, Contains(Contains(5)));
3084 EXPECT_THAT(a, Not(Contains(ElementsAre(3, 4, 5))));
3085 EXPECT_THAT(a, Contains(Not(Contains(5))));
3086 }
3087
3088 } // namespace
3089 } // namespace gmock_matchers_test
3090 } // namespace testing
3091
3092 #ifdef _MSC_VER
3093 #pragma warning(pop)
3094 #endif
3095