Sacado Package Browser (Single Doxygen Collection)  Version of the Day
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Groups Pages
gmock-matchers-containers_test.cc
Go to the documentation of this file.
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 "gmock/gmock.h"
48 #include "gtest/gtest.h"
49 
50 // Silence warning C4244: 'initializing': conversion from 'int' to 'short',
51 // possible loss of data and C4100, unreferenced local parameter
53 
54 namespace testing {
55 namespace gmock_matchers_test {
56 namespace {
57 
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 
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 
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
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
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
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.
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.
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 
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.
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.
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 
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 
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 
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 
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 
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 
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 
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 
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 
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 
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 
281  ConstPropagatingPtr() : val_() {}
282  explicit ConstPropagatingPtr(T* t) : val_(t) {}
283  ConstPropagatingPtr(const ConstPropagatingPtr& other) : val_(other.val_) {}
284 
285  T* get() { return val_; }
286  T& operator*() { return *val_; }
287  // Most smart pointers return non-const T* and T& from the next methods.
288  const T* get() const { return val_; }
289  const T& operator*() const { return *val_; }
290 
291  private:
292  T* val_;
293 };
294 
296 
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 
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)).
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 
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 
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 
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:
351  Uncopyable() : value_(-1) {}
352  explicit Uncopyable(int a_value) : value_(a_value) {}
353 
354  int value() const { return value_; }
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.
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 {
372  AStruct() : x(0), y(1.0), z(5), p(nullptr) {}
373  AStruct(const AStruct& rhs)
374  : x(rhs.x), y(rhs.y), z(rhs.z.value()), p(rhs.p) {}
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 
388 
389 // Tests that Field(&Foo::field, ...) works when field is non-const.
390 TEST(FieldTest, WorksForNonConstField) {
391  Matcher<AStruct> m = Field(&AStruct::x, Ge(0));
392  Matcher<AStruct> m_with_name = Field("x", &AStruct::x, Ge(0));
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.
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.
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.
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.
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.
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.
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.
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 
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.
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 
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.
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.
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.
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.
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*.
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.
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 
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.
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 
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:
623  AClass() : n_(0) {}
624 
625  // A getter that returns a non-reference.
626  int n() const { return n_; }
627 
628  void set_n(int new_n) { n_ = new_n; }
629 
630  // A getter that returns a reference to const.
631  const std::string& s() const { return s_; }
632 
633  const std::string& s_ref() const& { return s_; }
634 
635  void set_s(const std::string& new_s) { s_ = new_s; }
636 
637  // A getter that returns a reference to non-const.
638  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:
652  int k() const { return k_; }
653 
654  private:
655  int k_;
656 };
657 
659 
660 // Tests that Property(&Foo::property, ...) works when property()
661 // returns a non-reference.
662 TEST(PropertyTest, WorksForNonReferenceProperty) {
663  Matcher<const AClass&> m = Property(&AClass::n, Ge(0));
664  Matcher<const AClass&> m_with_name = Property("n", &AClass::n, Ge(0));
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.
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.
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.
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.
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.
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.
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.
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 
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.
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 
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.
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.
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.
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.
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*.
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.
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 
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.
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 
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.
926 std::string IntToStringFunction(int input) {
927  return input == 1 ? "foo" : "bar";
928 }
929 
931 
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.
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.
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.
964 int IntFunction(int input) { return input == 42 ? 80 : 90; }
965 
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 
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.
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.
999 double& DoubleFunction(double& input) { return input; } // NOLINT
1000 
1001 Uncopyable& RefUncopyableFunction(Uncopyable& obj) { // NOLINT
1002  return obj;
1003 }
1004 
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.
1024 const std::string& StringFunction(const std::string& input) { return input; }
1025 
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.
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.
1047 TEST(ResultOfDeathTest, DiesOnNullFunctionPointers) {
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.
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 {
1065  std::string operator()(int input) const { return IntToStringFunction(input); }
1066 };
1067 
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;
1080  int operator()(int n) { return n; }
1081  int operator()(const char* s) { return static_cast<int>(strlen(s)); }
1082  std::string operator()(int* p) { return p ? "good ptr" : "null"; }
1083 };
1084 
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 
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 
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 
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 
1125 const int* ReferencingFunction(const int& n) { return &n; }
1126 
1127 struct ReferencingFunctor {
1128  typedef const int* result_type;
1129  result_type operator()(const int& n) { return &n; }
1130 };
1131 
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 
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 
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 
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 
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 {
1185  int size() const { return 1; }
1186 };
1187 TEST(SizeIsTest, WorksWithMinimalistCustomType) {
1188  MinimalistCustomType container;
1189  EXPECT_THAT(container, SizeIs(1));
1190  EXPECT_THAT(container, Not(SizeIs(0)));
1191 }
1192 
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 
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, which matches (is equal to 0)",
1208  Explain(m3, container));
1209  EXPECT_EQ("whose size 0 doesn't match", Explain(m4, container));
1210  container.push_back(0);
1211  container.push_back(0);
1212  EXPECT_EQ("whose size 2 matches", Explain(m1, container));
1213  EXPECT_EQ("whose size 2 doesn't match", Explain(m2, container));
1214  EXPECT_EQ(
1215  "whose size 2 doesn't match, isn't equal to 0, and isn't equal to 3",
1216  Explain(m3, container));
1217  EXPECT_EQ("whose size 2 matches", Explain(m4, container));
1218 }
1219 
1220 TEST(WhenSortedByTest, WorksForEmptyContainer) {
1221  const vector<int> numbers;
1222  EXPECT_THAT(numbers, WhenSortedBy(less<int>(), ElementsAre()));
1223  EXPECT_THAT(numbers, Not(WhenSortedBy(less<int>(), ElementsAre(1))));
1224 }
1225 
1226 TEST(WhenSortedByTest, WorksForNonEmptyContainer) {
1227  vector<unsigned> numbers;
1228  numbers.push_back(3);
1229  numbers.push_back(1);
1230  numbers.push_back(2);
1231  numbers.push_back(2);
1232  EXPECT_THAT(numbers,
1233  WhenSortedBy(greater<unsigned>(), ElementsAre(3, 2, 2, 1)));
1234  EXPECT_THAT(numbers,
1235  Not(WhenSortedBy(greater<unsigned>(), ElementsAre(1, 2, 2, 3))));
1236 }
1237 
1238 TEST(WhenSortedByTest, WorksForNonVectorContainer) {
1239  list<std::string> words;
1240  words.push_back("say");
1241  words.push_back("hello");
1242  words.push_back("world");
1243  EXPECT_THAT(words, WhenSortedBy(less<std::string>(),
1244  ElementsAre("hello", "say", "world")));
1245  EXPECT_THAT(words, Not(WhenSortedBy(less<std::string>(),
1246  ElementsAre("say", "hello", "world"))));
1247 }
1248 
1249 TEST(WhenSortedByTest, WorksForNativeArray) {
1250  const int numbers[] = {1, 3, 2, 4};
1251  const int sorted_numbers[] = {1, 2, 3, 4};
1252  EXPECT_THAT(numbers, WhenSortedBy(less<int>(), ElementsAre(1, 2, 3, 4)));
1253  EXPECT_THAT(numbers,
1254  WhenSortedBy(less<int>(), ElementsAreArray(sorted_numbers)));
1255  EXPECT_THAT(numbers, Not(WhenSortedBy(less<int>(), ElementsAre(1, 3, 2, 4))));
1256 }
1257 
1258 TEST(WhenSortedByTest, CanDescribeSelf) {
1259  const Matcher<vector<int>> m = WhenSortedBy(less<int>(), ElementsAre(1, 2));
1260  EXPECT_EQ(
1261  "(when sorted) has 2 elements where\n"
1262  "element #0 is equal to 1,\n"
1263  "element #1 is equal to 2",
1264  Describe(m));
1265  EXPECT_EQ(
1266  "(when sorted) doesn't have 2 elements, or\n"
1267  "element #0 isn't equal to 1, or\n"
1268  "element #1 isn't equal to 2",
1269  DescribeNegation(m));
1270 }
1271 
1272 TEST(WhenSortedByTest, ExplainsMatchResult) {
1273  const int a[] = {2, 1};
1274  EXPECT_EQ("which is { 1, 2 } when sorted, whose element #0 doesn't match",
1275  Explain(WhenSortedBy(less<int>(), ElementsAre(2, 3)), a));
1276  EXPECT_EQ("which is { 1, 2 } when sorted",
1277  Explain(WhenSortedBy(less<int>(), ElementsAre(1, 2)), a));
1278 }
1279 
1280 // WhenSorted() is a simple wrapper on WhenSortedBy(). Hence we don't
1281 // need to test it as exhaustively as we test the latter.
1282 
1283 TEST(WhenSortedTest, WorksForEmptyContainer) {
1284  const vector<int> numbers;
1285  EXPECT_THAT(numbers, WhenSorted(ElementsAre()));
1286  EXPECT_THAT(numbers, Not(WhenSorted(ElementsAre(1))));
1287 }
1288 
1289 TEST(WhenSortedTest, WorksForNonEmptyContainer) {
1290  list<std::string> words;
1291  words.push_back("3");
1292  words.push_back("1");
1293  words.push_back("2");
1294  words.push_back("2");
1295  EXPECT_THAT(words, WhenSorted(ElementsAre("1", "2", "2", "3")));
1296  EXPECT_THAT(words, Not(WhenSorted(ElementsAre("3", "1", "2", "2"))));
1297 }
1298 
1299 TEST(WhenSortedTest, WorksForMapTypes) {
1300  map<std::string, int> word_counts;
1301  word_counts["and"] = 1;
1302  word_counts["the"] = 1;
1303  word_counts["buffalo"] = 2;
1304  EXPECT_THAT(word_counts,
1305  WhenSorted(ElementsAre(Pair("and", 1), Pair("buffalo", 2),
1306  Pair("the", 1))));
1307  EXPECT_THAT(word_counts,
1308  Not(WhenSorted(ElementsAre(Pair("and", 1), Pair("the", 1),
1309  Pair("buffalo", 2)))));
1310 }
1311 
1312 TEST(WhenSortedTest, WorksForMultiMapTypes) {
1313  multimap<int, int> ifib;
1314  ifib.insert(make_pair(8, 6));
1315  ifib.insert(make_pair(2, 3));
1316  ifib.insert(make_pair(1, 1));
1317  ifib.insert(make_pair(3, 4));
1318  ifib.insert(make_pair(1, 2));
1319  ifib.insert(make_pair(5, 5));
1320  EXPECT_THAT(ifib,
1321  WhenSorted(ElementsAre(Pair(1, 1), Pair(1, 2), Pair(2, 3),
1322  Pair(3, 4), Pair(5, 5), Pair(8, 6))));
1323  EXPECT_THAT(ifib,
1324  Not(WhenSorted(ElementsAre(Pair(8, 6), Pair(2, 3), Pair(1, 1),
1325  Pair(3, 4), Pair(1, 2), Pair(5, 5)))));
1326 }
1327 
1328 TEST(WhenSortedTest, WorksForPolymorphicMatcher) {
1329  std::deque<int> d;
1330  d.push_back(2);
1331  d.push_back(1);
1332  EXPECT_THAT(d, WhenSorted(ElementsAre(1, 2)));
1333  EXPECT_THAT(d, Not(WhenSorted(ElementsAre(2, 1))));
1334 }
1335 
1336 TEST(WhenSortedTest, WorksForVectorConstRefMatcher) {
1337  std::deque<int> d;
1338  d.push_back(2);
1339  d.push_back(1);
1340  Matcher<const std::vector<int>&> vector_match = ElementsAre(1, 2);
1341  EXPECT_THAT(d, WhenSorted(vector_match));
1342  Matcher<const std::vector<int>&> not_vector_match = ElementsAre(2, 1);
1343  EXPECT_THAT(d, Not(WhenSorted(not_vector_match)));
1344 }
1345 
1346 // Deliberately bare pseudo-container.
1347 // Offers only begin() and end() accessors, yielding InputIterator.
1348 template <typename T>
1349 class Streamlike {
1350  private:
1351  class ConstIter;
1352 
1353  public:
1354  typedef ConstIter const_iterator;
1355  typedef T value_type;
1356 
1357  template <typename InIter>
1358  Streamlike(InIter first, InIter last) : remainder_(first, last) {}
1359 
1360  const_iterator begin() const {
1361  return const_iterator(this, remainder_.begin());
1362  }
1363  const_iterator end() const { return const_iterator(this, remainder_.end()); }
1364 
1365  private:
1366  class ConstIter {
1367  public:
1368  using iterator_category = std::input_iterator_tag;
1369  using value_type = T;
1370  using difference_type = ptrdiff_t;
1371  using pointer = const value_type*;
1372  using reference = const value_type&;
1373 
1374  ConstIter(const Streamlike* s, typename std::list<value_type>::iterator pos)
1375  : s_(s), pos_(pos) {}
1376 
1377  const value_type& operator*() const { return *pos_; }
1378  const value_type* operator->() const { return &*pos_; }
1379  ConstIter& operator++() {
1380  s_->remainder_.erase(pos_++);
1381  return *this;
1382  }
1383 
1384  // *iter++ is required to work (see std::istreambuf_iterator).
1385  // (void)iter++ is also required to work.
1386  class PostIncrProxy {
1387  public:
1388  explicit PostIncrProxy(const value_type& value) : value_(value) {}
1389  value_type operator*() const { return value_; }
1390 
1391  private:
1392  value_type value_;
1393  };
1394  PostIncrProxy operator++(int) {
1395  PostIncrProxy proxy(**this);
1396  ++(*this);
1397  return proxy;
1398  }
1399 
1400  friend bool operator==(const ConstIter& a, const ConstIter& b) {
1401  return a.s_ == b.s_ && a.pos_ == b.pos_;
1402  }
1403  friend bool operator!=(const ConstIter& a, const ConstIter& b) {
1404  return !(a == b);
1405  }
1406 
1407  private:
1408  const Streamlike* s_;
1409  typename std::list<value_type>::iterator pos_;
1410  };
1411 
1412  friend std::ostream& operator<<(std::ostream& os, const Streamlike& s) {
1413  os << "[";
1414  typedef typename std::list<value_type>::const_iterator Iter;
1415  const char* sep = "";
1416  for (Iter it = s.remainder_.begin(); it != s.remainder_.end(); ++it) {
1417  os << sep << *it;
1418  sep = ",";
1419  }
1420  os << "]";
1421  return os;
1422  }
1423 
1424  mutable std::list<value_type> remainder_; // modified by iteration
1425 };
1426 
1427 TEST(StreamlikeTest, Iteration) {
1428  const int a[5] = {2, 1, 4, 5, 3};
1429  Streamlike<int> s(a, a + 5);
1430  Streamlike<int>::const_iterator it = s.begin();
1431  const int* ip = a;
1432  while (it != s.end()) {
1433  SCOPED_TRACE(ip - a);
1434  EXPECT_EQ(*ip++, *it++);
1435  }
1436 }
1437 
1438 INSTANTIATE_GTEST_MATCHER_TEST_P(BeginEndDistanceIsTest);
1439 
1440 TEST(BeginEndDistanceIsTest, WorksWithForwardList) {
1441  std::forward_list<int> container;
1442  EXPECT_THAT(container, BeginEndDistanceIs(0));
1443  EXPECT_THAT(container, Not(BeginEndDistanceIs(1)));
1444  container.push_front(0);
1445  EXPECT_THAT(container, Not(BeginEndDistanceIs(0)));
1446  EXPECT_THAT(container, BeginEndDistanceIs(1));
1447  container.push_front(0);
1448  EXPECT_THAT(container, Not(BeginEndDistanceIs(0)));
1449  EXPECT_THAT(container, BeginEndDistanceIs(2));
1450 }
1451 
1452 TEST(BeginEndDistanceIsTest, WorksWithNonStdList) {
1453  const int a[5] = {1, 2, 3, 4, 5};
1454  Streamlike<int> s(a, a + 5);
1455  EXPECT_THAT(s, BeginEndDistanceIs(5));
1456 }
1457 
1458 TEST(BeginEndDistanceIsTest, CanDescribeSelf) {
1459  Matcher<vector<int>> m = BeginEndDistanceIs(2);
1460  EXPECT_EQ("distance between begin() and end() is equal to 2", Describe(m));
1461  EXPECT_EQ("distance between begin() and end() isn't equal to 2",
1462  DescribeNegation(m));
1463 }
1464 
1465 TEST(BeginEndDistanceIsTest, WorksWithMoveOnly) {
1466  ContainerHelper helper;
1467  EXPECT_CALL(helper, Call(BeginEndDistanceIs(2)));
1468  helper.Call(MakeUniquePtrs({1, 2}));
1469 }
1470 
1471 TEST_P(BeginEndDistanceIsTestP, ExplainsResult) {
1472  Matcher<vector<int>> m1 = BeginEndDistanceIs(2);
1473  Matcher<vector<int>> m2 = BeginEndDistanceIs(Lt(2));
1474  Matcher<vector<int>> m3 = BeginEndDistanceIs(AnyOf(0, 3));
1475  Matcher<vector<int>> m4 = BeginEndDistanceIs(GreaterThan(1));
1476  vector<int> container;
1477  EXPECT_EQ("whose distance between begin() and end() 0 doesn't match",
1478  Explain(m1, container));
1479  EXPECT_EQ("whose distance between begin() and end() 0 matches",
1480  Explain(m2, container));
1481  EXPECT_EQ(
1482  "whose distance between begin() and end() 0 matches, which matches (is "
1483  "equal to 0)",
1484  Explain(m3, container));
1485  EXPECT_EQ(
1486  "whose distance between begin() and end() 0 doesn't match, which is 1 "
1487  "less than 1",
1488  Explain(m4, container));
1489  container.push_back(0);
1490  container.push_back(0);
1491  EXPECT_EQ("whose distance between begin() and end() 2 matches",
1492  Explain(m1, container));
1493  EXPECT_EQ("whose distance between begin() and end() 2 doesn't match",
1494  Explain(m2, container));
1495  EXPECT_EQ(
1496  "whose distance between begin() and end() 2 doesn't match, isn't equal "
1497  "to 0, and isn't equal to 3",
1498  Explain(m3, container));
1499  EXPECT_EQ(
1500  "whose distance between begin() and end() 2 matches, which is 1 more "
1501  "than 1",
1502  Explain(m4, container));
1503 }
1504 
1505 TEST(WhenSortedTest, WorksForStreamlike) {
1506  // Streamlike 'container' provides only minimal iterator support.
1507  // Its iterators are tagged with input_iterator_tag.
1508  const int a[5] = {2, 1, 4, 5, 3};
1509  Streamlike<int> s(std::begin(a), std::end(a));
1510  EXPECT_THAT(s, WhenSorted(ElementsAre(1, 2, 3, 4, 5)));
1511  EXPECT_THAT(s, Not(WhenSorted(ElementsAre(2, 1, 4, 5, 3))));
1512 }
1513 
1514 TEST(WhenSortedTest, WorksForVectorConstRefMatcherOnStreamlike) {
1515  const int a[] = {2, 1, 4, 5, 3};
1516  Streamlike<int> s(std::begin(a), std::end(a));
1517  Matcher<const std::vector<int>&> vector_match = ElementsAre(1, 2, 3, 4, 5);
1518  EXPECT_THAT(s, WhenSorted(vector_match));
1519  EXPECT_THAT(s, Not(WhenSorted(ElementsAre(2, 1, 4, 5, 3))));
1520 }
1521 
1522 TEST(IsSupersetOfTest, WorksForNativeArray) {
1523  const int subset[] = {1, 4};
1524  const int superset[] = {1, 2, 4};
1525  const int disjoint[] = {1, 0, 3};
1526  EXPECT_THAT(subset, IsSupersetOf(subset));
1527  EXPECT_THAT(subset, Not(IsSupersetOf(superset)));
1528  EXPECT_THAT(superset, IsSupersetOf(subset));
1529  EXPECT_THAT(subset, Not(IsSupersetOf(disjoint)));
1530  EXPECT_THAT(disjoint, Not(IsSupersetOf(subset)));
1531 }
1532 
1533 TEST(IsSupersetOfTest, WorksWithDuplicates) {
1534  const int not_enough[] = {1, 2};
1535  const int enough[] = {1, 1, 2};
1536  const int expected[] = {1, 1};
1537  EXPECT_THAT(not_enough, Not(IsSupersetOf(expected)));
1538  EXPECT_THAT(enough, IsSupersetOf(expected));
1539 }
1540 
1541 TEST(IsSupersetOfTest, WorksForEmpty) {
1542  vector<int> numbers;
1543  vector<int> expected;
1544  EXPECT_THAT(numbers, IsSupersetOf(expected));
1545  expected.push_back(1);
1546  EXPECT_THAT(numbers, Not(IsSupersetOf(expected)));
1547  expected.clear();
1548  numbers.push_back(1);
1549  numbers.push_back(2);
1550  EXPECT_THAT(numbers, IsSupersetOf(expected));
1551  expected.push_back(1);
1552  EXPECT_THAT(numbers, IsSupersetOf(expected));
1553  expected.push_back(2);
1554  EXPECT_THAT(numbers, IsSupersetOf(expected));
1555  expected.push_back(3);
1556  EXPECT_THAT(numbers, Not(IsSupersetOf(expected)));
1557 }
1558 
1559 TEST(IsSupersetOfTest, WorksForStreamlike) {
1560  const int a[5] = {1, 2, 3, 4, 5};
1561  Streamlike<int> s(std::begin(a), std::end(a));
1562 
1563  vector<int> expected;
1564  expected.push_back(1);
1565  expected.push_back(2);
1566  expected.push_back(5);
1567  EXPECT_THAT(s, IsSupersetOf(expected));
1568 
1569  expected.push_back(0);
1570  EXPECT_THAT(s, Not(IsSupersetOf(expected)));
1571 }
1572 
1573 TEST(IsSupersetOfTest, TakesStlContainer) {
1574  const int actual[] = {3, 1, 2};
1575 
1576  ::std::list<int> expected;
1577  expected.push_back(1);
1578  expected.push_back(3);
1579  EXPECT_THAT(actual, IsSupersetOf(expected));
1580 
1581  expected.push_back(4);
1582  EXPECT_THAT(actual, Not(IsSupersetOf(expected)));
1583 }
1584 
1585 TEST(IsSupersetOfTest, Describe) {
1586  typedef std::vector<int> IntVec;
1587  IntVec expected;
1588  expected.push_back(111);
1589  expected.push_back(222);
1590  expected.push_back(333);
1591  EXPECT_THAT(
1592  Describe<IntVec>(IsSupersetOf(expected)),
1593  Eq("a surjection from elements to requirements exists such that:\n"
1594  " - an element is equal to 111\n"
1595  " - an element is equal to 222\n"
1596  " - an element is equal to 333"));
1597 }
1598 
1599 TEST(IsSupersetOfTest, DescribeNegation) {
1600  typedef std::vector<int> IntVec;
1601  IntVec expected;
1602  expected.push_back(111);
1603  expected.push_back(222);
1604  expected.push_back(333);
1605  EXPECT_THAT(
1606  DescribeNegation<IntVec>(IsSupersetOf(expected)),
1607  Eq("no surjection from elements to requirements exists such that:\n"
1608  " - an element is equal to 111\n"
1609  " - an element is equal to 222\n"
1610  " - an element is equal to 333"));
1611 }
1612 
1613 TEST(IsSupersetOfTest, MatchAndExplain) {
1614  std::vector<int> v;
1615  v.push_back(2);
1616  v.push_back(3);
1617  std::vector<int> expected;
1618  expected.push_back(1);
1619  expected.push_back(2);
1620  StringMatchResultListener listener;
1621  ASSERT_FALSE(ExplainMatchResult(IsSupersetOf(expected), v, &listener))
1622  << listener.str();
1623  EXPECT_THAT(listener.str(),
1624  Eq("where the following matchers don't match any elements:\n"
1625  "matcher #0: is equal to 1"));
1626 
1627  v.push_back(1);
1628  listener.Clear();
1629  ASSERT_TRUE(ExplainMatchResult(IsSupersetOf(expected), v, &listener))
1630  << listener.str();
1631  EXPECT_THAT(listener.str(), Eq("where:\n"
1632  " - element #0 is matched by matcher #1,\n"
1633  " - element #2 is matched by matcher #0"));
1634 }
1635 
1636 TEST(IsSupersetOfTest, WorksForRhsInitializerList) {
1637  const int numbers[] = {1, 3, 6, 2, 4, 5};
1638  EXPECT_THAT(numbers, IsSupersetOf({1, 2}));
1639  EXPECT_THAT(numbers, Not(IsSupersetOf({3, 0})));
1640 }
1641 
1642 TEST(IsSupersetOfTest, WorksWithMoveOnly) {
1643  ContainerHelper helper;
1644  EXPECT_CALL(helper, Call(IsSupersetOf({Pointee(1)})));
1645  helper.Call(MakeUniquePtrs({1, 2}));
1646  EXPECT_CALL(helper, Call(Not(IsSupersetOf({Pointee(1), Pointee(2)}))));
1647  helper.Call(MakeUniquePtrs({2}));
1648 }
1649 
1650 TEST(IsSubsetOfTest, WorksForNativeArray) {
1651  const int subset[] = {1, 4};
1652  const int superset[] = {1, 2, 4};
1653  const int disjoint[] = {1, 0, 3};
1654  EXPECT_THAT(subset, IsSubsetOf(subset));
1655  EXPECT_THAT(subset, IsSubsetOf(superset));
1656  EXPECT_THAT(superset, Not(IsSubsetOf(subset)));
1657  EXPECT_THAT(subset, Not(IsSubsetOf(disjoint)));
1658  EXPECT_THAT(disjoint, Not(IsSubsetOf(subset)));
1659 }
1660 
1661 TEST(IsSubsetOfTest, WorksWithDuplicates) {
1662  const int not_enough[] = {1, 2};
1663  const int enough[] = {1, 1, 2};
1664  const int actual[] = {1, 1};
1665  EXPECT_THAT(actual, Not(IsSubsetOf(not_enough)));
1666  EXPECT_THAT(actual, IsSubsetOf(enough));
1667 }
1668 
1669 TEST(IsSubsetOfTest, WorksForEmpty) {
1670  vector<int> numbers;
1671  vector<int> expected;
1672  EXPECT_THAT(numbers, IsSubsetOf(expected));
1673  expected.push_back(1);
1674  EXPECT_THAT(numbers, IsSubsetOf(expected));
1675  expected.clear();
1676  numbers.push_back(1);
1677  numbers.push_back(2);
1678  EXPECT_THAT(numbers, Not(IsSubsetOf(expected)));
1679  expected.push_back(1);
1680  EXPECT_THAT(numbers, Not(IsSubsetOf(expected)));
1681  expected.push_back(2);
1682  EXPECT_THAT(numbers, IsSubsetOf(expected));
1683  expected.push_back(3);
1684  EXPECT_THAT(numbers, IsSubsetOf(expected));
1685 }
1686 
1687 TEST(IsSubsetOfTest, WorksForStreamlike) {
1688  const int a[5] = {1, 2};
1689  Streamlike<int> s(std::begin(a), std::end(a));
1690 
1691  vector<int> expected;
1692  expected.push_back(1);
1693  EXPECT_THAT(s, Not(IsSubsetOf(expected)));
1694  expected.push_back(2);
1695  expected.push_back(5);
1696  EXPECT_THAT(s, IsSubsetOf(expected));
1697 }
1698 
1699 TEST(IsSubsetOfTest, TakesStlContainer) {
1700  const int actual[] = {3, 1, 2};
1701 
1702  ::std::list<int> expected;
1703  expected.push_back(1);
1704  expected.push_back(3);
1705  EXPECT_THAT(actual, Not(IsSubsetOf(expected)));
1706 
1707  expected.push_back(2);
1708  expected.push_back(4);
1709  EXPECT_THAT(actual, IsSubsetOf(expected));
1710 }
1711 
1712 TEST(IsSubsetOfTest, Describe) {
1713  typedef std::vector<int> IntVec;
1714  IntVec expected;
1715  expected.push_back(111);
1716  expected.push_back(222);
1717  expected.push_back(333);
1718 
1719  EXPECT_THAT(
1720  Describe<IntVec>(IsSubsetOf(expected)),
1721  Eq("an injection from elements to requirements exists such that:\n"
1722  " - an element is equal to 111\n"
1723  " - an element is equal to 222\n"
1724  " - an element is equal to 333"));
1725 }
1726 
1727 TEST(IsSubsetOfTest, DescribeNegation) {
1728  typedef std::vector<int> IntVec;
1729  IntVec expected;
1730  expected.push_back(111);
1731  expected.push_back(222);
1732  expected.push_back(333);
1733  EXPECT_THAT(
1734  DescribeNegation<IntVec>(IsSubsetOf(expected)),
1735  Eq("no injection from elements to requirements exists such that:\n"
1736  " - an element is equal to 111\n"
1737  " - an element is equal to 222\n"
1738  " - an element is equal to 333"));
1739 }
1740 
1741 TEST(IsSubsetOfTest, MatchAndExplain) {
1742  std::vector<int> v;
1743  v.push_back(2);
1744  v.push_back(3);
1745  std::vector<int> expected;
1746  expected.push_back(1);
1747  expected.push_back(2);
1748  StringMatchResultListener listener;
1749  ASSERT_FALSE(ExplainMatchResult(IsSubsetOf(expected), v, &listener))
1750  << listener.str();
1751  EXPECT_THAT(listener.str(),
1752  Eq("where the following elements don't match any matchers:\n"
1753  "element #1: 3"));
1754 
1755  expected.push_back(3);
1756  listener.Clear();
1757  ASSERT_TRUE(ExplainMatchResult(IsSubsetOf(expected), v, &listener))
1758  << listener.str();
1759  EXPECT_THAT(listener.str(), Eq("where:\n"
1760  " - element #0 is matched by matcher #1,\n"
1761  " - element #1 is matched by matcher #2"));
1762 }
1763 
1764 TEST(IsSubsetOfTest, WorksForRhsInitializerList) {
1765  const int numbers[] = {1, 2, 3};
1766  EXPECT_THAT(numbers, IsSubsetOf({1, 2, 3, 4}));
1767  EXPECT_THAT(numbers, Not(IsSubsetOf({1, 2})));
1768 }
1769 
1770 TEST(IsSubsetOfTest, WorksWithMoveOnly) {
1771  ContainerHelper helper;
1772  EXPECT_CALL(helper, Call(IsSubsetOf({Pointee(1), Pointee(2)})));
1773  helper.Call(MakeUniquePtrs({1}));
1774  EXPECT_CALL(helper, Call(Not(IsSubsetOf({Pointee(1)}))));
1775  helper.Call(MakeUniquePtrs({2}));
1776 }
1777 
1778 // Tests using ElementsAre() and ElementsAreArray() with stream-like
1779 // "containers".
1780 
1781 TEST(ElemensAreStreamTest, WorksForStreamlike) {
1782  const int a[5] = {1, 2, 3, 4, 5};
1783  Streamlike<int> s(std::begin(a), std::end(a));
1784  EXPECT_THAT(s, ElementsAre(1, 2, 3, 4, 5));
1785  EXPECT_THAT(s, Not(ElementsAre(2, 1, 4, 5, 3)));
1786 }
1787 
1788 TEST(ElemensAreArrayStreamTest, WorksForStreamlike) {
1789  const int a[5] = {1, 2, 3, 4, 5};
1790  Streamlike<int> s(std::begin(a), std::end(a));
1791 
1792  vector<int> expected;
1793  expected.push_back(1);
1794  expected.push_back(2);
1795  expected.push_back(3);
1796  expected.push_back(4);
1797  expected.push_back(5);
1798  EXPECT_THAT(s, ElementsAreArray(expected));
1799 
1800  expected[3] = 0;
1801  EXPECT_THAT(s, Not(ElementsAreArray(expected)));
1802 }
1803 
1804 TEST(ElementsAreTest, WorksWithUncopyable) {
1805  Uncopyable objs[2];
1806  objs[0].set_value(-3);
1807  objs[1].set_value(1);
1808  EXPECT_THAT(objs, ElementsAre(UncopyableIs(-3), Truly(ValueIsPositive)));
1809 }
1810 
1811 TEST(ElementsAreTest, WorksWithMoveOnly) {
1812  ContainerHelper helper;
1813  EXPECT_CALL(helper, Call(ElementsAre(Pointee(1), Pointee(2))));
1814  helper.Call(MakeUniquePtrs({1, 2}));
1815 
1816  EXPECT_CALL(helper, Call(ElementsAreArray({Pointee(3), Pointee(4)})));
1817  helper.Call(MakeUniquePtrs({3, 4}));
1818 }
1819 
1820 TEST(ElementsAreTest, TakesStlContainer) {
1821  const int actual[] = {3, 1, 2};
1822 
1823  ::std::list<int> expected;
1824  expected.push_back(3);
1825  expected.push_back(1);
1826  expected.push_back(2);
1827  EXPECT_THAT(actual, ElementsAreArray(expected));
1828 
1829  expected.push_back(4);
1830  EXPECT_THAT(actual, Not(ElementsAreArray(expected)));
1831 }
1832 
1833 // Tests for UnorderedElementsAreArray()
1834 
1835 TEST(UnorderedElementsAreArrayTest, SucceedsWhenExpected) {
1836  const int a[] = {0, 1, 2, 3, 4};
1837  std::vector<int> s(std::begin(a), std::end(a));
1838  do {
1839  StringMatchResultListener listener;
1840  EXPECT_TRUE(ExplainMatchResult(UnorderedElementsAreArray(a), s, &listener))
1841  << listener.str();
1842  } while (std::next_permutation(s.begin(), s.end()));
1843 }
1844 
1845 TEST(UnorderedElementsAreArrayTest, VectorBool) {
1846  const bool a[] = {false, true, false, true, true};
1847  const bool b[] = {true, false, true, true, false};
1848  std::vector<bool> expected(std::begin(a), std::end(a));
1849  std::vector<bool> actual(std::begin(b), std::end(b));
1850  StringMatchResultListener listener;
1851  EXPECT_TRUE(ExplainMatchResult(UnorderedElementsAreArray(expected), actual,
1852  &listener))
1853  << listener.str();
1854 }
1855 
1856 TEST(UnorderedElementsAreArrayTest, WorksForStreamlike) {
1857  // Streamlike 'container' provides only minimal iterator support.
1858  // Its iterators are tagged with input_iterator_tag, and it has no
1859  // size() or empty() methods.
1860  const int a[5] = {2, 1, 4, 5, 3};
1861  Streamlike<int> s(std::begin(a), std::end(a));
1862 
1863  ::std::vector<int> expected;
1864  expected.push_back(1);
1865  expected.push_back(2);
1866  expected.push_back(3);
1867  expected.push_back(4);
1868  expected.push_back(5);
1869  EXPECT_THAT(s, UnorderedElementsAreArray(expected));
1870 
1871  expected.push_back(6);
1872  EXPECT_THAT(s, Not(UnorderedElementsAreArray(expected)));
1873 }
1874 
1875 TEST(UnorderedElementsAreArrayTest, TakesStlContainer) {
1876  const int actual[] = {3, 1, 2};
1877 
1878  ::std::list<int> expected;
1879  expected.push_back(1);
1880  expected.push_back(2);
1881  expected.push_back(3);
1882  EXPECT_THAT(actual, UnorderedElementsAreArray(expected));
1883 
1884  expected.push_back(4);
1885  EXPECT_THAT(actual, Not(UnorderedElementsAreArray(expected)));
1886 }
1887 
1888 TEST(UnorderedElementsAreArrayTest, TakesInitializerList) {
1889  const int a[5] = {2, 1, 4, 5, 3};
1890  EXPECT_THAT(a, UnorderedElementsAreArray({1, 2, 3, 4, 5}));
1891  EXPECT_THAT(a, Not(UnorderedElementsAreArray({1, 2, 3, 4, 6})));
1892 }
1893 
1894 TEST(UnorderedElementsAreArrayTest, TakesInitializerListOfCStrings) {
1895  const std::string a[5] = {"a", "b", "c", "d", "e"};
1896  EXPECT_THAT(a, UnorderedElementsAreArray({"a", "b", "c", "d", "e"}));
1897  EXPECT_THAT(a, Not(UnorderedElementsAreArray({"a", "b", "c", "d", "ef"})));
1898 }
1899 
1900 TEST(UnorderedElementsAreArrayTest, TakesInitializerListOfSameTypedMatchers) {
1901  const int a[5] = {2, 1, 4, 5, 3};
1902  EXPECT_THAT(a,
1903  UnorderedElementsAreArray({Eq(1), Eq(2), Eq(3), Eq(4), Eq(5)}));
1904  EXPECT_THAT(
1905  a, Not(UnorderedElementsAreArray({Eq(1), Eq(2), Eq(3), Eq(4), Eq(6)})));
1906 }
1907 
1908 TEST(UnorderedElementsAreArrayTest,
1909  TakesInitializerListOfDifferentTypedMatchers) {
1910  const int a[5] = {2, 1, 4, 5, 3};
1911  // The compiler cannot infer the type of the initializer list if its
1912  // elements have different types. We must explicitly specify the
1913  // unified element type in this case.
1914  EXPECT_THAT(a, UnorderedElementsAreArray<Matcher<int>>(
1915  {Eq(1), Ne(-2), Ge(3), Le(4), Eq(5)}));
1916  EXPECT_THAT(a, Not(UnorderedElementsAreArray<Matcher<int>>(
1917  {Eq(1), Ne(-2), Ge(3), Le(4), Eq(6)})));
1918 }
1919 
1920 TEST(UnorderedElementsAreArrayTest, WorksWithMoveOnly) {
1921  ContainerHelper helper;
1922  EXPECT_CALL(helper,
1923  Call(UnorderedElementsAreArray({Pointee(1), Pointee(2)})));
1924  helper.Call(MakeUniquePtrs({2, 1}));
1925 }
1926 
1927 class UnorderedElementsAreTest : public testing::Test {
1928  protected:
1929  typedef std::vector<int> IntVec;
1930 };
1931 
1932 TEST_F(UnorderedElementsAreTest, WorksWithUncopyable) {
1933  Uncopyable objs[2];
1934  objs[0].set_value(-3);
1935  objs[1].set_value(1);
1936  EXPECT_THAT(objs,
1937  UnorderedElementsAre(Truly(ValueIsPositive), UncopyableIs(-3)));
1938 }
1939 
1940 TEST_F(UnorderedElementsAreTest, SucceedsWhenExpected) {
1941  const int a[] = {1, 2, 3};
1942  std::vector<int> s(std::begin(a), std::end(a));
1943  do {
1944  StringMatchResultListener listener;
1945  EXPECT_TRUE(ExplainMatchResult(UnorderedElementsAre(1, 2, 3), s, &listener))
1946  << listener.str();
1947  } while (std::next_permutation(s.begin(), s.end()));
1948 }
1949 
1950 TEST_F(UnorderedElementsAreTest, FailsWhenAnElementMatchesNoMatcher) {
1951  const int a[] = {1, 2, 3};
1952  std::vector<int> s(std::begin(a), std::end(a));
1953  std::vector<Matcher<int>> mv;
1954  mv.push_back(1);
1955  mv.push_back(2);
1956  mv.push_back(2);
1957  // The element with value '3' matches nothing: fail fast.
1958  StringMatchResultListener listener;
1959  EXPECT_FALSE(ExplainMatchResult(UnorderedElementsAreArray(mv), s, &listener))
1960  << listener.str();
1961 }
1962 
1963 TEST_F(UnorderedElementsAreTest, WorksForStreamlike) {
1964  // Streamlike 'container' provides only minimal iterator support.
1965  // Its iterators are tagged with input_iterator_tag, and it has no
1966  // size() or empty() methods.
1967  const int a[5] = {2, 1, 4, 5, 3};
1968  Streamlike<int> s(std::begin(a), std::end(a));
1969 
1970  EXPECT_THAT(s, UnorderedElementsAre(1, 2, 3, 4, 5));
1971  EXPECT_THAT(s, Not(UnorderedElementsAre(2, 2, 3, 4, 5)));
1972 }
1973 
1974 TEST_F(UnorderedElementsAreTest, WorksWithMoveOnly) {
1975  ContainerHelper helper;
1976  EXPECT_CALL(helper, Call(UnorderedElementsAre(Pointee(1), Pointee(2))));
1977  helper.Call(MakeUniquePtrs({2, 1}));
1978 }
1979 
1980 // One naive implementation of the matcher runs in O(N!) time, which is too
1981 // slow for many real-world inputs. This test shows that our matcher can match
1982 // 100 inputs very quickly (a few milliseconds). An O(100!) is 10^158
1983 // iterations and obviously effectively incomputable.
1984 // [ RUN ] UnorderedElementsAreTest.Performance
1985 // [ OK ] UnorderedElementsAreTest.Performance (4 ms)
1986 TEST_F(UnorderedElementsAreTest, Performance) {
1987  std::vector<int> s;
1988  std::vector<Matcher<int>> mv;
1989  for (int i = 0; i < 100; ++i) {
1990  s.push_back(i);
1991  mv.push_back(_);
1992  }
1993  mv[50] = Eq(0);
1994  StringMatchResultListener listener;
1995  EXPECT_TRUE(ExplainMatchResult(UnorderedElementsAreArray(mv), s, &listener))
1996  << listener.str();
1997 }
1998 
1999 // Another variant of 'Performance' with similar expectations.
2000 // [ RUN ] UnorderedElementsAreTest.PerformanceHalfStrict
2001 // [ OK ] UnorderedElementsAreTest.PerformanceHalfStrict (4 ms)
2002 TEST_F(UnorderedElementsAreTest, PerformanceHalfStrict) {
2003  std::vector<int> s;
2004  std::vector<Matcher<int>> mv;
2005  for (int i = 0; i < 100; ++i) {
2006  s.push_back(i);
2007  if (i & 1) {
2008  mv.push_back(_);
2009  } else {
2010  mv.push_back(i);
2011  }
2012  }
2013  StringMatchResultListener listener;
2014  EXPECT_TRUE(ExplainMatchResult(UnorderedElementsAreArray(mv), s, &listener))
2015  << listener.str();
2016 }
2017 
2018 TEST_F(UnorderedElementsAreTest, FailMessageCountWrong) {
2019  std::vector<int> v;
2020  v.push_back(4);
2021  StringMatchResultListener listener;
2022  EXPECT_FALSE(ExplainMatchResult(UnorderedElementsAre(1, 2, 3), v, &listener))
2023  << listener.str();
2024  EXPECT_THAT(listener.str(),
2025  Eq("which has 1 element\n"
2026  "where the following matchers don't match any elements:\n"
2027  "matcher #0: is equal to 1,\n"
2028  "matcher #1: is equal to 2,\n"
2029  "matcher #2: is equal to 3\n"
2030  "and where the following elements don't match any matchers:\n"
2031  "element #0: 4"));
2032 }
2033 
2034 TEST_F(UnorderedElementsAreTest, FailMessageCountWrongZero) {
2035  std::vector<int> v;
2036  StringMatchResultListener listener;
2037  EXPECT_FALSE(ExplainMatchResult(UnorderedElementsAre(1, 2, 3), v, &listener))
2038  << listener.str();
2039  EXPECT_THAT(listener.str(),
2040  Eq("where the following matchers don't match any elements:\n"
2041  "matcher #0: is equal to 1,\n"
2042  "matcher #1: is equal to 2,\n"
2043  "matcher #2: is equal to 3"));
2044 }
2045 
2046 TEST_F(UnorderedElementsAreTest, FailMessageUnmatchedMatchers) {
2047  std::vector<int> v;
2048  v.push_back(1);
2049  v.push_back(1);
2050  StringMatchResultListener listener;
2051  EXPECT_FALSE(ExplainMatchResult(UnorderedElementsAre(1, 2), v, &listener))
2052  << listener.str();
2053  EXPECT_THAT(listener.str(),
2054  Eq("where the following matchers don't match any elements:\n"
2055  "matcher #1: is equal to 2"));
2056 }
2057 
2058 TEST_F(UnorderedElementsAreTest, FailMessageUnmatchedElements) {
2059  std::vector<int> v;
2060  v.push_back(1);
2061  v.push_back(2);
2062  StringMatchResultListener listener;
2063  EXPECT_FALSE(ExplainMatchResult(UnorderedElementsAre(1, 1), v, &listener))
2064  << listener.str();
2065  EXPECT_THAT(listener.str(),
2066  Eq("where the following elements don't match any matchers:\n"
2067  "element #1: 2"));
2068 }
2069 
2070 TEST_F(UnorderedElementsAreTest, FailMessageUnmatchedMatcherAndElement) {
2071  std::vector<int> v;
2072  v.push_back(2);
2073  v.push_back(3);
2074  StringMatchResultListener listener;
2075  EXPECT_FALSE(ExplainMatchResult(UnorderedElementsAre(1, 2), v, &listener))
2076  << listener.str();
2077  EXPECT_THAT(listener.str(),
2078  Eq("where"
2079  " the following matchers don't match any elements:\n"
2080  "matcher #0: is equal to 1\n"
2081  "and"
2082  " where"
2083  " the following elements don't match any matchers:\n"
2084  "element #1: 3"));
2085 }
2086 
2087 // Test helper for formatting element, matcher index pairs in expectations.
2088 static std::string EMString(int element, int matcher) {
2089  stringstream ss;
2090  ss << "(element #" << element << ", matcher #" << matcher << ")";
2091  return ss.str();
2092 }
2093 
2094 TEST_F(UnorderedElementsAreTest, FailMessageImperfectMatchOnly) {
2095  // A situation where all elements and matchers have a match
2096  // associated with them, but the max matching is not perfect.
2097  std::vector<std::string> v;
2098  v.push_back("a");
2099  v.push_back("b");
2100  v.push_back("c");
2101  StringMatchResultListener listener;
2102  EXPECT_FALSE(ExplainMatchResult(
2103  UnorderedElementsAre("a", "a", AnyOf("b", "c")), v, &listener))
2104  << listener.str();
2105 
2106  std::string prefix =
2107  "where no permutation of the elements can satisfy all matchers, "
2108  "and the closest match is 2 of 3 matchers with the "
2109  "pairings:\n";
2110 
2111  // We have to be a bit loose here, because there are 4 valid max matches.
2112  EXPECT_THAT(
2113  listener.str(),
2114  AnyOf(
2115  prefix + "{\n " + EMString(0, 0) + ",\n " + EMString(1, 2) + "\n}",
2116  prefix + "{\n " + EMString(0, 1) + ",\n " + EMString(1, 2) + "\n}",
2117  prefix + "{\n " + EMString(0, 0) + ",\n " + EMString(2, 2) + "\n}",
2118  prefix + "{\n " + EMString(0, 1) + ",\n " + EMString(2, 2) +
2119  "\n}"));
2120 }
2121 
2122 TEST_F(UnorderedElementsAreTest, Describe) {
2123  EXPECT_THAT(Describe<IntVec>(UnorderedElementsAre()), Eq("is empty"));
2124  EXPECT_THAT(Describe<IntVec>(UnorderedElementsAre(345)),
2125  Eq("has 1 element and that element is equal to 345"));
2126  EXPECT_THAT(Describe<IntVec>(UnorderedElementsAre(111, 222, 333)),
2127  Eq("has 3 elements and there exists some permutation "
2128  "of elements such that:\n"
2129  " - element #0 is equal to 111, and\n"
2130  " - element #1 is equal to 222, and\n"
2131  " - element #2 is equal to 333"));
2132 }
2133 
2134 TEST_F(UnorderedElementsAreTest, DescribeNegation) {
2135  EXPECT_THAT(DescribeNegation<IntVec>(UnorderedElementsAre()),
2136  Eq("isn't empty"));
2137  EXPECT_THAT(
2138  DescribeNegation<IntVec>(UnorderedElementsAre(345)),
2139  Eq("doesn't have 1 element, or has 1 element that isn't equal to 345"));
2140  EXPECT_THAT(DescribeNegation<IntVec>(UnorderedElementsAre(123, 234, 345)),
2141  Eq("doesn't have 3 elements, or there exists no permutation "
2142  "of elements such that:\n"
2143  " - element #0 is equal to 123, and\n"
2144  " - element #1 is equal to 234, and\n"
2145  " - element #2 is equal to 345"));
2146 }
2147 
2148 // Tests Each().
2149 
2151 
2152 TEST_P(EachTestP, ExplainsMatchResultCorrectly) {
2153  set<int> a; // empty
2154 
2155  Matcher<set<int>> m = Each(2);
2156  EXPECT_EQ("", Explain(m, a));
2157 
2158  Matcher<const int(&)[1]> n = Each(1); // NOLINT
2159 
2160  const int b[1] = {1};
2161  EXPECT_EQ("", Explain(n, b));
2162 
2163  n = Each(3);
2164  EXPECT_EQ("whose element #0 doesn't match", Explain(n, b));
2165 
2166  a.insert(1);
2167  a.insert(2);
2168  a.insert(3);
2169  m = Each(GreaterThan(0));
2170  EXPECT_EQ("", Explain(m, a));
2171 
2172  m = Each(GreaterThan(10));
2173  EXPECT_EQ("whose element #0 doesn't match, which is 9 less than 10",
2174  Explain(m, a));
2175 }
2176 
2177 TEST(EachTest, DescribesItselfCorrectly) {
2178  Matcher<vector<int>> m = Each(1);
2179  EXPECT_EQ("only contains elements that is equal to 1", Describe(m));
2180 
2181  Matcher<vector<int>> m2 = Not(m);
2182  EXPECT_EQ("contains some element that isn't equal to 1", Describe(m2));
2183 }
2184 
2185 TEST(EachTest, MatchesVectorWhenAllElementsMatch) {
2186  vector<int> some_vector;
2187  EXPECT_THAT(some_vector, Each(1));
2188  some_vector.push_back(3);
2189  EXPECT_THAT(some_vector, Not(Each(1)));
2190  EXPECT_THAT(some_vector, Each(3));
2191  some_vector.push_back(1);
2192  some_vector.push_back(2);
2193  EXPECT_THAT(some_vector, Not(Each(3)));
2194  EXPECT_THAT(some_vector, Each(Lt(3.5)));
2195 
2196  vector<std::string> another_vector;
2197  another_vector.push_back("fee");
2198  EXPECT_THAT(another_vector, Each(std::string("fee")));
2199  another_vector.push_back("fie");
2200  another_vector.push_back("foe");
2201  another_vector.push_back("fum");
2202  EXPECT_THAT(another_vector, Not(Each(std::string("fee"))));
2203 }
2204 
2205 TEST(EachTest, MatchesMapWhenAllElementsMatch) {
2206  map<const char*, int> my_map;
2207  const char* bar = "a string";
2208  my_map[bar] = 2;
2209  EXPECT_THAT(my_map, Each(make_pair(bar, 2)));
2210 
2211  map<std::string, int> another_map;
2212  EXPECT_THAT(another_map, Each(make_pair(std::string("fee"), 1)));
2213  another_map["fee"] = 1;
2214  EXPECT_THAT(another_map, Each(make_pair(std::string("fee"), 1)));
2215  another_map["fie"] = 2;
2216  another_map["foe"] = 3;
2217  another_map["fum"] = 4;
2218  EXPECT_THAT(another_map, Not(Each(make_pair(std::string("fee"), 1))));
2219  EXPECT_THAT(another_map, Not(Each(make_pair(std::string("fum"), 1))));
2220  EXPECT_THAT(another_map, Each(Pair(_, Gt(0))));
2221 }
2222 
2223 TEST(EachTest, AcceptsMatcher) {
2224  const int a[] = {1, 2, 3};
2225  EXPECT_THAT(a, Each(Gt(0)));
2226  EXPECT_THAT(a, Not(Each(Gt(1))));
2227 }
2228 
2229 TEST(EachTest, WorksForNativeArrayAsTuple) {
2230  const int a[] = {1, 2};
2231  const int* const pointer = a;
2232  EXPECT_THAT(std::make_tuple(pointer, 2), Each(Gt(0)));
2233  EXPECT_THAT(std::make_tuple(pointer, 2), Not(Each(Gt(1))));
2234 }
2235 
2236 TEST(EachTest, WorksWithMoveOnly) {
2237  ContainerHelper helper;
2238  EXPECT_CALL(helper, Call(Each(Pointee(Gt(0)))));
2239  helper.Call(MakeUniquePtrs({1, 2}));
2240 }
2241 
2242 // For testing Pointwise().
2243 class IsHalfOfMatcher {
2244  public:
2245  template <typename T1, typename T2>
2246  bool MatchAndExplain(const std::tuple<T1, T2>& a_pair,
2247  MatchResultListener* listener) const {
2248  if (std::get<0>(a_pair) == std::get<1>(a_pair) / 2) {
2249  *listener << "where the second is " << std::get<1>(a_pair);
2250  return true;
2251  } else {
2252  *listener << "where the second/2 is " << std::get<1>(a_pair) / 2;
2253  return false;
2254  }
2255  }
2256 
2257  void DescribeTo(ostream* os) const {
2258  *os << "are a pair where the first is half of the second";
2259  }
2260 
2261  void DescribeNegationTo(ostream* os) const {
2262  *os << "are a pair where the first isn't half of the second";
2263  }
2264 };
2265 
2266 PolymorphicMatcher<IsHalfOfMatcher> IsHalfOf() {
2267  return MakePolymorphicMatcher(IsHalfOfMatcher());
2268 }
2269 
2270 TEST(PointwiseTest, DescribesSelf) {
2271  vector<int> rhs;
2272  rhs.push_back(1);
2273  rhs.push_back(2);
2274  rhs.push_back(3);
2275  const Matcher<const vector<int>&> m = Pointwise(IsHalfOf(), rhs);
2276  EXPECT_EQ(
2277  "contains 3 values, where each value and its corresponding value "
2278  "in { 1, 2, 3 } are a pair where the first is half of the second",
2279  Describe(m));
2280  EXPECT_EQ(
2281  "doesn't contain exactly 3 values, or contains a value x at some "
2282  "index i where x and the i-th value of { 1, 2, 3 } are a pair "
2283  "where the first isn't half of the second",
2284  DescribeNegation(m));
2285 }
2286 
2287 TEST(PointwiseTest, MakesCopyOfRhs) {
2288  list<signed char> rhs;
2289  rhs.push_back(2);
2290  rhs.push_back(4);
2291 
2292  int lhs[] = {1, 2};
2293  const Matcher<const int(&)[2]> m = Pointwise(IsHalfOf(), rhs);
2294  EXPECT_THAT(lhs, m);
2295 
2296  // Changing rhs now shouldn't affect m, which made a copy of rhs.
2297  rhs.push_back(6);
2298  EXPECT_THAT(lhs, m);
2299 }
2300 
2301 TEST(PointwiseTest, WorksForLhsNativeArray) {
2302  const int lhs[] = {1, 2, 3};
2303  vector<int> rhs;
2304  rhs.push_back(2);
2305  rhs.push_back(4);
2306  rhs.push_back(6);
2307  EXPECT_THAT(lhs, Pointwise(Lt(), rhs));
2308  EXPECT_THAT(lhs, Not(Pointwise(Gt(), rhs)));
2309 }
2310 
2311 TEST(PointwiseTest, WorksForRhsNativeArray) {
2312  const int rhs[] = {1, 2, 3};
2313  vector<int> lhs;
2314  lhs.push_back(2);
2315  lhs.push_back(4);
2316  lhs.push_back(6);
2317  EXPECT_THAT(lhs, Pointwise(Gt(), rhs));
2318  EXPECT_THAT(lhs, Not(Pointwise(Lt(), rhs)));
2319 }
2320 
2321 // Test is effective only with sanitizers.
2322 TEST(PointwiseTest, WorksForVectorOfBool) {
2323  vector<bool> rhs(3, false);
2324  rhs[1] = true;
2325  vector<bool> lhs = rhs;
2326  EXPECT_THAT(lhs, Pointwise(Eq(), rhs));
2327  rhs[0] = true;
2328  EXPECT_THAT(lhs, Not(Pointwise(Eq(), rhs)));
2329 }
2330 
2331 TEST(PointwiseTest, WorksForRhsInitializerList) {
2332  const vector<int> lhs{2, 4, 6};
2333  EXPECT_THAT(lhs, Pointwise(Gt(), {1, 2, 3}));
2334  EXPECT_THAT(lhs, Not(Pointwise(Lt(), {3, 3, 7})));
2335 }
2336 
2337 TEST(PointwiseTest, RejectsWrongSize) {
2338  const double lhs[2] = {1, 2};
2339  const int rhs[1] = {0};
2340  EXPECT_THAT(lhs, Not(Pointwise(Gt(), rhs)));
2341  EXPECT_EQ("which contains 2 values", Explain(Pointwise(Gt(), rhs), lhs));
2342 
2343  const int rhs2[3] = {0, 1, 2};
2344  EXPECT_THAT(lhs, Not(Pointwise(Gt(), rhs2)));
2345 }
2346 
2347 TEST(PointwiseTest, RejectsWrongContent) {
2348  const double lhs[3] = {1, 2, 3};
2349  const int rhs[3] = {2, 6, 4};
2350  EXPECT_THAT(lhs, Not(Pointwise(IsHalfOf(), rhs)));
2351  EXPECT_EQ(
2352  "where the value pair (2, 6) at index #1 don't match, "
2353  "where the second/2 is 3",
2354  Explain(Pointwise(IsHalfOf(), rhs), lhs));
2355 }
2356 
2357 TEST(PointwiseTest, AcceptsCorrectContent) {
2358  const double lhs[3] = {1, 2, 3};
2359  const int rhs[3] = {2, 4, 6};
2360  EXPECT_THAT(lhs, Pointwise(IsHalfOf(), rhs));
2361  EXPECT_EQ("", Explain(Pointwise(IsHalfOf(), rhs), lhs));
2362 }
2363 
2364 TEST(PointwiseTest, AllowsMonomorphicInnerMatcher) {
2365  const double lhs[3] = {1, 2, 3};
2366  const int rhs[3] = {2, 4, 6};
2367  const Matcher<std::tuple<const double&, const int&>> m1 = IsHalfOf();
2368  EXPECT_THAT(lhs, Pointwise(m1, rhs));
2369  EXPECT_EQ("", Explain(Pointwise(m1, rhs), lhs));
2370 
2371  // This type works as a std::tuple<const double&, const int&> can be
2372  // implicitly cast to std::tuple<double, int>.
2373  const Matcher<std::tuple<double, int>> m2 = IsHalfOf();
2374  EXPECT_THAT(lhs, Pointwise(m2, rhs));
2375  EXPECT_EQ("", Explain(Pointwise(m2, rhs), lhs));
2376 }
2377 
2378 MATCHER(PointeeEquals, "Points to an equal value") {
2379  return ExplainMatchResult(::testing::Pointee(::testing::get<1>(arg)),
2380  ::testing::get<0>(arg), result_listener);
2381 }
2382 
2383 TEST(PointwiseTest, WorksWithMoveOnly) {
2384  ContainerHelper helper;
2385  EXPECT_CALL(helper, Call(Pointwise(PointeeEquals(), std::vector<int>{1, 2})));
2386  helper.Call(MakeUniquePtrs({1, 2}));
2387 }
2388 
2389 TEST(UnorderedPointwiseTest, DescribesSelf) {
2390  vector<int> rhs;
2391  rhs.push_back(1);
2392  rhs.push_back(2);
2393  rhs.push_back(3);
2394  const Matcher<const vector<int>&> m = UnorderedPointwise(IsHalfOf(), rhs);
2395  EXPECT_EQ(
2396  "has 3 elements and there exists some permutation of elements such "
2397  "that:\n"
2398  " - element #0 and 1 are a pair where the first is half of the second, "
2399  "and\n"
2400  " - element #1 and 2 are a pair where the first is half of the second, "
2401  "and\n"
2402  " - element #2 and 3 are a pair where the first is half of the second",
2403  Describe(m));
2404  EXPECT_EQ(
2405  "doesn't have 3 elements, or there exists no permutation of elements "
2406  "such that:\n"
2407  " - element #0 and 1 are a pair where the first is half of the second, "
2408  "and\n"
2409  " - element #1 and 2 are a pair where the first is half of the second, "
2410  "and\n"
2411  " - element #2 and 3 are a pair where the first is half of the second",
2412  DescribeNegation(m));
2413 }
2414 
2415 TEST(UnorderedPointwiseTest, MakesCopyOfRhs) {
2416  list<signed char> rhs;
2417  rhs.push_back(2);
2418  rhs.push_back(4);
2419 
2420  int lhs[] = {2, 1};
2421  const Matcher<const int(&)[2]> m = UnorderedPointwise(IsHalfOf(), rhs);
2422  EXPECT_THAT(lhs, m);
2423 
2424  // Changing rhs now shouldn't affect m, which made a copy of rhs.
2425  rhs.push_back(6);
2426  EXPECT_THAT(lhs, m);
2427 }
2428 
2429 TEST(UnorderedPointwiseTest, WorksForLhsNativeArray) {
2430  const int lhs[] = {1, 2, 3};
2431  vector<int> rhs;
2432  rhs.push_back(4);
2433  rhs.push_back(6);
2434  rhs.push_back(2);
2435  EXPECT_THAT(lhs, UnorderedPointwise(Lt(), rhs));
2436  EXPECT_THAT(lhs, Not(UnorderedPointwise(Gt(), rhs)));
2437 }
2438 
2439 TEST(UnorderedPointwiseTest, WorksForRhsNativeArray) {
2440  const int rhs[] = {1, 2, 3};
2441  vector<int> lhs;
2442  lhs.push_back(4);
2443  lhs.push_back(2);
2444  lhs.push_back(6);
2445  EXPECT_THAT(lhs, UnorderedPointwise(Gt(), rhs));
2446  EXPECT_THAT(lhs, Not(UnorderedPointwise(Lt(), rhs)));
2447 }
2448 
2449 TEST(UnorderedPointwiseTest, WorksForRhsInitializerList) {
2450  const vector<int> lhs{2, 4, 6};
2451  EXPECT_THAT(lhs, UnorderedPointwise(Gt(), {5, 1, 3}));
2452  EXPECT_THAT(lhs, Not(UnorderedPointwise(Lt(), {1, 1, 7})));
2453 }
2454 
2455 TEST(UnorderedPointwiseTest, RejectsWrongSize) {
2456  const double lhs[2] = {1, 2};
2457  const int rhs[1] = {0};
2458  EXPECT_THAT(lhs, Not(UnorderedPointwise(Gt(), rhs)));
2459  EXPECT_EQ("which has 2 elements\n",
2460  Explain(UnorderedPointwise(Gt(), rhs), lhs));
2461 
2462  const int rhs2[3] = {0, 1, 2};
2463  EXPECT_THAT(lhs, Not(UnorderedPointwise(Gt(), rhs2)));
2464 }
2465 
2466 TEST(UnorderedPointwiseTest, RejectsWrongContent) {
2467  const double lhs[3] = {1, 2, 3};
2468  const int rhs[3] = {2, 6, 6};
2469  EXPECT_THAT(lhs, Not(UnorderedPointwise(IsHalfOf(), rhs)));
2470  EXPECT_EQ(
2471  "where the following elements don't match any matchers:\n"
2472  "element #1: 2",
2473  Explain(UnorderedPointwise(IsHalfOf(), rhs), lhs));
2474 }
2475 
2476 TEST(UnorderedPointwiseTest, AcceptsCorrectContentInSameOrder) {
2477  const double lhs[3] = {1, 2, 3};
2478  const int rhs[3] = {2, 4, 6};
2479  EXPECT_THAT(lhs, UnorderedPointwise(IsHalfOf(), rhs));
2480 }
2481 
2482 TEST(UnorderedPointwiseTest, AcceptsCorrectContentInDifferentOrder) {
2483  const double lhs[3] = {1, 2, 3};
2484  const int rhs[3] = {6, 4, 2};
2485  EXPECT_THAT(lhs, UnorderedPointwise(IsHalfOf(), rhs));
2486 }
2487 
2488 TEST(UnorderedPointwiseTest, AllowsMonomorphicInnerMatcher) {
2489  const double lhs[3] = {1, 2, 3};
2490  const int rhs[3] = {4, 6, 2};
2491  const Matcher<std::tuple<const double&, const int&>> m1 = IsHalfOf();
2492  EXPECT_THAT(lhs, UnorderedPointwise(m1, rhs));
2493 
2494  // This type works as a std::tuple<const double&, const int&> can be
2495  // implicitly cast to std::tuple<double, int>.
2496  const Matcher<std::tuple<double, int>> m2 = IsHalfOf();
2497  EXPECT_THAT(lhs, UnorderedPointwise(m2, rhs));
2498 }
2499 
2500 TEST(UnorderedPointwiseTest, WorksWithMoveOnly) {
2501  ContainerHelper helper;
2502  EXPECT_CALL(helper, Call(UnorderedPointwise(PointeeEquals(),
2503  std::vector<int>{1, 2})));
2504  helper.Call(MakeUniquePtrs({2, 1}));
2505 }
2506 
2507 TEST(PointeeTest, WorksOnMoveOnlyType) {
2508  std::unique_ptr<int> p(new int(3));
2509  EXPECT_THAT(p, Pointee(Eq(3)));
2510  EXPECT_THAT(p, Not(Pointee(Eq(2))));
2511 }
2512 
2513 class PredicateFormatterFromMatcherTest : public ::testing::Test {
2514  protected:
2515  enum Behavior { kInitialSuccess, kAlwaysFail, kFlaky };
2516 
2517  // A matcher that can return different results when used multiple times on the
2518  // same input. No real matcher should do this; but this lets us test that we
2519  // detect such behavior and fail appropriately.
2520  class MockMatcher : public MatcherInterface<Behavior> {
2521  public:
2522  bool MatchAndExplain(Behavior behavior,
2523  MatchResultListener* listener) const override {
2524  *listener << "[MatchAndExplain]";
2525  switch (behavior) {
2526  case kInitialSuccess:
2527  // The first call to MatchAndExplain should use a "not interested"
2528  // listener; so this is expected to return |true|. There should be no
2529  // subsequent calls.
2530  return !listener->IsInterested();
2531 
2532  case kAlwaysFail:
2533  return false;
2534 
2535  case kFlaky:
2536  // The first call to MatchAndExplain should use a "not interested"
2537  // listener; so this will return |false|. Subsequent calls should have
2538  // an "interested" listener; so this will return |true|, thus
2539  // simulating a flaky matcher.
2540  return listener->IsInterested();
2541  }
2542 
2543  GTEST_LOG_(FATAL) << "This should never be reached";
2544  return false;
2545  }
2546 
2547  void DescribeTo(ostream* os) const override { *os << "[DescribeTo]"; }
2548 
2549  void DescribeNegationTo(ostream* os) const override {
2550  *os << "[DescribeNegationTo]";
2551  }
2552  };
2553 
2554  AssertionResult RunPredicateFormatter(Behavior behavior) {
2555  auto matcher = MakeMatcher(new MockMatcher);
2556  PredicateFormatterFromMatcher<Matcher<Behavior>> predicate_formatter(
2557  matcher);
2558  return predicate_formatter("dummy-name", behavior);
2559  }
2560 };
2561 
2562 TEST_F(PredicateFormatterFromMatcherTest, ShortCircuitOnSuccess) {
2563  AssertionResult result = RunPredicateFormatter(kInitialSuccess);
2564  EXPECT_TRUE(result); // Implicit cast to bool.
2565  std::string expect;
2566  EXPECT_EQ(expect, result.message());
2567 }
2568 
2569 TEST_F(PredicateFormatterFromMatcherTest, NoShortCircuitOnFailure) {
2570  AssertionResult result = RunPredicateFormatter(kAlwaysFail);
2571  EXPECT_FALSE(result); // Implicit cast to bool.
2572  std::string expect =
2573  "Value of: dummy-name\nExpected: [DescribeTo]\n"
2574  " Actual: 1" +
2575  OfType(internal::GetTypeName<Behavior>()) + ", [MatchAndExplain]";
2576  EXPECT_EQ(expect, result.message());
2577 }
2578 
2579 TEST_F(PredicateFormatterFromMatcherTest, DetectsFlakyShortCircuit) {
2580  AssertionResult result = RunPredicateFormatter(kFlaky);
2581  EXPECT_FALSE(result); // Implicit cast to bool.
2582  std::string expect =
2583  "Value of: dummy-name\nExpected: [DescribeTo]\n"
2584  " The matcher failed on the initial attempt; but passed when rerun to "
2585  "generate the explanation.\n"
2586  " Actual: 2" +
2587  OfType(internal::GetTypeName<Behavior>()) + ", [MatchAndExplain]";
2588  EXPECT_EQ(expect, result.message());
2589 }
2590 
2591 // Tests for ElementsAre().
2592 
2593 TEST(ElementsAreTest, CanDescribeExpectingNoElement) {
2594  Matcher<const vector<int>&> m = ElementsAre();
2595  EXPECT_EQ("is empty", Describe(m));
2596 }
2597 
2598 TEST(ElementsAreTest, CanDescribeExpectingOneElement) {
2599  Matcher<vector<int>> m = ElementsAre(Gt(5));
2600  EXPECT_EQ("has 1 element that is > 5", Describe(m));
2601 }
2602 
2603 TEST(ElementsAreTest, CanDescribeExpectingManyElements) {
2604  Matcher<list<std::string>> m = ElementsAre(StrEq("one"), "two");
2605  EXPECT_EQ(
2606  "has 2 elements where\n"
2607  "element #0 is equal to \"one\",\n"
2608  "element #1 is equal to \"two\"",
2609  Describe(m));
2610 }
2611 
2612 TEST(ElementsAreTest, CanDescribeNegationOfExpectingNoElement) {
2613  Matcher<vector<int>> m = ElementsAre();
2614  EXPECT_EQ("isn't empty", DescribeNegation(m));
2615 }
2616 
2617 TEST(ElementsAreTest, CanDescribeNegationOfExpectingOneElement) {
2618  Matcher<const list<int>&> m = ElementsAre(Gt(5));
2619  EXPECT_EQ(
2620  "doesn't have 1 element, or\n"
2621  "element #0 isn't > 5",
2622  DescribeNegation(m));
2623 }
2624 
2625 TEST(ElementsAreTest, CanDescribeNegationOfExpectingManyElements) {
2626  Matcher<const list<std::string>&> m = ElementsAre("one", "two");
2627  EXPECT_EQ(
2628  "doesn't have 2 elements, or\n"
2629  "element #0 isn't equal to \"one\", or\n"
2630  "element #1 isn't equal to \"two\"",
2631  DescribeNegation(m));
2632 }
2633 
2634 TEST(ElementsAreTest, DoesNotExplainTrivialMatch) {
2635  Matcher<const list<int>&> m = ElementsAre(1, Ne(2));
2636 
2637  list<int> test_list;
2638  test_list.push_back(1);
2639  test_list.push_back(3);
2640  EXPECT_EQ("", Explain(m, test_list)); // No need to explain anything.
2641 }
2642 
2643 TEST_P(ElementsAreTestP, ExplainsNonTrivialMatch) {
2644  Matcher<const vector<int>&> m =
2645  ElementsAre(GreaterThan(1), 0, GreaterThan(2));
2646 
2647  const int a[] = {10, 0, 100};
2648  vector<int> test_vector(std::begin(a), std::end(a));
2649  EXPECT_EQ(
2650  "whose element #0 matches, which is 9 more than 1,\n"
2651  "and whose element #2 matches, which is 98 more than 2",
2652  Explain(m, test_vector));
2653 }
2654 
2655 TEST(ElementsAreTest, CanExplainMismatchWrongSize) {
2656  Matcher<const list<int>&> m = ElementsAre(1, 3);
2657 
2658  list<int> test_list;
2659  // No need to explain when the container is empty.
2660  EXPECT_EQ("", Explain(m, test_list));
2661 
2662  test_list.push_back(1);
2663  EXPECT_EQ("which has 1 element", Explain(m, test_list));
2664 }
2665 
2666 TEST_P(ElementsAreTestP, CanExplainMismatchRightSize) {
2667  Matcher<const vector<int>&> m = ElementsAre(1, GreaterThan(5));
2668 
2669  vector<int> v;
2670  v.push_back(2);
2671  v.push_back(1);
2672  EXPECT_EQ("whose element #0 doesn't match", Explain(m, v));
2673 
2674  v[0] = 1;
2675  EXPECT_EQ("whose element #1 doesn't match, which is 4 less than 5",
2676  Explain(m, v));
2677 }
2678 
2679 TEST(ElementsAreTest, MatchesOneElementVector) {
2680  vector<std::string> test_vector;
2681  test_vector.push_back("test string");
2682 
2683  EXPECT_THAT(test_vector, ElementsAre(StrEq("test string")));
2684 }
2685 
2686 TEST(ElementsAreTest, MatchesOneElementList) {
2687  list<std::string> test_list;
2688  test_list.push_back("test string");
2689 
2690  EXPECT_THAT(test_list, ElementsAre("test string"));
2691 }
2692 
2693 TEST(ElementsAreTest, MatchesThreeElementVector) {
2694  vector<std::string> test_vector;
2695  test_vector.push_back("one");
2696  test_vector.push_back("two");
2697  test_vector.push_back("three");
2698 
2699  EXPECT_THAT(test_vector, ElementsAre("one", StrEq("two"), _));
2700 }
2701 
2702 TEST(ElementsAreTest, MatchesOneElementEqMatcher) {
2703  vector<int> test_vector;
2704  test_vector.push_back(4);
2705 
2706  EXPECT_THAT(test_vector, ElementsAre(Eq(4)));
2707 }
2708 
2709 TEST(ElementsAreTest, MatchesOneElementAnyMatcher) {
2710  vector<int> test_vector;
2711  test_vector.push_back(4);
2712 
2713  EXPECT_THAT(test_vector, ElementsAre(_));
2714 }
2715 
2716 TEST(ElementsAreTest, MatchesOneElementValue) {
2717  vector<int> test_vector;
2718  test_vector.push_back(4);
2719 
2720  EXPECT_THAT(test_vector, ElementsAre(4));
2721 }
2722 
2723 TEST(ElementsAreTest, MatchesThreeElementsMixedMatchers) {
2724  vector<int> test_vector;
2725  test_vector.push_back(1);
2726  test_vector.push_back(2);
2727  test_vector.push_back(3);
2728 
2729  EXPECT_THAT(test_vector, ElementsAre(1, Eq(2), _));
2730 }
2731 
2732 TEST(ElementsAreTest, MatchesTenElementVector) {
2733  const int a[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
2734  vector<int> test_vector(std::begin(a), std::end(a));
2735 
2736  EXPECT_THAT(test_vector,
2737  // The element list can contain values and/or matchers
2738  // of different types.
2739  ElementsAre(0, Ge(0), _, 3, 4, Ne(2), Eq(6), 7, 8, _));
2740 }
2741 
2742 TEST(ElementsAreTest, DoesNotMatchWrongSize) {
2743  vector<std::string> test_vector;
2744  test_vector.push_back("test string");
2745  test_vector.push_back("test string");
2746 
2747  Matcher<vector<std::string>> m = ElementsAre(StrEq("test string"));
2748  EXPECT_FALSE(m.Matches(test_vector));
2749 }
2750 
2751 TEST(ElementsAreTest, DoesNotMatchWrongValue) {
2752  vector<std::string> test_vector;
2753  test_vector.push_back("other string");
2754 
2755  Matcher<vector<std::string>> m = ElementsAre(StrEq("test string"));
2756  EXPECT_FALSE(m.Matches(test_vector));
2757 }
2758 
2759 TEST(ElementsAreTest, DoesNotMatchWrongOrder) {
2760  vector<std::string> test_vector;
2761  test_vector.push_back("one");
2762  test_vector.push_back("three");
2763  test_vector.push_back("two");
2764 
2765  Matcher<vector<std::string>> m =
2766  ElementsAre(StrEq("one"), StrEq("two"), StrEq("three"));
2767  EXPECT_FALSE(m.Matches(test_vector));
2768 }
2769 
2770 TEST(ElementsAreTest, WorksForNestedContainer) {
2771  constexpr std::array<const char*, 2> strings = {{"Hi", "world"}};
2772 
2773  vector<list<char>> nested;
2774  for (const auto& s : strings) {
2775  nested.emplace_back(s, s + strlen(s));
2776  }
2777 
2778  EXPECT_THAT(nested, ElementsAre(ElementsAre('H', Ne('e')),
2779  ElementsAre('w', 'o', _, _, 'd')));
2780  EXPECT_THAT(nested, Not(ElementsAre(ElementsAre('H', 'e'),
2781  ElementsAre('w', 'o', _, _, 'd'))));
2782 }
2783 
2784 TEST(ElementsAreTest, WorksWithByRefElementMatchers) {
2785  int a[] = {0, 1, 2};
2786  vector<int> v(std::begin(a), std::end(a));
2787 
2788  EXPECT_THAT(v, ElementsAre(Ref(v[0]), Ref(v[1]), Ref(v[2])));
2789  EXPECT_THAT(v, Not(ElementsAre(Ref(v[0]), Ref(v[1]), Ref(a[2]))));
2790 }
2791 
2792 TEST(ElementsAreTest, WorksWithContainerPointerUsingPointee) {
2793  int a[] = {0, 1, 2};
2794  vector<int> v(std::begin(a), std::end(a));
2795 
2796  EXPECT_THAT(&v, Pointee(ElementsAre(0, 1, _)));
2797  EXPECT_THAT(&v, Not(Pointee(ElementsAre(0, _, 3))));
2798 }
2799 
2800 TEST(ElementsAreTest, WorksWithNativeArrayPassedByReference) {
2801  int array[] = {0, 1, 2};
2802  EXPECT_THAT(array, ElementsAre(0, 1, _));
2803  EXPECT_THAT(array, Not(ElementsAre(1, _, _)));
2804  EXPECT_THAT(array, Not(ElementsAre(0, _)));
2805 }
2806 
2807 class NativeArrayPassedAsPointerAndSize {
2808  public:
2809  NativeArrayPassedAsPointerAndSize() = default;
2810 
2811  MOCK_METHOD(void, Helper, (int* array, int size));
2812 
2813  private:
2814  NativeArrayPassedAsPointerAndSize(const NativeArrayPassedAsPointerAndSize&) =
2815  delete;
2816  NativeArrayPassedAsPointerAndSize& operator=(
2817  const NativeArrayPassedAsPointerAndSize&) = delete;
2818 };
2819 
2820 TEST(ElementsAreTest, WorksWithNativeArrayPassedAsPointerAndSize) {
2821  int array[] = {0, 1};
2822  ::std::tuple<int*, size_t> array_as_tuple(array, 2);
2823  EXPECT_THAT(array_as_tuple, ElementsAre(0, 1));
2824  EXPECT_THAT(array_as_tuple, Not(ElementsAre(0)));
2825 
2826  NativeArrayPassedAsPointerAndSize helper;
2827  EXPECT_CALL(helper, Helper(_, _)).With(ElementsAre(0, 1));
2828  helper.Helper(array, 2);
2829 }
2830 
2831 TEST(ElementsAreTest, WorksWithTwoDimensionalNativeArray) {
2832  const char a2[][3] = {"hi", "lo"};
2833  EXPECT_THAT(a2, ElementsAre(ElementsAre('h', 'i', '\0'),
2834  ElementsAre('l', 'o', '\0')));
2835  EXPECT_THAT(a2, ElementsAre(StrEq("hi"), StrEq("lo")));
2836  EXPECT_THAT(a2, ElementsAre(Not(ElementsAre('h', 'o', '\0')),
2837  ElementsAre('l', 'o', '\0')));
2838 }
2839 
2840 TEST(ElementsAreTest, AcceptsStringLiteral) {
2841  std::string array[] = {"hi", "one", "two"};
2842  EXPECT_THAT(array, ElementsAre("hi", "one", "two"));
2843  EXPECT_THAT(array, Not(ElementsAre("hi", "one", "too")));
2844 }
2845 
2846 // Declared here with the size unknown. Defined AFTER the following test.
2847 extern const char kHi[];
2848 
2849 TEST(ElementsAreTest, AcceptsArrayWithUnknownSize) {
2850  // The size of kHi is not known in this test, but ElementsAre() should
2851  // still accept it.
2852 
2853  std::string array1[] = {"hi"};
2854  EXPECT_THAT(array1, ElementsAre(kHi));
2855 
2856  std::string array2[] = {"ho"};
2857  EXPECT_THAT(array2, Not(ElementsAre(kHi)));
2858 }
2859 
2860 const char kHi[] = "hi";
2861 
2862 TEST(ElementsAreTest, MakesCopyOfArguments) {
2863  int x = 1;
2864  int y = 2;
2865  // This should make a copy of x and y.
2866  ::testing::internal::ElementsAreMatcher<std::tuple<int, int>>
2867  polymorphic_matcher = ElementsAre(x, y);
2868  // Changing x and y now shouldn't affect the meaning of the above matcher.
2869  x = y = 0;
2870  const int array1[] = {1, 2};
2871  EXPECT_THAT(array1, polymorphic_matcher);
2872  const int array2[] = {0, 0};
2873  EXPECT_THAT(array2, Not(polymorphic_matcher));
2874 }
2875 
2876 // Tests for ElementsAreArray(). Since ElementsAreArray() shares most
2877 // of the implementation with ElementsAre(), we don't test it as
2878 // thoroughly here.
2879 
2880 TEST(ElementsAreArrayTest, CanBeCreatedWithValueArray) {
2881  const int a[] = {1, 2, 3};
2882 
2883  vector<int> test_vector(std::begin(a), std::end(a));
2884  EXPECT_THAT(test_vector, ElementsAreArray(a));
2885 
2886  test_vector[2] = 0;
2887  EXPECT_THAT(test_vector, Not(ElementsAreArray(a)));
2888 }
2889 
2890 TEST(ElementsAreArrayTest, CanBeCreatedWithArraySize) {
2891  std::array<const char*, 3> a = {{"one", "two", "three"}};
2892 
2893  vector<std::string> test_vector(std::begin(a), std::end(a));
2894  EXPECT_THAT(test_vector, ElementsAreArray(a.data(), a.size()));
2895 
2896  const char** p = a.data();
2897  test_vector[0] = "1";
2898  EXPECT_THAT(test_vector, Not(ElementsAreArray(p, a.size())));
2899 }
2900 
2901 TEST(ElementsAreArrayTest, CanBeCreatedWithoutArraySize) {
2902  const char* a[] = {"one", "two", "three"};
2903 
2904  vector<std::string> test_vector(std::begin(a), std::end(a));
2905  EXPECT_THAT(test_vector, ElementsAreArray(a));
2906 
2907  test_vector[0] = "1";
2908  EXPECT_THAT(test_vector, Not(ElementsAreArray(a)));
2909 }
2910 
2911 TEST(ElementsAreArrayTest, CanBeCreatedWithMatcherArray) {
2912  const Matcher<std::string> kMatcherArray[] = {StrEq("one"), StrEq("two"),
2913  StrEq("three")};
2914 
2915  vector<std::string> test_vector;
2916  test_vector.push_back("one");
2917  test_vector.push_back("two");
2918  test_vector.push_back("three");
2919  EXPECT_THAT(test_vector, ElementsAreArray(kMatcherArray));
2920 
2921  test_vector.push_back("three");
2922  EXPECT_THAT(test_vector, Not(ElementsAreArray(kMatcherArray)));
2923 }
2924 
2925 TEST(ElementsAreArrayTest, CanBeCreatedWithVector) {
2926  const int a[] = {1, 2, 3};
2927  vector<int> test_vector(std::begin(a), std::end(a));
2928  const vector<int> expected(std::begin(a), std::end(a));
2929  EXPECT_THAT(test_vector, ElementsAreArray(expected));
2930  test_vector.push_back(4);
2931  EXPECT_THAT(test_vector, Not(ElementsAreArray(expected)));
2932 }
2933 
2934 TEST(ElementsAreArrayTest, TakesInitializerList) {
2935  const int a[5] = {1, 2, 3, 4, 5};
2936  EXPECT_THAT(a, ElementsAreArray({1, 2, 3, 4, 5}));
2937  EXPECT_THAT(a, Not(ElementsAreArray({1, 2, 3, 5, 4})));
2938  EXPECT_THAT(a, Not(ElementsAreArray({1, 2, 3, 4, 6})));
2939 }
2940 
2941 TEST(ElementsAreArrayTest, TakesInitializerListOfCStrings) {
2942  const std::string a[5] = {"a", "b", "c", "d", "e"};
2943  EXPECT_THAT(a, ElementsAreArray({"a", "b", "c", "d", "e"}));
2944  EXPECT_THAT(a, Not(ElementsAreArray({"a", "b", "c", "e", "d"})));
2945  EXPECT_THAT(a, Not(ElementsAreArray({"a", "b", "c", "d", "ef"})));
2946 }
2947 
2948 TEST(ElementsAreArrayTest, TakesInitializerListOfSameTypedMatchers) {
2949  const int a[5] = {1, 2, 3, 4, 5};
2950  EXPECT_THAT(a, ElementsAreArray({Eq(1), Eq(2), Eq(3), Eq(4), Eq(5)}));
2951  EXPECT_THAT(a, Not(ElementsAreArray({Eq(1), Eq(2), Eq(3), Eq(4), Eq(6)})));
2952 }
2953 
2954 TEST(ElementsAreArrayTest, TakesInitializerListOfDifferentTypedMatchers) {
2955  const int a[5] = {1, 2, 3, 4, 5};
2956  // The compiler cannot infer the type of the initializer list if its
2957  // elements have different types. We must explicitly specify the
2958  // unified element type in this case.
2959  EXPECT_THAT(
2960  a, ElementsAreArray<Matcher<int>>({Eq(1), Ne(-2), Ge(3), Le(4), Eq(5)}));
2961  EXPECT_THAT(a, Not(ElementsAreArray<Matcher<int>>(
2962  {Eq(1), Ne(-2), Ge(3), Le(4), Eq(6)})));
2963 }
2964 
2965 TEST(ElementsAreArrayTest, CanBeCreatedWithMatcherVector) {
2966  const int a[] = {1, 2, 3};
2967  const Matcher<int> kMatchers[] = {Eq(1), Eq(2), Eq(3)};
2968  vector<int> test_vector(std::begin(a), std::end(a));
2969  const vector<Matcher<int>> expected(std::begin(kMatchers),
2970  std::end(kMatchers));
2971  EXPECT_THAT(test_vector, ElementsAreArray(expected));
2972  test_vector.push_back(4);
2973  EXPECT_THAT(test_vector, Not(ElementsAreArray(expected)));
2974 }
2975 
2976 TEST(ElementsAreArrayTest, CanBeCreatedWithIteratorRange) {
2977  const int a[] = {1, 2, 3};
2978  const vector<int> test_vector(std::begin(a), std::end(a));
2979  const vector<int> expected(std::begin(a), std::end(a));
2980  EXPECT_THAT(test_vector, ElementsAreArray(expected.begin(), expected.end()));
2981  // Pointers are iterators, too.
2982  EXPECT_THAT(test_vector, ElementsAreArray(std::begin(a), std::end(a)));
2983  // The empty range of NULL pointers should also be okay.
2984  int* const null_int = nullptr;
2985  EXPECT_THAT(test_vector, Not(ElementsAreArray(null_int, null_int)));
2986  EXPECT_THAT((vector<int>()), ElementsAreArray(null_int, null_int));
2987 }
2988 
2989 // Since ElementsAre() and ElementsAreArray() share much of the
2990 // implementation, we only do a test for native arrays here.
2991 TEST(ElementsAreArrayTest, WorksWithNativeArray) {
2992  ::std::string a[] = {"hi", "ho"};
2993  ::std::string b[] = {"hi", "ho"};
2994 
2995  EXPECT_THAT(a, ElementsAreArray(b));
2996  EXPECT_THAT(a, ElementsAreArray(b, 2));
2997  EXPECT_THAT(a, Not(ElementsAreArray(b, 1)));
2998 }
2999 
3000 TEST(ElementsAreArrayTest, SourceLifeSpan) {
3001  const int a[] = {1, 2, 3};
3002  vector<int> test_vector(std::begin(a), std::end(a));
3003  vector<int> expect(std::begin(a), std::end(a));
3004  ElementsAreArrayMatcher<int> matcher_maker =
3005  ElementsAreArray(expect.begin(), expect.end());
3006  EXPECT_THAT(test_vector, matcher_maker);
3007  // Changing in place the values that initialized matcher_maker should not
3008  // affect matcher_maker anymore. It should have made its own copy of them.
3009  for (int& i : expect) {
3010  i += 10;
3011  }
3012  EXPECT_THAT(test_vector, matcher_maker);
3013  test_vector.push_back(3);
3014  EXPECT_THAT(test_vector, Not(matcher_maker));
3015 }
3016 
3017 // Tests Contains().
3018 
3019 INSTANTIATE_GTEST_MATCHER_TEST_P(ContainsTest);
3020 
3021 TEST(ContainsTest, ListMatchesWhenElementIsInContainer) {
3022  list<int> some_list;
3023  some_list.push_back(3);
3024  some_list.push_back(1);
3025  some_list.push_back(2);
3026  some_list.push_back(3);
3027  EXPECT_THAT(some_list, Contains(1));
3028  EXPECT_THAT(some_list, Contains(Gt(2.5)));
3029  EXPECT_THAT(some_list, Contains(Eq(2.0f)));
3030 
3031  list<std::string> another_list;
3032  another_list.push_back("fee");
3033  another_list.push_back("fie");
3034  another_list.push_back("foe");
3035  another_list.push_back("fum");
3036  EXPECT_THAT(another_list, Contains(std::string("fee")));
3037 }
3038 
3039 TEST(ContainsTest, ListDoesNotMatchWhenElementIsNotInContainer) {
3040  list<int> some_list;
3041  some_list.push_back(3);
3042  some_list.push_back(1);
3043  EXPECT_THAT(some_list, Not(Contains(4)));
3044 }
3045 
3046 TEST(ContainsTest, SetMatchesWhenElementIsInContainer) {
3047  set<int> some_set;
3048  some_set.insert(3);
3049  some_set.insert(1);
3050  some_set.insert(2);
3051  EXPECT_THAT(some_set, Contains(Eq(1.0)));
3052  EXPECT_THAT(some_set, Contains(Eq(3.0f)));
3053  EXPECT_THAT(some_set, Contains(2));
3054 
3055  set<std::string> another_set;
3056  another_set.insert("fee");
3057  another_set.insert("fie");
3058  another_set.insert("foe");
3059  another_set.insert("fum");
3060  EXPECT_THAT(another_set, Contains(Eq(std::string("fum"))));
3061 }
3062 
3063 TEST(ContainsTest, SetDoesNotMatchWhenElementIsNotInContainer) {
3064  set<int> some_set;
3065  some_set.insert(3);
3066  some_set.insert(1);
3067  EXPECT_THAT(some_set, Not(Contains(4)));
3068 
3069  set<std::string> c_string_set;
3070  c_string_set.insert("hello");
3071  EXPECT_THAT(c_string_set, Not(Contains(std::string("goodbye"))));
3072 }
3073 
3074 TEST_P(ContainsTestP, ExplainsMatchResultCorrectly) {
3075  const int a[2] = {1, 2};
3076  Matcher<const int(&)[2]> m = Contains(2);
3077  EXPECT_EQ("whose element #1 matches", Explain(m, a));
3078 
3079  m = Contains(3);
3080  EXPECT_EQ("", Explain(m, a));
3081 
3082  m = Contains(GreaterThan(0));
3083  EXPECT_EQ("whose element #0 matches, which is 1 more than 0", Explain(m, a));
3084 
3085  m = Contains(GreaterThan(10));
3086  EXPECT_EQ("", Explain(m, a));
3087 }
3088 
3089 TEST(ContainsTest, DescribesItselfCorrectly) {
3090  Matcher<vector<int>> m = Contains(1);
3091  EXPECT_EQ("contains at least one element that is equal to 1", Describe(m));
3092 
3093  Matcher<vector<int>> m2 = Not(m);
3094  EXPECT_EQ("doesn't contain any element that is equal to 1", Describe(m2));
3095 }
3096 
3097 TEST(ContainsTest, MapMatchesWhenElementIsInContainer) {
3098  map<std::string, int> my_map;
3099  const char* bar = "a string";
3100  my_map[bar] = 2;
3101  EXPECT_THAT(my_map, Contains(pair<const char* const, int>(bar, 2)));
3102 
3103  map<std::string, int> another_map;
3104  another_map["fee"] = 1;
3105  another_map["fie"] = 2;
3106  another_map["foe"] = 3;
3107  another_map["fum"] = 4;
3108  EXPECT_THAT(another_map,
3109  Contains(pair<const std::string, int>(std::string("fee"), 1)));
3110  EXPECT_THAT(another_map, Contains(pair<const std::string, int>("fie", 2)));
3111 }
3112 
3113 TEST(ContainsTest, MapDoesNotMatchWhenElementIsNotInContainer) {
3114  map<int, int> some_map;
3115  some_map[1] = 11;
3116  some_map[2] = 22;
3117  EXPECT_THAT(some_map, Not(Contains(pair<const int, int>(2, 23))));
3118 }
3119 
3120 TEST(ContainsTest, ArrayMatchesWhenElementIsInContainer) {
3121  const char* string_array[] = {"fee", "fie", "foe", "fum"};
3122  EXPECT_THAT(string_array, Contains(Eq(std::string("fum"))));
3123 }
3124 
3125 TEST(ContainsTest, ArrayDoesNotMatchWhenElementIsNotInContainer) {
3126  int int_array[] = {1, 2, 3, 4};
3127  EXPECT_THAT(int_array, Not(Contains(5)));
3128 }
3129 
3130 TEST(ContainsTest, AcceptsMatcher) {
3131  const int a[] = {1, 2, 3};
3132  EXPECT_THAT(a, Contains(Gt(2)));
3133  EXPECT_THAT(a, Not(Contains(Gt(4))));
3134 }
3135 
3136 TEST(ContainsTest, WorksForNativeArrayAsTuple) {
3137  const int a[] = {1, 2};
3138  const int* const pointer = a;
3139  EXPECT_THAT(std::make_tuple(pointer, 2), Contains(1));
3140  EXPECT_THAT(std::make_tuple(pointer, 2), Not(Contains(Gt(3))));
3141 }
3142 
3143 TEST(ContainsTest, WorksForTwoDimensionalNativeArray) {
3144  int a[][3] = {{1, 2, 3}, {4, 5, 6}};
3145  EXPECT_THAT(a, Contains(ElementsAre(4, 5, 6)));
3146  EXPECT_THAT(a, Contains(Contains(5)));
3147  EXPECT_THAT(a, Not(Contains(ElementsAre(3, 4, 5))));
3148  EXPECT_THAT(a, Contains(Not(Contains(5))));
3149 }
3150 
3151 } // namespace
3152 } // namespace gmock_matchers_test
3153 } // namespace testing
3154 
3155 GTEST_DISABLE_MSC_WARNINGS_POP_() // 4244 4100
constexpr bool StartsWith(const char(&prefix)[N], const char(&str)[M])
#define EXPECT_DEATH_IF_SUPPORTED(statement, regex)
int value_
#define EXPECT_NONFATAL_FAILURE(statement, substr)
std::string Explain(const MatcherType &m, const Value &x)
constexpr bool EndsWith(const char(&suffix)[N], const char(&str)[M])
#define GTEST_LOG_(severity)
Definition: gtest-port.h:1093
#define MOCK_METHOD(...)
#define ASSERT_THAT(value, matcher)
#define TEST_F(test_fixture, test_name)
Definition: gtest.h:2224
#define TEST(test_suite_name, test_name)
Definition: gtest.h:2192
expr bar
#define INSTANTIATE_GTEST_MATCHER_TEST_P(TestSuite)
BigUInt< n > operator*(BigUInt< n > const &a, BigUInt< n > const &b)
#define EXPECT_FATAL_FAILURE(statement, substr)
#define MATCHER(name, description)
std::string Describe(const Matcher< T > &m)
bool operator!=(const Allocator< T > &a_t, const Allocator< U > &a_u)
std::ostream & operator<<(std::ostream &os, const Expr< T > &xx)
#define T
Definition: Sacado_rad.hpp:553
#define ASSERT_TRUE(condition)
Definition: gtest.h:1831
#define GTEST_DISABLE_MSC_WARNINGS_PUSH_(warnings)
Definition: gtest-port.h:377
std::string s_
const char * p
int value
#define SCOPED_TRACE(message)
Definition: gtest.h:2120
#define EXPECT_THAT(value, matcher)
#define MATCHER_P(name, p0, description)
std::list< value_type >::iterator pos_
#define EXPECT_CALL(obj, call)
bool operator==(const Handle< T > &h1, const Handle< T > &h2)
Compare two handles.
std::string DescribeNegation(const Matcher< T > &m)
#define EXPECT_EQ(val1, val2)
Definition: gtest.h:1884
#define TEST_P(test_suite_name, test_name)
const double y
#define EXPECT_TRUE(condition)
Definition: gtest.h:1823
#define EXPECT_FALSE(condition)
Definition: gtest.h:1827
#define ASSERT_FALSE(condition)
Definition: gtest.h:1835
int n
static double x_
std::list< value_type > remainder_
static ExpectedAnswer expected[4]