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