From bafa644c182e0d9ed1c21d97b16305a07633ec2d Mon Sep 17 00:00:00 2001 From: Krystian Kuzniarek Date: Tue, 10 Sep 2019 14:14:01 +0200 Subject: [PATCH 001/541] remove a dead function --- googletest/include/gtest/internal/gtest-port.h | 4 ---- 1 file changed, 4 deletions(-) diff --git a/googletest/include/gtest/internal/gtest-port.h b/googletest/include/gtest/internal/gtest-port.h index 830aa1918d..29d9edf4fc 100644 --- a/googletest/include/gtest/internal/gtest-port.h +++ b/googletest/include/gtest/internal/gtest-port.h @@ -2019,10 +2019,6 @@ inline bool IsDir(const StatStruct& st) { return S_ISDIR(st.st_mode); } GTEST_DISABLE_MSC_DEPRECATED_PUSH_() -inline const char* StrNCpy(char* dest, const char* src, size_t n) { - return strncpy(dest, src, n); -} - // ChDir(), FReopen(), FDOpen(), Read(), Write(), Close(), and // StrError() aren't needed on Windows CE at this time and thus not // defined there. From 838ea5cea301b9158ecfa6665908bdf748d07909 Mon Sep 17 00:00:00 2001 From: Krystian Kuzniarek Date: Tue, 10 Sep 2019 14:14:45 +0200 Subject: [PATCH 002/541] remove GTEST_HAS_STD_STRING --- googletest/include/gtest/internal/gtest-port.h | 9 --------- 1 file changed, 9 deletions(-) diff --git a/googletest/include/gtest/internal/gtest-port.h b/googletest/include/gtest/internal/gtest-port.h index 830aa1918d..25b1d13e62 100644 --- a/googletest/include/gtest/internal/gtest-port.h +++ b/googletest/include/gtest/internal/gtest-port.h @@ -439,15 +439,6 @@ typedef struct _RTL_CRITICAL_SECTION GTEST_CRITICAL_SECTION; # endif // defined(_MSC_VER) || defined(__BORLANDC__) #endif // GTEST_HAS_EXCEPTIONS -#if !defined(GTEST_HAS_STD_STRING) -// Even though we don't use this macro any longer, we keep it in case -// some clients still depend on it. -# define GTEST_HAS_STD_STRING 1 -#elif !GTEST_HAS_STD_STRING -// The user told us that ::std::string isn't available. -# error "::std::string isn't available." -#endif // !defined(GTEST_HAS_STD_STRING) - #ifndef GTEST_HAS_STD_WSTRING // The user didn't tell us whether ::std::wstring is available, so we need // to figure it out. From 0cd3fbc8abe649ac61f76b364a181f047a5e9e31 Mon Sep 17 00:00:00 2001 From: Krystian Kuzniarek Date: Tue, 10 Sep 2019 14:14:17 +0200 Subject: [PATCH 003/541] change includes in gtest-port.h --- googletest/include/gtest/gtest-message.h | 1 + googletest/include/gtest/internal/gtest-port.h | 5 +---- 2 files changed, 2 insertions(+), 4 deletions(-) diff --git a/googletest/include/gtest/gtest-message.h b/googletest/include/gtest/gtest-message.h index 4a80e11e6b..21899232a2 100644 --- a/googletest/include/gtest/gtest-message.h +++ b/googletest/include/gtest/gtest-message.h @@ -49,6 +49,7 @@ #include #include +#include #include "gtest/internal/gtest-port.h" diff --git a/googletest/include/gtest/internal/gtest-port.h b/googletest/include/gtest/internal/gtest-port.h index 29d9edf4fc..2f351ecaff 100644 --- a/googletest/include/gtest/internal/gtest-port.h +++ b/googletest/include/gtest/internal/gtest-port.h @@ -248,7 +248,6 @@ #include #include #include -#include #include #ifndef _WIN32_WCE @@ -261,12 +260,10 @@ # include #endif -#include // NOLINT #include // NOLINT -#include // NOLINT +#include #include // NOLINT #include -#include #include // NOLINT #include "gtest/internal/gtest-port-arch.h" From c96da8fea82ec30325a94b78645e8453bddd1dca Mon Sep 17 00:00:00 2001 From: Krystian Kuzniarek Date: Thu, 22 Aug 2019 22:16:01 +0200 Subject: [PATCH 004/541] change usings --- googlemock/test/gmock-spec-builders_test.cc | 2 +- googletest/test/googletest-printers-test.cc | 1 - 2 files changed, 1 insertion(+), 2 deletions(-) diff --git a/googlemock/test/gmock-spec-builders_test.cc b/googlemock/test/gmock-spec-builders_test.cc index 7bf5a8ad7b..791a247681 100644 --- a/googlemock/test/gmock-spec-builders_test.cc +++ b/googlemock/test/gmock-spec-builders_test.cc @@ -69,8 +69,8 @@ using testing::AtMost; using testing::Between; using testing::Cardinality; using testing::CardinalityInterface; -using testing::ContainsRegex; using testing::Const; +using testing::ContainsRegex; using testing::DoAll; using testing::DoDefault; using testing::Eq; diff --git a/googletest/test/googletest-printers-test.cc b/googletest/test/googletest-printers-test.cc index 4bdc9adde9..58be7d1c86 100644 --- a/googletest/test/googletest-printers-test.cc +++ b/googletest/test/googletest-printers-test.cc @@ -219,7 +219,6 @@ using ::testing::PrintToString; using ::testing::internal::FormatForComparisonFailureMessage; using ::testing::internal::ImplicitCast_; using ::testing::internal::NativeArray; -using ::testing::internal::RE; using ::testing::internal::RelationToSourceReference; using ::testing::internal::Strings; using ::testing::internal::UniversalPrint; From 7c2bd3af981e9f257a0b61ce664953008c105dad Mon Sep 17 00:00:00 2001 From: Krystian Kuzniarek Date: Sat, 7 Sep 2019 06:08:28 +0200 Subject: [PATCH 005/541] square away the stuff that hasn't been merged in a manual review This fixes up ab8f346b (a manual merge) that has abandoned some things from PR #2395. --- googlemock/include/gmock/gmock-matchers.h | 4 ++-- googlemock/include/gmock/internal/gmock-internal-utils.h | 2 -- googlemock/test/gmock-internal-utils_test.cc | 1 - 3 files changed, 2 insertions(+), 5 deletions(-) diff --git a/googlemock/include/gmock/gmock-matchers.h b/googlemock/include/gmock/gmock-matchers.h index bf9eb205e3..9bff5a72b7 100644 --- a/googlemock/include/gmock/gmock-matchers.h +++ b/googlemock/include/gmock/gmock-matchers.h @@ -1607,8 +1607,8 @@ class PointeeMatcher { template class Impl : public MatcherInterface { public: - typedef typename PointeeOf::type>::type>::type Pointee; + typedef typename PointeeOf::type + Pointee; explicit Impl(const InnerMatcher& matcher) : matcher_(MatcherCast(matcher)) {} diff --git a/googlemock/include/gmock/internal/gmock-internal-utils.h b/googlemock/include/gmock/internal/gmock-internal-utils.h index fdc049c589..d012e710b5 100644 --- a/googlemock/include/gmock/internal/gmock-internal-utils.h +++ b/googlemock/include/gmock/internal/gmock-internal-utils.h @@ -334,8 +334,6 @@ class WithoutMatchers { // Internal use only: access the singleton instance of WithoutMatchers. GTEST_API_ WithoutMatchers GetWithoutMatchers(); -// Type traits. - // Disable MSVC warnings for infinite recursion, since in this case the // the recursion is unreachable. #ifdef _MSC_VER diff --git a/googlemock/test/gmock-internal-utils_test.cc b/googlemock/test/gmock-internal-utils_test.cc index d000e6924c..19ba6fe5c7 100644 --- a/googlemock/test/gmock-internal-utils_test.cc +++ b/googlemock/test/gmock-internal-utils_test.cc @@ -40,7 +40,6 @@ #include #include #include -#include #include #include "gmock/gmock.h" From 3339b97c6a7fb908cd343ff8251d86782ea264a8 Mon Sep 17 00:00:00 2001 From: Krystian Kuzniarek Date: Mon, 16 Sep 2019 19:11:20 +0200 Subject: [PATCH 006/541] square away the stuff that hasn't been merged in a manual review This fixes up f2fb48c3 (a manual merge) that has abandoned some things from PR #2407. --- googletest/docs/advanced.md | 2 +- googletest/include/gtest/gtest.h | 3 +-- 2 files changed, 2 insertions(+), 3 deletions(-) diff --git a/googletest/docs/advanced.md b/googletest/docs/advanced.md index 3e5f779d0a..c30ef85eab 100644 --- a/googletest/docs/advanced.md +++ b/googletest/docs/advanced.md @@ -465,7 +465,7 @@ You can call the function to assert that types `T1` and `T2` are the same. The function does nothing if the assertion is satisfied. If the types are different, the function call will fail to compile, the compiler error message will say that -`type1 and type2 are not the same type` and most likely (depending on the compiler) +`T1 and T2 are not the same type` and most likely (depending on the compiler) show you the actual values of `T1` and `T2`. This is mainly useful inside template code. diff --git a/googletest/include/gtest/gtest.h b/googletest/include/gtest/gtest.h index dbe5b1c2c3..37a1762bf8 100644 --- a/googletest/include/gtest/gtest.h +++ b/googletest/include/gtest/gtest.h @@ -2298,8 +2298,7 @@ class GTEST_API_ ScopedTrace { // to cause a compiler error. template constexpr bool StaticAssertTypeEq() noexcept { - static_assert(std::is_same::value, - "type1 and type2 are not the same type"); + static_assert(std::is_same::value, "T1 and T2 are not the same type"); return true; } From 90a8ab70a1f604f35801569683450834f5e6ce3b Mon Sep 17 00:00:00 2001 From: Krystian Kuzniarek Date: Thu, 22 Aug 2019 22:41:10 +0200 Subject: [PATCH 007/541] mention the existing support for wide strings in string matchers --- googlemock/docs/cheat_sheet.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/googlemock/docs/cheat_sheet.md b/googlemock/docs/cheat_sheet.md index 850963af28..1f7ed92901 100644 --- a/googlemock/docs/cheat_sheet.md +++ b/googlemock/docs/cheat_sheet.md @@ -326,8 +326,8 @@ The `argument` can be either a C string or a C++ string object: `ContainsRegex()` and `MatchesRegex()` take ownership of the `RE` object. They use the regular expression syntax defined [here](../../googletest/docs/advanced.md#regular-expression-syntax). -`StrCaseEq()`, `StrCaseNe()`, `StrEq()`, and `StrNe()` work for wide strings as -well. +All of these matchers, except `ContainsRegex()` and `MatchesRegex()` work for +wide strings as well. #### Container Matchers From e0d16aa33662857a5b3f47359f46910d4d18ab5b Mon Sep 17 00:00:00 2001 From: Krystian Kuzniarek Date: Thu, 5 Sep 2019 01:03:20 +0200 Subject: [PATCH 008/541] remove GTEST_ARRAY_SIZE_ This macro didn't work when an array was passed to a function by pointer, in which case the information about its size was lost. Better alternatives are: * std::extent::value (compile-time) * std::array::size() (compile-time) * std::distance(std::begin(array), std::end(array)) (run-time) --- .../test/gmock-generated-matchers_test.cc | 51 +++++++++---------- googlemock/test/gmock-matchers_test.cc | 32 ++++++------ .../include/gtest/internal/gtest-port.h | 3 -- 3 files changed, 42 insertions(+), 44 deletions(-) diff --git a/googlemock/test/gmock-generated-matchers_test.cc b/googlemock/test/gmock-generated-matchers_test.cc index 6c4b30008b..6dc951c0a5 100644 --- a/googlemock/test/gmock-generated-matchers_test.cc +++ b/googlemock/test/gmock-generated-matchers_test.cc @@ -41,6 +41,8 @@ #include "gmock/gmock-generated-matchers.h" +#include +#include #include #include #include @@ -195,7 +197,7 @@ TEST(ElementsAreTest, ExplainsNonTrivialMatch) { ElementsAre(GreaterThan(1), 0, GreaterThan(2)); const int a[] = { 10, 0, 100 }; - vector test_vector(a, a + GTEST_ARRAY_SIZE_(a)); + vector test_vector(std::begin(a), std::end(a)); EXPECT_EQ("whose element #0 matches, which is 9 more than 1,\n" "and whose element #2 matches, which is 98 more than 2", Explain(m, test_vector)); @@ -280,7 +282,7 @@ TEST(ElementsAreTest, MatchesThreeElementsMixedMatchers) { TEST(ElementsAreTest, MatchesTenElementVector) { const int a[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }; - vector test_vector(a, a + GTEST_ARRAY_SIZE_(a)); + vector test_vector(std::begin(a), std::end(a)); EXPECT_THAT(test_vector, // The element list can contain values and/or matchers @@ -317,13 +319,10 @@ TEST(ElementsAreTest, DoesNotMatchWrongOrder) { } TEST(ElementsAreTest, WorksForNestedContainer) { - const char* strings[] = { - "Hi", - "world" - }; + constexpr std::array strings = {{"Hi", "world"}}; vector > nested; - for (size_t i = 0; i < GTEST_ARRAY_SIZE_(strings); i++) { + for (size_t i = 0; i < strings.size(); i++) { nested.push_back(list(strings[i], strings[i] + strlen(strings[i]))); } @@ -335,7 +334,7 @@ TEST(ElementsAreTest, WorksForNestedContainer) { TEST(ElementsAreTest, WorksWithByRefElementMatchers) { int a[] = { 0, 1, 2 }; - vector v(a, a + GTEST_ARRAY_SIZE_(a)); + vector v(std::begin(a), std::end(a)); EXPECT_THAT(v, ElementsAre(Ref(v[0]), Ref(v[1]), Ref(v[2]))); EXPECT_THAT(v, Not(ElementsAre(Ref(v[0]), Ref(v[1]), Ref(a[2])))); @@ -343,7 +342,7 @@ TEST(ElementsAreTest, WorksWithByRefElementMatchers) { TEST(ElementsAreTest, WorksWithContainerPointerUsingPointee) { int a[] = { 0, 1, 2 }; - vector v(a, a + GTEST_ARRAY_SIZE_(a)); + vector v(std::begin(a), std::end(a)); EXPECT_THAT(&v, Pointee(ElementsAre(0, 1, _))); EXPECT_THAT(&v, Not(Pointee(ElementsAre(0, _, 3)))); @@ -440,7 +439,7 @@ TEST(ElementsAreTest, MakesCopyOfArguments) { TEST(ElementsAreArrayTest, CanBeCreatedWithValueArray) { const int a[] = { 1, 2, 3 }; - vector test_vector(a, a + GTEST_ARRAY_SIZE_(a)); + vector test_vector(std::begin(a), std::end(a)); EXPECT_THAT(test_vector, ElementsAreArray(a)); test_vector[2] = 0; @@ -448,20 +447,20 @@ TEST(ElementsAreArrayTest, CanBeCreatedWithValueArray) { } TEST(ElementsAreArrayTest, CanBeCreatedWithArraySize) { - const char* a[] = { "one", "two", "three" }; + std::array a = {{"one", "two", "three"}}; - vector test_vector(a, a + GTEST_ARRAY_SIZE_(a)); - EXPECT_THAT(test_vector, ElementsAreArray(a, GTEST_ARRAY_SIZE_(a))); + vector test_vector(std::begin(a), std::end(a)); + EXPECT_THAT(test_vector, ElementsAreArray(a.data(), a.size())); - const char** p = a; + const char** p = a.data(); test_vector[0] = "1"; - EXPECT_THAT(test_vector, Not(ElementsAreArray(p, GTEST_ARRAY_SIZE_(a)))); + EXPECT_THAT(test_vector, Not(ElementsAreArray(p, a.size()))); } TEST(ElementsAreArrayTest, CanBeCreatedWithoutArraySize) { const char* a[] = { "one", "two", "three" }; - vector test_vector(a, a + GTEST_ARRAY_SIZE_(a)); + vector test_vector(std::begin(a), std::end(a)); EXPECT_THAT(test_vector, ElementsAreArray(a)); test_vector[0] = "1"; @@ -484,8 +483,8 @@ TEST(ElementsAreArrayTest, CanBeCreatedWithMatcherArray) { TEST(ElementsAreArrayTest, CanBeCreatedWithVector) { const int a[] = { 1, 2, 3 }; - vector test_vector(a, a + GTEST_ARRAY_SIZE_(a)); - const vector expected(a, a + GTEST_ARRAY_SIZE_(a)); + vector test_vector(std::begin(a), std::end(a)); + const vector expected(std::begin(a), std::end(a)); EXPECT_THAT(test_vector, ElementsAreArray(expected)); test_vector.push_back(4); EXPECT_THAT(test_vector, Not(ElementsAreArray(expected))); @@ -530,9 +529,9 @@ TEST(ElementsAreArrayTest, TEST(ElementsAreArrayTest, CanBeCreatedWithMatcherVector) { const int a[] = { 1, 2, 3 }; const Matcher kMatchers[] = { Eq(1), Eq(2), Eq(3) }; - vector test_vector(a, a + GTEST_ARRAY_SIZE_(a)); - const vector > expected( - kMatchers, kMatchers + GTEST_ARRAY_SIZE_(kMatchers)); + vector test_vector(std::begin(a), std::end(a)); + const vector> expected(std::begin(kMatchers), + std::end(kMatchers)); EXPECT_THAT(test_vector, ElementsAreArray(expected)); test_vector.push_back(4); EXPECT_THAT(test_vector, Not(ElementsAreArray(expected))); @@ -540,11 +539,11 @@ TEST(ElementsAreArrayTest, CanBeCreatedWithMatcherVector) { TEST(ElementsAreArrayTest, CanBeCreatedWithIteratorRange) { const int a[] = { 1, 2, 3 }; - const vector test_vector(a, a + GTEST_ARRAY_SIZE_(a)); - const vector expected(a, a + GTEST_ARRAY_SIZE_(a)); + const vector test_vector(std::begin(a), std::end(a)); + const vector expected(std::begin(a), std::end(a)); EXPECT_THAT(test_vector, ElementsAreArray(expected.begin(), expected.end())); // Pointers are iterators, too. - EXPECT_THAT(test_vector, ElementsAreArray(a, a + GTEST_ARRAY_SIZE_(a))); + EXPECT_THAT(test_vector, ElementsAreArray(std::begin(a), std::end(a))); // The empty range of NULL pointers should also be okay. int* const null_int = nullptr; EXPECT_THAT(test_vector, Not(ElementsAreArray(null_int, null_int))); @@ -564,8 +563,8 @@ TEST(ElementsAreArrayTest, WorksWithNativeArray) { TEST(ElementsAreArrayTest, SourceLifeSpan) { const int a[] = { 1, 2, 3 }; - vector test_vector(a, a + GTEST_ARRAY_SIZE_(a)); - vector expect(a, a + GTEST_ARRAY_SIZE_(a)); + vector test_vector(std::begin(a), std::end(a)); + vector expect(std::begin(a), std::end(a)); ElementsAreArrayMatcher matcher_maker = ElementsAreArray(expect.begin(), expect.end()); EXPECT_THAT(test_vector, matcher_maker); diff --git a/googlemock/test/gmock-matchers_test.cc b/googlemock/test/gmock-matchers_test.cc index 88f144d1c1..8a500673fc 100644 --- a/googlemock/test/gmock-matchers_test.cc +++ b/googlemock/test/gmock-matchers_test.cc @@ -45,6 +45,7 @@ #include #include +#include #include #include #include @@ -5083,14 +5084,14 @@ TEST(WhenSortedTest, WorksForStreamlike) { // Streamlike 'container' provides only minimal iterator support. // Its iterators are tagged with input_iterator_tag. const int a[5] = {2, 1, 4, 5, 3}; - Streamlike s(a, a + GTEST_ARRAY_SIZE_(a)); + Streamlike s(std::begin(a), std::end(a)); EXPECT_THAT(s, WhenSorted(ElementsAre(1, 2, 3, 4, 5))); EXPECT_THAT(s, Not(WhenSorted(ElementsAre(2, 1, 4, 5, 3)))); } TEST(WhenSortedTest, WorksForVectorConstRefMatcherOnStreamlike) { const int a[] = {2, 1, 4, 5, 3}; - Streamlike s(a, a + GTEST_ARRAY_SIZE_(a)); + Streamlike s(std::begin(a), std::end(a)); Matcher&> vector_match = ElementsAre(1, 2, 3, 4, 5); EXPECT_THAT(s, WhenSorted(vector_match)); EXPECT_THAT(s, Not(WhenSorted(ElementsAre(2, 1, 4, 5, 3)))); @@ -5135,7 +5136,7 @@ TEST(IsSupersetOfTest, WorksForEmpty) { TEST(IsSupersetOfTest, WorksForStreamlike) { const int a[5] = {1, 2, 3, 4, 5}; - Streamlike s(a, a + GTEST_ARRAY_SIZE_(a)); + Streamlike s(std::begin(a), std::end(a)); vector expected; expected.push_back(1); @@ -5263,7 +5264,7 @@ TEST(IsSubsetOfTest, WorksForEmpty) { TEST(IsSubsetOfTest, WorksForStreamlike) { const int a[5] = {1, 2}; - Streamlike s(a, a + GTEST_ARRAY_SIZE_(a)); + Streamlike s(std::begin(a), std::end(a)); vector expected; expected.push_back(1); @@ -5357,14 +5358,14 @@ TEST(IsSubsetOfTest, WorksWithMoveOnly) { TEST(ElemensAreStreamTest, WorksForStreamlike) { const int a[5] = {1, 2, 3, 4, 5}; - Streamlike s(a, a + GTEST_ARRAY_SIZE_(a)); + Streamlike s(std::begin(a), std::end(a)); EXPECT_THAT(s, ElementsAre(1, 2, 3, 4, 5)); EXPECT_THAT(s, Not(ElementsAre(2, 1, 4, 5, 3))); } TEST(ElemensAreArrayStreamTest, WorksForStreamlike) { const int a[5] = {1, 2, 3, 4, 5}; - Streamlike s(a, a + GTEST_ARRAY_SIZE_(a)); + Streamlike s(std::begin(a), std::end(a)); vector expected; expected.push_back(1); @@ -5411,7 +5412,7 @@ TEST(ElementsAreTest, TakesStlContainer) { TEST(UnorderedElementsAreArrayTest, SucceedsWhenExpected) { const int a[] = {0, 1, 2, 3, 4}; - std::vector s(a, a + GTEST_ARRAY_SIZE_(a)); + std::vector s(std::begin(a), std::end(a)); do { StringMatchResultListener listener; EXPECT_TRUE(ExplainMatchResult(UnorderedElementsAreArray(a), @@ -5422,8 +5423,8 @@ TEST(UnorderedElementsAreArrayTest, SucceedsWhenExpected) { TEST(UnorderedElementsAreArrayTest, VectorBool) { const bool a[] = {0, 1, 0, 1, 1}; const bool b[] = {1, 0, 1, 1, 0}; - std::vector expected(a, a + GTEST_ARRAY_SIZE_(a)); - std::vector actual(b, b + GTEST_ARRAY_SIZE_(b)); + std::vector expected(std::begin(a), std::end(a)); + std::vector actual(std::begin(b), std::end(b)); StringMatchResultListener listener; EXPECT_TRUE(ExplainMatchResult(UnorderedElementsAreArray(expected), actual, &listener)) << listener.str(); @@ -5434,7 +5435,7 @@ TEST(UnorderedElementsAreArrayTest, WorksForStreamlike) { // Its iterators are tagged with input_iterator_tag, and it has no // size() or empty() methods. const int a[5] = {2, 1, 4, 5, 3}; - Streamlike s(a, a + GTEST_ARRAY_SIZE_(a)); + Streamlike s(std::begin(a), std::end(a)); ::std::vector expected; expected.push_back(1); @@ -5517,7 +5518,7 @@ TEST_F(UnorderedElementsAreTest, WorksWithUncopyable) { TEST_F(UnorderedElementsAreTest, SucceedsWhenExpected) { const int a[] = {1, 2, 3}; - std::vector s(a, a + GTEST_ARRAY_SIZE_(a)); + std::vector s(std::begin(a), std::end(a)); do { StringMatchResultListener listener; EXPECT_TRUE(ExplainMatchResult(UnorderedElementsAre(1, 2, 3), @@ -5527,7 +5528,7 @@ TEST_F(UnorderedElementsAreTest, SucceedsWhenExpected) { TEST_F(UnorderedElementsAreTest, FailsWhenAnElementMatchesNoMatcher) { const int a[] = {1, 2, 3}; - std::vector s(a, a + GTEST_ARRAY_SIZE_(a)); + std::vector s(std::begin(a), std::end(a)); std::vector > mv; mv.push_back(1); mv.push_back(2); @@ -5543,7 +5544,7 @@ TEST_F(UnorderedElementsAreTest, WorksForStreamlike) { // Its iterators are tagged with input_iterator_tag, and it has no // size() or empty() methods. const int a[5] = {2, 1, 4, 5, 3}; - Streamlike s(a, a + GTEST_ARRAY_SIZE_(a)); + Streamlike s(std::begin(a), std::end(a)); EXPECT_THAT(s, UnorderedElementsAre(1, 2, 3, 4, 5)); EXPECT_THAT(s, Not(UnorderedElementsAre(2, 2, 3, 4, 5))); @@ -5859,8 +5860,9 @@ TEST_F(BipartiteNonSquareTest, SimpleBacktracking) { // :.......: // 0 1 2 MatchMatrix g(4, 3); - static const size_t kEdges[][2] = {{0, 2}, {1, 1}, {2, 1}, {3, 0}}; - for (size_t i = 0; i < GTEST_ARRAY_SIZE_(kEdges); ++i) { + constexpr std::array, 4> kEdges = { + {{{0, 2}}, {{1, 1}}, {{2, 1}}, {{3, 0}}}}; + for (size_t i = 0; i < kEdges.size(); ++i) { g.SetEdge(kEdges[i][0], kEdges[i][1], true); } EXPECT_THAT(FindBacktrackingMaxBPM(g), diff --git a/googletest/include/gtest/internal/gtest-port.h b/googletest/include/gtest/internal/gtest-port.h index 063fcb1083..f7a62f02e4 100644 --- a/googletest/include/gtest/internal/gtest-port.h +++ b/googletest/include/gtest/internal/gtest-port.h @@ -856,9 +856,6 @@ class Secret; // expression is false, compiler will issue an error containing this identifier. #define GTEST_COMPILE_ASSERT_(expr, msg) static_assert(expr, #msg) -// Evaluates to the number of elements in 'array'. -#define GTEST_ARRAY_SIZE_(array) (sizeof(array) / sizeof(array[0])) - // A helper for suppressing warnings on constant condition. It just // returns 'condition'. GTEST_API_ bool IsTrue(bool condition); From 2460f97152c93cdbc6c1d5cceba1265e89921579 Mon Sep 17 00:00:00 2001 From: Peter Barker Date: Fri, 16 Aug 2019 09:40:45 +1000 Subject: [PATCH 009/541] Add many missing override keywords This helps corrects builds with -Werror=suggest-overrides --- googletest/include/gtest/gtest-matchers.h | 6 +++--- googletest/include/gtest/gtest-param-test.h | 2 +- googletest/include/gtest/internal/gtest-internal.h | 2 +- googletest/include/gtest/internal/gtest-port.h | 4 ++-- 4 files changed, 7 insertions(+), 7 deletions(-) diff --git a/googletest/include/gtest/gtest-matchers.h b/googletest/include/gtest/gtest-matchers.h index 9de6c2e10a..d9b28e08a3 100644 --- a/googletest/include/gtest/gtest-matchers.h +++ b/googletest/include/gtest/gtest-matchers.h @@ -474,13 +474,13 @@ class PolymorphicMatcher { public: explicit MonomorphicImpl(const Impl& impl) : impl_(impl) {} - virtual void DescribeTo(::std::ostream* os) const { impl_.DescribeTo(os); } + void DescribeTo(::std::ostream* os) const override { impl_.DescribeTo(os); } - virtual void DescribeNegationTo(::std::ostream* os) const { + void DescribeNegationTo(::std::ostream* os) const override { impl_.DescribeNegationTo(os); } - virtual bool MatchAndExplain(T x, MatchResultListener* listener) const { + bool MatchAndExplain(T x, MatchResultListener* listener) const override { return impl_.MatchAndExplain(x, listener); } diff --git a/googletest/include/gtest/gtest-param-test.h b/googletest/include/gtest/gtest-param-test.h index c2e6eae3d8..e1135e998e 100644 --- a/googletest/include/gtest/gtest-param-test.h +++ b/googletest/include/gtest/gtest-param-test.h @@ -416,7 +416,7 @@ internal::CartesianProductHolder Combine(const Generator&... g) { : public test_suite_name { \ public: \ GTEST_TEST_CLASS_NAME_(test_suite_name, test_name)() {} \ - virtual void TestBody(); \ + void TestBody() override; \ \ private: \ static int AddToRegistry() { \ diff --git a/googletest/include/gtest/internal/gtest-internal.h b/googletest/include/gtest/internal/gtest-internal.h index 82ec6e24f1..37a18b52bc 100644 --- a/googletest/include/gtest/internal/gtest-internal.h +++ b/googletest/include/gtest/internal/gtest-internal.h @@ -1354,7 +1354,7 @@ constexpr bool InstantiateTypedTestCase_P_IsDeprecated() { return true; } GTEST_TEST_CLASS_NAME_(test_suite_name, test_name)() {} \ \ private: \ - virtual void TestBody(); \ + void TestBody() override; \ static ::testing::TestInfo* const test_info_ GTEST_ATTRIBUTE_UNUSED_; \ GTEST_DISALLOW_COPY_AND_ASSIGN_(GTEST_TEST_CLASS_NAME_(test_suite_name, \ test_name)); \ diff --git a/googletest/include/gtest/internal/gtest-port.h b/googletest/include/gtest/internal/gtest-port.h index 063fcb1083..3c9f725143 100644 --- a/googletest/include/gtest/internal/gtest-port.h +++ b/googletest/include/gtest/internal/gtest-port.h @@ -1808,7 +1808,7 @@ class GTEST_API_ ThreadLocal { class DefaultValueHolderFactory : public ValueHolderFactory { public: DefaultValueHolderFactory() {} - virtual ValueHolder* MakeNewHolder() const { return new ValueHolder(); } + ValueHolder* MakeNewHolder() const override { return new ValueHolder(); } private: GTEST_DISALLOW_COPY_AND_ASSIGN_(DefaultValueHolderFactory); @@ -1817,7 +1817,7 @@ class GTEST_API_ ThreadLocal { class InstanceValueHolderFactory : public ValueHolderFactory { public: explicit InstanceValueHolderFactory(const T& value) : value_(value) {} - virtual ValueHolder* MakeNewHolder() const { + ValueHolder* MakeNewHolder() const override { return new ValueHolder(value_); } From 51f7396d40585f6d785b7d1218be9319c358092a Mon Sep 17 00:00:00 2001 From: "hyuk.myeong" Date: Tue, 1 Oct 2019 14:24:55 +0900 Subject: [PATCH 010/541] Fix typo in documents --- googlemock/docs/for_dummies.md | 2 +- googletest/docs/advanced.md | 10 ++++------ googletest/docs/faq.md | 4 ++-- 3 files changed, 7 insertions(+), 9 deletions(-) diff --git a/googlemock/docs/for_dummies.md b/googlemock/docs/for_dummies.md index e11c18d9bf..93cf06f38e 100644 --- a/googlemock/docs/for_dummies.md +++ b/googlemock/docs/for_dummies.md @@ -213,7 +213,7 @@ specific domain much better than `Foo` does. Once you have a mock class, using it is easy. The typical work flow is: 1. Import the gMock names from the `testing` namespace such that you can use - them unqualified (You only have to do it once per file. Remember that + them unqualified (You only have to do it once per file). Remember that namespaces are a good idea. 2. Create some mock objects. 3. Specify your expectations on them (How many times will a method be called? diff --git a/googletest/docs/advanced.md b/googletest/docs/advanced.md index 3e5f779d0a..ef20379b40 100644 --- a/googletest/docs/advanced.md +++ b/googletest/docs/advanced.md @@ -642,7 +642,7 @@ Fatal assertion | Nonfatal assertion where `statement` is a statement that is expected to cause the process to die, `predicate` is a function or function object that evaluates an integer exit -status, and `matcher` is either a GMock matcher matching a `const std::string&` +status, and `matcher` is either a gMock matcher matching a `const std::string&` or a (Perl) regular expression - either of which is matched against the stderr output of `statement`. For legacy reasons, a bare string (i.e. with no matcher) is interpreted as `ContainsRegex(str)`, **not** `Eq(str)`. Note that `statement` @@ -657,7 +657,7 @@ As usual, the `ASSERT` variants abort the current test function, while the > has called `exit()` or `_exit()` with a non-zero value, or it may be killed by > a signal. > -> This means that if `*statement*` terminates the process with a 0 exit code, it +> This means that if *`statement`* terminates the process with a 0 exit code, it > is *not* considered a crash by `EXPECT_DEATH`. Use `EXPECT_EXIT` instead if > this is the case, or if you want to restrict the exit code more precisely. @@ -687,7 +687,7 @@ Note that a death test only cares about three things: 2. (in the case of `ASSERT_EXIT` and `EXPECT_EXIT`) does the exit status satisfy `predicate`? Or (in the case of `ASSERT_DEATH` and `EXPECT_DEATH`) is the exit status non-zero? And -3. does the stderr output match `regex`? +3. does the stderr output match `matcher`? In particular, if `statement` generates an `ASSERT_*` or `EXPECT_*` failure, it will **not** cause the death test to fail, as googletest assertions don't abort @@ -1132,7 +1132,7 @@ will output XML like this: > * `RecordProperty()` is a static member of the `Test` class. Therefore it > needs to be prefixed with `::testing::Test::` if used outside of the > `TEST` body and the test fixture class. -> * `*key*` must be a valid XML attribute name, and cannot conflict with the +> * *`key`* must be a valid XML attribute name, and cannot conflict with the > ones already used by googletest (`name`, `status`, `time`, `classname`, > `type_param`, and `value_param`). > * Calling `RecordProperty()` outside of the lifespan of a test is allowed. @@ -1904,8 +1904,6 @@ To obtain a `TestInfo` object for the currently running test, call const ::testing::TestInfo* const test_info = ::testing::UnitTest::GetInstance()->current_test_info(); - - printf("We are in test %s of test suite %s.\n", test_info->name(), test_info->test_suite_name()); diff --git a/googletest/docs/faq.md b/googletest/docs/faq.md index 960a827989..05ecdd7d8d 100644 --- a/googletest/docs/faq.md +++ b/googletest/docs/faq.md @@ -531,8 +531,8 @@ There are several good reasons: ## What can the statement argument in ASSERT_DEATH() be? -`ASSERT_DEATH(*statement*, *regex*)` (or any death assertion macro) can be used -wherever `*statement*` is valid. So basically `*statement*` can be any C++ +`ASSERT_DEATH(statement, matcher)` (or any death assertion macro) can be used +wherever *`statement`* is valid. So basically *`statement`* can be any C++ statement that makes sense in the current context. In particular, it can reference global and/or local variables, and can be: From 76a560c81cfe75cc6f9ff0c4a37ea3d1ce1229ed Mon Sep 17 00:00:00 2001 From: misterg Date: Thu, 3 Oct 2019 12:58:38 -0400 Subject: [PATCH 011/541] Googletest export Add an announcement about taking a dep on Abseil soon PiperOrigin-RevId: 272683117 --- README.md | 23 +++++++++-------------- 1 file changed, 9 insertions(+), 14 deletions(-) diff --git a/README.md b/README.md index 5b417fa883..44e01e2b2b 100644 --- a/README.md +++ b/README.md @@ -5,24 +5,19 @@ [![Build Status](https://api.travis-ci.org/google/googletest.svg?branch=master)](https://travis-ci.org/google/googletest) [![Build status](https://ci.appveyor.com/api/projects/status/4o38plt0xbo1ubc8/branch/master?svg=true)](https://ci.appveyor.com/project/GoogleTestAppVeyor/googletest/branch/master) -### Future Plans +### Announcements: -#### 1.8.x Release: +#### Release 1.10.x -[the 1.8.x](https://github.com/google/googletest/releases/tag/release-1.8.1) is -the last release that works with pre-C++11 compilers. The 1.8.x will not accept -any requests for any new features and any bugfix requests will only be accepted -if proven "critical" +[Release 1.10.x](https://github.com/google/googletest/releases/tag/v1.10.x) is +now available. -#### Post 1.8.x: +#### Coming Soon -On-going work to improve/cleanup/pay technical debt. When this work is completed -there will be a 1.9.x tagged release - -#### Post 1.9.x - -Post 1.9.x googletest will follow -[Abseil Live at Head philosophy](https://abseil.io/about/philosophy) +* Post 1.10.x googletest will follow + [Abseil Live at Head philosophy](https://abseil.io/about/philosophy) +* We are also planning to take a dependency on + [Abseil](https://github.com/abseil/abseil-cpp). ## Welcome to **Google Test**, Google's C++ test framework! From 5126ff48d9ac54828d1947d1423a5ef2a8efee3b Mon Sep 17 00:00:00 2001 From: David Seifert Date: Sat, 5 Oct 2019 15:58:45 +0200 Subject: [PATCH 012/541] Revert "Use pcfiledir for prefix in pkgconfig file" The change makes implicit assumptions on the layout of the install tree, which is going to break in many ways. The correct solution is to use the `PKG_CONFIG_SYSROOT_DIR` variable to inject the cross-compiled sysroot into `-I` and `-L` paths. --- googlemock/cmake/gmock.pc.in | 5 ++--- googlemock/cmake/gmock_main.pc.in | 5 ++--- googletest/cmake/gtest.pc.in | 5 ++--- googletest/cmake/gtest_main.pc.in | 5 ++--- 4 files changed, 8 insertions(+), 12 deletions(-) diff --git a/googlemock/cmake/gmock.pc.in b/googlemock/cmake/gmock.pc.in index 08e0454749..2ef0fbca10 100644 --- a/googlemock/cmake/gmock.pc.in +++ b/googlemock/cmake/gmock.pc.in @@ -1,6 +1,5 @@ -prefix=${pcfiledir}/../.. -libdir=${prefix}/@CMAKE_INSTALL_LIBDIR@ -includedir=${prefix}/@CMAKE_INSTALL_INCLUDEDIR@ +libdir=@CMAKE_INSTALL_FULL_LIBDIR@ +includedir=@CMAKE_INSTALL_FULL_INCLUDEDIR@ Name: gmock Description: GoogleMock (without main() function) diff --git a/googlemock/cmake/gmock_main.pc.in b/googlemock/cmake/gmock_main.pc.in index b22fe61482..04658fe2ee 100644 --- a/googlemock/cmake/gmock_main.pc.in +++ b/googlemock/cmake/gmock_main.pc.in @@ -1,6 +1,5 @@ -prefix=${pcfiledir}/../.. -libdir=${prefix}/@CMAKE_INSTALL_LIBDIR@ -includedir=${prefix}/@CMAKE_INSTALL_INCLUDEDIR@ +libdir=@CMAKE_INSTALL_FULL_LIBDIR@ +includedir=@CMAKE_INSTALL_FULL_INCLUDEDIR@ Name: gmock_main Description: GoogleMock (with main() function) diff --git a/googletest/cmake/gtest.pc.in b/googletest/cmake/gtest.pc.in index 9aae29e267..e7967ad56f 100644 --- a/googletest/cmake/gtest.pc.in +++ b/googletest/cmake/gtest.pc.in @@ -1,6 +1,5 @@ -prefix=${pcfiledir}/../.. -libdir=${prefix}/@CMAKE_INSTALL_LIBDIR@ -includedir=${prefix}/@CMAKE_INSTALL_INCLUDEDIR@ +libdir=@CMAKE_INSTALL_FULL_LIBDIR@ +includedir=@CMAKE_INSTALL_FULL_INCLUDEDIR@ Name: gtest Description: GoogleTest (without main() function) diff --git a/googletest/cmake/gtest_main.pc.in b/googletest/cmake/gtest_main.pc.in index 915f2973af..fe25d9c73c 100644 --- a/googletest/cmake/gtest_main.pc.in +++ b/googletest/cmake/gtest_main.pc.in @@ -1,6 +1,5 @@ -prefix=${pcfiledir}/../.. -libdir=${prefix}/@CMAKE_INSTALL_LIBDIR@ -includedir=${prefix}/@CMAKE_INSTALL_INCLUDEDIR@ +libdir=@CMAKE_INSTALL_FULL_LIBDIR@ +includedir=@CMAKE_INSTALL_FULL_INCLUDEDIR@ Name: gtest_main Description: GoogleTest (with main() function) From b96832a44b4994cafc824f200d69232d79f30d81 Mon Sep 17 00:00:00 2001 From: David Seifert Date: Sat, 5 Oct 2019 15:58:48 +0200 Subject: [PATCH 013/541] Add documentation for pkg-config in cross-compilation settings --- googletest/docs/pkgconfig.md | 78 ++++++++++++++++++++++++++++++++++++ 1 file changed, 78 insertions(+) diff --git a/googletest/docs/pkgconfig.md b/googletest/docs/pkgconfig.md index 6dc0673889..d5f3614481 100644 --- a/googletest/docs/pkgconfig.md +++ b/googletest/docs/pkgconfig.md @@ -139,3 +139,81 @@ export PKG_CONFIG_PATH=/usr/local/lib64/pkgconfig ``` pkg-config will also try to look in `PKG_CONFIG_PATH` to find `gtest_main.pc`. + +### Using pkg-config in a cross-compilation setting + +Pkg-config can be used in a cross-compilation setting too. To do this, let's +assume the final prefix of the cross-compiled installation will be `/usr`, +and your sysroot is `/home/MYUSER/sysroot`. Configure and install GTest using + +``` +mkdir build && cmake -DCMAKE_INSTALL_PREFIX=/usr .. +``` + +Install into the sysroot using `DESTDIR`: + +``` +make -j install DESTDIR=/home/MYUSER/sysroot +``` + +Before we continue, it is recommended to **always** define the following two +variables for pkg-config in a cross-compilation setting: + +``` +export PKG_CONFIG_ALLOW_SYSTEM_CFLAGS=yes +export PKG_CONFIG_ALLOW_SYSTEM_LIBS=yes +``` + +otherwise `pkg-config` will filter `-I` and `-L` flags against standard +prefixes such as `/usr` (see https://bugs.freedesktop.org/show_bug.cgi?id=28264#c3 +for reasons why this stripping needs to occur usually). + +If you look at the generated pkg-config file, it will look something like + +``` +libdir=/usr/lib64 +includedir=/usr/include + +Name: gtest +Description: GoogleTest (without main() function) +Version: 1.10.0 +URL: https://github.com/google/googletest +Libs: -L${libdir} -lgtest -lpthread +Cflags: -I${includedir} -DGTEST_HAS_PTHREAD=1 -lpthread +``` + +Notice that the sysroot is not included in `libdir` and `includedir`! If you +try to run `pkg-config` with the correct +`PKG_CONFIG_LIBDIR=/home/MYUSER/sysroot/usr/lib64/pkgconfig` against this `.pc` +file, you will get + +``` +$ pkg-config --cflags gtest +-DGTEST_HAS_PTHREAD=1 -lpthread -I/usr/include +$ pkg-config --libs gtest +-L/usr/lib64 -lgtest -lpthread +``` + +which is obviously wrong and points to the `CBUILD` and not `CHOST` root. +In order to use this in a cross-compilation setting, we need to tell +pkg-config to inject the actual sysroot into `-I` and `-L` variables. Let us +now tell pkg-config about the actual sysroot + +``` +export PKG_CONFIG_DIR= +export PKG_CONFIG_SYSROOT_DIR=/home/MYUSER/sysroot +export PKG_CONFIG_LIBDIR=${PKG_CONFIG_SYSROOT_DIR}/usr/lib64/pkgconfig +``` + +and running `pkg-config` again we get + +``` +$ pkg-config --cflags gtest +-DGTEST_HAS_PTHREAD=1 -lpthread -I/home/MYUSER/sysroot/usr/include +$ pkg-config --libs gtest +-L/home/MYUSER/sysroot/usr/lib64 -lgtest -lpthread +``` + +which contains the correct sysroot now. For a more comprehensive guide to +also including `${CHOST}` in build system calls, see the excellent tutorial +by Diego Elio Pettenò: https://autotools.io/pkgconfig/cross-compiling.html From 2ed2211db99ab4f3e4d11078c78ad48a5b692f02 Mon Sep 17 00:00:00 2001 From: Joshua Cannon Date: Mon, 7 Oct 2019 13:56:47 -0500 Subject: [PATCH 014/541] Use FormatFileLocation for streaming file and line --- googlemock/src/gmock-spec-builders.cc | 3 ++- googletest/src/gtest-test-part.cc | 3 ++- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/googlemock/src/gmock-spec-builders.cc b/googlemock/src/gmock-spec-builders.cc index f9d3434560..317b8cb5d7 100644 --- a/googlemock/src/gmock-spec-builders.cc +++ b/googlemock/src/gmock-spec-builders.cc @@ -34,6 +34,7 @@ // EXPECT_CALL). #include "gmock/gmock-spec-builders.h" +#include "gtest/internal/gtest-port.h" #include #include // NOLINT @@ -70,7 +71,7 @@ GTEST_API_ void LogWithLocation(testing::internal::LogSeverity severity, const char* file, int line, const std::string& message) { ::std::ostringstream s; - s << file << ":" << line << ": " << message << ::std::endl; + s << internal::FormatFileLocation(file, line) << " " << message << ::std::endl; Log(severity, s.str(), 0); } diff --git a/googletest/src/gtest-test-part.cc b/googletest/src/gtest-test-part.cc index 178317a6bc..9c5bcc6baa 100644 --- a/googletest/src/gtest-test-part.cc +++ b/googletest/src/gtest-test-part.cc @@ -31,6 +31,7 @@ // The Google C++ Testing and Mocking Framework (Google Test) #include "gtest/gtest-test-part.h" +#include "gtest/internal/gtest-port.h" #include "src/gtest-internal-inl.h" namespace testing { @@ -46,7 +47,7 @@ std::string TestPartResult::ExtractSummary(const char* message) { // Prints a TestPartResult object. std::ostream& operator<<(std::ostream& os, const TestPartResult& result) { - return os << result.file_name() << ":" << result.line_number() << ": " + return os << internal::FormatFileLocation(result.file_name(), result.line_number()) << " " << (result.type() == TestPartResult::kSuccess ? "Success" : result.type() == TestPartResult::kSkip From 10c1d8c4faed0b90670a4971cf80a75d552d6f22 Mon Sep 17 00:00:00 2001 From: Joshua Cannon Date: Mon, 7 Oct 2019 14:30:10 -0500 Subject: [PATCH 015/541] Use the verbatim noexcept spec in MOCKED_METHOD --- .../include/gmock/gmock-function-mocker.h | 24 +++++++++++-------- googlemock/test/gmock-function-mocker_test.cc | 21 ++++++++++++++++ 2 files changed, 35 insertions(+), 10 deletions(-) diff --git a/googlemock/include/gmock/gmock-function-mocker.h b/googlemock/include/gmock/gmock-function-mocker.h index cc1535c806..7036959199 100644 --- a/googlemock/include/gmock/gmock-function-mocker.h +++ b/googlemock/include/gmock/gmock-function-mocker.h @@ -60,7 +60,8 @@ GMOCK_INTERNAL_MOCK_METHOD_IMPL( \ GMOCK_PP_NARG0 _Args, _MethodName, GMOCK_INTERNAL_HAS_CONST(_Spec), \ GMOCK_INTERNAL_HAS_OVERRIDE(_Spec), GMOCK_INTERNAL_HAS_FINAL(_Spec), \ - GMOCK_INTERNAL_HAS_NOEXCEPT(_Spec), GMOCK_INTERNAL_GET_CALLTYPE(_Spec), \ + GMOCK_INTERNAL_GET_NOEXCEPT_SPEC(_Spec), \ + GMOCK_INTERNAL_GET_CALLTYPE(_Spec), \ (GMOCK_INTERNAL_SIGNATURE(_Ret, _Args))) #define GMOCK_INTERNAL_MOCK_METHOD_ARG_5(...) \ @@ -100,15 +101,16 @@ GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_ASSERT_VALID_SPEC_ELEMENT, ~, _Spec) #define GMOCK_INTERNAL_MOCK_METHOD_IMPL(_N, _MethodName, _Constness, \ - _Override, _Final, _Noexcept, \ + _Override, _Final, _NoexceptSpec, \ _CallType, _Signature) \ typename ::testing::internal::Function::Result \ GMOCK_INTERNAL_EXPAND(_CallType) \ _MethodName(GMOCK_PP_REPEAT(GMOCK_INTERNAL_PARAMETER, _Signature, _N)) \ - GMOCK_PP_IF(_Constness, const, ) GMOCK_PP_IF(_Noexcept, noexcept, ) \ - GMOCK_PP_IF(_Override, override, ) \ - GMOCK_PP_IF(_Final, final, ) { \ + GMOCK_PP_IF(_Constness, const, ) \ + _NoexceptSpec \ + GMOCK_PP_IF(_Override, override, ) \ + GMOCK_PP_IF(_Final, final, ) { \ GMOCK_MOCKER_(_N, _Constness, _MethodName) \ .SetOwnerAndName(this, #_MethodName); \ return GMOCK_MOCKER_(_N, _Constness, _MethodName) \ @@ -125,7 +127,7 @@ const ::testing::internal::WithoutMatchers&, \ GMOCK_PP_IF(_Constness, const, )::testing::internal::Function< \ GMOCK_PP_REMOVE_PARENS(_Signature)>*) \ - const GMOCK_PP_IF(_Noexcept, noexcept, ) { \ + const _NoexceptSpec { \ return GMOCK_PP_CAT(::testing::internal::AdjustConstness_, \ GMOCK_PP_IF(_Constness, const, ))(this) \ ->gmock_##_MethodName(GMOCK_PP_REPEAT( \ @@ -147,9 +149,12 @@ #define GMOCK_INTERNAL_HAS_FINAL(_Tuple) \ GMOCK_PP_HAS_COMMA(GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_DETECT_FINAL, ~, _Tuple)) -#define GMOCK_INTERNAL_HAS_NOEXCEPT(_Tuple) \ - GMOCK_PP_HAS_COMMA( \ - GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_DETECT_NOEXCEPT, ~, _Tuple)) +#define GMOCK_INTERNAL_GET_NOEXCEPT_SPEC(_Tuple) \ + GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_NOEXCEPT_SPEC_IF_NOEXCEPT, ~, _Tuple) + +#define GMOCK_INTERNAL_NOEXCEPT_SPEC_IF_NOEXCEPT(_i, _, _elem) \ + GMOCK_PP_IF( \ + GMOCK_PP_HAS_COMMA(GMOCK_INTERNAL_DETECT_NOEXCEPT(_i, _, _elem)),_elem,) #define GMOCK_INTERNAL_GET_CALLTYPE(_Tuple) \ GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_GET_CALLTYPE_IMPL, ~, _Tuple) @@ -180,7 +185,6 @@ #define GMOCK_INTERNAL_DETECT_FINAL_I_final , -// TODO(iserna): Maybe noexcept should accept an argument here as well. #define GMOCK_INTERNAL_DETECT_NOEXCEPT(_i, _, _elem) \ GMOCK_PP_CAT(GMOCK_INTERNAL_DETECT_NOEXCEPT_I_, _elem) diff --git a/googlemock/test/gmock-function-mocker_test.cc b/googlemock/test/gmock-function-mocker_test.cc index fbc5d5b2bb..4b41437ee4 100644 --- a/googlemock/test/gmock-function-mocker_test.cc +++ b/googlemock/test/gmock-function-mocker_test.cc @@ -656,5 +656,26 @@ TEST(MockMethodMockFunctionTest, MockMethodSizeOverhead) { EXPECT_EQ(sizeof(MockMethodSizes0), sizeof(MockMethodSizes4)); } +struct MockMethodNoexceptSpecifier { + MOCK_METHOD(void, func1, (), (noexcept)); + MOCK_METHOD(void, func2, (), (noexcept(true))); + MOCK_METHOD(void, func3, (), (noexcept(false))); + MOCK_METHOD(void, func4, (), (noexcept(noexcept(1+1)))); + MOCK_METHOD(void, func5, (), (const, noexcept(noexcept(1+1)))); + MOCK_METHOD(void, func6, (), (noexcept(noexcept(1+1)), const)); + // Put commas in the noexcept expression + MOCK_METHOD(void, func7, (), (noexcept(noexcept(1,2,3)), const)); +}; + +TEST(MockMethodMockFunctionTest, NoexceptSpecifierPreserved) { + EXPECT_TRUE(noexcept(MockMethodNoexceptSpecifier{}.func1())); + EXPECT_TRUE(noexcept(MockMethodNoexceptSpecifier{}.func2())); + EXPECT_FALSE(noexcept(MockMethodNoexceptSpecifier{}.func3())); + EXPECT_EQ(noexcept(MockMethodNoexceptSpecifier{}.func4()), noexcept(1+1)); + EXPECT_EQ(noexcept(MockMethodNoexceptSpecifier{}.func5()), noexcept(1+1)); + EXPECT_EQ(noexcept(MockMethodNoexceptSpecifier{}.func6()), noexcept(1+1)); + EXPECT_EQ(noexcept(MockMethodNoexceptSpecifier{}.func7()), noexcept(1,2,3)); +} + } // namespace gmock_function_mocker_test } // namespace testing From 0eadff8a932d5d4fb9eeaf52434cd62ac0bc2b45 Mon Sep 17 00:00:00 2001 From: Joshua Cannon Date: Mon, 7 Oct 2019 14:37:39 -0500 Subject: [PATCH 016/541] Fix spacing --- googlemock/include/gmock/gmock-function-mocker.h | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/googlemock/include/gmock/gmock-function-mocker.h b/googlemock/include/gmock/gmock-function-mocker.h index 7036959199..8320f1479b 100644 --- a/googlemock/include/gmock/gmock-function-mocker.h +++ b/googlemock/include/gmock/gmock-function-mocker.h @@ -150,11 +150,11 @@ GMOCK_PP_HAS_COMMA(GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_DETECT_FINAL, ~, _Tuple)) #define GMOCK_INTERNAL_GET_NOEXCEPT_SPEC(_Tuple) \ - GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_NOEXCEPT_SPEC_IF_NOEXCEPT, ~, _Tuple) + GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_NOEXCEPT_SPEC_IF_NOEXCEPT, ~, _Tuple) #define GMOCK_INTERNAL_NOEXCEPT_SPEC_IF_NOEXCEPT(_i, _, _elem) \ - GMOCK_PP_IF( \ - GMOCK_PP_HAS_COMMA(GMOCK_INTERNAL_DETECT_NOEXCEPT(_i, _, _elem)),_elem,) + GMOCK_PP_IF( \ + GMOCK_PP_HAS_COMMA(GMOCK_INTERNAL_DETECT_NOEXCEPT(_i, _, _elem)), _elem, ) #define GMOCK_INTERNAL_GET_CALLTYPE(_Tuple) \ GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_GET_CALLTYPE_IMPL, ~, _Tuple) From 872b9ceb6045949a5e8ab22221301e65fea3fe29 Mon Sep 17 00:00:00 2001 From: Joshua Cannon Date: Mon, 7 Oct 2019 15:12:51 -0500 Subject: [PATCH 017/541] Avoid comma operator --- googlemock/test/gmock-function-mocker_test.cc | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/googlemock/test/gmock-function-mocker_test.cc b/googlemock/test/gmock-function-mocker_test.cc index 4b41437ee4..efd2499d42 100644 --- a/googlemock/test/gmock-function-mocker_test.cc +++ b/googlemock/test/gmock-function-mocker_test.cc @@ -664,7 +664,8 @@ struct MockMethodNoexceptSpecifier { MOCK_METHOD(void, func5, (), (const, noexcept(noexcept(1+1)))); MOCK_METHOD(void, func6, (), (noexcept(noexcept(1+1)), const)); // Put commas in the noexcept expression - MOCK_METHOD(void, func7, (), (noexcept(noexcept(1,2,3)), const)); + void other_func(int, int) noexcept; + MOCK_METHOD(void, func7, (), (noexcept(noexcept(other_func(1,2))), const)); }; TEST(MockMethodMockFunctionTest, NoexceptSpecifierPreserved) { @@ -674,7 +675,7 @@ TEST(MockMethodMockFunctionTest, NoexceptSpecifierPreserved) { EXPECT_EQ(noexcept(MockMethodNoexceptSpecifier{}.func4()), noexcept(1+1)); EXPECT_EQ(noexcept(MockMethodNoexceptSpecifier{}.func5()), noexcept(1+1)); EXPECT_EQ(noexcept(MockMethodNoexceptSpecifier{}.func6()), noexcept(1+1)); - EXPECT_EQ(noexcept(MockMethodNoexceptSpecifier{}.func7()), noexcept(1,2,3)); + EXPECT_EQ(noexcept(MockMethodNoexceptSpecifier{}.func7()), noexcept(MockMethodNoexceptSpecifier{}.other_func(1,2))); } } // namespace gmock_function_mocker_test From 7f8617a7c53275654531e3c75fe11bc9b1b7e1a1 Mon Sep 17 00:00:00 2001 From: Joshua Cannon Date: Mon, 7 Oct 2019 15:49:52 -0500 Subject: [PATCH 018/541] Switch to free function to avoid GCC bug --- googlemock/test/gmock-function-mocker_test.cc | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/googlemock/test/gmock-function-mocker_test.cc b/googlemock/test/gmock-function-mocker_test.cc index efd2499d42..94f01fe2b3 100644 --- a/googlemock/test/gmock-function-mocker_test.cc +++ b/googlemock/test/gmock-function-mocker_test.cc @@ -656,6 +656,7 @@ TEST(MockMethodMockFunctionTest, MockMethodSizeOverhead) { EXPECT_EQ(sizeof(MockMethodSizes0), sizeof(MockMethodSizes4)); } +void hasTwoParams(int, int); struct MockMethodNoexceptSpecifier { MOCK_METHOD(void, func1, (), (noexcept)); MOCK_METHOD(void, func2, (), (noexcept(true))); @@ -664,8 +665,7 @@ struct MockMethodNoexceptSpecifier { MOCK_METHOD(void, func5, (), (const, noexcept(noexcept(1+1)))); MOCK_METHOD(void, func6, (), (noexcept(noexcept(1+1)), const)); // Put commas in the noexcept expression - void other_func(int, int) noexcept; - MOCK_METHOD(void, func7, (), (noexcept(noexcept(other_func(1,2))), const)); + MOCK_METHOD(void, func7, (), (noexcept(noexcept(hasTwoParams(1,2))), const)); }; TEST(MockMethodMockFunctionTest, NoexceptSpecifierPreserved) { @@ -675,7 +675,7 @@ TEST(MockMethodMockFunctionTest, NoexceptSpecifierPreserved) { EXPECT_EQ(noexcept(MockMethodNoexceptSpecifier{}.func4()), noexcept(1+1)); EXPECT_EQ(noexcept(MockMethodNoexceptSpecifier{}.func5()), noexcept(1+1)); EXPECT_EQ(noexcept(MockMethodNoexceptSpecifier{}.func6()), noexcept(1+1)); - EXPECT_EQ(noexcept(MockMethodNoexceptSpecifier{}.func7()), noexcept(MockMethodNoexceptSpecifier{}.other_func(1,2))); + EXPECT_EQ(noexcept(MockMethodNoexceptSpecifier{}.func7()), noexcept(hasTwoParams(1,2))); } } // namespace gmock_function_mocker_test From 20255e6f40995f03c808a0589ea92c52a26552cd Mon Sep 17 00:00:00 2001 From: Joshua Cannon Date: Mon, 7 Oct 2019 16:27:11 -0500 Subject: [PATCH 019/541] Use declval in noexcept expression --- googlemock/test/gmock-function-mocker_test.cc | 15 ++++++++------- 1 file changed, 8 insertions(+), 7 deletions(-) diff --git a/googlemock/test/gmock-function-mocker_test.cc b/googlemock/test/gmock-function-mocker_test.cc index 94f01fe2b3..f493c72f4a 100644 --- a/googlemock/test/gmock-function-mocker_test.cc +++ b/googlemock/test/gmock-function-mocker_test.cc @@ -42,6 +42,7 @@ #include #include +#include #include "gmock/gmock.h" #include "gtest/gtest.h" @@ -669,13 +670,13 @@ struct MockMethodNoexceptSpecifier { }; TEST(MockMethodMockFunctionTest, NoexceptSpecifierPreserved) { - EXPECT_TRUE(noexcept(MockMethodNoexceptSpecifier{}.func1())); - EXPECT_TRUE(noexcept(MockMethodNoexceptSpecifier{}.func2())); - EXPECT_FALSE(noexcept(MockMethodNoexceptSpecifier{}.func3())); - EXPECT_EQ(noexcept(MockMethodNoexceptSpecifier{}.func4()), noexcept(1+1)); - EXPECT_EQ(noexcept(MockMethodNoexceptSpecifier{}.func5()), noexcept(1+1)); - EXPECT_EQ(noexcept(MockMethodNoexceptSpecifier{}.func6()), noexcept(1+1)); - EXPECT_EQ(noexcept(MockMethodNoexceptSpecifier{}.func7()), noexcept(hasTwoParams(1,2))); + EXPECT_TRUE(noexcept(std::declval().func1())); + EXPECT_TRUE(noexcept(std::declval().func2())); + EXPECT_FALSE(noexcept(std::declval().func3())); + EXPECT_EQ(noexcept(std::declval().func4()), noexcept(1+1)); + EXPECT_EQ(noexcept(std::declval().func5()), noexcept(1+1)); + EXPECT_EQ(noexcept(std::declval().func6()), noexcept(1+1)); + EXPECT_EQ(noexcept(std::declval().func7()), noexcept(hasTwoParams(1,2))); } } // namespace gmock_function_mocker_test From de69803b1e380d021a6698d5cf085857a5bc9fa5 Mon Sep 17 00:00:00 2001 From: Zebedee Mason Date: Wed, 9 Oct 2019 10:44:03 +0100 Subject: [PATCH 020/541] Mention Cornichon as a related open source project --- README.md | 3 +++ 1 file changed, 3 insertions(+) diff --git a/README.md b/README.md index 44e01e2b2b..5d39303e3e 100644 --- a/README.md +++ b/README.md @@ -102,6 +102,9 @@ runs tests from your binary in parallel to provide significant speed-up. is a VS Code extension allowing to view Google Tests in a tree view, and run/debug your tests. +[Cornichon](https://pypi.org/project/cornichon/) is a small Gherkin DSL parser +that generates stub code for Google Test. + ## Requirements Google Test is designed to have fairly minimal requirements to build and use From 20b5b8ecc7a81d23b4716e22a2b35fd53379c8c6 Mon Sep 17 00:00:00 2001 From: Abseil Team Date: Wed, 9 Oct 2019 18:14:17 -0400 Subject: [PATCH 021/541] Googletest export Add a compile time check to ensure that the parameters to TEST_P and INSTANTIATE_TEST_SUITE_P are not empty. Some compilers already fail in that case and, even where it works, it's likely to result in technically invalid code by virtue of creating reserved identifiers: https://en.cppreference.com/w/cpp/language/identifiers PiperOrigin-RevId: 273832263 --- googletest/include/gtest/gtest-param-test.h | 20 ++++++++++++++----- .../googletest-output-test-golden-lin.txt | 6 +++--- googletest/test/googletest-output-test_.cc | 2 +- googletest/test/gtest_unittest.cc | 2 +- 4 files changed, 20 insertions(+), 10 deletions(-) diff --git a/googletest/include/gtest/gtest-param-test.h b/googletest/include/gtest/gtest-param-test.h index e1135e998e..9989765d97 100644 --- a/googletest/include/gtest/gtest-param-test.h +++ b/googletest/include/gtest/gtest-param-test.h @@ -58,7 +58,9 @@ class FooTest : public ::testing::TestWithParam { // Then, use the TEST_P macro to define as many parameterized tests // for this fixture as you want. The _P suffix is for "parameterized" -// or "pattern", whichever you prefer to think. +// or "pattern", whichever you prefer to think. The arguments to the +// TEST_P macro are the test_suite_name and test_case (both which must be +// non-empty) that will form the test name. TEST_P(FooTest, DoesBlah) { // Inside a test, access the test parameter with the GetParam() method @@ -101,10 +103,10 @@ INSTANTIATE_TEST_SUITE_P(InstantiationName, // To distinguish different instances of the pattern, (yes, you // can instantiate it more than once) the first argument to the -// INSTANTIATE_TEST_SUITE_P macro is a prefix that will be added to the -// actual test suite name. Remember to pick unique prefixes for different -// instantiations. The tests from the instantiation above will have -// these names: +// INSTANTIATE_TEST_SUITE_P macro is a prefix (which must be non-empty) that +// will be added to the actual test suite name. Remember to pick unique prefixes +// for different instantiations. The tests from the instantiation above will +// have these names: // // * InstantiationName/FooTest.DoesBlah/0 for "meeny" // * InstantiationName/FooTest.DoesBlah/1 for "miny" @@ -412,6 +414,10 @@ internal::CartesianProductHolder Combine(const Generator&... g) { } #define TEST_P(test_suite_name, test_name) \ + static_assert(sizeof(GTEST_STRINGIFY_(test_suite_name)) > 1, \ + "test_suite_name must not be empty"); \ + static_assert(sizeof(GTEST_STRINGIFY_(test_name)) > 1, \ + "test_name must not be empty"); \ class GTEST_TEST_CLASS_NAME_(test_suite_name, test_name) \ : public test_suite_name { \ public: \ @@ -458,6 +464,10 @@ internal::CartesianProductHolder Combine(const Generator&... g) { #define GTEST_GET_SECOND_(first, second, ...) second #define INSTANTIATE_TEST_SUITE_P(prefix, test_suite_name, ...) \ + static_assert(sizeof(GTEST_STRINGIFY_(test_suite_name)) > 1, \ + "test_suite_name must not be empty"); \ + static_assert(sizeof(GTEST_STRINGIFY_(prefix)) > 1, \ + "prefix must not be empty"); \ static ::testing::internal::ParamGenerator \ gtest_##prefix##test_suite_name##_EvalGenerator_() { \ return GTEST_EXPAND_(GTEST_GET_FIRST_(__VA_ARGS__, DUMMY_PARAM_)); \ diff --git a/googletest/test/googletest-output-test-golden-lin.txt b/googletest/test/googletest-output-test-golden-lin.txt index 038de921ba..de777cff22 100644 --- a/googletest/test/googletest-output-test-golden-lin.txt +++ b/googletest/test/googletest-output-test-golden-lin.txt @@ -966,9 +966,9 @@ Expected equality of these values: Stack trace: (omitted) [ FAILED ] PrintingFailingParams/FailingParamTest.Fails/0, where GetParam() = 2 -[----------] 1 test from EmptyBasenameParamInst -[ RUN ] EmptyBasenameParamInst.Passes/0 -[ OK ] EmptyBasenameParamInst.Passes/0 +[----------] 1 test from All/EmptyBasenameParamInst +[ RUN ] All/EmptyBasenameParamInst.Passes/0 +[ OK ] All/EmptyBasenameParamInst.Passes/0 [----------] 2 tests from PrintingStrings/ParamTest [ RUN ] PrintingStrings/ParamTest.Success/a [ OK ] PrintingStrings/ParamTest.Success/a diff --git a/googletest/test/googletest-output-test_.cc b/googletest/test/googletest-output-test_.cc index 4f716d843b..8de2bd1247 100644 --- a/googletest/test/googletest-output-test_.cc +++ b/googletest/test/googletest-output-test_.cc @@ -102,7 +102,7 @@ class EmptyBasenameParamInst : public testing::TestWithParam {}; TEST_P(EmptyBasenameParamInst, Passes) { EXPECT_EQ(1, GetParam()); } -INSTANTIATE_TEST_SUITE_P(, EmptyBasenameParamInst, testing::Values(1)); +INSTANTIATE_TEST_SUITE_P(All, EmptyBasenameParamInst, testing::Values(1)); static const char kGoldenString[] = "\"Line\0 1\"\nLine 2"; diff --git a/googletest/test/gtest_unittest.cc b/googletest/test/gtest_unittest.cc index 39749b7b19..05ee1c7000 100644 --- a/googletest/test/gtest_unittest.cc +++ b/googletest/test/gtest_unittest.cc @@ -5343,7 +5343,7 @@ TEST_P(CodeLocationForTESTP, Verify) { VERIFY_CODE_LOCATION; } -INSTANTIATE_TEST_SUITE_P(, CodeLocationForTESTP, Values(0)); +INSTANTIATE_TEST_SUITE_P(All, CodeLocationForTESTP, Values(0)); template class CodeLocationForTYPEDTEST : public Test { From bc996e0817d85c9dcfbf031480d22743aba697b2 Mon Sep 17 00:00:00 2001 From: Joshua Cannon Date: Thu, 10 Oct 2019 08:52:27 -0500 Subject: [PATCH 022/541] Made noexcept condition more exciting --- googlemock/test/gmock-function-mocker_test.cc | 20 +++++++++++-------- 1 file changed, 12 insertions(+), 8 deletions(-) diff --git a/googlemock/test/gmock-function-mocker_test.cc b/googlemock/test/gmock-function-mocker_test.cc index f493c72f4a..4889d681f7 100644 --- a/googlemock/test/gmock-function-mocker_test.cc +++ b/googlemock/test/gmock-function-mocker_test.cc @@ -658,25 +658,29 @@ TEST(MockMethodMockFunctionTest, MockMethodSizeOverhead) { } void hasTwoParams(int, int); +void MaybeThrows(); +void DoesntThrow() noexcept; struct MockMethodNoexceptSpecifier { MOCK_METHOD(void, func1, (), (noexcept)); MOCK_METHOD(void, func2, (), (noexcept(true))); MOCK_METHOD(void, func3, (), (noexcept(false))); - MOCK_METHOD(void, func4, (), (noexcept(noexcept(1+1)))); - MOCK_METHOD(void, func5, (), (const, noexcept(noexcept(1+1)))); - MOCK_METHOD(void, func6, (), (noexcept(noexcept(1+1)), const)); + MOCK_METHOD(void, func4, (), (noexcept(noexcept(MaybeThrows())))); + MOCK_METHOD(void, func5, (), (noexcept(noexcept(DoesntThrow())))); + MOCK_METHOD(void, func6, (), (noexcept(noexcept(DoesntThrow())), const)); + MOCK_METHOD(void, func7, (), (const, noexcept(noexcept(DoesntThrow())))); // Put commas in the noexcept expression - MOCK_METHOD(void, func7, (), (noexcept(noexcept(hasTwoParams(1,2))), const)); + MOCK_METHOD(void, func8, (), (noexcept(noexcept(hasTwoParams(1,2))), const)); }; TEST(MockMethodMockFunctionTest, NoexceptSpecifierPreserved) { EXPECT_TRUE(noexcept(std::declval().func1())); EXPECT_TRUE(noexcept(std::declval().func2())); EXPECT_FALSE(noexcept(std::declval().func3())); - EXPECT_EQ(noexcept(std::declval().func4()), noexcept(1+1)); - EXPECT_EQ(noexcept(std::declval().func5()), noexcept(1+1)); - EXPECT_EQ(noexcept(std::declval().func6()), noexcept(1+1)); - EXPECT_EQ(noexcept(std::declval().func7()), noexcept(hasTwoParams(1,2))); + EXPECT_FALSE(noexcept(std::declval().func4())); + EXPECT_TRUE(noexcept(std::declval().func5())); + EXPECT_TRUE(noexcept(std::declval().func6())); + EXPECT_TRUE(noexcept(std::declval().func7())); + EXPECT_EQ(noexcept(std::declval().func8()), noexcept(hasTwoParams(1,2))); } } // namespace gmock_function_mocker_test From 31406d79090e15a6ab224669b4607953247da5d5 Mon Sep 17 00:00:00 2001 From: Chris Johnson Date: Thu, 10 Oct 2019 12:28:02 -0500 Subject: [PATCH 023/541] chore: update version Updated version from 1.8.1 to 1.10.0. --- library.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/library.json b/library.json index e46fcbdabc..b21135c2b4 100644 --- a/library.json +++ b/library.json @@ -8,7 +8,7 @@ "type": "git", "url": "https://github.com/google/googletest.git" }, - "version": "1.8.1", + "version": "1.10.0", "frameworks": "arduino", "platforms": [ "espressif32" From 9b9700247d4666abd6675a2bb047f973daf0ae90 Mon Sep 17 00:00:00 2001 From: Krystian Kuzniarek Date: Fri, 11 Oct 2019 06:37:46 +0200 Subject: [PATCH 024/541] clean-up broken paths for PlatformIO --- library.json | 12 ------------ platformio.ini | 2 +- 2 files changed, 1 insertion(+), 13 deletions(-) diff --git a/library.json b/library.json index e46fcbdabc..49b9d20bbe 100644 --- a/library.json +++ b/library.json @@ -22,30 +22,18 @@ ], "exclude": [ "ci", - "googlemock/build-aux", "googlemock/cmake", - "googlemock/make", - "googlemock/msvc", "googlemock/scripts", "googlemock/src/gmock-all.cc", "googlemock/src/gmock_main.cc", "googlemock/test", "googlemock/CMakeLists.txt", - "googlemock/Makefile.am", - "googlemock/configure.ac", "googletest/cmake", - "googletest/codegear", - "googletest/m4", - "googletest/make", - "googletest/msvc", "googletest/scripts", "googletest/src/gtest-all.cc", "googletest/src/gtest_main.cc", "googletest/test", - "googletest/xcode", "googletest/CMakeLists.txt", - "googletest/Makefile.am", - "googletest/configure.ac" ] }, "build": { diff --git a/platformio.ini b/platformio.ini index 3910026be6..94495e805b 100644 --- a/platformio.ini +++ b/platformio.ini @@ -19,7 +19,7 @@ platform = espressif32 board = esp32dev framework = arduino build_flags = -I./googletest/include -I./googletest -src_filter = +<*> -<.git/> - - - - - - + + +src_filter = +<*> -<.git/> - - - - + + upload_speed = 921600 [env:googlemock_esp32] From ed78e54f38ab10c775e39e5c4d500c6134a60d64 Mon Sep 17 00:00:00 2001 From: Abseil Team Date: Thu, 10 Oct 2019 13:12:54 -0400 Subject: [PATCH 025/541] Googletest export Fix the O(n^2) number of instantiations in ElemFromList. It is now O(n). It still has O(1) instantiation depth. PiperOrigin-RevId: 273980821 --- .../gmock/internal/gmock-internal-utils.h | 3 +- .../include/gtest/internal/gtest-internal.h | 44 ++++++++++--------- googletest/test/gtest_unittest.cc | 17 +++---- 3 files changed, 30 insertions(+), 34 deletions(-) diff --git a/googlemock/include/gmock/internal/gmock-internal-utils.h b/googlemock/include/gmock/internal/gmock-internal-utils.h index d012e710b5..584afa989d 100644 --- a/googlemock/include/gmock/internal/gmock-internal-utils.h +++ b/googlemock/include/gmock/internal/gmock-internal-utils.h @@ -490,8 +490,7 @@ struct Function { using Result = R; static constexpr size_t ArgumentCount = sizeof...(Args); template - using Arg = ElemFromList::type, - Args...>; + using Arg = ElemFromList; using ArgumentTuple = std::tuple; using ArgumentMatcherTuple = std::tuple...>; using MakeResultVoid = void(Args...); diff --git a/googletest/include/gtest/internal/gtest-internal.h b/googletest/include/gtest/internal/gtest-internal.h index 76ce13ae8f..ebfe3c9d25 100644 --- a/googletest/include/gtest/internal/gtest-internal.h +++ b/googletest/include/gtest/internal/gtest-internal.h @@ -1124,25 +1124,29 @@ struct MakeIndexSequence template <> struct MakeIndexSequence<0> : IndexSequence<> {}; -// FIXME: This implementation of ElemFromList is O(1) in instantiation depth, -// but it is O(N^2) in total instantiations. Not sure if this is the best -// tradeoff, as it will make it somewhat slow to compile. -template -struct ElemFromListImpl {}; - -template -struct ElemFromListImpl { - using type = T; +template +struct Ignore { + Ignore(...); // NOLINT }; -// Get the Nth element from T... -// It uses O(1) instantiation depth. -template -struct ElemFromList; +template +struct ElemFromListImpl; +template +struct ElemFromListImpl> { + // We make Ignore a template to solve a problem with MSVC. + // A non-template Ignore would work fine with `decltype(Ignore(I))...`, but + // MSVC doesn't understand how to deal with that pack expansion. + // Use `0 * I` to have a single instantiation of Ignore. + template + static R Apply(Ignore<0 * I>..., R (*)(), ...); +}; -template -struct ElemFromList, T...> - : ElemFromListImpl... {}; +template +struct ElemFromList { + using type = + decltype(ElemFromListImpl::type>::Apply( + static_cast(nullptr)...)); +}; template class FlatTuple; @@ -1152,9 +1156,7 @@ struct FlatTupleElemBase; template struct FlatTupleElemBase, I> { - using value_type = - typename ElemFromList::type, - T...>::type; + using value_type = typename ElemFromList::type; FlatTupleElemBase() = default; explicit FlatTupleElemBase(value_type t) : value(std::move(t)) {} value_type value; @@ -1192,12 +1194,12 @@ class FlatTuple explicit FlatTuple(T... t) : FlatTuple::FlatTupleBase(std::move(t)...) {} template - const typename ElemFromList::type& Get() const { + const typename ElemFromList::type& Get() const { return static_cast*>(this)->value; } template - typename ElemFromList::type& Get() { + typename ElemFromList::type& Get() { return static_cast*>(this)->value; } }; diff --git a/googletest/test/gtest_unittest.cc b/googletest/test/gtest_unittest.cc index 05ee1c7000..8312bd10e7 100644 --- a/googletest/test/gtest_unittest.cc +++ b/googletest/test/gtest_unittest.cc @@ -7353,20 +7353,15 @@ TEST(IndexSequence, MakeIndexSequence) { // ElemFromList TEST(ElemFromList, Basic) { using testing::internal::ElemFromList; - using Idx = testing::internal::MakeIndexSequence<3>::type; - EXPECT_TRUE(( - std::is_same::type>::value)); EXPECT_TRUE( - (std::is_same::type>::value)); + (std::is_same::type>::value)); EXPECT_TRUE( - (std::is_same::type>::value)); + (std::is_same::type>::value)); EXPECT_TRUE( - (std::is_same< - char, ElemFromList<7, testing::internal::MakeIndexSequence<12>::type, - int, int, int, int, int, int, int, char, int, int, - int, int>::type>::value)); + (std::is_same::type>::value)); + EXPECT_TRUE(( + std::is_same::type>::value)); } // FlatTuple From a4a5a7c768ceaf8fdc79ccf1d9e3bfb9f481efa6 Mon Sep 17 00:00:00 2001 From: Abseil Team Date: Thu, 10 Oct 2019 18:04:20 -0400 Subject: [PATCH 026/541] Googletest export - Fix a bug in dealing with paramaterized tests where the name is it self a macro expansion. - Add a compile time check to ensure that the parameters to TEST_P and INSTANTIATE_TEST_SUITE_P are not empty. The above fix causes some compilers to fail in that case and even where it works, it's likely to result in technically invalid code by virtue of creating reserved identifiers: https://en.cppreference.com/w/cpp/language/identifiers PiperOrigin-RevId: 274047249 --- googletest/include/gtest/gtest-param-test.h | 7 ++-- googletest/test/googletest-param-test-test.cc | 33 ++++++++++++++++++- 2 files changed, 36 insertions(+), 4 deletions(-) diff --git a/googletest/include/gtest/gtest-param-test.h b/googletest/include/gtest/gtest-param-test.h index 9989765d97..f61e3c5d88 100644 --- a/googletest/include/gtest/gtest-param-test.h +++ b/googletest/include/gtest/gtest-param-test.h @@ -429,7 +429,7 @@ internal::CartesianProductHolder Combine(const Generator&... g) { ::testing::UnitTest::GetInstance() \ ->parameterized_test_registry() \ .GetTestSuitePatternHolder( \ - #test_suite_name, \ + GTEST_STRINGIFY_(test_suite_name), \ ::testing::internal::CodeLocation(__FILE__, __LINE__)) \ ->AddTestPattern( \ GTEST_STRINGIFY_(test_suite_name), GTEST_STRINGIFY_(test_name), \ @@ -493,10 +493,11 @@ internal::CartesianProductHolder Combine(const Generator&... g) { ::testing::UnitTest::GetInstance() \ ->parameterized_test_registry() \ .GetTestSuitePatternHolder( \ - #test_suite_name, \ + GTEST_STRINGIFY_(test_suite_name), \ ::testing::internal::CodeLocation(__FILE__, __LINE__)) \ ->AddTestSuiteInstantiation( \ - #prefix, >est_##prefix##test_suite_name##_EvalGenerator_, \ + GTEST_STRINGIFY_(prefix), \ + >est_##prefix##test_suite_name##_EvalGenerator_, \ >est_##prefix##test_suite_name##_EvalGenerateName_, \ __FILE__, __LINE__) diff --git a/googletest/test/googletest-param-test-test.cc b/googletest/test/googletest-param-test-test.cc index 6c187dfff0..2740aaab23 100644 --- a/googletest/test/googletest-param-test-test.cc +++ b/googletest/test/googletest-param-test-test.cc @@ -37,6 +37,7 @@ # include # include # include +# include # include # include # include @@ -802,7 +803,7 @@ TEST_P(PREFIX_WITH_MACRO(NamingTest), PREFIX_WITH_FOO(SomeTestName)) { ::testing::UnitTest::GetInstance()->current_test_info(); EXPECT_STREQ("FortyTwo/MacroNamingTest", test_info->test_suite_name()); - EXPECT_STREQ("FooSomeTestName", test_info->name()); + EXPECT_STREQ("FooSomeTestName/0", test_info->name()); } INSTANTIATE_TEST_SUITE_P(FortyTwo, MacroNamingTest, Values(42)); @@ -819,6 +820,36 @@ TEST_F(PREFIX_WITH_MACRO(NamingTestNonParametrized), EXPECT_STREQ("FooSomeTestName", test_info->name()); } +TEST(MacroNameing, LookupNames) { + std::set know_suite_names, know_test_names; + + auto ins = testing::UnitTest::GetInstance(); + int ts = 0; + while (const testing::TestSuite* suite = ins->GetTestSuite(ts++)) { + know_suite_names.insert(suite->name()); + + int ti = 0; + while (const testing::TestInfo* info = suite->GetTestInfo(ti++)) { + know_test_names.insert(std::string(suite->name()) + "." + info->name()); + } + } + + // Check that the expected form of the test suit name actualy exists. + EXPECT_NE( // + know_suite_names.find("FortyTwo/MacroNamingTest"), + know_suite_names.end()); + EXPECT_NE( + know_suite_names.find("MacroNamingTestNonParametrized"), + know_suite_names.end()); + // Check that the expected form of the test name actualy exists. + EXPECT_NE( // + know_test_names.find("FortyTwo/MacroNamingTest.FooSomeTestName/0"), + know_test_names.end()); + EXPECT_NE( + know_test_names.find("MacroNamingTestNonParametrized.FooSomeTestName"), + know_test_names.end()); +} + // Tests that user supplied custom parameter names are working correctly. // Runs the test with a builtin helper method which uses PrintToString, // as well as a custom function and custom functor to ensure all possible From a3ca5b9e0bf9abc3bc639684966085c4d3182578 Mon Sep 17 00:00:00 2001 From: misterg Date: Fri, 11 Oct 2019 07:27:05 -0400 Subject: [PATCH 027/541] Googletest export Updated release 1.10.0 link to point to https://github.com/google/googletest/releases/tag/release-1.10.0 ( that has the high level release info) PiperOrigin-RevId: 274147093 --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 5d39303e3e..8be9786c4b 100644 --- a/README.md +++ b/README.md @@ -9,8 +9,8 @@ #### Release 1.10.x -[Release 1.10.x](https://github.com/google/googletest/releases/tag/v1.10.x) is -now available. +[Release 1.10.x](https://github.com/google/googletest/releases/tag/release-1.10.0) +is now available. #### Coming Soon From c081ceebfb6f67ead723876fd54d502d09fa1dc7 Mon Sep 17 00:00:00 2001 From: Joshua Cannon Date: Fri, 11 Oct 2019 09:28:25 -0500 Subject: [PATCH 028/541] Workaround MSVC VA_ARGS weirdness --- googlemock/include/gmock/internal/gmock-pp.h | 85 +++++--------------- 1 file changed, 19 insertions(+), 66 deletions(-) diff --git a/googlemock/include/gmock/internal/gmock-pp.h b/googlemock/include/gmock/internal/gmock-pp.h index 1ab80e1cdb..e16bc5c688 100644 --- a/googlemock/include/gmock/internal/gmock-pp.h +++ b/googlemock/include/gmock/internal/gmock-pp.h @@ -1,19 +1,6 @@ #ifndef THIRD_PARTY_GOOGLETEST_GOOGLEMOCK_INCLUDE_GMOCK_PP_H_ #define THIRD_PARTY_GOOGLETEST_GOOGLEMOCK_INCLUDE_GMOCK_PP_H_ -#undef GMOCK_PP_INTERNAL_USE_MSVC -#if defined(__clang__) -#define GMOCK_PP_INTERNAL_USE_MSVC 0 -#elif defined(_MSC_VER) -// TODO(iserna): Also verify tradional versus comformant preprocessor. -static_assert( - _MSC_VER >= 1900, - "MSVC version not supported. There is support for MSVC 14.0 and above."); -#define GMOCK_PP_INTERNAL_USE_MSVC 1 -#else -#define GMOCK_PP_INTERNAL_USE_MSVC 0 -#endif - // Expands and concatenates the arguments. Constructed macros reevaluate. #define GMOCK_PP_CAT(_1, _2) GMOCK_PP_INTERNAL_CAT(_1, _2) @@ -29,10 +16,6 @@ static_assert( // Returns the only argument. #define GMOCK_PP_IDENTITY(_1) _1 -// MSVC preprocessor collapses __VA_ARGS__ in a single argument, we use a -// CAT-like directive to force correct evaluation. Each macro has its own. -#if GMOCK_PP_INTERNAL_USE_MSVC - // Evaluates to the number of arguments after expansion. // // #define PAIR x, y @@ -43,45 +26,32 @@ static_assert( // GMOCK_PP_NARG(PAIR) => 2 // // Requires: the number of arguments after expansion is at most 15. -#define GMOCK_PP_NARG(...) \ - GMOCK_PP_INTERNAL_NARG_CAT( \ - GMOCK_PP_INTERNAL_INTERNAL_16TH(__VA_ARGS__, 15, 14, 13, 12, 11, 10, 9, \ - 8, 7, 6, 5, 4, 3, 2, 1), ) +#define GMOCK_PP_NARG(...) \ + GMOCK_PP_INTERNAL_EXPAND_WITH( \ + GMOCK_PP_INTERNAL_INTERNAL_16TH, \ + (__VA_ARGS__, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1)) // Returns 1 if the expansion of arguments has an unprotected comma. Otherwise // returns 0. Requires no more than 15 unprotected commas. -#define GMOCK_PP_HAS_COMMA(...) \ - GMOCK_PP_INTERNAL_HAS_COMMA_CAT( \ - GMOCK_PP_INTERNAL_INTERNAL_16TH(__VA_ARGS__, 1, 1, 1, 1, 1, 1, 1, 1, 1, \ - 1, 1, 1, 1, 1, 0), ) +#define GMOCK_PP_HAS_COMMA(...) \ + GMOCK_PP_INTERNAL_EXPAND_WITH( \ + GMOCK_PP_INTERNAL_INTERNAL_16TH, \ + (__VA_ARGS__, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0)) + // Returns the first argument. #define GMOCK_PP_HEAD(...) \ - GMOCK_PP_INTERNAL_HEAD_CAT(GMOCK_PP_INTERNAL_HEAD(__VA_ARGS__), ) + GMOCK_PP_INTERNAL_EXPAND_WITH(GMOCK_PP_INTERNAL_HEAD, (__VA_ARGS__)) // Returns the tail. A variadic list of all arguments minus the first. Requires // at least one argument. #define GMOCK_PP_TAIL(...) \ - GMOCK_PP_INTERNAL_TAIL_CAT(GMOCK_PP_INTERNAL_TAIL(__VA_ARGS__), ) + GMOCK_PP_INTERNAL_EXPAND_WITH(GMOCK_PP_INTERNAL_TAIL, (__VA_ARGS__)) // Calls CAT(_Macro, NARG(__VA_ARGS__))(__VA_ARGS__) -#define GMOCK_PP_VARIADIC_CALL(_Macro, ...) \ - GMOCK_PP_INTERNAL_VARIADIC_CALL_CAT( \ - GMOCK_PP_CAT(_Macro, GMOCK_PP_NARG(__VA_ARGS__))(__VA_ARGS__), ) - -#else // GMOCK_PP_INTERNAL_USE_MSVC - -#define GMOCK_PP_NARG(...) \ - GMOCK_PP_INTERNAL_INTERNAL_16TH(__VA_ARGS__, 15, 14, 13, 12, 11, 10, 9, 8, \ - 7, 6, 5, 4, 3, 2, 1) -#define GMOCK_PP_HAS_COMMA(...) \ - GMOCK_PP_INTERNAL_INTERNAL_16TH(__VA_ARGS__, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, \ - 1, 1, 1, 1, 0) -#define GMOCK_PP_HEAD(...) GMOCK_PP_INTERNAL_HEAD(__VA_ARGS__) -#define GMOCK_PP_TAIL(...) GMOCK_PP_INTERNAL_TAIL(__VA_ARGS__) -#define GMOCK_PP_VARIADIC_CALL(_Macro, ...) \ - GMOCK_PP_CAT(_Macro, GMOCK_PP_NARG(__VA_ARGS__))(__VA_ARGS__) - -#endif // GMOCK_PP_INTERNAL_USE_MSVC +#define GMOCK_PP_VARIADIC_CALL(_Macro, ...) \ + GMOCK_PP_INTERNAL_EXPAND_WITH( \ + GMOCK_PP_CAT(_Macro, GMOCK_PP_NARG(__VA_ARGS__)), \ + (__VA_ARGS__)) // If the arguments after expansion have no tokens, evaluates to `1`. Otherwise // evaluates to `0`. @@ -192,28 +162,11 @@ static_assert( #define GMOCK_PP_INTERNAL_IF_0(_Then, _Else) _Else #define GMOCK_PP_INTERNAL_HEAD(_1, ...) _1 #define GMOCK_PP_INTERNAL_TAIL(_1, ...) __VA_ARGS__ - -#if GMOCK_PP_INTERNAL_USE_MSVC -#define GMOCK_PP_INTERNAL_NARG_CAT(_1, _2) GMOCK_PP_INTERNAL_NARG_CAT_I(_1, _2) -#define GMOCK_PP_INTERNAL_HEAD_CAT(_1, _2) GMOCK_PP_INTERNAL_HEAD_CAT_I(_1, _2) -#define GMOCK_PP_INTERNAL_HAS_COMMA_CAT(_1, _2) \ - GMOCK_PP_INTERNAL_HAS_COMMA_CAT_I(_1, _2) -#define GMOCK_PP_INTERNAL_TAIL_CAT(_1, _2) GMOCK_PP_INTERNAL_TAIL_CAT_I(_1, _2) -#define GMOCK_PP_INTERNAL_VARIADIC_CALL_CAT(_1, _2) \ - GMOCK_PP_INTERNAL_VARIADIC_CALL_CAT_I(_1, _2) -#define GMOCK_PP_INTERNAL_NARG_CAT_I(_1, _2) _1##_2 -#define GMOCK_PP_INTERNAL_HEAD_CAT_I(_1, _2) _1##_2 -#define GMOCK_PP_INTERNAL_HAS_COMMA_CAT_I(_1, _2) _1##_2 -#define GMOCK_PP_INTERNAL_TAIL_CAT_I(_1, _2) _1##_2 -#define GMOCK_PP_INTERNAL_VARIADIC_CALL_CAT_I(_1, _2) _1##_2 +// Workaround MSVC behavior of treating __VA_ARGS__ with commas as one arg +// _Args must be wrapped in parenthesis +#define GMOCK_PP_INTERNAL_EXPAND_WITH(_Macro, _Args) _Macro _Args #define GMOCK_PP_INTERNAL_ALTERNATE_HEAD(...) \ - GMOCK_PP_INTERNAL_ALTERNATE_HEAD_CAT(GMOCK_PP_HEAD(__VA_ARGS__), ) -#define GMOCK_PP_INTERNAL_ALTERNATE_HEAD_CAT(_1, _2) \ - GMOCK_PP_INTERNAL_ALTERNATE_HEAD_CAT_I(_1, _2) -#define GMOCK_PP_INTERNAL_ALTERNATE_HEAD_CAT_I(_1, _2) _1##_2 -#else // GMOCK_PP_INTERNAL_USE_MSVC -#define GMOCK_PP_INTERNAL_ALTERNATE_HEAD(...) GMOCK_PP_HEAD(__VA_ARGS__) -#endif // GMOCK_PP_INTERNAL_USE_MSVC + GMOCK_PP_INTERNAL_EXPAND_WITH(GMOCK_PP_HEAD, (__VA_ARGS__)) #define GMOCK_PP_INTERNAL_IBP_IS_VARIADIC_C(...) 1 _ #define GMOCK_PP_INTERNAL_IBP_IS_VARIADIC_R_1 1, From c1e8e71aab60158b3653e756f6b6e34180273eda Mon Sep 17 00:00:00 2001 From: Joshua Cannon Date: Fri, 11 Oct 2019 09:34:01 -0500 Subject: [PATCH 029/541] Add a compile test --- googlemock/test/gmock-function-mocker_test.cc | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/googlemock/test/gmock-function-mocker_test.cc b/googlemock/test/gmock-function-mocker_test.cc index fbc5d5b2bb..e99ede5315 100644 --- a/googlemock/test/gmock-function-mocker_test.cc +++ b/googlemock/test/gmock-function-mocker_test.cc @@ -656,5 +656,12 @@ TEST(MockMethodMockFunctionTest, MockMethodSizeOverhead) { EXPECT_EQ(sizeof(MockMethodSizes0), sizeof(MockMethodSizes4)); } +// TODO(thejcannon): This just tests that this will compile, as gmock repeating the +// noexcept specifier isn't supported yet +struct MockUsesNoexceptWithParenthesis +{ + MOCK_METHOD(void, func, (), (noexcept(false))); +}; + } // namespace gmock_function_mocker_test } // namespace testing From d935e8e3edaf0987ee8a0a664593e17771587393 Mon Sep 17 00:00:00 2001 From: Joshua Cannon Date: Fri, 11 Oct 2019 10:41:47 -0500 Subject: [PATCH 030/541] Fix preprocessor tests --- googlemock/include/gmock/internal/gmock-pp.h | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/googlemock/include/gmock/internal/gmock-pp.h b/googlemock/include/gmock/internal/gmock-pp.h index e16bc5c688..2ebeaddca0 100644 --- a/googlemock/include/gmock/internal/gmock-pp.h +++ b/googlemock/include/gmock/internal/gmock-pp.h @@ -110,7 +110,7 @@ // Expands to 1 if the first argument starts with something in parentheses, // otherwise to 0. #define GMOCK_PP_IS_BEGIN_PARENS(...) \ - GMOCK_PP_INTERNAL_ALTERNATE_HEAD( \ + GMOCK_PP_HEAD( \ GMOCK_PP_CAT(GMOCK_PP_INTERNAL_IBP_IS_VARIADIC_R_, \ GMOCK_PP_INTERNAL_IBP_IS_VARIADIC_C __VA_ARGS__)) @@ -165,8 +165,6 @@ // Workaround MSVC behavior of treating __VA_ARGS__ with commas as one arg // _Args must be wrapped in parenthesis #define GMOCK_PP_INTERNAL_EXPAND_WITH(_Macro, _Args) _Macro _Args -#define GMOCK_PP_INTERNAL_ALTERNATE_HEAD(...) \ - GMOCK_PP_INTERNAL_EXPAND_WITH(GMOCK_PP_HEAD, (__VA_ARGS__)) #define GMOCK_PP_INTERNAL_IBP_IS_VARIADIC_C(...) 1 _ #define GMOCK_PP_INTERNAL_IBP_IS_VARIADIC_R_1 1, From fe112cfee7e772fc94eb7c64abd86b0b9e937e70 Mon Sep 17 00:00:00 2001 From: Joshua Cannon Date: Fri, 11 Oct 2019 10:58:59 -0500 Subject: [PATCH 031/541] Replace compile-test with preprocessor test --- googlemock/test/gmock-function-mocker_test.cc | 7 ------- googlemock/test/gmock-pp_test.cc | 11 +++++++++++ 2 files changed, 11 insertions(+), 7 deletions(-) diff --git a/googlemock/test/gmock-function-mocker_test.cc b/googlemock/test/gmock-function-mocker_test.cc index e99ede5315..fbc5d5b2bb 100644 --- a/googlemock/test/gmock-function-mocker_test.cc +++ b/googlemock/test/gmock-function-mocker_test.cc @@ -656,12 +656,5 @@ TEST(MockMethodMockFunctionTest, MockMethodSizeOverhead) { EXPECT_EQ(sizeof(MockMethodSizes0), sizeof(MockMethodSizes4)); } -// TODO(thejcannon): This just tests that this will compile, as gmock repeating the -// noexcept specifier isn't supported yet -struct MockUsesNoexceptWithParenthesis -{ - MOCK_METHOD(void, func, (), (noexcept(false))); -}; - } // namespace gmock_function_mocker_test } // namespace testing diff --git a/googlemock/test/gmock-pp_test.cc b/googlemock/test/gmock-pp_test.cc index 7387d39899..aa3f2dd435 100644 --- a/googlemock/test/gmock-pp_test.cc +++ b/googlemock/test/gmock-pp_test.cc @@ -1,5 +1,10 @@ #include "gmock/internal/gmock-pp.h" +// Used to test MSVC treating __VA_ARGS__ with a comma in it as one value +#define GMOCK_TEST_REPLACE_comma_WITH_COMMA_I_comma , +#define GMOCK_TEST_REPLACE_comma_WITH_COMMA(x) \ + GMOCK_PP_CAT(GMOCK_TEST_REPLACE_comma_WITH_COMMA_I_, x) + // Static assertions. namespace testing { namespace internal { @@ -17,6 +22,12 @@ static_assert(GMOCK_PP_NARG(x, y, z, w) == 4, ""); static_assert(!GMOCK_PP_HAS_COMMA(), ""); static_assert(GMOCK_PP_HAS_COMMA(b, ), ""); static_assert(!GMOCK_PP_HAS_COMMA((, )), ""); +static_assert( + GMOCK_PP_HAS_COMMA(GMOCK_TEST_REPLACE_comma_WITH_COMMA(comma)), ""); +static_assert( + GMOCK_PP_HAS_COMMA(GMOCK_TEST_REPLACE_comma_WITH_COMMA(comma(unrelated))), + ""); +static_assert(GMOCK_PP_HAS_COMMA((, )), ""); static_assert(!GMOCK_PP_IS_EMPTY(, ), ""); static_assert(!GMOCK_PP_IS_EMPTY(a), ""); static_assert(!GMOCK_PP_IS_EMPTY(()), ""); From 5fe523361243b4e2d698df45e10076d89e6a992f Mon Sep 17 00:00:00 2001 From: Joshua Cannon Date: Fri, 11 Oct 2019 11:28:00 -0500 Subject: [PATCH 032/541] Removing extraneous test --- googlemock/test/gmock-pp_test.cc | 1 - 1 file changed, 1 deletion(-) diff --git a/googlemock/test/gmock-pp_test.cc b/googlemock/test/gmock-pp_test.cc index aa3f2dd435..96b7b26c8b 100644 --- a/googlemock/test/gmock-pp_test.cc +++ b/googlemock/test/gmock-pp_test.cc @@ -27,7 +27,6 @@ static_assert( static_assert( GMOCK_PP_HAS_COMMA(GMOCK_TEST_REPLACE_comma_WITH_COMMA(comma(unrelated))), ""); -static_assert(GMOCK_PP_HAS_COMMA((, )), ""); static_assert(!GMOCK_PP_IS_EMPTY(, ), ""); static_assert(!GMOCK_PP_IS_EMPTY(a), ""); static_assert(!GMOCK_PP_IS_EMPTY(()), ""); From 40a6b9662199890b20ccbac3b964ce04713d8ede Mon Sep 17 00:00:00 2001 From: Chris Johnson Date: Wed, 28 Aug 2019 09:39:35 -0500 Subject: [PATCH 033/541] feat: Add support for ESP8266 platform Added support for ESP8266 Arduino platform. Refactored Arduino defines to use the GTEST_OS_* model. --- googlemock/src/gmock_main.cc | 2 +- googletest/include/gtest/internal/gtest-port-arch.h | 4 ++++ googletest/src/gtest-filepath.cc | 2 +- googletest/src/gtest.cc | 2 ++ googletest/src/gtest_main.cc | 2 +- 5 files changed, 9 insertions(+), 3 deletions(-) diff --git a/googlemock/src/gmock_main.cc b/googlemock/src/gmock_main.cc index 98611b9353..4d4f48b7b6 100644 --- a/googlemock/src/gmock_main.cc +++ b/googlemock/src/gmock_main.cc @@ -32,7 +32,7 @@ #include "gmock/gmock.h" #include "gtest/gtest.h" -#ifdef ARDUINO +#if defined GTEST_OS_ESP8266 || defined GTEST_OS_ESP32 void setup() { // Since Google Mock depends on Google Test, InitGoogleMock() is // also responsible for initializing Google Test. Therefore there's diff --git a/googletest/include/gtest/internal/gtest-port-arch.h b/googletest/include/gtest/internal/gtest-port-arch.h index cece93dba1..e2acad357b 100644 --- a/googletest/include/gtest/internal/gtest-port-arch.h +++ b/googletest/include/gtest/internal/gtest-port-arch.h @@ -102,6 +102,10 @@ # define GTEST_OS_QNX 1 #elif defined(__HAIKU__) #define GTEST_OS_HAIKU 1 +#elif defined ESP8266 +# define GTEST_OS_ESP8266 1 +#elif defined ESP32 +# define GTEST_OS_ESP32 1 #endif // __CYGWIN__ #endif // GTEST_INCLUDE_GTEST_INTERNAL_GTEST_PORT_ARCH_H_ diff --git a/googletest/src/gtest-filepath.cc b/googletest/src/gtest-filepath.cc index bd7b99ff03..eb1024e4a6 100644 --- a/googletest/src/gtest-filepath.cc +++ b/googletest/src/gtest-filepath.cc @@ -93,7 +93,7 @@ static bool IsPathSeparator(char c) { // Returns the current working directory, or "" if unsuccessful. FilePath FilePath::GetCurrentDir() { #if GTEST_OS_WINDOWS_MOBILE || GTEST_OS_WINDOWS_PHONE || \ - GTEST_OS_WINDOWS_RT || ARDUINO || defined(ESP_PLATFORM) + GTEST_OS_WINDOWS_RT || GTEST_OS_ESP8266 || GTEST_OS_ESP32 // These platforms do not have a current directory, so we just return // something reasonable. return FilePath(kCurrentDirectoryString); diff --git a/googletest/src/gtest.cc b/googletest/src/gtest.cc index a5b4e5ac78..a11ce18429 100644 --- a/googletest/src/gtest.cc +++ b/googletest/src/gtest.cc @@ -4508,6 +4508,7 @@ class ScopedPrematureExitFile { } ~ScopedPrematureExitFile() { + #if !defined GTEST_OS_ESP8266 if (!premature_exit_filepath_.empty()) { int retval = remove(premature_exit_filepath_.c_str()); if (retval) { @@ -4516,6 +4517,7 @@ class ScopedPrematureExitFile { << retval; } } + #endif } private: diff --git a/googletest/src/gtest_main.cc b/googletest/src/gtest_main.cc index f6e1dd96fb..361cb73925 100644 --- a/googletest/src/gtest_main.cc +++ b/googletest/src/gtest_main.cc @@ -30,7 +30,7 @@ #include #include "gtest/gtest.h" -#ifdef ARDUINO +#if defined GTEST_OS_ESP8266 || defined GTEST_OS_ESP32 void setup() { testing::InitGoogleTest(); } From c2206b05aa0f2fbdf5b353b32cd565b0e89d3fa6 Mon Sep 17 00:00:00 2001 From: Chris Johnson Date: Thu, 29 Aug 2019 12:34:26 -0500 Subject: [PATCH 034/541] Add ESP8266 configs to PlatformIO build Added various conditional compliations for ESP8266 to stub out missing functionality. --- googlemock/src/gmock_main.cc | 9 ++++++++- googletest/include/gtest/internal/gtest-port.h | 16 ++++++++++++++++ googletest/src/gtest-filepath.cc | 5 ++++- googletest/src/gtest_main.cc | 9 ++++++++- platformio.ini | 18 +++++++++++++++++- 5 files changed, 53 insertions(+), 4 deletions(-) diff --git a/googlemock/src/gmock_main.cc b/googlemock/src/gmock_main.cc index 4d4f48b7b6..16f97b0ae8 100644 --- a/googlemock/src/gmock_main.cc +++ b/googlemock/src/gmock_main.cc @@ -32,7 +32,10 @@ #include "gmock/gmock.h" #include "gtest/gtest.h" -#if defined GTEST_OS_ESP8266 || defined GTEST_OS_ESP32 +#if GTEST_OS_ESP8266 || GTEST_OS_ESP32 +# if GTEST_OS_ESP8266 +extern "C" { +# endif void setup() { // Since Google Mock depends on Google Test, InitGoogleMock() is // also responsible for initializing Google Test. Therefore there's @@ -40,6 +43,10 @@ void setup() { testing::InitGoogleMock(); } void loop() { RUN_ALL_TESTS(); } +# if GTEST_OS_ESP8266 +} +# endif + #else // MS C++ compiler/linker has a bug on Windows (not on Windows CE), which diff --git a/googletest/include/gtest/internal/gtest-port.h b/googletest/include/gtest/internal/gtest-port.h index f6433c58aa..f24afe7e4b 100644 --- a/googletest/include/gtest/internal/gtest-port.h +++ b/googletest/include/gtest/internal/gtest-port.h @@ -1984,6 +1984,22 @@ inline bool IsDir(const StatStruct& st) { } # endif // GTEST_OS_WINDOWS_MOBILE +#elif GTEST_OS_ESP8266 +typedef struct stat StatStruct; + +inline int FileNo(FILE* file) { return fileno(file); } +inline int IsATTY(int fd) { return isatty(fd); } +inline int Stat(const char* path, StatStruct* buf) { + // stat function not implemented on ESP8266 + return 0; + } +inline int StrCaseCmp(const char* s1, const char* s2) { + return strcasecmp(s1, s2); +} +inline char* StrDup(const char* src) { return strdup(src); } +inline int RmDir(const char* dir) { return rmdir(dir); } +inline bool IsDir(const StatStruct& st) { return S_ISDIR(st.st_mode); } + #else typedef struct stat StatStruct; diff --git a/googletest/src/gtest-filepath.cc b/googletest/src/gtest-filepath.cc index eb1024e4a6..7e03e817ba 100644 --- a/googletest/src/gtest-filepath.cc +++ b/googletest/src/gtest-filepath.cc @@ -236,7 +236,7 @@ bool FilePath::DirectoryExists() const { result = true; } #else - posix::StatStruct file_stat; + posix::StatStruct file_stat = {}; result = posix::Stat(path.c_str(), &file_stat) == 0 && posix::IsDir(file_stat); #endif // GTEST_OS_WINDOWS_MOBILE @@ -323,6 +323,9 @@ bool FilePath::CreateFolder() const { delete [] unicode; #elif GTEST_OS_WINDOWS int result = _mkdir(pathname_.c_str()); +#elif GTEST_OS_ESP8266 + // do nothing + int result = 0; #else int result = mkdir(pathname_.c_str(), 0777); #endif // GTEST_OS_WINDOWS_MOBILE diff --git a/googletest/src/gtest_main.cc b/googletest/src/gtest_main.cc index 361cb73925..37479252b3 100644 --- a/googletest/src/gtest_main.cc +++ b/googletest/src/gtest_main.cc @@ -30,13 +30,20 @@ #include #include "gtest/gtest.h" -#if defined GTEST_OS_ESP8266 || defined GTEST_OS_ESP32 +#if GTEST_OS_ESP8266 || GTEST_OS_ESP32 +# if GTEST_OS_ESP8266 +extern "C" { +# endif void setup() { testing::InitGoogleTest(); } void loop() { RUN_ALL_TESTS(); } +# if GTEST_OS_ESP8266 +} +# endif + #else GTEST_API_ int main(int argc, char **argv) { diff --git a/platformio.ini b/platformio.ini index 3910026be6..31c7ec1649 100644 --- a/platformio.ini +++ b/platformio.ini @@ -27,5 +27,21 @@ platform = espressif32 board = esp32dev framework = arduino build_flags = -I./googlemock/include -I./googletest/include -I./googletest -I./googlemock -src_filter = +<*> -<.git/> - - - + + + +src_filter = +<*> -<.git/> - - - + + + upload_speed = 921600 + +[env:googletest_esp8266] +platform = espressif8266 +board = huzzah +framework = arduino +build_flags = -I./googletest/include -I./googletest +src_filter = +<*> -<.git/> - - - - - - + + +upload_speed = 921600 + +[env:googlemock_esp8266] +platform = espressif8266 +board = huzzah +framework = arduino +build_flags = -I./googlemock/include -I./googletest/include -I./googletest -I./googlemock +src_filter = +<*> -<.git/> - - - + + + +upload_speed = 921600 \ No newline at end of file From f8961b99f4c3045d3b99618b9cb9e702770622b8 Mon Sep 17 00:00:00 2001 From: Joshua Cannon Date: Fri, 11 Oct 2019 12:13:15 -0500 Subject: [PATCH 035/541] Evaluate and cat NARG in different macros --- googlemock/include/gmock/internal/gmock-pp.h | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/googlemock/include/gmock/internal/gmock-pp.h b/googlemock/include/gmock/internal/gmock-pp.h index 2ebeaddca0..4298a63eea 100644 --- a/googlemock/include/gmock/internal/gmock-pp.h +++ b/googlemock/include/gmock/internal/gmock-pp.h @@ -26,10 +26,9 @@ // GMOCK_PP_NARG(PAIR) => 2 // // Requires: the number of arguments after expansion is at most 15. -#define GMOCK_PP_NARG(...) \ - GMOCK_PP_INTERNAL_EXPAND_WITH( \ - GMOCK_PP_INTERNAL_INTERNAL_16TH, \ - (__VA_ARGS__, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1)) +#define GMOCK_PP_NARG(...) \ + GMOCK_PP_INTERNAL_INTERNAL_16TH( \ + __VA_ARGS__, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1) // Returns 1 if the expansion of arguments has an unprotected comma. Otherwise // returns 0. Requires no more than 15 unprotected commas. @@ -48,10 +47,9 @@ GMOCK_PP_INTERNAL_EXPAND_WITH(GMOCK_PP_INTERNAL_TAIL, (__VA_ARGS__)) // Calls CAT(_Macro, NARG(__VA_ARGS__))(__VA_ARGS__) -#define GMOCK_PP_VARIADIC_CALL(_Macro, ...) \ - GMOCK_PP_INTERNAL_EXPAND_WITH( \ - GMOCK_PP_CAT(_Macro, GMOCK_PP_NARG(__VA_ARGS__)), \ - (__VA_ARGS__)) +#define GMOCK_PP_VARIADIC_CALL(_Macro, ...) \ + GMOCK_PP_INTERNAL_VARIADIC_CALL( \ + _Macro, GMOCK_PP_NARG(__VA_ARGS__), (__VA_ARGS__)) // If the arguments after expansion have no tokens, evaluates to `1`. Otherwise // evaluates to `0`. @@ -165,6 +163,8 @@ // Workaround MSVC behavior of treating __VA_ARGS__ with commas as one arg // _Args must be wrapped in parenthesis #define GMOCK_PP_INTERNAL_EXPAND_WITH(_Macro, _Args) _Macro _Args +#define GMOCK_PP_INTERNAL_VARIADIC_CALL(_Macro, _N, ...) \ + GMOCK_PP_INTERNAL_EXPAND_WITH(GMOCK_PP_CAT(_Macro, _N),(__VA_ARGS__)) #define GMOCK_PP_INTERNAL_IBP_IS_VARIADIC_C(...) 1 _ #define GMOCK_PP_INTERNAL_IBP_IS_VARIADIC_R_1 1, From 3e813465a46bf9f7e590f008274e9f3b1e68fef7 Mon Sep 17 00:00:00 2001 From: Joshua Cannon Date: Fri, 11 Oct 2019 12:37:59 -0500 Subject: [PATCH 036/541] Removing extraneous parenthesis --- googlemock/include/gmock/internal/gmock-pp.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/googlemock/include/gmock/internal/gmock-pp.h b/googlemock/include/gmock/internal/gmock-pp.h index 4298a63eea..95fcc28be0 100644 --- a/googlemock/include/gmock/internal/gmock-pp.h +++ b/googlemock/include/gmock/internal/gmock-pp.h @@ -49,7 +49,7 @@ // Calls CAT(_Macro, NARG(__VA_ARGS__))(__VA_ARGS__) #define GMOCK_PP_VARIADIC_CALL(_Macro, ...) \ GMOCK_PP_INTERNAL_VARIADIC_CALL( \ - _Macro, GMOCK_PP_NARG(__VA_ARGS__), (__VA_ARGS__)) + _Macro, GMOCK_PP_NARG(__VA_ARGS__), __VA_ARGS__) // If the arguments after expansion have no tokens, evaluates to `1`. Otherwise // evaluates to `0`. From 84a5ae8b85605fd51cf3d0107315670d3cf00fa4 Mon Sep 17 00:00:00 2001 From: Chris Johnson Date: Mon, 7 Oct 2019 09:23:59 -0500 Subject: [PATCH 037/541] Update to distinguish prelease purpose of this fork. --- .../include/gtest/internal/gtest-port.h | 10 +++--- library.json | 32 +++++++++++++++---- 2 files changed, 31 insertions(+), 11 deletions(-) diff --git a/googletest/include/gtest/internal/gtest-port.h b/googletest/include/gtest/internal/gtest-port.h index f24afe7e4b..761b493ff0 100644 --- a/googletest/include/gtest/internal/gtest-port.h +++ b/googletest/include/gtest/internal/gtest-port.h @@ -449,7 +449,7 @@ typedef struct _RTL_CRITICAL_SECTION GTEST_CRITICAL_SECTION; // no support for it at least as recent as Froyo (2.2). #define GTEST_HAS_STD_WSTRING \ (!(GTEST_OS_LINUX_ANDROID || GTEST_OS_CYGWIN || GTEST_OS_SOLARIS || \ - GTEST_OS_HAIKU)) + GTEST_OS_HAIKU || GTEST_OS_ESP8266)) #endif // GTEST_HAS_STD_WSTRING @@ -573,7 +573,7 @@ typedef struct _RTL_CRITICAL_SECTION GTEST_CRITICAL_SECTION; #ifndef GTEST_HAS_STREAM_REDIRECTION // By default, we assume that stream redirection is supported on all // platforms except known mobile ones. -# if GTEST_OS_WINDOWS_MOBILE || GTEST_OS_WINDOWS_PHONE || GTEST_OS_WINDOWS_RT +# if GTEST_OS_WINDOWS_MOBILE || GTEST_OS_WINDOWS_PHONE || GTEST_OS_WINDOWS_RT || GTEST_OS_ESP8266 # define GTEST_HAS_STREAM_REDIRECTION 0 # else # define GTEST_HAS_STREAM_REDIRECTION 1 @@ -1989,9 +1989,9 @@ typedef struct stat StatStruct; inline int FileNo(FILE* file) { return fileno(file); } inline int IsATTY(int fd) { return isatty(fd); } -inline int Stat(const char* path, StatStruct* buf) { +inline int Stat(const char* path, StatStruct* buf) { // stat function not implemented on ESP8266 - return 0; + return 0; } inline int StrCaseCmp(const char* s1, const char* s2) { return strcasecmp(s1, s2); @@ -2052,7 +2052,7 @@ inline int Close(int fd) { return close(fd); } inline const char* StrError(int errnum) { return strerror(errnum); } #endif inline const char* GetEnv(const char* name) { -#if GTEST_OS_WINDOWS_MOBILE || GTEST_OS_WINDOWS_PHONE || GTEST_OS_WINDOWS_RT +#if GTEST_OS_WINDOWS_MOBILE || GTEST_OS_WINDOWS_PHONE || GTEST_OS_WINDOWS_RT || GTEST_OS_ESP8266 // We are on Windows CE, which has no environment variables. static_cast(name); // To prevent 'unused argument' warning. return nullptr; diff --git a/library.json b/library.json index e46fcbdabc..e8f0d6cfe0 100644 --- a/library.json +++ b/library.json @@ -1,17 +1,18 @@ { - "name": "googletest", + "name": "googletest-ciband-prelease", "keywords": "unittest, unit, test, gtest, gmock", - "description": "googletest is a testing framework developed by the Testing Technology team with Google's specific requirements and constraints in mind. No matter whether you work on Linux, Windows, or a Mac, if you write C++ code, googletest can help you. And it supports any kind of tests, not just unit tests.", + "description": "***This is a prelease repo to use new features before they are added to googletest.*** googletest is a testing framework developed by the Testing Technology team with Google's specific requirements and constraints in mind. No matter whether you work on Linux, Windows, or a Mac, if you write C++ code, googletest can help you. And it supports any kind of tests, not just unit tests.", "license": "BSD-3-Clause", "homepage": "https://github.com/google/googletest/blob/master/README.md", "repository": { "type": "git", - "url": "https://github.com/google/googletest.git" + "url": "https://github.com/ciband/googletest.git" }, "version": "1.8.1", "frameworks": "arduino", "platforms": [ - "espressif32" + "espressif32", + "espressif8266" ], "export": { "include": [ @@ -29,7 +30,7 @@ "googlemock/scripts", "googlemock/src/gmock-all.cc", "googlemock/src/gmock_main.cc", - "googlemock/test", + "googlemock/test/*", "googlemock/CMakeLists.txt", "googlemock/Makefile.am", "googlemock/configure.ac", @@ -38,10 +39,11 @@ "googletest/m4", "googletest/make", "googletest/msvc", + "googletest/samples", "googletest/scripts", "googletest/src/gtest-all.cc", "googletest/src/gtest_main.cc", - "googletest/test", + "googletest/test/*", "googletest/xcode", "googletest/CMakeLists.txt", "googletest/Makefile.am", @@ -54,6 +56,24 @@ "-Igooglemock", "-Igoogletest/include", "-Igoogletest" + ], + "srcFilter": [ + "+<*>", + "-<.git/>", + "-", + "-", + "-", + "+", + "+", + "+", + "-", + "-", + "-", + "-", + "-", + "-", + "+", + "+" ] } } From 3cddd56e195b516f449bea6dcd3edd4494195631 Mon Sep 17 00:00:00 2001 From: Robert Luberda Date: Wed, 9 Oct 2019 21:48:00 +0200 Subject: [PATCH 038/541] Add more override keywords Mark more functions with "override" keyword, just like it was done in commit 2460f97152c. This should prevent compiler from complaining while compiling both user code, and the googletest code itself with the -Wsuggest-override option turned on; with the exception of: * calls to new MOCK_METHOD() in test/gmock-function-mocker_test.cc * calls to old MOCK_METHODx()/MOCK_CONST_METHODx() in other unit test files. Closes #2493 --- .../include/gmock/gmock-generated-actions.h | 24 ++--- .../gmock/gmock-generated-actions.h.pump | 4 +- .../include/gmock/gmock-generated-matchers.h | 88 +++++++++---------- .../gmock/gmock-generated-matchers.h.pump | 8 +- googletest/include/gtest/gtest-typed-test.h | 4 +- .../include/gtest/internal/gtest-port.h | 4 +- googletest/test/gtest_unittest.cc | 4 +- 7 files changed, 68 insertions(+), 68 deletions(-) diff --git a/googlemock/include/gmock/gmock-generated-actions.h b/googlemock/include/gmock/gmock-generated-actions.h index 981af78ff9..cee96dae8c 100644 --- a/googlemock/include/gmock/gmock-generated-actions.h +++ b/googlemock/include/gmock/gmock-generated-actions.h @@ -663,7 +663,7 @@ class ActionHelper { typedef typename ::testing::internal::Function::ArgumentTuple\ args_type;\ explicit gmock_Impl GMOCK_INTERNAL_INIT_##value_params {}\ - virtual return_type Perform(const args_type& args) {\ + return_type Perform(const args_type& args) override {\ return ::testing::internal::ActionHelper::\ Perform(this, args);\ }\ @@ -726,7 +726,7 @@ class ActionHelper { typedef typename ::testing::internal::Function::ArgumentTuple\ args_type;\ gmock_Impl() {}\ - virtual return_type Perform(const args_type& args) {\ + return_type Perform(const args_type& args) override {\ return ::testing::internal::ActionHelper::\ Perform(this, args);\ }\ @@ -776,7 +776,7 @@ class ActionHelper { args_type;\ explicit gmock_Impl(p0##_type gmock_p0) : \ p0(::std::forward(gmock_p0)) {}\ - virtual return_type Perform(const args_type& args) {\ + return_type Perform(const args_type& args) override {\ return ::testing::internal::ActionHelper::\ Perform(this, args);\ }\ @@ -832,7 +832,7 @@ class ActionHelper { gmock_Impl(p0##_type gmock_p0, \ p1##_type gmock_p1) : p0(::std::forward(gmock_p0)), \ p1(::std::forward(gmock_p1)) {}\ - virtual return_type Perform(const args_type& args) {\ + return_type Perform(const args_type& args) override {\ return ::testing::internal::ActionHelper::\ Perform(this, args);\ }\ @@ -893,7 +893,7 @@ class ActionHelper { p2##_type gmock_p2) : p0(::std::forward(gmock_p0)), \ p1(::std::forward(gmock_p1)), \ p2(::std::forward(gmock_p2)) {}\ - virtual return_type Perform(const args_type& args) {\ + return_type Perform(const args_type& args) override {\ return ::testing::internal::ActionHelper::\ Perform(this, args);\ }\ @@ -961,7 +961,7 @@ class ActionHelper { p1(::std::forward(gmock_p1)), \ p2(::std::forward(gmock_p2)), \ p3(::std::forward(gmock_p3)) {}\ - virtual return_type Perform(const args_type& args) {\ + return_type Perform(const args_type& args) override {\ return ::testing::internal::ActionHelper::\ Perform(this, args);\ }\ @@ -1038,7 +1038,7 @@ class ActionHelper { p2(::std::forward(gmock_p2)), \ p3(::std::forward(gmock_p3)), \ p4(::std::forward(gmock_p4)) {}\ - virtual return_type Perform(const args_type& args) {\ + return_type Perform(const args_type& args) override {\ return ::testing::internal::ActionHelper::\ Perform(this, args);\ }\ @@ -1119,7 +1119,7 @@ class ActionHelper { p3(::std::forward(gmock_p3)), \ p4(::std::forward(gmock_p4)), \ p5(::std::forward(gmock_p5)) {}\ - virtual return_type Perform(const args_type& args) {\ + return_type Perform(const args_type& args) override {\ return ::testing::internal::ActionHelper::\ Perform(this, args);\ }\ @@ -1206,7 +1206,7 @@ class ActionHelper { p4(::std::forward(gmock_p4)), \ p5(::std::forward(gmock_p5)), \ p6(::std::forward(gmock_p6)) {}\ - virtual return_type Perform(const args_type& args) {\ + return_type Perform(const args_type& args) override {\ return ::testing::internal::ActionHelper::\ Perform(this, args);\ }\ @@ -1302,7 +1302,7 @@ class ActionHelper { p5(::std::forward(gmock_p5)), \ p6(::std::forward(gmock_p6)), \ p7(::std::forward(gmock_p7)) {}\ - virtual return_type Perform(const args_type& args) {\ + return_type Perform(const args_type& args) override {\ return ::testing::internal::ActionHelper::\ Perform(this, args);\ }\ @@ -1404,7 +1404,7 @@ class ActionHelper { p6(::std::forward(gmock_p6)), \ p7(::std::forward(gmock_p7)), \ p8(::std::forward(gmock_p8)) {}\ - virtual return_type Perform(const args_type& args) {\ + return_type Perform(const args_type& args) override {\ return ::testing::internal::ActionHelper::\ Perform(this, args);\ }\ @@ -1513,7 +1513,7 @@ class ActionHelper { p7(::std::forward(gmock_p7)), \ p8(::std::forward(gmock_p8)), \ p9(::std::forward(gmock_p9)) {}\ - virtual return_type Perform(const args_type& args) {\ + return_type Perform(const args_type& args) override {\ return ::testing::internal::ActionHelper::\ Perform(this, args);\ }\ diff --git a/googlemock/include/gmock/gmock-generated-actions.h.pump b/googlemock/include/gmock/gmock-generated-actions.h.pump index 209603c5a9..283abcdc2b 100644 --- a/googlemock/include/gmock/gmock-generated-actions.h.pump +++ b/googlemock/include/gmock/gmock-generated-actions.h.pump @@ -395,7 +395,7 @@ $range k 0..n-1 typedef typename ::testing::internal::Function::ArgumentTuple\ args_type;\ explicit gmock_Impl GMOCK_INTERNAL_INIT_##value_params {}\ - virtual return_type Perform(const args_type& args) {\ + return_type Perform(const args_type& args) override {\ return ::testing::internal::ActionHelper::\ Perform(this, args);\ }\ @@ -482,7 +482,7 @@ $var macro_name = [[$if i==0 [[ACTION]] $elif i==1 [[ACTION_P]] typedef typename ::testing::internal::Function::ArgumentTuple\ args_type;\ [[$if i==1 [[explicit ]]]]gmock_Impl($ctor_param_list)$inits {}\ - virtual return_type Perform(const args_type& args) {\ + return_type Perform(const args_type& args) override {\ return ::testing::internal::ActionHelper::\ Perform(this, args);\ }\ diff --git a/googlemock/include/gmock/gmock-generated-matchers.h b/googlemock/include/gmock/gmock-generated-matchers.h index 690a57f1c9..61892380c2 100644 --- a/googlemock/include/gmock/gmock-generated-matchers.h +++ b/googlemock/include/gmock/gmock-generated-matchers.h @@ -269,13 +269,13 @@ public:\ gmock_Impl()\ {}\ - virtual bool MatchAndExplain(\ + bool MatchAndExplain(\ GTEST_REFERENCE_TO_CONST_(arg_type) arg,\ - ::testing::MatchResultListener* result_listener) const;\ - virtual void DescribeTo(::std::ostream* gmock_os) const {\ + ::testing::MatchResultListener* result_listener) const override;\ + void DescribeTo(::std::ostream* gmock_os) const override {\ *gmock_os << FormatDescription(false);\ }\ - virtual void DescribeNegationTo(::std::ostream* gmock_os) const {\ + void DescribeNegationTo(::std::ostream* gmock_os) const override {\ *gmock_os << FormatDescription(true);\ }\ private:\ @@ -318,13 +318,13 @@ public:\ explicit gmock_Impl(p0##_type gmock_p0)\ : p0(::std::move(gmock_p0)) {}\ - virtual bool MatchAndExplain(\ + bool MatchAndExplain(\ GTEST_REFERENCE_TO_CONST_(arg_type) arg,\ - ::testing::MatchResultListener* result_listener) const;\ - virtual void DescribeTo(::std::ostream* gmock_os) const {\ + ::testing::MatchResultListener* result_listener) const override;\ + void DescribeTo(::std::ostream* gmock_os) const override {\ *gmock_os << FormatDescription(false);\ }\ - virtual void DescribeNegationTo(::std::ostream* gmock_os) const {\ + void DescribeNegationTo(::std::ostream* gmock_os) const override {\ *gmock_os << FormatDescription(true);\ }\ p0##_type const p0;\ @@ -371,13 +371,13 @@ public:\ gmock_Impl(p0##_type gmock_p0, p1##_type gmock_p1)\ : p0(::std::move(gmock_p0)), p1(::std::move(gmock_p1)) {}\ - virtual bool MatchAndExplain(\ + bool MatchAndExplain(\ GTEST_REFERENCE_TO_CONST_(arg_type) arg,\ - ::testing::MatchResultListener* result_listener) const;\ - virtual void DescribeTo(::std::ostream* gmock_os) const {\ + ::testing::MatchResultListener* result_listener) const override;\ + void DescribeTo(::std::ostream* gmock_os) const override {\ *gmock_os << FormatDescription(false);\ }\ - virtual void DescribeNegationTo(::std::ostream* gmock_os) const {\ + void DescribeNegationTo(::std::ostream* gmock_os) const override {\ *gmock_os << FormatDescription(true);\ }\ p0##_type const p0;\ @@ -431,13 +431,13 @@ gmock_Impl(p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2)\ : p0(::std::move(gmock_p0)), p1(::std::move(gmock_p1)), \ p2(::std::move(gmock_p2)) {}\ - virtual bool MatchAndExplain(\ + bool MatchAndExplain(\ GTEST_REFERENCE_TO_CONST_(arg_type) arg,\ - ::testing::MatchResultListener* result_listener) const;\ - virtual void DescribeTo(::std::ostream* gmock_os) const {\ + ::testing::MatchResultListener* result_listener) const override;\ + void DescribeTo(::std::ostream* gmock_os) const override {\ *gmock_os << FormatDescription(false);\ }\ - virtual void DescribeNegationTo(::std::ostream* gmock_os) const {\ + void DescribeNegationTo(::std::ostream* gmock_os) const override {\ *gmock_os << FormatDescription(true);\ }\ p0##_type const p0;\ @@ -495,13 +495,13 @@ p3##_type gmock_p3)\ : p0(::std::move(gmock_p0)), p1(::std::move(gmock_p1)), \ p2(::std::move(gmock_p2)), p3(::std::move(gmock_p3)) {}\ - virtual bool MatchAndExplain(\ + bool MatchAndExplain(\ GTEST_REFERENCE_TO_CONST_(arg_type) arg,\ - ::testing::MatchResultListener* result_listener) const;\ - virtual void DescribeTo(::std::ostream* gmock_os) const {\ + ::testing::MatchResultListener* result_listener) const override;\ + void DescribeTo(::std::ostream* gmock_os) const override {\ *gmock_os << FormatDescription(false);\ }\ - virtual void DescribeNegationTo(::std::ostream* gmock_os) const {\ + void DescribeNegationTo(::std::ostream* gmock_os) const override {\ *gmock_os << FormatDescription(true);\ }\ p0##_type const p0;\ @@ -568,13 +568,13 @@ : p0(::std::move(gmock_p0)), p1(::std::move(gmock_p1)), \ p2(::std::move(gmock_p2)), p3(::std::move(gmock_p3)), \ p4(::std::move(gmock_p4)) {}\ - virtual bool MatchAndExplain(\ + bool MatchAndExplain(\ GTEST_REFERENCE_TO_CONST_(arg_type) arg,\ - ::testing::MatchResultListener* result_listener) const;\ - virtual void DescribeTo(::std::ostream* gmock_os) const {\ + ::testing::MatchResultListener* result_listener) const override;\ + void DescribeTo(::std::ostream* gmock_os) const override {\ *gmock_os << FormatDescription(false);\ }\ - virtual void DescribeNegationTo(::std::ostream* gmock_os) const {\ + void DescribeNegationTo(::std::ostream* gmock_os) const override {\ *gmock_os << FormatDescription(true);\ }\ p0##_type const p0;\ @@ -644,13 +644,13 @@ : p0(::std::move(gmock_p0)), p1(::std::move(gmock_p1)), \ p2(::std::move(gmock_p2)), p3(::std::move(gmock_p3)), \ p4(::std::move(gmock_p4)), p5(::std::move(gmock_p5)) {}\ - virtual bool MatchAndExplain(\ + bool MatchAndExplain(\ GTEST_REFERENCE_TO_CONST_(arg_type) arg,\ - ::testing::MatchResultListener* result_listener) const;\ - virtual void DescribeTo(::std::ostream* gmock_os) const {\ + ::testing::MatchResultListener* result_listener) const override;\ + void DescribeTo(::std::ostream* gmock_os) const override {\ *gmock_os << FormatDescription(false);\ }\ - virtual void DescribeNegationTo(::std::ostream* gmock_os) const {\ + void DescribeNegationTo(::std::ostream* gmock_os) const override {\ *gmock_os << FormatDescription(true);\ }\ p0##_type const p0;\ @@ -726,13 +726,13 @@ p2(::std::move(gmock_p2)), p3(::std::move(gmock_p3)), \ p4(::std::move(gmock_p4)), p5(::std::move(gmock_p5)), \ p6(::std::move(gmock_p6)) {}\ - virtual bool MatchAndExplain(\ + bool MatchAndExplain(\ GTEST_REFERENCE_TO_CONST_(arg_type) arg,\ - ::testing::MatchResultListener* result_listener) const;\ - virtual void DescribeTo(::std::ostream* gmock_os) const {\ + ::testing::MatchResultListener* result_listener) const override;\ + void DescribeTo(::std::ostream* gmock_os) const override {\ *gmock_os << FormatDescription(false);\ }\ - virtual void DescribeNegationTo(::std::ostream* gmock_os) const {\ + void DescribeNegationTo(::std::ostream* gmock_os) const override {\ *gmock_os << FormatDescription(true);\ }\ p0##_type const p0;\ @@ -814,13 +814,13 @@ p2(::std::move(gmock_p2)), p3(::std::move(gmock_p3)), \ p4(::std::move(gmock_p4)), p5(::std::move(gmock_p5)), \ p6(::std::move(gmock_p6)), p7(::std::move(gmock_p7)) {}\ - virtual bool MatchAndExplain(\ + bool MatchAndExplain(\ GTEST_REFERENCE_TO_CONST_(arg_type) arg,\ - ::testing::MatchResultListener* result_listener) const;\ - virtual void DescribeTo(::std::ostream* gmock_os) const {\ + ::testing::MatchResultListener* result_listener) const override;\ + void DescribeTo(::std::ostream* gmock_os) const override {\ *gmock_os << FormatDescription(false);\ }\ - virtual void DescribeNegationTo(::std::ostream* gmock_os) const {\ + void DescribeNegationTo(::std::ostream* gmock_os) const override {\ *gmock_os << FormatDescription(true);\ }\ p0##_type const p0;\ @@ -909,13 +909,13 @@ p4(::std::move(gmock_p4)), p5(::std::move(gmock_p5)), \ p6(::std::move(gmock_p6)), p7(::std::move(gmock_p7)), \ p8(::std::move(gmock_p8)) {}\ - virtual bool MatchAndExplain(\ + bool MatchAndExplain(\ GTEST_REFERENCE_TO_CONST_(arg_type) arg,\ - ::testing::MatchResultListener* result_listener) const;\ - virtual void DescribeTo(::std::ostream* gmock_os) const {\ + ::testing::MatchResultListener* result_listener) const override;\ + void DescribeTo(::std::ostream* gmock_os) const override {\ *gmock_os << FormatDescription(false);\ }\ - virtual void DescribeNegationTo(::std::ostream* gmock_os) const {\ + void DescribeNegationTo(::std::ostream* gmock_os) const override {\ *gmock_os << FormatDescription(true);\ }\ p0##_type const p0;\ @@ -1009,13 +1009,13 @@ p4(::std::move(gmock_p4)), p5(::std::move(gmock_p5)), \ p6(::std::move(gmock_p6)), p7(::std::move(gmock_p7)), \ p8(::std::move(gmock_p8)), p9(::std::move(gmock_p9)) {}\ - virtual bool MatchAndExplain(\ + bool MatchAndExplain(\ GTEST_REFERENCE_TO_CONST_(arg_type) arg,\ - ::testing::MatchResultListener* result_listener) const;\ - virtual void DescribeTo(::std::ostream* gmock_os) const {\ + ::testing::MatchResultListener* result_listener) const override;\ + void DescribeTo(::std::ostream* gmock_os) const override {\ *gmock_os << FormatDescription(false);\ }\ - virtual void DescribeNegationTo(::std::ostream* gmock_os) const {\ + void DescribeNegationTo(::std::ostream* gmock_os) const override {\ *gmock_os << FormatDescription(true);\ }\ p0##_type const p0;\ diff --git a/googlemock/include/gmock/gmock-generated-matchers.h.pump b/googlemock/include/gmock/gmock-generated-matchers.h.pump index ae90917cc3..69d2ae418c 100644 --- a/googlemock/include/gmock/gmock-generated-matchers.h.pump +++ b/googlemock/include/gmock/gmock-generated-matchers.h.pump @@ -302,13 +302,13 @@ $var param_field_decls2 = [[$for j public:\ [[$if i==1 [[explicit ]]]]gmock_Impl($impl_ctor_param_list)\ $impl_inits {}\ - virtual bool MatchAndExplain(\ + bool MatchAndExplain(\ GTEST_REFERENCE_TO_CONST_(arg_type) arg,\ - ::testing::MatchResultListener* result_listener) const;\ - virtual void DescribeTo(::std::ostream* gmock_os) const {\ + ::testing::MatchResultListener* result_listener) const override;\ + void DescribeTo(::std::ostream* gmock_os) const override {\ *gmock_os << FormatDescription(false);\ }\ - virtual void DescribeNegationTo(::std::ostream* gmock_os) const {\ + void DescribeNegationTo(::std::ostream* gmock_os) const override {\ *gmock_os << FormatDescription(true);\ }\$param_field_decls private:\ diff --git a/googletest/include/gtest/gtest-typed-test.h b/googletest/include/gtest/gtest-typed-test.h index 095ce05802..6b7c9c8a07 100644 --- a/googletest/include/gtest/gtest-typed-test.h +++ b/googletest/include/gtest/gtest-typed-test.h @@ -201,7 +201,7 @@ INSTANTIATE_TYPED_TEST_SUITE_P(My, FooTest, MyTypes); private: \ typedef CaseName TestFixture; \ typedef gtest_TypeParam_ TypeParam; \ - virtual void TestBody(); \ + void TestBody() override; \ }; \ static bool gtest_##CaseName##_##TestName##_registered_ \ GTEST_ATTRIBUTE_UNUSED_ = \ @@ -276,7 +276,7 @@ INSTANTIATE_TYPED_TEST_SUITE_P(My, FooTest, MyTypes); private: \ typedef SuiteName TestFixture; \ typedef gtest_TypeParam_ TypeParam; \ - virtual void TestBody(); \ + void TestBody() override; \ }; \ static bool gtest_##TestName##_defined_ GTEST_ATTRIBUTE_UNUSED_ = \ GTEST_TYPED_TEST_SUITE_P_STATE_(SuiteName).AddTestName( \ diff --git a/googletest/include/gtest/internal/gtest-port.h b/googletest/include/gtest/internal/gtest-port.h index f6433c58aa..2b4770ff53 100644 --- a/googletest/include/gtest/internal/gtest-port.h +++ b/googletest/include/gtest/internal/gtest-port.h @@ -1590,7 +1590,7 @@ class ThreadLocal : public ThreadLocalBase { class DefaultValueHolderFactory : public ValueHolderFactory { public: DefaultValueHolderFactory() {} - virtual ValueHolder* MakeNewHolder() const { return new ValueHolder(); } + ValueHolder* MakeNewHolder() const override { return new ValueHolder(); } private: GTEST_DISALLOW_COPY_AND_ASSIGN_(DefaultValueHolderFactory); @@ -1599,7 +1599,7 @@ class ThreadLocal : public ThreadLocalBase { class InstanceValueHolderFactory : public ValueHolderFactory { public: explicit InstanceValueHolderFactory(const T& value) : value_(value) {} - virtual ValueHolder* MakeNewHolder() const { + ValueHolder* MakeNewHolder() const override { return new ValueHolder(value_); } diff --git a/googletest/test/gtest_unittest.cc b/googletest/test/gtest_unittest.cc index 8312bd10e7..d17a15540a 100644 --- a/googletest/test/gtest_unittest.cc +++ b/googletest/test/gtest_unittest.cc @@ -6170,7 +6170,7 @@ TEST_F(ParseFlagsTest, WideStrings) { #if GTEST_USE_OWN_FLAGFILE_FLAG_ class FlagfileTest : public ParseFlagsTest { public: - virtual void SetUp() { + void SetUp() override { ParseFlagsTest::SetUp(); testdata_path_.Set(internal::FilePath( @@ -6180,7 +6180,7 @@ class FlagfileTest : public ParseFlagsTest { EXPECT_TRUE(testdata_path_.CreateFolder()); } - virtual void TearDown() { + void TearDown() override { testing::internal::posix::RmDir(testdata_path_.c_str()); ParseFlagsTest::TearDown(); } From e1b67b07f7bde8398b540e2edf154404cc5a9904 Mon Sep 17 00:00:00 2001 From: Joshua Cannon Date: Fri, 11 Oct 2019 17:13:24 -0500 Subject: [PATCH 039/541] Avoid recursive macros --- googlemock/include/gmock/internal/gmock-pp.h | 50 +++++++++++--------- 1 file changed, 28 insertions(+), 22 deletions(-) diff --git a/googlemock/include/gmock/internal/gmock-pp.h b/googlemock/include/gmock/internal/gmock-pp.h index 95fcc28be0..a077f776d0 100644 --- a/googlemock/include/gmock/internal/gmock-pp.h +++ b/googlemock/include/gmock/internal/gmock-pp.h @@ -26,30 +26,29 @@ // GMOCK_PP_NARG(PAIR) => 2 // // Requires: the number of arguments after expansion is at most 15. -#define GMOCK_PP_NARG(...) \ - GMOCK_PP_INTERNAL_INTERNAL_16TH( \ - __VA_ARGS__, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1) +#define GMOCK_PP_NARG(...) \ + GMOCK_PP_INTERNAL_16TH( \ + (__VA_ARGS__, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1)) // Returns 1 if the expansion of arguments has an unprotected comma. Otherwise // returns 0. Requires no more than 15 unprotected commas. -#define GMOCK_PP_HAS_COMMA(...) \ - GMOCK_PP_INTERNAL_EXPAND_WITH( \ - GMOCK_PP_INTERNAL_INTERNAL_16TH, \ - (__VA_ARGS__, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0)) +#define GMOCK_PP_HAS_COMMA(...) \ + GMOCK_PP_INTERNAL_16TH( \ + (__VA_ARGS__, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0)) // Returns the first argument. #define GMOCK_PP_HEAD(...) \ - GMOCK_PP_INTERNAL_EXPAND_WITH(GMOCK_PP_INTERNAL_HEAD, (__VA_ARGS__)) + GMOCK_PP_INTERNAL_HEAD((__VA_ARGS__)) // Returns the tail. A variadic list of all arguments minus the first. Requires // at least one argument. #define GMOCK_PP_TAIL(...) \ - GMOCK_PP_INTERNAL_EXPAND_WITH(GMOCK_PP_INTERNAL_TAIL, (__VA_ARGS__)) + GMOCK_PP_INTERNAL_TAIL((__VA_ARGS__)) // Calls CAT(_Macro, NARG(__VA_ARGS__))(__VA_ARGS__) #define GMOCK_PP_VARIADIC_CALL(_Macro, ...) \ - GMOCK_PP_INTERNAL_VARIADIC_CALL( \ - _Macro, GMOCK_PP_NARG(__VA_ARGS__), __VA_ARGS__) + GMOCK_PP_IDENTITY( \ + GMOCK_PP_CAT(_Macro, GMOCK_PP_NARG(__VA_ARGS__))(__VA_ARGS__)) // If the arguments after expansion have no tokens, evaluates to `1`. Otherwise // evaluates to `0`. @@ -147,10 +146,6 @@ #define GMOCK_PP_INTENRAL_EMPTY_TUPLE (, , , , , , , , , , , , , , , ) #define GMOCK_PP_INTERNAL_CAT(_1, _2) _1##_2 #define GMOCK_PP_INTERNAL_STRINGIZE(...) #__VA_ARGS__ -#define GMOCK_PP_INTERNAL_INTERNAL_16TH(_1, _2, _3, _4, _5, _6, _7, _8, _9, \ - _10, _11, _12, _13, _14, _15, _16, \ - ...) \ - _16 #define GMOCK_PP_INTERNAL_CAT_5(_1, _2, _3, _4, _5) _1##_2##_3##_4##_5 #define GMOCK_PP_INTERNAL_IS_EMPTY(_1, _2, _3, _4) \ GMOCK_PP_HAS_COMMA(GMOCK_PP_INTERNAL_CAT_5(GMOCK_PP_INTERNAL_IS_EMPTY_CASE_, \ @@ -158,13 +153,24 @@ #define GMOCK_PP_INTERNAL_IS_EMPTY_CASE_0001 , #define GMOCK_PP_INTERNAL_IF_1(_Then, _Else) _Then #define GMOCK_PP_INTERNAL_IF_0(_Then, _Else) _Else -#define GMOCK_PP_INTERNAL_HEAD(_1, ...) _1 -#define GMOCK_PP_INTERNAL_TAIL(_1, ...) __VA_ARGS__ -// Workaround MSVC behavior of treating __VA_ARGS__ with commas as one arg -// _Args must be wrapped in parenthesis -#define GMOCK_PP_INTERNAL_EXPAND_WITH(_Macro, _Args) _Macro _Args -#define GMOCK_PP_INTERNAL_VARIADIC_CALL(_Macro, _N, ...) \ - GMOCK_PP_INTERNAL_EXPAND_WITH(GMOCK_PP_CAT(_Macro, _N),(__VA_ARGS__)) + +// Because of MSVC treating a token with a comma in it as a single token when passed +// to another macro, we need to force it to evaluate it as multiple tokens. We do that +// by using a "IDENTITY(MACRO PARENTHESIZED_ARGS)" macro. +// We define one per possible macro that relies on this behavior. +// Note "_Args" must be parenthesized. +#define GMOCK_PP_INTERNAL_INTERNAL_16TH(_1, _2, _3, _4, _5, _6, _7, _8, _9, \ + _10, _11, _12, _13, _14, _15, _16, \ + ...) \ + _16 +#define GMOCK_PP_INTERNAL_16TH(_Args) \ + GMOCK_PP_IDENTITY(GMOCK_PP_INTERNAL_INTERNAL_16TH _Args) +#define GMOCK_PP_INTERNAL_INTERNAL_HEAD(_1, ...) _1 +#define GMOCK_PP_INTERNAL_HEAD(_Args) \ + GMOCK_PP_IDENTITY(GMOCK_PP_INTERNAL_INTERNAL_HEAD _Args) +#define GMOCK_PP_INTERNAL_INTERNAL_TAIL(_1, ...) __VA_ARGS__ +#define GMOCK_PP_INTERNAL_TAIL(_Args) \ + GMOCK_PP_IDENTITY(GMOCK_PP_INTERNAL_INTERNAL_TAIL _Args) #define GMOCK_PP_INTERNAL_IBP_IS_VARIADIC_C(...) 1 _ #define GMOCK_PP_INTERNAL_IBP_IS_VARIADIC_R_1 1, From 4c25e2b87fcb78abcfdee2739db9ed7a19754cd3 Mon Sep 17 00:00:00 2001 From: Abseil Team Date: Wed, 16 Oct 2019 11:45:27 -0400 Subject: [PATCH 040/541] Googletest export Remove a test case rendered obsolete by disallowing empty argument for INSTANTIATE_TEST_SUITE_P. Remove the code that it was testing. PiperOrigin-RevId: 275040108 --- googletest/include/gtest/internal/gtest-param-util.h | 5 +---- googletest/test/googletest-output-test-golden-lin.txt | 9 +++------ googletest/test/googletest-output-test_.cc | 8 -------- 3 files changed, 4 insertions(+), 18 deletions(-) diff --git a/googletest/include/gtest/internal/gtest-param-util.h b/googletest/include/gtest/internal/gtest-param-util.h index 97533993c0..e900b3ffbf 100644 --- a/googletest/include/gtest/internal/gtest-param-util.h +++ b/googletest/include/gtest/internal/gtest-param-util.h @@ -565,10 +565,7 @@ class ParameterizedTestSuiteInfo : public ParameterizedTestSuiteInfoBase { test_param_names.insert(param_name); - if (!test_info->test_base_name.empty()) { - test_name_stream << test_info->test_base_name << "/"; - } - test_name_stream << param_name; + test_name_stream << test_info->test_base_name << "/" << param_name; MakeAndRegisterTestInfo( test_suite_name.c_str(), test_name_stream.GetString().c_str(), nullptr, // No type parameter. diff --git a/googletest/test/googletest-output-test-golden-lin.txt b/googletest/test/googletest-output-test-golden-lin.txt index de777cff22..270b15ae67 100644 --- a/googletest/test/googletest-output-test-golden-lin.txt +++ b/googletest/test/googletest-output-test-golden-lin.txt @@ -12,7 +12,7 @@ Expected equality of these values: 3 Stack trace: (omitted) -[==========] Running 85 tests from 40 test suites. +[==========] Running 84 tests from 39 test suites. [----------] Global test environment set-up. FooEnvironment::SetUp() called. BarEnvironment::SetUp() called. @@ -966,9 +966,6 @@ Expected equality of these values: Stack trace: (omitted) [ FAILED ] PrintingFailingParams/FailingParamTest.Fails/0, where GetParam() = 2 -[----------] 1 test from All/EmptyBasenameParamInst -[ RUN ] All/EmptyBasenameParamInst.Passes/0 -[ OK ] All/EmptyBasenameParamInst.Passes/0 [----------] 2 tests from PrintingStrings/ParamTest [ RUN ] PrintingStrings/ParamTest.Success/a [ OK ] PrintingStrings/ParamTest.Success/a @@ -995,8 +992,8 @@ Failed Expected fatal failure. Stack trace: (omitted) -[==========] 85 tests from 40 test suites ran. -[ PASSED ] 31 tests. +[==========] 84 tests from 39 test suites ran. +[ PASSED ] 30 tests. [ FAILED ] 54 tests, listed below: [ FAILED ] NonfatalFailureTest.EscapesStringOperands [ FAILED ] NonfatalFailureTest.DiffForLongStrings diff --git a/googletest/test/googletest-output-test_.cc b/googletest/test/googletest-output-test_.cc index 8de2bd1247..f724cca9ce 100644 --- a/googletest/test/googletest-output-test_.cc +++ b/googletest/test/googletest-output-test_.cc @@ -96,14 +96,6 @@ INSTANTIATE_TEST_SUITE_P(PrintingFailingParams, FailingParamTest, testing::Values(2)); -// Tests that an empty value for the test suite basename yields just -// the test name without any prior / -class EmptyBasenameParamInst : public testing::TestWithParam {}; - -TEST_P(EmptyBasenameParamInst, Passes) { EXPECT_EQ(1, GetParam()); } - -INSTANTIATE_TEST_SUITE_P(All, EmptyBasenameParamInst, testing::Values(1)); - static const char kGoldenString[] = "\"Line\0 1\"\nLine 2"; TEST(NonfatalFailureTest, EscapesStringOperands) { From cbf019de22c8dd37b2108da35b2748fd702d1796 Mon Sep 17 00:00:00 2001 From: Alexey Spiridonov Date: Thu, 17 Oct 2019 00:19:18 -0700 Subject: [PATCH 041/541] [googletest] Output skip message Closes #2208 Previously, skip messages were invisible, so debugging skips was hard. Now we have this: ``` $ ./googletest/gtest_skip_test Running main() from /home/lesha/github/snarkmaster/googletest/googletest/src/gtest_main.cc [==========] Running 3 tests from 2 test suites. [----------] Global test environment set-up. [----------] 1 test from SkipTest [ RUN ] SkipTest.DoesSkip /home/lesha/github/snarkmaster/googletest/googletest/test/gtest_skip_test.cc:38: Skipped skipping single test [ SKIPPED ] SkipTest.DoesSkip (0 ms) [----------] 1 test from SkipTest (1 ms total) ... ``` --- googletest/CMakeLists.txt | 1 + googletest/include/gtest/gtest.h | 2 +- googletest/src/gtest.cc | 4 +- googletest/test/BUILD.bazel | 8 +++ .../test/gtest_skip_check_output_test.py | 61 +++++++++++++++++++ googletest/test/gtest_skip_test.cc | 2 +- 6 files changed, 73 insertions(+), 5 deletions(-) create mode 100755 googletest/test/gtest_skip_check_output_test.py diff --git a/googletest/CMakeLists.txt b/googletest/CMakeLists.txt index db292946a5..4fd7b5262e 100644 --- a/googletest/CMakeLists.txt +++ b/googletest/CMakeLists.txt @@ -266,6 +266,7 @@ $env:Path = \"$project_bin;$env:Path\" cxx_executable(googletest-break-on-failure-unittest_ test gtest) py_test(googletest-break-on-failure-unittest) + py_test(gtest_skip_check_output_test) py_test(gtest_skip_environment_check_output_test) # Visual Studio .NET 2003 does not support STL with exceptions disabled. diff --git a/googletest/include/gtest/gtest.h b/googletest/include/gtest/gtest.h index 37a1762bf8..8eda6eac2b 100644 --- a/googletest/include/gtest/gtest.h +++ b/googletest/include/gtest/gtest.h @@ -1889,7 +1889,7 @@ class TestWithParam : public Test, public WithParamInterface { // Skips test in runtime. // Skipping test aborts current function. // Skipped tests are neither successful nor failed. -#define GTEST_SKIP() GTEST_SKIP_("Skipped") +#define GTEST_SKIP() GTEST_SKIP_("") // ADD_FAILURE unconditionally adds a failure to the current test. // SUCCEED generates a success - it doesn't automatically make the diff --git a/googletest/src/gtest.cc b/googletest/src/gtest.cc index a5b4e5ac78..6ddc5c8069 100644 --- a/googletest/src/gtest.cc +++ b/googletest/src/gtest.cc @@ -3220,9 +3220,7 @@ void PrettyUnitTestResultPrinter::OnTestStart(const TestInfo& test_info) { void PrettyUnitTestResultPrinter::OnTestPartResult( const TestPartResult& result) { switch (result.type()) { - // If the test part succeeded, or was skipped, - // we don't need to do anything. - case TestPartResult::kSkip: + // If the test part succeeded, we don't need to do anything. case TestPartResult::kSuccess: return; default: diff --git a/googletest/test/BUILD.bazel b/googletest/test/BUILD.bazel index 156d5d4b42..224e6e6e01 100644 --- a/googletest/test/BUILD.bazel +++ b/googletest/test/BUILD.bazel @@ -295,6 +295,14 @@ cc_test( deps = ["//:gtest_main"], ) +py_test( + name = "gtest_skip_check_output_test", + size = "small", + srcs = ["gtest_skip_check_output_test.py"], + data = [":gtest_skip_test"], + deps = [":gtest_test_utils"], +) + py_test( name = "gtest_skip_environment_check_output_test", size = "small", diff --git a/googletest/test/gtest_skip_check_output_test.py b/googletest/test/gtest_skip_check_output_test.py new file mode 100755 index 0000000000..d5708eeebb --- /dev/null +++ b/googletest/test/gtest_skip_check_output_test.py @@ -0,0 +1,61 @@ +#!/usr/bin/env python +# +# Copyright 2019 Google LLC. 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. +"""Tests Google Test's gtest skip in environment setup behavior. + +This script invokes gtest_skip_in_environment_setup_test_ and verifies its +output. +""" + +import gtest_test_utils +import re + +# Path to the gtest_skip_in_environment_setup_test binary +EXE_PATH = gtest_test_utils.GetTestExecutablePath('gtest_skip_test') + +OUTPUT = gtest_test_utils.Subprocess([EXE_PATH]).output + + +# Test. +class SkipEntireEnvironmentTest(gtest_test_utils.TestCase): + + def testSkipEntireEnvironmentTest(self): + self.assertIn('Skipped\nskipping single test\n', OUTPUT) + skip_fixture = 'Skipped\nskipping all tests for this fixture\n' + self.assertTrue( + re.search( + skip_fixture + '.*' + skip_fixture, OUTPUT, flags=re.DOTALL + ) is not None, + repr(OUTPUT) + ) + self.assertNotIn('FAILED', OUTPUT) + + +if __name__ == '__main__': + gtest_test_utils.Main() diff --git a/googletest/test/gtest_skip_test.cc b/googletest/test/gtest_skip_test.cc index 717e105e2e..4a23004cca 100644 --- a/googletest/test/gtest_skip_test.cc +++ b/googletest/test/gtest_skip_test.cc @@ -35,7 +35,7 @@ using ::testing::Test; TEST(SkipTest, DoesSkip) { - GTEST_SKIP(); + GTEST_SKIP() << "skipping single test"; EXPECT_EQ(0, 1); } From bbe4b7363bbaa7c9e07dbacde11602a4c69504d3 Mon Sep 17 00:00:00 2001 From: Abseil Team Date: Thu, 17 Oct 2019 12:50:10 -0400 Subject: [PATCH 042/541] Googletest export Added IsNan matcher PiperOrigin-RevId: 275278634 --- googlemock/docs/cheat_sheet.md | 1 + googlemock/include/gmock/gmock-matchers.h | 26 +++++- googlemock/test/gmock-matchers_test.cc | 108 ++++++++++++++++++++++ 3 files changed, 133 insertions(+), 2 deletions(-) diff --git a/googlemock/docs/cheat_sheet.md b/googlemock/docs/cheat_sheet.md index 8ec5ea0875..3236e6a9c5 100644 --- a/googlemock/docs/cheat_sheet.md +++ b/googlemock/docs/cheat_sheet.md @@ -287,6 +287,7 @@ is not changed afterwards, or the meaning of your matcher will be changed. | `FloatEq(a_float)` | `argument` is a `float` value approximately equal to `a_float`, treating two NaNs as unequal. | | `NanSensitiveDoubleEq(a_double)` | `argument` is a `double` value approximately equal to `a_double`, treating two NaNs as equal. | | `NanSensitiveFloatEq(a_float)` | `argument` is a `float` value approximately equal to `a_float`, treating two NaNs as equal. | +| `IsNan()` | `argument` is any floating-point type with a NaN value. | The above matchers use ULP-based comparison (the same as used in googletest). diff --git a/googlemock/include/gmock/gmock-matchers.h b/googlemock/include/gmock/gmock-matchers.h index 4428ec1436..be446aad4a 100644 --- a/googlemock/include/gmock/gmock-matchers.h +++ b/googlemock/include/gmock/gmock-matchers.h @@ -42,8 +42,8 @@ #ifndef GMOCK_INCLUDE_GMOCK_GMOCK_MATCHERS_H_ #define GMOCK_INCLUDE_GMOCK_GMOCK_MATCHERS_H_ -#include #include +#include #include #include #include @@ -54,6 +54,7 @@ #include #include #include + #include "gmock/internal/gmock-internal-utils.h" #include "gmock/internal/gmock-port.h" #include "gtest/gtest.h" @@ -1349,6 +1350,22 @@ MakePredicateFormatterFromMatcher(M matcher) { return PredicateFormatterFromMatcher(std::move(matcher)); } +// Implements the polymorphic IsNan() matcher, which matches any floating type +// value that is Nan. +class IsNanMatcher { + public: + template + bool MatchAndExplain(const FloatType& f, + MatchResultListener* /* listener */) const { + return (::std::isnan)(f); + } + + void DescribeTo(::std::ostream* os) const { *os << "is NaN"; } + void DescribeNegationTo(::std::ostream* os) const { + *os << "isn't NaN"; + } +}; + // Implements the polymorphic floating point equality matcher, which matches // two float values using ULP-based approximation or, optionally, a // user-specified epsilon. The template is meant to be instantiated with @@ -1409,7 +1426,7 @@ class FloatingEqMatcher { } const FloatType diff = value - expected_; - if (fabs(diff) <= max_abs_error_) { + if (::std::fabs(diff) <= max_abs_error_) { return true; } @@ -3626,6 +3643,11 @@ inline internal::RefMatcher Ref(T& x) { // NOLINT return internal::RefMatcher(x); } +// Creates a polymorphic matcher that matches any NaN floating point. +inline PolymorphicMatcher IsNan() { + return MakePolymorphicMatcher(internal::IsNanMatcher()); +} + // Creates a matcher that matches any double argument approximately // equal to rhs, where two NANs are considered unequal. inline internal::FloatingEqMatcher DoubleEq(double rhs) { diff --git a/googlemock/test/gmock-matchers_test.cc b/googlemock/test/gmock-matchers_test.cc index 037352676f..451417501f 100644 --- a/googlemock/test/gmock-matchers_test.cc +++ b/googlemock/test/gmock-matchers_test.cc @@ -2054,6 +2054,114 @@ TEST(PairMatchBaseTest, WorksWithMoveOnly) { EXPECT_TRUE(matcher.Matches(pointers)); } +// Tests that IsNan() matches a NaN, with float. +TEST(IsNan, FloatMatchesNan) { + float quiet_nan = std::numeric_limits::quiet_NaN(); + float other_nan = std::nan("1"); + float real_value = 1.0f; + + Matcher m = IsNan(); + EXPECT_TRUE(m.Matches(quiet_nan)); + EXPECT_TRUE(m.Matches(other_nan)); + EXPECT_FALSE(m.Matches(real_value)); + + Matcher m_ref = IsNan(); + EXPECT_TRUE(m_ref.Matches(quiet_nan)); + EXPECT_TRUE(m_ref.Matches(other_nan)); + EXPECT_FALSE(m_ref.Matches(real_value)); + + Matcher m_cref = IsNan(); + EXPECT_TRUE(m_cref.Matches(quiet_nan)); + EXPECT_TRUE(m_cref.Matches(other_nan)); + EXPECT_FALSE(m_cref.Matches(real_value)); +} + +// Tests that IsNan() matches a NaN, with double. +TEST(IsNan, DoubleMatchesNan) { + double quiet_nan = std::numeric_limits::quiet_NaN(); + double other_nan = std::nan("1"); + double real_value = 1.0; + + Matcher m = IsNan(); + EXPECT_TRUE(m.Matches(quiet_nan)); + EXPECT_TRUE(m.Matches(other_nan)); + EXPECT_FALSE(m.Matches(real_value)); + + Matcher m_ref = IsNan(); + EXPECT_TRUE(m_ref.Matches(quiet_nan)); + EXPECT_TRUE(m_ref.Matches(other_nan)); + EXPECT_FALSE(m_ref.Matches(real_value)); + + Matcher m_cref = IsNan(); + EXPECT_TRUE(m_cref.Matches(quiet_nan)); + EXPECT_TRUE(m_cref.Matches(other_nan)); + EXPECT_FALSE(m_cref.Matches(real_value)); +} + +// Tests that IsNan() matches a NaN, with long double. +TEST(IsNan, LongDoubleMatchesNan) { + long double quiet_nan = std::numeric_limits::quiet_NaN(); + long double other_nan = std::nan("1"); + long double real_value = 1.0; + + Matcher m = IsNan(); + EXPECT_TRUE(m.Matches(quiet_nan)); + EXPECT_TRUE(m.Matches(other_nan)); + EXPECT_FALSE(m.Matches(real_value)); + + Matcher m_ref = IsNan(); + EXPECT_TRUE(m_ref.Matches(quiet_nan)); + EXPECT_TRUE(m_ref.Matches(other_nan)); + EXPECT_FALSE(m_ref.Matches(real_value)); + + Matcher m_cref = IsNan(); + EXPECT_TRUE(m_cref.Matches(quiet_nan)); + EXPECT_TRUE(m_cref.Matches(other_nan)); + EXPECT_FALSE(m_cref.Matches(real_value)); +} + +// Tests that IsNan() works with Not. +TEST(IsNan, NotMatchesNan) { + Matcher mf = Not(IsNan()); + EXPECT_FALSE(mf.Matches(std::numeric_limits::quiet_NaN())); + EXPECT_FALSE(mf.Matches(std::nan("1"))); + EXPECT_TRUE(mf.Matches(1.0)); + + Matcher md = Not(IsNan()); + EXPECT_FALSE(md.Matches(std::numeric_limits::quiet_NaN())); + EXPECT_FALSE(md.Matches(std::nan("1"))); + EXPECT_TRUE(md.Matches(1.0)); + + Matcher mld = Not(IsNan()); + EXPECT_FALSE(mld.Matches(std::numeric_limits::quiet_NaN())); + EXPECT_FALSE(mld.Matches(std::nan("1"))); + EXPECT_TRUE(mld.Matches(1.0)); +} + +// Tests that IsNan() can describe itself. +TEST(IsNan, CanDescribeSelf) { + Matcher mf = IsNan(); + EXPECT_EQ("is NaN", Describe(mf)); + + Matcher md = IsNan(); + EXPECT_EQ("is NaN", Describe(md)); + + Matcher mld = IsNan(); + EXPECT_EQ("is NaN", Describe(mld)); +} + +// Tests that IsNan() can describe itself with Not. +TEST(IsNan, CanDescribeSelfWithNot) { + Matcher mf = Not(IsNan()); + EXPECT_EQ("isn't NaN", Describe(mf)); + + Matcher md = Not(IsNan()); + EXPECT_EQ("isn't NaN", Describe(md)); + + Matcher mld = Not(IsNan()); + EXPECT_EQ("isn't NaN", Describe(mld)); +} + // Tests that FloatEq() matches a 2-tuple where // FloatEq(first field) matches the second field. TEST(FloatEq2Test, MatchesEqualArguments) { From 1f9edcd9698162b48d94e1ef2e6a2ab7ab4e6c56 Mon Sep 17 00:00:00 2001 From: Abseil Team Date: Thu, 17 Oct 2019 16:14:42 -0400 Subject: [PATCH 043/541] Googletest export Addressing https://github.com/google/googletest/issues/2502 Add MOCK_METHOD support for returning function pointers. PiperOrigin-RevId: 275323671 --- .../include/gmock/gmock-function-mocker.h | 29 ++++++++++++++++--- googlemock/test/gmock-function-mocker_test.cc | 7 +++++ 2 files changed, 32 insertions(+), 4 deletions(-) diff --git a/googlemock/include/gmock/gmock-function-mocker.h b/googlemock/include/gmock/gmock-function-mocker.h index cc1535c806..684db139ba 100644 --- a/googlemock/include/gmock/gmock-function-mocker.h +++ b/googlemock/include/gmock/gmock-function-mocker.h @@ -39,6 +39,13 @@ #include "gmock/gmock-generated-function-mockers.h" // NOLINT #include "gmock/internal/gmock-pp.h" +namespace testing { +namespace internal { +template +using identity_t = T; +} // namespace internal +} // namespace testing + #define MOCK_METHOD(...) \ GMOCK_PP_VARIADIC_CALL(GMOCK_INTERNAL_MOCK_METHOD_ARG_, __VA_ARGS__) @@ -207,10 +214,24 @@ #define GMOCK_INTERNAL_IS_CALLTYPE_HELPER_Calltype -#define GMOCK_INTERNAL_SIGNATURE(_Ret, _Args) \ - GMOCK_PP_IF(GMOCK_PP_IS_BEGIN_PARENS(_Ret), GMOCK_PP_REMOVE_PARENS, \ - GMOCK_PP_IDENTITY) \ - (_Ret)(GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_GET_TYPE, _, _Args)) +// Note: The use of `identity_t` here allows _Ret to represent return types that +// would normally need to be specified in a different way. For example, a method +// returning a function pointer must be written as +// +// fn_ptr_return_t (*method(method_args_t...))(fn_ptr_args_t...) +// +// But we only support placing the return type at the beginning. To handle this, +// we wrap all calls in identity_t, so that a declaration will be expanded to +// +// identity_t method(method_args_t...) +// +// This allows us to work around the syntactic oddities of function/method +// types. +#define GMOCK_INTERNAL_SIGNATURE(_Ret, _Args) \ + ::testing::internal::identity_t( \ + GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_GET_TYPE, _, _Args)) #define GMOCK_INTERNAL_GET_TYPE(_i, _, _elem) \ GMOCK_PP_COMMA_IF(_i) \ diff --git a/googlemock/test/gmock-function-mocker_test.cc b/googlemock/test/gmock-function-mocker_test.cc index fbc5d5b2bb..55be70a806 100644 --- a/googlemock/test/gmock-function-mocker_test.cc +++ b/googlemock/test/gmock-function-mocker_test.cc @@ -101,6 +101,10 @@ class FooInterface { virtual int TypeWithComma(const std::map& a_map) = 0; virtual int TypeWithTemplatedCopyCtor(const TemplatedCopyable&) = 0; + virtual int (*ReturnsFunctionPointer1(int))(bool) = 0; + using fn_ptr = int (*)(bool); + virtual fn_ptr ReturnsFunctionPointer2(int) = 0; + #if GTEST_OS_WINDOWS STDMETHOD_(int, CTNullary)() = 0; STDMETHOD_(bool, CTUnary)(int x) = 0; @@ -159,6 +163,9 @@ class MockFoo : public FooInterface { MOCK_METHOD(int, TypeWithTemplatedCopyCtor, (const TemplatedCopyable&)); // NOLINT + MOCK_METHOD(int (*)(bool), ReturnsFunctionPointer1, (int), ()); + MOCK_METHOD(fn_ptr, ReturnsFunctionPointer2, (int), ()); + #if GTEST_OS_WINDOWS MOCK_METHOD(int, CTNullary, (), (Calltype(STDMETHODCALLTYPE))); MOCK_METHOD(bool, CTUnary, (int), (Calltype(STDMETHODCALLTYPE))); From f966ed158177f2ed6ff2c402effb16f7f00ca40b Mon Sep 17 00:00:00 2001 From: misterg Date: Fri, 18 Oct 2019 11:06:41 -0400 Subject: [PATCH 044/541] Googletest export Added IsNan matcher PiperOrigin-RevId: 275473218 --- googlemock/docs/cheat_sheet.md | 1 - googlemock/include/gmock/gmock-matchers.h | 26 +----- googlemock/test/gmock-matchers_test.cc | 108 ---------------------- 3 files changed, 2 insertions(+), 133 deletions(-) diff --git a/googlemock/docs/cheat_sheet.md b/googlemock/docs/cheat_sheet.md index 3236e6a9c5..8ec5ea0875 100644 --- a/googlemock/docs/cheat_sheet.md +++ b/googlemock/docs/cheat_sheet.md @@ -287,7 +287,6 @@ is not changed afterwards, or the meaning of your matcher will be changed. | `FloatEq(a_float)` | `argument` is a `float` value approximately equal to `a_float`, treating two NaNs as unequal. | | `NanSensitiveDoubleEq(a_double)` | `argument` is a `double` value approximately equal to `a_double`, treating two NaNs as equal. | | `NanSensitiveFloatEq(a_float)` | `argument` is a `float` value approximately equal to `a_float`, treating two NaNs as equal. | -| `IsNan()` | `argument` is any floating-point type with a NaN value. | The above matchers use ULP-based comparison (the same as used in googletest). diff --git a/googlemock/include/gmock/gmock-matchers.h b/googlemock/include/gmock/gmock-matchers.h index be446aad4a..4428ec1436 100644 --- a/googlemock/include/gmock/gmock-matchers.h +++ b/googlemock/include/gmock/gmock-matchers.h @@ -42,8 +42,8 @@ #ifndef GMOCK_INCLUDE_GMOCK_GMOCK_MATCHERS_H_ #define GMOCK_INCLUDE_GMOCK_GMOCK_MATCHERS_H_ +#include #include -#include #include #include #include @@ -54,7 +54,6 @@ #include #include #include - #include "gmock/internal/gmock-internal-utils.h" #include "gmock/internal/gmock-port.h" #include "gtest/gtest.h" @@ -1350,22 +1349,6 @@ MakePredicateFormatterFromMatcher(M matcher) { return PredicateFormatterFromMatcher(std::move(matcher)); } -// Implements the polymorphic IsNan() matcher, which matches any floating type -// value that is Nan. -class IsNanMatcher { - public: - template - bool MatchAndExplain(const FloatType& f, - MatchResultListener* /* listener */) const { - return (::std::isnan)(f); - } - - void DescribeTo(::std::ostream* os) const { *os << "is NaN"; } - void DescribeNegationTo(::std::ostream* os) const { - *os << "isn't NaN"; - } -}; - // Implements the polymorphic floating point equality matcher, which matches // two float values using ULP-based approximation or, optionally, a // user-specified epsilon. The template is meant to be instantiated with @@ -1426,7 +1409,7 @@ class FloatingEqMatcher { } const FloatType diff = value - expected_; - if (::std::fabs(diff) <= max_abs_error_) { + if (fabs(diff) <= max_abs_error_) { return true; } @@ -3643,11 +3626,6 @@ inline internal::RefMatcher Ref(T& x) { // NOLINT return internal::RefMatcher(x); } -// Creates a polymorphic matcher that matches any NaN floating point. -inline PolymorphicMatcher IsNan() { - return MakePolymorphicMatcher(internal::IsNanMatcher()); -} - // Creates a matcher that matches any double argument approximately // equal to rhs, where two NANs are considered unequal. inline internal::FloatingEqMatcher DoubleEq(double rhs) { diff --git a/googlemock/test/gmock-matchers_test.cc b/googlemock/test/gmock-matchers_test.cc index 451417501f..037352676f 100644 --- a/googlemock/test/gmock-matchers_test.cc +++ b/googlemock/test/gmock-matchers_test.cc @@ -2054,114 +2054,6 @@ TEST(PairMatchBaseTest, WorksWithMoveOnly) { EXPECT_TRUE(matcher.Matches(pointers)); } -// Tests that IsNan() matches a NaN, with float. -TEST(IsNan, FloatMatchesNan) { - float quiet_nan = std::numeric_limits::quiet_NaN(); - float other_nan = std::nan("1"); - float real_value = 1.0f; - - Matcher m = IsNan(); - EXPECT_TRUE(m.Matches(quiet_nan)); - EXPECT_TRUE(m.Matches(other_nan)); - EXPECT_FALSE(m.Matches(real_value)); - - Matcher m_ref = IsNan(); - EXPECT_TRUE(m_ref.Matches(quiet_nan)); - EXPECT_TRUE(m_ref.Matches(other_nan)); - EXPECT_FALSE(m_ref.Matches(real_value)); - - Matcher m_cref = IsNan(); - EXPECT_TRUE(m_cref.Matches(quiet_nan)); - EXPECT_TRUE(m_cref.Matches(other_nan)); - EXPECT_FALSE(m_cref.Matches(real_value)); -} - -// Tests that IsNan() matches a NaN, with double. -TEST(IsNan, DoubleMatchesNan) { - double quiet_nan = std::numeric_limits::quiet_NaN(); - double other_nan = std::nan("1"); - double real_value = 1.0; - - Matcher m = IsNan(); - EXPECT_TRUE(m.Matches(quiet_nan)); - EXPECT_TRUE(m.Matches(other_nan)); - EXPECT_FALSE(m.Matches(real_value)); - - Matcher m_ref = IsNan(); - EXPECT_TRUE(m_ref.Matches(quiet_nan)); - EXPECT_TRUE(m_ref.Matches(other_nan)); - EXPECT_FALSE(m_ref.Matches(real_value)); - - Matcher m_cref = IsNan(); - EXPECT_TRUE(m_cref.Matches(quiet_nan)); - EXPECT_TRUE(m_cref.Matches(other_nan)); - EXPECT_FALSE(m_cref.Matches(real_value)); -} - -// Tests that IsNan() matches a NaN, with long double. -TEST(IsNan, LongDoubleMatchesNan) { - long double quiet_nan = std::numeric_limits::quiet_NaN(); - long double other_nan = std::nan("1"); - long double real_value = 1.0; - - Matcher m = IsNan(); - EXPECT_TRUE(m.Matches(quiet_nan)); - EXPECT_TRUE(m.Matches(other_nan)); - EXPECT_FALSE(m.Matches(real_value)); - - Matcher m_ref = IsNan(); - EXPECT_TRUE(m_ref.Matches(quiet_nan)); - EXPECT_TRUE(m_ref.Matches(other_nan)); - EXPECT_FALSE(m_ref.Matches(real_value)); - - Matcher m_cref = IsNan(); - EXPECT_TRUE(m_cref.Matches(quiet_nan)); - EXPECT_TRUE(m_cref.Matches(other_nan)); - EXPECT_FALSE(m_cref.Matches(real_value)); -} - -// Tests that IsNan() works with Not. -TEST(IsNan, NotMatchesNan) { - Matcher mf = Not(IsNan()); - EXPECT_FALSE(mf.Matches(std::numeric_limits::quiet_NaN())); - EXPECT_FALSE(mf.Matches(std::nan("1"))); - EXPECT_TRUE(mf.Matches(1.0)); - - Matcher md = Not(IsNan()); - EXPECT_FALSE(md.Matches(std::numeric_limits::quiet_NaN())); - EXPECT_FALSE(md.Matches(std::nan("1"))); - EXPECT_TRUE(md.Matches(1.0)); - - Matcher mld = Not(IsNan()); - EXPECT_FALSE(mld.Matches(std::numeric_limits::quiet_NaN())); - EXPECT_FALSE(mld.Matches(std::nan("1"))); - EXPECT_TRUE(mld.Matches(1.0)); -} - -// Tests that IsNan() can describe itself. -TEST(IsNan, CanDescribeSelf) { - Matcher mf = IsNan(); - EXPECT_EQ("is NaN", Describe(mf)); - - Matcher md = IsNan(); - EXPECT_EQ("is NaN", Describe(md)); - - Matcher mld = IsNan(); - EXPECT_EQ("is NaN", Describe(mld)); -} - -// Tests that IsNan() can describe itself with Not. -TEST(IsNan, CanDescribeSelfWithNot) { - Matcher mf = Not(IsNan()); - EXPECT_EQ("isn't NaN", Describe(mf)); - - Matcher md = Not(IsNan()); - EXPECT_EQ("isn't NaN", Describe(md)); - - Matcher mld = Not(IsNan()); - EXPECT_EQ("isn't NaN", Describe(mld)); -} - // Tests that FloatEq() matches a 2-tuple where // FloatEq(first field) matches the second field. TEST(FloatEq2Test, MatchesEqualArguments) { From 5f92697d46aefb319a55ec382107d7c89c81d213 Mon Sep 17 00:00:00 2001 From: Sinclair-John Date: Fri, 18 Oct 2019 19:36:58 +0200 Subject: [PATCH 045/541] Fix Issue 2418 --- googletest/src/gtest.cc | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/googletest/src/gtest.cc b/googletest/src/gtest.cc index a5b4e5ac78..8d40a922cd 100644 --- a/googletest/src/gtest.cc +++ b/googletest/src/gtest.cc @@ -83,8 +83,11 @@ # include // NOLINT # undef min +#ifdef _MSC_VER # include // NOLINT # include // NOLINT +#endif + # include // NOLINT # include // NOLINT # include // NOLINT @@ -4908,7 +4911,6 @@ int UnitTest::Run() { _set_abort_behavior( 0x0, // Clear the following flags: _WRITE_ABORT_MSG | _CALL_REPORTFAULT); // pop-up window, core dump. -# endif // In debug mode, the Windows CRT can crash with an assertion over invalid // input (e.g. passing an invalid file descriptor). The default handling @@ -4919,6 +4921,7 @@ int UnitTest::Run() { _CRTDBG_MODE_FILE | _CRTDBG_MODE_DEBUG); (void)_CrtSetReportFile(_CRT_ASSERT, _CRTDBG_FILE_STDERR); } +# endif } #endif // GTEST_OS_WINDOWS From f164a9e23c0f368bb44f1e2ff047abd7ccc718f3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=CE=BBtlas?= <41349879+cloudrex@users.noreply.github.com> Date: Sat, 19 Oct 2019 11:46:52 -0400 Subject: [PATCH 046/541] Remove extra space --- googletest/README.md | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/googletest/README.md b/googletest/README.md index 766ddc1e07..dd23abcb9c 100644 --- a/googletest/README.md +++ b/googletest/README.md @@ -8,8 +8,7 @@ depends on which build system you use, and is usually straightforward. ### Build with CMake -Google Test comes with a CMake build script ( -[CMakeLists.txt](https://github.com/google/googletest/blob/master/CMakeLists.txt)) +Google Test comes with a CMake build script ([CMakeLists.txt](https://github.com/google/googletest/blob/master/CMakeLists.txt)) that can be used on a wide range of platforms ("C" stands for cross-platform.). If you don't have CMake installed already, you can download it for free from . From 011c4e23d5254bed4b64099a3cb5233d4c4b76e8 Mon Sep 17 00:00:00 2001 From: Abseil Team Date: Fri, 18 Oct 2019 15:23:13 -0400 Subject: [PATCH 047/541] Googletest export Rolling forward IsNan() matcher with fixes in test for -Wconversion issues. Use std::nanf and std::nanl where appropriate. PiperOrigin-RevId: 275523003 --- googlemock/docs/cheat_sheet.md | 1 + googlemock/include/gmock/gmock-matchers.h | 26 +++++- googlemock/test/gmock-matchers_test.cc | 108 ++++++++++++++++++++++ 3 files changed, 133 insertions(+), 2 deletions(-) diff --git a/googlemock/docs/cheat_sheet.md b/googlemock/docs/cheat_sheet.md index 8ec5ea0875..3236e6a9c5 100644 --- a/googlemock/docs/cheat_sheet.md +++ b/googlemock/docs/cheat_sheet.md @@ -287,6 +287,7 @@ is not changed afterwards, or the meaning of your matcher will be changed. | `FloatEq(a_float)` | `argument` is a `float` value approximately equal to `a_float`, treating two NaNs as unequal. | | `NanSensitiveDoubleEq(a_double)` | `argument` is a `double` value approximately equal to `a_double`, treating two NaNs as equal. | | `NanSensitiveFloatEq(a_float)` | `argument` is a `float` value approximately equal to `a_float`, treating two NaNs as equal. | +| `IsNan()` | `argument` is any floating-point type with a NaN value. | The above matchers use ULP-based comparison (the same as used in googletest). diff --git a/googlemock/include/gmock/gmock-matchers.h b/googlemock/include/gmock/gmock-matchers.h index 4428ec1436..be446aad4a 100644 --- a/googlemock/include/gmock/gmock-matchers.h +++ b/googlemock/include/gmock/gmock-matchers.h @@ -42,8 +42,8 @@ #ifndef GMOCK_INCLUDE_GMOCK_GMOCK_MATCHERS_H_ #define GMOCK_INCLUDE_GMOCK_GMOCK_MATCHERS_H_ -#include #include +#include #include #include #include @@ -54,6 +54,7 @@ #include #include #include + #include "gmock/internal/gmock-internal-utils.h" #include "gmock/internal/gmock-port.h" #include "gtest/gtest.h" @@ -1349,6 +1350,22 @@ MakePredicateFormatterFromMatcher(M matcher) { return PredicateFormatterFromMatcher(std::move(matcher)); } +// Implements the polymorphic IsNan() matcher, which matches any floating type +// value that is Nan. +class IsNanMatcher { + public: + template + bool MatchAndExplain(const FloatType& f, + MatchResultListener* /* listener */) const { + return (::std::isnan)(f); + } + + void DescribeTo(::std::ostream* os) const { *os << "is NaN"; } + void DescribeNegationTo(::std::ostream* os) const { + *os << "isn't NaN"; + } +}; + // Implements the polymorphic floating point equality matcher, which matches // two float values using ULP-based approximation or, optionally, a // user-specified epsilon. The template is meant to be instantiated with @@ -1409,7 +1426,7 @@ class FloatingEqMatcher { } const FloatType diff = value - expected_; - if (fabs(diff) <= max_abs_error_) { + if (::std::fabs(diff) <= max_abs_error_) { return true; } @@ -3626,6 +3643,11 @@ inline internal::RefMatcher Ref(T& x) { // NOLINT return internal::RefMatcher(x); } +// Creates a polymorphic matcher that matches any NaN floating point. +inline PolymorphicMatcher IsNan() { + return MakePolymorphicMatcher(internal::IsNanMatcher()); +} + // Creates a matcher that matches any double argument approximately // equal to rhs, where two NANs are considered unequal. inline internal::FloatingEqMatcher DoubleEq(double rhs) { diff --git a/googlemock/test/gmock-matchers_test.cc b/googlemock/test/gmock-matchers_test.cc index 037352676f..b9eb894d2d 100644 --- a/googlemock/test/gmock-matchers_test.cc +++ b/googlemock/test/gmock-matchers_test.cc @@ -2054,6 +2054,114 @@ TEST(PairMatchBaseTest, WorksWithMoveOnly) { EXPECT_TRUE(matcher.Matches(pointers)); } +// Tests that IsNan() matches a NaN, with float. +TEST(IsNan, FloatMatchesNan) { + float quiet_nan = std::numeric_limits::quiet_NaN(); + float other_nan = std::nanf("1"); + float real_value = 1.0f; + + Matcher m = IsNan(); + EXPECT_TRUE(m.Matches(quiet_nan)); + EXPECT_TRUE(m.Matches(other_nan)); + EXPECT_FALSE(m.Matches(real_value)); + + Matcher m_ref = IsNan(); + EXPECT_TRUE(m_ref.Matches(quiet_nan)); + EXPECT_TRUE(m_ref.Matches(other_nan)); + EXPECT_FALSE(m_ref.Matches(real_value)); + + Matcher m_cref = IsNan(); + EXPECT_TRUE(m_cref.Matches(quiet_nan)); + EXPECT_TRUE(m_cref.Matches(other_nan)); + EXPECT_FALSE(m_cref.Matches(real_value)); +} + +// Tests that IsNan() matches a NaN, with double. +TEST(IsNan, DoubleMatchesNan) { + double quiet_nan = std::numeric_limits::quiet_NaN(); + double other_nan = std::nan("1"); + double real_value = 1.0; + + Matcher m = IsNan(); + EXPECT_TRUE(m.Matches(quiet_nan)); + EXPECT_TRUE(m.Matches(other_nan)); + EXPECT_FALSE(m.Matches(real_value)); + + Matcher m_ref = IsNan(); + EXPECT_TRUE(m_ref.Matches(quiet_nan)); + EXPECT_TRUE(m_ref.Matches(other_nan)); + EXPECT_FALSE(m_ref.Matches(real_value)); + + Matcher m_cref = IsNan(); + EXPECT_TRUE(m_cref.Matches(quiet_nan)); + EXPECT_TRUE(m_cref.Matches(other_nan)); + EXPECT_FALSE(m_cref.Matches(real_value)); +} + +// Tests that IsNan() matches a NaN, with long double. +TEST(IsNan, LongDoubleMatchesNan) { + long double quiet_nan = std::numeric_limits::quiet_NaN(); + long double other_nan = std::nan("1"); + long double real_value = 1.0; + + Matcher m = IsNan(); + EXPECT_TRUE(m.Matches(quiet_nan)); + EXPECT_TRUE(m.Matches(other_nan)); + EXPECT_FALSE(m.Matches(real_value)); + + Matcher m_ref = IsNan(); + EXPECT_TRUE(m_ref.Matches(quiet_nan)); + EXPECT_TRUE(m_ref.Matches(other_nan)); + EXPECT_FALSE(m_ref.Matches(real_value)); + + Matcher m_cref = IsNan(); + EXPECT_TRUE(m_cref.Matches(quiet_nan)); + EXPECT_TRUE(m_cref.Matches(other_nan)); + EXPECT_FALSE(m_cref.Matches(real_value)); +} + +// Tests that IsNan() works with Not. +TEST(IsNan, NotMatchesNan) { + Matcher mf = Not(IsNan()); + EXPECT_FALSE(mf.Matches(std::numeric_limits::quiet_NaN())); + EXPECT_FALSE(mf.Matches(std::nanf("1"))); + EXPECT_TRUE(mf.Matches(1.0)); + + Matcher md = Not(IsNan()); + EXPECT_FALSE(md.Matches(std::numeric_limits::quiet_NaN())); + EXPECT_FALSE(md.Matches(std::nan("1"))); + EXPECT_TRUE(md.Matches(1.0)); + + Matcher mld = Not(IsNan()); + EXPECT_FALSE(mld.Matches(std::numeric_limits::quiet_NaN())); + EXPECT_FALSE(mld.Matches(std::nanl("1"))); + EXPECT_TRUE(mld.Matches(1.0)); +} + +// Tests that IsNan() can describe itself. +TEST(IsNan, CanDescribeSelf) { + Matcher mf = IsNan(); + EXPECT_EQ("is NaN", Describe(mf)); + + Matcher md = IsNan(); + EXPECT_EQ("is NaN", Describe(md)); + + Matcher mld = IsNan(); + EXPECT_EQ("is NaN", Describe(mld)); +} + +// Tests that IsNan() can describe itself with Not. +TEST(IsNan, CanDescribeSelfWithNot) { + Matcher mf = Not(IsNan()); + EXPECT_EQ("isn't NaN", Describe(mf)); + + Matcher md = Not(IsNan()); + EXPECT_EQ("isn't NaN", Describe(md)); + + Matcher mld = Not(IsNan()); + EXPECT_EQ("isn't NaN", Describe(mld)); +} + // Tests that FloatEq() matches a 2-tuple where // FloatEq(first field) matches the second field. TEST(FloatEq2Test, MatchesEqualArguments) { From 611a321a6e641846497f75375f9cbe7825ff3f23 Mon Sep 17 00:00:00 2001 From: Abseil Team Date: Mon, 21 Oct 2019 10:56:09 -0400 Subject: [PATCH 048/541] Googletest export Remove bool_constant in favor of std::integral_constant; The one non-trivial use of bool_constant has been changed to have significantly fewer template specializations. PiperOrigin-RevId: 275842490 --- googlemock/include/gmock/gmock-matchers.h | 2 +- .../gmock/internal/gmock-internal-utils.h | 92 ++++++------------- .../include/gtest/internal/gtest-internal.h | 3 +- .../include/gtest/internal/gtest-port.h | 3 - 4 files changed, 29 insertions(+), 71 deletions(-) diff --git a/googlemock/include/gmock/gmock-matchers.h b/googlemock/include/gmock/gmock-matchers.h index be446aad4a..bb047da96c 100644 --- a/googlemock/include/gmock/gmock-matchers.h +++ b/googlemock/include/gmock/gmock-matchers.h @@ -142,7 +142,7 @@ class MatcherCastImpl { template static Matcher CastImpl(const M& polymorphic_matcher_or_value, std::true_type /* convertible_to_matcher */, - bool_constant) { + std::integral_constant) { // M is implicitly convertible to Matcher, which means that either // M is a polymorphic matcher or Matcher has an implicit constructor // from M. In both cases using the implicit conversion will produce a diff --git a/googlemock/include/gmock/internal/gmock-internal-utils.h b/googlemock/include/gmock/internal/gmock-internal-utils.h index 584afa989d..5fd169e93d 100644 --- a/googlemock/include/gmock/internal/gmock-internal-utils.h +++ b/googlemock/include/gmock/internal/gmock-internal-utils.h @@ -157,9 +157,6 @@ GMOCK_DECLARE_KIND_(long double, kFloatingPoint); static_cast< ::testing::internal::TypeKind>( \ ::testing::internal::KindOf::value) -// Evaluates to true if and only if integer type T is signed. -#define GMOCK_IS_SIGNED_(T) (static_cast(-1) < 0) - // LosslessArithmeticConvertibleImpl::value // is true if and only if arithmetic type From can be losslessly converted to // arithmetic type To. @@ -170,65 +167,30 @@ GMOCK_DECLARE_KIND_(long double, kFloatingPoint); // From, and kToKind is the kind of To; the value is // implementation-defined when the above pre-condition is violated. template -struct LosslessArithmeticConvertibleImpl : public std::false_type {}; - -// Converting bool to bool is lossless. -template <> -struct LosslessArithmeticConvertibleImpl - : public std::true_type {}; - -// Converting bool to any integer type is lossless. -template -struct LosslessArithmeticConvertibleImpl - : public std::true_type {}; - -// Converting bool to any floating-point type is lossless. -template -struct LosslessArithmeticConvertibleImpl - : public std::true_type {}; - -// Converting an integer to bool is lossy. -template -struct LosslessArithmeticConvertibleImpl - : public std::false_type {}; - -// Converting an integer to another non-bool integer is lossless -// if and only if the target type's range encloses the source type's range. -template -struct LosslessArithmeticConvertibleImpl - : public bool_constant< - // When converting from a smaller size to a larger size, we are - // fine as long as we are not converting from signed to unsigned. - ((sizeof(From) < sizeof(To)) && - (!GMOCK_IS_SIGNED_(From) || GMOCK_IS_SIGNED_(To))) || - // When converting between the same size, the signedness must match. - ((sizeof(From) == sizeof(To)) && - (GMOCK_IS_SIGNED_(From) == GMOCK_IS_SIGNED_(To)))> {}; // NOLINT - -#undef GMOCK_IS_SIGNED_ - -// Converting an integer to a floating-point type may be lossy, since -// the format of a floating-point number is implementation-defined. -template -struct LosslessArithmeticConvertibleImpl - : public std::false_type {}; - -// Converting a floating-point to bool is lossy. -template -struct LosslessArithmeticConvertibleImpl - : public std::false_type {}; - -// Converting a floating-point to an integer is lossy. -template -struct LosslessArithmeticConvertibleImpl - : public std::false_type {}; - -// Converting a floating-point to another floating-point is lossless -// if and only if the target type is at least as big as the source type. -template -struct LosslessArithmeticConvertibleImpl< - kFloatingPoint, From, kFloatingPoint, To> - : public bool_constant {}; // NOLINT +using LosslessArithmeticConvertibleImpl = std::integral_constant< + bool, + // clang-format off + // Converting from bool is always lossless + (kFromKind == kBool) ? true + // Converting between any other type kinds will be lossy if the type + // kinds are not the same. + : (kFromKind != kToKind) ? false + : (kFromKind == kInteger && + // Converting between integers of different widths is allowed so long + // as the conversion does not go from signed to unsigned. + (((sizeof(From) < sizeof(To)) && + !(std::is_signed::value && !std::is_signed::value)) || + // Converting between integers of the same width only requires the + // two types to have the same signedness. + ((sizeof(From) == sizeof(To)) && + (std::is_signed::value == std::is_signed::value))) + ) ? true + // Floating point conversions are lossless if and only if `To` is at least + // as wide as `From`. + : (kFromKind == kFloatingPoint && (sizeof(From) <= sizeof(To))) ? true + : false + // clang-format on + >; // LosslessArithmeticConvertible::value is true if and only if // arithmetic type From can be losslessly converted to arithmetic type To. @@ -238,9 +200,9 @@ struct LosslessArithmeticConvertibleImpl< // reference) built-in arithmetic types; the value is // implementation-defined when the above pre-condition is violated. template -struct LosslessArithmeticConvertible - : public LosslessArithmeticConvertibleImpl< - GMOCK_KIND_OF_(From), From, GMOCK_KIND_OF_(To), To> {}; // NOLINT +using LosslessArithmeticConvertible = + LosslessArithmeticConvertibleImpl; // This interface knows how to report a Google Mock failure (either // non-fatal or fatal). diff --git a/googletest/include/gtest/internal/gtest-internal.h b/googletest/include/gtest/internal/gtest-internal.h index ebfe3c9d25..9524223232 100644 --- a/googletest/include/gtest/internal/gtest-internal.h +++ b/googletest/include/gtest/internal/gtest-internal.h @@ -855,8 +855,7 @@ class GTEST_API_ Random { // true if and only if T is type proto2::Message or a subclass of it. template struct IsAProtocolMessage - : public bool_constant< - std::is_convertible::value> {}; + : public std::is_convertible {}; // When the compiler sees expression IsContainerTest(0), if C is an // STL-style container class, the first overload of IsContainerTest diff --git a/googletest/include/gtest/internal/gtest-port.h b/googletest/include/gtest/internal/gtest-port.h index c4b1aabe25..dc67902b36 100644 --- a/googletest/include/gtest/internal/gtest-port.h +++ b/googletest/include/gtest/internal/gtest-port.h @@ -1875,9 +1875,6 @@ class GTEST_API_ ThreadLocal { // we cannot detect it. GTEST_API_ size_t GetThreadCount(); -template -using bool_constant = std::integral_constant; - #if GTEST_OS_WINDOWS # define GTEST_PATH_SEP_ "\\" # define GTEST_HAS_ALT_PATH_SEP_ 1 From b11fb80e9e94384589037ecd0595b96105906bbc Mon Sep 17 00:00:00 2001 From: Piotr Nycz Date: Tue, 22 Oct 2019 15:58:00 +0200 Subject: [PATCH 049/541] Prevent using ReturnRef on reference to temporary Fixed issue: 2471 --- googlemock/include/gmock/gmock-actions.h | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/googlemock/include/gmock/gmock-actions.h b/googlemock/include/gmock/gmock-actions.h index f12d39be06..931e69a7b2 100644 --- a/googlemock/include/gmock/gmock-actions.h +++ b/googlemock/include/gmock/gmock-actions.h @@ -1022,6 +1022,10 @@ inline internal::ReturnRefAction ReturnRef(R& x) { // NOLINT return internal::ReturnRefAction(x); } +// Prevent using ReturnRef on reference to temporary. +template +internal::ReturnRefAction ReturnRef(R&&) = delete; + // Creates an action that returns the reference to a copy of the // argument. The copy is created when the action is constructed and // lives as long as the action. From f1afeaa6434812276d106c161f09bf9351a47d39 Mon Sep 17 00:00:00 2001 From: Abseil Team Date: Tue, 22 Oct 2019 10:33:51 -0400 Subject: [PATCH 050/541] Googletest export Typo in Registering tests programmatically section. Changed "were" to "where". PiperOrigin-RevId: 276060801 --- googletest/docs/advanced.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/googletest/docs/advanced.md b/googletest/docs/advanced.md index 179118dcd7..5c34d262f0 100644 --- a/googletest/docs/advanced.md +++ b/googletest/docs/advanced.md @@ -1803,7 +1803,7 @@ For technical reasons, there are some caveats: ## Registering tests programmatically The `TEST` macros handle the vast majority of all use cases, but there are few -were runtime registration logic is required. For those cases, the framework +where runtime registration logic is required. For those cases, the framework provides the `::testing::RegisterTest` that allows callers to register arbitrary tests dynamically. From 19a3bbce512dc2c4959769134fddd52b27989003 Mon Sep 17 00:00:00 2001 From: Piotr Nycz Date: Tue, 22 Oct 2019 18:41:35 +0200 Subject: [PATCH 051/541] Added tests verifying that temporaries are accepted by ReturnRef Issue no 2527 --- googlemock/test/gmock-actions_test.cc | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/googlemock/test/gmock-actions_test.cc b/googlemock/test/gmock-actions_test.cc index f63c8c5af9..99d273aa79 100644 --- a/googlemock/test/gmock-actions_test.cc +++ b/googlemock/test/gmock-actions_test.cc @@ -646,6 +646,30 @@ TEST(ReturnRefTest, IsCovariant) { EXPECT_EQ(&derived, &a.Perform(std::make_tuple())); } +namespace +{ +template ()))> +bool CanCallReturnRef(T&&) { return true; } +bool CanCallReturnRef(Unused) { return false; } +} + +// Tests that ReturnRef(v) is not working with temporaries (T&&) +TEST(ReturnRefTest, WillNotAcceptTemporaryAkaRValueRef) { + int value = 13; + EXPECT_TRUE(CanCallReturnRef(value)); + EXPECT_FALSE(CanCallReturnRef(std::move(value))); + EXPECT_FALSE(CanCallReturnRef(value + 1)); + EXPECT_FALSE(CanCallReturnRef(123)); +} + +// Tests that ReturnRef(v) is not working with const temporaries (const T&&) +TEST(ReturnRefTest, WillNotAcceptConstTemporaryAkaContRValueRef) { + const int value = 42; + EXPECT_TRUE(CanCallReturnRef(value)); + EXPECT_FALSE(CanCallReturnRef(std::move(value))); +} + + // Tests that ReturnRefOfCopy(v) works for reference types. TEST(ReturnRefOfCopyTest, WorksForReference) { int n = 42; From 37590da6c08f062c511211462d2a13b57eedcd59 Mon Sep 17 00:00:00 2001 From: Piotr Nycz Date: Wed, 23 Oct 2019 10:12:48 +0200 Subject: [PATCH 052/541] Added more tests to verify: ReturnRef not accept temporary Issue 2471 --- googlemock/test/gmock-actions_test.cc | 72 +++++++++++++++++++++------ 1 file changed, 57 insertions(+), 15 deletions(-) diff --git a/googlemock/test/gmock-actions_test.cc b/googlemock/test/gmock-actions_test.cc index 99d273aa79..86f570fa41 100644 --- a/googlemock/test/gmock-actions_test.cc +++ b/googlemock/test/gmock-actions_test.cc @@ -46,6 +46,7 @@ #include #include #include +#include #include "gmock/gmock.h" #include "gmock/internal/gmock-port.h" #include "gtest/gtest.h" @@ -646,29 +647,70 @@ TEST(ReturnRefTest, IsCovariant) { EXPECT_EQ(&derived, &a.Perform(std::make_tuple())); } -namespace -{ template ()))> bool CanCallReturnRef(T&&) { return true; } bool CanCallReturnRef(Unused) { return false; } + +// Defined here, because gmock has to work with C++11 (std::void_t is from C++17) +template struct precpp17_make_void { typedef void type;}; +template using precpp17_void_t = typename precpp17_make_void::type; + +template +struct HasReturnRefAction : std::false_type {}; +template +struct HasReturnRefAction()))>> + : std::true_type {}; + +// Just an example of non-POD type +class MyNonPodType { + public: + MyNonPodType(int a_value) : value_(a_value) {} + + private: + int value_; +}; +// Just an example of POD type +using MyPodType = int; + +// Tests that ReturnRef(v) is working with non-temporaries (T&) +TEST(ReturnRefTest, IsAcceptingNonTemporary) { + EXPECT_TRUE(HasReturnRefAction::value); + EXPECT_TRUE(HasReturnRefAction::value); + EXPECT_TRUE(HasReturnRefAction::value); + EXPECT_TRUE(HasReturnRefAction::value); + + MyNonPodType nonPodValue{123}; + EXPECT_TRUE(CanCallReturnRef(nonPodValue)); + + MyPodType podValue{321}; + EXPECT_TRUE(CanCallReturnRef(podValue)); + + const MyNonPodType constNonPodValue{123}; + EXPECT_TRUE(CanCallReturnRef(constNonPodValue)); + + const MyPodType constPodValue{321}; + EXPECT_TRUE(CanCallReturnRef(constPodValue)); } // Tests that ReturnRef(v) is not working with temporaries (T&&) -TEST(ReturnRefTest, WillNotAcceptTemporaryAkaRValueRef) { - int value = 13; - EXPECT_TRUE(CanCallReturnRef(value)); - EXPECT_FALSE(CanCallReturnRef(std::move(value))); - EXPECT_FALSE(CanCallReturnRef(value + 1)); - EXPECT_FALSE(CanCallReturnRef(123)); -} +TEST(ReturnRefTest, IsNotAcceptingTemporary) { + EXPECT_FALSE(HasReturnRefAction::value); + EXPECT_FALSE(HasReturnRefAction::value); + EXPECT_FALSE(HasReturnRefAction::value); + EXPECT_FALSE(HasReturnRefAction::value); -// Tests that ReturnRef(v) is not working with const temporaries (const T&&) -TEST(ReturnRefTest, WillNotAcceptConstTemporaryAkaContRValueRef) { - const int value = 42; - EXPECT_TRUE(CanCallReturnRef(value)); - EXPECT_FALSE(CanCallReturnRef(std::move(value))); -} + auto nonPodValue = []() -> MyNonPodType { return MyNonPodType{123}; }; + EXPECT_FALSE(CanCallReturnRef(nonPodValue())); + + auto podValue = []() -> MyPodType { return MyPodType{321}; }; + EXPECT_FALSE(CanCallReturnRef(podValue())); + auto constNonPodValue = []() -> const MyNonPodType { return MyNonPodType{123}; }; + EXPECT_FALSE(CanCallReturnRef(constNonPodValue())); + + // cannot use here callable returning "const POD" because C++ ignores such const for POD return type, so the static_cast + EXPECT_FALSE(CanCallReturnRef(static_cast(42))); +} // Tests that ReturnRefOfCopy(v) works for reference types. TEST(ReturnRefOfCopyTest, WorksForReference) { From aa1146da816954a87bdd6ad745d6281a529e0d90 Mon Sep 17 00:00:00 2001 From: Abseil Team Date: Tue, 22 Oct 2019 12:24:04 -0400 Subject: [PATCH 053/541] Googletest export Split the scoped trace examples into two snippets. This doesn't have an effect in the github markdown renderer, but in some other renderers/templates, this leads them to be independently copy-pastable. In particular, the markdown rendering that Google uses internally has a copy button for each code snippet, which, before this change, would copy both lines. Bad copy button, no cookie! After this change, there will be two such buttons, one per line, and clicking a copy button will copy only the one snippet it is next to, and not the other. This is desirable because nobody will ever want to copy both lines, only one or the other. PiperOrigin-RevId: 276079009 --- googletest/docs/advanced.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/googletest/docs/advanced.md b/googletest/docs/advanced.md index 5c34d262f0..ce8644e409 100644 --- a/googletest/docs/advanced.md +++ b/googletest/docs/advanced.md @@ -918,6 +918,8 @@ the `SCOPED_TRACE` macro or the `ScopedTrace` utility: ```c++ SCOPED_TRACE(message); +``` +```c++ ScopedTrace trace("file_path", line_number, message); ``` From 676d0444bf95d0ffba07973dcc7234e645acdb91 Mon Sep 17 00:00:00 2001 From: Joshua Cannon Date: Wed, 23 Oct 2019 14:46:46 -0500 Subject: [PATCH 054/541] Revert "Merge pull request #2498 from thejcannon:noexcept_spec" This reverts commit ba513d2c9525a7c986c115ed5d603f2cf17c6016, reversing changes made to a3ca5b9e0bf9abc3bc639684966085c4d3182578. --- .../include/gmock/gmock-function-mocker.h | 42 ++++++++++--------- googlemock/test/gmock-function-mocker_test.cc | 29 +++++++++++++ 2 files changed, 51 insertions(+), 20 deletions(-) diff --git a/googlemock/include/gmock/gmock-function-mocker.h b/googlemock/include/gmock/gmock-function-mocker.h index 684db139ba..c5291412b5 100644 --- a/googlemock/include/gmock/gmock-function-mocker.h +++ b/googlemock/include/gmock/gmock-function-mocker.h @@ -58,16 +58,17 @@ using identity_t = T; #define GMOCK_INTERNAL_MOCK_METHOD_ARG_3(_Ret, _MethodName, _Args) \ GMOCK_INTERNAL_MOCK_METHOD_ARG_4(_Ret, _MethodName, _Args, ()) -#define GMOCK_INTERNAL_MOCK_METHOD_ARG_4(_Ret, _MethodName, _Args, _Spec) \ - GMOCK_INTERNAL_ASSERT_PARENTHESIS(_Args); \ - GMOCK_INTERNAL_ASSERT_PARENTHESIS(_Spec); \ - GMOCK_INTERNAL_ASSERT_VALID_SIGNATURE( \ - GMOCK_PP_NARG0 _Args, GMOCK_INTERNAL_SIGNATURE(_Ret, _Args)); \ - GMOCK_INTERNAL_ASSERT_VALID_SPEC(_Spec) \ - GMOCK_INTERNAL_MOCK_METHOD_IMPL( \ - GMOCK_PP_NARG0 _Args, _MethodName, GMOCK_INTERNAL_HAS_CONST(_Spec), \ - GMOCK_INTERNAL_HAS_OVERRIDE(_Spec), GMOCK_INTERNAL_HAS_FINAL(_Spec), \ - GMOCK_INTERNAL_HAS_NOEXCEPT(_Spec), GMOCK_INTERNAL_GET_CALLTYPE(_Spec), \ +#define GMOCK_INTERNAL_MOCK_METHOD_ARG_4(_Ret, _MethodName, _Args, _Spec) \ + GMOCK_INTERNAL_ASSERT_PARENTHESIS(_Args); \ + GMOCK_INTERNAL_ASSERT_PARENTHESIS(_Spec); \ + GMOCK_INTERNAL_ASSERT_VALID_SIGNATURE( \ + GMOCK_PP_NARG0 _Args, GMOCK_INTERNAL_SIGNATURE(_Ret, _Args)); \ + GMOCK_INTERNAL_ASSERT_VALID_SPEC(_Spec) \ + GMOCK_INTERNAL_MOCK_METHOD_IMPL( \ + GMOCK_PP_NARG0 _Args, _MethodName, GMOCK_INTERNAL_HAS_CONST(_Spec), \ + GMOCK_INTERNAL_HAS_OVERRIDE(_Spec), GMOCK_INTERNAL_HAS_FINAL(_Spec), \ + GMOCK_INTERNAL_GET_NOEXCEPT_SPEC(_Spec), \ + GMOCK_INTERNAL_GET_CALLTYPE(_Spec), \ (GMOCK_INTERNAL_SIGNATURE(_Ret, _Args))) #define GMOCK_INTERNAL_MOCK_METHOD_ARG_5(...) \ @@ -107,15 +108,14 @@ using identity_t = T; GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_ASSERT_VALID_SPEC_ELEMENT, ~, _Spec) #define GMOCK_INTERNAL_MOCK_METHOD_IMPL(_N, _MethodName, _Constness, \ - _Override, _Final, _Noexcept, \ + _Override, _Final, _NoexceptSpec, \ _CallType, _Signature) \ typename ::testing::internal::Function::Result \ GMOCK_INTERNAL_EXPAND(_CallType) \ _MethodName(GMOCK_PP_REPEAT(GMOCK_INTERNAL_PARAMETER, _Signature, _N)) \ - GMOCK_PP_IF(_Constness, const, ) GMOCK_PP_IF(_Noexcept, noexcept, ) \ - GMOCK_PP_IF(_Override, override, ) \ - GMOCK_PP_IF(_Final, final, ) { \ + GMOCK_PP_IF(_Constness, const, ) _NoexceptSpec \ + GMOCK_PP_IF(_Override, override, ) GMOCK_PP_IF(_Final, final, ) { \ GMOCK_MOCKER_(_N, _Constness, _MethodName) \ .SetOwnerAndName(this, #_MethodName); \ return GMOCK_MOCKER_(_N, _Constness, _MethodName) \ @@ -131,8 +131,7 @@ using identity_t = T; ::testing::MockSpec gmock_##_MethodName( \ const ::testing::internal::WithoutMatchers&, \ GMOCK_PP_IF(_Constness, const, )::testing::internal::Function< \ - GMOCK_PP_REMOVE_PARENS(_Signature)>*) \ - const GMOCK_PP_IF(_Noexcept, noexcept, ) { \ + GMOCK_PP_REMOVE_PARENS(_Signature)>*) const _NoexceptSpec { \ return GMOCK_PP_CAT(::testing::internal::AdjustConstness_, \ GMOCK_PP_IF(_Constness, const, ))(this) \ ->gmock_##_MethodName(GMOCK_PP_REPEAT( \ @@ -154,9 +153,13 @@ using identity_t = T; #define GMOCK_INTERNAL_HAS_FINAL(_Tuple) \ GMOCK_PP_HAS_COMMA(GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_DETECT_FINAL, ~, _Tuple)) -#define GMOCK_INTERNAL_HAS_NOEXCEPT(_Tuple) \ - GMOCK_PP_HAS_COMMA( \ - GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_DETECT_NOEXCEPT, ~, _Tuple)) +#define GMOCK_INTERNAL_GET_NOEXCEPT_SPEC(_Tuple) \ + GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_NOEXCEPT_SPEC_IF_NOEXCEPT, ~, _Tuple) + +#define GMOCK_INTERNAL_NOEXCEPT_SPEC_IF_NOEXCEPT(_i, _, _elem) \ + GMOCK_PP_IF( \ + GMOCK_PP_HAS_COMMA(GMOCK_INTERNAL_DETECT_NOEXCEPT(_i, _, _elem)), \ + _elem, ) #define GMOCK_INTERNAL_GET_CALLTYPE(_Tuple) \ GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_GET_CALLTYPE_IMPL, ~, _Tuple) @@ -187,7 +190,6 @@ using identity_t = T; #define GMOCK_INTERNAL_DETECT_FINAL_I_final , -// TODO(iserna): Maybe noexcept should accept an argument here as well. #define GMOCK_INTERNAL_DETECT_NOEXCEPT(_i, _, _elem) \ GMOCK_PP_CAT(GMOCK_INTERNAL_DETECT_NOEXCEPT_I_, _elem) diff --git a/googlemock/test/gmock-function-mocker_test.cc b/googlemock/test/gmock-function-mocker_test.cc index 55be70a806..90d6b5f136 100644 --- a/googlemock/test/gmock-function-mocker_test.cc +++ b/googlemock/test/gmock-function-mocker_test.cc @@ -42,6 +42,8 @@ #include #include +#include + #include "gmock/gmock.h" #include "gtest/gtest.h" @@ -663,5 +665,32 @@ TEST(MockMethodMockFunctionTest, MockMethodSizeOverhead) { EXPECT_EQ(sizeof(MockMethodSizes0), sizeof(MockMethodSizes4)); } +void hasTwoParams(int, int); +void MaybeThrows(); +void DoesntThrow() noexcept; +struct MockMethodNoexceptSpecifier { + MOCK_METHOD(void, func1, (), (noexcept)); + MOCK_METHOD(void, func2, (), (noexcept(true))); + MOCK_METHOD(void, func3, (), (noexcept(false))); + MOCK_METHOD(void, func4, (), (noexcept(noexcept(MaybeThrows())))); + MOCK_METHOD(void, func5, (), (noexcept(noexcept(DoesntThrow())))); + MOCK_METHOD(void, func6, (), (noexcept(noexcept(DoesntThrow())), const)); + MOCK_METHOD(void, func7, (), (const, noexcept(noexcept(DoesntThrow())))); + // Put commas in the noexcept expression + MOCK_METHOD(void, func8, (), (noexcept(noexcept(hasTwoParams(1, 2))), const)); +}; + +TEST(MockMethodMockFunctionTest, NoexceptSpecifierPreserved) { + EXPECT_TRUE(noexcept(std::declval().func1())); + EXPECT_TRUE(noexcept(std::declval().func2())); + EXPECT_FALSE(noexcept(std::declval().func3())); + EXPECT_FALSE(noexcept(std::declval().func4())); + EXPECT_TRUE(noexcept(std::declval().func5())); + EXPECT_TRUE(noexcept(std::declval().func6())); + EXPECT_TRUE(noexcept(std::declval().func7())); + EXPECT_EQ(noexcept(std::declval().func8()), + noexcept(hasTwoParams(1, 2))); +} + } // namespace gmock_function_mocker_test } // namespace testing From 37f322783175a66c11785d17fc153477b0777753 Mon Sep 17 00:00:00 2001 From: Abseil Team Date: Wed, 23 Oct 2019 14:09:41 -0400 Subject: [PATCH 055/541] Googletest export Add a matcher `testing::ReturnRoundRobin` which, on each call, returns the next element in the sequence, restarting at the beginning once it has reached the end. PiperOrigin-RevId: 276312136 --- googlemock/docs/cheat_sheet.md | 21 +- googlemock/include/gmock/gmock-actions.h | 47 ++ googlemock/scripts/README.md | 5 + googlemock/scripts/generator/cpp/ast.py | 46 +- .../scripts/generator/cpp/gmock_class.py | 114 +++- .../scripts/generator/cpp/gmock_class_test.py | 93 ++- googlemock/scripts/generator/cpp/keywords.py | 39 +- googlemock/scripts/generator/cpp/tokenize.py | 39 +- googlemock/scripts/generator/cpp/utils.py | 40 +- googlemock/scripts/generator/gmock_gen.py | 36 +- googlemock/scripts/gmock-config.in | 303 --------- googlemock/scripts/gmock_doctor.py | 640 ------------------ googlemock/scripts/upload.py | 35 +- googlemock/test/gmock-actions_test.cc | 26 + googletest/scripts/README.md | 5 + googletest/scripts/gen_gtest_pred_impl.py | 14 +- googletest/scripts/pump.py | 30 +- googletest/scripts/run_with_path.py | 32 + googletest/scripts/upload.py | 35 +- 19 files changed, 485 insertions(+), 1115 deletions(-) create mode 100644 googlemock/scripts/README.md delete mode 100755 googlemock/scripts/gmock-config.in delete mode 100755 googlemock/scripts/gmock_doctor.py create mode 100644 googletest/scripts/README.md create mode 100755 googletest/scripts/run_with_path.py diff --git a/googlemock/docs/cheat_sheet.md b/googlemock/docs/cheat_sheet.md index 3236e6a9c5..aafb3b3b18 100644 --- a/googlemock/docs/cheat_sheet.md +++ b/googlemock/docs/cheat_sheet.md @@ -503,16 +503,17 @@ which must be a permanent callback. #### Returning a Value -| | | -| :-------------------------- | :-------------------------------------------- | -| `Return()` | Return from a `void` mock function. | -| `Return(value)` | Return `value`. If the type of `value` is different to the mock function's return type, `value` is converted to the latter type at the time the expectation is set, not when the action is executed. | -| `ReturnArg()` | Return the `N`-th (0-based) argument. | -| `ReturnNew(a1, ..., ak)` | Return `new T(a1, ..., ak)`; a different object is created each time. | -| `ReturnNull()` | Return a null pointer. | -| `ReturnPointee(ptr)` | Return the value pointed to by `ptr`. | -| `ReturnRef(variable)` | Return a reference to `variable`. | -| `ReturnRefOfCopy(value)` | Return a reference to a copy of `value`; the copy lives as long as the action. | +| | | +| :-------------------------------- | :-------------------------------------------- | +| `Return()` | Return from a `void` mock function. | +| `Return(value)` | Return `value`. If the type of `value` is different to the mock function's return type, `value` is converted to the latter type at the time the expectation is set, not when the action is executed. | +| `ReturnArg()` | Return the `N`-th (0-based) argument. | +| `ReturnNew(a1, ..., ak)` | Return `new T(a1, ..., ak)`; a different object is created each time. | +| `ReturnNull()` | Return a null pointer. | +| `ReturnPointee(ptr)` | Return the value pointed to by `ptr`. | +| `ReturnRef(variable)` | Return a reference to `variable`. | +| `ReturnRefOfCopy(value)` | Return a reference to a copy of `value`; the copy lives as long as the action. | +| `ReturnRoundRobin({a1, ..., ak})` | Each call will return the next `ai` in the list, starting at the beginning when the end of the list is reached. | #### Side Effects diff --git a/googlemock/include/gmock/gmock-actions.h b/googlemock/include/gmock/gmock-actions.h index f12d39be06..91abcd351b 100644 --- a/googlemock/include/gmock/gmock-actions.h +++ b/googlemock/include/gmock/gmock-actions.h @@ -716,6 +716,36 @@ class ReturnRefOfCopyAction { GTEST_DISALLOW_ASSIGN_(ReturnRefOfCopyAction); }; +// Implements the polymorphic ReturnRoundRobin(v) action, which can be +// used in any function that returns the element_type of v. +template +class ReturnRoundRobinAction { + public: + explicit ReturnRoundRobinAction(std::vector values) { + GTEST_CHECK_(!values.empty()) + << "ReturnRoundRobin requires at least one element."; + state_->values = std::move(values); + } + + template + T operator()(Args&&...) const { + return state_->Next(); + } + + private: + struct State { + T Next() { + T ret_val = values[i++]; + if (i == values.size()) i = 0; + return ret_val; + } + + std::vector values; + size_t i = 0; + }; + std::shared_ptr state_ = std::make_shared(); +}; + // Implements the polymorphic DoDefault() action. class DoDefaultAction { public: @@ -1039,6 +1069,23 @@ internal::ByMoveWrapper ByMove(R x) { return internal::ByMoveWrapper(std::move(x)); } +// Creates an action that returns an element of `vals`. Calling this action will +// repeatedly return the next value from `vals` until it reaches the end and +// will restart from the beginning. +template +internal::ReturnRoundRobinAction ReturnRoundRobin(std::vector vals) { + return internal::ReturnRoundRobinAction(std::move(vals)); +} + +// Creates an action that returns an element of `vals`. Calling this action will +// repeatedly return the next value from `vals` until it reaches the end and +// will restart from the beginning. +template +internal::ReturnRoundRobinAction ReturnRoundRobin( + std::initializer_list vals) { + return internal::ReturnRoundRobinAction(std::vector(vals)); +} + // Creates an action that does the default action for the give mock function. inline internal::DoDefaultAction DoDefault() { return internal::DoDefaultAction(); diff --git a/googlemock/scripts/README.md b/googlemock/scripts/README.md new file mode 100644 index 0000000000..fa359fed92 --- /dev/null +++ b/googlemock/scripts/README.md @@ -0,0 +1,5 @@ +# Please Note: + +Files in this directory are no longer supported by the maintainers. They +represent mosty historical artifacts and supported by the community only. There +is no guarantee whatsoever that these scripts still work. diff --git a/googlemock/scripts/generator/cpp/ast.py b/googlemock/scripts/generator/cpp/ast.py index f14728b461..77bbec995f 100755 --- a/googlemock/scripts/generator/cpp/ast.py +++ b/googlemock/scripts/generator/cpp/ast.py @@ -17,10 +17,7 @@ """Generate an Abstract Syntax Tree (AST) for C++.""" -__author__ = 'nnorwitz@google.com (Neal Norwitz)' - - -# TODO: +# FIXME: # * Tokens should never be exported, need to convert to Nodes # (return types, parameters, etc.) # * Handle static class data for templatized classes @@ -338,7 +335,7 @@ def Requires(self, node): # TODO(nnorwitz): handle namespaces, etc. if self.bases: for token_list in self.bases: - # TODO(nnorwitz): bases are tokens, do name comparison. + # TODO(nnorwitz): bases are tokens, do name comparision. for token in token_list: if token.name == node.name: return True @@ -381,7 +378,7 @@ def IsExportable(self): def Requires(self, node): if self.parameters: - # TODO(nnorwitz): parameters are tokens, do name comparison. + # TODO(nnorwitz): parameters are tokens, do name comparision. for p in self.parameters: if p.name == node.name: return True @@ -739,6 +736,14 @@ def _GenerateOne(self, token): if token.token_type == tokenize.NAME: if (keywords.IsKeyword(token.name) and not keywords.IsBuiltinType(token.name)): + if token.name == 'enum': + # Pop the next token and only put it back if it's not + # 'class'. This allows us to support the two-token + # 'enum class' keyword as if it were simply 'enum'. + next = self._GetNextToken() + if next.name != 'class': + self._AddBackToken(next) + method = getattr(self, 'handle_' + token.name) return method() elif token.name == self.in_class_name_only: @@ -754,7 +759,8 @@ def _GenerateOne(self, token): # Handle data or function declaration/definition. syntax = tokenize.SYNTAX temp_tokens, last_token = \ - self._GetVarTokensUpTo(syntax, '(', ';', '{', '[') + self._GetVarTokensUpToIgnoringTemplates(syntax, + '(', ';', '{', '[') temp_tokens.insert(0, token) if last_token.name == '(': # If there is an assignment before the paren, @@ -858,7 +864,25 @@ def _GetVarTokensUpTo(self, expected_token_type, *expected_tokens): last_token = self._GetNextToken() return tokens, last_token - # TODO(nnorwitz): remove _IgnoreUpTo() it shouldn't be necessary. + # Same as _GetVarTokensUpTo, but skips over '<...>' which could contain an + # expected token. + def _GetVarTokensUpToIgnoringTemplates(self, expected_token_type, + *expected_tokens): + last_token = self._GetNextToken() + tokens = [] + nesting = 0 + while (nesting > 0 or + last_token.token_type != expected_token_type or + last_token.name not in expected_tokens): + tokens.append(last_token) + last_token = self._GetNextToken() + if last_token.name == '<': + nesting += 1 + elif last_token.name == '>': + nesting -= 1 + return tokens, last_token + + # TODO(nnorwitz): remove _IgnoreUpTo() it shouldn't be necesary. def _IgnoreUpTo(self, token_type, token): unused_tokens = self._GetTokensUpTo(token_type, token) @@ -1264,9 +1288,6 @@ def handle_union(self): return self._GetNestedType(Union) def handle_enum(self): - token = self._GetNextToken() - if not (token.token_type == tokenize.NAME and token.name == 'class'): - self._AddBackToken(token) return self._GetNestedType(Enum) def handle_auto(self): @@ -1298,7 +1319,8 @@ def handle_virtual(self): if token2.token_type == tokenize.SYNTAX and token2.name == '~': return self.GetMethod(FUNCTION_VIRTUAL + FUNCTION_DTOR, None) assert token.token_type == tokenize.NAME or token.name == '::', token - return_type_and_name = self._GetTokensUpTo(tokenize.SYNTAX, '(') # ) + return_type_and_name, _ = self._GetVarTokensUpToIgnoringTemplates( + tokenize.SYNTAX, '(') # ) return_type_and_name.insert(0, token) if token2 is not token: return_type_and_name.insert(1, token2) diff --git a/googlemock/scripts/generator/cpp/gmock_class.py b/googlemock/scripts/generator/cpp/gmock_class.py index f9966cbb4b..86dcedbfc7 100755 --- a/googlemock/scripts/generator/cpp/gmock_class.py +++ b/googlemock/scripts/generator/cpp/gmock_class.py @@ -1,18 +1,33 @@ #!/usr/bin/env python # -# Copyright 2008 Google Inc. All Rights Reserved. +# Copyright 2008, Google Inc. +# All rights reserved. # -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are +# met: # -# http://www.apache.org/licenses/LICENSE-2.0 +# * 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. # -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. +# 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. """Generate Google Mock classes from base classes. @@ -26,9 +41,6 @@ Output is sent to stdout. """ -__author__ = 'nnorwitz@google.com (Neal Norwitz)' - - import os import re import sys @@ -48,6 +60,50 @@ _INDENT = 2 +def _RenderType(ast_type): + """Renders the potentially recursively templated type into a string. + + Args: + ast_type: The AST of the type. + + Returns: + Rendered string and a boolean to indicate whether we have multiple args + (which is not handled correctly). + """ + has_multiarg_error = False + # Add modifiers like 'const'. + modifiers = '' + if ast_type.modifiers: + modifiers = ' '.join(ast_type.modifiers) + ' ' + return_type = modifiers + ast_type.name + if ast_type.templated_types: + # Collect template args. + template_args = [] + for arg in ast_type.templated_types: + rendered_arg, e = _RenderType(arg) + if e: has_multiarg_error = True + template_args.append(rendered_arg) + return_type += '<' + ', '.join(template_args) + '>' + # We are actually not handling multi-template-args correctly. So mark it. + if len(template_args) > 1: + has_multiarg_error = True + if ast_type.pointer: + return_type += '*' + if ast_type.reference: + return_type += '&' + return return_type, has_multiarg_error + + +def _GetNumParameters(parameters, source): + num_parameters = len(parameters) + if num_parameters == 1: + first_param = parameters[0] + if source[first_param.start:first_param.end].strip() == 'void': + # We must treat T(void) as a function with no parameters. + return 0 + return num_parameters + + def _GenerateMethods(output_lines, source, class_node): function_type = (ast.FUNCTION_VIRTUAL | ast.FUNCTION_PURE_VIRTUAL | ast.FUNCTION_OVERRIDE) @@ -63,32 +119,16 @@ def _GenerateMethods(output_lines, source, class_node): const = '' if node.modifiers & ast.FUNCTION_CONST: const = 'CONST_' + num_parameters = _GetNumParameters(node.parameters, source) return_type = 'void' if node.return_type: - # Add modifiers like 'const'. - modifiers = '' - if node.return_type.modifiers: - modifiers = ' '.join(node.return_type.modifiers) + ' ' - return_type = modifiers + node.return_type.name - template_args = [arg.name for arg in node.return_type.templated_types] - if template_args: - return_type += '<' + ', '.join(template_args) + '>' - if len(template_args) > 1: - for line in [ - '// The following line won\'t really compile, as the return', - '// type has multiple template arguments. To fix it, use a', - '// typedef for the return type.']: - output_lines.append(indent + line) - if node.return_type.pointer: - return_type += '*' - if node.return_type.reference: - return_type += '&' - num_parameters = len(node.parameters) - if len(node.parameters) == 1: - first_param = node.parameters[0] - if source[first_param.start:first_param.end].strip() == 'void': - # We must treat T(void) as a function with no parameters. - num_parameters = 0 + return_type, has_multiarg_error = _RenderType(node.return_type) + if has_multiarg_error: + for line in [ + '// The following line won\'t really compile, as the return', + '// type has multiple template arguments. To fix it, use a', + '// typedef for the return type.']: + output_lines.append(indent + line) tmpl = '' if class_node.templated_types: tmpl = '_T' diff --git a/googlemock/scripts/generator/cpp/gmock_class_test.py b/googlemock/scripts/generator/cpp/gmock_class_test.py index c53e60003e..0505162627 100755 --- a/googlemock/scripts/generator/cpp/gmock_class_test.py +++ b/googlemock/scripts/generator/cpp/gmock_class_test.py @@ -1,25 +1,36 @@ #!/usr/bin/env python # -# Copyright 2009 Neal Norwitz All Rights Reserved. -# Portions Copyright 2009 Google Inc. All Rights Reserved. +# Copyright 2009, Google Inc. +# All rights reserved. # -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are +# met: # -# http://www.apache.org/licenses/LICENSE-2.0 +# * 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. # -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. +# 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. """Tests for gmock.scripts.generator.cpp.gmock_class.""" -__author__ = 'nnorwitz@google.com (Neal Norwitz)' - - import os import sys import unittest @@ -444,19 +455,63 @@ class MockTest : public Test { self.assertEqualIgnoreLeadingWhitespace( expected, self.GenerateMocks(source)) - def testEnumClass(self): + def testEnumType(self): source = """ class Test { public: - enum class Baz { BAZINGA }; - virtual void Bar(const FooType& test_arg); + enum Bar { + BAZ, QUX, QUUX, QUUUX + }; + virtual void Foo(); }; """ expected = """\ class MockTest : public Test { public: -MOCK_METHOD1(Bar, -void(const FooType& test_arg)); +MOCK_METHOD0(Foo, +void()); +}; +""" + self.assertEqualIgnoreLeadingWhitespace( + expected, self.GenerateMocks(source)) + + def testEnumClassType(self): + source = """ +class Test { + public: + enum class Bar { + BAZ, QUX, QUUX, QUUUX + }; + virtual void Foo(); +}; +""" + expected = """\ +class MockTest : public Test { +public: +MOCK_METHOD0(Foo, +void()); +}; +""" + self.assertEqualIgnoreLeadingWhitespace( + expected, self.GenerateMocks(source)) + + def testStdFunction(self): + source = """ +class Test { + public: + Test(std::function foo) : foo_(foo) {} + + virtual std::function foo(); + + private: + std::function foo_; +}; +""" + expected = """\ +class MockTest : public Test { +public: +MOCK_METHOD0(foo, +std::function()); }; """ self.assertEqualIgnoreLeadingWhitespace( diff --git a/googlemock/scripts/generator/cpp/keywords.py b/googlemock/scripts/generator/cpp/keywords.py index f694450e37..8b75c2b47c 100755 --- a/googlemock/scripts/generator/cpp/keywords.py +++ b/googlemock/scripts/generator/cpp/keywords.py @@ -1,25 +1,36 @@ #!/usr/bin/env python # -# Copyright 2007 Neal Norwitz -# Portions Copyright 2007 Google Inc. +# Copyright 2007, Google Inc. +# All rights reserved. # -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are +# met: # -# http://www.apache.org/licenses/LICENSE-2.0 +# * 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. # -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. +# 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. """C++ keywords and helper utilities for determining keywords.""" -__author__ = 'nnorwitz@google.com (Neal Norwitz)' - - try: # Python 3.x import builtins diff --git a/googlemock/scripts/generator/cpp/tokenize.py b/googlemock/scripts/generator/cpp/tokenize.py index 359d5562d7..c64dcdee8b 100755 --- a/googlemock/scripts/generator/cpp/tokenize.py +++ b/googlemock/scripts/generator/cpp/tokenize.py @@ -1,25 +1,36 @@ #!/usr/bin/env python # -# Copyright 2007 Neal Norwitz -# Portions Copyright 2007 Google Inc. +# Copyright 2007, Google Inc. +# All rights reserved. # -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are +# met: # -# http://www.apache.org/licenses/LICENSE-2.0 +# * 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. # -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. +# 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. """Tokenize C++ source code.""" -__author__ = 'nnorwitz@google.com (Neal Norwitz)' - - try: # Python 3.x import builtins diff --git a/googlemock/scripts/generator/cpp/utils.py b/googlemock/scripts/generator/cpp/utils.py index eab36eec33..6945a78cc8 100755 --- a/googlemock/scripts/generator/cpp/utils.py +++ b/googlemock/scripts/generator/cpp/utils.py @@ -1,28 +1,38 @@ #!/usr/bin/env python # -# Copyright 2007 Neal Norwitz -# Portions Copyright 2007 Google Inc. +# Copyright 2007, Google Inc. +# All rights reserved. # -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are +# met: # -# http://www.apache.org/licenses/LICENSE-2.0 +# * 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. # -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. +# 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. """Generic utilities for C++ parsing.""" -__author__ = 'nnorwitz@google.com (Neal Norwitz)' - - import sys - # Set to True to see the start/end token indices. DEBUG = True diff --git a/googlemock/scripts/generator/gmock_gen.py b/googlemock/scripts/generator/gmock_gen.py index 8cc0d135d6..34a7f887f1 100755 --- a/googlemock/scripts/generator/gmock_gen.py +++ b/googlemock/scripts/generator/gmock_gen.py @@ -1,22 +1,36 @@ #!/usr/bin/env python # -# Copyright 2008 Google Inc. All Rights Reserved. +# Copyright 2008, Google Inc. +# All rights reserved. # -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are +# met: # -# http://www.apache.org/licenses/LICENSE-2.0 +# * 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. # -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. +# 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. """Driver for starting up Google Mock class generator.""" -__author__ = 'nnorwitz@google.com (Neal Norwitz)' import os import sys diff --git a/googlemock/scripts/gmock-config.in b/googlemock/scripts/gmock-config.in deleted file mode 100755 index 2baefe94d6..0000000000 --- a/googlemock/scripts/gmock-config.in +++ /dev/null @@ -1,303 +0,0 @@ -#!/bin/sh - -# These variables are automatically filled in by the configure script. -name="@PACKAGE_TARNAME@" -version="@PACKAGE_VERSION@" - -show_usage() -{ - echo "Usage: gmock-config [OPTIONS...]" -} - -show_help() -{ - show_usage - cat <<\EOF - -The `gmock-config' script provides access to the necessary compile and linking -flags to connect with Google C++ Mocking Framework, both in a build prior to -installation, and on the system proper after installation. The installation -overrides may be issued in combination with any other queries, but will only -affect installation queries if called on a built but not installed gmock. The -installation queries may not be issued with any other types of queries, and -only one installation query may be made at a time. The version queries and -compiler flag queries may be combined as desired but not mixed. Different -version queries are always combined with logical "and" semantics, and only the -last of any particular query is used while all previous ones ignored. All -versions must be specified as a sequence of numbers separated by periods. -Compiler flag queries output the union of the sets of flags when combined. - - Examples: - gmock-config --min-version=1.0 || echo "Insufficient Google Mock version." - - g++ $(gmock-config --cppflags --cxxflags) -o foo.o -c foo.cpp - g++ $(gmock-config --ldflags --libs) -o foo foo.o - - # When using a built but not installed Google Mock: - g++ $(../../my_gmock_build/scripts/gmock-config ...) ... - - # When using an installed Google Mock, but with installation overrides: - export GMOCK_PREFIX="/opt" - g++ $(gmock-config --libdir="/opt/lib64" ...) ... - - Help: - --usage brief usage information - --help display this help message - - Installation Overrides: - --prefix= overrides the installation prefix - --exec-prefix= overrides the executable installation prefix - --libdir= overrides the library installation prefix - --includedir= overrides the header file installation prefix - - Installation Queries: - --prefix installation prefix - --exec-prefix executable installation prefix - --libdir library installation directory - --includedir header file installation directory - --version the version of the Google Mock installation - - Version Queries: - --min-version=VERSION return 0 if the version is at least VERSION - --exact-version=VERSION return 0 if the version is exactly VERSION - --max-version=VERSION return 0 if the version is at most VERSION - - Compilation Flag Queries: - --cppflags compile flags specific to the C-like preprocessors - --cxxflags compile flags appropriate for C++ programs - --ldflags linker flags - --libs libraries for linking - -EOF -} - -# This function bounds our version with a min and a max. It uses some clever -# POSIX-compliant variable expansion to portably do all the work in the shell -# and avoid any dependency on a particular "sed" or "awk" implementation. -# Notable is that it will only ever compare the first 3 components of versions. -# Further components will be cleanly stripped off. All versions must be -# unadorned, so "v1.0" will *not* work. The minimum version must be in $1, and -# the max in $2. TODO(chandlerc@google.com): If this ever breaks, we should -# investigate expanding this via autom4te from AS_VERSION_COMPARE rather than -# continuing to maintain our own shell version. -check_versions() -{ - major_version=${version%%.*} - minor_version="0" - point_version="0" - if test "${version#*.}" != "${version}"; then - minor_version=${version#*.} - minor_version=${minor_version%%.*} - fi - if test "${version#*.*.}" != "${version}"; then - point_version=${version#*.*.} - point_version=${point_version%%.*} - fi - - min_version="$1" - min_major_version=${min_version%%.*} - min_minor_version="0" - min_point_version="0" - if test "${min_version#*.}" != "${min_version}"; then - min_minor_version=${min_version#*.} - min_minor_version=${min_minor_version%%.*} - fi - if test "${min_version#*.*.}" != "${min_version}"; then - min_point_version=${min_version#*.*.} - min_point_version=${min_point_version%%.*} - fi - - max_version="$2" - max_major_version=${max_version%%.*} - max_minor_version="0" - max_point_version="0" - if test "${max_version#*.}" != "${max_version}"; then - max_minor_version=${max_version#*.} - max_minor_version=${max_minor_version%%.*} - fi - if test "${max_version#*.*.}" != "${max_version}"; then - max_point_version=${max_version#*.*.} - max_point_version=${max_point_version%%.*} - fi - - test $(($major_version)) -lt $(($min_major_version)) && exit 1 - if test $(($major_version)) -eq $(($min_major_version)); then - test $(($minor_version)) -lt $(($min_minor_version)) && exit 1 - if test $(($minor_version)) -eq $(($min_minor_version)); then - test $(($point_version)) -lt $(($min_point_version)) && exit 1 - fi - fi - - test $(($major_version)) -gt $(($max_major_version)) && exit 1 - if test $(($major_version)) -eq $(($max_major_version)); then - test $(($minor_version)) -gt $(($max_minor_version)) && exit 1 - if test $(($minor_version)) -eq $(($max_minor_version)); then - test $(($point_version)) -gt $(($max_point_version)) && exit 1 - fi - fi - - exit 0 -} - -# Show the usage line when no arguments are specified. -if test $# -eq 0; then - show_usage - exit 1 -fi - -while test $# -gt 0; do - case $1 in - --usage) show_usage; exit 0;; - --help) show_help; exit 0;; - - # Installation overrides - --prefix=*) GMOCK_PREFIX=${1#--prefix=};; - --exec-prefix=*) GMOCK_EXEC_PREFIX=${1#--exec-prefix=};; - --libdir=*) GMOCK_LIBDIR=${1#--libdir=};; - --includedir=*) GMOCK_INCLUDEDIR=${1#--includedir=};; - - # Installation queries - --prefix|--exec-prefix|--libdir|--includedir|--version) - if test -n "${do_query}"; then - show_usage - exit 1 - fi - do_query=${1#--} - ;; - - # Version checking - --min-version=*) - do_check_versions=yes - min_version=${1#--min-version=} - ;; - --max-version=*) - do_check_versions=yes - max_version=${1#--max-version=} - ;; - --exact-version=*) - do_check_versions=yes - exact_version=${1#--exact-version=} - ;; - - # Compiler flag output - --cppflags) echo_cppflags=yes;; - --cxxflags) echo_cxxflags=yes;; - --ldflags) echo_ldflags=yes;; - --libs) echo_libs=yes;; - - # Everything else is an error - *) show_usage; exit 1;; - esac - shift -done - -# These have defaults filled in by the configure script but can also be -# overridden by environment variables or command line parameters. -prefix="${GMOCK_PREFIX:-@prefix@}" -exec_prefix="${GMOCK_EXEC_PREFIX:-@exec_prefix@}" -libdir="${GMOCK_LIBDIR:-@libdir@}" -includedir="${GMOCK_INCLUDEDIR:-@includedir@}" - -# We try and detect if our binary is not located at its installed location. If -# it's not, we provide variables pointing to the source and build tree rather -# than to the install tree. We also locate Google Test using the configured -# gtest-config script rather than searching the PATH and our bindir for one. -# This allows building against a just-built gmock rather than an installed -# gmock. -bindir="@bindir@" -this_relative_bindir=`dirname $0` -this_bindir=`cd ${this_relative_bindir}; pwd -P` -if test "${this_bindir}" = "${this_bindir%${bindir}}"; then - # The path to the script doesn't end in the bindir sequence from Autoconf, - # assume that we are in a build tree. - build_dir=`dirname ${this_bindir}` - src_dir=`cd ${this_bindir}/@top_srcdir@; pwd -P` - - # TODO(chandlerc@google.com): This is a dangerous dependency on libtool, we - # should work to remove it, and/or remove libtool altogether, replacing it - # with direct references to the library and a link path. - gmock_libs="${build_dir}/lib/libgmock.la" - gmock_ldflags="" - - # We provide hooks to include from either the source or build dir, where the - # build dir is always preferred. This will potentially allow us to write - # build rules for generated headers and have them automatically be preferred - # over provided versions. - gmock_cppflags="-I${build_dir}/include -I${src_dir}/include" - gmock_cxxflags="" - - # Directly invoke the gtest-config script used during the build process. - gtest_config="@GTEST_CONFIG@" -else - # We're using an installed gmock, although it may be staged under some - # prefix. Assume (as our own libraries do) that we can resolve the prefix, - # and are present in the dynamic link paths. - gmock_ldflags="-L${libdir}" - gmock_libs="-l${name}" - gmock_cppflags="-I${includedir}" - gmock_cxxflags="" - - # We also prefer any gtest-config script installed in our prefix. Lacking - # one, we look in the PATH for one. - gtest_config="${bindir}/gtest-config" - if test ! -x "${gtest_config}"; then - gtest_config=`which gtest-config` - fi -fi - -# Ensure that we have located a Google Test to link against. -if ! test -x "${gtest_config}"; then - echo "Unable to locate Google Test, check your Google Mock configuration" \ - "and installation" >&2 - exit 1 -elif ! "${gtest_config}" "--exact-version=@GTEST_VERSION@"; then - echo "The Google Test found is not the same version as Google Mock was " \ - "built against" >&2 - exit 1 -fi - -# Add the necessary Google Test bits into the various flag variables -gmock_cppflags="${gmock_cppflags} `${gtest_config} --cppflags`" -gmock_cxxflags="${gmock_cxxflags} `${gtest_config} --cxxflags`" -gmock_ldflags="${gmock_ldflags} `${gtest_config} --ldflags`" -gmock_libs="${gmock_libs} `${gtest_config} --libs`" - -# Do an installation query if requested. -if test -n "$do_query"; then - case $do_query in - prefix) echo $prefix; exit 0;; - exec-prefix) echo $exec_prefix; exit 0;; - libdir) echo $libdir; exit 0;; - includedir) echo $includedir; exit 0;; - version) echo $version; exit 0;; - *) show_usage; exit 1;; - esac -fi - -# Do a version check if requested. -if test "$do_check_versions" = "yes"; then - # Make sure we didn't receive a bad combination of parameters. - test "$echo_cppflags" = "yes" && show_usage && exit 1 - test "$echo_cxxflags" = "yes" && show_usage && exit 1 - test "$echo_ldflags" = "yes" && show_usage && exit 1 - test "$echo_libs" = "yes" && show_usage && exit 1 - - if test "$exact_version" != ""; then - check_versions $exact_version $exact_version - # unreachable - else - check_versions ${min_version:-0.0.0} ${max_version:-9999.9999.9999} - # unreachable - fi -fi - -# Do the output in the correct order so that these can be used in-line of -# a compiler invocation. -output="" -test "$echo_cppflags" = "yes" && output="$output $gmock_cppflags" -test "$echo_cxxflags" = "yes" && output="$output $gmock_cxxflags" -test "$echo_ldflags" = "yes" && output="$output $gmock_ldflags" -test "$echo_libs" = "yes" && output="$output $gmock_libs" -echo $output - -exit 0 diff --git a/googlemock/scripts/gmock_doctor.py b/googlemock/scripts/gmock_doctor.py deleted file mode 100755 index 74992bc744..0000000000 --- a/googlemock/scripts/gmock_doctor.py +++ /dev/null @@ -1,640 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2008, 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. - -"""Converts compiler's errors in code using Google Mock to plain English.""" - -__author__ = 'wan@google.com (Zhanyong Wan)' - -import re -import sys - -_VERSION = '1.0.3' - -_EMAIL = 'googlemock@googlegroups.com' - -_COMMON_GMOCK_SYMBOLS = [ - # Matchers - '_', - 'A', - 'AddressSatisfies', - 'AllOf', - 'An', - 'AnyOf', - 'ContainerEq', - 'Contains', - 'ContainsRegex', - 'DoubleEq', - 'ElementsAre', - 'ElementsAreArray', - 'EndsWith', - 'Eq', - 'Field', - 'FloatEq', - 'Ge', - 'Gt', - 'HasSubstr', - 'IsInitializedProto', - 'Le', - 'Lt', - 'MatcherCast', - 'Matches', - 'MatchesRegex', - 'NanSensitiveDoubleEq', - 'NanSensitiveFloatEq', - 'Ne', - 'Not', - 'NotNull', - 'Pointee', - 'Property', - 'Ref', - 'ResultOf', - 'SafeMatcherCast', - 'StartsWith', - 'StrCaseEq', - 'StrCaseNe', - 'StrEq', - 'StrNe', - 'Truly', - 'TypedEq', - 'Value', - - # Actions - 'Assign', - 'ByRef', - 'DeleteArg', - 'DoAll', - 'DoDefault', - 'IgnoreResult', - 'Invoke', - 'InvokeArgument', - 'InvokeWithoutArgs', - 'Return', - 'ReturnNew', - 'ReturnNull', - 'ReturnRef', - 'SaveArg', - 'SetArgReferee', - 'SetArgPointee', - 'SetArgumentPointee', - 'SetArrayArgument', - 'SetErrnoAndReturn', - 'Throw', - 'WithArg', - 'WithArgs', - 'WithoutArgs', - - # Cardinalities - 'AnyNumber', - 'AtLeast', - 'AtMost', - 'Between', - 'Exactly', - - # Sequences - 'InSequence', - 'Sequence', - - # Misc - 'DefaultValue', - 'Mock', - ] - -# Regex for matching source file path and line number in the compiler's errors. -_GCC_FILE_LINE_RE = r'(?P.*):(?P\d+):(\d+:)?\s+' -_CLANG_FILE_LINE_RE = r'(?P.*):(?P\d+):(?P\d+):\s+' -_CLANG_NON_GMOCK_FILE_LINE_RE = ( - r'(?P.*[/\\^](?!gmock-)[^/\\]+):(?P\d+):(?P\d+):\s+') - - -def _FindAllMatches(regex, s): - """Generates all matches of regex in string s.""" - - r = re.compile(regex) - return r.finditer(s) - - -def _GenericDiagnoser(short_name, long_name, diagnoses, msg): - """Diagnoses the given disease by pattern matching. - - Can provide different diagnoses for different patterns. - - Args: - short_name: Short name of the disease. - long_name: Long name of the disease. - diagnoses: A list of pairs (regex, pattern for formatting the diagnosis - for matching regex). - msg: Compiler's error messages. - Yields: - Tuples of the form - (short name of disease, long name of disease, diagnosis). - """ - for regex, diagnosis in diagnoses: - if re.search(regex, msg): - diagnosis = '%(file)s:%(line)s:' + diagnosis - for m in _FindAllMatches(regex, msg): - yield (short_name, long_name, diagnosis % m.groupdict()) - - -def _NeedToReturnReferenceDiagnoser(msg): - """Diagnoses the NRR disease, given the error messages by the compiler.""" - - gcc_regex = (r'In member function \'testing::internal::ReturnAction.*\n' - + _GCC_FILE_LINE_RE + r'instantiated from here\n' - r'.*gmock-actions\.h.*error: creating array with negative size') - clang_regex = (r'error:.*array.*negative.*\r?\n' - r'(.*\n)*?' + - _CLANG_NON_GMOCK_FILE_LINE_RE + - r'note: in instantiation of function template specialization ' - r'\'testing::internal::ReturnAction<(?P.*)>' - r'::operator Action<.*>\' requested here') - clang11_re = (r'use_ReturnRef_instead_of_Return_to_return_a_reference.*' - r'(.*\n)*?' + _CLANG_NON_GMOCK_FILE_LINE_RE) - - diagnosis = """ -You are using a Return() action in a function that returns a reference to -%(type)s. Please use ReturnRef() instead.""" - return _GenericDiagnoser('NRR', 'Need to Return Reference', - [(clang_regex, diagnosis), - (clang11_re, diagnosis % {'type': 'a type'}), - (gcc_regex, diagnosis % {'type': 'a type'})], - msg) - - -def _NeedToReturnSomethingDiagnoser(msg): - """Diagnoses the NRS disease, given the error messages by the compiler.""" - - gcc_regex = (_GCC_FILE_LINE_RE + r'(instantiated from here\n.' - r'*gmock.*actions\.h.*error: void value not ignored)' - r'|(error: control reaches end of non-void function)') - clang_regex1 = (_CLANG_FILE_LINE_RE + - r'error: cannot initialize return object ' - r'of type \'Result\' \(aka \'(?P.*)\'\) ' - r'with an rvalue of type \'void\'') - clang_regex2 = (_CLANG_FILE_LINE_RE + - r'error: cannot initialize return object ' - r'of type \'(?P.*)\' ' - r'with an rvalue of type \'void\'') - diagnosis = """ -You are using an action that returns void, but it needs to return -%(return_type)s. Please tell it *what* to return. Perhaps you can use -the pattern DoAll(some_action, Return(some_value))?""" - return _GenericDiagnoser( - 'NRS', - 'Need to Return Something', - [(gcc_regex, diagnosis % {'return_type': '*something*'}), - (clang_regex1, diagnosis), - (clang_regex2, diagnosis)], - msg) - - -def _NeedToReturnNothingDiagnoser(msg): - """Diagnoses the NRN disease, given the error messages by the compiler.""" - - gcc_regex = (_GCC_FILE_LINE_RE + r'instantiated from here\n' - r'.*gmock-actions\.h.*error: instantiation of ' - r'\'testing::internal::ReturnAction::Impl::value_\' ' - r'as type \'void\'') - clang_regex1 = (r'error: field has incomplete type ' - r'\'Result\' \(aka \'void\'\)(\r)?\n' - r'(.*\n)*?' + - _CLANG_NON_GMOCK_FILE_LINE_RE + r'note: in instantiation ' - r'of function template specialization ' - r'\'testing::internal::ReturnAction<(?P.*)>' - r'::operator Action\' requested here') - clang_regex2 = (r'error: field has incomplete type ' - r'\'Result\' \(aka \'void\'\)(\r)?\n' - r'(.*\n)*?' + - _CLANG_NON_GMOCK_FILE_LINE_RE + r'note: in instantiation ' - r'of function template specialization ' - r'\'testing::internal::DoBothAction<.*>' - r'::operator Action<(?P.*) \(.*\)>\' ' - r'requested here') - diagnosis = """ -You are using an action that returns %(return_type)s, but it needs to return -void. Please use a void-returning action instead. - -All actions but the last in DoAll(...) must return void. Perhaps you need -to re-arrange the order of actions in a DoAll(), if you are using one?""" - return _GenericDiagnoser( - 'NRN', - 'Need to Return Nothing', - [(gcc_regex, diagnosis % {'return_type': '*something*'}), - (clang_regex1, diagnosis), - (clang_regex2, diagnosis)], - msg) - - -def _IncompleteByReferenceArgumentDiagnoser(msg): - """Diagnoses the IBRA disease, given the error messages by the compiler.""" - - gcc_regex = (_GCC_FILE_LINE_RE + r'instantiated from here\n' - r'.*gtest-printers\.h.*error: invalid application of ' - r'\'sizeof\' to incomplete type \'(?P.*)\'') - - clang_regex = (r'.*gtest-printers\.h.*error: invalid application of ' - r'\'sizeof\' to an incomplete type ' - r'\'(?P.*)( const)?\'\r?\n' - r'(.*\n)*?' + - _CLANG_NON_GMOCK_FILE_LINE_RE + - r'note: in instantiation of member function ' - r'\'testing::internal2::TypeWithoutFormatter<.*>::' - r'PrintValue\' requested here') - diagnosis = """ -In order to mock this function, Google Mock needs to see the definition -of type "%(type)s" - declaration alone is not enough. Either #include -the header that defines it, or change the argument to be passed -by pointer.""" - - return _GenericDiagnoser('IBRA', 'Incomplete By-Reference Argument Type', - [(gcc_regex, diagnosis), - (clang_regex, diagnosis)], - msg) - - -def _OverloadedFunctionMatcherDiagnoser(msg): - """Diagnoses the OFM disease, given the error messages by the compiler.""" - - gcc_regex = (_GCC_FILE_LINE_RE + r'error: no matching function for ' - r'call to \'Truly\(\)') - clang_regex = (_CLANG_FILE_LINE_RE + r'error: no matching function for ' - r'call to \'Truly') - diagnosis = """ -The argument you gave to Truly() is an overloaded function. Please tell -your compiler which overloaded version you want to use. - -For example, if you want to use the version whose signature is - bool Foo(int n); -you should write - Truly(static_cast(Foo))""" - return _GenericDiagnoser('OFM', 'Overloaded Function Matcher', - [(gcc_regex, diagnosis), - (clang_regex, diagnosis)], - msg) - - -def _OverloadedFunctionActionDiagnoser(msg): - """Diagnoses the OFA disease, given the error messages by the compiler.""" - - gcc_regex = (_GCC_FILE_LINE_RE + r'error: no matching function for call to ' - r'\'Invoke\(') - clang_regex = (_CLANG_FILE_LINE_RE + r'error: no matching ' - r'function for call to \'Invoke\'\r?\n' - r'(.*\n)*?' - r'.*\bgmock-generated-actions\.h:\d+:\d+:\s+' - r'note: candidate template ignored:\s+' - r'couldn\'t infer template argument \'FunctionImpl\'') - diagnosis = """ -Function you are passing to Invoke is overloaded. Please tell your compiler -which overloaded version you want to use. - -For example, if you want to use the version whose signature is - bool MyFunction(int n, double x); -you should write something like - Invoke(static_cast(MyFunction))""" - return _GenericDiagnoser('OFA', 'Overloaded Function Action', - [(gcc_regex, diagnosis), - (clang_regex, diagnosis)], - msg) - - -def _OverloadedMethodActionDiagnoser(msg): - """Diagnoses the OMA disease, given the error messages by the compiler.""" - - gcc_regex = (_GCC_FILE_LINE_RE + r'error: no matching function for ' - r'call to \'Invoke\(.+, \)') - clang_regex = (_CLANG_FILE_LINE_RE + r'error: no matching function ' - r'for call to \'Invoke\'\r?\n' - r'(.*\n)*?' - r'.*\bgmock-generated-actions\.h:\d+:\d+: ' - r'note: candidate function template not viable: ' - r'requires .*, but 2 (arguments )?were provided') - diagnosis = """ -The second argument you gave to Invoke() is an overloaded method. Please -tell your compiler which overloaded version you want to use. - -For example, if you want to use the version whose signature is - class Foo { - ... - bool Bar(int n, double x); - }; -you should write something like - Invoke(foo, static_cast(&Foo::Bar))""" - return _GenericDiagnoser('OMA', 'Overloaded Method Action', - [(gcc_regex, diagnosis), - (clang_regex, diagnosis)], - msg) - - -def _MockObjectPointerDiagnoser(msg): - """Diagnoses the MOP disease, given the error messages by the compiler.""" - - gcc_regex = (_GCC_FILE_LINE_RE + r'error: request for member ' - r'\'gmock_(?P.+)\' in \'(?P.+)\', ' - r'which is of non-class type \'(.*::)*(?P.+)\*\'') - clang_regex = (_CLANG_FILE_LINE_RE + r'error: member reference type ' - r'\'(?P.*?) *\' is a pointer; ' - r'(did you mean|maybe you meant) to use \'->\'\?') - diagnosis = """ -The first argument to ON_CALL() and EXPECT_CALL() must be a mock *object*, -not a *pointer* to it. Please write '*(%(mock_object)s)' instead of -'%(mock_object)s' as your first argument. - -For example, given the mock class: - - class %(class_name)s : public ... { - ... - MOCK_METHOD0(%(method)s, ...); - }; - -and the following mock instance: - - %(class_name)s* mock_ptr = ... - -you should use the EXPECT_CALL like this: - - EXPECT_CALL(*mock_ptr, %(method)s(...));""" - - return _GenericDiagnoser( - 'MOP', - 'Mock Object Pointer', - [(gcc_regex, diagnosis), - (clang_regex, diagnosis % {'mock_object': 'mock_object', - 'method': 'method', - 'class_name': '%(class_name)s'})], - msg) - - -def _NeedToUseSymbolDiagnoser(msg): - """Diagnoses the NUS disease, given the error messages by the compiler.""" - - gcc_regex = (_GCC_FILE_LINE_RE + r'error: \'(?P.+)\' ' - r'(was not declared in this scope|has not been declared)') - clang_regex = (_CLANG_FILE_LINE_RE + - r'error: (use of undeclared identifier|unknown type name|' - r'no template named) \'(?P[^\']+)\'') - diagnosis = """ -'%(symbol)s' is defined by Google Mock in the testing namespace. -Did you forget to write - using testing::%(symbol)s; -?""" - for m in (list(_FindAllMatches(gcc_regex, msg)) + - list(_FindAllMatches(clang_regex, msg))): - symbol = m.groupdict()['symbol'] - if symbol in _COMMON_GMOCK_SYMBOLS: - yield ('NUS', 'Need to Use Symbol', diagnosis % m.groupdict()) - - -def _NeedToUseReturnNullDiagnoser(msg): - """Diagnoses the NRNULL disease, given the error messages by the compiler.""" - - gcc_regex = ('instantiated from \'testing::internal::ReturnAction' - '::operator testing::Action\(\) const.*\n' + - _GCC_FILE_LINE_RE + r'instantiated from here\n' - r'.*error: no matching function for call to \'ImplicitCast_\(' - r'(:?long )?int&\)') - clang_regex = (r'\bgmock-actions.h:.* error: no matching function for ' - r'call to \'ImplicitCast_\'\r?\n' - r'(.*\n)*?' + - _CLANG_NON_GMOCK_FILE_LINE_RE + r'note: in instantiation ' - r'of function template specialization ' - r'\'testing::internal::ReturnAction<(int|long)>::operator ' - r'Action<(?P.*)\(\)>\' requested here') - diagnosis = """ -You are probably calling Return(NULL) and the compiler isn't sure how to turn -NULL into %(type)s. Use ReturnNull() instead. -Note: the line number may be off; please fix all instances of Return(NULL).""" - return _GenericDiagnoser( - 'NRNULL', 'Need to use ReturnNull', - [(clang_regex, diagnosis), - (gcc_regex, diagnosis % {'type': 'the right type'})], - msg) - - -def _TypeInTemplatedBaseDiagnoser(msg): - """Diagnoses the TTB disease, given the error messages by the compiler.""" - - # This version works when the type is used as the mock function's return - # type. - gcc_4_3_1_regex_type_in_retval = ( - r'In member function \'int .*\n' + _GCC_FILE_LINE_RE + - r'error: a function call cannot appear in a constant-expression') - gcc_4_4_0_regex_type_in_retval = ( - r'error: a function call cannot appear in a constant-expression' - + _GCC_FILE_LINE_RE + r'error: template argument 1 is invalid\n') - # This version works when the type is used as the mock function's sole - # parameter type. - gcc_regex_type_of_sole_param = ( - _GCC_FILE_LINE_RE + - r'error: \'(?P.+)\' was not declared in this scope\n' - r'.*error: template argument 1 is invalid\n') - # This version works when the type is used as a parameter of a mock - # function that has multiple parameters. - gcc_regex_type_of_a_param = ( - r'error: expected `;\' before \'::\' token\n' - + _GCC_FILE_LINE_RE + - r'error: \'(?P.+)\' was not declared in this scope\n' - r'.*error: template argument 1 is invalid\n' - r'.*error: \'.+\' was not declared in this scope') - clang_regex_type_of_retval_or_sole_param = ( - _CLANG_FILE_LINE_RE + - r'error: use of undeclared identifier \'(?P.*)\'\n' - r'(.*\n)*?' - r'(?P=file):(?P=line):\d+: error: ' - r'non-friend class member \'Result\' cannot have a qualified name' - ) - clang_regex_type_of_a_param = ( - _CLANG_FILE_LINE_RE + - r'error: C\+\+ requires a type specifier for all declarations\n' - r'(.*\n)*?' - r'(?P=file):(?P=line):(?P=column): error: ' - r'C\+\+ requires a type specifier for all declarations' - ) - clang_regex_unknown_type = ( - _CLANG_FILE_LINE_RE + - r'error: unknown type name \'(?P[^\']+)\'' - ) - - diagnosis = """ -In a mock class template, types or typedefs defined in the base class -template are *not* automatically visible. This is how C++ works. Before -you can use a type or typedef named %(type)s defined in base class Base, you -need to make it visible. One way to do it is: - - typedef typename Base::%(type)s %(type)s;""" - - for diag in _GenericDiagnoser( - 'TTB', 'Type in Template Base', - [(gcc_4_3_1_regex_type_in_retval, diagnosis % {'type': 'Foo'}), - (gcc_4_4_0_regex_type_in_retval, diagnosis % {'type': 'Foo'}), - (gcc_regex_type_of_sole_param, diagnosis), - (gcc_regex_type_of_a_param, diagnosis), - (clang_regex_type_of_retval_or_sole_param, diagnosis), - (clang_regex_type_of_a_param, diagnosis % {'type': 'Foo'})], - msg): - yield diag - # Avoid overlap with the NUS pattern. - for m in _FindAllMatches(clang_regex_unknown_type, msg): - type_ = m.groupdict()['type'] - if type_ not in _COMMON_GMOCK_SYMBOLS: - yield ('TTB', 'Type in Template Base', diagnosis % m.groupdict()) - - -def _WrongMockMethodMacroDiagnoser(msg): - """Diagnoses the WMM disease, given the error messages by the compiler.""" - - gcc_regex = (_GCC_FILE_LINE_RE + - r'.*this_method_does_not_take_(?P\d+)_argument.*\n' - r'.*\n' - r'.*candidates are.*FunctionMocker<[^>]+A(?P\d+)\)>') - clang_regex = (_CLANG_NON_GMOCK_FILE_LINE_RE + - r'error:.*array.*negative.*r?\n' - r'(.*\n)*?' - r'(?P=file):(?P=line):(?P=column): error: too few arguments ' - r'to function call, expected (?P\d+), ' - r'have (?P\d+)') - clang11_re = (_CLANG_NON_GMOCK_FILE_LINE_RE + - r'.*this_method_does_not_take_' - r'(?P\d+)_argument.*') - diagnosis = """ -You are using MOCK_METHOD%(wrong_args)s to define a mock method that has -%(args)s arguments. Use MOCK_METHOD%(args)s (or MOCK_CONST_METHOD%(args)s, -MOCK_METHOD%(args)s_T, MOCK_CONST_METHOD%(args)s_T as appropriate) instead.""" - return _GenericDiagnoser('WMM', 'Wrong MOCK_METHODn Macro', - [(gcc_regex, diagnosis), - (clang11_re, diagnosis % {'wrong_args': 'm', - 'args': 'n'}), - (clang_regex, diagnosis)], - msg) - - -def _WrongParenPositionDiagnoser(msg): - """Diagnoses the WPP disease, given the error messages by the compiler.""" - - gcc_regex = (_GCC_FILE_LINE_RE + - r'error:.*testing::internal::MockSpec<.* has no member named \'' - r'(?P\w+)\'') - clang_regex = (_CLANG_NON_GMOCK_FILE_LINE_RE + - r'error: no member named \'(?P\w+)\' in ' - r'\'testing::internal::MockSpec<.*>\'') - diagnosis = """ -The closing parenthesis of ON_CALL or EXPECT_CALL should be *before* -".%(method)s". For example, you should write: - EXPECT_CALL(my_mock, Foo(_)).%(method)s(...); -instead of: - EXPECT_CALL(my_mock, Foo(_).%(method)s(...));""" - return _GenericDiagnoser('WPP', 'Wrong Parenthesis Position', - [(gcc_regex, diagnosis), - (clang_regex, diagnosis)], - msg) - - -_DIAGNOSERS = [ - _IncompleteByReferenceArgumentDiagnoser, - _MockObjectPointerDiagnoser, - _NeedToReturnNothingDiagnoser, - _NeedToReturnReferenceDiagnoser, - _NeedToReturnSomethingDiagnoser, - _NeedToUseReturnNullDiagnoser, - _NeedToUseSymbolDiagnoser, - _OverloadedFunctionActionDiagnoser, - _OverloadedFunctionMatcherDiagnoser, - _OverloadedMethodActionDiagnoser, - _TypeInTemplatedBaseDiagnoser, - _WrongMockMethodMacroDiagnoser, - _WrongParenPositionDiagnoser, - ] - - -def Diagnose(msg): - """Generates all possible diagnoses given the compiler error message.""" - - msg = re.sub(r'\x1b\[[^m]*m', '', msg) # Strips all color formatting. - # Assuming the string is using the UTF-8 encoding, replaces the left and - # the right single quote characters with apostrophes. - msg = re.sub(r'(\xe2\x80\x98|\xe2\x80\x99)', "'", msg) - - diagnoses = [] - for diagnoser in _DIAGNOSERS: - for diag in diagnoser(msg): - diagnosis = '[%s - %s]\n%s' % diag - if not diagnosis in diagnoses: - diagnoses.append(diagnosis) - return diagnoses - - -def main(): - print ('Google Mock Doctor v%s - ' - 'diagnoses problems in code using Google Mock.' % _VERSION) - - if sys.stdin.isatty(): - print ('Please copy and paste the compiler errors here. Press c-D when ' - 'you are done:') - else: - print ('Waiting for compiler errors on stdin . . .') - - msg = sys.stdin.read().strip() - diagnoses = Diagnose(msg) - count = len(diagnoses) - if not count: - print (""" -Your compiler complained: -8<------------------------------------------------------------ -%s ------------------------------------------------------------->8 - -Uh-oh, I'm not smart enough to figure out what the problem is. :-( -However... -If you send your source code and the compiler's error messages to -%s, you can be helped and I can get smarter -- -win-win for us!""" % (msg, _EMAIL)) - else: - print ('------------------------------------------------------------') - print ('Your code appears to have the following',) - if count > 1: - print ('%s diseases:' % (count,)) - else: - print ('disease:') - i = 0 - for d in diagnoses: - i += 1 - if count > 1: - print ('\n#%s:' % (i,)) - print (d) - print (""" -How did I do? If you think I'm wrong or unhelpful, please send your -source code and the compiler's error messages to %s. -Then you can be helped and I can get smarter -- I promise I won't be upset!""" % - _EMAIL) - - -if __name__ == '__main__': - main() diff --git a/googlemock/scripts/upload.py b/googlemock/scripts/upload.py index 95239dc2cb..129f53ef96 100755 --- a/googlemock/scripts/upload.py +++ b/googlemock/scripts/upload.py @@ -1,18 +1,33 @@ #!/usr/bin/env python # -# Copyright 2007 Google Inc. +# Copyright 2009, Google Inc. +# All rights reserved. # -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are +# met: # -# http://www.apache.org/licenses/LICENSE-2.0 +# * 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. # -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. +# 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. """Tool for uploading diffs from a version control system to the codereview app. diff --git a/googlemock/test/gmock-actions_test.cc b/googlemock/test/gmock-actions_test.cc index f63c8c5af9..dcce111a0d 100644 --- a/googlemock/test/gmock-actions_test.cc +++ b/googlemock/test/gmock-actions_test.cc @@ -73,6 +73,7 @@ using testing::Return; using testing::ReturnNull; using testing::ReturnRef; using testing::ReturnRefOfCopy; +using testing::ReturnRoundRobin; using testing::SetArgPointee; using testing::SetArgumentPointee; using testing::Unused; @@ -670,6 +671,31 @@ TEST(ReturnRefOfCopyTest, IsCovariant) { EXPECT_NE(&derived, &a.Perform(std::make_tuple())); } +// Tests that ReturnRoundRobin(v) works with initializer lists +TEST(ReturnRoundRobinTest, WorksForInitList) { + Action ret = ReturnRoundRobin({1, 2, 3}); + + EXPECT_EQ(1, ret.Perform(std::make_tuple())); + EXPECT_EQ(2, ret.Perform(std::make_tuple())); + EXPECT_EQ(3, ret.Perform(std::make_tuple())); + EXPECT_EQ(1, ret.Perform(std::make_tuple())); + EXPECT_EQ(2, ret.Perform(std::make_tuple())); + EXPECT_EQ(3, ret.Perform(std::make_tuple())); +} + +// Tests that ReturnRoundRobin(v) works with vectors +TEST(ReturnRoundRobinTest, WorksForVector) { + std::vector v = {4.4, 5.5, 6.6}; + Action ret = ReturnRoundRobin(v); + + EXPECT_EQ(4.4, ret.Perform(std::make_tuple())); + EXPECT_EQ(5.5, ret.Perform(std::make_tuple())); + EXPECT_EQ(6.6, ret.Perform(std::make_tuple())); + EXPECT_EQ(4.4, ret.Perform(std::make_tuple())); + EXPECT_EQ(5.5, ret.Perform(std::make_tuple())); + EXPECT_EQ(6.6, ret.Perform(std::make_tuple())); +} + // Tests that DoDefault() does the default action for the mock method. class MockClass { diff --git a/googletest/scripts/README.md b/googletest/scripts/README.md new file mode 100644 index 0000000000..fa359fed92 --- /dev/null +++ b/googletest/scripts/README.md @@ -0,0 +1,5 @@ +# Please Note: + +Files in this directory are no longer supported by the maintainers. They +represent mosty historical artifacts and supported by the community only. There +is no guarantee whatsoever that these scripts still work. diff --git a/googletest/scripts/gen_gtest_pred_impl.py b/googletest/scripts/gen_gtest_pred_impl.py index b43efdf41e..72942779cc 100755 --- a/googletest/scripts/gen_gtest_pred_impl.py +++ b/googletest/scripts/gen_gtest_pred_impl.py @@ -111,6 +111,8 @@ def HeaderPreamble(n): // '%(command)s'. DO NOT EDIT BY HAND! // // Implements a family of generic predicate assertion macros. +// GOOGLETEST_CM0001 DO NOT DELETE + #ifndef GTEST_INCLUDE_GTEST_GTEST_PRED_IMPL_H_ #define GTEST_INCLUDE_GTEST_GTEST_PRED_IMPL_H_ @@ -246,8 +248,10 @@ def ImplementationForArity(n): impl += ' << ") evaluates to false, where"' - impl += Iter(n, """ - << "\\n" << e%s << " evaluates to " << v%s""") + impl += Iter( + n, """ + << "\\n" << e%s << " evaluates to " << ::testing::PrintToString(v%s)""" + ) impl += """; } @@ -510,7 +514,7 @@ def TestsForArity(n): class Predicate%(n)sTest : public testing::Test { protected: - virtual void SetUp() { + void SetUp() override { expected_to_finish_ = true; finished_ = false;""" % DEFS @@ -520,7 +524,7 @@ class Predicate%(n)sTest : public testing::Test { """ tests += """ - virtual void TearDown() { + void TearDown() override { // Verifies that each of the predicate's arguments was evaluated // exactly once.""" @@ -588,7 +592,7 @@ def GenTest(use_format, use_assert, expect_failure, if use_assert: assrt = 'ASSERT' # 'assert' is reserved, so we cannot use - # that identifier here. + # that identifier here. else: assrt = 'EXPECT' diff --git a/googletest/scripts/pump.py b/googletest/scripts/pump.py index 5efb653c20..66e321700c 100755 --- a/googletest/scripts/pump.py +++ b/googletest/scripts/pump.py @@ -1,4 +1,4 @@ -#!/usr/bin/env python +#!/usr/bin/env python2.7 # # Copyright 2008, Google Inc. # All rights reserved. @@ -62,7 +62,7 @@ EXPRESSION has Python syntax. """ -__author__ = 'wan@google.com (Zhanyong Wan)' +from __future__ import print_function import os import re @@ -246,7 +246,7 @@ def ParseToken(lines, pos, regex, token_type): if m and not m.start(): return MakeToken(lines, pos, pos + m.end(), token_type) else: - print 'ERROR: %s expected at %s.' % (token_type, pos) + print('ERROR: %s expected at %s.' % (token_type, pos)) sys.exit(1) @@ -453,8 +453,8 @@ def PushFront(a_list, elem): def PopToken(a_list, token_type=None): token = PopFront(a_list) if token_type is not None and token.token_type != token_type: - print 'ERROR: %s expected at %s' % (token_type, token.start) - print 'ERROR: %s found instead' % (token,) + print('ERROR: %s expected at %s' % (token_type, token.start)) + print('ERROR: %s found instead' % (token,)) sys.exit(1) return token @@ -616,16 +616,16 @@ def GetValue(self, identifier): if identifier == var: return value - print 'ERROR: meta variable %s is undefined.' % (identifier,) + print('ERROR: meta variable %s is undefined.' % (identifier,)) sys.exit(1) def EvalExp(self, exp): try: result = eval(exp.python_exp) - except Exception, e: - print 'ERROR: caught exception %s: %s' % (e.__class__.__name__, e) - print ('ERROR: failed to evaluate meta expression %s at %s' % - (exp.python_exp, exp.token.start)) + except Exception as e: # pylint: disable=broad-except + print('ERROR: caught exception %s: %s' % (e.__class__.__name__, e)) + print('ERROR: failed to evaluate meta expression %s at %s' % + (exp.python_exp, exp.token.start)) sys.exit(1) return result @@ -634,7 +634,7 @@ def GetRange(self, identifier): if identifier == var: return (lower, upper) - print 'ERROR: range %s is undefined.' % (identifier,) + print('ERROR: range %s is undefined.' % (identifier,)) sys.exit(1) @@ -694,8 +694,8 @@ def RunAtomicCode(env, node, output): elif isinstance(node, CodeNode): RunCode(env.Clone(), node, output) else: - print 'BAD' - print node + print('BAD') + print(node) sys.exit(1) @@ -830,7 +830,7 @@ def ConvertFromPumpSource(src_text): def main(argv): if len(argv) == 1: - print __doc__ + print(__doc__) sys.exit(1) file_path = argv[-1] @@ -840,7 +840,7 @@ def main(argv): else: output_file_path = '-' if output_file_path == '-': - print output_str, + print(output_str,) else: output_file = file(output_file_path, 'w') output_file.write('// This file was GENERATED by command:\n') diff --git a/googletest/scripts/run_with_path.py b/googletest/scripts/run_with_path.py new file mode 100755 index 0000000000..d46ab4d34a --- /dev/null +++ b/googletest/scripts/run_with_path.py @@ -0,0 +1,32 @@ +#!/usr/bin/env python +# +# Copyright 2010 Google Inc. All Rights Reserved. + +"""Runs program specified in the command line with the substituted PATH. + + This script is needed for to support building under Pulse which is unable + to override the existing PATH variable. +""" + +import os +import subprocess +import sys + +SUBST_PATH_ENV_VAR_NAME = "SUBST_PATH" + +def main(): + if SUBST_PATH_ENV_VAR_NAME in os.environ: + os.environ["PATH"] = os.environ[SUBST_PATH_ENV_VAR_NAME] + + exit_code = subprocess.Popen(sys.argv[1:]).wait() + + # exit_code is negative (-signal) if the process has been terminated by + # a signal. Returning negative exit code is not portable and so we return + # 100 instead. + if exit_code < 0: + exit_code = 100 + + sys.exit(exit_code) + +if __name__ == "__main__": + main() diff --git a/googletest/scripts/upload.py b/googletest/scripts/upload.py index c852e4c91e..eba571142f 100755 --- a/googletest/scripts/upload.py +++ b/googletest/scripts/upload.py @@ -1,18 +1,33 @@ #!/usr/bin/env python # -# Copyright 2007 Google Inc. +# Copyright 2007, Google Inc. +# All rights reserved. # -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are +# met: # -# http://www.apache.org/licenses/LICENSE-2.0 +# * 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. # -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. +# 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. """Tool for uploading diffs from a version control system to the codereview app. From 6e87238c9b14bcd749364e9b7125622a985a8a20 Mon Sep 17 00:00:00 2001 From: Krystian Kuzniarek Date: Tue, 10 Sep 2019 12:20:09 +0200 Subject: [PATCH 056/541] remove BiggestInt --- googletest/include/gtest/gtest-printers.h | 16 ++++++------ googletest/include/gtest/gtest.h | 25 ++++++++----------- .../include/gtest/internal/gtest-port.h | 14 ----------- googletest/src/gtest.cc | 8 +++--- googletest/test/googletest-printers-test.cc | 16 ++++++------ googletest/test/gtest_unittest.cc | 6 ++--- 6 files changed, 34 insertions(+), 51 deletions(-) diff --git a/googletest/include/gtest/gtest-printers.h b/googletest/include/gtest/gtest-printers.h index 56a05450ef..74fc54b48a 100644 --- a/googletest/include/gtest/gtest-printers.h +++ b/googletest/include/gtest/gtest-printers.h @@ -133,7 +133,7 @@ GTEST_API_ void PrintBytesInObjectTo(const unsigned char* obj_bytes, // nor PrintTo(). enum TypeKind { kProtobuf, // a protobuf type - kConvertibleToInteger, // a type implicitly convertible to BiggestInt + kConvertibleToInteger, // a type implicitly convertible to std::intmax_t // (e.g. a named or unnamed enum type) #if GTEST_HAS_ABSL kConvertibleToStringView, // a type implicitly convertible to @@ -179,14 +179,14 @@ template class TypeWithoutFormatter { public: // Since T has no << operator or PrintTo() but can be implicitly - // converted to BiggestInt, we print it as a BiggestInt. + // converted to the maximum width integer, we print it as a std::intmax_t. // // Most likely T is an enum type (either named or unnamed), in which - // case printing it as an integer is the desired behavior. In case + // case printing it as an integer is the desired behavior. In case // T is not an enum, printing it as an integer is the best we can do // given that it has no user-defined printer. static void PrintValue(const T& value, ::std::ostream* os) { - const internal::BiggestInt kBigInt = value; + const std::intmax_t kBigInt = value; *os << kBigInt; } }; @@ -204,10 +204,10 @@ class TypeWithoutFormatter { }; #endif -// Prints the given value to the given ostream. If the value is a +// Prints the given value to the given ostream. If the value is a // protocol message, its debug string is printed; if it's an enum or -// of a type implicitly convertible to BiggestInt, it's printed as an -// integer; otherwise the bytes in the value are printed. This is +// of a type implicitly convertible to std::intmax_t, it's printed as an +// integer; otherwise the bytes in the value are printed. This is // what UniversalPrinter::Print() does when it knows nothing about // type T and T has neither << operator nor PrintTo(). // @@ -234,7 +234,7 @@ ::std::basic_ostream& operator<<( TypeWithoutFormatter::value ? kProtobuf : std::is_convertible< - const T&, internal::BiggestInt>::value + const T&, std::intmax_t>::value ? kConvertibleToInteger : #if GTEST_HAS_ABSL diff --git a/googletest/include/gtest/gtest.h b/googletest/include/gtest/gtest.h index dfe7c7869b..6c38043aa9 100644 --- a/googletest/include/gtest/gtest.h +++ b/googletest/include/gtest/gtest.h @@ -1530,13 +1530,12 @@ AssertionResult CmpHelperEQ(const char* lhs_expression, return CmpHelperEQFailure(lhs_expression, rhs_expression, lhs, rhs); } -// With this overloaded version, we allow anonymous enums to be used -// in {ASSERT|EXPECT}_EQ when compiled with gcc 4, as anonymous enums -// can be implicitly cast to BiggestInt. +// With this overloaded version, we allow anonymous enums to be used in +// {ASSERT|EXPECT}_EQ as anonymous enums can be implicitly cast to integers. GTEST_API_ AssertionResult CmpHelperEQ(const char* lhs_expression, const char* rhs_expression, - BiggestInt lhs, - BiggestInt rhs); + std::intmax_t lhs, + std::intmax_t rhs); class EqHelper { public: @@ -1553,16 +1552,15 @@ class EqHelper { return CmpHelperEQ(lhs_expression, rhs_expression, lhs, rhs); } - // With this overloaded version, we allow anonymous enums to be used - // in {ASSERT|EXPECT}_EQ when compiled with gcc 4, as anonymous - // enums can be implicitly cast to BiggestInt. + // With this overloaded version, we allow anonymous enums to be used in + // {ASSERT|EXPECT}_EQ as anonymous enums can be implicitly cast to integers. // // Even though its body looks the same as the above version, we // cannot merge the two, as it will make anonymous enums unhappy. static AssertionResult Compare(const char* lhs_expression, const char* rhs_expression, - BiggestInt lhs, - BiggestInt rhs) { + std::intmax_t lhs, + std::intmax_t rhs) { return CmpHelperEQ(lhs_expression, rhs_expression, lhs, rhs); } @@ -1595,9 +1593,8 @@ AssertionResult CmpHelperOpFailure(const char* expr1, const char* expr2, // of similar code. // // For each templatized helper function, we also define an overloaded -// version for BiggestInt in order to reduce code bloat and allow -// anonymous enums to be used with {ASSERT|EXPECT}_?? when compiled -// with gcc 4. +// version for std::intmax_t in order to reduce code bloat and allow +// anonymous enums to be used with {ASSERT|EXPECT}_??. // // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM. @@ -1612,7 +1609,7 @@ AssertionResult CmpHelper##op_name(const char* expr1, const char* expr2, \ }\ }\ GTEST_API_ AssertionResult CmpHelper##op_name(\ - const char* expr1, const char* expr2, BiggestInt val1, BiggestInt val2) + const char* expr1, const char* expr2, std::intmax_t val1, std::intmax_t val2) // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM. diff --git a/googletest/include/gtest/internal/gtest-port.h b/googletest/include/gtest/internal/gtest-port.h index 830aa1918d..daa8151893 100644 --- a/googletest/include/gtest/internal/gtest-port.h +++ b/googletest/include/gtest/internal/gtest-port.h @@ -225,7 +225,6 @@ // TypeWithSize - maps an integer to a int type. // Int32, UInt32, Int64, UInt64, TimeInMillis // - integers of known sizes. -// BiggestInt - the biggest signed integer type. // // Command-line utilities: // GTEST_DECLARE_*() - declares a flag. @@ -1899,12 +1898,9 @@ using bool_constant = std::integral_constant; #if GTEST_OS_WINDOWS # define GTEST_PATH_SEP_ "\\" # define GTEST_HAS_ALT_PATH_SEP_ 1 -// The biggest signed integer type the compiler supports. -typedef __int64 BiggestInt; #else # define GTEST_PATH_SEP_ "/" # define GTEST_HAS_ALT_PATH_SEP_ 0 -typedef long long BiggestInt; // NOLINT #endif // GTEST_OS_WINDOWS // Utilities for char. @@ -2094,16 +2090,6 @@ GTEST_DISABLE_MSC_DEPRECATED_POP_() # define GTEST_SNPRINTF_ snprintf #endif -// The maximum number a BiggestInt can represent. This definition -// works no matter BiggestInt is represented in one's complement or -// two's complement. -// -// We cannot rely on numeric_limits in STL, as __int64 and long long -// are not part of standard C++ and numeric_limits doesn't need to be -// defined for them. -const BiggestInt kMaxBiggestInt = - ~(static_cast(1) << (8*sizeof(BiggestInt) - 1)); - // This template class serves as a compile-time function from size to // type. It maps a size in bytes to a primitive type with that // size. e.g. diff --git a/googletest/src/gtest.cc b/googletest/src/gtest.cc index 0d1f4136ce..8f3301ccbc 100644 --- a/googletest/src/gtest.cc +++ b/googletest/src/gtest.cc @@ -1449,8 +1449,8 @@ namespace internal { // arguments. AssertionResult CmpHelperEQ(const char* lhs_expression, const char* rhs_expression, - BiggestInt lhs, - BiggestInt rhs) { + std::intmax_t lhs, + std::intmax_t rhs) { if (lhs == rhs) { return AssertionSuccess(); } @@ -1463,11 +1463,11 @@ AssertionResult CmpHelperEQ(const char* lhs_expression, } // A macro for implementing the helper functions needed to implement -// ASSERT_?? and EXPECT_?? with integer or enum arguments. It is here +// ASSERT_?? and EXPECT_?? with integer or enum arguments. It is here // just to avoid copy-and-paste of similar code. #define GTEST_IMPL_CMP_HELPER_(op_name, op)\ AssertionResult CmpHelper##op_name(const char* expr1, const char* expr2, \ - BiggestInt val1, BiggestInt val2) {\ + std::intmax_t val1, std::intmax_t val2) {\ if (val1 op val2) {\ return AssertionSuccess();\ } else {\ diff --git a/googletest/test/googletest-printers-test.cc b/googletest/test/googletest-printers-test.cc index 4bdc9adde9..06eedbda24 100644 --- a/googletest/test/googletest-printers-test.cc +++ b/googletest/test/googletest-printers-test.cc @@ -83,10 +83,10 @@ void PrintTo(EnumWithPrintTo e, std::ostream* os) { *os << (e == kEWPT1 ? "kEWPT1" : "invalid"); } -// A class implicitly convertible to BiggestInt. -class BiggestIntConvertible { +// A class implicitly convertible to std::intmax_t. +class IntMaxConvertible { public: - operator ::testing::internal::BiggestInt() const { return 42; } + constexpr operator std::intmax_t() const { return 42; } }; // A user-defined unprintable class template in the global namespace. @@ -268,10 +268,10 @@ TEST(PrintEnumTest, EnumWithPrintTo) { EXPECT_EQ("invalid", Print(static_cast(0))); } -// Tests printing a class implicitly convertible to BiggestInt. +// Tests printing a class implicitly convertible to std::intmax_t. -TEST(PrintClassTest, BiggestIntConvertible) { - EXPECT_EQ("42", Print(BiggestIntConvertible())); +TEST(PrintClassTest, IntMaxConvertible) { + EXPECT_EQ("42", Print(IntMaxConvertible())); } // Tests printing various char types. @@ -528,7 +528,7 @@ TEST(PrintPointerTest, NonMemberFunctionPointer) { // this limitation. EXPECT_EQ( PrintPointer(reinterpret_cast( - reinterpret_cast(&MyFunction))), + reinterpret_cast(&MyFunction))), Print(&MyFunction)); int (*p)(bool) = NULL; // NOLINT EXPECT_EQ("NULL", Print(p)); @@ -1122,7 +1122,7 @@ TEST(PrintReferenceTest, HandlesFunctionPointer) { // pointers to objects, and some compilers (e.g. GCC 3.4) enforce // this limitation. const std::string fp_string = PrintPointer(reinterpret_cast( - reinterpret_cast(fp))); + reinterpret_cast(fp))); EXPECT_EQ("@" + fp_pointer_string + " " + fp_string, PrintByRef(fp)); } diff --git a/googletest/test/gtest_unittest.cc b/googletest/test/gtest_unittest.cc index 12c5a87142..d90fee910f 100644 --- a/googletest/test/gtest_unittest.cc +++ b/googletest/test/gtest_unittest.cc @@ -55,11 +55,11 @@ TEST(CommandLineFlagsTest, CanBeAccessedInCodeOnceGTestHIsIncluded) { EXPECT_TRUE(dummy || !dummy); // Suppresses warning that dummy is unused. } -#include // For INT_MAX. #include #include #include +#include #include #include #include @@ -3953,11 +3953,11 @@ enum { // On Linux, kCaseB and kCaseA have the same value when truncated to // int size. We want to test whether this will confuse the // assertions. - kCaseB = testing::internal::kMaxBiggestInt, + kCaseB = std::numeric_limits::max(), # else - kCaseB = INT_MAX, + kCaseB = std::numeric_limits::max(), # endif // GTEST_OS_LINUX From d072682119f8673e090e2985f2cb5eb6a7b09fe0 Mon Sep 17 00:00:00 2001 From: Piotr Nycz Date: Thu, 24 Oct 2019 10:22:09 +0200 Subject: [PATCH 057/541] Tests simplified and names corrected (POD->scalar) Issue 2527 --- googlemock/test/gmock-actions_test.cc | 67 +++++++-------------------- 1 file changed, 18 insertions(+), 49 deletions(-) diff --git a/googlemock/test/gmock-actions_test.cc b/googlemock/test/gmock-actions_test.cc index 86f570fa41..52f140d112 100644 --- a/googlemock/test/gmock-actions_test.cc +++ b/googlemock/test/gmock-actions_test.cc @@ -651,65 +651,34 @@ template ()))> bool CanCallReturnRef(T&&) { return true; } bool CanCallReturnRef(Unused) { return false; } -// Defined here, because gmock has to work with C++11 (std::void_t is from C++17) -template struct precpp17_make_void { typedef void type;}; -template using precpp17_void_t = typename precpp17_make_void::type; - -template -struct HasReturnRefAction : std::false_type {}; -template -struct HasReturnRefAction()))>> - : std::true_type {}; - -// Just an example of non-POD type -class MyNonPodType { - public: - MyNonPodType(int a_value) : value_(a_value) {} - - private: - int value_; -}; -// Just an example of POD type -using MyPodType = int; - // Tests that ReturnRef(v) is working with non-temporaries (T&) -TEST(ReturnRefTest, IsAcceptingNonTemporary) { - EXPECT_TRUE(HasReturnRefAction::value); - EXPECT_TRUE(HasReturnRefAction::value); - EXPECT_TRUE(HasReturnRefAction::value); - EXPECT_TRUE(HasReturnRefAction::value); +TEST(ReturnRefTest, WorksForNonTemporary) { + int scalarValue = 123; + EXPECT_TRUE(CanCallReturnRef(scalarValue)); - MyNonPodType nonPodValue{123}; - EXPECT_TRUE(CanCallReturnRef(nonPodValue)); + std::string nonScalarValue("ABC"); + EXPECT_TRUE(CanCallReturnRef(nonScalarValue)); - MyPodType podValue{321}; - EXPECT_TRUE(CanCallReturnRef(podValue)); + const int constScalarValue{321}; + EXPECT_TRUE(CanCallReturnRef(constScalarValue)); - const MyNonPodType constNonPodValue{123}; - EXPECT_TRUE(CanCallReturnRef(constNonPodValue)); - - const MyPodType constPodValue{321}; - EXPECT_TRUE(CanCallReturnRef(constPodValue)); + const std::string constNonScalarValue("CBA"); + EXPECT_TRUE(CanCallReturnRef(constNonScalarValue)); } // Tests that ReturnRef(v) is not working with temporaries (T&&) -TEST(ReturnRefTest, IsNotAcceptingTemporary) { - EXPECT_FALSE(HasReturnRefAction::value); - EXPECT_FALSE(HasReturnRefAction::value); - EXPECT_FALSE(HasReturnRefAction::value); - EXPECT_FALSE(HasReturnRefAction::value); - - auto nonPodValue = []() -> MyNonPodType { return MyNonPodType{123}; }; - EXPECT_FALSE(CanCallReturnRef(nonPodValue())); +TEST(ReturnRefTest, DoesNotWorkForTemporary) { + auto scalarValue = []() -> int { return 123; }; + EXPECT_FALSE(CanCallReturnRef(scalarValue())); - auto podValue = []() -> MyPodType { return MyPodType{321}; }; - EXPECT_FALSE(CanCallReturnRef(podValue())); + auto nonScalarValue = []() -> std::string { return "ABC"; }; + EXPECT_FALSE(CanCallReturnRef(nonScalarValue())); - auto constNonPodValue = []() -> const MyNonPodType { return MyNonPodType{123}; }; - EXPECT_FALSE(CanCallReturnRef(constNonPodValue())); + // cannot use here callable returning "const scalar type" because C++ ignores such const for scalar return type, so the static_cast + EXPECT_FALSE(CanCallReturnRef(static_cast(321))); - // cannot use here callable returning "const POD" because C++ ignores such const for POD return type, so the static_cast - EXPECT_FALSE(CanCallReturnRef(static_cast(42))); + auto constNonScalarValue = []() -> const std::string { return "CBA"; }; + EXPECT_FALSE(CanCallReturnRef(constNonScalarValue())); } // Tests that ReturnRefOfCopy(v) works for reference types. From 5ff72f5295f315a23f83ce4cc86380d5bfed0787 Mon Sep 17 00:00:00 2001 From: Piotr Nycz Date: Fri, 25 Oct 2019 10:29:15 +0200 Subject: [PATCH 058/541] Apply 80chars limit Issue 2527 --- googlemock/test/gmock-actions_test.cc | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/googlemock/test/gmock-actions_test.cc b/googlemock/test/gmock-actions_test.cc index 52f140d112..e3c1d6cbfe 100644 --- a/googlemock/test/gmock-actions_test.cc +++ b/googlemock/test/gmock-actions_test.cc @@ -674,7 +674,8 @@ TEST(ReturnRefTest, DoesNotWorkForTemporary) { auto nonScalarValue = []() -> std::string { return "ABC"; }; EXPECT_FALSE(CanCallReturnRef(nonScalarValue())); - // cannot use here callable returning "const scalar type" because C++ ignores such const for scalar return type, so the static_cast + // cannot use here callable returning "const scalar type", + // because such const for scalar return type is ignored EXPECT_FALSE(CanCallReturnRef(static_cast(321))); auto constNonScalarValue = []() -> const std::string { return "CBA"; }; From 208c2f6b6076c7386faed78ee570cca87c6d3964 Mon Sep 17 00:00:00 2001 From: Piotr Nycz Date: Fri, 25 Oct 2019 16:14:18 +0200 Subject: [PATCH 059/541] variable names corrected (followed google coding style) Issue 2527 --- googlemock/test/gmock-actions_test.cc | 28 +++++++++++++-------------- 1 file changed, 14 insertions(+), 14 deletions(-) diff --git a/googlemock/test/gmock-actions_test.cc b/googlemock/test/gmock-actions_test.cc index e3c1d6cbfe..a1b6f11353 100644 --- a/googlemock/test/gmock-actions_test.cc +++ b/googlemock/test/gmock-actions_test.cc @@ -653,33 +653,33 @@ bool CanCallReturnRef(Unused) { return false; } // Tests that ReturnRef(v) is working with non-temporaries (T&) TEST(ReturnRefTest, WorksForNonTemporary) { - int scalarValue = 123; - EXPECT_TRUE(CanCallReturnRef(scalarValue)); + int scalar_value = 123; + EXPECT_TRUE(CanCallReturnRef(scalar_value)); - std::string nonScalarValue("ABC"); - EXPECT_TRUE(CanCallReturnRef(nonScalarValue)); + std::string non_scalar_value("ABC"); + EXPECT_TRUE(CanCallReturnRef(non_scalar_value)); - const int constScalarValue{321}; - EXPECT_TRUE(CanCallReturnRef(constScalarValue)); + const int const_scalar_value{321}; + EXPECT_TRUE(CanCallReturnRef(const_scalar_value)); - const std::string constNonScalarValue("CBA"); - EXPECT_TRUE(CanCallReturnRef(constNonScalarValue)); + const std::string const_non_scalar_value("CBA"); + EXPECT_TRUE(CanCallReturnRef(const_non_scalar_value)); } // Tests that ReturnRef(v) is not working with temporaries (T&&) TEST(ReturnRefTest, DoesNotWorkForTemporary) { - auto scalarValue = []() -> int { return 123; }; - EXPECT_FALSE(CanCallReturnRef(scalarValue())); + auto scalar_value = []() -> int { return 123; }; + EXPECT_FALSE(CanCallReturnRef(scalar_value())); - auto nonScalarValue = []() -> std::string { return "ABC"; }; - EXPECT_FALSE(CanCallReturnRef(nonScalarValue())); + auto non_scalar_value = []() -> std::string { return "ABC"; }; + EXPECT_FALSE(CanCallReturnRef(non_scalar_value())); // cannot use here callable returning "const scalar type", // because such const for scalar return type is ignored EXPECT_FALSE(CanCallReturnRef(static_cast(321))); - auto constNonScalarValue = []() -> const std::string { return "CBA"; }; - EXPECT_FALSE(CanCallReturnRef(constNonScalarValue())); + auto const_non_scalar_value = []() -> const std::string { return "CBA"; }; + EXPECT_FALSE(CanCallReturnRef(const_non_scalar_value())); } // Tests that ReturnRefOfCopy(v) works for reference types. From eed64b5fc6c0d619b2cb2df2eac1dc6cdf282a19 Mon Sep 17 00:00:00 2001 From: Krystian Kuzniarek Date: Thu, 8 Aug 2019 07:49:00 +0200 Subject: [PATCH 060/541] replace autogenerated TypesX classes by variadic ones --- googletest/include/gtest/gtest-typed-test.h | 18 +- .../include/gtest/internal/gtest-internal.h | 4 +- .../include/gtest/internal/gtest-type-util.h | 1590 +---------------- .../gtest/internal/gtest-type-util.h.pump | 132 +- googletest/test/gtest-unittest-api_test.cc | 9 +- 5 files changed, 102 insertions(+), 1651 deletions(-) diff --git a/googletest/include/gtest/gtest-typed-test.h b/googletest/include/gtest/gtest-typed-test.h index 6b7c9c8a07..3848044f19 100644 --- a/googletest/include/gtest/gtest-typed-test.h +++ b/googletest/include/gtest/gtest-typed-test.h @@ -27,7 +27,6 @@ // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - // GOOGLETEST_CM0001 DO NOT DELETE #ifndef GTEST_INCLUDE_GTEST_GTEST_TYPED_TEST_H_ @@ -188,13 +187,13 @@ INSTANTIATE_TYPED_TEST_SUITE_P(My, FooTest, MyTypes); #define GTEST_NAME_GENERATOR_(TestSuiteName) \ gtest_type_params_##TestSuiteName##_NameGenerator -#define TYPED_TEST_SUITE(CaseName, Types, ...) \ - typedef ::testing::internal::TypeList::type GTEST_TYPE_PARAMS_( \ - CaseName); \ - typedef ::testing::internal::NameGeneratorSelector<__VA_ARGS__>::type \ +#define TYPED_TEST_SUITE(CaseName, Types, ...) \ + typedef ::testing::internal::GenerateTypeList::type \ + GTEST_TYPE_PARAMS_(CaseName); \ + typedef ::testing::internal::NameGeneratorSelector<__VA_ARGS__>::type \ GTEST_NAME_GENERATOR_(CaseName) -# define TYPED_TEST(CaseName, TestName) \ +#define TYPED_TEST(CaseName, TestName) \ template \ class GTEST_TEST_CLASS_NAME_(CaseName, TestName) \ : public CaseName { \ @@ -204,8 +203,7 @@ INSTANTIATE_TYPED_TEST_SUITE_P(My, FooTest, MyTypes); void TestBody() override; \ }; \ static bool gtest_##CaseName##_##TestName##_registered_ \ - GTEST_ATTRIBUTE_UNUSED_ = \ - ::testing::internal::TypeParameterizedTest< \ + GTEST_ATTRIBUTE_UNUSED_ = ::testing::internal::TypeParameterizedTest< \ CaseName, \ ::testing::internal::TemplateSel, \ @@ -307,7 +305,7 @@ INSTANTIATE_TYPED_TEST_SUITE_P(My, FooTest, MyTypes); static bool gtest_##Prefix##_##SuiteName GTEST_ATTRIBUTE_UNUSED_ = \ ::testing::internal::TypeParameterizedTestSuite< \ SuiteName, GTEST_SUITE_NAMESPACE_(SuiteName)::gtest_AllTests_, \ - ::testing::internal::TypeList::type>:: \ + ::testing::internal::GenerateTypeList::type>:: \ Register(#Prefix, \ ::testing::internal::CodeLocation(__FILE__, __LINE__), \ >EST_TYPED_TEST_SUITE_P_STATE_(SuiteName), #SuiteName, \ @@ -315,7 +313,7 @@ INSTANTIATE_TYPED_TEST_SUITE_P(My, FooTest, MyTypes); ::testing::internal::GenerateNames< \ ::testing::internal::NameGeneratorSelector< \ __VA_ARGS__>::type, \ - ::testing::internal::TypeList::type>()) + ::testing::internal::GenerateTypeList::type>()) // Legacy API is deprecated but still available #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_ diff --git a/googletest/include/gtest/internal/gtest-internal.h b/googletest/include/gtest/internal/gtest-internal.h index 9524223232..2056561661 100644 --- a/googletest/include/gtest/internal/gtest-internal.h +++ b/googletest/include/gtest/internal/gtest-internal.h @@ -662,7 +662,7 @@ struct NameGeneratorSelector { }; template -void GenerateNamesRecursively(Types0, std::vector*, int) {} +void GenerateNamesRecursively(internal::None, std::vector*, int) {} template void GenerateNamesRecursively(Types, std::vector* result, int i) { @@ -729,7 +729,7 @@ class TypeParameterizedTest { // The base case for the compile time recursion. template -class TypeParameterizedTest { +class TypeParameterizedTest { public: static bool Register(const char* /*prefix*/, const CodeLocation&, const char* /*case_name*/, const char* /*test_names*/, diff --git a/googletest/include/gtest/internal/gtest-type-util.h b/googletest/include/gtest/internal/gtest-type-util.h index 3d7542d1fb..001fadbb3c 100644 --- a/googletest/include/gtest/internal/gtest-type-util.h +++ b/googletest/include/gtest/internal/gtest-type-util.h @@ -31,11 +31,12 @@ // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + // Type utilities needed for implementing typed and type-parameterized // tests. This file is generated by a SCRIPT. DO NOT EDIT BY HAND! // -// Currently we support at most 50 types in a list, and at most 50 -// type-parameterized tests in one type-parameterized test suite. +// Currently we support at most 50 type-parameterized tests +// in one type-parameterized test suite. // Please contact googletestframework@googlegroups.com if you need // more. @@ -105,1524 +106,6 @@ std::string GetTypeName() { #if GTEST_HAS_TYPED_TEST || GTEST_HAS_TYPED_TEST_P -// A unique type used as the default value for the arguments of class -// template Types. This allows us to simulate variadic templates -// (e.g. Types, Type, and etc), which C++ doesn't -// support directly. -struct None {}; - -// The following family of struct and struct templates are used to -// represent type lists. In particular, TypesN -// represents a type list with N types (T1, T2, ..., and TN) in it. -// Except for Types0, every struct in the family has two member types: -// Head for the first type in the list, and Tail for the rest of the -// list. - -// The empty type list. -struct Types0 {}; - -// Type lists of length 1, 2, 3, and so on. - -template -struct Types1 { - typedef T1 Head; - typedef Types0 Tail; -}; -template -struct Types2 { - typedef T1 Head; - typedef Types1 Tail; -}; - -template -struct Types3 { - typedef T1 Head; - typedef Types2 Tail; -}; - -template -struct Types4 { - typedef T1 Head; - typedef Types3 Tail; -}; - -template -struct Types5 { - typedef T1 Head; - typedef Types4 Tail; -}; - -template -struct Types6 { - typedef T1 Head; - typedef Types5 Tail; -}; - -template -struct Types7 { - typedef T1 Head; - typedef Types6 Tail; -}; - -template -struct Types8 { - typedef T1 Head; - typedef Types7 Tail; -}; - -template -struct Types9 { - typedef T1 Head; - typedef Types8 Tail; -}; - -template -struct Types10 { - typedef T1 Head; - typedef Types9 Tail; -}; - -template -struct Types11 { - typedef T1 Head; - typedef Types10 Tail; -}; - -template -struct Types12 { - typedef T1 Head; - typedef Types11 Tail; -}; - -template -struct Types13 { - typedef T1 Head; - typedef Types12 Tail; -}; - -template -struct Types14 { - typedef T1 Head; - typedef Types13 Tail; -}; - -template -struct Types15 { - typedef T1 Head; - typedef Types14 Tail; -}; - -template -struct Types16 { - typedef T1 Head; - typedef Types15 Tail; -}; - -template -struct Types17 { - typedef T1 Head; - typedef Types16 Tail; -}; - -template -struct Types18 { - typedef T1 Head; - typedef Types17 Tail; -}; - -template -struct Types19 { - typedef T1 Head; - typedef Types18 Tail; -}; - -template -struct Types20 { - typedef T1 Head; - typedef Types19 Tail; -}; - -template -struct Types21 { - typedef T1 Head; - typedef Types20 Tail; -}; - -template -struct Types22 { - typedef T1 Head; - typedef Types21 Tail; -}; - -template -struct Types23 { - typedef T1 Head; - typedef Types22 Tail; -}; - -template -struct Types24 { - typedef T1 Head; - typedef Types23 Tail; -}; - -template -struct Types25 { - typedef T1 Head; - typedef Types24 Tail; -}; - -template -struct Types26 { - typedef T1 Head; - typedef Types25 Tail; -}; - -template -struct Types27 { - typedef T1 Head; - typedef Types26 Tail; -}; - -template -struct Types28 { - typedef T1 Head; - typedef Types27 Tail; -}; - -template -struct Types29 { - typedef T1 Head; - typedef Types28 Tail; -}; - -template -struct Types30 { - typedef T1 Head; - typedef Types29 Tail; -}; - -template -struct Types31 { - typedef T1 Head; - typedef Types30 Tail; -}; - -template -struct Types32 { - typedef T1 Head; - typedef Types31 Tail; -}; - -template -struct Types33 { - typedef T1 Head; - typedef Types32 Tail; -}; - -template -struct Types34 { - typedef T1 Head; - typedef Types33 Tail; -}; - -template -struct Types35 { - typedef T1 Head; - typedef Types34 Tail; -}; - -template -struct Types36 { - typedef T1 Head; - typedef Types35 Tail; -}; - -template -struct Types37 { - typedef T1 Head; - typedef Types36 Tail; -}; - -template -struct Types38 { - typedef T1 Head; - typedef Types37 Tail; -}; - -template -struct Types39 { - typedef T1 Head; - typedef Types38 Tail; -}; - -template -struct Types40 { - typedef T1 Head; - typedef Types39 Tail; -}; - -template -struct Types41 { - typedef T1 Head; - typedef Types40 Tail; -}; - -template -struct Types42 { - typedef T1 Head; - typedef Types41 Tail; -}; - -template -struct Types43 { - typedef T1 Head; - typedef Types42 Tail; -}; - -template -struct Types44 { - typedef T1 Head; - typedef Types43 Tail; -}; - -template -struct Types45 { - typedef T1 Head; - typedef Types44 Tail; -}; - -template -struct Types46 { - typedef T1 Head; - typedef Types45 Tail; -}; - -template -struct Types47 { - typedef T1 Head; - typedef Types46 Tail; -}; - -template -struct Types48 { - typedef T1 Head; - typedef Types47 Tail; -}; - -template -struct Types49 { - typedef T1 Head; - typedef Types48 Tail; -}; - -template -struct Types50 { - typedef T1 Head; - typedef Types49 Tail; -}; - - -} // namespace internal - -// We don't want to require the users to write TypesN<...> directly, -// as that would require them to count the length. Types<...> is much -// easier to write, but generates horrible messages when there is a -// compiler error, as gcc insists on printing out each template -// argument, even if it has the default value (this means Types -// will appear as Types in the compiler -// errors). -// -// Our solution is to combine the best part of the two approaches: a -// user would write Types, and Google Test will translate -// that to TypesN internally to make error messages -// readable. The translation is done by the 'type' member of the -// Types template. -template -struct Types { - typedef internal::Types50 type; -}; - -template <> -struct Types { - typedef internal::Types0 type; -}; -template -struct Types { - typedef internal::Types1 type; -}; -template -struct Types { - typedef internal::Types2 type; -}; -template -struct Types { - typedef internal::Types3 type; -}; -template -struct Types { - typedef internal::Types4 type; -}; -template -struct Types { - typedef internal::Types5 type; -}; -template -struct Types { - typedef internal::Types6 type; -}; -template -struct Types { - typedef internal::Types7 type; -}; -template -struct Types { - typedef internal::Types8 type; -}; -template -struct Types { - typedef internal::Types9 type; -}; -template -struct Types { - typedef internal::Types10 type; -}; -template -struct Types { - typedef internal::Types11 type; -}; -template -struct Types { - typedef internal::Types12 type; -}; -template -struct Types { - typedef internal::Types13 type; -}; -template -struct Types { - typedef internal::Types14 type; -}; -template -struct Types { - typedef internal::Types15 type; -}; -template -struct Types { - typedef internal::Types16 type; -}; -template -struct Types { - typedef internal::Types17 type; -}; -template -struct Types { - typedef internal::Types18 type; -}; -template -struct Types { - typedef internal::Types19 type; -}; -template -struct Types { - typedef internal::Types20 type; -}; -template -struct Types { - typedef internal::Types21 type; -}; -template -struct Types { - typedef internal::Types22 type; -}; -template -struct Types { - typedef internal::Types23 type; -}; -template -struct Types { - typedef internal::Types24 type; -}; -template -struct Types { - typedef internal::Types25 type; -}; -template -struct Types { - typedef internal::Types26 type; -}; -template -struct Types { - typedef internal::Types27 type; -}; -template -struct Types { - typedef internal::Types28 type; -}; -template -struct Types { - typedef internal::Types29 type; -}; -template -struct Types { - typedef internal::Types30 type; -}; -template -struct Types { - typedef internal::Types31 type; -}; -template -struct Types { - typedef internal::Types32 type; -}; -template -struct Types { - typedef internal::Types33 type; -}; -template -struct Types { - typedef internal::Types34 type; -}; -template -struct Types { - typedef internal::Types35 type; -}; -template -struct Types { - typedef internal::Types36 type; -}; -template -struct Types { - typedef internal::Types37 type; -}; -template -struct Types { - typedef internal::Types38 type; -}; -template -struct Types { - typedef internal::Types39 type; -}; -template -struct Types { - typedef internal::Types40 type; -}; -template -struct Types { - typedef internal::Types41 type; -}; -template -struct Types { - typedef internal::Types42 type; -}; -template -struct Types { - typedef internal::Types43 type; -}; -template -struct Types { - typedef internal::Types44 type; -}; -template -struct Types { - typedef internal::Types45 type; -}; -template -struct Types { - typedef internal::Types46 type; -}; -template -struct Types { - typedef internal::Types47 type; -}; -template -struct Types { - typedef internal::Types48 type; -}; -template -struct Types { - typedef internal::Types49 type; -}; - -namespace internal { - # define GTEST_TEMPLATE_ template class // The template "selector" struct TemplateSel is used to @@ -3298,38 +1781,55 @@ struct Templates type; }; -// The TypeList template makes it possible to use either a single type -// or a Types<...> list in TYPED_TEST_SUITE() and -// INSTANTIATE_TYPED_TEST_SUITE_P(). +// A unique type indicating an empty node +struct None {}; + +// Tuple-like type lists +template +struct Types { + using Head = Head_; + using Tail = Types; +}; + +template +struct Types { + using Head = Head_; + using Tail = None; +}; + +// Helper metafunctions to tell apart a single type from types +// generated by ::testing::Types +template +struct ProxyTypeList { + typedef Types type; +}; + +template +struct is_proxy_type_list : std::false_type {}; + +template +struct is_proxy_type_list> : std::true_type {}; +// Generator which conditionally creates type lists. +// It recognizes if a requested type list should be created +// and prevents creating a new type list nested within another one. template -struct TypeList { - typedef Types1 type; -}; - -template -struct TypeList > { - typedef typename Types::type type; +struct GenerateTypeList { + private: + using proxy = typename std::conditional::value, T, + ProxyTypeList>::type; + + public: + using type = typename proxy::type; }; #endif // GTEST_HAS_TYPED_TEST || GTEST_HAS_TYPED_TEST_P } // namespace internal + +template +using Types = internal::ProxyTypeList; + } // namespace testing #endif // GTEST_INCLUDE_GTEST_INTERNAL_GTEST_TYPE_UTIL_H_ diff --git a/googletest/include/gtest/internal/gtest-type-util.h.pump b/googletest/include/gtest/internal/gtest-type-util.h.pump index 5e31b7b320..605b78f227 100644 --- a/googletest/include/gtest/internal/gtest-type-util.h.pump +++ b/googletest/include/gtest/internal/gtest-type-util.h.pump @@ -33,8 +33,8 @@ $var n = 50 $$ Maximum length of type lists we want to support. // Type utilities needed for implementing typed and type-parameterized // tests. This file is generated by a SCRIPT. DO NOT EDIT BY HAND! // -// Currently we support at most $n types in a list, and at most $n -// type-parameterized tests in one type-parameterized test suite. +// Currently we support at most $n type-parameterized tests +// in one type-parameterized test suite. // Please contact googletestframework@googlegroups.com if you need // more. @@ -104,84 +104,6 @@ std::string GetTypeName() { #if GTEST_HAS_TYPED_TEST || GTEST_HAS_TYPED_TEST_P -// A unique type used as the default value for the arguments of class -// template Types. This allows us to simulate variadic templates -// (e.g. Types, Type, and etc), which C++ doesn't -// support directly. -struct None {}; - -// The following family of struct and struct templates are used to -// represent type lists. In particular, TypesN -// represents a type list with N types (T1, T2, ..., and TN) in it. -// Except for Types0, every struct in the family has two member types: -// Head for the first type in the list, and Tail for the rest of the -// list. - -// The empty type list. -struct Types0 {}; - -// Type lists of length 1, 2, 3, and so on. - -template -struct Types1 { - typedef T1 Head; - typedef Types0 Tail; -}; - -$range i 2..n - -$for i [[ -$range j 1..i -$range k 2..i -template <$for j, [[typename T$j]]> -struct Types$i { - typedef T1 Head; - typedef Types$(i-1)<$for k, [[T$k]]> Tail; -}; - - -]] - -} // namespace internal - -// We don't want to require the users to write TypesN<...> directly, -// as that would require them to count the length. Types<...> is much -// easier to write, but generates horrible messages when there is a -// compiler error, as gcc insists on printing out each template -// argument, even if it has the default value (this means Types -// will appear as Types in the compiler -// errors). -// -// Our solution is to combine the best part of the two approaches: a -// user would write Types, and Google Test will translate -// that to TypesN internally to make error messages -// readable. The translation is done by the 'type' member of the -// Types template. - -$range i 1..n -template <$for i, [[typename T$i = internal::None]]> -struct Types { - typedef internal::Types$n<$for i, [[T$i]]> type; -}; - -template <> -struct Types<$for i, [[internal::None]]> { - typedef internal::Types0 type; -}; - -$range i 1..n-1 -$for i [[ -$range j 1..i -$range k i+1..n -template <$for j, [[typename T$j]]> -struct Types<$for j, [[T$j]]$for k[[, internal::None]]> { - typedef internal::Types$i<$for j, [[T$j]]> type; -}; - -]] - -namespace internal { - # define GTEST_TEMPLATE_ template class // The template "selector" struct TemplateSel is used to @@ -278,25 +200,55 @@ struct Templates<$for j, [[T$j]]$for k[[, NoneT]]> { ]] -// The TypeList template makes it possible to use either a single type -// or a Types<...> list in TYPED_TEST_SUITE() and -// INSTANTIATE_TYPED_TEST_SUITE_P(). +// A unique type indicating an empty node +struct None {}; -template -struct TypeList { - typedef Types1 type; +// Tuple-like type lists +template +struct Types { + using Head = Head_; + using Tail = Types; }; +template +struct Types { + using Head = Head_; + using Tail = None; +}; -$range i 1..n -template <$for i, [[typename T$i]]> -struct TypeList > { - typedef typename Types<$for i, [[T$i]]>::type type; +// Helper metafunctions to tell apart a single type from types +// generated by ::testing::Types +template +struct ProxyTypeList { + typedef Types type; +}; + +template +struct is_proxy_type_list : std::false_type {}; + +template +struct is_proxy_type_list> : std::true_type {}; + +// Generator which conditionally creates type lists. +// It recognizes if a requested type list should be created +// and prevents creating a new type list nested within another one. +template +struct GenerateTypeList { + private: + using proxy = typename std::conditional::value, T, + ProxyTypeList>::type; + + public: + using type = typename proxy::type; }; #endif // GTEST_HAS_TYPED_TEST || GTEST_HAS_TYPED_TEST_P } // namespace internal + +template +using Types = internal::ProxyTypeList; + } // namespace testing #endif // GTEST_INCLUDE_GTEST_INTERNAL_GTEST_TYPE_UTIL_H_ diff --git a/googletest/test/gtest-unittest-api_test.cc b/googletest/test/gtest-unittest-api_test.cc index 480a41fb42..7d2d8cc959 100644 --- a/googletest/test/gtest-unittest-api_test.cc +++ b/googletest/test/gtest-unittest-api_test.cc @@ -188,7 +188,7 @@ TEST(ApiTest, TestSuiteImmutableAccessorsWork) { ASSERT_TRUE(test_suite != nullptr); EXPECT_STREQ("TestSuiteWithCommentTest/0", test_suite->name()); - EXPECT_STREQ(GetTypeName().c_str(), test_suite->type_param()); + EXPECT_STREQ(GetTypeName>().c_str(), test_suite->type_param()); EXPECT_TRUE(test_suite->should_run()); EXPECT_EQ(0, test_suite->disabled_test_count()); EXPECT_EQ(1, test_suite->test_to_run_count()); @@ -199,7 +199,7 @@ TEST(ApiTest, TestSuiteImmutableAccessorsWork) { EXPECT_STREQ("Dummy", tests[0]->name()); EXPECT_STREQ("TestSuiteWithCommentTest/0", tests[0]->test_suite_name()); EXPECT_TRUE(IsNull(tests[0]->value_param())); - EXPECT_STREQ(GetTypeName().c_str(), tests[0]->type_param()); + EXPECT_STREQ(GetTypeName>().c_str(), tests[0]->type_param()); EXPECT_TRUE(tests[0]->should_run()); delete[] tests; @@ -265,7 +265,8 @@ class FinalSuccessChecker : public Environment { #if GTEST_HAS_TYPED_TEST EXPECT_STREQ("TestSuiteWithCommentTest/0", test_suites[2]->name()); - EXPECT_STREQ(GetTypeName().c_str(), test_suites[2]->type_param()); + EXPECT_STREQ(GetTypeName>().c_str(), + test_suites[2]->type_param()); EXPECT_TRUE(test_suites[2]->should_run()); EXPECT_EQ(0, test_suites[2]->disabled_test_count()); ASSERT_EQ(1, test_suites[2]->total_test_count()); @@ -317,7 +318,7 @@ class FinalSuccessChecker : public Environment { EXPECT_STREQ("Dummy", tests[0]->name()); EXPECT_STREQ("TestSuiteWithCommentTest/0", tests[0]->test_suite_name()); EXPECT_TRUE(IsNull(tests[0]->value_param())); - EXPECT_STREQ(GetTypeName().c_str(), tests[0]->type_param()); + EXPECT_STREQ(GetTypeName>().c_str(), tests[0]->type_param()); EXPECT_TRUE(tests[0]->should_run()); EXPECT_TRUE(tests[0]->result()->Passed()); EXPECT_EQ(0, tests[0]->result()->test_property_count()); From e3a9a567d8264965054cbf715c7ccf1f82c13b17 Mon Sep 17 00:00:00 2001 From: Krystian Kuzniarek Date: Thu, 8 Aug 2019 20:23:58 +0200 Subject: [PATCH 061/541] replace autogenerated TemplatesX classes by variadic ones --- googletest/include/gtest/gtest-typed-test.h | 14 +- .../include/gtest/internal/gtest-internal.h | 2 +- .../include/gtest/internal/gtest-type-util.h | 1667 +---------------- .../gtest/internal/gtest-type-util.h.pump | 88 +- 4 files changed, 28 insertions(+), 1743 deletions(-) diff --git a/googletest/include/gtest/gtest-typed-test.h b/googletest/include/gtest/gtest-typed-test.h index 3848044f19..151fc8f769 100644 --- a/googletest/include/gtest/gtest-typed-test.h +++ b/googletest/include/gtest/gtest-typed-test.h @@ -284,13 +284,13 @@ INSTANTIATE_TYPED_TEST_SUITE_P(My, FooTest, MyTypes); void GTEST_SUITE_NAMESPACE_( \ SuiteName)::TestName::TestBody() -#define REGISTER_TYPED_TEST_SUITE_P(SuiteName, ...) \ - namespace GTEST_SUITE_NAMESPACE_(SuiteName) { \ - typedef ::testing::internal::Templates<__VA_ARGS__>::type gtest_AllTests_; \ - } \ - static const char* const GTEST_REGISTERED_TEST_NAMES_( \ - SuiteName) GTEST_ATTRIBUTE_UNUSED_ = \ - GTEST_TYPED_TEST_SUITE_P_STATE_(SuiteName).VerifyRegisteredTestNames( \ +#define REGISTER_TYPED_TEST_SUITE_P(SuiteName, ...) \ + namespace GTEST_SUITE_NAMESPACE_(SuiteName) { \ + typedef ::testing::internal::Templates<__VA_ARGS__> gtest_AllTests_; \ + } \ + static const char* const GTEST_REGISTERED_TEST_NAMES_( \ + SuiteName) GTEST_ATTRIBUTE_UNUSED_ = \ + GTEST_TYPED_TEST_SUITE_P_STATE_(SuiteName).VerifyRegisteredTestNames( \ __FILE__, __LINE__, #__VA_ARGS__) // Legacy API is deprecated but still available diff --git a/googletest/include/gtest/internal/gtest-internal.h b/googletest/include/gtest/internal/gtest-internal.h index 2056561661..edf0afa249 100644 --- a/googletest/include/gtest/internal/gtest-internal.h +++ b/googletest/include/gtest/internal/gtest-internal.h @@ -781,7 +781,7 @@ class TypeParameterizedTestSuite { // The base case for the compile time recursion. template -class TypeParameterizedTestSuite { +class TypeParameterizedTestSuite { public: static bool Register(const char* /*prefix*/, const CodeLocation&, const TypedTestSuitePState* /*state*/, diff --git a/googletest/include/gtest/internal/gtest-type-util.h b/googletest/include/gtest/internal/gtest-type-util.h index 001fadbb3c..3f4c82a8bd 100644 --- a/googletest/include/gtest/internal/gtest-type-util.h +++ b/googletest/include/gtest/internal/gtest-type-util.h @@ -34,11 +34,6 @@ // Type utilities needed for implementing typed and type-parameterized // tests. This file is generated by a SCRIPT. DO NOT EDIT BY HAND! -// -// Currently we support at most 50 type-parameterized tests -// in one type-parameterized test suite. -// Please contact googletestframework@googlegroups.com if you need -// more. // GOOGLETEST_CM0001 DO NOT DELETE @@ -106,6 +101,9 @@ std::string GetTypeName() { #if GTEST_HAS_TYPED_TEST || GTEST_HAS_TYPED_TEST_P +// A unique type indicating an empty node +struct None {}; + # define GTEST_TEMPLATE_ template class // The template "selector" struct TemplateSel is used to @@ -127,1662 +125,17 @@ struct TemplateSel { # define GTEST_BIND_(TmplSel, T) \ TmplSel::template Bind::type -// A unique struct template used as the default value for the -// arguments of class template Templates. This allows us to simulate -// variadic templates (e.g. Templates, Templates, -// and etc), which C++ doesn't support directly. -template -struct NoneT {}; - -// The following family of struct and struct templates are used to -// represent template lists. In particular, TemplatesN represents a list of N templates (T1, T2, ..., and TN). Except -// for Templates0, every struct in the family has two member types: -// Head for the selector of the first template in the list, and Tail -// for the rest of the list. - -// The empty template list. -struct Templates0 {}; - -// Template lists of length 1, 2, 3, and so on. - -template -struct Templates1 { - typedef TemplateSel Head; - typedef Templates0 Tail; -}; -template -struct Templates2 { - typedef TemplateSel Head; - typedef Templates1 Tail; -}; - -template -struct Templates3 { - typedef TemplateSel Head; - typedef Templates2 Tail; -}; - -template -struct Templates4 { - typedef TemplateSel Head; - typedef Templates3 Tail; -}; - -template -struct Templates5 { - typedef TemplateSel Head; - typedef Templates4 Tail; -}; - -template -struct Templates6 { - typedef TemplateSel Head; - typedef Templates5 Tail; -}; - -template -struct Templates7 { - typedef TemplateSel Head; - typedef Templates6 Tail; -}; - -template -struct Templates8 { - typedef TemplateSel Head; - typedef Templates7 Tail; -}; - -template -struct Templates9 { - typedef TemplateSel Head; - typedef Templates8 Tail; -}; - -template -struct Templates10 { - typedef TemplateSel Head; - typedef Templates9 Tail; -}; - -template -struct Templates11 { - typedef TemplateSel Head; - typedef Templates10 Tail; -}; - -template -struct Templates12 { - typedef TemplateSel Head; - typedef Templates11 Tail; -}; - -template -struct Templates13 { - typedef TemplateSel Head; - typedef Templates12 Tail; -}; - -template -struct Templates14 { - typedef TemplateSel Head; - typedef Templates13 Tail; -}; - -template -struct Templates15 { - typedef TemplateSel Head; - typedef Templates14 Tail; -}; - -template -struct Templates16 { - typedef TemplateSel Head; - typedef Templates15 Tail; -}; - -template -struct Templates17 { - typedef TemplateSel Head; - typedef Templates16 Tail; -}; - -template -struct Templates18 { - typedef TemplateSel Head; - typedef Templates17 Tail; -}; - -template -struct Templates19 { - typedef TemplateSel Head; - typedef Templates18 Tail; -}; - -template -struct Templates20 { - typedef TemplateSel Head; - typedef Templates19 Tail; -}; - -template -struct Templates21 { - typedef TemplateSel Head; - typedef Templates20 Tail; -}; - -template -struct Templates22 { - typedef TemplateSel Head; - typedef Templates21 Tail; -}; - -template -struct Templates23 { - typedef TemplateSel Head; - typedef Templates22 Tail; -}; - -template -struct Templates24 { - typedef TemplateSel Head; - typedef Templates23 Tail; -}; - -template -struct Templates25 { - typedef TemplateSel Head; - typedef Templates24 Tail; -}; - -template -struct Templates26 { - typedef TemplateSel Head; - typedef Templates25 Tail; -}; - -template -struct Templates27 { - typedef TemplateSel Head; - typedef Templates26 Tail; -}; - -template -struct Templates28 { - typedef TemplateSel Head; - typedef Templates27 Tail; -}; - -template -struct Templates29 { - typedef TemplateSel Head; - typedef Templates28 Tail; -}; - -template -struct Templates30 { - typedef TemplateSel Head; - typedef Templates29 Tail; -}; - -template -struct Templates31 { - typedef TemplateSel Head; - typedef Templates30 Tail; -}; - -template -struct Templates32 { - typedef TemplateSel Head; - typedef Templates31 Tail; -}; - -template -struct Templates33 { - typedef TemplateSel Head; - typedef Templates32 Tail; -}; - -template -struct Templates34 { - typedef TemplateSel Head; - typedef Templates33 Tail; -}; - -template -struct Templates35 { - typedef TemplateSel Head; - typedef Templates34 Tail; -}; - -template -struct Templates36 { - typedef TemplateSel Head; - typedef Templates35 Tail; -}; - -template -struct Templates37 { - typedef TemplateSel Head; - typedef Templates36 Tail; -}; - -template -struct Templates38 { - typedef TemplateSel Head; - typedef Templates37 Tail; -}; - -template -struct Templates39 { - typedef TemplateSel Head; - typedef Templates38 Tail; -}; - -template -struct Templates40 { - typedef TemplateSel Head; - typedef Templates39 Tail; -}; - -template -struct Templates41 { - typedef TemplateSel Head; - typedef Templates40 Tail; -}; - -template -struct Templates42 { - typedef TemplateSel Head; - typedef Templates41 Tail; -}; - -template -struct Templates43 { - typedef TemplateSel Head; - typedef Templates42 Tail; -}; - -template -struct Templates44 { - typedef TemplateSel Head; - typedef Templates43 Tail; -}; - -template -struct Templates45 { - typedef TemplateSel Head; - typedef Templates44 Tail; -}; - -template -struct Templates46 { - typedef TemplateSel Head; - typedef Templates45 Tail; -}; - -template -struct Templates47 { - typedef TemplateSel Head; - typedef Templates46 Tail; -}; - -template -struct Templates48 { - typedef TemplateSel Head; - typedef Templates47 Tail; -}; - -template -struct Templates49 { - typedef TemplateSel Head; - typedef Templates48 Tail; -}; - -template -struct Templates50 { - typedef TemplateSel Head; - typedef Templates49 Tail; -}; - - -// We don't want to require the users to write TemplatesN<...> directly, -// as that would require them to count the length. Templates<...> is much -// easier to write, but generates horrible messages when there is a -// compiler error, as gcc insists on printing out each template -// argument, even if it has the default value (this means Templates -// will appear as Templates in the compiler -// errors). -// -// Our solution is to combine the best part of the two approaches: a -// user would write Templates, and Google Test will translate -// that to TemplatesN internally to make error messages -// readable. The translation is done by the 'type' member of the -// Templates template. -template +template struct Templates { - typedef Templates50 type; + using Head = TemplateSel; + using Tail = Templates; }; -template <> -struct Templates { - typedef Templates0 type; -}; -template -struct Templates { - typedef Templates1 type; -}; -template -struct Templates { - typedef Templates2 type; -}; -template -struct Templates { - typedef Templates3 type; -}; -template -struct Templates { - typedef Templates4 type; -}; -template -struct Templates { - typedef Templates5 type; -}; -template -struct Templates { - typedef Templates6 type; -}; -template -struct Templates { - typedef Templates7 type; -}; -template -struct Templates { - typedef Templates8 type; -}; -template -struct Templates { - typedef Templates9 type; -}; -template -struct Templates { - typedef Templates10 type; -}; -template -struct Templates { - typedef Templates11 type; -}; -template -struct Templates { - typedef Templates12 type; +template +struct Templates { + typedef TemplateSel Head; + typedef None Tail; }; -template -struct Templates { - typedef Templates13 type; -}; -template -struct Templates { - typedef Templates14 type; -}; -template -struct Templates { - typedef Templates15 type; -}; -template -struct Templates { - typedef Templates16 type; -}; -template -struct Templates { - typedef Templates17 type; -}; -template -struct Templates { - typedef Templates18 type; -}; -template -struct Templates { - typedef Templates19 type; -}; -template -struct Templates { - typedef Templates20 type; -}; -template -struct Templates { - typedef Templates21 type; -}; -template -struct Templates { - typedef Templates22 type; -}; -template -struct Templates { - typedef Templates23 type; -}; -template -struct Templates { - typedef Templates24 type; -}; -template -struct Templates { - typedef Templates25 type; -}; -template -struct Templates { - typedef Templates26 type; -}; -template -struct Templates { - typedef Templates27 type; -}; -template -struct Templates { - typedef Templates28 type; -}; -template -struct Templates { - typedef Templates29 type; -}; -template -struct Templates { - typedef Templates30 type; -}; -template -struct Templates { - typedef Templates31 type; -}; -template -struct Templates { - typedef Templates32 type; -}; -template -struct Templates { - typedef Templates33 type; -}; -template -struct Templates { - typedef Templates34 type; -}; -template -struct Templates { - typedef Templates35 type; -}; -template -struct Templates { - typedef Templates36 type; -}; -template -struct Templates { - typedef Templates37 type; -}; -template -struct Templates { - typedef Templates38 type; -}; -template -struct Templates { - typedef Templates39 type; -}; -template -struct Templates { - typedef Templates40 type; -}; -template -struct Templates { - typedef Templates41 type; -}; -template -struct Templates { - typedef Templates42 type; -}; -template -struct Templates { - typedef Templates43 type; -}; -template -struct Templates { - typedef Templates44 type; -}; -template -struct Templates { - typedef Templates45 type; -}; -template -struct Templates { - typedef Templates46 type; -}; -template -struct Templates { - typedef Templates47 type; -}; -template -struct Templates { - typedef Templates48 type; -}; -template -struct Templates { - typedef Templates49 type; -}; - -// A unique type indicating an empty node -struct None {}; // Tuple-like type lists template diff --git a/googletest/include/gtest/internal/gtest-type-util.h.pump b/googletest/include/gtest/internal/gtest-type-util.h.pump index 605b78f227..dcfde181ff 100644 --- a/googletest/include/gtest/internal/gtest-type-util.h.pump +++ b/googletest/include/gtest/internal/gtest-type-util.h.pump @@ -32,11 +32,6 @@ $var n = 50 $$ Maximum length of type lists we want to support. // Type utilities needed for implementing typed and type-parameterized // tests. This file is generated by a SCRIPT. DO NOT EDIT BY HAND! -// -// Currently we support at most $n type-parameterized tests -// in one type-parameterized test suite. -// Please contact googletestframework@googlegroups.com if you need -// more. // GOOGLETEST_CM0001 DO NOT DELETE @@ -104,6 +99,9 @@ std::string GetTypeName() { #if GTEST_HAS_TYPED_TEST || GTEST_HAS_TYPED_TEST_P +// A unique type indicating an empty node +struct None {}; + # define GTEST_TEMPLATE_ template class // The template "selector" struct TemplateSel is used to @@ -125,84 +123,18 @@ struct TemplateSel { # define GTEST_BIND_(TmplSel, T) \ TmplSel::template Bind::type -// A unique struct template used as the default value for the -// arguments of class template Templates. This allows us to simulate -// variadic templates (e.g. Templates, Templates, -// and etc), which C++ doesn't support directly. -template -struct NoneT {}; - -// The following family of struct and struct templates are used to -// represent template lists. In particular, TemplatesN represents a list of N templates (T1, T2, ..., and TN). Except -// for Templates0, every struct in the family has two member types: -// Head for the selector of the first template in the list, and Tail -// for the rest of the list. - -// The empty template list. -struct Templates0 {}; - -// Template lists of length 1, 2, 3, and so on. - -template -struct Templates1 { - typedef TemplateSel Head; - typedef Templates0 Tail; -}; - -$range i 2..n - -$for i [[ -$range j 1..i -$range k 2..i -template <$for j, [[GTEST_TEMPLATE_ T$j]]> -struct Templates$i { - typedef TemplateSel Head; - typedef Templates$(i-1)<$for k, [[T$k]]> Tail; -}; - - -]] - -// We don't want to require the users to write TemplatesN<...> directly, -// as that would require them to count the length. Templates<...> is much -// easier to write, but generates horrible messages when there is a -// compiler error, as gcc insists on printing out each template -// argument, even if it has the default value (this means Templates -// will appear as Templates in the compiler -// errors). -// -// Our solution is to combine the best part of the two approaches: a -// user would write Templates, and Google Test will translate -// that to TemplatesN internally to make error messages -// readable. The translation is done by the 'type' member of the -// Templates template. - -$range i 1..n -template <$for i, [[GTEST_TEMPLATE_ T$i = NoneT]]> +template struct Templates { - typedef Templates$n<$for i, [[T$i]]> type; + using Head = TemplateSel; + using Tail = Templates; }; -template <> -struct Templates<$for i, [[NoneT]]> { - typedef Templates0 type; +template +struct Templates { + typedef TemplateSel Head; + typedef None Tail; }; -$range i 1..n-1 -$for i [[ -$range j 1..i -$range k i+1..n -template <$for j, [[GTEST_TEMPLATE_ T$j]]> -struct Templates<$for j, [[T$j]]$for k[[, NoneT]]> { - typedef Templates$i<$for j, [[T$j]]> type; -}; - -]] - -// A unique type indicating an empty node -struct None {}; - // Tuple-like type lists template struct Types { From a7083564d55078e7bed7255a6aa2e52cdb96b557 Mon Sep 17 00:00:00 2001 From: Krystian Kuzniarek Date: Thu, 8 Aug 2019 20:33:52 +0200 Subject: [PATCH 062/541] remove gtest-type-util.h.pump --- CONTRIBUTING.md | 4 +- .../include/gtest/internal/gtest-type-util.h | 7 +- .../gtest/internal/gtest-type-util.h.pump | 186 ------------------ 3 files changed, 3 insertions(+), 194 deletions(-) delete mode 100644 googletest/include/gtest/internal/gtest-type-util.h.pump diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 30c8d8900b..b9c14e987d 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -133,8 +133,8 @@ All tests should pass. Some of Google Test's source files are generated from templates (not in the C++ sense) using a script. For example, the file -include/gtest/internal/gtest-type-util.h.pump is used to generate -gtest-type-util.h in the same directory. +*googlemock/include/gmock/gmock-generated-actions.h.pump* is used to generate +*gmock-generated-actions.h* in the same directory. You don't need to worry about regenerating the source files unless you need to modify them. You would then modify the corresponding `.pump` files and run the diff --git a/googletest/include/gtest/internal/gtest-type-util.h b/googletest/include/gtest/internal/gtest-type-util.h index 3f4c82a8bd..848c75621f 100644 --- a/googletest/include/gtest/internal/gtest-type-util.h +++ b/googletest/include/gtest/internal/gtest-type-util.h @@ -1,7 +1,3 @@ -// This file was GENERATED by command: -// pump.py gtest-type-util.h.pump -// DO NOT EDIT BY HAND!!! - // Copyright 2008 Google Inc. // All Rights Reserved. // @@ -31,9 +27,8 @@ // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - // Type utilities needed for implementing typed and type-parameterized -// tests. This file is generated by a SCRIPT. DO NOT EDIT BY HAND! +// tests. // GOOGLETEST_CM0001 DO NOT DELETE diff --git a/googletest/include/gtest/internal/gtest-type-util.h.pump b/googletest/include/gtest/internal/gtest-type-util.h.pump deleted file mode 100644 index dcfde181ff..0000000000 --- a/googletest/include/gtest/internal/gtest-type-util.h.pump +++ /dev/null @@ -1,186 +0,0 @@ -$$ -*- mode: c++; -*- -$var n = 50 $$ Maximum length of type lists we want to support. -// Copyright 2008 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. - - -// Type utilities needed for implementing typed and type-parameterized -// tests. This file is generated by a SCRIPT. DO NOT EDIT BY HAND! - -// GOOGLETEST_CM0001 DO NOT DELETE - -#ifndef GTEST_INCLUDE_GTEST_INTERNAL_GTEST_TYPE_UTIL_H_ -#define GTEST_INCLUDE_GTEST_INTERNAL_GTEST_TYPE_UTIL_H_ - -#include "gtest/internal/gtest-port.h" - -// #ifdef __GNUC__ is too general here. It is possible to use gcc without using -// libstdc++ (which is where cxxabi.h comes from). -# if GTEST_HAS_CXXABI_H_ -# include -# elif defined(__HP_aCC) -# include -# endif // GTEST_HASH_CXXABI_H_ - -namespace testing { -namespace internal { - -// Canonicalizes a given name with respect to the Standard C++ Library. -// This handles removing the inline namespace within `std` that is -// used by various standard libraries (e.g., `std::__1`). Names outside -// of namespace std are returned unmodified. -inline std::string CanonicalizeForStdLibVersioning(std::string s) { - static const char prefix[] = "std::__"; - if (s.compare(0, strlen(prefix), prefix) == 0) { - std::string::size_type end = s.find("::", strlen(prefix)); - if (end != s.npos) { - // Erase everything between the initial `std` and the second `::`. - s.erase(strlen("std"), end - strlen("std")); - } - } - return s; -} - -// GetTypeName() returns a human-readable name of type T. -// NB: This function is also used in Google Mock, so don't move it inside of -// the typed-test-only section below. -template -std::string GetTypeName() { -# if GTEST_HAS_RTTI - - const char* const name = typeid(T).name(); -# if GTEST_HAS_CXXABI_H_ || defined(__HP_aCC) - int status = 0; - // gcc's implementation of typeid(T).name() mangles the type name, - // so we have to demangle it. -# if GTEST_HAS_CXXABI_H_ - using abi::__cxa_demangle; -# endif // GTEST_HAS_CXXABI_H_ - char* const readable_name = __cxa_demangle(name, nullptr, nullptr, &status); - const std::string name_str(status == 0 ? readable_name : name); - free(readable_name); - return CanonicalizeForStdLibVersioning(name_str); -# else - return name; -# endif // GTEST_HAS_CXXABI_H_ || __HP_aCC - -# else - - return ""; - -# endif // GTEST_HAS_RTTI -} - -#if GTEST_HAS_TYPED_TEST || GTEST_HAS_TYPED_TEST_P - -// A unique type indicating an empty node -struct None {}; - -# define GTEST_TEMPLATE_ template class - -// The template "selector" struct TemplateSel is used to -// represent Tmpl, which must be a class template with one type -// parameter, as a type. TemplateSel::Bind::type is defined -// as the type Tmpl. This allows us to actually instantiate the -// template "selected" by TemplateSel. -// -// This trick is necessary for simulating typedef for class templates, -// which C++ doesn't support directly. -template -struct TemplateSel { - template - struct Bind { - typedef Tmpl type; - }; -}; - -# define GTEST_BIND_(TmplSel, T) \ - TmplSel::template Bind::type - -template -struct Templates { - using Head = TemplateSel; - using Tail = Templates; -}; - -template -struct Templates { - typedef TemplateSel Head; - typedef None Tail; -}; - -// Tuple-like type lists -template -struct Types { - using Head = Head_; - using Tail = Types; -}; - -template -struct Types { - using Head = Head_; - using Tail = None; -}; - -// Helper metafunctions to tell apart a single type from types -// generated by ::testing::Types -template -struct ProxyTypeList { - typedef Types type; -}; - -template -struct is_proxy_type_list : std::false_type {}; - -template -struct is_proxy_type_list> : std::true_type {}; - -// Generator which conditionally creates type lists. -// It recognizes if a requested type list should be created -// and prevents creating a new type list nested within another one. -template -struct GenerateTypeList { - private: - using proxy = typename std::conditional::value, T, - ProxyTypeList>::type; - - public: - using type = typename proxy::type; -}; - -#endif // GTEST_HAS_TYPED_TEST || GTEST_HAS_TYPED_TEST_P - -} // namespace internal - -template -using Types = internal::ProxyTypeList; - -} // namespace testing - -#endif // GTEST_INCLUDE_GTEST_INTERNAL_GTEST_TYPE_UTIL_H_ From 002905f29fc910c7d9756ae70edeffb96a21585a Mon Sep 17 00:00:00 2001 From: Krystian Kuzniarek Date: Thu, 8 Aug 2019 20:39:33 +0200 Subject: [PATCH 063/541] move the pumping script to googlemock --- CONTRIBUTING.md | 4 ++-- {googletest => googlemock}/docs/pump_manual.md | 0 {googletest => googlemock}/scripts/pump.py | 0 3 files changed, 2 insertions(+), 2 deletions(-) rename {googletest => googlemock}/docs/pump_manual.md (100%) rename {googletest => googlemock}/scripts/pump.py (100%) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index b9c14e987d..4c18499267 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -138,5 +138,5 @@ sense) using a script. For example, the file You don't need to worry about regenerating the source files unless you need to modify them. You would then modify the corresponding `.pump` files and run the -'[pump.py](googletest/scripts/pump.py)' generator script. See the -[Pump Manual](googletest/docs/pump_manual.md). +'[pump.py](googlemock/scripts/pump.py)' generator script. See the +[Pump Manual](googlemock/docs/pump_manual.md). diff --git a/googletest/docs/pump_manual.md b/googlemock/docs/pump_manual.md similarity index 100% rename from googletest/docs/pump_manual.md rename to googlemock/docs/pump_manual.md diff --git a/googletest/scripts/pump.py b/googlemock/scripts/pump.py similarity index 100% rename from googletest/scripts/pump.py rename to googlemock/scripts/pump.py From 1a49b67aebe9e5178d5614ff1359bbbca04d2eed Mon Sep 17 00:00:00 2001 From: Krystian Kuzniarek Date: Tue, 3 Sep 2019 18:15:09 +0200 Subject: [PATCH 064/541] update CONTRIBUTORS --- googletest/CONTRIBUTORS | 1 + 1 file changed, 1 insertion(+) diff --git a/googletest/CONTRIBUTORS b/googletest/CONTRIBUTORS index feae2fc044..1e4afe2182 100644 --- a/googletest/CONTRIBUTORS +++ b/googletest/CONTRIBUTORS @@ -17,6 +17,7 @@ Jói Sigurðsson Keir Mierle Keith Ray Kenton Varda +Krystian Kuzniarek Manuel Klimek Markus Heule Mika Raento From a1f71dd56df487ed755cdf6a6a2908a64207285a Mon Sep 17 00:00:00 2001 From: Abseil Team Date: Mon, 28 Oct 2019 10:43:06 -0400 Subject: [PATCH 065/541] Googletest export Remove badly formatted suggestion in gmock cheat sheet. PiperOrigin-RevId: 277060475 --- googlemock/docs/cheat_sheet.md | 13 ------------- 1 file changed, 13 deletions(-) diff --git a/googlemock/docs/cheat_sheet.md b/googlemock/docs/cheat_sheet.md index aafb3b3b18..975362bf3b 100644 --- a/googlemock/docs/cheat_sheet.md +++ b/googlemock/docs/cheat_sheet.md @@ -614,19 +614,6 @@ composite action - trying to do so will result in a run-time error. #### Defining Actions - - - - - - -
`struct SumAction {`
-  `template `
-  `T operator()(T x, Ty) { return x + y; }`
- `};` -
Defines a generic functor that can be used as an action summing its - arguments.
- | | | | :--------------------------------- | :-------------------------------------- | From 757d39a79bcb3194a42ad9279dba5f56e84dda66 Mon Sep 17 00:00:00 2001 From: Abseil Team Date: Mon, 28 Oct 2019 12:31:27 -0400 Subject: [PATCH 066/541] Googletest export Make it clearer that users should _not_ write their own main functions. PiperOrigin-RevId: 277079721 --- googletest/docs/primer.md | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/googletest/docs/primer.md b/googletest/docs/primer.md index 0317692bbb..5139402401 100644 --- a/googletest/docs/primer.md +++ b/googletest/docs/primer.md @@ -478,7 +478,13 @@ If a fatal failure happens the subsequent steps will be skipped. ## Writing the main() Function -Write your own main() function, which should return the value of +Most users should _not_ need to write their own `main` function and instead link +with `gtest_main` (as opposed to with `gtest`), which defines a suitable entry +point. See the end of this section for details. The remainder of this section +should only apply when you need to do something custom before the tests run that +cannot be expressed within the framework of fixtures and test suites. + +If you write your own `main` function, it should return the value of `RUN_ALL_TESTS()`. You can start from this boilerplate: From 755f853c6be9ff44d6125367fa5ebdb75c382640 Mon Sep 17 00:00:00 2001 From: Abseil Team Date: Mon, 28 Oct 2019 12:58:29 -0400 Subject: [PATCH 067/541] Googletest export Avoid temporary matcher instances. They are unnecessary and can be relatively more expensive than the rest of the algorithm. PiperOrigin-RevId: 277084853 --- googlemock/include/gmock/gmock-matchers.h | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/googlemock/include/gmock/gmock-matchers.h b/googlemock/include/gmock/gmock-matchers.h index bb047da96c..a96488354a 100644 --- a/googlemock/include/gmock/gmock-matchers.h +++ b/googlemock/include/gmock/gmock-matchers.h @@ -3028,12 +3028,14 @@ class UnorderedElementsAreMatcherImpl element_printouts->clear(); ::std::vector did_match; size_t num_elements = 0; + DummyMatchResultListener dummy; for (; elem_first != elem_last; ++num_elements, ++elem_first) { if (listener->IsInterested()) { element_printouts->push_back(PrintToString(*elem_first)); } for (size_t irhs = 0; irhs != matchers_.size(); ++irhs) { - did_match.push_back(Matches(matchers_[irhs])(*elem_first)); + did_match.push_back( + matchers_[irhs].MatchAndExplain(*elem_first, &dummy)); } } From 2bee6da24e9f63a22a4ed0f87e3db8583401fc68 Mon Sep 17 00:00:00 2001 From: Abseil Team Date: Mon, 28 Oct 2019 14:09:47 -0400 Subject: [PATCH 068/541] Googletest export Editorial cleanup of the "write the main function" section PiperOrigin-RevId: 277102507 --- googletest/docs/primer.md | 16 +++++++++++----- 1 file changed, 11 insertions(+), 5 deletions(-) diff --git a/googletest/docs/primer.md b/googletest/docs/primer.md index 5139402401..63f0516888 100644 --- a/googletest/docs/primer.md +++ b/googletest/docs/primer.md @@ -491,15 +491,18 @@ You can start from this boilerplate: ```c++ #include "this/package/foo.h" + #include "gtest/gtest.h" +namespace my { +namespace project { namespace { // The fixture for testing class Foo. class FooTest : public ::testing::Test { protected: - // You can remove any or all of the following functions if its body - // is empty. + // You can remove any or all of the following functions if their bodies would + // be empty. FooTest() { // You can do set-up work for each test here. @@ -522,7 +525,8 @@ class FooTest : public ::testing::Test { // before the destructor). } - // Objects declared here can be used by all tests in the test suite for Foo. + // Class members declared here can be used by all tests in the test suite + // for Foo. }; // Tests that the Foo::Bar() method does Abc. @@ -539,6 +543,8 @@ TEST_F(FooTest, DoesXyz) { } } // namespace +} // namespace project +} // namespace my int main(int argc, char **argv) { ::testing::InitGoogleTest(&argc, argv); @@ -555,10 +561,10 @@ the [AdvancedGuide](advanced.md). You **must** call this function before calling On Windows, `InitGoogleTest()` also works with wide strings, so it can be used in programs compiled in `UNICODE` mode as well. -But maybe you think that writing all those main() functions is too much work? We +But maybe you think that writing all those `main` functions is too much work? We agree with you completely, and that's why Google Test provides a basic implementation of main(). If it fits your needs, then just link your test with -gtest\_main library and you are good to go. +the `gtest_main` library and you are good to go. NOTE: `ParseGUnitFlags()` is deprecated in favor of `InitGoogleTest()`. From fff8dabbf6c5641e97a646d710862508746183a2 Mon Sep 17 00:00:00 2001 From: mhermas Date: Mon, 28 Oct 2019 15:26:05 -0400 Subject: [PATCH 069/541] Googletest export Merge 65032e28cba171c000accc85ffaf6f1e62921b86 into 8c91ecef292e963d23cd5b25f01ea1579fbe9aaa Closes #2470 COPYBARA_INTEGRATE_REVIEW=https://github.com/google/googletest/pull/2470 from hermas55:bugfix/default_const_param 65032e28cba171c000accc85ffaf6f1e62921b86 PiperOrigin-RevId: 277118535 --- googlemock/scripts/generator/cpp/ast.py | 55 ++- .../scripts/generator/cpp/gmock_class.py | 364 ++++++++------- .../scripts/generator/cpp/gmock_class_test.py | 415 ++++++++++-------- 3 files changed, 440 insertions(+), 394 deletions(-) diff --git a/googlemock/scripts/generator/cpp/ast.py b/googlemock/scripts/generator/cpp/ast.py index 77bbec995f..0d0c984ac0 100755 --- a/googlemock/scripts/generator/cpp/ast.py +++ b/googlemock/scripts/generator/cpp/ast.py @@ -1,19 +1,33 @@ #!/usr/bin/env python # -# Copyright 2007 Neal Norwitz -# Portions Copyright 2007 Google Inc. +# Copyright 2008, Google Inc. +# All rights reserved. # -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are +# met: # -# http://www.apache.org/licenses/LICENSE-2.0 +# * 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. # -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. +# 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. """Generate an Abstract Syntax Tree (AST) for C++.""" @@ -518,7 +532,7 @@ def AddType(templated_types): elif token.name == '&': reference = True elif token.name == '[': - pointer = True + pointer = True elif token.name == ']': pass else: @@ -576,7 +590,7 @@ def DeclarationToParts(self, parts, needs_name_removed): elif p.name not in ('*', '&', '>'): # Ensure that names have a space between them. if (type_name and type_name[-1].token_type == tokenize.NAME and - p.token_type == tokenize.NAME): + p.token_type == tokenize.NAME): type_name.append(tokenize.Token(tokenize.SYNTAX, ' ', 0, 0)) type_name.append(p) else: @@ -652,7 +666,7 @@ def CreateReturnType(self, return_type_seq): start = return_type_seq[0].start end = return_type_seq[-1].end _, name, templated_types, modifiers, default, other_tokens = \ - self.DeclarationToParts(return_type_seq, False) + self.DeclarationToParts(return_type_seq, False) names = [n.name for n in other_tokens] reference = '&' in names pointer = '*' in names @@ -816,7 +830,7 @@ def _GenerateOne(self, token): # self.in_class can contain A::Name, but the dtor will only # be Name. Make sure to compare against the right value. if (token.token_type == tokenize.NAME and - token.name == self.in_class_name_only): + token.name == self.in_class_name_only): return self._GetMethod([token], FUNCTION_DTOR, None, True) # TODO(nnorwitz): handle a lot more syntax. elif token.token_type == tokenize.PREPROCESSOR: @@ -929,7 +943,10 @@ def GetScope(self): def _GetNextToken(self): if self.token_queue: return self.token_queue.pop() - return next(self.tokens) + try: + return next(self.tokens) + except StopIteration: + return def _AddBackToken(self, token): if token.whence == tokenize.WHENCE_STREAM: @@ -1129,7 +1146,7 @@ def _GetMethod(self, return_type_and_name, modifiers, templated_types, # Looks like we got a method, not a function. if len(return_type) > 2 and return_type[-1].name == '::': return_type, in_class = \ - self._GetReturnTypeAndClassName(return_type) + self._GetReturnTypeAndClassName(return_type) return Method(indices.start, indices.end, name.name, in_class, return_type, parameters, modifiers, templated_types, body, self.namespace_stack) @@ -1374,7 +1391,7 @@ def handle_delete(self): def handle_typedef(self): token = self._GetNextToken() if (token.token_type == tokenize.NAME and - keywords.IsKeyword(token.name)): + keywords.IsKeyword(token.name)): # Token must be struct/enum/union/class. method = getattr(self, 'handle_' + token.name) self._handling_typedef = True @@ -1397,7 +1414,7 @@ def handle_typedef(self): if name.name == ')': # HACK(nnorwitz): Handle pointers to functions "properly". if (len(tokens) >= 4 and - tokens[1].name == '(' and tokens[2].name == '*'): + tokens[1].name == '(' and tokens[2].name == '*'): tokens.append(name) name = tokens[3] elif name.name == ']': diff --git a/googlemock/scripts/generator/cpp/gmock_class.py b/googlemock/scripts/generator/cpp/gmock_class.py index 86dcedbfc7..ce30d0c945 100755 --- a/googlemock/scripts/generator/cpp/gmock_class.py +++ b/googlemock/scripts/generator/cpp/gmock_class.py @@ -50,10 +50,11 @@ # Preserve compatibility with Python 2.3. try: - _dummy = set + _dummy = set except NameError: - import sets - set = sets.Set + import sets + + set = sets.Set _VERSION = (1, 0, 1) # The version of this script. # How many spaces to indent. Can set me with the INDENT environment variable. @@ -61,7 +62,7 @@ def _RenderType(ast_type): - """Renders the potentially recursively templated type into a string. + """Renders the potentially recursively templated type into a string. Args: ast_type: The AST of the type. @@ -70,198 +71,193 @@ def _RenderType(ast_type): Rendered string and a boolean to indicate whether we have multiple args (which is not handled correctly). """ - has_multiarg_error = False - # Add modifiers like 'const'. - modifiers = '' - if ast_type.modifiers: - modifiers = ' '.join(ast_type.modifiers) + ' ' - return_type = modifiers + ast_type.name - if ast_type.templated_types: - # Collect template args. - template_args = [] - for arg in ast_type.templated_types: - rendered_arg, e = _RenderType(arg) - if e: has_multiarg_error = True - template_args.append(rendered_arg) - return_type += '<' + ', '.join(template_args) + '>' - # We are actually not handling multi-template-args correctly. So mark it. - if len(template_args) > 1: - has_multiarg_error = True - if ast_type.pointer: - return_type += '*' - if ast_type.reference: - return_type += '&' - return return_type, has_multiarg_error + has_multiarg_error = False + # Add modifiers like 'const'. + modifiers = '' + if ast_type.modifiers: + modifiers = ' '.join(ast_type.modifiers) + ' ' + return_type = modifiers + ast_type.name + if ast_type.templated_types: + # Collect template args. + template_args = [] + for arg in ast_type.templated_types: + rendered_arg, e = _RenderType(arg) + if e: has_multiarg_error = True + template_args.append(rendered_arg) + return_type += '<' + ', '.join(template_args) + '>' + # We are actually not handling multi-template-args correctly. So mark it. + if len(template_args) > 1: + has_multiarg_error = True + if ast_type.pointer: + return_type += '*' + if ast_type.reference: + return_type += '&' + return return_type, has_multiarg_error def _GetNumParameters(parameters, source): - num_parameters = len(parameters) - if num_parameters == 1: - first_param = parameters[0] - if source[first_param.start:first_param.end].strip() == 'void': - # We must treat T(void) as a function with no parameters. - return 0 - return num_parameters + num_parameters = len(parameters) + if num_parameters == 1: + first_param = parameters[0] + if source[first_param.start:first_param.end].strip() == 'void': + # We must treat T(void) as a function with no parameters. + return 0 + return num_parameters def _GenerateMethods(output_lines, source, class_node): - function_type = (ast.FUNCTION_VIRTUAL | ast.FUNCTION_PURE_VIRTUAL | - ast.FUNCTION_OVERRIDE) - ctor_or_dtor = ast.FUNCTION_CTOR | ast.FUNCTION_DTOR - indent = ' ' * _INDENT - - for node in class_node.body: - # We only care about virtual functions. - if (isinstance(node, ast.Function) and - node.modifiers & function_type and - not node.modifiers & ctor_or_dtor): - # Pick out all the elements we need from the original function. - const = '' - if node.modifiers & ast.FUNCTION_CONST: - const = 'CONST_' - num_parameters = _GetNumParameters(node.parameters, source) - return_type = 'void' - if node.return_type: - return_type, has_multiarg_error = _RenderType(node.return_type) - if has_multiarg_error: - for line in [ - '// The following line won\'t really compile, as the return', - '// type has multiple template arguments. To fix it, use a', - '// typedef for the return type.']: - output_lines.append(indent + line) - tmpl = '' - if class_node.templated_types: - tmpl = '_T' - mock_method_macro = 'MOCK_%sMETHOD%d%s' % (const, num_parameters, tmpl) - - args = '' - if node.parameters: - # Due to the parser limitations, it is impossible to keep comments - # while stripping the default parameters. When defaults are - # present, we choose to strip them and comments (and produce - # compilable code). - # TODO(nnorwitz@google.com): Investigate whether it is possible to - # preserve parameter name when reconstructing parameter text from - # the AST. - if len([param for param in node.parameters if param.default]) > 0: - args = ', '.join(param.type.name for param in node.parameters) - else: - # Get the full text of the parameters from the start - # of the first parameter to the end of the last parameter. - start = node.parameters[0].start - end = node.parameters[-1].end - # Remove // comments. - args_strings = re.sub(r'//.*', '', source[start:end]) - # Condense multiple spaces and eliminate newlines putting the - # parameters together on a single line. Ensure there is a - # space in an argument which is split by a newline without - # intervening whitespace, e.g.: int\nBar - args = re.sub(' +', ' ', args_strings.replace('\n', ' ')) - - # Create the mock method definition. - output_lines.extend(['%s%s(%s,' % (indent, mock_method_macro, node.name), - '%s%s(%s));' % (indent*3, return_type, args)]) + function_type = (ast.FUNCTION_VIRTUAL | ast.FUNCTION_PURE_VIRTUAL | + ast.FUNCTION_OVERRIDE) + ctor_or_dtor = ast.FUNCTION_CTOR | ast.FUNCTION_DTOR + indent = ' ' * _INDENT + + for node in class_node.body: + # We only care about virtual functions. + if (isinstance(node, ast.Function) and + node.modifiers & function_type and + not node.modifiers & ctor_or_dtor): + # Pick out all the elements we need from the original function. + const = '' + if node.modifiers & ast.FUNCTION_CONST: + const = 'CONST_' + num_parameters = _GetNumParameters(node.parameters, source) + return_type = 'void' + if node.return_type: + return_type, has_multiarg_error = _RenderType(node.return_type) + if has_multiarg_error: + for line in [ + '// The following line won\'t really compile, as the return', + '// type has multiple template arguments. To fix it, use a', + '// typedef for the return type.']: + output_lines.append(indent + line) + tmpl = '' + if class_node.templated_types: + tmpl = '_T' + mock_method_macro = 'MOCK_%sMETHOD%d%s' % (const, num_parameters, tmpl) + + args = '' + if node.parameters: + # Get the full text of the parameters from the start + # of the first parameter to the end of the last parameter. + start = node.parameters[0].start + end = node.parameters[-1].end + # Remove // comments. + args_strings = re.sub(r'//.*', '', source[start:end]) + # Remove /* comments */. + args_strings = re.sub(r'/\*.*\*/', '', args_strings) + # Remove default arguments. + args_strings = re.sub(r'=.*,', ',', args_strings) + args_strings = re.sub(r'=.*', '', args_strings) + # Condense multiple spaces and eliminate newlines putting the + # parameters together on a single line. Ensure there is a + # space in an argument which is split by a newline without + # intervening whitespace, e.g.: int\nBar + args = re.sub(' +', ' ', args_strings.replace('\n', ' ')) + + # Create the mock method definition. + output_lines.extend(['%s%s(%s,' % (indent, mock_method_macro, node.name), + '%s%s(%s));' % (indent * 3, return_type, args)]) def _GenerateMocks(filename, source, ast_list, desired_class_names): - processed_class_names = set() - lines = [] - for node in ast_list: - if (isinstance(node, ast.Class) and node.body and - # desired_class_names being None means that all classes are selected. - (not desired_class_names or node.name in desired_class_names)): - class_name = node.name - parent_name = class_name - processed_class_names.add(class_name) - class_node = node - # Add namespace before the class. - if class_node.namespace: - lines.extend(['namespace %s {' % n for n in class_node.namespace]) # } - lines.append('') - - # Add template args for templated classes. - if class_node.templated_types: - # TODO(paulchang): The AST doesn't preserve template argument order, - # so we have to make up names here. - # TODO(paulchang): Handle non-type template arguments (e.g. - # template). - template_arg_count = len(class_node.templated_types.keys()) - template_args = ['T%d' % n for n in range(template_arg_count)] - template_decls = ['typename ' + arg for arg in template_args] - lines.append('template <' + ', '.join(template_decls) + '>') - parent_name += '<' + ', '.join(template_args) + '>' - - # Add the class prolog. - lines.append('class Mock%s : public %s {' # } - % (class_name, parent_name)) - lines.append('%spublic:' % (' ' * (_INDENT // 2))) - - # Add all the methods. - _GenerateMethods(lines, source, class_node) - - # Close the class. - if lines: - # If there are no virtual methods, no need for a public label. - if len(lines) == 2: - del lines[-1] - - # Only close the class if there really is a class. - lines.append('};') - lines.append('') # Add an extra newline. - - # Close the namespace. - if class_node.namespace: - for i in range(len(class_node.namespace)-1, -1, -1): - lines.append('} // namespace %s' % class_node.namespace[i]) - lines.append('') # Add an extra newline. - - if desired_class_names: - missing_class_name_list = list(desired_class_names - processed_class_names) - if missing_class_name_list: - missing_class_name_list.sort() - sys.stderr.write('Class(es) not found in %s: %s\n' % - (filename, ', '.join(missing_class_name_list))) - elif not processed_class_names: - sys.stderr.write('No class found in %s\n' % filename) - - return lines + processed_class_names = set() + lines = [] + for node in ast_list: + if (isinstance(node, ast.Class) and node.body and + # desired_class_names being None means that all classes are selected. + (not desired_class_names or node.name in desired_class_names)): + class_name = node.name + parent_name = class_name + processed_class_names.add(class_name) + class_node = node + # Add namespace before the class. + if class_node.namespace: + lines.extend(['namespace %s {' % n for n in class_node.namespace]) # } + lines.append('') + + # Add template args for templated classes. + if class_node.templated_types: + # TODO(paulchang): The AST doesn't preserve template argument order, + # so we have to make up names here. + # TODO(paulchang): Handle non-type template arguments (e.g. + # template). + template_arg_count = len(class_node.templated_types.keys()) + template_args = ['T%d' % n for n in range(template_arg_count)] + template_decls = ['typename ' + arg for arg in template_args] + lines.append('template <' + ', '.join(template_decls) + '>') + parent_name += '<' + ', '.join(template_args) + '>' + + # Add the class prolog. + lines.append('class Mock%s : public %s {' # } + % (class_name, parent_name)) + lines.append('%spublic:' % (' ' * (_INDENT // 2))) + + # Add all the methods. + _GenerateMethods(lines, source, class_node) + + # Close the class. + if lines: + # If there are no virtual methods, no need for a public label. + if len(lines) == 2: + del lines[-1] + + # Only close the class if there really is a class. + lines.append('};') + lines.append('') # Add an extra newline. + + # Close the namespace. + if class_node.namespace: + for i in range(len(class_node.namespace) - 1, -1, -1): + lines.append('} // namespace %s' % class_node.namespace[i]) + lines.append('') # Add an extra newline. + + if desired_class_names: + missing_class_name_list = list(desired_class_names - processed_class_names) + if missing_class_name_list: + missing_class_name_list.sort() + sys.stderr.write('Class(es) not found in %s: %s\n' % + (filename, ', '.join(missing_class_name_list))) + elif not processed_class_names: + sys.stderr.write('No class found in %s\n' % filename) + + return lines def main(argv=sys.argv): - if len(argv) < 2: - sys.stderr.write('Google Mock Class Generator v%s\n\n' % - '.'.join(map(str, _VERSION))) - sys.stderr.write(__doc__) - return 1 - - global _INDENT - try: - _INDENT = int(os.environ['INDENT']) - except KeyError: - pass - except: - sys.stderr.write('Unable to use indent of %s\n' % os.environ.get('INDENT')) - - filename = argv[1] - desired_class_names = None # None means all classes in the source file. - if len(argv) >= 3: - desired_class_names = set(argv[2:]) - source = utils.ReadFile(filename) - if source is None: - return 1 - - builder = ast.BuilderFromSource(source, filename) - try: - entire_ast = filter(None, builder.Generate()) - except KeyboardInterrupt: - return - except: - # An error message was already printed since we couldn't parse. - sys.exit(1) - else: - lines = _GenerateMocks(filename, source, entire_ast, desired_class_names) - sys.stdout.write('\n'.join(lines)) + if len(argv) < 2: + sys.stderr.write('Google Mock Class Generator v%s\n\n' % + '.'.join(map(str, _VERSION))) + sys.stderr.write(__doc__) + return 1 + + global _INDENT + try: + _INDENT = int(os.environ['INDENT']) + except KeyError: + pass + except: + sys.stderr.write('Unable to use indent of %s\n' % os.environ.get('INDENT')) + + filename = argv[1] + desired_class_names = None # None means all classes in the source file. + if len(argv) >= 3: + desired_class_names = set(argv[2:]) + source = utils.ReadFile(filename) + if source is None: + return 1 + + builder = ast.BuilderFromSource(source, filename) + try: + entire_ast = filter(None, builder.Generate()) + except KeyboardInterrupt: + return + except: + # An error message was already printed since we couldn't parse. + sys.exit(1) + else: + lines = _GenerateMocks(filename, source, entire_ast, desired_class_names) + sys.stdout.write('\n'.join(lines)) if __name__ == '__main__': - main(sys.argv) + main(sys.argv) diff --git a/googlemock/scripts/generator/cpp/gmock_class_test.py b/googlemock/scripts/generator/cpp/gmock_class_test.py index 0505162627..bd12f7ee5f 100755 --- a/googlemock/scripts/generator/cpp/gmock_class_test.py +++ b/googlemock/scripts/generator/cpp/gmock_class_test.py @@ -43,41 +43,43 @@ class TestCase(unittest.TestCase): - """Helper class that adds assert methods.""" + """Helper class that adds assert methods.""" - def StripLeadingWhitespace(self, lines): - """Strip leading whitespace in each line in 'lines'.""" - return '\n'.join([s.lstrip() for s in lines.split('\n')]) + @staticmethod + def StripLeadingWhitespace(lines): + """Strip leading whitespace in each line in 'lines'.""" + return '\n'.join([s.lstrip() for s in lines.split('\n')]) - def assertEqualIgnoreLeadingWhitespace(self, expected_lines, lines): - """Specialized assert that ignores the indent level.""" - self.assertEqual(expected_lines, self.StripLeadingWhitespace(lines)) + def assertEqualIgnoreLeadingWhitespace(self, expected_lines, lines): + """Specialized assert that ignores the indent level.""" + self.assertEqual(expected_lines, self.StripLeadingWhitespace(lines)) class GenerateMethodsTest(TestCase): - def GenerateMethodSource(self, cpp_source): - """Convert C++ source to Google Mock output source lines.""" - method_source_lines = [] - # is a pseudo-filename, it is not read or written. - builder = ast.BuilderFromSource(cpp_source, '') - ast_list = list(builder.Generate()) - gmock_class._GenerateMethods(method_source_lines, cpp_source, ast_list[0]) - return '\n'.join(method_source_lines) - - def testSimpleMethod(self): - source = """ + @staticmethod + def GenerateMethodSource(cpp_source): + """Convert C++ source to Google Mock output source lines.""" + method_source_lines = [] + # is a pseudo-filename, it is not read or written. + builder = ast.BuilderFromSource(cpp_source, '') + ast_list = list(builder.Generate()) + gmock_class._GenerateMethods(method_source_lines, cpp_source, ast_list[0]) + return '\n'.join(method_source_lines) + + def testSimpleMethod(self): + source = """ class Foo { public: virtual int Bar(); }; """ - self.assertEqualIgnoreLeadingWhitespace( - 'MOCK_METHOD0(Bar,\nint());', - self.GenerateMethodSource(source)) + self.assertEqualIgnoreLeadingWhitespace( + 'MOCK_METHOD0(Bar,\nint());', + self.GenerateMethodSource(source)) - def testSimpleConstructorsAndDestructor(self): - source = """ + def testSimpleConstructorsAndDestructor(self): + source = """ class Foo { public: Foo(); @@ -88,26 +90,26 @@ class Foo { virtual int Bar() = 0; }; """ - # The constructors and destructor should be ignored. - self.assertEqualIgnoreLeadingWhitespace( - 'MOCK_METHOD0(Bar,\nint());', - self.GenerateMethodSource(source)) + # The constructors and destructor should be ignored. + self.assertEqualIgnoreLeadingWhitespace( + 'MOCK_METHOD0(Bar,\nint());', + self.GenerateMethodSource(source)) - def testVirtualDestructor(self): - source = """ + def testVirtualDestructor(self): + source = """ class Foo { public: virtual ~Foo(); virtual int Bar() = 0; }; """ - # The destructor should be ignored. - self.assertEqualIgnoreLeadingWhitespace( - 'MOCK_METHOD0(Bar,\nint());', - self.GenerateMethodSource(source)) + # The destructor should be ignored. + self.assertEqualIgnoreLeadingWhitespace( + 'MOCK_METHOD0(Bar,\nint());', + self.GenerateMethodSource(source)) - def testExplicitlyDefaultedConstructorsAndDestructor(self): - source = """ + def testExplicitlyDefaultedConstructorsAndDestructor(self): + source = """ class Foo { public: Foo() = default; @@ -117,13 +119,13 @@ class Foo { virtual int Bar() = 0; }; """ - # The constructors and destructor should be ignored. - self.assertEqualIgnoreLeadingWhitespace( - 'MOCK_METHOD0(Bar,\nint());', - self.GenerateMethodSource(source)) + # The constructors and destructor should be ignored. + self.assertEqualIgnoreLeadingWhitespace( + 'MOCK_METHOD0(Bar,\nint());', + self.GenerateMethodSource(source)) - def testExplicitlyDeletedConstructorsAndDestructor(self): - source = """ + def testExplicitlyDeletedConstructorsAndDestructor(self): + source = """ class Foo { public: Foo() = delete; @@ -133,92 +135,121 @@ class Foo { virtual int Bar() = 0; }; """ - # The constructors and destructor should be ignored. - self.assertEqualIgnoreLeadingWhitespace( - 'MOCK_METHOD0(Bar,\nint());', - self.GenerateMethodSource(source)) + # The constructors and destructor should be ignored. + self.assertEqualIgnoreLeadingWhitespace( + 'MOCK_METHOD0(Bar,\nint());', + self.GenerateMethodSource(source)) - def testSimpleOverrideMethod(self): - source = """ + def testSimpleOverrideMethod(self): + source = """ class Foo { public: int Bar() override; }; """ - self.assertEqualIgnoreLeadingWhitespace( - 'MOCK_METHOD0(Bar,\nint());', - self.GenerateMethodSource(source)) + self.assertEqualIgnoreLeadingWhitespace( + 'MOCK_METHOD0(Bar,\nint());', + self.GenerateMethodSource(source)) - def testSimpleConstMethod(self): - source = """ + def testSimpleConstMethod(self): + source = """ class Foo { public: virtual void Bar(bool flag) const; }; """ - self.assertEqualIgnoreLeadingWhitespace( - 'MOCK_CONST_METHOD1(Bar,\nvoid(bool flag));', - self.GenerateMethodSource(source)) + self.assertEqualIgnoreLeadingWhitespace( + 'MOCK_CONST_METHOD1(Bar,\nvoid(bool flag));', + self.GenerateMethodSource(source)) - def testExplicitVoid(self): - source = """ + def testExplicitVoid(self): + source = """ class Foo { public: virtual int Bar(void); }; """ - self.assertEqualIgnoreLeadingWhitespace( - 'MOCK_METHOD0(Bar,\nint(void));', - self.GenerateMethodSource(source)) + self.assertEqualIgnoreLeadingWhitespace( + 'MOCK_METHOD0(Bar,\nint(void));', + self.GenerateMethodSource(source)) - def testStrangeNewlineInParameter(self): - source = """ + def testStrangeNewlineInParameter(self): + source = """ class Foo { public: virtual void Bar(int a) = 0; }; """ - self.assertEqualIgnoreLeadingWhitespace( - 'MOCK_METHOD1(Bar,\nvoid(int a));', - self.GenerateMethodSource(source)) + self.assertEqualIgnoreLeadingWhitespace( + 'MOCK_METHOD1(Bar,\nvoid(int a));', + self.GenerateMethodSource(source)) - def testDefaultParameters(self): - source = """ + def testDefaultParameters(self): + source = """ class Foo { public: virtual void Bar(int a, char c = 'x') = 0; }; """ - self.assertEqualIgnoreLeadingWhitespace( - 'MOCK_METHOD2(Bar,\nvoid(int, char));', - self.GenerateMethodSource(source)) + self.assertEqualIgnoreLeadingWhitespace( + 'MOCK_METHOD2(Bar,\nvoid(int a, char c ));', + self.GenerateMethodSource(source)) - def testMultipleDefaultParameters(self): - source = """ + def testMultipleDefaultParameters(self): + source = """ class Foo { public: - virtual void Bar(int a = 42, char c = 'x') = 0; + virtual void Bar( + int a = 42, + char c = 'x', + const int* const p = nullptr, + const std::string& s = "42", + char tab[] = {'4','2'}, + int const *& rp = aDefaultPointer) = 0; +}; +""" + self.assertEqualIgnoreLeadingWhitespace( + "MOCK_METHOD7(Bar,\n" + "void(int a , char c , const int* const p , const std::string& s , char tab[] , int const *& rp ));", + self.GenerateMethodSource(source)) + + def testConstDefaultParameter(self): + source = """ +class Test { + public: + virtual bool Bar(const int test_arg = 42) = 0; +}; +""" + expected = 'MOCK_METHOD1(Bar,\nbool(const int test_arg ));' + self.assertEqualIgnoreLeadingWhitespace( + expected, self.GenerateMethodSource(source)) + + def testConstRefDefaultParameter(self): + source = """ +class Test { + public: + virtual bool Bar(const std::string& test_arg = "42" ) = 0; }; """ - self.assertEqualIgnoreLeadingWhitespace( - 'MOCK_METHOD2(Bar,\nvoid(int, char));', - self.GenerateMethodSource(source)) + expected = 'MOCK_METHOD1(Bar,\nbool(const std::string& test_arg ));' + self.assertEqualIgnoreLeadingWhitespace( + expected, self.GenerateMethodSource(source)) - def testRemovesCommentsWhenDefaultsArePresent(self): - source = """ + def testRemovesCommentsWhenDefaultsArePresent(self): + source = """ class Foo { public: virtual void Bar(int a = 42 /* a comment */, char /* other comment */ c= 'x') = 0; }; """ - self.assertEqualIgnoreLeadingWhitespace( - 'MOCK_METHOD2(Bar,\nvoid(int, char));', - self.GenerateMethodSource(source)) + self.assertEqualIgnoreLeadingWhitespace( + 'MOCK_METHOD2(Bar,\nvoid(int a , char c));', + self.GenerateMethodSource(source)) - def testDoubleSlashCommentsInParameterListAreRemoved(self): - source = """ + def testDoubleSlashCommentsInParameterListAreRemoved(self): + source = """ class Foo { public: virtual void Bar(int a, // inline comments should be elided. @@ -226,116 +257,117 @@ class Foo { ) const = 0; }; """ - self.assertEqualIgnoreLeadingWhitespace( - 'MOCK_CONST_METHOD2(Bar,\nvoid(int a, int b));', - self.GenerateMethodSource(source)) + self.assertEqualIgnoreLeadingWhitespace( + 'MOCK_CONST_METHOD2(Bar,\nvoid(int a, int b));', + self.GenerateMethodSource(source)) - def testCStyleCommentsInParameterListAreNotRemoved(self): - # NOTE(nnorwitz): I'm not sure if it's the best behavior to keep these - # comments. Also note that C style comments after the last parameter - # are still elided. - source = """ + def testCStyleCommentsInParameterListAreNotRemoved(self): + # NOTE(nnorwitz): I'm not sure if it's the best behavior to keep these + # comments. Also note that C style comments after the last parameter + # are still elided. + source = """ class Foo { public: virtual const string& Bar(int /* keeper */, int b); }; """ - self.assertEqualIgnoreLeadingWhitespace( - 'MOCK_METHOD2(Bar,\nconst string&(int /* keeper */, int b));', - self.GenerateMethodSource(source)) + self.assertEqualIgnoreLeadingWhitespace( + 'MOCK_METHOD2(Bar,\nconst string&(int , int b));', + self.GenerateMethodSource(source)) - def testArgsOfTemplateTypes(self): - source = """ + def testArgsOfTemplateTypes(self): + source = """ class Foo { public: virtual int Bar(const vector& v, map* output); };""" - self.assertEqualIgnoreLeadingWhitespace( - 'MOCK_METHOD2(Bar,\n' - 'int(const vector& v, map* output));', - self.GenerateMethodSource(source)) + self.assertEqualIgnoreLeadingWhitespace( + 'MOCK_METHOD2(Bar,\n' + 'int(const vector& v, map* output));', + self.GenerateMethodSource(source)) - def testReturnTypeWithOneTemplateArg(self): - source = """ + def testReturnTypeWithOneTemplateArg(self): + source = """ class Foo { public: virtual vector* Bar(int n); };""" - self.assertEqualIgnoreLeadingWhitespace( - 'MOCK_METHOD1(Bar,\nvector*(int n));', - self.GenerateMethodSource(source)) + self.assertEqualIgnoreLeadingWhitespace( + 'MOCK_METHOD1(Bar,\nvector*(int n));', + self.GenerateMethodSource(source)) - def testReturnTypeWithManyTemplateArgs(self): - source = """ + def testReturnTypeWithManyTemplateArgs(self): + source = """ class Foo { public: virtual map Bar(); };""" - # Comparing the comment text is brittle - we'll think of something - # better in case this gets annoying, but for now let's keep it simple. - self.assertEqualIgnoreLeadingWhitespace( - '// The following line won\'t really compile, as the return\n' - '// type has multiple template arguments. To fix it, use a\n' - '// typedef for the return type.\n' - 'MOCK_METHOD0(Bar,\nmap());', - self.GenerateMethodSource(source)) - - def testSimpleMethodInTemplatedClass(self): - source = """ + # Comparing the comment text is brittle - we'll think of something + # better in case this gets annoying, but for now let's keep it simple. + self.assertEqualIgnoreLeadingWhitespace( + '// The following line won\'t really compile, as the return\n' + '// type has multiple template arguments. To fix it, use a\n' + '// typedef for the return type.\n' + 'MOCK_METHOD0(Bar,\nmap());', + self.GenerateMethodSource(source)) + + def testSimpleMethodInTemplatedClass(self): + source = """ template class Foo { public: virtual int Bar(); }; """ - self.assertEqualIgnoreLeadingWhitespace( - 'MOCK_METHOD0_T(Bar,\nint());', - self.GenerateMethodSource(source)) + self.assertEqualIgnoreLeadingWhitespace( + 'MOCK_METHOD0_T(Bar,\nint());', + self.GenerateMethodSource(source)) - def testPointerArgWithoutNames(self): - source = """ + def testPointerArgWithoutNames(self): + source = """ class Foo { virtual int Bar(C*); }; """ - self.assertEqualIgnoreLeadingWhitespace( - 'MOCK_METHOD1(Bar,\nint(C*));', - self.GenerateMethodSource(source)) + self.assertEqualIgnoreLeadingWhitespace( + 'MOCK_METHOD1(Bar,\nint(C*));', + self.GenerateMethodSource(source)) - def testReferenceArgWithoutNames(self): - source = """ + def testReferenceArgWithoutNames(self): + source = """ class Foo { virtual int Bar(C&); }; """ - self.assertEqualIgnoreLeadingWhitespace( - 'MOCK_METHOD1(Bar,\nint(C&));', - self.GenerateMethodSource(source)) + self.assertEqualIgnoreLeadingWhitespace( + 'MOCK_METHOD1(Bar,\nint(C&));', + self.GenerateMethodSource(source)) - def testArrayArgWithoutNames(self): - source = """ + def testArrayArgWithoutNames(self): + source = """ class Foo { virtual int Bar(C[]); }; """ - self.assertEqualIgnoreLeadingWhitespace( - 'MOCK_METHOD1(Bar,\nint(C[]));', - self.GenerateMethodSource(source)) + self.assertEqualIgnoreLeadingWhitespace( + 'MOCK_METHOD1(Bar,\nint(C[]));', + self.GenerateMethodSource(source)) class GenerateMocksTest(TestCase): - def GenerateMocks(self, cpp_source): - """Convert C++ source to complete Google Mock output source.""" - # is a pseudo-filename, it is not read or written. - filename = '' - builder = ast.BuilderFromSource(cpp_source, filename) - ast_list = list(builder.Generate()) - lines = gmock_class._GenerateMocks(filename, cpp_source, ast_list, None) - return '\n'.join(lines) - - def testNamespaces(self): - source = """ + @staticmethod + def GenerateMocks(cpp_source): + """Convert C++ source to complete Google Mock output source.""" + # is a pseudo-filename, it is not read or written. + filename = '' + builder = ast.BuilderFromSource(cpp_source, filename) + ast_list = list(builder.Generate()) + lines = gmock_class._GenerateMocks(filename, cpp_source, ast_list, None) + return '\n'.join(lines) + + def testNamespaces(self): + source = """ namespace Foo { namespace Bar { class Forward; } namespace Baz { @@ -348,7 +380,7 @@ class Test { } // namespace Baz } // namespace Foo """ - expected = """\ + expected = """\ namespace Foo { namespace Baz { @@ -361,53 +393,53 @@ class MockTest : public Test { } // namespace Baz } // namespace Foo """ - self.assertEqualIgnoreLeadingWhitespace( - expected, self.GenerateMocks(source)) + self.assertEqualIgnoreLeadingWhitespace( + expected, self.GenerateMocks(source)) - def testClassWithStorageSpecifierMacro(self): - source = """ + def testClassWithStorageSpecifierMacro(self): + source = """ class STORAGE_SPECIFIER Test { public: virtual void Foo(); }; """ - expected = """\ + expected = """\ class MockTest : public Test { public: MOCK_METHOD0(Foo, void()); }; """ - self.assertEqualIgnoreLeadingWhitespace( - expected, self.GenerateMocks(source)) + self.assertEqualIgnoreLeadingWhitespace( + expected, self.GenerateMocks(source)) - def testTemplatedForwardDeclaration(self): - source = """ + def testTemplatedForwardDeclaration(self): + source = """ template class Forward; // Forward declaration should be ignored. class Test { public: virtual void Foo(); }; """ - expected = """\ + expected = """\ class MockTest : public Test { public: MOCK_METHOD0(Foo, void()); }; """ - self.assertEqualIgnoreLeadingWhitespace( - expected, self.GenerateMocks(source)) + self.assertEqualIgnoreLeadingWhitespace( + expected, self.GenerateMocks(source)) - def testTemplatedClass(self): - source = """ + def testTemplatedClass(self): + source = """ template class Test { public: virtual void Foo(); }; """ - expected = """\ + expected = """\ template class MockTest : public Test { public: @@ -415,29 +447,29 @@ class MockTest : public Test { void()); }; """ - self.assertEqualIgnoreLeadingWhitespace( - expected, self.GenerateMocks(source)) + self.assertEqualIgnoreLeadingWhitespace( + expected, self.GenerateMocks(source)) - def testTemplateInATemplateTypedef(self): - source = """ + def testTemplateInATemplateTypedef(self): + source = """ class Test { public: typedef std::vector> FooType; virtual void Bar(const FooType& test_arg); }; """ - expected = """\ + expected = """\ class MockTest : public Test { public: MOCK_METHOD1(Bar, void(const FooType& test_arg)); }; """ - self.assertEqualIgnoreLeadingWhitespace( - expected, self.GenerateMocks(source)) + self.assertEqualIgnoreLeadingWhitespace( + expected, self.GenerateMocks(source)) - def testTemplateInATemplateTypedefWithComma(self): - source = """ + def testTemplateInATemplateTypedefWithComma(self): + source = """ class Test { public: typedef std::function foo) : foo_(foo) {} @@ -507,15 +539,16 @@ class Test { std::function foo_; }; """ - expected = """\ + expected = """\ class MockTest : public Test { public: MOCK_METHOD0(foo, std::function()); }; """ - self.assertEqualIgnoreLeadingWhitespace( - expected, self.GenerateMocks(source)) + self.assertEqualIgnoreLeadingWhitespace( + expected, self.GenerateMocks(source)) + if __name__ == '__main__': - unittest.main() + unittest.main() From ba33a8876c3eda4cb8def8e0e90f45930ef8c54f Mon Sep 17 00:00:00 2001 From: misterg Date: Tue, 29 Oct 2019 15:13:11 -0400 Subject: [PATCH 070/541] Googletest export Internal Change PiperOrigin-RevId: 277336786 --- googlemock/scripts/generator/cpp/ast.py | 36 ++++++------------- .../scripts/generator/cpp/gmock_class.py | 35 ++++++------------ .../scripts/generator/cpp/gmock_class_test.py | 36 ++++++------------- googlemock/scripts/generator/cpp/keywords.py | 36 ++++++------------- googlemock/scripts/generator/cpp/tokenize.py | 36 ++++++------------- googlemock/scripts/generator/cpp/utils.py | 36 ++++++------------- googlemock/scripts/generator/gmock_gen.py | 35 ++++++------------ 7 files changed, 75 insertions(+), 175 deletions(-) diff --git a/googlemock/scripts/generator/cpp/ast.py b/googlemock/scripts/generator/cpp/ast.py index 0d0c984ac0..f6331d80b8 100755 --- a/googlemock/scripts/generator/cpp/ast.py +++ b/googlemock/scripts/generator/cpp/ast.py @@ -1,33 +1,19 @@ #!/usr/bin/env python # -# Copyright 2008, Google Inc. -# All rights reserved. +# Copyright 2007 Neal Norwitz +# Portions Copyright 2007 Google Inc. # -# Redistribution and use in source and binary forms, with or without -# modification, are permitted provided that the following conditions are -# met: +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at # -# * 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. +# http://www.apache.org/licenses/LICENSE-2.0 # -# 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. +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. """Generate an Abstract Syntax Tree (AST) for C++.""" diff --git a/googlemock/scripts/generator/cpp/gmock_class.py b/googlemock/scripts/generator/cpp/gmock_class.py index ce30d0c945..89862ae1e1 100755 --- a/googlemock/scripts/generator/cpp/gmock_class.py +++ b/googlemock/scripts/generator/cpp/gmock_class.py @@ -1,33 +1,18 @@ #!/usr/bin/env python # -# Copyright 2008, Google Inc. -# All rights reserved. +# Copyright 2008 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: +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at # -# * 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. +# http://www.apache.org/licenses/LICENSE-2.0 # -# 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. +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. """Generate Google Mock classes from base classes. diff --git a/googlemock/scripts/generator/cpp/gmock_class_test.py b/googlemock/scripts/generator/cpp/gmock_class_test.py index bd12f7ee5f..211a92dd20 100755 --- a/googlemock/scripts/generator/cpp/gmock_class_test.py +++ b/googlemock/scripts/generator/cpp/gmock_class_test.py @@ -1,33 +1,19 @@ #!/usr/bin/env python # -# Copyright 2009, Google Inc. -# All rights reserved. +# Copyright 2009 Neal Norwitz All Rights Reserved. +# Portions Copyright 2009 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: +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at # -# * 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. +# http://www.apache.org/licenses/LICENSE-2.0 # -# 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. +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. """Tests for gmock.scripts.generator.cpp.gmock_class.""" diff --git a/googlemock/scripts/generator/cpp/keywords.py b/googlemock/scripts/generator/cpp/keywords.py index 8b75c2b47c..e4282714dd 100755 --- a/googlemock/scripts/generator/cpp/keywords.py +++ b/googlemock/scripts/generator/cpp/keywords.py @@ -1,33 +1,19 @@ #!/usr/bin/env python # -# Copyright 2007, Google Inc. -# All rights reserved. +# Copyright 2007 Neal Norwitz +# Portions Copyright 2007 Google Inc. # -# Redistribution and use in source and binary forms, with or without -# modification, are permitted provided that the following conditions are -# met: +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at # -# * 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. +# http://www.apache.org/licenses/LICENSE-2.0 # -# 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. +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. """C++ keywords and helper utilities for determining keywords.""" diff --git a/googlemock/scripts/generator/cpp/tokenize.py b/googlemock/scripts/generator/cpp/tokenize.py index c64dcdee8b..a75edcb142 100755 --- a/googlemock/scripts/generator/cpp/tokenize.py +++ b/googlemock/scripts/generator/cpp/tokenize.py @@ -1,33 +1,19 @@ #!/usr/bin/env python # -# Copyright 2007, Google Inc. -# All rights reserved. +# Copyright 2007 Neal Norwitz +# Portions Copyright 2007 Google Inc. # -# Redistribution and use in source and binary forms, with or without -# modification, are permitted provided that the following conditions are -# met: +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at # -# * 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. +# http://www.apache.org/licenses/LICENSE-2.0 # -# 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. +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. """Tokenize C++ source code.""" diff --git a/googlemock/scripts/generator/cpp/utils.py b/googlemock/scripts/generator/cpp/utils.py index 6945a78cc8..6f5fc097b9 100755 --- a/googlemock/scripts/generator/cpp/utils.py +++ b/googlemock/scripts/generator/cpp/utils.py @@ -1,33 +1,19 @@ #!/usr/bin/env python # -# Copyright 2007, Google Inc. -# All rights reserved. +# Copyright 2007 Neal Norwitz +# Portions Copyright 2007 Google Inc. # -# Redistribution and use in source and binary forms, with or without -# modification, are permitted provided that the following conditions are -# met: +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at # -# * 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. +# http://www.apache.org/licenses/LICENSE-2.0 # -# 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. +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. """Generic utilities for C++ parsing.""" diff --git a/googlemock/scripts/generator/gmock_gen.py b/googlemock/scripts/generator/gmock_gen.py index 34a7f887f1..9d528a56d9 100755 --- a/googlemock/scripts/generator/gmock_gen.py +++ b/googlemock/scripts/generator/gmock_gen.py @@ -1,33 +1,18 @@ #!/usr/bin/env python # -# Copyright 2008, Google Inc. -# All rights reserved. +# Copyright 2008 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: +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at # -# * 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. +# http://www.apache.org/licenses/LICENSE-2.0 # -# 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. +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. """Driver for starting up Google Mock class generator.""" From f626deda19e54adaaff1cd0d7b22421f934dec55 Mon Sep 17 00:00:00 2001 From: Ihor Dutchak Date: Tue, 6 Aug 2019 16:22:08 +0300 Subject: [PATCH 071/541] Added special catch for std::exception in GTEST_TEST_NO_THROW_ --- .../include/gtest/internal/gtest-internal.h | 34 +++++++++++++++++-- googletest/test/gtest_unittest.cc | 13 +++++++ 2 files changed, 44 insertions(+), 3 deletions(-) diff --git a/googletest/include/gtest/internal/gtest-internal.h b/googletest/include/gtest/internal/gtest-internal.h index 08531d8c4f..918fd4dd35 100644 --- a/googletest/include/gtest/internal/gtest-internal.h +++ b/googletest/include/gtest/internal/gtest-internal.h @@ -825,6 +825,16 @@ struct GTEST_API_ ConstCharPtr { const char* value; }; +// Helper for declaring std::string within 'if' statement +// in pre C++17 build environment. +struct GTEST_API_ TrueWithString { + TrueWithString() = default; + explicit TrueWithString(const char* str) : value(str) {} + explicit TrueWithString(const std::string& str) : value(str) {} + explicit operator bool() const { return true; } + std::string value; +}; + // A simple Linear Congruential Generator for generating random // numbers with a uniform distribution. Unlike rand() and srand(), it // doesn't use global state (and therefore can't interfere with user @@ -1335,19 +1345,37 @@ constexpr bool InstantiateTypedTestCase_P_IsDeprecated() { return true; } GTEST_CONCAT_TOKEN_(gtest_label_testthrow_, __LINE__): \ fail(gtest_msg.value) +#if GTEST_HAS_EXCEPTIONS + +#define GTEST_TEST_NO_THROW_CATCH_STD_EXCEPTION_() \ + catch (std::exception const& e) { \ + gtest_msg.value = "it throws std::exception-derived exception with description: \""; \ + gtest_msg.value += e.what(); \ + gtest_msg.value += "\"."; \ + goto GTEST_CONCAT_TOKEN_(gtest_label_testnothrow_, __LINE__); \ + } + +#else // GTEST_HAS_EXCEPTIONS + +#define GTEST_TEST_NO_THROW_CATCH_STD_EXCEPTION_() + +#endif // GTEST_HAS_EXCEPTIONS + #define GTEST_TEST_NO_THROW_(statement, fail) \ GTEST_AMBIGUOUS_ELSE_BLOCKER_ \ - if (::testing::internal::AlwaysTrue()) { \ + if (::testing::internal::TrueWithString gtest_msg{}) { \ try { \ GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement); \ } \ + GTEST_TEST_NO_THROW_CATCH_STD_EXCEPTION_() \ catch (...) { \ + gtest_msg.value = "it throws."; \ goto GTEST_CONCAT_TOKEN_(gtest_label_testnothrow_, __LINE__); \ } \ } else \ GTEST_CONCAT_TOKEN_(gtest_label_testnothrow_, __LINE__): \ - fail("Expected: " #statement " doesn't throw an exception.\n" \ - " Actual: it throws.") + fail(("Expected: " #statement " doesn't throw an exception.\n" \ + " Actual: " + gtest_msg.value).c_str()) #define GTEST_TEST_ANY_THROW_(statement, fail) \ GTEST_AMBIGUOUS_ELSE_BLOCKER_ \ diff --git a/googletest/test/gtest_unittest.cc b/googletest/test/gtest_unittest.cc index 2b00b70a8e..2496c59dd9 100644 --- a/googletest/test/gtest_unittest.cc +++ b/googletest/test/gtest_unittest.cc @@ -3351,6 +3351,9 @@ TEST_F(SingleEvaluationTest, OtherCases) { void ThrowAnInteger() { throw 1; } +void ThrowRuntimeError(const char* what) { + throw std::runtime_error(what); +} // Tests that assertion arguments are evaluated exactly once. TEST_F(SingleEvaluationTest, ExceptionTests) { @@ -3830,6 +3833,11 @@ TEST(AssertionTest, ASSERT_NO_THROW) { EXPECT_FATAL_FAILURE(ASSERT_NO_THROW(ThrowAnInteger()), "Expected: ThrowAnInteger() doesn't throw an exception." "\n Actual: it throws."); + EXPECT_FATAL_FAILURE(ASSERT_NO_THROW(ThrowRuntimeError("A description")), + "Expected: ThrowRuntimeError(\"A description\") " + "doesn't throw an exception.\n " + "Actual: it throws std::exception-derived exception " + "with description: \"A description\"."); } // Tests ASSERT_ANY_THROW. @@ -4567,6 +4575,11 @@ TEST(ExpectTest, EXPECT_NO_THROW) { EXPECT_NONFATAL_FAILURE(EXPECT_NO_THROW(ThrowAnInteger()), "Expected: ThrowAnInteger() doesn't throw an " "exception.\n Actual: it throws."); + EXPECT_NONFATAL_FAILURE(EXPECT_NO_THROW(ThrowRuntimeError("A description")), + "Expected: ThrowRuntimeError(\"A description\") " + "doesn't throw an exception.\n " + "Actual: it throws std::exception-derived exception " + "with description: \"A description\"."); } // Tests EXPECT_ANY_THROW. From 0a03480824b4fc7883255dbd2fd8940c9f81e22e Mon Sep 17 00:00:00 2001 From: misterg Date: Wed, 30 Oct 2019 15:08:08 -0400 Subject: [PATCH 072/541] Googletest export Remove outdated unsupported scripts PiperOrigin-RevId: 277556831 --- googlemock/scripts/upload.py | 1402 ---------------------------- googlemock/scripts/upload_gmock.py | 78 -- 2 files changed, 1480 deletions(-) delete mode 100755 googlemock/scripts/upload.py delete mode 100755 googlemock/scripts/upload_gmock.py diff --git a/googlemock/scripts/upload.py b/googlemock/scripts/upload.py deleted file mode 100755 index 129f53ef96..0000000000 --- a/googlemock/scripts/upload.py +++ /dev/null @@ -1,1402 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2009, 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. - -"""Tool for uploading diffs from a version control system to the codereview app. - -Usage summary: upload.py [options] [-- diff_options] - -Diff options are passed to the diff command of the underlying system. - -Supported version control systems: - Git - Mercurial - Subversion - -It is important for Git/Mercurial users to specify a tree/node/branch to diff -against by using the '--rev' option. -""" -# This code is derived from appcfg.py in the App Engine SDK (open source), -# and from ASPN recipe #146306. - -import cookielib -import getpass -import logging -import md5 -import mimetypes -import optparse -import os -import re -import socket -import subprocess -import sys -import urllib -import urllib2 -import urlparse - -try: - import readline -except ImportError: - pass - -# The logging verbosity: -# 0: Errors only. -# 1: Status messages. -# 2: Info logs. -# 3: Debug logs. -verbosity = 1 - -# Max size of patch or base file. -MAX_UPLOAD_SIZE = 900 * 1024 - - -def GetEmail(prompt): - """Prompts the user for their email address and returns it. - - The last used email address is saved to a file and offered up as a suggestion - to the user. If the user presses enter without typing in anything the last - used email address is used. If the user enters a new address, it is saved - for next time we prompt. - - """ - last_email_file_name = os.path.expanduser("~/.last_codereview_email_address") - last_email = "" - if os.path.exists(last_email_file_name): - try: - last_email_file = open(last_email_file_name, "r") - last_email = last_email_file.readline().strip("\n") - last_email_file.close() - prompt += " [%s]" % last_email - except IOError, e: - pass - email = raw_input(prompt + ": ").strip() - if email: - try: - last_email_file = open(last_email_file_name, "w") - last_email_file.write(email) - last_email_file.close() - except IOError, e: - pass - else: - email = last_email - return email - - -def StatusUpdate(msg): - """Print a status message to stdout. - - If 'verbosity' is greater than 0, print the message. - - Args: - msg: The string to print. - """ - if verbosity > 0: - print msg - - -def ErrorExit(msg): - """Print an error message to stderr and exit.""" - print >>sys.stderr, msg - sys.exit(1) - - -class ClientLoginError(urllib2.HTTPError): - """Raised to indicate there was an error authenticating with ClientLogin.""" - - def __init__(self, url, code, msg, headers, args): - urllib2.HTTPError.__init__(self, url, code, msg, headers, None) - self.args = args - self.reason = args["Error"] - - -class AbstractRpcServer(object): - """Provides a common interface for a simple RPC server.""" - - def __init__(self, host, auth_function, host_override=None, extra_headers={}, - save_cookies=False): - """Creates a new HttpRpcServer. - - Args: - host: The host to send requests to. - auth_function: A function that takes no arguments and returns an - (email, password) tuple when called. Will be called if authentication - is required. - host_override: The host header to send to the server (defaults to host). - extra_headers: A dict of extra headers to append to every request. - save_cookies: If True, save the authentication cookies to local disk. - If False, use an in-memory cookiejar instead. Subclasses must - implement this functionality. Defaults to False. - """ - self.host = host - self.host_override = host_override - self.auth_function = auth_function - self.authenticated = False - self.extra_headers = extra_headers - self.save_cookies = save_cookies - self.opener = self._GetOpener() - if self.host_override: - logging.info("Server: %s; Host: %s", self.host, self.host_override) - else: - logging.info("Server: %s", self.host) - - def _GetOpener(self): - """Returns an OpenerDirector for making HTTP requests. - - Returns: - A urllib2.OpenerDirector object. - """ - raise NotImplementedError() - - def _CreateRequest(self, url, data=None): - """Creates a new urllib request.""" - logging.debug("Creating request for: '%s' with payload:\n%s", url, data) - req = urllib2.Request(url, data=data) - if self.host_override: - req.add_header("Host", self.host_override) - for key, value in self.extra_headers.iteritems(): - req.add_header(key, value) - return req - - def _GetAuthToken(self, email, password): - """Uses ClientLogin to authenticate the user, returning an auth token. - - Args: - email: The user's email address - password: The user's password - - Raises: - ClientLoginError: If there was an error authenticating with ClientLogin. - HTTPError: If there was some other form of HTTP error. - - Returns: - The authentication token returned by ClientLogin. - """ - account_type = "GOOGLE" - if self.host.endswith(".google.com"): - # Needed for use inside Google. - account_type = "HOSTED" - req = self._CreateRequest( - url="https://www.google.com/accounts/ClientLogin", - data=urllib.urlencode({ - "Email": email, - "Passwd": password, - "service": "ah", - "source": "rietveld-codereview-upload", - "accountType": account_type, - }), - ) - try: - response = self.opener.open(req) - response_body = response.read() - response_dict = dict(x.split("=") - for x in response_body.split("\n") if x) - return response_dict["Auth"] - except urllib2.HTTPError, e: - if e.code == 403: - body = e.read() - response_dict = dict(x.split("=", 1) for x in body.split("\n") if x) - raise ClientLoginError(req.get_full_url(), e.code, e.msg, - e.headers, response_dict) - else: - raise - - def _GetAuthCookie(self, auth_token): - """Fetches authentication cookies for an authentication token. - - Args: - auth_token: The authentication token returned by ClientLogin. - - Raises: - HTTPError: If there was an error fetching the authentication cookies. - """ - # This is a dummy value to allow us to identify when we're successful. - continue_location = "http://localhost/" - args = {"continue": continue_location, "auth": auth_token} - req = self._CreateRequest("http://%s/_ah/login?%s" % - (self.host, urllib.urlencode(args))) - try: - response = self.opener.open(req) - except urllib2.HTTPError, e: - response = e - if (response.code != 302 or - response.info()["location"] != continue_location): - raise urllib2.HTTPError(req.get_full_url(), response.code, response.msg, - response.headers, response.fp) - self.authenticated = True - - def _Authenticate(self): - """Authenticates the user. - - The authentication process works as follows: - 1) We get a username and password from the user - 2) We use ClientLogin to obtain an AUTH token for the user - (see https://developers.google.com/identity/protocols/AuthForInstalledApps). - 3) We pass the auth token to /_ah/login on the server to obtain an - authentication cookie. If login was successful, it tries to redirect - us to the URL we provided. - - If we attempt to access the upload API without first obtaining an - authentication cookie, it returns a 401 response and directs us to - authenticate ourselves with ClientLogin. - """ - for i in range(3): - credentials = self.auth_function() - try: - auth_token = self._GetAuthToken(credentials[0], credentials[1]) - except ClientLoginError, e: - if e.reason == "BadAuthentication": - print >>sys.stderr, "Invalid username or password." - continue - if e.reason == "CaptchaRequired": - print >>sys.stderr, ( - "Please go to\n" - "https://www.google.com/accounts/DisplayUnlockCaptcha\n" - "and verify you are a human. Then try again.") - break - if e.reason == "NotVerified": - print >>sys.stderr, "Account not verified." - break - if e.reason == "TermsNotAgreed": - print >>sys.stderr, "User has not agreed to TOS." - break - if e.reason == "AccountDeleted": - print >>sys.stderr, "The user account has been deleted." - break - if e.reason == "AccountDisabled": - print >>sys.stderr, "The user account has been disabled." - break - if e.reason == "ServiceDisabled": - print >>sys.stderr, ("The user's access to the service has been " - "disabled.") - break - if e.reason == "ServiceUnavailable": - print >>sys.stderr, "The service is not available; try again later." - break - raise - self._GetAuthCookie(auth_token) - return - - def Send(self, request_path, payload=None, - content_type="application/octet-stream", - timeout=None, - **kwargs): - """Sends an RPC and returns the response. - - Args: - request_path: The path to send the request to, eg /api/appversion/create. - payload: The body of the request, or None to send an empty request. - content_type: The Content-Type header to use. - timeout: timeout in seconds; default None i.e. no timeout. - (Note: for large requests on OS X, the timeout doesn't work right.) - kwargs: Any keyword arguments are converted into query string parameters. - - Returns: - The response body, as a string. - """ - # TODO: Don't require authentication. Let the server say - # whether it is necessary. - if not self.authenticated: - self._Authenticate() - - old_timeout = socket.getdefaulttimeout() - socket.setdefaulttimeout(timeout) - try: - tries = 0 - while True: - tries += 1 - args = dict(kwargs) - url = "http://%s%s" % (self.host, request_path) - if args: - url += "?" + urllib.urlencode(args) - req = self._CreateRequest(url=url, data=payload) - req.add_header("Content-Type", content_type) - try: - f = self.opener.open(req) - response = f.read() - f.close() - return response - except urllib2.HTTPError, e: - if tries > 3: - raise - elif e.code == 401: - self._Authenticate() -## elif e.code >= 500 and e.code < 600: -## # Server Error - try again. -## continue - else: - raise - finally: - socket.setdefaulttimeout(old_timeout) - - -class HttpRpcServer(AbstractRpcServer): - """Provides a simplified RPC-style interface for HTTP requests.""" - - def _Authenticate(self): - """Save the cookie jar after authentication.""" - super(HttpRpcServer, self)._Authenticate() - if self.save_cookies: - StatusUpdate("Saving authentication cookies to %s" % self.cookie_file) - self.cookie_jar.save() - - def _GetOpener(self): - """Returns an OpenerDirector that supports cookies and ignores redirects. - - Returns: - A urllib2.OpenerDirector object. - """ - opener = urllib2.OpenerDirector() - opener.add_handler(urllib2.ProxyHandler()) - opener.add_handler(urllib2.UnknownHandler()) - opener.add_handler(urllib2.HTTPHandler()) - opener.add_handler(urllib2.HTTPDefaultErrorHandler()) - opener.add_handler(urllib2.HTTPSHandler()) - opener.add_handler(urllib2.HTTPErrorProcessor()) - if self.save_cookies: - self.cookie_file = os.path.expanduser("~/.codereview_upload_cookies") - self.cookie_jar = cookielib.MozillaCookieJar(self.cookie_file) - if os.path.exists(self.cookie_file): - try: - self.cookie_jar.load() - self.authenticated = True - StatusUpdate("Loaded authentication cookies from %s" % - self.cookie_file) - except (cookielib.LoadError, IOError): - # Failed to load cookies - just ignore them. - pass - else: - # Create an empty cookie file with mode 600 - fd = os.open(self.cookie_file, os.O_CREAT, 0600) - os.close(fd) - # Always chmod the cookie file - os.chmod(self.cookie_file, 0600) - else: - # Don't save cookies across runs of update.py. - self.cookie_jar = cookielib.CookieJar() - opener.add_handler(urllib2.HTTPCookieProcessor(self.cookie_jar)) - return opener - - -parser = optparse.OptionParser(usage="%prog [options] [-- diff_options]") -parser.add_option("-y", "--assume_yes", action="store_true", - dest="assume_yes", default=False, - help="Assume that the answer to yes/no questions is 'yes'.") -# Logging -group = parser.add_option_group("Logging options") -group.add_option("-q", "--quiet", action="store_const", const=0, - dest="verbose", help="Print errors only.") -group.add_option("-v", "--verbose", action="store_const", const=2, - dest="verbose", default=1, - help="Print info level logs (default).") -group.add_option("--noisy", action="store_const", const=3, - dest="verbose", help="Print all logs.") -# Review server -group = parser.add_option_group("Review server options") -group.add_option("-s", "--server", action="store", dest="server", - default="codereview.appspot.com", - metavar="SERVER", - help=("The server to upload to. The format is host[:port]. " - "Defaults to 'codereview.appspot.com'.")) -group.add_option("-e", "--email", action="store", dest="email", - metavar="EMAIL", default=None, - help="The username to use. Will prompt if omitted.") -group.add_option("-H", "--host", action="store", dest="host", - metavar="HOST", default=None, - help="Overrides the Host header sent with all RPCs.") -group.add_option("--no_cookies", action="store_false", - dest="save_cookies", default=True, - help="Do not save authentication cookies to local disk.") -# Issue -group = parser.add_option_group("Issue options") -group.add_option("-d", "--description", action="store", dest="description", - metavar="DESCRIPTION", default=None, - help="Optional description when creating an issue.") -group.add_option("-f", "--description_file", action="store", - dest="description_file", metavar="DESCRIPTION_FILE", - default=None, - help="Optional path of a file that contains " - "the description when creating an issue.") -group.add_option("-r", "--reviewers", action="store", dest="reviewers", - metavar="REVIEWERS", default=None, - help="Add reviewers (comma separated email addresses).") -group.add_option("--cc", action="store", dest="cc", - metavar="CC", default=None, - help="Add CC (comma separated email addresses).") -# Upload options -group = parser.add_option_group("Patch options") -group.add_option("-m", "--message", action="store", dest="message", - metavar="MESSAGE", default=None, - help="A message to identify the patch. " - "Will prompt if omitted.") -group.add_option("-i", "--issue", type="int", action="store", - metavar="ISSUE", default=None, - help="Issue number to which to add. Defaults to new issue.") -group.add_option("--download_base", action="store_true", - dest="download_base", default=False, - help="Base files will be downloaded by the server " - "(side-by-side diffs may not work on files with CRs).") -group.add_option("--rev", action="store", dest="revision", - metavar="REV", default=None, - help="Branch/tree/revision to diff against (used by DVCS).") -group.add_option("--send_mail", action="store_true", - dest="send_mail", default=False, - help="Send notification email to reviewers.") - - -def GetRpcServer(options): - """Returns an instance of an AbstractRpcServer. - - Returns: - A new AbstractRpcServer, on which RPC calls can be made. - """ - - rpc_server_class = HttpRpcServer - - def GetUserCredentials(): - """Prompts the user for a username and password.""" - email = options.email - if email is None: - email = GetEmail("Email (login for uploading to %s)" % options.server) - password = getpass.getpass("Password for %s: " % email) - return (email, password) - - # If this is the dev_appserver, use fake authentication. - host = (options.host or options.server).lower() - if host == "localhost" or host.startswith("localhost:"): - email = options.email - if email is None: - email = "test@example.com" - logging.info("Using debug user %s. Override with --email" % email) - server = rpc_server_class( - options.server, - lambda: (email, "password"), - host_override=options.host, - extra_headers={"Cookie": - 'dev_appserver_login="%s:False"' % email}, - save_cookies=options.save_cookies) - # Don't try to talk to ClientLogin. - server.authenticated = True - return server - - return rpc_server_class(options.server, GetUserCredentials, - host_override=options.host, - save_cookies=options.save_cookies) - - -def EncodeMultipartFormData(fields, files): - """Encode form fields for multipart/form-data. - - Args: - fields: A sequence of (name, value) elements for regular form fields. - files: A sequence of (name, filename, value) elements for data to be - uploaded as files. - Returns: - (content_type, body) ready for httplib.HTTP instance. - - Source: - https://web.archive.org/web/20160116052001/code.activestate.com/recipes/146306 - """ - BOUNDARY = '-M-A-G-I-C---B-O-U-N-D-A-R-Y-' - CRLF = '\r\n' - lines = [] - for (key, value) in fields: - lines.append('--' + BOUNDARY) - lines.append('Content-Disposition: form-data; name="%s"' % key) - lines.append('') - lines.append(value) - for (key, filename, value) in files: - lines.append('--' + BOUNDARY) - lines.append('Content-Disposition: form-data; name="%s"; filename="%s"' % - (key, filename)) - lines.append('Content-Type: %s' % GetContentType(filename)) - lines.append('') - lines.append(value) - lines.append('--' + BOUNDARY + '--') - lines.append('') - body = CRLF.join(lines) - content_type = 'multipart/form-data; boundary=%s' % BOUNDARY - return content_type, body - - -def GetContentType(filename): - """Helper to guess the content-type from the filename.""" - return mimetypes.guess_type(filename)[0] or 'application/octet-stream' - - -# Use a shell for subcommands on Windows to get a PATH search. -use_shell = sys.platform.startswith("win") - -def RunShellWithReturnCode(command, print_output=False, - universal_newlines=True): - """Executes a command and returns the output from stdout and the return code. - - Args: - command: Command to execute. - print_output: If True, the output is printed to stdout. - If False, both stdout and stderr are ignored. - universal_newlines: Use universal_newlines flag (default: True). - - Returns: - Tuple (output, return code) - """ - logging.info("Running %s", command) - p = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, - shell=use_shell, universal_newlines=universal_newlines) - if print_output: - output_array = [] - while True: - line = p.stdout.readline() - if not line: - break - print line.strip("\n") - output_array.append(line) - output = "".join(output_array) - else: - output = p.stdout.read() - p.wait() - errout = p.stderr.read() - if print_output and errout: - print >>sys.stderr, errout - p.stdout.close() - p.stderr.close() - return output, p.returncode - - -def RunShell(command, silent_ok=False, universal_newlines=True, - print_output=False): - data, retcode = RunShellWithReturnCode(command, print_output, - universal_newlines) - if retcode: - ErrorExit("Got error status from %s:\n%s" % (command, data)) - if not silent_ok and not data: - ErrorExit("No output from %s" % command) - return data - - -class VersionControlSystem(object): - """Abstract base class providing an interface to the VCS.""" - - def __init__(self, options): - """Constructor. - - Args: - options: Command line options. - """ - self.options = options - - def GenerateDiff(self, args): - """Return the current diff as a string. - - Args: - args: Extra arguments to pass to the diff command. - """ - raise NotImplementedError( - "abstract method -- subclass %s must override" % self.__class__) - - def GetUnknownFiles(self): - """Return a list of files unknown to the VCS.""" - raise NotImplementedError( - "abstract method -- subclass %s must override" % self.__class__) - - def CheckForUnknownFiles(self): - """Show an "are you sure?" prompt if there are unknown files.""" - unknown_files = self.GetUnknownFiles() - if unknown_files: - print "The following files are not added to version control:" - for line in unknown_files: - print line - prompt = "Are you sure to continue?(y/N) " - answer = raw_input(prompt).strip() - if answer != "y": - ErrorExit("User aborted") - - def GetBaseFile(self, filename): - """Get the content of the upstream version of a file. - - Returns: - A tuple (base_content, new_content, is_binary, status) - base_content: The contents of the base file. - new_content: For text files, this is empty. For binary files, this is - the contents of the new file, since the diff output won't contain - information to reconstruct the current file. - is_binary: True iff the file is binary. - status: The status of the file. - """ - - raise NotImplementedError( - "abstract method -- subclass %s must override" % self.__class__) - - - def GetBaseFiles(self, diff): - """Helper that calls GetBase file for each file in the patch. - - Returns: - A dictionary that maps from filename to GetBaseFile's tuple. Filenames - are retrieved based on lines that start with "Index:" or - "Property changes on:". - """ - files = {} - for line in diff.splitlines(True): - if line.startswith('Index:') or line.startswith('Property changes on:'): - unused, filename = line.split(':', 1) - # On Windows if a file has property changes its filename uses '\' - # instead of '/'. - filename = filename.strip().replace('\\', '/') - files[filename] = self.GetBaseFile(filename) - return files - - - def UploadBaseFiles(self, issue, rpc_server, patch_list, patchset, options, - files): - """Uploads the base files (and if necessary, the current ones as well).""" - - def UploadFile(filename, file_id, content, is_binary, status, is_base): - """Uploads a file to the server.""" - file_too_large = False - if is_base: - type = "base" - else: - type = "current" - if len(content) > MAX_UPLOAD_SIZE: - print ("Not uploading the %s file for %s because it's too large." % - (type, filename)) - file_too_large = True - content = "" - checksum = md5.new(content).hexdigest() - if options.verbose > 0 and not file_too_large: - print "Uploading %s file for %s" % (type, filename) - url = "/%d/upload_content/%d/%d" % (int(issue), int(patchset), file_id) - form_fields = [("filename", filename), - ("status", status), - ("checksum", checksum), - ("is_binary", str(is_binary)), - ("is_current", str(not is_base)), - ] - if file_too_large: - form_fields.append(("file_too_large", "1")) - if options.email: - form_fields.append(("user", options.email)) - ctype, body = EncodeMultipartFormData(form_fields, - [("data", filename, content)]) - response_body = rpc_server.Send(url, body, - content_type=ctype) - if not response_body.startswith("OK"): - StatusUpdate(" --> %s" % response_body) - sys.exit(1) - - patches = dict() - [patches.setdefault(v, k) for k, v in patch_list] - for filename in patches.keys(): - base_content, new_content, is_binary, status = files[filename] - file_id_str = patches.get(filename) - if file_id_str.find("nobase") != -1: - base_content = None - file_id_str = file_id_str[file_id_str.rfind("_") + 1:] - file_id = int(file_id_str) - if base_content != None: - UploadFile(filename, file_id, base_content, is_binary, status, True) - if new_content != None: - UploadFile(filename, file_id, new_content, is_binary, status, False) - - def IsImage(self, filename): - """Returns true if the filename has an image extension.""" - mimetype = mimetypes.guess_type(filename)[0] - if not mimetype: - return False - return mimetype.startswith("image/") - - -class SubversionVCS(VersionControlSystem): - """Implementation of the VersionControlSystem interface for Subversion.""" - - def __init__(self, options): - super(SubversionVCS, self).__init__(options) - if self.options.revision: - match = re.match(r"(\d+)(:(\d+))?", self.options.revision) - if not match: - ErrorExit("Invalid Subversion revision %s." % self.options.revision) - self.rev_start = match.group(1) - self.rev_end = match.group(3) - else: - self.rev_start = self.rev_end = None - # Cache output from "svn list -r REVNO dirname". - # Keys: dirname, Values: 2-tuple (ouput for start rev and end rev). - self.svnls_cache = {} - # SVN base URL is required to fetch files deleted in an older revision. - # Result is cached to not guess it over and over again in GetBaseFile(). - required = self.options.download_base or self.options.revision is not None - self.svn_base = self._GuessBase(required) - - def GuessBase(self, required): - """Wrapper for _GuessBase.""" - return self.svn_base - - def _GuessBase(self, required): - """Returns the SVN base URL. - - Args: - required: If true, exits if the url can't be guessed, otherwise None is - returned. - """ - info = RunShell(["svn", "info"]) - for line in info.splitlines(): - words = line.split() - if len(words) == 2 and words[0] == "URL:": - url = words[1] - scheme, netloc, path, params, query, fragment = urlparse.urlparse(url) - username, netloc = urllib.splituser(netloc) - if username: - logging.info("Removed username from base URL") - if netloc.endswith("svn.python.org"): - if netloc == "svn.python.org": - if path.startswith("/projects/"): - path = path[9:] - elif netloc != "pythondev@svn.python.org": - ErrorExit("Unrecognized Python URL: %s" % url) - base = "http://svn.python.org/view/*checkout*%s/" % path - logging.info("Guessed Python base = %s", base) - elif netloc.endswith("svn.collab.net"): - if path.startswith("/repos/"): - path = path[6:] - base = "http://svn.collab.net/viewvc/*checkout*%s/" % path - logging.info("Guessed CollabNet base = %s", base) - elif netloc.endswith(".googlecode.com"): - path = path + "/" - base = urlparse.urlunparse(("http", netloc, path, params, - query, fragment)) - logging.info("Guessed Google Code base = %s", base) - else: - path = path + "/" - base = urlparse.urlunparse((scheme, netloc, path, params, - query, fragment)) - logging.info("Guessed base = %s", base) - return base - if required: - ErrorExit("Can't find URL in output from svn info") - return None - - def GenerateDiff(self, args): - cmd = ["svn", "diff"] - if self.options.revision: - cmd += ["-r", self.options.revision] - cmd.extend(args) - data = RunShell(cmd) - count = 0 - for line in data.splitlines(): - if line.startswith("Index:") or line.startswith("Property changes on:"): - count += 1 - logging.info(line) - if not count: - ErrorExit("No valid patches found in output from svn diff") - return data - - def _CollapseKeywords(self, content, keyword_str): - """Collapses SVN keywords.""" - # svn cat translates keywords but svn diff doesn't. As a result of this - # behavior patching.PatchChunks() fails with a chunk mismatch error. - # This part was originally written by the Review Board development team - # who had the same problem (https://reviews.reviewboard.org/r/276/). - # Mapping of keywords to known aliases - svn_keywords = { - # Standard keywords - 'Date': ['Date', 'LastChangedDate'], - 'Revision': ['Revision', 'LastChangedRevision', 'Rev'], - 'Author': ['Author', 'LastChangedBy'], - 'HeadURL': ['HeadURL', 'URL'], - 'Id': ['Id'], - - # Aliases - 'LastChangedDate': ['LastChangedDate', 'Date'], - 'LastChangedRevision': ['LastChangedRevision', 'Rev', 'Revision'], - 'LastChangedBy': ['LastChangedBy', 'Author'], - 'URL': ['URL', 'HeadURL'], - } - - def repl(m): - if m.group(2): - return "$%s::%s$" % (m.group(1), " " * len(m.group(3))) - return "$%s$" % m.group(1) - keywords = [keyword - for name in keyword_str.split(" ") - for keyword in svn_keywords.get(name, [])] - return re.sub(r"\$(%s):(:?)([^\$]+)\$" % '|'.join(keywords), repl, content) - - def GetUnknownFiles(self): - status = RunShell(["svn", "status", "--ignore-externals"], silent_ok=True) - unknown_files = [] - for line in status.split("\n"): - if line and line[0] == "?": - unknown_files.append(line) - return unknown_files - - def ReadFile(self, filename): - """Returns the contents of a file.""" - file = open(filename, 'rb') - result = "" - try: - result = file.read() - finally: - file.close() - return result - - def GetStatus(self, filename): - """Returns the status of a file.""" - if not self.options.revision: - status = RunShell(["svn", "status", "--ignore-externals", filename]) - if not status: - ErrorExit("svn status returned no output for %s" % filename) - status_lines = status.splitlines() - # If file is in a cl, the output will begin with - # "\n--- Changelist 'cl_name':\n". See - # https://web.archive.org/web/20090918234815/svn.collab.net/repos/svn/trunk/notes/changelist-design.txt - if (len(status_lines) == 3 and - not status_lines[0] and - status_lines[1].startswith("--- Changelist")): - status = status_lines[2] - else: - status = status_lines[0] - # If we have a revision to diff against we need to run "svn list" - # for the old and the new revision and compare the results to get - # the correct status for a file. - else: - dirname, relfilename = os.path.split(filename) - if dirname not in self.svnls_cache: - cmd = ["svn", "list", "-r", self.rev_start, dirname or "."] - out, returncode = RunShellWithReturnCode(cmd) - if returncode: - ErrorExit("Failed to get status for %s." % filename) - old_files = out.splitlines() - args = ["svn", "list"] - if self.rev_end: - args += ["-r", self.rev_end] - cmd = args + [dirname or "."] - out, returncode = RunShellWithReturnCode(cmd) - if returncode: - ErrorExit("Failed to run command %s" % cmd) - self.svnls_cache[dirname] = (old_files, out.splitlines()) - old_files, new_files = self.svnls_cache[dirname] - if relfilename in old_files and relfilename not in new_files: - status = "D " - elif relfilename in old_files and relfilename in new_files: - status = "M " - else: - status = "A " - return status - - def GetBaseFile(self, filename): - status = self.GetStatus(filename) - base_content = None - new_content = None - - # If a file is copied its status will be "A +", which signifies - # "addition-with-history". See "svn st" for more information. We need to - # upload the original file or else diff parsing will fail if the file was - # edited. - if status[0] == "A" and status[3] != "+": - # We'll need to upload the new content if we're adding a binary file - # since diff's output won't contain it. - mimetype = RunShell(["svn", "propget", "svn:mime-type", filename], - silent_ok=True) - base_content = "" - is_binary = mimetype and not mimetype.startswith("text/") - if is_binary and self.IsImage(filename): - new_content = self.ReadFile(filename) - elif (status[0] in ("M", "D", "R") or - (status[0] == "A" and status[3] == "+") or # Copied file. - (status[0] == " " and status[1] == "M")): # Property change. - args = [] - if self.options.revision: - url = "%s/%s@%s" % (self.svn_base, filename, self.rev_start) - else: - # Don't change filename, it's needed later. - url = filename - args += ["-r", "BASE"] - cmd = ["svn"] + args + ["propget", "svn:mime-type", url] - mimetype, returncode = RunShellWithReturnCode(cmd) - if returncode: - # File does not exist in the requested revision. - # Reset mimetype, it contains an error message. - mimetype = "" - get_base = False - is_binary = mimetype and not mimetype.startswith("text/") - if status[0] == " ": - # Empty base content just to force an upload. - base_content = "" - elif is_binary: - if self.IsImage(filename): - get_base = True - if status[0] == "M": - if not self.rev_end: - new_content = self.ReadFile(filename) - else: - url = "%s/%s@%s" % (self.svn_base, filename, self.rev_end) - new_content = RunShell(["svn", "cat", url], - universal_newlines=True, silent_ok=True) - else: - base_content = "" - else: - get_base = True - - if get_base: - if is_binary: - universal_newlines = False - else: - universal_newlines = True - if self.rev_start: - # "svn cat -r REV delete_file.txt" doesn't work. cat requires - # the full URL with "@REV" appended instead of using "-r" option. - url = "%s/%s@%s" % (self.svn_base, filename, self.rev_start) - base_content = RunShell(["svn", "cat", url], - universal_newlines=universal_newlines, - silent_ok=True) - else: - base_content = RunShell(["svn", "cat", filename], - universal_newlines=universal_newlines, - silent_ok=True) - if not is_binary: - args = [] - if self.rev_start: - url = "%s/%s@%s" % (self.svn_base, filename, self.rev_start) - else: - url = filename - args += ["-r", "BASE"] - cmd = ["svn"] + args + ["propget", "svn:keywords", url] - keywords, returncode = RunShellWithReturnCode(cmd) - if keywords and not returncode: - base_content = self._CollapseKeywords(base_content, keywords) - else: - StatusUpdate("svn status returned unexpected output: %s" % status) - sys.exit(1) - return base_content, new_content, is_binary, status[0:5] - - -class GitVCS(VersionControlSystem): - """Implementation of the VersionControlSystem interface for Git.""" - - def __init__(self, options): - super(GitVCS, self).__init__(options) - # Map of filename -> hash of base file. - self.base_hashes = {} - - def GenerateDiff(self, extra_args): - # This is more complicated than svn's GenerateDiff because we must convert - # the diff output to include an svn-style "Index:" line as well as record - # the hashes of the base files, so we can upload them along with our diff. - if self.options.revision: - extra_args = [self.options.revision] + extra_args - gitdiff = RunShell(["git", "diff", "--full-index"] + extra_args) - svndiff = [] - filecount = 0 - filename = None - for line in gitdiff.splitlines(): - match = re.match(r"diff --git a/(.*) b/.*$", line) - if match: - filecount += 1 - filename = match.group(1) - svndiff.append("Index: %s\n" % filename) - else: - # The "index" line in a git diff looks like this (long hashes elided): - # index 82c0d44..b2cee3f 100755 - # We want to save the left hash, as that identifies the base file. - match = re.match(r"index (\w+)\.\.", line) - if match: - self.base_hashes[filename] = match.group(1) - svndiff.append(line + "\n") - if not filecount: - ErrorExit("No valid patches found in output from git diff") - return "".join(svndiff) - - def GetUnknownFiles(self): - status = RunShell(["git", "ls-files", "--exclude-standard", "--others"], - silent_ok=True) - return status.splitlines() - - def GetBaseFile(self, filename): - hash = self.base_hashes[filename] - base_content = None - new_content = None - is_binary = False - if hash == "0" * 40: # All-zero hash indicates no base file. - status = "A" - base_content = "" - else: - status = "M" - base_content, returncode = RunShellWithReturnCode(["git", "show", hash]) - if returncode: - ErrorExit("Got error status from 'git show %s'" % hash) - return (base_content, new_content, is_binary, status) - - -class MercurialVCS(VersionControlSystem): - """Implementation of the VersionControlSystem interface for Mercurial.""" - - def __init__(self, options, repo_dir): - super(MercurialVCS, self).__init__(options) - # Absolute path to repository (we can be in a subdir) - self.repo_dir = os.path.normpath(repo_dir) - # Compute the subdir - cwd = os.path.normpath(os.getcwd()) - assert cwd.startswith(self.repo_dir) - self.subdir = cwd[len(self.repo_dir):].lstrip(r"\/") - if self.options.revision: - self.base_rev = self.options.revision - else: - self.base_rev = RunShell(["hg", "parent", "-q"]).split(':')[1].strip() - - def _GetRelPath(self, filename): - """Get relative path of a file according to the current directory, - given its logical path in the repo.""" - assert filename.startswith(self.subdir), filename - return filename[len(self.subdir):].lstrip(r"\/") - - def GenerateDiff(self, extra_args): - # If no file specified, restrict to the current subdir - extra_args = extra_args or ["."] - cmd = ["hg", "diff", "--git", "-r", self.base_rev] + extra_args - data = RunShell(cmd, silent_ok=True) - svndiff = [] - filecount = 0 - for line in data.splitlines(): - m = re.match("diff --git a/(\S+) b/(\S+)", line) - if m: - # Modify line to make it look like as it comes from svn diff. - # With this modification no changes on the server side are required - # to make upload.py work with Mercurial repos. - # NOTE: for proper handling of moved/copied files, we have to use - # the second filename. - filename = m.group(2) - svndiff.append("Index: %s" % filename) - svndiff.append("=" * 67) - filecount += 1 - logging.info(line) - else: - svndiff.append(line) - if not filecount: - ErrorExit("No valid patches found in output from hg diff") - return "\n".join(svndiff) + "\n" - - def GetUnknownFiles(self): - """Return a list of files unknown to the VCS.""" - args = [] - status = RunShell(["hg", "status", "--rev", self.base_rev, "-u", "."], - silent_ok=True) - unknown_files = [] - for line in status.splitlines(): - st, fn = line.split(" ", 1) - if st == "?": - unknown_files.append(fn) - return unknown_files - - def GetBaseFile(self, filename): - # "hg status" and "hg cat" both take a path relative to the current subdir - # rather than to the repo root, but "hg diff" has given us the full path - # to the repo root. - base_content = "" - new_content = None - is_binary = False - oldrelpath = relpath = self._GetRelPath(filename) - # "hg status -C" returns two lines for moved/copied files, one otherwise - out = RunShell(["hg", "status", "-C", "--rev", self.base_rev, relpath]) - out = out.splitlines() - # HACK: strip error message about missing file/directory if it isn't in - # the working copy - if out[0].startswith('%s: ' % relpath): - out = out[1:] - if len(out) > 1: - # Moved/copied => considered as modified, use old filename to - # retrieve base contents - oldrelpath = out[1].strip() - status = "M" - else: - status, _ = out[0].split(' ', 1) - if status != "A": - base_content = RunShell(["hg", "cat", "-r", self.base_rev, oldrelpath], - silent_ok=True) - is_binary = "\0" in base_content # Mercurial's heuristic - if status != "R": - new_content = open(relpath, "rb").read() - is_binary = is_binary or "\0" in new_content - if is_binary and base_content: - # Fetch again without converting newlines - base_content = RunShell(["hg", "cat", "-r", self.base_rev, oldrelpath], - silent_ok=True, universal_newlines=False) - if not is_binary or not self.IsImage(relpath): - new_content = None - return base_content, new_content, is_binary, status - - -# NOTE: The SplitPatch function is duplicated in engine.py, keep them in sync. -def SplitPatch(data): - """Splits a patch into separate pieces for each file. - - Args: - data: A string containing the output of svn diff. - - Returns: - A list of 2-tuple (filename, text) where text is the svn diff output - pertaining to filename. - """ - patches = [] - filename = None - diff = [] - for line in data.splitlines(True): - new_filename = None - if line.startswith('Index:'): - unused, new_filename = line.split(':', 1) - new_filename = new_filename.strip() - elif line.startswith('Property changes on:'): - unused, temp_filename = line.split(':', 1) - # When a file is modified, paths use '/' between directories, however - # when a property is modified '\' is used on Windows. Make them the same - # otherwise the file shows up twice. - temp_filename = temp_filename.strip().replace('\\', '/') - if temp_filename != filename: - # File has property changes but no modifications, create a new diff. - new_filename = temp_filename - if new_filename: - if filename and diff: - patches.append((filename, ''.join(diff))) - filename = new_filename - diff = [line] - continue - if diff is not None: - diff.append(line) - if filename and diff: - patches.append((filename, ''.join(diff))) - return patches - - -def UploadSeparatePatches(issue, rpc_server, patchset, data, options): - """Uploads a separate patch for each file in the diff output. - - Returns a list of [patch_key, filename] for each file. - """ - patches = SplitPatch(data) - rv = [] - for patch in patches: - if len(patch[1]) > MAX_UPLOAD_SIZE: - print ("Not uploading the patch for " + patch[0] + - " because the file is too large.") - continue - form_fields = [("filename", patch[0])] - if not options.download_base: - form_fields.append(("content_upload", "1")) - files = [("data", "data.diff", patch[1])] - ctype, body = EncodeMultipartFormData(form_fields, files) - url = "/%d/upload_patch/%d" % (int(issue), int(patchset)) - print "Uploading patch for " + patch[0] - response_body = rpc_server.Send(url, body, content_type=ctype) - lines = response_body.splitlines() - if not lines or lines[0] != "OK": - StatusUpdate(" --> %s" % response_body) - sys.exit(1) - rv.append([lines[1], patch[0]]) - return rv - - -def GuessVCS(options): - """Helper to guess the version control system. - - This examines the current directory, guesses which VersionControlSystem - we're using, and returns an instance of the appropriate class. Exit with an - error if we can't figure it out. - - Returns: - A VersionControlSystem instance. Exits if the VCS can't be guessed. - """ - # Mercurial has a command to get the base directory of a repository - # Try running it, but don't die if we don't have hg installed. - # NOTE: we try Mercurial first as it can sit on top of an SVN working copy. - try: - out, returncode = RunShellWithReturnCode(["hg", "root"]) - if returncode == 0: - return MercurialVCS(options, out.strip()) - except OSError, (errno, message): - if errno != 2: # ENOENT -- they don't have hg installed. - raise - - # Subversion has a .svn in all working directories. - if os.path.isdir('.svn'): - logging.info("Guessed VCS = Subversion") - return SubversionVCS(options) - - # Git has a command to test if you're in a git tree. - # Try running it, but don't die if we don't have git installed. - try: - out, returncode = RunShellWithReturnCode(["git", "rev-parse", - "--is-inside-work-tree"]) - if returncode == 0: - return GitVCS(options) - except OSError, (errno, message): - if errno != 2: # ENOENT -- they don't have git installed. - raise - - ErrorExit(("Could not guess version control system. " - "Are you in a working copy directory?")) - - -def RealMain(argv, data=None): - """The real main function. - - Args: - argv: Command line arguments. - data: Diff contents. If None (default) the diff is generated by - the VersionControlSystem implementation returned by GuessVCS(). - - Returns: - A 2-tuple (issue id, patchset id). - The patchset id is None if the base files are not uploaded by this - script (applies only to SVN checkouts). - """ - logging.basicConfig(format=("%(asctime).19s %(levelname)s %(filename)s:" - "%(lineno)s %(message)s ")) - os.environ['LC_ALL'] = 'C' - options, args = parser.parse_args(argv[1:]) - global verbosity - verbosity = options.verbose - if verbosity >= 3: - logging.getLogger().setLevel(logging.DEBUG) - elif verbosity >= 2: - logging.getLogger().setLevel(logging.INFO) - vcs = GuessVCS(options) - if isinstance(vcs, SubversionVCS): - # base field is only allowed for Subversion. - # Note: Fetching base files may become deprecated in future releases. - base = vcs.GuessBase(options.download_base) - else: - base = None - if not base and options.download_base: - options.download_base = True - logging.info("Enabled upload of base file") - if not options.assume_yes: - vcs.CheckForUnknownFiles() - if data is None: - data = vcs.GenerateDiff(args) - files = vcs.GetBaseFiles(data) - if verbosity >= 1: - print "Upload server:", options.server, "(change with -s/--server)" - if options.issue: - prompt = "Message describing this patch set: " - else: - prompt = "New issue subject: " - message = options.message or raw_input(prompt).strip() - if not message: - ErrorExit("A non-empty message is required") - rpc_server = GetRpcServer(options) - form_fields = [("subject", message)] - if base: - form_fields.append(("base", base)) - if options.issue: - form_fields.append(("issue", str(options.issue))) - if options.email: - form_fields.append(("user", options.email)) - if options.reviewers: - for reviewer in options.reviewers.split(','): - if "@" in reviewer and not reviewer.split("@")[1].count(".") == 1: - ErrorExit("Invalid email address: %s" % reviewer) - form_fields.append(("reviewers", options.reviewers)) - if options.cc: - for cc in options.cc.split(','): - if "@" in cc and not cc.split("@")[1].count(".") == 1: - ErrorExit("Invalid email address: %s" % cc) - form_fields.append(("cc", options.cc)) - description = options.description - if options.description_file: - if options.description: - ErrorExit("Can't specify description and description_file") - file = open(options.description_file, 'r') - description = file.read() - file.close() - if description: - form_fields.append(("description", description)) - # Send a hash of all the base file so the server can determine if a copy - # already exists in an earlier patchset. - base_hashes = "" - for file, info in files.iteritems(): - if not info[0] is None: - checksum = md5.new(info[0]).hexdigest() - if base_hashes: - base_hashes += "|" - base_hashes += checksum + ":" + file - form_fields.append(("base_hashes", base_hashes)) - # If we're uploading base files, don't send the email before the uploads, so - # that it contains the file status. - if options.send_mail and options.download_base: - form_fields.append(("send_mail", "1")) - if not options.download_base: - form_fields.append(("content_upload", "1")) - if len(data) > MAX_UPLOAD_SIZE: - print "Patch is large, so uploading file patches separately." - uploaded_diff_file = [] - form_fields.append(("separate_patches", "1")) - else: - uploaded_diff_file = [("data", "data.diff", data)] - ctype, body = EncodeMultipartFormData(form_fields, uploaded_diff_file) - response_body = rpc_server.Send("/upload", body, content_type=ctype) - patchset = None - if not options.download_base or not uploaded_diff_file: - lines = response_body.splitlines() - if len(lines) >= 2: - msg = lines[0] - patchset = lines[1].strip() - patches = [x.split(" ", 1) for x in lines[2:]] - else: - msg = response_body - else: - msg = response_body - StatusUpdate(msg) - if not response_body.startswith("Issue created.") and \ - not response_body.startswith("Issue updated."): - sys.exit(0) - issue = msg[msg.rfind("/")+1:] - - if not uploaded_diff_file: - result = UploadSeparatePatches(issue, rpc_server, patchset, data, options) - if not options.download_base: - patches = result - - if not options.download_base: - vcs.UploadBaseFiles(issue, rpc_server, patches, patchset, options, files) - if options.send_mail: - rpc_server.Send("/" + issue + "/mail", payload="") - return issue, patchset - - -def main(): - try: - RealMain(sys.argv) - except KeyboardInterrupt: - print - StatusUpdate("Interrupted.") - sys.exit(1) - - -if __name__ == "__main__": - main() diff --git a/googlemock/scripts/upload_gmock.py b/googlemock/scripts/upload_gmock.py deleted file mode 100755 index 5dc484b391..0000000000 --- a/googlemock/scripts/upload_gmock.py +++ /dev/null @@ -1,78 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2009, 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. - -"""upload_gmock.py v0.1.0 -- uploads a Google Mock patch for review. - -This simple wrapper passes all command line flags and ---cc=googlemock@googlegroups.com to upload.py. - -USAGE: upload_gmock.py [options for upload.py] -""" - -__author__ = 'wan@google.com (Zhanyong Wan)' - -import os -import sys - -CC_FLAG = '--cc=' -GMOCK_GROUP = 'googlemock@googlegroups.com' - - -def main(): - # Finds the path to upload.py, assuming it is in the same directory - # as this file. - my_dir = os.path.dirname(os.path.abspath(__file__)) - upload_py_path = os.path.join(my_dir, 'upload.py') - - # Adds Google Mock discussion group to the cc line if it's not there - # already. - upload_py_argv = [upload_py_path] - found_cc_flag = False - for arg in sys.argv[1:]: - if arg.startswith(CC_FLAG): - found_cc_flag = True - cc_line = arg[len(CC_FLAG):] - cc_list = [addr for addr in cc_line.split(',') if addr] - if GMOCK_GROUP not in cc_list: - cc_list.append(GMOCK_GROUP) - upload_py_argv.append(CC_FLAG + ','.join(cc_list)) - else: - upload_py_argv.append(arg) - - if not found_cc_flag: - upload_py_argv.append(CC_FLAG + GMOCK_GROUP) - - # Invokes upload.py with the modified command line flags. - os.execv(upload_py_path, upload_py_argv) - - -if __name__ == '__main__': - main() From e2fc3a9c9cb8188c841a07ee59c01d1b2afd8622 Mon Sep 17 00:00:00 2001 From: Abseil Team Date: Wed, 30 Oct 2019 17:20:46 -0400 Subject: [PATCH 073/541] Googletest export Tolerate std::string's explicit copy construction from std::string_view. PiperOrigin-RevId: 277583394 --- googlemock/include/gmock/gmock-matchers.h | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/googlemock/include/gmock/gmock-matchers.h b/googlemock/include/gmock/gmock-matchers.h index a96488354a..b8ec24dddf 100644 --- a/googlemock/include/gmock/gmock-matchers.h +++ b/googlemock/include/gmock/gmock-matchers.h @@ -758,8 +758,7 @@ class HasSubstrMatcher { template bool MatchAndExplain(const MatcheeStringType& s, MatchResultListener* /* listener */) const { - const StringType& s2(s); - return s2.find(substring_) != StringType::npos; + return StringType(s).find(substring_) != StringType::npos; } // Describes what this matcher matches. From 2db3df9c4f825591dfce2d6909cebe4a3f073910 Mon Sep 17 00:00:00 2001 From: Abseil Team Date: Thu, 31 Oct 2019 10:04:51 -0400 Subject: [PATCH 074/541] Googletest export Change variable name to match comment. PiperOrigin-RevId: 277713621 --- googlemock/include/gmock/gmock-actions.h | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/googlemock/include/gmock/gmock-actions.h b/googlemock/include/gmock/gmock-actions.h index 2fe7574a7c..b040004a20 100644 --- a/googlemock/include/gmock/gmock-actions.h +++ b/googlemock/include/gmock/gmock-actions.h @@ -1098,14 +1098,14 @@ inline internal::DoDefaultAction DoDefault() { // Creates an action that sets the variable pointed by the N-th // (0-based) function argument to 'value'. template -internal::SetArgumentPointeeAction SetArgPointee(T x) { - return {std::move(x)}; +internal::SetArgumentPointeeAction SetArgPointee(T value) { + return {std::move(value)}; } // The following version is DEPRECATED. template -internal::SetArgumentPointeeAction SetArgumentPointee(T x) { - return {std::move(x)}; +internal::SetArgumentPointeeAction SetArgumentPointee(T value) { + return {std::move(value)}; } // Creates an action that sets a pointer referent to a given value. From 523ad489efc3a73dfbfdd5424c6ba518a3668593 Mon Sep 17 00:00:00 2001 From: Krystian Kuzniarek Date: Sat, 2 Nov 2019 01:08:24 +0100 Subject: [PATCH 075/541] update pump_manual.md --- googlemock/docs/pump_manual.md | 21 +++++++++------------ 1 file changed, 9 insertions(+), 12 deletions(-) diff --git a/googlemock/docs/pump_manual.md b/googlemock/docs/pump_manual.md index 10b3c5ff08..60ff06c3c4 100644 --- a/googlemock/docs/pump_manual.md +++ b/googlemock/docs/pump_manual.md @@ -6,18 +6,15 @@ Template and macro libraries often need to define many classes, functions, or macros that vary only (or almost only) in the number of arguments they take. It's a lot of repetitive, mechanical, and error-prone work. -Variadic templates and variadic macros can alleviate the problem. However, while -both are being considered by the C++ committee, neither is in the standard yet -or widely supported by compilers. Thus they are often not a good choice, -especially when your code needs to be portable. And their capabilities are still -limited. - -As a result, authors of such libraries often have to write scripts to generate -their implementation. However, our experience is that it's tedious to write such -scripts, which tend to reflect the structure of the generated code poorly and -are often hard to read and edit. For example, a small change needed in the -generated code may require some non-intuitive, non-trivial changes in the -script. This is especially painful when experimenting with the code. +Our experience is that it's tedious to write custom scripts, which tend to +reflect the structure of the generated code poorly and are often hard to +read and edit. For example, a small change needed in the generated code +may require some non-intuitive, non-trivial changes in the script. This is +especially painful when experimenting with the code. + +This script may be useful for generating meta code, for example a series of +macros of FOO1, FOO2, etc. Nevertheless, please make it your last resort +technique by favouring C++ template metaprogramming or variadic macros. # Our Solution From 442f45b376f54112d6991bdf259d1c8b5daf9ebf Mon Sep 17 00:00:00 2001 From: Krystian Kuzniarek Date: Sat, 2 Nov 2019 01:13:24 +0100 Subject: [PATCH 076/541] pump.py: add support for Python 3 --- googlemock/scripts/pump.py | 13 +++++++------ 1 file changed, 7 insertions(+), 6 deletions(-) diff --git a/googlemock/scripts/pump.py b/googlemock/scripts/pump.py index 66e321700c..5523a19de0 100755 --- a/googlemock/scripts/pump.py +++ b/googlemock/scripts/pump.py @@ -1,4 +1,4 @@ -#!/usr/bin/env python2.7 +#!/usr/bin/env python # # Copyright 2008, Google Inc. # All rights reserved. @@ -64,6 +64,7 @@ from __future__ import print_function +import io import os import re import sys @@ -834,7 +835,7 @@ def main(argv): sys.exit(1) file_path = argv[-1] - output_str = ConvertFromPumpSource(file(file_path, 'r').read()) + output_str = ConvertFromPumpSource(io.open(file_path, 'r').read()) if file_path.endswith('.pump'): output_file_path = file_path[:-5] else: @@ -842,11 +843,11 @@ def main(argv): if output_file_path == '-': print(output_str,) else: - output_file = file(output_file_path, 'w') - output_file.write('// This file was GENERATED by command:\n') - output_file.write('// %s %s\n' % + output_file = io.open(output_file_path, 'w') + output_file.write(u'// This file was GENERATED by command:\n') + output_file.write(u'// %s %s\n' % (os.path.basename(__file__), os.path.basename(file_path))) - output_file.write('// DO NOT EDIT BY HAND!!!\n\n') + output_file.write(u'// DO NOT EDIT BY HAND!!!\n\n') output_file.write(output_str) output_file.close() From f658561ef2530f4905ed0a27e113b9dffd2281f9 Mon Sep 17 00:00:00 2001 From: Krystian Kuzniarek Date: Sat, 2 Nov 2019 01:18:21 +0100 Subject: [PATCH 077/541] fix a typo --- googlemock/include/gmock/gmock-matchers.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/googlemock/include/gmock/gmock-matchers.h b/googlemock/include/gmock/gmock-matchers.h index b8ec24dddf..e71570bcfb 100644 --- a/googlemock/include/gmock/gmock-matchers.h +++ b/googlemock/include/gmock/gmock-matchers.h @@ -1323,7 +1323,7 @@ class PredicateFormatterFromMatcher { << "Expected: "; matcher.DescribeTo(&ss); - // Rerun the matcher to "PrintAndExain" the failure. + // Rerun the matcher to "PrintAndExplain" the failure. StringMatchResultListener listener; if (MatchPrintAndExplain(x, matcher, &listener)) { ss << "\n The matcher failed on the initial attempt; but passed when " From f9665846e405664bec650d77f9dd236c61a293b0 Mon Sep 17 00:00:00 2001 From: Krystian Kuzniarek Date: Tue, 5 Nov 2019 06:46:43 +0100 Subject: [PATCH 078/541] update gen_gtest_pred_impl.py After 7bd4a7f3 gtest_pred_impl_unittest.cc used to be newer than its template. --- googletest/scripts/gen_gtest_pred_impl.py | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/googletest/scripts/gen_gtest_pred_impl.py b/googletest/scripts/gen_gtest_pred_impl.py index 72942779cc..20206e3926 100755 --- a/googletest/scripts/gen_gtest_pred_impl.py +++ b/googletest/scripts/gen_gtest_pred_impl.py @@ -544,10 +544,10 @@ class Predicate%(n)sTest : public testing::Test { } } - // true iff the test function is expected to run to finish. + // true if and only if the test function is expected to run to finish. static bool expected_to_finish_; - // true iff the test function did run to finish. + // true if and only if the test function did run to finish. static bool finished_; """ % DEFS @@ -576,12 +576,12 @@ def GenTest(use_format, use_assert, expect_failure, """Returns the test for a predicate assertion macro. Args: - use_format: true iff the assertion is a *_PRED_FORMAT*. - use_assert: true iff the assertion is a ASSERT_*. - expect_failure: true iff the assertion is expected to fail. - use_functor: true iff the first argument of the assertion is + use_format: true if and only if the assertion is a *_PRED_FORMAT*. + use_assert: true if and only if the assertion is a ASSERT_*. + expect_failure: true if and only if the assertion is expected to fail. + use_functor: true if and only if the first argument of the assertion is a functor (as opposed to a function) - use_user_type: true iff the predicate functor/function takes + use_user_type: true if and only if the predicate functor/function takes argument(s) of a user-defined type. Example: From f79ac2ce0e785c6c0ffcc1e08d18cb414ceec83f Mon Sep 17 00:00:00 2001 From: Krystian Kuzniarek Date: Tue, 5 Nov 2019 06:37:41 +0100 Subject: [PATCH 079/541] change incorrect comments --- googletest/scripts/gen_gtest_pred_impl.py | 5 ++-- googletest/test/gtest_pred_impl_unittest.cc | 27 +++++++++------------ 2 files changed, 13 insertions(+), 19 deletions(-) diff --git a/googletest/scripts/gen_gtest_pred_impl.py b/googletest/scripts/gen_gtest_pred_impl.py index 20206e3926..3ffb972e71 100755 --- a/googletest/scripts/gen_gtest_pred_impl.py +++ b/googletest/scripts/gen_gtest_pred_impl.py @@ -439,9 +439,8 @@ def TestsForArity(n): return %(v_sum)s > 0; } -// The following two functions are needed to circumvent a bug in -// gcc 2.95.3, which sometimes has problem with the above template -// function. +// The following two functions are needed because a compiler doesn't have +// a context yet to know which template function must be instantiated. bool PredFunction%(n)sInt(%(int_vs)s) { return %(v_sum)s > 0; } diff --git a/googletest/test/gtest_pred_impl_unittest.cc b/googletest/test/gtest_pred_impl_unittest.cc index 1afe5e2da7..bbef9947d9 100644 --- a/googletest/test/gtest_pred_impl_unittest.cc +++ b/googletest/test/gtest_pred_impl_unittest.cc @@ -27,7 +27,7 @@ // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -// This file is AUTOMATICALLY GENERATED on 01/02/2019 by command +// This file is AUTOMATICALLY GENERATED on 11/05/2019 by command // 'gen_gtest_pred_impl.py 5'. DO NOT EDIT BY HAND! // Regression test for gtest_pred_impl.h @@ -78,9 +78,8 @@ bool PredFunction1(T1 v1) { return v1 > 0; } -// The following two functions are needed to circumvent a bug in -// gcc 2.95.3, which sometimes has problem with the above template -// function. +// The following two functions are needed because a compiler doesn't have +// a context yet to know which template function must be instantiated. bool PredFunction1Int(int v1) { return v1 > 0; } @@ -465,9 +464,8 @@ bool PredFunction2(T1 v1, T2 v2) { return v1 + v2 > 0; } -// The following two functions are needed to circumvent a bug in -// gcc 2.95.3, which sometimes has problem with the above template -// function. +// The following two functions are needed because a compiler doesn't have +// a context yet to know which template function must be instantiated. bool PredFunction2Int(int v1, int v2) { return v1 + v2 > 0; } @@ -894,9 +892,8 @@ bool PredFunction3(T1 v1, T2 v2, T3 v3) { return v1 + v2 + v3 > 0; } -// The following two functions are needed to circumvent a bug in -// gcc 2.95.3, which sometimes has problem with the above template -// function. +// The following two functions are needed because a compiler doesn't have +// a context yet to know which template function must be instantiated. bool PredFunction3Int(int v1, int v2, int v3) { return v1 + v2 + v3 > 0; } @@ -1365,9 +1362,8 @@ bool PredFunction4(T1 v1, T2 v2, T3 v3, T4 v4) { return v1 + v2 + v3 + v4 > 0; } -// The following two functions are needed to circumvent a bug in -// gcc 2.95.3, which sometimes has problem with the above template -// function. +// The following two functions are needed because a compiler doesn't have +// a context yet to know which template function must be instantiated. bool PredFunction4Int(int v1, int v2, int v3, int v4) { return v1 + v2 + v3 + v4 > 0; } @@ -1878,9 +1874,8 @@ bool PredFunction5(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5) { return v1 + v2 + v3 + v4 + v5 > 0; } -// The following two functions are needed to circumvent a bug in -// gcc 2.95.3, which sometimes has problem with the above template -// function. +// The following two functions are needed because a compiler doesn't have +// a context yet to know which template function must be instantiated. bool PredFunction5Int(int v1, int v2, int v3, int v4, int v5) { return v1 + v2 + v3 + v4 + v5 > 0; } From 6caa879a42d97f1b02ecc90c77fc486220251fa1 Mon Sep 17 00:00:00 2001 From: Martin Erik Werner Date: Sat, 19 Oct 2019 19:37:16 +0200 Subject: [PATCH 080/541] pkg-config: Remove pthread link flag from Cflags Remove the threads link library variable references from the pkg-config Cflags: field, removing -lpthread(s) from the compile flags. "-l*" linker flags should only be part of the Libs: section and should not be part of the Cflags: section in pkg-config files. This was first suggested in https://github.com/google/googletest/pull/2006 and further discussed in https://github.com/google/googletest/pull/2483 . --- googlemock/cmake/gmock.pc.in | 2 +- googlemock/cmake/gmock_main.pc.in | 2 +- googletest/cmake/gtest.pc.in | 2 +- googletest/cmake/gtest_main.pc.in | 2 +- 4 files changed, 4 insertions(+), 4 deletions(-) diff --git a/googlemock/cmake/gmock.pc.in b/googlemock/cmake/gmock.pc.in index 08e0454749..99eb3e178c 100644 --- a/googlemock/cmake/gmock.pc.in +++ b/googlemock/cmake/gmock.pc.in @@ -8,4 +8,4 @@ Version: @PROJECT_VERSION@ URL: https://github.com/google/googletest Requires: gtest Libs: -L${libdir} -lgmock @CMAKE_THREAD_LIBS_INIT@ -Cflags: -I${includedir} @GTEST_HAS_PTHREAD_MACRO@ @CMAKE_THREAD_LIBS_INIT@ +Cflags: -I${includedir} @GTEST_HAS_PTHREAD_MACRO@ diff --git a/googlemock/cmake/gmock_main.pc.in b/googlemock/cmake/gmock_main.pc.in index b22fe61482..3186f8edc4 100644 --- a/googlemock/cmake/gmock_main.pc.in +++ b/googlemock/cmake/gmock_main.pc.in @@ -8,4 +8,4 @@ Version: @PROJECT_VERSION@ URL: https://github.com/google/googletest Requires: gmock Libs: -L${libdir} -lgmock_main @CMAKE_THREAD_LIBS_INIT@ -Cflags: -I${includedir} @GTEST_HAS_PTHREAD_MACRO@ @CMAKE_THREAD_LIBS_INIT@ +Cflags: -I${includedir} @GTEST_HAS_PTHREAD_MACRO@ diff --git a/googletest/cmake/gtest.pc.in b/googletest/cmake/gtest.pc.in index 9aae29e267..49d70c9bb4 100644 --- a/googletest/cmake/gtest.pc.in +++ b/googletest/cmake/gtest.pc.in @@ -7,4 +7,4 @@ Description: GoogleTest (without main() function) Version: @PROJECT_VERSION@ URL: https://github.com/google/googletest Libs: -L${libdir} -lgtest @CMAKE_THREAD_LIBS_INIT@ -Cflags: -I${includedir} @GTEST_HAS_PTHREAD_MACRO@ @CMAKE_THREAD_LIBS_INIT@ +Cflags: -I${includedir} @GTEST_HAS_PTHREAD_MACRO@ diff --git a/googletest/cmake/gtest_main.pc.in b/googletest/cmake/gtest_main.pc.in index 915f2973af..e0d81a8d60 100644 --- a/googletest/cmake/gtest_main.pc.in +++ b/googletest/cmake/gtest_main.pc.in @@ -8,4 +8,4 @@ Version: @PROJECT_VERSION@ URL: https://github.com/google/googletest Requires: gtest Libs: -L${libdir} -lgtest_main @CMAKE_THREAD_LIBS_INIT@ -Cflags: -I${includedir} @GTEST_HAS_PTHREAD_MACRO@ @CMAKE_THREAD_LIBS_INIT@ +Cflags: -I${includedir} @GTEST_HAS_PTHREAD_MACRO@ From 681454dae48f109abf68c424c9d2e6db9a092238 Mon Sep 17 00:00:00 2001 From: Abseil Team Date: Tue, 5 Nov 2019 17:32:29 -0500 Subject: [PATCH 081/541] Googletest export Clone+exec death test allocates a single page of stack to run chdir + exec on. This is not enough when gtest is built with ASan and run on particular hardware. With ASan on x86_64, ExecDeathTestChildMain has frame size of 1728 bytes. Call to chdir() in ExecDeathTestChildMain ends up in _dl_runtime_resolve_xsavec, which attempts to save register state on the stack; according to cpuid(0xd) XSAVE register save area size is 2568 on my machine. This results in something like this in all death tests: Result: died but not with expected error. ... [ DEATH ] AddressSanitizer:DEADLYSIGNAL [ DEATH ] ================================================================= [ DEATH ] ==178637==ERROR: AddressSanitizer: stack-overflow on address ... PiperOrigin-RevId: 278709790 --- googletest/src/gtest-death-test.cc | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/googletest/src/gtest-death-test.cc b/googletest/src/gtest-death-test.cc index da09a1cfc2..5d1031bea2 100644 --- a/googletest/src/gtest-death-test.cc +++ b/googletest/src/gtest-death-test.cc @@ -1364,7 +1364,7 @@ static pid_t ExecDeathTestSpawnChild(char* const* argv, int close_fd) { if (!use_fork) { static const bool stack_grows_down = StackGrowsDown(); - const auto stack_size = static_cast(getpagesize()); + const auto stack_size = static_cast(getpagesize() * 2); // MMAP_ANONYMOUS is not defined on Mac, so we use MAP_ANON instead. void* const stack = mmap(nullptr, stack_size, PROT_READ | PROT_WRITE, MAP_ANON | MAP_PRIVATE, -1, 0); From d5707695cb020ace53dc35f30dd1c3f463daf98e Mon Sep 17 00:00:00 2001 From: Abseil Team Date: Fri, 8 Nov 2019 12:36:37 -0500 Subject: [PATCH 082/541] Googletest export Correctly deal with stringification, and forbid empty arguments where they could slip thought, in the type parameterized test API. Note: even where empty args work, it's likely to result in technically invalid code by virtue of creating reserved identifiers: https://en.cppreference.com/w/cpp/language/identifiers PiperOrigin-RevId: 279330971 --- googletest/include/gtest/gtest-typed-test.h | 17 +++++++++++++---- 1 file changed, 13 insertions(+), 4 deletions(-) diff --git a/googletest/include/gtest/gtest-typed-test.h b/googletest/include/gtest/gtest-typed-test.h index 151fc8f769..6f635c87c4 100644 --- a/googletest/include/gtest/gtest-typed-test.h +++ b/googletest/include/gtest/gtest-typed-test.h @@ -169,6 +169,7 @@ INSTANTIATE_TYPED_TEST_SUITE_P(My, FooTest, MyTypes); #endif // 0 +#include "gtest/internal/gtest-internal.h" #include "gtest/internal/gtest-port.h" #include "gtest/internal/gtest-type-util.h" @@ -194,6 +195,8 @@ INSTANTIATE_TYPED_TEST_SUITE_P(My, FooTest, MyTypes); GTEST_NAME_GENERATOR_(CaseName) #define TYPED_TEST(CaseName, TestName) \ + static_assert(sizeof(GTEST_STRINGIFY_(TestName)) > 1, \ + "test-name must not be empty"); \ template \ class GTEST_TEST_CLASS_NAME_(CaseName, TestName) \ : public CaseName { \ @@ -211,7 +214,8 @@ INSTANTIATE_TYPED_TEST_SUITE_P(My, FooTest, MyTypes); CaseName)>::Register("", \ ::testing::internal::CodeLocation( \ __FILE__, __LINE__), \ - #CaseName, #TestName, 0, \ + GTEST_STRINGIFY_(CaseName), \ + GTEST_STRINGIFY_(TestName), 0, \ ::testing::internal::GenerateNames< \ GTEST_NAME_GENERATOR_(CaseName), \ GTEST_TYPE_PARAMS_(CaseName)>()); \ @@ -278,12 +282,14 @@ INSTANTIATE_TYPED_TEST_SUITE_P(My, FooTest, MyTypes); }; \ static bool gtest_##TestName##_defined_ GTEST_ATTRIBUTE_UNUSED_ = \ GTEST_TYPED_TEST_SUITE_P_STATE_(SuiteName).AddTestName( \ - __FILE__, __LINE__, #SuiteName, #TestName); \ + __FILE__, __LINE__, GTEST_STRINGIFY_(SuiteName), \ + GTEST_STRINGIFY_(TestName)); \ } \ template \ void GTEST_SUITE_NAMESPACE_( \ SuiteName)::TestName::TestBody() +// Note: this won't work correctly if the trailing arguments are macros. #define REGISTER_TYPED_TEST_SUITE_P(SuiteName, ...) \ namespace GTEST_SUITE_NAMESPACE_(SuiteName) { \ typedef ::testing::internal::Templates<__VA_ARGS__> gtest_AllTests_; \ @@ -302,13 +308,16 @@ INSTANTIATE_TYPED_TEST_SUITE_P(My, FooTest, MyTypes); #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_ #define INSTANTIATE_TYPED_TEST_SUITE_P(Prefix, SuiteName, Types, ...) \ + static_assert(sizeof(GTEST_STRINGIFY_(Prefix)) > 1, \ + "test-suit-prefix must not be empty"); \ static bool gtest_##Prefix##_##SuiteName GTEST_ATTRIBUTE_UNUSED_ = \ ::testing::internal::TypeParameterizedTestSuite< \ SuiteName, GTEST_SUITE_NAMESPACE_(SuiteName)::gtest_AllTests_, \ ::testing::internal::GenerateTypeList::type>:: \ - Register(#Prefix, \ + Register(GTEST_STRINGIFY_(Prefix), \ ::testing::internal::CodeLocation(__FILE__, __LINE__), \ - >EST_TYPED_TEST_SUITE_P_STATE_(SuiteName), #SuiteName, \ + >EST_TYPED_TEST_SUITE_P_STATE_(SuiteName), \ + GTEST_STRINGIFY_(SuiteName), \ GTEST_REGISTERED_TEST_NAMES_(SuiteName), \ ::testing::internal::GenerateNames< \ ::testing::internal::NameGeneratorSelector< \ From dee725b05332ca59a679c7b7dde5297c502d34b4 Mon Sep 17 00:00:00 2001 From: Krystian Kuzniarek Date: Mon, 11 Nov 2019 17:17:52 +0100 Subject: [PATCH 083/541] add documentation for the premature-exit-file protocol --- googletest/docs/advanced.md | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/googletest/docs/advanced.md b/googletest/docs/advanced.md index ce8644e409..217d527a36 100644 --- a/googletest/docs/advanced.md +++ b/googletest/docs/advanced.md @@ -2541,6 +2541,18 @@ IMPORTANT: The exact format of the JSON document is subject to change. ### Controlling How Failures Are Reported +#### Detecting Test Premature Exit + +Google Test implements the _premature-exit-file_ protocol for test runners +to catch any kind of unexpected exits of test programs. Upon start, +Google Test creates the file which will be automatically deleted after +all work has been finished. Then, the test runner can check if this file +exists. In case the file remains undeleted, the inspected test has exited +prematurely. + +This feature is enabled only if the `TEST_PREMATURE_EXIT_FILE` environment +variable has been set. + #### Turning Assertion Failures into Break-Points When running test programs under a debugger, it's very convenient if the From 0c469a5a065e5db8093e0abd1a31648e9b459360 Mon Sep 17 00:00:00 2001 From: Brian Gianforcaro Date: Fri, 15 Nov 2019 17:26:47 -0800 Subject: [PATCH 084/541] Fix FlatTuple compilation on older msvc. googletest 1.10.0 fails to compile on msvc version 19.00.23917 with one compilation error: src\googletest\include\gtest\internal\gtest-internal.h(1188) : error C2039: 'FlatTupleBase,testing::internal::IndexSequence<0,1> >': is not a member of 'testing::internal::FlatTuple' This PR fixes the compilation error by explicitly specifying the full type that Indices is located in the base type. --- googletest/include/gtest/internal/gtest-internal.h | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/googletest/include/gtest/internal/gtest-internal.h b/googletest/include/gtest/internal/gtest-internal.h index f9da4899e2..6175bca0af 100644 --- a/googletest/include/gtest/internal/gtest-internal.h +++ b/googletest/include/gtest/internal/gtest-internal.h @@ -1185,7 +1185,7 @@ struct FlatTupleBase, IndexSequence> // Analog to std::tuple but with different tradeoffs. // This class minimizes the template instantiation depth, thus allowing more -// elements that std::tuple would. std::tuple has been seen to require an +// elements than std::tuple would. std::tuple has been seen to require an // instantiation depth of more than 10x the number of elements in some // implementations. // FlatTuple and ElemFromList are not recursive and have a fixed depth @@ -1196,7 +1196,9 @@ template class FlatTuple : private FlatTupleBase, typename MakeIndexSequence::type> { - using Indices = typename FlatTuple::FlatTupleBase::Indices; + + using Indices = typename FlatTupleBase, + typename MakeIndexSequence::type>::Indices; public: FlatTuple() = default; From dcdb65065f41aad2b706a945108f9d02b381a392 Mon Sep 17 00:00:00 2001 From: xyb Date: Sat, 16 Nov 2019 09:13:52 -0800 Subject: [PATCH 085/541] Fix internal memory leak in Windows _Crt report. We use "MemoryIsNotDeallocated" to aovid internal expected leak reported in Windows _Crt report, like: { #ifdef _MSC_VER MemoryIsNotDeallocated memory_is_not_deeallocated; #endif static ThreadIdToThreadLocals* map = new ThreadIdToThreadLocals(); return map; } But int the above code, only "new ThreadIdToThreadLocals()" is protected, if we invoke "insert()" function of the return value, the memory allocated in "insert()" will be reported to _Crt report also. This change try to fix this issue. --- googletest/src/gtest-port.cc | 3 +++ 1 file changed, 3 insertions(+) diff --git a/googletest/src/gtest-port.cc b/googletest/src/gtest-port.cc index fc5ba6becc..71909c349e 100644 --- a/googletest/src/gtest-port.cc +++ b/googletest/src/gtest-port.cc @@ -536,6 +536,9 @@ class ThreadLocalRegistryImpl { // Returns a value that can be used to identify the thread from other threads. static ThreadLocalValueHolderBase* GetValueOnCurrentThread( const ThreadLocalBase* thread_local_instance) { +#ifdef _MSC_VER + MemoryIsNotDeallocated memory_is_not_deallocated; +#endif // _MSC_VER DWORD current_thread = ::GetCurrentThreadId(); MutexLock lock(&mutex_); ThreadIdToThreadLocals* const thread_to_thread_locals = From 50cfbb726b26700d143ce5bb55c0b5e86de7a1e6 Mon Sep 17 00:00:00 2001 From: Abseil Team Date: Mon, 18 Nov 2019 17:42:08 -0500 Subject: [PATCH 086/541] Googletest export Update stale comments to point to proper location. PiperOrigin-RevId: 281157036 --- googlemock/include/gmock/gmock-generated-actions.h | 2 +- googlemock/include/gmock/gmock-generated-actions.h.pump | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/googlemock/include/gmock/gmock-generated-actions.h b/googlemock/include/gmock/gmock-generated-actions.h index cee96dae8c..5bb626677d 100644 --- a/googlemock/include/gmock/gmock-generated-actions.h +++ b/googlemock/include/gmock/gmock-generated-actions.h @@ -1638,7 +1638,7 @@ struct AdlTag {}; // InvokeArgumentAdl - a helper for InvokeArgument. // The basic overloads are provided here for generic functors. // Overloads for other custom-callables are provided in the -// internal/custom/callback-actions.h header. +// internal/custom/gmock-generated-actions.h header. template R InvokeArgumentAdl(AdlTag, F f) { diff --git a/googlemock/include/gmock/gmock-generated-actions.h.pump b/googlemock/include/gmock/gmock-generated-actions.h.pump index 283abcdc2b..1fa5e776d5 100644 --- a/googlemock/include/gmock/gmock-generated-actions.h.pump +++ b/googlemock/include/gmock/gmock-generated-actions.h.pump @@ -564,7 +564,7 @@ struct AdlTag {}; // InvokeArgumentAdl - a helper for InvokeArgument. // The basic overloads are provided here for generic functors. // Overloads for other custom-callables are provided in the -// internal/custom/callback-actions.h header. +// internal/custom/gmock-generated-actions.h header. $range i 0..n $for i From 4bf466236dbe1db812fab9264d800175eec1cd24 Mon Sep 17 00:00:00 2001 From: Abseil Team Date: Tue, 19 Nov 2019 11:57:57 -0500 Subject: [PATCH 087/541] Googletest export Add a breadcrumb about nullopt comparison near the Optional() matcher. Also add a note about how otherwise-spurious 'Eq()' may be needed in some cases. Without this, something like Field(&MyStruct::optional_field_without_equals_equals, absl::nullopt) doesn't work - it converts the nullopt to an optional<> of the non-equalable type, and fails to select the operator==(optional<>, nullopt_t) overload. The Eq() lets the type persist later into the match. PiperOrigin-RevId: 281305519 --- googlemock/docs/cheat_sheet.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/googlemock/docs/cheat_sheet.md b/googlemock/docs/cheat_sheet.md index 975362bf3b..f6e7349f96 100644 --- a/googlemock/docs/cheat_sheet.md +++ b/googlemock/docs/cheat_sheet.md @@ -266,7 +266,7 @@ Matcher | Description | `IsTrue()` | `argument` evaluates to `true` in a Boolean context. | | `IsNull()` | `argument` is a `NULL` pointer (raw or smart). | | `NotNull()` | `argument` is a non-null pointer (raw or smart). | -| `Optional(m)` | `argument` is `optional<>` that contains a value matching `m`. | +| `Optional(m)` | `argument` is `optional<>` that contains a value matching `m`. (For testing whether an `optional<>` is set, check for equality with `nullopt`. You may need to use `Eq(nullopt)` if the inner type doesn't have `==`.)| | `VariantWith(m)` | `argument` is `variant<>` that holds the alternative of type T with a value matching `m`. | | `Ref(variable)` | `argument` is a reference to `variable`. | | `TypedEq(value)` | `argument` has type `type` and is equal to `value`. You may need to use this instead of `Eq(value)` when the mock function is overloaded. | From 6a9d6d5c28a78bb0f1906d3a6bea5c04f584c24a Mon Sep 17 00:00:00 2001 From: Christoph Strehle Date: Thu, 21 Nov 2019 14:58:09 +0100 Subject: [PATCH 088/541] Fix compile break for Microsoft Visual Studio 2017 v141 This is a workaround, for those who have to compile with v141 build tools, for a bug in msvc that the compiler can't compile the WithArgsAction. see the following link for more details: https://developercommunityapi.westus.cloudapp.azure.com/content/problem/420339/googlemocks-withargs-doesnt-compile-with-permissiv.html --- googlemock/include/gmock/gmock-actions.h | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/googlemock/include/gmock/gmock-actions.h b/googlemock/include/gmock/gmock-actions.h index b040004a20..2146907021 100644 --- a/googlemock/include/gmock/gmock-actions.h +++ b/googlemock/include/gmock/gmock-actions.h @@ -916,7 +916,8 @@ struct WithArgsAction { // We use the conversion operator to detect the signature of the inner Action. template operator Action() const { // NOLINT - Action>::type...)> + using TupleType = std::tuple; + Action::type...)> converted(action); return [converted](Args... args) -> R { From 2241be0c3f2477781c1d9c37b380c1dae1fe37ad Mon Sep 17 00:00:00 2001 From: Krystian Kuzniarek Date: Fri, 22 Nov 2019 16:41:24 +0100 Subject: [PATCH 089/541] remove g++ 3.3 workaround: using on operator<< --- googletest/include/gtest/gtest-printers.h | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/googletest/include/gtest/gtest-printers.h b/googletest/include/gtest/gtest-printers.h index 56a05450ef..c443625f38 100644 --- a/googletest/include/gtest/gtest-printers.h +++ b/googletest/include/gtest/gtest-printers.h @@ -266,10 +266,8 @@ void DefaultPrintNonContainerTo(const T& value, ::std::ostream* os) { // 7.3.4-1 [namespace.udir]. This allows us to fall back onto // testing::internal2::operator<< in case T doesn't come with a << // operator. - // - // We cannot write 'using ::testing::internal2::operator<<;', which - // gcc 3.3 fails to compile due to a compiler bug. - using namespace ::testing::internal2; // NOLINT + + using ::testing::internal2::operator<<; // Assuming T is defined in namespace foo, in the next statement, // the compiler will consider all of: From e1dd49835ef24a70897286dd4bf79df186af596a Mon Sep 17 00:00:00 2001 From: Krystian Kuzniarek Date: Fri, 22 Nov 2019 16:42:32 +0100 Subject: [PATCH 090/541] remove g++ 2.95.0 workaround: no space after first comma in macros --- googletest/test/gtest_unittest.cc | 12 +++--------- 1 file changed, 3 insertions(+), 9 deletions(-) diff --git a/googletest/test/gtest_unittest.cc b/googletest/test/gtest_unittest.cc index d17a15540a..bbace578bb 100644 --- a/googletest/test/gtest_unittest.cc +++ b/googletest/test/gtest_unittest.cc @@ -2924,22 +2924,18 @@ TEST_F(FloatTest, Commutative) { TEST_F(FloatTest, EXPECT_NEAR) { EXPECT_NEAR(-1.0f, -1.1f, 0.2f); EXPECT_NEAR(2.0f, 3.0f, 1.0f); - EXPECT_NONFATAL_FAILURE(EXPECT_NEAR(1.0f,1.5f, 0.25f), // NOLINT + EXPECT_NONFATAL_FAILURE(EXPECT_NEAR(1.0f, 1.5f, 0.25f), // NOLINT "The difference between 1.0f and 1.5f is 0.5, " "which exceeds 0.25f"); - // To work around a bug in gcc 2.95.0, there is intentionally no - // space after the first comma in the previous line. } // Tests ASSERT_NEAR. TEST_F(FloatTest, ASSERT_NEAR) { ASSERT_NEAR(-1.0f, -1.1f, 0.2f); ASSERT_NEAR(2.0f, 3.0f, 1.0f); - EXPECT_FATAL_FAILURE(ASSERT_NEAR(1.0f,1.5f, 0.25f), // NOLINT + EXPECT_FATAL_FAILURE(ASSERT_NEAR(1.0f, 1.5f, 0.25f), // NOLINT "The difference between 1.0f and 1.5f is 0.5, " "which exceeds 0.25f"); - // To work around a bug in gcc 2.95.0, there is intentionally no - // space after the first comma in the previous line. } // Tests the cases where FloatLE() should succeed. @@ -4314,10 +4310,8 @@ TEST(AssertionWithMessageTest, ASSERT_STR) { TEST(AssertionWithMessageTest, ASSERT_FLOATING) { ASSERT_FLOAT_EQ(1, 1) << "This should succeed."; ASSERT_DOUBLE_EQ(1, 1) << "This should succeed."; - EXPECT_FATAL_FAILURE(ASSERT_NEAR(1,1.2, 0.1) << "Expect failure.", // NOLINT + EXPECT_FATAL_FAILURE(ASSERT_NEAR(1, 1.2, 0.1) << "Expect failure.", // NOLINT "Expect failure."); - // To work around a bug in gcc 2.95.0, there is intentionally no - // space after the first comma in the previous statement. } // Tests using ASSERT_FALSE with a streamed message. From a91e4e73b70273deea43e693e615e56f89f68437 Mon Sep 17 00:00:00 2001 From: Krystian Kuzniarek Date: Fri, 22 Nov 2019 16:43:23 +0100 Subject: [PATCH 091/541] remove stale comments about older GCC versions --- googletest/test/gtest_unittest.cc | 12 ------------ 1 file changed, 12 deletions(-) diff --git a/googletest/test/gtest_unittest.cc b/googletest/test/gtest_unittest.cc index d17a15540a..57a991320f 100644 --- a/googletest/test/gtest_unittest.cc +++ b/googletest/test/gtest_unittest.cc @@ -3080,8 +3080,6 @@ TEST_F(DoubleTest, EXPECT_NEAR) { EXPECT_NONFATAL_FAILURE(EXPECT_NEAR(1.0, 1.5, 0.25), // NOLINT "The difference between 1.0 and 1.5 is 0.5, " "which exceeds 0.25"); - // To work around a bug in gcc 2.95.0, there is intentionally no - // space after the first comma in the previous statement. } // Tests ASSERT_NEAR. @@ -3091,8 +3089,6 @@ TEST_F(DoubleTest, ASSERT_NEAR) { EXPECT_FATAL_FAILURE(ASSERT_NEAR(1.0, 1.5, 0.25), // NOLINT "The difference between 1.0 and 1.5 is 0.5, " "which exceeds 0.25"); - // To work around a bug in gcc 2.95.0, there is intentionally no - // space after the first comma in the previous statement. } // Tests the cases where DoubleLE() should succeed. @@ -3734,10 +3730,6 @@ TEST(AssertionTest, ASSERT_EQ) { TEST(AssertionTest, ASSERT_EQ_NULL) { // A success. const char* p = nullptr; - // Some older GCC versions may issue a spurious warning in this or the next - // assertion statement. This warning should not be suppressed with - // static_cast since the test verifies the ability to use bare NULL as the - // expected parameter to the macro. ASSERT_EQ(nullptr, p); // A failure. @@ -4458,10 +4450,6 @@ TEST(ExpectTest, EXPECT_EQ_Double) { TEST(ExpectTest, EXPECT_EQ_NULL) { // A success. const char* p = nullptr; - // Some older GCC versions may issue a spurious warning in this or the next - // assertion statement. This warning should not be suppressed with - // static_cast since the test verifies the ability to use bare NULL as the - // expected parameter to the macro. EXPECT_EQ(nullptr, p); // A failure. From 21d276b5c42d77de89477ff549cfdfda079ab0e3 Mon Sep 17 00:00:00 2001 From: Krystian Kuzniarek Date: Thu, 14 Nov 2019 10:26:49 +0100 Subject: [PATCH 092/541] remove MSVC workaround: accessing namespace scope from within nested classes --- googlemock/test/gmock-matchers_test.cc | 13 ++++--------- 1 file changed, 4 insertions(+), 9 deletions(-) diff --git a/googlemock/test/gmock-matchers_test.cc b/googlemock/test/gmock-matchers_test.cc index bc49cb62e6..799c3706f7 100644 --- a/googlemock/test/gmock-matchers_test.cc +++ b/googlemock/test/gmock-matchers_test.cc @@ -2987,18 +2987,13 @@ TEST(MatcherAssertionTest, WorksWhenMatcherIsNotSatisfied) { static unsigned short n; // NOLINT n = 5; - // VC++ prior to version 8.0 SP1 has a bug where it will not see any - // functions declared in the namespace scope from within nested classes. - // EXPECT/ASSERT_(NON)FATAL_FAILURE macros use nested classes so that all - // namespace-level functions invoked inside them need to be explicitly - // resolved. - EXPECT_FATAL_FAILURE(ASSERT_THAT(n, ::testing::Gt(10)), + EXPECT_FATAL_FAILURE(ASSERT_THAT(n, Gt(10)), "Value of: n\n" "Expected: is > 10\n" " Actual: 5" + OfType("unsigned short")); n = 0; EXPECT_NONFATAL_FAILURE( - EXPECT_THAT(n, ::testing::AllOf(::testing::Le(7), ::testing::Ge(5))), + EXPECT_THAT(n, AllOf(Le(7), Ge(5))), "Value of: n\n" "Expected: (is <= 7) and (is >= 5)\n" " Actual: 0" + OfType("unsigned short")); @@ -3012,11 +3007,11 @@ TEST(MatcherAssertionTest, WorksForByRefArguments) { static int n; n = 0; EXPECT_THAT(n, AllOf(Le(7), Ref(n))); - EXPECT_FATAL_FAILURE(ASSERT_THAT(n, ::testing::Not(::testing::Ref(n))), + EXPECT_FATAL_FAILURE(ASSERT_THAT(n, Not(Ref(n))), "Value of: n\n" "Expected: does not reference the variable @"); // Tests the "Actual" part. - EXPECT_FATAL_FAILURE(ASSERT_THAT(n, ::testing::Not(::testing::Ref(n))), + EXPECT_FATAL_FAILURE(ASSERT_THAT(n, Not(Ref(n))), "Actual: 0" + OfType("int") + ", which is located @"); } From a5136dbdd21eab0a3376c7dcd334607d2f3d6bd5 Mon Sep 17 00:00:00 2001 From: Krystian Kuzniarek Date: Thu, 14 Nov 2019 11:44:42 +0100 Subject: [PATCH 093/541] remove MSVC workaround: error C2665 --- googlemock/test/gmock-generated-matchers_test.cc | 9 --------- 1 file changed, 9 deletions(-) diff --git a/googlemock/test/gmock-generated-matchers_test.cc b/googlemock/test/gmock-generated-matchers_test.cc index f3f49a6896..6783f8f8d0 100644 --- a/googlemock/test/gmock-generated-matchers_test.cc +++ b/googlemock/test/gmock-generated-matchers_test.cc @@ -392,13 +392,6 @@ TEST(ElementsAreTest, AcceptsStringLiteral) { EXPECT_THAT(array, Not(ElementsAre("hi", "one", "too"))); } -#ifndef _MSC_VER - -// The following test passes a value of type const char[] to a -// function template that expects const T&. Some versions of MSVC -// generates a compiler error C2665 for that. We believe it's a bug -// in MSVC. Therefore this test is #if-ed out for MSVC. - // Declared here with the size unknown. Defined AFTER the following test. extern const char kHi[]; @@ -415,8 +408,6 @@ TEST(ElementsAreTest, AcceptsArrayWithUnknownSize) { const char kHi[] = "hi"; -#endif // _MSC_VER - TEST(ElementsAreTest, MakesCopyOfArguments) { int x = 1; int y = 2; From ecefcbd4aa714053befb6a5415cf2640181414ce Mon Sep 17 00:00:00 2001 From: Krystian Kuzniarek Date: Sun, 17 Nov 2019 16:55:07 +0100 Subject: [PATCH 094/541] remove MSVC workaround: warning 4355 --- googlemock/include/gmock/gmock-spec-builders.h | 8 -------- 1 file changed, 8 deletions(-) diff --git a/googlemock/include/gmock/gmock-spec-builders.h b/googlemock/include/gmock/gmock-spec-builders.h index 80c13b5549..718c9484ab 100644 --- a/googlemock/include/gmock/gmock-spec-builders.h +++ b/googlemock/include/gmock/gmock-spec-builders.h @@ -1350,12 +1350,6 @@ class ReferenceOrValueWrapper { T* value_ptr_; }; -// MSVC warns about using 'this' in base member initializer list, so -// we need to temporarily disable the warning. We have to do it for -// the entire class to suppress the warning, even though it's about -// the constructor only. -GTEST_DISABLE_MSC_WARNINGS_PUSH_(4355) - // C++ treats the void type specially. For example, you cannot define // a void-typed variable or pass a void value to a function. // ActionResultHolder holds a value of type T, where T must be a @@ -1786,8 +1780,6 @@ class FunctionMocker final : public UntypedFunctionMockerBase { } }; // class FunctionMocker -GTEST_DISABLE_MSC_WARNINGS_POP_() // 4355 - // Reports an uninteresting call (whose description is in msg) in the // manner specified by 'reaction'. void ReportUninterestingCall(CallReaction reaction, const std::string& msg); From 6748df1eab1dd741a6deffcdd5012d521c1d3a46 Mon Sep 17 00:00:00 2001 From: Krystian Kuzniarek Date: Sun, 17 Nov 2019 18:50:37 +0100 Subject: [PATCH 095/541] remove MSVC workaround: cease const dropping --- googlemock/include/gmock/gmock-matchers.h | 17 +++-------------- 1 file changed, 3 insertions(+), 14 deletions(-) diff --git a/googlemock/include/gmock/gmock-matchers.h b/googlemock/include/gmock/gmock-matchers.h index b8ec24dddf..133033bcd3 100644 --- a/googlemock/include/gmock/gmock-matchers.h +++ b/googlemock/include/gmock/gmock-matchers.h @@ -4057,11 +4057,8 @@ template inline PolymorphicMatcher::type>> ContainerEq(const Container& rhs) { - // This following line is for working around a bug in MSVC 8.0, - // which causes Container to be a const type sometimes. - typedef typename std::remove_const::type RawContainer; return MakePolymorphicMatcher( - internal::ContainerEqMatcher(rhs)); + internal::ContainerEqMatcher(rhs)); } // Returns a matcher that matches a container that, when sorted using @@ -4094,11 +4091,7 @@ template inline internal::PointwiseMatcher::type> Pointwise(const TupleMatcher& tuple_matcher, const Container& rhs) { - // This following line is for working around a bug in MSVC 8.0, - // which causes Container to be a const type sometimes (e.g. when - // rhs is a const int[]).. - typedef typename std::remove_const::type RawContainer; - return internal::PointwiseMatcher( + return internal::PointwiseMatcher( tuple_matcher, rhs); } @@ -4130,14 +4123,10 @@ inline internal::UnorderedElementsAreArrayMatcher< typename std::remove_const::type>::type::value_type>> UnorderedPointwise(const Tuple2Matcher& tuple2_matcher, const RhsContainer& rhs_container) { - // This following line is for working around a bug in MSVC 8.0, - // which causes RhsContainer to be a const type sometimes (e.g. when - // rhs_container is a const int[]). - typedef typename std::remove_const::type RawRhsContainer; // RhsView allows the same code to handle RhsContainer being a // STL-style container and it being a native C-style array. - typedef typename internal::StlContainerView RhsView; + typedef typename internal::StlContainerView RhsView; typedef typename RhsView::type RhsStlContainer; typedef typename RhsStlContainer::value_type Second; const RhsStlContainer& rhs_stl_container = From e0c80b0a6e5162578399e0539bd7de171e9843e4 Mon Sep 17 00:00:00 2001 From: Krystian Kuzniarek Date: Fri, 22 Nov 2019 14:54:41 +0100 Subject: [PATCH 096/541] consistency fix for SafeMatcherCastImpl member functions --- googlemock/include/gmock/gmock-matchers.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/googlemock/include/gmock/gmock-matchers.h b/googlemock/include/gmock/gmock-matchers.h index b8ec24dddf..1078b8d255 100644 --- a/googlemock/include/gmock/gmock-matchers.h +++ b/googlemock/include/gmock/gmock-matchers.h @@ -258,7 +258,7 @@ class SafeMatcherCastImpl { // monomorphic matchers are handled by the next one. template static inline Matcher Cast(const M& polymorphic_matcher_or_value) { - return internal::MatcherCastImpl::Cast(polymorphic_matcher_or_value); + return MatcherCast(polymorphic_matcher_or_value); } // This overload handles monomorphic matchers. From bbbc5d8a4b90b3c372c7cf0ec93c20b6f5cffd23 Mon Sep 17 00:00:00 2001 From: Krystian Kuzniarek Date: Fri, 22 Nov 2019 15:19:25 +0100 Subject: [PATCH 097/541] remove Nokia's Symbian compiler workaround: SafeMatcherCastImpl --- googlemock/include/gmock/gmock-matchers.h | 85 ++++++++++------------- 1 file changed, 36 insertions(+), 49 deletions(-) diff --git a/googlemock/include/gmock/gmock-matchers.h b/googlemock/include/gmock/gmock-matchers.h index 1078b8d255..71f1542b8d 100644 --- a/googlemock/include/gmock/gmock-matchers.h +++ b/googlemock/include/gmock/gmock-matchers.h @@ -247,56 +247,43 @@ inline Matcher MatcherCast(const M& matcher) { return internal::MatcherCastImpl::Cast(matcher); } -// Implements SafeMatcherCast(). -// -// FIXME: The intermediate SafeMatcherCastImpl class was introduced as a -// workaround for a compiler bug, and can now be removed. -template -class SafeMatcherCastImpl { - public: - // This overload handles polymorphic matchers and values only since - // monomorphic matchers are handled by the next one. - template - static inline Matcher Cast(const M& polymorphic_matcher_or_value) { - return MatcherCast(polymorphic_matcher_or_value); - } - - // This overload handles monomorphic matchers. - // - // In general, if type T can be implicitly converted to type U, we can - // safely convert a Matcher to a Matcher (i.e. Matcher is - // contravariant): just keep a copy of the original Matcher, convert the - // argument from type T to U, and then pass it to the underlying Matcher. - // The only exception is when U is a reference and T is not, as the - // underlying Matcher may be interested in the argument's address, which - // is not preserved in the conversion from T to U. - template - static inline Matcher Cast(const Matcher& matcher) { - // Enforce that T can be implicitly converted to U. - GTEST_COMPILE_ASSERT_((std::is_convertible::value), - "T must be implicitly convertible to U"); - // Enforce that we are not converting a non-reference type T to a reference - // type U. - GTEST_COMPILE_ASSERT_( - std::is_reference::value || !std::is_reference::value, - cannot_convert_non_reference_arg_to_reference); - // In case both T and U are arithmetic types, enforce that the - // conversion is not lossy. - typedef GTEST_REMOVE_REFERENCE_AND_CONST_(T) RawT; - typedef GTEST_REMOVE_REFERENCE_AND_CONST_(U) RawU; - const bool kTIsOther = GMOCK_KIND_OF_(RawT) == internal::kOther; - const bool kUIsOther = GMOCK_KIND_OF_(RawU) == internal::kOther; - GTEST_COMPILE_ASSERT_( - kTIsOther || kUIsOther || - (internal::LosslessArithmeticConvertible::value), - conversion_of_arithmetic_types_must_be_lossless); - return MatcherCast(matcher); - } -}; - +// This overload handles polymorphic matchers and values only since +// monomorphic matchers are handled by the next one. template -inline Matcher SafeMatcherCast(const M& polymorphic_matcher) { - return SafeMatcherCastImpl::Cast(polymorphic_matcher); +inline Matcher SafeMatcherCast(const M& polymorphic_matcher_or_value) { + return MatcherCast(polymorphic_matcher_or_value); +} + +// This overload handles monomorphic matchers. +// +// In general, if type T can be implicitly converted to type U, we can +// safely convert a Matcher to a Matcher (i.e. Matcher is +// contravariant): just keep a copy of the original Matcher, convert the +// argument from type T to U, and then pass it to the underlying Matcher. +// The only exception is when U is a reference and T is not, as the +// underlying Matcher may be interested in the argument's address, which +// is not preserved in the conversion from T to U. +template +inline Matcher SafeMatcherCast(const Matcher& matcher) { + // Enforce that T can be implicitly converted to U. + GTEST_COMPILE_ASSERT_((std::is_convertible::value), + "T must be implicitly convertible to U"); + // Enforce that we are not converting a non-reference type T to a reference + // type U. + GTEST_COMPILE_ASSERT_( + std::is_reference::value || !std::is_reference::value, + cannot_convert_non_reference_arg_to_reference); + // In case both T and U are arithmetic types, enforce that the + // conversion is not lossy. + typedef GTEST_REMOVE_REFERENCE_AND_CONST_(T) RawT; + typedef GTEST_REMOVE_REFERENCE_AND_CONST_(U) RawU; + constexpr bool kTIsOther = GMOCK_KIND_OF_(RawT) == internal::kOther; + constexpr bool kUIsOther = GMOCK_KIND_OF_(RawU) == internal::kOther; + GTEST_COMPILE_ASSERT_( + kTIsOther || kUIsOther || + (internal::LosslessArithmeticConvertible::value), + conversion_of_arithmetic_types_must_be_lossless); + return MatcherCast(matcher); } // A() returns a matcher that matches any value of type T. From 298a40f023e6813d2bf73847c3a38ceaf5e46320 Mon Sep 17 00:00:00 2001 From: Krystian Kuzniarek Date: Sun, 17 Nov 2019 16:37:41 +0100 Subject: [PATCH 098/541] remove MSVC workaround: wmain link error in the static library --- googlemock/src/gmock_main.cc | 11 ++--------- 1 file changed, 2 insertions(+), 9 deletions(-) diff --git a/googlemock/src/gmock_main.cc b/googlemock/src/gmock_main.cc index 18c500f663..89c81831e1 100644 --- a/googlemock/src/gmock_main.cc +++ b/googlemock/src/gmock_main.cc @@ -48,20 +48,13 @@ void loop() { RUN_ALL_TESTS(); } #endif #else - -// MS C++ compiler/linker has a bug on Windows (not on Windows CE), which -// causes a link error when _tmain is defined in a static library and UNICODE -// is enabled. For this reason instead of _tmain, main function is used on -// Windows. See the following link to track the current status of this bug: -// https://web.archive.org/web/20170912203238/connect.microsoft.com/VisualStudio/feedback/details/394464/wmain-link-error-in-the-static-library -// // NOLINT -#if GTEST_OS_WINDOWS_MOBILE +#if __MSC_VER # include // NOLINT GTEST_API_ int _tmain(int argc, TCHAR** argv) { #else GTEST_API_ int main(int argc, char** argv) { -#endif // GTEST_OS_WINDOWS_MOBILE +#endif // __MSC_VER std::cout << "Running main() from gmock_main.cc\n"; // Since Google Mock depends on Google Test, InitGoogleMock() is // also responsible for initializing Google Test. Therefore there's From a909becdc599c46bcb57346b6123cb57cd07d15d Mon Sep 17 00:00:00 2001 From: Krystian Kuzniarek Date: Sun, 17 Nov 2019 16:39:03 +0100 Subject: [PATCH 099/541] unify googletest and googlemock main functions --- googlemock/src/gmock_main.cc | 2 +- googletest/src/gtest_main.cc | 11 ++++++++--- 2 files changed, 9 insertions(+), 4 deletions(-) diff --git a/googlemock/src/gmock_main.cc b/googlemock/src/gmock_main.cc index 89c81831e1..d9e71700aa 100644 --- a/googlemock/src/gmock_main.cc +++ b/googlemock/src/gmock_main.cc @@ -55,7 +55,7 @@ GTEST_API_ int _tmain(int argc, TCHAR** argv) { #else GTEST_API_ int main(int argc, char** argv) { #endif // __MSC_VER - std::cout << "Running main() from gmock_main.cc\n"; + std::cout << "Running main() from " << __FILE__ << '\n'; // Since Google Mock depends on Google Test, InitGoogleMock() is // also responsible for initializing Google Test. Therefore there's // no need for calling testing::InitGoogleTest() separately. diff --git a/googletest/src/gtest_main.cc b/googletest/src/gtest_main.cc index 46b27c3d7d..63b2cfd1f2 100644 --- a/googletest/src/gtest_main.cc +++ b/googletest/src/gtest_main.cc @@ -27,7 +27,7 @@ // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -#include +#include #include "gtest/gtest.h" #if GTEST_OS_ESP8266 || GTEST_OS_ESP32 @@ -45,9 +45,14 @@ void loop() { RUN_ALL_TESTS(); } #endif #else +#if __MSC_VER +# include // NOLINT -GTEST_API_ int main(int argc, char **argv) { - printf("Running main() from %s\n", __FILE__); +GTEST_API_ int _tmain(int argc, TCHAR** argv) { +#else +GTEST_API_ int main(int argc, char** argv) { +#endif // __MSC_VER + std::cout << "Running main() from " << __FILE__ << '\n'; testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); } From 717ce7feb87278b81dad756d973693024621f8e8 Mon Sep 17 00:00:00 2001 From: Abseil Team Date: Wed, 20 Nov 2019 14:36:06 -0500 Subject: [PATCH 100/541] Googletest export Use standard C++11 integer types in gtest-port.h. Remove testing::internal::{Int,Uint}{32,64} in favor of types guaranteed to be in since C++11. Tests for built-in integer type coverage are switched from {Int,Uint}64 to [unsigned] long long, which is guaranteed by C++11 to exist and be at least 64-bit wide. PiperOrigin-RevId: 281565263 --- googlemock/include/gmock/gmock-actions.h | 4 +- .../gmock/internal/gmock-internal-utils.h | 6 +- .../include/gmock/internal/gmock-port.h | 6 +- googlemock/test/gmock-actions_test.cc | 12 ++-- googlemock/test/gmock-internal-utils_test.cc | 18 +++--- googlemock/test/gmock-matchers_test.cc | 5 +- .../include/gtest/internal/gtest-internal.h | 11 ++-- .../include/gtest/internal/gtest-port.h | 59 +++++++---------- .../include/gtest/internal/gtest-string.h | 3 +- googletest/src/gtest-internal-inl.h | 36 ++++------- googletest/src/gtest-port.cc | 13 ++-- googletest/src/gtest.cc | 63 +++++++++---------- googletest/test/googletest-printers-test.cc | 26 ++++---- googletest/test/gtest_unittest.cc | 37 ++++++----- 14 files changed, 138 insertions(+), 161 deletions(-) diff --git a/googlemock/include/gmock/gmock-actions.h b/googlemock/include/gmock/gmock-actions.h index b040004a20..dcdbab5a57 100644 --- a/googlemock/include/gmock/gmock-actions.h +++ b/googlemock/include/gmock/gmock-actions.h @@ -162,8 +162,8 @@ GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(unsigned int, 0U); GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(signed int, 0); GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(unsigned long, 0UL); // NOLINT GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(signed long, 0L); // NOLINT -GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(UInt64, 0); -GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(Int64, 0); +GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(unsigned long long, 0); // NOLINT +GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(signed long long, 0); // NOLINT GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(float, 0); GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(double, 0); diff --git a/googlemock/include/gmock/internal/gmock-internal-utils.h b/googlemock/include/gmock/internal/gmock-internal-utils.h index 5fd169e93d..66cf857b7b 100644 --- a/googlemock/include/gmock/internal/gmock-internal-utils.h +++ b/googlemock/include/gmock/internal/gmock-internal-utils.h @@ -136,15 +136,13 @@ GMOCK_DECLARE_KIND_(int, kInteger); GMOCK_DECLARE_KIND_(unsigned int, kInteger); GMOCK_DECLARE_KIND_(long, kInteger); // NOLINT GMOCK_DECLARE_KIND_(unsigned long, kInteger); // NOLINT +GMOCK_DECLARE_KIND_(long long, kInteger); // NOLINT +GMOCK_DECLARE_KIND_(unsigned long long, kInteger); // NOLINT #if GMOCK_WCHAR_T_IS_NATIVE_ GMOCK_DECLARE_KIND_(wchar_t, kInteger); #endif -// Non-standard integer types. -GMOCK_DECLARE_KIND_(Int64, kInteger); -GMOCK_DECLARE_KIND_(UInt64, kInteger); - // All standard floating-point types. GMOCK_DECLARE_KIND_(float, kFloatingPoint); GMOCK_DECLARE_KIND_(double, kFloatingPoint); diff --git a/googlemock/include/gmock/internal/gmock-port.h b/googlemock/include/gmock/internal/gmock-port.h index 063e2929ac..70872ef392 100644 --- a/googlemock/include/gmock/internal/gmock-port.h +++ b/googlemock/include/gmock/internal/gmock-port.h @@ -42,6 +42,7 @@ #include #include +#include #include // Most of the utilities needed for porting Google Mock are also @@ -69,8 +70,7 @@ // Macros for declaring flags. # define GMOCK_DECLARE_bool_(name) extern GTEST_API_ bool GMOCK_FLAG(name) -# define GMOCK_DECLARE_int32_(name) \ - extern GTEST_API_ ::testing::internal::Int32 GMOCK_FLAG(name) +# define GMOCK_DECLARE_int32_(name) extern GTEST_API_ int32_t GMOCK_FLAG(name) # define GMOCK_DECLARE_string_(name) \ extern GTEST_API_ ::std::string GMOCK_FLAG(name) @@ -78,7 +78,7 @@ # define GMOCK_DEFINE_bool_(name, default_val, doc) \ GTEST_API_ bool GMOCK_FLAG(name) = (default_val) # define GMOCK_DEFINE_int32_(name, default_val, doc) \ - GTEST_API_ ::testing::internal::Int32 GMOCK_FLAG(name) = (default_val) + GTEST_API_ int32_t GMOCK_FLAG(name) = (default_val) # define GMOCK_DEFINE_string_(name, default_val, doc) \ GTEST_API_ ::std::string GMOCK_FLAG(name) = (default_val) diff --git a/googlemock/test/gmock-actions_test.cc b/googlemock/test/gmock-actions_test.cc index ae4fa20e49..58a2d35a48 100644 --- a/googlemock/test/gmock-actions_test.cc +++ b/googlemock/test/gmock-actions_test.cc @@ -80,8 +80,6 @@ using testing::SetArgumentPointee; using testing::Unused; using testing::WithArgs; using testing::internal::BuiltInDefaultValue; -using testing::internal::Int64; -using testing::internal::UInt64; #if !GTEST_OS_WINDOWS_MOBILE using testing::SetErrnoAndReturn; @@ -123,8 +121,9 @@ TEST(BuiltInDefaultValueTest, IsZeroForNumericTypes) { EXPECT_EQ(0U, BuiltInDefaultValue::Get()); // NOLINT EXPECT_EQ(0, BuiltInDefaultValue::Get()); // NOLINT EXPECT_EQ(0, BuiltInDefaultValue::Get()); // NOLINT - EXPECT_EQ(0U, BuiltInDefaultValue::Get()); - EXPECT_EQ(0, BuiltInDefaultValue::Get()); + EXPECT_EQ(0U, BuiltInDefaultValue::Get()); // NOLINT + EXPECT_EQ(0, BuiltInDefaultValue::Get()); // NOLINT + EXPECT_EQ(0, BuiltInDefaultValue::Get()); // NOLINT EXPECT_EQ(0, BuiltInDefaultValue::Get()); EXPECT_EQ(0, BuiltInDefaultValue::Get()); } @@ -147,8 +146,9 @@ TEST(BuiltInDefaultValueTest, ExistsForNumericTypes) { EXPECT_TRUE(BuiltInDefaultValue::Exists()); // NOLINT EXPECT_TRUE(BuiltInDefaultValue::Exists()); // NOLINT EXPECT_TRUE(BuiltInDefaultValue::Exists()); // NOLINT - EXPECT_TRUE(BuiltInDefaultValue::Exists()); - EXPECT_TRUE(BuiltInDefaultValue::Exists()); + EXPECT_TRUE(BuiltInDefaultValue::Exists()); // NOLINT + EXPECT_TRUE(BuiltInDefaultValue::Exists()); // NOLINT + EXPECT_TRUE(BuiltInDefaultValue::Exists()); // NOLINT EXPECT_TRUE(BuiltInDefaultValue::Exists()); EXPECT_TRUE(BuiltInDefaultValue::Exists()); } diff --git a/googlemock/test/gmock-internal-utils_test.cc b/googlemock/test/gmock-internal-utils_test.cc index 19ba6fe5c7..8019f4a306 100644 --- a/googlemock/test/gmock-internal-utils_test.cc +++ b/googlemock/test/gmock-internal-utils_test.cc @@ -36,6 +36,7 @@ #include +#include #include #include #include @@ -172,9 +173,9 @@ TEST(KindOfTest, Integer) { EXPECT_EQ(kInteger, GMOCK_KIND_OF_(unsigned int)); // NOLINT EXPECT_EQ(kInteger, GMOCK_KIND_OF_(long)); // NOLINT EXPECT_EQ(kInteger, GMOCK_KIND_OF_(unsigned long)); // NOLINT + EXPECT_EQ(kInteger, GMOCK_KIND_OF_(long long)); // NOLINT + EXPECT_EQ(kInteger, GMOCK_KIND_OF_(unsigned long long)); // NOLINT EXPECT_EQ(kInteger, GMOCK_KIND_OF_(wchar_t)); // NOLINT - EXPECT_EQ(kInteger, GMOCK_KIND_OF_(Int64)); // NOLINT - EXPECT_EQ(kInteger, GMOCK_KIND_OF_(UInt64)); // NOLINT EXPECT_EQ(kInteger, GMOCK_KIND_OF_(size_t)); // NOLINT #if GTEST_OS_LINUX || GTEST_OS_MAC || GTEST_OS_CYGWIN // ssize_t is not defined on Windows and possibly some other OSes. @@ -222,11 +223,12 @@ TEST(LosslessArithmeticConvertibleTest, IntegerToInteger) { EXPECT_TRUE((LosslessArithmeticConvertible::value)); // Unsigned => larger unsigned is fine. - EXPECT_TRUE( - (LosslessArithmeticConvertible::value)); // NOLINT + EXPECT_TRUE((LosslessArithmeticConvertible< + unsigned short, uint64_t>::value)); // NOLINT // Signed => unsigned is not fine. - EXPECT_FALSE((LosslessArithmeticConvertible::value)); // NOLINT + EXPECT_FALSE((LosslessArithmeticConvertible< + short, uint64_t>::value)); // NOLINT EXPECT_FALSE((LosslessArithmeticConvertible< signed char, unsigned int>::value)); // NOLINT @@ -242,12 +244,12 @@ TEST(LosslessArithmeticConvertibleTest, IntegerToInteger) { EXPECT_FALSE((LosslessArithmeticConvertible< unsigned char, signed char>::value)); EXPECT_FALSE((LosslessArithmeticConvertible::value)); - EXPECT_FALSE((LosslessArithmeticConvertible::value)); + EXPECT_FALSE((LosslessArithmeticConvertible::value)); // Larger size => smaller size is not fine. EXPECT_FALSE((LosslessArithmeticConvertible::value)); // NOLINT EXPECT_FALSE((LosslessArithmeticConvertible::value)); - EXPECT_FALSE((LosslessArithmeticConvertible::value)); + EXPECT_FALSE((LosslessArithmeticConvertible::value)); } TEST(LosslessArithmeticConvertibleTest, IntegerToFloatingPoint) { @@ -266,7 +268,7 @@ TEST(LosslessArithmeticConvertibleTest, FloatingPointToBool) { TEST(LosslessArithmeticConvertibleTest, FloatingPointToInteger) { EXPECT_FALSE((LosslessArithmeticConvertible::value)); // NOLINT - EXPECT_FALSE((LosslessArithmeticConvertible::value)); + EXPECT_FALSE((LosslessArithmeticConvertible::value)); EXPECT_FALSE((LosslessArithmeticConvertible::value)); } diff --git a/googlemock/test/gmock-matchers_test.cc b/googlemock/test/gmock-matchers_test.cc index bc49cb62e6..c2c3abd966 100644 --- a/googlemock/test/gmock-matchers_test.cc +++ b/googlemock/test/gmock-matchers_test.cc @@ -46,6 +46,7 @@ #include #include +#include #include #include #include @@ -6028,9 +6029,9 @@ TEST_P(BipartiteRandomTest, LargerNets) { int iters = GetParam().second; MatchMatrix graph(static_cast(nodes), static_cast(nodes)); - auto seed = static_cast(GTEST_FLAG(random_seed)); + auto seed = static_cast(GTEST_FLAG(random_seed)); if (seed == 0) { - seed = static_cast(time(nullptr)); + seed = static_cast(time(nullptr)); } for (; iters > 0; --iters, ++seed) { diff --git a/googletest/include/gtest/internal/gtest-internal.h b/googletest/include/gtest/internal/gtest-internal.h index 44b037ac34..eac831a801 100644 --- a/googletest/include/gtest/internal/gtest-internal.h +++ b/googletest/include/gtest/internal/gtest-internal.h @@ -53,6 +53,7 @@ #include #include #include +#include #include #include #include @@ -842,18 +843,18 @@ struct GTEST_API_ TrueWithString { // but it's good enough for our purposes. class GTEST_API_ Random { public: - static const UInt32 kMaxRange = 1u << 31; + static const uint32_t kMaxRange = 1u << 31; - explicit Random(UInt32 seed) : state_(seed) {} + explicit Random(uint32_t seed) : state_(seed) {} - void Reseed(UInt32 seed) { state_ = seed; } + void Reseed(uint32_t seed) { state_ = seed; } // Generates a random number from [0, range). Crashes if 'range' is // 0 or greater than kMaxRange. - UInt32 Generate(UInt32 range); + uint32_t Generate(uint32_t range); private: - UInt32 state_; + uint32_t state_; GTEST_DISALLOW_COPY_AND_ASSIGN_(Random); }; diff --git a/googletest/include/gtest/internal/gtest-port.h b/googletest/include/gtest/internal/gtest-port.h index 90be25e27e..1812908f21 100644 --- a/googletest/include/gtest/internal/gtest-port.h +++ b/googletest/include/gtest/internal/gtest-port.h @@ -223,8 +223,7 @@ // // Integer types: // TypeWithSize - maps an integer to a int type. -// Int32, UInt32, Int64, UInt64, TimeInMillis -// - integers of known sizes. +// TimeInMillis - integers of known sizes. // BiggestInt - the biggest signed integer type. // // Command-line utilities: @@ -235,7 +234,7 @@ // Environment variable utilities: // GetEnv() - gets the value of an environment variable. // BoolFromGTestEnv() - parses a bool environment variable. -// Int32FromGTestEnv() - parses an Int32 environment variable. +// Int32FromGTestEnv() - parses an int32_t environment variable. // StringFromGTestEnv() - parses a string environment variable. // // Deprecation warnings: @@ -248,6 +247,8 @@ #include #include #include +#include +#include #include #ifndef _WIN32_WCE @@ -1876,12 +1877,9 @@ GTEST_API_ size_t GetThreadCount(); #if GTEST_OS_WINDOWS # define GTEST_PATH_SEP_ "\\" # define GTEST_HAS_ALT_PATH_SEP_ 1 -// The biggest signed integer type the compiler supports. -typedef __int64 BiggestInt; #else # define GTEST_PATH_SEP_ "/" # define GTEST_HAS_ALT_PATH_SEP_ 0 -typedef long long BiggestInt; // NOLINT #endif // GTEST_OS_WINDOWS // Utilities for char. @@ -2084,15 +2082,13 @@ GTEST_DISABLE_MSC_DEPRECATED_POP_() # define GTEST_SNPRINTF_ snprintf #endif -// The maximum number a BiggestInt can represent. This definition -// works no matter BiggestInt is represented in one's complement or -// two's complement. +// The biggest signed integer type the compiler supports. // -// We cannot rely on numeric_limits in STL, as __int64 and long long -// are not part of standard C++ and numeric_limits doesn't need to be -// defined for them. -const BiggestInt kMaxBiggestInt = - ~(static_cast(1) << (8*sizeof(BiggestInt) - 1)); +// long long is guaranteed to be at least 64-bits in C++11. +using BiggestInt = long long; // NOLINT + +// The maximum number a BiggestInt can represent. +constexpr BiggestInt kMaxBiggestInt = std::numeric_limits::max(); // This template class serves as a compile-time function from size to // type. It maps a size in bytes to a primitive type with that @@ -2117,40 +2113,27 @@ class TypeWithSize { public: // This prevents the user from using TypeWithSize with incorrect // values of N. - typedef void UInt; + using UInt = void; }; // The specialization for size 4. template <> class TypeWithSize<4> { public: - // unsigned int has size 4 in both gcc and MSVC. - // - // As base/basictypes.h doesn't compile on Windows, we cannot use - // uint32, uint64, and etc here. - typedef int Int; - typedef unsigned int UInt; + using Int = std::int32_t; + using UInt = std::uint32_t; }; // The specialization for size 8. template <> class TypeWithSize<8> { public: -#if GTEST_OS_WINDOWS - typedef __int64 Int; - typedef unsigned __int64 UInt; -#else - typedef long long Int; // NOLINT - typedef unsigned long long UInt; // NOLINT -#endif // GTEST_OS_WINDOWS + using Int = std::int64_t; + using UInt = std::uint64_t; }; // Integer types of known sizes. -typedef TypeWithSize<4>::Int Int32; -typedef TypeWithSize<4>::UInt UInt32; -typedef TypeWithSize<8>::Int Int64; -typedef TypeWithSize<8>::UInt UInt64; -typedef TypeWithSize<8>::Int TimeInMillis; // Represents time in milliseconds. +using TimeInMillis = int64_t; // Represents time in milliseconds. // Utilities for command line flags and environment variables. @@ -2169,7 +2152,7 @@ typedef TypeWithSize<8>::Int TimeInMillis; // Represents time in milliseconds. // Macros for declaring flags. # define GTEST_DECLARE_bool_(name) GTEST_API_ extern bool GTEST_FLAG(name) # define GTEST_DECLARE_int32_(name) \ - GTEST_API_ extern ::testing::internal::Int32 GTEST_FLAG(name) + GTEST_API_ extern std::int32_t GTEST_FLAG(name) # define GTEST_DECLARE_string_(name) \ GTEST_API_ extern ::std::string GTEST_FLAG(name) @@ -2177,7 +2160,7 @@ typedef TypeWithSize<8>::Int TimeInMillis; // Represents time in milliseconds. # define GTEST_DEFINE_bool_(name, default_val, doc) \ GTEST_API_ bool GTEST_FLAG(name) = (default_val) # define GTEST_DEFINE_int32_(name, default_val, doc) \ - GTEST_API_ ::testing::internal::Int32 GTEST_FLAG(name) = (default_val) + GTEST_API_ std::int32_t GTEST_FLAG(name) = (default_val) # define GTEST_DEFINE_string_(name, default_val, doc) \ GTEST_API_ ::std::string GTEST_FLAG(name) = (default_val) @@ -2192,12 +2175,12 @@ typedef TypeWithSize<8>::Int TimeInMillis; // Represents time in milliseconds. // Parses 'str' for a 32-bit signed integer. If successful, writes the result // to *value and returns true; otherwise leaves *value unchanged and returns // false. -bool ParseInt32(const Message& src_text, const char* str, Int32* value); +bool ParseInt32(const Message& src_text, const char* str, int32_t* value); -// Parses a bool/Int32/string from the environment variable +// Parses a bool/int32_t/string from the environment variable // corresponding to the given Google Test flag. bool BoolFromGTestEnv(const char* flag, bool default_val); -GTEST_API_ Int32 Int32FromGTestEnv(const char* flag, Int32 default_val); +GTEST_API_ int32_t Int32FromGTestEnv(const char* flag, int32_t default_val); std::string OutputFlagAlsoCheckEnvVar(); const char* StringFromGTestEnv(const char* flag, const char* default_val); diff --git a/googletest/include/gtest/internal/gtest-string.h b/googletest/include/gtest/internal/gtest-string.h index 82aaa63bf4..0b2a91a5dc 100644 --- a/googletest/include/gtest/internal/gtest-string.h +++ b/googletest/include/gtest/internal/gtest-string.h @@ -47,6 +47,7 @@ #endif #include +#include #include #include "gtest/internal/gtest-port.h" @@ -152,7 +153,7 @@ class GTEST_API_ String { static std::string FormatHexInt(int value); // Formats an int value as "%X". - static std::string FormatHexUInt32(UInt32 value); + static std::string FormatHexUInt32(uint32_t value); // Formats a byte as "%02X". static std::string FormatByte(unsigned char value); diff --git a/googletest/src/gtest-internal-inl.h b/googletest/src/gtest-internal-inl.h index 8ed70daab0..c3575ee3a4 100644 --- a/googletest/src/gtest-internal-inl.h +++ b/googletest/src/gtest-internal-inl.h @@ -42,6 +42,7 @@ #include // For memmove. #include +#include #include #include #include @@ -123,11 +124,11 @@ GTEST_API_ std::string FormatEpochTimeInMillisAsIso8601(TimeInMillis ms); // On success, stores the value of the flag in *value, and returns // true. On failure, returns false without changing *value. GTEST_API_ bool ParseInt32Flag( - const char* str, const char* flag, Int32* value); + const char* str, const char* flag, int32_t* value); // Returns a random seed in range [1, kMaxRandomSeed] based on the // given --gtest_random_seed flag value. -inline int GetRandomSeedFromFlag(Int32 random_seed_flag) { +inline int GetRandomSeedFromFlag(int32_t random_seed_flag) { const unsigned int raw_seed = (random_seed_flag == 0) ? static_cast(GetTimeInMillis()) : static_cast(random_seed_flag); @@ -213,10 +214,10 @@ class GTestFlagSaver { std::string output_; bool print_time_; bool print_utf8_; - internal::Int32 random_seed_; - internal::Int32 repeat_; + int32_t random_seed_; + int32_t repeat_; bool shuffle_; - internal::Int32 stack_trace_depth_; + int32_t stack_trace_depth_; std::string stream_result_to_; bool throw_on_failure_; } GTEST_ATTRIBUTE_UNUSED_; @@ -227,7 +228,7 @@ class GTestFlagSaver { // If the code_point is not a valid Unicode code point // (i.e. outside of Unicode range U+0 to U+10FFFF) it will be converted // to "(Invalid Unicode 0xXXXXXXXX)". -GTEST_API_ std::string CodePointToUtf8(UInt32 code_point); +GTEST_API_ std::string CodePointToUtf8(uint32_t code_point); // Converts a wide string to a narrow string in UTF-8 encoding. // The wide string is assumed to have the following encoding: @@ -260,10 +261,10 @@ GTEST_API_ bool ShouldShard(const char* total_shards_str, const char* shard_index_str, bool in_subprocess_for_death_test); -// Parses the environment variable var as an Int32. If it is unset, -// returns default_val. If it is not an Int32, prints an error and +// Parses the environment variable var as a 32-bit integer. If it is unset, +// returns default_val. If it is not a 32-bit integer, prints an error and // and aborts. -GTEST_API_ Int32 Int32FromEnvOrDie(const char* env_var, Int32 default_val); +GTEST_API_ int32_t Int32FromEnvOrDie(const char* env_var, int32_t default_val); // Given the total number of shards, the shard index, and the test id, // returns true if and only if the test should be run on this shard. The test id @@ -323,7 +324,7 @@ void ShuffleRange(internal::Random* random, int begin, int end, const int last_in_range = begin + range_width - 1; const int selected = begin + - static_cast(random->Generate(static_cast(range_width))); + static_cast(random->Generate(static_cast(range_width))); std::swap((*v)[static_cast(selected)], (*v)[static_cast(last_in_range)]); } @@ -999,20 +1000,9 @@ bool ParseNaturalNumber(const ::std::string& str, Integer* number) { char* end; // BiggestConvertible is the largest integer type that system-provided // string-to-number conversion routines can return. + using BiggestConvertible = unsigned long long; // NOLINT -# if GTEST_OS_WINDOWS && !defined(__GNUC__) - - // MSVC and C++ Builder define __int64 instead of the standard long long. - typedef unsigned __int64 BiggestConvertible; - const BiggestConvertible parsed = _strtoui64(str.c_str(), &end, 10); - -# else - - typedef unsigned long long BiggestConvertible; // NOLINT - const BiggestConvertible parsed = strtoull(str.c_str(), &end, 10); - -# endif // GTEST_OS_WINDOWS && !defined(__GNUC__) - + const BiggestConvertible parsed = strtoull(str.c_str(), &end, 10); // NOLINT const bool parse_success = *end == '\0' && errno == 0; GTEST_CHECK_(sizeof(Integer) <= sizeof(parsed)); diff --git a/googletest/src/gtest-port.cc b/googletest/src/gtest-port.cc index fc5ba6becc..c6df26d0a3 100644 --- a/googletest/src/gtest-port.cc +++ b/googletest/src/gtest-port.cc @@ -34,6 +34,7 @@ #include #include #include +#include #include #include @@ -1286,7 +1287,7 @@ static std::string FlagToEnvVar(const char* flag) { // Parses 'str' for a 32-bit signed integer. If successful, writes // the result to *value and returns true; otherwise leaves *value // unchanged and returns false. -bool ParseInt32(const Message& src_text, const char* str, Int32* value) { +bool ParseInt32(const Message& src_text, const char* str, int32_t* value) { // Parses the environment variable as a decimal integer. char* end = nullptr; const long long_value = strtol(str, &end, 10); // NOLINT @@ -1303,13 +1304,13 @@ bool ParseInt32(const Message& src_text, const char* str, Int32* value) { return false; } - // Is the parsed value in the range of an Int32? - const Int32 result = static_cast(long_value); + // Is the parsed value in the range of an int32_t? + const auto result = static_cast(long_value); if (long_value == LONG_MAX || long_value == LONG_MIN || // The parsed value overflows as a long. (strtol() returns // LONG_MAX or LONG_MIN when the input overflows.) result != long_value - // The parsed value overflows as an Int32. + // The parsed value overflows as an int32_t. ) { Message msg; msg << "WARNING: " << src_text @@ -1342,7 +1343,7 @@ bool BoolFromGTestEnv(const char* flag, bool default_value) { // Reads and returns a 32-bit integer stored in the environment // variable corresponding to the given flag; if it isn't set or // doesn't represent a valid 32-bit integer, returns default_value. -Int32 Int32FromGTestEnv(const char* flag, Int32 default_value) { +int32_t Int32FromGTestEnv(const char* flag, int32_t default_value) { #if defined(GTEST_GET_INT32_FROM_ENV_) return GTEST_GET_INT32_FROM_ENV_(flag, default_value); #else @@ -1353,7 +1354,7 @@ Int32 Int32FromGTestEnv(const char* flag, Int32 default_value) { return default_value; } - Int32 result = default_value; + int32_t result = default_value; if (!ParseInt32(Message() << "Environment variable " << env_var, string_value, &result)) { printf("The default value %s is used.\n", diff --git a/googletest/src/gtest.cc b/googletest/src/gtest.cc index f079fd4b9a..622865ce81 100644 --- a/googletest/src/gtest.cc +++ b/googletest/src/gtest.cc @@ -44,6 +44,7 @@ #include #include +#include #include #include #include @@ -333,10 +334,10 @@ namespace internal { // Generates a random number from [0, range), using a Linear // Congruential Generator (LCG). Crashes if 'range' is 0 or greater // than kMaxRange. -UInt32 Random::Generate(UInt32 range) { +uint32_t Random::Generate(uint32_t range) { // These constants are the same as are used in glibc's rand(3). // Use wider types than necessary to prevent unsigned overflow diagnostics. - state_ = static_cast(1103515245ULL*state_ + 12345U) % kMaxRange; + state_ = static_cast(1103515245ULL*state_ + 12345U) % kMaxRange; GTEST_CHECK_(range > 0) << "Cannot generate a number in the range [0, 0)."; @@ -1738,33 +1739,33 @@ AssertionResult IsHRESULTFailure(const char* expr, long hr) { // NOLINT // 17 - 21 bits 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx // The maximum code-point a one-byte UTF-8 sequence can represent. -const UInt32 kMaxCodePoint1 = (static_cast(1) << 7) - 1; +constexpr uint32_t kMaxCodePoint1 = (static_cast(1) << 7) - 1; // The maximum code-point a two-byte UTF-8 sequence can represent. -const UInt32 kMaxCodePoint2 = (static_cast(1) << (5 + 6)) - 1; +constexpr uint32_t kMaxCodePoint2 = (static_cast(1) << (5 + 6)) - 1; // The maximum code-point a three-byte UTF-8 sequence can represent. -const UInt32 kMaxCodePoint3 = (static_cast(1) << (4 + 2*6)) - 1; +constexpr uint32_t kMaxCodePoint3 = (static_cast(1) << (4 + 2*6)) - 1; // The maximum code-point a four-byte UTF-8 sequence can represent. -const UInt32 kMaxCodePoint4 = (static_cast(1) << (3 + 3*6)) - 1; +constexpr uint32_t kMaxCodePoint4 = (static_cast(1) << (3 + 3*6)) - 1; // Chops off the n lowest bits from a bit pattern. Returns the n // lowest bits. As a side effect, the original bit pattern will be // shifted to the right by n bits. -inline UInt32 ChopLowBits(UInt32* bits, int n) { - const UInt32 low_bits = *bits & ((static_cast(1) << n) - 1); +inline uint32_t ChopLowBits(uint32_t* bits, int n) { + const uint32_t low_bits = *bits & ((static_cast(1) << n) - 1); *bits >>= n; return low_bits; } // Converts a Unicode code point to a narrow string in UTF-8 encoding. -// code_point parameter is of type UInt32 because wchar_t may not be +// code_point parameter is of type uint32_t because wchar_t may not be // wide enough to contain a code point. // If the code_point is not a valid Unicode code point // (i.e. outside of Unicode range U+0 to U+10FFFF) it will be converted // to "(Invalid Unicode 0xXXXXXXXX)". -std::string CodePointToUtf8(UInt32 code_point) { +std::string CodePointToUtf8(uint32_t code_point) { if (code_point > kMaxCodePoint4) { return "(Invalid Unicode 0x" + String::FormatHexUInt32(code_point) + ")"; } @@ -1805,11 +1806,11 @@ inline bool IsUtf16SurrogatePair(wchar_t first, wchar_t second) { } // Creates a Unicode code point from UTF16 surrogate pair. -inline UInt32 CreateCodePointFromUtf16SurrogatePair(wchar_t first, - wchar_t second) { - const auto first_u = static_cast(first); - const auto second_u = static_cast(second); - const UInt32 mask = (1 << 10) - 1; +inline uint32_t CreateCodePointFromUtf16SurrogatePair(wchar_t first, + wchar_t second) { + const auto first_u = static_cast(first); + const auto second_u = static_cast(second); + const uint32_t mask = (1 << 10) - 1; return (sizeof(wchar_t) == 2) ? (((first_u & mask) << 10) | (second_u & mask)) + 0x10000 : @@ -1837,7 +1838,7 @@ std::string WideStringToUtf8(const wchar_t* str, int num_chars) { ::std::stringstream stream; for (int i = 0; i < num_chars; ++i) { - UInt32 unicode_code_point; + uint32_t unicode_code_point; if (str[i] == L'\0') { break; @@ -1846,7 +1847,7 @@ std::string WideStringToUtf8(const wchar_t* str, int num_chars) { str[i + 1]); i++; } else { - unicode_code_point = static_cast(str[i]); + unicode_code_point = static_cast(str[i]); } stream << CodePointToUtf8(unicode_code_point); @@ -1972,7 +1973,7 @@ std::string String::FormatIntWidth2(int value) { } // Formats an int value as "%X". -std::string String::FormatHexUInt32(UInt32 value) { +std::string String::FormatHexUInt32(uint32_t value) { std::stringstream ss; ss << std::hex << std::uppercase << value; return ss.str(); @@ -1980,7 +1981,7 @@ std::string String::FormatHexUInt32(UInt32 value) { // Formats an int value as "%X". std::string String::FormatHexInt(int value) { - return FormatHexUInt32(static_cast(value)); + return FormatHexUInt32(static_cast(value)); } // Formats a byte as "%02X". @@ -3156,7 +3157,7 @@ void PrettyUnitTestResultPrinter::OnTestIterationStart( } if (internal::ShouldShard(kTestTotalShards, kTestShardIndex, false)) { - const Int32 shard_index = Int32FromEnvOrDie(kTestShardIndex, -1); + const int32_t shard_index = Int32FromEnvOrDie(kTestShardIndex, -1); ColoredPrintf(COLOR_YELLOW, "Note: This is test shard %d of %s.\n", static_cast(shard_index) + 1, @@ -5302,7 +5303,7 @@ bool UnitTestImpl::RunAllTests() { // Shuffles test suites and tests if requested. if (has_tests_to_run && GTEST_FLAG(shuffle)) { - random()->Reseed(static_cast(random_seed_)); + random()->Reseed(static_cast(random_seed_)); // This should be done before calling OnTestIterationStart(), // such that a test event listener can see the actual test order // in the event. @@ -5425,8 +5426,8 @@ bool ShouldShard(const char* total_shards_env, return false; } - const Int32 total_shards = Int32FromEnvOrDie(total_shards_env, -1); - const Int32 shard_index = Int32FromEnvOrDie(shard_index_env, -1); + const int32_t total_shards = Int32FromEnvOrDie(total_shards_env, -1); + const int32_t shard_index = Int32FromEnvOrDie(shard_index_env, -1); if (total_shards == -1 && shard_index == -1) { return false; @@ -5463,13 +5464,13 @@ bool ShouldShard(const char* total_shards_env, // Parses the environment variable var as an Int32. If it is unset, // returns default_val. If it is not an Int32, prints an error // and aborts. -Int32 Int32FromEnvOrDie(const char* var, Int32 default_val) { +int32_t Int32FromEnvOrDie(const char* var, int32_t default_val) { const char* str_val = posix::GetEnv(var); if (str_val == nullptr) { return default_val; } - Int32 result; + int32_t result; if (!ParseInt32(Message() << "The value of environment variable " << var, str_val, &result)) { exit(EXIT_FAILURE); @@ -5493,9 +5494,9 @@ bool ShouldRunTestOnShard(int total_shards, int shard_index, int test_id) { // https://github.com/google/googletest/blob/master/googletest/docs/advanced.md // . Returns the number of tests that should run. int UnitTestImpl::FilterTests(ReactionToSharding shard_tests) { - const Int32 total_shards = shard_tests == HONOR_SHARDING_PROTOCOL ? + const int32_t total_shards = shard_tests == HONOR_SHARDING_PROTOCOL ? Int32FromEnvOrDie(kTestTotalShards, -1) : -1; - const Int32 shard_index = shard_tests == HONOR_SHARDING_PROTOCOL ? + const int32_t shard_index = shard_tests == HONOR_SHARDING_PROTOCOL ? Int32FromEnvOrDie(kTestShardIndex, -1) : -1; // num_runnable_tests are the number of tests that will @@ -5784,12 +5785,11 @@ static bool ParseBoolFlag(const char* str, const char* flag, bool* value) { return true; } -// Parses a string for an Int32 flag, in the form of -// "--flag=value". +// Parses a string for an int32_t flag, in the form of "--flag=value". // // On success, stores the value of the flag in *value, and returns // true. On failure, returns false without changing *value. -bool ParseInt32Flag(const char* str, const char* flag, Int32* value) { +bool ParseInt32Flag(const char* str, const char* flag, int32_t* value) { // Gets the value of the flag as a string. const char* const value_str = ParseFlagValue(str, flag, false); @@ -5801,8 +5801,7 @@ bool ParseInt32Flag(const char* str, const char* flag, Int32* value) { value_str, value); } -// Parses a string for a string flag, in the form of -// "--flag=value". +// Parses a string for a string flag, in the form of "--flag=value". // // On success, stores the value of the flag in *value, and returns // true. On failure, returns false without changing *value. diff --git a/googletest/test/googletest-printers-test.cc b/googletest/test/googletest-printers-test.cc index 58be7d1c86..bf37fb453c 100644 --- a/googletest/test/googletest-printers-test.cc +++ b/googletest/test/googletest-printers-test.cc @@ -33,11 +33,12 @@ // This file tests the universal value printer. #include -#include #include #include +#include #include #include +#include #include #include #include @@ -339,23 +340,25 @@ TEST(PrintBuiltInTypeTest, Wchar_t) { EXPECT_EQ("L'\\xC74D' (51021)", Print(static_cast(0xC74D))); } -// Test that Int64 provides more storage than wchar_t. +// Test that int64_t provides more storage than wchar_t. TEST(PrintTypeSizeTest, Wchar_t) { - EXPECT_LT(sizeof(wchar_t), sizeof(testing::internal::Int64)); + EXPECT_LT(sizeof(wchar_t), sizeof(int64_t)); } // Various integer types. TEST(PrintBuiltInTypeTest, Integer) { EXPECT_EQ("'\\xFF' (255)", Print(static_cast(255))); // uint8 EXPECT_EQ("'\\x80' (-128)", Print(static_cast(-128))); // int8 - EXPECT_EQ("65535", Print(USHRT_MAX)); // uint16 - EXPECT_EQ("-32768", Print(SHRT_MIN)); // int16 - EXPECT_EQ("4294967295", Print(UINT_MAX)); // uint32 - EXPECT_EQ("-2147483648", Print(INT_MIN)); // int32 + EXPECT_EQ("65535", Print(std::numeric_limits::max())); // uint16 + EXPECT_EQ("-32768", Print(std::numeric_limits::min())); // int16 + EXPECT_EQ("4294967295", + Print(std::numeric_limits::max())); // uint32 + EXPECT_EQ("-2147483648", + Print(std::numeric_limits::min())); // int32 EXPECT_EQ("18446744073709551615", - Print(static_cast(-1))); // uint64 + Print(std::numeric_limits::max())); // uint64 EXPECT_EQ("-9223372036854775808", - Print(static_cast(1) << 63)); // int64 + Print(std::numeric_limits::min())); // int64 } // Size types. @@ -977,9 +980,8 @@ TEST(PrintStdTupleTest, VariousSizes) { EXPECT_EQ("(false, 2, 3, 4)", Print(t4)); const char* const str = "8"; - ::std::tuple + ::std::tuple t10(false, 'a', static_cast(3), 4, 5, 1.5F, -2.5, str, // NOLINT nullptr, "10"); EXPECT_EQ("(false, 'a' (97, 0x61), 3, 4, 5, 1.5, -2.5, " + PrintPointer(str) + diff --git a/googletest/test/gtest_unittest.cc b/googletest/test/gtest_unittest.cc index 74379abcdf..5a1e8d034f 100644 --- a/googletest/test/gtest_unittest.cc +++ b/googletest/test/gtest_unittest.cc @@ -60,6 +60,7 @@ TEST(CommandLineFlagsTest, CanBeAccessedInCodeOnceGTestHIsIncluded) { #include #include +#include #include #include #include @@ -249,7 +250,6 @@ using testing::internal::GetTestTypeId; using testing::internal::GetTimeInMillis; using testing::internal::GetTypeId; using testing::internal::GetUnitTestImpl; -using testing::internal::Int32; using testing::internal::Int32FromEnvOrDie; using testing::internal::IsAProtocolMessage; using testing::internal::IsContainer; @@ -271,7 +271,6 @@ using testing::internal::StreamableToString; using testing::internal::String; using testing::internal::TestEventListenersAccessor; using testing::internal::TestResultAccessor; -using testing::internal::UInt32; using testing::internal::UnitTestImpl; using testing::internal::WideStringToUtf8; using testing::internal::edit_distance::CalculateOptimalEdits; @@ -788,7 +787,7 @@ TEST(RandomDeathTest, GeneratesCrashesOnInvalidRange) { } TEST(RandomTest, GeneratesNumbersWithinRange) { - const UInt32 kRange = 10000; + constexpr uint32_t kRange = 10000; testing::internal::Random random(12345); for (int i = 0; i < 10; i++) { EXPECT_LT(random.Generate(kRange), kRange) << " for iteration " << i; @@ -801,10 +800,10 @@ TEST(RandomTest, GeneratesNumbersWithinRange) { } TEST(RandomTest, RepeatsWhenReseeded) { - const int kSeed = 123; - const int kArraySize = 10; - const UInt32 kRange = 10000; - UInt32 values[kArraySize]; + constexpr int kSeed = 123; + constexpr int kArraySize = 10; + constexpr uint32_t kRange = 10000; + uint32_t values[kArraySize]; testing::internal::Random random(kSeed); for (int i = 0; i < kArraySize; i++) { @@ -1772,7 +1771,7 @@ TEST(Int32FromGTestEnvTest, ParsesAndReturnsValidValue) { // Tests that ParseInt32Flag() returns false and doesn't change the // output value when the flag has wrong format TEST(ParseInt32FlagTest, ReturnsFalseForInvalidFlag) { - Int32 value = 123; + int32_t value = 123; EXPECT_FALSE(ParseInt32Flag("--a=100", "b", &value)); EXPECT_EQ(123, value); @@ -1785,7 +1784,7 @@ TEST(ParseInt32FlagTest, ReturnsFalseForInvalidFlag) { TEST(ParseInt32FlagTest, ReturnsDefaultWhenValueOverflows) { printf("(expecting 2 warnings)\n"); - Int32 value = 123; + int32_t value = 123; EXPECT_FALSE(ParseInt32Flag("--abc=12345678987654321", "abc", &value)); EXPECT_EQ(123, value); @@ -1799,7 +1798,7 @@ TEST(ParseInt32FlagTest, ReturnsDefaultWhenValueOverflows) { TEST(ParseInt32FlagTest, ReturnsDefaultWhenValueIsInvalid) { printf("(expecting 2 warnings)\n"); - Int32 value = 123; + int32_t value = 123; EXPECT_FALSE(ParseInt32Flag("--abc=A1", "abc", &value)); EXPECT_EQ(123, value); @@ -1811,7 +1810,7 @@ TEST(ParseInt32FlagTest, ReturnsDefaultWhenValueIsInvalid) { // returns true when the flag represents a valid decimal integer in // the range of an Int32. TEST(ParseInt32FlagTest, ParsesAndReturnsValidValue) { - Int32 value = 123; + int32_t value = 123; EXPECT_TRUE(ParseInt32Flag("--" GTEST_FLAG_PREFIX_ "abc=456", "abc", &value)); EXPECT_EQ(456, value); @@ -1834,7 +1833,7 @@ TEST(Int32FromEnvOrDieTest, ParsesAndReturnsValidValue) { #endif // !GTEST_OS_WINDOWS_MOBILE // Tests that Int32FromEnvOrDie() aborts with an error message -// if the variable is not an Int32. +// if the variable is not an int32_t. TEST(Int32FromEnvOrDieDeathTest, AbortsOnFailure) { SetEnv(GTEST_FLAG_PREFIX_UPPER_ "VAR", "xxx"); EXPECT_DEATH_IF_SUPPORTED( @@ -1843,7 +1842,7 @@ TEST(Int32FromEnvOrDieDeathTest, AbortsOnFailure) { } // Tests that Int32FromEnvOrDie() aborts with an error message -// if the variable cannot be represented by an Int32. +// if the variable cannot be represented by an int32_t. TEST(Int32FromEnvOrDieDeathTest, AbortsOnInt32Overflow) { SetEnv(GTEST_FLAG_PREFIX_UPPER_ "VAR", "1234567891234567891234"); EXPECT_DEATH_IF_SUPPORTED( @@ -5597,7 +5596,7 @@ struct Flags { // Creates a Flags struct where the gtest_random_seed flag has the given // value. - static Flags RandomSeed(Int32 random_seed) { + static Flags RandomSeed(int32_t random_seed) { Flags flags; flags.random_seed = random_seed; return flags; @@ -5605,7 +5604,7 @@ struct Flags { // Creates a Flags struct where the gtest_repeat flag has the given // value. - static Flags Repeat(Int32 repeat) { + static Flags Repeat(int32_t repeat) { Flags flags; flags.repeat = repeat; return flags; @@ -5621,7 +5620,7 @@ struct Flags { // Creates a Flags struct where the GTEST_FLAG(stack_trace_depth) flag has // the given value. - static Flags StackTraceDepth(Int32 stack_trace_depth) { + static Flags StackTraceDepth(int32_t stack_trace_depth) { Flags flags; flags.stack_trace_depth = stack_trace_depth; return flags; @@ -5652,10 +5651,10 @@ struct Flags { bool list_tests; const char* output; bool print_time; - Int32 random_seed; - Int32 repeat; + int32_t random_seed; + int32_t repeat; bool shuffle; - Int32 stack_trace_depth; + int32_t stack_trace_depth; const char* stream_result_to; bool throw_on_failure; }; From 679bfec6db73c021b0226e386c65ec1baee7a09f Mon Sep 17 00:00:00 2001 From: Abseil Team Date: Fri, 22 Nov 2019 11:28:31 -0500 Subject: [PATCH 101/541] Googletest export Fix typo in the predicate assertion table. PiperOrigin-RevId: 281973457 --- googletest/docs/advanced.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/googletest/docs/advanced.md b/googletest/docs/advanced.md index ce8644e409..a9f2dfaea9 100644 --- a/googletest/docs/advanced.md +++ b/googletest/docs/advanced.md @@ -106,7 +106,7 @@ assertion* to get the function arguments printed for free: | Fatal assertion | Nonfatal assertion | Verifies | | --------------------------------- | --------------------------------- | --------------------------- | | `ASSERT_PRED1(pred1, val1)` | `EXPECT_PRED1(pred1, val1)` | `pred1(val1)` is true | -| `ASSERT_PRED2(pred2, val1, val2)` | `EXPECT_PRED2(pred2, val1, val2)` | `pred1(val1, val2)` is true | +| `ASSERT_PRED2(pred2, val1, val2)` | `EXPECT_PRED2(pred2, val1, val2)` | `pred2(val1, val2)` is true | | `...` | `...` | `...` | From 838a32845c641b855c831c36f56cfac22dba7be2 Mon Sep 17 00:00:00 2001 From: Maximilian Schwab Date: Mon, 25 Nov 2019 08:11:28 +0100 Subject: [PATCH 102/541] Fixed typo --- googlemock/scripts/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/googlemock/scripts/README.md b/googlemock/scripts/README.md index fa359fed92..a3301e5bf6 100644 --- a/googlemock/scripts/README.md +++ b/googlemock/scripts/README.md @@ -1,5 +1,5 @@ # Please Note: Files in this directory are no longer supported by the maintainers. They -represent mosty historical artifacts and supported by the community only. There +represent mostly historical artifacts and supported by the community only. There is no guarantee whatsoever that these scripts still work. From 5a62d400e057ddad7d4d55118bf5fd3bc095d65e Mon Sep 17 00:00:00 2001 From: Mate Pek Date: Mon, 25 Nov 2019 23:53:49 +0700 Subject: [PATCH 103/541] README.md: added Catch2 and Google Test Explorer --- README.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/README.md b/README.md index 8be9786c4b..8c18dbc81b 100644 --- a/README.md +++ b/README.md @@ -102,6 +102,10 @@ runs tests from your binary in parallel to provide significant speed-up. is a VS Code extension allowing to view Google Tests in a tree view, and run/debug your tests. +[Catch2 and Google Test Explorer](https://github.com/matepek/vscode-catch2-test-adapter) +is a VS Code extension allowing to view Google Tests in a tree view, and +run/debug your tests. + [Cornichon](https://pypi.org/project/cornichon/) is a small Gherkin DSL parser that generates stub code for Google Test. From 51545ee515fc9f27de0edabc74d96300f43b2966 Mon Sep 17 00:00:00 2001 From: Abseil Team Date: Mon, 25 Nov 2019 05:29:35 -0500 Subject: [PATCH 104/541] Googletest export Make generating goldens work with Python 3 golden_file.write(output) fails with Python 3 with: TypeError: a bytes-like object is required, not 'str' PiperOrigin-RevId: 282316101 --- googletest/test/googletest-output-test.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/googletest/test/googletest-output-test.py b/googletest/test/googletest-output-test.py index c727f17a49..093f6f9561 100755 --- a/googletest/test/googletest-output-test.py +++ b/googletest/test/googletest-output-test.py @@ -331,7 +331,7 @@ def testOutput(self): if CAN_GENERATE_GOLDEN_FILE: output = GetOutputOfAllCommands() golden_file = open(GOLDEN_PATH, 'wb') - golden_file.write(output) + golden_file.write(output.encode()) golden_file.close() else: message = ( From be74b4b2e0d14533b7a394fa45481be9892897ba Mon Sep 17 00:00:00 2001 From: Abseil Team Date: Tue, 26 Nov 2019 12:29:33 -0500 Subject: [PATCH 105/541] Googletest export Wrap call to std::numeric_limits<>::max into round braces to appease MSVC. Closes #2589 PiperOrigin-RevId: 282581361 --- googletest/include/gtest/internal/gtest-port.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/googletest/include/gtest/internal/gtest-port.h b/googletest/include/gtest/internal/gtest-port.h index 1812908f21..fcaac0bbbe 100644 --- a/googletest/include/gtest/internal/gtest-port.h +++ b/googletest/include/gtest/internal/gtest-port.h @@ -2088,7 +2088,7 @@ GTEST_DISABLE_MSC_DEPRECATED_POP_() using BiggestInt = long long; // NOLINT // The maximum number a BiggestInt can represent. -constexpr BiggestInt kMaxBiggestInt = std::numeric_limits::max(); +constexpr BiggestInt kMaxBiggestInt = (std::numeric_limits::max)(); // This template class serves as a compile-time function from size to // type. It maps a size in bytes to a primitive type with that From b8a92f7c86e4bb686bc47bef6dba418b3588e964 Mon Sep 17 00:00:00 2001 From: Oleksandr Yefremov Date: Wed, 27 Nov 2019 10:30:03 +0200 Subject: [PATCH 106/541] Rename test case to test suite --- googletest/docs/primer.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/googletest/docs/primer.md b/googletest/docs/primer.md index 63f0516888..f581d77a9b 100644 --- a/googletest/docs/primer.md +++ b/googletest/docs/primer.md @@ -261,7 +261,7 @@ TEST(TestSuiteName, TestName) { `TEST()` arguments go from general to specific. The *first* argument is the name of the test suite, and the *second* argument is the test's name within the test -case. Both names must be valid C++ identifiers, and they should not contain +suite. Both names must be valid C++ identifiers, and they should not contain any underscores (`_`). A test's *full name* consists of its containing test suite and its individual name. Tests from different test suites can have the same individual name. From 967d8e05c2f006dc0bcebb3b0b28ecc637204b8d Mon Sep 17 00:00:00 2001 From: Krystian Kuzniarek Date: Wed, 27 Nov 2019 15:00:52 +0100 Subject: [PATCH 107/541] Revert "unify googletest and googlemock main functions" This reverts commit a909becdc599c46bcb57346b6123cb57cd07d15d. --- googlemock/src/gmock_main.cc | 2 +- googletest/src/gtest_main.cc | 11 +++-------- 2 files changed, 4 insertions(+), 9 deletions(-) diff --git a/googlemock/src/gmock_main.cc b/googlemock/src/gmock_main.cc index d9e71700aa..89c81831e1 100644 --- a/googlemock/src/gmock_main.cc +++ b/googlemock/src/gmock_main.cc @@ -55,7 +55,7 @@ GTEST_API_ int _tmain(int argc, TCHAR** argv) { #else GTEST_API_ int main(int argc, char** argv) { #endif // __MSC_VER - std::cout << "Running main() from " << __FILE__ << '\n'; + std::cout << "Running main() from gmock_main.cc\n"; // Since Google Mock depends on Google Test, InitGoogleMock() is // also responsible for initializing Google Test. Therefore there's // no need for calling testing::InitGoogleTest() separately. diff --git a/googletest/src/gtest_main.cc b/googletest/src/gtest_main.cc index 63b2cfd1f2..46b27c3d7d 100644 --- a/googletest/src/gtest_main.cc +++ b/googletest/src/gtest_main.cc @@ -27,7 +27,7 @@ // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -#include +#include #include "gtest/gtest.h" #if GTEST_OS_ESP8266 || GTEST_OS_ESP32 @@ -45,14 +45,9 @@ void loop() { RUN_ALL_TESTS(); } #endif #else -#if __MSC_VER -# include // NOLINT -GTEST_API_ int _tmain(int argc, TCHAR** argv) { -#else -GTEST_API_ int main(int argc, char** argv) { -#endif // __MSC_VER - std::cout << "Running main() from " << __FILE__ << '\n'; +GTEST_API_ int main(int argc, char **argv) { + printf("Running main() from %s\n", __FILE__); testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); } From 3957b8898b589fd335971e1bfc5aa5d886a131e5 Mon Sep 17 00:00:00 2001 From: Krystian Kuzniarek Date: Wed, 27 Nov 2019 15:01:03 +0100 Subject: [PATCH 108/541] Revert "remove MSVC workaround: wmain link error in the static library" This reverts commit 298a40f023e6813d2bf73847c3a38ceaf5e46320. --- googlemock/src/gmock_main.cc | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/googlemock/src/gmock_main.cc b/googlemock/src/gmock_main.cc index 89c81831e1..18c500f663 100644 --- a/googlemock/src/gmock_main.cc +++ b/googlemock/src/gmock_main.cc @@ -48,13 +48,20 @@ void loop() { RUN_ALL_TESTS(); } #endif #else -#if __MSC_VER + +// MS C++ compiler/linker has a bug on Windows (not on Windows CE), which +// causes a link error when _tmain is defined in a static library and UNICODE +// is enabled. For this reason instead of _tmain, main function is used on +// Windows. See the following link to track the current status of this bug: +// https://web.archive.org/web/20170912203238/connect.microsoft.com/VisualStudio/feedback/details/394464/wmain-link-error-in-the-static-library +// // NOLINT +#if GTEST_OS_WINDOWS_MOBILE # include // NOLINT GTEST_API_ int _tmain(int argc, TCHAR** argv) { #else GTEST_API_ int main(int argc, char** argv) { -#endif // __MSC_VER +#endif // GTEST_OS_WINDOWS_MOBILE std::cout << "Running main() from gmock_main.cc\n"; // Since Google Mock depends on Google Test, InitGoogleMock() is // also responsible for initializing Google Test. Therefore there's From ae8d1fc81b1469905b3d0fa6f8a077f58fc4b250 Mon Sep 17 00:00:00 2001 From: Abseil Team Date: Mon, 2 Dec 2019 15:30:24 -0500 Subject: [PATCH 109/541] Googletest export Clarify use of IsTrue and IsFalse matchers. These matchers are subtle and confusing: what are they for? The docs in the code are clear, but not very accessible. googletest/googlemock/include/gmock/gmock-more-matchers.h PiperOrigin-RevId: 283393275 --- googlemock/docs/cheat_sheet.md | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/googlemock/docs/cheat_sheet.md b/googlemock/docs/cheat_sheet.md index f6e7349f96..b425e0a0ea 100644 --- a/googlemock/docs/cheat_sheet.md +++ b/googlemock/docs/cheat_sheet.md @@ -278,6 +278,12 @@ copy constructor, try wrap it in `ByRef()`, e.g. `Eq(ByRef(non_copyable_value))`. If you do that, make sure `non_copyable_value` is not changed afterwards, or the meaning of your matcher will be changed. +`IsTrue` and `IsFalse` are useful when you need to use a matcher, or for types +that can be explicitly converted to Boolean, but are not implicitly converted to +Boolean. In other cases, you can use the basic +[`EXPECT_TRUE` and `EXPECT_FALSE`](../../googletest/docs/primer#basic-assertions) +assertions. + #### Floating-Point Matchers {#FpMatchers} From cf75d4b92ecc20bb44ec33aa44eee6685b7595dd Mon Sep 17 00:00:00 2001 From: Abseil Team Date: Thu, 5 Dec 2019 07:26:54 -0500 Subject: [PATCH 110/541] Googletest export Internal change PiperOrigin-RevId: 283948137 --- googletest/test/googletest-output-test.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/googletest/test/googletest-output-test.py b/googletest/test/googletest-output-test.py index 093f6f9561..09028f66f9 100755 --- a/googletest/test/googletest-output-test.py +++ b/googletest/test/googletest-output-test.py @@ -29,7 +29,7 @@ # (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++ Testing and Mocking Framework. +r"""Tests the text output of Google C++ Testing and Mocking Framework. To update the golden file: googletest_output_test.py --build_dir=BUILD/DIR --gengolden From 2002f267f05be6f41a3d458954414ba2bfa3ff1d Mon Sep 17 00:00:00 2001 From: Abseil Team Date: Thu, 5 Dec 2019 12:07:30 -0500 Subject: [PATCH 111/541] Googletest export Update example Environment class destructor annotation PiperOrigin-RevId: 283986183 --- googletest/docs/advanced.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/googletest/docs/advanced.md b/googletest/docs/advanced.md index a9f2dfaea9..10af769eac 100644 --- a/googletest/docs/advanced.md +++ b/googletest/docs/advanced.md @@ -1231,7 +1231,7 @@ environment, which knows how to set-up and tear-down: ```c++ class Environment : public ::testing::Environment { public: - virtual ~Environment() {} + ~Environment() override {} // Override this to define how to set up the environment. void SetUp() override {} From 9ed99c6c837ae1cbfcabd36959fc802ebb5ae07f Mon Sep 17 00:00:00 2001 From: Abseil Team Date: Thu, 5 Dec 2019 15:53:48 -0500 Subject: [PATCH 112/541] Googletest export Change googletest to notice failures during SetUpTestSuite() and TearDownTestSuite(). Previously, errors that occurred during those functions were logged but otherwise ignored. After this change, such failures will cause the test to fail and a brief summary will be printed at the bottom of the test log. See https://github.com/google/googletest/issues/2330. PiperOrigin-RevId: 284033342 --- googletest/include/gtest/gtest.h | 8 ++- googletest/src/gtest.cc | 39 ++++++++++---- googletest/test/BUILD.bazel | 16 ++++++ .../test/googletest-setuptestsuite-test.py | 54 +++++++++++++++++++ .../test/googletest-setuptestsuite-test_.cc | 49 +++++++++++++++++ googletest/test/gtest_unittest.cc | 17 +----- 6 files changed, 152 insertions(+), 31 deletions(-) create mode 100755 googletest/test/googletest-setuptestsuite-test.py create mode 100644 googletest/test/googletest-setuptestsuite-test_.cc diff --git a/googletest/include/gtest/gtest.h b/googletest/include/gtest/gtest.h index 8eda6eac2b..eb44c4cd3e 100644 --- a/googletest/include/gtest/gtest.h +++ b/googletest/include/gtest/gtest.h @@ -412,8 +412,6 @@ class GTEST_API_ Test { // test in test case Foo. Hence a sub-class can define its own // SetUpTestSuite() method to shadow the one defined in the super // class. - // Failures that happen during SetUpTestSuite are logged but otherwise - // ignored. static void SetUpTestSuite() {} // Tears down the stuff shared by all tests in this test suite. @@ -422,8 +420,6 @@ class GTEST_API_ Test { // test in test case Foo. Hence a sub-class can define its own // TearDownTestSuite() method to shadow the one defined in the super // class. - // Failures that happen during TearDownTestSuite are logged but otherwise - // ignored. static void TearDownTestSuite() {} // Legacy API is deprecated but still available @@ -889,7 +885,9 @@ class GTEST_API_ TestSuite { bool Passed() const { return !Failed(); } // Returns true if and only if the test suite failed. - bool Failed() const { return failed_test_count() > 0; } + bool Failed() const { + return failed_test_count() > 0 || ad_hoc_test_result().Failed(); + } // Returns the elapsed time, in milliseconds. TimeInMillis elapsed_time() const { return elapsed_time_; } diff --git a/googletest/src/gtest.cc b/googletest/src/gtest.cc index 622865ce81..3dbf804132 100644 --- a/googletest/src/gtest.cc +++ b/googletest/src/gtest.cc @@ -3138,6 +3138,7 @@ class PrettyUnitTestResultPrinter : public TestEventListener { private: static void PrintFailedTests(const UnitTest& unit_test); + static void PrintFailedTestSuites(const UnitTest& unit_test); static void PrintSkippedTests(const UnitTest& unit_test); }; @@ -3290,9 +3291,8 @@ void PrettyUnitTestResultPrinter::OnEnvironmentsTearDownStart( // Internal helper for printing the list of failed tests. void PrettyUnitTestResultPrinter::PrintFailedTests(const UnitTest& unit_test) { const int failed_test_count = unit_test.failed_test_count(); - if (failed_test_count == 0) { - return; - } + ColoredPrintf(COLOR_RED, "[ FAILED ] "); + printf("%s, listed below:\n", FormatTestCount(failed_test_count).c_str()); for (int i = 0; i < unit_test.total_test_suite_count(); ++i) { const TestSuite& test_suite = *unit_test.GetTestSuite(i); @@ -3310,6 +3310,30 @@ void PrettyUnitTestResultPrinter::PrintFailedTests(const UnitTest& unit_test) { printf("\n"); } } + printf("\n%2d FAILED %s\n", failed_test_count, + failed_test_count == 1 ? "TEST" : "TESTS"); +} + +// Internal helper for printing the list of test suite failures not covered by +// PrintFailedTests. +void PrettyUnitTestResultPrinter::PrintFailedTestSuites( + const UnitTest& unit_test) { + int suite_failure_count = 0; + for (int i = 0; i < unit_test.total_test_suite_count(); ++i) { + const TestSuite& test_suite = *unit_test.GetTestSuite(i); + if (!test_suite.should_run()) { + continue; + } + if (test_suite.ad_hoc_test_result().Failed()) { + ColoredPrintf(COLOR_RED, "[ FAILED ] "); + printf("%s: SetUpTestSuite or TearDownTestSuite\n", test_suite.name()); + ++suite_failure_count; + } + } + if (suite_failure_count > 0) { + printf("\n%2d FAILED TEST %s\n", suite_failure_count, + suite_failure_count == 1 ? "SUITE" : "SUITES"); + } } // Internal helper for printing the list of skipped tests. @@ -3357,19 +3381,14 @@ void PrettyUnitTestResultPrinter::OnTestIterationEnd(const UnitTest& unit_test, PrintSkippedTests(unit_test); } - int num_failures = unit_test.failed_test_count(); if (!unit_test.Passed()) { - const int failed_test_count = unit_test.failed_test_count(); - ColoredPrintf(COLOR_RED, "[ FAILED ] "); - printf("%s, listed below:\n", FormatTestCount(failed_test_count).c_str()); PrintFailedTests(unit_test); - printf("\n%2d FAILED %s\n", num_failures, - num_failures == 1 ? "TEST" : "TESTS"); + PrintFailedTestSuites(unit_test); } int num_disabled = unit_test.reportable_disabled_test_count(); if (num_disabled && !GTEST_FLAG(also_run_disabled_tests)) { - if (!num_failures) { + if (unit_test.Passed()) { printf("\n"); // Add a spacer if no FAILURE banner is displayed. } ColoredPrintf(COLOR_YELLOW, diff --git a/googletest/test/BUILD.bazel b/googletest/test/BUILD.bazel index 224e6e6e01..15f7eef86e 100644 --- a/googletest/test/BUILD.bazel +++ b/googletest/test/BUILD.bazel @@ -65,6 +65,7 @@ cc_test( "googletest-output-test_.cc", "googletest-list-tests-unittest_.cc", "googletest-shuffle-test_.cc", + "googletest-setuptestsuite-test_.cc", "googletest-uninitialized-test_.cc", "googletest-death-test_ex_test.cc", "googletest-param-test-test", @@ -423,6 +424,21 @@ py_test( deps = [":gtest_test_utils"], ) +cc_binary( + name = "googletest-setuptestsuite-test_", + testonly = 1, + srcs = ["googletest-setuptestsuite-test_.cc"], + deps = ["//:gtest_main"], +) + +py_test( + name = "googletest-setuptestsuite-test", + size = "medium", + srcs = ["googletest-setuptestsuite-test.py"], + data = [":googletest-setuptestsuite-test_"], + deps = [":gtest_test_utils"], +) + cc_binary( name = "googletest-uninitialized-test_", testonly = 1, diff --git a/googletest/test/googletest-setuptestsuite-test.py b/googletest/test/googletest-setuptestsuite-test.py new file mode 100755 index 0000000000..c82162fc99 --- /dev/null +++ b/googletest/test/googletest-setuptestsuite-test.py @@ -0,0 +1,54 @@ +#!/usr/bin/env python +# +# Copyright 2019, 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. + +"""Verifies that SetUpTestSuite and TearDownTestSuite errors are noticed.""" + +import gtest_test_utils + +COMMAND = gtest_test_utils.GetTestExecutablePath( + 'googletest-setuptestsuite-test_') + + +class GTestSetUpTestSuiteTest(gtest_test_utils.TestCase): + + def testSetupErrorAndTearDownError(self): + p = gtest_test_utils.Subprocess(COMMAND) + self.assertNotEqual(p.exit_code, 0, msg=p.output) + + self.assertIn( + '[ FAILED ] SetupFailTest: SetUpTestSuite or TearDownTestSuite\n' + '[ FAILED ] TearDownFailTest: SetUpTestSuite or TearDownTestSuite\n' + '\n' + ' 2 FAILED TEST SUITES\n', + p.output) + +if __name__ == '__main__': + gtest_test_utils.Main() diff --git a/googletest/test/googletest-setuptestsuite-test_.cc b/googletest/test/googletest-setuptestsuite-test_.cc new file mode 100644 index 0000000000..a4bc4ef441 --- /dev/null +++ b/googletest/test/googletest-setuptestsuite-test_.cc @@ -0,0 +1,49 @@ +// Copyright 2008, 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. + + +#include "gtest/gtest.h" + +class SetupFailTest : public ::testing::Test { + protected: + static void SetUpTestSuite() { + ASSERT_EQ("", "SET_UP_FAIL"); + } +}; + +TEST_F(SetupFailTest, NoopPassingTest) {} + +class TearDownFailTest : public ::testing::Test { + protected: + static void TearDownTestSuite() { + ASSERT_EQ("", "TEAR_DOWN_FAIL"); + } +}; + +TEST_F(TearDownFailTest, NoopPassingTest) {} diff --git a/googletest/test/gtest_unittest.cc b/googletest/test/gtest_unittest.cc index 5a1e8d034f..d447d1b804 100644 --- a/googletest/test/gtest_unittest.cc +++ b/googletest/test/gtest_unittest.cc @@ -7446,22 +7446,7 @@ TEST(SkipPrefixTest, DoesNotSkipWhenPrefixDoesNotMatch) { } // Tests ad_hoc_test_result(). - -class AdHocTestResultTest : public testing::Test { - protected: - static void SetUpTestSuite() { - FAIL() << "A failure happened inside SetUpTestSuite()."; - } -}; - -TEST_F(AdHocTestResultTest, AdHocTestResultForTestSuiteShowsFailure) { - const testing::TestResult& test_result = testing::UnitTest::GetInstance() - ->current_test_suite() - ->ad_hoc_test_result(); - EXPECT_TRUE(test_result.Failed()); -} - -TEST_F(AdHocTestResultTest, AdHocTestResultTestForUnitTestDoesNotShowFailure) { +TEST(AdHocTestResultTest, AdHocTestResultForUnitTestDoesNotShowFailure) { const testing::TestResult& test_result = testing::UnitTest::GetInstance()->ad_hoc_test_result(); EXPECT_FALSE(test_result.Failed()); From 20b8e7a1c8278c4270705e5648739148a22661d0 Mon Sep 17 00:00:00 2001 From: Ilya Kravchuk Date: Fri, 13 Dec 2019 12:54:37 +0300 Subject: [PATCH 113/541] Activate GNU extensions in case of MSYS generator --- CMakeLists.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index f11bbb521e..755b8b72b5 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -15,7 +15,7 @@ if (CMAKE_VERSION VERSION_LESS "3.1") else() set(CMAKE_CXX_STANDARD 11) set(CMAKE_CXX_STANDARD_REQUIRED ON) - if(NOT CYGWIN) + if(NOT CYGWIN AND NOT MSYS) set(CMAKE_CXX_EXTENSIONS OFF) endif() endif() From 6251071a20e8ebfe9310b736baf55897853adba0 Mon Sep 17 00:00:00 2001 From: misterg Date: Fri, 6 Dec 2019 13:01:34 -0500 Subject: [PATCH 114/541] Googletest export Require all appveyor googletest windows builds to work on Pull Requests to increase CI coverage PiperOrigin-RevId: 284206759 --- appveyor.yml | 2 ++ 1 file changed, 2 insertions(+) diff --git a/appveyor.yml b/appveyor.yml index a58b7687d7..ec155a76ad 100644 --- a/appveyor.yml +++ b/appveyor.yml @@ -8,6 +8,7 @@ environment: generator: "Visual Studio 15 2017" build_system: cmake APPVEYOR_BUILD_WORKER_IMAGE: Visual Studio 2017 + enabled_on_pr: yes - compiler: msvc-15-seh generator: "Visual Studio 15 2017 Win64" @@ -28,6 +29,7 @@ environment: - compiler: msvc-14-seh build_system: cmake generator: "Visual Studio 14 2015 Win64" + enabled_on_pr: yes - compiler: gcc-6.3.0-posix build_system: cmake From d442089d53cecbba59b2d8f35d06eac01f1e46da Mon Sep 17 00:00:00 2001 From: Abseil Team Date: Tue, 10 Dec 2019 22:43:25 -0500 Subject: [PATCH 115/541] Googletest export Detect when C++ parametric tests (TEST_P) are not instantiated. When an un-instantiated TEST_P is found, a new test will be inserted that will emit a warning message. This can be made to error with minor code edits. In the future, that is intended to be the default. PiperOrigin-RevId: 284901666 --- .../include/gtest/internal/gtest-param-util.h | 15 ++++- googletest/src/gtest.cc | 60 +++++++++++++++++++ .../googletest-output-test-golden-lin.txt | 12 +++- googletest/test/googletest-output-test_.cc | 7 +++ googletest/test/googletest-param-test-test.cc | 6 ++ 5 files changed, 96 insertions(+), 4 deletions(-) diff --git a/googletest/include/gtest/internal/gtest-param-util.h b/googletest/include/gtest/internal/gtest-param-util.h index e900b3ffbf..539fa52ec6 100644 --- a/googletest/include/gtest/internal/gtest-param-util.h +++ b/googletest/include/gtest/internal/gtest-param-util.h @@ -42,12 +42,14 @@ #include #include #include +#include #include #include #include "gtest/internal/gtest-internal.h" #include "gtest/internal/gtest-port.h" #include "gtest/gtest-printers.h" +#include "gtest/gtest-test-part.h" namespace testing { // Input to a parameterized test name generator, describing a test parameter. @@ -472,6 +474,8 @@ class ParameterizedTestSuiteInfoBase { GTEST_DISALLOW_COPY_AND_ASSIGN_(ParameterizedTestSuiteInfoBase); }; +void InsertSyntheticTestCase(const std::string &name, CodeLocation location); + // INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE. // // ParameterizedTestSuiteInfo accumulates tests obtained from TEST_P @@ -522,11 +526,13 @@ class ParameterizedTestSuiteInfo : public ParameterizedTestSuiteInfoBase { return 0; // Return value used only to run this method in namespace scope. } // UnitTest class invokes this method to register tests in this test suite - // test suites right before running tests in RUN_ALL_TESTS macro. + // right before running tests in RUN_ALL_TESTS macro. // This method should not be called more than once on any single // instance of a ParameterizedTestSuiteInfoBase derived class. // UnitTest has a guard to prevent from calling this method more than once. void RegisterTests() override { + bool generated_instantiations = false; + for (typename TestInfoContainer::iterator test_it = tests_.begin(); test_it != tests_.end(); ++test_it) { std::shared_ptr test_info = *test_it; @@ -549,6 +555,8 @@ class ParameterizedTestSuiteInfo : public ParameterizedTestSuiteInfoBase { for (typename ParamGenerator::iterator param_it = generator.begin(); param_it != generator.end(); ++param_it, ++i) { + generated_instantiations = true; + Message test_name_stream; std::string param_name = name_func( @@ -577,6 +585,11 @@ class ParameterizedTestSuiteInfo : public ParameterizedTestSuiteInfoBase { } // for param_it } // for gen_it } // for test_it + + if (!generated_instantiations) { + // There are no generaotrs, or they all generate nothing ... + InsertSyntheticTestCase(GetTestSuiteName(), code_location_); + } } // RegisterTests private: diff --git a/googletest/src/gtest.cc b/googletest/src/gtest.cc index 3dbf804132..f6466b92ab 100644 --- a/googletest/src/gtest.cc +++ b/googletest/src/gtest.cc @@ -407,6 +407,66 @@ void AssertHelper::operator=(const Message& message) const { ); // NOLINT } +namespace { + +// When TEST_P is found without a matching INSTANTIATE_TEST_SUITE_P +// to creates test cases for it, a syntetic test case is +// inserted to report ether an error or a log message. +// +// This configuration bit will likely be removed at some point. +constexpr bool kErrorOnUninstantiatedParameterizedTest = false; + +// A test that fails at a given file/line location with a given message. +class FailureTest : public Test { + public: + explicit FailureTest(const CodeLocation& loc, std::string error_message, + bool as_error) + : loc_(loc), + error_message_(std::move(error_message)), + as_error_(as_error) {} + + void TestBody() override { + if (as_error_) { + AssertHelper(TestPartResult::kNonFatalFailure, loc_.file.c_str(), + loc_.line, "") = Message() << error_message_; + } else { + std::cout << error_message_ << std::endl; + } + } + + private: + const CodeLocation loc_; + const std::string error_message_; + const bool as_error_; +}; + + +} // namespace + +// If this parameterized test suite has no instantiations (and that +// has not been marked as okay), emit a test case reporting that. +void InsertSyntheticTestCase(const std::string &name, CodeLocation location) { + std::string message = + "Paramaterized test suite " + name + + " is defined via TEST_P, but never instantiated. None of the test cases " + "will run. Either no INSTANTIATE_TEST_SUITE_P is provided or the only " + "ones provided expand to nothing." + "\n\n" + "Ideally, TEST_P definitions should only ever be included as part of " + "binaries that intend to use them. (As opposed to, for example, being " + "placed in a library that may be linked in to get other utilities.)"; + + std::string full_name = "UninstantiatedParamaterizedTestSuite<" + name + ">"; + RegisterTest( // + "GoogleTestVerification", full_name.c_str(), + nullptr, // No type parameter. + nullptr, // No value parameter. + location.file.c_str(), location.line, [message, location] { + return new FailureTest(location, message, + kErrorOnUninstantiatedParameterizedTest); + }); +} + // A copy of all command line arguments. Set by InitGoogleTest(). static ::std::vector g_argvs; diff --git a/googletest/test/googletest-output-test-golden-lin.txt b/googletest/test/googletest-output-test-golden-lin.txt index 270b15ae67..27f9d489bc 100644 --- a/googletest/test/googletest-output-test-golden-lin.txt +++ b/googletest/test/googletest-output-test-golden-lin.txt @@ -12,7 +12,7 @@ Expected equality of these values: 3 Stack trace: (omitted) -[==========] Running 84 tests from 39 test suites. +[==========] Running 85 tests from 40 test suites. [----------] Global test environment set-up. FooEnvironment::SetUp() called. BarEnvironment::SetUp() called. @@ -979,6 +979,12 @@ Expected failure Stack trace: (omitted) [ FAILED ] PrintingStrings/ParamTest.Failure/a, where GetParam() = "a" +[----------] 1 test from GoogleTestVerification +[ RUN ] GoogleTestVerification.UninstantiatedParamaterizedTestSuite +Paramaterized test suite DetectNotInstantiatedTest is defined via TEST_P, but never instantiated. None of the test cases will run. Either no INSTANTIATE_TEST_SUITE_P is provided or the only ones provided expand to nothing. + +Ideally, TEST_P definitions should only ever be included as part of binaries that intend to use them. (As opposed to, for example, being placed in a library that may be linked in to get other utilities.) +[ OK ] GoogleTestVerification.UninstantiatedParamaterizedTestSuite [----------] Global test environment tear-down BarEnvironment::TearDown() called. googletest-output-test_.cc:#: Failure @@ -992,8 +998,8 @@ Failed Expected fatal failure. Stack trace: (omitted) -[==========] 84 tests from 39 test suites ran. -[ PASSED ] 30 tests. +[==========] 85 tests from 40 test suites ran. +[ PASSED ] 31 tests. [ FAILED ] 54 tests, listed below: [ FAILED ] NonfatalFailureTest.EscapesStringOperands [ FAILED ] NonfatalFailureTest.DiffForLongStrings diff --git a/googletest/test/googletest-output-test_.cc b/googletest/test/googletest-output-test_.cc index f724cca9ce..fe0d83f47c 100644 --- a/googletest/test/googletest-output-test_.cc +++ b/googletest/test/googletest-output-test_.cc @@ -782,6 +782,13 @@ INSTANTIATE_TEST_SUITE_P(PrintingStrings, testing::Values(std::string("a")), ParamNameFunc); +// fails under kErrorOnUninstantiatedParameterizedTest=true +class DetectNotInstantiatedTest : public testing::TestWithParam {}; +TEST_P(DetectNotInstantiatedTest, Used) { } + +// This would make the test failure from the above go away. +// INSTANTIATE_TEST_SUITE_P(Fix, DetectNotInstantiatedTest, testing::Values(1)); + // This #ifdef block tests the output of typed tests. #if GTEST_HAS_TYPED_TEST diff --git a/googletest/test/googletest-param-test-test.cc b/googletest/test/googletest-param-test-test.cc index 2740aaab23..85c76c347a 100644 --- a/googletest/test/googletest-param-test-test.cc +++ b/googletest/test/googletest-param-test-test.cc @@ -1068,6 +1068,12 @@ TEST_P(MyEnumTest, ChecksParamMoreThanZero) { EXPECT_GE(10, GetParam()); } INSTANTIATE_TEST_SUITE_P(MyEnumTests, MyEnumTest, ::testing::Values(ENUM1, ENUM2, 0)); +namespace works_here { +// Never used not instantiated, this should work. +class NotUsedTest : public testing::TestWithParam {}; + +} // namespace works_here + int main(int argc, char **argv) { // Used in TestGenerationTest test suite. AddGlobalTestEnvironment(TestGenerationTest::Environment::Instance()); From d8eeb9760afcab45dbdd887c2b6d106887c1739d Mon Sep 17 00:00:00 2001 From: Abseil Team Date: Wed, 11 Dec 2019 11:15:33 -0500 Subject: [PATCH 116/541] Googletest export Use C++11 variadic templates for ActionHelper in gmock-generated-actions.h. Make ActionHelper use variadic templates to generate Perform static member function specializations instead of using pump.py syntax. PiperOrigin-RevId: 284988441 --- googlemock/include/gmock/gmock-actions.h | 40 ++++++ .../include/gmock/gmock-generated-actions.h | 127 ------------------ .../gmock/gmock-generated-actions.h.pump | 48 ------- 3 files changed, 40 insertions(+), 175 deletions(-) diff --git a/googlemock/include/gmock/gmock-actions.h b/googlemock/include/gmock/gmock-actions.h index c08d97b9dc..4b8dcebb90 100644 --- a/googlemock/include/gmock/gmock-actions.h +++ b/googlemock/include/gmock/gmock-actions.h @@ -1184,6 +1184,46 @@ inline ::std::reference_wrapper ByRef(T& l_value) { // NOLINT return ::std::reference_wrapper(l_value); } +namespace internal { + +// A macro from the ACTION* family (defined later in gmock-generated-actions.h) +// defines an action that can be used in a mock function. Typically, +// these actions only care about a subset of the arguments of the mock +// function. For example, if such an action only uses the second +// argument, it can be used in any mock function that takes >= 2 +// arguments where the type of the second argument is compatible. +// +// Therefore, the action implementation must be prepared to take more +// arguments than it needs. The ExcessiveArg type is used to +// represent those excessive arguments. In order to keep the compiler +// error messages tractable, we define it in the testing namespace +// instead of testing::internal. However, this is an INTERNAL TYPE +// and subject to change without notice, so a user MUST NOT USE THIS +// TYPE DIRECTLY. +struct ExcessiveArg {}; + +// A helper class needed for implementing the ACTION* macros. +template +class ActionHelper { + public: + template + static Result Perform(Impl* impl, const std::tuple& args) { + return Apply(impl, args, MakeIndexSequence{}, + MakeIndexSequence<10 - sizeof...(Ts)>{}); + } + + private: + template + static Result Apply(Impl* impl, const std::tuple& args, + IndexSequence, IndexSequence) { + return impl->template gmock_PerformImpl( + args, std::get(args)..., + ((void)rest_ids, ExcessiveArg())...); + } +}; + +} // namespace internal + } // namespace testing #ifdef _MSC_VER diff --git a/googlemock/include/gmock/gmock-generated-actions.h b/googlemock/include/gmock/gmock-generated-actions.h index 5bb626677d..20b78cd43d 100644 --- a/googlemock/include/gmock/gmock-generated-actions.h +++ b/googlemock/include/gmock/gmock-generated-actions.h @@ -47,133 +47,6 @@ #include "gmock/gmock-actions.h" #include "gmock/internal/gmock-port.h" -namespace testing { -namespace internal { - -// A macro from the ACTION* family (defined later in this file) -// defines an action that can be used in a mock function. Typically, -// these actions only care about a subset of the arguments of the mock -// function. For example, if such an action only uses the second -// argument, it can be used in any mock function that takes >= 2 -// arguments where the type of the second argument is compatible. -// -// Therefore, the action implementation must be prepared to take more -// arguments than it needs. The ExcessiveArg type is used to -// represent those excessive arguments. In order to keep the compiler -// error messages tractable, we define it in the testing namespace -// instead of testing::internal. However, this is an INTERNAL TYPE -// and subject to change without notice, so a user MUST NOT USE THIS -// TYPE DIRECTLY. -struct ExcessiveArg {}; - -// A helper class needed for implementing the ACTION* macros. -template -class ActionHelper { - public: - static Result Perform(Impl* impl, const ::std::tuple<>& args) { - return impl->template gmock_PerformImpl<>(args, ExcessiveArg(), - ExcessiveArg(), ExcessiveArg(), ExcessiveArg(), ExcessiveArg(), - ExcessiveArg(), ExcessiveArg(), ExcessiveArg(), ExcessiveArg(), - ExcessiveArg()); - } - - template - static Result Perform(Impl* impl, const ::std::tuple& args) { - return impl->template gmock_PerformImpl(args, std::get<0>(args), - ExcessiveArg(), ExcessiveArg(), ExcessiveArg(), ExcessiveArg(), - ExcessiveArg(), ExcessiveArg(), ExcessiveArg(), ExcessiveArg(), - ExcessiveArg()); - } - - template - static Result Perform(Impl* impl, const ::std::tuple& args) { - return impl->template gmock_PerformImpl(args, std::get<0>(args), - std::get<1>(args), ExcessiveArg(), ExcessiveArg(), ExcessiveArg(), - ExcessiveArg(), ExcessiveArg(), ExcessiveArg(), ExcessiveArg(), - ExcessiveArg()); - } - - template - static Result Perform(Impl* impl, const ::std::tuple& args) { - return impl->template gmock_PerformImpl(args, - std::get<0>(args), std::get<1>(args), std::get<2>(args), - ExcessiveArg(), ExcessiveArg(), ExcessiveArg(), ExcessiveArg(), - ExcessiveArg(), ExcessiveArg(), ExcessiveArg()); - } - - template - static Result Perform(Impl* impl, const ::std::tuple& args) { - return impl->template gmock_PerformImpl(args, - std::get<0>(args), std::get<1>(args), std::get<2>(args), - std::get<3>(args), ExcessiveArg(), ExcessiveArg(), ExcessiveArg(), - ExcessiveArg(), ExcessiveArg(), ExcessiveArg()); - } - - template - static Result Perform(Impl* impl, const ::std::tuple& args) { - return impl->template gmock_PerformImpl(args, - std::get<0>(args), std::get<1>(args), std::get<2>(args), - std::get<3>(args), std::get<4>(args), ExcessiveArg(), ExcessiveArg(), - ExcessiveArg(), ExcessiveArg(), ExcessiveArg()); - } - - template - static Result Perform(Impl* impl, const ::std::tuple& args) { - return impl->template gmock_PerformImpl(args, - std::get<0>(args), std::get<1>(args), std::get<2>(args), - std::get<3>(args), std::get<4>(args), std::get<5>(args), - ExcessiveArg(), ExcessiveArg(), ExcessiveArg(), ExcessiveArg()); - } - - template - static Result Perform(Impl* impl, const ::std::tuple& args) { - return impl->template gmock_PerformImpl(args, - std::get<0>(args), std::get<1>(args), std::get<2>(args), - std::get<3>(args), std::get<4>(args), std::get<5>(args), - std::get<6>(args), ExcessiveArg(), ExcessiveArg(), ExcessiveArg()); - } - - template - static Result Perform(Impl* impl, const ::std::tuple& args) { - return impl->template gmock_PerformImpl(args, std::get<0>(args), std::get<1>(args), std::get<2>(args), - std::get<3>(args), std::get<4>(args), std::get<5>(args), - std::get<6>(args), std::get<7>(args), ExcessiveArg(), ExcessiveArg()); - } - - template - static Result Perform(Impl* impl, const ::std::tuple& args) { - return impl->template gmock_PerformImpl(args, std::get<0>(args), std::get<1>(args), std::get<2>(args), - std::get<3>(args), std::get<4>(args), std::get<5>(args), - std::get<6>(args), std::get<7>(args), std::get<8>(args), - ExcessiveArg()); - } - - template - static Result Perform(Impl* impl, const ::std::tuple& args) { - return impl->template gmock_PerformImpl(args, std::get<0>(args), std::get<1>(args), std::get<2>(args), - std::get<3>(args), std::get<4>(args), std::get<5>(args), - std::get<6>(args), std::get<7>(args), std::get<8>(args), - std::get<9>(args)); - } -}; - -} // namespace internal -} // namespace testing - // The ACTION* family of macros can be used in a namespace scope to // define custom actions easily. The syntax: // diff --git a/googlemock/include/gmock/gmock-generated-actions.h.pump b/googlemock/include/gmock/gmock-generated-actions.h.pump index 1fa5e776d5..1121fbdec8 100644 --- a/googlemock/include/gmock/gmock-generated-actions.h.pump +++ b/googlemock/include/gmock/gmock-generated-actions.h.pump @@ -49,54 +49,6 @@ $$}} This meta comment fixes auto-indentation in editors. #include "gmock/gmock-actions.h" #include "gmock/internal/gmock-port.h" -namespace testing { -namespace internal { - -// A macro from the ACTION* family (defined later in this file) -// defines an action that can be used in a mock function. Typically, -// these actions only care about a subset of the arguments of the mock -// function. For example, if such an action only uses the second -// argument, it can be used in any mock function that takes >= 2 -// arguments where the type of the second argument is compatible. -// -// Therefore, the action implementation must be prepared to take more -// arguments than it needs. The ExcessiveArg type is used to -// represent those excessive arguments. In order to keep the compiler -// error messages tractable, we define it in the testing namespace -// instead of testing::internal. However, this is an INTERNAL TYPE -// and subject to change without notice, so a user MUST NOT USE THIS -// TYPE DIRECTLY. -struct ExcessiveArg {}; - -// A helper class needed for implementing the ACTION* macros. -template -class ActionHelper { - public: -$range i 0..n -$for i - -[[ -$var template = [[$if i==0 [[]] $else [[ -$range j 0..i-1 - template <$for j, [[typename A$j]]> -]]]] -$range j 0..i-1 -$var As = [[$for j, [[A$j]]]] -$var as = [[$for j, [[std::get<$j>(args)]]]] -$range k 1..n-i -$var eas = [[$for k, [[ExcessiveArg()]]]] -$var arg_list = [[$if (i==0) | (i==n) [[$as$eas]] $else [[$as, $eas]]]] -$template - static Result Perform(Impl* impl, const ::std::tuple<$As>& args) { - return impl->template gmock_PerformImpl<$As>(args, $arg_list); - } - -]] -}; - -} // namespace internal -} // namespace testing - // The ACTION* family of macros can be used in a namespace scope to // define custom actions easily. The syntax: // From d16f86ff1cac9d91859349efb4e0d508ba863024 Mon Sep 17 00:00:00 2001 From: Abseil Team Date: Thu, 12 Dec 2019 12:40:06 -0500 Subject: [PATCH 117/541] Googletest export Add GTEST_API_ to correct a build failure under MSCV. PiperOrigin-RevId: 285208464 --- googletest/include/gtest/internal/gtest-param-util.h | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/googletest/include/gtest/internal/gtest-param-util.h b/googletest/include/gtest/internal/gtest-param-util.h index 539fa52ec6..70c43354e6 100644 --- a/googletest/include/gtest/internal/gtest-param-util.h +++ b/googletest/include/gtest/internal/gtest-param-util.h @@ -474,7 +474,8 @@ class ParameterizedTestSuiteInfoBase { GTEST_DISALLOW_COPY_AND_ASSIGN_(ParameterizedTestSuiteInfoBase); }; -void InsertSyntheticTestCase(const std::string &name, CodeLocation location); +GTEST_API_ void InsertSyntheticTestCase(const std::string& name, + CodeLocation location); // INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE. // From d2016469064bdb488ce271c84684518d2716fec2 Mon Sep 17 00:00:00 2001 From: Shahbaz Youssefi Date: Mon, 16 Dec 2019 11:23:21 -0500 Subject: [PATCH 118/541] Workaround VS bug w.r.t empty arguments to macros Empty arguments can be passed to macros per C99 and C++11 specs, which can then be forwarded to other macros. Visual Studio's compiler has a bug in the following situation: #define A(x) #x #define B(x, y) A(x) B(, b) In the above case, Visual Studio first expands x to nothing, then complains that A is not invoked with the right amount of arguments. However, x in A(x) is still one argument, even if it expands to no preprocessing tokens. See also https://stackoverflow.com/a/7674214. --- googletest/include/gtest/internal/gtest-internal.h | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/googletest/include/gtest/internal/gtest-internal.h b/googletest/include/gtest/internal/gtest-internal.h index eac831a801..978728e392 100644 --- a/googletest/include/gtest/internal/gtest-internal.h +++ b/googletest/include/gtest/internal/gtest-internal.h @@ -79,7 +79,16 @@ #define GTEST_CONCAT_TOKEN_IMPL_(foo, bar) foo ## bar // Stringifies its argument. -#define GTEST_STRINGIFY_(name) #name +// Work around a bug in visual studio which doesn't accept code like this: +// +// #define GTEST_STRINGIFY_(name) #name +// #define MACRO(a, b, c) ... GTEST_STRINGIFY_(a) ... +// MACRO(, x, y) +// +// Complaining about the argument to GTEST_STRINGIFY_ being empty. +// This is allowed by the spec. +#define GTEST_STRINGIFY_HELPER_(name, ...) #name +#define GTEST_STRINGIFY_(...) GTEST_STRINGIFY_HELPER_(__VA_ARGS__,) namespace proto2 { class Message; } From 4b7809c2f5236b16a2e3b45e2b5ade48fb6a3c0c Mon Sep 17 00:00:00 2001 From: Shahbaz Youssefi Date: Tue, 10 Dec 2019 09:59:56 -0500 Subject: [PATCH 119/541] Revert "Googletest export": Remove test for empty prefix This reverts commit 4c25e2b87fcb78abcfdee2739db9ed7a19754cd3. Reason for revert: Reverting the commit that disallows empty prefixes. Original commit message: Remove a test case rendered obsolete by disallowing empty argument for INSTANTIATE_TEST_SUITE_P. Remove the code that it was testing. --- googletest/include/gtest/internal/gtest-param-util.h | 5 ++++- googletest/test/googletest-output-test-golden-lin.txt | 9 ++++++--- googletest/test/googletest-output-test_.cc | 8 ++++++++ 3 files changed, 18 insertions(+), 4 deletions(-) diff --git a/googletest/include/gtest/internal/gtest-param-util.h b/googletest/include/gtest/internal/gtest-param-util.h index 70c43354e6..3f2495bfce 100644 --- a/googletest/include/gtest/internal/gtest-param-util.h +++ b/googletest/include/gtest/internal/gtest-param-util.h @@ -574,7 +574,10 @@ class ParameterizedTestSuiteInfo : public ParameterizedTestSuiteInfoBase { test_param_names.insert(param_name); - test_name_stream << test_info->test_base_name << "/" << param_name; + if (!test_info->test_base_name.empty()) { + test_name_stream << test_info->test_base_name << "/"; + } + test_name_stream << param_name; MakeAndRegisterTestInfo( test_suite_name.c_str(), test_name_stream.GetString().c_str(), nullptr, // No type parameter. diff --git a/googletest/test/googletest-output-test-golden-lin.txt b/googletest/test/googletest-output-test-golden-lin.txt index 27f9d489bc..a4cade31a3 100644 --- a/googletest/test/googletest-output-test-golden-lin.txt +++ b/googletest/test/googletest-output-test-golden-lin.txt @@ -12,7 +12,7 @@ Expected equality of these values: 3 Stack trace: (omitted) -[==========] Running 85 tests from 40 test suites. +[==========] Running 86 tests from 41 test suites. [----------] Global test environment set-up. FooEnvironment::SetUp() called. BarEnvironment::SetUp() called. @@ -966,6 +966,9 @@ Expected equality of these values: Stack trace: (omitted) [ FAILED ] PrintingFailingParams/FailingParamTest.Fails/0, where GetParam() = 2 +[----------] 1 test from All/EmptyBasenameParamInst +[ RUN ] All/EmptyBasenameParamInst.Passes/0 +[ OK ] All/EmptyBasenameParamInst.Passes/0 [----------] 2 tests from PrintingStrings/ParamTest [ RUN ] PrintingStrings/ParamTest.Success/a [ OK ] PrintingStrings/ParamTest.Success/a @@ -998,8 +1001,8 @@ Failed Expected fatal failure. Stack trace: (omitted) -[==========] 85 tests from 40 test suites ran. -[ PASSED ] 31 tests. +[==========] 86 tests from 41 test suites ran. +[ PASSED ] 32 tests. [ FAILED ] 54 tests, listed below: [ FAILED ] NonfatalFailureTest.EscapesStringOperands [ FAILED ] NonfatalFailureTest.DiffForLongStrings diff --git a/googletest/test/googletest-output-test_.cc b/googletest/test/googletest-output-test_.cc index fe0d83f47c..59b2c89b81 100644 --- a/googletest/test/googletest-output-test_.cc +++ b/googletest/test/googletest-output-test_.cc @@ -96,6 +96,14 @@ INSTANTIATE_TEST_SUITE_P(PrintingFailingParams, FailingParamTest, testing::Values(2)); +// Tests that an empty value for the test suite basename yields just +// the test name without any prior / +class EmptyBasenameParamInst : public testing::TestWithParam {}; + +TEST_P(EmptyBasenameParamInst, Passes) { EXPECT_EQ(1, GetParam()); } + +INSTANTIATE_TEST_SUITE_P(All, EmptyBasenameParamInst, testing::Values(1)); + static const char kGoldenString[] = "\"Line\0 1\"\nLine 2"; TEST(NonfatalFailureTest, EscapesStringOperands) { From 1800a38fb7d8d4f923fc450875afa3bc16f01151 Mon Sep 17 00:00:00 2001 From: Shahbaz Youssefi Date: Tue, 10 Dec 2019 10:01:25 -0500 Subject: [PATCH 120/541] Revert "Googletest export": disallow empty prefix This reverts commit 20b5b8ecc7a81d23b4716e22a2b35fd53379c8c6. Reason for revert: Breaks existing applications, such as ANGLE (angleproject.org), requires adding an extra prefix that needs to be typed for no reason (when testing from command line) and increases the logs' sizes by a non-trivial amount due to the very large number of tests ANGLE runs. Original commit message: Add a compile time check to ensure that the parameters to TEST_P and INSTANTIATE_TEST_SUITE_P are not empty. Some compilers already fail in that case and, even where it works, it's likely to result in technically invalid code by virtue of creating reserved identifiers: https://en.cppreference.com/w/cpp/language/identifiers First, every project is perfectly capable of adding a prefix if they want to support such a compiler. This change penalizes every project. Second, using a prefix such as `_p` also results in reserved identifiers, so this change is not really solving the problem. For that matter, instead of generating `gtest_##prefix##...`, you can generate `gtest_x##prefix##...` to correctly fix the issue, including when empty prefixes are used. --- googletest/include/gtest/gtest-param-test.h | 20 +++++-------------- .../googletest-output-test-golden-lin.txt | 6 +++--- googletest/test/googletest-output-test_.cc | 2 +- googletest/test/gtest_unittest.cc | 2 +- 4 files changed, 10 insertions(+), 20 deletions(-) diff --git a/googletest/include/gtest/gtest-param-test.h b/googletest/include/gtest/gtest-param-test.h index f61e3c5d88..70593da533 100644 --- a/googletest/include/gtest/gtest-param-test.h +++ b/googletest/include/gtest/gtest-param-test.h @@ -58,9 +58,7 @@ class FooTest : public ::testing::TestWithParam { // Then, use the TEST_P macro to define as many parameterized tests // for this fixture as you want. The _P suffix is for "parameterized" -// or "pattern", whichever you prefer to think. The arguments to the -// TEST_P macro are the test_suite_name and test_case (both which must be -// non-empty) that will form the test name. +// or "pattern", whichever you prefer to think. TEST_P(FooTest, DoesBlah) { // Inside a test, access the test parameter with the GetParam() method @@ -103,10 +101,10 @@ INSTANTIATE_TEST_SUITE_P(InstantiationName, // To distinguish different instances of the pattern, (yes, you // can instantiate it more than once) the first argument to the -// INSTANTIATE_TEST_SUITE_P macro is a prefix (which must be non-empty) that -// will be added to the actual test suite name. Remember to pick unique prefixes -// for different instantiations. The tests from the instantiation above will -// have these names: +// INSTANTIATE_TEST_SUITE_P macro is a prefix that will be added to the +// actual test suite name. Remember to pick unique prefixes for different +// instantiations. The tests from the instantiation above will have +// these names: // // * InstantiationName/FooTest.DoesBlah/0 for "meeny" // * InstantiationName/FooTest.DoesBlah/1 for "miny" @@ -414,10 +412,6 @@ internal::CartesianProductHolder Combine(const Generator&... g) { } #define TEST_P(test_suite_name, test_name) \ - static_assert(sizeof(GTEST_STRINGIFY_(test_suite_name)) > 1, \ - "test_suite_name must not be empty"); \ - static_assert(sizeof(GTEST_STRINGIFY_(test_name)) > 1, \ - "test_name must not be empty"); \ class GTEST_TEST_CLASS_NAME_(test_suite_name, test_name) \ : public test_suite_name { \ public: \ @@ -464,10 +458,6 @@ internal::CartesianProductHolder Combine(const Generator&... g) { #define GTEST_GET_SECOND_(first, second, ...) second #define INSTANTIATE_TEST_SUITE_P(prefix, test_suite_name, ...) \ - static_assert(sizeof(GTEST_STRINGIFY_(test_suite_name)) > 1, \ - "test_suite_name must not be empty"); \ - static_assert(sizeof(GTEST_STRINGIFY_(prefix)) > 1, \ - "prefix must not be empty"); \ static ::testing::internal::ParamGenerator \ gtest_##prefix##test_suite_name##_EvalGenerator_() { \ return GTEST_EXPAND_(GTEST_GET_FIRST_(__VA_ARGS__, DUMMY_PARAM_)); \ diff --git a/googletest/test/googletest-output-test-golden-lin.txt b/googletest/test/googletest-output-test-golden-lin.txt index a4cade31a3..a08140e159 100644 --- a/googletest/test/googletest-output-test-golden-lin.txt +++ b/googletest/test/googletest-output-test-golden-lin.txt @@ -966,9 +966,9 @@ Expected equality of these values: Stack trace: (omitted) [ FAILED ] PrintingFailingParams/FailingParamTest.Fails/0, where GetParam() = 2 -[----------] 1 test from All/EmptyBasenameParamInst -[ RUN ] All/EmptyBasenameParamInst.Passes/0 -[ OK ] All/EmptyBasenameParamInst.Passes/0 +[----------] 1 test from EmptyBasenameParamInst +[ RUN ] EmptyBasenameParamInst.Passes/0 +[ OK ] EmptyBasenameParamInst.Passes/0 [----------] 2 tests from PrintingStrings/ParamTest [ RUN ] PrintingStrings/ParamTest.Success/a [ OK ] PrintingStrings/ParamTest.Success/a diff --git a/googletest/test/googletest-output-test_.cc b/googletest/test/googletest-output-test_.cc index 59b2c89b81..1c7943c3d7 100644 --- a/googletest/test/googletest-output-test_.cc +++ b/googletest/test/googletest-output-test_.cc @@ -102,7 +102,7 @@ class EmptyBasenameParamInst : public testing::TestWithParam {}; TEST_P(EmptyBasenameParamInst, Passes) { EXPECT_EQ(1, GetParam()); } -INSTANTIATE_TEST_SUITE_P(All, EmptyBasenameParamInst, testing::Values(1)); +INSTANTIATE_TEST_SUITE_P(, EmptyBasenameParamInst, testing::Values(1)); static const char kGoldenString[] = "\"Line\0 1\"\nLine 2"; diff --git a/googletest/test/gtest_unittest.cc b/googletest/test/gtest_unittest.cc index 7acc22802d..83df6a7123 100644 --- a/googletest/test/gtest_unittest.cc +++ b/googletest/test/gtest_unittest.cc @@ -5349,7 +5349,7 @@ TEST_P(CodeLocationForTESTP, Verify) { VERIFY_CODE_LOCATION; } -INSTANTIATE_TEST_SUITE_P(All, CodeLocationForTESTP, Values(0)); +INSTANTIATE_TEST_SUITE_P(, CodeLocationForTESTP, Values(0)); template class CodeLocationForTYPEDTEST : public Test { From 0a0c826629926bb688f17fc4380dace434b66cc4 Mon Sep 17 00:00:00 2001 From: krzysio Date: Mon, 16 Dec 2019 12:41:00 -0500 Subject: [PATCH 121/541] Googletest export Don't use fully qualified ::std types in code examples. Having a nested user-defined 'std' namespace anywhere in a program is a minefield and shouldn't be either explicitly supported or implicitly condoned. PiperOrigin-RevId: 285790182 --- googlemock/docs/cook_book.md | 35 +++++++++++++++++------------------ 1 file changed, 17 insertions(+), 18 deletions(-) diff --git a/googlemock/docs/cook_book.md b/googlemock/docs/cook_book.md index ea55ab3583..69c5e4ac4a 100644 --- a/googlemock/docs/cook_book.md +++ b/googlemock/docs/cook_book.md @@ -1024,9 +1024,8 @@ using ::testing::Lt; says that the first argument of `InRange()` must not be 0, and must be less than the second argument. -The expression inside `With()` must be a matcher of type -`Matcher< ::std::tuple >`, where `A1`, ..., `An` are the types of -the function arguments. +The expression inside `With()` must be a matcher of type `Matcher>`, where `A1`, ..., `An` are the types of the function arguments. You can also write `AllArgs(m)` instead of `m` inside `.With()`. The two forms are equivalent, but `.With(AllArgs(Lt()))` is more readable than `.With(Lt())`. @@ -1054,8 +1053,8 @@ complete list. Note that if you want to pass the arguments to a predicate of your own (e.g. `.With(Args<0, 1>(Truly(&MyPredicate)))`), that predicate MUST be written to -take a `::std::tuple` as its argument; gMock will pass the `n` selected -arguments as *one* single tuple to the predicate. +take a `std::tuple` as its argument; gMock will pass the `n` selected arguments +as *one* single tuple to the predicate. ### Using Matchers as Predicates @@ -1331,11 +1330,11 @@ class BarPlusBazEqMatcher : public MatcherInterface { return (foo.bar() + foo.baz()) == expected_sum_; } - void DescribeTo(::std::ostream* os) const override { + void DescribeTo(std::ostream* os) const override { *os << "bar() + baz() equals " << expected_sum_; } - void DescribeNegationTo(::std::ostream* os) const override { + void DescribeNegationTo(std::ostream* os) const override { *os << "bar() + baz() does not equal " << expected_sum_; } private: @@ -3565,7 +3564,7 @@ class MatchResultListener { MatchResultListener& operator<<(const T& x); // Returns the underlying ostream. - ::std::ostream* stream(); + std::ostream* stream(); }; template @@ -3578,10 +3577,10 @@ class MatcherInterface { virtual bool MatchAndExplain(T x, MatchResultListener* listener) const = 0; // Describes this matcher to an ostream. - virtual void DescribeTo(::std::ostream* os) const = 0; + virtual void DescribeTo(std::ostream* os) const = 0; // Describes the negation of this matcher to an ostream. - virtual void DescribeNegationTo(::std::ostream* os) const; + virtual void DescribeNegationTo(std::ostream* os) const; }; ``` @@ -3609,11 +3608,11 @@ class DivisibleBy7Matcher : public MatcherInterface { return (n % 7) == 0; } - void DescribeTo(::std::ostream* os) const override { + void DescribeTo(std::ostream* os) const override { *os << "is divisible by 7"; } - void DescribeNegationTo(::std::ostream* os) const override { + void DescribeNegationTo(std::ostream* os) const override { *os << "is not divisible by 7"; } }; @@ -3995,7 +3994,7 @@ ACTION_TEMPLATE(DuplicateArg, // Note the comma between int and k: HAS_2_TEMPLATE_PARAMS(int, k, typename, T), AND_1_VALUE_PARAMS(output)) { - *output = T(::std::get(args)); + *output = T(std::get(args)); } ``` @@ -4087,7 +4086,7 @@ class ActionInterface { // // For example, if F is int(bool, const string&), then Result would - // be int, and ArgumentTuple would be ::std::tuple. + // be int, and ArgumentTuple would be std::tuple. virtual Result Perform(const ArgumentTuple& args) = 0; }; ``` @@ -4102,8 +4101,8 @@ typedef int IncrementMethod(int*); class IncrementArgumentAction : public ActionInterface { public: - int Perform(const ::std::tuple& args) override { - int* p = ::std::get<0>(args); // Grabs the first argument. + int Perform(const std::tuple& args) override { + int* p = std::get<0>(args); // Grabs the first argument. return *p++; } }; @@ -4148,8 +4147,8 @@ class ReturnSecondArgumentAction { public: template Result Perform(const ArgumentTuple& args) const { - // To get the i-th (0-based) argument, use ::std::get(args). - return ::std::get<1>(args); + // To get the i-th (0-based) argument, use std::get(args). + return std::get<1>(args); } }; ``` From 9d8222ad667284cfad8be9cb27b25dab75f34ccb Mon Sep 17 00:00:00 2001 From: trzeci Date: Tue, 17 Dec 2019 23:43:31 +0100 Subject: [PATCH 122/541] Disable move constructor and assignment operator for test classes. Disable move operations for TEST() and TEST_F() macros. Previous implementation disabled only copy ctor and assing operator, but this was violating rule of 5[1], which was captured by static code analysis tools like clang-tidy `cppcoreguidelines-special-member-functions`. [1]: https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#c21-if-you-define-or-delete-any-default-operation-define-or-delete-them-all --- .../include/gtest/internal/gtest-internal.h | 2 ++ googletest/include/gtest/internal/gtest-port.h | 17 +++++++++++++++-- 2 files changed, 17 insertions(+), 2 deletions(-) diff --git a/googletest/include/gtest/internal/gtest-internal.h b/googletest/include/gtest/internal/gtest-internal.h index eac831a801..062611ea2c 100644 --- a/googletest/include/gtest/internal/gtest-internal.h +++ b/googletest/include/gtest/internal/gtest-internal.h @@ -1395,6 +1395,8 @@ constexpr bool InstantiateTypedTestCase_P_IsDeprecated() { return true; } static ::testing::TestInfo* const test_info_ GTEST_ATTRIBUTE_UNUSED_; \ GTEST_DISALLOW_COPY_AND_ASSIGN_(GTEST_TEST_CLASS_NAME_(test_suite_name, \ test_name)); \ + GTEST_DISALLOW_MOVE_AND_ASSIGN_(GTEST_TEST_CLASS_NAME_(test_suite_name, \ + test_name)); \ }; \ \ ::testing::TestInfo* const GTEST_TEST_CLASS_NAME_(test_suite_name, \ diff --git a/googletest/include/gtest/internal/gtest-port.h b/googletest/include/gtest/internal/gtest-port.h index fcaac0bbbe..95a9479945 100644 --- a/googletest/include/gtest/internal/gtest-port.h +++ b/googletest/include/gtest/internal/gtest-port.h @@ -190,8 +190,10 @@ // GTEST_AMBIGUOUS_ELSE_BLOCKER_ - for disabling a gcc warning. // GTEST_ATTRIBUTE_UNUSED_ - declares that a class' instances or a // variable don't have to be used. -// GTEST_DISALLOW_ASSIGN_ - disables operator=. +// GTEST_DISALLOW_ASSIGN_ - disables copy operator=. // GTEST_DISALLOW_COPY_AND_ASSIGN_ - disables copy ctor and operator=. +// GTEST_DISALLOW_MOVE_ASSIGN_ - disables move operator=. +// GTEST_DISALLOW_MOVE_AND_ASSIGN_ - disables move ctor and operator=. // GTEST_MUST_USE_RESULT_ - declares that a function's result must be used. // GTEST_INTENTIONAL_CONST_COND_PUSH_ - start code section where MSVC C4127 is // suppressed (constant conditional). @@ -666,7 +668,7 @@ typedef struct _RTL_CRITICAL_SECTION GTEST_CRITICAL_SECTION; #endif -// A macro to disallow operator= +// A macro to disallow copy operator= // This should be used in the private: declarations for a class. #define GTEST_DISALLOW_ASSIGN_(type) \ void operator=(type const &) = delete @@ -677,6 +679,17 @@ typedef struct _RTL_CRITICAL_SECTION GTEST_CRITICAL_SECTION; type(type const &) = delete; \ GTEST_DISALLOW_ASSIGN_(type) +// A macro to disallow move operator= +// This should be used in the private: declarations for a class. +#define GTEST_DISALLOW_MOVE_ASSIGN_(type) \ + void operator=(type &&) = delete + +// A macro to disallow move constructor and operator= +// This should be used in the private: declarations for a class. +#define GTEST_DISALLOW_MOVE_AND_ASSIGN_(type) \ + type(type &&) = delete; \ + GTEST_DISALLOW_MOVE_ASSIGN_(type) + // Tell the compiler to warn about unused return values for functions declared // with this macro. The macro should be used on function declarations // following the argument list: From 77b3a250ea9e7c6d01b6eba1dfe70568b7e1fabc Mon Sep 17 00:00:00 2001 From: "Piotr Paczkowski (trzeci.eu)" Date: Fri, 20 Dec 2019 09:39:06 +0100 Subject: [PATCH 123/541] Review notes: Return T& from assignment operators --- googletest/include/gtest/internal/gtest-port.h | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/googletest/include/gtest/internal/gtest-port.h b/googletest/include/gtest/internal/gtest-port.h index 95a9479945..1a7f80cd7d 100644 --- a/googletest/include/gtest/internal/gtest-port.h +++ b/googletest/include/gtest/internal/gtest-port.h @@ -671,7 +671,7 @@ typedef struct _RTL_CRITICAL_SECTION GTEST_CRITICAL_SECTION; // A macro to disallow copy operator= // This should be used in the private: declarations for a class. #define GTEST_DISALLOW_ASSIGN_(type) \ - void operator=(type const &) = delete + type& operator=(type const &) = delete // A macro to disallow copy constructor and operator= // This should be used in the private: declarations for a class. @@ -682,7 +682,7 @@ typedef struct _RTL_CRITICAL_SECTION GTEST_CRITICAL_SECTION; // A macro to disallow move operator= // This should be used in the private: declarations for a class. #define GTEST_DISALLOW_MOVE_ASSIGN_(type) \ - void operator=(type &&) = delete + type& operator=(type &&) = delete // A macro to disallow move constructor and operator= // This should be used in the private: declarations for a class. From 05701fee2896329009cb040496bd0d6714c9a78b Mon Sep 17 00:00:00 2001 From: "Piotr Paczkowski (trzeci.eu)" Date: Fri, 20 Dec 2019 09:41:58 +0100 Subject: [PATCH 124/541] Deleted functions as part of public interface --- googletest/include/gtest/internal/gtest-internal.h | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/googletest/include/gtest/internal/gtest-internal.h b/googletest/include/gtest/internal/gtest-internal.h index 062611ea2c..ce081aa240 100644 --- a/googletest/include/gtest/internal/gtest-internal.h +++ b/googletest/include/gtest/internal/gtest-internal.h @@ -1389,14 +1389,14 @@ constexpr bool InstantiateTypedTestCase_P_IsDeprecated() { return true; } : public parent_class { \ public: \ GTEST_TEST_CLASS_NAME_(test_suite_name, test_name)() {} \ - \ - private: \ - void TestBody() override; \ - static ::testing::TestInfo* const test_info_ GTEST_ATTRIBUTE_UNUSED_; \ GTEST_DISALLOW_COPY_AND_ASSIGN_(GTEST_TEST_CLASS_NAME_(test_suite_name, \ test_name)); \ GTEST_DISALLOW_MOVE_AND_ASSIGN_(GTEST_TEST_CLASS_NAME_(test_suite_name, \ test_name)); \ + \ + private: \ + void TestBody() override; \ + static ::testing::TestInfo* const test_info_ GTEST_ATTRIBUTE_UNUSED_; \ }; \ \ ::testing::TestInfo* const GTEST_TEST_CLASS_NAME_(test_suite_name, \ From cc05a3ca014bdc25eaf987672004b36fa1ceeb36 Mon Sep 17 00:00:00 2001 From: "Piotr Paczkowski (trzeci.eu)" Date: Fri, 20 Dec 2019 09:45:28 +0100 Subject: [PATCH 125/541] Define default destructor for test classes --- googletest/include/gtest/internal/gtest-internal.h | 1 + 1 file changed, 1 insertion(+) diff --git a/googletest/include/gtest/internal/gtest-internal.h b/googletest/include/gtest/internal/gtest-internal.h index ce081aa240..ff2ff4ba58 100644 --- a/googletest/include/gtest/internal/gtest-internal.h +++ b/googletest/include/gtest/internal/gtest-internal.h @@ -1389,6 +1389,7 @@ constexpr bool InstantiateTypedTestCase_P_IsDeprecated() { return true; } : public parent_class { \ public: \ GTEST_TEST_CLASS_NAME_(test_suite_name, test_name)() {} \ + ~GTEST_TEST_CLASS_NAME_(test_suite_name, test_name)() = default; \ GTEST_DISALLOW_COPY_AND_ASSIGN_(GTEST_TEST_CLASS_NAME_(test_suite_name, \ test_name)); \ GTEST_DISALLOW_MOVE_AND_ASSIGN_(GTEST_TEST_CLASS_NAME_(test_suite_name, \ From bf31ed376ab1ae181dfa2bb0383f7710229b0d14 Mon Sep 17 00:00:00 2001 From: "Piotr Paczkowski (trzeci.eu)" Date: Fri, 20 Dec 2019 09:51:35 +0100 Subject: [PATCH 126/541] Make move operation noexcept. --- googletest/include/gtest/internal/gtest-port.h | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/googletest/include/gtest/internal/gtest-port.h b/googletest/include/gtest/internal/gtest-port.h index 1a7f80cd7d..0543da54d8 100644 --- a/googletest/include/gtest/internal/gtest-port.h +++ b/googletest/include/gtest/internal/gtest-port.h @@ -682,12 +682,12 @@ typedef struct _RTL_CRITICAL_SECTION GTEST_CRITICAL_SECTION; // A macro to disallow move operator= // This should be used in the private: declarations for a class. #define GTEST_DISALLOW_MOVE_ASSIGN_(type) \ - type& operator=(type &&) = delete + type& operator=(type &&) noexcept = delete // A macro to disallow move constructor and operator= // This should be used in the private: declarations for a class. #define GTEST_DISALLOW_MOVE_AND_ASSIGN_(type) \ - type(type &&) = delete; \ + type(type &&) noexcept = delete; \ GTEST_DISALLOW_MOVE_ASSIGN_(type) // Tell the compiler to warn about unused return values for functions declared From 6f1a8ffde934f4dda39cc12cd7260874c4f3e390 Mon Sep 17 00:00:00 2001 From: Abseil Team Date: Wed, 18 Dec 2019 04:40:32 -0500 Subject: [PATCH 127/541] Googletest export Use C++11 variadic templates for InvokeArgumentAdl in gmock-generated-actions.h. Make InvokeArgumentAdl use variadic templates to generate its overloads instead of using pump.py syntax. PiperOrigin-RevId: 286148805 --- googlemock/include/gmock/gmock-actions.h | 17 +++++ .../include/gmock/gmock-generated-actions.h | 72 ------------------- .../gmock/gmock-generated-actions.h.pump | 26 ------- 3 files changed, 17 insertions(+), 98 deletions(-) diff --git a/googlemock/include/gmock/gmock-actions.h b/googlemock/include/gmock/gmock-actions.h index 4b8dcebb90..f5ac13997e 100644 --- a/googlemock/include/gmock/gmock-actions.h +++ b/googlemock/include/gmock/gmock-actions.h @@ -1222,6 +1222,23 @@ class ActionHelper { } }; +namespace invoke_argument { + +// Appears in InvokeArgumentAdl's argument list to help avoid +// accidental calls to user functions of the same name. +struct AdlTag {}; + +// InvokeArgumentAdl - a helper for InvokeArgument. +// The basic overloads are provided here for generic functors. +// Overloads for other custom-callables are provided in the +// internal/custom/gmock-generated-actions.h header. + +template +R InvokeArgumentAdl(AdlTag, F f, Args&&... args) { + return f(std::forward(args)...); +} + +} // namespace invoke_argument } // namespace internal } // namespace testing diff --git a/googlemock/include/gmock/gmock-generated-actions.h b/googlemock/include/gmock/gmock-generated-actions.h index 20b78cd43d..c239f6cebd 100644 --- a/googlemock/include/gmock/gmock-generated-actions.h +++ b/googlemock/include/gmock/gmock-generated-actions.h @@ -1501,78 +1501,6 @@ namespace testing { // InvokeArgument action from temporary values and have it performed // later. -namespace internal { -namespace invoke_argument { - -// Appears in InvokeArgumentAdl's argument list to help avoid -// accidental calls to user functions of the same name. -struct AdlTag {}; - -// InvokeArgumentAdl - a helper for InvokeArgument. -// The basic overloads are provided here for generic functors. -// Overloads for other custom-callables are provided in the -// internal/custom/gmock-generated-actions.h header. - -template -R InvokeArgumentAdl(AdlTag, F f) { - return f(); -} -template -R InvokeArgumentAdl(AdlTag, F f, A1 a1) { - return f(a1); -} -template -R InvokeArgumentAdl(AdlTag, F f, A1 a1, A2 a2) { - return f(a1, a2); -} -template -R InvokeArgumentAdl(AdlTag, F f, A1 a1, A2 a2, A3 a3) { - return f(a1, a2, a3); -} -template -R InvokeArgumentAdl(AdlTag, F f, A1 a1, A2 a2, A3 a3, A4 a4) { - return f(a1, a2, a3, a4); -} -template -R InvokeArgumentAdl(AdlTag, F f, A1 a1, A2 a2, A3 a3, A4 a4, A5 a5) { - return f(a1, a2, a3, a4, a5); -} -template -R InvokeArgumentAdl(AdlTag, F f, A1 a1, A2 a2, A3 a3, A4 a4, A5 a5, A6 a6) { - return f(a1, a2, a3, a4, a5, a6); -} -template -R InvokeArgumentAdl(AdlTag, F f, A1 a1, A2 a2, A3 a3, A4 a4, A5 a5, A6 a6, - A7 a7) { - return f(a1, a2, a3, a4, a5, a6, a7); -} -template -R InvokeArgumentAdl(AdlTag, F f, A1 a1, A2 a2, A3 a3, A4 a4, A5 a5, A6 a6, - A7 a7, A8 a8) { - return f(a1, a2, a3, a4, a5, a6, a7, a8); -} -template -R InvokeArgumentAdl(AdlTag, F f, A1 a1, A2 a2, A3 a3, A4 a4, A5 a5, A6 a6, - A7 a7, A8 a8, A9 a9) { - return f(a1, a2, a3, a4, a5, a6, a7, a8, a9); -} -template -R InvokeArgumentAdl(AdlTag, F f, A1 a1, A2 a2, A3 a3, A4 a4, A5 a5, A6 a6, - A7 a7, A8 a8, A9 a9, A10 a10) { - return f(a1, a2, a3, a4, a5, a6, a7, a8, a9, a10); -} -} // namespace invoke_argument -} // namespace internal - ACTION_TEMPLATE(InvokeArgument, HAS_1_TEMPLATE_PARAMS(int, k), AND_0_VALUE_PARAMS()) { diff --git a/googlemock/include/gmock/gmock-generated-actions.h.pump b/googlemock/include/gmock/gmock-generated-actions.h.pump index 1121fbdec8..ab76d2cd26 100644 --- a/googlemock/include/gmock/gmock-generated-actions.h.pump +++ b/googlemock/include/gmock/gmock-generated-actions.h.pump @@ -506,32 +506,6 @@ namespace testing { // InvokeArgument action from temporary values and have it performed // later. -namespace internal { -namespace invoke_argument { - -// Appears in InvokeArgumentAdl's argument list to help avoid -// accidental calls to user functions of the same name. -struct AdlTag {}; - -// InvokeArgumentAdl - a helper for InvokeArgument. -// The basic overloads are provided here for generic functors. -// Overloads for other custom-callables are provided in the -// internal/custom/gmock-generated-actions.h header. - -$range i 0..n -$for i -[[ -$range j 1..i - -template -R InvokeArgumentAdl(AdlTag, F f[[$for j [[, A$j a$j]]]]) { - return f([[$for j, [[a$j]]]]); -} -]] - -} // namespace invoke_argument -} // namespace internal - $range i 0..n $for i [[ $range j 0..i-1 From d0a521255eb59ec6ff6e30fdf53c4f05f3fd3270 Mon Sep 17 00:00:00 2001 From: Abseil Team Date: Wed, 18 Dec 2019 17:36:29 -0500 Subject: [PATCH 128/541] Googletest export Use C++11 variadic templates for InvokeArgumentAdl in gmock-generated-actions.h. Make InvokeArgumentAdl use variadic templates to generate its overloads instead of using pump.py syntax. PiperOrigin-RevId: 286267615 --- googlemock/include/gmock/gmock-actions.h | 17 ----- .../include/gmock/gmock-generated-actions.h | 72 +++++++++++++++++++ .../gmock/gmock-generated-actions.h.pump | 26 +++++++ 3 files changed, 98 insertions(+), 17 deletions(-) diff --git a/googlemock/include/gmock/gmock-actions.h b/googlemock/include/gmock/gmock-actions.h index f5ac13997e..4b8dcebb90 100644 --- a/googlemock/include/gmock/gmock-actions.h +++ b/googlemock/include/gmock/gmock-actions.h @@ -1222,23 +1222,6 @@ class ActionHelper { } }; -namespace invoke_argument { - -// Appears in InvokeArgumentAdl's argument list to help avoid -// accidental calls to user functions of the same name. -struct AdlTag {}; - -// InvokeArgumentAdl - a helper for InvokeArgument. -// The basic overloads are provided here for generic functors. -// Overloads for other custom-callables are provided in the -// internal/custom/gmock-generated-actions.h header. - -template -R InvokeArgumentAdl(AdlTag, F f, Args&&... args) { - return f(std::forward(args)...); -} - -} // namespace invoke_argument } // namespace internal } // namespace testing diff --git a/googlemock/include/gmock/gmock-generated-actions.h b/googlemock/include/gmock/gmock-generated-actions.h index c239f6cebd..20b78cd43d 100644 --- a/googlemock/include/gmock/gmock-generated-actions.h +++ b/googlemock/include/gmock/gmock-generated-actions.h @@ -1501,6 +1501,78 @@ namespace testing { // InvokeArgument action from temporary values and have it performed // later. +namespace internal { +namespace invoke_argument { + +// Appears in InvokeArgumentAdl's argument list to help avoid +// accidental calls to user functions of the same name. +struct AdlTag {}; + +// InvokeArgumentAdl - a helper for InvokeArgument. +// The basic overloads are provided here for generic functors. +// Overloads for other custom-callables are provided in the +// internal/custom/gmock-generated-actions.h header. + +template +R InvokeArgumentAdl(AdlTag, F f) { + return f(); +} +template +R InvokeArgumentAdl(AdlTag, F f, A1 a1) { + return f(a1); +} +template +R InvokeArgumentAdl(AdlTag, F f, A1 a1, A2 a2) { + return f(a1, a2); +} +template +R InvokeArgumentAdl(AdlTag, F f, A1 a1, A2 a2, A3 a3) { + return f(a1, a2, a3); +} +template +R InvokeArgumentAdl(AdlTag, F f, A1 a1, A2 a2, A3 a3, A4 a4) { + return f(a1, a2, a3, a4); +} +template +R InvokeArgumentAdl(AdlTag, F f, A1 a1, A2 a2, A3 a3, A4 a4, A5 a5) { + return f(a1, a2, a3, a4, a5); +} +template +R InvokeArgumentAdl(AdlTag, F f, A1 a1, A2 a2, A3 a3, A4 a4, A5 a5, A6 a6) { + return f(a1, a2, a3, a4, a5, a6); +} +template +R InvokeArgumentAdl(AdlTag, F f, A1 a1, A2 a2, A3 a3, A4 a4, A5 a5, A6 a6, + A7 a7) { + return f(a1, a2, a3, a4, a5, a6, a7); +} +template +R InvokeArgumentAdl(AdlTag, F f, A1 a1, A2 a2, A3 a3, A4 a4, A5 a5, A6 a6, + A7 a7, A8 a8) { + return f(a1, a2, a3, a4, a5, a6, a7, a8); +} +template +R InvokeArgumentAdl(AdlTag, F f, A1 a1, A2 a2, A3 a3, A4 a4, A5 a5, A6 a6, + A7 a7, A8 a8, A9 a9) { + return f(a1, a2, a3, a4, a5, a6, a7, a8, a9); +} +template +R InvokeArgumentAdl(AdlTag, F f, A1 a1, A2 a2, A3 a3, A4 a4, A5 a5, A6 a6, + A7 a7, A8 a8, A9 a9, A10 a10) { + return f(a1, a2, a3, a4, a5, a6, a7, a8, a9, a10); +} +} // namespace invoke_argument +} // namespace internal + ACTION_TEMPLATE(InvokeArgument, HAS_1_TEMPLATE_PARAMS(int, k), AND_0_VALUE_PARAMS()) { diff --git a/googlemock/include/gmock/gmock-generated-actions.h.pump b/googlemock/include/gmock/gmock-generated-actions.h.pump index ab76d2cd26..1121fbdec8 100644 --- a/googlemock/include/gmock/gmock-generated-actions.h.pump +++ b/googlemock/include/gmock/gmock-generated-actions.h.pump @@ -506,6 +506,32 @@ namespace testing { // InvokeArgument action from temporary values and have it performed // later. +namespace internal { +namespace invoke_argument { + +// Appears in InvokeArgumentAdl's argument list to help avoid +// accidental calls to user functions of the same name. +struct AdlTag {}; + +// InvokeArgumentAdl - a helper for InvokeArgument. +// The basic overloads are provided here for generic functors. +// Overloads for other custom-callables are provided in the +// internal/custom/gmock-generated-actions.h header. + +$range i 0..n +$for i +[[ +$range j 1..i + +template +R InvokeArgumentAdl(AdlTag, F f[[$for j [[, A$j a$j]]]]) { + return f([[$for j, [[a$j]]]]); +} +]] + +} // namespace invoke_argument +} // namespace internal + $range i 0..n $for i [[ $range j 0..i-1 From a13a0626188b4e7d22d63a4c9fcfe9f441c81e4a Mon Sep 17 00:00:00 2001 From: Abseil Team Date: Thu, 19 Dec 2019 12:36:47 -0500 Subject: [PATCH 129/541] Googletest export Add option (default to disabled) to make C++ type parameterized tests (TYPED_TEST_P) fail when they're not instantiated. When an un-instantiated TYPED_TEST_P is found, a new test will be inserted that emits a suitable message. For now, that is just a notice, but the hope it to flip the bit to make it fail by default. PiperOrigin-RevId: 286408038 --- googletest/include/gtest/gtest-typed-test.h | 2 +- .../include/gtest/internal/gtest-internal.h | 11 +++- .../include/gtest/internal/gtest-param-util.h | 28 +++++++++ googletest/src/gtest-internal-inl.h | 9 +++ googletest/src/gtest-typed-test.cc | 5 +- googletest/src/gtest.cc | 59 +++++++++++++++++++ .../googletest-output-test-golden-lin.txt | 13 ++-- googletest/test/googletest-output-test_.cc | 15 +++++ googletest/test/googletest-param-test-test.cc | 5 ++ googletest/test/gtest-typed-test_test.cc | 12 ++-- 10 files changed, 145 insertions(+), 14 deletions(-) diff --git a/googletest/include/gtest/gtest-typed-test.h b/googletest/include/gtest/gtest-typed-test.h index 6f635c87c4..3ffa50b739 100644 --- a/googletest/include/gtest/gtest-typed-test.h +++ b/googletest/include/gtest/gtest-typed-test.h @@ -297,7 +297,7 @@ INSTANTIATE_TYPED_TEST_SUITE_P(My, FooTest, MyTypes); static const char* const GTEST_REGISTERED_TEST_NAMES_( \ SuiteName) GTEST_ATTRIBUTE_UNUSED_ = \ GTEST_TYPED_TEST_SUITE_P_STATE_(SuiteName).VerifyRegisteredTestNames( \ - __FILE__, __LINE__, #__VA_ARGS__) + GTEST_STRINGIFY_(SuiteName), __FILE__, __LINE__, #__VA_ARGS__) // Legacy API is deprecated but still available #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_ diff --git a/googletest/include/gtest/internal/gtest-internal.h b/googletest/include/gtest/internal/gtest-internal.h index 59d2a833cb..57ebbda18b 100644 --- a/googletest/include/gtest/internal/gtest-internal.h +++ b/googletest/include/gtest/internal/gtest-internal.h @@ -617,8 +617,9 @@ class GTEST_API_ TypedTestSuitePState { // Verifies that registered_tests match the test names in // defined_test_names_; returns registered_tests if successful, or // aborts the program otherwise. - const char* VerifyRegisteredTestNames( - const char* file, int line, const char* registered_tests); + const char* VerifyRegisteredTestNames(const char* test_suite_name, + const char* file, int line, + const char* registered_tests); private: typedef ::std::map RegisteredTestsMap; @@ -750,6 +751,11 @@ class TypeParameterizedTest { } }; +GTEST_API_ void RegisterTypeParameterizedTestSuite(const char* test_suite_name, + CodeLocation code_location); +GTEST_API_ void RegisterTypeParameterizedTestSuiteInstantiation( + const char* case_name); + // TypeParameterizedTestSuite::Register() // registers *all combinations* of 'Tests' and 'Types' with Google // Test. The return value is insignificant - we just need to return @@ -762,6 +768,7 @@ class TypeParameterizedTestSuite { const char* test_names, const std::vector& type_names = GenerateNames()) { + RegisterTypeParameterizedTestSuiteInstantiation(case_name); std::string test_name = StripTrailingSpaces( GetPrefixUntilComma(test_names)); if (!state->TestExists(test_name)) { diff --git a/googletest/include/gtest/internal/gtest-param-util.h b/googletest/include/gtest/internal/gtest-param-util.h index 3f2495bfce..ffa7d72c3b 100644 --- a/googletest/include/gtest/internal/gtest-param-util.h +++ b/googletest/include/gtest/internal/gtest-param-util.h @@ -731,6 +731,34 @@ class ParameterizedTestSuiteRegistry { GTEST_DISALLOW_COPY_AND_ASSIGN_(ParameterizedTestSuiteRegistry); }; +// Keep track of what type-parameterized test suite are defined and +// where as well as which are intatiated. This allows susequently +// identifying suits that are defined but never used. +class TypeParameterizedTestSuiteRegistry { + public: + // Add a suite definition + void RegisterTestSuite(const char* test_suite_name, + CodeLocation code_location); + + // Add an instantiation of a suit. + void RegisterInstantiation(const char* test_suite_name); + + // For each suit repored as defined but not reported as instantiation, + // emit a test that reports that fact (configurably, as an error). + void CheckForInstantiations(); + + private: + struct TypeParameterizedTestSuiteInfo { + explicit TypeParameterizedTestSuiteInfo(CodeLocation c) + : code_location(c), instantiated(false) {} + + CodeLocation code_location; + bool instantiated; + }; + + std::map suites_; +}; + } // namespace internal // Forward declarations of ValuesIn(), which is implemented in diff --git a/googletest/src/gtest-internal-inl.h b/googletest/src/gtest-internal-inl.h index c3575ee3a4..d0ebe0c519 100644 --- a/googletest/src/gtest-internal-inl.h +++ b/googletest/src/gtest-internal-inl.h @@ -698,6 +698,13 @@ class GTEST_API_ UnitTestImpl { return parameterized_test_registry_; } + // Returns TypeParameterizedTestSuiteRegistry object used to keep track of + // type-parameterized tests and instantiations of them. + internal::TypeParameterizedTestSuiteRegistry& + type_parameterized_test_registry() { + return type_parameterized_test_registry_; + } + // Sets the TestSuite object for the test that's currently running. void set_current_test_suite(TestSuite* a_current_test_suite) { current_test_suite_ = a_current_test_suite; @@ -874,6 +881,8 @@ class GTEST_API_ UnitTestImpl { // ParameterizedTestRegistry object used to register value-parameterized // tests. internal::ParameterizedTestSuiteRegistry parameterized_test_registry_; + internal::TypeParameterizedTestSuiteRegistry + type_parameterized_test_registry_; // Indicates whether RegisterParameterizedTests() has been called already. bool parameterized_tests_registered_; diff --git a/googletest/src/gtest-typed-test.cc b/googletest/src/gtest-typed-test.cc index 8677caf732..1b1cfb0dc1 100644 --- a/googletest/src/gtest-typed-test.cc +++ b/googletest/src/gtest-typed-test.cc @@ -58,7 +58,10 @@ static std::vector SplitIntoTestNames(const char* src) { // registered_tests_; returns registered_tests if successful, or // aborts the program otherwise. const char* TypedTestSuitePState::VerifyRegisteredTestNames( - const char* file, int line, const char* registered_tests) { + const char* test_suite_name, const char* file, int line, + const char* registered_tests) { + RegisterTypeParameterizedTestSuite(test_suite_name, CodeLocation(file, line)); + typedef RegisteredTestsMap::const_iterator RegisteredTestIter; registered_ = true; diff --git a/googletest/src/gtest.cc b/googletest/src/gtest.cc index f6466b92ab..07015cba7e 100644 --- a/googletest/src/gtest.cc +++ b/googletest/src/gtest.cc @@ -415,6 +415,7 @@ namespace { // // This configuration bit will likely be removed at some point. constexpr bool kErrorOnUninstantiatedParameterizedTest = false; +constexpr bool kErrorOnUninstantiatedTypeParameterizedTest = false; // A test that fails at a given file/line location with a given message. class FailureTest : public Test { @@ -467,6 +468,63 @@ void InsertSyntheticTestCase(const std::string &name, CodeLocation location) { }); } +void RegisterTypeParameterizedTestSuite(const char* test_suite_name, + CodeLocation code_location) { + GetUnitTestImpl()->type_parameterized_test_registry().RegisterTestSuite( + test_suite_name, code_location); +} + +void RegisterTypeParameterizedTestSuiteInstantiation(const char* case_name) { + GetUnitTestImpl() + ->type_parameterized_test_registry() + .RegisterInstantiation(case_name); +} + +void TypeParameterizedTestSuiteRegistry::RegisterTestSuite( + const char* test_suite_name, CodeLocation code_location) { + suites_.emplace(std::string(test_suite_name), + TypeParameterizedTestSuiteInfo(code_location)); +} + +void TypeParameterizedTestSuiteRegistry::RegisterInstantiation( + const char* test_suite_name) { + auto it = suites_.find(std::string(test_suite_name)); + if (it != suites_.end()) { + it->second.instantiated = true; + } else { + GTEST_LOG_(ERROR) << "Unknown type parameterized test suit '" + << test_suite_name << "'"; + } +} + +void TypeParameterizedTestSuiteRegistry::CheckForInstantiations() { + for (const auto& testcase : suites_) { + if (testcase.second.instantiated) continue; + + std::string message = + "Type paramaterized test suite " + testcase.first + + " is defined via REGISTER_TYPED_TEST_SUITE_P, but never instantiated " + "via INSTANTIATE_TYPED_TEST_SUITE_P. None of the test cases will run." + "\n\n" + "Ideally, TYPED_TEST_P definitions should only ever be included as " + "part of binaries that intend to use them. (As opposed to, for " + "example, being placed in a library that may be linked in to get other " + "utilities.)"; + + std::string full_name = + "UninstantiatedTypeParamaterizedTestSuite<" + testcase.first + ">"; + RegisterTest( // + "GoogleTestVerification", full_name.c_str(), + nullptr, // No type parameter. + nullptr, // No value parameter. + testcase.second.code_location.file.c_str(), + testcase.second.code_location.line, [message, testcase] { + return new FailureTest(testcase.second.code_location, message, + kErrorOnUninstantiatedTypeParameterizedTest); + }); + } +} + // A copy of all command line arguments. Set by InitGoogleTest(). static ::std::vector g_argvs; @@ -2710,6 +2768,7 @@ namespace internal { void UnitTestImpl::RegisterParameterizedTests() { if (!parameterized_tests_registered_) { parameterized_test_registry_.RegisterTests(); + type_parameterized_test_registry_.CheckForInstantiations(); parameterized_tests_registered_ = true; } } diff --git a/googletest/test/googletest-output-test-golden-lin.txt b/googletest/test/googletest-output-test-golden-lin.txt index a08140e159..c1db004cd4 100644 --- a/googletest/test/googletest-output-test-golden-lin.txt +++ b/googletest/test/googletest-output-test-golden-lin.txt @@ -12,7 +12,7 @@ Expected equality of these values: 3 Stack trace: (omitted) -[==========] Running 86 tests from 41 test suites. +[==========] Running 87 tests from 41 test suites. [----------] Global test environment set-up. FooEnvironment::SetUp() called. BarEnvironment::SetUp() called. @@ -982,12 +982,17 @@ Expected failure Stack trace: (omitted) [ FAILED ] PrintingStrings/ParamTest.Failure/a, where GetParam() = "a" -[----------] 1 test from GoogleTestVerification +[----------] 2 tests from GoogleTestVerification [ RUN ] GoogleTestVerification.UninstantiatedParamaterizedTestSuite Paramaterized test suite DetectNotInstantiatedTest is defined via TEST_P, but never instantiated. None of the test cases will run. Either no INSTANTIATE_TEST_SUITE_P is provided or the only ones provided expand to nothing. Ideally, TEST_P definitions should only ever be included as part of binaries that intend to use them. (As opposed to, for example, being placed in a library that may be linked in to get other utilities.) [ OK ] GoogleTestVerification.UninstantiatedParamaterizedTestSuite +[ RUN ] GoogleTestVerification.UninstantiatedTypeParamaterizedTestSuite +Type paramaterized test suite DetectNotInstantiatedTypesTest is defined via REGISTER_TYPED_TEST_SUITE_P, but never instantiated via INSTANTIATE_TYPED_TEST_SUITE_P. None of the test cases will run. + +Ideally, TYPED_TEST_P definitions should only ever be included as part of binaries that intend to use them. (As opposed to, for example, being placed in a library that may be linked in to get other utilities.) +[ OK ] GoogleTestVerification.UninstantiatedTypeParamaterizedTestSuite [----------] Global test environment tear-down BarEnvironment::TearDown() called. googletest-output-test_.cc:#: Failure @@ -1001,8 +1006,8 @@ Failed Expected fatal failure. Stack trace: (omitted) -[==========] 86 tests from 41 test suites ran. -[ PASSED ] 32 tests. +[==========] 87 tests from 41 test suites ran. +[ PASSED ] 33 tests. [ FAILED ] 54 tests, listed below: [ FAILED ] NonfatalFailureTest.EscapesStringOperands [ FAILED ] NonfatalFailureTest.DiffForLongStrings diff --git a/googletest/test/googletest-output-test_.cc b/googletest/test/googletest-output-test_.cc index 1c7943c3d7..b1d66f9fb6 100644 --- a/googletest/test/googletest-output-test_.cc +++ b/googletest/test/googletest-output-test_.cc @@ -876,6 +876,21 @@ class TypedTestPNames { INSTANTIATE_TYPED_TEST_SUITE_P(UnsignedCustomName, TypedTestP, UnsignedTypes, TypedTestPNames); +template +class DetectNotInstantiatedTypesTest : public testing::Test {}; +TYPED_TEST_SUITE_P(DetectNotInstantiatedTypesTest); +TYPED_TEST_P(DetectNotInstantiatedTypesTest, Used) { + TypeParam instantiate; + (void)instantiate; +} +REGISTER_TYPED_TEST_SUITE_P(DetectNotInstantiatedTypesTest, Used); + +// kErrorOnUninstantiatedTypeParameterizedTest=true would make the above fail. +// Adding the following would make that test failure go away. +// +// typedef ::testing::Types MyTypes; +// INSTANTIATE_TYPED_TEST_SUITE_P(All, DetectNotInstantiatedTypesTest, MyTypes); + #endif // GTEST_HAS_TYPED_TEST_P #if GTEST_HAS_DEATH_TEST diff --git a/googletest/test/googletest-param-test-test.cc b/googletest/test/googletest-param-test-test.cc index 85c76c347a..f92eb316c9 100644 --- a/googletest/test/googletest-param-test-test.cc +++ b/googletest/test/googletest-param-test-test.cc @@ -1072,6 +1072,11 @@ namespace works_here { // Never used not instantiated, this should work. class NotUsedTest : public testing::TestWithParam {}; +/////// +// Never used not instantiated, this should work. +template +class NotUsedTypeTest : public testing::Test {}; +TYPED_TEST_SUITE_P(NotUsedTypeTest); } // namespace works_here int main(int argc, char **argv) { diff --git a/googletest/test/gtest-typed-test_test.cc b/googletest/test/gtest-typed-test_test.cc index 5411832ab2..0c1f660fb5 100644 --- a/googletest/test/gtest-typed-test_test.cc +++ b/googletest/test/gtest-typed-test_test.cc @@ -228,7 +228,7 @@ class TypedTestSuitePStateTest : public Test { TEST_F(TypedTestSuitePStateTest, SucceedsForMatchingList) { const char* tests = "A, B, C"; EXPECT_EQ(tests, - state_.VerifyRegisteredTestNames("foo.cc", 1, tests)); + state_.VerifyRegisteredTestNames("Suite", "foo.cc", 1, tests)); } // Makes sure that the order of the tests and spaces around the names @@ -236,33 +236,33 @@ TEST_F(TypedTestSuitePStateTest, SucceedsForMatchingList) { TEST_F(TypedTestSuitePStateTest, IgnoresOrderAndSpaces) { const char* tests = "A,C, B"; EXPECT_EQ(tests, - state_.VerifyRegisteredTestNames("foo.cc", 1, tests)); + state_.VerifyRegisteredTestNames("Suite", "foo.cc", 1, tests)); } using TypedTestSuitePStateDeathTest = TypedTestSuitePStateTest; TEST_F(TypedTestSuitePStateDeathTest, DetectsDuplicates) { EXPECT_DEATH_IF_SUPPORTED( - state_.VerifyRegisteredTestNames("foo.cc", 1, "A, B, A, C"), + state_.VerifyRegisteredTestNames("Suite", "foo.cc", 1, "A, B, A, C"), "foo\\.cc.1.?: Test A is listed more than once\\."); } TEST_F(TypedTestSuitePStateDeathTest, DetectsExtraTest) { EXPECT_DEATH_IF_SUPPORTED( - state_.VerifyRegisteredTestNames("foo.cc", 1, "A, B, C, D"), + state_.VerifyRegisteredTestNames("Suite", "foo.cc", 1, "A, B, C, D"), "foo\\.cc.1.?: No test named D can be found in this test suite\\."); } TEST_F(TypedTestSuitePStateDeathTest, DetectsMissedTest) { EXPECT_DEATH_IF_SUPPORTED( - state_.VerifyRegisteredTestNames("foo.cc", 1, "A, C"), + state_.VerifyRegisteredTestNames("Suite", "foo.cc", 1, "A, C"), "foo\\.cc.1.?: You forgot to list test B\\."); } // Tests that defining a test for a parameterized test case generates // a run-time error if the test case has been registered. TEST_F(TypedTestSuitePStateDeathTest, DetectsTestAfterRegistration) { - state_.VerifyRegisteredTestNames("foo.cc", 1, "A, B, C"); + state_.VerifyRegisteredTestNames("Suite", "foo.cc", 1, "A, B, C"); EXPECT_DEATH_IF_SUPPORTED( state_.AddTestName("foo.cc", 2, "FooTest", "D"), "foo\\.cc.2.?: Test D must be defined before REGISTER_TYPED_TEST_SUITE_P" From 153909f096334161ddf62e81da1054c8858c4748 Mon Sep 17 00:00:00 2001 From: Abseil Team Date: Thu, 26 Dec 2019 15:08:14 -0500 Subject: [PATCH 130/541] Googletest export Fix typo in example. PiperOrigin-RevId: 287212448 --- googlemock/docs/cook_book.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/googlemock/docs/cook_book.md b/googlemock/docs/cook_book.md index 69c5e4ac4a..a493521481 100644 --- a/googlemock/docs/cook_book.md +++ b/googlemock/docs/cook_book.md @@ -2202,7 +2202,7 @@ class Helper { .WillOnce(&CalculateSum) .WillRepeatedly(Invoke(NewPermanentCallback(Sum3, 1))); EXPECT_CALL(foo, ComplexJob(_)) - .WillOnce(Invoke(&helper, &Helper::ComplexJob)); + .WillOnce(Invoke(&helper, &Helper::ComplexJob)) .WillRepeatedly([](int x) { return x > 0; }); foo.Sum(5, 6); // Invokes CalculateSum(5, 6). From 0d98d87e106919ad9216f1db430c452d95fb6f09 Mon Sep 17 00:00:00 2001 From: Abseil Team Date: Mon, 30 Dec 2019 11:08:39 -0500 Subject: [PATCH 131/541] Googletest export Add missing period. PiperOrigin-RevId: 287553550 --- CONTRIBUTING.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 4c18499267..bd1843eb48 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -80,7 +80,7 @@ fairly rigid coding style, as defined by the will be expected to conform to the style outlined [here](https://google.github.io/styleguide/cppguide.html). Use [.clang-format](https://github.com/google/googletest/blob/master/.clang-format) -to check your formatting +to check your formatting. ## Requirements for Contributors From 306f3754a71d6d1ac644681d3544d06744914228 Mon Sep 17 00:00:00 2001 From: Abseil Team Date: Mon, 30 Dec 2019 16:28:03 -0500 Subject: [PATCH 132/541] Googletest export Explicitly default copy constructor in BoundSecondMatcher Since C++11, implicit defaulting of copy constructors is deprecated for types with user-defined copy assignment operators, so we should explicitly default the copy constructor of BoundSecondMatcher. PiperOrigin-RevId: 287587847 --- googlemock/include/gmock/gmock-matchers.h | 2 ++ 1 file changed, 2 insertions(+) diff --git a/googlemock/include/gmock/gmock-matchers.h b/googlemock/include/gmock/gmock-matchers.h index 317d2c9f01..67bd7e2713 100644 --- a/googlemock/include/gmock/gmock-matchers.h +++ b/googlemock/include/gmock/gmock-matchers.h @@ -3169,6 +3169,8 @@ class BoundSecondMatcher { BoundSecondMatcher(const Tuple2Matcher& tm, const Second& second) : tuple2_matcher_(tm), second_value_(second) {} + BoundSecondMatcher(const BoundSecondMatcher& other) = default; + template operator Matcher() const { return MakeMatcher(new Impl(tuple2_matcher_, second_value_)); From 4b9c1691c4b7f01fbd9d37d86c88cdad298d48e9 Mon Sep 17 00:00:00 2001 From: Abseil Team Date: Tue, 7 Jan 2020 03:51:16 -0500 Subject: [PATCH 133/541] Googletest export Use C++11 variadic templates for Invoke in gmock-generated-actions.h. Replace InvokeArgumentAdl with Invoke that uses C++11 variadic templates. PiperOrigin-RevId: 288449236 --- googlemock/include/gmock/gmock-actions.h | 16 +++ .../include/gmock/gmock-generated-actions.h | 129 ++++-------------- .../gmock/gmock-generated-actions.h.pump | 31 +---- 3 files changed, 42 insertions(+), 134 deletions(-) diff --git a/googlemock/include/gmock/gmock-actions.h b/googlemock/include/gmock/gmock-actions.h index 4b8dcebb90..11223cf280 100644 --- a/googlemock/include/gmock/gmock-actions.h +++ b/googlemock/include/gmock/gmock-actions.h @@ -1222,6 +1222,22 @@ class ActionHelper { } }; +namespace invoke_argument { + +// Appears in InvokeArgumentAdl's argument list to help avoid +// accidental calls to user functions of the same name. +struct AdlTag {}; + +// InvokeArgumentAdl - a helper for InvokeArgument. +// The basic overloads are provided here for generic functors. +// Overloads for other custom-callables are provided in the +// internal/custom/gmock-generated-actions.h header. +template +auto InvokeArgumentAdl(AdlTag, F f, Args... args) -> decltype(f(args...)) { + return f(args...); +} + +} // namespace invoke_argument } // namespace internal } // namespace testing diff --git a/googlemock/include/gmock/gmock-generated-actions.h b/googlemock/include/gmock/gmock-generated-actions.h index 20b78cd43d..8257fb19ba 100644 --- a/googlemock/include/gmock/gmock-generated-actions.h +++ b/googlemock/include/gmock/gmock-generated-actions.h @@ -1501,175 +1501,94 @@ namespace testing { // InvokeArgument action from temporary values and have it performed // later. -namespace internal { -namespace invoke_argument { - -// Appears in InvokeArgumentAdl's argument list to help avoid -// accidental calls to user functions of the same name. -struct AdlTag {}; - -// InvokeArgumentAdl - a helper for InvokeArgument. -// The basic overloads are provided here for generic functors. -// Overloads for other custom-callables are provided in the -// internal/custom/gmock-generated-actions.h header. - -template -R InvokeArgumentAdl(AdlTag, F f) { - return f(); -} -template -R InvokeArgumentAdl(AdlTag, F f, A1 a1) { - return f(a1); -} -template -R InvokeArgumentAdl(AdlTag, F f, A1 a1, A2 a2) { - return f(a1, a2); -} -template -R InvokeArgumentAdl(AdlTag, F f, A1 a1, A2 a2, A3 a3) { - return f(a1, a2, a3); -} -template -R InvokeArgumentAdl(AdlTag, F f, A1 a1, A2 a2, A3 a3, A4 a4) { - return f(a1, a2, a3, a4); -} -template -R InvokeArgumentAdl(AdlTag, F f, A1 a1, A2 a2, A3 a3, A4 a4, A5 a5) { - return f(a1, a2, a3, a4, a5); -} -template -R InvokeArgumentAdl(AdlTag, F f, A1 a1, A2 a2, A3 a3, A4 a4, A5 a5, A6 a6) { - return f(a1, a2, a3, a4, a5, a6); -} -template -R InvokeArgumentAdl(AdlTag, F f, A1 a1, A2 a2, A3 a3, A4 a4, A5 a5, A6 a6, - A7 a7) { - return f(a1, a2, a3, a4, a5, a6, a7); -} -template -R InvokeArgumentAdl(AdlTag, F f, A1 a1, A2 a2, A3 a3, A4 a4, A5 a5, A6 a6, - A7 a7, A8 a8) { - return f(a1, a2, a3, a4, a5, a6, a7, a8); -} -template -R InvokeArgumentAdl(AdlTag, F f, A1 a1, A2 a2, A3 a3, A4 a4, A5 a5, A6 a6, - A7 a7, A8 a8, A9 a9) { - return f(a1, a2, a3, a4, a5, a6, a7, a8, a9); -} -template -R InvokeArgumentAdl(AdlTag, F f, A1 a1, A2 a2, A3 a3, A4 a4, A5 a5, A6 a6, - A7 a7, A8 a8, A9 a9, A10 a10) { - return f(a1, a2, a3, a4, a5, a6, a7, a8, a9, a10); -} -} // namespace invoke_argument -} // namespace internal - ACTION_TEMPLATE(InvokeArgument, HAS_1_TEMPLATE_PARAMS(int, k), AND_0_VALUE_PARAMS()) { using internal::invoke_argument::InvokeArgumentAdl; - return InvokeArgumentAdl( - internal::invoke_argument::AdlTag(), - ::std::get(args)); + return InvokeArgumentAdl(internal::invoke_argument::AdlTag(), + ::std::get(args)); } ACTION_TEMPLATE(InvokeArgument, HAS_1_TEMPLATE_PARAMS(int, k), AND_1_VALUE_PARAMS(p0)) { using internal::invoke_argument::InvokeArgumentAdl; - return InvokeArgumentAdl( - internal::invoke_argument::AdlTag(), - ::std::get(args), p0); + return InvokeArgumentAdl(internal::invoke_argument::AdlTag(), + ::std::get(args), p0); } ACTION_TEMPLATE(InvokeArgument, HAS_1_TEMPLATE_PARAMS(int, k), AND_2_VALUE_PARAMS(p0, p1)) { using internal::invoke_argument::InvokeArgumentAdl; - return InvokeArgumentAdl( - internal::invoke_argument::AdlTag(), - ::std::get(args), p0, p1); + return InvokeArgumentAdl(internal::invoke_argument::AdlTag(), + ::std::get(args), p0, p1); } ACTION_TEMPLATE(InvokeArgument, HAS_1_TEMPLATE_PARAMS(int, k), AND_3_VALUE_PARAMS(p0, p1, p2)) { using internal::invoke_argument::InvokeArgumentAdl; - return InvokeArgumentAdl( - internal::invoke_argument::AdlTag(), - ::std::get(args), p0, p1, p2); + return InvokeArgumentAdl(internal::invoke_argument::AdlTag(), + ::std::get(args), p0, p1, p2); } ACTION_TEMPLATE(InvokeArgument, HAS_1_TEMPLATE_PARAMS(int, k), AND_4_VALUE_PARAMS(p0, p1, p2, p3)) { using internal::invoke_argument::InvokeArgumentAdl; - return InvokeArgumentAdl( - internal::invoke_argument::AdlTag(), - ::std::get(args), p0, p1, p2, p3); + return InvokeArgumentAdl(internal::invoke_argument::AdlTag(), + ::std::get(args), p0, p1, p2, p3); } ACTION_TEMPLATE(InvokeArgument, HAS_1_TEMPLATE_PARAMS(int, k), AND_5_VALUE_PARAMS(p0, p1, p2, p3, p4)) { using internal::invoke_argument::InvokeArgumentAdl; - return InvokeArgumentAdl( - internal::invoke_argument::AdlTag(), - ::std::get(args), p0, p1, p2, p3, p4); + return InvokeArgumentAdl(internal::invoke_argument::AdlTag(), + ::std::get(args), p0, p1, p2, p3, p4); } ACTION_TEMPLATE(InvokeArgument, HAS_1_TEMPLATE_PARAMS(int, k), AND_6_VALUE_PARAMS(p0, p1, p2, p3, p4, p5)) { using internal::invoke_argument::InvokeArgumentAdl; - return InvokeArgumentAdl( - internal::invoke_argument::AdlTag(), - ::std::get(args), p0, p1, p2, p3, p4, p5); + return InvokeArgumentAdl(internal::invoke_argument::AdlTag(), + ::std::get(args), p0, p1, p2, p3, p4, p5); } ACTION_TEMPLATE(InvokeArgument, HAS_1_TEMPLATE_PARAMS(int, k), AND_7_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6)) { using internal::invoke_argument::InvokeArgumentAdl; - return InvokeArgumentAdl( - internal::invoke_argument::AdlTag(), - ::std::get(args), p0, p1, p2, p3, p4, p5, p6); + return InvokeArgumentAdl(internal::invoke_argument::AdlTag(), + ::std::get(args), p0, p1, p2, p3, p4, p5, p6); } ACTION_TEMPLATE(InvokeArgument, HAS_1_TEMPLATE_PARAMS(int, k), AND_8_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, p7)) { using internal::invoke_argument::InvokeArgumentAdl; - return InvokeArgumentAdl( - internal::invoke_argument::AdlTag(), - ::std::get(args), p0, p1, p2, p3, p4, p5, p6, p7); + return InvokeArgumentAdl(internal::invoke_argument::AdlTag(), + ::std::get(args), p0, p1, p2, p3, p4, p5, p6, p7); } ACTION_TEMPLATE(InvokeArgument, HAS_1_TEMPLATE_PARAMS(int, k), AND_9_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, p7, p8)) { using internal::invoke_argument::InvokeArgumentAdl; - return InvokeArgumentAdl( - internal::invoke_argument::AdlTag(), - ::std::get(args), p0, p1, p2, p3, p4, p5, p6, p7, p8); + return InvokeArgumentAdl(internal::invoke_argument::AdlTag(), + ::std::get(args), p0, p1, p2, p3, p4, p5, p6, p7, + p8); } ACTION_TEMPLATE(InvokeArgument, HAS_1_TEMPLATE_PARAMS(int, k), AND_10_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, p7, p8, p9)) { using internal::invoke_argument::InvokeArgumentAdl; - return InvokeArgumentAdl( - internal::invoke_argument::AdlTag(), - ::std::get(args), p0, p1, p2, p3, p4, p5, p6, p7, p8, p9); + return InvokeArgumentAdl(internal::invoke_argument::AdlTag(), + ::std::get(args), p0, p1, p2, p3, p4, p5, p6, p7, + p8, p9); } // Various overloads for ReturnNew(). diff --git a/googlemock/include/gmock/gmock-generated-actions.h.pump b/googlemock/include/gmock/gmock-generated-actions.h.pump index 1121fbdec8..bd3eadb9eb 100644 --- a/googlemock/include/gmock/gmock-generated-actions.h.pump +++ b/googlemock/include/gmock/gmock-generated-actions.h.pump @@ -506,32 +506,6 @@ namespace testing { // InvokeArgument action from temporary values and have it performed // later. -namespace internal { -namespace invoke_argument { - -// Appears in InvokeArgumentAdl's argument list to help avoid -// accidental calls to user functions of the same name. -struct AdlTag {}; - -// InvokeArgumentAdl - a helper for InvokeArgument. -// The basic overloads are provided here for generic functors. -// Overloads for other custom-callables are provided in the -// internal/custom/gmock-generated-actions.h header. - -$range i 0..n -$for i -[[ -$range j 1..i - -template -R InvokeArgumentAdl(AdlTag, F f[[$for j [[, A$j a$j]]]]) { - return f([[$for j, [[a$j]]]]); -} -]] - -} // namespace invoke_argument -} // namespace internal - $range i 0..n $for i [[ $range j 0..i-1 @@ -540,9 +514,8 @@ ACTION_TEMPLATE(InvokeArgument, HAS_1_TEMPLATE_PARAMS(int, k), AND_$i[[]]_VALUE_PARAMS($for j, [[p$j]])) { using internal::invoke_argument::InvokeArgumentAdl; - return InvokeArgumentAdl( - internal::invoke_argument::AdlTag(), - ::std::get(args)$for j [[, p$j]]); + return InvokeArgumentAdl(internal::invoke_argument::AdlTag(), + ::std::get(args)$for j[[, p$j]]); } ]] From 8417b7332210322090337d3232e39503437790f0 Mon Sep 17 00:00:00 2001 From: Abseil Team Date: Tue, 7 Jan 2020 12:03:58 -0500 Subject: [PATCH 134/541] Googletest export Close #2658 Mark test case destrucors as override. PiperOrigin-RevId: 288507991 --- googletest/include/gtest/internal/gtest-internal.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/googletest/include/gtest/internal/gtest-internal.h b/googletest/include/gtest/internal/gtest-internal.h index 41c94f4489..90c962b0d6 100644 --- a/googletest/include/gtest/internal/gtest-internal.h +++ b/googletest/include/gtest/internal/gtest-internal.h @@ -1405,7 +1405,7 @@ constexpr bool InstantiateTypedTestCase_P_IsDeprecated() { return true; } : public parent_class { \ public: \ GTEST_TEST_CLASS_NAME_(test_suite_name, test_name)() {} \ - ~GTEST_TEST_CLASS_NAME_(test_suite_name, test_name)() = default; \ + ~GTEST_TEST_CLASS_NAME_(test_suite_name, test_name)() override = default; \ GTEST_DISALLOW_COPY_AND_ASSIGN_(GTEST_TEST_CLASS_NAME_(test_suite_name, \ test_name)); \ GTEST_DISALLOW_MOVE_AND_ASSIGN_(GTEST_TEST_CLASS_NAME_(test_suite_name, \ From c901f67ddf8aab44443f1be3efe864cb3daa95af Mon Sep 17 00:00:00 2001 From: Abseil Team Date: Thu, 9 Jan 2020 11:59:39 -0500 Subject: [PATCH 135/541] Googletest export Move part of functionality of Action* class to the base one. Reduce copypaste. Make constructor and conversion operator of Action* class independent of pump. PiperOrigin-RevId: 288907005 --- googlemock/include/gmock/gmock-actions.h | 37 +++ .../include/gmock/gmock-generated-actions.h | 235 ++++-------------- .../gmock/gmock-generated-actions.h.pump | 8 +- 3 files changed, 94 insertions(+), 186 deletions(-) diff --git a/googlemock/include/gmock/gmock-actions.h b/googlemock/include/gmock/gmock-actions.h index 11223cf280..a7b84d1b95 100644 --- a/googlemock/include/gmock/gmock-actions.h +++ b/googlemock/include/gmock/gmock-actions.h @@ -1222,6 +1222,43 @@ class ActionHelper { } }; +// A helper base class needed for implementing the ACTION* macros. +// Implements constructor and conversion operator for Action. +// +// Template specialization for parameterless Action. +template +class ActionImpl { + public: + ActionImpl() = default; + + template + operator ::testing::Action() const { // NOLINT(runtime/explicit) + return ::testing::Action(new typename Derived::template gmock_Impl()); + } +}; + +// Template specialization for parameterized Action. +template