1 // Copyright 2007, Google Inc.
2 // All rights reserved.
4 // Redistribution and use in source and binary forms, with or without
5 // modification, are permitted provided that the following conditions are
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
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.
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.
30 // Google Mock - a framework for writing C++ mock classes.
32 // This file tests some commonly used argument matchers.
37 #include <forward_list>
46 #include "gtest/gtest.h"
48 // Silence warning C4244: 'initializing': conversion from 'int' to 'short',
49 // possible loss of data and C4100, unreferenced local parameter
50 GTEST_DISABLE_MSC_WARNINGS_PUSH_(4244 4100)
52 #include "test/gmock-matchers_test.h"
55 namespace gmock_matchers_test {
58 std::vector<std::unique_ptr<int>> MakeUniquePtrs(const std::vector<int>& ints) {
59 std::vector<std::unique_ptr<int>> pointers;
60 for (int i : ints) pointers.emplace_back(new int(i));
64 std::string OfType(const std::string& type_name) {
66 return IsReadableTypeName(type_name) ? " (of type " + type_name + ")" : "";
72 TEST(ContainsTest, WorksWithMoveOnly) {
73 ContainerHelper helper;
74 EXPECT_CALL(helper, Call(Contains(Pointee(2))));
75 helper.Call(MakeUniquePtrs({1, 2}));
78 INSTANTIATE_GTEST_MATCHER_TEST_P(ElementsAreTest);
80 // Tests the variadic version of the ElementsAreMatcher
81 TEST(ElementsAreTest, HugeMatcher) {
82 vector<int> test_vector{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12};
84 EXPECT_THAT(test_vector,
85 ElementsAre(Eq(1), Eq(2), Lt(13), Eq(4), Eq(5), Eq(6), Eq(7),
86 Eq(8), Eq(9), Eq(10), Gt(1), Eq(12)));
89 // Tests the variadic version of the UnorderedElementsAreMatcher
90 TEST(ElementsAreTest, HugeMatcherStr) {
91 vector<std::string> test_vector{
92 "literal_string", "", "", "", "", "", "", "", "", "", "", ""};
94 EXPECT_THAT(test_vector, UnorderedElementsAre("literal_string", _, _, _, _, _,
98 // Tests the variadic version of the UnorderedElementsAreMatcher
99 TEST(ElementsAreTest, HugeMatcherUnordered) {
100 vector<int> test_vector{2, 1, 8, 5, 4, 6, 7, 3, 9, 12, 11, 10};
102 EXPECT_THAT(test_vector, UnorderedElementsAre(
103 Eq(2), Eq(1), Gt(7), Eq(5), Eq(4), Eq(6), Eq(7),
104 Eq(3), Eq(9), Eq(12), Eq(11), Ne(122)));
107 // Tests that ASSERT_THAT() and EXPECT_THAT() work when the value
108 // matches the matcher.
109 TEST(MatcherAssertionTest, WorksWhenMatcherIsSatisfied) {
110 ASSERT_THAT(5, Ge(2)) << "This should succeed.";
111 ASSERT_THAT("Foo", EndsWith("oo"));
112 EXPECT_THAT(2, AllOf(Le(7), Ge(0))) << "This should succeed too.";
113 EXPECT_THAT("Hello", StartsWith("Hell"));
116 // Tests that ASSERT_THAT() and EXPECT_THAT() work when the value
117 // doesn't match the matcher.
118 TEST(MatcherAssertionTest, WorksWhenMatcherIsNotSatisfied) {
119 // 'n' must be static as it is used in an EXPECT_FATAL_FAILURE(),
120 // which cannot reference auto variables.
121 static unsigned short n; // NOLINT
124 EXPECT_FATAL_FAILURE(ASSERT_THAT(n, Gt(10)),
126 "Expected: is > 10\n"
128 OfType("unsigned short"));
130 EXPECT_NONFATAL_FAILURE(EXPECT_THAT(n, AllOf(Le(7), Ge(5))),
132 "Expected: (is <= 7) and (is >= 5)\n"
134 OfType("unsigned short"));
137 // Tests that ASSERT_THAT() and EXPECT_THAT() work when the argument
138 // has a reference type.
139 TEST(MatcherAssertionTest, WorksForByRefArguments) {
140 // We use a static variable here as EXPECT_FATAL_FAILURE() cannot
141 // reference auto variables.
144 EXPECT_THAT(n, AllOf(Le(7), Ref(n)));
145 EXPECT_FATAL_FAILURE(ASSERT_THAT(n, Not(Ref(n))),
147 "Expected: does not reference the variable @");
148 // Tests the "Actual" part.
149 EXPECT_FATAL_FAILURE(ASSERT_THAT(n, Not(Ref(n))),
150 "Actual: 0" + OfType("int") + ", which is located @");
153 // Tests that ASSERT_THAT() and EXPECT_THAT() work when the matcher is
155 TEST(MatcherAssertionTest, WorksForMonomorphicMatcher) {
156 Matcher<const char*> starts_with_he = StartsWith("he");
157 ASSERT_THAT("hello", starts_with_he);
159 Matcher<const std::string&> ends_with_ok = EndsWith("ok");
160 ASSERT_THAT("book", ends_with_ok);
161 const std::string bad = "bad";
162 EXPECT_NONFATAL_FAILURE(EXPECT_THAT(bad, ends_with_ok),
164 "Expected: ends with \"ok\"\n"
166 Matcher<int> is_greater_than_5 = Gt(5);
167 EXPECT_NONFATAL_FAILURE(EXPECT_THAT(5, is_greater_than_5),
174 TEST(PointeeTest, RawPointer) {
175 const Matcher<int*> m = Pointee(Ge(0));
178 EXPECT_TRUE(m.Matches(&n));
180 EXPECT_FALSE(m.Matches(&n));
181 EXPECT_FALSE(m.Matches(nullptr));
184 TEST(PointeeTest, RawPointerToConst) {
185 const Matcher<const double*> m = Pointee(Ge(0));
188 EXPECT_TRUE(m.Matches(&x));
190 EXPECT_FALSE(m.Matches(&x));
191 EXPECT_FALSE(m.Matches(nullptr));
194 TEST(PointeeTest, ReferenceToConstRawPointer) {
195 const Matcher<int* const&> m = Pointee(Ge(0));
198 EXPECT_TRUE(m.Matches(&n));
200 EXPECT_FALSE(m.Matches(&n));
201 EXPECT_FALSE(m.Matches(nullptr));
204 TEST(PointeeTest, ReferenceToNonConstRawPointer) {
205 const Matcher<double*&> m = Pointee(Ge(0));
209 EXPECT_TRUE(m.Matches(p));
211 EXPECT_FALSE(m.Matches(p));
213 EXPECT_FALSE(m.Matches(p));
216 TEST(PointeeTest, SmartPointer) {
217 const Matcher<std::unique_ptr<int>> m = Pointee(Ge(0));
219 std::unique_ptr<int> n(new int(1));
220 EXPECT_TRUE(m.Matches(n));
223 TEST(PointeeTest, SmartPointerToConst) {
224 const Matcher<std::unique_ptr<const int>> m = Pointee(Ge(0));
226 // There's no implicit conversion from unique_ptr<int> to const
227 // unique_ptr<const int>, so we must pass a unique_ptr<const int> into the
229 std::unique_ptr<const int> n(new int(1));
230 EXPECT_TRUE(m.Matches(n));
233 TEST(PointerTest, RawPointer) {
235 const Matcher<int*> m = Pointer(Eq(&n));
237 EXPECT_TRUE(m.Matches(&n));
240 EXPECT_FALSE(m.Matches(p));
241 EXPECT_FALSE(m.Matches(nullptr));
244 TEST(PointerTest, RawPointerToConst) {
246 const Matcher<const int*> m = Pointer(Eq(&n));
248 EXPECT_TRUE(m.Matches(&n));
251 EXPECT_FALSE(m.Matches(p));
252 EXPECT_FALSE(m.Matches(nullptr));
255 TEST(PointerTest, SmartPointer) {
256 std::unique_ptr<int> n(new int(10));
257 int* raw_n = n.get();
258 const Matcher<std::unique_ptr<int>> m = Pointer(Eq(raw_n));
260 EXPECT_TRUE(m.Matches(n));
263 TEST(PointerTest, SmartPointerToConst) {
264 std::unique_ptr<const int> n(new int(10));
265 const int* raw_n = n.get();
266 const Matcher<std::unique_ptr<const int>> m = Pointer(Eq(raw_n));
268 // There's no implicit conversion from unique_ptr<int> to const
269 // unique_ptr<const int>, so we must pass a unique_ptr<const int> into the
271 std::unique_ptr<const int> p(new int(10));
272 EXPECT_FALSE(m.Matches(p));
275 // Minimal const-propagating pointer.
276 template <typename T>
277 class ConstPropagatingPtr {
279 typedef T element_type;
281 ConstPropagatingPtr() : val_() {}
282 explicit ConstPropagatingPtr(T* t) : val_(t) {}
283 ConstPropagatingPtr(const ConstPropagatingPtr& other) : val_(other.val_) {}
285 T* get() { return val_; }
286 T& operator*() { return *val_; }
287 // Most smart pointers return non-const T* and T& from the next methods.
288 const T* get() const { return val_; }
289 const T& operator*() const { return *val_; }
295 INSTANTIATE_GTEST_MATCHER_TEST_P(PointeeTest);
297 TEST(PointeeTest, WorksWithConstPropagatingPointers) {
298 const Matcher<ConstPropagatingPtr<int>> m = Pointee(Lt(5));
300 const ConstPropagatingPtr<int> co(&three);
301 ConstPropagatingPtr<int> o(&three);
302 EXPECT_TRUE(m.Matches(o));
303 EXPECT_TRUE(m.Matches(co));
305 EXPECT_FALSE(m.Matches(o));
306 EXPECT_FALSE(m.Matches(ConstPropagatingPtr<int>()));
309 TEST(PointeeTest, NeverMatchesNull) {
310 const Matcher<const char*> m = Pointee(_);
311 EXPECT_FALSE(m.Matches(nullptr));
314 // Tests that we can write Pointee(value) instead of Pointee(Eq(value)).
315 TEST(PointeeTest, MatchesAgainstAValue) {
316 const Matcher<int*> m = Pointee(5);
319 EXPECT_TRUE(m.Matches(&n));
321 EXPECT_FALSE(m.Matches(&n));
322 EXPECT_FALSE(m.Matches(nullptr));
325 TEST(PointeeTest, CanDescribeSelf) {
326 const Matcher<int*> m = Pointee(Gt(3));
327 EXPECT_EQ("points to a value that is > 3", Describe(m));
328 EXPECT_EQ("does not point to a value that is > 3", DescribeNegation(m));
331 TEST_P(PointeeTestP, CanExplainMatchResult) {
332 const Matcher<const std::string*> m = Pointee(StartsWith("Hi"));
334 EXPECT_EQ("", Explain(m, static_cast<const std::string*>(nullptr)));
336 const Matcher<long*> m2 = Pointee(GreaterThan(1)); // NOLINT
337 long n = 3; // NOLINT
338 EXPECT_EQ("which points to 3" + OfType("long") + ", which is 2 more than 1",
342 TEST(PointeeTest, AlwaysExplainsPointee) {
343 const Matcher<int*> m = Pointee(0);
345 EXPECT_EQ("which points to 42" + OfType("int"), Explain(m, &n));
348 // An uncopyable class.
351 Uncopyable() : value_(-1) {}
352 explicit Uncopyable(int a_value) : value_(a_value) {}
354 int value() const { return value_; }
355 void set_value(int i) { value_ = i; }
359 Uncopyable(const Uncopyable&) = delete;
360 Uncopyable& operator=(const Uncopyable&) = delete;
363 // Returns true if and only if x.value() is positive.
364 bool ValueIsPositive(const Uncopyable& x) { return x.value() > 0; }
366 MATCHER_P(UncopyableIs, inner_matcher, "") {
367 return ExplainMatchResult(inner_matcher, arg.value(), result_listener);
370 // A user-defined struct for testing Field().
372 AStruct() : x(0), y(1.0), z(5), p(nullptr) {}
373 AStruct(const AStruct& rhs)
374 : x(rhs.x), y(rhs.y), z(rhs.z.value()), p(rhs.p) {}
376 int x; // A non-const field.
377 const double y; // A const field.
378 Uncopyable z; // An uncopyable field.
379 const char* p; // A pointer field.
382 // A derived struct for testing Field().
383 struct DerivedStruct : public AStruct {
387 INSTANTIATE_GTEST_MATCHER_TEST_P(FieldTest);
389 // Tests that Field(&Foo::field, ...) works when field is non-const.
390 TEST(FieldTest, WorksForNonConstField) {
391 Matcher<AStruct> m = Field(&AStruct::x, Ge(0));
392 Matcher<AStruct> m_with_name = Field("x", &AStruct::x, Ge(0));
395 EXPECT_TRUE(m.Matches(a));
396 EXPECT_TRUE(m_with_name.Matches(a));
398 EXPECT_FALSE(m.Matches(a));
399 EXPECT_FALSE(m_with_name.Matches(a));
402 // Tests that Field(&Foo::field, ...) works when field is const.
403 TEST(FieldTest, WorksForConstField) {
406 Matcher<AStruct> m = Field(&AStruct::y, Ge(0.0));
407 Matcher<AStruct> m_with_name = Field("y", &AStruct::y, Ge(0.0));
408 EXPECT_TRUE(m.Matches(a));
409 EXPECT_TRUE(m_with_name.Matches(a));
410 m = Field(&AStruct::y, Le(0.0));
411 m_with_name = Field("y", &AStruct::y, Le(0.0));
412 EXPECT_FALSE(m.Matches(a));
413 EXPECT_FALSE(m_with_name.Matches(a));
416 // Tests that Field(&Foo::field, ...) works when field is not copyable.
417 TEST(FieldTest, WorksForUncopyableField) {
420 Matcher<AStruct> m = Field(&AStruct::z, Truly(ValueIsPositive));
421 EXPECT_TRUE(m.Matches(a));
422 m = Field(&AStruct::z, Not(Truly(ValueIsPositive)));
423 EXPECT_FALSE(m.Matches(a));
426 // Tests that Field(&Foo::field, ...) works when field is a pointer.
427 TEST(FieldTest, WorksForPointerField) {
428 // Matching against NULL.
429 Matcher<AStruct> m = Field(&AStruct::p, static_cast<const char*>(nullptr));
431 EXPECT_TRUE(m.Matches(a));
433 EXPECT_FALSE(m.Matches(a));
435 // Matching a pointer that is not NULL.
436 m = Field(&AStruct::p, StartsWith("hi"));
438 EXPECT_TRUE(m.Matches(a));
440 EXPECT_FALSE(m.Matches(a));
443 // Tests that Field() works when the object is passed by reference.
444 TEST(FieldTest, WorksForByRefArgument) {
445 Matcher<const AStruct&> m = Field(&AStruct::x, Ge(0));
448 EXPECT_TRUE(m.Matches(a));
450 EXPECT_FALSE(m.Matches(a));
453 // Tests that Field(&Foo::field, ...) works when the argument's type
454 // is a sub-type of Foo.
455 TEST(FieldTest, WorksForArgumentOfSubType) {
456 // Note that the matcher expects DerivedStruct but we say AStruct
458 Matcher<const DerivedStruct&> m = Field(&AStruct::x, Ge(0));
461 EXPECT_TRUE(m.Matches(d));
463 EXPECT_FALSE(m.Matches(d));
466 // Tests that Field(&Foo::field, m) works when field's type and m's
467 // argument type are compatible but not the same.
468 TEST(FieldTest, WorksForCompatibleMatcherType) {
469 // The field is an int, but the inner matcher expects a signed char.
470 Matcher<const AStruct&> m = Field(&AStruct::x, Matcher<signed char>(Ge(0)));
473 EXPECT_TRUE(m.Matches(a));
475 EXPECT_FALSE(m.Matches(a));
478 // Tests that Field() can describe itself.
479 TEST(FieldTest, CanDescribeSelf) {
480 Matcher<const AStruct&> m = Field(&AStruct::x, Ge(0));
482 EXPECT_EQ("is an object whose given field is >= 0", Describe(m));
483 EXPECT_EQ("is an object whose given field isn't >= 0", DescribeNegation(m));
486 TEST(FieldTest, CanDescribeSelfWithFieldName) {
487 Matcher<const AStruct&> m = Field("field_name", &AStruct::x, Ge(0));
489 EXPECT_EQ("is an object whose field `field_name` is >= 0", Describe(m));
490 EXPECT_EQ("is an object whose field `field_name` isn't >= 0",
491 DescribeNegation(m));
494 // Tests that Field() can explain the match result.
495 TEST_P(FieldTestP, CanExplainMatchResult) {
496 Matcher<const AStruct&> m = Field(&AStruct::x, Ge(0));
500 EXPECT_EQ("whose given field is 1" + OfType("int"), Explain(m, a));
502 m = Field(&AStruct::x, GreaterThan(0));
504 "whose given field is 1" + OfType("int") + ", which is 1 more than 0",
508 TEST_P(FieldTestP, CanExplainMatchResultWithFieldName) {
509 Matcher<const AStruct&> m = Field("field_name", &AStruct::x, Ge(0));
513 EXPECT_EQ("whose field `field_name` is 1" + OfType("int"), Explain(m, a));
515 m = Field("field_name", &AStruct::x, GreaterThan(0));
516 EXPECT_EQ("whose field `field_name` is 1" + OfType("int") +
517 ", which is 1 more than 0",
521 INSTANTIATE_GTEST_MATCHER_TEST_P(FieldForPointerTest);
523 // Tests that Field() works when the argument is a pointer to const.
524 TEST(FieldForPointerTest, WorksForPointerToConst) {
525 Matcher<const AStruct*> m = Field(&AStruct::x, Ge(0));
528 EXPECT_TRUE(m.Matches(&a));
530 EXPECT_FALSE(m.Matches(&a));
533 // Tests that Field() works when the argument is a pointer to non-const.
534 TEST(FieldForPointerTest, WorksForPointerToNonConst) {
535 Matcher<AStruct*> m = Field(&AStruct::x, Ge(0));
538 EXPECT_TRUE(m.Matches(&a));
540 EXPECT_FALSE(m.Matches(&a));
543 // Tests that Field() works when the argument is a reference to a const pointer.
544 TEST(FieldForPointerTest, WorksForReferenceToConstPointer) {
545 Matcher<AStruct* const&> m = Field(&AStruct::x, Ge(0));
548 EXPECT_TRUE(m.Matches(&a));
550 EXPECT_FALSE(m.Matches(&a));
553 // Tests that Field() does not match the NULL pointer.
554 TEST(FieldForPointerTest, DoesNotMatchNull) {
555 Matcher<const AStruct*> m = Field(&AStruct::x, _);
556 EXPECT_FALSE(m.Matches(nullptr));
559 // Tests that Field(&Foo::field, ...) works when the argument's type
560 // is a sub-type of const Foo*.
561 TEST(FieldForPointerTest, WorksForArgumentOfSubType) {
562 // Note that the matcher expects DerivedStruct but we say AStruct
564 Matcher<DerivedStruct*> m = Field(&AStruct::x, Ge(0));
567 EXPECT_TRUE(m.Matches(&d));
569 EXPECT_FALSE(m.Matches(&d));
572 // Tests that Field() can describe itself when used to match a pointer.
573 TEST(FieldForPointerTest, CanDescribeSelf) {
574 Matcher<const AStruct*> m = Field(&AStruct::x, Ge(0));
576 EXPECT_EQ("is an object whose given field is >= 0", Describe(m));
577 EXPECT_EQ("is an object whose given field isn't >= 0", DescribeNegation(m));
580 TEST(FieldForPointerTest, CanDescribeSelfWithFieldName) {
581 Matcher<const AStruct*> m = Field("field_name", &AStruct::x, Ge(0));
583 EXPECT_EQ("is an object whose field `field_name` is >= 0", Describe(m));
584 EXPECT_EQ("is an object whose field `field_name` isn't >= 0",
585 DescribeNegation(m));
588 // Tests that Field() can explain the result of matching a pointer.
589 TEST_P(FieldForPointerTestP, CanExplainMatchResult) {
590 Matcher<const AStruct*> m = Field(&AStruct::x, Ge(0));
594 EXPECT_EQ("", Explain(m, static_cast<const AStruct*>(nullptr)));
595 EXPECT_EQ("which points to an object whose given field is 1" + OfType("int"),
598 m = Field(&AStruct::x, GreaterThan(0));
599 EXPECT_EQ("which points to an object whose given field is 1" + OfType("int") +
600 ", which is 1 more than 0",
604 TEST_P(FieldForPointerTestP, CanExplainMatchResultWithFieldName) {
605 Matcher<const AStruct*> m = Field("field_name", &AStruct::x, Ge(0));
609 EXPECT_EQ("", Explain(m, static_cast<const AStruct*>(nullptr)));
611 "which points to an object whose field `field_name` is 1" + OfType("int"),
614 m = Field("field_name", &AStruct::x, GreaterThan(0));
615 EXPECT_EQ("which points to an object whose field `field_name` is 1" +
616 OfType("int") + ", which is 1 more than 0",
620 // A user-defined class for testing Property().
625 // A getter that returns a non-reference.
626 int n() const { return n_; }
628 void set_n(int new_n) { n_ = new_n; }
630 // A getter that returns a reference to const.
631 const std::string& s() const { return s_; }
633 const std::string& s_ref() const& { return s_; }
635 void set_s(const std::string& new_s) { s_ = new_s; }
637 // A getter that returns a reference to non-const.
638 double& x() const { return x_; }
647 double AClass::x_ = 0.0;
649 // A derived class for testing Property().
650 class DerivedClass : public AClass {
652 int k() const { return k_; }
658 INSTANTIATE_GTEST_MATCHER_TEST_P(PropertyTest);
660 // Tests that Property(&Foo::property, ...) works when property()
661 // returns a non-reference.
662 TEST(PropertyTest, WorksForNonReferenceProperty) {
663 Matcher<const AClass&> m = Property(&AClass::n, Ge(0));
664 Matcher<const AClass&> m_with_name = Property("n", &AClass::n, Ge(0));
668 EXPECT_TRUE(m.Matches(a));
669 EXPECT_TRUE(m_with_name.Matches(a));
672 EXPECT_FALSE(m.Matches(a));
673 EXPECT_FALSE(m_with_name.Matches(a));
676 // Tests that Property(&Foo::property, ...) works when property()
677 // returns a reference to const.
678 TEST(PropertyTest, WorksForReferenceToConstProperty) {
679 Matcher<const AClass&> m = Property(&AClass::s, StartsWith("hi"));
680 Matcher<const AClass&> m_with_name =
681 Property("s", &AClass::s, StartsWith("hi"));
685 EXPECT_TRUE(m.Matches(a));
686 EXPECT_TRUE(m_with_name.Matches(a));
689 EXPECT_FALSE(m.Matches(a));
690 EXPECT_FALSE(m_with_name.Matches(a));
693 // Tests that Property(&Foo::property, ...) works when property() is
695 TEST(PropertyTest, WorksForRefQualifiedProperty) {
696 Matcher<const AClass&> m = Property(&AClass::s_ref, StartsWith("hi"));
697 Matcher<const AClass&> m_with_name =
698 Property("s", &AClass::s_ref, StartsWith("hi"));
702 EXPECT_TRUE(m.Matches(a));
703 EXPECT_TRUE(m_with_name.Matches(a));
706 EXPECT_FALSE(m.Matches(a));
707 EXPECT_FALSE(m_with_name.Matches(a));
710 // Tests that Property(&Foo::property, ...) works when property()
711 // returns a reference to non-const.
712 TEST(PropertyTest, WorksForReferenceToNonConstProperty) {
716 Matcher<const AClass&> m = Property(&AClass::x, Ref(x));
717 EXPECT_FALSE(m.Matches(a));
719 m = Property(&AClass::x, Not(Ref(x)));
720 EXPECT_TRUE(m.Matches(a));
723 // Tests that Property(&Foo::property, ...) works when the argument is
725 TEST(PropertyTest, WorksForByValueArgument) {
726 Matcher<AClass> m = Property(&AClass::s, StartsWith("hi"));
730 EXPECT_TRUE(m.Matches(a));
733 EXPECT_FALSE(m.Matches(a));
736 // Tests that Property(&Foo::property, ...) works when the argument's
737 // type is a sub-type of Foo.
738 TEST(PropertyTest, WorksForArgumentOfSubType) {
739 // The matcher expects a DerivedClass, but inside the Property() we
741 Matcher<const DerivedClass&> m = Property(&AClass::n, Ge(0));
745 EXPECT_TRUE(m.Matches(d));
748 EXPECT_FALSE(m.Matches(d));
751 // Tests that Property(&Foo::property, m) works when property()'s type
752 // and m's argument type are compatible but different.
753 TEST(PropertyTest, WorksForCompatibleMatcherType) {
754 // n() returns an int but the inner matcher expects a signed char.
755 Matcher<const AClass&> m = Property(&AClass::n, Matcher<signed char>(Ge(0)));
757 Matcher<const AClass&> m_with_name =
758 Property("n", &AClass::n, Matcher<signed char>(Ge(0)));
761 EXPECT_TRUE(m.Matches(a));
762 EXPECT_TRUE(m_with_name.Matches(a));
764 EXPECT_FALSE(m.Matches(a));
765 EXPECT_FALSE(m_with_name.Matches(a));
768 // Tests that Property() can describe itself.
769 TEST(PropertyTest, CanDescribeSelf) {
770 Matcher<const AClass&> m = Property(&AClass::n, Ge(0));
772 EXPECT_EQ("is an object whose given property is >= 0", Describe(m));
773 EXPECT_EQ("is an object whose given property isn't >= 0",
774 DescribeNegation(m));
777 TEST(PropertyTest, CanDescribeSelfWithPropertyName) {
778 Matcher<const AClass&> m = Property("fancy_name", &AClass::n, Ge(0));
780 EXPECT_EQ("is an object whose property `fancy_name` is >= 0", Describe(m));
781 EXPECT_EQ("is an object whose property `fancy_name` isn't >= 0",
782 DescribeNegation(m));
785 // Tests that Property() can explain the match result.
786 TEST_P(PropertyTestP, CanExplainMatchResult) {
787 Matcher<const AClass&> m = Property(&AClass::n, Ge(0));
791 EXPECT_EQ("whose given property is 1" + OfType("int"), Explain(m, a));
793 m = Property(&AClass::n, GreaterThan(0));
795 "whose given property is 1" + OfType("int") + ", which is 1 more than 0",
799 TEST_P(PropertyTestP, CanExplainMatchResultWithPropertyName) {
800 Matcher<const AClass&> m = Property("fancy_name", &AClass::n, Ge(0));
804 EXPECT_EQ("whose property `fancy_name` is 1" + OfType("int"), Explain(m, a));
806 m = Property("fancy_name", &AClass::n, GreaterThan(0));
807 EXPECT_EQ("whose property `fancy_name` is 1" + OfType("int") +
808 ", which is 1 more than 0",
812 INSTANTIATE_GTEST_MATCHER_TEST_P(PropertyForPointerTest);
814 // Tests that Property() works when the argument is a pointer to const.
815 TEST(PropertyForPointerTest, WorksForPointerToConst) {
816 Matcher<const AClass*> m = Property(&AClass::n, Ge(0));
820 EXPECT_TRUE(m.Matches(&a));
823 EXPECT_FALSE(m.Matches(&a));
826 // Tests that Property() works when the argument is a pointer to non-const.
827 TEST(PropertyForPointerTest, WorksForPointerToNonConst) {
828 Matcher<AClass*> m = Property(&AClass::s, StartsWith("hi"));
832 EXPECT_TRUE(m.Matches(&a));
835 EXPECT_FALSE(m.Matches(&a));
838 // Tests that Property() works when the argument is a reference to a
840 TEST(PropertyForPointerTest, WorksForReferenceToConstPointer) {
841 Matcher<AClass* const&> m = Property(&AClass::s, StartsWith("hi"));
845 EXPECT_TRUE(m.Matches(&a));
848 EXPECT_FALSE(m.Matches(&a));
851 // Tests that Property() does not match the NULL pointer.
852 TEST(PropertyForPointerTest, WorksForReferenceToNonConstProperty) {
853 Matcher<const AClass*> m = Property(&AClass::x, _);
854 EXPECT_FALSE(m.Matches(nullptr));
857 // Tests that Property(&Foo::property, ...) works when the argument's
858 // type is a sub-type of const Foo*.
859 TEST(PropertyForPointerTest, WorksForArgumentOfSubType) {
860 // The matcher expects a DerivedClass, but inside the Property() we
862 Matcher<const DerivedClass*> m = Property(&AClass::n, Ge(0));
866 EXPECT_TRUE(m.Matches(&d));
869 EXPECT_FALSE(m.Matches(&d));
872 // Tests that Property() can describe itself when used to match a pointer.
873 TEST(PropertyForPointerTest, CanDescribeSelf) {
874 Matcher<const AClass*> m = Property(&AClass::n, Ge(0));
876 EXPECT_EQ("is an object whose given property is >= 0", Describe(m));
877 EXPECT_EQ("is an object whose given property isn't >= 0",
878 DescribeNegation(m));
881 TEST(PropertyForPointerTest, CanDescribeSelfWithPropertyDescription) {
882 Matcher<const AClass*> m = Property("fancy_name", &AClass::n, Ge(0));
884 EXPECT_EQ("is an object whose property `fancy_name` is >= 0", Describe(m));
885 EXPECT_EQ("is an object whose property `fancy_name` isn't >= 0",
886 DescribeNegation(m));
889 // Tests that Property() can explain the result of matching a pointer.
890 TEST_P(PropertyForPointerTestP, CanExplainMatchResult) {
891 Matcher<const AClass*> m = Property(&AClass::n, Ge(0));
895 EXPECT_EQ("", Explain(m, static_cast<const AClass*>(nullptr)));
897 "which points to an object whose given property is 1" + OfType("int"),
900 m = Property(&AClass::n, GreaterThan(0));
901 EXPECT_EQ("which points to an object whose given property is 1" +
902 OfType("int") + ", which is 1 more than 0",
906 TEST_P(PropertyForPointerTestP, CanExplainMatchResultWithPropertyName) {
907 Matcher<const AClass*> m = Property("fancy_name", &AClass::n, Ge(0));
911 EXPECT_EQ("", Explain(m, static_cast<const AClass*>(nullptr)));
912 EXPECT_EQ("which points to an object whose property `fancy_name` is 1" +
916 m = Property("fancy_name", &AClass::n, GreaterThan(0));
917 EXPECT_EQ("which points to an object whose property `fancy_name` is 1" +
918 OfType("int") + ", which is 1 more than 0",
924 // Tests that ResultOf(f, ...) compiles and works as expected when f is a
926 std::string IntToStringFunction(int input) {
927 return input == 1 ? "foo" : "bar";
930 INSTANTIATE_GTEST_MATCHER_TEST_P(ResultOfTest);
932 TEST(ResultOfTest, WorksForFunctionPointers) {
933 Matcher<int> matcher = ResultOf(&IntToStringFunction, Eq(std::string("foo")));
935 EXPECT_TRUE(matcher.Matches(1));
936 EXPECT_FALSE(matcher.Matches(2));
939 // Tests that ResultOf() can describe itself.
940 TEST(ResultOfTest, CanDescribeItself) {
941 Matcher<int> matcher = ResultOf(&IntToStringFunction, StrEq("foo"));
944 "is mapped by the given callable to a value that "
945 "is equal to \"foo\"",
948 "is mapped by the given callable to a value that "
949 "isn't equal to \"foo\"",
950 DescribeNegation(matcher));
953 // Tests that ResultOf() can describe itself when provided a result description.
954 TEST(ResultOfTest, CanDescribeItselfWithResultDescription) {
955 Matcher<int> matcher =
956 ResultOf("string conversion", &IntToStringFunction, StrEq("foo"));
958 EXPECT_EQ("whose string conversion is equal to \"foo\"", Describe(matcher));
959 EXPECT_EQ("whose string conversion isn't equal to \"foo\"",
960 DescribeNegation(matcher));
963 // Tests that ResultOf() can explain the match result.
964 int IntFunction(int input) { return input == 42 ? 80 : 90; }
966 TEST_P(ResultOfTestP, CanExplainMatchResult) {
967 Matcher<int> matcher = ResultOf(&IntFunction, Ge(85));
968 EXPECT_EQ("which is mapped by the given callable to 90" + OfType("int"),
969 Explain(matcher, 36));
971 matcher = ResultOf(&IntFunction, GreaterThan(85));
972 EXPECT_EQ("which is mapped by the given callable to 90" + OfType("int") +
973 ", which is 5 more than 85",
974 Explain(matcher, 36));
977 TEST_P(ResultOfTestP, CanExplainMatchResultWithResultDescription) {
978 Matcher<int> matcher = ResultOf("magic int conversion", &IntFunction, Ge(85));
979 EXPECT_EQ("whose magic int conversion is 90" + OfType("int"),
980 Explain(matcher, 36));
982 matcher = ResultOf("magic int conversion", &IntFunction, GreaterThan(85));
983 EXPECT_EQ("whose magic int conversion is 90" + OfType("int") +
984 ", which is 5 more than 85",
985 Explain(matcher, 36));
988 // Tests that ResultOf(f, ...) compiles and works as expected when f(x)
989 // returns a non-reference.
990 TEST(ResultOfTest, WorksForNonReferenceResults) {
991 Matcher<int> matcher = ResultOf(&IntFunction, Eq(80));
993 EXPECT_TRUE(matcher.Matches(42));
994 EXPECT_FALSE(matcher.Matches(36));
997 // Tests that ResultOf(f, ...) compiles and works as expected when f(x)
998 // returns a reference to non-const.
999 double& DoubleFunction(double& input) { return input; } // NOLINT
1001 Uncopyable& RefUncopyableFunction(Uncopyable& obj) { // NOLINT
1005 TEST(ResultOfTest, WorksForReferenceToNonConstResults) {
1008 Matcher<double&> matcher = ResultOf(&DoubleFunction, Ref(x));
1010 EXPECT_TRUE(matcher.Matches(x));
1011 EXPECT_FALSE(matcher.Matches(x2));
1013 // Test that ResultOf works with uncopyable objects
1016 Matcher<Uncopyable&> matcher2 = ResultOf(&RefUncopyableFunction, Ref(obj));
1018 EXPECT_TRUE(matcher2.Matches(obj));
1019 EXPECT_FALSE(matcher2.Matches(obj2));
1022 // Tests that ResultOf(f, ...) compiles and works as expected when f(x)
1023 // returns a reference to const.
1024 const std::string& StringFunction(const std::string& input) { return input; }
1026 TEST(ResultOfTest, WorksForReferenceToConstResults) {
1027 std::string s = "foo";
1029 Matcher<const std::string&> matcher = ResultOf(&StringFunction, Ref(s));
1031 EXPECT_TRUE(matcher.Matches(s));
1032 EXPECT_FALSE(matcher.Matches(s2));
1035 // Tests that ResultOf(f, m) works when f(x) and m's
1036 // argument types are compatible but different.
1037 TEST(ResultOfTest, WorksForCompatibleMatcherTypes) {
1038 // IntFunction() returns int but the inner matcher expects a signed char.
1039 Matcher<int> matcher = ResultOf(IntFunction, Matcher<signed char>(Ge(85)));
1041 EXPECT_TRUE(matcher.Matches(36));
1042 EXPECT_FALSE(matcher.Matches(42));
1045 // Tests that the program aborts when ResultOf is passed
1046 // a NULL function pointer.
1047 TEST(ResultOfDeathTest, DiesOnNullFunctionPointers) {
1048 EXPECT_DEATH_IF_SUPPORTED(
1049 ResultOf(static_cast<std::string (*)(int dummy)>(nullptr),
1050 Eq(std::string("foo"))),
1051 "NULL function pointer is passed into ResultOf\\(\\)\\.");
1054 // Tests that ResultOf(f, ...) compiles and works as expected when f is a
1055 // function reference.
1056 TEST(ResultOfTest, WorksForFunctionReferences) {
1057 Matcher<int> matcher = ResultOf(IntToStringFunction, StrEq("foo"));
1058 EXPECT_TRUE(matcher.Matches(1));
1059 EXPECT_FALSE(matcher.Matches(2));
1062 // Tests that ResultOf(f, ...) compiles and works as expected when f is a
1065 std::string operator()(int input) const { return IntToStringFunction(input); }
1068 TEST(ResultOfTest, WorksForFunctors) {
1069 Matcher<int> matcher = ResultOf(Functor(), Eq(std::string("foo")));
1071 EXPECT_TRUE(matcher.Matches(1));
1072 EXPECT_FALSE(matcher.Matches(2));
1075 // Tests that ResultOf(f, ...) compiles and works as expected when f is a
1076 // functor with more than one operator() defined. ResultOf() must work
1077 // for each defined operator().
1078 struct PolymorphicFunctor {
1079 typedef int result_type;
1080 int operator()(int n) { return n; }
1081 int operator()(const char* s) { return static_cast<int>(strlen(s)); }
1082 std::string operator()(int* p) { return p ? "good ptr" : "null"; }
1085 TEST(ResultOfTest, WorksForPolymorphicFunctors) {
1086 Matcher<int> matcher_int = ResultOf(PolymorphicFunctor(), Ge(5));
1088 EXPECT_TRUE(matcher_int.Matches(10));
1089 EXPECT_FALSE(matcher_int.Matches(2));
1091 Matcher<const char*> matcher_string = ResultOf(PolymorphicFunctor(), Ge(5));
1093 EXPECT_TRUE(matcher_string.Matches("long string"));
1094 EXPECT_FALSE(matcher_string.Matches("shrt"));
1097 TEST(ResultOfTest, WorksForPolymorphicFunctorsIgnoringResultType) {
1098 Matcher<int*> matcher = ResultOf(PolymorphicFunctor(), "good ptr");
1101 EXPECT_TRUE(matcher.Matches(&n));
1102 EXPECT_FALSE(matcher.Matches(nullptr));
1105 TEST(ResultOfTest, WorksForLambdas) {
1106 Matcher<int> matcher = ResultOf(
1108 return std::string(static_cast<size_t>(str_len), 'x');
1111 EXPECT_TRUE(matcher.Matches(3));
1112 EXPECT_FALSE(matcher.Matches(1));
1115 TEST(ResultOfTest, WorksForNonCopyableArguments) {
1116 Matcher<std::unique_ptr<int>> matcher = ResultOf(
1117 [](const std::unique_ptr<int>& str_len) {
1118 return std::string(static_cast<size_t>(*str_len), 'x');
1121 EXPECT_TRUE(matcher.Matches(std::unique_ptr<int>(new int(3))));
1122 EXPECT_FALSE(matcher.Matches(std::unique_ptr<int>(new int(1))));
1125 const int* ReferencingFunction(const int& n) { return &n; }
1127 struct ReferencingFunctor {
1128 typedef const int* result_type;
1129 result_type operator()(const int& n) { return &n; }
1132 TEST(ResultOfTest, WorksForReferencingCallables) {
1135 Matcher<const int&> matcher2 = ResultOf(ReferencingFunction, Eq(&n));
1136 EXPECT_TRUE(matcher2.Matches(n));
1137 EXPECT_FALSE(matcher2.Matches(n2));
1139 Matcher<const int&> matcher3 = ResultOf(ReferencingFunctor(), Eq(&n));
1140 EXPECT_TRUE(matcher3.Matches(n));
1141 EXPECT_FALSE(matcher3.Matches(n2));
1144 TEST(SizeIsTest, ImplementsSizeIs) {
1145 vector<int> container;
1146 EXPECT_THAT(container, SizeIs(0));
1147 EXPECT_THAT(container, Not(SizeIs(1)));
1148 container.push_back(0);
1149 EXPECT_THAT(container, Not(SizeIs(0)));
1150 EXPECT_THAT(container, SizeIs(1));
1151 container.push_back(0);
1152 EXPECT_THAT(container, Not(SizeIs(0)));
1153 EXPECT_THAT(container, SizeIs(2));
1156 TEST(SizeIsTest, WorksWithMap) {
1157 map<std::string, int> container;
1158 EXPECT_THAT(container, SizeIs(0));
1159 EXPECT_THAT(container, Not(SizeIs(1)));
1160 container.insert(make_pair("foo", 1));
1161 EXPECT_THAT(container, Not(SizeIs(0)));
1162 EXPECT_THAT(container, SizeIs(1));
1163 container.insert(make_pair("bar", 2));
1164 EXPECT_THAT(container, Not(SizeIs(0)));
1165 EXPECT_THAT(container, SizeIs(2));
1168 TEST(SizeIsTest, WorksWithReferences) {
1169 vector<int> container;
1170 Matcher<const vector<int>&> m = SizeIs(1);
1171 EXPECT_THAT(container, Not(m));
1172 container.push_back(0);
1173 EXPECT_THAT(container, m);
1176 TEST(SizeIsTest, WorksWithMoveOnly) {
1177 ContainerHelper helper;
1178 EXPECT_CALL(helper, Call(SizeIs(3)));
1179 helper.Call(MakeUniquePtrs({1, 2, 3}));
1182 // SizeIs should work for any type that provides a size() member function.
1183 // For example, a size_type member type should not need to be provided.
1184 struct MinimalistCustomType {
1185 int size() const { return 1; }
1187 TEST(SizeIsTest, WorksWithMinimalistCustomType) {
1188 MinimalistCustomType container;
1189 EXPECT_THAT(container, SizeIs(1));
1190 EXPECT_THAT(container, Not(SizeIs(0)));
1193 TEST(SizeIsTest, CanDescribeSelf) {
1194 Matcher<vector<int>> m = SizeIs(2);
1195 EXPECT_EQ("has a size that is equal to 2", Describe(m));
1196 EXPECT_EQ("has a size that isn't equal to 2", DescribeNegation(m));
1199 TEST(SizeIsTest, ExplainsResult) {
1200 Matcher<vector<int>> m1 = SizeIs(2);
1201 Matcher<vector<int>> m2 = SizeIs(Lt(2u));
1202 Matcher<vector<int>> m3 = SizeIs(AnyOf(0, 3));
1203 Matcher<vector<int>> m4 = SizeIs(Gt(1u));
1204 vector<int> container;
1205 EXPECT_EQ("whose size 0 doesn't match", Explain(m1, container));
1206 EXPECT_EQ("whose size 0 matches", Explain(m2, container));
1207 EXPECT_EQ("whose size 0 matches", Explain(m3, container));
1208 EXPECT_EQ("whose size 0 doesn't match", Explain(m4, container));
1209 container.push_back(0);
1210 container.push_back(0);
1211 EXPECT_EQ("whose size 2 matches", Explain(m1, container));
1212 EXPECT_EQ("whose size 2 doesn't match", Explain(m2, container));
1213 EXPECT_EQ("whose size 2 doesn't match", Explain(m3, container));
1214 EXPECT_EQ("whose size 2 matches", Explain(m4, container));
1217 TEST(WhenSortedByTest, WorksForEmptyContainer) {
1218 const vector<int> numbers;
1219 EXPECT_THAT(numbers, WhenSortedBy(less<int>(), ElementsAre()));
1220 EXPECT_THAT(numbers, Not(WhenSortedBy(less<int>(), ElementsAre(1))));
1223 TEST(WhenSortedByTest, WorksForNonEmptyContainer) {
1224 vector<unsigned> numbers;
1225 numbers.push_back(3);
1226 numbers.push_back(1);
1227 numbers.push_back(2);
1228 numbers.push_back(2);
1229 EXPECT_THAT(numbers,
1230 WhenSortedBy(greater<unsigned>(), ElementsAre(3, 2, 2, 1)));
1231 EXPECT_THAT(numbers,
1232 Not(WhenSortedBy(greater<unsigned>(), ElementsAre(1, 2, 2, 3))));
1235 TEST(WhenSortedByTest, WorksForNonVectorContainer) {
1236 list<std::string> words;
1237 words.push_back("say");
1238 words.push_back("hello");
1239 words.push_back("world");
1240 EXPECT_THAT(words, WhenSortedBy(less<std::string>(),
1241 ElementsAre("hello", "say", "world")));
1242 EXPECT_THAT(words, Not(WhenSortedBy(less<std::string>(),
1243 ElementsAre("say", "hello", "world"))));
1246 TEST(WhenSortedByTest, WorksForNativeArray) {
1247 const int numbers[] = {1, 3, 2, 4};
1248 const int sorted_numbers[] = {1, 2, 3, 4};
1249 EXPECT_THAT(numbers, WhenSortedBy(less<int>(), ElementsAre(1, 2, 3, 4)));
1250 EXPECT_THAT(numbers,
1251 WhenSortedBy(less<int>(), ElementsAreArray(sorted_numbers)));
1252 EXPECT_THAT(numbers, Not(WhenSortedBy(less<int>(), ElementsAre(1, 3, 2, 4))));
1255 TEST(WhenSortedByTest, CanDescribeSelf) {
1256 const Matcher<vector<int>> m = WhenSortedBy(less<int>(), ElementsAre(1, 2));
1258 "(when sorted) has 2 elements where\n"
1259 "element #0 is equal to 1,\n"
1260 "element #1 is equal to 2",
1263 "(when sorted) doesn't have 2 elements, or\n"
1264 "element #0 isn't equal to 1, or\n"
1265 "element #1 isn't equal to 2",
1266 DescribeNegation(m));
1269 TEST(WhenSortedByTest, ExplainsMatchResult) {
1270 const int a[] = {2, 1};
1271 EXPECT_EQ("which is { 1, 2 } when sorted, whose element #0 doesn't match",
1272 Explain(WhenSortedBy(less<int>(), ElementsAre(2, 3)), a));
1273 EXPECT_EQ("which is { 1, 2 } when sorted",
1274 Explain(WhenSortedBy(less<int>(), ElementsAre(1, 2)), a));
1277 // WhenSorted() is a simple wrapper on WhenSortedBy(). Hence we don't
1278 // need to test it as exhaustively as we test the latter.
1280 TEST(WhenSortedTest, WorksForEmptyContainer) {
1281 const vector<int> numbers;
1282 EXPECT_THAT(numbers, WhenSorted(ElementsAre()));
1283 EXPECT_THAT(numbers, Not(WhenSorted(ElementsAre(1))));
1286 TEST(WhenSortedTest, WorksForNonEmptyContainer) {
1287 list<std::string> words;
1288 words.push_back("3");
1289 words.push_back("1");
1290 words.push_back("2");
1291 words.push_back("2");
1292 EXPECT_THAT(words, WhenSorted(ElementsAre("1", "2", "2", "3")));
1293 EXPECT_THAT(words, Not(WhenSorted(ElementsAre("3", "1", "2", "2"))));
1296 TEST(WhenSortedTest, WorksForMapTypes) {
1297 map<std::string, int> word_counts;
1298 word_counts["and"] = 1;
1299 word_counts["the"] = 1;
1300 word_counts["buffalo"] = 2;
1301 EXPECT_THAT(word_counts,
1302 WhenSorted(ElementsAre(Pair("and", 1), Pair("buffalo", 2),
1304 EXPECT_THAT(word_counts,
1305 Not(WhenSorted(ElementsAre(Pair("and", 1), Pair("the", 1),
1306 Pair("buffalo", 2)))));
1309 TEST(WhenSortedTest, WorksForMultiMapTypes) {
1310 multimap<int, int> ifib;
1311 ifib.insert(make_pair(8, 6));
1312 ifib.insert(make_pair(2, 3));
1313 ifib.insert(make_pair(1, 1));
1314 ifib.insert(make_pair(3, 4));
1315 ifib.insert(make_pair(1, 2));
1316 ifib.insert(make_pair(5, 5));
1318 WhenSorted(ElementsAre(Pair(1, 1), Pair(1, 2), Pair(2, 3),
1319 Pair(3, 4), Pair(5, 5), Pair(8, 6))));
1321 Not(WhenSorted(ElementsAre(Pair(8, 6), Pair(2, 3), Pair(1, 1),
1322 Pair(3, 4), Pair(1, 2), Pair(5, 5)))));
1325 TEST(WhenSortedTest, WorksForPolymorphicMatcher) {
1329 EXPECT_THAT(d, WhenSorted(ElementsAre(1, 2)));
1330 EXPECT_THAT(d, Not(WhenSorted(ElementsAre(2, 1))));
1333 TEST(WhenSortedTest, WorksForVectorConstRefMatcher) {
1337 Matcher<const std::vector<int>&> vector_match = ElementsAre(1, 2);
1338 EXPECT_THAT(d, WhenSorted(vector_match));
1339 Matcher<const std::vector<int>&> not_vector_match = ElementsAre(2, 1);
1340 EXPECT_THAT(d, Not(WhenSorted(not_vector_match)));
1343 // Deliberately bare pseudo-container.
1344 // Offers only begin() and end() accessors, yielding InputIterator.
1345 template <typename T>
1351 typedef ConstIter const_iterator;
1352 typedef T value_type;
1354 template <typename InIter>
1355 Streamlike(InIter first, InIter last) : remainder_(first, last) {}
1357 const_iterator begin() const {
1358 return const_iterator(this, remainder_.begin());
1360 const_iterator end() const { return const_iterator(this, remainder_.end()); }
1365 using iterator_category = std::input_iterator_tag;
1366 using value_type = T;
1367 using difference_type = ptrdiff_t;
1368 using pointer = const value_type*;
1369 using reference = const value_type&;
1371 ConstIter(const Streamlike* s, typename std::list<value_type>::iterator pos)
1372 : s_(s), pos_(pos) {}
1374 const value_type& operator*() const { return *pos_; }
1375 const value_type* operator->() const { return &*pos_; }
1376 ConstIter& operator++() {
1377 s_->remainder_.erase(pos_++);
1381 // *iter++ is required to work (see std::istreambuf_iterator).
1382 // (void)iter++ is also required to work.
1383 class PostIncrProxy {
1385 explicit PostIncrProxy(const value_type& value) : value_(value) {}
1386 value_type operator*() const { return value_; }
1391 PostIncrProxy operator++(int) {
1392 PostIncrProxy proxy(**this);
1397 friend bool operator==(const ConstIter& a, const ConstIter& b) {
1398 return a.s_ == b.s_ && a.pos_ == b.pos_;
1400 friend bool operator!=(const ConstIter& a, const ConstIter& b) {
1405 const Streamlike* s_;
1406 typename std::list<value_type>::iterator pos_;
1409 friend std::ostream& operator<<(std::ostream& os, const Streamlike& s) {
1411 typedef typename std::list<value_type>::const_iterator Iter;
1412 const char* sep = "";
1413 for (Iter it = s.remainder_.begin(); it != s.remainder_.end(); ++it) {
1421 mutable std::list<value_type> remainder_; // modified by iteration
1424 TEST(StreamlikeTest, Iteration) {
1425 const int a[5] = {2, 1, 4, 5, 3};
1426 Streamlike<int> s(a, a + 5);
1427 Streamlike<int>::const_iterator it = s.begin();
1429 while (it != s.end()) {
1430 SCOPED_TRACE(ip - a);
1431 EXPECT_EQ(*ip++, *it++);
1435 INSTANTIATE_GTEST_MATCHER_TEST_P(BeginEndDistanceIsTest);
1437 TEST(BeginEndDistanceIsTest, WorksWithForwardList) {
1438 std::forward_list<int> container;
1439 EXPECT_THAT(container, BeginEndDistanceIs(0));
1440 EXPECT_THAT(container, Not(BeginEndDistanceIs(1)));
1441 container.push_front(0);
1442 EXPECT_THAT(container, Not(BeginEndDistanceIs(0)));
1443 EXPECT_THAT(container, BeginEndDistanceIs(1));
1444 container.push_front(0);
1445 EXPECT_THAT(container, Not(BeginEndDistanceIs(0)));
1446 EXPECT_THAT(container, BeginEndDistanceIs(2));
1449 TEST(BeginEndDistanceIsTest, WorksWithNonStdList) {
1450 const int a[5] = {1, 2, 3, 4, 5};
1451 Streamlike<int> s(a, a + 5);
1452 EXPECT_THAT(s, BeginEndDistanceIs(5));
1455 TEST(BeginEndDistanceIsTest, CanDescribeSelf) {
1456 Matcher<vector<int>> m = BeginEndDistanceIs(2);
1457 EXPECT_EQ("distance between begin() and end() is equal to 2", Describe(m));
1458 EXPECT_EQ("distance between begin() and end() isn't equal to 2",
1459 DescribeNegation(m));
1462 TEST(BeginEndDistanceIsTest, WorksWithMoveOnly) {
1463 ContainerHelper helper;
1464 EXPECT_CALL(helper, Call(BeginEndDistanceIs(2)));
1465 helper.Call(MakeUniquePtrs({1, 2}));
1468 TEST_P(BeginEndDistanceIsTestP, ExplainsResult) {
1469 Matcher<vector<int>> m1 = BeginEndDistanceIs(2);
1470 Matcher<vector<int>> m2 = BeginEndDistanceIs(Lt(2));
1471 Matcher<vector<int>> m3 = BeginEndDistanceIs(AnyOf(0, 3));
1472 Matcher<vector<int>> m4 = BeginEndDistanceIs(GreaterThan(1));
1473 vector<int> container;
1474 EXPECT_EQ("whose distance between begin() and end() 0 doesn't match",
1475 Explain(m1, container));
1476 EXPECT_EQ("whose distance between begin() and end() 0 matches",
1477 Explain(m2, container));
1478 EXPECT_EQ("whose distance between begin() and end() 0 matches",
1479 Explain(m3, container));
1481 "whose distance between begin() and end() 0 doesn't match, which is 1 "
1483 Explain(m4, container));
1484 container.push_back(0);
1485 container.push_back(0);
1486 EXPECT_EQ("whose distance between begin() and end() 2 matches",
1487 Explain(m1, container));
1488 EXPECT_EQ("whose distance between begin() and end() 2 doesn't match",
1489 Explain(m2, container));
1490 EXPECT_EQ("whose distance between begin() and end() 2 doesn't match",
1491 Explain(m3, container));
1493 "whose distance between begin() and end() 2 matches, which is 1 more "
1495 Explain(m4, container));
1498 TEST(WhenSortedTest, WorksForStreamlike) {
1499 // Streamlike 'container' provides only minimal iterator support.
1500 // Its iterators are tagged with input_iterator_tag.
1501 const int a[5] = {2, 1, 4, 5, 3};
1502 Streamlike<int> s(std::begin(a), std::end(a));
1503 EXPECT_THAT(s, WhenSorted(ElementsAre(1, 2, 3, 4, 5)));
1504 EXPECT_THAT(s, Not(WhenSorted(ElementsAre(2, 1, 4, 5, 3))));
1507 TEST(WhenSortedTest, WorksForVectorConstRefMatcherOnStreamlike) {
1508 const int a[] = {2, 1, 4, 5, 3};
1509 Streamlike<int> s(std::begin(a), std::end(a));
1510 Matcher<const std::vector<int>&> vector_match = ElementsAre(1, 2, 3, 4, 5);
1511 EXPECT_THAT(s, WhenSorted(vector_match));
1512 EXPECT_THAT(s, Not(WhenSorted(ElementsAre(2, 1, 4, 5, 3))));
1515 TEST(IsSupersetOfTest, WorksForNativeArray) {
1516 const int subset[] = {1, 4};
1517 const int superset[] = {1, 2, 4};
1518 const int disjoint[] = {1, 0, 3};
1519 EXPECT_THAT(subset, IsSupersetOf(subset));
1520 EXPECT_THAT(subset, Not(IsSupersetOf(superset)));
1521 EXPECT_THAT(superset, IsSupersetOf(subset));
1522 EXPECT_THAT(subset, Not(IsSupersetOf(disjoint)));
1523 EXPECT_THAT(disjoint, Not(IsSupersetOf(subset)));
1526 TEST(IsSupersetOfTest, WorksWithDuplicates) {
1527 const int not_enough[] = {1, 2};
1528 const int enough[] = {1, 1, 2};
1529 const int expected[] = {1, 1};
1530 EXPECT_THAT(not_enough, Not(IsSupersetOf(expected)));
1531 EXPECT_THAT(enough, IsSupersetOf(expected));
1534 TEST(IsSupersetOfTest, WorksForEmpty) {
1535 vector<int> numbers;
1536 vector<int> expected;
1537 EXPECT_THAT(numbers, IsSupersetOf(expected));
1538 expected.push_back(1);
1539 EXPECT_THAT(numbers, Not(IsSupersetOf(expected)));
1541 numbers.push_back(1);
1542 numbers.push_back(2);
1543 EXPECT_THAT(numbers, IsSupersetOf(expected));
1544 expected.push_back(1);
1545 EXPECT_THAT(numbers, IsSupersetOf(expected));
1546 expected.push_back(2);
1547 EXPECT_THAT(numbers, IsSupersetOf(expected));
1548 expected.push_back(3);
1549 EXPECT_THAT(numbers, Not(IsSupersetOf(expected)));
1552 TEST(IsSupersetOfTest, WorksForStreamlike) {
1553 const int a[5] = {1, 2, 3, 4, 5};
1554 Streamlike<int> s(std::begin(a), std::end(a));
1556 vector<int> expected;
1557 expected.push_back(1);
1558 expected.push_back(2);
1559 expected.push_back(5);
1560 EXPECT_THAT(s, IsSupersetOf(expected));
1562 expected.push_back(0);
1563 EXPECT_THAT(s, Not(IsSupersetOf(expected)));
1566 TEST(IsSupersetOfTest, TakesStlContainer) {
1567 const int actual[] = {3, 1, 2};
1569 ::std::list<int> expected;
1570 expected.push_back(1);
1571 expected.push_back(3);
1572 EXPECT_THAT(actual, IsSupersetOf(expected));
1574 expected.push_back(4);
1575 EXPECT_THAT(actual, Not(IsSupersetOf(expected)));
1578 TEST(IsSupersetOfTest, Describe) {
1579 typedef std::vector<int> IntVec;
1581 expected.push_back(111);
1582 expected.push_back(222);
1583 expected.push_back(333);
1585 Describe<IntVec>(IsSupersetOf(expected)),
1586 Eq("a surjection from elements to requirements exists such that:\n"
1587 " - an element is equal to 111\n"
1588 " - an element is equal to 222\n"
1589 " - an element is equal to 333"));
1592 TEST(IsSupersetOfTest, DescribeNegation) {
1593 typedef std::vector<int> IntVec;
1595 expected.push_back(111);
1596 expected.push_back(222);
1597 expected.push_back(333);
1599 DescribeNegation<IntVec>(IsSupersetOf(expected)),
1600 Eq("no surjection from elements to requirements exists such that:\n"
1601 " - an element is equal to 111\n"
1602 " - an element is equal to 222\n"
1603 " - an element is equal to 333"));
1606 TEST(IsSupersetOfTest, MatchAndExplain) {
1610 std::vector<int> expected;
1611 expected.push_back(1);
1612 expected.push_back(2);
1613 StringMatchResultListener listener;
1614 ASSERT_FALSE(ExplainMatchResult(IsSupersetOf(expected), v, &listener))
1616 EXPECT_THAT(listener.str(),
1617 Eq("where the following matchers don't match any elements:\n"
1618 "matcher #0: is equal to 1"));
1622 ASSERT_TRUE(ExplainMatchResult(IsSupersetOf(expected), v, &listener))
1624 EXPECT_THAT(listener.str(), Eq("where:\n"
1625 " - element #0 is matched by matcher #1,\n"
1626 " - element #2 is matched by matcher #0"));
1629 TEST(IsSupersetOfTest, WorksForRhsInitializerList) {
1630 const int numbers[] = {1, 3, 6, 2, 4, 5};
1631 EXPECT_THAT(numbers, IsSupersetOf({1, 2}));
1632 EXPECT_THAT(numbers, Not(IsSupersetOf({3, 0})));
1635 TEST(IsSupersetOfTest, WorksWithMoveOnly) {
1636 ContainerHelper helper;
1637 EXPECT_CALL(helper, Call(IsSupersetOf({Pointee(1)})));
1638 helper.Call(MakeUniquePtrs({1, 2}));
1639 EXPECT_CALL(helper, Call(Not(IsSupersetOf({Pointee(1), Pointee(2)}))));
1640 helper.Call(MakeUniquePtrs({2}));
1643 TEST(IsSubsetOfTest, WorksForNativeArray) {
1644 const int subset[] = {1, 4};
1645 const int superset[] = {1, 2, 4};
1646 const int disjoint[] = {1, 0, 3};
1647 EXPECT_THAT(subset, IsSubsetOf(subset));
1648 EXPECT_THAT(subset, IsSubsetOf(superset));
1649 EXPECT_THAT(superset, Not(IsSubsetOf(subset)));
1650 EXPECT_THAT(subset, Not(IsSubsetOf(disjoint)));
1651 EXPECT_THAT(disjoint, Not(IsSubsetOf(subset)));
1654 TEST(IsSubsetOfTest, WorksWithDuplicates) {
1655 const int not_enough[] = {1, 2};
1656 const int enough[] = {1, 1, 2};
1657 const int actual[] = {1, 1};
1658 EXPECT_THAT(actual, Not(IsSubsetOf(not_enough)));
1659 EXPECT_THAT(actual, IsSubsetOf(enough));
1662 TEST(IsSubsetOfTest, WorksForEmpty) {
1663 vector<int> numbers;
1664 vector<int> expected;
1665 EXPECT_THAT(numbers, IsSubsetOf(expected));
1666 expected.push_back(1);
1667 EXPECT_THAT(numbers, IsSubsetOf(expected));
1669 numbers.push_back(1);
1670 numbers.push_back(2);
1671 EXPECT_THAT(numbers, Not(IsSubsetOf(expected)));
1672 expected.push_back(1);
1673 EXPECT_THAT(numbers, Not(IsSubsetOf(expected)));
1674 expected.push_back(2);
1675 EXPECT_THAT(numbers, IsSubsetOf(expected));
1676 expected.push_back(3);
1677 EXPECT_THAT(numbers, IsSubsetOf(expected));
1680 TEST(IsSubsetOfTest, WorksForStreamlike) {
1681 const int a[5] = {1, 2};
1682 Streamlike<int> s(std::begin(a), std::end(a));
1684 vector<int> expected;
1685 expected.push_back(1);
1686 EXPECT_THAT(s, Not(IsSubsetOf(expected)));
1687 expected.push_back(2);
1688 expected.push_back(5);
1689 EXPECT_THAT(s, IsSubsetOf(expected));
1692 TEST(IsSubsetOfTest, TakesStlContainer) {
1693 const int actual[] = {3, 1, 2};
1695 ::std::list<int> expected;
1696 expected.push_back(1);
1697 expected.push_back(3);
1698 EXPECT_THAT(actual, Not(IsSubsetOf(expected)));
1700 expected.push_back(2);
1701 expected.push_back(4);
1702 EXPECT_THAT(actual, IsSubsetOf(expected));
1705 TEST(IsSubsetOfTest, Describe) {
1706 typedef std::vector<int> IntVec;
1708 expected.push_back(111);
1709 expected.push_back(222);
1710 expected.push_back(333);
1713 Describe<IntVec>(IsSubsetOf(expected)),
1714 Eq("an injection from elements to requirements exists such that:\n"
1715 " - an element is equal to 111\n"
1716 " - an element is equal to 222\n"
1717 " - an element is equal to 333"));
1720 TEST(IsSubsetOfTest, DescribeNegation) {
1721 typedef std::vector<int> IntVec;
1723 expected.push_back(111);
1724 expected.push_back(222);
1725 expected.push_back(333);
1727 DescribeNegation<IntVec>(IsSubsetOf(expected)),
1728 Eq("no injection from elements to requirements exists such that:\n"
1729 " - an element is equal to 111\n"
1730 " - an element is equal to 222\n"
1731 " - an element is equal to 333"));
1734 TEST(IsSubsetOfTest, MatchAndExplain) {
1738 std::vector<int> expected;
1739 expected.push_back(1);
1740 expected.push_back(2);
1741 StringMatchResultListener listener;
1742 ASSERT_FALSE(ExplainMatchResult(IsSubsetOf(expected), v, &listener))
1744 EXPECT_THAT(listener.str(),
1745 Eq("where the following elements don't match any matchers:\n"
1748 expected.push_back(3);
1750 ASSERT_TRUE(ExplainMatchResult(IsSubsetOf(expected), v, &listener))
1752 EXPECT_THAT(listener.str(), Eq("where:\n"
1753 " - element #0 is matched by matcher #1,\n"
1754 " - element #1 is matched by matcher #2"));
1757 TEST(IsSubsetOfTest, WorksForRhsInitializerList) {
1758 const int numbers[] = {1, 2, 3};
1759 EXPECT_THAT(numbers, IsSubsetOf({1, 2, 3, 4}));
1760 EXPECT_THAT(numbers, Not(IsSubsetOf({1, 2})));
1763 TEST(IsSubsetOfTest, WorksWithMoveOnly) {
1764 ContainerHelper helper;
1765 EXPECT_CALL(helper, Call(IsSubsetOf({Pointee(1), Pointee(2)})));
1766 helper.Call(MakeUniquePtrs({1}));
1767 EXPECT_CALL(helper, Call(Not(IsSubsetOf({Pointee(1)}))));
1768 helper.Call(MakeUniquePtrs({2}));
1771 // Tests using ElementsAre() and ElementsAreArray() with stream-like
1774 TEST(ElemensAreStreamTest, WorksForStreamlike) {
1775 const int a[5] = {1, 2, 3, 4, 5};
1776 Streamlike<int> s(std::begin(a), std::end(a));
1777 EXPECT_THAT(s, ElementsAre(1, 2, 3, 4, 5));
1778 EXPECT_THAT(s, Not(ElementsAre(2, 1, 4, 5, 3)));
1781 TEST(ElemensAreArrayStreamTest, WorksForStreamlike) {
1782 const int a[5] = {1, 2, 3, 4, 5};
1783 Streamlike<int> s(std::begin(a), std::end(a));
1785 vector<int> expected;
1786 expected.push_back(1);
1787 expected.push_back(2);
1788 expected.push_back(3);
1789 expected.push_back(4);
1790 expected.push_back(5);
1791 EXPECT_THAT(s, ElementsAreArray(expected));
1794 EXPECT_THAT(s, Not(ElementsAreArray(expected)));
1797 TEST(ElementsAreTest, WorksWithUncopyable) {
1799 objs[0].set_value(-3);
1800 objs[1].set_value(1);
1801 EXPECT_THAT(objs, ElementsAre(UncopyableIs(-3), Truly(ValueIsPositive)));
1804 TEST(ElementsAreTest, WorksWithMoveOnly) {
1805 ContainerHelper helper;
1806 EXPECT_CALL(helper, Call(ElementsAre(Pointee(1), Pointee(2))));
1807 helper.Call(MakeUniquePtrs({1, 2}));
1809 EXPECT_CALL(helper, Call(ElementsAreArray({Pointee(3), Pointee(4)})));
1810 helper.Call(MakeUniquePtrs({3, 4}));
1813 TEST(ElementsAreTest, TakesStlContainer) {
1814 const int actual[] = {3, 1, 2};
1816 ::std::list<int> expected;
1817 expected.push_back(3);
1818 expected.push_back(1);
1819 expected.push_back(2);
1820 EXPECT_THAT(actual, ElementsAreArray(expected));
1822 expected.push_back(4);
1823 EXPECT_THAT(actual, Not(ElementsAreArray(expected)));
1826 // Tests for UnorderedElementsAreArray()
1828 TEST(UnorderedElementsAreArrayTest, SucceedsWhenExpected) {
1829 const int a[] = {0, 1, 2, 3, 4};
1830 std::vector<int> s(std::begin(a), std::end(a));
1832 StringMatchResultListener listener;
1833 EXPECT_TRUE(ExplainMatchResult(UnorderedElementsAreArray(a), s, &listener))
1835 } while (std::next_permutation(s.begin(), s.end()));
1838 TEST(UnorderedElementsAreArrayTest, VectorBool) {
1839 const bool a[] = {false, true, false, true, true};
1840 const bool b[] = {true, false, true, true, false};
1841 std::vector<bool> expected(std::begin(a), std::end(a));
1842 std::vector<bool> actual(std::begin(b), std::end(b));
1843 StringMatchResultListener listener;
1844 EXPECT_TRUE(ExplainMatchResult(UnorderedElementsAreArray(expected), actual,
1849 TEST(UnorderedElementsAreArrayTest, WorksForStreamlike) {
1850 // Streamlike 'container' provides only minimal iterator support.
1851 // Its iterators are tagged with input_iterator_tag, and it has no
1852 // size() or empty() methods.
1853 const int a[5] = {2, 1, 4, 5, 3};
1854 Streamlike<int> s(std::begin(a), std::end(a));
1856 ::std::vector<int> expected;
1857 expected.push_back(1);
1858 expected.push_back(2);
1859 expected.push_back(3);
1860 expected.push_back(4);
1861 expected.push_back(5);
1862 EXPECT_THAT(s, UnorderedElementsAreArray(expected));
1864 expected.push_back(6);
1865 EXPECT_THAT(s, Not(UnorderedElementsAreArray(expected)));
1868 TEST(UnorderedElementsAreArrayTest, TakesStlContainer) {
1869 const int actual[] = {3, 1, 2};
1871 ::std::list<int> expected;
1872 expected.push_back(1);
1873 expected.push_back(2);
1874 expected.push_back(3);
1875 EXPECT_THAT(actual, UnorderedElementsAreArray(expected));
1877 expected.push_back(4);
1878 EXPECT_THAT(actual, Not(UnorderedElementsAreArray(expected)));
1881 TEST(UnorderedElementsAreArrayTest, TakesInitializerList) {
1882 const int a[5] = {2, 1, 4, 5, 3};
1883 EXPECT_THAT(a, UnorderedElementsAreArray({1, 2, 3, 4, 5}));
1884 EXPECT_THAT(a, Not(UnorderedElementsAreArray({1, 2, 3, 4, 6})));
1887 TEST(UnorderedElementsAreArrayTest, TakesInitializerListOfCStrings) {
1888 const std::string a[5] = {"a", "b", "c", "d", "e"};
1889 EXPECT_THAT(a, UnorderedElementsAreArray({"a", "b", "c", "d", "e"}));
1890 EXPECT_THAT(a, Not(UnorderedElementsAreArray({"a", "b", "c", "d", "ef"})));
1893 TEST(UnorderedElementsAreArrayTest, TakesInitializerListOfSameTypedMatchers) {
1894 const int a[5] = {2, 1, 4, 5, 3};
1896 UnorderedElementsAreArray({Eq(1), Eq(2), Eq(3), Eq(4), Eq(5)}));
1898 a, Not(UnorderedElementsAreArray({Eq(1), Eq(2), Eq(3), Eq(4), Eq(6)})));
1901 TEST(UnorderedElementsAreArrayTest,
1902 TakesInitializerListOfDifferentTypedMatchers) {
1903 const int a[5] = {2, 1, 4, 5, 3};
1904 // The compiler cannot infer the type of the initializer list if its
1905 // elements have different types. We must explicitly specify the
1906 // unified element type in this case.
1907 EXPECT_THAT(a, UnorderedElementsAreArray<Matcher<int>>(
1908 {Eq(1), Ne(-2), Ge(3), Le(4), Eq(5)}));
1909 EXPECT_THAT(a, Not(UnorderedElementsAreArray<Matcher<int>>(
1910 {Eq(1), Ne(-2), Ge(3), Le(4), Eq(6)})));
1913 TEST(UnorderedElementsAreArrayTest, WorksWithMoveOnly) {
1914 ContainerHelper helper;
1916 Call(UnorderedElementsAreArray({Pointee(1), Pointee(2)})));
1917 helper.Call(MakeUniquePtrs({2, 1}));
1920 class UnorderedElementsAreTest : public testing::Test {
1922 typedef std::vector<int> IntVec;
1925 TEST_F(UnorderedElementsAreTest, WorksWithUncopyable) {
1927 objs[0].set_value(-3);
1928 objs[1].set_value(1);
1930 UnorderedElementsAre(Truly(ValueIsPositive), UncopyableIs(-3)));
1933 TEST_F(UnorderedElementsAreTest, SucceedsWhenExpected) {
1934 const int a[] = {1, 2, 3};
1935 std::vector<int> s(std::begin(a), std::end(a));
1937 StringMatchResultListener listener;
1938 EXPECT_TRUE(ExplainMatchResult(UnorderedElementsAre(1, 2, 3), s, &listener))
1940 } while (std::next_permutation(s.begin(), s.end()));
1943 TEST_F(UnorderedElementsAreTest, FailsWhenAnElementMatchesNoMatcher) {
1944 const int a[] = {1, 2, 3};
1945 std::vector<int> s(std::begin(a), std::end(a));
1946 std::vector<Matcher<int>> mv;
1950 // The element with value '3' matches nothing: fail fast.
1951 StringMatchResultListener listener;
1952 EXPECT_FALSE(ExplainMatchResult(UnorderedElementsAreArray(mv), s, &listener))
1956 TEST_F(UnorderedElementsAreTest, WorksForStreamlike) {
1957 // Streamlike 'container' provides only minimal iterator support.
1958 // Its iterators are tagged with input_iterator_tag, and it has no
1959 // size() or empty() methods.
1960 const int a[5] = {2, 1, 4, 5, 3};
1961 Streamlike<int> s(std::begin(a), std::end(a));
1963 EXPECT_THAT(s, UnorderedElementsAre(1, 2, 3, 4, 5));
1964 EXPECT_THAT(s, Not(UnorderedElementsAre(2, 2, 3, 4, 5)));
1967 TEST_F(UnorderedElementsAreTest, WorksWithMoveOnly) {
1968 ContainerHelper helper;
1969 EXPECT_CALL(helper, Call(UnorderedElementsAre(Pointee(1), Pointee(2))));
1970 helper.Call(MakeUniquePtrs({2, 1}));
1973 // One naive implementation of the matcher runs in O(N!) time, which is too
1974 // slow for many real-world inputs. This test shows that our matcher can match
1975 // 100 inputs very quickly (a few milliseconds). An O(100!) is 10^158
1976 // iterations and obviously effectively incomputable.
1977 // [ RUN ] UnorderedElementsAreTest.Performance
1978 // [ OK ] UnorderedElementsAreTest.Performance (4 ms)
1979 TEST_F(UnorderedElementsAreTest, Performance) {
1981 std::vector<Matcher<int>> mv;
1982 for (int i = 0; i < 100; ++i) {
1987 StringMatchResultListener listener;
1988 EXPECT_TRUE(ExplainMatchResult(UnorderedElementsAreArray(mv), s, &listener))
1992 // Another variant of 'Performance' with similar expectations.
1993 // [ RUN ] UnorderedElementsAreTest.PerformanceHalfStrict
1994 // [ OK ] UnorderedElementsAreTest.PerformanceHalfStrict (4 ms)
1995 TEST_F(UnorderedElementsAreTest, PerformanceHalfStrict) {
1997 std::vector<Matcher<int>> mv;
1998 for (int i = 0; i < 100; ++i) {
2006 StringMatchResultListener listener;
2007 EXPECT_TRUE(ExplainMatchResult(UnorderedElementsAreArray(mv), s, &listener))
2011 TEST_F(UnorderedElementsAreTest, FailMessageCountWrong) {
2014 StringMatchResultListener listener;
2015 EXPECT_FALSE(ExplainMatchResult(UnorderedElementsAre(1, 2, 3), v, &listener))
2017 EXPECT_THAT(listener.str(), Eq("which has 1 element"));
2020 TEST_F(UnorderedElementsAreTest, FailMessageCountWrongZero) {
2022 StringMatchResultListener listener;
2023 EXPECT_FALSE(ExplainMatchResult(UnorderedElementsAre(1, 2, 3), v, &listener))
2025 EXPECT_THAT(listener.str(), Eq(""));
2028 TEST_F(UnorderedElementsAreTest, FailMessageUnmatchedMatchers) {
2032 StringMatchResultListener listener;
2033 EXPECT_FALSE(ExplainMatchResult(UnorderedElementsAre(1, 2), v, &listener))
2035 EXPECT_THAT(listener.str(),
2036 Eq("where the following matchers don't match any elements:\n"
2037 "matcher #1: is equal to 2"));
2040 TEST_F(UnorderedElementsAreTest, FailMessageUnmatchedElements) {
2044 StringMatchResultListener listener;
2045 EXPECT_FALSE(ExplainMatchResult(UnorderedElementsAre(1, 1), v, &listener))
2047 EXPECT_THAT(listener.str(),
2048 Eq("where the following elements don't match any matchers:\n"
2052 TEST_F(UnorderedElementsAreTest, FailMessageUnmatchedMatcherAndElement) {
2056 StringMatchResultListener listener;
2057 EXPECT_FALSE(ExplainMatchResult(UnorderedElementsAre(1, 2), v, &listener))
2059 EXPECT_THAT(listener.str(),
2061 " the following matchers don't match any elements:\n"
2062 "matcher #0: is equal to 1\n"
2065 " the following elements don't match any matchers:\n"
2069 // Test helper for formatting element, matcher index pairs in expectations.
2070 static std::string EMString(int element, int matcher) {
2072 ss << "(element #" << element << ", matcher #" << matcher << ")";
2076 TEST_F(UnorderedElementsAreTest, FailMessageImperfectMatchOnly) {
2077 // A situation where all elements and matchers have a match
2078 // associated with them, but the max matching is not perfect.
2079 std::vector<std::string> v;
2083 StringMatchResultListener listener;
2084 EXPECT_FALSE(ExplainMatchResult(
2085 UnorderedElementsAre("a", "a", AnyOf("b", "c")), v, &listener))
2088 std::string prefix =
2089 "where no permutation of the elements can satisfy all matchers, "
2090 "and the closest match is 2 of 3 matchers with the "
2093 // We have to be a bit loose here, because there are 4 valid max matches.
2097 prefix + "{\n " + EMString(0, 0) + ",\n " + EMString(1, 2) + "\n}",
2098 prefix + "{\n " + EMString(0, 1) + ",\n " + EMString(1, 2) + "\n}",
2099 prefix + "{\n " + EMString(0, 0) + ",\n " + EMString(2, 2) + "\n}",
2100 prefix + "{\n " + EMString(0, 1) + ",\n " + EMString(2, 2) +
2104 TEST_F(UnorderedElementsAreTest, Describe) {
2105 EXPECT_THAT(Describe<IntVec>(UnorderedElementsAre()), Eq("is empty"));
2106 EXPECT_THAT(Describe<IntVec>(UnorderedElementsAre(345)),
2107 Eq("has 1 element and that element is equal to 345"));
2108 EXPECT_THAT(Describe<IntVec>(UnorderedElementsAre(111, 222, 333)),
2109 Eq("has 3 elements and there exists some permutation "
2110 "of elements such that:\n"
2111 " - element #0 is equal to 111, and\n"
2112 " - element #1 is equal to 222, and\n"
2113 " - element #2 is equal to 333"));
2116 TEST_F(UnorderedElementsAreTest, DescribeNegation) {
2117 EXPECT_THAT(DescribeNegation<IntVec>(UnorderedElementsAre()),
2120 DescribeNegation<IntVec>(UnorderedElementsAre(345)),
2121 Eq("doesn't have 1 element, or has 1 element that isn't equal to 345"));
2122 EXPECT_THAT(DescribeNegation<IntVec>(UnorderedElementsAre(123, 234, 345)),
2123 Eq("doesn't have 3 elements, or there exists no permutation "
2124 "of elements such that:\n"
2125 " - element #0 is equal to 123, and\n"
2126 " - element #1 is equal to 234, and\n"
2127 " - element #2 is equal to 345"));
2132 INSTANTIATE_GTEST_MATCHER_TEST_P(EachTest);
2134 TEST_P(EachTestP, ExplainsMatchResultCorrectly) {
2135 set<int> a; // empty
2137 Matcher<set<int>> m = Each(2);
2138 EXPECT_EQ("", Explain(m, a));
2140 Matcher<const int(&)[1]> n = Each(1); // NOLINT
2142 const int b[1] = {1};
2143 EXPECT_EQ("", Explain(n, b));
2146 EXPECT_EQ("whose element #0 doesn't match", Explain(n, b));
2151 m = Each(GreaterThan(0));
2152 EXPECT_EQ("", Explain(m, a));
2154 m = Each(GreaterThan(10));
2155 EXPECT_EQ("whose element #0 doesn't match, which is 9 less than 10",
2159 TEST(EachTest, DescribesItselfCorrectly) {
2160 Matcher<vector<int>> m = Each(1);
2161 EXPECT_EQ("only contains elements that is equal to 1", Describe(m));
2163 Matcher<vector<int>> m2 = Not(m);
2164 EXPECT_EQ("contains some element that isn't equal to 1", Describe(m2));
2167 TEST(EachTest, MatchesVectorWhenAllElementsMatch) {
2168 vector<int> some_vector;
2169 EXPECT_THAT(some_vector, Each(1));
2170 some_vector.push_back(3);
2171 EXPECT_THAT(some_vector, Not(Each(1)));
2172 EXPECT_THAT(some_vector, Each(3));
2173 some_vector.push_back(1);
2174 some_vector.push_back(2);
2175 EXPECT_THAT(some_vector, Not(Each(3)));
2176 EXPECT_THAT(some_vector, Each(Lt(3.5)));
2178 vector<std::string> another_vector;
2179 another_vector.push_back("fee");
2180 EXPECT_THAT(another_vector, Each(std::string("fee")));
2181 another_vector.push_back("fie");
2182 another_vector.push_back("foe");
2183 another_vector.push_back("fum");
2184 EXPECT_THAT(another_vector, Not(Each(std::string("fee"))));
2187 TEST(EachTest, MatchesMapWhenAllElementsMatch) {
2188 map<const char*, int> my_map;
2189 const char* bar = "a string";
2191 EXPECT_THAT(my_map, Each(make_pair(bar, 2)));
2193 map<std::string, int> another_map;
2194 EXPECT_THAT(another_map, Each(make_pair(std::string("fee"), 1)));
2195 another_map["fee"] = 1;
2196 EXPECT_THAT(another_map, Each(make_pair(std::string("fee"), 1)));
2197 another_map["fie"] = 2;
2198 another_map["foe"] = 3;
2199 another_map["fum"] = 4;
2200 EXPECT_THAT(another_map, Not(Each(make_pair(std::string("fee"), 1))));
2201 EXPECT_THAT(another_map, Not(Each(make_pair(std::string("fum"), 1))));
2202 EXPECT_THAT(another_map, Each(Pair(_, Gt(0))));
2205 TEST(EachTest, AcceptsMatcher) {
2206 const int a[] = {1, 2, 3};
2207 EXPECT_THAT(a, Each(Gt(0)));
2208 EXPECT_THAT(a, Not(Each(Gt(1))));
2211 TEST(EachTest, WorksForNativeArrayAsTuple) {
2212 const int a[] = {1, 2};
2213 const int* const pointer = a;
2214 EXPECT_THAT(std::make_tuple(pointer, 2), Each(Gt(0)));
2215 EXPECT_THAT(std::make_tuple(pointer, 2), Not(Each(Gt(1))));
2218 TEST(EachTest, WorksWithMoveOnly) {
2219 ContainerHelper helper;
2220 EXPECT_CALL(helper, Call(Each(Pointee(Gt(0)))));
2221 helper.Call(MakeUniquePtrs({1, 2}));
2224 // For testing Pointwise().
2225 class IsHalfOfMatcher {
2227 template <typename T1, typename T2>
2228 bool MatchAndExplain(const std::tuple<T1, T2>& a_pair,
2229 MatchResultListener* listener) const {
2230 if (std::get<0>(a_pair) == std::get<1>(a_pair) / 2) {
2231 *listener << "where the second is " << std::get<1>(a_pair);
2234 *listener << "where the second/2 is " << std::get<1>(a_pair) / 2;
2239 void DescribeTo(ostream* os) const {
2240 *os << "are a pair where the first is half of the second";
2243 void DescribeNegationTo(ostream* os) const {
2244 *os << "are a pair where the first isn't half of the second";
2248 PolymorphicMatcher<IsHalfOfMatcher> IsHalfOf() {
2249 return MakePolymorphicMatcher(IsHalfOfMatcher());
2252 TEST(PointwiseTest, DescribesSelf) {
2257 const Matcher<const vector<int>&> m = Pointwise(IsHalfOf(), rhs);
2259 "contains 3 values, where each value and its corresponding value "
2260 "in { 1, 2, 3 } are a pair where the first is half of the second",
2263 "doesn't contain exactly 3 values, or contains a value x at some "
2264 "index i where x and the i-th value of { 1, 2, 3 } are a pair "
2265 "where the first isn't half of the second",
2266 DescribeNegation(m));
2269 TEST(PointwiseTest, MakesCopyOfRhs) {
2270 list<signed char> rhs;
2275 const Matcher<const int(&)[2]> m = Pointwise(IsHalfOf(), rhs);
2276 EXPECT_THAT(lhs, m);
2278 // Changing rhs now shouldn't affect m, which made a copy of rhs.
2280 EXPECT_THAT(lhs, m);
2283 TEST(PointwiseTest, WorksForLhsNativeArray) {
2284 const int lhs[] = {1, 2, 3};
2289 EXPECT_THAT(lhs, Pointwise(Lt(), rhs));
2290 EXPECT_THAT(lhs, Not(Pointwise(Gt(), rhs)));
2293 TEST(PointwiseTest, WorksForRhsNativeArray) {
2294 const int rhs[] = {1, 2, 3};
2299 EXPECT_THAT(lhs, Pointwise(Gt(), rhs));
2300 EXPECT_THAT(lhs, Not(Pointwise(Lt(), rhs)));
2303 // Test is effective only with sanitizers.
2304 TEST(PointwiseTest, WorksForVectorOfBool) {
2305 vector<bool> rhs(3, false);
2307 vector<bool> lhs = rhs;
2308 EXPECT_THAT(lhs, Pointwise(Eq(), rhs));
2310 EXPECT_THAT(lhs, Not(Pointwise(Eq(), rhs)));
2313 TEST(PointwiseTest, WorksForRhsInitializerList) {
2314 const vector<int> lhs{2, 4, 6};
2315 EXPECT_THAT(lhs, Pointwise(Gt(), {1, 2, 3}));
2316 EXPECT_THAT(lhs, Not(Pointwise(Lt(), {3, 3, 7})));
2319 TEST(PointwiseTest, RejectsWrongSize) {
2320 const double lhs[2] = {1, 2};
2321 const int rhs[1] = {0};
2322 EXPECT_THAT(lhs, Not(Pointwise(Gt(), rhs)));
2323 EXPECT_EQ("which contains 2 values", Explain(Pointwise(Gt(), rhs), lhs));
2325 const int rhs2[3] = {0, 1, 2};
2326 EXPECT_THAT(lhs, Not(Pointwise(Gt(), rhs2)));
2329 TEST(PointwiseTest, RejectsWrongContent) {
2330 const double lhs[3] = {1, 2, 3};
2331 const int rhs[3] = {2, 6, 4};
2332 EXPECT_THAT(lhs, Not(Pointwise(IsHalfOf(), rhs)));
2334 "where the value pair (2, 6) at index #1 don't match, "
2335 "where the second/2 is 3",
2336 Explain(Pointwise(IsHalfOf(), rhs), lhs));
2339 TEST(PointwiseTest, AcceptsCorrectContent) {
2340 const double lhs[3] = {1, 2, 3};
2341 const int rhs[3] = {2, 4, 6};
2342 EXPECT_THAT(lhs, Pointwise(IsHalfOf(), rhs));
2343 EXPECT_EQ("", Explain(Pointwise(IsHalfOf(), rhs), lhs));
2346 TEST(PointwiseTest, AllowsMonomorphicInnerMatcher) {
2347 const double lhs[3] = {1, 2, 3};
2348 const int rhs[3] = {2, 4, 6};
2349 const Matcher<std::tuple<const double&, const int&>> m1 = IsHalfOf();
2350 EXPECT_THAT(lhs, Pointwise(m1, rhs));
2351 EXPECT_EQ("", Explain(Pointwise(m1, rhs), lhs));
2353 // This type works as a std::tuple<const double&, const int&> can be
2354 // implicitly cast to std::tuple<double, int>.
2355 const Matcher<std::tuple<double, int>> m2 = IsHalfOf();
2356 EXPECT_THAT(lhs, Pointwise(m2, rhs));
2357 EXPECT_EQ("", Explain(Pointwise(m2, rhs), lhs));
2360 MATCHER(PointeeEquals, "Points to an equal value") {
2361 return ExplainMatchResult(::testing::Pointee(::testing::get<1>(arg)),
2362 ::testing::get<0>(arg), result_listener);
2365 TEST(PointwiseTest, WorksWithMoveOnly) {
2366 ContainerHelper helper;
2367 EXPECT_CALL(helper, Call(Pointwise(PointeeEquals(), std::vector<int>{1, 2})));
2368 helper.Call(MakeUniquePtrs({1, 2}));
2371 TEST(UnorderedPointwiseTest, DescribesSelf) {
2376 const Matcher<const vector<int>&> m = UnorderedPointwise(IsHalfOf(), rhs);
2378 "has 3 elements and there exists some permutation of elements such "
2380 " - element #0 and 1 are a pair where the first is half of the second, "
2382 " - element #1 and 2 are a pair where the first is half of the second, "
2384 " - element #2 and 3 are a pair where the first is half of the second",
2387 "doesn't have 3 elements, or there exists no permutation of elements "
2389 " - element #0 and 1 are a pair where the first is half of the second, "
2391 " - element #1 and 2 are a pair where the first is half of the second, "
2393 " - element #2 and 3 are a pair where the first is half of the second",
2394 DescribeNegation(m));
2397 TEST(UnorderedPointwiseTest, MakesCopyOfRhs) {
2398 list<signed char> rhs;
2403 const Matcher<const int(&)[2]> m = UnorderedPointwise(IsHalfOf(), rhs);
2404 EXPECT_THAT(lhs, m);
2406 // Changing rhs now shouldn't affect m, which made a copy of rhs.
2408 EXPECT_THAT(lhs, m);
2411 TEST(UnorderedPointwiseTest, WorksForLhsNativeArray) {
2412 const int lhs[] = {1, 2, 3};
2417 EXPECT_THAT(lhs, UnorderedPointwise(Lt(), rhs));
2418 EXPECT_THAT(lhs, Not(UnorderedPointwise(Gt(), rhs)));
2421 TEST(UnorderedPointwiseTest, WorksForRhsNativeArray) {
2422 const int rhs[] = {1, 2, 3};
2427 EXPECT_THAT(lhs, UnorderedPointwise(Gt(), rhs));
2428 EXPECT_THAT(lhs, Not(UnorderedPointwise(Lt(), rhs)));
2431 TEST(UnorderedPointwiseTest, WorksForRhsInitializerList) {
2432 const vector<int> lhs{2, 4, 6};
2433 EXPECT_THAT(lhs, UnorderedPointwise(Gt(), {5, 1, 3}));
2434 EXPECT_THAT(lhs, Not(UnorderedPointwise(Lt(), {1, 1, 7})));
2437 TEST(UnorderedPointwiseTest, RejectsWrongSize) {
2438 const double lhs[2] = {1, 2};
2439 const int rhs[1] = {0};
2440 EXPECT_THAT(lhs, Not(UnorderedPointwise(Gt(), rhs)));
2441 EXPECT_EQ("which has 2 elements",
2442 Explain(UnorderedPointwise(Gt(), rhs), lhs));
2444 const int rhs2[3] = {0, 1, 2};
2445 EXPECT_THAT(lhs, Not(UnorderedPointwise(Gt(), rhs2)));
2448 TEST(UnorderedPointwiseTest, RejectsWrongContent) {
2449 const double lhs[3] = {1, 2, 3};
2450 const int rhs[3] = {2, 6, 6};
2451 EXPECT_THAT(lhs, Not(UnorderedPointwise(IsHalfOf(), rhs)));
2453 "where the following elements don't match any matchers:\n"
2455 Explain(UnorderedPointwise(IsHalfOf(), rhs), lhs));
2458 TEST(UnorderedPointwiseTest, AcceptsCorrectContentInSameOrder) {
2459 const double lhs[3] = {1, 2, 3};
2460 const int rhs[3] = {2, 4, 6};
2461 EXPECT_THAT(lhs, UnorderedPointwise(IsHalfOf(), rhs));
2464 TEST(UnorderedPointwiseTest, AcceptsCorrectContentInDifferentOrder) {
2465 const double lhs[3] = {1, 2, 3};
2466 const int rhs[3] = {6, 4, 2};
2467 EXPECT_THAT(lhs, UnorderedPointwise(IsHalfOf(), rhs));
2470 TEST(UnorderedPointwiseTest, AllowsMonomorphicInnerMatcher) {
2471 const double lhs[3] = {1, 2, 3};
2472 const int rhs[3] = {4, 6, 2};
2473 const Matcher<std::tuple<const double&, const int&>> m1 = IsHalfOf();
2474 EXPECT_THAT(lhs, UnorderedPointwise(m1, rhs));
2476 // This type works as a std::tuple<const double&, const int&> can be
2477 // implicitly cast to std::tuple<double, int>.
2478 const Matcher<std::tuple<double, int>> m2 = IsHalfOf();
2479 EXPECT_THAT(lhs, UnorderedPointwise(m2, rhs));
2482 TEST(UnorderedPointwiseTest, WorksWithMoveOnly) {
2483 ContainerHelper helper;
2484 EXPECT_CALL(helper, Call(UnorderedPointwise(PointeeEquals(),
2485 std::vector<int>{1, 2})));
2486 helper.Call(MakeUniquePtrs({2, 1}));
2489 TEST(PointeeTest, WorksOnMoveOnlyType) {
2490 std::unique_ptr<int> p(new int(3));
2491 EXPECT_THAT(p, Pointee(Eq(3)));
2492 EXPECT_THAT(p, Not(Pointee(Eq(2))));
2495 class PredicateFormatterFromMatcherTest : public ::testing::Test {
2497 enum Behavior { kInitialSuccess, kAlwaysFail, kFlaky };
2499 // A matcher that can return different results when used multiple times on the
2500 // same input. No real matcher should do this; but this lets us test that we
2501 // detect such behavior and fail appropriately.
2502 class MockMatcher : public MatcherInterface<Behavior> {
2504 bool MatchAndExplain(Behavior behavior,
2505 MatchResultListener* listener) const override {
2506 *listener << "[MatchAndExplain]";
2508 case kInitialSuccess:
2509 // The first call to MatchAndExplain should use a "not interested"
2510 // listener; so this is expected to return |true|. There should be no
2511 // subsequent calls.
2512 return !listener->IsInterested();
2518 // The first call to MatchAndExplain should use a "not interested"
2519 // listener; so this will return |false|. Subsequent calls should have
2520 // an "interested" listener; so this will return |true|, thus
2521 // simulating a flaky matcher.
2522 return listener->IsInterested();
2525 GTEST_LOG_(FATAL) << "This should never be reached";
2529 void DescribeTo(ostream* os) const override { *os << "[DescribeTo]"; }
2531 void DescribeNegationTo(ostream* os) const override {
2532 *os << "[DescribeNegationTo]";
2536 AssertionResult RunPredicateFormatter(Behavior behavior) {
2537 auto matcher = MakeMatcher(new MockMatcher);
2538 PredicateFormatterFromMatcher<Matcher<Behavior>> predicate_formatter(
2540 return predicate_formatter("dummy-name", behavior);
2544 TEST_F(PredicateFormatterFromMatcherTest, ShortCircuitOnSuccess) {
2545 AssertionResult result = RunPredicateFormatter(kInitialSuccess);
2546 EXPECT_TRUE(result); // Implicit cast to bool.
2548 EXPECT_EQ(expect, result.message());
2551 TEST_F(PredicateFormatterFromMatcherTest, NoShortCircuitOnFailure) {
2552 AssertionResult result = RunPredicateFormatter(kAlwaysFail);
2553 EXPECT_FALSE(result); // Implicit cast to bool.
2554 std::string expect =
2555 "Value of: dummy-name\nExpected: [DescribeTo]\n"
2557 OfType(internal::GetTypeName<Behavior>()) + ", [MatchAndExplain]";
2558 EXPECT_EQ(expect, result.message());
2561 TEST_F(PredicateFormatterFromMatcherTest, DetectsFlakyShortCircuit) {
2562 AssertionResult result = RunPredicateFormatter(kFlaky);
2563 EXPECT_FALSE(result); // Implicit cast to bool.
2564 std::string expect =
2565 "Value of: dummy-name\nExpected: [DescribeTo]\n"
2566 " The matcher failed on the initial attempt; but passed when rerun to "
2567 "generate the explanation.\n"
2569 OfType(internal::GetTypeName<Behavior>()) + ", [MatchAndExplain]";
2570 EXPECT_EQ(expect, result.message());
2573 // Tests for ElementsAre().
2575 TEST(ElementsAreTest, CanDescribeExpectingNoElement) {
2576 Matcher<const vector<int>&> m = ElementsAre();
2577 EXPECT_EQ("is empty", Describe(m));
2580 TEST(ElementsAreTest, CanDescribeExpectingOneElement) {
2581 Matcher<vector<int>> m = ElementsAre(Gt(5));
2582 EXPECT_EQ("has 1 element that is > 5", Describe(m));
2585 TEST(ElementsAreTest, CanDescribeExpectingManyElements) {
2586 Matcher<list<std::string>> m = ElementsAre(StrEq("one"), "two");
2588 "has 2 elements where\n"
2589 "element #0 is equal to \"one\",\n"
2590 "element #1 is equal to \"two\"",
2594 TEST(ElementsAreTest, CanDescribeNegationOfExpectingNoElement) {
2595 Matcher<vector<int>> m = ElementsAre();
2596 EXPECT_EQ("isn't empty", DescribeNegation(m));
2599 TEST(ElementsAreTest, CanDescribeNegationOfExpectingOneElement) {
2600 Matcher<const list<int>&> m = ElementsAre(Gt(5));
2602 "doesn't have 1 element, or\n"
2603 "element #0 isn't > 5",
2604 DescribeNegation(m));
2607 TEST(ElementsAreTest, CanDescribeNegationOfExpectingManyElements) {
2608 Matcher<const list<std::string>&> m = ElementsAre("one", "two");
2610 "doesn't have 2 elements, or\n"
2611 "element #0 isn't equal to \"one\", or\n"
2612 "element #1 isn't equal to \"two\"",
2613 DescribeNegation(m));
2616 TEST(ElementsAreTest, DoesNotExplainTrivialMatch) {
2617 Matcher<const list<int>&> m = ElementsAre(1, Ne(2));
2619 list<int> test_list;
2620 test_list.push_back(1);
2621 test_list.push_back(3);
2622 EXPECT_EQ("", Explain(m, test_list)); // No need to explain anything.
2625 TEST_P(ElementsAreTestP, ExplainsNonTrivialMatch) {
2626 Matcher<const vector<int>&> m =
2627 ElementsAre(GreaterThan(1), 0, GreaterThan(2));
2629 const int a[] = {10, 0, 100};
2630 vector<int> test_vector(std::begin(a), std::end(a));
2632 "whose element #0 matches, which is 9 more than 1,\n"
2633 "and whose element #2 matches, which is 98 more than 2",
2634 Explain(m, test_vector));
2637 TEST(ElementsAreTest, CanExplainMismatchWrongSize) {
2638 Matcher<const list<int>&> m = ElementsAre(1, 3);
2640 list<int> test_list;
2641 // No need to explain when the container is empty.
2642 EXPECT_EQ("", Explain(m, test_list));
2644 test_list.push_back(1);
2645 EXPECT_EQ("which has 1 element", Explain(m, test_list));
2648 TEST_P(ElementsAreTestP, CanExplainMismatchRightSize) {
2649 Matcher<const vector<int>&> m = ElementsAre(1, GreaterThan(5));
2654 EXPECT_EQ("whose element #0 doesn't match", Explain(m, v));
2657 EXPECT_EQ("whose element #1 doesn't match, which is 4 less than 5",
2661 TEST(ElementsAreTest, MatchesOneElementVector) {
2662 vector<std::string> test_vector;
2663 test_vector.push_back("test string");
2665 EXPECT_THAT(test_vector, ElementsAre(StrEq("test string")));
2668 TEST(ElementsAreTest, MatchesOneElementList) {
2669 list<std::string> test_list;
2670 test_list.push_back("test string");
2672 EXPECT_THAT(test_list, ElementsAre("test string"));
2675 TEST(ElementsAreTest, MatchesThreeElementVector) {
2676 vector<std::string> test_vector;
2677 test_vector.push_back("one");
2678 test_vector.push_back("two");
2679 test_vector.push_back("three");
2681 EXPECT_THAT(test_vector, ElementsAre("one", StrEq("two"), _));
2684 TEST(ElementsAreTest, MatchesOneElementEqMatcher) {
2685 vector<int> test_vector;
2686 test_vector.push_back(4);
2688 EXPECT_THAT(test_vector, ElementsAre(Eq(4)));
2691 TEST(ElementsAreTest, MatchesOneElementAnyMatcher) {
2692 vector<int> test_vector;
2693 test_vector.push_back(4);
2695 EXPECT_THAT(test_vector, ElementsAre(_));
2698 TEST(ElementsAreTest, MatchesOneElementValue) {
2699 vector<int> test_vector;
2700 test_vector.push_back(4);
2702 EXPECT_THAT(test_vector, ElementsAre(4));
2705 TEST(ElementsAreTest, MatchesThreeElementsMixedMatchers) {
2706 vector<int> test_vector;
2707 test_vector.push_back(1);
2708 test_vector.push_back(2);
2709 test_vector.push_back(3);
2711 EXPECT_THAT(test_vector, ElementsAre(1, Eq(2), _));
2714 TEST(ElementsAreTest, MatchesTenElementVector) {
2715 const int a[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
2716 vector<int> test_vector(std::begin(a), std::end(a));
2718 EXPECT_THAT(test_vector,
2719 // The element list can contain values and/or matchers
2720 // of different types.
2721 ElementsAre(0, Ge(0), _, 3, 4, Ne(2), Eq(6), 7, 8, _));
2724 TEST(ElementsAreTest, DoesNotMatchWrongSize) {
2725 vector<std::string> test_vector;
2726 test_vector.push_back("test string");
2727 test_vector.push_back("test string");
2729 Matcher<vector<std::string>> m = ElementsAre(StrEq("test string"));
2730 EXPECT_FALSE(m.Matches(test_vector));
2733 TEST(ElementsAreTest, DoesNotMatchWrongValue) {
2734 vector<std::string> test_vector;
2735 test_vector.push_back("other string");
2737 Matcher<vector<std::string>> m = ElementsAre(StrEq("test string"));
2738 EXPECT_FALSE(m.Matches(test_vector));
2741 TEST(ElementsAreTest, DoesNotMatchWrongOrder) {
2742 vector<std::string> test_vector;
2743 test_vector.push_back("one");
2744 test_vector.push_back("three");
2745 test_vector.push_back("two");
2747 Matcher<vector<std::string>> m =
2748 ElementsAre(StrEq("one"), StrEq("two"), StrEq("three"));
2749 EXPECT_FALSE(m.Matches(test_vector));
2752 TEST(ElementsAreTest, WorksForNestedContainer) {
2753 constexpr std::array<const char*, 2> strings = {{"Hi", "world"}};
2755 vector<list<char>> nested;
2756 for (const auto& s : strings) {
2757 nested.emplace_back(s, s + strlen(s));
2760 EXPECT_THAT(nested, ElementsAre(ElementsAre('H', Ne('e')),
2761 ElementsAre('w', 'o', _, _, 'd')));
2762 EXPECT_THAT(nested, Not(ElementsAre(ElementsAre('H', 'e'),
2763 ElementsAre('w', 'o', _, _, 'd'))));
2766 TEST(ElementsAreTest, WorksWithByRefElementMatchers) {
2767 int a[] = {0, 1, 2};
2768 vector<int> v(std::begin(a), std::end(a));
2770 EXPECT_THAT(v, ElementsAre(Ref(v[0]), Ref(v[1]), Ref(v[2])));
2771 EXPECT_THAT(v, Not(ElementsAre(Ref(v[0]), Ref(v[1]), Ref(a[2]))));
2774 TEST(ElementsAreTest, WorksWithContainerPointerUsingPointee) {
2775 int a[] = {0, 1, 2};
2776 vector<int> v(std::begin(a), std::end(a));
2778 EXPECT_THAT(&v, Pointee(ElementsAre(0, 1, _)));
2779 EXPECT_THAT(&v, Not(Pointee(ElementsAre(0, _, 3))));
2782 TEST(ElementsAreTest, WorksWithNativeArrayPassedByReference) {
2783 int array[] = {0, 1, 2};
2784 EXPECT_THAT(array, ElementsAre(0, 1, _));
2785 EXPECT_THAT(array, Not(ElementsAre(1, _, _)));
2786 EXPECT_THAT(array, Not(ElementsAre(0, _)));
2789 class NativeArrayPassedAsPointerAndSize {
2791 NativeArrayPassedAsPointerAndSize() = default;
2793 MOCK_METHOD(void, Helper, (int* array, int size));
2796 NativeArrayPassedAsPointerAndSize(const NativeArrayPassedAsPointerAndSize&) =
2798 NativeArrayPassedAsPointerAndSize& operator=(
2799 const NativeArrayPassedAsPointerAndSize&) = delete;
2802 TEST(ElementsAreTest, WorksWithNativeArrayPassedAsPointerAndSize) {
2803 int array[] = {0, 1};
2804 ::std::tuple<int*, size_t> array_as_tuple(array, 2);
2805 EXPECT_THAT(array_as_tuple, ElementsAre(0, 1));
2806 EXPECT_THAT(array_as_tuple, Not(ElementsAre(0)));
2808 NativeArrayPassedAsPointerAndSize helper;
2809 EXPECT_CALL(helper, Helper(_, _)).With(ElementsAre(0, 1));
2810 helper.Helper(array, 2);
2813 TEST(ElementsAreTest, WorksWithTwoDimensionalNativeArray) {
2814 const char a2[][3] = {"hi", "lo"};
2815 EXPECT_THAT(a2, ElementsAre(ElementsAre('h', 'i', '\0'),
2816 ElementsAre('l', 'o', '\0')));
2817 EXPECT_THAT(a2, ElementsAre(StrEq("hi"), StrEq("lo")));
2818 EXPECT_THAT(a2, ElementsAre(Not(ElementsAre('h', 'o', '\0')),
2819 ElementsAre('l', 'o', '\0')));
2822 TEST(ElementsAreTest, AcceptsStringLiteral) {
2823 std::string array[] = {"hi", "one", "two"};
2824 EXPECT_THAT(array, ElementsAre("hi", "one", "two"));
2825 EXPECT_THAT(array, Not(ElementsAre("hi", "one", "too")));
2828 // Declared here with the size unknown. Defined AFTER the following test.
2829 extern const char kHi[];
2831 TEST(ElementsAreTest, AcceptsArrayWithUnknownSize) {
2832 // The size of kHi is not known in this test, but ElementsAre() should
2835 std::string array1[] = {"hi"};
2836 EXPECT_THAT(array1, ElementsAre(kHi));
2838 std::string array2[] = {"ho"};
2839 EXPECT_THAT(array2, Not(ElementsAre(kHi)));
2842 const char kHi[] = "hi";
2844 TEST(ElementsAreTest, MakesCopyOfArguments) {
2847 // This should make a copy of x and y.
2848 ::testing::internal::ElementsAreMatcher<std::tuple<int, int>>
2849 polymorphic_matcher = ElementsAre(x, y);
2850 // Changing x and y now shouldn't affect the meaning of the above matcher.
2852 const int array1[] = {1, 2};
2853 EXPECT_THAT(array1, polymorphic_matcher);
2854 const int array2[] = {0, 0};
2855 EXPECT_THAT(array2, Not(polymorphic_matcher));
2858 // Tests for ElementsAreArray(). Since ElementsAreArray() shares most
2859 // of the implementation with ElementsAre(), we don't test it as
2862 TEST(ElementsAreArrayTest, CanBeCreatedWithValueArray) {
2863 const int a[] = {1, 2, 3};
2865 vector<int> test_vector(std::begin(a), std::end(a));
2866 EXPECT_THAT(test_vector, ElementsAreArray(a));
2869 EXPECT_THAT(test_vector, Not(ElementsAreArray(a)));
2872 TEST(ElementsAreArrayTest, CanBeCreatedWithArraySize) {
2873 std::array<const char*, 3> a = {{"one", "two", "three"}};
2875 vector<std::string> test_vector(std::begin(a), std::end(a));
2876 EXPECT_THAT(test_vector, ElementsAreArray(a.data(), a.size()));
2878 const char** p = a.data();
2879 test_vector[0] = "1";
2880 EXPECT_THAT(test_vector, Not(ElementsAreArray(p, a.size())));
2883 TEST(ElementsAreArrayTest, CanBeCreatedWithoutArraySize) {
2884 const char* a[] = {"one", "two", "three"};
2886 vector<std::string> test_vector(std::begin(a), std::end(a));
2887 EXPECT_THAT(test_vector, ElementsAreArray(a));
2889 test_vector[0] = "1";
2890 EXPECT_THAT(test_vector, Not(ElementsAreArray(a)));
2893 TEST(ElementsAreArrayTest, CanBeCreatedWithMatcherArray) {
2894 const Matcher<std::string> kMatcherArray[] = {StrEq("one"), StrEq("two"),
2897 vector<std::string> test_vector;
2898 test_vector.push_back("one");
2899 test_vector.push_back("two");
2900 test_vector.push_back("three");
2901 EXPECT_THAT(test_vector, ElementsAreArray(kMatcherArray));
2903 test_vector.push_back("three");
2904 EXPECT_THAT(test_vector, Not(ElementsAreArray(kMatcherArray)));
2907 TEST(ElementsAreArrayTest, CanBeCreatedWithVector) {
2908 const int a[] = {1, 2, 3};
2909 vector<int> test_vector(std::begin(a), std::end(a));
2910 const vector<int> expected(std::begin(a), std::end(a));
2911 EXPECT_THAT(test_vector, ElementsAreArray(expected));
2912 test_vector.push_back(4);
2913 EXPECT_THAT(test_vector, Not(ElementsAreArray(expected)));
2916 TEST(ElementsAreArrayTest, TakesInitializerList) {
2917 const int a[5] = {1, 2, 3, 4, 5};
2918 EXPECT_THAT(a, ElementsAreArray({1, 2, 3, 4, 5}));
2919 EXPECT_THAT(a, Not(ElementsAreArray({1, 2, 3, 5, 4})));
2920 EXPECT_THAT(a, Not(ElementsAreArray({1, 2, 3, 4, 6})));
2923 TEST(ElementsAreArrayTest, TakesInitializerListOfCStrings) {
2924 const std::string a[5] = {"a", "b", "c", "d", "e"};
2925 EXPECT_THAT(a, ElementsAreArray({"a", "b", "c", "d", "e"}));
2926 EXPECT_THAT(a, Not(ElementsAreArray({"a", "b", "c", "e", "d"})));
2927 EXPECT_THAT(a, Not(ElementsAreArray({"a", "b", "c", "d", "ef"})));
2930 TEST(ElementsAreArrayTest, TakesInitializerListOfSameTypedMatchers) {
2931 const int a[5] = {1, 2, 3, 4, 5};
2932 EXPECT_THAT(a, ElementsAreArray({Eq(1), Eq(2), Eq(3), Eq(4), Eq(5)}));
2933 EXPECT_THAT(a, Not(ElementsAreArray({Eq(1), Eq(2), Eq(3), Eq(4), Eq(6)})));
2936 TEST(ElementsAreArrayTest, TakesInitializerListOfDifferentTypedMatchers) {
2937 const int a[5] = {1, 2, 3, 4, 5};
2938 // The compiler cannot infer the type of the initializer list if its
2939 // elements have different types. We must explicitly specify the
2940 // unified element type in this case.
2942 a, ElementsAreArray<Matcher<int>>({Eq(1), Ne(-2), Ge(3), Le(4), Eq(5)}));
2943 EXPECT_THAT(a, Not(ElementsAreArray<Matcher<int>>(
2944 {Eq(1), Ne(-2), Ge(3), Le(4), Eq(6)})));
2947 TEST(ElementsAreArrayTest, CanBeCreatedWithMatcherVector) {
2948 const int a[] = {1, 2, 3};
2949 const Matcher<int> kMatchers[] = {Eq(1), Eq(2), Eq(3)};
2950 vector<int> test_vector(std::begin(a), std::end(a));
2951 const vector<Matcher<int>> expected(std::begin(kMatchers),
2952 std::end(kMatchers));
2953 EXPECT_THAT(test_vector, ElementsAreArray(expected));
2954 test_vector.push_back(4);
2955 EXPECT_THAT(test_vector, Not(ElementsAreArray(expected)));
2958 TEST(ElementsAreArrayTest, CanBeCreatedWithIteratorRange) {
2959 const int a[] = {1, 2, 3};
2960 const vector<int> test_vector(std::begin(a), std::end(a));
2961 const vector<int> expected(std::begin(a), std::end(a));
2962 EXPECT_THAT(test_vector, ElementsAreArray(expected.begin(), expected.end()));
2963 // Pointers are iterators, too.
2964 EXPECT_THAT(test_vector, ElementsAreArray(std::begin(a), std::end(a)));
2965 // The empty range of NULL pointers should also be okay.
2966 int* const null_int = nullptr;
2967 EXPECT_THAT(test_vector, Not(ElementsAreArray(null_int, null_int)));
2968 EXPECT_THAT((vector<int>()), ElementsAreArray(null_int, null_int));
2971 // Since ElementsAre() and ElementsAreArray() share much of the
2972 // implementation, we only do a test for native arrays here.
2973 TEST(ElementsAreArrayTest, WorksWithNativeArray) {
2974 ::std::string a[] = {"hi", "ho"};
2975 ::std::string b[] = {"hi", "ho"};
2977 EXPECT_THAT(a, ElementsAreArray(b));
2978 EXPECT_THAT(a, ElementsAreArray(b, 2));
2979 EXPECT_THAT(a, Not(ElementsAreArray(b, 1)));
2982 TEST(ElementsAreArrayTest, SourceLifeSpan) {
2983 const int a[] = {1, 2, 3};
2984 vector<int> test_vector(std::begin(a), std::end(a));
2985 vector<int> expect(std::begin(a), std::end(a));
2986 ElementsAreArrayMatcher<int> matcher_maker =
2987 ElementsAreArray(expect.begin(), expect.end());
2988 EXPECT_THAT(test_vector, matcher_maker);
2989 // Changing in place the values that initialized matcher_maker should not
2990 // affect matcher_maker anymore. It should have made its own copy of them.
2991 for (int& i : expect) {
2994 EXPECT_THAT(test_vector, matcher_maker);
2995 test_vector.push_back(3);
2996 EXPECT_THAT(test_vector, Not(matcher_maker));
2999 // Tests Contains().
3001 INSTANTIATE_GTEST_MATCHER_TEST_P(ContainsTest);
3003 TEST(ContainsTest, ListMatchesWhenElementIsInContainer) {
3004 list<int> some_list;
3005 some_list.push_back(3);
3006 some_list.push_back(1);
3007 some_list.push_back(2);
3008 some_list.push_back(3);
3009 EXPECT_THAT(some_list, Contains(1));
3010 EXPECT_THAT(some_list, Contains(Gt(2.5)));
3011 EXPECT_THAT(some_list, Contains(Eq(2.0f)));
3013 list<std::string> another_list;
3014 another_list.push_back("fee");
3015 another_list.push_back("fie");
3016 another_list.push_back("foe");
3017 another_list.push_back("fum");
3018 EXPECT_THAT(another_list, Contains(std::string("fee")));
3021 TEST(ContainsTest, ListDoesNotMatchWhenElementIsNotInContainer) {
3022 list<int> some_list;
3023 some_list.push_back(3);
3024 some_list.push_back(1);
3025 EXPECT_THAT(some_list, Not(Contains(4)));
3028 TEST(ContainsTest, SetMatchesWhenElementIsInContainer) {
3033 EXPECT_THAT(some_set, Contains(Eq(1.0)));
3034 EXPECT_THAT(some_set, Contains(Eq(3.0f)));
3035 EXPECT_THAT(some_set, Contains(2));
3037 set<std::string> another_set;
3038 another_set.insert("fee");
3039 another_set.insert("fie");
3040 another_set.insert("foe");
3041 another_set.insert("fum");
3042 EXPECT_THAT(another_set, Contains(Eq(std::string("fum"))));
3045 TEST(ContainsTest, SetDoesNotMatchWhenElementIsNotInContainer) {
3049 EXPECT_THAT(some_set, Not(Contains(4)));
3051 set<std::string> c_string_set;
3052 c_string_set.insert("hello");
3053 EXPECT_THAT(c_string_set, Not(Contains(std::string("goodbye"))));
3056 TEST_P(ContainsTestP, ExplainsMatchResultCorrectly) {
3057 const int a[2] = {1, 2};
3058 Matcher<const int(&)[2]> m = Contains(2);
3059 EXPECT_EQ("whose element #1 matches", Explain(m, a));
3062 EXPECT_EQ("", Explain(m, a));
3064 m = Contains(GreaterThan(0));
3065 EXPECT_EQ("whose element #0 matches, which is 1 more than 0", Explain(m, a));
3067 m = Contains(GreaterThan(10));
3068 EXPECT_EQ("", Explain(m, a));
3071 TEST(ContainsTest, DescribesItselfCorrectly) {
3072 Matcher<vector<int>> m = Contains(1);
3073 EXPECT_EQ("contains at least one element that is equal to 1", Describe(m));
3075 Matcher<vector<int>> m2 = Not(m);
3076 EXPECT_EQ("doesn't contain any element that is equal to 1", Describe(m2));
3079 TEST(ContainsTest, MapMatchesWhenElementIsInContainer) {
3080 map<std::string, int> my_map;
3081 const char* bar = "a string";
3083 EXPECT_THAT(my_map, Contains(pair<const char* const, int>(bar, 2)));
3085 map<std::string, int> another_map;
3086 another_map["fee"] = 1;
3087 another_map["fie"] = 2;
3088 another_map["foe"] = 3;
3089 another_map["fum"] = 4;
3090 EXPECT_THAT(another_map,
3091 Contains(pair<const std::string, int>(std::string("fee"), 1)));
3092 EXPECT_THAT(another_map, Contains(pair<const std::string, int>("fie", 2)));
3095 TEST(ContainsTest, MapDoesNotMatchWhenElementIsNotInContainer) {
3096 map<int, int> some_map;
3099 EXPECT_THAT(some_map, Not(Contains(pair<const int, int>(2, 23))));
3102 TEST(ContainsTest, ArrayMatchesWhenElementIsInContainer) {
3103 const char* string_array[] = {"fee", "fie", "foe", "fum"};
3104 EXPECT_THAT(string_array, Contains(Eq(std::string("fum"))));
3107 TEST(ContainsTest, ArrayDoesNotMatchWhenElementIsNotInContainer) {
3108 int int_array[] = {1, 2, 3, 4};
3109 EXPECT_THAT(int_array, Not(Contains(5)));
3112 TEST(ContainsTest, AcceptsMatcher) {
3113 const int a[] = {1, 2, 3};
3114 EXPECT_THAT(a, Contains(Gt(2)));
3115 EXPECT_THAT(a, Not(Contains(Gt(4))));
3118 TEST(ContainsTest, WorksForNativeArrayAsTuple) {
3119 const int a[] = {1, 2};
3120 const int* const pointer = a;
3121 EXPECT_THAT(std::make_tuple(pointer, 2), Contains(1));
3122 EXPECT_THAT(std::make_tuple(pointer, 2), Not(Contains(Gt(3))));
3125 TEST(ContainsTest, WorksForTwoDimensionalNativeArray) {
3126 int a[][3] = {{1, 2, 3}, {4, 5, 6}};
3127 EXPECT_THAT(a, Contains(ElementsAre(4, 5, 6)));
3128 EXPECT_THAT(a, Contains(Contains(5)));
3129 EXPECT_THAT(a, Not(Contains(ElementsAre(3, 4, 5))));
3130 EXPECT_THAT(a, Contains(Not(Contains(5))));
3134 } // namespace gmock_matchers_test
3135 } // namespace testing
3137 GTEST_DISABLE_MSC_WARNINGS_POP_() // 4244 4100