From 4665eee10a1d495aec9970fddf6231cf2339b1b7 Mon Sep 17 00:00:00 2001 From: Gennadiy Civil Date: Tue, 9 Oct 2018 11:34:09 -0400 Subject: test, please ignore --- newfile.txt | 1 + 1 file changed, 1 insertion(+) create mode 100644 newfile.txt diff --git a/newfile.txt b/newfile.txt new file mode 100644 index 00000000..2a02d41c --- /dev/null +++ b/newfile.txt @@ -0,0 +1 @@ +TEST -- cgit v1.2.3 From 096fb37a1976bbddde136c9db5fa88ac4332b802 Mon Sep 17 00:00:00 2001 From: Abseil Team Date: Fri, 14 Dec 2018 15:24:21 -0500 Subject: Googletest export Replace pump'd code for DoAll with variadic templates. PiperOrigin-RevId: 225584656 --- googlemock/include/gmock/gmock-actions.h | 86 ++++++++++---------- googlemock/include/gmock/gmock-generated-actions.h | 91 ---------------------- .../include/gmock/gmock-generated-actions.h.pump | 28 ------- 3 files changed, 40 insertions(+), 165 deletions(-) diff --git a/googlemock/include/gmock/gmock-actions.h b/googlemock/include/gmock/gmock-actions.h index 7105830d..e0437f3f 100644 --- a/googlemock/include/gmock/gmock-actions.h +++ b/googlemock/include/gmock/gmock-actions.h @@ -574,7 +574,7 @@ class ReturnAction { // This template type conversion operator allows Return(x) to be // used in ANY function that returns x's type. template - operator Action() const { + operator Action() const { // NOLINT // Assert statement belongs here because this is the best place to verify // conditions on F. It produces the clearest error messages // in most compilers. @@ -587,6 +587,8 @@ class ReturnAction { GTEST_COMPILE_ASSERT_( !is_reference::value, use_ReturnRef_instead_of_Return_to_return_a_reference); + static_assert(!std::is_void::value, + "Can't use Return() on an action expected to return `void`."); return Action(new Impl(value_)); } @@ -1017,51 +1019,6 @@ void PrintTo(const ReferenceWrapper& ref, ::std::ostream* os) { UniversalPrinter::Print(value, os); } -// Does two actions sequentially. Used for implementing the DoAll(a1, -// a2, ...) action. -template -class DoBothAction { - public: - DoBothAction(Action1 action1, Action2 action2) - : action1_(action1), action2_(action2) {} - - // This template type conversion operator allows DoAll(a1, ..., a_n) - // to be used in ANY function of compatible type. - template - operator Action() const { - return Action(new Impl(action1_, action2_)); - } - - private: - // Implements the DoAll(...) action for a particular function type F. - template - class Impl : public ActionInterface { - public: - typedef typename Function::Result Result; - typedef typename Function::ArgumentTuple ArgumentTuple; - typedef typename Function::MakeResultVoid VoidResult; - - Impl(const Action& action1, const Action& action2) - : action1_(action1), action2_(action2) {} - - Result Perform(const ArgumentTuple& args) override { - action1_.Perform(args); - return action2_.Perform(args); - } - - private: - const Action action1_; - const Action action2_; - - GTEST_DISALLOW_ASSIGN_(Impl); - }; - - Action1 action1_; - Action2 action2_; - - GTEST_DISALLOW_ASSIGN_(DoBothAction); -}; - template struct WithArgsAction { InnerAction action; @@ -1080,6 +1037,35 @@ struct WithArgsAction { } }; +template +struct DoAllAction { + private: + template + std::vector> Convert(IndexSequence) const { + return {std::get(actions)...}; + } + + public: + std::tuple actions; + + template + operator Action() const { // NOLINT + struct Op { + std::vector> converted; + Action last; + R operator()(Args... args) const { + auto tuple_args = std::forward_as_tuple(std::forward(args)...); + for (auto& a : converted) { + a.Perform(tuple_args); + } + return last.Perform(tuple_args); + } + }; + return Op{Convert(MakeIndexSequence()), + std::get(actions)}; + } +}; + } // namespace internal // An Unused object can be implicitly constructed from ANY value. @@ -1130,6 +1116,14 @@ Action::Action(const Action& from) : new internal::ActionAdaptor(from)) { } +// Creates an action that does actions a1, a2, ..., sequentially in +// each invocation. +template +internal::DoAllAction::type...> DoAll( + Action&&... action) { + return {std::forward_as_tuple(std::forward(action)...)}; +} + // WithArg(an_action) creates an action that passes the k-th // (0-based) argument of the mock function to an_action and performs // it. It adapts an action accepting one argument to one that accepts diff --git a/googlemock/include/gmock/gmock-generated-actions.h b/googlemock/include/gmock/gmock-generated-actions.h index fac491b7..910436e0 100644 --- a/googlemock/include/gmock/gmock-generated-actions.h +++ b/googlemock/include/gmock/gmock-generated-actions.h @@ -474,97 +474,6 @@ class ActionHelper { }; } // namespace internal - -// Creates an action that does actions a1, a2, ..., sequentially in -// each invocation. -template -inline internal::DoBothAction -DoAll(Action1 a1, Action2 a2) { - return internal::DoBothAction(a1, a2); -} - -template -inline internal::DoBothAction > -DoAll(Action1 a1, Action2 a2, Action3 a3) { - return DoAll(a1, DoAll(a2, a3)); -} - -template -inline internal::DoBothAction > > -DoAll(Action1 a1, Action2 a2, Action3 a3, Action4 a4) { - return DoAll(a1, DoAll(a2, a3, a4)); -} - -template -inline internal::DoBothAction > > > -DoAll(Action1 a1, Action2 a2, Action3 a3, Action4 a4, Action5 a5) { - return DoAll(a1, DoAll(a2, a3, a4, a5)); -} - -template -inline internal::DoBothAction > > > > -DoAll(Action1 a1, Action2 a2, Action3 a3, Action4 a4, Action5 a5, Action6 a6) { - return DoAll(a1, DoAll(a2, a3, a4, a5, a6)); -} - -template -inline internal::DoBothAction > > > > > -DoAll(Action1 a1, Action2 a2, Action3 a3, Action4 a4, Action5 a5, Action6 a6, - Action7 a7) { - return DoAll(a1, DoAll(a2, a3, a4, a5, a6, a7)); -} - -template -inline internal::DoBothAction > > > > > > -DoAll(Action1 a1, Action2 a2, Action3 a3, Action4 a4, Action5 a5, Action6 a6, - Action7 a7, Action8 a8) { - return DoAll(a1, DoAll(a2, a3, a4, a5, a6, a7, a8)); -} - -template -inline internal::DoBothAction > > > > > > > -DoAll(Action1 a1, Action2 a2, Action3 a3, Action4 a4, Action5 a5, Action6 a6, - Action7 a7, Action8 a8, Action9 a9) { - return DoAll(a1, DoAll(a2, a3, a4, a5, a6, a7, a8, a9)); -} - -template -inline internal::DoBothAction > > > > > > > > -DoAll(Action1 a1, Action2 a2, Action3 a3, Action4 a4, Action5 a5, Action6 a6, - Action7 a7, Action8 a8, Action9 a9, Action10 a10) { - return DoAll(a1, DoAll(a2, a3, a4, a5, a6, a7, a8, a9, a10)); -} - } // namespace testing // The ACTION* family of macros can be used in a namespace scope to diff --git a/googlemock/include/gmock/gmock-generated-actions.h.pump b/googlemock/include/gmock/gmock-generated-actions.h.pump index d38b1f92..27c96efc 100644 --- a/googlemock/include/gmock/gmock-generated-actions.h.pump +++ b/googlemock/include/gmock/gmock-generated-actions.h.pump @@ -165,34 +165,6 @@ $template }; } // namespace internal - -// Creates an action that does actions a1, a2, ..., sequentially in -// each invocation. -$range i 2..n -$for i [[ -$range j 2..i -$var types = [[$for j, [[typename Action$j]]]] -$var Aas = [[$for j [[, Action$j a$j]]]] - -template -$range k 1..i-1 - -inline $for k [[internal::DoBothAction]] - -DoAll(Action1 a1$Aas) { -$if i==2 [[ - - return internal::DoBothAction(a1, a2); -]] $else [[ -$range j2 2..i - - return DoAll(a1, DoAll($for j2, [[a$j2]])); -]] - -} - -]] - } // namespace testing // The ACTION* family of macros can be used in a namespace scope to -- cgit v1.2.3 From 1ec20f87e390e1d711e69b69345e68a1fa656bbc Mon Sep 17 00:00:00 2001 From: Abseil Team Date: Sat, 15 Dec 2018 08:11:02 -0500 Subject: Googletest export Allow container matchers to accept move-only containers. PiperOrigin-RevId: 225667441 --- googlemock/include/gmock/gmock-matchers.h | 30 +++++---- googlemock/test/gmock-matchers_test.cc | 107 ++++++++++++++++++++++++++++-- 2 files changed, 121 insertions(+), 16 deletions(-) diff --git a/googlemock/include/gmock/gmock-matchers.h b/googlemock/include/gmock/gmock-matchers.h index 68278bea..fa89bd60 100644 --- a/googlemock/include/gmock/gmock-matchers.h +++ b/googlemock/include/gmock/gmock-matchers.h @@ -1959,7 +1959,7 @@ class SizeIsMatcher { template operator Matcher() const { - return MakeMatcher(new Impl(size_matcher_)); + return Matcher(new Impl(size_matcher_)); } template @@ -2009,7 +2009,7 @@ class BeginEndDistanceIsMatcher { template operator Matcher() const { - return MakeMatcher(new Impl(distance_matcher_)); + return Matcher(new Impl(distance_matcher_)); } template @@ -2269,7 +2269,8 @@ class PointwiseMatcher { !IsHashTable::value, use_UnorderedPointwise_with_hash_tables); - return MakeMatcher(new Impl(tuple_matcher_, rhs_)); + return Matcher( + new Impl(tuple_matcher_, rhs_)); } template @@ -2471,7 +2472,8 @@ class ContainsMatcher { template operator Matcher() const { - return MakeMatcher(new ContainsMatcherImpl(inner_matcher_)); + return Matcher( + new ContainsMatcherImpl(inner_matcher_)); } private: @@ -2488,7 +2490,8 @@ class EachMatcher { template operator Matcher() const { - return MakeMatcher(new EachMatcherImpl(inner_matcher_)); + return Matcher( + new EachMatcherImpl(inner_matcher_)); } private: @@ -3086,8 +3089,10 @@ class UnorderedElementsAreMatcher { matchers.reserve(::std::tuple_size::value); TransformTupleValues(CastAndAppendTransform(), matchers_, ::std::back_inserter(matchers)); - return MakeMatcher(new UnorderedElementsAreMatcherImpl( - UnorderedMatcherRequire::ExactMatch, matchers.begin(), matchers.end())); + return Matcher( + new UnorderedElementsAreMatcherImpl( + UnorderedMatcherRequire::ExactMatch, matchers.begin(), + matchers.end())); } private: @@ -3116,8 +3121,8 @@ class ElementsAreMatcher { matchers.reserve(::std::tuple_size::value); TransformTupleValues(CastAndAppendTransform(), matchers_, ::std::back_inserter(matchers)); - return MakeMatcher(new ElementsAreMatcherImpl( - matchers.begin(), matchers.end())); + return Matcher(new ElementsAreMatcherImpl( + matchers.begin(), matchers.end())); } private: @@ -3136,8 +3141,9 @@ class UnorderedElementsAreArrayMatcher { template operator Matcher() const { - return MakeMatcher(new UnorderedElementsAreMatcherImpl( - match_flags_, matchers_.begin(), matchers_.end())); + return Matcher( + new UnorderedElementsAreMatcherImpl( + match_flags_, matchers_.begin(), matchers_.end())); } private: @@ -3160,7 +3166,7 @@ class ElementsAreArrayMatcher { !IsHashTable::value, use_UnorderedElementsAreArray_with_hash_tables); - return MakeMatcher(new ElementsAreMatcherImpl( + return Matcher(new ElementsAreMatcherImpl( matchers_.begin(), matchers_.end())); } diff --git a/googlemock/test/gmock-matchers_test.cc b/googlemock/test/gmock-matchers_test.cc index c1589a40..a7221877 100644 --- a/googlemock/test/gmock-matchers_test.cc +++ b/googlemock/test/gmock-matchers_test.cc @@ -72,6 +72,7 @@ namespace testing { namespace gmock_matchers_test { +namespace { using std::greater; using std::less; @@ -158,6 +159,19 @@ using testing::internal::StreamMatchResultListener; using testing::internal::string; using testing::internal::Strings; +// Helper for testing container-valued matchers in mock method context. It is +// important to test matchers in this context, since it requires additional type +// deduction beyond what EXPECT_THAT does, thus making it more restrictive. +struct ContainerHelper { + MOCK_METHOD1(Call, void(std::vector>)); +}; + +std::vector> MakeUniquePtrs(const std::vector& ints) { + std::vector> pointers; + for (int i : ints) pointers.emplace_back(new int(i)); + return pointers; +} + // For testing ExplainMatchResultTo(). class GreaterThanMatcher : public MatcherInterface { public: @@ -1679,6 +1693,12 @@ TEST(PairTest, InsideContainsUsingMap) { EXPECT_THAT(container, Not(Contains(Pair(3, _)))); } +TEST(ContainsTest, WorksWithMoveOnly) { + ContainerHelper helper; + EXPECT_CALL(helper, Call(Contains(Pointee(2)))); + helper.Call(MakeUniquePtrs({1, 2})); +} + #if GTEST_LANG_CXX11 TEST(PairTest, UseGetInsteadOfMembers) { PairWithGet pair{7, "ABC"}; @@ -4752,6 +4772,12 @@ TEST(IsEmptyTest, ExplainsResult) { EXPECT_EQ("whose size is 1", Explain(m, container)); } +TEST(IsEmptyTest, WorksWithMoveOnly) { + ContainerHelper helper; + EXPECT_CALL(helper, Call(IsEmpty())); + helper.Call({}); +} + TEST(IsTrueTest, IsTrueIsFalse) { EXPECT_THAT(true, IsTrue()); EXPECT_THAT(false, IsFalse()); @@ -4822,6 +4848,12 @@ TEST(SizeIsTest, WorksWithReferences) { EXPECT_THAT(container, m); } +TEST(SizeIsTest, WorksWithMoveOnly) { + ContainerHelper helper; + EXPECT_CALL(helper, Call(SizeIs(3))); + helper.Call(MakeUniquePtrs({1, 2, 3})); +} + // SizeIs should work for any type that provides a size() member function. // For example, a size_type member type should not need to be provided. struct MinimalistCustomType { @@ -5308,6 +5340,12 @@ TEST(BeginEndDistanceIsTest, CanDescribeSelf) { DescribeNegation(m)); } +TEST(BeginEndDistanceIsTest, WorksWithMoveOnly) { + ContainerHelper helper; + EXPECT_CALL(helper, Call(BeginEndDistanceIs(2))); + helper.Call(MakeUniquePtrs({1, 2})); +} + TEST(BeginEndDistanceIsTest, ExplainsResult) { Matcher > m1 = BeginEndDistanceIs(2); Matcher > m2 = BeginEndDistanceIs(Lt(2)); @@ -5477,6 +5515,14 @@ TEST(IsSupersetOfTest, WorksForRhsInitializerList) { } #endif +TEST(IsSupersetOfTest, WorksWithMoveOnly) { + ContainerHelper helper; + EXPECT_CALL(helper, Call(IsSupersetOf({Pointee(1)}))); + helper.Call(MakeUniquePtrs({1, 2})); + EXPECT_CALL(helper, Call(Not(IsSupersetOf({Pointee(1), Pointee(2)})))); + helper.Call(MakeUniquePtrs({2})); +} + TEST(IsSubsetOfTest, WorksForNativeArray) { const int subset[] = {1, 4}; const int superset[] = {1, 2, 4}; @@ -5599,6 +5645,14 @@ TEST(IsSubsetOfTest, WorksForRhsInitializerList) { } #endif +TEST(IsSubsetOfTest, WorksWithMoveOnly) { + ContainerHelper helper; + EXPECT_CALL(helper, Call(IsSubsetOf({Pointee(1), Pointee(2)}))); + helper.Call(MakeUniquePtrs({1})); + EXPECT_CALL(helper, Call(Not(IsSubsetOf({Pointee(1)})))); + helper.Call(MakeUniquePtrs({2})); +} + // Tests using ElementsAre() and ElementsAreArray() with stream-like // "containers". @@ -5632,6 +5686,15 @@ TEST(ElementsAreTest, WorksWithUncopyable) { EXPECT_THAT(objs, ElementsAre(UncopyableIs(-3), Truly(ValueIsPositive))); } +TEST(ElementsAreTest, WorksWithMoveOnly) { + ContainerHelper helper; + EXPECT_CALL(helper, Call(ElementsAre(Pointee(1), Pointee(2)))); + helper.Call(MakeUniquePtrs({1, 2})); + + EXPECT_CALL(helper, Call(ElementsAreArray({Pointee(3), Pointee(4)}))); + helper.Call(MakeUniquePtrs({3, 4})); +} + TEST(ElementsAreTest, TakesStlContainer) { const int actual[] = {3, 1, 2}; @@ -5735,6 +5798,13 @@ TEST(UnorderedElementsAreArrayTest, #endif // GTEST_HAS_STD_INITIALIZER_LIST_ +TEST(UnorderedElementsAreArrayTest, WorksWithMoveOnly) { + ContainerHelper helper; + EXPECT_CALL(helper, + Call(UnorderedElementsAreArray({Pointee(1), Pointee(2)}))); + helper.Call(MakeUniquePtrs({2, 1})); +} + class UnorderedElementsAreTest : public testing::Test { protected: typedef std::vector IntVec; @@ -5782,6 +5852,12 @@ TEST_F(UnorderedElementsAreTest, WorksForStreamlike) { EXPECT_THAT(s, Not(UnorderedElementsAre(2, 2, 3, 4, 5))); } +TEST_F(UnorderedElementsAreTest, WorksWithMoveOnly) { + ContainerHelper helper; + EXPECT_CALL(helper, Call(UnorderedElementsAre(Pointee(1), Pointee(2)))); + helper.Call(MakeUniquePtrs({2, 1})); +} + // One naive implementation of the matcher runs in O(N!) time, which is too // slow for many real-world inputs. This test shows that our matcher can match // 100 inputs very quickly (a few milliseconds). An O(100!) is 10^158 @@ -6332,6 +6408,12 @@ TEST(EachTest, WorksForNativeArrayAsTuple) { EXPECT_THAT(std::make_tuple(pointer, 2), Not(Each(Gt(1)))); } +TEST(EachTest, WorksWithMoveOnly) { + ContainerHelper helper; + EXPECT_CALL(helper, Call(Each(Pointee(Gt(0))))); + helper.Call(MakeUniquePtrs({1, 2})); +} + // For testing Pointwise(). class IsHalfOfMatcher { public: @@ -6470,6 +6552,17 @@ TEST(PointwiseTest, AllowsMonomorphicInnerMatcher) { EXPECT_EQ("", Explain(Pointwise(m2, rhs), lhs)); } +MATCHER(PointeeEquals, "Points to an equal value") { + return ExplainMatchResult(::testing::Pointee(::testing::get<1>(arg)), + ::testing::get<0>(arg), result_listener); +} + +TEST(PointwiseTest, WorksWithMoveOnly) { + ContainerHelper helper; + EXPECT_CALL(helper, Call(Pointwise(PointeeEquals(), std::vector{1, 2}))); + helper.Call(MakeUniquePtrs({1, 2})); +} + TEST(UnorderedPointwiseTest, DescribesSelf) { vector rhs; rhs.push_back(1); @@ -6584,6 +6677,13 @@ TEST(UnorderedPointwiseTest, AllowsMonomorphicInnerMatcher) { EXPECT_THAT(lhs, UnorderedPointwise(m2, rhs)); } +TEST(UnorderedPointwiseTest, WorksWithMoveOnly) { + ContainerHelper helper; + EXPECT_CALL(helper, Call(UnorderedPointwise(PointeeEquals(), + std::vector{1, 2}))); + helper.Call(MakeUniquePtrs({2, 1})); +} + // Sample optional type implementation with minimal requirements for use with // Optional matcher. class SampleOptionalInt { @@ -6976,8 +7076,7 @@ TEST_F(PredicateFormatterFromMatcherTest, NoShortCircuitOnFailure) { EXPECT_FALSE(result); // Implicit cast to bool. std::string expect = "Value of: dummy-name\nExpected: [DescribeTo]\n" - " Actual: 1" + - OfType(kMatcherType) + ", [MatchAndExplain]"; + " Actual: 1, [MatchAndExplain]"; EXPECT_EQ(expect, result.message()); } @@ -6988,11 +7087,11 @@ TEST_F(PredicateFormatterFromMatcherTest, DetectsFlakyShortCircuit) { "Value of: dummy-name\nExpected: [DescribeTo]\n" " The matcher failed on the initial attempt; but passed when rerun to " "generate the explanation.\n" - " Actual: 2" + - OfType(kMatcherType) + ", [MatchAndExplain]"; + " Actual: 2, [MatchAndExplain]"; EXPECT_EQ(expect, result.message()); } +} // namespace } // namespace gmock_matchers_test } // namespace testing -- cgit v1.2.3 From b7dd66519f4af354b1938860a4073669b6cd91ab Mon Sep 17 00:00:00 2001 From: Abseil Team Date: Sun, 16 Dec 2018 05:14:13 -0500 Subject: Googletest export Remove GTEST_REFERENCE_TO_CONST_ usage from GMock. In C++11, it's redundant. PiperOrigin-RevId: 225719210 --- googlemock/include/gmock/gmock-matchers.h | 45 ++++++++++++------------------- googletest/include/gtest/gtest-matchers.h | 29 ++++++++------------ 2 files changed, 28 insertions(+), 46 deletions(-) diff --git a/googlemock/include/gmock/gmock-matchers.h b/googlemock/include/gmock/gmock-matchers.h index fa89bd60..be881e14 100644 --- a/googlemock/include/gmock/gmock-matchers.h +++ b/googlemock/include/gmock/gmock-matchers.h @@ -387,7 +387,7 @@ class TuplePrefix { typename std::tuple_element::type matcher = std::get(matchers); typedef typename std::tuple_element::type Value; - GTEST_REFERENCE_TO_CONST_(Value) value = std::get(values); + const Value& value = std::get(values); StringMatchResultListener listener; if (!matcher.MatchAndExplain(value, &listener)) { // FIXME: include in the message the name of the parameter @@ -492,9 +492,9 @@ OutIter TransformTupleValues(Func f, const Tuple& t, OutIter out) { // Implements A(). template -class AnyMatcherImpl : public MatcherInterface { +class AnyMatcherImpl : public MatcherInterface { public: - bool MatchAndExplain(GTEST_REFERENCE_TO_CONST_(T) /* x */, + bool MatchAndExplain(const T& /* x */, MatchResultListener* /* listener */) const override { return true; } @@ -976,12 +976,12 @@ class Ge2Matcher : public PairMatchBase { // will prevent different instantiations of NotMatcher from sharing // the same NotMatcherImpl class. template -class NotMatcherImpl : public MatcherInterface { +class NotMatcherImpl : public MatcherInterface { public: explicit NotMatcherImpl(const Matcher& matcher) : matcher_(matcher) {} - bool MatchAndExplain(GTEST_REFERENCE_TO_CONST_(T) x, + bool MatchAndExplain(const T& x, MatchResultListener* listener) const override { return !matcher_.MatchAndExplain(x, listener); } @@ -1025,8 +1025,7 @@ class NotMatcher { // that will prevent different instantiations of BothOfMatcher from // sharing the same BothOfMatcherImpl class. template -class AllOfMatcherImpl - : public MatcherInterface { +class AllOfMatcherImpl : public MatcherInterface { public: explicit AllOfMatcherImpl(std::vector > matchers) : matchers_(std::move(matchers)) {} @@ -1049,7 +1048,7 @@ class AllOfMatcherImpl *os << ")"; } - bool MatchAndExplain(GTEST_REFERENCE_TO_CONST_(T) x, + bool MatchAndExplain(const T& x, MatchResultListener* listener) const override { // If either matcher1_ or matcher2_ doesn't match x, we only need // to explain why one of them fails. @@ -1132,8 +1131,7 @@ using AllOfMatcher = VariadicMatcher; // that will prevent different instantiations of AnyOfMatcher from // sharing the same EitherOfMatcherImpl class. template -class AnyOfMatcherImpl - : public MatcherInterface { +class AnyOfMatcherImpl : public MatcherInterface { public: explicit AnyOfMatcherImpl(std::vector > matchers) : matchers_(std::move(matchers)) {} @@ -1156,7 +1154,7 @@ class AnyOfMatcherImpl *os << ")"; } - bool MatchAndExplain(GTEST_REFERENCE_TO_CONST_(T) x, + bool MatchAndExplain(const T& x, MatchResultListener* listener) const override { std::string no_match_result; @@ -1584,8 +1582,7 @@ class PointeeMatcher { // enough for implementing the DescribeTo() method of Pointee(). template operator Matcher() const { - return Matcher( - new Impl(matcher_)); + return Matcher(new Impl(matcher_)); } private: @@ -1775,11 +1772,7 @@ class FieldMatcher { template class PropertyMatcher { public: - // The property may have a reference type, so 'const PropertyType&' - // may cause double references and fail to compile. That's why we - // need GTEST_REFERENCE_TO_CONST, which works regardless of - // PropertyType being a reference or not. - typedef GTEST_REFERENCE_TO_CONST_(PropertyType) RefToConstProperty; + typedef const PropertyType& RefToConstProperty; PropertyMatcher(Property property, const Matcher& matcher) : property_(property), @@ -3776,8 +3769,7 @@ Property(PropertyType (Class::*property)() const, return MakePolymorphicMatcher( internal::PropertyMatcher( - property, - MatcherCast(matcher))); + property, MatcherCast(matcher))); // The call to MatcherCast() is required for supporting inner // matchers of compatible types. For example, it allows // Property(&Foo::bar, m) @@ -3795,8 +3787,7 @@ Property(const std::string& property_name, return MakePolymorphicMatcher( internal::PropertyMatcher( - property_name, property, - MatcherCast(matcher))); + property_name, property, MatcherCast(matcher))); } #if GTEST_LANG_CXX11 @@ -3808,9 +3799,8 @@ Property(PropertyType (Class::*property)() const &, const PropertyMatcher& matcher) { return MakePolymorphicMatcher( internal::PropertyMatcher( - property, - MatcherCast(matcher))); + PropertyType (Class::*)() const&>( + property, MatcherCast(matcher))); } // Three-argument form for reference-qualified member functions. @@ -3822,9 +3812,8 @@ Property(const std::string& property_name, const PropertyMatcher& matcher) { return MakePolymorphicMatcher( internal::PropertyMatcher( - property_name, property, - MatcherCast(matcher))); + PropertyType (Class::*)() const&>( + property_name, property, MatcherCast(matcher))); } #endif diff --git a/googletest/include/gtest/gtest-matchers.h b/googletest/include/gtest/gtest-matchers.h index 9bcf5ac2..02a9952b 100644 --- a/googletest/include/gtest/gtest-matchers.h +++ b/googletest/include/gtest/gtest-matchers.h @@ -256,13 +256,12 @@ class MatcherBase { public: // Returns true iff the matcher matches x; also explains the match // result to 'listener'. - bool MatchAndExplain(GTEST_REFERENCE_TO_CONST_(T) x, - MatchResultListener* listener) const { + bool MatchAndExplain(const T& x, MatchResultListener* listener) const { return impl_->MatchAndExplain(x, listener); } // Returns true iff this matcher matches x. - bool Matches(GTEST_REFERENCE_TO_CONST_(T) x) const { + bool Matches(const T& x) const { DummyMatchResultListener dummy; return MatchAndExplain(x, &dummy); } @@ -276,8 +275,7 @@ class MatcherBase { } // Explains why x matches, or doesn't match, the matcher. - void ExplainMatchResultTo(GTEST_REFERENCE_TO_CONST_(T) x, - ::std::ostream* os) const { + void ExplainMatchResultTo(const T& x, ::std::ostream* os) const { StreamMatchResultListener listener(os); MatchAndExplain(x, &listener); } @@ -293,22 +291,19 @@ class MatcherBase { MatcherBase() {} // Constructs a matcher from its implementation. - explicit MatcherBase( - const MatcherInterface* impl) - : impl_(impl) {} + explicit MatcherBase(const MatcherInterface* impl) : impl_(impl) {} template explicit MatcherBase( const MatcherInterface* impl, typename internal::EnableIf< - !internal::IsSame::value>::type* = - nullptr) + !internal::IsSame::value>::type* = nullptr) : impl_(new internal::MatcherInterfaceAdapter(impl)) {} virtual ~MatcherBase() {} private: - std::shared_ptr> impl_; + std::shared_ptr> impl_; }; } // namespace internal @@ -326,15 +321,13 @@ class Matcher : public internal::MatcherBase { explicit Matcher() {} // NOLINT // Constructs a matcher from its implementation. - explicit Matcher(const MatcherInterface* impl) + explicit Matcher(const MatcherInterface* impl) : internal::MatcherBase(impl) {} template - explicit Matcher( - const MatcherInterface* impl, - typename internal::EnableIf< - !internal::IsSame::value>::type* = - nullptr) + explicit Matcher(const MatcherInterface* impl, + typename internal::EnableIf< + !internal::IsSame::value>::type* = nullptr) : internal::MatcherBase(impl) {} // Implicit constructor here allows people to write @@ -535,7 +528,7 @@ class PolymorphicMatcher { template operator Matcher() const { - return Matcher(new MonomorphicImpl(impl_)); + return Matcher(new MonomorphicImpl(impl_)); } private: -- cgit v1.2.3 From ed3f9bb229602c3b34590b3fa73b3ba0ba2a2dec Mon Sep 17 00:00:00 2001 From: misterg Date: Mon, 17 Dec 2018 13:35:15 -0500 Subject: Googletest export Internal Change PiperOrigin-RevId: 225849972 --- googletest/test/BUILD.bazel | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/googletest/test/BUILD.bazel b/googletest/test/BUILD.bazel index 66832063..9376feb1 100644 --- a/googletest/test/BUILD.bazel +++ b/googletest/test/BUILD.bazel @@ -278,6 +278,13 @@ cc_binary( deps = ["//:gtest"], ) +cc_test( + name = "gtest_skip_test", + size = "small", + srcs = ["gtest_skip_test.cc"], + deps = ["//:gtest_main"], +) + py_test( name = "googletest-list-tests-unittest", size = "small", -- cgit v1.2.3 From 85c4172ed66e59c747777f5cfebcec2991cca8b8 Mon Sep 17 00:00:00 2001 From: Gennadiy Civil Date: Mon, 17 Dec 2018 14:03:51 -0500 Subject: Update README.md Update build badge to point to the correct location --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 88ed935f..47483536 100644 --- a/README.md +++ b/README.md @@ -1,7 +1,7 @@ # Google Test # -[![Build Status](https://api.travis-ci.org/abseil/googletest.svg?branch=master)](https://travis-ci.org/abseil/googletest) +[![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**: -- cgit v1.2.3 From 7515e399436a832a0109d64a70b4e1125568dda5 Mon Sep 17 00:00:00 2001 From: misterg Date: Mon, 17 Dec 2018 15:35:22 -0500 Subject: Googletest export Suppress C4503 for MCVS PiperOrigin-RevId: 225871050 --- googlemock/test/gmock-generated-actions_test.cc | 2 ++ 1 file changed, 2 insertions(+) diff --git a/googlemock/test/gmock-generated-actions_test.cc b/googlemock/test/gmock-generated-actions_test.cc index 0fe43ab3..23711028 100644 --- a/googlemock/test/gmock-generated-actions_test.cc +++ b/googlemock/test/gmock-generated-actions_test.cc @@ -428,9 +428,11 @@ TEST(DoAllTest, TenActions) { // the macro definition, as the warnings are generated when the macro // is expanded and macro expansion cannot contain #pragma. Therefore // we suppress them here. +// Also suppress C4503 decorated name length exceeded, name was truncated #ifdef _MSC_VER # pragma warning(push) # pragma warning(disable:4100) +# pragma warning(disable:4503) #endif // Tests the ACTION*() macro family. -- cgit v1.2.3 From 9ab640ce5e5120021c5972d7e60f258bfca64d71 Mon Sep 17 00:00:00 2001 From: misterg Date: Mon, 17 Dec 2018 17:56:57 -0500 Subject: Googletest export Suppress C4503 for MCVS , again PiperOrigin-RevId: 225895719 --- googlemock/test/gmock-generated-actions_test.cc | 4 ---- 1 file changed, 4 deletions(-) diff --git a/googlemock/test/gmock-generated-actions_test.cc b/googlemock/test/gmock-generated-actions_test.cc index 23711028..4c649a7e 100644 --- a/googlemock/test/gmock-generated-actions_test.cc +++ b/googlemock/test/gmock-generated-actions_test.cc @@ -434,7 +434,6 @@ TEST(DoAllTest, TenActions) { # pragma warning(disable:4100) # pragma warning(disable:4503) #endif - // Tests the ACTION*() macro family. // Tests that ACTION() can define an action that doesn't reference the @@ -1060,9 +1059,6 @@ TEST(ActionTemplateTest, CanBeOverloadedOnNumberOfValueParameters) { EXPECT_EQ(12345, a4.Perform(std::make_tuple())); } -#ifdef _MSC_VER -# pragma warning(pop) -#endif } // namespace gmock_generated_actions_test } // namespace testing -- cgit v1.2.3 From e26a3fa13ca21500773293946e92ec72f8d8c9ea Mon Sep 17 00:00:00 2001 From: Abseil Team Date: Mon, 17 Dec 2018 18:59:00 -0500 Subject: Googletest export Unifdef c++11-related macros from googletest now that it requires C++11. PiperOrigin-RevId: 225905601 --- .gitignore | 56 ----- googlemock/include/gmock/gmock-actions.h | 50 +---- .../gmock/gmock-generated-function-mockers.h | 5 +- .../gmock/gmock-generated-function-mockers.h.pump | 5 +- .../include/gmock/gmock-generated-nice-strict.h | 240 --------------------- .../gmock/gmock-generated-nice-strict.h.pump | 22 -- googlemock/include/gmock/gmock-matchers.h | 63 +----- .../include/gmock/internal/gmock-internal-utils.h | 2 - googlemock/test/gmock-actions_test.cc | 12 -- googlemock/test/gmock-function-mocker_test.cc | 2 - .../test/gmock-generated-function-mockers_test.cc | 2 - googlemock/test/gmock-generated-matchers_test.cc | 4 - googlemock/test/gmock-internal-utils_test.cc | 8 - googlemock/test/gmock-matchers_test.cc | 44 +--- googlemock/test/gmock-nice-strict_test.cc | 27 +-- googletest/include/gtest/internal/gtest-port.h | 121 +---------- googletest/test/googletest-printers-test.cc | 21 +- 17 files changed, 30 insertions(+), 654 deletions(-) delete mode 100644 .gitignore diff --git a/.gitignore b/.gitignore deleted file mode 100644 index d6916f5d..00000000 --- a/.gitignore +++ /dev/null @@ -1,56 +0,0 @@ -# Ignore CI build directory -build/ -xcuserdata -cmake-build-debug/ -.idea/ -bazel-bin -bazel-genfiles -bazel-googletest -bazel-out -bazel-testlogs -# python -*.pyc - -# Visual Studio files -*.sdf -*.opensdf -*.VC.opendb -*.suo -*.user -_ReSharper.Caches/ -Win32-Debug/ -Win32-Release/ -x64-Debug/ -x64-Release/ - -# Ignore autoconf / automake files -Makefile.in -aclocal.m4 -configure -build-aux/ -autom4te.cache/ -googletest/m4/libtool.m4 -googletest/m4/ltoptions.m4 -googletest/m4/ltsugar.m4 -googletest/m4/ltversion.m4 -googletest/m4/lt~obsolete.m4 - -# Ignore generated directories. -googlemock/fused-src/ -googletest/fused-src/ - -# macOS files -.DS_Store -googletest/.DS_Store -googletest/xcode/.DS_Store - -# Ignore cmake generated directories and files. -CMakeFiles -CTestTestfile.cmake -Makefile -cmake_install.cmake -googlemock/CMakeFiles -googlemock/CTestTestfile.cmake -googlemock/Makefile -googlemock/cmake_install.cmake -googlemock/gtest diff --git a/googlemock/include/gmock/gmock-actions.h b/googlemock/include/gmock/gmock-actions.h index e0437f3f..4fd3400f 100644 --- a/googlemock/include/gmock/gmock-actions.h +++ b/googlemock/include/gmock/gmock-actions.h @@ -42,18 +42,15 @@ #endif #include +#include #include #include +#include #include #include "gmock/internal/gmock-internal-utils.h" #include "gmock/internal/gmock-port.h" -#if GTEST_LANG_CXX11 // Defined by gtest-port.h via gmock-port.h. -#include -#include -#endif // GTEST_LANG_CXX11 - #ifdef _MSC_VER # pragma warning(push) # pragma warning(disable:4100) @@ -105,7 +102,6 @@ struct BuiltInDefaultValueGetter { template class BuiltInDefaultValue { public: -#if GTEST_LANG_CXX11 // This function returns true iff type T has a built-in default value. static bool Exists() { return ::std::is_default_constructible::value; @@ -115,18 +111,6 @@ class BuiltInDefaultValue { return BuiltInDefaultValueGetter< T, ::std::is_default_constructible::value>::Get(); } - -#else // GTEST_LANG_CXX11 - // This function returns true iff type T has a built-in default value. - static bool Exists() { - return false; - } - - static T Get() { - return BuiltInDefaultValueGetter::Get(); - } - -#endif // GTEST_LANG_CXX11 }; // This partial specialization says that we use the same built-in @@ -366,7 +350,6 @@ class Action { // STL containers. Action() {} -#if GTEST_LANG_CXX11 // Construct an Action from a specified callable. // This cannot take std::function directly, because then Action would not be // directly constructible from lambda (it would require two conversions). @@ -374,7 +357,6 @@ class Action { typename = typename ::std::enable_if< ::std::is_constructible<::std::function, G>::value>::type> Action(G&& fun) : fun_(::std::forward(fun)) {} // NOLINT -#endif // Constructs an Action from its implementation. explicit Action(ActionInterface* impl) : impl_(impl) {} @@ -388,11 +370,7 @@ class Action { // Returns true iff this is the DoDefault() action. bool IsDoDefault() const { -#if GTEST_LANG_CXX11 return impl_ == nullptr && fun_ == nullptr; -#else - return impl_ == NULL; -#endif } // Performs the action. Note that this method is const even though @@ -405,11 +383,9 @@ class Action { if (IsDoDefault()) { internal::IllegalDoDefault(__FILE__, __LINE__); } -#if GTEST_LANG_CXX11 if (fun_ != nullptr) { return internal::Apply(fun_, ::std::move(args)); } -#endif return impl_->Perform(args); } @@ -420,16 +396,12 @@ class Action { template friend class Action; - // In C++11, Action can be implemented either as a generic functor (through - // std::function), or legacy ActionInterface. In C++98, only ActionInterface - // is available. The invariants are as follows: - // * in C++98, impl_ is null iff this is the default action - // * in C++11, at most one of fun_ & impl_ may be nonnull; both are null iff - // this is the default action -#if GTEST_LANG_CXX11 + // Action can be implemented either as a generic functor (via std::function), + // or legacy ActionInterface. The invariant is that at most one of fun_ and + // impl_ may be nonnull; both are null iff this is the default action. + // FIXME: Fold the ActionInterface into std::function. ::std::function fun_; -#endif - std::shared_ptr> impl_; + ::std::shared_ptr> impl_; }; // The PolymorphicAction class template makes it easy to implement a @@ -662,13 +634,7 @@ class ReturnNullAction { // pointer type on compile time. template static Result Perform(const ArgumentTuple&) { -#if GTEST_LANG_CXX11 return nullptr; -#else - GTEST_COMPILE_ASSERT_(internal::is_pointer::value, - ReturnNull_can_be_used_to_return_a_pointer_only); - return NULL; -#endif // GTEST_LANG_CXX11 } }; @@ -1108,9 +1074,7 @@ template template Action::Action(const Action& from) : -#if GTEST_LANG_CXX11 fun_(from.fun_), -#endif impl_(from.impl_ == nullptr ? nullptr : new internal::ActionAdaptor(from)) { diff --git a/googlemock/include/gmock/gmock-generated-function-mockers.h b/googlemock/include/gmock/gmock-generated-function-mockers.h index cbd7b59d..5229cc1e 100644 --- a/googlemock/include/gmock/gmock-generated-function-mockers.h +++ b/googlemock/include/gmock/gmock-generated-function-mockers.h @@ -41,15 +41,12 @@ #ifndef GMOCK_INCLUDE_GMOCK_GMOCK_GENERATED_FUNCTION_MOCKERS_H_ #define GMOCK_INCLUDE_GMOCK_GMOCK_GENERATED_FUNCTION_MOCKERS_H_ +#include #include #include "gmock/gmock-spec-builders.h" #include "gmock/internal/gmock-internal-utils.h" -#if GTEST_HAS_STD_FUNCTION_ -# include -#endif - namespace testing { namespace internal { // Removes the given pointer; this is a helper for the expectation setter method diff --git a/googlemock/include/gmock/gmock-generated-function-mockers.h.pump b/googlemock/include/gmock/gmock-generated-function-mockers.h.pump index 73b68b9d..a5ec7387 100644 --- a/googlemock/include/gmock/gmock-generated-function-mockers.h.pump +++ b/googlemock/include/gmock/gmock-generated-function-mockers.h.pump @@ -42,15 +42,12 @@ $var n = 10 $$ The maximum arity we support. #ifndef GMOCK_INCLUDE_GMOCK_GMOCK_GENERATED_FUNCTION_MOCKERS_H_ #define GMOCK_INCLUDE_GMOCK_GMOCK_GENERATED_FUNCTION_MOCKERS_H_ +#include #include #include "gmock/gmock-spec-builders.h" #include "gmock/internal/gmock-internal-utils.h" -#if GTEST_HAS_STD_FUNCTION_ -# include -#endif - namespace testing { namespace internal { diff --git a/googlemock/include/gmock/gmock-generated-nice-strict.h b/googlemock/include/gmock/gmock-generated-nice-strict.h index a2e8b9ad..550892cb 100644 --- a/googlemock/include/gmock/gmock-generated-nice-strict.h +++ b/googlemock/include/gmock/gmock-generated-nice-strict.h @@ -80,7 +80,6 @@ class NiceMock : public MockClass { internal::ImplicitCast_(this)); } -#if GTEST_LANG_CXX11 // Ideally, we would inherit base class's constructors through a using // declaration, which would preserve their visibility. However, many existing // tests rely on the fact that current implementation reexports protected @@ -101,85 +100,6 @@ class NiceMock : public MockClass { ::testing::Mock::AllowUninterestingCalls( internal::ImplicitCast_(this)); } -#else - // C++98 doesn't have variadic templates, so we have to define one - // for each arity. - template - explicit NiceMock(const A1& a1) : MockClass(a1) { - ::testing::Mock::AllowUninterestingCalls( - internal::ImplicitCast_(this)); - } - template - NiceMock(const A1& a1, const A2& a2) : MockClass(a1, a2) { - ::testing::Mock::AllowUninterestingCalls( - internal::ImplicitCast_(this)); - } - - template - NiceMock(const A1& a1, const A2& a2, const A3& a3) : MockClass(a1, a2, a3) { - ::testing::Mock::AllowUninterestingCalls( - internal::ImplicitCast_(this)); - } - - template - NiceMock(const A1& a1, const A2& a2, const A3& a3, - const A4& a4) : MockClass(a1, a2, a3, a4) { - ::testing::Mock::AllowUninterestingCalls( - internal::ImplicitCast_(this)); - } - - template - NiceMock(const A1& a1, const A2& a2, const A3& a3, const A4& a4, - const A5& a5) : MockClass(a1, a2, a3, a4, a5) { - ::testing::Mock::AllowUninterestingCalls( - internal::ImplicitCast_(this)); - } - - template - NiceMock(const A1& a1, const A2& a2, const A3& a3, const A4& a4, - const A5& a5, const A6& a6) : MockClass(a1, a2, a3, a4, a5, a6) { - ::testing::Mock::AllowUninterestingCalls( - internal::ImplicitCast_(this)); - } - - template - NiceMock(const A1& a1, const A2& a2, const A3& a3, const A4& a4, - const A5& a5, const A6& a6, const A7& a7) : MockClass(a1, a2, a3, a4, a5, - a6, a7) { - ::testing::Mock::AllowUninterestingCalls( - internal::ImplicitCast_(this)); - } - - template - NiceMock(const A1& a1, const A2& a2, const A3& a3, const A4& a4, - const A5& a5, const A6& a6, const A7& a7, const A8& a8) : MockClass(a1, - a2, a3, a4, a5, a6, a7, a8) { - ::testing::Mock::AllowUninterestingCalls( - internal::ImplicitCast_(this)); - } - - template - NiceMock(const A1& a1, const A2& a2, const A3& a3, const A4& a4, - const A5& a5, const A6& a6, const A7& a7, const A8& a8, - const A9& a9) : MockClass(a1, a2, a3, a4, a5, a6, a7, a8, a9) { - ::testing::Mock::AllowUninterestingCalls( - internal::ImplicitCast_(this)); - } - - template - NiceMock(const A1& a1, const A2& a2, const A3& a3, const A4& a4, - const A5& a5, const A6& a6, const A7& a7, const A8& a8, const A9& a9, - const A10& a10) : MockClass(a1, a2, a3, a4, a5, a6, a7, a8, a9, a10) { - ::testing::Mock::AllowUninterestingCalls( - internal::ImplicitCast_(this)); - } - -#endif // GTEST_LANG_CXX11 ~NiceMock() { // NOLINT ::testing::Mock::UnregisterCallReaction( @@ -198,7 +118,6 @@ class NaggyMock : public MockClass { internal::ImplicitCast_(this)); } -#if GTEST_LANG_CXX11 // Ideally, we would inherit base class's constructors through a using // declaration, which would preserve their visibility. However, many existing // tests rely on the fact that current implementation reexports protected @@ -219,85 +138,6 @@ class NaggyMock : public MockClass { ::testing::Mock::WarnUninterestingCalls( internal::ImplicitCast_(this)); } -#else - // C++98 doesn't have variadic templates, so we have to define one - // for each arity. - template - explicit NaggyMock(const A1& a1) : MockClass(a1) { - ::testing::Mock::WarnUninterestingCalls( - internal::ImplicitCast_(this)); - } - template - NaggyMock(const A1& a1, const A2& a2) : MockClass(a1, a2) { - ::testing::Mock::WarnUninterestingCalls( - internal::ImplicitCast_(this)); - } - - template - NaggyMock(const A1& a1, const A2& a2, const A3& a3) : MockClass(a1, a2, a3) { - ::testing::Mock::WarnUninterestingCalls( - internal::ImplicitCast_(this)); - } - - template - NaggyMock(const A1& a1, const A2& a2, const A3& a3, - const A4& a4) : MockClass(a1, a2, a3, a4) { - ::testing::Mock::WarnUninterestingCalls( - internal::ImplicitCast_(this)); - } - - template - NaggyMock(const A1& a1, const A2& a2, const A3& a3, const A4& a4, - const A5& a5) : MockClass(a1, a2, a3, a4, a5) { - ::testing::Mock::WarnUninterestingCalls( - internal::ImplicitCast_(this)); - } - - template - NaggyMock(const A1& a1, const A2& a2, const A3& a3, const A4& a4, - const A5& a5, const A6& a6) : MockClass(a1, a2, a3, a4, a5, a6) { - ::testing::Mock::WarnUninterestingCalls( - internal::ImplicitCast_(this)); - } - - template - NaggyMock(const A1& a1, const A2& a2, const A3& a3, const A4& a4, - const A5& a5, const A6& a6, const A7& a7) : MockClass(a1, a2, a3, a4, a5, - a6, a7) { - ::testing::Mock::WarnUninterestingCalls( - internal::ImplicitCast_(this)); - } - - template - NaggyMock(const A1& a1, const A2& a2, const A3& a3, const A4& a4, - const A5& a5, const A6& a6, const A7& a7, const A8& a8) : MockClass(a1, - a2, a3, a4, a5, a6, a7, a8) { - ::testing::Mock::WarnUninterestingCalls( - internal::ImplicitCast_(this)); - } - - template - NaggyMock(const A1& a1, const A2& a2, const A3& a3, const A4& a4, - const A5& a5, const A6& a6, const A7& a7, const A8& a8, - const A9& a9) : MockClass(a1, a2, a3, a4, a5, a6, a7, a8, a9) { - ::testing::Mock::WarnUninterestingCalls( - internal::ImplicitCast_(this)); - } - - template - NaggyMock(const A1& a1, const A2& a2, const A3& a3, const A4& a4, - const A5& a5, const A6& a6, const A7& a7, const A8& a8, const A9& a9, - const A10& a10) : MockClass(a1, a2, a3, a4, a5, a6, a7, a8, a9, a10) { - ::testing::Mock::WarnUninterestingCalls( - internal::ImplicitCast_(this)); - } - -#endif // GTEST_LANG_CXX11 ~NaggyMock() { // NOLINT ::testing::Mock::UnregisterCallReaction( @@ -316,7 +156,6 @@ class StrictMock : public MockClass { internal::ImplicitCast_(this)); } -#if GTEST_LANG_CXX11 // Ideally, we would inherit base class's constructors through a using // declaration, which would preserve their visibility. However, many existing // tests rely on the fact that current implementation reexports protected @@ -337,85 +176,6 @@ class StrictMock : public MockClass { ::testing::Mock::FailUninterestingCalls( internal::ImplicitCast_(this)); } -#else - // C++98 doesn't have variadic templates, so we have to define one - // for each arity. - template - explicit StrictMock(const A1& a1) : MockClass(a1) { - ::testing::Mock::FailUninterestingCalls( - internal::ImplicitCast_(this)); - } - template - StrictMock(const A1& a1, const A2& a2) : MockClass(a1, a2) { - ::testing::Mock::FailUninterestingCalls( - internal::ImplicitCast_(this)); - } - - template - StrictMock(const A1& a1, const A2& a2, const A3& a3) : MockClass(a1, a2, a3) { - ::testing::Mock::FailUninterestingCalls( - internal::ImplicitCast_(this)); - } - - template - StrictMock(const A1& a1, const A2& a2, const A3& a3, - const A4& a4) : MockClass(a1, a2, a3, a4) { - ::testing::Mock::FailUninterestingCalls( - internal::ImplicitCast_(this)); - } - - template - StrictMock(const A1& a1, const A2& a2, const A3& a3, const A4& a4, - const A5& a5) : MockClass(a1, a2, a3, a4, a5) { - ::testing::Mock::FailUninterestingCalls( - internal::ImplicitCast_(this)); - } - - template - StrictMock(const A1& a1, const A2& a2, const A3& a3, const A4& a4, - const A5& a5, const A6& a6) : MockClass(a1, a2, a3, a4, a5, a6) { - ::testing::Mock::FailUninterestingCalls( - internal::ImplicitCast_(this)); - } - - template - StrictMock(const A1& a1, const A2& a2, const A3& a3, const A4& a4, - const A5& a5, const A6& a6, const A7& a7) : MockClass(a1, a2, a3, a4, a5, - a6, a7) { - ::testing::Mock::FailUninterestingCalls( - internal::ImplicitCast_(this)); - } - - template - StrictMock(const A1& a1, const A2& a2, const A3& a3, const A4& a4, - const A5& a5, const A6& a6, const A7& a7, const A8& a8) : MockClass(a1, - a2, a3, a4, a5, a6, a7, a8) { - ::testing::Mock::FailUninterestingCalls( - internal::ImplicitCast_(this)); - } - - template - StrictMock(const A1& a1, const A2& a2, const A3& a3, const A4& a4, - const A5& a5, const A6& a6, const A7& a7, const A8& a8, - const A9& a9) : MockClass(a1, a2, a3, a4, a5, a6, a7, a8, a9) { - ::testing::Mock::FailUninterestingCalls( - internal::ImplicitCast_(this)); - } - - template - StrictMock(const A1& a1, const A2& a2, const A3& a3, const A4& a4, - const A5& a5, const A6& a6, const A7& a7, const A8& a8, const A9& a9, - const A10& a10) : MockClass(a1, a2, a3, a4, a5, a6, a7, a8, a9, a10) { - ::testing::Mock::FailUninterestingCalls( - internal::ImplicitCast_(this)); - } - -#endif // GTEST_LANG_CXX11 ~StrictMock() { // NOLINT ::testing::Mock::UnregisterCallReaction( diff --git a/googlemock/include/gmock/gmock-generated-nice-strict.h.pump b/googlemock/include/gmock/gmock-generated-nice-strict.h.pump index 024baeda..67160800 100644 --- a/googlemock/include/gmock/gmock-generated-nice-strict.h.pump +++ b/googlemock/include/gmock/gmock-generated-nice-strict.h.pump @@ -92,7 +92,6 @@ class $clazz : public MockClass { internal::ImplicitCast_(this)); } -#if GTEST_LANG_CXX11 // Ideally, we would inherit base class's constructors through a using // declaration, which would preserve their visibility. However, many existing // tests rely on the fact that current implementation reexports protected @@ -113,27 +112,6 @@ class $clazz : public MockClass { ::testing::Mock::$method( internal::ImplicitCast_(this)); } -#else - // C++98 doesn't have variadic templates, so we have to define one - // for each arity. - template - explicit $clazz(const A1& a1) : MockClass(a1) { - ::testing::Mock::$method( - internal::ImplicitCast_(this)); - } - -$range i 2..n -$for i [[ -$range j 1..i - template <$for j, [[typename A$j]]> - $clazz($for j, [[const A$j& a$j]]) : MockClass($for j, [[a$j]]) { - ::testing::Mock::$method( - internal::ImplicitCast_(this)); - } - - -]] -#endif // GTEST_LANG_CXX11 ~$clazz() { // NOLINT ::testing::Mock::UnregisterCallReaction( diff --git a/googlemock/include/gmock/gmock-matchers.h b/googlemock/include/gmock/gmock-matchers.h index be881e14..f9ad3489 100644 --- a/googlemock/include/gmock/gmock-matchers.h +++ b/googlemock/include/gmock/gmock-matchers.h @@ -44,6 +44,7 @@ #include #include +#include #include #include #include @@ -57,10 +58,6 @@ #include "gmock/internal/gmock-port.h" #include "gtest/gtest.h" -#if GTEST_HAS_STD_INITIALIZER_LIST_ -# include // NOLINT -- must be after gtest.h -#endif - GTEST_DISABLE_MSC_WARNINGS_PUSH_( 4251 5046 /* class A needs to have dll-interface to be used by clients of class B */ @@ -194,7 +191,6 @@ class MatcherCastImpl > { // We delegate the matching logic to the source matcher. bool MatchAndExplain(T x, MatchResultListener* listener) const override { -#if GTEST_LANG_CXX11 using FromType = typename std::remove_cv::type>::type>::type; using ToType = typename std::remove_cv > { std::is_same::value || !std::is_base_of::value, "Can't implicitly convert from to "); -#endif // GTEST_LANG_CXX11 return source_matcher_.MatchAndExplain(static_cast(x), listener); } @@ -524,11 +519,7 @@ class IsNullMatcher { template bool MatchAndExplain(const Pointer& p, MatchResultListener* /* listener */) const { -#if GTEST_LANG_CXX11 return p == nullptr; -#else // GTEST_LANG_CXX11 - return GetRawPointer(p) == NULL; -#endif // GTEST_LANG_CXX11 } void DescribeTo(::std::ostream* os) const { *os << "is NULL"; } @@ -544,11 +535,7 @@ class NotNullMatcher { template bool MatchAndExplain(const Pointer& p, MatchResultListener* /* listener */) const { -#if GTEST_LANG_CXX11 return p != nullptr; -#else // GTEST_LANG_CXX11 - return GetRawPointer(p) != NULL; -#endif // GTEST_LANG_CXX11 } void DescribeTo(::std::ostream* os) const { *os << "isn't NULL"; } @@ -1845,14 +1832,8 @@ struct CallableTraits { static void CheckIsValid(Functor /* functor */) {} -#if GTEST_LANG_CXX11 template static auto Invoke(Functor f, T arg) -> decltype(f(arg)) { return f(arg); } -#else - typedef typename Functor::result_type ResultType; - template - static ResultType Invoke(Functor f, T arg) { return f(arg); } -#endif }; // Specialization for function pointers. @@ -1891,12 +1872,8 @@ class ResultOfMatcher { template class Impl : public MatcherInterface { -#if GTEST_LANG_CXX11 using ResultType = decltype(CallableTraits::template Invoke( std::declval(), std::declval())); -#else - typedef typename CallableTraits::ResultType ResultType; -#endif public: template @@ -2027,13 +2004,9 @@ class BeginEndDistanceIsMatcher { bool MatchAndExplain(Container container, MatchResultListener* listener) const override { -#if GTEST_HAS_STD_BEGIN_AND_END_ using std::begin; using std::end; DistanceType distance = std::distance(begin(container), end(container)); -#else - DistanceType distance = std::distance(container.begin(), container.end()); -#endif StringMatchResultListener distance_listener; const bool result = distance_matcher_.MatchAndExplain(distance, &distance_listener); @@ -2497,7 +2470,6 @@ struct Rank1 {}; struct Rank0 : Rank1 {}; namespace pair_getters { -#if GTEST_LANG_CXX11 using std::get; template auto First(T& x, Rank1) -> decltype(get<0>(x)) { // NOLINT @@ -2516,25 +2488,6 @@ template auto Second(T& x, Rank0) -> decltype((x.second)) { // NOLINT return x.second; } -#else -template -typename T::first_type& First(T& x, Rank0) { // NOLINT - return x.first; -} -template -const typename T::first_type& First(const T& x, Rank0) { - return x.first; -} - -template -typename T::second_type& Second(T& x, Rank0) { // NOLINT - return x.second; -} -template -const typename T::second_type& Second(const T& x, Rank0) { - return x.second; -} -#endif // GTEST_LANG_CXX11 } // namespace pair_getters // Implements Key(inner_matcher) for the given argument pair type. @@ -3547,13 +3500,11 @@ ElementsAreArray(const Container& container) { return ElementsAreArray(container.begin(), container.end()); } -#if GTEST_HAS_STD_INITIALIZER_LIST_ template inline internal::ElementsAreArrayMatcher ElementsAreArray(::std::initializer_list xs) { return ElementsAreArray(xs.begin(), xs.end()); } -#endif // UnorderedElementsAreArray(iterator_first, iterator_last) // UnorderedElementsAreArray(pointer, count) @@ -3596,13 +3547,11 @@ UnorderedElementsAreArray(const Container& container) { return UnorderedElementsAreArray(container.begin(), container.end()); } -#if GTEST_HAS_STD_INITIALIZER_LIST_ template inline internal::UnorderedElementsAreArrayMatcher UnorderedElementsAreArray(::std::initializer_list xs) { return UnorderedElementsAreArray(xs.begin(), xs.end()); } -#endif // _ is a matcher that matches anything of any type. // @@ -3790,7 +3739,6 @@ Property(const std::string& property_name, property_name, property, MatcherCast(matcher))); } -#if GTEST_LANG_CXX11 // The same as above but for reference-qualified member functions. template inline PolymorphicMatcher( property_name, property, MatcherCast(matcher))); } -#endif // Creates a matcher that matches an object iff the result of applying // a callable to x matches 'matcher'. @@ -4107,7 +4054,6 @@ Pointwise(const TupleMatcher& tuple_matcher, const Container& rhs) { tuple_matcher, rhs); } -#if GTEST_HAS_STD_INITIALIZER_LIST_ // Supports the Pointwise(m, {a, b, c}) syntax. template @@ -4116,7 +4062,6 @@ inline internal::PointwiseMatcher > Pointwise( return Pointwise(tuple_matcher, std::vector(rhs)); } -#endif // GTEST_HAS_STD_INITIALIZER_LIST_ // UnorderedPointwise(pair_matcher, rhs) matches an STL-style // container or a native array that contains the same number of @@ -4161,7 +4106,6 @@ UnorderedPointwise(const Tuple2Matcher& tuple2_matcher, return UnorderedElementsAreArray(matchers); } -#if GTEST_HAS_STD_INITIALIZER_LIST_ // Supports the UnorderedPointwise(m, {a, b, c}) syntax. template @@ -4172,7 +4116,6 @@ UnorderedPointwise(const Tuple2Matcher& tuple2_matcher, return UnorderedPointwise(tuple2_matcher, std::vector(rhs)); } -#endif // GTEST_HAS_STD_INITIALIZER_LIST_ // Matches an STL-style container or a native array that contains at // least one element matching the given value or matcher. @@ -4252,13 +4195,11 @@ IsSupersetOf(const Container& container) { return IsSupersetOf(container.begin(), container.end()); } -#if GTEST_HAS_STD_INITIALIZER_LIST_ template inline internal::UnorderedElementsAreArrayMatcher IsSupersetOf( ::std::initializer_list xs) { return IsSupersetOf(xs.begin(), xs.end()); } -#endif // IsSubsetOf(iterator_first, iterator_last) // IsSubsetOf(pointer, count) @@ -4311,13 +4252,11 @@ IsSubsetOf(const Container& container) { return IsSubsetOf(container.begin(), container.end()); } -#if GTEST_HAS_STD_INITIALIZER_LIST_ template inline internal::UnorderedElementsAreArrayMatcher IsSubsetOf( ::std::initializer_list xs) { return IsSubsetOf(xs.begin(), xs.end()); } -#endif // Matches an STL-style container or a native array that contains only // elements matching the given value or matcher. diff --git a/googlemock/include/gmock/internal/gmock-internal-utils.h b/googlemock/include/gmock/internal/gmock-internal-utils.h index 7514635e..133fccef 100644 --- a/googlemock/include/gmock/internal/gmock-internal-utils.h +++ b/googlemock/include/gmock/internal/gmock-internal-utils.h @@ -528,7 +528,6 @@ struct BooleanConstant {}; // reduce code size. GTEST_API_ void IllegalDoDefault(const char* file, int line); -#if GTEST_LANG_CXX11 // Helper types for Apply() below. template struct int_pack { typedef int_pack type; }; @@ -554,7 +553,6 @@ auto Apply(F&& f, Tuple&& args) return ApplyImpl(std::forward(f), std::forward(args), make_int_pack::value>()); } -#endif #ifdef _MSC_VER diff --git a/googlemock/test/gmock-actions_test.cc b/googlemock/test/gmock-actions_test.cc index 938a11bf..f27d55aa 100644 --- a/googlemock/test/gmock-actions_test.cc +++ b/googlemock/test/gmock-actions_test.cc @@ -220,7 +220,6 @@ class MyNonDefaultConstructible { int value_; }; -#if GTEST_LANG_CXX11 TEST(BuiltInDefaultValueTest, ExistsForDefaultConstructibleType) { EXPECT_TRUE(BuiltInDefaultValue::Exists()); @@ -230,7 +229,6 @@ TEST(BuiltInDefaultValueTest, IsDefaultConstructedForDefaultConstructibleType) { EXPECT_EQ(42, BuiltInDefaultValue::Get().value()); } -#endif // GTEST_LANG_CXX11 TEST(BuiltInDefaultValueTest, DoesNotExistForNonDefaultConstructibleType) { EXPECT_FALSE(BuiltInDefaultValue::Exists()); @@ -300,7 +298,6 @@ TEST(DefaultValueDeathTest, GetReturnsBuiltInDefaultValueWhenUnset) { }, ""); } -#if GTEST_HAS_STD_UNIQUE_PTR_ TEST(DefaultValueTest, GetWorksForMoveOnlyIfSet) { EXPECT_TRUE(DefaultValue>::Exists()); EXPECT_TRUE(DefaultValue>::Get() == nullptr); @@ -311,7 +308,6 @@ TEST(DefaultValueTest, GetWorksForMoveOnlyIfSet) { std::unique_ptr i = DefaultValue>::Get(); EXPECT_EQ(42, *i); } -#endif // GTEST_HAS_STD_UNIQUE_PTR_ // Tests that DefaultValue::Get() returns void. TEST(DefaultValueTest, GetWorksForVoid) { @@ -643,7 +639,6 @@ TEST(ReturnNullTest, WorksInPointerReturningFunction) { EXPECT_TRUE(a2.Perform(std::make_tuple(true)) == nullptr); } -#if GTEST_HAS_STD_UNIQUE_PTR_ // Tests that ReturnNull() returns NULL for shared_ptr and unique_ptr returning // functions. TEST(ReturnNullTest, WorksInSmartPointerReturningFunction) { @@ -653,7 +648,6 @@ TEST(ReturnNullTest, WorksInSmartPointerReturningFunction) { const Action(std::string)> a2 = ReturnNull(); EXPECT_TRUE(a2.Perform(std::make_tuple("foo")) == nullptr); } -#endif // GTEST_HAS_STD_UNIQUE_PTR_ // Tests that ReturnRef(v) works for reference types. TEST(ReturnRefTest, WorksForReference) { @@ -706,14 +700,12 @@ class MockClass { MOCK_METHOD1(IntFunc, int(bool flag)); // NOLINT MOCK_METHOD0(Foo, MyNonDefaultConstructible()); -#if GTEST_HAS_STD_UNIQUE_PTR_ MOCK_METHOD0(MakeUnique, std::unique_ptr()); MOCK_METHOD0(MakeUniqueBase, std::unique_ptr()); MOCK_METHOD0(MakeVectorUnique, std::vector>()); MOCK_METHOD1(TakeUnique, int(std::unique_ptr)); MOCK_METHOD2(TakeUnique, int(const std::unique_ptr&, std::unique_ptr)); -#endif private: GTEST_DISALLOW_COPY_AND_ASSIGN_(MockClass); @@ -1265,7 +1257,6 @@ TEST(ByRefTest, PrintsCorrectly) { EXPECT_EQ(expected.str(), actual.str()); } -#if GTEST_HAS_STD_UNIQUE_PTR_ std::unique_ptr UniquePtrSource() { return std::unique_ptr(new int(19)); @@ -1378,9 +1369,7 @@ TEST(MockMethodTest, CanTakeMoveOnlyValue) { EXPECT_EQ(42, *saved); } -#endif // GTEST_HAS_STD_UNIQUE_PTR_ -#if GTEST_LANG_CXX11 // Tests for std::function based action. int Add(int val, int& ref, int* ptr) { // NOLINT @@ -1476,7 +1465,6 @@ TEST(MoveOnlyArgumentsTest, ReturningActions) { EXPECT_EQ(x, 3); } -#endif // GTEST_LANG_CXX11 } // Unnamed namespace diff --git a/googlemock/test/gmock-function-mocker_test.cc b/googlemock/test/gmock-function-mocker_test.cc index 007e86c2..294b21d2 100644 --- a/googlemock/test/gmock-function-mocker_test.cc +++ b/googlemock/test/gmock-function-mocker_test.cc @@ -598,7 +598,6 @@ TEST(MockMethodMockFunctionTest, WorksFor10Arguments) { EXPECT_EQ(2, foo.Call(true, 'a', 0, 0, 0, 0, 0, 'b', 1, false)); } -#if GTEST_HAS_STD_FUNCTION_ TEST(MockMethodMockFunctionTest, AsStdFunction) { MockFunction foo; auto call = [](const std::function &f, int i) { @@ -630,7 +629,6 @@ TEST(MockMethodMockFunctionTest, AsStdFunctionWithReferenceParameter) { EXPECT_EQ(-1, call(foo.AsStdFunction(), i)); } -#endif // GTEST_HAS_STD_FUNCTION_ struct MockMethodSizes0 { MOCK_METHOD(void, func, ()); diff --git a/googlemock/test/gmock-generated-function-mockers_test.cc b/googlemock/test/gmock-generated-function-mockers_test.cc index 79130bcf..52d9b8b8 100644 --- a/googlemock/test/gmock-generated-function-mockers_test.cc +++ b/googlemock/test/gmock-generated-function-mockers_test.cc @@ -582,7 +582,6 @@ TEST(MockFunctionTest, WorksFor10Arguments) { EXPECT_EQ(2, foo.Call(true, 'a', 0, 0, 0, 0, 0, 'b', 1, false)); } -#if GTEST_HAS_STD_FUNCTION_ TEST(MockFunctionTest, AsStdFunction) { MockFunction foo; auto call = [](const std::function &f, int i) { @@ -614,7 +613,6 @@ TEST(MockFunctionTest, AsStdFunctionWithReferenceParameter) { EXPECT_EQ(-1, call(foo.AsStdFunction(), i)); } -#endif // GTEST_HAS_STD_FUNCTION_ struct MockMethodSizes0 { MOCK_METHOD0(func, void()); diff --git a/googlemock/test/gmock-generated-matchers_test.cc b/googlemock/test/gmock-generated-matchers_test.cc index 727c8eaa..426e9545 100644 --- a/googlemock/test/gmock-generated-matchers_test.cc +++ b/googlemock/test/gmock-generated-matchers_test.cc @@ -489,7 +489,6 @@ TEST(ElementsAreArrayTest, CanBeCreatedWithVector) { EXPECT_THAT(test_vector, Not(ElementsAreArray(expected))); } -#if GTEST_HAS_STD_INITIALIZER_LIST_ TEST(ElementsAreArrayTest, TakesInitializerList) { const int a[5] = { 1, 2, 3, 4, 5 }; @@ -525,7 +524,6 @@ TEST(ElementsAreArrayTest, { Eq(1), Ne(-2), Ge(3), Le(4), Eq(6) }))); } -#endif // GTEST_HAS_STD_INITIALIZER_LIST_ TEST(ElementsAreArrayTest, CanBeCreatedWithMatcherVector) { const int a[] = { 1, 2, 3 }; @@ -1139,7 +1137,6 @@ TEST(AnyOfTest, DoesNotCallAnyOfUnqualified) { } // namespace adl_test -#if GTEST_LANG_CXX11 TEST(AllOfTest, WorksOnMoveOnlyType) { std::unique_ptr p(new int(3)); @@ -1177,7 +1174,6 @@ TEST(MatcherPMacroTest, WorksOnMoveOnlyType) { EXPECT_THAT(p, Not(UniquePointee(2))); } -#endif // GTEST_LASNG_CXX11 } // namespace diff --git a/googlemock/test/gmock-internal-utils_test.cc b/googlemock/test/gmock-internal-utils_test.cc index 48fcacc7..4c36cfb8 100644 --- a/googlemock/test/gmock-internal-utils_test.cc +++ b/googlemock/test/gmock-internal-utils_test.cc @@ -123,13 +123,9 @@ TEST(ConvertIdentifierNameToWordsTest, WorksWhenNameIsMixture) { } TEST(PointeeOfTest, WorksForSmartPointers) { -#if GTEST_HAS_STD_UNIQUE_PTR_ CompileAssertTypesEqual >::type>(); -#endif // GTEST_HAS_STD_UNIQUE_PTR_ -#if GTEST_HAS_STD_SHARED_PTR_ CompileAssertTypesEqual >::type>(); -#endif // GTEST_HAS_STD_SHARED_PTR_ } TEST(PointeeOfTest, WorksForRawPointers) { @@ -139,16 +135,12 @@ TEST(PointeeOfTest, WorksForRawPointers) { } TEST(GetRawPointerTest, WorksForSmartPointers) { -#if GTEST_HAS_STD_UNIQUE_PTR_ const char* const raw_p1 = new const char('a'); // NOLINT const std::unique_ptr p1(raw_p1); EXPECT_EQ(raw_p1, GetRawPointer(p1)); -#endif // GTEST_HAS_STD_UNIQUE_PTR_ -#if GTEST_HAS_STD_SHARED_PTR_ double* const raw_p2 = new double(2.5); // NOLINT const std::shared_ptr p2(raw_p2); EXPECT_EQ(raw_p2, GetRawPointer(p2)); -#endif // GTEST_HAS_STD_SHARED_PTR_ } TEST(GetRawPointerTest, WorksForRawPointers) { diff --git a/googlemock/test/gmock-matchers_test.cc b/googlemock/test/gmock-matchers_test.cc index a7221877..03fa75b1 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 #include @@ -56,20 +57,13 @@ #include #include #include +#include #include #include #include "gmock/gmock.h" #include "gtest/gtest.h" #include "gtest/gtest-spi.h" -#if GTEST_HAS_STD_FORWARD_LIST_ -# include // NOLINT -#endif - -#if GTEST_LANG_CXX11 -# include -#endif - namespace testing { namespace gmock_matchers_test { namespace { @@ -1189,14 +1183,12 @@ TEST(IsNullTest, MatchesNullPointer) { #endif } -#if GTEST_LANG_CXX11 TEST(IsNullTest, StdFunction) { const Matcher> m = IsNull(); EXPECT_TRUE(m.Matches(std::function())); EXPECT_FALSE(m.Matches([]{})); } -#endif // GTEST_LANG_CXX11 // Tests that IsNull() describes itself properly. TEST(IsNullTest, CanDescribeSelf) { @@ -1237,14 +1229,12 @@ TEST(NotNullTest, ReferenceToConstLinkedPtr) { EXPECT_TRUE(m.Matches(non_null_p)); } -#if GTEST_LANG_CXX11 TEST(NotNullTest, StdFunction) { const Matcher> m = NotNull(); EXPECT_TRUE(m.Matches([]{})); EXPECT_FALSE(m.Matches(std::function())); } -#endif // GTEST_LANG_CXX11 // Tests that NotNull() describes itself properly. TEST(NotNullTest, CanDescribeSelf) { @@ -1527,7 +1517,6 @@ TEST(KeyTest, MatchesCorrectly) { EXPECT_THAT(p, Not(Key(Lt(25)))); } -#if GTEST_LANG_CXX11 template struct Tag {}; @@ -1554,7 +1543,6 @@ TEST(PairTest, MatchesPairWithGetCorrectly) { std::vector v = {{11, "Foo"}, {29, "gMockIsBestMock"}}; EXPECT_THAT(v, Contains(Key(29))); } -#endif // GTEST_LANG_CXX11 TEST(KeyTest, SafelyCastsInnerMatcher) { Matcher is_positive = Gt(0); @@ -1699,7 +1687,6 @@ TEST(ContainsTest, WorksWithMoveOnly) { helper.Call(MakeUniquePtrs({1, 2})); } -#if GTEST_LANG_CXX11 TEST(PairTest, UseGetInsteadOfMembers) { PairWithGet pair{7, "ABC"}; EXPECT_THAT(pair, Pair(7, "ABC")); @@ -1709,7 +1696,6 @@ TEST(PairTest, UseGetInsteadOfMembers) { std::vector v = {{11, "Foo"}, {29, "gMockIsBestMock"}}; EXPECT_THAT(v, ElementsAre(Pair(11, string("Foo")), Pair(Ge(10), Not("")))); } -#endif // GTEST_LANG_CXX11 // Tests StartsWith(s). @@ -2680,7 +2666,6 @@ static void AnyOfMatches(int num, const Matcher& m) { EXPECT_FALSE(m.Matches(num + 1)); } -#if GTEST_LANG_CXX11 static void AnyOfStringMatches(int num, const Matcher& m) { SCOPED_TRACE(Describe(m)); EXPECT_FALSE(m.Matches(std::to_string(0))); @@ -2690,7 +2675,6 @@ static void AnyOfStringMatches(int num, const Matcher& m) { } EXPECT_FALSE(m.Matches(std::to_string(num + 1))); } -#endif // Tests that AnyOf(m1, ..., mn) matches any value that matches at // least one of the given matchers. @@ -2735,7 +2719,6 @@ TEST(AnyOfTest, MatchesWhenAnyMatches) { AnyOfMatches(10, AnyOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)); } -#if GTEST_LANG_CXX11 // Tests the variadic version of the AnyOfMatcher. TEST(AnyOfTest, VariadicMatchesWhenAnyMatches) { // Also make sure AnyOf is defined in the right namespace and does not depend @@ -2784,7 +2767,6 @@ TEST(ElementsAreTest, HugeMatcherUnordered) { Eq(3), Eq(9), Eq(12), Eq(11), Ne(122))); } -#endif // GTEST_LANG_CXX11 // Tests that AnyOf(m1, ..., mn) describes itself properly. TEST(AnyOfTest, CanDescribeSelf) { @@ -4155,9 +4137,7 @@ class AClass { // A getter that returns a reference to const. const std::string& s() const { return s_; } -#if GTEST_LANG_CXX11 const std::string& s_ref() const & { return s_; } -#endif void set_s(const std::string& new_s) { s_ = new_s; } @@ -4214,7 +4194,6 @@ TEST(PropertyTest, WorksForReferenceToConstProperty) { EXPECT_FALSE(m_with_name.Matches(a)); } -#if GTEST_LANG_CXX11 // Tests that Property(&Foo::property, ...) works when property() is // ref-qualified. TEST(PropertyTest, WorksForRefQualifiedProperty) { @@ -4231,7 +4210,6 @@ TEST(PropertyTest, WorksForRefQualifiedProperty) { EXPECT_FALSE(m.Matches(a)); EXPECT_FALSE(m_with_name.Matches(a)); } -#endif // Tests that Property(&Foo::property, ...) works when property() // returns a reference to non-const. @@ -4594,7 +4572,6 @@ TEST(ResultOfTest, WorksForPolymorphicFunctors) { EXPECT_FALSE(matcher_string.Matches("shrt")); } -#if GTEST_LANG_CXX11 TEST(ResultOfTest, WorksForPolymorphicFunctorsIgnoringResultType) { Matcher matcher = ResultOf(PolymorphicFunctor(), "good ptr"); @@ -4609,7 +4586,6 @@ TEST(ResultOfTest, WorksForLambdas) { EXPECT_TRUE(matcher.Matches(3)); EXPECT_FALSE(matcher.Matches(1)); } -#endif const int* ReferencingFunction(const int& n) { return &n; } @@ -4800,7 +4776,6 @@ TEST(IsTrueTest, IsTrueIsFalse) { EXPECT_THAT(&a, Not(IsFalse())); EXPECT_THAT(false, Not(IsTrue())); EXPECT_THAT(true, Not(IsFalse())); -#if GTEST_LANG_CXX11 EXPECT_THAT(std::true_type(), IsTrue()); EXPECT_THAT(std::true_type(), Not(IsFalse())); EXPECT_THAT(std::false_type(), IsFalse()); @@ -4813,7 +4788,6 @@ TEST(IsTrueTest, IsTrueIsFalse) { EXPECT_THAT(null_unique, IsFalse()); EXPECT_THAT(nonnull_unique, IsTrue()); EXPECT_THAT(nonnull_unique, Not(IsFalse())); -#endif // GTEST_LANG_CXX11 } TEST(SizeIsTest, ImplementsSizeIs) { @@ -5313,7 +5287,6 @@ TEST(StreamlikeTest, Iteration) { } } -#if GTEST_HAS_STD_FORWARD_LIST_ TEST(BeginEndDistanceIsTest, WorksWithForwardList) { std::forward_list container; EXPECT_THAT(container, BeginEndDistanceIs(0)); @@ -5325,7 +5298,6 @@ TEST(BeginEndDistanceIsTest, WorksWithForwardList) { EXPECT_THAT(container, Not(BeginEndDistanceIs(0))); EXPECT_THAT(container, BeginEndDistanceIs(2)); } -#endif // GTEST_HAS_STD_FORWARD_LIST_ TEST(BeginEndDistanceIsTest, WorksWithNonStdList) { const int a[5] = {1, 2, 3, 4, 5}; @@ -5507,13 +5479,11 @@ TEST(IsSupersetOfTest, MatchAndExplain) { " - element #2 is matched by matcher #0")); } -#if GTEST_HAS_STD_INITIALIZER_LIST_ TEST(IsSupersetOfTest, WorksForRhsInitializerList) { const int numbers[] = {1, 3, 6, 2, 4, 5}; EXPECT_THAT(numbers, IsSupersetOf({1, 2})); EXPECT_THAT(numbers, Not(IsSupersetOf({3, 0}))); } -#endif TEST(IsSupersetOfTest, WorksWithMoveOnly) { ContainerHelper helper; @@ -5637,13 +5607,11 @@ TEST(IsSubsetOfTest, MatchAndExplain) { " - element #1 is matched by matcher #2")); } -#if GTEST_HAS_STD_INITIALIZER_LIST_ TEST(IsSubsetOfTest, WorksForRhsInitializerList) { const int numbers[] = {1, 2, 3}; EXPECT_THAT(numbers, IsSubsetOf({1, 2, 3, 4})); EXPECT_THAT(numbers, Not(IsSubsetOf({1, 2}))); } -#endif TEST(IsSubsetOfTest, WorksWithMoveOnly) { ContainerHelper helper; @@ -5762,7 +5730,6 @@ TEST(UnorderedElementsAreArrayTest, TakesStlContainer) { EXPECT_THAT(actual, Not(UnorderedElementsAreArray(expected))); } -#if GTEST_HAS_STD_INITIALIZER_LIST_ TEST(UnorderedElementsAreArrayTest, TakesInitializerList) { const int a[5] = {2, 1, 4, 5, 3}; @@ -5796,7 +5763,6 @@ TEST(UnorderedElementsAreArrayTest, {Eq(1), Ne(-2), Ge(3), Le(4), Eq(6)}))); } -#endif // GTEST_HAS_STD_INITIALIZER_LIST_ TEST(UnorderedElementsAreArrayTest, WorksWithMoveOnly) { ContainerHelper helper; @@ -6501,7 +6467,6 @@ TEST(PointwiseTest, WorksForVectorOfBool) { EXPECT_THAT(lhs, Not(Pointwise(Eq(), rhs))); } -#if GTEST_HAS_STD_INITIALIZER_LIST_ TEST(PointwiseTest, WorksForRhsInitializerList) { const vector lhs{2, 4, 6}; @@ -6509,7 +6474,6 @@ TEST(PointwiseTest, WorksForRhsInitializerList) { EXPECT_THAT(lhs, Not(Pointwise(Lt(), {3, 3, 7}))); } -#endif // GTEST_HAS_STD_INITIALIZER_LIST_ TEST(PointwiseTest, RejectsWrongSize) { const double lhs[2] = {1, 2}; @@ -6623,7 +6587,6 @@ TEST(UnorderedPointwiseTest, WorksForRhsNativeArray) { EXPECT_THAT(lhs, Not(UnorderedPointwise(Lt(), rhs))); } -#if GTEST_HAS_STD_INITIALIZER_LIST_ TEST(UnorderedPointwiseTest, WorksForRhsInitializerList) { const vector lhs{2, 4, 6}; @@ -6631,7 +6594,6 @@ TEST(UnorderedPointwiseTest, WorksForRhsInitializerList) { EXPECT_THAT(lhs, Not(UnorderedPointwise(Lt(), {1, 1, 7}))); } -#endif // GTEST_HAS_STD_INITIALIZER_LIST_ TEST(UnorderedPointwiseTest, RejectsWrongSize) { const double lhs[2] = {1, 2}; @@ -6824,7 +6786,6 @@ TEST(AnyWithTest, TestBadCastType) { EXPECT_FALSE(m.Matches(SampleAnyType(1))); } -#if GTEST_LANG_CXX11 TEST(AnyWithTest, TestUseInContainers) { std::vector a; a.emplace_back(1); @@ -6841,7 +6802,6 @@ TEST(AnyWithTest, TestUseInContainers) { AnyWith("merhaba"), AnyWith("salut")})); } -#endif // GTEST_LANG_CXX11 TEST(AnyWithTest, TestCompare) { EXPECT_THAT(SampleAnyType(1), AnyWith(Gt(0))); } diff --git a/googlemock/test/gmock-nice-strict_test.cc b/googlemock/test/gmock-nice-strict_test.cc index d00f4536..5f8f9617 100644 --- a/googlemock/test/gmock-nice-strict_test.cc +++ b/googlemock/test/gmock-nice-strict_test.cc @@ -114,23 +114,22 @@ class MockBar { GTEST_DISALLOW_COPY_AND_ASSIGN_(MockBar); }; -#if GTEST_GTEST_LANG_CXX11 class MockBaz { public: class MoveOnly { + public: MoveOnly() = default; MoveOnly(const MoveOnly&) = delete; - operator=(const MoveOnly&) = delete; + MoveOnly& operator=(const MoveOnly&) = delete; MoveOnly(MoveOnly&&) = default; - operator=(MoveOnly&&) = default; + MoveOnly& operator=(MoveOnly&&) = default; }; MockBaz(MoveOnly) {} -} -#endif // GTEST_GTEST_LANG_CXX11 && GTEST_HAS_STD_MOVE_ +}; #if GTEST_HAS_STREAM_REDIRECTION @@ -292,14 +291,10 @@ TEST(NiceMockTest, AllowLeak) { leaked->DoThis(); } -#if GTEST_GTEST_LANG_CXX11 && GTEST_HAS_STD_MOVE_ - TEST(NiceMockTest, MoveOnlyConstructor) { - NiceMock nice_baz(MockBaz::MoveOnly()); + NiceMock nice_baz(MockBaz::MoveOnly{}); } -#endif // GTEST_LANG_CXX11 && GTEST_HAS_STD_MOVE_ - #if !GTEST_OS_SYMBIAN && !GTEST_OS_WINDOWS_MOBILE // Tests that NiceMock compiles where Mock is a user-defined // class (as opposed to ::testing::Mock). We had to work around an @@ -407,14 +402,10 @@ TEST(NaggyMockTest, AllowLeak) { leaked->DoThis(); } -#if GTEST_GTEST_LANG_CXX11 && GTEST_HAS_STD_MOVE_ - TEST(NaggyMockTest, MoveOnlyConstructor) { - NaggyMock naggy_baz(MockBaz::MoveOnly()); + NaggyMock naggy_baz(MockBaz::MoveOnly{}); } -#endif // GTEST_LANG_CXX11 && GTEST_HAS_STD_MOVE_ - #if !GTEST_OS_SYMBIAN && !GTEST_OS_WINDOWS_MOBILE // Tests that NaggyMock compiles where Mock is a user-defined // class (as opposed to ::testing::Mock). We had to work around an @@ -503,14 +494,10 @@ TEST(StrictMockTest, AllowLeak) { leaked->DoThis(); } -#if GTEST_GTEST_LANG_CXX11 && GTEST_HAS_STD_MOVE_ - TEST(StrictMockTest, MoveOnlyConstructor) { - StrictMock strict_baz(MockBaz::MoveOnly()); + StrictMock strict_baz(MockBaz::MoveOnly{}); } -#endif // GTEST_LANG_CXX11 && GTEST_HAS_STD_MOVE_ - #if !GTEST_OS_SYMBIAN && !GTEST_OS_WINDOWS_MOBILE // Tests that StrictMock compiles where Mock is a user-defined // class (as opposed to ::testing::Mock). We had to work around an diff --git a/googletest/include/gtest/internal/gtest-port.h b/googletest/include/gtest/internal/gtest-port.h index 0637a23a..97532666 100644 --- a/googletest/include/gtest/internal/gtest-port.h +++ b/googletest/include/gtest/internal/gtest-port.h @@ -92,8 +92,6 @@ // - Define it to 1/0 to indicate whether the // platform supports I/O stream redirection using // dup() and dup2(). -// GTEST_LANG_CXX11 - Define it to 1/0 to indicate that Google Test -// is building in C++11/C++98 mode. // GTEST_LINKED_AS_SHARED_LIBRARY // - Define to 1 when compiling tests that use // Google Test as a shared library (known as @@ -332,44 +330,6 @@ GTEST_DISABLE_MSC_WARNINGS_POP_() #endif -#define GTEST_LANG_CXX11 1 - -// Distinct from C++11 language support, some environments don't provide -// proper C++11 library support. Notably, it's possible to build in -// C++11 mode when targeting Mac OS X 10.6, which has an old libstdc++ -// with no C++11 support. -// -// libstdc++ has sufficient C++11 support as of GCC 4.6.0, __GLIBCXX__ -// 20110325, but maintenance releases in the 4.4 and 4.5 series followed -// this date, so check for those versions by their date stamps. -// https://gcc.gnu.org/onlinedocs/libstdc++/manual/abi.html#abi.versioning -#if GTEST_LANG_CXX11 && \ - (!defined(__GLIBCXX__) || ( \ - __GLIBCXX__ >= 20110325ul && /* GCC >= 4.6.0 */ \ - /* Blacklist of patch releases of older branches: */ \ - __GLIBCXX__ != 20110416ul && /* GCC 4.4.6 */ \ - __GLIBCXX__ != 20120313ul && /* GCC 4.4.7 */ \ - __GLIBCXX__ != 20110428ul && /* GCC 4.5.3 */ \ - __GLIBCXX__ != 20120702ul)) /* GCC 4.5.4 */ -# define GTEST_STDLIB_CXX11 1 -#endif - -// Only use C++11 library features if the library provides them. -#if GTEST_STDLIB_CXX11 -# define GTEST_HAS_STD_BEGIN_AND_END_ 1 -# define GTEST_HAS_STD_FORWARD_LIST_ 1 -# if !defined(_MSC_VER) || (_MSC_FULL_VER >= 190023824) -// works only with VS2015U2 and better -# define GTEST_HAS_STD_FUNCTION_ 1 -# endif -# define GTEST_HAS_STD_INITIALIZER_LIST_ 1 -# define GTEST_HAS_STD_MOVE_ 1 -# define GTEST_HAS_STD_UNIQUE_PTR_ 1 -# define GTEST_HAS_STD_SHARED_PTR_ 1 -# define GTEST_HAS_UNORDERED_MAP_ 1 -# define GTEST_HAS_UNORDERED_SET_ 1 -#endif - // Brings in definitions for functions used in the testing::internal::posix // namespace (read, write, close, chdir, isatty, stat). We do not currently // use them on Windows Mobile. @@ -712,12 +672,6 @@ typedef struct _RTL_CRITICAL_SECTION GTEST_CRITICAL_SECTION; # define GTEST_ATTRIBUTE_UNUSED_ #endif -#if GTEST_LANG_CXX11 -# define GTEST_CXX11_EQUALS_DELETE_ = delete -#else // GTEST_LANG_CXX11 -# define GTEST_CXX11_EQUALS_DELETE_ -#endif // GTEST_LANG_CXX11 - // Use this annotation before a function that takes a printf format string. #if (defined(__GNUC__) || defined(__clang__)) && !defined(COMPILER_ICC) # if defined(__MINGW_PRINTF_FORMAT) @@ -739,12 +693,12 @@ typedef struct _RTL_CRITICAL_SECTION GTEST_CRITICAL_SECTION; // A macro to disallow operator= // This should be used in the private: declarations for a class. #define GTEST_DISALLOW_ASSIGN_(type) \ - void operator=(type const &) GTEST_CXX11_EQUALS_DELETE_ + void operator=(type const &) = delete // A macro to disallow copy constructor and operator= // This should be used in the private: declarations for a class. #define GTEST_DISALLOW_COPY_AND_ASSIGN_(type) \ - type(type const &) GTEST_CXX11_EQUALS_DELETE_; \ + type(type const &) = delete; \ GTEST_DISALLOW_ASSIGN_(type) // Tell the compiler to warn about unused return values for functions declared @@ -893,75 +847,16 @@ namespace internal { // Secret object, which is what we want. class Secret; -// The GTEST_COMPILE_ASSERT_ macro can be used to verify that a compile time -// expression is true. For example, you could use it to verify the -// size of a static array: +// The GTEST_COMPILE_ASSERT_ is a legacy macro used to verify that a compile +// time expression is true (in new code, use static_assert instead). For +// example, you could use it to verify the size of a static array: // // GTEST_COMPILE_ASSERT_(GTEST_ARRAY_SIZE_(names) == NUM_NAMES, // names_incorrect_size); // -// or to make sure a struct is smaller than a certain size: -// -// GTEST_COMPILE_ASSERT_(sizeof(foo) < 128, foo_too_large); -// -// The second argument to the macro is the name of the variable. If -// the expression is false, most compilers will issue a warning/error -// containing the name of the variable. - -#if GTEST_LANG_CXX11 -# define GTEST_COMPILE_ASSERT_(expr, msg) static_assert(expr, #msg) -#else // !GTEST_LANG_CXX11 -template - struct CompileAssert { -}; - -# define GTEST_COMPILE_ASSERT_(expr, msg) \ - typedef ::testing::internal::CompileAssert<(static_cast(expr))> \ - msg[static_cast(expr) ? 1 : -1] GTEST_ATTRIBUTE_UNUSED_ -#endif // !GTEST_LANG_CXX11 - -// Implementation details of GTEST_COMPILE_ASSERT_: -// -// (In C++11, we simply use static_assert instead of the following) -// -// - GTEST_COMPILE_ASSERT_ works by defining an array type that has -1 -// elements (and thus is invalid) when the expression is false. -// -// - The simpler definition -// -// #define GTEST_COMPILE_ASSERT_(expr, msg) typedef char msg[(expr) ? 1 : -1] -// -// does not work, as gcc supports variable-length arrays whose sizes -// are determined at run-time (this is gcc's extension and not part -// of the C++ standard). As a result, gcc fails to reject the -// following code with the simple definition: -// -// int foo; -// GTEST_COMPILE_ASSERT_(foo, msg); // not supposed to compile as foo is -// // not a compile-time constant. -// -// - By using the type CompileAssert<(bool(expr))>, we ensures that -// expr is a compile-time constant. (Template arguments must be -// determined at compile-time.) -// -// - The outter parentheses in CompileAssert<(bool(expr))> are necessary -// to work around a bug in gcc 3.4.4 and 4.0.1. If we had written -// -// CompileAssert -// -// instead, these compilers will refuse to compile -// -// GTEST_COMPILE_ASSERT_(5 > 0, some_message); -// -// (They seem to think the ">" in "5 > 0" marks the end of the -// template argument list.) -// -// - The array size is (bool(expr) ? 1 : -1), instead of simply -// -// ((expr) ? 1 : -1). -// -// This is to avoid running into a bug in MS VC 7.1, which -// causes ((0.0) ? 1 : -1) to incorrectly evaluate to 1. +// The second argument to the macro must be a valid C++ identifier. If the +// expression is false, compiler will issue an error containing this identifier. +#define GTEST_COMPILE_ASSERT_(expr, msg) static_assert(expr, #msg) // StaticAssertTypeEqHelper is used by StaticAssertTypeEq defined in gtest.h. // diff --git a/googletest/test/googletest-printers-test.cc b/googletest/test/googletest-printers-test.cc index ed66fa2e..139b3e49 100644 --- a/googletest/test/googletest-printers-test.cc +++ b/googletest/test/googletest-printers-test.cc @@ -37,29 +37,20 @@ #include #include #include +#include #include #include #include #include #include +#include +#include #include #include #include "gtest/gtest-printers.h" #include "gtest/gtest.h" -#if GTEST_HAS_UNORDERED_MAP_ -# include // NOLINT -#endif // GTEST_HAS_UNORDERED_MAP_ - -#if GTEST_HAS_UNORDERED_SET_ -# include // NOLINT -#endif // GTEST_HAS_UNORDERED_SET_ - -#if GTEST_HAS_STD_FORWARD_LIST_ -# include // NOLINT -#endif // GTEST_HAS_STD_FORWARD_LIST_ - // Some user-defined types for testing the universal value printer. // An anonymous enum type. @@ -814,7 +805,6 @@ TEST(PrintStlContainerTest, NonEmptyDeque) { EXPECT_EQ("{ 1, 3 }", Print(non_empty)); } -#if GTEST_HAS_UNORDERED_MAP_ TEST(PrintStlContainerTest, OneElementHashMap) { ::std::unordered_map map1; @@ -834,9 +824,7 @@ TEST(PrintStlContainerTest, HashMultiMap) { << " where Print(map1) returns \"" << result << "\"."; } -#endif // GTEST_HAS_UNORDERED_MAP_ -#if GTEST_HAS_UNORDERED_SET_ TEST(PrintStlContainerTest, HashSet) { ::std::unordered_set set1; @@ -873,7 +861,6 @@ TEST(PrintStlContainerTest, HashMultiSet) { EXPECT_TRUE(std::equal(a, a + kSize, numbers.begin())); } -#endif // GTEST_HAS_UNORDERED_SET_ TEST(PrintStlContainerTest, List) { const std::string a[] = {"hello", "world"}; @@ -915,14 +902,12 @@ TEST(PrintStlContainerTest, MultiSet) { EXPECT_EQ("{ 1, 1, 1, 2, 5 }", Print(set1)); } -#if GTEST_HAS_STD_FORWARD_LIST_ TEST(PrintStlContainerTest, SinglyLinkedList) { int a[] = { 9, 2, 8 }; const std::forward_list ints(a, a + 3); EXPECT_EQ("{ 9, 2, 8 }", Print(ints)); } -#endif // GTEST_HAS_STD_FORWARD_LIST_ TEST(PrintStlContainerTest, Pair) { pair p(true, 5); -- cgit v1.2.3 From 9494c45e75a55547f3f183a1161fbd39d29b994e Mon Sep 17 00:00:00 2001 From: Abseil Team Date: Wed, 19 Dec 2018 03:16:02 -0500 Subject: Googletest export Use std::function to implement type erasure in Action, wrapping the legacy ActionInterface if necessary. This makes functors / std::function the primary way to implement Action; the existing ActionInterface implementations are handled through ActionAdaptor. The existing actions are not (yet) migrated though; they'll pay the cost of one additional indirection - but that should be negligible. PiperOrigin-RevId: 226126137 --- googlemock/include/gmock/gmock-actions.h | 76 +++++++++----------------------- 1 file changed, 20 insertions(+), 56 deletions(-) diff --git a/googlemock/include/gmock/gmock-actions.h b/googlemock/include/gmock/gmock-actions.h index 4fd3400f..8b3c03b0 100644 --- a/googlemock/include/gmock/gmock-actions.h +++ b/googlemock/include/gmock/gmock-actions.h @@ -69,9 +69,6 @@ namespace testing { namespace internal { -template -class ActionAdaptor; - // BuiltInDefaultValueGetter::Get() returns a // default-constructed T value. BuiltInDefaultValueGetter::Get() crashes with an error. @@ -342,6 +339,19 @@ class ActionInterface { // object as a handle to it. template class Action { + // Adapter class to allow constructing Action from a legacy ActionInterface. + // New code should create Actions from functors instead. + struct ActionAdapter { + // Adapter must be copyable to satisfy std::function requirements. + ::std::shared_ptr> impl_; + + template + typename internal::Function::Result operator()(Args&&... args) { + return impl_->Perform( + ::std::forward_as_tuple(::std::forward(args)...)); + } + }; + public: typedef typename internal::Function::Result Result; typedef typename internal::Function::ArgumentTuple ArgumentTuple; @@ -359,19 +369,17 @@ class Action { Action(G&& fun) : fun_(::std::forward(fun)) {} // NOLINT // Constructs an Action from its implementation. - explicit Action(ActionInterface* impl) : impl_(impl) {} + explicit Action(ActionInterface* impl) + : fun_(ActionAdapter{::std::shared_ptr>(impl)}) {} // This constructor allows us to turn an Action object into an // Action, as long as F's arguments can be implicitly converted - // to Func's and Func's return type can be implicitly converted to - // F's. + // to Func's and Func's return type can be implicitly converted to F's. template - explicit Action(const Action& action); + explicit Action(const Action& action) : fun_(action.fun_) {} // Returns true iff this is the DoDefault() action. - bool IsDoDefault() const { - return impl_ == nullptr && fun_ == nullptr; - } + bool IsDoDefault() const { return fun_ == nullptr; } // Performs the action. Note that this method is const even though // the corresponding method in ActionInterface is not. The reason @@ -383,25 +391,15 @@ class Action { if (IsDoDefault()) { internal::IllegalDoDefault(__FILE__, __LINE__); } - if (fun_ != nullptr) { - return internal::Apply(fun_, ::std::move(args)); - } - return impl_->Perform(args); + return internal::Apply(fun_, ::std::move(args)); } private: - template - friend class internal::ActionAdaptor; - template friend class Action; - // Action can be implemented either as a generic functor (via std::function), - // or legacy ActionInterface. The invariant is that at most one of fun_ and - // impl_ may be nonnull; both are null iff this is the default action. - // FIXME: Fold the ActionInterface into std::function. + // fun_ is an empty function iff this is the DoDefault() action. ::std::function fun_; - ::std::shared_ptr> impl_; }; // The PolymorphicAction class template makes it easy to implement a @@ -480,26 +478,6 @@ inline PolymorphicAction MakePolymorphicAction(const Impl& impl) { namespace internal { -// Allows an Action object to pose as an Action, as long as F2 -// and F1 are compatible. -template -class ActionAdaptor : public ActionInterface { - public: - typedef typename internal::Function::Result Result; - typedef typename internal::Function::ArgumentTuple ArgumentTuple; - - explicit ActionAdaptor(const Action& from) : impl_(from.impl_) {} - - Result Perform(const ArgumentTuple& args) override { - return impl_->Perform(args); - } - - private: - const std::shared_ptr> impl_; - - GTEST_DISALLOW_ASSIGN_(ActionAdaptor); -}; - // Helper struct to specialize ReturnAction to execute a move instead of a copy // on return. Useful for move-only types, but could be used on any type. template @@ -1066,20 +1044,6 @@ struct DoAllAction { // EXPECT_CALL(mock, Bar(5, _, _)).WillOnce(Invoke(DistanceToOrigin)); typedef internal::IgnoredValue Unused; -// This constructor allows us to turn an Action object into an -// Action, as long as To's arguments can be implicitly converted -// to From's and From's return type cann be implicitly converted to -// To's. -template -template -Action::Action(const Action& from) - : - fun_(from.fun_), - impl_(from.impl_ == nullptr - ? nullptr - : new internal::ActionAdaptor(from)) { -} - // Creates an action that does actions a1, a2, ..., sequentially in // each invocation. template -- cgit v1.2.3 From a83cc11abe4856a60d92ceba2d65af8236cc3500 Mon Sep 17 00:00:00 2001 From: Abseil Team Date: Thu, 20 Dec 2018 12:54:19 -0500 Subject: Googletest export Add public entry point testing::RegisterTest. PiperOrigin-RevId: 226350937 --- googletest/include/gtest/gtest.h | 86 ++++++++++++++++++++ .../test/googletest-output-test-golden-lin.txt | 91 ++++++++++++++++++++-- googletest/test/googletest-output-test_.cc | 50 ++++++++++++ googletest/test/gtest_unittest.cc | 27 +++++++ 4 files changed, 249 insertions(+), 5 deletions(-) diff --git a/googletest/include/gtest/gtest.h b/googletest/include/gtest/gtest.h index 5def00b1..cefa564c 100644 --- a/googletest/include/gtest/gtest.h +++ b/googletest/include/gtest/gtest.h @@ -2354,6 +2354,92 @@ GTEST_API_ std::string TempDir(); # pragma warning(pop) #endif +// Dynamically registers a test with the framework. +// +// This is an advanced API only to be used when the `TEST` macros are +// insufficient. The macros should be preferred when possible, as they avoid +// most of the complexity of calling this function. +// +// The `factory` argument is a factory callable (move-constructible) object or +// function pointer that creates a new instance of the Test object. It +// handles ownership to the caller. The signature of the callable is +// `Fixture*()`, where `Fixture` is the test fixture class for the test. All +// tests registered with the same `test_case_name` must return the same +// fixture type. This is checked at runtime. +// +// The framework will infer the fixture class from the factory and will call +// the `SetUpTestCase` and `TearDownTestCase` for it. +// +// Must be called before `RUN_ALL_TESTS()` is invoked, otherwise behavior is +// undefined. +// +// Use case example: +// +// class MyFixture : public ::testing::Test { +// public: +// // All of these optional, just like in regular macro usage. +// static void SetUpTestCase() { ... } +// static void TearDownTestCase() { ... } +// void SetUp() override { ... } +// void TearDown() override { ... } +// }; +// +// class MyTest : public MyFixture { +// public: +// explicit MyTest(int data) : data_(data) {} +// void TestBody() override { ... } +// +// private: +// int data_; +// }; +// +// void RegisterMyTests(const std::vector& values) { +// for (int v : values) { +// ::testing::RegisterTest( +// "MyFixture", ("Test" + std::to_string(v)).c_str(), nullptr, +// std::to_string(v).c_str(), +// __FILE__, __LINE__, +// // Important to use the fixture type as the return type here. +// [=]() -> MyFixture* { return new MyTest(v); }); +// } +// } +// ... +// int main(int argc, char** argv) { +// std::vector values_to_test = LoadValuesFromConfig(); +// RegisterMyTests(values_to_test); +// ... +// return RUN_ALL_TESTS(); +// } +// +template +TestInfo* RegisterTest(const char* test_case_name, const char* test_name, + const char* type_param, const char* value_param, + const char* file, int line, Factory factory) { + using TestT = typename std::remove_pointer::type; + + // Helper class to get SetUpTestCase and TearDownTestCase when they are in a + // protected scope. + struct Helper : TestT { + using TestT::SetUpTestCase; + using TestT::TearDownTestCase; + }; + + class FactoryImpl : public internal::TestFactoryBase { + public: + explicit FactoryImpl(Factory f) : factory_(std::move(f)) {} + Test* CreateTest() override { return factory_(); } + + private: + Factory factory_; + }; + + return internal::MakeAndRegisterTestInfo( + test_case_name, test_name, type_param, value_param, + internal::CodeLocation(file, line), internal::GetTypeId(), + &Helper::SetUpTestCase, &Helper::TearDownTestCase, + new FactoryImpl{std::move(factory)}); +} + } // namespace testing // Use this function in main() to run all tests. It returns 0 if all diff --git a/googletest/test/googletest-output-test-golden-lin.txt b/googletest/test/googletest-output-test-golden-lin.txt index 86da845b..89a38e9e 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 76 tests from 34 test cases. +[==========] Running 83 tests from 38 test cases. [----------] Global test environment set-up. FooEnvironment::SetUp() called. BarEnvironment::SetUp() called. @@ -870,6 +870,84 @@ Expected non-fatal failure. Stack trace: (omitted) [ FAILED ] ScopedFakeTestPartResultReporterTest.InterceptOnlyCurrentThread +[----------] 2 tests from DynamicFixture +DynamicFixture::SetUpTestCase +[ RUN ] DynamicFixture.DynamicTestPass +DynamicFixture() +DynamicFixture::SetUp +DynamicFixture::TearDown +~DynamicFixture() +[ OK ] DynamicFixture.DynamicTestPass +[ RUN ] DynamicFixture.DynamicTestFail +DynamicFixture() +DynamicFixture::SetUp +googletest-output-test_.cc:#: Failure +Value of: Pass + Actual: false +Expected: true +Stack trace: (omitted) + +DynamicFixture::TearDown +~DynamicFixture() +[ FAILED ] DynamicFixture.DynamicTestFail +DynamicFixture::TearDownTestCase +[----------] 1 test from DynamicFixtureAnotherName +DynamicFixture::SetUpTestCase +[ RUN ] DynamicFixtureAnotherName.DynamicTestPass +DynamicFixture() +DynamicFixture::SetUp +DynamicFixture::TearDown +~DynamicFixture() +[ OK ] DynamicFixtureAnotherName.DynamicTestPass +DynamicFixture::TearDownTestCase +[----------] 2 tests from BadDynamicFixture1 +DynamicFixture::SetUpTestCase +[ RUN ] BadDynamicFixture1.FixtureBase +DynamicFixture() +DynamicFixture::SetUp +DynamicFixture::TearDown +~DynamicFixture() +[ OK ] BadDynamicFixture1.FixtureBase +[ RUN ] BadDynamicFixture1.TestBase +DynamicFixture() +gtest.cc:#: Failure +Failed +All tests in the same test case must use the same test fixture +class, so mixing TEST_F and TEST in the same test case is +illegal. In test case BadDynamicFixture1, +test FixtureBase is defined using TEST_F but +test TestBase is defined using TEST. You probably +want to change the TEST to TEST_F or move it to another test +case. +Stack trace: (omitted) + +~DynamicFixture() +[ FAILED ] BadDynamicFixture1.TestBase +DynamicFixture::TearDownTestCase +[----------] 2 tests from BadDynamicFixture2 +DynamicFixture::SetUpTestCase +[ RUN ] BadDynamicFixture2.FixtureBase +DynamicFixture() +DynamicFixture::SetUp +DynamicFixture::TearDown +~DynamicFixture() +[ OK ] BadDynamicFixture2.FixtureBase +[ RUN ] BadDynamicFixture2.Derived +DynamicFixture() +gtest.cc:#: Failure +Failed +All tests in the same test case must use the same test fixture +class. However, in test case BadDynamicFixture2, +you defined test FixtureBase and test Derived +using two different test fixture classes. This can happen if +the two classes are from different namespaces or translation +units and have the same name. You should probably rename one +of the classes to put the tests into different test cases. +Stack trace: (omitted) + +~DynamicFixture() +[ FAILED ] BadDynamicFixture2.Derived +DynamicFixture::TearDownTestCase [----------] 1 test from PrintingFailingParams/FailingParamTest [ RUN ] PrintingFailingParams/FailingParamTest.Fails/0 googletest-output-test_.cc:#: Failure @@ -906,9 +984,9 @@ Failed Expected fatal failure. Stack trace: (omitted) -[==========] 76 tests from 34 test cases ran. -[ PASSED ] 26 tests. -[ FAILED ] 50 tests, listed below: +[==========] 83 tests from 38 test cases ran. +[ PASSED ] 30 tests. +[ FAILED ] 53 tests, listed below: [ FAILED ] NonfatalFailureTest.EscapesStringOperands [ FAILED ] NonfatalFailureTest.DiffForLongStrings [ FAILED ] FatalFailureTest.FatalFailureInSubroutine @@ -957,10 +1035,13 @@ Stack trace: (omitted) [ FAILED ] ExpectFailureWithThreadsTest.ExpectFatalFailure [ FAILED ] ExpectFailureWithThreadsTest.ExpectNonFatalFailure [ FAILED ] ScopedFakeTestPartResultReporterTest.InterceptOnlyCurrentThread +[ FAILED ] DynamicFixture.DynamicTestFail +[ FAILED ] BadDynamicFixture1.TestBase +[ FAILED ] BadDynamicFixture2.Derived [ FAILED ] PrintingFailingParams/FailingParamTest.Fails/0, where GetParam() = 2 [ FAILED ] PrintingStrings/ParamTest.Failure/a, where GetParam() = "a" -50 FAILED TESTS +53 FAILED TESTS  YOU HAVE 1 DISABLED TEST Note: Google Test filter = FatalFailureTest.*:LoggingTest.* diff --git a/googletest/test/googletest-output-test_.cc b/googletest/test/googletest-output-test_.cc index 67de2d17..f86d814f 100644 --- a/googletest/test/googletest-output-test_.cc +++ b/googletest/test/googletest-output-test_.cc @@ -1024,6 +1024,56 @@ TEST_F(ExpectFailureTest, ExpectNonFatalFailureOnAllThreads) { "Some other non-fatal failure."); } +class DynamicFixture : public testing::Test { + protected: + DynamicFixture() { printf("DynamicFixture()\n"); } + ~DynamicFixture() override { printf("~DynamicFixture()\n"); } + void SetUp() override { printf("DynamicFixture::SetUp\n"); } + void TearDown() override { printf("DynamicFixture::TearDown\n"); } + + static void SetUpTestCase() { printf("DynamicFixture::SetUpTestCase\n"); } + static void TearDownTestCase() { + printf("DynamicFixture::TearDownTestCase\n"); + } +}; + +template +class DynamicTest : public DynamicFixture { + public: + void TestBody() override { EXPECT_TRUE(Pass); } +}; + +auto dynamic_test = ( + // Register two tests with the same fixture correctly. + testing::RegisterTest( + "DynamicFixture", "DynamicTestPass", nullptr, nullptr, __FILE__, + __LINE__, []() -> DynamicFixture* { return new DynamicTest; }), + testing::RegisterTest( + "DynamicFixture", "DynamicTestFail", nullptr, nullptr, __FILE__, + __LINE__, []() -> DynamicFixture* { return new DynamicTest; }), + + // Register the same fixture with another name. That's fine. + testing::RegisterTest( + "DynamicFixtureAnotherName", "DynamicTestPass", nullptr, nullptr, + __FILE__, __LINE__, + []() -> DynamicFixture* { return new DynamicTest; }), + + // Register two tests with the same fixture incorrectly. + testing::RegisterTest( + "BadDynamicFixture1", "FixtureBase", nullptr, nullptr, __FILE__, + __LINE__, []() -> DynamicFixture* { return new DynamicTest; }), + testing::RegisterTest( + "BadDynamicFixture1", "TestBase", nullptr, nullptr, __FILE__, __LINE__, + []() -> testing::Test* { return new DynamicTest; }), + + // Register two tests with the same fixture incorrectly by ommiting the + // return type. + testing::RegisterTest( + "BadDynamicFixture2", "FixtureBase", nullptr, nullptr, __FILE__, + __LINE__, []() -> DynamicFixture* { return new DynamicTest; }), + testing::RegisterTest("BadDynamicFixture2", "Derived", nullptr, nullptr, + __FILE__, __LINE__, + []() { return new DynamicTest; })); // Two test environments for testing testing::AddGlobalTestEnvironment(). diff --git a/googletest/test/gtest_unittest.cc b/googletest/test/gtest_unittest.cc index 9ddb37d0..6d9bd347 100644 --- a/googletest/test/gtest_unittest.cc +++ b/googletest/test/gtest_unittest.cc @@ -7547,3 +7547,30 @@ TEST_F(AdHocTestResultTest, AdHocTestResultTestForUnitTestDoesNotShowFailure) { testing::UnitTest::GetInstance()->ad_hoc_test_result(); EXPECT_FALSE(test_result.Failed()); } + +class DynamicUnitTestFixture : public testing::Test {}; + +class DynamicTest : public DynamicUnitTestFixture { + void TestBody() override { EXPECT_TRUE(true); } +}; + +auto* dynamic_test = testing::RegisterTest( + "DynamicUnitTestFixture", "DynamicTest", "TYPE", "VALUE", __FILE__, + __LINE__, []() -> DynamicUnitTestFixture* { return new DynamicTest; }); + +TEST(RegisterTest, WasRegistered) { + auto* unittest = testing::UnitTest::GetInstance(); + for (int i = 0; i < unittest->total_test_case_count(); ++i) { + auto* tests = unittest->GetTestCase(i); + if (tests->name() != std::string("DynamicUnitTestFixture")) continue; + for (int j = 0; j < tests->total_test_count(); ++j) { + if (tests->GetTestInfo(j)->name() != std::string("DynamicTest")) continue; + // Found it. + EXPECT_STREQ(tests->GetTestInfo(j)->value_param(), "VALUE"); + EXPECT_STREQ(tests->GetTestInfo(j)->type_param(), "TYPE"); + return; + } + } + + FAIL() << "Didn't find the test!"; +} -- cgit v1.2.3 From b93a13ec4db4a160d784a5f3260ad2e56ab9e8c7 Mon Sep 17 00:00:00 2001 From: "Case, Matt" Date: Thu, 20 Dec 2018 20:58:56 -0600 Subject: Improvements have been made to the example/sample makefiles for both googlemock and googletest. Library files are now created and named like versions produced by Cmake. --- googlemock/make/Makefile | 30 +++++++++++++++++++++++------- googletest/make/Makefile | 18 ++++++++++++------ 2 files changed, 35 insertions(+), 13 deletions(-) diff --git a/googlemock/make/Makefile b/googlemock/make/Makefile index 7c13e05f..386293a0 100644 --- a/googlemock/make/Makefile +++ b/googlemock/make/Makefile @@ -19,6 +19,9 @@ # a copy of Google Test at a different location. GTEST_DIR = ../../googletest +# Points to the location of the Google Test libraries +GTEST_LIB_DIR = . + # Points to the root of Google Mock, relative to where this file is. # Remember to tweak this if you move this file. GMOCK_DIR = .. @@ -33,7 +36,10 @@ USER_DIR = ../test CPPFLAGS += -isystem $(GTEST_DIR)/include -isystem $(GMOCK_DIR)/include # Flags passed to the C++ compiler. -CXXFLAGS += -g -Wall -Wextra -pthread +CXXFLAGS += -g -Wall -Wextra -pthread -std=c++11 + +# Google Test libraries +GTEST_LIBS = libgtest.a libgtest_main.a libgmock.a libgmock_main.a # All tests produced by this Makefile. Remember to add new tests you # created to the list. @@ -53,10 +59,10 @@ GMOCK_HEADERS = $(GMOCK_DIR)/include/gmock/*.h \ # House-keeping build targets. -all : $(TESTS) +all : $(GTEST_LIBS) $(TESTS) clean : - rm -f $(TESTS) gmock.a gmock_main.a *.o + rm -f $(GTEST_LIBS) $(TESTS) *.o # Builds gmock.a and gmock_main.a. These libraries contain both # Google Mock and Google Test. A test should link with either gmock.a @@ -78,6 +84,10 @@ gtest-all.o : $(GTEST_SRCS_) $(CXX) $(CPPFLAGS) -I$(GTEST_DIR) -I$(GMOCK_DIR) $(CXXFLAGS) \ -c $(GTEST_DIR)/src/gtest-all.cc +gtest_main.o : $(GTEST_SRCS_) + $(CXX) $(CPPFLAGS) -I$(GTEST_DIR) -I$(GMOCK_DIR) $(CXXFLAGS) \ + -c $(GTEST_DIR)/src/gtest_main.cc + gmock-all.o : $(GMOCK_SRCS_) $(CXX) $(CPPFLAGS) -I$(GTEST_DIR) -I$(GMOCK_DIR) $(CXXFLAGS) \ -c $(GMOCK_DIR)/src/gmock-all.cc @@ -86,10 +96,16 @@ gmock_main.o : $(GMOCK_SRCS_) $(CXX) $(CPPFLAGS) -I$(GTEST_DIR) -I$(GMOCK_DIR) $(CXXFLAGS) \ -c $(GMOCK_DIR)/src/gmock_main.cc -gmock.a : gmock-all.o gtest-all.o +libgtest.a : gtest-all.o + $(AR) $(ARFLAGS) $@ $^ + +libgtest_main.a : gtest_main.o + $(AR) $(ARFLAGS) $@ $^ + +libgmock.a : gmock-all.o $(AR) $(ARFLAGS) $@ $^ -gmock_main.a : gmock-all.o gtest-all.o gmock_main.o +libgmock_main.a : gmock_main.o $(AR) $(ARFLAGS) $@ $^ # Builds a sample test. @@ -97,5 +113,5 @@ gmock_main.a : gmock-all.o gtest-all.o gmock_main.o gmock_test.o : $(USER_DIR)/gmock_test.cc $(GMOCK_HEADERS) $(CXX) $(CPPFLAGS) $(CXXFLAGS) -c $(USER_DIR)/gmock_test.cc -gmock_test : gmock_test.o gmock_main.a - $(CXX) $(CPPFLAGS) $(CXXFLAGS) -lpthread $^ -o $@ +gmock_test : gmock_test.o $(GTEST_LIBS) + $(CXX) $(CPPFLAGS) $(CXXFLAGS) -L$(GTEST_LIB_DIR) -lgmock -lpthread $^ -o $@ diff --git a/googletest/make/Makefile b/googletest/make/Makefile index 91eb68b5..b62da67a 100644 --- a/googletest/make/Makefile +++ b/googletest/make/Makefile @@ -16,6 +16,9 @@ # Remember to tweak this if you move this file. GTEST_DIR = .. +# Points to the location of the Google Test libraries +GTEST_LIB_DIR = . + # Where to find user code. USER_DIR = ../samples @@ -27,6 +30,9 @@ CPPFLAGS += -isystem $(GTEST_DIR)/include # Flags passed to the C++ compiler. CXXFLAGS += -g -Wall -Wextra -pthread -std=c++11 +# Google Test libraries +GTEST_LIBS = libgtest.a libgtest_main.a + # All tests produced by this Makefile. Remember to add new tests you # created to the list. TESTS = sample1_unittest @@ -38,10 +44,10 @@ GTEST_HEADERS = $(GTEST_DIR)/include/gtest/*.h \ # House-keeping build targets. -all : $(TESTS) +all : $(GTEST_LIBS) $(TESTS) clean : - rm -f $(TESTS) gtest.a gtest_main.a *.o + rm -f $(GTEST_LIBS) $(TESTS) *.o # Builds gtest.a and gtest_main.a. @@ -61,10 +67,10 @@ gtest_main.o : $(GTEST_SRCS_) $(CXX) $(CPPFLAGS) -I$(GTEST_DIR) $(CXXFLAGS) -c \ $(GTEST_DIR)/src/gtest_main.cc -gtest.a : gtest-all.o +libgtest.a : gtest-all.o $(AR) $(ARFLAGS) $@ $^ -gtest_main.a : gtest-all.o gtest_main.o +libgtest_main.a : gtest-all.o gtest_main.o $(AR) $(ARFLAGS) $@ $^ # Builds a sample test. A test should link with either gtest.a or @@ -78,5 +84,5 @@ sample1_unittest.o : $(USER_DIR)/sample1_unittest.cc \ $(USER_DIR)/sample1.h $(GTEST_HEADERS) $(CXX) $(CPPFLAGS) $(CXXFLAGS) -c $(USER_DIR)/sample1_unittest.cc -sample1_unittest : sample1.o sample1_unittest.o gtest_main.a - $(CXX) $(CPPFLAGS) $(CXXFLAGS) -lpthread $^ -o $@ +sample1_unittest : sample1.o sample1_unittest.o $(GTEST_LIBS) + $(CXX) $(CPPFLAGS) $(CXXFLAGS) -L$(GTEST_LIB_DIR) -lgtest_main -lpthread $^ -o $@ -- cgit v1.2.3 From 34a99e547ab7754bf69618d3047a80b1b35148b3 Mon Sep 17 00:00:00 2001 From: Abseil Team Date: Fri, 21 Dec 2018 04:17:43 -0500 Subject: Googletest export Get rid of code generation for NiceMock / StrictMock. They got small enough that it doesn't make sense to generate them. PiperOrigin-RevId: 226455689 --- googlemock/Makefile.am | 3 +- .../include/gmock/gmock-generated-nice-strict.h | 219 --------------------- .../gmock/gmock-generated-nice-strict.h.pump | 157 --------------- googlemock/include/gmock/gmock-nice-strict.h | 215 ++++++++++++++++++++ googlemock/include/gmock/gmock.h | 2 +- googlemock/test/gmock-nice-strict_test.cc | 3 +- 6 files changed, 218 insertions(+), 381 deletions(-) delete mode 100644 googlemock/include/gmock/gmock-generated-nice-strict.h delete mode 100644 googlemock/include/gmock/gmock-generated-nice-strict.h.pump create mode 100644 googlemock/include/gmock/gmock-nice-strict.h diff --git a/googlemock/Makefile.am b/googlemock/Makefile.am index 016a60e9..7fe68099 100644 --- a/googlemock/Makefile.am +++ b/googlemock/Makefile.am @@ -32,10 +32,10 @@ pkginclude_HEADERS = \ include/gmock/gmock-generated-actions.h \ include/gmock/gmock-generated-function-mockers.h \ include/gmock/gmock-generated-matchers.h \ - include/gmock/gmock-generated-nice-strict.h \ include/gmock/gmock-matchers.h \ include/gmock/gmock-more-actions.h \ include/gmock/gmock-more-matchers.h \ + include/gmock/gmock-nice-strict.h \ include/gmock/gmock-spec-builders.h \ include/gmock/gmock.h @@ -141,7 +141,6 @@ EXTRA_DIST += \ include/gmock/gmock-generated-actions.h.pump \ include/gmock/gmock-generated-function-mockers.h.pump \ include/gmock/gmock-generated-matchers.h.pump \ - include/gmock/gmock-generated-nice-strict.h.pump \ include/gmock/internal/gmock-generated-internal-utils.h.pump \ include/gmock/internal/custom/gmock-generated-actions.h.pump diff --git a/googlemock/include/gmock/gmock-generated-nice-strict.h b/googlemock/include/gmock/gmock-generated-nice-strict.h deleted file mode 100644 index 550892cb..00000000 --- a/googlemock/include/gmock/gmock-generated-nice-strict.h +++ /dev/null @@ -1,219 +0,0 @@ -// This file was GENERATED by command: -// pump.py gmock-generated-nice-strict.h.pump -// DO NOT EDIT BY HAND!!! - -// 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. - - -// Implements class templates NiceMock, NaggyMock, and StrictMock. -// -// Given a mock class MockFoo that is created using Google Mock, -// NiceMock is a subclass of MockFoo that allows -// uninteresting calls (i.e. calls to mock methods that have no -// EXPECT_CALL specs), NaggyMock is a subclass of MockFoo -// that prints a warning when an uninteresting call occurs, and -// StrictMock is a subclass of MockFoo that treats all -// uninteresting calls as errors. -// -// Currently a mock is naggy by default, so MockFoo and -// NaggyMock behave like the same. However, we will soon -// switch the default behavior of mocks to be nice, as that in general -// leads to more maintainable tests. When that happens, MockFoo will -// stop behaving like NaggyMock and start behaving like -// NiceMock. -// -// NiceMock, NaggyMock, and StrictMock "inherit" the constructors of -// their respective base class. Therefore you can write -// NiceMock(5, "a") to construct a nice mock where MockFoo -// has a constructor that accepts (int, const char*), for example. -// -// A known limitation is that NiceMock, NaggyMock, -// and StrictMock only works for mock methods defined using -// the MOCK_METHOD* family of macros DIRECTLY in the MockFoo class. -// If a mock method is defined in a base class of MockFoo, the "nice" -// or "strict" modifier may not affect it, depending on the compiler. -// In particular, nesting NiceMock, NaggyMock, and StrictMock is NOT -// supported. - -// GOOGLETEST_CM0002 DO NOT DELETE - -#ifndef GMOCK_INCLUDE_GMOCK_GMOCK_GENERATED_NICE_STRICT_H_ -#define GMOCK_INCLUDE_GMOCK_GMOCK_GENERATED_NICE_STRICT_H_ - -#include "gmock/gmock-spec-builders.h" -#include "gmock/internal/gmock-port.h" - -namespace testing { - -template -class NiceMock : public MockClass { - public: - NiceMock() : MockClass() { - ::testing::Mock::AllowUninterestingCalls( - internal::ImplicitCast_(this)); - } - - // Ideally, we would inherit base class's constructors through a using - // declaration, which would preserve their visibility. However, many existing - // tests rely on the fact that current implementation reexports protected - // constructors as public. These tests would need to be cleaned up first. - - // Single argument constructor is special-cased so that it can be - // made explicit. - template - explicit NiceMock(A&& arg) : MockClass(std::forward(arg)) { - ::testing::Mock::AllowUninterestingCalls( - internal::ImplicitCast_(this)); - } - - template - NiceMock(A1&& arg1, A2&& arg2, An&&... args) - : MockClass(std::forward(arg1), std::forward(arg2), - std::forward(args)...) { - ::testing::Mock::AllowUninterestingCalls( - internal::ImplicitCast_(this)); - } - - ~NiceMock() { // NOLINT - ::testing::Mock::UnregisterCallReaction( - internal::ImplicitCast_(this)); - } - - private: - GTEST_DISALLOW_COPY_AND_ASSIGN_(NiceMock); -}; - -template -class NaggyMock : public MockClass { - public: - NaggyMock() : MockClass() { - ::testing::Mock::WarnUninterestingCalls( - internal::ImplicitCast_(this)); - } - - // Ideally, we would inherit base class's constructors through a using - // declaration, which would preserve their visibility. However, many existing - // tests rely on the fact that current implementation reexports protected - // constructors as public. These tests would need to be cleaned up first. - - // Single argument constructor is special-cased so that it can be - // made explicit. - template - explicit NaggyMock(A&& arg) : MockClass(std::forward(arg)) { - ::testing::Mock::WarnUninterestingCalls( - internal::ImplicitCast_(this)); - } - - template - NaggyMock(A1&& arg1, A2&& arg2, An&&... args) - : MockClass(std::forward(arg1), std::forward(arg2), - std::forward(args)...) { - ::testing::Mock::WarnUninterestingCalls( - internal::ImplicitCast_(this)); - } - - ~NaggyMock() { // NOLINT - ::testing::Mock::UnregisterCallReaction( - internal::ImplicitCast_(this)); - } - - private: - GTEST_DISALLOW_COPY_AND_ASSIGN_(NaggyMock); -}; - -template -class StrictMock : public MockClass { - public: - StrictMock() : MockClass() { - ::testing::Mock::FailUninterestingCalls( - internal::ImplicitCast_(this)); - } - - // Ideally, we would inherit base class's constructors through a using - // declaration, which would preserve their visibility. However, many existing - // tests rely on the fact that current implementation reexports protected - // constructors as public. These tests would need to be cleaned up first. - - // Single argument constructor is special-cased so that it can be - // made explicit. - template - explicit StrictMock(A&& arg) : MockClass(std::forward(arg)) { - ::testing::Mock::FailUninterestingCalls( - internal::ImplicitCast_(this)); - } - - template - StrictMock(A1&& arg1, A2&& arg2, An&&... args) - : MockClass(std::forward(arg1), std::forward(arg2), - std::forward(args)...) { - ::testing::Mock::FailUninterestingCalls( - internal::ImplicitCast_(this)); - } - - ~StrictMock() { // NOLINT - ::testing::Mock::UnregisterCallReaction( - internal::ImplicitCast_(this)); - } - - private: - GTEST_DISALLOW_COPY_AND_ASSIGN_(StrictMock); -}; - -// The following specializations catch some (relatively more common) -// user errors of nesting nice and strict mocks. They do NOT catch -// all possible errors. - -// These specializations are declared but not defined, as NiceMock, -// NaggyMock, and StrictMock cannot be nested. - -template -class NiceMock >; -template -class NiceMock >; -template -class NiceMock >; - -template -class NaggyMock >; -template -class NaggyMock >; -template -class NaggyMock >; - -template -class StrictMock >; -template -class StrictMock >; -template -class StrictMock >; - -} // namespace testing - -#endif // GMOCK_INCLUDE_GMOCK_GMOCK_GENERATED_NICE_STRICT_H_ diff --git a/googlemock/include/gmock/gmock-generated-nice-strict.h.pump b/googlemock/include/gmock/gmock-generated-nice-strict.h.pump deleted file mode 100644 index 67160800..00000000 --- a/googlemock/include/gmock/gmock-generated-nice-strict.h.pump +++ /dev/null @@ -1,157 +0,0 @@ -$$ -*- mode: c++; -*- -$$ This is a Pump source file. Please use Pump to convert -$$ it to gmock-generated-nice-strict.h. -$$ -$var n = 10 $$ The maximum arity we 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. - - -// Implements class templates NiceMock, NaggyMock, and StrictMock. -// -// Given a mock class MockFoo that is created using Google Mock, -// NiceMock is a subclass of MockFoo that allows -// uninteresting calls (i.e. calls to mock methods that have no -// EXPECT_CALL specs), NaggyMock is a subclass of MockFoo -// that prints a warning when an uninteresting call occurs, and -// StrictMock is a subclass of MockFoo that treats all -// uninteresting calls as errors. -// -// Currently a mock is naggy by default, so MockFoo and -// NaggyMock behave like the same. However, we will soon -// switch the default behavior of mocks to be nice, as that in general -// leads to more maintainable tests. When that happens, MockFoo will -// stop behaving like NaggyMock and start behaving like -// NiceMock. -// -// NiceMock, NaggyMock, and StrictMock "inherit" the constructors of -// their respective base class. Therefore you can write -// NiceMock(5, "a") to construct a nice mock where MockFoo -// has a constructor that accepts (int, const char*), for example. -// -// A known limitation is that NiceMock, NaggyMock, -// and StrictMock only works for mock methods defined using -// the MOCK_METHOD* family of macros DIRECTLY in the MockFoo class. -// If a mock method is defined in a base class of MockFoo, the "nice" -// or "strict" modifier may not affect it, depending on the compiler. -// In particular, nesting NiceMock, NaggyMock, and StrictMock is NOT -// supported. - -// GOOGLETEST_CM0002 DO NOT DELETE - -#ifndef GMOCK_INCLUDE_GMOCK_GMOCK_GENERATED_NICE_STRICT_H_ -#define GMOCK_INCLUDE_GMOCK_GMOCK_GENERATED_NICE_STRICT_H_ - -#include "gmock/gmock-spec-builders.h" -#include "gmock/internal/gmock-port.h" - -namespace testing { - -$range kind 0..2 -$for kind [[ - -$var clazz=[[$if kind==0 [[NiceMock]] - $elif kind==1 [[NaggyMock]] - $else [[StrictMock]]]] - -$var method=[[$if kind==0 [[AllowUninterestingCalls]] - $elif kind==1 [[WarnUninterestingCalls]] - $else [[FailUninterestingCalls]]]] - -template -class $clazz : public MockClass { - public: - $clazz() : MockClass() { - ::testing::Mock::$method( - internal::ImplicitCast_(this)); - } - - // Ideally, we would inherit base class's constructors through a using - // declaration, which would preserve their visibility. However, many existing - // tests rely on the fact that current implementation reexports protected - // constructors as public. These tests would need to be cleaned up first. - - // Single argument constructor is special-cased so that it can be - // made explicit. - template - explicit $clazz(A&& arg) : MockClass(std::forward(arg)) { - ::testing::Mock::$method( - internal::ImplicitCast_(this)); - } - - template - $clazz(A1&& arg1, A2&& arg2, An&&... args) - : MockClass(std::forward(arg1), std::forward(arg2), - std::forward(args)...) { - ::testing::Mock::$method( - internal::ImplicitCast_(this)); - } - - ~$clazz() { // NOLINT - ::testing::Mock::UnregisterCallReaction( - internal::ImplicitCast_(this)); - } - - private: - GTEST_DISALLOW_COPY_AND_ASSIGN_($clazz); -}; - -]] - -// The following specializations catch some (relatively more common) -// user errors of nesting nice and strict mocks. They do NOT catch -// all possible errors. - -// These specializations are declared but not defined, as NiceMock, -// NaggyMock, and StrictMock cannot be nested. - -template -class NiceMock >; -template -class NiceMock >; -template -class NiceMock >; - -template -class NaggyMock >; -template -class NaggyMock >; -template -class NaggyMock >; - -template -class StrictMock >; -template -class StrictMock >; -template -class StrictMock >; - -} // namespace testing - -#endif // GMOCK_INCLUDE_GMOCK_GMOCK_GENERATED_NICE_STRICT_H_ diff --git a/googlemock/include/gmock/gmock-nice-strict.h b/googlemock/include/gmock/gmock-nice-strict.h new file mode 100644 index 00000000..5495a980 --- /dev/null +++ b/googlemock/include/gmock/gmock-nice-strict.h @@ -0,0 +1,215 @@ +// 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. + + +// Implements class templates NiceMock, NaggyMock, and StrictMock. +// +// Given a mock class MockFoo that is created using Google Mock, +// NiceMock is a subclass of MockFoo that allows +// uninteresting calls (i.e. calls to mock methods that have no +// EXPECT_CALL specs), NaggyMock is a subclass of MockFoo +// that prints a warning when an uninteresting call occurs, and +// StrictMock is a subclass of MockFoo that treats all +// uninteresting calls as errors. +// +// Currently a mock is naggy by default, so MockFoo and +// NaggyMock behave like the same. However, we will soon +// switch the default behavior of mocks to be nice, as that in general +// leads to more maintainable tests. When that happens, MockFoo will +// stop behaving like NaggyMock and start behaving like +// NiceMock. +// +// NiceMock, NaggyMock, and StrictMock "inherit" the constructors of +// their respective base class. Therefore you can write +// NiceMock(5, "a") to construct a nice mock where MockFoo +// has a constructor that accepts (int, const char*), for example. +// +// A known limitation is that NiceMock, NaggyMock, +// and StrictMock only works for mock methods defined using +// the MOCK_METHOD* family of macros DIRECTLY in the MockFoo class. +// If a mock method is defined in a base class of MockFoo, the "nice" +// or "strict" modifier may not affect it, depending on the compiler. +// In particular, nesting NiceMock, NaggyMock, and StrictMock is NOT +// supported. + +// GOOGLETEST_CM0002 DO NOT DELETE + +#ifndef GMOCK_INCLUDE_GMOCK_GMOCK_NICE_STRICT_H_ +#define GMOCK_INCLUDE_GMOCK_GMOCK_NICE_STRICT_H_ + +#include "gmock/gmock-spec-builders.h" +#include "gmock/internal/gmock-port.h" + +namespace testing { + +template +class NiceMock : public MockClass { + public: + NiceMock() : MockClass() { + ::testing::Mock::AllowUninterestingCalls( + internal::ImplicitCast_(this)); + } + + // Ideally, we would inherit base class's constructors through a using + // declaration, which would preserve their visibility. However, many existing + // tests rely on the fact that current implementation reexports protected + // constructors as public. These tests would need to be cleaned up first. + + // Single argument constructor is special-cased so that it can be + // made explicit. + template + explicit NiceMock(A&& arg) : MockClass(std::forward(arg)) { + ::testing::Mock::AllowUninterestingCalls( + internal::ImplicitCast_(this)); + } + + template + NiceMock(A1&& arg1, A2&& arg2, An&&... args) + : MockClass(std::forward(arg1), std::forward(arg2), + std::forward(args)...) { + ::testing::Mock::AllowUninterestingCalls( + internal::ImplicitCast_(this)); + } + + ~NiceMock() { // NOLINT + ::testing::Mock::UnregisterCallReaction( + internal::ImplicitCast_(this)); + } + + private: + GTEST_DISALLOW_COPY_AND_ASSIGN_(NiceMock); +}; + +template +class NaggyMock : public MockClass { + public: + NaggyMock() : MockClass() { + ::testing::Mock::WarnUninterestingCalls( + internal::ImplicitCast_(this)); + } + + // Ideally, we would inherit base class's constructors through a using + // declaration, which would preserve their visibility. However, many existing + // tests rely on the fact that current implementation reexports protected + // constructors as public. These tests would need to be cleaned up first. + + // Single argument constructor is special-cased so that it can be + // made explicit. + template + explicit NaggyMock(A&& arg) : MockClass(std::forward(arg)) { + ::testing::Mock::WarnUninterestingCalls( + internal::ImplicitCast_(this)); + } + + template + NaggyMock(A1&& arg1, A2&& arg2, An&&... args) + : MockClass(std::forward(arg1), std::forward(arg2), + std::forward(args)...) { + ::testing::Mock::WarnUninterestingCalls( + internal::ImplicitCast_(this)); + } + + ~NaggyMock() { // NOLINT + ::testing::Mock::UnregisterCallReaction( + internal::ImplicitCast_(this)); + } + + private: + GTEST_DISALLOW_COPY_AND_ASSIGN_(NaggyMock); +}; + +template +class StrictMock : public MockClass { + public: + StrictMock() : MockClass() { + ::testing::Mock::FailUninterestingCalls( + internal::ImplicitCast_(this)); + } + + // Ideally, we would inherit base class's constructors through a using + // declaration, which would preserve their visibility. However, many existing + // tests rely on the fact that current implementation reexports protected + // constructors as public. These tests would need to be cleaned up first. + + // Single argument constructor is special-cased so that it can be + // made explicit. + template + explicit StrictMock(A&& arg) : MockClass(std::forward(arg)) { + ::testing::Mock::FailUninterestingCalls( + internal::ImplicitCast_(this)); + } + + template + StrictMock(A1&& arg1, A2&& arg2, An&&... args) + : MockClass(std::forward(arg1), std::forward(arg2), + std::forward(args)...) { + ::testing::Mock::FailUninterestingCalls( + internal::ImplicitCast_(this)); + } + + ~StrictMock() { // NOLINT + ::testing::Mock::UnregisterCallReaction( + internal::ImplicitCast_(this)); + } + + private: + GTEST_DISALLOW_COPY_AND_ASSIGN_(StrictMock); +}; + +// The following specializations catch some (relatively more common) +// user errors of nesting nice and strict mocks. They do NOT catch +// all possible errors. + +// These specializations are declared but not defined, as NiceMock, +// NaggyMock, and StrictMock cannot be nested. + +template +class NiceMock >; +template +class NiceMock >; +template +class NiceMock >; + +template +class NaggyMock >; +template +class NaggyMock >; +template +class NaggyMock >; + +template +class StrictMock >; +template +class StrictMock >; +template +class StrictMock >; + +} // namespace testing + +#endif // GMOCK_INCLUDE_GMOCK_GMOCK_NICE_STRICT_H_ diff --git a/googlemock/include/gmock/gmock.h b/googlemock/include/gmock/gmock.h index a1e1e6f1..c68ae1c7 100644 --- a/googlemock/include/gmock/gmock.h +++ b/googlemock/include/gmock/gmock.h @@ -62,10 +62,10 @@ #include "gmock/gmock-generated-actions.h" #include "gmock/gmock-generated-function-mockers.h" #include "gmock/gmock-generated-matchers.h" -#include "gmock/gmock-generated-nice-strict.h" #include "gmock/gmock-matchers.h" #include "gmock/gmock-more-actions.h" #include "gmock/gmock-more-matchers.h" +#include "gmock/gmock-nice-strict.h" #include "gmock/internal/gmock-internal-utils.h" namespace testing { diff --git a/googlemock/test/gmock-nice-strict_test.cc b/googlemock/test/gmock-nice-strict_test.cc index 5f8f9617..455e591c 100644 --- a/googlemock/test/gmock-nice-strict_test.cc +++ b/googlemock/test/gmock-nice-strict_test.cc @@ -27,8 +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 "gmock/gmock-generated-nice-strict.h" +#include "gmock/gmock-nice-strict.h" #include #include -- cgit v1.2.3 From 150613166524c474a8a97df4c01d46b72050c495 Mon Sep 17 00:00:00 2001 From: Gennadiy Civil Date: Fri, 21 Dec 2018 13:24:39 -0500 Subject: Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 88ed935f..47483536 100644 --- a/README.md +++ b/README.md @@ -1,7 +1,7 @@ # Google Test # -[![Build Status](https://api.travis-ci.org/abseil/googletest.svg?branch=master)](https://travis-ci.org/abseil/googletest) +[![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**: -- cgit v1.2.3 From 77004096e8507c945b865236a3828f25d314c657 Mon Sep 17 00:00:00 2001 From: Gennadiy Civil Date: Thu, 27 Dec 2018 12:04:11 -0500 Subject: Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 88ed935f..47483536 100644 --- a/README.md +++ b/README.md @@ -1,7 +1,7 @@ # Google Test # -[![Build Status](https://api.travis-ci.org/abseil/googletest.svg?branch=master)](https://travis-ci.org/abseil/googletest) +[![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**: -- cgit v1.2.3 From 6729a1361150131bc5d394d5cd2b4cdf0953ee7b Mon Sep 17 00:00:00 2001 From: Ryohei Machida Date: Thu, 27 Dec 2018 11:33:30 -0500 Subject: Merge #2002 PiperOrigin-RevId: 227030722 --- googletest/include/gtest/internal/gtest-internal.h | 31 +++++++--------------- googletest/test/googletest-printers-test.cc | 6 +++++ 2 files changed, 15 insertions(+), 22 deletions(-) diff --git a/googletest/include/gtest/internal/gtest-internal.h b/googletest/include/gtest/internal/gtest-internal.h index b32237a1..f66a5c1b 100644 --- a/googletest/include/gtest/internal/gtest-internal.h +++ b/googletest/include/gtest/internal/gtest-internal.h @@ -967,37 +967,24 @@ struct IsHashTable { template const bool IsHashTable::value; -template -struct VoidT { - typedef void value_type; -}; - -template -struct HasValueType : false_type {}; -template -struct HasValueType > : true_type { -}; - template (0)) == sizeof(IsContainer), - bool = HasValueType::value> + bool = sizeof(IsContainerTest(0)) == sizeof(IsContainer)> struct IsRecursiveContainerImpl; -template -struct IsRecursiveContainerImpl : public false_type {}; +template +struct IsRecursiveContainerImpl : public false_type {}; // Since the IsRecursiveContainerImpl depends on the IsContainerTest we need to // obey the same inconsistencies as the IsContainerTest, namely check if // something is a container is relying on only const_iterator in C++11 and // is relying on both const_iterator and iterator otherwise template -struct IsRecursiveContainerImpl : public false_type {}; - -template -struct IsRecursiveContainerImpl { - typedef typename IteratorTraits::value_type - value_type; - typedef is_same type; +struct IsRecursiveContainerImpl { + using value_type = decltype(*std::declval()); + using type = + is_same::type>::type, + C>; }; // IsRecursiveContainer is a unary compile-time predicate that diff --git a/googletest/test/googletest-printers-test.cc b/googletest/test/googletest-printers-test.cc index 139b3e49..961e8184 100644 --- a/googletest/test/googletest-printers-test.cc +++ b/googletest/test/googletest-printers-test.cc @@ -183,8 +183,14 @@ class PathLike { public: struct iterator { typedef PathLike value_type; + + iterator& operator++(); + PathLike& operator*(); }; + using value_type = char; + using const_iterator = iterator; + PathLike() {} iterator begin() const { return iterator(); } -- cgit v1.2.3 From 0cf2130c0b59410a62a3e5df65fb5fc63a960ba0 Mon Sep 17 00:00:00 2001 From: Syohei YOSHIDA Date: Fri, 28 Dec 2018 13:23:44 +0900 Subject: Update Xcode project file Remove files which no longer exist. --- googletest/xcode/gtest.xcodeproj/project.pbxproj | 12 ------------ 1 file changed, 12 deletions(-) diff --git a/googletest/xcode/gtest.xcodeproj/project.pbxproj b/googletest/xcode/gtest.xcodeproj/project.pbxproj index 003bff8c..afc4d3d0 100644 --- a/googletest/xcode/gtest.xcodeproj/project.pbxproj +++ b/googletest/xcode/gtest.xcodeproj/project.pbxproj @@ -52,11 +52,9 @@ 404884A20E2F7BE600CF7658 /* gtest-internal.h in Copy Headers Internal */ = {isa = PBXBuildFile; fileRef = 404883E40E2F799B00CF7658 /* gtest-internal.h */; }; 404884A30E2F7BE600CF7658 /* gtest-port.h in Copy Headers Internal */ = {isa = PBXBuildFile; fileRef = 404883E50E2F799B00CF7658 /* gtest-port.h */; }; 404884A40E2F7BE600CF7658 /* gtest-string.h in Copy Headers Internal */ = {isa = PBXBuildFile; fileRef = 404883E60E2F799B00CF7658 /* gtest-string.h */; }; - 404884AC0E2F7CD900CF7658 /* CHANGES in Resources */ = {isa = PBXBuildFile; fileRef = 404884A90E2F7CD900CF7658 /* CHANGES */; }; 404884AD0E2F7CD900CF7658 /* CONTRIBUTORS in Resources */ = {isa = PBXBuildFile; fileRef = 404884AA0E2F7CD900CF7658 /* CONTRIBUTORS */; }; 404884AE0E2F7CD900CF7658 /* LICENSE in Resources */ = {isa = PBXBuildFile; fileRef = 404884AB0E2F7CD900CF7658 /* LICENSE */; }; 40899F3A0FFA70D4000B29AE /* gtest-all.cc in Sources */ = {isa = PBXBuildFile; fileRef = 224A12A10E9EADA700BD17FD /* gtest-all.cc */; }; - 40899F500FFA7281000B29AE /* gtest-tuple.h in Copy Headers Internal */ = {isa = PBXBuildFile; fileRef = 40899F4D0FFA7271000B29AE /* gtest-tuple.h */; }; 40899F530FFA72A0000B29AE /* gtest_unittest.cc in Sources */ = {isa = PBXBuildFile; fileRef = 3B238C120E7FE13C00846E11 /* gtest_unittest.cc */; }; 4089A0440FFAD1BE000B29AE /* sample1.cc in Sources */ = {isa = PBXBuildFile; fileRef = 4089A02C0FFACF7F000B29AE /* sample1.cc */; }; 4089A0460FFAD1BE000B29AE /* sample1_unittest.cc in Sources */ = {isa = PBXBuildFile; fileRef = 4089A02E0FFACF7F000B29AE /* sample1_unittest.cc */; }; @@ -75,7 +73,6 @@ 40C849A2101A37050083642A /* gtest.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 4539C8FF0EC27F6400A70F4C /* gtest.framework */; }; 40C849A4101A37150083642A /* gtest.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 4539C8FF0EC27F6400A70F4C /* gtest.framework */; }; 4539C9340EC280AE00A70F4C /* gtest-param-test.h in Headers */ = {isa = PBXBuildFile; fileRef = 4539C9330EC280AE00A70F4C /* gtest-param-test.h */; settings = {ATTRIBUTES = (Public, ); }; }; - 4539C9380EC280E200A70F4C /* gtest-linked_ptr.h in Copy Headers Internal */ = {isa = PBXBuildFile; fileRef = 4539C9350EC280E200A70F4C /* gtest-linked_ptr.h */; }; 4539C9390EC280E200A70F4C /* gtest-param-util-generated.h in Copy Headers Internal */ = {isa = PBXBuildFile; fileRef = 4539C9360EC280E200A70F4C /* gtest-param-util-generated.h */; }; 4539C93A0EC280E200A70F4C /* gtest-param-util.h in Copy Headers Internal */ = {isa = PBXBuildFile; fileRef = 4539C9370EC280E200A70F4C /* gtest-param-util.h */; }; 4567C8181264FF71007740BE /* gtest-printers.h in Headers */ = {isa = PBXBuildFile; fileRef = 4567C8171264FF71007740BE /* gtest-printers.h */; settings = {ATTRIBUTES = (Public, ); }; }; @@ -193,12 +190,10 @@ 404884A00E2F7BE600CF7658 /* gtest-death-test-internal.h in Copy Headers Internal */, 404884A10E2F7BE600CF7658 /* gtest-filepath.h in Copy Headers Internal */, 404884A20E2F7BE600CF7658 /* gtest-internal.h in Copy Headers Internal */, - 4539C9380EC280E200A70F4C /* gtest-linked_ptr.h in Copy Headers Internal */, 4539C9390EC280E200A70F4C /* gtest-param-util-generated.h in Copy Headers Internal */, 4539C93A0EC280E200A70F4C /* gtest-param-util.h in Copy Headers Internal */, 404884A30E2F7BE600CF7658 /* gtest-port.h in Copy Headers Internal */, 404884A40E2F7BE600CF7658 /* gtest-string.h in Copy Headers Internal */, - 40899F500FFA7281000B29AE /* gtest-tuple.h in Copy Headers Internal */, 3BF6F2A00E79B5AD000F2EEE /* gtest-type-util.h in Copy Headers Internal */, ); name = "Copy Headers Internal"; @@ -239,11 +234,9 @@ 404883E60E2F799B00CF7658 /* gtest-string.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = "gtest-string.h"; sourceTree = ""; }; 404883F60E2F799B00CF7658 /* README.md */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text; name = README.md; path = ../README.md; sourceTree = SOURCE_ROOT; }; 4048840D0E2F799B00CF7658 /* gtest_main.cc */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = gtest_main.cc; sourceTree = ""; }; - 404884A90E2F7CD900CF7658 /* CHANGES */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text; name = CHANGES; path = ../CHANGES; sourceTree = SOURCE_ROOT; }; 404884AA0E2F7CD900CF7658 /* CONTRIBUTORS */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text; name = CONTRIBUTORS; path = ../CONTRIBUTORS; sourceTree = SOURCE_ROOT; }; 404884AB0E2F7CD900CF7658 /* LICENSE */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text; name = LICENSE; path = ../LICENSE; sourceTree = SOURCE_ROOT; }; 40899F430FFA7184000B29AE /* gtest_unittest-framework */ = {isa = PBXFileReference; explicitFileType = "compiled.mach-o.executable"; includeInIndex = 0; path = "gtest_unittest-framework"; sourceTree = BUILT_PRODUCTS_DIR; }; - 40899F4D0FFA7271000B29AE /* gtest-tuple.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = "gtest-tuple.h"; sourceTree = ""; }; 40899FB30FFA7567000B29AE /* StaticLibraryTarget.xcconfig */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.xcconfig; path = StaticLibraryTarget.xcconfig; sourceTree = ""; }; 4089A0130FFACEFC000B29AE /* sample1_unittest-framework */ = {isa = PBXFileReference; explicitFileType = "compiled.mach-o.executable"; includeInIndex = 0; path = "sample1_unittest-framework"; sourceTree = BUILT_PRODUCTS_DIR; }; 4089A02C0FFACF7F000B29AE /* sample1.cc */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = sample1.cc; sourceTree = ""; }; @@ -260,7 +253,6 @@ 40D4CF510E30F5E200294801 /* Info.plist */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; 4539C8FF0EC27F6400A70F4C /* gtest.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = gtest.framework; sourceTree = BUILT_PRODUCTS_DIR; }; 4539C9330EC280AE00A70F4C /* gtest-param-test.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = "gtest-param-test.h"; sourceTree = ""; }; - 4539C9350EC280E200A70F4C /* gtest-linked_ptr.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = "gtest-linked_ptr.h"; sourceTree = ""; }; 4539C9360EC280E200A70F4C /* gtest-param-util-generated.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = "gtest-param-util-generated.h"; sourceTree = ""; }; 4539C9370EC280E200A70F4C /* gtest-param-util.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = "gtest-param-util.h"; sourceTree = ""; }; 4567C8171264FF71007740BE /* gtest-printers.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = "gtest-printers.h"; sourceTree = ""; }; @@ -339,7 +331,6 @@ 08FB77ACFE841707C02AAC07 /* Source */ = { isa = PBXGroup; children = ( - 404884A90E2F7CD900CF7658 /* CHANGES */, 404884AA0E2F7CD900CF7658 /* CONTRIBUTORS */, 404884AB0E2F7CD900CF7658 /* LICENSE */, 404883F60E2F799B00CF7658 /* README.md */, @@ -403,13 +394,11 @@ 404883E20E2F799B00CF7658 /* gtest-death-test-internal.h */, 404883E30E2F799B00CF7658 /* gtest-filepath.h */, 404883E40E2F799B00CF7658 /* gtest-internal.h */, - 4539C9350EC280E200A70F4C /* gtest-linked_ptr.h */, 4539C9360EC280E200A70F4C /* gtest-param-util-generated.h */, 4539C9370EC280E200A70F4C /* gtest-param-util.h */, 404883E50E2F799B00CF7658 /* gtest-port.h */, F67D4F3D1C7F5D8B0017C729 /* gtest-port-arch.h */, 404883E60E2F799B00CF7658 /* gtest-string.h */, - 40899F4D0FFA7271000B29AE /* gtest-tuple.h */, 3BF6F29F0E79B5AD000F2EEE /* gtest-type-util.h */, ); path = internal; @@ -659,7 +648,6 @@ buildActionMask = 2147483647; files = ( 404884500E2F799B00CF7658 /* README.md in Resources */, - 404884AC0E2F7CD900CF7658 /* CHANGES in Resources */, 404884AD0E2F7CD900CF7658 /* CONTRIBUTORS in Resources */, 404884AE0E2F7CD900CF7658 /* LICENSE in Resources */, 40C84978101A36540083642A /* libgtest_main.a in Resources */, -- cgit v1.2.3 From 2ace910a3580033264043789f5d6002422292772 Mon Sep 17 00:00:00 2001 From: Gennadiy Civil Date: Wed, 2 Jan 2019 16:02:34 -0500 Subject: Revert "test, please ignore" This reverts commit 4665eee10a1d495aec9970fddf6231cf2339b1b7. --- newfile.txt | 1 - 1 file changed, 1 deletion(-) delete mode 100644 newfile.txt diff --git a/newfile.txt b/newfile.txt deleted file mode 100644 index 2a02d41c..00000000 --- a/newfile.txt +++ /dev/null @@ -1 +0,0 @@ -TEST -- cgit v1.2.3 From 8ed34e0f6b4e6af4710eefe59b746534c42f9af6 Mon Sep 17 00:00:00 2001 From: Gennadiy Civil Date: Wed, 2 Jan 2019 16:03:50 -0500 Subject: Remove outdated scripts --- googletest/scripts/common.py | 83 --- googletest/scripts/release_docs.py | 158 ---- googletest/scripts/upload.py | 1387 ------------------------------------ googletest/scripts/upload_gtest.py | 78 -- 4 files changed, 1706 deletions(-) delete mode 100644 googletest/scripts/common.py delete mode 100755 googletest/scripts/release_docs.py delete mode 100755 googletest/scripts/upload.py delete mode 100755 googletest/scripts/upload_gtest.py diff --git a/googletest/scripts/common.py b/googletest/scripts/common.py deleted file mode 100644 index 3c0347a7..00000000 --- a/googletest/scripts/common.py +++ /dev/null @@ -1,83 +0,0 @@ -# Copyright 2013 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. - -"""Shared utilities for writing scripts for Google Test/Mock.""" - -__author__ = 'wan@google.com (Zhanyong Wan)' - - -import os -import re - - -# Matches the line from 'svn info .' output that describes what SVN -# path the current local directory corresponds to. For example, in -# a googletest SVN workspace's trunk/test directory, the output will be: -# -# URL: https://googletest.googlecode.com/svn/trunk/test -_SVN_INFO_URL_RE = re.compile(r'^URL: https://(\w+)\.googlecode\.com/svn(.*)') - - -def GetCommandOutput(command): - """Runs the shell command and returns its stdout as a list of lines.""" - - f = os.popen(command, 'r') - lines = [line.strip() for line in f.readlines()] - f.close() - return lines - - -def GetSvnInfo(): - """Returns the project name and the current SVN workspace's root path.""" - - for line in GetCommandOutput('svn info .'): - m = _SVN_INFO_URL_RE.match(line) - if m: - project = m.group(1) # googletest or googlemock - rel_path = m.group(2) - root = os.path.realpath(rel_path.count('/') * '../') - return project, root - - return None, None - - -def GetSvnTrunk(): - """Returns the current SVN workspace's trunk root path.""" - - _, root = GetSvnInfo() - return root + '/trunk' if root else None - - -def IsInGTestSvn(): - project, _ = GetSvnInfo() - return project == 'googletest' - - -def IsInGMockSvn(): - project, _ = GetSvnInfo() - return project == 'googlemock' diff --git a/googletest/scripts/release_docs.py b/googletest/scripts/release_docs.py deleted file mode 100755 index 1291347f..00000000 --- a/googletest/scripts/release_docs.py +++ /dev/null @@ -1,158 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2013 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. - -"""Script for branching Google Test/Mock wiki pages for a new version. - -SYNOPSIS - release_docs.py NEW_RELEASE_VERSION - - Google Test and Google Mock's external user documentation is in - interlinked wiki files. When we release a new version of - Google Test or Google Mock, we need to branch the wiki files - such that users of a specific version of Google Test/Mock can - look up documenation relevant for that version. This script - automates that process by: - - - branching the current wiki pages (which document the - behavior of the SVN trunk head) to pages for the specified - version (e.g. branching FAQ.wiki to V2_6_FAQ.wiki when - NEW_RELEASE_VERSION is 2.6); - - updating the links in the branched files to point to the branched - version (e.g. a link in V2_6_FAQ.wiki that pointed to - Primer.wiki#Anchor will now point to V2_6_Primer.wiki#Anchor). - - NOTE: NEW_RELEASE_VERSION must be a NEW version number for - which the wiki pages don't yet exist; otherwise you'll get SVN - errors like "svn: Path 'V1_7_PumpManual.wiki' is not a - directory" when running the script. - -EXAMPLE - $ cd PATH/TO/GTEST_SVN_WORKSPACE/trunk - $ scripts/release_docs.py 2.6 # create wiki pages for v2.6 - $ svn status # verify the file list - $ svn diff # verify the file contents - $ svn commit -m "release wiki pages for v2.6" -""" - -__author__ = 'wan@google.com (Zhanyong Wan)' - -import os -import re -import sys - -import common - - -# Wiki pages that shouldn't be branched for every gtest/gmock release. -GTEST_UNVERSIONED_WIKIS = ['DevGuide.wiki'] -GMOCK_UNVERSIONED_WIKIS = [ - 'DesignDoc.wiki', - 'DevGuide.wiki', - 'KnownIssues.wiki' - ] - - -def DropWikiSuffix(wiki_filename): - """Removes the .wiki suffix (if any) from the given filename.""" - - return (wiki_filename[:-len('.wiki')] if wiki_filename.endswith('.wiki') - else wiki_filename) - - -class WikiBrancher(object): - """Branches ...""" - - def __init__(self, dot_version): - self.project, svn_root_path = common.GetSvnInfo() - if self.project not in ('googletest', 'googlemock'): - sys.exit('This script must be run in a gtest or gmock SVN workspace.') - self.wiki_dir = svn_root_path + '/wiki' - # Turn '2.6' to 'V2_6_'. - self.version_prefix = 'V' + dot_version.replace('.', '_') + '_' - self.files_to_branch = self.GetFilesToBranch() - page_names = [DropWikiSuffix(f) for f in self.files_to_branch] - # A link to Foo.wiki is in one of the following forms: - # [Foo words] - # [Foo#Anchor words] - # [http://code.google.com/.../wiki/Foo words] - # [http://code.google.com/.../wiki/Foo#Anchor words] - # We want to replace 'Foo' with 'V2_6_Foo' in the above cases. - self.search_for_re = re.compile( - # This regex matches either - # [Foo - # or - # /wiki/Foo - # followed by a space or a #, where Foo is the name of an - # unversioned wiki page. - r'(\[|/wiki/)(%s)([ #])' % '|'.join(page_names)) - self.replace_with = r'\1%s\2\3' % (self.version_prefix,) - - def GetFilesToBranch(self): - """Returns a list of .wiki file names that need to be branched.""" - - unversioned_wikis = (GTEST_UNVERSIONED_WIKIS if self.project == 'googletest' - else GMOCK_UNVERSIONED_WIKIS) - return [f for f in os.listdir(self.wiki_dir) - if (f.endswith('.wiki') and - not re.match(r'^V\d', f) and # Excluded versioned .wiki files. - f not in unversioned_wikis)] - - def BranchFiles(self): - """Branches the .wiki files needed to be branched.""" - - print 'Branching %d .wiki files:' % (len(self.files_to_branch),) - os.chdir(self.wiki_dir) - for f in self.files_to_branch: - command = 'svn cp %s %s%s' % (f, self.version_prefix, f) - print command - os.system(command) - - def UpdateLinksInBranchedFiles(self): - - for f in self.files_to_branch: - source_file = os.path.join(self.wiki_dir, f) - versioned_file = os.path.join(self.wiki_dir, self.version_prefix + f) - print 'Updating links in %s.' % (versioned_file,) - text = file(source_file, 'r').read() - new_text = self.search_for_re.sub(self.replace_with, text) - file(versioned_file, 'w').write(new_text) - - -def main(): - if len(sys.argv) != 2: - sys.exit(__doc__) - - brancher = WikiBrancher(sys.argv[1]) - brancher.BranchFiles() - brancher.UpdateLinksInBranchedFiles() - - -if __name__ == '__main__': - main() diff --git a/googletest/scripts/upload.py b/googletest/scripts/upload.py deleted file mode 100755 index c852e4c9..00000000 --- a/googletest/scripts/upload.py +++ /dev/null @@ -1,1387 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2007 Google Inc. -# -# 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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# 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. - -"""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 (output 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/googletest/scripts/upload_gtest.py b/googletest/scripts/upload_gtest.py deleted file mode 100755 index be19ae80..00000000 --- a/googletest/scripts/upload_gtest.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_gtest.py v0.1.0 -- uploads a Google Test patch for review. - -This simple wrapper passes all command line flags and ---cc=googletestframework@googlegroups.com to upload.py. - -USAGE: upload_gtest.py [options for upload.py] -""" - -__author__ = 'wan@google.com (Zhanyong Wan)' - -import os -import sys - -CC_FLAG = '--cc=' -GTEST_GROUP = 'googletestframework@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 Test 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 GTEST_GROUP not in cc_list: - cc_list.append(GTEST_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 + GTEST_GROUP) - - # Invokes upload.py with the modified command line flags. - os.execv(upload_py_path, upload_py_argv) - - -if __name__ == '__main__': - main() -- cgit v1.2.3 From f8b1c1af17750189b83c58f360c85268c0d95105 Mon Sep 17 00:00:00 2001 From: Abseil Team Date: Fri, 28 Dec 2018 06:03:51 -0500 Subject: Googletest export Remove the #ifs for old, unsupported and buggy compilers: * old versions of GCC & MSVC * Symbian PiperOrigin-RevId: 227116941 --- googlemock/include/gmock/gmock-actions.h | 5 --- googlemock/include/gmock/gmock-matchers.h | 39 ++++++++---------- googlemock/include/gmock/gmock-spec-builders.h | 13 +----- .../internal/gmock-generated-internal-utils.h | 14 +------ .../internal/gmock-generated-internal-utils.h.pump | 14 +------ .../include/gmock/internal/gmock-internal-utils.h | 29 +------------ googlemock/src/gmock-internal-utils.cc | 3 -- googlemock/src/gmock-spec-builders.cc | 3 -- googlemock/test/gmock-actions_test.cc | 10 ----- googlemock/test/gmock-function-mocker_test.cc | 14 ------- googlemock/test/gmock-internal-utils_test.cc | 7 ---- googlemock/test/gmock-matchers_test.cc | 23 ----------- googlemock/test/gmock-nice-strict_test.cc | 30 ++------------ googletest/include/gtest/gtest-message.h | 32 --------------- googletest/include/gtest/gtest-param-test.h | 7 +--- googletest/include/gtest/gtest-param-test.h.pump | 7 +--- googletest/include/gtest/gtest-printers.h | 2 +- googletest/include/gtest/gtest.h | 2 +- googletest/include/gtest/internal/gtest-internal.h | 39 +++++++++--------- .../include/gtest/internal/gtest-port-arch.h | 2 - googletest/include/gtest/internal/gtest-port.h | 47 +++------------------- googletest/src/gtest-filepath.cc | 3 -- googletest/src/gtest-internal-inl.h | 2 +- googletest/src/gtest.cc | 18 +++------ googletest/test/gtest_unittest.cc | 47 ++-------------------- 25 files changed, 67 insertions(+), 345 deletions(-) diff --git a/googlemock/include/gmock/gmock-actions.h b/googlemock/include/gmock/gmock-actions.h index 8b3c03b0..28141257 100644 --- a/googlemock/include/gmock/gmock-actions.h +++ b/googlemock/include/gmock/gmock-actions.h @@ -1140,10 +1140,6 @@ SetArgPointee(const T& x) { N, T, internal::IsAProtocolMessage::value>(x)); } -#if !((GTEST_GCC_VER_ && GTEST_GCC_VER_ < 40000) || GTEST_OS_SYMBIAN) -// This overload allows SetArgPointee() to accept a string literal. -// GCC prior to the version 4.0 and Symbian C++ compiler cannot distinguish -// this overload from the templated version and emit a compile error. template PolymorphicAction< internal::SetArgumentPointeeAction > @@ -1159,7 +1155,6 @@ SetArgPointee(const wchar_t* p) { return MakePolymorphicAction(internal::SetArgumentPointeeAction< N, const wchar_t*, false>(p)); } -#endif // The following version is DEPRECATED. template diff --git a/googlemock/include/gmock/gmock-matchers.h b/googlemock/include/gmock/gmock-matchers.h index f9ad3489..36ff2992 100644 --- a/googlemock/include/gmock/gmock-matchers.h +++ b/googlemock/include/gmock/gmock-matchers.h @@ -244,11 +244,8 @@ inline Matcher MatcherCast(const M& matcher) { // Implements SafeMatcherCast(). // -// We use an intermediate class to do the actual safe casting as Nokia's -// Symbian compiler cannot decide between -// template ... (M) and -// template ... (const Matcher&) -// for function templates but can for member function templates. +// FIXME: The intermediate SafeMatcherCastImpl class was introduced as a +// workaround for a compiler bug, and can now be removed. template class SafeMatcherCastImpl { public: @@ -1714,23 +1711,22 @@ class FieldMatcher { template bool MatchAndExplain(const T& value, MatchResultListener* listener) const { + // FIXME: The dispatch on std::is_pointer was introduced as a workaround for + // a compiler bug, and can now be removed. return MatchAndExplainImpl( - typename ::testing::internal:: - is_pointer::type(), - value, listener); + typename std::is_pointer::type(), value, + listener); } private: - // The first argument of MatchAndExplainImpl() is needed to help - // Symbian's C++ compiler choose which overload to use. Its type is - // true_type iff the Field() matcher is used to match a pointer. - bool MatchAndExplainImpl(false_type /* is_not_pointer */, const Class& obj, + bool MatchAndExplainImpl(std::false_type /* is_not_pointer */, + const Class& obj, MatchResultListener* listener) const { *listener << whose_field_ << "is "; return MatchPrintAndExplain(obj.*field_, matcher_, listener); } - bool MatchAndExplainImpl(true_type /* is_pointer */, const Class* p, + bool MatchAndExplainImpl(std::true_type /* is_pointer */, const Class* p, MatchResultListener* listener) const { if (p == nullptr) return false; @@ -1738,7 +1734,7 @@ class FieldMatcher { // Since *p has a field, it must be a class/struct/union type and // thus cannot be a pointer. Therefore we pass false_type() as // the first argument. - return MatchAndExplainImpl(false_type(), *p, listener); + return MatchAndExplainImpl(std::false_type(), *p, listener); } const FieldType Class::*field_; @@ -1785,16 +1781,13 @@ class PropertyMatcher { template bool MatchAndExplain(const T&value, MatchResultListener* listener) const { return MatchAndExplainImpl( - typename ::testing::internal:: - is_pointer::type(), - value, listener); + typename std::is_pointer::type(), value, + listener); } private: - // The first argument of MatchAndExplainImpl() is needed to help - // Symbian's C++ compiler choose which overload to use. Its type is - // true_type iff the Property() matcher is used to match a pointer. - bool MatchAndExplainImpl(false_type /* is_not_pointer */, const Class& obj, + bool MatchAndExplainImpl(std::false_type /* is_not_pointer */, + const Class& obj, MatchResultListener* listener) const { *listener << whose_property_ << "is "; // Cannot pass the return value (for example, int) to MatchPrintAndExplain, @@ -1803,7 +1796,7 @@ class PropertyMatcher { return MatchPrintAndExplain(result, matcher_, listener); } - bool MatchAndExplainImpl(true_type /* is_pointer */, const Class* p, + bool MatchAndExplainImpl(std::true_type /* is_pointer */, const Class* p, MatchResultListener* listener) const { if (p == nullptr) return false; @@ -1811,7 +1804,7 @@ class PropertyMatcher { // Since *p has a property method, it must be a class/struct/union // type and thus cannot be a pointer. Therefore we pass // false_type() as the first argument. - return MatchAndExplainImpl(false_type(), *p, listener); + return MatchAndExplainImpl(std::false_type(), *p, listener); } Property property_; diff --git a/googlemock/include/gmock/gmock-spec-builders.h b/googlemock/include/gmock/gmock-spec-builders.h index 3fe31734..9a54b3ae 100644 --- a/googlemock/include/gmock/gmock-spec-builders.h +++ b/googlemock/include/gmock/gmock-spec-builders.h @@ -301,12 +301,7 @@ class OnCallSpec : public UntypedOnCallSpecBase { const ArgumentMatcherTuple& matchers) : UntypedOnCallSpecBase(a_file, a_line), matchers_(matchers), - // By default, extra_matcher_ should match anything. However, - // we cannot initialize it with _ as that triggers a compiler - // bug in Symbian's C++ compiler (cannot decide between two - // overloaded constructors of Matcher). - extra_matcher_(A()) { - } + extra_matcher_(_) {} // Implements the .With() clause. OnCallSpec& With(const Matcher& m) { @@ -896,11 +891,7 @@ class TypedExpectation : public ExpectationBase { : ExpectationBase(a_file, a_line, a_source_text), owner_(owner), matchers_(m), - // By default, extra_matcher_ should match anything. However, - // we cannot initialize it with _ as that triggers a compiler - // bug in Symbian's C++ compiler (cannot decide between two - // overloaded constructors of Matcher). - extra_matcher_(A()), + extra_matcher_(_), repeated_action_(DoDefault()) {} ~TypedExpectation() override { diff --git a/googlemock/include/gmock/internal/gmock-generated-internal-utils.h b/googlemock/include/gmock/internal/gmock-generated-internal-utils.h index efa04629..eb85e266 100644 --- a/googlemock/include/gmock/internal/gmock-generated-internal-utils.h +++ b/googlemock/include/gmock/internal/gmock-generated-internal-utils.h @@ -43,6 +43,7 @@ #define GMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_GENERATED_INTERNAL_UTILS_H_ #include "gmock/internal/gmock-port.h" +#include "gtest/gtest.h" namespace testing { @@ -51,19 +52,6 @@ class Matcher; namespace internal { -// An IgnoredValue object can be implicitly constructed from ANY value. -// This is used in implementing the IgnoreResult(a) action. -class IgnoredValue { - public: - // This constructor template allows any value to be implicitly - // converted to IgnoredValue. The object has no data member and - // doesn't try to remember anything about the argument. We - // deliberately omit the 'explicit' keyword in order to allow the - // conversion to be implicit. - template - IgnoredValue(const T& /* ignored */) {} // NOLINT(runtime/explicit) -}; - // MatcherTuple::type is a tuple type where each field is a Matcher // for the corresponding field in tuple type T. template diff --git a/googlemock/include/gmock/internal/gmock-generated-internal-utils.h.pump b/googlemock/include/gmock/internal/gmock-generated-internal-utils.h.pump index 9962f6b3..6787905b 100644 --- a/googlemock/include/gmock/internal/gmock-generated-internal-utils.h.pump +++ b/googlemock/include/gmock/internal/gmock-generated-internal-utils.h.pump @@ -44,6 +44,7 @@ $var n = 10 $$ The maximum arity we support. #define GMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_GENERATED_INTERNAL_UTILS_H_ #include "gmock/internal/gmock-port.h" +#include "gtest/gtest.h" namespace testing { @@ -52,19 +53,6 @@ class Matcher; namespace internal { -// An IgnoredValue object can be implicitly constructed from ANY value. -// This is used in implementing the IgnoreResult(a) action. -class IgnoredValue { - public: - // This constructor template allows any value to be implicitly - // converted to IgnoredValue. The object has no data member and - // doesn't try to remember anything about the argument. We - // deliberately omit the 'explicit' keyword in order to allow the - // conversion to be implicit. - template - IgnoredValue(const T& /* ignored */) {} // NOLINT(runtime/explicit) -}; - // MatcherTuple::type is a tuple type where each field is a Matcher // for the corresponding field in tuple type T. template diff --git a/googlemock/include/gmock/internal/gmock-internal-utils.h b/googlemock/include/gmock/internal/gmock-internal-utils.h index 133fccef..3de3d545 100644 --- a/googlemock/include/gmock/internal/gmock-internal-utils.h +++ b/googlemock/include/gmock/internal/gmock-internal-utils.h @@ -92,16 +92,11 @@ inline const typename Pointer::element_type* GetRawPointer(const Pointer& p) { template inline Element* GetRawPointer(Element* p) { return p; } -// Symbian compilation can be done with wchar_t being either a native -// type or a typedef. Using Google Mock with OpenC without wchar_t -// should require the definition of _STLP_NO_WCHAR_T. -// // MSVC treats wchar_t as a native type usually, but treats it as the // same as unsigned short when the compiler option /Zc:wchar_t- is // specified. It defines _NATIVE_WCHAR_T_DEFINED symbol when wchar_t // is a native type. -#if (GTEST_OS_SYMBIAN && defined(_STLP_NO_WCHAR_T)) || \ - (defined(_MSC_VER) && !defined(_NATIVE_WCHAR_T_DEFINED)) +#if defined(_MSC_VER) && !defined(_NATIVE_WCHAR_T_DEFINED) // wchar_t is a typedef. #else # define GMOCK_WCHAR_T_IS_NATIVE_ 1 @@ -452,32 +447,10 @@ class StlContainerView { static const_reference ConstReference(const Element (&array)[N]) { // Ensures that Element is not a const type. testing::StaticAssertTypeEq(); -#if GTEST_OS_SYMBIAN - // The Nokia Symbian compiler confuses itself in template instantiation - // for this call without the cast to Element*: - // function call '[testing::internal::NativeArray].NativeArray( - // {lval} const char *[4], long, testing::internal::RelationToSource)' - // does not match - // 'testing::internal::NativeArray::NativeArray( - // char *const *, unsigned int, testing::internal::RelationToSource)' - // (instantiating: 'testing::internal::ContainsMatcherImpl - // ::Matches(const char * (&)[4]) const') - // (instantiating: 'testing::internal::StlContainerView:: - // ConstReference(const char * (&)[4])') - // (and though the N parameter type is mismatched in the above explicit - // conversion of it doesn't help - only the conversion of the array). - return type(const_cast(&array[0]), N, - RelationToSourceReference()); -#else return type(array, N, RelationToSourceReference()); -#endif // GTEST_OS_SYMBIAN } static type Copy(const Element (&array)[N]) { -#if GTEST_OS_SYMBIAN - return type(const_cast(&array[0]), N, RelationToSourceCopy()); -#else return type(array, N, RelationToSourceCopy()); -#endif // GTEST_OS_SYMBIAN } }; diff --git a/googlemock/src/gmock-internal-utils.cc b/googlemock/src/gmock-internal-utils.cc index 937d830a..15946623 100644 --- a/googlemock/src/gmock-internal-utils.cc +++ b/googlemock/src/gmock-internal-utils.cc @@ -154,9 +154,6 @@ GTEST_API_ void Log(LogSeverity severity, const std::string& message, // Ensures that logs from different threads don't interleave. MutexLock l(&g_log_mutex); - // "using ::std::cout;" doesn't work with Symbian's STLport, where cout is a - // macro. - if (severity == kWarning) { // Prints a GMOCK WARNING marker to make the warnings easily searchable. std::cout << "\nGMOCK WARNING:"; diff --git a/googlemock/src/gmock-spec-builders.cc b/googlemock/src/gmock-spec-builders.cc index 5db774ed..b3d0cca2 100644 --- a/googlemock/src/gmock-spec-builders.cc +++ b/googlemock/src/gmock-spec-builders.cc @@ -592,9 +592,6 @@ class MockObjectRegistry { // object alive. Therefore we report any living object as test // failure, unless the user explicitly asked us to ignore it. ~MockObjectRegistry() { - // "using ::std::cout;" doesn't work with Symbian's STLport, where cout is - // a macro. - if (!GMOCK_FLAG(catch_leaked_mocks)) return; diff --git a/googlemock/test/gmock-actions_test.cc b/googlemock/test/gmock-actions_test.cc index f27d55aa..6c03b2e9 100644 --- a/googlemock/test/gmock-actions_test.cc +++ b/googlemock/test/gmock-actions_test.cc @@ -444,19 +444,12 @@ class IsNotZero : public ActionInterface { // NOLINT } }; -#if !GTEST_OS_SYMBIAN -// Compiling this test on Nokia's Symbian compiler fails with: -// 'Result' is not a member of class 'testing::internal::Function' -// (point of instantiation: '@unnamed@gmock_actions_test_cc@:: -// ActionTest_CanBeConvertedToOtherActionType_Test::TestBody()') -// with no obvious fix. TEST(ActionTest, CanBeConvertedToOtherActionType) { const Action a1(new IsNotZero); // NOLINT const Action a2 = Action(a1); // NOLINT EXPECT_EQ(1, a2.Perform(std::make_tuple('a'))); EXPECT_EQ(0, a2.Perform(std::make_tuple('\0'))); } -#endif // !GTEST_OS_SYMBIAN // The following two classes are for testing MakePolymorphicAction(). @@ -805,9 +798,7 @@ TEST(SetArgPointeeTest, SetsTheNthPointee) { EXPECT_EQ('a', ch); } -#if !((GTEST_GCC_VER_ && GTEST_GCC_VER_ < 40000) || GTEST_OS_SYMBIAN) // Tests that SetArgPointee() accepts a string literal. -// GCC prior to v4.0 and the Symbian compiler do not support this. TEST(SetArgPointeeTest, AcceptsStringLiteral) { typedef void MyFunction(std::string*, const char**); Action a = SetArgPointee<0>("hi"); @@ -841,7 +832,6 @@ TEST(SetArgPointeeTest, AcceptsWideStringLiteral) { # endif } -#endif // Tests that SetArgPointee() accepts a char pointer. TEST(SetArgPointeeTest, AcceptsCharPointer) { diff --git a/googlemock/test/gmock-function-mocker_test.cc b/googlemock/test/gmock-function-mocker_test.cc index 294b21d2..f29433f5 100644 --- a/googlemock/test/gmock-function-mocker_test.cc +++ b/googlemock/test/gmock-function-mocker_test.cc @@ -45,13 +45,6 @@ #include "gmock/gmock.h" #include "gtest/gtest.h" -// There is a bug in MSVC (fixed in VS 2008) that prevents creating a -// mock for a function with const arguments, so we don't test such -// cases for MSVC versions older than 2008. -#if !GTEST_OS_WINDOWS || (_MSC_VER >= 1500) -# define GMOCK_ALLOWS_CONST_PARAM_FUNCTIONS -#endif // !GTEST_OS_WINDOWS || (_MSC_VER >= 1500) - namespace testing { namespace gmock_function_mocker_test { @@ -84,9 +77,7 @@ class FooInterface { virtual bool TakesNonConstReference(int& n) = 0; // NOLINT virtual std::string TakesConstReference(const int& n) = 0; -#ifdef GMOCK_ALLOWS_CONST_PARAM_FUNCTIONS virtual bool TakesConst(const int x) = 0; -#endif // GMOCK_ALLOWS_CONST_PARAM_FUNCTIONS virtual int OverloadedOnArgumentNumber() = 0; virtual int OverloadedOnArgumentNumber(int n) = 0; @@ -137,10 +128,7 @@ class MockFoo : public FooInterface { MOCK_METHOD(bool, TakesNonConstReference, (int&)); // NOLINT MOCK_METHOD(std::string, TakesConstReference, (const int&)); - -#ifdef GMOCK_ALLOWS_CONST_PARAM_FUNCTIONS MOCK_METHOD(bool, TakesConst, (const int)); // NOLINT -#endif // Tests that the function return type can contain unprotected comma. MOCK_METHOD((std::map), ReturnTypeWithComma, (), ()); @@ -248,7 +236,6 @@ TEST_F(MockMethodFunctionMockerTest, MocksFunctionWithConstReferenceArgument) { EXPECT_EQ("Hello", foo_->TakesConstReference(a)); } -#ifdef GMOCK_ALLOWS_CONST_PARAM_FUNCTIONS // Tests mocking a function that takes a const variable. TEST_F(MockMethodFunctionMockerTest, MocksFunctionWithConstArgument) { EXPECT_CALL(mock_foo_, TakesConst(Lt(10))) @@ -256,7 +243,6 @@ TEST_F(MockMethodFunctionMockerTest, MocksFunctionWithConstArgument) { EXPECT_FALSE(foo_->TakesConst(5)); } -#endif // GMOCK_ALLOWS_CONST_PARAM_FUNCTIONS // Tests mocking functions overloaded on the number of arguments. TEST_F(MockMethodFunctionMockerTest, MocksFunctionsOverloadedOnArgumentNumber) { diff --git a/googlemock/test/gmock-internal-utils_test.cc b/googlemock/test/gmock-internal-utils_test.cc index 4c36cfb8..b322f2d1 100644 --- a/googlemock/test/gmock-internal-utils_test.cc +++ b/googlemock/test/gmock-internal-utils_test.cc @@ -145,7 +145,6 @@ TEST(GetRawPointerTest, WorksForSmartPointers) { TEST(GetRawPointerTest, WorksForRawPointers) { int* p = nullptr; - // Don't use EXPECT_EQ as no NULL-testing magic on Symbian. EXPECT_TRUE(nullptr == GetRawPointer(p)); int n = 1; EXPECT_EQ(&n, GetRawPointer(&n)); @@ -521,12 +520,6 @@ TEST(TypeTraitsTest, is_reference) { EXPECT_TRUE(is_reference::value); } -TEST(TypeTraitsTest, is_pointer) { - EXPECT_FALSE(is_pointer::value); - EXPECT_FALSE(is_pointer::value); - EXPECT_TRUE(is_pointer::value); -} - TEST(TypeTraitsTest, type_equals) { EXPECT_FALSE((type_equals::value)); EXPECT_FALSE((type_equals::value)); diff --git a/googlemock/test/gmock-matchers_test.cc b/googlemock/test/gmock-matchers_test.cc index 03fa75b1..a35942d7 100644 --- a/googlemock/test/gmock-matchers_test.cc +++ b/googlemock/test/gmock-matchers_test.cc @@ -1167,20 +1167,10 @@ TEST(IsNullTest, MatchesNullPointer) { EXPECT_TRUE(m2.Matches(p2)); EXPECT_FALSE(m2.Matches("hi")); -#if !GTEST_OS_SYMBIAN - // Nokia's Symbian compiler generates: - // gmock-matchers.h: ambiguous access to overloaded function - // gmock-matchers.h: 'testing::Matcher::Matcher(void *)' - // gmock-matchers.h: 'testing::Matcher::Matcher(const testing:: - // MatcherInterface *)' - // gmock-matchers.h: (point of instantiation: 'testing:: - // gmock_matchers_test::IsNullTest_MatchesNullPointer_Test::TestBody()') - // gmock-matchers.h: (instantiating: 'testing::PolymorphicMatc Matcher m3 = IsNull(); void* p3 = nullptr; EXPECT_TRUE(m3.Matches(p3)); EXPECT_FALSE(m3.Matches(reinterpret_cast(0xbeef))); -#endif } TEST(IsNullTest, StdFunction) { @@ -3168,20 +3158,8 @@ TEST(MatcherAssertionTest, WorksForByRefArguments) { "Actual: 0" + OfType("int") + ", which is located @"); } -#if !GTEST_OS_SYMBIAN // Tests that ASSERT_THAT() and EXPECT_THAT() work when the matcher is // monomorphic. - -// ASSERT_THAT("hello", starts_with_he) fails to compile with Nokia's -// Symbian compiler: it tries to compile -// template class MatcherCastImpl { ... -// virtual bool MatchAndExplain(T x, ...) const { -// return source_matcher_.MatchAndExplain(static_cast(x), ...); -// with U == string and T == const char* -// With ASSERT_THAT("hello"...) changed to ASSERT_THAT(string("hello") ... ) -// the compiler silently crashes with no output. -// If MatcherCastImpl is changed to use U(x) instead of static_cast(x) -// the code compiles but the converted string is bogus. TEST(MatcherAssertionTest, WorksForMonomorphicMatcher) { Matcher starts_with_he = StartsWith("he"); ASSERT_THAT("hello", starts_with_he); @@ -3199,7 +3177,6 @@ TEST(MatcherAssertionTest, WorksForMonomorphicMatcher) { "Expected: is > 5\n" " Actual: 5" + OfType("int")); } -#endif // !GTEST_OS_SYMBIAN // Tests floating-point matchers. template diff --git a/googlemock/test/gmock-nice-strict_test.cc b/googlemock/test/gmock-nice-strict_test.cc index 455e591c..0a201ed7 100644 --- a/googlemock/test/gmock-nice-strict_test.cc +++ b/googlemock/test/gmock-nice-strict_test.cc @@ -294,21 +294,13 @@ TEST(NiceMockTest, MoveOnlyConstructor) { NiceMock nice_baz(MockBaz::MoveOnly{}); } -#if !GTEST_OS_SYMBIAN && !GTEST_OS_WINDOWS_MOBILE // Tests that NiceMock compiles where Mock is a user-defined -// class (as opposed to ::testing::Mock). We had to work around an -// MSVC 8.0 bug that caused the symbol Mock used in the definition of -// NiceMock to be looked up in the wrong context, and this test -// ensures that our fix works. -// -// We have to skip this test on Symbian and Windows Mobile, as it -// causes the program to crash there, for reasons unclear to us yet. +// class (as opposed to ::testing::Mock). TEST(NiceMockTest, AcceptsClassNamedMock) { NiceMock< ::Mock> nice; EXPECT_CALL(nice, DoThis()); nice.DoThis(); } -#endif // !GTEST_OS_SYMBIAN && !GTEST_OS_WINDOWS_MOBILE TEST(NiceMockTest, IsNaggy_IsNice_IsStrict) { NiceMock nice_foo; @@ -405,21 +397,13 @@ TEST(NaggyMockTest, MoveOnlyConstructor) { NaggyMock naggy_baz(MockBaz::MoveOnly{}); } -#if !GTEST_OS_SYMBIAN && !GTEST_OS_WINDOWS_MOBILE // Tests that NaggyMock compiles where Mock is a user-defined -// class (as opposed to ::testing::Mock). We had to work around an -// MSVC 8.0 bug that caused the symbol Mock used in the definition of -// NaggyMock to be looked up in the wrong context, and this test -// ensures that our fix works. -// -// We have to skip this test on Symbian and Windows Mobile, as it -// causes the program to crash there, for reasons unclear to us yet. +// class (as opposed to ::testing::Mock). TEST(NaggyMockTest, AcceptsClassNamedMock) { NaggyMock< ::Mock> naggy; EXPECT_CALL(naggy, DoThis()); naggy.DoThis(); } -#endif // !GTEST_OS_SYMBIAN && !GTEST_OS_WINDOWS_MOBILE TEST(NaggyMockTest, IsNaggy_IsNice_IsStrict) { NaggyMock naggy_foo; @@ -497,21 +481,13 @@ TEST(StrictMockTest, MoveOnlyConstructor) { StrictMock strict_baz(MockBaz::MoveOnly{}); } -#if !GTEST_OS_SYMBIAN && !GTEST_OS_WINDOWS_MOBILE // Tests that StrictMock compiles where Mock is a user-defined -// class (as opposed to ::testing::Mock). We had to work around an -// MSVC 8.0 bug that caused the symbol Mock used in the definition of -// StrictMock to be looked up in the wrong context, and this test -// ensures that our fix works. -// -// We have to skip this test on Symbian and Windows Mobile, as it -// causes the program to crash there, for reasons unclear to us yet. +// class (as opposed to ::testing::Mock). TEST(StrictMockTest, AcceptsClassNamedMock) { StrictMock< ::Mock> strict; EXPECT_CALL(strict, DoThis()); strict.DoThis(); } -#endif // !GTEST_OS_SYMBIAN && !GTEST_OS_WINDOWS_MOBILE TEST(StrictMockTest, IsNaggy_IsNice_IsStrict) { StrictMock strict_foo; diff --git a/googletest/include/gtest/gtest-message.h b/googletest/include/gtest/gtest-message.h index 79d208a6..cd9319d6 100644 --- a/googletest/include/gtest/gtest-message.h +++ b/googletest/include/gtest/gtest-message.h @@ -107,14 +107,6 @@ class GTEST_API_ Message { *ss_ << str; } -#if GTEST_OS_SYMBIAN - // Streams a value (either a pointer or not) to this object. - template - inline Message& operator <<(const T& value) { - StreamHelper(typename internal::is_pointer::type(), value); - return *this; - } -#else // Streams a non-pointer value to this object. template inline Message& operator <<(const T& val) { @@ -159,7 +151,6 @@ class GTEST_API_ Message { } return *this; } -#endif // GTEST_OS_SYMBIAN // Since the basic IO manipulators are overloaded for both narrow // and wide streams, we have to provide this specialized definition @@ -201,29 +192,6 @@ class GTEST_API_ Message { std::string GetString() const; private: -#if GTEST_OS_SYMBIAN - // These are needed as the Nokia Symbian Compiler cannot decide between - // const T& and const T* in a function template. The Nokia compiler _can_ - // decide between class template specializations for T and T*, so a - // tr1::type_traits-like is_pointer works, and we can overload on that. - template - inline void StreamHelper(internal::true_type /*is_pointer*/, T* pointer) { - if (pointer == nullptr) { - *ss_ << "(null)"; - } else { - *ss_ << pointer; - } - } - template - inline void StreamHelper(internal::false_type /*is_pointer*/, - const T& value) { - // See the comments in Message& operator <<(const T&) above for why - // we need this using statement. - using ::operator <<; - *ss_ << value; - } -#endif // GTEST_OS_SYMBIAN - // We'll hold the text streamed to this object here. const std::unique_ptr< ::std::stringstream> ss_; diff --git a/googletest/include/gtest/gtest-param-test.h b/googletest/include/gtest/gtest-param-test.h index 8cc3dd74..2b27251f 100644 --- a/googletest/include/gtest/gtest-param-test.h +++ b/googletest/include/gtest/gtest-param-test.h @@ -178,15 +178,12 @@ TEST_P(DerivedTest, DoesBlah) { #endif // 0 -#include "gtest/internal/gtest-port.h" - -#if !GTEST_OS_SYMBIAN -# include -#endif +#include #include "gtest/internal/gtest-internal.h" #include "gtest/internal/gtest-param-util.h" #include "gtest/internal/gtest-param-util-generated.h" +#include "gtest/internal/gtest-port.h" namespace testing { diff --git a/googletest/include/gtest/gtest-param-test.h.pump b/googletest/include/gtest/gtest-param-test.h.pump index bb848ec3..a278330c 100644 --- a/googletest/include/gtest/gtest-param-test.h.pump +++ b/googletest/include/gtest/gtest-param-test.h.pump @@ -177,15 +177,12 @@ TEST_P(DerivedTest, DoesBlah) { #endif // 0 -#include "gtest/internal/gtest-port.h" - -#if !GTEST_OS_SYMBIAN -# include -#endif +#include #include "gtest/internal/gtest-internal.h" #include "gtest/internal/gtest-param-util.h" #include "gtest/internal/gtest-param-util-generated.h" +#include "gtest/internal/gtest-port.h" namespace testing { diff --git a/googletest/include/gtest/gtest-printers.h b/googletest/include/gtest/gtest-printers.h index 54674697..b79ddf4c 100644 --- a/googletest/include/gtest/gtest-printers.h +++ b/googletest/include/gtest/gtest-printers.h @@ -514,7 +514,7 @@ void PrintTo(const T& value, ::std::ostream* os) { (sizeof(IsContainerTest(0)) == sizeof(IsContainer)) && !IsRecursiveContainer::value ? kPrintContainer - : !is_pointer::value + : !std::is_pointer::value ? kPrintOther : std::is_function::type>::value ? kPrintFunctionPointer diff --git a/googletest/include/gtest/gtest.h b/googletest/include/gtest/gtest.h index cefa564c..27538ac8 100644 --- a/googletest/include/gtest/gtest.h +++ b/googletest/include/gtest/gtest.h @@ -1527,7 +1527,7 @@ class EqHelper { // expands to Compare("", "", NULL, my_ptr), which requires a conversion // to match the Secret* in the other overload, which would otherwise make // this template match better. - typename EnableIf::value>::type* = nullptr) { + typename EnableIf::value>::type* = nullptr) { return CmpHelperEQ(lhs_expression, rhs_expression, lhs, rhs); } diff --git a/googletest/include/gtest/internal/gtest-internal.h b/googletest/include/gtest/internal/gtest-internal.h index f66a5c1b..22d20006 100644 --- a/googletest/include/gtest/internal/gtest-internal.h +++ b/googletest/include/gtest/internal/gtest-internal.h @@ -106,12 +106,22 @@ class UnitTestImpl; // Opaque implementation of UnitTest // stack trace. GTEST_API_ extern const char kStackTraceMarker[]; +// An IgnoredValue object can be implicitly constructed from ANY value. +class IgnoredValue { + public: + // This constructor template allows any value to be implicitly + // converted to IgnoredValue. The object has no data member and + // doesn't try to remember anything about the argument. We + // deliberately omit the 'explicit' keyword in order to allow the + // conversion to be implicit. + template + IgnoredValue(const T& /* ignored */) {} // NOLINT(runtime/explicit) +}; + // Two overloaded helpers for checking at compile time whether an // expression is a null pointer literal (i.e. NULL or any 0-valued -// compile-time integral constant). Their return values have -// different sizes, so we can use sizeof() to test which version is -// picked by the compiler. These helpers have no implementations, as -// we only need their signatures. +// compile-time integral constant). These helpers have no +// implementations, as we only need their signatures. // // Given IsNullLiteralHelper(x), the compiler will pick the first // version if x can be implicitly converted to Secret*, and pick the @@ -120,20 +130,13 @@ GTEST_API_ extern const char kStackTraceMarker[]; // a null pointer literal. Therefore, we know that x is a null // pointer literal if and only if the first version is picked by the // compiler. -char IsNullLiteralHelper(Secret* p); -char (&IsNullLiteralHelper(...))[2]; // NOLINT - -// A compile-time bool constant that is true if and only if x is a -// null pointer literal (i.e. NULL or any 0-valued compile-time -// integral constant). -#ifdef GTEST_ELLIPSIS_NEEDS_POD_ -// We lose support for NULL detection where the compiler doesn't like -// passing non-POD classes through ellipsis (...). -# define GTEST_IS_NULL_LITERAL_(x) false -#else -# define GTEST_IS_NULL_LITERAL_(x) \ - (sizeof(::testing::internal::IsNullLiteralHelper(x)) == 1) -#endif // GTEST_ELLIPSIS_NEEDS_POD_ +std::true_type IsNullLiteralHelper(Secret*); +std::false_type IsNullLiteralHelper(IgnoredValue); + +// A compile-time bool constant that is true if and only if x is a null pointer +// literal (i.e. nullptr, NULL or any 0-valued compile-time integral constant). +#define GTEST_IS_NULL_LITERAL_(x) \ + decltype(::testing::internal::IsNullLiteralHelper(x))::value // Appends the user-supplied message to the Google-Test-generated message. GTEST_API_ std::string AppendUserMessage( diff --git a/googletest/include/gtest/internal/gtest-port-arch.h b/googletest/include/gtest/internal/gtest-port-arch.h index 4f2b87ba..2687d14c 100644 --- a/googletest/include/gtest/internal/gtest-port-arch.h +++ b/googletest/include/gtest/internal/gtest-port-arch.h @@ -41,8 +41,6 @@ # elif defined(__MINGW__) || defined(__MINGW32__) || defined(__MINGW64__) # define GTEST_OS_WINDOWS_MINGW 1 # define GTEST_OS_WINDOWS 1 -#elif defined __SYMBIAN32__ -# define GTEST_OS_SYMBIAN 1 #elif defined _WIN32 # define GTEST_OS_WINDOWS 1 # ifdef _WIN32_WCE diff --git a/googletest/include/gtest/internal/gtest-port.h b/googletest/include/gtest/internal/gtest-port.h index 97532666..12c64e78 100644 --- a/googletest/include/gtest/internal/gtest-port.h +++ b/googletest/include/gtest/internal/gtest-port.h @@ -130,7 +130,6 @@ // GTEST_OS_OS2 - OS/2 // GTEST_OS_QNX - QNX // GTEST_OS_SOLARIS - Sun Solaris -// GTEST_OS_SYMBIAN - Symbian // GTEST_OS_WINDOWS - Windows (Desktop, MinGW, or Mobile) // GTEST_OS_WINDOWS_DESKTOP - Windows Desktop // GTEST_OS_WINDOWS_MINGW - MinGW @@ -175,7 +174,6 @@ // define themselves. // GTEST_USES_SIMPLE_RE - our own simple regex is used; // the above RE\b(s) are mutually exclusive. -// GTEST_CAN_COMPARE_NULL - accepts untyped NULL in EXPECT_EQ(). // Misc public macros // ------------------ @@ -206,7 +204,6 @@ // - synchronization primitives. // // Template meta programming: -// is_pointer - as in TR1; needed on Symbian and IBM XL C/C++ only. // IteratorTraits - partial implementation of std::iterator_traits, which // is not available in libCstd when compiled with Sun C++. // @@ -492,7 +489,7 @@ typedef struct _RTL_CRITICAL_SECTION GTEST_CRITICAL_SECTION; # endif // Starting with version 4.3.2, gcc defines __GXX_RTTI iff RTTI is enabled. -# elif defined(__GNUC__) && (GTEST_GCC_VER_ >= 40302) +# elif defined(__GNUC__) # ifdef __GXX_RTTI // When building against STLport with the Android NDK and with @@ -595,12 +592,11 @@ 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_SYMBIAN || \ - GTEST_OS_WINDOWS_PHONE || GTEST_OS_WINDOWS_RT +# if GTEST_OS_WINDOWS_MOBILE || GTEST_OS_WINDOWS_PHONE || GTEST_OS_WINDOWS_RT # define GTEST_HAS_STREAM_REDIRECTION 0 # else # define GTEST_HAS_STREAM_REDIRECTION 1 -# endif // !GTEST_OS_WINDOWS_MOBILE && !GTEST_OS_SYMBIAN +# endif // !GTEST_OS_WINDOWS_MOBILE #endif // GTEST_HAS_STREAM_REDIRECTION // Determines whether to support death tests. @@ -626,8 +622,7 @@ typedef struct _RTL_CRITICAL_SECTION GTEST_CRITICAL_SECTION; // Determines whether the system compiler uses UTF-16 for encoding wide strings. #define GTEST_WIDE_STRING_USES_UTF16_ \ - (GTEST_OS_WINDOWS || GTEST_OS_CYGWIN || GTEST_OS_SYMBIAN || \ - GTEST_OS_AIX || GTEST_OS_OS2) + (GTEST_OS_WINDOWS || GTEST_OS_CYGWIN || GTEST_OS_AIX || GTEST_OS_OS2) // Determines whether test results can be streamed to a socket. #if GTEST_OS_LINUX @@ -706,11 +701,11 @@ typedef struct _RTL_CRITICAL_SECTION GTEST_CRITICAL_SECTION; // following the argument list: // // Sprocket* AllocateSprocket() GTEST_MUST_USE_RESULT_; -#if defined(__GNUC__) && (GTEST_GCC_VER_ >= 30400) && !defined(COMPILER_ICC) +#if defined(__GNUC__) && !defined(COMPILER_ICC) # define GTEST_MUST_USE_RESULT_ __attribute__ ((warn_unused_result)) #else # define GTEST_MUST_USE_RESULT_ -#endif // __GNUC__ && (GTEST_GCC_VER_ >= 30400) && !COMPILER_ICC +#endif // __GNUC__ && !COMPILER_ICC // MS C++ compiler emits warning when a conditional expression is compile time // constant. In some contexts this warning is false positive and needs to be @@ -1960,29 +1955,6 @@ class GTEST_API_ ThreadLocal { // we cannot detect it. GTEST_API_ size_t GetThreadCount(); -// Passing non-POD classes through ellipsis (...) crashes the ARM -// compiler and generates a warning in Sun Studio before 12u4. The Nokia Symbian -// and the IBM XL C/C++ compiler try to instantiate a copy constructor -// for objects passed through ellipsis (...), failing for uncopyable -// objects. We define this to ensure that only POD is passed through -// ellipsis on these systems. -#if defined(__SYMBIAN32__) || defined(__IBMCPP__) || \ - (defined(__SUNPRO_CC) && __SUNPRO_CC < 0x5130) -// We lose support for NULL detection where the compiler doesn't like -// passing non-POD classes through ellipsis (...). -# define GTEST_ELLIPSIS_NEEDS_POD_ 1 -#else -# define GTEST_CAN_COMPARE_NULL 1 -#endif - -// The Nokia Symbian and IBM XL C/C++ compilers cannot decide between -// const T& and const T* in a function template. These compilers -// _can_ decide between class template specializations for T and T*, -// so a tr1::type_traits-like is_pointer works. -#if defined(__SYMBIAN32__) || defined(__IBMCPP__) -# define GTEST_NEEDS_IS_POINTER_ 1 -#endif - template struct bool_constant { typedef bool_constant type; @@ -1999,13 +1971,6 @@ struct is_same : public false_type {}; template struct is_same : public true_type {}; - -template -struct is_pointer : public false_type {}; - -template -struct is_pointer : public true_type {}; - template struct IteratorTraits { typedef typename Iterator::value_type value_type; diff --git a/googletest/src/gtest-filepath.cc b/googletest/src/gtest-filepath.cc index d708b337..0b71ad30 100644 --- a/googletest/src/gtest-filepath.cc +++ b/googletest/src/gtest-filepath.cc @@ -38,9 +38,6 @@ #elif GTEST_OS_WINDOWS # include # include -#elif GTEST_OS_SYMBIAN -// Symbian OpenC has PATH_MAX in sys/syslimits.h -# include #else # include # include // Some Linux distributions define PATH_MAX here. diff --git a/googletest/src/gtest-internal-inl.h b/googletest/src/gtest-internal-inl.h index 55d3a694..262eb36b 100644 --- a/googletest/src/gtest-internal-inl.h +++ b/googletest/src/gtest-internal-inl.h @@ -231,7 +231,7 @@ GTEST_API_ std::string CodePointToUtf8(UInt32 code_point); // Converts a wide string to a narrow string in UTF-8 encoding. // The wide string is assumed to have the following encoding: -// UTF-16 if sizeof(wchar_t) == 2 (on Windows, Cygwin, Symbian OS) +// UTF-16 if sizeof(wchar_t) == 2 (on Windows, Cygwin) // UTF-32 if sizeof(wchar_t) == 4 (on Linux) // Parameter str points to a null-terminated wide string. // Parameter num_chars may additionally limit the number diff --git a/googletest/src/gtest.cc b/googletest/src/gtest.cc index 34641af3..641032a3 100644 --- a/googletest/src/gtest.cc +++ b/googletest/src/gtest.cc @@ -68,10 +68,6 @@ # include // NOLINT # include -#elif GTEST_OS_SYMBIAN -# define GTEST_HAS_GETTIMEOFDAY_ 1 -# include // NOLINT - #elif GTEST_OS_ZOS # define GTEST_HAS_GETTIMEOFDAY_ 1 # include // NOLINT @@ -1827,7 +1823,7 @@ std::string CodePointToUtf8(UInt32 code_point) { // The following two functions only make sense if the system // uses UTF-16 for wide string encoding. All supported systems -// with 16 bit wchar_t (Windows, Cygwin, Symbian OS) do use UTF-16. +// with 16 bit wchar_t (Windows, Cygwin) do use UTF-16. // Determines if the arguments constitute UTF-16 surrogate pair // and thus should be combined into a single Unicode code point @@ -1850,7 +1846,7 @@ inline UInt32 CreateCodePointFromUtf16SurrogatePair(wchar_t first, // Converts a wide string to a narrow string in UTF-8 encoding. // The wide string is assumed to have the following encoding: -// UTF-16 if sizeof(wchar_t) == 2 (on Windows, Cygwin, Symbian OS) +// UTF-16 if sizeof(wchar_t) == 2 (on Windows, Cygwin) // UTF-32 if sizeof(wchar_t) == 4 (on Linux) // Parameter str points to a null-terminated wide string. // Parameter num_chars may additionally limit the number @@ -3034,15 +3030,14 @@ void ColoredPrintf(GTestColor color, const char* fmt, ...) { va_list args; va_start(args, fmt); -#if GTEST_OS_WINDOWS_MOBILE || GTEST_OS_SYMBIAN || GTEST_OS_ZOS || \ - GTEST_OS_IOS || GTEST_OS_WINDOWS_PHONE || GTEST_OS_WINDOWS_RT +#if GTEST_OS_WINDOWS_MOBILE || GTEST_OS_ZOS || GTEST_OS_IOS || \ + GTEST_OS_WINDOWS_PHONE || GTEST_OS_WINDOWS_RT const bool use_color = AlwaysFalse(); #else static const bool in_color_mode = ShouldUseColor(posix::IsATTY(posix::FileNo(stdout)) != 0); const bool use_color = in_color_mode && (color != COLOR_DEFAULT); -#endif // GTEST_OS_WINDOWS_MOBILE || GTEST_OS_SYMBIAN || GTEST_OS_ZOS - // The '!= 0' comparison is necessary to satisfy MSVC 7.1. +#endif // GTEST_OS_WINDOWS_MOBILE || GTEST_OS_ZOS if (!use_color) { vprintf(fmt, args); @@ -4723,8 +4718,7 @@ void UnitTest::AddTestPartResult( #else // Dereference nullptr through a volatile pointer to prevent the compiler // from removing. We use this rather than abort() or __builtin_trap() for - // portability: Symbian doesn't implement abort() well, and some debuggers - // don't correctly trap abort(). + // portability: some debuggers don't correctly trap abort(). *static_cast(nullptr) = 1; #endif // GTEST_OS_WINDOWS } else if (GTEST_FLAG(throw_on_failure)) { diff --git a/googletest/test/gtest_unittest.cc b/googletest/test/gtest_unittest.cc index 6d9bd347..3da83556 100644 --- a/googletest/test/gtest_unittest.cc +++ b/googletest/test/gtest_unittest.cc @@ -511,8 +511,6 @@ TEST_F(FormatEpochTimeInMillisAsIso8601Test, PrintsEpochStart) { EXPECT_EQ("1970-01-01T00:00:00", FormatEpochTimeInMillisAsIso8601(0)); } -#if GTEST_CAN_COMPARE_NULL - # ifdef __BORLANDC__ // Silences warnings: "Condition is always true", "Unreachable code" # pragma option push -w-ccc -w-rch @@ -541,7 +539,6 @@ TEST(NullLiteralTest, IsFalseForNonNullLiterals) { # pragma option pop # endif -#endif // GTEST_CAN_COMPARE_NULL // // Tests CodePointToUtf8(). @@ -586,7 +583,7 @@ TEST(CodePointToUtf8Test, CanEncode12To16Bits) { #if !GTEST_WIDE_STRING_USES_UTF16_ // Tests in this group require a wchar_t to hold > 16 bits, and thus -// are skipped on Windows, Cygwin, and Symbian, where a wchar_t is +// are skipped on Windows, and Cygwin, where a wchar_t is // 16-bit wide. This code may not compile on those systems. // Tests that Unicode code-points that have 17 to 21 bits are encoded @@ -2822,8 +2819,6 @@ TEST_F(FloatTest, LargeDiff) { TEST_F(FloatTest, Infinity) { EXPECT_FLOAT_EQ(values_.infinity, values_.close_to_infinity); EXPECT_FLOAT_EQ(-values_.infinity, -values_.close_to_infinity); -#if !GTEST_OS_SYMBIAN - // Nokia's STLport crashes if we try to output infinity or NaN. EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(values_.infinity, -values_.infinity), "-values_.infinity"); @@ -2831,14 +2826,10 @@ TEST_F(FloatTest, Infinity) { // are only 1 DLP apart. EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(values_.infinity, values_.nan1), "values_.nan1"); -#endif // !GTEST_OS_SYMBIAN } // Tests that comparing with NAN always returns false. TEST_F(FloatTest, NaN) { -#if !GTEST_OS_SYMBIAN -// Nokia's STLport crashes if we try to output infinity or NaN. - // In C++Builder, names within local classes (such as used by // EXPECT_FATAL_FAILURE) cannot be resolved against static members of the // scoping class. Use a static local alias as a workaround. @@ -2856,7 +2847,6 @@ TEST_F(FloatTest, NaN) { EXPECT_FATAL_FAILURE(ASSERT_FLOAT_EQ(v.nan1, v.infinity), "v.infinity"); -#endif // !GTEST_OS_SYMBIAN } // Tests that *_FLOAT_EQ are reflexive. @@ -2918,10 +2908,6 @@ TEST_F(FloatTest, FloatLEFails) { EXPECT_PRED_FORMAT2(FloatLE, values_.further_from_one, 1.0f); }, "(values_.further_from_one) <= (1.0f)"); -#if !GTEST_OS_SYMBIAN && !defined(__BORLANDC__) - // Nokia's STLport crashes if we try to output infinity or NaN. - // C++Builder gives bad results for ordered comparisons involving NaNs - // due to compiler bugs. EXPECT_NONFATAL_FAILURE({ // NOLINT EXPECT_PRED_FORMAT2(FloatLE, values_.nan1, values_.infinity); }, "(values_.nan1) <= (values_.infinity)"); @@ -2931,7 +2917,6 @@ TEST_F(FloatTest, FloatLEFails) { EXPECT_FATAL_FAILURE({ // NOLINT ASSERT_PRED_FORMAT2(FloatLE, values_.nan1, values_.nan1); }, "(values_.nan1) <= (values_.nan1)"); -#endif // !GTEST_OS_SYMBIAN && !defined(__BORLANDC__) } // Instantiates FloatingPointTest for testing *_DOUBLE_EQ. @@ -2995,8 +2980,6 @@ TEST_F(DoubleTest, LargeDiff) { TEST_F(DoubleTest, Infinity) { EXPECT_DOUBLE_EQ(values_.infinity, values_.close_to_infinity); EXPECT_DOUBLE_EQ(-values_.infinity, -values_.close_to_infinity); -#if !GTEST_OS_SYMBIAN - // Nokia's STLport crashes if we try to output infinity or NaN. EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(values_.infinity, -values_.infinity), "-values_.infinity"); @@ -3004,18 +2987,10 @@ TEST_F(DoubleTest, Infinity) { // are only 1 DLP apart. EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(values_.infinity, values_.nan1), "values_.nan1"); -#endif // !GTEST_OS_SYMBIAN } // Tests that comparing with NAN always returns false. TEST_F(DoubleTest, NaN) { -#if !GTEST_OS_SYMBIAN - // In C++Builder, names within local classes (such as used by - // EXPECT_FATAL_FAILURE) cannot be resolved against static members of the - // scoping class. Use a static local alias as a workaround. - // We use the assignment syntax since some compilers, like Sun Studio, - // don't allow initializing references using construction syntax - // (parentheses). static const DoubleTest::TestValues& v = this->values_; // Nokia's STLport crashes if we try to output infinity or NaN. @@ -3025,17 +3000,13 @@ TEST_F(DoubleTest, NaN) { EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(1.0, v.nan1), "v.nan1"); EXPECT_FATAL_FAILURE(ASSERT_DOUBLE_EQ(v.nan1, v.infinity), "v.infinity"); -#endif // !GTEST_OS_SYMBIAN } // Tests that *_DOUBLE_EQ are reflexive. TEST_F(DoubleTest, Reflexive) { EXPECT_DOUBLE_EQ(0.0, 0.0); EXPECT_DOUBLE_EQ(1.0, 1.0); -#if !GTEST_OS_SYMBIAN - // Nokia's STLport crashes if we try to output infinity or NaN. ASSERT_DOUBLE_EQ(values_.infinity, values_.infinity); -#endif // !GTEST_OS_SYMBIAN } // Tests that *_DOUBLE_EQ are commutative. @@ -3090,10 +3061,6 @@ TEST_F(DoubleTest, DoubleLEFails) { EXPECT_PRED_FORMAT2(DoubleLE, values_.further_from_one, 1.0); }, "(values_.further_from_one) <= (1.0)"); -#if !GTEST_OS_SYMBIAN && !defined(__BORLANDC__) - // Nokia's STLport crashes if we try to output infinity or NaN. - // C++Builder gives bad results for ordered comparisons involving NaNs - // due to compiler bugs. EXPECT_NONFATAL_FAILURE({ // NOLINT EXPECT_PRED_FORMAT2(DoubleLE, values_.nan1, values_.infinity); }, "(values_.nan1) <= (values_.infinity)"); @@ -3103,7 +3070,6 @@ TEST_F(DoubleTest, DoubleLEFails) { EXPECT_FATAL_FAILURE({ // NOLINT ASSERT_PRED_FORMAT2(DoubleLE, values_.nan1, values_.nan1); }, "(values_.nan1) <= (values_.nan1)"); -#endif // !GTEST_OS_SYMBIAN && !defined(__BORLANDC__) } @@ -3711,7 +3677,6 @@ TEST(AssertionTest, ASSERT_EQ) { } // Tests ASSERT_EQ(NULL, pointer). -#if GTEST_CAN_COMPARE_NULL TEST(AssertionTest, ASSERT_EQ_NULL) { // A success. const char* p = nullptr; @@ -3725,7 +3690,6 @@ TEST(AssertionTest, ASSERT_EQ_NULL) { static int n = 0; EXPECT_FATAL_FAILURE(ASSERT_EQ(nullptr, &n), " &n\n Which is:"); } -#endif // GTEST_CAN_COMPARE_NULL // Tests ASSERT_EQ(0, non_pointer). Since the literal 0 can be // treated as a null pointer by the compiler, we need to make sure @@ -3916,11 +3880,8 @@ TEST(AssertionTest, NamedEnum) { EXPECT_NONFATAL_FAILURE(EXPECT_EQ(kE1, kE2), "Which is: 1"); } -// The version of gcc used in XCode 2.2 has a bug and doesn't allow -// anonymous enums in assertions. Therefore the following test is not -// done on Mac. -// Sun Studio and HP aCC also reject this code. -#if !GTEST_OS_MAC && !defined(__SUNPRO_CC) && !defined(__HP_aCC) +// Sun Studio and HP aCC2reject this code. +#if !defined(__SUNPRO_CC) && !defined(__HP_aCC) // Tests using assertions with anonymous enums. enum { @@ -4439,7 +4400,6 @@ TEST(ExpectTest, EXPECT_EQ_Double) { "5.1"); } -#if GTEST_CAN_COMPARE_NULL // Tests EXPECT_EQ(NULL, pointer). TEST(ExpectTest, EXPECT_EQ_NULL) { // A success. @@ -4454,7 +4414,6 @@ TEST(ExpectTest, EXPECT_EQ_NULL) { int n = 0; EXPECT_NONFATAL_FAILURE(EXPECT_EQ(nullptr, &n), " &n\n Which is:"); } -#endif // GTEST_CAN_COMPARE_NULL // Tests EXPECT_EQ(0, non_pointer). Since the literal 0 can be // treated as a null pointer by the compiler, we need to make sure -- cgit v1.2.3 From 14c2fba7349e1f84e506dd6eab2835a8023d0f05 Mon Sep 17 00:00:00 2001 From: misterg Date: Wed, 2 Jan 2019 16:50:02 -0500 Subject: Googletest export Internal Change PiperOrigin-RevId: 227575279 --- googlemock/include/gmock/gmock-matchers.h | 3 --- googlemock/include/gmock/gmock-spec-builders.h | 4 ---- .../include/gmock/internal/gmock-internal-utils.h | 2 -- googlemock/src/gmock-spec-builders.cc | 3 --- googlemock/src/gmock.cc | 3 --- googlemock/test/gmock-actions_test.cc | 4 ---- googletest/include/gtest/gtest-death-test.h | 1 - googletest/include/gtest/gtest-matchers.h | 4 ---- googletest/include/gtest/gtest-printers.h | 1 - googletest/include/gtest/gtest.h | 1 - googletest/include/gtest/internal/gtest-port.h | 13 ----------- googletest/src/gtest-death-test.cc | 4 ---- googletest/src/gtest-filepath.cc | 4 ---- googletest/src/gtest-internal-inl.h | 2 -- googletest/src/gtest-port.cc | 7 ------ googletest/src/gtest-printers.cc | 1 - googletest/src/gtest.cc | 25 ---------------------- googletest/test/googletest-death-test-test.cc | 3 --- googletest/test/googletest-filepath-test.cc | 2 -- googletest/test/googletest-json-outfiles-test.py | 5 ----- googletest/test/googletest-options-test.cc | 1 - googletest/test/googletest-output-test.py | 1 - googletest/test/googletest-test-part-test.cc | 2 -- .../test/googletest-throw-on-failure-test.py | 3 +-- googletest/test/gtest_assert_by_exception_test.cc | 1 - googletest/test/gtest_repeat_test.cc | 1 - googletest/test/gtest_test_utils.py | 2 -- googletest/test/gtest_unittest.cc | 1 - googletest/test/gtest_xml_outfiles_test.py | 5 ----- 29 files changed, 1 insertion(+), 108 deletions(-) diff --git a/googlemock/include/gmock/gmock-matchers.h b/googlemock/include/gmock/gmock-matchers.h index 36ff2992..b99fdc36 100644 --- a/googlemock/include/gmock/gmock-matchers.h +++ b/googlemock/include/gmock/gmock-matchers.h @@ -382,8 +382,6 @@ class TuplePrefix { const Value& value = std::get(values); StringMatchResultListener listener; if (!matcher.MatchAndExplain(value, &listener)) { - // FIXME: include in the message the name of the parameter - // as used in MOCK_METHOD*() when possible. *os << " Expected arg #" << N - 1 << ": "; std::get(matchers).DescribeTo(os); *os << "\n Actual: "; @@ -1657,7 +1655,6 @@ class WhenDynamicCastToMatcher : public WhenDynamicCastToMatcherBase { template bool MatchAndExplain(From from, MatchResultListener* listener) const { - // FIXME: Add more detail on failures. ie did the dyn_cast fail? To to = dynamic_cast(from); return MatchPrintAndExplain(to, this->matcher_, listener); } diff --git a/googlemock/include/gmock/gmock-spec-builders.h b/googlemock/include/gmock/gmock-spec-builders.h index 9a54b3ae..526fe7aa 100644 --- a/googlemock/include/gmock/gmock-spec-builders.h +++ b/googlemock/include/gmock/gmock-spec-builders.h @@ -186,7 +186,6 @@ class GTEST_API_ UntypedFunctionMockerBase { // this information in the global mock registry. Will be called // whenever an EXPECT_CALL() or ON_CALL() is executed on this mock // method. - // FIXME: rename to SetAndRegisterOwner(). void RegisterOwner(const void* mock_obj) GTEST_LOCK_EXCLUDED_(g_gmock_mutex); @@ -1197,9 +1196,6 @@ class TypedExpectation : public ExpectationBase { mocker->DescribeDefaultActionTo(args, what); DescribeCallCountTo(why); - // FIXME: allow the user to control whether - // unexpected calls should fail immediately or continue using a - // flag --gmock_unexpected_calls_are_fatal. return nullptr; } diff --git a/googlemock/include/gmock/internal/gmock-internal-utils.h b/googlemock/include/gmock/internal/gmock-internal-utils.h index 3de3d545..7ebd645e 100644 --- a/googlemock/include/gmock/internal/gmock-internal-utils.h +++ b/googlemock/include/gmock/internal/gmock-internal-utils.h @@ -346,8 +346,6 @@ class WithoutMatchers { // Internal use only: access the singleton instance of WithoutMatchers. GTEST_API_ WithoutMatchers GetWithoutMatchers(); -// FIXME: group all type utilities together. - // Type traits. // is_reference::value is non-zero iff T is a reference type. diff --git a/googlemock/src/gmock-spec-builders.cc b/googlemock/src/gmock-spec-builders.cc index b3d0cca2..ee0c5341 100644 --- a/googlemock/src/gmock-spec-builders.cc +++ b/googlemock/src/gmock-spec-builders.cc @@ -790,9 +790,6 @@ void Mock::RegisterUseByOnCallOrExpectCall(const void* mock_obj, const TestInfo* const test_info = UnitTest::GetInstance()->current_test_info(); if (test_info != nullptr) { - // FIXME: record the test case name when the - // ON_CALL or EXPECT_CALL is invoked from SetUpTestCase() or - // TearDownTestCase(). state.first_used_test_case = test_info->test_case_name(); state.first_used_test = test_info->name(); } diff --git a/googlemock/src/gmock.cc b/googlemock/src/gmock.cc index 675e8db8..3fd2e939 100644 --- a/googlemock/src/gmock.cc +++ b/googlemock/src/gmock.cc @@ -33,9 +33,6 @@ namespace testing { -// FIXME: support using environment variables to -// control the flag values, like what Google Test does. - GMOCK_DEFINE_bool_(catch_leaked_mocks, true, "true iff Google Mock should report leaked mock objects " "as failures."); diff --git a/googlemock/test/gmock-actions_test.cc b/googlemock/test/gmock-actions_test.cc index 6c03b2e9..f918410e 100644 --- a/googlemock/test/gmock-actions_test.cc +++ b/googlemock/test/gmock-actions_test.cc @@ -1438,10 +1438,6 @@ TEST(FunctorActionTest, UnusedArguments) { } // Test that basic built-in actions work with move-only arguments. -// FIXME: Currently, almost all ActionInterface-based actions will not -// work, even if they only try to use other, copyable arguments. Implement them -// if necessary (but note that DoAll cannot work on non-copyable types anyway - -// so maybe it's better to make users use lambdas instead. TEST(MoveOnlyArgumentsTest, ReturningActions) { Action)> a = Return(1); EXPECT_EQ(1, a.Perform(std::make_tuple(nullptr))); diff --git a/googletest/include/gtest/gtest-death-test.h b/googletest/include/gtest/gtest-death-test.h index 20c54d86..40389f07 100644 --- a/googletest/include/gtest/gtest-death-test.h +++ b/googletest/include/gtest/gtest-death-test.h @@ -161,7 +161,6 @@ GTEST_API_ bool InDeathTestChild(); // is rarely a problem as people usually don't put the test binary // directory in PATH. // -// FIXME: make thread-safe death tests search the PATH. // Asserts that a given statement causes the program to exit, with an // integer exit status that satisfies predicate, and emitting error output diff --git a/googletest/include/gtest/gtest-matchers.h b/googletest/include/gtest/gtest-matchers.h index 02a9952b..7bc855b8 100644 --- a/googletest/include/gtest/gtest-matchers.h +++ b/googletest/include/gtest/gtest-matchers.h @@ -69,10 +69,6 @@ namespace testing { // MatchResultListener is an abstract class. Its << operator can be // used by a matcher to explain why a value matches or doesn't match. // -// FIXME: add method -// bool InterestedInWhy(bool result) const; -// to indicate whether the listener is interested in why the match -// result is 'result'. class MatchResultListener { public: // Creates a listener object with the given underlying ostream. The diff --git a/googletest/include/gtest/gtest-printers.h b/googletest/include/gtest/gtest-printers.h index b79ddf4c..d6596e48 100644 --- a/googletest/include/gtest/gtest-printers.h +++ b/googletest/include/gtest/gtest-printers.h @@ -761,7 +761,6 @@ void UniversalPrintArray(const T* begin, size_t len, ::std::ostream* os) { // If the array has more than kThreshold elements, we'll have to // omit some details by printing only the first and the last // kChunkSize elements. - // FIXME: let the user control the threshold using a flag. if (len <= kThreshold) { PrintRawArrayTo(begin, len, os); } else { diff --git a/googletest/include/gtest/gtest.h b/googletest/include/gtest/gtest.h index 27538ac8..4dd103f5 100644 --- a/googletest/include/gtest/gtest.h +++ b/googletest/include/gtest/gtest.h @@ -329,7 +329,6 @@ class GTEST_API_ AssertionResult { const char* message() const { return message_.get() != nullptr ? message_->c_str() : ""; } - // FIXME: Remove this after making sure no clients use it. // Deprecated; please use message() instead. const char* failure_message() const { return message(); } diff --git a/googletest/include/gtest/internal/gtest-port.h b/googletest/include/gtest/internal/gtest-port.h index 12c64e78..d5839916 100644 --- a/googletest/include/gtest/internal/gtest-port.h +++ b/googletest/include/gtest/internal/gtest-port.h @@ -457,9 +457,6 @@ typedef struct _RTL_CRITICAL_SECTION GTEST_CRITICAL_SECTION; #ifndef GTEST_HAS_STD_WSTRING // The user didn't tell us whether ::std::wstring is available, so we need // to figure it out. -// FIXME: uses autoconf to detect whether ::std::wstring -// is available. - // Cygwin 1.7 and below doesn't support ::std::wstring. // Solaris' libc++ doesn't support it either. Android has // no support for it at least as recent as Froyo (2.2). @@ -926,9 +923,6 @@ class GTEST_API_ RE { // the entire str. // PartialMatch(str, re) returns true iff regular expression re // matches a substring of str (including str itself). - // - // FIXME: make FullMatch() and PartialMatch() work - // when str contains NUL characters. static bool FullMatch(const ::std::string& str, const RE& re) { return FullMatch(str.c_str(), re); } @@ -952,10 +946,6 @@ class GTEST_API_ RE { private: void Init(const char* regex); - - // We use a const char* instead of an std::string, as Google Test used to be - // used where std::string is not available. FIXME: change to - // std::string. const char* pattern_; bool is_valid_; @@ -2293,9 +2283,6 @@ 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. -// FIXME: Find a better way to refactor flag and environment parsing -// out of both gtest-port.cc and gtest.cc to avoid exporting this utility -// function. bool ParseInt32(const Message& src_text, const char* str, Int32* value); // Parses a bool/Int32/string from the environment variable diff --git a/googletest/src/gtest-death-test.cc b/googletest/src/gtest-death-test.cc index 44247e81..ddc3453b 100644 --- a/googletest/src/gtest-death-test.cc +++ b/googletest/src/gtest-death-test.cc @@ -274,8 +274,6 @@ static const int kFuchsiaReadPipeFd = 3; // statement, which is not allowed; THREW means that the test statement // returned control by throwing an exception. IN_PROGRESS means the test // has not yet concluded. -// FIXME: Unify names and possibly values for -// AbortReason, DeathTestOutcome, and flag characters above. enum DeathTestOutcome { IN_PROGRESS, DIED, LIVED, RETURNED, THREW }; // Routine for aborting the program which is safe to call from an @@ -1523,8 +1521,6 @@ static int GetStatusFileDescriptor(unsigned int parent_process_id, StreamableToString(parent_process_id)); } - // FIXME: Replace the following check with a - // compile-time assertion when available. GTEST_CHECK_(sizeof(HANDLE) <= sizeof(size_t)); const HANDLE write_handle = diff --git a/googletest/src/gtest-filepath.cc b/googletest/src/gtest-filepath.cc index 0b71ad30..204d4607 100644 --- a/googletest/src/gtest-filepath.cc +++ b/googletest/src/gtest-filepath.cc @@ -247,9 +247,6 @@ bool FilePath::DirectoryExists() const { // root directory per disk drive.) bool FilePath::IsRootDirectory() const { #if GTEST_OS_WINDOWS - // FIXME: on Windows a network share like - // \\server\share can be a root directory, although it cannot be the - // current directory. Handle this properly. return pathname_.length() == 3 && IsAbsolutePath(); #else return pathname_.length() == 1 && IsPathSeparator(pathname_.c_str()[0]); @@ -347,7 +344,6 @@ FilePath FilePath::RemoveTrailingPathSeparator() const { // Removes any redundant separators that might be in the pathname. // For example, "bar///foo" becomes "bar/foo". Does not eliminate other // redundancies that might be in a pathname involving "." or "..". -// FIXME: handle Windows network shares (e.g. \\server\share). void FilePath::Normalize() { if (pathname_.c_str() == nullptr) { pathname_ = ""; diff --git a/googletest/src/gtest-internal-inl.h b/googletest/src/gtest-internal-inl.h index 262eb36b..09521649 100644 --- a/googletest/src/gtest-internal-inl.h +++ b/googletest/src/gtest-internal-inl.h @@ -998,8 +998,6 @@ bool ParseNaturalNumber(const ::std::string& str, Integer* number) { const bool parse_success = *end == '\0' && errno == 0; - // FIXME: Convert this to compile time assertion when it is - // available. GTEST_CHECK_(sizeof(Integer) <= sizeof(parsed)); const Integer result = static_cast(parsed); diff --git a/googletest/src/gtest-port.cc b/googletest/src/gtest-port.cc index 950c16b6..989778cf 100644 --- a/googletest/src/gtest-port.cc +++ b/googletest/src/gtest-port.cc @@ -265,9 +265,6 @@ Mutex::Mutex() Mutex::~Mutex() { // Static mutexes are leaked intentionally. It is not thread-safe to try // to clean them up. - // FIXME: Switch to Slim Reader/Writer (SRW) Locks, which requires - // nothing to clean it up but is available only on Vista and later. - // https://docs.microsoft.com/en-us/windows/desktop/Sync/slim-reader-writer--srw--locks if (type_ == kDynamic) { ::DeleteCriticalSection(critical_section_); delete critical_section_; @@ -388,7 +385,6 @@ class ThreadWithParamSupport : public ThreadWithParamBase { Notification* thread_can_start) { ThreadMainParam* param = new ThreadMainParam(runnable, thread_can_start); DWORD thread_id; - // FIXME: Consider to use _beginthreadex instead. HANDLE thread_handle = ::CreateThread( nullptr, // Default security. 0, // Default stack size. @@ -741,9 +737,6 @@ static std::string FormatRegexSyntaxError(const char* regex, int index) { // otherwise returns true. bool ValidateRegex(const char* regex) { if (regex == nullptr) { - // FIXME: fix the source file location in the - // assertion failures to match where the regex is used in user - // code. ADD_FAILURE() << "NULL is not a valid simple regular expression."; return false; } diff --git a/googletest/src/gtest-printers.cc b/googletest/src/gtest-printers.cc index 12e6dbb6..f0e8e571 100644 --- a/googletest/src/gtest-printers.cc +++ b/googletest/src/gtest-printers.cc @@ -89,7 +89,6 @@ void PrintBytesInObjectToImpl(const unsigned char* obj_bytes, size_t count, // If the object size is bigger than kThreshold, we'll have to omit // some details by printing only the first and the last kChunkSize // bytes. - // FIXME: let the user control the threshold using a flag. if (count < kThreshold) { PrintByteSegmentInObjectTo(obj_bytes, 0, count, os); } else { diff --git a/googletest/src/gtest.cc b/googletest/src/gtest.cc index 641032a3..787c6484 100644 --- a/googletest/src/gtest.cc +++ b/googletest/src/gtest.cc @@ -54,8 +54,6 @@ #if GTEST_OS_LINUX -// FIXME: Use autoconf to detect availability of -// gettimeofday(). # define GTEST_HAS_GETTIMEOFDAY_ 1 # include // NOLINT @@ -89,11 +87,6 @@ # if GTEST_OS_WINDOWS_MINGW // MinGW has gettimeofday() but not _ftime64(). -// FIXME: Use autoconf to detect availability of -// gettimeofday(). -// FIXME: There are other ways to get the time on -// Windows, like GetTickCount() or GetSystemTimeAsFileTime(). MinGW -// supports these. consider using them instead. # define GTEST_HAS_GETTIMEOFDAY_ 1 # include // NOLINT # endif // GTEST_OS_WINDOWS_MINGW @@ -106,8 +99,6 @@ #else // Assume other platforms have gettimeofday(). -// FIXME: Use autoconf to detect availability of -// gettimeofday(). # define GTEST_HAS_GETTIMEOFDAY_ 1 // cpplint thinks that the header is already included, so we want to @@ -477,10 +468,6 @@ std::string UnitTestOptions::GetAbsolutePathToOutputFile() { internal::FilePath output_name(colon + 1); if (!output_name.IsAbsolutePath()) - // FIXME: on Windows \some\path is not an absolute - // path (as its meaning depends on the current drive), yet the - // following logic for turning it into an absolute path is wrong. - // Fix it. output_name = internal::FilePath::ConcatPaths( internal::FilePath(UnitTest::GetInstance()->original_working_dir()), internal::FilePath(colon + 1)); @@ -856,8 +843,6 @@ TimeInMillis GetTimeInMillis() { SYSTEMTIME now_systime; FILETIME now_filetime; ULARGE_INTEGER now_int64; - // FIXME: Shouldn't this just use - // GetSystemTimeAsFileTime()? GetSystemTime(&now_systime); if (SystemTimeToFileTime(&now_systime, &now_filetime)) { now_int64.LowPart = now_filetime.dwLowDateTime; @@ -872,8 +857,6 @@ TimeInMillis GetTimeInMillis() { // MSVC 8 deprecates _ftime64(), so we want to suppress warning 4996 // (deprecated function) there. - // FIXME: Use GetTickCount()? Or use - // SystemTimeToFileTime() GTEST_DISABLE_MSC_DEPRECATED_PUSH_() _ftime64(&now); GTEST_DISABLE_MSC_DEPRECATED_POP_() @@ -1407,8 +1390,6 @@ AssertionResult DoubleNearPredFormat(const char* expr1, const double diff = fabs(val1 - val2); if (diff <= abs_error) return AssertionSuccess(); - // FIXME: do not print the value of an expression if it's - // already a literal. return AssertionFailure() << "The difference between " << expr1 << " and " << expr2 << " is " << diff << ", which exceeds " << abs_error_expr << ", where\n" @@ -3388,7 +3369,6 @@ void TestEventRepeater::Append(TestEventListener *listener) { listeners_.push_back(listener); } -// FIXME: Factor the search functionality into Vector::Find. TestEventListener* TestEventRepeater::Release(TestEventListener *listener) { for (size_t i = 0; i < listeners_.size(); ++i) { if (listeners_[i] == listener) { @@ -3576,8 +3556,6 @@ void XmlUnitTestResultPrinter::ListTestsMatchingFilter( // module will consist of ordinary English text. // If this module is ever modified to produce version 1.1 XML output, // most invalid characters can be retained using character references. -// FIXME: It might be nice to have a minimally invasive, human-readable -// escaping scheme for invalid characters, rather than dropping them. std::string XmlUnitTestResultPrinter::EscapeXml( const std::string& str, bool is_attribute) { Message m; @@ -3726,7 +3704,6 @@ void XmlUnitTestResultPrinter::OutputXmlAttribute( } // Prints an XML representation of a TestInfo object. -// FIXME: There is also value in printing properties with the plain printer. void XmlUnitTestResultPrinter::OutputXmlTestInfo(::std::ostream* stream, const char* test_case_name, const TestInfo& test_info) { @@ -5717,8 +5694,6 @@ static bool HasGoogleTestFlagPrefix(const char* str) { // @Y changes the color to yellow. // @D changes to the default terminal text color. // -// FIXME: Write tests for this once we add stdout -// capturing to Google Test. static void PrintColorEncoded(const char* str) { GTestColor color = COLOR_DEFAULT; // The current color. diff --git a/googletest/test/googletest-death-test-test.cc b/googletest/test/googletest-death-test-test.cc index a1a8f181..78e05eb1 100644 --- a/googletest/test/googletest-death-test-test.cc +++ b/googletest/test/googletest-death-test-test.cc @@ -1281,9 +1281,6 @@ TEST(ParseNaturalNumberTest, WorksForShorterIntegers) { # if GTEST_OS_WINDOWS TEST(EnvironmentTest, HandleFitsIntoSizeT) { - // FIXME: Remove this test after this condition is verified - // in a static assertion in gtest-death-test.cc in the function - // GetStatusFileDescriptor. ASSERT_TRUE(sizeof(HANDLE) <= sizeof(size_t)); } # endif // GTEST_OS_WINDOWS diff --git a/googletest/test/googletest-filepath-test.cc b/googletest/test/googletest-filepath-test.cc index 674799a5..aafad36f 100644 --- a/googletest/test/googletest-filepath-test.cc +++ b/googletest/test/googletest-filepath-test.cc @@ -50,8 +50,6 @@ namespace internal { namespace { #if GTEST_OS_WINDOWS_MOBILE -// FIXME: Move these to the POSIX adapter section in -// gtest-port.h. // Windows CE doesn't have the remove C function. int remove(const char* path) { diff --git a/googletest/test/googletest-json-outfiles-test.py b/googletest/test/googletest-json-outfiles-test.py index c99be48e..0175e8d1 100644 --- a/googletest/test/googletest-json-outfiles-test.py +++ b/googletest/test/googletest-json-outfiles-test.py @@ -136,11 +136,6 @@ class GTestJsonOutFilesTest(gtest_test_utils.TestCase): self.assert_(p.exited) self.assertEquals(0, p.exit_code) - # FIXME: libtool causes the built test binary to be - # named lt-gtest_xml_outfiles_test_ instead of - # gtest_xml_outfiles_test_. To account for this possibility, we - # allow both names in the following code. We should remove this - # when libtool replacement tool is ready. output_file_name1 = test_name + '.json' output_file1 = os.path.join(self.output_dir_, output_file_name1) output_file_name2 = 'lt-' + output_file_name1 diff --git a/googletest/test/googletest-options-test.cc b/googletest/test/googletest-options-test.cc index 08aa9d82..f07b316d 100644 --- a/googletest/test/googletest-options-test.cc +++ b/googletest/test/googletest-options-test.cc @@ -111,7 +111,6 @@ TEST(OutputFileHelpersTest, GetCurrentExecutableName) { #elif GTEST_OS_FUCHSIA const bool success = exe_str == "app"; #else - // FIXME: remove the hard-coded "lt-" prefix when libtool replacement is ready const bool success = exe_str == "googletest-options-test" || exe_str == "gtest_all_test" || diff --git a/googletest/test/googletest-output-test.py b/googletest/test/googletest-output-test.py index 1a9ee6e3..c727f17a 100755 --- a/googletest/test/googletest-output-test.py +++ b/googletest/test/googletest-output-test.py @@ -55,7 +55,6 @@ NO_STACKTRACE_SUPPORT_FLAG = '--no_stacktrace_support' IS_LINUX = os.name == 'posix' and os.uname()[0] == 'Linux' IS_WINDOWS = os.name == 'nt' -# FIXME: remove the _lin suffix. GOLDEN_NAME = 'googletest-output-test-golden-lin.txt' PROGRAM_PATH = gtest_test_utils.GetTestExecutablePath('googletest-output-test_') diff --git a/googletest/test/googletest-test-part-test.cc b/googletest/test/googletest-test-part-test.cc index 8a689be5..44cf7ca0 100644 --- a/googletest/test/googletest-test-part-test.cc +++ b/googletest/test/googletest-test-part-test.cc @@ -227,6 +227,4 @@ TEST_F(TestPartResultArrayDeathTest, DiesWhenIndexIsOutOfBound) { EXPECT_DEATH_IF_SUPPORTED(results.GetTestPartResult(1), ""); } -// FIXME: Add a test for the class HasNewFatalFailureHelper. - } // namespace diff --git a/googletest/test/googletest-throw-on-failure-test.py b/googletest/test/googletest-throw-on-failure-test.py index 204e43e7..7e4b1584 100755 --- a/googletest/test/googletest-throw-on-failure-test.py +++ b/googletest/test/googletest-throw-on-failure-test.py @@ -73,8 +73,7 @@ def Run(command): return p.exited and p.exit_code == 0 -# The tests. FIXME: refactor the class to share common -# logic with code in googletest-break-on-failure-unittest.py. +# The tests. class ThrowOnFailureTest(gtest_test_utils.TestCase): """Tests the throw-on-failure mode.""" diff --git a/googletest/test/gtest_assert_by_exception_test.cc b/googletest/test/gtest_assert_by_exception_test.cc index 7dfd48c8..ada4cb30 100644 --- a/googletest/test/gtest_assert_by_exception_test.cc +++ b/googletest/test/gtest_assert_by_exception_test.cc @@ -96,7 +96,6 @@ TEST(Test, Test) { int kTestForContinuingTest = 0; TEST(Test, Test2) { - // FIXME: how to force Test2 to be after Test? kTestForContinuingTest = 1; } diff --git a/googletest/test/gtest_repeat_test.cc b/googletest/test/gtest_repeat_test.cc index 2ab82ca0..3ec416f4 100644 --- a/googletest/test/gtest_repeat_test.cc +++ b/googletest/test/gtest_repeat_test.cc @@ -117,7 +117,6 @@ const int kNumberOfParamTests = 10; class MyParamTest : public testing::TestWithParam {}; TEST_P(MyParamTest, ShouldPass) { - // FIXME: Make parameter value checking robust WRT order of tests. GTEST_CHECK_INT_EQ_(g_param_test_count % kNumberOfParamTests, GetParam()); g_param_test_count++; } diff --git a/googletest/test/gtest_test_utils.py b/googletest/test/gtest_test_utils.py index 245dcb10..9a4dcb82 100755 --- a/googletest/test/gtest_test_utils.py +++ b/googletest/test/gtest_test_utils.py @@ -307,8 +307,6 @@ def Main(): _ParseAndStripGTestFlags(sys.argv) # The tested binaries should not be writing XML output files unless the # script explicitly instructs them to. - # FIXME: Move this into Subprocess when we implement - # passing environment into it as a parameter. if GTEST_OUTPUT_VAR_NAME in os.environ: del os.environ[GTEST_OUTPUT_VAR_NAME] diff --git a/googletest/test/gtest_unittest.cc b/googletest/test/gtest_unittest.cc index 3da83556..307f630c 100644 --- a/googletest/test/gtest_unittest.cc +++ b/googletest/test/gtest_unittest.cc @@ -7013,7 +7013,6 @@ GTEST_TEST(AlternativeNameTest, Works) { // GTEST_TEST is the same as TEST. // Tests for internal utilities necessary for implementation of the universal // printing. -// FIXME: Find a better home for them. class ConversionHelperBase {}; class ConversionHelperDerived : public ConversionHelperBase {}; diff --git a/googletest/test/gtest_xml_outfiles_test.py b/googletest/test/gtest_xml_outfiles_test.py index 2c031ff8..3c715a38 100755 --- a/googletest/test/gtest_xml_outfiles_test.py +++ b/googletest/test/gtest_xml_outfiles_test.py @@ -111,11 +111,6 @@ class GTestXMLOutFilesTest(gtest_xml_test_utils.GTestXMLTestCase): self.assert_(p.exited) self.assertEquals(0, p.exit_code) - # FIXME: libtool causes the built test binary to be - # named lt-gtest_xml_outfiles_test_ instead of - # gtest_xml_outfiles_test_. To account for this possibility, we - # allow both names in the following code. We should remove this - # when libtool replacement tool is ready. output_file_name1 = test_name + ".xml" output_file1 = os.path.join(self.output_dir_, output_file_name1) output_file_name2 = 'lt-' + output_file_name1 -- cgit v1.2.3 From 8a27d164cbc78595d2e6b81ec1c56ee560624b23 Mon Sep 17 00:00:00 2001 From: Gennadiy Civil Date: Thu, 3 Jan 2019 11:40:37 -0500 Subject: Update README.md --- README.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/README.md b/README.md index 88ed935f..08d9587b 100644 --- a/README.md +++ b/README.md @@ -4,6 +4,10 @@ [![Build Status](https://api.travis-ci.org/abseil/googletest.svg?branch=master)](https://travis-ci.org/abseil/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**: +** PR FREEZE COMING SOON ** +We are working on a large refactoring that would make it hard to accept external PRs. *Really Soon Now* we will not be accepting new PRs until the refactoring has been completed. + **Future Plans**: * 1.8.x Release - [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" * Post 1.8.x - work to improve/cleanup/pay technical debt. When this work is completed there will be a 1.9.x tagged release -- cgit v1.2.3 From 6e410a3ae965306a87d2d664b817218031aefe07 Mon Sep 17 00:00:00 2001 From: Gennadiy Civil Date: Thu, 3 Jan 2019 11:41:17 -0500 Subject: Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 08d9587b..7fa78ee8 100644 --- a/README.md +++ b/README.md @@ -1,7 +1,7 @@ # Google Test # -[![Build Status](https://api.travis-ci.org/abseil/googletest.svg?branch=master)](https://travis-ci.org/abseil/googletest) +[![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**: -- cgit v1.2.3 From ac8c102dae661b8bff6780ffdc535c6d1957d45b Mon Sep 17 00:00:00 2001 From: Gennadiy Civil Date: Thu, 3 Jan 2019 11:41:41 -0500 Subject: Update README.md --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 7fa78ee8..cb988ce0 100644 --- a/README.md +++ b/README.md @@ -4,8 +4,8 @@ [![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**: -** PR FREEZE COMING SOON ** +**PR FREEZE COMING SOON** + We are working on a large refactoring that would make it hard to accept external PRs. *Really Soon Now* we will not be accepting new PRs until the refactoring has been completed. **Future Plans**: -- cgit v1.2.3 From 3a460a26b7a91abf87af7f31b93d29f930e25c82 Mon Sep 17 00:00:00 2001 From: misterg Date: Thu, 3 Jan 2019 12:39:44 -0500 Subject: Googletest export TestCase->TestSuite refactoring PiperOrigin-RevId: 227702164 --- googlemock/src/gmock-spec-builders.cc | 8 +- googletest/include/gtest/gtest-death-test.h | 6 +- googletest/include/gtest/gtest-param-test.h | 176 ++--- googletest/include/gtest/gtest-param-test.h.pump | 127 ++-- googletest/include/gtest/gtest-typed-test.h | 172 +++-- googletest/include/gtest/gtest.h | 328 +++++---- googletest/include/gtest/internal/gtest-internal.h | 148 ++-- .../include/gtest/internal/gtest-param-util.h | 210 +++--- googletest/include/gtest/internal/gtest-port.h | 1 + .../include/gtest/internal/gtest-type-util.h | 7 +- .../include/gtest/internal/gtest-type-util.h.pump | 6 +- googletest/src/gtest-death-test.cc | 18 +- googletest/src/gtest-internal-inl.h | 150 ++-- googletest/src/gtest-typed-test.cc | 4 +- googletest/src/gtest.cc | 777 +++++++++++---------- .../test/googletest-catch-exceptions-test.py | 6 +- googletest/test/googletest-listener-test.cc | 268 ++++--- .../test/googletest-output-test-golden-lin.txt | 58 +- googletest/test/gtest-typed-test_test.cc | 4 +- googletest/test/gtest_unittest.cc | 61 ++ 20 files changed, 1454 insertions(+), 1081 deletions(-) diff --git a/googlemock/src/gmock-spec-builders.cc b/googlemock/src/gmock-spec-builders.cc index ee0c5341..19714159 100644 --- a/googlemock/src/gmock-spec-builders.cc +++ b/googlemock/src/gmock-spec-builders.cc @@ -572,7 +572,7 @@ struct MockObjectState { // invoked on this mock object. const char* first_used_file; int first_used_line; - ::std::string first_used_test_case; + ::std::string first_used_test_suite; ::std::string first_used_test; bool leakable; // true iff it's OK to leak the object. FunctionMockers function_mockers; // All registered methods of the object. @@ -609,8 +609,8 @@ class MockObjectRegistry { state.first_used_line); std::cout << " ERROR: this mock object"; if (state.first_used_test != "") { - std::cout << " (used in test " << state.first_used_test_case << "." - << state.first_used_test << ")"; + std::cout << " (used in test " << state.first_used_test_suite << "." + << state.first_used_test << ")"; } std::cout << " should be deleted but never is. Its address is @" << it->first << "."; @@ -790,7 +790,7 @@ void Mock::RegisterUseByOnCallOrExpectCall(const void* mock_obj, const TestInfo* const test_info = UnitTest::GetInstance()->current_test_info(); if (test_info != nullptr) { - state.first_used_test_case = test_info->test_case_name(); + state.first_used_test_suite = test_info->test_suite_name(); state.first_used_test = test_info->name(); } } diff --git a/googletest/include/gtest/gtest-death-test.h b/googletest/include/gtest/gtest-death-test.h index 40389f07..0eb5b279 100644 --- a/googletest/include/gtest/gtest-death-test.h +++ b/googletest/include/gtest/gtest-death-test.h @@ -169,7 +169,7 @@ GTEST_API_ bool InDeathTestChild(); GTEST_DEATH_TEST_(statement, predicate, regex, GTEST_FATAL_FAILURE_) // Like ASSERT_EXIT, but continues on to successive tests in the -// test case, if any: +// test suite, if any: # define EXPECT_EXIT(statement, predicate, regex) \ GTEST_DEATH_TEST_(statement, predicate, regex, GTEST_NONFATAL_FAILURE_) @@ -180,7 +180,7 @@ GTEST_API_ bool InDeathTestChild(); ASSERT_EXIT(statement, ::testing::internal::ExitedUnsuccessfully, regex) // Like ASSERT_DEATH, but continues on to successive tests in the -// test case, if any: +// test suite, if any: # define EXPECT_DEATH(statement, regex) \ EXPECT_EXIT(statement, ::testing::internal::ExitedUnsuccessfully, regex) @@ -227,7 +227,7 @@ class GTEST_API_ KilledBySignal { // return 12; // } // -// TEST(TestCase, TestDieOr12WorksInDgbAndOpt) { +// TEST(TestSuite, TestDieOr12WorksInDgbAndOpt) { // int sideeffect = 0; // // Only asserts in dbg. // EXPECT_DEBUG_DEATH(DieInDebugOr12(&sideeffect), "death"); diff --git a/googletest/include/gtest/gtest-param-test.h b/googletest/include/gtest/gtest-param-test.h index 2b27251f..a0eecc69 100644 --- a/googletest/include/gtest/gtest-param-test.h +++ b/googletest/include/gtest/gtest-param-test.h @@ -75,7 +75,7 @@ TEST_P(FooTest, HasBlahBlah) { ... } -// Finally, you can use INSTANTIATE_TEST_CASE_P to instantiate the test +// Finally, you can use INSTANTIATE_TEST_SUITE_P to instantiate the test // case with any set of parameters you want. Google Test defines a number // of functions for generating test parameters. They return what we call // (surprise!) parameter generators. Here is a summary of them, which @@ -96,17 +96,17 @@ TEST_P(FooTest, HasBlahBlah) { // For more details, see comments at the definitions of these functions below // in this file. // -// The following statement will instantiate tests from the FooTest test case +// The following statement will instantiate tests from the FooTest test suite // each with parameter values "meeny", "miny", and "moe". -INSTANTIATE_TEST_CASE_P(InstantiationName, - FooTest, - Values("meeny", "miny", "moe")); +INSTANTIATE_TEST_SUITE_P(InstantiationName, + FooTest, + Values("meeny", "miny", "moe")); // To distinguish different instances of the pattern, (yes, you // can instantiate it more then once) the first argument to the -// INSTANTIATE_TEST_CASE_P macro is a prefix that will be added to the -// actual test case name. Remember to pick unique prefixes for different +// 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: // @@ -123,7 +123,7 @@ INSTANTIATE_TEST_CASE_P(InstantiationName, // with parameter values "cat" and "dog": const char* pets[] = {"cat", "dog"}; -INSTANTIATE_TEST_CASE_P(AnotherInstantiationName, FooTest, ValuesIn(pets)); +INSTANTIATE_TEST_SUITE_P(AnotherInstantiationName, FooTest, ValuesIn(pets)); // The tests from the instantiation above will have these names: // @@ -132,9 +132,9 @@ INSTANTIATE_TEST_CASE_P(AnotherInstantiationName, FooTest, ValuesIn(pets)); // * AnotherInstantiationName/FooTest.HasBlahBlah/0 for "cat" // * AnotherInstantiationName/FooTest.HasBlahBlah/1 for "dog" // -// Please note that INSTANTIATE_TEST_CASE_P will instantiate all tests -// in the given test case, whether their definitions come before or -// AFTER the INSTANTIATE_TEST_CASE_P statement. +// Please note that INSTANTIATE_TEST_SUITE_P will instantiate all tests +// in the given test suite, whether their definitions come before or +// AFTER the INSTANTIATE_TEST_SUITE_P statement. // // Please also note that generator expressions (including parameters to the // generators) are evaluated in InitGoogleTest(), after main() has started. @@ -190,11 +190,11 @@ namespace testing { // Functions producing parameter generators. // // Google Test uses these generators to produce parameters for value- -// parameterized tests. When a parameterized test case is instantiated +// parameterized tests. When a parameterized test suite is instantiated // with a particular generator, Google Test creates and runs tests // for each element in the sequence produced by the generator. // -// In the following sample, tests from test case FooTest are instantiated +// In the following sample, tests from test suite FooTest are instantiated // each three times with parameter values 3, 5, and 8: // // class FooTest : public TestWithParam { ... }; @@ -203,7 +203,7 @@ namespace testing { // } // TEST_P(FooTest, TestThat) { // } -// INSTANTIATE_TEST_CASE_P(TestSequence, FooTest, Values(3, 5, 8)); +// INSTANTIATE_TEST_SUITE_P(TestSequence, FooTest, Values(3, 5, 8)); // // Range() returns generators providing sequences of values in a range. @@ -260,13 +260,13 @@ internal::ParamGenerator Range(T start, T end) { // // Examples: // -// This instantiates tests from test case StringTest +// This instantiates tests from test suite StringTest // each with C-string values of "foo", "bar", and "baz": // // const char* strings[] = {"foo", "bar", "baz"}; -// INSTANTIATE_TEST_CASE_P(StringSequence, StringTest, ValuesIn(strings)); +// INSTANTIATE_TEST_SUITE_P(StringSequence, StringTest, ValuesIn(strings)); // -// This instantiates tests from test case StlStringTest +// This instantiates tests from test suite StlStringTest // each with STL strings with values "a" and "b": // // ::std::vector< ::std::string> GetParameterStrings() { @@ -276,9 +276,9 @@ internal::ParamGenerator Range(T start, T end) { // return v; // } // -// INSTANTIATE_TEST_CASE_P(CharSequence, -// StlStringTest, -// ValuesIn(GetParameterStrings())); +// INSTANTIATE_TEST_SUITE_P(CharSequence, +// StlStringTest, +// ValuesIn(GetParameterStrings())); // // // This will also instantiate tests from CharTest @@ -291,9 +291,9 @@ internal::ParamGenerator Range(T start, T end) { // return list; // } // ::std::list l = GetParameterChars(); -// INSTANTIATE_TEST_CASE_P(CharSequence2, -// CharTest, -// ValuesIn(l.begin(), l.end())); +// INSTANTIATE_TEST_SUITE_P(CharSequence2, +// CharTest, +// ValuesIn(l.begin(), l.end())); // template internal::ParamGenerator< @@ -323,15 +323,17 @@ internal::ParamGenerator ValuesIn( // Values(T v1, T v2, ..., T vN) // - returns a generator producing sequences with elements v1, v2, ..., vN. // -// For example, this instantiates tests from test case BarTest each +// For example, this instantiates tests from test suite BarTest each // with values "one", "two", and "three": // -// INSTANTIATE_TEST_CASE_P(NumSequence, BarTest, Values("one", "two", "three")); +// INSTANTIATE_TEST_SUITE_P(NumSequence, +// BarTest, +// Values("one", "two", "three")); // -// This instantiates tests from test case BazTest each with values 1, 2, 3.5. +// This instantiates tests from test suite BazTest each with values 1, 2, 3.5. // The exact type of values will depend on the type of parameter in BazTest. // -// INSTANTIATE_TEST_CASE_P(FloatingNumbers, BazTest, Values(1, 2, 3.5)); +// INSTANTIATE_TEST_SUITE_P(FloatingNumbers, BazTest, Values(1, 2, 3.5)); // // template @@ -349,7 +351,7 @@ internal::ValueArray Values(T... v) { // of multiple flags can be tested when several Bool()'s are combined using // Combine() function. // -// In the following example all tests in the test case FlagDependentTest +// In the following example all tests in the test suite FlagDependentTest // will be instantiated twice with parameters false and true. // // class FlagDependentTest : public testing::TestWithParam { @@ -357,7 +359,7 @@ internal::ValueArray Values(T... v) { // external_flag = GetParam(); // } // } -// INSTANTIATE_TEST_CASE_P(BoolSequence, FlagDependentTest, Bool()); +// INSTANTIATE_TEST_SUITE_P(BoolSequence, FlagDependentTest, Bool()); // inline internal::ParamGenerator Bool() { return Values(false, true); @@ -378,7 +380,7 @@ inline internal::ParamGenerator Bool() { // // Example: // -// This will instantiate tests in test case AnimalTest each one with +// This will instantiate tests in test suite AnimalTest each one with // the parameter values tuple("cat", BLACK), tuple("cat", WHITE), // tuple("dog", BLACK), and tuple("dog", WHITE): // @@ -388,9 +390,9 @@ inline internal::ParamGenerator Bool() { // // TEST_P(AnimalTest, AnimalLooksNice) {...} // -// INSTANTIATE_TEST_CASE_P(AnimalVariations, AnimalTest, -// Combine(Values("cat", "dog"), -// Values(BLACK, WHITE))); +// INSTANTIATE_TEST_SUITE_P(AnimalVariations, AnimalTest, +// Combine(Values("cat", "dog"), +// Values(BLACK, WHITE))); // // This will instantiate tests in FlagDependentTest with all variations of two // Boolean flags: @@ -406,8 +408,8 @@ inline internal::ParamGenerator Bool() { // TEST_P(FlagDependentTest, TestFeature1) { // // Test your code using external_flag_1 and external_flag_2 here. // } -// INSTANTIATE_TEST_CASE_P(TwoBoolSequence, FlagDependentTest, -// Combine(Bool(), Bool())); +// INSTANTIATE_TEST_SUITE_P(TwoBoolSequence, FlagDependentTest, +// Combine(Bool(), Bool())); // template internal::CartesianProductHolder2 Combine( @@ -513,36 +515,36 @@ internal::CartesianProductHolder10parameterized_test_registry(). \ - GetTestCasePatternHolder(\ - #test_case_name, \ - ::testing::internal::CodeLocation(\ - __FILE__, __LINE__))->AddTestPattern(\ - GTEST_STRINGIFY_(test_case_name), \ - GTEST_STRINGIFY_(test_name), \ - new ::testing::internal::TestMetaFactory< \ - GTEST_TEST_CLASS_NAME_(\ - test_case_name, test_name)>()); \ - return 0; \ - } \ - static int gtest_registering_dummy_ GTEST_ATTRIBUTE_UNUSED_; \ - GTEST_DISALLOW_COPY_AND_ASSIGN_(\ - GTEST_TEST_CLASS_NAME_(test_case_name, test_name)); \ - }; \ - int GTEST_TEST_CLASS_NAME_(test_case_name, \ - test_name)::gtest_registering_dummy_ = \ - GTEST_TEST_CLASS_NAME_(test_case_name, test_name)::AddToRegistry(); \ - void GTEST_TEST_CLASS_NAME_(test_case_name, test_name)::TestBody() - -// The optional last argument to INSTANTIATE_TEST_CASE_P allows the user +#define TEST_P(test_suite_name, test_name) \ + class GTEST_TEST_CLASS_NAME_(test_suite_name, test_name) \ + : public test_suite_name { \ + public: \ + GTEST_TEST_CLASS_NAME_(test_suite_name, test_name)() {} \ + virtual void TestBody(); \ + \ + private: \ + static int AddToRegistry() { \ + ::testing::UnitTest::GetInstance() \ + ->parameterized_test_registry() \ + .GetTestSuitePatternHolder( \ + #test_suite_name, \ + ::testing::internal::CodeLocation(__FILE__, __LINE__)) \ + ->AddTestPattern( \ + GTEST_STRINGIFY_(test_suite_name), GTEST_STRINGIFY_(test_name), \ + new ::testing::internal::TestMetaFactory()); \ + return 0; \ + } \ + static int gtest_registering_dummy_ GTEST_ATTRIBUTE_UNUSED_; \ + GTEST_DISALLOW_COPY_AND_ASSIGN_(GTEST_TEST_CLASS_NAME_(test_suite_name, \ + test_name)); \ + }; \ + int GTEST_TEST_CLASS_NAME_(test_suite_name, \ + test_name)::gtest_registering_dummy_ = \ + GTEST_TEST_CLASS_NAME_(test_suite_name, test_name)::AddToRegistry(); \ + void GTEST_TEST_CLASS_NAME_(test_suite_name, test_name)::TestBody() + +// The optional last argument to INSTANTIATE_TEST_SUITE_P allows the user // to specify a function or functor that generates custom test name suffixes // based on the test parameters. The function should accept one argument of // type testing::TestParamInfo, and return std::string. @@ -554,24 +556,32 @@ internal::CartesianProductHolder10 \ - gtest_##prefix##test_case_name##_EvalGenerator_() { return generator; } \ - static ::std::string gtest_##prefix##test_case_name##_EvalGenerateName_( \ - const ::testing::TestParamInfo& info) { \ - return ::testing::internal::GetParamNameGen \ - (__VA_ARGS__)(info); \ - } \ - static int gtest_##prefix##test_case_name##_dummy_ GTEST_ATTRIBUTE_UNUSED_ = \ - ::testing::UnitTest::GetInstance()->parameterized_test_registry(). \ - GetTestCasePatternHolder(\ - #test_case_name, \ - ::testing::internal::CodeLocation(\ - __FILE__, __LINE__))->AddTestCaseInstantiation(\ - #prefix, \ - >est_##prefix##test_case_name##_EvalGenerator_, \ - >est_##prefix##test_case_name##_EvalGenerateName_, \ - __FILE__, __LINE__) +#define INSTANTIATE_TEST_SUITE_P(prefix, test_suite_name, generator, ...) \ + static ::testing::internal::ParamGenerator \ + gtest_##prefix##test_suite_name##_EvalGenerator_() { \ + return generator; \ + } \ + static ::std::string gtest_##prefix##test_suite_name##_EvalGenerateName_( \ + const ::testing::TestParamInfo& info) { \ + return ::testing::internal::GetParamNameGen( \ + __VA_ARGS__)(info); \ + } \ + static int gtest_##prefix##test_suite_name##_dummy_ \ + GTEST_ATTRIBUTE_UNUSED_ = \ + ::testing::UnitTest::GetInstance() \ + ->parameterized_test_registry() \ + .GetTestSuitePatternHolder( \ + #test_suite_name, \ + ::testing::internal::CodeLocation(__FILE__, __LINE__)) \ + ->AddTestSuiteInstantiation( \ + #prefix, >est_##prefix##test_suite_name##_EvalGenerator_, \ + >est_##prefix##test_suite_name##_EvalGenerateName_, \ + __FILE__, __LINE__) + +// Legacy API is deprecated but still available +#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_ +#define INSTANTIATE_TEST_CASE_P INSTANTIATE_TEST_SUITE_P +#endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_ } // namespace testing diff --git a/googletest/include/gtest/gtest-param-test.h.pump b/googletest/include/gtest/gtest-param-test.h.pump index a278330c..7ecc36c3 100644 --- a/googletest/include/gtest/gtest-param-test.h.pump +++ b/googletest/include/gtest/gtest-param-test.h.pump @@ -74,7 +74,7 @@ TEST_P(FooTest, HasBlahBlah) { ... } -// Finally, you can use INSTANTIATE_TEST_CASE_P to instantiate the test +// Finally, you can use INSTANTIATE_TEST_SUITE_P to instantiate the test // case with any set of parameters you want. Google Test defines a number // of functions for generating test parameters. They return what we call // (surprise!) parameter generators. Here is a summary of them, which @@ -95,17 +95,17 @@ TEST_P(FooTest, HasBlahBlah) { // For more details, see comments at the definitions of these functions below // in this file. // -// The following statement will instantiate tests from the FooTest test case +// The following statement will instantiate tests from the FooTest test suite // each with parameter values "meeny", "miny", and "moe". -INSTANTIATE_TEST_CASE_P(InstantiationName, - FooTest, - Values("meeny", "miny", "moe")); +INSTANTIATE_TEST_SUITE_P(InstantiationName, + FooTest, + Values("meeny", "miny", "moe")); // To distinguish different instances of the pattern, (yes, you // can instantiate it more then once) the first argument to the -// INSTANTIATE_TEST_CASE_P macro is a prefix that will be added to the -// actual test case name. Remember to pick unique prefixes for different +// 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: // @@ -122,7 +122,7 @@ INSTANTIATE_TEST_CASE_P(InstantiationName, // with parameter values "cat" and "dog": const char* pets[] = {"cat", "dog"}; -INSTANTIATE_TEST_CASE_P(AnotherInstantiationName, FooTest, ValuesIn(pets)); +INSTANTIATE_TEST_SUITE_P(AnotherInstantiationName, FooTest, ValuesIn(pets)); // The tests from the instantiation above will have these names: // @@ -131,9 +131,9 @@ INSTANTIATE_TEST_CASE_P(AnotherInstantiationName, FooTest, ValuesIn(pets)); // * AnotherInstantiationName/FooTest.HasBlahBlah/0 for "cat" // * AnotherInstantiationName/FooTest.HasBlahBlah/1 for "dog" // -// Please note that INSTANTIATE_TEST_CASE_P will instantiate all tests -// in the given test case, whether their definitions come before or -// AFTER the INSTANTIATE_TEST_CASE_P statement. +// Please note that INSTANTIATE_TEST_SUITE_P will instantiate all tests +// in the given test suite, whether their definitions come before or +// AFTER the INSTANTIATE_TEST_SUITE_P statement. // // Please also note that generator expressions (including parameters to the // generators) are evaluated in InitGoogleTest(), after main() has started. @@ -189,11 +189,11 @@ namespace testing { // Functions producing parameter generators. // // Google Test uses these generators to produce parameters for value- -// parameterized tests. When a parameterized test case is instantiated +// parameterized tests. When a parameterized test suite is instantiated // with a particular generator, Google Test creates and runs tests // for each element in the sequence produced by the generator. // -// In the following sample, tests from test case FooTest are instantiated +// In the following sample, tests from test suite FooTest are instantiated // each three times with parameter values 3, 5, and 8: // // class FooTest : public TestWithParam { ... }; @@ -202,7 +202,7 @@ namespace testing { // } // TEST_P(FooTest, TestThat) { // } -// INSTANTIATE_TEST_CASE_P(TestSequence, FooTest, Values(3, 5, 8)); +// INSTANTIATE_TEST_SUITE_P(TestSequence, FooTest, Values(3, 5, 8)); // // Range() returns generators providing sequences of values in a range. @@ -259,13 +259,13 @@ internal::ParamGenerator Range(T start, T end) { // // Examples: // -// This instantiates tests from test case StringTest +// This instantiates tests from test suite StringTest // each with C-string values of "foo", "bar", and "baz": // // const char* strings[] = {"foo", "bar", "baz"}; -// INSTANTIATE_TEST_CASE_P(StringSequence, StringTest, ValuesIn(strings)); +// INSTANTIATE_TEST_SUITE_P(StringSequence, StringTest, ValuesIn(strings)); // -// This instantiates tests from test case StlStringTest +// This instantiates tests from test suite StlStringTest // each with STL strings with values "a" and "b": // // ::std::vector< ::std::string> GetParameterStrings() { @@ -275,9 +275,9 @@ internal::ParamGenerator Range(T start, T end) { // return v; // } // -// INSTANTIATE_TEST_CASE_P(CharSequence, -// StlStringTest, -// ValuesIn(GetParameterStrings())); +// INSTANTIATE_TEST_SUITE_P(CharSequence, +// StlStringTest, +// ValuesIn(GetParameterStrings())); // // // This will also instantiate tests from CharTest @@ -290,9 +290,9 @@ internal::ParamGenerator Range(T start, T end) { // return list; // } // ::std::list l = GetParameterChars(); -// INSTANTIATE_TEST_CASE_P(CharSequence2, -// CharTest, -// ValuesIn(l.begin(), l.end())); +// INSTANTIATE_TEST_SUITE_P(CharSequence2, +// CharTest, +// ValuesIn(l.begin(), l.end())); // template internal::ParamGenerator< @@ -322,15 +322,17 @@ internal::ParamGenerator ValuesIn( // Values(T v1, T v2, ..., T vN) // - returns a generator producing sequences with elements v1, v2, ..., vN. // -// For example, this instantiates tests from test case BarTest each +// For example, this instantiates tests from test suite BarTest each // with values "one", "two", and "three": // -// INSTANTIATE_TEST_CASE_P(NumSequence, BarTest, Values("one", "two", "three")); +// INSTANTIATE_TEST_SUITE_P(NumSequence, +// BarTest, +// Values("one", "two", "three")); // -// This instantiates tests from test case BazTest each with values 1, 2, 3.5. +// This instantiates tests from test suite BazTest each with values 1, 2, 3.5. // The exact type of values will depend on the type of parameter in BazTest. // -// INSTANTIATE_TEST_CASE_P(FloatingNumbers, BazTest, Values(1, 2, 3.5)); +// INSTANTIATE_TEST_SUITE_P(FloatingNumbers, BazTest, Values(1, 2, 3.5)); // // template @@ -348,7 +350,7 @@ internal::ValueArray Values(T... v) { // of multiple flags can be tested when several Bool()'s are combined using // Combine() function. // -// In the following example all tests in the test case FlagDependentTest +// In the following example all tests in the test suite FlagDependentTest // will be instantiated twice with parameters false and true. // // class FlagDependentTest : public testing::TestWithParam { @@ -356,7 +358,7 @@ internal::ValueArray Values(T... v) { // external_flag = GetParam(); // } // } -// INSTANTIATE_TEST_CASE_P(BoolSequence, FlagDependentTest, Bool()); +// INSTANTIATE_TEST_SUITE_P(BoolSequence, FlagDependentTest, Bool()); // inline internal::ParamGenerator Bool() { return Values(false, true); @@ -377,7 +379,7 @@ inline internal::ParamGenerator Bool() { // // Example: // -// This will instantiate tests in test case AnimalTest each one with +// This will instantiate tests in test suite AnimalTest each one with // the parameter values tuple("cat", BLACK), tuple("cat", WHITE), // tuple("dog", BLACK), and tuple("dog", WHITE): // @@ -387,9 +389,9 @@ inline internal::ParamGenerator Bool() { // // TEST_P(AnimalTest, AnimalLooksNice) {...} // -// INSTANTIATE_TEST_CASE_P(AnimalVariations, AnimalTest, -// Combine(Values("cat", "dog"), -// Values(BLACK, WHITE))); +// INSTANTIATE_TEST_SUITE_P(AnimalVariations, AnimalTest, +// Combine(Values("cat", "dog"), +// Values(BLACK, WHITE))); // // This will instantiate tests in FlagDependentTest with all variations of two // Boolean flags: @@ -405,8 +407,8 @@ inline internal::ParamGenerator Bool() { // TEST_P(FlagDependentTest, TestFeature1) { // // Test your code using external_flag_1 and external_flag_2 here. // } -// INSTANTIATE_TEST_CASE_P(TwoBoolSequence, FlagDependentTest, -// Combine(Bool(), Bool())); +// INSTANTIATE_TEST_SUITE_P(TwoBoolSequence, FlagDependentTest, +// Combine(Bool(), Bool())); // $range i 2..maxtuple $for i [[ @@ -421,36 +423,36 @@ internal::CartesianProductHolder$i<$for j, [[Generator$j]]> Combine( ]] -# define TEST_P(test_case_name, test_name) \ - class GTEST_TEST_CLASS_NAME_(test_case_name, test_name) \ - : public test_case_name { \ +# define TEST_P(test_suite_name, test_name) \ + class GTEST_TEST_CLASS_NAME_(test_suite_name, test_name) \ + : public test_suite_name { \ public: \ - GTEST_TEST_CLASS_NAME_(test_case_name, test_name)() {} \ + GTEST_TEST_CLASS_NAME_(test_suite_name, test_name)() {} \ virtual void TestBody(); \ private: \ static int AddToRegistry() { \ ::testing::UnitTest::GetInstance()->parameterized_test_registry(). \ - GetTestCasePatternHolder(\ - #test_case_name, \ + GetTestSuitePatternHolder(\ + #test_suite_name, \ ::testing::internal::CodeLocation(\ __FILE__, __LINE__))->AddTestPattern(\ - GTEST_STRINGIFY_(test_case_name), \ + GTEST_STRINGIFY_(test_suite_name), \ GTEST_STRINGIFY_(test_name), \ new ::testing::internal::TestMetaFactory< \ GTEST_TEST_CLASS_NAME_(\ - test_case_name, test_name)>()); \ + test_suite_name, test_name)>()); \ return 0; \ } \ static int gtest_registering_dummy_ GTEST_ATTRIBUTE_UNUSED_; \ GTEST_DISALLOW_COPY_AND_ASSIGN_(\ - GTEST_TEST_CLASS_NAME_(test_case_name, test_name)); \ + GTEST_TEST_CLASS_NAME_(test_suite_name, test_name)); \ }; \ - int GTEST_TEST_CLASS_NAME_(test_case_name, \ + int GTEST_TEST_CLASS_NAME_(test_suite_name, \ test_name)::gtest_registering_dummy_ = \ - GTEST_TEST_CLASS_NAME_(test_case_name, test_name)::AddToRegistry(); \ - void GTEST_TEST_CLASS_NAME_(test_case_name, test_name)::TestBody() + GTEST_TEST_CLASS_NAME_(test_suite_name, test_name)::AddToRegistry(); \ + void GTEST_TEST_CLASS_NAME_(test_suite_name, test_name)::TestBody() -// The optional last argument to INSTANTIATE_TEST_CASE_P allows the user +// The optional last argument to INSTANTIATE_TEST_SUITE_P allows the user // to specify a function or functor that generates custom test name suffixes // based on the test parameters. The function should accept one argument of // type testing::TestParamInfo, and return std::string. @@ -462,25 +464,30 @@ internal::CartesianProductHolder$i<$for j, [[Generator$j]]> Combine( // alphanumeric characters or underscore. Because PrintToString adds quotes // to std::string and C strings, it won't work for these types. -# define INSTANTIATE_TEST_CASE_P(prefix, test_case_name, generator, ...) \ - static ::testing::internal::ParamGenerator \ - gtest_##prefix##test_case_name##_EvalGenerator_() { return generator; } \ - static ::std::string gtest_##prefix##test_case_name##_EvalGenerateName_( \ - const ::testing::TestParamInfo& info) { \ - return ::testing::internal::GetParamNameGen \ +# define INSTANTIATE_TEST_SUITE_P(prefix, test_suite_name, generator, ...) \ + static ::testing::internal::ParamGenerator \ + gtest_##prefix##test_suite_name##_EvalGenerator_() { return generator; } \ + static ::std::string gtest_##prefix##test_suite_name##_EvalGenerateName_( \ + const ::testing::TestParamInfo& info) { \ + return ::testing::internal::GetParamNameGen \ (__VA_ARGS__)(info); \ } \ - static int gtest_##prefix##test_case_name##_dummy_ GTEST_ATTRIBUTE_UNUSED_ = \ + static int gtest_##prefix##test_suite_name##_dummy_ GTEST_ATTRIBUTE_UNUSED_ = \ ::testing::UnitTest::GetInstance()->parameterized_test_registry(). \ - GetTestCasePatternHolder(\ - #test_case_name, \ + GetTestSuitePatternHolder(\ + #test_suite_name, \ ::testing::internal::CodeLocation(\ - __FILE__, __LINE__))->AddTestCaseInstantiation(\ + __FILE__, __LINE__))->AddTestSuiteInstantiation(\ #prefix, \ - >est_##prefix##test_case_name##_EvalGenerator_, \ - >est_##prefix##test_case_name##_EvalGenerateName_, \ + >est_##prefix##test_suite_name##_EvalGenerator_, \ + >est_##prefix##test_suite_name##_EvalGenerateName_, \ __FILE__, __LINE__) +// Legacy API is deprecated but still available +#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_ +#define INSTANTIATE_TEST_CASE_P INSTANTIATE_TEST_SUITE_P +#endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_ + } // namespace testing #endif // GTEST_INCLUDE_GTEST_GTEST_PARAM_TEST_H_ diff --git a/googletest/include/gtest/gtest-typed-test.h b/googletest/include/gtest/gtest-typed-test.h index 74bce46b..30a89cf6 100644 --- a/googletest/include/gtest/gtest-typed-test.h +++ b/googletest/include/gtest/gtest-typed-test.h @@ -52,18 +52,18 @@ class FooTest : public testing::Test { T value_; }; -// Next, associate a list of types with the test case, which will be +// Next, associate a list of types with the test suite, which will be // repeated for each type in the list. The typedef is necessary for // the macro to parse correctly. typedef testing::Types MyTypes; -TYPED_TEST_CASE(FooTest, MyTypes); +TYPED_TEST_SUITE(FooTest, MyTypes); // If the type list contains only one type, you can write that type // directly without Types<...>: -// TYPED_TEST_CASE(FooTest, int); +// TYPED_TEST_SUITE(FooTest, int); // Then, use TYPED_TEST() instead of TEST_F() to define as many typed -// tests for this test case as you want. +// tests for this test suite as you want. TYPED_TEST(FooTest, DoesBlah) { // Inside a test, refer to TypeParam to get the type parameter. // Since we are inside a derived class template, C++ requires use to @@ -83,7 +83,7 @@ TYPED_TEST(FooTest, DoesBlah) { TYPED_TEST(FooTest, HasPropertyA) { ... } -// TYPED_TEST_CASE takes an optional third argument which allows to specify a +// TYPED_TEST_SUITE takes an optional third argument which allows to specify a // class that generates custom test name suffixes based on the type. This should // be a class which has a static template function GetName(int index) returning // a string for each type. The provided integer index equals the index of the @@ -99,7 +99,7 @@ TYPED_TEST(FooTest, HasPropertyA) { ... } // if (std::is_same()) return "unsignedInt"; // } // }; -// TYPED_TEST_CASE(FooTest, MyTypes, MyTypeNames); +// TYPED_TEST_SUITE(FooTest, MyTypes, MyTypeNames); #endif // 0 @@ -126,13 +126,13 @@ class FooTest : public testing::Test { ... }; -// Next, declare that you will define a type-parameterized test case +// Next, declare that you will define a type-parameterized test suite // (the _P suffix is for "parameterized" or "pattern", whichever you // prefer): -TYPED_TEST_CASE_P(FooTest); +TYPED_TEST_SUITE_P(FooTest); // Then, use TYPED_TEST_P() to define as many type-parameterized tests -// for this type-parameterized test case as you want. +// for this type-parameterized test suite as you want. TYPED_TEST_P(FooTest, DoesBlah) { // Inside a test, refer to TypeParam to get the type parameter. TypeParam n = 0; @@ -143,10 +143,10 @@ TYPED_TEST_P(FooTest, HasPropertyA) { ... } // Now the tricky part: you need to register all test patterns before // you can instantiate them. The first argument of the macro is the -// test case name; the rest are the names of the tests in this test +// test suite name; the rest are the names of the tests in this test // case. -REGISTER_TYPED_TEST_CASE_P(FooTest, - DoesBlah, HasPropertyA); +REGISTER_TYPED_TEST_SUITE_P(FooTest, + DoesBlah, HasPropertyA); // Finally, you are free to instantiate the pattern with the types you // want. If you put the above code in a header file, you can #include @@ -154,19 +154,19 @@ REGISTER_TYPED_TEST_CASE_P(FooTest, // // To distinguish different instances of the pattern, the first // argument to the INSTANTIATE_* macro is a prefix that will be added -// to the actual test case name. Remember to pick unique prefixes for +// to the actual test suite name. Remember to pick unique prefixes for // different instances. typedef testing::Types MyTypes; -INSTANTIATE_TYPED_TEST_CASE_P(My, FooTest, MyTypes); +INSTANTIATE_TYPED_TEST_SUITE_P(My, FooTest, MyTypes); // If the type list contains only one type, you can write that type // directly without Types<...>: -// INSTANTIATE_TYPED_TEST_CASE_P(My, FooTest, int); +// INSTANTIATE_TYPED_TEST_SUITE_P(My, FooTest, int); // -// Similar to the optional argument of TYPED_TEST_CASE above, -// INSTANTIATE_TEST_CASE_P takes an optional fourth argument which allows to +// Similar to the optional argument of TYPED_TEST_SUITE above, +// INSTANTIATE_TEST_SUITE_P takes an optional fourth argument which allows to // generate custom names. -// INSTANTIATE_TYPED_TEST_CASE_P(My, FooTest, MyTypes, MyTypeNames); +// INSTANTIATE_TYPED_TEST_SUITE_P(My, FooTest, MyTypes, MyTypeNames); #endif // 0 @@ -180,21 +180,21 @@ INSTANTIATE_TYPED_TEST_CASE_P(My, FooTest, MyTypes); // INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE. // // Expands to the name of the typedef for the type parameters of the -// given test case. -# define GTEST_TYPE_PARAMS_(TestCaseName) gtest_type_params_##TestCaseName##_ +// given test suite. +#define GTEST_TYPE_PARAMS_(TestSuiteName) gtest_type_params_##TestSuiteName##_ // Expands to the name of the typedef for the NameGenerator, responsible for // creating the suffixes of the name. -#define GTEST_NAME_GENERATOR_(TestCaseName) \ - gtest_type_params_##TestCaseName##_NameGenerator +#define GTEST_NAME_GENERATOR_(TestSuiteName) \ + gtest_type_params_##TestSuiteName##_NameGenerator // The 'Types' template argument below must have spaces around it // since some compilers may choke on '>>' when passing a template // instance (e.g. Types) -# define TYPED_TEST_CASE(CaseName, Types, ...) \ - typedef ::testing::internal::TypeList< Types >::type GTEST_TYPE_PARAMS_( \ - CaseName); \ - typedef ::testing::internal::NameGeneratorSelector<__VA_ARGS__>::type \ +#define TYPED_TEST_SUITE(CaseName, Types, ...) \ + typedef ::testing::internal::TypeList::type GTEST_TYPE_PARAMS_( \ + CaseName); \ + typedef ::testing::internal::NameGeneratorSelector<__VA_ARGS__>::type \ GTEST_NAME_GENERATOR_(CaseName) # define TYPED_TEST(CaseName, TestName) \ @@ -224,6 +224,11 @@ INSTANTIATE_TYPED_TEST_CASE_P(My, FooTest, MyTypes); void GTEST_TEST_CLASS_NAME_(CaseName, \ TestName)::TestBody() +// Legacy API is deprecated but still available +#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_ +#define TYPED_TEST_CASE TYPED_TEST_SUITE +#endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_ + #endif // GTEST_HAS_TYPED_TEST // Implements type-parameterized tests. @@ -233,73 +238,88 @@ INSTANTIATE_TYPED_TEST_CASE_P(My, FooTest, MyTypes); // INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE. // // Expands to the namespace name that the type-parameterized tests for -// the given type-parameterized test case are defined in. The exact +// the given type-parameterized test suite are defined in. The exact // name of the namespace is subject to change without notice. -# define GTEST_CASE_NAMESPACE_(TestCaseName) \ - gtest_case_##TestCaseName##_ +#define GTEST_SUITE_NAMESPACE_(TestSuiteName) gtest_suite_##TestSuiteName##_ // INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE. // // Expands to the name of the variable used to remember the names of -// the defined tests in the given test case. -# define GTEST_TYPED_TEST_CASE_P_STATE_(TestCaseName) \ - gtest_typed_test_case_p_state_##TestCaseName##_ +// the defined tests in the given test suite. +#define GTEST_TYPED_TEST_SUITE_P_STATE_(TestSuiteName) \ + gtest_typed_test_suite_p_state_##TestSuiteName##_ // INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE DIRECTLY. // // Expands to the name of the variable used to remember the names of -// the registered tests in the given test case. -# define GTEST_REGISTERED_TEST_NAMES_(TestCaseName) \ - gtest_registered_test_names_##TestCaseName##_ +// the registered tests in the given test suite. +#define GTEST_REGISTERED_TEST_NAMES_(TestSuiteName) \ + gtest_registered_test_names_##TestSuiteName##_ // The variables defined in the type-parameterized test macros are // static as typically these macros are used in a .h file that can be // #included in multiple translation units linked together. -# define TYPED_TEST_CASE_P(CaseName) \ - static ::testing::internal::TypedTestCasePState \ - GTEST_TYPED_TEST_CASE_P_STATE_(CaseName) - -# define TYPED_TEST_P(CaseName, TestName) \ - namespace GTEST_CASE_NAMESPACE_(CaseName) { \ - template \ - class TestName : public CaseName { \ - private: \ - typedef CaseName TestFixture; \ - typedef gtest_TypeParam_ TypeParam; \ - virtual void TestBody(); \ - }; \ - static bool gtest_##TestName##_defined_ GTEST_ATTRIBUTE_UNUSED_ = \ - GTEST_TYPED_TEST_CASE_P_STATE_(CaseName).AddTestName(\ - __FILE__, __LINE__, #CaseName, #TestName); \ - } \ - template \ - void GTEST_CASE_NAMESPACE_(CaseName)::TestName::TestBody() - -# define REGISTER_TYPED_TEST_CASE_P(CaseName, ...) \ - namespace GTEST_CASE_NAMESPACE_(CaseName) { \ - typedef ::testing::internal::Templates<__VA_ARGS__>::type gtest_AllTests_; \ - } \ - static const char* const GTEST_REGISTERED_TEST_NAMES_(CaseName) \ - GTEST_ATTRIBUTE_UNUSED_ = \ - GTEST_TYPED_TEST_CASE_P_STATE_(CaseName).VerifyRegisteredTestNames( \ - __FILE__, __LINE__, #__VA_ARGS__) +#define TYPED_TEST_SUITE_P(SuiteName) \ + static ::testing::internal::TypedTestSuitePState \ + GTEST_TYPED_TEST_SUITE_P_STATE_(SuiteName) + +// Legacy API is deprecated but still available +#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_ +#define TYPED_TEST_CASE_P TYPED_TEST_SUITE_P +#endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_ + +#define TYPED_TEST_P(SuiteName, TestName) \ + namespace GTEST_SUITE_NAMESPACE_(SuiteName) { \ + template \ + class TestName : public SuiteName { \ + private: \ + typedef SuiteName TestFixture; \ + typedef gtest_TypeParam_ TypeParam; \ + virtual void TestBody(); \ + }; \ + static bool gtest_##TestName##_defined_ GTEST_ATTRIBUTE_UNUSED_ = \ + GTEST_TYPED_TEST_SUITE_P_STATE_(SuiteName).AddTestName( \ + __FILE__, __LINE__, #SuiteName, #TestName); \ + } \ + template \ + 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( \ + __FILE__, __LINE__, #__VA_ARGS__) + +// Legacy API is deprecated but still available +#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_ +#define REGISTER_TYPED_TEST_CASE_P REGISTER_TYPED_TEST_SUITE_P +#endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_ // The 'Types' template argument below must have spaces around it // since some compilers may choke on '>>' when passing a template // instance (e.g. Types) -# define INSTANTIATE_TYPED_TEST_CASE_P(Prefix, CaseName, Types, ...) \ - static bool gtest_##Prefix##_##CaseName GTEST_ATTRIBUTE_UNUSED_ = \ - ::testing::internal::TypeParameterizedTestCase< \ - CaseName, GTEST_CASE_NAMESPACE_(CaseName)::gtest_AllTests_, \ - ::testing::internal::TypeList< Types >::type>:: \ - Register(#Prefix, \ - ::testing::internal::CodeLocation(__FILE__, __LINE__), \ - >EST_TYPED_TEST_CASE_P_STATE_(CaseName), #CaseName, \ - GTEST_REGISTERED_TEST_NAMES_(CaseName), \ - ::testing::internal::GenerateNames< \ - ::testing::internal::NameGeneratorSelector< \ - __VA_ARGS__>::type, \ - ::testing::internal::TypeList< Types >::type>()) +#define INSTANTIATE_TYPED_TEST_SUITE_P(Prefix, SuiteName, Types, ...) \ + static bool gtest_##Prefix##_##SuiteName GTEST_ATTRIBUTE_UNUSED_ = \ + ::testing::internal::TypeParameterizedTestSuite< \ + SuiteName, GTEST_SUITE_NAMESPACE_(SuiteName)::gtest_AllTests_, \ + ::testing::internal::TypeList::type>:: \ + Register(#Prefix, \ + ::testing::internal::CodeLocation(__FILE__, __LINE__), \ + >EST_TYPED_TEST_SUITE_P_STATE_(SuiteName), #SuiteName, \ + GTEST_REGISTERED_TEST_NAMES_(SuiteName), \ + ::testing::internal::GenerateNames< \ + ::testing::internal::NameGeneratorSelector< \ + __VA_ARGS__>::type, \ + ::testing::internal::TypeList::type>()) + +// Legacy API is deprecated but still available +#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_ +#define INSTANTIATE_TYPED_TEST_CASE_P INSTANTIATE_TYPED_TEST_SUITE_P +#endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_ #endif // GTEST_HAS_TYPED_TEST_P diff --git a/googletest/include/gtest/gtest.h b/googletest/include/gtest/gtest.h index 4dd103f5..a0df29e2 100644 --- a/googletest/include/gtest/gtest.h +++ b/googletest/include/gtest/gtest.h @@ -197,7 +197,12 @@ void ReportFailureInUnknownLocation(TestPartResult::Type result_type, // If we don't forward declare them the compiler might confuse the classes // in friendship clauses with same named classes on the scope. class Test; -class TestCase; +class TestSuite; + +// Old API is still available but deprecated +#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_ +using TestCase = TestSuite; +#endif class TestInfo; class UnitTest; @@ -386,8 +391,8 @@ namespace testing { // The abstract class that all tests inherit from. // -// In Google Test, a unit test program contains one or many TestCases, and -// each TestCase contains one or many Tests. +// In Google Test, a unit test program contains one or many TestSuites, and +// each TestSuite contains one or many Tests. // // When you define a test using the TEST macro, you don't need to // explicitly derive from Test - the TEST macro automatically does @@ -411,29 +416,30 @@ class GTEST_API_ Test { public: friend class TestInfo; - // Defines types for pointers to functions that set up and tear down - // a test case. - typedef internal::SetUpTestCaseFunc SetUpTestCaseFunc; - typedef internal::TearDownTestCaseFunc TearDownTestCaseFunc; - // The d'tor is virtual as we intend to inherit from Test. virtual ~Test(); // Sets up the stuff shared by all tests in this test case. // - // Google Test will call Foo::SetUpTestCase() before running the first + // Google Test will call Foo::SetUpTestSuite() before running the first // test in test case Foo. Hence a sub-class can define its own - // SetUpTestCase() method to shadow the one defined in the super + // SetUpTestSuite() method to shadow the one defined in the super // class. - static void SetUpTestCase() {} + static void SetUpTestSuite() {} // Tears down the stuff shared by all tests in this test case. // - // Google Test will call Foo::TearDownTestCase() after running the last + // Google Test will call Foo::TearDownTestSuite() after running the last // test in test case Foo. Hence a sub-class can define its own - // TearDownTestCase() method to shadow the one defined in the super + // TearDownTestSuite() method to shadow the one defined in the super // class. + static void TearDownTestSuite() {} + + // Legacy API is deprecated but still available +#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_ static void TearDownTestCase() {} + static void SetUpTestCase() {} +#endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_ // Returns true iff the current test has a fatal failure. static bool HasFatalFailure(); @@ -448,15 +454,15 @@ class GTEST_API_ Test { // non-fatal) failure. static bool HasFailure() { return HasFatalFailure() || HasNonfatalFailure(); } - // Logs a property for the current test, test case, or for the entire + // Logs a property for the current test, test suite, or for the entire // invocation of the test program when used outside of the context of a - // test case. Only the last value for a given key is remembered. These + // test suite. Only the last value for a given key is remembered. These // are public static so they can be called from utility functions that are // not members of the test fixture. Calls to RecordProperty made during // lifespan of the test (from the moment its constructor starts to the // moment its destructor finishes) will be output in XML as attributes of // the element. Properties recorded from fixture's - // SetUpTestCase or TearDownTestCase are logged as attributes of the + // SetUpTestSuite or TearDownTestSuite are logged as attributes of the // corresponding element. Calls to RecordProperty made in the // global context (before or after invocation of RUN_ALL_TESTS and from // SetUp/TearDown method of Environment objects registered with Google @@ -476,7 +482,7 @@ class GTEST_API_ Test { private: // Returns true iff the current test has the same fixture class as - // the first test in the current test case. + // the first test in the current test suite. static bool HasSameFixtureClass(); // Runs the test after the test fixture has been set up. @@ -606,7 +612,7 @@ class GTEST_API_ TestResult { private: friend class TestInfo; - friend class TestCase; + friend class TestSuite; friend class UnitTest; friend class internal::DefaultGlobalTestPartResultReporter; friend class internal::ExecDeathTest; @@ -638,7 +644,7 @@ class GTEST_API_ TestResult { const TestProperty& test_property); // Adds a failure if the key is a reserved attribute of Google Test - // testcase tags. Returns true if the property is valid. + // testsuite tags. Returns true if the property is valid. // FIXME: Validate attribute names are legal and human readable. static bool ValidateTestProperty(const std::string& xml_element, const TestProperty& test_property); @@ -677,7 +683,7 @@ class GTEST_API_ TestResult { // A TestInfo object stores the following information about a test: // -// Test case name +// Test suite name // Test name // Whether the test should be run // A function pointer that creates the test object when invoked @@ -692,8 +698,13 @@ class GTEST_API_ TestInfo { // don't inherit from TestInfo. ~TestInfo(); - // Returns the test case name. - const char* test_case_name() const { return test_case_name_.c_str(); } + // Returns the test suite name. + const char* test_suite_name() const { return test_suite_name_.c_str(); } + +// Legacy API is deprecated but still available +#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_ + const char* test_case_name() const { return test_suite_name(); } +#endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_ // Returns the test name. const char* name() const { return name_.c_str(); } @@ -726,7 +737,7 @@ class GTEST_API_ TestInfo { // been specified) and its full name matches the user-specified filter. // // Google Test allows the user to filter the tests by their full names. - // The full name of a test Bar in test case Foo is defined as + // The full name of a test Bar in test suite Foo is defined as // "Foo.Bar". Only the tests that match the filter will run. // // A filter is a colon-separated list of glob (not regex) patterns, @@ -754,24 +765,19 @@ class GTEST_API_ TestInfo { friend class internal::DefaultDeathTestFactory; #endif // GTEST_HAS_DEATH_TEST friend class Test; - friend class TestCase; + friend class TestSuite; friend class internal::UnitTestImpl; friend class internal::StreamingListenerTest; friend TestInfo* internal::MakeAndRegisterTestInfo( - const char* test_case_name, - const char* name, - const char* type_param, - const char* value_param, - internal::CodeLocation code_location, - internal::TypeId fixture_class_id, - Test::SetUpTestCaseFunc set_up_tc, - Test::TearDownTestCaseFunc tear_down_tc, + const char* test_suite_name, const char* name, const char* type_param, + const char* value_param, internal::CodeLocation code_location, + internal::TypeId fixture_class_id, internal::SetUpTestSuiteFunc set_up_tc, + internal::TearDownTestSuiteFunc tear_down_tc, internal::TestFactoryBase* factory); // Constructs a TestInfo object. The newly constructed instance assumes // ownership of the factory object. - TestInfo(const std::string& test_case_name, - const std::string& name, + TestInfo(const std::string& test_suite_name, const std::string& name, const char* a_type_param, // NULL if not a type-parameterized test const char* a_value_param, // NULL if not a value-parameterized test internal::CodeLocation a_code_location, @@ -793,7 +799,7 @@ class GTEST_API_ TestInfo { } // These fields are immutable properties of the test. - const std::string test_case_name_; // Test case name + const std::string test_suite_name_; // test suite name const std::string name_; // Test name // Name of the parameter type, or NULL if this is not a typed or a // type-parameterized test. @@ -818,71 +824,71 @@ class GTEST_API_ TestInfo { GTEST_DISALLOW_COPY_AND_ASSIGN_(TestInfo); }; -// A test case, which consists of a vector of TestInfos. +// A test suite, which consists of a vector of TestInfos. // -// TestCase is not copyable. -class GTEST_API_ TestCase { +// TestSuite is not copyable. +class GTEST_API_ TestSuite { public: - // Creates a TestCase with the given name. + // Creates a TestSuite with the given name. // - // TestCase does NOT have a default constructor. Always use this - // constructor to create a TestCase object. + // TestSuite does NOT have a default constructor. Always use this + // constructor to create a TestSuite object. // // Arguments: // - // name: name of the test case + // name: name of the test suite // a_type_param: the name of the test's type parameter, or NULL if // this is not a type-parameterized test. - // set_up_tc: pointer to the function that sets up the test case - // tear_down_tc: pointer to the function that tears down the test case - TestCase(const char* name, const char* a_type_param, - Test::SetUpTestCaseFunc set_up_tc, - Test::TearDownTestCaseFunc tear_down_tc); + // set_up_tc: pointer to the function that sets up the test suite + // tear_down_tc: pointer to the function that tears down the test suite + TestSuite(const char* name, const char* a_type_param, + internal::SetUpTestSuiteFunc set_up_tc, + internal::TearDownTestSuiteFunc tear_down_tc); - // Destructor of TestCase. - virtual ~TestCase(); + // Destructor of TestSuite. + virtual ~TestSuite(); - // Gets the name of the TestCase. + // Gets the name of the TestSuite. const char* name() const { return name_.c_str(); } // Returns the name of the parameter type, or NULL if this is not a - // type-parameterized test case. + // type-parameterized test suite. const char* type_param() const { if (type_param_.get() != nullptr) return type_param_->c_str(); return nullptr; } - // Returns true if any test in this test case should run. + // Returns true if any test in this test suite should run. bool should_run() const { return should_run_; } - // Gets the number of successful tests in this test case. + // Gets the number of successful tests in this test suite. int successful_test_count() const; - // Gets the number of skipped tests in this test case. + // Gets the number of skipped tests in this test suite. int skipped_test_count() const; - // Gets the number of failed tests in this test case. + // Gets the number of failed tests in this test suite. int failed_test_count() const; // Gets the number of disabled tests that will be reported in the XML report. int reportable_disabled_test_count() const; - // Gets the number of disabled tests in this test case. + // Gets the number of disabled tests in this test suite. int disabled_test_count() const; // Gets the number of tests to be printed in the XML report. int reportable_test_count() const; - // Get the number of tests in this test case that should run. + // Get the number of tests in this test suite that should run. int test_to_run_count() const; - // Gets the number of all tests in this test case. + // Gets the number of all tests in this test suite. int total_test_count() const; - // Returns true iff the test case passed. + // Returns true iff the test suite passed. bool Passed() const { return !Failed(); } - // Returns true iff the test case failed. + // Returns true iff the test suite failed. bool Failed() const { return failed_test_count() > 0; } // Returns the elapsed time, in milliseconds. @@ -893,17 +899,17 @@ class GTEST_API_ TestCase { const TestInfo* GetTestInfo(int i) const; // Returns the TestResult that holds test properties recorded during - // execution of SetUpTestCase and TearDownTestCase. + // execution of SetUpTestSuite and TearDownTestSuite. const TestResult& ad_hoc_test_result() const { return ad_hoc_test_result_; } private: friend class Test; friend class internal::UnitTestImpl; - // Gets the (mutable) vector of TestInfos in this TestCase. + // Gets the (mutable) vector of TestInfos in this TestSuite. std::vector& test_info_list() { return test_info_list_; } - // Gets the (immutable) vector of TestInfos in this TestCase. + // Gets the (immutable) vector of TestInfos in this TestSuite. const std::vector& test_info_list() const { return test_info_list_; } @@ -915,28 +921,36 @@ class GTEST_API_ TestCase { // Sets the should_run member. void set_should_run(bool should) { should_run_ = should; } - // Adds a TestInfo to this test case. Will delete the TestInfo upon - // destruction of the TestCase object. + // Adds a TestInfo to this test suite. Will delete the TestInfo upon + // destruction of the TestSuite object. void AddTestInfo(TestInfo * test_info); - // Clears the results of all tests in this test case. + // Clears the results of all tests in this test suite. void ClearResult(); - // Clears the results of all tests in the given test case. - static void ClearTestCaseResult(TestCase* test_case) { - test_case->ClearResult(); + // Clears the results of all tests in the given test suite. + static void ClearTestSuiteResult(TestSuite* test_suite) { + test_suite->ClearResult(); } - // Runs every test in this TestCase. + // Runs every test in this TestSuite. void Run(); - // Runs SetUpTestCase() for this TestCase. This wrapper is needed - // for catching exceptions thrown from SetUpTestCase(). - void RunSetUpTestCase() { (*set_up_tc_)(); } + // Runs SetUpTestSuite() for this TestSuite. This wrapper is needed + // for catching exceptions thrown from SetUpTestSuite(). + void RunSetUpTestSuite() { + if (set_up_tc_ != nullptr) { + (*set_up_tc_)(); + } + } - // Runs TearDownTestCase() for this TestCase. This wrapper is - // needed for catching exceptions thrown from TearDownTestCase(). - void RunTearDownTestCase() { (*tear_down_tc_)(); } + // Runs TearDownTestSuite() for this TestSuite. This wrapper is + // needed for catching exceptions thrown from TearDownTestSuite(). + void RunTearDownTestSuite() { + if (tear_down_tc_ != nullptr) { + (*tear_down_tc_)(); + } + } // Returns true iff test passed. static bool TestPassed(const TestInfo* test_info) { @@ -974,13 +988,13 @@ class GTEST_API_ TestCase { return test_info->should_run(); } - // Shuffles the tests in this test case. + // Shuffles the tests in this test suite. void ShuffleTests(internal::Random* random); // Restores the test order to before the first shuffle. void UnshuffleTests(); - // Name of the test case. + // Name of the test suite. std::string name_; // Name of the parameter type, or NULL if this is not a typed or a // type-parameterized test. @@ -992,20 +1006,20 @@ class GTEST_API_ TestCase { // shuffling and restoring the test order. The i-th element in this // vector is the index of the i-th test in the shuffled test list. std::vector test_indices_; - // Pointer to the function that sets up the test case. - Test::SetUpTestCaseFunc set_up_tc_; - // Pointer to the function that tears down the test case. - Test::TearDownTestCaseFunc tear_down_tc_; - // True iff any test in this test case should run. + // Pointer to the function that sets up the test suite. + internal::SetUpTestSuiteFunc set_up_tc_; + // Pointer to the function that tears down the test suite. + internal::TearDownTestSuiteFunc tear_down_tc_; + // True iff any test in this test suite should run. bool should_run_; // Elapsed time, in milliseconds. TimeInMillis elapsed_time_; - // Holds test properties recorded during execution of SetUpTestCase and - // TearDownTestCase. + // Holds test properties recorded during execution of SetUpTestSuite and + // TearDownTestSuite. TestResult ad_hoc_test_result_; - // We disallow copying TestCases. - GTEST_DISALLOW_COPY_AND_ASSIGN_(TestCase); + // We disallow copying TestSuites. + GTEST_DISALLOW_COPY_AND_ASSIGN_(TestSuite); }; // An Environment object is capable of setting up and tearing down an @@ -1072,8 +1086,13 @@ class TestEventListener { // Fired after environment set-up for each iteration of tests ends. virtual void OnEnvironmentsSetUpEnd(const UnitTest& unit_test) = 0; - // Fired before the test case starts. - virtual void OnTestCaseStart(const TestCase& test_case) = 0; + // Fired before the test suite starts. + virtual void OnTestSuiteStart(const TestSuite& test_suite) {} + + // Legacy API is deprecated but still available +#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_ + virtual void OnTestCaseStart(const TestCase& test_case) {} +#endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_ // Fired before the test starts. virtual void OnTestStart(const TestInfo& test_info) = 0; @@ -1086,8 +1105,13 @@ class TestEventListener { // Fired after the test ends. virtual void OnTestEnd(const TestInfo& test_info) = 0; - // Fired after the test case ends. - virtual void OnTestCaseEnd(const TestCase& test_case) = 0; + // Fired after the test suite ends. + virtual void OnTestSuiteEnd(const TestSuite& test_suite) {} + +// Legacy API is deprecated but still available +#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_ + virtual void OnTestCaseEnd(const TestCase& test_case) {} +#endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_ // Fired before environment tear-down for each iteration of tests starts. virtual void OnEnvironmentsTearDownStart(const UnitTest& unit_test) = 0; @@ -1115,11 +1139,20 @@ class EmptyTestEventListener : public TestEventListener { int /*iteration*/) override {} void OnEnvironmentsSetUpStart(const UnitTest& /*unit_test*/) override {} void OnEnvironmentsSetUpEnd(const UnitTest& /*unit_test*/) override {} - void OnTestCaseStart(const TestCase& /*test_case*/) override {} + void OnTestSuiteStart(const TestSuite& /*test_suite*/) override {} +// Legacy API is deprecated but still available +#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_ + void OnTestCaseStart(const TestCase& tc /*test_suite*/) override {} +#endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_ + void OnTestStart(const TestInfo& /*test_info*/) override {} void OnTestPartResult(const TestPartResult& /*test_part_result*/) override {} void OnTestEnd(const TestInfo& /*test_info*/) override {} - void OnTestCaseEnd(const TestCase& /*test_case*/) override {} + void OnTestSuiteEnd(const TestSuite& /*test_suite*/) override {} +#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_ + void OnTestCaseEnd(const TestCase& tc /*test_suite*/) override {} +#endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_ + void OnEnvironmentsTearDownStart(const UnitTest& /*unit_test*/) override {} void OnEnvironmentsTearDownEnd(const UnitTest& /*unit_test*/) override {} void OnTestIterationEnd(const UnitTest& /*unit_test*/, @@ -1164,7 +1197,7 @@ class GTEST_API_ TestEventListeners { } private: - friend class TestCase; + friend class TestSuite; friend class TestInfo; friend class internal::DefaultGlobalTestPartResultReporter; friend class internal::NoExecDeathTest; @@ -1205,7 +1238,7 @@ class GTEST_API_ TestEventListeners { GTEST_DISALLOW_COPY_AND_ASSIGN_(TestEventListeners); }; -// A UnitTest consists of a vector of TestCases. +// A UnitTest consists of a vector of TestSuites. // // This is a singleton class. The only instance of UnitTest is // created when UnitTest::GetInstance() is first called. This @@ -1234,10 +1267,14 @@ class GTEST_API_ UnitTest { // was executed. The UnitTest object owns the string. const char* original_working_dir() const; - // Returns the TestCase object for the test that's currently running, + // Returns the TestSuite object for the test that's currently running, // or NULL if no test is running. - const TestCase* current_test_case() const - GTEST_LOCK_EXCLUDED_(mutex_); + const TestSuite* current_test_suite() const GTEST_LOCK_EXCLUDED_(mutex_); + +// Legacy API is still available but deprecated +#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_ + const TestCase* current_test_case() const GTEST_LOCK_EXCLUDED_(mutex_); +#endif // Returns the TestInfo object for the test that's currently running, // or NULL if no test is running. @@ -1247,25 +1284,33 @@ class GTEST_API_ UnitTest { // Returns the random seed used at the start of the current test run. int random_seed() const; - // Returns the ParameterizedTestCaseRegistry object used to keep track of + // Returns the ParameterizedTestSuiteRegistry object used to keep track of // value-parameterized tests and instantiate and register them. // // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM. - internal::ParameterizedTestCaseRegistry& parameterized_test_registry() + internal::ParameterizedTestSuiteRegistry& parameterized_test_registry() GTEST_LOCK_EXCLUDED_(mutex_); - // Gets the number of successful test cases. - int successful_test_case_count() const; + // Gets the number of successful test suites. + int successful_test_suite_count() const; - // Gets the number of failed test cases. - int failed_test_case_count() const; + // Gets the number of failed test suites. + int failed_test_suite_count() const; - // Gets the number of all test cases. - int total_test_case_count() const; + // Gets the number of all test suites. + int total_test_suite_count() const; - // Gets the number of all test cases that contain at least one test + // Gets the number of all test suites that contain at least one test // that should run. + int test_suite_to_run_count() const; + + // Legacy API is deprecated but still available +#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_ + int successful_test_case_count() const; + int failed_test_case_count() const; + int total_test_case_count() const; int test_case_to_run_count() const; +#endif // EMOVE_LEGACY_TEST_CASEAPI // Gets the number of successful tests. int successful_test_count() const; @@ -1298,19 +1343,24 @@ class GTEST_API_ UnitTest { // Gets the elapsed time, in milliseconds. TimeInMillis elapsed_time() const; - // Returns true iff the unit test passed (i.e. all test cases passed). + // Returns true iff the unit test passed (i.e. all test suites passed). bool Passed() const; - // Returns true iff the unit test failed (i.e. some test case failed + // Returns true iff the unit test failed (i.e. some test suite failed // or something outside of all tests failed). bool Failed() const; - // Gets the i-th test case among all the test cases. i can range from 0 to - // total_test_case_count() - 1. If i is not in that range, returns NULL. + // Gets the i-th test suite among all the test suites. i can range from 0 to + // total_test_suite_count() - 1. If i is not in that range, returns NULL. + const TestSuite* GetTestSuite(int i) const; + +// Legacy API is deprecated but still available +#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_ const TestCase* GetTestCase(int i) const; +#endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_ // Returns the TestResult containing information on test failures and - // properties logged outside of individual test cases. + // properties logged outside of individual test suites. const TestResult& ad_hoc_test_result() const; // Returns the list of event listeners that can be used to track events @@ -1341,15 +1391,15 @@ class GTEST_API_ UnitTest { GTEST_LOCK_EXCLUDED_(mutex_); // Adds a TestProperty to the current TestResult object when invoked from - // inside a test, to current TestCase's ad_hoc_test_result_ when invoked - // from SetUpTestCase or TearDownTestCase, or to the global property set + // inside a test, to current TestSuite's ad_hoc_test_result_ when invoked + // from SetUpTestSuite or TearDownTestSuite, or to the global property set // when invoked elsewhere. If the result already contains a property with // the same key, the value will be updated. void RecordProperty(const std::string& key, const std::string& value); - // Gets the i-th test case among all the test cases. i can range from 0 to - // total_test_case_count() - 1. If i is not in that range, returns NULL. - TestCase* GetMutableTestCase(int i); + // Gets the i-th test suite among all the test suites. i can range from 0 to + // total_test_suite_count() - 1. If i is not in that range, returns NULL. + TestSuite* GetMutableTestSuite(int i); // Accessors for the implementation object. internal::UnitTestImpl* impl() { return impl_; } @@ -1815,7 +1865,7 @@ GTEST_API_ GTEST_ATTRIBUTE_PRINTF_(2, 3) void ColoredPrintf(GTestColor color, // Foo foo; // ASSERT_TRUE(foo.DoesBar(GetParam())); // } -// INSTANTIATE_TEST_CASE_P(OneToTenRange, FooTest, ::testing::Range(1, 10)); +// INSTANTIATE_TEST_SUITE_P(OneToTenRange, FooTest, ::testing::Range(1, 10)); template class WithParamInterface { @@ -2282,11 +2332,11 @@ bool StaticAssertTypeEq() { // Defines a test. // -// The first parameter is the name of the test case, and the second -// parameter is the name of the test within the test case. +// The first parameter is the name of the test suite, and the second +// parameter is the name of the test within the test suite. // -// The convention is to end the test case name with "Test". For -// example, a test case for the Foo class can be named FooTest. +// The convention is to end the test suite name with "Test". For +// example, a test suite for the Foo class can be named FooTest. // // Test code should appear between braces after an invocation of // this macro. Example: @@ -2305,21 +2355,21 @@ bool StaticAssertTypeEq() { // code. GetTestTypeId() is guaranteed to always return the same // value, as it always calls GetTypeId<>() from the Google Test // framework. -#define GTEST_TEST(test_case_name, test_name)\ - GTEST_TEST_(test_case_name, test_name, \ - ::testing::Test, ::testing::internal::GetTestTypeId()) +#define GTEST_TEST(test_suite_name, test_name) \ + GTEST_TEST_(test_suite_name, test_name, ::testing::Test, \ + ::testing::internal::GetTestTypeId()) // Define this macro to 1 to omit the definition of TEST(), which // is a generic name and clashes with some other libraries. #if !GTEST_DONT_DEFINE_TEST -# define TEST(test_case_name, test_name) GTEST_TEST(test_case_name, test_name) +#define TEST(test_suite_name, test_name) GTEST_TEST(test_suite_name, test_name) #endif // Defines a test that uses a test fixture. // // The first parameter is the name of the test fixture class, which -// also doubles as the test case name. The second parameter is the -// name of the test within the test case. +// also doubles as the test suite name. The second parameter is the +// name of the test within the test suite. // // A test fixture class must be declared earlier. The user should put // the test code between braces after using this macro. Example: @@ -2363,11 +2413,11 @@ GTEST_API_ std::string TempDir(); // function pointer that creates a new instance of the Test object. It // handles ownership to the caller. The signature of the callable is // `Fixture*()`, where `Fixture` is the test fixture class for the test. All -// tests registered with the same `test_case_name` must return the same +// tests registered with the same `test_suite_name` must return the same // fixture type. This is checked at runtime. // // The framework will infer the fixture class from the factory and will call -// the `SetUpTestCase` and `TearDownTestCase` for it. +// the `SetUpTestSuite` and `TearDownTestSuite` for it. // // Must be called before `RUN_ALL_TESTS()` is invoked, otherwise behavior is // undefined. @@ -2377,8 +2427,8 @@ GTEST_API_ std::string TempDir(); // class MyFixture : public ::testing::Test { // public: // // All of these optional, just like in regular macro usage. -// static void SetUpTestCase() { ... } -// static void TearDownTestCase() { ... } +// static void SetUpTestSuite() { ... } +// static void TearDownTestSuite() { ... } // void SetUp() override { ... } // void TearDown() override { ... } // }; @@ -2411,18 +2461,11 @@ GTEST_API_ std::string TempDir(); // } // template -TestInfo* RegisterTest(const char* test_case_name, const char* test_name, +TestInfo* RegisterTest(const char* test_suite_name, const char* test_name, const char* type_param, const char* value_param, const char* file, int line, Factory factory) { using TestT = typename std::remove_pointer::type; - // Helper class to get SetUpTestCase and TearDownTestCase when they are in a - // protected scope. - struct Helper : TestT { - using TestT::SetUpTestCase; - using TestT::TearDownTestCase; - }; - class FactoryImpl : public internal::TestFactoryBase { public: explicit FactoryImpl(Factory f) : factory_(std::move(f)) {} @@ -2433,9 +2476,10 @@ TestInfo* RegisterTest(const char* test_case_name, const char* test_name, }; return internal::MakeAndRegisterTestInfo( - test_case_name, test_name, type_param, value_param, + test_suite_name, test_name, type_param, value_param, internal::CodeLocation(file, line), internal::GetTypeId(), - &Helper::SetUpTestCase, &Helper::TearDownTestCase, + internal::SuiteApiResolver::GetSetUpCaseOrSuite(), + internal::SuiteApiResolver::GetTearDownCaseOrSuite(), new FactoryImpl{std::move(factory)}); } diff --git a/googletest/include/gtest/internal/gtest-internal.h b/googletest/include/gtest/internal/gtest-internal.h index 22d20006..02ef3b30 100644 --- a/googletest/include/gtest/internal/gtest-internal.h +++ b/googletest/include/gtest/internal/gtest-internal.h @@ -91,7 +91,7 @@ class Message; // Represents a failure message. class Test; // Represents a test. class TestInfo; // Information about a test. class TestPartResult; // Result of a test part. -class UnitTest; // A collection of test cases. +class UnitTest; // A collection of test suites. template ::std::string PrintToString(const T& value); @@ -412,7 +412,7 @@ typedef FloatingPoint Float; typedef FloatingPoint Double; // In order to catch the mistake of putting tests that use different -// test fixture classes in the same test case, we need to assign +// test fixture classes in the same test suite, we need to assign // unique IDs to fixture classes and compare them. The TypeId type is // used to hold such IDs. The user should treat TypeId as an opaque // type: the only operation allowed on TypeId values is to compare @@ -488,9 +488,9 @@ GTEST_API_ AssertionResult IsHRESULTFailure(const char* expr, #endif // GTEST_OS_WINDOWS -// Types of SetUpTestCase() and TearDownTestCase() functions. -typedef void (*SetUpTestCaseFunc)(); -typedef void (*TearDownTestCaseFunc)(); +// Types of SetUpTestSuite() and TearDownTestSuite() functions. +using SetUpTestSuiteFunc = void (*)(); +using TearDownTestSuiteFunc = void (*)(); struct CodeLocation { CodeLocation(const std::string& a_file, int a_line) @@ -500,12 +500,60 @@ struct CodeLocation { int line; }; +// Helper to identify which setup function for TestCase / TestSuite to call. +// Only one function is allowed, either TestCase or TestSute but not both. + +// Utility functions to help SuiteApiResolver +using SetUpTearDownSuiteFuncType = void (*)(); + +inline SetUpTearDownSuiteFuncType GetNotDefaultOrNull( + SetUpTearDownSuiteFuncType a, SetUpTearDownSuiteFuncType def) { + return a == def ? nullptr : a; +} + +template +// Note that SuiteApiResolver inherits from T because +// SetUpTestSuite()/TearDownTestSuite() could be protected. Ths way +// SuiteApiResolver can access them. +struct SuiteApiResolver : T { + // testing::Test is only forward declared at this point. So we make it a + // dependend class for the compiler to be OK with it. + using Test = + typename std::conditional::type; + + static SetUpTearDownSuiteFuncType GetSetUpCaseOrSuite() { + SetUpTearDownSuiteFuncType test_case_fp = + GetNotDefaultOrNull(&T::SetUpTestCase, &Test::SetUpTestCase); + SetUpTearDownSuiteFuncType test_suite_fp = + GetNotDefaultOrNull(&T::SetUpTestSuite, &Test::SetUpTestSuite); + + GTEST_CHECK_(!test_case_fp || !test_suite_fp) + << "Test can not provide both SetUpTestSuite and SetUpTestCase, please " + "make sure there is only one present "; + + return test_case_fp != nullptr ? test_case_fp : test_suite_fp; + } + + static SetUpTearDownSuiteFuncType GetTearDownCaseOrSuite() { + SetUpTearDownSuiteFuncType test_case_fp = + GetNotDefaultOrNull(&T::TearDownTestCase, &Test::TearDownTestCase); + SetUpTearDownSuiteFuncType test_suite_fp = + GetNotDefaultOrNull(&T::TearDownTestSuite, &Test::TearDownTestSuite); + + GTEST_CHECK_(!test_case_fp || !test_suite_fp) + << "Test can not provide both TearDownTestSuite and TearDownTestCase," + " please make sure there is only one present "; + + return test_case_fp != nullptr ? test_case_fp : test_suite_fp; + } +}; + // Creates a new TestInfo object and registers it with Google Test; // returns the created object. // // Arguments: // -// test_case_name: name of the test case +// test_suite_name: name of the test suite // name: name of the test // type_param the name of the test's type parameter, or NULL if // this is not a typed or a type-parameterized test. @@ -513,21 +561,16 @@ struct CodeLocation { // or NULL if this is not a type-parameterized test. // code_location: code location where the test is defined // fixture_class_id: ID of the test fixture class -// set_up_tc: pointer to the function that sets up the test case -// tear_down_tc: pointer to the function that tears down the test case +// set_up_tc: pointer to the function that sets up the test suite +// tear_down_tc: pointer to the function that tears down the test suite // factory: pointer to the factory that creates a test object. // The newly created TestInfo instance will assume // ownership of the factory object. GTEST_API_ TestInfo* MakeAndRegisterTestInfo( - const char* test_case_name, - const char* name, - const char* type_param, - const char* value_param, - CodeLocation code_location, - TypeId fixture_class_id, - SetUpTestCaseFunc set_up_tc, - TearDownTestCaseFunc tear_down_tc, - TestFactoryBase* factory); + const char* test_suite_name, const char* name, const char* type_param, + const char* value_param, CodeLocation code_location, + TypeId fixture_class_id, SetUpTestSuiteFunc set_up_tc, + TearDownTestSuiteFunc tear_down_tc, TestFactoryBase* factory); // If *pstr starts with the given prefix, modifies *pstr to be right // past the prefix and returns true; otherwise leaves *pstr unchanged @@ -539,19 +582,20 @@ GTEST_API_ bool SkipPrefix(const char* prefix, const char** pstr); GTEST_DISABLE_MSC_WARNINGS_PUSH_(4251 \ /* class A needs to have dll-interface to be used by clients of class B */) -// State of the definition of a type-parameterized test case. -class GTEST_API_ TypedTestCasePState { +// State of the definition of a type-parameterized test suite. +class GTEST_API_ TypedTestSuitePState { public: - TypedTestCasePState() : registered_(false) {} + TypedTestSuitePState() : registered_(false) {} // Adds the given test name to defined_test_names_ and return true - // if the test case hasn't been registered; otherwise aborts the + // if the test suite hasn't been registered; otherwise aborts the // program. bool AddTestName(const char* file, int line, const char* case_name, const char* test_name) { if (registered_) { - fprintf(stderr, "%s Test %s must be defined before " - "REGISTER_TYPED_TEST_CASE_P(%s, ...).\n", + fprintf(stderr, + "%s Test %s must be defined before " + "REGISTER_TYPED_TEST_SUITE_P(%s, ...).\n", FormatFileLocation(file, line).c_str(), test_name, case_name); fflush(stderr); posix::Abort(); @@ -584,6 +628,11 @@ class GTEST_API_ TypedTestCasePState { RegisteredTestsMap registered_tests_; }; +// Legacy API is deprecated but still available +#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_ +using TypedTestCasePState = TypedTestSuitePState; +#endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_ + GTEST_DISABLE_MSC_WARNINGS_POP_() // 4251 // Skips to the first non-space char after the first comma in 'str'; @@ -651,7 +700,7 @@ template class TypeParameterizedTest { public: // 'index' is the index of the test in the type list 'Types' - // specified in INSTANTIATE_TYPED_TEST_CASE_P(Prefix, TestCase, + // specified in INSTANTIATE_TYPED_TEST_SUITE_P(Prefix, TestSuite, // Types). Valid values for 'index' are [0, N - 1] where N is the // length of Types. static bool Register(const char* prefix, const CodeLocation& code_location, @@ -671,8 +720,10 @@ class TypeParameterizedTest { StripTrailingSpaces(GetPrefixUntilComma(test_names)).c_str(), GetTypeName().c_str(), nullptr, // No value parameter. - code_location, GetTypeId(), TestClass::SetUpTestCase, - TestClass::TearDownTestCase, new TestFactoryImpl); + code_location, GetTypeId(), + SuiteApiResolver::GetSetUpCaseOrSuite(), + SuiteApiResolver::GetTearDownCaseOrSuite(), + new TestFactoryImpl); // Next, recurses (at compile time) with the tail of the type list. return TypeParameterizedTest { } }; -// TypeParameterizedTestCase::Register() +// TypeParameterizedTestSuite::Register() // registers *all combinations* of 'Tests' and 'Types' with Google // Test. The return value is insignificant - we just need to return // something such that we can call this function in a namespace scope. template -class TypeParameterizedTestCase { +class TypeParameterizedTestSuite { public: static bool Register(const char* prefix, CodeLocation code_location, - const TypedTestCasePState* state, const char* case_name, + const TypedTestSuitePState* state, const char* case_name, const char* test_names, const std::vector& type_names = GenerateNames()) { @@ -729,20 +780,20 @@ class TypeParameterizedTestCase { prefix, test_location, case_name, test_names, 0, type_names); // Next, recurses (at compile time) with the tail of the test list. - return TypeParameterizedTestCase::Register(prefix, code_location, - state, case_name, - SkipComma(test_names), - type_names); + return TypeParameterizedTestSuite::Register(prefix, code_location, + state, case_name, + SkipComma(test_names), + type_names); } }; // The base case for the compile time recursion. template -class TypeParameterizedTestCase { +class TypeParameterizedTestSuite { public: static bool Register(const char* /*prefix*/, const CodeLocation&, - const TypedTestCasePState* /*state*/, + const TypedTestSuitePState* /*state*/, const char* /*case_name*/, const char* /*test_names*/, const std::vector& = std::vector() /*type_names*/) { @@ -1376,32 +1427,35 @@ class FlatTuple " Actual: it does.") // Expands to the name of the class that implements the given test. -#define GTEST_TEST_CLASS_NAME_(test_case_name, test_name) \ - test_case_name##_##test_name##_Test +#define GTEST_TEST_CLASS_NAME_(test_suite_name, test_name) \ + test_suite_name##_##test_name##_Test // Helper macro for defining tests. -#define GTEST_TEST_(test_case_name, test_name, parent_class, parent_id) \ - class GTEST_TEST_CLASS_NAME_(test_case_name, test_name) \ +#define GTEST_TEST_(test_suite_name, test_name, parent_class, parent_id) \ + class GTEST_TEST_CLASS_NAME_(test_suite_name, test_name) \ : public parent_class { \ public: \ - GTEST_TEST_CLASS_NAME_(test_case_name, test_name)() {} \ + GTEST_TEST_CLASS_NAME_(test_suite_name, test_name)() {} \ \ private: \ virtual void TestBody(); \ static ::testing::TestInfo* const test_info_ GTEST_ATTRIBUTE_UNUSED_; \ - GTEST_DISALLOW_COPY_AND_ASSIGN_(GTEST_TEST_CLASS_NAME_(test_case_name, \ + GTEST_DISALLOW_COPY_AND_ASSIGN_(GTEST_TEST_CLASS_NAME_(test_suite_name, \ test_name)); \ }; \ \ - ::testing::TestInfo* const GTEST_TEST_CLASS_NAME_(test_case_name, \ + ::testing::TestInfo* const GTEST_TEST_CLASS_NAME_(test_suite_name, \ test_name)::test_info_ = \ ::testing::internal::MakeAndRegisterTestInfo( \ - #test_case_name, #test_name, nullptr, nullptr, \ + #test_suite_name, #test_name, nullptr, nullptr, \ ::testing::internal::CodeLocation(__FILE__, __LINE__), (parent_id), \ - parent_class::SetUpTestCase, parent_class::TearDownTestCase, \ + ::testing::internal::SuiteApiResolver< \ + parent_class>::GetSetUpCaseOrSuite(), \ + ::testing::internal::SuiteApiResolver< \ + parent_class>::GetTearDownCaseOrSuite(), \ new ::testing::internal::TestFactoryImpl); \ - void GTEST_TEST_CLASS_NAME_(test_case_name, test_name)::TestBody() + test_suite_name, test_name)>); \ + void GTEST_TEST_CLASS_NAME_(test_suite_name, test_name)::TestBody() // Internal Macro to mark an API deprecated, for googletest usage only // Usage: class GTEST_INTERNAL_DEPRECATED(message) MyClass or diff --git a/googletest/include/gtest/internal/gtest-param-util.h b/googletest/include/gtest/internal/gtest-param-util.h index f0c52600..bca72539 100644 --- a/googletest/include/gtest/internal/gtest-param-util.h +++ b/googletest/include/gtest/internal/gtest-param-util.h @@ -75,11 +75,11 @@ namespace internal { // Utility Functions // Outputs a message explaining invalid registration of different -// fixture class for the same test case. This may happen when +// fixture class for the same test suite. This may happen when // TEST_P macro is used to define two tests with the same name // but in different namespaces. -GTEST_API_ void ReportInvalidTestCaseType(const char* test_case_name, - CodeLocation code_location); +GTEST_API_ void ReportInvalidTestSuiteType(const char* test_suite_name, + CodeLocation code_location); template class ParamGeneratorInterface; template class ParamGenerator; @@ -379,7 +379,7 @@ std::string DefaultParamName(const TestParamInfo& info) { // INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE. // // Parameterized test name overload helpers, which help the -// INSTANTIATE_TEST_CASE_P macro choose between the default parameterized +// INSTANTIATE_TEST_SUITE_P macro choose between the default parameterized // test name generator and user param name generator. template ParamNameGenFunctor GetParamNameGen(ParamNameGenFunctor func) { @@ -434,19 +434,19 @@ class TestMetaFactoryBase { // TestMetaFactory creates test factories for passing into // MakeAndRegisterTestInfo function. Since MakeAndRegisterTestInfo receives // ownership of test factory pointer, same factory object cannot be passed -// into that method twice. But ParameterizedTestCaseInfo is going to call +// into that method twice. But ParameterizedTestSuiteInfo is going to call // it for each Test/Parameter value combination. Thus it needs meta factory // creator class. -template +template class TestMetaFactory - : public TestMetaFactoryBase { + : public TestMetaFactoryBase { public: - typedef typename TestCase::ParamType ParamType; + using ParamType = typename TestSuite::ParamType; TestMetaFactory() {} TestFactoryBase* CreateTestFactory(ParamType parameter) override { - return new ParameterizedTestFactory(parameter); + return new ParameterizedTestFactory(parameter); } private: @@ -455,89 +455,88 @@ class TestMetaFactory // INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE. // -// ParameterizedTestCaseInfoBase is a generic interface -// to ParameterizedTestCaseInfo classes. ParameterizedTestCaseInfoBase +// ParameterizedTestSuiteInfoBase is a generic interface +// to ParameterizedTestSuiteInfo classes. ParameterizedTestSuiteInfoBase // accumulates test information provided by TEST_P macro invocations -// and generators provided by INSTANTIATE_TEST_CASE_P macro invocations +// and generators provided by INSTANTIATE_TEST_SUITE_P macro invocations // and uses that information to register all resulting test instances -// in RegisterTests method. The ParameterizeTestCaseRegistry class holds -// a collection of pointers to the ParameterizedTestCaseInfo objects +// in RegisterTests method. The ParameterizeTestSuiteRegistry class holds +// a collection of pointers to the ParameterizedTestSuiteInfo objects // and calls RegisterTests() on each of them when asked. -class ParameterizedTestCaseInfoBase { +class ParameterizedTestSuiteInfoBase { public: - virtual ~ParameterizedTestCaseInfoBase() {} + virtual ~ParameterizedTestSuiteInfoBase() {} - // Base part of test case name for display purposes. - virtual const std::string& GetTestCaseName() const = 0; + // Base part of test suite name for display purposes. + virtual const std::string& GetTestSuiteName() const = 0; // Test case id to verify identity. - virtual TypeId GetTestCaseTypeId() const = 0; + virtual TypeId GetTestSuiteTypeId() const = 0; // UnitTest class invokes this method to register tests in this - // test case right before running them in RUN_ALL_TESTS macro. + // test suite right before running them in RUN_ALL_TESTS macro. // This method should not be called more then once on any single - // instance of a ParameterizedTestCaseInfoBase derived class. + // instance of a ParameterizedTestSuiteInfoBase derived class. virtual void RegisterTests() = 0; protected: - ParameterizedTestCaseInfoBase() {} + ParameterizedTestSuiteInfoBase() {} private: - GTEST_DISALLOW_COPY_AND_ASSIGN_(ParameterizedTestCaseInfoBase); + GTEST_DISALLOW_COPY_AND_ASSIGN_(ParameterizedTestSuiteInfoBase); }; // INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE. // -// ParameterizedTestCaseInfo accumulates tests obtained from TEST_P -// macro invocations for a particular test case and generators -// obtained from INSTANTIATE_TEST_CASE_P macro invocations for that -// test case. It registers tests with all values generated by all +// ParameterizedTestSuiteInfo accumulates tests obtained from TEST_P +// macro invocations for a particular test suite and generators +// obtained from INSTANTIATE_TEST_SUITE_P macro invocations for that +// test suite. It registers tests with all values generated by all // generators when asked. -template -class ParameterizedTestCaseInfo : public ParameterizedTestCaseInfoBase { +template +class ParameterizedTestSuiteInfo : public ParameterizedTestSuiteInfoBase { public: // ParamType and GeneratorCreationFunc are private types but are required // for declarations of public methods AddTestPattern() and - // AddTestCaseInstantiation(). - typedef typename TestCase::ParamType ParamType; + // AddTestSuiteInstantiation(). + using ParamType = typename TestSuite::ParamType; // A function that returns an instance of appropriate generator type. typedef ParamGenerator(GeneratorCreationFunc)(); typedef typename ParamNameGenFunc::Type ParamNameGeneratorFunc; - explicit ParameterizedTestCaseInfo( - const char* name, CodeLocation code_location) - : test_case_name_(name), code_location_(code_location) {} + explicit ParameterizedTestSuiteInfo(const char* name, + CodeLocation code_location) + : test_suite_name_(name), code_location_(code_location) {} // Test case base name for display purposes. - const std::string& GetTestCaseName() const override { - return test_case_name_; + const std::string& GetTestSuiteName() const override { + return test_suite_name_; } // Test case id to verify identity. - TypeId GetTestCaseTypeId() const override { return GetTypeId(); } + TypeId GetTestSuiteTypeId() const override { return GetTypeId(); } // TEST_P macro uses AddTestPattern() to record information // about a single test in a LocalTestInfo structure. - // test_case_name is the base name of the test case (without invocation + // test_suite_name is the base name of the test suite (without invocation // prefix). test_base_name is the name of an individual test without // parameter index. For the test SequenceA/FooTest.DoBar/1 FooTest is - // test case base name and DoBar is test base name. - void AddTestPattern(const char* test_case_name, - const char* test_base_name, + // test suite base name and DoBar is test base name. + void AddTestPattern(const char* test_suite_name, const char* test_base_name, TestMetaFactoryBase* meta_factory) { tests_.push_back(std::shared_ptr( - new TestInfo(test_case_name, test_base_name, meta_factory))); + new TestInfo(test_suite_name, test_base_name, meta_factory))); } - // INSTANTIATE_TEST_CASE_P macro uses AddGenerator() to record information + // INSTANTIATE_TEST_SUITE_P macro uses AddGenerator() to record information // about a generator. - int AddTestCaseInstantiation(const std::string& instantiation_name, - GeneratorCreationFunc* func, - ParamNameGeneratorFunc* name_func, - const char* file, int line) { + int AddTestSuiteInstantiation(const std::string& instantiation_name, + GeneratorCreationFunc* func, + ParamNameGeneratorFunc* name_func, + const char* file, int line) { instantiations_.push_back( InstantiationInfo(instantiation_name, func, name_func, file, line)); return 0; // Return value used only to run this method in namespace scope. } - // UnitTest class invokes this method to register tests in this test case - // test cases right before running tests in RUN_ALL_TESTS macro. + // UnitTest class invokes this method to register tests in this test suite + // test suites right before running tests in RUN_ALL_TESTS macro. // This method should not be called more then once on any single - // instance of a ParameterizedTestCaseInfoBase derived class. + // instance of a ParameterizedTestSuiteInfoBase derived class. // UnitTest has a guard to prevent from calling this method more then once. void RegisterTests() override { for (typename TestInfoContainer::iterator test_it = tests_.begin(); @@ -552,10 +551,10 @@ class ParameterizedTestCaseInfo : public ParameterizedTestCaseInfoBase { const char* file = gen_it->file; int line = gen_it->line; - std::string test_case_name; + std::string test_suite_name; if ( !instantiation_name.empty() ) - test_case_name = instantiation_name + "/"; - test_case_name += test_info->test_case_base_name; + test_suite_name = instantiation_name + "/"; + test_suite_name += test_info->test_suite_base_name; size_t i = 0; std::set test_param_names; @@ -580,11 +579,12 @@ class ParameterizedTestCaseInfo : public ParameterizedTestCaseInfoBase { test_name_stream << test_info->test_base_name << "/" << param_name; MakeAndRegisterTestInfo( - test_case_name.c_str(), test_name_stream.GetString().c_str(), + test_suite_name.c_str(), test_name_stream.GetString().c_str(), nullptr, // No type parameter. PrintToString(*param_it).c_str(), code_location_, - GetTestCaseTypeId(), TestCase::SetUpTestCase, - TestCase::TearDownTestCase, + GetTestSuiteTypeId(), + SuiteApiResolver::GetSetUpCaseOrSuite(), + SuiteApiResolver::GetTearDownCaseOrSuite(), test_info->test_meta_factory->CreateTestFactory(*param_it)); } // for param_it } // for gen_it @@ -595,19 +595,18 @@ class ParameterizedTestCaseInfo : public ParameterizedTestCaseInfoBase { // LocalTestInfo structure keeps information about a single test registered // with TEST_P macro. struct TestInfo { - TestInfo(const char* a_test_case_base_name, - const char* a_test_base_name, - TestMetaFactoryBase* a_test_meta_factory) : - test_case_base_name(a_test_case_base_name), - test_base_name(a_test_base_name), - test_meta_factory(a_test_meta_factory) {} - - const std::string test_case_base_name; + TestInfo(const char* a_test_suite_base_name, const char* a_test_base_name, + TestMetaFactoryBase* a_test_meta_factory) + : test_suite_base_name(a_test_suite_base_name), + test_base_name(a_test_base_name), + test_meta_factory(a_test_meta_factory) {} + + const std::string test_suite_base_name; const std::string test_base_name; const std::unique_ptr > test_meta_factory; }; using TestInfoContainer = ::std::vector >; - // Records data received from INSTANTIATE_TEST_CASE_P macros: + // Records data received from INSTANTIATE_TEST_SUITE_P macros: // struct InstantiationInfo { @@ -644,76 +643,87 @@ class ParameterizedTestCaseInfo : public ParameterizedTestCaseInfoBase { return true; } - const std::string test_case_name_; + const std::string test_suite_name_; CodeLocation code_location_; TestInfoContainer tests_; InstantiationContainer instantiations_; - GTEST_DISALLOW_COPY_AND_ASSIGN_(ParameterizedTestCaseInfo); -}; // class ParameterizedTestCaseInfo + GTEST_DISALLOW_COPY_AND_ASSIGN_(ParameterizedTestSuiteInfo); +}; // class ParameterizedTestSuiteInfo + +// Legacy API is deprecated but still available +#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_ +template +using ParameterizedTestCaseInfo = ParameterizedTestSuiteInfo; +#endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_ // INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE. // -// ParameterizedTestCaseRegistry contains a map of ParameterizedTestCaseInfoBase -// classes accessed by test case names. TEST_P and INSTANTIATE_TEST_CASE_P -// macros use it to locate their corresponding ParameterizedTestCaseInfo -// descriptors. -class ParameterizedTestCaseRegistry { +// ParameterizedTestSuiteRegistry contains a map of +// ParameterizedTestSuiteInfoBase classes accessed by test suite names. TEST_P +// and INSTANTIATE_TEST_SUITE_P macros use it to locate their corresponding +// ParameterizedTestSuiteInfo descriptors. +class ParameterizedTestSuiteRegistry { public: - ParameterizedTestCaseRegistry() {} - ~ParameterizedTestCaseRegistry() { - for (TestCaseInfoContainer::iterator it = test_case_infos_.begin(); - it != test_case_infos_.end(); ++it) { - delete *it; + ParameterizedTestSuiteRegistry() {} + ~ParameterizedTestSuiteRegistry() { + for (auto& test_suite_info : test_suite_infos_) { + delete test_suite_info; } } // Looks up or creates and returns a structure containing information about - // tests and instantiations of a particular test case. - template - ParameterizedTestCaseInfo* GetTestCasePatternHolder( - const char* test_case_name, - CodeLocation code_location) { - ParameterizedTestCaseInfo* typed_test_info = nullptr; - for (TestCaseInfoContainer::iterator it = test_case_infos_.begin(); - it != test_case_infos_.end(); ++it) { - if ((*it)->GetTestCaseName() == test_case_name) { - if ((*it)->GetTestCaseTypeId() != GetTypeId()) { + // tests and instantiations of a particular test suite. + template + ParameterizedTestSuiteInfo* GetTestSuitePatternHolder( + const char* test_suite_name, CodeLocation code_location) { + ParameterizedTestSuiteInfo* typed_test_info = nullptr; + for (auto& test_suite_info : test_suite_infos_) { + if (test_suite_info->GetTestSuiteName() == test_suite_name) { + if (test_suite_info->GetTestSuiteTypeId() != GetTypeId()) { // Complain about incorrect usage of Google Test facilities // and terminate the program since we cannot guaranty correct - // test case setup and tear-down in this case. - ReportInvalidTestCaseType(test_case_name, code_location); + // test suite setup and tear-down in this case. + ReportInvalidTestSuiteType(test_suite_name, code_location); posix::Abort(); } else { // At this point we are sure that the object we found is of the same // type we are looking for, so we downcast it to that type // without further checks. typed_test_info = CheckedDowncastToActualType< - ParameterizedTestCaseInfo >(*it); + ParameterizedTestSuiteInfo >(test_suite_info); } break; } } if (typed_test_info == nullptr) { - typed_test_info = new ParameterizedTestCaseInfo( - test_case_name, code_location); - test_case_infos_.push_back(typed_test_info); + typed_test_info = new ParameterizedTestSuiteInfo( + test_suite_name, code_location); + test_suite_infos_.push_back(typed_test_info); } return typed_test_info; } void RegisterTests() { - for (TestCaseInfoContainer::iterator it = test_case_infos_.begin(); - it != test_case_infos_.end(); ++it) { - (*it)->RegisterTests(); + for (auto& test_suite_info : test_suite_infos_) { + test_suite_info->RegisterTests(); } } +// Legacy API is deprecated but still available +#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_ + template + ParameterizedTestCaseInfo* GetTestCasePatternHolder( + const char* test_case_name, CodeLocation code_location) { + return GetTestSuitePatternHolder(test_case_name, code_location); + } + +#endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_ private: - typedef ::std::vector TestCaseInfoContainer; + using TestSuiteInfoContainer = ::std::vector; - TestCaseInfoContainer test_case_infos_; + TestSuiteInfoContainer test_suite_infos_; - GTEST_DISALLOW_COPY_AND_ASSIGN_(ParameterizedTestCaseRegistry); + GTEST_DISALLOW_COPY_AND_ASSIGN_(ParameterizedTestSuiteRegistry); }; } // namespace internal diff --git a/googletest/include/gtest/internal/gtest-port.h b/googletest/include/gtest/internal/gtest-port.h index d5839916..a77eb72d 100644 --- a/googletest/include/gtest/internal/gtest-port.h +++ b/googletest/include/gtest/internal/gtest-port.h @@ -250,6 +250,7 @@ #include #include #include +#include #ifndef _WIN32_WCE # include diff --git a/googletest/include/gtest/internal/gtest-type-util.h b/googletest/include/gtest/internal/gtest-type-util.h index fd4f9ed9..4cd1cf3c 100644 --- a/googletest/include/gtest/internal/gtest-type-util.h +++ b/googletest/include/gtest/internal/gtest-type-util.h @@ -31,12 +31,11 @@ // (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 case. +// type-parameterized tests in one type-parameterized test suite. // Please contact googletestframework@googlegroups.com if you need // more. @@ -3312,8 +3311,8 @@ struct Templates list in TYPED_TEST_CASE() and -// INSTANTIATE_TYPED_TEST_CASE_P(). +// or a Types<...> list in TYPED_TEST_SUITE() and +// INSTANTIATE_TYPED_TEST_SUITE_P(). template struct TypeList { diff --git a/googletest/include/gtest/internal/gtest-type-util.h.pump b/googletest/include/gtest/internal/gtest-type-util.h.pump index 61c9d362..eb014ee1 100644 --- a/googletest/include/gtest/internal/gtest-type-util.h.pump +++ b/googletest/include/gtest/internal/gtest-type-util.h.pump @@ -34,7 +34,7 @@ $var n = 50 $$ Maximum length of type lists we want to support. // 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 case. +// type-parameterized tests in one type-parameterized test suite. // Please contact googletestframework@googlegroups.com if you need // more. @@ -291,8 +291,8 @@ 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_CASE() and -// INSTANTIATE_TYPED_TEST_CASE_P(). +// or a Types<...> list in TYPED_TEST_SUITE() and +// INSTANTIATE_TYPED_TEST_SUITE_P(). template struct TypeList { diff --git a/googletest/src/gtest-death-test.cc b/googletest/src/gtest-death-test.cc index ddc3453b..9bdfdea4 100644 --- a/googletest/src/gtest-death-test.cc +++ b/googletest/src/gtest-death-test.cc @@ -753,9 +753,9 @@ DeathTest::TestRole WindowsDeathTest::AssumeRole() { FALSE, // The initial state is non-signalled. nullptr)); // The even is unnamed. GTEST_DEATH_TEST_CHECK_(event_handle_.Get() != nullptr); - const std::string filter_flag = - std::string("--") + GTEST_FLAG_PREFIX_ + kFilterFlag + "=" + - info->test_case_name() + "." + info->name(); + const std::string filter_flag = std::string("--") + GTEST_FLAG_PREFIX_ + + kFilterFlag + "=" + info->test_suite_name() + + "." + info->name(); const std::string internal_flag = std::string("--") + GTEST_FLAG_PREFIX_ + kInternalRunDeathTestFlag + "=" + file_ + "|" + StreamableToString(line_) + "|" + @@ -972,9 +972,9 @@ DeathTest::TestRole FuchsiaDeathTest::AssumeRole() { FlushInfoLog(); // Build the child process command line. - const std::string filter_flag = - std::string("--") + GTEST_FLAG_PREFIX_ + kFilterFlag + "=" - + info->test_case_name() + "." + info->name(); + const std::string filter_flag = std::string("--") + GTEST_FLAG_PREFIX_ + + kFilterFlag + "=" + info->test_suite_name() + + "." + info->name(); const std::string internal_flag = std::string("--") + GTEST_FLAG_PREFIX_ + kInternalRunDeathTestFlag + "=" + file_ + "|" @@ -1411,9 +1411,9 @@ DeathTest::TestRole ExecDeathTest::AssumeRole() { // it be closed when the child process does an exec: GTEST_DEATH_TEST_CHECK_(fcntl(pipe_fd[1], F_SETFD, 0) != -1); - const std::string filter_flag = - std::string("--") + GTEST_FLAG_PREFIX_ + kFilterFlag + "=" - + info->test_case_name() + "." + info->name(); + const std::string filter_flag = std::string("--") + GTEST_FLAG_PREFIX_ + + kFilterFlag + "=" + info->test_suite_name() + + "." + info->name(); const std::string internal_flag = std::string("--") + GTEST_FLAG_PREFIX_ + kInternalRunDeathTestFlag + "=" + file_ + "|" + StreamableToString(line_) + "|" diff --git a/googletest/src/gtest-internal-inl.h b/googletest/src/gtest-internal-inl.h index 09521649..29dc6820 100644 --- a/googletest/src/gtest-internal-inl.h +++ b/googletest/src/gtest-internal-inl.h @@ -388,10 +388,10 @@ class GTEST_API_ UnitTestOptions { // works well enough for matching test names, which are short. static bool PatternMatchesString(const char *pattern, const char *str); - // Returns true iff the user-specified filter matches the test case + // Returns true iff the user-specified filter matches the test suite // name and the test name. - static bool FilterMatchesTest(const std::string &test_case_name, - const std::string &test_name); + static bool FilterMatchesTest(const std::string& test_suite_name, + const std::string& test_name); #if GTEST_OS_WINDOWS // Function for supporting the gtest_catch_exception flag. @@ -529,18 +529,18 @@ class GTEST_API_ UnitTestImpl { void SetTestPartResultReporterForCurrentThread( TestPartResultReporterInterface* reporter); - // Gets the number of successful test cases. - int successful_test_case_count() const; + // Gets the number of successful test suites. + int successful_test_suite_count() const; - // Gets the number of failed test cases. - int failed_test_case_count() const; + // Gets the number of failed test suites. + int failed_test_suite_count() const; - // Gets the number of all test cases. - int total_test_case_count() const; + // Gets the number of all test suites. + int total_test_suite_count() const; - // Gets the number of all test cases that contain at least one test + // Gets the number of all test suites that contain at least one test // that should run. - int test_case_to_run_count() const; + int test_suite_to_run_count() const; // Gets the number of successful tests. int successful_test_count() const; @@ -573,27 +573,32 @@ class GTEST_API_ UnitTestImpl { // Gets the elapsed time, in milliseconds. TimeInMillis elapsed_time() const { return elapsed_time_; } - // Returns true iff the unit test passed (i.e. all test cases passed). + // Returns true iff the unit test passed (i.e. all test suites passed). bool Passed() const { return !Failed(); } - // Returns true iff the unit test failed (i.e. some test case failed + // Returns true iff the unit test failed (i.e. some test suite failed // or something outside of all tests failed). bool Failed() const { - return failed_test_case_count() > 0 || ad_hoc_test_result()->Failed(); + return failed_test_suite_count() > 0 || ad_hoc_test_result()->Failed(); } - // Gets the i-th test case among all the test cases. i can range from 0 to - // total_test_case_count() - 1. If i is not in that range, returns NULL. - const TestCase* GetTestCase(int i) const { - const int index = GetElementOr(test_case_indices_, i, -1); - return index < 0 ? nullptr : test_cases_[i]; + // Gets the i-th test suite among all the test suites. i can range from 0 to + // total_test_suite_count() - 1. If i is not in that range, returns NULL. + const TestSuite* GetTestSuite(int i) const { + const int index = GetElementOr(test_suite_indices_, i, -1); + return index < 0 ? nullptr : test_suites_[i]; } - // Gets the i-th test case among all the test cases. i can range from 0 to - // total_test_case_count() - 1. If i is not in that range, returns NULL. - TestCase* GetMutableTestCase(int i) { - const int index = GetElementOr(test_case_indices_, i, -1); - return index < 0 ? nullptr : test_cases_[index]; + // Legacy API is deprecated but still available +#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_ + const TestCase* GetTestCase(int i) const { return GetTestSuite(i); } +#endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_ + + // Gets the i-th test suite among all the test suites. i can range from 0 to + // total_test_suite_count() - 1. If i is not in that range, returns NULL. + TestSuite* GetMutableSuiteCase(int i) { + const int index = GetElementOr(test_suite_indices_, i, -1); + return index < 0 ? nullptr : test_suites_[index]; } // Provides access to the event listener list. @@ -630,30 +635,38 @@ class GTEST_API_ UnitTestImpl { // trace but Bar() and CurrentOsStackTraceExceptTop() won't. std::string CurrentOsStackTraceExceptTop(int skip_count) GTEST_NO_INLINE_; - // Finds and returns a TestCase with the given name. If one doesn't + // Finds and returns a TestSuite with the given name. If one doesn't // exist, creates one and returns it. // // Arguments: // - // test_case_name: name of the test case + // test_suite_name: name of the test suite // type_param: the name of the test's type parameter, or NULL if // this is not a typed or a type-parameterized test. - // set_up_tc: pointer to the function that sets up the test case - // tear_down_tc: pointer to the function that tears down the test case - TestCase* GetTestCase(const char* test_case_name, - const char* type_param, - Test::SetUpTestCaseFunc set_up_tc, - Test::TearDownTestCaseFunc tear_down_tc); + // set_up_tc: pointer to the function that sets up the test suite + // tear_down_tc: pointer to the function that tears down the test suite + TestSuite* GetTestSuite(const char* test_suite_name, const char* type_param, + internal::SetUpTestSuiteFunc set_up_tc, + internal::TearDownTestSuiteFunc tear_down_tc); + +// Legacy API is deprecated but still available +#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_ + TestCase* GetTestCase(const char* test_case_name, const char* type_param, + internal::SetUpTestSuiteFunc set_up_tc, + internal::TearDownTestSuiteFunc tear_down_tc) { + return GetTestSuite(test_case_name, type_param, set_up_tc, tear_down_tc); + } +#endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_ // Adds a TestInfo to the unit test. // // Arguments: // - // set_up_tc: pointer to the function that sets up the test case - // tear_down_tc: pointer to the function that tears down the test case + // set_up_tc: pointer to the function that sets up the test suite + // tear_down_tc: pointer to the function that tears down the test suite // test_info: the TestInfo object - void AddTestInfo(Test::SetUpTestCaseFunc set_up_tc, - Test::TearDownTestCaseFunc tear_down_tc, + void AddTestInfo(internal::SetUpTestSuiteFunc set_up_tc, + internal::TearDownTestSuiteFunc tear_down_tc, TestInfo* test_info) { // In order to support thread-safe death tests, we need to // remember the original working directory when the test program @@ -668,21 +681,20 @@ class GTEST_API_ UnitTestImpl { << "Failed to get the current working directory."; } - GetTestCase(test_info->test_case_name(), - test_info->type_param(), - set_up_tc, - tear_down_tc)->AddTestInfo(test_info); + GetTestSuite(test_info->test_suite_name(), test_info->type_param(), + set_up_tc, tear_down_tc) + ->AddTestInfo(test_info); } - // Returns ParameterizedTestCaseRegistry object used to keep track of + // Returns ParameterizedTestSuiteRegistry object used to keep track of // value-parameterized tests and instantiate and register them. - internal::ParameterizedTestCaseRegistry& parameterized_test_registry() { + internal::ParameterizedTestSuiteRegistry& parameterized_test_registry() { return parameterized_test_registry_; } - // Sets the TestCase object for the test that's currently running. - void set_current_test_case(TestCase* a_current_test_case) { - current_test_case_ = a_current_test_case; + // 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; } // Sets the TestInfo object for the test that's currently running. If @@ -693,7 +705,7 @@ class GTEST_API_ UnitTestImpl { } // Registers all parameterized tests defined using TEST_P and - // INSTANTIATE_TEST_CASE_P, creating regular tests for each test/parameter + // INSTANTIATE_TEST_SUITE_P, creating regular tests for each test/parameter // combination. This method can be called more then once; it has guards // protecting from registering the tests more then once. If // value-parameterized tests are disabled, RegisterParameterizedTests is @@ -708,7 +720,7 @@ class GTEST_API_ UnitTestImpl { // Clears the results of all tests, except the ad hoc tests. void ClearNonAdHocTestResult() { - ForEach(test_cases_, TestCase::ClearTestCaseResult); + ForEach(test_suites_, TestSuite::ClearTestSuiteResult); } // Clears the results of ad-hoc test assertions. @@ -717,7 +729,7 @@ class GTEST_API_ UnitTestImpl { } // Adds a TestProperty to the current TestResult object when invoked in a - // context of a test or a test case, or to the global property set. If the + // context of a test or a test suite, or to the global property set. If the // result already contains a property with the same key, the value will be // updated. void RecordProperty(const TestProperty& test_property); @@ -729,7 +741,7 @@ class GTEST_API_ UnitTestImpl { // Matches the full name of each test against the user-specified // filter to decide whether the test should run, then records the - // result in each TestCase and TestInfo object. + // result in each TestSuite and TestInfo object. // If shard_tests == HONOR_SHARDING_PROTOCOL, further filters tests // based on sharding variables in the environment. // Returns the number of tests that should run. @@ -738,7 +750,7 @@ class GTEST_API_ UnitTestImpl { // Prints the names of the tests matching the user-specified filter flag. void ListTestsMatchingFilter(); - const TestCase* current_test_case() const { return current_test_case_; } + const TestSuite* current_test_suite() const { return current_test_suite_; } TestInfo* current_test_info() { return current_test_info_; } const TestInfo* current_test_info() const { return current_test_info_; } @@ -799,11 +811,11 @@ class GTEST_API_ UnitTestImpl { // Gets the random number generator. internal::Random* random() { return &random_; } - // Shuffles all test cases, and the tests within each test case, + // Shuffles all test suites, and the tests within each test suite, // making sure that death tests are still run first. void ShuffleTests(); - // Restores the test cases and tests to their order before the first shuffle. + // Restores the test suites and tests to their order before the first shuffle. void UnshuffleTests(); // Returns the value of GTEST_FLAG(catch_exceptions) at the moment @@ -843,31 +855,31 @@ class GTEST_API_ UnitTestImpl { // before/after the tests are run. std::vector environments_; - // The vector of TestCases in their original order. It owns the + // The vector of TestSuites in their original order. It owns the // elements in the vector. - std::vector test_cases_; + std::vector test_suites_; - // Provides a level of indirection for the test case list to allow - // easy shuffling and restoring the test case order. The i-th - // element of this vector is the index of the i-th test case in the + // Provides a level of indirection for the test suite list to allow + // easy shuffling and restoring the test suite order. The i-th + // element of this vector is the index of the i-th test suite in the // shuffled order. - std::vector test_case_indices_; + std::vector test_suite_indices_; // ParameterizedTestRegistry object used to register value-parameterized // tests. - internal::ParameterizedTestCaseRegistry parameterized_test_registry_; + internal::ParameterizedTestSuiteRegistry parameterized_test_registry_; // Indicates whether RegisterParameterizedTests() has been called already. bool parameterized_tests_registered_; - // Index of the last death test case registered. Initially -1. - int last_death_test_case_; + // Index of the last death test suite registered. Initially -1. + int last_death_test_suite_; - // This points to the TestCase for the currently running test. It - // changes as Google Test goes through one test case after another. + // This points to the TestSuite for the currently running test. It + // changes as Google Test goes through one test suite after another. // When no test is running, this is set to NULL and Google Test // stores assertion results in ad_hoc_test_result_. Initially NULL. - TestCase* current_test_case_; + TestSuite* current_test_suite_; // This points to the TestInfo for the currently running test. It // changes as Google Test goes through one test after another. When @@ -1136,14 +1148,18 @@ class StreamingListener : public EmptyTestEventListener { StreamableToString(unit_test.elapsed_time()) + "ms"); } + // Note that "event=TestCaseStart" is a wire format and has to remain + // "case" for compatibilty void OnTestCaseStart(const TestCase& test_case) override { SendLn(std::string("event=TestCaseStart&name=") + test_case.name()); } + // Note that "event=TestCaseEnd" is a wire format and has to remain + // "case" for compatibilty void OnTestCaseEnd(const TestCase& test_case) override { - SendLn("event=TestCaseEnd&passed=" + FormatBool(test_case.Passed()) - + "&elapsed_time=" + StreamableToString(test_case.elapsed_time()) - + "ms"); + SendLn("event=TestCaseEnd&passed=" + FormatBool(test_case.Passed()) + + "&elapsed_time=" + StreamableToString(test_case.elapsed_time()) + + "ms"); } void OnTestStart(const TestInfo& test_info) override { diff --git a/googletest/src/gtest-typed-test.cc b/googletest/src/gtest-typed-test.cc index a305ed1a..8677caf7 100644 --- a/googletest/src/gtest-typed-test.cc +++ b/googletest/src/gtest-typed-test.cc @@ -57,7 +57,7 @@ static std::vector SplitIntoTestNames(const char* src) { // Verifies that registered_tests match the test names in // registered_tests_; returns registered_tests if successful, or // aborts the program otherwise. -const char* TypedTestCasePState::VerifyRegisteredTestNames( +const char* TypedTestSuitePState::VerifyRegisteredTestNames( const char* file, int line, const char* registered_tests) { typedef RegisteredTestsMap::const_iterator RegisteredTestIter; registered_ = true; @@ -89,7 +89,7 @@ const char* TypedTestCasePState::VerifyRegisteredTestNames( tests.insert(name); } else { errors << "No test named " << name - << " can be found in this test case.\n"; + << " can be found in this test suite.\n"; } } diff --git a/googletest/src/gtest.cc b/googletest/src/gtest.cc index 787c6484..23b6e5f5 100644 --- a/googletest/src/gtest.cc +++ b/googletest/src/gtest.cc @@ -147,14 +147,14 @@ using internal::Shuffle; // Constants. -// A test whose test case name or test name matches this filter is +// A test whose test suite name or test name matches this filter is // disabled and not run. static const char kDisableTestFilter[] = "DISABLED_*:*/DISABLED_*"; -// A test case whose name matches this filter is considered a death -// test case and will be run before test cases whose name doesn't +// A test suite whose name matches this filter is considered a death +// test suite and will be run before test suites whose name doesn't // match this filter. -static const char kDeathTestCaseFilter[] = "*DeathTest:*DeathTest/*"; +static const char kDeathTestSuiteFilter[] = "*DeathTest:*DeathTest/*"; // A test filter that matches everything. static const char kUniversalFilter[] = "*"; @@ -359,11 +359,11 @@ UInt32 Random::Generate(UInt32 range) { // Google Test before calling RUN_ALL_TESTS(). static bool GTestIsInitialized() { return GetArgvs().size() > 0; } -// Iterates over a vector of TestCases, keeping a running sum of the +// Iterates over a vector of TestSuites, keeping a running sum of the // results of calling a given int-returning method on each. // Returns the sum. -static int SumOverTestCaseList(const std::vector& case_list, - int (TestCase::*method)() const) { +static int SumOverTestSuiteList(const std::vector& case_list, + int (TestSuite::*method)() const) { int sum = 0; for (size_t i = 0; i < case_list.size(); i++) { sum += (case_list[i]->*method)(); @@ -371,20 +371,20 @@ static int SumOverTestCaseList(const std::vector& case_list, return sum; } -// Returns true iff the test case passed. -static bool TestCasePassed(const TestCase* test_case) { - return test_case->should_run() && test_case->Passed(); +// Returns true iff the test suite passed. +static bool TestSuitePassed(const TestSuite* test_suite) { + return test_suite->should_run() && test_suite->Passed(); } -// Returns true iff the test case failed. -static bool TestCaseFailed(const TestCase* test_case) { - return test_case->should_run() && test_case->Failed(); +// Returns true iff the test suite failed. +static bool TestSuiteFailed(const TestSuite* test_suite) { + return test_suite->should_run() && test_suite->Failed(); } -// Returns true iff test_case contains at least one test that should +// Returns true iff test_suite contains at least one test that should // run. -static bool ShouldRunTestCase(const TestCase* test_case) { - return test_case->should_run(); +static bool ShouldRunTestSuite(const TestSuite* test_suite) { + return test_suite->should_run(); } // AssertHelper constructor. @@ -524,11 +524,11 @@ bool UnitTestOptions::MatchesFilter( } } -// Returns true iff the user-specified filter matches the test case +// Returns true iff the user-specified filter matches the test suite // name and the test name. -bool UnitTestOptions::FilterMatchesTest(const std::string &test_case_name, - const std::string &test_name) { - const std::string& full_name = test_case_name + "." + test_name.c_str(); +bool UnitTestOptions::FilterMatchesTest(const std::string& test_suite_name, + const std::string& test_name) { + const std::string& full_name = test_suite_name + "." + test_name.c_str(); // Split --gtest_filter at '-', if there is one, to separate into // positive filter and negative filter portions @@ -750,66 +750,66 @@ void UnitTestImpl::SetTestPartResultReporterForCurrentThread( per_thread_test_part_result_reporter_.set(reporter); } -// Gets the number of successful test cases. -int UnitTestImpl::successful_test_case_count() const { - return CountIf(test_cases_, TestCasePassed); +// Gets the number of successful test suites. +int UnitTestImpl::successful_test_suite_count() const { + return CountIf(test_suites_, TestSuitePassed); } -// Gets the number of failed test cases. -int UnitTestImpl::failed_test_case_count() const { - return CountIf(test_cases_, TestCaseFailed); +// Gets the number of failed test suites. +int UnitTestImpl::failed_test_suite_count() const { + return CountIf(test_suites_, TestSuiteFailed); } -// Gets the number of all test cases. -int UnitTestImpl::total_test_case_count() const { - return static_cast(test_cases_.size()); +// Gets the number of all test suites. +int UnitTestImpl::total_test_suite_count() const { + return static_cast(test_suites_.size()); } -// Gets the number of all test cases that contain at least one test +// Gets the number of all test suites that contain at least one test // that should run. -int UnitTestImpl::test_case_to_run_count() const { - return CountIf(test_cases_, ShouldRunTestCase); +int UnitTestImpl::test_suite_to_run_count() const { + return CountIf(test_suites_, ShouldRunTestSuite); } // Gets the number of successful tests. int UnitTestImpl::successful_test_count() const { - return SumOverTestCaseList(test_cases_, &TestCase::successful_test_count); + return SumOverTestSuiteList(test_suites_, &TestSuite::successful_test_count); } // Gets the number of skipped tests. int UnitTestImpl::skipped_test_count() const { - return SumOverTestCaseList(test_cases_, &TestCase::skipped_test_count); + return SumOverTestSuiteList(test_suites_, &TestSuite::skipped_test_count); } // Gets the number of failed tests. int UnitTestImpl::failed_test_count() const { - return SumOverTestCaseList(test_cases_, &TestCase::failed_test_count); + return SumOverTestSuiteList(test_suites_, &TestSuite::failed_test_count); } // Gets the number of disabled tests that will be reported in the XML report. int UnitTestImpl::reportable_disabled_test_count() const { - return SumOverTestCaseList(test_cases_, - &TestCase::reportable_disabled_test_count); + return SumOverTestSuiteList(test_suites_, + &TestSuite::reportable_disabled_test_count); } // Gets the number of disabled tests. int UnitTestImpl::disabled_test_count() const { - return SumOverTestCaseList(test_cases_, &TestCase::disabled_test_count); + return SumOverTestSuiteList(test_suites_, &TestSuite::disabled_test_count); } // Gets the number of tests to be printed in the XML report. int UnitTestImpl::reportable_test_count() const { - return SumOverTestCaseList(test_cases_, &TestCase::reportable_test_count); + return SumOverTestSuiteList(test_suites_, &TestSuite::reportable_test_count); } // Gets the number of all tests. int UnitTestImpl::total_test_count() const { - return SumOverTestCaseList(test_cases_, &TestCase::total_test_count); + return SumOverTestSuiteList(test_suites_, &TestSuite::total_test_count); } // Gets the number of tests that should run. int UnitTestImpl::test_to_run_count() const { - return SumOverTestCaseList(test_cases_, &TestCase::test_to_run_count); + return SumOverTestSuiteList(test_suites_, &TestSuite::test_to_run_count); } // Returns the current OS stack trace as an std::string. @@ -2283,17 +2283,17 @@ void ReportFailureInUnknownLocation(TestPartResult::Type result_type, } // namespace internal -// Google Test requires all tests in the same test case to use the same test +// Google Test requires all tests in the same test suite to use the same test // fixture class. This function checks if the current test has the -// same fixture class as the first test in the current test case. If +// same fixture class as the first test in the current test suite. If // yes, it returns true; otherwise it generates a Google Test failure and // returns false. bool Test::HasSameFixtureClass() { internal::UnitTestImpl* const impl = internal::GetUnitTestImpl(); - const TestCase* const test_case = impl->current_test_case(); + const TestSuite* const test_suite = impl->current_test_suite(); - // Info about the first test in the current test case. - const TestInfo* const first_test_info = test_case->test_info_list()[0]; + // Info about the first test in the current test suite. + const TestInfo* const first_test_info = test_suite->test_info_list()[0]; const internal::TypeId first_fixture_id = first_test_info->fixture_class_id_; const char* const first_test_name = first_test_info->name(); @@ -2309,7 +2309,7 @@ bool Test::HasSameFixtureClass() { const bool this_is_TEST = this_fixture_id == internal::GetTestTypeId(); if (first_is_TEST || this_is_TEST) { - // Both TEST and TEST_F appear in same test case, which is incorrect. + // Both TEST and TEST_F appear in same test suite, which is incorrect. // Tell the user how to fix this. // Gets the name of the TEST and the name of the TEST_F. Note @@ -2321,9 +2321,9 @@ bool Test::HasSameFixtureClass() { first_is_TEST ? this_test_name : first_test_name; ADD_FAILURE() - << "All tests in the same test case must use the same test fixture\n" - << "class, so mixing TEST_F and TEST in the same test case is\n" - << "illegal. In test case " << this_test_info->test_case_name() + << "All tests in the same test suite must use the same test fixture\n" + << "class, so mixing TEST_F and TEST in the same test suite is\n" + << "illegal. In test suite " << this_test_info->test_suite_name() << ",\n" << "test " << TEST_F_name << " is defined using TEST_F but\n" << "test " << TEST_name << " is defined using TEST. You probably\n" @@ -2333,15 +2333,15 @@ bool Test::HasSameFixtureClass() { // Two fixture classes with the same name appear in two different // namespaces, which is not allowed. Tell the user how to fix this. ADD_FAILURE() - << "All tests in the same test case must use the same test fixture\n" - << "class. However, in test case " - << this_test_info->test_case_name() << ",\n" - << "you defined test " << first_test_name - << " and test " << this_test_name << "\n" + << "All tests in the same test suite must use the same test fixture\n" + << "class. However, in test suite " + << this_test_info->test_suite_name() << ",\n" + << "you defined test " << first_test_name << " and test " + << this_test_name << "\n" << "using two different test fixture classes. This can happen if\n" << "the two classes are from different namespaces or translation\n" << "units and have the same name. You should probably rename one\n" - << "of the classes to put the tests into different test cases."; + << "of the classes to put the tests into different test suites."; } return false; } @@ -2528,13 +2528,13 @@ bool Test::IsSkipped() { // Constructs a TestInfo object. It assumes ownership of the test factory // object. -TestInfo::TestInfo(const std::string& a_test_case_name, +TestInfo::TestInfo(const std::string& a_test_suite_name, const std::string& a_name, const char* a_type_param, const char* a_value_param, internal::CodeLocation a_code_location, internal::TypeId fixture_class_id, internal::TestFactoryBase* factory) - : test_case_name_(a_test_case_name), + : test_suite_name_(a_test_suite_name), name_(a_name), type_param_(a_type_param ? new std::string(a_type_param) : nullptr), value_param_(a_value_param ? new std::string(a_value_param) : nullptr), @@ -2556,7 +2556,7 @@ namespace internal { // // Arguments: // -// test_case_name: name of the test case +// test_suite_name: name of the test suite // name: name of the test // type_param: the name of the test's type parameter, or NULL if // this is not a typed or a type-parameterized test. @@ -2564,40 +2564,35 @@ namespace internal { // or NULL if this is not a value-parameterized test. // code_location: code location where the test is defined // fixture_class_id: ID of the test fixture class -// set_up_tc: pointer to the function that sets up the test case -// tear_down_tc: pointer to the function that tears down the test case +// set_up_tc: pointer to the function that sets up the test suite +// tear_down_tc: pointer to the function that tears down the test suite // factory: pointer to the factory that creates a test object. // The newly created TestInfo instance will assume // ownership of the factory object. TestInfo* MakeAndRegisterTestInfo( - const char* test_case_name, - const char* name, - const char* type_param, - const char* value_param, - CodeLocation code_location, - TypeId fixture_class_id, - SetUpTestCaseFunc set_up_tc, - TearDownTestCaseFunc tear_down_tc, - TestFactoryBase* factory) { + const char* test_suite_name, const char* name, const char* type_param, + const char* value_param, CodeLocation code_location, + TypeId fixture_class_id, SetUpTestSuiteFunc set_up_tc, + TearDownTestSuiteFunc tear_down_tc, TestFactoryBase* factory) { TestInfo* const test_info = - new TestInfo(test_case_name, name, type_param, value_param, + new TestInfo(test_suite_name, name, type_param, value_param, code_location, fixture_class_id, factory); GetUnitTestImpl()->AddTestInfo(set_up_tc, tear_down_tc, test_info); return test_info; } -void ReportInvalidTestCaseType(const char* test_case_name, - CodeLocation code_location) { +void ReportInvalidTestSuiteType(const char* test_suite_name, + CodeLocation code_location) { Message errors; errors - << "Attempted redefinition of test case " << test_case_name << ".\n" - << "All tests in the same test case must use the same test fixture\n" - << "class. However, in test case " << test_case_name << ", you tried\n" + << "Attempted redefinition of test suite " << test_suite_name << ".\n" + << "All tests in the same test suite must use the same test fixture\n" + << "class. However, in test suite " << test_suite_name << ", you tried\n" << "to define a test using a fixture class different from the one\n" << "used earlier. This can happen if the two fixture classes are\n" << "from different namespaces and have the same name. You should\n" << "probably rename one of the classes to put the tests into different\n" - << "test cases."; + << "test suites."; GTEST_LOG_(ERROR) << FormatFileLocation(code_location.file.c_str(), code_location.line) @@ -2610,7 +2605,7 @@ namespace { // A predicate that checks the test name of a TestInfo against a known // value. // -// This is used for implementation of the TestCase class only. We put +// This is used for implementation of the TestSuite class only. We put // it in the anonymous namespace to prevent polluting the outer // namespace. // @@ -2637,7 +2632,7 @@ class TestNameIs { namespace internal { // This method expands all parameterized tests registered with macros TEST_P -// and INSTANTIATE_TEST_CASE_P into regular tests and registers those. +// and INSTANTIATE_TEST_SUITE_P into regular tests and registers those. // This will be done just once during the program runtime. void UnitTestImpl::RegisterParameterizedTests() { if (!parameterized_tests_registered_) { @@ -2695,60 +2690,60 @@ void TestInfo::Run() { impl->set_current_test_info(nullptr); } -// class TestCase +// class TestSuite -// Gets the number of successful tests in this test case. -int TestCase::successful_test_count() const { +// Gets the number of successful tests in this test suite. +int TestSuite::successful_test_count() const { return CountIf(test_info_list_, TestPassed); } -// Gets the number of successful tests in this test case. -int TestCase::skipped_test_count() const { +// Gets the number of successful tests in this test suite. +int TestSuite::skipped_test_count() const { return CountIf(test_info_list_, TestSkipped); } -// Gets the number of failed tests in this test case. -int TestCase::failed_test_count() const { +// Gets the number of failed tests in this test suite. +int TestSuite::failed_test_count() const { return CountIf(test_info_list_, TestFailed); } // Gets the number of disabled tests that will be reported in the XML report. -int TestCase::reportable_disabled_test_count() const { +int TestSuite::reportable_disabled_test_count() const { return CountIf(test_info_list_, TestReportableDisabled); } -// Gets the number of disabled tests in this test case. -int TestCase::disabled_test_count() const { +// Gets the number of disabled tests in this test suite. +int TestSuite::disabled_test_count() const { return CountIf(test_info_list_, TestDisabled); } // Gets the number of tests to be printed in the XML report. -int TestCase::reportable_test_count() const { +int TestSuite::reportable_test_count() const { return CountIf(test_info_list_, TestReportable); } -// Get the number of tests in this test case that should run. -int TestCase::test_to_run_count() const { +// Get the number of tests in this test suite that should run. +int TestSuite::test_to_run_count() const { return CountIf(test_info_list_, ShouldRunTest); } // Gets the number of all tests. -int TestCase::total_test_count() const { +int TestSuite::total_test_count() const { return static_cast(test_info_list_.size()); } -// Creates a TestCase with the given name. +// Creates a TestSuite with the given name. // // Arguments: // -// name: name of the test case -// a_type_param: the name of the test case's type parameter, or NULL if -// this is not a typed or a type-parameterized test case. -// set_up_tc: pointer to the function that sets up the test case -// tear_down_tc: pointer to the function that tears down the test case -TestCase::TestCase(const char* a_name, const char* a_type_param, - Test::SetUpTestCaseFunc set_up_tc, - Test::TearDownTestCaseFunc tear_down_tc) +// name: name of the test suite +// a_type_param: the name of the test suite's type parameter, or NULL if +// this is not a typed or a type-parameterized test suite. +// set_up_tc: pointer to the function that sets up the test suite +// tear_down_tc: pointer to the function that tears down the test suite +TestSuite::TestSuite(const char* a_name, const char* a_type_param, + internal::SetUpTestSuiteFunc set_up_tc, + internal::TearDownTestSuiteFunc tear_down_tc) : name_(a_name), type_param_(a_type_param ? new std::string(a_type_param) : nullptr), set_up_tc_(set_up_tc), @@ -2756,46 +2751,52 @@ TestCase::TestCase(const char* a_name, const char* a_type_param, should_run_(false), elapsed_time_(0) {} -// Destructor of TestCase. -TestCase::~TestCase() { +// Destructor of TestSuite. +TestSuite::~TestSuite() { // Deletes every Test in the collection. ForEach(test_info_list_, internal::Delete); } // Returns the i-th test among all the tests. i can range from 0 to // total_test_count() - 1. If i is not in that range, returns NULL. -const TestInfo* TestCase::GetTestInfo(int i) const { +const TestInfo* TestSuite::GetTestInfo(int i) const { const int index = GetElementOr(test_indices_, i, -1); return index < 0 ? nullptr : test_info_list_[index]; } // Returns the i-th test among all the tests. i can range from 0 to // total_test_count() - 1. If i is not in that range, returns NULL. -TestInfo* TestCase::GetMutableTestInfo(int i) { +TestInfo* TestSuite::GetMutableTestInfo(int i) { const int index = GetElementOr(test_indices_, i, -1); return index < 0 ? nullptr : test_info_list_[index]; } -// Adds a test to this test case. Will delete the test upon -// destruction of the TestCase object. -void TestCase::AddTestInfo(TestInfo * test_info) { +// Adds a test to this test suite. Will delete the test upon +// destruction of the TestSuite object. +void TestSuite::AddTestInfo(TestInfo* test_info) { test_info_list_.push_back(test_info); test_indices_.push_back(static_cast(test_indices_.size())); } -// Runs every test in this TestCase. -void TestCase::Run() { +// Runs every test in this TestSuite. +void TestSuite::Run() { if (!should_run_) return; internal::UnitTestImpl* const impl = internal::GetUnitTestImpl(); - impl->set_current_test_case(this); + impl->set_current_test_suite(this); TestEventListener* repeater = UnitTest::GetInstance()->listeners().repeater(); + // Call both legacy and the new API + repeater->OnTestSuiteStart(*this); +// Legacy API is deprecated but still available +#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI repeater->OnTestCaseStart(*this); +#endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI + impl->os_stack_trace_getter()->UponLeavingGTest(); internal::HandleExceptionsInMethodIfSupported( - this, &TestCase::RunSetUpTestCase, "SetUpTestCase()"); + this, &TestSuite::RunSetUpTestSuite, "SetUpTestSuite()"); const internal::TimeInMillis start = internal::GetTimeInMillis(); for (int i = 0; i < total_test_count(); i++) { @@ -2805,25 +2806,31 @@ void TestCase::Run() { impl->os_stack_trace_getter()->UponLeavingGTest(); internal::HandleExceptionsInMethodIfSupported( - this, &TestCase::RunTearDownTestCase, "TearDownTestCase()"); + this, &TestSuite::RunTearDownTestSuite, "TearDownTestSuite()"); + // Call both legacy and the new API + repeater->OnTestSuiteEnd(*this); +// Legacy API is deprecated but still available +#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI repeater->OnTestCaseEnd(*this); - impl->set_current_test_case(nullptr); +#endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI + + impl->set_current_test_suite(nullptr); } -// Clears the results of all tests in this test case. -void TestCase::ClearResult() { +// Clears the results of all tests in this test suite. +void TestSuite::ClearResult() { ad_hoc_test_result_.Clear(); ForEach(test_info_list_, TestInfo::ClearTestResult); } -// Shuffles the tests in this test case. -void TestCase::ShuffleTests(internal::Random* random) { +// Shuffles the tests in this test suite. +void TestSuite::ShuffleTests(internal::Random* random) { Shuffle(random, &test_indices_); } // Restores the test order to before the first shuffle. -void TestCase::UnshuffleTests() { +void TestSuite::UnshuffleTests() { for (size_t i = 0; i < test_indices_.size(); i++) { test_indices_[i] = static_cast(i); } @@ -2846,9 +2853,9 @@ static std::string FormatTestCount(int test_count) { return FormatCountableNoun(test_count, "test", "tests"); } -// Formats the count of test cases. -static std::string FormatTestCaseCount(int test_case_count) { - return FormatCountableNoun(test_case_count, "test case", "test cases"); +// Formats the count of test suites. +static std::string FormatTestSuiteCount(int test_suite_count) { + return FormatCountableNoun(test_suite_count, "test suite", "test suites"); } // Converts a TestPartResult::Type enum to human-friendly string @@ -3082,8 +3089,8 @@ static void PrintFullTestCommentIfPresent(const TestInfo& test_info) { class PrettyUnitTestResultPrinter : public TestEventListener { public: PrettyUnitTestResultPrinter() {} - static void PrintTestName(const char * test_case, const char * test) { - printf("%s.%s", test_case, test); + static void PrintTestName(const char* test_suite, const char* test) { + printf("%s.%s", test_suite, test); } // The following methods override what's in the TestEventListener class. @@ -3091,11 +3098,11 @@ class PrettyUnitTestResultPrinter : public TestEventListener { void OnTestIterationStart(const UnitTest& unit_test, int iteration) override; void OnEnvironmentsSetUpStart(const UnitTest& unit_test) override; void OnEnvironmentsSetUpEnd(const UnitTest& /*unit_test*/) override {} - void OnTestCaseStart(const TestCase& test_case) override; + void OnTestCaseStart(const TestSuite& test_suite) override; void OnTestStart(const TestInfo& test_info) override; void OnTestPartResult(const TestPartResult& result) override; void OnTestEnd(const TestInfo& test_info) override; - void OnTestCaseEnd(const TestCase& test_case) override; + void OnTestCaseEnd(const TestSuite& test_suite) override; void OnEnvironmentsTearDownStart(const UnitTest& unit_test) override; void OnEnvironmentsTearDownEnd(const UnitTest& /*unit_test*/) override {} void OnTestIterationEnd(const UnitTest& unit_test, int iteration) override; @@ -3138,7 +3145,7 @@ void PrettyUnitTestResultPrinter::OnTestIterationStart( ColoredPrintf(COLOR_GREEN, "[==========] "); printf("Running %s from %s.\n", FormatTestCount(unit_test.test_to_run_count()).c_str(), - FormatTestCaseCount(unit_test.test_case_to_run_count()).c_str()); + FormatTestSuiteCount(unit_test.test_suite_to_run_count()).c_str()); fflush(stdout); } @@ -3149,22 +3156,22 @@ void PrettyUnitTestResultPrinter::OnEnvironmentsSetUpStart( fflush(stdout); } -void PrettyUnitTestResultPrinter::OnTestCaseStart(const TestCase& test_case) { +void PrettyUnitTestResultPrinter::OnTestCaseStart(const TestSuite& test_suite) { const std::string counts = - FormatCountableNoun(test_case.test_to_run_count(), "test", "tests"); + FormatCountableNoun(test_suite.test_to_run_count(), "test", "tests"); ColoredPrintf(COLOR_GREEN, "[----------] "); - printf("%s from %s", counts.c_str(), test_case.name()); - if (test_case.type_param() == nullptr) { + printf("%s from %s", counts.c_str(), test_suite.name()); + if (test_suite.type_param() == nullptr) { printf("\n"); } else { - printf(", where %s = %s\n", kTypeParamLabel, test_case.type_param()); + printf(", where %s = %s\n", kTypeParamLabel, test_suite.type_param()); } fflush(stdout); } void PrettyUnitTestResultPrinter::OnTestStart(const TestInfo& test_info) { ColoredPrintf(COLOR_GREEN, "[ RUN ] "); - PrintTestName(test_info.test_case_name(), test_info.name()); + PrintTestName(test_info.test_suite_name(), test_info.name()); printf("\n"); fflush(stdout); } @@ -3194,7 +3201,7 @@ void PrettyUnitTestResultPrinter::OnTestEnd(const TestInfo& test_info) { } else { ColoredPrintf(COLOR_RED, "[ FAILED ] "); } - PrintTestName(test_info.test_case_name(), test_info.name()); + PrintTestName(test_info.test_suite_name(), test_info.name()); if (test_info.result()->Failed()) PrintFullTestCommentIfPresent(test_info); @@ -3207,15 +3214,14 @@ void PrettyUnitTestResultPrinter::OnTestEnd(const TestInfo& test_info) { fflush(stdout); } -void PrettyUnitTestResultPrinter::OnTestCaseEnd(const TestCase& test_case) { +void PrettyUnitTestResultPrinter::OnTestCaseEnd(const TestSuite& test_suite) { if (!GTEST_FLAG(print_time)) return; const std::string counts = - FormatCountableNoun(test_case.test_to_run_count(), "test", "tests"); + FormatCountableNoun(test_suite.test_to_run_count(), "test", "tests"); ColoredPrintf(COLOR_GREEN, "[----------] "); - printf("%s from %s (%s ms total)\n\n", - counts.c_str(), test_case.name(), - internal::StreamableToString(test_case.elapsed_time()).c_str()); + printf("%s from %s (%s ms total)\n\n", counts.c_str(), test_suite.name(), + internal::StreamableToString(test_suite.elapsed_time()).c_str()); fflush(stdout); } @@ -3233,18 +3239,18 @@ void PrettyUnitTestResultPrinter::PrintFailedTests(const UnitTest& unit_test) { return; } - for (int i = 0; i < unit_test.total_test_case_count(); ++i) { - const TestCase& test_case = *unit_test.GetTestCase(i); - if (!test_case.should_run() || (test_case.failed_test_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() || (test_suite.failed_test_count() == 0)) { continue; } - for (int j = 0; j < test_case.total_test_count(); ++j) { - const TestInfo& test_info = *test_case.GetTestInfo(j); + for (int j = 0; j < test_suite.total_test_count(); ++j) { + const TestInfo& test_info = *test_suite.GetTestInfo(j); if (!test_info.should_run() || !test_info.result()->Failed()) { continue; } ColoredPrintf(COLOR_RED, "[ FAILED ] "); - printf("%s.%s", test_case.name(), test_info.name()); + printf("%s.%s", test_suite.name(), test_info.name()); PrintFullTestCommentIfPresent(test_info); printf("\n"); } @@ -3258,18 +3264,18 @@ void PrettyUnitTestResultPrinter::PrintSkippedTests(const UnitTest& unit_test) { return; } - for (int i = 0; i < unit_test.total_test_case_count(); ++i) { - const TestCase& test_case = *unit_test.GetTestCase(i); - if (!test_case.should_run() || (test_case.skipped_test_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() || (test_suite.skipped_test_count() == 0)) { continue; } - for (int j = 0; j < test_case.total_test_count(); ++j) { - const TestInfo& test_info = *test_case.GetTestInfo(j); + for (int j = 0; j < test_suite.total_test_count(); ++j) { + const TestInfo& test_info = *test_suite.GetTestInfo(j); if (!test_info.should_run() || !test_info.result()->Skipped()) { continue; } ColoredPrintf(COLOR_GREEN, "[ SKIPPED ] "); - printf("%s.%s", test_case.name(), test_info.name()); + printf("%s.%s", test_suite.name(), test_info.name()); printf("\n"); } } @@ -3280,7 +3286,7 @@ void PrettyUnitTestResultPrinter::OnTestIterationEnd(const UnitTest& unit_test, ColoredPrintf(COLOR_GREEN, "[==========] "); printf("%s from %s ran.", FormatTestCount(unit_test.test_to_run_count()).c_str(), - FormatTestCaseCount(unit_test.test_case_to_run_count()).c_str()); + FormatTestSuiteCount(unit_test.test_suite_to_run_count()).c_str()); if (GTEST_FLAG(print_time)) { printf(" (%s ms total)", internal::StreamableToString(unit_test.elapsed_time()).c_str()); @@ -3341,11 +3347,19 @@ class TestEventRepeater : public TestEventListener { void OnTestIterationStart(const UnitTest& unit_test, int iteration) override; void OnEnvironmentsSetUpStart(const UnitTest& unit_test) override; void OnEnvironmentsSetUpEnd(const UnitTest& unit_test) override; - void OnTestCaseStart(const TestCase& test_case) override; +// Legacy API is deprecated but still available +#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI + void OnTestCaseStart(const TestSuite& parameter) override; +#endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI + void OnTestSuiteStart(const TestSuite& parameter) override; void OnTestStart(const TestInfo& test_info) override; void OnTestPartResult(const TestPartResult& result) override; void OnTestEnd(const TestInfo& test_info) override; - void OnTestCaseEnd(const TestCase& test_case) override; +// Legacy API is deprecated but still available +#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI + void OnTestCaseEnd(const TestSuite& parameter) override; +#endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI + void OnTestSuiteEnd(const TestSuite& parameter) override; void OnEnvironmentsTearDownStart(const UnitTest& unit_test) override; void OnEnvironmentsTearDownEnd(const UnitTest& unit_test) override; void OnTestIterationEnd(const UnitTest& unit_test, int iteration) override; @@ -3403,14 +3417,22 @@ void TestEventRepeater::Name(const Type& parameter) { \ GTEST_REPEATER_METHOD_(OnTestProgramStart, UnitTest) GTEST_REPEATER_METHOD_(OnEnvironmentsSetUpStart, UnitTest) -GTEST_REPEATER_METHOD_(OnTestCaseStart, TestCase) +// Legacy API is deprecated but still available +#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_ +GTEST_REPEATER_METHOD_(OnTestCaseStart, TestSuite) +#endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_ +GTEST_REPEATER_METHOD_(OnTestSuiteStart, TestSuite) GTEST_REPEATER_METHOD_(OnTestStart, TestInfo) GTEST_REPEATER_METHOD_(OnTestPartResult, TestPartResult) GTEST_REPEATER_METHOD_(OnEnvironmentsTearDownStart, UnitTest) GTEST_REVERSE_REPEATER_METHOD_(OnEnvironmentsSetUpEnd, UnitTest) GTEST_REVERSE_REPEATER_METHOD_(OnEnvironmentsTearDownEnd, UnitTest) GTEST_REVERSE_REPEATER_METHOD_(OnTestEnd, TestInfo) -GTEST_REVERSE_REPEATER_METHOD_(OnTestCaseEnd, TestCase) +// Legacy API is deprecated but still available +#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_ +GTEST_REVERSE_REPEATER_METHOD_(OnTestCaseEnd, TestSuite) +#endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_ +GTEST_REVERSE_REPEATER_METHOD_(OnTestSuiteEnd, TestSuite) GTEST_REVERSE_REPEATER_METHOD_(OnTestProgramEnd, UnitTest) #undef GTEST_REPEATER_METHOD_ @@ -3442,11 +3464,11 @@ class XmlUnitTestResultPrinter : public EmptyTestEventListener { explicit XmlUnitTestResultPrinter(const char* output_file); void OnTestIterationEnd(const UnitTest& unit_test, int iteration) override; - void ListTestsMatchingFilter(const std::vector& test_cases); + void ListTestsMatchingFilter(const std::vector& test_suites); // Prints an XML summary of all unit tests. static void PrintXmlTestsList(std::ostream* stream, - const std::vector& test_cases); + const std::vector& test_suites); private: // Is c a whitespace character that is normalized to a space character @@ -3491,12 +3513,12 @@ class XmlUnitTestResultPrinter : public EmptyTestEventListener { // Streams an XML representation of a TestInfo object. static void OutputXmlTestInfo(::std::ostream* stream, - const char* test_case_name, + const char* test_suite_name, const TestInfo& test_info); - // Prints an XML representation of a TestCase object - static void PrintXmlTestCase(::std::ostream* stream, - const TestCase& test_case); + // Prints an XML representation of a TestSuite object + static void PrintXmlTestSuite(::std::ostream* stream, + const TestSuite& test_suite); // Prints an XML summary of unit_test to output stream out. static void PrintXmlUnitTest(::std::ostream* stream, @@ -3538,10 +3560,10 @@ void XmlUnitTestResultPrinter::OnTestIterationEnd(const UnitTest& unit_test, } void XmlUnitTestResultPrinter::ListTestsMatchingFilter( - const std::vector& test_cases) { + const std::vector& test_suites) { FILE* xmlout = OpenFileForWriting(output_file_); std::stringstream stream; - PrintXmlTestsList(&stream, test_cases); + PrintXmlTestsList(&stream, test_suites); fprintf(xmlout, "%s", StringStreamToString(&stream).c_str()); fclose(xmlout); } @@ -3620,7 +3642,7 @@ std::string XmlUnitTestResultPrinter::RemoveInvalidXmlCharacters( // This is how Google Test concepts map to the DTD: // // <-- corresponds to a UnitTest object -// <-- corresponds to a TestCase object +// <-- corresponds to a TestSuite object // <-- corresponds to a TestInfo object // ... // ... @@ -3705,39 +3727,40 @@ void XmlUnitTestResultPrinter::OutputXmlAttribute( // Prints an XML representation of a TestInfo object. void XmlUnitTestResultPrinter::OutputXmlTestInfo(::std::ostream* stream, - const char* test_case_name, + const char* test_suite_name, const TestInfo& test_info) { const TestResult& result = *test_info.result(); - const std::string kTestcase = "testcase"; + const std::string kTestsuite = "testcase"; if (test_info.is_in_another_shard()) { return; } *stream << " \n"; return; } - OutputXmlAttribute(stream, kTestcase, "status", - result.Skipped() ? "skipped" : - test_info.should_run() ? "run" : "notrun"); - OutputXmlAttribute(stream, kTestcase, "time", + OutputXmlAttribute( + stream, kTestsuite, "status", + result.Skipped() ? "skipped" : test_info.should_run() ? "run" : "notrun"); + OutputXmlAttribute(stream, kTestsuite, "time", FormatTimeInMillisAsSeconds(result.elapsed_time())); - OutputXmlAttribute(stream, kTestcase, "classname", test_case_name); + OutputXmlAttribute(stream, kTestsuite, "classname", test_suite_name); int failures = 0; for (int i = 0; i < result.total_part_count(); ++i) { @@ -3770,29 +3793,29 @@ void XmlUnitTestResultPrinter::OutputXmlTestInfo(::std::ostream* stream, } } -// Prints an XML representation of a TestCase object -void XmlUnitTestResultPrinter::PrintXmlTestCase(std::ostream* stream, - const TestCase& test_case) { +// Prints an XML representation of a TestSuite object +void XmlUnitTestResultPrinter::PrintXmlTestSuite(std::ostream* stream, + const TestSuite& test_suite) { const std::string kTestsuite = "testsuite"; *stream << " <" << kTestsuite; - OutputXmlAttribute(stream, kTestsuite, "name", test_case.name()); + OutputXmlAttribute(stream, kTestsuite, "name", test_suite.name()); OutputXmlAttribute(stream, kTestsuite, "tests", - StreamableToString(test_case.reportable_test_count())); + StreamableToString(test_suite.reportable_test_count())); if (!GTEST_FLAG(list_tests)) { OutputXmlAttribute(stream, kTestsuite, "failures", - StreamableToString(test_case.failed_test_count())); + StreamableToString(test_suite.failed_test_count())); OutputXmlAttribute( stream, kTestsuite, "disabled", - StreamableToString(test_case.reportable_disabled_test_count())); + StreamableToString(test_suite.reportable_disabled_test_count())); OutputXmlAttribute(stream, kTestsuite, "errors", "0"); OutputXmlAttribute(stream, kTestsuite, "time", - FormatTimeInMillisAsSeconds(test_case.elapsed_time())); - *stream << TestPropertiesAsXmlAttributes(test_case.ad_hoc_test_result()); + FormatTimeInMillisAsSeconds(test_suite.elapsed_time())); + *stream << TestPropertiesAsXmlAttributes(test_suite.ad_hoc_test_result()); } *stream << ">\n"; - for (int i = 0; i < test_case.total_test_count(); ++i) { - if (test_case.GetTestInfo(i)->is_reportable()) - OutputXmlTestInfo(stream, test_case.name(), *test_case.GetTestInfo(i)); + for (int i = 0; i < test_suite.total_test_count(); ++i) { + if (test_suite.GetTestInfo(i)->is_reportable()) + OutputXmlTestInfo(stream, test_suite.name(), *test_suite.GetTestInfo(i)); } *stream << " \n"; } @@ -3828,31 +3851,31 @@ void XmlUnitTestResultPrinter::PrintXmlUnitTest(std::ostream* stream, OutputXmlAttribute(stream, kTestsuites, "name", "AllTests"); *stream << ">\n"; - for (int i = 0; i < unit_test.total_test_case_count(); ++i) { - if (unit_test.GetTestCase(i)->reportable_test_count() > 0) - PrintXmlTestCase(stream, *unit_test.GetTestCase(i)); + for (int i = 0; i < unit_test.total_test_suite_count(); ++i) { + if (unit_test.GetTestSuite(i)->reportable_test_count() > 0) + PrintXmlTestSuite(stream, *unit_test.GetTestSuite(i)); } *stream << "\n"; } void XmlUnitTestResultPrinter::PrintXmlTestsList( - std::ostream* stream, const std::vector& test_cases) { + std::ostream* stream, const std::vector& test_suites) { const std::string kTestsuites = "testsuites"; *stream << "\n"; *stream << "<" << kTestsuites; int total_tests = 0; - for (size_t i = 0; i < test_cases.size(); ++i) { - total_tests += test_cases[i]->total_test_count(); + for (auto test_suite : test_suites) { + total_tests += test_suite->total_test_count(); } OutputXmlAttribute(stream, kTestsuites, "tests", StreamableToString(total_tests)); OutputXmlAttribute(stream, kTestsuites, "name", "AllTests"); *stream << ">\n"; - for (size_t i = 0; i < test_cases.size(); ++i) { - PrintXmlTestCase(stream, *test_cases[i]); + for (auto test_suite : test_suites) { + PrintXmlTestSuite(stream, *test_suite); } *stream << "\n"; } @@ -3901,7 +3924,7 @@ class JsonUnitTestResultPrinter : public EmptyTestEventListener { // Prints an JSON summary of all unit tests. static void PrintJsonTestList(::std::ostream* stream, - const std::vector& test_cases); + const std::vector& test_suites); private: // Returns an JSON-escaped copy of the input string str. @@ -3924,12 +3947,12 @@ class JsonUnitTestResultPrinter : public EmptyTestEventListener { // Streams a JSON representation of a TestInfo object. static void OutputJsonTestInfo(::std::ostream* stream, - const char* test_case_name, + const char* test_suite_name, const TestInfo& test_info); - // Prints a JSON representation of a TestCase object - static void PrintJsonTestCase(::std::ostream* stream, - const TestCase& test_case); + // Prints a JSON representation of a TestSuite object + static void PrintJsonTestSuite(::std::ostream* stream, + const TestSuite& test_suite); // Prints a JSON summary of unit_test to output stream out. static void PrintJsonUnitTest(::std::ostream* stream, @@ -4074,36 +4097,38 @@ void JsonUnitTestResultPrinter::OutputJsonKey( // Prints a JSON representation of a TestInfo object. void JsonUnitTestResultPrinter::OutputJsonTestInfo(::std::ostream* stream, - const char* test_case_name, + const char* test_suite_name, const TestInfo& test_info) { const TestResult& result = *test_info.result(); - const std::string kTestcase = "testcase"; + const std::string kTestsuite = "testcase"; const std::string kIndent = Indent(10); *stream << Indent(8) << "{\n"; - OutputJsonKey(stream, kTestcase, "name", test_info.name(), kIndent); + OutputJsonKey(stream, kTestsuite, "name", test_info.name(), kIndent); if (test_info.value_param() != nullptr) { - OutputJsonKey(stream, kTestcase, "value_param", - test_info.value_param(), kIndent); + OutputJsonKey(stream, kTestsuite, "value_param", test_info.value_param(), + kIndent); } if (test_info.type_param() != nullptr) { - OutputJsonKey(stream, kTestcase, "type_param", test_info.type_param(), + OutputJsonKey(stream, kTestsuite, "type_param", test_info.type_param(), kIndent); } if (GTEST_FLAG(list_tests)) { - OutputJsonKey(stream, kTestcase, "file", test_info.file(), kIndent); - OutputJsonKey(stream, kTestcase, "line", test_info.line(), kIndent, false); + OutputJsonKey(stream, kTestsuite, "file", test_info.file(), kIndent); + OutputJsonKey(stream, kTestsuite, "line", test_info.line(), kIndent, false); *stream << "\n" << Indent(8) << "}"; return; } - OutputJsonKey(stream, kTestcase, "status", - result.Skipped() ? "SKIPPED" : - test_info.should_run() ? "RUN" : "NOTRUN", kIndent); - OutputJsonKey(stream, kTestcase, "time", + OutputJsonKey( + stream, kTestsuite, "status", + result.Skipped() ? "SKIPPED" : test_info.should_run() ? "RUN" : "NOTRUN", + kIndent); + OutputJsonKey(stream, kTestsuite, "time", FormatTimeInMillisAsDuration(result.elapsed_time()), kIndent); - OutputJsonKey(stream, kTestcase, "classname", test_case_name, kIndent, false); + OutputJsonKey(stream, kTestsuite, "classname", test_suite_name, kIndent, + false); *stream << TestPropertiesAsJson(result, kIndent); int failures = 0; @@ -4130,40 +4155,40 @@ void JsonUnitTestResultPrinter::OutputJsonTestInfo(::std::ostream* stream, *stream << "\n" << Indent(8) << "}"; } -// Prints an JSON representation of a TestCase object -void JsonUnitTestResultPrinter::PrintJsonTestCase(std::ostream* stream, - const TestCase& test_case) { +// Prints an JSON representation of a TestSuite object +void JsonUnitTestResultPrinter::PrintJsonTestSuite( + std::ostream* stream, const TestSuite& test_suite) { const std::string kTestsuite = "testsuite"; const std::string kIndent = Indent(6); *stream << Indent(4) << "{\n"; - OutputJsonKey(stream, kTestsuite, "name", test_case.name(), kIndent); - OutputJsonKey(stream, kTestsuite, "tests", test_case.reportable_test_count(), + OutputJsonKey(stream, kTestsuite, "name", test_suite.name(), kIndent); + OutputJsonKey(stream, kTestsuite, "tests", test_suite.reportable_test_count(), kIndent); if (!GTEST_FLAG(list_tests)) { - OutputJsonKey(stream, kTestsuite, "failures", test_case.failed_test_count(), - kIndent); + OutputJsonKey(stream, kTestsuite, "failures", + test_suite.failed_test_count(), kIndent); OutputJsonKey(stream, kTestsuite, "disabled", - test_case.reportable_disabled_test_count(), kIndent); + test_suite.reportable_disabled_test_count(), kIndent); OutputJsonKey(stream, kTestsuite, "errors", 0, kIndent); OutputJsonKey(stream, kTestsuite, "time", - FormatTimeInMillisAsDuration(test_case.elapsed_time()), + FormatTimeInMillisAsDuration(test_suite.elapsed_time()), kIndent, false); - *stream << TestPropertiesAsJson(test_case.ad_hoc_test_result(), kIndent) + *stream << TestPropertiesAsJson(test_suite.ad_hoc_test_result(), kIndent) << ",\n"; } *stream << kIndent << "\"" << kTestsuite << "\": [\n"; bool comma = false; - for (int i = 0; i < test_case.total_test_count(); ++i) { - if (test_case.GetTestInfo(i)->is_reportable()) { + for (int i = 0; i < test_suite.total_test_count(); ++i) { + if (test_suite.GetTestInfo(i)->is_reportable()) { if (comma) { *stream << ",\n"; } else { comma = true; } - OutputJsonTestInfo(stream, test_case.name(), *test_case.GetTestInfo(i)); + OutputJsonTestInfo(stream, test_suite.name(), *test_suite.GetTestInfo(i)); } } *stream << "\n" << kIndent << "]\n" << Indent(4) << "}"; @@ -4201,14 +4226,14 @@ void JsonUnitTestResultPrinter::PrintJsonUnitTest(std::ostream* stream, *stream << kIndent << "\"" << kTestsuites << "\": [\n"; bool comma = false; - for (int i = 0; i < unit_test.total_test_case_count(); ++i) { - if (unit_test.GetTestCase(i)->reportable_test_count() > 0) { + for (int i = 0; i < unit_test.total_test_suite_count(); ++i) { + if (unit_test.GetTestSuite(i)->reportable_test_count() > 0) { if (comma) { *stream << ",\n"; } else { comma = true; } - PrintJsonTestCase(stream, *unit_test.GetTestCase(i)); + PrintJsonTestSuite(stream, *unit_test.GetTestSuite(i)); } } @@ -4216,24 +4241,24 @@ void JsonUnitTestResultPrinter::PrintJsonUnitTest(std::ostream* stream, } void JsonUnitTestResultPrinter::PrintJsonTestList( - std::ostream* stream, const std::vector& test_cases) { + std::ostream* stream, const std::vector& test_suites) { const std::string kTestsuites = "testsuites"; const std::string kIndent = Indent(2); *stream << "{\n"; int total_tests = 0; - for (size_t i = 0; i < test_cases.size(); ++i) { - total_tests += test_cases[i]->total_test_count(); + for (auto test_suite : test_suites) { + total_tests += test_suite->total_test_count(); } OutputJsonKey(stream, kTestsuites, "tests", total_tests, kIndent); OutputJsonKey(stream, kTestsuites, "name", "AllTests", kIndent); *stream << kIndent << "\"" << kTestsuites << "\": [\n"; - for (size_t i = 0; i < test_cases.size(); ++i) { + for (size_t i = 0; i < test_suites.size(); ++i) { if (i != 0) { *stream << ",\n"; } - PrintJsonTestCase(stream, *test_cases[i]); + PrintJsonTestSuite(stream, *test_suites[i]); } *stream << "\n" @@ -4524,26 +4549,42 @@ UnitTest* UnitTest::GetInstance() { #endif // defined(__BORLANDC__) } -// Gets the number of successful test cases. -int UnitTest::successful_test_case_count() const { - return impl()->successful_test_case_count(); +// Gets the number of successful test suites. +int UnitTest::successful_test_suite_count() const { + return impl()->successful_test_suite_count(); } -// Gets the number of failed test cases. -int UnitTest::failed_test_case_count() const { - return impl()->failed_test_case_count(); +// Gets the number of failed test suites. +int UnitTest::failed_test_suite_count() const { + return impl()->failed_test_suite_count(); } -// Gets the number of all test cases. -int UnitTest::total_test_case_count() const { - return impl()->total_test_case_count(); +// Gets the number of all test suites. +int UnitTest::total_test_suite_count() const { + return impl()->total_test_suite_count(); } -// Gets the number of all test cases that contain at least one test +// Gets the number of all test suites that contain at least one test // that should run. +int UnitTest::test_suite_to_run_count() const { + return impl()->test_suite_to_run_count(); +} + +// Legacy API is deprecated but still available +#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_ +int UnitTest::successful_test_case_count() const { + return impl()->successful_test_suite_count(); +} +int UnitTest::failed_test_case_count() const { + return impl()->failed_test_suite_count(); +} +int UnitTest::total_test_case_count() const { + return impl()->total_test_suite_count(); +} int UnitTest::test_case_to_run_count() const { - return impl()->test_case_to_run_count(); + return impl()->test_suite_to_run_count(); } +#endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_ // Gets the number of successful tests. int UnitTest::successful_test_count() const { @@ -4590,29 +4631,36 @@ internal::TimeInMillis UnitTest::elapsed_time() const { return impl()->elapsed_time(); } -// Returns true iff the unit test passed (i.e. all test cases passed). +// Returns true iff the unit test passed (i.e. all test suites passed). bool UnitTest::Passed() const { return impl()->Passed(); } -// Returns true iff the unit test failed (i.e. some test case failed +// Returns true iff the unit test failed (i.e. some test suite failed // or something outside of all tests failed). bool UnitTest::Failed() const { return impl()->Failed(); } -// Gets the i-th test case among all the test cases. i can range from 0 to -// total_test_case_count() - 1. If i is not in that range, returns NULL. +// Gets the i-th test suite among all the test suites. i can range from 0 to +// total_test_suite_count() - 1. If i is not in that range, returns NULL. +const TestSuite* UnitTest::GetTestSuite(int i) const { + return impl()->GetTestSuite(i); +} + +// Legacy API is deprecated but still available +#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_ const TestCase* UnitTest::GetTestCase(int i) const { return impl()->GetTestCase(i); } +#endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_ // Returns the TestResult containing information on test failures and -// properties logged outside of individual test cases. +// properties logged outside of individual test suites. const TestResult& UnitTest::ad_hoc_test_result() const { return *impl()->ad_hoc_test_result(); } -// Gets the i-th test case among all the test cases. i can range from 0 to -// total_test_case_count() - 1. If i is not in that range, returns NULL. -TestCase* UnitTest::GetMutableTestCase(int i) { - return impl()->GetMutableTestCase(i); +// Gets the i-th test suite among all the test suites. i can range from 0 to +// total_test_suite_count() - 1. If i is not in that range, returns NULL. +TestSuite* UnitTest::GetMutableTestSuite(int i) { + return impl()->GetMutableSuiteCase(i); } // Returns the list of event listeners that can be used to track events @@ -4711,8 +4759,8 @@ void UnitTest::AddTestPartResult( } // Adds a TestProperty to the current TestResult object when invoked from -// inside a test, to current TestCase's ad_hoc_test_result_ when invoked -// from SetUpTestCase or TearDownTestCase, or to the global property set +// inside a test, to current TestSuite's ad_hoc_test_result_ when invoked +// from SetUpTestSuite or TearDownTestSuite, or to the global property set // when invoked elsewhere. If the result already contains a property with // the same key, the value will be updated. void UnitTest::RecordProperty(const std::string& key, @@ -4804,13 +4852,22 @@ const char* UnitTest::original_working_dir() const { return impl_->original_working_dir_.c_str(); } -// Returns the TestCase object for the test that's currently running, +// Returns the TestSuite object for the test that's currently running, // or NULL if no test is running. +const TestSuite* UnitTest::current_test_suite() const + GTEST_LOCK_EXCLUDED_(mutex_) { + internal::MutexLock lock(&mutex_); + return impl_->current_test_suite(); +} + +// Legacy API is still available but deprecated +#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_ const TestCase* UnitTest::current_test_case() const GTEST_LOCK_EXCLUDED_(mutex_) { internal::MutexLock lock(&mutex_); - return impl_->current_test_case(); + return impl_->current_test_suite(); } +#endif // Returns the TestInfo object for the test that's currently running, // or NULL if no test is running. @@ -4823,11 +4880,10 @@ const TestInfo* UnitTest::current_test_info() const // Returns the random seed used at the start of the current test run. int UnitTest::random_seed() const { return impl_->random_seed(); } -// Returns ParameterizedTestCaseRegistry object used to keep track of +// Returns ParameterizedTestSuiteRegistry object used to keep track of // value-parameterized tests and instantiate and register them. -internal::ParameterizedTestCaseRegistry& - UnitTest::parameterized_test_registry() - GTEST_LOCK_EXCLUDED_(mutex_) { +internal::ParameterizedTestSuiteRegistry& +UnitTest::parameterized_test_registry() GTEST_LOCK_EXCLUDED_(mutex_) { return impl_->parameterized_test_registry(); } @@ -4869,8 +4925,8 @@ UnitTestImpl::UnitTestImpl(UnitTest* parent) &default_per_thread_test_part_result_reporter_), parameterized_test_registry_(), parameterized_tests_registered_(false), - last_death_test_case_(-1), - current_test_case_(nullptr), + last_death_test_suite_(-1), + current_test_suite_(nullptr), current_test_info_(nullptr), ad_hoc_test_result_(), os_stack_trace_getter_(nullptr), @@ -4888,8 +4944,8 @@ UnitTestImpl::UnitTestImpl(UnitTest* parent) } UnitTestImpl::~UnitTestImpl() { - // Deletes every TestCase. - ForEach(test_cases_, internal::Delete); + // Deletes every TestSuite. + ForEach(test_suites_, internal::Delete); // Deletes every Environment. ForEach(environments_, internal::Delete); @@ -4898,8 +4954,8 @@ UnitTestImpl::~UnitTestImpl() { } // Adds a TestProperty to the current TestResult object when invoked in a -// context of a test, to current test case's ad_hoc_test_result when invoke -// from SetUpTestCase/TearDownTestCase, or to the global property set +// context of a test, to current test suite's ad_hoc_test_result when invoke +// from SetUpTestSuite/TearDownTestSuite, or to the global property set // otherwise. If the result already contains a property with the same key, // the value will be updated. void UnitTestImpl::RecordProperty(const TestProperty& test_property) { @@ -4909,9 +4965,9 @@ void UnitTestImpl::RecordProperty(const TestProperty& test_property) { if (current_test_info_ != nullptr) { xml_element = "testcase"; test_result = &(current_test_info_->result_); - } else if (current_test_case_ != nullptr) { + } else if (current_test_suite_ != nullptr) { xml_element = "testsuite"; - test_result = &(current_test_case_->ad_hoc_test_result_); + test_result = &(current_test_suite_->ad_hoc_test_result_); } else { xml_element = "testsuites"; test_result = &ad_hoc_test_result_; @@ -5005,75 +5061,73 @@ void UnitTestImpl::PostFlagParsingInit() { } } -// A predicate that checks the name of a TestCase against a known +// A predicate that checks the name of a TestSuite against a known // value. // // This is used for implementation of the UnitTest class only. We put // it in the anonymous namespace to prevent polluting the outer // namespace. // -// TestCaseNameIs is copyable. -class TestCaseNameIs { +// TestSuiteNameIs is copyable. +class TestSuiteNameIs { public: // Constructor. - explicit TestCaseNameIs(const std::string& name) - : name_(name) {} + explicit TestSuiteNameIs(const std::string& name) : name_(name) {} - // Returns true iff the name of test_case matches name_. - bool operator()(const TestCase* test_case) const { - return test_case != nullptr && - strcmp(test_case->name(), name_.c_str()) == 0; + // Returns true iff the name of test_suite matches name_. + bool operator()(const TestSuite* test_suite) const { + return test_suite != nullptr && + strcmp(test_suite->name(), name_.c_str()) == 0; } private: std::string name_; }; -// Finds and returns a TestCase with the given name. If one doesn't +// Finds and returns a TestSuite with the given name. If one doesn't // exist, creates one and returns it. It's the CALLER'S // RESPONSIBILITY to ensure that this function is only called WHEN THE // TESTS ARE NOT SHUFFLED. // // Arguments: // -// test_case_name: name of the test case -// type_param: the name of the test case's type parameter, or NULL if -// this is not a typed or a type-parameterized test case. -// set_up_tc: pointer to the function that sets up the test case -// tear_down_tc: pointer to the function that tears down the test case -TestCase* UnitTestImpl::GetTestCase(const char* test_case_name, - const char* type_param, - Test::SetUpTestCaseFunc set_up_tc, - Test::TearDownTestCaseFunc tear_down_tc) { - // Can we find a TestCase with the given name? - const std::vector::const_reverse_iterator test_case = - std::find_if(test_cases_.rbegin(), test_cases_.rend(), - TestCaseNameIs(test_case_name)); - - if (test_case != test_cases_.rend()) - return *test_case; +// test_suite_name: name of the test suite +// type_param: the name of the test suite's type parameter, or NULL if +// this is not a typed or a type-parameterized test suite. +// set_up_tc: pointer to the function that sets up the test suite +// tear_down_tc: pointer to the function that tears down the test suite +TestSuite* UnitTestImpl::GetTestSuite( + const char* test_suite_name, const char* type_param, + internal::SetUpTestSuiteFunc set_up_tc, + internal::TearDownTestSuiteFunc tear_down_tc) { + // Can we find a TestSuite with the given name? + const auto test_suite = + std::find_if(test_suites_.rbegin(), test_suites_.rend(), + TestSuiteNameIs(test_suite_name)); + + if (test_suite != test_suites_.rend()) return *test_suite; // No. Let's create one. - TestCase* const new_test_case = - new TestCase(test_case_name, type_param, set_up_tc, tear_down_tc); - - // Is this a death test case? - if (internal::UnitTestOptions::MatchesFilter(test_case_name, - kDeathTestCaseFilter)) { - // Yes. Inserts the test case after the last death test case - // defined so far. This only works when the test cases haven't + auto* const new_test_suite = + new TestSuite(test_suite_name, type_param, set_up_tc, tear_down_tc); + + // Is this a death test suite? + if (internal::UnitTestOptions::MatchesFilter(test_suite_name, + kDeathTestSuiteFilter)) { + // Yes. Inserts the test suite after the last death test suite + // defined so far. This only works when the test suites haven't // been shuffled. Otherwise we may end up running a death test // after a non-death test. - ++last_death_test_case_; - test_cases_.insert(test_cases_.begin() + last_death_test_case_, - new_test_case); + ++last_death_test_suite_; + test_suites_.insert(test_suites_.begin() + last_death_test_suite_, + new_test_suite); } else { // No. Appends to the end of the list. - test_cases_.push_back(new_test_case); + test_suites_.push_back(new_test_suite); } - test_case_indices_.push_back(static_cast(test_case_indices_.size())); - return new_test_case; + test_suite_indices_.push_back(static_cast(test_suite_indices_.size())); + return new_test_suite; } // Helpers for setting up / tearing down the given environment. They @@ -5160,7 +5214,7 @@ bool UnitTestImpl::RunAllTests() { const TimeInMillis start = GetTimeInMillis(); - // Shuffles test cases and tests if requested. + // Shuffles test suites and tests if requested. if (has_tests_to_run && GTEST_FLAG(shuffle)) { random()->Reseed(random_seed_); // This should be done before calling OnTestIterationStart(), @@ -5172,7 +5226,7 @@ bool UnitTestImpl::RunAllTests() { // Tells the unit test event listeners that the tests are about to start. repeater->OnTestIterationStart(*parent_, i); - // Runs each test case if there is at least one test to run. + // Runs each test suite if there is at least one test to run. if (has_tests_to_run) { // Sets up all environments beforehand. repeater->OnEnvironmentsSetUpStart(*parent_); @@ -5182,9 +5236,9 @@ bool UnitTestImpl::RunAllTests() { // Runs the tests only if there was no fatal failure during global // set-up. if (!Test::HasFatalFailure()) { - for (int test_index = 0; test_index < total_test_case_count(); + for (int test_index = 0; test_index < total_test_suite_count(); test_index++) { - GetMutableTestCase(test_index)->Run(); + GetMutableSuiteCase(test_index)->Run(); } } @@ -5333,7 +5387,7 @@ bool ShouldRunTestOnShard(int total_shards, int shard_index, int test_id) { // Compares the name of each test with the user-specified filter to // decide whether the test should be run, then records the result in -// each TestCase and TestInfo object. +// each TestSuite and TestInfo object. // If shard_tests == true, further filters tests based on sharding // variables in the environment - see // https://github.com/google/googletest/blob/master/googletest/docs/advanced.md @@ -5350,26 +5404,23 @@ int UnitTestImpl::FilterTests(ReactionToSharding shard_tests) { // this shard. int num_runnable_tests = 0; int num_selected_tests = 0; - for (size_t i = 0; i < test_cases_.size(); i++) { - TestCase* const test_case = test_cases_[i]; - const std::string &test_case_name = test_case->name(); - test_case->set_should_run(false); + for (auto* test_suite : test_suites_) { + const std::string& test_suite_name = test_suite->name(); + test_suite->set_should_run(false); - for (size_t j = 0; j < test_case->test_info_list().size(); j++) { - TestInfo* const test_info = test_case->test_info_list()[j]; + for (size_t j = 0; j < test_suite->test_info_list().size(); j++) { + TestInfo* const test_info = test_suite->test_info_list()[j]; const std::string test_name(test_info->name()); - // A test is disabled if test case name or test name matches + // A test is disabled if test suite name or test name matches // kDisableTestFilter. - const bool is_disabled = - internal::UnitTestOptions::MatchesFilter(test_case_name, - kDisableTestFilter) || - internal::UnitTestOptions::MatchesFilter(test_name, - kDisableTestFilter); + const bool is_disabled = internal::UnitTestOptions::MatchesFilter( + test_suite_name, kDisableTestFilter) || + internal::UnitTestOptions::MatchesFilter( + test_name, kDisableTestFilter); test_info->is_disabled_ = is_disabled; - const bool matches_filter = - internal::UnitTestOptions::FilterMatchesTest(test_case_name, - test_name); + const bool matches_filter = internal::UnitTestOptions::FilterMatchesTest( + test_suite_name, test_name); test_info->matches_filter_ = matches_filter; const bool is_runnable = @@ -5386,7 +5437,7 @@ int UnitTestImpl::FilterTests(ReactionToSharding shard_tests) { num_selected_tests += is_selected; test_info->should_run_ = is_selected; - test_case->set_should_run(test_case->should_run() || is_selected); + test_suite->set_should_run(test_suite->should_run() || is_selected); } } return num_selected_tests; @@ -5419,22 +5470,20 @@ void UnitTestImpl::ListTestsMatchingFilter() { // Print at most this many characters for each type/value parameter. const int kMaxParamLength = 250; - for (size_t i = 0; i < test_cases_.size(); i++) { - const TestCase* const test_case = test_cases_[i]; - bool printed_test_case_name = false; + for (auto* test_suite : test_suites_) { + bool printed_test_suite_name = false; - for (size_t j = 0; j < test_case->test_info_list().size(); j++) { - const TestInfo* const test_info = - test_case->test_info_list()[j]; + for (size_t j = 0; j < test_suite->test_info_list().size(); j++) { + const TestInfo* const test_info = test_suite->test_info_list()[j]; if (test_info->matches_filter_) { - if (!printed_test_case_name) { - printed_test_case_name = true; - printf("%s.", test_case->name()); - if (test_case->type_param() != nullptr) { + if (!printed_test_suite_name) { + printed_test_suite_name = true; + printf("%s.", test_suite->name()); + if (test_suite->type_param() != nullptr) { printf(" # %s = ", kTypeParamLabel); // We print the type parameter on a single line to make // the output easy to parse by a program. - PrintOnOneLine(test_case->type_param(), kMaxParamLength); + PrintOnOneLine(test_suite->type_param(), kMaxParamLength); } printf("\n"); } @@ -5458,11 +5507,11 @@ void UnitTestImpl::ListTestsMatchingFilter() { if (output_format == "xml") { XmlUnitTestResultPrinter( UnitTestOptions::GetAbsolutePathToOutputFile().c_str()) - .PrintXmlTestsList(&stream, test_cases_); + .PrintXmlTestsList(&stream, test_suites_); } else if (output_format == "json") { JsonUnitTestResultPrinter( UnitTestOptions::GetAbsolutePathToOutputFile().c_str()) - .PrintJsonTestList(&stream, test_cases_); + .PrintJsonTestList(&stream, test_suites_); } fprintf(fileout, "%s", StringStreamToString(&stream).c_str()); fclose(fileout); @@ -5502,35 +5551,35 @@ TestResult* UnitTestImpl::current_test_result() { if (current_test_info_ != nullptr) { return ¤t_test_info_->result_; } - if (current_test_case_ != nullptr) { - return ¤t_test_case_->ad_hoc_test_result_; + if (current_test_suite_ != nullptr) { + return ¤t_test_suite_->ad_hoc_test_result_; } return &ad_hoc_test_result_; } -// Shuffles all test cases, and the tests within each test case, +// Shuffles all test suites, and the tests within each test suite, // making sure that death tests are still run first. void UnitTestImpl::ShuffleTests() { - // Shuffles the death test cases. - ShuffleRange(random(), 0, last_death_test_case_ + 1, &test_case_indices_); + // Shuffles the death test suites. + ShuffleRange(random(), 0, last_death_test_suite_ + 1, &test_suite_indices_); - // Shuffles the non-death test cases. - ShuffleRange(random(), last_death_test_case_ + 1, - static_cast(test_cases_.size()), &test_case_indices_); + // Shuffles the non-death test suites. + ShuffleRange(random(), last_death_test_suite_ + 1, + static_cast(test_suites_.size()), &test_suite_indices_); - // Shuffles the tests inside each test case. - for (size_t i = 0; i < test_cases_.size(); i++) { - test_cases_[i]->ShuffleTests(random()); + // Shuffles the tests inside each test suite. + for (auto& test_suite : test_suites_) { + test_suite->ShuffleTests(random()); } } -// Restores the test cases and tests to their order before the first shuffle. +// Restores the test suites and tests to their order before the first shuffle. void UnitTestImpl::UnshuffleTests() { - for (size_t i = 0; i < test_cases_.size(); i++) { - // Unshuffles the tests in each test case. - test_cases_[i]->UnshuffleTests(); - // Resets the index of each test case. - test_case_indices_[i] = static_cast(i); + for (size_t i = 0; i < test_suites_.size(); i++) { + // Unshuffles the tests in each test suite. + test_suites_[i]->UnshuffleTests(); + // Resets the index of each test suite. + test_suite_indices_[i] = static_cast(i); } } diff --git a/googletest/test/googletest-catch-exceptions-test.py b/googletest/test/googletest-catch-exceptions-test.py index 5d49c102..6a4dce21 100755 --- a/googletest/test/googletest-catch-exceptions-test.py +++ b/googletest/test/googletest-catch-exceptions-test.py @@ -140,8 +140,7 @@ class CatchCxxExceptionsTest(gtest_test_utils.TestCase): def testCatchesCxxExceptionsInSetUpTestCase(self): self.assert_('C++ exception with description "Standard C++ exception"' - ' thrown in SetUpTestCase()' - in EX_BINARY_OUTPUT) + ' thrown in SetUpTestSuite()' in EX_BINARY_OUTPUT) self.assert_('CxxExceptionInConstructorTest::TearDownTestCase() ' 'called as expected.' in EX_BINARY_OUTPUT) @@ -163,8 +162,7 @@ class CatchCxxExceptionsTest(gtest_test_utils.TestCase): def testCatchesCxxExceptionsInTearDownTestCase(self): self.assert_('C++ exception with description "Standard C++ exception"' - ' thrown in TearDownTestCase()' - in EX_BINARY_OUTPUT) + ' thrown in TearDownTestSuite()' in EX_BINARY_OUTPUT) def testCatchesCxxExceptionsInSetUp(self): self.assert_('C++ exception with description "Standard C++ exception"' diff --git a/googletest/test/googletest-listener-test.cc b/googletest/test/googletest-listener-test.cc index 1f5f5c53..e0331090 100644 --- a/googletest/test/googletest-listener-test.cc +++ b/googletest/test/googletest-listener-test.cc @@ -125,6 +125,78 @@ class EventRecordingListener : public TestEventListener { std::string name_; }; +// This listener is using OnTestSuiteStart, OnTestSuiteEnd API +class EventRecordingListener2 : public TestEventListener { + public: + explicit EventRecordingListener2(const char* name) : name_(name) {} + + protected: + void OnTestProgramStart(const UnitTest& /*unit_test*/) override { + g_events->push_back(GetFullMethodName("OnTestProgramStart")); + } + + void OnTestIterationStart(const UnitTest& /*unit_test*/, + int iteration) override { + Message message; + message << GetFullMethodName("OnTestIterationStart") << "(" << iteration + << ")"; + g_events->push_back(message.GetString()); + } + + void OnEnvironmentsSetUpStart(const UnitTest& /*unit_test*/) override { + g_events->push_back(GetFullMethodName("OnEnvironmentsSetUpStart")); + } + + void OnEnvironmentsSetUpEnd(const UnitTest& /*unit_test*/) override { + g_events->push_back(GetFullMethodName("OnEnvironmentsSetUpEnd")); + } + + void OnTestSuiteStart(const TestSuite& /*test_suite*/) override { + g_events->push_back(GetFullMethodName("OnTestSuiteStart")); + } + + void OnTestStart(const TestInfo& /*test_info*/) override { + g_events->push_back(GetFullMethodName("OnTestStart")); + } + + void OnTestPartResult(const TestPartResult& /*test_part_result*/) override { + g_events->push_back(GetFullMethodName("OnTestPartResult")); + } + + void OnTestEnd(const TestInfo& /*test_info*/) override { + g_events->push_back(GetFullMethodName("OnTestEnd")); + } + + void OnTestSuiteEnd(const TestSuite& /*test_suite*/) override { + g_events->push_back(GetFullMethodName("OnTestSuiteEnd")); + } + + void OnEnvironmentsTearDownStart(const UnitTest& /*unit_test*/) override { + g_events->push_back(GetFullMethodName("OnEnvironmentsTearDownStart")); + } + + void OnEnvironmentsTearDownEnd(const UnitTest& /*unit_test*/) override { + g_events->push_back(GetFullMethodName("OnEnvironmentsTearDownEnd")); + } + + void OnTestIterationEnd(const UnitTest& /*unit_test*/, + int iteration) override { + Message message; + message << GetFullMethodName("OnTestIterationEnd") << "(" << iteration + << ")"; + g_events->push_back(message.GetString()); + } + + void OnTestProgramEnd(const UnitTest& /*unit_test*/) override { + g_events->push_back(GetFullMethodName("OnTestProgramEnd")); + } + + private: + std::string GetFullMethodName(const char* name) { return name_ + "." + name; } + + std::string name_; +}; + class EnvironmentInvocationCatcher : public Environment { protected: void SetUp() override { g_events->push_back("Environment::SetUp"); } @@ -165,6 +237,7 @@ TEST_F(ListenerTest, DoesBar) { using ::testing::internal::EnvironmentInvocationCatcher; using ::testing::internal::EventRecordingListener; +using ::testing::internal::EventRecordingListener2; void VerifyResults(const std::vector& data, const char* const* expected_data, @@ -199,6 +272,8 @@ int main(int argc, char **argv) { new EventRecordingListener("1st")); UnitTest::GetInstance()->listeners().Append( new EventRecordingListener("2nd")); + UnitTest::GetInstance()->listeners().Append( + new EventRecordingListener2("3rd")); AddGlobalTestEnvironment(new EnvironmentInvocationCatcher); @@ -208,88 +283,117 @@ int main(int argc, char **argv) { ::testing::GTEST_FLAG(repeat) = 2; int ret_val = RUN_ALL_TESTS(); - const char* const expected_events[] = { - "1st.OnTestProgramStart", - "2nd.OnTestProgramStart", - "1st.OnTestIterationStart(0)", - "2nd.OnTestIterationStart(0)", - "1st.OnEnvironmentsSetUpStart", - "2nd.OnEnvironmentsSetUpStart", - "Environment::SetUp", - "2nd.OnEnvironmentsSetUpEnd", - "1st.OnEnvironmentsSetUpEnd", - "1st.OnTestCaseStart", - "2nd.OnTestCaseStart", - "ListenerTest::SetUpTestCase", - "1st.OnTestStart", - "2nd.OnTestStart", - "ListenerTest::SetUp", - "ListenerTest::* Test Body", - "1st.OnTestPartResult", - "2nd.OnTestPartResult", - "ListenerTest::TearDown", - "2nd.OnTestEnd", - "1st.OnTestEnd", - "1st.OnTestStart", - "2nd.OnTestStart", - "ListenerTest::SetUp", - "ListenerTest::* Test Body", - "1st.OnTestPartResult", - "2nd.OnTestPartResult", - "ListenerTest::TearDown", - "2nd.OnTestEnd", - "1st.OnTestEnd", - "ListenerTest::TearDownTestCase", - "2nd.OnTestCaseEnd", - "1st.OnTestCaseEnd", - "1st.OnEnvironmentsTearDownStart", - "2nd.OnEnvironmentsTearDownStart", - "Environment::TearDown", - "2nd.OnEnvironmentsTearDownEnd", - "1st.OnEnvironmentsTearDownEnd", - "2nd.OnTestIterationEnd(0)", - "1st.OnTestIterationEnd(0)", - "1st.OnTestIterationStart(1)", - "2nd.OnTestIterationStart(1)", - "1st.OnEnvironmentsSetUpStart", - "2nd.OnEnvironmentsSetUpStart", - "Environment::SetUp", - "2nd.OnEnvironmentsSetUpEnd", - "1st.OnEnvironmentsSetUpEnd", - "1st.OnTestCaseStart", - "2nd.OnTestCaseStart", - "ListenerTest::SetUpTestCase", - "1st.OnTestStart", - "2nd.OnTestStart", - "ListenerTest::SetUp", - "ListenerTest::* Test Body", - "1st.OnTestPartResult", - "2nd.OnTestPartResult", - "ListenerTest::TearDown", - "2nd.OnTestEnd", - "1st.OnTestEnd", - "1st.OnTestStart", - "2nd.OnTestStart", - "ListenerTest::SetUp", - "ListenerTest::* Test Body", - "1st.OnTestPartResult", - "2nd.OnTestPartResult", - "ListenerTest::TearDown", - "2nd.OnTestEnd", - "1st.OnTestEnd", - "ListenerTest::TearDownTestCase", - "2nd.OnTestCaseEnd", - "1st.OnTestCaseEnd", - "1st.OnEnvironmentsTearDownStart", - "2nd.OnEnvironmentsTearDownStart", - "Environment::TearDown", - "2nd.OnEnvironmentsTearDownEnd", - "1st.OnEnvironmentsTearDownEnd", - "2nd.OnTestIterationEnd(1)", - "1st.OnTestIterationEnd(1)", - "2nd.OnTestProgramEnd", - "1st.OnTestProgramEnd" - }; + const char* const expected_events[] = {"1st.OnTestProgramStart", + "2nd.OnTestProgramStart", + "3rd.OnTestProgramStart", + "1st.OnTestIterationStart(0)", + "2nd.OnTestIterationStart(0)", + "3rd.OnTestIterationStart(0)", + "1st.OnEnvironmentsSetUpStart", + "2nd.OnEnvironmentsSetUpStart", + "3rd.OnEnvironmentsSetUpStart", + "Environment::SetUp", + "3rd.OnEnvironmentsSetUpEnd", + "2nd.OnEnvironmentsSetUpEnd", + "1st.OnEnvironmentsSetUpEnd", + "3rd.OnTestSuiteStart", + "1st.OnTestCaseStart", + "2nd.OnTestCaseStart", + "ListenerTest::SetUpTestCase", + "1st.OnTestStart", + "2nd.OnTestStart", + "3rd.OnTestStart", + "ListenerTest::SetUp", + "ListenerTest::* Test Body", + "1st.OnTestPartResult", + "2nd.OnTestPartResult", + "3rd.OnTestPartResult", + "ListenerTest::TearDown", + "3rd.OnTestEnd", + "2nd.OnTestEnd", + "1st.OnTestEnd", + "1st.OnTestStart", + "2nd.OnTestStart", + "3rd.OnTestStart", + "ListenerTest::SetUp", + "ListenerTest::* Test Body", + "1st.OnTestPartResult", + "2nd.OnTestPartResult", + "3rd.OnTestPartResult", + "ListenerTest::TearDown", + "3rd.OnTestEnd", + "2nd.OnTestEnd", + "1st.OnTestEnd", + "ListenerTest::TearDownTestCase", + "3rd.OnTestSuiteEnd", + "2nd.OnTestCaseEnd", + "1st.OnTestCaseEnd", + "1st.OnEnvironmentsTearDownStart", + "2nd.OnEnvironmentsTearDownStart", + "3rd.OnEnvironmentsTearDownStart", + "Environment::TearDown", + "3rd.OnEnvironmentsTearDownEnd", + "2nd.OnEnvironmentsTearDownEnd", + "1st.OnEnvironmentsTearDownEnd", + "3rd.OnTestIterationEnd(0)", + "2nd.OnTestIterationEnd(0)", + "1st.OnTestIterationEnd(0)", + "1st.OnTestIterationStart(1)", + "2nd.OnTestIterationStart(1)", + "3rd.OnTestIterationStart(1)", + "1st.OnEnvironmentsSetUpStart", + "2nd.OnEnvironmentsSetUpStart", + "3rd.OnEnvironmentsSetUpStart", + "Environment::SetUp", + "3rd.OnEnvironmentsSetUpEnd", + "2nd.OnEnvironmentsSetUpEnd", + "1st.OnEnvironmentsSetUpEnd", + "3rd.OnTestSuiteStart", + "1st.OnTestCaseStart", + "2nd.OnTestCaseStart", + "ListenerTest::SetUpTestCase", + "1st.OnTestStart", + "2nd.OnTestStart", + "3rd.OnTestStart", + "ListenerTest::SetUp", + "ListenerTest::* Test Body", + "1st.OnTestPartResult", + "2nd.OnTestPartResult", + "3rd.OnTestPartResult", + "ListenerTest::TearDown", + "3rd.OnTestEnd", + "2nd.OnTestEnd", + "1st.OnTestEnd", + "1st.OnTestStart", + "2nd.OnTestStart", + "3rd.OnTestStart", + "ListenerTest::SetUp", + "ListenerTest::* Test Body", + "1st.OnTestPartResult", + "2nd.OnTestPartResult", + "3rd.OnTestPartResult", + "ListenerTest::TearDown", + "3rd.OnTestEnd", + "2nd.OnTestEnd", + "1st.OnTestEnd", + "ListenerTest::TearDownTestCase", + "3rd.OnTestSuiteEnd", + "2nd.OnTestCaseEnd", + "1st.OnTestCaseEnd", + "1st.OnEnvironmentsTearDownStart", + "2nd.OnEnvironmentsTearDownStart", + "3rd.OnEnvironmentsTearDownStart", + "Environment::TearDown", + "3rd.OnEnvironmentsTearDownEnd", + "2nd.OnEnvironmentsTearDownEnd", + "1st.OnEnvironmentsTearDownEnd", + "3rd.OnTestIterationEnd(1)", + "2nd.OnTestIterationEnd(1)", + "1st.OnTestIterationEnd(1)", + "3rd.OnTestProgramEnd", + "2nd.OnTestProgramEnd", + "1st.OnTestProgramEnd"}; + VerifyResults(events, expected_events, sizeof(expected_events)/sizeof(expected_events[0])); diff --git a/googletest/test/googletest-output-test-golden-lin.txt b/googletest/test/googletest-output-test-golden-lin.txt index 89a38e9e..464a03a4 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 83 tests from 38 test cases. +[==========] Running 83 tests from 38 test suites. [----------] Global test environment set-up. FooEnvironment::SetUp() called. BarEnvironment::SetUp() called. @@ -392,26 +392,26 @@ Stack trace: (omitted) [ RUN ] MixedUpTestCaseTest.ThisShouldFail gtest.cc:#: Failure Failed -All tests in the same test case must use the same test fixture -class. However, in test case MixedUpTestCaseTest, +All tests in the same test suite must use the same test fixture +class. However, in test suite MixedUpTestCaseTest, you defined test FirstTestFromNamespaceFoo and test ThisShouldFail using two different test fixture classes. This can happen if the two classes are from different namespaces or translation units and have the same name. You should probably rename one -of the classes to put the tests into different test cases. +of the classes to put the tests into different test suites. Stack trace: (omitted) [ FAILED ] MixedUpTestCaseTest.ThisShouldFail [ RUN ] MixedUpTestCaseTest.ThisShouldFailToo gtest.cc:#: Failure Failed -All tests in the same test case must use the same test fixture -class. However, in test case MixedUpTestCaseTest, +All tests in the same test suite must use the same test fixture +class. However, in test suite MixedUpTestCaseTest, you defined test FirstTestFromNamespaceFoo and test ThisShouldFailToo using two different test fixture classes. This can happen if the two classes are from different namespaces or translation units and have the same name. You should probably rename one -of the classes to put the tests into different test cases. +of the classes to put the tests into different test suites. Stack trace: (omitted) [ FAILED ] MixedUpTestCaseTest.ThisShouldFailToo @@ -421,13 +421,13 @@ Stack trace: (omitted) [ RUN ] MixedUpTestCaseWithSameTestNameTest.TheSecondTestWithThisNameShouldFail gtest.cc:#: Failure Failed -All tests in the same test case must use the same test fixture -class. However, in test case MixedUpTestCaseWithSameTestNameTest, +All tests in the same test suite must use the same test fixture +class. However, in test suite MixedUpTestCaseWithSameTestNameTest, you defined test TheSecondTestWithThisNameShouldFail and test TheSecondTestWithThisNameShouldFail using two different test fixture classes. This can happen if the two classes are from different namespaces or translation units and have the same name. You should probably rename one -of the classes to put the tests into different test cases. +of the classes to put the tests into different test suites. Stack trace: (omitted) [ FAILED ] MixedUpTestCaseWithSameTestNameTest.TheSecondTestWithThisNameShouldFail @@ -437,9 +437,9 @@ Stack trace: (omitted) [ RUN ] TEST_F_before_TEST_in_same_test_case.DefinedUsingTESTAndShouldFail gtest.cc:#: Failure Failed -All tests in the same test case must use the same test fixture -class, so mixing TEST_F and TEST in the same test case is -illegal. In test case TEST_F_before_TEST_in_same_test_case, +All tests in the same test suite must use the same test fixture +class, so mixing TEST_F and TEST in the same test suite is +illegal. In test suite TEST_F_before_TEST_in_same_test_case, test DefinedUsingTEST_F is defined using TEST_F but test DefinedUsingTESTAndShouldFail is defined using TEST. You probably want to change the TEST to TEST_F or move it to another test @@ -453,9 +453,9 @@ Stack trace: (omitted) [ RUN ] TEST_before_TEST_F_in_same_test_case.DefinedUsingTEST_FAndShouldFail gtest.cc:#: Failure Failed -All tests in the same test case must use the same test fixture -class, so mixing TEST_F and TEST in the same test case is -illegal. In test case TEST_before_TEST_F_in_same_test_case, +All tests in the same test suite must use the same test fixture +class, so mixing TEST_F and TEST in the same test suite is +illegal. In test suite TEST_before_TEST_F_in_same_test_case, test DefinedUsingTEST_FAndShouldFail is defined using TEST_F but test DefinedUsingTEST is defined using TEST. You probably want to change the TEST to TEST_F or move it to another test @@ -912,9 +912,9 @@ DynamicFixture::TearDown DynamicFixture() gtest.cc:#: Failure Failed -All tests in the same test case must use the same test fixture -class, so mixing TEST_F and TEST in the same test case is -illegal. In test case BadDynamicFixture1, +All tests in the same test suite must use the same test fixture +class, so mixing TEST_F and TEST in the same test suite is +illegal. In test suite BadDynamicFixture1, test FixtureBase is defined using TEST_F but test TestBase is defined using TEST. You probably want to change the TEST to TEST_F or move it to another test @@ -936,13 +936,13 @@ DynamicFixture::TearDown DynamicFixture() gtest.cc:#: Failure Failed -All tests in the same test case must use the same test fixture -class. However, in test case BadDynamicFixture2, +All tests in the same test suite must use the same test fixture +class. However, in test suite BadDynamicFixture2, you defined test FixtureBase and test Derived using two different test fixture classes. This can happen if the two classes are from different namespaces or translation units and have the same name. You should probably rename one -of the classes to put the tests into different test cases. +of the classes to put the tests into different test suites. Stack trace: (omitted) ~DynamicFixture() @@ -984,7 +984,7 @@ Failed Expected fatal failure. Stack trace: (omitted) -[==========] 83 tests from 38 test cases ran. +[==========] 83 tests from 38 test suites ran. [ PASSED ] 30 tests. [ FAILED ] 53 tests, listed below: [ FAILED ] NonfatalFailureTest.EscapesStringOperands @@ -1045,7 +1045,7 @@ Stack trace: (omitted)  YOU HAVE 1 DISABLED TEST Note: Google Test filter = FatalFailureTest.*:LoggingTest.* -[==========] Running 4 tests from 2 test cases. +[==========] Running 4 tests from 2 test suites. [----------] Global test environment set-up. [----------] 3 tests from FatalFailureTest [ RUN ] FatalFailureTest.FatalFailureInSubroutine @@ -1098,7 +1098,7 @@ Stack trace: (omitted) [----------] 1 test from LoggingTest (? ms total) [----------] Global test environment tear-down -[==========] 4 tests from 2 test cases ran. (? ms total) +[==========] 4 tests from 2 test suites ran. (? ms total) [ PASSED ] 0 tests. [ FAILED ] 4 tests, listed below: [ FAILED ] FatalFailureTest.FatalFailureInSubroutine @@ -1108,21 +1108,21 @@ Stack trace: (omitted) 4 FAILED TESTS Note: Google Test filter = *DISABLED_* -[==========] Running 1 test from 1 test case. +[==========] Running 1 test from 1 test suite. [----------] Global test environment set-up. [----------] 1 test from DisabledTestsWarningTest [ RUN ] DisabledTestsWarningTest.DISABLED_AlsoRunDisabledTestsFlagSuppressesWarning [ OK ] DisabledTestsWarningTest.DISABLED_AlsoRunDisabledTestsFlagSuppressesWarning [----------] Global test environment tear-down -[==========] 1 test from 1 test case ran. +[==========] 1 test from 1 test suite ran. [ PASSED ] 1 test. Note: Google Test filter = PassingTest.* Note: This is test shard 2 of 2. -[==========] Running 1 test from 1 test case. +[==========] Running 1 test from 1 test suite. [----------] Global test environment set-up. [----------] 1 test from PassingTest [ RUN ] PassingTest.PassingTest2 [ OK ] PassingTest.PassingTest2 [----------] Global test environment tear-down -[==========] 1 test from 1 test case ran. +[==========] 1 test from 1 test suite ran. [ PASSED ] 1 test. diff --git a/googletest/test/gtest-typed-test_test.cc b/googletest/test/gtest-typed-test_test.cc index de6cc534..4b0ae08d 100644 --- a/googletest/test/gtest-typed-test_test.cc +++ b/googletest/test/gtest-typed-test_test.cc @@ -249,7 +249,7 @@ TEST_F(TypedTestCasePStateDeathTest, DetectsDuplicates) { TEST_F(TypedTestCasePStateDeathTest, DetectsExtraTest) { EXPECT_DEATH_IF_SUPPORTED( state_.VerifyRegisteredTestNames("foo.cc", 1, "A, B, C, D"), - "foo\\.cc.1.?: No test named D can be found in this test case\\."); + "foo\\.cc.1.?: No test named D can be found in this test suite\\."); } TEST_F(TypedTestCasePStateDeathTest, DetectsMissedTest) { @@ -264,7 +264,7 @@ TEST_F(TypedTestCasePStateDeathTest, DetectsTestAfterRegistration) { state_.VerifyRegisteredTestNames("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_CASE_P" + "foo\\.cc.2.?: Test D must be defined before REGISTER_TYPED_TEST_SUITE_P" "\\(FooTest, \\.\\.\\.\\)\\."); } diff --git a/googletest/test/gtest_unittest.cc b/googletest/test/gtest_unittest.cc index 307f630c..6c7d5519 100644 --- a/googletest/test/gtest_unittest.cc +++ b/googletest/test/gtest_unittest.cc @@ -5431,6 +5431,67 @@ TEST_F(SetUpTestCaseTest, Test2) { EXPECT_STREQ("123", shared_resource_); } +// Tests SetupTestSuite/TearDown TestSuite API +class SetUpTestSuiteTest : public Test { + protected: + // This will be called once before the first test in this test case + // is run. + static void SetUpTestSuite() { + printf("Setting up the test suite . . .\n"); + + // Initializes some shared resource. In this simple example, we + // just create a C string. More complex stuff can be done if + // desired. + shared_resource_ = "123"; + + // Increments the number of test cases that have been set up. + counter_++; + + // SetUpTestSuite() should be called only once. + EXPECT_EQ(1, counter_); + } + + // This will be called once after the last test in this test case is + // run. + static void TearDownTestSuite() { + printf("Tearing down the test suite . . .\n"); + + // Decrements the number of test suites that have been set up. + counter_--; + + // TearDownTestSuite() should be called only once. + EXPECT_EQ(0, counter_); + + // Cleans up the shared resource. + shared_resource_ = nullptr; + } + + // This will be called before each test in this test case. + void SetUp() override { + // SetUpTestSuite() should be called only once, so counter_ should + // always be 1. + EXPECT_EQ(1, counter_); + } + + // Number of test suites that have been set up. + static int counter_; + + // Some resource to be shared by all tests in this test case. + static const char* shared_resource_; +}; + +int SetUpTestSuiteTest::counter_ = 0; +const char* SetUpTestSuiteTest::shared_resource_ = nullptr; + +// A test that uses the shared resource. +TEST_F(SetUpTestSuiteTest, TestSetupTestSuite1) { + EXPECT_STRNE(nullptr, shared_resource_); +} + +// Another test that uses the shared resource. +TEST_F(SetUpTestSuiteTest, TestSetupTestSuite2) { + EXPECT_STREQ("123", shared_resource_); +} // The ParseFlagsTest test case tests ParseGoogleTestFlagsOnly. -- cgit v1.2.3 From 827515f8a092050901d4eb9fdc1ddbb972f38442 Mon Sep 17 00:00:00 2001 From: misterg Date: Thu, 3 Jan 2019 16:32:01 -0500 Subject: Googletest export Fixes #1261 PiperOrigin-RevId: 227740670 --- googletest/include/gtest/gtest_pred_impl.h | 74 ++++++++++++++--------------- googletest/test/gtest_pred_impl_unittest.cc | 2 +- googletest/test/gtest_unittest.cc | 10 ++++ 3 files changed, 48 insertions(+), 38 deletions(-) diff --git a/googletest/include/gtest/gtest_pred_impl.h b/googletest/include/gtest/gtest_pred_impl.h index 0c1105cb..d514255c 100644 --- a/googletest/include/gtest/gtest_pred_impl.h +++ b/googletest/include/gtest/gtest_pred_impl.h @@ -27,11 +27,10 @@ // (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/2018 by command +// This file is AUTOMATICALLY GENERATED on 01/02/2019 by command // 'gen_gtest_pred_impl.py 5'. 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_ @@ -67,6 +66,8 @@ namespace testing { // We also define the EXPECT_* variations. // // For now we only support predicates whose arity is at most 5. +// Please email googletestframework@googlegroups.com if you need +// support for higher arities. // GTEST_ASSERT_ is the basic statement to which all of the assertions // in this file reduce. Don't use this in your code. @@ -89,9 +90,10 @@ AssertionResult AssertPred1Helper(const char* pred_text, const T1& v1) { if (pred(v1)) return AssertionSuccess(); - return AssertionFailure() << pred_text << "(" - << e1 << ") evaluates to false, where" - << "\n" << e1 << " evaluates to " << v1; + return AssertionFailure() + << pred_text << "(" << e1 << ") evaluates to false, where" + << "\n" + << e1 << " evaluates to " << ::testing::PrintToString(v1); } // Internal macro for implementing {EXPECT|ASSERT}_PRED_FORMAT1. @@ -133,11 +135,12 @@ AssertionResult AssertPred2Helper(const char* pred_text, const T2& v2) { if (pred(v1, v2)) return AssertionSuccess(); - return AssertionFailure() << pred_text << "(" - << e1 << ", " - << e2 << ") evaluates to false, where" - << "\n" << e1 << " evaluates to " << v1 - << "\n" << e2 << " evaluates to " << v2; + return AssertionFailure() + << pred_text << "(" << e1 << ", " << e2 + << ") evaluates to false, where" + << "\n" + << e1 << " evaluates to " << ::testing::PrintToString(v1) << "\n" + << e2 << " evaluates to " << ::testing::PrintToString(v2); } // Internal macro for implementing {EXPECT|ASSERT}_PRED_FORMAT2. @@ -184,13 +187,13 @@ AssertionResult AssertPred3Helper(const char* pred_text, const T3& v3) { if (pred(v1, v2, v3)) return AssertionSuccess(); - return AssertionFailure() << pred_text << "(" - << e1 << ", " - << e2 << ", " - << e3 << ") evaluates to false, where" - << "\n" << e1 << " evaluates to " << v1 - << "\n" << e2 << " evaluates to " << v2 - << "\n" << e3 << " evaluates to " << v3; + return AssertionFailure() + << pred_text << "(" << e1 << ", " << e2 << ", " << e3 + << ") evaluates to false, where" + << "\n" + << e1 << " evaluates to " << ::testing::PrintToString(v1) << "\n" + << e2 << " evaluates to " << ::testing::PrintToString(v2) << "\n" + << e3 << " evaluates to " << ::testing::PrintToString(v3); } // Internal macro for implementing {EXPECT|ASSERT}_PRED_FORMAT3. @@ -242,15 +245,14 @@ AssertionResult AssertPred4Helper(const char* pred_text, const T4& v4) { if (pred(v1, v2, v3, v4)) return AssertionSuccess(); - return AssertionFailure() << pred_text << "(" - << e1 << ", " - << e2 << ", " - << e3 << ", " - << e4 << ") evaluates to false, where" - << "\n" << e1 << " evaluates to " << v1 - << "\n" << e2 << " evaluates to " << v2 - << "\n" << e3 << " evaluates to " << v3 - << "\n" << e4 << " evaluates to " << v4; + return AssertionFailure() + << pred_text << "(" << e1 << ", " << e2 << ", " << e3 << ", " << e4 + << ") evaluates to false, where" + << "\n" + << e1 << " evaluates to " << ::testing::PrintToString(v1) << "\n" + << e2 << " evaluates to " << ::testing::PrintToString(v2) << "\n" + << e3 << " evaluates to " << ::testing::PrintToString(v3) << "\n" + << e4 << " evaluates to " << ::testing::PrintToString(v4); } // Internal macro for implementing {EXPECT|ASSERT}_PRED_FORMAT4. @@ -307,17 +309,15 @@ AssertionResult AssertPred5Helper(const char* pred_text, const T5& v5) { if (pred(v1, v2, v3, v4, v5)) return AssertionSuccess(); - return AssertionFailure() << pred_text << "(" - << e1 << ", " - << e2 << ", " - << e3 << ", " - << e4 << ", " - << e5 << ") evaluates to false, where" - << "\n" << e1 << " evaluates to " << v1 - << "\n" << e2 << " evaluates to " << v2 - << "\n" << e3 << " evaluates to " << v3 - << "\n" << e4 << " evaluates to " << v4 - << "\n" << e5 << " evaluates to " << v5; + return AssertionFailure() + << pred_text << "(" << e1 << ", " << e2 << ", " << e3 << ", " << e4 + << ", " << e5 << ") evaluates to false, where" + << "\n" + << e1 << " evaluates to " << ::testing::PrintToString(v1) << "\n" + << e2 << " evaluates to " << ::testing::PrintToString(v2) << "\n" + << e3 << " evaluates to " << ::testing::PrintToString(v3) << "\n" + << e4 << " evaluates to " << ::testing::PrintToString(v4) << "\n" + << e5 << " evaluates to " << ::testing::PrintToString(v5); } // Internal macro for implementing {EXPECT|ASSERT}_PRED_FORMAT5. diff --git a/googletest/test/gtest_pred_impl_unittest.cc b/googletest/test/gtest_pred_impl_unittest.cc index 2019a30c..049ef983 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/2018 by command +// This file is AUTOMATICALLY GENERATED on 01/02/2019 by command // 'gen_gtest_pred_impl.py 5'. DO NOT EDIT BY HAND! // Regression test for gtest_pred_impl.h diff --git a/googletest/test/gtest_unittest.cc b/googletest/test/gtest_unittest.cc index 6c7d5519..5e0e43a4 100644 --- a/googletest/test/gtest_unittest.cc +++ b/googletest/test/gtest_unittest.cc @@ -2357,6 +2357,16 @@ TEST(PredTest, SingleEvaluationOnFailure) { EXPECT_EQ(1, n4) << "Argument 4 is not evaluated exactly once."; } +// Test predicate assertions for sets +TEST(PredTest, ExpectPredEvalFailure) { + std::set set_a = {2, 1, 3, 4, 5}; + std::set set_b = {0, 4, 8}; + const auto compare_sets = [] (std::set, std::set) { return false; }; + EXPECT_NONFATAL_FAILURE( + EXPECT_PRED2(compare_sets, set_a, set_b), + "compare_sets(set_a, set_b) evaluates to false, where\nset_a evaluates " + "to { 1, 2, 3, 4, 5 }\nset_b evaluates to { 0, 4, 8 }"); +} // Some helper functions for testing using overloaded/template // functions with ASSERT_PREDn and EXPECT_PREDn. -- cgit v1.2.3 From 5d3a2cd9c854a697d0d1147e2bc19d4254b8f053 Mon Sep 17 00:00:00 2001 From: Gennadiy Civil Date: Thu, 3 Jan 2019 17:18:03 -0500 Subject: Update docs, TestCase->TestSuite --- googletest/docs/advanced.md | 170 ++++++++++++++++++++++---------------------- googletest/docs/faq.md | 24 +++---- googletest/docs/primer.md | 20 +++--- 3 files changed, 106 insertions(+), 108 deletions(-) diff --git a/googletest/docs/advanced.md b/googletest/docs/advanced.md index 05524809..dbe6694a 100644 --- a/googletest/docs/advanced.md +++ b/googletest/docs/advanced.md @@ -751,7 +751,7 @@ necessary. ### Death Test Naming IMPORTANT: We strongly recommend you to follow the convention of naming your -**test case** (not test) `*DeathTest` when it contains a death test, as +**test suite** (not test) `*DeathTest` when it contains a death test, as demonstrated in the above example. The [Death Tests And Threads](#death-tests-and-threads) section below explains why. @@ -865,7 +865,7 @@ googletest has three features intended to raise awareness of threading issues. 1. A warning is emitted if multiple threads are running when a death test is encountered. -2. Test cases with a name ending in "DeathTest" are run before all other tests. +2. Test suites with a name ending in "DeathTest" are run before all other tests. 3. It uses `clone()` instead of `fork()` to spawn the child process on Linux (`clone()` is not available on Cygwin and Mac), as `fork()` is more likely to cause the child to hang when the parent process has multiple threads. @@ -944,7 +944,7 @@ handlers registered with `pthread_atfork(3)`. If a test sub-routine is called from several places, when an assertion inside it fails, it can be hard to tell which invocation of the sub-routine the failure is -from. +from. You can alleviate this problem using extra logging or custom failure messages, but that usually clutters up your tests. A better solution is to use the `SCOPED_TRACE` macro or the `ScopedTrace` utility: @@ -1174,15 +1174,15 @@ will output XML like this: > 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. -> If it's called outside of a test but between a test case's -> `SetUpTestCase()` and `TearDownTestCase()` methods, it will be attributed -> to the XML element for the test case. If it's called outside of all test -> cases (e.g. in a test environment), it will be attributed to the top-level +> If it's called outside of a test but between a test suite's +> `SetUpTestSuite()` and `TearDownTestSuite()` methods, it will be attributed +> to the XML element for the test suite. If it's called outside of all test +> suites (e.g. in a test environment), it will be attributed to the top-level > XML element. **Availability**: Linux, Windows, Mac. -## Sharing Resources Between Tests in the Same Test Case +## Sharing Resources Between Tests in the Same Test Suite googletest creates a new test fixture object for each test in order to make tests independent and easier to debug. However, sometimes tests use resources @@ -1191,20 +1191,20 @@ expensive. If the tests don't change the resource, there's no harm in their sharing a single resource copy. So, in addition to per-test set-up/tear-down, googletest -also supports per-test-case set-up/tear-down. To use it: +also supports per-test-suite set-up/tear-down. To use it: 1. In your test fixture class (say `FooTest` ), declare as `static` some member variables to hold the shared resources. 1. Outside your test fixture class (typically just below it), define those member variables, optionally giving them initial values. -1. In the same test fixture class, define a `static void SetUpTestCase()` - function (remember not to spell it as **`SetupTestCase`** with a small `u`!) - to set up the shared resources and a `static void TearDownTestCase()` +1. In the same test fixture class, define a `static void SetUpTestSuite()` + function (remember not to spell it as **`SetUpTestSuite`** with a small `u`!) + to set up the shared resources and a `static void TearDownTestSuite()` function to tear them down. -That's it! googletest automatically calls `SetUpTestCase()` before running the -*first test* in the `FooTest` test case (i.e. before creating the first -`FooTest` object), and calls `TearDownTestCase()` after running the *last test* +That's it! googletest automatically calls `SetUpTestSuite()` before running the +*first test* in the `FooTest` test suite (i.e. before creating the first +`FooTest` object), and calls `TearDownTestSuite()` after running the *last test* in it (i.e. after deleting the last `FooTest` object). In between, the tests can use the shared resources. @@ -1213,22 +1213,22 @@ preceding or following another. Also, the tests must either not modify the state of any shared resource, or, if they do modify the state, they must restore the state to its original value before passing control to the next test. -Here's an example of per-test-case set-up and tear-down: +Here's an example of per-test-suite set-up and tear-down: ```c++ class FooTest : public ::testing::Test { protected: - // Per-test-case set-up. - // Called before the first test in this test case. + // Per-test-suite set-up. + // Called before the first test in this test suite. // Can be omitted if not needed. - static void SetUpTestCase() { + static void SetUpTestSuite() { shared_resource_ = new ...; } - // Per-test-case tear-down. - // Called after the last test in this test case. + // Per-test-suite tear-down. + // Called after the last test in this test suite. // Can be omitted if not needed. - static void TearDownTestCase() { + static void TearDownTestSuite() { delete shared_resource_; shared_resource_ = NULL; } @@ -1254,7 +1254,7 @@ TEST_F(FooTest, Test2) { } ``` -NOTE: Though the above code declares `SetUpTestCase()` protected, it may +NOTE: Though the above code declares `SetUpTestSuite()` protected, it may sometimes be necessary to declare it public, such as when using it with `TEST_P`. @@ -1262,7 +1262,7 @@ sometimes be necessary to declare it public, such as when using it with ## Global Set-Up and Tear-Down -Just as you can do set-up and tear-down at the test level and the test case +Just as you can do set-up and tear-down at the test level and the test suite level, you can also do it at the test program level. Here's how. First, you subclass the `::testing::Environment` class to define a test @@ -1341,7 +1341,7 @@ both `::testing::Test` and `::testing::WithParamInterface`. `T` can be any copyable type. If it's a raw pointer, you are responsible for managing the lifespan of the pointed values. -NOTE: If your test fixture defines `SetUpTestCase()` or `TearDownTestCase()` +NOTE: If your test fixture defines `SetUpTestSuite()` or `TearDownTestSuite()` they must be declared **public** rather than **protected** in order to use `TEST_P`. @@ -1380,7 +1380,7 @@ TEST_P(FooTest, HasBlahBlah) { } ``` -Finally, you can use `INSTANTIATE_TEST_CASE_P` to instantiate the test case with +Finally, you can use `INSTANTIATE_TEST_SUITE_P` to instantiate the test suite with any set of parameters you want. googletest defines a number of functions for generating test parameters. They return what we call (surprise!) *parameter generators*. Here is a summary of them, which are all in the `testing` @@ -1396,11 +1396,11 @@ namespace: For more details, see the comments at the definitions of these functions. -The following statement will instantiate tests from the `FooTest` test case each +The following statement will instantiate tests from the `FooTest` test suite each with parameter values `"meeny"`, `"miny"`, and `"moe"`. ```c++ -INSTANTIATE_TEST_CASE_P(InstantiationName, +INSTANTIATE_TEST_SUITE_P(InstantiationName, FooTest, ::testing::Values("meeny", "miny", "moe")); ``` @@ -1409,11 +1409,11 @@ NOTE: The code above must be placed at global or namespace scope, not at function scope. NOTE: Don't forget this step! If you do your test will silently pass, but none -of its cases will ever run! +of its suites will ever run! To distinguish different instances of the pattern (yes, you can instantiate it -more than once), the first argument to `INSTANTIATE_TEST_CASE_P` is a prefix -that will be added to the actual test case name. Remember to pick unique +more than once), the first argument to `INSTANTIATE_TEST_SUITE_P` 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: @@ -1431,7 +1431,7 @@ parameter values `"cat"` and `"dog"`: ```c++ const char* pets[] = {"cat", "dog"}; -INSTANTIATE_TEST_CASE_P(AnotherInstantiationName, FooTest, +INSTANTIATE_TEST_SUITE_P(AnotherInstantiationName, FooTest, ::testing::ValuesIn(pets)); ``` @@ -1442,9 +1442,9 @@ The tests from the instantiation above will have these names: * `AnotherInstantiationName/FooTest.HasBlahBlah/0` for `"cat"` * `AnotherInstantiationName/FooTest.HasBlahBlah/1` for `"dog"` -Please note that `INSTANTIATE_TEST_CASE_P` will instantiate *all* tests in the -given test case, whether their definitions come before or *after* the -`INSTANTIATE_TEST_CASE_P` statement. +Please note that `INSTANTIATE_TEST_SUITE_P` will instantiate *all* tests in the +given test suite, whether their definitions come before or *after* the +`INSTANTIATE_TEST_SUITE_P` statement. You can see sample7_unittest.cc and sample8_unittest.cc for more examples. @@ -1470,13 +1470,13 @@ To define abstract tests, you should organize your code like this: `foo_param_test.h`. Think of this as *implementing* your abstract tests. Once they are defined, you can instantiate them by including `foo_param_test.h`, -invoking `INSTANTIATE_TEST_CASE_P()`, and depending on the library target that -contains `foo_param_test.cc`. You can instantiate the same abstract test case +invoking `INSTANTIATE_TEST_SUITE_P()`, and depending on the library target that +contains `foo_param_test.cc`. You can instantiate the same abstract test suite multiple times, possibly in different source files. ### Specifying Names for Value-Parameterized Test Parameters -The optional last argument to `INSTANTIATE_TEST_CASE_P()` allows the user to +The optional last argument to `INSTANTIATE_TEST_SUITE_P()` allows the user to specify a function or functor that generates custom test name suffixes based on the test parameters. The function should accept one argument of type `testing::TestParamInfo`, and return `std::string`. @@ -1487,17 +1487,17 @@ returns the value of `testing::PrintToString(GetParam())`. It does not work for NOTE: test names must be non-empty, unique, and may only contain ASCII alphanumeric characters. In particular, they [should not contain -underscores](https://github.com/google/googletest/blob/master/googletest/docs/faq.md#why-should-test-case-names-and-test-names-not-contain-underscore). +underscores](https://github.com/google/googletest/blob/master/googletest/docs/faq.md#why-should-test-suite-names-and-test-names-not-contain-underscore). ```c++ -class MyTestCase : public testing::TestWithParam {}; +class MyTestsuite : public testing::TestWithParam {}; -TEST_P(MyTestCase, MyTest) +TEST_P(MyTestsuite, MyTest) { std::cout << "Example Test Param: " << GetParam() << std::endl; } -INSTANTIATE_TEST_CASE_P(MyGroup, MyTestCase, testing::Range(0, 10), +INSTANTIATE_TEST_SUITE_P(MyGroup, MyTestsuite, testing::Range(0, 10), testing::PrintToStringParamName()); ``` @@ -1532,20 +1532,20 @@ class FooTest : public ::testing::Test { }; ``` -Next, associate a list of types with the test case, which will be repeated for +Next, associate a list of types with the test suite, which will be repeated for each type in the list: ```c++ using MyTypes = ::testing::Types; -TYPED_TEST_CASE(FooTest, MyTypes); +TYPED_TEST_SUITE(FooTest, MyTypes); ``` -The type alias (`using` or `typedef`) is necessary for the `TYPED_TEST_CASE` +The type alias (`using` or `typedef`) is necessary for the `TYPED_TEST_SUITE` macro to parse correctly. Otherwise the compiler will think that each comma in the type list introduces a new macro argument. Then, use `TYPED_TEST()` instead of `TEST_F()` to define a typed test for this -test case. You can repeat this as many times as you want: +test suite. You can repeat this as many times as you want: ```c++ TYPED_TEST(FooTest, DoesBlah) { @@ -1596,10 +1596,10 @@ class FooTest : public ::testing::Test { }; ``` -Next, declare that you will define a type-parameterized test case: +Next, declare that you will define a type-parameterized test suite: ```c++ -TYPED_TEST_CASE_P(FooTest); +TYPED_TEST_SUITE_P(FooTest); ``` Then, use `TYPED_TEST_P()` to define a type-parameterized test. You can repeat @@ -1616,12 +1616,12 @@ TYPED_TEST_P(FooTest, HasPropertyA) { ... } ``` Now the tricky part: you need to register all test patterns using the -`REGISTER_TYPED_TEST_CASE_P` macro before you can instantiate them. The first -argument of the macro is the test case name; the rest are the names of the tests -in this test case: +`REGISTER_TYPED_TEST_SUITE_P` macro before you can instantiate them. The first +argument of the macro is the test suite name; the rest are the names of the tests +in this test suite: ```c++ -REGISTER_TYPED_TEST_CASE_P(FooTest, +REGISTER_TYPED_TEST_SUITE_P(FooTest, DoesBlah, HasPropertyA); ``` @@ -1631,18 +1631,18 @@ source files and instantiate it multiple times. ```c++ typedef ::testing::Types MyTypes; -INSTANTIATE_TYPED_TEST_CASE_P(My, FooTest, MyTypes); +INSTANTIATE_TYPED_TEST_SUITE_P(My, FooTest, MyTypes); ``` To distinguish different instances of the pattern, the first argument to the -`INSTANTIATE_TYPED_TEST_CASE_P` macro is a prefix that will be added to the -actual test case name. Remember to pick unique prefixes for different instances. +`INSTANTIATE_TYPED_TEST_SUITE_P` macro is a prefix that will be added to the +actual test suite name. Remember to pick unique prefixes for different instances. In the special case where the type list contains only one type, you can write that type directly without `::testing::Types<...>`, like this: ```c++ -INSTANTIATE_TYPED_TEST_CASE_P(My, FooTest, int); +INSTANTIATE_TYPED_TEST_SUITE_P(My, FooTest, int); ``` You can see `sample6_unittest.cc` for a complete example. @@ -1704,7 +1704,7 @@ To test them, we use the following special techniques: this line in the class body: ```c++ - FRIEND_TEST(TestCaseName, TestName); + FRIEND_TEST(TestsuiteName, TestName); ``` For example, @@ -1826,11 +1826,11 @@ namespace testing { class TestInfo { public: - // Returns the test case name and the test name, respectively. + // Returns the test suite name and the test name, respectively. // // Do NOT delete or free the return value - it's managed by the // TestInfo class. - const char* test_case_name() const; + const char* test_suite_name() const; const char* name() const; }; @@ -1848,14 +1848,14 @@ To obtain a `TestInfo` object for the currently running test, call - printf("We are in test %s of test case %s.\n", + printf("We are in test %s of test suite %s.\n", test_info->name(), - test_info->test_case_name()); + test_info->test_suite_name()); ``` `current_test_info()` returns a null pointer if no test is running. In -particular, you cannot find the test case name in `TestCaseSetUp()`, -`TestCaseTearDown()` (where you know the test case name implicitly), or +particular, you cannot find the test suite name in `TestsuiteSetUp()`, +`TestsuiteTearDown()` (where you know the test suite name implicitly), or functions called from them. **Availability**: Linux, Windows, Mac. @@ -1864,7 +1864,7 @@ functions called from them. googletest provides an **event listener API** to let you receive notifications about the progress of a test program and test failures. The events you can -listen to include the start and end of the test program, a test case, or a test +listen to include the start and end of the test program, a test suite, or a test method, among others. You may use this API to augment or replace the standard console output, replace the XML output, or provide a completely different form of output, such as a GUI or a database. You can also use test events as @@ -1885,7 +1885,7 @@ When an event is fired, its context is passed to the handler function as an argument. The following argument types are used: * UnitTest reflects the state of the entire test program, -* TestCase has information about a test case, which can contain one or more +* Testsuite has information about a test suite, which can contain one or more tests, * TestInfo contains the state of a test, and * TestPartResult represents the result of a test assertion. @@ -1900,7 +1900,7 @@ Here's an example: // Called before a test starts. virtual void OnTestStart(const ::testing::TestInfo& test_info) { printf("*** Test %s.%s starting.\n", - test_info.test_case_name(), test_info.name()); + test_info.test_suite_name(), test_info.name()); } // Called after a failed assertion or a SUCCESS(). @@ -1915,7 +1915,7 @@ Here's an example: // Called after a test ends. virtual void OnTestEnd(const ::testing::TestInfo& test_info) { printf("*** Test %s.%s ending.\n", - test_info.test_case_name(), test_info.name()); + test_info.test_suite_name(), test_info.name()); } }; ``` @@ -2002,10 +2002,10 @@ running them so that a filter may be applied if needed. Including the flag format: ```none -TestCase1. +Testsuite1. TestName1 TestName2 -TestCase2. +Testsuite2. TestName ``` @@ -2020,7 +2020,7 @@ By default, a googletest program runs all tests the user has defined. Sometimes, you want to run only a subset of the tests (e.g. for debugging or quickly verifying a change). If you set the `GTEST_FILTER` environment variable or the `--gtest_filter` flag to a filter string, googletest will only run the tests -whose full names (in the form of `TestCaseName.TestName`) match the filter. +whose full names (in the form of `TestsuiteName.TestName`) match the filter. The format of a filter is a '`:`'-separated list of wildcard patterns (called the *positive patterns*) optionally followed by a '`-`' and another @@ -2038,17 +2038,17 @@ For example: * `./foo_test` Has no flag, and thus runs all its tests. * `./foo_test --gtest_filter=*` Also runs everything, due to the single match-everything `*` value. -* `./foo_test --gtest_filter=FooTest.*` Runs everything in test case `FooTest` +* `./foo_test --gtest_filter=FooTest.*` Runs everything in test suite `FooTest` . * `./foo_test --gtest_filter=*Null*:*Constructor*` Runs any test whose full name contains either `"Null"` or `"Constructor"` . * `./foo_test --gtest_filter=-*DeathTest.*` Runs all non-death tests. * `./foo_test --gtest_filter=FooTest.*-FooTest.Bar` Runs everything in test - case `FooTest` except `FooTest.Bar`. + suite `FooTest` except `FooTest.Bar`. * `./foo_test --gtest_filter=FooTest.*:BarTest.*-FooTest.Bar:BarTest.Foo` Runs - everything in test case `FooTest` except `FooTest.Bar` and everything in - test case `BarTest` except `BarTest.Foo`. - + everything in test suite `FooTest` except `FooTest.Bar` and everything in + test suite `BarTest` except `BarTest.Foo`. + #### Temporarily Disabling Tests If you have a broken test that you cannot fix right away, you can add the @@ -2056,9 +2056,9 @@ If you have a broken test that you cannot fix right away, you can add the better than commenting out the code or using `#if 0`, as disabled tests are still compiled (and thus won't rot). -If you need to disable all tests in a test case, you can either add `DISABLED_` +If you need to disable all tests in a test suite, you can either add `DISABLED_` to the front of the name of each test, or alternatively add it to the front of -the test case name. +the test suite name. For example, the following tests won't be run by googletest, even though they will still be compiled: @@ -2165,7 +2165,7 @@ important information: ... some error messages ...
[ FAILED ] BarTest.ReturnsTrueOnSuccess
...
-[==========] 30 tests from 14 test cases ran.
+[==========] 30 tests from 14 test suites ran.
[ PASSED ] 28 tests.
[ FAILED ] 2 tests, listed below:
[ FAILED ] BarTest.ReturnsTrueOnSuccess
@@ -2227,7 +2227,7 @@ apply to googletest tests, as shown here: ```xml - + @@ -2238,7 +2238,7 @@ apply to googletest tests, as shown here: ``` * The root `` element corresponds to the entire test program. -* `` elements correspond to googletest test cases. +* `` elements correspond to googletest test suites. * `` elements correspond to googletest test functions. For instance, the following program @@ -2272,10 +2272,10 @@ could generate this report: Things to note: * The `tests` attribute of a `` or `` element tells how - many test functions the googletest program or test case contains, while the + many test functions the googletest program or test suite contains, while the `failures` attribute tells how many of them failed. -* The `time` attribute expresses the duration of the test, test case, or +* The `time` attribute expresses the duration of the test, test suite, or entire test program in seconds. * The `timestamp` attribute records the local date and time of the test @@ -2302,7 +2302,7 @@ The report format conforms to the following JSON Schema: "$schema": "http://json-schema.org/schema#", "type": "object", "definitions": { - "TestCase": { + "Testsuite": { "type": "object", "properties": { "name": { "type": "string" }, @@ -2358,7 +2358,7 @@ The report format conforms to the following JSON Schema: "testsuites": { "type": "array", "items": { - "$ref": "#/definitions/TestCase" + "$ref": "#/definitions/Testsuite" } } } @@ -2384,7 +2384,7 @@ message UnitTest { google.protobuf.Timestamp timestamp = 5; google.protobuf.Duration time = 6; string name = 7; - repeated TestCase testsuites = 8; + repeated Testsuite testsuites = 8; } message TestCase { diff --git a/googletest/docs/faq.md b/googletest/docs/faq.md index 54584548..d6ae53c9 100644 --- a/googletest/docs/faq.md +++ b/googletest/docs/faq.md @@ -1,7 +1,7 @@ # Googletest FAQ -## Why should test case names and test names not contain underscore? +## Why should test suite names and test names not contain underscore? Underscore (`_`) is special, as C++ reserves the following to be used by the compiler and the standard library: @@ -14,26 +14,26 @@ User code is *prohibited* from using such identifiers. Now let's look at what this means for `TEST` and `TEST_F`. -Currently `TEST(TestCaseName, TestName)` generates a class named -`TestCaseName_TestName_Test`. What happens if `TestCaseName` or `TestName` +Currently `TEST(TestSuiteName, TestName)` generates a class named +`TestSuiteName_TestName_Test`. What happens if `TestSuiteName` or `TestName` contains `_`? -1. If `TestCaseName` starts with an `_` followed by an upper-case letter (say, +1. If `TestSuiteName` starts with an `_` followed by an upper-case letter (say, `_Foo`), we end up with `_Foo_TestName_Test`, which is reserved and thus invalid. -1. If `TestCaseName` ends with an `_` (say, `Foo_`), we get +1. If `TestSuiteName` ends with an `_` (say, `Foo_`), we get `Foo__TestName_Test`, which is invalid. 1. If `TestName` starts with an `_` (say, `_Bar`), we get - `TestCaseName__Bar_Test`, which is invalid. + `TestSuiteName__Bar_Test`, which is invalid. 1. If `TestName` ends with an `_` (say, `Bar_`), we get - `TestCaseName_Bar__Test`, which is invalid. + `TestSuiteName_Bar__Test`, which is invalid. -So clearly `TestCaseName` and `TestName` cannot start or end with `_` (Actually, -`TestCaseName` can start with `_` -- as long as the `_` isn't followed by an +So clearly `TestSuiteName` and `TestName` cannot start or end with `_` (Actually, +`TestSuiteName` can start with `_` -- as long as the `_` isn't followed by an upper-case letter. But that's getting complicated. So for simplicity we just say that it cannot start with `_`.). -It may seem fine for `TestCaseName` and `TestName` to contain `_` in the middle. +It may seem fine for `TestSuiteName` and `TestName` to contain `_` in the middle. However, consider this: ```c++ @@ -44,7 +44,7 @@ TEST(Time_Flies, Like_An_Arrow) { ... } Now, the two `TEST`s will both generate the same class (`Time_Flies_Like_An_Arrow_Test`). That's not good. -So for simplicity, we just ask the users to avoid `_` in `TestCaseName` and +So for simplicity, we just ask the users to avoid `_` in `TestSuiteName` and `TestName`. The rule is more constraining than necessary, but it's simple and easy to remember. It also gives googletest some wiggle room in case its implementation needs to change in the future. @@ -472,7 +472,7 @@ switch to `EXPECT_*()` if that works. This C++ is case-sensitive. Did you spell it as `Setup()`? -Similarly, sometimes people spell `SetUpTestCase()` as `SetupTestCase()` and +Similarly, sometimes people spell `SetUpTestSuite()` as `SetupTestSuite()` and wonder why it's never called. ## How do I jump to the line of a failure in Emacs directly? diff --git a/googletest/docs/primer.md b/googletest/docs/primer.md index 902e8274..6344ba33 100644 --- a/googletest/docs/primer.md +++ b/googletest/docs/primer.md @@ -61,21 +61,19 @@ The related term _Test_, as it is used in the googletest, is corresponding to the term _[Test Case](http://glossary.istqb.org/search/test%20case)_ of ISTQB and others. -The term _Test_ is commonly of broad enough sense, including ISTQB's -definition of _Test Case_, so it's not much of a problem here. But the -term _Test Case_ as used in Google Test is of contradictory sense and thus confusing. +The term _Test_ is commonly of broad enough sense, including ISTQB's definition +of _Test Case_, so it's not much of a problem here. But the term _Test Case_ as +was used in Google Test is of contradictory sense and thus confusing. -Unfortunately replacing the term _Test Case_ by _Test Suite_ throughout the -googletest is not easy without breaking dependent projects, as `TestCase` is -part of the public API at various places. +googletest recently started replacing the term _Test Case_ by _Test Suite_ The +preferred API is TestSuite*. The older TestCase* API is being slowly deprecated +and refactored away -So for the time being, please be aware of the different definitions of -the terms: +So please be aware of the different definitions of the terms: Meaning | googletest Term | [ISTQB](http://www.istqb.org/) Term :----------------------------------------------------------------------------------- | :--------------------------------------------------------------------------------------------------------- | :---------------------------------- Exercise a particular program path with specific input values and verify the results | [TEST()](#simple-tests) | [Test Case](http://glossary.istqb.org/search/test%20case) -A set of several tests related to one component | [TestCase](#basic-concepts) | [TestSuite](http://glossary.istqb.org/search/test%20suite) ## Basic Concepts @@ -252,7 +250,7 @@ To create a test: entire test fails. Otherwise, it succeeds. ```c++ -TEST(TestCaseName, TestName) { +TEST(TestSuiteName, TestName) { ... test body ... } ``` @@ -324,7 +322,7 @@ When using a fixture, use `TEST_F()` instead of `TEST()` as it allows you to access objects and subroutines in the test fixture: ```c++ -TEST_F(TestCaseName, TestName) { +TEST_F(TestSuiteName, TestName) { ... test body ... } ``` -- cgit v1.2.3