xref: /freebsd/contrib/googletest/googlemock/test/gmock-matchers-containers_test.cc (revision 5ca8c28cd8c725b81781201cfdb5f9969396f934)
1 // Copyright 2007, Google Inc.
2 // All rights reserved.
3 //
4 // Redistribution and use in source and binary forms, with or without
5 // modification, are permitted provided that the following conditions are
6 // met:
7 //
8 //     * Redistributions of source code must retain the above copyright
9 // notice, this list of conditions and the following disclaimer.
10 //     * Redistributions in binary form must reproduce the above
11 // copyright notice, this list of conditions and the following disclaimer
12 // in the documentation and/or other materials provided with the
13 // distribution.
14 //     * Neither the name of Google Inc. nor the names of its
15 // contributors may be used to endorse or promote products derived from
16 // this software without specific prior written permission.
17 //
18 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29 
30 // Google Mock - a framework for writing C++ mock classes.
31 //
32 // This file tests some commonly used argument matchers.
33 
34 #include <algorithm>
35 #include <array>
36 #include <deque>
37 #include <forward_list>
38 #include <iterator>
39 #include <list>
40 #include <memory>
41 #include <ostream>
42 #include <string>
43 #include <tuple>
44 #include <vector>
45 
46 #include "gtest/gtest.h"
47 
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)
51 
52 #include "test/gmock-matchers_test.h"
53 
54 namespace testing {
55 namespace gmock_matchers_test {
56 namespace {
57 
MakeUniquePtrs(const std::vector<int> & ints)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));
61   return pointers;
62 }
63 
OfType(const std::string & type_name)64 std::string OfType(const std::string& type_name) {
65 #if GTEST_HAS_RTTI
66   return IsReadableTypeName(type_name) ? " (of type " + type_name + ")" : "";
67 #else
68   return "";
69 #endif
70 }
71 
TEST(ContainsTest,WorksWithMoveOnly)72 TEST(ContainsTest, WorksWithMoveOnly) {
73   ContainerHelper helper;
74   EXPECT_CALL(helper, Call(Contains(Pointee(2))));
75   helper.Call(MakeUniquePtrs({1, 2}));
76 }
77 
78 INSTANTIATE_GTEST_MATCHER_TEST_P(ElementsAreTest);
79 
80 // Tests the variadic version of the ElementsAreMatcher
TEST(ElementsAreTest,HugeMatcher)81 TEST(ElementsAreTest, HugeMatcher) {
82   vector<int> test_vector{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12};
83 
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)));
87 }
88 
89 // Tests the variadic version of the UnorderedElementsAreMatcher
TEST(ElementsAreTest,HugeMatcherStr)90 TEST(ElementsAreTest, HugeMatcherStr) {
91   vector<std::string> test_vector{
92       "literal_string", "", "", "", "", "", "", "", "", "", "", ""};
93 
94   EXPECT_THAT(test_vector, UnorderedElementsAre("literal_string", _, _, _, _, _,
95                                                 _, _, _, _, _, _));
96 }
97 
98 // Tests the variadic version of the UnorderedElementsAreMatcher
TEST(ElementsAreTest,HugeMatcherUnordered)99 TEST(ElementsAreTest, HugeMatcherUnordered) {
100   vector<int> test_vector{2, 1, 8, 5, 4, 6, 7, 3, 9, 12, 11, 10};
101 
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)));
105 }
106 
107 // Tests that ASSERT_THAT() and EXPECT_THAT() work when the value
108 // matches the matcher.
TEST(MatcherAssertionTest,WorksWhenMatcherIsSatisfied)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"));
114 }
115 
116 // Tests that ASSERT_THAT() and EXPECT_THAT() work when the value
117 // doesn't match the matcher.
TEST(MatcherAssertionTest,WorksWhenMatcherIsNotSatisfied)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
122   n = 5;
123 
124   EXPECT_FATAL_FAILURE(ASSERT_THAT(n, Gt(10)),
125                        "Value of: n\n"
126                        "Expected: is > 10\n"
127                        "  Actual: 5" +
128                            OfType("unsigned short"));
129   n = 0;
130   EXPECT_NONFATAL_FAILURE(EXPECT_THAT(n, AllOf(Le(7), Ge(5))),
131                           "Value of: n\n"
132                           "Expected: (is <= 7) and (is >= 5)\n"
133                           "  Actual: 0" +
134                               OfType("unsigned short"));
135 }
136 
137 // Tests that ASSERT_THAT() and EXPECT_THAT() work when the argument
138 // has a reference type.
TEST(MatcherAssertionTest,WorksForByRefArguments)139 TEST(MatcherAssertionTest, WorksForByRefArguments) {
140   // We use a static variable here as EXPECT_FATAL_FAILURE() cannot
141   // reference auto variables.
142   static int n;
143   n = 0;
144   EXPECT_THAT(n, AllOf(Le(7), Ref(n)));
145   EXPECT_FATAL_FAILURE(ASSERT_THAT(n, Not(Ref(n))),
146                        "Value of: n\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 @");
151 }
152 
153 // Tests that ASSERT_THAT() and EXPECT_THAT() work when the matcher is
154 // monomorphic.
TEST(MatcherAssertionTest,WorksForMonomorphicMatcher)155 TEST(MatcherAssertionTest, WorksForMonomorphicMatcher) {
156   Matcher<const char*> starts_with_he = StartsWith("he");
157   ASSERT_THAT("hello", starts_with_he);
158 
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),
163                           "Value of: bad\n"
164                           "Expected: ends with \"ok\"\n"
165                           "  Actual: \"bad\"");
166   Matcher<int> is_greater_than_5 = Gt(5);
167   EXPECT_NONFATAL_FAILURE(EXPECT_THAT(5, is_greater_than_5),
168                           "Value of: 5\n"
169                           "Expected: is > 5\n"
170                           "  Actual: 5" +
171                               OfType("int"));
172 }
173 
TEST(PointeeTest,RawPointer)174 TEST(PointeeTest, RawPointer) {
175   const Matcher<int*> m = Pointee(Ge(0));
176 
177   int n = 1;
178   EXPECT_TRUE(m.Matches(&n));
179   n = -1;
180   EXPECT_FALSE(m.Matches(&n));
181   EXPECT_FALSE(m.Matches(nullptr));
182 }
183 
TEST(PointeeTest,RawPointerToConst)184 TEST(PointeeTest, RawPointerToConst) {
185   const Matcher<const double*> m = Pointee(Ge(0));
186 
187   double x = 1;
188   EXPECT_TRUE(m.Matches(&x));
189   x = -1;
190   EXPECT_FALSE(m.Matches(&x));
191   EXPECT_FALSE(m.Matches(nullptr));
192 }
193 
TEST(PointeeTest,ReferenceToConstRawPointer)194 TEST(PointeeTest, ReferenceToConstRawPointer) {
195   const Matcher<int* const&> m = Pointee(Ge(0));
196 
197   int n = 1;
198   EXPECT_TRUE(m.Matches(&n));
199   n = -1;
200   EXPECT_FALSE(m.Matches(&n));
201   EXPECT_FALSE(m.Matches(nullptr));
202 }
203 
TEST(PointeeTest,ReferenceToNonConstRawPointer)204 TEST(PointeeTest, ReferenceToNonConstRawPointer) {
205   const Matcher<double*&> m = Pointee(Ge(0));
206 
207   double x = 1.0;
208   double* p = &x;
209   EXPECT_TRUE(m.Matches(p));
210   x = -1;
211   EXPECT_FALSE(m.Matches(p));
212   p = nullptr;
213   EXPECT_FALSE(m.Matches(p));
214 }
215 
TEST(PointeeTest,SmartPointer)216 TEST(PointeeTest, SmartPointer) {
217   const Matcher<std::unique_ptr<int>> m = Pointee(Ge(0));
218 
219   std::unique_ptr<int> n(new int(1));
220   EXPECT_TRUE(m.Matches(n));
221 }
222 
TEST(PointeeTest,SmartPointerToConst)223 TEST(PointeeTest, SmartPointerToConst) {
224   const Matcher<std::unique_ptr<const int>> m = Pointee(Ge(0));
225 
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
228   // matcher.
229   std::unique_ptr<const int> n(new int(1));
230   EXPECT_TRUE(m.Matches(n));
231 }
232 
TEST(PointerTest,RawPointer)233 TEST(PointerTest, RawPointer) {
234   int n = 1;
235   const Matcher<int*> m = Pointer(Eq(&n));
236 
237   EXPECT_TRUE(m.Matches(&n));
238 
239   int* p = nullptr;
240   EXPECT_FALSE(m.Matches(p));
241   EXPECT_FALSE(m.Matches(nullptr));
242 }
243 
TEST(PointerTest,RawPointerToConst)244 TEST(PointerTest, RawPointerToConst) {
245   int n = 1;
246   const Matcher<const int*> m = Pointer(Eq(&n));
247 
248   EXPECT_TRUE(m.Matches(&n));
249 
250   int* p = nullptr;
251   EXPECT_FALSE(m.Matches(p));
252   EXPECT_FALSE(m.Matches(nullptr));
253 }
254 
TEST(PointerTest,SmartPointer)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));
259 
260   EXPECT_TRUE(m.Matches(n));
261 }
262 
TEST(PointerTest,SmartPointerToConst)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));
267 
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
270   // matcher.
271   std::unique_ptr<const int> p(new int(10));
272   EXPECT_FALSE(m.Matches(p));
273 }
274 
275 // Minimal const-propagating pointer.
276 template <typename T>
277 class ConstPropagatingPtr {
278  public:
279   typedef T element_type;
280 
ConstPropagatingPtr()281   ConstPropagatingPtr() : val_() {}
ConstPropagatingPtr(T * t)282   explicit ConstPropagatingPtr(T* t) : val_(t) {}
ConstPropagatingPtr(const ConstPropagatingPtr & other)283   ConstPropagatingPtr(const ConstPropagatingPtr& other) : val_(other.val_) {}
284 
get()285   T* get() { return val_; }
operator *()286   T& operator*() { return *val_; }
287   // Most smart pointers return non-const T* and T& from the next methods.
get() const288   const T* get() const { return val_; }
operator *() const289   const T& operator*() const { return *val_; }
290 
291  private:
292   T* val_;
293 };
294 
295 INSTANTIATE_GTEST_MATCHER_TEST_P(PointeeTest);
296 
TEST(PointeeTest,WorksWithConstPropagatingPointers)297 TEST(PointeeTest, WorksWithConstPropagatingPointers) {
298   const Matcher<ConstPropagatingPtr<int>> m = Pointee(Lt(5));
299   int three = 3;
300   const ConstPropagatingPtr<int> co(&three);
301   ConstPropagatingPtr<int> o(&three);
302   EXPECT_TRUE(m.Matches(o));
303   EXPECT_TRUE(m.Matches(co));
304   *o = 6;
305   EXPECT_FALSE(m.Matches(o));
306   EXPECT_FALSE(m.Matches(ConstPropagatingPtr<int>()));
307 }
308 
TEST(PointeeTest,NeverMatchesNull)309 TEST(PointeeTest, NeverMatchesNull) {
310   const Matcher<const char*> m = Pointee(_);
311   EXPECT_FALSE(m.Matches(nullptr));
312 }
313 
314 // Tests that we can write Pointee(value) instead of Pointee(Eq(value)).
TEST(PointeeTest,MatchesAgainstAValue)315 TEST(PointeeTest, MatchesAgainstAValue) {
316   const Matcher<int*> m = Pointee(5);
317 
318   int n = 5;
319   EXPECT_TRUE(m.Matches(&n));
320   n = -1;
321   EXPECT_FALSE(m.Matches(&n));
322   EXPECT_FALSE(m.Matches(nullptr));
323 }
324 
TEST(PointeeTest,CanDescribeSelf)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));
329 }
330 
TEST_P(PointeeTestP,CanExplainMatchResult)331 TEST_P(PointeeTestP, CanExplainMatchResult) {
332   const Matcher<const std::string*> m = Pointee(StartsWith("Hi"));
333 
334   EXPECT_EQ("", Explain(m, static_cast<const std::string*>(nullptr)));
335 
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",
339             Explain(m2, &n));
340 }
341 
TEST(PointeeTest,AlwaysExplainsPointee)342 TEST(PointeeTest, AlwaysExplainsPointee) {
343   const Matcher<int*> m = Pointee(0);
344   int n = 42;
345   EXPECT_EQ("which points to 42" + OfType("int"), Explain(m, &n));
346 }
347 
348 // An uncopyable class.
349 class Uncopyable {
350  public:
Uncopyable()351   Uncopyable() : value_(-1) {}
Uncopyable(int a_value)352   explicit Uncopyable(int a_value) : value_(a_value) {}
353 
value() const354   int value() const { return value_; }
set_value(int i)355   void set_value(int i) { value_ = i; }
356 
357  private:
358   int value_;
359   Uncopyable(const Uncopyable&) = delete;
360   Uncopyable& operator=(const Uncopyable&) = delete;
361 };
362 
363 // Returns true if and only if x.value() is positive.
ValueIsPositive(const Uncopyable & x)364 bool ValueIsPositive(const Uncopyable& x) { return x.value() > 0; }
365 
366 MATCHER_P(UncopyableIs, inner_matcher, "") {
367   return ExplainMatchResult(inner_matcher, arg.value(), result_listener);
368 }
369 
370 // A user-defined struct for testing Field().
371 struct AStruct {
AStructtesting::gmock_matchers_test::__anon540e1b3d0111::AStruct372   AStruct() : x(0), y(1.0), z(5), p(nullptr) {}
AStructtesting::gmock_matchers_test::__anon540e1b3d0111::AStruct373   AStruct(const AStruct& rhs)
374       : x(rhs.x), y(rhs.y), z(rhs.z.value()), p(rhs.p) {}
375 
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.
380 };
381 
382 // A derived struct for testing Field().
383 struct DerivedStruct : public AStruct {
384   char ch;
385 };
386 
387 INSTANTIATE_GTEST_MATCHER_TEST_P(FieldTest);
388 
389 // Tests that Field(&Foo::field, ...) works when field is non-const.
TEST(FieldTest,WorksForNonConstField)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));
393 
394   AStruct a;
395   EXPECT_TRUE(m.Matches(a));
396   EXPECT_TRUE(m_with_name.Matches(a));
397   a.x = -1;
398   EXPECT_FALSE(m.Matches(a));
399   EXPECT_FALSE(m_with_name.Matches(a));
400 }
401 
402 // Tests that Field(&Foo::field, ...) works when field is const.
TEST(FieldTest,WorksForConstField)403 TEST(FieldTest, WorksForConstField) {
404   AStruct a;
405 
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));
414 }
415 
416 // Tests that Field(&Foo::field, ...) works when field is not copyable.
TEST(FieldTest,WorksForUncopyableField)417 TEST(FieldTest, WorksForUncopyableField) {
418   AStruct a;
419 
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));
424 }
425 
426 // Tests that Field(&Foo::field, ...) works when field is a pointer.
TEST(FieldTest,WorksForPointerField)427 TEST(FieldTest, WorksForPointerField) {
428   // Matching against NULL.
429   Matcher<AStruct> m = Field(&AStruct::p, static_cast<const char*>(nullptr));
430   AStruct a;
431   EXPECT_TRUE(m.Matches(a));
432   a.p = "hi";
433   EXPECT_FALSE(m.Matches(a));
434 
435   // Matching a pointer that is not NULL.
436   m = Field(&AStruct::p, StartsWith("hi"));
437   a.p = "hill";
438   EXPECT_TRUE(m.Matches(a));
439   a.p = "hole";
440   EXPECT_FALSE(m.Matches(a));
441 }
442 
443 // Tests that Field() works when the object is passed by reference.
TEST(FieldTest,WorksForByRefArgument)444 TEST(FieldTest, WorksForByRefArgument) {
445   Matcher<const AStruct&> m = Field(&AStruct::x, Ge(0));
446 
447   AStruct a;
448   EXPECT_TRUE(m.Matches(a));
449   a.x = -1;
450   EXPECT_FALSE(m.Matches(a));
451 }
452 
453 // Tests that Field(&Foo::field, ...) works when the argument's type
454 // is a sub-type of Foo.
TEST(FieldTest,WorksForArgumentOfSubType)455 TEST(FieldTest, WorksForArgumentOfSubType) {
456   // Note that the matcher expects DerivedStruct but we say AStruct
457   // inside Field().
458   Matcher<const DerivedStruct&> m = Field(&AStruct::x, Ge(0));
459 
460   DerivedStruct d;
461   EXPECT_TRUE(m.Matches(d));
462   d.x = -1;
463   EXPECT_FALSE(m.Matches(d));
464 }
465 
466 // Tests that Field(&Foo::field, m) works when field's type and m's
467 // argument type are compatible but not the same.
TEST(FieldTest,WorksForCompatibleMatcherType)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)));
471 
472   AStruct a;
473   EXPECT_TRUE(m.Matches(a));
474   a.x = -1;
475   EXPECT_FALSE(m.Matches(a));
476 }
477 
478 // Tests that Field() can describe itself.
TEST(FieldTest,CanDescribeSelf)479 TEST(FieldTest, CanDescribeSelf) {
480   Matcher<const AStruct&> m = Field(&AStruct::x, Ge(0));
481 
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));
484 }
485 
TEST(FieldTest,CanDescribeSelfWithFieldName)486 TEST(FieldTest, CanDescribeSelfWithFieldName) {
487   Matcher<const AStruct&> m = Field("field_name", &AStruct::x, Ge(0));
488 
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));
492 }
493 
494 // Tests that Field() can explain the match result.
TEST_P(FieldTestP,CanExplainMatchResult)495 TEST_P(FieldTestP, CanExplainMatchResult) {
496   Matcher<const AStruct&> m = Field(&AStruct::x, Ge(0));
497 
498   AStruct a;
499   a.x = 1;
500   EXPECT_EQ("whose given field is 1" + OfType("int"), Explain(m, a));
501 
502   m = Field(&AStruct::x, GreaterThan(0));
503   EXPECT_EQ(
504       "whose given field is 1" + OfType("int") + ", which is 1 more than 0",
505       Explain(m, a));
506 }
507 
TEST_P(FieldTestP,CanExplainMatchResultWithFieldName)508 TEST_P(FieldTestP, CanExplainMatchResultWithFieldName) {
509   Matcher<const AStruct&> m = Field("field_name", &AStruct::x, Ge(0));
510 
511   AStruct a;
512   a.x = 1;
513   EXPECT_EQ("whose field `field_name` is 1" + OfType("int"), Explain(m, a));
514 
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",
518             Explain(m, a));
519 }
520 
521 INSTANTIATE_GTEST_MATCHER_TEST_P(FieldForPointerTest);
522 
523 // Tests that Field() works when the argument is a pointer to const.
TEST(FieldForPointerTest,WorksForPointerToConst)524 TEST(FieldForPointerTest, WorksForPointerToConst) {
525   Matcher<const AStruct*> m = Field(&AStruct::x, Ge(0));
526 
527   AStruct a;
528   EXPECT_TRUE(m.Matches(&a));
529   a.x = -1;
530   EXPECT_FALSE(m.Matches(&a));
531 }
532 
533 // Tests that Field() works when the argument is a pointer to non-const.
TEST(FieldForPointerTest,WorksForPointerToNonConst)534 TEST(FieldForPointerTest, WorksForPointerToNonConst) {
535   Matcher<AStruct*> m = Field(&AStruct::x, Ge(0));
536 
537   AStruct a;
538   EXPECT_TRUE(m.Matches(&a));
539   a.x = -1;
540   EXPECT_FALSE(m.Matches(&a));
541 }
542 
543 // Tests that Field() works when the argument is a reference to a const pointer.
TEST(FieldForPointerTest,WorksForReferenceToConstPointer)544 TEST(FieldForPointerTest, WorksForReferenceToConstPointer) {
545   Matcher<AStruct* const&> m = Field(&AStruct::x, Ge(0));
546 
547   AStruct a;
548   EXPECT_TRUE(m.Matches(&a));
549   a.x = -1;
550   EXPECT_FALSE(m.Matches(&a));
551 }
552 
553 // Tests that Field() does not match the NULL pointer.
TEST(FieldForPointerTest,DoesNotMatchNull)554 TEST(FieldForPointerTest, DoesNotMatchNull) {
555   Matcher<const AStruct*> m = Field(&AStruct::x, _);
556   EXPECT_FALSE(m.Matches(nullptr));
557 }
558 
559 // Tests that Field(&Foo::field, ...) works when the argument's type
560 // is a sub-type of const Foo*.
TEST(FieldForPointerTest,WorksForArgumentOfSubType)561 TEST(FieldForPointerTest, WorksForArgumentOfSubType) {
562   // Note that the matcher expects DerivedStruct but we say AStruct
563   // inside Field().
564   Matcher<DerivedStruct*> m = Field(&AStruct::x, Ge(0));
565 
566   DerivedStruct d;
567   EXPECT_TRUE(m.Matches(&d));
568   d.x = -1;
569   EXPECT_FALSE(m.Matches(&d));
570 }
571 
572 // Tests that Field() can describe itself when used to match a pointer.
TEST(FieldForPointerTest,CanDescribeSelf)573 TEST(FieldForPointerTest, CanDescribeSelf) {
574   Matcher<const AStruct*> m = Field(&AStruct::x, Ge(0));
575 
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));
578 }
579 
TEST(FieldForPointerTest,CanDescribeSelfWithFieldName)580 TEST(FieldForPointerTest, CanDescribeSelfWithFieldName) {
581   Matcher<const AStruct*> m = Field("field_name", &AStruct::x, Ge(0));
582 
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));
586 }
587 
588 // Tests that Field() can explain the result of matching a pointer.
TEST_P(FieldForPointerTestP,CanExplainMatchResult)589 TEST_P(FieldForPointerTestP, CanExplainMatchResult) {
590   Matcher<const AStruct*> m = Field(&AStruct::x, Ge(0));
591 
592   AStruct a;
593   a.x = 1;
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"),
596             Explain(m, &a));
597 
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",
601             Explain(m, &a));
602 }
603 
TEST_P(FieldForPointerTestP,CanExplainMatchResultWithFieldName)604 TEST_P(FieldForPointerTestP, CanExplainMatchResultWithFieldName) {
605   Matcher<const AStruct*> m = Field("field_name", &AStruct::x, Ge(0));
606 
607   AStruct a;
608   a.x = 1;
609   EXPECT_EQ("", Explain(m, static_cast<const AStruct*>(nullptr)));
610   EXPECT_EQ(
611       "which points to an object whose field `field_name` is 1" + OfType("int"),
612       Explain(m, &a));
613 
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",
617             Explain(m, &a));
618 }
619 
620 // A user-defined class for testing Property().
621 class AClass {
622  public:
AClass()623   AClass() : n_(0) {}
624 
625   // A getter that returns a non-reference.
n() const626   int n() const { return n_; }
627 
set_n(int new_n)628   void set_n(int new_n) { n_ = new_n; }
629 
630   // A getter that returns a reference to const.
s() const631   const std::string& s() const { return s_; }
632 
s_ref() const633   const std::string& s_ref() const& { return s_; }
634 
set_s(const std::string & new_s)635   void set_s(const std::string& new_s) { s_ = new_s; }
636 
637   // A getter that returns a reference to non-const.
x() const638   double& x() const { return x_; }
639 
640  private:
641   int n_;
642   std::string s_;
643 
644   static double x_;
645 };
646 
647 double AClass::x_ = 0.0;
648 
649 // A derived class for testing Property().
650 class DerivedClass : public AClass {
651  public:
k() const652   int k() const { return k_; }
653 
654  private:
655   int k_;
656 };
657 
658 INSTANTIATE_GTEST_MATCHER_TEST_P(PropertyTest);
659 
660 // Tests that Property(&Foo::property, ...) works when property()
661 // returns a non-reference.
TEST(PropertyTest,WorksForNonReferenceProperty)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));
665 
666   AClass a;
667   a.set_n(1);
668   EXPECT_TRUE(m.Matches(a));
669   EXPECT_TRUE(m_with_name.Matches(a));
670 
671   a.set_n(-1);
672   EXPECT_FALSE(m.Matches(a));
673   EXPECT_FALSE(m_with_name.Matches(a));
674 }
675 
676 // Tests that Property(&Foo::property, ...) works when property()
677 // returns a reference to const.
TEST(PropertyTest,WorksForReferenceToConstProperty)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"));
682 
683   AClass a;
684   a.set_s("hill");
685   EXPECT_TRUE(m.Matches(a));
686   EXPECT_TRUE(m_with_name.Matches(a));
687 
688   a.set_s("hole");
689   EXPECT_FALSE(m.Matches(a));
690   EXPECT_FALSE(m_with_name.Matches(a));
691 }
692 
693 // Tests that Property(&Foo::property, ...) works when property() is
694 // ref-qualified.
TEST(PropertyTest,WorksForRefQualifiedProperty)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"));
699 
700   AClass a;
701   a.set_s("hill");
702   EXPECT_TRUE(m.Matches(a));
703   EXPECT_TRUE(m_with_name.Matches(a));
704 
705   a.set_s("hole");
706   EXPECT_FALSE(m.Matches(a));
707   EXPECT_FALSE(m_with_name.Matches(a));
708 }
709 
710 // Tests that Property(&Foo::property, ...) works when property()
711 // returns a reference to non-const.
TEST(PropertyTest,WorksForReferenceToNonConstProperty)712 TEST(PropertyTest, WorksForReferenceToNonConstProperty) {
713   double x = 0.0;
714   AClass a;
715 
716   Matcher<const AClass&> m = Property(&AClass::x, Ref(x));
717   EXPECT_FALSE(m.Matches(a));
718 
719   m = Property(&AClass::x, Not(Ref(x)));
720   EXPECT_TRUE(m.Matches(a));
721 }
722 
723 // Tests that Property(&Foo::property, ...) works when the argument is
724 // passed by value.
TEST(PropertyTest,WorksForByValueArgument)725 TEST(PropertyTest, WorksForByValueArgument) {
726   Matcher<AClass> m = Property(&AClass::s, StartsWith("hi"));
727 
728   AClass a;
729   a.set_s("hill");
730   EXPECT_TRUE(m.Matches(a));
731 
732   a.set_s("hole");
733   EXPECT_FALSE(m.Matches(a));
734 }
735 
736 // Tests that Property(&Foo::property, ...) works when the argument's
737 // type is a sub-type of Foo.
TEST(PropertyTest,WorksForArgumentOfSubType)738 TEST(PropertyTest, WorksForArgumentOfSubType) {
739   // The matcher expects a DerivedClass, but inside the Property() we
740   // say AClass.
741   Matcher<const DerivedClass&> m = Property(&AClass::n, Ge(0));
742 
743   DerivedClass d;
744   d.set_n(1);
745   EXPECT_TRUE(m.Matches(d));
746 
747   d.set_n(-1);
748   EXPECT_FALSE(m.Matches(d));
749 }
750 
751 // Tests that Property(&Foo::property, m) works when property()'s type
752 // and m's argument type are compatible but different.
TEST(PropertyTest,WorksForCompatibleMatcherType)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)));
756 
757   Matcher<const AClass&> m_with_name =
758       Property("n", &AClass::n, Matcher<signed char>(Ge(0)));
759 
760   AClass a;
761   EXPECT_TRUE(m.Matches(a));
762   EXPECT_TRUE(m_with_name.Matches(a));
763   a.set_n(-1);
764   EXPECT_FALSE(m.Matches(a));
765   EXPECT_FALSE(m_with_name.Matches(a));
766 }
767 
768 // Tests that Property() can describe itself.
TEST(PropertyTest,CanDescribeSelf)769 TEST(PropertyTest, CanDescribeSelf) {
770   Matcher<const AClass&> m = Property(&AClass::n, Ge(0));
771 
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));
775 }
776 
TEST(PropertyTest,CanDescribeSelfWithPropertyName)777 TEST(PropertyTest, CanDescribeSelfWithPropertyName) {
778   Matcher<const AClass&> m = Property("fancy_name", &AClass::n, Ge(0));
779 
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));
783 }
784 
785 // Tests that Property() can explain the match result.
TEST_P(PropertyTestP,CanExplainMatchResult)786 TEST_P(PropertyTestP, CanExplainMatchResult) {
787   Matcher<const AClass&> m = Property(&AClass::n, Ge(0));
788 
789   AClass a;
790   a.set_n(1);
791   EXPECT_EQ("whose given property is 1" + OfType("int"), Explain(m, a));
792 
793   m = Property(&AClass::n, GreaterThan(0));
794   EXPECT_EQ(
795       "whose given property is 1" + OfType("int") + ", which is 1 more than 0",
796       Explain(m, a));
797 }
798 
TEST_P(PropertyTestP,CanExplainMatchResultWithPropertyName)799 TEST_P(PropertyTestP, CanExplainMatchResultWithPropertyName) {
800   Matcher<const AClass&> m = Property("fancy_name", &AClass::n, Ge(0));
801 
802   AClass a;
803   a.set_n(1);
804   EXPECT_EQ("whose property `fancy_name` is 1" + OfType("int"), Explain(m, a));
805 
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",
809             Explain(m, a));
810 }
811 
812 INSTANTIATE_GTEST_MATCHER_TEST_P(PropertyForPointerTest);
813 
814 // Tests that Property() works when the argument is a pointer to const.
TEST(PropertyForPointerTest,WorksForPointerToConst)815 TEST(PropertyForPointerTest, WorksForPointerToConst) {
816   Matcher<const AClass*> m = Property(&AClass::n, Ge(0));
817 
818   AClass a;
819   a.set_n(1);
820   EXPECT_TRUE(m.Matches(&a));
821 
822   a.set_n(-1);
823   EXPECT_FALSE(m.Matches(&a));
824 }
825 
826 // Tests that Property() works when the argument is a pointer to non-const.
TEST(PropertyForPointerTest,WorksForPointerToNonConst)827 TEST(PropertyForPointerTest, WorksForPointerToNonConst) {
828   Matcher<AClass*> m = Property(&AClass::s, StartsWith("hi"));
829 
830   AClass a;
831   a.set_s("hill");
832   EXPECT_TRUE(m.Matches(&a));
833 
834   a.set_s("hole");
835   EXPECT_FALSE(m.Matches(&a));
836 }
837 
838 // Tests that Property() works when the argument is a reference to a
839 // const pointer.
TEST(PropertyForPointerTest,WorksForReferenceToConstPointer)840 TEST(PropertyForPointerTest, WorksForReferenceToConstPointer) {
841   Matcher<AClass* const&> m = Property(&AClass::s, StartsWith("hi"));
842 
843   AClass a;
844   a.set_s("hill");
845   EXPECT_TRUE(m.Matches(&a));
846 
847   a.set_s("hole");
848   EXPECT_FALSE(m.Matches(&a));
849 }
850 
851 // Tests that Property() does not match the NULL pointer.
TEST(PropertyForPointerTest,WorksForReferenceToNonConstProperty)852 TEST(PropertyForPointerTest, WorksForReferenceToNonConstProperty) {
853   Matcher<const AClass*> m = Property(&AClass::x, _);
854   EXPECT_FALSE(m.Matches(nullptr));
855 }
856 
857 // Tests that Property(&Foo::property, ...) works when the argument's
858 // type is a sub-type of const Foo*.
TEST(PropertyForPointerTest,WorksForArgumentOfSubType)859 TEST(PropertyForPointerTest, WorksForArgumentOfSubType) {
860   // The matcher expects a DerivedClass, but inside the Property() we
861   // say AClass.
862   Matcher<const DerivedClass*> m = Property(&AClass::n, Ge(0));
863 
864   DerivedClass d;
865   d.set_n(1);
866   EXPECT_TRUE(m.Matches(&d));
867 
868   d.set_n(-1);
869   EXPECT_FALSE(m.Matches(&d));
870 }
871 
872 // Tests that Property() can describe itself when used to match a pointer.
TEST(PropertyForPointerTest,CanDescribeSelf)873 TEST(PropertyForPointerTest, CanDescribeSelf) {
874   Matcher<const AClass*> m = Property(&AClass::n, Ge(0));
875 
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));
879 }
880 
TEST(PropertyForPointerTest,CanDescribeSelfWithPropertyDescription)881 TEST(PropertyForPointerTest, CanDescribeSelfWithPropertyDescription) {
882   Matcher<const AClass*> m = Property("fancy_name", &AClass::n, Ge(0));
883 
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));
887 }
888 
889 // Tests that Property() can explain the result of matching a pointer.
TEST_P(PropertyForPointerTestP,CanExplainMatchResult)890 TEST_P(PropertyForPointerTestP, CanExplainMatchResult) {
891   Matcher<const AClass*> m = Property(&AClass::n, Ge(0));
892 
893   AClass a;
894   a.set_n(1);
895   EXPECT_EQ("", Explain(m, static_cast<const AClass*>(nullptr)));
896   EXPECT_EQ(
897       "which points to an object whose given property is 1" + OfType("int"),
898       Explain(m, &a));
899 
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",
903             Explain(m, &a));
904 }
905 
TEST_P(PropertyForPointerTestP,CanExplainMatchResultWithPropertyName)906 TEST_P(PropertyForPointerTestP, CanExplainMatchResultWithPropertyName) {
907   Matcher<const AClass*> m = Property("fancy_name", &AClass::n, Ge(0));
908 
909   AClass a;
910   a.set_n(1);
911   EXPECT_EQ("", Explain(m, static_cast<const AClass*>(nullptr)));
912   EXPECT_EQ("which points to an object whose property `fancy_name` is 1" +
913                 OfType("int"),
914             Explain(m, &a));
915 
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",
919             Explain(m, &a));
920 }
921 
922 // Tests ResultOf.
923 
924 // Tests that ResultOf(f, ...) compiles and works as expected when f is a
925 // function pointer.
IntToStringFunction(int input)926 std::string IntToStringFunction(int input) {
927   return input == 1 ? "foo" : "bar";
928 }
929 
930 INSTANTIATE_GTEST_MATCHER_TEST_P(ResultOfTest);
931 
TEST(ResultOfTest,WorksForFunctionPointers)932 TEST(ResultOfTest, WorksForFunctionPointers) {
933   Matcher<int> matcher = ResultOf(&IntToStringFunction, Eq(std::string("foo")));
934 
935   EXPECT_TRUE(matcher.Matches(1));
936   EXPECT_FALSE(matcher.Matches(2));
937 }
938 
939 // Tests that ResultOf() can describe itself.
TEST(ResultOfTest,CanDescribeItself)940 TEST(ResultOfTest, CanDescribeItself) {
941   Matcher<int> matcher = ResultOf(&IntToStringFunction, StrEq("foo"));
942 
943   EXPECT_EQ(
944       "is mapped by the given callable to a value that "
945       "is equal to \"foo\"",
946       Describe(matcher));
947   EXPECT_EQ(
948       "is mapped by the given callable to a value that "
949       "isn't equal to \"foo\"",
950       DescribeNegation(matcher));
951 }
952 
953 // Tests that ResultOf() can describe itself when provided a result description.
TEST(ResultOfTest,CanDescribeItselfWithResultDescription)954 TEST(ResultOfTest, CanDescribeItselfWithResultDescription) {
955   Matcher<int> matcher =
956       ResultOf("string conversion", &IntToStringFunction, StrEq("foo"));
957 
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));
961 }
962 
963 // Tests that ResultOf() can explain the match result.
IntFunction(int input)964 int IntFunction(int input) { return input == 42 ? 80 : 90; }
965 
TEST_P(ResultOfTestP,CanExplainMatchResult)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));
970 
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));
975 }
976 
TEST_P(ResultOfTestP,CanExplainMatchResultWithResultDescription)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));
981 
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));
986 }
987 
988 // Tests that ResultOf(f, ...) compiles and works as expected when f(x)
989 // returns a non-reference.
TEST(ResultOfTest,WorksForNonReferenceResults)990 TEST(ResultOfTest, WorksForNonReferenceResults) {
991   Matcher<int> matcher = ResultOf(&IntFunction, Eq(80));
992 
993   EXPECT_TRUE(matcher.Matches(42));
994   EXPECT_FALSE(matcher.Matches(36));
995 }
996 
997 // Tests that ResultOf(f, ...) compiles and works as expected when f(x)
998 // returns a reference to non-const.
DoubleFunction(double & input)999 double& DoubleFunction(double& input) { return input; }  // NOLINT
1000 
RefUncopyableFunction(Uncopyable & obj)1001 Uncopyable& RefUncopyableFunction(Uncopyable& obj) {  // NOLINT
1002   return obj;
1003 }
1004 
TEST(ResultOfTest,WorksForReferenceToNonConstResults)1005 TEST(ResultOfTest, WorksForReferenceToNonConstResults) {
1006   double x = 3.14;
1007   double x2 = x;
1008   Matcher<double&> matcher = ResultOf(&DoubleFunction, Ref(x));
1009 
1010   EXPECT_TRUE(matcher.Matches(x));
1011   EXPECT_FALSE(matcher.Matches(x2));
1012 
1013   // Test that ResultOf works with uncopyable objects
1014   Uncopyable obj(0);
1015   Uncopyable obj2(0);
1016   Matcher<Uncopyable&> matcher2 = ResultOf(&RefUncopyableFunction, Ref(obj));
1017 
1018   EXPECT_TRUE(matcher2.Matches(obj));
1019   EXPECT_FALSE(matcher2.Matches(obj2));
1020 }
1021 
1022 // Tests that ResultOf(f, ...) compiles and works as expected when f(x)
1023 // returns a reference to const.
StringFunction(const std::string & input)1024 const std::string& StringFunction(const std::string& input) { return input; }
1025 
TEST(ResultOfTest,WorksForReferenceToConstResults)1026 TEST(ResultOfTest, WorksForReferenceToConstResults) {
1027   std::string s = "foo";
1028   std::string s2 = s;
1029   Matcher<const std::string&> matcher = ResultOf(&StringFunction, Ref(s));
1030 
1031   EXPECT_TRUE(matcher.Matches(s));
1032   EXPECT_FALSE(matcher.Matches(s2));
1033 }
1034 
1035 // Tests that ResultOf(f, m) works when f(x) and m's
1036 // argument types are compatible but different.
TEST(ResultOfTest,WorksForCompatibleMatcherTypes)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)));
1040 
1041   EXPECT_TRUE(matcher.Matches(36));
1042   EXPECT_FALSE(matcher.Matches(42));
1043 }
1044 
1045 // Tests that the program aborts when ResultOf is passed
1046 // a NULL function pointer.
TEST(ResultOfDeathTest,DiesOnNullFunctionPointers)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\\(\\)\\.");
1052 }
1053 
1054 // Tests that ResultOf(f, ...) compiles and works as expected when f is a
1055 // function reference.
TEST(ResultOfTest,WorksForFunctionReferences)1056 TEST(ResultOfTest, WorksForFunctionReferences) {
1057   Matcher<int> matcher = ResultOf(IntToStringFunction, StrEq("foo"));
1058   EXPECT_TRUE(matcher.Matches(1));
1059   EXPECT_FALSE(matcher.Matches(2));
1060 }
1061 
1062 // Tests that ResultOf(f, ...) compiles and works as expected when f is a
1063 // function object.
1064 struct Functor {
operator ()testing::gmock_matchers_test::__anon540e1b3d0111::Functor1065   std::string operator()(int input) const { return IntToStringFunction(input); }
1066 };
1067 
TEST(ResultOfTest,WorksForFunctors)1068 TEST(ResultOfTest, WorksForFunctors) {
1069   Matcher<int> matcher = ResultOf(Functor(), Eq(std::string("foo")));
1070 
1071   EXPECT_TRUE(matcher.Matches(1));
1072   EXPECT_FALSE(matcher.Matches(2));
1073 }
1074 
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;
operator ()testing::gmock_matchers_test::__anon540e1b3d0111::PolymorphicFunctor1080   int operator()(int n) { return n; }
operator ()testing::gmock_matchers_test::__anon540e1b3d0111::PolymorphicFunctor1081   int operator()(const char* s) { return static_cast<int>(strlen(s)); }
operator ()testing::gmock_matchers_test::__anon540e1b3d0111::PolymorphicFunctor1082   std::string operator()(int* p) { return p ? "good ptr" : "null"; }
1083 };
1084 
TEST(ResultOfTest,WorksForPolymorphicFunctors)1085 TEST(ResultOfTest, WorksForPolymorphicFunctors) {
1086   Matcher<int> matcher_int = ResultOf(PolymorphicFunctor(), Ge(5));
1087 
1088   EXPECT_TRUE(matcher_int.Matches(10));
1089   EXPECT_FALSE(matcher_int.Matches(2));
1090 
1091   Matcher<const char*> matcher_string = ResultOf(PolymorphicFunctor(), Ge(5));
1092 
1093   EXPECT_TRUE(matcher_string.Matches("long string"));
1094   EXPECT_FALSE(matcher_string.Matches("shrt"));
1095 }
1096 
TEST(ResultOfTest,WorksForPolymorphicFunctorsIgnoringResultType)1097 TEST(ResultOfTest, WorksForPolymorphicFunctorsIgnoringResultType) {
1098   Matcher<int*> matcher = ResultOf(PolymorphicFunctor(), "good ptr");
1099 
1100   int n = 0;
1101   EXPECT_TRUE(matcher.Matches(&n));
1102   EXPECT_FALSE(matcher.Matches(nullptr));
1103 }
1104 
TEST(ResultOfTest,WorksForLambdas)1105 TEST(ResultOfTest, WorksForLambdas) {
1106   Matcher<int> matcher = ResultOf(
1107       [](int str_len) {
1108         return std::string(static_cast<size_t>(str_len), 'x');
1109       },
1110       "xxx");
1111   EXPECT_TRUE(matcher.Matches(3));
1112   EXPECT_FALSE(matcher.Matches(1));
1113 }
1114 
TEST(ResultOfTest,WorksForNonCopyableArguments)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');
1119       },
1120       "xxx");
1121   EXPECT_TRUE(matcher.Matches(std::unique_ptr<int>(new int(3))));
1122   EXPECT_FALSE(matcher.Matches(std::unique_ptr<int>(new int(1))));
1123 }
1124 
ReferencingFunction(const int & n)1125 const int* ReferencingFunction(const int& n) { return &n; }
1126 
1127 struct ReferencingFunctor {
1128   typedef const int* result_type;
operator ()testing::gmock_matchers_test::__anon540e1b3d0111::ReferencingFunctor1129   result_type operator()(const int& n) { return &n; }
1130 };
1131 
TEST(ResultOfTest,WorksForReferencingCallables)1132 TEST(ResultOfTest, WorksForReferencingCallables) {
1133   const int n = 1;
1134   const int n2 = 1;
1135   Matcher<const int&> matcher2 = ResultOf(ReferencingFunction, Eq(&n));
1136   EXPECT_TRUE(matcher2.Matches(n));
1137   EXPECT_FALSE(matcher2.Matches(n2));
1138 
1139   Matcher<const int&> matcher3 = ResultOf(ReferencingFunctor(), Eq(&n));
1140   EXPECT_TRUE(matcher3.Matches(n));
1141   EXPECT_FALSE(matcher3.Matches(n2));
1142 }
1143 
TEST(SizeIsTest,ImplementsSizeIs)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));
1154 }
1155 
TEST(SizeIsTest,WorksWithMap)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));
1166 }
1167 
TEST(SizeIsTest,WorksWithReferences)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);
1174 }
1175 
TEST(SizeIsTest,WorksWithMoveOnly)1176 TEST(SizeIsTest, WorksWithMoveOnly) {
1177   ContainerHelper helper;
1178   EXPECT_CALL(helper, Call(SizeIs(3)));
1179   helper.Call(MakeUniquePtrs({1, 2, 3}));
1180 }
1181 
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 {
sizetesting::gmock_matchers_test::__anon540e1b3d0111::MinimalistCustomType1185   int size() const { return 1; }
1186 };
TEST(SizeIsTest,WorksWithMinimalistCustomType)1187 TEST(SizeIsTest, WorksWithMinimalistCustomType) {
1188   MinimalistCustomType container;
1189   EXPECT_THAT(container, SizeIs(1));
1190   EXPECT_THAT(container, Not(SizeIs(0)));
1191 }
1192 
TEST(SizeIsTest,CanDescribeSelf)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));
1197 }
1198 
TEST(SizeIsTest,ExplainsResult)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));
1215 }
1216 
TEST(WhenSortedByTest,WorksForEmptyContainer)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))));
1221 }
1222 
TEST(WhenSortedByTest,WorksForNonEmptyContainer)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))));
1233 }
1234 
TEST(WhenSortedByTest,WorksForNonVectorContainer)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"))));
1244 }
1245 
TEST(WhenSortedByTest,WorksForNativeArray)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))));
1253 }
1254 
TEST(WhenSortedByTest,CanDescribeSelf)1255 TEST(WhenSortedByTest, CanDescribeSelf) {
1256   const Matcher<vector<int>> m = WhenSortedBy(less<int>(), ElementsAre(1, 2));
1257   EXPECT_EQ(
1258       "(when sorted) has 2 elements where\n"
1259       "element #0 is equal to 1,\n"
1260       "element #1 is equal to 2",
1261       Describe(m));
1262   EXPECT_EQ(
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));
1267 }
1268 
TEST(WhenSortedByTest,ExplainsMatchResult)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));
1275 }
1276 
1277 // WhenSorted() is a simple wrapper on WhenSortedBy().  Hence we don't
1278 // need to test it as exhaustively as we test the latter.
1279 
TEST(WhenSortedTest,WorksForEmptyContainer)1280 TEST(WhenSortedTest, WorksForEmptyContainer) {
1281   const vector<int> numbers;
1282   EXPECT_THAT(numbers, WhenSorted(ElementsAre()));
1283   EXPECT_THAT(numbers, Not(WhenSorted(ElementsAre(1))));
1284 }
1285 
TEST(WhenSortedTest,WorksForNonEmptyContainer)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"))));
1294 }
1295 
TEST(WhenSortedTest,WorksForMapTypes)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),
1303                                      Pair("the", 1))));
1304   EXPECT_THAT(word_counts,
1305               Not(WhenSorted(ElementsAre(Pair("and", 1), Pair("the", 1),
1306                                          Pair("buffalo", 2)))));
1307 }
1308 
TEST(WhenSortedTest,WorksForMultiMapTypes)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));
1317   EXPECT_THAT(ifib,
1318               WhenSorted(ElementsAre(Pair(1, 1), Pair(1, 2), Pair(2, 3),
1319                                      Pair(3, 4), Pair(5, 5), Pair(8, 6))));
1320   EXPECT_THAT(ifib,
1321               Not(WhenSorted(ElementsAre(Pair(8, 6), Pair(2, 3), Pair(1, 1),
1322                                          Pair(3, 4), Pair(1, 2), Pair(5, 5)))));
1323 }
1324 
TEST(WhenSortedTest,WorksForPolymorphicMatcher)1325 TEST(WhenSortedTest, WorksForPolymorphicMatcher) {
1326   std::deque<int> d;
1327   d.push_back(2);
1328   d.push_back(1);
1329   EXPECT_THAT(d, WhenSorted(ElementsAre(1, 2)));
1330   EXPECT_THAT(d, Not(WhenSorted(ElementsAre(2, 1))));
1331 }
1332 
TEST(WhenSortedTest,WorksForVectorConstRefMatcher)1333 TEST(WhenSortedTest, WorksForVectorConstRefMatcher) {
1334   std::deque<int> d;
1335   d.push_back(2);
1336   d.push_back(1);
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)));
1341 }
1342 
1343 // Deliberately bare pseudo-container.
1344 // Offers only begin() and end() accessors, yielding InputIterator.
1345 template <typename T>
1346 class Streamlike {
1347  private:
1348   class ConstIter;
1349 
1350  public:
1351   typedef ConstIter const_iterator;
1352   typedef T value_type;
1353 
1354   template <typename InIter>
Streamlike(InIter first,InIter last)1355   Streamlike(InIter first, InIter last) : remainder_(first, last) {}
1356 
begin() const1357   const_iterator begin() const {
1358     return const_iterator(this, remainder_.begin());
1359   }
end() const1360   const_iterator end() const { return const_iterator(this, remainder_.end()); }
1361 
1362  private:
1363   class ConstIter {
1364    public:
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&;
1370 
ConstIter(const Streamlike * s,typename std::list<value_type>::iterator pos)1371     ConstIter(const Streamlike* s, typename std::list<value_type>::iterator pos)
1372         : s_(s), pos_(pos) {}
1373 
operator *() const1374     const value_type& operator*() const { return *pos_; }
operator ->() const1375     const value_type* operator->() const { return &*pos_; }
operator ++()1376     ConstIter& operator++() {
1377       s_->remainder_.erase(pos_++);
1378       return *this;
1379     }
1380 
1381     // *iter++ is required to work (see std::istreambuf_iterator).
1382     // (void)iter++ is also required to work.
1383     class PostIncrProxy {
1384      public:
PostIncrProxy(const value_type & value)1385       explicit PostIncrProxy(const value_type& value) : value_(value) {}
operator *() const1386       value_type operator*() const { return value_; }
1387 
1388      private:
1389       value_type value_;
1390     };
operator ++(int)1391     PostIncrProxy operator++(int) {
1392       PostIncrProxy proxy(**this);
1393       ++(*this);
1394       return proxy;
1395     }
1396 
operator ==(const ConstIter & a,const ConstIter & b)1397     friend bool operator==(const ConstIter& a, const ConstIter& b) {
1398       return a.s_ == b.s_ && a.pos_ == b.pos_;
1399     }
operator !=(const ConstIter & a,const ConstIter & b)1400     friend bool operator!=(const ConstIter& a, const ConstIter& b) {
1401       return !(a == b);
1402     }
1403 
1404    private:
1405     const Streamlike* s_;
1406     typename std::list<value_type>::iterator pos_;
1407   };
1408 
operator <<(std::ostream & os,const Streamlike & s)1409   friend std::ostream& operator<<(std::ostream& os, const Streamlike& s) {
1410     os << "[";
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) {
1414       os << sep << *it;
1415       sep = ",";
1416     }
1417     os << "]";
1418     return os;
1419   }
1420 
1421   mutable std::list<value_type> remainder_;  // modified by iteration
1422 };
1423 
TEST(StreamlikeTest,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();
1428   const int* ip = a;
1429   while (it != s.end()) {
1430     SCOPED_TRACE(ip - a);
1431     EXPECT_EQ(*ip++, *it++);
1432   }
1433 }
1434 
1435 INSTANTIATE_GTEST_MATCHER_TEST_P(BeginEndDistanceIsTest);
1436 
TEST(BeginEndDistanceIsTest,WorksWithForwardList)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));
1447 }
1448 
TEST(BeginEndDistanceIsTest,WorksWithNonStdList)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));
1453 }
1454 
TEST(BeginEndDistanceIsTest,CanDescribeSelf)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));
1460 }
1461 
TEST(BeginEndDistanceIsTest,WorksWithMoveOnly)1462 TEST(BeginEndDistanceIsTest, WorksWithMoveOnly) {
1463   ContainerHelper helper;
1464   EXPECT_CALL(helper, Call(BeginEndDistanceIs(2)));
1465   helper.Call(MakeUniquePtrs({1, 2}));
1466 }
1467 
TEST_P(BeginEndDistanceIsTestP,ExplainsResult)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));
1480   EXPECT_EQ(
1481       "whose distance between begin() and end() 0 doesn't match, which is 1 "
1482       "less than 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));
1492   EXPECT_EQ(
1493       "whose distance between begin() and end() 2 matches, which is 1 more "
1494       "than 1",
1495       Explain(m4, container));
1496 }
1497 
TEST(WhenSortedTest,WorksForStreamlike)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))));
1505 }
1506 
TEST(WhenSortedTest,WorksForVectorConstRefMatcherOnStreamlike)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))));
1513 }
1514 
TEST(IsSupersetOfTest,WorksForNativeArray)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)));
1524 }
1525 
TEST(IsSupersetOfTest,WorksWithDuplicates)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));
1532 }
1533 
TEST(IsSupersetOfTest,WorksForEmpty)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)));
1540   expected.clear();
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)));
1550 }
1551 
TEST(IsSupersetOfTest,WorksForStreamlike)1552 TEST(IsSupersetOfTest, WorksForStreamlike) {
1553   const int a[5] = {1, 2, 3, 4, 5};
1554   Streamlike<int> s(std::begin(a), std::end(a));
1555 
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));
1561 
1562   expected.push_back(0);
1563   EXPECT_THAT(s, Not(IsSupersetOf(expected)));
1564 }
1565 
TEST(IsSupersetOfTest,TakesStlContainer)1566 TEST(IsSupersetOfTest, TakesStlContainer) {
1567   const int actual[] = {3, 1, 2};
1568 
1569   ::std::list<int> expected;
1570   expected.push_back(1);
1571   expected.push_back(3);
1572   EXPECT_THAT(actual, IsSupersetOf(expected));
1573 
1574   expected.push_back(4);
1575   EXPECT_THAT(actual, Not(IsSupersetOf(expected)));
1576 }
1577 
TEST(IsSupersetOfTest,Describe)1578 TEST(IsSupersetOfTest, Describe) {
1579   typedef std::vector<int> IntVec;
1580   IntVec expected;
1581   expected.push_back(111);
1582   expected.push_back(222);
1583   expected.push_back(333);
1584   EXPECT_THAT(
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"));
1590 }
1591 
TEST(IsSupersetOfTest,DescribeNegation)1592 TEST(IsSupersetOfTest, DescribeNegation) {
1593   typedef std::vector<int> IntVec;
1594   IntVec expected;
1595   expected.push_back(111);
1596   expected.push_back(222);
1597   expected.push_back(333);
1598   EXPECT_THAT(
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"));
1604 }
1605 
TEST(IsSupersetOfTest,MatchAndExplain)1606 TEST(IsSupersetOfTest, MatchAndExplain) {
1607   std::vector<int> v;
1608   v.push_back(2);
1609   v.push_back(3);
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))
1615       << listener.str();
1616   EXPECT_THAT(listener.str(),
1617               Eq("where the following matchers don't match any elements:\n"
1618                  "matcher #0: is equal to 1"));
1619 
1620   v.push_back(1);
1621   listener.Clear();
1622   ASSERT_TRUE(ExplainMatchResult(IsSupersetOf(expected), v, &listener))
1623       << listener.str();
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"));
1627 }
1628 
TEST(IsSupersetOfTest,WorksForRhsInitializerList)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})));
1633 }
1634 
TEST(IsSupersetOfTest,WorksWithMoveOnly)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}));
1641 }
1642 
TEST(IsSubsetOfTest,WorksForNativeArray)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)));
1652 }
1653 
TEST(IsSubsetOfTest,WorksWithDuplicates)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));
1660 }
1661 
TEST(IsSubsetOfTest,WorksForEmpty)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));
1668   expected.clear();
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));
1678 }
1679 
TEST(IsSubsetOfTest,WorksForStreamlike)1680 TEST(IsSubsetOfTest, WorksForStreamlike) {
1681   const int a[5] = {1, 2};
1682   Streamlike<int> s(std::begin(a), std::end(a));
1683 
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));
1690 }
1691 
TEST(IsSubsetOfTest,TakesStlContainer)1692 TEST(IsSubsetOfTest, TakesStlContainer) {
1693   const int actual[] = {3, 1, 2};
1694 
1695   ::std::list<int> expected;
1696   expected.push_back(1);
1697   expected.push_back(3);
1698   EXPECT_THAT(actual, Not(IsSubsetOf(expected)));
1699 
1700   expected.push_back(2);
1701   expected.push_back(4);
1702   EXPECT_THAT(actual, IsSubsetOf(expected));
1703 }
1704 
TEST(IsSubsetOfTest,Describe)1705 TEST(IsSubsetOfTest, Describe) {
1706   typedef std::vector<int> IntVec;
1707   IntVec expected;
1708   expected.push_back(111);
1709   expected.push_back(222);
1710   expected.push_back(333);
1711 
1712   EXPECT_THAT(
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"));
1718 }
1719 
TEST(IsSubsetOfTest,DescribeNegation)1720 TEST(IsSubsetOfTest, DescribeNegation) {
1721   typedef std::vector<int> IntVec;
1722   IntVec expected;
1723   expected.push_back(111);
1724   expected.push_back(222);
1725   expected.push_back(333);
1726   EXPECT_THAT(
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"));
1732 }
1733 
TEST(IsSubsetOfTest,MatchAndExplain)1734 TEST(IsSubsetOfTest, MatchAndExplain) {
1735   std::vector<int> v;
1736   v.push_back(2);
1737   v.push_back(3);
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))
1743       << listener.str();
1744   EXPECT_THAT(listener.str(),
1745               Eq("where the following elements don't match any matchers:\n"
1746                  "element #1: 3"));
1747 
1748   expected.push_back(3);
1749   listener.Clear();
1750   ASSERT_TRUE(ExplainMatchResult(IsSubsetOf(expected), v, &listener))
1751       << listener.str();
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"));
1755 }
1756 
TEST(IsSubsetOfTest,WorksForRhsInitializerList)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})));
1761 }
1762 
TEST(IsSubsetOfTest,WorksWithMoveOnly)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}));
1769 }
1770 
1771 // Tests using ElementsAre() and ElementsAreArray() with stream-like
1772 // "containers".
1773 
TEST(ElemensAreStreamTest,WorksForStreamlike)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)));
1779 }
1780 
TEST(ElemensAreArrayStreamTest,WorksForStreamlike)1781 TEST(ElemensAreArrayStreamTest, WorksForStreamlike) {
1782   const int a[5] = {1, 2, 3, 4, 5};
1783   Streamlike<int> s(std::begin(a), std::end(a));
1784 
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));
1792 
1793   expected[3] = 0;
1794   EXPECT_THAT(s, Not(ElementsAreArray(expected)));
1795 }
1796 
TEST(ElementsAreTest,WorksWithUncopyable)1797 TEST(ElementsAreTest, WorksWithUncopyable) {
1798   Uncopyable objs[2];
1799   objs[0].set_value(-3);
1800   objs[1].set_value(1);
1801   EXPECT_THAT(objs, ElementsAre(UncopyableIs(-3), Truly(ValueIsPositive)));
1802 }
1803 
TEST(ElementsAreTest,WorksWithMoveOnly)1804 TEST(ElementsAreTest, WorksWithMoveOnly) {
1805   ContainerHelper helper;
1806   EXPECT_CALL(helper, Call(ElementsAre(Pointee(1), Pointee(2))));
1807   helper.Call(MakeUniquePtrs({1, 2}));
1808 
1809   EXPECT_CALL(helper, Call(ElementsAreArray({Pointee(3), Pointee(4)})));
1810   helper.Call(MakeUniquePtrs({3, 4}));
1811 }
1812 
TEST(ElementsAreTest,TakesStlContainer)1813 TEST(ElementsAreTest, TakesStlContainer) {
1814   const int actual[] = {3, 1, 2};
1815 
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));
1821 
1822   expected.push_back(4);
1823   EXPECT_THAT(actual, Not(ElementsAreArray(expected)));
1824 }
1825 
1826 // Tests for UnorderedElementsAreArray()
1827 
TEST(UnorderedElementsAreArrayTest,SucceedsWhenExpected)1828 TEST(UnorderedElementsAreArrayTest, SucceedsWhenExpected) {
1829   const int a[] = {0, 1, 2, 3, 4};
1830   std::vector<int> s(std::begin(a), std::end(a));
1831   do {
1832     StringMatchResultListener listener;
1833     EXPECT_TRUE(ExplainMatchResult(UnorderedElementsAreArray(a), s, &listener))
1834         << listener.str();
1835   } while (std::next_permutation(s.begin(), s.end()));
1836 }
1837 
TEST(UnorderedElementsAreArrayTest,VectorBool)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,
1845                                  &listener))
1846       << listener.str();
1847 }
1848 
TEST(UnorderedElementsAreArrayTest,WorksForStreamlike)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));
1855 
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));
1863 
1864   expected.push_back(6);
1865   EXPECT_THAT(s, Not(UnorderedElementsAreArray(expected)));
1866 }
1867 
TEST(UnorderedElementsAreArrayTest,TakesStlContainer)1868 TEST(UnorderedElementsAreArrayTest, TakesStlContainer) {
1869   const int actual[] = {3, 1, 2};
1870 
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));
1876 
1877   expected.push_back(4);
1878   EXPECT_THAT(actual, Not(UnorderedElementsAreArray(expected)));
1879 }
1880 
TEST(UnorderedElementsAreArrayTest,TakesInitializerList)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})));
1885 }
1886 
TEST(UnorderedElementsAreArrayTest,TakesInitializerListOfCStrings)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"})));
1891 }
1892 
TEST(UnorderedElementsAreArrayTest,TakesInitializerListOfSameTypedMatchers)1893 TEST(UnorderedElementsAreArrayTest, TakesInitializerListOfSameTypedMatchers) {
1894   const int a[5] = {2, 1, 4, 5, 3};
1895   EXPECT_THAT(a,
1896               UnorderedElementsAreArray({Eq(1), Eq(2), Eq(3), Eq(4), Eq(5)}));
1897   EXPECT_THAT(
1898       a, Not(UnorderedElementsAreArray({Eq(1), Eq(2), Eq(3), Eq(4), Eq(6)})));
1899 }
1900 
TEST(UnorderedElementsAreArrayTest,TakesInitializerListOfDifferentTypedMatchers)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)})));
1911 }
1912 
TEST(UnorderedElementsAreArrayTest,WorksWithMoveOnly)1913 TEST(UnorderedElementsAreArrayTest, WorksWithMoveOnly) {
1914   ContainerHelper helper;
1915   EXPECT_CALL(helper,
1916               Call(UnorderedElementsAreArray({Pointee(1), Pointee(2)})));
1917   helper.Call(MakeUniquePtrs({2, 1}));
1918 }
1919 
1920 class UnorderedElementsAreTest : public testing::Test {
1921  protected:
1922   typedef std::vector<int> IntVec;
1923 };
1924 
TEST_F(UnorderedElementsAreTest,WorksWithUncopyable)1925 TEST_F(UnorderedElementsAreTest, WorksWithUncopyable) {
1926   Uncopyable objs[2];
1927   objs[0].set_value(-3);
1928   objs[1].set_value(1);
1929   EXPECT_THAT(objs,
1930               UnorderedElementsAre(Truly(ValueIsPositive), UncopyableIs(-3)));
1931 }
1932 
TEST_F(UnorderedElementsAreTest,SucceedsWhenExpected)1933 TEST_F(UnorderedElementsAreTest, SucceedsWhenExpected) {
1934   const int a[] = {1, 2, 3};
1935   std::vector<int> s(std::begin(a), std::end(a));
1936   do {
1937     StringMatchResultListener listener;
1938     EXPECT_TRUE(ExplainMatchResult(UnorderedElementsAre(1, 2, 3), s, &listener))
1939         << listener.str();
1940   } while (std::next_permutation(s.begin(), s.end()));
1941 }
1942 
TEST_F(UnorderedElementsAreTest,FailsWhenAnElementMatchesNoMatcher)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;
1947   mv.push_back(1);
1948   mv.push_back(2);
1949   mv.push_back(2);
1950   // The element with value '3' matches nothing: fail fast.
1951   StringMatchResultListener listener;
1952   EXPECT_FALSE(ExplainMatchResult(UnorderedElementsAreArray(mv), s, &listener))
1953       << listener.str();
1954 }
1955 
TEST_F(UnorderedElementsAreTest,WorksForStreamlike)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));
1962 
1963   EXPECT_THAT(s, UnorderedElementsAre(1, 2, 3, 4, 5));
1964   EXPECT_THAT(s, Not(UnorderedElementsAre(2, 2, 3, 4, 5)));
1965 }
1966 
TEST_F(UnorderedElementsAreTest,WorksWithMoveOnly)1967 TEST_F(UnorderedElementsAreTest, WorksWithMoveOnly) {
1968   ContainerHelper helper;
1969   EXPECT_CALL(helper, Call(UnorderedElementsAre(Pointee(1), Pointee(2))));
1970   helper.Call(MakeUniquePtrs({2, 1}));
1971 }
1972 
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)
TEST_F(UnorderedElementsAreTest,Performance)1979 TEST_F(UnorderedElementsAreTest, Performance) {
1980   std::vector<int> s;
1981   std::vector<Matcher<int>> mv;
1982   for (int i = 0; i < 100; ++i) {
1983     s.push_back(i);
1984     mv.push_back(_);
1985   }
1986   mv[50] = Eq(0);
1987   StringMatchResultListener listener;
1988   EXPECT_TRUE(ExplainMatchResult(UnorderedElementsAreArray(mv), s, &listener))
1989       << listener.str();
1990 }
1991 
1992 // Another variant of 'Performance' with similar expectations.
1993 // [ RUN      ] UnorderedElementsAreTest.PerformanceHalfStrict
1994 // [       OK ] UnorderedElementsAreTest.PerformanceHalfStrict (4 ms)
TEST_F(UnorderedElementsAreTest,PerformanceHalfStrict)1995 TEST_F(UnorderedElementsAreTest, PerformanceHalfStrict) {
1996   std::vector<int> s;
1997   std::vector<Matcher<int>> mv;
1998   for (int i = 0; i < 100; ++i) {
1999     s.push_back(i);
2000     if (i & 1) {
2001       mv.push_back(_);
2002     } else {
2003       mv.push_back(i);
2004     }
2005   }
2006   StringMatchResultListener listener;
2007   EXPECT_TRUE(ExplainMatchResult(UnorderedElementsAreArray(mv), s, &listener))
2008       << listener.str();
2009 }
2010 
TEST_F(UnorderedElementsAreTest,FailMessageCountWrong)2011 TEST_F(UnorderedElementsAreTest, FailMessageCountWrong) {
2012   std::vector<int> v;
2013   v.push_back(4);
2014   StringMatchResultListener listener;
2015   EXPECT_FALSE(ExplainMatchResult(UnorderedElementsAre(1, 2, 3), v, &listener))
2016       << listener.str();
2017   EXPECT_THAT(listener.str(),
2018               Eq("which has 1 element\n"
2019                  "where the following matchers don't match any elements:\n"
2020                  "matcher #0: is equal to 1,\n"
2021                  "matcher #1: is equal to 2,\n"
2022                  "matcher #2: is equal to 3\n"
2023                  "and where the following elements don't match any matchers:\n"
2024                  "element #0: 4"));
2025 }
2026 
TEST_F(UnorderedElementsAreTest,FailMessageCountWrongZero)2027 TEST_F(UnorderedElementsAreTest, FailMessageCountWrongZero) {
2028   std::vector<int> v;
2029   StringMatchResultListener listener;
2030   EXPECT_FALSE(ExplainMatchResult(UnorderedElementsAre(1, 2, 3), v, &listener))
2031       << listener.str();
2032   EXPECT_THAT(listener.str(),
2033               Eq("where the following matchers don't match any elements:\n"
2034                  "matcher #0: is equal to 1,\n"
2035                  "matcher #1: is equal to 2,\n"
2036                  "matcher #2: is equal to 3"));
2037 }
2038 
TEST_F(UnorderedElementsAreTest,FailMessageUnmatchedMatchers)2039 TEST_F(UnorderedElementsAreTest, FailMessageUnmatchedMatchers) {
2040   std::vector<int> v;
2041   v.push_back(1);
2042   v.push_back(1);
2043   StringMatchResultListener listener;
2044   EXPECT_FALSE(ExplainMatchResult(UnorderedElementsAre(1, 2), v, &listener))
2045       << listener.str();
2046   EXPECT_THAT(listener.str(),
2047               Eq("where the following matchers don't match any elements:\n"
2048                  "matcher #1: is equal to 2"));
2049 }
2050 
TEST_F(UnorderedElementsAreTest,FailMessageUnmatchedElements)2051 TEST_F(UnorderedElementsAreTest, FailMessageUnmatchedElements) {
2052   std::vector<int> v;
2053   v.push_back(1);
2054   v.push_back(2);
2055   StringMatchResultListener listener;
2056   EXPECT_FALSE(ExplainMatchResult(UnorderedElementsAre(1, 1), v, &listener))
2057       << listener.str();
2058   EXPECT_THAT(listener.str(),
2059               Eq("where the following elements don't match any matchers:\n"
2060                  "element #1: 2"));
2061 }
2062 
TEST_F(UnorderedElementsAreTest,FailMessageUnmatchedMatcherAndElement)2063 TEST_F(UnorderedElementsAreTest, FailMessageUnmatchedMatcherAndElement) {
2064   std::vector<int> v;
2065   v.push_back(2);
2066   v.push_back(3);
2067   StringMatchResultListener listener;
2068   EXPECT_FALSE(ExplainMatchResult(UnorderedElementsAre(1, 2), v, &listener))
2069       << listener.str();
2070   EXPECT_THAT(listener.str(),
2071               Eq("where"
2072                  " the following matchers don't match any elements:\n"
2073                  "matcher #0: is equal to 1\n"
2074                  "and"
2075                  " where"
2076                  " the following elements don't match any matchers:\n"
2077                  "element #1: 3"));
2078 }
2079 
2080 // Test helper for formatting element, matcher index pairs in expectations.
EMString(int element,int matcher)2081 static std::string EMString(int element, int matcher) {
2082   stringstream ss;
2083   ss << "(element #" << element << ", matcher #" << matcher << ")";
2084   return ss.str();
2085 }
2086 
TEST_F(UnorderedElementsAreTest,FailMessageImperfectMatchOnly)2087 TEST_F(UnorderedElementsAreTest, FailMessageImperfectMatchOnly) {
2088   // A situation where all elements and matchers have a match
2089   // associated with them, but the max matching is not perfect.
2090   std::vector<std::string> v;
2091   v.push_back("a");
2092   v.push_back("b");
2093   v.push_back("c");
2094   StringMatchResultListener listener;
2095   EXPECT_FALSE(ExplainMatchResult(
2096       UnorderedElementsAre("a", "a", AnyOf("b", "c")), v, &listener))
2097       << listener.str();
2098 
2099   std::string prefix =
2100       "where no permutation of the elements can satisfy all matchers, "
2101       "and the closest match is 2 of 3 matchers with the "
2102       "pairings:\n";
2103 
2104   // We have to be a bit loose here, because there are 4 valid max matches.
2105   EXPECT_THAT(
2106       listener.str(),
2107       AnyOf(
2108           prefix + "{\n  " + EMString(0, 0) + ",\n  " + EMString(1, 2) + "\n}",
2109           prefix + "{\n  " + EMString(0, 1) + ",\n  " + EMString(1, 2) + "\n}",
2110           prefix + "{\n  " + EMString(0, 0) + ",\n  " + EMString(2, 2) + "\n}",
2111           prefix + "{\n  " + EMString(0, 1) + ",\n  " + EMString(2, 2) +
2112               "\n}"));
2113 }
2114 
TEST_F(UnorderedElementsAreTest,Describe)2115 TEST_F(UnorderedElementsAreTest, Describe) {
2116   EXPECT_THAT(Describe<IntVec>(UnorderedElementsAre()), Eq("is empty"));
2117   EXPECT_THAT(Describe<IntVec>(UnorderedElementsAre(345)),
2118               Eq("has 1 element and that element is equal to 345"));
2119   EXPECT_THAT(Describe<IntVec>(UnorderedElementsAre(111, 222, 333)),
2120               Eq("has 3 elements and there exists some permutation "
2121                  "of elements such that:\n"
2122                  " - element #0 is equal to 111, and\n"
2123                  " - element #1 is equal to 222, and\n"
2124                  " - element #2 is equal to 333"));
2125 }
2126 
TEST_F(UnorderedElementsAreTest,DescribeNegation)2127 TEST_F(UnorderedElementsAreTest, DescribeNegation) {
2128   EXPECT_THAT(DescribeNegation<IntVec>(UnorderedElementsAre()),
2129               Eq("isn't empty"));
2130   EXPECT_THAT(
2131       DescribeNegation<IntVec>(UnorderedElementsAre(345)),
2132       Eq("doesn't have 1 element, or has 1 element that isn't equal to 345"));
2133   EXPECT_THAT(DescribeNegation<IntVec>(UnorderedElementsAre(123, 234, 345)),
2134               Eq("doesn't have 3 elements, or there exists no permutation "
2135                  "of elements such that:\n"
2136                  " - element #0 is equal to 123, and\n"
2137                  " - element #1 is equal to 234, and\n"
2138                  " - element #2 is equal to 345"));
2139 }
2140 
2141 // Tests Each().
2142 
2143 INSTANTIATE_GTEST_MATCHER_TEST_P(EachTest);
2144 
TEST_P(EachTestP,ExplainsMatchResultCorrectly)2145 TEST_P(EachTestP, ExplainsMatchResultCorrectly) {
2146   set<int> a;  // empty
2147 
2148   Matcher<set<int>> m = Each(2);
2149   EXPECT_EQ("", Explain(m, a));
2150 
2151   Matcher<const int(&)[1]> n = Each(1);  // NOLINT
2152 
2153   const int b[1] = {1};
2154   EXPECT_EQ("", Explain(n, b));
2155 
2156   n = Each(3);
2157   EXPECT_EQ("whose element #0 doesn't match", Explain(n, b));
2158 
2159   a.insert(1);
2160   a.insert(2);
2161   a.insert(3);
2162   m = Each(GreaterThan(0));
2163   EXPECT_EQ("", Explain(m, a));
2164 
2165   m = Each(GreaterThan(10));
2166   EXPECT_EQ("whose element #0 doesn't match, which is 9 less than 10",
2167             Explain(m, a));
2168 }
2169 
TEST(EachTest,DescribesItselfCorrectly)2170 TEST(EachTest, DescribesItselfCorrectly) {
2171   Matcher<vector<int>> m = Each(1);
2172   EXPECT_EQ("only contains elements that is equal to 1", Describe(m));
2173 
2174   Matcher<vector<int>> m2 = Not(m);
2175   EXPECT_EQ("contains some element that isn't equal to 1", Describe(m2));
2176 }
2177 
TEST(EachTest,MatchesVectorWhenAllElementsMatch)2178 TEST(EachTest, MatchesVectorWhenAllElementsMatch) {
2179   vector<int> some_vector;
2180   EXPECT_THAT(some_vector, Each(1));
2181   some_vector.push_back(3);
2182   EXPECT_THAT(some_vector, Not(Each(1)));
2183   EXPECT_THAT(some_vector, Each(3));
2184   some_vector.push_back(1);
2185   some_vector.push_back(2);
2186   EXPECT_THAT(some_vector, Not(Each(3)));
2187   EXPECT_THAT(some_vector, Each(Lt(3.5)));
2188 
2189   vector<std::string> another_vector;
2190   another_vector.push_back("fee");
2191   EXPECT_THAT(another_vector, Each(std::string("fee")));
2192   another_vector.push_back("fie");
2193   another_vector.push_back("foe");
2194   another_vector.push_back("fum");
2195   EXPECT_THAT(another_vector, Not(Each(std::string("fee"))));
2196 }
2197 
TEST(EachTest,MatchesMapWhenAllElementsMatch)2198 TEST(EachTest, MatchesMapWhenAllElementsMatch) {
2199   map<const char*, int> my_map;
2200   const char* bar = "a string";
2201   my_map[bar] = 2;
2202   EXPECT_THAT(my_map, Each(make_pair(bar, 2)));
2203 
2204   map<std::string, int> another_map;
2205   EXPECT_THAT(another_map, Each(make_pair(std::string("fee"), 1)));
2206   another_map["fee"] = 1;
2207   EXPECT_THAT(another_map, Each(make_pair(std::string("fee"), 1)));
2208   another_map["fie"] = 2;
2209   another_map["foe"] = 3;
2210   another_map["fum"] = 4;
2211   EXPECT_THAT(another_map, Not(Each(make_pair(std::string("fee"), 1))));
2212   EXPECT_THAT(another_map, Not(Each(make_pair(std::string("fum"), 1))));
2213   EXPECT_THAT(another_map, Each(Pair(_, Gt(0))));
2214 }
2215 
TEST(EachTest,AcceptsMatcher)2216 TEST(EachTest, AcceptsMatcher) {
2217   const int a[] = {1, 2, 3};
2218   EXPECT_THAT(a, Each(Gt(0)));
2219   EXPECT_THAT(a, Not(Each(Gt(1))));
2220 }
2221 
TEST(EachTest,WorksForNativeArrayAsTuple)2222 TEST(EachTest, WorksForNativeArrayAsTuple) {
2223   const int a[] = {1, 2};
2224   const int* const pointer = a;
2225   EXPECT_THAT(std::make_tuple(pointer, 2), Each(Gt(0)));
2226   EXPECT_THAT(std::make_tuple(pointer, 2), Not(Each(Gt(1))));
2227 }
2228 
TEST(EachTest,WorksWithMoveOnly)2229 TEST(EachTest, WorksWithMoveOnly) {
2230   ContainerHelper helper;
2231   EXPECT_CALL(helper, Call(Each(Pointee(Gt(0)))));
2232   helper.Call(MakeUniquePtrs({1, 2}));
2233 }
2234 
2235 // For testing Pointwise().
2236 class IsHalfOfMatcher {
2237  public:
2238   template <typename T1, typename T2>
MatchAndExplain(const std::tuple<T1,T2> & a_pair,MatchResultListener * listener) const2239   bool MatchAndExplain(const std::tuple<T1, T2>& a_pair,
2240                        MatchResultListener* listener) const {
2241     if (std::get<0>(a_pair) == std::get<1>(a_pair) / 2) {
2242       *listener << "where the second is " << std::get<1>(a_pair);
2243       return true;
2244     } else {
2245       *listener << "where the second/2 is " << std::get<1>(a_pair) / 2;
2246       return false;
2247     }
2248   }
2249 
DescribeTo(ostream * os) const2250   void DescribeTo(ostream* os) const {
2251     *os << "are a pair where the first is half of the second";
2252   }
2253 
DescribeNegationTo(ostream * os) const2254   void DescribeNegationTo(ostream* os) const {
2255     *os << "are a pair where the first isn't half of the second";
2256   }
2257 };
2258 
IsHalfOf()2259 PolymorphicMatcher<IsHalfOfMatcher> IsHalfOf() {
2260   return MakePolymorphicMatcher(IsHalfOfMatcher());
2261 }
2262 
TEST(PointwiseTest,DescribesSelf)2263 TEST(PointwiseTest, DescribesSelf) {
2264   vector<int> rhs;
2265   rhs.push_back(1);
2266   rhs.push_back(2);
2267   rhs.push_back(3);
2268   const Matcher<const vector<int>&> m = Pointwise(IsHalfOf(), rhs);
2269   EXPECT_EQ(
2270       "contains 3 values, where each value and its corresponding value "
2271       "in { 1, 2, 3 } are a pair where the first is half of the second",
2272       Describe(m));
2273   EXPECT_EQ(
2274       "doesn't contain exactly 3 values, or contains a value x at some "
2275       "index i where x and the i-th value of { 1, 2, 3 } are a pair "
2276       "where the first isn't half of the second",
2277       DescribeNegation(m));
2278 }
2279 
TEST(PointwiseTest,MakesCopyOfRhs)2280 TEST(PointwiseTest, MakesCopyOfRhs) {
2281   list<signed char> rhs;
2282   rhs.push_back(2);
2283   rhs.push_back(4);
2284 
2285   int lhs[] = {1, 2};
2286   const Matcher<const int(&)[2]> m = Pointwise(IsHalfOf(), rhs);
2287   EXPECT_THAT(lhs, m);
2288 
2289   // Changing rhs now shouldn't affect m, which made a copy of rhs.
2290   rhs.push_back(6);
2291   EXPECT_THAT(lhs, m);
2292 }
2293 
TEST(PointwiseTest,WorksForLhsNativeArray)2294 TEST(PointwiseTest, WorksForLhsNativeArray) {
2295   const int lhs[] = {1, 2, 3};
2296   vector<int> rhs;
2297   rhs.push_back(2);
2298   rhs.push_back(4);
2299   rhs.push_back(6);
2300   EXPECT_THAT(lhs, Pointwise(Lt(), rhs));
2301   EXPECT_THAT(lhs, Not(Pointwise(Gt(), rhs)));
2302 }
2303 
TEST(PointwiseTest,WorksForRhsNativeArray)2304 TEST(PointwiseTest, WorksForRhsNativeArray) {
2305   const int rhs[] = {1, 2, 3};
2306   vector<int> lhs;
2307   lhs.push_back(2);
2308   lhs.push_back(4);
2309   lhs.push_back(6);
2310   EXPECT_THAT(lhs, Pointwise(Gt(), rhs));
2311   EXPECT_THAT(lhs, Not(Pointwise(Lt(), rhs)));
2312 }
2313 
2314 // Test is effective only with sanitizers.
TEST(PointwiseTest,WorksForVectorOfBool)2315 TEST(PointwiseTest, WorksForVectorOfBool) {
2316   vector<bool> rhs(3, false);
2317   rhs[1] = true;
2318   vector<bool> lhs = rhs;
2319   EXPECT_THAT(lhs, Pointwise(Eq(), rhs));
2320   rhs[0] = true;
2321   EXPECT_THAT(lhs, Not(Pointwise(Eq(), rhs)));
2322 }
2323 
TEST(PointwiseTest,WorksForRhsInitializerList)2324 TEST(PointwiseTest, WorksForRhsInitializerList) {
2325   const vector<int> lhs{2, 4, 6};
2326   EXPECT_THAT(lhs, Pointwise(Gt(), {1, 2, 3}));
2327   EXPECT_THAT(lhs, Not(Pointwise(Lt(), {3, 3, 7})));
2328 }
2329 
TEST(PointwiseTest,RejectsWrongSize)2330 TEST(PointwiseTest, RejectsWrongSize) {
2331   const double lhs[2] = {1, 2};
2332   const int rhs[1] = {0};
2333   EXPECT_THAT(lhs, Not(Pointwise(Gt(), rhs)));
2334   EXPECT_EQ("which contains 2 values", Explain(Pointwise(Gt(), rhs), lhs));
2335 
2336   const int rhs2[3] = {0, 1, 2};
2337   EXPECT_THAT(lhs, Not(Pointwise(Gt(), rhs2)));
2338 }
2339 
TEST(PointwiseTest,RejectsWrongContent)2340 TEST(PointwiseTest, RejectsWrongContent) {
2341   const double lhs[3] = {1, 2, 3};
2342   const int rhs[3] = {2, 6, 4};
2343   EXPECT_THAT(lhs, Not(Pointwise(IsHalfOf(), rhs)));
2344   EXPECT_EQ(
2345       "where the value pair (2, 6) at index #1 don't match, "
2346       "where the second/2 is 3",
2347       Explain(Pointwise(IsHalfOf(), rhs), lhs));
2348 }
2349 
TEST(PointwiseTest,AcceptsCorrectContent)2350 TEST(PointwiseTest, AcceptsCorrectContent) {
2351   const double lhs[3] = {1, 2, 3};
2352   const int rhs[3] = {2, 4, 6};
2353   EXPECT_THAT(lhs, Pointwise(IsHalfOf(), rhs));
2354   EXPECT_EQ("", Explain(Pointwise(IsHalfOf(), rhs), lhs));
2355 }
2356 
TEST(PointwiseTest,AllowsMonomorphicInnerMatcher)2357 TEST(PointwiseTest, AllowsMonomorphicInnerMatcher) {
2358   const double lhs[3] = {1, 2, 3};
2359   const int rhs[3] = {2, 4, 6};
2360   const Matcher<std::tuple<const double&, const int&>> m1 = IsHalfOf();
2361   EXPECT_THAT(lhs, Pointwise(m1, rhs));
2362   EXPECT_EQ("", Explain(Pointwise(m1, rhs), lhs));
2363 
2364   // This type works as a std::tuple<const double&, const int&> can be
2365   // implicitly cast to std::tuple<double, int>.
2366   const Matcher<std::tuple<double, int>> m2 = IsHalfOf();
2367   EXPECT_THAT(lhs, Pointwise(m2, rhs));
2368   EXPECT_EQ("", Explain(Pointwise(m2, rhs), lhs));
2369 }
2370 
2371 MATCHER(PointeeEquals, "Points to an equal value") {
2372   return ExplainMatchResult(::testing::Pointee(::testing::get<1>(arg)),
2373                             ::testing::get<0>(arg), result_listener);
2374 }
2375 
TEST(PointwiseTest,WorksWithMoveOnly)2376 TEST(PointwiseTest, WorksWithMoveOnly) {
2377   ContainerHelper helper;
2378   EXPECT_CALL(helper, Call(Pointwise(PointeeEquals(), std::vector<int>{1, 2})));
2379   helper.Call(MakeUniquePtrs({1, 2}));
2380 }
2381 
TEST(UnorderedPointwiseTest,DescribesSelf)2382 TEST(UnorderedPointwiseTest, DescribesSelf) {
2383   vector<int> rhs;
2384   rhs.push_back(1);
2385   rhs.push_back(2);
2386   rhs.push_back(3);
2387   const Matcher<const vector<int>&> m = UnorderedPointwise(IsHalfOf(), rhs);
2388   EXPECT_EQ(
2389       "has 3 elements and there exists some permutation of elements such "
2390       "that:\n"
2391       " - element #0 and 1 are a pair where the first is half of the second, "
2392       "and\n"
2393       " - element #1 and 2 are a pair where the first is half of the second, "
2394       "and\n"
2395       " - element #2 and 3 are a pair where the first is half of the second",
2396       Describe(m));
2397   EXPECT_EQ(
2398       "doesn't have 3 elements, or there exists no permutation of elements "
2399       "such that:\n"
2400       " - element #0 and 1 are a pair where the first is half of the second, "
2401       "and\n"
2402       " - element #1 and 2 are a pair where the first is half of the second, "
2403       "and\n"
2404       " - element #2 and 3 are a pair where the first is half of the second",
2405       DescribeNegation(m));
2406 }
2407 
TEST(UnorderedPointwiseTest,MakesCopyOfRhs)2408 TEST(UnorderedPointwiseTest, MakesCopyOfRhs) {
2409   list<signed char> rhs;
2410   rhs.push_back(2);
2411   rhs.push_back(4);
2412 
2413   int lhs[] = {2, 1};
2414   const Matcher<const int(&)[2]> m = UnorderedPointwise(IsHalfOf(), rhs);
2415   EXPECT_THAT(lhs, m);
2416 
2417   // Changing rhs now shouldn't affect m, which made a copy of rhs.
2418   rhs.push_back(6);
2419   EXPECT_THAT(lhs, m);
2420 }
2421 
TEST(UnorderedPointwiseTest,WorksForLhsNativeArray)2422 TEST(UnorderedPointwiseTest, WorksForLhsNativeArray) {
2423   const int lhs[] = {1, 2, 3};
2424   vector<int> rhs;
2425   rhs.push_back(4);
2426   rhs.push_back(6);
2427   rhs.push_back(2);
2428   EXPECT_THAT(lhs, UnorderedPointwise(Lt(), rhs));
2429   EXPECT_THAT(lhs, Not(UnorderedPointwise(Gt(), rhs)));
2430 }
2431 
TEST(UnorderedPointwiseTest,WorksForRhsNativeArray)2432 TEST(UnorderedPointwiseTest, WorksForRhsNativeArray) {
2433   const int rhs[] = {1, 2, 3};
2434   vector<int> lhs;
2435   lhs.push_back(4);
2436   lhs.push_back(2);
2437   lhs.push_back(6);
2438   EXPECT_THAT(lhs, UnorderedPointwise(Gt(), rhs));
2439   EXPECT_THAT(lhs, Not(UnorderedPointwise(Lt(), rhs)));
2440 }
2441 
TEST(UnorderedPointwiseTest,WorksForRhsInitializerList)2442 TEST(UnorderedPointwiseTest, WorksForRhsInitializerList) {
2443   const vector<int> lhs{2, 4, 6};
2444   EXPECT_THAT(lhs, UnorderedPointwise(Gt(), {5, 1, 3}));
2445   EXPECT_THAT(lhs, Not(UnorderedPointwise(Lt(), {1, 1, 7})));
2446 }
2447 
TEST(UnorderedPointwiseTest,RejectsWrongSize)2448 TEST(UnorderedPointwiseTest, RejectsWrongSize) {
2449   const double lhs[2] = {1, 2};
2450   const int rhs[1] = {0};
2451   EXPECT_THAT(lhs, Not(UnorderedPointwise(Gt(), rhs)));
2452   EXPECT_EQ("which has 2 elements\n",
2453             Explain(UnorderedPointwise(Gt(), rhs), lhs));
2454 
2455   const int rhs2[3] = {0, 1, 2};
2456   EXPECT_THAT(lhs, Not(UnorderedPointwise(Gt(), rhs2)));
2457 }
2458 
TEST(UnorderedPointwiseTest,RejectsWrongContent)2459 TEST(UnorderedPointwiseTest, RejectsWrongContent) {
2460   const double lhs[3] = {1, 2, 3};
2461   const int rhs[3] = {2, 6, 6};
2462   EXPECT_THAT(lhs, Not(UnorderedPointwise(IsHalfOf(), rhs)));
2463   EXPECT_EQ(
2464       "where the following elements don't match any matchers:\n"
2465       "element #1: 2",
2466       Explain(UnorderedPointwise(IsHalfOf(), rhs), lhs));
2467 }
2468 
TEST(UnorderedPointwiseTest,AcceptsCorrectContentInSameOrder)2469 TEST(UnorderedPointwiseTest, AcceptsCorrectContentInSameOrder) {
2470   const double lhs[3] = {1, 2, 3};
2471   const int rhs[3] = {2, 4, 6};
2472   EXPECT_THAT(lhs, UnorderedPointwise(IsHalfOf(), rhs));
2473 }
2474 
TEST(UnorderedPointwiseTest,AcceptsCorrectContentInDifferentOrder)2475 TEST(UnorderedPointwiseTest, AcceptsCorrectContentInDifferentOrder) {
2476   const double lhs[3] = {1, 2, 3};
2477   const int rhs[3] = {6, 4, 2};
2478   EXPECT_THAT(lhs, UnorderedPointwise(IsHalfOf(), rhs));
2479 }
2480 
TEST(UnorderedPointwiseTest,AllowsMonomorphicInnerMatcher)2481 TEST(UnorderedPointwiseTest, AllowsMonomorphicInnerMatcher) {
2482   const double lhs[3] = {1, 2, 3};
2483   const int rhs[3] = {4, 6, 2};
2484   const Matcher<std::tuple<const double&, const int&>> m1 = IsHalfOf();
2485   EXPECT_THAT(lhs, UnorderedPointwise(m1, rhs));
2486 
2487   // This type works as a std::tuple<const double&, const int&> can be
2488   // implicitly cast to std::tuple<double, int>.
2489   const Matcher<std::tuple<double, int>> m2 = IsHalfOf();
2490   EXPECT_THAT(lhs, UnorderedPointwise(m2, rhs));
2491 }
2492 
TEST(UnorderedPointwiseTest,WorksWithMoveOnly)2493 TEST(UnorderedPointwiseTest, WorksWithMoveOnly) {
2494   ContainerHelper helper;
2495   EXPECT_CALL(helper, Call(UnorderedPointwise(PointeeEquals(),
2496                                               std::vector<int>{1, 2})));
2497   helper.Call(MakeUniquePtrs({2, 1}));
2498 }
2499 
TEST(PointeeTest,WorksOnMoveOnlyType)2500 TEST(PointeeTest, WorksOnMoveOnlyType) {
2501   std::unique_ptr<int> p(new int(3));
2502   EXPECT_THAT(p, Pointee(Eq(3)));
2503   EXPECT_THAT(p, Not(Pointee(Eq(2))));
2504 }
2505 
2506 class PredicateFormatterFromMatcherTest : public ::testing::Test {
2507  protected:
2508   enum Behavior { kInitialSuccess, kAlwaysFail, kFlaky };
2509 
2510   // A matcher that can return different results when used multiple times on the
2511   // same input. No real matcher should do this; but this lets us test that we
2512   // detect such behavior and fail appropriately.
2513   class MockMatcher : public MatcherInterface<Behavior> {
2514    public:
MatchAndExplain(Behavior behavior,MatchResultListener * listener) const2515     bool MatchAndExplain(Behavior behavior,
2516                          MatchResultListener* listener) const override {
2517       *listener << "[MatchAndExplain]";
2518       switch (behavior) {
2519         case kInitialSuccess:
2520           // The first call to MatchAndExplain should use a "not interested"
2521           // listener; so this is expected to return |true|. There should be no
2522           // subsequent calls.
2523           return !listener->IsInterested();
2524 
2525         case kAlwaysFail:
2526           return false;
2527 
2528         case kFlaky:
2529           // The first call to MatchAndExplain should use a "not interested"
2530           // listener; so this will return |false|. Subsequent calls should have
2531           // an "interested" listener; so this will return |true|, thus
2532           // simulating a flaky matcher.
2533           return listener->IsInterested();
2534       }
2535 
2536       GTEST_LOG_(FATAL) << "This should never be reached";
2537       return false;
2538     }
2539 
DescribeTo(ostream * os) const2540     void DescribeTo(ostream* os) const override { *os << "[DescribeTo]"; }
2541 
DescribeNegationTo(ostream * os) const2542     void DescribeNegationTo(ostream* os) const override {
2543       *os << "[DescribeNegationTo]";
2544     }
2545   };
2546 
RunPredicateFormatter(Behavior behavior)2547   AssertionResult RunPredicateFormatter(Behavior behavior) {
2548     auto matcher = MakeMatcher(new MockMatcher);
2549     PredicateFormatterFromMatcher<Matcher<Behavior>> predicate_formatter(
2550         matcher);
2551     return predicate_formatter("dummy-name", behavior);
2552   }
2553 };
2554 
TEST_F(PredicateFormatterFromMatcherTest,ShortCircuitOnSuccess)2555 TEST_F(PredicateFormatterFromMatcherTest, ShortCircuitOnSuccess) {
2556   AssertionResult result = RunPredicateFormatter(kInitialSuccess);
2557   EXPECT_TRUE(result);  // Implicit cast to bool.
2558   std::string expect;
2559   EXPECT_EQ(expect, result.message());
2560 }
2561 
TEST_F(PredicateFormatterFromMatcherTest,NoShortCircuitOnFailure)2562 TEST_F(PredicateFormatterFromMatcherTest, NoShortCircuitOnFailure) {
2563   AssertionResult result = RunPredicateFormatter(kAlwaysFail);
2564   EXPECT_FALSE(result);  // Implicit cast to bool.
2565   std::string expect =
2566       "Value of: dummy-name\nExpected: [DescribeTo]\n"
2567       "  Actual: 1" +
2568       OfType(internal::GetTypeName<Behavior>()) + ", [MatchAndExplain]";
2569   EXPECT_EQ(expect, result.message());
2570 }
2571 
TEST_F(PredicateFormatterFromMatcherTest,DetectsFlakyShortCircuit)2572 TEST_F(PredicateFormatterFromMatcherTest, DetectsFlakyShortCircuit) {
2573   AssertionResult result = RunPredicateFormatter(kFlaky);
2574   EXPECT_FALSE(result);  // Implicit cast to bool.
2575   std::string expect =
2576       "Value of: dummy-name\nExpected: [DescribeTo]\n"
2577       "  The matcher failed on the initial attempt; but passed when rerun to "
2578       "generate the explanation.\n"
2579       "  Actual: 2" +
2580       OfType(internal::GetTypeName<Behavior>()) + ", [MatchAndExplain]";
2581   EXPECT_EQ(expect, result.message());
2582 }
2583 
2584 // Tests for ElementsAre().
2585 
TEST(ElementsAreTest,CanDescribeExpectingNoElement)2586 TEST(ElementsAreTest, CanDescribeExpectingNoElement) {
2587   Matcher<const vector<int>&> m = ElementsAre();
2588   EXPECT_EQ("is empty", Describe(m));
2589 }
2590 
TEST(ElementsAreTest,CanDescribeExpectingOneElement)2591 TEST(ElementsAreTest, CanDescribeExpectingOneElement) {
2592   Matcher<vector<int>> m = ElementsAre(Gt(5));
2593   EXPECT_EQ("has 1 element that is > 5", Describe(m));
2594 }
2595 
TEST(ElementsAreTest,CanDescribeExpectingManyElements)2596 TEST(ElementsAreTest, CanDescribeExpectingManyElements) {
2597   Matcher<list<std::string>> m = ElementsAre(StrEq("one"), "two");
2598   EXPECT_EQ(
2599       "has 2 elements where\n"
2600       "element #0 is equal to \"one\",\n"
2601       "element #1 is equal to \"two\"",
2602       Describe(m));
2603 }
2604 
TEST(ElementsAreTest,CanDescribeNegationOfExpectingNoElement)2605 TEST(ElementsAreTest, CanDescribeNegationOfExpectingNoElement) {
2606   Matcher<vector<int>> m = ElementsAre();
2607   EXPECT_EQ("isn't empty", DescribeNegation(m));
2608 }
2609 
TEST(ElementsAreTest,CanDescribeNegationOfExpectingOneElement)2610 TEST(ElementsAreTest, CanDescribeNegationOfExpectingOneElement) {
2611   Matcher<const list<int>&> m = ElementsAre(Gt(5));
2612   EXPECT_EQ(
2613       "doesn't have 1 element, or\n"
2614       "element #0 isn't > 5",
2615       DescribeNegation(m));
2616 }
2617 
TEST(ElementsAreTest,CanDescribeNegationOfExpectingManyElements)2618 TEST(ElementsAreTest, CanDescribeNegationOfExpectingManyElements) {
2619   Matcher<const list<std::string>&> m = ElementsAre("one", "two");
2620   EXPECT_EQ(
2621       "doesn't have 2 elements, or\n"
2622       "element #0 isn't equal to \"one\", or\n"
2623       "element #1 isn't equal to \"two\"",
2624       DescribeNegation(m));
2625 }
2626 
TEST(ElementsAreTest,DoesNotExplainTrivialMatch)2627 TEST(ElementsAreTest, DoesNotExplainTrivialMatch) {
2628   Matcher<const list<int>&> m = ElementsAre(1, Ne(2));
2629 
2630   list<int> test_list;
2631   test_list.push_back(1);
2632   test_list.push_back(3);
2633   EXPECT_EQ("", Explain(m, test_list));  // No need to explain anything.
2634 }
2635 
TEST_P(ElementsAreTestP,ExplainsNonTrivialMatch)2636 TEST_P(ElementsAreTestP, ExplainsNonTrivialMatch) {
2637   Matcher<const vector<int>&> m =
2638       ElementsAre(GreaterThan(1), 0, GreaterThan(2));
2639 
2640   const int a[] = {10, 0, 100};
2641   vector<int> test_vector(std::begin(a), std::end(a));
2642   EXPECT_EQ(
2643       "whose element #0 matches, which is 9 more than 1,\n"
2644       "and whose element #2 matches, which is 98 more than 2",
2645       Explain(m, test_vector));
2646 }
2647 
TEST(ElementsAreTest,CanExplainMismatchWrongSize)2648 TEST(ElementsAreTest, CanExplainMismatchWrongSize) {
2649   Matcher<const list<int>&> m = ElementsAre(1, 3);
2650 
2651   list<int> test_list;
2652   // No need to explain when the container is empty.
2653   EXPECT_EQ("", Explain(m, test_list));
2654 
2655   test_list.push_back(1);
2656   EXPECT_EQ("which has 1 element", Explain(m, test_list));
2657 }
2658 
TEST_P(ElementsAreTestP,CanExplainMismatchRightSize)2659 TEST_P(ElementsAreTestP, CanExplainMismatchRightSize) {
2660   Matcher<const vector<int>&> m = ElementsAre(1, GreaterThan(5));
2661 
2662   vector<int> v;
2663   v.push_back(2);
2664   v.push_back(1);
2665   EXPECT_EQ("whose element #0 doesn't match", Explain(m, v));
2666 
2667   v[0] = 1;
2668   EXPECT_EQ("whose element #1 doesn't match, which is 4 less than 5",
2669             Explain(m, v));
2670 }
2671 
TEST(ElementsAreTest,MatchesOneElementVector)2672 TEST(ElementsAreTest, MatchesOneElementVector) {
2673   vector<std::string> test_vector;
2674   test_vector.push_back("test string");
2675 
2676   EXPECT_THAT(test_vector, ElementsAre(StrEq("test string")));
2677 }
2678 
TEST(ElementsAreTest,MatchesOneElementList)2679 TEST(ElementsAreTest, MatchesOneElementList) {
2680   list<std::string> test_list;
2681   test_list.push_back("test string");
2682 
2683   EXPECT_THAT(test_list, ElementsAre("test string"));
2684 }
2685 
TEST(ElementsAreTest,MatchesThreeElementVector)2686 TEST(ElementsAreTest, MatchesThreeElementVector) {
2687   vector<std::string> test_vector;
2688   test_vector.push_back("one");
2689   test_vector.push_back("two");
2690   test_vector.push_back("three");
2691 
2692   EXPECT_THAT(test_vector, ElementsAre("one", StrEq("two"), _));
2693 }
2694 
TEST(ElementsAreTest,MatchesOneElementEqMatcher)2695 TEST(ElementsAreTest, MatchesOneElementEqMatcher) {
2696   vector<int> test_vector;
2697   test_vector.push_back(4);
2698 
2699   EXPECT_THAT(test_vector, ElementsAre(Eq(4)));
2700 }
2701 
TEST(ElementsAreTest,MatchesOneElementAnyMatcher)2702 TEST(ElementsAreTest, MatchesOneElementAnyMatcher) {
2703   vector<int> test_vector;
2704   test_vector.push_back(4);
2705 
2706   EXPECT_THAT(test_vector, ElementsAre(_));
2707 }
2708 
TEST(ElementsAreTest,MatchesOneElementValue)2709 TEST(ElementsAreTest, MatchesOneElementValue) {
2710   vector<int> test_vector;
2711   test_vector.push_back(4);
2712 
2713   EXPECT_THAT(test_vector, ElementsAre(4));
2714 }
2715 
TEST(ElementsAreTest,MatchesThreeElementsMixedMatchers)2716 TEST(ElementsAreTest, MatchesThreeElementsMixedMatchers) {
2717   vector<int> test_vector;
2718   test_vector.push_back(1);
2719   test_vector.push_back(2);
2720   test_vector.push_back(3);
2721 
2722   EXPECT_THAT(test_vector, ElementsAre(1, Eq(2), _));
2723 }
2724 
TEST(ElementsAreTest,MatchesTenElementVector)2725 TEST(ElementsAreTest, MatchesTenElementVector) {
2726   const int a[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
2727   vector<int> test_vector(std::begin(a), std::end(a));
2728 
2729   EXPECT_THAT(test_vector,
2730               // The element list can contain values and/or matchers
2731               // of different types.
2732               ElementsAre(0, Ge(0), _, 3, 4, Ne(2), Eq(6), 7, 8, _));
2733 }
2734 
TEST(ElementsAreTest,DoesNotMatchWrongSize)2735 TEST(ElementsAreTest, DoesNotMatchWrongSize) {
2736   vector<std::string> test_vector;
2737   test_vector.push_back("test string");
2738   test_vector.push_back("test string");
2739 
2740   Matcher<vector<std::string>> m = ElementsAre(StrEq("test string"));
2741   EXPECT_FALSE(m.Matches(test_vector));
2742 }
2743 
TEST(ElementsAreTest,DoesNotMatchWrongValue)2744 TEST(ElementsAreTest, DoesNotMatchWrongValue) {
2745   vector<std::string> test_vector;
2746   test_vector.push_back("other string");
2747 
2748   Matcher<vector<std::string>> m = ElementsAre(StrEq("test string"));
2749   EXPECT_FALSE(m.Matches(test_vector));
2750 }
2751 
TEST(ElementsAreTest,DoesNotMatchWrongOrder)2752 TEST(ElementsAreTest, DoesNotMatchWrongOrder) {
2753   vector<std::string> test_vector;
2754   test_vector.push_back("one");
2755   test_vector.push_back("three");
2756   test_vector.push_back("two");
2757 
2758   Matcher<vector<std::string>> m =
2759       ElementsAre(StrEq("one"), StrEq("two"), StrEq("three"));
2760   EXPECT_FALSE(m.Matches(test_vector));
2761 }
2762 
TEST(ElementsAreTest,WorksForNestedContainer)2763 TEST(ElementsAreTest, WorksForNestedContainer) {
2764   constexpr std::array<const char*, 2> strings = {{"Hi", "world"}};
2765 
2766   vector<list<char>> nested;
2767   for (const auto& s : strings) {
2768     nested.emplace_back(s, s + strlen(s));
2769   }
2770 
2771   EXPECT_THAT(nested, ElementsAre(ElementsAre('H', Ne('e')),
2772                                   ElementsAre('w', 'o', _, _, 'd')));
2773   EXPECT_THAT(nested, Not(ElementsAre(ElementsAre('H', 'e'),
2774                                       ElementsAre('w', 'o', _, _, 'd'))));
2775 }
2776 
TEST(ElementsAreTest,WorksWithByRefElementMatchers)2777 TEST(ElementsAreTest, WorksWithByRefElementMatchers) {
2778   int a[] = {0, 1, 2};
2779   vector<int> v(std::begin(a), std::end(a));
2780 
2781   EXPECT_THAT(v, ElementsAre(Ref(v[0]), Ref(v[1]), Ref(v[2])));
2782   EXPECT_THAT(v, Not(ElementsAre(Ref(v[0]), Ref(v[1]), Ref(a[2]))));
2783 }
2784 
TEST(ElementsAreTest,WorksWithContainerPointerUsingPointee)2785 TEST(ElementsAreTest, WorksWithContainerPointerUsingPointee) {
2786   int a[] = {0, 1, 2};
2787   vector<int> v(std::begin(a), std::end(a));
2788 
2789   EXPECT_THAT(&v, Pointee(ElementsAre(0, 1, _)));
2790   EXPECT_THAT(&v, Not(Pointee(ElementsAre(0, _, 3))));
2791 }
2792 
TEST(ElementsAreTest,WorksWithNativeArrayPassedByReference)2793 TEST(ElementsAreTest, WorksWithNativeArrayPassedByReference) {
2794   int array[] = {0, 1, 2};
2795   EXPECT_THAT(array, ElementsAre(0, 1, _));
2796   EXPECT_THAT(array, Not(ElementsAre(1, _, _)));
2797   EXPECT_THAT(array, Not(ElementsAre(0, _)));
2798 }
2799 
2800 class NativeArrayPassedAsPointerAndSize {
2801  public:
2802   NativeArrayPassedAsPointerAndSize() = default;
2803 
2804   MOCK_METHOD(void, Helper, (int* array, int size));
2805 
2806  private:
2807   NativeArrayPassedAsPointerAndSize(const NativeArrayPassedAsPointerAndSize&) =
2808       delete;
2809   NativeArrayPassedAsPointerAndSize& operator=(
2810       const NativeArrayPassedAsPointerAndSize&) = delete;
2811 };
2812 
TEST(ElementsAreTest,WorksWithNativeArrayPassedAsPointerAndSize)2813 TEST(ElementsAreTest, WorksWithNativeArrayPassedAsPointerAndSize) {
2814   int array[] = {0, 1};
2815   ::std::tuple<int*, size_t> array_as_tuple(array, 2);
2816   EXPECT_THAT(array_as_tuple, ElementsAre(0, 1));
2817   EXPECT_THAT(array_as_tuple, Not(ElementsAre(0)));
2818 
2819   NativeArrayPassedAsPointerAndSize helper;
2820   EXPECT_CALL(helper, Helper(_, _)).With(ElementsAre(0, 1));
2821   helper.Helper(array, 2);
2822 }
2823 
TEST(ElementsAreTest,WorksWithTwoDimensionalNativeArray)2824 TEST(ElementsAreTest, WorksWithTwoDimensionalNativeArray) {
2825   const char a2[][3] = {"hi", "lo"};
2826   EXPECT_THAT(a2, ElementsAre(ElementsAre('h', 'i', '\0'),
2827                               ElementsAre('l', 'o', '\0')));
2828   EXPECT_THAT(a2, ElementsAre(StrEq("hi"), StrEq("lo")));
2829   EXPECT_THAT(a2, ElementsAre(Not(ElementsAre('h', 'o', '\0')),
2830                               ElementsAre('l', 'o', '\0')));
2831 }
2832 
TEST(ElementsAreTest,AcceptsStringLiteral)2833 TEST(ElementsAreTest, AcceptsStringLiteral) {
2834   std::string array[] = {"hi", "one", "two"};
2835   EXPECT_THAT(array, ElementsAre("hi", "one", "two"));
2836   EXPECT_THAT(array, Not(ElementsAre("hi", "one", "too")));
2837 }
2838 
2839 // Declared here with the size unknown.  Defined AFTER the following test.
2840 extern const char kHi[];
2841 
TEST(ElementsAreTest,AcceptsArrayWithUnknownSize)2842 TEST(ElementsAreTest, AcceptsArrayWithUnknownSize) {
2843   // The size of kHi is not known in this test, but ElementsAre() should
2844   // still accept it.
2845 
2846   std::string array1[] = {"hi"};
2847   EXPECT_THAT(array1, ElementsAre(kHi));
2848 
2849   std::string array2[] = {"ho"};
2850   EXPECT_THAT(array2, Not(ElementsAre(kHi)));
2851 }
2852 
2853 const char kHi[] = "hi";
2854 
TEST(ElementsAreTest,MakesCopyOfArguments)2855 TEST(ElementsAreTest, MakesCopyOfArguments) {
2856   int x = 1;
2857   int y = 2;
2858   // This should make a copy of x and y.
2859   ::testing::internal::ElementsAreMatcher<std::tuple<int, int>>
2860       polymorphic_matcher = ElementsAre(x, y);
2861   // Changing x and y now shouldn't affect the meaning of the above matcher.
2862   x = y = 0;
2863   const int array1[] = {1, 2};
2864   EXPECT_THAT(array1, polymorphic_matcher);
2865   const int array2[] = {0, 0};
2866   EXPECT_THAT(array2, Not(polymorphic_matcher));
2867 }
2868 
2869 // Tests for ElementsAreArray().  Since ElementsAreArray() shares most
2870 // of the implementation with ElementsAre(), we don't test it as
2871 // thoroughly here.
2872 
TEST(ElementsAreArrayTest,CanBeCreatedWithValueArray)2873 TEST(ElementsAreArrayTest, CanBeCreatedWithValueArray) {
2874   const int a[] = {1, 2, 3};
2875 
2876   vector<int> test_vector(std::begin(a), std::end(a));
2877   EXPECT_THAT(test_vector, ElementsAreArray(a));
2878 
2879   test_vector[2] = 0;
2880   EXPECT_THAT(test_vector, Not(ElementsAreArray(a)));
2881 }
2882 
TEST(ElementsAreArrayTest,CanBeCreatedWithArraySize)2883 TEST(ElementsAreArrayTest, CanBeCreatedWithArraySize) {
2884   std::array<const char*, 3> a = {{"one", "two", "three"}};
2885 
2886   vector<std::string> test_vector(std::begin(a), std::end(a));
2887   EXPECT_THAT(test_vector, ElementsAreArray(a.data(), a.size()));
2888 
2889   const char** p = a.data();
2890   test_vector[0] = "1";
2891   EXPECT_THAT(test_vector, Not(ElementsAreArray(p, a.size())));
2892 }
2893 
TEST(ElementsAreArrayTest,CanBeCreatedWithoutArraySize)2894 TEST(ElementsAreArrayTest, CanBeCreatedWithoutArraySize) {
2895   const char* a[] = {"one", "two", "three"};
2896 
2897   vector<std::string> test_vector(std::begin(a), std::end(a));
2898   EXPECT_THAT(test_vector, ElementsAreArray(a));
2899 
2900   test_vector[0] = "1";
2901   EXPECT_THAT(test_vector, Not(ElementsAreArray(a)));
2902 }
2903 
TEST(ElementsAreArrayTest,CanBeCreatedWithMatcherArray)2904 TEST(ElementsAreArrayTest, CanBeCreatedWithMatcherArray) {
2905   const Matcher<std::string> kMatcherArray[] = {StrEq("one"), StrEq("two"),
2906                                                 StrEq("three")};
2907 
2908   vector<std::string> test_vector;
2909   test_vector.push_back("one");
2910   test_vector.push_back("two");
2911   test_vector.push_back("three");
2912   EXPECT_THAT(test_vector, ElementsAreArray(kMatcherArray));
2913 
2914   test_vector.push_back("three");
2915   EXPECT_THAT(test_vector, Not(ElementsAreArray(kMatcherArray)));
2916 }
2917 
TEST(ElementsAreArrayTest,CanBeCreatedWithVector)2918 TEST(ElementsAreArrayTest, CanBeCreatedWithVector) {
2919   const int a[] = {1, 2, 3};
2920   vector<int> test_vector(std::begin(a), std::end(a));
2921   const vector<int> expected(std::begin(a), std::end(a));
2922   EXPECT_THAT(test_vector, ElementsAreArray(expected));
2923   test_vector.push_back(4);
2924   EXPECT_THAT(test_vector, Not(ElementsAreArray(expected)));
2925 }
2926 
TEST(ElementsAreArrayTest,TakesInitializerList)2927 TEST(ElementsAreArrayTest, TakesInitializerList) {
2928   const int a[5] = {1, 2, 3, 4, 5};
2929   EXPECT_THAT(a, ElementsAreArray({1, 2, 3, 4, 5}));
2930   EXPECT_THAT(a, Not(ElementsAreArray({1, 2, 3, 5, 4})));
2931   EXPECT_THAT(a, Not(ElementsAreArray({1, 2, 3, 4, 6})));
2932 }
2933 
TEST(ElementsAreArrayTest,TakesInitializerListOfCStrings)2934 TEST(ElementsAreArrayTest, TakesInitializerListOfCStrings) {
2935   const std::string a[5] = {"a", "b", "c", "d", "e"};
2936   EXPECT_THAT(a, ElementsAreArray({"a", "b", "c", "d", "e"}));
2937   EXPECT_THAT(a, Not(ElementsAreArray({"a", "b", "c", "e", "d"})));
2938   EXPECT_THAT(a, Not(ElementsAreArray({"a", "b", "c", "d", "ef"})));
2939 }
2940 
TEST(ElementsAreArrayTest,TakesInitializerListOfSameTypedMatchers)2941 TEST(ElementsAreArrayTest, TakesInitializerListOfSameTypedMatchers) {
2942   const int a[5] = {1, 2, 3, 4, 5};
2943   EXPECT_THAT(a, ElementsAreArray({Eq(1), Eq(2), Eq(3), Eq(4), Eq(5)}));
2944   EXPECT_THAT(a, Not(ElementsAreArray({Eq(1), Eq(2), Eq(3), Eq(4), Eq(6)})));
2945 }
2946 
TEST(ElementsAreArrayTest,TakesInitializerListOfDifferentTypedMatchers)2947 TEST(ElementsAreArrayTest, TakesInitializerListOfDifferentTypedMatchers) {
2948   const int a[5] = {1, 2, 3, 4, 5};
2949   // The compiler cannot infer the type of the initializer list if its
2950   // elements have different types.  We must explicitly specify the
2951   // unified element type in this case.
2952   EXPECT_THAT(
2953       a, ElementsAreArray<Matcher<int>>({Eq(1), Ne(-2), Ge(3), Le(4), Eq(5)}));
2954   EXPECT_THAT(a, Not(ElementsAreArray<Matcher<int>>(
2955                      {Eq(1), Ne(-2), Ge(3), Le(4), Eq(6)})));
2956 }
2957 
TEST(ElementsAreArrayTest,CanBeCreatedWithMatcherVector)2958 TEST(ElementsAreArrayTest, CanBeCreatedWithMatcherVector) {
2959   const int a[] = {1, 2, 3};
2960   const Matcher<int> kMatchers[] = {Eq(1), Eq(2), Eq(3)};
2961   vector<int> test_vector(std::begin(a), std::end(a));
2962   const vector<Matcher<int>> expected(std::begin(kMatchers),
2963                                       std::end(kMatchers));
2964   EXPECT_THAT(test_vector, ElementsAreArray(expected));
2965   test_vector.push_back(4);
2966   EXPECT_THAT(test_vector, Not(ElementsAreArray(expected)));
2967 }
2968 
TEST(ElementsAreArrayTest,CanBeCreatedWithIteratorRange)2969 TEST(ElementsAreArrayTest, CanBeCreatedWithIteratorRange) {
2970   const int a[] = {1, 2, 3};
2971   const vector<int> test_vector(std::begin(a), std::end(a));
2972   const vector<int> expected(std::begin(a), std::end(a));
2973   EXPECT_THAT(test_vector, ElementsAreArray(expected.begin(), expected.end()));
2974   // Pointers are iterators, too.
2975   EXPECT_THAT(test_vector, ElementsAreArray(std::begin(a), std::end(a)));
2976   // The empty range of NULL pointers should also be okay.
2977   int* const null_int = nullptr;
2978   EXPECT_THAT(test_vector, Not(ElementsAreArray(null_int, null_int)));
2979   EXPECT_THAT((vector<int>()), ElementsAreArray(null_int, null_int));
2980 }
2981 
2982 // Since ElementsAre() and ElementsAreArray() share much of the
2983 // implementation, we only do a test for native arrays here.
TEST(ElementsAreArrayTest,WorksWithNativeArray)2984 TEST(ElementsAreArrayTest, WorksWithNativeArray) {
2985   ::std::string a[] = {"hi", "ho"};
2986   ::std::string b[] = {"hi", "ho"};
2987 
2988   EXPECT_THAT(a, ElementsAreArray(b));
2989   EXPECT_THAT(a, ElementsAreArray(b, 2));
2990   EXPECT_THAT(a, Not(ElementsAreArray(b, 1)));
2991 }
2992 
TEST(ElementsAreArrayTest,SourceLifeSpan)2993 TEST(ElementsAreArrayTest, SourceLifeSpan) {
2994   const int a[] = {1, 2, 3};
2995   vector<int> test_vector(std::begin(a), std::end(a));
2996   vector<int> expect(std::begin(a), std::end(a));
2997   ElementsAreArrayMatcher<int> matcher_maker =
2998       ElementsAreArray(expect.begin(), expect.end());
2999   EXPECT_THAT(test_vector, matcher_maker);
3000   // Changing in place the values that initialized matcher_maker should not
3001   // affect matcher_maker anymore. It should have made its own copy of them.
3002   for (int& i : expect) {
3003     i += 10;
3004   }
3005   EXPECT_THAT(test_vector, matcher_maker);
3006   test_vector.push_back(3);
3007   EXPECT_THAT(test_vector, Not(matcher_maker));
3008 }
3009 
3010 // Tests Contains().
3011 
3012 INSTANTIATE_GTEST_MATCHER_TEST_P(ContainsTest);
3013 
TEST(ContainsTest,ListMatchesWhenElementIsInContainer)3014 TEST(ContainsTest, ListMatchesWhenElementIsInContainer) {
3015   list<int> some_list;
3016   some_list.push_back(3);
3017   some_list.push_back(1);
3018   some_list.push_back(2);
3019   some_list.push_back(3);
3020   EXPECT_THAT(some_list, Contains(1));
3021   EXPECT_THAT(some_list, Contains(Gt(2.5)));
3022   EXPECT_THAT(some_list, Contains(Eq(2.0f)));
3023 
3024   list<std::string> another_list;
3025   another_list.push_back("fee");
3026   another_list.push_back("fie");
3027   another_list.push_back("foe");
3028   another_list.push_back("fum");
3029   EXPECT_THAT(another_list, Contains(std::string("fee")));
3030 }
3031 
TEST(ContainsTest,ListDoesNotMatchWhenElementIsNotInContainer)3032 TEST(ContainsTest, ListDoesNotMatchWhenElementIsNotInContainer) {
3033   list<int> some_list;
3034   some_list.push_back(3);
3035   some_list.push_back(1);
3036   EXPECT_THAT(some_list, Not(Contains(4)));
3037 }
3038 
TEST(ContainsTest,SetMatchesWhenElementIsInContainer)3039 TEST(ContainsTest, SetMatchesWhenElementIsInContainer) {
3040   set<int> some_set;
3041   some_set.insert(3);
3042   some_set.insert(1);
3043   some_set.insert(2);
3044   EXPECT_THAT(some_set, Contains(Eq(1.0)));
3045   EXPECT_THAT(some_set, Contains(Eq(3.0f)));
3046   EXPECT_THAT(some_set, Contains(2));
3047 
3048   set<std::string> another_set;
3049   another_set.insert("fee");
3050   another_set.insert("fie");
3051   another_set.insert("foe");
3052   another_set.insert("fum");
3053   EXPECT_THAT(another_set, Contains(Eq(std::string("fum"))));
3054 }
3055 
TEST(ContainsTest,SetDoesNotMatchWhenElementIsNotInContainer)3056 TEST(ContainsTest, SetDoesNotMatchWhenElementIsNotInContainer) {
3057   set<int> some_set;
3058   some_set.insert(3);
3059   some_set.insert(1);
3060   EXPECT_THAT(some_set, Not(Contains(4)));
3061 
3062   set<std::string> c_string_set;
3063   c_string_set.insert("hello");
3064   EXPECT_THAT(c_string_set, Not(Contains(std::string("goodbye"))));
3065 }
3066 
TEST_P(ContainsTestP,ExplainsMatchResultCorrectly)3067 TEST_P(ContainsTestP, ExplainsMatchResultCorrectly) {
3068   const int a[2] = {1, 2};
3069   Matcher<const int(&)[2]> m = Contains(2);
3070   EXPECT_EQ("whose element #1 matches", Explain(m, a));
3071 
3072   m = Contains(3);
3073   EXPECT_EQ("", Explain(m, a));
3074 
3075   m = Contains(GreaterThan(0));
3076   EXPECT_EQ("whose element #0 matches, which is 1 more than 0", Explain(m, a));
3077 
3078   m = Contains(GreaterThan(10));
3079   EXPECT_EQ("", Explain(m, a));
3080 }
3081 
TEST(ContainsTest,DescribesItselfCorrectly)3082 TEST(ContainsTest, DescribesItselfCorrectly) {
3083   Matcher<vector<int>> m = Contains(1);
3084   EXPECT_EQ("contains at least one element that is equal to 1", Describe(m));
3085 
3086   Matcher<vector<int>> m2 = Not(m);
3087   EXPECT_EQ("doesn't contain any element that is equal to 1", Describe(m2));
3088 }
3089 
TEST(ContainsTest,MapMatchesWhenElementIsInContainer)3090 TEST(ContainsTest, MapMatchesWhenElementIsInContainer) {
3091   map<std::string, int> my_map;
3092   const char* bar = "a string";
3093   my_map[bar] = 2;
3094   EXPECT_THAT(my_map, Contains(pair<const char* const, int>(bar, 2)));
3095 
3096   map<std::string, int> another_map;
3097   another_map["fee"] = 1;
3098   another_map["fie"] = 2;
3099   another_map["foe"] = 3;
3100   another_map["fum"] = 4;
3101   EXPECT_THAT(another_map,
3102               Contains(pair<const std::string, int>(std::string("fee"), 1)));
3103   EXPECT_THAT(another_map, Contains(pair<const std::string, int>("fie", 2)));
3104 }
3105 
TEST(ContainsTest,MapDoesNotMatchWhenElementIsNotInContainer)3106 TEST(ContainsTest, MapDoesNotMatchWhenElementIsNotInContainer) {
3107   map<int, int> some_map;
3108   some_map[1] = 11;
3109   some_map[2] = 22;
3110   EXPECT_THAT(some_map, Not(Contains(pair<const int, int>(2, 23))));
3111 }
3112 
TEST(ContainsTest,ArrayMatchesWhenElementIsInContainer)3113 TEST(ContainsTest, ArrayMatchesWhenElementIsInContainer) {
3114   const char* string_array[] = {"fee", "fie", "foe", "fum"};
3115   EXPECT_THAT(string_array, Contains(Eq(std::string("fum"))));
3116 }
3117 
TEST(ContainsTest,ArrayDoesNotMatchWhenElementIsNotInContainer)3118 TEST(ContainsTest, ArrayDoesNotMatchWhenElementIsNotInContainer) {
3119   int int_array[] = {1, 2, 3, 4};
3120   EXPECT_THAT(int_array, Not(Contains(5)));
3121 }
3122 
TEST(ContainsTest,AcceptsMatcher)3123 TEST(ContainsTest, AcceptsMatcher) {
3124   const int a[] = {1, 2, 3};
3125   EXPECT_THAT(a, Contains(Gt(2)));
3126   EXPECT_THAT(a, Not(Contains(Gt(4))));
3127 }
3128 
TEST(ContainsTest,WorksForNativeArrayAsTuple)3129 TEST(ContainsTest, WorksForNativeArrayAsTuple) {
3130   const int a[] = {1, 2};
3131   const int* const pointer = a;
3132   EXPECT_THAT(std::make_tuple(pointer, 2), Contains(1));
3133   EXPECT_THAT(std::make_tuple(pointer, 2), Not(Contains(Gt(3))));
3134 }
3135 
TEST(ContainsTest,WorksForTwoDimensionalNativeArray)3136 TEST(ContainsTest, WorksForTwoDimensionalNativeArray) {
3137   int a[][3] = {{1, 2, 3}, {4, 5, 6}};
3138   EXPECT_THAT(a, Contains(ElementsAre(4, 5, 6)));
3139   EXPECT_THAT(a, Contains(Contains(5)));
3140   EXPECT_THAT(a, Not(Contains(ElementsAre(3, 4, 5))));
3141   EXPECT_THAT(a, Contains(Not(Contains(5))));
3142 }
3143 
3144 }  // namespace
3145 }  // namespace gmock_matchers_test
3146 }  // namespace testing
3147 
3148 GTEST_DISABLE_MSC_WARNINGS_POP_()  // 4244 4100
3149