Path: blob/main/contrib/googletest/googlemock/test/gmock-matchers-containers_test.cc
110956 views
// Copyright 2007, Google Inc.1// All rights reserved.2//3// Redistribution and use in source and binary forms, with or without4// modification, are permitted provided that the following conditions are5// met:6//7// * Redistributions of source code must retain the above copyright8// notice, this list of conditions and the following disclaimer.9// * Redistributions in binary form must reproduce the above10// copyright notice, this list of conditions and the following disclaimer11// in the documentation and/or other materials provided with the12// distribution.13// * Neither the name of Google Inc. nor the names of its14// contributors may be used to endorse or promote products derived from15// this software without specific prior written permission.16//17// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS18// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT19// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR20// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT21// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,22// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT23// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,24// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY25// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT26// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE27// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.2829// Google Mock - a framework for writing C++ mock classes.30//31// This file tests some commonly used argument matchers.3233#include <algorithm>34#include <array>35#include <cstddef>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>4546#include "gmock/gmock.h"47#include "test/gmock-matchers_test.h"48#include "gtest/gtest.h"4950// Silence warning C4244: 'initializing': conversion from 'int' to 'short',51// possible loss of data and C4100, unreferenced local parameter52GTEST_DISABLE_MSC_WARNINGS_PUSH_(4244 4100)5354namespace testing {55namespace gmock_matchers_test {56namespace {5758std::vector<std::unique_ptr<int>> MakeUniquePtrs(const std::vector<int>& ints) {59std::vector<std::unique_ptr<int>> pointers;60for (int i : ints) pointers.emplace_back(new int(i));61return pointers;62}6364std::string OfType(const std::string& type_name) {65#if GTEST_HAS_RTTI66return IsReadableTypeName(type_name) ? " (of type " + type_name + ")" : "";67#else68return "";69#endif70}7172TEST(ContainsTest, WorksWithMoveOnly) {73ContainerHelper helper;74EXPECT_CALL(helper, Call(Contains(Pointee(2))));75helper.Call(MakeUniquePtrs({1, 2}));76}7778INSTANTIATE_GTEST_MATCHER_TEST_P(ElementsAreTest);7980// Tests the variadic version of the ElementsAreMatcher81TEST(ElementsAreTest, HugeMatcher) {82vector<int> test_vector{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12};8384EXPECT_THAT(test_vector,85ElementsAre(Eq(1), Eq(2), Lt(13), Eq(4), Eq(5), Eq(6), Eq(7),86Eq(8), Eq(9), Eq(10), Gt(1), Eq(12)));87}8889// Tests the variadic version of the UnorderedElementsAreMatcher90TEST(ElementsAreTest, HugeMatcherStr) {91vector<std::string> test_vector{92"literal_string", "", "", "", "", "", "", "", "", "", "", ""};9394EXPECT_THAT(test_vector, UnorderedElementsAre("literal_string", _, _, _, _, _,95_, _, _, _, _, _));96}9798// Tests the variadic version of the UnorderedElementsAreMatcher99TEST(ElementsAreTest, HugeMatcherUnordered) {100vector<int> test_vector{2, 1, 8, 5, 4, 6, 7, 3, 9, 12, 11, 10};101102EXPECT_THAT(test_vector, UnorderedElementsAre(103Eq(2), Eq(1), Gt(7), Eq(5), Eq(4), Eq(6), Eq(7),104Eq(3), Eq(9), Eq(12), Eq(11), Ne(122)));105}106107// Tests that ASSERT_THAT() and EXPECT_THAT() work when the value108// matches the matcher.109TEST(MatcherAssertionTest, WorksWhenMatcherIsSatisfied) {110ASSERT_THAT(5, Ge(2)) << "This should succeed.";111ASSERT_THAT("Foo", EndsWith("oo"));112EXPECT_THAT(2, AllOf(Le(7), Ge(0))) << "This should succeed too.";113EXPECT_THAT("Hello", StartsWith("Hell"));114}115116// Tests that ASSERT_THAT() and EXPECT_THAT() work when the value117// doesn't match the matcher.118TEST(MatcherAssertionTest, WorksWhenMatcherIsNotSatisfied) {119// 'n' must be static as it is used in an EXPECT_FATAL_FAILURE(),120// which cannot reference auto variables.121static unsigned short n; // NOLINT122n = 5;123124EXPECT_FATAL_FAILURE(ASSERT_THAT(n, Gt(10)),125"Value of: n\n"126"Expected: is > 10\n"127" Actual: 5" +128OfType("unsigned short"));129n = 0;130EXPECT_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" +134OfType("unsigned short"));135}136137// Tests that ASSERT_THAT() and EXPECT_THAT() work when the argument138// has a reference type.139TEST(MatcherAssertionTest, WorksForByRefArguments) {140// We use a static variable here as EXPECT_FATAL_FAILURE() cannot141// reference auto variables.142static int n;143n = 0;144EXPECT_THAT(n, AllOf(Le(7), Ref(n)));145EXPECT_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.149EXPECT_FATAL_FAILURE(ASSERT_THAT(n, Not(Ref(n))),150"Actual: 0" + OfType("int") + ", which is located @");151}152153// Tests that ASSERT_THAT() and EXPECT_THAT() work when the matcher is154// monomorphic.155TEST(MatcherAssertionTest, WorksForMonomorphicMatcher) {156Matcher<const char*> starts_with_he = StartsWith("he");157ASSERT_THAT("hello", starts_with_he);158159Matcher<const std::string&> ends_with_ok = EndsWith("ok");160ASSERT_THAT("book", ends_with_ok);161const std::string bad = "bad";162EXPECT_NONFATAL_FAILURE(EXPECT_THAT(bad, ends_with_ok),163"Value of: bad\n"164"Expected: ends with \"ok\"\n"165" Actual: \"bad\"");166Matcher<int> is_greater_than_5 = Gt(5);167EXPECT_NONFATAL_FAILURE(EXPECT_THAT(5, is_greater_than_5),168"Value of: 5\n"169"Expected: is > 5\n"170" Actual: 5" +171OfType("int"));172}173174TEST(PointeeTest, RawPointer) {175const Matcher<int*> m = Pointee(Ge(0));176177int n = 1;178EXPECT_TRUE(m.Matches(&n));179n = -1;180EXPECT_FALSE(m.Matches(&n));181EXPECT_FALSE(m.Matches(nullptr));182}183184TEST(PointeeTest, RawPointerToConst) {185const Matcher<const double*> m = Pointee(Ge(0));186187double x = 1;188EXPECT_TRUE(m.Matches(&x));189x = -1;190EXPECT_FALSE(m.Matches(&x));191EXPECT_FALSE(m.Matches(nullptr));192}193194TEST(PointeeTest, ReferenceToConstRawPointer) {195const Matcher<int* const&> m = Pointee(Ge(0));196197int n = 1;198EXPECT_TRUE(m.Matches(&n));199n = -1;200EXPECT_FALSE(m.Matches(&n));201EXPECT_FALSE(m.Matches(nullptr));202}203204TEST(PointeeTest, ReferenceToNonConstRawPointer) {205const Matcher<double*&> m = Pointee(Ge(0));206207double x = 1.0;208double* p = &x;209EXPECT_TRUE(m.Matches(p));210x = -1;211EXPECT_FALSE(m.Matches(p));212p = nullptr;213EXPECT_FALSE(m.Matches(p));214}215216TEST(PointeeTest, SmartPointer) {217const Matcher<std::unique_ptr<int>> m = Pointee(Ge(0));218219std::unique_ptr<int> n(new int(1));220EXPECT_TRUE(m.Matches(n));221}222223TEST(PointeeTest, SmartPointerToConst) {224const Matcher<std::unique_ptr<const int>> m = Pointee(Ge(0));225226// There's no implicit conversion from unique_ptr<int> to const227// unique_ptr<const int>, so we must pass a unique_ptr<const int> into the228// matcher.229std::unique_ptr<const int> n(new int(1));230EXPECT_TRUE(m.Matches(n));231}232233TEST(PointerTest, RawPointer) {234int n = 1;235const Matcher<int*> m = Pointer(Eq(&n));236237EXPECT_TRUE(m.Matches(&n));238239int* p = nullptr;240EXPECT_FALSE(m.Matches(p));241EXPECT_FALSE(m.Matches(nullptr));242}243244TEST(PointerTest, RawPointerToConst) {245int n = 1;246const Matcher<const int*> m = Pointer(Eq(&n));247248EXPECT_TRUE(m.Matches(&n));249250int* p = nullptr;251EXPECT_FALSE(m.Matches(p));252EXPECT_FALSE(m.Matches(nullptr));253}254255TEST(PointerTest, SmartPointer) {256std::unique_ptr<int> n(new int(10));257int* raw_n = n.get();258const Matcher<std::unique_ptr<int>> m = Pointer(Eq(raw_n));259260EXPECT_TRUE(m.Matches(n));261}262263TEST(PointerTest, SmartPointerToConst) {264std::unique_ptr<const int> n(new int(10));265const int* raw_n = n.get();266const Matcher<std::unique_ptr<const int>> m = Pointer(Eq(raw_n));267268// There's no implicit conversion from unique_ptr<int> to const269// unique_ptr<const int>, so we must pass a unique_ptr<const int> into the270// matcher.271std::unique_ptr<const int> p(new int(10));272EXPECT_FALSE(m.Matches(p));273}274275// Minimal const-propagating pointer.276template <typename T>277class ConstPropagatingPtr {278public:279typedef T element_type;280281ConstPropagatingPtr() : val_() {}282explicit ConstPropagatingPtr(T* t) : val_(t) {}283ConstPropagatingPtr(const ConstPropagatingPtr& other) : val_(other.val_) {}284285T* get() { return val_; }286T& operator*() { return *val_; }287// Most smart pointers return non-const T* and T& from the next methods.288const T* get() const { return val_; }289const T& operator*() const { return *val_; }290291private:292T* val_;293};294295INSTANTIATE_GTEST_MATCHER_TEST_P(PointeeTest);296297TEST(PointeeTest, WorksWithConstPropagatingPointers) {298const Matcher<ConstPropagatingPtr<int>> m = Pointee(Lt(5));299int three = 3;300const ConstPropagatingPtr<int> co(&three);301ConstPropagatingPtr<int> o(&three);302EXPECT_TRUE(m.Matches(o));303EXPECT_TRUE(m.Matches(co));304*o = 6;305EXPECT_FALSE(m.Matches(o));306EXPECT_FALSE(m.Matches(ConstPropagatingPtr<int>()));307}308309TEST(PointeeTest, NeverMatchesNull) {310const Matcher<const char*> m = Pointee(_);311EXPECT_FALSE(m.Matches(nullptr));312}313314// Tests that we can write Pointee(value) instead of Pointee(Eq(value)).315TEST(PointeeTest, MatchesAgainstAValue) {316const Matcher<int*> m = Pointee(5);317318int n = 5;319EXPECT_TRUE(m.Matches(&n));320n = -1;321EXPECT_FALSE(m.Matches(&n));322EXPECT_FALSE(m.Matches(nullptr));323}324325TEST(PointeeTest, CanDescribeSelf) {326const Matcher<int*> m = Pointee(Gt(3));327EXPECT_EQ("points to a value that is > 3", Describe(m));328EXPECT_EQ("does not point to a value that is > 3", DescribeNegation(m));329}330331TEST_P(PointeeTestP, CanExplainMatchResult) {332const Matcher<const std::string*> m = Pointee(StartsWith("Hi"));333334EXPECT_EQ("", Explain(m, static_cast<const std::string*>(nullptr)));335336const Matcher<long*> m2 = Pointee(GreaterThan(1)); // NOLINT337long n = 3; // NOLINT338EXPECT_EQ("which points to 3" + OfType("long") + ", which is 2 more than 1",339Explain(m2, &n));340}341342TEST(PointeeTest, AlwaysExplainsPointee) {343const Matcher<int*> m = Pointee(0);344int n = 42;345EXPECT_EQ("which points to 42" + OfType("int"), Explain(m, &n));346}347348// An uncopyable class.349class Uncopyable {350public:351Uncopyable() : value_(-1) {}352explicit Uncopyable(int a_value) : value_(a_value) {}353354int value() const { return value_; }355void set_value(int i) { value_ = i; }356357private:358int value_;359Uncopyable(const Uncopyable&) = delete;360Uncopyable& operator=(const Uncopyable&) = delete;361};362363// Returns true if and only if x.value() is positive.364bool ValueIsPositive(const Uncopyable& x) { return x.value() > 0; }365366MATCHER_P(UncopyableIs, inner_matcher, "") {367return ExplainMatchResult(inner_matcher, arg.value(), result_listener);368}369370// A user-defined struct for testing Field().371struct AStruct {372AStruct() : x(0), y(1.0), z(5), p(nullptr) {}373AStruct(const AStruct& rhs)374: x(rhs.x), y(rhs.y), z(rhs.z.value()), p(rhs.p) {}375376int x; // A non-const field.377const double y; // A const field.378Uncopyable z; // An uncopyable field.379const char* p; // A pointer field.380};381382// A derived struct for testing Field().383struct DerivedStruct : public AStruct {384char ch;385};386387INSTANTIATE_GTEST_MATCHER_TEST_P(FieldTest);388389// Tests that Field(&Foo::field, ...) works when field is non-const.390TEST(FieldTest, WorksForNonConstField) {391Matcher<AStruct> m = Field(&AStruct::x, Ge(0));392Matcher<AStruct> m_with_name = Field("x", &AStruct::x, Ge(0));393394AStruct a;395EXPECT_TRUE(m.Matches(a));396EXPECT_TRUE(m_with_name.Matches(a));397a.x = -1;398EXPECT_FALSE(m.Matches(a));399EXPECT_FALSE(m_with_name.Matches(a));400}401402// Tests that Field(&Foo::field, ...) works when field is const.403TEST(FieldTest, WorksForConstField) {404AStruct a;405406Matcher<AStruct> m = Field(&AStruct::y, Ge(0.0));407Matcher<AStruct> m_with_name = Field("y", &AStruct::y, Ge(0.0));408EXPECT_TRUE(m.Matches(a));409EXPECT_TRUE(m_with_name.Matches(a));410m = Field(&AStruct::y, Le(0.0));411m_with_name = Field("y", &AStruct::y, Le(0.0));412EXPECT_FALSE(m.Matches(a));413EXPECT_FALSE(m_with_name.Matches(a));414}415416// Tests that Field(&Foo::field, ...) works when field is not copyable.417TEST(FieldTest, WorksForUncopyableField) {418AStruct a;419420Matcher<AStruct> m = Field(&AStruct::z, Truly(ValueIsPositive));421EXPECT_TRUE(m.Matches(a));422m = Field(&AStruct::z, Not(Truly(ValueIsPositive)));423EXPECT_FALSE(m.Matches(a));424}425426// Tests that Field(&Foo::field, ...) works when field is a pointer.427TEST(FieldTest, WorksForPointerField) {428// Matching against NULL.429Matcher<AStruct> m = Field(&AStruct::p, static_cast<const char*>(nullptr));430AStruct a;431EXPECT_TRUE(m.Matches(a));432a.p = "hi";433EXPECT_FALSE(m.Matches(a));434435// Matching a pointer that is not NULL.436m = Field(&AStruct::p, StartsWith("hi"));437a.p = "hill";438EXPECT_TRUE(m.Matches(a));439a.p = "hole";440EXPECT_FALSE(m.Matches(a));441}442443// Tests that Field() works when the object is passed by reference.444TEST(FieldTest, WorksForByRefArgument) {445Matcher<const AStruct&> m = Field(&AStruct::x, Ge(0));446447AStruct a;448EXPECT_TRUE(m.Matches(a));449a.x = -1;450EXPECT_FALSE(m.Matches(a));451}452453// Tests that Field(&Foo::field, ...) works when the argument's type454// is a sub-type of Foo.455TEST(FieldTest, WorksForArgumentOfSubType) {456// Note that the matcher expects DerivedStruct but we say AStruct457// inside Field().458Matcher<const DerivedStruct&> m = Field(&AStruct::x, Ge(0));459460DerivedStruct d;461EXPECT_TRUE(m.Matches(d));462d.x = -1;463EXPECT_FALSE(m.Matches(d));464}465466// Tests that Field(&Foo::field, m) works when field's type and m's467// argument type are compatible but not the same.468TEST(FieldTest, WorksForCompatibleMatcherType) {469// The field is an int, but the inner matcher expects a signed char.470Matcher<const AStruct&> m = Field(&AStruct::x, Matcher<signed char>(Ge(0)));471472AStruct a;473EXPECT_TRUE(m.Matches(a));474a.x = -1;475EXPECT_FALSE(m.Matches(a));476}477478// Tests that Field() can describe itself.479TEST(FieldTest, CanDescribeSelf) {480Matcher<const AStruct&> m = Field(&AStruct::x, Ge(0));481482EXPECT_EQ("is an object whose given field is >= 0", Describe(m));483EXPECT_EQ("is an object whose given field isn't >= 0", DescribeNegation(m));484}485486TEST(FieldTest, CanDescribeSelfWithFieldName) {487Matcher<const AStruct&> m = Field("field_name", &AStruct::x, Ge(0));488489EXPECT_EQ("is an object whose field `field_name` is >= 0", Describe(m));490EXPECT_EQ("is an object whose field `field_name` isn't >= 0",491DescribeNegation(m));492}493494// Tests that Field() can explain the match result.495TEST_P(FieldTestP, CanExplainMatchResult) {496Matcher<const AStruct&> m = Field(&AStruct::x, Ge(0));497498AStruct a;499a.x = 1;500EXPECT_EQ("whose given field is 1" + OfType("int"), Explain(m, a));501502m = Field(&AStruct::x, GreaterThan(0));503EXPECT_EQ(504"whose given field is 1" + OfType("int") + ", which is 1 more than 0",505Explain(m, a));506}507508TEST_P(FieldTestP, CanExplainMatchResultWithFieldName) {509Matcher<const AStruct&> m = Field("field_name", &AStruct::x, Ge(0));510511AStruct a;512a.x = 1;513EXPECT_EQ("whose field `field_name` is 1" + OfType("int"), Explain(m, a));514515m = Field("field_name", &AStruct::x, GreaterThan(0));516EXPECT_EQ("whose field `field_name` is 1" + OfType("int") +517", which is 1 more than 0",518Explain(m, a));519}520521INSTANTIATE_GTEST_MATCHER_TEST_P(FieldForPointerTest);522523// Tests that Field() works when the argument is a pointer to const.524TEST(FieldForPointerTest, WorksForPointerToConst) {525Matcher<const AStruct*> m = Field(&AStruct::x, Ge(0));526527AStruct a;528EXPECT_TRUE(m.Matches(&a));529a.x = -1;530EXPECT_FALSE(m.Matches(&a));531}532533// Tests that Field() works when the argument is a pointer to non-const.534TEST(FieldForPointerTest, WorksForPointerToNonConst) {535Matcher<AStruct*> m = Field(&AStruct::x, Ge(0));536537AStruct a;538EXPECT_TRUE(m.Matches(&a));539a.x = -1;540EXPECT_FALSE(m.Matches(&a));541}542543// Tests that Field() works when the argument is a reference to a const pointer.544TEST(FieldForPointerTest, WorksForReferenceToConstPointer) {545Matcher<AStruct* const&> m = Field(&AStruct::x, Ge(0));546547AStruct a;548EXPECT_TRUE(m.Matches(&a));549a.x = -1;550EXPECT_FALSE(m.Matches(&a));551}552553// Tests that Field() does not match the NULL pointer.554TEST(FieldForPointerTest, DoesNotMatchNull) {555Matcher<const AStruct*> m = Field(&AStruct::x, _);556EXPECT_FALSE(m.Matches(nullptr));557}558559// Tests that Field(&Foo::field, ...) works when the argument's type560// is a sub-type of const Foo*.561TEST(FieldForPointerTest, WorksForArgumentOfSubType) {562// Note that the matcher expects DerivedStruct but we say AStruct563// inside Field().564Matcher<DerivedStruct*> m = Field(&AStruct::x, Ge(0));565566DerivedStruct d;567EXPECT_TRUE(m.Matches(&d));568d.x = -1;569EXPECT_FALSE(m.Matches(&d));570}571572// Tests that Field() can describe itself when used to match a pointer.573TEST(FieldForPointerTest, CanDescribeSelf) {574Matcher<const AStruct*> m = Field(&AStruct::x, Ge(0));575576EXPECT_EQ("is an object whose given field is >= 0", Describe(m));577EXPECT_EQ("is an object whose given field isn't >= 0", DescribeNegation(m));578}579580TEST(FieldForPointerTest, CanDescribeSelfWithFieldName) {581Matcher<const AStruct*> m = Field("field_name", &AStruct::x, Ge(0));582583EXPECT_EQ("is an object whose field `field_name` is >= 0", Describe(m));584EXPECT_EQ("is an object whose field `field_name` isn't >= 0",585DescribeNegation(m));586}587588// Tests that Field() can explain the result of matching a pointer.589TEST_P(FieldForPointerTestP, CanExplainMatchResult) {590Matcher<const AStruct*> m = Field(&AStruct::x, Ge(0));591592AStruct a;593a.x = 1;594EXPECT_EQ("", Explain(m, static_cast<const AStruct*>(nullptr)));595EXPECT_EQ("which points to an object whose given field is 1" + OfType("int"),596Explain(m, &a));597598m = Field(&AStruct::x, GreaterThan(0));599EXPECT_EQ("which points to an object whose given field is 1" + OfType("int") +600", which is 1 more than 0",601Explain(m, &a));602}603604TEST_P(FieldForPointerTestP, CanExplainMatchResultWithFieldName) {605Matcher<const AStruct*> m = Field("field_name", &AStruct::x, Ge(0));606607AStruct a;608a.x = 1;609EXPECT_EQ("", Explain(m, static_cast<const AStruct*>(nullptr)));610EXPECT_EQ(611"which points to an object whose field `field_name` is 1" + OfType("int"),612Explain(m, &a));613614m = Field("field_name", &AStruct::x, GreaterThan(0));615EXPECT_EQ("which points to an object whose field `field_name` is 1" +616OfType("int") + ", which is 1 more than 0",617Explain(m, &a));618}619620// A user-defined class for testing Property().621class AClass {622public:623AClass() : n_(0) {}624625// A getter that returns a non-reference.626int n() const { return n_; }627628void set_n(int new_n) { n_ = new_n; }629630// A getter that returns a reference to const.631const std::string& s() const { return s_; }632633const std::string& s_ref() const& { return s_; }634635void set_s(const std::string& new_s) { s_ = new_s; }636637// A getter that returns a reference to non-const.638double& x() const { return x_; }639640private:641int n_;642std::string s_;643644static double x_;645};646647double AClass::x_ = 0.0;648649// A derived class for testing Property().650class DerivedClass : public AClass {651public:652int k() const { return k_; }653654private:655int k_;656};657658INSTANTIATE_GTEST_MATCHER_TEST_P(PropertyTest);659660// Tests that Property(&Foo::property, ...) works when property()661// returns a non-reference.662TEST(PropertyTest, WorksForNonReferenceProperty) {663Matcher<const AClass&> m = Property(&AClass::n, Ge(0));664Matcher<const AClass&> m_with_name = Property("n", &AClass::n, Ge(0));665666AClass a;667a.set_n(1);668EXPECT_TRUE(m.Matches(a));669EXPECT_TRUE(m_with_name.Matches(a));670671a.set_n(-1);672EXPECT_FALSE(m.Matches(a));673EXPECT_FALSE(m_with_name.Matches(a));674}675676// Tests that Property(&Foo::property, ...) works when property()677// returns a reference to const.678TEST(PropertyTest, WorksForReferenceToConstProperty) {679Matcher<const AClass&> m = Property(&AClass::s, StartsWith("hi"));680Matcher<const AClass&> m_with_name =681Property("s", &AClass::s, StartsWith("hi"));682683AClass a;684a.set_s("hill");685EXPECT_TRUE(m.Matches(a));686EXPECT_TRUE(m_with_name.Matches(a));687688a.set_s("hole");689EXPECT_FALSE(m.Matches(a));690EXPECT_FALSE(m_with_name.Matches(a));691}692693// Tests that Property(&Foo::property, ...) works when property() is694// ref-qualified.695TEST(PropertyTest, WorksForRefQualifiedProperty) {696Matcher<const AClass&> m = Property(&AClass::s_ref, StartsWith("hi"));697Matcher<const AClass&> m_with_name =698Property("s", &AClass::s_ref, StartsWith("hi"));699700AClass a;701a.set_s("hill");702EXPECT_TRUE(m.Matches(a));703EXPECT_TRUE(m_with_name.Matches(a));704705a.set_s("hole");706EXPECT_FALSE(m.Matches(a));707EXPECT_FALSE(m_with_name.Matches(a));708}709710// Tests that Property(&Foo::property, ...) works when property()711// returns a reference to non-const.712TEST(PropertyTest, WorksForReferenceToNonConstProperty) {713double x = 0.0;714AClass a;715716Matcher<const AClass&> m = Property(&AClass::x, Ref(x));717EXPECT_FALSE(m.Matches(a));718719m = Property(&AClass::x, Not(Ref(x)));720EXPECT_TRUE(m.Matches(a));721}722723// Tests that Property(&Foo::property, ...) works when the argument is724// passed by value.725TEST(PropertyTest, WorksForByValueArgument) {726Matcher<AClass> m = Property(&AClass::s, StartsWith("hi"));727728AClass a;729a.set_s("hill");730EXPECT_TRUE(m.Matches(a));731732a.set_s("hole");733EXPECT_FALSE(m.Matches(a));734}735736// Tests that Property(&Foo::property, ...) works when the argument's737// type is a sub-type of Foo.738TEST(PropertyTest, WorksForArgumentOfSubType) {739// The matcher expects a DerivedClass, but inside the Property() we740// say AClass.741Matcher<const DerivedClass&> m = Property(&AClass::n, Ge(0));742743DerivedClass d;744d.set_n(1);745EXPECT_TRUE(m.Matches(d));746747d.set_n(-1);748EXPECT_FALSE(m.Matches(d));749}750751// Tests that Property(&Foo::property, m) works when property()'s type752// and m's argument type are compatible but different.753TEST(PropertyTest, WorksForCompatibleMatcherType) {754// n() returns an int but the inner matcher expects a signed char.755Matcher<const AClass&> m = Property(&AClass::n, Matcher<signed char>(Ge(0)));756757Matcher<const AClass&> m_with_name =758Property("n", &AClass::n, Matcher<signed char>(Ge(0)));759760AClass a;761EXPECT_TRUE(m.Matches(a));762EXPECT_TRUE(m_with_name.Matches(a));763a.set_n(-1);764EXPECT_FALSE(m.Matches(a));765EXPECT_FALSE(m_with_name.Matches(a));766}767768// Tests that Property() can describe itself.769TEST(PropertyTest, CanDescribeSelf) {770Matcher<const AClass&> m = Property(&AClass::n, Ge(0));771772EXPECT_EQ("is an object whose given property is >= 0", Describe(m));773EXPECT_EQ("is an object whose given property isn't >= 0",774DescribeNegation(m));775}776777TEST(PropertyTest, CanDescribeSelfWithPropertyName) {778Matcher<const AClass&> m = Property("fancy_name", &AClass::n, Ge(0));779780EXPECT_EQ("is an object whose property `fancy_name` is >= 0", Describe(m));781EXPECT_EQ("is an object whose property `fancy_name` isn't >= 0",782DescribeNegation(m));783}784785// Tests that Property() can explain the match result.786TEST_P(PropertyTestP, CanExplainMatchResult) {787Matcher<const AClass&> m = Property(&AClass::n, Ge(0));788789AClass a;790a.set_n(1);791EXPECT_EQ("whose given property is 1" + OfType("int"), Explain(m, a));792793m = Property(&AClass::n, GreaterThan(0));794EXPECT_EQ(795"whose given property is 1" + OfType("int") + ", which is 1 more than 0",796Explain(m, a));797}798799TEST_P(PropertyTestP, CanExplainMatchResultWithPropertyName) {800Matcher<const AClass&> m = Property("fancy_name", &AClass::n, Ge(0));801802AClass a;803a.set_n(1);804EXPECT_EQ("whose property `fancy_name` is 1" + OfType("int"), Explain(m, a));805806m = Property("fancy_name", &AClass::n, GreaterThan(0));807EXPECT_EQ("whose property `fancy_name` is 1" + OfType("int") +808", which is 1 more than 0",809Explain(m, a));810}811812INSTANTIATE_GTEST_MATCHER_TEST_P(PropertyForPointerTest);813814// Tests that Property() works when the argument is a pointer to const.815TEST(PropertyForPointerTest, WorksForPointerToConst) {816Matcher<const AClass*> m = Property(&AClass::n, Ge(0));817818AClass a;819a.set_n(1);820EXPECT_TRUE(m.Matches(&a));821822a.set_n(-1);823EXPECT_FALSE(m.Matches(&a));824}825826// Tests that Property() works when the argument is a pointer to non-const.827TEST(PropertyForPointerTest, WorksForPointerToNonConst) {828Matcher<AClass*> m = Property(&AClass::s, StartsWith("hi"));829830AClass a;831a.set_s("hill");832EXPECT_TRUE(m.Matches(&a));833834a.set_s("hole");835EXPECT_FALSE(m.Matches(&a));836}837838// Tests that Property() works when the argument is a reference to a839// const pointer.840TEST(PropertyForPointerTest, WorksForReferenceToConstPointer) {841Matcher<AClass* const&> m = Property(&AClass::s, StartsWith("hi"));842843AClass a;844a.set_s("hill");845EXPECT_TRUE(m.Matches(&a));846847a.set_s("hole");848EXPECT_FALSE(m.Matches(&a));849}850851// Tests that Property() does not match the NULL pointer.852TEST(PropertyForPointerTest, WorksForReferenceToNonConstProperty) {853Matcher<const AClass*> m = Property(&AClass::x, _);854EXPECT_FALSE(m.Matches(nullptr));855}856857// Tests that Property(&Foo::property, ...) works when the argument's858// type is a sub-type of const Foo*.859TEST(PropertyForPointerTest, WorksForArgumentOfSubType) {860// The matcher expects a DerivedClass, but inside the Property() we861// say AClass.862Matcher<const DerivedClass*> m = Property(&AClass::n, Ge(0));863864DerivedClass d;865d.set_n(1);866EXPECT_TRUE(m.Matches(&d));867868d.set_n(-1);869EXPECT_FALSE(m.Matches(&d));870}871872// Tests that Property() can describe itself when used to match a pointer.873TEST(PropertyForPointerTest, CanDescribeSelf) {874Matcher<const AClass*> m = Property(&AClass::n, Ge(0));875876EXPECT_EQ("is an object whose given property is >= 0", Describe(m));877EXPECT_EQ("is an object whose given property isn't >= 0",878DescribeNegation(m));879}880881TEST(PropertyForPointerTest, CanDescribeSelfWithPropertyDescription) {882Matcher<const AClass*> m = Property("fancy_name", &AClass::n, Ge(0));883884EXPECT_EQ("is an object whose property `fancy_name` is >= 0", Describe(m));885EXPECT_EQ("is an object whose property `fancy_name` isn't >= 0",886DescribeNegation(m));887}888889// Tests that Property() can explain the result of matching a pointer.890TEST_P(PropertyForPointerTestP, CanExplainMatchResult) {891Matcher<const AClass*> m = Property(&AClass::n, Ge(0));892893AClass a;894a.set_n(1);895EXPECT_EQ("", Explain(m, static_cast<const AClass*>(nullptr)));896EXPECT_EQ(897"which points to an object whose given property is 1" + OfType("int"),898Explain(m, &a));899900m = Property(&AClass::n, GreaterThan(0));901EXPECT_EQ("which points to an object whose given property is 1" +902OfType("int") + ", which is 1 more than 0",903Explain(m, &a));904}905906TEST_P(PropertyForPointerTestP, CanExplainMatchResultWithPropertyName) {907Matcher<const AClass*> m = Property("fancy_name", &AClass::n, Ge(0));908909AClass a;910a.set_n(1);911EXPECT_EQ("", Explain(m, static_cast<const AClass*>(nullptr)));912EXPECT_EQ("which points to an object whose property `fancy_name` is 1" +913OfType("int"),914Explain(m, &a));915916m = Property("fancy_name", &AClass::n, GreaterThan(0));917EXPECT_EQ("which points to an object whose property `fancy_name` is 1" +918OfType("int") + ", which is 1 more than 0",919Explain(m, &a));920}921922// Tests ResultOf.923924// Tests that ResultOf(f, ...) compiles and works as expected when f is a925// function pointer.926std::string IntToStringFunction(int input) {927return input == 1 ? "foo" : "bar";928}929930INSTANTIATE_GTEST_MATCHER_TEST_P(ResultOfTest);931932TEST(ResultOfTest, WorksForFunctionPointers) {933Matcher<int> matcher = ResultOf(&IntToStringFunction, Eq(std::string("foo")));934935EXPECT_TRUE(matcher.Matches(1));936EXPECT_FALSE(matcher.Matches(2));937}938939// Tests that ResultOf() can describe itself.940TEST(ResultOfTest, CanDescribeItself) {941Matcher<int> matcher = ResultOf(&IntToStringFunction, StrEq("foo"));942943EXPECT_EQ(944"is mapped by the given callable to a value that "945"is equal to \"foo\"",946Describe(matcher));947EXPECT_EQ(948"is mapped by the given callable to a value that "949"isn't equal to \"foo\"",950DescribeNegation(matcher));951}952953// Tests that ResultOf() can describe itself when provided a result description.954TEST(ResultOfTest, CanDescribeItselfWithResultDescription) {955Matcher<int> matcher =956ResultOf("string conversion", &IntToStringFunction, StrEq("foo"));957958EXPECT_EQ("whose string conversion is equal to \"foo\"", Describe(matcher));959EXPECT_EQ("whose string conversion isn't equal to \"foo\"",960DescribeNegation(matcher));961}962963// Tests that ResultOf() can explain the match result.964int IntFunction(int input) { return input == 42 ? 80 : 90; }965966TEST_P(ResultOfTestP, CanExplainMatchResult) {967Matcher<int> matcher = ResultOf(&IntFunction, Ge(85));968EXPECT_EQ("which is mapped by the given callable to 90" + OfType("int"),969Explain(matcher, 36));970971matcher = ResultOf(&IntFunction, GreaterThan(85));972EXPECT_EQ("which is mapped by the given callable to 90" + OfType("int") +973", which is 5 more than 85",974Explain(matcher, 36));975}976977TEST_P(ResultOfTestP, CanExplainMatchResultWithResultDescription) {978Matcher<int> matcher = ResultOf("magic int conversion", &IntFunction, Ge(85));979EXPECT_EQ("whose magic int conversion is 90" + OfType("int"),980Explain(matcher, 36));981982matcher = ResultOf("magic int conversion", &IntFunction, GreaterThan(85));983EXPECT_EQ("whose magic int conversion is 90" + OfType("int") +984", which is 5 more than 85",985Explain(matcher, 36));986}987988// Tests that ResultOf(f, ...) compiles and works as expected when f(x)989// returns a non-reference.990TEST(ResultOfTest, WorksForNonReferenceResults) {991Matcher<int> matcher = ResultOf(&IntFunction, Eq(80));992993EXPECT_TRUE(matcher.Matches(42));994EXPECT_FALSE(matcher.Matches(36));995}996997// Tests that ResultOf(f, ...) compiles and works as expected when f(x)998// returns a reference to non-const.999double& DoubleFunction(double& input) { return input; } // NOLINT10001001Uncopyable& RefUncopyableFunction(Uncopyable& obj) { // NOLINT1002return obj;1003}10041005TEST(ResultOfTest, WorksForReferenceToNonConstResults) {1006double x = 3.14;1007double x2 = x;1008Matcher<double&> matcher = ResultOf(&DoubleFunction, Ref(x));10091010EXPECT_TRUE(matcher.Matches(x));1011EXPECT_FALSE(matcher.Matches(x2));10121013// Test that ResultOf works with uncopyable objects1014Uncopyable obj(0);1015Uncopyable obj2(0);1016Matcher<Uncopyable&> matcher2 = ResultOf(&RefUncopyableFunction, Ref(obj));10171018EXPECT_TRUE(matcher2.Matches(obj));1019EXPECT_FALSE(matcher2.Matches(obj2));1020}10211022// Tests that ResultOf(f, ...) compiles and works as expected when f(x)1023// returns a reference to const.1024const std::string& StringFunction(const std::string& input) { return input; }10251026TEST(ResultOfTest, WorksForReferenceToConstResults) {1027std::string s = "foo";1028std::string s2 = s;1029Matcher<const std::string&> matcher = ResultOf(&StringFunction, Ref(s));10301031EXPECT_TRUE(matcher.Matches(s));1032EXPECT_FALSE(matcher.Matches(s2));1033}10341035// Tests that ResultOf(f, m) works when f(x) and m's1036// argument types are compatible but different.1037TEST(ResultOfTest, WorksForCompatibleMatcherTypes) {1038// IntFunction() returns int but the inner matcher expects a signed char.1039Matcher<int> matcher = ResultOf(IntFunction, Matcher<signed char>(Ge(85)));10401041EXPECT_TRUE(matcher.Matches(36));1042EXPECT_FALSE(matcher.Matches(42));1043}10441045// Tests that the program aborts when ResultOf is passed1046// a NULL function pointer.1047TEST(ResultOfDeathTest, DiesOnNullFunctionPointers) {1048EXPECT_DEATH_IF_SUPPORTED(1049ResultOf(static_cast<std::string (*)(int dummy)>(nullptr),1050Eq(std::string("foo"))),1051"NULL function pointer is passed into ResultOf\\(\\)\\.");1052}10531054// Tests that ResultOf(f, ...) compiles and works as expected when f is a1055// function reference.1056TEST(ResultOfTest, WorksForFunctionReferences) {1057Matcher<int> matcher = ResultOf(IntToStringFunction, StrEq("foo"));1058EXPECT_TRUE(matcher.Matches(1));1059EXPECT_FALSE(matcher.Matches(2));1060}10611062// Tests that ResultOf(f, ...) compiles and works as expected when f is a1063// function object.1064struct Functor {1065std::string operator()(int input) const { return IntToStringFunction(input); }1066};10671068TEST(ResultOfTest, WorksForFunctors) {1069Matcher<int> matcher = ResultOf(Functor(), Eq(std::string("foo")));10701071EXPECT_TRUE(matcher.Matches(1));1072EXPECT_FALSE(matcher.Matches(2));1073}10741075// Tests that ResultOf(f, ...) compiles and works as expected when f is a1076// functor with more than one operator() defined. ResultOf() must work1077// for each defined operator().1078struct PolymorphicFunctor {1079typedef int result_type;1080int operator()(int n) { return n; }1081int operator()(const char* s) { return static_cast<int>(strlen(s)); }1082std::string operator()(int* p) { return p ? "good ptr" : "null"; }1083};10841085TEST(ResultOfTest, WorksForPolymorphicFunctors) {1086Matcher<int> matcher_int = ResultOf(PolymorphicFunctor(), Ge(5));10871088EXPECT_TRUE(matcher_int.Matches(10));1089EXPECT_FALSE(matcher_int.Matches(2));10901091Matcher<const char*> matcher_string = ResultOf(PolymorphicFunctor(), Ge(5));10921093EXPECT_TRUE(matcher_string.Matches("long string"));1094EXPECT_FALSE(matcher_string.Matches("shrt"));1095}10961097TEST(ResultOfTest, WorksForPolymorphicFunctorsIgnoringResultType) {1098Matcher<int*> matcher = ResultOf(PolymorphicFunctor(), "good ptr");10991100int n = 0;1101EXPECT_TRUE(matcher.Matches(&n));1102EXPECT_FALSE(matcher.Matches(nullptr));1103}11041105TEST(ResultOfTest, WorksForLambdas) {1106Matcher<int> matcher = ResultOf(1107[](int str_len) {1108return std::string(static_cast<size_t>(str_len), 'x');1109},1110"xxx");1111EXPECT_TRUE(matcher.Matches(3));1112EXPECT_FALSE(matcher.Matches(1));1113}11141115TEST(ResultOfTest, WorksForNonCopyableArguments) {1116Matcher<std::unique_ptr<int>> matcher = ResultOf(1117[](const std::unique_ptr<int>& str_len) {1118return std::string(static_cast<size_t>(*str_len), 'x');1119},1120"xxx");1121EXPECT_TRUE(matcher.Matches(std::unique_ptr<int>(new int(3))));1122EXPECT_FALSE(matcher.Matches(std::unique_ptr<int>(new int(1))));1123}11241125const int* ReferencingFunction(const int& n) { return &n; }11261127struct ReferencingFunctor {1128typedef const int* result_type;1129result_type operator()(const int& n) { return &n; }1130};11311132TEST(ResultOfTest, WorksForReferencingCallables) {1133const int n = 1;1134const int n2 = 1;1135Matcher<const int&> matcher2 = ResultOf(ReferencingFunction, Eq(&n));1136EXPECT_TRUE(matcher2.Matches(n));1137EXPECT_FALSE(matcher2.Matches(n2));11381139Matcher<const int&> matcher3 = ResultOf(ReferencingFunctor(), Eq(&n));1140EXPECT_TRUE(matcher3.Matches(n));1141EXPECT_FALSE(matcher3.Matches(n2));1142}11431144TEST(SizeIsTest, ImplementsSizeIs) {1145vector<int> container;1146EXPECT_THAT(container, SizeIs(0));1147EXPECT_THAT(container, Not(SizeIs(1)));1148container.push_back(0);1149EXPECT_THAT(container, Not(SizeIs(0)));1150EXPECT_THAT(container, SizeIs(1));1151container.push_back(0);1152EXPECT_THAT(container, Not(SizeIs(0)));1153EXPECT_THAT(container, SizeIs(2));1154}11551156TEST(SizeIsTest, WorksWithMap) {1157map<std::string, int> container;1158EXPECT_THAT(container, SizeIs(0));1159EXPECT_THAT(container, Not(SizeIs(1)));1160container.insert(make_pair("foo", 1));1161EXPECT_THAT(container, Not(SizeIs(0)));1162EXPECT_THAT(container, SizeIs(1));1163container.insert(make_pair("bar", 2));1164EXPECT_THAT(container, Not(SizeIs(0)));1165EXPECT_THAT(container, SizeIs(2));1166}11671168TEST(SizeIsTest, WorksWithReferences) {1169vector<int> container;1170Matcher<const vector<int>&> m = SizeIs(1);1171EXPECT_THAT(container, Not(m));1172container.push_back(0);1173EXPECT_THAT(container, m);1174}11751176TEST(SizeIsTest, WorksWithMoveOnly) {1177ContainerHelper helper;1178EXPECT_CALL(helper, Call(SizeIs(3)));1179helper.Call(MakeUniquePtrs({1, 2, 3}));1180}11811182// 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.1184struct MinimalistCustomType {1185int size() const { return 1; }1186};1187TEST(SizeIsTest, WorksWithMinimalistCustomType) {1188MinimalistCustomType container;1189EXPECT_THAT(container, SizeIs(1));1190EXPECT_THAT(container, Not(SizeIs(0)));1191}11921193TEST(SizeIsTest, CanDescribeSelf) {1194Matcher<vector<int>> m = SizeIs(2);1195EXPECT_EQ("has a size that is equal to 2", Describe(m));1196EXPECT_EQ("has a size that isn't equal to 2", DescribeNegation(m));1197}11981199TEST(SizeIsTest, ExplainsResult) {1200Matcher<vector<int>> m1 = SizeIs(2);1201Matcher<vector<int>> m2 = SizeIs(Lt(2u));1202Matcher<vector<int>> m3 = SizeIs(AnyOf(0, 3));1203Matcher<vector<int>> m4 = SizeIs(Gt(1u));1204vector<int> container;1205EXPECT_EQ("whose size 0 doesn't match", Explain(m1, container));1206EXPECT_EQ("whose size 0 matches", Explain(m2, container));1207EXPECT_EQ("whose size 0 matches, which matches (is equal to 0)",1208Explain(m3, container));1209EXPECT_EQ("whose size 0 doesn't match", Explain(m4, container));1210container.push_back(0);1211container.push_back(0);1212EXPECT_EQ("whose size 2 matches", Explain(m1, container));1213EXPECT_EQ("whose size 2 doesn't match", Explain(m2, container));1214EXPECT_EQ(1215"whose size 2 doesn't match, isn't equal to 0, and isn't equal to 3",1216Explain(m3, container));1217EXPECT_EQ("whose size 2 matches", Explain(m4, container));1218}12191220TEST(WhenSortedByTest, WorksForEmptyContainer) {1221const vector<int> numbers;1222EXPECT_THAT(numbers, WhenSortedBy(less<int>(), ElementsAre()));1223EXPECT_THAT(numbers, Not(WhenSortedBy(less<int>(), ElementsAre(1))));1224}12251226TEST(WhenSortedByTest, WorksForNonEmptyContainer) {1227vector<unsigned> numbers;1228numbers.push_back(3);1229numbers.push_back(1);1230numbers.push_back(2);1231numbers.push_back(2);1232EXPECT_THAT(numbers,1233WhenSortedBy(greater<unsigned>(), ElementsAre(3, 2, 2, 1)));1234EXPECT_THAT(numbers,1235Not(WhenSortedBy(greater<unsigned>(), ElementsAre(1, 2, 2, 3))));1236}12371238TEST(WhenSortedByTest, WorksForNonVectorContainer) {1239list<std::string> words;1240words.push_back("say");1241words.push_back("hello");1242words.push_back("world");1243EXPECT_THAT(words, WhenSortedBy(less<std::string>(),1244ElementsAre("hello", "say", "world")));1245EXPECT_THAT(words, Not(WhenSortedBy(less<std::string>(),1246ElementsAre("say", "hello", "world"))));1247}12481249TEST(WhenSortedByTest, WorksForNativeArray) {1250const int numbers[] = {1, 3, 2, 4};1251const int sorted_numbers[] = {1, 2, 3, 4};1252EXPECT_THAT(numbers, WhenSortedBy(less<int>(), ElementsAre(1, 2, 3, 4)));1253EXPECT_THAT(numbers,1254WhenSortedBy(less<int>(), ElementsAreArray(sorted_numbers)));1255EXPECT_THAT(numbers, Not(WhenSortedBy(less<int>(), ElementsAre(1, 3, 2, 4))));1256}12571258TEST(WhenSortedByTest, CanDescribeSelf) {1259const Matcher<vector<int>> m = WhenSortedBy(less<int>(), ElementsAre(1, 2));1260EXPECT_EQ(1261"(when sorted) has 2 elements where\n"1262"element #0 is equal to 1,\n"1263"element #1 is equal to 2",1264Describe(m));1265EXPECT_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",1269DescribeNegation(m));1270}12711272TEST(WhenSortedByTest, ExplainsMatchResult) {1273const int a[] = {2, 1};1274EXPECT_EQ(1275Explain(WhenSortedBy(less<int>(), ElementsAre(2, 3)), a),1276"which is { 1, 2 } when sorted, whose element #0 (1) isn't equal to 2");1277EXPECT_EQ(Explain(WhenSortedBy(less<int>(), ElementsAre(1, 2)), a),1278"which is { 1, 2 } when sorted");1279}12801281// WhenSorted() is a simple wrapper on WhenSortedBy(). Hence we don't1282// need to test it as exhaustively as we test the latter.12831284TEST(WhenSortedTest, WorksForEmptyContainer) {1285const vector<int> numbers;1286EXPECT_THAT(numbers, WhenSorted(ElementsAre()));1287EXPECT_THAT(numbers, Not(WhenSorted(ElementsAre(1))));1288}12891290TEST(WhenSortedTest, WorksForNonEmptyContainer) {1291list<std::string> words;1292words.push_back("3");1293words.push_back("1");1294words.push_back("2");1295words.push_back("2");1296EXPECT_THAT(words, WhenSorted(ElementsAre("1", "2", "2", "3")));1297EXPECT_THAT(words, Not(WhenSorted(ElementsAre("3", "1", "2", "2"))));1298}12991300TEST(WhenSortedTest, WorksForMapTypes) {1301map<std::string, int> word_counts;1302word_counts["and"] = 1;1303word_counts["the"] = 1;1304word_counts["buffalo"] = 2;1305EXPECT_THAT(word_counts,1306WhenSorted(ElementsAre(Pair("and", 1), Pair("buffalo", 2),1307Pair("the", 1))));1308EXPECT_THAT(word_counts,1309Not(WhenSorted(ElementsAre(Pair("and", 1), Pair("the", 1),1310Pair("buffalo", 2)))));1311}13121313TEST(WhenSortedTest, WorksForMultiMapTypes) {1314multimap<int, int> ifib;1315ifib.insert(make_pair(8, 6));1316ifib.insert(make_pair(2, 3));1317ifib.insert(make_pair(1, 1));1318ifib.insert(make_pair(3, 4));1319ifib.insert(make_pair(1, 2));1320ifib.insert(make_pair(5, 5));1321EXPECT_THAT(ifib,1322WhenSorted(ElementsAre(Pair(1, 1), Pair(1, 2), Pair(2, 3),1323Pair(3, 4), Pair(5, 5), Pair(8, 6))));1324EXPECT_THAT(ifib,1325Not(WhenSorted(ElementsAre(Pair(8, 6), Pair(2, 3), Pair(1, 1),1326Pair(3, 4), Pair(1, 2), Pair(5, 5)))));1327}13281329TEST(WhenSortedTest, WorksForPolymorphicMatcher) {1330std::deque<int> d;1331d.push_back(2);1332d.push_back(1);1333EXPECT_THAT(d, WhenSorted(ElementsAre(1, 2)));1334EXPECT_THAT(d, Not(WhenSorted(ElementsAre(2, 1))));1335}13361337TEST(WhenSortedTest, WorksForVectorConstRefMatcher) {1338std::deque<int> d;1339d.push_back(2);1340d.push_back(1);1341Matcher<const std::vector<int>&> vector_match = ElementsAre(1, 2);1342EXPECT_THAT(d, WhenSorted(vector_match));1343Matcher<const std::vector<int>&> not_vector_match = ElementsAre(2, 1);1344EXPECT_THAT(d, Not(WhenSorted(not_vector_match)));1345}13461347// Deliberately bare pseudo-container.1348// Offers only begin() and end() accessors, yielding InputIterator.1349template <typename T>1350class Streamlike {1351private:1352class ConstIter;13531354public:1355typedef ConstIter const_iterator;1356typedef T value_type;13571358template <typename InIter>1359Streamlike(InIter first, InIter last) : remainder_(first, last) {}13601361const_iterator begin() const {1362return const_iterator(this, remainder_.begin());1363}1364const_iterator end() const { return const_iterator(this, remainder_.end()); }13651366private:1367class ConstIter {1368public:1369using iterator_category = std::input_iterator_tag;1370using value_type = T;1371using difference_type = ptrdiff_t;1372using pointer = const value_type*;1373using reference = const value_type&;13741375ConstIter(const Streamlike* s, typename std::list<value_type>::iterator pos)1376: s_(s), pos_(pos) {}13771378const value_type& operator*() const { return *pos_; }1379const value_type* operator->() const { return &*pos_; }1380ConstIter& operator++() {1381s_->remainder_.erase(pos_++);1382return *this;1383}13841385// *iter++ is required to work (see std::istreambuf_iterator).1386// (void)iter++ is also required to work.1387class PostIncrProxy {1388public:1389explicit PostIncrProxy(const value_type& value) : value_(value) {}1390value_type operator*() const { return value_; }13911392private:1393value_type value_;1394};1395PostIncrProxy operator++(int) {1396PostIncrProxy proxy(**this);1397++(*this);1398return proxy;1399}14001401friend bool operator==(const ConstIter& a, const ConstIter& b) {1402return a.s_ == b.s_ && a.pos_ == b.pos_;1403}1404friend bool operator!=(const ConstIter& a, const ConstIter& b) {1405return !(a == b);1406}14071408private:1409const Streamlike* s_;1410typename std::list<value_type>::iterator pos_;1411};14121413friend std::ostream& operator<<(std::ostream& os, const Streamlike& s) {1414os << "[";1415typedef typename std::list<value_type>::const_iterator Iter;1416const char* sep = "";1417for (Iter it = s.remainder_.begin(); it != s.remainder_.end(); ++it) {1418os << sep << *it;1419sep = ",";1420}1421os << "]";1422return os;1423}14241425mutable std::list<value_type> remainder_; // modified by iteration1426};14271428TEST(StreamlikeTest, Iteration) {1429const int a[5] = {2, 1, 4, 5, 3};1430Streamlike<int> s(a, a + 5);1431Streamlike<int>::const_iterator it = s.begin();1432const int* ip = a;1433while (it != s.end()) {1434SCOPED_TRACE(ip - a);1435EXPECT_EQ(*ip++, *it++);1436}1437}14381439INSTANTIATE_GTEST_MATCHER_TEST_P(BeginEndDistanceIsTest);14401441TEST(BeginEndDistanceIsTest, WorksWithForwardList) {1442std::forward_list<int> container;1443EXPECT_THAT(container, BeginEndDistanceIs(0));1444EXPECT_THAT(container, Not(BeginEndDistanceIs(1)));1445container.push_front(0);1446EXPECT_THAT(container, Not(BeginEndDistanceIs(0)));1447EXPECT_THAT(container, BeginEndDistanceIs(1));1448container.push_front(0);1449EXPECT_THAT(container, Not(BeginEndDistanceIs(0)));1450EXPECT_THAT(container, BeginEndDistanceIs(2));1451}14521453TEST(BeginEndDistanceIsTest, WorksWithNonStdList) {1454const int a[5] = {1, 2, 3, 4, 5};1455Streamlike<int> s(a, a + 5);1456EXPECT_THAT(s, BeginEndDistanceIs(5));1457}14581459TEST(BeginEndDistanceIsTest, CanDescribeSelf) {1460Matcher<vector<int>> m = BeginEndDistanceIs(2);1461EXPECT_EQ("distance between begin() and end() is equal to 2", Describe(m));1462EXPECT_EQ("distance between begin() and end() isn't equal to 2",1463DescribeNegation(m));1464}14651466TEST(BeginEndDistanceIsTest, WorksWithMoveOnly) {1467ContainerHelper helper;1468EXPECT_CALL(helper, Call(BeginEndDistanceIs(2)));1469helper.Call(MakeUniquePtrs({1, 2}));1470}14711472TEST_P(BeginEndDistanceIsTestP, ExplainsResult) {1473Matcher<vector<int>> m1 = BeginEndDistanceIs(2);1474Matcher<vector<int>> m2 = BeginEndDistanceIs(Lt(2));1475Matcher<vector<int>> m3 = BeginEndDistanceIs(AnyOf(0, 3));1476Matcher<vector<int>> m4 = BeginEndDistanceIs(GreaterThan(1));1477vector<int> container;1478EXPECT_EQ("whose distance between begin() and end() 0 doesn't match",1479Explain(m1, container));1480EXPECT_EQ("whose distance between begin() and end() 0 matches",1481Explain(m2, container));1482EXPECT_EQ(1483"whose distance between begin() and end() 0 matches, which matches (is "1484"equal to 0)",1485Explain(m3, container));1486EXPECT_EQ(1487"whose distance between begin() and end() 0 doesn't match, which is 1 "1488"less than 1",1489Explain(m4, container));1490container.push_back(0);1491container.push_back(0);1492EXPECT_EQ("whose distance between begin() and end() 2 matches",1493Explain(m1, container));1494EXPECT_EQ("whose distance between begin() and end() 2 doesn't match",1495Explain(m2, container));1496EXPECT_EQ(1497"whose distance between begin() and end() 2 doesn't match, isn't equal "1498"to 0, and isn't equal to 3",1499Explain(m3, container));1500EXPECT_EQ(1501"whose distance between begin() and end() 2 matches, which is 1 more "1502"than 1",1503Explain(m4, container));1504}15051506TEST(WhenSortedTest, WorksForStreamlike) {1507// Streamlike 'container' provides only minimal iterator support.1508// Its iterators are tagged with input_iterator_tag.1509const int a[5] = {2, 1, 4, 5, 3};1510Streamlike<int> s(std::begin(a), std::end(a));1511EXPECT_THAT(s, WhenSorted(ElementsAre(1, 2, 3, 4, 5)));1512EXPECT_THAT(s, Not(WhenSorted(ElementsAre(2, 1, 4, 5, 3))));1513}15141515TEST(WhenSortedTest, WorksForVectorConstRefMatcherOnStreamlike) {1516const int a[] = {2, 1, 4, 5, 3};1517Streamlike<int> s(std::begin(a), std::end(a));1518Matcher<const std::vector<int>&> vector_match = ElementsAre(1, 2, 3, 4, 5);1519EXPECT_THAT(s, WhenSorted(vector_match));1520EXPECT_THAT(s, Not(WhenSorted(ElementsAre(2, 1, 4, 5, 3))));1521}15221523TEST(IsSupersetOfTest, WorksForNativeArray) {1524const int subset[] = {1, 4};1525const int superset[] = {1, 2, 4};1526const int disjoint[] = {1, 0, 3};1527EXPECT_THAT(subset, IsSupersetOf(subset));1528EXPECT_THAT(subset, Not(IsSupersetOf(superset)));1529EXPECT_THAT(superset, IsSupersetOf(subset));1530EXPECT_THAT(subset, Not(IsSupersetOf(disjoint)));1531EXPECT_THAT(disjoint, Not(IsSupersetOf(subset)));1532}15331534TEST(IsSupersetOfTest, WorksWithDuplicates) {1535const int not_enough[] = {1, 2};1536const int enough[] = {1, 1, 2};1537const int expected[] = {1, 1};1538EXPECT_THAT(not_enough, Not(IsSupersetOf(expected)));1539EXPECT_THAT(enough, IsSupersetOf(expected));1540}15411542TEST(IsSupersetOfTest, WorksForEmpty) {1543vector<int> numbers;1544vector<int> expected;1545EXPECT_THAT(numbers, IsSupersetOf(expected));1546expected.push_back(1);1547EXPECT_THAT(numbers, Not(IsSupersetOf(expected)));1548expected.clear();1549numbers.push_back(1);1550numbers.push_back(2);1551EXPECT_THAT(numbers, IsSupersetOf(expected));1552expected.push_back(1);1553EXPECT_THAT(numbers, IsSupersetOf(expected));1554expected.push_back(2);1555EXPECT_THAT(numbers, IsSupersetOf(expected));1556expected.push_back(3);1557EXPECT_THAT(numbers, Not(IsSupersetOf(expected)));1558}15591560TEST(IsSupersetOfTest, WorksForStreamlike) {1561const int a[5] = {1, 2, 3, 4, 5};1562Streamlike<int> s(std::begin(a), std::end(a));15631564vector<int> expected;1565expected.push_back(1);1566expected.push_back(2);1567expected.push_back(5);1568EXPECT_THAT(s, IsSupersetOf(expected));15691570expected.push_back(0);1571EXPECT_THAT(s, Not(IsSupersetOf(expected)));1572}15731574TEST(IsSupersetOfTest, TakesStlContainer) {1575const int actual[] = {3, 1, 2};15761577::std::list<int> expected;1578expected.push_back(1);1579expected.push_back(3);1580EXPECT_THAT(actual, IsSupersetOf(expected));15811582expected.push_back(4);1583EXPECT_THAT(actual, Not(IsSupersetOf(expected)));1584}15851586TEST(IsSupersetOfTest, Describe) {1587typedef std::vector<int> IntVec;1588IntVec expected;1589expected.push_back(111);1590expected.push_back(222);1591expected.push_back(333);1592EXPECT_THAT(1593Describe<IntVec>(IsSupersetOf(expected)),1594Eq("a surjection from elements to requirements exists such that:\n"1595" - an element is equal to 111\n"1596" - an element is equal to 222\n"1597" - an element is equal to 333"));1598}15991600TEST(IsSupersetOfTest, DescribeNegation) {1601typedef std::vector<int> IntVec;1602IntVec expected;1603expected.push_back(111);1604expected.push_back(222);1605expected.push_back(333);1606EXPECT_THAT(1607DescribeNegation<IntVec>(IsSupersetOf(expected)),1608Eq("no surjection from elements to requirements exists such that:\n"1609" - an element is equal to 111\n"1610" - an element is equal to 222\n"1611" - an element is equal to 333"));1612}16131614TEST(IsSupersetOfTest, MatchAndExplain) {1615std::vector<int> v;1616v.push_back(2);1617v.push_back(3);1618std::vector<int> expected;1619expected.push_back(1);1620expected.push_back(2);1621StringMatchResultListener listener;1622ASSERT_FALSE(ExplainMatchResult(IsSupersetOf(expected), v, &listener))1623<< listener.str();1624EXPECT_THAT(listener.str(),1625Eq("where the following matchers don't match any elements:\n"1626"matcher #0: is equal to 1"));16271628v.push_back(1);1629listener.Clear();1630ASSERT_TRUE(ExplainMatchResult(IsSupersetOf(expected), v, &listener))1631<< listener.str();1632EXPECT_THAT(listener.str(), Eq("where:\n"1633" - element #0 is matched by matcher #1,\n"1634" - element #2 is matched by matcher #0"));1635}16361637TEST(IsSupersetOfTest, WorksForRhsInitializerList) {1638const int numbers[] = {1, 3, 6, 2, 4, 5};1639EXPECT_THAT(numbers, IsSupersetOf({1, 2}));1640EXPECT_THAT(numbers, Not(IsSupersetOf({3, 0})));1641}16421643TEST(IsSupersetOfTest, WorksWithMoveOnly) {1644ContainerHelper helper;1645EXPECT_CALL(helper, Call(IsSupersetOf({Pointee(1)})));1646helper.Call(MakeUniquePtrs({1, 2}));1647EXPECT_CALL(helper, Call(Not(IsSupersetOf({Pointee(1), Pointee(2)}))));1648helper.Call(MakeUniquePtrs({2}));1649}16501651TEST(IsSubsetOfTest, WorksForNativeArray) {1652const int subset[] = {1, 4};1653const int superset[] = {1, 2, 4};1654const int disjoint[] = {1, 0, 3};1655EXPECT_THAT(subset, IsSubsetOf(subset));1656EXPECT_THAT(subset, IsSubsetOf(superset));1657EXPECT_THAT(superset, Not(IsSubsetOf(subset)));1658EXPECT_THAT(subset, Not(IsSubsetOf(disjoint)));1659EXPECT_THAT(disjoint, Not(IsSubsetOf(subset)));1660}16611662TEST(IsSubsetOfTest, WorksWithDuplicates) {1663const int not_enough[] = {1, 2};1664const int enough[] = {1, 1, 2};1665const int actual[] = {1, 1};1666EXPECT_THAT(actual, Not(IsSubsetOf(not_enough)));1667EXPECT_THAT(actual, IsSubsetOf(enough));1668}16691670TEST(IsSubsetOfTest, WorksForEmpty) {1671vector<int> numbers;1672vector<int> expected;1673EXPECT_THAT(numbers, IsSubsetOf(expected));1674expected.push_back(1);1675EXPECT_THAT(numbers, IsSubsetOf(expected));1676expected.clear();1677numbers.push_back(1);1678numbers.push_back(2);1679EXPECT_THAT(numbers, Not(IsSubsetOf(expected)));1680expected.push_back(1);1681EXPECT_THAT(numbers, Not(IsSubsetOf(expected)));1682expected.push_back(2);1683EXPECT_THAT(numbers, IsSubsetOf(expected));1684expected.push_back(3);1685EXPECT_THAT(numbers, IsSubsetOf(expected));1686}16871688TEST(IsSubsetOfTest, WorksForStreamlike) {1689const int a[5] = {1, 2};1690Streamlike<int> s(std::begin(a), std::end(a));16911692vector<int> expected;1693expected.push_back(1);1694EXPECT_THAT(s, Not(IsSubsetOf(expected)));1695expected.push_back(2);1696expected.push_back(5);1697EXPECT_THAT(s, IsSubsetOf(expected));1698}16991700TEST(IsSubsetOfTest, TakesStlContainer) {1701const int actual[] = {3, 1, 2};17021703::std::list<int> expected;1704expected.push_back(1);1705expected.push_back(3);1706EXPECT_THAT(actual, Not(IsSubsetOf(expected)));17071708expected.push_back(2);1709expected.push_back(4);1710EXPECT_THAT(actual, IsSubsetOf(expected));1711}17121713TEST(IsSubsetOfTest, Describe) {1714typedef std::vector<int> IntVec;1715IntVec expected;1716expected.push_back(111);1717expected.push_back(222);1718expected.push_back(333);17191720EXPECT_THAT(1721Describe<IntVec>(IsSubsetOf(expected)),1722Eq("an injection from elements to requirements exists such that:\n"1723" - an element is equal to 111\n"1724" - an element is equal to 222\n"1725" - an element is equal to 333"));1726}17271728TEST(IsSubsetOfTest, DescribeNegation) {1729typedef std::vector<int> IntVec;1730IntVec expected;1731expected.push_back(111);1732expected.push_back(222);1733expected.push_back(333);1734EXPECT_THAT(1735DescribeNegation<IntVec>(IsSubsetOf(expected)),1736Eq("no injection from elements to requirements exists such that:\n"1737" - an element is equal to 111\n"1738" - an element is equal to 222\n"1739" - an element is equal to 333"));1740}17411742TEST(IsSubsetOfTest, MatchAndExplain) {1743std::vector<int> v;1744v.push_back(2);1745v.push_back(3);1746std::vector<int> expected;1747expected.push_back(1);1748expected.push_back(2);1749StringMatchResultListener listener;1750ASSERT_FALSE(ExplainMatchResult(IsSubsetOf(expected), v, &listener))1751<< listener.str();1752EXPECT_THAT(listener.str(),1753Eq("where the following elements don't match any matchers:\n"1754"element #1: 3"));17551756expected.push_back(3);1757listener.Clear();1758ASSERT_TRUE(ExplainMatchResult(IsSubsetOf(expected), v, &listener))1759<< listener.str();1760EXPECT_THAT(listener.str(), Eq("where:\n"1761" - element #0 is matched by matcher #1,\n"1762" - element #1 is matched by matcher #2"));1763}17641765TEST(IsSubsetOfTest, WorksForRhsInitializerList) {1766const int numbers[] = {1, 2, 3};1767EXPECT_THAT(numbers, IsSubsetOf({1, 2, 3, 4}));1768EXPECT_THAT(numbers, Not(IsSubsetOf({1, 2})));1769}17701771TEST(IsSubsetOfTest, WorksWithMoveOnly) {1772ContainerHelper helper;1773EXPECT_CALL(helper, Call(IsSubsetOf({Pointee(1), Pointee(2)})));1774helper.Call(MakeUniquePtrs({1}));1775EXPECT_CALL(helper, Call(Not(IsSubsetOf({Pointee(1)}))));1776helper.Call(MakeUniquePtrs({2}));1777}17781779// A container whose iterator returns a temporary. This can iterate over the1780// characters in a string.1781class CharString {1782public:1783using value_type = char;17841785class const_iterator {1786public:1787using iterator_category = std::input_iterator_tag;1788using value_type = char;1789using difference_type = std::ptrdiff_t;1790using pointer = const char*;1791using reference = const char&;17921793// Create an iterator that points to the given character.1794explicit const_iterator(const char* ptr) : ptr_(ptr) {}17951796// Returns the current character. IMPORTANT: this must return a temporary,1797// not a reference, to test that ElementsAre() works with containers whose1798// iterators return temporaries.1799char operator*() const { return *ptr_; }18001801// Advances to the next character.1802const_iterator& operator++() {1803++ptr_;1804return *this;1805}18061807// Compares two iterators.1808bool operator==(const const_iterator& other) const {1809return ptr_ == other.ptr_;1810}1811bool operator!=(const const_iterator& other) const {1812return ptr_ != other.ptr_;1813}18141815private:1816const char* ptr_ = nullptr;1817};18181819// Creates a CharString that contains the given string.1820explicit CharString(const std::string& s) : s_(s) {}18211822// Returns an iterator pointing to the first character in the string.1823const_iterator begin() const { return const_iterator(s_.c_str()); }18241825// Returns an iterator pointing past the last character in the string.1826const_iterator end() const { return const_iterator(s_.c_str() + s_.size()); }18271828private:1829std::string s_;1830};18311832// Tests using ElementsAre() with a container whose iterator returns a1833// temporary.1834TEST(ElementsAreTest, WorksWithContainerThatReturnsTempInIterator) {1835CharString s("abc");1836EXPECT_THAT(s, ElementsAre('a', 'b', 'c'));1837EXPECT_THAT(s, Not(ElementsAre('a', 'b', 'd')));1838}18391840// Tests using ElementsAreArray() with a container whose iterator returns a1841// temporary.1842TEST(ElementsAreArrayTest, WorksWithContainerThatReturnsTempInIterator) {1843CharString s("abc");1844EXPECT_THAT(s, ElementsAreArray({'a', 'b', 'c'}));1845EXPECT_THAT(s, Not(ElementsAreArray({'a', 'b', 'd'})));1846}18471848// A container whose iterator returns a temporary and is not copy-assignable.1849// This simulates the behavior of the proxy object returned by absl::StrSplit().1850class CharString2 {1851public:1852using value_type = char;18531854class const_iterator {1855public:1856using iterator_category = std::input_iterator_tag;1857using value_type = char;1858using difference_type = std::ptrdiff_t;1859using pointer = const char*;1860using reference = const char&;18611862// Make const_iterator copy-constructible but not copy-assignable,1863// simulating the behavior of the proxy object returned by absl::StrSplit().1864const_iterator(const const_iterator&) = default;1865const_iterator& operator=(const const_iterator&) = delete;18661867// Create an iterator that points to the given character.1868explicit const_iterator(const char* ptr) : ptr_(ptr) {}18691870// Returns the current character. IMPORTANT: this must return a temporary,1871// not a reference, to test that ElementsAre() works with containers whose1872// iterators return temporaries.1873char operator*() const { return *ptr_; }18741875// Advances to the next character.1876const_iterator& operator++() {1877++ptr_;1878return *this;1879}18801881// Compares two iterators.1882bool operator==(const const_iterator& other) const {1883return ptr_ == other.ptr_;1884}1885bool operator!=(const const_iterator& other) const {1886return ptr_ != other.ptr_;1887}18881889private:1890const char* ptr_ = nullptr;1891};18921893// Creates a CharString that contains the given string.1894explicit CharString2(const std::string& s) : s_(s) {}18951896// Returns an iterator pointing to the first character in the string.1897const_iterator begin() const { return const_iterator(s_.c_str()); }18981899// Returns an iterator pointing past the last character in the string.1900const_iterator end() const { return const_iterator(s_.c_str() + s_.size()); }19011902private:1903std::string s_;1904};19051906// Tests using ElementsAre() with a container whose iterator returns a1907// temporary and is not copy-assignable.1908TEST(ElementsAreTest, WorksWithContainerThatReturnsTempInUnassignableIterator) {1909CharString2 s("abc");1910EXPECT_THAT(s, ElementsAre('a', 'b', 'c'));1911EXPECT_THAT(s, Not(ElementsAre('a', 'b', 'd')));1912}19131914// Tests using ElementsAreArray() with a container whose iterator returns a1915// temporary and is not copy-assignable.1916TEST(ElementsAreArrayTest,1917WorksWithContainerThatReturnsTempInUnassignableIterator) {1918CharString2 s("abc");1919EXPECT_THAT(s, ElementsAreArray({'a', 'b', 'c'}));1920EXPECT_THAT(s, Not(ElementsAreArray({'a', 'b', 'd'})));1921}19221923// A container whose iterator returns a temporary and is neither1924// copy-constructible nor copy-assignable.1925class CharString3 {1926public:1927using value_type = char;19281929class const_iterator {1930public:1931using iterator_category = std::input_iterator_tag;1932using value_type = char;1933using difference_type = std::ptrdiff_t;1934using pointer = const char*;1935using reference = const char&;19361937// Make const_iterator neither copy-constructible nor copy-assignable.1938const_iterator(const const_iterator&) = delete;1939const_iterator& operator=(const const_iterator&) = delete;19401941// Create an iterator that points to the given character.1942explicit const_iterator(const char* ptr) : ptr_(ptr) {}19431944// Returns the current character. IMPORTANT: this must return a temporary,1945// not a reference, to test that ElementsAre() works with containers whose1946// iterators return temporaries.1947char operator*() const { return *ptr_; }19481949// Advances to the next character.1950const_iterator& operator++() {1951++ptr_;1952return *this;1953}19541955// Compares two iterators.1956bool operator==(const const_iterator& other) const {1957return ptr_ == other.ptr_;1958}1959bool operator!=(const const_iterator& other) const {1960return ptr_ != other.ptr_;1961}19621963private:1964const char* ptr_ = nullptr;1965};19661967// Creates a CharString that contains the given string.1968explicit CharString3(const std::string& s) : s_(s) {}19691970// Returns an iterator pointing to the first character in the string.1971const_iterator begin() const { return const_iterator(s_.c_str()); }19721973// Returns an iterator pointing past the last character in the string.1974const_iterator end() const { return const_iterator(s_.c_str() + s_.size()); }19751976private:1977std::string s_;1978};19791980// Tests using ElementsAre() with a container whose iterator returns a1981// temporary and is neither copy-constructible nor copy-assignable.1982TEST(ElementsAreTest, WorksWithContainerThatReturnsTempInUncopyableIterator) {1983CharString3 s("abc");1984EXPECT_THAT(s, ElementsAre('a', 'b', 'c'));1985EXPECT_THAT(s, Not(ElementsAre('a', 'b', 'd')));1986}19871988// Tests using ElementsAreArray() with a container whose iterator returns a1989// temporary and is neither copy-constructible nor copy-assignable.1990TEST(ElementsAreArrayTest,1991WorksWithContainerThatReturnsTempInUncopyableIterator) {1992CharString3 s("abc");1993EXPECT_THAT(s, ElementsAreArray({'a', 'b', 'c'}));1994EXPECT_THAT(s, Not(ElementsAreArray({'a', 'b', 'd'})));1995}19961997// A container whose iterator returns a temporary, is neither1998// copy-constructible nor copy-assignable, and has no member types.1999class CharString4 {2000public:2001using value_type = char;20022003class const_iterator {2004public:2005// Do not define difference_type, etc.20062007// Make const_iterator neither copy-constructible nor copy-assignable.2008const_iterator(const const_iterator&) = delete;2009const_iterator& operator=(const const_iterator&) = delete;20102011// Create an iterator that points to the given character.2012explicit const_iterator(const char* ptr) : ptr_(ptr) {}20132014// Returns the current character. IMPORTANT: this must return a temporary,2015// not a reference, to test that ElementsAre() works with containers whose2016// iterators return temporaries.2017char operator*() const { return *ptr_; }20182019// Advances to the next character.2020const_iterator& operator++() {2021++ptr_;2022return *this;2023}20242025// Compares two iterators.2026bool operator==(const const_iterator& other) const {2027return ptr_ == other.ptr_;2028}2029bool operator!=(const const_iterator& other) const {2030return ptr_ != other.ptr_;2031}20322033private:2034const char* ptr_ = nullptr;2035};20362037// Creates a CharString that contains the given string.2038explicit CharString4(const std::string& s) : s_(s) {}20392040// Returns an iterator pointing to the first character in the string.2041const_iterator begin() const { return const_iterator(s_.c_str()); }20422043// Returns an iterator pointing past the last character in the string.2044const_iterator end() const { return const_iterator(s_.c_str() + s_.size()); }20452046private:2047std::string s_;2048};20492050// Tests using ElementsAre() with a container whose iterator returns a2051// temporary, is neither copy-constructible nor copy-assignable, and has no2052// member types.2053TEST(ElementsAreTest, WorksWithContainerWithIteratorWithNoMemberTypes) {2054CharString4 s("abc");2055EXPECT_THAT(s, ElementsAre('a', 'b', 'c'));2056EXPECT_THAT(s, Not(ElementsAre('a', 'b', 'd')));2057}20582059// Tests using ElementsAreArray() with a container whose iterator returns a2060// temporary, is neither copy-constructible nor copy-assignable, and has no2061// member types.2062TEST(ElementsAreArrayTest, WorksWithContainerWithIteratorWithNoMemberTypes) {2063CharString4 s("abc");2064EXPECT_THAT(s, ElementsAreArray({'a', 'b', 'c'}));2065EXPECT_THAT(s, Not(ElementsAreArray({'a', 'b', 'd'})));2066}20672068// Tests using ElementsAre() and ElementsAreArray() with stream-like2069// "containers".20702071TEST(ElemensAreStreamTest, WorksForStreamlike) {2072const int a[5] = {1, 2, 3, 4, 5};2073Streamlike<int> s(std::begin(a), std::end(a));2074EXPECT_THAT(s, ElementsAre(1, 2, 3, 4, 5));2075EXPECT_THAT(s, Not(ElementsAre(2, 1, 4, 5, 3)));2076}20772078TEST(ElemensAreArrayStreamTest, WorksForStreamlike) {2079const int a[5] = {1, 2, 3, 4, 5};2080Streamlike<int> s(std::begin(a), std::end(a));20812082vector<int> expected;2083expected.push_back(1);2084expected.push_back(2);2085expected.push_back(3);2086expected.push_back(4);2087expected.push_back(5);2088EXPECT_THAT(s, ElementsAreArray(expected));20892090expected[3] = 0;2091EXPECT_THAT(s, Not(ElementsAreArray(expected)));2092}20932094TEST(ElementsAreTest, WorksWithUncopyable) {2095Uncopyable objs[2];2096objs[0].set_value(-3);2097objs[1].set_value(1);2098EXPECT_THAT(objs, ElementsAre(UncopyableIs(-3), Truly(ValueIsPositive)));2099}21002101TEST(ElementsAreTest, WorksWithMoveOnly) {2102ContainerHelper helper;2103EXPECT_CALL(helper, Call(ElementsAre(Pointee(1), Pointee(2))));2104helper.Call(MakeUniquePtrs({1, 2}));21052106EXPECT_CALL(helper, Call(ElementsAreArray({Pointee(3), Pointee(4)})));2107helper.Call(MakeUniquePtrs({3, 4}));2108}21092110TEST(ElementsAreTest, TakesStlContainer) {2111const int actual[] = {3, 1, 2};21122113::std::list<int> expected;2114expected.push_back(3);2115expected.push_back(1);2116expected.push_back(2);2117EXPECT_THAT(actual, ElementsAreArray(expected));21182119expected.push_back(4);2120EXPECT_THAT(actual, Not(ElementsAreArray(expected)));2121}21222123// Tests for UnorderedElementsAreArray()21242125TEST(UnorderedElementsAreArrayTest, SucceedsWhenExpected) {2126const int a[] = {0, 1, 2, 3, 4};2127std::vector<int> s(std::begin(a), std::end(a));2128do {2129StringMatchResultListener listener;2130EXPECT_TRUE(ExplainMatchResult(UnorderedElementsAreArray(a), s, &listener))2131<< listener.str();2132} while (std::next_permutation(s.begin(), s.end()));2133}21342135TEST(UnorderedElementsAreArrayTest, VectorBool) {2136const bool a[] = {false, true, false, true, true};2137const bool b[] = {true, false, true, true, false};2138std::vector<bool> expected(std::begin(a), std::end(a));2139std::vector<bool> actual(std::begin(b), std::end(b));2140StringMatchResultListener listener;2141EXPECT_TRUE(ExplainMatchResult(UnorderedElementsAreArray(expected), actual,2142&listener))2143<< listener.str();2144}21452146TEST(UnorderedElementsAreArrayTest, WorksForStreamlike) {2147// Streamlike 'container' provides only minimal iterator support.2148// Its iterators are tagged with input_iterator_tag, and it has no2149// size() or empty() methods.2150const int a[5] = {2, 1, 4, 5, 3};2151Streamlike<int> s(std::begin(a), std::end(a));21522153::std::vector<int> expected;2154expected.push_back(1);2155expected.push_back(2);2156expected.push_back(3);2157expected.push_back(4);2158expected.push_back(5);2159EXPECT_THAT(s, UnorderedElementsAreArray(expected));21602161expected.push_back(6);2162EXPECT_THAT(s, Not(UnorderedElementsAreArray(expected)));2163}21642165TEST(UnorderedElementsAreArrayTest, TakesStlContainer) {2166const int actual[] = {3, 1, 2};21672168::std::list<int> expected;2169expected.push_back(1);2170expected.push_back(2);2171expected.push_back(3);2172EXPECT_THAT(actual, UnorderedElementsAreArray(expected));21732174expected.push_back(4);2175EXPECT_THAT(actual, Not(UnorderedElementsAreArray(expected)));2176}21772178TEST(UnorderedElementsAreArrayTest, TakesInitializerList) {2179const int a[5] = {2, 1, 4, 5, 3};2180EXPECT_THAT(a, UnorderedElementsAreArray({1, 2, 3, 4, 5}));2181EXPECT_THAT(a, Not(UnorderedElementsAreArray({1, 2, 3, 4, 6})));2182}21832184TEST(UnorderedElementsAreArrayTest, TakesInitializerListOfCStrings) {2185const std::string a[5] = {"a", "b", "c", "d", "e"};2186EXPECT_THAT(a, UnorderedElementsAreArray({"a", "b", "c", "d", "e"}));2187EXPECT_THAT(a, Not(UnorderedElementsAreArray({"a", "b", "c", "d", "ef"})));2188}21892190TEST(UnorderedElementsAreArrayTest, TakesInitializerListOfSameTypedMatchers) {2191const int a[5] = {2, 1, 4, 5, 3};2192EXPECT_THAT(a,2193UnorderedElementsAreArray({Eq(1), Eq(2), Eq(3), Eq(4), Eq(5)}));2194EXPECT_THAT(2195a, Not(UnorderedElementsAreArray({Eq(1), Eq(2), Eq(3), Eq(4), Eq(6)})));2196}21972198TEST(UnorderedElementsAreArrayTest,2199TakesInitializerListOfDifferentTypedMatchers) {2200const int a[5] = {2, 1, 4, 5, 3};2201// The compiler cannot infer the type of the initializer list if its2202// elements have different types. We must explicitly specify the2203// unified element type in this case.2204EXPECT_THAT(a, UnorderedElementsAreArray<Matcher<int>>(2205{Eq(1), Ne(-2), Ge(3), Le(4), Eq(5)}));2206EXPECT_THAT(a, Not(UnorderedElementsAreArray<Matcher<int>>(2207{Eq(1), Ne(-2), Ge(3), Le(4), Eq(6)})));2208}22092210TEST(UnorderedElementsAreArrayTest, WorksWithMoveOnly) {2211ContainerHelper helper;2212EXPECT_CALL(helper,2213Call(UnorderedElementsAreArray({Pointee(1), Pointee(2)})));2214helper.Call(MakeUniquePtrs({2, 1}));2215}22162217class UnorderedElementsAreTest : public testing::Test {2218protected:2219typedef std::vector<int> IntVec;2220};22212222TEST_F(UnorderedElementsAreTest, WorksWithUncopyable) {2223Uncopyable objs[2];2224objs[0].set_value(-3);2225objs[1].set_value(1);2226EXPECT_THAT(objs,2227UnorderedElementsAre(Truly(ValueIsPositive), UncopyableIs(-3)));2228}22292230TEST_F(UnorderedElementsAreTest, SucceedsWhenExpected) {2231const int a[] = {1, 2, 3};2232std::vector<int> s(std::begin(a), std::end(a));2233do {2234StringMatchResultListener listener;2235EXPECT_TRUE(ExplainMatchResult(UnorderedElementsAre(1, 2, 3), s, &listener))2236<< listener.str();2237} while (std::next_permutation(s.begin(), s.end()));2238}22392240TEST_F(UnorderedElementsAreTest, FailsWhenAnElementMatchesNoMatcher) {2241const int a[] = {1, 2, 3};2242std::vector<int> s(std::begin(a), std::end(a));2243std::vector<Matcher<int>> mv;2244mv.push_back(1);2245mv.push_back(2);2246mv.push_back(2);2247// The element with value '3' matches nothing: fail fast.2248StringMatchResultListener listener;2249EXPECT_FALSE(ExplainMatchResult(UnorderedElementsAreArray(mv), s, &listener))2250<< listener.str();2251}22522253TEST_F(UnorderedElementsAreTest, WorksForStreamlike) {2254// Streamlike 'container' provides only minimal iterator support.2255// Its iterators are tagged with input_iterator_tag, and it has no2256// size() or empty() methods.2257const int a[5] = {2, 1, 4, 5, 3};2258Streamlike<int> s(std::begin(a), std::end(a));22592260EXPECT_THAT(s, UnorderedElementsAre(1, 2, 3, 4, 5));2261EXPECT_THAT(s, Not(UnorderedElementsAre(2, 2, 3, 4, 5)));2262}22632264TEST_F(UnorderedElementsAreTest, WorksWithMoveOnly) {2265ContainerHelper helper;2266EXPECT_CALL(helper, Call(UnorderedElementsAre(Pointee(1), Pointee(2))));2267helper.Call(MakeUniquePtrs({2, 1}));2268}22692270// One naive implementation of the matcher runs in O(N!) time, which is too2271// slow for many real-world inputs. This test shows that our matcher can match2272// 100 inputs very quickly (a few milliseconds). An O(100!) is 10^1582273// iterations and obviously effectively incomputable.2274// [ RUN ] UnorderedElementsAreTest.Performance2275// [ OK ] UnorderedElementsAreTest.Performance (4 ms)2276TEST_F(UnorderedElementsAreTest, Performance) {2277std::vector<int> s;2278std::vector<Matcher<int>> mv;2279for (int i = 0; i < 100; ++i) {2280s.push_back(i);2281mv.push_back(_);2282}2283mv[50] = Eq(0);2284StringMatchResultListener listener;2285EXPECT_TRUE(ExplainMatchResult(UnorderedElementsAreArray(mv), s, &listener))2286<< listener.str();2287}22882289// Another variant of 'Performance' with similar expectations.2290// [ RUN ] UnorderedElementsAreTest.PerformanceHalfStrict2291// [ OK ] UnorderedElementsAreTest.PerformanceHalfStrict (4 ms)2292TEST_F(UnorderedElementsAreTest, PerformanceHalfStrict) {2293std::vector<int> s;2294std::vector<Matcher<int>> mv;2295for (int i = 0; i < 100; ++i) {2296s.push_back(i);2297if (i & 1) {2298mv.push_back(_);2299} else {2300mv.push_back(i);2301}2302}2303StringMatchResultListener listener;2304EXPECT_TRUE(ExplainMatchResult(UnorderedElementsAreArray(mv), s, &listener))2305<< listener.str();2306}23072308TEST_F(UnorderedElementsAreTest, FailMessageCountWrong) {2309std::vector<int> v;2310v.push_back(4);2311StringMatchResultListener listener;2312EXPECT_FALSE(ExplainMatchResult(UnorderedElementsAre(1, 2, 3), v, &listener))2313<< listener.str();2314EXPECT_THAT(listener.str(),2315Eq("which has 1 element\n"2316"where the following matchers don't match any elements:\n"2317"matcher #0: is equal to 1,\n"2318"matcher #1: is equal to 2,\n"2319"matcher #2: is equal to 3\n"2320"and where the following elements don't match any matchers:\n"2321"element #0: 4"));2322}23232324TEST_F(UnorderedElementsAreTest, FailMessageCountWrongZero) {2325std::vector<int> v;2326StringMatchResultListener listener;2327EXPECT_FALSE(ExplainMatchResult(UnorderedElementsAre(1, 2, 3), v, &listener))2328<< listener.str();2329EXPECT_THAT(listener.str(),2330Eq("where the following matchers don't match any elements:\n"2331"matcher #0: is equal to 1,\n"2332"matcher #1: is equal to 2,\n"2333"matcher #2: is equal to 3"));2334}23352336TEST_F(UnorderedElementsAreTest, FailMessageUnmatchedMatchers) {2337std::vector<int> v;2338v.push_back(1);2339v.push_back(1);2340StringMatchResultListener listener;2341EXPECT_FALSE(ExplainMatchResult(UnorderedElementsAre(1, 2), v, &listener))2342<< listener.str();2343EXPECT_THAT(listener.str(),2344Eq("where the following matchers don't match any elements:\n"2345"matcher #1: is equal to 2"));2346}23472348TEST_F(UnorderedElementsAreTest, FailMessageUnmatchedElements) {2349std::vector<int> v;2350v.push_back(1);2351v.push_back(2);2352StringMatchResultListener listener;2353EXPECT_FALSE(ExplainMatchResult(UnorderedElementsAre(1, 1), v, &listener))2354<< listener.str();2355EXPECT_THAT(listener.str(),2356Eq("where the following elements don't match any matchers:\n"2357"element #1: 2"));2358}23592360TEST_F(UnorderedElementsAreTest, FailMessageUnmatchedMatcherAndElement) {2361std::vector<int> v;2362v.push_back(2);2363v.push_back(3);2364StringMatchResultListener listener;2365EXPECT_FALSE(ExplainMatchResult(UnorderedElementsAre(1, 2), v, &listener))2366<< listener.str();2367EXPECT_THAT(listener.str(),2368Eq("where"2369" the following matchers don't match any elements:\n"2370"matcher #0: is equal to 1\n"2371"and"2372" where"2373" the following elements don't match any matchers:\n"2374"element #1: 3"));2375}23762377// Test helper for formatting element, matcher index pairs in expectations.2378static std::string EMString(int element, int matcher) {2379stringstream ss;2380ss << "(element #" << element << ", matcher #" << matcher << ")";2381return ss.str();2382}23832384TEST_F(UnorderedElementsAreTest, FailMessageImperfectMatchOnly) {2385// A situation where all elements and matchers have a match2386// associated with them, but the max matching is not perfect.2387std::vector<std::string> v;2388v.push_back("a");2389v.push_back("b");2390v.push_back("c");2391StringMatchResultListener listener;2392EXPECT_FALSE(ExplainMatchResult(2393UnorderedElementsAre("a", "a", AnyOf("b", "c")), v, &listener))2394<< listener.str();23952396std::string prefix =2397"where no permutation of the elements can satisfy all matchers, "2398"and the closest match is 2 of 3 matchers with the "2399"pairings:\n";24002401// We have to be a bit loose here, because there are 4 valid max matches.2402EXPECT_THAT(2403listener.str(),2404AnyOf(2405prefix + "{\n " + EMString(0, 0) + ",\n " + EMString(1, 2) + "\n}",2406prefix + "{\n " + EMString(0, 1) + ",\n " + EMString(1, 2) + "\n}",2407prefix + "{\n " + EMString(0, 0) + ",\n " + EMString(2, 2) + "\n}",2408prefix + "{\n " + EMString(0, 1) + ",\n " + EMString(2, 2) +2409"\n}"));2410}24112412TEST_F(UnorderedElementsAreTest, Describe) {2413EXPECT_THAT(Describe<IntVec>(UnorderedElementsAre()), Eq("is empty"));2414EXPECT_THAT(Describe<IntVec>(UnorderedElementsAre(345)),2415Eq("has 1 element and that element is equal to 345"));2416EXPECT_THAT(Describe<IntVec>(UnorderedElementsAre(111, 222, 333)),2417Eq("has 3 elements and there exists some permutation "2418"of elements such that:\n"2419" - element #0 is equal to 111, and\n"2420" - element #1 is equal to 222, and\n"2421" - element #2 is equal to 333"));2422}24232424TEST_F(UnorderedElementsAreTest, DescribeNegation) {2425EXPECT_THAT(DescribeNegation<IntVec>(UnorderedElementsAre()),2426Eq("isn't empty"));2427EXPECT_THAT(2428DescribeNegation<IntVec>(UnorderedElementsAre(345)),2429Eq("doesn't have 1 element, or has 1 element that isn't equal to 345"));2430EXPECT_THAT(DescribeNegation<IntVec>(UnorderedElementsAre(123, 234, 345)),2431Eq("doesn't have 3 elements, or there exists no permutation "2432"of elements such that:\n"2433" - element #0 is equal to 123, and\n"2434" - element #1 is equal to 234, and\n"2435" - element #2 is equal to 345"));2436}24372438// Tests Each().24392440INSTANTIATE_GTEST_MATCHER_TEST_P(EachTest);24412442TEST_P(EachTestP, ExplainsMatchResultCorrectly) {2443set<int> a; // empty24442445Matcher<set<int>> m = Each(2);2446EXPECT_EQ("", Explain(m, a));24472448Matcher<const int (&)[1]> n = Each(1); // NOLINT24492450const int b[1] = {1};2451EXPECT_EQ("", Explain(n, b));24522453n = Each(3);2454EXPECT_EQ("whose element #0 doesn't match", Explain(n, b));24552456a.insert(1);2457a.insert(2);2458a.insert(3);2459m = Each(GreaterThan(0));2460EXPECT_EQ("", Explain(m, a));24612462m = Each(GreaterThan(10));2463EXPECT_EQ("whose element #0 doesn't match, which is 9 less than 10",2464Explain(m, a));2465}24662467TEST(EachTest, DescribesItselfCorrectly) {2468Matcher<vector<int>> m = Each(1);2469EXPECT_EQ("only contains elements that is equal to 1", Describe(m));24702471Matcher<vector<int>> m2 = Not(m);2472EXPECT_EQ("contains some element that isn't equal to 1", Describe(m2));2473}24742475TEST(EachTest, MatchesVectorWhenAllElementsMatch) {2476vector<int> some_vector;2477EXPECT_THAT(some_vector, Each(1));2478some_vector.push_back(3);2479EXPECT_THAT(some_vector, Not(Each(1)));2480EXPECT_THAT(some_vector, Each(3));2481some_vector.push_back(1);2482some_vector.push_back(2);2483EXPECT_THAT(some_vector, Not(Each(3)));2484EXPECT_THAT(some_vector, Each(Lt(3.5)));24852486vector<std::string> another_vector;2487another_vector.push_back("fee");2488EXPECT_THAT(another_vector, Each(std::string("fee")));2489another_vector.push_back("fie");2490another_vector.push_back("foe");2491another_vector.push_back("fum");2492EXPECT_THAT(another_vector, Not(Each(std::string("fee"))));2493}24942495TEST(EachTest, MatchesMapWhenAllElementsMatch) {2496map<const char*, int> my_map;2497const char* bar = "a string";2498my_map[bar] = 2;2499EXPECT_THAT(my_map, Each(make_pair(bar, 2)));25002501map<std::string, int> another_map;2502EXPECT_THAT(another_map, Each(make_pair(std::string("fee"), 1)));2503another_map["fee"] = 1;2504EXPECT_THAT(another_map, Each(make_pair(std::string("fee"), 1)));2505another_map["fie"] = 2;2506another_map["foe"] = 3;2507another_map["fum"] = 4;2508EXPECT_THAT(another_map, Not(Each(make_pair(std::string("fee"), 1))));2509EXPECT_THAT(another_map, Not(Each(make_pair(std::string("fum"), 1))));2510EXPECT_THAT(another_map, Each(Pair(_, Gt(0))));2511}25122513TEST(EachTest, AcceptsMatcher) {2514const int a[] = {1, 2, 3};2515EXPECT_THAT(a, Each(Gt(0)));2516EXPECT_THAT(a, Not(Each(Gt(1))));2517}25182519TEST(EachTest, WorksForNativeArrayAsTuple) {2520const int a[] = {1, 2};2521const int* const pointer = a;2522EXPECT_THAT(std::make_tuple(pointer, 2), Each(Gt(0)));2523EXPECT_THAT(std::make_tuple(pointer, 2), Not(Each(Gt(1))));2524}25252526TEST(EachTest, WorksWithMoveOnly) {2527ContainerHelper helper;2528EXPECT_CALL(helper, Call(Each(Pointee(Gt(0)))));2529helper.Call(MakeUniquePtrs({1, 2}));2530}25312532// For testing Pointwise().2533class IsHalfOfMatcher {2534public:2535template <typename T1, typename T2>2536bool MatchAndExplain(const std::tuple<T1, T2>& a_pair,2537MatchResultListener* listener) const {2538if (std::get<0>(a_pair) == std::get<1>(a_pair) / 2) {2539*listener << "where the second is " << std::get<1>(a_pair);2540return true;2541} else {2542*listener << "where the second/2 is " << std::get<1>(a_pair) / 2;2543return false;2544}2545}25462547void DescribeTo(ostream* os) const {2548*os << "are a pair where the first is half of the second";2549}25502551void DescribeNegationTo(ostream* os) const {2552*os << "are a pair where the first isn't half of the second";2553}2554};25552556PolymorphicMatcher<IsHalfOfMatcher> IsHalfOf() {2557return MakePolymorphicMatcher(IsHalfOfMatcher());2558}25592560TEST(PointwiseTest, DescribesSelf) {2561vector<int> rhs;2562rhs.push_back(1);2563rhs.push_back(2);2564rhs.push_back(3);2565const Matcher<const vector<int>&> m = Pointwise(IsHalfOf(), rhs);2566EXPECT_EQ(2567"contains 3 values, where each value and its corresponding value "2568"in { 1, 2, 3 } are a pair where the first is half of the second",2569Describe(m));2570EXPECT_EQ(2571"doesn't contain exactly 3 values, or contains a value x at some "2572"index i where x and the i-th value of { 1, 2, 3 } are a pair "2573"where the first isn't half of the second",2574DescribeNegation(m));2575}25762577TEST(PointwiseTest, MakesCopyOfRhs) {2578list<signed char> rhs;2579rhs.push_back(2);2580rhs.push_back(4);25812582int lhs[] = {1, 2};2583const Matcher<const int (&)[2]> m = Pointwise(IsHalfOf(), rhs);2584EXPECT_THAT(lhs, m);25852586// Changing rhs now shouldn't affect m, which made a copy of rhs.2587rhs.push_back(6);2588EXPECT_THAT(lhs, m);2589}25902591TEST(PointwiseTest, WorksForLhsNativeArray) {2592const int lhs[] = {1, 2, 3};2593vector<int> rhs;2594rhs.push_back(2);2595rhs.push_back(4);2596rhs.push_back(6);2597EXPECT_THAT(lhs, Pointwise(Lt(), rhs));2598EXPECT_THAT(lhs, Not(Pointwise(Gt(), rhs)));2599}26002601TEST(PointwiseTest, WorksForRhsNativeArray) {2602const int rhs[] = {1, 2, 3};2603vector<int> lhs;2604lhs.push_back(2);2605lhs.push_back(4);2606lhs.push_back(6);2607EXPECT_THAT(lhs, Pointwise(Gt(), rhs));2608EXPECT_THAT(lhs, Not(Pointwise(Lt(), rhs)));2609}26102611// Test is effective only with sanitizers.2612TEST(PointwiseTest, WorksForVectorOfBool) {2613vector<bool> rhs(3, false);2614rhs[1] = true;2615vector<bool> lhs = rhs;2616EXPECT_THAT(lhs, Pointwise(Eq(), rhs));2617rhs[0] = true;2618EXPECT_THAT(lhs, Not(Pointwise(Eq(), rhs)));2619}26202621TEST(PointwiseTest, WorksForRhsInitializerList) {2622const vector<int> lhs{2, 4, 6};2623EXPECT_THAT(lhs, Pointwise(Gt(), {1, 2, 3}));2624EXPECT_THAT(lhs, Not(Pointwise(Lt(), {3, 3, 7})));2625}26262627TEST(PointwiseTest, RejectsWrongSize) {2628const double lhs[2] = {1, 2};2629const int rhs[1] = {0};2630EXPECT_THAT(lhs, Not(Pointwise(Gt(), rhs)));2631EXPECT_EQ("which contains 2 values", Explain(Pointwise(Gt(), rhs), lhs));26322633const int rhs2[3] = {0, 1, 2};2634EXPECT_THAT(lhs, Not(Pointwise(Gt(), rhs2)));2635}26362637TEST(PointwiseTest, RejectsWrongContent) {2638const double lhs[3] = {1, 2, 3};2639const int rhs[3] = {2, 6, 4};2640EXPECT_THAT(lhs, Not(Pointwise(IsHalfOf(), rhs)));2641EXPECT_EQ(2642"where the value pair (2, 6) at index #1 don't match, "2643"where the second/2 is 3",2644Explain(Pointwise(IsHalfOf(), rhs), lhs));2645}26462647TEST(PointwiseTest, AcceptsCorrectContent) {2648const double lhs[3] = {1, 2, 3};2649const int rhs[3] = {2, 4, 6};2650EXPECT_THAT(lhs, Pointwise(IsHalfOf(), rhs));2651EXPECT_EQ("", Explain(Pointwise(IsHalfOf(), rhs), lhs));2652}26532654TEST(PointwiseTest, AllowsMonomorphicInnerMatcher) {2655const double lhs[3] = {1, 2, 3};2656const int rhs[3] = {2, 4, 6};2657const Matcher<std::tuple<const double&, const int&>> m1 = IsHalfOf();2658EXPECT_THAT(lhs, Pointwise(m1, rhs));2659EXPECT_EQ("", Explain(Pointwise(m1, rhs), lhs));26602661// This type works as a std::tuple<const double&, const int&> can be2662// implicitly cast to std::tuple<double, int>.2663const Matcher<std::tuple<double, int>> m2 = IsHalfOf();2664EXPECT_THAT(lhs, Pointwise(m2, rhs));2665EXPECT_EQ("", Explain(Pointwise(m2, rhs), lhs));2666}26672668MATCHER(PointeeEquals, "Points to an equal value") {2669return ExplainMatchResult(::testing::Pointee(::testing::get<1>(arg)),2670::testing::get<0>(arg), result_listener);2671}26722673TEST(PointwiseTest, WorksWithMoveOnly) {2674ContainerHelper helper;2675EXPECT_CALL(helper, Call(Pointwise(PointeeEquals(), std::vector<int>{1, 2})));2676helper.Call(MakeUniquePtrs({1, 2}));2677}26782679TEST(UnorderedPointwiseTest, DescribesSelf) {2680vector<int> rhs;2681rhs.push_back(1);2682rhs.push_back(2);2683rhs.push_back(3);2684const Matcher<const vector<int>&> m = UnorderedPointwise(IsHalfOf(), rhs);2685EXPECT_EQ(2686"has 3 elements and there exists some permutation of elements such "2687"that:\n"2688" - element #0 and 1 are a pair where the first is half of the second, "2689"and\n"2690" - element #1 and 2 are a pair where the first is half of the second, "2691"and\n"2692" - element #2 and 3 are a pair where the first is half of the second",2693Describe(m));2694EXPECT_EQ(2695"doesn't have 3 elements, or there exists no permutation of elements "2696"such that:\n"2697" - element #0 and 1 are a pair where the first is half of the second, "2698"and\n"2699" - element #1 and 2 are a pair where the first is half of the second, "2700"and\n"2701" - element #2 and 3 are a pair where the first is half of the second",2702DescribeNegation(m));2703}27042705TEST(UnorderedPointwiseTest, MakesCopyOfRhs) {2706list<signed char> rhs;2707rhs.push_back(2);2708rhs.push_back(4);27092710int lhs[] = {2, 1};2711const Matcher<const int (&)[2]> m = UnorderedPointwise(IsHalfOf(), rhs);2712EXPECT_THAT(lhs, m);27132714// Changing rhs now shouldn't affect m, which made a copy of rhs.2715rhs.push_back(6);2716EXPECT_THAT(lhs, m);2717}27182719TEST(UnorderedPointwiseTest, WorksForLhsNativeArray) {2720const int lhs[] = {1, 2, 3};2721vector<int> rhs;2722rhs.push_back(4);2723rhs.push_back(6);2724rhs.push_back(2);2725EXPECT_THAT(lhs, UnorderedPointwise(Lt(), rhs));2726EXPECT_THAT(lhs, Not(UnorderedPointwise(Gt(), rhs)));2727}27282729TEST(UnorderedPointwiseTest, WorksForRhsNativeArray) {2730const int rhs[] = {1, 2, 3};2731vector<int> lhs;2732lhs.push_back(4);2733lhs.push_back(2);2734lhs.push_back(6);2735EXPECT_THAT(lhs, UnorderedPointwise(Gt(), rhs));2736EXPECT_THAT(lhs, Not(UnorderedPointwise(Lt(), rhs)));2737}27382739TEST(UnorderedPointwiseTest, WorksForRhsInitializerList) {2740const vector<int> lhs{2, 4, 6};2741EXPECT_THAT(lhs, UnorderedPointwise(Gt(), {5, 1, 3}));2742EXPECT_THAT(lhs, Not(UnorderedPointwise(Lt(), {1, 1, 7})));2743}27442745TEST(UnorderedPointwiseTest, RejectsWrongSize) {2746const double lhs[2] = {1, 2};2747const int rhs[1] = {0};2748EXPECT_THAT(lhs, Not(UnorderedPointwise(Gt(), rhs)));2749EXPECT_EQ("which has 2 elements\n",2750Explain(UnorderedPointwise(Gt(), rhs), lhs));27512752const int rhs2[3] = {0, 1, 2};2753EXPECT_THAT(lhs, Not(UnorderedPointwise(Gt(), rhs2)));2754}27552756TEST(UnorderedPointwiseTest, RejectsWrongContent) {2757const double lhs[3] = {1, 2, 3};2758const int rhs[3] = {2, 6, 6};2759EXPECT_THAT(lhs, Not(UnorderedPointwise(IsHalfOf(), rhs)));2760EXPECT_EQ(2761"where the following elements don't match any matchers:\n"2762"element #1: 2",2763Explain(UnorderedPointwise(IsHalfOf(), rhs), lhs));2764}27652766TEST(UnorderedPointwiseTest, AcceptsCorrectContentInSameOrder) {2767const double lhs[3] = {1, 2, 3};2768const int rhs[3] = {2, 4, 6};2769EXPECT_THAT(lhs, UnorderedPointwise(IsHalfOf(), rhs));2770}27712772TEST(UnorderedPointwiseTest, AcceptsCorrectContentInDifferentOrder) {2773const double lhs[3] = {1, 2, 3};2774const int rhs[3] = {6, 4, 2};2775EXPECT_THAT(lhs, UnorderedPointwise(IsHalfOf(), rhs));2776}27772778TEST(UnorderedPointwiseTest, AllowsMonomorphicInnerMatcher) {2779const double lhs[3] = {1, 2, 3};2780const int rhs[3] = {4, 6, 2};2781const Matcher<std::tuple<const double&, const int&>> m1 = IsHalfOf();2782EXPECT_THAT(lhs, UnorderedPointwise(m1, rhs));27832784// This type works as a std::tuple<const double&, const int&> can be2785// implicitly cast to std::tuple<double, int>.2786const Matcher<std::tuple<double, int>> m2 = IsHalfOf();2787EXPECT_THAT(lhs, UnorderedPointwise(m2, rhs));2788}27892790TEST(UnorderedPointwiseTest, WorksWithMoveOnly) {2791ContainerHelper helper;2792EXPECT_CALL(helper, Call(UnorderedPointwise(PointeeEquals(),2793std::vector<int>{1, 2})));2794helper.Call(MakeUniquePtrs({2, 1}));2795}27962797TEST(PointeeTest, WorksOnMoveOnlyType) {2798std::unique_ptr<int> p(new int(3));2799EXPECT_THAT(p, Pointee(Eq(3)));2800EXPECT_THAT(p, Not(Pointee(Eq(2))));2801}28022803class PredicateFormatterFromMatcherTest : public ::testing::Test {2804protected:2805enum Behavior { kInitialSuccess, kAlwaysFail, kFlaky };28062807// A matcher that can return different results when used multiple times on the2808// same input. No real matcher should do this; but this lets us test that we2809// detect such behavior and fail appropriately.2810class MockMatcher : public MatcherInterface<Behavior> {2811public:2812bool MatchAndExplain(Behavior behavior,2813MatchResultListener* listener) const override {2814*listener << "[MatchAndExplain]";2815switch (behavior) {2816case kInitialSuccess:2817// The first call to MatchAndExplain should use a "not interested"2818// listener; so this is expected to return |true|. There should be no2819// subsequent calls.2820return !listener->IsInterested();28212822case kAlwaysFail:2823return false;28242825case kFlaky:2826// The first call to MatchAndExplain should use a "not interested"2827// listener; so this will return |false|. Subsequent calls should have2828// an "interested" listener; so this will return |true|, thus2829// simulating a flaky matcher.2830return listener->IsInterested();2831}28322833GTEST_LOG_(FATAL) << "This should never be reached";2834return false;2835}28362837void DescribeTo(ostream* os) const override { *os << "[DescribeTo]"; }28382839void DescribeNegationTo(ostream* os) const override {2840*os << "[DescribeNegationTo]";2841}2842};28432844AssertionResult RunPredicateFormatter(Behavior behavior) {2845auto matcher = MakeMatcher(new MockMatcher);2846PredicateFormatterFromMatcher<Matcher<Behavior>> predicate_formatter(2847matcher);2848return predicate_formatter("dummy-name", behavior);2849}2850};28512852TEST_F(PredicateFormatterFromMatcherTest, ShortCircuitOnSuccess) {2853AssertionResult result = RunPredicateFormatter(kInitialSuccess);2854EXPECT_TRUE(result); // Implicit cast to bool.2855std::string expect;2856EXPECT_EQ(expect, result.message());2857}28582859TEST_F(PredicateFormatterFromMatcherTest, NoShortCircuitOnFailure) {2860AssertionResult result = RunPredicateFormatter(kAlwaysFail);2861EXPECT_FALSE(result); // Implicit cast to bool.2862std::string expect =2863"Value of: dummy-name\nExpected: [DescribeTo]\n"2864" Actual: 1" +2865OfType(internal::GetTypeName<Behavior>()) + ", [MatchAndExplain]";2866EXPECT_EQ(expect, result.message());2867}28682869TEST_F(PredicateFormatterFromMatcherTest, DetectsFlakyShortCircuit) {2870AssertionResult result = RunPredicateFormatter(kFlaky);2871EXPECT_FALSE(result); // Implicit cast to bool.2872std::string expect =2873"Value of: dummy-name\nExpected: [DescribeTo]\n"2874" The matcher failed on the initial attempt; but passed when rerun to "2875"generate the explanation.\n"2876" Actual: 2" +2877OfType(internal::GetTypeName<Behavior>()) + ", [MatchAndExplain]";2878EXPECT_EQ(expect, result.message());2879}28802881// Tests for ElementsAre().28822883TEST(ElementsAreTest, CanDescribeExpectingNoElement) {2884Matcher<const vector<int>&> m = ElementsAre();2885EXPECT_EQ("is empty", Describe(m));2886}28872888TEST(ElementsAreTest, CanDescribeExpectingOneElement) {2889Matcher<vector<int>> m = ElementsAre(Gt(5));2890EXPECT_EQ("has 1 element that is > 5", Describe(m));2891}28922893TEST(ElementsAreTest, CanDescribeExpectingManyElements) {2894Matcher<list<std::string>> m = ElementsAre(StrEq("one"), "two");2895EXPECT_EQ(2896"has 2 elements where\n"2897"element #0 is equal to \"one\",\n"2898"element #1 is equal to \"two\"",2899Describe(m));2900}29012902TEST(ElementsAreTest, CanDescribeNegationOfExpectingNoElement) {2903Matcher<vector<int>> m = ElementsAre();2904EXPECT_EQ("isn't empty", DescribeNegation(m));2905}29062907TEST(ElementsAreTest, CanDescribeNegationOfExpectingOneElement) {2908Matcher<const list<int>&> m = ElementsAre(Gt(5));2909EXPECT_EQ(2910"doesn't have 1 element, or\n"2911"element #0 isn't > 5",2912DescribeNegation(m));2913}29142915TEST(ElementsAreTest, CanDescribeNegationOfExpectingManyElements) {2916Matcher<const list<std::string>&> m = ElementsAre("one", "two");2917EXPECT_EQ(2918"doesn't have 2 elements, or\n"2919"element #0 isn't equal to \"one\", or\n"2920"element #1 isn't equal to \"two\"",2921DescribeNegation(m));2922}29232924TEST(ElementsAreTest, DoesNotExplainTrivialMatch) {2925Matcher<const list<int>&> m = ElementsAre(1, Ne(2));29262927list<int> test_list;2928test_list.push_back(1);2929test_list.push_back(3);2930EXPECT_EQ("", Explain(m, test_list)); // No need to explain anything.2931}29322933TEST_P(ElementsAreTestP, ExplainsNonTrivialMatch) {2934Matcher<const vector<int>&> m =2935ElementsAre(GreaterThan(1), 0, GreaterThan(2));29362937const int a[] = {10, 0, 100};2938vector<int> test_vector(std::begin(a), std::end(a));2939EXPECT_EQ(2940"whose element #0 matches, which is 9 more than 1,\n"2941"and whose element #2 matches, which is 98 more than 2",2942Explain(m, test_vector));2943}29442945TEST(ElementsAreTest, CanExplainMismatchWrongSize) {2946Matcher<const list<int>&> m = ElementsAre(1, 3);29472948list<int> test_list;2949// No need to explain when the container is empty.2950EXPECT_EQ("", Explain(m, test_list));29512952test_list.push_back(1);2953EXPECT_EQ("which has 1 element", Explain(m, test_list));2954}29552956TEST_P(ElementsAreTestP, CanExplainMismatchRightSize) {2957Matcher<const vector<int>&> m = ElementsAre(1, GreaterThan(5));29582959vector<int> v;2960v.push_back(2);2961v.push_back(1);2962EXPECT_EQ(Explain(m, v), "whose element #0 (2) isn't equal to 1");29632964v[0] = 1;2965EXPECT_EQ(Explain(m, v),2966"whose element #1 (1) is <= 5, which is 4 less than 5");2967}29682969TEST(ElementsAreTest, MatchesOneElementVector) {2970vector<std::string> test_vector;2971test_vector.push_back("test string");29722973EXPECT_THAT(test_vector, ElementsAre(StrEq("test string")));2974}29752976TEST(ElementsAreTest, MatchesOneElementList) {2977list<std::string> test_list;2978test_list.push_back("test string");29792980EXPECT_THAT(test_list, ElementsAre("test string"));2981}29822983TEST(ElementsAreTest, MatchesThreeElementVector) {2984vector<std::string> test_vector;2985test_vector.push_back("one");2986test_vector.push_back("two");2987test_vector.push_back("three");29882989EXPECT_THAT(test_vector, ElementsAre("one", StrEq("two"), _));2990}29912992TEST(ElementsAreTest, MatchesOneElementEqMatcher) {2993vector<int> test_vector;2994test_vector.push_back(4);29952996EXPECT_THAT(test_vector, ElementsAre(Eq(4)));2997}29982999TEST(ElementsAreTest, MatchesOneElementAnyMatcher) {3000vector<int> test_vector;3001test_vector.push_back(4);30023003EXPECT_THAT(test_vector, ElementsAre(_));3004}30053006TEST(ElementsAreTest, MatchesOneElementValue) {3007vector<int> test_vector;3008test_vector.push_back(4);30093010EXPECT_THAT(test_vector, ElementsAre(4));3011}30123013TEST(ElementsAreTest, MatchesThreeElementsMixedMatchers) {3014vector<int> test_vector;3015test_vector.push_back(1);3016test_vector.push_back(2);3017test_vector.push_back(3);30183019EXPECT_THAT(test_vector, ElementsAre(1, Eq(2), _));3020}30213022TEST(ElementsAreTest, MatchesTenElementVector) {3023const int a[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};3024vector<int> test_vector(std::begin(a), std::end(a));30253026EXPECT_THAT(test_vector,3027// The element list can contain values and/or matchers3028// of different types.3029ElementsAre(0, Ge(0), _, 3, 4, Ne(2), Eq(6), 7, 8, _));3030}30313032TEST(ElementsAreTest, DoesNotMatchWrongSize) {3033vector<std::string> test_vector;3034test_vector.push_back("test string");3035test_vector.push_back("test string");30363037Matcher<vector<std::string>> m = ElementsAre(StrEq("test string"));3038EXPECT_FALSE(m.Matches(test_vector));3039}30403041TEST(ElementsAreTest, DoesNotMatchWrongValue) {3042vector<std::string> test_vector;3043test_vector.push_back("other string");30443045Matcher<vector<std::string>> m = ElementsAre(StrEq("test string"));3046EXPECT_FALSE(m.Matches(test_vector));3047}30483049TEST(ElementsAreTest, DoesNotMatchWrongOrder) {3050vector<std::string> test_vector;3051test_vector.push_back("one");3052test_vector.push_back("three");3053test_vector.push_back("two");30543055Matcher<vector<std::string>> m =3056ElementsAre(StrEq("one"), StrEq("two"), StrEq("three"));3057EXPECT_FALSE(m.Matches(test_vector));3058}30593060TEST(ElementsAreTest, WorksForNestedContainer) {3061constexpr std::array<const char*, 2> strings = {{"Hi", "world"}};30623063vector<list<char>> nested;3064for (const auto& s : strings) {3065nested.emplace_back(s, s + strlen(s));3066}30673068EXPECT_THAT(nested, ElementsAre(ElementsAre('H', Ne('e')),3069ElementsAre('w', 'o', _, _, 'd')));3070EXPECT_THAT(nested, Not(ElementsAre(ElementsAre('H', 'e'),3071ElementsAre('w', 'o', _, _, 'd'))));3072}30733074TEST(ElementsAreTest, WorksWithByRefElementMatchers) {3075int a[] = {0, 1, 2};3076vector<int> v(std::begin(a), std::end(a));30773078EXPECT_THAT(v, ElementsAre(Ref(v[0]), Ref(v[1]), Ref(v[2])));3079EXPECT_THAT(v, Not(ElementsAre(Ref(v[0]), Ref(v[1]), Ref(a[2]))));3080}30813082TEST(ElementsAreTest, WorksWithContainerPointerUsingPointee) {3083int a[] = {0, 1, 2};3084vector<int> v(std::begin(a), std::end(a));30853086EXPECT_THAT(&v, Pointee(ElementsAre(0, 1, _)));3087EXPECT_THAT(&v, Not(Pointee(ElementsAre(0, _, 3))));3088}30893090TEST(ElementsAreTest, WorksWithNativeArrayPassedByReference) {3091int array[] = {0, 1, 2};3092EXPECT_THAT(array, ElementsAre(0, 1, _));3093EXPECT_THAT(array, Not(ElementsAre(1, _, _)));3094EXPECT_THAT(array, Not(ElementsAre(0, _)));3095}30963097class NativeArrayPassedAsPointerAndSize {3098public:3099NativeArrayPassedAsPointerAndSize() = default;31003101MOCK_METHOD(void, Helper, (int* array, int size));31023103private:3104NativeArrayPassedAsPointerAndSize(const NativeArrayPassedAsPointerAndSize&) =3105delete;3106NativeArrayPassedAsPointerAndSize& operator=(3107const NativeArrayPassedAsPointerAndSize&) = delete;3108};31093110TEST(ElementsAreTest, WorksWithNativeArrayPassedAsPointerAndSize) {3111int array[] = {0, 1};3112::std::tuple<int*, size_t> array_as_tuple(array, 2);3113EXPECT_THAT(array_as_tuple, ElementsAre(0, 1));3114EXPECT_THAT(array_as_tuple, Not(ElementsAre(0)));31153116NativeArrayPassedAsPointerAndSize helper;3117EXPECT_CALL(helper, Helper(_, _)).With(ElementsAre(0, 1));3118helper.Helper(array, 2);3119}31203121TEST(ElementsAreTest, WorksWithTwoDimensionalNativeArray) {3122const char a2[][3] = {"hi", "lo"};3123EXPECT_THAT(a2, ElementsAre(ElementsAre('h', 'i', '\0'),3124ElementsAre('l', 'o', '\0')));3125EXPECT_THAT(a2, ElementsAre(StrEq("hi"), StrEq("lo")));3126EXPECT_THAT(a2, ElementsAre(Not(ElementsAre('h', 'o', '\0')),3127ElementsAre('l', 'o', '\0')));3128}31293130TEST(ElementsAreTest, AcceptsStringLiteral) {3131std::string array[] = {"hi", "one", "two"};3132EXPECT_THAT(array, ElementsAre("hi", "one", "two"));3133EXPECT_THAT(array, Not(ElementsAre("hi", "one", "too")));3134}31353136// Declared here with the size unknown. Defined AFTER the following test.3137extern const char kHi[];31383139TEST(ElementsAreTest, AcceptsArrayWithUnknownSize) {3140// The size of kHi is not known in this test, but ElementsAre() should3141// still accept it.31423143std::string array1[] = {"hi"};3144EXPECT_THAT(array1, ElementsAre(kHi));31453146std::string array2[] = {"ho"};3147EXPECT_THAT(array2, Not(ElementsAre(kHi)));3148}31493150const char kHi[] = "hi";31513152TEST(ElementsAreTest, MakesCopyOfArguments) {3153int x = 1;3154int y = 2;3155// This should make a copy of x and y.3156::testing::internal::ElementsAreMatcher<std::tuple<int, int>>3157polymorphic_matcher = ElementsAre(x, y);3158// Changing x and y now shouldn't affect the meaning of the above matcher.3159x = y = 0;3160const int array1[] = {1, 2};3161EXPECT_THAT(array1, polymorphic_matcher);3162const int array2[] = {0, 0};3163EXPECT_THAT(array2, Not(polymorphic_matcher));3164}31653166// Tests for ElementsAreArray(). Since ElementsAreArray() shares most3167// of the implementation with ElementsAre(), we don't test it as3168// thoroughly here.31693170TEST(ElementsAreArrayTest, CanBeCreatedWithValueArray) {3171const int a[] = {1, 2, 3};31723173vector<int> test_vector(std::begin(a), std::end(a));3174EXPECT_THAT(test_vector, ElementsAreArray(a));31753176test_vector[2] = 0;3177EXPECT_THAT(test_vector, Not(ElementsAreArray(a)));3178}31793180TEST(ElementsAreArrayTest, CanBeCreatedWithArraySize) {3181std::array<const char*, 3> a = {{"one", "two", "three"}};31823183vector<std::string> test_vector(std::begin(a), std::end(a));3184EXPECT_THAT(test_vector, ElementsAreArray(a.data(), a.size()));31853186const char** p = a.data();3187test_vector[0] = "1";3188EXPECT_THAT(test_vector, Not(ElementsAreArray(p, a.size())));3189}31903191TEST(ElementsAreArrayTest, CanBeCreatedWithoutArraySize) {3192const char* a[] = {"one", "two", "three"};31933194vector<std::string> test_vector(std::begin(a), std::end(a));3195EXPECT_THAT(test_vector, ElementsAreArray(a));31963197test_vector[0] = "1";3198EXPECT_THAT(test_vector, Not(ElementsAreArray(a)));3199}32003201TEST(ElementsAreArrayTest, CanBeCreatedWithMatcherArray) {3202const Matcher<std::string> kMatcherArray[] = {StrEq("one"), StrEq("two"),3203StrEq("three")};32043205vector<std::string> test_vector;3206test_vector.push_back("one");3207test_vector.push_back("two");3208test_vector.push_back("three");3209EXPECT_THAT(test_vector, ElementsAreArray(kMatcherArray));32103211test_vector.push_back("three");3212EXPECT_THAT(test_vector, Not(ElementsAreArray(kMatcherArray)));3213}32143215TEST(ElementsAreArrayTest, CanBeCreatedWithVector) {3216const int a[] = {1, 2, 3};3217vector<int> test_vector(std::begin(a), std::end(a));3218const vector<int> expected(std::begin(a), std::end(a));3219EXPECT_THAT(test_vector, ElementsAreArray(expected));3220test_vector.push_back(4);3221EXPECT_THAT(test_vector, Not(ElementsAreArray(expected)));3222}32233224TEST(ElementsAreArrayTest, TakesInitializerList) {3225const int a[5] = {1, 2, 3, 4, 5};3226EXPECT_THAT(a, ElementsAreArray({1, 2, 3, 4, 5}));3227EXPECT_THAT(a, Not(ElementsAreArray({1, 2, 3, 5, 4})));3228EXPECT_THAT(a, Not(ElementsAreArray({1, 2, 3, 4, 6})));3229}32303231TEST(ElementsAreArrayTest, TakesInitializerListOfCStrings) {3232const std::string a[5] = {"a", "b", "c", "d", "e"};3233EXPECT_THAT(a, ElementsAreArray({"a", "b", "c", "d", "e"}));3234EXPECT_THAT(a, Not(ElementsAreArray({"a", "b", "c", "e", "d"})));3235EXPECT_THAT(a, Not(ElementsAreArray({"a", "b", "c", "d", "ef"})));3236}32373238TEST(ElementsAreArrayTest, TakesInitializerListOfSameTypedMatchers) {3239const int a[5] = {1, 2, 3, 4, 5};3240EXPECT_THAT(a, ElementsAreArray({Eq(1), Eq(2), Eq(3), Eq(4), Eq(5)}));3241EXPECT_THAT(a, Not(ElementsAreArray({Eq(1), Eq(2), Eq(3), Eq(4), Eq(6)})));3242}32433244TEST(ElementsAreArrayTest, TakesInitializerListOfDifferentTypedMatchers) {3245const int a[5] = {1, 2, 3, 4, 5};3246// The compiler cannot infer the type of the initializer list if its3247// elements have different types. We must explicitly specify the3248// unified element type in this case.3249EXPECT_THAT(3250a, ElementsAreArray<Matcher<int>>({Eq(1), Ne(-2), Ge(3), Le(4), Eq(5)}));3251EXPECT_THAT(a, Not(ElementsAreArray<Matcher<int>>(3252{Eq(1), Ne(-2), Ge(3), Le(4), Eq(6)})));3253}32543255TEST(ElementsAreArrayTest, CanBeCreatedWithMatcherVector) {3256const int a[] = {1, 2, 3};3257const Matcher<int> kMatchers[] = {Eq(1), Eq(2), Eq(3)};3258vector<int> test_vector(std::begin(a), std::end(a));3259const vector<Matcher<int>> expected(std::begin(kMatchers),3260std::end(kMatchers));3261EXPECT_THAT(test_vector, ElementsAreArray(expected));3262test_vector.push_back(4);3263EXPECT_THAT(test_vector, Not(ElementsAreArray(expected)));3264}32653266TEST(ElementsAreArrayTest, CanBeCreatedWithIteratorRange) {3267const int a[] = {1, 2, 3};3268const vector<int> test_vector(std::begin(a), std::end(a));3269const vector<int> expected(std::begin(a), std::end(a));3270EXPECT_THAT(test_vector, ElementsAreArray(expected.begin(), expected.end()));3271// Pointers are iterators, too.3272EXPECT_THAT(test_vector, ElementsAreArray(std::begin(a), std::end(a)));3273// The empty range of NULL pointers should also be okay.3274int* const null_int = nullptr;3275EXPECT_THAT(test_vector, Not(ElementsAreArray(null_int, null_int)));3276EXPECT_THAT((vector<int>()), ElementsAreArray(null_int, null_int));3277}32783279// Since ElementsAre() and ElementsAreArray() share much of the3280// implementation, we only do a test for native arrays here.3281TEST(ElementsAreArrayTest, WorksWithNativeArray) {3282::std::string a[] = {"hi", "ho"};3283::std::string b[] = {"hi", "ho"};32843285EXPECT_THAT(a, ElementsAreArray(b));3286EXPECT_THAT(a, ElementsAreArray(b, 2));3287EXPECT_THAT(a, Not(ElementsAreArray(b, 1)));3288}32893290TEST(ElementsAreArrayTest, SourceLifeSpan) {3291const int a[] = {1, 2, 3};3292vector<int> test_vector(std::begin(a), std::end(a));3293vector<int> expect(std::begin(a), std::end(a));3294ElementsAreArrayMatcher<int> matcher_maker =3295ElementsAreArray(expect.begin(), expect.end());3296EXPECT_THAT(test_vector, matcher_maker);3297// Changing in place the values that initialized matcher_maker should not3298// affect matcher_maker anymore. It should have made its own copy of them.3299for (int& i : expect) {3300i += 10;3301}3302EXPECT_THAT(test_vector, matcher_maker);3303test_vector.push_back(3);3304EXPECT_THAT(test_vector, Not(matcher_maker));3305}33063307// Tests Contains().33083309INSTANTIATE_GTEST_MATCHER_TEST_P(ContainsTest);33103311TEST(ContainsTest, ListMatchesWhenElementIsInContainer) {3312list<int> some_list;3313some_list.push_back(3);3314some_list.push_back(1);3315some_list.push_back(2);3316some_list.push_back(3);3317EXPECT_THAT(some_list, Contains(1));3318EXPECT_THAT(some_list, Contains(Gt(2.5)));3319EXPECT_THAT(some_list, Contains(Eq(2.0f)));33203321list<std::string> another_list;3322another_list.push_back("fee");3323another_list.push_back("fie");3324another_list.push_back("foe");3325another_list.push_back("fum");3326EXPECT_THAT(another_list, Contains(std::string("fee")));3327}33283329TEST(ContainsTest, ListDoesNotMatchWhenElementIsNotInContainer) {3330list<int> some_list;3331some_list.push_back(3);3332some_list.push_back(1);3333EXPECT_THAT(some_list, Not(Contains(4)));3334}33353336TEST(ContainsTest, SetMatchesWhenElementIsInContainer) {3337set<int> some_set;3338some_set.insert(3);3339some_set.insert(1);3340some_set.insert(2);3341EXPECT_THAT(some_set, Contains(Eq(1.0)));3342EXPECT_THAT(some_set, Contains(Eq(3.0f)));3343EXPECT_THAT(some_set, Contains(2));33443345set<std::string> another_set;3346another_set.insert("fee");3347another_set.insert("fie");3348another_set.insert("foe");3349another_set.insert("fum");3350EXPECT_THAT(another_set, Contains(Eq(std::string("fum"))));3351}33523353TEST(ContainsTest, SetDoesNotMatchWhenElementIsNotInContainer) {3354set<int> some_set;3355some_set.insert(3);3356some_set.insert(1);3357EXPECT_THAT(some_set, Not(Contains(4)));33583359set<std::string> c_string_set;3360c_string_set.insert("hello");3361EXPECT_THAT(c_string_set, Not(Contains(std::string("goodbye"))));3362}33633364TEST_P(ContainsTestP, ExplainsMatchResultCorrectly) {3365const int a[2] = {1, 2};3366Matcher<const int (&)[2]> m = Contains(2);3367EXPECT_EQ("whose element #1 matches", Explain(m, a));33683369m = Contains(3);3370EXPECT_EQ("", Explain(m, a));33713372m = Contains(GreaterThan(0));3373EXPECT_EQ("whose element #0 matches, which is 1 more than 0", Explain(m, a));33743375m = Contains(GreaterThan(10));3376EXPECT_EQ("", Explain(m, a));3377}33783379TEST(ContainsTest, DescribesItselfCorrectly) {3380Matcher<vector<int>> m = Contains(1);3381EXPECT_EQ("contains at least one element that is equal to 1", Describe(m));33823383Matcher<vector<int>> m2 = Not(m);3384EXPECT_EQ("doesn't contain any element that is equal to 1", Describe(m2));3385}33863387TEST(ContainsTest, MapMatchesWhenElementIsInContainer) {3388map<std::string, int> my_map;3389const char* bar = "a string";3390my_map[bar] = 2;3391EXPECT_THAT(my_map, Contains(pair<const char* const, int>(bar, 2)));33923393map<std::string, int> another_map;3394another_map["fee"] = 1;3395another_map["fie"] = 2;3396another_map["foe"] = 3;3397another_map["fum"] = 4;3398EXPECT_THAT(another_map,3399Contains(pair<const std::string, int>(std::string("fee"), 1)));3400EXPECT_THAT(another_map, Contains(pair<const std::string, int>("fie", 2)));3401}34023403TEST(ContainsTest, MapDoesNotMatchWhenElementIsNotInContainer) {3404map<int, int> some_map;3405some_map[1] = 11;3406some_map[2] = 22;3407EXPECT_THAT(some_map, Not(Contains(pair<const int, int>(2, 23))));3408}34093410TEST(ContainsTest, ArrayMatchesWhenElementIsInContainer) {3411const char* string_array[] = {"fee", "fie", "foe", "fum"};3412EXPECT_THAT(string_array, Contains(Eq(std::string("fum"))));3413}34143415TEST(ContainsTest, ArrayDoesNotMatchWhenElementIsNotInContainer) {3416int int_array[] = {1, 2, 3, 4};3417EXPECT_THAT(int_array, Not(Contains(5)));3418}34193420TEST(ContainsTest, AcceptsMatcher) {3421const int a[] = {1, 2, 3};3422EXPECT_THAT(a, Contains(Gt(2)));3423EXPECT_THAT(a, Not(Contains(Gt(4))));3424}34253426TEST(ContainsTest, WorksForNativeArrayAsTuple) {3427const int a[] = {1, 2};3428const int* const pointer = a;3429EXPECT_THAT(std::make_tuple(pointer, 2), Contains(1));3430EXPECT_THAT(std::make_tuple(pointer, 2), Not(Contains(Gt(3))));3431}34323433TEST(ContainsTest, WorksForTwoDimensionalNativeArray) {3434int a[][3] = {{1, 2, 3}, {4, 5, 6}};3435EXPECT_THAT(a, Contains(ElementsAre(4, 5, 6)));3436EXPECT_THAT(a, Contains(Contains(5)));3437EXPECT_THAT(a, Not(Contains(ElementsAre(3, 4, 5))));3438EXPECT_THAT(a, Contains(Not(Contains(5))));3439}34403441} // namespace3442} // namespace gmock_matchers_test3443} // namespace testing34443445GTEST_DISABLE_MSC_WARNINGS_POP_() // 4244 4100344634473448