diff options
author | BrukerJWD <jonathan.wendeborn@bruker.com> | 2018-10-16 06:37:56 (GMT) |
---|---|---|
committer | GitHub <noreply@github.com> | 2018-10-16 06:37:56 (GMT) |
commit | 8c82ba48e433005b9e25835b4a342ef4dcc0cfc0 (patch) | |
tree | e1ae94f37108a8f506cd4d11eec0e058c2c39980 /googlemock/test | |
parent | 6bbf911a8dc0c42ad05135f26a07f4893eb83916 (diff) | |
parent | a651a4d44e65b749467fa3dddf93819a22f0cc4a (diff) | |
download | googletest-8c82ba48e433005b9e25835b4a342ef4dcc0cfc0.zip googletest-8c82ba48e433005b9e25835b4a342ef4dcc0cfc0.tar.gz googletest-8c82ba48e433005b9e25835b4a342ef4dcc0cfc0.tar.bz2 |
Merge branch 'master' into isnice
Diffstat (limited to 'googlemock/test')
26 files changed, 2875 insertions, 1339 deletions
diff --git a/googlemock/test/BUILD.bazel b/googlemock/test/BUILD.bazel new file mode 100644 index 0000000..0fe72a6 --- /dev/null +++ b/googlemock/test/BUILD.bazel @@ -0,0 +1,123 @@ +# Copyright 2017 Google Inc. +# All Rights Reserved. +# +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are +# met: +# +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above +# copyright notice, this list of conditions and the following disclaimer +# in the documentation and/or other materials provided with the +# distribution. +# * Neither the name of Google Inc. nor the names of its +# contributors may be used to endorse or promote products derived from +# this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# +# Author: misterg@google.com (Gennadiy Civil) +# +# Bazel Build for Google C++ Testing Framework(Google Test)-googlemock + +licenses(["notice"]) + +""" gmock own tests """ + +cc_test( + name = "gmock_all_test", + size = "small", + srcs = glob( + include = [ + "gmock-*.cc", + ], + ), + linkopts = select({ + "//:windows": [], + "//:windows_msvc": [], + "//conditions:default": [ + "-pthread", + ], + }), + deps = ["//:gtest"], +) + +# Py tests + +py_library( + name = "gmock_test_utils", + testonly = 1, + srcs = ["gmock_test_utils.py"], +) + +cc_binary( + name = "gmock_leak_test_", + testonly = 1, + srcs = ["gmock_leak_test_.cc"], + deps = [ + "//:gtest_main", + ], +) + +py_test( + name = "gmock_leak_test", + size = "medium", + srcs = ["gmock_leak_test.py"], + data = [ + ":gmock_leak_test_", + ":gmock_test_utils", + ], +) + +cc_test( + name = "gmock_link_test", + size = "small", + srcs = [ + "gmock_link2_test.cc", + "gmock_link_test.cc", + "gmock_link_test.h", + ], + deps = [ + "//:gtest_main", + ], +) + +cc_binary( + name = "gmock_output_test_", + srcs = ["gmock_output_test_.cc"], + deps = [ + "//:gtest", + ], +) + +py_test( + name = "gmock_output_test", + size = "medium", + srcs = ["gmock_output_test.py"], + data = [ + ":gmock_output_test_", + ":gmock_output_test_golden.txt", + ], + deps = [":gmock_test_utils"], +) + +cc_test( + name = "gmock_test", + size = "small", + srcs = ["gmock_test.cc"], + deps = [ + "//:gtest_main", + ], +) diff --git a/googlemock/test/gmock-actions_test.cc b/googlemock/test/gmock-actions_test.cc index f470de4..0de8481 100644 --- a/googlemock/test/gmock-actions_test.cc +++ b/googlemock/test/gmock-actions_test.cc @@ -26,13 +26,21 @@ // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -// -// Author: wan@google.com (Zhanyong Wan) + // Google Mock - a framework for writing C++ mock classes. // // This file tests the built-in actions. +// Silence C4800 (C4800: 'int *const ': forcing value +// to bool 'true' or 'false') for MSVC 14,15 +#ifdef _MSC_VER +#if _MSC_VER <= 1900 +# pragma warning(push) +# pragma warning(disable:4800) +#endif +#endif + #include "gmock/gmock-actions.h" #include <algorithm> #include <iterator> @@ -65,28 +73,21 @@ using testing::ReturnRef; using testing::ReturnRefOfCopy; using testing::SetArgPointee; using testing::SetArgumentPointee; +using testing::Unused; using testing::_; -using testing::get; using testing::internal::BuiltInDefaultValue; using testing::internal::Int64; using testing::internal::UInt64; -using testing::make_tuple; -using testing::tuple; -using testing::tuple_element; #if !GTEST_OS_WINDOWS_MOBILE using testing::SetErrnoAndReturn; #endif -#if GTEST_HAS_PROTOBUF_ -using testing::internal::TestMessage; -#endif // GTEST_HAS_PROTOBUF_ - // Tests that BuiltInDefaultValue<T*>::Get() returns NULL. TEST(BuiltInDefaultValueTest, IsNullForPointerTypes) { - EXPECT_TRUE(BuiltInDefaultValue<int*>::Get() == NULL); - EXPECT_TRUE(BuiltInDefaultValue<const char*>::Get() == NULL); - EXPECT_TRUE(BuiltInDefaultValue<void*>::Get() == NULL); + EXPECT_TRUE(BuiltInDefaultValue<int*>::Get() == nullptr); + EXPECT_TRUE(BuiltInDefaultValue<const char*>::Get() == nullptr); + EXPECT_TRUE(BuiltInDefaultValue<void*>::Get() == nullptr); } // Tests that BuiltInDefaultValue<T*>::Exists() return true. @@ -107,7 +108,11 @@ TEST(BuiltInDefaultValueTest, IsZeroForNumericTypes) { EXPECT_EQ(0, BuiltInDefaultValue<signed wchar_t>::Get()); #endif #if GMOCK_WCHAR_T_IS_NATIVE_ +#if !defined(__WCHAR_UNSIGNED__) EXPECT_EQ(0, BuiltInDefaultValue<wchar_t>::Get()); +#else + EXPECT_EQ(0U, BuiltInDefaultValue<wchar_t>::Get()); +#endif #endif EXPECT_EQ(0U, BuiltInDefaultValue<unsigned short>::Get()); // NOLINT EXPECT_EQ(0, BuiltInDefaultValue<signed short>::Get()); // NOLINT @@ -187,7 +192,7 @@ TEST(BuiltInDefaultValueTest, ExistsForString) { TEST(BuiltInDefaultValueTest, WorksForConstTypes) { EXPECT_EQ("", BuiltInDefaultValue<const std::string>::Get()); EXPECT_EQ(0, BuiltInDefaultValue<const int>::Get()); - EXPECT_TRUE(BuiltInDefaultValue<char* const>::Get() == NULL); + EXPECT_TRUE(BuiltInDefaultValue<char* const>::Get() == nullptr); EXPECT_FALSE(BuiltInDefaultValue<const bool>::Get()); } @@ -214,7 +219,7 @@ class MyNonDefaultConstructible { int value_; }; -#if GTEST_HAS_STD_TYPE_TRAITS_ +#if GTEST_LANG_CXX11 TEST(BuiltInDefaultValueTest, ExistsForDefaultConstructibleType) { EXPECT_TRUE(BuiltInDefaultValue<MyDefaultConstructible>::Exists()); @@ -224,7 +229,7 @@ TEST(BuiltInDefaultValueTest, IsDefaultConstructedForDefaultConstructibleType) { EXPECT_EQ(42, BuiltInDefaultValue<MyDefaultConstructible>::Get().value()); } -#endif // GTEST_HAS_STD_TYPE_TRAITS_ +#endif // GTEST_LANG_CXX11 TEST(BuiltInDefaultValueTest, DoesNotExistForNonDefaultConstructibleType) { EXPECT_FALSE(BuiltInDefaultValue<MyNonDefaultConstructible>::Exists()); @@ -297,7 +302,7 @@ TEST(DefaultValueDeathTest, GetReturnsBuiltInDefaultValueWhenUnset) { #if GTEST_HAS_STD_UNIQUE_PTR_ TEST(DefaultValueTest, GetWorksForMoveOnlyIfSet) { EXPECT_TRUE(DefaultValue<std::unique_ptr<int>>::Exists()); - EXPECT_TRUE(DefaultValue<std::unique_ptr<int>>::Get() == NULL); + EXPECT_TRUE(DefaultValue<std::unique_ptr<int>>::Get() == nullptr); DefaultValue<std::unique_ptr<int>>::SetFactory([] { return std::unique_ptr<int>(new int(42)); }); @@ -373,8 +378,8 @@ typedef int MyGlobalFunction(bool, int); class MyActionImpl : public ActionInterface<MyGlobalFunction> { public: - virtual int Perform(const tuple<bool, int>& args) { - return get<0>(args) ? get<1>(args) : 0; + virtual int Perform(const std::tuple<bool, int>& args) { + return std::get<0>(args) ? std::get<1>(args) : 0; } }; @@ -390,8 +395,8 @@ TEST(ActionInterfaceTest, MakeAction) { // it a tuple whose size and type are compatible with F's argument // types. For example, if F is int(), then Perform() takes a // 0-tuple; if F is void(bool, int), then Perform() takes a - // tuple<bool, int>, and so on. - EXPECT_EQ(5, action.Perform(make_tuple(true, 5))); + // std::tuple<bool, int>, and so on. + EXPECT_EQ(5, action.Perform(std::make_tuple(true, 5))); } // Tests that Action<F> can be contructed from a pointer to @@ -404,8 +409,8 @@ TEST(ActionTest, CanBeConstructedFromActionInterface) { TEST(ActionTest, DelegatesWorkToActionInterface) { const Action<MyGlobalFunction> action(new MyActionImpl); - EXPECT_EQ(5, action.Perform(make_tuple(true, 5))); - EXPECT_EQ(0, action.Perform(make_tuple(false, 1))); + EXPECT_EQ(5, action.Perform(std::make_tuple(true, 5))); + EXPECT_EQ(0, action.Perform(std::make_tuple(false, 1))); } // Tests that Action<F> can be copied. @@ -414,22 +419,22 @@ TEST(ActionTest, IsCopyable) { Action<MyGlobalFunction> a2(a1); // Tests the copy constructor. // a1 should continue to work after being copied from. - EXPECT_EQ(5, a1.Perform(make_tuple(true, 5))); - EXPECT_EQ(0, a1.Perform(make_tuple(false, 1))); + EXPECT_EQ(5, a1.Perform(std::make_tuple(true, 5))); + EXPECT_EQ(0, a1.Perform(std::make_tuple(false, 1))); // a2 should work like the action it was copied from. - EXPECT_EQ(5, a2.Perform(make_tuple(true, 5))); - EXPECT_EQ(0, a2.Perform(make_tuple(false, 1))); + EXPECT_EQ(5, a2.Perform(std::make_tuple(true, 5))); + EXPECT_EQ(0, a2.Perform(std::make_tuple(false, 1))); a2 = a1; // Tests the assignment operator. // a1 should continue to work after being copied from. - EXPECT_EQ(5, a1.Perform(make_tuple(true, 5))); - EXPECT_EQ(0, a1.Perform(make_tuple(false, 1))); + EXPECT_EQ(5, a1.Perform(std::make_tuple(true, 5))); + EXPECT_EQ(0, a1.Perform(std::make_tuple(false, 1))); // a2 should work like the action it was copied from. - EXPECT_EQ(5, a2.Perform(make_tuple(true, 5))); - EXPECT_EQ(0, a2.Perform(make_tuple(false, 1))); + EXPECT_EQ(5, a2.Perform(std::make_tuple(true, 5))); + EXPECT_EQ(0, a2.Perform(std::make_tuple(false, 1))); } // Tests that an Action<From> object can be converted to a @@ -437,8 +442,8 @@ TEST(ActionTest, IsCopyable) { class IsNotZero : public ActionInterface<bool(int)> { // NOLINT public: - virtual bool Perform(const tuple<int>& arg) { - return get<0>(arg) != 0; + virtual bool Perform(const std::tuple<int>& arg) { + return std::get<0>(arg) != 0; } }; @@ -451,8 +456,8 @@ class IsNotZero : public ActionInterface<bool(int)> { // NOLINT TEST(ActionTest, CanBeConvertedToOtherActionType) { const Action<bool(int)> a1(new IsNotZero); // NOLINT const Action<int(char)> a2 = Action<int(char)>(a1); // NOLINT - EXPECT_EQ(1, a2.Perform(make_tuple('a'))); - EXPECT_EQ(0, a2.Perform(make_tuple('\0'))); + EXPECT_EQ(1, a2.Perform(std::make_tuple('a'))); + EXPECT_EQ(0, a2.Perform(std::make_tuple('\0'))); } #endif // !GTEST_OS_SYMBIAN @@ -466,7 +471,9 @@ class ReturnSecondArgumentAction { // polymorphic action whose Perform() method template is either // const or not. This lets us verify the non-const case. template <typename Result, typename ArgumentTuple> - Result Perform(const ArgumentTuple& args) { return get<1>(args); } + Result Perform(const ArgumentTuple& args) { + return std::get<1>(args); + } }; // Implements a polymorphic action that can be used in a nullary @@ -481,7 +488,9 @@ class ReturnZeroFromNullaryFunctionAction { // polymorphic action whose Perform() method template is either // const or not. This lets us verify the const case. template <typename Result> - Result Perform(const tuple<>&) const { return 0; } + Result Perform(const std::tuple<>&) const { + return 0; + } }; // These functions verify that MakePolymorphicAction() returns a @@ -500,42 +509,42 @@ ReturnZeroFromNullaryFunction() { // implementation class into a polymorphic action. TEST(MakePolymorphicActionTest, ConstructsActionFromImpl) { Action<int(bool, int, double)> a1 = ReturnSecondArgument(); // NOLINT - EXPECT_EQ(5, a1.Perform(make_tuple(false, 5, 2.0))); + EXPECT_EQ(5, a1.Perform(std::make_tuple(false, 5, 2.0))); } // Tests that MakePolymorphicAction() works when the implementation // class' Perform() method template has only one template parameter. TEST(MakePolymorphicActionTest, WorksWhenPerformHasOneTemplateParameter) { Action<int()> a1 = ReturnZeroFromNullaryFunction(); - EXPECT_EQ(0, a1.Perform(make_tuple())); + EXPECT_EQ(0, a1.Perform(std::make_tuple())); Action<void*()> a2 = ReturnZeroFromNullaryFunction(); - EXPECT_TRUE(a2.Perform(make_tuple()) == NULL); + EXPECT_TRUE(a2.Perform(std::make_tuple()) == nullptr); } // Tests that Return() works as an action for void-returning // functions. TEST(ReturnTest, WorksForVoid) { const Action<void(int)> ret = Return(); // NOLINT - return ret.Perform(make_tuple(1)); + return ret.Perform(std::make_tuple(1)); } // Tests that Return(v) returns v. TEST(ReturnTest, ReturnsGivenValue) { Action<int()> ret = Return(1); // NOLINT - EXPECT_EQ(1, ret.Perform(make_tuple())); + EXPECT_EQ(1, ret.Perform(std::make_tuple())); ret = Return(-5); - EXPECT_EQ(-5, ret.Perform(make_tuple())); + EXPECT_EQ(-5, ret.Perform(std::make_tuple())); } // Tests that Return("string literal") works. TEST(ReturnTest, AcceptsStringLiteral) { Action<const char*()> a1 = Return("Hello"); - EXPECT_STREQ("Hello", a1.Perform(make_tuple())); + EXPECT_STREQ("Hello", a1.Perform(std::make_tuple())); Action<std::string()> a2 = Return("world"); - EXPECT_EQ("world", a2.Perform(make_tuple())); + EXPECT_EQ("world", a2.Perform(std::make_tuple())); } // Test struct which wraps a vector of integers. Used in @@ -554,7 +563,7 @@ TEST(ReturnTest, SupportsWrapperReturnType) { // Return() called with 'v' as argument. The Action will return the same data // as 'v' (copy) but it will be wrapped in an IntegerVectorWrapper. Action<IntegerVectorWrapper()> a = Return(v); - const std::vector<int>& result = *(a.Perform(make_tuple()).v); + const std::vector<int>& result = *(a.Perform(std::make_tuple()).v); EXPECT_THAT(result, ::testing::ElementsAre(0, 1, 2, 3, 4)); } @@ -572,10 +581,10 @@ TEST(ReturnTest, IsCovariant) { Base base; Derived derived; Action<Base*()> ret = Return(&base); - EXPECT_EQ(&base, ret.Perform(make_tuple())); + EXPECT_EQ(&base, ret.Perform(std::make_tuple())); ret = Return(&derived); - EXPECT_EQ(&derived, ret.Perform(make_tuple())); + EXPECT_EQ(&derived, ret.Perform(std::make_tuple())); } // Tests that the type of the value passed into Return is converted into T @@ -606,7 +615,7 @@ TEST(ReturnTest, ConvertsArgumentWhenConverted) { EXPECT_TRUE(converted) << "Return must convert its argument in its own " << "conversion operator."; converted = false; - action.Perform(tuple<>()); + action.Perform(std::tuple<>()); EXPECT_FALSE(converted) << "Action must NOT convert its argument " << "when performed."; } @@ -627,10 +636,10 @@ TEST(ReturnTest, CanConvertArgumentUsingNonConstTypeCastOperator) { // Tests that ReturnNull() returns NULL in a pointer-returning function. TEST(ReturnNullTest, WorksInPointerReturningFunction) { const Action<int*()> a1 = ReturnNull(); - EXPECT_TRUE(a1.Perform(make_tuple()) == NULL); + EXPECT_TRUE(a1.Perform(std::make_tuple()) == nullptr); const Action<const char*(bool)> a2 = ReturnNull(); // NOLINT - EXPECT_TRUE(a2.Perform(make_tuple(true)) == NULL); + EXPECT_TRUE(a2.Perform(std::make_tuple(true)) == nullptr); } #if GTEST_HAS_STD_UNIQUE_PTR_ @@ -638,10 +647,10 @@ TEST(ReturnNullTest, WorksInPointerReturningFunction) { // functions. TEST(ReturnNullTest, WorksInSmartPointerReturningFunction) { const Action<std::unique_ptr<const int>()> a1 = ReturnNull(); - EXPECT_TRUE(a1.Perform(make_tuple()) == nullptr); + EXPECT_TRUE(a1.Perform(std::make_tuple()) == nullptr); const Action<std::shared_ptr<int>(std::string)> a2 = ReturnNull(); - EXPECT_TRUE(a2.Perform(make_tuple("foo")) == nullptr); + EXPECT_TRUE(a2.Perform(std::make_tuple("foo")) == nullptr); } #endif // GTEST_HAS_STD_UNIQUE_PTR_ @@ -650,7 +659,7 @@ TEST(ReturnRefTest, WorksForReference) { const int n = 0; const Action<const int&(bool)> ret = ReturnRef(n); // NOLINT - EXPECT_EQ(&n, &ret.Perform(make_tuple(true))); + EXPECT_EQ(&n, &ret.Perform(std::make_tuple(true))); } // Tests that ReturnRef(v) is covariant. @@ -658,10 +667,10 @@ TEST(ReturnRefTest, IsCovariant) { Base base; Derived derived; Action<Base&()> a = ReturnRef(base); - EXPECT_EQ(&base, &a.Perform(make_tuple())); + EXPECT_EQ(&base, &a.Perform(std::make_tuple())); a = ReturnRef(derived); - EXPECT_EQ(&derived, &a.Perform(make_tuple())); + EXPECT_EQ(&derived, &a.Perform(std::make_tuple())); } // Tests that ReturnRefOfCopy(v) works for reference types. @@ -669,12 +678,12 @@ TEST(ReturnRefOfCopyTest, WorksForReference) { int n = 42; const Action<const int&()> ret = ReturnRefOfCopy(n); - EXPECT_NE(&n, &ret.Perform(make_tuple())); - EXPECT_EQ(42, ret.Perform(make_tuple())); + EXPECT_NE(&n, &ret.Perform(std::make_tuple())); + EXPECT_EQ(42, ret.Perform(std::make_tuple())); n = 43; - EXPECT_NE(&n, &ret.Perform(make_tuple())); - EXPECT_EQ(42, ret.Perform(make_tuple())); + EXPECT_NE(&n, &ret.Perform(std::make_tuple())); + EXPECT_EQ(42, ret.Perform(std::make_tuple())); } // Tests that ReturnRefOfCopy(v) is covariant. @@ -682,10 +691,10 @@ TEST(ReturnRefOfCopyTest, IsCovariant) { Base base; Derived derived; Action<Base&()> a = ReturnRefOfCopy(base); - EXPECT_NE(&base, &a.Perform(make_tuple())); + EXPECT_NE(&base, &a.Perform(std::make_tuple())); a = ReturnRefOfCopy(derived); - EXPECT_NE(&derived, &a.Perform(make_tuple())); + EXPECT_NE(&derived, &a.Perform(std::make_tuple())); } // Tests that DoDefault() does the default action for the mock method. @@ -700,6 +709,9 @@ class MockClass { MOCK_METHOD0(MakeUnique, std::unique_ptr<int>()); MOCK_METHOD0(MakeUniqueBase, std::unique_ptr<Base>()); MOCK_METHOD0(MakeVectorUnique, std::vector<std::unique_ptr<int>>()); + MOCK_METHOD1(TakeUnique, int(std::unique_ptr<int>)); + MOCK_METHOD2(TakeUnique, + int(const std::unique_ptr<int>&, std::unique_ptr<int>)); #endif private: @@ -788,14 +800,14 @@ TEST(SetArgPointeeTest, SetsTheNthPointee) { int n = 0; char ch = '\0'; - a.Perform(make_tuple(true, &n, &ch)); + a.Perform(std::make_tuple(true, &n, &ch)); EXPECT_EQ(2, n); EXPECT_EQ('\0', ch); a = SetArgPointee<2>('a'); n = 0; ch = '\0'; - a.Perform(make_tuple(true, &n, &ch)); + a.Perform(std::make_tuple(true, &n, &ch)); EXPECT_EQ(0, n); EXPECT_EQ('a', ch); } @@ -807,14 +819,14 @@ TEST(SetArgPointeeTest, AcceptsStringLiteral) { typedef void MyFunction(std::string*, const char**); Action<MyFunction> a = SetArgPointee<0>("hi"); std::string str; - const char* ptr = NULL; - a.Perform(make_tuple(&str, &ptr)); + const char* ptr = nullptr; + a.Perform(std::make_tuple(&str, &ptr)); EXPECT_EQ("hi", str); - EXPECT_TRUE(ptr == NULL); + EXPECT_TRUE(ptr == nullptr); a = SetArgPointee<1>("world"); str = ""; - a.Perform(make_tuple(&str, &ptr)); + a.Perform(std::make_tuple(&str, &ptr)); EXPECT_EQ("", str); EXPECT_STREQ("world", ptr); } @@ -822,8 +834,8 @@ TEST(SetArgPointeeTest, AcceptsStringLiteral) { TEST(SetArgPointeeTest, AcceptsWideStringLiteral) { typedef void MyFunction(const wchar_t**); Action<MyFunction> a = SetArgPointee<0>(L"world"); - const wchar_t* ptr = NULL; - a.Perform(make_tuple(&ptr)); + const wchar_t* ptr = nullptr; + a.Perform(std::make_tuple(&ptr)); EXPECT_STREQ(L"world", ptr); # if GTEST_HAS_STD_WSTRING @@ -831,7 +843,7 @@ TEST(SetArgPointeeTest, AcceptsWideStringLiteral) { typedef void MyStringFunction(std::wstring*); Action<MyStringFunction> a2 = SetArgPointee<0>(L"world"); std::wstring str = L""; - a2.Perform(make_tuple(&str)); + a2.Perform(std::make_tuple(&str)); EXPECT_EQ(L"world", str); # endif @@ -844,16 +856,16 @@ TEST(SetArgPointeeTest, AcceptsCharPointer) { const char* const hi = "hi"; Action<MyFunction> a = SetArgPointee<1>(hi); std::string str; - const char* ptr = NULL; - a.Perform(make_tuple(true, &str, &ptr)); + const char* ptr = nullptr; + a.Perform(std::make_tuple(true, &str, &ptr)); EXPECT_EQ("hi", str); - EXPECT_TRUE(ptr == NULL); + EXPECT_TRUE(ptr == nullptr); char world_array[] = "world"; char* const world = world_array; a = SetArgPointee<2>(world); str = ""; - a.Perform(make_tuple(true, &str, &ptr)); + a.Perform(std::make_tuple(true, &str, &ptr)); EXPECT_EQ("", str); EXPECT_EQ(world, ptr); } @@ -862,8 +874,8 @@ TEST(SetArgPointeeTest, AcceptsWideCharPointer) { typedef void MyFunction(bool, const wchar_t**); const wchar_t* const hi = L"hi"; Action<MyFunction> a = SetArgPointee<1>(hi); - const wchar_t* ptr = NULL; - a.Perform(make_tuple(true, &ptr)); + const wchar_t* ptr = nullptr; + a.Perform(std::make_tuple(true, &ptr)); EXPECT_EQ(hi, ptr); # if GTEST_HAS_STD_WSTRING @@ -873,110 +885,11 @@ TEST(SetArgPointeeTest, AcceptsWideCharPointer) { wchar_t* const world = world_array; Action<MyStringFunction> a2 = SetArgPointee<1>(world); std::wstring str; - a2.Perform(make_tuple(true, &str)); + a2.Perform(std::make_tuple(true, &str)); EXPECT_EQ(world_array, str); # endif } -#if GTEST_HAS_PROTOBUF_ - -// Tests that SetArgPointee<N>(proto_buffer) sets the v1 protobuf -// variable pointed to by the N-th (0-based) argument to proto_buffer. -TEST(SetArgPointeeTest, SetsTheNthPointeeOfProtoBufferType) { - TestMessage* const msg = new TestMessage; - msg->set_member("yes"); - TestMessage orig_msg; - orig_msg.CopyFrom(*msg); - - Action<void(bool, TestMessage*)> a = SetArgPointee<1>(*msg); - // SetArgPointee<N>(proto_buffer) makes a copy of proto_buffer - // s.t. the action works even when the original proto_buffer has - // died. We ensure this behavior by deleting msg before using the - // action. - delete msg; - - TestMessage dest; - EXPECT_FALSE(orig_msg.Equals(dest)); - a.Perform(make_tuple(true, &dest)); - EXPECT_TRUE(orig_msg.Equals(dest)); -} - -// Tests that SetArgPointee<N>(proto_buffer) sets the -// ::ProtocolMessage variable pointed to by the N-th (0-based) -// argument to proto_buffer. -TEST(SetArgPointeeTest, SetsTheNthPointeeOfProtoBufferBaseType) { - TestMessage* const msg = new TestMessage; - msg->set_member("yes"); - TestMessage orig_msg; - orig_msg.CopyFrom(*msg); - - Action<void(bool, ::ProtocolMessage*)> a = SetArgPointee<1>(*msg); - // SetArgPointee<N>(proto_buffer) makes a copy of proto_buffer - // s.t. the action works even when the original proto_buffer has - // died. We ensure this behavior by deleting msg before using the - // action. - delete msg; - - TestMessage dest; - ::ProtocolMessage* const dest_base = &dest; - EXPECT_FALSE(orig_msg.Equals(dest)); - a.Perform(make_tuple(true, dest_base)); - EXPECT_TRUE(orig_msg.Equals(dest)); -} - -// Tests that SetArgPointee<N>(proto2_buffer) sets the v2 -// protobuf variable pointed to by the N-th (0-based) argument to -// proto2_buffer. -TEST(SetArgPointeeTest, SetsTheNthPointeeOfProto2BufferType) { - using testing::internal::FooMessage; - FooMessage* const msg = new FooMessage; - msg->set_int_field(2); - msg->set_string_field("hi"); - FooMessage orig_msg; - orig_msg.CopyFrom(*msg); - - Action<void(bool, FooMessage*)> a = SetArgPointee<1>(*msg); - // SetArgPointee<N>(proto2_buffer) makes a copy of - // proto2_buffer s.t. the action works even when the original - // proto2_buffer has died. We ensure this behavior by deleting msg - // before using the action. - delete msg; - - FooMessage dest; - dest.set_int_field(0); - a.Perform(make_tuple(true, &dest)); - EXPECT_EQ(2, dest.int_field()); - EXPECT_EQ("hi", dest.string_field()); -} - -// Tests that SetArgPointee<N>(proto2_buffer) sets the -// proto2::Message variable pointed to by the N-th (0-based) argument -// to proto2_buffer. -TEST(SetArgPointeeTest, SetsTheNthPointeeOfProto2BufferBaseType) { - using testing::internal::FooMessage; - FooMessage* const msg = new FooMessage; - msg->set_int_field(2); - msg->set_string_field("hi"); - FooMessage orig_msg; - orig_msg.CopyFrom(*msg); - - Action<void(bool, ::proto2::Message*)> a = SetArgPointee<1>(*msg); - // SetArgPointee<N>(proto2_buffer) makes a copy of - // proto2_buffer s.t. the action works even when the original - // proto2_buffer has died. We ensure this behavior by deleting msg - // before using the action. - delete msg; - - FooMessage dest; - dest.set_int_field(0); - ::proto2::Message* const dest_base = &dest; - a.Perform(make_tuple(true, dest_base)); - EXPECT_EQ(2, dest.int_field()); - EXPECT_EQ("hi", dest.string_field()); -} - -#endif // GTEST_HAS_PROTOBUF_ - // Tests that SetArgumentPointee<N>(v) sets the variable pointed to by // the N-th (0-based) argument to v. TEST(SetArgumentPointeeTest, SetsTheNthPointee) { @@ -985,117 +898,18 @@ TEST(SetArgumentPointeeTest, SetsTheNthPointee) { int n = 0; char ch = '\0'; - a.Perform(make_tuple(true, &n, &ch)); + a.Perform(std::make_tuple(true, &n, &ch)); EXPECT_EQ(2, n); EXPECT_EQ('\0', ch); a = SetArgumentPointee<2>('a'); n = 0; ch = '\0'; - a.Perform(make_tuple(true, &n, &ch)); + a.Perform(std::make_tuple(true, &n, &ch)); EXPECT_EQ(0, n); EXPECT_EQ('a', ch); } -#if GTEST_HAS_PROTOBUF_ - -// Tests that SetArgumentPointee<N>(proto_buffer) sets the v1 protobuf -// variable pointed to by the N-th (0-based) argument to proto_buffer. -TEST(SetArgumentPointeeTest, SetsTheNthPointeeOfProtoBufferType) { - TestMessage* const msg = new TestMessage; - msg->set_member("yes"); - TestMessage orig_msg; - orig_msg.CopyFrom(*msg); - - Action<void(bool, TestMessage*)> a = SetArgumentPointee<1>(*msg); - // SetArgumentPointee<N>(proto_buffer) makes a copy of proto_buffer - // s.t. the action works even when the original proto_buffer has - // died. We ensure this behavior by deleting msg before using the - // action. - delete msg; - - TestMessage dest; - EXPECT_FALSE(orig_msg.Equals(dest)); - a.Perform(make_tuple(true, &dest)); - EXPECT_TRUE(orig_msg.Equals(dest)); -} - -// Tests that SetArgumentPointee<N>(proto_buffer) sets the -// ::ProtocolMessage variable pointed to by the N-th (0-based) -// argument to proto_buffer. -TEST(SetArgumentPointeeTest, SetsTheNthPointeeOfProtoBufferBaseType) { - TestMessage* const msg = new TestMessage; - msg->set_member("yes"); - TestMessage orig_msg; - orig_msg.CopyFrom(*msg); - - Action<void(bool, ::ProtocolMessage*)> a = SetArgumentPointee<1>(*msg); - // SetArgumentPointee<N>(proto_buffer) makes a copy of proto_buffer - // s.t. the action works even when the original proto_buffer has - // died. We ensure this behavior by deleting msg before using the - // action. - delete msg; - - TestMessage dest; - ::ProtocolMessage* const dest_base = &dest; - EXPECT_FALSE(orig_msg.Equals(dest)); - a.Perform(make_tuple(true, dest_base)); - EXPECT_TRUE(orig_msg.Equals(dest)); -} - -// Tests that SetArgumentPointee<N>(proto2_buffer) sets the v2 -// protobuf variable pointed to by the N-th (0-based) argument to -// proto2_buffer. -TEST(SetArgumentPointeeTest, SetsTheNthPointeeOfProto2BufferType) { - using testing::internal::FooMessage; - FooMessage* const msg = new FooMessage; - msg->set_int_field(2); - msg->set_string_field("hi"); - FooMessage orig_msg; - orig_msg.CopyFrom(*msg); - - Action<void(bool, FooMessage*)> a = SetArgumentPointee<1>(*msg); - // SetArgumentPointee<N>(proto2_buffer) makes a copy of - // proto2_buffer s.t. the action works even when the original - // proto2_buffer has died. We ensure this behavior by deleting msg - // before using the action. - delete msg; - - FooMessage dest; - dest.set_int_field(0); - a.Perform(make_tuple(true, &dest)); - EXPECT_EQ(2, dest.int_field()); - EXPECT_EQ("hi", dest.string_field()); -} - -// Tests that SetArgumentPointee<N>(proto2_buffer) sets the -// proto2::Message variable pointed to by the N-th (0-based) argument -// to proto2_buffer. -TEST(SetArgumentPointeeTest, SetsTheNthPointeeOfProto2BufferBaseType) { - using testing::internal::FooMessage; - FooMessage* const msg = new FooMessage; - msg->set_int_field(2); - msg->set_string_field("hi"); - FooMessage orig_msg; - orig_msg.CopyFrom(*msg); - - Action<void(bool, ::proto2::Message*)> a = SetArgumentPointee<1>(*msg); - // SetArgumentPointee<N>(proto2_buffer) makes a copy of - // proto2_buffer s.t. the action works even when the original - // proto2_buffer has died. We ensure this behavior by deleting msg - // before using the action. - delete msg; - - FooMessage dest; - dest.set_int_field(0); - ::proto2::Message* const dest_base = &dest; - a.Perform(make_tuple(true, dest_base)); - EXPECT_EQ(2, dest.int_field()); - EXPECT_EQ("hi", dest.string_field()); -} - -#endif // GTEST_HAS_PROTOBUF_ - // Sample functions and functors for testing Invoke() and etc. int Nullary() { return 1; } @@ -1126,16 +940,16 @@ class Foo { TEST(InvokeWithoutArgsTest, Function) { // As an action that takes one argument. Action<int(int)> a = InvokeWithoutArgs(Nullary); // NOLINT - EXPECT_EQ(1, a.Perform(make_tuple(2))); + EXPECT_EQ(1, a.Perform(std::make_tuple(2))); // As an action that takes two arguments. Action<int(int, double)> a2 = InvokeWithoutArgs(Nullary); // NOLINT - EXPECT_EQ(1, a2.Perform(make_tuple(2, 3.5))); + EXPECT_EQ(1, a2.Perform(std::make_tuple(2, 3.5))); // As an action that returns void. Action<void(int)> a3 = InvokeWithoutArgs(VoidNullary); // NOLINT g_done = false; - a3.Perform(make_tuple(1)); + a3.Perform(std::make_tuple(1)); EXPECT_TRUE(g_done); } @@ -1143,17 +957,17 @@ TEST(InvokeWithoutArgsTest, Function) { TEST(InvokeWithoutArgsTest, Functor) { // As an action that takes no argument. Action<int()> a = InvokeWithoutArgs(NullaryFunctor()); // NOLINT - EXPECT_EQ(2, a.Perform(make_tuple())); + EXPECT_EQ(2, a.Perform(std::make_tuple())); // As an action that takes three arguments. Action<int(int, double, char)> a2 = // NOLINT InvokeWithoutArgs(NullaryFunctor()); - EXPECT_EQ(2, a2.Perform(make_tuple(3, 3.5, 'a'))); + EXPECT_EQ(2, a2.Perform(std::make_tuple(3, 3.5, 'a'))); // As an action that returns void. Action<void()> a3 = InvokeWithoutArgs(VoidNullaryFunctor()); g_done = false; - a3.Perform(make_tuple()); + a3.Perform(std::make_tuple()); EXPECT_TRUE(g_done); } @@ -1162,13 +976,13 @@ TEST(InvokeWithoutArgsTest, Method) { Foo foo; Action<int(bool, char)> a = // NOLINT InvokeWithoutArgs(&foo, &Foo::Nullary); - EXPECT_EQ(123, a.Perform(make_tuple(true, 'a'))); + EXPECT_EQ(123, a.Perform(std::make_tuple(true, 'a'))); } // Tests using IgnoreResult() on a polymorphic action. TEST(IgnoreResultTest, PolymorphicAction) { Action<void(int)> a = IgnoreResult(Return(5)); // NOLINT - a.Perform(make_tuple(1)); + a.Perform(std::make_tuple(1)); } // Tests using IgnoreResult() on a monomorphic action. @@ -1181,7 +995,7 @@ int ReturnOne() { TEST(IgnoreResultTest, MonomorphicAction) { g_done = false; Action<void()> a = IgnoreResult(Invoke(ReturnOne)); - a.Perform(make_tuple()); + a.Perform(std::make_tuple()); EXPECT_TRUE(g_done); } @@ -1196,28 +1010,28 @@ TEST(IgnoreResultTest, ActionReturningClass) { g_done = false; Action<void(int)> a = IgnoreResult(Invoke(ReturnMyNonDefaultConstructible)); // NOLINT - a.Perform(make_tuple(2)); + a.Perform(std::make_tuple(2)); EXPECT_TRUE(g_done); } TEST(AssignTest, Int) { int x = 0; Action<void(int)> a = Assign(&x, 5); - a.Perform(make_tuple(0)); + a.Perform(std::make_tuple(0)); EXPECT_EQ(5, x); } TEST(AssignTest, String) { ::std::string x; Action<void(void)> a = Assign(&x, "Hello, world"); - a.Perform(make_tuple()); + a.Perform(std::make_tuple()); EXPECT_EQ("Hello, world", x); } TEST(AssignTest, CompatibleTypes) { double x = 0; Action<void(int)> a = Assign(&x, 5); - a.Perform(make_tuple(0)); + a.Perform(std::make_tuple(0)); EXPECT_DOUBLE_EQ(5, x); } @@ -1231,20 +1045,20 @@ class SetErrnoAndReturnTest : public testing::Test { TEST_F(SetErrnoAndReturnTest, Int) { Action<int(void)> a = SetErrnoAndReturn(ENOTTY, -5); - EXPECT_EQ(-5, a.Perform(make_tuple())); + EXPECT_EQ(-5, a.Perform(std::make_tuple())); EXPECT_EQ(ENOTTY, errno); } TEST_F(SetErrnoAndReturnTest, Ptr) { int x; Action<int*(void)> a = SetErrnoAndReturn(ENOTTY, &x); - EXPECT_EQ(&x, a.Perform(make_tuple())); + EXPECT_EQ(&x, a.Perform(std::make_tuple())); EXPECT_EQ(ENOTTY, errno); } TEST_F(SetErrnoAndReturnTest, CompatibleTypes) { Action<double()> a = SetErrnoAndReturn(EINVAL, 5); - EXPECT_DOUBLE_EQ(5.0, a.Perform(make_tuple())); + EXPECT_DOUBLE_EQ(5.0, a.Perform(std::make_tuple())); EXPECT_EQ(EINVAL, errno); } @@ -1406,6 +1220,153 @@ TEST(MockMethodTest, CanReturnMoveOnlyValue_Invoke) { EXPECT_EQ(7, *vresult[0]); } +TEST(MockMethodTest, CanTakeMoveOnlyValue) { + MockClass mock; + auto make = [](int i) { return std::unique_ptr<int>(new int(i)); }; + + EXPECT_CALL(mock, TakeUnique(_)).WillRepeatedly([](std::unique_ptr<int> i) { + return *i; + }); + // DoAll() does not compile, since it would move from its arguments twice. + // EXPECT_CALL(mock, TakeUnique(_, _)) + // .WillRepeatedly(DoAll(Invoke([](std::unique_ptr<int> j) {}), + // Return(1))); + EXPECT_CALL(mock, TakeUnique(testing::Pointee(7))) + .WillOnce(Return(-7)) + .RetiresOnSaturation(); + EXPECT_CALL(mock, TakeUnique(testing::IsNull())) + .WillOnce(Return(-1)) + .RetiresOnSaturation(); + + EXPECT_EQ(5, mock.TakeUnique(make(5))); + EXPECT_EQ(-7, mock.TakeUnique(make(7))); + EXPECT_EQ(7, mock.TakeUnique(make(7))); + EXPECT_EQ(7, mock.TakeUnique(make(7))); + EXPECT_EQ(-1, mock.TakeUnique({})); + + // Some arguments are moved, some passed by reference. + auto lvalue = make(6); + EXPECT_CALL(mock, TakeUnique(_, _)) + .WillOnce([](const std::unique_ptr<int>& i, std::unique_ptr<int> j) { + return *i * *j; + }); + EXPECT_EQ(42, mock.TakeUnique(lvalue, make(7))); + + // The unique_ptr can be saved by the action. + std::unique_ptr<int> saved; + EXPECT_CALL(mock, TakeUnique(_)).WillOnce([&saved](std::unique_ptr<int> i) { + saved = std::move(i); + return 0; + }); + EXPECT_EQ(0, mock.TakeUnique(make(42))); + EXPECT_EQ(42, *saved); +} + #endif // GTEST_HAS_STD_UNIQUE_PTR_ +#if GTEST_LANG_CXX11 +// Tests for std::function based action. + +int Add(int val, int& ref, int* ptr) { // NOLINT + int result = val + ref + *ptr; + ref = 42; + *ptr = 43; + return result; +} + +int Deref(std::unique_ptr<int> ptr) { return *ptr; } + +struct Double { + template <typename T> + T operator()(T t) { return 2 * t; } +}; + +std::unique_ptr<int> UniqueInt(int i) { + return std::unique_ptr<int>(new int(i)); +} + +TEST(FunctorActionTest, ActionFromFunction) { + Action<int(int, int&, int*)> a = &Add; + int x = 1, y = 2, z = 3; + EXPECT_EQ(6, a.Perform(std::forward_as_tuple(x, y, &z))); + EXPECT_EQ(42, y); + EXPECT_EQ(43, z); + + Action<int(std::unique_ptr<int>)> a1 = &Deref; + EXPECT_EQ(7, a1.Perform(std::make_tuple(UniqueInt(7)))); +} + +TEST(FunctorActionTest, ActionFromLambda) { + Action<int(bool, int)> a1 = [](bool b, int i) { return b ? i : 0; }; + EXPECT_EQ(5, a1.Perform(std::make_tuple(true, 5))); + EXPECT_EQ(0, a1.Perform(std::make_tuple(false, 5))); + + std::unique_ptr<int> saved; + Action<void(std::unique_ptr<int>)> a2 = [&saved](std::unique_ptr<int> p) { + saved = std::move(p); + }; + a2.Perform(std::make_tuple(UniqueInt(5))); + EXPECT_EQ(5, *saved); +} + +TEST(FunctorActionTest, PolymorphicFunctor) { + Action<int(int)> ai = Double(); + EXPECT_EQ(2, ai.Perform(std::make_tuple(1))); + Action<double(double)> ad = Double(); // Double? Double double! + EXPECT_EQ(3.0, ad.Perform(std::make_tuple(1.5))); +} + +TEST(FunctorActionTest, TypeConversion) { + // Numeric promotions are allowed. + const Action<bool(int)> a1 = [](int i) { return i > 1; }; + const Action<int(bool)> a2 = Action<int(bool)>(a1); + EXPECT_EQ(1, a1.Perform(std::make_tuple(42))); + EXPECT_EQ(0, a2.Perform(std::make_tuple(42))); + + // Implicit constructors are allowed. + const Action<bool(std::string)> s1 = [](std::string s) { return !s.empty(); }; + const Action<int(const char*)> s2 = Action<int(const char*)>(s1); + EXPECT_EQ(0, s2.Perform(std::make_tuple(""))); + EXPECT_EQ(1, s2.Perform(std::make_tuple("hello"))); + + // Also between the lambda and the action itself. + const Action<bool(std::string)> x = [](Unused) { return 42; }; + EXPECT_TRUE(x.Perform(std::make_tuple("hello"))); +} + +TEST(FunctorActionTest, UnusedArguments) { + // Verify that users can ignore uninteresting arguments. + Action<int(int, double y, double z)> a = + [](int i, Unused, Unused) { return 2 * i; }; + std::tuple<int, double, double> dummy = std::make_tuple(3, 7.3, 9.44); + EXPECT_EQ(6, a.Perform(dummy)); +} + +// Test that basic built-in actions work with move-only arguments. +// FIXME: Currently, almost all ActionInterface-based actions will not +// work, even if they only try to use other, copyable arguments. Implement them +// if necessary (but note that DoAll cannot work on non-copyable types anyway - +// so maybe it's better to make users use lambdas instead. +TEST(MoveOnlyArgumentsTest, ReturningActions) { + Action<int(std::unique_ptr<int>)> a = Return(1); + EXPECT_EQ(1, a.Perform(std::make_tuple(nullptr))); + + a = testing::WithoutArgs([]() { return 7; }); + EXPECT_EQ(7, a.Perform(std::make_tuple(nullptr))); + + Action<void(std::unique_ptr<int>, int*)> a2 = testing::SetArgPointee<1>(3); + int x = 0; + a2.Perform(std::make_tuple(nullptr, &x)); + EXPECT_EQ(x, 3); +} + +#endif // GTEST_LANG_CXX11 + } // Unnamed namespace + +#ifdef _MSC_VER +#if _MSC_VER == 1900 +# pragma warning(pop) +#endif +#endif + diff --git a/googlemock/test/gmock-cardinalities_test.cc b/googlemock/test/gmock-cardinalities_test.cc index 64815e5..132591b 100644 --- a/googlemock/test/gmock-cardinalities_test.cc +++ b/googlemock/test/gmock-cardinalities_test.cc @@ -26,8 +26,7 @@ // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -// -// Author: wan@google.com (Zhanyong Wan) + // Google Mock - a framework for writing C++ mock classes. // @@ -391,7 +390,7 @@ TEST(ExactlyTest, HasCorrectBounds) { EXPECT_EQ(3, c.ConservativeUpperBound()); } -// Tests that a user can make his own cardinality by implementing +// Tests that a user can make their own cardinality by implementing // CardinalityInterface and calling MakeCardinality(). class EvenCardinality : public CardinalityInterface { diff --git a/googlemock/test/gmock-generated-actions_test.cc b/googlemock/test/gmock-generated-actions_test.cc index 5ca5bc7..2d663a5 100644 --- a/googlemock/test/gmock-generated-actions_test.cc +++ b/googlemock/test/gmock-generated-actions_test.cc @@ -26,8 +26,7 @@ // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -// -// Author: wan@google.com (Zhanyong Wan) + // Google Mock - a framework for writing C++ mock classes. // @@ -46,10 +45,6 @@ namespace gmock_generated_actions_test { using ::std::plus; using ::std::string; -using testing::get; -using testing::make_tuple; -using testing::tuple; -using testing::tuple_element; using testing::_; using testing::Action; using testing::ActionInterface; @@ -81,12 +76,12 @@ bool Unary(int x) { return x < 0; } const char* Plus1(const char* s) { return s + 1; } -bool ByConstRef(const string& s) { return s == "Hi"; } +bool ByConstRef(const std::string& s) { return s == "Hi"; } const double g_double = 0; bool ReferencesGlobalDouble(const double& x) { return &x == &g_double; } -string ByNonConstRef(string& s) { return s += "+"; } // NOLINT +std::string ByNonConstRef(std::string& s) { return s += "+"; } // NOLINT struct UnaryFunctor { int operator()(bool x) { return x ? 1 : -1; } @@ -102,9 +97,9 @@ void VoidTernary(int, char, bool) { g_done = true; } int SumOf4(int a, int b, int c, int d) { return a + b + c + d; } -string Concat4(const char* s1, const char* s2, const char* s3, - const char* s4) { - return string(s1) + s2 + s3 + s4; +std::string Concat4(const char* s1, const char* s2, const char* s3, + const char* s4) { + return std::string(s1) + s2 + s3 + s4; } int SumOf5(int a, int b, int c, int d, int e) { return a + b + c + d + e; } @@ -115,9 +110,9 @@ struct SumOf5Functor { } }; -string Concat5(const char* s1, const char* s2, const char* s3, - const char* s4, const char* s5) { - return string(s1) + s2 + s3 + s4 + s5; +std::string Concat5(const char* s1, const char* s2, const char* s3, + const char* s4, const char* s5) { + return std::string(s1) + s2 + s3 + s4 + s5; } int SumOf6(int a, int b, int c, int d, int e, int f) { @@ -130,34 +125,34 @@ struct SumOf6Functor { } }; -string Concat6(const char* s1, const char* s2, const char* s3, - const char* s4, const char* s5, const char* s6) { - return string(s1) + s2 + s3 + s4 + s5 + s6; +std::string Concat6(const char* s1, const char* s2, const char* s3, + const char* s4, const char* s5, const char* s6) { + return std::string(s1) + s2 + s3 + s4 + s5 + s6; } -string Concat7(const char* s1, const char* s2, const char* s3, - const char* s4, const char* s5, const char* s6, - const char* s7) { - return string(s1) + s2 + s3 + s4 + s5 + s6 + s7; +std::string Concat7(const char* s1, const char* s2, const char* s3, + const char* s4, const char* s5, const char* s6, + const char* s7) { + return std::string(s1) + s2 + s3 + s4 + s5 + s6 + s7; } -string Concat8(const char* s1, const char* s2, const char* s3, - const char* s4, const char* s5, const char* s6, - const char* s7, const char* s8) { - return string(s1) + s2 + s3 + s4 + s5 + s6 + s7 + s8; +std::string Concat8(const char* s1, const char* s2, const char* s3, + const char* s4, const char* s5, const char* s6, + const char* s7, const char* s8) { + return std::string(s1) + s2 + s3 + s4 + s5 + s6 + s7 + s8; } -string Concat9(const char* s1, const char* s2, const char* s3, - const char* s4, const char* s5, const char* s6, - const char* s7, const char* s8, const char* s9) { - return string(s1) + s2 + s3 + s4 + s5 + s6 + s7 + s8 + s9; +std::string Concat9(const char* s1, const char* s2, const char* s3, + const char* s4, const char* s5, const char* s6, + const char* s7, const char* s8, const char* s9) { + return std::string(s1) + s2 + s3 + s4 + s5 + s6 + s7 + s8 + s9; } -string Concat10(const char* s1, const char* s2, const char* s3, - const char* s4, const char* s5, const char* s6, - const char* s7, const char* s8, const char* s9, - const char* s10) { - return string(s1) + s2 + s3 + s4 + s5 + s6 + s7 + s8 + s9 + s10; +std::string Concat10(const char* s1, const char* s2, const char* s3, + const char* s4, const char* s5, const char* s6, + const char* s7, const char* s8, const char* s9, + const char* s10) { + return std::string(s1) + s2 + s3 + s4 + s5 + s6 + s7 + s8 + s9 + s10; } // A helper that turns the type of a C-string literal from const @@ -169,85 +164,84 @@ inline const char* CharPtr(const char* s) { return s; } // Tests using InvokeArgument with a nullary function. TEST(InvokeArgumentTest, Function0) { Action<int(int, int(*)())> a = InvokeArgument<1>(); // NOLINT - EXPECT_EQ(1, a.Perform(make_tuple(2, &Nullary))); + EXPECT_EQ(1, a.Perform(std::make_tuple(2, &Nullary))); } // Tests using InvokeArgument with a unary function. TEST(InvokeArgumentTest, Functor1) { Action<int(UnaryFunctor)> a = InvokeArgument<0>(true); // NOLINT - EXPECT_EQ(1, a.Perform(make_tuple(UnaryFunctor()))); + EXPECT_EQ(1, a.Perform(std::make_tuple(UnaryFunctor()))); } // Tests using InvokeArgument with a 5-ary function. TEST(InvokeArgumentTest, Function5) { Action<int(int(*)(int, int, int, int, int))> a = // NOLINT InvokeArgument<0>(10000, 2000, 300, 40, 5); - EXPECT_EQ(12345, a.Perform(make_tuple(&SumOf5))); + EXPECT_EQ(12345, a.Perform(std::make_tuple(&SumOf5))); } // Tests using InvokeArgument with a 5-ary functor. TEST(InvokeArgumentTest, Functor5) { Action<int(SumOf5Functor)> a = // NOLINT InvokeArgument<0>(10000, 2000, 300, 40, 5); - EXPECT_EQ(12345, a.Perform(make_tuple(SumOf5Functor()))); + EXPECT_EQ(12345, a.Perform(std::make_tuple(SumOf5Functor()))); } // Tests using InvokeArgument with a 6-ary function. TEST(InvokeArgumentTest, Function6) { Action<int(int(*)(int, int, int, int, int, int))> a = // NOLINT InvokeArgument<0>(100000, 20000, 3000, 400, 50, 6); - EXPECT_EQ(123456, a.Perform(make_tuple(&SumOf6))); + EXPECT_EQ(123456, a.Perform(std::make_tuple(&SumOf6))); } // Tests using InvokeArgument with a 6-ary functor. TEST(InvokeArgumentTest, Functor6) { Action<int(SumOf6Functor)> a = // NOLINT InvokeArgument<0>(100000, 20000, 3000, 400, 50, 6); - EXPECT_EQ(123456, a.Perform(make_tuple(SumOf6Functor()))); + EXPECT_EQ(123456, a.Perform(std::make_tuple(SumOf6Functor()))); } // Tests using InvokeArgument with a 7-ary function. TEST(InvokeArgumentTest, Function7) { - Action<string(string(*)(const char*, const char*, const char*, - const char*, const char*, const char*, - const char*))> a = - InvokeArgument<0>("1", "2", "3", "4", "5", "6", "7"); - EXPECT_EQ("1234567", a.Perform(make_tuple(&Concat7))); + Action<std::string(std::string(*)(const char*, const char*, const char*, + const char*, const char*, const char*, + const char*))> + a = InvokeArgument<0>("1", "2", "3", "4", "5", "6", "7"); + EXPECT_EQ("1234567", a.Perform(std::make_tuple(&Concat7))); } // Tests using InvokeArgument with a 8-ary function. TEST(InvokeArgumentTest, Function8) { - Action<string(string(*)(const char*, const char*, const char*, - const char*, const char*, const char*, - const char*, const char*))> a = - InvokeArgument<0>("1", "2", "3", "4", "5", "6", "7", "8"); - EXPECT_EQ("12345678", a.Perform(make_tuple(&Concat8))); + Action<std::string(std::string(*)(const char*, const char*, const char*, + const char*, const char*, const char*, + const char*, const char*))> + a = InvokeArgument<0>("1", "2", "3", "4", "5", "6", "7", "8"); + EXPECT_EQ("12345678", a.Perform(std::make_tuple(&Concat8))); } // Tests using InvokeArgument with a 9-ary function. TEST(InvokeArgumentTest, Function9) { - Action<string(string(*)(const char*, const char*, const char*, - const char*, const char*, const char*, - const char*, const char*, const char*))> a = - InvokeArgument<0>("1", "2", "3", "4", "5", "6", "7", "8", "9"); - EXPECT_EQ("123456789", a.Perform(make_tuple(&Concat9))); + Action<std::string(std::string(*)(const char*, const char*, const char*, + const char*, const char*, const char*, + const char*, const char*, const char*))> + a = InvokeArgument<0>("1", "2", "3", "4", "5", "6", "7", "8", "9"); + EXPECT_EQ("123456789", a.Perform(std::make_tuple(&Concat9))); } // Tests using InvokeArgument with a 10-ary function. TEST(InvokeArgumentTest, Function10) { - Action<string(string(*)(const char*, const char*, const char*, - const char*, const char*, const char*, - const char*, const char*, const char*, - const char*))> a = - InvokeArgument<0>("1", "2", "3", "4", "5", "6", "7", "8", "9", "0"); - EXPECT_EQ("1234567890", a.Perform(make_tuple(&Concat10))); + Action<std::string(std::string(*)( + const char*, const char*, const char*, const char*, const char*, + const char*, const char*, const char*, const char*, const char*))> + a = InvokeArgument<0>("1", "2", "3", "4", "5", "6", "7", "8", "9", "0"); + EXPECT_EQ("1234567890", a.Perform(std::make_tuple(&Concat10))); } // Tests using InvokeArgument with a function that takes a pointer argument. TEST(InvokeArgumentTest, ByPointerFunction) { Action<const char*(const char*(*)(const char* input, short n))> a = // NOLINT InvokeArgument<0>(static_cast<const char*>("Hi"), Short(1)); - EXPECT_STREQ("i", a.Perform(make_tuple(&Binary))); + EXPECT_STREQ("i", a.Perform(std::make_tuple(&Binary))); } // Tests using InvokeArgument with a function that takes a const char* @@ -255,17 +249,17 @@ TEST(InvokeArgumentTest, ByPointerFunction) { TEST(InvokeArgumentTest, FunctionWithCStringLiteral) { Action<const char*(const char*(*)(const char* input, short n))> a = // NOLINT InvokeArgument<0>("Hi", Short(1)); - EXPECT_STREQ("i", a.Perform(make_tuple(&Binary))); + EXPECT_STREQ("i", a.Perform(std::make_tuple(&Binary))); } // Tests using InvokeArgument with a function that takes a const reference. TEST(InvokeArgumentTest, ByConstReferenceFunction) { - Action<bool(bool(*function)(const string& s))> a = // NOLINT - InvokeArgument<0>(string("Hi")); + Action<bool(bool (*function)(const std::string& s))> a = // NOLINT + InvokeArgument<0>(std::string("Hi")); // When action 'a' is constructed, it makes a copy of the temporary // string object passed to it, so it's OK to use 'a' later, when the // temporary object has already died. - EXPECT_TRUE(a.Perform(make_tuple(&ByConstRef))); + EXPECT_TRUE(a.Perform(std::make_tuple(&ByConstRef))); } // Tests using InvokeArgument with ByRef() and a function that takes a @@ -274,18 +268,18 @@ TEST(InvokeArgumentTest, ByExplicitConstReferenceFunction) { Action<bool(bool(*)(const double& x))> a = // NOLINT InvokeArgument<0>(ByRef(g_double)); // The above line calls ByRef() on a const value. - EXPECT_TRUE(a.Perform(make_tuple(&ReferencesGlobalDouble))); + EXPECT_TRUE(a.Perform(std::make_tuple(&ReferencesGlobalDouble))); double x = 0; a = InvokeArgument<0>(ByRef(x)); // This calls ByRef() on a non-const. - EXPECT_FALSE(a.Perform(make_tuple(&ReferencesGlobalDouble))); + EXPECT_FALSE(a.Perform(std::make_tuple(&ReferencesGlobalDouble))); } // Tests using WithArgs and with an action that takes 1 argument. TEST(WithArgsTest, OneArg) { Action<bool(double x, int n)> a = WithArgs<1>(Invoke(Unary)); // NOLINT - EXPECT_TRUE(a.Perform(make_tuple(1.5, -1))); - EXPECT_FALSE(a.Perform(make_tuple(1.5, 1))); + EXPECT_TRUE(a.Perform(std::make_tuple(1.5, -1))); + EXPECT_FALSE(a.Perform(std::make_tuple(1.5, 1))); } // Tests using WithArgs with an action that takes 2 arguments. @@ -293,105 +287,105 @@ TEST(WithArgsTest, TwoArgs) { Action<const char*(const char* s, double x, short n)> a = WithArgs<0, 2>(Invoke(Binary)); const char s[] = "Hello"; - EXPECT_EQ(s + 2, a.Perform(make_tuple(CharPtr(s), 0.5, Short(2)))); + EXPECT_EQ(s + 2, a.Perform(std::make_tuple(CharPtr(s), 0.5, Short(2)))); } // Tests using WithArgs with an action that takes 3 arguments. TEST(WithArgsTest, ThreeArgs) { Action<int(int, double, char, short)> a = // NOLINT WithArgs<0, 2, 3>(Invoke(Ternary)); - EXPECT_EQ(123, a.Perform(make_tuple(100, 6.5, Char(20), Short(3)))); + EXPECT_EQ(123, a.Perform(std::make_tuple(100, 6.5, Char(20), Short(3)))); } // Tests using WithArgs with an action that takes 4 arguments. TEST(WithArgsTest, FourArgs) { - Action<string(const char*, const char*, double, const char*, const char*)> a = - WithArgs<4, 3, 1, 0>(Invoke(Concat4)); - EXPECT_EQ("4310", a.Perform(make_tuple(CharPtr("0"), CharPtr("1"), 2.5, - CharPtr("3"), CharPtr("4")))); + Action<std::string(const char*, const char*, double, const char*, + const char*)> + a = WithArgs<4, 3, 1, 0>(Invoke(Concat4)); + EXPECT_EQ("4310", a.Perform(std::make_tuple(CharPtr("0"), CharPtr("1"), 2.5, + CharPtr("3"), CharPtr("4")))); } // Tests using WithArgs with an action that takes 5 arguments. TEST(WithArgsTest, FiveArgs) { - Action<string(const char*, const char*, const char*, - const char*, const char*)> a = - WithArgs<4, 3, 2, 1, 0>(Invoke(Concat5)); + Action<std::string(const char*, const char*, const char*, const char*, + const char*)> + a = WithArgs<4, 3, 2, 1, 0>(Invoke(Concat5)); EXPECT_EQ("43210", - a.Perform(make_tuple(CharPtr("0"), CharPtr("1"), CharPtr("2"), - CharPtr("3"), CharPtr("4")))); + a.Perform(std::make_tuple(CharPtr("0"), CharPtr("1"), CharPtr("2"), + CharPtr("3"), CharPtr("4")))); } // Tests using WithArgs with an action that takes 6 arguments. TEST(WithArgsTest, SixArgs) { - Action<string(const char*, const char*, const char*)> a = + Action<std::string(const char*, const char*, const char*)> a = WithArgs<0, 1, 2, 2, 1, 0>(Invoke(Concat6)); - EXPECT_EQ("012210", - a.Perform(make_tuple(CharPtr("0"), CharPtr("1"), CharPtr("2")))); + EXPECT_EQ("012210", a.Perform(std::make_tuple(CharPtr("0"), CharPtr("1"), + CharPtr("2")))); } // Tests using WithArgs with an action that takes 7 arguments. TEST(WithArgsTest, SevenArgs) { - Action<string(const char*, const char*, const char*, const char*)> a = + Action<std::string(const char*, const char*, const char*, const char*)> a = WithArgs<0, 1, 2, 3, 2, 1, 0>(Invoke(Concat7)); - EXPECT_EQ("0123210", - a.Perform(make_tuple(CharPtr("0"), CharPtr("1"), CharPtr("2"), - CharPtr("3")))); + EXPECT_EQ("0123210", a.Perform(std::make_tuple(CharPtr("0"), CharPtr("1"), + CharPtr("2"), CharPtr("3")))); } // Tests using WithArgs with an action that takes 8 arguments. TEST(WithArgsTest, EightArgs) { - Action<string(const char*, const char*, const char*, const char*)> a = + Action<std::string(const char*, const char*, const char*, const char*)> a = WithArgs<0, 1, 2, 3, 0, 1, 2, 3>(Invoke(Concat8)); - EXPECT_EQ("01230123", - a.Perform(make_tuple(CharPtr("0"), CharPtr("1"), CharPtr("2"), - CharPtr("3")))); + EXPECT_EQ("01230123", a.Perform(std::make_tuple(CharPtr("0"), CharPtr("1"), + CharPtr("2"), CharPtr("3")))); } // Tests using WithArgs with an action that takes 9 arguments. TEST(WithArgsTest, NineArgs) { - Action<string(const char*, const char*, const char*, const char*)> a = + Action<std::string(const char*, const char*, const char*, const char*)> a = WithArgs<0, 1, 2, 3, 1, 2, 3, 2, 3>(Invoke(Concat9)); EXPECT_EQ("012312323", - a.Perform(make_tuple(CharPtr("0"), CharPtr("1"), CharPtr("2"), - CharPtr("3")))); + a.Perform(std::make_tuple(CharPtr("0"), CharPtr("1"), CharPtr("2"), + CharPtr("3")))); } // Tests using WithArgs with an action that takes 10 arguments. TEST(WithArgsTest, TenArgs) { - Action<string(const char*, const char*, const char*, const char*)> a = + Action<std::string(const char*, const char*, const char*, const char*)> a = WithArgs<0, 1, 2, 3, 2, 1, 0, 1, 2, 3>(Invoke(Concat10)); EXPECT_EQ("0123210123", - a.Perform(make_tuple(CharPtr("0"), CharPtr("1"), CharPtr("2"), - CharPtr("3")))); + a.Perform(std::make_tuple(CharPtr("0"), CharPtr("1"), CharPtr("2"), + CharPtr("3")))); } // Tests using WithArgs with an action that is not Invoke(). class SubstractAction : public ActionInterface<int(int, int)> { // NOLINT public: - virtual int Perform(const tuple<int, int>& args) { - return get<0>(args) - get<1>(args); + virtual int Perform(const std::tuple<int, int>& args) { + return std::get<0>(args) - std::get<1>(args); } }; TEST(WithArgsTest, NonInvokeAction) { - Action<int(const string&, int, int)> a = // NOLINT + Action<int(const std::string&, int, int)> a = // NOLINT WithArgs<2, 1>(MakeAction(new SubstractAction)); - string s("hello"); - EXPECT_EQ(8, a.Perform(tuple<const string&, int, int>(s, 2, 10))); + std::tuple<std::string, int, int> dummy = + std::make_tuple(std::string("hi"), 2, 10); + EXPECT_EQ(8, a.Perform(dummy)); } // Tests using WithArgs to pass all original arguments in the original order. TEST(WithArgsTest, Identity) { Action<int(int x, char y, short z)> a = // NOLINT WithArgs<0, 1, 2>(Invoke(Ternary)); - EXPECT_EQ(123, a.Perform(make_tuple(100, Char(20), Short(3)))); + EXPECT_EQ(123, a.Perform(std::make_tuple(100, Char(20), Short(3)))); } // Tests using WithArgs with repeated arguments. TEST(WithArgsTest, RepeatedArguments) { Action<int(bool, int m, int n)> a = // NOLINT WithArgs<1, 1, 1, 1>(Invoke(SumOf4)); - EXPECT_EQ(4, a.Perform(make_tuple(false, 1, 10))); + EXPECT_EQ(4, a.Perform(std::make_tuple(false, 1, 10))); } // Tests using WithArgs with reversed argument order. @@ -399,21 +393,22 @@ TEST(WithArgsTest, ReversedArgumentOrder) { Action<const char*(short n, const char* input)> a = // NOLINT WithArgs<1, 0>(Invoke(Binary)); const char s[] = "Hello"; - EXPECT_EQ(s + 2, a.Perform(make_tuple(Short(2), CharPtr(s)))); + EXPECT_EQ(s + 2, a.Perform(std::make_tuple(Short(2), CharPtr(s)))); } // Tests using WithArgs with compatible, but not identical, argument types. TEST(WithArgsTest, ArgsOfCompatibleTypes) { Action<long(short x, char y, double z, char c)> a = // NOLINT WithArgs<0, 1, 3>(Invoke(Ternary)); - EXPECT_EQ(123, a.Perform(make_tuple(Short(100), Char(20), 5.6, Char(3)))); + EXPECT_EQ(123, + a.Perform(std::make_tuple(Short(100), Char(20), 5.6, Char(3)))); } // Tests using WithArgs with an action that returns void. TEST(WithArgsTest, VoidAction) { Action<void(double x, char c, int n)> a = WithArgs<2, 1>(Invoke(VoidBinary)); g_done = false; - a.Perform(make_tuple(1.5, 'a', 3)); + a.Perform(std::make_tuple(1.5, 'a', 3)); EXPECT_TRUE(g_done); } @@ -422,7 +417,7 @@ TEST(DoAllTest, TwoActions) { int n = 0; Action<int(int*)> a = DoAll(SetArgPointee<0>(1), // NOLINT Return(2)); - EXPECT_EQ(2, a.Perform(make_tuple(&n))); + EXPECT_EQ(2, a.Perform(std::make_tuple(&n))); EXPECT_EQ(1, n); } @@ -432,7 +427,7 @@ TEST(DoAllTest, ThreeActions) { Action<int(int*, int*)> a = DoAll(SetArgPointee<0>(1), // NOLINT SetArgPointee<1>(2), Return(3)); - EXPECT_EQ(3, a.Perform(make_tuple(&m, &n))); + EXPECT_EQ(3, a.Perform(std::make_tuple(&m, &n))); EXPECT_EQ(1, m); EXPECT_EQ(2, n); } @@ -446,7 +441,7 @@ TEST(DoAllTest, FourActions) { SetArgPointee<1>(2), SetArgPointee<2>('a'), Return(3)); - EXPECT_EQ(3, a.Perform(make_tuple(&m, &n, &ch))); + EXPECT_EQ(3, a.Perform(std::make_tuple(&m, &n, &ch))); EXPECT_EQ(1, m); EXPECT_EQ(2, n); EXPECT_EQ('a', ch); @@ -462,7 +457,7 @@ TEST(DoAllTest, FiveActions) { SetArgPointee<2>('a'), SetArgPointee<3>('b'), Return(3)); - EXPECT_EQ(3, action.Perform(make_tuple(&m, &n, &a, &b))); + EXPECT_EQ(3, action.Perform(std::make_tuple(&m, &n, &a, &b))); EXPECT_EQ(1, m); EXPECT_EQ(2, n); EXPECT_EQ('a', a); @@ -480,7 +475,7 @@ TEST(DoAllTest, SixActions) { SetArgPointee<3>('b'), SetArgPointee<4>('c'), Return(3)); - EXPECT_EQ(3, action.Perform(make_tuple(&m, &n, &a, &b, &c))); + EXPECT_EQ(3, action.Perform(std::make_tuple(&m, &n, &a, &b, &c))); EXPECT_EQ(1, m); EXPECT_EQ(2, n); EXPECT_EQ('a', a); @@ -500,7 +495,7 @@ TEST(DoAllTest, SevenActions) { SetArgPointee<4>('c'), SetArgPointee<5>('d'), Return(3)); - EXPECT_EQ(3, action.Perform(make_tuple(&m, &n, &a, &b, &c, &d))); + EXPECT_EQ(3, action.Perform(std::make_tuple(&m, &n, &a, &b, &c, &d))); EXPECT_EQ(1, m); EXPECT_EQ(2, n); EXPECT_EQ('a', a); @@ -523,7 +518,7 @@ TEST(DoAllTest, EightActions) { SetArgPointee<5>('d'), SetArgPointee<6>('e'), Return(3)); - EXPECT_EQ(3, action.Perform(make_tuple(&m, &n, &a, &b, &c, &d, &e))); + EXPECT_EQ(3, action.Perform(std::make_tuple(&m, &n, &a, &b, &c, &d, &e))); EXPECT_EQ(1, m); EXPECT_EQ(2, n); EXPECT_EQ('a', a); @@ -548,7 +543,7 @@ TEST(DoAllTest, NineActions) { SetArgPointee<6>('e'), SetArgPointee<7>('f'), Return(3)); - EXPECT_EQ(3, action.Perform(make_tuple(&m, &n, &a, &b, &c, &d, &e, &f))); + EXPECT_EQ(3, action.Perform(std::make_tuple(&m, &n, &a, &b, &c, &d, &e, &f))); EXPECT_EQ(1, m); EXPECT_EQ(2, n); EXPECT_EQ('a', a); @@ -576,7 +571,8 @@ TEST(DoAllTest, TenActions) { SetArgPointee<7>('f'), SetArgPointee<8>('g'), Return(3)); - EXPECT_EQ(3, action.Perform(make_tuple(&m, &n, &a, &b, &c, &d, &e, &f, &g))); + EXPECT_EQ( + 3, action.Perform(std::make_tuple(&m, &n, &a, &b, &c, &d, &e, &f, &g))); EXPECT_EQ(1, m); EXPECT_EQ(2, n); EXPECT_EQ('a', a); @@ -606,10 +602,10 @@ ACTION(Return5) { return 5; } TEST(ActionMacroTest, WorksWhenNotReferencingArguments) { Action<double()> a1 = Return5(); - EXPECT_DOUBLE_EQ(5, a1.Perform(make_tuple())); + EXPECT_DOUBLE_EQ(5, a1.Perform(std::make_tuple())); Action<int(double, bool)> a2 = Return5(); - EXPECT_EQ(5, a2.Perform(make_tuple(1, true))); + EXPECT_EQ(5, a2.Perform(std::make_tuple(1, true))); } // Tests that ACTION() can define an action that returns void. @@ -618,7 +614,7 @@ ACTION(IncrementArg1) { (*arg1)++; } TEST(ActionMacroTest, WorksWhenReturningVoid) { Action<void(int, int*)> a1 = IncrementArg1(); int n = 0; - a1.Perform(make_tuple(5, &n)); + a1.Perform(std::make_tuple(5, &n)); EXPECT_EQ(1, n); } @@ -633,22 +629,22 @@ ACTION(IncrementArg2) { TEST(ActionMacroTest, CanReferenceArgumentType) { Action<void(int, bool, int*)> a1 = IncrementArg2(); int n = 0; - a1.Perform(make_tuple(5, false, &n)); + a1.Perform(std::make_tuple(5, false, &n)); EXPECT_EQ(1, n); } // Tests that the body of ACTION() can reference the argument tuple // via args_type and args. ACTION(Sum2) { - StaticAssertTypeEq<tuple<int, char, int*>, args_type>(); + StaticAssertTypeEq<std::tuple<int, char, int*>, args_type>(); args_type args_copy = args; - return get<0>(args_copy) + get<1>(args_copy); + return std::get<0>(args_copy) + std::get<1>(args_copy); } TEST(ActionMacroTest, CanReferenceArgumentTuple) { Action<int(int, char, int*)> a1 = Sum2(); int dummy = 0; - EXPECT_EQ(11, a1.Perform(make_tuple(5, Char(6), &dummy))); + EXPECT_EQ(11, a1.Perform(std::make_tuple(5, Char(6), &dummy))); } // Tests that the body of ACTION() can reference the mock function @@ -663,8 +659,8 @@ ACTION(InvokeDummy) { TEST(ActionMacroTest, CanReferenceMockFunctionType) { Action<int(bool)> a1 = InvokeDummy(); - EXPECT_EQ(1, a1.Perform(make_tuple(true))); - EXPECT_EQ(1, a1.Perform(make_tuple(false))); + EXPECT_EQ(1, a1.Perform(std::make_tuple(true))); + EXPECT_EQ(1, a1.Perform(std::make_tuple(false))); } // Tests that the body of ACTION() can reference the mock function's @@ -677,8 +673,8 @@ ACTION(InvokeDummy2) { TEST(ActionMacroTest, CanReferenceMockFunctionReturnType) { Action<int(bool)> a1 = InvokeDummy2(); - EXPECT_EQ(1, a1.Perform(make_tuple(true))); - EXPECT_EQ(1, a1.Perform(make_tuple(false))); + EXPECT_EQ(1, a1.Perform(std::make_tuple(true))); + EXPECT_EQ(1, a1.Perform(std::make_tuple(false))); } // Tests that ACTION() works for arguments passed by const reference. @@ -690,7 +686,7 @@ ACTION(ReturnAddrOfConstBoolReferenceArg) { TEST(ActionMacroTest, WorksForConstReferenceArg) { Action<const bool*(int, const bool&)> a = ReturnAddrOfConstBoolReferenceArg(); const bool b = false; - EXPECT_EQ(&b, a.Perform(tuple<int, const bool&>(0, b))); + EXPECT_EQ(&b, a.Perform(std::tuple<int, const bool&>(0, b))); } // Tests that ACTION() works for arguments passed by non-const reference. @@ -702,7 +698,7 @@ ACTION(ReturnAddrOfIntReferenceArg) { TEST(ActionMacroTest, WorksForNonConstReferenceArg) { Action<int*(int&, bool, int)> a = ReturnAddrOfIntReferenceArg(); int n = 0; - EXPECT_EQ(&n, a.Perform(tuple<int&, bool, int>(n, true, 1))); + EXPECT_EQ(&n, a.Perform(std::tuple<int&, bool, int>(n, true, 1))); } // Tests that ACTION() can be used in a namespace. @@ -712,7 +708,7 @@ ACTION(Sum) { return arg0 + arg1; } TEST(ActionMacroTest, WorksInNamespace) { Action<int(int, int)> a1 = action_test::Sum(); - EXPECT_EQ(3, a1.Perform(make_tuple(1, 2))); + EXPECT_EQ(3, a1.Perform(std::make_tuple(1, 2))); } // Tests that the same ACTION definition works for mock functions with @@ -721,11 +717,11 @@ ACTION(PlusTwo) { return arg0 + 2; } TEST(ActionMacroTest, WorksForDifferentArgumentNumbers) { Action<int(int)> a1 = PlusTwo(); - EXPECT_EQ(4, a1.Perform(make_tuple(2))); + EXPECT_EQ(4, a1.Perform(std::make_tuple(2))); Action<double(float, void*)> a2 = PlusTwo(); int dummy; - EXPECT_DOUBLE_EQ(6, a2.Perform(make_tuple(4.0f, &dummy))); + EXPECT_DOUBLE_EQ(6, a2.Perform(std::make_tuple(4.0f, &dummy))); } // Tests that ACTION_P can define a parameterized action. @@ -733,7 +729,7 @@ ACTION_P(Plus, n) { return arg0 + n; } TEST(ActionPMacroTest, DefinesParameterizedAction) { Action<int(int m, bool t)> a1 = Plus(9); - EXPECT_EQ(10, a1.Perform(make_tuple(1, true))); + EXPECT_EQ(10, a1.Perform(std::make_tuple(1, true))); } // Tests that the body of ACTION_P can reference the argument types @@ -746,7 +742,7 @@ ACTION_P(TypedPlus, n) { TEST(ActionPMacroTest, CanReferenceArgumentAndParameterTypes) { Action<int(char m, bool t)> a1 = TypedPlus(9); - EXPECT_EQ(10, a1.Perform(make_tuple(Char(1), true))); + EXPECT_EQ(10, a1.Perform(std::make_tuple(Char(1), true))); } // Tests that a parameterized action can be used in any mock function @@ -754,7 +750,8 @@ TEST(ActionPMacroTest, CanReferenceArgumentAndParameterTypes) { TEST(ActionPMacroTest, WorksInCompatibleMockFunction) { Action<std::string(const std::string& s)> a1 = Plus("tail"); const std::string re = "re"; - EXPECT_EQ("retail", a1.Perform(tuple<const std::string&>(re))); + std::tuple<const std::string> dummy = std::make_tuple(re); + EXPECT_EQ("retail", a1.Perform(dummy)); } // Tests that we can use ACTION*() to define actions overloaded on the @@ -774,16 +771,16 @@ TEST(ActionMacroTest, CanDefineOverloadedActions) { typedef Action<const char*(bool, const char*)> MyAction; const MyAction a1 = OverloadedAction(); - EXPECT_STREQ("hello", a1.Perform(make_tuple(false, CharPtr("world")))); - EXPECT_STREQ("world", a1.Perform(make_tuple(true, CharPtr("world")))); + EXPECT_STREQ("hello", a1.Perform(std::make_tuple(false, CharPtr("world")))); + EXPECT_STREQ("world", a1.Perform(std::make_tuple(true, CharPtr("world")))); const MyAction a2 = OverloadedAction("hi"); - EXPECT_STREQ("hi", a2.Perform(make_tuple(false, CharPtr("world")))); - EXPECT_STREQ("world", a2.Perform(make_tuple(true, CharPtr("world")))); + EXPECT_STREQ("hi", a2.Perform(std::make_tuple(false, CharPtr("world")))); + EXPECT_STREQ("world", a2.Perform(std::make_tuple(true, CharPtr("world")))); const MyAction a3 = OverloadedAction("hi", "you"); - EXPECT_STREQ("hi", a3.Perform(make_tuple(true, CharPtr("world")))); - EXPECT_STREQ("you", a3.Perform(make_tuple(false, CharPtr("world")))); + EXPECT_STREQ("hi", a3.Perform(std::make_tuple(true, CharPtr("world")))); + EXPECT_STREQ("you", a3.Perform(std::make_tuple(false, CharPtr("world")))); } // Tests ACTION_Pn where n >= 3. @@ -792,25 +789,26 @@ ACTION_P3(Plus, m, n, k) { return arg0 + m + n + k; } TEST(ActionPnMacroTest, WorksFor3Parameters) { Action<double(int m, bool t)> a1 = Plus(100, 20, 3.4); - EXPECT_DOUBLE_EQ(3123.4, a1.Perform(make_tuple(3000, true))); + EXPECT_DOUBLE_EQ(3123.4, a1.Perform(std::make_tuple(3000, true))); Action<std::string(const std::string& s)> a2 = Plus("tail", "-", ">"); const std::string re = "re"; - EXPECT_EQ("retail->", a2.Perform(tuple<const std::string&>(re))); + std::tuple<const std::string> dummy = std::make_tuple(re); + EXPECT_EQ("retail->", a2.Perform(dummy)); } ACTION_P4(Plus, p0, p1, p2, p3) { return arg0 + p0 + p1 + p2 + p3; } TEST(ActionPnMacroTest, WorksFor4Parameters) { Action<int(int)> a1 = Plus(1, 2, 3, 4); - EXPECT_EQ(10 + 1 + 2 + 3 + 4, a1.Perform(make_tuple(10))); + EXPECT_EQ(10 + 1 + 2 + 3 + 4, a1.Perform(std::make_tuple(10))); } ACTION_P5(Plus, p0, p1, p2, p3, p4) { return arg0 + p0 + p1 + p2 + p3 + p4; } TEST(ActionPnMacroTest, WorksFor5Parameters) { Action<int(int)> a1 = Plus(1, 2, 3, 4, 5); - EXPECT_EQ(10 + 1 + 2 + 3 + 4 + 5, a1.Perform(make_tuple(10))); + EXPECT_EQ(10 + 1 + 2 + 3 + 4 + 5, a1.Perform(std::make_tuple(10))); } ACTION_P6(Plus, p0, p1, p2, p3, p4, p5) { @@ -819,7 +817,7 @@ ACTION_P6(Plus, p0, p1, p2, p3, p4, p5) { TEST(ActionPnMacroTest, WorksFor6Parameters) { Action<int(int)> a1 = Plus(1, 2, 3, 4, 5, 6); - EXPECT_EQ(10 + 1 + 2 + 3 + 4 + 5 + 6, a1.Perform(make_tuple(10))); + EXPECT_EQ(10 + 1 + 2 + 3 + 4 + 5 + 6, a1.Perform(std::make_tuple(10))); } ACTION_P7(Plus, p0, p1, p2, p3, p4, p5, p6) { @@ -828,7 +826,7 @@ ACTION_P7(Plus, p0, p1, p2, p3, p4, p5, p6) { TEST(ActionPnMacroTest, WorksFor7Parameters) { Action<int(int)> a1 = Plus(1, 2, 3, 4, 5, 6, 7); - EXPECT_EQ(10 + 1 + 2 + 3 + 4 + 5 + 6 + 7, a1.Perform(make_tuple(10))); + EXPECT_EQ(10 + 1 + 2 + 3 + 4 + 5 + 6 + 7, a1.Perform(std::make_tuple(10))); } ACTION_P8(Plus, p0, p1, p2, p3, p4, p5, p6, p7) { @@ -837,7 +835,8 @@ ACTION_P8(Plus, p0, p1, p2, p3, p4, p5, p6, p7) { TEST(ActionPnMacroTest, WorksFor8Parameters) { Action<int(int)> a1 = Plus(1, 2, 3, 4, 5, 6, 7, 8); - EXPECT_EQ(10 + 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8, a1.Perform(make_tuple(10))); + EXPECT_EQ(10 + 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8, + a1.Perform(std::make_tuple(10))); } ACTION_P9(Plus, p0, p1, p2, p3, p4, p5, p6, p7, p8) { @@ -846,7 +845,8 @@ ACTION_P9(Plus, p0, p1, p2, p3, p4, p5, p6, p7, p8) { TEST(ActionPnMacroTest, WorksFor9Parameters) { Action<int(int)> a1 = Plus(1, 2, 3, 4, 5, 6, 7, 8, 9); - EXPECT_EQ(10 + 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9, a1.Perform(make_tuple(10))); + EXPECT_EQ(10 + 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9, + a1.Perform(std::make_tuple(10))); } ACTION_P10(Plus, p0, p1, p2, p3, p4, p5, p6, p7, p8, last_param) { @@ -858,7 +858,7 @@ ACTION_P10(Plus, p0, p1, p2, p3, p4, p5, p6, p7, p8, last_param) { TEST(ActionPnMacroTest, WorksFor10Parameters) { Action<int(int)> a1 = Plus(1, 2, 3, 4, 5, 6, 7, 8, 9, 10); EXPECT_EQ(10 + 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10, - a1.Perform(make_tuple(10))); + a1.Perform(std::make_tuple(10))); } // Tests that the action body can promote the parameter types. @@ -875,8 +875,8 @@ TEST(ActionPnMacroTest, SimpleTypePromotion) { PadArgument(std::string("foo"), 'r'); Action<std::string(const char*)> promo = PadArgument("foo", static_cast<int>('r')); - EXPECT_EQ("foobar", no_promo.Perform(make_tuple(CharPtr("ba")))); - EXPECT_EQ("foobar", promo.Perform(make_tuple(CharPtr("ba")))); + EXPECT_EQ("foobar", no_promo.Perform(std::make_tuple(CharPtr("ba")))); + EXPECT_EQ("foobar", promo.Perform(std::make_tuple(CharPtr("ba")))); } // Tests that we can partially restrict parameter types using a @@ -925,10 +925,10 @@ Concat(T1 a, int b, T2 c) { TEST(ActionPnMacroTest, CanPartiallyRestrictParameterTypes) { Action<const std::string()> a1 = Concat("Hello", "1", 2); - EXPECT_EQ("Hello12", a1.Perform(make_tuple())); + EXPECT_EQ("Hello12", a1.Perform(std::make_tuple())); a1 = Concat(1, 2, 3); - EXPECT_EQ("123", a1.Perform(make_tuple())); + EXPECT_EQ("123", a1.Perform(std::make_tuple())); } // Verifies the type of an ACTION*. @@ -986,7 +986,7 @@ ACTION_P10(Plus10, a0, a1, a2, a3, a4, a5, a6, a7, a8, a9) { TEST(ActionPnMacroTest, CanExplicitlyInstantiateWithReferenceTypes) { int x = 1, y = 2, z = 3; - const tuple<> empty = make_tuple(); + const std::tuple<> empty = std::make_tuple(); Action<int()> a = Plus1<int&>(x); EXPECT_EQ(1, a.Perform(empty)); @@ -1013,7 +1013,7 @@ class NullaryConstructorClass { // Tests using ReturnNew() with a nullary constructor. TEST(ReturnNewTest, NoArgs) { Action<NullaryConstructorClass*()> a = ReturnNew<NullaryConstructorClass>(); - NullaryConstructorClass* c = a.Perform(make_tuple()); + NullaryConstructorClass* c = a.Perform(std::make_tuple()); EXPECT_EQ(123, c->value_); delete c; } @@ -1027,7 +1027,7 @@ class UnaryConstructorClass { // Tests using ReturnNew() with a unary constructor. TEST(ReturnNewTest, Unary) { Action<UnaryConstructorClass*()> a = ReturnNew<UnaryConstructorClass>(4000); - UnaryConstructorClass* c = a.Perform(make_tuple()); + UnaryConstructorClass* c = a.Perform(std::make_tuple()); EXPECT_EQ(4000, c->value_); delete c; } @@ -1035,7 +1035,7 @@ TEST(ReturnNewTest, Unary) { TEST(ReturnNewTest, UnaryWorksWhenMockMethodHasArgs) { Action<UnaryConstructorClass*(bool, int)> a = ReturnNew<UnaryConstructorClass>(4000); - UnaryConstructorClass* c = a.Perform(make_tuple(false, 5)); + UnaryConstructorClass* c = a.Perform(std::make_tuple(false, 5)); EXPECT_EQ(4000, c->value_); delete c; } @@ -1043,7 +1043,7 @@ TEST(ReturnNewTest, UnaryWorksWhenMockMethodHasArgs) { TEST(ReturnNewTest, UnaryWorksWhenMockMethodReturnsPointerToConst) { Action<const UnaryConstructorClass*()> a = ReturnNew<UnaryConstructorClass>(4000); - const UnaryConstructorClass* c = a.Perform(make_tuple()); + const UnaryConstructorClass* c = a.Perform(std::make_tuple()); EXPECT_EQ(4000, c->value_); delete c; } @@ -1063,7 +1063,7 @@ TEST(ReturnNewTest, ConstructorThatTakes10Arguments) { ReturnNew<TenArgConstructorClass>(1000000000, 200000000, 30000000, 4000000, 500000, 60000, 7000, 800, 90, 0); - TenArgConstructorClass* c = a.Perform(make_tuple()); + TenArgConstructorClass* c = a.Perform(std::make_tuple()); EXPECT_EQ(1234567890, c->value_); delete c; } @@ -1077,7 +1077,7 @@ ACTION_TEMPLATE(CreateNew, TEST(ActionTemplateTest, WorksWithoutValueParam) { const Action<int*()> a = CreateNew<int>(); - int* p = a.Perform(make_tuple()); + int* p = a.Perform(std::make_tuple()); delete p; } @@ -1090,7 +1090,7 @@ ACTION_TEMPLATE(CreateNew, TEST(ActionTemplateTest, WorksWithValueParams) { const Action<int*()> a = CreateNew<int>(42); - int* p = a.Perform(make_tuple()); + int* p = a.Perform(std::make_tuple()); EXPECT_EQ(42, *p); delete p; } @@ -1099,7 +1099,7 @@ TEST(ActionTemplateTest, WorksWithValueParams) { ACTION_TEMPLATE(MyDeleteArg, HAS_1_TEMPLATE_PARAMS(int, k), AND_0_VALUE_PARAMS()) { - delete get<k>(args); + delete std::get<k>(args); } // Resets a bool variable in the destructor. @@ -1116,7 +1116,7 @@ TEST(ActionTemplateTest, WorksForIntegralTemplateParams) { int n = 0; bool b = true; BoolResetter* resetter = new BoolResetter(&b); - a.Perform(make_tuple(&n, resetter)); + a.Perform(std::make_tuple(&n, resetter)); EXPECT_FALSE(b); // Verifies that resetter is deleted. } @@ -1131,7 +1131,7 @@ ACTION_TEMPLATE(ReturnSmartPointer, TEST(ActionTemplateTest, WorksForTemplateTemplateParameters) { using ::testing::internal::linked_ptr; const Action<linked_ptr<int>()> a = ReturnSmartPointer<linked_ptr>(42); - linked_ptr<int> p = a.Perform(make_tuple()); + linked_ptr<int> p = a.Perform(std::make_tuple()); EXPECT_EQ(42, *p); } @@ -1166,7 +1166,7 @@ TEST(ActionTemplateTest, WorksFor10TemplateParameters) { true, 6, char, unsigned, int> Giant; const Action<Giant()> a = ReturnGiant< int, bool, double, 5, true, 6, char, unsigned, int, linked_ptr>(42); - Giant giant = a.Perform(make_tuple()); + Giant giant = a.Perform(std::make_tuple()); EXPECT_EQ(42, giant.value); } @@ -1179,7 +1179,7 @@ ACTION_TEMPLATE(ReturnSum, TEST(ActionTemplateTest, WorksFor10ValueParameters) { const Action<int()> a = ReturnSum<int>(1, 2, 3, 4, 5, 6, 7, 8, 9, 10); - EXPECT_EQ(55, a.Perform(make_tuple())); + EXPECT_EQ(55, a.Perform(std::make_tuple())); } // Tests that ACTION_TEMPLATE and ACTION/ACTION_P* can be overloaded @@ -1213,11 +1213,11 @@ TEST(ActionTemplateTest, CanBeOverloadedOnNumberOfValueParameters) { const Action<int()> a2 = ReturnSum<int>(1, 2); const Action<int()> a3 = ReturnSum<int>(1, 2, 3); const Action<int()> a4 = ReturnSum<int, 10000>(2000, 300, 40, 5); - EXPECT_EQ(0, a0.Perform(make_tuple())); - EXPECT_EQ(1, a1.Perform(make_tuple())); - EXPECT_EQ(3, a2.Perform(make_tuple())); - EXPECT_EQ(6, a3.Perform(make_tuple())); - EXPECT_EQ(12345, a4.Perform(make_tuple())); + EXPECT_EQ(0, a0.Perform(std::make_tuple())); + EXPECT_EQ(1, a1.Perform(std::make_tuple())); + EXPECT_EQ(3, a2.Perform(std::make_tuple())); + EXPECT_EQ(6, a3.Perform(std::make_tuple())); + EXPECT_EQ(12345, a4.Perform(std::make_tuple())); } #ifdef _MSC_VER diff --git a/googlemock/test/gmock-generated-function-mockers_test.cc b/googlemock/test/gmock-generated-function-mockers_test.cc index a86a613..820a2b6 100644 --- a/googlemock/test/gmock-generated-function-mockers_test.cc +++ b/googlemock/test/gmock-generated-function-mockers_test.cc @@ -26,8 +26,7 @@ // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -// -// Author: wan@google.com (Zhanyong Wan) + // Google Mock - a framework for writing C++ mock classes. // @@ -57,7 +56,6 @@ namespace testing { namespace gmock_generated_function_mockers_test { -using testing::internal::string; using testing::_; using testing::A; using testing::An; @@ -82,11 +80,11 @@ class FooInterface { virtual bool Unary(int x) = 0; virtual long Binary(short x, int y) = 0; // NOLINT virtual int Decimal(bool b, char c, short d, int e, long f, // NOLINT - float g, double h, unsigned i, char* j, const string& k) - = 0; + float g, double h, unsigned i, char* j, + const std::string& k) = 0; virtual bool TakesNonConstReference(int& n) = 0; // NOLINT - virtual string TakesConstReference(const int& n) = 0; + virtual std::string TakesConstReference(const int& n) = 0; #ifdef GMOCK_ALLOWS_CONST_PARAM_FUNCTIONS virtual bool TakesConst(const int x) = 0; #endif // GMOCK_ALLOWS_CONST_PARAM_FUNCTIONS @@ -101,13 +99,14 @@ class FooInterface { virtual char OverloadedOnConstness() const = 0; virtual int TypeWithHole(int (*func)()) = 0; - virtual int TypeWithComma(const std::map<int, string>& a_map) = 0; + virtual int TypeWithComma(const std::map<int, std::string>& a_map) = 0; #if GTEST_OS_WINDOWS STDMETHOD_(int, CTNullary)() = 0; STDMETHOD_(bool, CTUnary)(int x) = 0; - STDMETHOD_(int, CTDecimal)(bool b, char c, short d, int e, long f, // NOLINT - float g, double h, unsigned i, char* j, const string& k) = 0; + STDMETHOD_(int, CTDecimal) + (bool b, char c, short d, int e, long f, // NOLINT + float g, double h, unsigned i, char* j, const std::string& k) = 0; STDMETHOD_(char, CTConst)(int x) const = 0; #endif // GTEST_OS_WINDOWS }; @@ -133,19 +132,19 @@ class MockFoo : public FooInterface { MOCK_METHOD1(Unary, bool(int)); // NOLINT MOCK_METHOD2(Binary, long(short, int)); // NOLINT MOCK_METHOD10(Decimal, int(bool, char, short, int, long, float, // NOLINT - double, unsigned, char*, const string& str)); + double, unsigned, char*, const std::string& str)); MOCK_METHOD1(TakesNonConstReference, bool(int&)); // NOLINT - MOCK_METHOD1(TakesConstReference, string(const int&)); + MOCK_METHOD1(TakesConstReference, std::string(const int&)); #ifdef GMOCK_ALLOWS_CONST_PARAM_FUNCTIONS MOCK_METHOD1(TakesConst, bool(const int)); // NOLINT #endif // Tests that the function return type can contain unprotected comma. - MOCK_METHOD0(ReturnTypeWithComma, std::map<int, string>()); + MOCK_METHOD0(ReturnTypeWithComma, std::map<int, std::string>()); MOCK_CONST_METHOD1(ReturnTypeWithComma, - std::map<int, string>(int)); // NOLINT + std::map<int, std::string>(int)); // NOLINT MOCK_METHOD0(OverloadedOnArgumentNumber, int()); // NOLINT MOCK_METHOD1(OverloadedOnArgumentNumber, int(int)); // NOLINT @@ -157,19 +156,21 @@ class MockFoo : public FooInterface { MOCK_CONST_METHOD0(OverloadedOnConstness, char()); // NOLINT MOCK_METHOD1(TypeWithHole, int(int (*)())); // NOLINT - MOCK_METHOD1(TypeWithComma, int(const std::map<int, string>&)); // NOLINT + MOCK_METHOD1(TypeWithComma, + int(const std::map<int, std::string>&)); // NOLINT #if GTEST_OS_WINDOWS MOCK_METHOD0_WITH_CALLTYPE(STDMETHODCALLTYPE, CTNullary, int()); MOCK_METHOD1_WITH_CALLTYPE(STDMETHODCALLTYPE, CTUnary, bool(int)); - MOCK_METHOD10_WITH_CALLTYPE(STDMETHODCALLTYPE, CTDecimal, int(bool b, char c, - short d, int e, long f, float g, double h, unsigned i, char* j, - const string& k)); + MOCK_METHOD10_WITH_CALLTYPE(STDMETHODCALLTYPE, CTDecimal, + int(bool b, char c, short d, int e, long f, + float g, double h, unsigned i, char* j, + const std::string& k)); MOCK_CONST_METHOD1_WITH_CALLTYPE(STDMETHODCALLTYPE, CTConst, char(int)); // Tests that the function return type can contain unprotected comma. MOCK_METHOD0_WITH_CALLTYPE(STDMETHODCALLTYPE, CTReturnTypeWithComma, - std::map<int, string>()); + std::map<int, std::string>()); #endif // GTEST_OS_WINDOWS private: @@ -227,7 +228,7 @@ TEST_F(FunctionMockerTest, MocksDecimalFunction) { Lt(100), 5U, NULL, "hi")) .WillOnce(Return(5)); - EXPECT_EQ(5, foo_->Decimal(true, 'a', 0, 0, 1, 0, 0, 5, NULL, "hi")); + EXPECT_EQ(5, foo_->Decimal(true, 'a', 0, 0, 1, 0, 0, 5, nullptr, "hi")); } // Tests mocking a function that takes a non-const reference. @@ -291,7 +292,7 @@ TEST_F(FunctionMockerTest, MocksFunctionsOverloadedOnConstnessOfThis) { } TEST_F(FunctionMockerTest, MocksReturnTypeWithComma) { - const std::map<int, string> a_map; + const std::map<int, std::string> a_map; EXPECT_CALL(mock_foo_, ReturnTypeWithComma()) .WillOnce(Return(a_map)); EXPECT_CALL(mock_foo_, ReturnTypeWithComma(42)) @@ -341,7 +342,7 @@ TEST_F(FunctionMockerTest, MocksFunctionsConstFunctionWithCallType) { } TEST_F(FunctionMockerTest, MocksReturnTypeWithCommaAndCallType) { - const std::map<int, string> a_map; + const std::map<int, std::string> a_map; EXPECT_CALL(mock_foo_, CTReturnTypeWithComma()) .WillOnce(Return(a_map)); @@ -616,7 +617,41 @@ TEST(MockFunctionTest, AsStdFunctionReturnsReference) { value = 2; EXPECT_EQ(2, ref); } + +TEST(MockFunctionTest, AsStdFunctionWithReferenceParameter) { + MockFunction<int(int &)> foo; + auto call = [](const std::function<int(int& )> &f, int &i) { + return f(i); + }; + int i = 42; + EXPECT_CALL(foo, Call(i)).WillOnce(Return(-1)); + EXPECT_EQ(-1, call(foo.AsStdFunction(), i)); +} + #endif // GTEST_HAS_STD_FUNCTION_ +struct MockMethodSizes0 { + MOCK_METHOD0(func, void()); +}; +struct MockMethodSizes1 { + MOCK_METHOD1(func, void(int)); +}; +struct MockMethodSizes2 { + MOCK_METHOD2(func, void(int, int)); +}; +struct MockMethodSizes3 { + MOCK_METHOD3(func, void(int, int, int)); +}; +struct MockMethodSizes4 { + MOCK_METHOD4(func, void(int, int, int, int)); +}; + +TEST(MockFunctionTest, MockMethodSizeOverhead) { + EXPECT_EQ(sizeof(MockMethodSizes0), sizeof(MockMethodSizes1)); + EXPECT_EQ(sizeof(MockMethodSizes0), sizeof(MockMethodSizes2)); + EXPECT_EQ(sizeof(MockMethodSizes0), sizeof(MockMethodSizes3)); + EXPECT_EQ(sizeof(MockMethodSizes0), sizeof(MockMethodSizes4)); +} + } // namespace gmock_generated_function_mockers_test } // namespace testing diff --git a/googlemock/test/gmock-generated-internal-utils_test.cc b/googlemock/test/gmock-generated-internal-utils_test.cc index e0a535a..965cbaa 100644 --- a/googlemock/test/gmock-generated-internal-utils_test.cc +++ b/googlemock/test/gmock-generated-internal-utils_test.cc @@ -26,8 +26,7 @@ // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -// -// Author: wan@google.com (Zhanyong Wan) + // Google Mock - a framework for writing C++ mock classes. // @@ -39,7 +38,6 @@ namespace { -using ::testing::tuple; using ::testing::Matcher; using ::testing::internal::CompileAssertTypesEqual; using ::testing::internal::MatcherTuple; @@ -49,24 +47,24 @@ using ::testing::internal::IgnoredValue; // Tests the MatcherTuple template struct. TEST(MatcherTupleTest, ForSize0) { - CompileAssertTypesEqual<tuple<>, MatcherTuple<tuple<> >::type>(); + CompileAssertTypesEqual<std::tuple<>, MatcherTuple<std::tuple<> >::type>(); } TEST(MatcherTupleTest, ForSize1) { - CompileAssertTypesEqual<tuple<Matcher<int> >, - MatcherTuple<tuple<int> >::type>(); + CompileAssertTypesEqual<std::tuple<Matcher<int> >, + MatcherTuple<std::tuple<int> >::type>(); } TEST(MatcherTupleTest, ForSize2) { - CompileAssertTypesEqual<tuple<Matcher<int>, Matcher<char> >, - MatcherTuple<tuple<int, char> >::type>(); + CompileAssertTypesEqual<std::tuple<Matcher<int>, Matcher<char> >, + MatcherTuple<std::tuple<int, char> >::type>(); } TEST(MatcherTupleTest, ForSize5) { - CompileAssertTypesEqual<tuple<Matcher<int>, Matcher<char>, Matcher<bool>, - Matcher<double>, Matcher<char*> >, - MatcherTuple<tuple<int, char, bool, double, char*> - >::type>(); + CompileAssertTypesEqual< + std::tuple<Matcher<int>, Matcher<char>, Matcher<bool>, Matcher<double>, + Matcher<char*> >, + MatcherTuple<std::tuple<int, char, bool, double, char*> >::type>(); } // Tests the Function template struct. @@ -74,8 +72,8 @@ TEST(MatcherTupleTest, ForSize5) { TEST(FunctionTest, Nullary) { typedef Function<int()> F; // NOLINT CompileAssertTypesEqual<int, F::Result>(); - CompileAssertTypesEqual<tuple<>, F::ArgumentTuple>(); - CompileAssertTypesEqual<tuple<>, F::ArgumentMatcherTuple>(); + CompileAssertTypesEqual<std::tuple<>, F::ArgumentTuple>(); + CompileAssertTypesEqual<std::tuple<>, F::ArgumentMatcherTuple>(); CompileAssertTypesEqual<void(), F::MakeResultVoid>(); CompileAssertTypesEqual<IgnoredValue(), F::MakeResultIgnoredValue>(); } @@ -84,8 +82,9 @@ TEST(FunctionTest, Unary) { typedef Function<int(bool)> F; // NOLINT CompileAssertTypesEqual<int, F::Result>(); CompileAssertTypesEqual<bool, F::Argument1>(); - CompileAssertTypesEqual<tuple<bool>, F::ArgumentTuple>(); - CompileAssertTypesEqual<tuple<Matcher<bool> >, F::ArgumentMatcherTuple>(); + CompileAssertTypesEqual<std::tuple<bool>, F::ArgumentTuple>(); + CompileAssertTypesEqual<std::tuple<Matcher<bool> >, + F::ArgumentMatcherTuple>(); CompileAssertTypesEqual<void(bool), F::MakeResultVoid>(); // NOLINT CompileAssertTypesEqual<IgnoredValue(bool), // NOLINT F::MakeResultIgnoredValue>(); @@ -96,9 +95,11 @@ TEST(FunctionTest, Binary) { CompileAssertTypesEqual<int, F::Result>(); CompileAssertTypesEqual<bool, F::Argument1>(); CompileAssertTypesEqual<const long&, F::Argument2>(); // NOLINT - CompileAssertTypesEqual<tuple<bool, const long&>, F::ArgumentTuple>(); // NOLINT - CompileAssertTypesEqual<tuple<Matcher<bool>, Matcher<const long&> >, // NOLINT - F::ArgumentMatcherTuple>(); + CompileAssertTypesEqual<std::tuple<bool, const long&>, // NOLINT + F::ArgumentTuple>(); + CompileAssertTypesEqual< + std::tuple<Matcher<bool>, Matcher<const long&> >, // NOLINT + F::ArgumentMatcherTuple>(); CompileAssertTypesEqual<void(bool, const long&), F::MakeResultVoid>(); // NOLINT CompileAssertTypesEqual<IgnoredValue(bool, const long&), // NOLINT F::MakeResultIgnoredValue>(); @@ -112,11 +113,13 @@ TEST(FunctionTest, LongArgumentList) { CompileAssertTypesEqual<char*, F::Argument3>(); CompileAssertTypesEqual<int&, F::Argument4>(); CompileAssertTypesEqual<const long&, F::Argument5>(); // NOLINT - CompileAssertTypesEqual<tuple<bool, int, char*, int&, const long&>, // NOLINT - F::ArgumentTuple>(); - CompileAssertTypesEqual<tuple<Matcher<bool>, Matcher<int>, Matcher<char*>, - Matcher<int&>, Matcher<const long&> >, // NOLINT - F::ArgumentMatcherTuple>(); + CompileAssertTypesEqual< + std::tuple<bool, int, char*, int&, const long&>, // NOLINT + F::ArgumentTuple>(); + CompileAssertTypesEqual< + std::tuple<Matcher<bool>, Matcher<int>, Matcher<char*>, Matcher<int&>, + Matcher<const long&> >, // NOLINT + F::ArgumentMatcherTuple>(); CompileAssertTypesEqual<void(bool, int, char*, int&, const long&), // NOLINT F::MakeResultVoid>(); CompileAssertTypesEqual< diff --git a/googlemock/test/gmock-generated-matchers_test.cc b/googlemock/test/gmock-generated-matchers_test.cc index 0e9f77f..fdbfb54 100644 --- a/googlemock/test/gmock-generated-matchers_test.cc +++ b/googlemock/test/gmock-generated-matchers_test.cc @@ -31,10 +31,19 @@ // // This file tests the built-in matchers generated by a script. +// Silence warning C4244: 'initializing': conversion from 'int' to 'short', +// possible loss of data and C4100, unreferenced local parameter +#ifdef _MSC_VER +# pragma warning(push) +# pragma warning(disable:4244) +# pragma warning(disable:4100) +#endif + #include "gmock/gmock-generated-matchers.h" #include <list> #include <map> +#include <memory> #include <set> #include <sstream> #include <string> @@ -53,10 +62,9 @@ using std::pair; using std::set; using std::stringstream; using std::vector; -using testing::get; -using testing::make_tuple; -using testing::tuple; using testing::_; +using testing::AllOf; +using testing::AnyOf; using testing::Args; using testing::Contains; using testing::ElementsAre; @@ -79,11 +87,10 @@ using testing::StaticAssertTypeEq; using testing::StrEq; using testing::Value; using testing::internal::ElementsAreArrayMatcher; -using testing::internal::string; // Returns the description of the given matcher. template <typename T> -string Describe(const Matcher<T>& m) { +std::string Describe(const Matcher<T>& m) { stringstream ss; m.DescribeTo(&ss); return ss.str(); @@ -91,7 +98,7 @@ string Describe(const Matcher<T>& m) { // Returns the description of the negation of the given matcher. template <typename T> -string DescribeNegation(const Matcher<T>& m) { +std::string DescribeNegation(const Matcher<T>& m) { stringstream ss; m.DescribeNegationTo(&ss); return ss.str(); @@ -99,7 +106,7 @@ string DescribeNegation(const Matcher<T>& m) { // Returns the reason why x matches, or doesn't match, m. template <typename MatcherType, typename Value> -string Explain(const MatcherType& m, const Value& x) { +std::string Explain(const MatcherType& m, const Value& x) { stringstream ss; m.ExplainMatchResultTo(x, &ss); return ss.str(); @@ -108,20 +115,20 @@ string Explain(const MatcherType& m, const Value& x) { // Tests Args<k0, ..., kn>(m). TEST(ArgsTest, AcceptsZeroTemplateArg) { - const tuple<int, bool> t(5, true); - EXPECT_THAT(t, Args<>(Eq(tuple<>()))); - EXPECT_THAT(t, Not(Args<>(Ne(tuple<>())))); + const std::tuple<int, bool> t(5, true); + EXPECT_THAT(t, Args<>(Eq(std::tuple<>()))); + EXPECT_THAT(t, Not(Args<>(Ne(std::tuple<>())))); } TEST(ArgsTest, AcceptsOneTemplateArg) { - const tuple<int, bool> t(5, true); - EXPECT_THAT(t, Args<0>(Eq(make_tuple(5)))); - EXPECT_THAT(t, Args<1>(Eq(make_tuple(true)))); - EXPECT_THAT(t, Not(Args<1>(Eq(make_tuple(false))))); + const std::tuple<int, bool> t(5, true); + EXPECT_THAT(t, Args<0>(Eq(std::make_tuple(5)))); + EXPECT_THAT(t, Args<1>(Eq(std::make_tuple(true)))); + EXPECT_THAT(t, Not(Args<1>(Eq(std::make_tuple(false))))); } TEST(ArgsTest, AcceptsTwoTemplateArgs) { - const tuple<short, int, long> t(4, 5, 6L); // NOLINT + const std::tuple<short, int, long> t(4, 5, 6L); // NOLINT EXPECT_THAT(t, (Args<0, 1>(Lt()))); EXPECT_THAT(t, (Args<1, 2>(Lt()))); @@ -129,13 +136,13 @@ TEST(ArgsTest, AcceptsTwoTemplateArgs) { } TEST(ArgsTest, AcceptsRepeatedTemplateArgs) { - const tuple<short, int, long> t(4, 5, 6L); // NOLINT + const std::tuple<short, int, long> t(4, 5, 6L); // NOLINT EXPECT_THAT(t, (Args<0, 0>(Eq()))); EXPECT_THAT(t, Not(Args<1, 1>(Ne()))); } TEST(ArgsTest, AcceptsDecreasingTemplateArgs) { - const tuple<short, int, long> t(4, 5, 6L); // NOLINT + const std::tuple<short, int, long> t(4, 5, 6L); // NOLINT EXPECT_THAT(t, (Args<2, 0>(Gt()))); EXPECT_THAT(t, Not(Args<2, 1>(Lt()))); } @@ -151,29 +158,29 @@ TEST(ArgsTest, AcceptsDecreasingTemplateArgs) { #endif MATCHER(SumIsZero, "") { - return get<0>(arg) + get<1>(arg) + get<2>(arg) == 0; + return std::get<0>(arg) + std::get<1>(arg) + std::get<2>(arg) == 0; } TEST(ArgsTest, AcceptsMoreTemplateArgsThanArityOfOriginalTuple) { - EXPECT_THAT(make_tuple(-1, 2), (Args<0, 0, 1>(SumIsZero()))); - EXPECT_THAT(make_tuple(1, 2), Not(Args<0, 0, 1>(SumIsZero()))); + EXPECT_THAT(std::make_tuple(-1, 2), (Args<0, 0, 1>(SumIsZero()))); + EXPECT_THAT(std::make_tuple(1, 2), Not(Args<0, 0, 1>(SumIsZero()))); } TEST(ArgsTest, CanBeNested) { - const tuple<short, int, long, int> t(4, 5, 6L, 6); // NOLINT + const std::tuple<short, int, long, int> t(4, 5, 6L, 6); // NOLINT EXPECT_THAT(t, (Args<1, 2, 3>(Args<1, 2>(Eq())))); EXPECT_THAT(t, (Args<0, 1, 3>(Args<0, 2>(Lt())))); } TEST(ArgsTest, CanMatchTupleByValue) { - typedef tuple<char, int, int> Tuple3; + typedef std::tuple<char, int, int> Tuple3; const Matcher<Tuple3> m = Args<1, 2>(Lt()); EXPECT_TRUE(m.Matches(Tuple3('a', 1, 2))); EXPECT_FALSE(m.Matches(Tuple3('b', 2, 2))); } TEST(ArgsTest, CanMatchTupleByReference) { - typedef tuple<char, char, int> Tuple3; + typedef std::tuple<char, char, int> Tuple3; const Matcher<const Tuple3&> m = Args<0, 1>(Lt()); EXPECT_TRUE(m.Matches(Tuple3('a', 'b', 2))); EXPECT_FALSE(m.Matches(Tuple3('b', 'b', 2))); @@ -185,23 +192,23 @@ MATCHER_P(PrintsAs, str, "") { } TEST(ArgsTest, AcceptsTenTemplateArgs) { - EXPECT_THAT(make_tuple(0, 1L, 2, 3L, 4, 5, 6, 7, 8, 9), + EXPECT_THAT(std::make_tuple(0, 1L, 2, 3L, 4, 5, 6, 7, 8, 9), (Args<9, 8, 7, 6, 5, 4, 3, 2, 1, 0>( PrintsAs("(9, 8, 7, 6, 5, 4, 3, 2, 1, 0)")))); - EXPECT_THAT(make_tuple(0, 1L, 2, 3L, 4, 5, 6, 7, 8, 9), + EXPECT_THAT(std::make_tuple(0, 1L, 2, 3L, 4, 5, 6, 7, 8, 9), Not(Args<9, 8, 7, 6, 5, 4, 3, 2, 1, 0>( - PrintsAs("(0, 8, 7, 6, 5, 4, 3, 2, 1, 0)")))); + PrintsAs("(0, 8, 7, 6, 5, 4, 3, 2, 1, 0)")))); } TEST(ArgsTest, DescirbesSelfCorrectly) { - const Matcher<tuple<int, bool, char> > m = Args<2, 0>(Lt()); + const Matcher<std::tuple<int, bool, char> > m = Args<2, 0>(Lt()); EXPECT_EQ("are a tuple whose fields (#2, #0) are a pair where " "the first < the second", Describe(m)); } TEST(ArgsTest, DescirbesNestedArgsCorrectly) { - const Matcher<const tuple<int, bool, char, int>&> m = + const Matcher<const std::tuple<int, bool, char, int>&> m = Args<0, 2, 3>(Args<2, 0>(Lt())); EXPECT_EQ("are a tuple whose fields (#0, #2, #3) are a tuple " "whose fields (#2, #0) are a pair where the first < the second", @@ -209,28 +216,28 @@ TEST(ArgsTest, DescirbesNestedArgsCorrectly) { } TEST(ArgsTest, DescribesNegationCorrectly) { - const Matcher<tuple<int, char> > m = Args<1, 0>(Gt()); + const Matcher<std::tuple<int, char> > m = Args<1, 0>(Gt()); EXPECT_EQ("are a tuple whose fields (#1, #0) aren't a pair " "where the first > the second", DescribeNegation(m)); } TEST(ArgsTest, ExplainsMatchResultWithoutInnerExplanation) { - const Matcher<tuple<bool, int, int> > m = Args<1, 2>(Eq()); + const Matcher<std::tuple<bool, int, int> > m = Args<1, 2>(Eq()); EXPECT_EQ("whose fields (#1, #2) are (42, 42)", - Explain(m, make_tuple(false, 42, 42))); + Explain(m, std::make_tuple(false, 42, 42))); EXPECT_EQ("whose fields (#1, #2) are (42, 43)", - Explain(m, make_tuple(false, 42, 43))); + Explain(m, std::make_tuple(false, 42, 43))); } // For testing Args<>'s explanation. -class LessThanMatcher : public MatcherInterface<tuple<char, int> > { +class LessThanMatcher : public MatcherInterface<std::tuple<char, int> > { public: virtual void DescribeTo(::std::ostream* os) const {} - virtual bool MatchAndExplain(tuple<char, int> value, + virtual bool MatchAndExplain(std::tuple<char, int> value, MatchResultListener* listener) const { - const int diff = get<0>(value) - get<1>(value); + const int diff = std::get<0>(value) - std::get<1>(value); if (diff > 0) { *listener << "where the first value is " << diff << " more than the second"; @@ -239,17 +246,18 @@ class LessThanMatcher : public MatcherInterface<tuple<char, int> > { } }; -Matcher<tuple<char, int> > LessThan() { +Matcher<std::tuple<char, int> > LessThan() { return MakeMatcher(new LessThanMatcher); } TEST(ArgsTest, ExplainsMatchResultWithInnerExplanation) { - const Matcher<tuple<char, int, int> > m = Args<0, 2>(LessThan()); - EXPECT_EQ("whose fields (#0, #2) are ('a' (97, 0x61), 42), " - "where the first value is 55 more than the second", - Explain(m, make_tuple('a', 42, 42))); + const Matcher<std::tuple<char, int, int> > m = Args<0, 2>(LessThan()); + EXPECT_EQ( + "whose fields (#0, #2) are ('a' (97, 0x61), 42), " + "where the first value is 55 more than the second", + Explain(m, std::make_tuple('a', 42, 42))); EXPECT_EQ("whose fields (#0, #2) are ('\\0', 43)", - Explain(m, make_tuple('\0', 42, 43))); + Explain(m, std::make_tuple('\0', 42, 43))); } // For testing ExplainMatchResultTo(). @@ -296,7 +304,7 @@ TEST(ElementsAreTest, CanDescribeExpectingOneElement) { } TEST(ElementsAreTest, CanDescribeExpectingManyElements) { - Matcher<list<string> > m = ElementsAre(StrEq("one"), "two"); + Matcher<list<std::string> > m = ElementsAre(StrEq("one"), "two"); EXPECT_EQ("has 2 elements where\n" "element #0 is equal to \"one\",\n" "element #1 is equal to \"two\"", Describe(m)); @@ -314,7 +322,7 @@ TEST(ElementsAreTest, CanDescribeNegationOfExpectingOneElment) { } TEST(ElementsAreTest, CanDescribeNegationOfExpectingManyElements) { - Matcher<const list<string>& > m = ElementsAre("one", "two"); + Matcher<const list<std::string>&> m = ElementsAre("one", "two"); EXPECT_EQ("doesn't have 2 elements, or\n" "element #0 isn't equal to \"one\", or\n" "element #1 isn't equal to \"two\"", DescribeNegation(m)); @@ -365,21 +373,21 @@ TEST(ElementsAreTest, CanExplainMismatchRightSize) { } TEST(ElementsAreTest, MatchesOneElementVector) { - vector<string> test_vector; + vector<std::string> test_vector; test_vector.push_back("test string"); EXPECT_THAT(test_vector, ElementsAre(StrEq("test string"))); } TEST(ElementsAreTest, MatchesOneElementList) { - list<string> test_list; + list<std::string> test_list; test_list.push_back("test string"); EXPECT_THAT(test_list, ElementsAre("test string")); } TEST(ElementsAreTest, MatchesThreeElementVector) { - vector<string> test_vector; + vector<std::string> test_vector; test_vector.push_back("one"); test_vector.push_back("two"); test_vector.push_back("three"); @@ -428,30 +436,30 @@ TEST(ElementsAreTest, MatchesTenElementVector) { } TEST(ElementsAreTest, DoesNotMatchWrongSize) { - vector<string> test_vector; + vector<std::string> test_vector; test_vector.push_back("test string"); test_vector.push_back("test string"); - Matcher<vector<string> > m = ElementsAre(StrEq("test string")); + Matcher<vector<std::string> > m = ElementsAre(StrEq("test string")); EXPECT_FALSE(m.Matches(test_vector)); } TEST(ElementsAreTest, DoesNotMatchWrongValue) { - vector<string> test_vector; + vector<std::string> test_vector; test_vector.push_back("other string"); - Matcher<vector<string> > m = ElementsAre(StrEq("test string")); + Matcher<vector<std::string> > m = ElementsAre(StrEq("test string")); EXPECT_FALSE(m.Matches(test_vector)); } TEST(ElementsAreTest, DoesNotMatchWrongOrder) { - vector<string> test_vector; + vector<std::string> test_vector; test_vector.push_back("one"); test_vector.push_back("three"); test_vector.push_back("two"); - Matcher<vector<string> > m = ElementsAre( - StrEq("one"), StrEq("two"), StrEq("three")); + Matcher<vector<std::string> > m = + ElementsAre(StrEq("one"), StrEq("two"), StrEq("three")); EXPECT_FALSE(m.Matches(test_vector)); } @@ -507,7 +515,7 @@ class NativeArrayPassedAsPointerAndSize { TEST(ElementsAreTest, WorksWithNativeArrayPassedAsPointerAndSize) { int array[] = { 0, 1 }; - ::testing::tuple<int*, size_t> array_as_tuple(array, 2); + ::std::tuple<int*, size_t> array_as_tuple(array, 2); EXPECT_THAT(array_as_tuple, ElementsAre(0, 1)); EXPECT_THAT(array_as_tuple, Not(ElementsAre(0))); @@ -527,7 +535,7 @@ TEST(ElementsAreTest, WorksWithTwoDimensionalNativeArray) { } TEST(ElementsAreTest, AcceptsStringLiteral) { - string array[] = { "hi", "one", "two" }; + std::string array[] = {"hi", "one", "two"}; EXPECT_THAT(array, ElementsAre("hi", "one", "two")); EXPECT_THAT(array, Not(ElementsAre("hi", "one", "too"))); } @@ -546,10 +554,10 @@ TEST(ElementsAreTest, AcceptsArrayWithUnknownSize) { // The size of kHi is not known in this test, but ElementsAre() should // still accept it. - string array1[] = { "hi" }; + std::string array1[] = {"hi"}; EXPECT_THAT(array1, ElementsAre(kHi)); - string array2[] = { "ho" }; + std::string array2[] = {"ho"}; EXPECT_THAT(array2, Not(ElementsAre(kHi))); } @@ -561,8 +569,8 @@ TEST(ElementsAreTest, MakesCopyOfArguments) { int x = 1; int y = 2; // This should make a copy of x and y. - ::testing::internal::ElementsAreMatcher<testing::tuple<int, int> > - polymorphic_matcher = ElementsAre(x, y); + ::testing::internal::ElementsAreMatcher<std::tuple<int, int> > + polymorphic_matcher = ElementsAre(x, y); // Changing x and y now shouldn't affect the meaning of the above matcher. x = y = 0; const int array1[] = { 1, 2 }; @@ -589,7 +597,7 @@ TEST(ElementsAreArrayTest, CanBeCreatedWithValueArray) { TEST(ElementsAreArrayTest, CanBeCreatedWithArraySize) { const char* a[] = { "one", "two", "three" }; - vector<string> test_vector(a, a + GTEST_ARRAY_SIZE_(a)); + vector<std::string> test_vector(a, a + GTEST_ARRAY_SIZE_(a)); EXPECT_THAT(test_vector, ElementsAreArray(a, GTEST_ARRAY_SIZE_(a))); const char** p = a; @@ -600,7 +608,7 @@ TEST(ElementsAreArrayTest, CanBeCreatedWithArraySize) { TEST(ElementsAreArrayTest, CanBeCreatedWithoutArraySize) { const char* a[] = { "one", "two", "three" }; - vector<string> test_vector(a, a + GTEST_ARRAY_SIZE_(a)); + vector<std::string> test_vector(a, a + GTEST_ARRAY_SIZE_(a)); EXPECT_THAT(test_vector, ElementsAreArray(a)); test_vector[0] = "1"; @@ -608,10 +616,10 @@ TEST(ElementsAreArrayTest, CanBeCreatedWithoutArraySize) { } TEST(ElementsAreArrayTest, CanBeCreatedWithMatcherArray) { - const Matcher<string> kMatcherArray[] = - { StrEq("one"), StrEq("two"), StrEq("three") }; + const Matcher<std::string> kMatcherArray[] = {StrEq("one"), StrEq("two"), + StrEq("three")}; - vector<string> test_vector; + vector<std::string> test_vector; test_vector.push_back("one"); test_vector.push_back("two"); test_vector.push_back("three"); @@ -640,7 +648,7 @@ TEST(ElementsAreArrayTest, TakesInitializerList) { } TEST(ElementsAreArrayTest, TakesInitializerListOfCStrings) { - const string a[5] = { "a", "b", "c", "d", "e" }; + const std::string a[5] = {"a", "b", "c", "d", "e"}; EXPECT_THAT(a, ElementsAreArray({ "a", "b", "c", "d", "e" })); EXPECT_THAT(a, Not(ElementsAreArray({ "a", "b", "c", "e", "d" }))); EXPECT_THAT(a, Not(ElementsAreArray({ "a", "b", "c", "d", "ef" }))); @@ -687,7 +695,7 @@ TEST(ElementsAreArrayTest, CanBeCreatedWithIteratorRange) { // Pointers are iterators, too. EXPECT_THAT(test_vector, ElementsAreArray(a, a + GTEST_ARRAY_SIZE_(a))); // The empty range of NULL pointers should also be okay. - int* const null_int = NULL; + int* const null_int = nullptr; EXPECT_THAT(test_vector, Not(ElementsAreArray(null_int, null_int))); EXPECT_THAT((vector<int>()), ElementsAreArray(null_int, null_int)); } @@ -751,16 +759,16 @@ MATCHER(IsEven2, negation ? "is odd" : "is even") { // This also tests that the description string can reference matcher // parameters. -MATCHER_P2(EqSumOf, x, y, - string(negation ? "doesn't equal" : "equals") + " the sum of " + - PrintToString(x) + " and " + PrintToString(y)) { +MATCHER_P2(EqSumOf, x, y, std::string(negation ? "doesn't equal" : "equals") + + " the sum of " + PrintToString(x) + " and " + + PrintToString(y)) { if (arg == (x + y)) { *result_listener << "OK"; return true; } else { // Verifies that we can stream to the underlying stream of // result_listener. - if (result_listener->stream() != NULL) { + if (result_listener->stream() != nullptr) { *result_listener->stream() << "diff == " << (x + y - arg); } return false; @@ -1117,12 +1125,12 @@ TEST(ContainsTest, ListMatchesWhenElementIsInContainer) { EXPECT_THAT(some_list, Contains(Gt(2.5))); EXPECT_THAT(some_list, Contains(Eq(2.0f))); - list<string> another_list; + list<std::string> another_list; another_list.push_back("fee"); another_list.push_back("fie"); another_list.push_back("foe"); another_list.push_back("fum"); - EXPECT_THAT(another_list, Contains(string("fee"))); + EXPECT_THAT(another_list, Contains(std::string("fee"))); } TEST(ContainsTest, ListDoesNotMatchWhenElementIsNotInContainer) { @@ -1146,7 +1154,7 @@ TEST(ContainsTest, SetMatchesWhenElementIsInContainer) { another_set.insert("fie"); another_set.insert("foe"); another_set.insert("fum"); - EXPECT_THAT(another_set, Contains(Eq(string("fum")))); + EXPECT_THAT(another_set, Contains(Eq(std::string("fum")))); } TEST(ContainsTest, SetDoesNotMatchWhenElementIsNotInContainer) { @@ -1157,7 +1165,7 @@ TEST(ContainsTest, SetDoesNotMatchWhenElementIsNotInContainer) { set<const char*> c_string_set; c_string_set.insert("hello"); - EXPECT_THAT(c_string_set, Not(Contains(string("hello").c_str()))); + EXPECT_THAT(c_string_set, Not(Contains(std::string("hello").c_str()))); } TEST(ContainsTest, ExplainsMatchResultCorrectly) { @@ -1189,13 +1197,14 @@ TEST(ContainsTest, MapMatchesWhenElementIsInContainer) { my_map[bar] = 2; EXPECT_THAT(my_map, Contains(pair<const char* const, int>(bar, 2))); - map<string, int> another_map; + map<std::string, int> another_map; another_map["fee"] = 1; another_map["fie"] = 2; another_map["foe"] = 3; another_map["fum"] = 4; - EXPECT_THAT(another_map, Contains(pair<const string, int>(string("fee"), 1))); - EXPECT_THAT(another_map, Contains(pair<const string, int>("fie", 2))); + EXPECT_THAT(another_map, + Contains(pair<const std::string, int>(std::string("fee"), 1))); + EXPECT_THAT(another_map, Contains(pair<const std::string, int>("fie", 2))); } TEST(ContainsTest, MapDoesNotMatchWhenElementIsNotInContainer) { @@ -1207,7 +1216,7 @@ TEST(ContainsTest, MapDoesNotMatchWhenElementIsNotInContainer) { TEST(ContainsTest, ArrayMatchesWhenElementIsInContainer) { const char* string_array[] = { "fee", "fie", "foe", "fum" }; - EXPECT_THAT(string_array, Contains(Eq(string("fum")))); + EXPECT_THAT(string_array, Contains(Eq(std::string("fum")))); } TEST(ContainsTest, ArrayDoesNotMatchWhenElementIsNotInContainer) { @@ -1224,8 +1233,8 @@ TEST(ContainsTest, AcceptsMatcher) { TEST(ContainsTest, WorksForNativeArrayAsTuple) { const int a[] = { 1, 2 }; const int* const pointer = a; - EXPECT_THAT(make_tuple(pointer, 2), Contains(1)); - EXPECT_THAT(make_tuple(pointer, 2), Not(Contains(Gt(3)))); + EXPECT_THAT(std::make_tuple(pointer, 2), Contains(1)); + EXPECT_THAT(std::make_tuple(pointer, 2), Not(Contains(Gt(3)))); } TEST(ContainsTest, WorksForTwoDimensionalNativeArray) { @@ -1283,4 +1292,48 @@ TEST(AnyOfTest, DoesNotCallAnyOfUnqualified) { # pragma warning(pop) #endif +#if GTEST_LANG_CXX11 + +TEST(AllOfTest, WorksOnMoveOnlyType) { + std::unique_ptr<int> p(new int(3)); + EXPECT_THAT(p, AllOf(Pointee(Eq(3)), Pointee(Gt(0)), Pointee(Lt(5)))); + EXPECT_THAT(p, Not(AllOf(Pointee(Eq(3)), Pointee(Gt(0)), Pointee(Lt(3))))); +} + +TEST(AnyOfTest, WorksOnMoveOnlyType) { + std::unique_ptr<int> p(new int(3)); + EXPECT_THAT(p, AnyOf(Pointee(Eq(5)), Pointee(Lt(0)), Pointee(Lt(5)))); + EXPECT_THAT(p, Not(AnyOf(Pointee(Eq(5)), Pointee(Lt(0)), Pointee(Gt(5))))); +} + +MATCHER(IsNotNull, "") { + return arg != nullptr; +} + +// Verifies that a matcher defined using MATCHER() can work on +// move-only types. +TEST(MatcherMacroTest, WorksOnMoveOnlyType) { + std::unique_ptr<int> p(new int(3)); + EXPECT_THAT(p, IsNotNull()); + EXPECT_THAT(std::unique_ptr<int>(), Not(IsNotNull())); +} + +MATCHER_P(UniquePointee, pointee, "") { + return *arg == pointee; +} + +// Verifies that a matcher defined using MATCHER_P*() can work on +// move-only types. +TEST(MatcherPMacroTest, WorksOnMoveOnlyType) { + std::unique_ptr<int> p(new int(3)); + EXPECT_THAT(p, UniquePointee(3)); + EXPECT_THAT(p, Not(UniquePointee(2))); +} + +#endif // GTEST_LASNG_CXX11 + } // namespace + +#ifdef _MSC_VER +# pragma warning(pop) +#endif diff --git a/googlemock/test/gmock-internal-utils_test.cc b/googlemock/test/gmock-internal-utils_test.cc index 9d5ec60..41498f0 100644 --- a/googlemock/test/gmock-internal-utils_test.cc +++ b/googlemock/test/gmock-internal-utils_test.cc @@ -26,8 +26,7 @@ // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -// -// Author: wan@google.com (Zhanyong Wan) + // Google Mock - a framework for writing C++ mock classes. // @@ -49,7 +48,7 @@ // implementation. It must come before gtest-internal-inl.h is // included, or there will be a compiler error. This trick is to // prevent a user from accidentally including gtest-internal-inl.h in -// his code. +// their code. #define GTEST_IMPLEMENTATION_ 1 #include "src/gtest-internal-inl.h" #undef GTEST_IMPLEMENTATION_ @@ -69,6 +68,26 @@ namespace internal { namespace { +TEST(JoinAsTupleTest, JoinsEmptyTuple) { + EXPECT_EQ("", JoinAsTuple(Strings())); +} + +TEST(JoinAsTupleTest, JoinsOneTuple) { + const char* fields[] = {"1"}; + EXPECT_EQ("1", JoinAsTuple(Strings(fields, fields + 1))); +} + +TEST(JoinAsTupleTest, JoinsTwoTuple) { + const char* fields[] = {"1", "a"}; + EXPECT_EQ("(1, a)", JoinAsTuple(Strings(fields, fields + 2))); +} + +TEST(JoinAsTupleTest, JoinsTenTuple) { + const char* fields[] = {"1", "2", "3", "4", "5", "6", "7", "8", "9", "10"}; + EXPECT_EQ("(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)", + JoinAsTuple(Strings(fields, fields + 10))); +} + TEST(ConvertIdentifierNameToWordsTest, WorksWhenNameContainsNoWord) { EXPECT_EQ("", ConvertIdentifierNameToWords("")); EXPECT_EQ("", ConvertIdentifierNameToWords("_")); @@ -139,9 +158,9 @@ TEST(GetRawPointerTest, WorksForSmartPointers) { } TEST(GetRawPointerTest, WorksForRawPointers) { - int* p = NULL; + int* p = nullptr; // Don't use EXPECT_EQ as no NULL-testing magic on Symbian. - EXPECT_TRUE(NULL == GetRawPointer(p)); + EXPECT_TRUE(nullptr == GetRawPointer(p)); int n = 1; EXPECT_EQ(&n, GetRawPointer(&n)); } @@ -289,26 +308,23 @@ TEST(LosslessArithmeticConvertibleTest, FloatingPointToFloatingPoint) { // Tests the TupleMatches() template function. TEST(TupleMatchesTest, WorksForSize0) { - tuple<> matchers; - tuple<> values; + std::tuple<> matchers; + std::tuple<> values; EXPECT_TRUE(TupleMatches(matchers, values)); } TEST(TupleMatchesTest, WorksForSize1) { - tuple<Matcher<int> > matchers(Eq(1)); - tuple<int> values1(1), - values2(2); + std::tuple<Matcher<int> > matchers(Eq(1)); + std::tuple<int> values1(1), values2(2); EXPECT_TRUE(TupleMatches(matchers, values1)); EXPECT_FALSE(TupleMatches(matchers, values2)); } TEST(TupleMatchesTest, WorksForSize2) { - tuple<Matcher<int>, Matcher<char> > matchers(Eq(1), Eq('a')); - tuple<int, char> values1(1, 'a'), - values2(1, 'b'), - values3(2, 'a'), + std::tuple<Matcher<int>, Matcher<char> > matchers(Eq(1), Eq('a')); + std::tuple<int, char> values1(1, 'a'), values2(1, 'b'), values3(2, 'a'), values4(2, 'b'); EXPECT_TRUE(TupleMatches(matchers, values1)); @@ -318,12 +334,12 @@ TEST(TupleMatchesTest, WorksForSize2) { } TEST(TupleMatchesTest, WorksForSize5) { - tuple<Matcher<int>, Matcher<char>, Matcher<bool>, Matcher<long>, // NOLINT - Matcher<string> > + std::tuple<Matcher<int>, Matcher<char>, Matcher<bool>, + Matcher<long>, // NOLINT + Matcher<std::string> > matchers(Eq(1), Eq('a'), Eq(true), Eq(2L), Eq("hi")); - tuple<int, char, bool, long, string> // NOLINT - values1(1, 'a', true, 2L, "hi"), - values2(1, 'a', true, 2L, "hello"), + std::tuple<int, char, bool, long, std::string> // NOLINT + values1(1, 'a', true, 2L, "hi"), values2(1, 'a', true, 2L, "hello"), values3(2, 'a', true, 2L, "hi"); EXPECT_TRUE(TupleMatches(matchers, values1)); @@ -375,7 +391,7 @@ class LogIsVisibleTest : public ::testing::Test { virtual void TearDown() { GMOCK_FLAG(verbose) = original_verbose_; } - string original_verbose_; + std::string original_verbose_; }; TEST_F(LogIsVisibleTest, AlwaysReturnsTrueIfVerbosityIsInfo) { @@ -402,9 +418,9 @@ TEST_F(LogIsVisibleTest, WorksWhenVerbosityIsWarning) { // Verifies that Log() behaves correctly for the given verbosity level // and log severity. -void TestLogWithSeverity(const string& verbosity, LogSeverity severity, +void TestLogWithSeverity(const std::string& verbosity, LogSeverity severity, bool should_print) { - const string old_flag = GMOCK_FLAG(verbose); + const std::string old_flag = GMOCK_FLAG(verbose); GMOCK_FLAG(verbose) = verbosity; CaptureStdout(); Log(severity, "Test log.\n", 0); @@ -423,7 +439,7 @@ void TestLogWithSeverity(const string& verbosity, LogSeverity severity, // Tests that when the stack_frames_to_skip parameter is negative, // Log() doesn't include the stack trace in the output. TEST(LogTest, NoStackTraceWhenStackFramesToSkipIsNegative) { - const string saved_flag = GMOCK_FLAG(verbose); + const std::string saved_flag = GMOCK_FLAG(verbose); GMOCK_FLAG(verbose) = kInfoVerbosity; CaptureStdout(); Log(kInfo, "Test log.\n", -1); @@ -432,7 +448,7 @@ TEST(LogTest, NoStackTraceWhenStackFramesToSkipIsNegative) { } struct MockStackTraceGetter : testing::internal::OsStackTraceGetterInterface { - virtual string CurrentStackTrace(int max_depth, int skip_count) { + virtual std::string CurrentStackTrace(int max_depth, int skip_count) { return (testing::Message() << max_depth << "::" << skip_count << "\n") .GetString(); } @@ -447,11 +463,11 @@ TEST(LogTest, NoSkippingStackFrameInOptMode) { CaptureStdout(); Log(kWarning, "Test log.\n", 100); - const string log = GetCapturedStdout(); + const std::string log = GetCapturedStdout(); - string expected_trace = + std::string expected_trace = (testing::Message() << GTEST_FLAG(stack_trace_depth) << "::").GetString(); - string expected_message = + std::string expected_message = "\nGMOCK WARNING:\n" "Test log.\n" "Stack trace:\n" + @@ -474,7 +490,7 @@ TEST(LogTest, NoSkippingStackFrameInOptMode) { AllOf(Ge(expected_skip_count), Le(expected_skip_count + 10))); // Restores the default OS stack trace getter. - GetUnitTestImpl()->set_os_stack_trace_getter(NULL); + GetUnitTestImpl()->set_os_stack_trace_getter(nullptr); } // Tests that all logs are printed when the value of the @@ -547,7 +563,7 @@ TEST(TypeTraitsTest, remove_reference) { // Verifies that Log() behaves correctly for the given verbosity level // and log severity. std::string GrabOutput(void(*logger)(), const char* verbosity) { - const string saved_flag = GMOCK_FLAG(verbose); + const std::string saved_flag = GMOCK_FLAG(verbose); GMOCK_FLAG(verbose) = verbosity; CaptureStdout(); logger(); @@ -668,22 +684,25 @@ TEST(StlContainerViewTest, WorksForStaticNativeArray) { TEST(StlContainerViewTest, WorksForDynamicNativeArray) { StaticAssertTypeEq<NativeArray<int>, - StlContainerView<tuple<const int*, size_t> >::type>(); - StaticAssertTypeEq<NativeArray<double>, - StlContainerView<tuple<linked_ptr<double>, int> >::type>(); + StlContainerView<std::tuple<const int*, size_t> >::type>(); + StaticAssertTypeEq< + NativeArray<double>, + StlContainerView<std::tuple<linked_ptr<double>, int> >::type>(); - StaticAssertTypeEq<const NativeArray<int>, - StlContainerView<tuple<const int*, int> >::const_reference>(); + StaticAssertTypeEq< + const NativeArray<int>, + StlContainerView<std::tuple<const int*, int> >::const_reference>(); int a1[3] = { 0, 1, 2 }; const int* const p1 = a1; - NativeArray<int> a2 = StlContainerView<tuple<const int*, int> >:: - ConstReference(make_tuple(p1, 3)); + NativeArray<int> a2 = + StlContainerView<std::tuple<const int*, int> >::ConstReference( + std::make_tuple(p1, 3)); EXPECT_EQ(3U, a2.size()); EXPECT_EQ(a1, a2.begin()); - const NativeArray<int> a3 = StlContainerView<tuple<int*, size_t> >:: - Copy(make_tuple(static_cast<int*>(a1), 3)); + const NativeArray<int> a3 = StlContainerView<std::tuple<int*, size_t> >::Copy( + std::make_tuple(static_cast<int*>(a1), 3)); ASSERT_EQ(3U, a3.size()); EXPECT_EQ(0, a3.begin()[0]); EXPECT_EQ(1, a3.begin()[1]); diff --git a/googlemock/test/gmock-matchers_test.cc b/googlemock/test/gmock-matchers_test.cc index 9f62c3d..f4e9e9f 100644 --- a/googlemock/test/gmock-matchers_test.cc +++ b/googlemock/test/gmock-matchers_test.cc @@ -26,8 +26,7 @@ // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -// -// Author: wan@google.com (Zhanyong Wan) + // Google Mock - a framework for writing C++ mock classes. // @@ -45,6 +44,7 @@ #include <limits> #include <list> #include <map> +#include <memory> #include <set> #include <sstream> #include <string> @@ -58,12 +58,11 @@ # include <forward_list> // NOLINT #endif -namespace testing { - -namespace internal { -GTEST_API_ string JoinAsTuple(const Strings& fields); -} // namespace internal +#if GTEST_LANG_CXX11 +# include <type_traits> +#endif +namespace testing { namespace gmock_matchers_test { using std::greater; @@ -137,7 +136,6 @@ using testing::Value; using testing::WhenSorted; using testing::WhenSortedBy; using testing::_; -using testing::get; using testing::internal::DummyMatchResultListener; using testing::internal::ElementMatcherPair; using testing::internal::ElementMatcherPairs; @@ -145,7 +143,6 @@ using testing::internal::ExplainMatchFailureTupleTo; using testing::internal::FloatingEqMatcher; using testing::internal::FormatMatcherDescription; using testing::internal::IsReadableTypeName; -using testing::internal::JoinAsTuple; using testing::internal::linked_ptr; using testing::internal::MatchMatrix; using testing::internal::RE; @@ -155,8 +152,6 @@ using testing::internal::Strings; using testing::internal::linked_ptr; using testing::internal::scoped_ptr; using testing::internal::string; -using testing::make_tuple; -using testing::tuple; // For testing ExplainMatchResultTo(). class GreaterThanMatcher : public MatcherInterface<int> { @@ -189,7 +184,7 @@ Matcher<int> GreaterThan(int n) { return MakeMatcher(new GreaterThanMatcher(n)); } -string OfType(const string& type_name) { +std::string OfType(const std::string& type_name) { #if GTEST_HAS_RTTI return " (of type " + type_name + ")"; #else @@ -199,28 +194,30 @@ string OfType(const string& type_name) { // Returns the description of the given matcher. template <typename T> -string Describe(const Matcher<T>& m) { - stringstream ss; - m.DescribeTo(&ss); - return ss.str(); +std::string Describe(const Matcher<T>& m) { + return DescribeMatcher<T>(m); } // Returns the description of the negation of the given matcher. template <typename T> -string DescribeNegation(const Matcher<T>& m) { - stringstream ss; - m.DescribeNegationTo(&ss); - return ss.str(); +std::string DescribeNegation(const Matcher<T>& m) { + return DescribeMatcher<T>(m, true); } // Returns the reason why x matches, or doesn't match, m. template <typename MatcherType, typename Value> -string Explain(const MatcherType& m, const Value& x) { +std::string Explain(const MatcherType& m, const Value& x) { StringMatchResultListener listener; ExplainMatchResult(m, x, &listener); return listener.str(); } +TEST(MonotonicMatcherTest, IsPrintable) { + stringstream ss; + ss << GreaterThan(5); + EXPECT_EQ("is > 5", ss.str()); +} + TEST(MatchResultListenerTest, StreamingWorks) { StringMatchResultListener listener; listener << "hi" << 5; @@ -238,8 +235,8 @@ TEST(MatchResultListenerTest, StreamingWorks) { } TEST(MatchResultListenerTest, CanAccessUnderlyingStream) { - EXPECT_TRUE(DummyMatchResultListener().stream() == NULL); - EXPECT_TRUE(StreamMatchResultListener(NULL).stream() == NULL); + EXPECT_TRUE(DummyMatchResultListener().stream() == nullptr); + EXPECT_TRUE(StreamMatchResultListener(nullptr).stream() == nullptr); EXPECT_EQ(&std::cout, StreamMatchResultListener(&std::cout).stream()); } @@ -249,7 +246,7 @@ TEST(MatchResultListenerTest, IsInterestedWorks) { EXPECT_TRUE(StreamMatchResultListener(&std::cout).IsInterested()); EXPECT_FALSE(DummyMatchResultListener().IsInterested()); - EXPECT_FALSE(StreamMatchResultListener(NULL).IsInterested()); + EXPECT_FALSE(StreamMatchResultListener(nullptr).IsInterested()); } // Makes sure that the MatcherInterface<T> interface doesn't @@ -283,7 +280,7 @@ class NewEvenMatcherImpl : public MatcherInterface<int> { const bool match = x % 2 == 0; // Verifies that we can stream to a listener directly. *listener << "value % " << 2; - if (listener->stream() != NULL) { + if (listener->stream() != nullptr) { // Verifies that we can stream to a listener's underlying stream // too. *listener->stream() << " == " << (x % 2); @@ -327,11 +324,27 @@ TEST(MatcherTest, CanBeImplicitlyConstructedFromValue) { // Tests that NULL can be used in place of Eq(NULL). TEST(MatcherTest, CanBeImplicitlyConstructedFromNULL) { Matcher<int*> m1 = NULL; - EXPECT_TRUE(m1.Matches(NULL)); + EXPECT_TRUE(m1.Matches(nullptr)); int n = 0; EXPECT_FALSE(m1.Matches(&n)); } +// Tests that matchers can be constructed from a variable that is not properly +// defined. This should be illegal, but many users rely on this accidentally. +struct Undefined { + virtual ~Undefined() = 0; + static const int kInt = 1; +}; + +TEST(MatcherTest, CanBeConstructedFromUndefinedVariable) { + Matcher<int> m1 = Undefined::kInt; + EXPECT_TRUE(m1.Matches(1)); + EXPECT_FALSE(m1.Matches(2)); +} + +// Test that a matcher parameterized with an abstract class compiles. +TEST(MatcherTest, CanAcceptAbstractClass) { Matcher<const Undefined&> m = _; } + // Tests that matchers are copyable. TEST(MatcherTest, IsCopyable) { // Tests the copy constructor. @@ -365,72 +378,138 @@ TEST(MatcherTest, MatchAndExplain) { } // Tests that a C-string literal can be implicitly converted to a -// Matcher<string> or Matcher<const string&>. +// Matcher<std::string> or Matcher<const std::string&>. TEST(StringMatcherTest, CanBeImplicitlyConstructedFromCStringLiteral) { - Matcher<string> m1 = "hi"; + Matcher<std::string> m1 = "hi"; EXPECT_TRUE(m1.Matches("hi")); EXPECT_FALSE(m1.Matches("hello")); - Matcher<const string&> m2 = "hi"; + Matcher<const std::string&> m2 = "hi"; EXPECT_TRUE(m2.Matches("hi")); EXPECT_FALSE(m2.Matches("hello")); } // Tests that a string object can be implicitly converted to a -// Matcher<string> or Matcher<const string&>. +// Matcher<std::string> or Matcher<const std::string&>. TEST(StringMatcherTest, CanBeImplicitlyConstructedFromString) { - Matcher<string> m1 = string("hi"); + Matcher<std::string> m1 = std::string("hi"); + EXPECT_TRUE(m1.Matches("hi")); + EXPECT_FALSE(m1.Matches("hello")); + + Matcher<const std::string&> m2 = std::string("hi"); + EXPECT_TRUE(m2.Matches("hi")); + EXPECT_FALSE(m2.Matches("hello")); +} + +#if GTEST_HAS_GLOBAL_STRING +// Tests that a ::string object can be implicitly converted to a +// Matcher<std::string> or Matcher<const std::string&>. +TEST(StringMatcherTest, CanBeImplicitlyConstructedFromGlobalString) { + Matcher<std::string> m1 = ::string("hi"); + EXPECT_TRUE(m1.Matches("hi")); + EXPECT_FALSE(m1.Matches("hello")); + + Matcher<const std::string&> m2 = ::string("hi"); + EXPECT_TRUE(m2.Matches("hi")); + EXPECT_FALSE(m2.Matches("hello")); +} +#endif // GTEST_HAS_GLOBAL_STRING + +#if GTEST_HAS_GLOBAL_STRING +// Tests that a C-string literal can be implicitly converted to a +// Matcher<::string> or Matcher<const ::string&>. +TEST(GlobalStringMatcherTest, CanBeImplicitlyConstructedFromCStringLiteral) { + Matcher< ::string> m1 = "hi"; EXPECT_TRUE(m1.Matches("hi")); EXPECT_FALSE(m1.Matches("hello")); - Matcher<const string&> m2 = string("hi"); + Matcher<const ::string&> m2 = "hi"; EXPECT_TRUE(m2.Matches("hi")); EXPECT_FALSE(m2.Matches("hello")); } -#if GTEST_HAS_STRING_PIECE_ +// Tests that a std::string object can be implicitly converted to a +// Matcher<::string> or Matcher<const ::string&>. +TEST(GlobalStringMatcherTest, CanBeImplicitlyConstructedFromString) { + Matcher< ::string> m1 = std::string("hi"); + EXPECT_TRUE(m1.Matches("hi")); + EXPECT_FALSE(m1.Matches("hello")); + + Matcher<const ::string&> m2 = std::string("hi"); + EXPECT_TRUE(m2.Matches("hi")); + EXPECT_FALSE(m2.Matches("hello")); +} + +// Tests that a ::string object can be implicitly converted to a +// Matcher<::string> or Matcher<const ::string&>. +TEST(GlobalStringMatcherTest, CanBeImplicitlyConstructedFromGlobalString) { + Matcher< ::string> m1 = ::string("hi"); + EXPECT_TRUE(m1.Matches("hi")); + EXPECT_FALSE(m1.Matches("hello")); + + Matcher<const ::string&> m2 = ::string("hi"); + EXPECT_TRUE(m2.Matches("hi")); + EXPECT_FALSE(m2.Matches("hello")); +} +#endif // GTEST_HAS_GLOBAL_STRING + +#if GTEST_HAS_ABSL // Tests that a C-string literal can be implicitly converted to a -// Matcher<StringPiece> or Matcher<const StringPiece&>. -TEST(StringPieceMatcherTest, CanBeImplicitlyConstructedFromCStringLiteral) { - Matcher<StringPiece> m1 = "cats"; +// Matcher<absl::string_view> or Matcher<const absl::string_view&>. +TEST(StringViewMatcherTest, CanBeImplicitlyConstructedFromCStringLiteral) { + Matcher<absl::string_view> m1 = "cats"; EXPECT_TRUE(m1.Matches("cats")); EXPECT_FALSE(m1.Matches("dogs")); - Matcher<const StringPiece&> m2 = "cats"; + Matcher<const absl::string_view&> m2 = "cats"; EXPECT_TRUE(m2.Matches("cats")); EXPECT_FALSE(m2.Matches("dogs")); } -// Tests that a string object can be implicitly converted to a -// Matcher<StringPiece> or Matcher<const StringPiece&>. -TEST(StringPieceMatcherTest, CanBeImplicitlyConstructedFromString) { - Matcher<StringPiece> m1 = string("cats"); +// Tests that a std::string object can be implicitly converted to a +// Matcher<absl::string_view> or Matcher<const absl::string_view&>. +TEST(StringViewMatcherTest, CanBeImplicitlyConstructedFromString) { + Matcher<absl::string_view> m1 = std::string("cats"); + EXPECT_TRUE(m1.Matches("cats")); + EXPECT_FALSE(m1.Matches("dogs")); + + Matcher<const absl::string_view&> m2 = std::string("cats"); + EXPECT_TRUE(m2.Matches("cats")); + EXPECT_FALSE(m2.Matches("dogs")); +} + +#if GTEST_HAS_GLOBAL_STRING +// Tests that a ::string object can be implicitly converted to a +// Matcher<absl::string_view> or Matcher<const absl::string_view&>. +TEST(StringViewMatcherTest, CanBeImplicitlyConstructedFromGlobalString) { + Matcher<absl::string_view> m1 = ::string("cats"); EXPECT_TRUE(m1.Matches("cats")); EXPECT_FALSE(m1.Matches("dogs")); - Matcher<const StringPiece&> m2 = string("cats"); + Matcher<const absl::string_view&> m2 = ::string("cats"); EXPECT_TRUE(m2.Matches("cats")); EXPECT_FALSE(m2.Matches("dogs")); } +#endif // GTEST_HAS_GLOBAL_STRING -// Tests that a StringPiece object can be implicitly converted to a -// Matcher<StringPiece> or Matcher<const StringPiece&>. -TEST(StringPieceMatcherTest, CanBeImplicitlyConstructedFromStringPiece) { - Matcher<StringPiece> m1 = StringPiece("cats"); +// Tests that a absl::string_view object can be implicitly converted to a +// Matcher<absl::string_view> or Matcher<const absl::string_view&>. +TEST(StringViewMatcherTest, CanBeImplicitlyConstructedFromStringView) { + Matcher<absl::string_view> m1 = absl::string_view("cats"); EXPECT_TRUE(m1.Matches("cats")); EXPECT_FALSE(m1.Matches("dogs")); - Matcher<const StringPiece&> m2 = StringPiece("cats"); + Matcher<const absl::string_view&> m2 = absl::string_view("cats"); EXPECT_TRUE(m2.Matches("cats")); EXPECT_FALSE(m2.Matches("dogs")); } -#endif // GTEST_HAS_STRING_PIECE_ +#endif // GTEST_HAS_ABSL // Tests that MakeMatcher() constructs a Matcher<T> from a // MatcherInterface* without requiring the user to explicitly // write the type. TEST(MakeMatcherTest, ConstructsMatcherFromMatcherInterface) { - const MatcherInterface<int>* dummy_impl = NULL; + const MatcherInterface<int>* dummy_impl = nullptr; Matcher<int> m = MakeMatcher(dummy_impl); } @@ -489,7 +568,7 @@ class PolymorphicIsEvenImpl { bool MatchAndExplain(const T& x, MatchResultListener* listener) const { // Verifies that we can stream to the listener directly. *listener << "% " << 2; - if (listener->stream() != NULL) { + if (listener->stream() != nullptr) { // Verifies that we can stream to the listener's underlying stream // too. *listener->stream() << " == " << (x % 2); @@ -609,11 +688,76 @@ TEST(MatcherCastTest, FromSameType) { EXPECT_FALSE(m2.Matches(1)); } +// Tests that MatcherCast<T>(m) works when m is a value of the same type as the +// value type of the Matcher. +TEST(MatcherCastTest, FromAValue) { + Matcher<int> m = MatcherCast<int>(42); + EXPECT_TRUE(m.Matches(42)); + EXPECT_FALSE(m.Matches(239)); +} + +// Tests that MatcherCast<T>(m) works when m is a value of the type implicitly +// convertible to the value type of the Matcher. +TEST(MatcherCastTest, FromAnImplicitlyConvertibleValue) { + const int kExpected = 'c'; + Matcher<int> m = MatcherCast<int>('c'); + EXPECT_TRUE(m.Matches(kExpected)); + EXPECT_FALSE(m.Matches(kExpected + 1)); +} + +struct NonImplicitlyConstructibleTypeWithOperatorEq { + friend bool operator==( + const NonImplicitlyConstructibleTypeWithOperatorEq& /* ignored */, + int rhs) { + return 42 == rhs; + } + friend bool operator==( + int lhs, + const NonImplicitlyConstructibleTypeWithOperatorEq& /* ignored */) { + return lhs == 42; + } +}; + +// Tests that MatcherCast<T>(m) works when m is a neither a matcher nor +// implicitly convertible to the value type of the Matcher, but the value type +// of the matcher has operator==() overload accepting m. +TEST(MatcherCastTest, NonImplicitlyConstructibleTypeWithOperatorEq) { + Matcher<NonImplicitlyConstructibleTypeWithOperatorEq> m1 = + MatcherCast<NonImplicitlyConstructibleTypeWithOperatorEq>(42); + EXPECT_TRUE(m1.Matches(NonImplicitlyConstructibleTypeWithOperatorEq())); + + Matcher<NonImplicitlyConstructibleTypeWithOperatorEq> m2 = + MatcherCast<NonImplicitlyConstructibleTypeWithOperatorEq>(239); + EXPECT_FALSE(m2.Matches(NonImplicitlyConstructibleTypeWithOperatorEq())); + + // When updating the following lines please also change the comment to + // namespace convertible_from_any. + Matcher<int> m3 = + MatcherCast<int>(NonImplicitlyConstructibleTypeWithOperatorEq()); + EXPECT_TRUE(m3.Matches(42)); + EXPECT_FALSE(m3.Matches(239)); +} + +// ConvertibleFromAny does not work with MSVC. resulting in +// error C2440: 'initializing': cannot convert from 'Eq' to 'M' +// No constructor could take the source type, or constructor overload +// resolution was ambiguous + +#if !defined _MSC_VER + +// The below ConvertibleFromAny struct is implicitly constructible from anything +// and when in the same namespace can interact with other tests. In particular, +// if it is in the same namespace as other tests and one removes +// NonImplicitlyConstructibleTypeWithOperatorEq::operator==(int lhs, ...); +// then the corresponding test still compiles (and it should not!) by implicitly +// converting NonImplicitlyConstructibleTypeWithOperatorEq to ConvertibleFromAny +// in m3.Matcher(). +namespace convertible_from_any { // Implicitly convertible from any type. struct ConvertibleFromAny { ConvertibleFromAny(int a_value) : value(a_value) {} template <typename T> - explicit ConvertibleFromAny(const T& /*a_value*/) : value(-1) { + ConvertibleFromAny(const T& /*a_value*/) : value(-1) { ADD_FAILURE() << "Conversion constructor called"; } int value; @@ -639,6 +783,9 @@ TEST(MatcherCastTest, FromConvertibleFromAny) { EXPECT_TRUE(m.Matches(ConvertibleFromAny(1))); EXPECT_FALSE(m.Matches(ConvertibleFromAny(2))); } +} // namespace convertible_from_any + +#endif // !defined _MSC_VER struct IntReferenceWrapper { IntReferenceWrapper(const int& a_value) : value(&a_value) {} @@ -744,6 +891,9 @@ TEST(SafeMatcherCastTest, FromSameType) { EXPECT_FALSE(m2.Matches(1)); } +#if !defined _MSC_VER + +namespace convertible_from_any { TEST(SafeMatcherCastTest, ConversionConstructorIsUsed) { Matcher<ConvertibleFromAny> m = SafeMatcherCast<ConvertibleFromAny>(1); EXPECT_TRUE(m.Matches(ConvertibleFromAny(1))); @@ -756,6 +906,9 @@ TEST(SafeMatcherCastTest, FromConvertibleFromAny) { EXPECT_TRUE(m.Matches(ConvertibleFromAny(1))); EXPECT_FALSE(m.Matches(ConvertibleFromAny(2))); } +} // namespace convertible_from_any + +#endif // !defined _MSC_VER TEST(SafeMatcherCastTest, ValueIsNotCopied) { int n = 42; @@ -767,7 +920,7 @@ TEST(SafeMatcherCastTest, ValueIsNotCopied) { TEST(ExpectThat, TakesLiterals) { EXPECT_THAT(1, 1); EXPECT_THAT(1.0, 1.0); - EXPECT_THAT(string(), ""); + EXPECT_THAT(std::string(), ""); } TEST(ExpectThat, TakesFunctions) { @@ -867,15 +1020,11 @@ class Unprintable { public: Unprintable() : c_('a') {} + bool operator==(const Unprintable& /* rhs */) const { return true; } private: char c_; }; -inline bool operator==(const Unprintable& /* lhs */, - const Unprintable& /* rhs */) { - return true; -} - TEST(EqTest, CanDescribeSelf) { Matcher<Unprintable> m = Eq(Unprintable()); EXPECT_EQ("is equal to 1-byte object <61>", Describe(m)); @@ -914,7 +1063,7 @@ TEST(TypedEqTest, CanDescribeSelf) { // Type<T>::IsTypeOf(v) compiles iff the type of value v is T, where T // is a "bare" type (i.e. not in the form of const U or U&). If v's // type is not T, the compiler will generate a message about -// "undefined referece". +// "undefined reference". template <typename T> struct Type { static bool IsTypeOf(const T& /* v */) { return true; } @@ -973,7 +1122,7 @@ TEST(LeTest, CanDescribeSelf) { // Tests that Lt(v) matches anything < v. TEST(LtTest, ImplementsLessThan) { - Matcher<const string&> m1 = Lt("Hello"); + Matcher<const std::string&> m1 = Lt("Hello"); EXPECT_TRUE(m1.Matches("Abc")); EXPECT_FALSE(m1.Matches("Hello")); EXPECT_FALSE(m1.Matches("Hello, world!")); @@ -1002,13 +1151,13 @@ TEST(NeTest, CanDescribeSelf) { // Tests that IsNull() matches any NULL pointer of any type. TEST(IsNullTest, MatchesNullPointer) { Matcher<int*> m1 = IsNull(); - int* p1 = NULL; + int* p1 = nullptr; int n = 0; EXPECT_TRUE(m1.Matches(p1)); EXPECT_FALSE(m1.Matches(&n)); Matcher<const char*> m2 = IsNull(); - const char* p2 = NULL; + const char* p2 = nullptr; EXPECT_TRUE(m2.Matches(p2)); EXPECT_FALSE(m2.Matches("hi")); @@ -1022,7 +1171,7 @@ TEST(IsNullTest, MatchesNullPointer) { // gmock_matchers_test::IsNullTest_MatchesNullPointer_Test::TestBody()') // gmock-matchers.h: (instantiating: 'testing::PolymorphicMatc Matcher<void*> m3 = IsNull(); - void* p3 = NULL; + void* p3 = nullptr; EXPECT_TRUE(m3.Matches(p3)); EXPECT_FALSE(m3.Matches(reinterpret_cast<void*>(0xbeef))); #endif @@ -1046,14 +1195,14 @@ TEST(IsNullTest, ReferenceToConstLinkedPtr) { EXPECT_FALSE(m.Matches(non_null_p)); } -#if GTEST_HAS_STD_FUNCTION_ +#if GTEST_LANG_CXX11 TEST(IsNullTest, StdFunction) { const Matcher<std::function<void()>> m = IsNull(); EXPECT_TRUE(m.Matches(std::function<void()>())); EXPECT_FALSE(m.Matches([]{})); } -#endif // GTEST_HAS_STD_FUNCTION_ +#endif // GTEST_LANG_CXX11 // Tests that IsNull() describes itself properly. TEST(IsNullTest, CanDescribeSelf) { @@ -1065,13 +1214,13 @@ TEST(IsNullTest, CanDescribeSelf) { // Tests that NotNull() matches any non-NULL pointer of any type. TEST(NotNullTest, MatchesNonNullPointer) { Matcher<int*> m1 = NotNull(); - int* p1 = NULL; + int* p1 = nullptr; int n = 0; EXPECT_FALSE(m1.Matches(p1)); EXPECT_TRUE(m1.Matches(&n)); Matcher<const char*> m2 = NotNull(); - const char* p2 = NULL; + const char* p2 = nullptr; EXPECT_FALSE(m2.Matches(p2)); EXPECT_TRUE(m2.Matches("hi")); } @@ -1094,14 +1243,14 @@ TEST(NotNullTest, ReferenceToConstLinkedPtr) { EXPECT_TRUE(m.Matches(non_null_p)); } -#if GTEST_HAS_STD_FUNCTION_ +#if GTEST_LANG_CXX11 TEST(NotNullTest, StdFunction) { const Matcher<std::function<void()>> m = NotNull(); EXPECT_TRUE(m.Matches([]{})); EXPECT_FALSE(m.Matches(std::function<void()>())); } -#endif // GTEST_HAS_STD_FUNCTION_ +#endif // GTEST_LANG_CXX11 // Tests that NotNull() describes itself properly. TEST(NotNullTest, CanDescribeSelf) { @@ -1125,7 +1274,7 @@ TEST(RefTest, CanDescribeSelf) { Matcher<int&> m = Ref(n); stringstream ss; ss << "references the variable @" << &n << " 5"; - EXPECT_EQ(string(ss.str()), Describe(m)); + EXPECT_EQ(ss.str(), Describe(m)); } // Test that Ref(non_const_varialbe) can be used as a matcher for a @@ -1169,39 +1318,58 @@ TEST(RefTest, ExplainsResult) { // Tests string comparison matchers. TEST(StrEqTest, MatchesEqualString) { - Matcher<const char*> m = StrEq(string("Hello")); + Matcher<const char*> m = StrEq(std::string("Hello")); EXPECT_TRUE(m.Matches("Hello")); EXPECT_FALSE(m.Matches("hello")); - EXPECT_FALSE(m.Matches(NULL)); + EXPECT_FALSE(m.Matches(nullptr)); - Matcher<const string&> m2 = StrEq("Hello"); + Matcher<const std::string&> m2 = StrEq("Hello"); EXPECT_TRUE(m2.Matches("Hello")); EXPECT_FALSE(m2.Matches("Hi")); + +#if GTEST_HAS_ABSL + Matcher<const absl::string_view&> m3 = StrEq("Hello"); + EXPECT_TRUE(m3.Matches(absl::string_view("Hello"))); + EXPECT_FALSE(m3.Matches(absl::string_view("hello"))); + EXPECT_FALSE(m3.Matches(absl::string_view())); + + Matcher<const absl::string_view&> m_empty = StrEq(""); + EXPECT_TRUE(m_empty.Matches(absl::string_view(""))); + EXPECT_TRUE(m_empty.Matches(absl::string_view())); + EXPECT_FALSE(m_empty.Matches(absl::string_view("hello"))); +#endif // GTEST_HAS_ABSL } TEST(StrEqTest, CanDescribeSelf) { - Matcher<string> m = StrEq("Hi-\'\"?\\\a\b\f\n\r\t\v\xD3"); + Matcher<std::string> m = StrEq("Hi-\'\"?\\\a\b\f\n\r\t\v\xD3"); EXPECT_EQ("is equal to \"Hi-\'\\\"?\\\\\\a\\b\\f\\n\\r\\t\\v\\xD3\"", Describe(m)); - string str("01204500800"); + std::string str("01204500800"); str[3] = '\0'; - Matcher<string> m2 = StrEq(str); + Matcher<std::string> m2 = StrEq(str); EXPECT_EQ("is equal to \"012\\04500800\"", Describe(m2)); str[0] = str[6] = str[7] = str[9] = str[10] = '\0'; - Matcher<string> m3 = StrEq(str); + Matcher<std::string> m3 = StrEq(str); EXPECT_EQ("is equal to \"\\012\\045\\0\\08\\0\\0\"", Describe(m3)); } TEST(StrNeTest, MatchesUnequalString) { Matcher<const char*> m = StrNe("Hello"); EXPECT_TRUE(m.Matches("")); - EXPECT_TRUE(m.Matches(NULL)); + EXPECT_TRUE(m.Matches(nullptr)); EXPECT_FALSE(m.Matches("Hello")); - Matcher<string> m2 = StrNe(string("Hello")); + Matcher<std::string> m2 = StrNe(std::string("Hello")); EXPECT_TRUE(m2.Matches("hello")); EXPECT_FALSE(m2.Matches("Hello")); + +#if GTEST_HAS_ABSL + Matcher<const absl::string_view> m3 = StrNe("Hello"); + EXPECT_TRUE(m3.Matches(absl::string_view(""))); + EXPECT_TRUE(m3.Matches(absl::string_view())); + EXPECT_FALSE(m3.Matches(absl::string_view("Hello"))); +#endif // GTEST_HAS_ABSL } TEST(StrNeTest, CanDescribeSelf) { @@ -1210,57 +1378,73 @@ TEST(StrNeTest, CanDescribeSelf) { } TEST(StrCaseEqTest, MatchesEqualStringIgnoringCase) { - Matcher<const char*> m = StrCaseEq(string("Hello")); + Matcher<const char*> m = StrCaseEq(std::string("Hello")); EXPECT_TRUE(m.Matches("Hello")); EXPECT_TRUE(m.Matches("hello")); EXPECT_FALSE(m.Matches("Hi")); - EXPECT_FALSE(m.Matches(NULL)); + EXPECT_FALSE(m.Matches(nullptr)); - Matcher<const string&> m2 = StrCaseEq("Hello"); + Matcher<const std::string&> m2 = StrCaseEq("Hello"); EXPECT_TRUE(m2.Matches("hello")); EXPECT_FALSE(m2.Matches("Hi")); + +#if GTEST_HAS_ABSL + Matcher<const absl::string_view&> m3 = StrCaseEq(std::string("Hello")); + EXPECT_TRUE(m3.Matches(absl::string_view("Hello"))); + EXPECT_TRUE(m3.Matches(absl::string_view("hello"))); + EXPECT_FALSE(m3.Matches(absl::string_view("Hi"))); + EXPECT_FALSE(m3.Matches(absl::string_view())); +#endif // GTEST_HAS_ABSL } TEST(StrCaseEqTest, MatchesEqualStringWith0IgnoringCase) { - string str1("oabocdooeoo"); - string str2("OABOCDOOEOO"); - Matcher<const string&> m0 = StrCaseEq(str1); - EXPECT_FALSE(m0.Matches(str2 + string(1, '\0'))); + std::string str1("oabocdooeoo"); + std::string str2("OABOCDOOEOO"); + Matcher<const std::string&> m0 = StrCaseEq(str1); + EXPECT_FALSE(m0.Matches(str2 + std::string(1, '\0'))); str1[3] = str2[3] = '\0'; - Matcher<const string&> m1 = StrCaseEq(str1); + Matcher<const std::string&> m1 = StrCaseEq(str1); EXPECT_TRUE(m1.Matches(str2)); str1[0] = str1[6] = str1[7] = str1[10] = '\0'; str2[0] = str2[6] = str2[7] = str2[10] = '\0'; - Matcher<const string&> m2 = StrCaseEq(str1); + Matcher<const std::string&> m2 = StrCaseEq(str1); str1[9] = str2[9] = '\0'; EXPECT_FALSE(m2.Matches(str2)); - Matcher<const string&> m3 = StrCaseEq(str1); + Matcher<const std::string&> m3 = StrCaseEq(str1); EXPECT_TRUE(m3.Matches(str2)); EXPECT_FALSE(m3.Matches(str2 + "x")); str2.append(1, '\0'); EXPECT_FALSE(m3.Matches(str2)); - EXPECT_FALSE(m3.Matches(string(str2, 0, 9))); + EXPECT_FALSE(m3.Matches(std::string(str2, 0, 9))); } TEST(StrCaseEqTest, CanDescribeSelf) { - Matcher<string> m = StrCaseEq("Hi"); + Matcher<std::string> m = StrCaseEq("Hi"); EXPECT_EQ("is equal to (ignoring case) \"Hi\"", Describe(m)); } TEST(StrCaseNeTest, MatchesUnequalStringIgnoringCase) { Matcher<const char*> m = StrCaseNe("Hello"); EXPECT_TRUE(m.Matches("Hi")); - EXPECT_TRUE(m.Matches(NULL)); + EXPECT_TRUE(m.Matches(nullptr)); EXPECT_FALSE(m.Matches("Hello")); EXPECT_FALSE(m.Matches("hello")); - Matcher<string> m2 = StrCaseNe(string("Hello")); + Matcher<std::string> m2 = StrCaseNe(std::string("Hello")); EXPECT_TRUE(m2.Matches("")); EXPECT_FALSE(m2.Matches("Hello")); + +#if GTEST_HAS_ABSL + Matcher<const absl::string_view> m3 = StrCaseNe("Hello"); + EXPECT_TRUE(m3.Matches(absl::string_view("Hi"))); + EXPECT_TRUE(m3.Matches(absl::string_view())); + EXPECT_FALSE(m3.Matches(absl::string_view("Hello"))); + EXPECT_FALSE(m3.Matches(absl::string_view("hello"))); +#endif // GTEST_HAS_ABSL } TEST(StrCaseNeTest, CanDescribeSelf) { @@ -1270,13 +1454,17 @@ TEST(StrCaseNeTest, CanDescribeSelf) { // Tests that HasSubstr() works for matching string-typed values. TEST(HasSubstrTest, WorksForStringClasses) { - const Matcher<string> m1 = HasSubstr("foo"); - EXPECT_TRUE(m1.Matches(string("I love food."))); - EXPECT_FALSE(m1.Matches(string("tofo"))); + const Matcher<std::string> m1 = HasSubstr("foo"); + EXPECT_TRUE(m1.Matches(std::string("I love food."))); + EXPECT_FALSE(m1.Matches(std::string("tofo"))); const Matcher<const std::string&> m2 = HasSubstr("foo"); EXPECT_TRUE(m2.Matches(std::string("I love food."))); EXPECT_FALSE(m2.Matches(std::string("tofo"))); + + const Matcher<std::string> m_empty = HasSubstr(""); + EXPECT_TRUE(m_empty.Matches(std::string())); + EXPECT_TRUE(m_empty.Matches(std::string("not empty"))); } // Tests that HasSubstr() works for matching C-string-typed values. @@ -1284,17 +1472,42 @@ TEST(HasSubstrTest, WorksForCStrings) { const Matcher<char*> m1 = HasSubstr("foo"); EXPECT_TRUE(m1.Matches(const_cast<char*>("I love food."))); EXPECT_FALSE(m1.Matches(const_cast<char*>("tofo"))); - EXPECT_FALSE(m1.Matches(NULL)); + EXPECT_FALSE(m1.Matches(nullptr)); const Matcher<const char*> m2 = HasSubstr("foo"); EXPECT_TRUE(m2.Matches("I love food.")); EXPECT_FALSE(m2.Matches("tofo")); - EXPECT_FALSE(m2.Matches(NULL)); + EXPECT_FALSE(m2.Matches(nullptr)); + + const Matcher<const char*> m_empty = HasSubstr(""); + EXPECT_TRUE(m_empty.Matches("not empty")); + EXPECT_TRUE(m_empty.Matches("")); + EXPECT_FALSE(m_empty.Matches(nullptr)); } +#if GTEST_HAS_ABSL +// Tests that HasSubstr() works for matching absl::string_view-typed values. +TEST(HasSubstrTest, WorksForStringViewClasses) { + const Matcher<absl::string_view> m1 = HasSubstr("foo"); + EXPECT_TRUE(m1.Matches(absl::string_view("I love food."))); + EXPECT_FALSE(m1.Matches(absl::string_view("tofo"))); + EXPECT_FALSE(m1.Matches(absl::string_view())); + + const Matcher<const absl::string_view&> m2 = HasSubstr("foo"); + EXPECT_TRUE(m2.Matches(absl::string_view("I love food."))); + EXPECT_FALSE(m2.Matches(absl::string_view("tofo"))); + EXPECT_FALSE(m2.Matches(absl::string_view())); + + const Matcher<const absl::string_view&> m3 = HasSubstr(""); + EXPECT_TRUE(m3.Matches(absl::string_view("foo"))); + EXPECT_TRUE(m3.Matches(absl::string_view(""))); + EXPECT_TRUE(m3.Matches(absl::string_view())); +} +#endif // GTEST_HAS_ABSL + // Tests that HasSubstr(s) describes itself properly. TEST(HasSubstrTest, CanDescribeSelf) { - Matcher<string> m = HasSubstr("foo\n\""); + Matcher<std::string> m = HasSubstr("foo\n\""); EXPECT_EQ("has substring \"foo\\n\\\"\"", Describe(m)); } @@ -1320,6 +1533,35 @@ TEST(KeyTest, MatchesCorrectly) { EXPECT_THAT(p, Not(Key(Lt(25)))); } +#if GTEST_LANG_CXX11 +template <size_t I> +struct Tag {}; + +struct PairWithGet { + int member_1; + string member_2; + using first_type = int; + using second_type = string; + + const int& GetImpl(Tag<0>) const { return member_1; } + const string& GetImpl(Tag<1>) const { return member_2; } +}; +template <size_t I> +auto get(const PairWithGet& value) -> decltype(value.GetImpl(Tag<I>())) { + return value.GetImpl(Tag<I>()); +} +TEST(PairTest, MatchesPairWithGetCorrectly) { + PairWithGet p{25, "foo"}; + EXPECT_THAT(p, Key(25)); + EXPECT_THAT(p, Not(Key(42))); + EXPECT_THAT(p, Key(Ge(20))); + EXPECT_THAT(p, Not(Key(Lt(25)))); + + std::vector<PairWithGet> v = {{11, "Foo"}, {29, "gMockIsBestMock"}}; + EXPECT_THAT(v, Contains(Key(29))); +} +#endif // GTEST_LANG_CXX11 + TEST(KeyTest, SafelyCastsInnerMatcher) { Matcher<int> is_positive = Gt(0); Matcher<int> is_negative = Lt(0); @@ -1457,20 +1699,39 @@ TEST(PairTest, InsideContainsUsingMap) { EXPECT_THAT(container, Not(Contains(Pair(3, _)))); } +#if GTEST_LANG_CXX11 +TEST(PairTest, UseGetInsteadOfMembers) { + PairWithGet pair{7, "ABC"}; + EXPECT_THAT(pair, Pair(7, "ABC")); + EXPECT_THAT(pair, Pair(Ge(7), HasSubstr("AB"))); + EXPECT_THAT(pair, Not(Pair(Lt(7), "ABC"))); + + std::vector<PairWithGet> v = {{11, "Foo"}, {29, "gMockIsBestMock"}}; + EXPECT_THAT(v, ElementsAre(Pair(11, string("Foo")), Pair(Ge(10), Not("")))); +} +#endif // GTEST_LANG_CXX11 + // Tests StartsWith(s). TEST(StartsWithTest, MatchesStringWithGivenPrefix) { - const Matcher<const char*> m1 = StartsWith(string("")); + const Matcher<const char*> m1 = StartsWith(std::string("")); EXPECT_TRUE(m1.Matches("Hi")); EXPECT_TRUE(m1.Matches("")); - EXPECT_FALSE(m1.Matches(NULL)); + EXPECT_FALSE(m1.Matches(nullptr)); - const Matcher<const string&> m2 = StartsWith("Hi"); + const Matcher<const std::string&> m2 = StartsWith("Hi"); EXPECT_TRUE(m2.Matches("Hi")); EXPECT_TRUE(m2.Matches("Hi Hi!")); EXPECT_TRUE(m2.Matches("High")); EXPECT_FALSE(m2.Matches("H")); EXPECT_FALSE(m2.Matches(" Hi")); + +#if GTEST_HAS_ABSL + const Matcher<absl::string_view> m_empty = StartsWith(""); + EXPECT_TRUE(m_empty.Matches(absl::string_view())); + EXPECT_TRUE(m_empty.Matches(absl::string_view(""))); + EXPECT_TRUE(m_empty.Matches(absl::string_view("not empty"))); +#endif // GTEST_HAS_ABSL } TEST(StartsWithTest, CanDescribeSelf) { @@ -1484,14 +1745,31 @@ TEST(EndsWithTest, MatchesStringWithGivenSuffix) { const Matcher<const char*> m1 = EndsWith(""); EXPECT_TRUE(m1.Matches("Hi")); EXPECT_TRUE(m1.Matches("")); - EXPECT_FALSE(m1.Matches(NULL)); + EXPECT_FALSE(m1.Matches(nullptr)); - const Matcher<const string&> m2 = EndsWith(string("Hi")); + const Matcher<const std::string&> m2 = EndsWith(std::string("Hi")); EXPECT_TRUE(m2.Matches("Hi")); EXPECT_TRUE(m2.Matches("Wow Hi Hi")); EXPECT_TRUE(m2.Matches("Super Hi")); EXPECT_FALSE(m2.Matches("i")); EXPECT_FALSE(m2.Matches("Hi ")); + +#if GTEST_HAS_GLOBAL_STRING + const Matcher<const ::string&> m3 = EndsWith(::string("Hi")); + EXPECT_TRUE(m3.Matches("Hi")); + EXPECT_TRUE(m3.Matches("Wow Hi Hi")); + EXPECT_TRUE(m3.Matches("Super Hi")); + EXPECT_FALSE(m3.Matches("i")); + EXPECT_FALSE(m3.Matches("Hi ")); +#endif // GTEST_HAS_GLOBAL_STRING + +#if GTEST_HAS_ABSL + const Matcher<const absl::string_view&> m4 = EndsWith(""); + EXPECT_TRUE(m4.Matches("Hi")); + EXPECT_TRUE(m4.Matches("")); + EXPECT_TRUE(m4.Matches(absl::string_view())); + EXPECT_TRUE(m4.Matches(absl::string_view(""))); +#endif // GTEST_HAS_ABSL } TEST(EndsWithTest, CanDescribeSelf) { @@ -1505,34 +1783,61 @@ TEST(MatchesRegexTest, MatchesStringMatchingGivenRegex) { const Matcher<const char*> m1 = MatchesRegex("a.*z"); EXPECT_TRUE(m1.Matches("az")); EXPECT_TRUE(m1.Matches("abcz")); - EXPECT_FALSE(m1.Matches(NULL)); + EXPECT_FALSE(m1.Matches(nullptr)); - const Matcher<const string&> m2 = MatchesRegex(new RE("a.*z")); + const Matcher<const std::string&> m2 = MatchesRegex(new RE("a.*z")); EXPECT_TRUE(m2.Matches("azbz")); EXPECT_FALSE(m2.Matches("az1")); EXPECT_FALSE(m2.Matches("1az")); + +#if GTEST_HAS_ABSL + const Matcher<const absl::string_view&> m3 = MatchesRegex("a.*z"); + EXPECT_TRUE(m3.Matches(absl::string_view("az"))); + EXPECT_TRUE(m3.Matches(absl::string_view("abcz"))); + EXPECT_FALSE(m3.Matches(absl::string_view("1az"))); + EXPECT_FALSE(m3.Matches(absl::string_view())); + const Matcher<const absl::string_view&> m4 = MatchesRegex(""); + EXPECT_TRUE(m4.Matches(absl::string_view(""))); + EXPECT_TRUE(m4.Matches(absl::string_view())); +#endif // GTEST_HAS_ABSL } TEST(MatchesRegexTest, CanDescribeSelf) { - Matcher<const std::string> m1 = MatchesRegex(string("Hi.*")); + Matcher<const std::string> m1 = MatchesRegex(std::string("Hi.*")); EXPECT_EQ("matches regular expression \"Hi.*\"", Describe(m1)); Matcher<const char*> m2 = MatchesRegex(new RE("a.*")); EXPECT_EQ("matches regular expression \"a.*\"", Describe(m2)); + +#if GTEST_HAS_ABSL + Matcher<const absl::string_view> m3 = MatchesRegex(new RE("0.*")); + EXPECT_EQ("matches regular expression \"0.*\"", Describe(m3)); +#endif // GTEST_HAS_ABSL } // Tests ContainsRegex(). TEST(ContainsRegexTest, MatchesStringContainingGivenRegex) { - const Matcher<const char*> m1 = ContainsRegex(string("a.*z")); + const Matcher<const char*> m1 = ContainsRegex(std::string("a.*z")); EXPECT_TRUE(m1.Matches("az")); EXPECT_TRUE(m1.Matches("0abcz1")); - EXPECT_FALSE(m1.Matches(NULL)); + EXPECT_FALSE(m1.Matches(nullptr)); - const Matcher<const string&> m2 = ContainsRegex(new RE("a.*z")); + const Matcher<const std::string&> m2 = ContainsRegex(new RE("a.*z")); EXPECT_TRUE(m2.Matches("azbz")); EXPECT_TRUE(m2.Matches("az1")); EXPECT_FALSE(m2.Matches("1a")); + +#if GTEST_HAS_ABSL + const Matcher<const absl::string_view&> m3 = ContainsRegex(new RE("a.*z")); + EXPECT_TRUE(m3.Matches(absl::string_view("azbz"))); + EXPECT_TRUE(m3.Matches(absl::string_view("az1"))); + EXPECT_FALSE(m3.Matches(absl::string_view("1a"))); + EXPECT_FALSE(m3.Matches(absl::string_view())); + const Matcher<const absl::string_view&> m4 = ContainsRegex(""); + EXPECT_TRUE(m4.Matches(absl::string_view(""))); + EXPECT_TRUE(m4.Matches(absl::string_view())); +#endif // GTEST_HAS_ABSL } TEST(ContainsRegexTest, CanDescribeSelf) { @@ -1541,6 +1846,11 @@ TEST(ContainsRegexTest, CanDescribeSelf) { Matcher<const char*> m2 = ContainsRegex(new RE("a.*")); EXPECT_EQ("contains regular expression \"a.*\"", Describe(m2)); + +#if GTEST_HAS_ABSL + Matcher<const absl::string_view> m3 = ContainsRegex(new RE("0.*")); + EXPECT_EQ("contains regular expression \"0.*\"", Describe(m3)); +#endif // GTEST_HAS_ABSL } // Tests for wide strings. @@ -1549,7 +1859,7 @@ TEST(StdWideStrEqTest, MatchesEqual) { Matcher<const wchar_t*> m = StrEq(::std::wstring(L"Hello")); EXPECT_TRUE(m.Matches(L"Hello")); EXPECT_FALSE(m.Matches(L"hello")); - EXPECT_FALSE(m.Matches(NULL)); + EXPECT_FALSE(m.Matches(nullptr)); Matcher<const ::std::wstring&> m2 = StrEq(L"Hello"); EXPECT_TRUE(m2.Matches(L"Hello")); @@ -1589,7 +1899,7 @@ TEST(StdWideStrEqTest, CanDescribeSelf) { TEST(StdWideStrNeTest, MatchesUnequalString) { Matcher<const wchar_t*> m = StrNe(L"Hello"); EXPECT_TRUE(m.Matches(L"")); - EXPECT_TRUE(m.Matches(NULL)); + EXPECT_TRUE(m.Matches(nullptr)); EXPECT_FALSE(m.Matches(L"Hello")); Matcher< ::std::wstring> m2 = StrNe(::std::wstring(L"Hello")); @@ -1607,7 +1917,7 @@ TEST(StdWideStrCaseEqTest, MatchesEqualStringIgnoringCase) { EXPECT_TRUE(m.Matches(L"Hello")); EXPECT_TRUE(m.Matches(L"hello")); EXPECT_FALSE(m.Matches(L"Hi")); - EXPECT_FALSE(m.Matches(NULL)); + EXPECT_FALSE(m.Matches(nullptr)); Matcher<const ::std::wstring&> m2 = StrCaseEq(L"Hello"); EXPECT_TRUE(m2.Matches(L"hello")); @@ -1647,7 +1957,7 @@ TEST(StdWideStrCaseEqTest, CanDescribeSelf) { TEST(StdWideStrCaseNeTest, MatchesUnequalStringIgnoringCase) { Matcher<const wchar_t*> m = StrCaseNe(L"Hello"); EXPECT_TRUE(m.Matches(L"Hi")); - EXPECT_TRUE(m.Matches(NULL)); + EXPECT_TRUE(m.Matches(nullptr)); EXPECT_FALSE(m.Matches(L"Hello")); EXPECT_FALSE(m.Matches(L"hello")); @@ -1677,12 +1987,12 @@ TEST(StdWideHasSubstrTest, WorksForCStrings) { const Matcher<wchar_t*> m1 = HasSubstr(L"foo"); EXPECT_TRUE(m1.Matches(const_cast<wchar_t*>(L"I love food."))); EXPECT_FALSE(m1.Matches(const_cast<wchar_t*>(L"tofo"))); - EXPECT_FALSE(m1.Matches(NULL)); + EXPECT_FALSE(m1.Matches(nullptr)); const Matcher<const wchar_t*> m2 = HasSubstr(L"foo"); EXPECT_TRUE(m2.Matches(L"I love food.")); EXPECT_FALSE(m2.Matches(L"tofo")); - EXPECT_FALSE(m2.Matches(NULL)); + EXPECT_FALSE(m2.Matches(nullptr)); } // Tests that HasSubstr(s) describes itself properly. @@ -1697,7 +2007,7 @@ TEST(StdWideStartsWithTest, MatchesStringWithGivenPrefix) { const Matcher<const wchar_t*> m1 = StartsWith(::std::wstring(L"")); EXPECT_TRUE(m1.Matches(L"Hi")); EXPECT_TRUE(m1.Matches(L"")); - EXPECT_FALSE(m1.Matches(NULL)); + EXPECT_FALSE(m1.Matches(nullptr)); const Matcher<const ::std::wstring&> m2 = StartsWith(L"Hi"); EXPECT_TRUE(m2.Matches(L"Hi")); @@ -1718,7 +2028,7 @@ TEST(StdWideEndsWithTest, MatchesStringWithGivenSuffix) { const Matcher<const wchar_t*> m1 = EndsWith(L""); EXPECT_TRUE(m1.Matches(L"Hi")); EXPECT_TRUE(m1.Matches(L"")); - EXPECT_FALSE(m1.Matches(NULL)); + EXPECT_FALSE(m1.Matches(nullptr)); const Matcher<const ::std::wstring&> m2 = EndsWith(::std::wstring(L"Hi")); EXPECT_TRUE(m2.Matches(L"Hi")); @@ -1740,7 +2050,7 @@ TEST(GlobalWideStrEqTest, MatchesEqual) { Matcher<const wchar_t*> m = StrEq(::wstring(L"Hello")); EXPECT_TRUE(m.Matches(L"Hello")); EXPECT_FALSE(m.Matches(L"hello")); - EXPECT_FALSE(m.Matches(NULL)); + EXPECT_FALSE(m.Matches(nullptr)); Matcher<const ::wstring&> m2 = StrEq(L"Hello"); EXPECT_TRUE(m2.Matches(L"Hello")); @@ -1780,7 +2090,7 @@ TEST(GlobalWideStrEqTest, CanDescribeSelf) { TEST(GlobalWideStrNeTest, MatchesUnequalString) { Matcher<const wchar_t*> m = StrNe(L"Hello"); EXPECT_TRUE(m.Matches(L"")); - EXPECT_TRUE(m.Matches(NULL)); + EXPECT_TRUE(m.Matches(nullptr)); EXPECT_FALSE(m.Matches(L"Hello")); Matcher< ::wstring> m2 = StrNe(::wstring(L"Hello")); @@ -1798,7 +2108,7 @@ TEST(GlobalWideStrCaseEqTest, MatchesEqualStringIgnoringCase) { EXPECT_TRUE(m.Matches(L"Hello")); EXPECT_TRUE(m.Matches(L"hello")); EXPECT_FALSE(m.Matches(L"Hi")); - EXPECT_FALSE(m.Matches(NULL)); + EXPECT_FALSE(m.Matches(nullptr)); Matcher<const ::wstring&> m2 = StrCaseEq(L"Hello"); EXPECT_TRUE(m2.Matches(L"hello")); @@ -1838,7 +2148,7 @@ TEST(GlobalWideStrCaseEqTest, CanDescribeSelf) { TEST(GlobalWideStrCaseNeTest, MatchesUnequalStringIgnoringCase) { Matcher<const wchar_t*> m = StrCaseNe(L"Hello"); EXPECT_TRUE(m.Matches(L"Hi")); - EXPECT_TRUE(m.Matches(NULL)); + EXPECT_TRUE(m.Matches(nullptr)); EXPECT_FALSE(m.Matches(L"Hello")); EXPECT_FALSE(m.Matches(L"hello")); @@ -1868,12 +2178,12 @@ TEST(GlobalWideHasSubstrTest, WorksForCStrings) { const Matcher<wchar_t*> m1 = HasSubstr(L"foo"); EXPECT_TRUE(m1.Matches(const_cast<wchar_t*>(L"I love food."))); EXPECT_FALSE(m1.Matches(const_cast<wchar_t*>(L"tofo"))); - EXPECT_FALSE(m1.Matches(NULL)); + EXPECT_FALSE(m1.Matches(nullptr)); const Matcher<const wchar_t*> m2 = HasSubstr(L"foo"); EXPECT_TRUE(m2.Matches(L"I love food.")); EXPECT_FALSE(m2.Matches(L"tofo")); - EXPECT_FALSE(m2.Matches(NULL)); + EXPECT_FALSE(m2.Matches(nullptr)); } // Tests that HasSubstr(s) describes itself properly. @@ -1888,7 +2198,7 @@ TEST(GlobalWideStartsWithTest, MatchesStringWithGivenPrefix) { const Matcher<const wchar_t*> m1 = StartsWith(::wstring(L"")); EXPECT_TRUE(m1.Matches(L"Hi")); EXPECT_TRUE(m1.Matches(L"")); - EXPECT_FALSE(m1.Matches(NULL)); + EXPECT_FALSE(m1.Matches(nullptr)); const Matcher<const ::wstring&> m2 = StartsWith(L"Hi"); EXPECT_TRUE(m2.Matches(L"Hi")); @@ -1909,7 +2219,7 @@ TEST(GlobalWideEndsWithTest, MatchesStringWithGivenSuffix) { const Matcher<const wchar_t*> m1 = EndsWith(L""); EXPECT_TRUE(m1.Matches(L"Hi")); EXPECT_TRUE(m1.Matches(L"")); - EXPECT_FALSE(m1.Matches(NULL)); + EXPECT_FALSE(m1.Matches(nullptr)); const Matcher<const ::wstring&> m2 = EndsWith(::wstring(L"Hi")); EXPECT_TRUE(m2.Matches(L"Hi")); @@ -1926,8 +2236,7 @@ TEST(GlobalWideEndsWithTest, CanDescribeSelf) { #endif // GTEST_HAS_GLOBAL_WSTRING - -typedef ::testing::tuple<long, int> Tuple2; // NOLINT +typedef ::std::tuple<long, int> Tuple2; // NOLINT // Tests that Eq() matches a 2-tuple where the first field == the // second field. @@ -2018,6 +2327,148 @@ TEST(Ne2Test, CanDescribeSelf) { EXPECT_EQ("are an unequal pair", Describe(m)); } +// Tests that FloatEq() matches a 2-tuple where +// FloatEq(first field) matches the second field. +TEST(FloatEq2Test, MatchesEqualArguments) { + typedef ::std::tuple<float, float> Tpl; + Matcher<const Tpl&> m = FloatEq(); + EXPECT_TRUE(m.Matches(Tpl(1.0f, 1.0f))); + EXPECT_TRUE(m.Matches(Tpl(0.3f, 0.1f + 0.1f + 0.1f))); + EXPECT_FALSE(m.Matches(Tpl(1.1f, 1.0f))); +} + +// Tests that FloatEq() describes itself properly. +TEST(FloatEq2Test, CanDescribeSelf) { + Matcher<const ::std::tuple<float, float>&> m = FloatEq(); + EXPECT_EQ("are an almost-equal pair", Describe(m)); +} + +// Tests that NanSensitiveFloatEq() matches a 2-tuple where +// NanSensitiveFloatEq(first field) matches the second field. +TEST(NanSensitiveFloatEqTest, MatchesEqualArgumentsWithNaN) { + typedef ::std::tuple<float, float> Tpl; + Matcher<const Tpl&> m = NanSensitiveFloatEq(); + EXPECT_TRUE(m.Matches(Tpl(1.0f, 1.0f))); + EXPECT_TRUE(m.Matches(Tpl(std::numeric_limits<float>::quiet_NaN(), + std::numeric_limits<float>::quiet_NaN()))); + EXPECT_FALSE(m.Matches(Tpl(1.1f, 1.0f))); + EXPECT_FALSE(m.Matches(Tpl(1.0f, std::numeric_limits<float>::quiet_NaN()))); + EXPECT_FALSE(m.Matches(Tpl(std::numeric_limits<float>::quiet_NaN(), 1.0f))); +} + +// Tests that NanSensitiveFloatEq() describes itself properly. +TEST(NanSensitiveFloatEqTest, CanDescribeSelfWithNaNs) { + Matcher<const ::std::tuple<float, float>&> m = NanSensitiveFloatEq(); + EXPECT_EQ("are an almost-equal pair", Describe(m)); +} + +// Tests that DoubleEq() matches a 2-tuple where +// DoubleEq(first field) matches the second field. +TEST(DoubleEq2Test, MatchesEqualArguments) { + typedef ::std::tuple<double, double> Tpl; + Matcher<const Tpl&> m = DoubleEq(); + EXPECT_TRUE(m.Matches(Tpl(1.0, 1.0))); + EXPECT_TRUE(m.Matches(Tpl(0.3, 0.1 + 0.1 + 0.1))); + EXPECT_FALSE(m.Matches(Tpl(1.1, 1.0))); +} + +// Tests that DoubleEq() describes itself properly. +TEST(DoubleEq2Test, CanDescribeSelf) { + Matcher<const ::std::tuple<double, double>&> m = DoubleEq(); + EXPECT_EQ("are an almost-equal pair", Describe(m)); +} + +// Tests that NanSensitiveDoubleEq() matches a 2-tuple where +// NanSensitiveDoubleEq(first field) matches the second field. +TEST(NanSensitiveDoubleEqTest, MatchesEqualArgumentsWithNaN) { + typedef ::std::tuple<double, double> Tpl; + Matcher<const Tpl&> m = NanSensitiveDoubleEq(); + EXPECT_TRUE(m.Matches(Tpl(1.0f, 1.0f))); + EXPECT_TRUE(m.Matches(Tpl(std::numeric_limits<double>::quiet_NaN(), + std::numeric_limits<double>::quiet_NaN()))); + EXPECT_FALSE(m.Matches(Tpl(1.1f, 1.0f))); + EXPECT_FALSE(m.Matches(Tpl(1.0f, std::numeric_limits<double>::quiet_NaN()))); + EXPECT_FALSE(m.Matches(Tpl(std::numeric_limits<double>::quiet_NaN(), 1.0f))); +} + +// Tests that DoubleEq() describes itself properly. +TEST(NanSensitiveDoubleEqTest, CanDescribeSelfWithNaNs) { + Matcher<const ::std::tuple<double, double>&> m = NanSensitiveDoubleEq(); + EXPECT_EQ("are an almost-equal pair", Describe(m)); +} + +// Tests that FloatEq() matches a 2-tuple where +// FloatNear(first field, max_abs_error) matches the second field. +TEST(FloatNear2Test, MatchesEqualArguments) { + typedef ::std::tuple<float, float> Tpl; + Matcher<const Tpl&> m = FloatNear(0.5f); + EXPECT_TRUE(m.Matches(Tpl(1.0f, 1.0f))); + EXPECT_TRUE(m.Matches(Tpl(1.3f, 1.0f))); + EXPECT_FALSE(m.Matches(Tpl(1.8f, 1.0f))); +} + +// Tests that FloatNear() describes itself properly. +TEST(FloatNear2Test, CanDescribeSelf) { + Matcher<const ::std::tuple<float, float>&> m = FloatNear(0.5f); + EXPECT_EQ("are an almost-equal pair", Describe(m)); +} + +// Tests that NanSensitiveFloatNear() matches a 2-tuple where +// NanSensitiveFloatNear(first field) matches the second field. +TEST(NanSensitiveFloatNearTest, MatchesNearbyArgumentsWithNaN) { + typedef ::std::tuple<float, float> Tpl; + Matcher<const Tpl&> m = NanSensitiveFloatNear(0.5f); + EXPECT_TRUE(m.Matches(Tpl(1.0f, 1.0f))); + EXPECT_TRUE(m.Matches(Tpl(1.1f, 1.0f))); + EXPECT_TRUE(m.Matches(Tpl(std::numeric_limits<float>::quiet_NaN(), + std::numeric_limits<float>::quiet_NaN()))); + EXPECT_FALSE(m.Matches(Tpl(1.6f, 1.0f))); + EXPECT_FALSE(m.Matches(Tpl(1.0f, std::numeric_limits<float>::quiet_NaN()))); + EXPECT_FALSE(m.Matches(Tpl(std::numeric_limits<float>::quiet_NaN(), 1.0f))); +} + +// Tests that NanSensitiveFloatNear() describes itself properly. +TEST(NanSensitiveFloatNearTest, CanDescribeSelfWithNaNs) { + Matcher<const ::std::tuple<float, float>&> m = NanSensitiveFloatNear(0.5f); + EXPECT_EQ("are an almost-equal pair", Describe(m)); +} + +// Tests that FloatEq() matches a 2-tuple where +// DoubleNear(first field, max_abs_error) matches the second field. +TEST(DoubleNear2Test, MatchesEqualArguments) { + typedef ::std::tuple<double, double> Tpl; + Matcher<const Tpl&> m = DoubleNear(0.5); + EXPECT_TRUE(m.Matches(Tpl(1.0, 1.0))); + EXPECT_TRUE(m.Matches(Tpl(1.3, 1.0))); + EXPECT_FALSE(m.Matches(Tpl(1.8, 1.0))); +} + +// Tests that DoubleNear() describes itself properly. +TEST(DoubleNear2Test, CanDescribeSelf) { + Matcher<const ::std::tuple<double, double>&> m = DoubleNear(0.5); + EXPECT_EQ("are an almost-equal pair", Describe(m)); +} + +// Tests that NanSensitiveDoubleNear() matches a 2-tuple where +// NanSensitiveDoubleNear(first field) matches the second field. +TEST(NanSensitiveDoubleNearTest, MatchesNearbyArgumentsWithNaN) { + typedef ::std::tuple<double, double> Tpl; + Matcher<const Tpl&> m = NanSensitiveDoubleNear(0.5f); + EXPECT_TRUE(m.Matches(Tpl(1.0f, 1.0f))); + EXPECT_TRUE(m.Matches(Tpl(1.1f, 1.0f))); + EXPECT_TRUE(m.Matches(Tpl(std::numeric_limits<double>::quiet_NaN(), + std::numeric_limits<double>::quiet_NaN()))); + EXPECT_FALSE(m.Matches(Tpl(1.6f, 1.0f))); + EXPECT_FALSE(m.Matches(Tpl(1.0f, std::numeric_limits<double>::quiet_NaN()))); + EXPECT_FALSE(m.Matches(Tpl(std::numeric_limits<double>::quiet_NaN(), 1.0f))); +} + +// Tests that NanSensitiveDoubleNear() describes itself properly. +TEST(NanSensitiveDoubleNearTest, CanDescribeSelfWithNaNs) { + Matcher<const ::std::tuple<double, double>&> m = NanSensitiveDoubleNear(0.5f); + EXPECT_EQ("are an almost-equal pair", Describe(m)); +} + // Tests that Not(m) matches any value that doesn't match m. TEST(NotTest, NegatesMatcher) { Matcher<int> m; @@ -2096,29 +2547,16 @@ TEST(AllOfTest, MatchesWhenAllMatch) { Ne(8), Ne(9))); AllOfMatches(10, AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5), Ne(6), Ne(7), Ne(8), Ne(9), Ne(10))); + AllOfMatches( + 50, AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5), Ne(6), Ne(7), Ne(8), Ne(9), + Ne(10), Ne(11), Ne(12), Ne(13), Ne(14), Ne(15), Ne(16), Ne(17), + Ne(18), Ne(19), Ne(20), Ne(21), Ne(22), Ne(23), Ne(24), Ne(25), + Ne(26), Ne(27), Ne(28), Ne(29), Ne(30), Ne(31), Ne(32), Ne(33), + Ne(34), Ne(35), Ne(36), Ne(37), Ne(38), Ne(39), Ne(40), Ne(41), + Ne(42), Ne(43), Ne(44), Ne(45), Ne(46), Ne(47), Ne(48), Ne(49), + Ne(50))); } -#if GTEST_LANG_CXX11 -// Tests the variadic version of the AllOfMatcher. -TEST(AllOfTest, VariadicMatchesWhenAllMatch) { - // Make sure AllOf is defined in the right namespace and does not depend on - // ADL. - ::testing::AllOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11); - Matcher<int> m = AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5), Ne(6), Ne(7), Ne(8), - Ne(9), Ne(10), Ne(11)); - EXPECT_THAT(Describe(m), EndsWith("and (isn't equal to 11))))))))))")); - AllOfMatches(11, m); - AllOfMatches(50, AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5), Ne(6), Ne(7), Ne(8), - Ne(9), Ne(10), Ne(11), Ne(12), Ne(13), Ne(14), Ne(15), - Ne(16), Ne(17), Ne(18), Ne(19), Ne(20), Ne(21), Ne(22), - Ne(23), Ne(24), Ne(25), Ne(26), Ne(27), Ne(28), Ne(29), - Ne(30), Ne(31), Ne(32), Ne(33), Ne(34), Ne(35), Ne(36), - Ne(37), Ne(38), Ne(39), Ne(40), Ne(41), Ne(42), Ne(43), - Ne(44), Ne(45), Ne(46), Ne(47), Ne(48), Ne(49), - Ne(50))); -} - -#endif // GTEST_LANG_CXX11 // Tests that AllOf(m1, ..., mn) describes itself properly. TEST(AllOfTest, CanDescribeSelf) { @@ -2127,59 +2565,51 @@ TEST(AllOfTest, CanDescribeSelf) { EXPECT_EQ("(is <= 2) and (is >= 1)", Describe(m)); m = AllOf(Gt(0), Ne(1), Ne(2)); - EXPECT_EQ("(is > 0) and " - "((isn't equal to 1) and " - "(isn't equal to 2))", - Describe(m)); - + std::string expected_descr1 = + "(is > 0) and (isn't equal to 1) and (isn't equal to 2)"; + EXPECT_EQ(expected_descr1, Describe(m)); m = AllOf(Gt(0), Ne(1), Ne(2), Ne(3)); - EXPECT_EQ("((is > 0) and " - "(isn't equal to 1)) and " - "((isn't equal to 2) and " - "(isn't equal to 3))", - Describe(m)); - + std::string expected_descr2 = + "(is > 0) and (isn't equal to 1) and (isn't equal to 2) and (isn't equal " + "to 3)"; + EXPECT_EQ(expected_descr2, Describe(m)); m = AllOf(Ge(0), Lt(10), Ne(3), Ne(5), Ne(7)); - EXPECT_EQ("((is >= 0) and " - "(is < 10)) and " - "((isn't equal to 3) and " - "((isn't equal to 5) and " - "(isn't equal to 7)))", - Describe(m)); + std::string expected_descr3 = + "(is >= 0) and (is < 10) and (isn't equal to 3) and (isn't equal to 5) " + "and (isn't equal to 7)"; + EXPECT_EQ(expected_descr3, Describe(m)); } // Tests that AllOf(m1, ..., mn) describes its negation properly. TEST(AllOfTest, CanDescribeNegation) { Matcher<int> m; m = AllOf(Le(2), Ge(1)); - EXPECT_EQ("(isn't <= 2) or " - "(isn't >= 1)", - DescribeNegation(m)); + std::string expected_descr4 = "(isn't <= 2) or (isn't >= 1)"; + EXPECT_EQ(expected_descr4, DescribeNegation(m)); m = AllOf(Gt(0), Ne(1), Ne(2)); - EXPECT_EQ("(isn't > 0) or " - "((is equal to 1) or " - "(is equal to 2))", - DescribeNegation(m)); - + std::string expected_descr5 = + "(isn't > 0) or (is equal to 1) or (is equal to 2)"; + EXPECT_EQ(expected_descr5, DescribeNegation(m)); m = AllOf(Gt(0), Ne(1), Ne(2), Ne(3)); - EXPECT_EQ("((isn't > 0) or " - "(is equal to 1)) or " - "((is equal to 2) or " - "(is equal to 3))", - DescribeNegation(m)); - + std::string expected_descr6 = + "(isn't > 0) or (is equal to 1) or (is equal to 2) or (is equal to 3)"; + EXPECT_EQ(expected_descr6, DescribeNegation(m)); m = AllOf(Ge(0), Lt(10), Ne(3), Ne(5), Ne(7)); - EXPECT_EQ("((isn't >= 0) or " - "(isn't < 10)) or " - "((is equal to 3) or " - "((is equal to 5) or " - "(is equal to 7)))", - DescribeNegation(m)); + std::string expected_desr7 = + "(isn't >= 0) or (isn't < 10) or (is equal to 3) or (is equal to 5) or " + "(is equal to 7)"; + EXPECT_EQ(expected_desr7, DescribeNegation(m)); + + m = AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5), Ne(6), Ne(7), Ne(8), Ne(9), + Ne(10), Ne(11)); + AllOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11); + EXPECT_THAT(Describe(m), EndsWith("and (isn't equal to 11)")); + AllOfMatches(11, m); } // Tests that monomorphic matchers are safely cast by the AllOf matcher. @@ -2241,7 +2671,7 @@ TEST(AllOfTest, ExplainsResult) { } // Helper to allow easy testing of AnyOf matchers with num parameters. -void AnyOfMatches(int num, const Matcher<int>& m) { +static void AnyOfMatches(int num, const Matcher<int>& m) { SCOPED_TRACE(Describe(m)); EXPECT_FALSE(m.Matches(0)); for (int i = 1; i <= num; ++i) { @@ -2250,6 +2680,18 @@ void AnyOfMatches(int num, const Matcher<int>& m) { EXPECT_FALSE(m.Matches(num + 1)); } +#if GTEST_LANG_CXX11 +static void AnyOfStringMatches(int num, const Matcher<std::string>& m) { + SCOPED_TRACE(Describe(m)); + EXPECT_FALSE(m.Matches(std::to_string(0))); + + for (int i = 1; i <= num; ++i) { + EXPECT_TRUE(m.Matches(std::to_string(i))); + } + EXPECT_FALSE(m.Matches(std::to_string(num + 1))); +} +#endif + // Tests that AnyOf(m1, ..., mn) matches any value that matches at // least one of the given matchers. TEST(AnyOfTest, MatchesWhenAnyMatches) { @@ -2300,13 +2742,46 @@ TEST(AnyOfTest, VariadicMatchesWhenAnyMatches) { // on ADL. Matcher<int> m = ::testing::AnyOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11); - EXPECT_THAT(Describe(m), EndsWith("or (is equal to 11))))))))))")); + EXPECT_THAT(Describe(m), EndsWith("or (is equal to 11)")); AnyOfMatches(11, m); AnyOfMatches(50, AnyOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50)); + AnyOfStringMatches( + 50, AnyOf("1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", + "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", + "23", "24", "25", "26", "27", "28", "29", "30", "31", "32", + "33", "34", "35", "36", "37", "38", "39", "40", "41", "42", + "43", "44", "45", "46", "47", "48", "49", "50")); +} + +// Tests the variadic version of the ElementsAreMatcher +TEST(ElementsAreTest, HugeMatcher) { + vector<int> test_vector{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}; + + EXPECT_THAT(test_vector, + ElementsAre(Eq(1), Eq(2), Lt(13), Eq(4), Eq(5), Eq(6), Eq(7), + Eq(8), Eq(9), Eq(10), Gt(1), Eq(12))); +} + +// Tests the variadic version of the UnorderedElementsAreMatcher +TEST(ElementsAreTest, HugeMatcherStr) { + vector<string> test_vector{ + "literal_string", "", "", "", "", "", "", "", "", "", "", ""}; + + EXPECT_THAT(test_vector, UnorderedElementsAre("literal_string", _, _, _, _, _, + _, _, _, _, _, _)); +} + +// Tests the variadic version of the UnorderedElementsAreMatcher +TEST(ElementsAreTest, HugeMatcherUnordered) { + vector<int> test_vector{2, 1, 8, 5, 4, 6, 7, 3, 9, 12, 11, 10}; + + EXPECT_THAT(test_vector, UnorderedElementsAre( + Eq(2), Eq(1), Gt(7), Eq(5), Eq(4), Eq(6), Eq(7), + Eq(3), Eq(9), Eq(12), Eq(11), Ne(122))); } #endif // GTEST_LANG_CXX11 @@ -2315,28 +2790,22 @@ TEST(AnyOfTest, VariadicMatchesWhenAnyMatches) { TEST(AnyOfTest, CanDescribeSelf) { Matcher<int> m; m = AnyOf(Le(1), Ge(3)); + EXPECT_EQ("(is <= 1) or (is >= 3)", Describe(m)); m = AnyOf(Lt(0), Eq(1), Eq(2)); - EXPECT_EQ("(is < 0) or " - "((is equal to 1) or (is equal to 2))", - Describe(m)); + EXPECT_EQ("(is < 0) or (is equal to 1) or (is equal to 2)", Describe(m)); m = AnyOf(Lt(0), Eq(1), Eq(2), Eq(3)); - EXPECT_EQ("((is < 0) or " - "(is equal to 1)) or " - "((is equal to 2) or " - "(is equal to 3))", + EXPECT_EQ("(is < 0) or (is equal to 1) or (is equal to 2) or (is equal to 3)", Describe(m)); m = AnyOf(Le(0), Gt(10), 3, 5, 7); - EXPECT_EQ("((is <= 0) or " - "(is > 10)) or " - "((is equal to 3) or " - "((is equal to 5) or " - "(is equal to 7)))", - Describe(m)); + EXPECT_EQ( + "(is <= 0) or (is > 10) or (is equal to 3) or (is equal to 5) or (is " + "equal to 7)", + Describe(m)); } // Tests that AnyOf(m1, ..., mn) describes its negation properly. @@ -2347,24 +2816,20 @@ TEST(AnyOfTest, CanDescribeNegation) { DescribeNegation(m)); m = AnyOf(Lt(0), Eq(1), Eq(2)); - EXPECT_EQ("(isn't < 0) and " - "((isn't equal to 1) and (isn't equal to 2))", + EXPECT_EQ("(isn't < 0) and (isn't equal to 1) and (isn't equal to 2)", DescribeNegation(m)); m = AnyOf(Lt(0), Eq(1), Eq(2), Eq(3)); - EXPECT_EQ("((isn't < 0) and " - "(isn't equal to 1)) and " - "((isn't equal to 2) and " - "(isn't equal to 3))", - DescribeNegation(m)); + EXPECT_EQ( + "(isn't < 0) and (isn't equal to 1) and (isn't equal to 2) and (isn't " + "equal to 3)", + DescribeNegation(m)); m = AnyOf(Le(0), Gt(10), 3, 5, 7); - EXPECT_EQ("((isn't <= 0) and " - "(isn't > 10)) and " - "((isn't equal to 3) and " - "((isn't equal to 5) and " - "(isn't equal to 7)))", - DescribeNegation(m)); + EXPECT_EQ( + "(isn't <= 0) and (isn't > 10) and (isn't equal to 3) and (isn't equal " + "to 5) and (isn't equal to 7)", + DescribeNegation(m)); } // Tests that monomorphic matchers are safely cast by the AnyOf matcher. @@ -2583,9 +3048,25 @@ TEST(ExplainMatchResultTest, WorksInsideMATCHER) { EXPECT_THAT(0, Really(Eq(0))); } +TEST(DescribeMatcherTest, WorksWithValue) { + EXPECT_EQ("is equal to 42", DescribeMatcher<int>(42)); + EXPECT_EQ("isn't equal to 42", DescribeMatcher<int>(42, true)); +} + +TEST(DescribeMatcherTest, WorksWithMonomorphicMatcher) { + const Matcher<int> monomorphic = Le(0); + EXPECT_EQ("is <= 0", DescribeMatcher<int>(monomorphic)); + EXPECT_EQ("isn't <= 0", DescribeMatcher<int>(monomorphic, true)); +} + +TEST(DescribeMatcherTest, WorksWithPolymorphicMatcher) { + EXPECT_EQ("is even", DescribeMatcher<int>(PolymorphicIsEven())); + EXPECT_EQ("is odd", DescribeMatcher<int>(PolymorphicIsEven(), true)); +} + TEST(AllArgsTest, WorksForTuple) { - EXPECT_THAT(make_tuple(1, 2L), AllArgs(Lt())); - EXPECT_THAT(make_tuple(2L, 1), Not(AllArgs(Lt()))); + EXPECT_THAT(std::make_tuple(1, 2L), AllArgs(Lt())); + EXPECT_THAT(std::make_tuple(2L, 1), Not(AllArgs(Lt()))); } TEST(AllArgsTest, WorksForNonTuple) { @@ -2617,6 +3098,44 @@ TEST(AllArgsTest, WorksInWithClause) { EXPECT_EQ(2, helper.Helper('a', 1)); } +class OptionalMatchersHelper { + public: + OptionalMatchersHelper() {} + + MOCK_METHOD0(NoArgs, int()); + + MOCK_METHOD1(OneArg, int(int y)); + + MOCK_METHOD2(TwoArgs, int(char x, int y)); + + MOCK_METHOD1(Overloaded, int(char x)); + MOCK_METHOD2(Overloaded, int(char x, int y)); + + private: + GTEST_DISALLOW_COPY_AND_ASSIGN_(OptionalMatchersHelper); +}; + +TEST(AllArgsTest, WorksWithoutMatchers) { + OptionalMatchersHelper helper; + + ON_CALL(helper, NoArgs).WillByDefault(Return(10)); + ON_CALL(helper, OneArg).WillByDefault(Return(20)); + ON_CALL(helper, TwoArgs).WillByDefault(Return(30)); + + EXPECT_EQ(10, helper.NoArgs()); + EXPECT_EQ(20, helper.OneArg(1)); + EXPECT_EQ(30, helper.TwoArgs('\1', 2)); + + EXPECT_CALL(helper, NoArgs).Times(1); + EXPECT_CALL(helper, OneArg).WillOnce(Return(100)); + EXPECT_CALL(helper, OneArg(17)).WillOnce(Return(200)); + EXPECT_CALL(helper, TwoArgs).Times(0); + + EXPECT_EQ(10, helper.NoArgs()); + EXPECT_EQ(100, helper.OneArg(1)); + EXPECT_EQ(200, helper.OneArg(17)); +} + // Tests that ASSERT_THAT() and EXPECT_THAT() work when the value // matches the matcher. TEST(MatcherAssertionTest, WorksWhenMatcherIsSatisfied) { @@ -2685,9 +3204,9 @@ TEST(MatcherAssertionTest, WorksForMonomorphicMatcher) { Matcher<const char*> starts_with_he = StartsWith("he"); ASSERT_THAT("hello", starts_with_he); - Matcher<const string&> ends_with_ok = EndsWith("ok"); + Matcher<const std::string&> ends_with_ok = EndsWith("ok"); ASSERT_THAT("book", ends_with_ok); - const string bad = "bad"; + const std::string bad = "bad"; EXPECT_NONFATAL_FAILURE(EXPECT_THAT(bad, ends_with_ok), "Value of: bad\n" "Expected: ends with \"ok\"\n" @@ -2712,18 +3231,22 @@ class FloatingPointTest : public testing::Test { zero_bits_(Floating(0).bits()), one_bits_(Floating(1).bits()), infinity_bits_(Floating(Floating::Infinity()).bits()), - close_to_positive_zero_(AsBits(zero_bits_ + max_ulps_/2)), - close_to_negative_zero_(AsBits(zero_bits_ + max_ulps_ - max_ulps_/2)), - further_from_negative_zero_(-AsBits( + close_to_positive_zero_( + Floating::ReinterpretBits(zero_bits_ + max_ulps_/2)), + close_to_negative_zero_( + -Floating::ReinterpretBits(zero_bits_ + max_ulps_ - max_ulps_/2)), + further_from_negative_zero_(-Floating::ReinterpretBits( zero_bits_ + max_ulps_ + 1 - max_ulps_/2)), - close_to_one_(AsBits(one_bits_ + max_ulps_)), - further_from_one_(AsBits(one_bits_ + max_ulps_ + 1)), + close_to_one_(Floating::ReinterpretBits(one_bits_ + max_ulps_)), + further_from_one_(Floating::ReinterpretBits(one_bits_ + max_ulps_ + 1)), infinity_(Floating::Infinity()), - close_to_infinity_(AsBits(infinity_bits_ - max_ulps_)), - further_from_infinity_(AsBits(infinity_bits_ - max_ulps_ - 1)), + close_to_infinity_( + Floating::ReinterpretBits(infinity_bits_ - max_ulps_)), + further_from_infinity_( + Floating::ReinterpretBits(infinity_bits_ - max_ulps_ - 1)), max_(Floating::Max()), - nan1_(AsBits(Floating::kExponentBitMask | 1)), - nan2_(AsBits(Floating::kExponentBitMask | 200)) { + nan1_(Floating::ReinterpretBits(Floating::kExponentBitMask | 1)), + nan2_(Floating::ReinterpretBits(Floating::kExponentBitMask | 200)) { } void TestSize() { @@ -2778,7 +3301,7 @@ class FloatingPointTest : public testing::Test { // Pre-calculated numbers to be used by the tests. - const size_t max_ulps_; + const Bits max_ulps_; const Bits zero_bits_; // The bits that represent 0.0. const Bits one_bits_; // The bits that represent 1.0. @@ -2804,12 +3327,6 @@ class FloatingPointTest : public testing::Test { // Some NaNs. const RawType nan1_; const RawType nan2_; - - private: - template <typename T> - static RawType AsBits(T value) { - return Floating::ReinterpretBits(static_cast<Bits>(value)); - } }; // Tests floating-point matchers with fixed epsilons. @@ -3099,7 +3616,8 @@ TEST_F(DoubleNearTest, ExplainsResultWhenMatchFails) { EXPECT_EQ("which is 0.2 from 2", Explain(DoubleNear(2.0, 0.1), 2.2)); EXPECT_EQ("which is -0.3 from 2", Explain(DoubleNear(2.0, 0.1), 1.7)); - const string explanation = Explain(DoubleNear(2.1, 1e-10), 2.1 + 1.2e-10); + const std::string explanation = + Explain(DoubleNear(2.1, 1e-10), 2.1 + 1.2e-10); // Different C++ implementations may print floating-point numbers // slightly differently. EXPECT_TRUE(explanation == "which is 1.2e-10 from 2.1" || // GCC @@ -3146,7 +3664,7 @@ TEST(PointeeTest, RawPointer) { EXPECT_TRUE(m.Matches(&n)); n = -1; EXPECT_FALSE(m.Matches(&n)); - EXPECT_FALSE(m.Matches(NULL)); + EXPECT_FALSE(m.Matches(nullptr)); } TEST(PointeeTest, RawPointerToConst) { @@ -3156,7 +3674,7 @@ TEST(PointeeTest, RawPointerToConst) { EXPECT_TRUE(m.Matches(&x)); x = -1; EXPECT_FALSE(m.Matches(&x)); - EXPECT_FALSE(m.Matches(NULL)); + EXPECT_FALSE(m.Matches(nullptr)); } TEST(PointeeTest, ReferenceToConstRawPointer) { @@ -3166,7 +3684,7 @@ TEST(PointeeTest, ReferenceToConstRawPointer) { EXPECT_TRUE(m.Matches(&n)); n = -1; EXPECT_FALSE(m.Matches(&n)); - EXPECT_FALSE(m.Matches(NULL)); + EXPECT_FALSE(m.Matches(nullptr)); } TEST(PointeeTest, ReferenceToNonConstRawPointer) { @@ -3177,7 +3695,7 @@ TEST(PointeeTest, ReferenceToNonConstRawPointer) { EXPECT_TRUE(m.Matches(p)); x = -1; EXPECT_FALSE(m.Matches(p)); - p = NULL; + p = nullptr; EXPECT_FALSE(m.Matches(p)); } @@ -3186,7 +3704,6 @@ MATCHER_P(FieldIIs, inner_matcher, "") { } #if GTEST_HAS_RTTI - TEST(WhenDynamicCastToTest, SameType) { Derived derived; derived.i = 4; @@ -3217,7 +3734,7 @@ TEST(WhenDynamicCastToTest, WrongTypes) { TEST(WhenDynamicCastToTest, AlreadyNull) { // Already NULL. - Base* as_base_ptr = NULL; + Base* as_base_ptr = nullptr; EXPECT_THAT(as_base_ptr, WhenDynamicCastTo<Derived*>(IsNull())); } @@ -3244,7 +3761,7 @@ TEST(WhenDynamicCastToTest, AmbiguousCast) { TEST(WhenDynamicCastToTest, Describe) { Matcher<Base*> matcher = WhenDynamicCastTo<Derived*>(Pointee(_)); - const string prefix = + const std::string prefix = "when dynamic_cast to " + internal::GetTypeName<Derived*>() + ", "; EXPECT_EQ(prefix + "points to a value that is anything", Describe(matcher)); EXPECT_EQ(prefix + "does not point to a value that is anything", @@ -3253,7 +3770,7 @@ TEST(WhenDynamicCastToTest, Describe) { TEST(WhenDynamicCastToTest, Explain) { Matcher<Base*> matcher = WhenDynamicCastTo<Derived*>(Pointee(_)); - Base* null = NULL; + Base* null = nullptr; EXPECT_THAT(Explain(matcher, null), HasSubstr("NULL")); Derived derived; EXPECT_TRUE(matcher.Matches(&derived)); @@ -3278,7 +3795,6 @@ TEST(WhenDynamicCastToTest, BadReference) { Base& as_base_ref = derived; EXPECT_THAT(as_base_ref, Not(WhenDynamicCastTo<const OtherDerived&>(_))); } - #endif // GTEST_HAS_RTTI // Minimal const-propagating pointer. @@ -3315,7 +3831,7 @@ TEST(PointeeTest, WorksWithConstPropagatingPointers) { TEST(PointeeTest, NeverMatchesNull) { const Matcher<const char*> m = Pointee(_); - EXPECT_FALSE(m.Matches(NULL)); + EXPECT_FALSE(m.Matches(nullptr)); } // Tests that we can write Pointee(value) instead of Pointee(Eq(value)). @@ -3326,7 +3842,7 @@ TEST(PointeeTest, MatchesAgainstAValue) { EXPECT_TRUE(m.Matches(&n)); n = -1; EXPECT_FALSE(m.Matches(&n)); - EXPECT_FALSE(m.Matches(NULL)); + EXPECT_FALSE(m.Matches(nullptr)); } TEST(PointeeTest, CanDescribeSelf) { @@ -3337,9 +3853,9 @@ TEST(PointeeTest, CanDescribeSelf) { } TEST(PointeeTest, CanExplainMatchResult) { - const Matcher<const string*> m = Pointee(StartsWith("Hi")); + const Matcher<const std::string*> m = Pointee(StartsWith("Hi")); - EXPECT_EQ("", Explain(m, static_cast<const string*>(NULL))); + EXPECT_EQ("", Explain(m, static_cast<const std::string*>(nullptr))); const Matcher<long*> m2 = Pointee(GreaterThan(1)); // NOLINT long n = 3; // NOLINT @@ -3376,7 +3892,7 @@ MATCHER_P(UncopyableIs, inner_matcher, "") { // A user-defined struct for testing Field(). struct AStruct { - AStruct() : x(0), y(1.0), z(5), p(NULL) {} + AStruct() : x(0), y(1.0), z(5), p(nullptr) {} AStruct(const AStruct& rhs) : x(rhs.x), y(rhs.y), z(rhs.z.value()), p(rhs.p) {} @@ -3400,11 +3916,14 @@ struct DerivedStruct : public AStruct { // Tests that Field(&Foo::field, ...) works when field is non-const. TEST(FieldTest, WorksForNonConstField) { Matcher<AStruct> m = Field(&AStruct::x, Ge(0)); + Matcher<AStruct> m_with_name = Field("x", &AStruct::x, Ge(0)); AStruct a; EXPECT_TRUE(m.Matches(a)); + EXPECT_TRUE(m_with_name.Matches(a)); a.x = -1; EXPECT_FALSE(m.Matches(a)); + EXPECT_FALSE(m_with_name.Matches(a)); } // Tests that Field(&Foo::field, ...) works when field is const. @@ -3412,9 +3931,13 @@ TEST(FieldTest, WorksForConstField) { AStruct a; Matcher<AStruct> m = Field(&AStruct::y, Ge(0.0)); + Matcher<AStruct> m_with_name = Field("y", &AStruct::y, Ge(0.0)); EXPECT_TRUE(m.Matches(a)); + EXPECT_TRUE(m_with_name.Matches(a)); m = Field(&AStruct::y, Le(0.0)); + m_with_name = Field("y", &AStruct::y, Le(0.0)); EXPECT_FALSE(m.Matches(a)); + EXPECT_FALSE(m_with_name.Matches(a)); } // Tests that Field(&Foo::field, ...) works when field is not copyable. @@ -3430,7 +3953,7 @@ TEST(FieldTest, WorksForUncopyableField) { // Tests that Field(&Foo::field, ...) works when field is a pointer. TEST(FieldTest, WorksForPointerField) { // Matching against NULL. - Matcher<AStruct> m = Field(&AStruct::p, static_cast<const char*>(NULL)); + Matcher<AStruct> m = Field(&AStruct::p, static_cast<const char*>(nullptr)); AStruct a; EXPECT_TRUE(m.Matches(a)); a.p = "hi"; @@ -3488,6 +4011,14 @@ TEST(FieldTest, CanDescribeSelf) { EXPECT_EQ("is an object whose given field isn't >= 0", DescribeNegation(m)); } +TEST(FieldTest, CanDescribeSelfWithFieldName) { + Matcher<const AStruct&> m = Field("field_name", &AStruct::x, Ge(0)); + + EXPECT_EQ("is an object whose field `field_name` is >= 0", Describe(m)); + EXPECT_EQ("is an object whose field `field_name` isn't >= 0", + DescribeNegation(m)); +} + // Tests that Field() can explain the match result. TEST(FieldTest, CanExplainMatchResult) { Matcher<const AStruct&> m = Field(&AStruct::x, Ge(0)); @@ -3502,6 +4033,19 @@ TEST(FieldTest, CanExplainMatchResult) { Explain(m, a)); } +TEST(FieldTest, CanExplainMatchResultWithFieldName) { + Matcher<const AStruct&> m = Field("field_name", &AStruct::x, Ge(0)); + + AStruct a; + a.x = 1; + EXPECT_EQ("whose field `field_name` is 1" + OfType("int"), Explain(m, a)); + + m = Field("field_name", &AStruct::x, GreaterThan(0)); + EXPECT_EQ("whose field `field_name` is 1" + OfType("int") + + ", which is 1 more than 0", + Explain(m, a)); +} + // Tests that Field() works when the argument is a pointer to const. TEST(FieldForPointerTest, WorksForPointerToConst) { Matcher<const AStruct*> m = Field(&AStruct::x, Ge(0)); @@ -3535,7 +4079,7 @@ TEST(FieldForPointerTest, WorksForReferenceToConstPointer) { // Tests that Field() does not match the NULL pointer. TEST(FieldForPointerTest, DoesNotMatchNull) { Matcher<const AStruct*> m = Field(&AStruct::x, _); - EXPECT_FALSE(m.Matches(NULL)); + EXPECT_FALSE(m.Matches(nullptr)); } // Tests that Field(&Foo::field, ...) works when the argument's type @@ -3559,13 +4103,21 @@ TEST(FieldForPointerTest, CanDescribeSelf) { EXPECT_EQ("is an object whose given field isn't >= 0", DescribeNegation(m)); } +TEST(FieldForPointerTest, CanDescribeSelfWithFieldName) { + Matcher<const AStruct*> m = Field("field_name", &AStruct::x, Ge(0)); + + EXPECT_EQ("is an object whose field `field_name` is >= 0", Describe(m)); + EXPECT_EQ("is an object whose field `field_name` isn't >= 0", + DescribeNegation(m)); +} + // Tests that Field() can explain the result of matching a pointer. TEST(FieldForPointerTest, CanExplainMatchResult) { Matcher<const AStruct*> m = Field(&AStruct::x, Ge(0)); AStruct a; a.x = 1; - EXPECT_EQ("", Explain(m, static_cast<const AStruct*>(NULL))); + EXPECT_EQ("", Explain(m, static_cast<const AStruct*>(nullptr))); EXPECT_EQ("which points to an object whose given field is 1" + OfType("int"), Explain(m, &a)); @@ -3574,6 +4126,22 @@ TEST(FieldForPointerTest, CanExplainMatchResult) { ", which is 1 more than 0", Explain(m, &a)); } +TEST(FieldForPointerTest, CanExplainMatchResultWithFieldName) { + Matcher<const AStruct*> m = Field("field_name", &AStruct::x, Ge(0)); + + AStruct a; + a.x = 1; + EXPECT_EQ("", Explain(m, static_cast<const AStruct*>(nullptr))); + EXPECT_EQ( + "which points to an object whose field `field_name` is 1" + OfType("int"), + Explain(m, &a)); + + m = Field("field_name", &AStruct::x, GreaterThan(0)); + EXPECT_EQ("which points to an object whose field `field_name` is 1" + + OfType("int") + ", which is 1 more than 0", + Explain(m, &a)); +} + // A user-defined class for testing Property(). class AClass { public: @@ -3585,15 +4153,20 @@ class AClass { void set_n(int new_n) { n_ = new_n; } // A getter that returns a reference to const. - const string& s() const { return s_; } + const std::string& s() const { return s_; } + +#if GTEST_LANG_CXX11 + const std::string& s_ref() const & { return s_; } +#endif - void set_s(const string& new_s) { s_ = new_s; } + void set_s(const std::string& new_s) { s_ = new_s; } // A getter that returns a reference to non-const. double& x() const { return x_; } + private: int n_; - string s_; + std::string s_; static double x_; }; @@ -3612,27 +4185,53 @@ class DerivedClass : public AClass { // returns a non-reference. TEST(PropertyTest, WorksForNonReferenceProperty) { Matcher<const AClass&> m = Property(&AClass::n, Ge(0)); + Matcher<const AClass&> m_with_name = Property("n", &AClass::n, Ge(0)); AClass a; a.set_n(1); EXPECT_TRUE(m.Matches(a)); + EXPECT_TRUE(m_with_name.Matches(a)); a.set_n(-1); EXPECT_FALSE(m.Matches(a)); + EXPECT_FALSE(m_with_name.Matches(a)); } // Tests that Property(&Foo::property, ...) works when property() // returns a reference to const. TEST(PropertyTest, WorksForReferenceToConstProperty) { Matcher<const AClass&> m = Property(&AClass::s, StartsWith("hi")); + Matcher<const AClass&> m_with_name = + Property("s", &AClass::s, StartsWith("hi")); + + AClass a; + a.set_s("hill"); + EXPECT_TRUE(m.Matches(a)); + EXPECT_TRUE(m_with_name.Matches(a)); + + a.set_s("hole"); + EXPECT_FALSE(m.Matches(a)); + EXPECT_FALSE(m_with_name.Matches(a)); +} + +#if GTEST_LANG_CXX11 +// Tests that Property(&Foo::property, ...) works when property() is +// ref-qualified. +TEST(PropertyTest, WorksForRefQualifiedProperty) { + Matcher<const AClass&> m = Property(&AClass::s_ref, StartsWith("hi")); + Matcher<const AClass&> m_with_name = + Property("s", &AClass::s_ref, StartsWith("hi")); AClass a; a.set_s("hill"); EXPECT_TRUE(m.Matches(a)); + EXPECT_TRUE(m_with_name.Matches(a)); a.set_s("hole"); EXPECT_FALSE(m.Matches(a)); + EXPECT_FALSE(m_with_name.Matches(a)); } +#endif // Tests that Property(&Foo::property, ...) works when property() // returns a reference to non-const. @@ -3682,10 +4281,15 @@ TEST(PropertyTest, WorksForCompatibleMatcherType) { Matcher<const AClass&> m = Property(&AClass::n, Matcher<signed char>(Ge(0))); + Matcher<const AClass&> m_with_name = + Property("n", &AClass::n, Matcher<signed char>(Ge(0))); + AClass a; EXPECT_TRUE(m.Matches(a)); + EXPECT_TRUE(m_with_name.Matches(a)); a.set_n(-1); EXPECT_FALSE(m.Matches(a)); + EXPECT_FALSE(m_with_name.Matches(a)); } // Tests that Property() can describe itself. @@ -3697,6 +4301,14 @@ TEST(PropertyTest, CanDescribeSelf) { DescribeNegation(m)); } +TEST(PropertyTest, CanDescribeSelfWithPropertyName) { + Matcher<const AClass&> m = Property("fancy_name", &AClass::n, Ge(0)); + + EXPECT_EQ("is an object whose property `fancy_name` is >= 0", Describe(m)); + EXPECT_EQ("is an object whose property `fancy_name` isn't >= 0", + DescribeNegation(m)); +} + // Tests that Property() can explain the match result. TEST(PropertyTest, CanExplainMatchResult) { Matcher<const AClass&> m = Property(&AClass::n, Ge(0)); @@ -3711,6 +4323,19 @@ TEST(PropertyTest, CanExplainMatchResult) { Explain(m, a)); } +TEST(PropertyTest, CanExplainMatchResultWithPropertyName) { + Matcher<const AClass&> m = Property("fancy_name", &AClass::n, Ge(0)); + + AClass a; + a.set_n(1); + EXPECT_EQ("whose property `fancy_name` is 1" + OfType("int"), Explain(m, a)); + + m = Property("fancy_name", &AClass::n, GreaterThan(0)); + EXPECT_EQ("whose property `fancy_name` is 1" + OfType("int") + + ", which is 1 more than 0", + Explain(m, a)); +} + // Tests that Property() works when the argument is a pointer to const. TEST(PropertyForPointerTest, WorksForPointerToConst) { Matcher<const AClass*> m = Property(&AClass::n, Ge(0)); @@ -3751,7 +4376,7 @@ TEST(PropertyForPointerTest, WorksForReferenceToConstPointer) { // Tests that Property() does not match the NULL pointer. TEST(PropertyForPointerTest, WorksForReferenceToNonConstProperty) { Matcher<const AClass*> m = Property(&AClass::x, _); - EXPECT_FALSE(m.Matches(NULL)); + EXPECT_FALSE(m.Matches(nullptr)); } // Tests that Property(&Foo::property, ...) works when the argument's @@ -3778,13 +4403,21 @@ TEST(PropertyForPointerTest, CanDescribeSelf) { DescribeNegation(m)); } +TEST(PropertyForPointerTest, CanDescribeSelfWithPropertyDescription) { + Matcher<const AClass*> m = Property("fancy_name", &AClass::n, Ge(0)); + + EXPECT_EQ("is an object whose property `fancy_name` is >= 0", Describe(m)); + EXPECT_EQ("is an object whose property `fancy_name` isn't >= 0", + DescribeNegation(m)); +} + // Tests that Property() can explain the result of matching a pointer. TEST(PropertyForPointerTest, CanExplainMatchResult) { Matcher<const AClass*> m = Property(&AClass::n, Ge(0)); AClass a; a.set_n(1); - EXPECT_EQ("", Explain(m, static_cast<const AClass*>(NULL))); + EXPECT_EQ("", Explain(m, static_cast<const AClass*>(nullptr))); EXPECT_EQ( "which points to an object whose given property is 1" + OfType("int"), Explain(m, &a)); @@ -3795,14 +4428,32 @@ TEST(PropertyForPointerTest, CanExplainMatchResult) { Explain(m, &a)); } +TEST(PropertyForPointerTest, CanExplainMatchResultWithPropertyName) { + Matcher<const AClass*> m = Property("fancy_name", &AClass::n, Ge(0)); + + AClass a; + a.set_n(1); + EXPECT_EQ("", Explain(m, static_cast<const AClass*>(nullptr))); + EXPECT_EQ("which points to an object whose property `fancy_name` is 1" + + OfType("int"), + Explain(m, &a)); + + m = Property("fancy_name", &AClass::n, GreaterThan(0)); + EXPECT_EQ("which points to an object whose property `fancy_name` is 1" + + OfType("int") + ", which is 1 more than 0", + Explain(m, &a)); +} + // Tests ResultOf. // Tests that ResultOf(f, ...) compiles and works as expected when f is a // function pointer. -string IntToStringFunction(int input) { return input == 1 ? "foo" : "bar"; } +std::string IntToStringFunction(int input) { + return input == 1 ? "foo" : "bar"; +} TEST(ResultOfTest, WorksForFunctionPointers) { - Matcher<int> matcher = ResultOf(&IntToStringFunction, Eq(string("foo"))); + Matcher<int> matcher = ResultOf(&IntToStringFunction, Eq(std::string("foo"))); EXPECT_TRUE(matcher.Matches(1)); EXPECT_FALSE(matcher.Matches(2)); @@ -3868,12 +4519,12 @@ TEST(ResultOfTest, WorksForReferenceToNonConstResults) { // Tests that ResultOf(f, ...) compiles and works as expected when f(x) // returns a reference to const. -const string& StringFunction(const string& input) { return input; } +const std::string& StringFunction(const std::string& input) { return input; } TEST(ResultOfTest, WorksForReferenceToConstResults) { - string s = "foo"; - string s2 = s; - Matcher<const string&> matcher = ResultOf(&StringFunction, Ref(s)); + std::string s = "foo"; + std::string s2 = s; + Matcher<const std::string&> matcher = ResultOf(&StringFunction, Ref(s)); EXPECT_TRUE(matcher.Matches(s)); EXPECT_FALSE(matcher.Matches(s2)); @@ -3893,8 +4544,9 @@ TEST(ResultOfTest, WorksForCompatibleMatcherTypes) { // a NULL function pointer. TEST(ResultOfDeathTest, DiesOnNullFunctionPointers) { EXPECT_DEATH_IF_SUPPORTED( - ResultOf(static_cast<string(*)(int dummy)>(NULL), Eq(string("foo"))), - "NULL function pointer is passed into ResultOf\\(\\)\\."); + ResultOf(static_cast<std::string (*)(int dummy)>(nullptr), + Eq(std::string("foo"))), + "NULL function pointer is passed into ResultOf\\(\\)\\."); } // Tests that ResultOf(f, ...) compiles and works as expected when f is a @@ -3907,26 +4559,27 @@ TEST(ResultOfTest, WorksForFunctionReferences) { // Tests that ResultOf(f, ...) compiles and works as expected when f is a // function object. -struct Functor : public ::std::unary_function<int, string> { +struct Functor : public ::std::unary_function<int, std::string> { result_type operator()(argument_type input) const { return IntToStringFunction(input); } }; TEST(ResultOfTest, WorksForFunctors) { - Matcher<int> matcher = ResultOf(Functor(), Eq(string("foo"))); + Matcher<int> matcher = ResultOf(Functor(), Eq(std::string("foo"))); EXPECT_TRUE(matcher.Matches(1)); EXPECT_FALSE(matcher.Matches(2)); } // Tests that ResultOf(f, ...) compiles and works as expected when f is a -// functor with more then one operator() defined. ResultOf() must work +// functor with more than one operator() defined. ResultOf() must work // for each defined operator(). struct PolymorphicFunctor { typedef int result_type; int operator()(int n) { return n; } int operator()(const char* s) { return static_cast<int>(strlen(s)); } + std::string operator()(int *p) { return p ? "good ptr" : "null"; } }; TEST(ResultOfTest, WorksForPolymorphicFunctors) { @@ -3941,6 +4594,23 @@ TEST(ResultOfTest, WorksForPolymorphicFunctors) { EXPECT_FALSE(matcher_string.Matches("shrt")); } +#if GTEST_LANG_CXX11 +TEST(ResultOfTest, WorksForPolymorphicFunctorsIgnoringResultType) { + Matcher<int*> matcher = ResultOf(PolymorphicFunctor(), "good ptr"); + + int n = 0; + EXPECT_TRUE(matcher.Matches(&n)); + EXPECT_FALSE(matcher.Matches(nullptr)); +} + +TEST(ResultOfTest, WorksForLambdas) { + Matcher<int> matcher = + ResultOf([](int str_len) { return std::string(str_len, 'x'); }, "xxx"); + EXPECT_TRUE(matcher.Matches(3)); + EXPECT_FALSE(matcher.Matches(1)); +} +#endif + const int* ReferencingFunction(const int& n) { return &n; } struct ReferencingFunctor { @@ -4080,11 +4750,11 @@ TEST(IsEmptyTest, ImplementsIsEmpty) { } TEST(IsEmptyTest, WorksWithString) { - string text; + std::string text; EXPECT_THAT(text, IsEmpty()); text = "foo"; EXPECT_THAT(text, Not(IsEmpty())); - text = string("\0", 1); + text = std::string("\0", 1); EXPECT_THAT(text, Not(IsEmpty())); } @@ -4102,6 +4772,44 @@ TEST(IsEmptyTest, ExplainsResult) { EXPECT_EQ("whose size is 1", Explain(m, container)); } +TEST(IsTrueTest, IsTrueIsFalse) { + EXPECT_THAT(true, IsTrue()); + EXPECT_THAT(false, IsFalse()); + EXPECT_THAT(true, Not(IsFalse())); + EXPECT_THAT(false, Not(IsTrue())); + EXPECT_THAT(0, Not(IsTrue())); + EXPECT_THAT(0, IsFalse()); + EXPECT_THAT(NULL, Not(IsTrue())); + EXPECT_THAT(NULL, IsFalse()); + EXPECT_THAT(-1, IsTrue()); + EXPECT_THAT(-1, Not(IsFalse())); + EXPECT_THAT(1, IsTrue()); + EXPECT_THAT(1, Not(IsFalse())); + EXPECT_THAT(2, IsTrue()); + EXPECT_THAT(2, Not(IsFalse())); + int a = 42; + EXPECT_THAT(a, IsTrue()); + EXPECT_THAT(a, Not(IsFalse())); + EXPECT_THAT(&a, IsTrue()); + EXPECT_THAT(&a, Not(IsFalse())); + EXPECT_THAT(false, Not(IsTrue())); + EXPECT_THAT(true, Not(IsFalse())); +#if GTEST_LANG_CXX11 + EXPECT_THAT(std::true_type(), IsTrue()); + EXPECT_THAT(std::true_type(), Not(IsFalse())); + EXPECT_THAT(std::false_type(), IsFalse()); + EXPECT_THAT(std::false_type(), Not(IsTrue())); + EXPECT_THAT(nullptr, Not(IsTrue())); + EXPECT_THAT(nullptr, IsFalse()); + std::unique_ptr<int> null_unique; + std::unique_ptr<int> nonnull_unique(new int(0)); + EXPECT_THAT(null_unique, Not(IsTrue())); + EXPECT_THAT(null_unique, IsFalse()); + EXPECT_THAT(nonnull_unique, IsTrue()); + EXPECT_THAT(nonnull_unique, Not(IsFalse())); +#endif // GTEST_LANG_CXX11 +} + TEST(SizeIsTest, ImplementsSizeIs) { vector<int> container; EXPECT_THAT(container, SizeIs(0)); @@ -4115,7 +4823,7 @@ TEST(SizeIsTest, ImplementsSizeIs) { } TEST(SizeIsTest, WorksWithMap) { - map<string, int> container; + map<std::string, int> container; EXPECT_THAT(container, SizeIs(0)); EXPECT_THAT(container, Not(SizeIs(1))); container.insert(make_pair("foo", 1)); @@ -4235,7 +4943,7 @@ TYPED_TEST(ContainerEqTest, DuplicateDifference) { #endif // GTEST_HAS_TYPED_TEST // Tests that mutliple missing values are reported. -// Using just vector here, so order is predicatble. +// Using just vector here, so order is predictable. TEST(ContainerEqExtraTest, MultipleValuesMissing) { static const int vals[] = {1, 1, 2, 3, 5, 8}; static const int test_vals[] = {2, 1, 5}; @@ -4248,7 +4956,7 @@ TEST(ContainerEqExtraTest, MultipleValuesMissing) { } // Tests that added values are reported. -// Using just vector here, so order is predicatble. +// Using just vector here, so order is predictable. TEST(ContainerEqExtraTest, MultipleValuesAdded) { static const int vals[] = {1, 1, 2, 3, 5, 8}; static const int test_vals[] = {1, 2, 92, 3, 5, 8, 46}; @@ -4336,11 +5044,11 @@ TEST(ContainerEqExtraTest, WorksForNativeArrayAsTuple) { const int b[] = {1, 2, 3, 4}; const int* const p1 = a1; - EXPECT_THAT(make_tuple(p1, 3), ContainerEq(a2)); - EXPECT_THAT(make_tuple(p1, 3), Not(ContainerEq(b))); + EXPECT_THAT(std::make_tuple(p1, 3), ContainerEq(a2)); + EXPECT_THAT(std::make_tuple(p1, 3), Not(ContainerEq(b))); const int c[] = {1, 3, 2}; - EXPECT_THAT(make_tuple(p1, 3), Not(ContainerEq(c))); + EXPECT_THAT(std::make_tuple(p1, 3), Not(ContainerEq(c))); } TEST(ContainerEqExtraTest, CopiesNativeArrayParameter) { @@ -4380,13 +5088,13 @@ TEST(WhenSortedByTest, WorksForNonEmptyContainer) { } TEST(WhenSortedByTest, WorksForNonVectorContainer) { - list<string> words; + list<std::string> words; words.push_back("say"); words.push_back("hello"); words.push_back("world"); - EXPECT_THAT(words, WhenSortedBy(less<string>(), + EXPECT_THAT(words, WhenSortedBy(less<std::string>(), ElementsAre("hello", "say", "world"))); - EXPECT_THAT(words, Not(WhenSortedBy(less<string>(), + EXPECT_THAT(words, Not(WhenSortedBy(less<std::string>(), ElementsAre("say", "hello", "world")))); } @@ -4429,7 +5137,7 @@ TEST(WhenSortedTest, WorksForEmptyContainer) { } TEST(WhenSortedTest, WorksForNonEmptyContainer) { - list<string> words; + list<std::string> words; words.push_back("3"); words.push_back("1"); words.push_back("2"); @@ -4439,14 +5147,16 @@ TEST(WhenSortedTest, WorksForNonEmptyContainer) { } TEST(WhenSortedTest, WorksForMapTypes) { - map<string, int> word_counts; - word_counts["and"] = 1; - word_counts["the"] = 1; - word_counts["buffalo"] = 2; - EXPECT_THAT(word_counts, WhenSorted(ElementsAre( - Pair("and", 1), Pair("buffalo", 2), Pair("the", 1)))); - EXPECT_THAT(word_counts, Not(WhenSorted(ElementsAre( - Pair("and", 1), Pair("the", 1), Pair("buffalo", 2))))); + map<std::string, int> word_counts; + word_counts["and"] = 1; + word_counts["the"] = 1; + word_counts["buffalo"] = 2; + EXPECT_THAT(word_counts, + WhenSorted(ElementsAre(Pair("and", 1), Pair("buffalo", 2), + Pair("the", 1)))); + EXPECT_THAT(word_counts, + Not(WhenSorted(ElementsAre(Pair("and", 1), Pair("the", 1), + Pair("buffalo", 2))))); } TEST(WhenSortedTest, WorksForMultiMapTypes) { @@ -4654,6 +5364,250 @@ TEST(WhenSortedTest, WorksForVectorConstRefMatcherOnStreamlike) { EXPECT_THAT(s, Not(WhenSorted(ElementsAre(2, 1, 4, 5, 3)))); } +TEST(IsSupersetOfTest, WorksForNativeArray) { + const int subset[] = {1, 4}; + const int superset[] = {1, 2, 4}; + const int disjoint[] = {1, 0, 3}; + EXPECT_THAT(subset, IsSupersetOf(subset)); + EXPECT_THAT(subset, Not(IsSupersetOf(superset))); + EXPECT_THAT(superset, IsSupersetOf(subset)); + EXPECT_THAT(subset, Not(IsSupersetOf(disjoint))); + EXPECT_THAT(disjoint, Not(IsSupersetOf(subset))); +} + +TEST(IsSupersetOfTest, WorksWithDuplicates) { + const int not_enough[] = {1, 2}; + const int enough[] = {1, 1, 2}; + const int expected[] = {1, 1}; + EXPECT_THAT(not_enough, Not(IsSupersetOf(expected))); + EXPECT_THAT(enough, IsSupersetOf(expected)); +} + +TEST(IsSupersetOfTest, WorksForEmpty) { + vector<int> numbers; + vector<int> expected; + EXPECT_THAT(numbers, IsSupersetOf(expected)); + expected.push_back(1); + EXPECT_THAT(numbers, Not(IsSupersetOf(expected))); + expected.clear(); + numbers.push_back(1); + numbers.push_back(2); + EXPECT_THAT(numbers, IsSupersetOf(expected)); + expected.push_back(1); + EXPECT_THAT(numbers, IsSupersetOf(expected)); + expected.push_back(2); + EXPECT_THAT(numbers, IsSupersetOf(expected)); + expected.push_back(3); + EXPECT_THAT(numbers, Not(IsSupersetOf(expected))); +} + +TEST(IsSupersetOfTest, WorksForStreamlike) { + const int a[5] = {1, 2, 3, 4, 5}; + Streamlike<int> s(a, a + GTEST_ARRAY_SIZE_(a)); + + vector<int> expected; + expected.push_back(1); + expected.push_back(2); + expected.push_back(5); + EXPECT_THAT(s, IsSupersetOf(expected)); + + expected.push_back(0); + EXPECT_THAT(s, Not(IsSupersetOf(expected))); +} + +TEST(IsSupersetOfTest, TakesStlContainer) { + const int actual[] = {3, 1, 2}; + + ::std::list<int> expected; + expected.push_back(1); + expected.push_back(3); + EXPECT_THAT(actual, IsSupersetOf(expected)); + + expected.push_back(4); + EXPECT_THAT(actual, Not(IsSupersetOf(expected))); +} + +TEST(IsSupersetOfTest, Describe) { + typedef std::vector<int> IntVec; + IntVec expected; + expected.push_back(111); + expected.push_back(222); + expected.push_back(333); + EXPECT_THAT( + Describe<IntVec>(IsSupersetOf(expected)), + Eq("a surjection from elements to requirements exists such that:\n" + " - an element is equal to 111\n" + " - an element is equal to 222\n" + " - an element is equal to 333")); +} + +TEST(IsSupersetOfTest, DescribeNegation) { + typedef std::vector<int> IntVec; + IntVec expected; + expected.push_back(111); + expected.push_back(222); + expected.push_back(333); + EXPECT_THAT( + DescribeNegation<IntVec>(IsSupersetOf(expected)), + Eq("no surjection from elements to requirements exists such that:\n" + " - an element is equal to 111\n" + " - an element is equal to 222\n" + " - an element is equal to 333")); +} + +TEST(IsSupersetOfTest, MatchAndExplain) { + std::vector<int> v; + v.push_back(2); + v.push_back(3); + std::vector<int> expected; + expected.push_back(1); + expected.push_back(2); + StringMatchResultListener listener; + ASSERT_FALSE(ExplainMatchResult(IsSupersetOf(expected), v, &listener)) + << listener.str(); + EXPECT_THAT(listener.str(), + Eq("where the following matchers don't match any elements:\n" + "matcher #0: is equal to 1")); + + v.push_back(1); + listener.Clear(); + ASSERT_TRUE(ExplainMatchResult(IsSupersetOf(expected), v, &listener)) + << listener.str(); + EXPECT_THAT(listener.str(), Eq("where:\n" + " - element #0 is matched by matcher #1,\n" + " - element #2 is matched by matcher #0")); +} + +#if GTEST_HAS_STD_INITIALIZER_LIST_ +TEST(IsSupersetOfTest, WorksForRhsInitializerList) { + const int numbers[] = {1, 3, 6, 2, 4, 5}; + EXPECT_THAT(numbers, IsSupersetOf({1, 2})); + EXPECT_THAT(numbers, Not(IsSupersetOf({3, 0}))); +} +#endif + +TEST(IsSubsetOfTest, WorksForNativeArray) { + const int subset[] = {1, 4}; + const int superset[] = {1, 2, 4}; + const int disjoint[] = {1, 0, 3}; + EXPECT_THAT(subset, IsSubsetOf(subset)); + EXPECT_THAT(subset, IsSubsetOf(superset)); + EXPECT_THAT(superset, Not(IsSubsetOf(subset))); + EXPECT_THAT(subset, Not(IsSubsetOf(disjoint))); + EXPECT_THAT(disjoint, Not(IsSubsetOf(subset))); +} + +TEST(IsSubsetOfTest, WorksWithDuplicates) { + const int not_enough[] = {1, 2}; + const int enough[] = {1, 1, 2}; + const int actual[] = {1, 1}; + EXPECT_THAT(actual, Not(IsSubsetOf(not_enough))); + EXPECT_THAT(actual, IsSubsetOf(enough)); +} + +TEST(IsSubsetOfTest, WorksForEmpty) { + vector<int> numbers; + vector<int> expected; + EXPECT_THAT(numbers, IsSubsetOf(expected)); + expected.push_back(1); + EXPECT_THAT(numbers, IsSubsetOf(expected)); + expected.clear(); + numbers.push_back(1); + numbers.push_back(2); + EXPECT_THAT(numbers, Not(IsSubsetOf(expected))); + expected.push_back(1); + EXPECT_THAT(numbers, Not(IsSubsetOf(expected))); + expected.push_back(2); + EXPECT_THAT(numbers, IsSubsetOf(expected)); + expected.push_back(3); + EXPECT_THAT(numbers, IsSubsetOf(expected)); +} + +TEST(IsSubsetOfTest, WorksForStreamlike) { + const int a[5] = {1, 2}; + Streamlike<int> s(a, a + GTEST_ARRAY_SIZE_(a)); + + vector<int> expected; + expected.push_back(1); + EXPECT_THAT(s, Not(IsSubsetOf(expected))); + expected.push_back(2); + expected.push_back(5); + EXPECT_THAT(s, IsSubsetOf(expected)); +} + +TEST(IsSubsetOfTest, TakesStlContainer) { + const int actual[] = {3, 1, 2}; + + ::std::list<int> expected; + expected.push_back(1); + expected.push_back(3); + EXPECT_THAT(actual, Not(IsSubsetOf(expected))); + + expected.push_back(2); + expected.push_back(4); + EXPECT_THAT(actual, IsSubsetOf(expected)); +} + +TEST(IsSubsetOfTest, Describe) { + typedef std::vector<int> IntVec; + IntVec expected; + expected.push_back(111); + expected.push_back(222); + expected.push_back(333); + + EXPECT_THAT( + Describe<IntVec>(IsSubsetOf(expected)), + Eq("an injection from elements to requirements exists such that:\n" + " - an element is equal to 111\n" + " - an element is equal to 222\n" + " - an element is equal to 333")); +} + +TEST(IsSubsetOfTest, DescribeNegation) { + typedef std::vector<int> IntVec; + IntVec expected; + expected.push_back(111); + expected.push_back(222); + expected.push_back(333); + EXPECT_THAT( + DescribeNegation<IntVec>(IsSubsetOf(expected)), + Eq("no injection from elements to requirements exists such that:\n" + " - an element is equal to 111\n" + " - an element is equal to 222\n" + " - an element is equal to 333")); +} + +TEST(IsSubsetOfTest, MatchAndExplain) { + std::vector<int> v; + v.push_back(2); + v.push_back(3); + std::vector<int> expected; + expected.push_back(1); + expected.push_back(2); + StringMatchResultListener listener; + ASSERT_FALSE(ExplainMatchResult(IsSubsetOf(expected), v, &listener)) + << listener.str(); + EXPECT_THAT(listener.str(), + Eq("where the following elements don't match any matchers:\n" + "element #1: 3")); + + expected.push_back(3); + listener.Clear(); + ASSERT_TRUE(ExplainMatchResult(IsSubsetOf(expected), v, &listener)) + << listener.str(); + EXPECT_THAT(listener.str(), Eq("where:\n" + " - element #0 is matched by matcher #1,\n" + " - element #1 is matched by matcher #2")); +} + +#if GTEST_HAS_STD_INITIALIZER_LIST_ +TEST(IsSubsetOfTest, WorksForRhsInitializerList) { + const int numbers[] = {1, 2, 3}; + EXPECT_THAT(numbers, IsSubsetOf({1, 2, 3, 4})); + EXPECT_THAT(numbers, Not(IsSubsetOf({1, 2}))); +} +#endif + // Tests using ElementsAre() and ElementsAreArray() with stream-like // "containers". @@ -4763,7 +5717,7 @@ TEST(UnorderedElementsAreArrayTest, TakesInitializerList) { } TEST(UnorderedElementsAreArrayTest, TakesInitializerListOfCStrings) { - const string a[5] = {"a", "b", "c", "d", "e"}; + const std::string a[5] = {"a", "b", "c", "d", "e"}; EXPECT_THAT(a, UnorderedElementsAreArray({"a", "b", "c", "d", "e"})); EXPECT_THAT(a, Not(UnorderedElementsAreArray({"a", "b", "c", "d", "ef"}))); } @@ -4937,7 +5891,7 @@ TEST_F(UnorderedElementsAreTest, FailMessageUnmatchedMatcherAndElement) { } // Test helper for formatting element, matcher index pairs in expectations. -static string EMString(int element, int matcher) { +static std::string EMString(int element, int matcher) { stringstream ss; ss << "(element #" << element << ", matcher #" << matcher << ")"; return ss.str(); @@ -4946,7 +5900,7 @@ static string EMString(int element, int matcher) { TEST_F(UnorderedElementsAreTest, FailMessageImperfectMatchOnly) { // A situation where all elements and matchers have a match // associated with them, but the max matching is not perfect. - std::vector<string> v; + std::vector<std::string> v; v.push_back("a"); v.push_back("b"); v.push_back("c"); @@ -4955,7 +5909,7 @@ TEST_F(UnorderedElementsAreTest, FailMessageImperfectMatchOnly) { UnorderedElementsAre("a", "a", AnyOf("b", "c")), v, &listener)) << listener.str(); - string prefix = + std::string prefix = "where no permutation of the elements can satisfy all matchers, " "and the closest match is 2 of 3 matchers with the " "pairings:\n"; @@ -5190,7 +6144,7 @@ TEST_P(BipartiteRandomTest, LargerNets) { testing::internal::Int32 seed = GTEST_FLAG(random_seed); if (seed == 0) { - seed = static_cast<testing::internal::Int32>(time(NULL)); + seed = static_cast<testing::internal::Int32>(time(nullptr)); } for (; iters > 0; --iters, ++seed) { @@ -5238,28 +6192,6 @@ TEST(IsReadableTypeNameTest, ReturnsFalseForLongFunctionTypeNames) { EXPECT_FALSE(IsReadableTypeName("void (&)(int, bool, char, float)")); } -// Tests JoinAsTuple(). - -TEST(JoinAsTupleTest, JoinsEmptyTuple) { - EXPECT_EQ("", JoinAsTuple(Strings())); -} - -TEST(JoinAsTupleTest, JoinsOneTuple) { - const char* fields[] = {"1"}; - EXPECT_EQ("1", JoinAsTuple(Strings(fields, fields + 1))); -} - -TEST(JoinAsTupleTest, JoinsTwoTuple) { - const char* fields[] = {"1", "a"}; - EXPECT_EQ("(1, a)", JoinAsTuple(Strings(fields, fields + 2))); -} - -TEST(JoinAsTupleTest, JoinsTenTuple) { - const char* fields[] = {"1", "2", "3", "4", "5", "6", "7", "8", "9", "10"}; - EXPECT_EQ("(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)", - JoinAsTuple(Strings(fields, fields + 10))); -} - // Tests FormatMatcherDescription(). TEST(FormatMatcherDescriptionTest, WorksForEmptyDescription) { @@ -5298,13 +6230,15 @@ TEST(PolymorphicMatcherTest, CanAccessImpl) { TEST(MatcherTupleTest, ExplainsMatchFailure) { stringstream ss1; - ExplainMatchFailureTupleTo(make_tuple(Matcher<char>(Eq('a')), GreaterThan(5)), - make_tuple('a', 10), &ss1); + ExplainMatchFailureTupleTo( + std::make_tuple(Matcher<char>(Eq('a')), GreaterThan(5)), + std::make_tuple('a', 10), &ss1); EXPECT_EQ("", ss1.str()); // Successful match. stringstream ss2; - ExplainMatchFailureTupleTo(make_tuple(GreaterThan(5), Matcher<char>(Eq('a'))), - make_tuple(2, 'b'), &ss2); + ExplainMatchFailureTupleTo( + std::make_tuple(GreaterThan(5), Matcher<char>(Eq('a'))), + std::make_tuple(2, 'b'), &ss2); EXPECT_EQ(" Expected arg #0: is > 5\n" " Actual: 2, which is 3 less than 5\n" " Expected arg #1: is equal to 'a' (97, 0x61)\n" @@ -5312,8 +6246,9 @@ TEST(MatcherTupleTest, ExplainsMatchFailure) { ss2.str()); // Failed match where both arguments need explanation. stringstream ss3; - ExplainMatchFailureTupleTo(make_tuple(GreaterThan(5), Matcher<char>(Eq('a'))), - make_tuple(2, 'a'), &ss3); + ExplainMatchFailureTupleTo( + std::make_tuple(GreaterThan(5), Matcher<char>(Eq('a'))), + std::make_tuple(2, 'a'), &ss3); EXPECT_EQ(" Expected arg #0: is > 5\n" " Actual: 2, which is 3 less than 5\n", ss3.str()); // Failed match where only one argument needs @@ -5366,13 +6301,13 @@ TEST(EachTest, MatchesVectorWhenAllElementsMatch) { EXPECT_THAT(some_vector, Not(Each(3))); EXPECT_THAT(some_vector, Each(Lt(3.5))); - vector<string> another_vector; + vector<std::string> another_vector; another_vector.push_back("fee"); - EXPECT_THAT(another_vector, Each(string("fee"))); + EXPECT_THAT(another_vector, Each(std::string("fee"))); another_vector.push_back("fie"); another_vector.push_back("foe"); another_vector.push_back("fum"); - EXPECT_THAT(another_vector, Not(Each(string("fee")))); + EXPECT_THAT(another_vector, Not(Each(std::string("fee")))); } TEST(EachTest, MatchesMapWhenAllElementsMatch) { @@ -5381,15 +6316,15 @@ TEST(EachTest, MatchesMapWhenAllElementsMatch) { my_map[bar] = 2; EXPECT_THAT(my_map, Each(make_pair(bar, 2))); - map<string, int> another_map; - EXPECT_THAT(another_map, Each(make_pair(string("fee"), 1))); + map<std::string, int> another_map; + EXPECT_THAT(another_map, Each(make_pair(std::string("fee"), 1))); another_map["fee"] = 1; - EXPECT_THAT(another_map, Each(make_pair(string("fee"), 1))); + EXPECT_THAT(another_map, Each(make_pair(std::string("fee"), 1))); another_map["fie"] = 2; another_map["foe"] = 3; another_map["fum"] = 4; - EXPECT_THAT(another_map, Not(Each(make_pair(string("fee"), 1)))); - EXPECT_THAT(another_map, Not(Each(make_pair(string("fum"), 1)))); + EXPECT_THAT(another_map, Not(Each(make_pair(std::string("fee"), 1)))); + EXPECT_THAT(another_map, Not(Each(make_pair(std::string("fum"), 1)))); EXPECT_THAT(another_map, Each(Pair(_, Gt(0)))); } @@ -5402,21 +6337,21 @@ TEST(EachTest, AcceptsMatcher) { TEST(EachTest, WorksForNativeArrayAsTuple) { const int a[] = {1, 2}; const int* const pointer = a; - EXPECT_THAT(make_tuple(pointer, 2), Each(Gt(0))); - EXPECT_THAT(make_tuple(pointer, 2), Not(Each(Gt(1)))); + EXPECT_THAT(std::make_tuple(pointer, 2), Each(Gt(0))); + EXPECT_THAT(std::make_tuple(pointer, 2), Not(Each(Gt(1)))); } // For testing Pointwise(). class IsHalfOfMatcher { public: template <typename T1, typename T2> - bool MatchAndExplain(const tuple<T1, T2>& a_pair, + bool MatchAndExplain(const std::tuple<T1, T2>& a_pair, MatchResultListener* listener) const { - if (get<0>(a_pair) == get<1>(a_pair)/2) { - *listener << "where the second is " << get<1>(a_pair); + if (std::get<0>(a_pair) == std::get<1>(a_pair) / 2) { + *listener << "where the second is " << std::get<1>(a_pair); return true; } else { - *listener << "where the second/2 is " << get<1>(a_pair)/2; + *listener << "where the second/2 is " << std::get<1>(a_pair) / 2; return false; } } @@ -5483,6 +6418,16 @@ TEST(PointwiseTest, WorksForRhsNativeArray) { EXPECT_THAT(lhs, Not(Pointwise(Lt(), rhs))); } +// Test is effective only with sanitizers. +TEST(PointwiseTest, WorksForVectorOfBool) { + vector<bool> rhs(3, false); + rhs[1] = true; + vector<bool> lhs = rhs; + EXPECT_THAT(lhs, Pointwise(Eq(), rhs)); + rhs[0] = true; + EXPECT_THAT(lhs, Not(Pointwise(Eq(), rhs))); +} + #if GTEST_HAS_STD_INITIALIZER_LIST_ TEST(PointwiseTest, WorksForRhsInitializerList) { @@ -5523,13 +6468,13 @@ TEST(PointwiseTest, AcceptsCorrectContent) { TEST(PointwiseTest, AllowsMonomorphicInnerMatcher) { const double lhs[3] = {1, 2, 3}; const int rhs[3] = {2, 4, 6}; - const Matcher<tuple<const double&, const int&> > m1 = IsHalfOf(); + const Matcher<std::tuple<const double&, const int&>> m1 = IsHalfOf(); EXPECT_THAT(lhs, Pointwise(m1, rhs)); EXPECT_EQ("", Explain(Pointwise(m1, rhs), lhs)); - // This type works as a tuple<const double&, const int&> can be - // implicitly cast to tuple<double, int>. - const Matcher<tuple<double, int> > m2 = IsHalfOf(); + // This type works as a std::tuple<const double&, const int&> can be + // implicitly cast to std::tuple<double, int>. + const Matcher<std::tuple<double, int>> m2 = IsHalfOf(); EXPECT_THAT(lhs, Pointwise(m2, rhs)); EXPECT_EQ("", Explain(Pointwise(m2, rhs), lhs)); } @@ -5639,14 +6584,207 @@ TEST(UnorderedPointwiseTest, AcceptsCorrectContentInDifferentOrder) { TEST(UnorderedPointwiseTest, AllowsMonomorphicInnerMatcher) { const double lhs[3] = {1, 2, 3}; const int rhs[3] = {4, 6, 2}; - const Matcher<tuple<const double&, const int&> > m1 = IsHalfOf(); + const Matcher<std::tuple<const double&, const int&>> m1 = IsHalfOf(); EXPECT_THAT(lhs, UnorderedPointwise(m1, rhs)); - // This type works as a tuple<const double&, const int&> can be - // implicitly cast to tuple<double, int>. - const Matcher<tuple<double, int> > m2 = IsHalfOf(); + // This type works as a std::tuple<const double&, const int&> can be + // implicitly cast to std::tuple<double, int>. + const Matcher<std::tuple<double, int>> m2 = IsHalfOf(); EXPECT_THAT(lhs, UnorderedPointwise(m2, rhs)); } +// Sample optional type implementation with minimal requirements for use with +// Optional matcher. +class SampleOptionalInt { + public: + typedef int value_type; + explicit SampleOptionalInt(int value) : value_(value), has_value_(true) {} + SampleOptionalInt() : value_(0), has_value_(false) {} + operator bool() const { + return has_value_; + } + const int& operator*() const { + return value_; + } + private: + int value_; + bool has_value_; +}; + +TEST(OptionalTest, DescribesSelf) { + const Matcher<SampleOptionalInt> m = Optional(Eq(1)); + EXPECT_EQ("value is equal to 1", Describe(m)); +} + +TEST(OptionalTest, ExplainsSelf) { + const Matcher<SampleOptionalInt> m = Optional(Eq(1)); + EXPECT_EQ("whose value 1 matches", Explain(m, SampleOptionalInt(1))); + EXPECT_EQ("whose value 2 doesn't match", Explain(m, SampleOptionalInt(2))); +} + +TEST(OptionalTest, MatchesNonEmptyOptional) { + const Matcher<SampleOptionalInt> m1 = Optional(1); + const Matcher<SampleOptionalInt> m2 = Optional(Eq(2)); + const Matcher<SampleOptionalInt> m3 = Optional(Lt(3)); + SampleOptionalInt opt(1); + EXPECT_TRUE(m1.Matches(opt)); + EXPECT_FALSE(m2.Matches(opt)); + EXPECT_TRUE(m3.Matches(opt)); +} + +TEST(OptionalTest, DoesNotMatchNullopt) { + const Matcher<SampleOptionalInt> m = Optional(1); + SampleOptionalInt empty; + EXPECT_FALSE(m.Matches(empty)); +} + +class SampleVariantIntString { + public: + SampleVariantIntString(int i) : i_(i), has_int_(true) {} + SampleVariantIntString(const std::string& s) : s_(s), has_int_(false) {} + + template <typename T> + friend bool holds_alternative(const SampleVariantIntString& value) { + return value.has_int_ == internal::IsSame<T, int>::value; + } + + template <typename T> + friend const T& get(const SampleVariantIntString& value) { + return value.get_impl(static_cast<T*>(nullptr)); + } + + private: + const int& get_impl(int*) const { return i_; } + const std::string& get_impl(std::string*) const { return s_; } + + int i_; + std::string s_; + bool has_int_; +}; + +TEST(VariantTest, DescribesSelf) { + const Matcher<SampleVariantIntString> m = VariantWith<int>(Eq(1)); + EXPECT_THAT(Describe(m), ContainsRegex("is a variant<> with value of type " + "'.*' and the value is equal to 1")); +} + +TEST(VariantTest, ExplainsSelf) { + const Matcher<SampleVariantIntString> m = VariantWith<int>(Eq(1)); + EXPECT_THAT(Explain(m, SampleVariantIntString(1)), + ContainsRegex("whose value 1")); + EXPECT_THAT(Explain(m, SampleVariantIntString("A")), + HasSubstr("whose value is not of type '")); + EXPECT_THAT(Explain(m, SampleVariantIntString(2)), + "whose value 2 doesn't match"); +} + +TEST(VariantTest, FullMatch) { + Matcher<SampleVariantIntString> m = VariantWith<int>(Eq(1)); + EXPECT_TRUE(m.Matches(SampleVariantIntString(1))); + + m = VariantWith<std::string>(Eq("1")); + EXPECT_TRUE(m.Matches(SampleVariantIntString("1"))); +} + +TEST(VariantTest, TypeDoesNotMatch) { + Matcher<SampleVariantIntString> m = VariantWith<int>(Eq(1)); + EXPECT_FALSE(m.Matches(SampleVariantIntString("1"))); + + m = VariantWith<std::string>(Eq("1")); + EXPECT_FALSE(m.Matches(SampleVariantIntString(1))); +} + +TEST(VariantTest, InnerDoesNotMatch) { + Matcher<SampleVariantIntString> m = VariantWith<int>(Eq(1)); + EXPECT_FALSE(m.Matches(SampleVariantIntString(2))); + + m = VariantWith<std::string>(Eq("1")); + EXPECT_FALSE(m.Matches(SampleVariantIntString("2"))); +} + +class SampleAnyType { + public: + explicit SampleAnyType(int i) : index_(0), i_(i) {} + explicit SampleAnyType(const std::string& s) : index_(1), s_(s) {} + + template <typename T> + friend const T* any_cast(const SampleAnyType* any) { + return any->get_impl(static_cast<T*>(nullptr)); + } + + private: + int index_; + int i_; + std::string s_; + + const int* get_impl(int*) const { return index_ == 0 ? &i_ : nullptr; } + const std::string* get_impl(std::string*) const { + return index_ == 1 ? &s_ : nullptr; + } +}; + +TEST(AnyWithTest, FullMatch) { + Matcher<SampleAnyType> m = AnyWith<int>(Eq(1)); + EXPECT_TRUE(m.Matches(SampleAnyType(1))); +} + +TEST(AnyWithTest, TestBadCastType) { + Matcher<SampleAnyType> m = AnyWith<std::string>(Eq("fail")); + EXPECT_FALSE(m.Matches(SampleAnyType(1))); +} + +#if GTEST_LANG_CXX11 +TEST(AnyWithTest, TestUseInContainers) { + std::vector<SampleAnyType> a; + a.emplace_back(1); + a.emplace_back(2); + a.emplace_back(3); + EXPECT_THAT( + a, ElementsAreArray({AnyWith<int>(1), AnyWith<int>(2), AnyWith<int>(3)})); + + std::vector<SampleAnyType> b; + b.emplace_back("hello"); + b.emplace_back("merhaba"); + b.emplace_back("salut"); + EXPECT_THAT(b, ElementsAreArray({AnyWith<std::string>("hello"), + AnyWith<std::string>("merhaba"), + AnyWith<std::string>("salut")})); +} +#endif // GTEST_LANG_CXX11 +TEST(AnyWithTest, TestCompare) { + EXPECT_THAT(SampleAnyType(1), AnyWith<int>(Gt(0))); +} + +TEST(AnyWithTest, DescribesSelf) { + const Matcher<const SampleAnyType&> m = AnyWith<int>(Eq(1)); + EXPECT_THAT(Describe(m), ContainsRegex("is an 'any' type with value of type " + "'.*' and the value is equal to 1")); +} + +TEST(AnyWithTest, ExplainsSelf) { + const Matcher<const SampleAnyType&> m = AnyWith<int>(Eq(1)); + + EXPECT_THAT(Explain(m, SampleAnyType(1)), ContainsRegex("whose value 1")); + EXPECT_THAT(Explain(m, SampleAnyType("A")), + HasSubstr("whose value is not of type '")); + EXPECT_THAT(Explain(m, SampleAnyType(2)), "whose value 2 doesn't match"); +} + +#if GTEST_LANG_CXX11 + +TEST(PointeeTest, WorksOnMoveOnlyType) { + std::unique_ptr<int> p(new int(3)); + EXPECT_THAT(p, Pointee(Eq(3))); + EXPECT_THAT(p, Not(Pointee(Eq(2)))); +} + +TEST(NotTest, WorksOnMoveOnlyType) { + std::unique_ptr<int> p(new int(3)); + EXPECT_THAT(p, Pointee(Eq(3))); + EXPECT_THAT(p, Not(Pointee(Eq(2)))); +} + +#endif // GTEST_LANG_CXX11 + } // namespace gmock_matchers_test } // namespace testing diff --git a/googlemock/test/gmock-more-actions_test.cc b/googlemock/test/gmock-more-actions_test.cc index 77e15bd..521f305 100644 --- a/googlemock/test/gmock-more-actions_test.cc +++ b/googlemock/test/gmock-more-actions_test.cc @@ -26,8 +26,7 @@ // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -// -// Author: wan@google.com (Zhanyong Wan) + // Google Mock - a framework for writing C++ mock classes. // @@ -47,10 +46,6 @@ namespace gmock_more_actions_test { using ::std::plus; using ::std::string; -using testing::get; -using testing::make_tuple; -using testing::tuple; -using testing::tuple_element; using testing::_; using testing::Action; using testing::ActionInterface; @@ -94,12 +89,12 @@ const char* Plus1(const char* s) { return s + 1; } void VoidUnary(int /* n */) { g_done = true; } -bool ByConstRef(const string& s) { return s == "Hi"; } +bool ByConstRef(const std::string& s) { return s == "Hi"; } const double g_double = 0; bool ReferencesGlobalDouble(const double& x) { return &x == &g_double; } -string ByNonConstRef(string& s) { return s += "+"; } // NOLINT +std::string ByNonConstRef(std::string& s) { return s += "+"; } // NOLINT struct UnaryFunctor { int operator()(bool x) { return x ? 1 : -1; } @@ -119,9 +114,9 @@ int SumOfFirst2(int a, int b, Unused, Unused) { return a + b; } void VoidFunctionWithFourArguments(char, int, float, double) { g_done = true; } -string Concat4(const char* s1, const char* s2, const char* s3, - const char* s4) { - return string(s1) + s2 + s3 + s4; +std::string Concat4(const char* s1, const char* s2, const char* s3, + const char* s4) { + return std::string(s1) + s2 + s3 + s4; } int SumOf5(int a, int b, int c, int d, int e) { return a + b + c + d + e; } @@ -132,9 +127,9 @@ struct SumOf5Functor { } }; -string Concat5(const char* s1, const char* s2, const char* s3, - const char* s4, const char* s5) { - return string(s1) + s2 + s3 + s4 + s5; +std::string Concat5(const char* s1, const char* s2, const char* s3, + const char* s4, const char* s5) { + return std::string(s1) + s2 + s3 + s4 + s5; } int SumOf6(int a, int b, int c, int d, int e, int f) { @@ -147,34 +142,34 @@ struct SumOf6Functor { } }; -string Concat6(const char* s1, const char* s2, const char* s3, - const char* s4, const char* s5, const char* s6) { - return string(s1) + s2 + s3 + s4 + s5 + s6; +std::string Concat6(const char* s1, const char* s2, const char* s3, + const char* s4, const char* s5, const char* s6) { + return std::string(s1) + s2 + s3 + s4 + s5 + s6; } -string Concat7(const char* s1, const char* s2, const char* s3, - const char* s4, const char* s5, const char* s6, - const char* s7) { - return string(s1) + s2 + s3 + s4 + s5 + s6 + s7; +std::string Concat7(const char* s1, const char* s2, const char* s3, + const char* s4, const char* s5, const char* s6, + const char* s7) { + return std::string(s1) + s2 + s3 + s4 + s5 + s6 + s7; } -string Concat8(const char* s1, const char* s2, const char* s3, - const char* s4, const char* s5, const char* s6, - const char* s7, const char* s8) { - return string(s1) + s2 + s3 + s4 + s5 + s6 + s7 + s8; +std::string Concat8(const char* s1, const char* s2, const char* s3, + const char* s4, const char* s5, const char* s6, + const char* s7, const char* s8) { + return std::string(s1) + s2 + s3 + s4 + s5 + s6 + s7 + s8; } -string Concat9(const char* s1, const char* s2, const char* s3, - const char* s4, const char* s5, const char* s6, - const char* s7, const char* s8, const char* s9) { - return string(s1) + s2 + s3 + s4 + s5 + s6 + s7 + s8 + s9; +std::string Concat9(const char* s1, const char* s2, const char* s3, + const char* s4, const char* s5, const char* s6, + const char* s7, const char* s8, const char* s9) { + return std::string(s1) + s2 + s3 + s4 + s5 + s6 + s7 + s8 + s9; } -string Concat10(const char* s1, const char* s2, const char* s3, - const char* s4, const char* s5, const char* s6, - const char* s7, const char* s8, const char* s9, - const char* s10) { - return string(s1) + s2 + s3 + s4 + s5 + s6 + s7 + s8 + s9 + s10; +std::string Concat10(const char* s1, const char* s2, const char* s3, + const char* s4, const char* s5, const char* s6, + const char* s7, const char* s8, const char* s9, + const char* s10) { + return std::string(s1) + s2 + s3 + s4 + s5 + s6 + s7 + s8 + s9 + s10; } class Foo { @@ -185,7 +180,7 @@ class Foo { short Unary(long x) { return static_cast<short>(value_ + x); } // NOLINT - string Binary(const string& str, char c) const { return str + c; } + std::string Binary(const std::string& str, char c) const { return str + c; } int Ternary(int x, bool y, char z) { return value_ + x + y*z; } @@ -201,29 +196,29 @@ class Foo { return a + b + c + d + e + f; } - string Concat7(const char* s1, const char* s2, const char* s3, - const char* s4, const char* s5, const char* s6, - const char* s7) { - return string(s1) + s2 + s3 + s4 + s5 + s6 + s7; + std::string Concat7(const char* s1, const char* s2, const char* s3, + const char* s4, const char* s5, const char* s6, + const char* s7) { + return std::string(s1) + s2 + s3 + s4 + s5 + s6 + s7; } - string Concat8(const char* s1, const char* s2, const char* s3, - const char* s4, const char* s5, const char* s6, - const char* s7, const char* s8) { - return string(s1) + s2 + s3 + s4 + s5 + s6 + s7 + s8; + std::string Concat8(const char* s1, const char* s2, const char* s3, + const char* s4, const char* s5, const char* s6, + const char* s7, const char* s8) { + return std::string(s1) + s2 + s3 + s4 + s5 + s6 + s7 + s8; } - string Concat9(const char* s1, const char* s2, const char* s3, - const char* s4, const char* s5, const char* s6, - const char* s7, const char* s8, const char* s9) { - return string(s1) + s2 + s3 + s4 + s5 + s6 + s7 + s8 + s9; + std::string Concat9(const char* s1, const char* s2, const char* s3, + const char* s4, const char* s5, const char* s6, + const char* s7, const char* s8, const char* s9) { + return std::string(s1) + s2 + s3 + s4 + s5 + s6 + s7 + s8 + s9; } - string Concat10(const char* s1, const char* s2, const char* s3, - const char* s4, const char* s5, const char* s6, - const char* s7, const char* s8, const char* s9, - const char* s10) { - return string(s1) + s2 + s3 + s4 + s5 + s6 + s7 + s8 + s9 + s10; + std::string Concat10(const char* s1, const char* s2, const char* s3, + const char* s4, const char* s5, const char* s6, + const char* s7, const char* s8, const char* s9, + const char* s10) { + return std::string(s1) + s2 + s3 + s4 + s5 + s6 + s7 + s8 + s9 + s10; } private: @@ -233,45 +228,46 @@ class Foo { // Tests using Invoke() with a nullary function. TEST(InvokeTest, Nullary) { Action<int()> a = Invoke(Nullary); // NOLINT - EXPECT_EQ(1, a.Perform(make_tuple())); + EXPECT_EQ(1, a.Perform(std::make_tuple())); } // Tests using Invoke() with a unary function. TEST(InvokeTest, Unary) { Action<bool(int)> a = Invoke(Unary); // NOLINT - EXPECT_FALSE(a.Perform(make_tuple(1))); - EXPECT_TRUE(a.Perform(make_tuple(-1))); + EXPECT_FALSE(a.Perform(std::make_tuple(1))); + EXPECT_TRUE(a.Perform(std::make_tuple(-1))); } // Tests using Invoke() with a binary function. TEST(InvokeTest, Binary) { Action<const char*(const char*, short)> a = Invoke(Binary); // NOLINT const char* p = "Hello"; - EXPECT_EQ(p + 2, a.Perform(make_tuple(p, Short(2)))); + EXPECT_EQ(p + 2, a.Perform(std::make_tuple(p, Short(2)))); } // Tests using Invoke() with a ternary function. TEST(InvokeTest, Ternary) { Action<int(int, char, short)> a = Invoke(Ternary); // NOLINT - EXPECT_EQ(6, a.Perform(make_tuple(1, '\2', Short(3)))); + EXPECT_EQ(6, a.Perform(std::make_tuple(1, '\2', Short(3)))); } // Tests using Invoke() with a 4-argument function. TEST(InvokeTest, FunctionThatTakes4Arguments) { Action<int(int, int, int, int)> a = Invoke(SumOf4); // NOLINT - EXPECT_EQ(1234, a.Perform(make_tuple(1000, 200, 30, 4))); + EXPECT_EQ(1234, a.Perform(std::make_tuple(1000, 200, 30, 4))); } // Tests using Invoke() with a 5-argument function. TEST(InvokeTest, FunctionThatTakes5Arguments) { Action<int(int, int, int, int, int)> a = Invoke(SumOf5); // NOLINT - EXPECT_EQ(12345, a.Perform(make_tuple(10000, 2000, 300, 40, 5))); + EXPECT_EQ(12345, a.Perform(std::make_tuple(10000, 2000, 300, 40, 5))); } // Tests using Invoke() with a 6-argument function. TEST(InvokeTest, FunctionThatTakes6Arguments) { Action<int(int, int, int, int, int, int)> a = Invoke(SumOf6); // NOLINT - EXPECT_EQ(123456, a.Perform(make_tuple(100000, 20000, 3000, 400, 50, 6))); + EXPECT_EQ(123456, + a.Perform(std::make_tuple(100000, 20000, 3000, 400, 50, 6))); } // A helper that turns the type of a C-string literal from const @@ -280,84 +276,85 @@ inline const char* CharPtr(const char* s) { return s; } // Tests using Invoke() with a 7-argument function. TEST(InvokeTest, FunctionThatTakes7Arguments) { - Action<string(const char*, const char*, const char*, const char*, - const char*, const char*, const char*)> a = - Invoke(Concat7); + Action<std::string(const char*, const char*, const char*, const char*, + const char*, const char*, const char*)> + a = Invoke(Concat7); EXPECT_EQ("1234567", - a.Perform(make_tuple(CharPtr("1"), CharPtr("2"), CharPtr("3"), - CharPtr("4"), CharPtr("5"), CharPtr("6"), - CharPtr("7")))); + a.Perform(std::make_tuple(CharPtr("1"), CharPtr("2"), CharPtr("3"), + CharPtr("4"), CharPtr("5"), CharPtr("6"), + CharPtr("7")))); } // Tests using Invoke() with a 8-argument function. TEST(InvokeTest, FunctionThatTakes8Arguments) { - Action<string(const char*, const char*, const char*, const char*, - const char*, const char*, const char*, const char*)> a = - Invoke(Concat8); + Action<std::string(const char*, const char*, const char*, const char*, + const char*, const char*, const char*, const char*)> + a = Invoke(Concat8); EXPECT_EQ("12345678", - a.Perform(make_tuple(CharPtr("1"), CharPtr("2"), CharPtr("3"), - CharPtr("4"), CharPtr("5"), CharPtr("6"), - CharPtr("7"), CharPtr("8")))); + a.Perform(std::make_tuple(CharPtr("1"), CharPtr("2"), CharPtr("3"), + CharPtr("4"), CharPtr("5"), CharPtr("6"), + CharPtr("7"), CharPtr("8")))); } // Tests using Invoke() with a 9-argument function. TEST(InvokeTest, FunctionThatTakes9Arguments) { - Action<string(const char*, const char*, const char*, const char*, - const char*, const char*, const char*, const char*, - const char*)> a = Invoke(Concat9); - EXPECT_EQ("123456789", - a.Perform(make_tuple(CharPtr("1"), CharPtr("2"), CharPtr("3"), - CharPtr("4"), CharPtr("5"), CharPtr("6"), - CharPtr("7"), CharPtr("8"), CharPtr("9")))); + Action<std::string(const char*, const char*, const char*, const char*, + const char*, const char*, const char*, const char*, + const char*)> + a = Invoke(Concat9); + EXPECT_EQ("123456789", a.Perform(std::make_tuple( + CharPtr("1"), CharPtr("2"), CharPtr("3"), + CharPtr("4"), CharPtr("5"), CharPtr("6"), + CharPtr("7"), CharPtr("8"), CharPtr("9")))); } // Tests using Invoke() with a 10-argument function. TEST(InvokeTest, FunctionThatTakes10Arguments) { - Action<string(const char*, const char*, const char*, const char*, - const char*, const char*, const char*, const char*, - const char*, const char*)> a = Invoke(Concat10); + Action<std::string(const char*, const char*, const char*, const char*, + const char*, const char*, const char*, const char*, + const char*, const char*)> + a = Invoke(Concat10); EXPECT_EQ("1234567890", - a.Perform(make_tuple(CharPtr("1"), CharPtr("2"), CharPtr("3"), - CharPtr("4"), CharPtr("5"), CharPtr("6"), - CharPtr("7"), CharPtr("8"), CharPtr("9"), - CharPtr("0")))); + a.Perform(std::make_tuple(CharPtr("1"), CharPtr("2"), CharPtr("3"), + CharPtr("4"), CharPtr("5"), CharPtr("6"), + CharPtr("7"), CharPtr("8"), CharPtr("9"), + CharPtr("0")))); } // Tests using Invoke() with functions with parameters declared as Unused. TEST(InvokeTest, FunctionWithUnusedParameters) { - Action<int(int, int, double, const string&)> a1 = - Invoke(SumOfFirst2); - string s("hi"); - EXPECT_EQ(12, a1.Perform( - tuple<int, int, double, const string&>(10, 2, 5.6, s))); + Action<int(int, int, double, const std::string&)> a1 = Invoke(SumOfFirst2); + std::tuple<int, int, double, std::string> dummy = + std::make_tuple(10, 2, 5.6, std::string("hi")); + EXPECT_EQ(12, a1.Perform(dummy)); Action<int(int, int, bool, int*)> a2 = Invoke(SumOfFirst2); - EXPECT_EQ(23, a2.Perform(make_tuple(20, 3, true, static_cast<int*>(NULL)))); + EXPECT_EQ( + 23, a2.Perform(std::make_tuple(20, 3, true, static_cast<int*>(nullptr)))); } // Tests using Invoke() with methods with parameters declared as Unused. TEST(InvokeTest, MethodWithUnusedParameters) { Foo foo; - Action<int(string, bool, int, int)> a1 = - Invoke(&foo, &Foo::SumOfLast2); - EXPECT_EQ(12, a1.Perform(make_tuple(CharPtr("hi"), true, 10, 2))); + Action<int(std::string, bool, int, int)> a1 = Invoke(&foo, &Foo::SumOfLast2); + EXPECT_EQ(12, a1.Perform(std::make_tuple(CharPtr("hi"), true, 10, 2))); Action<int(char, double, int, int)> a2 = Invoke(&foo, &Foo::SumOfLast2); - EXPECT_EQ(23, a2.Perform(make_tuple('a', 2.5, 20, 3))); + EXPECT_EQ(23, a2.Perform(std::make_tuple('a', 2.5, 20, 3))); } // Tests using Invoke() with a functor. TEST(InvokeTest, Functor) { Action<long(long, int)> a = Invoke(plus<long>()); // NOLINT - EXPECT_EQ(3L, a.Perform(make_tuple(1, 2))); + EXPECT_EQ(3L, a.Perform(std::make_tuple(1, 2))); } // Tests using Invoke(f) as an action of a compatible type. TEST(InvokeTest, FunctionWithCompatibleType) { Action<long(int, short, char, bool)> a = Invoke(SumOf4); // NOLINT - EXPECT_EQ(4321, a.Perform(make_tuple(4000, Short(300), Char(20), true))); + EXPECT_EQ(4321, a.Perform(std::make_tuple(4000, Short(300), Char(20), true))); } // Tests using Invoke() with an object pointer and a method pointer. @@ -366,44 +363,44 @@ TEST(InvokeTest, FunctionWithCompatibleType) { TEST(InvokeMethodTest, Nullary) { Foo foo; Action<int()> a = Invoke(&foo, &Foo::Nullary); // NOLINT - EXPECT_EQ(123, a.Perform(make_tuple())); + EXPECT_EQ(123, a.Perform(std::make_tuple())); } // Tests using Invoke() with a unary method. TEST(InvokeMethodTest, Unary) { Foo foo; Action<short(long)> a = Invoke(&foo, &Foo::Unary); // NOLINT - EXPECT_EQ(4123, a.Perform(make_tuple(4000))); + EXPECT_EQ(4123, a.Perform(std::make_tuple(4000))); } // Tests using Invoke() with a binary method. TEST(InvokeMethodTest, Binary) { Foo foo; - Action<string(const string&, char)> a = Invoke(&foo, &Foo::Binary); - string s("Hell"); - EXPECT_EQ("Hello", a.Perform( - tuple<const string&, char>(s, 'o'))); + Action<std::string(const std::string&, char)> a = Invoke(&foo, &Foo::Binary); + std::string s("Hell"); + std::tuple<std::string, char> dummy = std::make_tuple(s, 'o'); + EXPECT_EQ("Hello", a.Perform(dummy)); } // Tests using Invoke() with a ternary method. TEST(InvokeMethodTest, Ternary) { Foo foo; Action<int(int, bool, char)> a = Invoke(&foo, &Foo::Ternary); // NOLINT - EXPECT_EQ(1124, a.Perform(make_tuple(1000, true, Char(1)))); + EXPECT_EQ(1124, a.Perform(std::make_tuple(1000, true, Char(1)))); } // Tests using Invoke() with a 4-argument method. TEST(InvokeMethodTest, MethodThatTakes4Arguments) { Foo foo; Action<int(int, int, int, int)> a = Invoke(&foo, &Foo::SumOf4); // NOLINT - EXPECT_EQ(1357, a.Perform(make_tuple(1000, 200, 30, 4))); + EXPECT_EQ(1357, a.Perform(std::make_tuple(1000, 200, 30, 4))); } // Tests using Invoke() with a 5-argument method. TEST(InvokeMethodTest, MethodThatTakes5Arguments) { Foo foo; Action<int(int, int, int, int, int)> a = Invoke(&foo, &Foo::SumOf5); // NOLINT - EXPECT_EQ(12345, a.Perform(make_tuple(10000, 2000, 300, 40, 5))); + EXPECT_EQ(12345, a.Perform(std::make_tuple(10000, 2000, 300, 40, 5))); } // Tests using Invoke() with a 6-argument method. @@ -411,56 +408,59 @@ TEST(InvokeMethodTest, MethodThatTakes6Arguments) { Foo foo; Action<int(int, int, int, int, int, int)> a = // NOLINT Invoke(&foo, &Foo::SumOf6); - EXPECT_EQ(123456, a.Perform(make_tuple(100000, 20000, 3000, 400, 50, 6))); + EXPECT_EQ(123456, + a.Perform(std::make_tuple(100000, 20000, 3000, 400, 50, 6))); } // Tests using Invoke() with a 7-argument method. TEST(InvokeMethodTest, MethodThatTakes7Arguments) { Foo foo; - Action<string(const char*, const char*, const char*, const char*, - const char*, const char*, const char*)> a = - Invoke(&foo, &Foo::Concat7); + Action<std::string(const char*, const char*, const char*, const char*, + const char*, const char*, const char*)> + a = Invoke(&foo, &Foo::Concat7); EXPECT_EQ("1234567", - a.Perform(make_tuple(CharPtr("1"), CharPtr("2"), CharPtr("3"), - CharPtr("4"), CharPtr("5"), CharPtr("6"), - CharPtr("7")))); + a.Perform(std::make_tuple(CharPtr("1"), CharPtr("2"), CharPtr("3"), + CharPtr("4"), CharPtr("5"), CharPtr("6"), + CharPtr("7")))); } // Tests using Invoke() with a 8-argument method. TEST(InvokeMethodTest, MethodThatTakes8Arguments) { Foo foo; - Action<string(const char*, const char*, const char*, const char*, - const char*, const char*, const char*, const char*)> a = - Invoke(&foo, &Foo::Concat8); + Action<std::string(const char*, const char*, const char*, const char*, + const char*, const char*, const char*, const char*)> + a = Invoke(&foo, &Foo::Concat8); EXPECT_EQ("12345678", - a.Perform(make_tuple(CharPtr("1"), CharPtr("2"), CharPtr("3"), - CharPtr("4"), CharPtr("5"), CharPtr("6"), - CharPtr("7"), CharPtr("8")))); + a.Perform(std::make_tuple(CharPtr("1"), CharPtr("2"), CharPtr("3"), + CharPtr("4"), CharPtr("5"), CharPtr("6"), + CharPtr("7"), CharPtr("8")))); } // Tests using Invoke() with a 9-argument method. TEST(InvokeMethodTest, MethodThatTakes9Arguments) { Foo foo; - Action<string(const char*, const char*, const char*, const char*, - const char*, const char*, const char*, const char*, - const char*)> a = Invoke(&foo, &Foo::Concat9); - EXPECT_EQ("123456789", - a.Perform(make_tuple(CharPtr("1"), CharPtr("2"), CharPtr("3"), - CharPtr("4"), CharPtr("5"), CharPtr("6"), - CharPtr("7"), CharPtr("8"), CharPtr("9")))); + Action<std::string(const char*, const char*, const char*, const char*, + const char*, const char*, const char*, const char*, + const char*)> + a = Invoke(&foo, &Foo::Concat9); + EXPECT_EQ("123456789", a.Perform(std::make_tuple( + CharPtr("1"), CharPtr("2"), CharPtr("3"), + CharPtr("4"), CharPtr("5"), CharPtr("6"), + CharPtr("7"), CharPtr("8"), CharPtr("9")))); } // Tests using Invoke() with a 10-argument method. TEST(InvokeMethodTest, MethodThatTakes10Arguments) { Foo foo; - Action<string(const char*, const char*, const char*, const char*, - const char*, const char*, const char*, const char*, - const char*, const char*)> a = Invoke(&foo, &Foo::Concat10); + Action<std::string(const char*, const char*, const char*, const char*, + const char*, const char*, const char*, const char*, + const char*, const char*)> + a = Invoke(&foo, &Foo::Concat10); EXPECT_EQ("1234567890", - a.Perform(make_tuple(CharPtr("1"), CharPtr("2"), CharPtr("3"), - CharPtr("4"), CharPtr("5"), CharPtr("6"), - CharPtr("7"), CharPtr("8"), CharPtr("9"), - CharPtr("0")))); + a.Perform(std::make_tuple(CharPtr("1"), CharPtr("2"), CharPtr("3"), + CharPtr("4"), CharPtr("5"), CharPtr("6"), + CharPtr("7"), CharPtr("8"), CharPtr("9"), + CharPtr("0")))); } // Tests using Invoke(f) as an action of a compatible type. @@ -468,48 +468,48 @@ TEST(InvokeMethodTest, MethodWithCompatibleType) { Foo foo; Action<long(int, short, char, bool)> a = // NOLINT Invoke(&foo, &Foo::SumOf4); - EXPECT_EQ(4444, a.Perform(make_tuple(4000, Short(300), Char(20), true))); + EXPECT_EQ(4444, a.Perform(std::make_tuple(4000, Short(300), Char(20), true))); } // Tests using WithoutArgs with an action that takes no argument. TEST(WithoutArgsTest, NoArg) { Action<int(int n)> a = WithoutArgs(Invoke(Nullary)); // NOLINT - EXPECT_EQ(1, a.Perform(make_tuple(2))); + EXPECT_EQ(1, a.Perform(std::make_tuple(2))); } // Tests using WithArg with an action that takes 1 argument. TEST(WithArgTest, OneArg) { Action<bool(double x, int n)> b = WithArg<1>(Invoke(Unary)); // NOLINT - EXPECT_TRUE(b.Perform(make_tuple(1.5, -1))); - EXPECT_FALSE(b.Perform(make_tuple(1.5, 1))); + EXPECT_TRUE(b.Perform(std::make_tuple(1.5, -1))); + EXPECT_FALSE(b.Perform(std::make_tuple(1.5, 1))); } TEST(ReturnArgActionTest, WorksForOneArgIntArg0) { const Action<int(int)> a = ReturnArg<0>(); - EXPECT_EQ(5, a.Perform(make_tuple(5))); + EXPECT_EQ(5, a.Perform(std::make_tuple(5))); } TEST(ReturnArgActionTest, WorksForMultiArgBoolArg0) { const Action<bool(bool, bool, bool)> a = ReturnArg<0>(); - EXPECT_TRUE(a.Perform(make_tuple(true, false, false))); + EXPECT_TRUE(a.Perform(std::make_tuple(true, false, false))); } TEST(ReturnArgActionTest, WorksForMultiArgStringArg2) { - const Action<string(int, int, string, int)> a = ReturnArg<2>(); - EXPECT_EQ("seven", a.Perform(make_tuple(5, 6, string("seven"), 8))); + const Action<std::string(int, int, std::string, int)> a = ReturnArg<2>(); + EXPECT_EQ("seven", a.Perform(std::make_tuple(5, 6, std::string("seven"), 8))); } TEST(SaveArgActionTest, WorksForSameType) { int result = 0; const Action<void(int n)> a1 = SaveArg<0>(&result); - a1.Perform(make_tuple(5)); + a1.Perform(std::make_tuple(5)); EXPECT_EQ(5, result); } TEST(SaveArgActionTest, WorksForCompatibleType) { int result = 0; const Action<void(bool, char)> a1 = SaveArg<1>(&result); - a1.Perform(make_tuple(true, 'a')); + a1.Perform(std::make_tuple(true, 'a')); EXPECT_EQ('a', result); } @@ -517,7 +517,7 @@ TEST(SaveArgPointeeActionTest, WorksForSameType) { int result = 0; const int value = 5; const Action<void(const int*)> a1 = SaveArgPointee<0>(&result); - a1.Perform(make_tuple(&value)); + a1.Perform(std::make_tuple(&value)); EXPECT_EQ(5, result); } @@ -525,7 +525,7 @@ TEST(SaveArgPointeeActionTest, WorksForCompatibleType) { int result = 0; char value = 'a'; const Action<void(bool, char*)> a1 = SaveArgPointee<1>(&result); - a1.Perform(make_tuple(true, &value)); + a1.Perform(std::make_tuple(true, &value)); EXPECT_EQ('a', result); } @@ -533,28 +533,28 @@ TEST(SaveArgPointeeActionTest, WorksForLinkedPtr) { int result = 0; linked_ptr<int> value(new int(5)); const Action<void(linked_ptr<int>)> a1 = SaveArgPointee<0>(&result); - a1.Perform(make_tuple(value)); + a1.Perform(std::make_tuple(value)); EXPECT_EQ(5, result); } TEST(SetArgRefereeActionTest, WorksForSameType) { int value = 0; const Action<void(int&)> a1 = SetArgReferee<0>(1); - a1.Perform(tuple<int&>(value)); + a1.Perform(std::tuple<int&>(value)); EXPECT_EQ(1, value); } TEST(SetArgRefereeActionTest, WorksForCompatibleType) { int value = 0; const Action<void(int, int&)> a1 = SetArgReferee<1>('a'); - a1.Perform(tuple<int, int&>(0, value)); + a1.Perform(std::tuple<int, int&>(0, value)); EXPECT_EQ('a', value); } TEST(SetArgRefereeActionTest, WorksWithExtraArguments) { int value = 0; const Action<void(bool, int, int&, const char*)> a1 = SetArgReferee<2>('a'); - a1.Perform(tuple<bool, int, int&, const char*>(true, 0, value, "hi")); + a1.Perform(std::tuple<bool, int, int&, const char*>(true, 0, value, "hi")); EXPECT_EQ('a', value); } @@ -581,7 +581,7 @@ TEST(DeleteArgActionTest, OneArg) { DeletionTester* t = new DeletionTester(&is_deleted); const Action<void(DeletionTester*)> a1 = DeleteArg<0>(); // NOLINT EXPECT_FALSE(is_deleted); - a1.Perform(make_tuple(t)); + a1.Perform(std::make_tuple(t)); EXPECT_TRUE(is_deleted); } @@ -591,7 +591,7 @@ TEST(DeleteArgActionTest, TenArgs) { const Action<void(bool, int, int, const char*, bool, int, int, int, int, DeletionTester*)> a1 = DeleteArg<9>(); EXPECT_FALSE(is_deleted); - a1.Perform(make_tuple(true, 5, 6, CharPtr("hi"), false, 7, 8, 9, 10, t)); + a1.Perform(std::make_tuple(true, 5, 6, CharPtr("hi"), false, 7, 8, 9, 10, t)); EXPECT_TRUE(is_deleted); } @@ -599,19 +599,19 @@ TEST(DeleteArgActionTest, TenArgs) { TEST(ThrowActionTest, ThrowsGivenExceptionInVoidFunction) { const Action<void(int n)> a = Throw('a'); - EXPECT_THROW(a.Perform(make_tuple(0)), char); + EXPECT_THROW(a.Perform(std::make_tuple(0)), char); } class MyException {}; TEST(ThrowActionTest, ThrowsGivenExceptionInNonVoidFunction) { const Action<double(char ch)> a = Throw(MyException()); - EXPECT_THROW(a.Perform(make_tuple('0')), MyException); + EXPECT_THROW(a.Perform(std::make_tuple('0')), MyException); } TEST(ThrowActionTest, ThrowsGivenExceptionInNullaryFunction) { const Action<double()> a = Throw(MyException()); - EXPECT_THROW(a.Perform(make_tuple()), MyException); + EXPECT_THROW(a.Perform(std::make_tuple()), MyException); } #endif // GTEST_HAS_EXCEPTIONS @@ -627,7 +627,7 @@ TEST(SetArrayArgumentTest, SetsTheNthArray) { int* pn = n; char ch[4] = {}; char* pch = ch; - a.Perform(make_tuple(true, pn, pch)); + a.Perform(std::make_tuple(true, pn, pch)); EXPECT_EQ(1, n[0]); EXPECT_EQ(2, n[1]); EXPECT_EQ(3, n[2]); @@ -642,7 +642,7 @@ TEST(SetArrayArgumentTest, SetsTheNthArray) { a = SetArrayArgument<2>(letters.begin(), letters.end()); std::fill_n(n, 4, 0); std::fill_n(ch, 4, '\0'); - a.Perform(make_tuple(true, pn, pch)); + a.Perform(std::make_tuple(true, pn, pch)); EXPECT_EQ(0, n[0]); EXPECT_EQ(0, n[1]); EXPECT_EQ(0, n[2]); @@ -661,7 +661,7 @@ TEST(SetArrayArgumentTest, SetsTheNthArrayWithEmptyRange) { int n[4] = {}; int* pn = n; - a.Perform(make_tuple(true, pn)); + a.Perform(std::make_tuple(true, pn)); EXPECT_EQ(0, n[0]); EXPECT_EQ(0, n[1]); EXPECT_EQ(0, n[2]); @@ -677,7 +677,7 @@ TEST(SetArrayArgumentTest, SetsTheNthArrayWithConvertibleType) { int codes[4] = { 111, 222, 333, 444 }; int* pcodes = codes; - a.Perform(make_tuple(true, pcodes)); + a.Perform(std::make_tuple(true, pcodes)); EXPECT_EQ(97, codes[0]); EXPECT_EQ(98, codes[1]); EXPECT_EQ(99, codes[2]); @@ -691,17 +691,17 @@ TEST(SetArrayArgumentTest, SetsTheNthArrayWithIteratorArgument) { Action<MyFunction> a = SetArrayArgument<1>(letters.begin(), letters.end()); std::string s; - a.Perform(make_tuple(true, back_inserter(s))); + a.Perform(std::make_tuple(true, back_inserter(s))); EXPECT_EQ(letters, s); } TEST(ReturnPointeeTest, Works) { int n = 42; const Action<int()> a = ReturnPointee(&n); - EXPECT_EQ(42, a.Perform(make_tuple())); + EXPECT_EQ(42, a.Perform(std::make_tuple())); n = 43; - EXPECT_EQ(43, a.Perform(make_tuple())); + EXPECT_EQ(43, a.Perform(std::make_tuple())); } } // namespace gmock_generated_actions_test diff --git a/googlemock/test/gmock-nice-strict_test.cc b/googlemock/test/gmock-nice-strict_test.cc index 38daee0..9cae987 100644 --- a/googlemock/test/gmock-nice-strict_test.cc +++ b/googlemock/test/gmock-nice-strict_test.cc @@ -26,15 +26,15 @@ // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -// -// Author: wan@google.com (Zhanyong Wan) + #include "gmock/gmock-generated-nice-strict.h" #include <string> +#include <utility> #include "gmock/gmock.h" -#include "gtest/gtest.h" #include "gtest/gtest-spi.h" +#include "gtest/gtest.h" // This must not be defined inside the ::testing namespace, or it will // clash with ::testing::Mock. @@ -51,7 +51,6 @@ class Mock { namespace testing { namespace gmock_nice_strict_test { -using testing::internal::string; using testing::GMOCK_FLAG(verbose); using testing::HasSubstr; using testing::NaggyMock; @@ -63,6 +62,12 @@ using testing::internal::CaptureStdout; using testing::internal::GetCapturedStdout; #endif +// Class without default constructor. +class NotDefaultConstructible { + public: + explicit NotDefaultConstructible(int) {} +}; + // Defines some mock classes needed by the tests. class Foo { @@ -80,6 +85,7 @@ class MockFoo : public Foo { MOCK_METHOD0(DoThis, void()); MOCK_METHOD1(DoThat, int(bool flag)); + MOCK_METHOD0(ReturnNonDefaultConstructible, NotDefaultConstructible()); private: GTEST_DISALLOW_COPY_AND_ASSIGN_(MockFoo); @@ -87,32 +93,50 @@ class MockFoo : public Foo { class MockBar { public: - explicit MockBar(const string& s) : str_(s) {} + explicit MockBar(const std::string& s) : str_(s) {} - MockBar(char a1, char a2, string a3, string a4, int a5, int a6, - const string& a7, const string& a8, bool a9, bool a10) { - str_ = string() + a1 + a2 + a3 + a4 + static_cast<char>(a5) + + MockBar(char a1, char a2, std::string a3, std::string a4, int a5, int a6, + const std::string& a7, const std::string& a8, bool a9, bool a10) { + str_ = std::string() + a1 + a2 + a3 + a4 + static_cast<char>(a5) + static_cast<char>(a6) + a7 + a8 + (a9 ? 'T' : 'F') + (a10 ? 'T' : 'F'); } virtual ~MockBar() {} - const string& str() const { return str_; } + const std::string& str() const { return str_; } MOCK_METHOD0(This, int()); - MOCK_METHOD2(That, string(int, bool)); + MOCK_METHOD2(That, std::string(int, bool)); private: - string str_; + std::string str_; GTEST_DISALLOW_COPY_AND_ASSIGN_(MockBar); }; +#if GTEST_GTEST_LANG_CXX11 + +class MockBaz { + public: + class MoveOnly { + MoveOnly() = default; + + MoveOnly(const MoveOnly&) = delete; + operator=(const MoveOnly&) = delete; + + MoveOnly(MoveOnly&&) = default; + operator=(MoveOnly&&) = default; + }; + + MockBaz(MoveOnly) {} +} +#endif // GTEST_GTEST_LANG_CXX11 && GTEST_HAS_STD_MOVE_ + #if GTEST_HAS_STREAM_REDIRECTION // Tests that a raw mock generates warnings for uninteresting calls. TEST(RawMockTest, WarningForUninterestingCall) { - const string saved_flag = GMOCK_FLAG(verbose); + const std::string saved_flag = GMOCK_FLAG(verbose); GMOCK_FLAG(verbose) = "warning"; MockFoo raw_foo; @@ -129,7 +153,7 @@ TEST(RawMockTest, WarningForUninterestingCall) { // Tests that a raw mock generates warnings for uninteresting calls // that delete the mock object. TEST(RawMockTest, WarningForUninterestingCallAfterDeath) { - const string saved_flag = GMOCK_FLAG(verbose); + const std::string saved_flag = GMOCK_FLAG(verbose); GMOCK_FLAG(verbose) = "warning"; MockFoo* const raw_foo = new MockFoo; @@ -150,7 +174,7 @@ TEST(RawMockTest, WarningForUninterestingCallAfterDeath) { TEST(RawMockTest, InfoForUninterestingCall) { MockFoo raw_foo; - const string saved_flag = GMOCK_FLAG(verbose); + const std::string saved_flag = GMOCK_FLAG(verbose); GMOCK_FLAG(verbose) = "info"; CaptureStdout(); raw_foo.DoThis(); @@ -196,7 +220,7 @@ TEST(NiceMockTest, NoWarningForUninterestingCallAfterDeath) { TEST(NiceMockTest, InfoForUninterestingCall) { NiceMock<MockFoo> nice_foo; - const string saved_flag = GMOCK_FLAG(verbose); + const std::string saved_flag = GMOCK_FLAG(verbose); GMOCK_FLAG(verbose) = "info"; CaptureStdout(); nice_foo.DoThis(); @@ -216,6 +240,23 @@ TEST(NiceMockTest, AllowsExpectedCall) { nice_foo.DoThis(); } +// Tests that an unexpected call on a nice mock which returns a +// not-default-constructible type throws an exception and the exception contains +// the method's name. +TEST(NiceMockTest, ThrowsExceptionForUnknownReturnTypes) { + NiceMock<MockFoo> nice_foo; +#if GTEST_HAS_EXCEPTIONS + try { + nice_foo.ReturnNonDefaultConstructible(); + FAIL(); + } catch (const std::runtime_error& ex) { + EXPECT_THAT(ex.what(), HasSubstr("ReturnNonDefaultConstructible")); + } +#else + EXPECT_DEATH_IF_SUPPORTED({ nice_foo.ReturnNonDefaultConstructible(); }, ""); +#endif +} + // Tests that an unexpected call on a nice mock fails. TEST(NiceMockTest, UnexpectedCallFails) { NiceMock<MockFoo> nice_foo; @@ -245,6 +286,21 @@ TEST(NiceMockTest, NonDefaultConstructor10) { nice_bar.That(5, true); } +TEST(NiceMockTest, AllowLeak) { + NiceMock<MockFoo>* leaked = new NiceMock<MockFoo>; + Mock::AllowLeak(leaked); + EXPECT_CALL(*leaked, DoThis()); + leaked->DoThis(); +} + +#if GTEST_GTEST_LANG_CXX11 && GTEST_HAS_STD_MOVE_ + +TEST(NiceMockTest, MoveOnlyConstructor) { + NiceMock<MockBaz> nice_baz(MockBaz::MoveOnly()); +} + +#endif // GTEST_LANG_CXX11 && GTEST_HAS_STD_MOVE_ + #if !GTEST_OS_SYMBIAN && !GTEST_OS_WINDOWS_MOBILE // Tests that NiceMock<Mock> compiles where Mock is a user-defined // class (as opposed to ::testing::Mock). We had to work around an @@ -272,7 +328,7 @@ TEST(NiceMockTest, IsNaggy_IsNice_IsStrict) { // Tests that a naggy mock generates warnings for uninteresting calls. TEST(NaggyMockTest, WarningForUninterestingCall) { - const string saved_flag = GMOCK_FLAG(verbose); + const std::string saved_flag = GMOCK_FLAG(verbose); GMOCK_FLAG(verbose) = "warning"; NaggyMock<MockFoo> naggy_foo; @@ -289,7 +345,7 @@ TEST(NaggyMockTest, WarningForUninterestingCall) { // Tests that a naggy mock generates a warning for an uninteresting call // that deletes the mock object. TEST(NaggyMockTest, WarningForUninterestingCallAfterDeath) { - const string saved_flag = GMOCK_FLAG(verbose); + const std::string saved_flag = GMOCK_FLAG(verbose); GMOCK_FLAG(verbose) = "warning"; NaggyMock<MockFoo>* const naggy_foo = new NaggyMock<MockFoo>; @@ -345,6 +401,21 @@ TEST(NaggyMockTest, NonDefaultConstructor10) { naggy_bar.That(5, true); } +TEST(NaggyMockTest, AllowLeak) { + NaggyMock<MockFoo>* leaked = new NaggyMock<MockFoo>; + Mock::AllowLeak(leaked); + EXPECT_CALL(*leaked, DoThis()); + leaked->DoThis(); +} + +#if GTEST_GTEST_LANG_CXX11 && GTEST_HAS_STD_MOVE_ + +TEST(NaggyMockTest, MoveOnlyConstructor) { + NaggyMock<MockBaz> naggy_baz(MockBaz::MoveOnly()); +} + +#endif // GTEST_LANG_CXX11 && GTEST_HAS_STD_MOVE_ + #if !GTEST_OS_SYMBIAN && !GTEST_OS_WINDOWS_MOBILE // Tests that NaggyMock<Mock> compiles where Mock is a user-defined // class (as opposed to ::testing::Mock). We had to work around an @@ -426,6 +497,21 @@ TEST(StrictMockTest, NonDefaultConstructor10) { "Uninteresting mock function call"); } +TEST(StrictMockTest, AllowLeak) { + StrictMock<MockFoo>* leaked = new StrictMock<MockFoo>; + Mock::AllowLeak(leaked); + EXPECT_CALL(*leaked, DoThis()); + leaked->DoThis(); +} + +#if GTEST_GTEST_LANG_CXX11 && GTEST_HAS_STD_MOVE_ + +TEST(StrictMockTest, MoveOnlyConstructor) { + StrictMock<MockBaz> strict_baz(MockBaz::MoveOnly()); +} + +#endif // GTEST_LANG_CXX11 && GTEST_HAS_STD_MOVE_ + #if !GTEST_OS_SYMBIAN && !GTEST_OS_WINDOWS_MOBILE // Tests that StrictMock<Mock> compiles where Mock is a user-defined // class (as opposed to ::testing::Mock). We had to work around an diff --git a/googlemock/test/gmock-port_test.cc b/googlemock/test/gmock-port_test.cc index d6a8d44..a2c2be2 100644 --- a/googlemock/test/gmock-port_test.cc +++ b/googlemock/test/gmock-port_test.cc @@ -26,8 +26,7 @@ // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -// -// Author: vladl@google.com (Vlad Losev) + // Google Mock - a framework for writing C++ mock classes. // diff --git a/googlemock/test/gmock-spec-builders_test.cc b/googlemock/test/gmock-spec-builders_test.cc index 59ea87c..65c9fcc 100644 --- a/googlemock/test/gmock-spec-builders_test.cc +++ b/googlemock/test/gmock-spec-builders_test.cc @@ -26,8 +26,7 @@ // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -// -// Author: wan@google.com (Zhanyong Wan) + // Google Mock - a framework for writing C++ mock classes. // @@ -89,15 +88,18 @@ using testing::Mock; using testing::NaggyMock; using testing::Ne; using testing::Return; +using testing::SaveArg; using testing::Sequence; using testing::SetArgPointee; using testing::internal::ExpectationTester; using testing::internal::FormatFileLocation; +using testing::internal::kAllow; using testing::internal::kErrorVerbosity; +using testing::internal::kFail; using testing::internal::kInfoVerbosity; +using testing::internal::kWarn; using testing::internal::kWarningVerbosity; using testing::internal::linked_ptr; -using testing::internal::string; #if GTEST_HAS_STREAM_REDIRECTION using testing::HasSubstr; @@ -692,6 +694,60 @@ TEST(ExpectCallSyntaxTest, WarnsOnTooFewActions) { b.DoB(); } +TEST(ExpectCallSyntaxTest, WarningIsErrorWithFlag) { + int original_behavior = testing::GMOCK_FLAG(default_mock_behavior); + + testing::GMOCK_FLAG(default_mock_behavior) = kAllow; + CaptureStdout(); + { + MockA a; + a.DoA(0); + } + std::string output = GetCapturedStdout(); + EXPECT_TRUE(output.empty()) << output; + + testing::GMOCK_FLAG(default_mock_behavior) = kWarn; + CaptureStdout(); + { + MockA a; + a.DoA(0); + } + std::string warning_output = GetCapturedStdout(); + EXPECT_PRED_FORMAT2(IsSubstring, "GMOCK WARNING", warning_output); + EXPECT_PRED_FORMAT2(IsSubstring, "Uninteresting mock function call", + warning_output); + + testing::GMOCK_FLAG(default_mock_behavior) = kFail; + EXPECT_NONFATAL_FAILURE({ + MockA a; + a.DoA(0); + }, "Uninteresting mock function call"); + + // Out of bounds values are converted to kWarn + testing::GMOCK_FLAG(default_mock_behavior) = -1; + CaptureStdout(); + { + MockA a; + a.DoA(0); + } + warning_output = GetCapturedStdout(); + EXPECT_PRED_FORMAT2(IsSubstring, "GMOCK WARNING", warning_output); + EXPECT_PRED_FORMAT2(IsSubstring, "Uninteresting mock function call", + warning_output); + testing::GMOCK_FLAG(default_mock_behavior) = 3; + CaptureStdout(); + { + MockA a; + a.DoA(0); + } + warning_output = GetCapturedStdout(); + EXPECT_PRED_FORMAT2(IsSubstring, "GMOCK WARNING", warning_output); + EXPECT_PRED_FORMAT2(IsSubstring, "Uninteresting mock function call", + warning_output); + + testing::GMOCK_FLAG(default_mock_behavior) = original_behavior; +} + #endif // GTEST_HAS_STREAM_REDIRECTION // Tests the semantics of ON_CALL(). @@ -1119,7 +1175,7 @@ TEST(UnexpectedCallTest, UnsatisifiedPrerequisites) { TEST(UndefinedReturnValueTest, ReturnValueIsMandatoryWhenNotDefaultConstructible) { MockA a; - // TODO(wan@google.com): We should really verify the output message, + // FIXME: We should really verify the output message, // but we cannot yet due to that EXPECT_DEATH only captures stderr // while Google Mock logs to stdout. #if GTEST_HAS_EXCEPTIONS @@ -1954,7 +2010,7 @@ class MockC { public: MockC() {} - MOCK_METHOD6(VoidMethod, void(bool cond, int n, string s, void* p, + MOCK_METHOD6(VoidMethod, void(bool cond, int n, std::string s, void* p, const Printable& x, Unprintable y)); MOCK_METHOD0(NonVoidMethod, int()); // NOLINT @@ -1970,7 +2026,7 @@ class VerboseFlagPreservingFixture : public testing::Test { ~VerboseFlagPreservingFixture() { GMOCK_FLAG(verbose) = saved_verbose_flag_; } private: - const string saved_verbose_flag_; + const std::string saved_verbose_flag_; GTEST_DISALLOW_COPY_AND_ASSIGN_(VerboseFlagPreservingFixture); }; @@ -1985,7 +2041,7 @@ TEST(FunctionCallMessageTest, GMOCK_FLAG(verbose) = kWarningVerbosity; NaggyMock<MockC> c; CaptureStdout(); - c.VoidMethod(false, 5, "Hi", NULL, Printable(), Unprintable()); + c.VoidMethod(false, 5, "Hi", nullptr, Printable(), Unprintable()); const std::string output = GetCapturedStdout(); EXPECT_PRED_FORMAT2(IsSubstring, "GMOCK WARNING", output); EXPECT_PRED_FORMAT2(IsNotSubstring, "Stack trace:", output); @@ -1999,7 +2055,7 @@ TEST(FunctionCallMessageTest, GMOCK_FLAG(verbose) = kInfoVerbosity; NaggyMock<MockC> c; CaptureStdout(); - c.VoidMethod(false, 5, "Hi", NULL, Printable(), Unprintable()); + c.VoidMethod(false, 5, "Hi", nullptr, Printable(), Unprintable()); const std::string output = GetCapturedStdout(); EXPECT_PRED_FORMAT2(IsSubstring, "GMOCK WARNING", output); EXPECT_PRED_FORMAT2(IsSubstring, "Stack trace:", output); @@ -2042,7 +2098,7 @@ TEST(FunctionCallMessageTest, // A void mock function. NaggyMock<MockC> c; CaptureStdout(); - c.VoidMethod(false, 5, "Hi", NULL, Printable(), Unprintable()); + c.VoidMethod(false, 5, "Hi", nullptr, Printable(), Unprintable()); const std::string output2 = GetCapturedStdout(); EXPECT_THAT(output2.c_str(), ContainsRegex( @@ -2062,8 +2118,8 @@ class GMockVerboseFlagTest : public VerboseFlagPreservingFixture { // contain the given function name in the stack trace. When it's // false, the output should be empty.) void VerifyOutput(const std::string& output, bool should_print, - const string& expected_substring, - const string& function_name) { + const std::string& expected_substring, + const std::string& function_name) { if (should_print) { EXPECT_THAT(output.c_str(), HasSubstr(expected_substring)); # ifndef NDEBUG @@ -2113,11 +2169,13 @@ class GMockVerboseFlagTest : public VerboseFlagPreservingFixture { // Tests how the flag affects uninteresting calls on a naggy mock. void TestUninterestingCallOnNaggyMock(bool should_print) { NaggyMock<MockA> a; - const string note = + const std::string note = "NOTE: You can safely ignore the above warning unless this " "call should not happen. Do not suppress it by blindly adding " "an EXPECT_CALL() if you don't mean to enforce the call. " - "See https://github.com/google/googletest/blob/master/googlemock/docs/CookBook.md#" + "See " + "https://github.com/google/googletest/blob/master/googlemock/docs/" + "CookBook.md#" "knowing-when-to-expect for details."; // A void-returning function. @@ -2623,9 +2681,78 @@ TEST(SynchronizationTest, CanCallMockMethodInAction) { // EXPECT_CALL() did not specify an action. } +TEST(ParameterlessExpectationsTest, CanSetExpectationsWithoutMatchers) { + MockA a; + int do_a_arg0 = 0; + ON_CALL(a, DoA).WillByDefault(SaveArg<0>(&do_a_arg0)); + int do_a_47_arg0 = 0; + ON_CALL(a, DoA(47)).WillByDefault(SaveArg<0>(&do_a_47_arg0)); + + a.DoA(17); + EXPECT_THAT(do_a_arg0, 17); + EXPECT_THAT(do_a_47_arg0, 0); + a.DoA(47); + EXPECT_THAT(do_a_arg0, 17); + EXPECT_THAT(do_a_47_arg0, 47); + + ON_CALL(a, Binary).WillByDefault(Return(true)); + ON_CALL(a, Binary(_, 14)).WillByDefault(Return(false)); + EXPECT_THAT(a.Binary(14, 17), true); + EXPECT_THAT(a.Binary(17, 14), false); +} + +TEST(ParameterlessExpectationsTest, CanSetExpectationsForOverloadedMethods) { + MockB b; + ON_CALL(b, DoB()).WillByDefault(Return(9)); + ON_CALL(b, DoB(5)).WillByDefault(Return(11)); + + EXPECT_THAT(b.DoB(), 9); + EXPECT_THAT(b.DoB(1), 0); // default value + EXPECT_THAT(b.DoB(5), 11); +} + +struct MockWithConstMethods { + public: + MOCK_CONST_METHOD1(Foo, int(int)); + MOCK_CONST_METHOD2(Bar, int(int, const char*)); +}; + +TEST(ParameterlessExpectationsTest, CanSetExpectationsForConstMethods) { + MockWithConstMethods mock; + ON_CALL(mock, Foo).WillByDefault(Return(7)); + ON_CALL(mock, Bar).WillByDefault(Return(33)); + + EXPECT_THAT(mock.Foo(17), 7); + EXPECT_THAT(mock.Bar(27, "purple"), 33); +} + +class MockConstOverload { + public: + MOCK_METHOD1(Overloaded, int(int)); + MOCK_CONST_METHOD1(Overloaded, int(int)); +}; + +TEST(ParameterlessExpectationsTest, + CanSetExpectationsForConstOverloadedMethods) { + MockConstOverload mock; + ON_CALL(mock, Overloaded(_)).WillByDefault(Return(7)); + ON_CALL(mock, Overloaded(5)).WillByDefault(Return(9)); + ON_CALL(Const(mock), Overloaded(5)).WillByDefault(Return(11)); + ON_CALL(Const(mock), Overloaded(7)).WillByDefault(Return(13)); + + EXPECT_THAT(mock.Overloaded(1), 7); + EXPECT_THAT(mock.Overloaded(5), 9); + EXPECT_THAT(mock.Overloaded(7), 7); + + const MockConstOverload& const_mock = mock; + EXPECT_THAT(const_mock.Overloaded(1), 0); + EXPECT_THAT(const_mock.Overloaded(5), 11); + EXPECT_THAT(const_mock.Overloaded(7), 13); +} + } // namespace -// Allows the user to define his own main and then invoke gmock_main +// Allows the user to define their own main and then invoke gmock_main // from it. This might be necessary on some platforms which require // specific setup and teardown. #if GMOCK_RENAME_MAIN @@ -2634,7 +2761,6 @@ int gmock_main(int argc, char **argv) { int main(int argc, char **argv) { #endif // GMOCK_RENAME_MAIN testing::InitGoogleMock(&argc, argv); - // Ensures that the tests pass no matter what value of // --gmock_catch_leaked_mocks and --gmock_verbose the user specifies. testing::GMOCK_FLAG(catch_leaked_mocks) = true; diff --git a/googlemock/test/gmock_all_test.cc b/googlemock/test/gmock_all_test.cc index 56d6c49..e1774fb 100644 --- a/googlemock/test/gmock_all_test.cc +++ b/googlemock/test/gmock_all_test.cc @@ -26,8 +26,7 @@ // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -// -// Author: wan@google.com (Zhanyong Wan) + // // Tests for Google C++ Mocking Framework (Google Mock) // diff --git a/googlemock/test/gmock_ex_test.cc b/googlemock/test/gmock_ex_test.cc index 3afed86..72eb43f 100644 --- a/googlemock/test/gmock_ex_test.cc +++ b/googlemock/test/gmock_ex_test.cc @@ -26,17 +26,18 @@ // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -// -// Author: wan@google.com (Zhanyong Wan) + // Tests Google Mock's functionality that depends on exceptions. #include "gmock/gmock.h" #include "gtest/gtest.h" +#if GTEST_HAS_EXCEPTIONS namespace { using testing::HasSubstr; + using testing::internal::GoogleTestFailureException; // A type that cannot be default constructed. @@ -52,8 +53,6 @@ class MockFoo { MOCK_METHOD0(GetNonDefaultConstructible, NonDefaultConstructible()); }; -#if GTEST_HAS_EXCEPTIONS - TEST(DefaultValueTest, ThrowsRuntimeErrorWhenNoDefaultValue) { MockFoo mock; try { @@ -76,6 +75,6 @@ TEST(DefaultValueTest, ThrowsRuntimeErrorWhenNoDefaultValue) { } } -#endif } // unnamed namespace +#endif diff --git a/googlemock/test/gmock_leak_test.py b/googlemock/test/gmock_leak_test.py index 997680c..7e4b1ee 100755 --- a/googlemock/test/gmock_leak_test.py +++ b/googlemock/test/gmock_leak_test.py @@ -31,12 +31,8 @@ """Tests that leaked mock objects can be caught be Google Mock.""" -__author__ = 'wan@google.com (Zhanyong Wan)' - - import gmock_test_utils - PROGRAM_PATH = gmock_test_utils.GetTestExecutablePath('gmock_leak_test_') TEST_WITH_EXPECT_CALL = [PROGRAM_PATH, '--gtest_filter=*ExpectCall*'] TEST_WITH_ON_CALL = [PROGRAM_PATH, '--gtest_filter=*OnCall*'] diff --git a/googlemock/test/gmock_leak_test_.cc b/googlemock/test/gmock_leak_test_.cc index 1d27d22..2e095ab 100644 --- a/googlemock/test/gmock_leak_test_.cc +++ b/googlemock/test/gmock_leak_test_.cc @@ -26,8 +26,7 @@ // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -// -// Author: wan@google.com (Zhanyong Wan) + // Google Mock - a framework for writing C++ mock classes. // diff --git a/googlemock/test/gmock_link2_test.cc b/googlemock/test/gmock_link2_test.cc index 4c310c3..d27ce17 100644 --- a/googlemock/test/gmock_link2_test.cc +++ b/googlemock/test/gmock_link2_test.cc @@ -26,8 +26,7 @@ // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -// -// Author: wan@google.com (Zhanyong Wan), vladl@google.com (Vlad Losev) + // Google Mock - a framework for writing C++ mock classes. // @@ -37,4 +36,4 @@ #define LinkTest LinkTest2 -#include "test/gmock_link_test.h" +#include "test/gmock_link_test.h" diff --git a/googlemock/test/gmock_link_test.cc b/googlemock/test/gmock_link_test.cc index 61e97d1..e7c54cc 100644 --- a/googlemock/test/gmock_link_test.cc +++ b/googlemock/test/gmock_link_test.cc @@ -26,8 +26,7 @@ // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -// -// Author: wan@google.com (Zhanyong Wan), vladl@google.com (Vlad Losev) + // Google Mock - a framework for writing C++ mock classes. // @@ -37,4 +36,4 @@ #define LinkTest LinkTest1 -#include "test/gmock_link_test.h" +#include "test/gmock_link_test.h" diff --git a/googlemock/test/gmock_link_test.h b/googlemock/test/gmock_link_test.h index 1f55f5b..e85f750 100644 --- a/googlemock/test/gmock_link_test.h +++ b/googlemock/test/gmock_link_test.h @@ -26,8 +26,7 @@ // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -// -// Author: vladl@google.com (Vlad Losev) + // Google Mock - a framework for writing C++ mock classes. // @@ -90,8 +89,10 @@ // Field // Property // ResultOf(function) +// ResultOf(callback) // Pointee // Truly(predicate) +// AddressSatisfies // AllOf // AnyOf // Not @@ -120,13 +121,15 @@ # include <errno.h> #endif -#include "gmock/internal/gmock-port.h" -#include "gtest/gtest.h" #include <iostream> #include <vector> +#include "gtest/gtest.h" +#include "gtest/internal/gtest-port.h" + using testing::_; using testing::A; +using testing::Action; using testing::AllOf; using testing::AnyOf; using testing::Assign; @@ -148,6 +151,8 @@ using testing::Invoke; using testing::InvokeArgument; using testing::InvokeWithoutArgs; using testing::IsNull; +using testing::IsSubsetOf; +using testing::IsSupersetOf; using testing::Le; using testing::Lt; using testing::Matcher; @@ -243,7 +248,7 @@ TEST(LinkTest, TestReturnVoid) { Mock mock; EXPECT_CALL(mock, VoidFromString(_)).WillOnce(Return()); - mock.VoidFromString(NULL); + mock.VoidFromString(nullptr); } // Tests the linkage of the Return action. @@ -252,7 +257,7 @@ TEST(LinkTest, TestReturn) { char ch = 'x'; EXPECT_CALL(mock, StringFromString(_)).WillOnce(Return(&ch)); - mock.StringFromString(NULL); + mock.StringFromString(nullptr); } // Tests the linkage of the ReturnNull action. @@ -260,7 +265,7 @@ TEST(LinkTest, TestReturnNull) { Mock mock; EXPECT_CALL(mock, VoidFromString(_)).WillOnce(Return()); - mock.VoidFromString(NULL); + mock.VoidFromString(nullptr); } // Tests the linkage of the ReturnRef action. @@ -269,7 +274,7 @@ TEST(LinkTest, TestReturnRef) { int n = 42; EXPECT_CALL(mock, IntRefFromString(_)).WillOnce(ReturnRef(n)); - mock.IntRefFromString(NULL); + mock.IntRefFromString(nullptr); } // Tests the linkage of the Assign action. @@ -278,7 +283,7 @@ TEST(LinkTest, TestAssign) { char ch = 'x'; EXPECT_CALL(mock, VoidFromString(_)).WillOnce(Assign(&ch, 'y')); - mock.VoidFromString(NULL); + mock.VoidFromString(nullptr); } // Tests the linkage of the SetArgPointee action. @@ -309,7 +314,7 @@ TEST(LinkTest, TestSetErrnoAndReturn) { int saved_errno = errno; EXPECT_CALL(mock, IntFromString(_)).WillOnce(SetErrnoAndReturn(1, -1)); - mock.IntFromString(NULL); + mock.IntFromString(nullptr); errno = saved_errno; } @@ -323,8 +328,8 @@ TEST(LinkTest, TestInvoke) { EXPECT_CALL(mock, VoidFromString(_)) .WillOnce(Invoke(&InvokeHelper::StaticVoidFromString)) .WillOnce(Invoke(&test_invoke_helper, &InvokeHelper::VoidFromString)); - mock.VoidFromString(NULL); - mock.VoidFromString(NULL); + mock.VoidFromString(nullptr); + mock.VoidFromString(nullptr); } // Tests the linkage of the InvokeWithoutArgs action. @@ -336,8 +341,8 @@ TEST(LinkTest, TestInvokeWithoutArgs) { .WillOnce(InvokeWithoutArgs(&InvokeHelper::StaticVoidFromVoid)) .WillOnce(InvokeWithoutArgs(&test_invoke_helper, &InvokeHelper::VoidFromVoid)); - mock.VoidFromString(NULL); - mock.VoidFromString(NULL); + mock.VoidFromString(nullptr); + mock.VoidFromString(nullptr); } // Tests the linkage of the InvokeArgument action. @@ -355,7 +360,7 @@ TEST(LinkTest, TestWithArg) { EXPECT_CALL(mock, VoidFromString(_)) .WillOnce(WithArg<0>(Invoke(&InvokeHelper::StaticVoidFromString))); - mock.VoidFromString(NULL); + mock.VoidFromString(nullptr); } // Tests the linkage of the WithArgs action. @@ -364,7 +369,7 @@ TEST(LinkTest, TestWithArgs) { EXPECT_CALL(mock, VoidFromString(_)) .WillOnce(WithArgs<0>(Invoke(&InvokeHelper::StaticVoidFromString))); - mock.VoidFromString(NULL); + mock.VoidFromString(nullptr); } // Tests the linkage of the WithoutArgs action. @@ -372,7 +377,7 @@ TEST(LinkTest, TestWithoutArgs) { Mock mock; EXPECT_CALL(mock, VoidFromString(_)).WillOnce(WithoutArgs(Return())); - mock.VoidFromString(NULL); + mock.VoidFromString(nullptr); } // Tests the linkage of the DoAll action. @@ -400,7 +405,7 @@ TEST(LinkTest, TestIgnoreResult) { Mock mock; EXPECT_CALL(mock, VoidFromString(_)).WillOnce(IgnoreResult(Return(42))); - mock.VoidFromString(NULL); + mock.VoidFromString(nullptr); } #if GTEST_HAS_EXCEPTIONS @@ -432,7 +437,7 @@ TEST(LinkTest, TestActionMacro) { Mock mock; EXPECT_CALL(mock, IntFromString(_)).WillOnce(Return1()); - mock.IntFromString(NULL); + mock.IntFromString(nullptr); } // Tests the linkage of actions created using ACTION_P macro. @@ -444,7 +449,7 @@ TEST(LinkTest, TestActionPMacro) { Mock mock; EXPECT_CALL(mock, IntFromString(_)).WillOnce(ReturnArgument(42)); - mock.IntFromString(NULL); + mock.IntFromString(nullptr); } // Tests the linkage of actions created using ACTION_P2 macro. @@ -592,6 +597,22 @@ TEST(LinkTest, TestMatcherElementsAreArray) { ON_CALL(mock, VoidFromVector(ElementsAreArray(arr))).WillByDefault(Return()); } +// Tests the linkage of the IsSubsetOf matcher. +TEST(LinkTest, TestMatcherIsSubsetOf) { + Mock mock; + char arr[] = {'a', 'b'}; + + ON_CALL(mock, VoidFromVector(IsSubsetOf(arr))).WillByDefault(Return()); +} + +// Tests the linkage of the IsSupersetOf matcher. +TEST(LinkTest, TestMatcherIsSupersetOf) { + Mock mock; + char arr[] = {'a', 'b'}; + + ON_CALL(mock, VoidFromVector(IsSupersetOf(arr))).WillByDefault(Return()); +} + // Tests the linkage of the ContainerEq matcher. TEST(LinkTest, TestMatcherContainerEq) { Mock mock; @@ -625,7 +646,7 @@ TEST(LinkTest, TestMatcherProperty) { // Tests the linkage of the ResultOf matcher. TEST(LinkTest, TestMatcherResultOf) { Matcher<char*> m = ResultOf(&InvokeHelper::StaticIntFromString, Eq(1)); - EXPECT_TRUE(m.Matches(NULL)); + EXPECT_TRUE(m.Matches(nullptr)); } // Tests the linkage of the ResultOf matcher. @@ -639,7 +660,7 @@ TEST(LinkTest, TestMatcherPointee) { // Tests the linkage of the Truly matcher. TEST(LinkTest, TestMatcherTruly) { Matcher<const char*> m = Truly(&InvokeHelper::StaticBoolFromString); - EXPECT_TRUE(m.Matches(NULL)); + EXPECT_TRUE(m.Matches(nullptr)); } // Tests the linkage of the AllOf matcher. @@ -663,7 +684,7 @@ TEST(LinkTest, TestMatcherNot) { // Tests the linkage of the MatcherCast<T>() function. TEST(LinkTest, TestMatcherCast) { Matcher<const char*> m = MatcherCast<const char*>(_); - EXPECT_TRUE(m.Matches(NULL)); + EXPECT_TRUE(m.Matches(nullptr)); } #endif // GMOCK_TEST_GMOCK_LINK_TEST_H_ diff --git a/googlemock/test/gmock_output_test.py b/googlemock/test/gmock_output_test.py index eced8a8..0527bd9 100755 --- a/googlemock/test/gmock_output_test.py +++ b/googlemock/test/gmock_output_test.py @@ -29,21 +29,19 @@ # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -"""Tests the text output of Google C++ Mocking Framework. +r"""Tests the text output of Google C++ Mocking Framework. -SYNOPSIS - gmock_output_test.py --build_dir=BUILD/DIR --gengolden - # where BUILD/DIR contains the built gmock_output_test_ file. - gmock_output_test.py --gengolden - gmock_output_test.py -""" +To update the golden file: +gmock_output_test.py --build_dir=BUILD/DIR --gengolden +where BUILD/DIR contains the built gmock_output_test_ file. +gmock_output_test.py --gengolden +gmock_output_test.py -__author__ = 'wan@google.com (Zhanyong Wan)' +""" import os import re import sys - import gmock_test_utils @@ -176,5 +174,8 @@ if __name__ == '__main__': golden_file = open(GOLDEN_PATH, 'wb') golden_file.write(output) golden_file.close() + # Suppress the error "googletest was imported but a call to its main() + # was never detected." + os._exit(0) else: gmock_test_utils.Main() diff --git a/googlemock/test/gmock_output_test_.cc b/googlemock/test/gmock_output_test_.cc index 44cba34..3955c73 100644 --- a/googlemock/test/gmock_output_test_.cc +++ b/googlemock/test/gmock_output_test_.cc @@ -26,8 +26,7 @@ // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -// -// Author: wan@google.com (Zhanyong Wan) + // Tests Google Mock's output in various scenarios. This ensures that // Google Mock's messages are readable and useful. @@ -39,6 +38,12 @@ #include "gtest/gtest.h" +// Silence C4100 (unreferenced formal parameter) +#ifdef _MSC_VER +# pragma warning(push) +# pragma warning(disable:4100) +#endif + using testing::_; using testing::AnyNumber; using testing::Ge; @@ -47,6 +52,7 @@ using testing::NaggyMock; using testing::Ref; using testing::Return; using testing::Sequence; +using testing::Value; class MockFoo { public: @@ -268,6 +274,15 @@ TEST_F(GMockOutputTest, CatchesLeakedMocks) { // Both foo1 and foo2 are deliberately leaked. } +MATCHER_P2(IsPair, first, second, "") { + return Value(arg.first, first) && Value(arg.second, second); +} + +TEST_F(GMockOutputTest, PrintsMatcher) { + const testing::Matcher<int> m1 = Ge(48); + EXPECT_THAT((std::pair<int, bool>(42, true)), IsPair(m1, true)); +} + void TestCatchesLeakedMocksInAdHocTests() { MockFoo* foo = new MockFoo; @@ -280,7 +295,6 @@ void TestCatchesLeakedMocksInAdHocTests() { int main(int argc, char **argv) { testing::InitGoogleMock(&argc, argv); - // Ensures that the tests pass no matter what value of // --gmock_catch_leaked_mocks and --gmock_verbose the user specifies. testing::GMOCK_FLAG(catch_leaked_mocks) = true; @@ -289,3 +303,7 @@ int main(int argc, char **argv) { TestCatchesLeakedMocksInAdHocTests(); return RUN_ALL_TESTS(); } + +#ifdef _MSC_VER +# pragma warning(pop) +#endif diff --git a/googlemock/test/gmock_output_test_golden.txt b/googlemock/test/gmock_output_test_golden.txt index 689d5ee..dbcb211 100644 --- a/googlemock/test/gmock_output_test_golden.txt +++ b/googlemock/test/gmock_output_test_golden.txt @@ -288,6 +288,12 @@ Stack trace: [ OK ] GMockOutputTest.ExplicitActionsRunOutWithDefaultAction [ RUN ] GMockOutputTest.CatchesLeakedMocks [ OK ] GMockOutputTest.CatchesLeakedMocks +[ RUN ] GMockOutputTest.PrintsMatcher +FILE:#: Failure +Value of: (std::pair<int, bool>(42, true)) +Expected: is pair (is >= 48, true) + Actual: (42, true) (of type std::pair<int, bool>) +[ FAILED ] GMockOutputTest.PrintsMatcher [ FAILED ] GMockOutputTest.UnexpectedCall [ FAILED ] GMockOutputTest.UnexpectedCallToVoidFunction [ FAILED ] GMockOutputTest.ExcessiveCall @@ -302,9 +308,10 @@ Stack trace: [ FAILED ] GMockOutputTest.MismatchArgumentsAndWith [ FAILED ] GMockOutputTest.UnexpectedCallWithDefaultAction [ FAILED ] GMockOutputTest.ExcessiveCallWithDefaultAction +[ FAILED ] GMockOutputTest.PrintsMatcher FILE:#: ERROR: this mock object should be deleted but never is. Its address is @0x#. FILE:#: ERROR: this mock object should be deleted but never is. Its address is @0x#. FILE:#: ERROR: this mock object should be deleted but never is. Its address is @0x#. -ERROR: 3 leaked mock objects found at program exit. +ERROR: 3 leaked mock objects found at program exit. Expectations on a mock object is verified when the object is destructed. Leaking a mock means that its expectations aren't verified, which is usually a test bug. If you really intend to leak a mock, you can suppress this error using testing::Mock::AllowLeak(mock_object), or you may use a fake or stub instead of a mock. diff --git a/googlemock/test/gmock_stress_test.cc b/googlemock/test/gmock_stress_test.cc index 0e97aee..9ae0b1e 100644 --- a/googlemock/test/gmock_stress_test.cc +++ b/googlemock/test/gmock_stress_test.cc @@ -26,8 +26,7 @@ // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -// -// Author: wan@google.com (Zhanyong Wan) + // Tests that Google Mock constructs can be used in a large number of // threads concurrently. @@ -38,7 +37,7 @@ namespace testing { namespace { -// From <gtest/internal/gtest-port.h>. +// From gtest-port.h. using ::testing::internal::ThreadWithParam; // The maximum number of test threads (not including helper threads) @@ -51,7 +50,7 @@ const int kRepeat = 50; class MockFoo { public: MOCK_METHOD1(Bar, int(int n)); // NOLINT - MOCK_METHOD2(Baz, char(const char* s1, const internal::string& s2)); // NOLINT + MOCK_METHOD2(Baz, char(const char* s1, const std::string& s2)); // NOLINT }; // Helper for waiting for the given thread to finish and then deleting it. @@ -211,7 +210,7 @@ void TestConcurrentCallsOnSameObject(Dummy /* dummy */) { int count1 = 0; const Helper1Param param = { &foo, &count1 }; ThreadWithParam<Helper1Param>* const t = - new ThreadWithParam<Helper1Param>(Helper1, param, NULL); + new ThreadWithParam<Helper1Param>(Helper1, param, nullptr); int count2 = 0; const Helper1Param param2 = { &foo, &count2 }; @@ -265,7 +264,7 @@ void TestPartiallyOrderedExpectationsWithThreads(Dummy /* dummy */) { foo.Bar(1); ThreadWithParam<MockFoo*>* const t = - new ThreadWithParam<MockFoo*>(Helper2, &foo, NULL); + new ThreadWithParam<MockFoo*>(Helper2, &foo, nullptr); Helper2(&foo); JoinAndDelete(t); @@ -289,8 +288,8 @@ TEST(StressTest, CanUseGMockWithThreads) { ThreadWithParam<Dummy>* threads[kTestThreads] = {}; for (int i = 0; i < kTestThreads; i++) { // Creates a thread to run the test function. - threads[i] = - new ThreadWithParam<Dummy>(test_routines[i % kRoutines], Dummy(), NULL); + threads[i] = new ThreadWithParam<Dummy>(test_routines[i % kRoutines], + Dummy(), nullptr); GTEST_LOG_(INFO) << "Thread #" << i << " running . . ."; } diff --git a/googlemock/test/gmock_test.cc b/googlemock/test/gmock_test.cc index d8d0c57..e9840a3 100644 --- a/googlemock/test/gmock_test.cc +++ b/googlemock/test/gmock_test.cc @@ -26,8 +26,7 @@ // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -// -// Author: wan@google.com (Zhanyong Wan) + // Google Mock - a framework for writing C++ mock classes. // @@ -37,9 +36,11 @@ #include <string> #include "gtest/gtest.h" +#include "gtest/internal/custom/gtest.h" #if !defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_) +using testing::GMOCK_FLAG(default_mock_behavior); using testing::GMOCK_FLAG(verbose); using testing::InitGoogleMock; @@ -50,9 +51,9 @@ void TestInitGoogleMock(const Char* (&argv)[M], const Char* (&new_argv)[N], const ::std::string& expected_gmock_verbose) { const ::std::string old_verbose = GMOCK_FLAG(verbose); - int argc = M; + int argc = M - 1; InitGoogleMock(&argc, const_cast<Char**>(argv)); - ASSERT_EQ(N, argc) << "The new argv has wrong number of elements."; + ASSERT_EQ(N - 1, argc) << "The new argv has wrong number of elements."; for (int i = 0; i < N; i++) { EXPECT_STREQ(new_argv[i], argv[i]); @@ -63,149 +64,109 @@ void TestInitGoogleMock(const Char* (&argv)[M], const Char* (&new_argv)[N], } TEST(InitGoogleMockTest, ParsesInvalidCommandLine) { - const char* argv[] = { - NULL - }; + const char* argv[] = {nullptr}; - const char* new_argv[] = { - NULL - }; + const char* new_argv[] = {nullptr}; TestInitGoogleMock(argv, new_argv, GMOCK_FLAG(verbose)); } TEST(InitGoogleMockTest, ParsesEmptyCommandLine) { - const char* argv[] = { - "foo.exe", - NULL - }; + const char* argv[] = {"foo.exe", nullptr}; - const char* new_argv[] = { - "foo.exe", - NULL - }; + const char* new_argv[] = {"foo.exe", nullptr}; TestInitGoogleMock(argv, new_argv, GMOCK_FLAG(verbose)); } TEST(InitGoogleMockTest, ParsesSingleFlag) { - const char* argv[] = { - "foo.exe", - "--gmock_verbose=info", - NULL - }; + const char* argv[] = {"foo.exe", "--gmock_verbose=info", nullptr}; + + const char* new_argv[] = {"foo.exe", nullptr}; + + TestInitGoogleMock(argv, new_argv, "info"); +} - const char* new_argv[] = { - "foo.exe", - NULL - }; +TEST(InitGoogleMockTest, ParsesMultipleFlags) { + int old_default_behavior = GMOCK_FLAG(default_mock_behavior); + const wchar_t* argv[] = {L"foo.exe", L"--gmock_verbose=info", + L"--gmock_default_mock_behavior=2", nullptr}; + + const wchar_t* new_argv[] = {L"foo.exe", nullptr}; TestInitGoogleMock(argv, new_argv, "info"); + EXPECT_EQ(2, GMOCK_FLAG(default_mock_behavior)); + EXPECT_NE(2, old_default_behavior); + GMOCK_FLAG(default_mock_behavior) = old_default_behavior; } TEST(InitGoogleMockTest, ParsesUnrecognizedFlag) { - const char* argv[] = { - "foo.exe", - "--non_gmock_flag=blah", - NULL - }; - - const char* new_argv[] = { - "foo.exe", - "--non_gmock_flag=blah", - NULL - }; + const char* argv[] = {"foo.exe", "--non_gmock_flag=blah", nullptr}; + + const char* new_argv[] = {"foo.exe", "--non_gmock_flag=blah", nullptr}; TestInitGoogleMock(argv, new_argv, GMOCK_FLAG(verbose)); } TEST(InitGoogleMockTest, ParsesGoogleMockFlagAndUnrecognizedFlag) { - const char* argv[] = { - "foo.exe", - "--non_gmock_flag=blah", - "--gmock_verbose=error", - NULL - }; - - const char* new_argv[] = { - "foo.exe", - "--non_gmock_flag=blah", - NULL - }; + const char* argv[] = {"foo.exe", "--non_gmock_flag=blah", + "--gmock_verbose=error", nullptr}; + + const char* new_argv[] = {"foo.exe", "--non_gmock_flag=blah", nullptr}; TestInitGoogleMock(argv, new_argv, "error"); } TEST(WideInitGoogleMockTest, ParsesInvalidCommandLine) { - const wchar_t* argv[] = { - NULL - }; + const wchar_t* argv[] = {nullptr}; - const wchar_t* new_argv[] = { - NULL - }; + const wchar_t* new_argv[] = {nullptr}; TestInitGoogleMock(argv, new_argv, GMOCK_FLAG(verbose)); } TEST(WideInitGoogleMockTest, ParsesEmptyCommandLine) { - const wchar_t* argv[] = { - L"foo.exe", - NULL - }; + const wchar_t* argv[] = {L"foo.exe", nullptr}; - const wchar_t* new_argv[] = { - L"foo.exe", - NULL - }; + const wchar_t* new_argv[] = {L"foo.exe", nullptr}; TestInitGoogleMock(argv, new_argv, GMOCK_FLAG(verbose)); } TEST(WideInitGoogleMockTest, ParsesSingleFlag) { - const wchar_t* argv[] = { - L"foo.exe", - L"--gmock_verbose=info", - NULL - }; + const wchar_t* argv[] = {L"foo.exe", L"--gmock_verbose=info", nullptr}; + + const wchar_t* new_argv[] = {L"foo.exe", nullptr}; + + TestInitGoogleMock(argv, new_argv, "info"); +} + +TEST(WideInitGoogleMockTest, ParsesMultipleFlags) { + int old_default_behavior = GMOCK_FLAG(default_mock_behavior); + const wchar_t* argv[] = {L"foo.exe", L"--gmock_verbose=info", + L"--gmock_default_mock_behavior=2", nullptr}; - const wchar_t* new_argv[] = { - L"foo.exe", - NULL - }; + const wchar_t* new_argv[] = {L"foo.exe", nullptr}; TestInitGoogleMock(argv, new_argv, "info"); + EXPECT_EQ(2, GMOCK_FLAG(default_mock_behavior)); + EXPECT_NE(2, old_default_behavior); + GMOCK_FLAG(default_mock_behavior) = old_default_behavior; } TEST(WideInitGoogleMockTest, ParsesUnrecognizedFlag) { - const wchar_t* argv[] = { - L"foo.exe", - L"--non_gmock_flag=blah", - NULL - }; - - const wchar_t* new_argv[] = { - L"foo.exe", - L"--non_gmock_flag=blah", - NULL - }; + const wchar_t* argv[] = {L"foo.exe", L"--non_gmock_flag=blah", nullptr}; + + const wchar_t* new_argv[] = {L"foo.exe", L"--non_gmock_flag=blah", nullptr}; TestInitGoogleMock(argv, new_argv, GMOCK_FLAG(verbose)); } TEST(WideInitGoogleMockTest, ParsesGoogleMockFlagAndUnrecognizedFlag) { - const wchar_t* argv[] = { - L"foo.exe", - L"--non_gmock_flag=blah", - L"--gmock_verbose=error", - NULL - }; - - const wchar_t* new_argv[] = { - L"foo.exe", - L"--non_gmock_flag=blah", - NULL - }; + const wchar_t* argv[] = {L"foo.exe", L"--non_gmock_flag=blah", + L"--gmock_verbose=error", nullptr}; + + const wchar_t* new_argv[] = {L"foo.exe", L"--non_gmock_flag=blah", nullptr}; TestInitGoogleMock(argv, new_argv, "error"); } diff --git a/googlemock/test/gmock_test_utils.py b/googlemock/test/gmock_test_utils.py index 20e3d3d..7dc4e11 100755 --- a/googlemock/test/gmock_test_utils.py +++ b/googlemock/test/gmock_test_utils.py @@ -1,5 +1,3 @@ -#!/usr/bin/env python -# # Copyright 2006, Google Inc. # All rights reserved. # @@ -31,24 +29,22 @@ """Unit test utilities for Google C++ Mocking Framework.""" -__author__ = 'wan@google.com (Zhanyong Wan)' - import os import sys - # Determines path to gtest_test_utils and imports it. SCRIPT_DIR = os.path.dirname(__file__) or '.' # isdir resolves symbolic links. -gtest_tests_util_dir = os.path.join(SCRIPT_DIR, '../gtest/test') +gtest_tests_util_dir = os.path.join(SCRIPT_DIR, '../../googletest/test') if os.path.isdir(gtest_tests_util_dir): GTEST_TESTS_UTIL_DIR = gtest_tests_util_dir else: - GTEST_TESTS_UTIL_DIR = os.path.join(SCRIPT_DIR, '../../gtest/test') - + GTEST_TESTS_UTIL_DIR = os.path.join(SCRIPT_DIR, '../../googletest/test') sys.path.append(GTEST_TESTS_UTIL_DIR) -import gtest_test_utils # pylint: disable-msg=C6204 + +# pylint: disable=C6204 +import gtest_test_utils def GetSourceDir(): |