diff options
author | Brad Messer <messerb5467@gmail.com> | 2022-03-18 16:32:39 (GMT) |
---|---|---|
committer | GitHub <noreply@github.com> | 2022-03-18 16:32:39 (GMT) |
commit | 9e712372214d75bb30ec2847a44bf124d48096f3 (patch) | |
tree | fd19cd5a8192428a0826307d76d6b57c5cda526b | |
parent | 794da715d409aa8d5b092a1692d7802624066ab3 (diff) | |
parent | b007c54f2944e193ac44fba1bc997cb65826a0b9 (diff) | |
download | googletest-9e712372214d75bb30ec2847a44bf124d48096f3.zip googletest-9e712372214d75bb30ec2847a44bf124d48096f3.tar.gz googletest-9e712372214d75bb30ec2847a44bf124d48096f3.tar.bz2 |
Merge branch 'main' into promote-inclusive-behaviorrefs/pull/3779/head
135 files changed, 5943 insertions, 7135 deletions
diff --git a/CONTRIBUTORS b/CONTRIBUTORS index d9bc587..77397a5 100644 --- a/CONTRIBUTORS +++ b/CONTRIBUTORS @@ -56,6 +56,7 @@ Russ Rufer <russ@pentad.com> Sean Mcafee <eefacm@gmail.com> Sigurður Ásgeirsson <siggi@google.com> Sverre Sundsdal <sundsdal@gmail.com> +Szymon Sobik <sobik.szymon@gmail.com> Takeshi Yoshino <tyoshino@google.com> Tracy Bialik <tracy@pentad.com> Vadim Berman <vadimb@google.com> diff --git a/docs/advanced.md b/docs/advanced.md index f2f8854..7d81162 100644 --- a/docs/advanced.md +++ b/docs/advanced.md @@ -839,7 +839,7 @@ will output XML like this: ```xml ... - <testcase name="MinAndMaxWidgets" status="run" time="0.006" classname="WidgetUsageTest" MaximumWidgets="12" MinimumWidgets="9" /> + <testcase name="MinAndMaxWidgets" file="test.cpp" line="1" status="run" time="0.006" classname="WidgetUsageTest" MaximumWidgets="12" MinimumWidgets="9" /> ... ``` @@ -2082,15 +2082,15 @@ could generate this report: <?xml version="1.0" encoding="UTF-8"?> <testsuites tests="3" failures="1" errors="0" time="0.035" timestamp="2011-10-31T18:52:42" name="AllTests"> <testsuite name="MathTest" tests="2" failures="1" errors="0" time="0.015"> - <testcase name="Addition" status="run" time="0.007" classname=""> + <testcase name="Addition" file="test.cpp" line="1" status="run" time="0.007" classname=""> <failure message="Value of: add(1, 1)
 Actual: 3
Expected: 2" type="">...</failure> <failure message="Value of: add(1, -1)
 Actual: 1
Expected: 0" type="">...</failure> </testcase> - <testcase name="Subtraction" status="run" time="0.005" classname=""> + <testcase name="Subtraction" file="test.cpp" line="2" status="run" time="0.005" classname=""> </testcase> </testsuite> <testsuite name="LogicTest" tests="1" failures="0" errors="0" time="0.005"> - <testcase name="NonContradiction" status="run" time="0.005" classname=""> + <testcase name="NonContradiction" file="test.cpp" line="3" status="run" time="0.005" classname=""> </testcase> </testsuite> </testsuites> @@ -2108,6 +2108,9 @@ Things to note: * The `timestamp` attribute records the local date and time of the test execution. +* The `file` and `line` attributes record the source file location, where the + test was defined. + * Each `<failure>` element corresponds to a single failed googletest assertion. @@ -2147,6 +2150,8 @@ The report format conforms to the following JSON Schema: "type": "object", "properties": { "name": { "type": "string" }, + "file": { "type": "string" }, + "line": { "type": "integer" }, "status": { "type": "string", "enum": ["RUN", "NOTRUN"] @@ -2224,6 +2229,8 @@ message TestCase { message TestInfo { string name = 1; + string file = 6; + int32 line = 7; enum Status { RUN = 0; NOTRUN = 1; @@ -2267,6 +2274,8 @@ could generate this report: "testsuite": [ { "name": "Addition", + "file": "test.cpp", + "line": 1, "status": "RUN", "time": "0.007s", "classname": "", @@ -2283,6 +2292,8 @@ could generate this report: }, { "name": "Subtraction", + "file": "test.cpp", + "line": 2, "status": "RUN", "time": "0.005s", "classname": "" @@ -2298,6 +2309,8 @@ could generate this report: "testsuite": [ { "name": "NonContradiction", + "file": "test.cpp", + "line": 3, "status": "RUN", "time": "0.005s", "classname": "" diff --git a/docs/reference/testing.md b/docs/reference/testing.md index 554d6c9..dc47942 100644 --- a/docs/reference/testing.md +++ b/docs/reference/testing.md @@ -518,8 +518,8 @@ Logs a property for the current test, test suite, or entire invocation of the test program. Only the last value for a given key is logged. The key must be a valid XML attribute name, and cannot conflict with the ones -already used by GoogleTest (`name`, `status`, `time`, `classname`, `type_param`, -and `value_param`). +already used by GoogleTest (`name`, `file`, `line`, `status`, `time`, +`classname`, `type_param`, and `value_param`). `RecordProperty` is `public static` so it can be called from utility functions that are not members of the test fixture. diff --git a/googlemock/include/gmock/gmock-actions.h b/googlemock/include/gmock/gmock-actions.h index 035b66b..26272e9 100644 --- a/googlemock/include/gmock/gmock-actions.h +++ b/googlemock/include/gmock/gmock-actions.h @@ -131,7 +131,7 @@ #define GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_ACTIONS_H_ #ifndef _WIN32_WCE -# include <errno.h> +#include <errno.h> #endif #include <algorithm> @@ -147,8 +147,8 @@ #include "gmock/internal/gmock-pp.h" #ifdef _MSC_VER -# pragma warning(push) -# pragma warning(disable:4100) +#pragma warning(push) +#pragma warning(disable : 4100) #endif namespace testing { @@ -196,9 +196,7 @@ class BuiltInDefaultValue { public: // This function returns true if and only if type T has a built-in default // value. - static bool Exists() { - return ::std::is_default_constructible<T>::value; - } + static bool Exists() { return ::std::is_default_constructible<T>::value; } static T Get() { return BuiltInDefaultValueGetter< @@ -227,11 +225,11 @@ class BuiltInDefaultValue<T*> { // The following specializations define the default values for // specific types we care about. #define GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(type, value) \ - template <> \ - class BuiltInDefaultValue<type> { \ - public: \ - static bool Exists() { return true; } \ - static type Get() { return value; } \ + template <> \ + class BuiltInDefaultValue<type> { \ + public: \ + static bool Exists() { return true; } \ + static type Get() { return value; } \ } GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(void, ); // NOLINT @@ -255,10 +253,10 @@ GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(unsigned short, 0U); // NOLINT GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(signed short, 0); // NOLINT GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(unsigned int, 0U); GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(signed int, 0); -GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(unsigned long, 0UL); // NOLINT -GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(signed long, 0L); // NOLINT +GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(unsigned long, 0UL); // NOLINT +GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(signed long, 0L); // NOLINT GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(unsigned long long, 0); // NOLINT -GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(signed long long, 0); // NOLINT +GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(signed long long, 0); // NOLINT GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(float, 0); GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(double, 0); @@ -839,7 +837,7 @@ class ReturnRoundRobinAction { template <typename... Args> T operator()(Args&&...) const { - return state_->Next(); + return state_->Next(); } private: @@ -862,7 +860,9 @@ class DoDefaultAction { // This template type conversion operator allows DoDefault() to be // used in any function. template <typename F> - operator Action<F>() const { return Action<F>(); } // NOLINT + operator Action<F>() const { + return Action<F>(); + } // NOLINT }; // Implements the Assign action to set a given pointer referent to a @@ -890,8 +890,7 @@ template <typename T> class SetErrnoAndReturnAction { public: SetErrnoAndReturnAction(int errno_value, T result) - : errno_(errno_value), - result_(result) {} + : errno_(errno_value), result_(result) {} template <typename Result, typename ArgumentTuple> Result Perform(const ArgumentTuple& /* args */) const { errno = errno_; @@ -1002,8 +1001,8 @@ class IgnoreResultAction { private: // Type OriginalFunction is the same as F except that its return // type is IgnoredValue. - typedef typename internal::Function<F>::MakeResultIgnoredValue - OriginalFunction; + typedef + typename internal::Function<F>::MakeResultIgnoredValue OriginalFunction; const Action<OriginalFunction> action_; }; @@ -1020,12 +1019,12 @@ struct WithArgsAction { template <typename R, typename... Args> operator Action<R(Args...)>() const { // NOLINT using TupleType = std::tuple<Args...>; - Action<R(typename std::tuple_element<I, TupleType>::type...)> - converted(action); + Action<R(typename std::tuple_element<I, TupleType>::type...)> converted( + action); return [converted](Args... args) -> R { return converted.Perform(std::forward_as_tuple( - std::get<I>(std::forward_as_tuple(std::forward<Args>(args)...))...)); + std::get<I>(std::forward_as_tuple(std::forward<Args>(args)...))...)); }; } }; @@ -1212,8 +1211,8 @@ internal::DoAllAction<typename std::decay<Action>::type...> DoAll( // multiple arguments. For convenience, we also provide // WithArgs<k>(an_action) (defined below) as a synonym. template <size_t k, typename InnerAction> -internal::WithArgsAction<typename std::decay<InnerAction>::type, k> -WithArg(InnerAction&& action) { +internal::WithArgsAction<typename std::decay<InnerAction>::type, k> WithArg( + InnerAction&& action) { return {std::forward<InnerAction>(action)}; } @@ -1232,8 +1231,8 @@ WithArgs(InnerAction&& action) { // argument. In other words, it adapts an action accepting no // argument to one that accepts (and ignores) arguments. template <typename InnerAction> -internal::WithArgsAction<typename std::decay<InnerAction>::type> -WithoutArgs(InnerAction&& action) { +internal::WithArgsAction<typename std::decay<InnerAction>::type> WithoutArgs( + InnerAction&& action) { return {std::forward<InnerAction>(action)}; } @@ -1319,7 +1318,7 @@ internal::SetArgumentPointeeAction<N, T> SetArgumentPointee(T value) { // Creates an action that sets a pointer referent to a given value. template <typename T1, typename T2> -PolymorphicAction<internal::AssignAction<T1, T2> > Assign(T1* ptr, T2 val) { +PolymorphicAction<internal::AssignAction<T1, T2>> Assign(T1* ptr, T2 val) { return MakePolymorphicAction(internal::AssignAction<T1, T2>(ptr, val)); } @@ -1327,8 +1326,8 @@ PolymorphicAction<internal::AssignAction<T1, T2> > Assign(T1* ptr, T2 val) { // Creates an action that sets errno and returns the appropriate error. template <typename T> -PolymorphicAction<internal::SetErrnoAndReturnAction<T> > -SetErrnoAndReturn(int errval, T result) { +PolymorphicAction<internal::SetErrnoAndReturnAction<T>> SetErrnoAndReturn( + int errval, T result) { return MakePolymorphicAction( internal::SetErrnoAndReturnAction<T>(errval, result)); } @@ -1482,7 +1481,8 @@ struct ExcessiveArg {}; // Builds an implementation of an Action<> for some particular signature, using // a class defined by an ACTION* macro. -template <typename F, typename Impl> struct ActionImpl; +template <typename F, typename Impl> +struct ActionImpl; template <typename Impl> struct ImplBase { @@ -1502,7 +1502,7 @@ struct ActionImpl<R(Args...), Impl> : ImplBase<Impl>::type { using args_type = std::tuple<Args...>; ActionImpl() = default; // Only defined if appropriate for Base. - explicit ActionImpl(std::shared_ptr<Impl> impl) : Base{std::move(impl)} { } + explicit ActionImpl(std::shared_ptr<Impl> impl) : Base{std::move(impl)} {} R operator()(Args&&... arg) const { static constexpr size_t kMaxArgs = @@ -1521,12 +1521,14 @@ struct ActionImpl<R(Args...), Impl> : ImplBase<Impl>::type { // args_type get passed, followed by a dummy of unspecified type for the // remainder up to 10 explicit args. static constexpr ExcessiveArg kExcessArg{}; - return static_cast<const Impl&>(*this).template gmock_PerformImpl< - /*function_type=*/function_type, /*return_type=*/R, - /*args_type=*/args_type, - /*argN_type=*/typename std::tuple_element<arg_id, args_type>::type...>( - /*args=*/args, std::get<arg_id>(args)..., - ((void)excess_id, kExcessArg)...); + return static_cast<const Impl&>(*this) + .template gmock_PerformImpl< + /*function_type=*/function_type, /*return_type=*/R, + /*args_type=*/args_type, + /*argN_type=*/ + typename std::tuple_element<arg_id, args_type>::type...>( + /*args=*/args, std::get<arg_id>(args)..., + ((void)excess_id, kExcessArg)...); } }; @@ -1545,7 +1547,7 @@ template <typename F, typename Impl> #define GMOCK_INTERNAL_ARG_UNUSED(i, data, el) \ , const arg##i##_type& arg##i GTEST_ATTRIBUTE_UNUSED_ -#define GMOCK_ACTION_ARG_TYPES_AND_NAMES_UNUSED_ \ +#define GMOCK_ACTION_ARG_TYPES_AND_NAMES_UNUSED_ \ const args_type& args GTEST_ATTRIBUTE_UNUSED_ GMOCK_PP_REPEAT( \ GMOCK_INTERNAL_ARG_UNUSED, , 10) @@ -1584,45 +1586,47 @@ template <typename F, typename Impl> #define GMOCK_ACTION_FIELD_PARAMS_(params) \ GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_FIELD_PARAM, , params) -#define GMOCK_INTERNAL_ACTION(name, full_name, params) \ - template <GMOCK_ACTION_TYPENAME_PARAMS_(params)> \ - class full_name { \ - public: \ - explicit full_name(GMOCK_ACTION_TYPE_GVALUE_PARAMS_(params)) \ - : impl_(std::make_shared<gmock_Impl>( \ - GMOCK_ACTION_GVALUE_PARAMS_(params))) { } \ - full_name(const full_name&) = default; \ - full_name(full_name&&) noexcept = default; \ - template <typename F> \ - operator ::testing::Action<F>() const { \ - return ::testing::internal::MakeAction<F>(impl_); \ - } \ - private: \ - class gmock_Impl { \ - public: \ - explicit gmock_Impl(GMOCK_ACTION_TYPE_GVALUE_PARAMS_(params)) \ - : GMOCK_ACTION_INIT_PARAMS_(params) {} \ - template <typename function_type, typename return_type, \ - typename args_type, GMOCK_ACTION_TEMPLATE_ARGS_NAMES_> \ - return_type gmock_PerformImpl(GMOCK_ACTION_ARG_TYPES_AND_NAMES_) const; \ - GMOCK_ACTION_FIELD_PARAMS_(params) \ - }; \ - std::shared_ptr<const gmock_Impl> impl_; \ - }; \ - template <GMOCK_ACTION_TYPENAME_PARAMS_(params)> \ - inline full_name<GMOCK_ACTION_TYPE_PARAMS_(params)> name( \ - GMOCK_ACTION_TYPE_GVALUE_PARAMS_(params)) GTEST_MUST_USE_RESULT_; \ - template <GMOCK_ACTION_TYPENAME_PARAMS_(params)> \ - inline full_name<GMOCK_ACTION_TYPE_PARAMS_(params)> name( \ - GMOCK_ACTION_TYPE_GVALUE_PARAMS_(params)) { \ - return full_name<GMOCK_ACTION_TYPE_PARAMS_(params)>( \ - GMOCK_ACTION_GVALUE_PARAMS_(params)); \ - } \ - template <GMOCK_ACTION_TYPENAME_PARAMS_(params)> \ - template <typename function_type, typename return_type, typename args_type, \ - GMOCK_ACTION_TEMPLATE_ARGS_NAMES_> \ - return_type full_name<GMOCK_ACTION_TYPE_PARAMS_(params)>::gmock_Impl:: \ - gmock_PerformImpl(GMOCK_ACTION_ARG_TYPES_AND_NAMES_UNUSED_) const +#define GMOCK_INTERNAL_ACTION(name, full_name, params) \ + template <GMOCK_ACTION_TYPENAME_PARAMS_(params)> \ + class full_name { \ + public: \ + explicit full_name(GMOCK_ACTION_TYPE_GVALUE_PARAMS_(params)) \ + : impl_(std::make_shared<gmock_Impl>( \ + GMOCK_ACTION_GVALUE_PARAMS_(params))) {} \ + full_name(const full_name&) = default; \ + full_name(full_name&&) noexcept = default; \ + template <typename F> \ + operator ::testing::Action<F>() const { \ + return ::testing::internal::MakeAction<F>(impl_); \ + } \ + \ + private: \ + class gmock_Impl { \ + public: \ + explicit gmock_Impl(GMOCK_ACTION_TYPE_GVALUE_PARAMS_(params)) \ + : GMOCK_ACTION_INIT_PARAMS_(params) {} \ + template <typename function_type, typename return_type, \ + typename args_type, GMOCK_ACTION_TEMPLATE_ARGS_NAMES_> \ + return_type gmock_PerformImpl(GMOCK_ACTION_ARG_TYPES_AND_NAMES_) const; \ + GMOCK_ACTION_FIELD_PARAMS_(params) \ + }; \ + std::shared_ptr<const gmock_Impl> impl_; \ + }; \ + template <GMOCK_ACTION_TYPENAME_PARAMS_(params)> \ + inline full_name<GMOCK_ACTION_TYPE_PARAMS_(params)> name( \ + GMOCK_ACTION_TYPE_GVALUE_PARAMS_(params)) GTEST_MUST_USE_RESULT_; \ + template <GMOCK_ACTION_TYPENAME_PARAMS_(params)> \ + inline full_name<GMOCK_ACTION_TYPE_PARAMS_(params)> name( \ + GMOCK_ACTION_TYPE_GVALUE_PARAMS_(params)) { \ + return full_name<GMOCK_ACTION_TYPE_PARAMS_(params)>( \ + GMOCK_ACTION_GVALUE_PARAMS_(params)); \ + } \ + template <GMOCK_ACTION_TYPENAME_PARAMS_(params)> \ + template <typename function_type, typename return_type, typename args_type, \ + GMOCK_ACTION_TEMPLATE_ARGS_NAMES_> \ + return_type \ + full_name<GMOCK_ACTION_TYPE_PARAMS_(params)>::gmock_Impl::gmock_PerformImpl( \ + GMOCK_ACTION_ARG_TYPES_AND_NAMES_UNUSED_) const } // namespace internal @@ -1630,12 +1634,13 @@ template <typename F, typename Impl> #define ACTION(name) \ class name##Action { \ public: \ - explicit name##Action() noexcept {} \ - name##Action(const name##Action&) noexcept {} \ + explicit name##Action() noexcept {} \ + name##Action(const name##Action&) noexcept {} \ template <typename F> \ operator ::testing::Action<F>() const { \ return ::testing::internal::MakeAction<F, gmock_Impl>(); \ } \ + \ private: \ class gmock_Impl { \ public: \ @@ -1684,7 +1689,7 @@ template <typename F, typename Impl> } // namespace testing #ifdef _MSC_VER -# pragma warning(pop) +#pragma warning(pop) #endif #endif // GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_ACTIONS_H_ diff --git a/googlemock/include/gmock/gmock-cardinalities.h b/googlemock/include/gmock/gmock-cardinalities.h index 48196dd..b6ab648 100644 --- a/googlemock/include/gmock/gmock-cardinalities.h +++ b/googlemock/include/gmock/gmock-cardinalities.h @@ -40,8 +40,10 @@ #define GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_CARDINALITIES_H_ #include <limits.h> + #include <memory> #include <ostream> // NOLINT + #include "gmock/internal/gmock-port.h" #include "gtest/gtest.h" @@ -116,7 +118,7 @@ class GTEST_API_ Cardinality { // cardinality, i.e. exceed the maximum number of allowed calls. bool IsOverSaturatedByCallCount(int call_count) const { return impl_->IsSaturatedByCallCount(call_count) && - !impl_->IsSatisfiedByCallCount(call_count); + !impl_->IsSatisfiedByCallCount(call_count); } // Describes self to an ostream diff --git a/googlemock/include/gmock/gmock-function-mocker.h b/googlemock/include/gmock/gmock-function-mocker.h index 2de1d41..f565d98 100644 --- a/googlemock/include/gmock/gmock-function-mocker.h +++ b/googlemock/include/gmock/gmock-function-mocker.h @@ -201,7 +201,7 @@ using internal::FunctionMocker; GMOCK_INTERNAL_A_MATCHER_ARGUMENT, _Signature, _N)); \ } \ mutable ::testing::FunctionMocker<GMOCK_PP_REMOVE_PARENS(_Signature)> \ - GMOCK_MOCKER_(_N, _Constness, _MethodName) + GMOCK_MOCKER_(_N, _Constness, _MethodName) #define GMOCK_INTERNAL_EXPAND(...) __VA_ARGS__ diff --git a/googlemock/include/gmock/gmock-more-actions.h b/googlemock/include/gmock/gmock-more-actions.h index bf85ff5..87307f0 100644 --- a/googlemock/include/gmock/gmock-more-actions.h +++ b/googlemock/include/gmock/gmock-more-actions.h @@ -129,170 +129,207 @@ // Declares the template parameters. #define GMOCK_INTERNAL_DECL_HAS_1_TEMPLATE_PARAMS(kind0, name0) kind0 name0 -#define GMOCK_INTERNAL_DECL_HAS_2_TEMPLATE_PARAMS(kind0, name0, kind1, \ - name1) kind0 name0, kind1 name1 +#define GMOCK_INTERNAL_DECL_HAS_2_TEMPLATE_PARAMS(kind0, name0, kind1, name1) \ + kind0 name0, kind1 name1 #define GMOCK_INTERNAL_DECL_HAS_3_TEMPLATE_PARAMS(kind0, name0, kind1, name1, \ - kind2, name2) kind0 name0, kind1 name1, kind2 name2 + kind2, name2) \ + kind0 name0, kind1 name1, kind2 name2 #define GMOCK_INTERNAL_DECL_HAS_4_TEMPLATE_PARAMS(kind0, name0, kind1, name1, \ - kind2, name2, kind3, name3) kind0 name0, kind1 name1, kind2 name2, \ - kind3 name3 -#define GMOCK_INTERNAL_DECL_HAS_5_TEMPLATE_PARAMS(kind0, name0, kind1, name1, \ - kind2, name2, kind3, name3, kind4, name4) kind0 name0, kind1 name1, \ - kind2 name2, kind3 name3, kind4 name4 + kind2, name2, kind3, name3) \ + kind0 name0, kind1 name1, kind2 name2, kind3 name3 +#define GMOCK_INTERNAL_DECL_HAS_5_TEMPLATE_PARAMS( \ + kind0, name0, kind1, name1, kind2, name2, kind3, name3, kind4, name4) \ + kind0 name0, kind1 name1, kind2 name2, kind3 name3, kind4 name4 #define GMOCK_INTERNAL_DECL_HAS_6_TEMPLATE_PARAMS(kind0, name0, kind1, name1, \ - kind2, name2, kind3, name3, kind4, name4, kind5, name5) kind0 name0, \ - kind1 name1, kind2 name2, kind3 name3, kind4 name4, kind5 name5 -#define GMOCK_INTERNAL_DECL_HAS_7_TEMPLATE_PARAMS(kind0, name0, kind1, name1, \ - kind2, name2, kind3, name3, kind4, name4, kind5, name5, kind6, \ - name6) kind0 name0, kind1 name1, kind2 name2, kind3 name3, kind4 name4, \ - kind5 name5, kind6 name6 -#define GMOCK_INTERNAL_DECL_HAS_8_TEMPLATE_PARAMS(kind0, name0, kind1, name1, \ - kind2, name2, kind3, name3, kind4, name4, kind5, name5, kind6, name6, \ - kind7, name7) kind0 name0, kind1 name1, kind2 name2, kind3 name3, \ - kind4 name4, kind5 name5, kind6 name6, kind7 name7 -#define GMOCK_INTERNAL_DECL_HAS_9_TEMPLATE_PARAMS(kind0, name0, kind1, name1, \ - kind2, name2, kind3, name3, kind4, name4, kind5, name5, kind6, name6, \ - kind7, name7, kind8, name8) kind0 name0, kind1 name1, kind2 name2, \ - kind3 name3, kind4 name4, kind5 name5, kind6 name6, kind7 name7, \ - kind8 name8 -#define GMOCK_INTERNAL_DECL_HAS_10_TEMPLATE_PARAMS(kind0, name0, kind1, \ - name1, kind2, name2, kind3, name3, kind4, name4, kind5, name5, kind6, \ - name6, kind7, name7, kind8, name8, kind9, name9) kind0 name0, \ - kind1 name1, kind2 name2, kind3 name3, kind4 name4, kind5 name5, \ - kind6 name6, kind7 name7, kind8 name8, kind9 name9 + kind2, name2, kind3, name3, \ + kind4, name4, kind5, name5) \ + kind0 name0, kind1 name1, kind2 name2, kind3 name3, kind4 name4, kind5 name5 +#define GMOCK_INTERNAL_DECL_HAS_7_TEMPLATE_PARAMS( \ + kind0, name0, kind1, name1, kind2, name2, kind3, name3, kind4, name4, \ + kind5, name5, kind6, name6) \ + kind0 name0, kind1 name1, kind2 name2, kind3 name3, kind4 name4, \ + kind5 name5, kind6 name6 +#define GMOCK_INTERNAL_DECL_HAS_8_TEMPLATE_PARAMS( \ + kind0, name0, kind1, name1, kind2, name2, kind3, name3, kind4, name4, \ + kind5, name5, kind6, name6, kind7, name7) \ + kind0 name0, kind1 name1, kind2 name2, kind3 name3, kind4 name4, \ + kind5 name5, kind6 name6, kind7 name7 +#define GMOCK_INTERNAL_DECL_HAS_9_TEMPLATE_PARAMS( \ + kind0, name0, kind1, name1, kind2, name2, kind3, name3, kind4, name4, \ + kind5, name5, kind6, name6, kind7, name7, kind8, name8) \ + kind0 name0, kind1 name1, kind2 name2, kind3 name3, kind4 name4, \ + kind5 name5, kind6 name6, kind7 name7, kind8 name8 +#define GMOCK_INTERNAL_DECL_HAS_10_TEMPLATE_PARAMS( \ + kind0, name0, kind1, name1, kind2, name2, kind3, name3, kind4, name4, \ + kind5, name5, kind6, name6, kind7, name7, kind8, name8, kind9, name9) \ + kind0 name0, kind1 name1, kind2 name2, kind3 name3, kind4 name4, \ + kind5 name5, kind6 name6, kind7 name7, kind8 name8, kind9 name9 // Lists the template parameters. #define GMOCK_INTERNAL_LIST_HAS_1_TEMPLATE_PARAMS(kind0, name0) name0 -#define GMOCK_INTERNAL_LIST_HAS_2_TEMPLATE_PARAMS(kind0, name0, kind1, \ - name1) name0, name1 +#define GMOCK_INTERNAL_LIST_HAS_2_TEMPLATE_PARAMS(kind0, name0, kind1, name1) \ + name0, name1 #define GMOCK_INTERNAL_LIST_HAS_3_TEMPLATE_PARAMS(kind0, name0, kind1, name1, \ - kind2, name2) name0, name1, name2 + kind2, name2) \ + name0, name1, name2 #define GMOCK_INTERNAL_LIST_HAS_4_TEMPLATE_PARAMS(kind0, name0, kind1, name1, \ - kind2, name2, kind3, name3) name0, name1, name2, name3 -#define GMOCK_INTERNAL_LIST_HAS_5_TEMPLATE_PARAMS(kind0, name0, kind1, name1, \ - kind2, name2, kind3, name3, kind4, name4) name0, name1, name2, name3, \ - name4 + kind2, name2, kind3, name3) \ + name0, name1, name2, name3 +#define GMOCK_INTERNAL_LIST_HAS_5_TEMPLATE_PARAMS( \ + kind0, name0, kind1, name1, kind2, name2, kind3, name3, kind4, name4) \ + name0, name1, name2, name3, name4 #define GMOCK_INTERNAL_LIST_HAS_6_TEMPLATE_PARAMS(kind0, name0, kind1, name1, \ - kind2, name2, kind3, name3, kind4, name4, kind5, name5) name0, name1, \ - name2, name3, name4, name5 -#define GMOCK_INTERNAL_LIST_HAS_7_TEMPLATE_PARAMS(kind0, name0, kind1, name1, \ - kind2, name2, kind3, name3, kind4, name4, kind5, name5, kind6, \ - name6) name0, name1, name2, name3, name4, name5, name6 -#define GMOCK_INTERNAL_LIST_HAS_8_TEMPLATE_PARAMS(kind0, name0, kind1, name1, \ - kind2, name2, kind3, name3, kind4, name4, kind5, name5, kind6, name6, \ - kind7, name7) name0, name1, name2, name3, name4, name5, name6, name7 -#define GMOCK_INTERNAL_LIST_HAS_9_TEMPLATE_PARAMS(kind0, name0, kind1, name1, \ - kind2, name2, kind3, name3, kind4, name4, kind5, name5, kind6, name6, \ - kind7, name7, kind8, name8) name0, name1, name2, name3, name4, name5, \ - name6, name7, name8 -#define GMOCK_INTERNAL_LIST_HAS_10_TEMPLATE_PARAMS(kind0, name0, kind1, \ - name1, kind2, name2, kind3, name3, kind4, name4, kind5, name5, kind6, \ - name6, kind7, name7, kind8, name8, kind9, name9) name0, name1, name2, \ - name3, name4, name5, name6, name7, name8, name9 + kind2, name2, kind3, name3, \ + kind4, name4, kind5, name5) \ + name0, name1, name2, name3, name4, name5 +#define GMOCK_INTERNAL_LIST_HAS_7_TEMPLATE_PARAMS( \ + kind0, name0, kind1, name1, kind2, name2, kind3, name3, kind4, name4, \ + kind5, name5, kind6, name6) \ + name0, name1, name2, name3, name4, name5, name6 +#define GMOCK_INTERNAL_LIST_HAS_8_TEMPLATE_PARAMS( \ + kind0, name0, kind1, name1, kind2, name2, kind3, name3, kind4, name4, \ + kind5, name5, kind6, name6, kind7, name7) \ + name0, name1, name2, name3, name4, name5, name6, name7 +#define GMOCK_INTERNAL_LIST_HAS_9_TEMPLATE_PARAMS( \ + kind0, name0, kind1, name1, kind2, name2, kind3, name3, kind4, name4, \ + kind5, name5, kind6, name6, kind7, name7, kind8, name8) \ + name0, name1, name2, name3, name4, name5, name6, name7, name8 +#define GMOCK_INTERNAL_LIST_HAS_10_TEMPLATE_PARAMS( \ + kind0, name0, kind1, name1, kind2, name2, kind3, name3, kind4, name4, \ + kind5, name5, kind6, name6, kind7, name7, kind8, name8, kind9, name9) \ + name0, name1, name2, name3, name4, name5, name6, name7, name8, name9 // Declares the types of value parameters. #define GMOCK_INTERNAL_DECL_TYPE_AND_0_VALUE_PARAMS() #define GMOCK_INTERNAL_DECL_TYPE_AND_1_VALUE_PARAMS(p0) , typename p0##_type -#define GMOCK_INTERNAL_DECL_TYPE_AND_2_VALUE_PARAMS(p0, p1) , \ - typename p0##_type, typename p1##_type -#define GMOCK_INTERNAL_DECL_TYPE_AND_3_VALUE_PARAMS(p0, p1, p2) , \ - typename p0##_type, typename p1##_type, typename p2##_type -#define GMOCK_INTERNAL_DECL_TYPE_AND_4_VALUE_PARAMS(p0, p1, p2, p3) , \ - typename p0##_type, typename p1##_type, typename p2##_type, \ - typename p3##_type -#define GMOCK_INTERNAL_DECL_TYPE_AND_5_VALUE_PARAMS(p0, p1, p2, p3, p4) , \ - typename p0##_type, typename p1##_type, typename p2##_type, \ - typename p3##_type, typename p4##_type -#define GMOCK_INTERNAL_DECL_TYPE_AND_6_VALUE_PARAMS(p0, p1, p2, p3, p4, p5) , \ - typename p0##_type, typename p1##_type, typename p2##_type, \ - typename p3##_type, typename p4##_type, typename p5##_type +#define GMOCK_INTERNAL_DECL_TYPE_AND_2_VALUE_PARAMS(p0, p1) \ + , typename p0##_type, typename p1##_type +#define GMOCK_INTERNAL_DECL_TYPE_AND_3_VALUE_PARAMS(p0, p1, p2) \ + , typename p0##_type, typename p1##_type, typename p2##_type +#define GMOCK_INTERNAL_DECL_TYPE_AND_4_VALUE_PARAMS(p0, p1, p2, p3) \ + , typename p0##_type, typename p1##_type, typename p2##_type, \ + typename p3##_type +#define GMOCK_INTERNAL_DECL_TYPE_AND_5_VALUE_PARAMS(p0, p1, p2, p3, p4) \ + , typename p0##_type, typename p1##_type, typename p2##_type, \ + typename p3##_type, typename p4##_type +#define GMOCK_INTERNAL_DECL_TYPE_AND_6_VALUE_PARAMS(p0, p1, p2, p3, p4, p5) \ + , typename p0##_type, typename p1##_type, typename p2##_type, \ + typename p3##_type, typename p4##_type, typename p5##_type #define GMOCK_INTERNAL_DECL_TYPE_AND_7_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, \ - p6) , typename p0##_type, typename p1##_type, typename p2##_type, \ - typename p3##_type, typename p4##_type, typename p5##_type, \ - typename p6##_type + p6) \ + , typename p0##_type, typename p1##_type, typename p2##_type, \ + typename p3##_type, typename p4##_type, typename p5##_type, \ + typename p6##_type #define GMOCK_INTERNAL_DECL_TYPE_AND_8_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, \ - p6, p7) , typename p0##_type, typename p1##_type, typename p2##_type, \ - typename p3##_type, typename p4##_type, typename p5##_type, \ - typename p6##_type, typename p7##_type + p6, p7) \ + , typename p0##_type, typename p1##_type, typename p2##_type, \ + typename p3##_type, typename p4##_type, typename p5##_type, \ + typename p6##_type, typename p7##_type #define GMOCK_INTERNAL_DECL_TYPE_AND_9_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, \ - p6, p7, p8) , typename p0##_type, typename p1##_type, typename p2##_type, \ - typename p3##_type, typename p4##_type, typename p5##_type, \ - typename p6##_type, typename p7##_type, typename p8##_type + p6, p7, p8) \ + , typename p0##_type, typename p1##_type, typename p2##_type, \ + typename p3##_type, typename p4##_type, typename p5##_type, \ + typename p6##_type, typename p7##_type, typename p8##_type #define GMOCK_INTERNAL_DECL_TYPE_AND_10_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, \ - p6, p7, p8, p9) , typename p0##_type, typename p1##_type, \ - typename p2##_type, typename p3##_type, typename p4##_type, \ - typename p5##_type, typename p6##_type, typename p7##_type, \ - typename p8##_type, typename p9##_type + p6, p7, p8, p9) \ + , typename p0##_type, typename p1##_type, typename p2##_type, \ + typename p3##_type, typename p4##_type, typename p5##_type, \ + typename p6##_type, typename p7##_type, typename p8##_type, \ + typename p9##_type // Initializes the value parameters. -#define GMOCK_INTERNAL_INIT_AND_0_VALUE_PARAMS()\ - () -#define GMOCK_INTERNAL_INIT_AND_1_VALUE_PARAMS(p0)\ - (p0##_type gmock_p0) : p0(::std::move(gmock_p0)) -#define GMOCK_INTERNAL_INIT_AND_2_VALUE_PARAMS(p0, p1)\ - (p0##_type gmock_p0, p1##_type gmock_p1) : p0(::std::move(gmock_p0)), \ - p1(::std::move(gmock_p1)) -#define GMOCK_INTERNAL_INIT_AND_3_VALUE_PARAMS(p0, p1, p2)\ - (p0##_type gmock_p0, p1##_type gmock_p1, \ - p2##_type gmock_p2) : p0(::std::move(gmock_p0)), \ - p1(::std::move(gmock_p1)), p2(::std::move(gmock_p2)) -#define GMOCK_INTERNAL_INIT_AND_4_VALUE_PARAMS(p0, p1, p2, p3)\ - (p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \ - p3##_type gmock_p3) : p0(::std::move(gmock_p0)), \ - p1(::std::move(gmock_p1)), p2(::std::move(gmock_p2)), \ +#define GMOCK_INTERNAL_INIT_AND_0_VALUE_PARAMS() () +#define GMOCK_INTERNAL_INIT_AND_1_VALUE_PARAMS(p0) \ + (p0##_type gmock_p0) : p0(::std::move(gmock_p0)) +#define GMOCK_INTERNAL_INIT_AND_2_VALUE_PARAMS(p0, p1) \ + (p0##_type gmock_p0, p1##_type gmock_p1) \ + : p0(::std::move(gmock_p0)), p1(::std::move(gmock_p1)) +#define GMOCK_INTERNAL_INIT_AND_3_VALUE_PARAMS(p0, p1, p2) \ + (p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2) \ + : p0(::std::move(gmock_p0)), \ + p1(::std::move(gmock_p1)), \ + p2(::std::move(gmock_p2)) +#define GMOCK_INTERNAL_INIT_AND_4_VALUE_PARAMS(p0, p1, p2, p3) \ + (p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \ + p3##_type gmock_p3) \ + : p0(::std::move(gmock_p0)), \ + p1(::std::move(gmock_p1)), \ + p2(::std::move(gmock_p2)), \ p3(::std::move(gmock_p3)) -#define GMOCK_INTERNAL_INIT_AND_5_VALUE_PARAMS(p0, p1, p2, p3, p4)\ - (p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \ - p3##_type gmock_p3, p4##_type gmock_p4) : p0(::std::move(gmock_p0)), \ - p1(::std::move(gmock_p1)), p2(::std::move(gmock_p2)), \ - p3(::std::move(gmock_p3)), p4(::std::move(gmock_p4)) -#define GMOCK_INTERNAL_INIT_AND_6_VALUE_PARAMS(p0, p1, p2, p3, p4, p5)\ - (p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \ - p3##_type gmock_p3, p4##_type gmock_p4, \ - p5##_type gmock_p5) : p0(::std::move(gmock_p0)), \ - p1(::std::move(gmock_p1)), p2(::std::move(gmock_p2)), \ - p3(::std::move(gmock_p3)), p4(::std::move(gmock_p4)), \ +#define GMOCK_INTERNAL_INIT_AND_5_VALUE_PARAMS(p0, p1, p2, p3, p4) \ + (p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \ + p3##_type gmock_p3, p4##_type gmock_p4) \ + : p0(::std::move(gmock_p0)), \ + p1(::std::move(gmock_p1)), \ + p2(::std::move(gmock_p2)), \ + p3(::std::move(gmock_p3)), \ + p4(::std::move(gmock_p4)) +#define GMOCK_INTERNAL_INIT_AND_6_VALUE_PARAMS(p0, p1, p2, p3, p4, p5) \ + (p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \ + p3##_type gmock_p3, p4##_type gmock_p4, p5##_type gmock_p5) \ + : p0(::std::move(gmock_p0)), \ + p1(::std::move(gmock_p1)), \ + p2(::std::move(gmock_p2)), \ + p3(::std::move(gmock_p3)), \ + p4(::std::move(gmock_p4)), \ p5(::std::move(gmock_p5)) -#define GMOCK_INTERNAL_INIT_AND_7_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6)\ - (p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \ - p3##_type gmock_p3, p4##_type gmock_p4, p5##_type gmock_p5, \ - p6##_type gmock_p6) : p0(::std::move(gmock_p0)), \ - p1(::std::move(gmock_p1)), p2(::std::move(gmock_p2)), \ - p3(::std::move(gmock_p3)), p4(::std::move(gmock_p4)), \ - p5(::std::move(gmock_p5)), p6(::std::move(gmock_p6)) -#define GMOCK_INTERNAL_INIT_AND_8_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, p7)\ - (p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \ - p3##_type gmock_p3, p4##_type gmock_p4, p5##_type gmock_p5, \ - p6##_type gmock_p6, p7##_type gmock_p7) : p0(::std::move(gmock_p0)), \ - p1(::std::move(gmock_p1)), p2(::std::move(gmock_p2)), \ - p3(::std::move(gmock_p3)), p4(::std::move(gmock_p4)), \ - p5(::std::move(gmock_p5)), p6(::std::move(gmock_p6)), \ +#define GMOCK_INTERNAL_INIT_AND_7_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6) \ + (p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \ + p3##_type gmock_p3, p4##_type gmock_p4, p5##_type gmock_p5, \ + p6##_type gmock_p6) \ + : p0(::std::move(gmock_p0)), \ + p1(::std::move(gmock_p1)), \ + p2(::std::move(gmock_p2)), \ + p3(::std::move(gmock_p3)), \ + p4(::std::move(gmock_p4)), \ + p5(::std::move(gmock_p5)), \ + p6(::std::move(gmock_p6)) +#define GMOCK_INTERNAL_INIT_AND_8_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, p7) \ + (p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \ + p3##_type gmock_p3, p4##_type gmock_p4, p5##_type gmock_p5, \ + p6##_type gmock_p6, p7##_type gmock_p7) \ + : p0(::std::move(gmock_p0)), \ + p1(::std::move(gmock_p1)), \ + p2(::std::move(gmock_p2)), \ + p3(::std::move(gmock_p3)), \ + p4(::std::move(gmock_p4)), \ + p5(::std::move(gmock_p5)), \ + p6(::std::move(gmock_p6)), \ p7(::std::move(gmock_p7)) -#define GMOCK_INTERNAL_INIT_AND_9_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, \ - p7, p8)\ - (p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \ - p3##_type gmock_p3, p4##_type gmock_p4, p5##_type gmock_p5, \ - p6##_type gmock_p6, p7##_type gmock_p7, \ - p8##_type gmock_p8) : p0(::std::move(gmock_p0)), \ - p1(::std::move(gmock_p1)), p2(::std::move(gmock_p2)), \ - p3(::std::move(gmock_p3)), p4(::std::move(gmock_p4)), \ - p5(::std::move(gmock_p5)), p6(::std::move(gmock_p6)), \ - p7(::std::move(gmock_p7)), p8(::std::move(gmock_p8)) +#define GMOCK_INTERNAL_INIT_AND_9_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, p7, \ + p8) \ + (p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \ + p3##_type gmock_p3, p4##_type gmock_p4, p5##_type gmock_p5, \ + p6##_type gmock_p6, p7##_type gmock_p7, p8##_type gmock_p8) \ + : p0(::std::move(gmock_p0)), \ + p1(::std::move(gmock_p1)), \ + p2(::std::move(gmock_p2)), \ + p3(::std::move(gmock_p3)), \ + p4(::std::move(gmock_p4)), \ + p5(::std::move(gmock_p5)), \ + p6(::std::move(gmock_p6)), \ + p7(::std::move(gmock_p7)), \ + p8(::std::move(gmock_p8)) #define GMOCK_INTERNAL_INIT_AND_10_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, \ - p7, p8, p9)\ - (p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \ - p3##_type gmock_p3, p4##_type gmock_p4, p5##_type gmock_p5, \ - p6##_type gmock_p6, p7##_type gmock_p7, p8##_type gmock_p8, \ - p9##_type gmock_p9) : p0(::std::move(gmock_p0)), \ - p1(::std::move(gmock_p1)), p2(::std::move(gmock_p2)), \ - p3(::std::move(gmock_p3)), p4(::std::move(gmock_p4)), \ - p5(::std::move(gmock_p5)), p6(::std::move(gmock_p6)), \ - p7(::std::move(gmock_p7)), p8(::std::move(gmock_p8)), \ + p7, p8, p9) \ + (p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \ + p3##_type gmock_p3, p4##_type gmock_p4, p5##_type gmock_p5, \ + p6##_type gmock_p6, p7##_type gmock_p7, p8##_type gmock_p8, \ + p9##_type gmock_p9) \ + : p0(::std::move(gmock_p0)), \ + p1(::std::move(gmock_p1)), \ + p2(::std::move(gmock_p2)), \ + p3(::std::move(gmock_p3)), \ + p4(::std::move(gmock_p4)), \ + p5(::std::move(gmock_p5)), \ + p6(::std::move(gmock_p6)), \ + p7(::std::move(gmock_p7)), \ + p8(::std::move(gmock_p8)), \ p9(::std::move(gmock_p9)) // Defines the copy constructor #define GMOCK_INTERNAL_DEFN_COPY_AND_0_VALUE_PARAMS() \ - {} // Avoid https://gcc.gnu.org/bugzilla/show_bug.cgi?id=82134 + {} // Avoid https://gcc.gnu.org/bugzilla/show_bug.cgi?id=82134 #define GMOCK_INTERNAL_DEFN_COPY_AND_1_VALUE_PARAMS(...) = default; #define GMOCK_INTERNAL_DEFN_COPY_AND_2_VALUE_PARAMS(...) = default; #define GMOCK_INTERNAL_DEFN_COPY_AND_3_VALUE_PARAMS(...) = default; @@ -307,30 +344,71 @@ // Declares the fields for storing the value parameters. #define GMOCK_INTERNAL_DEFN_AND_0_VALUE_PARAMS() #define GMOCK_INTERNAL_DEFN_AND_1_VALUE_PARAMS(p0) p0##_type p0; -#define GMOCK_INTERNAL_DEFN_AND_2_VALUE_PARAMS(p0, p1) p0##_type p0; \ - p1##_type p1; -#define GMOCK_INTERNAL_DEFN_AND_3_VALUE_PARAMS(p0, p1, p2) p0##_type p0; \ - p1##_type p1; p2##_type p2; -#define GMOCK_INTERNAL_DEFN_AND_4_VALUE_PARAMS(p0, p1, p2, p3) p0##_type p0; \ - p1##_type p1; p2##_type p2; p3##_type p3; -#define GMOCK_INTERNAL_DEFN_AND_5_VALUE_PARAMS(p0, p1, p2, p3, \ - p4) p0##_type p0; p1##_type p1; p2##_type p2; p3##_type p3; p4##_type p4; -#define GMOCK_INTERNAL_DEFN_AND_6_VALUE_PARAMS(p0, p1, p2, p3, p4, \ - p5) p0##_type p0; p1##_type p1; p2##_type p2; p3##_type p3; p4##_type p4; \ - p5##_type p5; -#define GMOCK_INTERNAL_DEFN_AND_7_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, \ - p6) p0##_type p0; p1##_type p1; p2##_type p2; p3##_type p3; p4##_type p4; \ - p5##_type p5; p6##_type p6; -#define GMOCK_INTERNAL_DEFN_AND_8_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, \ - p7) p0##_type p0; p1##_type p1; p2##_type p2; p3##_type p3; p4##_type p4; \ - p5##_type p5; p6##_type p6; p7##_type p7; -#define GMOCK_INTERNAL_DEFN_AND_9_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, \ - p7, p8) p0##_type p0; p1##_type p1; p2##_type p2; p3##_type p3; \ - p4##_type p4; p5##_type p5; p6##_type p6; p7##_type p7; p8##_type p8; +#define GMOCK_INTERNAL_DEFN_AND_2_VALUE_PARAMS(p0, p1) \ + p0##_type p0; \ + p1##_type p1; +#define GMOCK_INTERNAL_DEFN_AND_3_VALUE_PARAMS(p0, p1, p2) \ + p0##_type p0; \ + p1##_type p1; \ + p2##_type p2; +#define GMOCK_INTERNAL_DEFN_AND_4_VALUE_PARAMS(p0, p1, p2, p3) \ + p0##_type p0; \ + p1##_type p1; \ + p2##_type p2; \ + p3##_type p3; +#define GMOCK_INTERNAL_DEFN_AND_5_VALUE_PARAMS(p0, p1, p2, p3, p4) \ + p0##_type p0; \ + p1##_type p1; \ + p2##_type p2; \ + p3##_type p3; \ + p4##_type p4; +#define GMOCK_INTERNAL_DEFN_AND_6_VALUE_PARAMS(p0, p1, p2, p3, p4, p5) \ + p0##_type p0; \ + p1##_type p1; \ + p2##_type p2; \ + p3##_type p3; \ + p4##_type p4; \ + p5##_type p5; +#define GMOCK_INTERNAL_DEFN_AND_7_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6) \ + p0##_type p0; \ + p1##_type p1; \ + p2##_type p2; \ + p3##_type p3; \ + p4##_type p4; \ + p5##_type p5; \ + p6##_type p6; +#define GMOCK_INTERNAL_DEFN_AND_8_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, p7) \ + p0##_type p0; \ + p1##_type p1; \ + p2##_type p2; \ + p3##_type p3; \ + p4##_type p4; \ + p5##_type p5; \ + p6##_type p6; \ + p7##_type p7; +#define GMOCK_INTERNAL_DEFN_AND_9_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, p7, \ + p8) \ + p0##_type p0; \ + p1##_type p1; \ + p2##_type p2; \ + p3##_type p3; \ + p4##_type p4; \ + p5##_type p5; \ + p6##_type p6; \ + p7##_type p7; \ + p8##_type p8; #define GMOCK_INTERNAL_DEFN_AND_10_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, \ - p7, p8, p9) p0##_type p0; p1##_type p1; p2##_type p2; p3##_type p3; \ - p4##_type p4; p5##_type p5; p6##_type p6; p7##_type p7; p8##_type p8; \ - p9##_type p9; + p7, p8, p9) \ + p0##_type p0; \ + p1##_type p1; \ + p2##_type p2; \ + p3##_type p3; \ + p4##_type p4; \ + p5##_type p5; \ + p6##_type p6; \ + p7##_type p7; \ + p8##_type p8; \ + p9##_type p9; // Lists the value parameters. #define GMOCK_INTERNAL_LIST_AND_0_VALUE_PARAMS() @@ -338,72 +416,78 @@ #define GMOCK_INTERNAL_LIST_AND_2_VALUE_PARAMS(p0, p1) p0, p1 #define GMOCK_INTERNAL_LIST_AND_3_VALUE_PARAMS(p0, p1, p2) p0, p1, p2 #define GMOCK_INTERNAL_LIST_AND_4_VALUE_PARAMS(p0, p1, p2, p3) p0, p1, p2, p3 -#define GMOCK_INTERNAL_LIST_AND_5_VALUE_PARAMS(p0, p1, p2, p3, p4) p0, p1, \ - p2, p3, p4 -#define GMOCK_INTERNAL_LIST_AND_6_VALUE_PARAMS(p0, p1, p2, p3, p4, p5) p0, \ - p1, p2, p3, p4, p5 -#define GMOCK_INTERNAL_LIST_AND_7_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, \ - p6) p0, p1, p2, p3, p4, p5, p6 -#define GMOCK_INTERNAL_LIST_AND_8_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, \ - p7) p0, p1, p2, p3, p4, p5, p6, p7 -#define GMOCK_INTERNAL_LIST_AND_9_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, \ - p7, p8) p0, p1, p2, p3, p4, p5, p6, p7, p8 +#define GMOCK_INTERNAL_LIST_AND_5_VALUE_PARAMS(p0, p1, p2, p3, p4) \ + p0, p1, p2, p3, p4 +#define GMOCK_INTERNAL_LIST_AND_6_VALUE_PARAMS(p0, p1, p2, p3, p4, p5) \ + p0, p1, p2, p3, p4, p5 +#define GMOCK_INTERNAL_LIST_AND_7_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6) \ + p0, p1, p2, p3, p4, p5, p6 +#define GMOCK_INTERNAL_LIST_AND_8_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, p7) \ + p0, p1, p2, p3, p4, p5, p6, p7 +#define GMOCK_INTERNAL_LIST_AND_9_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, p7, \ + p8) \ + p0, p1, p2, p3, p4, p5, p6, p7, p8 #define GMOCK_INTERNAL_LIST_AND_10_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, \ - p7, p8, p9) p0, p1, p2, p3, p4, p5, p6, p7, p8, p9 + p7, p8, p9) \ + p0, p1, p2, p3, p4, p5, p6, p7, p8, p9 // Lists the value parameter types. #define GMOCK_INTERNAL_LIST_TYPE_AND_0_VALUE_PARAMS() #define GMOCK_INTERNAL_LIST_TYPE_AND_1_VALUE_PARAMS(p0) , p0##_type -#define GMOCK_INTERNAL_LIST_TYPE_AND_2_VALUE_PARAMS(p0, p1) , p0##_type, \ - p1##_type -#define GMOCK_INTERNAL_LIST_TYPE_AND_3_VALUE_PARAMS(p0, p1, p2) , p0##_type, \ - p1##_type, p2##_type -#define GMOCK_INTERNAL_LIST_TYPE_AND_4_VALUE_PARAMS(p0, p1, p2, p3) , \ - p0##_type, p1##_type, p2##_type, p3##_type -#define GMOCK_INTERNAL_LIST_TYPE_AND_5_VALUE_PARAMS(p0, p1, p2, p3, p4) , \ - p0##_type, p1##_type, p2##_type, p3##_type, p4##_type -#define GMOCK_INTERNAL_LIST_TYPE_AND_6_VALUE_PARAMS(p0, p1, p2, p3, p4, p5) , \ - p0##_type, p1##_type, p2##_type, p3##_type, p4##_type, p5##_type +#define GMOCK_INTERNAL_LIST_TYPE_AND_2_VALUE_PARAMS(p0, p1) \ + , p0##_type, p1##_type +#define GMOCK_INTERNAL_LIST_TYPE_AND_3_VALUE_PARAMS(p0, p1, p2) \ + , p0##_type, p1##_type, p2##_type +#define GMOCK_INTERNAL_LIST_TYPE_AND_4_VALUE_PARAMS(p0, p1, p2, p3) \ + , p0##_type, p1##_type, p2##_type, p3##_type +#define GMOCK_INTERNAL_LIST_TYPE_AND_5_VALUE_PARAMS(p0, p1, p2, p3, p4) \ + , p0##_type, p1##_type, p2##_type, p3##_type, p4##_type +#define GMOCK_INTERNAL_LIST_TYPE_AND_6_VALUE_PARAMS(p0, p1, p2, p3, p4, p5) \ + , p0##_type, p1##_type, p2##_type, p3##_type, p4##_type, p5##_type #define GMOCK_INTERNAL_LIST_TYPE_AND_7_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, \ - p6) , p0##_type, p1##_type, p2##_type, p3##_type, p4##_type, p5##_type, \ - p6##_type + p6) \ + , p0##_type, p1##_type, p2##_type, p3##_type, p4##_type, p5##_type, p6##_type #define GMOCK_INTERNAL_LIST_TYPE_AND_8_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, \ - p6, p7) , p0##_type, p1##_type, p2##_type, p3##_type, p4##_type, \ - p5##_type, p6##_type, p7##_type + p6, p7) \ + , p0##_type, p1##_type, p2##_type, p3##_type, p4##_type, p5##_type, \ + p6##_type, p7##_type #define GMOCK_INTERNAL_LIST_TYPE_AND_9_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, \ - p6, p7, p8) , p0##_type, p1##_type, p2##_type, p3##_type, p4##_type, \ - p5##_type, p6##_type, p7##_type, p8##_type + p6, p7, p8) \ + , p0##_type, p1##_type, p2##_type, p3##_type, p4##_type, p5##_type, \ + p6##_type, p7##_type, p8##_type #define GMOCK_INTERNAL_LIST_TYPE_AND_10_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, \ - p6, p7, p8, p9) , p0##_type, p1##_type, p2##_type, p3##_type, p4##_type, \ - p5##_type, p6##_type, p7##_type, p8##_type, p9##_type + p6, p7, p8, p9) \ + , p0##_type, p1##_type, p2##_type, p3##_type, p4##_type, p5##_type, \ + p6##_type, p7##_type, p8##_type, p9##_type // Declares the value parameters. #define GMOCK_INTERNAL_DECL_AND_0_VALUE_PARAMS() #define GMOCK_INTERNAL_DECL_AND_1_VALUE_PARAMS(p0) p0##_type p0 -#define GMOCK_INTERNAL_DECL_AND_2_VALUE_PARAMS(p0, p1) p0##_type p0, \ - p1##_type p1 -#define GMOCK_INTERNAL_DECL_AND_3_VALUE_PARAMS(p0, p1, p2) p0##_type p0, \ - p1##_type p1, p2##_type p2 -#define GMOCK_INTERNAL_DECL_AND_4_VALUE_PARAMS(p0, p1, p2, p3) p0##_type p0, \ - p1##_type p1, p2##_type p2, p3##_type p3 -#define GMOCK_INTERNAL_DECL_AND_5_VALUE_PARAMS(p0, p1, p2, p3, \ - p4) p0##_type p0, p1##_type p1, p2##_type p2, p3##_type p3, p4##_type p4 -#define GMOCK_INTERNAL_DECL_AND_6_VALUE_PARAMS(p0, p1, p2, p3, p4, \ - p5) p0##_type p0, p1##_type p1, p2##_type p2, p3##_type p3, p4##_type p4, \ - p5##_type p5 -#define GMOCK_INTERNAL_DECL_AND_7_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, \ - p6) p0##_type p0, p1##_type p1, p2##_type p2, p3##_type p3, p4##_type p4, \ - p5##_type p5, p6##_type p6 -#define GMOCK_INTERNAL_DECL_AND_8_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, \ - p7) p0##_type p0, p1##_type p1, p2##_type p2, p3##_type p3, p4##_type p4, \ - p5##_type p5, p6##_type p6, p7##_type p7 -#define GMOCK_INTERNAL_DECL_AND_9_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, \ - p7, p8) p0##_type p0, p1##_type p1, p2##_type p2, p3##_type p3, \ - p4##_type p4, p5##_type p5, p6##_type p6, p7##_type p7, p8##_type p8 +#define GMOCK_INTERNAL_DECL_AND_2_VALUE_PARAMS(p0, p1) \ + p0##_type p0, p1##_type p1 +#define GMOCK_INTERNAL_DECL_AND_3_VALUE_PARAMS(p0, p1, p2) \ + p0##_type p0, p1##_type p1, p2##_type p2 +#define GMOCK_INTERNAL_DECL_AND_4_VALUE_PARAMS(p0, p1, p2, p3) \ + p0##_type p0, p1##_type p1, p2##_type p2, p3##_type p3 +#define GMOCK_INTERNAL_DECL_AND_5_VALUE_PARAMS(p0, p1, p2, p3, p4) \ + p0##_type p0, p1##_type p1, p2##_type p2, p3##_type p3, p4##_type p4 +#define GMOCK_INTERNAL_DECL_AND_6_VALUE_PARAMS(p0, p1, p2, p3, p4, p5) \ + p0##_type p0, p1##_type p1, p2##_type p2, p3##_type p3, p4##_type p4, \ + p5##_type p5 +#define GMOCK_INTERNAL_DECL_AND_7_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6) \ + p0##_type p0, p1##_type p1, p2##_type p2, p3##_type p3, p4##_type p4, \ + p5##_type p5, p6##_type p6 +#define GMOCK_INTERNAL_DECL_AND_8_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, p7) \ + p0##_type p0, p1##_type p1, p2##_type p2, p3##_type p3, p4##_type p4, \ + p5##_type p5, p6##_type p6, p7##_type p7 +#define GMOCK_INTERNAL_DECL_AND_9_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, p7, \ + p8) \ + p0##_type p0, p1##_type p1, p2##_type p2, p3##_type p3, p4##_type p4, \ + p5##_type p5, p6##_type p6, p7##_type p7, p8##_type p8 #define GMOCK_INTERNAL_DECL_AND_10_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, \ - p7, p8, p9) p0##_type p0, p1##_type p1, p2##_type p2, p3##_type p3, \ - p4##_type p4, p5##_type p5, p6##_type p6, p7##_type p7, p8##_type p8, \ - p9##_type p9 + p7, p8, p9) \ + p0##_type p0, p1##_type p1, p2##_type p2, p3##_type p3, p4##_type p4, \ + p5##_type p5, p6##_type p6, p7##_type p7, p8##_type p8, p9##_type p9 // The suffix of the class template implementing the action template. #define GMOCK_INTERNAL_COUNT_AND_0_VALUE_PARAMS() @@ -415,40 +499,43 @@ #define GMOCK_INTERNAL_COUNT_AND_6_VALUE_PARAMS(p0, p1, p2, p3, p4, p5) P6 #define GMOCK_INTERNAL_COUNT_AND_7_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6) P7 #define GMOCK_INTERNAL_COUNT_AND_8_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, \ - p7) P8 + p7) \ + P8 #define GMOCK_INTERNAL_COUNT_AND_9_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, \ - p7, p8) P9 + p7, p8) \ + P9 #define GMOCK_INTERNAL_COUNT_AND_10_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, \ - p7, p8, p9) P10 + p7, p8, p9) \ + P10 // The name of the class template implementing the action template. -#define GMOCK_ACTION_CLASS_(name, value_params)\ - GTEST_CONCAT_TOKEN_(name##Action, GMOCK_INTERNAL_COUNT_##value_params) +#define GMOCK_ACTION_CLASS_(name, value_params) \ + GTEST_CONCAT_TOKEN_(name##Action, GMOCK_INTERNAL_COUNT_##value_params) #define ACTION_TEMPLATE(name, template_params, value_params) \ template <GMOCK_INTERNAL_DECL_##template_params \ - GMOCK_INTERNAL_DECL_TYPE_##value_params> \ + GMOCK_INTERNAL_DECL_TYPE_##value_params> \ class GMOCK_ACTION_CLASS_(name, value_params) { \ public: \ explicit GMOCK_ACTION_CLASS_(name, value_params)( \ GMOCK_INTERNAL_DECL_##value_params) \ GMOCK_PP_IF(GMOCK_PP_IS_EMPTY(GMOCK_INTERNAL_COUNT_##value_params), \ - = default; , \ + = default; \ + , \ : impl_(std::make_shared<gmock_Impl>( \ - GMOCK_INTERNAL_LIST_##value_params)) { }) \ - GMOCK_ACTION_CLASS_(name, value_params)( \ - const GMOCK_ACTION_CLASS_(name, value_params)&) noexcept \ - GMOCK_INTERNAL_DEFN_COPY_##value_params \ - GMOCK_ACTION_CLASS_(name, value_params)( \ - GMOCK_ACTION_CLASS_(name, value_params)&&) noexcept \ - GMOCK_INTERNAL_DEFN_COPY_##value_params \ - template <typename F> \ - operator ::testing::Action<F>() const { \ + GMOCK_INTERNAL_LIST_##value_params)){}) \ + GMOCK_ACTION_CLASS_(name, value_params)(const GMOCK_ACTION_CLASS_( \ + name, value_params) &) noexcept GMOCK_INTERNAL_DEFN_COPY_ \ + ##value_params GMOCK_ACTION_CLASS_(name, value_params)( \ + GMOCK_ACTION_CLASS_(name, value_params) &&) noexcept \ + GMOCK_INTERNAL_DEFN_COPY_##value_params template <typename F> \ + operator ::testing::Action<F>() const { \ return GMOCK_PP_IF( \ GMOCK_PP_IS_EMPTY(GMOCK_INTERNAL_COUNT_##value_params), \ - (::testing::internal::MakeAction<F, gmock_Impl>()), \ - (::testing::internal::MakeAction<F>(impl_))); \ + (::testing::internal::MakeAction<F, gmock_Impl>()), \ + (::testing::internal::MakeAction<F>(impl_))); \ } \ + \ private: \ class gmock_Impl { \ public: \ @@ -458,34 +545,35 @@ return_type gmock_PerformImpl(GMOCK_ACTION_ARG_TYPES_AND_NAMES_) const; \ GMOCK_INTERNAL_DEFN_##value_params \ }; \ - GMOCK_PP_IF(GMOCK_PP_IS_EMPTY(GMOCK_INTERNAL_COUNT_##value_params), \ - , std::shared_ptr<const gmock_Impl> impl_;) \ + GMOCK_PP_IF(GMOCK_PP_IS_EMPTY(GMOCK_INTERNAL_COUNT_##value_params), , \ + std::shared_ptr<const gmock_Impl> impl_;) \ }; \ template <GMOCK_INTERNAL_DECL_##template_params \ - GMOCK_INTERNAL_DECL_TYPE_##value_params> \ - GMOCK_ACTION_CLASS_(name, value_params)< \ - GMOCK_INTERNAL_LIST_##template_params \ - GMOCK_INTERNAL_LIST_TYPE_##value_params> name( \ - GMOCK_INTERNAL_DECL_##value_params) GTEST_MUST_USE_RESULT_; \ + GMOCK_INTERNAL_DECL_TYPE_##value_params> \ + GMOCK_ACTION_CLASS_( \ + name, value_params)<GMOCK_INTERNAL_LIST_##template_params \ + GMOCK_INTERNAL_LIST_TYPE_##value_params> \ + name(GMOCK_INTERNAL_DECL_##value_params) GTEST_MUST_USE_RESULT_; \ template <GMOCK_INTERNAL_DECL_##template_params \ - GMOCK_INTERNAL_DECL_TYPE_##value_params> \ - inline GMOCK_ACTION_CLASS_(name, value_params)< \ - GMOCK_INTERNAL_LIST_##template_params \ - GMOCK_INTERNAL_LIST_TYPE_##value_params> name( \ - GMOCK_INTERNAL_DECL_##value_params) { \ - return GMOCK_ACTION_CLASS_(name, value_params)< \ - GMOCK_INTERNAL_LIST_##template_params \ - GMOCK_INTERNAL_LIST_TYPE_##value_params>( \ - GMOCK_INTERNAL_LIST_##value_params); \ + GMOCK_INTERNAL_DECL_TYPE_##value_params> \ + inline GMOCK_ACTION_CLASS_( \ + name, value_params)<GMOCK_INTERNAL_LIST_##template_params \ + GMOCK_INTERNAL_LIST_TYPE_##value_params> \ + name(GMOCK_INTERNAL_DECL_##value_params) { \ + return GMOCK_ACTION_CLASS_( \ + name, value_params)<GMOCK_INTERNAL_LIST_##template_params \ + GMOCK_INTERNAL_LIST_TYPE_##value_params>( \ + GMOCK_INTERNAL_LIST_##value_params); \ } \ template <GMOCK_INTERNAL_DECL_##template_params \ - GMOCK_INTERNAL_DECL_TYPE_##value_params> \ + GMOCK_INTERNAL_DECL_TYPE_##value_params> \ template <typename function_type, typename return_type, typename args_type, \ GMOCK_ACTION_TEMPLATE_ARGS_NAMES_> \ - return_type GMOCK_ACTION_CLASS_(name, value_params)< \ - GMOCK_INTERNAL_LIST_##template_params \ - GMOCK_INTERNAL_LIST_TYPE_##value_params>::gmock_Impl::gmock_PerformImpl( \ - GMOCK_ACTION_ARG_TYPES_AND_NAMES_UNUSED_) const + return_type GMOCK_ACTION_CLASS_( \ + name, value_params)<GMOCK_INTERNAL_LIST_##template_params \ + GMOCK_INTERNAL_LIST_TYPE_##value_params>:: \ + gmock_Impl::gmock_PerformImpl(GMOCK_ACTION_ARG_TYPES_AND_NAMES_UNUSED_) \ + const namespace testing { @@ -495,8 +583,8 @@ namespace testing { // is expanded and macro expansion cannot contain #pragma. Therefore // we suppress them here. #ifdef _MSC_VER -# pragma warning(push) -# pragma warning(disable:4100) +#pragma warning(push) +#pragma warning(disable : 4100) #endif namespace internal { @@ -565,7 +653,7 @@ InvokeArgument(Params&&... params) { } #ifdef _MSC_VER -# pragma warning(pop) +#pragma warning(pop) #endif } // namespace testing diff --git a/googlemock/include/gmock/gmock-more-matchers.h b/googlemock/include/gmock/gmock-more-matchers.h index 6442d2f..47aaf98 100644 --- a/googlemock/include/gmock/gmock-more-matchers.h +++ b/googlemock/include/gmock/gmock-more-matchers.h @@ -47,13 +47,13 @@ namespace testing { // Silence C4100 (unreferenced formal // parameter) for MSVC #ifdef _MSC_VER -# pragma warning(push) -# pragma warning(disable:4100) +#pragma warning(push) +#pragma warning(disable : 4100) #if (_MSC_VER == 1900) // and silence C4800 (C4800: 'int *const ': forcing value // to bool 'true' or 'false') for MSVC 14 -# pragma warning(disable:4800) - #endif +#pragma warning(disable : 4800) +#endif #endif // Defines a matcher that matches an empty container. The container must @@ -83,10 +83,9 @@ MATCHER(IsFalse, negation ? "is true" : "is false") { } #ifdef _MSC_VER -# pragma warning(pop) +#pragma warning(pop) #endif - } // namespace testing #endif // GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_MORE_MATCHERS_H_ diff --git a/googlemock/include/gmock/gmock-spec-builders.h b/googlemock/include/gmock/gmock-spec-builders.h index dfe642d..8e4c5c6 100644 --- a/googlemock/include/gmock/gmock-spec-builders.h +++ b/googlemock/include/gmock/gmock-spec-builders.h @@ -70,6 +70,7 @@ #include <type_traits> #include <utility> #include <vector> + #include "gmock/gmock-actions.h" #include "gmock/gmock-cardinalities.h" #include "gmock/gmock-matchers.h" @@ -78,7 +79,7 @@ #include "gtest/gtest.h" #if GTEST_HAS_EXCEPTIONS -# include <stdexcept> // NOLINT +#include <stdexcept> // NOLINT #endif GTEST_DISABLE_MSC_WARNINGS_PUSH_(4251 \ @@ -97,13 +98,15 @@ class ExpectationSet; namespace internal { // Implements a mock function. -template <typename F> class FunctionMocker; +template <typename F> +class FunctionMocker; // Base class for expectations. class ExpectationBase; // Implements an expectation. -template <typename F> class TypedExpectation; +template <typename F> +class TypedExpectation; // Helper class for testing the Expectation class template. class ExpectationTester; @@ -171,10 +174,9 @@ class GTEST_API_ UntypedFunctionMockerBase { // Writes a message that the call is uninteresting (i.e. neither // explicitly expected nor explicitly unexpected) to the given // ostream. - virtual void UntypedDescribeUninterestingCall( - const void* untyped_args, - ::std::ostream* os) const - GTEST_LOCK_EXCLUDED_(g_gmock_mutex) = 0; + virtual void UntypedDescribeUninterestingCall(const void* untyped_args, + ::std::ostream* os) const + GTEST_LOCK_EXCLUDED_(g_gmock_mutex) = 0; // Returns the expectation that matches the given function arguments // (or NULL is there's no match); when a match is found, @@ -183,10 +185,9 @@ class GTEST_API_ UntypedFunctionMockerBase { // is_excessive is modified to indicate whether the call exceeds the // expected number. virtual const ExpectationBase* UntypedFindMatchingExpectation( - const void* untyped_args, - const void** untyped_action, bool* is_excessive, + const void* untyped_args, const void** untyped_action, bool* is_excessive, ::std::ostream* what, ::std::ostream* why) - GTEST_LOCK_EXCLUDED_(g_gmock_mutex) = 0; + GTEST_LOCK_EXCLUDED_(g_gmock_mutex) = 0; // Prints the given function arguments to the ostream. virtual void UntypedPrintArgs(const void* untyped_args, @@ -196,8 +197,7 @@ 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. - void RegisterOwner(const void* mock_obj) - GTEST_LOCK_EXCLUDED_(g_gmock_mutex); + void RegisterOwner(const void* mock_obj) GTEST_LOCK_EXCLUDED_(g_gmock_mutex); // Sets the mock object this mock method belongs to, and sets the // name of the mock function. Will be called upon each invocation @@ -208,13 +208,11 @@ class GTEST_API_ UntypedFunctionMockerBase { // Returns the mock object this mock method belongs to. Must be // called after RegisterOwner() or SetOwnerAndName() has been // called. - const void* MockObject() const - GTEST_LOCK_EXCLUDED_(g_gmock_mutex); + const void* MockObject() const GTEST_LOCK_EXCLUDED_(g_gmock_mutex); // Returns the name of this mock method. Must be called after // SetOwnerAndName() has been called. - const char* Name() const - GTEST_LOCK_EXCLUDED_(g_gmock_mutex); + const char* Name() const GTEST_LOCK_EXCLUDED_(g_gmock_mutex); // Returns the result of invoking this mock function with the given // arguments. This function can be safely called from multiple @@ -451,8 +449,7 @@ class GTEST_API_ Mock { // Returns the reaction Google Mock will have on uninteresting calls // made on the given mock object. static internal::CallReaction GetReactionOnUninterestingCalls( - const void* mock_obj) - GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex); + const void* mock_obj) GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex); // Verifies that all expectations on the given mock object have been // satisfied. Reports one or more Google Test non-fatal failures @@ -465,17 +462,16 @@ class GTEST_API_ Mock { GTEST_EXCLUSIVE_LOCK_REQUIRED_(internal::g_gmock_mutex); // Registers a mock object and a mock method it owns. - static void Register( - const void* mock_obj, - internal::UntypedFunctionMockerBase* mocker) - GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex); + static void Register(const void* mock_obj, + internal::UntypedFunctionMockerBase* mocker) + GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex); // Tells Google Mock where in the source code mock_obj is used in an // ON_CALL or EXPECT_CALL. In case mock_obj is leaked, this // information helps the user identify which object it is. - static void RegisterUseByOnCallOrExpectCall( - const void* mock_obj, const char* file, int line) - GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex); + static void RegisterUseByOnCallOrExpectCall(const void* mock_obj, + const char* file, int line) + GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex); // Unregisters a mock method; removes the owning mock object from // the registry when the last mock method associated with it has @@ -632,7 +628,6 @@ class ExpectationSet { Expectation::Set expectations_; }; - // Sequence objects are used by a user to specify the relative order // in which the expectations should match. They are copyable (we rely // on the compiler-defined copy constructor and assignment operator). @@ -678,6 +673,7 @@ class GTEST_API_ InSequence { public: InSequence(); ~InSequence(); + private: bool sequence_created_; @@ -784,40 +780,34 @@ class GTEST_API_ ExpectationBase { // the current thread. // Retires all pre-requisites of this expectation. - void RetireAllPreRequisites() - GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex); + void RetireAllPreRequisites() GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex); // Returns true if and only if this expectation is retired. - bool is_retired() const - GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) { + bool is_retired() const GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) { g_gmock_mutex.AssertHeld(); return retired_; } // Retires this expectation. - void Retire() - GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) { + void Retire() GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) { g_gmock_mutex.AssertHeld(); retired_ = true; } // Returns true if and only if this expectation is satisfied. - bool IsSatisfied() const - GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) { + bool IsSatisfied() const GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) { g_gmock_mutex.AssertHeld(); return cardinality().IsSatisfiedByCallCount(call_count_); } // Returns true if and only if this expectation is saturated. - bool IsSaturated() const - GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) { + bool IsSaturated() const GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) { g_gmock_mutex.AssertHeld(); return cardinality().IsSaturatedByCallCount(call_count_); } // Returns true if and only if this expectation is over-saturated. - bool IsOverSaturated() const - GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) { + bool IsOverSaturated() const GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) { g_gmock_mutex.AssertHeld(); return cardinality().IsOverSaturatedByCallCount(call_count_); } @@ -832,15 +822,13 @@ class GTEST_API_ ExpectationBase { GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex); // Returns the number this expectation has been invoked. - int call_count() const - GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) { + int call_count() const GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) { g_gmock_mutex.AssertHeld(); return call_count_; } // Increments the number this expectation has been invoked. - void IncrementCallCount() - GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) { + void IncrementCallCount() GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) { g_gmock_mutex.AssertHeld(); call_count_++; } @@ -849,8 +837,7 @@ class GTEST_API_ ExpectationBase { // WillRepeatedly() clauses) against the cardinality if this hasn't // been done before. Prints a warning if there are too many or too // few actions. - void CheckActionCountIfNotDone() const - GTEST_LOCK_EXCLUDED_(mutex_); + void CheckActionCountIfNotDone() const GTEST_LOCK_EXCLUDED_(mutex_); friend class ::testing::Sequence; friend class ::testing::internal::ExpectationTester; @@ -863,12 +850,12 @@ class GTEST_API_ ExpectationBase { // This group of fields are part of the spec and won't change after // an EXPECT_CALL() statement finishes. - const char* file_; // The file that contains the expectation. - int line_; // The line number of the expectation. + const char* file_; // The file that contains the expectation. + int line_; // The line number of the expectation. const std::string source_text_; // The EXPECT_CALL(...) source text. // True if and only if the cardinality is specified explicitly. bool cardinality_specified_; - Cardinality cardinality_; // The cardinality of the expectation. + Cardinality cardinality_; // The cardinality of the expectation. // The immediate pre-requisites (i.e. expectations that must be // satisfied before this expectation can be matched) of this // expectation. We use std::shared_ptr in the set because we want an @@ -887,8 +874,8 @@ class GTEST_API_ ExpectationBase { bool retires_on_saturation_; Clause last_clause_; mutable bool action_count_checked_; // Under mutex_. - mutable Mutex mutex_; // Protects action_count_checked_. -}; // class ExpectationBase + mutable Mutex mutex_; // Protects action_count_checked_. +}; // class ExpectationBase // Implements an expectation for the given function type. template <typename F> @@ -945,9 +932,7 @@ class TypedExpectation : public ExpectationBase { } // Implements the .Times() clause. - TypedExpectation& Times(int n) { - return Times(Exactly(n)); - } + TypedExpectation& Times(int n) { return Times(Exactly(n)); } // Implements the .InSequence() clause. TypedExpectation& InSequence(const Sequence& s) { @@ -1062,9 +1047,7 @@ class TypedExpectation : public ExpectationBase { // Returns the matchers for the arguments as specified inside the // EXPECT_CALL() macro. - const ArgumentMatcherTuple& matchers() const { - return matchers_; - } + const ArgumentMatcherTuple& matchers() const { return matchers_; } // Returns the matcher specified by the .With() clause. const Matcher<const ArgumentTuple&>& extra_matcher() const { @@ -1119,10 +1102,8 @@ class TypedExpectation : public ExpectationBase { // Describes the result of matching the arguments against this // expectation to the given ostream. - void ExplainMatchResultTo( - const ArgumentTuple& args, - ::std::ostream* os) const - GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) { + void ExplainMatchResultTo(const ArgumentTuple& args, ::std::ostream* os) const + GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) { g_gmock_mutex.AssertHeld(); if (is_retired()) { @@ -1181,9 +1162,9 @@ class TypedExpectation : public ExpectationBase { ::std::stringstream ss; DescribeLocationTo(&ss); ss << "Actions ran out in " << source_text() << "...\n" - << "Called " << count << " times, but only " - << action_count << " WillOnce()" - << (action_count == 1 ? " is" : "s are") << " specified - "; + << "Called " << count << " times, but only " << action_count + << " WillOnce()" << (action_count == 1 ? " is" : "s are") + << " specified - "; mocker->DescribeDefaultActionTo(args, &ss); Log(kWarning, ss.str(), 1); } @@ -1225,7 +1206,7 @@ class TypedExpectation : public ExpectationBase { } // Must be done after IncrementCount()! - *what << "Mock function call matches " << source_text() <<"...\n"; + *what << "Mock function call matches " << source_text() << "...\n"; return &(GetCurrentAction(mocker, args)); } @@ -1258,8 +1239,8 @@ template <typename F> class MockSpec { public: typedef typename internal::Function<F>::ArgumentTuple ArgumentTuple; - typedef typename internal::Function<F>::ArgumentMatcherTuple - ArgumentMatcherTuple; + typedef + typename internal::Function<F>::ArgumentMatcherTuple ArgumentMatcherTuple; // Constructs a MockSpec object, given the function mocker object // that the spec is associated with. @@ -1269,8 +1250,9 @@ class MockSpec { // Adds a new default action spec to the function mocker and returns // the newly created spec. - internal::OnCallSpec<F>& InternalDefaultActionSetAt( - const char* file, int line, const char* obj, const char* call) { + internal::OnCallSpec<F>& InternalDefaultActionSetAt(const char* file, + int line, const char* obj, + const char* call) { LogWithLocation(internal::kInfo, file, line, std::string("ON_CALL(") + obj + ", " + call + ") invoked"); return function_mocker_->AddNewOnCallSpec(file, line, matchers_); @@ -1278,13 +1260,14 @@ class MockSpec { // Adds a new expectation spec to the function mocker and returns // the newly created spec. - internal::TypedExpectation<F>& InternalExpectedAt( - const char* file, int line, const char* obj, const char* call) { + internal::TypedExpectation<F>& InternalExpectedAt(const char* file, int line, + const char* obj, + const char* call) { const std::string source_text(std::string("EXPECT_CALL(") + obj + ", " + call + ")"); LogWithLocation(internal::kInfo, file, line, source_text + " invoked"); - return function_mocker_->AddNewExpectation( - file, line, source_text, matchers_); + return function_mocker_->AddNewExpectation(file, line, source_text, + matchers_); } // This operator overload is used to swallow the superfluous parameter list @@ -1317,9 +1300,7 @@ template <typename T> class ReferenceOrValueWrapper { public: // Constructs a wrapper from the given value/reference. - explicit ReferenceOrValueWrapper(T value) - : value_(std::move(value)) { - } + explicit ReferenceOrValueWrapper(T value) : value_(std::move(value)) {} // Unwraps and returns the underlying value/reference, exactly as // originally passed. The behavior of calling this more than once on @@ -1330,9 +1311,7 @@ class ReferenceOrValueWrapper { // Always returns a const reference (more precisely, // const std::add_lvalue_reference<T>::type). The behavior of calling this // after calling Unwrap on the same object is unspecified. - const T& Peek() const { - return value_; - } + const T& Peek() const { return value_; } private: T value_; @@ -1346,8 +1325,7 @@ class ReferenceOrValueWrapper<T&> { // Workaround for debatable pass-by-reference lint warning (c-library-team // policy precludes NOLINT in this context) typedef T& reference; - explicit ReferenceOrValueWrapper(reference ref) - : value_ptr_(&ref) {} + explicit ReferenceOrValueWrapper(reference ref) : value_ptr_(&ref) {} T& Unwrap() { return *value_ptr_; } const T& Peek() const { return *value_ptr_; } @@ -1377,9 +1355,7 @@ template <typename T> class ActionResultHolder : public UntypedActionResultHolderBase { public: // Returns the held value. Must not be called more than once. - T Unwrap() { - return result_.Unwrap(); - } + T Unwrap() { return result_.Unwrap(); } // Prints the held value as an action's result to os. void PrintAsActionResult(::std::ostream* os) const override { @@ -1395,8 +1371,8 @@ class ActionResultHolder : public UntypedActionResultHolderBase { const FunctionMocker<F>* func_mocker, typename Function<F>::ArgumentTuple&& args, const std::string& call_description) { - return new ActionResultHolder(Wrapper(func_mocker->PerformDefaultAction( - std::move(args), call_description))); + return new ActionResultHolder(Wrapper( + func_mocker->PerformDefaultAction(std::move(args), call_description))); } // Performs the given action and returns the result in a new-ed @@ -1404,16 +1380,13 @@ class ActionResultHolder : public UntypedActionResultHolderBase { template <typename F> static ActionResultHolder* PerformAction( const Action<F>& action, typename Function<F>::ArgumentTuple&& args) { - return new ActionResultHolder( - Wrapper(action.Perform(std::move(args)))); + return new ActionResultHolder(Wrapper(action.Perform(std::move(args)))); } private: typedef ReferenceOrValueWrapper<T> Wrapper; - explicit ActionResultHolder(Wrapper result) - : result_(std::move(result)) { - } + explicit ActionResultHolder(Wrapper result) : result_(std::move(result)) {} Wrapper result_; @@ -1424,7 +1397,7 @@ class ActionResultHolder : public UntypedActionResultHolderBase { template <> class ActionResultHolder<void> : public UntypedActionResultHolderBase { public: - void Unwrap() { } + void Unwrap() {} void PrintAsActionResult(::std::ostream* /* os */) const override {} @@ -1495,14 +1468,12 @@ class FunctionMocker<R(Args...)> final : public UntypedFunctionMockerBase { // Returns the ON_CALL spec that matches this mock function with the // given arguments; returns NULL if no matching ON_CALL is found. // L = * - const OnCallSpec<F>* FindOnCallSpec( - const ArgumentTuple& args) const { - for (UntypedOnCallSpecs::const_reverse_iterator it - = untyped_on_call_specs_.rbegin(); + const OnCallSpec<F>* FindOnCallSpec(const ArgumentTuple& args) const { + for (UntypedOnCallSpecs::const_reverse_iterator it = + untyped_on_call_specs_.rbegin(); it != untyped_on_call_specs_.rend(); ++it) { const OnCallSpec<F>* spec = static_cast<const OnCallSpec<F>*>(*it); - if (spec->Matches(args)) - return spec; + if (spec->Matches(args)) return spec; } return nullptr; @@ -1517,8 +1488,7 @@ class FunctionMocker<R(Args...)> final : public UntypedFunctionMockerBase { // L = * Result PerformDefaultAction(ArgumentTuple&& args, const std::string& call_description) const { - const OnCallSpec<F>* const spec = - this->FindOnCallSpec(args); + const OnCallSpec<F>* const spec = this->FindOnCallSpec(args); if (spec != nullptr) { return spec->GetAction().Perform(std::move(args)); } @@ -1579,8 +1549,7 @@ class FunctionMocker<R(Args...)> final : public UntypedFunctionMockerBase { untyped_on_call_specs_.swap(specs_to_delete); g_gmock_mutex.Unlock(); - for (UntypedOnCallSpecs::const_iterator it = - specs_to_delete.begin(); + for (UntypedOnCallSpecs::const_iterator it = specs_to_delete.begin(); it != specs_to_delete.end(); ++it) { delete static_cast<const OnCallSpec<F>*>(*it); } @@ -1611,10 +1580,9 @@ class FunctionMocker<R(Args...)> final : public UntypedFunctionMockerBase { typedef ActionResultHolder<Result> ResultHolder; // Adds and returns a default action spec for this mock function. - OnCallSpec<F>& AddNewOnCallSpec( - const char* file, int line, - const ArgumentMatcherTuple& m) - GTEST_LOCK_EXCLUDED_(g_gmock_mutex) { + OnCallSpec<F>& AddNewOnCallSpec(const char* file, int line, + const ArgumentMatcherTuple& m) + GTEST_LOCK_EXCLUDED_(g_gmock_mutex) { Mock::RegisterUseByOnCallOrExpectCall(MockObject(), file, line); OnCallSpec<F>* const on_call_spec = new OnCallSpec<F>(file, line, m); untyped_on_call_specs_.push_back(on_call_spec); @@ -1644,7 +1612,8 @@ class FunctionMocker<R(Args...)> final : public UntypedFunctionMockerBase { } private: - template <typename Func> friend class TypedExpectation; + template <typename Func> + friend class TypedExpectation; // Some utilities needed for implementing UntypedInvokeWith(). @@ -1728,9 +1697,8 @@ class FunctionMocker<R(Args...)> final : public UntypedFunctionMockerBase { // Returns the expectation that matches the arguments, or NULL if no // expectation matches them. - TypedExpectation<F>* FindMatchingExpectationLocked( - const ArgumentTuple& args) const - GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) { + TypedExpectation<F>* FindMatchingExpectationLocked(const ArgumentTuple& args) + const GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) { g_gmock_mutex.AssertHeld(); // See the definition of untyped_expectations_ for why access to // it is unprotected here. @@ -1747,11 +1715,10 @@ class FunctionMocker<R(Args...)> final : public UntypedFunctionMockerBase { } // Returns a message that the arguments don't match any expectation. - void FormatUnexpectedCallMessageLocked( - const ArgumentTuple& args, - ::std::ostream* os, - ::std::ostream* why) const - GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) { + void FormatUnexpectedCallMessageLocked(const ArgumentTuple& args, + ::std::ostream* os, + ::std::ostream* why) const + GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) { g_gmock_mutex.AssertHeld(); *os << "\nUnexpected mock function call - "; DescribeDefaultActionTo(args, os); @@ -1760,15 +1727,14 @@ class FunctionMocker<R(Args...)> final : public UntypedFunctionMockerBase { // Prints a list of expectations that have been tried against the // current mock function call. - void PrintTriedExpectationsLocked( - const ArgumentTuple& args, - ::std::ostream* why) const - GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) { + void PrintTriedExpectationsLocked(const ArgumentTuple& args, + ::std::ostream* why) const + GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) { g_gmock_mutex.AssertHeld(); const size_t count = untyped_expectations_.size(); *why << "Google Mock tried the following " << count << " " - << (count == 1 ? "expectation, but it didn't match" : - "expectations, but none matched") + << (count == 1 ? "expectation, but it didn't match" + : "expectations, but none matched") << ":\n"; for (size_t i = 0; i < count; i++) { TypedExpectation<F>* const expectation = @@ -1952,7 +1918,9 @@ using internal::MockSpec; // // Expects a call to const MockFoo::Bar(). // EXPECT_CALL(Const(foo), Bar()); template <typename T> -inline const T& Const(const T& x) { return x; } +inline const T& Const(const T& x) { + return x; +} // Constructs an Expectation object that references and co-owns exp. inline Expectation::Expectation(internal::ExpectationBase& exp) // NOLINT diff --git a/googlemock/include/gmock/internal/gmock-internal-utils.h b/googlemock/include/gmock/internal/gmock-internal-utils.h index d9d812a..22fff5c 100644 --- a/googlemock/include/gmock/internal/gmock-internal-utils.h +++ b/googlemock/include/gmock/internal/gmock-internal-utils.h @@ -59,9 +59,9 @@ namespace internal { // Silence MSVC C4100 (unreferenced formal parameter) and // C4805('==': unsafe mix of type 'const int' and type 'const bool') #ifdef _MSC_VER -# pragma warning(push) -# pragma warning(disable:4100) -# pragma warning(disable:4805) +#pragma warning(push) +#pragma warning(disable : 4100) +#pragma warning(disable : 4805) #endif // Joins a vector of strings as if they are fields of a tuple; returns @@ -91,7 +91,9 @@ inline const Element* GetRawPointer(const std::reference_wrapper<Element>& r) { // This overloaded version is for the raw pointer case. template <typename Element> -inline Element* GetRawPointer(Element* p) { return p; } +inline Element* GetRawPointer(Element* p) { + return p; +} // 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 @@ -100,7 +102,7 @@ inline Element* GetRawPointer(Element* p) { return p; } #if defined(_MSC_VER) && !defined(_NATIVE_WCHAR_T_DEFINED) // wchar_t is a typedef. #else -# define GMOCK_WCHAR_T_IS_NATIVE_ 1 +#define GMOCK_WCHAR_T_IS_NATIVE_ 1 #endif // In what follows, we use the term "kind" to indicate whether a type @@ -108,18 +110,20 @@ inline Element* GetRawPointer(Element* p) { return p; } // or none of them. This categorization is useful for determining // when a matcher argument type can be safely converted to another // type in the implementation of SafeMatcherCast. -enum TypeKind { - kBool, kInteger, kFloatingPoint, kOther -}; +enum TypeKind { kBool, kInteger, kFloatingPoint, kOther }; // KindOf<T>::value is the kind of type T. -template <typename T> struct KindOf { +template <typename T> +struct KindOf { enum { value = kOther }; // The default kind. }; // This macro declares that the kind of 'type' is 'kind'. #define GMOCK_DECLARE_KIND_(type, kind) \ - template <> struct KindOf<type> { enum { value = kind }; } + template <> \ + struct KindOf<type> { \ + enum { value = kind }; \ + } GMOCK_DECLARE_KIND_(bool, kBool); @@ -127,13 +131,13 @@ GMOCK_DECLARE_KIND_(bool, kBool); GMOCK_DECLARE_KIND_(char, kInteger); GMOCK_DECLARE_KIND_(signed char, kInteger); GMOCK_DECLARE_KIND_(unsigned char, kInteger); -GMOCK_DECLARE_KIND_(short, kInteger); // NOLINT +GMOCK_DECLARE_KIND_(short, kInteger); // NOLINT GMOCK_DECLARE_KIND_(unsigned short, kInteger); // NOLINT GMOCK_DECLARE_KIND_(int, kInteger); GMOCK_DECLARE_KIND_(unsigned int, kInteger); -GMOCK_DECLARE_KIND_(long, kInteger); // NOLINT -GMOCK_DECLARE_KIND_(unsigned long, kInteger); // NOLINT -GMOCK_DECLARE_KIND_(long long, kInteger); // NOLINT +GMOCK_DECLARE_KIND_(long, kInteger); // NOLINT +GMOCK_DECLARE_KIND_(unsigned long, kInteger); // NOLINT +GMOCK_DECLARE_KIND_(long long, kInteger); // NOLINT GMOCK_DECLARE_KIND_(unsigned long long, kInteger); // NOLINT #if GMOCK_WCHAR_T_IS_NATIVE_ @@ -148,7 +152,7 @@ GMOCK_DECLARE_KIND_(long double, kFloatingPoint); #undef GMOCK_DECLARE_KIND_ // Evaluates to the kind of 'type'. -#define GMOCK_KIND_OF_(type) \ +#define GMOCK_KIND_OF_(type) \ static_cast< ::testing::internal::TypeKind>( \ ::testing::internal::KindOf<type>::value) @@ -204,9 +208,7 @@ using LosslessArithmeticConvertible = class FailureReporterInterface { public: // The type of a failure (either non-fatal or fatal). - enum FailureType { - kNonfatal, kFatal - }; + enum FailureType { kNonfatal, kFatal }; virtual ~FailureReporterInterface() {} @@ -226,8 +228,8 @@ GTEST_API_ FailureReporterInterface* GetFailureReporter(); inline void Assert(bool condition, const char* file, int line, const std::string& msg) { if (!condition) { - GetFailureReporter()->ReportFailure(FailureReporterInterface::kFatal, - file, line, msg); + GetFailureReporter()->ReportFailure(FailureReporterInterface::kFatal, file, + line, msg); } } inline void Assert(bool condition, const char* file, int line) { @@ -248,10 +250,7 @@ inline void Expect(bool condition, const char* file, int line) { } // Severity level of a log. -enum LogSeverity { - kInfo = 0, - kWarning = 1 -}; +enum LogSeverity { kInfo = 0, kWarning = 1 }; // Valid values for the --gmock_verbose flag. @@ -294,8 +293,8 @@ GTEST_API_ WithoutMatchers GetWithoutMatchers(); // Disable MSVC warnings for infinite recursion, since in this case the // recursion is unreachable. #ifdef _MSC_VER -# pragma warning(push) -# pragma warning(disable:4717) +#pragma warning(push) +#pragma warning(disable : 4717) #endif // Invalid<T>() is usable as an expression of type T, but will terminate @@ -313,7 +312,7 @@ inline T Invalid() { } #ifdef _MSC_VER -# pragma warning(pop) +#pragma warning(pop) #endif // Given a raw type (i.e. having no top-level reference or const @@ -392,7 +391,8 @@ class StlContainerView< ::std::tuple<ElementPointer, Size> > { // The following specialization prevents the user from instantiating // StlContainer with a reference type. -template <typename T> class StlContainerView<T&>; +template <typename T> +class StlContainerView<T&>; // A type transform to remove constness from the first part of a pair. // Pairs like that are used as the value_type of associative containers, @@ -413,17 +413,18 @@ struct RemoveConstFromKey<std::pair<const K, V> > { GTEST_API_ void IllegalDoDefault(const char* file, int line); template <typename F, typename Tuple, size_t... Idx> -auto ApplyImpl(F&& f, Tuple&& args, IndexSequence<Idx...>) -> decltype( - std::forward<F>(f)(std::get<Idx>(std::forward<Tuple>(args))...)) { +auto ApplyImpl(F&& f, Tuple&& args, IndexSequence<Idx...>) + -> decltype(std::forward<F>(f)( + std::get<Idx>(std::forward<Tuple>(args))...)) { return std::forward<F>(f)(std::get<Idx>(std::forward<Tuple>(args))...); } // Apply the function to a tuple of arguments. template <typename F, typename Tuple> -auto Apply(F&& f, Tuple&& args) -> decltype( - ApplyImpl(std::forward<F>(f), std::forward<Tuple>(args), - MakeIndexSequence<std::tuple_size< - typename std::remove_reference<Tuple>::type>::value>())) { +auto Apply(F&& f, Tuple&& args) -> decltype(ApplyImpl( + std::forward<F>(f), std::forward<Tuple>(args), + MakeIndexSequence<std::tuple_size< + typename std::remove_reference<Tuple>::type>::value>())) { return ApplyImpl(std::forward<F>(f), std::forward<Tuple>(args), MakeIndexSequence<std::tuple_size< typename std::remove_reference<Tuple>::type>::value>()); @@ -463,7 +464,7 @@ constexpr size_t Function<R(Args...)>::ArgumentCount; bool Base64Unescape(const std::string& encoded, std::string* decoded); #ifdef _MSC_VER -# pragma warning(pop) +#pragma warning(pop) #endif } // namespace internal diff --git a/googlemock/include/gmock/internal/gmock-port.h b/googlemock/include/gmock/internal/gmock-port.h index 998f6c7..f3e63c1 100644 --- a/googlemock/include/gmock/internal/gmock-port.h +++ b/googlemock/include/gmock/internal/gmock-port.h @@ -42,6 +42,7 @@ #include <assert.h> #include <stdlib.h> + #include <cstdint> #include <iostream> @@ -53,13 +54,13 @@ // here, as Google Mock depends on Google Test. Only add a utility // here if it's truly specific to Google Mock. -#include "gtest/internal/gtest-port.h" #include "gmock/internal/custom/gmock-port.h" +#include "gtest/internal/gtest-port.h" // For MS Visual C++, check the compiler version. At least VS 2015 is // required to compile Google Mock. #if defined(_MSC_VER) && _MSC_VER < 1900 -# error "At least Visual C++ 2015 (14.0) is required to compile Google Mock." +#error "At least Visual C++ 2015 (14.0) is required to compile Google Mock." #endif // Macro for referencing flags. This is public as we want the user to @@ -72,29 +73,35 @@ #define GMOCK_DECLARE_bool_(name) \ namespace testing { \ GTEST_API_ extern bool GMOCK_FLAG(name); \ - } static_assert(true, "no-op to require trailing semicolon") + } \ + static_assert(true, "no-op to require trailing semicolon") #define GMOCK_DECLARE_int32_(name) \ namespace testing { \ GTEST_API_ extern int32_t GMOCK_FLAG(name); \ - } static_assert(true, "no-op to require trailing semicolon") + } \ + static_assert(true, "no-op to require trailing semicolon") #define GMOCK_DECLARE_string_(name) \ namespace testing { \ GTEST_API_ extern ::std::string GMOCK_FLAG(name); \ - } static_assert(true, "no-op to require trailing semicolon") + } \ + static_assert(true, "no-op to require trailing semicolon") // Macros for defining flags. #define GMOCK_DEFINE_bool_(name, default_val, doc) \ namespace testing { \ GTEST_API_ bool GMOCK_FLAG(name) = (default_val); \ - } static_assert(true, "no-op to require trailing semicolon") + } \ + static_assert(true, "no-op to require trailing semicolon") #define GMOCK_DEFINE_int32_(name, default_val, doc) \ namespace testing { \ GTEST_API_ int32_t GMOCK_FLAG(name) = (default_val); \ - } static_assert(true, "no-op to require trailing semicolon") + } \ + static_assert(true, "no-op to require trailing semicolon") #define GMOCK_DEFINE_string_(name, default_val, doc) \ namespace testing { \ GTEST_API_ ::std::string GMOCK_FLAG(name) = (default_val); \ - } static_assert(true, "no-op to require trailing semicolon") + } \ + static_assert(true, "no-op to require trailing semicolon") #endif // !defined(GMOCK_DECLARE_bool_) #if !defined(GMOCK_FLAG_GET) diff --git a/googlemock/src/gmock-cardinalities.cc b/googlemock/src/gmock-cardinalities.cc index 7463f43..1e7b898 100644 --- a/googlemock/src/gmock-cardinalities.cc +++ b/googlemock/src/gmock-cardinalities.cc @@ -27,7 +27,6 @@ // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - // Google Mock - a framework for writing C++ mock classes. // // This file implements cardinalities. @@ -35,9 +34,11 @@ #include "gmock/gmock-cardinalities.h" #include <limits.h> + #include <ostream> // NOLINT #include <sstream> #include <string> + #include "gmock/internal/gmock-internal-utils.h" #include "gtest/gtest.h" @@ -49,8 +50,7 @@ namespace { class BetweenCardinalityImpl : public CardinalityInterface { public: BetweenCardinalityImpl(int min, int max) - : min_(min >= 0 ? min : 0), - max_(max >= min_ ? max : min_) { + : min_(min >= 0 ? min : 0), max_(max >= min_ ? max : min_) { std::stringstream ss; if (min < 0) { ss << "The invocation lower bound must be >= 0, " @@ -62,8 +62,7 @@ class BetweenCardinalityImpl : public CardinalityInterface { internal::Expect(false, __FILE__, __LINE__, ss.str()); } else if (min > max) { ss << "The invocation upper bound (" << max - << ") must be >= the invocation lower bound (" << min - << ")."; + << ") must be >= the invocation lower bound (" << min << ")."; internal::Expect(false, __FILE__, __LINE__, ss.str()); } } diff --git a/googlemock/src/gmock-internal-utils.cc b/googlemock/src/gmock-internal-utils.cc index 6020736..bb0a698 100644 --- a/googlemock/src/gmock-internal-utils.cc +++ b/googlemock/src/gmock-internal-utils.cc @@ -27,7 +27,6 @@ // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - // Google Mock - a framework for writing C++ mock classes. // // This file defines some utilities useful for implementing Google @@ -84,12 +83,11 @@ GTEST_API_ std::string ConvertIdentifierNameToWords(const char* id_name) { // We don't care about the current locale as the input is // guaranteed to be a valid C++ identifier name. const bool starts_new_word = IsUpper(*p) || - (!IsAlpha(prev_char) && IsLower(*p)) || - (!IsDigit(prev_char) && IsDigit(*p)); + (!IsAlpha(prev_char) && IsLower(*p)) || + (!IsDigit(prev_char) && IsDigit(*p)); if (IsAlNum(*p)) { - if (starts_new_word && result != "") - result += ' '; + if (starts_new_word && result != "") result += ' '; result += ToLower(*p); } } @@ -103,12 +101,9 @@ class GoogleTestFailureReporter : public FailureReporterInterface { public: void ReportFailure(FailureType type, const char* file, int line, const std::string& message) override { - AssertHelper(type == kFatal ? - TestPartResult::kFatalFailure : - TestPartResult::kNonFatalFailure, - file, - line, - message.c_str()) = Message(); + AssertHelper(type == kFatal ? TestPartResult::kFatalFailure + : TestPartResult::kNonFatalFailure, + file, line, message.c_str()) = Message(); if (type == kFatal) { posix::Abort(); } @@ -156,8 +151,7 @@ GTEST_API_ bool LogIsVisible(LogSeverity severity) { // conservative. GTEST_API_ void Log(LogSeverity severity, const std::string& message, int stack_frames_to_skip) { - if (!LogIsVisible(severity)) - return; + if (!LogIsVisible(severity)) return; // Ensures that logs from different threads don't interleave. MutexLock l(&g_log_mutex); @@ -186,8 +180,8 @@ GTEST_API_ void Log(LogSeverity severity, const std::string& message, std::cout << "\n"; } std::cout << "Stack trace:\n" - << ::testing::internal::GetCurrentOsStackTraceExceptTop( - ::testing::UnitTest::GetInstance(), actual_to_skip); + << ::testing::internal::GetCurrentOsStackTraceExceptTop( + ::testing::UnitTest::GetInstance(), actual_to_skip); } std::cout << ::std::flush; } diff --git a/googlemock/src/gmock-matchers.cc b/googlemock/src/gmock-matchers.cc index 873527b..a8d04a6 100644 --- a/googlemock/src/gmock-matchers.cc +++ b/googlemock/src/gmock-matchers.cc @@ -27,7 +27,6 @@ // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - // Google Mock - a framework for writing C++ mock classes. // // This file implements Matcher<const string&>, Matcher<string>, and diff --git a/googlemock/src/gmock-spec-builders.cc b/googlemock/src/gmock-spec-builders.cc index 7b4a38b..b671921 100644 --- a/googlemock/src/gmock-spec-builders.cc +++ b/googlemock/src/gmock-spec-builders.cc @@ -27,7 +27,6 @@ // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - // Google Mock - a framework for writing C++ mock classes. // // This file implements the spec builder syntax (ON_CALL and @@ -49,15 +48,15 @@ #include "gtest/internal/gtest-port.h" #if GTEST_OS_CYGWIN || GTEST_OS_LINUX || GTEST_OS_MAC -# include <unistd.h> // NOLINT +#include <unistd.h> // NOLINT #endif // Silence C4800 (C4800: 'int *const ': forcing value // to bool 'true' or 'false') for MSVC 15 #ifdef _MSC_VER #if _MSC_VER == 1900 -# pragma warning(push) -# pragma warning(disable:4800) +#pragma warning(push) +#pragma warning(disable : 4800) #endif #endif @@ -195,11 +194,12 @@ void ExpectationBase::DescribeCallCountTo(::std::ostream* os) const // Describes the state of the expectation (e.g. is it satisfied? // is it active?). - *os << " - " << (IsOverSaturated() ? "over-saturated" : - IsSaturated() ? "saturated" : - IsSatisfied() ? "satisfied" : "unsatisfied") - << " and " - << (is_retired() ? "retired" : "active"); + *os << " - " + << (IsOverSaturated() ? "over-saturated" + : IsSaturated() ? "saturated" + : IsSatisfied() ? "satisfied" + : "unsatisfied") + << " and " << (is_retired() ? "retired" : "active"); } // Checks the action count (i.e. the number of WillOnce() and @@ -242,13 +242,12 @@ void ExpectationBase::CheckActionCountIfNotDone() const ::std::stringstream ss; DescribeLocationTo(&ss); - ss << "Too " << (too_many ? "many" : "few") - << " actions specified in " << source_text() << "...\n" + ss << "Too " << (too_many ? "many" : "few") << " actions specified in " + << source_text() << "...\n" << "Expected to be "; cardinality().DescribeTo(&ss); - ss << ", but has " << (too_many ? "" : "only ") - << action_count << " WillOnce()" - << (action_count == 1 ? "" : "s"); + ss << ", but has " << (too_many ? "" : "only ") << action_count + << " WillOnce()" << (action_count == 1 ? "" : "s"); if (repeated_action_specified_) { ss << " and a WillRepeatedly()"; } @@ -398,11 +397,11 @@ UntypedActionResultHolderBase* UntypedFunctionMockerBase::UntypedInvokeWith( // If the user wants this to be a warning, we print // it only when they want to see warnings. reaction == kWarn - ? LogIsVisible(kWarning) - : - // Otherwise, the user wants this to be an error, and we - // should always print detailed information in the error. - true; + ? LogIsVisible(kWarning) + : + // Otherwise, the user wants this to be an error, and we + // should always print detailed information in the error. + true; if (!need_to_report_uninteresting_call) { // Perform the action without printing the call information. @@ -505,8 +504,7 @@ UntypedActionResultHolderBase* UntypedFunctionMockerBase::UntypedInvokeWith( Expectation UntypedFunctionMockerBase::GetHandleOf(ExpectationBase* exp) { // See the definition of untyped_expectations_ for why access to it // is unprotected here. - for (UntypedExpectations::const_iterator it = - untyped_expectations_.begin(); + for (UntypedExpectations::const_iterator it = untyped_expectations_.begin(); it != untyped_expectations_.end(); ++it) { if (it->get() == exp) { return Expectation(*it); @@ -526,8 +524,7 @@ bool UntypedFunctionMockerBase::VerifyAndClearExpectationsLocked() GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) { g_gmock_mutex.AssertHeld(); bool expectations_met = true; - for (UntypedExpectations::const_iterator it = - untyped_expectations_.begin(); + for (UntypedExpectations::const_iterator it = untyped_expectations_.begin(); it != untyped_expectations_.end(); ++it) { ExpectationBase* const untyped_expectation = it->get(); if (untyped_expectation->IsOverSaturated()) { @@ -538,15 +535,15 @@ bool UntypedFunctionMockerBase::VerifyAndClearExpectationsLocked() } else if (!untyped_expectation->IsSatisfied()) { expectations_met = false; ::std::stringstream ss; - ss << "Actual function call count doesn't match " - << untyped_expectation->source_text() << "...\n"; + ss << "Actual function call count doesn't match " + << untyped_expectation->source_text() << "...\n"; // No need to show the source file location of the expectation // in the description, as the Expect() call that follows already // takes care of it. untyped_expectation->MaybeDescribeExtraMatcherTo(&ss); untyped_expectation->DescribeCallCountTo(&ss); - Expect(false, untyped_expectation->file(), - untyped_expectation->line(), ss.str()); + Expect(false, untyped_expectation->file(), untyped_expectation->line(), + ss.str()); } } @@ -633,7 +630,7 @@ class MockObjectRegistry { << state.first_used_test << ")"; } std::cout << " should be deleted but never is. Its address is @" - << it->first << "."; + << it->first << "."; leaked_count++; } if (leaked_count > 0) { @@ -712,8 +709,7 @@ void Mock::UnregisterCallReaction(const void* mock_obj) // Returns the reaction Google Mock will have on uninteresting calls // made on the given mock object. internal::CallReaction Mock::GetReactionOnUninterestingCalls( - const void* mock_obj) - GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) { + const void* mock_obj) GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) { internal::MutexLock l(&internal::g_gmock_mutex); return (g_uninteresting_call_reaction.count(mock_obj) == 0) ? internal::intToCallReaction( @@ -873,8 +869,8 @@ Expectation::~Expectation() {} void Sequence::AddExpectation(const Expectation& expectation) const { if (*last_expectation_ != expectation) { if (last_expectation_->expectation_base() != nullptr) { - expectation.expectation_base()->immediate_prerequisites_ - += *last_expectation_; + expectation.expectation_base()->immediate_prerequisites_ += + *last_expectation_; } *last_expectation_ = expectation; } @@ -903,6 +899,6 @@ InSequence::~InSequence() { #ifdef _MSC_VER #if _MSC_VER == 1900 -# pragma warning(pop) +#pragma warning(pop) #endif #endif diff --git a/googlemock/src/gmock.cc b/googlemock/src/gmock.cc index a20aed8..5025656 100644 --- a/googlemock/src/gmock.cc +++ b/googlemock/src/gmock.cc @@ -27,8 +27,8 @@ // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - #include "gmock/gmock.h" + #include "gmock/internal/gmock-port.h" GMOCK_DEFINE_bool_(catch_leaked_mocks, true, diff --git a/googlemock/src/gmock_main.cc b/googlemock/src/gmock_main.cc index 18c500f..b411c5e 100644 --- a/googlemock/src/gmock_main.cc +++ b/googlemock/src/gmock_main.cc @@ -27,8 +27,8 @@ // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - #include <iostream> + #include "gmock/gmock.h" #include "gtest/gtest.h" @@ -56,7 +56,7 @@ void loop() { RUN_ALL_TESTS(); } // https://web.archive.org/web/20170912203238/connect.microsoft.com/VisualStudio/feedback/details/394464/wmain-link-error-in-the-static-library // // NOLINT #if GTEST_OS_WINDOWS_MOBILE -# include <tchar.h> // NOLINT +#include <tchar.h> // NOLINT GTEST_API_ int _tmain(int argc, TCHAR** argv) { #else diff --git a/googlemock/test/gmock-actions_test.cc b/googlemock/test/gmock-actions_test.cc index fc62893..233b60c 100644 --- a/googlemock/test/gmock-actions_test.cc +++ b/googlemock/test/gmock-actions_test.cc @@ -27,32 +27,33 @@ // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - // Google Mock - a framework for writing C++ mock classes. // // This file tests the built-in actions. // Silence C4100 (unreferenced formal parameter) for MSVC #ifdef _MSC_VER -# pragma warning(push) -# pragma warning(disable:4100) +#pragma warning(push) +#pragma warning(disable : 4100) #if _MSC_VER == 1900 // and silence C4800 (C4800: 'int *const ': forcing value // to bool 'true' or 'false') for MSVC 15 -# pragma warning(disable:4800) +#pragma warning(disable : 4800) #endif #endif #include "gmock/gmock-actions.h" + #include <algorithm> #include <iterator> #include <memory> #include <string> #include <type_traits> + #include "gmock/gmock.h" #include "gmock/internal/gmock-port.h" -#include "gtest/gtest.h" #include "gtest/gtest-spi.h" +#include "gtest/gtest.h" namespace { @@ -114,17 +115,17 @@ TEST(BuiltInDefaultValueTest, IsZeroForNumericTypes) { #endif #endif EXPECT_EQ(0U, BuiltInDefaultValue<unsigned short>::Get()); // NOLINT - EXPECT_EQ(0, BuiltInDefaultValue<signed short>::Get()); // NOLINT - EXPECT_EQ(0, BuiltInDefaultValue<short>::Get()); // NOLINT + EXPECT_EQ(0, BuiltInDefaultValue<signed short>::Get()); // NOLINT + EXPECT_EQ(0, BuiltInDefaultValue<short>::Get()); // NOLINT EXPECT_EQ(0U, BuiltInDefaultValue<unsigned int>::Get()); EXPECT_EQ(0, BuiltInDefaultValue<signed int>::Get()); EXPECT_EQ(0, BuiltInDefaultValue<int>::Get()); - EXPECT_EQ(0U, BuiltInDefaultValue<unsigned long>::Get()); // NOLINT - EXPECT_EQ(0, BuiltInDefaultValue<signed long>::Get()); // NOLINT - EXPECT_EQ(0, BuiltInDefaultValue<long>::Get()); // NOLINT + EXPECT_EQ(0U, BuiltInDefaultValue<unsigned long>::Get()); // NOLINT + EXPECT_EQ(0, BuiltInDefaultValue<signed long>::Get()); // NOLINT + EXPECT_EQ(0, BuiltInDefaultValue<long>::Get()); // NOLINT EXPECT_EQ(0U, BuiltInDefaultValue<unsigned long long>::Get()); // NOLINT - EXPECT_EQ(0, BuiltInDefaultValue<signed long long>::Get()); // NOLINT - EXPECT_EQ(0, BuiltInDefaultValue<long long>::Get()); // NOLINT + EXPECT_EQ(0, BuiltInDefaultValue<signed long long>::Get()); // NOLINT + EXPECT_EQ(0, BuiltInDefaultValue<long long>::Get()); // NOLINT EXPECT_EQ(0, BuiltInDefaultValue<float>::Get()); EXPECT_EQ(0, BuiltInDefaultValue<double>::Get()); } @@ -139,17 +140,17 @@ TEST(BuiltInDefaultValueTest, ExistsForNumericTypes) { EXPECT_TRUE(BuiltInDefaultValue<wchar_t>::Exists()); #endif EXPECT_TRUE(BuiltInDefaultValue<unsigned short>::Exists()); // NOLINT - EXPECT_TRUE(BuiltInDefaultValue<signed short>::Exists()); // NOLINT - EXPECT_TRUE(BuiltInDefaultValue<short>::Exists()); // NOLINT + EXPECT_TRUE(BuiltInDefaultValue<signed short>::Exists()); // NOLINT + EXPECT_TRUE(BuiltInDefaultValue<short>::Exists()); // NOLINT EXPECT_TRUE(BuiltInDefaultValue<unsigned int>::Exists()); EXPECT_TRUE(BuiltInDefaultValue<signed int>::Exists()); EXPECT_TRUE(BuiltInDefaultValue<int>::Exists()); - EXPECT_TRUE(BuiltInDefaultValue<unsigned long>::Exists()); // NOLINT - EXPECT_TRUE(BuiltInDefaultValue<signed long>::Exists()); // NOLINT - EXPECT_TRUE(BuiltInDefaultValue<long>::Exists()); // NOLINT + EXPECT_TRUE(BuiltInDefaultValue<unsigned long>::Exists()); // NOLINT + EXPECT_TRUE(BuiltInDefaultValue<signed long>::Exists()); // NOLINT + EXPECT_TRUE(BuiltInDefaultValue<long>::Exists()); // NOLINT EXPECT_TRUE(BuiltInDefaultValue<unsigned long long>::Exists()); // NOLINT - EXPECT_TRUE(BuiltInDefaultValue<signed long long>::Exists()); // NOLINT - EXPECT_TRUE(BuiltInDefaultValue<long long>::Exists()); // NOLINT + EXPECT_TRUE(BuiltInDefaultValue<signed long long>::Exists()); // NOLINT + EXPECT_TRUE(BuiltInDefaultValue<long long>::Exists()); // NOLINT EXPECT_TRUE(BuiltInDefaultValue<float>::Exists()); EXPECT_TRUE(BuiltInDefaultValue<double>::Exists()); } @@ -167,13 +168,13 @@ TEST(BuiltInDefaultValueTest, BoolExists) { // Tests that BuiltInDefaultValue<T>::Get() returns "" when T is a // string type. TEST(BuiltInDefaultValueTest, IsEmptyStringForString) { - EXPECT_EQ("", BuiltInDefaultValue< ::std::string>::Get()); + EXPECT_EQ("", BuiltInDefaultValue<::std::string>::Get()); } // Tests that BuiltInDefaultValue<T>::Exists() returns true when T is a // string type. TEST(BuiltInDefaultValueTest, ExistsForString) { - EXPECT_TRUE(BuiltInDefaultValue< ::std::string>::Exists()); + EXPECT_TRUE(BuiltInDefaultValue<::std::string>::Exists()); } // Tests that BuiltInDefaultValue<const T>::Get() returns the same @@ -208,7 +209,6 @@ class MyNonDefaultConstructible { int value_; }; - TEST(BuiltInDefaultValueTest, ExistsForDefaultConstructibleType) { EXPECT_TRUE(BuiltInDefaultValue<MyDefaultConstructible>::Exists()); } @@ -217,25 +217,19 @@ TEST(BuiltInDefaultValueTest, IsDefaultConstructedForDefaultConstructibleType) { EXPECT_EQ(42, BuiltInDefaultValue<MyDefaultConstructible>::Get().value()); } - TEST(BuiltInDefaultValueTest, DoesNotExistForNonDefaultConstructibleType) { EXPECT_FALSE(BuiltInDefaultValue<MyNonDefaultConstructible>::Exists()); } // Tests that BuiltInDefaultValue<T&>::Get() aborts the program. TEST(BuiltInDefaultValueDeathTest, IsUndefinedForReferences) { - EXPECT_DEATH_IF_SUPPORTED({ - BuiltInDefaultValue<int&>::Get(); - }, ""); - EXPECT_DEATH_IF_SUPPORTED({ - BuiltInDefaultValue<const char&>::Get(); - }, ""); + EXPECT_DEATH_IF_SUPPORTED({ BuiltInDefaultValue<int&>::Get(); }, ""); + EXPECT_DEATH_IF_SUPPORTED({ BuiltInDefaultValue<const char&>::Get(); }, ""); } TEST(BuiltInDefaultValueDeathTest, IsUndefinedForNonDefaultConstructibleType) { - EXPECT_DEATH_IF_SUPPORTED({ - BuiltInDefaultValue<MyNonDefaultConstructible>::Get(); - }, ""); + EXPECT_DEATH_IF_SUPPORTED( + { BuiltInDefaultValue<MyNonDefaultConstructible>::Get(); }, ""); } // Tests that DefaultValue<T>::IsSet() is false initially. @@ -281,26 +275,22 @@ TEST(DefaultValueDeathTest, GetReturnsBuiltInDefaultValueWhenUnset) { EXPECT_EQ(0, DefaultValue<int>::Get()); - EXPECT_DEATH_IF_SUPPORTED({ - DefaultValue<MyNonDefaultConstructible>::Get(); - }, ""); + EXPECT_DEATH_IF_SUPPORTED({ DefaultValue<MyNonDefaultConstructible>::Get(); }, + ""); } TEST(DefaultValueTest, GetWorksForMoveOnlyIfSet) { EXPECT_TRUE(DefaultValue<std::unique_ptr<int>>::Exists()); EXPECT_TRUE(DefaultValue<std::unique_ptr<int>>::Get() == nullptr); - DefaultValue<std::unique_ptr<int>>::SetFactory([] { - return std::unique_ptr<int>(new int(42)); - }); + DefaultValue<std::unique_ptr<int>>::SetFactory( + [] { return std::unique_ptr<int>(new int(42)); }); EXPECT_TRUE(DefaultValue<std::unique_ptr<int>>::Exists()); std::unique_ptr<int> i = DefaultValue<std::unique_ptr<int>>::Get(); EXPECT_EQ(42, *i); } // Tests that DefaultValue<void>::Get() returns void. -TEST(DefaultValueTest, GetWorksForVoid) { - return DefaultValue<void>::Get(); -} +TEST(DefaultValueTest, GetWorksForVoid) { return DefaultValue<void>::Get(); } // Tests using DefaultValue with a reference type. @@ -348,12 +338,9 @@ TEST(DefaultValueOfReferenceDeathTest, GetReturnsBuiltInDefaultValueWhenUnset) { EXPECT_FALSE(DefaultValue<int&>::IsSet()); EXPECT_FALSE(DefaultValue<MyNonDefaultConstructible&>::IsSet()); - EXPECT_DEATH_IF_SUPPORTED({ - DefaultValue<int&>::Get(); - }, ""); - EXPECT_DEATH_IF_SUPPORTED({ - DefaultValue<MyNonDefaultConstructible>::Get(); - }, ""); + EXPECT_DEATH_IF_SUPPORTED({ DefaultValue<int&>::Get(); }, ""); + EXPECT_DEATH_IF_SUPPORTED({ DefaultValue<MyNonDefaultConstructible>::Get(); }, + ""); } // Tests that ActionInterface can be implemented by defining the @@ -433,7 +420,7 @@ class IsNotZero : public ActionInterface<bool(int)> { // NOLINT }; TEST(ActionTest, CanBeConvertedToOtherActionType) { - const Action<bool(int)> a1(new IsNotZero); // NOLINT + const Action<bool(int)> a1(new IsNotZero); // NOLINT const Action<int(char)> a2 = Action<int(char)>(a1); // NOLINT EXPECT_EQ(1, a2.Perform(std::make_tuple('a'))); EXPECT_EQ(0, a2.Perform(std::make_tuple('\0'))); @@ -528,7 +515,7 @@ TEST(ReturnTest, AcceptsStringLiteral) { // Test struct which wraps a vector of integers. Used in // 'SupportsWrapperReturnType' test. struct IntegerVectorWrapper { - std::vector<int> * v; + std::vector<int>* v; IntegerVectorWrapper(std::vector<int>& _v) : v(&_v) {} // NOLINT }; @@ -648,7 +635,9 @@ TEST(ReturnRefTest, IsCovariant) { } template <typename T, typename = decltype(ReturnRef(std::declval<T&&>()))> -bool CanCallReturnRef(T&&) { return true; } +bool CanCallReturnRef(T&&) { + return true; +} bool CanCallReturnRef(Unused) { return false; } // Tests that ReturnRef(v) is working with non-temporaries (T&) @@ -668,7 +657,7 @@ TEST(ReturnRefTest, WorksForNonTemporary) { // Tests that ReturnRef(v) is not working with temporaries (T&&) TEST(ReturnRefTest, DoesNotWorkForTemporary) { - auto scalar_value = []() -> int { return 123; }; + auto scalar_value = []() -> int { return 123; }; EXPECT_FALSE(CanCallReturnRef(scalar_value())); auto non_scalar_value = []() -> std::string { return "ABC"; }; @@ -754,8 +743,7 @@ class MockClass { // return type by default. TEST(DoDefaultTest, ReturnsBuiltInDefaultValueByDefault) { MockClass mock; - EXPECT_CALL(mock, IntFunc(_)) - .WillOnce(DoDefault()); + EXPECT_CALL(mock, IntFunc(_)).WillOnce(DoDefault()); EXPECT_EQ(0, mock.IntFunc(true)); } @@ -763,14 +751,11 @@ TEST(DoDefaultTest, ReturnsBuiltInDefaultValueByDefault) { // the process when there is no built-in default value for the return type. TEST(DoDefaultDeathTest, DiesForUnknowType) { MockClass mock; - EXPECT_CALL(mock, Foo()) - .WillRepeatedly(DoDefault()); + EXPECT_CALL(mock, Foo()).WillRepeatedly(DoDefault()); #if GTEST_HAS_EXCEPTIONS EXPECT_ANY_THROW(mock.Foo()); #else - EXPECT_DEATH_IF_SUPPORTED({ - mock.Foo(); - }, ""); + EXPECT_DEATH_IF_SUPPORTED({ mock.Foo(); }, ""); #endif } @@ -782,16 +767,13 @@ void VoidFunc(bool /* flag */) {} TEST(DoDefaultDeathTest, DiesIfUsedInCompositeAction) { MockClass mock; EXPECT_CALL(mock, IntFunc(_)) - .WillRepeatedly(DoAll(Invoke(VoidFunc), - DoDefault())); + .WillRepeatedly(DoAll(Invoke(VoidFunc), DoDefault())); // Ideally we should verify the error message as well. Sadly, // EXPECT_DEATH() can only capture stderr, while Google Mock's // errors are printed on stdout. Therefore we have to settle for // not verifying the message. - EXPECT_DEATH_IF_SUPPORTED({ - mock.IntFunc(true); - }, ""); + EXPECT_DEATH_IF_SUPPORTED({ mock.IntFunc(true); }, ""); } // Tests that DoDefault() returns the default value set by @@ -799,8 +781,7 @@ TEST(DoDefaultDeathTest, DiesIfUsedInCompositeAction) { TEST(DoDefaultTest, ReturnsUserSpecifiedPerTypeDefaultValueWhenThereIsOne) { DefaultValue<int>::Set(1); MockClass mock; - EXPECT_CALL(mock, IntFunc(_)) - .WillOnce(DoDefault()); + EXPECT_CALL(mock, IntFunc(_)).WillOnce(DoDefault()); EXPECT_EQ(1, mock.IntFunc(false)); DefaultValue<int>::Clear(); } @@ -808,20 +789,19 @@ TEST(DoDefaultTest, ReturnsUserSpecifiedPerTypeDefaultValueWhenThereIsOne) { // Tests that DoDefault() does the action specified by ON_CALL(). TEST(DoDefaultTest, DoesWhatOnCallSpecifies) { MockClass mock; - ON_CALL(mock, IntFunc(_)) - .WillByDefault(Return(2)); - EXPECT_CALL(mock, IntFunc(_)) - .WillOnce(DoDefault()); + ON_CALL(mock, IntFunc(_)).WillByDefault(Return(2)); + EXPECT_CALL(mock, IntFunc(_)).WillOnce(DoDefault()); EXPECT_EQ(2, mock.IntFunc(false)); } // Tests that using DoDefault() in ON_CALL() leads to a run-time failure. TEST(DoDefaultTest, CannotBeUsedInOnCall) { MockClass mock; - EXPECT_NONFATAL_FAILURE({ // NOLINT - ON_CALL(mock, IntFunc(_)) - .WillByDefault(DoDefault()); - }, "DoDefault() cannot be used in ON_CALL()"); + EXPECT_NONFATAL_FAILURE( + { // NOLINT + ON_CALL(mock, IntFunc(_)).WillByDefault(DoDefault()); + }, + "DoDefault() cannot be used in ON_CALL()"); } // Tests that SetArgPointee<N>(v) sets the variable pointed to by @@ -868,7 +848,7 @@ TEST(SetArgPointeeTest, AcceptsWideStringLiteral) { a.Perform(std::make_tuple(&ptr)); EXPECT_STREQ(L"world", ptr); -# if GTEST_HAS_STD_WSTRING +#if GTEST_HAS_STD_WSTRING typedef void MyStringFunction(std::wstring*); Action<MyStringFunction> a2 = SetArgPointee<0>(L"world"); @@ -876,7 +856,7 @@ TEST(SetArgPointeeTest, AcceptsWideStringLiteral) { a2.Perform(std::make_tuple(&str)); EXPECT_EQ(L"world", str); -# endif +#endif } // Tests that SetArgPointee<N>() accepts a char pointer. @@ -907,7 +887,7 @@ TEST(SetArgPointeeTest, AcceptsWideCharPointer) { a.Perform(std::make_tuple(true, &ptr)); EXPECT_EQ(hi, ptr); -# if GTEST_HAS_STD_WSTRING +#if GTEST_HAS_STD_WSTRING typedef void MyStringFunction(bool, std::wstring*); wchar_t world_array[] = L"world"; @@ -916,7 +896,7 @@ TEST(SetArgPointeeTest, AcceptsWideCharPointer) { std::wstring str; a2.Perform(std::make_tuple(true, &str)); EXPECT_EQ(world_array, str); -# endif +#endif } // Tests that SetArgumentPointee<N>(v) sets the variable pointed to by @@ -1079,7 +1059,6 @@ TEST(AssignTest, CompatibleTypes) { EXPECT_DOUBLE_EQ(5, x); } - // Tests using WithArgs and with an action that takes 1 argument. TEST(WithArgsTest, OneArg) { Action<bool(double x, int n)> a = WithArgs<1>(Invoke(Unary)); // NOLINT @@ -1235,7 +1214,7 @@ TEST(ByRefTest, IsCopyable) { TEST(ByRefTest, ConstValue) { const int n = 0; // int& ref = ByRef(n); // This shouldn't compile - we have a - // negative compilation test to catch it. + // negative compilation test to catch it. const int& const_ref = ByRef(n); EXPECT_EQ(&n, &const_ref); } @@ -1260,7 +1239,7 @@ TEST(ByRefTest, ExplicitType) { EXPECT_EQ(&n, &r1); // ByRef<char>(n); // This shouldn't compile - we have a negative - // compilation test to catch it. + // compilation test to catch it. Derived d; Derived& r2 = ByRef<Derived>(d); @@ -1375,9 +1354,10 @@ TEST(MockMethodTest, CanReturnMoveOnlyValue_DoAllReturn) { MockClass mock; std::unique_ptr<int> i(new int(19)); EXPECT_CALL(mock_function, Call()); - EXPECT_CALL(mock, MakeUnique()).WillOnce(DoAll( - InvokeWithoutArgs(&mock_function, &testing::MockFunction<void()>::Call), - Return(ByMove(std::move(i))))); + EXPECT_CALL(mock, MakeUnique()) + .WillOnce(DoAll(InvokeWithoutArgs(&mock_function, + &testing::MockFunction<void()>::Call), + Return(ByMove(std::move(i))))); std::unique_ptr<int> result1 = mock.MakeUnique(); EXPECT_EQ(19, *result1); @@ -1387,9 +1367,8 @@ TEST(MockMethodTest, CanReturnMoveOnlyValue_Invoke) { MockClass mock; // Check default value - DefaultValue<std::unique_ptr<int>>::SetFactory([] { - return std::unique_ptr<int>(new int(42)); - }); + DefaultValue<std::unique_ptr<int>>::SetFactory( + [] { return std::unique_ptr<int>(new int(42)); }); EXPECT_EQ(42, *mock.MakeUnique()); EXPECT_CALL(mock, MakeUnique()).WillRepeatedly(Invoke(UniquePtrSource)); @@ -1449,7 +1428,6 @@ TEST(MockMethodTest, CanTakeMoveOnlyValue) { EXPECT_EQ(42, *saved); } - // Tests for std::function based action. int Add(int val, int& ref, int* ptr) { // NOLINT @@ -1463,7 +1441,9 @@ int Deref(std::unique_ptr<int> ptr) { return *ptr; } struct Double { template <typename T> - T operator()(T t) { return 2 * t; } + T operator()(T t) { + return 2 * t; + } }; std::unique_ptr<int> UniqueInt(int i) { @@ -1532,8 +1512,9 @@ TEST(FunctorActionTest, TypeConversion) { TEST(FunctorActionTest, UnusedArguments) { // Verify that users can ignore uninteresting arguments. - Action<int(int, double y, double z)> a = - [](int i, Unused, Unused) { return 2 * i; }; + Action<int(int, double y, double z)> a = [](int i, Unused, Unused) { + return 2 * i; + }; std::tuple<int, double, double> dummy = std::make_tuple(3, 7.3, 9.44); EXPECT_EQ(6, a.Perform(dummy)); } @@ -1552,9 +1533,7 @@ TEST(MoveOnlyArgumentsTest, ReturningActions) { EXPECT_EQ(x, 3); } -ACTION(ReturnArity) { - return std::tuple_size<args_type>::value; -} +ACTION(ReturnArity) { return std::tuple_size<args_type>::value; } TEST(ActionMacro, LargeArity) { EXPECT_EQ( @@ -1577,7 +1556,6 @@ TEST(ActionMacro, LargeArity) { #ifdef _MSC_VER #if _MSC_VER == 1900 -# pragma warning(pop) +#pragma warning(pop) #endif #endif - diff --git a/googlemock/test/gmock-cardinalities_test.cc b/googlemock/test/gmock-cardinalities_test.cc index ca97cae..e7efd97 100644 --- a/googlemock/test/gmock-cardinalities_test.cc +++ b/googlemock/test/gmock-cardinalities_test.cc @@ -27,14 +27,13 @@ // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - // Google Mock - a framework for writing C++ mock classes. // // This file tests the built-in cardinalities. #include "gmock/gmock.h" -#include "gtest/gtest.h" #include "gtest/gtest-spi.h" +#include "gtest/gtest.h" namespace { @@ -59,9 +58,7 @@ class MockFoo { }; // Tests that Cardinality objects can be default constructed. -TEST(CardinalityTest, IsDefaultConstructable) { - Cardinality c; -} +TEST(CardinalityTest, IsDefaultConstructable) { Cardinality c; } // Tests that Cardinality objects are copyable. TEST(CardinalityTest, IsCopyable) { @@ -119,8 +116,7 @@ TEST(AnyNumber, Works) { stringstream ss; c.DescribeTo(&ss); - EXPECT_PRED_FORMAT2(IsSubstring, "called any number of times", - ss.str()); + EXPECT_PRED_FORMAT2(IsSubstring, "called any number of times", ss.str()); } TEST(AnyNumberTest, HasCorrectBounds) { @@ -132,9 +128,11 @@ TEST(AnyNumberTest, HasCorrectBounds) { // Tests AtLeast(n). TEST(AtLeastTest, OnNegativeNumber) { - EXPECT_NONFATAL_FAILURE({ // NOLINT - AtLeast(-1); - }, "The invocation lower bound must be >= 0"); + EXPECT_NONFATAL_FAILURE( + { // NOLINT + AtLeast(-1); + }, + "The invocation lower bound must be >= 0"); } TEST(AtLeastTest, OnZero) { @@ -147,8 +145,7 @@ TEST(AtLeastTest, OnZero) { stringstream ss; c.DescribeTo(&ss); - EXPECT_PRED_FORMAT2(IsSubstring, "any number of times", - ss.str()); + EXPECT_PRED_FORMAT2(IsSubstring, "any number of times", ss.str()); } TEST(AtLeastTest, OnPositiveNumber) { @@ -164,18 +161,15 @@ TEST(AtLeastTest, OnPositiveNumber) { stringstream ss1; AtLeast(1).DescribeTo(&ss1); - EXPECT_PRED_FORMAT2(IsSubstring, "at least once", - ss1.str()); + EXPECT_PRED_FORMAT2(IsSubstring, "at least once", ss1.str()); stringstream ss2; c.DescribeTo(&ss2); - EXPECT_PRED_FORMAT2(IsSubstring, "at least twice", - ss2.str()); + EXPECT_PRED_FORMAT2(IsSubstring, "at least twice", ss2.str()); stringstream ss3; AtLeast(3).DescribeTo(&ss3); - EXPECT_PRED_FORMAT2(IsSubstring, "at least 3 times", - ss3.str()); + EXPECT_PRED_FORMAT2(IsSubstring, "at least 3 times", ss3.str()); } TEST(AtLeastTest, HasCorrectBounds) { @@ -187,9 +181,11 @@ TEST(AtLeastTest, HasCorrectBounds) { // Tests AtMost(n). TEST(AtMostTest, OnNegativeNumber) { - EXPECT_NONFATAL_FAILURE({ // NOLINT - AtMost(-1); - }, "The invocation upper bound must be >= 0"); + EXPECT_NONFATAL_FAILURE( + { // NOLINT + AtMost(-1); + }, + "The invocation upper bound must be >= 0"); } TEST(AtMostTest, OnZero) { @@ -202,8 +198,7 @@ TEST(AtMostTest, OnZero) { stringstream ss; c.DescribeTo(&ss); - EXPECT_PRED_FORMAT2(IsSubstring, "never called", - ss.str()); + EXPECT_PRED_FORMAT2(IsSubstring, "never called", ss.str()); } TEST(AtMostTest, OnPositiveNumber) { @@ -219,18 +214,15 @@ TEST(AtMostTest, OnPositiveNumber) { stringstream ss1; AtMost(1).DescribeTo(&ss1); - EXPECT_PRED_FORMAT2(IsSubstring, "called at most once", - ss1.str()); + EXPECT_PRED_FORMAT2(IsSubstring, "called at most once", ss1.str()); stringstream ss2; c.DescribeTo(&ss2); - EXPECT_PRED_FORMAT2(IsSubstring, "called at most twice", - ss2.str()); + EXPECT_PRED_FORMAT2(IsSubstring, "called at most twice", ss2.str()); stringstream ss3; AtMost(3).DescribeTo(&ss3); - EXPECT_PRED_FORMAT2(IsSubstring, "called at most 3 times", - ss3.str()); + EXPECT_PRED_FORMAT2(IsSubstring, "called at most 3 times", ss3.str()); } TEST(AtMostTest, HasCorrectBounds) { @@ -242,22 +234,28 @@ TEST(AtMostTest, HasCorrectBounds) { // Tests Between(m, n). TEST(BetweenTest, OnNegativeStart) { - EXPECT_NONFATAL_FAILURE({ // NOLINT - Between(-1, 2); - }, "The invocation lower bound must be >= 0, but is actually -1"); + EXPECT_NONFATAL_FAILURE( + { // NOLINT + Between(-1, 2); + }, + "The invocation lower bound must be >= 0, but is actually -1"); } TEST(BetweenTest, OnNegativeEnd) { - EXPECT_NONFATAL_FAILURE({ // NOLINT - Between(1, -2); - }, "The invocation upper bound must be >= 0, but is actually -2"); + EXPECT_NONFATAL_FAILURE( + { // NOLINT + Between(1, -2); + }, + "The invocation upper bound must be >= 0, but is actually -2"); } TEST(BetweenTest, OnStartBiggerThanEnd) { - EXPECT_NONFATAL_FAILURE({ // NOLINT - Between(2, 1); - }, "The invocation upper bound (1) must be >= " - "the invocation lower bound (2)"); + EXPECT_NONFATAL_FAILURE( + { // NOLINT + Between(2, 1); + }, + "The invocation upper bound (1) must be >= " + "the invocation lower bound (2)"); } TEST(BetweenTest, OnZeroStartAndZeroEnd) { @@ -271,8 +269,7 @@ TEST(BetweenTest, OnZeroStartAndZeroEnd) { stringstream ss; c.DescribeTo(&ss); - EXPECT_PRED_FORMAT2(IsSubstring, "never called", - ss.str()); + EXPECT_PRED_FORMAT2(IsSubstring, "never called", ss.str()); } TEST(BetweenTest, OnZeroStartAndNonZeroEnd) { @@ -289,8 +286,7 @@ TEST(BetweenTest, OnZeroStartAndNonZeroEnd) { stringstream ss; c.DescribeTo(&ss); - EXPECT_PRED_FORMAT2(IsSubstring, "called at most twice", - ss.str()); + EXPECT_PRED_FORMAT2(IsSubstring, "called at most twice", ss.str()); } TEST(BetweenTest, OnSameStartAndEnd) { @@ -307,8 +303,7 @@ TEST(BetweenTest, OnSameStartAndEnd) { stringstream ss; c.DescribeTo(&ss); - EXPECT_PRED_FORMAT2(IsSubstring, "called 3 times", - ss.str()); + EXPECT_PRED_FORMAT2(IsSubstring, "called 3 times", ss.str()); } TEST(BetweenTest, OnDifferentStartAndEnd) { @@ -328,8 +323,7 @@ TEST(BetweenTest, OnDifferentStartAndEnd) { stringstream ss; c.DescribeTo(&ss); - EXPECT_PRED_FORMAT2(IsSubstring, "called between 3 and 5 times", - ss.str()); + EXPECT_PRED_FORMAT2(IsSubstring, "called between 3 and 5 times", ss.str()); } TEST(BetweenTest, HasCorrectBounds) { @@ -341,9 +335,11 @@ TEST(BetweenTest, HasCorrectBounds) { // Tests Exactly(n). TEST(ExactlyTest, OnNegativeNumber) { - EXPECT_NONFATAL_FAILURE({ // NOLINT - Exactly(-1); - }, "The invocation lower bound must be >= 0"); + EXPECT_NONFATAL_FAILURE( + { // NOLINT + Exactly(-1); + }, + "The invocation lower bound must be >= 0"); } TEST(ExactlyTest, OnZero) { @@ -356,8 +352,7 @@ TEST(ExactlyTest, OnZero) { stringstream ss; c.DescribeTo(&ss); - EXPECT_PRED_FORMAT2(IsSubstring, "never called", - ss.str()); + EXPECT_PRED_FORMAT2(IsSubstring, "never called", ss.str()); } TEST(ExactlyTest, OnPositiveNumber) { @@ -370,18 +365,15 @@ TEST(ExactlyTest, OnPositiveNumber) { stringstream ss1; Exactly(1).DescribeTo(&ss1); - EXPECT_PRED_FORMAT2(IsSubstring, "called once", - ss1.str()); + EXPECT_PRED_FORMAT2(IsSubstring, "called once", ss1.str()); stringstream ss2; c.DescribeTo(&ss2); - EXPECT_PRED_FORMAT2(IsSubstring, "called twice", - ss2.str()); + EXPECT_PRED_FORMAT2(IsSubstring, "called twice", ss2.str()); stringstream ss3; Exactly(3).DescribeTo(&ss3); - EXPECT_PRED_FORMAT2(IsSubstring, "called 3 times", - ss3.str()); + EXPECT_PRED_FORMAT2(IsSubstring, "called 3 times", ss3.str()); } TEST(ExactlyTest, HasCorrectBounds) { diff --git a/googlemock/test/gmock-function-mocker_test.cc b/googlemock/test/gmock-function-mocker_test.cc index cf76fa9..dc750a3 100644 --- a/googlemock/test/gmock-function-mocker_test.cc +++ b/googlemock/test/gmock-function-mocker_test.cc @@ -27,7 +27,6 @@ // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - // Google Mock - a framework for writing C++ mock classes. // // This file tests the function mocker classes. @@ -37,7 +36,7 @@ // MSDN says the header file to be included for STDMETHOD is BaseTyps.h but // we are getting compiler errors if we use basetyps.h, hence including // objbase.h for definition of STDMETHOD. -# include <objbase.h> +#include <objbase.h> #endif // GTEST_OS_WINDOWS #include <functional> @@ -65,7 +64,7 @@ using testing::Return; using testing::ReturnRef; using testing::TypedEq; -template<typename T> +template <typename T> class TemplatedCopyable { public: TemplatedCopyable() {} @@ -82,7 +81,7 @@ class FooInterface { virtual int Nullary() = 0; virtual bool Unary(int x) = 0; - virtual long Binary(short x, int y) = 0; // NOLINT + virtual long Binary(short x, int y) = 0; // NOLINT virtual int Decimal(bool b, char c, short d, int e, long f, // NOLINT float g, double h, unsigned i, char* j, const std::string& k) = 0; @@ -133,8 +132,8 @@ class FooInterface { // signature. This was fixed in Visual Studio 2008. However, the compiler // still emits a warning that alerts about this change in behavior. #ifdef _MSC_VER -# pragma warning(push) -# pragma warning(disable : 4373) +#pragma warning(push) +#pragma warning(disable : 4373) #endif class MockFoo : public FooInterface { public: @@ -279,7 +278,7 @@ class LegacyMockFoo : public FooInterface { }; #ifdef _MSC_VER -# pragma warning(pop) +#pragma warning(pop) #endif template <class T> @@ -595,10 +594,8 @@ TYPED_TEST(TemplateMockTest, Works) { .WillOnce(Return(0)); EXPECT_CALL(mock, Push(_)); int n = 5; - EXPECT_CALL(mock, GetTop()) - .WillOnce(ReturnRef(n)); - EXPECT_CALL(mock, Pop()) - .Times(AnyNumber()); + EXPECT_CALL(mock, GetTop()).WillOnce(ReturnRef(n)); + EXPECT_CALL(mock, Pop()).Times(AnyNumber()); EXPECT_EQ(0, mock.GetSize()); mock.Push(5); @@ -612,10 +609,8 @@ TYPED_TEST(TemplateMockTest, MethodWithCommaInReturnTypeWorks) { TypeParam mock; const std::map<int, int> a_map; - EXPECT_CALL(mock, ReturnTypeWithComma()) - .WillOnce(Return(a_map)); - EXPECT_CALL(mock, ReturnTypeWithComma(1)) - .WillOnce(Return(a_map)); + EXPECT_CALL(mock, ReturnTypeWithComma()).WillOnce(Return(a_map)); + EXPECT_CALL(mock, ReturnTypeWithComma(1)).WillOnce(Return(a_map)); EXPECT_EQ(a_map, mock.ReturnTypeWithComma()); EXPECT_EQ(a_map, mock.ReturnTypeWithComma(1)); @@ -685,10 +680,8 @@ TYPED_TEST(TemplateMockTestWithCallType, Works) { .WillOnce(Return(0)); EXPECT_CALL(mock, Push(_)); int n = 5; - EXPECT_CALL(mock, GetTop()) - .WillOnce(ReturnRef(n)); - EXPECT_CALL(mock, Pop()) - .Times(AnyNumber()); + EXPECT_CALL(mock, GetTop()).WillOnce(ReturnRef(n)); + EXPECT_CALL(mock, Pop()).Times(AnyNumber()); EXPECT_EQ(0, mock.GetSize()); mock.Push(5); @@ -747,9 +740,9 @@ TYPED_TEST(OverloadedMockMethodTest, CanOverloadOnArgNumberInMacroBody) { EXPECT_TRUE(mock.Overloaded(true, 1)); } -#define MY_MOCK_METHODS2_ \ - MOCK_CONST_METHOD1(Overloaded, int(int n)); \ - MOCK_METHOD1(Overloaded, int(int n)) +#define MY_MOCK_METHODS2_ \ + MOCK_CONST_METHOD1(Overloaded, int(int n)); \ + MOCK_METHOD1(Overloaded, int(int n)) class MockOverloadedOnConstness { public: @@ -779,9 +772,7 @@ TEST(MockMethodMockFunctionTest, WorksForVoidNullary) { TEST(MockMethodMockFunctionTest, WorksForNonVoidNullary) { MockFunction<int()> foo; - EXPECT_CALL(foo, Call()) - .WillOnce(Return(1)) - .WillOnce(Return(2)); + EXPECT_CALL(foo, Call()).WillOnce(Return(1)).WillOnce(Return(2)); EXPECT_EQ(1, foo.Call()); EXPECT_EQ(2, foo.Call()); } @@ -794,19 +785,17 @@ TEST(MockMethodMockFunctionTest, WorksForVoidUnary) { TEST(MockMethodMockFunctionTest, WorksForNonVoidBinary) { MockFunction<int(bool, int)> foo; - EXPECT_CALL(foo, Call(false, 42)) - .WillOnce(Return(1)) - .WillOnce(Return(2)); - EXPECT_CALL(foo, Call(true, Ge(100))) - .WillOnce(Return(3)); + EXPECT_CALL(foo, Call(false, 42)).WillOnce(Return(1)).WillOnce(Return(2)); + EXPECT_CALL(foo, Call(true, Ge(100))).WillOnce(Return(3)); EXPECT_EQ(1, foo.Call(false, 42)); EXPECT_EQ(2, foo.Call(false, 42)); EXPECT_EQ(3, foo.Call(true, 120)); } TEST(MockMethodMockFunctionTest, WorksFor10Arguments) { - MockFunction<int(bool a0, char a1, int a2, int a3, int a4, - int a5, int a6, char a7, int a8, bool a9)> foo; + MockFunction<int(bool a0, char a1, int a2, int a3, int a4, int a5, int a6, + char a7, int a8, bool a9)> + foo; EXPECT_CALL(foo, Call(_, 'a', _, _, _, _, _, _, _, _)) .WillOnce(Return(1)) .WillOnce(Return(2)); @@ -816,9 +805,7 @@ TEST(MockMethodMockFunctionTest, WorksFor10Arguments) { TEST(MockMethodMockFunctionTest, AsStdFunction) { MockFunction<int(int)> foo; - auto call = [](const std::function<int(int)> &f, int i) { - return f(i); - }; + auto call = [](const std::function<int(int)>& f, int i) { return f(i); }; EXPECT_CALL(foo, Call(1)).WillOnce(Return(-1)); EXPECT_CALL(foo, Call(2)).WillOnce(Return(-2)); EXPECT_EQ(-1, call(foo.AsStdFunction(), 1)); @@ -836,10 +823,8 @@ TEST(MockMethodMockFunctionTest, AsStdFunctionReturnsReference) { } TEST(MockMethodMockFunctionTest, AsStdFunctionWithReferenceParameter) { - MockFunction<int(int &)> foo; - auto call = [](const std::function<int(int& )> &f, int &i) { - return f(i); - }; + MockFunction<int(int&)> foo; + auto call = [](const std::function<int(int&)>& f, int& i) { return f(i); }; int i = 42; EXPECT_CALL(foo, Call(i)).WillOnce(Return(-1)); EXPECT_EQ(-1, call(foo.AsStdFunction(), i)); @@ -888,8 +873,7 @@ TYPED_TEST( } template <typename F> -struct AlternateCallable { -}; +struct AlternateCallable {}; TYPED_TEST(MockMethodMockFunctionSignatureTest, IsMockFunctionTemplateArgumentDeducedForAlternateCallable) { @@ -898,16 +882,14 @@ TYPED_TEST(MockMethodMockFunctionSignatureTest, EXPECT_TRUE(IsMockFunctionTemplateArgumentDeducedTo<TypeParam>(foo)); } -TYPED_TEST( - MockMethodMockFunctionSignatureTest, - IsMockFunctionCallMethodSignatureTheSameForAlternateCallable) { +TYPED_TEST(MockMethodMockFunctionSignatureTest, + IsMockFunctionCallMethodSignatureTheSameForAlternateCallable) { using ForRawSignature = decltype(&MockFunction<TypeParam>::Call); using ForStdFunction = decltype(&MockFunction<std::function<TypeParam>>::Call); EXPECT_TRUE((std::is_same<ForRawSignature, ForStdFunction>::value)); } - struct MockMethodSizes0 { MOCK_METHOD(void, func, ()); }; @@ -925,22 +907,21 @@ struct MockMethodSizes4 { }; struct LegacyMockMethodSizes0 { - MOCK_METHOD0(func, void()); + MOCK_METHOD0(func, void()); }; struct LegacyMockMethodSizes1 { - MOCK_METHOD1(func, void(int)); + MOCK_METHOD1(func, void(int)); }; struct LegacyMockMethodSizes2 { - MOCK_METHOD2(func, void(int, int)); + MOCK_METHOD2(func, void(int, int)); }; struct LegacyMockMethodSizes3 { - MOCK_METHOD3(func, void(int, int, int)); + MOCK_METHOD3(func, void(int, int, int)); }; struct LegacyMockMethodSizes4 { - MOCK_METHOD4(func, void(int, int, int, int)); + MOCK_METHOD4(func, void(int, int, int, int)); }; - TEST(MockMethodMockFunctionTest, MockMethodSizeOverhead) { EXPECT_EQ(sizeof(MockMethodSizes0), sizeof(MockMethodSizes1)); EXPECT_EQ(sizeof(MockMethodSizes0), sizeof(MockMethodSizes2)); diff --git a/googlemock/test/gmock-internal-utils_test.cc b/googlemock/test/gmock-internal-utils_test.cc index 800ee8a..932bece 100644 --- a/googlemock/test/gmock-internal-utils_test.cc +++ b/googlemock/test/gmock-internal-utils_test.cc @@ -27,7 +27,6 @@ // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - // Google Mock - a framework for writing C++ mock classes. // // This file tests the internal utilities. @@ -58,7 +57,7 @@ #undef GTEST_IMPLEMENTATION_ #if GTEST_OS_CYGWIN -# include <sys/types.h> // For ssize_t. NOLINT +#include <sys/types.h> // For ssize_t. NOLINT #endif namespace proto2 { @@ -155,19 +154,19 @@ TEST(KindOfTest, Bool) { } TEST(KindOfTest, Integer) { - EXPECT_EQ(kInteger, GMOCK_KIND_OF_(char)); // NOLINT - EXPECT_EQ(kInteger, GMOCK_KIND_OF_(signed char)); // NOLINT - EXPECT_EQ(kInteger, GMOCK_KIND_OF_(unsigned char)); // NOLINT - EXPECT_EQ(kInteger, GMOCK_KIND_OF_(short)); // NOLINT - EXPECT_EQ(kInteger, GMOCK_KIND_OF_(unsigned short)); // NOLINT - EXPECT_EQ(kInteger, GMOCK_KIND_OF_(int)); // NOLINT - EXPECT_EQ(kInteger, GMOCK_KIND_OF_(unsigned int)); // NOLINT - EXPECT_EQ(kInteger, GMOCK_KIND_OF_(long)); // NOLINT - EXPECT_EQ(kInteger, GMOCK_KIND_OF_(unsigned long)); // NOLINT - EXPECT_EQ(kInteger, GMOCK_KIND_OF_(long long)); // NOLINT + EXPECT_EQ(kInteger, GMOCK_KIND_OF_(char)); // NOLINT + EXPECT_EQ(kInteger, GMOCK_KIND_OF_(signed char)); // NOLINT + EXPECT_EQ(kInteger, GMOCK_KIND_OF_(unsigned char)); // NOLINT + EXPECT_EQ(kInteger, GMOCK_KIND_OF_(short)); // NOLINT + EXPECT_EQ(kInteger, GMOCK_KIND_OF_(unsigned short)); // NOLINT + EXPECT_EQ(kInteger, GMOCK_KIND_OF_(int)); // NOLINT + EXPECT_EQ(kInteger, GMOCK_KIND_OF_(unsigned int)); // NOLINT + EXPECT_EQ(kInteger, GMOCK_KIND_OF_(long)); // NOLINT + EXPECT_EQ(kInteger, GMOCK_KIND_OF_(unsigned long)); // NOLINT + EXPECT_EQ(kInteger, GMOCK_KIND_OF_(long long)); // NOLINT EXPECT_EQ(kInteger, GMOCK_KIND_OF_(unsigned long long)); // NOLINT - EXPECT_EQ(kInteger, GMOCK_KIND_OF_(wchar_t)); // NOLINT - EXPECT_EQ(kInteger, GMOCK_KIND_OF_(size_t)); // NOLINT + EXPECT_EQ(kInteger, GMOCK_KIND_OF_(wchar_t)); // NOLINT + EXPECT_EQ(kInteger, GMOCK_KIND_OF_(size_t)); // NOLINT #if GTEST_OS_LINUX || GTEST_OS_MAC || GTEST_OS_CYGWIN // ssize_t is not defined on Windows and possibly some other OSes. EXPECT_EQ(kInteger, GMOCK_KIND_OF_(ssize_t)); // NOLINT @@ -175,15 +174,15 @@ TEST(KindOfTest, Integer) { } TEST(KindOfTest, FloatingPoint) { - EXPECT_EQ(kFloatingPoint, GMOCK_KIND_OF_(float)); // NOLINT - EXPECT_EQ(kFloatingPoint, GMOCK_KIND_OF_(double)); // NOLINT + EXPECT_EQ(kFloatingPoint, GMOCK_KIND_OF_(float)); // NOLINT + EXPECT_EQ(kFloatingPoint, GMOCK_KIND_OF_(double)); // NOLINT EXPECT_EQ(kFloatingPoint, GMOCK_KIND_OF_(long double)); // NOLINT } TEST(KindOfTest, Other) { - EXPECT_EQ(kOther, GMOCK_KIND_OF_(void*)); // NOLINT + EXPECT_EQ(kOther, GMOCK_KIND_OF_(void*)); // NOLINT EXPECT_EQ(kOther, GMOCK_KIND_OF_(char**)); // NOLINT - EXPECT_EQ(kOther, GMOCK_KIND_OF_(Base)); // NOLINT + EXPECT_EQ(kOther, GMOCK_KIND_OF_(Base)); // NOLINT } // Tests LosslessArithmeticConvertible<T, U>. @@ -214,26 +213,26 @@ TEST(LosslessArithmeticConvertibleTest, IntegerToInteger) { EXPECT_TRUE((LosslessArithmeticConvertible<unsigned char, int>::value)); // Unsigned => larger unsigned is fine. - EXPECT_TRUE((LosslessArithmeticConvertible< - unsigned short, uint64_t>::value)); // NOLINT + EXPECT_TRUE((LosslessArithmeticConvertible<unsigned short, + uint64_t>::value)); // NOLINT // Signed => unsigned is not fine. - EXPECT_FALSE((LosslessArithmeticConvertible< - short, uint64_t>::value)); // NOLINT - EXPECT_FALSE((LosslessArithmeticConvertible< - signed char, unsigned int>::value)); // NOLINT + EXPECT_FALSE( + (LosslessArithmeticConvertible<short, uint64_t>::value)); // NOLINT + EXPECT_FALSE((LosslessArithmeticConvertible<signed char, + unsigned int>::value)); // NOLINT // Same size and same signedness: fine too. - EXPECT_TRUE((LosslessArithmeticConvertible< - unsigned char, unsigned char>::value)); + EXPECT_TRUE( + (LosslessArithmeticConvertible<unsigned char, unsigned char>::value)); EXPECT_TRUE((LosslessArithmeticConvertible<int, int>::value)); EXPECT_TRUE((LosslessArithmeticConvertible<wchar_t, wchar_t>::value)); - EXPECT_TRUE((LosslessArithmeticConvertible< - unsigned long, unsigned long>::value)); // NOLINT + EXPECT_TRUE((LosslessArithmeticConvertible<unsigned long, + unsigned long>::value)); // NOLINT // Same size, different signedness: not fine. - EXPECT_FALSE((LosslessArithmeticConvertible< - unsigned char, signed char>::value)); + EXPECT_FALSE( + (LosslessArithmeticConvertible<unsigned char, signed char>::value)); EXPECT_FALSE((LosslessArithmeticConvertible<int, unsigned int>::value)); EXPECT_FALSE((LosslessArithmeticConvertible<uint64_t, int64_t>::value)); @@ -248,8 +247,8 @@ TEST(LosslessArithmeticConvertibleTest, IntegerToFloatingPoint) { // the format of the latter is implementation-defined. EXPECT_FALSE((LosslessArithmeticConvertible<char, float>::value)); EXPECT_FALSE((LosslessArithmeticConvertible<int, double>::value)); - EXPECT_FALSE((LosslessArithmeticConvertible< - short, long double>::value)); // NOLINT + EXPECT_FALSE( + (LosslessArithmeticConvertible<short, long double>::value)); // NOLINT } TEST(LosslessArithmeticConvertibleTest, FloatingPointToBool) { @@ -277,7 +276,7 @@ TEST(LosslessArithmeticConvertibleTest, FloatingPointToFloatingPoint) { EXPECT_FALSE((LosslessArithmeticConvertible<double, float>::value)); GTEST_INTENTIONAL_CONST_COND_PUSH_() if (sizeof(double) == sizeof(long double)) { // NOLINT - GTEST_INTENTIONAL_CONST_COND_POP_() + GTEST_INTENTIONAL_CONST_COND_POP_() // In some implementations (e.g. MSVC), double and long double // have the same size. EXPECT_TRUE((LosslessArithmeticConvertible<long double, double>::value)); @@ -296,7 +295,7 @@ TEST(TupleMatchesTest, WorksForSize0) { } TEST(TupleMatchesTest, WorksForSize1) { - std::tuple<Matcher<int> > matchers(Eq(1)); + std::tuple<Matcher<int>> matchers(Eq(1)); std::tuple<int> values1(1), values2(2); EXPECT_TRUE(TupleMatches(matchers, values1)); @@ -304,7 +303,7 @@ TEST(TupleMatchesTest, WorksForSize1) { } TEST(TupleMatchesTest, WorksForSize2) { - std::tuple<Matcher<int>, Matcher<char> > matchers(Eq(1), Eq('a')); + std::tuple<Matcher<int>, Matcher<char>> matchers(Eq(1), Eq('a')); std::tuple<int, char> values1(1, 'a'), values2(1, 'b'), values3(2, 'a'), values4(2, 'b'); @@ -317,7 +316,7 @@ TEST(TupleMatchesTest, WorksForSize2) { TEST(TupleMatchesTest, WorksForSize5) { std::tuple<Matcher<int>, Matcher<char>, Matcher<bool>, Matcher<long>, // NOLINT - Matcher<std::string> > + Matcher<std::string>> matchers(Eq(1), Eq('a'), Eq(true), Eq(2L), Eq("hi")); std::tuple<int, char, bool, long, std::string> // NOLINT values1(1, 'a', true, 2L, "hi"), values2(1, 'a', true, 2L, "hello"), @@ -336,13 +335,10 @@ TEST(AssertTest, SucceedsOnTrue) { // Tests that Assert(false, ...) generates a fatal failure. TEST(AssertTest, FailsFatallyOnFalse) { - EXPECT_DEATH_IF_SUPPORTED({ - Assert(false, __FILE__, __LINE__, "This should fail."); - }, ""); + EXPECT_DEATH_IF_SUPPORTED( + { Assert(false, __FILE__, __LINE__, "This should fail."); }, ""); - EXPECT_DEATH_IF_SUPPORTED({ - Assert(false, __FILE__, __LINE__); - }, ""); + EXPECT_DEATH_IF_SUPPORTED({ Assert(false, __FILE__, __LINE__); }, ""); } // Tests that Expect(true, ...) succeeds. @@ -353,13 +349,17 @@ TEST(ExpectTest, SucceedsOnTrue) { // Tests that Expect(false, ...) generates a non-fatal failure. TEST(ExpectTest, FailsNonfatallyOnFalse) { - EXPECT_NONFATAL_FAILURE({ // NOLINT - Expect(false, __FILE__, __LINE__, "This should fail."); - }, "This should fail"); + EXPECT_NONFATAL_FAILURE( + { // NOLINT + Expect(false, __FILE__, __LINE__, "This should fail."); + }, + "This should fail"); - EXPECT_NONFATAL_FAILURE({ // NOLINT - Expect(false, __FILE__, __LINE__); - }, "Expectation failed"); + EXPECT_NONFATAL_FAILURE( + { // NOLINT + Expect(false, __FILE__, __LINE__); + }, + "Expectation failed"); } // Tests LogIsVisible(). @@ -404,11 +404,11 @@ void TestLogWithSeverity(const std::string& verbosity, LogSeverity severity, CaptureStdout(); Log(severity, "Test log.\n", 0); if (should_print) { - EXPECT_THAT(GetCapturedStdout().c_str(), - ContainsRegex( - severity == kWarning ? - "^\nGMOCK WARNING:\nTest log\\.\nStack trace:\n" : - "^\nTest log\\.\nStack trace:\n")); + EXPECT_THAT( + GetCapturedStdout().c_str(), + ContainsRegex(severity == kWarning + ? "^\nGMOCK WARNING:\nTest log\\.\nStack trace:\n" + : "^\nTest log\\.\nStack trace:\n")); } else { EXPECT_STREQ("", GetCapturedStdout().c_str()); } @@ -455,13 +455,13 @@ TEST(LogTest, NoSkippingStackFrameInOptMode) { EXPECT_THAT(log, HasSubstr(expected_message)); int skip_count = atoi(log.substr(expected_message.size()).c_str()); -# if defined(NDEBUG) +#if defined(NDEBUG) // In opt mode, no stack frame should be skipped. const int expected_skip_count = 0; -# else +#else // In dbg mode, the stack frames should be skipped. const int expected_skip_count = 100; -# endif +#endif // Note that each inner implementation layer will +1 the number to remove // itself from the trace. This means that the value is a little higher than @@ -503,7 +503,7 @@ TEST(LogTest, OnlyWarningsArePrintedWhenVerbosityIsInvalid) { // Verifies that Log() behaves correctly for the given verbosity level // and log severity. -std::string GrabOutput(void(*logger)(), const char* verbosity) { +std::string GrabOutput(void (*logger)(), const char* verbosity) { const std::string saved_flag = GMOCK_FLAG_GET(verbose); GMOCK_FLAG_SET(verbose, verbosity); CaptureStdout(); @@ -538,7 +538,7 @@ TEST(ExpectCallTest, DoesNotLogWhenVerbosityIsWarning) { // Verifies that EXPECT_CALL doesn't log // if the --gmock_verbose flag is set to "error". -TEST(ExpectCallTest, DoesNotLogWhenVerbosityIsError) { +TEST(ExpectCallTest, DoesNotLogWhenVerbosityIsError) { EXPECT_STREQ("", GrabOutput(ExpectCallLogger, kErrorVerbosity).c_str()); } @@ -582,9 +582,9 @@ TEST(OnCallTest, LogsAnythingArgument) { TEST(StlContainerViewTest, WorksForStlContainer) { StaticAssertTypeEq<std::vector<int>, - StlContainerView<std::vector<int> >::type>(); + StlContainerView<std::vector<int>>::type>(); StaticAssertTypeEq<const std::vector<double>&, - StlContainerView<std::vector<double> >::const_reference>(); + StlContainerView<std::vector<double>>::const_reference>(); typedef std::vector<char> Chars; Chars v1; @@ -597,17 +597,16 @@ TEST(StlContainerViewTest, WorksForStlContainer) { } TEST(StlContainerViewTest, WorksForStaticNativeArray) { - StaticAssertTypeEq<NativeArray<int>, - StlContainerView<int[3]>::type>(); + StaticAssertTypeEq<NativeArray<int>, StlContainerView<int[3]>::type>(); StaticAssertTypeEq<NativeArray<double>, - StlContainerView<const double[4]>::type>(); + StlContainerView<const double[4]>::type>(); StaticAssertTypeEq<NativeArray<char[3]>, - StlContainerView<const char[2][3]>::type>(); + StlContainerView<const char[2][3]>::type>(); StaticAssertTypeEq<const NativeArray<int>, - StlContainerView<int[2]>::const_reference>(); + StlContainerView<int[2]>::const_reference>(); - int a1[3] = { 0, 1, 2 }; + int a1[3] = {0, 1, 2}; NativeArray<int> a2 = StlContainerView<int[3]>::ConstReference(a1); EXPECT_EQ(3U, a2.size()); EXPECT_EQ(a1, a2.begin()); @@ -625,24 +624,24 @@ TEST(StlContainerViewTest, WorksForStaticNativeArray) { TEST(StlContainerViewTest, WorksForDynamicNativeArray) { StaticAssertTypeEq<NativeArray<int>, - StlContainerView<std::tuple<const int*, size_t> >::type>(); + StlContainerView<std::tuple<const int*, size_t>>::type>(); StaticAssertTypeEq< NativeArray<double>, - StlContainerView<std::tuple<std::shared_ptr<double>, int> >::type>(); + StlContainerView<std::tuple<std::shared_ptr<double>, int>>::type>(); StaticAssertTypeEq< const NativeArray<int>, - StlContainerView<std::tuple<const int*, int> >::const_reference>(); + StlContainerView<std::tuple<const int*, int>>::const_reference>(); - int a1[3] = { 0, 1, 2 }; + int a1[3] = {0, 1, 2}; const int* const p1 = a1; NativeArray<int> a2 = - StlContainerView<std::tuple<const int*, int> >::ConstReference( + StlContainerView<std::tuple<const int*, int>>::ConstReference( std::make_tuple(p1, 3)); EXPECT_EQ(3U, a2.size()); EXPECT_EQ(a1, a2.begin()); - const NativeArray<int> a3 = StlContainerView<std::tuple<int*, size_t> >::Copy( + const NativeArray<int> a3 = StlContainerView<std::tuple<int*, size_t>>::Copy( std::make_tuple(static_cast<int*>(a1), 3)); ASSERT_EQ(3U, a3.size()); EXPECT_EQ(0, a3.begin()[0]); diff --git a/googlemock/test/gmock-matchers_test.cc b/googlemock/test/gmock-matchers_test.cc index 578425d..45d5241 100644 --- a/googlemock/test/gmock-matchers_test.cc +++ b/googlemock/test/gmock-matchers_test.cc @@ -27,7 +27,6 @@ // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - // Google Mock - a framework for writing C++ mock classes. // // This file tests some commonly used argument matchers. @@ -35,9 +34,9 @@ // Silence warning C4244: 'initializing': conversion from 'int' to 'short', // possible loss of data and C4100, unreferenced local parameter #ifdef _MSC_VER -# pragma warning(push) -# pragma warning(disable:4244) -# pragma warning(disable:4100) +#pragma warning(push) +#pragma warning(disable : 4244) +#pragma warning(disable : 4100) #endif #include "gmock/gmock-matchers.h" @@ -256,9 +255,7 @@ TEST(MatcherInterfaceTest, CanBeImplementedUsingNewAPI) { } // Tests default-constructing a matcher. -TEST(MatcherTest, CanBeDefaultConstructed) { - Matcher<double> m; -} +TEST(MatcherTest, CanBeDefaultConstructed) { Matcher<double> m; } // Tests that Matcher<T> can be constructed from a MatcherInterface<T>*. TEST(MatcherTest, CanBeConstructedFromMatcherInterface) { @@ -315,8 +312,7 @@ TEST(MatcherTest, IsCopyable) { // Tests that Matcher<T>::DescribeTo() calls // MatcherInterface<T>::DescribeTo(). TEST(MatcherTest, CanDescribeItself) { - EXPECT_EQ("is an even number", - Describe(Matcher<int>(new EvenMatcherImpl))); + EXPECT_EQ("is an even number", Describe(Matcher<int>(new EvenMatcherImpl))); } // Tests Matcher<T>::MatchAndExplain(). @@ -421,8 +417,7 @@ const int g_bar = 1; class ReferencesBarOrIsZeroImpl { public: template <typename T> - bool MatchAndExplain(const T& x, - MatchResultListener* /* listener */) const { + bool MatchAndExplain(const T& x, MatchResultListener* /* listener */) const { const void* p = &x; return p == &g_bar || x == 0; } @@ -462,9 +457,7 @@ class PolymorphicIsEvenImpl { public: void DescribeTo(ostream* os) const { *os << "is even"; } - void DescribeNegationTo(ostream* os) const { - *os << "is odd"; - } + void DescribeNegationTo(ostream* os) const { *os << "is odd"; } template <typename T> bool MatchAndExplain(const T& x, MatchResultListener* listener) const { @@ -522,14 +515,13 @@ class IntValue { explicit IntValue(int a_value) : value_(a_value) {} int value() const { return value_; } + private: int value_; }; // For testing casting matchers between compatible types. -bool IsPositiveIntValue(const IntValue& foo) { - return foo.value() > 0; -} +bool IsPositiveIntValue(const IntValue& foo) { return foo.value() > 0; } // Tests that MatcherCast<T>(m) works when m is a Matcher<U> where T // can be statically converted to U. @@ -709,6 +701,7 @@ class Base { public: virtual ~Base() {} Base() {} + private: GTEST_DISALLOW_COPY_AND_ASSIGN_(Base); }; @@ -860,9 +853,7 @@ TEST(ATest, WorksForDerivedClass) { } // Tests that A<T>() describes itself properly. -TEST(ATest, CanDescribeSelf) { - EXPECT_EQ("is anything", Describe(A<bool>())); -} +TEST(ATest, CanDescribeSelf) { EXPECT_EQ("is anything", Describe(A<bool>())); } // Tests that An<T>() matches any value of type T. TEST(AnTest, MatchesAnyValue) { @@ -880,9 +871,7 @@ TEST(AnTest, MatchesAnyValue) { } // Tests that An<T>() describes itself properly. -TEST(AnTest, CanDescribeSelf) { - EXPECT_EQ("is anything", Describe(An<int>())); -} +TEST(AnTest, CanDescribeSelf) { EXPECT_EQ("is anything", Describe(An<int>())); } // Tests that _ can be used as a matcher for any type and matches any // value of that type. @@ -926,6 +915,7 @@ class Unprintable { bool operator==(const Unprintable& /* rhs */) const { return true; } // -Wunused-private-field: dummy accessor for `c_`. char dummy_c() { return c_; } + private: char c_; }; @@ -978,8 +968,8 @@ struct Type { TEST(TypedEqTest, HasSpecifiedType) { // Verfies that the type of TypedEq<T>(v) is Matcher<T>. - Type<Matcher<int> >::IsTypeOf(TypedEq<int>(5)); - Type<Matcher<double> >::IsTypeOf(TypedEq<double>(5)); + Type<Matcher<int>>::IsTypeOf(TypedEq<int>(5)); + Type<Matcher<double>>::IsTypeOf(TypedEq<double>(5)); } // Tests that Ge(v) matches anything >= v. @@ -1121,7 +1111,7 @@ TEST(IsNullTest, StdFunction) { const Matcher<std::function<void()>> m = IsNull(); EXPECT_TRUE(m.Matches(std::function<void()>())); - EXPECT_FALSE(m.Matches([]{})); + EXPECT_FALSE(m.Matches([] {})); } // Tests that IsNull() describes itself properly. @@ -1166,7 +1156,7 @@ TEST(NotNullTest, ReferenceToConstLinkedPtr) { TEST(NotNullTest, StdFunction) { const Matcher<std::function<void()>> m = NotNull(); - EXPECT_TRUE(m.Matches([]{})); + EXPECT_TRUE(m.Matches([] {})); EXPECT_FALSE(m.Matches(std::function<void()>())); } @@ -1281,7 +1271,7 @@ TEST(StrEqTest, MatchesEqualString) { TEST(StrEqTest, CanDescribeSelf) { Matcher<std::string> m = StrEq("Hi-\'\"?\\\a\b\f\n\r\t\v\xD3"); EXPECT_EQ("is equal to \"Hi-\'\\\"?\\\\\\a\\b\\f\\n\\r\\t\\v\\xD3\"", - Describe(m)); + Describe(m)); std::string str("01204500800"); str[3] = '\0'; @@ -1459,7 +1449,7 @@ TEST(KeyTest, CanDescribeSelf) { } TEST(KeyTest, ExplainsResult) { - Matcher<pair<int, bool> > m = Key(GreaterThan(10)); + Matcher<pair<int, bool>> m = Key(GreaterThan(10)); EXPECT_EQ("whose first field is a value which is 5 less than 10", Explain(m, make_pair(5, true))); EXPECT_EQ("whose first field is a value which is 5 more than 10", @@ -1542,32 +1532,35 @@ TEST(KeyTest, InsideContainsUsingMultimap) { TEST(PairTest, Typing) { // Test verifies the following type conversions can be compiled. Matcher<const pair<const char*, int>&> m1 = Pair("foo", 42); - Matcher<const pair<const char*, int> > m2 = Pair("foo", 42); - Matcher<pair<const char*, int> > m3 = Pair("foo", 42); + Matcher<const pair<const char*, int>> m2 = Pair("foo", 42); + Matcher<pair<const char*, int>> m3 = Pair("foo", 42); - Matcher<pair<int, const std::string> > m4 = Pair(25, "42"); - Matcher<pair<const std::string, int> > m5 = Pair("25", 42); + Matcher<pair<int, const std::string>> m4 = Pair(25, "42"); + Matcher<pair<const std::string, int>> m5 = Pair("25", 42); } TEST(PairTest, CanDescribeSelf) { Matcher<const pair<std::string, int>&> m1 = Pair("foo", 42); - EXPECT_EQ("has a first field that is equal to \"foo\"" - ", and has a second field that is equal to 42", - Describe(m1)); - EXPECT_EQ("has a first field that isn't equal to \"foo\"" - ", or has a second field that isn't equal to 42", - DescribeNegation(m1)); + EXPECT_EQ( + "has a first field that is equal to \"foo\"" + ", and has a second field that is equal to 42", + Describe(m1)); + EXPECT_EQ( + "has a first field that isn't equal to \"foo\"" + ", or has a second field that isn't equal to 42", + DescribeNegation(m1)); // Double and triple negation (1 or 2 times not and description of negation). Matcher<const pair<int, int>&> m2 = Not(Pair(Not(13), 42)); - EXPECT_EQ("has a first field that isn't equal to 13" - ", and has a second field that is equal to 42", - DescribeNegation(m2)); + EXPECT_EQ( + "has a first field that isn't equal to 13" + ", and has a second field that is equal to 42", + DescribeNegation(m2)); } TEST(PairTest, CanExplainMatchResultTo) { // If neither field matches, Pair() should explain about the first // field. - const Matcher<pair<int, int> > m = Pair(GreaterThan(0), GreaterThan(0)); + const Matcher<pair<int, int>> m = Pair(GreaterThan(0), GreaterThan(0)); EXPECT_EQ("whose first field does not match, which is 1 less than 0", Explain(m, make_pair(-1, -2))); @@ -1582,24 +1575,27 @@ TEST(PairTest, CanExplainMatchResultTo) { Explain(m, make_pair(-1, 2))); // If both fields match, Pair() should explain about them both. - EXPECT_EQ("whose both fields match, where the first field is a value " - "which is 1 more than 0, and the second field is a value " - "which is 2 more than 0", - Explain(m, make_pair(1, 2))); + EXPECT_EQ( + "whose both fields match, where the first field is a value " + "which is 1 more than 0, and the second field is a value " + "which is 2 more than 0", + Explain(m, make_pair(1, 2))); // If only the first match has an explanation, only this explanation should // be printed. - const Matcher<pair<int, int> > explain_first = Pair(GreaterThan(0), 0); - EXPECT_EQ("whose both fields match, where the first field is a value " - "which is 1 more than 0", - Explain(explain_first, make_pair(1, 0))); + const Matcher<pair<int, int>> explain_first = Pair(GreaterThan(0), 0); + EXPECT_EQ( + "whose both fields match, where the first field is a value " + "which is 1 more than 0", + Explain(explain_first, make_pair(1, 0))); // If only the second match has an explanation, only this explanation should // be printed. - const Matcher<pair<int, int> > explain_second = Pair(0, GreaterThan(0)); - EXPECT_EQ("whose both fields match, where the second field is a value " - "which is 1 more than 0", - Explain(explain_second, make_pair(0, 1))); + const Matcher<pair<int, int>> explain_second = Pair(0, GreaterThan(0)); + EXPECT_EQ( + "whose both fields match, where the second field is a value " + "which is 1 more than 0", + Explain(explain_second, make_pair(0, 1))); } TEST(PairTest, MatchesCorrectly) { @@ -1946,8 +1942,7 @@ TEST(ContainsRegexTest, MatchesStringContainingGivenRegex) { EXPECT_FALSE(m2.Matches("1a")); #if GTEST_INTERNAL_HAS_STRING_VIEW - const Matcher<const internal::StringView&> m3 = - ContainsRegex(new RE("a.*z")); + const Matcher<const internal::StringView&> m3 = ContainsRegex(new RE("a.*z")); EXPECT_TRUE(m3.Matches(internal::StringView("azbz"))); EXPECT_TRUE(m3.Matches(internal::StringView("az1"))); EXPECT_FALSE(m3.Matches(internal::StringView("1a"))); @@ -1998,13 +1993,12 @@ TEST(StdWideStrEqTest, MatchesEqual) { } TEST(StdWideStrEqTest, CanDescribeSelf) { - Matcher< ::std::wstring> m = StrEq(L"Hi-\'\"?\\\a\b\f\n\r\t\v"); + Matcher<::std::wstring> m = StrEq(L"Hi-\'\"?\\\a\b\f\n\r\t\v"); EXPECT_EQ("is equal to L\"Hi-\'\\\"?\\\\\\a\\b\\f\\n\\r\\t\\v\"", - Describe(m)); + Describe(m)); - Matcher< ::std::wstring> m2 = StrEq(L"\xD3\x576\x8D3\xC74D"); - EXPECT_EQ("is equal to L\"\\xD3\\x576\\x8D3\\xC74D\"", - Describe(m2)); + Matcher<::std::wstring> m2 = StrEq(L"\xD3\x576\x8D3\xC74D"); + EXPECT_EQ("is equal to L\"\\xD3\\x576\\x8D3\\xC74D\"", Describe(m2)); ::std::wstring str(L"01204500800"); str[3] = L'\0'; @@ -2021,7 +2015,7 @@ TEST(StdWideStrNeTest, MatchesUnequalString) { EXPECT_TRUE(m.Matches(nullptr)); EXPECT_FALSE(m.Matches(L"Hello")); - Matcher< ::std::wstring> m2 = StrNe(::std::wstring(L"Hello")); + Matcher<::std::wstring> m2 = StrNe(::std::wstring(L"Hello")); EXPECT_TRUE(m2.Matches(L"hello")); EXPECT_FALSE(m2.Matches(L"Hello")); } @@ -2069,7 +2063,7 @@ TEST(StdWideStrCaseEqTest, MatchesEqualStringWith0IgnoringCase) { } TEST(StdWideStrCaseEqTest, CanDescribeSelf) { - Matcher< ::std::wstring> m = StrCaseEq(L"Hi"); + Matcher<::std::wstring> m = StrCaseEq(L"Hi"); EXPECT_EQ("is equal to (ignoring case) L\"Hi\"", Describe(m)); } @@ -2080,7 +2074,7 @@ TEST(StdWideStrCaseNeTest, MatchesUnequalStringIgnoringCase) { EXPECT_FALSE(m.Matches(L"Hello")); EXPECT_FALSE(m.Matches(L"hello")); - Matcher< ::std::wstring> m2 = StrCaseNe(::std::wstring(L"Hello")); + Matcher<::std::wstring> m2 = StrCaseNe(::std::wstring(L"Hello")); EXPECT_TRUE(m2.Matches(L"")); EXPECT_FALSE(m2.Matches(L"Hello")); } @@ -2092,7 +2086,7 @@ TEST(StdWideStrCaseNeTest, CanDescribeSelf) { // Tests that HasSubstr() works for matching wstring-typed values. TEST(StdWideHasSubstrTest, WorksForStringClasses) { - const Matcher< ::std::wstring> m1 = HasSubstr(L"foo"); + const Matcher<::std::wstring> m1 = HasSubstr(L"foo"); EXPECT_TRUE(m1.Matches(::std::wstring(L"I love food."))); EXPECT_FALSE(m1.Matches(::std::wstring(L"tofo"))); @@ -2116,7 +2110,7 @@ TEST(StdWideHasSubstrTest, WorksForCStrings) { // Tests that HasSubstr(s) describes itself properly. TEST(StdWideHasSubstrTest, CanDescribeSelf) { - Matcher< ::std::wstring> m = HasSubstr(L"foo\n\""); + Matcher<::std::wstring> m = HasSubstr(L"foo\n\""); EXPECT_EQ("has substring L\"foo\\n\\\"\"", Describe(m)); } @@ -2586,10 +2580,10 @@ TEST(AllOfTest, MatchesWhenAllMatch) { AllOfMatches(5, AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5))); AllOfMatches(6, AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5), Ne(6))); AllOfMatches(7, AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5), Ne(6), Ne(7))); - AllOfMatches(8, AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5), Ne(6), Ne(7), - Ne(8))); - AllOfMatches(9, AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5), Ne(6), Ne(7), - Ne(8), Ne(9))); + AllOfMatches(8, + AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5), Ne(6), Ne(7), Ne(8))); + AllOfMatches( + 9, AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5), Ne(6), Ne(7), Ne(8), Ne(9))); AllOfMatches(10, AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5), Ne(6), Ne(7), Ne(8), Ne(9), Ne(10))); AllOfMatches( @@ -2602,7 +2596,6 @@ TEST(AllOfTest, MatchesWhenAllMatch) { Ne(50))); } - // Tests that AllOf(m1, ..., mn) describes itself properly. TEST(AllOfTest, CanDescribeSelf) { Matcher<int> m; @@ -2694,9 +2687,10 @@ TEST(AllOfTest, ExplainsResult) { // Successful match. All matchers need to explain. m = AllOf(GreaterThan(10), GreaterThan(20), GreaterThan(30)); - EXPECT_EQ("which is 30 more than 10, and which is 20 more than 20, " - "and which is 10 more than 30", - Explain(m, 40)); + EXPECT_EQ( + "which is 30 more than 10, and which is 20 more than 20, " + "and which is 10 more than 30", + Explain(m, 40)); // Failed match. The first matcher, which failed, needs to // explain. @@ -2786,11 +2780,10 @@ TEST(AnyOfTest, VariadicMatchesWhenAnyMatches) { EXPECT_THAT(Describe(m), EndsWith("or (is equal to 11)")); AnyOfMatches(11, m); - AnyOfMatches(50, AnyOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, - 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, - 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, - 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, - 41, 42, 43, 44, 45, 46, 47, 48, 49, 50)); + AnyOfMatches(50, AnyOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, + 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, + 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, + 45, 46, 47, 48, 49, 50)); AnyOfStringMatches( 50, AnyOf("1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", @@ -2854,14 +2847,12 @@ TEST(ElementsAreTest, HugeMatcherUnordered) { Eq(3), Eq(9), Eq(12), Eq(11), Ne(122))); } - // Tests that AnyOf(m1, ..., mn) describes itself properly. TEST(AnyOfTest, CanDescribeSelf) { Matcher<int> m; m = AnyOf(Le(1), Ge(3)); - EXPECT_EQ("(is <= 1) or (is >= 3)", - Describe(m)); + EXPECT_EQ("(is <= 1) or (is >= 3)", Describe(m)); m = AnyOf(Lt(0), Eq(1), Eq(2)); EXPECT_EQ("(is < 0) or (is equal to 1) or (is equal to 2)", Describe(m)); @@ -2881,8 +2872,7 @@ TEST(AnyOfTest, CanDescribeSelf) { TEST(AnyOfTest, CanDescribeNegation) { Matcher<int> m; m = AnyOf(Le(1), Ge(3)); - EXPECT_EQ("(isn't <= 1) and (isn't >= 3)", - DescribeNegation(m)); + EXPECT_EQ("(isn't <= 1) and (isn't >= 3)", DescribeNegation(m)); m = AnyOf(Lt(0), Eq(1), Eq(2)); EXPECT_EQ("(isn't < 0) and (isn't equal to 1) and (isn't equal to 2)", @@ -2938,9 +2928,10 @@ TEST(AnyOfTest, ExplainsResult) { // Failed match. All matchers need to explain. m = AnyOf(GreaterThan(10), GreaterThan(20), GreaterThan(30)); - EXPECT_EQ("which is 5 less than 10, and which is 15 less than 20, " - "and which is 25 less than 30", - Explain(m, 5)); + EXPECT_EQ( + "which is 5 less than 10, and which is 15 less than 20, " + "and which is 25 less than 30", + Explain(m, 5)); // Successful match. The first matcher, which succeeded, needs to // explain. @@ -2966,9 +2957,7 @@ TEST(AnyOfTest, ExplainsResult) { // type of this function is not bool. It's OK as Truly() accepts any // unary function or functor whose return type can be implicitly // converted to bool. -int IsPositive(double x) { - return x > 0 ? 1 : 0; -} +int IsPositive(double x) { return x > 0 ? 1 : 0; } // This functor returns true if the input is greater than the given // number. @@ -2987,9 +2976,7 @@ const int foo = 0; // This predicate returns true if and only if the argument references foo and // has a zero value. -bool ReferencesFooAndIsZero(const int& n) { - return (&n == &foo) && (n == 0); -} +bool ReferencesFooAndIsZero(const int& n) { return (&n == &foo) && (n == 0); } // Tests that Truly(predicate) matches what satisfies the given // predicate. @@ -3016,9 +3003,7 @@ class ConvertibleToBool { int number_; }; -ConvertibleToBool IsNotZero(int number) { - return ConvertibleToBool(number); -} +ConvertibleToBool IsNotZero(int number) { return ConvertibleToBool(number); } // Tests that the predicate used in Truly() may return a class that's // implicitly convertible to bool, even when the class has no @@ -3032,8 +3017,7 @@ TEST(TrulyTest, PredicateCanReturnAClassConvertibleToBool) { // Tests that Truly(predicate) can describe itself properly. TEST(TrulyTest, CanDescribeSelf) { Matcher<double> m = Truly(IsPositive); - EXPECT_EQ("satisfies the given predicate", - Describe(m)); + EXPECT_EQ("satisfies the given predicate", Describe(m)); } // Tests that Truly(predicate) works when the matcher takes its @@ -3189,13 +3173,9 @@ class AllArgsHelper { TEST(AllArgsTest, WorksInWithClause) { AllArgsHelper helper; - ON_CALL(helper, Helper(_, _)) - .With(AllArgs(Lt())) - .WillByDefault(Return(1)); + ON_CALL(helper, Helper(_, _)).With(AllArgs(Lt())).WillByDefault(Return(1)); EXPECT_CALL(helper, Helper(_, _)); - EXPECT_CALL(helper, Helper(_, _)) - .With(AllArgs(Gt())) - .WillOnce(Return(2)); + EXPECT_CALL(helper, Helper(_, _)).With(AllArgs(Gt())).WillOnce(Return(2)); EXPECT_EQ(1, helper.Helper('\1', 2)); EXPECT_EQ(2, helper.Helper('a', 1)); @@ -3259,13 +3239,14 @@ TEST(MatcherAssertionTest, WorksWhenMatcherIsNotSatisfied) { EXPECT_FATAL_FAILURE(ASSERT_THAT(n, Gt(10)), "Value of: n\n" "Expected: is > 10\n" - " Actual: 5" + OfType("unsigned short")); + " Actual: 5" + + OfType("unsigned short")); n = 0; - EXPECT_NONFATAL_FAILURE( - EXPECT_THAT(n, AllOf(Le(7), Ge(5))), - "Value of: n\n" - "Expected: (is <= 7) and (is >= 5)\n" - " Actual: 0" + OfType("unsigned short")); + EXPECT_NONFATAL_FAILURE(EXPECT_THAT(n, AllOf(Le(7), Ge(5))), + "Value of: n\n" + "Expected: (is <= 7) and (is >= 5)\n" + " Actual: 0" + + OfType("unsigned short")); } // Tests that ASSERT_THAT() and EXPECT_THAT() work when the argument @@ -3301,7 +3282,8 @@ TEST(MatcherAssertionTest, WorksForMonomorphicMatcher) { EXPECT_NONFATAL_FAILURE(EXPECT_THAT(5, is_greater_than_5), "Value of: 5\n" "Expected: is > 5\n" - " Actual: 5" + OfType("int")); + " Actual: 5" + + OfType("int")); } // Tests floating-point matchers. @@ -3317,11 +3299,11 @@ class FloatingPointTest : public testing::Test { one_bits_(Floating(1).bits()), infinity_bits_(Floating(Floating::Infinity()).bits()), close_to_positive_zero_( - Floating::ReinterpretBits(zero_bits_ + max_ulps_/2)), + Floating::ReinterpretBits(zero_bits_ + max_ulps_ / 2)), close_to_negative_zero_( - -Floating::ReinterpretBits(zero_bits_ + max_ulps_ - max_ulps_/2)), + -Floating::ReinterpretBits(zero_bits_ + max_ulps_ - max_ulps_ / 2)), further_from_negative_zero_(-Floating::ReinterpretBits( - zero_bits_ + max_ulps_ + 1 - max_ulps_/2)), + zero_bits_ + max_ulps_ + 1 - max_ulps_ / 2)), close_to_one_(Floating::ReinterpretBits(one_bits_ + max_ulps_)), further_from_one_(Floating::ReinterpretBits(one_bits_ + max_ulps_ + 1)), infinity_(Floating::Infinity()), @@ -3331,12 +3313,9 @@ class FloatingPointTest : public testing::Test { Floating::ReinterpretBits(infinity_bits_ - max_ulps_ - 1)), max_(Floating::Max()), nan1_(Floating::ReinterpretBits(Floating::kExponentBitMask | 1)), - nan2_(Floating::ReinterpretBits(Floating::kExponentBitMask | 200)) { - } + nan2_(Floating::ReinterpretBits(Floating::kExponentBitMask | 200)) {} - void TestSize() { - EXPECT_EQ(sizeof(RawType), sizeof(Bits)); - } + void TestSize() { EXPECT_EQ(sizeof(RawType), sizeof(Bits)); } // A battery of tests for FloatingEqMatcher::Matches. // matcher_maker is a pointer to a function which creates a FloatingEqMatcher. @@ -3388,8 +3367,8 @@ class FloatingPointTest : public testing::Test { const Bits max_ulps_; - const Bits zero_bits_; // The bits that represent 0.0. - const Bits one_bits_; // The bits that represent 1.0. + const Bits zero_bits_; // The bits that represent 0.0. + const Bits one_bits_; // The bits that represent 1.0. const Bits infinity_bits_; // The bits that represent +infinity. // Some numbers close to 0.0. @@ -3422,9 +3401,8 @@ class FloatingPointNearTest : public FloatingPointTest<RawType> { // A battery of tests for FloatingEqMatcher::Matches with a fixed epsilon. // matcher_maker is a pointer to a function which creates a FloatingEqMatcher. - void TestNearMatches( - testing::internal::FloatingEqMatcher<RawType> - (*matcher_maker)(RawType, RawType)) { + void TestNearMatches(testing::internal::FloatingEqMatcher<RawType> ( + *matcher_maker)(RawType, RawType)) { Matcher<RawType> m1 = matcher_maker(0.0, 0.0); EXPECT_TRUE(m1.Matches(0.0)); EXPECT_TRUE(m1.Matches(-0.0)); @@ -3471,8 +3449,8 @@ class FloatingPointNearTest : public FloatingPointTest<RawType> { // The difference between max() and -max() normally overflows to infinity, // but it should still match if the max_abs_error is also infinity. - Matcher<RawType> m9 = matcher_maker( - ParentType::max_, ParentType::infinity_); + Matcher<RawType> m9 = + matcher_maker(ParentType::max_, ParentType::infinity_); EXPECT_TRUE(m8.Matches(-ParentType::max_)); // matcher_maker can produce a Matcher<const RawType&>, which is needed in @@ -3501,9 +3479,7 @@ class FloatingPointNearTest : public FloatingPointTest<RawType> { // Instantiate FloatingPointTest for testing floats. typedef FloatingPointTest<float> FloatTest; -TEST_F(FloatTest, FloatEqApproximatelyMatchesFloats) { - TestMatches(&FloatEq); -} +TEST_F(FloatTest, FloatEqApproximatelyMatchesFloats) { TestMatches(&FloatEq); } TEST_F(FloatTest, NanSensitiveFloatEqApproximatelyMatchesFloats) { TestMatches(&NanSensitiveFloatEq); @@ -3557,9 +3533,7 @@ TEST_F(FloatTest, NanSensitiveFloatEqCanDescribeSelf) { // max absolute error. typedef FloatingPointNearTest<float> FloatNearTest; -TEST_F(FloatNearTest, FloatNearMatches) { - TestNearMatches(&FloatNear); -} +TEST_F(FloatNearTest, FloatNearMatches) { TestNearMatches(&FloatNear); } TEST_F(FloatNearTest, NanSensitiveFloatNearApproximatelyMatchesFloats) { TestNearMatches(&NanSensitiveFloatNear); @@ -3568,13 +3542,13 @@ TEST_F(FloatNearTest, NanSensitiveFloatNearApproximatelyMatchesFloats) { TEST_F(FloatNearTest, FloatNearCanDescribeSelf) { Matcher<float> m1 = FloatNear(2.0f, 0.5f); EXPECT_EQ("is approximately 2 (absolute error <= 0.5)", Describe(m1)); - EXPECT_EQ( - "isn't approximately 2 (absolute error > 0.5)", DescribeNegation(m1)); + EXPECT_EQ("isn't approximately 2 (absolute error > 0.5)", + DescribeNegation(m1)); Matcher<float> m2 = FloatNear(0.5f, 0.5f); EXPECT_EQ("is approximately 0.5 (absolute error <= 0.5)", Describe(m2)); - EXPECT_EQ( - "isn't approximately 0.5 (absolute error > 0.5)", DescribeNegation(m2)); + EXPECT_EQ("isn't approximately 0.5 (absolute error > 0.5)", + DescribeNegation(m2)); Matcher<float> m3 = FloatNear(nan1_, 0.0); EXPECT_EQ("never matches", Describe(m3)); @@ -3584,13 +3558,13 @@ TEST_F(FloatNearTest, FloatNearCanDescribeSelf) { TEST_F(FloatNearTest, NanSensitiveFloatNearCanDescribeSelf) { Matcher<float> m1 = NanSensitiveFloatNear(2.0f, 0.5f); EXPECT_EQ("is approximately 2 (absolute error <= 0.5)", Describe(m1)); - EXPECT_EQ( - "isn't approximately 2 (absolute error > 0.5)", DescribeNegation(m1)); + EXPECT_EQ("isn't approximately 2 (absolute error > 0.5)", + DescribeNegation(m1)); Matcher<float> m2 = NanSensitiveFloatNear(0.5f, 0.5f); EXPECT_EQ("is approximately 0.5 (absolute error <= 0.5)", Describe(m2)); - EXPECT_EQ( - "isn't approximately 0.5 (absolute error > 0.5)", DescribeNegation(m2)); + EXPECT_EQ("isn't approximately 0.5 (absolute error > 0.5)", + DescribeNegation(m2)); Matcher<float> m3 = NanSensitiveFloatNear(nan1_, 0.1f); EXPECT_EQ("is NaN", Describe(m3)); @@ -3672,9 +3646,7 @@ TEST_F(DoubleTest, NanSensitiveDoubleEqCanDescribeSelf) { // max absolute error. typedef FloatingPointNearTest<double> DoubleNearTest; -TEST_F(DoubleNearTest, DoubleNearMatches) { - TestNearMatches(&DoubleNear); -} +TEST_F(DoubleNearTest, DoubleNearMatches) { TestNearMatches(&DoubleNear); } TEST_F(DoubleNearTest, NanSensitiveDoubleNearApproximatelyMatchesDoubles) { TestNearMatches(&NanSensitiveDoubleNear); @@ -3683,13 +3655,13 @@ TEST_F(DoubleNearTest, NanSensitiveDoubleNearApproximatelyMatchesDoubles) { TEST_F(DoubleNearTest, DoubleNearCanDescribeSelf) { Matcher<double> m1 = DoubleNear(2.0, 0.5); EXPECT_EQ("is approximately 2 (absolute error <= 0.5)", Describe(m1)); - EXPECT_EQ( - "isn't approximately 2 (absolute error > 0.5)", DescribeNegation(m1)); + EXPECT_EQ("isn't approximately 2 (absolute error > 0.5)", + DescribeNegation(m1)); Matcher<double> m2 = DoubleNear(0.5, 0.5); EXPECT_EQ("is approximately 0.5 (absolute error <= 0.5)", Describe(m2)); - EXPECT_EQ( - "isn't approximately 0.5 (absolute error > 0.5)", DescribeNegation(m2)); + EXPECT_EQ("isn't approximately 0.5 (absolute error > 0.5)", + DescribeNegation(m2)); Matcher<double> m3 = DoubleNear(nan1_, 0.0); EXPECT_EQ("never matches", Describe(m3)); @@ -3713,13 +3685,13 @@ TEST_F(DoubleNearTest, ExplainsResultWhenMatchFails) { TEST_F(DoubleNearTest, NanSensitiveDoubleNearCanDescribeSelf) { Matcher<double> m1 = NanSensitiveDoubleNear(2.0, 0.5); EXPECT_EQ("is approximately 2 (absolute error <= 0.5)", Describe(m1)); - EXPECT_EQ( - "isn't approximately 2 (absolute error > 0.5)", DescribeNegation(m1)); + EXPECT_EQ("isn't approximately 2 (absolute error > 0.5)", + DescribeNegation(m1)); Matcher<double> m2 = NanSensitiveDoubleNear(0.5, 0.5); EXPECT_EQ("is approximately 0.5 (absolute error <= 0.5)", Describe(m2)); - EXPECT_EQ( - "isn't approximately 0.5 (absolute error > 0.5)", DescribeNegation(m2)); + EXPECT_EQ("isn't approximately 0.5 (absolute error > 0.5)", + DescribeNegation(m2)); Matcher<double> m3 = NanSensitiveDoubleNear(nan1_, 0.1); EXPECT_EQ("is NaN", Describe(m3)); @@ -3763,7 +3735,7 @@ TEST(PointeeTest, RawPointerToConst) { } TEST(PointeeTest, ReferenceToConstRawPointer) { - const Matcher<int* const &> m = Pointee(Ge(0)); + const Matcher<int* const&> m = Pointee(Ge(0)); int n = 1; EXPECT_TRUE(m.Matches(&n)); @@ -3773,7 +3745,7 @@ TEST(PointeeTest, ReferenceToConstRawPointer) { } TEST(PointeeTest, ReferenceToNonConstRawPointer) { - const Matcher<double* &> m = Pointee(Ge(0)); + const Matcher<double*&> m = Pointee(Ge(0)); double x = 1.0; double* p = &x; @@ -4002,7 +3974,7 @@ class ConstPropagatingPtr { }; TEST(PointeeTest, WorksWithConstPropagatingPointers) { - const Matcher< ConstPropagatingPtr<int> > m = Pointee(Lt(5)); + const Matcher<ConstPropagatingPtr<int>> m = Pointee(Lt(5)); int three = 3; const ConstPropagatingPtr<int> co(&three); ConstPropagatingPtr<int> o(&three); @@ -4032,8 +4004,7 @@ TEST(PointeeTest, MatchesAgainstAValue) { TEST(PointeeTest, CanDescribeSelf) { const Matcher<int*> m = Pointee(Gt(3)); EXPECT_EQ("points to a value that is > 3", Describe(m)); - EXPECT_EQ("does not point to a value that is > 3", - DescribeNegation(m)); + EXPECT_EQ("does not point to a value that is > 3", DescribeNegation(m)); } TEST(PointeeTest, CanExplainMatchResult) { @@ -4042,7 +4013,7 @@ TEST(PointeeTest, CanExplainMatchResult) { EXPECT_EQ("", Explain(m, static_cast<const std::string*>(nullptr))); const Matcher<long*> m2 = Pointee(GreaterThan(1)); // NOLINT - long n = 3; // NOLINT + long n = 3; // NOLINT EXPECT_EQ("which points to 3" + OfType("long") + ", which is 2 more than 1", Explain(m2, &n)); } @@ -4172,8 +4143,7 @@ TEST(FieldTest, WorksForArgumentOfSubType) { // argument type are compatible but not the same. TEST(FieldTest, WorksForCompatibleMatcherType) { // The field is an int, but the inner matcher expects a signed char. - Matcher<const AStruct&> m = Field(&AStruct::x, - Matcher<signed char>(Ge(0))); + Matcher<const AStruct&> m = Field(&AStruct::x, Matcher<signed char>(Ge(0))); AStruct a; EXPECT_TRUE(m.Matches(a)); @@ -4301,7 +4271,8 @@ TEST(FieldForPointerTest, CanExplainMatchResult) { m = Field(&AStruct::x, GreaterThan(0)); EXPECT_EQ("which points to an object whose given field is 1" + OfType("int") + - ", which is 1 more than 0", Explain(m, &a)); + ", which is 1 more than 0", + Explain(m, &a)); } TEST(FieldForPointerTest, CanExplainMatchResultWithFieldName) { @@ -4333,7 +4304,7 @@ class AClass { // A getter that returns a reference to const. const std::string& s() const { return s_; } - const std::string& s_ref() const & { return s_; } + const std::string& s_ref() const& { return s_; } void set_s(const std::string& new_s) { s_ = new_s; } @@ -4353,6 +4324,7 @@ double AClass::x_ = 0.0; class DerivedClass : public AClass { public: int k() const { return k_; } + private: int k_; }; @@ -4452,8 +4424,7 @@ TEST(PropertyTest, WorksForArgumentOfSubType) { // and m's argument type are compatible but different. TEST(PropertyTest, WorksForCompatibleMatcherType) { // n() returns an int but the inner matcher expects a signed char. - Matcher<const AClass&> m = Property(&AClass::n, - Matcher<signed char>(Ge(0))); + Matcher<const AClass&> m = Property(&AClass::n, Matcher<signed char>(Ge(0))); Matcher<const AClass&> m_with_name = Property("n", &AClass::n, Matcher<signed char>(Ge(0))); @@ -4598,7 +4569,7 @@ TEST(PropertyForPointerTest, CanExplainMatchResult) { m = Property(&AClass::n, GreaterThan(0)); EXPECT_EQ("which points to an object whose given property is 1" + - OfType("int") + ", which is 1 more than 0", + OfType("int") + ", which is 1 more than 0", Explain(m, &a)); } @@ -4637,10 +4608,14 @@ TEST(ResultOfTest, WorksForFunctionPointers) { TEST(ResultOfTest, CanDescribeItself) { Matcher<int> matcher = ResultOf(&IntToStringFunction, StrEq("foo")); - EXPECT_EQ("is mapped by the given callable to a value that " - "is equal to \"foo\"", Describe(matcher)); - EXPECT_EQ("is mapped by the given callable to a value that " - "isn't equal to \"foo\"", DescribeNegation(matcher)); + EXPECT_EQ( + "is mapped by the given callable to a value that " + "is equal to \"foo\"", + Describe(matcher)); + EXPECT_EQ( + "is mapped by the given callable to a value that " + "isn't equal to \"foo\"", + DescribeNegation(matcher)); } // Tests that ResultOf() can describe itself when provided a result description. @@ -4663,7 +4638,8 @@ TEST(ResultOfTest, CanExplainMatchResult) { matcher = ResultOf(&IntFunction, GreaterThan(85)); EXPECT_EQ("which is mapped by the given callable to 90" + OfType("int") + - ", which is 5 more than 85", Explain(matcher, 36)); + ", which is 5 more than 85", + Explain(matcher, 36)); } // Tests that ResultOf(f, ...) compiles and works as expected when f(x) @@ -4694,8 +4670,7 @@ TEST(ResultOfTest, WorksForReferenceToNonConstResults) { // Test that ResultOf works with uncopyable objects Uncopyable obj(0); Uncopyable obj2(0); - Matcher<Uncopyable&> matcher2 = - ResultOf(&RefUncopyableFunction, Ref(obj)); + Matcher<Uncopyable&> matcher2 = ResultOf(&RefUncopyableFunction, Ref(obj)); EXPECT_TRUE(matcher2.Matches(obj)); EXPECT_FALSE(matcher2.Matches(obj2)); @@ -4744,9 +4719,7 @@ TEST(ResultOfTest, WorksForFunctionReferences) { // Tests that ResultOf(f, ...) compiles and works as expected when f is a // function object. struct Functor { - std::string operator()(int input) const { - return IntToStringFunction(input); - } + std::string operator()(int input) const { return IntToStringFunction(input); } }; TEST(ResultOfTest, WorksForFunctors) { @@ -4763,7 +4736,7 @@ struct PolymorphicFunctor { typedef int result_type; int operator()(int n) { return n; } int operator()(const char* s) { return static_cast<int>(strlen(s)); } - std::string operator()(int *p) { return p ? "good ptr" : "null"; } + std::string operator()(int* p) { return p ? "good ptr" : "null"; } }; TEST(ResultOfTest, WorksForPolymorphicFunctors) { @@ -4832,14 +4805,11 @@ class DivisibleByImpl { // For testing using ExplainMatchResultTo() with polymorphic matchers. template <typename T> bool MatchAndExplain(const T& n, MatchResultListener* listener) const { - *listener << "which is " << (n % divider_) << " modulo " - << divider_; + *listener << "which is " << (n % divider_) << " modulo " << divider_; return (n % divider_) == 0; } - void DescribeTo(ostream* os) const { - *os << "is divisible by " << divider_; - } + void DescribeTo(ostream* os) const { *os << "is divisible by " << divider_; } void DescribeNegationTo(ostream* os) const { *os << "is not divisible by " << divider_; @@ -4911,6 +4881,7 @@ class NotCopyable { bool operator>=(const NotCopyable& rhs) const { return value() >= rhs.value(); } + private: int value_; @@ -4954,13 +4925,13 @@ TEST(IsEmptyTest, WorksWithString) { } TEST(IsEmptyTest, CanDescribeSelf) { - Matcher<vector<int> > m = IsEmpty(); + Matcher<vector<int>> m = IsEmpty(); EXPECT_EQ("is empty", Describe(m)); EXPECT_EQ("isn't empty", DescribeNegation(m)); } TEST(IsEmptyTest, ExplainsResult) { - Matcher<vector<int> > m = IsEmpty(); + Matcher<vector<int>> m = IsEmpty(); vector<int> container; EXPECT_EQ("", Explain(m, container)); container.push_back(0); @@ -5059,16 +5030,16 @@ TEST(SizeIsTest, WorksWithMinimalistCustomType) { } TEST(SizeIsTest, CanDescribeSelf) { - Matcher<vector<int> > m = SizeIs(2); + Matcher<vector<int>> m = SizeIs(2); EXPECT_EQ("size is equal to 2", Describe(m)); EXPECT_EQ("size isn't equal to 2", DescribeNegation(m)); } TEST(SizeIsTest, ExplainsResult) { - Matcher<vector<int> > m1 = SizeIs(2); - Matcher<vector<int> > m2 = SizeIs(Lt(2u)); - Matcher<vector<int> > m3 = SizeIs(AnyOf(0, 3)); - Matcher<vector<int> > m4 = SizeIs(Gt(1u)); + Matcher<vector<int>> m1 = SizeIs(2); + Matcher<vector<int>> m2 = SizeIs(Lt(2u)); + Matcher<vector<int>> m3 = SizeIs(AnyOf(0, 3)); + Matcher<vector<int>> m4 = SizeIs(Gt(1u)); vector<int> container; EXPECT_EQ("whose size 0 doesn't match", Explain(m1, container)); EXPECT_EQ("whose size 0 matches", Explain(m2, container)); @@ -5089,11 +5060,7 @@ TEST(SizeIsTest, ExplainsResult) { template <typename T> class ContainerEqTest : public testing::Test {}; -typedef testing::Types< - set<int>, - vector<size_t>, - multiset<size_t>, - list<int> > +typedef testing::Types<set<int>, vector<size_t>, multiset<size_t>, list<int>> ContainerEqTestTypes; TYPED_TEST_SUITE(ContainerEqTest, ContainerEqTestTypes); @@ -5138,9 +5105,10 @@ TYPED_TEST(ContainerEqTest, ValueAddedAndRemoved) { TypeParam test_set(test_vals, test_vals + 5); const Matcher<TypeParam> m = ContainerEq(my_set); EXPECT_FALSE(m.Matches(test_set)); - EXPECT_EQ("which has these unexpected elements: 46,\n" - "and doesn't have these expected elements: 5", - Explain(m, test_set)); + EXPECT_EQ( + "which has these unexpected elements: 46,\n" + "and doesn't have these expected elements: 5", + Explain(m, test_set)); } // Tests duplicated value -- expect no explanation. @@ -5163,7 +5131,7 @@ TEST(ContainerEqExtraTest, MultipleValuesMissing) { static const int test_vals[] = {2, 1, 5}; vector<int> my_set(vals, vals + 6); vector<int> test_set(test_vals, test_vals + 3); - const Matcher<vector<int> > m = ContainerEq(my_set); + const Matcher<vector<int>> m = ContainerEq(my_set); EXPECT_FALSE(m.Matches(test_set)); EXPECT_EQ("which doesn't have these expected elements: 3, 8", Explain(m, test_set)); @@ -5188,11 +5156,12 @@ TEST(ContainerEqExtraTest, MultipleValuesAddedAndRemoved) { static const int test_vals[] = {1, 2, 3, 92, 46}; list<size_t> my_set(vals, vals + 6); list<size_t> test_set(test_vals, test_vals + 5); - const Matcher<const list<size_t> > m = ContainerEq(my_set); + const Matcher<const list<size_t>> m = ContainerEq(my_set); EXPECT_FALSE(m.Matches(test_set)); - EXPECT_EQ("which has these unexpected elements: 92, 46,\n" - "and doesn't have these expected elements: 5, 8", - Explain(m, test_set)); + EXPECT_EQ( + "which has these unexpected elements: 92, 46,\n" + "and doesn't have these expected elements: 5, 8", + Explain(m, test_set)); } // Tests to see that duplicate elements are detected, @@ -5202,7 +5171,7 @@ TEST(ContainerEqExtraTest, MultiSetOfIntDuplicateDifference) { static const int test_vals[] = {1, 2, 3, 5, 8}; vector<int> my_set(vals, vals + 6); vector<int> test_set(test_vals, test_vals + 5); - const Matcher<vector<int> > m = ContainerEq(my_set); + const Matcher<vector<int>> m = ContainerEq(my_set); EXPECT_TRUE(m.Matches(my_set)); EXPECT_FALSE(m.Matches(test_set)); // There is nothing to report when both sets contain all the same values. @@ -5224,9 +5193,10 @@ TEST(ContainerEqExtraTest, WorksForMaps) { EXPECT_TRUE(m.Matches(my_map)); EXPECT_FALSE(m.Matches(test_map)); - EXPECT_EQ("which has these unexpected elements: (0, \"aa\"),\n" - "and doesn't have these expected elements: (0, \"a\")", - Explain(m, test_map)); + EXPECT_EQ( + "which has these unexpected elements: (0, \"aa\"),\n" + "and doesn't have these expected elements: (0, \"a\")", + Explain(m, test_map)); } TEST(ContainerEqExtraTest, WorksForNativeArray) { @@ -5266,15 +5236,9 @@ TEST(ContainerEqExtraTest, WorksForNativeArrayAsTuple) { } TEST(ContainerEqExtraTest, CopiesNativeArrayParameter) { - std::string a1[][3] = { - {"hi", "hello", "ciao"}, - {"bye", "see you", "ciao"} - }; + std::string a1[][3] = {{"hi", "hello", "ciao"}, {"bye", "see you", "ciao"}}; - std::string a2[][3] = { - {"hi", "hello", "ciao"}, - {"bye", "see you", "ciao"} - }; + std::string a2[][3] = {{"hi", "hello", "ciao"}, {"bye", "see you", "ciao"}}; const Matcher<const std::string(&)[2][3]> m = ContainerEq(a2); EXPECT_THAT(a1, m); @@ -5295,10 +5259,10 @@ TEST(WhenSortedByTest, WorksForNonEmptyContainer) { numbers.push_back(1); numbers.push_back(2); numbers.push_back(2); - EXPECT_THAT(numbers, WhenSortedBy(greater<unsigned>(), - ElementsAre(3, 2, 2, 1))); - EXPECT_THAT(numbers, Not(WhenSortedBy(greater<unsigned>(), - ElementsAre(1, 2, 2, 3)))); + EXPECT_THAT(numbers, + WhenSortedBy(greater<unsigned>(), ElementsAre(3, 2, 2, 1))); + EXPECT_THAT(numbers, + Not(WhenSortedBy(greater<unsigned>(), ElementsAre(1, 2, 2, 3)))); } TEST(WhenSortedByTest, WorksForNonVectorContainer) { @@ -5316,21 +5280,23 @@ TEST(WhenSortedByTest, WorksForNativeArray) { const int numbers[] = {1, 3, 2, 4}; const int sorted_numbers[] = {1, 2, 3, 4}; EXPECT_THAT(numbers, WhenSortedBy(less<int>(), ElementsAre(1, 2, 3, 4))); - EXPECT_THAT(numbers, WhenSortedBy(less<int>(), - ElementsAreArray(sorted_numbers))); + EXPECT_THAT(numbers, + WhenSortedBy(less<int>(), ElementsAreArray(sorted_numbers))); EXPECT_THAT(numbers, Not(WhenSortedBy(less<int>(), ElementsAre(1, 3, 2, 4)))); } TEST(WhenSortedByTest, CanDescribeSelf) { - const Matcher<vector<int> > m = WhenSortedBy(less<int>(), ElementsAre(1, 2)); - EXPECT_EQ("(when sorted) has 2 elements where\n" - "element #0 is equal to 1,\n" - "element #1 is equal to 2", - Describe(m)); - EXPECT_EQ("(when sorted) doesn't have 2 elements, or\n" - "element #0 isn't equal to 1, or\n" - "element #1 isn't equal to 2", - DescribeNegation(m)); + const Matcher<vector<int>> m = WhenSortedBy(less<int>(), ElementsAre(1, 2)); + EXPECT_EQ( + "(when sorted) has 2 elements where\n" + "element #0 is equal to 1,\n" + "element #1 is equal to 2", + Describe(m)); + EXPECT_EQ( + "(when sorted) doesn't have 2 elements, or\n" + "element #0 isn't equal to 1, or\n" + "element #1 isn't equal to 2", + DescribeNegation(m)); } TEST(WhenSortedByTest, ExplainsMatchResult) { @@ -5374,43 +5340,37 @@ TEST(WhenSortedTest, WorksForMapTypes) { } TEST(WhenSortedTest, WorksForMultiMapTypes) { - multimap<int, int> ifib; - ifib.insert(make_pair(8, 6)); - ifib.insert(make_pair(2, 3)); - ifib.insert(make_pair(1, 1)); - ifib.insert(make_pair(3, 4)); - ifib.insert(make_pair(1, 2)); - ifib.insert(make_pair(5, 5)); - EXPECT_THAT(ifib, WhenSorted(ElementsAre(Pair(1, 1), - Pair(1, 2), - Pair(2, 3), - Pair(3, 4), - Pair(5, 5), - Pair(8, 6)))); - EXPECT_THAT(ifib, Not(WhenSorted(ElementsAre(Pair(8, 6), - Pair(2, 3), - Pair(1, 1), - Pair(3, 4), - Pair(1, 2), - Pair(5, 5))))); + multimap<int, int> ifib; + ifib.insert(make_pair(8, 6)); + ifib.insert(make_pair(2, 3)); + ifib.insert(make_pair(1, 1)); + ifib.insert(make_pair(3, 4)); + ifib.insert(make_pair(1, 2)); + ifib.insert(make_pair(5, 5)); + EXPECT_THAT(ifib, + WhenSorted(ElementsAre(Pair(1, 1), Pair(1, 2), Pair(2, 3), + Pair(3, 4), Pair(5, 5), Pair(8, 6)))); + EXPECT_THAT(ifib, + Not(WhenSorted(ElementsAre(Pair(8, 6), Pair(2, 3), Pair(1, 1), + Pair(3, 4), Pair(1, 2), Pair(5, 5))))); } TEST(WhenSortedTest, WorksForPolymorphicMatcher) { - std::deque<int> d; - d.push_back(2); - d.push_back(1); - EXPECT_THAT(d, WhenSorted(ElementsAre(1, 2))); - EXPECT_THAT(d, Not(WhenSorted(ElementsAre(2, 1)))); + std::deque<int> d; + d.push_back(2); + d.push_back(1); + EXPECT_THAT(d, WhenSorted(ElementsAre(1, 2))); + EXPECT_THAT(d, Not(WhenSorted(ElementsAre(2, 1)))); } TEST(WhenSortedTest, WorksForVectorConstRefMatcher) { - std::deque<int> d; - d.push_back(2); - d.push_back(1); - Matcher<const std::vector<int>&> vector_match = ElementsAre(1, 2); - EXPECT_THAT(d, WhenSorted(vector_match)); - Matcher<const std::vector<int>&> not_vector_match = ElementsAre(2, 1); - EXPECT_THAT(d, Not(WhenSorted(not_vector_match))); + std::deque<int> d; + d.push_back(2); + d.push_back(1); + Matcher<const std::vector<int>&> vector_match = ElementsAre(1, 2); + EXPECT_THAT(d, WhenSorted(vector_match)); + Matcher<const std::vector<int>&> not_vector_match = ElementsAre(2, 1); + EXPECT_THAT(d, Not(WhenSorted(not_vector_match))); } // Deliberately bare pseudo-container. @@ -5419,6 +5379,7 @@ template <typename T> class Streamlike { private: class ConstIter; + public: typedef ConstIter const_iterator; typedef T value_type; @@ -5429,9 +5390,7 @@ class Streamlike { const_iterator begin() const { return const_iterator(this, remainder_.begin()); } - const_iterator end() const { - return const_iterator(this, remainder_.end()); - } + const_iterator end() const { return const_iterator(this, remainder_.end()); } private: class ConstIter { @@ -5442,8 +5401,7 @@ class Streamlike { using pointer = const value_type*; using reference = const value_type&; - ConstIter(const Streamlike* s, - typename std::list<value_type>::iterator pos) + ConstIter(const Streamlike* s, typename std::list<value_type>::iterator pos) : s_(s), pos_(pos) {} const value_type& operator*() const { return *pos_; } @@ -5459,6 +5417,7 @@ class Streamlike { public: explicit PostIncrProxy(const value_type& value) : value_(value) {} value_type operator*() const { return value_; } + private: value_type value_; }; @@ -5525,7 +5484,7 @@ TEST(BeginEndDistanceIsTest, WorksWithNonStdList) { } TEST(BeginEndDistanceIsTest, CanDescribeSelf) { - Matcher<vector<int> > m = BeginEndDistanceIs(2); + Matcher<vector<int>> m = BeginEndDistanceIs(2); EXPECT_EQ("distance between begin() and end() is equal to 2", Describe(m)); EXPECT_EQ("distance between begin() and end() isn't equal to 2", DescribeNegation(m)); @@ -5538,10 +5497,10 @@ TEST(BeginEndDistanceIsTest, WorksWithMoveOnly) { } TEST(BeginEndDistanceIsTest, ExplainsResult) { - Matcher<vector<int> > m1 = BeginEndDistanceIs(2); - Matcher<vector<int> > m2 = BeginEndDistanceIs(Lt(2)); - Matcher<vector<int> > m3 = BeginEndDistanceIs(AnyOf(0, 3)); - Matcher<vector<int> > m4 = BeginEndDistanceIs(GreaterThan(1)); + Matcher<vector<int>> m1 = BeginEndDistanceIs(2); + Matcher<vector<int>> m2 = BeginEndDistanceIs(Lt(2)); + Matcher<vector<int>> m3 = BeginEndDistanceIs(AnyOf(0, 3)); + Matcher<vector<int>> m4 = BeginEndDistanceIs(GreaterThan(1)); vector<int> container; EXPECT_EQ("whose distance between begin() and end() 0 doesn't match", Explain(m1, container)); @@ -5902,8 +5861,8 @@ TEST(UnorderedElementsAreArrayTest, SucceedsWhenExpected) { std::vector<int> s(std::begin(a), std::end(a)); do { StringMatchResultListener listener; - EXPECT_TRUE(ExplainMatchResult(UnorderedElementsAreArray(a), - s, &listener)) << listener.str(); + EXPECT_TRUE(ExplainMatchResult(UnorderedElementsAreArray(a), s, &listener)) + << listener.str(); } while (std::next_permutation(s.begin(), s.end())); } @@ -5913,8 +5872,9 @@ TEST(UnorderedElementsAreArrayTest, VectorBool) { std::vector<bool> expected(std::begin(a), std::end(a)); std::vector<bool> actual(std::begin(b), std::end(b)); StringMatchResultListener listener; - EXPECT_TRUE(ExplainMatchResult(UnorderedElementsAreArray(expected), - actual, &listener)) << listener.str(); + EXPECT_TRUE(ExplainMatchResult(UnorderedElementsAreArray(expected), actual, + &listener)) + << listener.str(); } TEST(UnorderedElementsAreArrayTest, WorksForStreamlike) { @@ -5949,7 +5909,6 @@ TEST(UnorderedElementsAreArrayTest, TakesStlContainer) { EXPECT_THAT(actual, Not(UnorderedElementsAreArray(expected))); } - TEST(UnorderedElementsAreArrayTest, TakesInitializerList) { const int a[5] = {2, 1, 4, 5, 3}; EXPECT_THAT(a, UnorderedElementsAreArray({1, 2, 3, 4, 5})); @@ -5964,10 +5923,10 @@ TEST(UnorderedElementsAreArrayTest, TakesInitializerListOfCStrings) { TEST(UnorderedElementsAreArrayTest, TakesInitializerListOfSameTypedMatchers) { const int a[5] = {2, 1, 4, 5, 3}; - EXPECT_THAT(a, UnorderedElementsAreArray( - {Eq(1), Eq(2), Eq(3), Eq(4), Eq(5)})); - EXPECT_THAT(a, Not(UnorderedElementsAreArray( - {Eq(1), Eq(2), Eq(3), Eq(4), Eq(6)}))); + EXPECT_THAT(a, + UnorderedElementsAreArray({Eq(1), Eq(2), Eq(3), Eq(4), Eq(5)})); + EXPECT_THAT( + a, Not(UnorderedElementsAreArray({Eq(1), Eq(2), Eq(3), Eq(4), Eq(6)}))); } TEST(UnorderedElementsAreArrayTest, @@ -5976,13 +5935,12 @@ TEST(UnorderedElementsAreArrayTest, // The compiler cannot infer the type of the initializer list if its // elements have different types. We must explicitly specify the // unified element type in this case. - EXPECT_THAT(a, UnorderedElementsAreArray<Matcher<int> >( - {Eq(1), Ne(-2), Ge(3), Le(4), Eq(5)})); - EXPECT_THAT(a, Not(UnorderedElementsAreArray<Matcher<int> >( - {Eq(1), Ne(-2), Ge(3), Le(4), Eq(6)}))); + EXPECT_THAT(a, UnorderedElementsAreArray<Matcher<int>>( + {Eq(1), Ne(-2), Ge(3), Le(4), Eq(5)})); + EXPECT_THAT(a, Not(UnorderedElementsAreArray<Matcher<int>>( + {Eq(1), Ne(-2), Ge(3), Le(4), Eq(6)}))); } - TEST(UnorderedElementsAreArrayTest, WorksWithMoveOnly) { ContainerHelper helper; EXPECT_CALL(helper, @@ -6008,22 +5966,22 @@ TEST_F(UnorderedElementsAreTest, SucceedsWhenExpected) { std::vector<int> s(std::begin(a), std::end(a)); do { StringMatchResultListener listener; - EXPECT_TRUE(ExplainMatchResult(UnorderedElementsAre(1, 2, 3), - s, &listener)) << listener.str(); + EXPECT_TRUE(ExplainMatchResult(UnorderedElementsAre(1, 2, 3), s, &listener)) + << listener.str(); } while (std::next_permutation(s.begin(), s.end())); } TEST_F(UnorderedElementsAreTest, FailsWhenAnElementMatchesNoMatcher) { const int a[] = {1, 2, 3}; std::vector<int> s(std::begin(a), std::end(a)); - std::vector<Matcher<int> > mv; + std::vector<Matcher<int>> mv; mv.push_back(1); mv.push_back(2); mv.push_back(2); // The element with value '3' matches nothing: fail fast. StringMatchResultListener listener; - EXPECT_FALSE(ExplainMatchResult(UnorderedElementsAreArray(mv), - s, &listener)) << listener.str(); + EXPECT_FALSE(ExplainMatchResult(UnorderedElementsAreArray(mv), s, &listener)) + << listener.str(); } TEST_F(UnorderedElementsAreTest, WorksForStreamlike) { @@ -6051,15 +6009,15 @@ TEST_F(UnorderedElementsAreTest, WorksWithMoveOnly) { // [ OK ] UnorderedElementsAreTest.Performance (4 ms) TEST_F(UnorderedElementsAreTest, Performance) { std::vector<int> s; - std::vector<Matcher<int> > mv; + std::vector<Matcher<int>> mv; for (int i = 0; i < 100; ++i) { s.push_back(i); mv.push_back(_); } mv[50] = Eq(0); StringMatchResultListener listener; - EXPECT_TRUE(ExplainMatchResult(UnorderedElementsAreArray(mv), - s, &listener)) << listener.str(); + EXPECT_TRUE(ExplainMatchResult(UnorderedElementsAreArray(mv), s, &listener)) + << listener.str(); } // Another variant of 'Performance' with similar expectations. @@ -6067,7 +6025,7 @@ TEST_F(UnorderedElementsAreTest, Performance) { // [ OK ] UnorderedElementsAreTest.PerformanceHalfStrict (4 ms) TEST_F(UnorderedElementsAreTest, PerformanceHalfStrict) { std::vector<int> s; - std::vector<Matcher<int> > mv; + std::vector<Matcher<int>> mv; for (int i = 0; i < 100; ++i) { s.push_back(i); if (i & 1) { @@ -6077,24 +6035,24 @@ TEST_F(UnorderedElementsAreTest, PerformanceHalfStrict) { } } StringMatchResultListener listener; - EXPECT_TRUE(ExplainMatchResult(UnorderedElementsAreArray(mv), - s, &listener)) << listener.str(); + EXPECT_TRUE(ExplainMatchResult(UnorderedElementsAreArray(mv), s, &listener)) + << listener.str(); } TEST_F(UnorderedElementsAreTest, FailMessageCountWrong) { std::vector<int> v; v.push_back(4); StringMatchResultListener listener; - EXPECT_FALSE(ExplainMatchResult(UnorderedElementsAre(1, 2, 3), - v, &listener)) << listener.str(); + EXPECT_FALSE(ExplainMatchResult(UnorderedElementsAre(1, 2, 3), v, &listener)) + << listener.str(); EXPECT_THAT(listener.str(), Eq("which has 1 element")); } TEST_F(UnorderedElementsAreTest, FailMessageCountWrongZero) { std::vector<int> v; StringMatchResultListener listener; - EXPECT_FALSE(ExplainMatchResult(UnorderedElementsAre(1, 2, 3), - v, &listener)) << listener.str(); + EXPECT_FALSE(ExplainMatchResult(UnorderedElementsAre(1, 2, 3), v, &listener)) + << listener.str(); EXPECT_THAT(listener.str(), Eq("")); } @@ -6103,12 +6061,11 @@ TEST_F(UnorderedElementsAreTest, FailMessageUnmatchedMatchers) { v.push_back(1); v.push_back(1); StringMatchResultListener listener; - EXPECT_FALSE(ExplainMatchResult(UnorderedElementsAre(1, 2), - v, &listener)) << listener.str(); - EXPECT_THAT( - listener.str(), - Eq("where the following matchers don't match any elements:\n" - "matcher #1: is equal to 2")); + EXPECT_FALSE(ExplainMatchResult(UnorderedElementsAre(1, 2), v, &listener)) + << listener.str(); + EXPECT_THAT(listener.str(), + Eq("where the following matchers don't match any elements:\n" + "matcher #1: is equal to 2")); } TEST_F(UnorderedElementsAreTest, FailMessageUnmatchedElements) { @@ -6116,12 +6073,11 @@ TEST_F(UnorderedElementsAreTest, FailMessageUnmatchedElements) { v.push_back(1); v.push_back(2); StringMatchResultListener listener; - EXPECT_FALSE(ExplainMatchResult(UnorderedElementsAre(1, 1), - v, &listener)) << listener.str(); - EXPECT_THAT( - listener.str(), - Eq("where the following elements don't match any matchers:\n" - "element #1: 2")); + EXPECT_FALSE(ExplainMatchResult(UnorderedElementsAre(1, 1), v, &listener)) + << listener.str(); + EXPECT_THAT(listener.str(), + Eq("where the following elements don't match any matchers:\n" + "element #1: 2")); } TEST_F(UnorderedElementsAreTest, FailMessageUnmatchedMatcherAndElement) { @@ -6129,17 +6085,16 @@ TEST_F(UnorderedElementsAreTest, FailMessageUnmatchedMatcherAndElement) { v.push_back(2); v.push_back(3); StringMatchResultListener listener; - EXPECT_FALSE(ExplainMatchResult(UnorderedElementsAre(1, 2), - v, &listener)) << listener.str(); - EXPECT_THAT( - listener.str(), - Eq("where" - " the following matchers don't match any elements:\n" - "matcher #0: is equal to 1\n" - "and" - " where" - " the following elements don't match any matchers:\n" - "element #1: 3")); + EXPECT_FALSE(ExplainMatchResult(UnorderedElementsAre(1, 2), v, &listener)) + << listener.str(); + EXPECT_THAT(listener.str(), + Eq("where" + " the following matchers don't match any elements:\n" + "matcher #0: is equal to 1\n" + "and" + " where" + " the following elements don't match any matchers:\n" + "element #1: 3")); } // Test helper for formatting element, matcher index pairs in expectations. @@ -6169,29 +6124,24 @@ TEST_F(UnorderedElementsAreTest, FailMessageImperfectMatchOnly) { // We have to be a bit loose here, because there are 4 valid max matches. EXPECT_THAT( listener.str(), - AnyOf(prefix + "{\n " + EMString(0, 0) + - ",\n " + EMString(1, 2) + "\n}", - prefix + "{\n " + EMString(0, 1) + - ",\n " + EMString(1, 2) + "\n}", - prefix + "{\n " + EMString(0, 0) + - ",\n " + EMString(2, 2) + "\n}", - prefix + "{\n " + EMString(0, 1) + - ",\n " + EMString(2, 2) + "\n}")); + AnyOf( + prefix + "{\n " + EMString(0, 0) + ",\n " + EMString(1, 2) + "\n}", + prefix + "{\n " + EMString(0, 1) + ",\n " + EMString(1, 2) + "\n}", + prefix + "{\n " + EMString(0, 0) + ",\n " + EMString(2, 2) + "\n}", + prefix + "{\n " + EMString(0, 1) + ",\n " + EMString(2, 2) + + "\n}")); } TEST_F(UnorderedElementsAreTest, Describe) { - EXPECT_THAT(Describe<IntVec>(UnorderedElementsAre()), - Eq("is empty")); - EXPECT_THAT( - Describe<IntVec>(UnorderedElementsAre(345)), - Eq("has 1 element and that element is equal to 345")); - EXPECT_THAT( - Describe<IntVec>(UnorderedElementsAre(111, 222, 333)), - Eq("has 3 elements and there exists some permutation " - "of elements such that:\n" - " - element #0 is equal to 111, and\n" - " - element #1 is equal to 222, and\n" - " - element #2 is equal to 333")); + EXPECT_THAT(Describe<IntVec>(UnorderedElementsAre()), Eq("is empty")); + EXPECT_THAT(Describe<IntVec>(UnorderedElementsAre(345)), + Eq("has 1 element and that element is equal to 345")); + EXPECT_THAT(Describe<IntVec>(UnorderedElementsAre(111, 222, 333)), + Eq("has 3 elements and there exists some permutation " + "of elements such that:\n" + " - element #0 is equal to 111, and\n" + " - element #1 is equal to 222, and\n" + " - element #2 is equal to 333")); } TEST_F(UnorderedElementsAreTest, DescribeNegation) { @@ -6200,13 +6150,12 @@ TEST_F(UnorderedElementsAreTest, DescribeNegation) { EXPECT_THAT( DescribeNegation<IntVec>(UnorderedElementsAre(345)), Eq("doesn't have 1 element, or has 1 element that isn't equal to 345")); - EXPECT_THAT( - DescribeNegation<IntVec>(UnorderedElementsAre(123, 234, 345)), - Eq("doesn't have 3 elements, or there exists no permutation " - "of elements such that:\n" - " - element #0 is equal to 123, and\n" - " - element #1 is equal to 234, and\n" - " - element #2 is equal to 345")); + EXPECT_THAT(DescribeNegation<IntVec>(UnorderedElementsAre(123, 234, 345)), + Eq("doesn't have 3 elements, or there exists no permutation " + "of elements such that:\n" + " - element #0 is equal to 123, and\n" + " - element #1 is equal to 234, and\n" + " - element #2 is equal to 345")); } namespace { @@ -6219,7 +6168,7 @@ template <typename Graph> class BacktrackingMaxBPMState { public: // Does not take ownership of 'g'. - explicit BacktrackingMaxBPMState(const Graph* g) : graph_(g) { } + explicit BacktrackingMaxBPMState(const Graph* g) : graph_(g) {} ElementMatcherPairs Compute() { if (graph_->LhsSize() == 0 || graph_->RhsSize() == 0) { @@ -6230,8 +6179,7 @@ class BacktrackingMaxBPMState { for (size_t irhs = 0; irhs < graph_->RhsSize(); ++irhs) { matches_.clear(); RecurseInto(irhs); - if (best_so_far_.size() == graph_->RhsSize()) - break; + if (best_so_far_.size() == graph_->RhsSize()) break; } return best_so_far_; } @@ -6293,12 +6241,11 @@ const size_t BacktrackingMaxBPMState<Graph>::kUnused; // Implement a simple backtracking algorithm to determine if it is possible // to find one element per matcher, without reusing elements. template <typename Graph> -ElementMatcherPairs -FindBacktrackingMaxBPM(const Graph& g) { +ElementMatcherPairs FindBacktrackingMaxBPM(const Graph& g) { return BacktrackingMaxBPMState<Graph>(&g).Compute(); } -class BacktrackingBPMTest : public ::testing::Test { }; +class BacktrackingBPMTest : public ::testing::Test {}; // Tests the MaxBipartiteMatching algorithm with square matrices. // The single int param is the # of nodes on each of the left and right sides. @@ -6309,8 +6256,7 @@ TEST_P(BipartiteTest, Exhaustive) { size_t nodes = GetParam(); MatchMatrix graph(nodes, nodes); do { - ElementMatcherPairs matches = - internal::FindMaxBipartiteMatching(graph); + ElementMatcherPairs matches = internal::FindMaxBipartiteMatching(graph); EXPECT_EQ(FindBacktrackingMaxBPM(graph).size(), matches.size()) << "graph: " << graph.DebugString(); // Check that all elements of matches are in the graph. @@ -6335,8 +6281,7 @@ INSTANTIATE_TEST_SUITE_P(AllGraphs, BipartiteTest, // Parameterized by a pair interpreted as (LhsSize, RhsSize). class BipartiteNonSquareTest - : public ::testing::TestWithParam<std::pair<size_t, size_t> > { -}; + : public ::testing::TestWithParam<std::pair<size_t, size_t>> {}; TEST_F(BipartiteNonSquareTest, SimpleBacktracking) { // ....... @@ -6353,9 +6298,8 @@ TEST_F(BipartiteNonSquareTest, SimpleBacktracking) { g.SetEdge(kEdges[i][0], kEdges[i][1], true); } EXPECT_THAT(FindBacktrackingMaxBPM(g), - ElementsAre(Pair(3, 0), - Pair(AnyOf(1, 2), 1), - Pair(0, 2))) << g.DebugString(); + ElementsAre(Pair(3, 0), Pair(AnyOf(1, 2), 1), Pair(0, 2))) + << g.DebugString(); } // Verify a few nonsquare matrices. @@ -6367,27 +6311,21 @@ TEST_P(BipartiteNonSquareTest, Exhaustive) { EXPECT_EQ(FindBacktrackingMaxBPM(graph).size(), internal::FindMaxBipartiteMatching(graph).size()) << "graph: " << graph.DebugString() - << "\nbacktracking: " - << PrintToString(FindBacktrackingMaxBPM(graph)) + << "\nbacktracking: " << PrintToString(FindBacktrackingMaxBPM(graph)) << "\nmax flow: " << PrintToString(internal::FindMaxBipartiteMatching(graph)); } while (graph.NextGraph()); } -INSTANTIATE_TEST_SUITE_P(AllGraphs, BipartiteNonSquareTest, - testing::Values( - std::make_pair(1, 2), - std::make_pair(2, 1), - std::make_pair(3, 2), - std::make_pair(2, 3), - std::make_pair(4, 1), - std::make_pair(1, 4), - std::make_pair(4, 3), - std::make_pair(3, 4))); +INSTANTIATE_TEST_SUITE_P( + AllGraphs, BipartiteNonSquareTest, + testing::Values(std::make_pair(1, 2), std::make_pair(2, 1), + std::make_pair(3, 2), std::make_pair(2, 3), + std::make_pair(4, 1), std::make_pair(1, 4), + std::make_pair(4, 3), std::make_pair(3, 4))); class BipartiteRandomTest - : public ::testing::TestWithParam<std::pair<int, int> > { -}; + : public ::testing::TestWithParam<std::pair<int, int>> {}; // Verifies a large sample of larger graphs. TEST_P(BipartiteRandomTest, LargerNets) { @@ -6407,18 +6345,18 @@ TEST_P(BipartiteRandomTest, LargerNets) { internal::FindMaxBipartiteMatching(graph).size()) << " graph: " << graph.DebugString() << "\nTo reproduce the failure, rerun the test with the flag" - " --" << GTEST_FLAG_PREFIX_ << "random_seed=" << seed; + " --" + << GTEST_FLAG_PREFIX_ << "random_seed=" << seed; } } // Test argument is a std::pair<int, int> representing (nodes, iters). INSTANTIATE_TEST_SUITE_P(Samples, BipartiteRandomTest, - testing::Values( - std::make_pair(5, 10000), - std::make_pair(6, 5000), - std::make_pair(7, 2000), - std::make_pair(8, 500), - std::make_pair(9, 100))); + testing::Values(std::make_pair(5, 10000), + std::make_pair(6, 5000), + std::make_pair(7, 2000), + std::make_pair(8, 500), + std::make_pair(9, 100))); // Tests IsReadableTypeName(). @@ -6489,20 +6427,22 @@ TEST(MatcherTupleTest, ExplainsMatchFailure) { ExplainMatchFailureTupleTo( std::make_tuple(GreaterThan(5), Matcher<char>(Eq('a'))), std::make_tuple(2, 'b'), &ss2); - EXPECT_EQ(" Expected arg #0: is > 5\n" - " Actual: 2, which is 3 less than 5\n" - " Expected arg #1: is equal to 'a' (97, 0x61)\n" - " Actual: 'b' (98, 0x62)\n", - ss2.str()); // Failed match where both arguments need explanation. + EXPECT_EQ( + " Expected arg #0: is > 5\n" + " Actual: 2, which is 3 less than 5\n" + " Expected arg #1: is equal to 'a' (97, 0x61)\n" + " Actual: 'b' (98, 0x62)\n", + ss2.str()); // Failed match where both arguments need explanation. stringstream ss3; ExplainMatchFailureTupleTo( std::make_tuple(GreaterThan(5), Matcher<char>(Eq('a'))), std::make_tuple(2, 'a'), &ss3); - EXPECT_EQ(" Expected arg #0: is > 5\n" - " Actual: 2, which is 3 less than 5\n", - ss3.str()); // Failed match where only one argument needs - // explanation. + EXPECT_EQ( + " Expected arg #0: is > 5\n" + " Actual: 2, which is 3 less than 5\n", + ss3.str()); // Failed match where only one argument needs + // explanation. } // Tests Each(). @@ -6510,7 +6450,7 @@ TEST(MatcherTupleTest, ExplainsMatchFailure) { TEST(EachTest, ExplainsMatchResultCorrectly) { set<int> a; // empty - Matcher<set<int> > m = Each(2); + Matcher<set<int>> m = Each(2); EXPECT_EQ("", Explain(m, a)); Matcher<const int(&)[1]> n = Each(1); // NOLINT @@ -6533,10 +6473,10 @@ TEST(EachTest, ExplainsMatchResultCorrectly) { } TEST(EachTest, DescribesItselfCorrectly) { - Matcher<vector<int> > m = Each(1); + Matcher<vector<int>> m = Each(1); EXPECT_EQ("only contains elements that is equal to 1", Describe(m)); - Matcher<vector<int> > m2 = Not(m); + Matcher<vector<int>> m2 = Not(m); EXPECT_EQ("contains some element that isn't equal to 1", Describe(m2)); } @@ -6631,13 +6571,15 @@ TEST(PointwiseTest, DescribesSelf) { rhs.push_back(2); rhs.push_back(3); const Matcher<const vector<int>&> m = Pointwise(IsHalfOf(), rhs); - EXPECT_EQ("contains 3 values, where each value and its corresponding value " - "in { 1, 2, 3 } are a pair where the first is half of the second", - Describe(m)); - EXPECT_EQ("doesn't contain exactly 3 values, or contains a value x at some " - "index i where x and the i-th value of { 1, 2, 3 } are a pair " - "where the first isn't half of the second", - DescribeNegation(m)); + EXPECT_EQ( + "contains 3 values, where each value and its corresponding value " + "in { 1, 2, 3 } are a pair where the first is half of the second", + Describe(m)); + EXPECT_EQ( + "doesn't contain exactly 3 values, or contains a value x at some " + "index i where x and the i-th value of { 1, 2, 3 } are a pair " + "where the first isn't half of the second", + DescribeNegation(m)); } TEST(PointwiseTest, MakesCopyOfRhs) { @@ -6646,7 +6588,7 @@ TEST(PointwiseTest, MakesCopyOfRhs) { rhs.push_back(4); int lhs[] = {1, 2}; - const Matcher<const int (&)[2]> m = Pointwise(IsHalfOf(), rhs); + const Matcher<const int(&)[2]> m = Pointwise(IsHalfOf(), rhs); EXPECT_THAT(lhs, m); // Changing rhs now shouldn't affect m, which made a copy of rhs. @@ -6684,20 +6626,17 @@ TEST(PointwiseTest, WorksForVectorOfBool) { EXPECT_THAT(lhs, Not(Pointwise(Eq(), rhs))); } - TEST(PointwiseTest, WorksForRhsInitializerList) { const vector<int> lhs{2, 4, 6}; EXPECT_THAT(lhs, Pointwise(Gt(), {1, 2, 3})); EXPECT_THAT(lhs, Not(Pointwise(Lt(), {3, 3, 7}))); } - TEST(PointwiseTest, RejectsWrongSize) { const double lhs[2] = {1, 2}; const int rhs[1] = {0}; EXPECT_THAT(lhs, Not(Pointwise(Gt(), rhs))); - EXPECT_EQ("which contains 2 values", - Explain(Pointwise(Gt(), rhs), lhs)); + EXPECT_EQ("which contains 2 values", Explain(Pointwise(Gt(), rhs), lhs)); const int rhs2[3] = {0, 1, 2}; EXPECT_THAT(lhs, Not(Pointwise(Gt(), rhs2))); @@ -6707,9 +6646,10 @@ TEST(PointwiseTest, RejectsWrongContent) { const double lhs[3] = {1, 2, 3}; const int rhs[3] = {2, 6, 4}; EXPECT_THAT(lhs, Not(Pointwise(IsHalfOf(), rhs))); - EXPECT_EQ("where the value pair (2, 6) at index #1 don't match, " - "where the second/2 is 3", - Explain(Pointwise(IsHalfOf(), rhs), lhs)); + EXPECT_EQ( + "where the value pair (2, 6) at index #1 don't match, " + "where the second/2 is 3", + Explain(Pointwise(IsHalfOf(), rhs), lhs)); } TEST(PointwiseTest, AcceptsCorrectContent) { @@ -6776,7 +6716,7 @@ TEST(UnorderedPointwiseTest, MakesCopyOfRhs) { rhs.push_back(4); int lhs[] = {2, 1}; - const Matcher<const int (&)[2]> m = UnorderedPointwise(IsHalfOf(), rhs); + const Matcher<const int(&)[2]> m = UnorderedPointwise(IsHalfOf(), rhs); EXPECT_THAT(lhs, m); // Changing rhs now shouldn't affect m, which made a copy of rhs. @@ -6804,14 +6744,12 @@ TEST(UnorderedPointwiseTest, WorksForRhsNativeArray) { EXPECT_THAT(lhs, Not(UnorderedPointwise(Lt(), rhs))); } - TEST(UnorderedPointwiseTest, WorksForRhsInitializerList) { const vector<int> lhs{2, 4, 6}; EXPECT_THAT(lhs, UnorderedPointwise(Gt(), {5, 1, 3})); EXPECT_THAT(lhs, Not(UnorderedPointwise(Lt(), {1, 1, 7}))); } - TEST(UnorderedPointwiseTest, RejectsWrongSize) { const double lhs[2] = {1, 2}; const int rhs[1] = {0}; @@ -6827,9 +6765,10 @@ TEST(UnorderedPointwiseTest, RejectsWrongContent) { const double lhs[3] = {1, 2, 3}; const int rhs[3] = {2, 6, 6}; EXPECT_THAT(lhs, Not(UnorderedPointwise(IsHalfOf(), rhs))); - EXPECT_EQ("where the following elements don't match any matchers:\n" - "element #1: 2", - Explain(UnorderedPointwise(IsHalfOf(), rhs), lhs)); + EXPECT_EQ( + "where the following elements don't match any matchers:\n" + "element #1: 2", + Explain(UnorderedPointwise(IsHalfOf(), rhs), lhs)); } TEST(UnorderedPointwiseTest, AcceptsCorrectContentInSameOrder) { @@ -7119,9 +7058,7 @@ TEST(ArgsTest, CanMatchTupleByReference) { } // Validates that arg is printed as str. -MATCHER_P(PrintsAs, str, "") { - return testing::PrintToString(arg) == str; -} +MATCHER_P(PrintsAs, str, "") { return testing::PrintToString(arg) == str; } TEST(ArgsTest, AcceptsTenTemplateArgs) { EXPECT_THAT(std::make_tuple(0, 1L, 2, 3L, 4, 5, 6, 7, 8, 9), @@ -7133,29 +7070,32 @@ TEST(ArgsTest, AcceptsTenTemplateArgs) { } TEST(ArgsTest, DescirbesSelfCorrectly) { - const Matcher<std::tuple<int, bool, char> > m = Args<2, 0>(Lt()); - EXPECT_EQ("are a tuple whose fields (#2, #0) are a pair where " - "the first < the second", - Describe(m)); + const Matcher<std::tuple<int, bool, char>> m = Args<2, 0>(Lt()); + EXPECT_EQ( + "are a tuple whose fields (#2, #0) are a pair where " + "the first < the second", + Describe(m)); } TEST(ArgsTest, DescirbesNestedArgsCorrectly) { const Matcher<const std::tuple<int, bool, char, int>&> m = Args<0, 2, 3>(Args<2, 0>(Lt())); - EXPECT_EQ("are a tuple whose fields (#0, #2, #3) are a tuple " - "whose fields (#2, #0) are a pair where the first < the second", - Describe(m)); + EXPECT_EQ( + "are a tuple whose fields (#0, #2, #3) are a tuple " + "whose fields (#2, #0) are a pair where the first < the second", + Describe(m)); } TEST(ArgsTest, DescribesNegationCorrectly) { - const Matcher<std::tuple<int, char> > m = Args<1, 0>(Gt()); - EXPECT_EQ("are a tuple whose fields (#1, #0) aren't a pair " - "where the first > the second", - DescribeNegation(m)); + const Matcher<std::tuple<int, char>> m = Args<1, 0>(Gt()); + EXPECT_EQ( + "are a tuple whose fields (#1, #0) aren't a pair " + "where the first > the second", + DescribeNegation(m)); } TEST(ArgsTest, ExplainsMatchResultWithoutInnerExplanation) { - const Matcher<std::tuple<bool, int, int> > m = Args<1, 2>(Eq()); + const Matcher<std::tuple<bool, int, int>> m = Args<1, 2>(Eq()); EXPECT_EQ("whose fields (#1, #2) are (42, 42)", Explain(m, std::make_tuple(false, 42, 42))); EXPECT_EQ("whose fields (#1, #2) are (42, 43)", @@ -7163,7 +7103,7 @@ TEST(ArgsTest, ExplainsMatchResultWithoutInnerExplanation) { } // For testing Args<>'s explanation. -class LessThanMatcher : public MatcherInterface<std::tuple<char, int> > { +class LessThanMatcher : public MatcherInterface<std::tuple<char, int>> { public: void DescribeTo(::std::ostream* /*os*/) const override {} @@ -7178,12 +7118,12 @@ class LessThanMatcher : public MatcherInterface<std::tuple<char, int> > { } }; -Matcher<std::tuple<char, int> > LessThan() { +Matcher<std::tuple<char, int>> LessThan() { return MakeMatcher(new LessThanMatcher); } TEST(ArgsTest, ExplainsMatchResultWithInnerExplanation) { - const Matcher<std::tuple<char, int, int> > m = Args<0, 2>(LessThan()); + const Matcher<std::tuple<char, int, int>> m = Args<0, 2>(LessThan()); EXPECT_EQ( "whose fields (#0, #2) are ('a' (97, 0x61), 42), " "where the first value is 55 more than the second", @@ -8698,5 +8638,5 @@ TEST(ThrowsPredicateCompilesTest, MessageMatcherAcceptsNonMatcher) { } // namespace testing #ifdef _MSC_VER -# pragma warning(pop) +#pragma warning(pop) #endif diff --git a/googlemock/test/gmock-more-actions_test.cc b/googlemock/test/gmock-more-actions_test.cc index fdc8c70..b9b66bf 100644 --- a/googlemock/test/gmock-more-actions_test.cc +++ b/googlemock/test/gmock-more-actions_test.cc @@ -145,7 +145,7 @@ class Foo { std::string Binary(const std::string& str, char c) const { return str + c; } - int Ternary(int x, bool y, char z) { return value_ + x + y*z; } + int Ternary(int x, bool y, char z) { return value_ + x + y * z; } int SumOf4(int a, int b, int c, int d) const { return a + b + c + d + value_; @@ -291,8 +291,7 @@ TEST(InvokeTest, FunctionWithUnusedParameters) { std::make_tuple(10, 2, 5.6, std::string("hi")); EXPECT_EQ(12, a1.Perform(dummy)); - Action<int(int, int, bool, int*)> a2 = - Invoke(SumOfFirst2); + Action<int(int, int, bool, int*)> a2 = Invoke(SumOfFirst2); EXPECT_EQ( 23, a2.Perform(std::make_tuple(20, 3, true, static_cast<int*>(nullptr)))); } @@ -303,8 +302,7 @@ TEST(InvokeTest, MethodWithUnusedParameters) { Action<int(std::string, bool, int, int)> a1 = Invoke(&foo, &Foo::SumOfLast2); EXPECT_EQ(12, a1.Perform(std::make_tuple(CharPtr("hi"), true, 10, 2))); - Action<int(char, double, int, int)> a2 = - Invoke(&foo, &Foo::SumOfLast2); + Action<int(char, double, int, int)> a2 = Invoke(&foo, &Foo::SumOfLast2); EXPECT_EQ(23, a2.Perform(std::make_tuple('a', 2.5, 20, 3))); } @@ -362,7 +360,8 @@ TEST(InvokeMethodTest, MethodThatTakes4Arguments) { // Tests using Invoke() with a 5-argument method. TEST(InvokeMethodTest, MethodThatTakes5Arguments) { Foo foo; - Action<int(int, int, int, int, int)> a = Invoke(&foo, &Foo::SumOf5); // NOLINT + Action<int(int, int, int, int, int)> a = + Invoke(&foo, &Foo::SumOf5); // NOLINT EXPECT_EQ(12345, a.Perform(std::make_tuple(10000, 2000, 300, 40, 5))); } @@ -523,15 +522,12 @@ TEST(SetArgRefereeActionTest, WorksWithExtraArguments) { // the bool provided to the constructor to true when destroyed. class DeletionTester { public: - explicit DeletionTester(bool* is_deleted) - : is_deleted_(is_deleted) { + explicit DeletionTester(bool* is_deleted) : is_deleted_(is_deleted) { // Make sure the bit is set to false. *is_deleted_ = false; } - ~DeletionTester() { - *is_deleted_ = true; - } + ~DeletionTester() { *is_deleted_ = true; } private: bool* is_deleted_; @@ -540,7 +536,7 @@ class DeletionTester { TEST(DeleteArgActionTest, OneArg) { bool is_deleted = false; DeletionTester* t = new DeletionTester(&is_deleted); - const Action<void(DeletionTester*)> a1 = DeleteArg<0>(); // NOLINT + const Action<void(DeletionTester*)> a1 = DeleteArg<0>(); // NOLINT EXPECT_FALSE(is_deleted); a1.Perform(std::make_tuple(t)); EXPECT_TRUE(is_deleted); @@ -549,8 +545,9 @@ TEST(DeleteArgActionTest, OneArg) { TEST(DeleteArgActionTest, TenArgs) { bool is_deleted = false; DeletionTester* t = new DeletionTester(&is_deleted); - const Action<void(bool, int, int, const char*, bool, - int, int, int, int, DeletionTester*)> a1 = DeleteArg<9>(); + const Action<void(bool, int, int, const char*, bool, int, int, int, int, + DeletionTester*)> + a1 = DeleteArg<9>(); EXPECT_FALSE(is_deleted); a1.Perform(std::make_tuple(true, 5, 6, CharPtr("hi"), false, 7, 8, 9, 10, t)); EXPECT_TRUE(is_deleted); @@ -608,7 +605,7 @@ TEST(ThrowActionTest, Times0) { // pointed to by the N-th (0-based) argument to values in range [first, last). TEST(SetArrayArgumentTest, SetsTheNthArray) { using MyFunction = void(bool, int*, char*); - int numbers[] = { 1, 2, 3 }; + int numbers[] = {1, 2, 3}; Action<MyFunction> a = SetArrayArgument<1>(numbers, numbers + 3); int n[4] = {}; @@ -644,7 +641,7 @@ TEST(SetArrayArgumentTest, SetsTheNthArray) { // Tests SetArrayArgument<N>(first, last) where first == last. TEST(SetArrayArgumentTest, SetsTheNthArrayWithEmptyRange) { using MyFunction = void(bool, int*); - int numbers[] = { 1, 2, 3 }; + int numbers[] = {1, 2, 3}; Action<MyFunction> a = SetArrayArgument<1>(numbers, numbers); int n[4] = {}; @@ -660,10 +657,10 @@ TEST(SetArrayArgumentTest, SetsTheNthArrayWithEmptyRange) { // (but not equal) to the argument type. TEST(SetArrayArgumentTest, SetsTheNthArrayWithConvertibleType) { using MyFunction = void(bool, int*); - char chars[] = { 97, 98, 99 }; + char chars[] = {97, 98, 99}; Action<MyFunction> a = SetArrayArgument<1>(chars, chars + 3); - int codes[4] = { 111, 222, 333, 444 }; + int codes[4] = {111, 222, 333, 444}; int* pcodes = codes; a.Perform(std::make_tuple(true, pcodes)); EXPECT_EQ(97, codes[0]); diff --git a/googlemock/test/gmock-nice-strict_test.cc b/googlemock/test/gmock-nice-strict_test.cc index 319b18d..21130d4 100644 --- a/googlemock/test/gmock-nice-strict_test.cc +++ b/googlemock/test/gmock-nice-strict_test.cc @@ -31,6 +31,7 @@ #include <string> #include <utility> + #include "gmock/gmock.h" #include "gtest/gtest-spi.h" #include "gtest/gtest.h" @@ -102,7 +103,8 @@ class MockBar { MockBar(char a1, char a2, std::string a3, std::string a4, int a5, int a6, const std::string& a7, const std::string& a8, bool a9, bool a10) { str_ = std::string() + a1 + a2 + a3 + a4 + static_cast<char>(a5) + - static_cast<char>(a6) + a7 + a8 + (a9 ? 'T' : 'F') + (a10 ? 'T' : 'F'); + static_cast<char>(a6) + a7 + a8 + (a9 ? 'T' : 'F') + + (a10 ? 'T' : 'F'); } virtual ~MockBar() {} @@ -118,7 +120,6 @@ class MockBar { GTEST_DISALLOW_COPY_AND_ASSIGN_(MockBar); }; - class MockBaz { public: class MoveOnly { @@ -161,8 +162,7 @@ TEST(RawMockTest, WarningForUninterestingCallAfterDeath) { MockFoo* const raw_foo = new MockFoo; - ON_CALL(*raw_foo, DoThis()) - .WillByDefault(Invoke(raw_foo, &MockFoo::Delete)); + ON_CALL(*raw_foo, DoThis()).WillByDefault(Invoke(raw_foo, &MockFoo::Delete)); CaptureStdout(); raw_foo->DoThis(); @@ -280,8 +280,8 @@ TEST(NiceMockTest, NonDefaultConstructor) { // Tests that NiceMock works with a mock class that has a 10-ary // non-default constructor. TEST(NiceMockTest, NonDefaultConstructor10) { - NiceMock<MockBar> nice_bar('a', 'b', "c", "d", 'e', 'f', - "g", "h", true, false); + NiceMock<MockBar> nice_bar('a', 'b', "c", "d", 'e', 'f', "g", "h", true, + false); EXPECT_EQ("abcdefghTF", nice_bar.str()); nice_bar.This(); @@ -390,8 +390,8 @@ TEST(NaggyMockTest, NonDefaultConstructor) { // Tests that NaggyMock works with a mock class that has a 10-ary // non-default constructor. TEST(NaggyMockTest, NonDefaultConstructor10) { - NaggyMock<MockBar> naggy_bar('0', '1', "2", "3", '4', '5', - "6", "7", true, false); + NaggyMock<MockBar> naggy_bar('0', '1', "2", "3", '4', '5', "6", "7", true, + false); EXPECT_EQ("01234567TF", naggy_bar.str()); naggy_bar.This(); @@ -490,8 +490,8 @@ TEST(StrictMockTest, NonDefaultConstructor) { // Tests that StrictMock works with a mock class that has a 10-ary // non-default constructor. TEST(StrictMockTest, NonDefaultConstructor10) { - StrictMock<MockBar> strict_bar('a', 'b', "c", "d", 'e', 'f', - "g", "h", true, false); + StrictMock<MockBar> strict_bar('a', 'b', "c", "d", 'e', 'f', "g", "h", true, + false); EXPECT_EQ("abcdefghTF", strict_bar.str()); EXPECT_NONFATAL_FAILURE(strict_bar.That(5, true), diff --git a/googlemock/test/gmock-port_test.cc b/googlemock/test/gmock-port_test.cc index a2c2be2..c31af82 100644 --- a/googlemock/test/gmock-port_test.cc +++ b/googlemock/test/gmock-port_test.cc @@ -27,12 +27,12 @@ // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - // Google Mock - a framework for writing C++ mock classes. // // This file tests the internal cross-platform support utilities. #include "gmock/internal/gmock-port.h" + #include "gtest/gtest.h" // NOTE: if this file is left without tests for some reason, put a dummy diff --git a/googlemock/test/gmock-pp-string_test.cc b/googlemock/test/gmock-pp-string_test.cc index 6f66cf1..53c80f4 100644 --- a/googlemock/test/gmock-pp-string_test.cc +++ b/googlemock/test/gmock-pp-string_test.cc @@ -30,11 +30,10 @@ // Google Mock - a framework for writing C++ mock classes. // // This file tests the internal preprocessor macro library. -#include "gmock/internal/gmock-pp.h" - #include <string> #include "gmock/gmock.h" +#include "gmock/internal/gmock-pp.h" namespace testing { namespace { diff --git a/googlemock/test/gmock-spec-builders_test.cc b/googlemock/test/gmock-spec-builders_test.cc index 7f29b61..b59676f 100644 --- a/googlemock/test/gmock-spec-builders_test.cc +++ b/googlemock/test/gmock-spec-builders_test.cc @@ -27,7 +27,6 @@ // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - // Google Mock - a framework for writing C++ mock classes. // // This file tests the spec builder syntax. @@ -41,8 +40,8 @@ #include "gmock/gmock.h" #include "gmock/internal/gmock-port.h" -#include "gtest/gtest.h" #include "gtest/gtest-spi.h" +#include "gtest/gtest.h" #include "gtest/internal/gtest-port.h" namespace testing { @@ -52,9 +51,7 @@ namespace internal { class ExpectationTester { public: // Sets the call count of the given expectation to the given number. - void SetCallCount(int n, ExpectationBase* exp) { - exp->call_count_ = n; - } + void SetCallCount(int n, ExpectationBase* exp) { exp->call_count_ = n; } }; } // namespace internal @@ -125,8 +122,7 @@ TEST(MockMethodTest, CanInstantiateWithIncompleteArgType) { // use the mock, as long as Google Mock knows how to print the // argument. MockIncomplete incomplete; - EXPECT_CALL(incomplete, ByRefFunc(_)) - .Times(AnyNumber()); + EXPECT_CALL(incomplete, ByRefFunc(_)).Times(AnyNumber()); } // The definition of the printer for the argument type doesn't have to @@ -162,7 +158,7 @@ class MockB { MockB() {} MOCK_CONST_METHOD0(DoB, int()); // NOLINT - MOCK_METHOD1(DoB, int(int n)); // NOLINT + MOCK_METHOD1(DoB, int(int n)); // NOLINT private: GTEST_DISALLOW_COPY_AND_ASSIGN_(MockB); @@ -253,41 +249,42 @@ TEST(OnCallSyntaxTest, EvaluatesSecondArgumentOnce) { TEST(OnCallSyntaxTest, WithIsOptional) { MockA a; - ON_CALL(a, DoA(5)) - .WillByDefault(Return()); - ON_CALL(a, DoA(_)) - .With(_) - .WillByDefault(Return()); + ON_CALL(a, DoA(5)).WillByDefault(Return()); + ON_CALL(a, DoA(_)).With(_).WillByDefault(Return()); } TEST(OnCallSyntaxTest, WithCanAppearAtMostOnce) { MockA a; - EXPECT_NONFATAL_FAILURE({ // NOLINT - ON_CALL(a, ReturnResult(_)) - .With(_) - .With(_) - .WillByDefault(Return(Result())); - }, ".With() cannot appear more than once in an ON_CALL()"); + EXPECT_NONFATAL_FAILURE( + { // NOLINT + ON_CALL(a, ReturnResult(_)) + .With(_) + .With(_) + .WillByDefault(Return(Result())); + }, + ".With() cannot appear more than once in an ON_CALL()"); } TEST(OnCallSyntaxTest, WillByDefaultIsMandatory) { MockA a; - EXPECT_DEATH_IF_SUPPORTED({ - ON_CALL(a, DoA(5)); - a.DoA(5); - }, ""); + EXPECT_DEATH_IF_SUPPORTED( + { + ON_CALL(a, DoA(5)); + a.DoA(5); + }, + ""); } TEST(OnCallSyntaxTest, WillByDefaultCanAppearAtMostOnce) { MockA a; - EXPECT_NONFATAL_FAILURE({ // NOLINT - ON_CALL(a, DoA(5)) - .WillByDefault(Return()) - .WillByDefault(Return()); - }, ".WillByDefault() must appear exactly once in an ON_CALL()"); + EXPECT_NONFATAL_FAILURE( + { // NOLINT + ON_CALL(a, DoA(5)).WillByDefault(Return()).WillByDefault(Return()); + }, + ".WillByDefault() must appear exactly once in an ON_CALL()"); } // Tests that EXPECT_CALL evaluates its arguments exactly once as @@ -315,21 +312,18 @@ TEST(ExpectCallSyntaxTest, EvaluatesSecondArgumentOnce) { TEST(ExpectCallSyntaxTest, WithIsOptional) { MockA a; - EXPECT_CALL(a, DoA(5)) - .Times(0); - EXPECT_CALL(a, DoA(6)) - .With(_) - .Times(0); + EXPECT_CALL(a, DoA(5)).Times(0); + EXPECT_CALL(a, DoA(6)).With(_).Times(0); } TEST(ExpectCallSyntaxTest, WithCanAppearAtMostOnce) { MockA a; - EXPECT_NONFATAL_FAILURE({ // NOLINT - EXPECT_CALL(a, DoA(6)) - .With(_) - .With(_); - }, ".With() cannot appear more than once in an EXPECT_CALL()"); + EXPECT_NONFATAL_FAILURE( + { // NOLINT + EXPECT_CALL(a, DoA(6)).With(_).With(_); + }, + ".With() cannot appear more than once in an EXPECT_CALL()"); a.DoA(6); } @@ -337,19 +331,19 @@ TEST(ExpectCallSyntaxTest, WithCanAppearAtMostOnce) { TEST(ExpectCallSyntaxTest, WithMustBeFirstClause) { MockA a; - EXPECT_NONFATAL_FAILURE({ // NOLINT - EXPECT_CALL(a, DoA(1)) - .Times(1) - .With(_); - }, ".With() must be the first clause in an EXPECT_CALL()"); + EXPECT_NONFATAL_FAILURE( + { // NOLINT + EXPECT_CALL(a, DoA(1)).Times(1).With(_); + }, + ".With() must be the first clause in an EXPECT_CALL()"); a.DoA(1); - EXPECT_NONFATAL_FAILURE({ // NOLINT - EXPECT_CALL(a, DoA(2)) - .WillOnce(Return()) - .With(_); - }, ".With() must be the first clause in an EXPECT_CALL()"); + EXPECT_NONFATAL_FAILURE( + { // NOLINT + EXPECT_CALL(a, DoA(2)).WillOnce(Return()).With(_); + }, + ".With() must be the first clause in an EXPECT_CALL()"); a.DoA(2); } @@ -357,12 +351,9 @@ TEST(ExpectCallSyntaxTest, WithMustBeFirstClause) { TEST(ExpectCallSyntaxTest, TimesCanBeInferred) { MockA a; - EXPECT_CALL(a, DoA(1)) - .WillOnce(Return()); + EXPECT_CALL(a, DoA(1)).WillOnce(Return()); - EXPECT_CALL(a, DoA(2)) - .WillOnce(Return()) - .WillRepeatedly(Return()); + EXPECT_CALL(a, DoA(2)).WillOnce(Return()).WillRepeatedly(Return()); a.DoA(1); a.DoA(2); @@ -372,11 +363,11 @@ TEST(ExpectCallSyntaxTest, TimesCanBeInferred) { TEST(ExpectCallSyntaxTest, TimesCanAppearAtMostOnce) { MockA a; - EXPECT_NONFATAL_FAILURE({ // NOLINT - EXPECT_CALL(a, DoA(1)) - .Times(1) - .Times(2); - }, ".Times() cannot appear more than once in an EXPECT_CALL()"); + EXPECT_NONFATAL_FAILURE( + { // NOLINT + EXPECT_CALL(a, DoA(1)).Times(1).Times(2); + }, + ".Times() cannot appear more than once in an EXPECT_CALL()"); a.DoA(1); a.DoA(1); @@ -386,11 +377,11 @@ TEST(ExpectCallSyntaxTest, TimesMustBeBeforeInSequence) { MockA a; Sequence s; - EXPECT_NONFATAL_FAILURE({ // NOLINT - EXPECT_CALL(a, DoA(1)) - .InSequence(s) - .Times(1); - }, ".Times() may only appear *before* "); + EXPECT_NONFATAL_FAILURE( + { // NOLINT + EXPECT_CALL(a, DoA(1)).InSequence(s).Times(1); + }, + ".Times() may only appear *before* "); a.DoA(1); } @@ -400,8 +391,7 @@ TEST(ExpectCallSyntaxTest, InSequenceIsOptional) { Sequence s; EXPECT_CALL(a, DoA(1)); - EXPECT_CALL(a, DoA(2)) - .InSequence(s); + EXPECT_CALL(a, DoA(2)).InSequence(s); a.DoA(1); a.DoA(2); @@ -411,9 +401,7 @@ TEST(ExpectCallSyntaxTest, InSequenceCanAppearMultipleTimes) { MockA a; Sequence s1, s2; - EXPECT_CALL(a, DoA(1)) - .InSequence(s1, s2) - .InSequence(s1); + EXPECT_CALL(a, DoA(1)).InSequence(s1, s2).InSequence(s1); a.DoA(1); } @@ -422,13 +410,12 @@ TEST(ExpectCallSyntaxTest, InSequenceMustBeBeforeAfter) { MockA a; Sequence s; - Expectation e = EXPECT_CALL(a, DoA(1)) - .Times(AnyNumber()); - EXPECT_NONFATAL_FAILURE({ // NOLINT - EXPECT_CALL(a, DoA(2)) - .After(e) - .InSequence(s); - }, ".InSequence() cannot appear after "); + Expectation e = EXPECT_CALL(a, DoA(1)).Times(AnyNumber()); + EXPECT_NONFATAL_FAILURE( + { // NOLINT + EXPECT_CALL(a, DoA(2)).After(e).InSequence(s); + }, + ".InSequence() cannot appear after "); a.DoA(2); } @@ -437,11 +424,11 @@ TEST(ExpectCallSyntaxTest, InSequenceMustBeBeforeWillOnce) { MockA a; Sequence s; - EXPECT_NONFATAL_FAILURE({ // NOLINT - EXPECT_CALL(a, DoA(1)) - .WillOnce(Return()) - .InSequence(s); - }, ".InSequence() cannot appear after "); + EXPECT_NONFATAL_FAILURE( + { // NOLINT + EXPECT_CALL(a, DoA(1)).WillOnce(Return()).InSequence(s); + }, + ".InSequence() cannot appear after "); a.DoA(1); } @@ -450,11 +437,9 @@ TEST(ExpectCallSyntaxTest, AfterMustBeBeforeWillOnce) { MockA a; Expectation e = EXPECT_CALL(a, DoA(1)); - EXPECT_NONFATAL_FAILURE({ - EXPECT_CALL(a, DoA(2)) - .WillOnce(Return()) - .After(e); - }, ".After() cannot appear after "); + EXPECT_NONFATAL_FAILURE( + { EXPECT_CALL(a, DoA(2)).WillOnce(Return()).After(e); }, + ".After() cannot appear after "); a.DoA(1); a.DoA(2); @@ -464,8 +449,7 @@ TEST(ExpectCallSyntaxTest, WillIsOptional) { MockA a; EXPECT_CALL(a, DoA(1)); - EXPECT_CALL(a, DoA(2)) - .WillOnce(Return()); + EXPECT_CALL(a, DoA(2)).WillOnce(Return()); a.DoA(1); a.DoA(2); @@ -484,11 +468,11 @@ TEST(ExpectCallSyntaxTest, WillCanAppearMultipleTimes) { TEST(ExpectCallSyntaxTest, WillMustBeBeforeWillRepeatedly) { MockA a; - EXPECT_NONFATAL_FAILURE({ // NOLINT - EXPECT_CALL(a, DoA(1)) - .WillRepeatedly(Return()) - .WillOnce(Return()); - }, ".WillOnce() cannot appear after "); + EXPECT_NONFATAL_FAILURE( + { // NOLINT + EXPECT_CALL(a, DoA(1)).WillRepeatedly(Return()).WillOnce(Return()); + }, + ".WillOnce() cannot appear after "); a.DoA(1); } @@ -496,11 +480,8 @@ TEST(ExpectCallSyntaxTest, WillMustBeBeforeWillRepeatedly) { TEST(ExpectCallSyntaxTest, WillRepeatedlyIsOptional) { MockA a; - EXPECT_CALL(a, DoA(1)) - .WillOnce(Return()); - EXPECT_CALL(a, DoA(2)) - .WillOnce(Return()) - .WillRepeatedly(Return()); + EXPECT_CALL(a, DoA(1)).WillOnce(Return()); + EXPECT_CALL(a, DoA(2)).WillOnce(Return()).WillRepeatedly(Return()); a.DoA(1); a.DoA(2); @@ -510,30 +491,30 @@ TEST(ExpectCallSyntaxTest, WillRepeatedlyIsOptional) { TEST(ExpectCallSyntaxTest, WillRepeatedlyCannotAppearMultipleTimes) { MockA a; - EXPECT_NONFATAL_FAILURE({ // NOLINT - EXPECT_CALL(a, DoA(1)) - .WillRepeatedly(Return()) - .WillRepeatedly(Return()); - }, ".WillRepeatedly() cannot appear more than once in an " - "EXPECT_CALL()"); + EXPECT_NONFATAL_FAILURE( + { // NOLINT + EXPECT_CALL(a, DoA(1)).WillRepeatedly(Return()).WillRepeatedly( + Return()); + }, + ".WillRepeatedly() cannot appear more than once in an " + "EXPECT_CALL()"); } TEST(ExpectCallSyntaxTest, WillRepeatedlyMustBeBeforeRetiresOnSaturation) { MockA a; - EXPECT_NONFATAL_FAILURE({ // NOLINT - EXPECT_CALL(a, DoA(1)) - .RetiresOnSaturation() - .WillRepeatedly(Return()); - }, ".WillRepeatedly() cannot appear after "); + EXPECT_NONFATAL_FAILURE( + { // NOLINT + EXPECT_CALL(a, DoA(1)).RetiresOnSaturation().WillRepeatedly(Return()); + }, + ".WillRepeatedly() cannot appear after "); } TEST(ExpectCallSyntaxTest, RetiresOnSaturationIsOptional) { MockA a; EXPECT_CALL(a, DoA(1)); - EXPECT_CALL(a, DoA(1)) - .RetiresOnSaturation(); + EXPECT_CALL(a, DoA(1)).RetiresOnSaturation(); a.DoA(1); a.DoA(1); @@ -542,11 +523,11 @@ TEST(ExpectCallSyntaxTest, RetiresOnSaturationIsOptional) { TEST(ExpectCallSyntaxTest, RetiresOnSaturationCannotAppearMultipleTimes) { MockA a; - EXPECT_NONFATAL_FAILURE({ // NOLINT - EXPECT_CALL(a, DoA(1)) - .RetiresOnSaturation() - .RetiresOnSaturation(); - }, ".RetiresOnSaturation() cannot appear more than once"); + EXPECT_NONFATAL_FAILURE( + { // NOLINT + EXPECT_CALL(a, DoA(1)).RetiresOnSaturation().RetiresOnSaturation(); + }, + ".RetiresOnSaturation() cannot appear more than once"); a.DoA(1); } @@ -557,16 +538,20 @@ TEST(ExpectCallSyntaxTest, DefaultCardinalityIsOnce) { EXPECT_CALL(a, DoA(1)); a.DoA(1); } - EXPECT_NONFATAL_FAILURE({ // NOLINT - MockA a; - EXPECT_CALL(a, DoA(1)); - }, "to be called once"); - EXPECT_NONFATAL_FAILURE({ // NOLINT - MockA a; - EXPECT_CALL(a, DoA(1)); - a.DoA(1); - a.DoA(1); - }, "to be called once"); + EXPECT_NONFATAL_FAILURE( + { // NOLINT + MockA a; + EXPECT_CALL(a, DoA(1)); + }, + "to be called once"); + EXPECT_NONFATAL_FAILURE( + { // NOLINT + MockA a; + EXPECT_CALL(a, DoA(1)); + a.DoA(1); + a.DoA(1); + }, + "to be called once"); } #if GTEST_HAS_STREAM_REDIRECTION @@ -579,13 +564,9 @@ TEST(ExpectCallSyntaxTest, DoesNotWarnOnAdequateActionCount) { MockB b; // It's always fine to omit WillOnce() entirely. - EXPECT_CALL(b, DoB()) - .Times(0); - EXPECT_CALL(b, DoB(1)) - .Times(AtMost(1)); - EXPECT_CALL(b, DoB(2)) - .Times(1) - .WillRepeatedly(Return(1)); + EXPECT_CALL(b, DoB()).Times(0); + EXPECT_CALL(b, DoB(1)).Times(AtMost(1)); + EXPECT_CALL(b, DoB(2)).Times(1).WillRepeatedly(Return(1)); // It's fine for the number of WillOnce()s to equal the upper bound. EXPECT_CALL(b, DoB(3)) @@ -595,10 +576,8 @@ TEST(ExpectCallSyntaxTest, DoesNotWarnOnAdequateActionCount) { // It's fine for the number of WillOnce()s to be smaller than the // upper bound when there is a WillRepeatedly(). - EXPECT_CALL(b, DoB(4)) - .Times(AtMost(3)) - .WillOnce(Return(1)) - .WillRepeatedly(Return(2)); + EXPECT_CALL(b, DoB(4)).Times(AtMost(3)).WillOnce(Return(1)).WillRepeatedly( + Return(2)); // Satisfies the above expectations. b.DoB(2); @@ -615,13 +594,9 @@ TEST(ExpectCallSyntaxTest, WarnsOnTooManyActions) { MockB b; // Warns when the number of WillOnce()s is larger than the upper bound. - EXPECT_CALL(b, DoB()) - .Times(0) - .WillOnce(Return(1)); // #1 - EXPECT_CALL(b, DoB()) - .Times(AtMost(1)) - .WillOnce(Return(1)) - .WillOnce(Return(2)); // #2 + EXPECT_CALL(b, DoB()).Times(0).WillOnce(Return(1)); // #1 + EXPECT_CALL(b, DoB()).Times(AtMost(1)).WillOnce(Return(1)).WillOnce( + Return(2)); // #2 EXPECT_CALL(b, DoB(1)) .Times(1) .WillOnce(Return(1)) @@ -630,41 +605,34 @@ TEST(ExpectCallSyntaxTest, WarnsOnTooManyActions) { // Warns when the number of WillOnce()s equals the upper bound and // there is a WillRepeatedly(). - EXPECT_CALL(b, DoB()) - .Times(0) - .WillRepeatedly(Return(1)); // #4 - EXPECT_CALL(b, DoB(2)) - .Times(1) - .WillOnce(Return(1)) - .WillRepeatedly(Return(2)); // #5 + EXPECT_CALL(b, DoB()).Times(0).WillRepeatedly(Return(1)); // #4 + EXPECT_CALL(b, DoB(2)).Times(1).WillOnce(Return(1)).WillRepeatedly( + Return(2)); // #5 // Satisfies the above expectations. b.DoB(1); b.DoB(2); } const std::string output = GetCapturedStdout(); - EXPECT_PRED_FORMAT2( - IsSubstring, - "Too many actions specified in EXPECT_CALL(b, DoB())...\n" - "Expected to be never called, but has 1 WillOnce().", - output); // #1 - EXPECT_PRED_FORMAT2( - IsSubstring, - "Too many actions specified in EXPECT_CALL(b, DoB())...\n" - "Expected to be called at most once, " - "but has 2 WillOnce()s.", - output); // #2 + EXPECT_PRED_FORMAT2(IsSubstring, + "Too many actions specified in EXPECT_CALL(b, DoB())...\n" + "Expected to be never called, but has 1 WillOnce().", + output); // #1 + EXPECT_PRED_FORMAT2(IsSubstring, + "Too many actions specified in EXPECT_CALL(b, DoB())...\n" + "Expected to be called at most once, " + "but has 2 WillOnce()s.", + output); // #2 EXPECT_PRED_FORMAT2( IsSubstring, "Too many actions specified in EXPECT_CALL(b, DoB(1))...\n" "Expected to be called once, but has 2 WillOnce()s.", output); // #3 - EXPECT_PRED_FORMAT2( - IsSubstring, - "Too many actions specified in EXPECT_CALL(b, DoB())...\n" - "Expected to be never called, but has 0 WillOnce()s " - "and a WillRepeatedly().", - output); // #4 + EXPECT_PRED_FORMAT2(IsSubstring, + "Too many actions specified in EXPECT_CALL(b, DoB())...\n" + "Expected to be never called, but has 0 WillOnce()s " + "and a WillRepeatedly().", + output); // #4 EXPECT_PRED_FORMAT2( IsSubstring, "Too many actions specified in EXPECT_CALL(b, DoB(2))...\n" @@ -678,19 +646,16 @@ TEST(ExpectCallSyntaxTest, WarnsOnTooManyActions) { TEST(ExpectCallSyntaxTest, WarnsOnTooFewActions) { MockB b; - EXPECT_CALL(b, DoB()) - .Times(Between(2, 3)) - .WillOnce(Return(1)); + EXPECT_CALL(b, DoB()).Times(Between(2, 3)).WillOnce(Return(1)); CaptureStdout(); b.DoB(); const std::string output = GetCapturedStdout(); - EXPECT_PRED_FORMAT2( - IsSubstring, - "Too few actions specified in EXPECT_CALL(b, DoB())...\n" - "Expected to be called between 2 and 3 times, " - "but has only 1 WillOnce().", - output); + EXPECT_PRED_FORMAT2(IsSubstring, + "Too few actions specified in EXPECT_CALL(b, DoB())...\n" + "Expected to be called between 2 and 3 times, " + "but has only 1 WillOnce().", + output); b.DoB(); } @@ -718,10 +683,12 @@ TEST(ExpectCallSyntaxTest, WarningIsErrorWithFlag) { warning_output); GMOCK_FLAG_SET(default_mock_behavior, kFail); - EXPECT_NONFATAL_FAILURE({ - MockA a; - a.DoA(0); - }, "Uninteresting mock function call"); + EXPECT_NONFATAL_FAILURE( + { + MockA a; + a.DoA(0); + }, + "Uninteresting mock function call"); // Out of bounds values are converted to kWarn GMOCK_FLAG_SET(default_mock_behavior, -1); @@ -765,8 +732,7 @@ TEST(OnCallTest, TakesBuiltInDefaultActionWhenNoOnCall) { // matches the invocation. TEST(OnCallTest, TakesBuiltInDefaultActionWhenNoOnCallMatches) { MockB b; - ON_CALL(b, DoB(1)) - .WillByDefault(Return(1)); + ON_CALL(b, DoB(1)).WillByDefault(Return(1)); EXPECT_CALL(b, DoB(_)); EXPECT_EQ(0, b.DoB(2)); @@ -775,12 +741,9 @@ TEST(OnCallTest, TakesBuiltInDefaultActionWhenNoOnCallMatches) { // Tests that the last matching ON_CALL() action is taken. TEST(OnCallTest, PicksLastMatchingOnCall) { MockB b; - ON_CALL(b, DoB(_)) - .WillByDefault(Return(3)); - ON_CALL(b, DoB(2)) - .WillByDefault(Return(2)); - ON_CALL(b, DoB(1)) - .WillByDefault(Return(1)); + ON_CALL(b, DoB(_)).WillByDefault(Return(3)); + ON_CALL(b, DoB(2)).WillByDefault(Return(2)); + ON_CALL(b, DoB(1)).WillByDefault(Return(1)); EXPECT_CALL(b, DoB(_)); EXPECT_EQ(2, b.DoB(2)); @@ -804,25 +767,24 @@ TEST(ExpectCallTest, AllowsAnyCallWhenNoSpec) { // Tests that the last matching EXPECT_CALL() fires. TEST(ExpectCallTest, PicksLastMatchingExpectCall) { MockB b; - EXPECT_CALL(b, DoB(_)) - .WillRepeatedly(Return(2)); - EXPECT_CALL(b, DoB(1)) - .WillRepeatedly(Return(1)); + EXPECT_CALL(b, DoB(_)).WillRepeatedly(Return(2)); + EXPECT_CALL(b, DoB(1)).WillRepeatedly(Return(1)); EXPECT_EQ(1, b.DoB(1)); } // Tests lower-bound violation. TEST(ExpectCallTest, CatchesTooFewCalls) { - EXPECT_NONFATAL_FAILURE({ // NOLINT - MockB b; - EXPECT_CALL(b, DoB(5)) - .Times(AtLeast(2)); + EXPECT_NONFATAL_FAILURE( + { // NOLINT + MockB b; + EXPECT_CALL(b, DoB(5)).Times(AtLeast(2)); - b.DoB(5); - }, "Actual function call count doesn't match EXPECT_CALL(b, DoB(5))...\n" - " Expected: to be called at least twice\n" - " Actual: called once - unsatisfied and active"); + b.DoB(5); + }, + "Actual function call count doesn't match EXPECT_CALL(b, DoB(5))...\n" + " Expected: to be called at least twice\n" + " Actual: called once - unsatisfied and active"); } // Tests that the cardinality can be inferred when no Times(...) is @@ -830,28 +792,24 @@ TEST(ExpectCallTest, CatchesTooFewCalls) { TEST(ExpectCallTest, InfersCardinalityWhenThereIsNoWillRepeatedly) { { MockB b; - EXPECT_CALL(b, DoB()) - .WillOnce(Return(1)) - .WillOnce(Return(2)); + EXPECT_CALL(b, DoB()).WillOnce(Return(1)).WillOnce(Return(2)); EXPECT_EQ(1, b.DoB()); EXPECT_EQ(2, b.DoB()); } - EXPECT_NONFATAL_FAILURE({ // NOLINT - MockB b; - EXPECT_CALL(b, DoB()) - .WillOnce(Return(1)) - .WillOnce(Return(2)); + EXPECT_NONFATAL_FAILURE( + { // NOLINT + MockB b; + EXPECT_CALL(b, DoB()).WillOnce(Return(1)).WillOnce(Return(2)); - EXPECT_EQ(1, b.DoB()); - }, "to be called twice"); + EXPECT_EQ(1, b.DoB()); + }, + "to be called twice"); { // NOLINT MockB b; - EXPECT_CALL(b, DoB()) - .WillOnce(Return(1)) - .WillOnce(Return(2)); + EXPECT_CALL(b, DoB()).WillOnce(Return(1)).WillOnce(Return(2)); EXPECT_EQ(1, b.DoB()); EXPECT_EQ(2, b.DoB()); @@ -862,40 +820,34 @@ TEST(ExpectCallTest, InfersCardinalityWhenThereIsNoWillRepeatedly) { TEST(ExpectCallTest, InfersCardinality1WhenThereIsWillRepeatedly) { { MockB b; - EXPECT_CALL(b, DoB()) - .WillOnce(Return(1)) - .WillRepeatedly(Return(2)); + EXPECT_CALL(b, DoB()).WillOnce(Return(1)).WillRepeatedly(Return(2)); EXPECT_EQ(1, b.DoB()); } { // NOLINT MockB b; - EXPECT_CALL(b, DoB()) - .WillOnce(Return(1)) - .WillRepeatedly(Return(2)); + EXPECT_CALL(b, DoB()).WillOnce(Return(1)).WillRepeatedly(Return(2)); EXPECT_EQ(1, b.DoB()); EXPECT_EQ(2, b.DoB()); EXPECT_EQ(2, b.DoB()); } - EXPECT_NONFATAL_FAILURE({ // NOLINT - MockB b; - EXPECT_CALL(b, DoB()) - .WillOnce(Return(1)) - .WillRepeatedly(Return(2)); - }, "to be called at least once"); + EXPECT_NONFATAL_FAILURE( + { // NOLINT + MockB b; + EXPECT_CALL(b, DoB()).WillOnce(Return(1)).WillRepeatedly(Return(2)); + }, + "to be called at least once"); } // Tests that the n-th action is taken for the n-th matching // invocation. TEST(ExpectCallTest, NthMatchTakesNthAction) { MockB b; - EXPECT_CALL(b, DoB()) - .WillOnce(Return(1)) - .WillOnce(Return(2)) - .WillOnce(Return(3)); + EXPECT_CALL(b, DoB()).WillOnce(Return(1)).WillOnce(Return(2)).WillOnce( + Return(3)); EXPECT_EQ(1, b.DoB()); EXPECT_EQ(2, b.DoB()); @@ -906,9 +858,7 @@ TEST(ExpectCallTest, NthMatchTakesNthAction) { // list is exhausted. TEST(ExpectCallTest, TakesRepeatedActionWhenWillListIsExhausted) { MockB b; - EXPECT_CALL(b, DoB()) - .WillOnce(Return(1)) - .WillRepeatedly(Return(2)); + EXPECT_CALL(b, DoB()).WillOnce(Return(1)).WillRepeatedly(Return(2)); EXPECT_EQ(1, b.DoB()); EXPECT_EQ(2, b.DoB()); @@ -921,8 +871,7 @@ TEST(ExpectCallTest, TakesRepeatedActionWhenWillListIsExhausted) { // exhausted and there is no WillRepeatedly(). TEST(ExpectCallTest, TakesDefaultActionWhenWillListIsExhausted) { MockB b; - EXPECT_CALL(b, DoB(_)) - .Times(1); + EXPECT_CALL(b, DoB(_)).Times(1); EXPECT_CALL(b, DoB()) .Times(AnyNumber()) .WillOnce(Return(1)) @@ -984,8 +933,7 @@ TEST(UninterestingCallTest, DoesDefaultAction) { // When there is an ON_CALL() statement, the action specified by it // should be taken. MockA a; - ON_CALL(a, Binary(_, _)) - .WillByDefault(Return(true)); + ON_CALL(a, Binary(_, _)).WillByDefault(Return(true)); EXPECT_TRUE(a.Binary(1, 2)); // When there is no ON_CALL(), the default value for the return type @@ -999,8 +947,7 @@ TEST(UnexpectedCallTest, DoesDefaultAction) { // When there is an ON_CALL() statement, the action specified by it // should be taken. MockA a; - ON_CALL(a, Binary(_, _)) - .WillByDefault(Return(true)); + ON_CALL(a, Binary(_, _)).WillByDefault(Return(true)); EXPECT_CALL(a, Binary(0, 0)); a.Binary(0, 0); bool result = false; @@ -1011,11 +958,9 @@ TEST(UnexpectedCallTest, DoesDefaultAction) { // When there is no ON_CALL(), the default value for the return type // should be returned. MockB b; - EXPECT_CALL(b, DoB(0)) - .Times(0); + EXPECT_CALL(b, DoB(0)).Times(0); int n = -1; - EXPECT_NONFATAL_FAILURE(n = b.DoB(1), - "Unexpected mock function call"); + EXPECT_NONFATAL_FAILURE(n = b.DoB(1), "Unexpected mock function call"); EXPECT_EQ(0, n); } @@ -1092,14 +1037,12 @@ TEST(UnexpectedCallTest, GeneartesFailureForNonVoidFunction) { // match the call. TEST(UnexpectedCallTest, RetiredExpectation) { MockB b; - EXPECT_CALL(b, DoB(1)) - .RetiresOnSaturation(); + EXPECT_CALL(b, DoB(1)).RetiresOnSaturation(); b.DoB(1); - EXPECT_NONFATAL_FAILURE( - b.DoB(1), - " Expected: the expectation is active\n" - " Actual: it is retired"); + EXPECT_NONFATAL_FAILURE(b.DoB(1), + " Expected: the expectation is active\n" + " Actual: it is retired"); } // Tests that Google Mock explains that an expectation that doesn't @@ -1108,10 +1051,9 @@ TEST(UnexpectedCallTest, UnmatchedArguments) { MockB b; EXPECT_CALL(b, DoB(1)); - EXPECT_NONFATAL_FAILURE( - b.DoB(2), - " Expected arg #0: is equal to 1\n" - " Actual: 2\n"); + EXPECT_NONFATAL_FAILURE(b.DoB(2), + " Expected arg #0: is equal to 1\n" + " Actual: 2\n"); b.DoB(1); } @@ -1120,15 +1062,10 @@ TEST(UnexpectedCallTest, UnmatchedArguments) { TEST(UnexpectedCallTest, UnsatisifiedPrerequisites) { Sequence s1, s2; MockB b; - EXPECT_CALL(b, DoB(1)) - .InSequence(s1); - EXPECT_CALL(b, DoB(2)) - .Times(AnyNumber()) - .InSequence(s1); - EXPECT_CALL(b, DoB(3)) - .InSequence(s2); - EXPECT_CALL(b, DoB(4)) - .InSequence(s1, s2); + EXPECT_CALL(b, DoB(1)).InSequence(s1); + EXPECT_CALL(b, DoB(2)).Times(AnyNumber()).InSequence(s1); + EXPECT_CALL(b, DoB(3)).InSequence(s2); + EXPECT_CALL(b, DoB(4)).InSequence(s1, s2); ::testing::TestPartResultArray failures; { @@ -1146,23 +1083,27 @@ TEST(UnexpectedCallTest, UnsatisifiedPrerequisites) { // Verifies that the failure message contains the two unsatisfied // pre-requisites but not the satisfied one. #if GTEST_USES_PCRE - EXPECT_THAT(r.message(), ContainsRegex( - // PCRE has trouble using (.|\n) to match any character, but - // supports the (?s) prefix for using . to match any character. - "(?s)the following immediate pre-requisites are not satisfied:\n" - ".*: pre-requisite #0\n" - ".*: pre-requisite #1")); + EXPECT_THAT( + r.message(), + ContainsRegex( + // PCRE has trouble using (.|\n) to match any character, but + // supports the (?s) prefix for using . to match any character. + "(?s)the following immediate pre-requisites are not satisfied:\n" + ".*: pre-requisite #0\n" + ".*: pre-requisite #1")); #elif GTEST_USES_POSIX_RE - EXPECT_THAT(r.message(), ContainsRegex( - // POSIX RE doesn't understand the (?s) prefix, but has no trouble - // with (.|\n). - "the following immediate pre-requisites are not satisfied:\n" - "(.|\n)*: pre-requisite #0\n" - "(.|\n)*: pre-requisite #1")); + EXPECT_THAT(r.message(), + ContainsRegex( + // POSIX RE doesn't understand the (?s) prefix, but has no + // trouble with (.|\n). + "the following immediate pre-requisites are not satisfied:\n" + "(.|\n)*: pre-requisite #0\n" + "(.|\n)*: pre-requisite #1")); #else // We can only use Google Test's own simple regex. - EXPECT_THAT(r.message(), ContainsRegex( - "the following immediate pre-requisites are not satisfied:")); + EXPECT_THAT(r.message(), + ContainsRegex( + "the following immediate pre-requisites are not satisfied:")); EXPECT_THAT(r.message(), ContainsRegex(": pre-requisite #0")); EXPECT_THAT(r.message(), ContainsRegex(": pre-requisite #1")); #endif // GTEST_USES_PCRE @@ -1191,8 +1132,7 @@ TEST(ExcessiveCallTest, DoesDefaultAction) { // When there is an ON_CALL() statement, the action specified by it // should be taken. MockA a; - ON_CALL(a, Binary(_, _)) - .WillByDefault(Return(true)); + ON_CALL(a, Binary(_, _)).WillByDefault(Return(true)); EXPECT_CALL(a, Binary(0, 0)); a.Binary(0, 0); bool result = false; @@ -1203,8 +1143,7 @@ TEST(ExcessiveCallTest, DoesDefaultAction) { // When there is no ON_CALL(), the default value for the return type // should be returned. MockB b; - EXPECT_CALL(b, DoB(0)) - .Times(0); + EXPECT_CALL(b, DoB(0)).Times(0); int n = -1; EXPECT_NONFATAL_FAILURE(n = b.DoB(0), "Mock function called more times than expected"); @@ -1215,8 +1154,7 @@ TEST(ExcessiveCallTest, DoesDefaultAction) { // the failure message contains the argument values. TEST(ExcessiveCallTest, GeneratesFailureForVoidFunction) { MockA a; - EXPECT_CALL(a, DoA(_)) - .Times(0); + EXPECT_CALL(a, DoA(_)).Times(0); EXPECT_NONFATAL_FAILURE( a.DoA(9), "Mock function called more times than expected - returning directly.\n" @@ -1252,9 +1190,11 @@ TEST(InSequenceTest, AllExpectationInScopeAreInSequence) { EXPECT_CALL(a, DoA(2)); } - EXPECT_NONFATAL_FAILURE({ // NOLINT - a.DoA(2); - }, "Unexpected mock function call"); + EXPECT_NONFATAL_FAILURE( + { // NOLINT + a.DoA(2); + }, + "Unexpected mock function call"); a.DoA(1); a.DoA(2); @@ -1274,10 +1214,12 @@ TEST(InSequenceTest, NestedInSequence) { } } - EXPECT_NONFATAL_FAILURE({ // NOLINT - a.DoA(1); - a.DoA(3); - }, "Unexpected mock function call"); + EXPECT_NONFATAL_FAILURE( + { // NOLINT + a.DoA(1); + a.DoA(3); + }, + "Unexpected mock function call"); a.DoA(2); a.DoA(3); @@ -1293,9 +1235,11 @@ TEST(InSequenceTest, ExpectationsOutOfScopeAreNotAffected) { } EXPECT_CALL(a, DoA(3)); - EXPECT_NONFATAL_FAILURE({ // NOLINT - a.DoA(2); - }, "Unexpected mock function call"); + EXPECT_NONFATAL_FAILURE( + { // NOLINT + a.DoA(2); + }, + "Unexpected mock function call"); a.DoA(3); a.DoA(1); @@ -1309,8 +1253,7 @@ TEST(SequenceTest, AnyOrderIsOkByDefault) { MockB b; EXPECT_CALL(a, DoA(1)); - EXPECT_CALL(b, DoB()) - .Times(AnyNumber()); + EXPECT_CALL(b, DoB()).Times(AnyNumber()); a.DoA(1); b.DoB(); @@ -1321,8 +1264,7 @@ TEST(SequenceTest, AnyOrderIsOkByDefault) { MockB b; EXPECT_CALL(a, DoA(1)); - EXPECT_CALL(b, DoB()) - .Times(AnyNumber()); + EXPECT_CALL(b, DoB()).Times(AnyNumber()); b.DoB(); a.DoA(1); @@ -1333,16 +1275,12 @@ TEST(SequenceTest, AnyOrderIsOkByDefault) { // is specified. TEST(SequenceTest, CallsMustBeInStrictOrderWhenSaidSo1) { MockA a; - ON_CALL(a, ReturnResult(_)) - .WillByDefault(Return(Result())); + ON_CALL(a, ReturnResult(_)).WillByDefault(Return(Result())); Sequence s; - EXPECT_CALL(a, ReturnResult(1)) - .InSequence(s); - EXPECT_CALL(a, ReturnResult(2)) - .InSequence(s); - EXPECT_CALL(a, ReturnResult(3)) - .InSequence(s); + EXPECT_CALL(a, ReturnResult(1)).InSequence(s); + EXPECT_CALL(a, ReturnResult(2)).InSequence(s); + EXPECT_CALL(a, ReturnResult(3)).InSequence(s); a.ReturnResult(1); @@ -1357,14 +1295,11 @@ TEST(SequenceTest, CallsMustBeInStrictOrderWhenSaidSo1) { // is specified. TEST(SequenceTest, CallsMustBeInStrictOrderWhenSaidSo2) { MockA a; - ON_CALL(a, ReturnResult(_)) - .WillByDefault(Return(Result())); + ON_CALL(a, ReturnResult(_)).WillByDefault(Return(Result())); Sequence s; - EXPECT_CALL(a, ReturnResult(1)) - .InSequence(s); - EXPECT_CALL(a, ReturnResult(2)) - .InSequence(s); + EXPECT_CALL(a, ReturnResult(1)).InSequence(s); + EXPECT_CALL(a, ReturnResult(2)).InSequence(s); // May only be called after a.ReturnResult(1). EXPECT_NONFATAL_FAILURE(a.ReturnResult(2), "Unexpected mock function call"); @@ -1377,8 +1312,7 @@ TEST(SequenceTest, CallsMustBeInStrictOrderWhenSaidSo2) { class PartialOrderTest : public testing::Test { protected: PartialOrderTest() { - ON_CALL(a_, ReturnResult(_)) - .WillByDefault(Return(Result())); + ON_CALL(a_, ReturnResult(_)).WillByDefault(Return(Result())); // Specifies this partial ordering: // @@ -1386,16 +1320,10 @@ class PartialOrderTest : public testing::Test { // a.ReturnResult(2) * n ==> a.ReturnResult(3) // b.DoB() * 2 ==> Sequence x, y; - EXPECT_CALL(a_, ReturnResult(1)) - .InSequence(x); - EXPECT_CALL(b_, DoB()) - .Times(2) - .InSequence(y); - EXPECT_CALL(a_, ReturnResult(2)) - .Times(AnyNumber()) - .InSequence(x, y); - EXPECT_CALL(a_, ReturnResult(3)) - .InSequence(x); + EXPECT_CALL(a_, ReturnResult(1)).InSequence(x); + EXPECT_CALL(b_, DoB()).Times(2).InSequence(y); + EXPECT_CALL(a_, ReturnResult(2)).Times(AnyNumber()).InSequence(x, y); + EXPECT_CALL(a_, ReturnResult(3)).InSequence(x); } MockA a_; @@ -1447,13 +1375,9 @@ TEST(SequenceTest, Retirement) { MockA a; Sequence s; - EXPECT_CALL(a, DoA(1)) - .InSequence(s); - EXPECT_CALL(a, DoA(_)) - .InSequence(s) - .RetiresOnSaturation(); - EXPECT_CALL(a, DoA(1)) - .InSequence(s); + EXPECT_CALL(a, DoA(1)).InSequence(s); + EXPECT_CALL(a, DoA(_)).InSequence(s).RetiresOnSaturation(); + EXPECT_CALL(a, DoA(1)).InSequence(s); a.DoA(1); a.DoA(2); @@ -1518,12 +1442,12 @@ TEST(ExpectationSetTest, ConstructorsWork) { Expectation e1; const Expectation e2; - ExpectationSet es1; // Default ctor. + ExpectationSet es1; // Default ctor. ExpectationSet es2 = EXPECT_CALL(a, DoA(1)); // Ctor from EXPECT_CALL. - ExpectationSet es3 = e1; // Ctor from Expectation. - ExpectationSet es4(e1); // Ctor from Expectation; alternative syntax. - ExpectationSet es5 = e2; // Ctor from const Expectation. - ExpectationSet es6(e2); // Ctor from const Expectation; alternative syntax. + ExpectationSet es3 = e1; // Ctor from Expectation. + ExpectationSet es4(e1); // Ctor from Expectation; alternative syntax. + ExpectationSet es5 = e2; // Ctor from const Expectation. + ExpectationSet es6(e2); // Ctor from const Expectation; alternative syntax. ExpectationSet es7 = es2; // Copy ctor. EXPECT_EQ(0, es1.size()); @@ -1595,7 +1519,7 @@ TEST(ExpectationSetTest, IsEnumerable) { EXPECT_TRUE(it != es.end()); EXPECT_THAT(*it, Eq(Expectation())); ++it; - EXPECT_TRUE(it== es.end()); + EXPECT_TRUE(it == es.end()); } // Tests the .After() clause. @@ -1605,8 +1529,7 @@ TEST(AfterTest, SucceedsWhenPartialOrderIsSatisfied) { ExpectationSet es; es += EXPECT_CALL(a, DoA(1)); es += EXPECT_CALL(a, DoA(2)); - EXPECT_CALL(a, DoA(3)) - .After(es); + EXPECT_CALL(a, DoA(3)).After(es); a.DoA(1); a.DoA(2); @@ -1619,9 +1542,7 @@ TEST(AfterTest, SucceedsWhenTotalOrderIsSatisfied) { // The following also verifies that const Expectation objects work // too. Do not remove the const modifiers. const Expectation e1 = EXPECT_CALL(a, DoA(1)); - const Expectation e2 = EXPECT_CALL(b, DoB()) - .Times(2) - .After(e1); + const Expectation e2 = EXPECT_CALL(b, DoB()).Times(2).After(e1); EXPECT_CALL(a, DoA(2)).After(e2); a.DoA(1); @@ -1638,10 +1559,8 @@ TEST(AfterTest, CallsMustBeInStrictOrderWhenSpecifiedSo1) { // Define ordering: // a.DoA(1) ==> b.DoB() ==> a.DoA(2) Expectation e1 = EXPECT_CALL(a, DoA(1)); - Expectation e2 = EXPECT_CALL(b, DoB()) - .After(e1); - EXPECT_CALL(a, DoA(2)) - .After(e2); + Expectation e2 = EXPECT_CALL(b, DoB()).After(e1); + EXPECT_CALL(a, DoA(2)).After(e2); a.DoA(1); @@ -1660,11 +1579,8 @@ TEST(AfterTest, CallsMustBeInStrictOrderWhenSpecifiedSo2) { // Define ordering: // a.DoA(1) ==> b.DoB() * 2 ==> a.DoA(2) Expectation e1 = EXPECT_CALL(a, DoA(1)); - Expectation e2 = EXPECT_CALL(b, DoB()) - .Times(2) - .After(e1); - EXPECT_CALL(a, DoA(2)) - .After(e2); + Expectation e2 = EXPECT_CALL(b, DoB()).Times(2).After(e1); + EXPECT_CALL(a, DoA(2)).After(e2); a.DoA(1); b.DoB(); @@ -1679,16 +1595,14 @@ TEST(AfterTest, CallsMustBeInStrictOrderWhenSpecifiedSo2) { // Calls must satisfy the partial order when specified so. TEST(AfterTest, CallsMustSatisfyPartialOrderWhenSpecifiedSo) { MockA a; - ON_CALL(a, ReturnResult(_)) - .WillByDefault(Return(Result())); + ON_CALL(a, ReturnResult(_)).WillByDefault(Return(Result())); // Define ordering: // a.DoA(1) ==> // a.DoA(2) ==> a.ReturnResult(3) Expectation e = EXPECT_CALL(a, DoA(1)); const ExpectationSet es = EXPECT_CALL(a, DoA(2)); - EXPECT_CALL(a, ReturnResult(3)) - .After(e, es); + EXPECT_CALL(a, ReturnResult(3)).After(e, es); // May only be called last. EXPECT_NONFATAL_FAILURE(a.ReturnResult(3), "Unexpected mock function call"); @@ -1707,8 +1621,7 @@ TEST(AfterTest, CallsMustSatisfyPartialOrderWhenSpecifiedSo2) { // a.DoA(2) ==> a.DoA(3) Expectation e = EXPECT_CALL(a, DoA(1)); const ExpectationSet es = EXPECT_CALL(a, DoA(2)); - EXPECT_CALL(a, DoA(3)) - .After(e, es); + EXPECT_CALL(a, DoA(3)).After(e, es); a.DoA(2); @@ -1725,9 +1638,7 @@ TEST(AfterTest, CanBeUsedWithInSequence) { Sequence s; Expectation e = EXPECT_CALL(a, DoA(1)); EXPECT_CALL(a, DoA(2)).InSequence(s); - EXPECT_CALL(a, DoA(3)) - .InSequence(s) - .After(e); + EXPECT_CALL(a, DoA(3)).InSequence(s).After(e); a.DoA(1); @@ -1744,10 +1655,7 @@ TEST(AfterTest, CanBeCalledManyTimes) { Expectation e1 = EXPECT_CALL(a, DoA(1)); Expectation e2 = EXPECT_CALL(a, DoA(2)); Expectation e3 = EXPECT_CALL(a, DoA(3)); - EXPECT_CALL(a, DoA(4)) - .After(e1) - .After(e2) - .After(e3); + EXPECT_CALL(a, DoA(4)).After(e1).After(e2).After(e3); a.DoA(3); a.DoA(1); @@ -1763,8 +1671,7 @@ TEST(AfterTest, AcceptsUpToFiveArguments) { Expectation e3 = EXPECT_CALL(a, DoA(3)); ExpectationSet es1 = EXPECT_CALL(a, DoA(4)); ExpectationSet es2 = EXPECT_CALL(a, DoA(5)); - EXPECT_CALL(a, DoA(6)) - .After(e1, e2, e3, es1, es2); + EXPECT_CALL(a, DoA(6)).After(e1, e2, e3, es1, es2); a.DoA(5); a.DoA(2); @@ -1777,8 +1684,7 @@ TEST(AfterTest, AcceptsUpToFiveArguments) { // .After() allows input to contain duplicated Expectations. TEST(AfterTest, AcceptsDuplicatedInput) { MockA a; - ON_CALL(a, ReturnResult(_)) - .WillByDefault(Return(Result())); + ON_CALL(a, ReturnResult(_)).WillByDefault(Return(Result())); // Define ordering: // DoA(1) ==> @@ -1788,8 +1694,7 @@ TEST(AfterTest, AcceptsDuplicatedInput) { ExpectationSet es; es += e1; es += e2; - EXPECT_CALL(a, ReturnResult(3)) - .After(e1, e2, es, e1); + EXPECT_CALL(a, ReturnResult(3)).After(e1, e2, es, e1); a.DoA(1); @@ -1806,8 +1711,7 @@ TEST(AfterTest, ChangesToExpectationSetHaveNoEffectAfterwards) { MockA a; ExpectationSet es1 = EXPECT_CALL(a, DoA(1)); Expectation e2 = EXPECT_CALL(a, DoA(2)); - EXPECT_CALL(a, DoA(3)) - .After(es1); + EXPECT_CALL(a, DoA(3)).After(es1); es1 += e2; a.DoA(1); @@ -1826,14 +1730,11 @@ TEST(DeletingMockEarlyTest, Success1) { { InSequence dummy; - EXPECT_CALL(*b1, DoB(_)) - .WillOnce(Return(1)); + EXPECT_CALL(*b1, DoB(_)).WillOnce(Return(1)); EXPECT_CALL(*a, Binary(_, _)) .Times(AnyNumber()) .WillRepeatedly(Return(true)); - EXPECT_CALL(*b2, DoB(_)) - .Times(AnyNumber()) - .WillRepeatedly(Return(2)); + EXPECT_CALL(*b2, DoB(_)).Times(AnyNumber()).WillRepeatedly(Return(2)); } EXPECT_EQ(1, b1->DoB(1)); @@ -1854,13 +1755,9 @@ TEST(DeletingMockEarlyTest, Success2) { { InSequence dummy; - EXPECT_CALL(*b1, DoB(_)) - .WillOnce(Return(1)); - EXPECT_CALL(*a, Binary(_, _)) - .Times(AnyNumber()); - EXPECT_CALL(*b2, DoB(_)) - .Times(AnyNumber()) - .WillRepeatedly(Return(2)); + EXPECT_CALL(*b1, DoB(_)).WillOnce(Return(1)); + EXPECT_CALL(*a, Binary(_, _)).Times(AnyNumber()); + EXPECT_CALL(*b2, DoB(_)).Times(AnyNumber()).WillRepeatedly(Return(2)); } delete a; // a is trivially satisfied. @@ -1875,14 +1772,14 @@ TEST(DeletingMockEarlyTest, Success2) { // Suppresses warning on unreferenced formal parameter in MSVC with // -W4. #ifdef _MSC_VER -# pragma warning(push) -# pragma warning(disable:4100) +#pragma warning(push) +#pragma warning(disable : 4100) #endif ACTION_P(Delete, ptr) { delete ptr; } #ifdef _MSC_VER -# pragma warning(pop) +#pragma warning(pop) #endif TEST(DeletingMockEarlyTest, CanDeleteSelfInActionReturningVoid) { @@ -1893,8 +1790,7 @@ TEST(DeletingMockEarlyTest, CanDeleteSelfInActionReturningVoid) { TEST(DeletingMockEarlyTest, CanDeleteSelfInActionReturningValue) { MockA* const a = new MockA; - EXPECT_CALL(*a, ReturnResult(_)) - .WillOnce(DoAll(Delete(a), Return(Result()))); + EXPECT_CALL(*a, ReturnResult(_)).WillOnce(DoAll(Delete(a), Return(Result()))); a->ReturnResult(42); // This will cause a to be deleted. } @@ -1906,19 +1802,13 @@ TEST(DeletingMockEarlyTest, Failure1) { { InSequence dummy; - EXPECT_CALL(*b1, DoB(_)) - .WillOnce(Return(1)); - EXPECT_CALL(*a, Binary(_, _)) - .Times(AnyNumber()); - EXPECT_CALL(*b2, DoB(_)) - .Times(AnyNumber()) - .WillRepeatedly(Return(2)); + EXPECT_CALL(*b1, DoB(_)).WillOnce(Return(1)); + EXPECT_CALL(*a, Binary(_, _)).Times(AnyNumber()); + EXPECT_CALL(*b2, DoB(_)).Times(AnyNumber()).WillRepeatedly(Return(2)); } delete a; // a is trivially satisfied. - EXPECT_NONFATAL_FAILURE({ - b2->DoB(2); - }, "Unexpected mock function call"); + EXPECT_NONFATAL_FAILURE({ b2->DoB(2); }, "Unexpected mock function call"); EXPECT_EQ(1, b1->DoB(1)); delete b1; delete b2; @@ -1933,18 +1823,13 @@ TEST(DeletingMockEarlyTest, Failure2) { { InSequence dummy; EXPECT_CALL(*b1, DoB(_)); - EXPECT_CALL(*a, Binary(_, _)) - .Times(AnyNumber()); - EXPECT_CALL(*b2, DoB(_)) - .Times(AnyNumber()); + EXPECT_CALL(*a, Binary(_, _)).Times(AnyNumber()); + EXPECT_CALL(*b2, DoB(_)).Times(AnyNumber()); } - EXPECT_NONFATAL_FAILURE(delete b1, - "Actual: never called"); - EXPECT_NONFATAL_FAILURE(a->Binary(0, 1), - "Unexpected mock function call"); - EXPECT_NONFATAL_FAILURE(b2->DoB(1), - "Unexpected mock function call"); + EXPECT_NONFATAL_FAILURE(delete b1, "Actual: never called"); + EXPECT_NONFATAL_FAILURE(a->Binary(0, 1), "Unexpected mock function call"); + EXPECT_NONFATAL_FAILURE(b2->DoB(1), "Unexpected mock function call"); delete a; delete b2; } @@ -1969,23 +1854,16 @@ class EvenNumberCardinality : public CardinalityInterface { } }; -Cardinality EvenNumber() { - return Cardinality(new EvenNumberCardinality); -} +Cardinality EvenNumber() { return Cardinality(new EvenNumberCardinality); } TEST(ExpectationBaseTest, AllPrerequisitesAreSatisfiedWorksForNonMonotonicCardinality) { MockA* a = new MockA; Sequence s; - EXPECT_CALL(*a, DoA(1)) - .Times(EvenNumber()) - .InSequence(s); - EXPECT_CALL(*a, DoA(2)) - .Times(AnyNumber()) - .InSequence(s); - EXPECT_CALL(*a, DoA(3)) - .Times(AnyNumber()); + EXPECT_CALL(*a, DoA(1)).Times(EvenNumber()).InSequence(s); + EXPECT_CALL(*a, DoA(2)).Times(AnyNumber()).InSequence(s); + EXPECT_CALL(*a, DoA(3)).Times(AnyNumber()); a->DoA(3); a->DoA(1); @@ -1996,8 +1874,7 @@ TEST(ExpectationBaseTest, // The following tests verify the message generated when a mock // function is called. -struct Printable { -}; +struct Printable {}; inline void operator<<(::std::ostream& os, const Printable&) { os << "Printable"; @@ -2064,7 +1941,7 @@ TEST(FunctionCallMessageTest, EXPECT_PRED_FORMAT2(IsSubstring, "GMOCK WARNING", output); EXPECT_PRED_FORMAT2(IsSubstring, "Stack trace:", output); -# ifndef NDEBUG +#ifndef NDEBUG // We check the stack trace content in dbg-mode only, as opt-mode // may inline the call we are interested in seeing. @@ -2080,7 +1957,7 @@ TEST(FunctionCallMessageTest, const std::string output2 = GetCapturedStdout(); EXPECT_PRED_FORMAT2(IsSubstring, "NonVoidMethod(", output2); -# endif // NDEBUG +#endif // NDEBUG } // Tests that an uninteresting mock function call on a naggy mock @@ -2096,7 +1973,8 @@ TEST(FunctionCallMessageTest, IsSubstring, "Uninteresting mock function call - returning default value.\n" " Function call: DoB()\n" - " Returns: 0\n", output1.c_str()); + " Returns: 0\n", + output1.c_str()); // Makes sure the return value is printed. // A void mock function. @@ -2104,12 +1982,12 @@ TEST(FunctionCallMessageTest, CaptureStdout(); c.VoidMethod(false, 5, "Hi", nullptr, Printable(), Unprintable()); const std::string output2 = GetCapturedStdout(); - EXPECT_THAT(output2.c_str(), - ContainsRegex( - "Uninteresting mock function call - returning directly\\.\n" - " Function call: VoidMethod" - "\\(false, 5, \"Hi\", NULL, @.+ " - "Printable, 4-byte object <00-00 00-00>\\)")); + EXPECT_THAT( + output2.c_str(), + ContainsRegex("Uninteresting mock function call - returning directly\\.\n" + " Function call: VoidMethod" + "\\(false, 5, \"Hi\", NULL, @.+ " + "Printable, 4-byte object <00-00 00-00>\\)")); // A void function has no return value to print. } @@ -2126,14 +2004,14 @@ class GMockVerboseFlagTest : public VerboseFlagPreservingFixture { const std::string& function_name) { if (should_print) { EXPECT_THAT(output.c_str(), HasSubstr(expected_substring)); -# ifndef NDEBUG +#ifndef NDEBUG // We check the stack trace content in dbg-mode only, as opt-mode // may inline the call we are interested in seeing. EXPECT_THAT(output.c_str(), HasSubstr(function_name)); -# else +#else // Suppresses 'unused function parameter' warnings. static_cast<void>(function_name); -# endif // NDEBUG +#endif // NDEBUG } else { EXPECT_STREQ("", output.c_str()); } @@ -2143,31 +2021,26 @@ class GMockVerboseFlagTest : public VerboseFlagPreservingFixture { void TestExpectedCall(bool should_print) { MockA a; EXPECT_CALL(a, DoA(5)); - EXPECT_CALL(a, Binary(_, 1)) - .WillOnce(Return(true)); + EXPECT_CALL(a, Binary(_, 1)).WillOnce(Return(true)); // A void-returning function. CaptureStdout(); a.DoA(5); - VerifyOutput( - GetCapturedStdout(), - should_print, - "Mock function call matches EXPECT_CALL(a, DoA(5))...\n" - " Function call: DoA(5)\n" - "Stack trace:\n", - "DoA"); + VerifyOutput(GetCapturedStdout(), should_print, + "Mock function call matches EXPECT_CALL(a, DoA(5))...\n" + " Function call: DoA(5)\n" + "Stack trace:\n", + "DoA"); // A non-void-returning function. CaptureStdout(); a.Binary(2, 1); - VerifyOutput( - GetCapturedStdout(), - should_print, - "Mock function call matches EXPECT_CALL(a, Binary(_, 1))...\n" - " Function call: Binary(2, 1)\n" - " Returns: true\n" - "Stack trace:\n", - "Binary"); + VerifyOutput(GetCapturedStdout(), should_print, + "Mock function call matches EXPECT_CALL(a, Binary(_, 1))...\n" + " Function call: Binary(2, 1)\n" + " Returns: true\n" + "Stack trace:\n", + "Binary"); } // Tests how the flag affects uninteresting calls on a naggy mock. @@ -2185,27 +2058,23 @@ class GMockVerboseFlagTest : public VerboseFlagPreservingFixture { // A void-returning function. CaptureStdout(); a.DoA(5); - VerifyOutput( - GetCapturedStdout(), - should_print, - "\nGMOCK WARNING:\n" - "Uninteresting mock function call - returning directly.\n" - " Function call: DoA(5)\n" + - note, - "DoA"); + VerifyOutput(GetCapturedStdout(), should_print, + "\nGMOCK WARNING:\n" + "Uninteresting mock function call - returning directly.\n" + " Function call: DoA(5)\n" + + note, + "DoA"); // A non-void-returning function. CaptureStdout(); a.Binary(2, 1); - VerifyOutput( - GetCapturedStdout(), - should_print, - "\nGMOCK WARNING:\n" - "Uninteresting mock function call - returning default value.\n" - " Function call: Binary(2, 1)\n" - " Returns: false\n" + - note, - "Binary"); + VerifyOutput(GetCapturedStdout(), should_print, + "\nGMOCK WARNING:\n" + "Uninteresting mock function call - returning default value.\n" + " Function call: Binary(2, 1)\n" + " Returns: false\n" + + note, + "Binary"); } }; @@ -2270,22 +2139,19 @@ class GMockLogTest : public VerboseFlagPreservingFixture { TEST_F(GMockLogTest, DoesNotPrintGoodCallInternallyIfVerbosityIsWarning) { GMOCK_FLAG_SET(verbose, kWarningVerbosity); - EXPECT_CALL(helper_, Foo(_)) - .WillOnce(Return(PrintMeNot())); + EXPECT_CALL(helper_, Foo(_)).WillOnce(Return(PrintMeNot())); helper_.Foo(PrintMeNot()); // This is an expected call. } TEST_F(GMockLogTest, DoesNotPrintGoodCallInternallyIfVerbosityIsError) { GMOCK_FLAG_SET(verbose, kErrorVerbosity); - EXPECT_CALL(helper_, Foo(_)) - .WillOnce(Return(PrintMeNot())); + EXPECT_CALL(helper_, Foo(_)).WillOnce(Return(PrintMeNot())); helper_.Foo(PrintMeNot()); // This is an expected call. } TEST_F(GMockLogTest, DoesNotPrintWarningInternallyIfVerbosityIsError) { GMOCK_FLAG_SET(verbose, kErrorVerbosity); - ON_CALL(helper_, Foo(_)) - .WillByDefault(Return(PrintMeNot())); + ON_CALL(helper_, Foo(_)).WillByDefault(Return(PrintMeNot())); helper_.Foo(PrintMeNot()); // This should generate a warning. } @@ -2346,8 +2212,7 @@ TEST(VerifyAndClearExpectationsTest, NoMethodHasExpectations) { // verification succeeds. TEST(VerifyAndClearExpectationsTest, SomeMethodsHaveExpectationsAndSucceed) { MockB b; - EXPECT_CALL(b, DoB()) - .WillOnce(Return(1)); + EXPECT_CALL(b, DoB()).WillOnce(Return(1)); b.DoB(); ASSERT_TRUE(Mock::VerifyAndClearExpectations(&b)); @@ -2362,8 +2227,7 @@ TEST(VerifyAndClearExpectationsTest, SomeMethodsHaveExpectationsAndSucceed) { // verification fails. TEST(VerifyAndClearExpectationsTest, SomeMethodsHaveExpectationsAndFail) { MockB b; - EXPECT_CALL(b, DoB()) - .WillOnce(Return(1)); + EXPECT_CALL(b, DoB()).WillOnce(Return(1)); bool result = true; EXPECT_NONFATAL_FAILURE(result = Mock::VerifyAndClearExpectations(&b), "Actual: never called"); @@ -2379,10 +2243,8 @@ TEST(VerifyAndClearExpectationsTest, SomeMethodsHaveExpectationsAndFail) { // when all of its methods have expectations. TEST(VerifyAndClearExpectationsTest, AllMethodsHaveExpectations) { MockB b; - EXPECT_CALL(b, DoB()) - .WillOnce(Return(1)); - EXPECT_CALL(b, DoB(_)) - .WillOnce(Return(2)); + EXPECT_CALL(b, DoB()).WillOnce(Return(1)); + EXPECT_CALL(b, DoB(_)).WillOnce(Return(2)); b.DoB(); b.DoB(1); ASSERT_TRUE(Mock::VerifyAndClearExpectations(&b)); @@ -2397,10 +2259,8 @@ TEST(VerifyAndClearExpectationsTest, AllMethodsHaveExpectations) { // when a method has more than one expectation. TEST(VerifyAndClearExpectationsTest, AMethodHasManyExpectations) { MockB b; - EXPECT_CALL(b, DoB(0)) - .WillOnce(Return(1)); - EXPECT_CALL(b, DoB(_)) - .WillOnce(Return(2)); + EXPECT_CALL(b, DoB(0)).WillOnce(Return(1)); + EXPECT_CALL(b, DoB(_)).WillOnce(Return(2)); b.DoB(1); bool result = true; EXPECT_NONFATAL_FAILURE(result = Mock::VerifyAndClearExpectations(&b), @@ -2421,8 +2281,7 @@ TEST(VerifyAndClearExpectationsTest, CanCallManyTimes) { b.DoB(); Mock::VerifyAndClearExpectations(&b); - EXPECT_CALL(b, DoB(_)) - .WillOnce(Return(1)); + EXPECT_CALL(b, DoB(_)).WillOnce(Return(1)); b.DoB(1); Mock::VerifyAndClearExpectations(&b); Mock::VerifyAndClearExpectations(&b); @@ -2446,8 +2305,7 @@ TEST(VerifyAndClearTest, NoMethodHasDefaultActions) { // but not all of its methods have default actions. TEST(VerifyAndClearTest, SomeMethodsHaveDefaultActions) { MockB b; - ON_CALL(b, DoB()) - .WillByDefault(Return(1)); + ON_CALL(b, DoB()).WillByDefault(Return(1)); Mock::VerifyAndClear(&b); @@ -2459,10 +2317,8 @@ TEST(VerifyAndClearTest, SomeMethodsHaveDefaultActions) { // its methods have default actions. TEST(VerifyAndClearTest, AllMethodsHaveDefaultActions) { MockB b; - ON_CALL(b, DoB()) - .WillByDefault(Return(1)); - ON_CALL(b, DoB(_)) - .WillByDefault(Return(2)); + ON_CALL(b, DoB()).WillByDefault(Return(1)); + ON_CALL(b, DoB(_)).WillByDefault(Return(2)); Mock::VerifyAndClear(&b); @@ -2477,10 +2333,8 @@ TEST(VerifyAndClearTest, AllMethodsHaveDefaultActions) { // method has more than one ON_CALL() set on it. TEST(VerifyAndClearTest, AMethodHasManyDefaultActions) { MockB b; - ON_CALL(b, DoB(0)) - .WillByDefault(Return(1)); - ON_CALL(b, DoB(_)) - .WillByDefault(Return(2)); + ON_CALL(b, DoB(0)).WillByDefault(Return(1)); + ON_CALL(b, DoB(_)).WillByDefault(Return(2)); Mock::VerifyAndClear(&b); @@ -2494,13 +2348,11 @@ TEST(VerifyAndClearTest, AMethodHasManyDefaultActions) { // times. TEST(VerifyAndClearTest, CanCallManyTimes) { MockB b; - ON_CALL(b, DoB()) - .WillByDefault(Return(1)); + ON_CALL(b, DoB()).WillByDefault(Return(1)); Mock::VerifyAndClear(&b); Mock::VerifyAndClear(&b); - ON_CALL(b, DoB(_)) - .WillByDefault(Return(1)); + ON_CALL(b, DoB(_)).WillByDefault(Return(1)); Mock::VerifyAndClear(&b); EXPECT_EQ(0, b.DoB()); @@ -2510,10 +2362,8 @@ TEST(VerifyAndClearTest, CanCallManyTimes) { // Tests that VerifyAndClear() works when the verification succeeds. TEST(VerifyAndClearTest, Success) { MockB b; - ON_CALL(b, DoB()) - .WillByDefault(Return(1)); - EXPECT_CALL(b, DoB(1)) - .WillOnce(Return(2)); + ON_CALL(b, DoB()).WillByDefault(Return(1)); + EXPECT_CALL(b, DoB(1)).WillOnce(Return(2)); b.DoB(); b.DoB(1); @@ -2528,10 +2378,8 @@ TEST(VerifyAndClearTest, Success) { // Tests that VerifyAndClear() works when the verification fails. TEST(VerifyAndClearTest, Failure) { MockB b; - ON_CALL(b, DoB(_)) - .WillByDefault(Return(1)); - EXPECT_CALL(b, DoB()) - .WillOnce(Return(2)); + ON_CALL(b, DoB(_)).WillByDefault(Return(1)); + EXPECT_CALL(b, DoB()).WillOnce(Return(2)); b.DoB(1); bool result = true; @@ -2549,12 +2397,9 @@ TEST(VerifyAndClearTest, Failure) { // expectations are set on a const mock object. TEST(VerifyAndClearTest, Const) { MockB b; - ON_CALL(Const(b), DoB()) - .WillByDefault(Return(1)); + ON_CALL(Const(b), DoB()).WillByDefault(Return(1)); - EXPECT_CALL(Const(b), DoB()) - .WillOnce(DoDefault()) - .WillOnce(Return(2)); + EXPECT_CALL(Const(b), DoB()).WillOnce(DoDefault()).WillOnce(Return(2)); b.DoB(); b.DoB(); @@ -2570,18 +2415,14 @@ TEST(VerifyAndClearTest, Const) { // object after VerifyAndClear() has been called on it. TEST(VerifyAndClearTest, CanSetDefaultActionsAndExpectationsAfterwards) { MockB b; - ON_CALL(b, DoB()) - .WillByDefault(Return(1)); - EXPECT_CALL(b, DoB(_)) - .WillOnce(Return(2)); + ON_CALL(b, DoB()).WillByDefault(Return(1)); + EXPECT_CALL(b, DoB(_)).WillOnce(Return(2)); b.DoB(1); Mock::VerifyAndClear(&b); - EXPECT_CALL(b, DoB()) - .WillOnce(Return(3)); - ON_CALL(b, DoB(_)) - .WillByDefault(Return(4)); + EXPECT_CALL(b, DoB()).WillOnce(Return(3)); + ON_CALL(b, DoB(_)).WillByDefault(Return(4)); EXPECT_EQ(3, b.DoB()); EXPECT_EQ(4, b.DoB(1)); @@ -2594,19 +2435,13 @@ TEST(VerifyAndClearTest, DoesNotAffectOtherMockObjects) { MockB b1; MockB b2; - ON_CALL(a, Binary(_, _)) - .WillByDefault(Return(true)); - EXPECT_CALL(a, Binary(_, _)) - .WillOnce(DoDefault()) - .WillOnce(Return(false)); + ON_CALL(a, Binary(_, _)).WillByDefault(Return(true)); + EXPECT_CALL(a, Binary(_, _)).WillOnce(DoDefault()).WillOnce(Return(false)); - ON_CALL(b1, DoB()) - .WillByDefault(Return(1)); - EXPECT_CALL(b1, DoB(_)) - .WillOnce(Return(2)); + ON_CALL(b1, DoB()).WillByDefault(Return(1)); + EXPECT_CALL(b1, DoB(_)).WillOnce(Return(2)); - ON_CALL(b2, DoB()) - .WillByDefault(Return(3)); + ON_CALL(b2, DoB()).WillByDefault(Return(3)); EXPECT_CALL(b2, DoB(_)); b2.DoB(0); @@ -2647,8 +2482,7 @@ TEST(VerifyAndClearTest, ReferenceHoldingMock test_mock; // ON_CALL stores a reference to a inside test_mock. - ON_CALL(test_mock, AcceptReference(_)) - .WillByDefault(SetArgPointee<0>(a)); + ON_CALL(test_mock, AcceptReference(_)).WillByDefault(SetArgPointee<0>(a)); // Throw away the reference to the mock that we have in a. After this, the // only reference to it is stored by test_mock. @@ -2669,9 +2503,8 @@ TEST(VerifyAndClearTest, TEST(SynchronizationTest, CanCallMockMethodInAction) { MockA a; MockC c; - ON_CALL(a, DoA(_)) - .WillByDefault(IgnoreResult(InvokeWithoutArgs(&c, - &MockC::NonVoidMethod))); + ON_CALL(a, DoA(_)).WillByDefault( + IgnoreResult(InvokeWithoutArgs(&c, &MockC::NonVoidMethod))); EXPECT_CALL(a, DoA(1)); EXPECT_CALL(a, DoA(1)) .WillOnce(Invoke(&a, &MockA::DoA)) @@ -2760,9 +2593,9 @@ TEST(ParameterlessExpectationsTest, // from it. This might be necessary on some platforms which require // specific setup and teardown. #if GMOCK_RENAME_MAIN -int gmock_main(int argc, char **argv) { +int gmock_main(int argc, char** argv) { #else -int main(int argc, char **argv) { +int main(int argc, char** argv) { #endif // GMOCK_RENAME_MAIN testing::InitGoogleMock(&argc, argv); // Ensures that the tests pass no matter what value of diff --git a/googlemock/test/gmock_ex_test.cc b/googlemock/test/gmock_ex_test.cc index 72eb43f..44e5e35 100644 --- a/googlemock/test/gmock_ex_test.cc +++ b/googlemock/test/gmock_ex_test.cc @@ -27,7 +27,6 @@ // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - // Tests Google Mock's functionality that depends on exceptions. #include "gmock/gmock.h" @@ -75,6 +74,5 @@ TEST(DefaultValueTest, ThrowsRuntimeErrorWhenNoDefaultValue) { } } - } // unnamed namespace #endif diff --git a/googlemock/test/gmock_leak_test_.cc b/googlemock/test/gmock_leak_test_.cc index 2e095ab..ad6f6d6 100644 --- a/googlemock/test/gmock_leak_test_.cc +++ b/googlemock/test/gmock_leak_test_.cc @@ -27,7 +27,6 @@ // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - // Google Mock - a framework for writing C++ mock classes. // // This program is for verifying that a leaked mock object can be diff --git a/googlemock/test/gmock_link2_test.cc b/googlemock/test/gmock_link2_test.cc index d27ce17..cd3d690 100644 --- a/googlemock/test/gmock_link2_test.cc +++ b/googlemock/test/gmock_link2_test.cc @@ -27,7 +27,6 @@ // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - // Google Mock - a framework for writing C++ mock classes. // // This file is for verifying that various Google Mock constructs do not diff --git a/googlemock/test/gmock_link_test.cc b/googlemock/test/gmock_link_test.cc index e7c54cc..f51e398 100644 --- a/googlemock/test/gmock_link_test.cc +++ b/googlemock/test/gmock_link_test.cc @@ -27,7 +27,6 @@ // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - // Google Mock - a framework for writing C++ mock classes. // // This file is for verifying that various Google Mock constructs do not diff --git a/googlemock/test/gmock_link_test.h b/googlemock/test/gmock_link_test.h index 5734b2e..dc9bd85 100644 --- a/googlemock/test/gmock_link_test.h +++ b/googlemock/test/gmock_link_test.h @@ -27,7 +27,6 @@ // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - // Google Mock - a framework for writing C++ mock classes. // // This file tests that: @@ -118,7 +117,7 @@ #include "gmock/gmock.h" #if !GTEST_OS_WINDOWS_MOBILE -# include <errno.h> +#include <errno.h> #endif #include <iostream> @@ -200,14 +199,14 @@ class Interface { virtual char* StringFromString(char* str) = 0; virtual int IntFromString(char* str) = 0; virtual int& IntRefFromString(char* str) = 0; - virtual void VoidFromFunc(void(*func)(char* str)) = 0; + virtual void VoidFromFunc(void (*func)(char* str)) = 0; virtual void VoidFromIntRef(int& n) = 0; // NOLINT virtual void VoidFromFloat(float n) = 0; virtual void VoidFromDouble(double n) = 0; virtual void VoidFromVector(const std::vector<int>& v) = 0; }; -class Mock: public Interface { +class Mock : public Interface { public: Mock() {} @@ -215,7 +214,7 @@ class Mock: public Interface { MOCK_METHOD1(StringFromString, char*(char* str)); MOCK_METHOD1(IntFromString, int(char* str)); MOCK_METHOD1(IntRefFromString, int&(char* str)); - MOCK_METHOD1(VoidFromFunc, void(void(*func)(char* str))); + MOCK_METHOD1(VoidFromFunc, void(void (*func)(char* str))); MOCK_METHOD1(VoidFromIntRef, void(int& n)); // NOLINT MOCK_METHOD1(VoidFromFloat, void(float n)); MOCK_METHOD1(VoidFromDouble, void(double n)); @@ -301,8 +300,8 @@ TEST(LinkTest, TestSetArrayArgument) { char ch = 'x'; char ch2 = 'y'; - EXPECT_CALL(mock, VoidFromString(_)).WillOnce(SetArrayArgument<0>(&ch2, - &ch2 + 1)); + EXPECT_CALL(mock, VoidFromString(_)) + .WillOnce(SetArrayArgument<0>(&ch2, &ch2 + 1)); mock.VoidFromString(&ch); } @@ -339,8 +338,8 @@ TEST(LinkTest, TestInvokeWithoutArgs) { EXPECT_CALL(mock, VoidFromString(_)) .WillOnce(InvokeWithoutArgs(&InvokeHelper::StaticVoidFromVoid)) - .WillOnce(InvokeWithoutArgs(&test_invoke_helper, - &InvokeHelper::VoidFromVoid)); + .WillOnce( + InvokeWithoutArgs(&test_invoke_helper, &InvokeHelper::VoidFromVoid)); mock.VoidFromString(nullptr); mock.VoidFromString(nullptr); } @@ -424,14 +423,14 @@ TEST(LinkTest, TestThrow) { // is expanded and macro expansion cannot contain #pragma. Therefore // we suppress them here. #ifdef _MSC_VER -# pragma warning(push) -# pragma warning(disable:4100) +#pragma warning(push) +#pragma warning(disable : 4100) #endif // Tests the linkage of actions created using ACTION macro. namespace { ACTION(Return1) { return 1; } -} +} // namespace TEST(LinkTest, TestActionMacro) { Mock mock; @@ -443,7 +442,7 @@ TEST(LinkTest, TestActionMacro) { // Tests the linkage of actions created using ACTION_P macro. namespace { ACTION_P(ReturnArgument, ret_value) { return ret_value; } -} +} // namespace TEST(LinkTest, TestActionPMacro) { Mock mock; @@ -457,10 +456,10 @@ namespace { ACTION_P2(ReturnEqualsEitherOf, first, second) { return arg0 == first || arg0 == second; } -} +} // namespace #ifdef _MSC_VER -# pragma warning(pop) +#pragma warning(pop) #endif TEST(LinkTest, TestActionP2Macro) { @@ -492,8 +491,7 @@ TEST(LinkTest, TestMatchersEq) { const char* p = "x"; ON_CALL(mock, VoidFromString(Eq(p))).WillByDefault(Return()); - ON_CALL(mock, VoidFromString(const_cast<char*>("y"))) - .WillByDefault(Return()); + ON_CALL(mock, VoidFromString(const_cast<char*>("y"))).WillByDefault(Return()); } // Tests the linkage of the Lt, Gt, Le, Ge, and Ne matchers. @@ -592,7 +590,7 @@ TEST(LinkTest, TestMatcherElementsAre) { // Tests the linkage of the ElementsAreArray matcher. TEST(LinkTest, TestMatcherElementsAreArray) { Mock mock; - char arr[] = { 'a', 'b' }; + char arr[] = {'a', 'b'}; ON_CALL(mock, VoidFromVector(ElementsAreArray(arr))).WillByDefault(Return()); } diff --git a/googlemock/test/gmock_output_test_.cc b/googlemock/test/gmock_output_test_.cc index b1dac45..b4abbc9 100644 --- a/googlemock/test/gmock_output_test_.cc +++ b/googlemock/test/gmock_output_test_.cc @@ -27,21 +27,20 @@ // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - // Tests Google Mock's output in various scenarios. This ensures that // Google Mock's messages are readable and useful. -#include "gmock/gmock.h" - #include <stdio.h> + #include <string> +#include "gmock/gmock.h" #include "gtest/gtest.h" // Silence C4100 (unreferenced formal parameter) #ifdef _MSC_VER -# pragma warning(push) -# pragma warning(disable:4100) +#pragma warning(push) +#pragma warning(disable : 4100) #endif using testing::_; @@ -90,9 +89,7 @@ TEST_F(GMockOutputTest, ExpectedCallToVoidFunction) { } TEST_F(GMockOutputTest, ExplicitActionsRunOut) { - EXPECT_CALL(foo_, Bar2(_, _)) - .Times(2) - .WillOnce(Return(false)); + EXPECT_CALL(foo_, Bar2(_, _)).Times(2).WillOnce(Return(false)); foo_.Bar2(2, 2); foo_.Bar2(1, 1); // Explicit actions in EXPECT_CALL run out. } @@ -134,8 +131,7 @@ TEST_F(GMockOutputTest, UninterestingCallToVoidFunction) { } TEST_F(GMockOutputTest, RetiredExpectation) { - EXPECT_CALL(foo_, Bar2(_, _)) - .RetiresOnSaturation(); + EXPECT_CALL(foo_, Bar2(_, _)).RetiresOnSaturation(); EXPECT_CALL(foo_, Bar2(0, 0)); foo_.Bar2(1, 1); @@ -160,12 +156,9 @@ TEST_F(GMockOutputTest, UnsatisfiedPrerequisite) { TEST_F(GMockOutputTest, UnsatisfiedPrerequisites) { Sequence s1, s2; - EXPECT_CALL(foo_, Bar(_, 0, _)) - .InSequence(s1); - EXPECT_CALL(foo_, Bar2(0, 0)) - .InSequence(s2); - EXPECT_CALL(foo_, Bar2(1, _)) - .InSequence(s1, s2); + EXPECT_CALL(foo_, Bar(_, 0, _)).InSequence(s1); + EXPECT_CALL(foo_, Bar2(0, 0)).InSequence(s2); + EXPECT_CALL(foo_, Bar2(1, _)).InSequence(s1, s2); foo_.Bar2(1, 0); // Has two immediate unsatisfied pre-requisites foo_.Bar("Hi", 0, 0); @@ -179,8 +172,7 @@ TEST_F(GMockOutputTest, UnsatisfiedWith) { TEST_F(GMockOutputTest, UnsatisfiedExpectation) { EXPECT_CALL(foo_, Bar(_, _, _)); - EXPECT_CALL(foo_, Bar2(0, _)) - .Times(2); + EXPECT_CALL(foo_, Bar2(0, _)).Times(2); foo_.Bar2(0, 1); } @@ -194,26 +186,22 @@ TEST_F(GMockOutputTest, MismatchArguments) { } TEST_F(GMockOutputTest, MismatchWith) { - EXPECT_CALL(foo_, Bar2(Ge(2), Ge(1))) - .With(Ge()); + EXPECT_CALL(foo_, Bar2(Ge(2), Ge(1))).With(Ge()); foo_.Bar2(2, 3); // Mismatch With() foo_.Bar2(2, 1); } TEST_F(GMockOutputTest, MismatchArgumentsAndWith) { - EXPECT_CALL(foo_, Bar2(Ge(2), Ge(1))) - .With(Ge()); + EXPECT_CALL(foo_, Bar2(Ge(2), Ge(1))).With(Ge()); foo_.Bar2(1, 3); // Mismatch arguments and mismatch With() foo_.Bar2(2, 1); } TEST_F(GMockOutputTest, UnexpectedCallWithDefaultAction) { - ON_CALL(foo_, Bar2(_, _)) - .WillByDefault(Return(true)); // Default action #1 - ON_CALL(foo_, Bar2(1, _)) - .WillByDefault(Return(false)); // Default action #2 + ON_CALL(foo_, Bar2(_, _)).WillByDefault(Return(true)); // Default action #1 + ON_CALL(foo_, Bar2(1, _)).WillByDefault(Return(false)); // Default action #2 EXPECT_CALL(foo_, Bar2(2, 2)); foo_.Bar2(1, 0); // Unexpected call, takes default action #2. @@ -222,10 +210,8 @@ TEST_F(GMockOutputTest, UnexpectedCallWithDefaultAction) { } TEST_F(GMockOutputTest, ExcessiveCallWithDefaultAction) { - ON_CALL(foo_, Bar2(_, _)) - .WillByDefault(Return(true)); // Default action #1 - ON_CALL(foo_, Bar2(1, _)) - .WillByDefault(Return(false)); // Default action #2 + ON_CALL(foo_, Bar2(_, _)).WillByDefault(Return(true)); // Default action #1 + ON_CALL(foo_, Bar2(1, _)).WillByDefault(Return(false)); // Default action #2 EXPECT_CALL(foo_, Bar2(2, 2)); EXPECT_CALL(foo_, Bar2(1, 1)); @@ -237,22 +223,17 @@ TEST_F(GMockOutputTest, ExcessiveCallWithDefaultAction) { } TEST_F(GMockOutputTest, UninterestingCallWithDefaultAction) { - ON_CALL(foo_, Bar2(_, _)) - .WillByDefault(Return(true)); // Default action #1 - ON_CALL(foo_, Bar2(1, _)) - .WillByDefault(Return(false)); // Default action #2 + ON_CALL(foo_, Bar2(_, _)).WillByDefault(Return(true)); // Default action #1 + ON_CALL(foo_, Bar2(1, _)).WillByDefault(Return(false)); // Default action #2 foo_.Bar2(2, 2); // Uninteresting call, takes default action #1. foo_.Bar2(1, 1); // Uninteresting call, takes default action #2. } TEST_F(GMockOutputTest, ExplicitActionsRunOutWithDefaultAction) { - ON_CALL(foo_, Bar2(_, _)) - .WillByDefault(Return(true)); // Default action #1 + ON_CALL(foo_, Bar2(_, _)).WillByDefault(Return(true)); // Default action #1 - EXPECT_CALL(foo_, Bar2(_, _)) - .Times(2) - .WillOnce(Return(false)); + EXPECT_CALL(foo_, Bar2(_, _)).Times(2).WillOnce(Return(false)); foo_.Bar2(2, 2); foo_.Bar2(1, 1); // Explicit actions in EXPECT_CALL run out. } @@ -293,7 +274,7 @@ void TestCatchesLeakedMocksInAdHocTests() { // foo is deliberately leaked. } -int main(int argc, char **argv) { +int main(int argc, char** argv) { testing::InitGoogleMock(&argc, argv); // Ensures that the tests pass no matter what value of // --gmock_catch_leaked_mocks and --gmock_verbose the user specifies. @@ -305,5 +286,5 @@ int main(int argc, char **argv) { } #ifdef _MSC_VER -# pragma warning(pop) +#pragma warning(pop) #endif diff --git a/googlemock/test/gmock_stress_test.cc b/googlemock/test/gmock_stress_test.cc index 20725d6..9e42cd9 100644 --- a/googlemock/test/gmock_stress_test.cc +++ b/googlemock/test/gmock_stress_test.cc @@ -27,7 +27,6 @@ // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - // Tests that Google Mock constructs can be used in a large number of // threads concurrently. @@ -49,7 +48,7 @@ const int kRepeat = 50; class MockFoo { public: - MOCK_METHOD1(Bar, int(int n)); // NOLINT + MOCK_METHOD1(Bar, int(int n)); // NOLINT MOCK_METHOD2(Baz, char(const char* s1, const std::string& s2)); // NOLINT }; @@ -62,21 +61,16 @@ void JoinAndDelete(ThreadWithParam<T>* t) { struct Dummy {}; - // Tests that different mock objects can be used in their respective // threads. This should generate no Google Test failure. void TestConcurrentMockObjects(Dummy /* dummy */) { // Creates a mock and does some typical operations on it. MockFoo foo; - ON_CALL(foo, Bar(_)) - .WillByDefault(Return(1)); - ON_CALL(foo, Baz(_, _)) - .WillByDefault(Return('b')); - ON_CALL(foo, Baz(_, "you")) - .WillByDefault(Return('a')); - - EXPECT_CALL(foo, Bar(0)) - .Times(AtMost(3)); + ON_CALL(foo, Bar(_)).WillByDefault(Return(1)); + ON_CALL(foo, Baz(_, _)).WillByDefault(Return('b')); + ON_CALL(foo, Baz(_, "you")).WillByDefault(Return('a')); + + EXPECT_CALL(foo, Bar(0)).Times(AtMost(3)); EXPECT_CALL(foo, Baz(_, _)); EXPECT_CALL(foo, Baz("hi", "you")) .WillOnce(Return('z')) @@ -119,22 +113,19 @@ void Helper1(Helper1Param param) { void TestConcurrentCallsOnSameObject(Dummy /* dummy */) { MockFoo foo; - ON_CALL(foo, Bar(_)) - .WillByDefault(Return(1)); - EXPECT_CALL(foo, Baz(_, "b")) - .Times(kRepeat) - .WillRepeatedly(Return('a')); + ON_CALL(foo, Bar(_)).WillByDefault(Return(1)); + EXPECT_CALL(foo, Baz(_, "b")).Times(kRepeat).WillRepeatedly(Return('a')); EXPECT_CALL(foo, Baz(_, "c")); // Expected to be unsatisfied. // This chunk of code should generate kRepeat failures about // excessive calls, and 2*kRepeat failures about unexpected calls. int count1 = 0; - const Helper1Param param = { &foo, &count1 }; + const Helper1Param param = {&foo, &count1}; ThreadWithParam<Helper1Param>* const t = new ThreadWithParam<Helper1Param>(Helper1, param, nullptr); int count2 = 0; - const Helper1Param param2 = { &foo, &count2 }; + const Helper1Param param2 = {&foo, &count2}; Helper1(param2); JoinAndDelete(t); @@ -162,22 +153,18 @@ void TestPartiallyOrderedExpectationsWithThreads(Dummy /* dummy */) { { InSequence dummy; EXPECT_CALL(foo, Bar(0)); - EXPECT_CALL(foo, Bar(1)) - .InSequence(s1, s2); + EXPECT_CALL(foo, Bar(1)).InSequence(s1, s2); } EXPECT_CALL(foo, Bar(2)) - .Times(2*kRepeat) + .Times(2 * kRepeat) .InSequence(s1) .RetiresOnSaturation(); - EXPECT_CALL(foo, Bar(3)) - .Times(2*kRepeat) - .InSequence(s2); + EXPECT_CALL(foo, Bar(3)).Times(2 * kRepeat).InSequence(s2); { InSequence dummy; - EXPECT_CALL(foo, Bar(2)) - .InSequence(s1, s2); + EXPECT_CALL(foo, Bar(2)).InSequence(s1, s2); EXPECT_CALL(foo, Bar(4)); } @@ -196,12 +183,12 @@ void TestPartiallyOrderedExpectationsWithThreads(Dummy /* dummy */) { // Tests using Google Mock constructs in many threads concurrently. TEST(StressTest, CanUseGMockWithThreads) { void (*test_routines[])(Dummy dummy) = { - &TestConcurrentMockObjects, - &TestConcurrentCallsOnSameObject, - &TestPartiallyOrderedExpectationsWithThreads, + &TestConcurrentMockObjects, + &TestConcurrentCallsOnSameObject, + &TestPartiallyOrderedExpectationsWithThreads, }; - const int kRoutines = sizeof(test_routines)/sizeof(test_routines[0]); + const int kRoutines = sizeof(test_routines) / sizeof(test_routines[0]); const int kCopiesOfEachRoutine = kMaxTestThreads / kRoutines; const int kTestThreads = kCopiesOfEachRoutine * kRoutines; ThreadWithParam<Dummy>* threads[kTestThreads] = {}; @@ -220,7 +207,7 @@ TEST(StressTest, CanUseGMockWithThreads) { // Ensures that the correct number of failures have been reported. const TestInfo* const info = UnitTest::GetInstance()->current_test_info(); const TestResult& result = *info->result(); - const int kExpectedFailures = (3*kRepeat + 1)*kCopiesOfEachRoutine; + const int kExpectedFailures = (3 * kRepeat + 1) * kCopiesOfEachRoutine; GTEST_CHECK_(kExpectedFailures == result.total_part_count()) << "Expected " << kExpectedFailures << " failures, but got " << result.total_part_count(); @@ -229,7 +216,7 @@ TEST(StressTest, CanUseGMockWithThreads) { } // namespace } // namespace testing -int main(int argc, char **argv) { +int main(int argc, char** argv) { testing::InitGoogleMock(&argc, argv); const int exit_code = RUN_ALL_TESTS(); // Expected to fail. diff --git a/googlemock/test/gmock_test.cc b/googlemock/test/gmock_test.cc index 9a2bd93..8f1bd5d 100644 --- a/googlemock/test/gmock_test.cc +++ b/googlemock/test/gmock_test.cc @@ -27,7 +27,6 @@ // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - // Google Mock - a framework for writing C++ mock classes. // // This file tests code in gmock.cc. @@ -35,6 +34,7 @@ #include "gmock/gmock.h" #include <string> + #include "gtest/gtest.h" #include "gtest/internal/custom/gtest.h" diff --git a/googletest/include/gtest/gtest-death-test.h b/googletest/include/gtest/gtest-death-test.h index cd34e1f..84e5a5b 100644 --- a/googletest/include/gtest/gtest-death-test.h +++ b/googletest/include/gtest/gtest-death-test.h @@ -170,24 +170,24 @@ GTEST_API_ bool InDeathTestChild(); // Asserts that a given `statement` causes the program to exit, with an // integer exit status that satisfies `predicate`, and emitting error output // that matches `matcher`. -# define ASSERT_EXIT(statement, predicate, matcher) \ - GTEST_DEATH_TEST_(statement, predicate, matcher, GTEST_FATAL_FAILURE_) +#define ASSERT_EXIT(statement, predicate, matcher) \ + GTEST_DEATH_TEST_(statement, predicate, matcher, GTEST_FATAL_FAILURE_) // Like `ASSERT_EXIT`, but continues on to successive tests in the // test suite, if any: -# define EXPECT_EXIT(statement, predicate, matcher) \ - GTEST_DEATH_TEST_(statement, predicate, matcher, GTEST_NONFATAL_FAILURE_) +#define EXPECT_EXIT(statement, predicate, matcher) \ + GTEST_DEATH_TEST_(statement, predicate, matcher, GTEST_NONFATAL_FAILURE_) // Asserts that a given `statement` causes the program to exit, either by // explicitly exiting with a nonzero exit code or being killed by a // signal, and emitting error output that matches `matcher`. -# define ASSERT_DEATH(statement, matcher) \ - ASSERT_EXIT(statement, ::testing::internal::ExitedUnsuccessfully, matcher) +#define ASSERT_DEATH(statement, matcher) \ + ASSERT_EXIT(statement, ::testing::internal::ExitedUnsuccessfully, matcher) // Like `ASSERT_DEATH`, but continues on to successive tests in the // test suite, if any: -# define EXPECT_DEATH(statement, matcher) \ - EXPECT_EXIT(statement, ::testing::internal::ExitedUnsuccessfully, matcher) +#define EXPECT_DEATH(statement, matcher) \ + EXPECT_EXIT(statement, ::testing::internal::ExitedUnsuccessfully, matcher) // Two predicate classes that can be used in {ASSERT,EXPECT}_EXIT*: @@ -198,21 +198,23 @@ class GTEST_API_ ExitedWithCode { ExitedWithCode(const ExitedWithCode&) = default; void operator=(const ExitedWithCode& other) = delete; bool operator()(int exit_status) const; + private: const int exit_code_; }; -# if !GTEST_OS_WINDOWS && !GTEST_OS_FUCHSIA +#if !GTEST_OS_WINDOWS && !GTEST_OS_FUCHSIA // Tests that an exit code describes an exit due to termination by a // given signal. class GTEST_API_ KilledBySignal { public: explicit KilledBySignal(int signum); bool operator()(int exit_status) const; + private: const int signum_; }; -# endif // !GTEST_OS_WINDOWS +#endif // !GTEST_OS_WINDOWS // EXPECT_DEBUG_DEATH asserts that the given statements die in debug mode. // The death testing framework causes this to have interesting semantics, @@ -257,23 +259,21 @@ class GTEST_API_ KilledBySignal { // EXPECT_EQ(12, DieInDebugOr12(&sideeffect)); // }, "death"); // -# ifdef NDEBUG +#ifdef NDEBUG -# define EXPECT_DEBUG_DEATH(statement, regex) \ +#define EXPECT_DEBUG_DEATH(statement, regex) \ GTEST_EXECUTE_STATEMENT_(statement, regex) -# define ASSERT_DEBUG_DEATH(statement, regex) \ +#define ASSERT_DEBUG_DEATH(statement, regex) \ GTEST_EXECUTE_STATEMENT_(statement, regex) -# else +#else -# define EXPECT_DEBUG_DEATH(statement, regex) \ - EXPECT_DEATH(statement, regex) +#define EXPECT_DEBUG_DEATH(statement, regex) EXPECT_DEATH(statement, regex) -# define ASSERT_DEBUG_DEATH(statement, regex) \ - ASSERT_DEATH(statement, regex) +#define ASSERT_DEBUG_DEATH(statement, regex) ASSERT_DEATH(statement, regex) -# endif // NDEBUG for EXPECT_DEBUG_DEATH +#endif // NDEBUG for EXPECT_DEBUG_DEATH #endif // GTEST_HAS_DEATH_TEST // This macro is used for implementing macros such as @@ -311,18 +311,17 @@ class GTEST_API_ KilledBySignal { // statement unconditionally returns or throws. The Message constructor at // the end allows the syntax of streaming additional messages into the // macro, for compilational compatibility with EXPECT_DEATH/ASSERT_DEATH. -# define GTEST_UNSUPPORTED_DEATH_TEST(statement, regex, terminator) \ - GTEST_AMBIGUOUS_ELSE_BLOCKER_ \ - if (::testing::internal::AlwaysTrue()) { \ - GTEST_LOG_(WARNING) \ - << "Death tests are not supported on this platform.\n" \ - << "Statement '" #statement "' cannot be verified."; \ - } else if (::testing::internal::AlwaysFalse()) { \ - ::testing::internal::RE::PartialMatch(".*", (regex)); \ - GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement); \ - terminator; \ - } else \ - ::testing::Message() +#define GTEST_UNSUPPORTED_DEATH_TEST(statement, regex, terminator) \ + GTEST_AMBIGUOUS_ELSE_BLOCKER_ \ + if (::testing::internal::AlwaysTrue()) { \ + GTEST_LOG_(WARNING) << "Death tests are not supported on this platform.\n" \ + << "Statement '" #statement "' cannot be verified."; \ + } else if (::testing::internal::AlwaysFalse()) { \ + ::testing::internal::RE::PartialMatch(".*", (regex)); \ + GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement); \ + terminator; \ + } else \ + ::testing::Message() // EXPECT_DEATH_IF_SUPPORTED(statement, regex) and // ASSERT_DEATH_IF_SUPPORTED(statement, regex) expand to real death tests if @@ -330,15 +329,15 @@ class GTEST_API_ KilledBySignal { // useful when you are combining death test assertions with normal test // assertions in one test. #if GTEST_HAS_DEATH_TEST -# define EXPECT_DEATH_IF_SUPPORTED(statement, regex) \ - EXPECT_DEATH(statement, regex) -# define ASSERT_DEATH_IF_SUPPORTED(statement, regex) \ - ASSERT_DEATH(statement, regex) +#define EXPECT_DEATH_IF_SUPPORTED(statement, regex) \ + EXPECT_DEATH(statement, regex) +#define ASSERT_DEATH_IF_SUPPORTED(statement, regex) \ + ASSERT_DEATH(statement, regex) #else -# define EXPECT_DEATH_IF_SUPPORTED(statement, regex) \ - GTEST_UNSUPPORTED_DEATH_TEST(statement, regex, ) -# define ASSERT_DEATH_IF_SUPPORTED(statement, regex) \ - GTEST_UNSUPPORTED_DEATH_TEST(statement, regex, return) +#define EXPECT_DEATH_IF_SUPPORTED(statement, regex) \ + GTEST_UNSUPPORTED_DEATH_TEST(statement, regex, ) +#define ASSERT_DEATH_IF_SUPPORTED(statement, regex) \ + GTEST_UNSUPPORTED_DEATH_TEST(statement, regex, return) #endif } // namespace testing diff --git a/googletest/include/gtest/gtest-matchers.h b/googletest/include/gtest/gtest-matchers.h index 3472db7..7583660 100644 --- a/googletest/include/gtest/gtest-matchers.h +++ b/googletest/include/gtest/gtest-matchers.h @@ -105,8 +105,7 @@ class MatchResultListener { GTEST_DISALLOW_COPY_AND_ASSIGN_(MatchResultListener); }; -inline MatchResultListener::~MatchResultListener() { -} +inline MatchResultListener::~MatchResultListener() {} // An instance of a subclass of this knows how to describe itself as a // matcher. @@ -180,27 +179,39 @@ namespace internal { struct AnyEq { template <typename A, typename B> - bool operator()(const A& a, const B& b) const { return a == b; } + bool operator()(const A& a, const B& b) const { + return a == b; + } }; struct AnyNe { template <typename A, typename B> - bool operator()(const A& a, const B& b) const { return a != b; } + bool operator()(const A& a, const B& b) const { + return a != b; + } }; struct AnyLt { template <typename A, typename B> - bool operator()(const A& a, const B& b) const { return a < b; } + bool operator()(const A& a, const B& b) const { + return a < b; + } }; struct AnyGt { template <typename A, typename B> - bool operator()(const A& a, const B& b) const { return a > b; } + bool operator()(const A& a, const B& b) const { + return a > b; + } }; struct AnyLe { template <typename A, typename B> - bool operator()(const A& a, const B& b) const { return a <= b; } + bool operator()(const A& a, const B& b) const { + return a <= b; + } }; struct AnyGe { template <typename A, typename B> - bool operator()(const A& a, const B& b) const { return a >= b; } + bool operator()(const A& a, const B& b) const { + return a >= b; + } }; // A match result listener that ignores the explanation. @@ -424,8 +435,8 @@ class MatcherBase : private MatcherDescriberInterface { static const M& Get(const MatcherBase& m) { // When inlined along with Init, need to be explicit to avoid violating // strict aliasing rules. - const M *ptr = static_cast<const M*>( - static_cast<const void*>(&m.buffer_)); + const M* ptr = + static_cast<const M*>(static_cast<const void*>(&m.buffer_)); return *ptr; } static void Init(MatcherBase& m, M impl) { @@ -745,7 +756,7 @@ template <typename Rhs> class EqMatcher : public ComparisonBase<EqMatcher<Rhs>, Rhs, AnyEq> { public: explicit EqMatcher(const Rhs& rhs) - : ComparisonBase<EqMatcher<Rhs>, Rhs, AnyEq>(rhs) { } + : ComparisonBase<EqMatcher<Rhs>, Rhs, AnyEq>(rhs) {} static const char* Desc() { return "is equal to"; } static const char* NegatedDesc() { return "isn't equal to"; } }; @@ -753,7 +764,7 @@ template <typename Rhs> class NeMatcher : public ComparisonBase<NeMatcher<Rhs>, Rhs, AnyNe> { public: explicit NeMatcher(const Rhs& rhs) - : ComparisonBase<NeMatcher<Rhs>, Rhs, AnyNe>(rhs) { } + : ComparisonBase<NeMatcher<Rhs>, Rhs, AnyNe>(rhs) {} static const char* Desc() { return "isn't equal to"; } static const char* NegatedDesc() { return "is equal to"; } }; @@ -761,7 +772,7 @@ template <typename Rhs> class LtMatcher : public ComparisonBase<LtMatcher<Rhs>, Rhs, AnyLt> { public: explicit LtMatcher(const Rhs& rhs) - : ComparisonBase<LtMatcher<Rhs>, Rhs, AnyLt>(rhs) { } + : ComparisonBase<LtMatcher<Rhs>, Rhs, AnyLt>(rhs) {} static const char* Desc() { return "is <"; } static const char* NegatedDesc() { return "isn't <"; } }; @@ -769,7 +780,7 @@ template <typename Rhs> class GtMatcher : public ComparisonBase<GtMatcher<Rhs>, Rhs, AnyGt> { public: explicit GtMatcher(const Rhs& rhs) - : ComparisonBase<GtMatcher<Rhs>, Rhs, AnyGt>(rhs) { } + : ComparisonBase<GtMatcher<Rhs>, Rhs, AnyGt>(rhs) {} static const char* Desc() { return "is >"; } static const char* NegatedDesc() { return "isn't >"; } }; @@ -777,7 +788,7 @@ template <typename Rhs> class LeMatcher : public ComparisonBase<LeMatcher<Rhs>, Rhs, AnyLe> { public: explicit LeMatcher(const Rhs& rhs) - : ComparisonBase<LeMatcher<Rhs>, Rhs, AnyLe>(rhs) { } + : ComparisonBase<LeMatcher<Rhs>, Rhs, AnyLe>(rhs) {} static const char* Desc() { return "is <="; } static const char* NegatedDesc() { return "isn't <="; } }; @@ -785,7 +796,7 @@ template <typename Rhs> class GeMatcher : public ComparisonBase<GeMatcher<Rhs>, Rhs, AnyGe> { public: explicit GeMatcher(const Rhs& rhs) - : ComparisonBase<GeMatcher<Rhs>, Rhs, AnyGe>(rhs) { } + : ComparisonBase<GeMatcher<Rhs>, Rhs, AnyGe>(rhs) {} static const char* Desc() { return "is >="; } static const char* NegatedDesc() { return "isn't >="; } }; @@ -876,12 +887,16 @@ PolymorphicMatcher<internal::MatchesRegexMatcher> ContainsRegex( // Note: if the parameter of Eq() were declared as const T&, Eq("foo") // wouldn't compile. template <typename T> -inline internal::EqMatcher<T> Eq(T x) { return internal::EqMatcher<T>(x); } +inline internal::EqMatcher<T> Eq(T x) { + return internal::EqMatcher<T>(x); +} // Constructs a Matcher<T> from a 'value' of type T. The constructed // matcher matches any value that's equal to 'value'. template <typename T> -Matcher<T>::Matcher(T value) { *this = Eq(value); } +Matcher<T>::Matcher(T value) { + *this = Eq(value); +} // Creates a monomorphic matcher that matches anything with type Lhs // and equal to rhs. A user may need to use this instead of Eq(...) @@ -896,7 +911,9 @@ Matcher<T>::Matcher(T value) { *this = Eq(value); } // can always write Matcher<T>(Lt(5)) to be explicit about the type, // for example. template <typename Lhs, typename Rhs> -inline Matcher<Lhs> TypedEq(const Rhs& rhs) { return Eq(rhs); } +inline Matcher<Lhs> TypedEq(const Rhs& rhs) { + return Eq(rhs); +} // Creates a polymorphic matcher that matches anything >= x. template <typename Rhs> diff --git a/googletest/include/gtest/gtest-message.h b/googletest/include/gtest/gtest-message.h index 9419229..6c8bf90 100644 --- a/googletest/include/gtest/gtest-message.h +++ b/googletest/include/gtest/gtest-message.h @@ -111,8 +111,8 @@ class GTEST_API_ Message { // Streams a non-pointer value to this object. template <typename T> - inline Message& operator <<(const T& val) { - // Some libraries overload << for STL containers. These + inline Message& operator<<(const T& val) { + // Some libraries overload << for STL containers. These // overloads are defined in the global namespace instead of ::std. // // C++'s symbol lookup rule (i.e. Koenig lookup) says that these @@ -126,7 +126,7 @@ class GTEST_API_ Message { // from the global namespace. With this using declaration, // overloads of << defined in the global namespace and those // visible via Koenig lookup are both exposed in this function. - using ::operator <<; + using ::operator<<; *ss_ << val; return *this; } @@ -145,7 +145,7 @@ class GTEST_API_ Message { // ensure consistent result across compilers, we always treat NULL // as "(null)". template <typename T> - inline Message& operator <<(T* const& pointer) { // NOLINT + inline Message& operator<<(T* const& pointer) { // NOLINT if (pointer == nullptr) { *ss_ << "(null)"; } else { @@ -160,25 +160,23 @@ class GTEST_API_ Message { // templatized version above. Without this definition, streaming // endl or other basic IO manipulators to Message will confuse the // compiler. - Message& operator <<(BasicNarrowIoManip val) { + Message& operator<<(BasicNarrowIoManip val) { *ss_ << val; return *this; } // Instead of 1/0, we want to see true/false for bool values. - Message& operator <<(bool b) { - return *this << (b ? "true" : "false"); - } + Message& operator<<(bool b) { return *this << (b ? "true" : "false"); } // These two overloads allow streaming a wide C string to a Message // using the UTF-8 encoding. - Message& operator <<(const wchar_t* wide_c_str); - Message& operator <<(wchar_t* wide_c_str); + Message& operator<<(const wchar_t* wide_c_str); + Message& operator<<(wchar_t* wide_c_str); #if GTEST_HAS_STD_WSTRING // Converts the given wide string to a narrow string using the UTF-8 // encoding, and streams the result to this Message object. - Message& operator <<(const ::std::wstring& wstr); + Message& operator<<(const ::std::wstring& wstr); #endif // GTEST_HAS_STD_WSTRING // Gets the text streamed to this object so far as an std::string. @@ -197,7 +195,7 @@ class GTEST_API_ Message { }; // Streams a Message to an ostream. -inline std::ostream& operator <<(std::ostream& os, const Message& sb) { +inline std::ostream& operator<<(std::ostream& os, const Message& sb) { return os << sb.GetString(); } diff --git a/googletest/include/gtest/gtest-param-test.h b/googletest/include/gtest/gtest-param-test.h index 96c1c72..e9a6260 100644 --- a/googletest/include/gtest/gtest-param-test.h +++ b/googletest/include/gtest/gtest-param-test.h @@ -356,9 +356,7 @@ internal::ValueArray<T...> Values(T... v) { // } // INSTANTIATE_TEST_SUITE_P(BoolSequence, FlagDependentTest, Bool()); // -inline internal::ParamGenerator<bool> Bool() { - return Values(false, true); -} +inline internal::ParamGenerator<bool> Bool() { return Values(false, true); } // Combine() allows the user to combine two or more sequences to produce // values of a Cartesian product of those sequences' elements. @@ -456,43 +454,42 @@ internal::CartesianProductHolder<Generator...> Combine(const Generator&... g) { #define GTEST_GET_FIRST_(first, ...) first #define GTEST_GET_SECOND_(first, second, ...) second -#define INSTANTIATE_TEST_SUITE_P(prefix, test_suite_name, ...) \ - static ::testing::internal::ParamGenerator<test_suite_name::ParamType> \ - gtest_##prefix##test_suite_name##_EvalGenerator_() { \ - return GTEST_EXPAND_(GTEST_GET_FIRST_(__VA_ARGS__, DUMMY_PARAM_)); \ - } \ - static ::std::string gtest_##prefix##test_suite_name##_EvalGenerateName_( \ - const ::testing::TestParamInfo<test_suite_name::ParamType>& info) { \ - if (::testing::internal::AlwaysFalse()) { \ - ::testing::internal::TestNotEmpty(GTEST_EXPAND_(GTEST_GET_SECOND_( \ - __VA_ARGS__, \ - ::testing::internal::DefaultParamName<test_suite_name::ParamType>, \ - DUMMY_PARAM_))); \ - auto t = std::make_tuple(__VA_ARGS__); \ - static_assert(std::tuple_size<decltype(t)>::value <= 2, \ - "Too Many Args!"); \ - } \ - return ((GTEST_EXPAND_(GTEST_GET_SECOND_( \ - __VA_ARGS__, \ - ::testing::internal::DefaultParamName<test_suite_name::ParamType>, \ - DUMMY_PARAM_))))(info); \ - } \ - static int gtest_##prefix##test_suite_name##_dummy_ \ - GTEST_ATTRIBUTE_UNUSED_ = \ - ::testing::UnitTest::GetInstance() \ - ->parameterized_test_registry() \ - .GetTestSuitePatternHolder<test_suite_name>( \ - GTEST_STRINGIFY_(test_suite_name), \ - ::testing::internal::CodeLocation(__FILE__, __LINE__)) \ - ->AddTestSuiteInstantiation( \ - GTEST_STRINGIFY_(prefix), \ - >est_##prefix##test_suite_name##_EvalGenerator_, \ - >est_##prefix##test_suite_name##_EvalGenerateName_, \ +#define INSTANTIATE_TEST_SUITE_P(prefix, test_suite_name, ...) \ + static ::testing::internal::ParamGenerator<test_suite_name::ParamType> \ + gtest_##prefix##test_suite_name##_EvalGenerator_() { \ + return GTEST_EXPAND_(GTEST_GET_FIRST_(__VA_ARGS__, DUMMY_PARAM_)); \ + } \ + static ::std::string gtest_##prefix##test_suite_name##_EvalGenerateName_( \ + const ::testing::TestParamInfo<test_suite_name::ParamType>& info) { \ + if (::testing::internal::AlwaysFalse()) { \ + ::testing::internal::TestNotEmpty(GTEST_EXPAND_(GTEST_GET_SECOND_( \ + __VA_ARGS__, \ + ::testing::internal::DefaultParamName<test_suite_name::ParamType>, \ + DUMMY_PARAM_))); \ + auto t = std::make_tuple(__VA_ARGS__); \ + static_assert(std::tuple_size<decltype(t)>::value <= 2, \ + "Too Many Args!"); \ + } \ + return ((GTEST_EXPAND_(GTEST_GET_SECOND_( \ + __VA_ARGS__, \ + ::testing::internal::DefaultParamName<test_suite_name::ParamType>, \ + DUMMY_PARAM_))))(info); \ + } \ + static int gtest_##prefix##test_suite_name##_dummy_ \ + GTEST_ATTRIBUTE_UNUSED_ = \ + ::testing::UnitTest::GetInstance() \ + ->parameterized_test_registry() \ + .GetTestSuitePatternHolder<test_suite_name>( \ + GTEST_STRINGIFY_(test_suite_name), \ + ::testing::internal::CodeLocation(__FILE__, __LINE__)) \ + ->AddTestSuiteInstantiation( \ + GTEST_STRINGIFY_(prefix), \ + >est_##prefix##test_suite_name##_EvalGenerator_, \ + >est_##prefix##test_suite_name##_EvalGenerateName_, \ __FILE__, __LINE__) - // Allow Marking a Parameterized test class as not needing to be instantiated. -#define GTEST_ALLOW_UNINSTANTIATED_PARAMETERIZED_TEST(T) \ +#define GTEST_ALLOW_UNINSTANTIATED_PARAMETERIZED_TEST(T) \ namespace gtest_do_not_use_outside_namespace_scope {} \ static const ::testing::internal::MarkAsIgnored gtest_allow_ignore_##T( \ GTEST_STRINGIFY_(T)) diff --git a/googletest/include/gtest/gtest-printers.h b/googletest/include/gtest/gtest-printers.h index b097e98..a91e8b8 100644 --- a/googletest/include/gtest/gtest-printers.h +++ b/googletest/include/gtest/gtest-printers.h @@ -258,12 +258,10 @@ struct ConvertibleToStringViewPrinter { #endif }; - // Prints the given number of bytes in the given object to the given // ostream. GTEST_API_ void PrintBytesInObjectTo(const unsigned char* obj_bytes, - size_t count, - ::std::ostream* os); + size_t count, ::std::ostream* os); struct RawBytesPrinter { // SFINAE on `sizeof` to make sure we have a complete type. template <typename T, size_t = sizeof(T)> @@ -376,12 +374,12 @@ GTEST_IMPL_FORMAT_C_STRING_AS_POINTER_(const char32_t); // to point to a NUL-terminated string, and thus can print it as a string. #define GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(CharType, OtherStringType) \ - template <> \ - class FormatForComparison<CharType*, OtherStringType> { \ - public: \ - static ::std::string Format(CharType* value) { \ - return ::testing::PrintToString(value); \ - } \ + template <> \ + class FormatForComparison<CharType*, OtherStringType> { \ + public: \ + static ::std::string Format(CharType* value) { \ + return ::testing::PrintToString(value); \ + } \ } GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(char, ::std::string); @@ -411,8 +409,8 @@ GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(const wchar_t, ::std::wstring); // // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM. template <typename T1, typename T2> -std::string FormatForComparisonFailureMessage( - const T1& value, const T2& /* other_operand */) { +std::string FormatForComparisonFailureMessage(const T1& value, + const T2& /* other_operand */) { return FormatForComparison<T1, T2>::Format(value); } @@ -552,7 +550,7 @@ void PrintRawArrayTo(const T a[], size_t count, ::std::ostream* os) { } // Overloads for ::std::string. -GTEST_API_ void PrintStringTo(const ::std::string&s, ::std::ostream* os); +GTEST_API_ void PrintStringTo(const ::std::string& s, ::std::ostream* os); inline void PrintTo(const ::std::string& s, ::std::ostream* os) { PrintStringTo(s, os); } @@ -579,7 +577,7 @@ inline void PrintTo(const ::std::u32string& s, ::std::ostream* os) { // Overloads for ::std::wstring. #if GTEST_HAS_STD_WSTRING -GTEST_API_ void PrintWideStringTo(const ::std::wstring&s, ::std::ostream* os); +GTEST_API_ void PrintWideStringTo(const ::std::wstring& s, ::std::ostream* os); inline void PrintTo(const ::std::wstring& s, ::std::ostream* os) { PrintWideStringTo(s, os); } @@ -823,8 +821,8 @@ void UniversalPrintArray(const T* begin, size_t len, ::std::ostream* os) { } } // This overload prints a (const) char array compactly. -GTEST_API_ void UniversalPrintArray( - const char* begin, size_t len, ::std::ostream* os); +GTEST_API_ void UniversalPrintArray(const char* begin, size_t len, + ::std::ostream* os); #ifdef __cpp_char8_t // This overload prints a (const) char8_t array compactly. @@ -841,8 +839,8 @@ GTEST_API_ void UniversalPrintArray(const char32_t* begin, size_t len, ::std::ostream* os); // This overload prints a (const) wchar_t array compactly. -GTEST_API_ void UniversalPrintArray( - const wchar_t* begin, size_t len, ::std::ostream* os); +GTEST_API_ void UniversalPrintArray(const wchar_t* begin, size_t len, + ::std::ostream* os); // Implements printing an array type T[N]. template <typename T, size_t N> @@ -1001,10 +999,10 @@ void UniversalPrint(const T& value, ::std::ostream* os) { UniversalPrinter<T1>::Print(value, os); } -typedef ::std::vector< ::std::string> Strings; +typedef ::std::vector<::std::string> Strings; - // Tersely prints the first N fields of a tuple to a string vector, - // one element for each field. +// Tersely prints the first N fields of a tuple to a string vector, +// one element for each field. template <typename Tuple> void TersePrintPrefixToStrings(const Tuple&, std::integral_constant<size_t, 0>, Strings*) {} diff --git a/googletest/include/gtest/gtest-spi.h b/googletest/include/gtest/gtest-spi.h index 12c94e4..2554621 100644 --- a/googletest/include/gtest/gtest-spi.h +++ b/googletest/include/gtest/gtest-spi.h @@ -101,6 +101,7 @@ class GTEST_API_ SingleFailureChecker { SingleFailureChecker(const TestPartResultArray* results, TestPartResult::Type type, const std::string& substr); ~SingleFailureChecker(); + private: const TestPartResultArray* const results_; const TestPartResult::Type type_; @@ -138,38 +139,39 @@ GTEST_DISABLE_MSC_WARNINGS_POP_() // 4251 // helper macro, due to some peculiarity in how the preprocessor // works. The AcceptsMacroThatExpandsToUnprotectedComma test in // gtest_unittest.cc will fail to compile if we do that. -#define EXPECT_FATAL_FAILURE(statement, substr) \ - do { \ - class GTestExpectFatalFailureHelper {\ - public:\ - static void Execute() { statement; }\ - };\ - ::testing::TestPartResultArray gtest_failures;\ - ::testing::internal::SingleFailureChecker gtest_checker(\ - >est_failures, ::testing::TestPartResult::kFatalFailure, (substr));\ - {\ - ::testing::ScopedFakeTestPartResultReporter gtest_reporter(\ - ::testing::ScopedFakeTestPartResultReporter:: \ - INTERCEPT_ONLY_CURRENT_THREAD, >est_failures);\ - GTestExpectFatalFailureHelper::Execute();\ - }\ +#define EXPECT_FATAL_FAILURE(statement, substr) \ + do { \ + class GTestExpectFatalFailureHelper { \ + public: \ + static void Execute() { statement; } \ + }; \ + ::testing::TestPartResultArray gtest_failures; \ + ::testing::internal::SingleFailureChecker gtest_checker( \ + >est_failures, ::testing::TestPartResult::kFatalFailure, (substr)); \ + { \ + ::testing::ScopedFakeTestPartResultReporter gtest_reporter( \ + ::testing::ScopedFakeTestPartResultReporter:: \ + INTERCEPT_ONLY_CURRENT_THREAD, \ + >est_failures); \ + GTestExpectFatalFailureHelper::Execute(); \ + } \ } while (::testing::internal::AlwaysFalse()) -#define EXPECT_FATAL_FAILURE_ON_ALL_THREADS(statement, substr) \ - do { \ - class GTestExpectFatalFailureHelper {\ - public:\ - static void Execute() { statement; }\ - };\ - ::testing::TestPartResultArray gtest_failures;\ - ::testing::internal::SingleFailureChecker gtest_checker(\ - >est_failures, ::testing::TestPartResult::kFatalFailure, (substr));\ - {\ - ::testing::ScopedFakeTestPartResultReporter gtest_reporter(\ - ::testing::ScopedFakeTestPartResultReporter:: \ - INTERCEPT_ALL_THREADS, >est_failures);\ - GTestExpectFatalFailureHelper::Execute();\ - }\ +#define EXPECT_FATAL_FAILURE_ON_ALL_THREADS(statement, substr) \ + do { \ + class GTestExpectFatalFailureHelper { \ + public: \ + static void Execute() { statement; } \ + }; \ + ::testing::TestPartResultArray gtest_failures; \ + ::testing::internal::SingleFailureChecker gtest_checker( \ + >est_failures, ::testing::TestPartResult::kFatalFailure, (substr)); \ + { \ + ::testing::ScopedFakeTestPartResultReporter gtest_reporter( \ + ::testing::ScopedFakeTestPartResultReporter::INTERCEPT_ALL_THREADS, \ + >est_failures); \ + GTestExpectFatalFailureHelper::Execute(); \ + } \ } while (::testing::internal::AlwaysFalse()) // A macro for testing Google Test assertions or code that's expected to @@ -204,32 +206,37 @@ GTEST_DISABLE_MSC_WARNINGS_POP_() // 4251 // instead of // GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement) // to avoid an MSVC warning on unreachable code. -#define EXPECT_NONFATAL_FAILURE(statement, substr) \ - do {\ - ::testing::TestPartResultArray gtest_failures;\ - ::testing::internal::SingleFailureChecker gtest_checker(\ +#define EXPECT_NONFATAL_FAILURE(statement, substr) \ + do { \ + ::testing::TestPartResultArray gtest_failures; \ + ::testing::internal::SingleFailureChecker gtest_checker( \ >est_failures, ::testing::TestPartResult::kNonFatalFailure, \ - (substr));\ - {\ - ::testing::ScopedFakeTestPartResultReporter gtest_reporter(\ - ::testing::ScopedFakeTestPartResultReporter:: \ - INTERCEPT_ONLY_CURRENT_THREAD, >est_failures);\ - if (::testing::internal::AlwaysTrue()) { statement; }\ - }\ + (substr)); \ + { \ + ::testing::ScopedFakeTestPartResultReporter gtest_reporter( \ + ::testing::ScopedFakeTestPartResultReporter:: \ + INTERCEPT_ONLY_CURRENT_THREAD, \ + >est_failures); \ + if (::testing::internal::AlwaysTrue()) { \ + statement; \ + } \ + } \ } while (::testing::internal::AlwaysFalse()) -#define EXPECT_NONFATAL_FAILURE_ON_ALL_THREADS(statement, substr) \ - do {\ - ::testing::TestPartResultArray gtest_failures;\ - ::testing::internal::SingleFailureChecker gtest_checker(\ - >est_failures, ::testing::TestPartResult::kNonFatalFailure, \ - (substr));\ - {\ - ::testing::ScopedFakeTestPartResultReporter gtest_reporter(\ +#define EXPECT_NONFATAL_FAILURE_ON_ALL_THREADS(statement, substr) \ + do { \ + ::testing::TestPartResultArray gtest_failures; \ + ::testing::internal::SingleFailureChecker gtest_checker( \ + >est_failures, ::testing::TestPartResult::kNonFatalFailure, \ + (substr)); \ + { \ + ::testing::ScopedFakeTestPartResultReporter gtest_reporter( \ ::testing::ScopedFakeTestPartResultReporter::INTERCEPT_ALL_THREADS, \ - >est_failures);\ - if (::testing::internal::AlwaysTrue()) { statement; }\ - }\ + >est_failures); \ + if (::testing::internal::AlwaysTrue()) { \ + statement; \ + } \ + } \ } while (::testing::internal::AlwaysFalse()) #endif // GOOGLETEST_INCLUDE_GTEST_GTEST_SPI_H_ diff --git a/googletest/include/gtest/gtest-test-part.h b/googletest/include/gtest/gtest-test-part.h index 39393b2..8e9fba2 100644 --- a/googletest/include/gtest/gtest-test-part.h +++ b/googletest/include/gtest/gtest-test-part.h @@ -36,6 +36,7 @@ #include <iosfwd> #include <vector> + #include "gtest/internal/gtest-internal.h" #include "gtest/internal/gtest-string.h" @@ -170,6 +171,7 @@ class GTEST_API_ HasNewFatalFailureHelper ~HasNewFatalFailureHelper() override; void ReportTestPartResult(const TestPartResult& result) override; bool has_new_fatal_failure() const { return has_new_fatal_failure_; } + private: bool has_new_fatal_failure_; TestPartResultReporterInterface* original_reporter_; diff --git a/googletest/include/gtest/gtest-typed-test.h b/googletest/include/gtest/gtest-typed-test.h index 343bf6f..bd35a32 100644 --- a/googletest/include/gtest/gtest-typed-test.h +++ b/googletest/include/gtest/gtest-typed-test.h @@ -192,7 +192,7 @@ INSTANTIATE_TYPED_TEST_SUITE_P(My, FooTest, MyTypes); typedef ::testing::internal::GenerateTypeList<Types>::type \ GTEST_TYPE_PARAMS_(CaseName); \ typedef ::testing::internal::NameGeneratorSelector<__VA_ARGS__>::type \ - GTEST_NAME_GENERATOR_(CaseName) + GTEST_NAME_GENERATOR_(CaseName) #define TYPED_TEST(CaseName, TestName) \ static_assert(sizeof(GTEST_STRINGIFY_(TestName)) > 1, \ @@ -258,7 +258,7 @@ INSTANTIATE_TYPED_TEST_SUITE_P(My, FooTest, MyTypes); // #included in multiple translation units linked together. #define TYPED_TEST_SUITE_P(SuiteName) \ static ::testing::internal::TypedTestSuitePState \ - GTEST_TYPED_TEST_SUITE_P_STATE_(SuiteName) + GTEST_TYPED_TEST_SUITE_P_STATE_(SuiteName) // Legacy API is deprecated but still available #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_ @@ -303,21 +303,21 @@ INSTANTIATE_TYPED_TEST_SUITE_P(My, FooTest, MyTypes); REGISTER_TYPED_TEST_SUITE_P #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_ -#define INSTANTIATE_TYPED_TEST_SUITE_P(Prefix, SuiteName, Types, ...) \ - static_assert(sizeof(GTEST_STRINGIFY_(Prefix)) > 1, \ - "test-suit-prefix must not be empty"); \ - static bool gtest_##Prefix##_##SuiteName GTEST_ATTRIBUTE_UNUSED_ = \ - ::testing::internal::TypeParameterizedTestSuite< \ - SuiteName, GTEST_SUITE_NAMESPACE_(SuiteName)::gtest_AllTests_, \ - ::testing::internal::GenerateTypeList<Types>::type>:: \ - Register(GTEST_STRINGIFY_(Prefix), \ - ::testing::internal::CodeLocation(__FILE__, __LINE__), \ - >EST_TYPED_TEST_SUITE_P_STATE_(SuiteName), \ - GTEST_STRINGIFY_(SuiteName), \ - GTEST_REGISTERED_TEST_NAMES_(SuiteName), \ - ::testing::internal::GenerateNames< \ - ::testing::internal::NameGeneratorSelector< \ - __VA_ARGS__>::type, \ +#define INSTANTIATE_TYPED_TEST_SUITE_P(Prefix, SuiteName, Types, ...) \ + static_assert(sizeof(GTEST_STRINGIFY_(Prefix)) > 1, \ + "test-suit-prefix must not be empty"); \ + static bool gtest_##Prefix##_##SuiteName GTEST_ATTRIBUTE_UNUSED_ = \ + ::testing::internal::TypeParameterizedTestSuite< \ + SuiteName, GTEST_SUITE_NAMESPACE_(SuiteName)::gtest_AllTests_, \ + ::testing::internal::GenerateTypeList<Types>::type>:: \ + Register(GTEST_STRINGIFY_(Prefix), \ + ::testing::internal::CodeLocation(__FILE__, __LINE__), \ + >EST_TYPED_TEST_SUITE_P_STATE_(SuiteName), \ + GTEST_STRINGIFY_(SuiteName), \ + GTEST_REGISTERED_TEST_NAMES_(SuiteName), \ + ::testing::internal::GenerateNames< \ + ::testing::internal::NameGeneratorSelector< \ + __VA_ARGS__>::type, \ ::testing::internal::GenerateTypeList<Types>::type>()) // Legacy API is deprecated but still available diff --git a/googletest/include/gtest/gtest.h b/googletest/include/gtest/gtest.h index a4174cd..0c6e75c 100644 --- a/googletest/include/gtest/gtest.h +++ b/googletest/include/gtest/gtest.h @@ -353,24 +353,17 @@ class TestProperty { // C'tor. TestProperty does NOT have a default constructor. // Always use this constructor (with parameters) to create a // TestProperty object. - TestProperty(const std::string& a_key, const std::string& a_value) : - key_(a_key), value_(a_value) { - } + TestProperty(const std::string& a_key, const std::string& a_value) + : key_(a_key), value_(a_value) {} // Gets the user supplied key. - const char* key() const { - return key_.c_str(); - } + const char* key() const { return key_.c_str(); } // Gets the user supplied value. - const char* value() const { - return value_.c_str(); - } + const char* value() const { return value_.c_str(); } // Sets a new value, overriding the one supplied in the constructor. - void SetValue(const std::string& new_value) { - value_ = new_value; - } + void SetValue(const std::string& new_value) { value_ = new_value; } private: // The key supplied by the user. @@ -628,8 +621,8 @@ class GTEST_API_ TestInfo { } // These fields are immutable properties of the test. - const std::string test_suite_name_; // test suite name - const std::string name_; // Test 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. const std::unique_ptr<const ::std::string> type_param_; @@ -758,7 +751,7 @@ class GTEST_API_ TestSuite { // Adds a TestInfo to this test suite. Will delete the TestInfo upon // destruction of the TestSuite object. - void AddTestInfo(TestInfo * test_info); + void AddTestInfo(TestInfo* test_info); // Clears the results of all tests in this test suite. void ClearResult(); @@ -886,6 +879,7 @@ class Environment { // Override this to define how to tear down the environment. virtual void TearDown() {} + private: // If you see an error about overriding the following function or // about it being private, you have mis-spelled SetUp() as Setup(). @@ -963,8 +957,7 @@ class TestEventListener { virtual void OnEnvironmentsTearDownEnd(const UnitTest& unit_test) = 0; // Fired after each iteration of tests finishes. - virtual void OnTestIterationEnd(const UnitTest& unit_test, - int iteration) = 0; + virtual void OnTestIterationEnd(const UnitTest& unit_test, int iteration) = 0; // Fired after all test activities have ended. virtual void OnTestProgramEnd(const UnitTest& unit_test) = 0; @@ -1122,8 +1115,7 @@ class GTEST_API_ UnitTest { // Returns the TestInfo object for the test that's currently running, // or NULL if no test is running. - const TestInfo* current_test_info() const - GTEST_LOCK_EXCLUDED_(mutex_); + const TestInfo* current_test_info() const GTEST_LOCK_EXCLUDED_(mutex_); // Returns the random seed used at the start of the current test run. int random_seed() const; @@ -1229,8 +1221,7 @@ class GTEST_API_ UnitTest { // eventually call this to report their results. The user code // should use the assertion macros instead of calling this directly. void AddTestPartResult(TestPartResult::Type result_type, - const char* file_name, - int line_number, + const char* file_name, int line_number, const std::string& message, const std::string& os_stack_trace) GTEST_LOCK_EXCLUDED_(mutex_); @@ -1261,8 +1252,7 @@ class GTEST_API_ UnitTest { friend std::set<std::string>* internal::GetIgnoredParameterizedTestSuites(); friend internal::UnitTestImpl* internal::GetUnitTestImpl(); friend void internal::ReportFailureInUnknownLocation( - TestPartResult::Type result_type, - const std::string& message); + TestPartResult::Type result_type, const std::string& message); // Creates an empty UnitTest. UnitTest(); @@ -1276,8 +1266,7 @@ class GTEST_API_ UnitTest { GTEST_LOCK_EXCLUDED_(mutex_); // Pops a trace from the per-thread Google Test trace stack. - void PopGTestTrace() - GTEST_LOCK_EXCLUDED_(mutex_); + void PopGTestTrace() GTEST_LOCK_EXCLUDED_(mutex_); // Protects mutable state in *impl_. This is mutable as some const // methods need to lock it too. @@ -1341,13 +1330,11 @@ namespace internal { // when calling EXPECT_* in a tight loop. template <typename T1, typename T2> AssertionResult CmpHelperEQFailure(const char* lhs_expression, - const char* rhs_expression, - const T1& lhs, const T2& rhs) { - return EqFailure(lhs_expression, - rhs_expression, + const char* rhs_expression, const T1& lhs, + const T2& rhs) { + return EqFailure(lhs_expression, rhs_expression, FormatForComparisonFailureMessage(lhs, rhs), - FormatForComparisonFailureMessage(rhs, lhs), - false); + FormatForComparisonFailureMessage(rhs, lhs), false); } // This block of code defines operator==/!= @@ -1360,8 +1347,7 @@ inline bool operator!=(faketype, faketype) { return false; } // The helper function for {ASSERT|EXPECT}_EQ. template <typename T1, typename T2> AssertionResult CmpHelperEQ(const char* lhs_expression, - const char* rhs_expression, - const T1& lhs, + const char* rhs_expression, const T1& lhs, const T2& rhs) { if (lhs == rhs) { return AssertionSuccess(); @@ -1392,8 +1378,7 @@ class EqHelper { // Even though its body looks the same as the above version, we // cannot merge the two, as it will make anonymous enums unhappy. static AssertionResult Compare(const char* lhs_expression, - const char* rhs_expression, - BiggestInt lhs, + const char* rhs_expression, BiggestInt lhs, BiggestInt rhs) { return CmpHelperEQ(lhs_expression, rhs_expression, lhs, rhs); } @@ -1428,16 +1413,16 @@ AssertionResult CmpHelperOpFailure(const char* expr1, const char* expr2, // // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM. -#define GTEST_IMPL_CMP_HELPER_(op_name, op)\ -template <typename T1, typename T2>\ -AssertionResult CmpHelper##op_name(const char* expr1, const char* expr2, \ - const T1& val1, const T2& val2) {\ - if (val1 op val2) {\ - return AssertionSuccess();\ - } else {\ - return CmpHelperOpFailure(expr1, expr2, val1, val2, #op);\ - }\ -} +#define GTEST_IMPL_CMP_HELPER_(op_name, op) \ + template <typename T1, typename T2> \ + AssertionResult CmpHelper##op_name(const char* expr1, const char* expr2, \ + const T1& val1, const T2& val2) { \ + if (val1 op val2) { \ + return AssertionSuccess(); \ + } else { \ + return CmpHelperOpFailure(expr1, expr2, val1, val2, #op); \ + } \ + } // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM. @@ -1459,49 +1444,42 @@ GTEST_IMPL_CMP_HELPER_(GT, >) // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM. GTEST_API_ AssertionResult CmpHelperSTREQ(const char* s1_expression, const char* s2_expression, - const char* s1, - const char* s2); + const char* s1, const char* s2); // The helper function for {ASSERT|EXPECT}_STRCASEEQ. // // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM. GTEST_API_ AssertionResult CmpHelperSTRCASEEQ(const char* s1_expression, const char* s2_expression, - const char* s1, - const char* s2); + const char* s1, const char* s2); // The helper function for {ASSERT|EXPECT}_STRNE. // // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM. GTEST_API_ AssertionResult CmpHelperSTRNE(const char* s1_expression, const char* s2_expression, - const char* s1, - const char* s2); + const char* s1, const char* s2); // The helper function for {ASSERT|EXPECT}_STRCASENE. // // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM. GTEST_API_ AssertionResult CmpHelperSTRCASENE(const char* s1_expression, const char* s2_expression, - const char* s1, - const char* s2); - + const char* s1, const char* s2); // Helper function for *_STREQ on wide strings. // // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM. GTEST_API_ AssertionResult CmpHelperSTREQ(const char* s1_expression, const char* s2_expression, - const wchar_t* s1, - const wchar_t* s2); + const wchar_t* s1, const wchar_t* s2); // Helper function for *_STRNE on wide strings. // // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM. GTEST_API_ AssertionResult CmpHelperSTRNE(const char* s1_expression, const char* s2_expression, - const wchar_t* s1, - const wchar_t* s2); + const wchar_t* s1, const wchar_t* s2); } // namespace internal @@ -1513,32 +1491,40 @@ GTEST_API_ AssertionResult CmpHelperSTRNE(const char* s1_expression, // // The {needle,haystack}_expr arguments are the stringified // expressions that generated the two real arguments. -GTEST_API_ AssertionResult IsSubstring( - const char* needle_expr, const char* haystack_expr, - const char* needle, const char* haystack); -GTEST_API_ AssertionResult IsSubstring( - const char* needle_expr, const char* haystack_expr, - const wchar_t* needle, const wchar_t* haystack); -GTEST_API_ AssertionResult IsNotSubstring( - const char* needle_expr, const char* haystack_expr, - const char* needle, const char* haystack); -GTEST_API_ AssertionResult IsNotSubstring( - const char* needle_expr, const char* haystack_expr, - const wchar_t* needle, const wchar_t* haystack); -GTEST_API_ AssertionResult IsSubstring( - const char* needle_expr, const char* haystack_expr, - const ::std::string& needle, const ::std::string& haystack); -GTEST_API_ AssertionResult IsNotSubstring( - const char* needle_expr, const char* haystack_expr, - const ::std::string& needle, const ::std::string& haystack); +GTEST_API_ AssertionResult IsSubstring(const char* needle_expr, + const char* haystack_expr, + const char* needle, + const char* haystack); +GTEST_API_ AssertionResult IsSubstring(const char* needle_expr, + const char* haystack_expr, + const wchar_t* needle, + const wchar_t* haystack); +GTEST_API_ AssertionResult IsNotSubstring(const char* needle_expr, + const char* haystack_expr, + const char* needle, + const char* haystack); +GTEST_API_ AssertionResult IsNotSubstring(const char* needle_expr, + const char* haystack_expr, + const wchar_t* needle, + const wchar_t* haystack); +GTEST_API_ AssertionResult IsSubstring(const char* needle_expr, + const char* haystack_expr, + const ::std::string& needle, + const ::std::string& haystack); +GTEST_API_ AssertionResult IsNotSubstring(const char* needle_expr, + const char* haystack_expr, + const ::std::string& needle, + const ::std::string& haystack); #if GTEST_HAS_STD_WSTRING -GTEST_API_ AssertionResult IsSubstring( - const char* needle_expr, const char* haystack_expr, - const ::std::wstring& needle, const ::std::wstring& haystack); -GTEST_API_ AssertionResult IsNotSubstring( - const char* needle_expr, const char* haystack_expr, - const ::std::wstring& needle, const ::std::wstring& haystack); +GTEST_API_ AssertionResult IsSubstring(const char* needle_expr, + const char* haystack_expr, + const ::std::wstring& needle, + const ::std::wstring& haystack); +GTEST_API_ AssertionResult IsNotSubstring(const char* needle_expr, + const char* haystack_expr, + const ::std::wstring& needle, + const ::std::wstring& haystack); #endif // GTEST_HAS_STD_WSTRING namespace internal { @@ -1553,8 +1539,7 @@ namespace internal { template <typename RawType> AssertionResult CmpHelperFloatingPointEQ(const char* lhs_expression, const char* rhs_expression, - RawType lhs_value, - RawType rhs_value) { + RawType lhs_value, RawType rhs_value) { const FloatingPoint<RawType> lhs(lhs_value), rhs(rhs_value); if (lhs.AlmostEquals(rhs)) { @@ -1569,10 +1554,8 @@ AssertionResult CmpHelperFloatingPointEQ(const char* lhs_expression, rhs_ss << std::setprecision(std::numeric_limits<RawType>::digits10 + 2) << rhs_value; - return EqFailure(lhs_expression, - rhs_expression, - StringStreamToString(&lhs_ss), - StringStreamToString(&rhs_ss), + return EqFailure(lhs_expression, rhs_expression, + StringStreamToString(&lhs_ss), StringStreamToString(&rhs_ss), false); } @@ -1582,8 +1565,7 @@ AssertionResult CmpHelperFloatingPointEQ(const char* lhs_expression, GTEST_API_ AssertionResult DoubleNearPredFormat(const char* expr1, const char* expr2, const char* abs_error_expr, - double val1, - double val2, + double val1, double val2, double abs_error); // INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE. @@ -1591,9 +1573,7 @@ GTEST_API_ AssertionResult DoubleNearPredFormat(const char* expr1, class GTEST_API_ AssertHelper { public: // Constructor. - AssertHelper(TestPartResult::Type type, - const char* file, - int line, + AssertHelper(TestPartResult::Type type, const char* file, int line, const char* message); ~AssertHelper(); @@ -1607,11 +1587,9 @@ class GTEST_API_ AssertHelper { // re-using stack space even for temporary variables, so every EXPECT_EQ // reserves stack space for another AssertHelper. struct AssertHelperData { - AssertHelperData(TestPartResult::Type t, - const char* srcfile, - int line_num, + AssertHelperData(TestPartResult::Type t, const char* srcfile, int line_num, const char* msg) - : type(t), file(srcfile), line(line_num), message(msg) { } + : type(t), file(srcfile), line(line_num), message(msg) {} TestPartResult::Type const type; const char* const file; @@ -1681,15 +1659,14 @@ class WithParamInterface { private: // Sets parameter value. The caller is responsible for making sure the value // remains alive and unchanged throughout the current test. - static void SetParam(const ParamType* parameter) { - parameter_ = parameter; - } + static void SetParam(const ParamType* parameter) { parameter_ = parameter; } // Static value used for accessing parameter during a test lifetime. static const ParamType* parameter_; // TestClass must be a subclass of WithParamInterface<T> and Test. - template <class TestClass> friend class internal::ParameterizedTestFactory; + template <class TestClass> + friend class internal::ParameterizedTestFactory; }; template <typename T> @@ -1699,8 +1676,7 @@ const T* WithParamInterface<T>::parameter_ = nullptr; // WithParamInterface, and can just inherit from ::testing::TestWithParam. template <typename T> -class TestWithParam : public Test, public WithParamInterface<T> { -}; +class TestWithParam : public Test, public WithParamInterface<T> {}; // Macros for indicating success/failure in test code. @@ -1731,7 +1707,7 @@ class TestWithParam : public Test, public WithParamInterface<T> { // Generates a nonfatal failure at the given source file location with // a generic message. -#define ADD_FAILURE_AT(file, line) \ +#define ADD_FAILURE_AT(file, line) \ GTEST_MESSAGE_AT_(file, line, "Failed", \ ::testing::TestPartResult::kNonFatalFailure) @@ -1746,7 +1722,7 @@ class TestWithParam : public Test, public WithParamInterface<T> { // Define this macro to 1 to omit the definition of FAIL(), which is a // generic name and clashes with some other libraries. #if !GTEST_DONT_DEFINE_FAIL -# define FAIL() GTEST_FAIL() +#define FAIL() GTEST_FAIL() #endif // Generates a success with a generic message. @@ -1755,7 +1731,7 @@ class TestWithParam : public Test, public WithParamInterface<T> { // Define this macro to 1 to omit the definition of SUCCEED(), which // is a generic name and clashes with some other libraries. #if !GTEST_DONT_DEFINE_SUCCEED -# define SUCCEED() GTEST_SUCCEED() +#define SUCCEED() GTEST_SUCCEED() #endif // Macros for testing exceptions. @@ -1783,16 +1759,15 @@ class TestWithParam : public Test, public WithParamInterface<T> { // Boolean assertions. Condition can be either a Boolean expression or an // AssertionResult. For more information on how to use AssertionResult with // these macros see comments on that class. -#define GTEST_EXPECT_TRUE(condition) \ +#define GTEST_EXPECT_TRUE(condition) \ GTEST_TEST_BOOLEAN_(condition, #condition, false, true, \ GTEST_NONFATAL_FAILURE_) -#define GTEST_EXPECT_FALSE(condition) \ +#define GTEST_EXPECT_FALSE(condition) \ GTEST_TEST_BOOLEAN_(!(condition), #condition, true, false, \ GTEST_NONFATAL_FAILURE_) #define GTEST_ASSERT_TRUE(condition) \ - GTEST_TEST_BOOLEAN_(condition, #condition, false, true, \ - GTEST_FATAL_FAILURE_) -#define GTEST_ASSERT_FALSE(condition) \ + GTEST_TEST_BOOLEAN_(condition, #condition, false, true, GTEST_FATAL_FAILURE_) +#define GTEST_ASSERT_FALSE(condition) \ GTEST_TEST_BOOLEAN_(!(condition), #condition, true, false, \ GTEST_FATAL_FAILURE_) @@ -1891,27 +1866,27 @@ class TestWithParam : public Test, public WithParamInterface<T> { // ASSERT_XY(), which clashes with some users' own code. #if !GTEST_DONT_DEFINE_ASSERT_EQ -# define ASSERT_EQ(val1, val2) GTEST_ASSERT_EQ(val1, val2) +#define ASSERT_EQ(val1, val2) GTEST_ASSERT_EQ(val1, val2) #endif #if !GTEST_DONT_DEFINE_ASSERT_NE -# define ASSERT_NE(val1, val2) GTEST_ASSERT_NE(val1, val2) +#define ASSERT_NE(val1, val2) GTEST_ASSERT_NE(val1, val2) #endif #if !GTEST_DONT_DEFINE_ASSERT_LE -# define ASSERT_LE(val1, val2) GTEST_ASSERT_LE(val1, val2) +#define ASSERT_LE(val1, val2) GTEST_ASSERT_LE(val1, val2) #endif #if !GTEST_DONT_DEFINE_ASSERT_LT -# define ASSERT_LT(val1, val2) GTEST_ASSERT_LT(val1, val2) +#define ASSERT_LT(val1, val2) GTEST_ASSERT_LT(val1, val2) #endif #if !GTEST_DONT_DEFINE_ASSERT_GE -# define ASSERT_GE(val1, val2) GTEST_ASSERT_GE(val1, val2) +#define ASSERT_GE(val1, val2) GTEST_ASSERT_GE(val1, val2) #endif #if !GTEST_DONT_DEFINE_ASSERT_GT -# define ASSERT_GT(val1, val2) GTEST_ASSERT_GT(val1, val2) +#define ASSERT_GT(val1, val2) GTEST_ASSERT_GT(val1, val2) #endif // C-string Comparisons. All tests treat NULL and any non-NULL string @@ -1936,7 +1911,7 @@ class TestWithParam : public Test, public WithParamInterface<T> { EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperSTRNE, s1, s2) #define EXPECT_STRCASEEQ(s1, s2) \ EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperSTRCASEEQ, s1, s2) -#define EXPECT_STRCASENE(s1, s2)\ +#define EXPECT_STRCASENE(s1, s2) \ EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperSTRCASENE, s1, s2) #define ASSERT_STREQ(s1, s2) \ @@ -1945,7 +1920,7 @@ class TestWithParam : public Test, public WithParamInterface<T> { ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperSTRNE, s1, s2) #define ASSERT_STRCASEEQ(s1, s2) \ ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperSTRCASEEQ, s1, s2) -#define ASSERT_STRCASENE(s1, s2)\ +#define ASSERT_STRCASENE(s1, s2) \ ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperSTRCASENE, s1, s2) // Macros for comparing floating-point numbers. @@ -1962,29 +1937,29 @@ class TestWithParam : public Test, public WithParamInterface<T> { // FloatingPoint template class in gtest-internal.h if you are // interested in the implementation details. -#define EXPECT_FLOAT_EQ(val1, val2)\ +#define EXPECT_FLOAT_EQ(val1, val2) \ EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperFloatingPointEQ<float>, \ val1, val2) -#define EXPECT_DOUBLE_EQ(val1, val2)\ +#define EXPECT_DOUBLE_EQ(val1, val2) \ EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperFloatingPointEQ<double>, \ val1, val2) -#define ASSERT_FLOAT_EQ(val1, val2)\ +#define ASSERT_FLOAT_EQ(val1, val2) \ ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperFloatingPointEQ<float>, \ val1, val2) -#define ASSERT_DOUBLE_EQ(val1, val2)\ +#define ASSERT_DOUBLE_EQ(val1, val2) \ ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperFloatingPointEQ<double>, \ val1, val2) -#define EXPECT_NEAR(val1, val2, abs_error)\ - EXPECT_PRED_FORMAT3(::testing::internal::DoubleNearPredFormat, \ - val1, val2, abs_error) +#define EXPECT_NEAR(val1, val2, abs_error) \ + EXPECT_PRED_FORMAT3(::testing::internal::DoubleNearPredFormat, val1, val2, \ + abs_error) -#define ASSERT_NEAR(val1, val2, abs_error)\ - ASSERT_PRED_FORMAT3(::testing::internal::DoubleNearPredFormat, \ - val1, val2, abs_error) +#define ASSERT_NEAR(val1, val2, abs_error) \ + ASSERT_PRED_FORMAT3(::testing::internal::DoubleNearPredFormat, val1, val2, \ + abs_error) // These predicate format functions work on floating-point values, and // can be used in {ASSERT|EXPECT}_PRED_FORMAT2*(), e.g. @@ -1998,7 +1973,6 @@ GTEST_API_ AssertionResult FloatLE(const char* expr1, const char* expr2, GTEST_API_ AssertionResult DoubleLE(const char* expr1, const char* expr2, double val1, double val2); - #if GTEST_OS_WINDOWS // Macros that test for HRESULT failure and success, these are only useful @@ -2010,17 +1984,17 @@ GTEST_API_ AssertionResult DoubleLE(const char* expr1, const char* expr2, // expected result and the actual result with both a human-readable // string representation of the error, if available, as well as the // hex result code. -# define EXPECT_HRESULT_SUCCEEDED(expr) \ - EXPECT_PRED_FORMAT1(::testing::internal::IsHRESULTSuccess, (expr)) +#define EXPECT_HRESULT_SUCCEEDED(expr) \ + EXPECT_PRED_FORMAT1(::testing::internal::IsHRESULTSuccess, (expr)) -# define ASSERT_HRESULT_SUCCEEDED(expr) \ - ASSERT_PRED_FORMAT1(::testing::internal::IsHRESULTSuccess, (expr)) +#define ASSERT_HRESULT_SUCCEEDED(expr) \ + ASSERT_PRED_FORMAT1(::testing::internal::IsHRESULTSuccess, (expr)) -# define EXPECT_HRESULT_FAILED(expr) \ - EXPECT_PRED_FORMAT1(::testing::internal::IsHRESULTFailure, (expr)) +#define EXPECT_HRESULT_FAILED(expr) \ + EXPECT_PRED_FORMAT1(::testing::internal::IsHRESULTFailure, (expr)) -# define ASSERT_HRESULT_FAILED(expr) \ - ASSERT_PRED_FORMAT1(::testing::internal::IsHRESULTFailure, (expr)) +#define ASSERT_HRESULT_FAILED(expr) \ + ASSERT_PRED_FORMAT1(::testing::internal::IsHRESULTFailure, (expr)) #endif // GTEST_OS_WINDOWS @@ -2035,9 +2009,9 @@ GTEST_API_ AssertionResult DoubleLE(const char* expr1, const char* expr2, // ASSERT_NO_FATAL_FAILURE(Process()) << "Process() failed"; // #define ASSERT_NO_FATAL_FAILURE(statement) \ - GTEST_TEST_NO_FATAL_FAILURE_(statement, GTEST_FATAL_FAILURE_) + GTEST_TEST_NO_FATAL_FAILURE_(statement, GTEST_FATAL_FAILURE_) #define EXPECT_NO_FATAL_FAILURE(statement) \ - GTEST_TEST_NO_FATAL_FAILURE_(statement, GTEST_NONFATAL_FAILURE_) + GTEST_TEST_NO_FATAL_FAILURE_(statement, GTEST_NONFATAL_FAILURE_) // Causes a trace (including the given source file path and line number, // and the given message) to be included in every test failure message generated @@ -2099,9 +2073,9 @@ class GTEST_API_ ScopedTrace { // Assuming that each thread maintains its own stack of traces. // Therefore, a SCOPED_TRACE() would (correctly) only affect the // assertions in its own thread. -#define SCOPED_TRACE(message) \ - ::testing::ScopedTrace GTEST_CONCAT_TOKEN_(gtest_trace_, __LINE__)(\ - __FILE__, __LINE__, (message)) +#define SCOPED_TRACE(message) \ + ::testing::ScopedTrace GTEST_CONCAT_TOKEN_(gtest_trace_, __LINE__)( \ + __FILE__, __LINE__, (message)) // Compile-time assertion for type equality. // StaticAssertTypeEq<type1, type2>() compiles if and only if type1 and type2 @@ -2199,7 +2173,7 @@ constexpr bool StaticAssertTypeEq() noexcept { // EXPECT_EQ(a_.size(), 0); // EXPECT_EQ(b_.size(), 1); // } -#define GTEST_TEST_F(test_fixture, test_name)\ +#define GTEST_TEST_F(test_fixture, test_name) \ GTEST_TEST_(test_fixture, test_name, test_fixture, \ ::testing::internal::GetTypeId<test_fixture>()) #if !GTEST_DONT_DEFINE_TEST_F @@ -2211,7 +2185,7 @@ constexpr bool StaticAssertTypeEq() noexcept { GTEST_API_ std::string TempDir(); #ifdef _MSC_VER -# pragma warning(pop) +#pragma warning(pop) #endif // Dynamically registers a test with the framework. @@ -2307,9 +2281,7 @@ TestInfo* RegisterTest(const char* test_suite_name, const char* test_name, // namespace and has an all-caps name. int RUN_ALL_TESTS() GTEST_MUST_USE_RESULT_; -inline int RUN_ALL_TESTS() { - return ::testing::UnitTest::GetInstance()->Run(); -} +inline int RUN_ALL_TESTS() { return ::testing::UnitTest::GetInstance()->Run(); } GTEST_DISABLE_MSC_WARNINGS_POP_() // 4251 diff --git a/googletest/include/gtest/gtest_pred_impl.h b/googletest/include/gtest/gtest_pred_impl.h index 68b7c50..47a24aa 100644 --- a/googletest/include/gtest/gtest_pred_impl.h +++ b/googletest/include/gtest/gtest_pred_impl.h @@ -74,22 +74,18 @@ namespace testing { // GTEST_ASSERT_ is the basic statement to which all of the assertions // in this file reduce. Don't use this in your code. -#define GTEST_ASSERT_(expression, on_failure) \ - GTEST_AMBIGUOUS_ELSE_BLOCKER_ \ +#define GTEST_ASSERT_(expression, on_failure) \ + GTEST_AMBIGUOUS_ELSE_BLOCKER_ \ if (const ::testing::AssertionResult gtest_ar = (expression)) \ - ; \ - else \ + ; \ + else \ on_failure(gtest_ar.failure_message()) - // Helper function for implementing {EXPECT|ASSERT}_PRED1. Don't use // this in your code. -template <typename Pred, - typename T1> -AssertionResult AssertPred1Helper(const char* pred_text, - const char* e1, - Pred pred, - const T1& v1) { +template <typename Pred, typename T1> +AssertionResult AssertPred1Helper(const char* pred_text, const char* e1, + Pred pred, const T1& v1) { if (pred(v1)) return AssertionSuccess(); return AssertionFailure() @@ -100,40 +96,27 @@ AssertionResult AssertPred1Helper(const char* pred_text, // Internal macro for implementing {EXPECT|ASSERT}_PRED_FORMAT1. // Don't use this in your code. -#define GTEST_PRED_FORMAT1_(pred_format, v1, on_failure)\ - GTEST_ASSERT_(pred_format(#v1, v1), \ - on_failure) +#define GTEST_PRED_FORMAT1_(pred_format, v1, on_failure) \ + GTEST_ASSERT_(pred_format(#v1, v1), on_failure) // Internal macro for implementing {EXPECT|ASSERT}_PRED1. Don't use // this in your code. -#define GTEST_PRED1_(pred, v1, on_failure)\ - GTEST_ASSERT_(::testing::AssertPred1Helper(#pred, \ - #v1, \ - pred, \ - v1), on_failure) +#define GTEST_PRED1_(pred, v1, on_failure) \ + GTEST_ASSERT_(::testing::AssertPred1Helper(#pred, #v1, pred, v1), on_failure) // Unary predicate assertion macros. #define EXPECT_PRED_FORMAT1(pred_format, v1) \ GTEST_PRED_FORMAT1_(pred_format, v1, GTEST_NONFATAL_FAILURE_) -#define EXPECT_PRED1(pred, v1) \ - GTEST_PRED1_(pred, v1, GTEST_NONFATAL_FAILURE_) +#define EXPECT_PRED1(pred, v1) GTEST_PRED1_(pred, v1, GTEST_NONFATAL_FAILURE_) #define ASSERT_PRED_FORMAT1(pred_format, v1) \ GTEST_PRED_FORMAT1_(pred_format, v1, GTEST_FATAL_FAILURE_) -#define ASSERT_PRED1(pred, v1) \ - GTEST_PRED1_(pred, v1, GTEST_FATAL_FAILURE_) - - +#define ASSERT_PRED1(pred, v1) GTEST_PRED1_(pred, v1, GTEST_FATAL_FAILURE_) // Helper function for implementing {EXPECT|ASSERT}_PRED2. Don't use // this in your code. -template <typename Pred, - typename T1, - typename T2> -AssertionResult AssertPred2Helper(const char* pred_text, - const char* e1, - const char* e2, - Pred pred, - const T1& v1, +template <typename Pred, typename T1, typename T2> +AssertionResult AssertPred2Helper(const char* pred_text, const char* e1, + const char* e2, Pred pred, const T1& v1, const T2& v2) { if (pred(v1, v2)) return AssertionSuccess(); @@ -147,19 +130,14 @@ AssertionResult AssertPred2Helper(const char* pred_text, // Internal macro for implementing {EXPECT|ASSERT}_PRED_FORMAT2. // Don't use this in your code. -#define GTEST_PRED_FORMAT2_(pred_format, v1, v2, on_failure)\ - GTEST_ASSERT_(pred_format(#v1, #v2, v1, v2), \ - on_failure) +#define GTEST_PRED_FORMAT2_(pred_format, v1, v2, on_failure) \ + GTEST_ASSERT_(pred_format(#v1, #v2, v1, v2), on_failure) // Internal macro for implementing {EXPECT|ASSERT}_PRED2. Don't use // this in your code. -#define GTEST_PRED2_(pred, v1, v2, on_failure)\ - GTEST_ASSERT_(::testing::AssertPred2Helper(#pred, \ - #v1, \ - #v2, \ - pred, \ - v1, \ - v2), on_failure) +#define GTEST_PRED2_(pred, v1, v2, on_failure) \ + GTEST_ASSERT_(::testing::AssertPred2Helper(#pred, #v1, #v2, pred, v1, v2), \ + on_failure) // Binary predicate assertion macros. #define EXPECT_PRED_FORMAT2(pred_format, v1, v2) \ @@ -171,22 +149,12 @@ AssertionResult AssertPred2Helper(const char* pred_text, #define ASSERT_PRED2(pred, v1, v2) \ GTEST_PRED2_(pred, v1, v2, GTEST_FATAL_FAILURE_) - - // Helper function for implementing {EXPECT|ASSERT}_PRED3. Don't use // this in your code. -template <typename Pred, - typename T1, - typename T2, - typename T3> -AssertionResult AssertPred3Helper(const char* pred_text, - const char* e1, - const char* e2, - const char* e3, - Pred pred, - const T1& v1, - const T2& v2, - const T3& v3) { +template <typename Pred, typename T1, typename T2, typename T3> +AssertionResult AssertPred3Helper(const char* pred_text, const char* e1, + const char* e2, const char* e3, Pred pred, + const T1& v1, const T2& v2, const T3& v3) { if (pred(v1, v2, v3)) return AssertionSuccess(); return AssertionFailure() @@ -200,21 +168,15 @@ AssertionResult AssertPred3Helper(const char* pred_text, // Internal macro for implementing {EXPECT|ASSERT}_PRED_FORMAT3. // Don't use this in your code. -#define GTEST_PRED_FORMAT3_(pred_format, v1, v2, v3, on_failure)\ - GTEST_ASSERT_(pred_format(#v1, #v2, #v3, v1, v2, v3), \ - on_failure) +#define GTEST_PRED_FORMAT3_(pred_format, v1, v2, v3, on_failure) \ + GTEST_ASSERT_(pred_format(#v1, #v2, #v3, v1, v2, v3), on_failure) // Internal macro for implementing {EXPECT|ASSERT}_PRED3. Don't use // this in your code. -#define GTEST_PRED3_(pred, v1, v2, v3, on_failure)\ - GTEST_ASSERT_(::testing::AssertPred3Helper(#pred, \ - #v1, \ - #v2, \ - #v3, \ - pred, \ - v1, \ - v2, \ - v3), on_failure) +#define GTEST_PRED3_(pred, v1, v2, v3, on_failure) \ + GTEST_ASSERT_( \ + ::testing::AssertPred3Helper(#pred, #v1, #v2, #v3, pred, v1, v2, v3), \ + on_failure) // Ternary predicate assertion macros. #define EXPECT_PRED_FORMAT3(pred_format, v1, v2, v3) \ @@ -226,25 +188,13 @@ AssertionResult AssertPred3Helper(const char* pred_text, #define ASSERT_PRED3(pred, v1, v2, v3) \ GTEST_PRED3_(pred, v1, v2, v3, GTEST_FATAL_FAILURE_) - - // Helper function for implementing {EXPECT|ASSERT}_PRED4. Don't use // this in your code. -template <typename Pred, - typename T1, - typename T2, - typename T3, - typename T4> -AssertionResult AssertPred4Helper(const char* pred_text, - const char* e1, - const char* e2, - const char* e3, - const char* e4, - Pred pred, - const T1& v1, - const T2& v2, - const T3& v3, - const T4& v4) { +template <typename Pred, typename T1, typename T2, typename T3, typename T4> +AssertionResult AssertPred4Helper(const char* pred_text, const char* e1, + const char* e2, const char* e3, + const char* e4, Pred pred, const T1& v1, + const T2& v2, const T3& v3, const T4& v4) { if (pred(v1, v2, v3, v4)) return AssertionSuccess(); return AssertionFailure() @@ -259,23 +209,15 @@ AssertionResult AssertPred4Helper(const char* pred_text, // Internal macro for implementing {EXPECT|ASSERT}_PRED_FORMAT4. // Don't use this in your code. -#define GTEST_PRED_FORMAT4_(pred_format, v1, v2, v3, v4, on_failure)\ - GTEST_ASSERT_(pred_format(#v1, #v2, #v3, #v4, v1, v2, v3, v4), \ - on_failure) +#define GTEST_PRED_FORMAT4_(pred_format, v1, v2, v3, v4, on_failure) \ + GTEST_ASSERT_(pred_format(#v1, #v2, #v3, #v4, v1, v2, v3, v4), on_failure) // Internal macro for implementing {EXPECT|ASSERT}_PRED4. Don't use // this in your code. -#define GTEST_PRED4_(pred, v1, v2, v3, v4, on_failure)\ - GTEST_ASSERT_(::testing::AssertPred4Helper(#pred, \ - #v1, \ - #v2, \ - #v3, \ - #v4, \ - pred, \ - v1, \ - v2, \ - v3, \ - v4), on_failure) +#define GTEST_PRED4_(pred, v1, v2, v3, v4, on_failure) \ + GTEST_ASSERT_(::testing::AssertPred4Helper(#pred, #v1, #v2, #v3, #v4, pred, \ + v1, v2, v3, v4), \ + on_failure) // 4-ary predicate assertion macros. #define EXPECT_PRED_FORMAT4(pred_format, v1, v2, v3, v4) \ @@ -287,28 +229,15 @@ AssertionResult AssertPred4Helper(const char* pred_text, #define ASSERT_PRED4(pred, v1, v2, v3, v4) \ GTEST_PRED4_(pred, v1, v2, v3, v4, GTEST_FATAL_FAILURE_) - - // Helper function for implementing {EXPECT|ASSERT}_PRED5. Don't use // this in your code. -template <typename Pred, - typename T1, - typename T2, - typename T3, - typename T4, +template <typename Pred, typename T1, typename T2, typename T3, typename T4, typename T5> -AssertionResult AssertPred5Helper(const char* pred_text, - const char* e1, - const char* e2, - const char* e3, - const char* e4, - const char* e5, - Pred pred, - const T1& v1, - const T2& v2, - const T3& v3, - const T4& v4, - const T5& v5) { +AssertionResult AssertPred5Helper(const char* pred_text, const char* e1, + const char* e2, const char* e3, + const char* e4, const char* e5, Pred pred, + const T1& v1, const T2& v2, const T3& v3, + const T4& v4, const T5& v5) { if (pred(v1, v2, v3, v4, v5)) return AssertionSuccess(); return AssertionFailure() @@ -324,25 +253,16 @@ AssertionResult AssertPred5Helper(const char* pred_text, // Internal macro for implementing {EXPECT|ASSERT}_PRED_FORMAT5. // Don't use this in your code. -#define GTEST_PRED_FORMAT5_(pred_format, v1, v2, v3, v4, v5, on_failure)\ +#define GTEST_PRED_FORMAT5_(pred_format, v1, v2, v3, v4, v5, on_failure) \ GTEST_ASSERT_(pred_format(#v1, #v2, #v3, #v4, #v5, v1, v2, v3, v4, v5), \ on_failure) // Internal macro for implementing {EXPECT|ASSERT}_PRED5. Don't use // this in your code. -#define GTEST_PRED5_(pred, v1, v2, v3, v4, v5, on_failure)\ - GTEST_ASSERT_(::testing::AssertPred5Helper(#pred, \ - #v1, \ - #v2, \ - #v3, \ - #v4, \ - #v5, \ - pred, \ - v1, \ - v2, \ - v3, \ - v4, \ - v5), on_failure) +#define GTEST_PRED5_(pred, v1, v2, v3, v4, v5, on_failure) \ + GTEST_ASSERT_(::testing::AssertPred5Helper(#pred, #v1, #v2, #v3, #v4, #v5, \ + pred, v1, v2, v3, v4, v5), \ + on_failure) // 5-ary predicate assertion macros. #define EXPECT_PRED_FORMAT5(pred_format, v1, v2, v3, v4, v5) \ @@ -354,8 +274,6 @@ AssertionResult AssertPred5Helper(const char* pred_text, #define ASSERT_PRED5(pred, v1, v2, v3, v4, v5) \ GTEST_PRED5_(pred, v1, v2, v3, v4, v5, GTEST_FATAL_FAILURE_) - - } // namespace testing #endif // GOOGLETEST_INCLUDE_GTEST_GTEST_PRED_IMPL_H_ diff --git a/googletest/include/gtest/gtest_prod.h b/googletest/include/gtest/gtest_prod.h index b22030a..1f37dc3 100644 --- a/googletest/include/gtest/gtest_prod.h +++ b/googletest/include/gtest/gtest_prod.h @@ -54,7 +54,7 @@ // Note: The test class must be in the same namespace as the class being tested. // For example, putting MyClassTest in an anonymous namespace will not work. -#define FRIEND_TEST(test_case_name, test_name)\ -friend class test_case_name##_##test_name##_Test +#define FRIEND_TEST(test_case_name, test_name) \ + friend class test_case_name##_##test_name##_Test #endif // GOOGLETEST_INCLUDE_GTEST_GTEST_PROD_H_ diff --git a/googletest/include/gtest/internal/gtest-death-test-internal.h b/googletest/include/gtest/internal/gtest-death-test-internal.h index 128e0f4..b9315c8 100644 --- a/googletest/include/gtest/internal/gtest-death-test-internal.h +++ b/googletest/include/gtest/internal/gtest-death-test-internal.h @@ -39,12 +39,13 @@ #ifndef GOOGLETEST_INCLUDE_GTEST_INTERNAL_GTEST_DEATH_TEST_INTERNAL_H_ #define GOOGLETEST_INCLUDE_GTEST_INTERNAL_GTEST_DEATH_TEST_INTERNAL_H_ -#include "gtest/gtest-matchers.h" -#include "gtest/internal/gtest-internal.h" - #include <stdio.h> + #include <memory> +#include "gtest/gtest-matchers.h" +#include "gtest/internal/gtest-internal.h" + GTEST_DECLARE_string_(internal_run_death_test); namespace testing { @@ -86,13 +87,14 @@ class GTEST_API_ DeathTest { static bool Create(const char* statement, Matcher<const std::string&> matcher, const char* file, int line, DeathTest** test); DeathTest(); - virtual ~DeathTest() { } + virtual ~DeathTest() {} // A helper class that aborts a death test when it's deleted. class ReturnSentinel { public: - explicit ReturnSentinel(DeathTest* test) : test_(test) { } + explicit ReturnSentinel(DeathTest* test) : test_(test) {} ~ReturnSentinel() { test_->Abort(TEST_ENCOUNTERED_RETURN_STATEMENT); } + private: DeathTest* const test_; GTEST_DISALLOW_COPY_AND_ASSIGN_(ReturnSentinel); @@ -148,7 +150,7 @@ GTEST_DISABLE_MSC_WARNINGS_POP_() // 4251 // Factory interface for death tests. May be mocked out for testing. class DeathTestFactory { public: - virtual ~DeathTestFactory() { } + virtual ~DeathTestFactory() {} virtual bool Create(const char* statement, Matcher<const std::string&> matcher, const char* file, int line, DeathTest** test) = 0; @@ -189,28 +191,28 @@ inline Matcher<const ::std::string&> MakeDeathTestMatcher( // Traps C++ exceptions escaping statement and reports them as test // failures. Note that trapping SEH exceptions is not implemented here. -# if GTEST_HAS_EXCEPTIONS -# define GTEST_EXECUTE_DEATH_TEST_STATEMENT_(statement, death_test) \ - try { \ - GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement); \ - } catch (const ::std::exception& gtest_exception) { \ - fprintf(\ - stderr, \ - "\n%s: Caught std::exception-derived exception escaping the " \ - "death test statement. Exception message: %s\n", \ +#if GTEST_HAS_EXCEPTIONS +#define GTEST_EXECUTE_DEATH_TEST_STATEMENT_(statement, death_test) \ + try { \ + GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement); \ + } catch (const ::std::exception& gtest_exception) { \ + fprintf( \ + stderr, \ + "\n%s: Caught std::exception-derived exception escaping the " \ + "death test statement. Exception message: %s\n", \ ::testing::internal::FormatFileLocation(__FILE__, __LINE__).c_str(), \ - gtest_exception.what()); \ - fflush(stderr); \ + gtest_exception.what()); \ + fflush(stderr); \ death_test->Abort(::testing::internal::DeathTest::TEST_THREW_EXCEPTION); \ - } catch (...) { \ + } catch (...) { \ death_test->Abort(::testing::internal::DeathTest::TEST_THREW_EXCEPTION); \ } -# else -# define GTEST_EXECUTE_DEATH_TEST_STATEMENT_(statement, death_test) \ +#else +#define GTEST_EXECUTE_DEATH_TEST_STATEMENT_(statement, death_test) \ GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement) -# endif +#endif // This macro is for implementing ASSERT_DEATH*, EXPECT_DEATH*, // ASSERT_EXIT*, and EXPECT_EXIT*. @@ -266,16 +268,12 @@ inline Matcher<const ::std::string&> MakeDeathTestMatcher( // RUN_ALL_TESTS was called. class InternalRunDeathTestFlag { public: - InternalRunDeathTestFlag(const std::string& a_file, - int a_line, - int an_index, + InternalRunDeathTestFlag(const std::string& a_file, int a_line, int an_index, int a_write_fd) - : file_(a_file), line_(a_line), index_(an_index), - write_fd_(a_write_fd) {} + : file_(a_file), line_(a_line), index_(an_index), write_fd_(a_write_fd) {} ~InternalRunDeathTestFlag() { - if (write_fd_ >= 0) - posix::Close(write_fd_); + if (write_fd_ >= 0) posix::Close(write_fd_); } const std::string& file() const { return file_; } diff --git a/googletest/include/gtest/internal/gtest-filepath.h b/googletest/include/gtest/internal/gtest-filepath.h index 4dfe2e2..a2a60a9 100644 --- a/googletest/include/gtest/internal/gtest-filepath.h +++ b/googletest/include/gtest/internal/gtest-filepath.h @@ -63,8 +63,8 @@ namespace internal { class GTEST_API_ FilePath { public: - FilePath() : pathname_("") { } - FilePath(const FilePath& rhs) : pathname_(rhs.pathname_) { } + FilePath() : pathname_("") {} + FilePath(const FilePath& rhs) : pathname_(rhs.pathname_) {} explicit FilePath(const std::string& pathname) : pathname_(pathname) { Normalize(); @@ -75,9 +75,7 @@ class GTEST_API_ FilePath { return *this; } - void Set(const FilePath& rhs) { - pathname_ = rhs.pathname_; - } + void Set(const FilePath& rhs) { pathname_ = rhs.pathname_; } const std::string& string() const { return pathname_; } const char* c_str() const { return pathname_.c_str(); } @@ -90,8 +88,7 @@ class GTEST_API_ FilePath { // than zero (e.g., 12), returns "dir/test_12.xml". // On Windows platform, uses \ as the separator rather than /. static FilePath MakeFileName(const FilePath& directory, - const FilePath& base_name, - int number, + const FilePath& base_name, int number, const char* extension); // Given directory = "dir", relative_path = "test.xml", diff --git a/googletest/include/gtest/internal/gtest-internal.h b/googletest/include/gtest/internal/gtest-internal.h index fc15e94..3ac39cd 100644 --- a/googletest/include/gtest/internal/gtest-internal.h +++ b/googletest/include/gtest/internal/gtest-internal.h @@ -42,19 +42,20 @@ #include "gtest/internal/gtest-port.h" #if GTEST_OS_LINUX -# include <stdlib.h> -# include <sys/types.h> -# include <sys/wait.h> -# include <unistd.h> +#include <stdlib.h> +#include <sys/types.h> +#include <sys/wait.h> +#include <unistd.h> #endif // GTEST_OS_LINUX #if GTEST_HAS_EXCEPTIONS -# include <stdexcept> +#include <stdexcept> #endif #include <ctype.h> #include <float.h> #include <string.h> + #include <cstdint> #include <iomanip> #include <limits> @@ -78,7 +79,7 @@ // the current line number. For more details, see // http://www.parashift.com/c++-faq-lite/misc-technical-issues.html#faq-39.6 #define GTEST_CONCAT_TOKEN_(foo, bar) GTEST_CONCAT_TOKEN_IMPL_(foo, bar) -#define GTEST_CONCAT_TOKEN_IMPL_(foo, bar) foo ## bar +#define GTEST_CONCAT_TOKEN_IMPL_(foo, bar) foo##bar // Stringifies its argument. // Work around a bug in visual studio which doesn't accept code like this: @@ -100,21 +101,21 @@ namespace testing { // Forward declarations. -class AssertionResult; // Result of an assertion. -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 suites. +class AssertionResult; // Result of an assertion. +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 suites. template <typename T> ::std::string PrintToString(const T& value); namespace internal { -struct TraceInfo; // Information about a trace point. -class TestInfoImpl; // Opaque implementation of TestInfo -class UnitTestImpl; // Opaque implementation of UnitTest +struct TraceInfo; // Information about a trace point. +class TestInfoImpl; // Opaque implementation of TestInfo +class UnitTestImpl; // Opaque implementation of UnitTest // The text used in failure messages to indicate the start of the // stack trace. @@ -123,6 +124,7 @@ GTEST_API_ extern const char kStackTraceMarker[]; // An IgnoredValue object can be implicitly constructed from ANY value. class IgnoredValue { struct Sink {}; + public: // This constructor template allows any value to be implicitly // converted to IgnoredValue. The object has no data member and @@ -138,13 +140,13 @@ class IgnoredValue { }; // Appends the user-supplied message to the Google-Test-generated message. -GTEST_API_ std::string AppendUserMessage( - const std::string& gtest_msg, const Message& user_msg); +GTEST_API_ std::string AppendUserMessage(const std::string& gtest_msg, + const Message& user_msg); #if GTEST_HAS_EXCEPTIONS -GTEST_DISABLE_MSC_WARNINGS_PUSH_(4275 \ -/* an exported class was derived from a class that was not exported */) +GTEST_DISABLE_MSC_WARNINGS_PUSH_( + 4275 /* an exported class was derived from a class that was not exported */) // This exception is thrown by (and only by) a failed Google Test // assertion when GTEST_FLAG(throw_on_failure) is true (if exceptions @@ -214,10 +216,8 @@ GTEST_API_ AssertionResult EqFailure(const char* expected_expression, // Constructs a failure message for Boolean assertions such as EXPECT_TRUE. GTEST_API_ std::string GetBoolAssertionFailureMessage( - const AssertionResult& assertion_result, - const char* expression_text, - const char* actual_predicate_value, - const char* expected_predicate_value); + const AssertionResult& assertion_result, const char* expression_text, + const char* actual_predicate_value, const char* expected_predicate_value); // This template class represents an IEEE floating-point number // (either single-precision or double-precision, depending on the @@ -258,11 +258,11 @@ class FloatingPoint { // Constants. // # of bits in a number. - static const size_t kBitCount = 8*sizeof(RawType); + static const size_t kBitCount = 8 * sizeof(RawType); // # of fraction bits in a number. static const size_t kFractionBitCount = - std::numeric_limits<RawType>::digits - 1; + std::numeric_limits<RawType>::digits - 1; // # of exponent bits in a number. static const size_t kExponentBitCount = kBitCount - 1 - kFractionBitCount; @@ -271,8 +271,8 @@ class FloatingPoint { static const Bits kSignBitMask = static_cast<Bits>(1) << (kBitCount - 1); // The mask for the fraction bits. - static const Bits kFractionBitMask = - ~static_cast<Bits>(0) >> (kExponentBitCount + 1); + static const Bits kFractionBitMask = ~static_cast<Bits>(0) >> + (kExponentBitCount + 1); // The mask for the exponent bits. static const Bits kExponentBitMask = ~(kSignBitMask | kFractionBitMask); @@ -311,9 +311,7 @@ class FloatingPoint { } // Returns the floating-point number that represent positive infinity. - static RawType Infinity() { - return ReinterpretBits(kExponentBitMask); - } + static RawType Infinity() { return ReinterpretBits(kExponentBitMask); } // Returns the maximum representable finite floating-point number. static RawType Max(); @@ -321,7 +319,7 @@ class FloatingPoint { // Non-static methods // Returns the bits that represents this number. - const Bits &bits() const { return u_.bits_; } + const Bits& bits() const { return u_.bits_; } // Returns the exponent bits of this number. Bits exponent_bits() const { return kExponentBitMask & u_.bits_; } @@ -350,8 +348,8 @@ class FloatingPoint { // a NAN must return false. if (is_nan() || rhs.is_nan()) return false; - return DistanceBetweenSignAndMagnitudeNumbers(u_.bits_, rhs.u_.bits_) - <= kMaxUlps; + return DistanceBetweenSignAndMagnitudeNumbers(u_.bits_, rhs.u_.bits_) <= + kMaxUlps; } private: @@ -376,7 +374,7 @@ class FloatingPoint { // // Read http://en.wikipedia.org/wiki/Signed_number_representations // for more details on signed number representations. - static Bits SignAndMagnitudeToBiased(const Bits &sam) { + static Bits SignAndMagnitudeToBiased(const Bits& sam) { if (kSignBitMask & sam) { // sam represents a negative number. return ~sam + 1; @@ -388,8 +386,8 @@ class FloatingPoint { // Given two numbers in the sign-and-magnitude representation, // returns the distance between them as an unsigned number. - static Bits DistanceBetweenSignAndMagnitudeNumbers(const Bits &sam1, - const Bits &sam2) { + static Bits DistanceBetweenSignAndMagnitudeNumbers(const Bits& sam1, + const Bits& sam2) { const Bits biased1 = SignAndMagnitudeToBiased(sam1); const Bits biased2 = SignAndMagnitudeToBiased(sam2); return (biased1 >= biased2) ? (biased1 - biased2) : (biased2 - biased1); @@ -401,9 +399,13 @@ class FloatingPoint { // We cannot use std::numeric_limits<T>::max() as it clashes with the max() // macro defined by <windows.h>. template <> -inline float FloatingPoint<float>::Max() { return FLT_MAX; } +inline float FloatingPoint<float>::Max() { + return FLT_MAX; +} template <> -inline double FloatingPoint<double>::Max() { return DBL_MAX; } +inline double FloatingPoint<double>::Max() { + return DBL_MAX; +} // Typedefs the instances of the FloatingPoint template class that we // care to use. @@ -656,7 +658,8 @@ inline const char* SkipComma(const char* str) { if (comma == nullptr) { return nullptr; } - while (IsSpace(*(++comma))) {} + while (IsSpace(*(++comma))) { + } return comma; } @@ -670,7 +673,7 @@ inline std::string GetPrefixUntilComma(const char* str) { // Splits a given string on a given delimiter, populating a given // vector with the fields. void SplitString(const ::std::string& str, char delimiter, - ::std::vector< ::std::string>* dest); + ::std::vector<::std::string>* dest); // The default argument to the template below for the case when the user does // not provide a name generator. @@ -783,13 +786,13 @@ class TypeParameterizedTestSuite { const std::vector<std::string>& type_names = GenerateNames<DefaultNameGenerator, Types>()) { RegisterTypeParameterizedTestSuiteInstantiation(case_name); - std::string test_name = StripTrailingSpaces( - GetPrefixUntilComma(test_names)); + std::string test_name = + StripTrailingSpaces(GetPrefixUntilComma(test_names)); if (!state->TestExists(test_name)) { fprintf(stderr, "Failed to get code location for test %s.%s at %s.", case_name, test_name.c_str(), - FormatFileLocation(code_location.file.c_str(), - code_location.line).c_str()); + FormatFileLocation(code_location.file.c_str(), code_location.line) + .c_str()); fflush(stderr); posix::Abort(); } @@ -833,8 +836,8 @@ class TypeParameterizedTestSuite<Fixture, internal::None, Types> { // For example, if Foo() calls Bar(), which in turn calls // GetCurrentOsStackTraceExceptTop(..., 1), Foo() will be included in // the trace but Bar() and GetCurrentOsStackTraceExceptTop() won't. -GTEST_API_ std::string GetCurrentOsStackTraceExceptTop( - UnitTest* unit_test, int skip_count); +GTEST_API_ std::string GetCurrentOsStackTraceExceptTop(UnitTest* unit_test, + int skip_count); // Helpers for suppressing warnings on unreachable code or constant // condition. @@ -956,7 +959,9 @@ IsContainer IsContainerTest(int /* dummy */) { typedef char IsNotContainer; template <class C> -IsNotContainer IsContainerTest(long /* dummy */) { return '\0'; } +IsNotContainer IsContainerTest(long /* dummy */) { + return '\0'; +} // Trait to detect whether a type T is a hash table. // The heuristic used is that the type contains an inner type `hasher` and does @@ -1019,11 +1024,13 @@ bool ArrayEq(const T* lhs, size_t size, const U* rhs); // This generic version is used when k is 0. template <typename T, typename U> -inline bool ArrayEq(const T& lhs, const U& rhs) { return lhs == rhs; } +inline bool ArrayEq(const T& lhs, const U& rhs) { + return lhs == rhs; +} // This overload is used when k >= 1. template <typename T, typename U, size_t N> -inline bool ArrayEq(const T(&lhs)[N], const U(&rhs)[N]) { +inline bool ArrayEq(const T (&lhs)[N], const U (&rhs)[N]) { return internal::ArrayEq(lhs, N, rhs); } @@ -1033,8 +1040,7 @@ inline bool ArrayEq(const T(&lhs)[N], const U(&rhs)[N]) { template <typename T, typename U> bool ArrayEq(const T* lhs, size_t size, const U* rhs) { for (size_t i = 0; i != size; i++) { - if (!internal::ArrayEq(lhs[i], rhs[i])) - return false; + if (!internal::ArrayEq(lhs[i], rhs[i])) return false; } return true; } @@ -1044,8 +1050,7 @@ bool ArrayEq(const T* lhs, size_t size, const U* rhs) { template <typename Iter, typename Element> Iter ArrayAwareFind(Iter begin, Iter end, const Element& elem) { for (Iter it = begin; it != end; ++it) { - if (internal::ArrayEq(*it, elem)) - return it; + if (internal::ArrayEq(*it, elem)) return it; } return end; } @@ -1059,11 +1064,13 @@ void CopyArray(const T* from, size_t size, U* to); // This generic version is used when k is 0. template <typename T, typename U> -inline void CopyArray(const T& from, U* to) { *to = from; } +inline void CopyArray(const T& from, U* to) { + *to = from; +} // This overload is used when k >= 1. template <typename T, typename U, size_t N> -inline void CopyArray(const T(&from)[N], U(*to)[N]) { +inline void CopyArray(const T (&from)[N], U (*to)[N]) { internal::CopyArray(from, N, *to); } @@ -1116,8 +1123,7 @@ class NativeArray { } ~NativeArray() { - if (clone_ != &NativeArray::InitRef) - delete[] array_; + if (clone_ != &NativeArray::InitRef) delete[] array_; } // STL-style container methods. @@ -1125,8 +1131,7 @@ class NativeArray { const_iterator begin() const { return array_; } const_iterator end() const { return array_ + size_; } bool operator==(const NativeArray& rhs) const { - return size() == rhs.size() && - ArrayEq(begin(), size(), rhs.begin()); + return size() == rhs.size() && ArrayEq(begin(), size(), rhs.begin()); } private: @@ -1337,9 +1342,9 @@ struct tuple_size<testing::internal::FlatTuple<Ts...>> #endif } // namespace std -#define GTEST_MESSAGE_AT_(file, line, message, result_type) \ - ::testing::internal::AssertHelper(result_type, file, line, message) \ - = ::testing::Message() +#define GTEST_MESSAGE_AT_(file, line, message, result_type) \ + ::testing::internal::AssertHelper(result_type, file, line, message) = \ + ::testing::Message() #define GTEST_MESSAGE_(message, result_type) \ GTEST_MESSAGE_AT_(__FILE__, __LINE__, message, result_type) @@ -1460,66 +1465,69 @@ class NeverThrown { #endif // GTEST_HAS_EXCEPTIONS -#define GTEST_TEST_NO_THROW_(statement, fail) \ - GTEST_AMBIGUOUS_ELSE_BLOCKER_ \ - if (::testing::internal::TrueWithString gtest_msg{}) { \ - try { \ - GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement); \ - } \ - GTEST_TEST_NO_THROW_CATCH_STD_EXCEPTION_() \ - catch (...) { \ - gtest_msg.value = "it throws."; \ - goto GTEST_CONCAT_TOKEN_(gtest_label_testnothrow_, __LINE__); \ - } \ - } else \ - GTEST_CONCAT_TOKEN_(gtest_label_testnothrow_, __LINE__): \ - fail(("Expected: " #statement " doesn't throw an exception.\n" \ - " Actual: " + gtest_msg.value).c_str()) - -#define GTEST_TEST_ANY_THROW_(statement, fail) \ - GTEST_AMBIGUOUS_ELSE_BLOCKER_ \ - if (::testing::internal::AlwaysTrue()) { \ - bool gtest_caught_any = false; \ - try { \ - GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement); \ - } \ - catch (...) { \ - gtest_caught_any = true; \ - } \ - if (!gtest_caught_any) { \ +#define GTEST_TEST_NO_THROW_(statement, fail) \ + GTEST_AMBIGUOUS_ELSE_BLOCKER_ \ + if (::testing::internal::TrueWithString gtest_msg{}) { \ + try { \ + GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement); \ + } \ + GTEST_TEST_NO_THROW_CATCH_STD_EXCEPTION_() \ + catch (...) { \ + gtest_msg.value = "it throws."; \ + goto GTEST_CONCAT_TOKEN_(gtest_label_testnothrow_, __LINE__); \ + } \ + } else \ + GTEST_CONCAT_TOKEN_(gtest_label_testnothrow_, __LINE__) \ + : fail(("Expected: " #statement " doesn't throw an exception.\n" \ + " Actual: " + \ + gtest_msg.value) \ + .c_str()) + +#define GTEST_TEST_ANY_THROW_(statement, fail) \ + GTEST_AMBIGUOUS_ELSE_BLOCKER_ \ + if (::testing::internal::AlwaysTrue()) { \ + bool gtest_caught_any = false; \ + try { \ + GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement); \ + } catch (...) { \ + gtest_caught_any = true; \ + } \ + if (!gtest_caught_any) { \ goto GTEST_CONCAT_TOKEN_(gtest_label_testanythrow_, __LINE__); \ - } \ - } else \ - GTEST_CONCAT_TOKEN_(gtest_label_testanythrow_, __LINE__): \ - fail("Expected: " #statement " throws an exception.\n" \ - " Actual: it doesn't.") - + } \ + } else \ + GTEST_CONCAT_TOKEN_(gtest_label_testanythrow_, __LINE__) \ + : fail("Expected: " #statement \ + " throws an exception.\n" \ + " Actual: it doesn't.") // Implements Boolean test assertions such as EXPECT_TRUE. expression can be // either a boolean expression or an AssertionResult. text is a textual // representation of expression as it was passed into the EXPECT_TRUE. #define GTEST_TEST_BOOLEAN_(expression, text, actual, expected, fail) \ - GTEST_AMBIGUOUS_ELSE_BLOCKER_ \ - if (const ::testing::AssertionResult gtest_ar_ = \ - ::testing::AssertionResult(expression)) \ - ; \ - else \ - fail(::testing::internal::GetBoolAssertionFailureMessage(\ - gtest_ar_, text, #actual, #expected).c_str()) - -#define GTEST_TEST_NO_FATAL_FAILURE_(statement, fail) \ - GTEST_AMBIGUOUS_ELSE_BLOCKER_ \ - if (::testing::internal::AlwaysTrue()) { \ + GTEST_AMBIGUOUS_ELSE_BLOCKER_ \ + if (const ::testing::AssertionResult gtest_ar_ = \ + ::testing::AssertionResult(expression)) \ + ; \ + else \ + fail(::testing::internal::GetBoolAssertionFailureMessage( \ + gtest_ar_, text, #actual, #expected) \ + .c_str()) + +#define GTEST_TEST_NO_FATAL_FAILURE_(statement, fail) \ + GTEST_AMBIGUOUS_ELSE_BLOCKER_ \ + if (::testing::internal::AlwaysTrue()) { \ ::testing::internal::HasNewFatalFailureHelper gtest_fatal_failure_checker; \ - GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement); \ - if (gtest_fatal_failure_checker.has_new_fatal_failure()) { \ - goto GTEST_CONCAT_TOKEN_(gtest_label_testnofatal_, __LINE__); \ - } \ - } else \ - GTEST_CONCAT_TOKEN_(gtest_label_testnofatal_, __LINE__): \ - fail("Expected: " #statement " doesn't generate new fatal " \ - "failures in the current thread.\n" \ - " Actual: it does.") + GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement); \ + if (gtest_fatal_failure_checker.has_new_fatal_failure()) { \ + goto GTEST_CONCAT_TOKEN_(gtest_label_testnofatal_, __LINE__); \ + } \ + } else \ + GTEST_CONCAT_TOKEN_(gtest_label_testnofatal_, __LINE__) \ + : fail("Expected: " #statement \ + " doesn't generate new fatal " \ + "failures in the current thread.\n" \ + " Actual: it does.") // Expands to the name of the class that implements the given test. #define GTEST_TEST_CLASS_NAME_(test_suite_name, test_name) \ diff --git a/googletest/include/gtest/internal/gtest-param-util.h b/googletest/include/gtest/internal/gtest-param-util.h index ff25d99..d70cd85 100644 --- a/googletest/include/gtest/internal/gtest-param-util.h +++ b/googletest/include/gtest/internal/gtest-param-util.h @@ -47,19 +47,18 @@ #include <utility> #include <vector> -#include "gtest/internal/gtest-internal.h" -#include "gtest/internal/gtest-port.h" #include "gtest/gtest-printers.h" #include "gtest/gtest-test-part.h" +#include "gtest/internal/gtest-internal.h" +#include "gtest/internal/gtest-port.h" namespace testing { // Input to a parameterized test name generator, describing a test parameter. // Consists of the parameter value and the integer parameter index. template <class ParamType> struct TestParamInfo { - TestParamInfo(const ParamType& a_param, size_t an_index) : - param(a_param), - index(an_index) {} + TestParamInfo(const ParamType& a_param, size_t an_index) + : param(a_param), index(an_index) {} ParamType param; size_t index; }; @@ -85,8 +84,10 @@ namespace internal { GTEST_API_ void ReportInvalidTestSuiteType(const char* test_suite_name, CodeLocation code_location); -template <typename> class ParamGeneratorInterface; -template <typename> class ParamGenerator; +template <typename> +class ParamGeneratorInterface; +template <typename> +class ParamGenerator; // Interface for iterating over elements provided by an implementation // of ParamGeneratorInterface<T>. @@ -130,8 +131,7 @@ class ParamIterator { // ParamIterator assumes ownership of the impl_ pointer. ParamIterator(const ParamIterator& other) : impl_(other.impl_->Clone()) {} ParamIterator& operator=(const ParamIterator& other) { - if (this != &other) - impl_.reset(other.impl_->Clone()); + if (this != &other) impl_.reset(other.impl_->Clone()); return *this; } @@ -158,7 +158,7 @@ class ParamIterator { private: friend class ParamGenerator<T>; explicit ParamIterator(ParamIteratorInterface<T>* impl) : impl_(impl) {} - std::unique_ptr<ParamIteratorInterface<T> > impl_; + std::unique_ptr<ParamIteratorInterface<T>> impl_; }; // ParamGeneratorInterface<T> is the binary interface to access generators @@ -180,7 +180,7 @@ class ParamGeneratorInterface { // This class implements copy initialization semantics and the contained // ParamGeneratorInterface<T> instance is shared among all copies // of the original object. This is possible because that instance is immutable. -template<typename T> +template <typename T> class ParamGenerator { public: typedef ParamIterator<T> iterator; @@ -197,7 +197,7 @@ class ParamGenerator { iterator end() const { return iterator(impl_->End()); } private: - std::shared_ptr<const ParamGeneratorInterface<T> > impl_; + std::shared_ptr<const ParamGeneratorInterface<T>> impl_; }; // Generates values from a range of two comparable values. Can be used to @@ -208,8 +208,10 @@ template <typename T, typename IncrementT> class RangeGenerator : public ParamGeneratorInterface<T> { public: RangeGenerator(T begin, T end, IncrementT step) - : begin_(begin), end_(end), - step_(step), end_index_(CalculateEndIndex(begin, end, step)) {} + : begin_(begin), + end_(end), + step_(step), + end_index_(CalculateEndIndex(begin, end, step)) {} ~RangeGenerator() override {} ParamIteratorInterface<T>* Begin() const override { @@ -252,7 +254,9 @@ class RangeGenerator : public ParamGeneratorInterface<T> { private: Iterator(const Iterator& other) : ParamIteratorInterface<T>(), - base_(other.base_), value_(other.value_), index_(other.index_), + base_(other.base_), + value_(other.value_), + index_(other.index_), step_(other.step_) {} // No implementation - assignment is unsupported. @@ -264,12 +268,10 @@ class RangeGenerator : public ParamGeneratorInterface<T> { const IncrementT step_; }; // class RangeGenerator::Iterator - static int CalculateEndIndex(const T& begin, - const T& end, + static int CalculateEndIndex(const T& begin, const T& end, const IncrementT& step) { int end_index = 0; - for (T i = begin; i < end; i = static_cast<T>(i + step)) - end_index++; + for (T i = begin; i < end; i = static_cast<T>(i + step)) end_index++; return end_index; } @@ -284,7 +286,6 @@ class RangeGenerator : public ParamGeneratorInterface<T> { const int end_index_; }; // class RangeGenerator - // Generates values from a pair of STL-style iterators. Used in the // ValuesIn() function. The elements are copied from the source range // since the source can be located on the stack, and the generator @@ -342,13 +343,13 @@ class ValuesInIteratorRangeGenerator : public ParamGeneratorInterface<T> { << "The program attempted to compare iterators " << "from different generators." << std::endl; return iterator_ == - CheckedDowncastToActualType<const Iterator>(&other)->iterator_; + CheckedDowncastToActualType<const Iterator>(&other)->iterator_; } private: Iterator(const Iterator& other) - // The explicit constructor call suppresses a false warning - // emitted by gcc when supplied with the -Wextra option. + // The explicit constructor call suppresses a false warning + // emitted by gcc when supplied with the -Wextra option. : ParamIteratorInterface<T>(), base_(other.base_), iterator_(other.iterator_) {} @@ -395,8 +396,8 @@ template <class TestClass> class ParameterizedTestFactory : public TestFactoryBase { public: typedef typename TestClass::ParamType ParamType; - explicit ParameterizedTestFactory(ParamType parameter) : - parameter_(parameter) {} + explicit ParameterizedTestFactory(ParamType parameter) + : parameter_(parameter) {} Test* CreateTest() override { TestClass::SetParam(¶meter_); return new TestClass(); @@ -548,8 +549,8 @@ class ParameterizedTestSuiteInfo : public ParameterizedTestSuiteInfoBase { test_it != tests_.end(); ++test_it) { std::shared_ptr<TestInfo> test_info = *test_it; for (typename InstantiationContainer::iterator gen_it = - instantiations_.begin(); gen_it != instantiations_.end(); - ++gen_it) { + instantiations_.begin(); + gen_it != instantiations_.end(); ++gen_it) { const std::string& instantiation_name = gen_it->name; ParamGenerator<ParamType> generator((*gen_it->generator)()); ParamNameGeneratorFunc* name_func = gen_it->name_func; @@ -557,7 +558,7 @@ class ParameterizedTestSuiteInfo : public ParameterizedTestSuiteInfoBase { int line = gen_it->line; std::string test_suite_name; - if ( !instantiation_name.empty() ) + if (!instantiation_name.empty()) test_suite_name = instantiation_name + "/"; test_suite_name += test_info->test_suite_base_name; @@ -570,17 +571,16 @@ class ParameterizedTestSuiteInfo : public ParameterizedTestSuiteInfoBase { Message test_name_stream; - std::string param_name = name_func( - TestParamInfo<ParamType>(*param_it, i)); + std::string param_name = + name_func(TestParamInfo<ParamType>(*param_it, i)); GTEST_CHECK_(IsValidParamName(param_name)) << "Parameterized test name '" << param_name - << "' is invalid, in " << file - << " line " << line << std::endl; + << "' is invalid, in " << file << " line " << line << std::endl; GTEST_CHECK_(test_param_names.count(param_name) == 0) - << "Duplicate parameterized test name '" << param_name - << "', in " << file << " line " << line << std::endl; + << "Duplicate parameterized test name '" << param_name << "', in " + << file << " line " << line << std::endl; test_param_names.insert(param_name); @@ -597,15 +597,15 @@ class ParameterizedTestSuiteInfo : public ParameterizedTestSuiteInfoBase { SuiteApiResolver<TestSuite>::GetTearDownCaseOrSuite(file, line), test_info->test_meta_factory->CreateTestFactory(*param_it)); } // for param_it - } // for gen_it - } // for test_it + } // for gen_it + } // for test_it if (!generated_instantiations) { // There are no generaotrs, or they all generate nothing ... InsertSyntheticTestCase(GetTestSuiteName(), code_location_, !tests_.empty()); } - } // RegisterTests + } // RegisterTests private: // LocalTestInfo structure keeps information about a single test registered @@ -621,42 +621,39 @@ class ParameterizedTestSuiteInfo : public ParameterizedTestSuiteInfoBase { const std::string test_suite_base_name; const std::string test_base_name; - const std::unique_ptr<TestMetaFactoryBase<ParamType> > test_meta_factory; + const std::unique_ptr<TestMetaFactoryBase<ParamType>> test_meta_factory; const CodeLocation code_location; }; - using TestInfoContainer = ::std::vector<std::shared_ptr<TestInfo> >; + using TestInfoContainer = ::std::vector<std::shared_ptr<TestInfo>>; // Records data received from INSTANTIATE_TEST_SUITE_P macros: // <Instantiation name, Sequence generator creation function, // Name generator function, Source file, Source line> struct InstantiationInfo { - InstantiationInfo(const std::string &name_in, - GeneratorCreationFunc* generator_in, - ParamNameGeneratorFunc* name_func_in, - const char* file_in, - int line_in) - : name(name_in), - generator(generator_in), - name_func(name_func_in), - file(file_in), - line(line_in) {} - - std::string name; - GeneratorCreationFunc* generator; - ParamNameGeneratorFunc* name_func; - const char* file; - int line; + InstantiationInfo(const std::string& name_in, + GeneratorCreationFunc* generator_in, + ParamNameGeneratorFunc* name_func_in, const char* file_in, + int line_in) + : name(name_in), + generator(generator_in), + name_func(name_func_in), + file(file_in), + line(line_in) {} + + std::string name; + GeneratorCreationFunc* generator; + ParamNameGeneratorFunc* name_func; + const char* file; + int line; }; typedef ::std::vector<InstantiationInfo> InstantiationContainer; static bool IsValidParamName(const std::string& name) { // Check for empty string - if (name.empty()) - return false; + if (name.empty()) return false; // Check for invalid characters for (std::string::size_type index = 0; index < name.size(); ++index) { - if (!IsAlNum(name[index]) && name[index] != '_') - return false; + if (!IsAlNum(name[index]) && name[index] != '_') return false; } return true; @@ -710,7 +707,7 @@ class ParameterizedTestSuiteRegistry { // type we are looking for, so we downcast it to that type // without further checks. typed_test_info = CheckedDowncastToActualType< - ParameterizedTestSuiteInfo<TestSuite> >(test_suite_info); + ParameterizedTestSuiteInfo<TestSuite>>(test_suite_info); } break; } @@ -837,7 +834,8 @@ class CartesianProductGenerator : public ParamIteratorInterface<ParamType> { public: IteratorImpl(const ParamGeneratorInterface<ParamType>* base, - const std::tuple<ParamGenerator<T>...>& generators, bool is_end) + const std::tuple<ParamGenerator<T>...>& generators, + bool is_end) : base_(base), begin_(std::get<I>(generators).begin()...), end_(std::get<I>(generators).end()...), diff --git a/googletest/include/gtest/internal/gtest-port-arch.h b/googletest/include/gtest/internal/gtest-port-arch.h index 22bbad9..f025db7 100644 --- a/googletest/include/gtest/internal/gtest-port-arch.h +++ b/googletest/include/gtest/internal/gtest-port-arch.h @@ -37,72 +37,72 @@ // Determines the platform on which Google Test is compiled. #ifdef __CYGWIN__ -# define GTEST_OS_CYGWIN 1 -# elif defined(__MINGW__) || defined(__MINGW32__) || defined(__MINGW64__) -# define GTEST_OS_WINDOWS_MINGW 1 -# define GTEST_OS_WINDOWS 1 +#define GTEST_OS_CYGWIN 1 +#elif defined(__MINGW__) || defined(__MINGW32__) || defined(__MINGW64__) +#define GTEST_OS_WINDOWS_MINGW 1 +#define GTEST_OS_WINDOWS 1 #elif defined _WIN32 -# define GTEST_OS_WINDOWS 1 -# ifdef _WIN32_WCE -# define GTEST_OS_WINDOWS_MOBILE 1 -# elif defined(WINAPI_FAMILY) -# include <winapifamily.h> -# if WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_DESKTOP) -# define GTEST_OS_WINDOWS_DESKTOP 1 -# elif WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_PHONE_APP) -# define GTEST_OS_WINDOWS_PHONE 1 -# elif WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_APP) -# define GTEST_OS_WINDOWS_RT 1 -# elif WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_TV_TITLE) -# define GTEST_OS_WINDOWS_PHONE 1 -# define GTEST_OS_WINDOWS_TV_TITLE 1 -# else - // WINAPI_FAMILY defined but no known partition matched. - // Default to desktop. -# define GTEST_OS_WINDOWS_DESKTOP 1 -# endif -# else -# define GTEST_OS_WINDOWS_DESKTOP 1 -# endif // _WIN32_WCE +#define GTEST_OS_WINDOWS 1 +#ifdef _WIN32_WCE +#define GTEST_OS_WINDOWS_MOBILE 1 +#elif defined(WINAPI_FAMILY) +#include <winapifamily.h> +#if WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_DESKTOP) +#define GTEST_OS_WINDOWS_DESKTOP 1 +#elif WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_PHONE_APP) +#define GTEST_OS_WINDOWS_PHONE 1 +#elif WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_APP) +#define GTEST_OS_WINDOWS_RT 1 +#elif WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_TV_TITLE) +#define GTEST_OS_WINDOWS_PHONE 1 +#define GTEST_OS_WINDOWS_TV_TITLE 1 +#else +// WINAPI_FAMILY defined but no known partition matched. +// Default to desktop. +#define GTEST_OS_WINDOWS_DESKTOP 1 +#endif +#else +#define GTEST_OS_WINDOWS_DESKTOP 1 +#endif // _WIN32_WCE #elif defined __OS2__ -# define GTEST_OS_OS2 1 +#define GTEST_OS_OS2 1 #elif defined __APPLE__ -# define GTEST_OS_MAC 1 -# include <TargetConditionals.h> -# if TARGET_OS_IPHONE -# define GTEST_OS_IOS 1 -# endif +#define GTEST_OS_MAC 1 +#include <TargetConditionals.h> +#if TARGET_OS_IPHONE +#define GTEST_OS_IOS 1 +#endif #elif defined __DragonFly__ -# define GTEST_OS_DRAGONFLY 1 +#define GTEST_OS_DRAGONFLY 1 #elif defined __FreeBSD__ -# define GTEST_OS_FREEBSD 1 +#define GTEST_OS_FREEBSD 1 #elif defined __Fuchsia__ -# define GTEST_OS_FUCHSIA 1 +#define GTEST_OS_FUCHSIA 1 #elif defined(__GNU__) -# define GTEST_OS_GNU_HURD 1 +#define GTEST_OS_GNU_HURD 1 #elif defined(__GLIBC__) && defined(__FreeBSD_kernel__) -# define GTEST_OS_GNU_KFREEBSD 1 +#define GTEST_OS_GNU_KFREEBSD 1 #elif defined __linux__ -# define GTEST_OS_LINUX 1 -# if defined __ANDROID__ -# define GTEST_OS_LINUX_ANDROID 1 -# endif +#define GTEST_OS_LINUX 1 +#if defined __ANDROID__ +#define GTEST_OS_LINUX_ANDROID 1 +#endif #elif defined __MVS__ -# define GTEST_OS_ZOS 1 +#define GTEST_OS_ZOS 1 #elif defined(__sun) && defined(__SVR4) -# define GTEST_OS_SOLARIS 1 +#define GTEST_OS_SOLARIS 1 #elif defined(_AIX) -# define GTEST_OS_AIX 1 +#define GTEST_OS_AIX 1 #elif defined(__hpux) -# define GTEST_OS_HPUX 1 +#define GTEST_OS_HPUX 1 #elif defined __native_client__ -# define GTEST_OS_NACL 1 +#define GTEST_OS_NACL 1 #elif defined __NetBSD__ -# define GTEST_OS_NETBSD 1 +#define GTEST_OS_NETBSD 1 #elif defined __OpenBSD__ -# define GTEST_OS_OPENBSD 1 +#define GTEST_OS_OPENBSD 1 #elif defined __QNX__ -# define GTEST_OS_QNX 1 +#define GTEST_OS_QNX 1 #elif defined(__HAIKU__) #define GTEST_OS_HAIKU 1 #elif defined ESP8266 diff --git a/googletest/include/gtest/internal/gtest-port.h b/googletest/include/gtest/internal/gtest-port.h index 929b709..e178782 100644 --- a/googletest/include/gtest/internal/gtest-port.h +++ b/googletest/include/gtest/internal/gtest-port.h @@ -275,36 +275,36 @@ #include <vector> #ifndef _WIN32_WCE -# include <sys/types.h> -# include <sys/stat.h> +#include <sys/stat.h> +#include <sys/types.h> #endif // !_WIN32_WCE #if defined __APPLE__ -# include <AvailabilityMacros.h> -# include <TargetConditionals.h> +#include <AvailabilityMacros.h> +#include <TargetConditionals.h> #endif #include "gtest/internal/custom/gtest-port.h" #include "gtest/internal/gtest-port-arch.h" #if !defined(GTEST_DEV_EMAIL_) -# define GTEST_DEV_EMAIL_ "googletestframework@@googlegroups.com" -# define GTEST_FLAG_PREFIX_ "gtest_" -# define GTEST_FLAG_PREFIX_DASH_ "gtest-" -# define GTEST_FLAG_PREFIX_UPPER_ "GTEST_" -# define GTEST_NAME_ "Google Test" -# define GTEST_PROJECT_URL_ "https://github.com/google/googletest/" +#define GTEST_DEV_EMAIL_ "googletestframework@@googlegroups.com" +#define GTEST_FLAG_PREFIX_ "gtest_" +#define GTEST_FLAG_PREFIX_DASH_ "gtest-" +#define GTEST_FLAG_PREFIX_UPPER_ "GTEST_" +#define GTEST_NAME_ "Google Test" +#define GTEST_PROJECT_URL_ "https://github.com/google/googletest/" #endif // !defined(GTEST_DEV_EMAIL_) #if !defined(GTEST_INIT_GOOGLE_TEST_NAME_) -# define GTEST_INIT_GOOGLE_TEST_NAME_ "testing::InitGoogleTest" +#define GTEST_INIT_GOOGLE_TEST_NAME_ "testing::InitGoogleTest" #endif // !defined(GTEST_INIT_GOOGLE_TEST_NAME_) // Determines the version of gcc that is used to compile this. #ifdef __GNUC__ // 40302 means version 4.3.2. -# define GTEST_GCC_VER_ \ - (__GNUC__*10000 + __GNUC_MINOR__*100 + __GNUC_PATCHLEVEL__) +#define GTEST_GCC_VER_ \ + (__GNUC__ * 10000 + __GNUC_MINOR__ * 100 + __GNUC_PATCHLEVEL__) #endif // __GNUC__ // Macros for disabling Microsoft Visual C++ warnings. @@ -313,41 +313,37 @@ // /* code that triggers warnings C4800 and C4385 */ // GTEST_DISABLE_MSC_WARNINGS_POP_() #if defined(_MSC_VER) -# define GTEST_DISABLE_MSC_WARNINGS_PUSH_(warnings) \ - __pragma(warning(push)) \ - __pragma(warning(disable: warnings)) -# define GTEST_DISABLE_MSC_WARNINGS_POP_() \ - __pragma(warning(pop)) +#define GTEST_DISABLE_MSC_WARNINGS_PUSH_(warnings) \ + __pragma(warning(push)) __pragma(warning(disable : warnings)) +#define GTEST_DISABLE_MSC_WARNINGS_POP_() __pragma(warning(pop)) #else // Not all compilers are MSVC -# define GTEST_DISABLE_MSC_WARNINGS_PUSH_(warnings) -# define GTEST_DISABLE_MSC_WARNINGS_POP_() +#define GTEST_DISABLE_MSC_WARNINGS_PUSH_(warnings) +#define GTEST_DISABLE_MSC_WARNINGS_POP_() #endif // Clang on Windows does not understand MSVC's pragma warning. // We need clang-specific way to disable function deprecation warning. #ifdef __clang__ -# define GTEST_DISABLE_MSC_DEPRECATED_PUSH_() \ - _Pragma("clang diagnostic push") \ - _Pragma("clang diagnostic ignored \"-Wdeprecated-declarations\"") \ - _Pragma("clang diagnostic ignored \"-Wdeprecated-implementations\"") -#define GTEST_DISABLE_MSC_DEPRECATED_POP_() \ - _Pragma("clang diagnostic pop") +#define GTEST_DISABLE_MSC_DEPRECATED_PUSH_() \ + _Pragma("clang diagnostic push") \ + _Pragma("clang diagnostic ignored \"-Wdeprecated-declarations\"") \ + _Pragma("clang diagnostic ignored \"-Wdeprecated-implementations\"") +#define GTEST_DISABLE_MSC_DEPRECATED_POP_() _Pragma("clang diagnostic pop") #else -# define GTEST_DISABLE_MSC_DEPRECATED_PUSH_() \ - GTEST_DISABLE_MSC_WARNINGS_PUSH_(4996) -# define GTEST_DISABLE_MSC_DEPRECATED_POP_() \ - GTEST_DISABLE_MSC_WARNINGS_POP_() +#define GTEST_DISABLE_MSC_DEPRECATED_PUSH_() \ + GTEST_DISABLE_MSC_WARNINGS_PUSH_(4996) +#define GTEST_DISABLE_MSC_DEPRECATED_POP_() GTEST_DISABLE_MSC_WARNINGS_POP_() #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. #if GTEST_OS_WINDOWS -# if !GTEST_OS_WINDOWS_MOBILE -# include <direct.h> -# include <io.h> -# endif +#if !GTEST_OS_WINDOWS_MOBILE +#include <direct.h> +#include <io.h> +#endif // In order to avoid having to include <windows.h>, use forward declaration #if GTEST_OS_WINDOWS_MINGW && !defined(__MINGW64_VERSION_MAJOR) // MinGW defined _CRITICAL_SECTION and _RTL_CRITICAL_SECTION as two @@ -367,24 +363,24 @@ typedef struct _RTL_CRITICAL_SECTION GTEST_CRITICAL_SECTION; // This assumes that non-Windows OSes provide unistd.h. For OSes where this // is not the case, we need to include headers that provide the functions // mentioned above. -# include <unistd.h> -# include <strings.h> +#include <strings.h> +#include <unistd.h> #endif // GTEST_OS_WINDOWS #if GTEST_OS_LINUX_ANDROID // Used to define __ANDROID_API__ matching the target NDK API level. -# include <android/api-level.h> // NOLINT +#include <android/api-level.h> // NOLINT #endif // Defines this to true if and only if Google Test can use POSIX regular // expressions. #ifndef GTEST_HAS_POSIX_RE -# if GTEST_OS_LINUX_ANDROID +#if GTEST_OS_LINUX_ANDROID // On Android, <regex.h> is only available starting with Gingerbread. -# define GTEST_HAS_POSIX_RE (__ANDROID_API__ >= 9) -# else +#define GTEST_HAS_POSIX_RE (__ANDROID_API__ >= 9) +#else #define GTEST_HAS_POSIX_RE (!GTEST_OS_WINDOWS && !GTEST_OS_XTENSA) -# endif +#endif #endif #if GTEST_USES_PCRE @@ -396,39 +392,39 @@ typedef struct _RTL_CRITICAL_SECTION GTEST_CRITICAL_SECTION; // won't compile otherwise. We can #include it here as we already // included <stdlib.h>, which is guaranteed to define size_t through // <stddef.h>. -# include <regex.h> // NOLINT +#include <regex.h> // NOLINT -# define GTEST_USES_POSIX_RE 1 +#define GTEST_USES_POSIX_RE 1 #elif GTEST_OS_WINDOWS // <regex.h> is not available on Windows. Use our own simple regex // implementation instead. -# define GTEST_USES_SIMPLE_RE 1 +#define GTEST_USES_SIMPLE_RE 1 #else // <regex.h> may not be available on this platform. Use our own // simple regex implementation instead. -# define GTEST_USES_SIMPLE_RE 1 +#define GTEST_USES_SIMPLE_RE 1 #endif // GTEST_USES_PCRE #ifndef GTEST_HAS_EXCEPTIONS // The user didn't tell us whether exceptions are enabled, so we need // to figure it out. -# if defined(_MSC_VER) && defined(_CPPUNWIND) +#if defined(_MSC_VER) && defined(_CPPUNWIND) // MSVC defines _CPPUNWIND to 1 if and only if exceptions are enabled. -# define GTEST_HAS_EXCEPTIONS 1 -# elif defined(__BORLANDC__) +#define GTEST_HAS_EXCEPTIONS 1 +#elif defined(__BORLANDC__) // C++Builder's implementation of the STL uses the _HAS_EXCEPTIONS // macro to enable exceptions, so we'll do the same. // Assumes that exceptions are enabled by default. -# ifndef _HAS_EXCEPTIONS -# define _HAS_EXCEPTIONS 1 -# endif // _HAS_EXCEPTIONS -# define GTEST_HAS_EXCEPTIONS _HAS_EXCEPTIONS -# elif defined(__clang__) +#ifndef _HAS_EXCEPTIONS +#define _HAS_EXCEPTIONS 1 +#endif // _HAS_EXCEPTIONS +#define GTEST_HAS_EXCEPTIONS _HAS_EXCEPTIONS +#elif defined(__clang__) // clang defines __EXCEPTIONS if and only if exceptions are enabled before clang // 220714, but if and only if cleanups are enabled after that. In Obj-C++ files, // there can be cleanups for ObjC exceptions which also need cleanups, even if @@ -437,27 +433,27 @@ typedef struct _RTL_CRITICAL_SECTION GTEST_CRITICAL_SECTION; // cleanups prior to that. To reliably check for C++ exception availability with // clang, check for // __EXCEPTIONS && __has_feature(cxx_exceptions). -# define GTEST_HAS_EXCEPTIONS (__EXCEPTIONS && __has_feature(cxx_exceptions)) -# elif defined(__GNUC__) && __EXCEPTIONS +#define GTEST_HAS_EXCEPTIONS (__EXCEPTIONS && __has_feature(cxx_exceptions)) +#elif defined(__GNUC__) && __EXCEPTIONS // gcc defines __EXCEPTIONS to 1 if and only if exceptions are enabled. -# define GTEST_HAS_EXCEPTIONS 1 -# elif defined(__SUNPRO_CC) +#define GTEST_HAS_EXCEPTIONS 1 +#elif defined(__SUNPRO_CC) // Sun Pro CC supports exceptions. However, there is no compile-time way of // detecting whether they are enabled or not. Therefore, we assume that // they are enabled unless the user tells us otherwise. -# define GTEST_HAS_EXCEPTIONS 1 -# elif defined(__IBMCPP__) && __EXCEPTIONS +#define GTEST_HAS_EXCEPTIONS 1 +#elif defined(__IBMCPP__) && __EXCEPTIONS // xlC defines __EXCEPTIONS to 1 if and only if exceptions are enabled. -# define GTEST_HAS_EXCEPTIONS 1 -# elif defined(__HP_aCC) +#define GTEST_HAS_EXCEPTIONS 1 +#elif defined(__HP_aCC) // Exception handling is in effect by default in HP aCC compiler. It has to // be turned of by +noeh compiler option if desired. -# define GTEST_HAS_EXCEPTIONS 1 -# else +#define GTEST_HAS_EXCEPTIONS 1 +#else // For other compilers, we assume exceptions are disabled to be // conservative. -# define GTEST_HAS_EXCEPTIONS 0 -# endif // defined(_MSC_VER) || defined(__BORLANDC__) +#define GTEST_HAS_EXCEPTIONS 0 +#endif // defined(_MSC_VER) || defined(__BORLANDC__) #endif // GTEST_HAS_EXCEPTIONS #ifndef GTEST_HAS_STD_WSTRING @@ -477,63 +473,62 @@ typedef struct _RTL_CRITICAL_SECTION GTEST_CRITICAL_SECTION; // The user didn't tell us whether RTTI is enabled, so we need to // figure it out. -# ifdef _MSC_VER +#ifdef _MSC_VER #ifdef _CPPRTTI // MSVC defines this macro if and only if RTTI is enabled. -# define GTEST_HAS_RTTI 1 -# else -# define GTEST_HAS_RTTI 0 -# endif +#define GTEST_HAS_RTTI 1 +#else +#define GTEST_HAS_RTTI 0 +#endif // Starting with version 4.3.2, gcc defines __GXX_RTTI if and only if RTTI is // enabled. -# elif defined(__GNUC__) +#elif defined(__GNUC__) -# ifdef __GXX_RTTI +#ifdef __GXX_RTTI // When building against STLport with the Android NDK and with // -frtti -fno-exceptions, the build fails at link time with undefined // references to __cxa_bad_typeid. Note sure if STL or toolchain bug, // so disable RTTI when detected. -# if GTEST_OS_LINUX_ANDROID && defined(_STLPORT_MAJOR) && \ - !defined(__EXCEPTIONS) -# define GTEST_HAS_RTTI 0 -# else -# define GTEST_HAS_RTTI 1 -# endif // GTEST_OS_LINUX_ANDROID && __STLPORT_MAJOR && !__EXCEPTIONS -# else -# define GTEST_HAS_RTTI 0 -# endif // __GXX_RTTI +#if GTEST_OS_LINUX_ANDROID && defined(_STLPORT_MAJOR) && !defined(__EXCEPTIONS) +#define GTEST_HAS_RTTI 0 +#else +#define GTEST_HAS_RTTI 1 +#endif // GTEST_OS_LINUX_ANDROID && __STLPORT_MAJOR && !__EXCEPTIONS +#else +#define GTEST_HAS_RTTI 0 +#endif // __GXX_RTTI // Clang defines __GXX_RTTI starting with version 3.0, but its manual recommends // using has_feature instead. has_feature(cxx_rtti) is supported since 2.7, the // first version with C++ support. -# elif defined(__clang__) +#elif defined(__clang__) -# define GTEST_HAS_RTTI __has_feature(cxx_rtti) +#define GTEST_HAS_RTTI __has_feature(cxx_rtti) // Starting with version 9.0 IBM Visual Age defines __RTTI_ALL__ to 1 if // both the typeid and dynamic_cast features are present. -# elif defined(__IBMCPP__) && (__IBMCPP__ >= 900) +#elif defined(__IBMCPP__) && (__IBMCPP__ >= 900) -# ifdef __RTTI_ALL__ -# define GTEST_HAS_RTTI 1 -# else -# define GTEST_HAS_RTTI 0 -# endif +#ifdef __RTTI_ALL__ +#define GTEST_HAS_RTTI 1 +#else +#define GTEST_HAS_RTTI 0 +#endif -# else +#else // For all other compilers, we assume RTTI is enabled. -# define GTEST_HAS_RTTI 1 +#define GTEST_HAS_RTTI 1 -# endif // _MSC_VER +#endif // _MSC_VER #endif // GTEST_HAS_RTTI // It's this header's responsibility to #include <typeinfo> when RTTI // is enabled. #if GTEST_HAS_RTTI -# include <typeinfo> +#include <typeinfo> #endif // Determines whether Google Test can use the pthreads library. @@ -553,10 +548,10 @@ typedef struct _RTL_CRITICAL_SECTION GTEST_CRITICAL_SECTION; #if GTEST_HAS_PTHREAD // gtest-port.h guarantees to #include <pthread.h> when GTEST_HAS_PTHREAD is // true. -# include <pthread.h> // NOLINT +#include <pthread.h> // NOLINT // For timespec and nanosleep, used below. -# include <time.h> // NOLINT +#include <time.h> // NOLINT #endif // Determines whether clone(2) is supported. @@ -566,24 +561,23 @@ typedef struct _RTL_CRITICAL_SECTION GTEST_CRITICAL_SECTION; #ifndef GTEST_HAS_CLONE // The user didn't tell us, so we need to figure it out. -# if GTEST_OS_LINUX && !defined(__ia64__) -# if GTEST_OS_LINUX_ANDROID +#if GTEST_OS_LINUX && !defined(__ia64__) +#if GTEST_OS_LINUX_ANDROID // On Android, clone() became available at different API levels for each 32-bit // architecture. -# if defined(__LP64__) || \ - (defined(__arm__) && __ANDROID_API__ >= 9) || \ - (defined(__mips__) && __ANDROID_API__ >= 12) || \ - (defined(__i386__) && __ANDROID_API__ >= 17) -# define GTEST_HAS_CLONE 1 -# else -# define GTEST_HAS_CLONE 0 -# endif -# else -# define GTEST_HAS_CLONE 1 -# endif -# else -# define GTEST_HAS_CLONE 0 -# endif // GTEST_OS_LINUX && !defined(__ia64__) +#if defined(__LP64__) || (defined(__arm__) && __ANDROID_API__ >= 9) || \ + (defined(__mips__) && __ANDROID_API__ >= 12) || \ + (defined(__i386__) && __ANDROID_API__ >= 17) +#define GTEST_HAS_CLONE 1 +#else +#define GTEST_HAS_CLONE 0 +#endif +#else +#define GTEST_HAS_CLONE 1 +#endif +#else +#define GTEST_HAS_CLONE 0 +#endif // GTEST_OS_LINUX && !defined(__ia64__) #endif // GTEST_HAS_CLONE @@ -594,10 +588,10 @@ typedef struct _RTL_CRITICAL_SECTION GTEST_CRITICAL_SECTION; // platforms except known mobile ones. #if GTEST_OS_WINDOWS_MOBILE || GTEST_OS_WINDOWS_PHONE || \ GTEST_OS_WINDOWS_RT || GTEST_OS_ESP8266 || GTEST_OS_XTENSA -# define GTEST_HAS_STREAM_REDIRECTION 0 -# else -# define GTEST_HAS_STREAM_REDIRECTION 1 -# endif // !GTEST_OS_WINDOWS_MOBILE +#define GTEST_HAS_STREAM_REDIRECTION 0 +#else +#define GTEST_HAS_STREAM_REDIRECTION 1 +#endif // !GTEST_OS_WINDOWS_MOBILE #endif // GTEST_HAS_STREAM_REDIRECTION // Determines whether to support death tests. @@ -609,7 +603,7 @@ typedef struct _RTL_CRITICAL_SECTION GTEST_CRITICAL_SECTION; GTEST_OS_FREEBSD || GTEST_OS_NETBSD || GTEST_OS_FUCHSIA || \ GTEST_OS_DRAGONFLY || GTEST_OS_GNU_KFREEBSD || GTEST_OS_HAIKU || \ GTEST_OS_GNU_HURD) -# define GTEST_HAS_DEATH_TEST 1 +#define GTEST_HAS_DEATH_TEST 1 #endif // Determines whether to support type-driven tests. @@ -618,8 +612,8 @@ typedef struct _RTL_CRITICAL_SECTION GTEST_CRITICAL_SECTION; // Sun Pro CC, IBM Visual Age, and HP aCC support. #if defined(__GNUC__) || defined(_MSC_VER) || defined(__SUNPRO_CC) || \ defined(__IBMCPP__) || defined(__HP_aCC) -# define GTEST_HAS_TYPED_TEST 1 -# define GTEST_HAS_TYPED_TEST_P 1 +#define GTEST_HAS_TYPED_TEST 1 +#define GTEST_HAS_TYPED_TEST_P 1 #endif // Determines whether the system compiler uses UTF-16 for encoding wide strings. @@ -630,7 +624,7 @@ typedef struct _RTL_CRITICAL_SECTION GTEST_CRITICAL_SECTION; #if GTEST_OS_LINUX || GTEST_OS_GNU_KFREEBSD || GTEST_OS_DRAGONFLY || \ GTEST_OS_FREEBSD || GTEST_OS_NETBSD || GTEST_OS_OPENBSD || \ GTEST_OS_GNU_HURD -# define GTEST_CAN_STREAM_RESULTS_ 1 +#define GTEST_CAN_STREAM_RESULTS_ 1 #endif // Defines some utility macros. @@ -644,9 +638,12 @@ typedef struct _RTL_CRITICAL_SECTION GTEST_CRITICAL_SECTION; // // The "switch (0) case 0:" idiom is used to suppress this. #ifdef __INTEL_COMPILER -# define GTEST_AMBIGUOUS_ELSE_BLOCKER_ +#define GTEST_AMBIGUOUS_ELSE_BLOCKER_ #else -# define GTEST_AMBIGUOUS_ELSE_BLOCKER_ switch (0) case 0: default: // NOLINT +#define GTEST_AMBIGUOUS_ELSE_BLOCKER_ \ + switch (0) \ + case 0: \ + default: // NOLINT #endif // Use this annotation at the end of a struct/class definition to @@ -661,31 +658,31 @@ typedef struct _RTL_CRITICAL_SECTION GTEST_CRITICAL_SECTION; // Also use it after a variable or parameter declaration to tell the // compiler the variable/parameter does not have to be used. #if defined(__GNUC__) && !defined(COMPILER_ICC) -# define GTEST_ATTRIBUTE_UNUSED_ __attribute__ ((unused)) +#define GTEST_ATTRIBUTE_UNUSED_ __attribute__((unused)) #elif defined(__clang__) -# if __has_attribute(unused) -# define GTEST_ATTRIBUTE_UNUSED_ __attribute__ ((unused)) -# endif +#if __has_attribute(unused) +#define GTEST_ATTRIBUTE_UNUSED_ __attribute__((unused)) +#endif #endif #ifndef GTEST_ATTRIBUTE_UNUSED_ -# define GTEST_ATTRIBUTE_UNUSED_ +#define GTEST_ATTRIBUTE_UNUSED_ #endif // 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) +#if defined(__MINGW_PRINTF_FORMAT) // MinGW has two different printf implementations. Ensure the format macro // matches the selected implementation. See // https://sourceforge.net/p/mingw-w64/wiki2/gnu%20printf/. -# define GTEST_ATTRIBUTE_PRINTF_(string_index, first_to_check) \ - __attribute__((__format__(__MINGW_PRINTF_FORMAT, string_index, \ - first_to_check))) -# else -# define GTEST_ATTRIBUTE_PRINTF_(string_index, first_to_check) \ - __attribute__((__format__(__printf__, string_index, first_to_check))) -# endif +#define GTEST_ATTRIBUTE_PRINTF_(string_index, first_to_check) \ + __attribute__(( \ + __format__(__MINGW_PRINTF_FORMAT, string_index, first_to_check))) +#else +#define GTEST_ATTRIBUTE_PRINTF_(string_index, first_to_check) \ + __attribute__((__format__(__printf__, string_index, first_to_check))) +#endif #else -# define GTEST_ATTRIBUTE_PRINTF_(string_index, first_to_check) +#define GTEST_ATTRIBUTE_PRINTF_(string_index, first_to_check) #endif // A macro to disallow copy constructor and operator= @@ -708,9 +705,9 @@ typedef struct _RTL_CRITICAL_SECTION GTEST_CRITICAL_SECTION; // // Sprocket* AllocateSprocket() GTEST_MUST_USE_RESULT_; #if defined(__GNUC__) && !defined(COMPILER_ICC) -# define GTEST_MUST_USE_RESULT_ __attribute__ ((warn_unused_result)) +#define GTEST_MUST_USE_RESULT_ __attribute__((warn_unused_result)) #else -# define GTEST_MUST_USE_RESULT_ +#define GTEST_MUST_USE_RESULT_ #endif // __GNUC__ && !COMPILER_ICC // MS C++ compiler emits warning when a conditional expression is compile time @@ -721,10 +718,9 @@ typedef struct _RTL_CRITICAL_SECTION GTEST_CRITICAL_SECTION; // while (true) { // GTEST_INTENTIONAL_CONST_COND_POP_() // } -# define GTEST_INTENTIONAL_CONST_COND_PUSH_() \ - GTEST_DISABLE_MSC_WARNINGS_PUSH_(4127) -# define GTEST_INTENTIONAL_CONST_COND_POP_() \ - GTEST_DISABLE_MSC_WARNINGS_POP_() +#define GTEST_INTENTIONAL_CONST_COND_PUSH_() \ + GTEST_DISABLE_MSC_WARNINGS_PUSH_(4127) +#define GTEST_INTENTIONAL_CONST_COND_POP_() GTEST_DISABLE_MSC_WARNINGS_POP_() // Determine whether the compiler supports Microsoft's Structured Exception // Handling. This is supported by several Windows compilers but generally @@ -732,13 +728,13 @@ typedef struct _RTL_CRITICAL_SECTION GTEST_CRITICAL_SECTION; #ifndef GTEST_HAS_SEH // The user didn't tell us, so we need to figure it out. -# if defined(_MSC_VER) || defined(__BORLANDC__) +#if defined(_MSC_VER) || defined(__BORLANDC__) // These two compilers are known to support SEH. -# define GTEST_HAS_SEH 1 -# else +#define GTEST_HAS_SEH 1 +#else // Assume no SEH. -# define GTEST_HAS_SEH 0 -# endif +#define GTEST_HAS_SEH 0 +#endif #endif // GTEST_HAS_SEH @@ -754,8 +750,8 @@ typedef struct _RTL_CRITICAL_SECTION GTEST_CRITICAL_SECTION; #if GTEST_IS_THREADSAFE // Some platforms don't support including these threading related headers. #include <condition_variable> // NOLINT -#include <mutex> // NOLINT -#endif // GTEST_IS_THREADSAFE +#include <mutex> // NOLINT +#endif // GTEST_IS_THREADSAFE // GTEST_API_ qualifies all symbols that must be exported. The definitions below // are guarded by #ifndef to give embedders a chance to define GTEST_API_ in @@ -763,30 +759,30 @@ typedef struct _RTL_CRITICAL_SECTION GTEST_CRITICAL_SECTION; #ifndef GTEST_API_ #ifdef _MSC_VER -# if GTEST_LINKED_AS_SHARED_LIBRARY -# define GTEST_API_ __declspec(dllimport) -# elif GTEST_CREATE_SHARED_LIBRARY -# define GTEST_API_ __declspec(dllexport) -# endif +#if GTEST_LINKED_AS_SHARED_LIBRARY +#define GTEST_API_ __declspec(dllimport) +#elif GTEST_CREATE_SHARED_LIBRARY +#define GTEST_API_ __declspec(dllexport) +#endif #elif __GNUC__ >= 4 || defined(__clang__) -# define GTEST_API_ __attribute__((visibility ("default"))) +#define GTEST_API_ __attribute__((visibility("default"))) #endif // _MSC_VER #endif // GTEST_API_ #ifndef GTEST_API_ -# define GTEST_API_ +#define GTEST_API_ #endif // GTEST_API_ #ifndef GTEST_DEFAULT_DEATH_TEST_STYLE -# define GTEST_DEFAULT_DEATH_TEST_STYLE "fast" +#define GTEST_DEFAULT_DEATH_TEST_STYLE "fast" #endif // GTEST_DEFAULT_DEATH_TEST_STYLE #ifdef __GNUC__ // Ask the compiler to never inline a given function. -# define GTEST_NO_INLINE_ __attribute__((noinline)) +#define GTEST_NO_INLINE_ __attribute__((noinline)) #else -# define GTEST_NO_INLINE_ +#define GTEST_NO_INLINE_ #endif #if defined(__clang__) @@ -805,60 +801,58 @@ typedef struct _RTL_CRITICAL_SECTION GTEST_CRITICAL_SECTION; // _LIBCPP_VERSION is defined by the libc++ library from the LLVM project. #if !defined(GTEST_HAS_CXXABI_H_) -# if defined(__GLIBCXX__) || (defined(_LIBCPP_VERSION) && !defined(_MSC_VER)) -# define GTEST_HAS_CXXABI_H_ 1 -# else -# define GTEST_HAS_CXXABI_H_ 0 -# endif +#if defined(__GLIBCXX__) || (defined(_LIBCPP_VERSION) && !defined(_MSC_VER)) +#define GTEST_HAS_CXXABI_H_ 1 +#else +#define GTEST_HAS_CXXABI_H_ 0 +#endif #endif // A function level attribute to disable checking for use of uninitialized // memory when built with MemorySanitizer. #if defined(__clang__) -# if __has_feature(memory_sanitizer) -# define GTEST_ATTRIBUTE_NO_SANITIZE_MEMORY_ \ - __attribute__((no_sanitize_memory)) -# else -# define GTEST_ATTRIBUTE_NO_SANITIZE_MEMORY_ -# endif // __has_feature(memory_sanitizer) +#if __has_feature(memory_sanitizer) +#define GTEST_ATTRIBUTE_NO_SANITIZE_MEMORY_ __attribute__((no_sanitize_memory)) +#else +#define GTEST_ATTRIBUTE_NO_SANITIZE_MEMORY_ +#endif // __has_feature(memory_sanitizer) #else -# define GTEST_ATTRIBUTE_NO_SANITIZE_MEMORY_ +#define GTEST_ATTRIBUTE_NO_SANITIZE_MEMORY_ #endif // __clang__ // A function level attribute to disable AddressSanitizer instrumentation. #if defined(__clang__) -# if __has_feature(address_sanitizer) -# define GTEST_ATTRIBUTE_NO_SANITIZE_ADDRESS_ \ - __attribute__((no_sanitize_address)) -# else -# define GTEST_ATTRIBUTE_NO_SANITIZE_ADDRESS_ -# endif // __has_feature(address_sanitizer) +#if __has_feature(address_sanitizer) +#define GTEST_ATTRIBUTE_NO_SANITIZE_ADDRESS_ \ + __attribute__((no_sanitize_address)) #else -# define GTEST_ATTRIBUTE_NO_SANITIZE_ADDRESS_ +#define GTEST_ATTRIBUTE_NO_SANITIZE_ADDRESS_ +#endif // __has_feature(address_sanitizer) +#else +#define GTEST_ATTRIBUTE_NO_SANITIZE_ADDRESS_ #endif // __clang__ // A function level attribute to disable HWAddressSanitizer instrumentation. #if defined(__clang__) -# if __has_feature(hwaddress_sanitizer) -# define GTEST_ATTRIBUTE_NO_SANITIZE_HWADDRESS_ \ - __attribute__((no_sanitize("hwaddress"))) -# else -# define GTEST_ATTRIBUTE_NO_SANITIZE_HWADDRESS_ -# endif // __has_feature(hwaddress_sanitizer) +#if __has_feature(hwaddress_sanitizer) +#define GTEST_ATTRIBUTE_NO_SANITIZE_HWADDRESS_ \ + __attribute__((no_sanitize("hwaddress"))) +#else +#define GTEST_ATTRIBUTE_NO_SANITIZE_HWADDRESS_ +#endif // __has_feature(hwaddress_sanitizer) #else -# define GTEST_ATTRIBUTE_NO_SANITIZE_HWADDRESS_ +#define GTEST_ATTRIBUTE_NO_SANITIZE_HWADDRESS_ #endif // __clang__ // A function level attribute to disable ThreadSanitizer instrumentation. #if defined(__clang__) -# if __has_feature(thread_sanitizer) -# define GTEST_ATTRIBUTE_NO_SANITIZE_THREAD_ \ - __attribute__((no_sanitize_thread)) -# else -# define GTEST_ATTRIBUTE_NO_SANITIZE_THREAD_ -# endif // __has_feature(thread_sanitizer) +#if __has_feature(thread_sanitizer) +#define GTEST_ATTRIBUTE_NO_SANITIZE_THREAD_ __attribute__((no_sanitize_thread)) #else -# define GTEST_ATTRIBUTE_NO_SANITIZE_THREAD_ +#define GTEST_ATTRIBUTE_NO_SANITIZE_THREAD_ +#endif // __has_feature(thread_sanitizer) +#else +#define GTEST_ATTRIBUTE_NO_SANITIZE_THREAD_ #endif // __clang__ namespace testing { @@ -937,16 +931,16 @@ class GTEST_API_ RE { const char* pattern_; bool is_valid_; -# if GTEST_USES_POSIX_RE +#if GTEST_USES_POSIX_RE regex_t full_regex_; // For FullMatch(). regex_t partial_regex_; // For PartialMatch(). -# else // GTEST_USES_SIMPLE_RE +#else // GTEST_USES_SIMPLE_RE const char* full_pattern_; // For FullMatch(); -# endif +#endif }; #endif // GTEST_USES_PCRE @@ -967,12 +961,7 @@ GTEST_API_ ::std::string FormatCompilerIndependentFileLocation(const char* file, // LogToStderr() - directs all log messages to stderr. // FlushInfoLog() - flushes informational log messages. -enum GTestLogSeverity { - GTEST_INFO, - GTEST_WARNING, - GTEST_ERROR, - GTEST_FATAL -}; +enum GTestLogSeverity { GTEST_INFO, GTEST_WARNING, GTEST_ERROR, GTEST_FATAL }; // Formats log entry severity, provides a stream object for streaming the // log message, and terminates the message with a newline when going out of @@ -994,9 +983,10 @@ class GTEST_API_ GTestLog { #if !defined(GTEST_LOG_) -# define GTEST_LOG_(severity) \ - ::testing::internal::GTestLog(::testing::internal::GTEST_##severity, \ - __FILE__, __LINE__).GetStream() +#define GTEST_LOG_(severity) \ + ::testing::internal::GTestLog(::testing::internal::GTEST_##severity, \ + __FILE__, __LINE__) \ + .GetStream() inline void LogToStderr() {} inline void FlushInfoLog() { fflush(nullptr); } @@ -1018,12 +1008,12 @@ inline void FlushInfoLog() { fflush(nullptr); } // condition itself, plus additional message streamed into it, if any, // and then it aborts the program. It aborts the program irrespective of // whether it is built in the debug mode or not. -# define GTEST_CHECK_(condition) \ - GTEST_AMBIGUOUS_ELSE_BLOCKER_ \ - if (::testing::internal::IsTrue(condition)) \ - ; \ - else \ - GTEST_LOG_(FATAL) << "Condition " #condition " failed. " +#define GTEST_CHECK_(condition) \ + GTEST_AMBIGUOUS_ELSE_BLOCKER_ \ + if (::testing::internal::IsTrue(condition)) \ + ; \ + else \ + GTEST_LOG_(FATAL) << "Condition " #condition " failed. " #endif // !defined(GTEST_CHECK_) // An all-mode assert to verify that the given POSIX-style function @@ -1032,9 +1022,8 @@ inline void FlushInfoLog() { fflush(nullptr); } // in {} if you need to use it as the only statement in an 'if' // branch. #define GTEST_CHECK_POSIX_SUCCESS_(posix_call) \ - if (const int gtest_error = (posix_call)) \ - GTEST_LOG_(FATAL) << #posix_call << "failed with error " \ - << gtest_error + if (const int gtest_error = (posix_call)) \ + GTEST_LOG_(FATAL) << #posix_call << "failed with error " << gtest_error // Transforms "T" into "const T&" according to standard reference collapsing // rules (this is only needed as a backport for C++98 compilers that do not @@ -1048,9 +1037,13 @@ inline void FlushInfoLog() { fflush(nullptr); } // Note that the non-const reference will not have "const" added. This is // standard, and necessary so that "T" can always bind to "const T&". template <typename T> -struct ConstRef { typedef const T& type; }; +struct ConstRef { + typedef const T& type; +}; template <typename T> -struct ConstRef<T&> { typedef T& type; }; +struct ConstRef<T&> { + typedef T& type; +}; // The argument T must depend on some template parameters. #define GTEST_REFERENCE_TO_CONST_(T) \ @@ -1076,8 +1069,10 @@ struct ConstRef<T&> { typedef T& type; }; // This relatively ugly name is intentional. It prevents clashes with // similar functions users may have (e.g., implicit_cast). The internal // namespace alone is not enough because the function can be found by ADL. -template<typename To> -inline To ImplicitCast_(To x) { return x; } +template <typename To> +inline To ImplicitCast_(To x) { + return x; +} // When you upcast (that is, cast a pointer from type Foo to type // SuperclassOfFoo), it's fine to use ImplicitCast_<>, since upcasts @@ -1100,17 +1095,17 @@ inline To ImplicitCast_(To x) { return x; } // This relatively ugly name is intentional. It prevents clashes with // similar functions users may have (e.g., down_cast). The internal // namespace alone is not enough because the function can be found by ADL. -template<typename To, typename From> // use like this: DownCast_<T*>(foo); -inline To DownCast_(From* f) { // so we only accept pointers +template <typename To, typename From> // use like this: DownCast_<T*>(foo); +inline To DownCast_(From* f) { // so we only accept pointers // Ensures that To is a sub-type of From *. This test is here only // for compile-time type checking, and has no overhead in an // optimized build at run-time, as it will be optimized away // completely. GTEST_INTENTIONAL_CONST_COND_PUSH_() if (false) { - GTEST_INTENTIONAL_CONST_COND_POP_() - const To to = nullptr; - ::testing::internal::ImplicitCast_<From*>(to); + GTEST_INTENTIONAL_CONST_COND_POP_() + const To to = nullptr; + ::testing::internal::ImplicitCast_<From*>(to); } #if GTEST_HAS_RTTI @@ -1176,7 +1171,7 @@ void ClearInjectableArgvs(); // Defines synchronization primitives. #if GTEST_IS_THREADSAFE -# if GTEST_OS_WINDOWS +#if GTEST_OS_WINDOWS // Provides leak-safe Windows kernel handle ownership. // Used in death tests and in threading support. class GTEST_API_ AutoHandle { @@ -1205,13 +1200,13 @@ class GTEST_API_ AutoHandle { GTEST_DISALLOW_COPY_AND_ASSIGN_(AutoHandle); }; -# endif +#endif -# if GTEST_HAS_NOTIFICATION_ +#if GTEST_HAS_NOTIFICATION_ // Notification has already been imported into the namespace. // Nothing to do here. -# else +#else // Allows a controller thread to pause execution of newly created // threads until notified. Instances of this class must be created // and destroyed in the controller thread. @@ -1245,12 +1240,12 @@ class GTEST_API_ Notification { std::condition_variable cv_; bool notified_; }; -# endif // GTEST_HAS_NOTIFICATION_ +#endif // GTEST_HAS_NOTIFICATION_ // On MinGW, we can have both GTEST_OS_WINDOWS and GTEST_HAS_PTHREAD // defined, but we don't want to use MinGW's pthreads implementation, which // has conformance problems with some versions of the POSIX standard. -# if GTEST_HAS_PTHREAD && !GTEST_OS_WINDOWS_MINGW +#if GTEST_HAS_PTHREAD && !GTEST_OS_WINDOWS_MINGW // As a C-function, ThreadFuncWithCLinkage cannot be templated itself. // Consequently, it cannot select a correct instantiation of ThreadWithParam @@ -1328,14 +1323,14 @@ class ThreadWithParam : public ThreadWithParamBase { GTEST_DISALLOW_COPY_AND_ASSIGN_(ThreadWithParam); }; -# endif // !GTEST_OS_WINDOWS && GTEST_HAS_PTHREAD || - // GTEST_HAS_MUTEX_AND_THREAD_LOCAL_ +#endif // !GTEST_OS_WINDOWS && GTEST_HAS_PTHREAD || + // GTEST_HAS_MUTEX_AND_THREAD_LOCAL_ -# if GTEST_HAS_MUTEX_AND_THREAD_LOCAL_ +#if GTEST_HAS_MUTEX_AND_THREAD_LOCAL_ // Mutex and ThreadLocal have already been imported into the namespace. // Nothing to do here. -# elif GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_PHONE && !GTEST_OS_WINDOWS_RT +#elif GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_PHONE && !GTEST_OS_WINDOWS_RT // Mutex implements mutex on Windows platforms. It is used in conjunction // with class MutexLock: @@ -1392,11 +1387,11 @@ class GTEST_API_ Mutex { GTEST_DISALLOW_COPY_AND_ASSIGN_(Mutex); }; -# define GTEST_DECLARE_STATIC_MUTEX_(mutex) \ - extern ::testing::internal::Mutex mutex +#define GTEST_DECLARE_STATIC_MUTEX_(mutex) \ + extern ::testing::internal::Mutex mutex -# define GTEST_DEFINE_STATIC_MUTEX_(mutex) \ - ::testing::internal::Mutex mutex(::testing::internal::Mutex::kStaticMutex) +#define GTEST_DEFINE_STATIC_MUTEX_(mutex) \ + ::testing::internal::Mutex mutex(::testing::internal::Mutex::kStaticMutex) // We cannot name this class MutexLock because the ctor declaration would // conflict with a macro named MutexLock, which is defined on some @@ -1405,8 +1400,7 @@ class GTEST_API_ Mutex { // "MutexLock l(&mu)". Hence the typedef trick below. class GTestMutexLock { public: - explicit GTestMutexLock(Mutex* mutex) - : mutex_(mutex) { mutex_->Lock(); } + explicit GTestMutexLock(Mutex* mutex) : mutex_(mutex) { mutex_->Lock(); } ~GTestMutexLock() { mutex_->Unlock(); } @@ -1469,7 +1463,7 @@ class GTEST_API_ ThreadWithParamBase { virtual void Run() = 0; }; - ThreadWithParamBase(Runnable *runnable, Notification* thread_can_start); + ThreadWithParamBase(Runnable* runnable, Notification* thread_can_start); virtual ~ThreadWithParamBase(); private: @@ -1483,21 +1477,15 @@ class ThreadWithParam : public ThreadWithParamBase { typedef void UserThreadFunc(T); ThreadWithParam(UserThreadFunc* func, T param, Notification* thread_can_start) - : ThreadWithParamBase(new RunnableImpl(func, param), thread_can_start) { - } + : ThreadWithParamBase(new RunnableImpl(func, param), thread_can_start) {} virtual ~ThreadWithParam() {} private: class RunnableImpl : public Runnable { public: - RunnableImpl(UserThreadFunc* func, T param) - : func_(func), - param_(param) { - } + RunnableImpl(UserThreadFunc* func, T param) : func_(func), param_(param) {} virtual ~RunnableImpl() {} - virtual void Run() { - func_(param_); - } + virtual void Run() { func_(param_); } private: UserThreadFunc* const func_; @@ -1565,10 +1553,10 @@ class ThreadLocal : public ThreadLocalBase { GTEST_DISALLOW_COPY_AND_ASSIGN_(ValueHolder); }; - T* GetOrCreateValue() const { return static_cast<ValueHolder*>( - ThreadLocalRegistry::GetValueOnCurrentThread(this))->pointer(); + ThreadLocalRegistry::GetValueOnCurrentThread(this)) + ->pointer(); } virtual ThreadLocalValueHolderBase* NewValueForCurrentThread() const { @@ -1612,7 +1600,7 @@ class ThreadLocal : public ThreadLocalBase { GTEST_DISALLOW_COPY_AND_ASSIGN_(ThreadLocal); }; -# elif GTEST_HAS_PTHREAD +#elif GTEST_HAS_PTHREAD // MutexBase and Mutex implement mutex on pthreads-based platforms. class MutexBase { @@ -1659,8 +1647,8 @@ class MutexBase { }; // Forward-declares a static mutex. -# define GTEST_DECLARE_STATIC_MUTEX_(mutex) \ - extern ::testing::internal::MutexBase mutex +#define GTEST_DECLARE_STATIC_MUTEX_(mutex) \ + extern ::testing::internal::MutexBase mutex // Defines and statically (i.e. at link time) initializes a static mutex. // The initialization list here does not explicitly initialize each field, @@ -1679,9 +1667,7 @@ class Mutex : public MutexBase { GTEST_CHECK_POSIX_SUCCESS_(pthread_mutex_init(&mutex_, nullptr)); has_owner_ = false; } - ~Mutex() { - GTEST_CHECK_POSIX_SUCCESS_(pthread_mutex_destroy(&mutex_)); - } + ~Mutex() { GTEST_CHECK_POSIX_SUCCESS_(pthread_mutex_destroy(&mutex_)); } private: GTEST_DISALLOW_COPY_AND_ASSIGN_(Mutex); @@ -1694,8 +1680,7 @@ class Mutex : public MutexBase { // "MutexLock l(&mu)". Hence the typedef trick below. class GTestMutexLock { public: - explicit GTestMutexLock(MutexBase* mutex) - : mutex_(mutex) { mutex_->Lock(); } + explicit GTestMutexLock(MutexBase* mutex) : mutex_(mutex) { mutex_->Lock(); } ~GTestMutexLock() { mutex_->Unlock(); } @@ -1823,7 +1808,7 @@ class GTEST_API_ ThreadLocal { GTEST_DISALLOW_COPY_AND_ASSIGN_(ThreadLocal); }; -# endif // GTEST_HAS_MUTEX_AND_THREAD_LOCAL_ +#endif // GTEST_HAS_MUTEX_AND_THREAD_LOCAL_ #else // GTEST_IS_THREADSAFE @@ -1840,10 +1825,10 @@ class Mutex { void AssertHeld() const {} }; -# define GTEST_DECLARE_STATIC_MUTEX_(mutex) \ +#define GTEST_DECLARE_STATIC_MUTEX_(mutex) \ extern ::testing::internal::Mutex mutex -# define GTEST_DEFINE_STATIC_MUTEX_(mutex) ::testing::internal::Mutex mutex +#define GTEST_DEFINE_STATIC_MUTEX_(mutex) ::testing::internal::Mutex mutex // We cannot name this class MutexLock because the ctor declaration would // conflict with a macro named MutexLock, which is defined on some @@ -1866,6 +1851,7 @@ class GTEST_API_ ThreadLocal { const T* pointer() const { return &value_; } const T& get() const { return value_; } void set(const T& value) { value_ = value; } + private: T value_; }; @@ -1877,11 +1863,11 @@ class GTEST_API_ ThreadLocal { GTEST_API_ size_t GetThreadCount(); #if GTEST_OS_WINDOWS -# define GTEST_PATH_SEP_ "\\" -# define GTEST_HAS_ALT_PATH_SEP_ 1 +#define GTEST_PATH_SEP_ "\\" +#define GTEST_HAS_ALT_PATH_SEP_ 1 #else -# define GTEST_PATH_SEP_ "/" -# define GTEST_HAS_ALT_PATH_SEP_ 0 +#define GTEST_PATH_SEP_ "/" +#define GTEST_HAS_ALT_PATH_SEP_ 0 #endif // GTEST_OS_WINDOWS // Utilities for char. @@ -1939,8 +1925,7 @@ inline char ToUpper(char ch) { inline std::string StripTrailingSpaces(std::string str) { std::string::iterator it = str.end(); - while (it != str.begin() && IsSpace(*--it)) - it = str.erase(it); + while (it != str.begin() && IsSpace(*--it)) it = str.erase(it); return str; } @@ -1958,36 +1943,34 @@ namespace posix { typedef struct _stat StatStruct; -# ifdef __BORLANDC__ +#ifdef __BORLANDC__ inline int DoIsATTY(int fd) { return isatty(fd); } inline int StrCaseCmp(const char* s1, const char* s2) { return stricmp(s1, s2); } inline char* StrDup(const char* src) { return strdup(src); } -# else // !__BORLANDC__ -# if GTEST_OS_WINDOWS_MOBILE +#else // !__BORLANDC__ +#if GTEST_OS_WINDOWS_MOBILE inline int DoIsATTY(int /* fd */) { return 0; } -# else +#else inline int DoIsATTY(int fd) { return _isatty(fd); } -# endif // GTEST_OS_WINDOWS_MOBILE +#endif // GTEST_OS_WINDOWS_MOBILE inline int StrCaseCmp(const char* s1, const char* s2) { return _stricmp(s1, s2); } inline char* StrDup(const char* src) { return _strdup(src); } -# endif // __BORLANDC__ +#endif // __BORLANDC__ -# if GTEST_OS_WINDOWS_MOBILE +#if GTEST_OS_WINDOWS_MOBILE inline int FileNo(FILE* file) { return reinterpret_cast<int>(_fileno(file)); } // Stat(), RmDir(), and IsDir() are not needed on Windows CE at this // time and thus not defined there. -# else +#else inline int FileNo(FILE* file) { return _fileno(file); } inline int Stat(const char* path, StatStruct* buf) { return _stat(path, buf); } inline int RmDir(const char* dir) { return _rmdir(dir); } -inline bool IsDir(const StatStruct& st) { - return (_S_IFDIR & st.st_mode) != 0; -} -# endif // GTEST_OS_WINDOWS_MOBILE +inline bool IsDir(const StatStruct& st) { return (_S_IFDIR & st.st_mode) != 0; } +#endif // GTEST_OS_WINDOWS_MOBILE #elif GTEST_OS_ESP8266 typedef struct stat StatStruct; @@ -2051,12 +2034,12 @@ inline FILE* FOpen(const char* path, const char* mode) { std::wstring wide_path = converter.from_bytes(path); std::wstring wide_mode = converter.from_bytes(mode); return _wfopen(wide_path.c_str(), wide_mode.c_str()); -#else // GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MINGW +#else // GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MINGW return fopen(path, mode); #endif // GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MINGW } #if !GTEST_OS_WINDOWS_MOBILE -inline FILE *FReopen(const char* path, const char* mode, FILE* stream) { +inline FILE* FReopen(const char* path, const char* mode, FILE* stream) { return freopen(path, mode, stream); } inline FILE* FDOpen(int fd, const char* mode) { return fdopen(fd, mode); } @@ -2108,13 +2091,13 @@ GTEST_DISABLE_MSC_DEPRECATED_POP_() // snprintf is a variadic function. #if _MSC_VER && !GTEST_OS_WINDOWS_MOBILE // MSVC 2005 and above support variadic macros. -# define GTEST_SNPRINTF_(buffer, size, format, ...) \ - _snprintf_s(buffer, size, size, format, __VA_ARGS__) +#define GTEST_SNPRINTF_(buffer, size, format, ...) \ + _snprintf_s(buffer, size, size, format, __VA_ARGS__) #elif defined(_MSC_VER) // Windows CE does not define _snprintf_s -# define GTEST_SNPRINTF_ _snprintf +#define GTEST_SNPRINTF_ _snprintf #else -# define GTEST_SNPRINTF_ snprintf +#define GTEST_SNPRINTF_ snprintf #endif // The biggest signed integer type the compiler supports. @@ -2174,43 +2157,49 @@ using TimeInMillis = int64_t; // Represents time in milliseconds. // Macro for referencing flags. #if !defined(GTEST_FLAG) -# define GTEST_FLAG(name) FLAGS_gtest_##name +#define GTEST_FLAG(name) FLAGS_gtest_##name #endif // !defined(GTEST_FLAG) #if !defined(GTEST_USE_OWN_FLAGFILE_FLAG_) -# define GTEST_USE_OWN_FLAGFILE_FLAG_ 1 +#define GTEST_USE_OWN_FLAGFILE_FLAG_ 1 #endif // !defined(GTEST_USE_OWN_FLAGFILE_FLAG_) #if !defined(GTEST_DECLARE_bool_) -# define GTEST_FLAG_SAVER_ ::testing::internal::GTestFlagSaver +#define GTEST_FLAG_SAVER_ ::testing::internal::GTestFlagSaver // Macros for declaring flags. #define GTEST_DECLARE_bool_(name) \ namespace testing { \ GTEST_API_ extern bool GTEST_FLAG(name); \ - } static_assert(true, "no-op to require trailing semicolon") + } \ + static_assert(true, "no-op to require trailing semicolon") #define GTEST_DECLARE_int32_(name) \ namespace testing { \ GTEST_API_ extern std::int32_t GTEST_FLAG(name); \ - } static_assert(true, "no-op to require trailing semicolon") + } \ + static_assert(true, "no-op to require trailing semicolon") #define GTEST_DECLARE_string_(name) \ namespace testing { \ GTEST_API_ extern ::std::string GTEST_FLAG(name); \ - } static_assert(true, "no-op to require trailing semicolon") + } \ + static_assert(true, "no-op to require trailing semicolon") // Macros for defining flags. #define GTEST_DEFINE_bool_(name, default_val, doc) \ namespace testing { \ GTEST_API_ bool GTEST_FLAG(name) = (default_val); \ - } static_assert(true, "no-op to require trailing semicolon") + } \ + static_assert(true, "no-op to require trailing semicolon") #define GTEST_DEFINE_int32_(name, default_val, doc) \ namespace testing { \ GTEST_API_ std::int32_t GTEST_FLAG(name) = (default_val); \ - } static_assert(true, "no-op to require trailing semicolon") + } \ + static_assert(true, "no-op to require trailing semicolon") #define GTEST_DEFINE_string_(name, default_val, doc) \ namespace testing { \ GTEST_API_ ::std::string GTEST_FLAG(name) = (default_val); \ - } static_assert(true, "no-op to require trailing semicolon") + } \ + static_assert(true, "no-op to require trailing semicolon") #endif // !defined(GTEST_DECLARE_bool_) @@ -2221,8 +2210,8 @@ using TimeInMillis = int64_t; // Represents time in milliseconds. // Thread annotations #if !defined(GTEST_EXCLUSIVE_LOCK_REQUIRED_) -# define GTEST_EXCLUSIVE_LOCK_REQUIRED_(locks) -# define GTEST_LOCK_EXCLUDED_(locks) +#define GTEST_EXCLUSIVE_LOCK_REQUIRED_(locks) +#define GTEST_LOCK_EXCLUDED_(locks) #endif // !defined(GTEST_EXCLUSIVE_LOCK_REQUIRED_) // Parses 'str' for a 32-bit signed integer. If successful, writes the result @@ -2324,7 +2313,7 @@ inline ::std::nullopt_t Nullopt() { return ::std::nullopt; } #if GTEST_HAS_ABSL // Always use absl::string_view for Matcher<> specializations if googletest // is built with absl support. -# define GTEST_INTERNAL_HAS_STRING_VIEW 1 +#define GTEST_INTERNAL_HAS_STRING_VIEW 1 #include "absl/strings/string_view.h" namespace testing { namespace internal { @@ -2332,11 +2321,11 @@ using StringView = ::absl::string_view; } // namespace internal } // namespace testing #else -# ifdef __has_include -# if __has_include(<string_view>) && __cplusplus >= 201703L +#ifdef __has_include +#if __has_include(<string_view>) && __cplusplus >= 201703L // Otherwise for C++17 and higher use std::string_view for Matcher<> // specializations. -# define GTEST_INTERNAL_HAS_STRING_VIEW 1 +#define GTEST_INTERNAL_HAS_STRING_VIEW 1 #include <string_view> namespace testing { namespace internal { @@ -2345,8 +2334,8 @@ using StringView = ::std::string_view; } // namespace testing // The case where absl is configured NOT to alias std::string_view is not // supported. -# endif // __has_include(<string_view>) && __cplusplus >= 201703L -# endif // __has_include +#endif // __has_include(<string_view>) && __cplusplus >= 201703L +#endif // __has_include #endif // GTEST_HAS_ABSL #if GTEST_HAS_ABSL @@ -2373,7 +2362,8 @@ template <typename... T> using Variant = ::std::variant<T...>; } // namespace internal } // namespace testing -// The case where absl is configured NOT to alias std::variant is not supported. + // The case where absl is configured NOT to alias std::variant is not + // supported. #endif // __has_include(<variant>) && __cplusplus >= 201703L #endif // __has_include #endif // GTEST_HAS_ABSL diff --git a/googletest/include/gtest/internal/gtest-string.h b/googletest/include/gtest/internal/gtest-string.h index 4cb8e07..cca2e1f 100644 --- a/googletest/include/gtest/internal/gtest-string.h +++ b/googletest/include/gtest/internal/gtest-string.h @@ -45,10 +45,11 @@ #ifdef __BORLANDC__ // string.h is not guaranteed to provide strcpy on C++ Builder. -# include <mem.h> +#include <mem.h> #endif #include <string.h> + #include <cstdint> #include <string> @@ -125,8 +126,7 @@ class GTEST_API_ String { // Unlike strcasecmp(), this function can handle NULL argument(s). // A NULL C string is considered different to any non-NULL C string, // including the empty string. - static bool CaseInsensitiveCStringEquals(const char* lhs, - const char* rhs); + static bool CaseInsensitiveCStringEquals(const char* lhs, const char* rhs); // Compares two wide C strings, ignoring case. Returns true if and only if // they have the same content. @@ -145,8 +145,8 @@ class GTEST_API_ String { // Returns true if and only if the given string ends with the given suffix, // ignoring case. Any string is considered to end with an empty suffix. - static bool EndsWithCaseInsensitive( - const std::string& str, const std::string& suffix); + static bool EndsWithCaseInsensitive(const std::string& str, + const std::string& suffix); // Formats an int value as "%02d". static std::string FormatIntWidth2(int value); // "%02d" for width == 2 @@ -165,7 +165,7 @@ class GTEST_API_ String { private: String(); // Not meant to be instantiated. -}; // class String +}; // class String // Gets the content of the stringstream's buffer as an std::string. Each '\0' // character in the buffer is replaced with "\\0". diff --git a/googletest/include/gtest/internal/gtest-type-util.h b/googletest/include/gtest/internal/gtest-type-util.h index 665564a..6bc02a7 100644 --- a/googletest/include/gtest/internal/gtest-type-util.h +++ b/googletest/include/gtest/internal/gtest-type-util.h @@ -41,11 +41,11 @@ // #ifdef __GNUC__ is too general here. It is possible to use gcc without using // libstdc++ (which is where cxxabi.h comes from). -# if GTEST_HAS_CXXABI_H_ -# include <cxxabi.h> -# elif defined(__HP_aCC) -# include <acxx_demangle.h> -# endif // GTEST_HASH_CXXABI_H_ +#if GTEST_HAS_CXXABI_H_ +#include <cxxabi.h> +#elif defined(__HP_aCC) +#include <acxx_demangle.h> +#endif // GTEST_HASH_CXXABI_H_ namespace testing { namespace internal { @@ -103,7 +103,9 @@ std::string GetTypeName() { // A unique type indicating an empty node struct None {}; -# define GTEST_TEMPLATE_ template <typename T> class +#define GTEST_TEMPLATE_ \ + template <typename T> \ + class // The template "selector" struct TemplateSel<Tmpl> is used to // represent Tmpl, which must be a class template with one type @@ -121,8 +123,7 @@ struct TemplateSel { }; }; -# define GTEST_BIND_(TmplSel, T) \ - TmplSel::template Bind<T>::type +#define GTEST_BIND_(TmplSel, T) TmplSel::template Bind<T>::type template <GTEST_TEMPLATE_ Head_, GTEST_TEMPLATE_... Tail_> struct Templates { diff --git a/googletest/samples/prime_tables.h b/googletest/samples/prime_tables.h index 3a10352..7c0286e 100644 --- a/googletest/samples/prime_tables.h +++ b/googletest/samples/prime_tables.h @@ -27,8 +27,6 @@ // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - - // This provides interface PrimeTable that determines whether a number is a // prime and determines a next prime number. This interface is used // in Google Test samples demonstrating use of parameterized tests. @@ -57,7 +55,7 @@ class OnTheFlyPrimeTable : public PrimeTable { bool IsPrime(int n) const override { if (n <= 1) return false; - for (int i = 2; i*i <= n; i++) { + for (int i = 2; i * i <= n; i++) { // n is divisible by an integer other than 1 and itself. if ((n % i) == 0) return false; } @@ -104,13 +102,13 @@ class PreCalculatedPrimeTable : public PrimeTable { // Checks every candidate for prime number (we know that 2 is the only even // prime). - for (int i = 2; i*i <= max; i += i%2+1) { + for (int i = 2; i * i <= max; i += i % 2 + 1) { if (!is_prime_[i]) continue; // Marks all multiples of i (except i itself) as non-prime. // We are starting here from i-th multiplier, because all smaller // complex numbers were already marked. - for (int j = i*i; j <= max; j += i) { + for (int j = i * i; j <= max; j += i) { is_prime_[j] = false; } } diff --git a/googletest/samples/sample1.cc b/googletest/samples/sample1.cc index 1d42759..80b69f4 100644 --- a/googletest/samples/sample1.cc +++ b/googletest/samples/sample1.cc @@ -52,9 +52,9 @@ bool IsPrime(int n) { // Now, we have that n is odd and n >= 3. // Try to divide n by every odd number i, starting from 3 - for (int i = 3; ; i += 2) { + for (int i = 3;; i += 2) { // We only have to try i up to the square root of n - if (i > n/i) break; + if (i > n / i) break; // Now, we have i <= n/i < n. // If n is divisible by i, n is not prime. diff --git a/googletest/samples/sample10_unittest.cc b/googletest/samples/sample10_unittest.cc index 36cdac2..95b4811 100644 --- a/googletest/samples/sample10_unittest.cc +++ b/googletest/samples/sample10_unittest.cc @@ -26,7 +26,6 @@ // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - // This sample shows how to use Google Test listener API to implement // a primitive leak checker. @@ -104,14 +103,15 @@ TEST(ListenersTest, LeaksWater) { } } // namespace -int main(int argc, char **argv) { +int main(int argc, char** argv) { InitGoogleTest(&argc, argv); bool check_for_leaks = false; - if (argc > 1 && strcmp(argv[1], "--check_for_leaks") == 0 ) + if (argc > 1 && strcmp(argv[1], "--check_for_leaks") == 0) check_for_leaks = true; else - printf("%s\n", "Run this program with --check_for_leaks to enable " + printf("%s\n", + "Run this program with --check_for_leaks to enable " "custom leak checking in the tests."); // If we are given the --check_for_leaks command line flag, installs the diff --git a/googletest/samples/sample1_unittest.cc b/googletest/samples/sample1_unittest.cc index cb08b61..60f2770 100644 --- a/googletest/samples/sample1_unittest.cc +++ b/googletest/samples/sample1_unittest.cc @@ -34,14 +34,15 @@ // // Writing a unit test using Google C++ testing framework is easy as 1-2-3: - // Step 1. Include necessary header files such that the stuff your // test logic needs is declared. // // Don't forget gtest.h, which declares the testing framework. -#include <limits.h> #include "sample1.h" + +#include <limits.h> + #include "gtest/gtest.h" namespace { @@ -69,7 +70,6 @@ namespace { // // </TechnicalDetails> - // Tests Factorial(). // Tests factorial of negative numbers. @@ -97,9 +97,7 @@ TEST(FactorialTest, Negative) { } // Tests factorial of 0. -TEST(FactorialTest, Zero) { - EXPECT_EQ(1, Factorial(0)); -} +TEST(FactorialTest, Zero) { EXPECT_EQ(1, Factorial(0)); } // Tests factorial of positive numbers. TEST(FactorialTest, Positive) { @@ -109,7 +107,6 @@ TEST(FactorialTest, Positive) { EXPECT_EQ(40320, Factorial(8)); } - // Tests IsPrime() // Tests negative input. diff --git a/googletest/samples/sample2.cc b/googletest/samples/sample2.cc index d8e8723..be7c4c9 100644 --- a/googletest/samples/sample2.cc +++ b/googletest/samples/sample2.cc @@ -38,7 +38,7 @@ const char* MyString::CloneCString(const char* a_c_string) { if (a_c_string == nullptr) return nullptr; const size_t len = strlen(a_c_string); - char* const clone = new char[ len + 1 ]; + char* const clone = new char[len + 1]; memcpy(clone, a_c_string, len + 1); return clone; diff --git a/googletest/samples/sample2.h b/googletest/samples/sample2.h index 0f98689..15a1ce7 100644 --- a/googletest/samples/sample2.h +++ b/googletest/samples/sample2.h @@ -34,7 +34,6 @@ #include <string.h> - // A simple string class. class MyString { private: diff --git a/googletest/samples/sample2_unittest.cc b/googletest/samples/sample2_unittest.cc index 41e31c1..cd734f9 100644 --- a/googletest/samples/sample2_unittest.cc +++ b/googletest/samples/sample2_unittest.cc @@ -38,6 +38,7 @@ // needed. #include "sample2.h" + #include "gtest/gtest.h" namespace { // In this example, we test the MyString class (a simple string). @@ -77,8 +78,7 @@ const char kHelloString[] = "Hello, world!"; TEST(MyString, ConstructorFromCString) { const MyString s(kHelloString); EXPECT_EQ(0, strcmp(s.c_string(), kHelloString)); - EXPECT_EQ(sizeof(kHelloString)/sizeof(kHelloString[0]) - 1, - s.Length()); + EXPECT_EQ(sizeof(kHelloString) / sizeof(kHelloString[0]) - 1, s.Length()); } // Tests the copy c'tor. diff --git a/googletest/samples/sample3-inl.h b/googletest/samples/sample3-inl.h index 659e0f0..bc3ffb9 100644 --- a/googletest/samples/sample3-inl.h +++ b/googletest/samples/sample3-inl.h @@ -34,7 +34,6 @@ #include <stddef.h> - // Queue is a simple queue implemented as a singled-linked list. // // The element type must support copy constructor. @@ -62,7 +61,7 @@ class QueueNode { : element_(an_element), next_(nullptr) {} // We disable the default assignment operator and copy c'tor. - const QueueNode& operator = (const QueueNode&); + const QueueNode& operator=(const QueueNode&); QueueNode(const QueueNode&); E element_; @@ -84,7 +83,7 @@ class Queue { // 1. Deletes every node. QueueNode<E>* node = head_; QueueNode<E>* next = node->next(); - for (; ;) { + for (;;) { delete node; node = next; if (node == nullptr) break; @@ -162,11 +161,11 @@ class Queue { private: QueueNode<E>* head_; // The first node of the queue. QueueNode<E>* last_; // The last node of the queue. - size_t size_; // The number of elements in the queue. + size_t size_; // The number of elements in the queue. // We disallow copying a queue. Queue(const Queue&); - const Queue& operator = (const Queue&); + const Queue& operator=(const Queue&); }; #endif // GOOGLETEST_SAMPLES_SAMPLE3_INL_H_ diff --git a/googletest/samples/sample3_unittest.cc b/googletest/samples/sample3_unittest.cc index b19416d..71609c6 100644 --- a/googletest/samples/sample3_unittest.cc +++ b/googletest/samples/sample3_unittest.cc @@ -67,7 +67,6 @@ namespace { class QueueTestSmpl3 : public testing::Test { protected: // You should make the members protected s.t. they can be // accessed from sub-classes. - // virtual void SetUp() will be called before each test is run. You // should define it if you need to initialize the variables. // Otherwise, this can be skipped. @@ -85,15 +84,13 @@ class QueueTestSmpl3 : public testing::Test { // } // A helper function that some test uses. - static int Double(int n) { - return 2*n; - } + static int Double(int n) { return 2 * n; } // A helper function for testing Queue::Map(). - void MapTester(const Queue<int> * q) { + void MapTester(const Queue<int>* q) { // Creates a new queue, where each element is twice as big as the // corresponding one in q. - const Queue<int> * const new_q = q->Map(Double); + const Queue<int>* const new_q = q->Map(Double); // Verifies that the new queue has the same size as q. ASSERT_EQ(q->Size(), new_q->Size()); @@ -124,7 +121,7 @@ TEST_F(QueueTestSmpl3, DefaultConstructor) { // Tests Dequeue(). TEST_F(QueueTestSmpl3, Dequeue) { - int * n = q0_.Dequeue(); + int* n = q0_.Dequeue(); EXPECT_TRUE(n == nullptr); n = q1_.Dequeue(); diff --git a/googletest/samples/sample4.cc b/googletest/samples/sample4.cc index b0ee609..489c89b 100644 --- a/googletest/samples/sample4.cc +++ b/googletest/samples/sample4.cc @@ -29,26 +29,22 @@ // A sample program demonstrating using Google C++ testing framework. -#include <stdio.h> - #include "sample4.h" +#include <stdio.h> + // Returns the current counter value, and increments it. -int Counter::Increment() { - return counter_++; -} +int Counter::Increment() { return counter_++; } // Returns the current counter value, and decrements it. // counter can not be less than 0, return 0 in this case int Counter::Decrement() { if (counter_ == 0) { return counter_; - } else { + } else { return counter_--; } } // Prints the current counter value to STDOUT. -void Counter::Print() const { - printf("%d", counter_); -} +void Counter::Print() const { printf("%d", counter_); } diff --git a/googletest/samples/sample4_unittest.cc b/googletest/samples/sample4_unittest.cc index d5144c0..fb9973f 100644 --- a/googletest/samples/sample4_unittest.cc +++ b/googletest/samples/sample4_unittest.cc @@ -27,8 +27,8 @@ // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - #include "sample4.h" + #include "gtest/gtest.h" namespace { diff --git a/googletest/samples/sample5_unittest.cc b/googletest/samples/sample5_unittest.cc index 0a21dd2..cc8c0f0 100644 --- a/googletest/samples/sample5_unittest.cc +++ b/googletest/samples/sample5_unittest.cc @@ -27,7 +27,6 @@ // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - // This sample teaches how to reuse a test fixture in multiple test // cases by deriving sub-fixtures from it. // @@ -45,9 +44,10 @@ #include <limits.h> #include <time.h> -#include "gtest/gtest.h" + #include "sample1.h" #include "sample3-inl.h" +#include "gtest/gtest.h" namespace { // In this sample, we want to ensure that every test finishes within // ~5 seconds. If a test takes longer to run, we consider it a @@ -81,7 +81,6 @@ class QuickTest : public testing::Test { time_t start_time_; }; - // We derive a fixture named IntegerFunctionTest from the QuickTest // fixture. All tests using this fixture will be automatically // required to be quick. @@ -90,7 +89,6 @@ class IntegerFunctionTest : public QuickTest { // Therefore the body is empty. }; - // Now we can write tests in the IntegerFunctionTest test case. // Tests Factorial() @@ -110,7 +108,6 @@ TEST_F(IntegerFunctionTest, Factorial) { EXPECT_EQ(40320, Factorial(8)); } - // Tests IsPrime() TEST_F(IntegerFunctionTest, IsPrime) { // Tests negative input. @@ -131,7 +128,6 @@ TEST_F(IntegerFunctionTest, IsPrime) { EXPECT_TRUE(IsPrime(23)); } - // The next test case (named "QueueTest") also needs to be quick, so // we derive another fixture from QuickTest. // @@ -163,13 +159,10 @@ class QueueTest : public QuickTest { Queue<int> q2_; }; - // Now, let's write tests using the QueueTest fixture. // Tests the default constructor. -TEST_F(QueueTest, DefaultConstructor) { - EXPECT_EQ(0u, q0_.Size()); -} +TEST_F(QueueTest, DefaultConstructor) { EXPECT_EQ(0u, q0_.Size()); } // Tests Dequeue(). TEST_F(QueueTest, Dequeue) { diff --git a/googletest/samples/sample6_unittest.cc b/googletest/samples/sample6_unittest.cc index da317ee..cf576f0 100644 --- a/googletest/samples/sample6_unittest.cc +++ b/googletest/samples/sample6_unittest.cc @@ -27,13 +27,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. - // This sample shows how to test common properties of multiple // implementations of the same interface (aka interface tests). // The interface and its implementations are in this header. #include "prime_tables.h" - #include "gtest/gtest.h" namespace { // First, we define some factory functions for creating instances of @@ -151,8 +149,7 @@ using testing::Types; // the PrimeTableTest fixture defined earlier: template <class T> -class PrimeTableTest2 : public PrimeTableTest<T> { -}; +class PrimeTableTest2 : public PrimeTableTest<T> {}; // Then, declare the test case. The argument is the name of the test // fixture, and also the name of the test case (as usual). The _P diff --git a/googletest/samples/sample7_unittest.cc b/googletest/samples/sample7_unittest.cc index e0efc29..3ad22ca 100644 --- a/googletest/samples/sample7_unittest.cc +++ b/googletest/samples/sample7_unittest.cc @@ -27,7 +27,6 @@ // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - // This sample shows how to test common properties of multiple // implementations of an interface (aka interface tests) using // value-parameterized tests. Each test in the test case has @@ -36,7 +35,6 @@ // The interface and its implementations are in this header. #include "prime_tables.h" - #include "gtest/gtest.h" namespace { @@ -50,9 +48,7 @@ using ::testing::Values; // SetUp() method and delete them in TearDown() method. typedef PrimeTable* CreatePrimeTableFunc(); -PrimeTable* CreateOnTheFlyPrimeTable() { - return new OnTheFlyPrimeTable(); -} +PrimeTable* CreateOnTheFlyPrimeTable() { return new OnTheFlyPrimeTable(); } template <size_t max_precalculated> PrimeTable* CreatePreCalculatedPrimeTable() { diff --git a/googletest/samples/sample8_unittest.cc b/googletest/samples/sample8_unittest.cc index 10488b0..9717e28 100644 --- a/googletest/samples/sample8_unittest.cc +++ b/googletest/samples/sample8_unittest.cc @@ -27,14 +27,12 @@ // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - // This sample shows how to test code relying on some global flag variables. // Combine() helps with generating all possible combinations of such flags, // and each test is given one combination as a parameter. // Use class definitions to test from this header. #include "prime_tables.h" - #include "gtest/gtest.h" namespace { @@ -79,10 +77,10 @@ class HybridPrimeTable : public PrimeTable { int max_precalculated_; }; -using ::testing::TestWithParam; using ::testing::Bool; -using ::testing::Values; using ::testing::Combine; +using ::testing::TestWithParam; +using ::testing::Values; // To test all code paths for HybridPrimeTable we must test it with numbers // both within and outside PreCalculatedPrimeTable's capacity and also with diff --git a/googletest/samples/sample9_unittest.cc b/googletest/samples/sample9_unittest.cc index 0245b53..d627ea7 100644 --- a/googletest/samples/sample9_unittest.cc +++ b/googletest/samples/sample9_unittest.cc @@ -26,7 +26,6 @@ // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - // This sample shows how to use Google Test listener API to implement // an alternative console output and how to use the UnitTest reflection API // to enumerate test suites and tests and to inspect their results. @@ -38,10 +37,10 @@ using ::testing::EmptyTestEventListener; using ::testing::InitGoogleTest; using ::testing::Test; -using ::testing::TestSuite; using ::testing::TestEventListeners; using ::testing::TestInfo; using ::testing::TestPartResult; +using ::testing::TestSuite; using ::testing::UnitTest; namespace { // Provides alternative output mode which produces minimal amount of @@ -59,29 +58,23 @@ class TersePrinter : public EmptyTestEventListener { // Called before a test starts. void OnTestStart(const TestInfo& test_info) override { - fprintf(stdout, - "*** Test %s.%s starting.\n", - test_info.test_suite_name(), + fprintf(stdout, "*** Test %s.%s starting.\n", test_info.test_suite_name(), test_info.name()); fflush(stdout); } // Called after a failed assertion or a SUCCEED() invocation. void OnTestPartResult(const TestPartResult& test_part_result) override { - fprintf(stdout, - "%s in %s:%d\n%s\n", + fprintf(stdout, "%s in %s:%d\n%s\n", test_part_result.failed() ? "*** Failure" : "Success", - test_part_result.file_name(), - test_part_result.line_number(), + test_part_result.file_name(), test_part_result.line_number(), test_part_result.summary()); fflush(stdout); } // Called after a test ends. void OnTestEnd(const TestInfo& test_info) override { - fprintf(stdout, - "*** Test %s.%s ending.\n", - test_info.test_suite_name(), + fprintf(stdout, "*** Test %s.%s ending.\n", test_info.test_suite_name(), test_info.name()); fflush(stdout); } @@ -101,14 +94,15 @@ TEST(CustomOutputTest, Fails) { } } // namespace -int main(int argc, char **argv) { +int main(int argc, char** argv) { InitGoogleTest(&argc, argv); bool terse_output = false; - if (argc > 1 && strcmp(argv[1], "--terse_output") == 0 ) + if (argc > 1 && strcmp(argv[1], "--terse_output") == 0) terse_output = true; else - printf("%s\n", "Run this program with --terse_output to change the way " + printf("%s\n", + "Run this program with --terse_output to change the way " "it prints its output."); UnitTest& unit_test = *UnitTest::GetInstance(); @@ -149,8 +143,7 @@ int main(int argc, char **argv) { } // Test that were meant to fail should not affect the test program outcome. - if (unexpectedly_failed_tests == 0) - ret_val = 0; + if (unexpectedly_failed_tests == 0) ret_val = 0; return ret_val; } diff --git a/googletest/src/gtest-all.cc b/googletest/src/gtest-all.cc index 29eba16..2a70ed8 100644 --- a/googletest/src/gtest-all.cc +++ b/googletest/src/gtest-all.cc @@ -38,7 +38,6 @@ #include "gtest/gtest.h" // The following lines pull in the real gtest *.cc files. -#include "src/gtest.cc" #include "src/gtest-assertion-result.cc" #include "src/gtest-death-test.cc" #include "src/gtest-filepath.cc" @@ -47,3 +46,4 @@ #include "src/gtest-printers.cc" #include "src/gtest-test-part.cc" #include "src/gtest-typed-test.cc" +#include "src/gtest.cc" diff --git a/googletest/src/gtest-assertion-result.cc b/googletest/src/gtest-assertion-result.cc index 9f90e87..f1c0b10 100644 --- a/googletest/src/gtest-assertion-result.cc +++ b/googletest/src/gtest-assertion-result.cc @@ -33,8 +33,8 @@ #include "gtest/gtest-assertion-result.h" -#include <utility> #include <string> +#include <utility> #include "gtest/gtest-message.h" @@ -63,14 +63,10 @@ AssertionResult AssertionResult::operator!() const { } // Makes a successful assertion result. -AssertionResult AssertionSuccess() { - return AssertionResult(true); -} +AssertionResult AssertionSuccess() { return AssertionResult(true); } // Makes a failed assertion result. -AssertionResult AssertionFailure() { - return AssertionResult(false); -} +AssertionResult AssertionFailure() { return AssertionResult(false); } // Makes a failed assertion result with the given failure message. // Deprecated; use AssertionFailure() << message. diff --git a/googletest/src/gtest-death-test.cc b/googletest/src/gtest-death-test.cc index 87d5e9b..e6abc62 100644 --- a/googletest/src/gtest-death-test.cc +++ b/googletest/src/gtest-death-test.cc @@ -35,49 +35,49 @@ #include <functional> #include <utility> -#include "gtest/internal/gtest-port.h" #include "gtest/internal/custom/gtest.h" +#include "gtest/internal/gtest-port.h" #if GTEST_HAS_DEATH_TEST -# if GTEST_OS_MAC -# include <crt_externs.h> -# endif // GTEST_OS_MAC - -# include <errno.h> -# include <fcntl.h> -# include <limits.h> - -# if GTEST_OS_LINUX -# include <signal.h> -# endif // GTEST_OS_LINUX - -# include <stdarg.h> - -# if GTEST_OS_WINDOWS -# include <windows.h> -# else -# include <sys/mman.h> -# include <sys/wait.h> -# endif // GTEST_OS_WINDOWS - -# if GTEST_OS_QNX -# include <spawn.h> -# endif // GTEST_OS_QNX - -# if GTEST_OS_FUCHSIA -# include <lib/fdio/fd.h> -# include <lib/fdio/io.h> -# include <lib/fdio/spawn.h> -# include <lib/zx/channel.h> -# include <lib/zx/port.h> -# include <lib/zx/process.h> -# include <lib/zx/socket.h> -# include <zircon/processargs.h> -# include <zircon/syscalls.h> -# include <zircon/syscalls/policy.h> -# include <zircon/syscalls/port.h> -# endif // GTEST_OS_FUCHSIA +#if GTEST_OS_MAC +#include <crt_externs.h> +#endif // GTEST_OS_MAC + +#include <errno.h> +#include <fcntl.h> +#include <limits.h> + +#if GTEST_OS_LINUX +#include <signal.h> +#endif // GTEST_OS_LINUX + +#include <stdarg.h> + +#if GTEST_OS_WINDOWS +#include <windows.h> +#else +#include <sys/mman.h> +#include <sys/wait.h> +#endif // GTEST_OS_WINDOWS + +#if GTEST_OS_QNX +#include <spawn.h> +#endif // GTEST_OS_QNX + +#if GTEST_OS_FUCHSIA +#include <lib/fdio/fd.h> +#include <lib/fdio/io.h> +#include <lib/fdio/spawn.h> +#include <lib/zx/channel.h> +#include <lib/zx/port.h> +#include <lib/zx/process.h> +#include <lib/zx/socket.h> +#include <zircon/processargs.h> +#include <zircon/syscalls.h> +#include <zircon/syscalls/policy.h> +#include <zircon/syscalls/port.h> +#endif // GTEST_OS_FUCHSIA #endif // GTEST_HAS_DEATH_TEST @@ -137,9 +137,9 @@ namespace internal { // Valid only for fast death tests. Indicates the code is running in the // child process of a fast style death test. -# if !GTEST_OS_WINDOWS && !GTEST_OS_FUCHSIA +#if !GTEST_OS_WINDOWS && !GTEST_OS_FUCHSIA static bool g_in_fast_death_test_child = false; -# endif +#endif // Returns a Boolean value indicating whether the caller is currently // executing in the context of the death test child process. Tools such as @@ -147,13 +147,13 @@ static bool g_in_fast_death_test_child = false; // tests. IMPORTANT: This is an internal utility. Using it may break the // implementation of death tests. User code MUST NOT use it. bool InDeathTestChild() { -# if GTEST_OS_WINDOWS || GTEST_OS_FUCHSIA +#if GTEST_OS_WINDOWS || GTEST_OS_FUCHSIA // On Windows and Fuchsia, death tests are thread-safe regardless of the value // of the death_test_style flag. return !GTEST_FLAG_GET(internal_run_death_test).empty(); -# else +#else if (GTEST_FLAG_GET(death_test_style) == "threadsafe") return !GTEST_FLAG_GET(internal_run_death_test).empty(); @@ -165,40 +165,38 @@ bool InDeathTestChild() { } // namespace internal // ExitedWithCode constructor. -ExitedWithCode::ExitedWithCode(int exit_code) : exit_code_(exit_code) { -} +ExitedWithCode::ExitedWithCode(int exit_code) : exit_code_(exit_code) {} // ExitedWithCode function-call operator. bool ExitedWithCode::operator()(int exit_status) const { -# if GTEST_OS_WINDOWS || GTEST_OS_FUCHSIA +#if GTEST_OS_WINDOWS || GTEST_OS_FUCHSIA return exit_status == exit_code_; -# else +#else return WIFEXITED(exit_status) && WEXITSTATUS(exit_status) == exit_code_; -# endif // GTEST_OS_WINDOWS || GTEST_OS_FUCHSIA +#endif // GTEST_OS_WINDOWS || GTEST_OS_FUCHSIA } -# if !GTEST_OS_WINDOWS && !GTEST_OS_FUCHSIA +#if !GTEST_OS_WINDOWS && !GTEST_OS_FUCHSIA // KilledBySignal constructor. -KilledBySignal::KilledBySignal(int signum) : signum_(signum) { -} +KilledBySignal::KilledBySignal(int signum) : signum_(signum) {} // KilledBySignal function-call operator. bool KilledBySignal::operator()(int exit_status) const { -# if defined(GTEST_KILLED_BY_SIGNAL_OVERRIDE_) +#if defined(GTEST_KILLED_BY_SIGNAL_OVERRIDE_) { bool result; if (GTEST_KILLED_BY_SIGNAL_OVERRIDE_(signum_, exit_status, &result)) { return result; } } -# endif // defined(GTEST_KILLED_BY_SIGNAL_OVERRIDE_) +#endif // defined(GTEST_KILLED_BY_SIGNAL_OVERRIDE_) return WIFSIGNALED(exit_status) && WTERMSIG(exit_status) == signum_; } -# endif // !GTEST_OS_WINDOWS && !GTEST_OS_FUCHSIA +#endif // !GTEST_OS_WINDOWS && !GTEST_OS_FUCHSIA namespace internal { @@ -209,23 +207,23 @@ namespace internal { static std::string ExitSummary(int exit_code) { Message m; -# if GTEST_OS_WINDOWS || GTEST_OS_FUCHSIA +#if GTEST_OS_WINDOWS || GTEST_OS_FUCHSIA m << "Exited with exit status " << exit_code; -# else +#else if (WIFEXITED(exit_code)) { m << "Exited with exit status " << WEXITSTATUS(exit_code); } else if (WIFSIGNALED(exit_code)) { m << "Terminated by signal " << WTERMSIG(exit_code); } -# ifdef WCOREDUMP +#ifdef WCOREDUMP if (WCOREDUMP(exit_code)) { m << " (core dumped)"; } -# endif -# endif // GTEST_OS_WINDOWS || GTEST_OS_FUCHSIA +#endif +#endif // GTEST_OS_WINDOWS || GTEST_OS_FUCHSIA return m.GetString(); } @@ -236,7 +234,7 @@ bool ExitedUnsuccessfully(int exit_status) { return !ExitedWithCode(0)(exit_status); } -# if !GTEST_OS_WINDOWS && !GTEST_OS_FUCHSIA +#if !GTEST_OS_WINDOWS && !GTEST_OS_FUCHSIA // Generates a textual failure message when a death test finds more than // one thread running, or cannot determine the number of threads, prior // to executing the given statement. It is the responsibility of the @@ -257,7 +255,7 @@ static std::string DeathTestThreadWarning(size_t thread_count) { << " this is the last message you see before your test times out."; return msg.GetString(); } -# endif // !GTEST_OS_WINDOWS && !GTEST_OS_FUCHSIA +#endif // !GTEST_OS_WINDOWS && !GTEST_OS_FUCHSIA // Flag characters for reporting a death test that did not die. static const char kDeathTestLived = 'L'; @@ -307,14 +305,14 @@ static void DeathTestAbort(const std::string& message) { // A replacement for CHECK that calls DeathTestAbort if the assertion // fails. -# define GTEST_DEATH_TEST_CHECK_(expression) \ - do { \ - if (!::testing::internal::IsTrue(expression)) { \ - DeathTestAbort( \ - ::std::string("CHECK failed: File ") + __FILE__ + ", line " \ - + ::testing::internal::StreamableToString(__LINE__) + ": " \ - + #expression); \ - } \ +#define GTEST_DEATH_TEST_CHECK_(expression) \ + do { \ + if (!::testing::internal::IsTrue(expression)) { \ + DeathTestAbort(::std::string("CHECK failed: File ") + __FILE__ + \ + ", line " + \ + ::testing::internal::StreamableToString(__LINE__) + \ + ": " + #expression); \ + } \ } while (::testing::internal::AlwaysFalse()) // This macro is similar to GTEST_DEATH_TEST_CHECK_, but it is meant for @@ -324,23 +322,23 @@ static void DeathTestAbort(const std::string& message) { // evaluates the expression as long as it evaluates to -1 and sets // errno to EINTR. If the expression evaluates to -1 but errno is // something other than EINTR, DeathTestAbort is called. -# define GTEST_DEATH_TEST_CHECK_SYSCALL_(expression) \ - do { \ - int gtest_retval; \ - do { \ - gtest_retval = (expression); \ - } while (gtest_retval == -1 && errno == EINTR); \ - if (gtest_retval == -1) { \ - DeathTestAbort( \ - ::std::string("CHECK failed: File ") + __FILE__ + ", line " \ - + ::testing::internal::StreamableToString(__LINE__) + ": " \ - + #expression + " != -1"); \ - } \ +#define GTEST_DEATH_TEST_CHECK_SYSCALL_(expression) \ + do { \ + int gtest_retval; \ + do { \ + gtest_retval = (expression); \ + } while (gtest_retval == -1 && errno == EINTR); \ + if (gtest_retval == -1) { \ + DeathTestAbort(::std::string("CHECK failed: File ") + __FILE__ + \ + ", line " + \ + ::testing::internal::StreamableToString(__LINE__) + \ + ": " + #expression + " != -1"); \ + } \ } while (::testing::internal::AlwaysFalse()) // Returns the message describing the last system error in errno. std::string GetLastErrnoDescription() { - return errno == 0 ? "" : posix::StrError(errno); + return errno == 0 ? "" : posix::StrError(errno); } // This is called from a death test parent process to read a failure @@ -373,8 +371,9 @@ static void FailFromInternalError(int fd) { DeathTest::DeathTest() { TestInfo* const info = GetUnitTestImpl()->current_test_info(); if (info == nullptr) { - DeathTestAbort("Cannot run a death test outside of a TEST or " - "TEST_F construct"); + DeathTestAbort( + "Cannot run a death test outside of a TEST or " + "TEST_F construct"); } } @@ -503,9 +502,7 @@ void DeathTestImpl::ReadAndInterpretStatusByte() { set_read_fd(-1); } -std::string DeathTestImpl::GetErrorLogs() { - return GetCapturedStderr(); -} +std::string DeathTestImpl::GetErrorLogs() { return GetCapturedStderr(); } // Signals that the death test code which should have exited, didn't. // Should be called only in a death test child process. @@ -515,9 +512,9 @@ void DeathTestImpl::Abort(AbortReason reason) { // The parent process considers the death test to be a failure if // it finds any data in our pipe. So, here we write a single flag byte // to the pipe, then exit. - const char status_ch = - reason == TEST_DID_NOT_DIE ? kDeathTestLived : - reason == TEST_THREW_EXCEPTION ? kDeathTestThrew : kDeathTestReturned; + const char status_ch = reason == TEST_DID_NOT_DIE ? kDeathTestLived + : reason == TEST_THREW_EXCEPTION ? kDeathTestThrew + : kDeathTestReturned; GTEST_DEATH_TEST_CHECK_SYSCALL_(posix::Write(write_fd(), &status_ch, 1)); // We are leaking the descriptor here because on some platforms (i.e., @@ -536,7 +533,7 @@ void DeathTestImpl::Abort(AbortReason reason) { // much easier. static ::std::string FormatDeathTestOutput(const ::std::string& output) { ::std::string ret; - for (size_t at = 0; ; ) { + for (size_t at = 0;;) { const size_t line_end = output.find('\n', at); ret += "[ DEATH ] "; if (line_end == ::std::string::npos) { @@ -571,8 +568,7 @@ static ::std::string FormatDeathTestOutput(const ::std::string& output) { // the first failing condition, in the order given above, is the one that is // reported. Also sets the last death test message string. bool DeathTestImpl::Passed(bool status_ok) { - if (!spawned()) - return false; + if (!spawned()) return false; const std::string error_message = GetErrorLogs(); @@ -583,15 +579,18 @@ bool DeathTestImpl::Passed(bool status_ok) { switch (outcome()) { case LIVED: buffer << " Result: failed to die.\n" - << " Error msg:\n" << FormatDeathTestOutput(error_message); + << " Error msg:\n" + << FormatDeathTestOutput(error_message); break; case THREW: buffer << " Result: threw an exception.\n" - << " Error msg:\n" << FormatDeathTestOutput(error_message); + << " Error msg:\n" + << FormatDeathTestOutput(error_message); break; case RETURNED: buffer << " Result: illegal return in test statement.\n" - << " Error msg:\n" << FormatDeathTestOutput(error_message); + << " Error msg:\n" + << FormatDeathTestOutput(error_message); break; case DIED: if (status_ok) { @@ -608,7 +607,8 @@ bool DeathTestImpl::Passed(bool status_ok) { } else { buffer << " Result: died but not with expected exit code:\n" << " " << ExitSummary(status()) << "\n" - << "Actual msg:\n" << FormatDeathTestOutput(error_message); + << "Actual msg:\n" + << FormatDeathTestOutput(error_message); } break; case IN_PROGRESS: @@ -621,7 +621,7 @@ bool DeathTestImpl::Passed(bool status_ok) { return success; } -# if GTEST_OS_WINDOWS +#if GTEST_OS_WINDOWS // WindowsDeathTest implements death tests on Windows. Due to the // specifics of starting new processes on Windows, death tests there are // always threadsafe, and Google Test considers the @@ -682,14 +682,12 @@ class WindowsDeathTest : public DeathTestImpl { // status, or 0 if no child process exists. As a side effect, sets the // outcome data member. int WindowsDeathTest::Wait() { - if (!spawned()) - return 0; + if (!spawned()) return 0; // Wait until the child either signals that it has acquired the write end // of the pipe or it dies. - const HANDLE wait_handles[2] = { child_handle_.Get(), event_handle_.Get() }; - switch (::WaitForMultipleObjects(2, - wait_handles, + const HANDLE wait_handles[2] = {child_handle_.Get(), event_handle_.Get()}; + switch (::WaitForMultipleObjects(2, wait_handles, FALSE, // Waits for any of the handles. INFINITE)) { case WAIT_OBJECT_0: @@ -710,9 +708,8 @@ int WindowsDeathTest::Wait() { // returns immediately if the child has already exited, regardless of // whether previous calls to WaitForMultipleObjects synchronized on this // handle or not. - GTEST_DEATH_TEST_CHECK_( - WAIT_OBJECT_0 == ::WaitForSingleObject(child_handle_.Get(), - INFINITE)); + GTEST_DEATH_TEST_CHECK_(WAIT_OBJECT_0 == + ::WaitForSingleObject(child_handle_.Get(), INFINITE)); DWORD status_code; GTEST_DEATH_TEST_CHECK_( ::GetExitCodeProcess(child_handle_.Get(), &status_code) != FALSE); @@ -745,12 +742,12 @@ DeathTest::TestRole WindowsDeathTest::AssumeRole() { SECURITY_ATTRIBUTES handles_are_inheritable = {sizeof(SECURITY_ATTRIBUTES), nullptr, TRUE}; HANDLE read_handle, write_handle; - GTEST_DEATH_TEST_CHECK_( - ::CreatePipe(&read_handle, &write_handle, &handles_are_inheritable, - 0) // Default buffer size. - != FALSE); - set_read_fd(::_open_osfhandle(reinterpret_cast<intptr_t>(read_handle), - O_RDONLY)); + GTEST_DEATH_TEST_CHECK_(::CreatePipe(&read_handle, &write_handle, + &handles_are_inheritable, + 0) // Default buffer size. + != FALSE); + set_read_fd( + ::_open_osfhandle(reinterpret_cast<intptr_t>(read_handle), O_RDONLY)); write_handle_.Reset(write_handle); event_handle_.Reset(::CreateEvent( &handles_are_inheritable, @@ -777,9 +774,8 @@ DeathTest::TestRole WindowsDeathTest::AssumeRole() { executable_path, _MAX_PATH)); - std::string command_line = - std::string(::GetCommandLineA()) + " " + filter_flag + " \"" + - internal_flag + "\""; + std::string command_line = std::string(::GetCommandLineA()) + " " + + filter_flag + " \"" + internal_flag + "\""; DeathTest::set_last_death_test_message(""); @@ -812,7 +808,7 @@ DeathTest::TestRole WindowsDeathTest::AssumeRole() { return OVERSEE_TEST; } -# elif GTEST_OS_FUCHSIA +#elif GTEST_OS_FUCHSIA class FuchsiaDeathTest : public DeathTestImpl { public: @@ -858,18 +854,13 @@ class Arguments { template <typename Str> void AddArguments(const ::std::vector<Str>& arguments) { for (typename ::std::vector<Str>::const_iterator i = arguments.begin(); - i != arguments.end(); - ++i) { + i != arguments.end(); ++i) { args_.insert(args_.end() - 1, posix::StrDup(i->c_str())); } } - char* const* Argv() { - return &args_[0]; - } + char* const* Argv() { return &args_[0]; } - int size() { - return static_cast<int>(args_.size()) - 1; - } + int size() { return static_cast<int>(args_.size()) - 1; } private: std::vector<char*> args_; @@ -883,8 +874,7 @@ int FuchsiaDeathTest::Wait() { const int kSocketKey = 1; const int kExceptionKey = 2; - if (!spawned()) - return 0; + if (!spawned()) return 0; // Create a port to wait for socket/task/exception events. zx_status_t status_zx; @@ -893,8 +883,8 @@ int FuchsiaDeathTest::Wait() { GTEST_DEATH_TEST_CHECK_(status_zx == ZX_OK); // Register to wait for the child process to terminate. - status_zx = child_process_.wait_async( - port, kProcessKey, ZX_PROCESS_TERMINATED, 0); + status_zx = + child_process_.wait_async(port, kProcessKey, ZX_PROCESS_TERMINATED, 0); GTEST_DEATH_TEST_CHECK_(status_zx == ZX_OK); // Register to wait for the socket to be readable or closed. @@ -903,8 +893,8 @@ int FuchsiaDeathTest::Wait() { GTEST_DEATH_TEST_CHECK_(status_zx == ZX_OK); // Register to wait for an exception. - status_zx = exception_channel_.wait_async( - port, kExceptionKey, ZX_CHANNEL_READABLE, 0); + status_zx = exception_channel_.wait_async(port, kExceptionKey, + ZX_CHANNEL_READABLE, 0); GTEST_DEATH_TEST_CHECK_(status_zx == ZX_OK); bool process_terminated = false; @@ -934,9 +924,9 @@ int FuchsiaDeathTest::Wait() { size_t old_length = captured_stderr_.length(); size_t bytes_read = 0; captured_stderr_.resize(old_length + kBufferSize); - status_zx = stderr_socket_.read( - 0, &captured_stderr_.front() + old_length, kBufferSize, - &bytes_read); + status_zx = + stderr_socket_.read(0, &captured_stderr_.front() + old_length, + kBufferSize, &bytes_read); captured_stderr_.resize(old_length + bytes_read); } while (status_zx == ZX_OK); if (status_zx == ZX_ERR_PEER_CLOSED) { @@ -992,11 +982,10 @@ DeathTest::TestRole FuchsiaDeathTest::AssumeRole() { const std::string filter_flag = std::string("--") + GTEST_FLAG_PREFIX_ + "filter=" + info->test_suite_name() + "." + info->name(); - const std::string internal_flag = - std::string("--") + GTEST_FLAG_PREFIX_ + kInternalRunDeathTestFlag + "=" - + file_ + "|" - + StreamableToString(line_) + "|" - + StreamableToString(death_test_index); + const std::string internal_flag = std::string("--") + GTEST_FLAG_PREFIX_ + + kInternalRunDeathTestFlag + "=" + file_ + + "|" + StreamableToString(line_) + "|" + + StreamableToString(death_test_index); Arguments args; args.AddArguments(GetInjectableArgvs()); args.AddArgument(filter_flag.c_str()); @@ -1019,8 +1008,7 @@ DeathTest::TestRole FuchsiaDeathTest::AssumeRole() { // Create a socket pair will be used to receive the child process' stderr. zx::socket stderr_producer_socket; - status = - zx::socket::create(0, &stderr_producer_socket, &stderr_socket_); + status = zx::socket::create(0, &stderr_producer_socket, &stderr_socket_); GTEST_DEATH_TEST_CHECK_(status >= 0); int stderr_producer_fd = -1; status = @@ -1037,35 +1025,32 @@ DeathTest::TestRole FuchsiaDeathTest::AssumeRole() { // Create a child job. zx_handle_t child_job = ZX_HANDLE_INVALID; - status = zx_job_create(zx_job_default(), 0, & child_job); + status = zx_job_create(zx_job_default(), 0, &child_job); GTEST_DEATH_TEST_CHECK_(status == ZX_OK); zx_policy_basic_t policy; policy.condition = ZX_POL_NEW_ANY; policy.policy = ZX_POL_ACTION_ALLOW; - status = zx_job_set_policy( - child_job, ZX_JOB_POL_RELATIVE, ZX_JOB_POL_BASIC, &policy, 1); + status = zx_job_set_policy(child_job, ZX_JOB_POL_RELATIVE, ZX_JOB_POL_BASIC, + &policy, 1); GTEST_DEATH_TEST_CHECK_(status == ZX_OK); // Create an exception channel attached to the |child_job|, to allow // us to suppress the system default exception handler from firing. - status = - zx_task_create_exception_channel( - child_job, 0, exception_channel_.reset_and_get_address()); + status = zx_task_create_exception_channel( + child_job, 0, exception_channel_.reset_and_get_address()); GTEST_DEATH_TEST_CHECK_(status == ZX_OK); // Spawn the child process. - status = fdio_spawn_etc( - child_job, FDIO_SPAWN_CLONE_ALL, args.Argv()[0], args.Argv(), nullptr, - 2, spawn_actions, child_process_.reset_and_get_address(), nullptr); + status = fdio_spawn_etc(child_job, FDIO_SPAWN_CLONE_ALL, args.Argv()[0], + args.Argv(), nullptr, 2, spawn_actions, + child_process_.reset_and_get_address(), nullptr); GTEST_DEATH_TEST_CHECK_(status == ZX_OK); set_spawned(true); return OVERSEE_TEST; } -std::string FuchsiaDeathTest::GetErrorLogs() { - return captured_stderr_; -} +std::string FuchsiaDeathTest::GetErrorLogs() { return captured_stderr_; } #else // We are neither on Windows, nor on Fuchsia. @@ -1096,8 +1081,7 @@ ForkingDeathTest::ForkingDeathTest(const char* a_statement, // status, or 0 if no child process exists. As a side effect, sets the // outcome data member. int ForkingDeathTest::Wait() { - if (!spawned()) - return 0; + if (!spawned()) return 0; ReadAndInterpretStatusByte(); @@ -1176,11 +1160,11 @@ class ExecDeathTest : public ForkingDeathTest { private: static ::std::vector<std::string> GetArgvsForDeathTestChildProcess() { ::std::vector<std::string> args = GetInjectableArgvs(); -# if defined(GTEST_EXTRA_DEATH_TEST_COMMAND_LINE_ARGS_) +#if defined(GTEST_EXTRA_DEATH_TEST_COMMAND_LINE_ARGS_) ::std::vector<std::string> extra_args = GTEST_EXTRA_DEATH_TEST_COMMAND_LINE_ARGS_(); args.insert(args.end(), extra_args.begin(), extra_args.end()); -# endif // defined(GTEST_EXTRA_DEATH_TEST_COMMAND_LINE_ARGS_) +#endif // defined(GTEST_EXTRA_DEATH_TEST_COMMAND_LINE_ARGS_) return args; } // The name of the file in which the death test is located. @@ -1207,14 +1191,11 @@ class Arguments { template <typename Str> void AddArguments(const ::std::vector<Str>& arguments) { for (typename ::std::vector<Str>::const_iterator i = arguments.begin(); - i != arguments.end(); - ++i) { + i != arguments.end(); ++i) { args_.insert(args_.end() - 1, posix::StrDup(i->c_str())); } } - char* const* Argv() { - return &args_[0]; - } + char* const* Argv() { return &args_[0]; } private: std::vector<char*> args_; @@ -1227,9 +1208,9 @@ struct ExecDeathTestArgs { int close_fd; // File descriptor to close; the read end of a pipe }; -# if GTEST_OS_QNX +#if GTEST_OS_QNX extern "C" char** environ; -# else // GTEST_OS_QNX +#else // GTEST_OS_QNX // The main function for a threadsafe-style death test child process. // This function is called in a clone()-ed process and thus must avoid // any potentially unsafe operations like malloc or libc functions. @@ -1244,8 +1225,8 @@ static int ExecDeathTestChildMain(void* child_arg) { UnitTest::GetInstance()->original_working_dir(); // We can safely call chdir() as it's a direct system call. if (chdir(original_dir) != 0) { - DeathTestAbort(std::string("chdir(\"") + original_dir + "\") failed: " + - GetLastErrnoDescription()); + DeathTestAbort(std::string("chdir(\"") + original_dir + + "\") failed: " + GetLastErrnoDescription()); return EXIT_FAILURE; } @@ -1256,13 +1237,12 @@ static int ExecDeathTestChildMain(void* child_arg) { // one path separator. execv(args->argv[0], args->argv); DeathTestAbort(std::string("execv(") + args->argv[0] + ", ...) in " + - original_dir + " failed: " + - GetLastErrnoDescription()); + original_dir + " failed: " + GetLastErrnoDescription()); return EXIT_FAILURE; } -# endif // GTEST_OS_QNX +#endif // GTEST_OS_QNX -# if GTEST_HAS_CLONE +#if GTEST_HAS_CLONE // Two utility routines that together determine the direction the stack // grows. // This could be accomplished more elegantly by a single recursive @@ -1296,7 +1276,7 @@ static bool StackGrowsDown() { StackLowerThanAddress(&dummy, &result); return result; } -# endif // GTEST_HAS_CLONE +#endif // GTEST_HAS_CLONE // Spawns a child process with the same executable as the current process in // a thread-safe manner and instructs it to run the death test. The @@ -1306,10 +1286,10 @@ static bool StackGrowsDown() { // spawn(2) there instead. The function dies with an error message if // anything goes wrong. static pid_t ExecDeathTestSpawnChild(char* const* argv, int close_fd) { - ExecDeathTestArgs args = { argv, close_fd }; + ExecDeathTestArgs args = {argv, close_fd}; pid_t child_pid = -1; -# if GTEST_OS_QNX +#if GTEST_OS_QNX // Obtains the current directory and sets it to be closed in the child // process. const int cwd_fd = open(".", O_RDONLY); @@ -1322,16 +1302,16 @@ static pid_t ExecDeathTestSpawnChild(char* const* argv, int close_fd) { UnitTest::GetInstance()->original_working_dir(); // We can safely call chdir() as it's a direct system call. if (chdir(original_dir) != 0) { - DeathTestAbort(std::string("chdir(\"") + original_dir + "\") failed: " + - GetLastErrnoDescription()); + DeathTestAbort(std::string("chdir(\"") + original_dir + + "\") failed: " + GetLastErrnoDescription()); return EXIT_FAILURE; } int fd_flags; // Set close_fd to be closed after spawn. GTEST_DEATH_TEST_CHECK_SYSCALL_(fd_flags = fcntl(close_fd, F_GETFD)); - GTEST_DEATH_TEST_CHECK_SYSCALL_(fcntl(close_fd, F_SETFD, - fd_flags | FD_CLOEXEC)); + GTEST_DEATH_TEST_CHECK_SYSCALL_( + fcntl(close_fd, F_SETFD, fd_flags | FD_CLOEXEC)); struct inheritance inherit = {0}; // spawn is a system call. child_pid = spawn(args.argv[0], 0, nullptr, &inherit, args.argv, environ); @@ -1339,8 +1319,8 @@ static pid_t ExecDeathTestSpawnChild(char* const* argv, int close_fd) { GTEST_DEATH_TEST_CHECK_(fchdir(cwd_fd) != -1); GTEST_DEATH_TEST_CHECK_SYSCALL_(close(cwd_fd)); -# else // GTEST_OS_QNX -# if GTEST_OS_LINUX +#else // GTEST_OS_QNX +#if GTEST_OS_LINUX // When a SIGPROF signal is received while fork() or clone() are executing, // the process may hang. To avoid this, we ignore SIGPROF here and re-enable // it after the call to fork()/clone() is complete. @@ -1349,11 +1329,11 @@ static pid_t ExecDeathTestSpawnChild(char* const* argv, int close_fd) { memset(&ignore_sigprof_action, 0, sizeof(ignore_sigprof_action)); sigemptyset(&ignore_sigprof_action.sa_mask); ignore_sigprof_action.sa_handler = SIG_IGN; - GTEST_DEATH_TEST_CHECK_SYSCALL_(sigaction( - SIGPROF, &ignore_sigprof_action, &saved_sigprof_action)); -# endif // GTEST_OS_LINUX + GTEST_DEATH_TEST_CHECK_SYSCALL_( + sigaction(SIGPROF, &ignore_sigprof_action, &saved_sigprof_action)); +#endif // GTEST_OS_LINUX -# if GTEST_HAS_CLONE +#if GTEST_HAS_CLONE const bool use_fork = GTEST_FLAG_GET(death_test_use_fork); if (!use_fork) { @@ -1373,7 +1353,7 @@ static pid_t ExecDeathTestSpawnChild(char* const* argv, int close_fd) { const size_t kMaxStackAlignment = 64; void* const stack_top = static_cast<char*>(stack) + - (stack_grows_down ? stack_size - kMaxStackAlignment : 0); + (stack_grows_down ? stack_size - kMaxStackAlignment : 0); GTEST_DEATH_TEST_CHECK_( static_cast<size_t>(stack_size) > kMaxStackAlignment && reinterpret_cast<uintptr_t>(stack_top) % kMaxStackAlignment == 0); @@ -1382,19 +1362,19 @@ static pid_t ExecDeathTestSpawnChild(char* const* argv, int close_fd) { GTEST_DEATH_TEST_CHECK_(munmap(stack, stack_size) != -1); } -# else +#else const bool use_fork = true; -# endif // GTEST_HAS_CLONE +#endif // GTEST_HAS_CLONE if (use_fork && (child_pid = fork()) == 0) { - ExecDeathTestChildMain(&args); - _exit(0); + ExecDeathTestChildMain(&args); + _exit(0); } -# endif // GTEST_OS_QNX -# if GTEST_OS_LINUX +#endif // GTEST_OS_QNX +#if GTEST_OS_LINUX GTEST_DEATH_TEST_CHECK_SYSCALL_( sigaction(SIGPROF, &saved_sigprof_action, nullptr)); -# endif // GTEST_OS_LINUX +#endif // GTEST_OS_LINUX GTEST_DEATH_TEST_CHECK_(child_pid != -1); return child_pid; @@ -1450,7 +1430,7 @@ DeathTest::TestRole ExecDeathTest::AssumeRole() { return OVERSEE_TEST; } -# endif // !GTEST_OS_WINDOWS +#endif // !GTEST_OS_WINDOWS // Creates a concrete DeathTest-derived class that depends on the // --gtest_death_test_style flag, and sets the pointer pointed to @@ -1464,15 +1444,15 @@ bool DefaultDeathTestFactory::Create(const char* statement, UnitTestImpl* const impl = GetUnitTestImpl(); const InternalRunDeathTestFlag* const flag = impl->internal_run_death_test_flag(); - const int death_test_index = impl->current_test_info() - ->increment_death_test_count(); + const int death_test_index = + impl->current_test_info()->increment_death_test_count(); if (flag != nullptr) { if (death_test_index > flag->index()) { DeathTest::set_last_death_test_message( - "Death test count (" + StreamableToString(death_test_index) - + ") somehow exceeded expected maximum (" - + StreamableToString(flag->index()) + ")"); + "Death test count (" + StreamableToString(death_test_index) + + ") somehow exceeded expected maximum (" + + StreamableToString(flag->index()) + ")"); return false; } @@ -1483,21 +1463,21 @@ bool DefaultDeathTestFactory::Create(const char* statement, } } -# if GTEST_OS_WINDOWS +#if GTEST_OS_WINDOWS if (GTEST_FLAG_GET(death_test_style) == "threadsafe" || GTEST_FLAG_GET(death_test_style) == "fast") { *test = new WindowsDeathTest(statement, std::move(matcher), file, line); } -# elif GTEST_OS_FUCHSIA +#elif GTEST_OS_FUCHSIA if (GTEST_FLAG_GET(death_test_style) == "threadsafe" || GTEST_FLAG_GET(death_test_style) == "fast") { *test = new FuchsiaDeathTest(statement, std::move(matcher), file, line); } -# else +#else if (GTEST_FLAG_GET(death_test_style) == "threadsafe") { *test = new ExecDeathTest(statement, std::move(matcher), file, line); @@ -1505,7 +1485,7 @@ bool DefaultDeathTestFactory::Create(const char* statement, *test = new NoExecDeathTest(statement, std::move(matcher)); } -# endif // GTEST_OS_WINDOWS +#endif // GTEST_OS_WINDOWS else { // NOLINT - this is more readable than unbalanced brackets inside #if. DeathTest::set_last_death_test_message("Unknown death test style \"" + @@ -1517,16 +1497,16 @@ bool DefaultDeathTestFactory::Create(const char* statement, return true; } -# if GTEST_OS_WINDOWS +#if GTEST_OS_WINDOWS // Recreates the pipe and event handles from the provided parameters, // signals the event, and returns a file descriptor wrapped around the pipe // handle. This function is called in the child process only. static int GetStatusFileDescriptor(unsigned int parent_process_id, - size_t write_handle_as_size_t, - size_t event_handle_as_size_t) { + size_t write_handle_as_size_t, + size_t event_handle_as_size_t) { AutoHandle parent_process_handle(::OpenProcess(PROCESS_DUP_HANDLE, - FALSE, // Non-inheritable. - parent_process_id)); + FALSE, // Non-inheritable. + parent_process_id)); if (parent_process_handle.Get() == INVALID_HANDLE_VALUE) { DeathTestAbort("Unable to open parent process " + StreamableToString(parent_process_id)); @@ -1534,8 +1514,7 @@ static int GetStatusFileDescriptor(unsigned int parent_process_id, GTEST_CHECK_(sizeof(HANDLE) <= sizeof(size_t)); - const HANDLE write_handle = - reinterpret_cast<HANDLE>(write_handle_as_size_t); + const HANDLE write_handle = reinterpret_cast<HANDLE>(write_handle_as_size_t); HANDLE dup_write_handle; // The newly initialized handle is accessible only in the parent @@ -1557,9 +1536,7 @@ static int GetStatusFileDescriptor(unsigned int parent_process_id, HANDLE dup_event_handle; if (!::DuplicateHandle(parent_process_handle.Get(), event_handle, - ::GetCurrentProcess(), &dup_event_handle, - 0x0, - FALSE, + ::GetCurrentProcess(), &dup_event_handle, 0x0, FALSE, DUPLICATE_SAME_ACCESS)) { DeathTestAbort("Unable to duplicate the event handle " + StreamableToString(event_handle_as_size_t) + @@ -1581,7 +1558,7 @@ static int GetStatusFileDescriptor(unsigned int parent_process_id, return write_fd; } -# endif // GTEST_OS_WINDOWS +#endif // GTEST_OS_WINDOWS // Returns a newly created InternalRunDeathTestFlag object with fields // initialized from the GTEST_FLAG(internal_run_death_test) flag if @@ -1597,45 +1574,41 @@ InternalRunDeathTestFlag* ParseInternalRunDeathTestFlag() { SplitString(GTEST_FLAG_GET(internal_run_death_test), '|', &fields); int write_fd = -1; -# if GTEST_OS_WINDOWS +#if GTEST_OS_WINDOWS unsigned int parent_process_id = 0; size_t write_handle_as_size_t = 0; size_t event_handle_as_size_t = 0; - if (fields.size() != 6 - || !ParseNaturalNumber(fields[1], &line) - || !ParseNaturalNumber(fields[2], &index) - || !ParseNaturalNumber(fields[3], &parent_process_id) - || !ParseNaturalNumber(fields[4], &write_handle_as_size_t) - || !ParseNaturalNumber(fields[5], &event_handle_as_size_t)) { + if (fields.size() != 6 || !ParseNaturalNumber(fields[1], &line) || + !ParseNaturalNumber(fields[2], &index) || + !ParseNaturalNumber(fields[3], &parent_process_id) || + !ParseNaturalNumber(fields[4], &write_handle_as_size_t) || + !ParseNaturalNumber(fields[5], &event_handle_as_size_t)) { DeathTestAbort("Bad --gtest_internal_run_death_test flag: " + GTEST_FLAG_GET(internal_run_death_test)); } - write_fd = GetStatusFileDescriptor(parent_process_id, - write_handle_as_size_t, + write_fd = GetStatusFileDescriptor(parent_process_id, write_handle_as_size_t, event_handle_as_size_t); -# elif GTEST_OS_FUCHSIA +#elif GTEST_OS_FUCHSIA - if (fields.size() != 3 - || !ParseNaturalNumber(fields[1], &line) - || !ParseNaturalNumber(fields[2], &index)) { + if (fields.size() != 3 || !ParseNaturalNumber(fields[1], &line) || + !ParseNaturalNumber(fields[2], &index)) { DeathTestAbort("Bad --gtest_internal_run_death_test flag: " + GTEST_FLAG_GET(internal_run_death_test)); } -# else +#else - if (fields.size() != 4 - || !ParseNaturalNumber(fields[1], &line) - || !ParseNaturalNumber(fields[2], &index) - || !ParseNaturalNumber(fields[3], &write_fd)) { + if (fields.size() != 4 || !ParseNaturalNumber(fields[1], &line) || + !ParseNaturalNumber(fields[2], &index) || + !ParseNaturalNumber(fields[3], &write_fd)) { DeathTestAbort("Bad --gtest_internal_run_death_test flag: " + GTEST_FLAG_GET(internal_run_death_test)); } -# endif // GTEST_OS_WINDOWS +#endif // GTEST_OS_WINDOWS return new InternalRunDeathTestFlag(fields[0], line, index, write_fd); } diff --git a/googletest/src/gtest-filepath.cc b/googletest/src/gtest-filepath.cc index 0b56294..f6ee90c 100644 --- a/googletest/src/gtest-filepath.cc +++ b/googletest/src/gtest-filepath.cc @@ -30,29 +30,31 @@ #include "gtest/internal/gtest-filepath.h" #include <stdlib.h> -#include "gtest/internal/gtest-port.h" + #include "gtest/gtest-message.h" +#include "gtest/internal/gtest-port.h" #if GTEST_OS_WINDOWS_MOBILE -# include <windows.h> +#include <windows.h> #elif GTEST_OS_WINDOWS -# include <direct.h> -# include <io.h> +#include <direct.h> +#include <io.h> #else -# include <limits.h> -# include <climits> // Some Linux distributions define PATH_MAX here. -#endif // GTEST_OS_WINDOWS_MOBILE +#include <limits.h> + +#include <climits> // Some Linux distributions define PATH_MAX here. +#endif // GTEST_OS_WINDOWS_MOBILE #include "gtest/internal/gtest-string.h" #if GTEST_OS_WINDOWS -# define GTEST_PATH_MAX_ _MAX_PATH +#define GTEST_PATH_MAX_ _MAX_PATH #elif defined(PATH_MAX) -# define GTEST_PATH_MAX_ PATH_MAX +#define GTEST_PATH_MAX_ PATH_MAX #elif defined(_XOPEN_PATH_MAX) -# define GTEST_PATH_MAX_ _XOPEN_PATH_MAX +#define GTEST_PATH_MAX_ _XOPEN_PATH_MAX #else -# define GTEST_PATH_MAX_ _POSIX_PATH_MAX +#define GTEST_PATH_MAX_ _POSIX_PATH_MAX #endif // GTEST_OS_WINDOWS namespace testing { @@ -66,16 +68,16 @@ namespace internal { const char kPathSeparator = '\\'; const char kAlternatePathSeparator = '/'; const char kAlternatePathSeparatorString[] = "/"; -# if GTEST_OS_WINDOWS_MOBILE +#if GTEST_OS_WINDOWS_MOBILE // Windows CE doesn't have a current directory. You should not use // the current directory in tests on Windows CE, but this at least // provides a reasonable fallback. const char kCurrentDirectoryString[] = "\\"; // Windows CE doesn't define INVALID_FILE_ATTRIBUTES const DWORD kInvalidFileAttributes = 0xffffffff; -# else +#else const char kCurrentDirectoryString[] = ".\\"; -# endif // GTEST_OS_WINDOWS_MOBILE +#endif // GTEST_OS_WINDOWS_MOBILE #else const char kPathSeparator = '/'; const char kCurrentDirectoryString[] = "./"; @@ -99,17 +101,17 @@ FilePath FilePath::GetCurrentDir() { // something reasonable. return FilePath(kCurrentDirectoryString); #elif GTEST_OS_WINDOWS - char cwd[GTEST_PATH_MAX_ + 1] = { '\0' }; + char cwd[GTEST_PATH_MAX_ + 1] = {'\0'}; return FilePath(_getcwd(cwd, sizeof(cwd)) == nullptr ? "" : cwd); #else - char cwd[GTEST_PATH_MAX_ + 1] = { '\0' }; + char cwd[GTEST_PATH_MAX_ + 1] = {'\0'}; char* result = getcwd(cwd, sizeof(cwd)); -# if GTEST_OS_NACL +#if GTEST_OS_NACL // getcwd will likely fail in NaCl due to the sandbox, so return something // reasonable. The user may have provided a shim implementation for getcwd, // however, so fallback only when failure is detected. return FilePath(result == nullptr ? kCurrentDirectoryString : cwd); -# endif // GTEST_OS_NACL +#endif // GTEST_OS_NACL return FilePath(result == nullptr ? "" : cwd); #endif // GTEST_OS_WINDOWS_MOBILE } @@ -121,8 +123,8 @@ FilePath FilePath::GetCurrentDir() { FilePath FilePath::RemoveExtension(const char* extension) const { const std::string dot_extension = std::string(".") + extension; if (String::EndsWithCaseInsensitive(pathname_, dot_extension)) { - return FilePath(pathname_.substr( - 0, pathname_.length() - dot_extension.length())); + return FilePath( + pathname_.substr(0, pathname_.length() - dot_extension.length())); } return *this; } @@ -178,15 +180,14 @@ FilePath FilePath::RemoveFileName() const { // than zero (e.g., 12), returns "dir/test_12.xml". // On Windows platform, uses \ as the separator rather than /. FilePath FilePath::MakeFileName(const FilePath& directory, - const FilePath& base_name, - int number, + const FilePath& base_name, int number, const char* extension) { std::string file; if (number == 0) { file = base_name.string() + "." + extension; } else { - file = base_name.string() + "_" + StreamableToString(number) - + "." + extension; + file = + base_name.string() + "_" + StreamableToString(number) + "." + extension; } return ConcatPaths(directory, FilePath(file)); } @@ -195,8 +196,7 @@ FilePath FilePath::MakeFileName(const FilePath& directory, // On Windows, uses \ as the separator rather than /. FilePath FilePath::ConcatPaths(const FilePath& directory, const FilePath& relative_path) { - if (directory.IsEmpty()) - return relative_path; + if (directory.IsEmpty()) return relative_path; const FilePath dir(directory.RemoveTrailingPathSeparator()); return FilePath(dir.string() + kPathSeparator + relative_path.string()); } @@ -207,7 +207,7 @@ bool FilePath::FileOrDirectoryExists() const { #if GTEST_OS_WINDOWS_MOBILE LPCWSTR unicode = String::AnsiToUtf16(pathname_.c_str()); const DWORD attributes = GetFileAttributes(unicode); - delete [] unicode; + delete[] unicode; return attributes != kInvalidFileAttributes; #else posix::StatStruct file_stat{}; @@ -222,8 +222,8 @@ bool FilePath::DirectoryExists() const { #if GTEST_OS_WINDOWS // Don't strip off trailing separator if path is a root directory on // Windows (like "C:\\"). - const FilePath& path(IsRootDirectory() ? *this : - RemoveTrailingPathSeparator()); + const FilePath& path(IsRootDirectory() ? *this + : RemoveTrailingPathSeparator()); #else const FilePath& path(*this); #endif @@ -231,15 +231,15 @@ bool FilePath::DirectoryExists() const { #if GTEST_OS_WINDOWS_MOBILE LPCWSTR unicode = String::AnsiToUtf16(path.c_str()); const DWORD attributes = GetFileAttributes(unicode); - delete [] unicode; + delete[] unicode; if ((attributes != kInvalidFileAttributes) && (attributes & FILE_ATTRIBUTE_DIRECTORY)) { result = true; } #else posix::StatStruct file_stat{}; - result = posix::Stat(path.c_str(), &file_stat) == 0 && - posix::IsDir(file_stat); + result = + posix::Stat(path.c_str(), &file_stat) == 0 && posix::IsDir(file_stat); #endif // GTEST_OS_WINDOWS_MOBILE return result; @@ -260,10 +260,9 @@ bool FilePath::IsAbsolutePath() const { const char* const name = pathname_.c_str(); #if GTEST_OS_WINDOWS return pathname_.length() >= 3 && - ((name[0] >= 'a' && name[0] <= 'z') || - (name[0] >= 'A' && name[0] <= 'Z')) && - name[1] == ':' && - IsPathSeparator(name[2]); + ((name[0] >= 'a' && name[0] <= 'z') || + (name[0] >= 'A' && name[0] <= 'Z')) && + name[1] == ':' && IsPathSeparator(name[2]); #else return IsPathSeparator(name[0]); #endif @@ -321,7 +320,7 @@ bool FilePath::CreateFolder() const { FilePath removed_sep(this->RemoveTrailingPathSeparator()); LPCWSTR unicode = String::AnsiToUtf16(removed_sep.c_str()); int result = CreateDirectory(unicode, nullptr) ? 0 : -1; - delete [] unicode; + delete[] unicode; #elif GTEST_OS_WINDOWS int result = _mkdir(pathname_.c_str()); #elif GTEST_OS_ESP8266 || GTEST_OS_XTENSA @@ -341,9 +340,8 @@ bool FilePath::CreateFolder() const { // name, otherwise return the name string unmodified. // On Windows platform, uses \ as the separator, other platforms use /. FilePath FilePath::RemoveTrailingPathSeparator() const { - return IsDirectory() - ? FilePath(pathname_.substr(0, pathname_.length() - 1)) - : *this; + return IsDirectory() ? FilePath(pathname_.substr(0, pathname_.length() - 1)) + : *this; } // Removes any redundant separators that might be in the pathname. diff --git a/googletest/src/gtest-internal-inl.h b/googletest/src/gtest-internal-inl.h index 3f5551d..542a8ec 100644 --- a/googletest/src/gtest-internal-inl.h +++ b/googletest/src/gtest-internal-inl.h @@ -35,7 +35,7 @@ #define GOOGLETEST_SRC_GTEST_INTERNAL_INL_H_ #ifndef _WIN32_WCE -# include <errno.h> +#include <errno.h> #endif // !_WIN32_WCE #include <stddef.h> #include <stdlib.h> // For strtoll/_strtoul64/malloc/free. @@ -50,16 +50,16 @@ #include "gtest/internal/gtest-port.h" #if GTEST_CAN_STREAM_RESULTS_ -# include <arpa/inet.h> // NOLINT -# include <netdb.h> // NOLINT +#include <arpa/inet.h> // NOLINT +#include <netdb.h> // NOLINT #endif #if GTEST_OS_WINDOWS -# include <windows.h> // NOLINT -#endif // GTEST_OS_WINDOWS +#include <windows.h> // NOLINT +#endif // GTEST_OS_WINDOWS -#include "gtest/gtest.h" #include "gtest/gtest-spi.h" +#include "gtest/gtest.h" GTEST_DISABLE_MSC_WARNINGS_PUSH_(4251 \ /* class A needs to have dll-interface to be used by clients of class B */) @@ -109,15 +109,16 @@ GTEST_API_ bool ParseFlag(const char* str, const char* flag, int32_t* value); // Returns a random seed in range [1, kMaxRandomSeed] based on the // given --gtest_random_seed flag value. inline int GetRandomSeedFromFlag(int32_t random_seed_flag) { - const unsigned int raw_seed = (random_seed_flag == 0) ? - static_cast<unsigned int>(GetTimeInMillis()) : - static_cast<unsigned int>(random_seed_flag); + const unsigned int raw_seed = + (random_seed_flag == 0) ? static_cast<unsigned int>(GetTimeInMillis()) + : static_cast<unsigned int>(random_seed_flag); // Normalizes the actual seed to range [1, kMaxRandomSeed] such that // it's easy to type. const int normalized_seed = static_cast<int>((raw_seed - 1U) % - static_cast<unsigned int>(kMaxRandomSeed)) + 1; + static_cast<unsigned int>(kMaxRandomSeed)) + + 1; return normalized_seed; } @@ -261,8 +262,8 @@ GTEST_API_ int32_t Int32FromEnvOrDie(const char* env_var, int32_t default_val); // returns true if and only if the test should be run on this shard. The test id // is some arbitrary but unique non-negative integer assigned to each test // method. Assumes that 0 <= shard_index < total_shards. -GTEST_API_ bool ShouldRunTestOnShard( - int total_shards, int shard_index, int test_id); +GTEST_API_ bool ShouldRunTestOnShard(int total_shards, int shard_index, + int test_id); // STL container utilities. @@ -274,8 +275,7 @@ inline int CountIf(const Container& c, Predicate predicate) { // Solaris has a non-standard signature. int count = 0; for (auto it = c.begin(); it != c.end(); ++it) { - if (predicate(*it)) - ++count; + if (predicate(*it)) ++count; } return count; } @@ -459,7 +459,7 @@ struct TraceInfo { // This is the default global test part result reporter used in UnitTestImpl. // This class should only be used by UnitTestImpl. class DefaultGlobalTestPartResultReporter - : public TestPartResultReporterInterface { + : public TestPartResultReporterInterface { public: explicit DefaultGlobalTestPartResultReporter(UnitTestImpl* unit_test); // Implements the TestPartResultReporterInterface. Reports the test part @@ -728,9 +728,7 @@ class GTEST_API_ UnitTestImpl { } // Clears the results of ad-hoc test assertions. - void ClearAdHocTestResult() { - ad_hoc_test_result_.Clear(); - } + void ClearAdHocTestResult() { ad_hoc_test_result_.Clear(); } // Adds a TestProperty to the current TestResult object when invoked in a // context of a test or a test suite, or to the global property set. If the @@ -738,10 +736,7 @@ class GTEST_API_ UnitTestImpl { // updated. void RecordProperty(const TestProperty& test_property); - enum ReactionToSharding { - HONOR_SHARDING_PROTOCOL, - IGNORE_SHARDING_PROTOCOL - }; + enum ReactionToSharding { HONOR_SHARDING_PROTOCOL, IGNORE_SHARDING_PROTOCOL }; // Matches the full name of each test against the user-specified // filter to decide whether the test should run, then records the @@ -970,8 +965,9 @@ GTEST_API_ bool IsValidEscape(char ch); GTEST_API_ bool AtomMatchesChar(bool escaped, char pattern, char ch); GTEST_API_ bool ValidateRegex(const char* regex); GTEST_API_ bool MatchRegexAtHead(const char* regex, const char* str); -GTEST_API_ bool MatchRepetitionAndRegexAtHead( - bool escaped, char ch, char repeat, const char* regex, const char* str); +GTEST_API_ bool MatchRepetitionAndRegexAtHead(bool escaped, char ch, + char repeat, const char* regex, + const char* str); GTEST_API_ bool MatchRegexAnywhere(const char* regex, const char* str); #endif // GTEST_USES_SIMPLE_RE @@ -1073,8 +1069,7 @@ class StreamingListener : public EmptyTestEventListener { } ~SocketWriter() override { - if (sockfd_ != -1) - CloseConnection(); + if (sockfd_ != -1) CloseConnection(); } // Sends a string to the socket. @@ -1084,9 +1079,8 @@ class StreamingListener : public EmptyTestEventListener { const auto len = static_cast<size_t>(message.length()); if (write(sockfd_, message.c_str(), len) != static_cast<ssize_t>(len)) { - GTEST_LOG_(WARNING) - << "stream_result_to: failed to stream to " - << host_name_ << ":" << port_num_; + GTEST_LOG_(WARNING) << "stream_result_to: failed to stream to " + << host_name_ << ":" << port_num_; } } @@ -1119,7 +1113,9 @@ class StreamingListener : public EmptyTestEventListener { } explicit StreamingListener(AbstractSocketWriter* socket_writer) - : socket_writer_(socket_writer) { Start(); } + : socket_writer_(socket_writer) { + Start(); + } void OnTestProgramStart(const UnitTest& /* unit_test */) override { SendLn("event=TestProgramStart"); @@ -1142,9 +1138,9 @@ class StreamingListener : public EmptyTestEventListener { void OnTestIterationEnd(const UnitTest& unit_test, int /* iteration */) override { - SendLn("event=TestIterationEnd&passed=" + - FormatBool(unit_test.Passed()) + "&elapsed_time=" + - StreamableToString(unit_test.elapsed_time()) + "ms"); + SendLn("event=TestIterationEnd&passed=" + FormatBool(unit_test.Passed()) + + "&elapsed_time=" + StreamableToString(unit_test.elapsed_time()) + + "ms"); } // Note that "event=TestCaseStart" is a wire format and has to remain @@ -1167,8 +1163,7 @@ class StreamingListener : public EmptyTestEventListener { void OnTestEnd(const TestInfo& test_info) override { SendLn("event=TestEnd&passed=" + - FormatBool((test_info.result())->Passed()) + - "&elapsed_time=" + + FormatBool((test_info.result())->Passed()) + "&elapsed_time=" + StreamableToString((test_info.result())->elapsed_time()) + "ms"); } diff --git a/googletest/src/gtest-matchers.cc b/googletest/src/gtest-matchers.cc index 65104eb..7e3bcc0 100644 --- a/googletest/src/gtest-matchers.cc +++ b/googletest/src/gtest-matchers.cc @@ -32,12 +32,13 @@ // This file implements just enough of the matcher interface to allow // EXPECT_DEATH and friends to accept a matcher argument. -#include "gtest/internal/gtest-internal.h" -#include "gtest/internal/gtest-port.h" #include "gtest/gtest-matchers.h" #include <string> +#include "gtest/internal/gtest-internal.h" +#include "gtest/internal/gtest-port.h" + namespace testing { // Constructs a matcher that matches a const std::string& whose value is diff --git a/googletest/src/gtest-port.cc b/googletest/src/gtest-port.cc index d47550a..32c27c2 100644 --- a/googletest/src/gtest-port.cc +++ b/googletest/src/gtest-port.cc @@ -27,61 +27,62 @@ // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - #include "gtest/internal/gtest-port.h" #include <limits.h> #include <stdio.h> #include <stdlib.h> #include <string.h> + #include <cstdint> #include <fstream> #include <memory> #if GTEST_OS_WINDOWS -# include <windows.h> -# include <io.h> -# include <sys/stat.h> -# include <map> // Used in ThreadLocal. -# ifdef _MSC_VER -# include <crtdbg.h> -# endif // _MSC_VER +#include <io.h> +#include <sys/stat.h> +#include <windows.h> + +#include <map> // Used in ThreadLocal. +#ifdef _MSC_VER +#include <crtdbg.h> +#endif // _MSC_VER #else -# include <unistd.h> +#include <unistd.h> #endif // GTEST_OS_WINDOWS #if GTEST_OS_MAC -# include <mach/mach_init.h> -# include <mach/task.h> -# include <mach/vm_map.h> +#include <mach/mach_init.h> +#include <mach/task.h> +#include <mach/vm_map.h> #endif // GTEST_OS_MAC #if GTEST_OS_DRAGONFLY || GTEST_OS_FREEBSD || GTEST_OS_GNU_KFREEBSD || \ GTEST_OS_NETBSD || GTEST_OS_OPENBSD -# include <sys/sysctl.h> -# if GTEST_OS_DRAGONFLY || GTEST_OS_FREEBSD || GTEST_OS_GNU_KFREEBSD -# include <sys/user.h> -# endif +#include <sys/sysctl.h> +#if GTEST_OS_DRAGONFLY || GTEST_OS_FREEBSD || GTEST_OS_GNU_KFREEBSD +#include <sys/user.h> +#endif #endif #if GTEST_OS_QNX -# include <devctl.h> -# include <fcntl.h> -# include <sys/procfs.h> +#include <devctl.h> +#include <fcntl.h> +#include <sys/procfs.h> #endif // GTEST_OS_QNX #if GTEST_OS_AIX -# include <procinfo.h> -# include <sys/types.h> +#include <procinfo.h> +#include <sys/types.h> #endif // GTEST_OS_AIX #if GTEST_OS_FUCHSIA -# include <zircon/process.h> -# include <zircon/syscalls.h> +#include <zircon/process.h> +#include <zircon/syscalls.h> #endif // GTEST_OS_FUCHSIA -#include "gtest/gtest-spi.h" #include "gtest/gtest-message.h" +#include "gtest/gtest-spi.h" #include "gtest/internal/gtest-internal.h" #include "gtest/internal/gtest-string.h" #include "src/gtest-internal-inl.h" @@ -131,8 +132,7 @@ size_t GetThreadCount() { if (status == KERN_SUCCESS) { // task_threads allocates resources in thread_list and we need to free them // to avoid leaks. - vm_deallocate(task, - reinterpret_cast<vm_address_t>(thread_list), + vm_deallocate(task, reinterpret_cast<vm_address_t>(thread_list), sizeof(thread_t) * thread_count); return static_cast<size_t>(thread_count); } else { @@ -141,7 +141,7 @@ size_t GetThreadCount() { } #elif GTEST_OS_DRAGONFLY || GTEST_OS_FREEBSD || GTEST_OS_GNU_KFREEBSD || \ - GTEST_OS_NETBSD + GTEST_OS_NETBSD #if GTEST_OS_NETBSD #undef KERN_PROC @@ -184,12 +184,12 @@ size_t GetThreadCount() { // we cannot detect it. size_t GetThreadCount() { int mib[] = { - CTL_KERN, - KERN_PROC, - KERN_PROC_PID | KERN_PROC_SHOW_THREADS, - getpid(), - sizeof(struct kinfo_proc), - 0, + CTL_KERN, + KERN_PROC, + KERN_PROC_PID | KERN_PROC_SHOW_THREADS, + getpid(), + sizeof(struct kinfo_proc), + 0, }; u_int miblen = sizeof(mib) / sizeof(mib[0]); @@ -210,8 +210,7 @@ size_t GetThreadCount() { // exclude empty members size_t nthreads = 0; for (size_t i = 0; i < size / static_cast<size_t>(mib[4]); i++) { - if (info[i].p_tid != -1) - nthreads++; + if (info[i].p_tid != -1) nthreads++; } return nthreads; } @@ -254,13 +253,9 @@ size_t GetThreadCount() { size_t GetThreadCount() { int dummy_buffer; size_t avail; - zx_status_t status = zx_object_get_info( - zx_process_self(), - ZX_INFO_PROCESS_THREADS, - &dummy_buffer, - 0, - nullptr, - &avail); + zx_status_t status = + zx_object_get_info(zx_process_self(), ZX_INFO_PROCESS_THREADS, + &dummy_buffer, 0, nullptr, &avail); if (status == ZX_OK) { return avail; } else { @@ -280,23 +275,15 @@ size_t GetThreadCount() { #if GTEST_IS_THREADSAFE && GTEST_OS_WINDOWS -AutoHandle::AutoHandle() - : handle_(INVALID_HANDLE_VALUE) {} +AutoHandle::AutoHandle() : handle_(INVALID_HANDLE_VALUE) {} -AutoHandle::AutoHandle(Handle handle) - : handle_(handle) {} +AutoHandle::AutoHandle(Handle handle) : handle_(handle) {} -AutoHandle::~AutoHandle() { - Reset(); -} +AutoHandle::~AutoHandle() { Reset(); } -AutoHandle::Handle AutoHandle::Get() const { - return handle_; -} +AutoHandle::Handle AutoHandle::Get() const { return handle_; } -void AutoHandle::Reset() { - Reset(INVALID_HANDLE_VALUE); -} +void AutoHandle::Reset() { Reset(INVALID_HANDLE_VALUE); } void AutoHandle::Reset(HANDLE handle) { // Resetting with the same handle we already own is invalid. @@ -308,7 +295,7 @@ void AutoHandle::Reset(HANDLE handle) { } else { GTEST_CHECK_(!IsCloseable()) << "Resetting a valid handle to itself is likely a programmer error " - "and thus not allowed."; + "and thus not allowed."; } } @@ -370,8 +357,7 @@ namespace { // MemoryIsNotDeallocated memory_is_not_deallocated; // critical_section_ = new CRITICAL_SECTION; // -class MemoryIsNotDeallocated -{ +class MemoryIsNotDeallocated { public: MemoryIsNotDeallocated() : old_crtdbg_flag_(0) { old_crtdbg_flag_ = _CrtSetDbgFlag(_CRTDBG_REPORT_FLAG); @@ -414,15 +400,13 @@ void Mutex::ThreadSafeLazyInit() { ::InitializeCriticalSection(critical_section_); // Updates the critical_section_init_phase_ to 2 to signal // initialization complete. - GTEST_CHECK_(::InterlockedCompareExchange( - &critical_section_init_phase_, 2L, 1L) == - 1L); + GTEST_CHECK_(::InterlockedCompareExchange(&critical_section_init_phase_, + 2L, 1L) == 1L); break; case 1: // Somebody else is already initializing the mutex; spin until they // are done. - while (::InterlockedCompareExchange(&critical_section_init_phase_, - 2L, + while (::InterlockedCompareExchange(&critical_section_init_phase_, 2L, 2L) != 2L) { // Possibly yields the rest of the thread's time slice to other // threads. @@ -467,9 +451,7 @@ class ThreadWithParamSupport : public ThreadWithParamBase { private: struct ThreadMainParam { ThreadMainParam(Runnable* runnable, Notification* thread_can_start) - : runnable_(runnable), - thread_can_start_(thread_can_start) { - } + : runnable_(runnable), thread_can_start_(thread_can_start) {} std::unique_ptr<Runnable> runnable_; // Does not own. Notification* thread_can_start_; @@ -492,15 +474,12 @@ class ThreadWithParamSupport : public ThreadWithParamBase { } // namespace -ThreadWithParamBase::ThreadWithParamBase(Runnable *runnable, +ThreadWithParamBase::ThreadWithParamBase(Runnable* runnable, Notification* thread_can_start) - : thread_(ThreadWithParamSupport::CreateThread(runnable, - thread_can_start)) { -} + : thread_( + ThreadWithParamSupport::CreateThread(runnable, thread_can_start)) {} -ThreadWithParamBase::~ThreadWithParamBase() { - Join(); -} +ThreadWithParamBase::~ThreadWithParamBase() { Join(); } void ThreadWithParamBase::Join() { GTEST_CHECK_(::WaitForSingleObject(thread_.Get(), INFINITE) == WAIT_OBJECT_0) @@ -527,8 +506,10 @@ class ThreadLocalRegistryImpl { ThreadIdToThreadLocals::iterator thread_local_pos = thread_to_thread_locals->find(current_thread); if (thread_local_pos == thread_to_thread_locals->end()) { - thread_local_pos = thread_to_thread_locals->insert( - std::make_pair(current_thread, ThreadLocalValues())).first; + thread_local_pos = + thread_to_thread_locals + ->insert(std::make_pair(current_thread, ThreadLocalValues())) + .first; StartWatcherThreadFor(current_thread); } ThreadLocalValues& thread_local_values = thread_local_pos->second; @@ -556,9 +537,8 @@ class ThreadLocalRegistryImpl { ThreadIdToThreadLocals* const thread_to_thread_locals = GetThreadLocalsMapLocked(); for (ThreadIdToThreadLocals::iterator it = - thread_to_thread_locals->begin(); - it != thread_to_thread_locals->end(); - ++it) { + thread_to_thread_locals->begin(); + it != thread_to_thread_locals->end(); ++it) { ThreadLocalValues& thread_local_values = it->second; ThreadLocalValues::iterator value_pos = thread_local_values.find(thread_local_instance); @@ -588,9 +568,8 @@ class ThreadLocalRegistryImpl { if (thread_local_pos != thread_to_thread_locals->end()) { ThreadLocalValues& thread_local_values = thread_local_pos->second; for (ThreadLocalValues::iterator value_pos = - thread_local_values.begin(); - value_pos != thread_local_values.end(); - ++value_pos) { + thread_local_values.begin(); + value_pos != thread_local_values.end(); ++value_pos) { value_holders.push_back(value_pos->second); } thread_to_thread_locals->erase(thread_local_pos); @@ -616,9 +595,8 @@ class ThreadLocalRegistryImpl { static void StartWatcherThreadFor(DWORD thread_id) { // The returned handle will be kept in thread_map and closed by // watcher_thread in WatcherThreadFunc. - HANDLE thread = ::OpenThread(SYNCHRONIZE | THREAD_QUERY_INFORMATION, - FALSE, - thread_id); + HANDLE thread = + ::OpenThread(SYNCHRONIZE | THREAD_QUERY_INFORMATION, FALSE, thread_id); GTEST_CHECK_(thread != nullptr); // We need to pass a valid thread ID pointer into CreateThread for it // to work correctly under Win98. @@ -644,8 +622,7 @@ class ThreadLocalRegistryImpl { static DWORD WINAPI WatcherThreadFunc(LPVOID param) { const ThreadIdAndHandle* tah = reinterpret_cast<const ThreadIdAndHandle*>(param); - GTEST_CHECK_( - ::WaitForSingleObject(tah->second, INFINITE) == WAIT_OBJECT_0); + GTEST_CHECK_(::WaitForSingleObject(tah->second, INFINITE) == WAIT_OBJECT_0); OnThreadExit(tah->first); ::CloseHandle(tah->second); delete tah; @@ -669,16 +646,17 @@ class ThreadLocalRegistryImpl { }; Mutex ThreadLocalRegistryImpl::mutex_(Mutex::kStaticMutex); // NOLINT -Mutex ThreadLocalRegistryImpl::thread_map_mutex_(Mutex::kStaticMutex); // NOLINT +Mutex ThreadLocalRegistryImpl::thread_map_mutex_( + Mutex::kStaticMutex); // NOLINT ThreadLocalValueHolderBase* ThreadLocalRegistry::GetValueOnCurrentThread( - const ThreadLocalBase* thread_local_instance) { + const ThreadLocalBase* thread_local_instance) { return ThreadLocalRegistryImpl::GetValueOnCurrentThread( thread_local_instance); } void ThreadLocalRegistry::OnThreadLocalDestroyed( - const ThreadLocalBase* thread_local_instance) { + const ThreadLocalBase* thread_local_instance) { ThreadLocalRegistryImpl::OnThreadLocalDestroyed(thread_local_instance); } @@ -766,7 +744,7 @@ bool IsRepeat(char ch) { return IsInSet(ch, "?*+"); } bool IsAsciiWhiteSpace(char ch) { return IsInSet(ch, " \f\n\r\t\v"); } bool IsAsciiWordChar(char ch) { return ('a' <= ch && ch <= 'z') || ('A' <= ch && ch <= 'Z') || - ('0' <= ch && ch <= '9') || ch == '_'; + ('0' <= ch && ch <= '9') || ch == '_'; } // Returns true if and only if "\\c" is a supported escape sequence. @@ -779,17 +757,28 @@ bool IsValidEscape(char c) { bool AtomMatchesChar(bool escaped, char pattern_char, char ch) { if (escaped) { // "\\p" where p is pattern_char. switch (pattern_char) { - case 'd': return IsAsciiDigit(ch); - case 'D': return !IsAsciiDigit(ch); - case 'f': return ch == '\f'; - case 'n': return ch == '\n'; - case 'r': return ch == '\r'; - case 's': return IsAsciiWhiteSpace(ch); - case 'S': return !IsAsciiWhiteSpace(ch); - case 't': return ch == '\t'; - case 'v': return ch == '\v'; - case 'w': return IsAsciiWordChar(ch); - case 'W': return !IsAsciiWordChar(ch); + case 'd': + return IsAsciiDigit(ch); + case 'D': + return !IsAsciiDigit(ch); + case 'f': + return ch == '\f'; + case 'n': + return ch == '\n'; + case 'r': + return ch == '\r'; + case 's': + return IsAsciiWhiteSpace(ch); + case 'S': + return !IsAsciiWhiteSpace(ch); + case 't': + return ch == '\t'; + case 'v': + return ch == '\v'; + case 'w': + return IsAsciiWordChar(ch); + case 'W': + return !IsAsciiWordChar(ch); } return IsAsciiPunct(pattern_char) && pattern_char == ch; } @@ -800,7 +789,8 @@ bool AtomMatchesChar(bool escaped, char pattern_char, char ch) { // Helper function used by ValidateRegex() to format error messages. static std::string FormatRegexSyntaxError(const char* regex, int index) { return (Message() << "Syntax error at index " << index - << " in simple regular expression \"" << regex << "\": ").GetString(); + << " in simple regular expression \"" << regex << "\": ") + .GetString(); } // Generates non-fatal failures and returns false if regex is invalid; @@ -842,12 +832,12 @@ bool ValidateRegex(const char* regex) { << "'$' can only appear at the end."; is_valid = false; } else if (IsInSet(ch, "()[]{}|")) { - ADD_FAILURE() << FormatRegexSyntaxError(regex, i) - << "'" << ch << "' is unsupported."; + ADD_FAILURE() << FormatRegexSyntaxError(regex, i) << "'" << ch + << "' is unsupported."; is_valid = false; } else if (IsRepeat(ch) && !prev_repeatable) { - ADD_FAILURE() << FormatRegexSyntaxError(regex, i) - << "'" << ch << "' can only follow a repeatable token."; + ADD_FAILURE() << FormatRegexSyntaxError(regex, i) << "'" << ch + << "' can only follow a repeatable token."; is_valid = false; } @@ -865,12 +855,10 @@ bool ValidateRegex(const char* regex) { // characters to be indexable by size_t, in which case the test will // probably time out anyway. We are fine with this limitation as // std::string has it too. -bool MatchRepetitionAndRegexAtHead( - bool escaped, char c, char repeat, const char* regex, - const char* str) { +bool MatchRepetitionAndRegexAtHead(bool escaped, char c, char repeat, + const char* regex, const char* str) { const size_t min_count = (repeat == '+') ? 1 : 0; - const size_t max_count = (repeat == '?') ? 1 : - static_cast<size_t>(-1) - 1; + const size_t max_count = (repeat == '?') ? 1 : static_cast<size_t>(-1) - 1; // We cannot call numeric_limits::max() as it conflicts with the // max() macro on Windows. @@ -883,8 +871,7 @@ bool MatchRepetitionAndRegexAtHead( // greedy match. return true; } - if (str[i] == '\0' || !AtomMatchesChar(escaped, c, str[i])) - return false; + if (str[i] == '\0' || !AtomMatchesChar(escaped, c, str[i])) return false; } return false; } @@ -898,25 +885,23 @@ bool MatchRegexAtHead(const char* regex, const char* str) { // "$" only matches the end of a string. Note that regex being // valid guarantees that there's nothing after "$" in it. - if (*regex == '$') - return *str == '\0'; + if (*regex == '$') return *str == '\0'; // Is the first thing in regex an escape sequence? const bool escaped = *regex == '\\'; - if (escaped) - ++regex; + if (escaped) ++regex; if (IsRepeat(regex[1])) { // MatchRepetitionAndRegexAtHead() calls MatchRegexAtHead(), so // here's an indirect recursion. It terminates as the regex gets // shorter in each recursion. - return MatchRepetitionAndRegexAtHead( - escaped, regex[0], regex[1], regex + 2, str); + return MatchRepetitionAndRegexAtHead(escaped, regex[0], regex[1], regex + 2, + str); } else { // regex isn't empty, isn't "$", and doesn't start with a // repetition. We match the first atom of regex with the first // character of str and recurse. return (*str != '\0') && AtomMatchesChar(escaped, *regex, *str) && - MatchRegexAtHead(regex + 1, str + 1); + MatchRegexAtHead(regex + 1, str + 1); } } @@ -931,13 +916,11 @@ bool MatchRegexAtHead(const char* regex, const char* str) { bool MatchRegexAnywhere(const char* regex, const char* str) { if (regex == nullptr || str == nullptr) return false; - if (*regex == '^') - return MatchRegexAtHead(regex + 1, str); + if (*regex == '^') return MatchRegexAtHead(regex + 1, str); // A successful match can be anywhere in str. do { - if (MatchRegexAtHead(regex, str)) - return true; + if (MatchRegexAtHead(regex, str)) return true; } while (*str++ != '\0'); return false; } @@ -1018,8 +1001,8 @@ GTEST_API_ ::std::string FormatFileLocation(const char* file, int line) { // FormatFileLocation in order to contrast the two functions. // Note that FormatCompilerIndependentFileLocation() does NOT append colon // to the file location it produces, unlike FormatFileLocation(). -GTEST_API_ ::std::string FormatCompilerIndependentFileLocation( - const char* file, int line) { +GTEST_API_ ::std::string FormatCompilerIndependentFileLocation(const char* file, + int line) { const std::string file_name(file == nullptr ? kUnknownFile : file); if (line < 0) @@ -1030,12 +1013,13 @@ GTEST_API_ ::std::string FormatCompilerIndependentFileLocation( GTestLog::GTestLog(GTestLogSeverity severity, const char* file, int line) : severity_(severity) { - const char* const marker = - severity == GTEST_INFO ? "[ INFO ]" : - severity == GTEST_WARNING ? "[WARNING]" : - severity == GTEST_ERROR ? "[ ERROR ]" : "[ FATAL ]"; - GetStream() << ::std::endl << marker << " " - << FormatFileLocation(file, line).c_str() << ": "; + const char* const marker = severity == GTEST_INFO ? "[ INFO ]" + : severity == GTEST_WARNING ? "[WARNING]" + : severity == GTEST_ERROR ? "[ ERROR ]" + : "[ FATAL ]"; + GetStream() << ::std::endl + << marker << " " << FormatFileLocation(file, line).c_str() + << ": "; } // Flushes the buffers and, if severity is GTEST_FATAL, aborts the program. @@ -1058,27 +1042,26 @@ class CapturedStream { public: // The ctor redirects the stream to a temporary file. explicit CapturedStream(int fd) : fd_(fd), uncaptured_fd_(dup(fd)) { -# if GTEST_OS_WINDOWS - char temp_dir_path[MAX_PATH + 1] = { '\0' }; // NOLINT - char temp_file_path[MAX_PATH + 1] = { '\0' }; // NOLINT +#if GTEST_OS_WINDOWS + char temp_dir_path[MAX_PATH + 1] = {'\0'}; // NOLINT + char temp_file_path[MAX_PATH + 1] = {'\0'}; // NOLINT ::GetTempPathA(sizeof(temp_dir_path), temp_dir_path); - const UINT success = ::GetTempFileNameA(temp_dir_path, - "gtest_redir", + const UINT success = ::GetTempFileNameA(temp_dir_path, "gtest_redir", 0, // Generate unique file name. temp_file_path); GTEST_CHECK_(success != 0) << "Unable to create a temporary file in " << temp_dir_path; const int captured_fd = creat(temp_file_path, _S_IREAD | _S_IWRITE); - GTEST_CHECK_(captured_fd != -1) << "Unable to open temporary file " - << temp_file_path; + GTEST_CHECK_(captured_fd != -1) + << "Unable to open temporary file " << temp_file_path; filename_ = temp_file_path; -# else +#else // There's no guarantee that a test has write access to the current // directory, so we create the temporary file in a temporary directory. std::string name_template; -# if GTEST_OS_LINUX_ANDROID +#if GTEST_OS_LINUX_ANDROID // Note: Android applications are expected to call the framework's // Context.getExternalStorageDirectory() method through JNI to get // the location of the world-writable SD Card directory. However, @@ -1091,7 +1074,7 @@ class CapturedStream { // '/sdcard' and other variants cannot be relied on, as they are not // guaranteed to be mounted, or may have a delay in mounting. name_template = "/data/local/tmp/"; -# elif GTEST_OS_IOS +#elif GTEST_OS_IOS char user_temp_dir[PATH_MAX + 1]; // Documented alternative to NSTemporaryDirectory() (for obtaining creating @@ -1112,9 +1095,9 @@ class CapturedStream { name_template = user_temp_dir; if (name_template.back() != GTEST_PATH_SEP_[0]) name_template.push_back(GTEST_PATH_SEP_[0]); -# else +#else name_template = "/tmp/"; -# endif +#endif name_template.append("gtest_captured_stream.XXXXXX"); // mkstemp() modifies the string bytes in place, and does not go beyond the @@ -1130,15 +1113,13 @@ class CapturedStream { << " for test; does the test have access to the /tmp directory?"; } filename_ = std::move(name_template); -# endif // GTEST_OS_WINDOWS +#endif // GTEST_OS_WINDOWS fflush(nullptr); dup2(captured_fd, fd_); close(captured_fd); } - ~CapturedStream() { - remove(filename_.c_str()); - } + ~CapturedStream() { remove(filename_.c_str()); } std::string GetCapturedString() { if (uncaptured_fd_ != -1) { @@ -1215,10 +1196,6 @@ std::string GetCapturedStderr() { #endif // GTEST_HAS_STREAM_REDIRECTION - - - - size_t GetFileSize(FILE* file) { fseek(file, 0, SEEK_END); return static_cast<size_t>(ftell(file)); @@ -1236,7 +1213,8 @@ std::string ReadEntireFile(FILE* file) { // Keeps reading the file until we cannot read further or the // pre-determined file size is reached. do { - bytes_last_read = fread(buffer+bytes_read, 1, file_size-bytes_read, file); + bytes_last_read = + fread(buffer + bytes_read, 1, file_size - bytes_read, file); bytes_read += bytes_last_read; } while (bytes_last_read > 0 && bytes_read < file_size); @@ -1324,7 +1302,7 @@ bool ParseInt32(const Message& src_text, const char* str, int32_t* value) { // LONG_MAX or LONG_MIN when the input overflows.) result != long_value // The parsed value overflows as an int32_t. - ) { + ) { Message msg; msg << "WARNING: " << src_text << " is expected to be a 32-bit integer, but actually" @@ -1368,8 +1346,8 @@ int32_t Int32FromGTestEnv(const char* flag, int32_t default_value) { } int32_t result = default_value; - if (!ParseInt32(Message() << "Environment variable " << env_var, - string_value, &result)) { + if (!ParseInt32(Message() << "Environment variable " << env_var, string_value, + &result)) { printf("The default value %s is used.\n", (Message() << default_value).GetString().c_str()); fflush(stdout); @@ -1388,7 +1366,7 @@ int32_t Int32FromGTestEnv(const char* flag, int32_t default_value) { // not check that the flag is 'output' // In essence this checks an env variable called XML_OUTPUT_FILE // and if it is set we prepend "xml:" to its value, if it not set we return "" -std::string OutputFlagAlsoCheckEnvVar(){ +std::string OutputFlagAlsoCheckEnvVar() { std::string default_value_for_output_flag = ""; const char* xml_output_file_env = posix::GetEnv("XML_OUTPUT_FILE"); if (nullptr != xml_output_file_env) { diff --git a/googletest/src/gtest-printers.cc b/googletest/src/gtest-printers.cc index 0c80ab7..f3976d2 100644 --- a/googletest/src/gtest-printers.cc +++ b/googletest/src/gtest-printers.cc @@ -27,7 +27,6 @@ // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - // Google Test - The Google C++ Testing and Mocking Framework // // This file implements a universal value printer that can print a @@ -101,7 +100,7 @@ void PrintBytesInObjectToImpl(const unsigned char* obj_bytes, size_t count, PrintByteSegmentInObjectTo(obj_bytes, 0, kChunkSize, os); *os << " ... "; // Rounds up to 2-byte boundary. - const size_t resume_pos = (count - kChunkSize + 1)/2*2; + const size_t resume_pos = (count - kChunkSize + 1) / 2 * 2; PrintByteSegmentInObjectTo(obj_bytes, resume_pos, count - resume_pos, os); } *os << ">"; @@ -136,11 +135,7 @@ void PrintBytesInObjectTo(const unsigned char* obj_bytes, size_t count, // - as is if it's a printable ASCII (e.g. 'a', '2', ' '), // - as a hexadecimal escape sequence (e.g. '\x7F'), or // - as a special escape sequence (e.g. '\r', '\n'). -enum CharFormat { - kAsIs, - kHexEscape, - kSpecialEscape -}; +enum CharFormat { kAsIs, kHexEscape, kSpecialEscape }; // Returns true if c is a printable ASCII character. We test the // value of c directly instead of calling isprint(), which is buggy on @@ -213,35 +208,21 @@ static CharFormat PrintAsStringLiteralTo(char32_t c, ostream* os) { } } -static const char* GetCharWidthPrefix(char) { - return ""; -} +static const char* GetCharWidthPrefix(char) { return ""; } -static const char* GetCharWidthPrefix(signed char) { - return ""; -} +static const char* GetCharWidthPrefix(signed char) { return ""; } -static const char* GetCharWidthPrefix(unsigned char) { - return ""; -} +static const char* GetCharWidthPrefix(unsigned char) { return ""; } #ifdef __cpp_char8_t -static const char* GetCharWidthPrefix(char8_t) { - return "u8"; -} +static const char* GetCharWidthPrefix(char8_t) { return "u8"; } #endif -static const char* GetCharWidthPrefix(char16_t) { - return "u"; -} +static const char* GetCharWidthPrefix(char16_t) { return "u"; } -static const char* GetCharWidthPrefix(char32_t) { - return "U"; -} +static const char* GetCharWidthPrefix(char32_t) { return "U"; } -static const char* GetCharWidthPrefix(wchar_t) { - return "L"; -} +static const char* GetCharWidthPrefix(wchar_t) { return "L"; } // Prints a char c as if it's part of a string literal, escaping it when // necessary; returns how c was formatted. @@ -276,8 +257,7 @@ void PrintCharAndCodeTo(Char c, ostream* os) { // To aid user debugging, we also print c's code in decimal, unless // it's 0 (in which case c was printed as '\\0', making the code // obvious). - if (c == 0) - return; + if (c == 0) return; *os << " (" << static_cast<int>(c); // For more convenience, we print c's code again in hexadecimal, @@ -354,12 +334,10 @@ void PrintTo(__int128_t v, ::std::ostream* os) { // The array starts at begin, the length is len, it may include '\0' characters // and may not be NUL-terminated. template <typename CharType> -GTEST_ATTRIBUTE_NO_SANITIZE_MEMORY_ -GTEST_ATTRIBUTE_NO_SANITIZE_ADDRESS_ -GTEST_ATTRIBUTE_NO_SANITIZE_HWADDRESS_ -GTEST_ATTRIBUTE_NO_SANITIZE_THREAD_ -static CharFormat PrintCharsAsStringTo( - const CharType* begin, size_t len, ostream* os) { +GTEST_ATTRIBUTE_NO_SANITIZE_MEMORY_ GTEST_ATTRIBUTE_NO_SANITIZE_ADDRESS_ + GTEST_ATTRIBUTE_NO_SANITIZE_HWADDRESS_ + GTEST_ATTRIBUTE_NO_SANITIZE_THREAD_ static CharFormat + PrintCharsAsStringTo(const CharType* begin, size_t len, ostream* os) { const char* const quote_prefix = GetCharWidthPrefix(*begin); *os << quote_prefix << "\""; bool is_previous_hex = false; @@ -385,12 +363,11 @@ static CharFormat PrintCharsAsStringTo( // Prints a (const) char/wchar_t array of 'len' elements, starting at address // 'begin'. CharType must be either char or wchar_t. template <typename CharType> -GTEST_ATTRIBUTE_NO_SANITIZE_MEMORY_ -GTEST_ATTRIBUTE_NO_SANITIZE_ADDRESS_ -GTEST_ATTRIBUTE_NO_SANITIZE_HWADDRESS_ -GTEST_ATTRIBUTE_NO_SANITIZE_THREAD_ -static void UniversalPrintCharArray( - const CharType* begin, size_t len, ostream* os) { +GTEST_ATTRIBUTE_NO_SANITIZE_MEMORY_ GTEST_ATTRIBUTE_NO_SANITIZE_ADDRESS_ + GTEST_ATTRIBUTE_NO_SANITIZE_HWADDRESS_ + GTEST_ATTRIBUTE_NO_SANITIZE_THREAD_ static void + UniversalPrintCharArray(const CharType* begin, size_t len, + ostream* os) { // The code // const char kFoo[] = "foo"; // generates an array of 4, not 3, elements, with the last one being '\0'. @@ -481,28 +458,28 @@ void PrintTo(const wchar_t* s, ostream* os) { PrintCStringTo(s, os); } namespace { bool ContainsUnprintableControlCodes(const char* str, size_t length) { - const unsigned char *s = reinterpret_cast<const unsigned char *>(str); + const unsigned char* s = reinterpret_cast<const unsigned char*>(str); for (size_t i = 0; i < length; i++) { unsigned char ch = *s++; if (std::iscntrl(ch)) { - switch (ch) { + switch (ch) { case '\t': case '\n': case '\r': break; default: return true; - } } + } } return false; } -bool IsUTF8TrailByte(unsigned char t) { return 0x80 <= t && t<= 0xbf; } +bool IsUTF8TrailByte(unsigned char t) { return 0x80 <= t && t <= 0xbf; } bool IsValidUTF8(const char* str, size_t length) { - const unsigned char *s = reinterpret_cast<const unsigned char *>(str); + const unsigned char* s = reinterpret_cast<const unsigned char*>(str); for (size_t i = 0; i < length;) { unsigned char lead = s[i++]; @@ -515,15 +492,13 @@ bool IsValidUTF8(const char* str, size_t length) { } else if (lead <= 0xdf && (i + 1) <= length && IsUTF8TrailByte(s[i])) { ++i; // 2-byte character } else if (0xe0 <= lead && lead <= 0xef && (i + 2) <= length && - IsUTF8TrailByte(s[i]) && - IsUTF8TrailByte(s[i + 1]) && + IsUTF8TrailByte(s[i]) && IsUTF8TrailByte(s[i + 1]) && // check for non-shortest form and surrogate (lead != 0xe0 || s[i] >= 0xa0) && (lead != 0xed || s[i] < 0xa0)) { i += 2; // 3-byte character } else if (0xf0 <= lead && lead <= 0xf4 && (i + 3) <= length && - IsUTF8TrailByte(s[i]) && - IsUTF8TrailByte(s[i + 1]) && + IsUTF8TrailByte(s[i]) && IsUTF8TrailByte(s[i + 1]) && IsUTF8TrailByte(s[i + 2]) && // check for non-shortest form (lead != 0xf0 || s[i] >= 0x90) && diff --git a/googletest/src/gtest-test-part.cc b/googletest/src/gtest-test-part.cc index a938683..eb7c8d1 100644 --- a/googletest/src/gtest-test-part.cc +++ b/googletest/src/gtest-test-part.cc @@ -51,13 +51,11 @@ std::ostream& operator<<(std::ostream& os, const TestPartResult& result) { return os << internal::FormatFileLocation(result.file_name(), result.line_number()) << " " - << (result.type() == TestPartResult::kSuccess - ? "Success" - : result.type() == TestPartResult::kSkip - ? "Skipped" - : result.type() == TestPartResult::kFatalFailure - ? "Fatal failure" - : "Non-fatal failure") + << (result.type() == TestPartResult::kSuccess ? "Success" + : result.type() == TestPartResult::kSkip ? "Skipped" + : result.type() == TestPartResult::kFatalFailure + ? "Fatal failure" + : "Non-fatal failure") << ":\n" << result.message() << std::endl; } @@ -86,8 +84,8 @@ namespace internal { HasNewFatalFailureHelper::HasNewFatalFailureHelper() : has_new_fatal_failure_(false), - original_reporter_(GetUnitTestImpl()-> - GetTestPartResultReporterForCurrentThread()) { + original_reporter_( + GetUnitTestImpl()->GetTestPartResultReporterForCurrentThread()) { GetUnitTestImpl()->SetTestPartResultReporterForCurrentThread(this); } @@ -98,8 +96,7 @@ HasNewFatalFailureHelper::~HasNewFatalFailureHelper() { void HasNewFatalFailureHelper::ReportTestPartResult( const TestPartResult& result) { - if (result.fatally_failed()) - has_new_fatal_failure_ = true; + if (result.fatally_failed()) has_new_fatal_failure_ = true; original_reporter_->ReportTestPartResult(result); } diff --git a/googletest/src/gtest-typed-test.cc b/googletest/src/gtest-typed-test.cc index c02c3df..a2828b8 100644 --- a/googletest/src/gtest-typed-test.cc +++ b/googletest/src/gtest-typed-test.cc @@ -27,7 +27,6 @@ // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - #include "gtest/gtest-typed-test.h" #include "gtest/gtest.h" @@ -38,8 +37,7 @@ namespace internal { // Skips to the first non-space char in str. Returns an empty string if str // contains only whitespace characters. static const char* SkipSpaces(const char* str) { - while (IsSpace(*str)) - str++; + while (IsSpace(*str)) str++; return str; } @@ -85,8 +83,7 @@ const char* TypedTestSuitePState::VerifyRegisteredTestNames( } for (RegisteredTestIter it = registered_tests_.begin(); - it != registered_tests_.end(); - ++it) { + it != registered_tests_.end(); ++it) { if (tests.count(it->first) == 0) { errors << "You forgot to list test " << it->first << ".\n"; } diff --git a/googletest/src/gtest.cc b/googletest/src/gtest.cc index 396fdfe..e422e92 100644 --- a/googletest/src/gtest.cc +++ b/googletest/src/gtest.cc @@ -60,69 +60,70 @@ #if GTEST_OS_LINUX -# include <fcntl.h> // NOLINT -# include <limits.h> // NOLINT -# include <sched.h> // NOLINT +#include <fcntl.h> // NOLINT +#include <limits.h> // NOLINT +#include <sched.h> // NOLINT // Declares vsnprintf(). This header is not available on Windows. -# include <strings.h> // NOLINT -# include <sys/mman.h> // NOLINT -# include <sys/time.h> // NOLINT -# include <unistd.h> // NOLINT -# include <string> +#include <strings.h> // NOLINT +#include <sys/mman.h> // NOLINT +#include <sys/time.h> // NOLINT +#include <unistd.h> // NOLINT + +#include <string> #elif GTEST_OS_ZOS -# include <sys/time.h> // NOLINT +#include <sys/time.h> // NOLINT // On z/OS we additionally need strings.h for strcasecmp. -# include <strings.h> // NOLINT +#include <strings.h> // NOLINT #elif GTEST_OS_WINDOWS_MOBILE // We are on Windows CE. -# include <windows.h> // NOLINT -# undef min +#include <windows.h> // NOLINT +#undef min #elif GTEST_OS_WINDOWS // We are on Windows proper. -# include <windows.h> // NOLINT -# undef min +#include <windows.h> // NOLINT +#undef min #ifdef _MSC_VER -# include <crtdbg.h> // NOLINT +#include <crtdbg.h> // NOLINT #endif -# include <io.h> // NOLINT -# include <sys/timeb.h> // NOLINT -# include <sys/types.h> // NOLINT -# include <sys/stat.h> // NOLINT +#include <io.h> // NOLINT +#include <sys/stat.h> // NOLINT +#include <sys/timeb.h> // NOLINT +#include <sys/types.h> // NOLINT -# if GTEST_OS_WINDOWS_MINGW -# include <sys/time.h> // NOLINT -# endif // GTEST_OS_WINDOWS_MINGW +#if GTEST_OS_WINDOWS_MINGW +#include <sys/time.h> // NOLINT +#endif // GTEST_OS_WINDOWS_MINGW #else // cpplint thinks that the header is already included, so we want to // silence it. -# include <sys/time.h> // NOLINT -# include <unistd.h> // NOLINT +#include <sys/time.h> // NOLINT +#include <unistd.h> // NOLINT #endif // GTEST_OS_LINUX #if GTEST_HAS_EXCEPTIONS -# include <stdexcept> +#include <stdexcept> #endif #if GTEST_CAN_STREAM_RESULTS_ -# include <arpa/inet.h> // NOLINT -# include <netdb.h> // NOLINT -# include <sys/socket.h> // NOLINT -# include <sys/types.h> // NOLINT +#include <arpa/inet.h> // NOLINT +#include <netdb.h> // NOLINT +#include <sys/socket.h> // NOLINT +#include <sys/types.h> // NOLINT #endif #include "src/gtest-internal-inl.h" #if GTEST_OS_WINDOWS -# define vsnprintf _vsnprintf +#define vsnprintf _vsnprintf #endif // GTEST_OS_WINDOWS #if GTEST_OS_MAC @@ -271,8 +272,7 @@ GTEST_DEFINE_bool_( "install a signal handler that dumps debugging information when fatal " "signals are raised."); -GTEST_DEFINE_bool_(list_tests, false, - "List all tests without running them."); +GTEST_DEFINE_bool_(list_tests, false, "List all tests without running them."); // The net priority order after flag processing is thus: // --gtest_output command line flag @@ -374,10 +374,9 @@ namespace internal { uint32_t Random::Generate(uint32_t range) { // These constants are the same as are used in glibc's rand(3). // Use wider types than necessary to prevent unsigned overflow diagnostics. - state_ = static_cast<uint32_t>(1103515245ULL*state_ + 12345U) % kMaxRange; + state_ = static_cast<uint32_t>(1103515245ULL * state_ + 12345U) % kMaxRange; - GTEST_CHECK_(range > 0) - << "Cannot generate a number in the range [0, 0)."; + GTEST_CHECK_(range > 0) << "Cannot generate a number in the range [0, 0)."; GTEST_CHECK_(range <= kMaxRange) << "Generation of a number in [0, " << range << ") was requested, " << "but this can only generate numbers in [0, " << kMaxRange << ")."; @@ -422,26 +421,20 @@ static bool ShouldRunTestSuite(const TestSuite* test_suite) { } // AssertHelper constructor. -AssertHelper::AssertHelper(TestPartResult::Type type, - const char* file, - int line, - const char* message) - : data_(new AssertHelperData(type, file, line, message)) { -} +AssertHelper::AssertHelper(TestPartResult::Type type, const char* file, + int line, const char* message) + : data_(new AssertHelperData(type, file, line, message)) {} -AssertHelper::~AssertHelper() { - delete data_; -} +AssertHelper::~AssertHelper() { delete data_; } // Message assignment, for assertion streaming support. void AssertHelper::operator=(const Message& message) const { - UnitTest::GetInstance()-> - AddTestPartResult(data_->type, data_->file, data_->line, - AppendUserMessage(data_->message, message), - UnitTest::GetInstance()->impl() - ->CurrentOsStackTraceExceptTop(1) - // Skips the stack frame for this function itself. - ); // NOLINT + UnitTest::GetInstance()->AddTestPartResult( + data_->type, data_->file, data_->line, + AppendUserMessage(data_->message, message), + UnitTest::GetInstance()->impl()->CurrentOsStackTraceExceptTop(1) + // Skips the stack frame for this function itself. + ); // NOLINT } namespace { @@ -478,7 +471,6 @@ class FailureTest : public Test { const bool as_error_; }; - } // namespace std::set<std::string>* GetIgnoredParameterizedTestSuites() { @@ -522,7 +514,8 @@ void InsertSyntheticTestCase(const std::string& name, CodeLocation location, "To suppress this error for this test suite, insert the following line " "(in a non-header) in the namespace it is defined in:" "\n\n" - "GTEST_ALLOW_UNINSTANTIATED_PARAMETERIZED_TEST(" + name + ");"; + "GTEST_ALLOW_UNINSTANTIATED_PARAMETERIZED_TEST(" + + name + ");"; std::string full_name = "UninstantiatedParameterizedTestSuite<" + name + ">"; RegisterTest( // @@ -542,19 +535,18 @@ void RegisterTypeParameterizedTestSuite(const char* test_suite_name, } void RegisterTypeParameterizedTestSuiteInstantiation(const char* case_name) { - GetUnitTestImpl() - ->type_parameterized_test_registry() - .RegisterInstantiation(case_name); + GetUnitTestImpl()->type_parameterized_test_registry().RegisterInstantiation( + case_name); } void TypeParameterizedTestSuiteRegistry::RegisterTestSuite( const char* test_suite_name, CodeLocation code_location) { suites_.emplace(std::string(test_suite_name), - TypeParameterizedTestSuiteInfo(code_location)); + TypeParameterizedTestSuiteInfo(code_location)); } void TypeParameterizedTestSuiteRegistry::RegisterInstantiation( - const char* test_suite_name) { + const char* test_suite_name) { auto it = suites_.find(std::string(test_suite_name)); if (it != suites_.end()) { it->second.instantiated = true; @@ -648,16 +640,15 @@ std::string UnitTestOptions::GetAbsolutePathToOutputFile() { const char* const gtest_output_flag = s.c_str(); std::string format = GetOutputFormat(); - if (format.empty()) - format = std::string(kDefaultOutputFormat); + if (format.empty()) format = std::string(kDefaultOutputFormat); const char* const colon = strchr(gtest_output_flag, ':'); if (colon == nullptr) return internal::FilePath::MakeFileName( - internal::FilePath( - UnitTest::GetInstance()->original_working_dir()), - internal::FilePath(kDefaultOutputFile), 0, - format.c_str()).string(); + internal::FilePath( + UnitTest::GetInstance()->original_working_dir()), + internal::FilePath(kDefaultOutputFile), 0, format.c_str()) + .string(); internal::FilePath output_name(colon + 1); if (!output_name.IsAbsolutePath()) @@ -665,8 +656,7 @@ std::string UnitTestOptions::GetAbsolutePathToOutputFile() { internal::FilePath(UnitTest::GetInstance()->original_working_dir()), internal::FilePath(colon + 1)); - if (!output_name.IsDirectory()) - return output_name.string(); + if (!output_name.IsDirectory()) return output_name.string(); internal::FilePath result(internal::FilePath::GenerateUniqueFileName( output_name, internal::GetCurrentExecutableName(), @@ -877,8 +867,7 @@ int UnitTestOptions::GTestShouldProcessSEH(DWORD exception_code) { // results. Intercepts only failures from the current thread. ScopedFakeTestPartResultReporter::ScopedFakeTestPartResultReporter( TestPartResultArray* result) - : intercept_mode_(INTERCEPT_ONLY_CURRENT_THREAD), - result_(result) { + : intercept_mode_(INTERCEPT_ONLY_CURRENT_THREAD), result_(result) { Init(); } @@ -887,8 +876,7 @@ ScopedFakeTestPartResultReporter::ScopedFakeTestPartResultReporter( // results. ScopedFakeTestPartResultReporter::ScopedFakeTestPartResultReporter( InterceptMode intercept_mode, TestPartResultArray* result) - : intercept_mode_(intercept_mode), - result_(result) { + : intercept_mode_(intercept_mode), result_(result) { Init(); } @@ -932,9 +920,7 @@ namespace internal { // from user test code. GetTestTypeId() is guaranteed to always // return the same value, as it always calls GetTypeId<>() from the // gtest.cc, which is within the Google Test framework. -TypeId GetTestTypeId() { - return GetTypeId<Test>(); -} +TypeId GetTestTypeId() { return GetTypeId<Test>(); } // The value of GetTestTypeId() as seen from within the Google Test // library. This is solely for testing GetTestTypeId(). @@ -949,9 +935,9 @@ static AssertionResult HasOneFailure(const char* /* results_expr */, const TestPartResultArray& results, TestPartResult::Type type, const std::string& substr) { - const std::string expected(type == TestPartResult::kFatalFailure ? - "1 fatal failure" : - "1 non-fatal failure"); + const std::string expected(type == TestPartResult::kFatalFailure + ? "1 fatal failure" + : "1 non-fatal failure"); Message msg; if (results.size() != 1) { msg << "Expected: " << expected << "\n" @@ -970,10 +956,10 @@ static AssertionResult HasOneFailure(const char* /* results_expr */, } if (strstr(r.message(), substr.c_str()) == nullptr) { - return AssertionFailure() << "Expected: " << expected << " containing \"" - << substr << "\"\n" - << " Actual:\n" - << r; + return AssertionFailure() + << "Expected: " << expected << " containing \"" << substr << "\"\n" + << " Actual:\n" + << r; } return AssertionSuccess(); @@ -996,7 +982,8 @@ SingleFailureChecker::~SingleFailureChecker() { } DefaultGlobalTestPartResultReporter::DefaultGlobalTestPartResultReporter( - UnitTestImpl* unit_test) : unit_test_(unit_test) {} + UnitTestImpl* unit_test) + : unit_test_(unit_test) {} void DefaultGlobalTestPartResultReporter::ReportTestPartResult( const TestPartResult& result) { @@ -1005,7 +992,8 @@ void DefaultGlobalTestPartResultReporter::ReportTestPartResult( } DefaultPerThreadTestPartResultReporter::DefaultPerThreadTestPartResultReporter( - UnitTestImpl* unit_test) : unit_test_(unit_test) {} + UnitTestImpl* unit_test) + : unit_test_(unit_test) {} void DefaultPerThreadTestPartResultReporter::ReportTestPartResult( const TestPartResult& result) { @@ -1159,8 +1147,7 @@ LPCWSTR String::AnsiToUtf16(const char* ansi) { const int unicode_length = MultiByteToWideChar(CP_ACP, 0, ansi, length, nullptr, 0); WCHAR* unicode = new WCHAR[unicode_length + 1]; - MultiByteToWideChar(CP_ACP, 0, ansi, length, - unicode, unicode_length); + MultiByteToWideChar(CP_ACP, 0, ansi, length, unicode, unicode_length); unicode[unicode_length] = 0; return unicode; } @@ -1169,7 +1156,7 @@ LPCWSTR String::AnsiToUtf16(const char* ansi) { // memory using new. The caller is responsible for deleting the return // value using delete[]. Returns the ANSI string, or NULL if the // input is NULL. -const char* String::Utf16ToAnsi(LPCWSTR utf16_str) { +const char* String::Utf16ToAnsi(LPCWSTR utf16_str) { if (!utf16_str) return nullptr; const int ansi_length = WideCharToMultiByte(CP_ACP, 0, utf16_str, -1, nullptr, 0, nullptr, nullptr); @@ -1188,7 +1175,7 @@ const char* String::Utf16ToAnsi(LPCWSTR utf16_str) { // Unlike strcmp(), this function can handle NULL argument(s). A NULL // C string is considered different to any non-NULL C string, // including the empty string. -bool String::CStringEquals(const char * lhs, const char * rhs) { +bool String::CStringEquals(const char* lhs, const char* rhs) { if (lhs == nullptr) return rhs == nullptr; if (rhs == nullptr) return false; @@ -1202,11 +1189,10 @@ bool String::CStringEquals(const char * lhs, const char * rhs) { // encoding, and streams the result to the given Message object. static void StreamWideCharsToMessage(const wchar_t* wstr, size_t length, Message* msg) { - for (size_t i = 0; i != length; ) { // NOLINT + for (size_t i = 0; i != length;) { // NOLINT if (wstr[i] != L'\0') { *msg << WideStringToUtf8(wstr + i, static_cast<int>(length - i)); - while (i != length && wstr[i] != L'\0') - i++; + while (i != length && wstr[i] != L'\0') i++; } else { *msg << '\0'; i++; @@ -1248,17 +1234,17 @@ Message::Message() : ss_(new ::std::stringstream) { // These two overloads allow streaming a wide C string to a Message // using the UTF-8 encoding. -Message& Message::operator <<(const wchar_t* wide_c_str) { +Message& Message::operator<<(const wchar_t* wide_c_str) { return *this << internal::String::ShowWideCString(wide_c_str); } -Message& Message::operator <<(wchar_t* wide_c_str) { +Message& Message::operator<<(wchar_t* wide_c_str) { return *this << internal::String::ShowWideCString(wide_c_str); } #if GTEST_HAS_STD_WSTRING // Converts the given wide string to a narrow string using the UTF-8 // encoding, and streams the result to this Message object. -Message& Message::operator <<(const ::std::wstring& wstr) { +Message& Message::operator<<(const ::std::wstring& wstr) { internal::StreamWideCharsToMessage(wstr.c_str(), wstr.length(), this); return *this; } @@ -1561,8 +1547,7 @@ std::vector<std::string> SplitEscapedString(const std::string& str) { AssertionResult EqFailure(const char* lhs_expression, const char* rhs_expression, const std::string& lhs_value, - const std::string& rhs_value, - bool ignoring_case) { + const std::string& rhs_value, bool ignoring_case) { Message msg; msg << "Expected equality of these values:"; msg << "\n " << lhs_expression; @@ -1579,10 +1564,8 @@ AssertionResult EqFailure(const char* lhs_expression, } if (!lhs_value.empty() && !rhs_value.empty()) { - const std::vector<std::string> lhs_lines = - SplitEscapedString(lhs_value); - const std::vector<std::string> rhs_lines = - SplitEscapedString(rhs_value); + const std::vector<std::string> lhs_lines = SplitEscapedString(lhs_value); + const std::vector<std::string> rhs_lines = SplitEscapedString(rhs_value); if (lhs_lines.size() > 1 || rhs_lines.size() > 1) { msg << "\nWith diff:\n" << edit_distance::CreateUnifiedDiff(lhs_lines, rhs_lines); @@ -1594,27 +1577,21 @@ AssertionResult EqFailure(const char* lhs_expression, // Constructs a failure message for Boolean assertions such as EXPECT_TRUE. std::string GetBoolAssertionFailureMessage( - const AssertionResult& assertion_result, - const char* expression_text, - const char* actual_predicate_value, - const char* expected_predicate_value) { + const AssertionResult& assertion_result, const char* expression_text, + const char* actual_predicate_value, const char* expected_predicate_value) { const char* actual_message = assertion_result.message(); Message msg; msg << "Value of: " << expression_text << "\n Actual: " << actual_predicate_value; - if (actual_message[0] != '\0') - msg << " (" << actual_message << ")"; + if (actual_message[0] != '\0') msg << " (" << actual_message << ")"; msg << "\nExpected: " << expected_predicate_value; return msg.GetString(); } // Helper function for implementing ASSERT_NEAR. -AssertionResult DoubleNearPredFormat(const char* expr1, - const char* expr2, - const char* abs_error_expr, - double val1, - double val2, - double abs_error) { +AssertionResult DoubleNearPredFormat(const char* expr1, const char* expr2, + const char* abs_error_expr, double val1, + double val2, double abs_error) { const double diff = fabs(val1 - val2); if (diff <= abs_error) return AssertionSuccess(); @@ -1644,20 +1621,17 @@ AssertionResult DoubleNearPredFormat(const char* expr1, "EXPECT_EQUAL. Consider using EXPECT_DOUBLE_EQ instead."; } return AssertionFailure() - << "The difference between " << expr1 << " and " << expr2 - << " is " << diff << ", which exceeds " << abs_error_expr << ", where\n" - << expr1 << " evaluates to " << val1 << ",\n" - << expr2 << " evaluates to " << val2 << ", and\n" - << abs_error_expr << " evaluates to " << abs_error << "."; + << "The difference between " << expr1 << " and " << expr2 << " is " + << diff << ", which exceeds " << abs_error_expr << ", where\n" + << expr1 << " evaluates to " << val1 << ",\n" + << expr2 << " evaluates to " << val2 << ", and\n" + << abs_error_expr << " evaluates to " << abs_error << "."; } - // Helper template for implementing FloatLE() and DoubleLE(). template <typename RawType> -AssertionResult FloatingPointLE(const char* expr1, - const char* expr2, - RawType val1, - RawType val2) { +AssertionResult FloatingPointLE(const char* expr1, const char* expr2, + RawType val1, RawType val2) { // Returns success if val1 is less than val2, if (val1 < val2) { return AssertionSuccess(); @@ -1682,24 +1656,24 @@ AssertionResult FloatingPointLE(const char* expr1, << val2; return AssertionFailure() - << "Expected: (" << expr1 << ") <= (" << expr2 << ")\n" - << " Actual: " << StringStreamToString(&val1_ss) << " vs " - << StringStreamToString(&val2_ss); + << "Expected: (" << expr1 << ") <= (" << expr2 << ")\n" + << " Actual: " << StringStreamToString(&val1_ss) << " vs " + << StringStreamToString(&val2_ss); } } // namespace internal // Asserts that val1 is less than, or almost equal to, val2. Fails // otherwise. In particular, it fails if either val1 or val2 is NaN. -AssertionResult FloatLE(const char* expr1, const char* expr2, - float val1, float val2) { +AssertionResult FloatLE(const char* expr1, const char* expr2, float val1, + float val2) { return internal::FloatingPointLE<float>(expr1, expr2, val1, val2); } // Asserts that val1 is less than, or almost equal to, val2. Fails // otherwise. In particular, it fails if either val1 or val2 is NaN. -AssertionResult DoubleLE(const char* expr1, const char* expr2, - double val1, double val2) { +AssertionResult DoubleLE(const char* expr1, const char* expr2, double val1, + double val2) { return internal::FloatingPointLE<double>(expr1, expr2, val1, val2); } @@ -1707,62 +1681,51 @@ namespace internal { // The helper function for {ASSERT|EXPECT}_STREQ. AssertionResult CmpHelperSTREQ(const char* lhs_expression, - const char* rhs_expression, - const char* lhs, + const char* rhs_expression, const char* lhs, const char* rhs) { if (String::CStringEquals(lhs, rhs)) { return AssertionSuccess(); } - return EqFailure(lhs_expression, - rhs_expression, - PrintToString(lhs), - PrintToString(rhs), - false); + return EqFailure(lhs_expression, rhs_expression, PrintToString(lhs), + PrintToString(rhs), false); } // The helper function for {ASSERT|EXPECT}_STRCASEEQ. AssertionResult CmpHelperSTRCASEEQ(const char* lhs_expression, - const char* rhs_expression, - const char* lhs, + const char* rhs_expression, const char* lhs, const char* rhs) { if (String::CaseInsensitiveCStringEquals(lhs, rhs)) { return AssertionSuccess(); } - return EqFailure(lhs_expression, - rhs_expression, - PrintToString(lhs), - PrintToString(rhs), - true); + return EqFailure(lhs_expression, rhs_expression, PrintToString(lhs), + PrintToString(rhs), true); } // The helper function for {ASSERT|EXPECT}_STRNE. AssertionResult CmpHelperSTRNE(const char* s1_expression, - const char* s2_expression, - const char* s1, + const char* s2_expression, const char* s1, const char* s2) { if (!String::CStringEquals(s1, s2)) { return AssertionSuccess(); } else { - return AssertionFailure() << "Expected: (" << s1_expression << ") != (" - << s2_expression << "), actual: \"" - << s1 << "\" vs \"" << s2 << "\""; + return AssertionFailure() + << "Expected: (" << s1_expression << ") != (" << s2_expression + << "), actual: \"" << s1 << "\" vs \"" << s2 << "\""; } } // The helper function for {ASSERT|EXPECT}_STRCASENE. AssertionResult CmpHelperSTRCASENE(const char* s1_expression, - const char* s2_expression, - const char* s1, + const char* s2_expression, const char* s1, const char* s2) { if (!String::CaseInsensitiveCStringEquals(s1, s2)) { return AssertionSuccess(); } else { return AssertionFailure() - << "Expected: (" << s1_expression << ") != (" - << s2_expression << ") (ignoring case), actual: \"" - << s1 << "\" vs \"" << s2 << "\""; + << "Expected: (" << s1_expression << ") != (" << s2_expression + << ") (ignoring case), actual: \"" << s1 << "\" vs \"" << s2 << "\""; } } @@ -1790,8 +1753,7 @@ bool IsSubstringPred(const wchar_t* needle, const wchar_t* haystack) { // StringType here can be either ::std::string or ::std::wstring. template <typename StringType> -bool IsSubstringPred(const StringType& needle, - const StringType& haystack) { +bool IsSubstringPred(const StringType& needle, const StringType& haystack) { return haystack.find(needle) != StringType::npos; } @@ -1800,21 +1762,22 @@ bool IsSubstringPred(const StringType& needle, // StringType here can be const char*, const wchar_t*, ::std::string, // or ::std::wstring. template <typename StringType> -AssertionResult IsSubstringImpl( - bool expected_to_be_substring, - const char* needle_expr, const char* haystack_expr, - const StringType& needle, const StringType& haystack) { +AssertionResult IsSubstringImpl(bool expected_to_be_substring, + const char* needle_expr, + const char* haystack_expr, + const StringType& needle, + const StringType& haystack) { if (IsSubstringPred(needle, haystack) == expected_to_be_substring) return AssertionSuccess(); const bool is_wide_string = sizeof(needle[0]) > 1; const char* const begin_string_quote = is_wide_string ? "L\"" : "\""; return AssertionFailure() - << "Value of: " << needle_expr << "\n" - << " Actual: " << begin_string_quote << needle << "\"\n" - << "Expected: " << (expected_to_be_substring ? "" : "not ") - << "a substring of " << haystack_expr << "\n" - << "Which is: " << begin_string_quote << haystack << "\""; + << "Value of: " << needle_expr << "\n" + << " Actual: " << begin_string_quote << needle << "\"\n" + << "Expected: " << (expected_to_be_substring ? "" : "not ") + << "a substring of " << haystack_expr << "\n" + << "Which is: " << begin_string_quote << haystack << "\""; } } // namespace @@ -1823,52 +1786,52 @@ AssertionResult IsSubstringImpl( // substring of haystack (NULL is considered a substring of itself // only), and return an appropriate error message when they fail. -AssertionResult IsSubstring( - const char* needle_expr, const char* haystack_expr, - const char* needle, const char* haystack) { +AssertionResult IsSubstring(const char* needle_expr, const char* haystack_expr, + const char* needle, const char* haystack) { return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack); } -AssertionResult IsSubstring( - const char* needle_expr, const char* haystack_expr, - const wchar_t* needle, const wchar_t* haystack) { +AssertionResult IsSubstring(const char* needle_expr, const char* haystack_expr, + const wchar_t* needle, const wchar_t* haystack) { return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack); } -AssertionResult IsNotSubstring( - const char* needle_expr, const char* haystack_expr, - const char* needle, const char* haystack) { +AssertionResult IsNotSubstring(const char* needle_expr, + const char* haystack_expr, const char* needle, + const char* haystack) { return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack); } -AssertionResult IsNotSubstring( - const char* needle_expr, const char* haystack_expr, - const wchar_t* needle, const wchar_t* haystack) { +AssertionResult IsNotSubstring(const char* needle_expr, + const char* haystack_expr, const wchar_t* needle, + const wchar_t* haystack) { return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack); } -AssertionResult IsSubstring( - const char* needle_expr, const char* haystack_expr, - const ::std::string& needle, const ::std::string& haystack) { +AssertionResult IsSubstring(const char* needle_expr, const char* haystack_expr, + const ::std::string& needle, + const ::std::string& haystack) { return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack); } -AssertionResult IsNotSubstring( - const char* needle_expr, const char* haystack_expr, - const ::std::string& needle, const ::std::string& haystack) { +AssertionResult IsNotSubstring(const char* needle_expr, + const char* haystack_expr, + const ::std::string& needle, + const ::std::string& haystack) { return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack); } #if GTEST_HAS_STD_WSTRING -AssertionResult IsSubstring( - const char* needle_expr, const char* haystack_expr, - const ::std::wstring& needle, const ::std::wstring& haystack) { +AssertionResult IsSubstring(const char* needle_expr, const char* haystack_expr, + const ::std::wstring& needle, + const ::std::wstring& haystack) { return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack); } -AssertionResult IsNotSubstring( - const char* needle_expr, const char* haystack_expr, - const ::std::wstring& needle, const ::std::wstring& haystack) { +AssertionResult IsNotSubstring(const char* needle_expr, + const char* haystack_expr, + const ::std::wstring& needle, + const ::std::wstring& haystack) { return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack); } #endif // GTEST_HAS_STD_WSTRING @@ -1880,43 +1843,42 @@ namespace internal { namespace { // Helper function for IsHRESULT{SuccessFailure} predicates -AssertionResult HRESULTFailureHelper(const char* expr, - const char* expected, +AssertionResult HRESULTFailureHelper(const char* expr, const char* expected, long hr) { // NOLINT -# if GTEST_OS_WINDOWS_MOBILE || GTEST_OS_WINDOWS_TV_TITLE +#if GTEST_OS_WINDOWS_MOBILE || GTEST_OS_WINDOWS_TV_TITLE // Windows CE doesn't support FormatMessage. const char error_text[] = ""; -# else +#else // Looks up the human-readable system message for the HRESULT code // and since we're not passing any params to FormatMessage, we don't // want inserts expanded. - const DWORD kFlags = FORMAT_MESSAGE_FROM_SYSTEM | - FORMAT_MESSAGE_IGNORE_INSERTS; + const DWORD kFlags = + FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS; const DWORD kBufSize = 4096; // Gets the system's human readable message string for this HRESULT. - char error_text[kBufSize] = { '\0' }; + char error_text[kBufSize] = {'\0'}; DWORD message_length = ::FormatMessageA(kFlags, - 0, // no source, we're asking system + 0, // no source, we're asking system static_cast<DWORD>(hr), // the error - 0, // no line width restrictions + 0, // no line width restrictions error_text, // output buffer kBufSize, // buf size nullptr); // no arguments for inserts // Trims tailing white space (FormatMessage leaves a trailing CR-LF) for (; message_length && IsSpace(error_text[message_length - 1]); - --message_length) { + --message_length) { error_text[message_length - 1] = '\0'; } -# endif // GTEST_OS_WINDOWS_MOBILE +#endif // GTEST_OS_WINDOWS_MOBILE const std::string error_hex("0x" + String::FormatHexInt(hr)); return ::testing::AssertionFailure() - << "Expected: " << expr << " " << expected << ".\n" - << " Actual: " << error_hex << " " << error_text << "\n"; + << "Expected: " << expr << " " << expected << ".\n" + << " Actual: " << error_hex << " " << error_text << "\n"; } } // namespace @@ -1950,16 +1912,18 @@ AssertionResult IsHRESULTFailure(const char* expr, long hr) { // NOLINT // 17 - 21 bits 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx // The maximum code-point a one-byte UTF-8 sequence can represent. -constexpr uint32_t kMaxCodePoint1 = (static_cast<uint32_t>(1) << 7) - 1; +constexpr uint32_t kMaxCodePoint1 = (static_cast<uint32_t>(1) << 7) - 1; // The maximum code-point a two-byte UTF-8 sequence can represent. constexpr uint32_t kMaxCodePoint2 = (static_cast<uint32_t>(1) << (5 + 6)) - 1; // The maximum code-point a three-byte UTF-8 sequence can represent. -constexpr uint32_t kMaxCodePoint3 = (static_cast<uint32_t>(1) << (4 + 2*6)) - 1; +constexpr uint32_t kMaxCodePoint3 = + (static_cast<uint32_t>(1) << (4 + 2 * 6)) - 1; // The maximum code-point a four-byte UTF-8 sequence can represent. -constexpr uint32_t kMaxCodePoint4 = (static_cast<uint32_t>(1) << (3 + 3*6)) - 1; +constexpr uint32_t kMaxCodePoint4 = + (static_cast<uint32_t>(1) << (3 + 3 * 6)) - 1; // Chops off the n lowest bits from a bit pattern. Returns the n // lowest bits. As a side effect, the original bit pattern will be @@ -1984,7 +1948,7 @@ std::string CodePointToUtf8(uint32_t code_point) { char str[5]; // Big enough for the largest valid code point. if (code_point <= kMaxCodePoint1) { str[1] = '\0'; - str[0] = static_cast<char>(code_point); // 0xxxxxxx + str[0] = static_cast<char>(code_point); // 0xxxxxxx } else if (code_point <= kMaxCodePoint2) { str[2] = '\0'; str[1] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx @@ -2012,8 +1976,8 @@ std::string CodePointToUtf8(uint32_t code_point) { // and thus should be combined into a single Unicode code point // using CreateCodePointFromUtf16SurrogatePair. inline bool IsUtf16SurrogatePair(wchar_t first, wchar_t second) { - return sizeof(wchar_t) == 2 && - (first & 0xFC00) == 0xD800 && (second & 0xFC00) == 0xDC00; + return sizeof(wchar_t) == 2 && (first & 0xFC00) == 0xD800 && + (second & 0xFC00) == 0xDC00; } // Creates a Unicode code point from UTF16 surrogate pair. @@ -2044,8 +2008,7 @@ inline uint32_t CreateCodePointFromUtf16SurrogatePair(wchar_t first, // and contains invalid UTF-16 surrogate pairs, values in those pairs // will be encoded as individual Unicode characters from Basic Normal Plane. std::string WideStringToUtf8(const wchar_t* str, int num_chars) { - if (num_chars == -1) - num_chars = static_cast<int>(wcslen(str)); + if (num_chars == -1) num_chars = static_cast<int>(wcslen(str)); ::std::stringstream stream; for (int i = 0; i < num_chars; ++i) { @@ -2054,8 +2017,8 @@ std::string WideStringToUtf8(const wchar_t* str, int num_chars) { if (str[i] == L'\0') { break; } else if (i + 1 < num_chars && IsUtf16SurrogatePair(str[i], str[i + 1])) { - unicode_code_point = CreateCodePointFromUtf16SurrogatePair(str[i], - str[i + 1]); + unicode_code_point = + CreateCodePointFromUtf16SurrogatePair(str[i], str[i + 1]); i++; } else { unicode_code_point = static_cast<uint32_t>(str[i]); @@ -2068,7 +2031,7 @@ std::string WideStringToUtf8(const wchar_t* str, int num_chars) { // Converts a wide C string to an std::string using the UTF-8 encoding. // NULL will be converted to "(null)". -std::string String::ShowWideCString(const wchar_t * wide_c_str) { +std::string String::ShowWideCString(const wchar_t* wide_c_str) { if (wide_c_str == nullptr) return "(null)"; return internal::WideStringToUtf8(wide_c_str, -1); @@ -2080,7 +2043,7 @@ std::string String::ShowWideCString(const wchar_t * wide_c_str) { // Unlike wcscmp(), this function can handle NULL argument(s). A NULL // C string is considered different to any non-NULL C string, // including the empty string. -bool String::WideCStringEquals(const wchar_t * lhs, const wchar_t * rhs) { +bool String::WideCStringEquals(const wchar_t* lhs, const wchar_t* rhs) { if (lhs == nullptr) return rhs == nullptr; if (rhs == nullptr) return false; @@ -2090,33 +2053,27 @@ bool String::WideCStringEquals(const wchar_t * lhs, const wchar_t * rhs) { // Helper function for *_STREQ on wide strings. AssertionResult CmpHelperSTREQ(const char* lhs_expression, - const char* rhs_expression, - const wchar_t* lhs, + const char* rhs_expression, const wchar_t* lhs, const wchar_t* rhs) { if (String::WideCStringEquals(lhs, rhs)) { return AssertionSuccess(); } - return EqFailure(lhs_expression, - rhs_expression, - PrintToString(lhs), - PrintToString(rhs), - false); + return EqFailure(lhs_expression, rhs_expression, PrintToString(lhs), + PrintToString(rhs), false); } // Helper function for *_STRNE on wide strings. AssertionResult CmpHelperSTRNE(const char* s1_expression, - const char* s2_expression, - const wchar_t* s1, + const char* s2_expression, const wchar_t* s1, const wchar_t* s2) { if (!String::WideCStringEquals(s1, s2)) { return AssertionSuccess(); } - return AssertionFailure() << "Expected: (" << s1_expression << ") != (" - << s2_expression << "), actual: " - << PrintToString(s1) - << " vs " << PrintToString(s2); + return AssertionFailure() + << "Expected: (" << s1_expression << ") != (" << s2_expression + << "), actual: " << PrintToString(s1) << " vs " << PrintToString(s2); } // Compares two C strings, ignoring case. Returns true if and only if they have @@ -2125,7 +2082,7 @@ AssertionResult CmpHelperSTRNE(const char* s1_expression, // Unlike strcasecmp(), this function can handle NULL argument(s). A // NULL C string is considered different to any non-NULL C string, // including the empty string. -bool String::CaseInsensitiveCStringEquals(const char * lhs, const char * rhs) { +bool String::CaseInsensitiveCStringEquals(const char* lhs, const char* rhs) { if (lhs == nullptr) return rhs == nullptr; if (rhs == nullptr) return false; return posix::StrCaseCmp(lhs, rhs) == 0; @@ -2167,8 +2124,8 @@ bool String::CaseInsensitiveWideCStringEquals(const wchar_t* lhs, // Returns true if and only if str ends with the given suffix, ignoring case. // Any string is considered to end with an empty suffix. -bool String::EndsWithCaseInsensitive( - const std::string& str, const std::string& suffix) { +bool String::EndsWithCaseInsensitive(const std::string& str, + const std::string& suffix) { const size_t str_len = str.length(); const size_t suffix_len = suffix.length(); return (str_len >= suffix_len) && @@ -2251,15 +2208,13 @@ TestResult::TestResult() : death_test_count_(0), start_timestamp_(0), elapsed_time_(0) {} // D'tor. -TestResult::~TestResult() { -} +TestResult::~TestResult() {} // Returns the i-th test part result among all the results. i can // range from 0 to total_part_count() - 1. If i is not in that range, // aborts the program. const TestPartResult& TestResult::GetTestPartResult(int i) const { - if (i < 0 || i >= total_part_count()) - internal::posix::Abort(); + if (i < 0 || i >= total_part_count()) internal::posix::Abort(); return test_part_results_.at(static_cast<size_t>(i)); } @@ -2267,15 +2222,12 @@ const TestPartResult& TestResult::GetTestPartResult(int i) const { // test_property_count() - 1. If i is not in that range, aborts the // program. const TestProperty& TestResult::GetTestProperty(int i) const { - if (i < 0 || i >= test_property_count()) - internal::posix::Abort(); + if (i < 0 || i >= test_property_count()) internal::posix::Abort(); return test_properties_.at(static_cast<size_t>(i)); } // Clears the test part results. -void TestResult::ClearTestPartResults() { - test_part_results_.clear(); -} +void TestResult::ClearTestPartResults() { test_part_results_.clear(); } // Adds a test part result to the list. void TestResult::AddTestPartResult(const TestPartResult& test_part_result) { @@ -2304,15 +2256,8 @@ void TestResult::RecordProperty(const std::string& xml_element, // The list of reserved attributes used in the <testsuites> element of XML // output. static const char* const kReservedTestSuitesAttributes[] = { - "disabled", - "errors", - "failures", - "name", - "random_seed", - "tests", - "time", - "timestamp" -}; + "disabled", "errors", "failures", "name", + "random_seed", "tests", "time", "timestamp"}; // The list of reserved attributes used in the <testsuite> element of XML // output. @@ -2322,8 +2267,8 @@ static const char* const kReservedTestSuiteAttributes[] = { // The list of reserved attributes used in the <testcase> element of XML output. static const char* const kReservedTestCaseAttributes[] = { - "classname", "name", "status", "time", "type_param", - "value_param", "file", "line"}; + "classname", "name", "status", "time", + "type_param", "value_param", "file", "line"}; // Use a slightly different set for allowed output to ensure existing tests can // still RecordProperty("result") or "RecordProperty(timestamp") @@ -2385,7 +2330,7 @@ static bool ValidateTestPropertyName( const std::string& property_name, const std::vector<std::string>& reserved_names) { if (std::find(reserved_names.begin(), reserved_names.end(), property_name) != - reserved_names.end()) { + reserved_names.end()) { ADD_FAILURE() << "Reserved key used in RecordProperty(): " << property_name << " (" << FormatWordList(reserved_names) << " are reserved by " << GTEST_NAME_ << ")"; @@ -2423,8 +2368,7 @@ bool TestResult::Skipped() const { // Returns true if and only if the test failed. bool TestResult::Failed() const { for (int i = 0; i < total_part_count(); ++i) { - if (GetTestPartResult(i).failed()) - return true; + if (GetTestPartResult(i).failed()) return true; } return false; } @@ -2465,27 +2409,22 @@ int TestResult::test_property_count() const { // Creates a Test object. // The c'tor saves the states of all flags. -Test::Test() - : gtest_flag_saver_(new GTEST_FLAG_SAVER_) { -} +Test::Test() : gtest_flag_saver_(new GTEST_FLAG_SAVER_) {} // The d'tor restores the states of all flags. The actual work is // done by the d'tor of the gtest_flag_saver_ field, and thus not // visible here. -Test::~Test() { -} +Test::~Test() {} // Sets up the test fixture. // // A sub-class may override this. -void Test::SetUp() { -} +void Test::SetUp() {} // Tears down the test fixture. // // A sub-class may override this. -void Test::TearDown() { -} +void Test::TearDown() {} // Allows user supplied key value pairs to be recorded for later output. void Test::RecordProperty(const std::string& key, const std::string& value) { @@ -2590,8 +2529,8 @@ bool Test::HasSameFixtureClass() { static std::string* FormatSehExceptionMessage(DWORD exception_code, const char* location) { Message message; - message << "SEH exception with code 0x" << std::setbase(16) << - exception_code << std::setbase(10) << " thrown in " << location << "."; + message << "SEH exception with code 0x" << std::setbase(16) << exception_code + << std::setbase(10) << " thrown in " << location << "."; return new std::string(message.GetString()); } @@ -2634,8 +2573,8 @@ GoogleTestFailureException::GoogleTestFailureException( // exceptions in the same function. Therefore, we provide a separate // wrapper function for handling SEH exceptions.) template <class T, typename Result> -Result HandleSehExceptionsInMethodIfSupported( - T* object, Result (T::*method)(), const char* location) { +Result HandleSehExceptionsInMethodIfSupported(T* object, Result (T::*method)(), + const char* location) { #if GTEST_HAS_SEH __try { return (object->*method)(); @@ -2644,8 +2583,8 @@ Result HandleSehExceptionsInMethodIfSupported( // We create the exception message on the heap because VC++ prohibits // creation of objects with destructors on stack in functions using __try // (see error C2712). - std::string* exception_message = FormatSehExceptionMessage( - GetExceptionCode(), location); + std::string* exception_message = + FormatSehExceptionMessage(GetExceptionCode(), location); internal::ReportFailureInUnknownLocation(TestPartResult::kFatalFailure, *exception_message); delete exception_message; @@ -2661,8 +2600,8 @@ Result HandleSehExceptionsInMethodIfSupported( // exceptions, if they are supported; returns the 0-value for type // Result in case of an SEH exception. template <class T, typename Result> -Result HandleExceptionsInMethodIfSupported( - T* object, Result (T::*method)(), const char* location) { +Result HandleExceptionsInMethodIfSupported(T* object, Result (T::*method)(), + const char* location) { // NOTE: The user code can affect the way in which Google Test handles // exceptions by setting GTEST_FLAG(catch_exceptions), but only before // RUN_ALL_TESTS() starts. It is technically possible to check the flag @@ -2728,16 +2667,16 @@ void Test::Run() { // GTEST_SKIP(). if (!HasFatalFailure() && !IsSkipped()) { impl->os_stack_trace_getter()->UponLeavingGTest(); - internal::HandleExceptionsInMethodIfSupported( - this, &Test::TestBody, "the test body"); + internal::HandleExceptionsInMethodIfSupported(this, &Test::TestBody, + "the test body"); } // However, we want to clean up as much as possible. Hence we will // always call TearDown(), even if SetUp() or the test body has // failed. impl->os_stack_trace_getter()->UponLeavingGTest(); - internal::HandleExceptionsInMethodIfSupported( - this, &Test::TearDown, "TearDown()"); + internal::HandleExceptionsInMethodIfSupported(this, &Test::TearDown, + "TearDown()"); } // Returns true if and only if the current test has a fatal failure. @@ -2747,8 +2686,9 @@ bool Test::HasFatalFailure() { // Returns true if and only if the current test has a non-fatal failure. bool Test::HasNonfatalFailure() { - return internal::GetUnitTestImpl()->current_test_result()-> - HasNonfatalFailure(); + return internal::GetUnitTestImpl() + ->current_test_result() + ->HasNonfatalFailure(); } // Returns true if and only if the current test was skipped. @@ -2848,11 +2788,10 @@ class TestNameIs { // Constructor. // // TestNameIs has NO default constructor. - explicit TestNameIs(const char* name) - : name_(name) {} + explicit TestNameIs(const char* name) : name_(name) {} // Returns true if and only if the test name of test_info matches name_. - bool operator()(const TestInfo * test_info) const { + bool operator()(const TestInfo* test_info) const { return test_info && test_info->name() == name_; } @@ -3145,11 +3084,10 @@ void TestSuite::UnshuffleTests() { // // FormatCountableNoun(1, "formula", "formuli") returns "1 formula". // FormatCountableNoun(5, "book", "books") returns "5 books". -static std::string FormatCountableNoun(int count, - const char * singular_form, - const char * plural_form) { +static std::string FormatCountableNoun(int count, const char* singular_form, + const char* plural_form) { return internal::StreamableToString(count) + " " + - (count == 1 ? singular_form : plural_form); + (count == 1 ? singular_form : plural_form); } // Formats the count of tests. @@ -3166,7 +3104,7 @@ static std::string FormatTestSuiteCount(int test_suite_count) { // representation. Both kNonFatalFailure and kFatalFailure are translated // to "Failure", as the user usually doesn't care about the difference // between the two when viewing the test result. -static const char * TestPartResultTypeToString(TestPartResult::Type type) { +static const char* TestPartResultTypeToString(TestPartResult::Type type) { switch (type) { case TestPartResult::kSkip: return "Skipped\n"; @@ -3193,17 +3131,18 @@ enum class GTestColor { kDefault, kRed, kGreen, kYellow }; // Prints a TestPartResult to an std::string. static std::string PrintTestPartResultToString( const TestPartResult& test_part_result) { - return (Message() - << internal::FormatFileLocation(test_part_result.file_name(), - test_part_result.line_number()) - << " " << TestPartResultTypeToString(test_part_result.type()) - << test_part_result.message()).GetString(); + return (Message() << internal::FormatFileLocation( + test_part_result.file_name(), + test_part_result.line_number()) + << " " + << TestPartResultTypeToString(test_part_result.type()) + << test_part_result.message()) + .GetString(); } // Prints a TestPartResult. static void PrintTestPartResult(const TestPartResult& test_part_result) { - const std::string& result = - PrintTestPartResultToString(test_part_result); + const std::string& result = PrintTestPartResultToString(test_part_result); printf("%s\n", result.c_str()); fflush(stdout); // If the test program runs in Visual Studio or a debugger, the @@ -3220,8 +3159,8 @@ static void PrintTestPartResult(const TestPartResult& test_part_result) { } // class PrettyUnitTestResultPrinter -#if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE && \ - !GTEST_OS_WINDOWS_PHONE && !GTEST_OS_WINDOWS_RT && !GTEST_OS_WINDOWS_MINGW +#if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE && !GTEST_OS_WINDOWS_PHONE && \ + !GTEST_OS_WINDOWS_RT && !GTEST_OS_WINDOWS_MINGW // Returns the character attribute for the given color. static WORD GetColorAttribute(GTestColor color) { @@ -3232,7 +3171,8 @@ static WORD GetColorAttribute(GTestColor color) { return FOREGROUND_GREEN; case GTestColor::kYellow: return FOREGROUND_RED | FOREGROUND_GREEN; - default: return 0; + default: + return 0; } } @@ -3316,9 +3256,9 @@ bool ShouldUseColor(bool stdout_is_tty) { } return String::CaseInsensitiveCStringEquals(gtest_color, "yes") || - String::CaseInsensitiveCStringEquals(gtest_color, "true") || - String::CaseInsensitiveCStringEquals(gtest_color, "t") || - String::CStringEquals(gtest_color, "1"); + String::CaseInsensitiveCStringEquals(gtest_color, "true") || + String::CaseInsensitiveCStringEquals(gtest_color, "t") || + String::CStringEquals(gtest_color, "1"); // We take "yes", "true", "t", and "1" as meaning "yes". If the // value is neither one of these nor "auto", we treat it as "no" to // be conservative. @@ -3330,7 +3270,7 @@ bool ShouldUseColor(bool stdout_is_tty) { // that would be colored when printed, as can be done on Linux. GTEST_ATTRIBUTE_PRINTF_(2, 3) -static void ColoredPrintf(GTestColor color, const char *fmt, ...) { +static void ColoredPrintf(GTestColor color, const char* fmt, ...) { va_list args; va_start(args, fmt); @@ -3349,8 +3289,8 @@ static void ColoredPrintf(GTestColor color, const char *fmt, ...) { return; } -#if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE && \ - !GTEST_OS_WINDOWS_PHONE && !GTEST_OS_WINDOWS_RT && !GTEST_OS_WINDOWS_MINGW +#if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE && !GTEST_OS_WINDOWS_PHONE && \ + !GTEST_OS_WINDOWS_RT && !GTEST_OS_WINDOWS_MINGW const HANDLE stdout_handle = GetStdHandle(STD_OUTPUT_HANDLE); // Gets the current text color. @@ -3442,7 +3382,7 @@ class PrettyUnitTestResultPrinter : public TestEventListener { static void PrintSkippedTests(const UnitTest& unit_test); }; - // Fired before each iteration of tests starts. +// Fired before each iteration of tests starts. void PrettyUnitTestResultPrinter::OnTestIterationStart( const UnitTest& unit_test, int iteration) { if (GTEST_FLAG_GET(repeat) != 1) @@ -3552,12 +3492,12 @@ void PrettyUnitTestResultPrinter::OnTestEnd(const TestInfo& test_info) { ColoredPrintf(GTestColor::kRed, "[ FAILED ] "); } PrintTestName(test_info.test_suite_name(), test_info.name()); - if (test_info.result()->Failed()) - PrintFullTestCommentIfPresent(test_info); + if (test_info.result()->Failed()) PrintFullTestCommentIfPresent(test_info); if (GTEST_FLAG_GET(print_time)) { - printf(" (%s ms)\n", internal::StreamableToString( - test_info.result()->elapsed_time()).c_str()); + printf(" (%s ms)\n", + internal::StreamableToString(test_info.result()->elapsed_time()) + .c_str()); } else { printf("\n"); } @@ -3819,7 +3759,7 @@ class TestEventRepeater : public TestEventListener { public: TestEventRepeater() : forwarding_enabled_(true) {} ~TestEventRepeater() override; - void Append(TestEventListener *listener); + void Append(TestEventListener* listener); TestEventListener* Release(TestEventListener* listener); // Controls whether events will be forwarded to listeners_. Set to false @@ -3864,11 +3804,11 @@ TestEventRepeater::~TestEventRepeater() { ForEach(listeners_, Delete<TestEventListener>); } -void TestEventRepeater::Append(TestEventListener *listener) { +void TestEventRepeater::Append(TestEventListener* listener) { listeners_.push_back(listener); } -TestEventListener* TestEventRepeater::Release(TestEventListener *listener) { +TestEventListener* TestEventRepeater::Release(TestEventListener* listener) { for (size_t i = 0; i < listeners_.size(); ++i) { if (listeners_[i] == listener) { listeners_.erase(listeners_.begin() + static_cast<int>(i)); @@ -3881,14 +3821,14 @@ TestEventListener* TestEventRepeater::Release(TestEventListener *listener) { // Since most methods are very similar, use macros to reduce boilerplate. // This defines a member that forwards the call to all listeners. -#define GTEST_REPEATER_METHOD_(Name, Type) \ -void TestEventRepeater::Name(const Type& parameter) { \ - if (forwarding_enabled_) { \ - for (size_t i = 0; i < listeners_.size(); i++) { \ - listeners_[i]->Name(parameter); \ - } \ - } \ -} +#define GTEST_REPEATER_METHOD_(Name, Type) \ + void TestEventRepeater::Name(const Type& parameter) { \ + if (forwarding_enabled_) { \ + for (size_t i = 0; i < listeners_.size(); i++) { \ + listeners_[i]->Name(parameter); \ + } \ + } \ + } // This defines a member that forwards the call to all listeners in reverse // order. #define GTEST_REVERSE_REPEATER_METHOD_(Name, Type) \ @@ -4075,8 +4015,8 @@ 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. -std::string XmlUnitTestResultPrinter::EscapeXml( - const std::string& str, bool is_attribute) { +std::string XmlUnitTestResultPrinter::EscapeXml(const std::string& str, + bool is_attribute) { Message m; for (size_t i = 0; i < str.size(); ++i) { @@ -4183,12 +4123,12 @@ std::string FormatEpochTimeInMillisAsIso8601(TimeInMillis ms) { return ""; // YYYY-MM-DDThh:mm:ss.sss return StreamableToString(time_struct.tm_year + 1900) + "-" + - String::FormatIntWidth2(time_struct.tm_mon + 1) + "-" + - String::FormatIntWidth2(time_struct.tm_mday) + "T" + - String::FormatIntWidth2(time_struct.tm_hour) + ":" + - String::FormatIntWidth2(time_struct.tm_min) + ":" + - String::FormatIntWidth2(time_struct.tm_sec) + "." + - String::FormatIntWidthN(static_cast<int>(ms % 1000), 3); + String::FormatIntWidth2(time_struct.tm_mon + 1) + "-" + + String::FormatIntWidth2(time_struct.tm_mday) + "T" + + String::FormatIntWidth2(time_struct.tm_hour) + ":" + + String::FormatIntWidth2(time_struct.tm_min) + ":" + + String::FormatIntWidth2(time_struct.tm_sec) + "." + + String::FormatIntWidthN(static_cast<int>(ms % 1000), 3); } // Streams an XML CDATA section, escaping invalid CDATA sequences as needed. @@ -4199,8 +4139,8 @@ void XmlUnitTestResultPrinter::OutputXmlCDataSection(::std::ostream* stream, for (;;) { const char* const next_segment = strstr(segment, "]]>"); if (next_segment != nullptr) { - stream->write( - segment, static_cast<std::streamsize>(next_segment - segment)); + stream->write(segment, + static_cast<std::streamsize>(next_segment - segment)); *stream << "]]>]]><![CDATA["; segment = next_segment + strlen("]]>"); } else { @@ -4212,15 +4152,13 @@ void XmlUnitTestResultPrinter::OutputXmlCDataSection(::std::ostream* stream, } void XmlUnitTestResultPrinter::OutputXmlAttribute( - std::ostream* stream, - const std::string& element_name, - const std::string& name, - const std::string& value) { + std::ostream* stream, const std::string& element_name, + const std::string& name, const std::string& value) { const std::vector<std::string>& allowed_names = GetReservedOutputAttributesForElement(element_name); GTEST_CHECK_(std::find(allowed_names.begin(), allowed_names.end(), name) != - allowed_names.end()) + allowed_names.end()) << "Attribute " << name << " is not allowed for element <" << element_name << ">."; @@ -4286,10 +4224,11 @@ void XmlUnitTestResultPrinter::OutputXmlTestInfo(::std::ostream* stream, OutputXmlAttribute(stream, kTestsuite, "type_param", test_info.type_param()); } + + OutputXmlAttribute(stream, kTestsuite, "file", test_info.file()); + OutputXmlAttribute(stream, kTestsuite, "line", + StreamableToString(test_info.line())); if (GTEST_FLAG_GET(list_tests)) { - OutputXmlAttribute(stream, kTestsuite, "file", test_info.file()); - OutputXmlAttribute(stream, kTestsuite, "line", - StreamableToString(test_info.line())); *stream << " />\n"; return; } @@ -4324,8 +4263,7 @@ void XmlUnitTestResultPrinter::OutputXmlTestResult(::std::ostream* stream, internal::FormatCompilerIndependentFileLocation(part.file_name(), part.line_number()); const std::string summary = location + "\n" + part.summary(); - *stream << " <failure message=\"" - << EscapeXmlAttribute(summary) + *stream << " <failure message=\"" << EscapeXmlAttribute(summary) << "\" type=\"\">"; const std::string detail = location + "\n" + part.message(); OutputXmlCDataSection(stream, RemoveInvalidXmlCharacters(detail).c_str()); @@ -4466,7 +4404,7 @@ std::string XmlUnitTestResultPrinter::TestPropertiesAsXmlAttributes( for (int i = 0; i < result.test_property_count(); ++i) { const TestProperty& property = result.GetTestProperty(i); attributes << " " << property.key() << "=" - << "\"" << EscapeXmlAttribute(property.value()) << "\""; + << "\"" << EscapeXmlAttribute(property.value()) << "\""; } return attributes.GetString(); } @@ -4512,16 +4450,12 @@ class JsonUnitTestResultPrinter : public EmptyTestEventListener { //// streams the attribute as JSON. static void OutputJsonKey(std::ostream* stream, const std::string& element_name, - const std::string& name, - const std::string& value, - const std::string& indent, - bool comma = true); + const std::string& name, const std::string& value, + const std::string& indent, bool comma = true); static void OutputJsonKey(std::ostream* stream, const std::string& element_name, - const std::string& name, - int value, - const std::string& indent, - bool comma = true); + const std::string& name, int value, + const std::string& indent, bool comma = true); // Streams a test suite JSON stanza containing the given test result. // @@ -4566,7 +4500,7 @@ JsonUnitTestResultPrinter::JsonUnitTestResultPrinter(const char* output_file) } void JsonUnitTestResultPrinter::OnTestIterationEnd(const UnitTest& unit_test, - int /*iteration*/) { + int /*iteration*/) { FILE* jsonout = OpenFileForWriting(output_file_); std::stringstream stream; PrintJsonUnitTest(&stream, unit_test); @@ -4632,55 +4566,48 @@ static std::string FormatEpochTimeInMillisAsRFC3339(TimeInMillis ms) { return ""; // YYYY-MM-DDThh:mm:ss return StreamableToString(time_struct.tm_year + 1900) + "-" + - String::FormatIntWidth2(time_struct.tm_mon + 1) + "-" + - String::FormatIntWidth2(time_struct.tm_mday) + "T" + - String::FormatIntWidth2(time_struct.tm_hour) + ":" + - String::FormatIntWidth2(time_struct.tm_min) + ":" + - String::FormatIntWidth2(time_struct.tm_sec) + "Z"; + String::FormatIntWidth2(time_struct.tm_mon + 1) + "-" + + String::FormatIntWidth2(time_struct.tm_mday) + "T" + + String::FormatIntWidth2(time_struct.tm_hour) + ":" + + String::FormatIntWidth2(time_struct.tm_min) + ":" + + String::FormatIntWidth2(time_struct.tm_sec) + "Z"; } static inline std::string Indent(size_t width) { return std::string(width, ' '); } -void JsonUnitTestResultPrinter::OutputJsonKey( - std::ostream* stream, - const std::string& element_name, - const std::string& name, - const std::string& value, - const std::string& indent, - bool comma) { +void JsonUnitTestResultPrinter::OutputJsonKey(std::ostream* stream, + const std::string& element_name, + const std::string& name, + const std::string& value, + const std::string& indent, + bool comma) { const std::vector<std::string>& allowed_names = GetReservedOutputAttributesForElement(element_name); GTEST_CHECK_(std::find(allowed_names.begin(), allowed_names.end(), name) != - allowed_names.end()) + allowed_names.end()) << "Key \"" << name << "\" is not allowed for value \"" << element_name << "\"."; *stream << indent << "\"" << name << "\": \"" << EscapeJson(value) << "\""; - if (comma) - *stream << ",\n"; + if (comma) *stream << ",\n"; } void JsonUnitTestResultPrinter::OutputJsonKey( - std::ostream* stream, - const std::string& element_name, - const std::string& name, - int value, - const std::string& indent, - bool comma) { + std::ostream* stream, const std::string& element_name, + const std::string& name, int value, const std::string& indent, bool comma) { const std::vector<std::string>& allowed_names = GetReservedOutputAttributesForElement(element_name); GTEST_CHECK_(std::find(allowed_names.begin(), allowed_names.end(), name) != - allowed_names.end()) + allowed_names.end()) << "Key \"" << name << "\" is not allowed for value \"" << element_name << "\"."; *stream << indent << "\"" << name << "\": " << StreamableToString(value); - if (comma) - *stream << ",\n"; + if (comma) *stream << ",\n"; } // Streams a test suite JSON stanza containing the given test result. @@ -4744,11 +4671,14 @@ void JsonUnitTestResultPrinter::OutputJsonTestInfo(::std::ostream* stream, OutputJsonKey(stream, kTestsuite, "type_param", test_info.type_param(), kIndent); } + + OutputJsonKey(stream, kTestsuite, "file", test_info.file(), kIndent); + OutputJsonKey(stream, kTestsuite, "line", test_info.line(), kIndent, false); if (GTEST_FLAG_GET(list_tests)) { - OutputJsonKey(stream, kTestsuite, "file", test_info.file(), kIndent); - OutputJsonKey(stream, kTestsuite, "line", test_info.line(), kIndent, false); *stream << "\n" << Indent(8) << "}"; return; + } else { + *stream << ",\n"; } OutputJsonKey(stream, kTestsuite, "status", @@ -4780,7 +4710,9 @@ void JsonUnitTestResultPrinter::OutputJsonTestResult(::std::ostream* stream, if (part.failed()) { *stream << ",\n"; if (++failures == 1) { - *stream << kIndent << "\"" << "failures" << "\": [\n"; + *stream << kIndent << "\"" + << "failures" + << "\": [\n"; } const std::string location = internal::FormatCompilerIndependentFileLocation(part.file_name(), @@ -4793,8 +4725,7 @@ void JsonUnitTestResultPrinter::OutputJsonTestResult(::std::ostream* stream, } } - if (failures > 0) - *stream << "\n" << kIndent << "]"; + if (failures > 0) *stream << "\n" << kIndent << "]"; *stream << "\n" << Indent(8) << "}"; } @@ -4890,7 +4821,9 @@ void JsonUnitTestResultPrinter::PrintJsonUnitTest(std::ostream* stream, OutputJsonTestSuiteForTestResult(stream, unit_test.ad_hoc_test_result()); } - *stream << "\n" << kIndent << "]\n" << "}\n"; + *stream << "\n" + << kIndent << "]\n" + << "}\n"; } void JsonUnitTestResultPrinter::PrintJsonTestList( @@ -4925,7 +4858,8 @@ std::string JsonUnitTestResultPrinter::TestPropertiesAsJson( Message attributes; for (int i = 0; i < result.test_property_count(); ++i) { const TestProperty& property = result.GetTestProperty(i); - attributes << ",\n" << indent << "\"" << property.key() << "\": " + attributes << ",\n" + << indent << "\"" << property.key() << "\": " << "\"" << EscapeJson(property.value()) << "\""; } return attributes.GetString(); @@ -4965,14 +4899,14 @@ void StreamingListener::SocketWriter::MakeConnection() { addrinfo hints; memset(&hints, 0, sizeof(hints)); - hints.ai_family = AF_UNSPEC; // To allow both IPv4 and IPv6 addresses. + hints.ai_family = AF_UNSPEC; // To allow both IPv4 and IPv6 addresses. hints.ai_socktype = SOCK_STREAM; addrinfo* servinfo = nullptr; // Use the getaddrinfo() to get a linked list of IP addresses for // the given host name. - const int error_num = getaddrinfo( - host_name_.c_str(), port_num_.c_str(), &hints, &servinfo); + const int error_num = + getaddrinfo(host_name_.c_str(), port_num_.c_str(), &hints, &servinfo); if (error_num != 0) { GTEST_LOG_(WARNING) << "stream_result_to: getaddrinfo() failed: " << gai_strerror(error_num); @@ -4981,8 +4915,8 @@ void StreamingListener::SocketWriter::MakeConnection() { // Loop through all the results and connect to the first we can. for (addrinfo* cur_addr = servinfo; sockfd_ == -1 && cur_addr != nullptr; cur_addr = cur_addr->ai_next) { - sockfd_ = socket( - cur_addr->ai_family, cur_addr->ai_socktype, cur_addr->ai_protocol); + sockfd_ = socket(cur_addr->ai_family, cur_addr->ai_socktype, + cur_addr->ai_protocol); if (sockfd_ != -1) { // Connect the client socket to the server socket. if (connect(sockfd_, cur_addr->ai_addr, cur_addr->ai_addrlen) == -1) { @@ -5051,7 +4985,7 @@ std::string OsStackTraceGetter::CurrentStackTrace(int max_depth, int skip_count) return result; -#else // !GTEST_HAS_ABSL +#else // !GTEST_HAS_ABSL static_cast<void>(max_depth); static_cast<void>(skip_count); return ""; @@ -5075,8 +5009,8 @@ void OsStackTraceGetter::UponLeavingGTest() GTEST_LOCK_EXCLUDED_(mutex_) { class ScopedPrematureExitFile { public: explicit ScopedPrematureExitFile(const char* premature_exit_filepath) - : premature_exit_filepath_(premature_exit_filepath ? - premature_exit_filepath : "") { + : premature_exit_filepath_( + premature_exit_filepath ? premature_exit_filepath : "") { // If a path to the premature-exit file is specified... if (!premature_exit_filepath_.empty()) { // create the file with a single "0" character in it. I/O @@ -5278,7 +5212,7 @@ int UnitTest::test_to_run_count() const { return impl()->test_to_run_count(); } // Gets the time of the test program start, in ms from the start of the // UNIX epoch. internal::TimeInMillis UnitTest::start_timestamp() const { - return impl()->start_timestamp(); + return impl()->start_timestamp(); } // Gets the elapsed time, in milliseconds. @@ -5321,9 +5255,7 @@ TestSuite* UnitTest::GetMutableTestSuite(int i) { // Returns the list of event listeners that can be used to track events // inside Google Test. -TestEventListeners& UnitTest::listeners() { - return *impl()->listeners(); -} +TestEventListeners& UnitTest::listeners() { return *impl()->listeners(); } // Registers and returns a global test environment. When a test // program is run, all global test environments will be set-up in the @@ -5348,12 +5280,11 @@ Environment* UnitTest::AddEnvironment(Environment* env) { // assertion macros (e.g. ASSERT_TRUE, EXPECT_EQ, etc) eventually call // this to report their results. The user code should use the // assertion macros instead of calling this directly. -void UnitTest::AddTestPartResult( - TestPartResult::Type result_type, - const char* file_name, - int line_number, - const std::string& message, - const std::string& os_stack_trace) GTEST_LOCK_EXCLUDED_(mutex_) { +void UnitTest::AddTestPartResult(TestPartResult::Type result_type, + const char* file_name, int line_number, + const std::string& message, + const std::string& os_stack_trace) + GTEST_LOCK_EXCLUDED_(mutex_) { Message msg; msg << message; @@ -5363,8 +5294,9 @@ void UnitTest::AddTestPartResult( for (size_t i = impl_->gtest_trace_stack().size(); i > 0; --i) { const internal::TraceInfo& trace = impl_->gtest_trace_stack()[i - 1]; - msg << "\n" << internal::FormatFileLocation(trace.file, trace.line) - << " " << trace.message; + msg << "\n" + << internal::FormatFileLocation(trace.file, trace.line) << " " + << trace.message; } } @@ -5374,8 +5306,8 @@ void UnitTest::AddTestPartResult( const TestPartResult result = TestPartResult( result_type, file_name, line_number, msg.GetString().c_str()); - impl_->GetTestPartResultReporterForCurrentThread()-> - ReportTestPartResult(result); + impl_->GetTestPartResultReporterForCurrentThread()->ReportTestPartResult( + result); if (result_type != TestPartResult::kSuccess && result_type != TestPartResult::kSkip) { @@ -5468,20 +5400,20 @@ int UnitTest::Run() { // process. In either case the user does not want to see pop-up dialogs // about crashes - they are expected. if (impl()->catch_exceptions() || in_death_test_child_process) { -# if !GTEST_OS_WINDOWS_MOBILE && !GTEST_OS_WINDOWS_PHONE && !GTEST_OS_WINDOWS_RT +#if !GTEST_OS_WINDOWS_MOBILE && !GTEST_OS_WINDOWS_PHONE && !GTEST_OS_WINDOWS_RT // SetErrorMode doesn't exist on CE. SetErrorMode(SEM_FAILCRITICALERRORS | SEM_NOALIGNMENTFAULTEXCEPT | SEM_NOGPFAULTERRORBOX | SEM_NOOPENFILEERRORBOX); -# endif // !GTEST_OS_WINDOWS_MOBILE +#endif // !GTEST_OS_WINDOWS_MOBILE -# if (defined(_MSC_VER) || GTEST_OS_WINDOWS_MINGW) && !GTEST_OS_WINDOWS_MOBILE +#if (defined(_MSC_VER) || GTEST_OS_WINDOWS_MINGW) && !GTEST_OS_WINDOWS_MOBILE // Death test children can be terminated with _abort(). On Windows, // _abort() can show a dialog with a warning message. This forces the // abort message to go to stderr instead. _set_error_mode(_OUT_TO_STDERR); -# endif +#endif -# if defined(_MSC_VER) && !GTEST_OS_WINDOWS_MOBILE +#if defined(_MSC_VER) && !GTEST_OS_WINDOWS_MOBILE // In the debug version, Visual Studio pops up a separate dialog // offering a choice to debug the aborted program. We need to suppress // this dialog or it will pop up for every EXPECT/ASSERT_DEATH statement @@ -5501,14 +5433,15 @@ int UnitTest::Run() { _CRTDBG_MODE_FILE | _CRTDBG_MODE_DEBUG); (void)_CrtSetReportFile(_CRT_ASSERT, _CRTDBG_FILE_STDERR); } -# endif +#endif } #endif // GTEST_OS_WINDOWS return internal::HandleExceptionsInMethodIfSupported( - impl(), - &internal::UnitTestImpl::RunAllTests, - "auxiliary test code (environments or event listeners)") ? 0 : 1; + impl(), &internal::UnitTestImpl::RunAllTests, + "auxiliary test code (environments or event listeners)") + ? 0 + : 1; } // Returns the working directory when the first TEST() or TEST_F() was @@ -5553,14 +5486,10 @@ UnitTest::parameterized_test_registry() GTEST_LOCK_EXCLUDED_(mutex_) { } // Creates an empty UnitTest. -UnitTest::UnitTest() { - impl_ = new internal::UnitTestImpl(this); -} +UnitTest::UnitTest() { impl_ = new internal::UnitTestImpl(this); } // Destructor of UnitTest. -UnitTest::~UnitTest() { - delete impl_; -} +UnitTest::~UnitTest() { delete impl_; } // Pushes a trace defined by SCOPED_TRACE() on to the per-thread // Google Test trace stack. @@ -5571,8 +5500,7 @@ void UnitTest::PushGTestTrace(const internal::TraceInfo& trace) } // Pops a trace from the per-thread Google Test trace stack. -void UnitTest::PopGTestTrace() - GTEST_LOCK_EXCLUDED_(mutex_) { +void UnitTest::PopGTestTrace() GTEST_LOCK_EXCLUDED_(mutex_) { internal::MutexLock lock(&mutex_); impl_->gtest_trace_stack().pop_back(); } @@ -5673,8 +5601,8 @@ void UnitTestImpl::ConfigureStreamingOutput() { if (!target.empty()) { const size_t pos = target.find(':'); if (pos != std::string::npos) { - listeners()->Append(new StreamingListener(target.substr(0, pos), - target.substr(pos+1))); + listeners()->Append( + new StreamingListener(target.substr(0, pos), target.substr(pos + 1))); } else { GTEST_LOG_(WARNING) << "unrecognized streaming target \"" << target << "\" ignored."; @@ -5819,8 +5747,7 @@ bool UnitTestImpl::RunAllTests() { const bool gtest_is_initialized_before_run_all_tests = GTestIsInitialized(); // Do not run any test if the --help flag was specified. - if (g_help_flag) - return true; + if (g_help_flag) return true; // Repeats the call to the post-flag parsing initialization in case the // user didn't call InitGoogleTest. @@ -5838,11 +5765,11 @@ bool UnitTestImpl::RunAllTests() { #if GTEST_HAS_DEATH_TEST in_subprocess_for_death_test = (internal_run_death_test_flag_.get() != nullptr); -# if defined(GTEST_EXTRA_DEATH_TEST_CHILD_SETUP_) +#if defined(GTEST_EXTRA_DEATH_TEST_CHILD_SETUP_) if (in_subprocess_for_death_test) { GTEST_EXTRA_DEATH_TEST_CHILD_SETUP_(); } -# endif // defined(GTEST_EXTRA_DEATH_TEST_CHILD_SETUP_) +#endif // defined(GTEST_EXTRA_DEATH_TEST_CHILD_SETUP_) #endif // GTEST_HAS_DEATH_TEST const bool should_shard = ShouldShard(kTestTotalShards, kTestShardIndex, @@ -5850,9 +5777,9 @@ bool UnitTestImpl::RunAllTests() { // Compares the full test names with the filter to decide which // tests to run. - const bool has_tests_to_run = FilterTests(should_shard - ? HONOR_SHARDING_PROTOCOL - : IGNORE_SHARDING_PROTOCOL) > 0; + const bool has_tests_to_run = + FilterTests(should_shard ? HONOR_SHARDING_PROTOCOL + : IGNORE_SHARDING_PROTOCOL) > 0; // Lists the tests and exits if the --gtest_list_tests flag was specified. if (GTEST_FLAG_GET(list_tests)) { @@ -6035,8 +5962,7 @@ void WriteToShardStatusFileIfNeeded() { // an error and exits. If in_subprocess_for_death_test, sharding is // disabled because it must only be applied to the original test // process. Otherwise, we could filter out death tests we intended to execute. -bool ShouldShard(const char* total_shards_env, - const char* shard_index_env, +bool ShouldShard(const char* total_shards_env, const char* shard_index_env, bool in_subprocess_for_death_test) { if (in_subprocess_for_death_test) { return false; @@ -6048,27 +5974,27 @@ bool ShouldShard(const char* total_shards_env, if (total_shards == -1 && shard_index == -1) { return false; } else if (total_shards == -1 && shard_index != -1) { - const Message msg = Message() - << "Invalid environment variables: you have " - << kTestShardIndex << " = " << shard_index - << ", but have left " << kTestTotalShards << " unset.\n"; + const Message msg = Message() << "Invalid environment variables: you have " + << kTestShardIndex << " = " << shard_index + << ", but have left " << kTestTotalShards + << " unset.\n"; ColoredPrintf(GTestColor::kRed, "%s", msg.GetString().c_str()); fflush(stdout); exit(EXIT_FAILURE); } else if (total_shards != -1 && shard_index == -1) { const Message msg = Message() - << "Invalid environment variables: you have " - << kTestTotalShards << " = " << total_shards - << ", but have left " << kTestShardIndex << " unset.\n"; + << "Invalid environment variables: you have " + << kTestTotalShards << " = " << total_shards + << ", but have left " << kTestShardIndex << " unset.\n"; ColoredPrintf(GTestColor::kRed, "%s", msg.GetString().c_str()); fflush(stdout); exit(EXIT_FAILURE); } else if (shard_index < 0 || shard_index >= total_shards) { - const Message msg = Message() - << "Invalid environment variables: we require 0 <= " - << kTestShardIndex << " < " << kTestTotalShards - << ", but you have " << kTestShardIndex << "=" << shard_index - << ", " << kTestTotalShards << "=" << total_shards << ".\n"; + const Message msg = + Message() << "Invalid environment variables: we require 0 <= " + << kTestShardIndex << " < " << kTestTotalShards + << ", but you have " << kTestShardIndex << "=" << shard_index + << ", " << kTestTotalShards << "=" << total_shards << ".\n"; ColoredPrintf(GTestColor::kRed, "%s", msg.GetString().c_str()); fflush(stdout); exit(EXIT_FAILURE); @@ -6110,10 +6036,12 @@ bool ShouldRunTestOnShard(int total_shards, int shard_index, int test_id) { // https://github.com/google/googletest/blob/master/googletest/docs/advanced.md // . Returns the number of tests that should run. int UnitTestImpl::FilterTests(ReactionToSharding shard_tests) { - const int32_t total_shards = shard_tests == HONOR_SHARDING_PROTOCOL ? - Int32FromEnvOrDie(kTestTotalShards, -1) : -1; - const int32_t shard_index = shard_tests == HONOR_SHARDING_PROTOCOL ? - Int32FromEnvOrDie(kTestShardIndex, -1) : -1; + const int32_t total_shards = shard_tests == HONOR_SHARDING_PROTOCOL + ? Int32FromEnvOrDie(kTestTotalShards, -1) + : -1; + const int32_t shard_index = shard_tests == HONOR_SHARDING_PROTOCOL + ? Int32FromEnvOrDie(kTestShardIndex, -1) + : -1; const PositiveAndNegativeUnitTestFilter gtest_flag_filter( GTEST_FLAG_GET(filter)); @@ -6323,7 +6251,7 @@ GetCurrentOsStackTraceExceptTop(UnitTest* /*unit_test*/, int skip_count) { // suppress unreachable code warnings. namespace { class ClassUniqueToAlwaysTrue {}; -} +} // namespace bool IsTrue(bool condition) { return condition; } @@ -6331,8 +6259,7 @@ bool AlwaysTrue() { #if GTEST_HAS_EXCEPTIONS // This condition is always false so AlwaysTrue() never actually throws, // but it makes the compiler think that it may throw. - if (IsTrue(false)) - throw ClassUniqueToAlwaysTrue(); + if (IsTrue(false)) throw ClassUniqueToAlwaysTrue(); #endif // GTEST_HAS_EXCEPTIONS return true; } @@ -6444,8 +6371,7 @@ static bool ParseFlag(const char* str, const char* flag_name, String* value) { // GTEST_INTERNAL_PREFIX_ followed by "internal_" are considered Google Test // internal flags and do not trigger the help message. static bool HasGoogleTestFlagPrefix(const char* str) { - return (SkipPrefix("--", &str) || - SkipPrefix("-", &str) || + return (SkipPrefix("--", &str) || SkipPrefix("-", &str) || SkipPrefix("/", &str)) && !SkipPrefix(GTEST_FLAG_PREFIX_ "internal_", &str) && (SkipPrefix(GTEST_FLAG_PREFIX_, &str) || @@ -6549,18 +6475,18 @@ static const char kColorEncodedHelpMessage[] = " Generate a JSON or XML report in the given directory or with the " "given\n" " file name. @YFILE_PATH@D defaults to @Gtest_detail.xml@D.\n" -# if GTEST_CAN_STREAM_RESULTS_ +#if GTEST_CAN_STREAM_RESULTS_ " @G--" GTEST_FLAG_PREFIX_ "stream_result_to=@YHOST@G:@YPORT@D\n" " Stream test results to the given server.\n" -# endif // GTEST_CAN_STREAM_RESULTS_ +#endif // GTEST_CAN_STREAM_RESULTS_ "\n" "Assertion Behavior:\n" -# if GTEST_HAS_DEATH_TEST && !GTEST_OS_WINDOWS +#if GTEST_HAS_DEATH_TEST && !GTEST_OS_WINDOWS " @G--" GTEST_FLAG_PREFIX_ "death_test_style=@Y(@Gfast@Y|@Gthreadsafe@Y)@D\n" " Set the default death test style.\n" -# endif // GTEST_HAS_DEATH_TEST && !GTEST_OS_WINDOWS +#endif // GTEST_HAS_DEATH_TEST && !GTEST_OS_WINDOWS " @G--" GTEST_FLAG_PREFIX_ "break_on_failure@D\n" " Turn assertion failures into debugger break-points.\n" @@ -6637,10 +6563,8 @@ static void LoadFlagsFromFile(const std::string& path) { std::vector<std::string> lines; SplitString(contents, '\n', &lines); for (size_t i = 0; i < lines.size(); ++i) { - if (lines[i].empty()) - continue; - if (!ParseGoogleTestFlag(lines[i].c_str())) - g_help_flag = true; + if (lines[i].empty()) continue; + if (!ParseGoogleTestFlag(lines[i].c_str())) g_help_flag = true; } } #endif // GTEST_USE_OWN_FLAGFILE_FLAG_ @@ -6758,7 +6682,7 @@ void InitGoogleTestImpl(int* argc, CharType** argv) { void InitGoogleTest(int* argc, char** argv) { #if defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_) GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_(argc, argv); -#else // defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_) +#else // defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_) internal::InitGoogleTestImpl(argc, argv); #endif // defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_) } @@ -6768,7 +6692,7 @@ void InitGoogleTest(int* argc, char** argv) { void InitGoogleTest(int* argc, wchar_t** argv) { #if defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_) GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_(argc, argv); -#else // defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_) +#else // defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_) internal::InitGoogleTestImpl(argc, argv); #endif // defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_) } @@ -6784,7 +6708,7 @@ void InitGoogleTest() { #if defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_) GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_(&argc, argv); -#else // defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_) +#else // defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_) internal::InitGoogleTestImpl(&argc, argv); #endif // defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_) } @@ -6836,8 +6760,7 @@ void ScopedTrace::PushTrace(const char* file, int line, std::string message) { } // Pops the info pushed by the c'tor. -ScopedTrace::~ScopedTrace() - GTEST_LOCK_EXCLUDED_(&UnitTest::mutex_) { +ScopedTrace::~ScopedTrace() GTEST_LOCK_EXCLUDED_(&UnitTest::mutex_) { UnitTest::GetInstance()->PopGTestTrace(); } diff --git a/googletest/src/gtest_main.cc b/googletest/src/gtest_main.cc index 46b27c3..4497637 100644 --- a/googletest/src/gtest_main.cc +++ b/googletest/src/gtest_main.cc @@ -28,15 +28,14 @@ // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include <cstdio> + #include "gtest/gtest.h" #if GTEST_OS_ESP8266 || GTEST_OS_ESP32 #if GTEST_OS_ESP8266 extern "C" { #endif -void setup() { - testing::InitGoogleTest(); -} +void setup() { testing::InitGoogleTest(); } void loop() { RUN_ALL_TESTS(); } diff --git a/googletest/test/googletest-break-on-failure-unittest_.cc b/googletest/test/googletest-break-on-failure-unittest_.cc index f84957a..324294f 100644 --- a/googletest/test/googletest-break-on-failure-unittest_.cc +++ b/googletest/test/googletest-break-on-failure-unittest_.cc @@ -27,7 +27,6 @@ // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - // Unit test for Google Test's break-on-failure mode. // // A user can ask Google Test to seg-fault when an assertion fails, using @@ -41,34 +40,32 @@ #include "gtest/gtest.h" #if GTEST_OS_WINDOWS -# include <windows.h> -# include <stdlib.h> +#include <stdlib.h> +#include <windows.h> #endif namespace { // A test that's expected to fail. -TEST(Foo, Bar) { - EXPECT_EQ(2, 3); -} +TEST(Foo, Bar) { EXPECT_EQ(2, 3); } #if GTEST_HAS_SEH && !GTEST_OS_WINDOWS_MOBILE // On Windows Mobile global exception handlers are not supported. -LONG WINAPI ExitWithExceptionCode( - struct _EXCEPTION_POINTERS* exception_pointers) { +LONG WINAPI +ExitWithExceptionCode(struct _EXCEPTION_POINTERS* exception_pointers) { exit(exception_pointers->ExceptionRecord->ExceptionCode); } #endif } // namespace -int main(int argc, char **argv) { +int main(int argc, char** argv) { #if GTEST_OS_WINDOWS // Suppresses display of the Windows error dialog upon encountering // a general protection fault (segment violation). SetErrorMode(SEM_NOGPFAULTERRORBOX | SEM_FAILCRITICALERRORS); -# if GTEST_HAS_SEH && !GTEST_OS_WINDOWS_MOBILE +#if GTEST_HAS_SEH && !GTEST_OS_WINDOWS_MOBILE // The default unhandled exception filter does not always exit // with the exception code as exit code - for example it exits with @@ -78,7 +75,7 @@ int main(int argc, char **argv) { // exceptions. SetUnhandledExceptionFilter(ExitWithExceptionCode); -# endif +#endif #endif // GTEST_OS_WINDOWS testing::InitGoogleTest(&argc, argv); diff --git a/googletest/test/googletest-catch-exceptions-test_.cc b/googletest/test/googletest-catch-exceptions-test_.cc index 8c127d4..3c8f4f4 100644 --- a/googletest/test/googletest-catch-exceptions-test_.cc +++ b/googletest/test/googletest-catch-exceptions-test_.cc @@ -32,18 +32,18 @@ // exceptions, and the output is verified by // googletest-catch-exceptions-test.py. -#include <stdio.h> // NOLINT +#include <stdio.h> // NOLINT #include <stdlib.h> // For exit(). #include "gtest/gtest.h" #if GTEST_HAS_SEH -# include <windows.h> +#include <windows.h> #endif #if GTEST_HAS_EXCEPTIONS -# include <exception> // For set_terminate(). -# include <stdexcept> +#include <exception> // For set_terminate(). +#include <stdexcept> #endif using testing::Test; @@ -93,9 +93,7 @@ class SehExceptionInTearDownTest : public Test { TEST_F(SehExceptionInTearDownTest, ThrowsExceptionInTearDown) {} -TEST(SehExceptionTest, ThrowsSehException) { - RaiseException(42, 0, 0, NULL); -} +TEST(SehExceptionTest, ThrowsSehException) { RaiseException(42, 0, 0, NULL); } #endif // GTEST_HAS_SEH @@ -269,9 +267,7 @@ TEST_F(CxxExceptionInTestBodyTest, ThrowsStdCxxException) { throw std::runtime_error("Standard C++ exception"); } -TEST(CxxExceptionTest, ThrowsNonStdCxxException) { - throw "C-string"; -} +TEST(CxxExceptionTest, ThrowsNonStdCxxException) { throw "C-string"; } // This terminate handler aborts the program using exit() rather than abort(). // This avoids showing pop-ups on Windows systems and core dumps on Unix-like diff --git a/googletest/test/googletest-color-test_.cc b/googletest/test/googletest-color-test_.cc index 220a3a0..55657b7 100644 --- a/googletest/test/googletest-color-test_.cc +++ b/googletest/test/googletest-color-test_.cc @@ -27,7 +27,6 @@ // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - // A helper program for testing how Google Test determines whether to use // colors in the output. It prints "YES" and returns 1 if Google Test // decides to use colors, and prints "NO" and returns 0 otherwise. @@ -43,8 +42,7 @@ using testing::internal::ShouldUseColor; // created before main() is entered, and thus that ShouldUseColor() // works the same way as in a real Google-Test-based test. We don't actual // run the TEST itself. -TEST(GTestColorTest, Dummy) { -} +TEST(GTestColorTest, Dummy) {} int main(int argc, char** argv) { testing::InitGoogleTest(&argc, argv); diff --git a/googletest/test/googletest-death-test-test.cc b/googletest/test/googletest-death-test-test.cc index 62a84b4..4737ff9 100644 --- a/googletest/test/googletest-death-test-test.cc +++ b/googletest/test/googletest-death-test-test.cc @@ -31,7 +31,6 @@ // Tests for death tests. #include "gtest/gtest-death-test.h" - #include "gtest/gtest.h" #include "gtest/internal/gtest-filepath.h" @@ -40,25 +39,25 @@ using testing::internal::AlwaysTrue; #if GTEST_HAS_DEATH_TEST -# if GTEST_OS_WINDOWS -# include <fcntl.h> // For O_BINARY -# include <direct.h> // For chdir(). -# include <io.h> -# else -# include <unistd.h> -# include <sys/wait.h> // For waitpid. -# endif // GTEST_OS_WINDOWS +#if GTEST_OS_WINDOWS +#include <direct.h> // For chdir(). +#include <fcntl.h> // For O_BINARY +#include <io.h> +#else +#include <sys/wait.h> // For waitpid. +#include <unistd.h> +#endif // GTEST_OS_WINDOWS -# include <limits.h> -# include <signal.h> -# include <stdio.h> +#include <limits.h> +#include <signal.h> +#include <stdio.h> -# if GTEST_OS_LINUX -# include <sys/time.h> -# endif // GTEST_OS_LINUX +#if GTEST_OS_LINUX +#include <sys/time.h> +#endif // GTEST_OS_LINUX -# include "gtest/gtest-spi.h" -# include "src/gtest-internal-inl.h" +#include "gtest/gtest-spi.h" +#include "src/gtest-internal-inl.h" namespace posix = ::testing::internal::posix; @@ -90,6 +89,7 @@ class ReplaceDeathTestFactory { unit_test_impl_->death_test_factory_.release(); unit_test_impl_->death_test_factory_.reset(old_factory_); } + private: // Prevents copying ReplaceDeathTestFactory objects. ReplaceDeathTestFactory(const ReplaceDeathTestFactory&); @@ -116,8 +116,7 @@ void DieWithMessage(const ::std::string& message) { // Some compilers can recognize that _exit() never returns and issue the // 'unreachable code' warning for code following this function, unless // fooled by a fake condition. - if (AlwaysTrue()) - _exit(1); + if (AlwaysTrue()) _exit(1); } void DieInside(const ::std::string& function) { @@ -137,8 +136,7 @@ class TestForDeathTest : public testing::Test { // A method of the test fixture that may die. void MemberFunction() { - if (should_die_) - DieInside("MemberFunction"); + if (should_die_) DieInside("MemberFunction"); } // True if and only if MemberFunction() should die. @@ -153,8 +151,7 @@ class MayDie { // A member function that may die. void MemberFunction() const { - if (should_die_) - DieInside("MayDie::MemberFunction"); + if (should_die_) DieInside("MayDie::MemberFunction"); } private: @@ -173,8 +170,7 @@ int NonVoidFunction() { // A unary function that may die. void DieIf(bool should_die) { - if (should_die) - DieInside("DieIf"); + if (should_die) DieInside("DieIf"); } // A binary function that may die. @@ -195,16 +191,16 @@ void DeathTestSubroutine() { int DieInDebugElse12(int* sideeffect) { if (sideeffect) *sideeffect = 12; -# ifndef NDEBUG +#ifndef NDEBUG DieInside("DieInDebugElse12"); -# endif // NDEBUG +#endif // NDEBUG return 12; } -# if GTEST_OS_WINDOWS +#if GTEST_OS_WINDOWS // Death in dbg due to Windows CRT assertion failure, not opt. int DieInCRTDebugElse12(int* sideeffect) { @@ -224,7 +220,7 @@ int DieInCRTDebugElse12(int* sideeffect) { #endif // GTEST_OS_WINDOWS -# if GTEST_OS_WINDOWS || GTEST_OS_FUCHSIA +#if GTEST_OS_WINDOWS || GTEST_OS_FUCHSIA // Tests the ExitedWithCode predicate. TEST(ExitStatusPredicateTest, ExitedWithCode) { @@ -237,7 +233,7 @@ TEST(ExitStatusPredicateTest, ExitedWithCode) { EXPECT_FALSE(testing::ExitedWithCode(1)(0)); } -# else +#else // Returns the exit status of a process that calls _exit(2) with a // given exit code. This is a helper function for the @@ -270,14 +266,14 @@ static int KilledExitStatus(int signum) { // Tests the ExitedWithCode predicate. TEST(ExitStatusPredicateTest, ExitedWithCode) { - const int status0 = NormalExitStatus(0); - const int status1 = NormalExitStatus(1); + const int status0 = NormalExitStatus(0); + const int status1 = NormalExitStatus(1); const int status42 = NormalExitStatus(42); const testing::ExitedWithCode pred0(0); const testing::ExitedWithCode pred1(1); const testing::ExitedWithCode pred42(42); - EXPECT_PRED1(pred0, status0); - EXPECT_PRED1(pred1, status1); + EXPECT_PRED1(pred0, status0); + EXPECT_PRED1(pred1, status1); EXPECT_PRED1(pred42, status42); EXPECT_FALSE(pred0(status1)); EXPECT_FALSE(pred42(status0)); @@ -296,7 +292,7 @@ TEST(ExitStatusPredicateTest, KilledBySignal) { EXPECT_FALSE(pred_kill(status_segv)); } -# endif // GTEST_OS_WINDOWS || GTEST_OS_FUCHSIA +#endif // GTEST_OS_WINDOWS || GTEST_OS_FUCHSIA // The following code intentionally tests a suboptimal syntax. #ifdef __GNUC__ @@ -320,8 +316,7 @@ TEST_F(TestForDeathTest, SingleStatement) { // doesn't expand into an "if" statement without an "else" ; - if (AlwaysFalse()) - ASSERT_DEATH(return, "") << "did not die"; + if (AlwaysFalse()) ASSERT_DEATH(return, "") << "did not die"; if (AlwaysFalse()) ; @@ -332,7 +327,7 @@ TEST_F(TestForDeathTest, SingleStatement) { #pragma GCC diagnostic pop #endif -# if GTEST_USES_PCRE +#if GTEST_USES_PCRE void DieWithEmbeddedNul() { fprintf(stderr, "Hello%cmy null world.\n", '\0'); @@ -347,7 +342,7 @@ TEST_F(TestForDeathTest, EmbeddedNulInMessage) { ASSERT_DEATH(DieWithEmbeddedNul(), "my null world"); } -# endif // GTEST_USES_PCRE +#endif // GTEST_USES_PCRE // Tests that death test macros expand to code which interacts well with switch // statements. @@ -357,12 +352,12 @@ TEST_F(TestForDeathTest, SwitchStatement) { GTEST_DISABLE_MSC_WARNINGS_PUSH_(4065) switch (0) - default: - ASSERT_DEATH(_exit(1), "") << "exit in default switch handler"; + default: + ASSERT_DEATH(_exit(1), "") << "exit in default switch handler"; switch (0) - case 0: - EXPECT_DEATH(_exit(1), "") << "exit in switch case"; + case 0: + EXPECT_DEATH(_exit(1), "") << "exit in switch case"; GTEST_DISABLE_MSC_WARNINGS_POP_() } @@ -396,8 +391,9 @@ TEST_F(TestForDeathTest, FastDeathTestInChangedDir) { ASSERT_DEATH(_exit(1), ""); } -# if GTEST_OS_LINUX -void SigprofAction(int, siginfo_t*, void*) { /* no op */ } +#if GTEST_OS_LINUX +void SigprofAction(int, siginfo_t*, void*) { /* no op */ +} // Sets SIGPROF action and ITIMER_PROF timer (interval: 1ms). void SetSigprofActionAndTimer() { @@ -448,7 +444,7 @@ TEST_F(TestForDeathTest, ThreadSafeSigprofActionSet) { DisableSigprofActionAndTimer(&old_signal_action); EXPECT_TRUE(old_signal_action.sa_sigaction == SigprofAction); } -# endif // GTEST_OS_LINUX +#endif // GTEST_OS_LINUX // Repeats a representative sample of death tests in the "threadsafe" style: @@ -487,13 +483,11 @@ TEST_F(TestForDeathTest, MixedStyles) { EXPECT_DEATH(_exit(1), ""); } -# if GTEST_HAS_CLONE && GTEST_HAS_PTHREAD +#if GTEST_HAS_CLONE && GTEST_HAS_PTHREAD bool pthread_flag; -void SetPthreadFlag() { - pthread_flag = true; -} +void SetPthreadFlag() { pthread_flag = true; } TEST_F(TestForDeathTest, DoesNotExecuteAtforkHooks) { if (!GTEST_FLAG_GET(death_test_use_fork)) { @@ -505,7 +499,7 @@ TEST_F(TestForDeathTest, DoesNotExecuteAtforkHooks) { } } -# endif // GTEST_HAS_CLONE && GTEST_HAS_PTHREAD +#endif // GTEST_HAS_CLONE && GTEST_HAS_PTHREAD // Tests that a method of another class can be used in a death test. TEST_F(TestForDeathTest, MethodOfAnotherClass) { @@ -527,7 +521,7 @@ TEST_F(TestForDeathTest, AcceptsAnythingConvertibleToRE) { const testing::internal::RE regex(regex_c_str); EXPECT_DEATH(GlobalFunction(), regex); -# if !GTEST_USES_PCRE +#if !GTEST_USES_PCRE const ::std::string regex_std_str(regex_c_str); EXPECT_DEATH(GlobalFunction(), regex_std_str); @@ -536,7 +530,7 @@ TEST_F(TestForDeathTest, AcceptsAnythingConvertibleToRE) { // lifetime extension of the pointer is not sufficient. EXPECT_DEATH(GlobalFunction(), ::std::string(regex_c_str).c_str()); -# endif // !GTEST_USES_PCRE +#endif // !GTEST_USES_PCRE } // Tests that a non-void function can be used in a death test. @@ -551,9 +545,7 @@ TEST_F(TestForDeathTest, FunctionWithParameter) { } // Tests that ASSERT_DEATH can be used outside a TEST, TEST_F, or test fixture. -TEST_F(TestForDeathTest, OutsideFixture) { - DeathTestSubroutine(); -} +TEST_F(TestForDeathTest, OutsideFixture) { DeathTestSubroutine(); } // Tests that death tests can be done inside a loop. TEST_F(TestForDeathTest, InsideLoop) { @@ -564,25 +556,28 @@ TEST_F(TestForDeathTest, InsideLoop) { // Tests that a compound statement can be used in a death test. TEST_F(TestForDeathTest, CompoundStatement) { - EXPECT_DEATH({ // NOLINT - const int x = 2; - const int y = x + 1; - DieIfLessThan(x, y); - }, - "DieIfLessThan"); + EXPECT_DEATH( + { // NOLINT + const int x = 2; + const int y = x + 1; + DieIfLessThan(x, y); + }, + "DieIfLessThan"); } // Tests that code that doesn't die causes a death test to fail. TEST_F(TestForDeathTest, DoesNotDie) { - EXPECT_NONFATAL_FAILURE(EXPECT_DEATH(DieIf(false), "DieIf"), - "failed to die"); + EXPECT_NONFATAL_FAILURE(EXPECT_DEATH(DieIf(false), "DieIf"), "failed to die"); } // Tests that a death test fails when the error message isn't expected. TEST_F(TestForDeathTest, ErrorMessageMismatch) { - EXPECT_NONFATAL_FAILURE({ // NOLINT - EXPECT_DEATH(DieIf(true), "DieIfLessThan") << "End of death test message."; - }, "died but not with expected error"); + EXPECT_NONFATAL_FAILURE( + { // NOLINT + EXPECT_DEATH(DieIf(true), "DieIfLessThan") + << "End of death test message."; + }, + "died but not with expected error"); } // On exit, *aborted will be true if and only if the EXPECT_DEATH() @@ -596,19 +591,20 @@ void ExpectDeathTestHelper(bool* aborted) { // Tests that EXPECT_DEATH doesn't abort the test on failure. TEST_F(TestForDeathTest, EXPECT_DEATH) { bool aborted = true; - EXPECT_NONFATAL_FAILURE(ExpectDeathTestHelper(&aborted), - "failed to die"); + EXPECT_NONFATAL_FAILURE(ExpectDeathTestHelper(&aborted), "failed to die"); EXPECT_FALSE(aborted); } // Tests that ASSERT_DEATH does abort the test on failure. TEST_F(TestForDeathTest, ASSERT_DEATH) { static bool aborted; - EXPECT_FATAL_FAILURE({ // NOLINT - aborted = true; - ASSERT_DEATH(DieIf(false), "DieIf"); // This assertion should fail. - aborted = false; - }, "failed to die"); + EXPECT_FATAL_FAILURE( + { // NOLINT + aborted = true; + ASSERT_DEATH(DieIf(false), "DieIf"); // This assertion should fail. + aborted = false; + }, + "failed to die"); EXPECT_TRUE(aborted); } @@ -653,20 +649,20 @@ TEST_F(TestForDeathTest, TestExpectDebugDeath) { EXPECT_DEBUG_DEATH(DieInDebugElse12(&sideeffect), regex) << "Must accept a streamed message"; -# ifdef NDEBUG +#ifdef NDEBUG // Checks that the assignment occurs in opt mode (sideeffect). EXPECT_EQ(12, sideeffect); -# else +#else // Checks that the assignment does not occur in dbg mode (no sideeffect). EXPECT_EQ(0, sideeffect); -# endif +#endif } -# if GTEST_OS_WINDOWS +#if GTEST_OS_WINDOWS // https://docs.microsoft.com/en-us/cpp/c-runtime-library/reference/crtsetreportmode // In debug mode, the calls to _CrtSetReportMode and _CrtSetReportFile enable @@ -682,7 +678,7 @@ TEST_F(TestForDeathTest, CRTDebugDeath) { } #endif // _DEBUG -# endif // GTEST_OS_WINDOWS +#endif // GTEST_OS_WINDOWS // Tests that ASSERT_DEBUG_DEATH works as expected, that is, you can stream a // message to it, and in debug mode it: @@ -697,20 +693,20 @@ TEST_F(TestForDeathTest, TestAssertDebugDeath) { ASSERT_DEBUG_DEATH(DieInDebugElse12(&sideeffect), "death.*DieInDebugElse12") << "Must accept a streamed message"; -# ifdef NDEBUG +#ifdef NDEBUG // Checks that the assignment occurs in opt mode (sideeffect). EXPECT_EQ(12, sideeffect); -# else +#else // Checks that the assignment does not occur in dbg mode (no sideeffect). EXPECT_EQ(0, sideeffect); -# endif +#endif } -# ifndef NDEBUG +#ifndef NDEBUG void ExpectDebugDeathHelper(bool* aborted) { *aborted = true; @@ -718,10 +714,11 @@ void ExpectDebugDeathHelper(bool* aborted) { *aborted = false; } -# if GTEST_OS_WINDOWS +#if GTEST_OS_WINDOWS TEST(PopUpDeathTest, DoesNotShowPopUpOnAbort) { - printf("This test should be considered failing if it shows " - "any pop-up dialogs.\n"); + printf( + "This test should be considered failing if it shows " + "any pop-up dialogs.\n"); fflush(stdout); EXPECT_DEATH( @@ -731,7 +728,7 @@ TEST(PopUpDeathTest, DoesNotShowPopUpOnAbort) { }, ""); } -# endif // GTEST_OS_WINDOWS +#endif // GTEST_OS_WINDOWS // Tests that EXPECT_DEBUG_DEATH in debug mode does not abort // the function. @@ -822,42 +819,44 @@ TEST_F(TestForDeathTest, AssertDebugDeathAborts10) { EXPECT_TRUE(aborted); } -# endif // _NDEBUG +#endif // _NDEBUG // Tests the *_EXIT family of macros, using a variety of predicates. static void TestExitMacros() { - EXPECT_EXIT(_exit(1), testing::ExitedWithCode(1), ""); + EXPECT_EXIT(_exit(1), testing::ExitedWithCode(1), ""); ASSERT_EXIT(_exit(42), testing::ExitedWithCode(42), ""); -# if GTEST_OS_WINDOWS +#if GTEST_OS_WINDOWS // Of all signals effects on the process exit code, only those of SIGABRT // are documented on Windows. // See https://msdn.microsoft.com/en-us/query-bi/m/dwwzkt4c. EXPECT_EXIT(raise(SIGABRT), testing::ExitedWithCode(3), "") << "b_ar"; -# elif !GTEST_OS_FUCHSIA +#elif !GTEST_OS_FUCHSIA // Fuchsia has no unix signals. EXPECT_EXIT(raise(SIGKILL), testing::KilledBySignal(SIGKILL), "") << "foo"; ASSERT_EXIT(raise(SIGUSR2), testing::KilledBySignal(SIGUSR2), "") << "bar"; - EXPECT_FATAL_FAILURE({ // NOLINT - ASSERT_EXIT(_exit(0), testing::KilledBySignal(SIGSEGV), "") - << "This failure is expected, too."; - }, "This failure is expected, too."); + EXPECT_FATAL_FAILURE( + { // NOLINT + ASSERT_EXIT(_exit(0), testing::KilledBySignal(SIGSEGV), "") + << "This failure is expected, too."; + }, + "This failure is expected, too."); -# endif // GTEST_OS_WINDOWS +#endif // GTEST_OS_WINDOWS - EXPECT_NONFATAL_FAILURE({ // NOLINT - EXPECT_EXIT(raise(SIGSEGV), testing::ExitedWithCode(0), "") - << "This failure is expected."; - }, "This failure is expected."); + EXPECT_NONFATAL_FAILURE( + { // NOLINT + EXPECT_EXIT(raise(SIGSEGV), testing::ExitedWithCode(0), "") + << "This failure is expected."; + }, + "This failure is expected."); } -TEST_F(TestForDeathTest, ExitMacros) { - TestExitMacros(); -} +TEST_F(TestForDeathTest, ExitMacros) { TestExitMacros(); } TEST_F(TestForDeathTest, ExitMacrosUsingFork) { GTEST_FLAG_SET(death_test_use_fork, true); @@ -866,39 +865,40 @@ TEST_F(TestForDeathTest, ExitMacrosUsingFork) { TEST_F(TestForDeathTest, InvalidStyle) { GTEST_FLAG_SET(death_test_style, "rococo"); - EXPECT_NONFATAL_FAILURE({ // NOLINT - EXPECT_DEATH(_exit(0), "") << "This failure is expected."; - }, "This failure is expected."); + EXPECT_NONFATAL_FAILURE( + { // NOLINT + EXPECT_DEATH(_exit(0), "") << "This failure is expected."; + }, + "This failure is expected."); } TEST_F(TestForDeathTest, DeathTestFailedOutput) { GTEST_FLAG_SET(death_test_style, "fast"); EXPECT_NONFATAL_FAILURE( - EXPECT_DEATH(DieWithMessage("death\n"), - "expected message"), + EXPECT_DEATH(DieWithMessage("death\n"), "expected message"), "Actual msg:\n" "[ DEATH ] death\n"); } TEST_F(TestForDeathTest, DeathTestUnexpectedReturnOutput) { GTEST_FLAG_SET(death_test_style, "fast"); - EXPECT_NONFATAL_FAILURE( - EXPECT_DEATH({ - fprintf(stderr, "returning\n"); - fflush(stderr); - return; - }, ""), - " Result: illegal return in test statement.\n" - " Error msg:\n" - "[ DEATH ] returning\n"); + EXPECT_NONFATAL_FAILURE(EXPECT_DEATH( + { + fprintf(stderr, "returning\n"); + fflush(stderr); + return; + }, + ""), + " Result: illegal return in test statement.\n" + " Error msg:\n" + "[ DEATH ] returning\n"); } TEST_F(TestForDeathTest, DeathTestBadExitCodeOutput) { GTEST_FLAG_SET(death_test_style, "fast"); EXPECT_NONFATAL_FAILURE( EXPECT_EXIT(DieWithMessage("exiting with rc 1\n"), - testing::ExitedWithCode(3), - "expected message"), + testing::ExitedWithCode(3), "expected message"), " Result: died but not with expected exit code:\n" " Exited with exit status 1\n" "Actual msg:\n" @@ -931,8 +931,8 @@ class MockDeathTestFactory : public DeathTestFactory { int line, DeathTest** test) override; // Sets the parameters for subsequent calls to Create. - void SetParameters(bool create, DeathTest::TestRole role, - int status, bool passed); + void SetParameters(bool create, DeathTest::TestRole role, int status, + bool passed); // Accessors. int AssumeRoleCalls() const { return assume_role_calls_; } @@ -974,17 +974,15 @@ class MockDeathTestFactory : public DeathTestFactory { bool test_deleted_; }; - // A DeathTest implementation useful in testing. It returns values set // at its creation from its various inherited DeathTest methods, and // reports calls to those methods to its parent MockDeathTestFactory // object. class MockDeathTest : public DeathTest { public: - MockDeathTest(MockDeathTestFactory *parent, - TestRole role, int status, bool passed) : - parent_(parent), role_(role), status_(status), passed_(passed) { - } + MockDeathTest(MockDeathTestFactory* parent, TestRole role, int status, + bool passed) + : parent_(parent), role_(role), status_(status), passed_(passed) {} ~MockDeathTest() override { parent_->test_deleted_ = true; } TestRole AssumeRole() override { ++parent_->assume_role_calls_; @@ -1009,7 +1007,6 @@ class MockDeathTest : public DeathTest { const bool passed_; }; - // MockDeathTestFactory constructor. MockDeathTestFactory::MockDeathTestFactory() : create_(true), @@ -1019,13 +1016,10 @@ MockDeathTestFactory::MockDeathTestFactory() assume_role_calls_(0), wait_calls_(0), passed_args_(), - abort_args_() { -} - + abort_args_() {} // Sets the parameters for subsequent calls to Create. -void MockDeathTestFactory::SetParameters(bool create, - DeathTest::TestRole role, +void MockDeathTestFactory::SetParameters(bool create, DeathTest::TestRole role, int status, bool passed) { create_ = create; role_ = role; @@ -1038,7 +1032,6 @@ void MockDeathTestFactory::SetParameters(bool create, abort_args_.clear(); } - // Sets test to NULL (if create_ is false) or to the address of a new // MockDeathTest object with parameters taken from the last call // to SetParameters (if create_ is true). Always returns true. @@ -1078,10 +1071,12 @@ class MacroLogicDeathTest : public testing::Test { // test cannot be run directly from a test routine that uses a // MockDeathTest, or the remainder of the routine will not be executed. static void RunReturningDeathTest(bool* flag) { - ASSERT_DEATH({ // NOLINT - *flag = true; - return; - }, ""); + ASSERT_DEATH( + { // NOLINT + *flag = true; + return; + }, + ""); } }; @@ -1166,8 +1161,7 @@ TEST_F(MacroLogicDeathTest, ChildDoesNotDie) { // _exit(2) is called in that case by ForkingDeathTest, but not by // our MockDeathTest. ASSERT_EQ(2U, factory_->AbortCalls()); - EXPECT_EQ(DeathTest::TEST_DID_NOT_DIE, - factory_->AbortArgument(0)); + EXPECT_EQ(DeathTest::TEST_DID_NOT_DIE, factory_->AbortArgument(0)); EXPECT_EQ(DeathTest::TEST_ENCOUNTERED_RETURN_STATEMENT, factory_->AbortArgument(1)); EXPECT_TRUE(factory_->TestDeleted()); @@ -1183,12 +1177,16 @@ TEST(SuccessRegistrationDeathTest, NoSuccessPart) { TEST(StreamingAssertionsDeathTest, DeathTest) { EXPECT_DEATH(_exit(1), "") << "unexpected failure"; ASSERT_DEATH(_exit(1), "") << "unexpected failure"; - EXPECT_NONFATAL_FAILURE({ // NOLINT - EXPECT_DEATH(_exit(0), "") << "expected failure"; - }, "expected failure"); - EXPECT_FATAL_FAILURE({ // NOLINT - ASSERT_DEATH(_exit(0), "") << "expected failure"; - }, "expected failure"); + EXPECT_NONFATAL_FAILURE( + { // NOLINT + EXPECT_DEATH(_exit(0), "") << "expected failure"; + }, + "expected failure"); + EXPECT_FATAL_FAILURE( + { // NOLINT + ASSERT_DEATH(_exit(0), "") << "expected failure"; + }, + "expected failure"); } // Tests that GetLastErrnoDescription returns an empty string when the @@ -1200,7 +1198,7 @@ TEST(GetLastErrnoDescription, GetLastErrnoDescriptionWorks) { EXPECT_STREQ("", GetLastErrnoDescription().c_str()); } -# if GTEST_OS_WINDOWS +#if GTEST_OS_WINDOWS TEST(AutoHandleTest, AutoHandleWorks) { HANDLE handle = ::CreateEvent(NULL, FALSE, FALSE, NULL); ASSERT_NE(INVALID_HANDLE_VALUE, handle); @@ -1225,15 +1223,15 @@ TEST(AutoHandleTest, AutoHandleWorks) { testing::internal::AutoHandle auto_handle2; EXPECT_EQ(INVALID_HANDLE_VALUE, auto_handle2.Get()); } -# endif // GTEST_OS_WINDOWS +#endif // GTEST_OS_WINDOWS -# if GTEST_OS_WINDOWS +#if GTEST_OS_WINDOWS typedef unsigned __int64 BiggestParsable; typedef signed __int64 BiggestSignedParsable; -# else +#else typedef unsigned long long BiggestParsable; typedef signed long long BiggestSignedParsable; -# endif // GTEST_OS_WINDOWS +#endif // GTEST_OS_WINDOWS // We cannot use std::numeric_limits<T>::max() as it clashes with the // max() macro defined by <windows.h>. @@ -1324,11 +1322,11 @@ TEST(ParseNaturalNumberTest, WorksForShorterIntegers) { EXPECT_EQ(123, char_result); } -# if GTEST_OS_WINDOWS +#if GTEST_OS_WINDOWS TEST(EnvironmentTest, HandleFitsIntoSizeT) { ASSERT_TRUE(sizeof(HANDLE) <= sizeof(size_t)); } -# endif // GTEST_OS_WINDOWS +#endif // GTEST_OS_WINDOWS // Tests that EXPECT_DEATH_IF_SUPPORTED/ASSERT_DEATH_IF_SUPPORTED trigger // failures when death tests are available on the system. @@ -1346,21 +1344,25 @@ TEST(ConditionalDeathMacrosDeathTest, ExpectsDeathWhenDeathTestsAvailable) { TEST(InDeathTestChildDeathTest, ReportsDeathTestCorrectlyInFastStyle) { GTEST_FLAG_SET(death_test_style, "fast"); EXPECT_FALSE(InDeathTestChild()); - EXPECT_DEATH({ - fprintf(stderr, InDeathTestChild() ? "Inside" : "Outside"); - fflush(stderr); - _exit(1); - }, "Inside"); + EXPECT_DEATH( + { + fprintf(stderr, InDeathTestChild() ? "Inside" : "Outside"); + fflush(stderr); + _exit(1); + }, + "Inside"); } TEST(InDeathTestChildDeathTest, ReportsDeathTestCorrectlyInThreadSafeStyle) { GTEST_FLAG_SET(death_test_style, "threadsafe"); EXPECT_FALSE(InDeathTestChild()); - EXPECT_DEATH({ - fprintf(stderr, InDeathTestChild() ? "Inside" : "Outside"); - fflush(stderr); - _exit(1); - }, "Inside"); + EXPECT_DEATH( + { + fprintf(stderr, InDeathTestChild() ? "Inside" : "Outside"); + fflush(stderr); + _exit(1); + }, + "Inside"); } void DieWithMessage(const char* message) { @@ -1488,8 +1490,7 @@ TEST(ConditionalDeathMacrosSyntaxDeathTest, SingleStatement) { // doesn't expand into an "if" statement without an "else" ; // NOLINT - if (AlwaysFalse()) - ASSERT_DEATH_IF_SUPPORTED(return, "") << "did not die"; + if (AlwaysFalse()) ASSERT_DEATH_IF_SUPPORTED(return, "") << "did not die"; if (AlwaysFalse()) ; // NOLINT @@ -1508,21 +1509,18 @@ TEST(ConditionalDeathMacrosSyntaxDeathTest, SwitchStatement) { GTEST_DISABLE_MSC_WARNINGS_PUSH_(4065) switch (0) - default: - ASSERT_DEATH_IF_SUPPORTED(_exit(1), "") - << "exit in default switch handler"; + default: + ASSERT_DEATH_IF_SUPPORTED(_exit(1), "") << "exit in default switch handler"; switch (0) - case 0: - EXPECT_DEATH_IF_SUPPORTED(_exit(1), "") << "exit in switch case"; + case 0: + EXPECT_DEATH_IF_SUPPORTED(_exit(1), "") << "exit in switch case"; GTEST_DISABLE_MSC_WARNINGS_POP_() } // Tests that a test case whose name ends with "DeathTest" works fine // on Windows. -TEST(NotADeathTest, Test) { - SUCCEED(); -} +TEST(NotADeathTest, Test) { SUCCEED(); } } // namespace diff --git a/googletest/test/googletest-death-test_ex_test.cc b/googletest/test/googletest-death-test_ex_test.cc index bbacc8a..f2515e3 100644 --- a/googletest/test/googletest-death-test_ex_test.cc +++ b/googletest/test/googletest-death-test_ex_test.cc @@ -35,15 +35,15 @@ #if GTEST_HAS_DEATH_TEST -# if GTEST_HAS_SEH -# include <windows.h> // For RaiseException(). -# endif +#if GTEST_HAS_SEH +#include <windows.h> // For RaiseException(). +#endif -# include "gtest/gtest-spi.h" +#include "gtest/gtest-spi.h" -# if GTEST_HAS_EXCEPTIONS +#if GTEST_HAS_EXCEPTIONS -# include <exception> // For std::exception. +#include <exception> // For std::exception. // Tests that death tests report thrown exceptions as failures and that the // exceptions do not escape death test macros. @@ -67,12 +67,11 @@ TEST(CxxExceptionDeathTest, PrintsMessageForStdExceptions) { EXPECT_NONFATAL_FAILURE(EXPECT_DEATH(throw TestException(), ""), "exceptional message"); // Verifies that the location is mentioned in the failure text. - EXPECT_NONFATAL_FAILURE(EXPECT_DEATH(throw TestException(), ""), - __FILE__); + EXPECT_NONFATAL_FAILURE(EXPECT_DEATH(throw TestException(), ""), __FILE__); } -# endif // GTEST_HAS_EXCEPTIONS +#endif // GTEST_HAS_EXCEPTIONS -# if GTEST_HAS_SEH +#if GTEST_HAS_SEH // Tests that enabling interception of SEH exceptions with the // catch_exceptions flag does not interfere with SEH exceptions being // treated as death by death tests. @@ -81,7 +80,7 @@ TEST(SehExceptionDeasTest, CatchExceptionsDoesNotInterfere) { << "with catch_exceptions " << (GTEST_FLAG_GET(catch_exceptions) ? "enabled" : "disabled"); } -# endif +#endif #endif // GTEST_HAS_DEATH_TEST diff --git a/googletest/test/googletest-env-var-test_.cc b/googletest/test/googletest-env-var-test_.cc index 0ff0152..3653375 100644 --- a/googletest/test/googletest-env-var-test_.cc +++ b/googletest/test/googletest-env-var-test_.cc @@ -27,7 +27,6 @@ // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - // A helper program for testing that Google Test parses the environment // variables correctly. @@ -43,8 +42,7 @@ namespace testing { // The purpose of this is to make the test more realistic by ensuring // that the UnitTest singleton is created before main() is entered. // We don't actual run the TEST itself. -TEST(GTestEnvVarTest, Dummy) { -} +TEST(GTestEnvVarTest, Dummy) {} void PrintFlag(const char* flag) { if (strcmp(flag, "break_on_failure") == 0) { diff --git a/googletest/test/googletest-failfast-unittest_.cc b/googletest/test/googletest-failfast-unittest_.cc index 0b2c951..3bd05a8 100644 --- a/googletest/test/googletest-failfast-unittest_.cc +++ b/googletest/test/googletest-failfast-unittest_.cc @@ -27,7 +27,6 @@ // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - // Unit test for Google Test test filters. // // A user can specify which test(s) in a Google Test program to run via @@ -160,7 +159,7 @@ TEST(HasSkipTest, Test4) { FAIL() << "Expected failure."; } } // namespace -int main(int argc, char **argv) { +int main(int argc, char** argv) { ::testing::InitGoogleTest(&argc, argv); ::testing::UnitTest::GetInstance()->listeners().Append(new MyTestListener()); return RUN_ALL_TESTS(); diff --git a/googletest/test/googletest-filepath-test.cc b/googletest/test/googletest-filepath-test.cc index aafad36..62f1b2e 100644 --- a/googletest/test/googletest-filepath-test.cc +++ b/googletest/test/googletest-filepath-test.cc @@ -35,15 +35,15 @@ // This file is #included from gtest-internal.h. // Do not #include this file anywhere else! -#include "gtest/internal/gtest-filepath.h" #include "gtest/gtest.h" +#include "gtest/internal/gtest-filepath.h" #include "src/gtest-internal-inl.h" #if GTEST_OS_WINDOWS_MOBILE -# include <windows.h> // NOLINT +#include <windows.h> // NOLINT #elif GTEST_OS_WINDOWS -# include <direct.h> // NOLINT -#endif // GTEST_OS_WINDOWS_MOBILE +#include <direct.h> // NOLINT +#endif // GTEST_OS_WINDOWS_MOBILE namespace testing { namespace internal { @@ -55,16 +55,16 @@ namespace { int remove(const char* path) { LPCWSTR wpath = String::AnsiToUtf16(path); int ret = DeleteFile(wpath) ? 0 : -1; - delete [] wpath; + delete[] wpath; return ret; } // Windows CE doesn't have the _rmdir C function. int _rmdir(const char* path) { FilePath filepath(path); - LPCWSTR wpath = String::AnsiToUtf16( - filepath.RemoveTrailingPathSeparator().c_str()); + LPCWSTR wpath = + String::AnsiToUtf16(filepath.RemoveTrailingPathSeparator().c_str()); int ret = RemoveDirectory(wpath) ? 0 : -1; - delete [] wpath; + delete[] wpath; return ret; } @@ -78,18 +78,18 @@ TEST(GetCurrentDirTest, ReturnsCurrentDir) { const FilePath cwd = FilePath::GetCurrentDir(); posix::ChDir(original_dir.c_str()); -# if GTEST_OS_WINDOWS || GTEST_OS_OS2 +#if GTEST_OS_WINDOWS || GTEST_OS_OS2 // Skips the ":". const char* const cwd_without_drive = strchr(cwd.c_str(), ':'); ASSERT_TRUE(cwd_without_drive != NULL); EXPECT_STREQ(GTEST_PATH_SEP_, cwd_without_drive + 1); -# else +#else EXPECT_EQ(GTEST_PATH_SEP_, cwd.string()); -# endif +#endif } #endif // GTEST_OS_WINDOWS_MOBILE @@ -112,33 +112,34 @@ TEST(RemoveDirectoryNameTest, WhenEmptyName) { // RemoveDirectoryName "afile" -> "afile" TEST(RemoveDirectoryNameTest, ButNoDirectory) { - EXPECT_EQ("afile", - FilePath("afile").RemoveDirectoryName().string()); + EXPECT_EQ("afile", FilePath("afile").RemoveDirectoryName().string()); } // RemoveDirectoryName "/afile" -> "afile" TEST(RemoveDirectoryNameTest, RootFileShouldGiveFileName) { EXPECT_EQ("afile", - FilePath(GTEST_PATH_SEP_ "afile").RemoveDirectoryName().string()); + FilePath(GTEST_PATH_SEP_ "afile").RemoveDirectoryName().string()); } // RemoveDirectoryName "adir/" -> "" TEST(RemoveDirectoryNameTest, WhereThereIsNoFileName) { EXPECT_EQ("", - FilePath("adir" GTEST_PATH_SEP_).RemoveDirectoryName().string()); + FilePath("adir" GTEST_PATH_SEP_).RemoveDirectoryName().string()); } // RemoveDirectoryName "adir/afile" -> "afile" TEST(RemoveDirectoryNameTest, ShouldGiveFileName) { - EXPECT_EQ("afile", + EXPECT_EQ( + "afile", FilePath("adir" GTEST_PATH_SEP_ "afile").RemoveDirectoryName().string()); } // RemoveDirectoryName "adir/subdir/afile" -> "afile" TEST(RemoveDirectoryNameTest, ShouldAlsoGiveFileName) { EXPECT_EQ("afile", - FilePath("adir" GTEST_PATH_SEP_ "subdir" GTEST_PATH_SEP_ "afile") - .RemoveDirectoryName().string()); + FilePath("adir" GTEST_PATH_SEP_ "subdir" GTEST_PATH_SEP_ "afile") + .RemoveDirectoryName() + .string()); } #if GTEST_HAS_ALT_PATH_SEP_ @@ -182,7 +183,7 @@ TEST(RemoveFileNameTest, EmptyName) { // RemoveFileName "adir/" -> "adir/" TEST(RemoveFileNameTest, ButNoFile) { EXPECT_EQ("adir" GTEST_PATH_SEP_, - FilePath("adir" GTEST_PATH_SEP_).RemoveFileName().string()); + FilePath("adir" GTEST_PATH_SEP_).RemoveFileName().string()); } // RemoveFileName "adir/afile" -> "adir/" @@ -194,14 +195,15 @@ TEST(RemoveFileNameTest, GivesDirName) { // RemoveFileName "adir/subdir/afile" -> "adir/subdir/" TEST(RemoveFileNameTest, GivesDirAndSubDirName) { EXPECT_EQ("adir" GTEST_PATH_SEP_ "subdir" GTEST_PATH_SEP_, - FilePath("adir" GTEST_PATH_SEP_ "subdir" GTEST_PATH_SEP_ "afile") - .RemoveFileName().string()); + FilePath("adir" GTEST_PATH_SEP_ "subdir" GTEST_PATH_SEP_ "afile") + .RemoveFileName() + .string()); } // RemoveFileName "/afile" -> "/" TEST(RemoveFileNameTest, GivesRootDir) { EXPECT_EQ(GTEST_PATH_SEP_, - FilePath(GTEST_PATH_SEP_ "afile").RemoveFileName().string()); + FilePath(GTEST_PATH_SEP_ "afile").RemoveFileName().string()); } #if GTEST_HAS_ALT_PATH_SEP_ @@ -235,44 +237,43 @@ TEST(RemoveFileNameTest, GivesRootDirForAlternateSeparator) { #endif TEST(MakeFileNameTest, GenerateWhenNumberIsZero) { - FilePath actual = FilePath::MakeFileName(FilePath("foo"), FilePath("bar"), - 0, "xml"); + FilePath actual = + FilePath::MakeFileName(FilePath("foo"), FilePath("bar"), 0, "xml"); EXPECT_EQ("foo" GTEST_PATH_SEP_ "bar.xml", actual.string()); } TEST(MakeFileNameTest, GenerateFileNameNumberGtZero) { - FilePath actual = FilePath::MakeFileName(FilePath("foo"), FilePath("bar"), - 12, "xml"); + FilePath actual = + FilePath::MakeFileName(FilePath("foo"), FilePath("bar"), 12, "xml"); EXPECT_EQ("foo" GTEST_PATH_SEP_ "bar_12.xml", actual.string()); } TEST(MakeFileNameTest, GenerateFileNameWithSlashNumberIsZero) { FilePath actual = FilePath::MakeFileName(FilePath("foo" GTEST_PATH_SEP_), - FilePath("bar"), 0, "xml"); + FilePath("bar"), 0, "xml"); EXPECT_EQ("foo" GTEST_PATH_SEP_ "bar.xml", actual.string()); } TEST(MakeFileNameTest, GenerateFileNameWithSlashNumberGtZero) { FilePath actual = FilePath::MakeFileName(FilePath("foo" GTEST_PATH_SEP_), - FilePath("bar"), 12, "xml"); + FilePath("bar"), 12, "xml"); EXPECT_EQ("foo" GTEST_PATH_SEP_ "bar_12.xml", actual.string()); } TEST(MakeFileNameTest, GenerateWhenNumberIsZeroAndDirIsEmpty) { - FilePath actual = FilePath::MakeFileName(FilePath(""), FilePath("bar"), - 0, "xml"); + FilePath actual = + FilePath::MakeFileName(FilePath(""), FilePath("bar"), 0, "xml"); EXPECT_EQ("bar.xml", actual.string()); } TEST(MakeFileNameTest, GenerateWhenNumberIsNotZeroAndDirIsEmpty) { - FilePath actual = FilePath::MakeFileName(FilePath(""), FilePath("bar"), - 14, "xml"); + FilePath actual = + FilePath::MakeFileName(FilePath(""), FilePath("bar"), 14, "xml"); EXPECT_EQ("bar_14.xml", actual.string()); } TEST(ConcatPathsTest, WorksWhenDirDoesNotEndWithPathSep) { - FilePath actual = FilePath::ConcatPaths(FilePath("foo"), - FilePath("bar.xml")); + FilePath actual = FilePath::ConcatPaths(FilePath("foo"), FilePath("bar.xml")); EXPECT_EQ("foo" GTEST_PATH_SEP_ "bar.xml", actual.string()); } @@ -283,8 +284,7 @@ TEST(ConcatPathsTest, WorksWhenPath1EndsWithPathSep) { } TEST(ConcatPathsTest, Path1BeingEmpty) { - FilePath actual = FilePath::ConcatPaths(FilePath(""), - FilePath("bar.xml")); + FilePath actual = FilePath::ConcatPaths(FilePath(""), FilePath("bar.xml")); EXPECT_EQ("bar.xml", actual.string()); } @@ -294,8 +294,7 @@ TEST(ConcatPathsTest, Path2BeingEmpty) { } TEST(ConcatPathsTest, BothPathBeingEmpty) { - FilePath actual = FilePath::ConcatPaths(FilePath(""), - FilePath("")); + FilePath actual = FilePath::ConcatPaths(FilePath(""), FilePath("")); EXPECT_EQ("", actual.string()); } @@ -307,16 +306,16 @@ TEST(ConcatPathsTest, Path1ContainsPathSep) { } TEST(ConcatPathsTest, Path2ContainsPathSep) { - FilePath actual = FilePath::ConcatPaths( - FilePath("foo" GTEST_PATH_SEP_), - FilePath("bar" GTEST_PATH_SEP_ "bar.xml")); + FilePath actual = + FilePath::ConcatPaths(FilePath("foo" GTEST_PATH_SEP_), + FilePath("bar" GTEST_PATH_SEP_ "bar.xml")); EXPECT_EQ("foo" GTEST_PATH_SEP_ "bar" GTEST_PATH_SEP_ "bar.xml", actual.string()); } TEST(ConcatPathsTest, Path2EndsWithPathSep) { - FilePath actual = FilePath::ConcatPaths(FilePath("foo"), - FilePath("bar" GTEST_PATH_SEP_)); + FilePath actual = + FilePath::ConcatPaths(FilePath("foo"), FilePath("bar" GTEST_PATH_SEP_)); EXPECT_EQ("foo" GTEST_PATH_SEP_ "bar" GTEST_PATH_SEP_, actual.string()); } @@ -332,7 +331,8 @@ TEST(RemoveTrailingPathSeparatorTest, FileNoSlashString) { // RemoveTrailingPathSeparator "foo/" -> "foo" TEST(RemoveTrailingPathSeparatorTest, ShouldRemoveTrailingSeparator) { - EXPECT_EQ("foo", + EXPECT_EQ( + "foo", FilePath("foo" GTEST_PATH_SEP_).RemoveTrailingPathSeparator().string()); #if GTEST_HAS_ALT_PATH_SEP_ EXPECT_EQ("foo", FilePath("foo/").RemoveTrailingPathSeparator().string()); @@ -343,18 +343,19 @@ TEST(RemoveTrailingPathSeparatorTest, ShouldRemoveTrailingSeparator) { TEST(RemoveTrailingPathSeparatorTest, ShouldRemoveLastSeparator) { EXPECT_EQ("foo" GTEST_PATH_SEP_ "bar", FilePath("foo" GTEST_PATH_SEP_ "bar" GTEST_PATH_SEP_) - .RemoveTrailingPathSeparator().string()); + .RemoveTrailingPathSeparator() + .string()); } // RemoveTrailingPathSeparator "foo/bar" -> "foo/bar" TEST(RemoveTrailingPathSeparatorTest, ShouldReturnUnmodified) { - EXPECT_EQ("foo" GTEST_PATH_SEP_ "bar", - FilePath("foo" GTEST_PATH_SEP_ "bar") - .RemoveTrailingPathSeparator().string()); + EXPECT_EQ("foo" GTEST_PATH_SEP_ "bar", FilePath("foo" GTEST_PATH_SEP_ "bar") + .RemoveTrailingPathSeparator() + .string()); } TEST(DirectoryTest, RootDirectoryExists) { -#if GTEST_OS_WINDOWS // We are on Windows. +#if GTEST_OS_WINDOWS // We are on Windows. char current_drive[_MAX_PATH]; // NOLINT current_drive[0] = static_cast<char>(_getdrive() + 'A' - 1); current_drive[1] = ':'; @@ -393,12 +394,12 @@ TEST(DirectoryTest, EmptyPathDirectoryDoesNotExist) { TEST(DirectoryTest, CurrentDirectoryExists) { #if GTEST_OS_WINDOWS // We are on Windows. -# ifndef _WIN32_CE // Windows CE doesn't have a current directory. +#ifndef _WIN32_CE // Windows CE doesn't have a current directory. EXPECT_TRUE(FilePath(".").DirectoryExists()); EXPECT_TRUE(FilePath(".\\").DirectoryExists()); -# endif // _WIN32_CE +#endif // _WIN32_CE #else EXPECT_TRUE(FilePath(".").DirectoryExists()); EXPECT_TRUE(FilePath("./").DirectoryExists()); @@ -411,29 +412,30 @@ TEST(NormalizeTest, MultipleConsecutiveSepaparatorsInMidstring) { FilePath("foo" GTEST_PATH_SEP_ "bar").string()); EXPECT_EQ("foo" GTEST_PATH_SEP_ "bar", FilePath("foo" GTEST_PATH_SEP_ GTEST_PATH_SEP_ "bar").string()); - EXPECT_EQ("foo" GTEST_PATH_SEP_ "bar", - FilePath("foo" GTEST_PATH_SEP_ GTEST_PATH_SEP_ - GTEST_PATH_SEP_ "bar").string()); + EXPECT_EQ( + "foo" GTEST_PATH_SEP_ "bar", + FilePath("foo" GTEST_PATH_SEP_ GTEST_PATH_SEP_ GTEST_PATH_SEP_ "bar") + .string()); } // "/bar" == //bar" == "///bar" TEST(NormalizeTest, MultipleConsecutiveSepaparatorsAtStringStart) { + EXPECT_EQ(GTEST_PATH_SEP_ "bar", FilePath(GTEST_PATH_SEP_ "bar").string()); EXPECT_EQ(GTEST_PATH_SEP_ "bar", - FilePath(GTEST_PATH_SEP_ "bar").string()); - EXPECT_EQ(GTEST_PATH_SEP_ "bar", - FilePath(GTEST_PATH_SEP_ GTEST_PATH_SEP_ "bar").string()); - EXPECT_EQ(GTEST_PATH_SEP_ "bar", - FilePath(GTEST_PATH_SEP_ GTEST_PATH_SEP_ GTEST_PATH_SEP_ "bar").string()); + FilePath(GTEST_PATH_SEP_ GTEST_PATH_SEP_ "bar").string()); + EXPECT_EQ( + GTEST_PATH_SEP_ "bar", + FilePath(GTEST_PATH_SEP_ GTEST_PATH_SEP_ GTEST_PATH_SEP_ "bar").string()); } // "foo/" == foo//" == "foo///" TEST(NormalizeTest, MultipleConsecutiveSepaparatorsAtStringEnd) { + EXPECT_EQ("foo" GTEST_PATH_SEP_, FilePath("foo" GTEST_PATH_SEP_).string()); EXPECT_EQ("foo" GTEST_PATH_SEP_, - FilePath("foo" GTEST_PATH_SEP_).string()); - EXPECT_EQ("foo" GTEST_PATH_SEP_, - FilePath("foo" GTEST_PATH_SEP_ GTEST_PATH_SEP_).string()); - EXPECT_EQ("foo" GTEST_PATH_SEP_, - FilePath("foo" GTEST_PATH_SEP_ GTEST_PATH_SEP_ GTEST_PATH_SEP_).string()); + FilePath("foo" GTEST_PATH_SEP_ GTEST_PATH_SEP_).string()); + EXPECT_EQ( + "foo" GTEST_PATH_SEP_, + FilePath("foo" GTEST_PATH_SEP_ GTEST_PATH_SEP_ GTEST_PATH_SEP_).string()); } #if GTEST_HAS_ALT_PATH_SEP_ @@ -442,12 +444,10 @@ TEST(NormalizeTest, MultipleConsecutiveSepaparatorsAtStringEnd) { // regardless of their combination (e.g. "foo\" =="foo/\" == // "foo\\/"). TEST(NormalizeTest, MixAlternateSeparatorAtStringEnd) { - EXPECT_EQ("foo" GTEST_PATH_SEP_, - FilePath("foo/").string()); + EXPECT_EQ("foo" GTEST_PATH_SEP_, FilePath("foo/").string()); EXPECT_EQ("foo" GTEST_PATH_SEP_, FilePath("foo" GTEST_PATH_SEP_ "/").string()); - EXPECT_EQ("foo" GTEST_PATH_SEP_, - FilePath("foo//" GTEST_PATH_SEP_).string()); + EXPECT_EQ("foo" GTEST_PATH_SEP_, FilePath("foo//" GTEST_PATH_SEP_).string()); } #endif @@ -478,15 +478,15 @@ TEST(AssignmentOperatorTest, ConstAssignedToNonConst) { class DirectoryCreationTest : public Test { protected: void SetUp() override { - testdata_path_.Set(FilePath( - TempDir() + GetCurrentExecutableName().string() + - "_directory_creation" GTEST_PATH_SEP_ "test" GTEST_PATH_SEP_)); + testdata_path_.Set( + FilePath(TempDir() + GetCurrentExecutableName().string() + + "_directory_creation" GTEST_PATH_SEP_ "test" GTEST_PATH_SEP_)); testdata_file_.Set(testdata_path_.RemoveTrailingPathSeparator()); - unique_file0_.Set(FilePath::MakeFileName(testdata_path_, FilePath("unique"), - 0, "txt")); - unique_file1_.Set(FilePath::MakeFileName(testdata_path_, FilePath("unique"), - 1, "txt")); + unique_file0_.Set( + FilePath::MakeFileName(testdata_path_, FilePath("unique"), 0, "txt")); + unique_file1_.Set( + FilePath::MakeFileName(testdata_path_, FilePath("unique"), 1, "txt")); remove(testdata_file_.c_str()); remove(unique_file0_.c_str()); @@ -512,8 +512,8 @@ class DirectoryCreationTest : public Test { // a directory named 'test' from a file named 'test'. Example names: FilePath testdata_path_; // "/tmp/directory_creation/test/" FilePath testdata_file_; // "/tmp/directory_creation/test" - FilePath unique_file0_; // "/tmp/directory_creation/test/unique.txt" - FilePath unique_file1_; // "/tmp/directory_creation/test/unique_1.txt" + FilePath unique_file0_; // "/tmp/directory_creation/test/unique.txt" + FilePath unique_file1_; // "/tmp/directory_creation/test/unique_1.txt" }; TEST_F(DirectoryCreationTest, CreateDirectoriesRecursively) { @@ -530,8 +530,8 @@ TEST_F(DirectoryCreationTest, CreateDirectoriesForAlreadyExistingPath) { } TEST_F(DirectoryCreationTest, CreateDirectoriesAndUniqueFilename) { - FilePath file_path(FilePath::GenerateUniqueFileName(testdata_path_, - FilePath("unique"), "txt")); + FilePath file_path(FilePath::GenerateUniqueFileName( + testdata_path_, FilePath("unique"), "txt")); EXPECT_EQ(unique_file0_.string(), file_path.string()); EXPECT_FALSE(file_path.FileOrDirectoryExists()); // file not there @@ -540,8 +540,8 @@ TEST_F(DirectoryCreationTest, CreateDirectoriesAndUniqueFilename) { CreateTextFile(file_path.c_str()); EXPECT_TRUE(file_path.FileOrDirectoryExists()); - FilePath file_path2(FilePath::GenerateUniqueFileName(testdata_path_, - FilePath("unique"), "txt")); + FilePath file_path2(FilePath::GenerateUniqueFileName( + testdata_path_, FilePath("unique"), "txt")); EXPECT_EQ(unique_file1_.string(), file_path2.string()); EXPECT_FALSE(file_path2.FileOrDirectoryExists()); // file not there CreateTextFile(file_path2.c_str()); @@ -614,14 +614,16 @@ TEST(FilePathTest, IsAbsolutePath) { EXPECT_FALSE(FilePath("is" GTEST_PATH_SEP_ "relative").IsAbsolutePath()); EXPECT_FALSE(FilePath("").IsAbsolutePath()); #if GTEST_OS_WINDOWS - EXPECT_TRUE(FilePath("c:\\" GTEST_PATH_SEP_ "is_not" - GTEST_PATH_SEP_ "relative").IsAbsolutePath()); + EXPECT_TRUE( + FilePath("c:\\" GTEST_PATH_SEP_ "is_not" GTEST_PATH_SEP_ "relative") + .IsAbsolutePath()); EXPECT_FALSE(FilePath("c:foo" GTEST_PATH_SEP_ "bar").IsAbsolutePath()); - EXPECT_TRUE(FilePath("c:/" GTEST_PATH_SEP_ "is_not" - GTEST_PATH_SEP_ "relative").IsAbsolutePath()); + EXPECT_TRUE( + FilePath("c:/" GTEST_PATH_SEP_ "is_not" GTEST_PATH_SEP_ "relative") + .IsAbsolutePath()); #else EXPECT_TRUE(FilePath(GTEST_PATH_SEP_ "is_not" GTEST_PATH_SEP_ "relative") - .IsAbsolutePath()); + .IsAbsolutePath()); #endif // GTEST_OS_WINDOWS } diff --git a/googletest/test/googletest-filter-unittest_.cc b/googletest/test/googletest-filter-unittest_.cc index d30ec9c..bc7aa59 100644 --- a/googletest/test/googletest-filter-unittest_.cc +++ b/googletest/test/googletest-filter-unittest_.cc @@ -27,7 +27,6 @@ // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - // Unit test for Google Test test filters. // // A user can specify which test(s) in a Google Test program to run via @@ -43,87 +42,57 @@ namespace { // Test case FooTest. -class FooTest : public testing::Test { -}; +class FooTest : public testing::Test {}; -TEST_F(FooTest, Abc) { -} +TEST_F(FooTest, Abc) {} -TEST_F(FooTest, Xyz) { - FAIL() << "Expected failure."; -} +TEST_F(FooTest, Xyz) { FAIL() << "Expected failure."; } // Test case BarTest. -TEST(BarTest, TestOne) { -} +TEST(BarTest, TestOne) {} -TEST(BarTest, TestTwo) { -} +TEST(BarTest, TestTwo) {} -TEST(BarTest, TestThree) { -} +TEST(BarTest, TestThree) {} -TEST(BarTest, DISABLED_TestFour) { - FAIL() << "Expected failure."; -} +TEST(BarTest, DISABLED_TestFour) { FAIL() << "Expected failure."; } -TEST(BarTest, DISABLED_TestFive) { - FAIL() << "Expected failure."; -} +TEST(BarTest, DISABLED_TestFive) { FAIL() << "Expected failure."; } // Test case BazTest. -TEST(BazTest, TestOne) { - FAIL() << "Expected failure."; -} +TEST(BazTest, TestOne) { FAIL() << "Expected failure."; } -TEST(BazTest, TestA) { -} +TEST(BazTest, TestA) {} -TEST(BazTest, TestB) { -} +TEST(BazTest, TestB) {} -TEST(BazTest, DISABLED_TestC) { - FAIL() << "Expected failure."; -} +TEST(BazTest, DISABLED_TestC) { FAIL() << "Expected failure."; } // Test case HasDeathTest -TEST(HasDeathTest, Test1) { - EXPECT_DEATH_IF_SUPPORTED(exit(1), ".*"); -} +TEST(HasDeathTest, Test1) { EXPECT_DEATH_IF_SUPPORTED(exit(1), ".*"); } // We need at least two death tests to make sure that the all death tests // aren't on the first shard. -TEST(HasDeathTest, Test2) { - EXPECT_DEATH_IF_SUPPORTED(exit(1), ".*"); -} +TEST(HasDeathTest, Test2) { EXPECT_DEATH_IF_SUPPORTED(exit(1), ".*"); } // Test case FoobarTest -TEST(DISABLED_FoobarTest, Test1) { - FAIL() << "Expected failure."; -} +TEST(DISABLED_FoobarTest, Test1) { FAIL() << "Expected failure."; } -TEST(DISABLED_FoobarTest, DISABLED_Test2) { - FAIL() << "Expected failure."; -} +TEST(DISABLED_FoobarTest, DISABLED_Test2) { FAIL() << "Expected failure."; } // Test case FoobarbazTest -TEST(DISABLED_FoobarbazTest, TestA) { - FAIL() << "Expected failure."; -} +TEST(DISABLED_FoobarbazTest, TestA) { FAIL() << "Expected failure."; } -class ParamTest : public testing::TestWithParam<int> { -}; +class ParamTest : public testing::TestWithParam<int> {}; -TEST_P(ParamTest, TestX) { -} +TEST_P(ParamTest, TestX) {} -TEST_P(ParamTest, TestY) { -} +TEST_P(ParamTest, TestY) {} INSTANTIATE_TEST_SUITE_P(SeqP, ParamTest, testing::Values(1, 2)); INSTANTIATE_TEST_SUITE_P(SeqQ, ParamTest, testing::Values(5, 6)); diff --git a/googletest/test/googletest-json-outfiles-test.py b/googletest/test/googletest-json-outfiles-test.py index db9716c..179283b 100644 --- a/googletest/test/googletest-json-outfiles-test.py +++ b/googletest/test/googletest-json-outfiles-test.py @@ -71,6 +71,8 @@ EXPECTED_1 = { u'*', u'testsuite': [{ u'name': u'TestSomeProperties', + u'file': u'gtest_xml_outfile1_test_.cc', + u'line': 41, u'status': u'RUN', u'result': u'COMPLETED', u'time': u'*', @@ -115,6 +117,8 @@ EXPECTED_2 = { u'*', u'testsuite': [{ u'name': u'TestSomeProperties', + u'file': u'gtest_xml_outfile2_test_.cc', + u'line': 41, u'status': u'RUN', u'result': u'COMPLETED', u'timestamp': u'*', diff --git a/googletest/test/googletest-json-output-unittest.py b/googletest/test/googletest-json-output-unittest.py index cb31965..e0fbe46 100644 --- a/googletest/test/googletest-json-output-unittest.py +++ b/googletest/test/googletest-json-output-unittest.py @@ -90,6 +90,8 @@ EXPECTED_NON_EMPTY = { u'*', u'testsuite': [{ u'name': u'Succeeds', + u'file': u'gtest_xml_output_unittest_.cc', + u'line': 51, u'status': u'RUN', u'result': u'COMPLETED', u'time': u'*', @@ -114,6 +116,10 @@ EXPECTED_NON_EMPTY = { u'testsuite': [{ u'name': u'Fails', + u'file': + u'gtest_xml_output_unittest_.cc', + u'line': + 59, u'status': u'RUN', u'result': @@ -148,6 +154,8 @@ EXPECTED_NON_EMPTY = { u'*', u'testsuite': [{ u'name': u'DISABLED_test_not_run', + u'file': u'gtest_xml_output_unittest_.cc', + u'line': 66, u'status': u'NOTRUN', u'result': u'SUPPRESSED', u'time': u'*', @@ -171,6 +179,8 @@ EXPECTED_NON_EMPTY = { u'*', u'testsuite': [{ u'name': u'Skipped', + u'file': 'gtest_xml_output_unittest_.cc', + u'line': 73, u'status': u'RUN', u'result': u'SKIPPED', u'time': u'*', @@ -178,6 +188,8 @@ EXPECTED_NON_EMPTY = { u'classname': u'SkippedTest' }, { u'name': u'SkippedWithMessage', + u'file': 'gtest_xml_output_unittest_.cc', + u'line': 77, u'status': u'RUN', u'result': u'SKIPPED', u'time': u'*', @@ -186,6 +198,10 @@ EXPECTED_NON_EMPTY = { }, { u'name': u'SkippedAfterFailure', + u'file': + 'gtest_xml_output_unittest_.cc', + u'line': + 81, u'status': u'RUN', u'result': @@ -220,6 +236,8 @@ EXPECTED_NON_EMPTY = { u'*', u'testsuite': [{ u'name': u'Succeeds', + u'file': 'gtest_xml_output_unittest_.cc', + u'line': 86, u'status': u'RUN', u'result': u'COMPLETED', u'time': u'*', @@ -228,6 +246,10 @@ EXPECTED_NON_EMPTY = { }, { u'name': u'Fails', + u'file': + u'gtest_xml_output_unittest_.cc', + u'line': + 91, u'status': u'RUN', u'result': @@ -251,6 +273,8 @@ EXPECTED_NON_EMPTY = { }] }, { u'name': u'DISABLED_test', + u'file': u'gtest_xml_output_unittest_.cc', + u'line': 96, u'status': u'NOTRUN', u'result': u'SUPPRESSED', u'time': u'*', @@ -275,6 +299,10 @@ EXPECTED_NON_EMPTY = { u'testsuite': [{ u'name': u'OutputsCData', + u'file': + u'gtest_xml_output_unittest_.cc', + u'line': + 100, u'status': u'RUN', u'result': @@ -311,6 +339,10 @@ EXPECTED_NON_EMPTY = { u'testsuite': [{ u'name': u'InvalidCharactersInMessage', + u'file': + u'gtest_xml_output_unittest_.cc', + u'line': + 107, u'status': u'RUN', u'result': @@ -349,6 +381,8 @@ EXPECTED_NON_EMPTY = { u'aye', u'testsuite': [{ u'name': u'OneProperty', + u'file': u'gtest_xml_output_unittest_.cc', + u'line': 119, u'status': u'RUN', u'result': u'COMPLETED', u'time': u'*', @@ -357,6 +391,8 @@ EXPECTED_NON_EMPTY = { u'key_1': u'1' }, { u'name': u'IntValuedProperty', + u'file': u'gtest_xml_output_unittest_.cc', + u'line': 123, u'status': u'RUN', u'result': u'COMPLETED', u'time': u'*', @@ -365,6 +401,8 @@ EXPECTED_NON_EMPTY = { u'key_int': u'1' }, { u'name': u'ThreeProperties', + u'file': u'gtest_xml_output_unittest_.cc', + u'line': 127, u'status': u'RUN', u'result': u'COMPLETED', u'time': u'*', @@ -375,6 +413,8 @@ EXPECTED_NON_EMPTY = { u'key_3': u'3' }, { u'name': u'TwoValuesForOneKeyUsesLastValue', + u'file': u'gtest_xml_output_unittest_.cc', + u'line': 133, u'status': u'RUN', u'result': u'COMPLETED', u'time': u'*', @@ -399,6 +439,8 @@ EXPECTED_NON_EMPTY = { u'*', u'testsuite': [{ u'name': u'RecordProperty', + u'file': u'gtest_xml_output_unittest_.cc', + u'line': 138, u'status': u'RUN', u'result': u'COMPLETED', u'time': u'*', @@ -407,6 +449,8 @@ EXPECTED_NON_EMPTY = { u'key': u'1' }, { u'name': u'ExternalUtilityThatCallsRecordIntValuedProperty', + u'file': u'gtest_xml_output_unittest_.cc', + u'line': 151, u'status': u'RUN', u'result': u'COMPLETED', u'time': u'*', @@ -415,6 +459,8 @@ EXPECTED_NON_EMPTY = { u'key_for_utility_int': u'1' }, { u'name': u'ExternalUtilityThatCallsRecordStringValuedProperty', + u'file': u'gtest_xml_output_unittest_.cc', + u'line': 155, u'status': u'RUN', u'result': u'COMPLETED', u'time': u'*', @@ -440,6 +486,8 @@ EXPECTED_NON_EMPTY = { u'testsuite': [{ u'name': u'HasTypeParamAttribute', u'type_param': u'int', + u'file': u'gtest_xml_output_unittest_.cc', + u'line': 171, u'status': u'RUN', u'result': u'COMPLETED', u'time': u'*', @@ -464,6 +512,8 @@ EXPECTED_NON_EMPTY = { u'testsuite': [{ u'name': u'HasTypeParamAttribute', u'type_param': u'long', + u'file': u'gtest_xml_output_unittest_.cc', + u'line': 171, u'status': u'RUN', u'result': u'COMPLETED', u'time': u'*', @@ -488,6 +538,8 @@ EXPECTED_NON_EMPTY = { u'testsuite': [{ u'name': u'HasTypeParamAttribute', u'type_param': u'int', + u'file': u'gtest_xml_output_unittest_.cc', + u'line': 178, u'status': u'RUN', u'result': u'COMPLETED', u'time': u'*', @@ -512,6 +564,8 @@ EXPECTED_NON_EMPTY = { u'testsuite': [{ u'name': u'HasTypeParamAttribute', u'type_param': u'long', + u'file': u'gtest_xml_output_unittest_.cc', + u'line': 178, u'status': u'RUN', u'result': u'COMPLETED', u'time': u'*', @@ -536,6 +590,8 @@ EXPECTED_NON_EMPTY = { u'testsuite': [{ u'name': u'HasValueParamAttribute/0', u'value_param': u'33', + u'file': u'gtest_xml_output_unittest_.cc', + u'line': 162, u'status': u'RUN', u'result': u'COMPLETED', u'time': u'*', @@ -544,6 +600,8 @@ EXPECTED_NON_EMPTY = { }, { u'name': u'HasValueParamAttribute/1', u'value_param': u'42', + u'file': u'gtest_xml_output_unittest_.cc', + u'line': 162, u'status': u'RUN', u'result': u'COMPLETED', u'time': u'*', @@ -552,6 +610,8 @@ EXPECTED_NON_EMPTY = { }, { u'name': u'AnotherTestThatHasValueParamAttribute/0', u'value_param': u'33', + u'file': u'gtest_xml_output_unittest_.cc', + u'line': 163, u'status': u'RUN', u'result': u'COMPLETED', u'time': u'*', @@ -560,6 +620,8 @@ EXPECTED_NON_EMPTY = { }, { u'name': u'AnotherTestThatHasValueParamAttribute/1', u'value_param': u'42', + u'file': u'gtest_xml_output_unittest_.cc', + u'line': 163, u'status': u'RUN', u'result': u'COMPLETED', u'time': u'*', @@ -603,6 +665,8 @@ EXPECTED_FILTERED = { u'*', u'testsuite': [{ u'name': u'Succeeds', + u'file': u'gtest_xml_output_unittest_.cc', + u'line': 51, u'status': u'RUN', u'result': u'COMPLETED', u'time': u'*', diff --git a/googletest/test/googletest-list-tests-unittest_.cc b/googletest/test/googletest-list-tests-unittest_.cc index 493c6f0..5577e89 100644 --- a/googletest/test/googletest-list-tests-unittest_.cc +++ b/googletest/test/googletest-list-tests-unittest_.cc @@ -27,7 +27,6 @@ // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - // Unit test for Google Test's --gtest_list_tests flag. // // A user can ask Google Test to list all tests that will run @@ -40,38 +39,27 @@ #include "gtest/gtest.h" // Several different test cases and tests that will be listed. -TEST(Foo, Bar1) { -} +TEST(Foo, Bar1) {} -TEST(Foo, Bar2) { -} +TEST(Foo, Bar2) {} -TEST(Foo, DISABLED_Bar3) { -} +TEST(Foo, DISABLED_Bar3) {} -TEST(Abc, Xyz) { -} +TEST(Abc, Xyz) {} -TEST(Abc, Def) { -} +TEST(Abc, Def) {} -TEST(FooBar, Baz) { -} +TEST(FooBar, Baz) {} -class FooTest : public testing::Test { -}; +class FooTest : public testing::Test {}; -TEST_F(FooTest, Test1) { -} +TEST_F(FooTest, Test1) {} -TEST_F(FooTest, DISABLED_Test2) { -} +TEST_F(FooTest, DISABLED_Test2) {} -TEST_F(FooTest, Test3) { -} +TEST_F(FooTest, Test3) {} -TEST(FooDeathTest, Test1) { -} +TEST(FooDeathTest, Test1) {} // A group of value-parameterized tests. @@ -86,70 +74,66 @@ class MyType { }; // Teaches Google Test how to print a MyType. -void PrintTo(const MyType& x, std::ostream* os) { - *os << x.value(); -} +void PrintTo(const MyType& x, std::ostream* os) { *os << x.value(); } -class ValueParamTest : public testing::TestWithParam<MyType> { -}; +class ValueParamTest : public testing::TestWithParam<MyType> {}; -TEST_P(ValueParamTest, TestA) { -} +TEST_P(ValueParamTest, TestA) {} -TEST_P(ValueParamTest, TestB) { -} +TEST_P(ValueParamTest, TestB) {} INSTANTIATE_TEST_SUITE_P( MyInstantiation, ValueParamTest, - testing::Values(MyType("one line"), - MyType("two\nlines"), - MyType("a very\nloooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong line"))); // NOLINT + testing::Values( + MyType("one line"), MyType("two\nlines"), + MyType("a " + "very\nloooooooooooooooooooooooooooooooooooooooooooooooooooooooo" + "ooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo" + "ooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo" + "ooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo" + "ooooong line"))); // NOLINT // A group of typed tests. // A deliberately long type name for testing the line-truncating // behavior when printing a type parameter. -class VeryLoooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooogName { // NOLINT +class + VeryLoooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooogName { // NOLINT }; template <typename T> -class TypedTest : public testing::Test { -}; +class TypedTest : public testing::Test {}; template <typename T, int kSize> -class MyArray { -}; +class MyArray {}; -typedef testing::Types<VeryLoooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooogName, // NOLINT - int*, MyArray<bool, 42> > MyTypes; +typedef testing::Types< + VeryLoooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooogName, // NOLINT + int*, MyArray<bool, 42> > + MyTypes; TYPED_TEST_SUITE(TypedTest, MyTypes); -TYPED_TEST(TypedTest, TestA) { -} +TYPED_TEST(TypedTest, TestA) {} -TYPED_TEST(TypedTest, TestB) { -} +TYPED_TEST(TypedTest, TestB) {} // A group of type-parameterized tests. template <typename T> -class TypeParamTest : public testing::Test { -}; +class TypeParamTest : public testing::Test {}; TYPED_TEST_SUITE_P(TypeParamTest); -TYPED_TEST_P(TypeParamTest, TestA) { -} +TYPED_TEST_P(TypeParamTest, TestA) {} -TYPED_TEST_P(TypeParamTest, TestB) { -} +TYPED_TEST_P(TypeParamTest, TestB) {} REGISTER_TYPED_TEST_SUITE_P(TypeParamTest, TestA, TestB); INSTANTIATE_TYPED_TEST_SUITE_P(My, TypeParamTest, MyTypes); -int main(int argc, char **argv) { +int main(int argc, char** argv) { ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); diff --git a/googletest/test/googletest-listener-test.cc b/googletest/test/googletest-listener-test.cc index e7f9b13..89d01b3 100644 --- a/googletest/test/googletest-listener-test.cc +++ b/googletest/test/googletest-listener-test.cc @@ -41,10 +41,10 @@ using ::testing::AddGlobalTestEnvironment; using ::testing::Environment; using ::testing::InitGoogleTest; using ::testing::Test; -using ::testing::TestSuite; using ::testing::TestEventListener; using ::testing::TestInfo; using ::testing::TestPartResult; +using ::testing::TestSuite; using ::testing::UnitTest; // Used by tests to register their events. @@ -65,8 +65,8 @@ class EventRecordingListener : public TestEventListener { void OnTestIterationStart(const UnitTest& /*unit_test*/, int iteration) override { Message message; - message << GetFullMethodName("OnTestIterationStart") - << "(" << iteration << ")"; + message << GetFullMethodName("OnTestIterationStart") << "(" << iteration + << ")"; g_events->push_back(message.GetString()); } @@ -112,8 +112,8 @@ class EventRecordingListener : public TestEventListener { void OnTestIterationEnd(const UnitTest& /*unit_test*/, int iteration) override { Message message; - message << GetFullMethodName("OnTestIterationEnd") - << "(" << iteration << ")"; + message << GetFullMethodName("OnTestIterationEnd") << "(" << iteration + << ")"; g_events->push_back(message.GetString()); } @@ -122,9 +122,7 @@ class EventRecordingListener : public TestEventListener { } private: - std::string GetFullMethodName(const char* name) { - return name_ + "." + name; - } + std::string GetFullMethodName(const char* name) { return name_ + "." + name; } std::string name_; }; @@ -252,22 +250,21 @@ void VerifyResults(const std::vector<std::string>& data, EXPECT_EQ(expected_data_size, actual_size); // Compares the common prefix. - const size_t shorter_size = expected_data_size <= actual_size ? - expected_data_size : actual_size; + const size_t shorter_size = + expected_data_size <= actual_size ? expected_data_size : actual_size; size_t i = 0; for (; i < shorter_size; ++i) { - ASSERT_STREQ(expected_data[i], data[i].c_str()) - << "at position " << i; + ASSERT_STREQ(expected_data[i], data[i].c_str()) << "at position " << i; } // Prints extra elements in the actual data. for (; i < actual_size; ++i) { - printf(" Actual event #%lu: %s\n", - static_cast<unsigned long>(i), data[i].c_str()); + printf(" Actual event #%lu: %s\n", static_cast<unsigned long>(i), + data[i].c_str()); } } -int main(int argc, char **argv) { +int main(int argc, char** argv) { std::vector<std::string> events; g_events = &events; InitGoogleTest(&argc, argv); @@ -506,14 +503,12 @@ int main(int argc, char **argv) { "1st.OnTestProgramEnd"}; #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_ - VerifyResults(events, - expected_events, - sizeof(expected_events)/sizeof(expected_events[0])); + VerifyResults(events, expected_events, + sizeof(expected_events) / sizeof(expected_events[0])); // We need to check manually for ad hoc test failures that happen after // RUN_ALL_TESTS finishes. - if (UnitTest::GetInstance()->Failed()) - ret_val = 1; + if (UnitTest::GetInstance()->Failed()) ret_val = 1; return ret_val; } diff --git a/googletest/test/googletest-message-test.cc b/googletest/test/googletest-message-test.cc index 962d519..252a861 100644 --- a/googletest/test/googletest-message-test.cc +++ b/googletest/test/googletest-message-test.cc @@ -31,7 +31,6 @@ // Tests for the Message class. #include "gtest/gtest-message.h" - #include "gtest/gtest.h" namespace { @@ -69,8 +68,9 @@ TEST(MessageTest, StreamsFloat) { // Tests streaming a double. TEST(MessageTest, StreamsDouble) { - const std::string s = (Message() << 1260570880.4555497 << " " - << 1260572265.1954534).GetString(); + const std::string s = + (Message() << 1260570880.4555497 << " " << 1260572265.1954534) + .GetString(); // Both numbers should be printed with enough precision. EXPECT_PRED_FORMAT2(testing::IsSubstring, "1260570880.45", s.c_str()); EXPECT_PRED_FORMAT2(testing::IsSubstring, " 1260572265.19", s.c_str()); @@ -108,8 +108,7 @@ TEST(MessageTest, StreamsString) { // Tests that we can output strings containing embedded NULs. TEST(MessageTest, StreamsStringWithEmbeddedNUL) { - const char char_array_with_nul[] = - "Here's a NUL\0 and some more string"; + const char char_array_with_nul[] = "Here's a NUL\0 and some more string"; const ::std::string string_with_nul(char_array_with_nul, sizeof(char_array_with_nul) - 1); EXPECT_EQ("Here's a NUL\\0 and some more string", @@ -129,10 +128,11 @@ TEST(MessageTest, StreamsInt) { // Tests that basic IO manipulators (endl, ends, and flush) can be // streamed to Message. TEST(MessageTest, StreamsBasicIoManip) { - EXPECT_EQ("Line 1.\nA NUL char \\0 in line 2.", - (Message() << "Line 1." << std::endl - << "A NUL char " << std::ends << std::flush - << " in line 2.").GetString()); + EXPECT_EQ( + "Line 1.\nA NUL char \\0 in line 2.", + (Message() << "Line 1." << std::endl + << "A NUL char " << std::ends << std::flush << " in line 2.") + .GetString()); } // Tests Message::GetString() diff --git a/googletest/test/googletest-options-test.cc b/googletest/test/googletest-options-test.cc index cd386ff..1265c22 100644 --- a/googletest/test/googletest-options-test.cc +++ b/googletest/test/googletest-options-test.cc @@ -39,9 +39,9 @@ #include "gtest/gtest.h" #if GTEST_OS_WINDOWS_MOBILE -# include <windows.h> +#include <windows.h> #elif GTEST_OS_WINDOWS -# include <direct.h> +#include <direct.h> #elif GTEST_OS_OS2 // For strcasecmp on OS/2 #include <strings.h> @@ -85,9 +85,9 @@ TEST(XmlOutputTest, GetOutputFileSingleFile) { TEST(XmlOutputTest, GetOutputFileFromDirectoryPath) { GTEST_FLAG_SET(output, "xml:path" GTEST_PATH_SEP_); const std::string expected_output_file = - GetAbsolutePathOf( - FilePath(std::string("path") + GTEST_PATH_SEP_ + - GetCurrentExecutableName().string() + ".xml")).string(); + GetAbsolutePathOf(FilePath(std::string("path") + GTEST_PATH_SEP_ + + GetCurrentExecutableName().string() + ".xml")) + .string(); const std::string& output_file = UnitTestOptions::GetAbsolutePathToOutputFile(); #if GTEST_OS_WINDOWS @@ -115,13 +115,10 @@ TEST(OutputFileHelpersTest, GetCurrentExecutableName) { const bool success = exe_str == "app"; #else const bool success = - exe_str == "googletest-options-test" || - exe_str == "gtest_all_test" || - exe_str == "lt-gtest_all_test" || - exe_str == "gtest_dll_test"; + exe_str == "googletest-options-test" || exe_str == "gtest_all_test" || + exe_str == "lt-gtest_all_test" || exe_str == "gtest_dll_test"; #endif // GTEST_OS_WINDOWS - if (!success) - FAIL() << "GetCurrentExecutableName() returns " << exe_str; + if (!success) FAIL() << "GetCurrentExecutableName() returns " << exe_str; } #if !GTEST_OS_FUCHSIA @@ -145,23 +142,26 @@ class XmlOutputChangeDirTest : public Test { TEST_F(XmlOutputChangeDirTest, PreserveOriginalWorkingDirWithDefault) { GTEST_FLAG_SET(output, ""); - EXPECT_EQ(FilePath::ConcatPaths(original_working_dir_, - FilePath("test_detail.xml")).string(), - UnitTestOptions::GetAbsolutePathToOutputFile()); + EXPECT_EQ( + FilePath::ConcatPaths(original_working_dir_, FilePath("test_detail.xml")) + .string(), + UnitTestOptions::GetAbsolutePathToOutputFile()); } TEST_F(XmlOutputChangeDirTest, PreserveOriginalWorkingDirWithDefaultXML) { GTEST_FLAG_SET(output, "xml"); - EXPECT_EQ(FilePath::ConcatPaths(original_working_dir_, - FilePath("test_detail.xml")).string(), - UnitTestOptions::GetAbsolutePathToOutputFile()); + EXPECT_EQ( + FilePath::ConcatPaths(original_working_dir_, FilePath("test_detail.xml")) + .string(), + UnitTestOptions::GetAbsolutePathToOutputFile()); } TEST_F(XmlOutputChangeDirTest, PreserveOriginalWorkingDirWithRelativeFile) { GTEST_FLAG_SET(output, "xml:filename.abc"); - EXPECT_EQ(FilePath::ConcatPaths(original_working_dir_, - FilePath("filename.abc")).string(), - UnitTestOptions::GetAbsolutePathToOutputFile()); + EXPECT_EQ( + FilePath::ConcatPaths(original_working_dir_, FilePath("filename.abc")) + .string(), + UnitTestOptions::GetAbsolutePathToOutputFile()); } TEST_F(XmlOutputChangeDirTest, PreserveOriginalWorkingDirWithRelativePath) { @@ -170,7 +170,8 @@ TEST_F(XmlOutputChangeDirTest, PreserveOriginalWorkingDirWithRelativePath) { FilePath::ConcatPaths( original_working_dir_, FilePath(std::string("path") + GTEST_PATH_SEP_ + - GetCurrentExecutableName().string() + ".xml")).string(); + GetCurrentExecutableName().string() + ".xml")) + .string(); const std::string& output_file = UnitTestOptions::GetAbsolutePathToOutputFile(); #if GTEST_OS_WINDOWS diff --git a/googletest/test/googletest-output-test_.cc b/googletest/test/googletest-output-test_.cc index 04fbfb3..c2f96d9 100644 --- a/googletest/test/googletest-output-test_.cc +++ b/googletest/test/googletest-output-test_.cc @@ -33,12 +33,12 @@ // desired messages. Therefore, most tests in this file are MEANT TO // FAIL. +#include <stdlib.h> + #include "gtest/gtest-spi.h" #include "gtest/gtest.h" #include "src/gtest-internal-inl.h" -#include <stdlib.h> - #if _MSC_VER GTEST_DISABLE_MSC_WARNINGS_PUSH_(4127 /* conditional expression is constant */) #endif // _MSC_VER @@ -56,9 +56,7 @@ namespace posix = ::testing::internal::posix; // Tests catching fatal failures. // A subroutine used by the following test. -void TestEq1(int x) { - ASSERT_EQ(1, x); -} +void TestEq1(int x) { ASSERT_EQ(1, x); } // This function calls a test subroutine, catches the fatal failure it // generates, and then returns early. @@ -76,24 +74,19 @@ void TryTestSubroutine() { FAIL() << "This should never be reached."; } -TEST(PassingTest, PassingTest1) { -} +TEST(PassingTest, PassingTest1) {} -TEST(PassingTest, PassingTest2) { -} +TEST(PassingTest, PassingTest2) {} // Tests that parameters of failing parameterized tests are printed in the // failing test summary. class FailingParamTest : public testing::TestWithParam<int> {}; -TEST_P(FailingParamTest, Fails) { - EXPECT_EQ(1, GetParam()); -} +TEST_P(FailingParamTest, Fails) { EXPECT_EQ(1, GetParam()); } // This generates a test which will fail. Google Test is expected to print // its parameter when it outputs the list of all failed tests. -INSTANTIATE_TEST_SUITE_P(PrintingFailingParams, - FailingParamTest, +INSTANTIATE_TEST_SUITE_P(PrintingFailingParams, FailingParamTest, testing::Values(2)); // Tests that an empty value for the test suite basename yields just @@ -146,18 +139,16 @@ TEST(FatalFailureTest, FatalFailureInNestedSubroutine) { // Tests HasFatalFailure() after a failed EXPECT check. TEST(FatalFailureTest, NonfatalFailureInSubroutine) { printf("(expecting a failure on false)\n"); - EXPECT_TRUE(false); // Generates a nonfatal failure + EXPECT_TRUE(false); // Generates a nonfatal failure ASSERT_FALSE(HasFatalFailure()); // This should succeed. } // Tests interleaving user logging and Google Test assertions. TEST(LoggingTest, InterleavingLoggingAndAssertions) { - static const int a[4] = { - 3, 9, 2, 6 - }; + static const int a[4] = {3, 9, 2, 6}; printf("(expecting 2 failures on (3) >= (a[i]))\n"); - for (int i = 0; i < static_cast<int>(sizeof(a)/sizeof(*a)); i++) { + for (int i = 0; i < static_cast<int>(sizeof(a) / sizeof(*a)); i++) { printf("i == %d\n", i); EXPECT_GE(3, a[i]); } @@ -297,16 +288,14 @@ struct CheckPoints { static void ThreadWithScopedTrace(CheckPoints* check_points) { { SCOPED_TRACE("Trace B"); - ADD_FAILURE() - << "Expected failure #1 (in thread B, only trace B alive)."; + ADD_FAILURE() << "Expected failure #1 (in thread B, only trace B alive)."; check_points->n1.Notify(); check_points->n2.WaitForNotification(); ADD_FAILURE() << "Expected failure #3 (in thread B, trace A & B both alive)."; } // Trace B dies here. - ADD_FAILURE() - << "Expected failure #4 (in thread B, only trace A alive)."; + ADD_FAILURE() << "Expected failure #4 (in thread B, only trace A alive)."; check_points->n3.Notify(); } @@ -325,11 +314,9 @@ TEST(SCOPED_TRACETest, WorksConcurrently) { check_points.n2.Notify(); check_points.n3.WaitForNotification(); - ADD_FAILURE() - << "Expected failure #5 (in thread A, only trace A alive)."; + ADD_FAILURE() << "Expected failure #5 (in thread A, only trace A alive)."; } // Trace A dies here. - ADD_FAILURE() - << "Expected failure #6 (in thread A, no trace alive)."; + ADD_FAILURE() << "Expected failure #6 (in thread A, no trace alive)."; thread.Join(); } #endif // GTEST_IS_THREADSAFE @@ -412,9 +399,7 @@ class FatalFailureInFixtureConstructorTest : public testing::Test { } private: - void Init() { - FAIL() << "Expected failure #1, in the test fixture c'tor."; - } + void Init() { FAIL() << "Expected failure #1, in the test fixture c'tor."; } }; TEST_F(FatalFailureInFixtureConstructorTest, FailureInConstructor) { @@ -436,9 +421,7 @@ class NonFatalFailureInSetUpTest : public testing::Test { void TearDown() override { FAIL() << "Expected failure #3, in TearDown()."; } private: - void Deinit() { - FAIL() << "Expected failure #4, in the test fixture d'tor."; - } + void Deinit() { FAIL() << "Expected failure #4, in the test fixture d'tor."; } }; TEST_F(NonFatalFailureInSetUpTest, FailureInSetUp) { @@ -458,9 +441,7 @@ class FatalFailureInSetUpTest : public testing::Test { void TearDown() override { FAIL() << "Expected failure #2, in TearDown()."; } private: - void Deinit() { - FAIL() << "Expected failure #3, in the test fixture d'tor."; - } + void Deinit() { FAIL() << "Expected failure #3, in the test fixture d'tor."; } }; TEST_F(FatalFailureInSetUpTest, FailureInSetUp) { @@ -488,14 +469,12 @@ TEST(GtestFailAtTest, MessageContainsSpecifiedFileAndLineNumber) { namespace foo { -class MixedUpTestSuiteTest : public testing::Test { -}; +class MixedUpTestSuiteTest : public testing::Test {}; TEST_F(MixedUpTestSuiteTest, FirstTestFromNamespaceFoo) {} TEST_F(MixedUpTestSuiteTest, SecondTestFromNamespaceFoo) {} -class MixedUpTestSuiteWithSameTestNameTest : public testing::Test { -}; +class MixedUpTestSuiteWithSameTestNameTest : public testing::Test {}; TEST_F(MixedUpTestSuiteWithSameTestNameTest, TheSecondTestWithThisNameShouldFail) {} @@ -504,16 +483,14 @@ TEST_F(MixedUpTestSuiteWithSameTestNameTest, namespace bar { -class MixedUpTestSuiteTest : public testing::Test { -}; +class MixedUpTestSuiteTest : public testing::Test {}; // The following two tests are expected to fail. We rely on the // golden file to check that Google Test generates the right error message. TEST_F(MixedUpTestSuiteTest, ThisShouldFail) {} TEST_F(MixedUpTestSuiteTest, ThisShouldFailToo) {} -class MixedUpTestSuiteWithSameTestNameTest : public testing::Test { -}; +class MixedUpTestSuiteWithSameTestNameTest : public testing::Test {}; // Expected to fail. We rely on the golden file to check that Google Test // generates the right error message. @@ -527,8 +504,7 @@ TEST_F(MixedUpTestSuiteWithSameTestNameTest, // test case checks the scenario where TEST_F appears before TEST, and // the second one checks where TEST appears before TEST_F. -class TEST_F_before_TEST_in_same_test_case : public testing::Test { -}; +class TEST_F_before_TEST_in_same_test_case : public testing::Test {}; TEST_F(TEST_F_before_TEST_in_same_test_case, DefinedUsingTEST_F) {} @@ -536,15 +512,13 @@ TEST_F(TEST_F_before_TEST_in_same_test_case, DefinedUsingTEST_F) {} // generates the right error message. TEST(TEST_F_before_TEST_in_same_test_case, DefinedUsingTESTAndShouldFail) {} -class TEST_before_TEST_F_in_same_test_case : public testing::Test { -}; +class TEST_before_TEST_F_in_same_test_case : public testing::Test {}; TEST(TEST_before_TEST_F_in_same_test_case, DefinedUsingTEST) {} // Expected to fail. We rely on the golden file to check that Google Test // generates the right error message. -TEST_F(TEST_before_TEST_F_in_same_test_case, DefinedUsingTEST_FAndShouldFail) { -} +TEST_F(TEST_before_TEST_F_in_same_test_case, DefinedUsingTEST_FAndShouldFail) {} // Used for testing EXPECT_NONFATAL_FAILURE() and EXPECT_FATAL_FAILURE(). int global_integer = 0; @@ -552,9 +526,9 @@ int global_integer = 0; // Tests that EXPECT_NONFATAL_FAILURE() can reference global variables. TEST(ExpectNonfatalFailureTest, CanReferenceGlobalVariables) { global_integer = 0; - EXPECT_NONFATAL_FAILURE({ - EXPECT_EQ(1, global_integer) << "Expected non-fatal failure."; - }, "Expected non-fatal failure."); + EXPECT_NONFATAL_FAILURE( + { EXPECT_EQ(1, global_integer) << "Expected non-fatal failure."; }, + "Expected non-fatal failure."); } // Tests that EXPECT_NONFATAL_FAILURE() can reference local variables @@ -563,53 +537,48 @@ TEST(ExpectNonfatalFailureTest, CanReferenceLocalVariables) { int m = 0; static int n; n = 1; - EXPECT_NONFATAL_FAILURE({ - EXPECT_EQ(m, n) << "Expected non-fatal failure."; - }, "Expected non-fatal failure."); + EXPECT_NONFATAL_FAILURE({ EXPECT_EQ(m, n) << "Expected non-fatal failure."; }, + "Expected non-fatal failure."); } // Tests that EXPECT_NONFATAL_FAILURE() succeeds when there is exactly // one non-fatal failure and no fatal failure. TEST(ExpectNonfatalFailureTest, SucceedsWhenThereIsOneNonfatalFailure) { - EXPECT_NONFATAL_FAILURE({ - ADD_FAILURE() << "Expected non-fatal failure."; - }, "Expected non-fatal failure."); + EXPECT_NONFATAL_FAILURE({ ADD_FAILURE() << "Expected non-fatal failure."; }, + "Expected non-fatal failure."); } // Tests that EXPECT_NONFATAL_FAILURE() fails when there is no // non-fatal failure. TEST(ExpectNonfatalFailureTest, FailsWhenThereIsNoNonfatalFailure) { printf("(expecting a failure)\n"); - EXPECT_NONFATAL_FAILURE({ - }, ""); + EXPECT_NONFATAL_FAILURE({}, ""); } // Tests that EXPECT_NONFATAL_FAILURE() fails when there are two // non-fatal failures. TEST(ExpectNonfatalFailureTest, FailsWhenThereAreTwoNonfatalFailures) { printf("(expecting a failure)\n"); - EXPECT_NONFATAL_FAILURE({ - ADD_FAILURE() << "Expected non-fatal failure 1."; - ADD_FAILURE() << "Expected non-fatal failure 2."; - }, ""); + EXPECT_NONFATAL_FAILURE( + { + ADD_FAILURE() << "Expected non-fatal failure 1."; + ADD_FAILURE() << "Expected non-fatal failure 2."; + }, + ""); } // Tests that EXPECT_NONFATAL_FAILURE() fails when there is one fatal // failure. TEST(ExpectNonfatalFailureTest, FailsWhenThereIsOneFatalFailure) { printf("(expecting a failure)\n"); - EXPECT_NONFATAL_FAILURE({ - FAIL() << "Expected fatal failure."; - }, ""); + EXPECT_NONFATAL_FAILURE({ FAIL() << "Expected fatal failure."; }, ""); } // Tests that EXPECT_NONFATAL_FAILURE() fails when the statement being // tested returns. TEST(ExpectNonfatalFailureTest, FailsWhenStatementReturns) { printf("(expecting a failure)\n"); - EXPECT_NONFATAL_FAILURE({ - return; - }, ""); + EXPECT_NONFATAL_FAILURE({ return; }, ""); } #if GTEST_HAS_EXCEPTIONS @@ -619,10 +588,8 @@ TEST(ExpectNonfatalFailureTest, FailsWhenStatementReturns) { TEST(ExpectNonfatalFailureTest, FailsWhenStatementThrows) { printf("(expecting a failure)\n"); try { - EXPECT_NONFATAL_FAILURE({ - throw 0; - }, ""); - } catch(int) { // NOLINT + EXPECT_NONFATAL_FAILURE({ throw 0; }, ""); + } catch (int) { // NOLINT } } @@ -631,9 +598,9 @@ TEST(ExpectNonfatalFailureTest, FailsWhenStatementThrows) { // Tests that EXPECT_FATAL_FAILURE() can reference global variables. TEST(ExpectFatalFailureTest, CanReferenceGlobalVariables) { global_integer = 0; - EXPECT_FATAL_FAILURE({ - ASSERT_EQ(1, global_integer) << "Expected fatal failure."; - }, "Expected fatal failure."); + EXPECT_FATAL_FAILURE( + { ASSERT_EQ(1, global_integer) << "Expected fatal failure."; }, + "Expected fatal failure."); } // Tests that EXPECT_FATAL_FAILURE() can reference local static @@ -641,58 +608,51 @@ TEST(ExpectFatalFailureTest, CanReferenceGlobalVariables) { TEST(ExpectFatalFailureTest, CanReferenceLocalStaticVariables) { static int n; n = 1; - EXPECT_FATAL_FAILURE({ - ASSERT_EQ(0, n) << "Expected fatal failure."; - }, "Expected fatal failure."); + EXPECT_FATAL_FAILURE({ ASSERT_EQ(0, n) << "Expected fatal failure."; }, + "Expected fatal failure."); } // Tests that EXPECT_FATAL_FAILURE() succeeds when there is exactly // one fatal failure and no non-fatal failure. TEST(ExpectFatalFailureTest, SucceedsWhenThereIsOneFatalFailure) { - EXPECT_FATAL_FAILURE({ - FAIL() << "Expected fatal failure."; - }, "Expected fatal failure."); + EXPECT_FATAL_FAILURE({ FAIL() << "Expected fatal failure."; }, + "Expected fatal failure."); } // Tests that EXPECT_FATAL_FAILURE() fails when there is no fatal // failure. TEST(ExpectFatalFailureTest, FailsWhenThereIsNoFatalFailure) { printf("(expecting a failure)\n"); - EXPECT_FATAL_FAILURE({ - }, ""); + EXPECT_FATAL_FAILURE({}, ""); } // A helper for generating a fatal failure. -void FatalFailure() { - FAIL() << "Expected fatal failure."; -} +void FatalFailure() { FAIL() << "Expected fatal failure."; } // Tests that EXPECT_FATAL_FAILURE() fails when there are two // fatal failures. TEST(ExpectFatalFailureTest, FailsWhenThereAreTwoFatalFailures) { printf("(expecting a failure)\n"); - EXPECT_FATAL_FAILURE({ - FatalFailure(); - FatalFailure(); - }, ""); + EXPECT_FATAL_FAILURE( + { + FatalFailure(); + FatalFailure(); + }, + ""); } // Tests that EXPECT_FATAL_FAILURE() fails when there is one non-fatal // failure. TEST(ExpectFatalFailureTest, FailsWhenThereIsOneNonfatalFailure) { printf("(expecting a failure)\n"); - EXPECT_FATAL_FAILURE({ - ADD_FAILURE() << "Expected non-fatal failure."; - }, ""); + EXPECT_FATAL_FAILURE({ ADD_FAILURE() << "Expected non-fatal failure."; }, ""); } // Tests that EXPECT_FATAL_FAILURE() fails when the statement being // tested returns. TEST(ExpectFatalFailureTest, FailsWhenStatementReturns) { printf("(expecting a failure)\n"); - EXPECT_FATAL_FAILURE({ - return; - }, ""); + EXPECT_FATAL_FAILURE({ return; }, ""); } #if GTEST_HAS_EXCEPTIONS @@ -702,10 +662,8 @@ TEST(ExpectFatalFailureTest, FailsWhenStatementReturns) { TEST(ExpectFatalFailureTest, FailsWhenStatementThrows) { printf("(expecting a failure)\n"); try { - EXPECT_FATAL_FAILURE({ - throw 0; - }, ""); - } catch(int) { // NOLINT + EXPECT_FATAL_FAILURE({ throw 0; }, ""); + } catch (int) { // NOLINT } } @@ -717,21 +675,14 @@ std::string ParamNameFunc(const testing::TestParamInfo<std::string>& info) { return info.param; } -class ParamTest : public testing::TestWithParam<std::string> { -}; +class ParamTest : public testing::TestWithParam<std::string> {}; -TEST_P(ParamTest, Success) { - EXPECT_EQ("a", GetParam()); -} +TEST_P(ParamTest, Success) { EXPECT_EQ("a", GetParam()); } -TEST_P(ParamTest, Failure) { - EXPECT_EQ("b", GetParam()) << "Expected failure"; -} +TEST_P(ParamTest, Failure) { EXPECT_EQ("b", GetParam()) << "Expected failure"; } -INSTANTIATE_TEST_SUITE_P(PrintingStrings, - ParamTest, - testing::Values(std::string("a")), - ParamNameFunc); +INSTANTIATE_TEST_SUITE_P(PrintingStrings, ParamTest, + testing::Values(std::string("a")), ParamNameFunc); // The case where a suite has INSTANTIATE_TEST_SUITE_P but not TEST_P. using NoTests = ParamTest; @@ -739,20 +690,17 @@ INSTANTIATE_TEST_SUITE_P(ThisIsOdd, NoTests, ::testing::Values("Hello")); // fails under kErrorOnUninstantiatedParameterizedTest=true class DetectNotInstantiatedTest : public testing::TestWithParam<int> {}; -TEST_P(DetectNotInstantiatedTest, Used) { } +TEST_P(DetectNotInstantiatedTest, Used) {} // This would make the test failure from the above go away. // INSTANTIATE_TEST_SUITE_P(Fix, DetectNotInstantiatedTest, testing::Values(1)); template <typename T> -class TypedTest : public testing::Test { -}; +class TypedTest : public testing::Test {}; TYPED_TEST_SUITE(TypedTest, testing::Types<int>); -TYPED_TEST(TypedTest, Success) { - EXPECT_EQ(0, TypeParam()); -} +TYPED_TEST(TypedTest, Success) { EXPECT_EQ(0, TypeParam()); } TYPED_TEST(TypedTest, Failure) { EXPECT_EQ(1, TypeParam()) << "Expected failure"; @@ -781,14 +729,11 @@ TYPED_TEST(TypedTestWithNames, Success) {} TYPED_TEST(TypedTestWithNames, Failure) { FAIL(); } template <typename T> -class TypedTestP : public testing::Test { -}; +class TypedTestP : public testing::Test {}; TYPED_TEST_SUITE_P(TypedTestP); -TYPED_TEST_P(TypedTestP, Success) { - EXPECT_EQ(0U, TypeParam()); -} +TYPED_TEST_P(TypedTestP, Success) { EXPECT_EQ(0U, TypeParam()); } TYPED_TEST_P(TypedTestP, Failure) { EXPECT_EQ(1U, TypeParam()) << "Expected failure"; @@ -813,7 +758,7 @@ class TypedTestPNames { }; INSTANTIATE_TYPED_TEST_SUITE_P(UnsignedCustomName, TypedTestP, UnsignedTypes, - TypedTestPNames); + TypedTestPNames); template <typename T> class DetectNotInstantiatedTypesTest : public testing::Test {}; @@ -835,34 +780,28 @@ REGISTER_TYPED_TEST_SUITE_P(DetectNotInstantiatedTypesTest, Used); // We rely on the golden file to verify that tests whose test case // name ends with DeathTest are run first. -TEST(ADeathTest, ShouldRunFirst) { -} +TEST(ADeathTest, ShouldRunFirst) {} // We rely on the golden file to verify that typed tests whose test // case name ends with DeathTest are run first. template <typename T> -class ATypedDeathTest : public testing::Test { -}; +class ATypedDeathTest : public testing::Test {}; typedef testing::Types<int, double> NumericTypes; TYPED_TEST_SUITE(ATypedDeathTest, NumericTypes); -TYPED_TEST(ATypedDeathTest, ShouldRunFirst) { -} - +TYPED_TEST(ATypedDeathTest, ShouldRunFirst) {} // We rely on the golden file to verify that type-parameterized tests // whose test case name ends with DeathTest are run first. template <typename T> -class ATypeParamDeathTest : public testing::Test { -}; +class ATypeParamDeathTest : public testing::Test {}; TYPED_TEST_SUITE_P(ATypeParamDeathTest); -TYPED_TEST_P(ATypeParamDeathTest, ShouldRunFirst) { -} +TYPED_TEST_P(ATypeParamDeathTest, ShouldRunFirst) {} REGISTER_TYPED_TEST_SUITE_P(ATypeParamDeathTest, ShouldRunFirst); @@ -874,10 +813,7 @@ INSTANTIATE_TYPED_TEST_SUITE_P(My, ATypeParamDeathTest, NumericTypes); // EXPECT_{,NON}FATAL_FAILURE{,_ON_ALL_THREADS}. class ExpectFailureTest : public testing::Test { public: // Must be public and not protected due to a bug in g++ 3.4.2. - enum FailureMode { - FATAL_FAILURE, - NONFATAL_FAILURE - }; + enum FailureMode { FATAL_FAILURE, NONFATAL_FAILURE }; static void AddFailure(FailureMode failure) { if (failure == FATAL_FAILURE) { FAIL() << "Expected fatal failure."; @@ -893,11 +829,13 @@ TEST_F(ExpectFailureTest, ExpectFatalFailure) { EXPECT_FATAL_FAILURE(SUCCEED(), "Expected fatal failure."); // Expected fatal failure, but got a non-fatal failure. printf("(expecting 1 failure)\n"); - EXPECT_FATAL_FAILURE(AddFailure(NONFATAL_FAILURE), "Expected non-fatal " + EXPECT_FATAL_FAILURE(AddFailure(NONFATAL_FAILURE), + "Expected non-fatal " "failure."); // Wrong message. printf("(expecting 1 failure)\n"); - EXPECT_FATAL_FAILURE(AddFailure(FATAL_FAILURE), "Some other fatal failure " + EXPECT_FATAL_FAILURE(AddFailure(FATAL_FAILURE), + "Some other fatal failure " "expected."); } @@ -910,7 +848,8 @@ TEST_F(ExpectFailureTest, ExpectNonFatalFailure) { EXPECT_NONFATAL_FAILURE(AddFailure(FATAL_FAILURE), "Expected fatal failure."); // Wrong message. printf("(expecting 1 failure)\n"); - EXPECT_NONFATAL_FAILURE(AddFailure(NONFATAL_FAILURE), "Some other non-fatal " + EXPECT_NONFATAL_FAILURE(AddFailure(NONFATAL_FAILURE), + "Some other non-fatal " "failure."); } @@ -975,7 +914,8 @@ TEST_F(ExpectFailureTest, ExpectFatalFailureOnAllThreads) { TEST_F(ExpectFailureTest, ExpectNonFatalFailureOnAllThreads) { // Expected non-fatal failure, but succeeds. printf("(expecting 1 failure)\n"); - EXPECT_NONFATAL_FAILURE_ON_ALL_THREADS(SUCCEED(), "Expected non-fatal " + EXPECT_NONFATAL_FAILURE_ON_ALL_THREADS(SUCCEED(), + "Expected non-fatal " "failure."); // Expected non-fatal failure, but got a fatal failure. printf("(expecting 1 failure)\n"); @@ -1064,16 +1004,14 @@ class TestSuiteThatFailsToSetUp : public testing::Test { public: static void SetUpTestSuite() { EXPECT_TRUE(false); } }; -TEST_F(TestSuiteThatFailsToSetUp, ShouldNotRun) { - std::abort(); -} +TEST_F(TestSuiteThatFailsToSetUp, ShouldNotRun) { std::abort(); } // The main function. // // The idea is to use Google Test to run all the tests we have defined (some // of them are intended to fail), and then compare the test results // with the "golden" file. -int main(int argc, char **argv) { +int main(int argc, char** argv) { GTEST_FLAG_SET(print_time, false); // We just run the tests, knowing some of them are intended to fail. @@ -1092,17 +1030,16 @@ int main(int argc, char **argv) { if (GTEST_FLAG_GET(internal_run_death_test) != "") { // Skip the usual output capturing if we're running as the child // process of an threadsafe-style death test. -# if GTEST_OS_WINDOWS +#if GTEST_OS_WINDOWS posix::FReopen("nul:", "w", stdout); -# else +#else posix::FReopen("/dev/null", "w", stdout); -# endif // GTEST_OS_WINDOWS +#endif // GTEST_OS_WINDOWS return RUN_ALL_TESTS(); } #endif // GTEST_HAS_DEATH_TEST - if (internal_skip_environment_and_ad_hoc_tests) - return RUN_ALL_TESTS(); + if (internal_skip_environment_and_ad_hoc_tests) return RUN_ALL_TESTS(); // Registers two global test environments. // The golden file verifies that they are set up in the order they @@ -1110,7 +1047,7 @@ int main(int argc, char **argv) { testing::AddGlobalTestEnvironment(new FooEnvironment); testing::AddGlobalTestEnvironment(new BarEnvironment); #if _MSC_VER -GTEST_DISABLE_MSC_WARNINGS_POP_() // 4127 -#endif // _MSC_VER + GTEST_DISABLE_MSC_WARNINGS_POP_() // 4127 +#endif // _MSC_VER return RunAllTests(); } diff --git a/googletest/test/googletest-param-test-invalid-name1-test_.cc b/googletest/test/googletest-param-test-invalid-name1-test_.cc index 955d699..004733a 100644 --- a/googletest/test/googletest-param-test-invalid-name1-test_.cc +++ b/googletest/test/googletest-param-test-invalid-name1-test_.cc @@ -27,17 +27,14 @@ // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - #include "gtest/gtest.h" namespace { class DummyTest : public ::testing::TestWithParam<const char *> {}; -TEST_P(DummyTest, Dummy) { -} +TEST_P(DummyTest, Dummy) {} -INSTANTIATE_TEST_SUITE_P(InvalidTestName, - DummyTest, +INSTANTIATE_TEST_SUITE_P(InvalidTestName, DummyTest, ::testing::Values("InvalidWithQuotes"), ::testing::PrintToStringParamName()); @@ -47,4 +44,3 @@ int main(int argc, char *argv[]) { testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); } - diff --git a/googletest/test/googletest-param-test-invalid-name2-test_.cc b/googletest/test/googletest-param-test-invalid-name2-test_.cc index 76371df..d0c44da 100644 --- a/googletest/test/googletest-param-test-invalid-name2-test_.cc +++ b/googletest/test/googletest-param-test-invalid-name2-test_.cc @@ -27,22 +27,19 @@ // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - #include "gtest/gtest.h" namespace { class DummyTest : public ::testing::TestWithParam<const char *> {}; std::string StringParamTestSuffix( - const testing::TestParamInfo<const char*>& info) { + const testing::TestParamInfo<const char *> &info) { return std::string(info.param); } -TEST_P(DummyTest, Dummy) { -} +TEST_P(DummyTest, Dummy) {} -INSTANTIATE_TEST_SUITE_P(DuplicateTestNames, - DummyTest, +INSTANTIATE_TEST_SUITE_P(DuplicateTestNames, DummyTest, ::testing::Values("a", "b", "a", "c"), StringParamTestSuffix); } // namespace @@ -51,5 +48,3 @@ int main(int argc, char *argv[]) { testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); } - - diff --git a/googletest/test/googletest-param-test-test.cc b/googletest/test/googletest-param-test-test.cc index 023aa46..4e9323f 100644 --- a/googletest/test/googletest-param-test-test.cc +++ b/googletest/test/googletest-param-test-test.cc @@ -32,21 +32,21 @@ // generators objects produce correct parameter sequences and that // Google Test runtime instantiates correct tests from those sequences. -#include "gtest/gtest.h" +#include "test/googletest-param-test-test.h" -# include <algorithm> -# include <iostream> -# include <list> -# include <set> -# include <sstream> -# include <string> -# include <vector> +#include <algorithm> +#include <iostream> +#include <list> +#include <set> +#include <sstream> +#include <string> +#include <vector> -# include "src/gtest-internal-inl.h" // for UnitTestOptions -# include "test/googletest-param-test-test.h" +#include "gtest/gtest.h" +#include "src/gtest-internal-inl.h" // for UnitTestOptions -using ::std::vector; using ::std::sort; +using ::std::vector; using ::testing::AddGlobalTestEnvironment; using ::testing::Bool; @@ -85,15 +85,14 @@ void VerifyGenerator(const ParamGenerator<T>& generator, // We cannot use EXPECT_EQ() here as the values may be tuples, // which don't support <<. EXPECT_TRUE(expected_values[i] == *it) - << "where i is " << i - << ", expected_values[i] is " << PrintValue(expected_values[i]) - << ", *it is " << PrintValue(*it) + << "where i is " << i << ", expected_values[i] is " + << PrintValue(expected_values[i]) << ", *it is " << PrintValue(*it) << ", and 'it' is an iterator created with the copy constructor.\n"; ++it; } EXPECT_TRUE(it == generator.end()) - << "At the presumed end of sequence when accessing via an iterator " - << "created with the copy constructor.\n"; + << "At the presumed end of sequence when accessing via an iterator " + << "created with the copy constructor.\n"; // Test the iterator assignment. The following lines verify that // the sequence accessed via an iterator initialized via the @@ -105,15 +104,14 @@ void VerifyGenerator(const ParamGenerator<T>& generator, << "At element " << i << " when accessing via an iterator " << "created with the assignment operator.\n"; EXPECT_TRUE(expected_values[i] == *it) - << "where i is " << i - << ", expected_values[i] is " << PrintValue(expected_values[i]) - << ", *it is " << PrintValue(*it) + << "where i is " << i << ", expected_values[i] is " + << PrintValue(expected_values[i]) << ", *it is " << PrintValue(*it) << ", and 'it' is an iterator created with the copy constructor.\n"; ++it; } EXPECT_TRUE(it == generator.end()) - << "At the presumed end of sequence when accessing via an iterator " - << "created with the assignment operator.\n"; + << "At the presumed end of sequence when accessing via an iterator " + << "created with the assignment operator.\n"; } template <typename T> @@ -216,8 +214,7 @@ class DogAdder { DogAdder(const DogAdder& other) : value_(other.value_.c_str()) {} DogAdder operator=(const DogAdder& other) { - if (this != &other) - value_ = other.value_; + if (this != &other) value_ = other.value_; return *this; } DogAdder operator+(const DogAdder& other) const { @@ -225,9 +222,7 @@ class DogAdder { msg << value_.c_str() << other.value_.c_str(); return DogAdder(msg.GetString().c_str()); } - bool operator<(const DogAdder& other) const { - return value_ < other.value_; - } + bool operator<(const DogAdder& other) const { return value_ < other.value_; } const std::string& value() const { return value_; } private: @@ -372,19 +367,17 @@ TEST(ValuesTest, ValuesWorksForValuesOfCompatibleTypes) { } TEST(ValuesTest, ValuesWorksForMaxLengthList) { - const ParamGenerator<int> gen = Values( - 10, 20, 30, 40, 50, 60, 70, 80, 90, 100, - 110, 120, 130, 140, 150, 160, 170, 180, 190, 200, - 210, 220, 230, 240, 250, 260, 270, 280, 290, 300, - 310, 320, 330, 340, 350, 360, 370, 380, 390, 400, - 410, 420, 430, 440, 450, 460, 470, 480, 490, 500); + const ParamGenerator<int> gen = + Values(10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 110, 120, 130, 140, 150, + 160, 170, 180, 190, 200, 210, 220, 230, 240, 250, 260, 270, 280, + 290, 300, 310, 320, 330, 340, 350, 360, 370, 380, 390, 400, 410, + 420, 430, 440, 450, 460, 470, 480, 490, 500); const int expected_values[] = { - 10, 20, 30, 40, 50, 60, 70, 80, 90, 100, - 110, 120, 130, 140, 150, 160, 170, 180, 190, 200, - 210, 220, 230, 240, 250, 260, 270, 280, 290, 300, - 310, 320, 330, 340, 350, 360, 370, 380, 390, 400, - 410, 420, 430, 440, 450, 460, 470, 480, 490, 500}; + 10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 110, 120, 130, + 140, 150, 160, 170, 180, 190, 200, 210, 220, 230, 240, 250, 260, + 270, 280, 290, 300, 310, 320, 330, 340, 350, 360, 370, 380, 390, + 400, 410, 420, 430, 440, 450, 460, 470, 480, 490, 500}; VerifyGenerator(gen, expected_values); } @@ -530,7 +523,6 @@ TEST(CombineTest, NonDefaultConstructAssign) { EXPECT_TRUE(it == gen.end()); } - // Tests that an generator produces correct sequence after being // assigned from another generator. TEST(ParamGeneratorTest, AssignmentWorks) { @@ -573,7 +565,7 @@ class TestGenerationEnvironment : public ::testing::Environment { Message msg; msg << "TestsExpandedAndRun/" << i; if (UnitTestOptions::FilterMatchesTest( - "TestExpansionModule/MultipleTestGenerationTest", + "TestExpansionModule/MultipleTestGenerationTest", msg.GetString().c_str())) { perform_check = true; } @@ -595,8 +587,11 @@ class TestGenerationEnvironment : public ::testing::Environment { } private: - TestGenerationEnvironment() : fixture_constructor_count_(0), set_up_count_(0), - tear_down_count_(0), test_body_count_(0) {} + TestGenerationEnvironment() + : fixture_constructor_count_(0), + set_up_count_(0), + tear_down_count_(0), + test_body_count_(0) {} int fixture_constructor_count_; int set_up_count_; @@ -612,7 +607,7 @@ class TestGenerationTest : public TestWithParam<int> { public: enum { PARAMETER_COUNT = - sizeof(test_generation_params)/sizeof(test_generation_params[0]) + sizeof(test_generation_params) / sizeof(test_generation_params[0]) }; typedef TestGenerationEnvironment<PARAMETER_COUNT> Environment; @@ -636,9 +631,9 @@ class TestGenerationTest : public TestWithParam<int> { for (int i = 0; i < PARAMETER_COUNT; ++i) { Message test_name; test_name << "TestsExpandedAndRun/" << i; - if ( !UnitTestOptions::FilterMatchesTest( - "TestExpansionModule/MultipleTestGenerationTest", - test_name.GetString())) { + if (!UnitTestOptions::FilterMatchesTest( + "TestExpansionModule/MultipleTestGenerationTest", + test_name.GetString())) { all_tests_in_test_case_selected = false; } } @@ -729,8 +724,7 @@ TEST_P(ExternalInstantiationTest, IsMultipleOf33) { // Tests that a parameterized test case can be instantiated with multiple // generators. class MultipleInstantiationTest : public TestWithParam<int> {}; -TEST_P(MultipleInstantiationTest, AllowsMultipleInstances) { -} +TEST_P(MultipleInstantiationTest, AllowsMultipleInstances) {} INSTANTIATE_TEST_SUITE_P(Sequence1, MultipleInstantiationTest, Values(1, 2)); INSTANTIATE_TEST_SUITE_P(Sequence2, MultipleInstantiationTest, Range(3, 5)); @@ -780,7 +774,7 @@ class NamingTest : public TestWithParam<int> {}; TEST_P(NamingTest, TestsReportCorrectNamesAndParameters) { const ::testing::TestInfo* const test_info = - ::testing::UnitTest::GetInstance()->current_test_info(); + ::testing::UnitTest::GetInstance()->current_test_info(); EXPECT_STREQ("ZeroToFiveSequence/NamingTest", test_info->test_suite_name()); @@ -801,7 +795,7 @@ class MacroNamingTest : public TestWithParam<int> {}; TEST_P(PREFIX_WITH_MACRO(NamingTest), PREFIX_WITH_FOO(SomeTestName)) { const ::testing::TestInfo* const test_info = - ::testing::UnitTest::GetInstance()->current_test_info(); + ::testing::UnitTest::GetInstance()->current_test_info(); EXPECT_STREQ("FortyTwo/MacroNamingTest", test_info->test_suite_name()); EXPECT_STREQ("FooSomeTestName/0", test_info->name()); @@ -815,7 +809,7 @@ class MacroNamingTestNonParametrized : public ::testing::Test {}; TEST_F(PREFIX_WITH_MACRO(NamingTestNonParametrized), PREFIX_WITH_FOO(SomeTestName)) { const ::testing::TestInfo* const test_info = - ::testing::UnitTest::GetInstance()->current_test_info(); + ::testing::UnitTest::GetInstance()->current_test_info(); EXPECT_STREQ("MacroNamingTestNonParametrized", test_info->test_suite_name()); EXPECT_STREQ("FooSomeTestName", test_info->name()); @@ -839,9 +833,8 @@ TEST(MacroNameing, LookupNames) { EXPECT_NE( // know_suite_names.find("FortyTwo/MacroNamingTest"), know_suite_names.end()); - EXPECT_NE( - know_suite_names.find("MacroNamingTestNonParametrized"), - know_suite_names.end()); + EXPECT_NE(know_suite_names.find("MacroNamingTestNonParametrized"), + know_suite_names.end()); // Check that the expected form of the test name actually exists. EXPECT_NE( // know_test_names.find("FortyTwo/MacroNamingTest.FooSomeTestName/0"), @@ -924,7 +917,7 @@ class CustomIntegerNamingTest : public TestWithParam<int> {}; TEST_P(CustomIntegerNamingTest, TestsReportCorrectNames) { const ::testing::TestInfo* const test_info = - ::testing::UnitTest::GetInstance()->current_test_info(); + ::testing::UnitTest::GetInstance()->current_test_info(); Message test_name_stream; test_name_stream << "TestsReportCorrectNames/" << GetParam(); EXPECT_STREQ(test_name_stream.GetString().c_str(), test_info->name()); @@ -949,7 +942,7 @@ class CustomStructNamingTest : public TestWithParam<CustomStruct> {}; TEST_P(CustomStructNamingTest, TestsReportCorrectNames) { const ::testing::TestInfo* const test_info = - ::testing::UnitTest::GetInstance()->current_test_info(); + ::testing::UnitTest::GetInstance()->current_test_info(); Message test_name_stream; test_name_stream << "TestsReportCorrectNames/" << GetParam(); EXPECT_STREQ(test_name_stream.GetString().c_str(), test_info->name()); @@ -979,7 +972,7 @@ class StatefulNamingTest : public ::testing::TestWithParam<int> { TEST_P(StatefulNamingTest, TestsReportCorrectNames) { const ::testing::TestInfo* const test_info = - ::testing::UnitTest::GetInstance()->current_test_info(); + ::testing::UnitTest::GetInstance()->current_test_info(); sum_ += GetParam(); Message test_name_stream; test_name_stream << "TestsReportCorrectNames/" << sum_; @@ -1007,7 +1000,7 @@ class CommentTest : public TestWithParam<Unstreamable> {}; TEST_P(CommentTest, TestsCorrectlyReportUnstreamableParams) { const ::testing::TestInfo* const test_info = - ::testing::UnitTest::GetInstance()->current_test_info(); + ::testing::UnitTest::GetInstance()->current_test_info(); EXPECT_EQ(::testing::PrintToString(GetParam()), test_info->value_param()); } @@ -1021,7 +1014,8 @@ INSTANTIATE_TEST_SUITE_P(InstantiationWithComments, CommentTest, // perform simple tests on both. class NonParameterizedBaseTest : public ::testing::Test { public: - NonParameterizedBaseTest() : n_(17) { } + NonParameterizedBaseTest() : n_(17) {} + protected: int n_; }; @@ -1029,16 +1023,14 @@ class NonParameterizedBaseTest : public ::testing::Test { class ParameterizedDerivedTest : public NonParameterizedBaseTest, public ::testing::WithParamInterface<int> { protected: - ParameterizedDerivedTest() : count_(0) { } + ParameterizedDerivedTest() : count_(0) {} int count_; static int global_count_; }; int ParameterizedDerivedTest::global_count_ = 0; -TEST_F(NonParameterizedBaseTest, FixtureIsInitialized) { - EXPECT_EQ(17, n_); -} +TEST_F(NonParameterizedBaseTest, FixtureIsInitialized) { EXPECT_EQ(17, n_); } TEST_P(ParameterizedDerivedTest, SeesSequence) { EXPECT_EQ(17, n_); @@ -1046,11 +1038,10 @@ TEST_P(ParameterizedDerivedTest, SeesSequence) { EXPECT_EQ(GetParam(), global_count_++); } -class ParameterizedDeathTest : public ::testing::TestWithParam<int> { }; +class ParameterizedDeathTest : public ::testing::TestWithParam<int> {}; TEST_F(ParameterizedDeathTest, GetParamDiesFromTestF) { - EXPECT_DEATH_IF_SUPPORTED(GetParam(), - ".* value-parameterized test .*"); + EXPECT_DEATH_IF_SUPPORTED(GetParam(), ".* value-parameterized test .*"); } INSTANTIATE_TEST_SUITE_P(RangeZeroToFive, ParameterizedDerivedTest, @@ -1084,11 +1075,11 @@ class NotInstantiatedTest : public testing::TestWithParam<int> {}; // ... we mark is as allowed. GTEST_ALLOW_UNINSTANTIATED_PARAMETERIZED_TEST(NotInstantiatedTest); -TEST_P(NotInstantiatedTest, Used) { } +TEST_P(NotInstantiatedTest, Used) {} using OtherName = NotInstantiatedTest; GTEST_ALLOW_UNINSTANTIATED_PARAMETERIZED_TEST(OtherName); -TEST_P(OtherName, Used) { } +TEST_P(OtherName, Used) {} // Used but not instantiated, this would fail. but... template <typename T> @@ -1097,11 +1088,11 @@ TYPED_TEST_SUITE_P(NotInstantiatedTypeTest); // ... we mark is as allowed. GTEST_ALLOW_UNINSTANTIATED_PARAMETERIZED_TEST(NotInstantiatedTypeTest); -TYPED_TEST_P(NotInstantiatedTypeTest, Used) { } +TYPED_TEST_P(NotInstantiatedTypeTest, Used) {} REGISTER_TYPED_TEST_SUITE_P(NotInstantiatedTypeTest, Used); } // namespace works_here -int main(int argc, char **argv) { +int main(int argc, char** argv) { // Used in TestGenerationTest test suite. AddGlobalTestEnvironment(TestGenerationTest::Environment::Instance()); // Used in GeneratorEvaluationTest test suite. Tests that the updated value diff --git a/googletest/test/googletest-param-test-test.h b/googletest/test/googletest-param-test-test.h index 8919375..6d77e10 100644 --- a/googletest/test/googletest-param-test-test.h +++ b/googletest/test/googletest-param-test-test.h @@ -39,13 +39,11 @@ // Test fixture for testing definition and instantiation of a test // in separate translation units. -class ExternalInstantiationTest : public ::testing::TestWithParam<int> { -}; +class ExternalInstantiationTest : public ::testing::TestWithParam<int> {}; // Test fixture for testing instantiation of a test in multiple // translation units. class InstantiationInMultipleTranslationUnitsTest - : public ::testing::TestWithParam<int> { -}; + : public ::testing::TestWithParam<int> {}; #endif // GOOGLETEST_TEST_GOOGLETEST_PARAM_TEST_TEST_H_ diff --git a/googletest/test/googletest-param-test2-test.cc b/googletest/test/googletest-param-test2-test.cc index 2a29fb1..71727a6 100644 --- a/googletest/test/googletest-param-test2-test.cc +++ b/googletest/test/googletest-param-test2-test.cc @@ -46,8 +46,7 @@ ParamGenerator<int> extern_gen = Values(33); // and instantiated in another. The test is defined in // googletest-param-test-test.cc and ExternalInstantiationTest fixture class is // defined in gtest-param-test_test.h. -INSTANTIATE_TEST_SUITE_P(MultiplesOf33, - ExternalInstantiationTest, +INSTANTIATE_TEST_SUITE_P(MultiplesOf33, ExternalInstantiationTest, Values(33, 66)); // Tests that a parameterized test case can be instantiated @@ -55,7 +54,5 @@ INSTANTIATE_TEST_SUITE_P(MultiplesOf33, // in googletest-param-test-test.cc and // InstantiationInMultipleTranslationUnitsTest fixture is defined in // gtest-param-test_test.h -INSTANTIATE_TEST_SUITE_P(Sequence2, - InstantiationInMultipleTranslationUnitsTest, - Values(42*3, 42*4, 42*5)); - +INSTANTIATE_TEST_SUITE_P(Sequence2, InstantiationInMultipleTranslationUnitsTest, + Values(42 * 3, 42 * 4, 42 * 5)); diff --git a/googletest/test/googletest-port-test.cc b/googletest/test/googletest-port-test.cc index b14e1f7..29926c2 100644 --- a/googletest/test/googletest-port-test.cc +++ b/googletest/test/googletest-port-test.cc @@ -33,18 +33,18 @@ #include "gtest/internal/gtest-port.h" #if GTEST_OS_MAC -# include <time.h> +#include <time.h> #endif // GTEST_OS_MAC #include <chrono> // NOLINT #include <list> #include <memory> -#include <thread> // NOLINT +#include <thread> // NOLINT #include <utility> // For std::pair and std::make_pair. #include <vector> -#include "gtest/gtest.h" #include "gtest/gtest-spi.h" +#include "gtest/gtest.h" #include "src/gtest-internal-inl.h" using std::make_pair; @@ -238,8 +238,8 @@ TEST(GtestCheckSyntaxTest, WorksWithSwitch) { } switch (0) - case 0: - GTEST_CHECK_(true) << "Check failed in switch case"; + case 0: + GTEST_CHECK_(true) << "Check failed in switch case"; } // Verifies behavior of FormatFileLocation. @@ -281,7 +281,7 @@ TEST(FormatCompilerIndependentFileLocationTest, FormatsUknownFileAndLine) { } #if GTEST_OS_LINUX || GTEST_OS_MAC || GTEST_OS_QNX || GTEST_OS_FUCHSIA || \ - GTEST_OS_DRAGONFLY || GTEST_OS_FREEBSD || GTEST_OS_GNU_KFREEBSD || \ + GTEST_OS_DRAGONFLY || GTEST_OS_FREEBSD || GTEST_OS_GNU_KFREEBSD || \ GTEST_OS_NETBSD || GTEST_OS_OPENBSD || GTEST_OS_GNU_HURD void* ThreadFunc(void* data) { internal::Mutex* mutex = static_cast<internal::Mutex*>(data); @@ -357,13 +357,13 @@ TEST(GtestCheckDeathTest, DiesWithCorrectOutputOnFailure) { const bool a_false_condition = false; const char regex[] = #ifdef _MSC_VER - "googletest-port-test\\.cc\\(\\d+\\):" + "googletest-port-test\\.cc\\(\\d+\\):" #elif GTEST_USES_POSIX_RE - "googletest-port-test\\.cc:[0-9]+" + "googletest-port-test\\.cc:[0-9]+" #else - "googletest-port-test\\.cc:\\d+" + "googletest-port-test\\.cc:\\d+" #endif // _MSC_VER - ".*a_false_condition.*Extra info.*"; + ".*a_false_condition.*Extra info.*"; EXPECT_DEATH_IF_SUPPORTED(GTEST_CHECK_(a_false_condition) << "Extra info", regex); @@ -372,10 +372,12 @@ TEST(GtestCheckDeathTest, DiesWithCorrectOutputOnFailure) { #if GTEST_HAS_DEATH_TEST TEST(GtestCheckDeathTest, LivesSilentlyOnSuccess) { - EXPECT_EXIT({ - GTEST_CHECK_(true) << "Extra info"; - ::std::cerr << "Success\n"; - exit(0); }, + EXPECT_EXIT( + { + GTEST_CHECK_(true) << "Extra info"; + ::std::cerr << "Success\n"; + exit(0); + }, ::testing::ExitedWithCode(0), "Success"); } @@ -386,15 +388,15 @@ TEST(GtestCheckDeathTest, LivesSilentlyOnSuccess) { // For simplicity, we only cover the most important platforms here. TEST(RegexEngineSelectionTest, SelectsCorrectRegexEngine) { #if !GTEST_USES_PCRE -# if GTEST_HAS_POSIX_RE +#if GTEST_HAS_POSIX_RE EXPECT_TRUE(GTEST_USES_POSIX_RE); -# else +#else EXPECT_TRUE(GTEST_USES_SIMPLE_RE); -# endif +#endif #endif // !GTEST_USES_PCRE } @@ -423,9 +425,9 @@ TYPED_TEST(RETest, ImplicitConstructorWorks) { // Tests that RE's constructors reject invalid regular expressions. TYPED_TEST(RETest, RejectsInvalidRegex) { - EXPECT_NONFATAL_FAILURE({ - const RE invalid(TypeParam("?")); - }, "\"?\" is not a valid POSIX Extended regular expression."); + EXPECT_NONFATAL_FAILURE( + { const RE invalid(TypeParam("?")); }, + "\"?\" is not a valid POSIX Extended regular expression."); } // Tests RE::FullMatch(). @@ -819,8 +821,7 @@ TEST(MatchRegexAtHeadTest, WorksWhenRegexStartsWithRepetition) { EXPECT_TRUE(MatchRegexAtHead("a?b", "ab")); } -TEST(MatchRegexAtHeadTest, - WorksWhenRegexStartsWithRepetionOfEscapeSequence) { +TEST(MatchRegexAtHeadTest, WorksWhenRegexStartsWithRepetionOfEscapeSequence) { EXPECT_FALSE(MatchRegexAtHead("\\.+a", "abc")); EXPECT_FALSE(MatchRegexAtHead("\\s?b", " b")); @@ -876,17 +877,14 @@ TEST(RETest, ImplicitConstructorWorks) { // Tests that RE's constructors reject invalid regular expressions. TEST(RETest, RejectsInvalidRegex) { - EXPECT_NONFATAL_FAILURE({ - const RE normal(NULL); - }, "NULL is not a valid simple regular expression"); + EXPECT_NONFATAL_FAILURE({ const RE normal(NULL); }, + "NULL is not a valid simple regular expression"); - EXPECT_NONFATAL_FAILURE({ - const RE normal(".*(\\w+"); - }, "'(' is unsupported"); + EXPECT_NONFATAL_FAILURE({ const RE normal(".*(\\w+"); }, + "'(' is unsupported"); - EXPECT_NONFATAL_FAILURE({ - const RE invalid("^?"); - }, "'?' can only follow a repeatable token"); + EXPECT_NONFATAL_FAILURE({ const RE invalid("^?"); }, + "'?' can only follow a repeatable token"); } // Tests RE::FullMatch(). @@ -1028,12 +1026,13 @@ TEST(ThreadWithParamTest, ConstructorExecutesThreadFunc) { TEST(MutexDeathTest, AssertHeldShouldAssertWhenNotLocked) { // AssertHeld() is flaky only in the presence of multiple threads accessing // the lock. In this case, the test is robust. - EXPECT_DEATH_IF_SUPPORTED({ - Mutex m; - { MutexLock lock(&m); } - m.AssertHeld(); - }, - "thread .*hold"); + EXPECT_DEATH_IF_SUPPORTED( + { + Mutex m; + { MutexLock lock(&m); } + m.AssertHeld(); + }, + "thread .*hold"); } TEST(MutexTest, AssertHeldShouldNotAssertWhenLocked) { @@ -1044,8 +1043,8 @@ TEST(MutexTest, AssertHeldShouldNotAssertWhenLocked) { class AtomicCounterWithMutex { public: - explicit AtomicCounterWithMutex(Mutex* mutex) : - value_(0), mutex_(mutex), random_(42) {} + explicit AtomicCounterWithMutex(Mutex* mutex) + : value_(0), mutex_(mutex), random_(42) {} void Increment() { MutexLock lock(mutex_); @@ -1076,7 +1075,7 @@ class AtomicCounterWithMutex { std::chrono::milliseconds(random_.Generate(30))); ::InterlockedIncrement(&dummy); #else -# error "Memory barrier not implemented on this platform." +#error "Memory barrier not implemented on this platform." #endif // GTEST_HAS_PTHREAD } value_ = temp + 1; @@ -1086,12 +1085,11 @@ class AtomicCounterWithMutex { private: volatile int value_; Mutex* const mutex_; // Protects value_. - Random random_; + Random random_; }; void CountingThreadFunc(pair<AtomicCounterWithMutex*, int> param) { - for (int i = 0; i < param.second; ++i) - param.first->Increment(); + for (int i = 0; i < param.second; ++i) param.first->Increment(); } // Tests that the mutex only lets one thread at a time to lock it. @@ -1107,14 +1105,12 @@ TEST(MutexTest, OnlyOneThreadCanLockAtATime) { // Creates and runs kThreadCount threads that increment locked_counter // kCycleCount times each. for (int i = 0; i < kThreadCount; ++i) { - counting_threads[i].reset(new ThreadType(&CountingThreadFunc, - make_pair(&locked_counter, - kCycleCount), - &threads_can_start)); + counting_threads[i].reset(new ThreadType( + &CountingThreadFunc, make_pair(&locked_counter, kCycleCount), + &threads_can_start)); } threads_can_start.Notify(); - for (int i = 0; i < kThreadCount; ++i) - counting_threads[i]->Join(); + for (int i = 0; i < kThreadCount; ++i) counting_threads[i]->Join(); // If the mutex lets more than one thread to increment the counter at a // time, they are likely to encounter a race condition and have some @@ -1124,7 +1120,7 @@ TEST(MutexTest, OnlyOneThreadCanLockAtATime) { } template <typename T> -void RunFromThread(void (func)(T), T param) { +void RunFromThread(void(func)(T), T param) { ThreadWithParam<T> thread(func, param, nullptr); thread.Join(); } diff --git a/googletest/test/googletest-printers-test.cc b/googletest/test/googletest-printers-test.cc index 6017d0d..acfecf9 100644 --- a/googletest/test/googletest-printers-test.cc +++ b/googletest/test/googletest-printers-test.cc @@ -27,7 +27,6 @@ // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - // Google Test - The Google C++ Testing and Mocking Framework // // This file tests the universal value printer. @@ -56,30 +55,20 @@ // Some user-defined types for testing the universal value printer. // An anonymous enum type. -enum AnonymousEnum { - kAE1 = -1, - kAE2 = 1 -}; +enum AnonymousEnum { kAE1 = -1, kAE2 = 1 }; // An enum without a user-defined printer. -enum EnumWithoutPrinter { - kEWP1 = -2, - kEWP2 = 42 -}; +enum EnumWithoutPrinter { kEWP1 = -2, kEWP2 = 42 }; // An enum with a << operator. -enum EnumWithStreaming { - kEWS1 = 10 -}; +enum EnumWithStreaming { kEWS1 = 10 }; std::ostream& operator<<(std::ostream& os, EnumWithStreaming e) { return os << (e == kEWS1 ? "kEWS1" : "invalid"); } // An enum with a PrintTo() function. -enum EnumWithPrintTo { - kEWPT1 = 1 -}; +enum EnumWithPrintTo { kEWPT1 = 1 }; void PrintTo(EnumWithPrintTo e, std::ostream* os) { *os << (e == kEWPT1 ? "kEWPT1" : "invalid"); @@ -108,6 +97,7 @@ template <typename T> class UnprintableTemplateInGlobal { public: UnprintableTemplateInGlobal() : value_() {} + private: T value_; }; @@ -133,6 +123,7 @@ class UnprintableInFoo { public: UnprintableInFoo() : z_(0) { memcpy(xy_, "\xEF\x12\x0\x0\x34\xAB\x0\x0", 8); } double z() const { return z_; } + private: char xy_[8]; double z_; @@ -149,8 +140,7 @@ void PrintTo(const PrintableViaPrintTo& x, ::std::ostream* os) { } // A type with a user-defined << for printing its pointer. -struct PointerPrintable { -}; +struct PointerPrintable {}; ::std::ostream& operator<<(::std::ostream& os, const PointerPrintable* /* x */) { @@ -164,6 +154,7 @@ class PrintableViaPrintToTemplate { explicit PrintableViaPrintToTemplate(const T& a_value) : value_(a_value) {} const T& value() const { return value_; } + private: T value_; }; @@ -180,6 +171,7 @@ class StreamableTemplateInFoo { StreamableTemplateInFoo() : value_() {} const T& value() const { return value_; } + private: T value_; }; @@ -255,7 +247,6 @@ class UniversalPrinter<Wrapper<T>> { }; } // namespace internal - namespace gtest_printers_test { using ::std::deque; @@ -350,29 +341,21 @@ TEST(PrintCharTest, PlainChar) { // signed char. TEST(PrintCharTest, SignedChar) { EXPECT_EQ("'\\0'", Print(static_cast<signed char>('\0'))); - EXPECT_EQ("'\\xCE' (-50)", - Print(static_cast<signed char>(-50))); + EXPECT_EQ("'\\xCE' (-50)", Print(static_cast<signed char>(-50))); } // unsigned char. TEST(PrintCharTest, UnsignedChar) { EXPECT_EQ("'\\0'", Print(static_cast<unsigned char>('\0'))); - EXPECT_EQ("'b' (98, 0x62)", - Print(static_cast<unsigned char>('b'))); + EXPECT_EQ("'b' (98, 0x62)", Print(static_cast<unsigned char>('b'))); } -TEST(PrintCharTest, Char16) { - EXPECT_EQ("U+0041", Print(u'A')); -} +TEST(PrintCharTest, Char16) { EXPECT_EQ("U+0041", Print(u'A')); } -TEST(PrintCharTest, Char32) { - EXPECT_EQ("U+0041", Print(U'A')); -} +TEST(PrintCharTest, Char32) { EXPECT_EQ("U+0041", Print(U'A')); } #ifdef __cpp_char8_t -TEST(PrintCharTest, Char8) { - EXPECT_EQ("U+0041", Print(u8'A')); -} +TEST(PrintCharTest, Char8) { EXPECT_EQ("U+0041", Print(u8'A')); } #endif // Tests printing other simple, built-in types. @@ -414,8 +397,8 @@ TEST(PrintTypeSizeTest, Wchar_t) { TEST(PrintBuiltInTypeTest, Integer) { EXPECT_EQ("'\\xFF' (255)", Print(static_cast<unsigned char>(255))); // uint8 EXPECT_EQ("'\\x80' (-128)", Print(static_cast<signed char>(-128))); // int8 - EXPECT_EQ("65535", Print(std::numeric_limits<uint16_t>::max())); // uint16 - EXPECT_EQ("-32768", Print(std::numeric_limits<int16_t>::min())); // int16 + EXPECT_EQ("65535", Print(std::numeric_limits<uint16_t>::max())); // uint16 + EXPECT_EQ("-32768", Print(std::numeric_limits<int16_t>::min())); // int16 EXPECT_EQ("4294967295", Print(std::numeric_limits<uint32_t>::max())); // uint32 EXPECT_EQ("-2147483648", @@ -446,7 +429,7 @@ TEST(PrintBuiltInTypeTest, Size_t) { #if !GTEST_OS_WINDOWS // Windows has no ssize_t type. EXPECT_EQ("-2", Print(static_cast<ssize_t>(-2))); // ssize_t. -#endif // !GTEST_OS_WINDOWS +#endif // !GTEST_OS_WINDOWS } // gcc/clang __{u,}int128_t values. @@ -516,8 +499,9 @@ TEST(PrintCStringTest, Null) { // Tests that C strings are escaped properly. TEST(PrintCStringTest, EscapesProperly) { const char* p = "'\"?\\\a\b\f\n\r\t\v\x7F\xFF a"; - EXPECT_EQ(PrintPointer(p) + " pointing to \"'\\\"?\\\\\\a\\b\\f" - "\\n\\r\\t\\v\\x7F\\xFF a\"", + EXPECT_EQ(PrintPointer(p) + + " pointing to \"'\\\"?\\\\\\a\\b\\f" + "\\n\\r\\t\\v\\x7F\\xFF a\"", Print(p)); } @@ -636,10 +620,12 @@ TEST(PrintWideCStringTest, Null) { // Tests that wide C strings are escaped properly. TEST(PrintWideCStringTest, EscapesProperly) { - const wchar_t s[] = {'\'', '"', '?', '\\', '\a', '\b', '\f', '\n', '\r', - '\t', '\v', 0xD3, 0x576, 0x8D3, 0xC74D, ' ', 'a', '\0'}; - EXPECT_EQ(PrintPointer(s) + " pointing to L\"'\\\"?\\\\\\a\\b\\f" - "\\n\\r\\t\\v\\xD3\\x576\\x8D3\\xC74D a\"", + const wchar_t s[] = {'\'', '"', '?', '\\', '\a', '\b', + '\f', '\n', '\r', '\t', '\v', 0xD3, + 0x576, 0x8D3, 0xC74D, ' ', 'a', '\0'}; + EXPECT_EQ(PrintPointer(s) + + " pointing to L\"'\\\"?\\\\\\a\\b\\f" + "\\n\\r\\t\\v\\xD3\\x576\\x8D3\\xC74D a\"", Print(static_cast<const wchar_t*>(s))); } #endif // native wchar_t @@ -721,10 +707,9 @@ TEST(PrintPointerTest, NonMemberFunctionPointer) { // standard disallows casting between pointers to functions and // pointers to objects, and some compilers (e.g. GCC 3.4) enforce // this limitation. - EXPECT_EQ( - PrintPointer(reinterpret_cast<const void*>( - reinterpret_cast<internal::BiggestInt>(&MyFunction))), - Print(&MyFunction)); + EXPECT_EQ(PrintPointer(reinterpret_cast<const void*>( + reinterpret_cast<internal::BiggestInt>(&MyFunction))), + Print(&MyFunction)); int (*p)(bool) = NULL; // NOLINT EXPECT_EQ("NULL", Print(p)); } @@ -733,14 +718,13 @@ TEST(PrintPointerTest, NonMemberFunctionPointer) { // another. template <typename StringType> AssertionResult HasPrefix(const StringType& str, const StringType& prefix) { - if (str.find(prefix, 0) == 0) - return AssertionSuccess(); + if (str.find(prefix, 0) == 0) return AssertionSuccess(); const bool is_wide_string = sizeof(prefix[0]) > 1; const char* const begin_string_quote = is_wide_string ? "L\"" : "\""; return AssertionFailure() - << begin_string_quote << prefix << "\" is not a prefix of " - << begin_string_quote << str << "\"\n"; + << begin_string_quote << prefix << "\" is not a prefix of " + << begin_string_quote << str << "\"\n"; } // Tests printing member variable pointers. Although they are called @@ -761,8 +745,7 @@ TEST(PrintPointerTest, MemberVariablePointer) { EXPECT_TRUE(HasPrefix(Print(&Foo::value), Print(sizeof(&Foo::value)) + "-byte object ")); int Foo::*p = NULL; // NOLINT - EXPECT_TRUE(HasPrefix(Print(p), - Print(sizeof(p)) + "-byte object ")); + EXPECT_TRUE(HasPrefix(Print(p), Print(sizeof(p)) + "-byte object ")); } // Tests printing member function pointers. Although they are called @@ -776,8 +759,7 @@ TEST(PrintPointerTest, MemberFunctionPointer) { HasPrefix(Print(&Foo::MyVirtualMethod), Print(sizeof((&Foo::MyVirtualMethod))) + "-byte object ")); int (Foo::*p)(char) = NULL; // NOLINT - EXPECT_TRUE(HasPrefix(Print(p), - Print(sizeof(p)) + "-byte object ")); + EXPECT_TRUE(HasPrefix(Print(p), Print(sizeof(p)) + "-byte object ")); } // Tests printing C arrays. @@ -791,29 +773,26 @@ std::string PrintArrayHelper(T (&a)[N]) { // One-dimensional array. TEST(PrintArrayTest, OneDimensionalArray) { - int a[5] = { 1, 2, 3, 4, 5 }; + int a[5] = {1, 2, 3, 4, 5}; EXPECT_EQ("{ 1, 2, 3, 4, 5 }", PrintArrayHelper(a)); } // Two-dimensional array. TEST(PrintArrayTest, TwoDimensionalArray) { - int a[2][5] = { - { 1, 2, 3, 4, 5 }, - { 6, 7, 8, 9, 0 } - }; + int a[2][5] = {{1, 2, 3, 4, 5}, {6, 7, 8, 9, 0}}; EXPECT_EQ("{ { 1, 2, 3, 4, 5 }, { 6, 7, 8, 9, 0 } }", PrintArrayHelper(a)); } // Array of const elements. TEST(PrintArrayTest, ConstArray) { - const bool a[1] = { false }; + const bool a[1] = {false}; EXPECT_EQ("{ false }", PrintArrayHelper(a)); } // char array without terminating NUL. TEST(PrintArrayTest, CharArrayWithNoTerminatingNul) { // Array a contains '\0' in the middle and doesn't end with '\0'. - char a[] = { 'H', '\0', 'i' }; + char a[] = {'H', '\0', 'i'}; EXPECT_EQ("\"H\\0i\" (no terminating NUL)", PrintArrayHelper(a)); } @@ -834,9 +813,7 @@ TEST(PrintArrayTest, Char8ArrayWithNoTerminatingNul) { // char8_t array with terminating NUL. TEST(PrintArrayTest, Char8ArrayWithTerminatingNul) { const char8_t a[] = u8"\0世界"; - EXPECT_EQ( - "u8\"\\0\\xE4\\xB8\\x96\\xE7\\x95\\x8C\"", - PrintArrayHelper(a)); + EXPECT_EQ("u8\"\\0\\xE4\\xB8\\x96\\xE7\\x95\\x8C\"", PrintArrayHelper(a)); } #endif @@ -889,7 +866,7 @@ TEST(PrintArrayTest, ObjectArray) { // Array with many elements. TEST(PrintArrayTest, BigArray) { - int a[100] = { 1, 2, 3 }; + int a[100] = {1, 2, 3}; EXPECT_EQ("{ 1, 2, 3, 0, 0, 0, 0, 0, ..., 0, 0, 0, 0, 0, 0, 0, 0 }", PrintArrayHelper(a)); } @@ -909,11 +886,14 @@ TEST(PrintStringTest, StringAmbiguousHex) { // '\x6', '\x6B', or '\x6BA'. // a hex escaping sequence following by a decimal digit - EXPECT_EQ("\"0\\x12\" \"3\"", Print(::std::string("0\x12" "3"))); + EXPECT_EQ("\"0\\x12\" \"3\"", Print(::std::string("0\x12" + "3"))); // a hex escaping sequence following by a hex digit (lower-case) - EXPECT_EQ("\"mm\\x6\" \"bananas\"", Print(::std::string("mm\x6" "bananas"))); + EXPECT_EQ("\"mm\\x6\" \"bananas\"", Print(::std::string("mm\x6" + "bananas"))); // a hex escaping sequence following by a hex digit (upper-case) - EXPECT_EQ("\"NOM\\x6\" \"BANANA\"", Print(::std::string("NOM\x6" "BANANA"))); + EXPECT_EQ("\"NOM\\x6\" \"BANANA\"", Print(::std::string("NOM\x6" + "BANANA"))); // a hex escaping sequence following by a non-xdigit EXPECT_EQ("\"!\\x5-!\"", Print(::std::string("!\x5-!"))); } @@ -923,19 +903,21 @@ TEST(PrintStringTest, StringAmbiguousHex) { // ::std::wstring. TEST(PrintWideStringTest, StringInStdNamespace) { const wchar_t s[] = L"'\"?\\\a\b\f\n\0\r\t\v\xD3\x576\x8D3\xC74D a"; - const ::std::wstring str(s, sizeof(s)/sizeof(wchar_t)); - EXPECT_EQ("L\"'\\\"?\\\\\\a\\b\\f\\n\\0\\r\\t\\v" - "\\xD3\\x576\\x8D3\\xC74D a\\0\"", - Print(str)); + const ::std::wstring str(s, sizeof(s) / sizeof(wchar_t)); + EXPECT_EQ( + "L\"'\\\"?\\\\\\a\\b\\f\\n\\0\\r\\t\\v" + "\\xD3\\x576\\x8D3\\xC74D a\\0\"", + Print(str)); } TEST(PrintWideStringTest, StringAmbiguousHex) { // same for wide strings. - EXPECT_EQ("L\"0\\x12\" L\"3\"", Print(::std::wstring(L"0\x12" L"3"))); - EXPECT_EQ("L\"mm\\x6\" L\"bananas\"", - Print(::std::wstring(L"mm\x6" L"bananas"))); - EXPECT_EQ("L\"NOM\\x6\" L\"BANANA\"", - Print(::std::wstring(L"NOM\x6" L"BANANA"))); + EXPECT_EQ("L\"0\\x12\" L\"3\"", Print(::std::wstring(L"0\x12" + L"3"))); + EXPECT_EQ("L\"mm\\x6\" L\"bananas\"", Print(::std::wstring(L"mm\x6" + L"bananas"))); + EXPECT_EQ("L\"NOM\\x6\" L\"BANANA\"", Print(::std::wstring(L"NOM\x6" + L"BANANA"))); EXPECT_EQ("L\"!\\x5-!\"", Print(::std::wstring(L"!\x5-!"))); } #endif // GTEST_HAS_STD_WSTRING @@ -1049,7 +1031,6 @@ TEST(PrintStlContainerTest, NonEmptyDeque) { EXPECT_EQ("{ 1, 3 }", Print(non_empty)); } - TEST(PrintStlContainerTest, OneElementHashMap) { ::std::unordered_map<int, char> map1; map1[1] = 'a'; @@ -1065,11 +1046,9 @@ TEST(PrintStlContainerTest, HashMultiMap) { const std::string result = Print(map1); EXPECT_TRUE(result == "{ (5, true), (5, false) }" || result == "{ (5, false), (5, true) }") - << " where Print(map1) returns \"" << result << "\"."; + << " where Print(map1) returns \"" << result << "\"."; } - - TEST(PrintStlContainerTest, HashSet) { ::std::unordered_set<int> set1; set1.insert(1); @@ -1078,7 +1057,7 @@ TEST(PrintStlContainerTest, HashSet) { TEST(PrintStlContainerTest, HashMultiSet) { const int kSize = 5; - int a[kSize] = { 1, 1, 2, 5, 1 }; + int a[kSize] = {1, 1, 2, 5, 1}; ::std::unordered_multiset<int> set1(a, a + kSize); // Elements of hash_multiset can be printed in any order. @@ -1094,8 +1073,8 @@ TEST(PrintStlContainerTest, HashMultiSet) { ASSERT_NE(isdigit(static_cast<unsigned char>(result[i])), 0); numbers.push_back(result[i] - '0'); } else { - EXPECT_EQ(expected_pattern[i], result[i]) << " where result is " - << result; + EXPECT_EQ(expected_pattern[i], result[i]) + << " where result is " << result; } } @@ -1105,7 +1084,6 @@ TEST(PrintStlContainerTest, HashMultiSet) { EXPECT_TRUE(std::equal(a, a + kSize, numbers.begin())); } - TEST(PrintStlContainerTest, List) { const std::string a[] = {"hello", "world"}; const list<std::string> strings(a, a + 2); @@ -1135,20 +1113,19 @@ TEST(PrintStlContainerTest, MultiMap) { } TEST(PrintStlContainerTest, Set) { - const unsigned int a[] = { 3, 0, 5 }; + const unsigned int a[] = {3, 0, 5}; set<unsigned int> set1(a, a + 3); EXPECT_EQ("{ 0, 3, 5 }", Print(set1)); } TEST(PrintStlContainerTest, MultiSet) { - const int a[] = { 1, 1, 2, 5, 1 }; + const int a[] = {1, 1, 2, 5, 1}; multiset<int> set1(a, a + 5); EXPECT_EQ("{ 1, 1, 1, 2, 5 }", Print(set1)); } - TEST(PrintStlContainerTest, SinglyLinkedList) { - int a[] = { 9, 2, 8 }; + int a[] = {9, 2, 8}; const std::forward_list<int> ints(a, a + 3); EXPECT_EQ("{ 9, 2, 8 }", Print(ints)); } @@ -1166,32 +1143,34 @@ TEST(PrintStlContainerTest, Vector) { } TEST(PrintStlContainerTest, LongSequence) { - const int a[100] = { 1, 2, 3 }; + const int a[100] = {1, 2, 3}; const vector<int> v(a, a + 100); - EXPECT_EQ("{ 1, 2, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, " - "0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, ... }", Print(v)); + EXPECT_EQ( + "{ 1, 2, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, " + "0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, ... }", + Print(v)); } TEST(PrintStlContainerTest, NestedContainer) { - const int a1[] = { 1, 2 }; - const int a2[] = { 3, 4, 5 }; + const int a1[] = {1, 2}; + const int a2[] = {3, 4, 5}; const list<int> l1(a1, a1 + 2); const list<int> l2(a2, a2 + 3); - vector<list<int> > v; + vector<list<int>> v; v.push_back(l1); v.push_back(l2); EXPECT_EQ("{ { 1, 2 }, { 3, 4, 5 } }", Print(v)); } TEST(PrintStlContainerTest, OneDimensionalNativeArray) { - const int a[3] = { 1, 2, 3 }; + const int a[3] = {1, 2, 3}; NativeArray<int> b(a, 3, RelationToSourceReference()); EXPECT_EQ("{ 1, 2, 3 }", Print(b)); } TEST(PrintStlContainerTest, TwoDimensionalNativeArray) { - const int a[2][3] = { { 1, 2, 3 }, { 4, 5, 6 } }; + const int a[2][3] = {{1, 2, 3}, {4, 5, 6}}; NativeArray<int[3]> b(a, 2, RelationToSourceReference()); EXPECT_EQ("{ { 1, 2, 3 }, { 4, 5, 6 } }", Print(b)); } @@ -1243,20 +1222,18 @@ TEST(PrintStdTupleTest, VariousSizes) { t10(false, 'a', static_cast<short>(3), 4, 5, 1.5F, -2.5, str, // NOLINT nullptr, "10"); EXPECT_EQ("(false, 'a' (97, 0x61), 3, 4, 5, 1.5, -2.5, " + PrintPointer(str) + - " pointing to \"8\", NULL, \"10\")", + " pointing to \"8\", NULL, \"10\")", Print(t10)); } // Nested tuples. TEST(PrintStdTupleTest, NestedTuple) { - ::std::tuple< ::std::tuple<int, bool>, char> nested( - ::std::make_tuple(5, true), 'a'); + ::std::tuple<::std::tuple<int, bool>, char> nested(::std::make_tuple(5, true), + 'a'); EXPECT_EQ("((5, true), 'a' (97, 0x61))", Print(nested)); } -TEST(PrintNullptrT, Basic) { - EXPECT_EQ("(nullptr)", Print(nullptr)); -} +TEST(PrintNullptrT, Basic) { EXPECT_EQ("(nullptr)", Print(nullptr)); } TEST(PrintReferenceWrapper, Printable) { int x = 5; @@ -1280,8 +1257,7 @@ TEST(PrintReferenceWrapper, Unprintable) { // Unprintable types in the global namespace. TEST(PrintUnprintableTypeTest, InGlobalNamespace) { - EXPECT_EQ("1-byte object <00>", - Print(UnprintableTemplateInGlobal<char>())); + EXPECT_EQ("1-byte object <00>", Print(UnprintableTemplateInGlobal<char>())); } // Unprintable types in a user namespace. @@ -1298,14 +1274,15 @@ struct Big { }; TEST(PrintUnpritableTypeTest, BigObject) { - EXPECT_EQ("257-byte object <00-00 00-00 00-00 00-00 00-00 00-00 " - "00-00 00-00 00-00 00-00 00-00 00-00 00-00 00-00 00-00 00-00 " - "00-00 00-00 00-00 00-00 00-00 00-00 00-00 00-00 00-00 00-00 " - "00-00 00-00 00-00 00-00 00-00 00-00 ... 00-00 00-00 00-00 " - "00-00 00-00 00-00 00-00 00-00 00-00 00-00 00-00 00-00 00-00 " - "00-00 00-00 00-00 00-00 00-00 00-00 00-00 00-00 00-00 00-00 " - "00-00 00-00 00-00 00-00 00-00 00-00 00-00 00-00 00>", - Print(Big())); + EXPECT_EQ( + "257-byte object <00-00 00-00 00-00 00-00 00-00 00-00 " + "00-00 00-00 00-00 00-00 00-00 00-00 00-00 00-00 00-00 00-00 " + "00-00 00-00 00-00 00-00 00-00 00-00 00-00 00-00 00-00 00-00 " + "00-00 00-00 00-00 00-00 00-00 00-00 ... 00-00 00-00 00-00 " + "00-00 00-00 00-00 00-00 00-00 00-00 00-00 00-00 00-00 00-00 " + "00-00 00-00 00-00 00-00 00-00 00-00 00-00 00-00 00-00 00-00 " + "00-00 00-00 00-00 00-00 00-00 00-00 00-00 00-00 00>", + Print(Big())); } // Tests printing user-defined streamable types. @@ -1348,8 +1325,7 @@ TEST(PrintStreamableTypeTest, PathLikeInUserNamespace) { // Tests printing user-defined types that have a PrintTo() function. TEST(PrintPrintableTypeTest, InUserNamespace) { - EXPECT_EQ("PrintableViaPrintTo: 0", - Print(::foo::PrintableViaPrintTo())); + EXPECT_EQ("PrintableViaPrintTo: 0", Print(::foo::PrintableViaPrintTo())); } // Tests printing a pointer to a user-defined type that has a << @@ -1371,16 +1347,14 @@ TEST(PrintReferenceTest, PrintsAddressAndValue) { int n = 5; EXPECT_EQ("@" + PrintPointer(&n) + " 5", PrintByRef(n)); - int a[2][3] = { - { 0, 1, 2 }, - { 3, 4, 5 } - }; + int a[2][3] = {{0, 1, 2}, {3, 4, 5}}; EXPECT_EQ("@" + PrintPointer(a) + " { { 0, 1, 2 }, { 3, 4, 5 } }", PrintByRef(a)); const ::foo::UnprintableInFoo x; - EXPECT_EQ("@" + PrintPointer(&x) + " 16-byte object " - "<EF-12 00-00 34-AB 00-00 00-00 00-00 00-00 00-00>", + EXPECT_EQ("@" + PrintPointer(&x) + + " 16-byte object " + "<EF-12 00-00 34-AB 00-00 00-00 00-00 00-00 00-00>", PrintByRef(x)); } @@ -1396,33 +1370,29 @@ TEST(PrintReferenceTest, HandlesFunctionPointer) { // this limitation. const std::string fp_string = PrintPointer(reinterpret_cast<const void*>( reinterpret_cast<internal::BiggestInt>(fp))); - EXPECT_EQ("@" + fp_pointer_string + " " + fp_string, - PrintByRef(fp)); + EXPECT_EQ("@" + fp_pointer_string + " " + fp_string, PrintByRef(fp)); } // Tests that the universal printer prints a member function pointer // passed by reference. TEST(PrintReferenceTest, HandlesMemberFunctionPointer) { int (Foo::*p)(char ch) = &Foo::MyMethod; - EXPECT_TRUE(HasPrefix( - PrintByRef(p), - "@" + PrintPointer(reinterpret_cast<const void*>(&p)) + " " + - Print(sizeof(p)) + "-byte object ")); + EXPECT_TRUE(HasPrefix(PrintByRef(p), + "@" + PrintPointer(reinterpret_cast<const void*>(&p)) + + " " + Print(sizeof(p)) + "-byte object ")); char (Foo::*p2)(int n) = &Foo::MyVirtualMethod; - EXPECT_TRUE(HasPrefix( - PrintByRef(p2), - "@" + PrintPointer(reinterpret_cast<const void*>(&p2)) + " " + - Print(sizeof(p2)) + "-byte object ")); + EXPECT_TRUE(HasPrefix(PrintByRef(p2), + "@" + PrintPointer(reinterpret_cast<const void*>(&p2)) + + " " + Print(sizeof(p2)) + "-byte object ")); } // Tests that the universal printer prints a member variable pointer // passed by reference. TEST(PrintReferenceTest, HandlesMemberVariablePointer) { int Foo::*p = &Foo::value; // NOLINT - EXPECT_TRUE(HasPrefix( - PrintByRef(p), - "@" + PrintPointer(&p) + " " + Print(sizeof(p)) + "-byte object ")); + EXPECT_TRUE(HasPrefix(PrintByRef(p), "@" + PrintPointer(&p) + " " + + Print(sizeof(p)) + "-byte object ")); } // Tests that FormatForComparisonFailureMessage(), which is used to print @@ -1431,8 +1401,7 @@ TEST(PrintReferenceTest, HandlesMemberVariablePointer) { // scalar TEST(FormatForComparisonFailureMessageTest, WorksForScalar) { - EXPECT_STREQ("123", - FormatForComparisonFailureMessage(123, 124).c_str()); + EXPECT_STREQ("123", FormatForComparisonFailureMessage(123, 124).c_str()); } // non-char pointer @@ -1446,9 +1415,8 @@ TEST(FormatForComparisonFailureMessageTest, WorksForNonCharPointer) { TEST(FormatForComparisonFailureMessageTest, FormatsNonCharArrayAsPointer) { // In expression 'array == x', 'array' is compared by pointer. // Therefore we want to print an array operand as a pointer. - int n[] = { 1, 2, 3 }; - EXPECT_EQ(PrintPointer(n), - FormatForComparisonFailureMessage(n, n).c_str()); + int n[] = {1, 2, 3}; + EXPECT_EQ(PrintPointer(n), FormatForComparisonFailureMessage(n, n).c_str()); } // Tests formatting a char pointer when it's compared with another pointer. @@ -1464,8 +1432,7 @@ TEST(FormatForComparisonFailureMessageTest, WorksForCharPointerVsPointer) { // const char* const char* s = "hello"; - EXPECT_EQ(PrintPointer(s), - FormatForComparisonFailureMessage(s, s).c_str()); + EXPECT_EQ(PrintPointer(s), FormatForComparisonFailureMessage(s, s).c_str()); // char* char ch = 'a'; @@ -1482,8 +1449,7 @@ TEST(FormatForComparisonFailureMessageTest, WorksForWCharPointerVsPointer) { // const wchar_t* const wchar_t* s = L"hello"; - EXPECT_EQ(PrintPointer(s), - FormatForComparisonFailureMessage(s, s).c_str()); + EXPECT_EQ(PrintPointer(s), FormatForComparisonFailureMessage(s, s).c_str()); // wchar_t* wchar_t ch = L'a'; @@ -1580,13 +1546,11 @@ TEST(FormatForComparisonFailureMessageTest, WorksForWCharArrayVsStdWString) { // Useful for testing PrintToString(). We cannot use EXPECT_EQ() // there as its implementation uses PrintToString(). The caller must // ensure that 'value' has no side effect. -#define EXPECT_PRINT_TO_STRING_(value, expected_string) \ - EXPECT_TRUE(PrintToString(value) == (expected_string)) \ +#define EXPECT_PRINT_TO_STRING_(value, expected_string) \ + EXPECT_TRUE(PrintToString(value) == (expected_string)) \ << " where " #value " prints as " << (PrintToString(value)) -TEST(PrintToStringTest, WorksForScalar) { - EXPECT_PRINT_TO_STRING_(123, "123"); -} +TEST(PrintToStringTest, WorksForScalar) { EXPECT_PRINT_TO_STRING_(123, "123"); } TEST(PrintToStringTest, WorksForPointerToConstChar) { const char* p = "hello"; @@ -1611,7 +1575,7 @@ TEST(PrintToStringTest, EscapesForPointerToNonConstChar) { } TEST(PrintToStringTest, WorksForArray) { - int n[3] = { 1, 2, 3 }; + int n[3] = {1, 2, 3}; EXPECT_PRINT_TO_STRING_(n, "{ 1, 2, 3 }"); } @@ -1628,7 +1592,7 @@ TEST(PrintToStringTest, WorksForCharArrayWithEmbeddedNul) { EXPECT_PRINT_TO_STRING_(mutable_str_with_nul, "\"hello\\0 world\""); } - TEST(PrintToStringTest, ContainsNonLatin) { +TEST(PrintToStringTest, ContainsNonLatin) { // Test with valid UTF-8. Prints both in hex and as text. std::string non_ascii_str = ::std::string("오전 4:30"); EXPECT_PRINT_TO_STRING_(non_ascii_str, @@ -1645,57 +1609,58 @@ TEST(IsValidUTF8Test, IllFormedUTF8) { // as hex only (or ASCII, in case of ASCII bytes) because IsValidUTF8() is // expected to fail, thus output does not contain "As Text:". - static const char *const kTestdata[][2] = { - // 2-byte lead byte followed by a single-byte character. - {"\xC3\x74", "\"\\xC3t\""}, - // Valid 2-byte character followed by an orphan trail byte. - {"\xC3\x84\xA4", "\"\\xC3\\x84\\xA4\""}, - // Lead byte without trail byte. - {"abc\xC3", "\"abc\\xC3\""}, - // 3-byte lead byte, single-byte character, orphan trail byte. - {"x\xE2\x70\x94", "\"x\\xE2p\\x94\""}, - // Truncated 3-byte character. - {"\xE2\x80", "\"\\xE2\\x80\""}, - // Truncated 3-byte character followed by valid 2-byte char. - {"\xE2\x80\xC3\x84", "\"\\xE2\\x80\\xC3\\x84\""}, - // Truncated 3-byte character followed by a single-byte character. - {"\xE2\x80\x7A", "\"\\xE2\\x80z\""}, - // 3-byte lead byte followed by valid 3-byte character. - {"\xE2\xE2\x80\x94", "\"\\xE2\\xE2\\x80\\x94\""}, - // 4-byte lead byte followed by valid 3-byte character. - {"\xF0\xE2\x80\x94", "\"\\xF0\\xE2\\x80\\x94\""}, - // Truncated 4-byte character. - {"\xF0\xE2\x80", "\"\\xF0\\xE2\\x80\""}, - // Invalid UTF-8 byte sequences embedded in other chars. - {"abc\xE2\x80\x94\xC3\x74xyc", "\"abc\\xE2\\x80\\x94\\xC3txyc\""}, - {"abc\xC3\x84\xE2\x80\xC3\x84xyz", - "\"abc\\xC3\\x84\\xE2\\x80\\xC3\\x84xyz\""}, - // Non-shortest UTF-8 byte sequences are also ill-formed. - // The classics: xC0, xC1 lead byte. - {"\xC0\x80", "\"\\xC0\\x80\""}, - {"\xC1\x81", "\"\\xC1\\x81\""}, - // Non-shortest sequences. - {"\xE0\x80\x80", "\"\\xE0\\x80\\x80\""}, - {"\xf0\x80\x80\x80", "\"\\xF0\\x80\\x80\\x80\""}, - // Last valid code point before surrogate range, should be printed as text, - // too. - {"\xED\x9F\xBF", "\"\\xED\\x9F\\xBF\"\n As Text: \"\""}, - // Start of surrogate lead. Surrogates are not printed as text. - {"\xED\xA0\x80", "\"\\xED\\xA0\\x80\""}, - // Last non-private surrogate lead. - {"\xED\xAD\xBF", "\"\\xED\\xAD\\xBF\""}, - // First private-use surrogate lead. - {"\xED\xAE\x80", "\"\\xED\\xAE\\x80\""}, - // Last private-use surrogate lead. - {"\xED\xAF\xBF", "\"\\xED\\xAF\\xBF\""}, - // Mid-point of surrogate trail. - {"\xED\xB3\xBF", "\"\\xED\\xB3\\xBF\""}, - // First valid code point after surrogate range, should be printed as text, - // too. - {"\xEE\x80\x80", "\"\\xEE\\x80\\x80\"\n As Text: \"\""} - }; - - for (int i = 0; i < int(sizeof(kTestdata)/sizeof(kTestdata[0])); ++i) { + static const char* const kTestdata[][2] = { + // 2-byte lead byte followed by a single-byte character. + {"\xC3\x74", "\"\\xC3t\""}, + // Valid 2-byte character followed by an orphan trail byte. + {"\xC3\x84\xA4", "\"\\xC3\\x84\\xA4\""}, + // Lead byte without trail byte. + {"abc\xC3", "\"abc\\xC3\""}, + // 3-byte lead byte, single-byte character, orphan trail byte. + {"x\xE2\x70\x94", "\"x\\xE2p\\x94\""}, + // Truncated 3-byte character. + {"\xE2\x80", "\"\\xE2\\x80\""}, + // Truncated 3-byte character followed by valid 2-byte char. + {"\xE2\x80\xC3\x84", "\"\\xE2\\x80\\xC3\\x84\""}, + // Truncated 3-byte character followed by a single-byte character. + {"\xE2\x80\x7A", "\"\\xE2\\x80z\""}, + // 3-byte lead byte followed by valid 3-byte character. + {"\xE2\xE2\x80\x94", "\"\\xE2\\xE2\\x80\\x94\""}, + // 4-byte lead byte followed by valid 3-byte character. + {"\xF0\xE2\x80\x94", "\"\\xF0\\xE2\\x80\\x94\""}, + // Truncated 4-byte character. + {"\xF0\xE2\x80", "\"\\xF0\\xE2\\x80\""}, + // Invalid UTF-8 byte sequences embedded in other chars. + {"abc\xE2\x80\x94\xC3\x74xyc", "\"abc\\xE2\\x80\\x94\\xC3txyc\""}, + {"abc\xC3\x84\xE2\x80\xC3\x84xyz", + "\"abc\\xC3\\x84\\xE2\\x80\\xC3\\x84xyz\""}, + // Non-shortest UTF-8 byte sequences are also ill-formed. + // The classics: xC0, xC1 lead byte. + {"\xC0\x80", "\"\\xC0\\x80\""}, + {"\xC1\x81", "\"\\xC1\\x81\""}, + // Non-shortest sequences. + {"\xE0\x80\x80", "\"\\xE0\\x80\\x80\""}, + {"\xf0\x80\x80\x80", "\"\\xF0\\x80\\x80\\x80\""}, + // Last valid code point before surrogate range, should be printed as + // text, + // too. + {"\xED\x9F\xBF", "\"\\xED\\x9F\\xBF\"\n As Text: \"\""}, + // Start of surrogate lead. Surrogates are not printed as text. + {"\xED\xA0\x80", "\"\\xED\\xA0\\x80\""}, + // Last non-private surrogate lead. + {"\xED\xAD\xBF", "\"\\xED\\xAD\\xBF\""}, + // First private-use surrogate lead. + {"\xED\xAE\x80", "\"\\xED\\xAE\\x80\""}, + // Last private-use surrogate lead. + {"\xED\xAF\xBF", "\"\\xED\\xAF\\xBF\""}, + // Mid-point of surrogate trail. + {"\xED\xB3\xBF", "\"\\xED\\xB3\\xBF\""}, + // First valid code point after surrogate range, should be printed as + // text, + // too. + {"\xEE\x80\x80", "\"\\xEE\\x80\\x80\"\n As Text: \"\""}}; + + for (int i = 0; i < int(sizeof(kTestdata) / sizeof(kTestdata[0])); ++i) { EXPECT_PRINT_TO_STRING_(kTestdata[i][0], kTestdata[i][1]); } } @@ -1844,15 +1809,15 @@ TEST(UniversalTersePrintTupleFieldsToStringsTestWithStd, PrintsEmptyTuple) { } TEST(UniversalTersePrintTupleFieldsToStringsTestWithStd, PrintsOneTuple) { - Strings result = UniversalTersePrintTupleFieldsToStrings( - ::std::make_tuple(1)); + Strings result = + UniversalTersePrintTupleFieldsToStrings(::std::make_tuple(1)); ASSERT_EQ(1u, result.size()); EXPECT_EQ("1", result[0]); } TEST(UniversalTersePrintTupleFieldsToStringsTestWithStd, PrintsTwoTuple) { - Strings result = UniversalTersePrintTupleFieldsToStrings( - ::std::make_tuple(1, 'a')); + Strings result = + UniversalTersePrintTupleFieldsToStrings(::std::make_tuple(1, 'a')); ASSERT_EQ(2u, result.size()); EXPECT_EQ("1", result[0]); EXPECT_EQ("'a' (97, 0x61)", result[1]); diff --git a/googletest/test/googletest-setuptestsuite-test_.cc b/googletest/test/googletest-setuptestsuite-test_.cc index a4bc4ef..d20899f 100644 --- a/googletest/test/googletest-setuptestsuite-test_.cc +++ b/googletest/test/googletest-setuptestsuite-test_.cc @@ -27,23 +27,18 @@ // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - #include "gtest/gtest.h" class SetupFailTest : public ::testing::Test { protected: - static void SetUpTestSuite() { - ASSERT_EQ("", "SET_UP_FAIL"); - } + static void SetUpTestSuite() { ASSERT_EQ("", "SET_UP_FAIL"); } }; TEST_F(SetupFailTest, NoopPassingTest) {} class TearDownFailTest : public ::testing::Test { protected: - static void TearDownTestSuite() { - ASSERT_EQ("", "TEAR_DOWN_FAIL"); - } + static void TearDownTestSuite() { ASSERT_EQ("", "TEAR_DOWN_FAIL"); } }; TEST_F(TearDownFailTest, NoopPassingTest) {} diff --git a/googletest/test/googletest-shuffle-test_.cc b/googletest/test/googletest-shuffle-test_.cc index 4505663..a14e22f 100644 --- a/googletest/test/googletest-shuffle-test_.cc +++ b/googletest/test/googletest-shuffle-test_.cc @@ -27,7 +27,6 @@ // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - // Verifies that test shuffling works. #include "gtest/gtest.h" @@ -88,7 +87,7 @@ class TestNamePrinter : public EmptyTestEventListener { } // namespace -int main(int argc, char **argv) { +int main(int argc, char** argv) { InitGoogleTest(&argc, argv); // Replaces the default printer with TestNamePrinter, which prints diff --git a/googletest/test/googletest-test-part-test.cc b/googletest/test/googletest-test-part-test.cc index 44cf7ca..076e5be 100644 --- a/googletest/test/googletest-test-part-test.cc +++ b/googletest/test/googletest-test-part-test.cc @@ -28,7 +28,6 @@ // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include "gtest/gtest-test-part.h" - #include "gtest/gtest.h" using testing::Message; @@ -52,17 +51,14 @@ class TestPartResultTest : public Test { TestPartResult r1_, r2_, r3_, r4_; }; - TEST_F(TestPartResultTest, ConstructorWorks) { Message message; message << "something is terribly wrong"; message << static_cast<const char*>(testing::internal::kStackTraceMarker); message << "some unimportant stack trace"; - const TestPartResult result(TestPartResult::kNonFatalFailure, - "some_file.cc", - 42, - message.GetString().c_str()); + const TestPartResult result(TestPartResult::kNonFatalFailure, "some_file.cc", + 42, message.GetString().c_str()); EXPECT_EQ(TestPartResult::kNonFatalFailure, result.type()); EXPECT_STREQ("some_file.cc", result.file_name()); @@ -72,9 +68,7 @@ TEST_F(TestPartResultTest, ConstructorWorks) { } TEST_F(TestPartResultTest, ResultAccessorsWork) { - const TestPartResult success(TestPartResult::kSuccess, - "file.cc", - 42, + const TestPartResult success(TestPartResult::kSuccess, "file.cc", 42, "message"); EXPECT_TRUE(success.passed()); EXPECT_FALSE(success.failed()); @@ -83,19 +77,15 @@ TEST_F(TestPartResultTest, ResultAccessorsWork) { EXPECT_FALSE(success.skipped()); const TestPartResult nonfatal_failure(TestPartResult::kNonFatalFailure, - "file.cc", - 42, - "message"); + "file.cc", 42, "message"); EXPECT_FALSE(nonfatal_failure.passed()); EXPECT_TRUE(nonfatal_failure.failed()); EXPECT_TRUE(nonfatal_failure.nonfatally_failed()); EXPECT_FALSE(nonfatal_failure.fatally_failed()); EXPECT_FALSE(nonfatal_failure.skipped()); - const TestPartResult fatal_failure(TestPartResult::kFatalFailure, - "file.cc", - 42, - "message"); + const TestPartResult fatal_failure(TestPartResult::kFatalFailure, "file.cc", + 42, "message"); EXPECT_FALSE(fatal_failure.passed()); EXPECT_TRUE(fatal_failure.failed()); EXPECT_FALSE(fatal_failure.nonfatally_failed()); diff --git a/googletest/test/googletest-throw-on-failure-test_.cc b/googletest/test/googletest-throw-on-failure-test_.cc index 83bb914..3b81a5a 100644 --- a/googletest/test/googletest-throw-on-failure-test_.cc +++ b/googletest/test/googletest-throw-on-failure-test_.cc @@ -27,18 +27,18 @@ // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - // Tests Google Test's throw-on-failure mode with exceptions disabled. // // This program must be compiled with exceptions disabled. It will be // invoked by googletest-throw-on-failure-test.py, and is expected to exit // with non-zero in the throw-on-failure mode or 0 otherwise. -#include "gtest/gtest.h" +#include <stdio.h> // for fflush, fprintf, NULL, etc. +#include <stdlib.h> // for exit -#include <stdio.h> // for fflush, fprintf, NULL, etc. -#include <stdlib.h> // for exit -#include <exception> // for set_terminate +#include <exception> // for set_terminate + +#include "gtest/gtest.h" // This terminate handler aborts the program using exit() rather than abort(). // This avoids showing pop-ups on Windows systems and core dumps on Unix-like diff --git a/googletest/test/googletest-uninitialized-test_.cc b/googletest/test/googletest-uninitialized-test_.cc index b4434d5..88b61fc 100644 --- a/googletest/test/googletest-uninitialized-test_.cc +++ b/googletest/test/googletest-uninitialized-test_.cc @@ -27,7 +27,6 @@ // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - #include "gtest/gtest.h" TEST(DummyTest, Dummy) { @@ -37,6 +36,4 @@ TEST(DummyTest, Dummy) { // testing::InitGoogleTest() being called first. } -int main() { - return RUN_ALL_TESTS(); -} +int main() { return RUN_ALL_TESTS(); } diff --git a/googletest/test/gtest-typed-test2_test.cc b/googletest/test/gtest-typed-test2_test.cc index e83ca2e..f2eae12 100644 --- a/googletest/test/gtest-typed-test2_test.cc +++ b/googletest/test/gtest-typed-test2_test.cc @@ -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. - #include <vector> -#include "test/gtest-typed-test_test.h" #include "gtest/gtest.h" +#include "test/gtest-typed-test_test.h" // Tests that the same type-parameterized test case can be // instantiated in different translation units linked together. diff --git a/googletest/test/gtest-typed-test_test.cc b/googletest/test/gtest-typed-test_test.cc index 5fc678c..af23f86 100644 --- a/googletest/test/gtest-typed-test_test.cc +++ b/googletest/test/gtest-typed-test_test.cc @@ -27,7 +27,6 @@ // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - #include "test/gtest-typed-test_test.h" #include <set> @@ -50,9 +49,7 @@ class CommonTest : public Test { // For some technical reason, SetUpTestSuite() and TearDownTestSuite() // must be public. public: - static void SetUpTestSuite() { - shared_ = new T(5); - } + static void SetUpTestSuite() { shared_ = new T(5); } static void TearDownTestSuite() { delete shared_; @@ -130,8 +127,7 @@ TYPED_TEST(CommonTest, ValuesAreStillCorrect) { // translation unit. template <typename T> -class TypedTest1 : public Test { -}; +class TypedTest1 : public Test {}; // Verifies that the second argument of TYPED_TEST_SUITE can be a // single type. @@ -139,8 +135,7 @@ TYPED_TEST_SUITE(TypedTest1, int); TYPED_TEST(TypedTest1, A) {} template <typename T> -class TypedTest2 : public Test { -}; +class TypedTest2 : public Test {}; // Verifies that the second argument of TYPED_TEST_SUITE can be a // Types<...> type list. @@ -155,15 +150,12 @@ TYPED_TEST(TypedTest2, A) {} namespace library1 { template <typename T> -class NumericTest : public Test { -}; +class NumericTest : public Test {}; typedef Types<int, long> NumericTypes; TYPED_TEST_SUITE(NumericTest, NumericTypes); -TYPED_TEST(NumericTest, DefaultIsZero) { - EXPECT_EQ(0, TypeParam()); -} +TYPED_TEST(NumericTest, DefaultIsZero) { EXPECT_EQ(0, TypeParam()); } } // namespace library1 @@ -265,8 +257,7 @@ TEST_F(TypedTestSuitePStateDeathTest, DetectsTestAfterRegistration) { // and SetUp()/TearDown() work correctly in type-parameterized tests. template <typename T> -class DerivedTest : public CommonTest<T> { -}; +class DerivedTest : public CommonTest<T> {}; TYPED_TEST_SUITE_P(DerivedTest); @@ -290,8 +281,8 @@ TYPED_TEST_P(DerivedTest, ValuesAreStillCorrect) { EXPECT_EQ(2, this->value_); } -REGISTER_TYPED_TEST_SUITE_P(DerivedTest, - ValuesAreCorrect, ValuesAreStillCorrect); +REGISTER_TYPED_TEST_SUITE_P(DerivedTest, ValuesAreCorrect, + ValuesAreStillCorrect); typedef Types<short, long> MyTwoTypes; INSTANTIATE_TYPED_TEST_SUITE_P(My, DerivedTest, MyTwoTypes); @@ -334,14 +325,13 @@ class TypeParametrizedTestNames { }; INSTANTIATE_TYPED_TEST_SUITE_P(CustomName, TypeParametrizedTestWithNames, - TwoTypes, TypeParametrizedTestNames); + TwoTypes, TypeParametrizedTestNames); // Tests that multiple TYPED_TEST_SUITE_P's can be defined in the same // translation unit. template <typename T> -class TypedTestP1 : public Test { -}; +class TypedTestP1 : public Test {}; TYPED_TEST_SUITE_P(TypedTestP1); @@ -359,8 +349,7 @@ using IntBeforeRegisterTypedTestSuiteP = int; REGISTER_TYPED_TEST_SUITE_P(TypedTestP1, A, B); template <typename T> -class TypedTestP2 : public Test { -}; +class TypedTestP2 : public Test {}; TYPED_TEST_SUITE_P(TypedTestP2); @@ -396,21 +385,17 @@ INSTANTIATE_TYPED_TEST_SUITE_P(My, ContainerTest, MyContainers); namespace library2 { template <typename T> -class NumericTest : public Test { -}; +class NumericTest : public Test {}; TYPED_TEST_SUITE_P(NumericTest); -TYPED_TEST_P(NumericTest, DefaultIsZero) { - EXPECT_EQ(0, TypeParam()); -} +TYPED_TEST_P(NumericTest, DefaultIsZero) { EXPECT_EQ(0, TypeParam()); } TYPED_TEST_P(NumericTest, ZeroIsLessThanOne) { EXPECT_LT(TypeParam(0), TypeParam(1)); } -REGISTER_TYPED_TEST_SUITE_P(NumericTest, - DefaultIsZero, ZeroIsLessThanOne); +REGISTER_TYPED_TEST_SUITE_P(NumericTest, DefaultIsZero, ZeroIsLessThanOne); typedef Types<int, double> NumericTypes; INSTANTIATE_TYPED_TEST_SUITE_P(My, NumericTest, NumericTypes); @@ -418,20 +403,20 @@ static const char* GetTestName() { return testing::UnitTest::GetInstance()->current_test_info()->name(); } // Test the stripping of space from test names -template <typename T> class TrimmedTest : public Test { }; +template <typename T> +class TrimmedTest : public Test {}; TYPED_TEST_SUITE_P(TrimmedTest); TYPED_TEST_P(TrimmedTest, Test1) { EXPECT_STREQ("Test1", GetTestName()); } TYPED_TEST_P(TrimmedTest, Test2) { EXPECT_STREQ("Test2", GetTestName()); } TYPED_TEST_P(TrimmedTest, Test3) { EXPECT_STREQ("Test3", GetTestName()); } TYPED_TEST_P(TrimmedTest, Test4) { EXPECT_STREQ("Test4", GetTestName()); } TYPED_TEST_P(TrimmedTest, Test5) { EXPECT_STREQ("Test5", GetTestName()); } -REGISTER_TYPED_TEST_SUITE_P( - TrimmedTest, - Test1, Test2,Test3 , Test4 ,Test5 ); // NOLINT -template <typename T1, typename T2> struct MyPair {}; +REGISTER_TYPED_TEST_SUITE_P(TrimmedTest, Test1, Test2, Test3, Test4, + Test5); // NOLINT +template <typename T1, typename T2> +struct MyPair {}; // Be sure to try a type with a comma in its name just in case it matters. typedef Types<int, double, MyPair<int, int> > TrimTypes; INSTANTIATE_TYPED_TEST_SUITE_P(My, TrimmedTest, TrimTypes); } // namespace library2 - diff --git a/googletest/test/gtest-typed-test_test.h b/googletest/test/gtest-typed-test_test.h index 8ce559c..f3ef0a5 100644 --- a/googletest/test/gtest-typed-test_test.h +++ b/googletest/test/gtest-typed-test_test.h @@ -40,21 +40,18 @@ using testing::Test; // and gtest-typed-test2_test.cc. template <typename T> -class ContainerTest : public Test { -}; +class ContainerTest : public Test {}; TYPED_TEST_SUITE_P(ContainerTest); -TYPED_TEST_P(ContainerTest, CanBeDefaultConstructed) { - TypeParam container; -} +TYPED_TEST_P(ContainerTest, CanBeDefaultConstructed) { TypeParam container; } TYPED_TEST_P(ContainerTest, InitialSizeIsZero) { TypeParam container; EXPECT_EQ(0U, container.size()); } -REGISTER_TYPED_TEST_SUITE_P(ContainerTest, - CanBeDefaultConstructed, InitialSizeIsZero); +REGISTER_TYPED_TEST_SUITE_P(ContainerTest, CanBeDefaultConstructed, + InitialSizeIsZero); #endif // GOOGLETEST_TEST_GTEST_TYPED_TEST_TEST_H_ diff --git a/googletest/test/gtest-unittest-api_test.cc b/googletest/test/gtest-unittest-api_test.cc index 8ef5058..2a13fa3 100644 --- a/googletest/test/gtest-unittest-api_test.cc +++ b/googletest/test/gtest-unittest-api_test.cc @@ -32,11 +32,12 @@ // This file contains tests verifying correctness of data provided via // UnitTest's public methods. -#include "gtest/gtest.h" - #include <string.h> // For strcmp. + #include <algorithm> +#include "gtest/gtest.h" + using ::testing::InitGoogleTest; namespace testing { @@ -56,13 +57,12 @@ class UnitTestHelper { static TestSuite const** GetSortedTestSuites() { UnitTest& unit_test = *UnitTest::GetInstance(); auto const** const test_suites = new const TestSuite*[static_cast<size_t>( - unit_test.total_test_suite_count())]; + unit_test.total_test_suite_count())]; for (int i = 0; i < unit_test.total_test_suite_count(); ++i) test_suites[i] = unit_test.GetTestSuite(i); - std::sort(test_suites, - test_suites + unit_test.total_test_suite_count(), + std::sort(test_suites, test_suites + unit_test.total_test_suite_count(), LessByName<TestSuite>()); return test_suites; } @@ -73,8 +73,7 @@ class UnitTestHelper { UnitTest& unit_test = *UnitTest::GetInstance(); for (int i = 0; i < unit_test.total_test_suite_count(); ++i) { const TestSuite* test_suite = unit_test.GetTestSuite(i); - if (0 == strcmp(test_suite->name(), name)) - return test_suite; + if (0 == strcmp(test_suite->name(), name)) return test_suite; } return nullptr; } @@ -84,7 +83,7 @@ class UnitTestHelper { // array. static TestInfo const** GetSortedTests(const TestSuite* test_suite) { TestInfo const** const tests = new const TestInfo*[static_cast<size_t>( - test_suite->total_test_count())]; + test_suite->total_test_count())]; for (int i = 0; i < test_suite->total_test_count(); ++i) tests[i] = test_suite->GetTestInfo(i); @@ -95,7 +94,8 @@ class UnitTestHelper { } }; -template <typename T> class TestSuiteWithCommentTest : public Test {}; +template <typename T> +class TestSuiteWithCommentTest : public Test {}; TYPED_TEST_SUITE(TestSuiteWithCommentTest, Types<int>); TYPED_TEST(TestSuiteWithCommentTest, Dummy) {} @@ -319,7 +319,7 @@ class FinalSuccessChecker : public Environment { } // namespace internal } // namespace testing -int main(int argc, char **argv) { +int main(int argc, char** argv) { InitGoogleTest(&argc, argv); AddGlobalTestEnvironment(new testing::internal::FinalSuccessChecker()); diff --git a/googletest/test/gtest_assert_by_exception_test.cc b/googletest/test/gtest_assert_by_exception_test.cc index ada4cb3..f507eac 100644 --- a/googletest/test/gtest_assert_by_exception_test.cc +++ b/googletest/test/gtest_assert_by_exception_test.cc @@ -27,16 +27,16 @@ // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - // Tests Google Test's assert-by-exception mode with exceptions enabled. -#include "gtest/gtest.h" - -#include <stdlib.h> #include <stdio.h> +#include <stdlib.h> #include <string.h> + #include <stdexcept> +#include "gtest/gtest.h" + class ThrowListener : public testing::EmptyTestEventListener { void OnTestPartResult(const testing::TestPartResult& result) override { if (result.type() == testing::TestPartResult::kFatalFailure) { @@ -55,9 +55,7 @@ void Fail(const char* msg) { exit(1); } -static void AssertFalse() { - ASSERT_EQ(2, 3) << "Expected failure"; -} +static void AssertFalse() { ASSERT_EQ(2, 3) << "Expected failure"; } // Tests that an assertion failure throws a subclass of // std::runtime_error. @@ -65,21 +63,21 @@ TEST(Test, Test) { // A successful assertion shouldn't throw. try { EXPECT_EQ(3, 3); - } catch(...) { + } catch (...) { Fail("A successful assertion wrongfully threw."); } // A successful assertion shouldn't throw. try { EXPECT_EQ(3, 4); - } catch(...) { + } catch (...) { Fail("A failed non-fatal assertion wrongfully threw."); } // A failed assertion should throw. try { AssertFalse(); - } catch(const testing::AssertionException& e) { + } catch (const testing::AssertionException& e) { if (strstr(e.what(), "Expected failure") != nullptr) throw; printf("%s", @@ -87,7 +85,7 @@ TEST(Test, Test) { "but the message is incorrect. Instead of containing \"Expected " "failure\", it is:\n"); Fail(e.what()); - } catch(...) { + } catch (...) { Fail("A failed assertion threw the wrong type of exception."); } Fail("A failed assertion should've thrown but didn't."); @@ -95,9 +93,7 @@ TEST(Test, Test) { int kTestForContinuingTest = 0; -TEST(Test, Test2) { - kTestForContinuingTest = 1; -} +TEST(Test, Test2) { kTestForContinuingTest = 1; } int main(int argc, char** argv) { testing::InitGoogleTest(&argc, argv); diff --git a/googletest/test/gtest_environment_test.cc b/googletest/test/gtest_environment_test.cc index c7facf5..122eaf3 100644 --- a/googletest/test/gtest_environment_test.cc +++ b/googletest/test/gtest_environment_test.cc @@ -30,16 +30,15 @@ // // Tests using global test environments. -#include <stdlib.h> #include <stdio.h> +#include <stdlib.h> + #include "gtest/gtest.h" #include "src/gtest-internal-inl.h" namespace { -enum FailureType { - NO_FAILURE, NON_FATAL_FAILURE, FATAL_FAILURE -}; +enum FailureType { NO_FAILURE, NON_FATAL_FAILURE, FATAL_FAILURE }; // For testing using global test environments. class MyEnvironment : public testing::Environment { @@ -79,9 +78,7 @@ class MyEnvironment : public testing::Environment { // We call this function to set the type of failure SetUp() should // generate. - void set_failure_in_set_up(FailureType type) { - failure_in_set_up_ = type; - } + void set_failure_in_set_up(FailureType type) { failure_in_set_up_ = type; } // Was SetUp() run? bool set_up_was_run() const { return set_up_was_run_; } @@ -100,9 +97,7 @@ bool test_was_run; // The sole purpose of this TEST is to enable us to check whether it // was run. -TEST(FooTest, Bar) { - test_was_run = true; -} +TEST(FooTest, Bar) { test_was_run = true; } // Prints the message and aborts the program if condition is false. void Check(bool condition, const char* msg) { @@ -126,7 +121,7 @@ int RunAllTests(MyEnvironment* env, FailureType failure) { } // namespace -int main(int argc, char **argv) { +int main(int argc, char** argv) { testing::InitGoogleTest(&argc, argv); // Registers a global test environment, and verifies that the diff --git a/googletest/test/gtest_help_test_.cc b/googletest/test/gtest_help_test_.cc index 750ae6c..da289f0 100644 --- a/googletest/test/gtest_help_test_.cc +++ b/googletest/test/gtest_help_test_.cc @@ -27,7 +27,6 @@ // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - // This program is meant to be run by gtest_help_test.py. Do not run // it directly. diff --git a/googletest/test/gtest_json_test_utils.py b/googletest/test/gtest_json_test_utils.py index 62bbfc2..f62896c 100644 --- a/googletest/test/gtest_json_test_utils.py +++ b/googletest/test/gtest_json_test_utils.py @@ -50,6 +50,8 @@ def normalize(obj): elif key == 'failure': value = re.sub(r'^.*[/\\](.*:)\d+\n', '\\1*\n', value) return re.sub(r'Stack trace:\n(.|\n)*', 'Stack trace:\n*', value) + elif key == 'file': + return re.sub(r'^.*[/\\](.*)', '\\1', value) else: return normalize(value) if isinstance(obj, dict): diff --git a/googletest/test/gtest_main_unittest.cc b/googletest/test/gtest_main_unittest.cc index eddedea..29cd551 100644 --- a/googletest/test/gtest_main_unittest.cc +++ b/googletest/test/gtest_main_unittest.cc @@ -27,7 +27,6 @@ // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - #include "gtest/gtest.h" // Tests that we don't have to define main() when we link to @@ -35,8 +34,7 @@ namespace { -TEST(GTestMainTest, ShouldSucceed) { -} +TEST(GTestMainTest, ShouldSucceed) {} } // namespace diff --git a/googletest/test/gtest_pred_impl_unittest.cc b/googletest/test/gtest_pred_impl_unittest.cc index 01855f2..3d43665 100644 --- a/googletest/test/gtest_pred_impl_unittest.cc +++ b/googletest/test/gtest_pred_impl_unittest.cc @@ -46,8 +46,8 @@ #include <iostream> -#include "gtest/gtest.h" #include "gtest/gtest-spi.h" +#include "gtest/gtest.h" // A user-defined data type. struct Bool { @@ -77,12 +77,8 @@ bool PredFunction1(T1 v1) { // The following two functions are needed because a compiler doesn't have // a context yet to know which template function must be instantiated. -bool PredFunction1Int(int v1) { - return v1 > 0; -} -bool PredFunction1Bool(Bool v1) { - return v1 > 0; -} +bool PredFunction1Int(int v1) { return v1 > 0; } +bool PredFunction1Bool(Bool v1) { return v1 > 0; } // A unary predicate functor. struct PredFunctor1 { @@ -94,22 +90,17 @@ struct PredFunctor1 { // A unary predicate-formatter function. template <typename T1> -testing::AssertionResult PredFormatFunction1(const char* e1, - const T1& v1) { - if (PredFunction1(v1)) - return testing::AssertionSuccess(); +testing::AssertionResult PredFormatFunction1(const char* e1, const T1& v1) { + if (PredFunction1(v1)) return testing::AssertionSuccess(); return testing::AssertionFailure() - << e1 - << " is expected to be positive, but evaluates to " - << v1 << "."; + << e1 << " is expected to be positive, but evaluates to " << v1 << "."; } // A unary predicate-formatter functor. struct PredFormatFunctor1 { template <typename T1> - testing::AssertionResult operator()(const char* e1, - const T1& v1) const { + testing::AssertionResult operator()(const char* e1, const T1& v1) const { return PredFormatFunction1(e1, v1); } }; @@ -127,9 +118,8 @@ class Predicate1Test : public testing::Test { void TearDown() override { // Verifies that each of the predicate's arguments was evaluated // exactly once. - EXPECT_EQ(1, n1_) << - "The predicate assertion didn't evaluate argument 2 " - "exactly once."; + EXPECT_EQ(1, n1_) << "The predicate assertion didn't evaluate argument 2 " + "exactly once."; // Verifies that the control flow in the test function is expected. if (expected_to_finish_ && !finished_) { @@ -161,104 +151,100 @@ typedef Predicate1Test ASSERT_PRED1Test; // Tests a successful EXPECT_PRED1 where the // predicate-formatter is a function on a built-in type (int). TEST_F(EXPECT_PRED1Test, FunctionOnBuiltInTypeSuccess) { - EXPECT_PRED1(PredFunction1Int, - ++n1_); + EXPECT_PRED1(PredFunction1Int, ++n1_); finished_ = true; } // Tests a successful EXPECT_PRED1 where the // predicate-formatter is a function on a user-defined type (Bool). TEST_F(EXPECT_PRED1Test, FunctionOnUserTypeSuccess) { - EXPECT_PRED1(PredFunction1Bool, - Bool(++n1_)); + EXPECT_PRED1(PredFunction1Bool, Bool(++n1_)); finished_ = true; } // Tests a successful EXPECT_PRED1 where the // predicate-formatter is a functor on a built-in type (int). TEST_F(EXPECT_PRED1Test, FunctorOnBuiltInTypeSuccess) { - EXPECT_PRED1(PredFunctor1(), - ++n1_); + EXPECT_PRED1(PredFunctor1(), ++n1_); finished_ = true; } // Tests a successful EXPECT_PRED1 where the // predicate-formatter is a functor on a user-defined type (Bool). TEST_F(EXPECT_PRED1Test, FunctorOnUserTypeSuccess) { - EXPECT_PRED1(PredFunctor1(), - Bool(++n1_)); + EXPECT_PRED1(PredFunctor1(), Bool(++n1_)); finished_ = true; } // Tests a failed EXPECT_PRED1 where the // predicate-formatter is a function on a built-in type (int). TEST_F(EXPECT_PRED1Test, FunctionOnBuiltInTypeFailure) { - EXPECT_NONFATAL_FAILURE({ // NOLINT - EXPECT_PRED1(PredFunction1Int, - n1_++); - finished_ = true; - }, ""); + EXPECT_NONFATAL_FAILURE( + { // NOLINT + EXPECT_PRED1(PredFunction1Int, n1_++); + finished_ = true; + }, + ""); } // Tests a failed EXPECT_PRED1 where the // predicate-formatter is a function on a user-defined type (Bool). TEST_F(EXPECT_PRED1Test, FunctionOnUserTypeFailure) { - EXPECT_NONFATAL_FAILURE({ // NOLINT - EXPECT_PRED1(PredFunction1Bool, - Bool(n1_++)); - finished_ = true; - }, ""); + EXPECT_NONFATAL_FAILURE( + { // NOLINT + EXPECT_PRED1(PredFunction1Bool, Bool(n1_++)); + finished_ = true; + }, + ""); } // Tests a failed EXPECT_PRED1 where the // predicate-formatter is a functor on a built-in type (int). TEST_F(EXPECT_PRED1Test, FunctorOnBuiltInTypeFailure) { - EXPECT_NONFATAL_FAILURE({ // NOLINT - EXPECT_PRED1(PredFunctor1(), - n1_++); - finished_ = true; - }, ""); + EXPECT_NONFATAL_FAILURE( + { // NOLINT + EXPECT_PRED1(PredFunctor1(), n1_++); + finished_ = true; + }, + ""); } // Tests a failed EXPECT_PRED1 where the // predicate-formatter is a functor on a user-defined type (Bool). TEST_F(EXPECT_PRED1Test, FunctorOnUserTypeFailure) { - EXPECT_NONFATAL_FAILURE({ // NOLINT - EXPECT_PRED1(PredFunctor1(), - Bool(n1_++)); - finished_ = true; - }, ""); + EXPECT_NONFATAL_FAILURE( + { // NOLINT + EXPECT_PRED1(PredFunctor1(), Bool(n1_++)); + finished_ = true; + }, + ""); } // Tests a successful ASSERT_PRED1 where the // predicate-formatter is a function on a built-in type (int). TEST_F(ASSERT_PRED1Test, FunctionOnBuiltInTypeSuccess) { - ASSERT_PRED1(PredFunction1Int, - ++n1_); + ASSERT_PRED1(PredFunction1Int, ++n1_); finished_ = true; } // Tests a successful ASSERT_PRED1 where the // predicate-formatter is a function on a user-defined type (Bool). TEST_F(ASSERT_PRED1Test, FunctionOnUserTypeSuccess) { - ASSERT_PRED1(PredFunction1Bool, - Bool(++n1_)); + ASSERT_PRED1(PredFunction1Bool, Bool(++n1_)); finished_ = true; } // Tests a successful ASSERT_PRED1 where the // predicate-formatter is a functor on a built-in type (int). TEST_F(ASSERT_PRED1Test, FunctorOnBuiltInTypeSuccess) { - ASSERT_PRED1(PredFunctor1(), - ++n1_); + ASSERT_PRED1(PredFunctor1(), ++n1_); finished_ = true; } // Tests a successful ASSERT_PRED1 where the // predicate-formatter is a functor on a user-defined type (Bool). TEST_F(ASSERT_PRED1Test, FunctorOnUserTypeSuccess) { - ASSERT_PRED1(PredFunctor1(), - Bool(++n1_)); + ASSERT_PRED1(PredFunctor1(), Bool(++n1_)); finished_ = true; } @@ -266,147 +252,147 @@ TEST_F(ASSERT_PRED1Test, FunctorOnUserTypeSuccess) { // predicate-formatter is a function on a built-in type (int). TEST_F(ASSERT_PRED1Test, FunctionOnBuiltInTypeFailure) { expected_to_finish_ = false; - EXPECT_FATAL_FAILURE({ // NOLINT - ASSERT_PRED1(PredFunction1Int, - n1_++); - finished_ = true; - }, ""); + EXPECT_FATAL_FAILURE( + { // NOLINT + ASSERT_PRED1(PredFunction1Int, n1_++); + finished_ = true; + }, + ""); } // Tests a failed ASSERT_PRED1 where the // predicate-formatter is a function on a user-defined type (Bool). TEST_F(ASSERT_PRED1Test, FunctionOnUserTypeFailure) { expected_to_finish_ = false; - EXPECT_FATAL_FAILURE({ // NOLINT - ASSERT_PRED1(PredFunction1Bool, - Bool(n1_++)); - finished_ = true; - }, ""); + EXPECT_FATAL_FAILURE( + { // NOLINT + ASSERT_PRED1(PredFunction1Bool, Bool(n1_++)); + finished_ = true; + }, + ""); } // Tests a failed ASSERT_PRED1 where the // predicate-formatter is a functor on a built-in type (int). TEST_F(ASSERT_PRED1Test, FunctorOnBuiltInTypeFailure) { expected_to_finish_ = false; - EXPECT_FATAL_FAILURE({ // NOLINT - ASSERT_PRED1(PredFunctor1(), - n1_++); - finished_ = true; - }, ""); + EXPECT_FATAL_FAILURE( + { // NOLINT + ASSERT_PRED1(PredFunctor1(), n1_++); + finished_ = true; + }, + ""); } // Tests a failed ASSERT_PRED1 where the // predicate-formatter is a functor on a user-defined type (Bool). TEST_F(ASSERT_PRED1Test, FunctorOnUserTypeFailure) { expected_to_finish_ = false; - EXPECT_FATAL_FAILURE({ // NOLINT - ASSERT_PRED1(PredFunctor1(), - Bool(n1_++)); - finished_ = true; - }, ""); + EXPECT_FATAL_FAILURE( + { // NOLINT + ASSERT_PRED1(PredFunctor1(), Bool(n1_++)); + finished_ = true; + }, + ""); } // Tests a successful EXPECT_PRED_FORMAT1 where the // predicate-formatter is a function on a built-in type (int). TEST_F(EXPECT_PRED_FORMAT1Test, FunctionOnBuiltInTypeSuccess) { - EXPECT_PRED_FORMAT1(PredFormatFunction1, - ++n1_); + EXPECT_PRED_FORMAT1(PredFormatFunction1, ++n1_); finished_ = true; } // Tests a successful EXPECT_PRED_FORMAT1 where the // predicate-formatter is a function on a user-defined type (Bool). TEST_F(EXPECT_PRED_FORMAT1Test, FunctionOnUserTypeSuccess) { - EXPECT_PRED_FORMAT1(PredFormatFunction1, - Bool(++n1_)); + EXPECT_PRED_FORMAT1(PredFormatFunction1, Bool(++n1_)); finished_ = true; } // Tests a successful EXPECT_PRED_FORMAT1 where the // predicate-formatter is a functor on a built-in type (int). TEST_F(EXPECT_PRED_FORMAT1Test, FunctorOnBuiltInTypeSuccess) { - EXPECT_PRED_FORMAT1(PredFormatFunctor1(), - ++n1_); + EXPECT_PRED_FORMAT1(PredFormatFunctor1(), ++n1_); finished_ = true; } // Tests a successful EXPECT_PRED_FORMAT1 where the // predicate-formatter is a functor on a user-defined type (Bool). TEST_F(EXPECT_PRED_FORMAT1Test, FunctorOnUserTypeSuccess) { - EXPECT_PRED_FORMAT1(PredFormatFunctor1(), - Bool(++n1_)); + EXPECT_PRED_FORMAT1(PredFormatFunctor1(), Bool(++n1_)); finished_ = true; } // Tests a failed EXPECT_PRED_FORMAT1 where the // predicate-formatter is a function on a built-in type (int). TEST_F(EXPECT_PRED_FORMAT1Test, FunctionOnBuiltInTypeFailure) { - EXPECT_NONFATAL_FAILURE({ // NOLINT - EXPECT_PRED_FORMAT1(PredFormatFunction1, - n1_++); - finished_ = true; - }, ""); + EXPECT_NONFATAL_FAILURE( + { // NOLINT + EXPECT_PRED_FORMAT1(PredFormatFunction1, n1_++); + finished_ = true; + }, + ""); } // Tests a failed EXPECT_PRED_FORMAT1 where the // predicate-formatter is a function on a user-defined type (Bool). TEST_F(EXPECT_PRED_FORMAT1Test, FunctionOnUserTypeFailure) { - EXPECT_NONFATAL_FAILURE({ // NOLINT - EXPECT_PRED_FORMAT1(PredFormatFunction1, - Bool(n1_++)); - finished_ = true; - }, ""); + EXPECT_NONFATAL_FAILURE( + { // NOLINT + EXPECT_PRED_FORMAT1(PredFormatFunction1, Bool(n1_++)); + finished_ = true; + }, + ""); } // Tests a failed EXPECT_PRED_FORMAT1 where the // predicate-formatter is a functor on a built-in type (int). TEST_F(EXPECT_PRED_FORMAT1Test, FunctorOnBuiltInTypeFailure) { - EXPECT_NONFATAL_FAILURE({ // NOLINT - EXPECT_PRED_FORMAT1(PredFormatFunctor1(), - n1_++); - finished_ = true; - }, ""); + EXPECT_NONFATAL_FAILURE( + { // NOLINT + EXPECT_PRED_FORMAT1(PredFormatFunctor1(), n1_++); + finished_ = true; + }, + ""); } // Tests a failed EXPECT_PRED_FORMAT1 where the // predicate-formatter is a functor on a user-defined type (Bool). TEST_F(EXPECT_PRED_FORMAT1Test, FunctorOnUserTypeFailure) { - EXPECT_NONFATAL_FAILURE({ // NOLINT - EXPECT_PRED_FORMAT1(PredFormatFunctor1(), - Bool(n1_++)); - finished_ = true; - }, ""); + EXPECT_NONFATAL_FAILURE( + { // NOLINT + EXPECT_PRED_FORMAT1(PredFormatFunctor1(), Bool(n1_++)); + finished_ = true; + }, + ""); } // Tests a successful ASSERT_PRED_FORMAT1 where the // predicate-formatter is a function on a built-in type (int). TEST_F(ASSERT_PRED_FORMAT1Test, FunctionOnBuiltInTypeSuccess) { - ASSERT_PRED_FORMAT1(PredFormatFunction1, - ++n1_); + ASSERT_PRED_FORMAT1(PredFormatFunction1, ++n1_); finished_ = true; } // Tests a successful ASSERT_PRED_FORMAT1 where the // predicate-formatter is a function on a user-defined type (Bool). TEST_F(ASSERT_PRED_FORMAT1Test, FunctionOnUserTypeSuccess) { - ASSERT_PRED_FORMAT1(PredFormatFunction1, - Bool(++n1_)); + ASSERT_PRED_FORMAT1(PredFormatFunction1, Bool(++n1_)); finished_ = true; } // Tests a successful ASSERT_PRED_FORMAT1 where the // predicate-formatter is a functor on a built-in type (int). TEST_F(ASSERT_PRED_FORMAT1Test, FunctorOnBuiltInTypeSuccess) { - ASSERT_PRED_FORMAT1(PredFormatFunctor1(), - ++n1_); + ASSERT_PRED_FORMAT1(PredFormatFunctor1(), ++n1_); finished_ = true; } // Tests a successful ASSERT_PRED_FORMAT1 where the // predicate-formatter is a functor on a user-defined type (Bool). TEST_F(ASSERT_PRED_FORMAT1Test, FunctorOnUserTypeSuccess) { - ASSERT_PRED_FORMAT1(PredFormatFunctor1(), - Bool(++n1_)); + ASSERT_PRED_FORMAT1(PredFormatFunctor1(), Bool(++n1_)); finished_ = true; } @@ -414,44 +400,48 @@ TEST_F(ASSERT_PRED_FORMAT1Test, FunctorOnUserTypeSuccess) { // predicate-formatter is a function on a built-in type (int). TEST_F(ASSERT_PRED_FORMAT1Test, FunctionOnBuiltInTypeFailure) { expected_to_finish_ = false; - EXPECT_FATAL_FAILURE({ // NOLINT - ASSERT_PRED_FORMAT1(PredFormatFunction1, - n1_++); - finished_ = true; - }, ""); + EXPECT_FATAL_FAILURE( + { // NOLINT + ASSERT_PRED_FORMAT1(PredFormatFunction1, n1_++); + finished_ = true; + }, + ""); } // Tests a failed ASSERT_PRED_FORMAT1 where the // predicate-formatter is a function on a user-defined type (Bool). TEST_F(ASSERT_PRED_FORMAT1Test, FunctionOnUserTypeFailure) { expected_to_finish_ = false; - EXPECT_FATAL_FAILURE({ // NOLINT - ASSERT_PRED_FORMAT1(PredFormatFunction1, - Bool(n1_++)); - finished_ = true; - }, ""); + EXPECT_FATAL_FAILURE( + { // NOLINT + ASSERT_PRED_FORMAT1(PredFormatFunction1, Bool(n1_++)); + finished_ = true; + }, + ""); } // Tests a failed ASSERT_PRED_FORMAT1 where the // predicate-formatter is a functor on a built-in type (int). TEST_F(ASSERT_PRED_FORMAT1Test, FunctorOnBuiltInTypeFailure) { expected_to_finish_ = false; - EXPECT_FATAL_FAILURE({ // NOLINT - ASSERT_PRED_FORMAT1(PredFormatFunctor1(), - n1_++); - finished_ = true; - }, ""); + EXPECT_FATAL_FAILURE( + { // NOLINT + ASSERT_PRED_FORMAT1(PredFormatFunctor1(), n1_++); + finished_ = true; + }, + ""); } // Tests a failed ASSERT_PRED_FORMAT1 where the // predicate-formatter is a functor on a user-defined type (Bool). TEST_F(ASSERT_PRED_FORMAT1Test, FunctorOnUserTypeFailure) { expected_to_finish_ = false; - EXPECT_FATAL_FAILURE({ // NOLINT - ASSERT_PRED_FORMAT1(PredFormatFunctor1(), - Bool(n1_++)); - finished_ = true; - }, ""); + EXPECT_FATAL_FAILURE( + { // NOLINT + ASSERT_PRED_FORMAT1(PredFormatFunctor1(), Bool(n1_++)); + finished_ = true; + }, + ""); } // Sample functions/functors for testing binary predicate assertions. @@ -463,44 +453,33 @@ bool PredFunction2(T1 v1, T2 v2) { // The following two functions are needed because a compiler doesn't have // a context yet to know which template function must be instantiated. -bool PredFunction2Int(int v1, int v2) { - return v1 + v2 > 0; -} -bool PredFunction2Bool(Bool v1, Bool v2) { - return v1 + v2 > 0; -} +bool PredFunction2Int(int v1, int v2) { return v1 + v2 > 0; } +bool PredFunction2Bool(Bool v1, Bool v2) { return v1 + v2 > 0; } // A binary predicate functor. struct PredFunctor2 { template <typename T1, typename T2> - bool operator()(const T1& v1, - const T2& v2) { + bool operator()(const T1& v1, const T2& v2) { return v1 + v2 > 0; } }; // A binary predicate-formatter function. template <typename T1, typename T2> -testing::AssertionResult PredFormatFunction2(const char* e1, - const char* e2, - const T1& v1, - const T2& v2) { - if (PredFunction2(v1, v2)) - return testing::AssertionSuccess(); +testing::AssertionResult PredFormatFunction2(const char* e1, const char* e2, + const T1& v1, const T2& v2) { + if (PredFunction2(v1, v2)) return testing::AssertionSuccess(); return testing::AssertionFailure() - << e1 << " + " << e2 - << " is expected to be positive, but evaluates to " - << v1 + v2 << "."; + << e1 << " + " << e2 + << " is expected to be positive, but evaluates to " << v1 + v2 << "."; } // A binary predicate-formatter functor. struct PredFormatFunctor2 { template <typename T1, typename T2> - testing::AssertionResult operator()(const char* e1, - const char* e2, - const T1& v1, - const T2& v2) const { + testing::AssertionResult operator()(const char* e1, const char* e2, + const T1& v1, const T2& v2) const { return PredFormatFunction2(e1, e2, v1, v2); } }; @@ -518,12 +497,10 @@ class Predicate2Test : public testing::Test { void TearDown() override { // Verifies that each of the predicate's arguments was evaluated // exactly once. - EXPECT_EQ(1, n1_) << - "The predicate assertion didn't evaluate argument 2 " - "exactly once."; - EXPECT_EQ(1, n2_) << - "The predicate assertion didn't evaluate argument 3 " - "exactly once."; + EXPECT_EQ(1, n1_) << "The predicate assertion didn't evaluate argument 2 " + "exactly once."; + EXPECT_EQ(1, n2_) << "The predicate assertion didn't evaluate argument 3 " + "exactly once."; // Verifies that the control flow in the test function is expected. if (expected_to_finish_ && !finished_) { @@ -557,116 +534,100 @@ typedef Predicate2Test ASSERT_PRED2Test; // Tests a successful EXPECT_PRED2 where the // predicate-formatter is a function on a built-in type (int). TEST_F(EXPECT_PRED2Test, FunctionOnBuiltInTypeSuccess) { - EXPECT_PRED2(PredFunction2Int, - ++n1_, - ++n2_); + EXPECT_PRED2(PredFunction2Int, ++n1_, ++n2_); finished_ = true; } // Tests a successful EXPECT_PRED2 where the // predicate-formatter is a function on a user-defined type (Bool). TEST_F(EXPECT_PRED2Test, FunctionOnUserTypeSuccess) { - EXPECT_PRED2(PredFunction2Bool, - Bool(++n1_), - Bool(++n2_)); + EXPECT_PRED2(PredFunction2Bool, Bool(++n1_), Bool(++n2_)); finished_ = true; } // Tests a successful EXPECT_PRED2 where the // predicate-formatter is a functor on a built-in type (int). TEST_F(EXPECT_PRED2Test, FunctorOnBuiltInTypeSuccess) { - EXPECT_PRED2(PredFunctor2(), - ++n1_, - ++n2_); + EXPECT_PRED2(PredFunctor2(), ++n1_, ++n2_); finished_ = true; } // Tests a successful EXPECT_PRED2 where the // predicate-formatter is a functor on a user-defined type (Bool). TEST_F(EXPECT_PRED2Test, FunctorOnUserTypeSuccess) { - EXPECT_PRED2(PredFunctor2(), - Bool(++n1_), - Bool(++n2_)); + EXPECT_PRED2(PredFunctor2(), Bool(++n1_), Bool(++n2_)); finished_ = true; } // Tests a failed EXPECT_PRED2 where the // predicate-formatter is a function on a built-in type (int). TEST_F(EXPECT_PRED2Test, FunctionOnBuiltInTypeFailure) { - EXPECT_NONFATAL_FAILURE({ // NOLINT - EXPECT_PRED2(PredFunction2Int, - n1_++, - n2_++); - finished_ = true; - }, ""); + EXPECT_NONFATAL_FAILURE( + { // NOLINT + EXPECT_PRED2(PredFunction2Int, n1_++, n2_++); + finished_ = true; + }, + ""); } // Tests a failed EXPECT_PRED2 where the // predicate-formatter is a function on a user-defined type (Bool). TEST_F(EXPECT_PRED2Test, FunctionOnUserTypeFailure) { - EXPECT_NONFATAL_FAILURE({ // NOLINT - EXPECT_PRED2(PredFunction2Bool, - Bool(n1_++), - Bool(n2_++)); - finished_ = true; - }, ""); + EXPECT_NONFATAL_FAILURE( + { // NOLINT + EXPECT_PRED2(PredFunction2Bool, Bool(n1_++), Bool(n2_++)); + finished_ = true; + }, + ""); } // Tests a failed EXPECT_PRED2 where the // predicate-formatter is a functor on a built-in type (int). TEST_F(EXPECT_PRED2Test, FunctorOnBuiltInTypeFailure) { - EXPECT_NONFATAL_FAILURE({ // NOLINT - EXPECT_PRED2(PredFunctor2(), - n1_++, - n2_++); - finished_ = true; - }, ""); + EXPECT_NONFATAL_FAILURE( + { // NOLINT + EXPECT_PRED2(PredFunctor2(), n1_++, n2_++); + finished_ = true; + }, + ""); } // Tests a failed EXPECT_PRED2 where the // predicate-formatter is a functor on a user-defined type (Bool). TEST_F(EXPECT_PRED2Test, FunctorOnUserTypeFailure) { - EXPECT_NONFATAL_FAILURE({ // NOLINT - EXPECT_PRED2(PredFunctor2(), - Bool(n1_++), - Bool(n2_++)); - finished_ = true; - }, ""); + EXPECT_NONFATAL_FAILURE( + { // NOLINT + EXPECT_PRED2(PredFunctor2(), Bool(n1_++), Bool(n2_++)); + finished_ = true; + }, + ""); } // Tests a successful ASSERT_PRED2 where the // predicate-formatter is a function on a built-in type (int). TEST_F(ASSERT_PRED2Test, FunctionOnBuiltInTypeSuccess) { - ASSERT_PRED2(PredFunction2Int, - ++n1_, - ++n2_); + ASSERT_PRED2(PredFunction2Int, ++n1_, ++n2_); finished_ = true; } // Tests a successful ASSERT_PRED2 where the // predicate-formatter is a function on a user-defined type (Bool). TEST_F(ASSERT_PRED2Test, FunctionOnUserTypeSuccess) { - ASSERT_PRED2(PredFunction2Bool, - Bool(++n1_), - Bool(++n2_)); + ASSERT_PRED2(PredFunction2Bool, Bool(++n1_), Bool(++n2_)); finished_ = true; } // Tests a successful ASSERT_PRED2 where the // predicate-formatter is a functor on a built-in type (int). TEST_F(ASSERT_PRED2Test, FunctorOnBuiltInTypeSuccess) { - ASSERT_PRED2(PredFunctor2(), - ++n1_, - ++n2_); + ASSERT_PRED2(PredFunctor2(), ++n1_, ++n2_); finished_ = true; } // Tests a successful ASSERT_PRED2 where the // predicate-formatter is a functor on a user-defined type (Bool). TEST_F(ASSERT_PRED2Test, FunctorOnUserTypeSuccess) { - ASSERT_PRED2(PredFunctor2(), - Bool(++n1_), - Bool(++n2_)); + ASSERT_PRED2(PredFunctor2(), Bool(++n1_), Bool(++n2_)); finished_ = true; } @@ -674,163 +635,147 @@ TEST_F(ASSERT_PRED2Test, FunctorOnUserTypeSuccess) { // predicate-formatter is a function on a built-in type (int). TEST_F(ASSERT_PRED2Test, FunctionOnBuiltInTypeFailure) { expected_to_finish_ = false; - EXPECT_FATAL_FAILURE({ // NOLINT - ASSERT_PRED2(PredFunction2Int, - n1_++, - n2_++); - finished_ = true; - }, ""); + EXPECT_FATAL_FAILURE( + { // NOLINT + ASSERT_PRED2(PredFunction2Int, n1_++, n2_++); + finished_ = true; + }, + ""); } // Tests a failed ASSERT_PRED2 where the // predicate-formatter is a function on a user-defined type (Bool). TEST_F(ASSERT_PRED2Test, FunctionOnUserTypeFailure) { expected_to_finish_ = false; - EXPECT_FATAL_FAILURE({ // NOLINT - ASSERT_PRED2(PredFunction2Bool, - Bool(n1_++), - Bool(n2_++)); - finished_ = true; - }, ""); + EXPECT_FATAL_FAILURE( + { // NOLINT + ASSERT_PRED2(PredFunction2Bool, Bool(n1_++), Bool(n2_++)); + finished_ = true; + }, + ""); } // Tests a failed ASSERT_PRED2 where the // predicate-formatter is a functor on a built-in type (int). TEST_F(ASSERT_PRED2Test, FunctorOnBuiltInTypeFailure) { expected_to_finish_ = false; - EXPECT_FATAL_FAILURE({ // NOLINT - ASSERT_PRED2(PredFunctor2(), - n1_++, - n2_++); - finished_ = true; - }, ""); + EXPECT_FATAL_FAILURE( + { // NOLINT + ASSERT_PRED2(PredFunctor2(), n1_++, n2_++); + finished_ = true; + }, + ""); } // Tests a failed ASSERT_PRED2 where the // predicate-formatter is a functor on a user-defined type (Bool). TEST_F(ASSERT_PRED2Test, FunctorOnUserTypeFailure) { expected_to_finish_ = false; - EXPECT_FATAL_FAILURE({ // NOLINT - ASSERT_PRED2(PredFunctor2(), - Bool(n1_++), - Bool(n2_++)); - finished_ = true; - }, ""); + EXPECT_FATAL_FAILURE( + { // NOLINT + ASSERT_PRED2(PredFunctor2(), Bool(n1_++), Bool(n2_++)); + finished_ = true; + }, + ""); } // Tests a successful EXPECT_PRED_FORMAT2 where the // predicate-formatter is a function on a built-in type (int). TEST_F(EXPECT_PRED_FORMAT2Test, FunctionOnBuiltInTypeSuccess) { - EXPECT_PRED_FORMAT2(PredFormatFunction2, - ++n1_, - ++n2_); + EXPECT_PRED_FORMAT2(PredFormatFunction2, ++n1_, ++n2_); finished_ = true; } // Tests a successful EXPECT_PRED_FORMAT2 where the // predicate-formatter is a function on a user-defined type (Bool). TEST_F(EXPECT_PRED_FORMAT2Test, FunctionOnUserTypeSuccess) { - EXPECT_PRED_FORMAT2(PredFormatFunction2, - Bool(++n1_), - Bool(++n2_)); + EXPECT_PRED_FORMAT2(PredFormatFunction2, Bool(++n1_), Bool(++n2_)); finished_ = true; } // Tests a successful EXPECT_PRED_FORMAT2 where the // predicate-formatter is a functor on a built-in type (int). TEST_F(EXPECT_PRED_FORMAT2Test, FunctorOnBuiltInTypeSuccess) { - EXPECT_PRED_FORMAT2(PredFormatFunctor2(), - ++n1_, - ++n2_); + EXPECT_PRED_FORMAT2(PredFormatFunctor2(), ++n1_, ++n2_); finished_ = true; } // Tests a successful EXPECT_PRED_FORMAT2 where the // predicate-formatter is a functor on a user-defined type (Bool). TEST_F(EXPECT_PRED_FORMAT2Test, FunctorOnUserTypeSuccess) { - EXPECT_PRED_FORMAT2(PredFormatFunctor2(), - Bool(++n1_), - Bool(++n2_)); + EXPECT_PRED_FORMAT2(PredFormatFunctor2(), Bool(++n1_), Bool(++n2_)); finished_ = true; } // Tests a failed EXPECT_PRED_FORMAT2 where the // predicate-formatter is a function on a built-in type (int). TEST_F(EXPECT_PRED_FORMAT2Test, FunctionOnBuiltInTypeFailure) { - EXPECT_NONFATAL_FAILURE({ // NOLINT - EXPECT_PRED_FORMAT2(PredFormatFunction2, - n1_++, - n2_++); - finished_ = true; - }, ""); + EXPECT_NONFATAL_FAILURE( + { // NOLINT + EXPECT_PRED_FORMAT2(PredFormatFunction2, n1_++, n2_++); + finished_ = true; + }, + ""); } // Tests a failed EXPECT_PRED_FORMAT2 where the // predicate-formatter is a function on a user-defined type (Bool). TEST_F(EXPECT_PRED_FORMAT2Test, FunctionOnUserTypeFailure) { - EXPECT_NONFATAL_FAILURE({ // NOLINT - EXPECT_PRED_FORMAT2(PredFormatFunction2, - Bool(n1_++), - Bool(n2_++)); - finished_ = true; - }, ""); + EXPECT_NONFATAL_FAILURE( + { // NOLINT + EXPECT_PRED_FORMAT2(PredFormatFunction2, Bool(n1_++), Bool(n2_++)); + finished_ = true; + }, + ""); } // Tests a failed EXPECT_PRED_FORMAT2 where the // predicate-formatter is a functor on a built-in type (int). TEST_F(EXPECT_PRED_FORMAT2Test, FunctorOnBuiltInTypeFailure) { - EXPECT_NONFATAL_FAILURE({ // NOLINT - EXPECT_PRED_FORMAT2(PredFormatFunctor2(), - n1_++, - n2_++); - finished_ = true; - }, ""); + EXPECT_NONFATAL_FAILURE( + { // NOLINT + EXPECT_PRED_FORMAT2(PredFormatFunctor2(), n1_++, n2_++); + finished_ = true; + }, + ""); } // Tests a failed EXPECT_PRED_FORMAT2 where the // predicate-formatter is a functor on a user-defined type (Bool). TEST_F(EXPECT_PRED_FORMAT2Test, FunctorOnUserTypeFailure) { - EXPECT_NONFATAL_FAILURE({ // NOLINT - EXPECT_PRED_FORMAT2(PredFormatFunctor2(), - Bool(n1_++), - Bool(n2_++)); - finished_ = true; - }, ""); + EXPECT_NONFATAL_FAILURE( + { // NOLINT + EXPECT_PRED_FORMAT2(PredFormatFunctor2(), Bool(n1_++), Bool(n2_++)); + finished_ = true; + }, + ""); } // Tests a successful ASSERT_PRED_FORMAT2 where the // predicate-formatter is a function on a built-in type (int). TEST_F(ASSERT_PRED_FORMAT2Test, FunctionOnBuiltInTypeSuccess) { - ASSERT_PRED_FORMAT2(PredFormatFunction2, - ++n1_, - ++n2_); + ASSERT_PRED_FORMAT2(PredFormatFunction2, ++n1_, ++n2_); finished_ = true; } // Tests a successful ASSERT_PRED_FORMAT2 where the // predicate-formatter is a function on a user-defined type (Bool). TEST_F(ASSERT_PRED_FORMAT2Test, FunctionOnUserTypeSuccess) { - ASSERT_PRED_FORMAT2(PredFormatFunction2, - Bool(++n1_), - Bool(++n2_)); + ASSERT_PRED_FORMAT2(PredFormatFunction2, Bool(++n1_), Bool(++n2_)); finished_ = true; } // Tests a successful ASSERT_PRED_FORMAT2 where the // predicate-formatter is a functor on a built-in type (int). TEST_F(ASSERT_PRED_FORMAT2Test, FunctorOnBuiltInTypeSuccess) { - ASSERT_PRED_FORMAT2(PredFormatFunctor2(), - ++n1_, - ++n2_); + ASSERT_PRED_FORMAT2(PredFormatFunctor2(), ++n1_, ++n2_); finished_ = true; } // Tests a successful ASSERT_PRED_FORMAT2 where the // predicate-formatter is a functor on a user-defined type (Bool). TEST_F(ASSERT_PRED_FORMAT2Test, FunctorOnUserTypeSuccess) { - ASSERT_PRED_FORMAT2(PredFormatFunctor2(), - Bool(++n1_), - Bool(++n2_)); + ASSERT_PRED_FORMAT2(PredFormatFunctor2(), Bool(++n1_), Bool(++n2_)); finished_ = true; } @@ -838,48 +783,48 @@ TEST_F(ASSERT_PRED_FORMAT2Test, FunctorOnUserTypeSuccess) { // predicate-formatter is a function on a built-in type (int). TEST_F(ASSERT_PRED_FORMAT2Test, FunctionOnBuiltInTypeFailure) { expected_to_finish_ = false; - EXPECT_FATAL_FAILURE({ // NOLINT - ASSERT_PRED_FORMAT2(PredFormatFunction2, - n1_++, - n2_++); - finished_ = true; - }, ""); + EXPECT_FATAL_FAILURE( + { // NOLINT + ASSERT_PRED_FORMAT2(PredFormatFunction2, n1_++, n2_++); + finished_ = true; + }, + ""); } // Tests a failed ASSERT_PRED_FORMAT2 where the // predicate-formatter is a function on a user-defined type (Bool). TEST_F(ASSERT_PRED_FORMAT2Test, FunctionOnUserTypeFailure) { expected_to_finish_ = false; - EXPECT_FATAL_FAILURE({ // NOLINT - ASSERT_PRED_FORMAT2(PredFormatFunction2, - Bool(n1_++), - Bool(n2_++)); - finished_ = true; - }, ""); + EXPECT_FATAL_FAILURE( + { // NOLINT + ASSERT_PRED_FORMAT2(PredFormatFunction2, Bool(n1_++), Bool(n2_++)); + finished_ = true; + }, + ""); } // Tests a failed ASSERT_PRED_FORMAT2 where the // predicate-formatter is a functor on a built-in type (int). TEST_F(ASSERT_PRED_FORMAT2Test, FunctorOnBuiltInTypeFailure) { expected_to_finish_ = false; - EXPECT_FATAL_FAILURE({ // NOLINT - ASSERT_PRED_FORMAT2(PredFormatFunctor2(), - n1_++, - n2_++); - finished_ = true; - }, ""); + EXPECT_FATAL_FAILURE( + { // NOLINT + ASSERT_PRED_FORMAT2(PredFormatFunctor2(), n1_++, n2_++); + finished_ = true; + }, + ""); } // Tests a failed ASSERT_PRED_FORMAT2 where the // predicate-formatter is a functor on a user-defined type (Bool). TEST_F(ASSERT_PRED_FORMAT2Test, FunctorOnUserTypeFailure) { expected_to_finish_ = false; - EXPECT_FATAL_FAILURE({ // NOLINT - ASSERT_PRED_FORMAT2(PredFormatFunctor2(), - Bool(n1_++), - Bool(n2_++)); - finished_ = true; - }, ""); + EXPECT_FATAL_FAILURE( + { // NOLINT + ASSERT_PRED_FORMAT2(PredFormatFunctor2(), Bool(n1_++), Bool(n2_++)); + finished_ = true; + }, + ""); } // Sample functions/functors for testing ternary predicate assertions. @@ -891,49 +836,36 @@ bool PredFunction3(T1 v1, T2 v2, T3 v3) { // The following two functions are needed because a compiler doesn't have // a context yet to know which template function must be instantiated. -bool PredFunction3Int(int v1, int v2, int v3) { - return v1 + v2 + v3 > 0; -} -bool PredFunction3Bool(Bool v1, Bool v2, Bool v3) { - return v1 + v2 + v3 > 0; -} +bool PredFunction3Int(int v1, int v2, int v3) { return v1 + v2 + v3 > 0; } +bool PredFunction3Bool(Bool v1, Bool v2, Bool v3) { return v1 + v2 + v3 > 0; } // A ternary predicate functor. struct PredFunctor3 { template <typename T1, typename T2, typename T3> - bool operator()(const T1& v1, - const T2& v2, - const T3& v3) { + bool operator()(const T1& v1, const T2& v2, const T3& v3) { return v1 + v2 + v3 > 0; } }; // A ternary predicate-formatter function. template <typename T1, typename T2, typename T3> -testing::AssertionResult PredFormatFunction3(const char* e1, - const char* e2, - const char* e3, - const T1& v1, - const T2& v2, - const T3& v3) { - if (PredFunction3(v1, v2, v3)) - return testing::AssertionSuccess(); +testing::AssertionResult PredFormatFunction3(const char* e1, const char* e2, + const char* e3, const T1& v1, + const T2& v2, const T3& v3) { + if (PredFunction3(v1, v2, v3)) return testing::AssertionSuccess(); return testing::AssertionFailure() - << e1 << " + " << e2 << " + " << e3 - << " is expected to be positive, but evaluates to " - << v1 + v2 + v3 << "."; + << e1 << " + " << e2 << " + " << e3 + << " is expected to be positive, but evaluates to " << v1 + v2 + v3 + << "."; } // A ternary predicate-formatter functor. struct PredFormatFunctor3 { template <typename T1, typename T2, typename T3> - testing::AssertionResult operator()(const char* e1, - const char* e2, - const char* e3, - const T1& v1, - const T2& v2, - const T3& v3) const { + testing::AssertionResult operator()(const char* e1, const char* e2, + const char* e3, const T1& v1, + const T2& v2, const T3& v3) const { return PredFormatFunction3(e1, e2, e3, v1, v2, v3); } }; @@ -951,15 +883,12 @@ class Predicate3Test : public testing::Test { void TearDown() override { // Verifies that each of the predicate's arguments was evaluated // exactly once. - EXPECT_EQ(1, n1_) << - "The predicate assertion didn't evaluate argument 2 " - "exactly once."; - EXPECT_EQ(1, n2_) << - "The predicate assertion didn't evaluate argument 3 " - "exactly once."; - EXPECT_EQ(1, n3_) << - "The predicate assertion didn't evaluate argument 4 " - "exactly once."; + EXPECT_EQ(1, n1_) << "The predicate assertion didn't evaluate argument 2 " + "exactly once."; + EXPECT_EQ(1, n2_) << "The predicate assertion didn't evaluate argument 3 " + "exactly once."; + EXPECT_EQ(1, n3_) << "The predicate assertion didn't evaluate argument 4 " + "exactly once."; // Verifies that the control flow in the test function is expected. if (expected_to_finish_ && !finished_) { @@ -995,128 +924,100 @@ typedef Predicate3Test ASSERT_PRED3Test; // Tests a successful EXPECT_PRED3 where the // predicate-formatter is a function on a built-in type (int). TEST_F(EXPECT_PRED3Test, FunctionOnBuiltInTypeSuccess) { - EXPECT_PRED3(PredFunction3Int, - ++n1_, - ++n2_, - ++n3_); + EXPECT_PRED3(PredFunction3Int, ++n1_, ++n2_, ++n3_); finished_ = true; } // Tests a successful EXPECT_PRED3 where the // predicate-formatter is a function on a user-defined type (Bool). TEST_F(EXPECT_PRED3Test, FunctionOnUserTypeSuccess) { - EXPECT_PRED3(PredFunction3Bool, - Bool(++n1_), - Bool(++n2_), - Bool(++n3_)); + EXPECT_PRED3(PredFunction3Bool, Bool(++n1_), Bool(++n2_), Bool(++n3_)); finished_ = true; } // Tests a successful EXPECT_PRED3 where the // predicate-formatter is a functor on a built-in type (int). TEST_F(EXPECT_PRED3Test, FunctorOnBuiltInTypeSuccess) { - EXPECT_PRED3(PredFunctor3(), - ++n1_, - ++n2_, - ++n3_); + EXPECT_PRED3(PredFunctor3(), ++n1_, ++n2_, ++n3_); finished_ = true; } // Tests a successful EXPECT_PRED3 where the // predicate-formatter is a functor on a user-defined type (Bool). TEST_F(EXPECT_PRED3Test, FunctorOnUserTypeSuccess) { - EXPECT_PRED3(PredFunctor3(), - Bool(++n1_), - Bool(++n2_), - Bool(++n3_)); + EXPECT_PRED3(PredFunctor3(), Bool(++n1_), Bool(++n2_), Bool(++n3_)); finished_ = true; } // Tests a failed EXPECT_PRED3 where the // predicate-formatter is a function on a built-in type (int). TEST_F(EXPECT_PRED3Test, FunctionOnBuiltInTypeFailure) { - EXPECT_NONFATAL_FAILURE({ // NOLINT - EXPECT_PRED3(PredFunction3Int, - n1_++, - n2_++, - n3_++); - finished_ = true; - }, ""); + EXPECT_NONFATAL_FAILURE( + { // NOLINT + EXPECT_PRED3(PredFunction3Int, n1_++, n2_++, n3_++); + finished_ = true; + }, + ""); } // Tests a failed EXPECT_PRED3 where the // predicate-formatter is a function on a user-defined type (Bool). TEST_F(EXPECT_PRED3Test, FunctionOnUserTypeFailure) { - EXPECT_NONFATAL_FAILURE({ // NOLINT - EXPECT_PRED3(PredFunction3Bool, - Bool(n1_++), - Bool(n2_++), - Bool(n3_++)); - finished_ = true; - }, ""); + EXPECT_NONFATAL_FAILURE( + { // NOLINT + EXPECT_PRED3(PredFunction3Bool, Bool(n1_++), Bool(n2_++), Bool(n3_++)); + finished_ = true; + }, + ""); } // Tests a failed EXPECT_PRED3 where the // predicate-formatter is a functor on a built-in type (int). TEST_F(EXPECT_PRED3Test, FunctorOnBuiltInTypeFailure) { - EXPECT_NONFATAL_FAILURE({ // NOLINT - EXPECT_PRED3(PredFunctor3(), - n1_++, - n2_++, - n3_++); - finished_ = true; - }, ""); + EXPECT_NONFATAL_FAILURE( + { // NOLINT + EXPECT_PRED3(PredFunctor3(), n1_++, n2_++, n3_++); + finished_ = true; + }, + ""); } // Tests a failed EXPECT_PRED3 where the // predicate-formatter is a functor on a user-defined type (Bool). TEST_F(EXPECT_PRED3Test, FunctorOnUserTypeFailure) { - EXPECT_NONFATAL_FAILURE({ // NOLINT - EXPECT_PRED3(PredFunctor3(), - Bool(n1_++), - Bool(n2_++), - Bool(n3_++)); - finished_ = true; - }, ""); + EXPECT_NONFATAL_FAILURE( + { // NOLINT + EXPECT_PRED3(PredFunctor3(), Bool(n1_++), Bool(n2_++), Bool(n3_++)); + finished_ = true; + }, + ""); } // Tests a successful ASSERT_PRED3 where the // predicate-formatter is a function on a built-in type (int). TEST_F(ASSERT_PRED3Test, FunctionOnBuiltInTypeSuccess) { - ASSERT_PRED3(PredFunction3Int, - ++n1_, - ++n2_, - ++n3_); + ASSERT_PRED3(PredFunction3Int, ++n1_, ++n2_, ++n3_); finished_ = true; } // Tests a successful ASSERT_PRED3 where the // predicate-formatter is a function on a user-defined type (Bool). TEST_F(ASSERT_PRED3Test, FunctionOnUserTypeSuccess) { - ASSERT_PRED3(PredFunction3Bool, - Bool(++n1_), - Bool(++n2_), - Bool(++n3_)); + ASSERT_PRED3(PredFunction3Bool, Bool(++n1_), Bool(++n2_), Bool(++n3_)); finished_ = true; } // Tests a successful ASSERT_PRED3 where the // predicate-formatter is a functor on a built-in type (int). TEST_F(ASSERT_PRED3Test, FunctorOnBuiltInTypeSuccess) { - ASSERT_PRED3(PredFunctor3(), - ++n1_, - ++n2_, - ++n3_); + ASSERT_PRED3(PredFunctor3(), ++n1_, ++n2_, ++n3_); finished_ = true; } // Tests a successful ASSERT_PRED3 where the // predicate-formatter is a functor on a user-defined type (Bool). TEST_F(ASSERT_PRED3Test, FunctorOnUserTypeSuccess) { - ASSERT_PRED3(PredFunctor3(), - Bool(++n1_), - Bool(++n2_), - Bool(++n3_)); + ASSERT_PRED3(PredFunctor3(), Bool(++n1_), Bool(++n2_), Bool(++n3_)); finished_ = true; } @@ -1124,70 +1025,61 @@ TEST_F(ASSERT_PRED3Test, FunctorOnUserTypeSuccess) { // predicate-formatter is a function on a built-in type (int). TEST_F(ASSERT_PRED3Test, FunctionOnBuiltInTypeFailure) { expected_to_finish_ = false; - EXPECT_FATAL_FAILURE({ // NOLINT - ASSERT_PRED3(PredFunction3Int, - n1_++, - n2_++, - n3_++); - finished_ = true; - }, ""); + EXPECT_FATAL_FAILURE( + { // NOLINT + ASSERT_PRED3(PredFunction3Int, n1_++, n2_++, n3_++); + finished_ = true; + }, + ""); } // Tests a failed ASSERT_PRED3 where the // predicate-formatter is a function on a user-defined type (Bool). TEST_F(ASSERT_PRED3Test, FunctionOnUserTypeFailure) { expected_to_finish_ = false; - EXPECT_FATAL_FAILURE({ // NOLINT - ASSERT_PRED3(PredFunction3Bool, - Bool(n1_++), - Bool(n2_++), - Bool(n3_++)); - finished_ = true; - }, ""); + EXPECT_FATAL_FAILURE( + { // NOLINT + ASSERT_PRED3(PredFunction3Bool, Bool(n1_++), Bool(n2_++), Bool(n3_++)); + finished_ = true; + }, + ""); } // Tests a failed ASSERT_PRED3 where the // predicate-formatter is a functor on a built-in type (int). TEST_F(ASSERT_PRED3Test, FunctorOnBuiltInTypeFailure) { expected_to_finish_ = false; - EXPECT_FATAL_FAILURE({ // NOLINT - ASSERT_PRED3(PredFunctor3(), - n1_++, - n2_++, - n3_++); - finished_ = true; - }, ""); + EXPECT_FATAL_FAILURE( + { // NOLINT + ASSERT_PRED3(PredFunctor3(), n1_++, n2_++, n3_++); + finished_ = true; + }, + ""); } // Tests a failed ASSERT_PRED3 where the // predicate-formatter is a functor on a user-defined type (Bool). TEST_F(ASSERT_PRED3Test, FunctorOnUserTypeFailure) { expected_to_finish_ = false; - EXPECT_FATAL_FAILURE({ // NOLINT - ASSERT_PRED3(PredFunctor3(), - Bool(n1_++), - Bool(n2_++), - Bool(n3_++)); - finished_ = true; - }, ""); + EXPECT_FATAL_FAILURE( + { // NOLINT + ASSERT_PRED3(PredFunctor3(), Bool(n1_++), Bool(n2_++), Bool(n3_++)); + finished_ = true; + }, + ""); } // Tests a successful EXPECT_PRED_FORMAT3 where the // predicate-formatter is a function on a built-in type (int). TEST_F(EXPECT_PRED_FORMAT3Test, FunctionOnBuiltInTypeSuccess) { - EXPECT_PRED_FORMAT3(PredFormatFunction3, - ++n1_, - ++n2_, - ++n3_); + EXPECT_PRED_FORMAT3(PredFormatFunction3, ++n1_, ++n2_, ++n3_); finished_ = true; } // Tests a successful EXPECT_PRED_FORMAT3 where the // predicate-formatter is a function on a user-defined type (Bool). TEST_F(EXPECT_PRED_FORMAT3Test, FunctionOnUserTypeSuccess) { - EXPECT_PRED_FORMAT3(PredFormatFunction3, - Bool(++n1_), - Bool(++n2_), + EXPECT_PRED_FORMAT3(PredFormatFunction3, Bool(++n1_), Bool(++n2_), Bool(++n3_)); finished_ = true; } @@ -1195,19 +1087,14 @@ TEST_F(EXPECT_PRED_FORMAT3Test, FunctionOnUserTypeSuccess) { // Tests a successful EXPECT_PRED_FORMAT3 where the // predicate-formatter is a functor on a built-in type (int). TEST_F(EXPECT_PRED_FORMAT3Test, FunctorOnBuiltInTypeSuccess) { - EXPECT_PRED_FORMAT3(PredFormatFunctor3(), - ++n1_, - ++n2_, - ++n3_); + EXPECT_PRED_FORMAT3(PredFormatFunctor3(), ++n1_, ++n2_, ++n3_); finished_ = true; } // Tests a successful EXPECT_PRED_FORMAT3 where the // predicate-formatter is a functor on a user-defined type (Bool). TEST_F(EXPECT_PRED_FORMAT3Test, FunctorOnUserTypeSuccess) { - EXPECT_PRED_FORMAT3(PredFormatFunctor3(), - Bool(++n1_), - Bool(++n2_), + EXPECT_PRED_FORMAT3(PredFormatFunctor3(), Bool(++n1_), Bool(++n2_), Bool(++n3_)); finished_ = true; } @@ -1215,67 +1102,60 @@ TEST_F(EXPECT_PRED_FORMAT3Test, FunctorOnUserTypeSuccess) { // Tests a failed EXPECT_PRED_FORMAT3 where the // predicate-formatter is a function on a built-in type (int). TEST_F(EXPECT_PRED_FORMAT3Test, FunctionOnBuiltInTypeFailure) { - EXPECT_NONFATAL_FAILURE({ // NOLINT - EXPECT_PRED_FORMAT3(PredFormatFunction3, - n1_++, - n2_++, - n3_++); - finished_ = true; - }, ""); + EXPECT_NONFATAL_FAILURE( + { // NOLINT + EXPECT_PRED_FORMAT3(PredFormatFunction3, n1_++, n2_++, n3_++); + finished_ = true; + }, + ""); } // Tests a failed EXPECT_PRED_FORMAT3 where the // predicate-formatter is a function on a user-defined type (Bool). TEST_F(EXPECT_PRED_FORMAT3Test, FunctionOnUserTypeFailure) { - EXPECT_NONFATAL_FAILURE({ // NOLINT - EXPECT_PRED_FORMAT3(PredFormatFunction3, - Bool(n1_++), - Bool(n2_++), - Bool(n3_++)); - finished_ = true; - }, ""); + EXPECT_NONFATAL_FAILURE( + { // NOLINT + EXPECT_PRED_FORMAT3(PredFormatFunction3, Bool(n1_++), Bool(n2_++), + Bool(n3_++)); + finished_ = true; + }, + ""); } // Tests a failed EXPECT_PRED_FORMAT3 where the // predicate-formatter is a functor on a built-in type (int). TEST_F(EXPECT_PRED_FORMAT3Test, FunctorOnBuiltInTypeFailure) { - EXPECT_NONFATAL_FAILURE({ // NOLINT - EXPECT_PRED_FORMAT3(PredFormatFunctor3(), - n1_++, - n2_++, - n3_++); - finished_ = true; - }, ""); + EXPECT_NONFATAL_FAILURE( + { // NOLINT + EXPECT_PRED_FORMAT3(PredFormatFunctor3(), n1_++, n2_++, n3_++); + finished_ = true; + }, + ""); } // Tests a failed EXPECT_PRED_FORMAT3 where the // predicate-formatter is a functor on a user-defined type (Bool). TEST_F(EXPECT_PRED_FORMAT3Test, FunctorOnUserTypeFailure) { - EXPECT_NONFATAL_FAILURE({ // NOLINT - EXPECT_PRED_FORMAT3(PredFormatFunctor3(), - Bool(n1_++), - Bool(n2_++), - Bool(n3_++)); - finished_ = true; - }, ""); + EXPECT_NONFATAL_FAILURE( + { // NOLINT + EXPECT_PRED_FORMAT3(PredFormatFunctor3(), Bool(n1_++), Bool(n2_++), + Bool(n3_++)); + finished_ = true; + }, + ""); } // Tests a successful ASSERT_PRED_FORMAT3 where the // predicate-formatter is a function on a built-in type (int). TEST_F(ASSERT_PRED_FORMAT3Test, FunctionOnBuiltInTypeSuccess) { - ASSERT_PRED_FORMAT3(PredFormatFunction3, - ++n1_, - ++n2_, - ++n3_); + ASSERT_PRED_FORMAT3(PredFormatFunction3, ++n1_, ++n2_, ++n3_); finished_ = true; } // Tests a successful ASSERT_PRED_FORMAT3 where the // predicate-formatter is a function on a user-defined type (Bool). TEST_F(ASSERT_PRED_FORMAT3Test, FunctionOnUserTypeSuccess) { - ASSERT_PRED_FORMAT3(PredFormatFunction3, - Bool(++n1_), - Bool(++n2_), + ASSERT_PRED_FORMAT3(PredFormatFunction3, Bool(++n1_), Bool(++n2_), Bool(++n3_)); finished_ = true; } @@ -1283,19 +1163,14 @@ TEST_F(ASSERT_PRED_FORMAT3Test, FunctionOnUserTypeSuccess) { // Tests a successful ASSERT_PRED_FORMAT3 where the // predicate-formatter is a functor on a built-in type (int). TEST_F(ASSERT_PRED_FORMAT3Test, FunctorOnBuiltInTypeSuccess) { - ASSERT_PRED_FORMAT3(PredFormatFunctor3(), - ++n1_, - ++n2_, - ++n3_); + ASSERT_PRED_FORMAT3(PredFormatFunctor3(), ++n1_, ++n2_, ++n3_); finished_ = true; } // Tests a successful ASSERT_PRED_FORMAT3 where the // predicate-formatter is a functor on a user-defined type (Bool). TEST_F(ASSERT_PRED_FORMAT3Test, FunctorOnUserTypeSuccess) { - ASSERT_PRED_FORMAT3(PredFormatFunctor3(), - Bool(++n1_), - Bool(++n2_), + ASSERT_PRED_FORMAT3(PredFormatFunctor3(), Bool(++n1_), Bool(++n2_), Bool(++n3_)); finished_ = true; } @@ -1304,52 +1179,50 @@ TEST_F(ASSERT_PRED_FORMAT3Test, FunctorOnUserTypeSuccess) { // predicate-formatter is a function on a built-in type (int). TEST_F(ASSERT_PRED_FORMAT3Test, FunctionOnBuiltInTypeFailure) { expected_to_finish_ = false; - EXPECT_FATAL_FAILURE({ // NOLINT - ASSERT_PRED_FORMAT3(PredFormatFunction3, - n1_++, - n2_++, - n3_++); - finished_ = true; - }, ""); + EXPECT_FATAL_FAILURE( + { // NOLINT + ASSERT_PRED_FORMAT3(PredFormatFunction3, n1_++, n2_++, n3_++); + finished_ = true; + }, + ""); } // Tests a failed ASSERT_PRED_FORMAT3 where the // predicate-formatter is a function on a user-defined type (Bool). TEST_F(ASSERT_PRED_FORMAT3Test, FunctionOnUserTypeFailure) { expected_to_finish_ = false; - EXPECT_FATAL_FAILURE({ // NOLINT - ASSERT_PRED_FORMAT3(PredFormatFunction3, - Bool(n1_++), - Bool(n2_++), - Bool(n3_++)); - finished_ = true; - }, ""); + EXPECT_FATAL_FAILURE( + { // NOLINT + ASSERT_PRED_FORMAT3(PredFormatFunction3, Bool(n1_++), Bool(n2_++), + Bool(n3_++)); + finished_ = true; + }, + ""); } // Tests a failed ASSERT_PRED_FORMAT3 where the // predicate-formatter is a functor on a built-in type (int). TEST_F(ASSERT_PRED_FORMAT3Test, FunctorOnBuiltInTypeFailure) { expected_to_finish_ = false; - EXPECT_FATAL_FAILURE({ // NOLINT - ASSERT_PRED_FORMAT3(PredFormatFunctor3(), - n1_++, - n2_++, - n3_++); - finished_ = true; - }, ""); + EXPECT_FATAL_FAILURE( + { // NOLINT + ASSERT_PRED_FORMAT3(PredFormatFunctor3(), n1_++, n2_++, n3_++); + finished_ = true; + }, + ""); } // Tests a failed ASSERT_PRED_FORMAT3 where the // predicate-formatter is a functor on a user-defined type (Bool). TEST_F(ASSERT_PRED_FORMAT3Test, FunctorOnUserTypeFailure) { expected_to_finish_ = false; - EXPECT_FATAL_FAILURE({ // NOLINT - ASSERT_PRED_FORMAT3(PredFormatFunctor3(), - Bool(n1_++), - Bool(n2_++), - Bool(n3_++)); - finished_ = true; - }, ""); + EXPECT_FATAL_FAILURE( + { // NOLINT + ASSERT_PRED_FORMAT3(PredFormatFunctor3(), Bool(n1_++), Bool(n2_++), + Bool(n3_++)); + finished_ = true; + }, + ""); } // Sample functions/functors for testing 4-ary predicate assertions. @@ -1371,43 +1244,31 @@ bool PredFunction4Bool(Bool v1, Bool v2, Bool v3, Bool v4) { // A 4-ary predicate functor. struct PredFunctor4 { template <typename T1, typename T2, typename T3, typename T4> - bool operator()(const T1& v1, - const T2& v2, - const T3& v3, - const T4& v4) { + bool operator()(const T1& v1, const T2& v2, const T3& v3, const T4& v4) { return v1 + v2 + v3 + v4 > 0; } }; // A 4-ary predicate-formatter function. template <typename T1, typename T2, typename T3, typename T4> -testing::AssertionResult PredFormatFunction4(const char* e1, - const char* e2, - const char* e3, - const char* e4, - const T1& v1, - const T2& v2, - const T3& v3, - const T4& v4) { - if (PredFunction4(v1, v2, v3, v4)) - return testing::AssertionSuccess(); +testing::AssertionResult PredFormatFunction4(const char* e1, const char* e2, + const char* e3, const char* e4, + const T1& v1, const T2& v2, + const T3& v3, const T4& v4) { + if (PredFunction4(v1, v2, v3, v4)) return testing::AssertionSuccess(); return testing::AssertionFailure() - << e1 << " + " << e2 << " + " << e3 << " + " << e4 - << " is expected to be positive, but evaluates to " - << v1 + v2 + v3 + v4 << "."; + << e1 << " + " << e2 << " + " << e3 << " + " << e4 + << " is expected to be positive, but evaluates to " + << v1 + v2 + v3 + v4 << "."; } // A 4-ary predicate-formatter functor. struct PredFormatFunctor4 { template <typename T1, typename T2, typename T3, typename T4> - testing::AssertionResult operator()(const char* e1, - const char* e2, - const char* e3, - const char* e4, - const T1& v1, - const T2& v2, - const T3& v3, + testing::AssertionResult operator()(const char* e1, const char* e2, + const char* e3, const char* e4, + const T1& v1, const T2& v2, const T3& v3, const T4& v4) const { return PredFormatFunction4(e1, e2, e3, e4, v1, v2, v3, v4); } @@ -1426,18 +1287,14 @@ class Predicate4Test : public testing::Test { void TearDown() override { // Verifies that each of the predicate's arguments was evaluated // exactly once. - EXPECT_EQ(1, n1_) << - "The predicate assertion didn't evaluate argument 2 " - "exactly once."; - EXPECT_EQ(1, n2_) << - "The predicate assertion didn't evaluate argument 3 " - "exactly once."; - EXPECT_EQ(1, n3_) << - "The predicate assertion didn't evaluate argument 4 " - "exactly once."; - EXPECT_EQ(1, n4_) << - "The predicate assertion didn't evaluate argument 5 " - "exactly once."; + EXPECT_EQ(1, n1_) << "The predicate assertion didn't evaluate argument 2 " + "exactly once."; + EXPECT_EQ(1, n2_) << "The predicate assertion didn't evaluate argument 3 " + "exactly once."; + EXPECT_EQ(1, n3_) << "The predicate assertion didn't evaluate argument 4 " + "exactly once."; + EXPECT_EQ(1, n4_) << "The predicate assertion didn't evaluate argument 5 " + "exactly once."; // Verifies that the control flow in the test function is expected. if (expected_to_finish_ && !finished_) { @@ -1475,21 +1332,14 @@ typedef Predicate4Test ASSERT_PRED4Test; // Tests a successful EXPECT_PRED4 where the // predicate-formatter is a function on a built-in type (int). TEST_F(EXPECT_PRED4Test, FunctionOnBuiltInTypeSuccess) { - EXPECT_PRED4(PredFunction4Int, - ++n1_, - ++n2_, - ++n3_, - ++n4_); + EXPECT_PRED4(PredFunction4Int, ++n1_, ++n2_, ++n3_, ++n4_); finished_ = true; } // Tests a successful EXPECT_PRED4 where the // predicate-formatter is a function on a user-defined type (Bool). TEST_F(EXPECT_PRED4Test, FunctionOnUserTypeSuccess) { - EXPECT_PRED4(PredFunction4Bool, - Bool(++n1_), - Bool(++n2_), - Bool(++n3_), + EXPECT_PRED4(PredFunction4Bool, Bool(++n1_), Bool(++n2_), Bool(++n3_), Bool(++n4_)); finished_ = true; } @@ -1497,21 +1347,14 @@ TEST_F(EXPECT_PRED4Test, FunctionOnUserTypeSuccess) { // Tests a successful EXPECT_PRED4 where the // predicate-formatter is a functor on a built-in type (int). TEST_F(EXPECT_PRED4Test, FunctorOnBuiltInTypeSuccess) { - EXPECT_PRED4(PredFunctor4(), - ++n1_, - ++n2_, - ++n3_, - ++n4_); + EXPECT_PRED4(PredFunctor4(), ++n1_, ++n2_, ++n3_, ++n4_); finished_ = true; } // Tests a successful EXPECT_PRED4 where the // predicate-formatter is a functor on a user-defined type (Bool). TEST_F(EXPECT_PRED4Test, FunctorOnUserTypeSuccess) { - EXPECT_PRED4(PredFunctor4(), - Bool(++n1_), - Bool(++n2_), - Bool(++n3_), + EXPECT_PRED4(PredFunctor4(), Bool(++n1_), Bool(++n2_), Bool(++n3_), Bool(++n4_)); finished_ = true; } @@ -1519,73 +1362,60 @@ TEST_F(EXPECT_PRED4Test, FunctorOnUserTypeSuccess) { // Tests a failed EXPECT_PRED4 where the // predicate-formatter is a function on a built-in type (int). TEST_F(EXPECT_PRED4Test, FunctionOnBuiltInTypeFailure) { - EXPECT_NONFATAL_FAILURE({ // NOLINT - EXPECT_PRED4(PredFunction4Int, - n1_++, - n2_++, - n3_++, - n4_++); - finished_ = true; - }, ""); + EXPECT_NONFATAL_FAILURE( + { // NOLINT + EXPECT_PRED4(PredFunction4Int, n1_++, n2_++, n3_++, n4_++); + finished_ = true; + }, + ""); } // Tests a failed EXPECT_PRED4 where the // predicate-formatter is a function on a user-defined type (Bool). TEST_F(EXPECT_PRED4Test, FunctionOnUserTypeFailure) { - EXPECT_NONFATAL_FAILURE({ // NOLINT - EXPECT_PRED4(PredFunction4Bool, - Bool(n1_++), - Bool(n2_++), - Bool(n3_++), - Bool(n4_++)); - finished_ = true; - }, ""); + EXPECT_NONFATAL_FAILURE( + { // NOLINT + EXPECT_PRED4(PredFunction4Bool, Bool(n1_++), Bool(n2_++), Bool(n3_++), + Bool(n4_++)); + finished_ = true; + }, + ""); } // Tests a failed EXPECT_PRED4 where the // predicate-formatter is a functor on a built-in type (int). TEST_F(EXPECT_PRED4Test, FunctorOnBuiltInTypeFailure) { - EXPECT_NONFATAL_FAILURE({ // NOLINT - EXPECT_PRED4(PredFunctor4(), - n1_++, - n2_++, - n3_++, - n4_++); - finished_ = true; - }, ""); + EXPECT_NONFATAL_FAILURE( + { // NOLINT + EXPECT_PRED4(PredFunctor4(), n1_++, n2_++, n3_++, n4_++); + finished_ = true; + }, + ""); } // Tests a failed EXPECT_PRED4 where the // predicate-formatter is a functor on a user-defined type (Bool). TEST_F(EXPECT_PRED4Test, FunctorOnUserTypeFailure) { - EXPECT_NONFATAL_FAILURE({ // NOLINT - EXPECT_PRED4(PredFunctor4(), - Bool(n1_++), - Bool(n2_++), - Bool(n3_++), - Bool(n4_++)); - finished_ = true; - }, ""); + EXPECT_NONFATAL_FAILURE( + { // NOLINT + EXPECT_PRED4(PredFunctor4(), Bool(n1_++), Bool(n2_++), Bool(n3_++), + Bool(n4_++)); + finished_ = true; + }, + ""); } // Tests a successful ASSERT_PRED4 where the // predicate-formatter is a function on a built-in type (int). TEST_F(ASSERT_PRED4Test, FunctionOnBuiltInTypeSuccess) { - ASSERT_PRED4(PredFunction4Int, - ++n1_, - ++n2_, - ++n3_, - ++n4_); + ASSERT_PRED4(PredFunction4Int, ++n1_, ++n2_, ++n3_, ++n4_); finished_ = true; } // Tests a successful ASSERT_PRED4 where the // predicate-formatter is a function on a user-defined type (Bool). TEST_F(ASSERT_PRED4Test, FunctionOnUserTypeSuccess) { - ASSERT_PRED4(PredFunction4Bool, - Bool(++n1_), - Bool(++n2_), - Bool(++n3_), + ASSERT_PRED4(PredFunction4Bool, Bool(++n1_), Bool(++n2_), Bool(++n3_), Bool(++n4_)); finished_ = true; } @@ -1593,21 +1423,14 @@ TEST_F(ASSERT_PRED4Test, FunctionOnUserTypeSuccess) { // Tests a successful ASSERT_PRED4 where the // predicate-formatter is a functor on a built-in type (int). TEST_F(ASSERT_PRED4Test, FunctorOnBuiltInTypeSuccess) { - ASSERT_PRED4(PredFunctor4(), - ++n1_, - ++n2_, - ++n3_, - ++n4_); + ASSERT_PRED4(PredFunctor4(), ++n1_, ++n2_, ++n3_, ++n4_); finished_ = true; } // Tests a successful ASSERT_PRED4 where the // predicate-formatter is a functor on a user-defined type (Bool). TEST_F(ASSERT_PRED4Test, FunctorOnUserTypeSuccess) { - ASSERT_PRED4(PredFunctor4(), - Bool(++n1_), - Bool(++n2_), - Bool(++n3_), + ASSERT_PRED4(PredFunctor4(), Bool(++n1_), Bool(++n2_), Bool(++n3_), Bool(++n4_)); finished_ = true; } @@ -1616,195 +1439,155 @@ TEST_F(ASSERT_PRED4Test, FunctorOnUserTypeSuccess) { // predicate-formatter is a function on a built-in type (int). TEST_F(ASSERT_PRED4Test, FunctionOnBuiltInTypeFailure) { expected_to_finish_ = false; - EXPECT_FATAL_FAILURE({ // NOLINT - ASSERT_PRED4(PredFunction4Int, - n1_++, - n2_++, - n3_++, - n4_++); - finished_ = true; - }, ""); + EXPECT_FATAL_FAILURE( + { // NOLINT + ASSERT_PRED4(PredFunction4Int, n1_++, n2_++, n3_++, n4_++); + finished_ = true; + }, + ""); } // Tests a failed ASSERT_PRED4 where the // predicate-formatter is a function on a user-defined type (Bool). TEST_F(ASSERT_PRED4Test, FunctionOnUserTypeFailure) { expected_to_finish_ = false; - EXPECT_FATAL_FAILURE({ // NOLINT - ASSERT_PRED4(PredFunction4Bool, - Bool(n1_++), - Bool(n2_++), - Bool(n3_++), - Bool(n4_++)); - finished_ = true; - }, ""); + EXPECT_FATAL_FAILURE( + { // NOLINT + ASSERT_PRED4(PredFunction4Bool, Bool(n1_++), Bool(n2_++), Bool(n3_++), + Bool(n4_++)); + finished_ = true; + }, + ""); } // Tests a failed ASSERT_PRED4 where the // predicate-formatter is a functor on a built-in type (int). TEST_F(ASSERT_PRED4Test, FunctorOnBuiltInTypeFailure) { expected_to_finish_ = false; - EXPECT_FATAL_FAILURE({ // NOLINT - ASSERT_PRED4(PredFunctor4(), - n1_++, - n2_++, - n3_++, - n4_++); - finished_ = true; - }, ""); + EXPECT_FATAL_FAILURE( + { // NOLINT + ASSERT_PRED4(PredFunctor4(), n1_++, n2_++, n3_++, n4_++); + finished_ = true; + }, + ""); } // Tests a failed ASSERT_PRED4 where the // predicate-formatter is a functor on a user-defined type (Bool). TEST_F(ASSERT_PRED4Test, FunctorOnUserTypeFailure) { expected_to_finish_ = false; - EXPECT_FATAL_FAILURE({ // NOLINT - ASSERT_PRED4(PredFunctor4(), - Bool(n1_++), - Bool(n2_++), - Bool(n3_++), - Bool(n4_++)); - finished_ = true; - }, ""); + EXPECT_FATAL_FAILURE( + { // NOLINT + ASSERT_PRED4(PredFunctor4(), Bool(n1_++), Bool(n2_++), Bool(n3_++), + Bool(n4_++)); + finished_ = true; + }, + ""); } // Tests a successful EXPECT_PRED_FORMAT4 where the // predicate-formatter is a function on a built-in type (int). TEST_F(EXPECT_PRED_FORMAT4Test, FunctionOnBuiltInTypeSuccess) { - EXPECT_PRED_FORMAT4(PredFormatFunction4, - ++n1_, - ++n2_, - ++n3_, - ++n4_); + EXPECT_PRED_FORMAT4(PredFormatFunction4, ++n1_, ++n2_, ++n3_, ++n4_); finished_ = true; } // Tests a successful EXPECT_PRED_FORMAT4 where the // predicate-formatter is a function on a user-defined type (Bool). TEST_F(EXPECT_PRED_FORMAT4Test, FunctionOnUserTypeSuccess) { - EXPECT_PRED_FORMAT4(PredFormatFunction4, - Bool(++n1_), - Bool(++n2_), - Bool(++n3_), - Bool(++n4_)); + EXPECT_PRED_FORMAT4(PredFormatFunction4, Bool(++n1_), Bool(++n2_), + Bool(++n3_), Bool(++n4_)); finished_ = true; } // Tests a successful EXPECT_PRED_FORMAT4 where the // predicate-formatter is a functor on a built-in type (int). TEST_F(EXPECT_PRED_FORMAT4Test, FunctorOnBuiltInTypeSuccess) { - EXPECT_PRED_FORMAT4(PredFormatFunctor4(), - ++n1_, - ++n2_, - ++n3_, - ++n4_); + EXPECT_PRED_FORMAT4(PredFormatFunctor4(), ++n1_, ++n2_, ++n3_, ++n4_); finished_ = true; } // Tests a successful EXPECT_PRED_FORMAT4 where the // predicate-formatter is a functor on a user-defined type (Bool). TEST_F(EXPECT_PRED_FORMAT4Test, FunctorOnUserTypeSuccess) { - EXPECT_PRED_FORMAT4(PredFormatFunctor4(), - Bool(++n1_), - Bool(++n2_), - Bool(++n3_), - Bool(++n4_)); + EXPECT_PRED_FORMAT4(PredFormatFunctor4(), Bool(++n1_), Bool(++n2_), + Bool(++n3_), Bool(++n4_)); finished_ = true; } // Tests a failed EXPECT_PRED_FORMAT4 where the // predicate-formatter is a function on a built-in type (int). TEST_F(EXPECT_PRED_FORMAT4Test, FunctionOnBuiltInTypeFailure) { - EXPECT_NONFATAL_FAILURE({ // NOLINT - EXPECT_PRED_FORMAT4(PredFormatFunction4, - n1_++, - n2_++, - n3_++, - n4_++); - finished_ = true; - }, ""); + EXPECT_NONFATAL_FAILURE( + { // NOLINT + EXPECT_PRED_FORMAT4(PredFormatFunction4, n1_++, n2_++, n3_++, n4_++); + finished_ = true; + }, + ""); } // Tests a failed EXPECT_PRED_FORMAT4 where the // predicate-formatter is a function on a user-defined type (Bool). TEST_F(EXPECT_PRED_FORMAT4Test, FunctionOnUserTypeFailure) { - EXPECT_NONFATAL_FAILURE({ // NOLINT - EXPECT_PRED_FORMAT4(PredFormatFunction4, - Bool(n1_++), - Bool(n2_++), - Bool(n3_++), - Bool(n4_++)); - finished_ = true; - }, ""); + EXPECT_NONFATAL_FAILURE( + { // NOLINT + EXPECT_PRED_FORMAT4(PredFormatFunction4, Bool(n1_++), Bool(n2_++), + Bool(n3_++), Bool(n4_++)); + finished_ = true; + }, + ""); } // Tests a failed EXPECT_PRED_FORMAT4 where the // predicate-formatter is a functor on a built-in type (int). TEST_F(EXPECT_PRED_FORMAT4Test, FunctorOnBuiltInTypeFailure) { - EXPECT_NONFATAL_FAILURE({ // NOLINT - EXPECT_PRED_FORMAT4(PredFormatFunctor4(), - n1_++, - n2_++, - n3_++, - n4_++); - finished_ = true; - }, ""); + EXPECT_NONFATAL_FAILURE( + { // NOLINT + EXPECT_PRED_FORMAT4(PredFormatFunctor4(), n1_++, n2_++, n3_++, n4_++); + finished_ = true; + }, + ""); } // Tests a failed EXPECT_PRED_FORMAT4 where the // predicate-formatter is a functor on a user-defined type (Bool). TEST_F(EXPECT_PRED_FORMAT4Test, FunctorOnUserTypeFailure) { - EXPECT_NONFATAL_FAILURE({ // NOLINT - EXPECT_PRED_FORMAT4(PredFormatFunctor4(), - Bool(n1_++), - Bool(n2_++), - Bool(n3_++), - Bool(n4_++)); - finished_ = true; - }, ""); + EXPECT_NONFATAL_FAILURE( + { // NOLINT + EXPECT_PRED_FORMAT4(PredFormatFunctor4(), Bool(n1_++), Bool(n2_++), + Bool(n3_++), Bool(n4_++)); + finished_ = true; + }, + ""); } // Tests a successful ASSERT_PRED_FORMAT4 where the // predicate-formatter is a function on a built-in type (int). TEST_F(ASSERT_PRED_FORMAT4Test, FunctionOnBuiltInTypeSuccess) { - ASSERT_PRED_FORMAT4(PredFormatFunction4, - ++n1_, - ++n2_, - ++n3_, - ++n4_); + ASSERT_PRED_FORMAT4(PredFormatFunction4, ++n1_, ++n2_, ++n3_, ++n4_); finished_ = true; } // Tests a successful ASSERT_PRED_FORMAT4 where the // predicate-formatter is a function on a user-defined type (Bool). TEST_F(ASSERT_PRED_FORMAT4Test, FunctionOnUserTypeSuccess) { - ASSERT_PRED_FORMAT4(PredFormatFunction4, - Bool(++n1_), - Bool(++n2_), - Bool(++n3_), - Bool(++n4_)); + ASSERT_PRED_FORMAT4(PredFormatFunction4, Bool(++n1_), Bool(++n2_), + Bool(++n3_), Bool(++n4_)); finished_ = true; } // Tests a successful ASSERT_PRED_FORMAT4 where the // predicate-formatter is a functor on a built-in type (int). TEST_F(ASSERT_PRED_FORMAT4Test, FunctorOnBuiltInTypeSuccess) { - ASSERT_PRED_FORMAT4(PredFormatFunctor4(), - ++n1_, - ++n2_, - ++n3_, - ++n4_); + ASSERT_PRED_FORMAT4(PredFormatFunctor4(), ++n1_, ++n2_, ++n3_, ++n4_); finished_ = true; } // Tests a successful ASSERT_PRED_FORMAT4 where the // predicate-formatter is a functor on a user-defined type (Bool). TEST_F(ASSERT_PRED_FORMAT4Test, FunctorOnUserTypeSuccess) { - ASSERT_PRED_FORMAT4(PredFormatFunctor4(), - Bool(++n1_), - Bool(++n2_), - Bool(++n3_), - Bool(++n4_)); + ASSERT_PRED_FORMAT4(PredFormatFunctor4(), Bool(++n1_), Bool(++n2_), + Bool(++n3_), Bool(++n4_)); finished_ = true; } @@ -1812,56 +1595,50 @@ TEST_F(ASSERT_PRED_FORMAT4Test, FunctorOnUserTypeSuccess) { // predicate-formatter is a function on a built-in type (int). TEST_F(ASSERT_PRED_FORMAT4Test, FunctionOnBuiltInTypeFailure) { expected_to_finish_ = false; - EXPECT_FATAL_FAILURE({ // NOLINT - ASSERT_PRED_FORMAT4(PredFormatFunction4, - n1_++, - n2_++, - n3_++, - n4_++); - finished_ = true; - }, ""); + EXPECT_FATAL_FAILURE( + { // NOLINT + ASSERT_PRED_FORMAT4(PredFormatFunction4, n1_++, n2_++, n3_++, n4_++); + finished_ = true; + }, + ""); } // Tests a failed ASSERT_PRED_FORMAT4 where the // predicate-formatter is a function on a user-defined type (Bool). TEST_F(ASSERT_PRED_FORMAT4Test, FunctionOnUserTypeFailure) { expected_to_finish_ = false; - EXPECT_FATAL_FAILURE({ // NOLINT - ASSERT_PRED_FORMAT4(PredFormatFunction4, - Bool(n1_++), - Bool(n2_++), - Bool(n3_++), - Bool(n4_++)); - finished_ = true; - }, ""); + EXPECT_FATAL_FAILURE( + { // NOLINT + ASSERT_PRED_FORMAT4(PredFormatFunction4, Bool(n1_++), Bool(n2_++), + Bool(n3_++), Bool(n4_++)); + finished_ = true; + }, + ""); } // Tests a failed ASSERT_PRED_FORMAT4 where the // predicate-formatter is a functor on a built-in type (int). TEST_F(ASSERT_PRED_FORMAT4Test, FunctorOnBuiltInTypeFailure) { expected_to_finish_ = false; - EXPECT_FATAL_FAILURE({ // NOLINT - ASSERT_PRED_FORMAT4(PredFormatFunctor4(), - n1_++, - n2_++, - n3_++, - n4_++); - finished_ = true; - }, ""); + EXPECT_FATAL_FAILURE( + { // NOLINT + ASSERT_PRED_FORMAT4(PredFormatFunctor4(), n1_++, n2_++, n3_++, n4_++); + finished_ = true; + }, + ""); } // Tests a failed ASSERT_PRED_FORMAT4 where the // predicate-formatter is a functor on a user-defined type (Bool). TEST_F(ASSERT_PRED_FORMAT4Test, FunctorOnUserTypeFailure) { expected_to_finish_ = false; - EXPECT_FATAL_FAILURE({ // NOLINT - ASSERT_PRED_FORMAT4(PredFormatFunctor4(), - Bool(n1_++), - Bool(n2_++), - Bool(n3_++), - Bool(n4_++)); - finished_ = true; - }, ""); + EXPECT_FATAL_FAILURE( + { // NOLINT + ASSERT_PRED_FORMAT4(PredFormatFunctor4(), Bool(n1_++), Bool(n2_++), + Bool(n3_++), Bool(n4_++)); + finished_ = true; + }, + ""); } // Sample functions/functors for testing 5-ary predicate assertions. @@ -1883,10 +1660,7 @@ bool PredFunction5Bool(Bool v1, Bool v2, Bool v3, Bool v4, Bool v5) { // A 5-ary predicate functor. struct PredFunctor5 { template <typename T1, typename T2, typename T3, typename T4, typename T5> - bool operator()(const T1& v1, - const T2& v2, - const T3& v3, - const T4& v4, + bool operator()(const T1& v1, const T2& v2, const T3& v3, const T4& v4, const T5& v5) { return v1 + v2 + v3 + v4 + v5 > 0; } @@ -1894,37 +1668,26 @@ struct PredFunctor5 { // A 5-ary predicate-formatter function. template <typename T1, typename T2, typename T3, typename T4, typename T5> -testing::AssertionResult PredFormatFunction5(const char* e1, - const char* e2, - const char* e3, - const char* e4, - const char* e5, - const T1& v1, - const T2& v2, - const T3& v3, - const T4& v4, - const T5& v5) { - if (PredFunction5(v1, v2, v3, v4, v5)) - return testing::AssertionSuccess(); +testing::AssertionResult PredFormatFunction5(const char* e1, const char* e2, + const char* e3, const char* e4, + const char* e5, const T1& v1, + const T2& v2, const T3& v3, + const T4& v4, const T5& v5) { + if (PredFunction5(v1, v2, v3, v4, v5)) return testing::AssertionSuccess(); return testing::AssertionFailure() - << e1 << " + " << e2 << " + " << e3 << " + " << e4 << " + " << e5 - << " is expected to be positive, but evaluates to " - << v1 + v2 + v3 + v4 + v5 << "."; + << e1 << " + " << e2 << " + " << e3 << " + " << e4 << " + " << e5 + << " is expected to be positive, but evaluates to " + << v1 + v2 + v3 + v4 + v5 << "."; } // A 5-ary predicate-formatter functor. struct PredFormatFunctor5 { template <typename T1, typename T2, typename T3, typename T4, typename T5> - testing::AssertionResult operator()(const char* e1, - const char* e2, - const char* e3, - const char* e4, - const char* e5, - const T1& v1, - const T2& v2, - const T3& v3, - const T4& v4, + testing::AssertionResult operator()(const char* e1, const char* e2, + const char* e3, const char* e4, + const char* e5, const T1& v1, + const T2& v2, const T3& v3, const T4& v4, const T5& v5) const { return PredFormatFunction5(e1, e2, e3, e4, e5, v1, v2, v3, v4, v5); } @@ -1943,21 +1706,16 @@ class Predicate5Test : public testing::Test { void TearDown() override { // Verifies that each of the predicate's arguments was evaluated // exactly once. - EXPECT_EQ(1, n1_) << - "The predicate assertion didn't evaluate argument 2 " - "exactly once."; - EXPECT_EQ(1, n2_) << - "The predicate assertion didn't evaluate argument 3 " - "exactly once."; - EXPECT_EQ(1, n3_) << - "The predicate assertion didn't evaluate argument 4 " - "exactly once."; - EXPECT_EQ(1, n4_) << - "The predicate assertion didn't evaluate argument 5 " - "exactly once."; - EXPECT_EQ(1, n5_) << - "The predicate assertion didn't evaluate argument 6 " - "exactly once."; + EXPECT_EQ(1, n1_) << "The predicate assertion didn't evaluate argument 2 " + "exactly once."; + EXPECT_EQ(1, n2_) << "The predicate assertion didn't evaluate argument 3 " + "exactly once."; + EXPECT_EQ(1, n3_) << "The predicate assertion didn't evaluate argument 4 " + "exactly once."; + EXPECT_EQ(1, n4_) << "The predicate assertion didn't evaluate argument 5 " + "exactly once."; + EXPECT_EQ(1, n5_) << "The predicate assertion didn't evaluate argument 6 " + "exactly once."; // Verifies that the control flow in the test function is expected. if (expected_to_finish_ && !finished_) { @@ -1997,152 +1755,106 @@ typedef Predicate5Test ASSERT_PRED5Test; // Tests a successful EXPECT_PRED5 where the // predicate-formatter is a function on a built-in type (int). TEST_F(EXPECT_PRED5Test, FunctionOnBuiltInTypeSuccess) { - EXPECT_PRED5(PredFunction5Int, - ++n1_, - ++n2_, - ++n3_, - ++n4_, - ++n5_); + EXPECT_PRED5(PredFunction5Int, ++n1_, ++n2_, ++n3_, ++n4_, ++n5_); finished_ = true; } // Tests a successful EXPECT_PRED5 where the // predicate-formatter is a function on a user-defined type (Bool). TEST_F(EXPECT_PRED5Test, FunctionOnUserTypeSuccess) { - EXPECT_PRED5(PredFunction5Bool, - Bool(++n1_), - Bool(++n2_), - Bool(++n3_), - Bool(++n4_), - Bool(++n5_)); + EXPECT_PRED5(PredFunction5Bool, Bool(++n1_), Bool(++n2_), Bool(++n3_), + Bool(++n4_), Bool(++n5_)); finished_ = true; } // Tests a successful EXPECT_PRED5 where the // predicate-formatter is a functor on a built-in type (int). TEST_F(EXPECT_PRED5Test, FunctorOnBuiltInTypeSuccess) { - EXPECT_PRED5(PredFunctor5(), - ++n1_, - ++n2_, - ++n3_, - ++n4_, - ++n5_); + EXPECT_PRED5(PredFunctor5(), ++n1_, ++n2_, ++n3_, ++n4_, ++n5_); finished_ = true; } // Tests a successful EXPECT_PRED5 where the // predicate-formatter is a functor on a user-defined type (Bool). TEST_F(EXPECT_PRED5Test, FunctorOnUserTypeSuccess) { - EXPECT_PRED5(PredFunctor5(), - Bool(++n1_), - Bool(++n2_), - Bool(++n3_), - Bool(++n4_), - Bool(++n5_)); + EXPECT_PRED5(PredFunctor5(), Bool(++n1_), Bool(++n2_), Bool(++n3_), + Bool(++n4_), Bool(++n5_)); finished_ = true; } // Tests a failed EXPECT_PRED5 where the // predicate-formatter is a function on a built-in type (int). TEST_F(EXPECT_PRED5Test, FunctionOnBuiltInTypeFailure) { - EXPECT_NONFATAL_FAILURE({ // NOLINT - EXPECT_PRED5(PredFunction5Int, - n1_++, - n2_++, - n3_++, - n4_++, - n5_++); - finished_ = true; - }, ""); + EXPECT_NONFATAL_FAILURE( + { // NOLINT + EXPECT_PRED5(PredFunction5Int, n1_++, n2_++, n3_++, n4_++, n5_++); + finished_ = true; + }, + ""); } // Tests a failed EXPECT_PRED5 where the // predicate-formatter is a function on a user-defined type (Bool). TEST_F(EXPECT_PRED5Test, FunctionOnUserTypeFailure) { - EXPECT_NONFATAL_FAILURE({ // NOLINT - EXPECT_PRED5(PredFunction5Bool, - Bool(n1_++), - Bool(n2_++), - Bool(n3_++), - Bool(n4_++), - Bool(n5_++)); - finished_ = true; - }, ""); + EXPECT_NONFATAL_FAILURE( + { // NOLINT + EXPECT_PRED5(PredFunction5Bool, Bool(n1_++), Bool(n2_++), Bool(n3_++), + Bool(n4_++), Bool(n5_++)); + finished_ = true; + }, + ""); } // Tests a failed EXPECT_PRED5 where the // predicate-formatter is a functor on a built-in type (int). TEST_F(EXPECT_PRED5Test, FunctorOnBuiltInTypeFailure) { - EXPECT_NONFATAL_FAILURE({ // NOLINT - EXPECT_PRED5(PredFunctor5(), - n1_++, - n2_++, - n3_++, - n4_++, - n5_++); - finished_ = true; - }, ""); + EXPECT_NONFATAL_FAILURE( + { // NOLINT + EXPECT_PRED5(PredFunctor5(), n1_++, n2_++, n3_++, n4_++, n5_++); + finished_ = true; + }, + ""); } // Tests a failed EXPECT_PRED5 where the // predicate-formatter is a functor on a user-defined type (Bool). TEST_F(EXPECT_PRED5Test, FunctorOnUserTypeFailure) { - EXPECT_NONFATAL_FAILURE({ // NOLINT - EXPECT_PRED5(PredFunctor5(), - Bool(n1_++), - Bool(n2_++), - Bool(n3_++), - Bool(n4_++), - Bool(n5_++)); - finished_ = true; - }, ""); + EXPECT_NONFATAL_FAILURE( + { // NOLINT + EXPECT_PRED5(PredFunctor5(), Bool(n1_++), Bool(n2_++), Bool(n3_++), + Bool(n4_++), Bool(n5_++)); + finished_ = true; + }, + ""); } // Tests a successful ASSERT_PRED5 where the // predicate-formatter is a function on a built-in type (int). TEST_F(ASSERT_PRED5Test, FunctionOnBuiltInTypeSuccess) { - ASSERT_PRED5(PredFunction5Int, - ++n1_, - ++n2_, - ++n3_, - ++n4_, - ++n5_); + ASSERT_PRED5(PredFunction5Int, ++n1_, ++n2_, ++n3_, ++n4_, ++n5_); finished_ = true; } // Tests a successful ASSERT_PRED5 where the // predicate-formatter is a function on a user-defined type (Bool). TEST_F(ASSERT_PRED5Test, FunctionOnUserTypeSuccess) { - ASSERT_PRED5(PredFunction5Bool, - Bool(++n1_), - Bool(++n2_), - Bool(++n3_), - Bool(++n4_), - Bool(++n5_)); + ASSERT_PRED5(PredFunction5Bool, Bool(++n1_), Bool(++n2_), Bool(++n3_), + Bool(++n4_), Bool(++n5_)); finished_ = true; } // Tests a successful ASSERT_PRED5 where the // predicate-formatter is a functor on a built-in type (int). TEST_F(ASSERT_PRED5Test, FunctorOnBuiltInTypeSuccess) { - ASSERT_PRED5(PredFunctor5(), - ++n1_, - ++n2_, - ++n3_, - ++n4_, - ++n5_); + ASSERT_PRED5(PredFunctor5(), ++n1_, ++n2_, ++n3_, ++n4_, ++n5_); finished_ = true; } // Tests a successful ASSERT_PRED5 where the // predicate-formatter is a functor on a user-defined type (Bool). TEST_F(ASSERT_PRED5Test, FunctorOnUserTypeSuccess) { - ASSERT_PRED5(PredFunctor5(), - Bool(++n1_), - Bool(++n2_), - Bool(++n3_), - Bool(++n4_), - Bool(++n5_)); + ASSERT_PRED5(PredFunctor5(), Bool(++n1_), Bool(++n2_), Bool(++n3_), + Bool(++n4_), Bool(++n5_)); finished_ = true; } @@ -2150,211 +1862,157 @@ TEST_F(ASSERT_PRED5Test, FunctorOnUserTypeSuccess) { // predicate-formatter is a function on a built-in type (int). TEST_F(ASSERT_PRED5Test, FunctionOnBuiltInTypeFailure) { expected_to_finish_ = false; - EXPECT_FATAL_FAILURE({ // NOLINT - ASSERT_PRED5(PredFunction5Int, - n1_++, - n2_++, - n3_++, - n4_++, - n5_++); - finished_ = true; - }, ""); + EXPECT_FATAL_FAILURE( + { // NOLINT + ASSERT_PRED5(PredFunction5Int, n1_++, n2_++, n3_++, n4_++, n5_++); + finished_ = true; + }, + ""); } // Tests a failed ASSERT_PRED5 where the // predicate-formatter is a function on a user-defined type (Bool). TEST_F(ASSERT_PRED5Test, FunctionOnUserTypeFailure) { expected_to_finish_ = false; - EXPECT_FATAL_FAILURE({ // NOLINT - ASSERT_PRED5(PredFunction5Bool, - Bool(n1_++), - Bool(n2_++), - Bool(n3_++), - Bool(n4_++), - Bool(n5_++)); - finished_ = true; - }, ""); + EXPECT_FATAL_FAILURE( + { // NOLINT + ASSERT_PRED5(PredFunction5Bool, Bool(n1_++), Bool(n2_++), Bool(n3_++), + Bool(n4_++), Bool(n5_++)); + finished_ = true; + }, + ""); } // Tests a failed ASSERT_PRED5 where the // predicate-formatter is a functor on a built-in type (int). TEST_F(ASSERT_PRED5Test, FunctorOnBuiltInTypeFailure) { expected_to_finish_ = false; - EXPECT_FATAL_FAILURE({ // NOLINT - ASSERT_PRED5(PredFunctor5(), - n1_++, - n2_++, - n3_++, - n4_++, - n5_++); - finished_ = true; - }, ""); + EXPECT_FATAL_FAILURE( + { // NOLINT + ASSERT_PRED5(PredFunctor5(), n1_++, n2_++, n3_++, n4_++, n5_++); + finished_ = true; + }, + ""); } // Tests a failed ASSERT_PRED5 where the // predicate-formatter is a functor on a user-defined type (Bool). TEST_F(ASSERT_PRED5Test, FunctorOnUserTypeFailure) { expected_to_finish_ = false; - EXPECT_FATAL_FAILURE({ // NOLINT - ASSERT_PRED5(PredFunctor5(), - Bool(n1_++), - Bool(n2_++), - Bool(n3_++), - Bool(n4_++), - Bool(n5_++)); - finished_ = true; - }, ""); + EXPECT_FATAL_FAILURE( + { // NOLINT + ASSERT_PRED5(PredFunctor5(), Bool(n1_++), Bool(n2_++), Bool(n3_++), + Bool(n4_++), Bool(n5_++)); + finished_ = true; + }, + ""); } // Tests a successful EXPECT_PRED_FORMAT5 where the // predicate-formatter is a function on a built-in type (int). TEST_F(EXPECT_PRED_FORMAT5Test, FunctionOnBuiltInTypeSuccess) { - EXPECT_PRED_FORMAT5(PredFormatFunction5, - ++n1_, - ++n2_, - ++n3_, - ++n4_, - ++n5_); + EXPECT_PRED_FORMAT5(PredFormatFunction5, ++n1_, ++n2_, ++n3_, ++n4_, ++n5_); finished_ = true; } // Tests a successful EXPECT_PRED_FORMAT5 where the // predicate-formatter is a function on a user-defined type (Bool). TEST_F(EXPECT_PRED_FORMAT5Test, FunctionOnUserTypeSuccess) { - EXPECT_PRED_FORMAT5(PredFormatFunction5, - Bool(++n1_), - Bool(++n2_), - Bool(++n3_), - Bool(++n4_), - Bool(++n5_)); + EXPECT_PRED_FORMAT5(PredFormatFunction5, Bool(++n1_), Bool(++n2_), + Bool(++n3_), Bool(++n4_), Bool(++n5_)); finished_ = true; } // Tests a successful EXPECT_PRED_FORMAT5 where the // predicate-formatter is a functor on a built-in type (int). TEST_F(EXPECT_PRED_FORMAT5Test, FunctorOnBuiltInTypeSuccess) { - EXPECT_PRED_FORMAT5(PredFormatFunctor5(), - ++n1_, - ++n2_, - ++n3_, - ++n4_, - ++n5_); + EXPECT_PRED_FORMAT5(PredFormatFunctor5(), ++n1_, ++n2_, ++n3_, ++n4_, ++n5_); finished_ = true; } // Tests a successful EXPECT_PRED_FORMAT5 where the // predicate-formatter is a functor on a user-defined type (Bool). TEST_F(EXPECT_PRED_FORMAT5Test, FunctorOnUserTypeSuccess) { - EXPECT_PRED_FORMAT5(PredFormatFunctor5(), - Bool(++n1_), - Bool(++n2_), - Bool(++n3_), - Bool(++n4_), - Bool(++n5_)); + EXPECT_PRED_FORMAT5(PredFormatFunctor5(), Bool(++n1_), Bool(++n2_), + Bool(++n3_), Bool(++n4_), Bool(++n5_)); finished_ = true; } // Tests a failed EXPECT_PRED_FORMAT5 where the // predicate-formatter is a function on a built-in type (int). TEST_F(EXPECT_PRED_FORMAT5Test, FunctionOnBuiltInTypeFailure) { - EXPECT_NONFATAL_FAILURE({ // NOLINT - EXPECT_PRED_FORMAT5(PredFormatFunction5, - n1_++, - n2_++, - n3_++, - n4_++, - n5_++); - finished_ = true; - }, ""); + EXPECT_NONFATAL_FAILURE( + { // NOLINT + EXPECT_PRED_FORMAT5(PredFormatFunction5, n1_++, n2_++, n3_++, n4_++, + n5_++); + finished_ = true; + }, + ""); } // Tests a failed EXPECT_PRED_FORMAT5 where the // predicate-formatter is a function on a user-defined type (Bool). TEST_F(EXPECT_PRED_FORMAT5Test, FunctionOnUserTypeFailure) { - EXPECT_NONFATAL_FAILURE({ // NOLINT - EXPECT_PRED_FORMAT5(PredFormatFunction5, - Bool(n1_++), - Bool(n2_++), - Bool(n3_++), - Bool(n4_++), - Bool(n5_++)); - finished_ = true; - }, ""); + EXPECT_NONFATAL_FAILURE( + { // NOLINT + EXPECT_PRED_FORMAT5(PredFormatFunction5, Bool(n1_++), Bool(n2_++), + Bool(n3_++), Bool(n4_++), Bool(n5_++)); + finished_ = true; + }, + ""); } // Tests a failed EXPECT_PRED_FORMAT5 where the // predicate-formatter is a functor on a built-in type (int). TEST_F(EXPECT_PRED_FORMAT5Test, FunctorOnBuiltInTypeFailure) { - EXPECT_NONFATAL_FAILURE({ // NOLINT - EXPECT_PRED_FORMAT5(PredFormatFunctor5(), - n1_++, - n2_++, - n3_++, - n4_++, - n5_++); - finished_ = true; - }, ""); + EXPECT_NONFATAL_FAILURE( + { // NOLINT + EXPECT_PRED_FORMAT5(PredFormatFunctor5(), n1_++, n2_++, n3_++, n4_++, + n5_++); + finished_ = true; + }, + ""); } // Tests a failed EXPECT_PRED_FORMAT5 where the // predicate-formatter is a functor on a user-defined type (Bool). TEST_F(EXPECT_PRED_FORMAT5Test, FunctorOnUserTypeFailure) { - EXPECT_NONFATAL_FAILURE({ // NOLINT - EXPECT_PRED_FORMAT5(PredFormatFunctor5(), - Bool(n1_++), - Bool(n2_++), - Bool(n3_++), - Bool(n4_++), - Bool(n5_++)); - finished_ = true; - }, ""); + EXPECT_NONFATAL_FAILURE( + { // NOLINT + EXPECT_PRED_FORMAT5(PredFormatFunctor5(), Bool(n1_++), Bool(n2_++), + Bool(n3_++), Bool(n4_++), Bool(n5_++)); + finished_ = true; + }, + ""); } // Tests a successful ASSERT_PRED_FORMAT5 where the // predicate-formatter is a function on a built-in type (int). TEST_F(ASSERT_PRED_FORMAT5Test, FunctionOnBuiltInTypeSuccess) { - ASSERT_PRED_FORMAT5(PredFormatFunction5, - ++n1_, - ++n2_, - ++n3_, - ++n4_, - ++n5_); + ASSERT_PRED_FORMAT5(PredFormatFunction5, ++n1_, ++n2_, ++n3_, ++n4_, ++n5_); finished_ = true; } // Tests a successful ASSERT_PRED_FORMAT5 where the // predicate-formatter is a function on a user-defined type (Bool). TEST_F(ASSERT_PRED_FORMAT5Test, FunctionOnUserTypeSuccess) { - ASSERT_PRED_FORMAT5(PredFormatFunction5, - Bool(++n1_), - Bool(++n2_), - Bool(++n3_), - Bool(++n4_), - Bool(++n5_)); + ASSERT_PRED_FORMAT5(PredFormatFunction5, Bool(++n1_), Bool(++n2_), + Bool(++n3_), Bool(++n4_), Bool(++n5_)); finished_ = true; } // Tests a successful ASSERT_PRED_FORMAT5 where the // predicate-formatter is a functor on a built-in type (int). TEST_F(ASSERT_PRED_FORMAT5Test, FunctorOnBuiltInTypeSuccess) { - ASSERT_PRED_FORMAT5(PredFormatFunctor5(), - ++n1_, - ++n2_, - ++n3_, - ++n4_, - ++n5_); + ASSERT_PRED_FORMAT5(PredFormatFunctor5(), ++n1_, ++n2_, ++n3_, ++n4_, ++n5_); finished_ = true; } // Tests a successful ASSERT_PRED_FORMAT5 where the // predicate-formatter is a functor on a user-defined type (Bool). TEST_F(ASSERT_PRED_FORMAT5Test, FunctorOnUserTypeSuccess) { - ASSERT_PRED_FORMAT5(PredFormatFunctor5(), - Bool(++n1_), - Bool(++n2_), - Bool(++n3_), - Bool(++n4_), - Bool(++n5_)); + ASSERT_PRED_FORMAT5(PredFormatFunctor5(), Bool(++n1_), Bool(++n2_), + Bool(++n3_), Bool(++n4_), Bool(++n5_)); finished_ = true; } @@ -2362,58 +2020,50 @@ TEST_F(ASSERT_PRED_FORMAT5Test, FunctorOnUserTypeSuccess) { // predicate-formatter is a function on a built-in type (int). TEST_F(ASSERT_PRED_FORMAT5Test, FunctionOnBuiltInTypeFailure) { expected_to_finish_ = false; - EXPECT_FATAL_FAILURE({ // NOLINT - ASSERT_PRED_FORMAT5(PredFormatFunction5, - n1_++, - n2_++, - n3_++, - n4_++, - n5_++); - finished_ = true; - }, ""); + EXPECT_FATAL_FAILURE( + { // NOLINT + ASSERT_PRED_FORMAT5(PredFormatFunction5, n1_++, n2_++, n3_++, n4_++, + n5_++); + finished_ = true; + }, + ""); } // Tests a failed ASSERT_PRED_FORMAT5 where the // predicate-formatter is a function on a user-defined type (Bool). TEST_F(ASSERT_PRED_FORMAT5Test, FunctionOnUserTypeFailure) { expected_to_finish_ = false; - EXPECT_FATAL_FAILURE({ // NOLINT - ASSERT_PRED_FORMAT5(PredFormatFunction5, - Bool(n1_++), - Bool(n2_++), - Bool(n3_++), - Bool(n4_++), - Bool(n5_++)); - finished_ = true; - }, ""); + EXPECT_FATAL_FAILURE( + { // NOLINT + ASSERT_PRED_FORMAT5(PredFormatFunction5, Bool(n1_++), Bool(n2_++), + Bool(n3_++), Bool(n4_++), Bool(n5_++)); + finished_ = true; + }, + ""); } // Tests a failed ASSERT_PRED_FORMAT5 where the // predicate-formatter is a functor on a built-in type (int). TEST_F(ASSERT_PRED_FORMAT5Test, FunctorOnBuiltInTypeFailure) { expected_to_finish_ = false; - EXPECT_FATAL_FAILURE({ // NOLINT - ASSERT_PRED_FORMAT5(PredFormatFunctor5(), - n1_++, - n2_++, - n3_++, - n4_++, - n5_++); - finished_ = true; - }, ""); + EXPECT_FATAL_FAILURE( + { // NOLINT + ASSERT_PRED_FORMAT5(PredFormatFunctor5(), n1_++, n2_++, n3_++, n4_++, + n5_++); + finished_ = true; + }, + ""); } // Tests a failed ASSERT_PRED_FORMAT5 where the // predicate-formatter is a functor on a user-defined type (Bool). TEST_F(ASSERT_PRED_FORMAT5Test, FunctorOnUserTypeFailure) { expected_to_finish_ = false; - EXPECT_FATAL_FAILURE({ // NOLINT - ASSERT_PRED_FORMAT5(PredFormatFunctor5(), - Bool(n1_++), - Bool(n2_++), - Bool(n3_++), - Bool(n4_++), - Bool(n5_++)); - finished_ = true; - }, ""); + EXPECT_FATAL_FAILURE( + { // NOLINT + ASSERT_PRED_FORMAT5(PredFormatFunctor5(), Bool(n1_++), Bool(n2_++), + Bool(n3_++), Bool(n4_++), Bool(n5_++)); + finished_ = true; + }, + ""); } diff --git a/googletest/test/gtest_premature_exit_test.cc b/googletest/test/gtest_premature_exit_test.cc index 1d1187e..1a0c5ea 100644 --- a/googletest/test/gtest_premature_exit_test.cc +++ b/googletest/test/gtest_premature_exit_test.cc @@ -81,15 +81,17 @@ TEST_F(PrematureExitDeathTest, FileExistsDuringExecutionOfDeathTest) { return; } - EXPECT_DEATH_IF_SUPPORTED({ - // If the file exists, crash the process such that the main test - // process will catch the (expected) crash and report a success; - // otherwise don't crash, which will cause the main test process - // to report that the death test has failed. - if (PrematureExitFileExists()) { - exit(1); - } - }, ""); + EXPECT_DEATH_IF_SUPPORTED( + { + // If the file exists, crash the process such that the main test + // process will catch the (expected) crash and report a success; + // otherwise don't crash, which will cause the main test process + // to report that the death test has failed. + if (PrematureExitFileExists()) { + exit(1); + } + }, + ""); } // Tests that the premature-exit file exists during the execution of a @@ -106,7 +108,7 @@ TEST_F(PrematureExitTest, PrematureExitFileExistsDuringTestExecution) { } // namespace -int main(int argc, char **argv) { +int main(int argc, char** argv) { InitGoogleTest(&argc, argv); const int exit_code = RUN_ALL_TESTS(); diff --git a/googletest/test/gtest_repeat_test.cc b/googletest/test/gtest_repeat_test.cc index 6b10048..73fb8dc 100644 --- a/googletest/test/gtest_repeat_test.cc +++ b/googletest/test/gtest_repeat_test.cc @@ -27,11 +27,12 @@ // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - // Tests the --gtest_repeat=number flag. #include <stdlib.h> + #include <iostream> + #include "gtest/gtest.h" #include "src/gtest-internal-inl.h" @@ -39,20 +40,19 @@ namespace { // We need this when we are testing Google Test itself and therefore // cannot use Google Test assertions. -#define GTEST_CHECK_INT_EQ_(expected, actual) \ - do {\ - const int expected_val = (expected);\ - const int actual_val = (actual);\ - if (::testing::internal::IsTrue(expected_val != actual_val)) {\ - ::std::cout << "Value of: " #actual "\n"\ - << " Actual: " << actual_val << "\n"\ - << "Expected: " #expected "\n"\ - << "Which is: " << expected_val << "\n";\ - ::testing::internal::posix::Abort();\ - }\ +#define GTEST_CHECK_INT_EQ_(expected, actual) \ + do { \ + const int expected_val = (expected); \ + const int actual_val = (actual); \ + if (::testing::internal::IsTrue(expected_val != actual_val)) { \ + ::std::cout << "Value of: " #actual "\n" \ + << " Actual: " << actual_val << "\n" \ + << "Expected: " #expected "\n" \ + << "Which is: " << expected_val << "\n"; \ + ::testing::internal::posix::Abort(); \ + } \ } while (::testing::internal::AlwaysFalse()) - // Used for verifying that global environment set-up and tear-down are // inside the --gtest_repeat loop. @@ -79,9 +79,7 @@ TEST(FooTest, ShouldFail) { int g_should_pass_count = 0; -TEST(FooTest, ShouldPass) { - g_should_pass_count++; -} +TEST(FooTest, ShouldPass) { g_should_pass_count++; } // A test that contains a thread-safe death test and a fast death // test. It should pass. @@ -108,8 +106,7 @@ TEST_P(MyParamTest, ShouldPass) { GTEST_CHECK_INT_EQ_(g_param_test_count % kNumberOfParamTests, GetParam()); g_param_test_count++; } -INSTANTIATE_TEST_SUITE_P(MyParamSequence, - MyParamTest, +INSTANTIATE_TEST_SUITE_P(MyParamSequence, MyParamTest, testing::Range(0, kNumberOfParamTests)); // Resets the count for each test. diff --git a/googletest/test/gtest_skip_in_environment_setup_test.cc b/googletest/test/gtest_skip_in_environment_setup_test.cc index 9372310..5f21c27 100644 --- a/googletest/test/gtest_skip_in_environment_setup_test.cc +++ b/googletest/test/gtest_skip_in_environment_setup_test.cc @@ -31,6 +31,7 @@ // testcases being skipped. #include <iostream> + #include "gtest/gtest.h" class SetupEnvironment : public testing::Environment { diff --git a/googletest/test/gtest_skip_test.cc b/googletest/test/gtest_skip_test.cc index 4a23004..e1b8d65 100644 --- a/googletest/test/gtest_skip_test.cc +++ b/googletest/test/gtest_skip_test.cc @@ -46,10 +46,6 @@ class Fixture : public Test { } }; -TEST_F(Fixture, SkipsOneTest) { - EXPECT_EQ(5, 7); -} +TEST_F(Fixture, SkipsOneTest) { EXPECT_EQ(5, 7); } -TEST_F(Fixture, SkipsAnotherTest) { - EXPECT_EQ(99, 100); -} +TEST_F(Fixture, SkipsAnotherTest) { EXPECT_EQ(99, 100); } diff --git a/googletest/test/gtest_sole_header_test.cc b/googletest/test/gtest_sole_header_test.cc index 1d94ac6..e8e22a8 100644 --- a/googletest/test/gtest_sole_header_test.cc +++ b/googletest/test/gtest_sole_header_test.cc @@ -35,9 +35,7 @@ namespace { -void Subroutine() { - EXPECT_EQ(42, 42); -} +void Subroutine() { EXPECT_EQ(42, 42); } TEST(NoFatalFailureTest, ExpectNoFatalFailure) { EXPECT_NO_FATAL_FAILURE(;); diff --git a/googletest/test/gtest_stress_test.cc b/googletest/test/gtest_stress_test.cc index 8434819..24b173f 100644 --- a/googletest/test/gtest_stress_test.cc +++ b/googletest/test/gtest_stress_test.cc @@ -27,14 +27,12 @@ // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - // Tests that SCOPED_TRACE() and various Google Test assertions can be // used in a large number of threads concurrently. -#include "gtest/gtest.h" - #include <vector> +#include "gtest/gtest.h" #include "src/gtest-internal-inl.h" #if GTEST_IS_THREADSAFE @@ -66,8 +64,7 @@ std::string IdToString(int id) { } void ExpectKeyAndValueWereRecordedForId( - const std::vector<TestProperty>& properties, - int id, const char* suffix) { + const std::vector<TestProperty>& properties, int id, const char* suffix) { TestPropertyKeyIs matches_key(IdToKey(id, suffix).c_str()); const std::vector<TestProperty>::const_iterator property = std::find_if(properties.begin(), properties.end(), matches_key); @@ -121,15 +118,13 @@ TEST(StressTest, CanUseScopedTraceAndAssertionsInManyThreads) { std::unique_ptr<ThreadWithParam<int> > threads[kThreadCount]; Notification threads_can_start; for (int i = 0; i != kThreadCount; i++) - threads[i].reset(new ThreadWithParam<int>(&ManyAsserts, - i, - &threads_can_start)); + threads[i].reset( + new ThreadWithParam<int>(&ManyAsserts, i, &threads_can_start)); threads_can_start.Notify(); // Blocks until all the threads are done. - for (int i = 0; i != kThreadCount; i++) - threads[i]->Join(); + for (int i = 0; i != kThreadCount; i++) threads[i]->Join(); } // Ensures that kThreadCount*kThreadCount failures have been reported. @@ -149,7 +144,7 @@ TEST(StressTest, CanUseScopedTraceAndAssertionsInManyThreads) { ExpectKeyAndValueWereRecordedForId(properties, i, "string"); ExpectKeyAndValueWereRecordedForId(properties, i, "int"); } - CheckTestFailureCount(kThreadCount*kThreadCount); + CheckTestFailureCount(kThreadCount * kThreadCount); } void FailingThread(bool is_fatal) { @@ -196,8 +191,8 @@ TEST(FatalFailureTest, ExpectFatalFailureIgnoresFailuresInOtherThreads) { TEST(FatalFailureOnAllThreadsTest, ExpectFatalFailureOnAllThreads) { // This statement should succeed, because failures in all threads are // considered. - EXPECT_FATAL_FAILURE_ON_ALL_THREADS( - GenerateFatalFailureInAnotherThread(true), "expected"); + EXPECT_FATAL_FAILURE_ON_ALL_THREADS(GenerateFatalFailureInAnotherThread(true), + "expected"); CheckTestFailureCount(0); // We need to add a failure, because main() checks that there are failures. // But when only this test is run, we shouldn't have any failures. @@ -226,7 +221,7 @@ TEST(NonFatalFailureOnAllThreadsTest, ExpectNonFatalFailureOnAllThreads) { } // namespace } // namespace testing -int main(int argc, char **argv) { +int main(int argc, char** argv) { testing::InitGoogleTest(&argc, argv); const int result = RUN_ALL_TESTS(); // Expected to fail. @@ -238,8 +233,7 @@ int main(int argc, char **argv) { #else TEST(StressTest, - DISABLED_ThreadSafetyTestsAreSkippedWhenGoogleTestIsNotThreadSafe) { -} + DISABLED_ThreadSafetyTestsAreSkippedWhenGoogleTestIsNotThreadSafe) {} int main(int argc, char **argv) { testing::InitGoogleTest(&argc, argv); diff --git a/googletest/test/gtest_test_macro_stack_footprint_test.cc b/googletest/test/gtest_test_macro_stack_footprint_test.cc index a48db05..45f368b 100644 --- a/googletest/test/gtest_test_macro_stack_footprint_test.cc +++ b/googletest/test/gtest_test_macro_stack_footprint_test.cc @@ -39,42 +39,42 @@ // This macro defines 10 dummy tests. #define TEN_TESTS_(test_case_name) \ - TEST(test_case_name, T0) {} \ - TEST(test_case_name, T1) {} \ - TEST(test_case_name, T2) {} \ - TEST(test_case_name, T3) {} \ - TEST(test_case_name, T4) {} \ - TEST(test_case_name, T5) {} \ - TEST(test_case_name, T6) {} \ - TEST(test_case_name, T7) {} \ - TEST(test_case_name, T8) {} \ + TEST(test_case_name, T0) {} \ + TEST(test_case_name, T1) {} \ + TEST(test_case_name, T2) {} \ + TEST(test_case_name, T3) {} \ + TEST(test_case_name, T4) {} \ + TEST(test_case_name, T5) {} \ + TEST(test_case_name, T6) {} \ + TEST(test_case_name, T7) {} \ + TEST(test_case_name, T8) {} \ TEST(test_case_name, T9) {} // This macro defines 100 dummy tests. #define HUNDRED_TESTS_(test_case_name_prefix) \ - TEN_TESTS_(test_case_name_prefix ## 0) \ - TEN_TESTS_(test_case_name_prefix ## 1) \ - TEN_TESTS_(test_case_name_prefix ## 2) \ - TEN_TESTS_(test_case_name_prefix ## 3) \ - TEN_TESTS_(test_case_name_prefix ## 4) \ - TEN_TESTS_(test_case_name_prefix ## 5) \ - TEN_TESTS_(test_case_name_prefix ## 6) \ - TEN_TESTS_(test_case_name_prefix ## 7) \ - TEN_TESTS_(test_case_name_prefix ## 8) \ - TEN_TESTS_(test_case_name_prefix ## 9) + TEN_TESTS_(test_case_name_prefix##0) \ + TEN_TESTS_(test_case_name_prefix##1) \ + TEN_TESTS_(test_case_name_prefix##2) \ + TEN_TESTS_(test_case_name_prefix##3) \ + TEN_TESTS_(test_case_name_prefix##4) \ + TEN_TESTS_(test_case_name_prefix##5) \ + TEN_TESTS_(test_case_name_prefix##6) \ + TEN_TESTS_(test_case_name_prefix##7) \ + TEN_TESTS_(test_case_name_prefix##8) \ + TEN_TESTS_(test_case_name_prefix##9) // This macro defines 1000 dummy tests. #define THOUSAND_TESTS_(test_case_name_prefix) \ - HUNDRED_TESTS_(test_case_name_prefix ## 0) \ - HUNDRED_TESTS_(test_case_name_prefix ## 1) \ - HUNDRED_TESTS_(test_case_name_prefix ## 2) \ - HUNDRED_TESTS_(test_case_name_prefix ## 3) \ - HUNDRED_TESTS_(test_case_name_prefix ## 4) \ - HUNDRED_TESTS_(test_case_name_prefix ## 5) \ - HUNDRED_TESTS_(test_case_name_prefix ## 6) \ - HUNDRED_TESTS_(test_case_name_prefix ## 7) \ - HUNDRED_TESTS_(test_case_name_prefix ## 8) \ - HUNDRED_TESTS_(test_case_name_prefix ## 9) + HUNDRED_TESTS_(test_case_name_prefix##0) \ + HUNDRED_TESTS_(test_case_name_prefix##1) \ + HUNDRED_TESTS_(test_case_name_prefix##2) \ + HUNDRED_TESTS_(test_case_name_prefix##3) \ + HUNDRED_TESTS_(test_case_name_prefix##4) \ + HUNDRED_TESTS_(test_case_name_prefix##5) \ + HUNDRED_TESTS_(test_case_name_prefix##6) \ + HUNDRED_TESTS_(test_case_name_prefix##7) \ + HUNDRED_TESTS_(test_case_name_prefix##8) \ + HUNDRED_TESTS_(test_case_name_prefix##9) // Ensures that we can define 1000 TEST()s in the same translation // unit. diff --git a/googletest/test/gtest_testbridge_test_.cc b/googletest/test/gtest_testbridge_test_.cc index 24617b2..c2c000d 100644 --- a/googletest/test/gtest_testbridge_test_.cc +++ b/googletest/test/gtest_testbridge_test_.cc @@ -27,7 +27,6 @@ // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - // This program is meant to be run by gtest_test_filter_test.py. Do not run // it directly. diff --git a/googletest/test/gtest_throw_on_failure_ex_test.cc b/googletest/test/gtest_throw_on_failure_ex_test.cc index aeead13..25d7c79 100644 --- a/googletest/test/gtest_throw_on_failure_ex_test.cc +++ b/googletest/test/gtest_throw_on_failure_ex_test.cc @@ -27,16 +27,16 @@ // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - // Tests Google Test's throw-on-failure mode with exceptions enabled. -#include "gtest/gtest.h" - -#include <stdlib.h> #include <stdio.h> +#include <stdlib.h> #include <string.h> + #include <stdexcept> +#include "gtest/gtest.h" + // Prints the given failure message and exits the program with // non-zero. We use this instead of a Google Test assertion to // indicate a failure, as the latter is been tested and cannot be @@ -55,14 +55,14 @@ void TestFailureThrowsRuntimeError() { // A successful assertion shouldn't throw. try { EXPECT_EQ(3, 3); - } catch(...) { + } catch (...) { Fail("A successful assertion wrongfully threw."); } // A failed assertion should throw a subclass of std::runtime_error. try { EXPECT_EQ(2, 3) << "Expected failure"; - } catch(const std::runtime_error& e) { + } catch (const std::runtime_error& e) { if (strstr(e.what(), "Expected failure") != nullptr) return; printf("%s", @@ -70,7 +70,7 @@ void TestFailureThrowsRuntimeError() { "but the message is incorrect. Instead of containing \"Expected " "failure\", it is:\n"); Fail(e.what()); - } catch(...) { + } catch (...) { Fail("A failed assertion threw the wrong type of exception."); } Fail("A failed assertion should've thrown but didn't."); diff --git a/googletest/test/gtest_unittest.cc b/googletest/test/gtest_unittest.cc index 936b7a2..9b26899 100644 --- a/googletest/test/gtest_unittest.cc +++ b/googletest/test/gtest_unittest.cc @@ -137,8 +137,8 @@ TEST_F(StreamingListenerTest, OnTestEnd) { TEST_F(StreamingListenerTest, OnTestPartResult) { *output() = ""; - streamer_.OnTestPartResult(TestPartResult( - TestPartResult::kFatalFailure, "foo.cc", 42, "failed=\n&%")); + streamer_.OnTestPartResult(TestPartResult(TestPartResult::kFatalFailure, + "foo.cc", 42, "failed=\n&%")); // Meta characters in the failure message should be properly escaped. EXPECT_EQ( @@ -272,11 +272,9 @@ using testing::internal::GetCapturedStdout; using testing::internal::ThreadWithParam; #endif -class TestingVector : public std::vector<int> { -}; +class TestingVector : public std::vector<int> {}; -::std::ostream& operator<<(::std::ostream& os, - const TestingVector& vector) { +::std::ostream& operator<<(::std::ostream& os, const TestingVector& vector) { os << "{ "; for (size_t i = 0; i < vector.size(); i++) { os << vector[i] << " "; @@ -420,8 +418,7 @@ class FormatEpochTimeInMillisAsIso8601Test : public Test { saved_tz_ = nullptr; GTEST_DISABLE_MSC_DEPRECATED_PUSH_(/* getenv, strdup: deprecated */) - if (getenv("TZ")) - saved_tz_ = strdup(getenv("TZ")); + if (getenv("TZ")) saved_tz_ = strdup(getenv("TZ")); GTEST_DISABLE_MSC_DEPRECATED_POP_() // Set up the time zone for FormatEpochTimeInMillisAsIso8601 to use. We @@ -476,9 +473,8 @@ TEST_F(FormatEpochTimeInMillisAsIso8601Test, PrintsTwoDigitSegments) { } TEST_F(FormatEpochTimeInMillisAsIso8601Test, IncludesMillisecondsAfterDot) { - EXPECT_EQ( - "2011-10-31T18:52:42.234", - FormatEpochTimeInMillisAsIso8601(1320087162 * kMillisPerSec + 234)); + EXPECT_EQ("2011-10-31T18:52:42.234", + FormatEpochTimeInMillisAsIso8601(1320087162 * kMillisPerSec + 234)); } TEST_F(FormatEpochTimeInMillisAsIso8601Test, PrintsLeadingZeroes) { @@ -495,10 +491,10 @@ TEST_F(FormatEpochTimeInMillisAsIso8601Test, PrintsEpochStart) { EXPECT_EQ("1970-01-01T00:00:00.000", FormatEpochTimeInMillisAsIso8601(0)); } -# ifdef __BORLANDC__ +#ifdef __BORLANDC__ // Silences warnings: "Condition is always true", "Unreachable code" -# pragma option push -w-ccc -w-rch -# endif +#pragma option push -w-ccc -w-rch +#endif // Tests that the LHS of EXPECT_EQ or ASSERT_EQ can be used as a null literal // when the RHS is a pointer type. @@ -572,10 +568,10 @@ TEST(NullLiteralTest, NoConversionNoWarning) { #pragma clang diagnostic pop #endif -# ifdef __BORLANDC__ +#ifdef __BORLANDC__ // Restores warnings after previous "#pragma option push" suppressed them. -# pragma option pop -# endif +#pragma option pop +#endif // // Tests CodePointToUtf8(). @@ -603,20 +599,17 @@ TEST(CodePointToUtf8Test, CanEncode8To11Bits) { // Some compilers (e.g., GCC on MinGW) cannot handle non-ASCII codepoints // in wide strings and wide chars. In order to accommodate them, we have to // introduce such character constants as integers. - EXPECT_EQ("\xD5\xB6", - CodePointToUtf8(static_cast<wchar_t>(0x576))); + EXPECT_EQ("\xD5\xB6", CodePointToUtf8(static_cast<wchar_t>(0x576))); } // Tests that Unicode code-points that have 12 to 16 bits are encoded // as 1110xxxx 10xxxxxx 10xxxxxx. TEST(CodePointToUtf8Test, CanEncode12To16Bits) { // 0000 1000 1101 0011 => 1110-0000 10-100011 10-010011 - EXPECT_EQ("\xE0\xA3\x93", - CodePointToUtf8(static_cast<wchar_t>(0x8D3))); + EXPECT_EQ("\xE0\xA3\x93", CodePointToUtf8(static_cast<wchar_t>(0x8D3))); // 1100 0111 0100 1101 => 1110-1100 10-011101 10-001101 - EXPECT_EQ("\xEC\x9D\x8D", - CodePointToUtf8(static_cast<wchar_t>(0xC74D))); + EXPECT_EQ("\xEC\x9D\x8D", CodePointToUtf8(static_cast<wchar_t>(0xC74D))); } #if !GTEST_WIDE_STRING_USES_UTF16_ @@ -668,7 +661,7 @@ TEST(WideStringToUtf8Test, CanEncode8To11Bits) { EXPECT_STREQ("\xC3\x93", WideStringToUtf8(L"\xD3", -1).c_str()); // 101 0111 0110 => 110-10101 10-110110 - const wchar_t s[] = { 0x576, '\0' }; + const wchar_t s[] = {0x576, '\0'}; EXPECT_STREQ("\xD5\xB6", WideStringToUtf8(s, 1).c_str()); EXPECT_STREQ("\xD5\xB6", WideStringToUtf8(s, -1).c_str()); } @@ -677,12 +670,12 @@ TEST(WideStringToUtf8Test, CanEncode8To11Bits) { // as 1110xxxx 10xxxxxx 10xxxxxx. TEST(WideStringToUtf8Test, CanEncode12To16Bits) { // 0000 1000 1101 0011 => 1110-0000 10-100011 10-010011 - const wchar_t s1[] = { 0x8D3, '\0' }; + const wchar_t s1[] = {0x8D3, '\0'}; EXPECT_STREQ("\xE0\xA3\x93", WideStringToUtf8(s1, 1).c_str()); EXPECT_STREQ("\xE0\xA3\x93", WideStringToUtf8(s1, -1).c_str()); // 1100 0111 0100 1101 => 1110-1100 10-011101 10-001101 - const wchar_t s2[] = { 0xC74D, '\0' }; + const wchar_t s2[] = {0xC74D, '\0'}; EXPECT_STREQ("\xEC\x9D\x8D", WideStringToUtf8(s2, 1).c_str()); EXPECT_STREQ("\xEC\x9D\x8D", WideStringToUtf8(s2, -1).c_str()); } @@ -717,11 +710,11 @@ TEST(WideStringToUtf8Test, CanEncodeInvalidCodePoint) { EXPECT_STREQ("(Invalid Unicode 0xABCDFF)", WideStringToUtf8(L"\xABCDFF", -1).c_str()); } -#else // !GTEST_WIDE_STRING_USES_UTF16_ +#else // !GTEST_WIDE_STRING_USES_UTF16_ // Tests that surrogate pairs are encoded correctly on the systems using // UTF-16 encoding in the wide strings. TEST(WideStringToUtf8Test, CanEncodeValidUtf16SUrrogatePairs) { - const wchar_t s[] = { 0xD801, 0xDC00, '\0' }; + const wchar_t s[] = {0xD801, 0xDC00, '\0'}; EXPECT_STREQ("\xF0\x90\x90\x80", WideStringToUtf8(s, -1).c_str()); } @@ -729,13 +722,13 @@ TEST(WideStringToUtf8Test, CanEncodeValidUtf16SUrrogatePairs) { // generates the expected result. TEST(WideStringToUtf8Test, CanEncodeInvalidUtf16SurrogatePair) { // Leading surrogate is at the end of the string. - const wchar_t s1[] = { 0xD800, '\0' }; + const wchar_t s1[] = {0xD800, '\0'}; EXPECT_STREQ("\xED\xA0\x80", WideStringToUtf8(s1, -1).c_str()); // Leading surrogate is not followed by the trailing surrogate. - const wchar_t s2[] = { 0xD800, 'M', '\0' }; + const wchar_t s2[] = {0xD800, 'M', '\0'}; EXPECT_STREQ("\xED\xA0\x80M", WideStringToUtf8(s2, -1).c_str()); // Trailing surrogate appearas without a leading surrogate. - const wchar_t s3[] = { 0xDC00, 'P', 'Q', 'R', '\0' }; + const wchar_t s3[] = {0xDC00, 'P', 'Q', 'R', '\0'}; EXPECT_STREQ("\xED\xB0\x80PQR", WideStringToUtf8(s3, -1).c_str()); } #endif // !GTEST_WIDE_STRING_USES_UTF16_ @@ -743,21 +736,24 @@ TEST(WideStringToUtf8Test, CanEncodeInvalidUtf16SurrogatePair) { // Tests that codepoint concatenation works correctly. #if !GTEST_WIDE_STRING_USES_UTF16_ TEST(WideStringToUtf8Test, ConcatenatesCodepointsCorrectly) { - const wchar_t s[] = { 0x108634, 0xC74D, '\n', 0x576, 0x8D3, 0x108634, '\0'}; + const wchar_t s[] = {0x108634, 0xC74D, '\n', 0x576, 0x8D3, 0x108634, '\0'}; EXPECT_STREQ( "\xF4\x88\x98\xB4" - "\xEC\x9D\x8D" - "\n" - "\xD5\xB6" - "\xE0\xA3\x93" - "\xF4\x88\x98\xB4", + "\xEC\x9D\x8D" + "\n" + "\xD5\xB6" + "\xE0\xA3\x93" + "\xF4\x88\x98\xB4", WideStringToUtf8(s, -1).c_str()); } #else TEST(WideStringToUtf8Test, ConcatenatesCodepointsCorrectly) { - const wchar_t s[] = { 0xC74D, '\n', 0x576, 0x8D3, '\0'}; + const wchar_t s[] = {0xC74D, '\n', 0x576, 0x8D3, '\0'}; EXPECT_STREQ( - "\xEC\x9D\x8D" "\n" "\xD5\xB6" "\xE0\xA3\x93", + "\xEC\x9D\x8D" + "\n" + "\xD5\xB6" + "\xE0\xA3\x93", WideStringToUtf8(s, -1).c_str()); } #endif // !GTEST_WIDE_STRING_USES_UTF16_ @@ -766,9 +762,8 @@ TEST(WideStringToUtf8Test, ConcatenatesCodepointsCorrectly) { TEST(RandomDeathTest, GeneratesCrashesOnInvalidRange) { testing::internal::Random random(42); - EXPECT_DEATH_IF_SUPPORTED( - random.Generate(0), - "Cannot generate a number in the range \\[0, 0\\)"); + EXPECT_DEATH_IF_SUPPORTED(random.Generate(0), + "Cannot generate a number in the range \\[0, 0\\)"); EXPECT_DEATH_IF_SUPPORTED( random.Generate(testing::internal::Random::kMaxRange + 1), "Generation of a number in \\[0, 2147483649\\) was requested, " @@ -897,7 +892,7 @@ class VectorShuffleTest : public Test { return true; } - bool found_in_vector[kVectorSize] = { false }; + bool found_in_vector[kVectorSize] = {false}; for (size_t i = 0; i < vector.size(); i++) { const int e = vector[i]; if (e < 0 || e >= static_cast<int>(kVectorSize) || found_in_vector[e]) { @@ -924,8 +919,8 @@ class VectorShuffleTest : public Test { return false; } - static bool RangeIsUnshuffled( - const TestingVector& vector, int begin, int end) { + static bool RangeIsUnshuffled(const TestingVector& vector, int begin, + int end) { return !RangeIsShuffled(vector, begin, end); } @@ -950,7 +945,7 @@ TEST_F(VectorShuffleTest, HandlesEmptyRange) { ASSERT_PRED1(VectorIsUnshuffled, vector_); // ...in the middle... - ShuffleRange(&random_, kVectorSize/2, kVectorSize/2, &vector_); + ShuffleRange(&random_, kVectorSize / 2, kVectorSize / 2, &vector_); ASSERT_PRED1(VectorIsNotCorrupt, vector_); ASSERT_PRED1(VectorIsUnshuffled, vector_); @@ -972,7 +967,7 @@ TEST_F(VectorShuffleTest, HandlesRangeOfSizeOne) { ASSERT_PRED1(VectorIsUnshuffled, vector_); // ...in the middle... - ShuffleRange(&random_, kVectorSize/2, kVectorSize/2 + 1, &vector_); + ShuffleRange(&random_, kVectorSize / 2, kVectorSize / 2 + 1, &vector_); ASSERT_PRED1(VectorIsNotCorrupt, vector_); ASSERT_PRED1(VectorIsUnshuffled, vector_); @@ -997,7 +992,7 @@ TEST_F(VectorShuffleTest, ShufflesEntireVector) { } TEST_F(VectorShuffleTest, ShufflesStartOfVector) { - const int kRangeSize = kVectorSize/2; + const int kRangeSize = kVectorSize / 2; ShuffleRange(&random_, 0, kRangeSize, &vector_); @@ -1019,11 +1014,11 @@ TEST_F(VectorShuffleTest, ShufflesEndOfVector) { TEST_F(VectorShuffleTest, ShufflesMiddleOfVector) { const int kRangeSize = static_cast<int>(kVectorSize) / 3; - ShuffleRange(&random_, kRangeSize, 2*kRangeSize, &vector_); + ShuffleRange(&random_, kRangeSize, 2 * kRangeSize, &vector_); ASSERT_PRED1(VectorIsNotCorrupt, vector_); EXPECT_PRED3(RangeIsUnshuffled, vector_, 0, kRangeSize); - EXPECT_PRED3(RangeIsShuffled, vector_, kRangeSize, 2*kRangeSize); + EXPECT_PRED3(RangeIsShuffled, vector_, kRangeSize, 2 * kRangeSize); EXPECT_PRED3(RangeIsUnshuffled, vector_, 2 * kRangeSize, static_cast<int>(kVectorSize)); } @@ -1088,13 +1083,12 @@ TEST(StringTest, CaseInsensitiveWideCStringEquals) { // Tests String::ShowWideCString(). TEST(StringTest, ShowWideCString) { - EXPECT_STREQ("(null)", - String::ShowWideCString(NULL).c_str()); + EXPECT_STREQ("(null)", String::ShowWideCString(NULL).c_str()); EXPECT_STREQ("", String::ShowWideCString(L"").c_str()); EXPECT_STREQ("foo", String::ShowWideCString(L"foo").c_str()); } -# if GTEST_OS_WINDOWS_MOBILE +#if GTEST_OS_WINDOWS_MOBILE TEST(StringTest, AnsiAndUtf16Null) { EXPECT_EQ(NULL, String::AnsiToUtf16(NULL)); EXPECT_EQ(NULL, String::Utf16ToAnsi(NULL)); @@ -1103,21 +1097,21 @@ TEST(StringTest, AnsiAndUtf16Null) { TEST(StringTest, AnsiAndUtf16ConvertBasic) { const char* ansi = String::Utf16ToAnsi(L"str"); EXPECT_STREQ("str", ansi); - delete [] ansi; + delete[] ansi; const WCHAR* utf16 = String::AnsiToUtf16("str"); EXPECT_EQ(0, wcsncmp(L"str", utf16, 3)); - delete [] utf16; + delete[] utf16; } TEST(StringTest, AnsiAndUtf16ConvertPathChars) { const char* ansi = String::Utf16ToAnsi(L".:\\ \"*?"); EXPECT_STREQ(".:\\ \"*?", ansi); - delete [] ansi; + delete[] ansi; const WCHAR* utf16 = String::AnsiToUtf16(".:\\ \"*?"); EXPECT_EQ(0, wcsncmp(L".:\\ \"*?", utf16, 3)); - delete [] utf16; + delete[] utf16; } -# endif // GTEST_OS_WINDOWS_MOBILE +#endif // GTEST_OS_WINDOWS_MOBILE #endif // GTEST_OS_WINDOWS @@ -1139,9 +1133,7 @@ TEST(TestPropertyTest, ReplaceStringValue) { // AddFatalFailure() and AddNonfatalFailure() must be stand-alone // functions (i.e. their definitions cannot be inlined at the call // sites), or C++Builder won't compile the code. -static void AddFatalFailure() { - FAIL() << "Expected fatal failure."; -} +static void AddFatalFailure() { FAIL() << "Expected fatal failure."; } static void AddNonfatalFailure() { ADD_FAILURE() << "Expected non-fatal failure."; @@ -1149,10 +1141,7 @@ static void AddNonfatalFailure() { class ScopedFakeTestPartResultReporterTest : public Test { public: // Must be public and not protected due to a bug in g++ 3.4.2. - enum FailureMode { - FATAL_FAILURE, - NONFATAL_FAILURE - }; + enum FailureMode { FATAL_FAILURE, NONFATAL_FAILURE }; static void AddFailure(FailureMode failure) { if (failure == FATAL_FAILURE) { AddFatalFailure(); @@ -1192,7 +1181,7 @@ TEST_F(ScopedFakeTestPartResultReporterTest, DeprecatedConstructor) { #if GTEST_IS_THREADSAFE class ScopedFakeTestPartResultReporterWithThreadsTest - : public ScopedFakeTestPartResultReporterTest { + : public ScopedFakeTestPartResultReporterTest { protected: static void AddFailureInOtherThread(FailureMode failure) { ThreadWithParam<FailureMode> thread(&AddFailure, failure, nullptr); @@ -1245,7 +1234,7 @@ TEST_F(ExpectFatalFailureTest, CatchesFatalFailureOnAllThreads) { #ifdef __BORLANDC__ // Silences warnings: "Condition is always true" -# pragma option push -w-ccc +#pragma option push -w-ccc #endif // Tests that EXPECT_FATAL_FAILURE() can be used in a non-void @@ -1273,7 +1262,7 @@ void DoesNotAbortHelper(bool* aborted) { #ifdef __BORLANDC__ // Restores warnings after previous "#pragma option push" suppressed them. -# pragma option pop +#pragma option pop #endif TEST_F(ExpectFatalFailureTest, DoesNotAbort) { @@ -1292,16 +1281,20 @@ static int global_var = 0; TEST_F(ExpectFatalFailureTest, AcceptsMacroThatExpandsToUnprotectedComma) { #ifndef __BORLANDC__ // ICE's in C++Builder. - EXPECT_FATAL_FAILURE({ - GTEST_USE_UNPROTECTED_COMMA_; - AddFatalFailure(); - }, ""); + EXPECT_FATAL_FAILURE( + { + GTEST_USE_UNPROTECTED_COMMA_; + AddFatalFailure(); + }, + ""); #endif - EXPECT_FATAL_FAILURE_ON_ALL_THREADS({ - GTEST_USE_UNPROTECTED_COMMA_; - AddFatalFailure(); - }, ""); + EXPECT_FATAL_FAILURE_ON_ALL_THREADS( + { + GTEST_USE_UNPROTECTED_COMMA_; + AddFatalFailure(); + }, + ""); } // Tests EXPECT_NONFATAL_FAILURE{,ON_ALL_THREADS}. @@ -1309,8 +1302,7 @@ TEST_F(ExpectFatalFailureTest, AcceptsMacroThatExpandsToUnprotectedComma) { typedef ScopedFakeTestPartResultReporterTest ExpectNonfatalFailureTest; TEST_F(ExpectNonfatalFailureTest, CatchesNonfatalFailure) { - EXPECT_NONFATAL_FAILURE(AddNonfatalFailure(), - "Expected non-fatal failure."); + EXPECT_NONFATAL_FAILURE(AddNonfatalFailure(), "Expected non-fatal failure."); } TEST_F(ExpectNonfatalFailureTest, AcceptsStdStringObject) { @@ -1329,15 +1321,19 @@ TEST_F(ExpectNonfatalFailureTest, CatchesNonfatalFailureOnAllThreads) { // statement that contains a macro which expands to code containing an // unprotected comma. TEST_F(ExpectNonfatalFailureTest, AcceptsMacroThatExpandsToUnprotectedComma) { - EXPECT_NONFATAL_FAILURE({ - GTEST_USE_UNPROTECTED_COMMA_; - AddNonfatalFailure(); - }, ""); + EXPECT_NONFATAL_FAILURE( + { + GTEST_USE_UNPROTECTED_COMMA_; + AddNonfatalFailure(); + }, + ""); - EXPECT_NONFATAL_FAILURE_ON_ALL_THREADS({ - GTEST_USE_UNPROTECTED_COMMA_; - AddNonfatalFailure(); - }, ""); + EXPECT_NONFATAL_FAILURE_ON_ALL_THREADS( + { + GTEST_USE_UNPROTECTED_COMMA_; + AddNonfatalFailure(); + }, + ""); } #if GTEST_IS_THREADSAFE @@ -1381,21 +1377,18 @@ class TestResultTest : public Test { typedef std::vector<TestPartResult> TPRVector; // We make use of 2 TestPartResult objects, - TestPartResult * pr1, * pr2; + TestPartResult *pr1, *pr2; // ... and 3 TestResult objects. - TestResult * r0, * r1, * r2; + TestResult *r0, *r1, *r2; void SetUp() override { // pr1 is for success. - pr1 = new TestPartResult(TestPartResult::kSuccess, - "foo/bar.cc", - 10, + pr1 = new TestPartResult(TestPartResult::kSuccess, "foo/bar.cc", 10, "Success!"); // pr2 is for fatal failure. - pr2 = new TestPartResult(TestPartResult::kFatalFailure, - "foo/bar.cc", + pr2 = new TestPartResult(TestPartResult::kFatalFailure, "foo/bar.cc", -1, // This line number means "unknown" "Failure!"); @@ -1408,10 +1401,10 @@ class TestResultTest : public Test { // state, in particular the TestPartResult vector it holds. // test_part_results() returns a const reference to this vector. // We cast it to a non-const object s.t. it can be modified - TPRVector* results1 = const_cast<TPRVector*>( - &TestResultAccessor::test_part_results(*r1)); - TPRVector* results2 = const_cast<TPRVector*>( - &TestResultAccessor::test_part_results(*r2)); + TPRVector* results1 = + const_cast<TPRVector*>(&TestResultAccessor::test_part_results(*r1)); + TPRVector* results2 = + const_cast<TPRVector*>(&TestResultAccessor::test_part_results(*r2)); // r0 is an empty TestResult. @@ -1662,15 +1655,11 @@ GTestFlagSaver* GTestFlagSaverTest::saver_ = nullptr; // tests are designed to work regardless of their order. // Modifies the Google Test flags in the test body. -TEST_F(GTestFlagSaverTest, ModifyGTestFlags) { - VerifyAndModifyFlags(); -} +TEST_F(GTestFlagSaverTest, ModifyGTestFlags) { VerifyAndModifyFlags(); } // Verifies that the Google Test flags in the body of the previous test were // restored to their original values. -TEST_F(GTestFlagSaverTest, VerifyGTestFlags) { - VerifyAndModifyFlags(); -} +TEST_F(GTestFlagSaverTest, VerifyGTestFlags) { VerifyAndModifyFlags(); } // Sets an environment variable with the given name to the given // value. If the value argument is "", unsets the environment @@ -1687,12 +1676,12 @@ static void SetEnv(const char* name, const char* value) { // Because putenv stores a pointer to the string buffer, we can't delete the // previous string (if present) until after it's replaced. - std::string *prev_env = NULL; + std::string* prev_env = NULL; if (added_env.find(name) != added_env.end()) { prev_env = added_env[name]; } - added_env[name] = new std::string( - (Message() << name << "=" << value).GetString()); + added_env[name] = + new std::string((Message() << name << "=" << value).GetString()); // The standard signature of putenv accepts a 'char*' argument. Other // implementations, like C++Builder's, accept a 'const char*'. @@ -1724,7 +1713,7 @@ TEST(Int32FromGTestEnvTest, ReturnsDefaultWhenVariableIsNotSet) { EXPECT_EQ(10, Int32FromGTestEnv("temp", 10)); } -# if !defined(GTEST_GET_INT32_FROM_ENV_) +#if !defined(GTEST_GET_INT32_FROM_ENV_) // Tests that Int32FromGTestEnv() returns the default value when the // environment variable overflows as an Int32. @@ -1750,7 +1739,7 @@ TEST(Int32FromGTestEnvTest, ReturnsDefaultWhenValueIsInvalid) { EXPECT_EQ(50, Int32FromGTestEnv("temp", 50)); } -# endif // !defined(GTEST_GET_INT32_FROM_ENV_) +#endif // !defined(GTEST_GET_INT32_FROM_ENV_) // Tests that Int32FromGTestEnv() parses and returns the value of the // environment variable when it represents a valid decimal integer in @@ -1834,8 +1823,7 @@ TEST(Int32FromEnvOrDieTest, ParsesAndReturnsValidValue) { TEST(Int32FromEnvOrDieDeathTest, AbortsOnFailure) { SetEnv(GTEST_FLAG_PREFIX_UPPER_ "VAR", "xxx"); EXPECT_DEATH_IF_SUPPORTED( - Int32FromEnvOrDie(GTEST_FLAG_PREFIX_UPPER_ "VAR", 123), - ".*"); + Int32FromEnvOrDie(GTEST_FLAG_PREFIX_UPPER_ "VAR", 123), ".*"); } // Tests that Int32FromEnvOrDie() aborts with an error message @@ -1843,8 +1831,7 @@ TEST(Int32FromEnvOrDieDeathTest, AbortsOnFailure) { TEST(Int32FromEnvOrDieDeathTest, AbortsOnInt32Overflow) { SetEnv(GTEST_FLAG_PREFIX_UPPER_ "VAR", "1234567891234567891234"); EXPECT_DEATH_IF_SUPPORTED( - Int32FromEnvOrDie(GTEST_FLAG_PREFIX_UPPER_ "VAR", 123), - ".*"); + Int32FromEnvOrDie(GTEST_FLAG_PREFIX_UPPER_ "VAR", 123), ".*"); } // Tests that ShouldRunTestOnShard() selects all tests @@ -1951,7 +1938,8 @@ TEST(ShouldRunTestOnShardTest, IsPartitionWhenThereAreFiveShards) { prev_selected_shard_index = shard_index; } else { ADD_FAILURE() << "Shard " << prev_selected_shard_index << " and " - << shard_index << " are both selected to run test " << test_id; + << shard_index << " are both selected to run test " + << test_id; } } } @@ -1963,7 +1951,7 @@ TEST(ShouldRunTestOnShardTest, IsPartitionWhenThereAreFiveShards) { int num_tests_on_shard = 0; for (int test_id = 0; test_id < num_tests; test_id++) { num_tests_on_shard += - ShouldRunTestOnShard(num_shards, shard_index, test_id); + ShouldRunTestOnShard(num_shards, shard_index, test_id); } EXPECT_GE(num_tests_on_shard, num_tests / num_shards); } @@ -1995,8 +1983,8 @@ TEST(UnitTestTest, ReturnsPlausibleTimestamp) { void ExpectNonFatalFailureRecordingPropertyWithReservedKey( const TestResult& test_result, const char* key) { EXPECT_NONFATAL_FAILURE(Test::RecordProperty(key, "1"), "Reserved key"); - ASSERT_EQ(0, test_result.test_property_count()) << "Property for key '" << key - << "' recorded unexpectedly."; + ASSERT_EQ(0, test_result.test_property_count()) + << "Property for key '" << key << "' recorded unexpectedly."; } void ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTest( @@ -2025,8 +2013,8 @@ void ExpectNonFatalFailureRecordingPropertyWithReservedKeyOutsideOfTestSuite( // Tests that property recording functions in UnitTest outside of tests // functions correctly. Creating a separate instance of UnitTest ensures it // is in a state similar to the UnitTest's singleton's between tests. -class UnitTestRecordPropertyTest : - public testing::internal::UnitTestRecordPropertyTestHelper { +class UnitTestRecordPropertyTest + : public testing::internal::UnitTestRecordPropertyTestHelper { public: static void SetUpTestSuite() { ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTestSuite( @@ -2065,8 +2053,7 @@ TEST_F(UnitTestRecordPropertyTest, OnePropertyFoundWhenAdded) { EXPECT_STREQ("key_1", unit_test_.ad_hoc_test_result().GetTestProperty(0).key()); - EXPECT_STREQ("1", - unit_test_.ad_hoc_test_result().GetTestProperty(0).value()); + EXPECT_STREQ("1", unit_test_.ad_hoc_test_result().GetTestProperty(0).value()); } // Tests TestResult has multiple properties when added. @@ -2107,16 +2094,13 @@ TEST_F(UnitTestRecordPropertyTest, OverridesValuesForDuplicateKeys) { TEST_F(UnitTestRecordPropertyTest, AddFailureInsideTestsWhenUsingTestSuiteReservedKeys) { - ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTest( - "name"); + ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTest("name"); ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTest( "value_param"); ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTest( "type_param"); - ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTest( - "status"); - ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTest( - "time"); + ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTest("status"); + ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTest("time"); ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTest( "classname"); } @@ -2164,9 +2148,7 @@ static Environment* record_property_env GTEST_ATTRIBUTE_UNUSED_ = // First, some predicates and predicate-formatters needed by the tests. // Returns true if and only if the argument is an even number. -bool IsEven(int n) { - return (n % 2) == 0; -} +bool IsEven(int n) { return (n % 2) == 0; } // A functor that returns true if and only if the argument is an even number. struct IsEvenFunctor { @@ -2213,41 +2195,37 @@ struct AssertIsEvenFunctor { }; // Returns true if and only if the sum of the arguments is an even number. -bool SumIsEven2(int n1, int n2) { - return IsEven(n1 + n2); -} +bool SumIsEven2(int n1, int n2) { return IsEven(n1 + n2); } // A functor that returns true if and only if the sum of the arguments is an // even number. struct SumIsEven3Functor { - bool operator()(int n1, int n2, int n3) { - return IsEven(n1 + n2 + n3); - } + bool operator()(int n1, int n2, int n3) { return IsEven(n1 + n2 + n3); } }; // A predicate-formatter function that asserts the sum of the // arguments is an even number. -AssertionResult AssertSumIsEven4( - const char* e1, const char* e2, const char* e3, const char* e4, - int n1, int n2, int n3, int n4) { +AssertionResult AssertSumIsEven4(const char* e1, const char* e2, const char* e3, + const char* e4, int n1, int n2, int n3, + int n4) { const int sum = n1 + n2 + n3 + n4; if (IsEven(sum)) { return AssertionSuccess(); } Message msg; - msg << e1 << " + " << e2 << " + " << e3 << " + " << e4 - << " (" << n1 << " + " << n2 << " + " << n3 << " + " << n4 - << ") evaluates to " << sum << ", which is not even."; + msg << e1 << " + " << e2 << " + " << e3 << " + " << e4 << " (" << n1 << " + " + << n2 << " + " << n3 << " + " << n4 << ") evaluates to " << sum + << ", which is not even."; return AssertionFailure(msg); } // A predicate-formatter functor that asserts the sum of the arguments // is an even number. struct AssertSumIsEven5Functor { - AssertionResult operator()( - const char* e1, const char* e2, const char* e3, const char* e4, - const char* e5, int n1, int n2, int n3, int n4, int n5) { + AssertionResult operator()(const char* e1, const char* e2, const char* e3, + const char* e4, const char* e5, int n1, int n2, + int n3, int n4, int n5) { const int sum = n1 + n2 + n3 + n4 + n5; if (IsEven(sum)) { return AssertionSuccess(); @@ -2255,14 +2233,12 @@ struct AssertSumIsEven5Functor { Message msg; msg << e1 << " + " << e2 << " + " << e3 << " + " << e4 << " + " << e5 - << " (" - << n1 << " + " << n2 << " + " << n3 << " + " << n4 << " + " << n5 - << ") evaluates to " << sum << ", which is not even."; + << " (" << n1 << " + " << n2 << " + " << n3 << " + " << n4 << " + " + << n5 << ") evaluates to " << sum << ", which is not even."; return AssertionFailure(msg); } }; - // Tests unary predicate assertions. // Tests unary predicate assertions that don't use a custom formatter. @@ -2272,11 +2248,12 @@ TEST(Pred1Test, WithoutFormat) { ASSERT_PRED1(IsEven, 4); // Failure cases. - EXPECT_NONFATAL_FAILURE({ // NOLINT - EXPECT_PRED1(IsEven, 5) << "This failure is expected."; - }, "This failure is expected."); - EXPECT_FATAL_FAILURE(ASSERT_PRED1(IsEvenFunctor(), 5), - "evaluates to false"); + EXPECT_NONFATAL_FAILURE( + { // NOLINT + EXPECT_PRED1(IsEven, 5) << "This failure is expected."; + }, + "This failure is expected."); + EXPECT_FATAL_FAILURE(ASSERT_PRED1(IsEvenFunctor(), 5), "evaluates to false"); } // Tests unary predicate assertions that use a custom formatter. @@ -2284,15 +2261,17 @@ TEST(Pred1Test, WithFormat) { // Success cases. EXPECT_PRED_FORMAT1(AssertIsEven, 2); ASSERT_PRED_FORMAT1(AssertIsEvenFunctor(), 4) - << "This failure is UNEXPECTED!"; + << "This failure is UNEXPECTED!"; // Failure cases. const int n = 5; EXPECT_NONFATAL_FAILURE(EXPECT_PRED_FORMAT1(AssertIsEvenFunctor(), n), "n evaluates to 5, which is not even."); - EXPECT_FATAL_FAILURE({ // NOLINT - ASSERT_PRED_FORMAT1(AssertIsEven, 5) << "This failure is expected."; - }, "This failure is expected."); + EXPECT_FATAL_FAILURE( + { // NOLINT + ASSERT_PRED_FORMAT1(AssertIsEven, 5) << "This failure is expected."; + }, + "This failure is expected."); } // Tests that unary predicate assertions evaluates their arguments @@ -2304,14 +2283,15 @@ TEST(Pred1Test, SingleEvaluationOnFailure) { EXPECT_EQ(1, n) << "The argument is not evaluated exactly once."; // A failure case. - EXPECT_FATAL_FAILURE({ // NOLINT - ASSERT_PRED_FORMAT1(AssertIsEvenFunctor(), n++) - << "This failure is expected."; - }, "This failure is expected."); + EXPECT_FATAL_FAILURE( + { // NOLINT + ASSERT_PRED_FORMAT1(AssertIsEvenFunctor(), n++) + << "This failure is expected."; + }, + "This failure is expected."); EXPECT_EQ(2, n) << "The argument is not evaluated exactly once."; } - // Tests predicate assertions whose arity is >= 2. // Tests predicate assertions that don't use a custom formatter. @@ -2323,19 +2303,23 @@ TEST(PredTest, WithoutFormat) { // Failure cases. const int n1 = 1; const int n2 = 2; - EXPECT_NONFATAL_FAILURE({ // NOLINT - EXPECT_PRED2(SumIsEven2, n1, n2) << "This failure is expected."; - }, "This failure is expected."); - EXPECT_FATAL_FAILURE({ // NOLINT - ASSERT_PRED3(SumIsEven3Functor(), 1, 2, 4); - }, "evaluates to false"); + EXPECT_NONFATAL_FAILURE( + { // NOLINT + EXPECT_PRED2(SumIsEven2, n1, n2) << "This failure is expected."; + }, + "This failure is expected."); + EXPECT_FATAL_FAILURE( + { // NOLINT + ASSERT_PRED3(SumIsEven3Functor(), 1, 2, 4); + }, + "evaluates to false"); } // Tests predicate assertions that use a custom formatter. TEST(PredTest, WithFormat) { // Success cases. - ASSERT_PRED_FORMAT4(AssertSumIsEven4, 4, 6, 8, 10) << - "This failure is UNEXPECTED!"; + ASSERT_PRED_FORMAT4(AssertSumIsEven4, 4, 6, 8, 10) + << "This failure is UNEXPECTED!"; EXPECT_PRED_FORMAT5(AssertSumIsEven5Functor(), 2, 4, 6, 8, 10); // Failure cases. @@ -2343,13 +2327,17 @@ TEST(PredTest, WithFormat) { const int n2 = 2; const int n3 = 4; const int n4 = 6; - EXPECT_NONFATAL_FAILURE({ // NOLINT - EXPECT_PRED_FORMAT4(AssertSumIsEven4, n1, n2, n3, n4); - }, "evaluates to 13, which is not even."); - EXPECT_FATAL_FAILURE({ // NOLINT - ASSERT_PRED_FORMAT5(AssertSumIsEven5Functor(), 1, 2, 4, 6, 8) - << "This failure is expected."; - }, "This failure is expected."); + EXPECT_NONFATAL_FAILURE( + { // NOLINT + EXPECT_PRED_FORMAT4(AssertSumIsEven4, n1, n2, n3, n4); + }, + "evaluates to 13, which is not even."); + EXPECT_FATAL_FAILURE( + { // NOLINT + ASSERT_PRED_FORMAT5(AssertSumIsEven5Functor(), 1, 2, 4, 6, 8) + << "This failure is expected."; + }, + "This failure is expected."); } // Tests that predicate assertions evaluates their arguments @@ -2367,9 +2355,8 @@ TEST(PredTest, SingleEvaluationOnFailure) { int n3 = 0; int n4 = 0; int n5 = 0; - ASSERT_PRED_FORMAT5(AssertSumIsEven5Functor(), - n1++, n2++, n3++, n4++, n5++) - << "This failure is UNEXPECTED!"; + ASSERT_PRED_FORMAT5(AssertSumIsEven5Functor(), n1++, n2++, n3++, n4++, n5++) + << "This failure is UNEXPECTED!"; EXPECT_EQ(1, n1) << "Argument 1 is not evaluated exactly once."; EXPECT_EQ(1, n2) << "Argument 2 is not evaluated exactly once."; EXPECT_EQ(1, n3) << "Argument 3 is not evaluated exactly once."; @@ -2378,19 +2365,23 @@ TEST(PredTest, SingleEvaluationOnFailure) { // A failure case. n1 = n2 = n3 = 0; - EXPECT_NONFATAL_FAILURE({ // NOLINT - EXPECT_PRED3(SumIsEven3Functor(), ++n1, n2++, n3++) - << "This failure is expected."; - }, "This failure is expected."); + EXPECT_NONFATAL_FAILURE( + { // NOLINT + EXPECT_PRED3(SumIsEven3Functor(), ++n1, n2++, n3++) + << "This failure is expected."; + }, + "This failure is expected."); EXPECT_EQ(1, n1) << "Argument 1 is not evaluated exactly once."; EXPECT_EQ(1, n2) << "Argument 2 is not evaluated exactly once."; EXPECT_EQ(1, n3) << "Argument 3 is not evaluated exactly once."; // Another failure case. n1 = n2 = n3 = n4 = 0; - EXPECT_NONFATAL_FAILURE({ // NOLINT - EXPECT_PRED_FORMAT4(AssertSumIsEven4, ++n1, n2++, n3++, n4++); - }, "evaluates to 1, which is not even."); + EXPECT_NONFATAL_FAILURE( + { // NOLINT + EXPECT_PRED_FORMAT4(AssertSumIsEven4, ++n1, n2++, n3++, n4++); + }, + "evaluates to 1, which is not even."); EXPECT_EQ(1, n1) << "Argument 1 is not evaluated exactly once."; EXPECT_EQ(1, n2) << "Argument 2 is not evaluated exactly once."; EXPECT_EQ(1, n3) << "Argument 3 is not evaluated exactly once."; @@ -2401,7 +2392,7 @@ TEST(PredTest, SingleEvaluationOnFailure) { TEST(PredTest, ExpectPredEvalFailure) { std::set<int> set_a = {2, 1, 3, 4, 5}; std::set<int> set_b = {0, 4, 8}; - const auto compare_sets = [] (std::set<int>, std::set<int>) { return false; }; + const auto compare_sets = [](std::set<int>, std::set<int>) { 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 " @@ -2411,9 +2402,7 @@ TEST(PredTest, ExpectPredEvalFailure) { // Some helper functions for testing using overloaded/template // functions with ASSERT_PREDn and EXPECT_PREDn. -bool IsPositive(double x) { - return x > 0; -} +bool IsPositive(double x) { return x > 0; } template <typename T> bool IsNegative(T x) { @@ -2429,7 +2418,7 @@ bool GreaterThan(T1 x1, T2 x2) { // their types are explicitly specified. TEST(PredicateAssertionTest, AcceptsOverloadedFunction) { // C++Builder requires C-style casts rather than static_cast. - EXPECT_PRED1((bool (*)(int))(IsPositive), 5); // NOLINT + EXPECT_PRED1((bool (*)(int))(IsPositive), 5); // NOLINT ASSERT_PRED1((bool (*)(double))(IsPositive), 6.0); // NOLINT } @@ -2442,31 +2431,27 @@ TEST(PredicateAssertionTest, AcceptsTemplateFunction) { ASSERT_PRED2((GreaterThan<int, int>), 5, 0); } - // Some helper functions for testing using overloaded/template // functions with ASSERT_PRED_FORMATn and EXPECT_PRED_FORMATn. AssertionResult IsPositiveFormat(const char* /* expr */, int n) { - return n > 0 ? AssertionSuccess() : - AssertionFailure(Message() << "Failure"); + return n > 0 ? AssertionSuccess() : AssertionFailure(Message() << "Failure"); } AssertionResult IsPositiveFormat(const char* /* expr */, double x) { - return x > 0 ? AssertionSuccess() : - AssertionFailure(Message() << "Failure"); + return x > 0 ? AssertionSuccess() : AssertionFailure(Message() << "Failure"); } template <typename T> AssertionResult IsNegativeFormat(const char* /* expr */, T x) { - return x < 0 ? AssertionSuccess() : - AssertionFailure(Message() << "Failure"); + return x < 0 ? AssertionSuccess() : AssertionFailure(Message() << "Failure"); } template <typename T1, typename T2> AssertionResult EqualsFormat(const char* /* expr1 */, const char* /* expr2 */, const T1& x1, const T2& x2) { - return x1 == x2 ? AssertionSuccess() : - AssertionFailure(Message() << "Failure"); + return x1 == x2 ? AssertionSuccess() + : AssertionFailure(Message() << "Failure"); } // Tests that overloaded functions can be used in *_PRED_FORMAT* @@ -2483,20 +2468,18 @@ TEST(PredicateFormatAssertionTest, AcceptsTemplateFunction) { ASSERT_PRED_FORMAT2(EqualsFormat, 3, 3); } - // Tests string assertions. // Tests ASSERT_STREQ with non-NULL arguments. TEST(StringAssertionTest, ASSERT_STREQ) { - const char * const p1 = "good"; + const char* const p1 = "good"; ASSERT_STREQ(p1, p1); // Let p2 have the same content as p1, but be at a different address. const char p2[] = "good"; ASSERT_STREQ(p1, p2); - EXPECT_FATAL_FAILURE(ASSERT_STREQ("bad", "good"), - " \"bad\"\n \"good\""); + EXPECT_FATAL_FAILURE(ASSERT_STREQ("bad", "good"), " \"bad\"\n \"good\""); } // Tests ASSERT_STREQ with NULL arguments. @@ -2519,8 +2502,7 @@ TEST(StringAssertionTest, ASSERT_STRNE) { ASSERT_STRNE(nullptr, ""); ASSERT_STRNE("", "Hi"); ASSERT_STRNE("Hi", ""); - EXPECT_FATAL_FAILURE(ASSERT_STRNE("Hi", "Hi"), - "\"Hi\" vs \"Hi\""); + EXPECT_FATAL_FAILURE(ASSERT_STRNE("Hi", "Hi"), "\"Hi\" vs \"Hi\""); } // Tests ASSERT_STRCASEEQ. @@ -2529,8 +2511,7 @@ TEST(StringAssertionTest, ASSERT_STRCASEEQ) { ASSERT_STRCASEEQ(static_cast<const char*>(nullptr), nullptr); ASSERT_STRCASEEQ("", ""); - EXPECT_FATAL_FAILURE(ASSERT_STRCASEEQ("Hi", "hi2"), - "Ignoring case"); + EXPECT_FATAL_FAILURE(ASSERT_STRCASEEQ("Hi", "hi2"), "Ignoring case"); } // Tests ASSERT_STRCASENE. @@ -2542,8 +2523,7 @@ TEST(StringAssertionTest, ASSERT_STRCASENE) { ASSERT_STRCASENE(nullptr, ""); ASSERT_STRCASENE("", "Hi"); ASSERT_STRCASENE("Hi", ""); - EXPECT_FATAL_FAILURE(ASSERT_STRCASENE("Hi", "hi"), - "(ignoring case)"); + EXPECT_FATAL_FAILURE(ASSERT_STRCASENE("Hi", "hi"), "(ignoring case)"); } // Tests *_STREQ on wide strings. @@ -2561,17 +2541,17 @@ TEST(StringAssertionTest, STREQ_Wide) { EXPECT_STREQ(L"Hi", L"Hi"); // Unequal strings. - EXPECT_NONFATAL_FAILURE(EXPECT_STREQ(L"abc", L"Abc"), - "Abc"); + EXPECT_NONFATAL_FAILURE(EXPECT_STREQ(L"abc", L"Abc"), "Abc"); // Strings containing wide characters. - EXPECT_NONFATAL_FAILURE(EXPECT_STREQ(L"abc\x8119", L"abc\x8120"), - "abc"); + EXPECT_NONFATAL_FAILURE(EXPECT_STREQ(L"abc\x8119", L"abc\x8120"), "abc"); // The streaming variation. - EXPECT_NONFATAL_FAILURE({ // NOLINT - EXPECT_STREQ(L"abc\x8119", L"abc\x8121") << "Expected failure"; - }, "Expected failure"); + EXPECT_NONFATAL_FAILURE( + { // NOLINT + EXPECT_STREQ(L"abc\x8119", L"abc\x8121") << "Expected failure"; + }, + "Expected failure"); } // Tests *_STRNE on wide strings. @@ -2584,22 +2564,19 @@ TEST(StringAssertionTest, STRNE_Wide) { ""); // Empty strings. - EXPECT_NONFATAL_FAILURE(EXPECT_STRNE(L"", L""), - "L\"\""); + EXPECT_NONFATAL_FAILURE(EXPECT_STRNE(L"", L""), "L\"\""); // Non-null vs NULL. ASSERT_STRNE(L"non-null", nullptr); // Equal strings. - EXPECT_NONFATAL_FAILURE(EXPECT_STRNE(L"Hi", L"Hi"), - "L\"Hi\""); + EXPECT_NONFATAL_FAILURE(EXPECT_STRNE(L"Hi", L"Hi"), "L\"Hi\""); // Unequal strings. EXPECT_STRNE(L"abc", L"Abc"); // Strings containing wide characters. - EXPECT_NONFATAL_FAILURE(EXPECT_STRNE(L"abc\x8119", L"abc\x8119"), - "abc"); + EXPECT_NONFATAL_FAILURE(EXPECT_STRNE(L"abc\x8119", L"abc\x8119"), "abc"); // The streaming variation. ASSERT_STRNE(L"abc\x8119", L"abc\x8120") << "This shouldn't happen"; @@ -2633,12 +2610,13 @@ TEST(IsSubstringTest, ReturnsCorrectResultForWideCString) { // Tests that IsSubstring() generates the correct message when the input // argument type is const char*. TEST(IsSubstringTest, GeneratesCorrectMessageForCString) { - EXPECT_STREQ("Value of: needle_expr\n" - " Actual: \"needle\"\n" - "Expected: a substring of haystack_expr\n" - "Which is: \"haystack\"", - IsSubstring("needle_expr", "haystack_expr", - "needle", "haystack").failure_message()); + EXPECT_STREQ( + "Value of: needle_expr\n" + " Actual: \"needle\"\n" + "Expected: a substring of haystack_expr\n" + "Which is: \"haystack\"", + IsSubstring("needle_expr", "haystack_expr", "needle", "haystack") + .failure_message()); } // Tests that IsSubstring returns the correct result when the input @@ -2659,13 +2637,14 @@ TEST(IsSubstringTest, ReturnsCorrectResultForStdWstring) { // Tests that IsSubstring() generates the correct message when the input // argument type is ::std::wstring. TEST(IsSubstringTest, GeneratesCorrectMessageForWstring) { - EXPECT_STREQ("Value of: needle_expr\n" - " Actual: L\"needle\"\n" - "Expected: a substring of haystack_expr\n" - "Which is: L\"haystack\"", - IsSubstring( - "needle_expr", "haystack_expr", - ::std::wstring(L"needle"), L"haystack").failure_message()); + EXPECT_STREQ( + "Value of: needle_expr\n" + " Actual: L\"needle\"\n" + "Expected: a substring of haystack_expr\n" + "Which is: L\"haystack\"", + IsSubstring("needle_expr", "haystack_expr", ::std::wstring(L"needle"), + L"haystack") + .failure_message()); } #endif // GTEST_HAS_STD_WSTRING @@ -2689,13 +2668,13 @@ TEST(IsNotSubstringTest, ReturnsCorrectResultForWideCString) { // Tests that IsNotSubstring() generates the correct message when the input // argument type is const wchar_t*. TEST(IsNotSubstringTest, GeneratesCorrectMessageForWideCString) { - EXPECT_STREQ("Value of: needle_expr\n" - " Actual: L\"needle\"\n" - "Expected: not a substring of haystack_expr\n" - "Which is: L\"two needles\"", - IsNotSubstring( - "needle_expr", "haystack_expr", - L"needle", L"two needles").failure_message()); + EXPECT_STREQ( + "Value of: needle_expr\n" + " Actual: L\"needle\"\n" + "Expected: not a substring of haystack_expr\n" + "Which is: L\"two needles\"", + IsNotSubstring("needle_expr", "haystack_expr", L"needle", L"two needles") + .failure_message()); } // Tests that IsNotSubstring returns the correct result when the input @@ -2708,13 +2687,14 @@ TEST(IsNotSubstringTest, ReturnsCorrectResultsForStdString) { // Tests that IsNotSubstring() generates the correct message when the input // argument type is ::std::string. TEST(IsNotSubstringTest, GeneratesCorrectMessageForStdString) { - EXPECT_STREQ("Value of: needle_expr\n" - " Actual: \"needle\"\n" - "Expected: not a substring of haystack_expr\n" - "Which is: \"two needles\"", - IsNotSubstring( - "needle_expr", "haystack_expr", - ::std::string("needle"), "two needles").failure_message()); + EXPECT_STREQ( + "Value of: needle_expr\n" + " Actual: \"needle\"\n" + "Expected: not a substring of haystack_expr\n" + "Which is: \"two needles\"", + IsNotSubstring("needle_expr", "haystack_expr", ::std::string("needle"), + "two needles") + .failure_message()); } #if GTEST_HAS_STD_WSTRING @@ -2761,20 +2741,20 @@ class FloatingPointTest : public Test { const Bits zero_bits = Floating(0).bits(); // Makes some numbers close to 0.0. - values_.close_to_positive_zero = Floating::ReinterpretBits( - zero_bits + max_ulps/2); - values_.close_to_negative_zero = -Floating::ReinterpretBits( - zero_bits + max_ulps - max_ulps/2); - values_.further_from_negative_zero = -Floating::ReinterpretBits( - zero_bits + max_ulps + 1 - max_ulps/2); + values_.close_to_positive_zero = + Floating::ReinterpretBits(zero_bits + max_ulps / 2); + values_.close_to_negative_zero = + -Floating::ReinterpretBits(zero_bits + max_ulps - max_ulps / 2); + values_.further_from_negative_zero = + -Floating::ReinterpretBits(zero_bits + max_ulps + 1 - max_ulps / 2); // The bits that represent 1.0. const Bits one_bits = Floating(1).bits(); // Makes some numbers close to 1.0. values_.close_to_one = Floating::ReinterpretBits(one_bits + max_ulps); - values_.further_from_one = Floating::ReinterpretBits( - one_bits + max_ulps + 1); + values_.further_from_one = + Floating::ReinterpretBits(one_bits + max_ulps + 1); // +infinity. values_.infinity = Floating::Infinity(); @@ -2783,23 +2763,23 @@ class FloatingPointTest : public Test { const Bits infinity_bits = Floating(values_.infinity).bits(); // Makes some numbers close to infinity. - values_.close_to_infinity = Floating::ReinterpretBits( - infinity_bits - max_ulps); - values_.further_from_infinity = Floating::ReinterpretBits( - infinity_bits - max_ulps - 1); + values_.close_to_infinity = + Floating::ReinterpretBits(infinity_bits - max_ulps); + values_.further_from_infinity = + Floating::ReinterpretBits(infinity_bits - max_ulps - 1); // Makes some NAN's. Sets the most significant bit of the fraction so that // our NaN's are quiet; trying to process a signaling NaN would raise an // exception if our environment enables floating point exceptions. - values_.nan1 = Floating::ReinterpretBits(Floating::kExponentBitMask - | (static_cast<Bits>(1) << (Floating::kFractionBitCount - 1)) | 1); - values_.nan2 = Floating::ReinterpretBits(Floating::kExponentBitMask - | (static_cast<Bits>(1) << (Floating::kFractionBitCount - 1)) | 200); + values_.nan1 = Floating::ReinterpretBits( + Floating::kExponentBitMask | + (static_cast<Bits>(1) << (Floating::kFractionBitCount - 1)) | 1); + values_.nan2 = Floating::ReinterpretBits( + Floating::kExponentBitMask | + (static_cast<Bits>(1) << (Floating::kFractionBitCount - 1)) | 200); } - void TestSize() { - EXPECT_EQ(sizeof(RawType), sizeof(Bits)); - } + void TestSize() { EXPECT_EQ(sizeof(RawType), sizeof(Bits)); } static TestValues values_; }; @@ -2812,17 +2792,13 @@ typename FloatingPointTest<RawType>::TestValues typedef FloatingPointTest<float> FloatTest; // Tests that the size of Float::Bits matches the size of float. -TEST_F(FloatTest, Size) { - TestSize(); -} +TEST_F(FloatTest, Size) { TestSize(); } // Tests comparing with +0 and -0. TEST_F(FloatTest, Zeros) { EXPECT_FLOAT_EQ(0.0, -0.0); - EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(-0.0, 1.0), - "1.0"); - EXPECT_FATAL_FAILURE(ASSERT_FLOAT_EQ(0.0, 1.5), - "1.5"); + EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(-0.0, 1.0), "1.0"); + EXPECT_FATAL_FAILURE(ASSERT_FLOAT_EQ(0.0, 1.5), "1.5"); } // Tests comparing numbers close to 0. @@ -2843,10 +2819,11 @@ TEST_F(FloatTest, AlmostZeros) { EXPECT_FLOAT_EQ(-0.0, v.close_to_negative_zero); EXPECT_FLOAT_EQ(v.close_to_positive_zero, v.close_to_negative_zero); - EXPECT_FATAL_FAILURE({ // NOLINT - ASSERT_FLOAT_EQ(v.close_to_positive_zero, - v.further_from_negative_zero); - }, "v.further_from_negative_zero"); + EXPECT_FATAL_FAILURE( + { // NOLINT + ASSERT_FLOAT_EQ(v.close_to_positive_zero, v.further_from_negative_zero); + }, + "v.further_from_negative_zero"); } // Tests comparing numbers close to each other. @@ -2858,8 +2835,7 @@ TEST_F(FloatTest, SmallDiff) { // Tests comparing numbers far apart. TEST_F(FloatTest, LargeDiff) { - EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(2.5, 3.0), - "3.0"); + EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(2.5, 3.0), "3.0"); } // Tests comparing with infinity. @@ -2888,15 +2864,11 @@ TEST_F(FloatTest, NaN) { // (parentheses). static const FloatTest::TestValues& v = this->values_; - EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(v.nan1, v.nan1), - "v.nan1"); - EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(v.nan1, v.nan2), - "v.nan2"); - EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(1.0, v.nan1), - "v.nan1"); + EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(v.nan1, v.nan1), "v.nan1"); + EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(v.nan1, v.nan2), "v.nan2"); + EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(1.0, v.nan1), "v.nan1"); - EXPECT_FATAL_FAILURE(ASSERT_FLOAT_EQ(v.nan1, v.infinity), - "v.infinity"); + EXPECT_FATAL_FAILURE(ASSERT_FLOAT_EQ(v.nan1, v.infinity), "v.infinity"); } // Tests that *_FLOAT_EQ are reflexive. @@ -2950,36 +2922,40 @@ TEST_F(FloatTest, FloatLEFails) { "(2.0f) <= (1.0f)"); // or by a small yet non-negligible margin, - EXPECT_NONFATAL_FAILURE({ // NOLINT - EXPECT_PRED_FORMAT2(FloatLE, values_.further_from_one, 1.0f); - }, "(values_.further_from_one) <= (1.0f)"); + EXPECT_NONFATAL_FAILURE( + { // NOLINT + EXPECT_PRED_FORMAT2(FloatLE, values_.further_from_one, 1.0f); + }, + "(values_.further_from_one) <= (1.0f)"); - EXPECT_NONFATAL_FAILURE({ // NOLINT - EXPECT_PRED_FORMAT2(FloatLE, values_.nan1, values_.infinity); - }, "(values_.nan1) <= (values_.infinity)"); - EXPECT_NONFATAL_FAILURE({ // NOLINT - EXPECT_PRED_FORMAT2(FloatLE, -values_.infinity, values_.nan1); - }, "(-values_.infinity) <= (values_.nan1)"); - EXPECT_FATAL_FAILURE({ // NOLINT - ASSERT_PRED_FORMAT2(FloatLE, values_.nan1, values_.nan1); - }, "(values_.nan1) <= (values_.nan1)"); + EXPECT_NONFATAL_FAILURE( + { // NOLINT + EXPECT_PRED_FORMAT2(FloatLE, values_.nan1, values_.infinity); + }, + "(values_.nan1) <= (values_.infinity)"); + EXPECT_NONFATAL_FAILURE( + { // NOLINT + EXPECT_PRED_FORMAT2(FloatLE, -values_.infinity, values_.nan1); + }, + "(-values_.infinity) <= (values_.nan1)"); + EXPECT_FATAL_FAILURE( + { // NOLINT + ASSERT_PRED_FORMAT2(FloatLE, values_.nan1, values_.nan1); + }, + "(values_.nan1) <= (values_.nan1)"); } // Instantiates FloatingPointTest for testing *_DOUBLE_EQ. typedef FloatingPointTest<double> DoubleTest; // Tests that the size of Double::Bits matches the size of double. -TEST_F(DoubleTest, Size) { - TestSize(); -} +TEST_F(DoubleTest, Size) { TestSize(); } // Tests comparing with +0 and -0. TEST_F(DoubleTest, Zeros) { EXPECT_DOUBLE_EQ(0.0, -0.0); - EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(-0.0, 1.0), - "1.0"); - EXPECT_FATAL_FAILURE(ASSERT_DOUBLE_EQ(0.0, 1.0), - "1.0"); + EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(-0.0, 1.0), "1.0"); + EXPECT_FATAL_FAILURE(ASSERT_DOUBLE_EQ(0.0, 1.0), "1.0"); } // Tests comparing numbers close to 0. @@ -3000,10 +2976,12 @@ TEST_F(DoubleTest, AlmostZeros) { EXPECT_DOUBLE_EQ(-0.0, v.close_to_negative_zero); EXPECT_DOUBLE_EQ(v.close_to_positive_zero, v.close_to_negative_zero); - EXPECT_FATAL_FAILURE({ // NOLINT - ASSERT_DOUBLE_EQ(v.close_to_positive_zero, - v.further_from_negative_zero); - }, "v.further_from_negative_zero"); + EXPECT_FATAL_FAILURE( + { // NOLINT + ASSERT_DOUBLE_EQ(v.close_to_positive_zero, + v.further_from_negative_zero); + }, + "v.further_from_negative_zero"); } // Tests comparing numbers close to each other. @@ -3015,8 +2993,7 @@ TEST_F(DoubleTest, SmallDiff) { // Tests comparing numbers far apart. TEST_F(DoubleTest, LargeDiff) { - EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(2.0, 3.0), - "3.0"); + EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(2.0, 3.0), "3.0"); } // Tests comparing with infinity. @@ -3040,12 +3017,10 @@ TEST_F(DoubleTest, NaN) { static const DoubleTest::TestValues& v = this->values_; // Nokia's STLport crashes if we try to output infinity or NaN. - EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(v.nan1, v.nan1), - "v.nan1"); + EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(v.nan1, v.nan1), "v.nan1"); EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(v.nan1, v.nan2), "v.nan2"); EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(1.0, v.nan1), "v.nan1"); - EXPECT_FATAL_FAILURE(ASSERT_DOUBLE_EQ(v.nan1, v.infinity), - "v.infinity"); + EXPECT_FATAL_FAILURE(ASSERT_DOUBLE_EQ(v.nan1, v.infinity), "v.infinity"); } // Tests that *_DOUBLE_EQ are reflexive. @@ -3106,22 +3081,29 @@ TEST_F(DoubleTest, DoubleLEFails) { "(2.0) <= (1.0)"); // or by a small yet non-negligible margin, - EXPECT_NONFATAL_FAILURE({ // NOLINT - EXPECT_PRED_FORMAT2(DoubleLE, values_.further_from_one, 1.0); - }, "(values_.further_from_one) <= (1.0)"); + EXPECT_NONFATAL_FAILURE( + { // NOLINT + EXPECT_PRED_FORMAT2(DoubleLE, values_.further_from_one, 1.0); + }, + "(values_.further_from_one) <= (1.0)"); - EXPECT_NONFATAL_FAILURE({ // NOLINT - EXPECT_PRED_FORMAT2(DoubleLE, values_.nan1, values_.infinity); - }, "(values_.nan1) <= (values_.infinity)"); - EXPECT_NONFATAL_FAILURE({ // NOLINT - EXPECT_PRED_FORMAT2(DoubleLE, -values_.infinity, values_.nan1); - }, " (-values_.infinity) <= (values_.nan1)"); - EXPECT_FATAL_FAILURE({ // NOLINT - ASSERT_PRED_FORMAT2(DoubleLE, values_.nan1, values_.nan1); - }, "(values_.nan1) <= (values_.nan1)"); + EXPECT_NONFATAL_FAILURE( + { // NOLINT + EXPECT_PRED_FORMAT2(DoubleLE, values_.nan1, values_.infinity); + }, + "(values_.nan1) <= (values_.infinity)"); + EXPECT_NONFATAL_FAILURE( + { // NOLINT + EXPECT_PRED_FORMAT2(DoubleLE, -values_.infinity, values_.nan1); + }, + " (-values_.infinity) <= (values_.nan1)"); + EXPECT_FATAL_FAILURE( + { // NOLINT + ASSERT_PRED_FORMAT2(DoubleLE, values_.nan1, values_.nan1); + }, + "(values_.nan1) <= (values_.nan1)"); } - // Verifies that a test or test case whose name starts with DISABLED_ is // not run. @@ -3133,9 +3115,7 @@ TEST(DisabledTest, DISABLED_TestShouldNotRun) { // A test whose name does not start with DISABLED_. // Should run. -TEST(DisabledTest, NotDISABLED_TestShouldRun) { - EXPECT_EQ(1, 1); -} +TEST(DisabledTest, NotDISABLED_TestShouldRun) { EXPECT_EQ(1, 1); } // A test case whose name starts with DISABLED_. // Should not run. @@ -3175,8 +3155,7 @@ TEST_F(DisabledTestsTest, DISABLED_TestShouldNotRun_2) { // Tests that disabled typed tests aren't run. template <typename T> -class TypedTest : public Test { -}; +class TypedTest : public Test {}; typedef testing::Types<int, double> NumericTypes; TYPED_TEST_SUITE(TypedTest, NumericTypes); @@ -3186,8 +3165,7 @@ TYPED_TEST(TypedTest, DISABLED_ShouldNotRun) { } template <typename T> -class DISABLED_TypedTest : public Test { -}; +class DISABLED_TypedTest : public Test {}; TYPED_TEST_SUITE(DISABLED_TypedTest, NumericTypes); @@ -3198,8 +3176,7 @@ TYPED_TEST(DISABLED_TypedTest, ShouldNotRun) { // Tests that disabled type-parameterized tests aren't run. template <typename T> -class TypedTestP : public Test { -}; +class TypedTestP : public Test {}; TYPED_TEST_SUITE_P(TypedTestP); @@ -3213,8 +3190,7 @@ REGISTER_TYPED_TEST_SUITE_P(TypedTestP, DISABLED_ShouldNotRun); INSTANTIATE_TYPED_TEST_SUITE_P(My, TypedTestP, NumericTypes); template <typename T> -class DISABLED_TypedTestP : public Test { -}; +class DISABLED_TypedTestP : public Test {}; TYPED_TEST_SUITE_P(DISABLED_TypedTestP); @@ -3234,15 +3210,11 @@ class SingleEvaluationTest : public Test { // This helper function is needed by the FailedASSERT_STREQ test // below. It's public to work around C++Builder's bug with scoping local // classes. - static void CompareAndIncrementCharPtrs() { - ASSERT_STREQ(p1_++, p2_++); - } + static void CompareAndIncrementCharPtrs() { ASSERT_STREQ(p1_++, p2_++); } // This helper function is needed by the FailedASSERT_NE test below. It's // public to work around C++Builder's bug with scoping local classes. - static void CompareAndIncrementInts() { - ASSERT_NE(a_++, b_++); - } + static void CompareAndIncrementInts() { ASSERT_NE(a_++, b_++); } protected: SingleEvaluationTest() { @@ -3285,8 +3257,7 @@ TEST_F(SingleEvaluationTest, ASSERT_STR) { EXPECT_EQ(s2_ + 1, p2_); // failed EXPECT_STRCASEEQ - EXPECT_NONFATAL_FAILURE(EXPECT_STRCASEEQ(p1_++, p2_++), - "Ignoring case"); + EXPECT_NONFATAL_FAILURE(EXPECT_STRCASEEQ(p1_++, p2_++), "Ignoring case"); EXPECT_EQ(s1_ + 2, p1_); EXPECT_EQ(s2_ + 2, p2_); } @@ -3346,34 +3317,39 @@ TEST_F(SingleEvaluationTest, OtherCases) { #endif // GTEST_HAS_RTTI -void ThrowAnInteger() { - throw 1; -} -void ThrowRuntimeError(const char* what) { - throw std::runtime_error(what); -} +void ThrowAnInteger() { throw 1; } +void ThrowRuntimeError(const char* what) { throw std::runtime_error(what); } // Tests that assertion arguments are evaluated exactly once. TEST_F(SingleEvaluationTest, ExceptionTests) { // successful EXPECT_THROW - EXPECT_THROW({ // NOLINT - a_++; - ThrowAnInteger(); - }, int); + EXPECT_THROW( + { // NOLINT + a_++; + ThrowAnInteger(); + }, + int); EXPECT_EQ(1, a_); // failed EXPECT_THROW, throws different - EXPECT_NONFATAL_FAILURE(EXPECT_THROW({ // NOLINT - a_++; - ThrowAnInteger(); - }, bool), "throws a different type"); + EXPECT_NONFATAL_FAILURE(EXPECT_THROW( + { // NOLINT + a_++; + ThrowAnInteger(); + }, + bool), + "throws a different type"); EXPECT_EQ(2, a_); // failed EXPECT_THROW, throws runtime error - EXPECT_NONFATAL_FAILURE(EXPECT_THROW({ // NOLINT - a_++; - ThrowRuntimeError("A description"); - }, bool), "throws " ERROR_DESC " with description \"A description\""); + EXPECT_NONFATAL_FAILURE(EXPECT_THROW( + { // NOLINT + a_++; + ThrowRuntimeError("A description"); + }, + bool), + "throws " ERROR_DESC + " with description \"A description\""); EXPECT_EQ(3, a_); // failed EXPECT_THROW, throws nothing @@ -3386,9 +3362,10 @@ TEST_F(SingleEvaluationTest, ExceptionTests) { // failed EXPECT_NO_THROW EXPECT_NONFATAL_FAILURE(EXPECT_NO_THROW({ // NOLINT - a_++; - ThrowAnInteger(); - }), "it throws"); + a_++; + ThrowAnInteger(); + }), + "it throws"); EXPECT_EQ(6, a_); // successful EXPECT_ANY_THROW @@ -3409,12 +3386,8 @@ TEST_F(SingleEvaluationTest, ExceptionTests) { class NoFatalFailureTest : public Test { protected: void Succeeds() {} - void FailsNonFatal() { - ADD_FAILURE() << "some non-fatal failure"; - } - void Fails() { - FAIL() << "some fatal failure"; - } + void FailsNonFatal() { ADD_FAILURE() << "some non-fatal failure"; } + void Fails() { FAIL() << "some fatal failure"; } void DoAssertNoFatalFailureOnFails() { ASSERT_NO_FATAL_FAILURE(Fails()); @@ -3433,12 +3406,10 @@ TEST_F(NoFatalFailureTest, NoFailure) { } TEST_F(NoFatalFailureTest, NonFatalIsNoFailure) { - EXPECT_NONFATAL_FAILURE( - EXPECT_NO_FATAL_FAILURE(FailsNonFatal()), - "some non-fatal failure"); - EXPECT_NONFATAL_FAILURE( - ASSERT_NO_FATAL_FAILURE(FailsNonFatal()), - "some non-fatal failure"); + EXPECT_NONFATAL_FAILURE(EXPECT_NO_FATAL_FAILURE(FailsNonFatal()), + "some non-fatal failure"); + EXPECT_NONFATAL_FAILURE(ASSERT_NO_FATAL_FAILURE(FailsNonFatal()), + "some non-fatal failure"); } TEST_F(NoFatalFailureTest, AssertNoFatalFailureOnFatalFailure) { @@ -3561,8 +3532,9 @@ TEST(EditDistance, TestSuites) { EditsToString(CalculateOptimalEdits(CharsToIndices(c->left), CharsToIndices(c->right)))) << "Left <" << c->left << "> Right <" << c->right << "> Edits <" - << EditsToString(CalculateOptimalEdits( - CharsToIndices(c->left), CharsToIndices(c->right))) << ">"; + << EditsToString(CalculateOptimalEdits(CharsToIndices(c->left), + CharsToIndices(c->right))) + << ">"; EXPECT_TRUE(c->expected_diff == CreateUnifiedDiff(CharsToLines(c->left), CharsToLines(c->right))) << "Left <" << c->left << "> Right <" << c->right << "> Diff <" @@ -3575,8 +3547,7 @@ TEST(EditDistance, TestSuites) { TEST(AssertionTest, EqFailure) { const std::string foo_val("5"), bar_val("6"); const std::string msg1( - EqFailure("foo", "bar", foo_val, bar_val, false) - .failure_message()); + EqFailure("foo", "bar", foo_val, bar_val, false).failure_message()); EXPECT_STREQ( "Expected equality of these values:\n" " foo\n" @@ -3586,8 +3557,7 @@ TEST(AssertionTest, EqFailure) { msg1.c_str()); const std::string msg2( - EqFailure("foo", "6", foo_val, bar_val, false) - .failure_message()); + EqFailure("foo", "6", foo_val, bar_val, false).failure_message()); EXPECT_STREQ( "Expected equality of these values:\n" " foo\n" @@ -3596,8 +3566,7 @@ TEST(AssertionTest, EqFailure) { msg2.c_str()); const std::string msg3( - EqFailure("5", "bar", foo_val, bar_val, false) - .failure_message()); + EqFailure("5", "bar", foo_val, bar_val, false).failure_message()); EXPECT_STREQ( "Expected equality of these values:\n" " 5\n" @@ -3614,9 +3583,8 @@ TEST(AssertionTest, EqFailure) { msg4.c_str()); const std::string msg5( - EqFailure("foo", "bar", - std::string("\"x\""), std::string("\"y\""), - true).failure_message()); + EqFailure("foo", "bar", std::string("\"x\""), std::string("\"y\""), true) + .failure_message()); EXPECT_STREQ( "Expected equality of these values:\n" " foo\n" @@ -3651,24 +3619,21 @@ TEST(AssertionTest, AppendUserMessage) { const std::string foo("foo"); Message msg; - EXPECT_STREQ("foo", - AppendUserMessage(foo, msg).c_str()); + EXPECT_STREQ("foo", AppendUserMessage(foo, msg).c_str()); msg << "bar"; - EXPECT_STREQ("foo\nbar", - AppendUserMessage(foo, msg).c_str()); + EXPECT_STREQ("foo\nbar", AppendUserMessage(foo, msg).c_str()); } #ifdef __BORLANDC__ // Silences warnings: "Condition is always true", "Unreachable code" -# pragma option push -w-ccc -w-rch +#pragma option push -w-ccc -w-rch #endif // Tests ASSERT_TRUE. TEST(AssertionTest, ASSERT_TRUE) { ASSERT_TRUE(2 > 1); // NOLINT - EXPECT_FATAL_FAILURE(ASSERT_TRUE(2 < 1), - "2 < 1"); + EXPECT_FATAL_FAILURE(ASSERT_TRUE(2 < 1), "2 < 1"); } // Tests ASSERT_TRUE(predicate) for predicates returning AssertionResult. @@ -3716,7 +3681,7 @@ TEST(AssertionTest, AssertFalseWithAssertionResult) { #ifdef __BORLANDC__ // Restores warnings after previous "#pragma option push" suppressed them -# pragma option pop +#pragma option pop #endif // Tests using ASSERT_EQ on double values. The purpose is to make @@ -3727,18 +3692,19 @@ TEST(ExpectTest, ASSERT_EQ_Double) { ASSERT_EQ(5.6, 5.6); // A failure. - EXPECT_FATAL_FAILURE(ASSERT_EQ(5.1, 5.2), - "5.1"); + EXPECT_FATAL_FAILURE(ASSERT_EQ(5.1, 5.2), "5.1"); } // Tests ASSERT_EQ. TEST(AssertionTest, ASSERT_EQ) { ASSERT_EQ(5, 2 + 3); + // clang-format off EXPECT_FATAL_FAILURE(ASSERT_EQ(5, 2*3), "Expected equality of these values:\n" " 5\n" " 2*3\n" " Which is: 6"); + // clang-format on } // Tests ASSERT_EQ(NULL, pointer). @@ -3763,8 +3729,7 @@ TEST(ExpectTest, ASSERT_EQ_0) { ASSERT_EQ(0, n); // A failure. - EXPECT_FATAL_FAILURE(ASSERT_EQ(0, 5.6), - " 0\n 5.6"); + EXPECT_FATAL_FAILURE(ASSERT_EQ(0, 5.6), " 0\n 5.6"); } // Tests ASSERT_NE. @@ -3779,30 +3744,26 @@ TEST(AssertionTest, ASSERT_NE) { TEST(AssertionTest, ASSERT_LE) { ASSERT_LE(2, 3); ASSERT_LE(2, 2); - EXPECT_FATAL_FAILURE(ASSERT_LE(2, 0), - "Expected: (2) <= (0), actual: 2 vs 0"); + EXPECT_FATAL_FAILURE(ASSERT_LE(2, 0), "Expected: (2) <= (0), actual: 2 vs 0"); } // Tests ASSERT_LT. TEST(AssertionTest, ASSERT_LT) { ASSERT_LT(2, 3); - EXPECT_FATAL_FAILURE(ASSERT_LT(2, 2), - "Expected: (2) < (2), actual: 2 vs 2"); + EXPECT_FATAL_FAILURE(ASSERT_LT(2, 2), "Expected: (2) < (2), actual: 2 vs 2"); } // Tests ASSERT_GE. TEST(AssertionTest, ASSERT_GE) { ASSERT_GE(2, 1); ASSERT_GE(2, 2); - EXPECT_FATAL_FAILURE(ASSERT_GE(2, 3), - "Expected: (2) >= (3), actual: 2 vs 3"); + EXPECT_FATAL_FAILURE(ASSERT_GE(2, 3), "Expected: (2) >= (3), actual: 2 vs 3"); } // Tests ASSERT_GT. TEST(AssertionTest, ASSERT_GT) { ASSERT_GT(2, 1); - EXPECT_FATAL_FAILURE(ASSERT_GT(2, 2), - "Expected: (2) > (2), actual: 2 vs 2"); + EXPECT_FATAL_FAILURE(ASSERT_GT(2, 2), "Expected: (2) > (2), actual: 2 vs 2"); } #if GTEST_HAS_EXCEPTIONS @@ -3813,7 +3774,7 @@ void ThrowNothing() {} TEST(AssertionTest, ASSERT_THROW) { ASSERT_THROW(ThrowAnInteger(), int); -# ifndef __BORLANDC__ +#ifndef __BORLANDC__ // ICE's in C++Builder 2007 and 2009. EXPECT_FATAL_FAILURE( @@ -3824,9 +3785,10 @@ TEST(AssertionTest, ASSERT_THROW) { ASSERT_THROW(ThrowRuntimeError("A description"), std::logic_error), "Expected: ThrowRuntimeError(\"A description\") " "throws an exception of type std::logic_error.\n " - "Actual: it throws " ERROR_DESC " " + "Actual: it throws " ERROR_DESC + " " "with description \"A description\"."); -# endif +#endif EXPECT_FATAL_FAILURE( ASSERT_THROW(ThrowNothing(), bool), @@ -3843,17 +3805,17 @@ TEST(AssertionTest, ASSERT_NO_THROW) { EXPECT_FATAL_FAILURE(ASSERT_NO_THROW(ThrowRuntimeError("A description")), "Expected: ThrowRuntimeError(\"A description\") " "doesn't throw an exception.\n " - "Actual: it throws " ERROR_DESC " " + "Actual: it throws " ERROR_DESC + " " "with description \"A description\"."); } // Tests ASSERT_ANY_THROW. TEST(AssertionTest, ASSERT_ANY_THROW) { ASSERT_ANY_THROW(ThrowAnInteger()); - EXPECT_FATAL_FAILURE( - ASSERT_ANY_THROW(ThrowNothing()), - "Expected: ThrowNothing() throws an exception.\n" - " Actual: it doesn't."); + EXPECT_FATAL_FAILURE(ASSERT_ANY_THROW(ThrowNothing()), + "Expected: ThrowNothing() throws an exception.\n" + " Actual: it doesn't."); } #endif // GTEST_HAS_EXCEPTIONS @@ -3867,14 +3829,11 @@ TEST(AssertionTest, AssertPrecedence) { } // A subroutine used by the following test. -void TestEq1(int x) { - ASSERT_EQ(1, x); -} +void TestEq1(int x) { ASSERT_EQ(1, x); } // Tests calling a test subroutine that's not part of a fixture. TEST(AssertionTest, NonFixtureSubroutine) { - EXPECT_FATAL_FAILURE(TestEq1(2), - " x\n Which is: 2"); + EXPECT_FATAL_FAILURE(TestEq1(2), " x\n Which is: 2"); } // An uncopyable class. @@ -3886,6 +3845,7 @@ class Uncopyable { bool operator==(const Uncopyable& rhs) const { return value() == rhs.value(); } + private: // This constructor deliberately has no implementation, as we don't // want this class to be copyable. @@ -3898,10 +3858,7 @@ class Uncopyable { return os << value.value(); } - -bool IsPositiveUncopyable(const Uncopyable& x) { - return x.value() > 0; -} +bool IsPositiveUncopyable(const Uncopyable& x) { return x.value() > 0; } // A subroutine used by the following test. void TestAssertNonPositive() { @@ -3920,8 +3877,9 @@ TEST(AssertionTest, AssertWorksWithUncopyableObject) { Uncopyable x(5); ASSERT_PRED1(IsPositiveUncopyable, x); ASSERT_EQ(x, x); - EXPECT_FATAL_FAILURE(TestAssertNonPositive(), - "IsPositiveUncopyable(y) evaluates to false, where\ny evaluates to -1"); + EXPECT_FATAL_FAILURE( + TestAssertNonPositive(), + "IsPositiveUncopyable(y) evaluates to false, where\ny evaluates to -1"); EXPECT_FATAL_FAILURE(TestAssertEqualsUncopyable(), "Expected equality of these values:\n" " x\n Which is: 5\n y\n Which is: -1"); @@ -3932,18 +3890,16 @@ TEST(AssertionTest, ExpectWorksWithUncopyableObject) { Uncopyable x(5); EXPECT_PRED1(IsPositiveUncopyable, x); Uncopyable y(-1); - EXPECT_NONFATAL_FAILURE(EXPECT_PRED1(IsPositiveUncopyable, y), - "IsPositiveUncopyable(y) evaluates to false, where\ny evaluates to -1"); + EXPECT_NONFATAL_FAILURE( + EXPECT_PRED1(IsPositiveUncopyable, y), + "IsPositiveUncopyable(y) evaluates to false, where\ny evaluates to -1"); EXPECT_EQ(x, x); EXPECT_NONFATAL_FAILURE(EXPECT_EQ(x, y), "Expected equality of these values:\n" " x\n Which is: 5\n y\n Which is: -1"); } -enum NamedEnum { - kE1 = 0, - kE2 = 1 -}; +enum NamedEnum { kE1 = 0, kE2 = 1 }; TEST(AssertionTest, NamedEnum) { EXPECT_EQ(kE1, kE1); @@ -3959,7 +3915,7 @@ TEST(AssertionTest, NamedEnum) { enum { kCaseA = -1, -# if GTEST_OS_LINUX +#if GTEST_OS_LINUX // We want to test the case where the size of the anonymous enum is // larger than sizeof(int), to make sure our implementation of the @@ -3972,21 +3928,21 @@ enum { // assertions. kCaseB = testing::internal::kMaxBiggestInt, -# else +#else kCaseB = INT_MAX, -# endif // GTEST_OS_LINUX +#endif // GTEST_OS_LINUX kCaseC = 42 }; TEST(AssertionTest, AnonymousEnum) { -# if GTEST_OS_LINUX +#if GTEST_OS_LINUX EXPECT_EQ(static_cast<int>(kCaseA), static_cast<int>(kCaseB)); -# endif // GTEST_OS_LINUX +#endif // GTEST_OS_LINUX EXPECT_EQ(kCaseA, kCaseA); EXPECT_NE(kCaseA, kCaseB); @@ -3994,10 +3950,8 @@ TEST(AssertionTest, AnonymousEnum) { EXPECT_LE(kCaseA, kCaseB); EXPECT_GT(kCaseB, kCaseA); EXPECT_GE(kCaseA, kCaseA); - EXPECT_NONFATAL_FAILURE(EXPECT_GE(kCaseA, kCaseB), - "(kCaseA) >= (kCaseB)"); - EXPECT_NONFATAL_FAILURE(EXPECT_GE(kCaseA, kCaseC), - "-1 vs 42"); + EXPECT_NONFATAL_FAILURE(EXPECT_GE(kCaseA, kCaseB), "(kCaseA) >= (kCaseB)"); + EXPECT_NONFATAL_FAILURE(EXPECT_GE(kCaseA, kCaseC), "-1 vs 42"); ASSERT_EQ(kCaseA, kCaseA); ASSERT_NE(kCaseA, kCaseB); @@ -4006,34 +3960,25 @@ TEST(AssertionTest, AnonymousEnum) { ASSERT_GT(kCaseB, kCaseA); ASSERT_GE(kCaseA, kCaseA); -# ifndef __BORLANDC__ +#ifndef __BORLANDC__ // ICE's in C++Builder. - EXPECT_FATAL_FAILURE(ASSERT_EQ(kCaseA, kCaseB), - " kCaseB\n Which is: "); - EXPECT_FATAL_FAILURE(ASSERT_EQ(kCaseA, kCaseC), - "\n Which is: 42"); -# endif + EXPECT_FATAL_FAILURE(ASSERT_EQ(kCaseA, kCaseB), " kCaseB\n Which is: "); + EXPECT_FATAL_FAILURE(ASSERT_EQ(kCaseA, kCaseC), "\n Which is: 42"); +#endif - EXPECT_FATAL_FAILURE(ASSERT_EQ(kCaseA, kCaseC), - "\n Which is: -1"); + EXPECT_FATAL_FAILURE(ASSERT_EQ(kCaseA, kCaseC), "\n Which is: -1"); } #endif // !GTEST_OS_MAC && !defined(__SUNPRO_CC) #if GTEST_OS_WINDOWS -static HRESULT UnexpectedHRESULTFailure() { - return E_UNEXPECTED; -} +static HRESULT UnexpectedHRESULTFailure() { return E_UNEXPECTED; } -static HRESULT OkHRESULTSuccess() { - return S_OK; -} +static HRESULT OkHRESULTSuccess() { return S_OK; } -static HRESULT FalseHRESULTSuccess() { - return S_FALSE; -} +static HRESULT FalseHRESULTSuccess() { return S_FALSE; } // HRESULT assertion tests test both zero and non-zero // success codes as well as failure message for each. @@ -4044,8 +3989,8 @@ TEST(HRESULTAssertionTest, EXPECT_HRESULT_SUCCEEDED) { EXPECT_HRESULT_SUCCEEDED(S_FALSE); EXPECT_NONFATAL_FAILURE(EXPECT_HRESULT_SUCCEEDED(UnexpectedHRESULTFailure()), - "Expected: (UnexpectedHRESULTFailure()) succeeds.\n" - " Actual: 0x8000FFFF"); + "Expected: (UnexpectedHRESULTFailure()) succeeds.\n" + " Actual: 0x8000FFFF"); } TEST(HRESULTAssertionTest, ASSERT_HRESULT_SUCCEEDED) { @@ -4053,35 +3998,35 @@ TEST(HRESULTAssertionTest, ASSERT_HRESULT_SUCCEEDED) { ASSERT_HRESULT_SUCCEEDED(S_FALSE); EXPECT_FATAL_FAILURE(ASSERT_HRESULT_SUCCEEDED(UnexpectedHRESULTFailure()), - "Expected: (UnexpectedHRESULTFailure()) succeeds.\n" - " Actual: 0x8000FFFF"); + "Expected: (UnexpectedHRESULTFailure()) succeeds.\n" + " Actual: 0x8000FFFF"); } TEST(HRESULTAssertionTest, EXPECT_HRESULT_FAILED) { EXPECT_HRESULT_FAILED(E_UNEXPECTED); EXPECT_NONFATAL_FAILURE(EXPECT_HRESULT_FAILED(OkHRESULTSuccess()), - "Expected: (OkHRESULTSuccess()) fails.\n" - " Actual: 0x0"); + "Expected: (OkHRESULTSuccess()) fails.\n" + " Actual: 0x0"); EXPECT_NONFATAL_FAILURE(EXPECT_HRESULT_FAILED(FalseHRESULTSuccess()), - "Expected: (FalseHRESULTSuccess()) fails.\n" - " Actual: 0x1"); + "Expected: (FalseHRESULTSuccess()) fails.\n" + " Actual: 0x1"); } TEST(HRESULTAssertionTest, ASSERT_HRESULT_FAILED) { ASSERT_HRESULT_FAILED(E_UNEXPECTED); -# ifndef __BORLANDC__ +#ifndef __BORLANDC__ // ICE's in C++Builder 2007 and 2009. EXPECT_FATAL_FAILURE(ASSERT_HRESULT_FAILED(OkHRESULTSuccess()), - "Expected: (OkHRESULTSuccess()) fails.\n" - " Actual: 0x0"); -# endif + "Expected: (OkHRESULTSuccess()) fails.\n" + " Actual: 0x0"); +#endif EXPECT_FATAL_FAILURE(ASSERT_HRESULT_FAILED(FalseHRESULTSuccess()), - "Expected: (FalseHRESULTSuccess()) fails.\n" - " Actual: 0x1"); + "Expected: (FalseHRESULTSuccess()) fails.\n" + " Actual: 0x1"); } // Tests that streaming to the HRESULT macros works. @@ -4091,25 +4036,23 @@ TEST(HRESULTAssertionTest, Streaming) { EXPECT_HRESULT_FAILED(E_UNEXPECTED) << "unexpected failure"; ASSERT_HRESULT_FAILED(E_UNEXPECTED) << "unexpected failure"; - EXPECT_NONFATAL_FAILURE( - EXPECT_HRESULT_SUCCEEDED(E_UNEXPECTED) << "expected failure", - "expected failure"); + EXPECT_NONFATAL_FAILURE(EXPECT_HRESULT_SUCCEEDED(E_UNEXPECTED) + << "expected failure", + "expected failure"); -# ifndef __BORLANDC__ +#ifndef __BORLANDC__ // ICE's in C++Builder 2007 and 2009. - EXPECT_FATAL_FAILURE( - ASSERT_HRESULT_SUCCEEDED(E_UNEXPECTED) << "expected failure", - "expected failure"); -# endif + EXPECT_FATAL_FAILURE(ASSERT_HRESULT_SUCCEEDED(E_UNEXPECTED) + << "expected failure", + "expected failure"); +#endif - EXPECT_NONFATAL_FAILURE( - EXPECT_HRESULT_FAILED(S_OK) << "expected failure", - "expected failure"); + EXPECT_NONFATAL_FAILURE(EXPECT_HRESULT_FAILED(S_OK) << "expected failure", + "expected failure"); - EXPECT_FATAL_FAILURE( - ASSERT_HRESULT_FAILED(S_OK) << "expected failure", - "expected failure"); + EXPECT_FATAL_FAILURE(ASSERT_HRESULT_FAILED(S_OK) << "expected failure", + "expected failure"); } #endif // GTEST_OS_WINDOWS @@ -4132,8 +4075,7 @@ TEST(AssertionSyntaxTest, BasicAssertionsBehavesLikeSingleStatement) { else ; // NOLINT - if (AlwaysFalse()) - ASSERT_LT(1, 3); + if (AlwaysFalse()) ASSERT_LT(1, 3); if (AlwaysFalse()) ; // NOLINT @@ -4171,24 +4113,21 @@ TEST(ExpectThrowTest, DoesNotGenerateDuplicateCatchClauseWarning) { #pragma GCC diagnostic ignored "-Wpragmas" #endif TEST(AssertionSyntaxTest, ExceptionAssertionsBehavesLikeSingleStatement) { - if (AlwaysFalse()) - EXPECT_THROW(ThrowNothing(), bool); + if (AlwaysFalse()) EXPECT_THROW(ThrowNothing(), bool); if (AlwaysTrue()) EXPECT_THROW(ThrowAnInteger(), int); else ; // NOLINT - if (AlwaysFalse()) - EXPECT_NO_THROW(ThrowAnInteger()); + if (AlwaysFalse()) EXPECT_NO_THROW(ThrowAnInteger()); if (AlwaysTrue()) EXPECT_NO_THROW(ThrowNothing()); else ; // NOLINT - if (AlwaysFalse()) - EXPECT_ANY_THROW(ThrowNothing()); + if (AlwaysFalse()) EXPECT_ANY_THROW(ThrowNothing()); if (AlwaysTrue()) EXPECT_ANY_THROW(ThrowAnInteger()); @@ -4244,8 +4183,8 @@ TEST(AssertionSyntaxTest, WorksWithSwitch) { } switch (0) - case 0: - EXPECT_FALSE(false) << "EXPECT_FALSE failed in switch case"; + case 0: + EXPECT_FALSE(false) << "EXPECT_FALSE failed in switch case"; // Binary assertions are implemented using a different code path // than the Boolean assertions. Hence we test them separately. @@ -4256,22 +4195,20 @@ TEST(AssertionSyntaxTest, WorksWithSwitch) { } switch (0) - case 0: - EXPECT_NE(1, 2); + case 0: + EXPECT_NE(1, 2); } #if GTEST_HAS_EXCEPTIONS -void ThrowAString() { - throw "std::string"; -} +void ThrowAString() { throw "std::string"; } // Test that the exception assertion macros compile and work with const // type qualifier. TEST(AssertionSyntaxTest, WorksWithConst) { - ASSERT_THROW(ThrowAString(), const char*); + ASSERT_THROW(ThrowAString(), const char*); - EXPECT_THROW(ThrowAString(), const char*); + EXPECT_THROW(ThrowAString(), const char*); } #endif // GTEST_HAS_EXCEPTIONS @@ -4369,22 +4306,19 @@ TEST(AssertionWithMessageTest, ASSERT_FLOATING) { // Tests using ASSERT_FALSE with a streamed message. TEST(AssertionWithMessageTest, ASSERT_FALSE) { ASSERT_FALSE(false) << "This shouldn't fail."; - EXPECT_FATAL_FAILURE({ // NOLINT - ASSERT_FALSE(true) << "Expected failure: " << 2 << " > " << 1 - << " evaluates to " << true; - }, "Expected failure"); + EXPECT_FATAL_FAILURE( + { // NOLINT + ASSERT_FALSE(true) << "Expected failure: " << 2 << " > " << 1 + << " evaluates to " << true; + }, + "Expected failure"); } // Tests using FAIL with a streamed message. -TEST(AssertionWithMessageTest, FAIL) { - EXPECT_FATAL_FAILURE(FAIL() << 0, - "0"); -} +TEST(AssertionWithMessageTest, FAIL) { EXPECT_FATAL_FAILURE(FAIL() << 0, "0"); } // Tests using SUCCEED with a streamed message. -TEST(AssertionWithMessageTest, SUCCEED) { - SUCCEED() << "Success == " << 1; -} +TEST(AssertionWithMessageTest, SUCCEED) { SUCCEED() << "Success == " << 1; } // Tests using ASSERT_TRUE with a streamed message. TEST(AssertionWithMessageTest, ASSERT_TRUE) { @@ -4401,13 +4335,16 @@ TEST(AssertionWithMessageTest, ASSERT_TRUE) { #if GTEST_OS_WINDOWS // Tests using wide strings in assertion messages. TEST(AssertionWithMessageTest, WideStringMessage) { - EXPECT_NONFATAL_FAILURE({ // NOLINT - EXPECT_TRUE(false) << L"This failure is expected.\x8119"; - }, "This failure is expected."); - EXPECT_FATAL_FAILURE({ // NOLINT - ASSERT_EQ(1, 2) << "This failure is " - << L"expected too.\x8120"; - }, "This failure is expected too."); + EXPECT_NONFATAL_FAILURE( + { // NOLINT + EXPECT_TRUE(false) << L"This failure is expected.\x8119"; + }, + "This failure is expected."); + EXPECT_FATAL_FAILURE( + { // NOLINT + ASSERT_EQ(1, 2) << "This failure is " << L"expected too.\x8120"; + }, + "This failure is expected too."); } #endif // GTEST_OS_WINDOWS @@ -4423,8 +4360,7 @@ TEST(ExpectTest, EXPECT_TRUE) { "Value of: 2 < 1\n" " Actual: false\n" "Expected: true"); - EXPECT_NONFATAL_FAILURE(EXPECT_TRUE(2 > 3), - "2 > 3"); + EXPECT_NONFATAL_FAILURE(EXPECT_TRUE(2 > 3), "2 > 3"); } // Tests EXPECT_TRUE(predicate) for predicates returning AssertionResult. @@ -4453,8 +4389,7 @@ TEST(ExpectTest, EXPECT_FALSE) { "Value of: 2 > 1\n" " Actual: true\n" "Expected: false"); - EXPECT_NONFATAL_FAILURE(EXPECT_FALSE(2 < 3), - "2 < 3"); + EXPECT_NONFATAL_FAILURE(EXPECT_FALSE(2 < 3), "2 < 3"); } // Tests EXPECT_FALSE(predicate) for predicates returning AssertionResult. @@ -4473,19 +4408,20 @@ TEST(ExpectTest, ExpectFalseWithAssertionResult) { #ifdef __BORLANDC__ // Restores warnings after previous "#pragma option push" suppressed them -# pragma option pop +#pragma option pop #endif // Tests EXPECT_EQ. TEST(ExpectTest, EXPECT_EQ) { EXPECT_EQ(5, 2 + 3); + // clang-format off EXPECT_NONFATAL_FAILURE(EXPECT_EQ(5, 2*3), "Expected equality of these values:\n" " 5\n" " 2*3\n" " Which is: 6"); - EXPECT_NONFATAL_FAILURE(EXPECT_EQ(5, 2 - 3), - "2 - 3"); + EXPECT_NONFATAL_FAILURE(EXPECT_EQ(5, 2 - 3), "2 - 3"); + // clang-format on } // Tests using EXPECT_EQ on double values. The purpose is to make @@ -4496,8 +4432,7 @@ TEST(ExpectTest, EXPECT_EQ_Double) { EXPECT_EQ(5.6, 5.6); // A failure. - EXPECT_NONFATAL_FAILURE(EXPECT_EQ(5.1, 5.2), - "5.1"); + EXPECT_NONFATAL_FAILURE(EXPECT_EQ(5.1, 5.2), "5.1"); } // Tests EXPECT_EQ(NULL, pointer). @@ -4522,8 +4457,7 @@ TEST(ExpectTest, EXPECT_EQ_0) { EXPECT_EQ(0, n); // A failure. - EXPECT_NONFATAL_FAILURE(EXPECT_EQ(0, 5.6), - " 0\n 5.6"); + EXPECT_NONFATAL_FAILURE(EXPECT_EQ(0, 5.6), " 0\n 5.6"); } // Tests EXPECT_NE. @@ -4533,19 +4467,16 @@ TEST(ExpectTest, EXPECT_NE) { EXPECT_NONFATAL_FAILURE(EXPECT_NE('a', 'a'), "Expected: ('a') != ('a'), " "actual: 'a' (97, 0x61) vs 'a' (97, 0x61)"); - EXPECT_NONFATAL_FAILURE(EXPECT_NE(2, 2), - "2"); + EXPECT_NONFATAL_FAILURE(EXPECT_NE(2, 2), "2"); char* const p0 = nullptr; - EXPECT_NONFATAL_FAILURE(EXPECT_NE(p0, p0), - "p0"); + EXPECT_NONFATAL_FAILURE(EXPECT_NE(p0, p0), "p0"); // Only way to get the Nokia compiler to compile the cast // is to have a separate void* variable first. Putting // the two casts on the same line doesn't work, neither does // a direct C-style to char*. void* pv1 = (void*)0x1234; // NOLINT char* const p1 = reinterpret_cast<char*>(pv1); - EXPECT_NONFATAL_FAILURE(EXPECT_NE(p1, p1), - "p1"); + EXPECT_NONFATAL_FAILURE(EXPECT_NE(p1, p1), "p1"); } // Tests EXPECT_LE. @@ -4554,8 +4485,7 @@ TEST(ExpectTest, EXPECT_LE) { EXPECT_LE(2, 2); EXPECT_NONFATAL_FAILURE(EXPECT_LE(2, 0), "Expected: (2) <= (0), actual: 2 vs 0"); - EXPECT_NONFATAL_FAILURE(EXPECT_LE(1.1, 0.9), - "(1.1) <= (0.9)"); + EXPECT_NONFATAL_FAILURE(EXPECT_LE(1.1, 0.9), "(1.1) <= (0.9)"); } // Tests EXPECT_LT. @@ -4563,8 +4493,7 @@ TEST(ExpectTest, EXPECT_LT) { EXPECT_LT(2, 3); EXPECT_NONFATAL_FAILURE(EXPECT_LT(2, 2), "Expected: (2) < (2), actual: 2 vs 2"); - EXPECT_NONFATAL_FAILURE(EXPECT_LT(2, 1), - "(2) < (1)"); + EXPECT_NONFATAL_FAILURE(EXPECT_LT(2, 1), "(2) < (1)"); } // Tests EXPECT_GE. @@ -4573,8 +4502,7 @@ TEST(ExpectTest, EXPECT_GE) { EXPECT_GE(2, 2); EXPECT_NONFATAL_FAILURE(EXPECT_GE(2, 3), "Expected: (2) >= (3), actual: 2 vs 3"); - EXPECT_NONFATAL_FAILURE(EXPECT_GE(0.9, 1.1), - "(0.9) >= (1.1)"); + EXPECT_NONFATAL_FAILURE(EXPECT_GE(0.9, 1.1), "(0.9) >= (1.1)"); } // Tests EXPECT_GT. @@ -4582,8 +4510,7 @@ TEST(ExpectTest, EXPECT_GT) { EXPECT_GT(2, 1); EXPECT_NONFATAL_FAILURE(EXPECT_GT(2, 2), "Expected: (2) > (2), actual: 2 vs 2"); - EXPECT_NONFATAL_FAILURE(EXPECT_GT(2, 3), - "(2) > (3)"); + EXPECT_NONFATAL_FAILURE(EXPECT_GT(2, 3), "(2) > (3)"); } #if GTEST_HAS_EXCEPTIONS @@ -4594,12 +4521,13 @@ TEST(ExpectTest, EXPECT_THROW) { EXPECT_NONFATAL_FAILURE(EXPECT_THROW(ThrowAnInteger(), bool), "Expected: ThrowAnInteger() throws an exception of " "type bool.\n Actual: it throws a different type."); - EXPECT_NONFATAL_FAILURE(EXPECT_THROW(ThrowRuntimeError("A description"), - std::logic_error), - "Expected: ThrowRuntimeError(\"A description\") " - "throws an exception of type std::logic_error.\n " - "Actual: it throws " ERROR_DESC " " - "with description \"A description\"."); + EXPECT_NONFATAL_FAILURE( + EXPECT_THROW(ThrowRuntimeError("A description"), std::logic_error), + "Expected: ThrowRuntimeError(\"A description\") " + "throws an exception of type std::logic_error.\n " + "Actual: it throws " ERROR_DESC + " " + "with description \"A description\"."); EXPECT_NONFATAL_FAILURE( EXPECT_THROW(ThrowNothing(), bool), "Expected: ThrowNothing() throws an exception of type bool.\n" @@ -4615,17 +4543,17 @@ TEST(ExpectTest, EXPECT_NO_THROW) { EXPECT_NONFATAL_FAILURE(EXPECT_NO_THROW(ThrowRuntimeError("A description")), "Expected: ThrowRuntimeError(\"A description\") " "doesn't throw an exception.\n " - "Actual: it throws " ERROR_DESC " " + "Actual: it throws " ERROR_DESC + " " "with description \"A description\"."); } // Tests EXPECT_ANY_THROW. TEST(ExpectTest, EXPECT_ANY_THROW) { EXPECT_ANY_THROW(ThrowAnInteger()); - EXPECT_NONFATAL_FAILURE( - EXPECT_ANY_THROW(ThrowNothing()), - "Expected: ThrowNothing() throws an exception.\n" - " Actual: it doesn't."); + EXPECT_NONFATAL_FAILURE(EXPECT_ANY_THROW(ThrowNothing()), + "Expected: ThrowNothing() throws an exception.\n" + " Actual: it doesn't."); } #endif // GTEST_HAS_EXCEPTIONS @@ -4637,7 +4565,6 @@ TEST(ExpectTest, ExpectPrecedence) { " true && false\n Which is: false"); } - // Tests the StreamableToString() function. // Tests using StreamableToString() on a scalar. @@ -4675,8 +4602,7 @@ TEST(StreamableToStringTest, NullCString) { TEST(StreamableTest, string) { static const std::string str( "This failure message is a std::string, and is expected."); - EXPECT_FATAL_FAILURE(FAIL() << str, - str.c_str()); + EXPECT_FATAL_FAILURE(FAIL() << str, str.c_str()); } // Tests that we can output strings containing embedded NULs. @@ -4684,25 +4610,24 @@ TEST(StreamableTest, string) { TEST(StreamableTest, stringWithEmbeddedNUL) { static const char char_array_with_nul[] = "Here's a NUL\0 and some more string"; - static const std::string string_with_nul(char_array_with_nul, - sizeof(char_array_with_nul) - - 1); // drops the trailing NUL + static const std::string string_with_nul( + char_array_with_nul, + sizeof(char_array_with_nul) - 1); // drops the trailing NUL EXPECT_FATAL_FAILURE(FAIL() << string_with_nul, "Here's a NUL\\0 and some more string"); } // Tests that we can output a NUL char. TEST(StreamableTest, NULChar) { - EXPECT_FATAL_FAILURE({ // NOLINT - FAIL() << "A NUL" << '\0' << " and some more string"; - }, "A NUL\\0 and some more string"); + EXPECT_FATAL_FAILURE( + { // NOLINT + FAIL() << "A NUL" << '\0' << " and some more string"; + }, + "A NUL\\0 and some more string"); } // Tests using int as an assertion message. -TEST(StreamableTest, int) { - EXPECT_FATAL_FAILURE(FAIL() << 900913, - "900913"); -} +TEST(StreamableTest, int) { EXPECT_FATAL_FAILURE(FAIL() << 900913, "900913"); } // Tests using NULL char pointer as an assertion message. // @@ -4716,10 +4641,12 @@ TEST(StreamableTest, NullCharPtr) { // Tests that basic IO manipulators (endl, ends, and flush) can be // streamed to testing::Message. TEST(StreamableTest, BasicIoManip) { - EXPECT_FATAL_FAILURE({ // NOLINT - FAIL() << "Line 1." << std::endl - << "A NUL char " << std::ends << std::flush << " in line 2."; - }, "Line 1.\nA NUL char \\0 in line 2."); + EXPECT_FATAL_FAILURE( + { // NOLINT + FAIL() << "Line 1." << std::endl + << "A NUL char " << std::ends << std::flush << " in line 2."; + }, + "Line 1.\nA NUL char \\0 in line 2."); } // Tests the macros that haven't been covered so far. @@ -4733,8 +4660,7 @@ void AddFailureHelper(bool* aborted) { // Tests ADD_FAILURE. TEST(MacroTest, ADD_FAILURE) { bool aborted = true; - EXPECT_NONFATAL_FAILURE(AddFailureHelper(&aborted), - "Intentional failure."); + EXPECT_NONFATAL_FAILURE(AddFailureHelper(&aborted), "Intentional failure."); EXPECT_FALSE(aborted); } @@ -4755,8 +4681,7 @@ TEST(MacroTest, ADD_FAILURE_AT) { // Tests FAIL. TEST(MacroTest, FAIL) { - EXPECT_FATAL_FAILURE(FAIL(), - "Failed"); + EXPECT_FATAL_FAILURE(FAIL(), "Failed"); EXPECT_FATAL_FAILURE(FAIL() << "Intentional failure.", "Intentional failure."); } @@ -4789,37 +4714,34 @@ TEST(MacroTest, SUCCEED) { // Tests using bool values in {EXPECT|ASSERT}_EQ. TEST(EqAssertionTest, Bool) { - EXPECT_EQ(true, true); - EXPECT_FATAL_FAILURE({ - bool false_value = false; - ASSERT_EQ(false_value, true); - }, " false_value\n Which is: false\n true"); + EXPECT_EQ(true, true); + EXPECT_FATAL_FAILURE( + { + bool false_value = false; + ASSERT_EQ(false_value, true); + }, + " false_value\n Which is: false\n true"); } // Tests using int values in {EXPECT|ASSERT}_EQ. TEST(EqAssertionTest, Int) { ASSERT_EQ(32, 32); - EXPECT_NONFATAL_FAILURE(EXPECT_EQ(32, 33), - " 32\n 33"); + EXPECT_NONFATAL_FAILURE(EXPECT_EQ(32, 33), " 32\n 33"); } // Tests using time_t values in {EXPECT|ASSERT}_EQ. TEST(EqAssertionTest, Time_T) { - EXPECT_EQ(static_cast<time_t>(0), - static_cast<time_t>(0)); - EXPECT_FATAL_FAILURE(ASSERT_EQ(static_cast<time_t>(0), - static_cast<time_t>(1234)), - "1234"); + EXPECT_EQ(static_cast<time_t>(0), static_cast<time_t>(0)); + EXPECT_FATAL_FAILURE( + ASSERT_EQ(static_cast<time_t>(0), static_cast<time_t>(1234)), "1234"); } // Tests using char values in {EXPECT|ASSERT}_EQ. TEST(EqAssertionTest, Char) { ASSERT_EQ('z', 'z'); const char ch = 'b'; - EXPECT_NONFATAL_FAILURE(EXPECT_EQ('\0', ch), - " ch\n Which is: 'b'"); - EXPECT_NONFATAL_FAILURE(EXPECT_EQ('a', ch), - " ch\n Which is: 'b'"); + EXPECT_NONFATAL_FAILURE(EXPECT_EQ('\0', ch), " ch\n Which is: 'b'"); + EXPECT_NONFATAL_FAILURE(EXPECT_EQ('a', ch), " ch\n Which is: 'b'"); } // Tests using wchar_t values in {EXPECT|ASSERT}_EQ. @@ -4835,8 +4757,7 @@ TEST(EqAssertionTest, WideChar) { static wchar_t wchar; wchar = L'b'; - EXPECT_NONFATAL_FAILURE(EXPECT_EQ(L'a', wchar), - "wchar"); + EXPECT_NONFATAL_FAILURE(EXPECT_EQ(L'a', wchar), "wchar"); wchar = 0x8119; EXPECT_FATAL_FAILURE(ASSERT_EQ(static_cast<wchar_t>(0x8120), wchar), " wchar\n Which is: L'"); @@ -4855,13 +4776,11 @@ TEST(EqAssertionTest, StdString) { // Compares a const char* to an std::string that has different // content - EXPECT_NONFATAL_FAILURE(EXPECT_EQ("Test", ::std::string("test")), - "\"test\""); + EXPECT_NONFATAL_FAILURE(EXPECT_EQ("Test", ::std::string("test")), "\"test\""); // Compares an std::string to a char* that has different content. char* const p1 = const_cast<char*>("foo"); - EXPECT_NONFATAL_FAILURE(EXPECT_EQ(::std::string("bar"), p1), - "p1"); + EXPECT_NONFATAL_FAILURE(EXPECT_EQ(::std::string("bar"), p1), "p1"); // Compares two std::strings that have different contents, one of // which having a NUL character in the middle. This should fail. @@ -4882,28 +4801,31 @@ TEST(EqAssertionTest, StdWideString) { // Compares an std::wstring to a const wchar_t* that has identical // content. - const wchar_t kTestX8119[] = { 'T', 'e', 's', 't', 0x8119, '\0' }; + const wchar_t kTestX8119[] = {'T', 'e', 's', 't', 0x8119, '\0'}; EXPECT_EQ(::std::wstring(kTestX8119), kTestX8119); // Compares an std::wstring to a const wchar_t* that has different // content. - const wchar_t kTestX8120[] = { 'T', 'e', 's', 't', 0x8120, '\0' }; - EXPECT_NONFATAL_FAILURE({ // NOLINT - EXPECT_EQ(::std::wstring(kTestX8119), kTestX8120); - }, "kTestX8120"); + const wchar_t kTestX8120[] = {'T', 'e', 's', 't', 0x8120, '\0'}; + EXPECT_NONFATAL_FAILURE( + { // NOLINT + EXPECT_EQ(::std::wstring(kTestX8119), kTestX8120); + }, + "kTestX8120"); // Compares two std::wstrings that have different contents, one of // which having a NUL character in the middle. ::std::wstring wstr3(wstr1); wstr3.at(2) = L'\0'; - EXPECT_NONFATAL_FAILURE(EXPECT_EQ(wstr1, wstr3), - "wstr3"); + EXPECT_NONFATAL_FAILURE(EXPECT_EQ(wstr1, wstr3), "wstr3"); // Compares a wchar_t* to an std::wstring that has different // content. - EXPECT_FATAL_FAILURE({ // NOLINT - ASSERT_EQ(const_cast<wchar_t*>(L"foo"), ::std::wstring(L"bar")); - }, ""); + EXPECT_FATAL_FAILURE( + { // NOLINT + ASSERT_EQ(const_cast<wchar_t*>(L"foo"), ::std::wstring(L"bar")); + }, + ""); } #endif // GTEST_HAS_STD_WSTRING @@ -4921,10 +4843,8 @@ TEST(EqAssertionTest, CharPointer) { char* const p2 = reinterpret_cast<char*>(pv2); ASSERT_EQ(p1, p1); - EXPECT_NONFATAL_FAILURE(EXPECT_EQ(p0, p2), - " p2\n Which is:"); - EXPECT_NONFATAL_FAILURE(EXPECT_EQ(p1, p2), - " p2\n Which is:"); + EXPECT_NONFATAL_FAILURE(EXPECT_EQ(p0, p2), " p2\n Which is:"); + EXPECT_NONFATAL_FAILURE(EXPECT_EQ(p1, p2), " p2\n Which is:"); EXPECT_FATAL_FAILURE(ASSERT_EQ(reinterpret_cast<char*>(0x1234), reinterpret_cast<char*>(0xABC0)), "ABC0"); @@ -4943,16 +4863,13 @@ TEST(EqAssertionTest, WideCharPointer) { wchar_t* const p2 = reinterpret_cast<wchar_t*>(pv2); EXPECT_EQ(p0, p0); - EXPECT_NONFATAL_FAILURE(EXPECT_EQ(p0, p2), - " p2\n Which is:"); - EXPECT_NONFATAL_FAILURE(EXPECT_EQ(p1, p2), - " p2\n Which is:"); + EXPECT_NONFATAL_FAILURE(EXPECT_EQ(p0, p2), " p2\n Which is:"); + EXPECT_NONFATAL_FAILURE(EXPECT_EQ(p1, p2), " p2\n Which is:"); void* pv3 = (void*)0x1234; // NOLINT void* pv4 = (void*)0xABC0; // NOLINT const wchar_t* p3 = reinterpret_cast<const wchar_t*>(pv3); const wchar_t* p4 = reinterpret_cast<const wchar_t*>(pv4); - EXPECT_NONFATAL_FAILURE(EXPECT_EQ(p3, p4), - "p4"); + EXPECT_NONFATAL_FAILURE(EXPECT_EQ(p3, p4), "p4"); } // Tests using other types of pointers in {EXPECT|ASSERT}_EQ. @@ -4974,15 +4891,11 @@ class UnprintableChar { bool operator!=(const UnprintableChar& rhs) const { return char_ != rhs.char_; } - bool operator<(const UnprintableChar& rhs) const { - return char_ < rhs.char_; - } + bool operator<(const UnprintableChar& rhs) const { return char_ < rhs.char_; } bool operator<=(const UnprintableChar& rhs) const { return char_ <= rhs.char_; } - bool operator>(const UnprintableChar& rhs) const { - return char_ > rhs.char_; - } + bool operator>(const UnprintableChar& rhs) const { return char_ > rhs.char_; } bool operator>=(const UnprintableChar& rhs) const { return char_ >= rhs.char_; } @@ -5044,9 +4957,7 @@ class Foo { // Tests that the FRIEND_TEST declaration allows a TEST to access a // class's private members. This should compile. -TEST(FRIEND_TEST_Test, TEST) { - ASSERT_EQ(1, Foo().Bar()); -} +TEST(FRIEND_TEST_Test, TEST) { ASSERT_EQ(1, Foo().Bar()); } // The fixture needed to test using FRIEND_TEST with TEST_F. class FRIEND_TEST_Test2 : public Test { @@ -5056,9 +4967,7 @@ class FRIEND_TEST_Test2 : public Test { // Tests that the FRIEND_TEST declaration allows a TEST_F to access a // class's private members. This should compile. -TEST_F(FRIEND_TEST_Test2, TEST_F) { - ASSERT_EQ(1, foo.Bar()); -} +TEST_F(FRIEND_TEST_Test2, TEST_F) { ASSERT_EQ(1, foo.Bar()); } // Tests the life cycle of Test objects. @@ -5193,15 +5102,14 @@ class Base { public: explicit Base(int an_x) : x_(an_x) {} int x() const { return x_; } + private: int x_; }; -std::ostream& operator<<(std::ostream& os, - const Base& val) { +std::ostream& operator<<(std::ostream& os, const Base& val) { return os << val.x(); } -std::ostream& operator<<(std::ostream& os, - const Base* pointer) { +std::ostream& operator<<(std::ostream& os, const Base* pointer) { return os << "(" << pointer->x() << ")"; } @@ -5218,7 +5126,7 @@ TEST(MessageTest, CanStreamUserTypeInGlobalNameSpace) { namespace { class MyTypeInUnnamedNameSpace : public Base { public: - explicit MyTypeInUnnamedNameSpace(int an_x): Base(an_x) {} + explicit MyTypeInUnnamedNameSpace(int an_x) : Base(an_x) {} }; std::ostream& operator<<(std::ostream& os, const MyTypeInUnnamedNameSpace& val) { @@ -5243,14 +5151,12 @@ TEST(MessageTest, CanStreamUserTypeInUnnamedNameSpace) { namespace namespace1 { class MyTypeInNameSpace1 : public Base { public: - explicit MyTypeInNameSpace1(int an_x): Base(an_x) {} + explicit MyTypeInNameSpace1(int an_x) : Base(an_x) {} }; -std::ostream& operator<<(std::ostream& os, - const MyTypeInNameSpace1& val) { +std::ostream& operator<<(std::ostream& os, const MyTypeInNameSpace1& val) { return os << val.x(); } -std::ostream& operator<<(std::ostream& os, - const MyTypeInNameSpace1* pointer) { +std::ostream& operator<<(std::ostream& os, const MyTypeInNameSpace1* pointer) { return os << "(" << pointer->x() << ")"; } } // namespace namespace1 @@ -5268,7 +5174,7 @@ TEST(MessageTest, CanStreamUserTypeInUserNameSpace) { namespace namespace2 { class MyTypeInNameSpace2 : public ::Base { public: - explicit MyTypeInNameSpace2(int an_x): Base(an_x) {} + explicit MyTypeInNameSpace2(int an_x) : Base(an_x) {} }; } // namespace namespace2 std::ostream& operator<<(std::ostream& os, @@ -5299,21 +5205,18 @@ TEST(MessageTest, NullPointers) { Message* p6 = nullptr; msg << p1 << p2 << p3 << p4 << p5 << p6; - ASSERT_STREQ("(null)(null)(null)(null)(null)(null)", - msg.GetString().c_str()); + ASSERT_STREQ("(null)(null)(null)(null)(null)(null)", msg.GetString().c_str()); } // Tests streaming wide strings to testing::Message. TEST(MessageTest, WideStrings) { // Streams a NULL of type const wchar_t*. const wchar_t* const_wstr = nullptr; - EXPECT_STREQ("(null)", - (Message() << const_wstr).GetString().c_str()); + EXPECT_STREQ("(null)", (Message() << const_wstr).GetString().c_str()); // Streams a NULL of type wchar_t*. wchar_t* wstr = nullptr; - EXPECT_STREQ("(null)", - (Message() << wstr).GetString().c_str()); + EXPECT_STREQ("(null)", (Message() << wstr).GetString().c_str()); // Streams a non-NULL of type const wchar_t*. const_wstr = L"abc\x8119"; @@ -5322,11 +5225,9 @@ TEST(MessageTest, WideStrings) { // Streams a non-NULL of type wchar_t*. wstr = const_cast<wchar_t*>(const_wstr); - EXPECT_STREQ("abc\xe8\x84\x99", - (Message() << wstr).GetString().c_str()); + EXPECT_STREQ("abc\xe8\x84\x99", (Message() << wstr).GetString().c_str()); } - // This line tests that we can define tests in the testing namespace. namespace testing { @@ -5340,14 +5241,12 @@ class TestInfoTest : public Test { for (int i = 0; i < test_suite->total_test_count(); ++i) { const TestInfo* const test_info = test_suite->GetTestInfo(i); - if (strcmp(test_name, test_info->name()) == 0) - return test_info; + if (strcmp(test_name, test_info->name()) == 0) return test_info; } return nullptr; } - static const TestResult* GetTestResult( - const TestInfo* test_info) { + static const TestResult* GetTestResult(const TestInfo* test_info) { return test_info->result(); } }; @@ -5371,26 +5270,25 @@ TEST_F(TestInfoTest, result) { ASSERT_EQ(0, GetTestResult(test_info)->total_part_count()); } -#define VERIFY_CODE_LOCATION \ - const int expected_line = __LINE__ - 1; \ +#define VERIFY_CODE_LOCATION \ + const int expected_line = __LINE__ - 1; \ const TestInfo* const test_info = GetUnitTestImpl()->current_test_info(); \ - ASSERT_TRUE(test_info); \ - EXPECT_STREQ(__FILE__, test_info->file()); \ + ASSERT_TRUE(test_info); \ + EXPECT_STREQ(__FILE__, test_info->file()); \ EXPECT_EQ(expected_line, test_info->line()) +// clang-format off TEST(CodeLocationForTEST, Verify) { VERIFY_CODE_LOCATION; } -class CodeLocationForTESTF : public Test { -}; +class CodeLocationForTESTF : public Test {}; TEST_F(CodeLocationForTESTF, Verify) { VERIFY_CODE_LOCATION; } -class CodeLocationForTESTP : public TestWithParam<int> { -}; +class CodeLocationForTESTP : public TestWithParam<int> {}; TEST_P(CodeLocationForTESTP, Verify) { VERIFY_CODE_LOCATION; @@ -5399,8 +5297,7 @@ TEST_P(CodeLocationForTESTP, Verify) { INSTANTIATE_TEST_SUITE_P(, CodeLocationForTESTP, Values(0)); template <typename T> -class CodeLocationForTYPEDTEST : public Test { -}; +class CodeLocationForTYPEDTEST : public Test {}; TYPED_TEST_SUITE(CodeLocationForTYPEDTEST, int); @@ -5409,8 +5306,7 @@ TYPED_TEST(CodeLocationForTYPEDTEST, Verify) { } template <typename T> -class CodeLocationForTYPEDTESTP : public Test { -}; +class CodeLocationForTYPEDTESTP : public Test {}; TYPED_TEST_SUITE_P(CodeLocationForTYPEDTESTP); @@ -5423,6 +5319,7 @@ REGISTER_TYPED_TEST_SUITE_P(CodeLocationForTYPEDTESTP, Verify); INSTANTIATE_TYPED_TEST_SUITE_P(My, CodeLocationForTYPEDTESTP, int); #undef VERIFY_CODE_LOCATION +// clang-format on // Tests setting up and tearing down a test case. // Legacy API is deprecated but still available @@ -5482,9 +5379,7 @@ const char* SetUpTestCaseTest::shared_resource_ = nullptr; TEST_F(SetUpTestCaseTest, Test1) { EXPECT_STRNE(nullptr, shared_resource_); } // Another test that uses the shared resource. -TEST_F(SetUpTestCaseTest, Test2) { - EXPECT_STREQ("123", shared_resource_); -} +TEST_F(SetUpTestCaseTest, Test2) { EXPECT_STREQ("123", shared_resource_); } #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_ // Tests SetupTestSuite/TearDown TestSuite @@ -5797,22 +5692,22 @@ class ParseFlagsTest : public Test { // verifies that the flag values are expected and that the // recognized flags are removed from the command line. template <typename CharType> - static void TestParsingFlags(int argc1, const CharType** argv1, - int argc2, const CharType** argv2, - const Flags& expected, bool should_print_help) { + static void TestParsingFlags(int argc1, const CharType** argv1, int argc2, + const CharType** argv2, const Flags& expected, + bool should_print_help) { const bool saved_help_flag = ::testing::internal::g_help_flag; ::testing::internal::g_help_flag = false; -# if GTEST_HAS_STREAM_REDIRECTION +#if GTEST_HAS_STREAM_REDIRECTION CaptureStdout(); -# endif +#endif // Parses the command line. internal::ParseGoogleTestFlagsOnly(&argc1, const_cast<CharType**>(argv1)); -# if GTEST_HAS_STREAM_REDIRECTION +#if GTEST_HAS_STREAM_REDIRECTION const std::string captured_stdout = GetCapturedStdout(); -# endif +#endif // Verifies the flag values. CheckFlags(expected); @@ -5825,16 +5720,16 @@ class ParseFlagsTest : public Test { // help message for the flags it recognizes. EXPECT_EQ(should_print_help, ::testing::internal::g_help_flag); -# if GTEST_HAS_STREAM_REDIRECTION +#if GTEST_HAS_STREAM_REDIRECTION const char* const expected_help_fragment = "This program contains tests written using"; if (should_print_help) { EXPECT_PRED_FORMAT2(IsSubstring, expected_help_fragment, captured_stdout); } else { - EXPECT_PRED_FORMAT2(IsNotSubstring, - expected_help_fragment, captured_stdout); + EXPECT_PRED_FORMAT2(IsNotSubstring, expected_help_fragment, + captured_stdout); } -# endif // GTEST_HAS_STREAM_REDIRECTION +#endif // GTEST_HAS_STREAM_REDIRECTION ::testing::internal::g_help_flag = saved_help_flag; } @@ -5842,10 +5737,10 @@ class ParseFlagsTest : public Test { // This macro wraps TestParsingFlags s.t. the user doesn't need // to specify the array sizes. -# define GTEST_TEST_PARSING_FLAGS_(argv1, argv2, expected, should_print_help) \ - TestParsingFlags(sizeof(argv1)/sizeof(*argv1) - 1, argv1, \ - sizeof(argv2)/sizeof(*argv2) - 1, argv2, \ - expected, should_print_help) +#define GTEST_TEST_PARSING_FLAGS_(argv1, argv2, expected, should_print_help) \ + TestParsingFlags(sizeof(argv1) / sizeof(*argv1) - 1, argv1, \ + sizeof(argv2) / sizeof(*argv2) - 1, argv2, expected, \ + should_print_help) }; // Tests parsing an empty command line. @@ -6070,8 +5965,8 @@ TEST_F(ParseFlagsTest, OutputXmlDirectory) { const char* argv2[] = {"foo.exe", nullptr}; - GTEST_TEST_PARSING_FLAGS_(argv, argv2, - Flags::Output("xml:directory/path/"), false); + GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Output("xml:directory/path/"), + false); } // Tests having a --gtest_brief flag @@ -6252,8 +6147,8 @@ TEST_F(ParseFlagsTest, StreamResultTo) { const char* argv2[] = {"foo.exe", nullptr}; - GTEST_TEST_PARSING_FLAGS_( - argv, argv2, Flags::StreamResultTo("localhost:1234"), false); + GTEST_TEST_PARSING_FLAGS_(argv, argv2, + Flags::StreamResultTo("localhost:1234"), false); } // Tests parsing --gtest_throw_on_failure. @@ -6284,23 +6179,17 @@ TEST_F(ParseFlagsTest, ThrowOnFailureTrue) { GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::ThrowOnFailure(true), false); } -# if GTEST_OS_WINDOWS +#if GTEST_OS_WINDOWS // Tests parsing wide strings. TEST_F(ParseFlagsTest, WideStrings) { - const wchar_t* argv[] = { - L"foo.exe", - L"--gtest_filter=Foo*", - L"--gtest_list_tests=1", - L"--gtest_break_on_failure", - L"--non_gtest_flag", - NULL - }; + const wchar_t* argv[] = {L"foo.exe", + L"--gtest_filter=Foo*", + L"--gtest_list_tests=1", + L"--gtest_break_on_failure", + L"--non_gtest_flag", + NULL}; - const wchar_t* argv2[] = { - L"foo.exe", - L"--non_gtest_flag", - NULL - }; + const wchar_t* argv2[] = {L"foo.exe", L"--non_gtest_flag", NULL}; Flags expected_flags; expected_flags.break_on_failure = true; @@ -6309,7 +6198,7 @@ TEST_F(ParseFlagsTest, WideStrings) { GTEST_TEST_PARSING_FLAGS_(argv, argv2, expected_flags, false); } -# endif // GTEST_OS_WINDOWS +#endif // GTEST_OS_WINDOWS #if GTEST_USE_OWN_FLAGFILE_FLAG_ class FlagfileTest : public ParseFlagsTest { @@ -6357,8 +6246,8 @@ TEST_F(FlagfileTest, Empty) { // Tests passing a non-empty --gtest_filter flag via --gtest_flagfile. TEST_F(FlagfileTest, FilterNonEmpty) { - internal::FilePath flagfile_path(CreateFlagfile( - "--" GTEST_FLAG_PREFIX_ "filter=abc")); + internal::FilePath flagfile_path( + CreateFlagfile("--" GTEST_FLAG_PREFIX_ "filter=abc")); std::string flagfile_flag = std::string("--" GTEST_FLAG_PREFIX_ "flagfile=") + flagfile_path.c_str(); @@ -6371,10 +6260,10 @@ TEST_F(FlagfileTest, FilterNonEmpty) { // Tests passing several flags via --gtest_flagfile. TEST_F(FlagfileTest, SeveralFlags) { - internal::FilePath flagfile_path(CreateFlagfile( - "--" GTEST_FLAG_PREFIX_ "filter=abc\n" - "--" GTEST_FLAG_PREFIX_ "break_on_failure\n" - "--" GTEST_FLAG_PREFIX_ "list_tests")); + internal::FilePath flagfile_path( + CreateFlagfile("--" GTEST_FLAG_PREFIX_ "filter=abc\n" + "--" GTEST_FLAG_PREFIX_ "break_on_failure\n" + "--" GTEST_FLAG_PREFIX_ "list_tests")); std::string flagfile_flag = std::string("--" GTEST_FLAG_PREFIX_ "flagfile=") + flagfile_path.c_str(); @@ -6398,8 +6287,7 @@ class CurrentTestInfoTest : public Test { // the test case is run. static void SetUpTestSuite() { // There should be no tests running at this point. - const TestInfo* test_info = - UnitTest::GetInstance()->current_test_info(); + const TestInfo* test_info = UnitTest::GetInstance()->current_test_info(); EXPECT_TRUE(test_info == nullptr) << "There should be no tests running at this point."; } @@ -6407,8 +6295,7 @@ class CurrentTestInfoTest : public Test { // Tests that current_test_info() returns NULL after the last test in // the test case has run. static void TearDownTestSuite() { - const TestInfo* test_info = - UnitTest::GetInstance()->current_test_info(); + const TestInfo* test_info = UnitTest::GetInstance()->current_test_info(); EXPECT_TRUE(test_info == nullptr) << "There should be no tests running at this point."; } @@ -6417,8 +6304,7 @@ class CurrentTestInfoTest : public Test { // Tests that current_test_info() returns TestInfo for currently running // test by checking the expected test name against the actual one. TEST_F(CurrentTestInfoTest, WorksForFirstTestInATestSuite) { - const TestInfo* test_info = - UnitTest::GetInstance()->current_test_info(); + const TestInfo* test_info = UnitTest::GetInstance()->current_test_info(); ASSERT_TRUE(nullptr != test_info) << "There is a test running so we should have a valid TestInfo."; EXPECT_STREQ("CurrentTestInfoTest", test_info->test_suite_name()) @@ -6432,8 +6318,7 @@ TEST_F(CurrentTestInfoTest, WorksForFirstTestInATestSuite) { // use this test to see that the TestInfo object actually changed from // the previous invocation. TEST_F(CurrentTestInfoTest, WorksForSecondTestInATestSuite) { - const TestInfo* test_info = - UnitTest::GetInstance()->current_test_info(); + const TestInfo* test_info = UnitTest::GetInstance()->current_test_info(); ASSERT_TRUE(nullptr != test_info) << "There is a test running so we should have a valid TestInfo."; EXPECT_STREQ("CurrentTestInfoTest", test_info->test_suite_name()) @@ -6444,7 +6329,6 @@ TEST_F(CurrentTestInfoTest, WorksForSecondTestInATestSuite) { } // namespace testing - // These two lines test that we can define tests in a namespace that // has the name "testing" and is nested in another namespace. namespace my_namespace { @@ -6493,13 +6377,12 @@ TEST(StreamingAssertionsTest, Unconditional) { SUCCEED() << "expected success"; EXPECT_NONFATAL_FAILURE(ADD_FAILURE() << "expected failure", "expected failure"); - EXPECT_FATAL_FAILURE(FAIL() << "expected failure", - "expected failure"); + EXPECT_FATAL_FAILURE(FAIL() << "expected failure", "expected failure"); } #ifdef __BORLANDC__ // Silences warnings: "Condition is always true", "Unreachable code" -# pragma option push -w-ccc -w-rch +#pragma option push -w-ccc -w-rch #endif TEST(StreamingAssertionsTest, Truth) { @@ -6522,7 +6405,7 @@ TEST(StreamingAssertionsTest, Truth2) { #ifdef __BORLANDC__ // Restores warnings after previous "#pragma option push" suppressed them -# pragma option pop +#pragma option pop #endif TEST(StreamingAssertionsTest, IntegerEquals) { @@ -6593,28 +6476,32 @@ TEST(StreamingAssertionsTest, FloatingPointEquals) { TEST(StreamingAssertionsTest, Throw) { EXPECT_THROW(ThrowAnInteger(), int) << "unexpected failure"; ASSERT_THROW(ThrowAnInteger(), int) << "unexpected failure"; - EXPECT_NONFATAL_FAILURE(EXPECT_THROW(ThrowAnInteger(), bool) << - "expected failure", "expected failure"); - EXPECT_FATAL_FAILURE(ASSERT_THROW(ThrowAnInteger(), bool) << - "expected failure", "expected failure"); + EXPECT_NONFATAL_FAILURE(EXPECT_THROW(ThrowAnInteger(), bool) + << "expected failure", + "expected failure"); + EXPECT_FATAL_FAILURE(ASSERT_THROW(ThrowAnInteger(), bool) + << "expected failure", + "expected failure"); } TEST(StreamingAssertionsTest, NoThrow) { EXPECT_NO_THROW(ThrowNothing()) << "unexpected failure"; ASSERT_NO_THROW(ThrowNothing()) << "unexpected failure"; - EXPECT_NONFATAL_FAILURE(EXPECT_NO_THROW(ThrowAnInteger()) << - "expected failure", "expected failure"); - EXPECT_FATAL_FAILURE(ASSERT_NO_THROW(ThrowAnInteger()) << - "expected failure", "expected failure"); + EXPECT_NONFATAL_FAILURE(EXPECT_NO_THROW(ThrowAnInteger()) + << "expected failure", + "expected failure"); + EXPECT_FATAL_FAILURE(ASSERT_NO_THROW(ThrowAnInteger()) << "expected failure", + "expected failure"); } TEST(StreamingAssertionsTest, AnyThrow) { EXPECT_ANY_THROW(ThrowAnInteger()) << "unexpected failure"; ASSERT_ANY_THROW(ThrowAnInteger()) << "unexpected failure"; - EXPECT_NONFATAL_FAILURE(EXPECT_ANY_THROW(ThrowNothing()) << - "expected failure", "expected failure"); - EXPECT_FATAL_FAILURE(ASSERT_ANY_THROW(ThrowNothing()) << - "expected failure", "expected failure"); + EXPECT_NONFATAL_FAILURE(EXPECT_ANY_THROW(ThrowNothing()) + << "expected failure", + "expected failure"); + EXPECT_FATAL_FAILURE(ASSERT_ANY_THROW(ThrowNothing()) << "expected failure", + "expected failure"); } #endif // GTEST_HAS_EXCEPTIONS @@ -6624,12 +6511,12 @@ TEST(StreamingAssertionsTest, AnyThrow) { TEST(ColoredOutputTest, UsesColorsWhenGTestColorFlagIsYes) { GTEST_FLAG_SET(color, "yes"); - SetEnv("TERM", "xterm"); // TERM supports colors. - EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY. + SetEnv("TERM", "xterm"); // TERM supports colors. + EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY. EXPECT_TRUE(ShouldUseColor(false)); // Stdout is not a TTY. - SetEnv("TERM", "dumb"); // TERM doesn't support colors. - EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY. + SetEnv("TERM", "dumb"); // TERM doesn't support colors. + EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY. EXPECT_TRUE(ShouldUseColor(false)); // Stdout is not a TTY. } @@ -6649,12 +6536,12 @@ TEST(ColoredOutputTest, UsesColorsWhenGTestColorFlagIsAliasOfYes) { TEST(ColoredOutputTest, UsesNoColorWhenGTestColorFlagIsNo) { GTEST_FLAG_SET(color, "no"); - SetEnv("TERM", "xterm"); // TERM supports colors. - EXPECT_FALSE(ShouldUseColor(true)); // Stdout is a TTY. + SetEnv("TERM", "xterm"); // TERM supports colors. + EXPECT_FALSE(ShouldUseColor(true)); // Stdout is a TTY. EXPECT_FALSE(ShouldUseColor(false)); // Stdout is not a TTY. - SetEnv("TERM", "dumb"); // TERM doesn't support colors. - EXPECT_FALSE(ShouldUseColor(true)); // Stdout is a TTY. + SetEnv("TERM", "dumb"); // TERM doesn't support colors. + EXPECT_FALSE(ShouldUseColor(true)); // Stdout is a TTY. EXPECT_FALSE(ShouldUseColor(false)); // Stdout is not a TTY. } @@ -6674,7 +6561,7 @@ TEST(ColoredOutputTest, UsesNoColorWhenGTestColorFlagIsInvalid) { TEST(ColoredOutputTest, UsesColorsWhenStdoutIsTty) { GTEST_FLAG_SET(color, "auto"); - SetEnv("TERM", "xterm"); // TERM supports colors. + SetEnv("TERM", "xterm"); // TERM supports colors. EXPECT_FALSE(ShouldUseColor(false)); // Stdout is not a TTY. EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY. } @@ -6697,49 +6584,49 @@ TEST(ColoredOutputTest, UsesColorsWhenTermSupportsColors) { // On non-Windows platforms, we rely on TERM to determine if the // terminal supports colors. - SetEnv("TERM", "dumb"); // TERM doesn't support colors. + SetEnv("TERM", "dumb"); // TERM doesn't support colors. EXPECT_FALSE(ShouldUseColor(true)); // Stdout is a TTY. - SetEnv("TERM", "emacs"); // TERM doesn't support colors. + SetEnv("TERM", "emacs"); // TERM doesn't support colors. EXPECT_FALSE(ShouldUseColor(true)); // Stdout is a TTY. - SetEnv("TERM", "vt100"); // TERM doesn't support colors. + SetEnv("TERM", "vt100"); // TERM doesn't support colors. EXPECT_FALSE(ShouldUseColor(true)); // Stdout is a TTY. - SetEnv("TERM", "xterm-mono"); // TERM doesn't support colors. + SetEnv("TERM", "xterm-mono"); // TERM doesn't support colors. EXPECT_FALSE(ShouldUseColor(true)); // Stdout is a TTY. - SetEnv("TERM", "xterm"); // TERM supports colors. + SetEnv("TERM", "xterm"); // TERM supports colors. EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY. - SetEnv("TERM", "xterm-color"); // TERM supports colors. + SetEnv("TERM", "xterm-color"); // TERM supports colors. EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY. - SetEnv("TERM", "xterm-256color"); // TERM supports colors. + SetEnv("TERM", "xterm-256color"); // TERM supports colors. EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY. - SetEnv("TERM", "screen"); // TERM supports colors. + SetEnv("TERM", "screen"); // TERM supports colors. EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY. SetEnv("TERM", "screen-256color"); // TERM supports colors. EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY. - SetEnv("TERM", "tmux"); // TERM supports colors. + SetEnv("TERM", "tmux"); // TERM supports colors. EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY. - SetEnv("TERM", "tmux-256color"); // TERM supports colors. + SetEnv("TERM", "tmux-256color"); // TERM supports colors. EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY. - SetEnv("TERM", "rxvt-unicode"); // TERM supports colors. + SetEnv("TERM", "rxvt-unicode"); // TERM supports colors. EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY. SetEnv("TERM", "rxvt-unicode-256color"); // TERM supports colors. - EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY. + EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY. - SetEnv("TERM", "linux"); // TERM supports colors. + SetEnv("TERM", "linux"); // TERM supports colors. EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY. - SetEnv("TERM", "cygwin"); // TERM supports colors. + SetEnv("TERM", "cygwin"); // TERM supports colors. EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY. #endif // GTEST_OS_WINDOWS } @@ -6859,12 +6746,10 @@ class TestListener : public EmptyTestEventListener { public: TestListener() : on_start_counter_(nullptr), is_destroyed_(nullptr) {} TestListener(int* on_start_counter, bool* is_destroyed) - : on_start_counter_(on_start_counter), - is_destroyed_(is_destroyed) {} + : on_start_counter_(on_start_counter), is_destroyed_(is_destroyed) {} ~TestListener() override { - if (is_destroyed_) - *is_destroyed_ = true; + if (is_destroyed_) *is_destroyed_ = true; } protected: @@ -6921,8 +6806,8 @@ TEST(TestEventListenersTest, Append) { { TestEventListeners listeners; listeners.Append(listener); - TestEventListenersAccessor::GetRepeater(&listeners)->OnTestProgramStart( - *UnitTest::GetInstance()); + TestEventListenersAccessor::GetRepeater(&listeners) + ->OnTestProgramStart(*UnitTest::GetInstance()); EXPECT_EQ(1, on_start_counter); } EXPECT_TRUE(is_destroyed); @@ -6975,32 +6860,32 @@ TEST(EventListenerTest, AppendKeepsOrder) { listeners.Append(new SequenceTestingListener(&vec, "2nd")); listeners.Append(new SequenceTestingListener(&vec, "3rd")); - TestEventListenersAccessor::GetRepeater(&listeners)->OnTestProgramStart( - *UnitTest::GetInstance()); + TestEventListenersAccessor::GetRepeater(&listeners) + ->OnTestProgramStart(*UnitTest::GetInstance()); ASSERT_EQ(3U, vec.size()); EXPECT_STREQ("1st.OnTestProgramStart", vec[0].c_str()); EXPECT_STREQ("2nd.OnTestProgramStart", vec[1].c_str()); EXPECT_STREQ("3rd.OnTestProgramStart", vec[2].c_str()); vec.clear(); - TestEventListenersAccessor::GetRepeater(&listeners)->OnTestProgramEnd( - *UnitTest::GetInstance()); + TestEventListenersAccessor::GetRepeater(&listeners) + ->OnTestProgramEnd(*UnitTest::GetInstance()); ASSERT_EQ(3U, vec.size()); EXPECT_STREQ("3rd.OnTestProgramEnd", vec[0].c_str()); EXPECT_STREQ("2nd.OnTestProgramEnd", vec[1].c_str()); EXPECT_STREQ("1st.OnTestProgramEnd", vec[2].c_str()); vec.clear(); - TestEventListenersAccessor::GetRepeater(&listeners)->OnTestIterationStart( - *UnitTest::GetInstance(), 0); + TestEventListenersAccessor::GetRepeater(&listeners) + ->OnTestIterationStart(*UnitTest::GetInstance(), 0); ASSERT_EQ(3U, vec.size()); EXPECT_STREQ("1st.OnTestIterationStart", vec[0].c_str()); EXPECT_STREQ("2nd.OnTestIterationStart", vec[1].c_str()); EXPECT_STREQ("3rd.OnTestIterationStart", vec[2].c_str()); vec.clear(); - TestEventListenersAccessor::GetRepeater(&listeners)->OnTestIterationEnd( - *UnitTest::GetInstance(), 0); + TestEventListenersAccessor::GetRepeater(&listeners) + ->OnTestIterationEnd(*UnitTest::GetInstance(), 0); ASSERT_EQ(3U, vec.size()); EXPECT_STREQ("3rd.OnTestIterationEnd", vec[0].c_str()); EXPECT_STREQ("2nd.OnTestIterationEnd", vec[1].c_str()); @@ -7020,8 +6905,8 @@ TEST(TestEventListenersTest, Release) { TestEventListeners listeners; listeners.Append(listener); EXPECT_EQ(listener, listeners.Release(listener)); - TestEventListenersAccessor::GetRepeater(&listeners)->OnTestProgramStart( - *UnitTest::GetInstance()); + TestEventListenersAccessor::GetRepeater(&listeners) + ->OnTestProgramStart(*UnitTest::GetInstance()); EXPECT_TRUE(listeners.Release(listener) == nullptr); } EXPECT_EQ(0, on_start_counter); @@ -7039,17 +6924,20 @@ TEST(EventListenerTest, SuppressEventForwarding) { ASSERT_TRUE(TestEventListenersAccessor::EventForwardingEnabled(listeners)); TestEventListenersAccessor::SuppressEventForwarding(&listeners); ASSERT_FALSE(TestEventListenersAccessor::EventForwardingEnabled(listeners)); - TestEventListenersAccessor::GetRepeater(&listeners)->OnTestProgramStart( - *UnitTest::GetInstance()); + TestEventListenersAccessor::GetRepeater(&listeners) + ->OnTestProgramStart(*UnitTest::GetInstance()); EXPECT_EQ(0, on_start_counter); } // Tests that events generated by Google Test are not forwarded in // death test subprocesses. TEST(EventListenerDeathTest, EventsNotForwardedInDeathTestSubprecesses) { - EXPECT_DEATH_IF_SUPPORTED({ - GTEST_CHECK_(TestEventListenersAccessor::EventForwardingEnabled( - *GetUnitTestImpl()->listeners())) << "expected failure";}, + EXPECT_DEATH_IF_SUPPORTED( + { + GTEST_CHECK_(TestEventListenersAccessor::EventForwardingEnabled( + *GetUnitTestImpl()->listeners())) + << "expected failure"; + }, "expected failure"); } @@ -7066,8 +6954,8 @@ TEST(EventListenerTest, default_result_printer) { EXPECT_EQ(listener, listeners.default_result_printer()); - TestEventListenersAccessor::GetRepeater(&listeners)->OnTestProgramStart( - *UnitTest::GetInstance()); + TestEventListenersAccessor::GetRepeater(&listeners) + ->OnTestProgramStart(*UnitTest::GetInstance()); EXPECT_EQ(1, on_start_counter); @@ -7080,8 +6968,8 @@ TEST(EventListenerTest, default_result_printer) { // After broadcasting an event the counter is still the same, indicating // the listener is not in the list anymore. - TestEventListenersAccessor::GetRepeater(&listeners)->OnTestProgramStart( - *UnitTest::GetInstance()); + TestEventListenersAccessor::GetRepeater(&listeners) + ->OnTestProgramStart(*UnitTest::GetInstance()); EXPECT_EQ(1, on_start_counter); } @@ -7103,8 +6991,8 @@ TEST(EventListenerTest, RemovingDefaultResultPrinterWorks) { EXPECT_FALSE(is_destroyed); // Broadcasting events now should not affect default_result_printer. - TestEventListenersAccessor::GetRepeater(&listeners)->OnTestProgramStart( - *UnitTest::GetInstance()); + TestEventListenersAccessor::GetRepeater(&listeners) + ->OnTestProgramStart(*UnitTest::GetInstance()); EXPECT_EQ(0, on_start_counter); } // Destroying the list should not affect the listener now, too. @@ -7125,8 +7013,8 @@ TEST(EventListenerTest, default_xml_generator) { EXPECT_EQ(listener, listeners.default_xml_generator()); - TestEventListenersAccessor::GetRepeater(&listeners)->OnTestProgramStart( - *UnitTest::GetInstance()); + TestEventListenersAccessor::GetRepeater(&listeners) + ->OnTestProgramStart(*UnitTest::GetInstance()); EXPECT_EQ(1, on_start_counter); @@ -7139,8 +7027,8 @@ TEST(EventListenerTest, default_xml_generator) { // After broadcasting an event the counter is still the same, indicating // the listener is not in the list anymore. - TestEventListenersAccessor::GetRepeater(&listeners)->OnTestProgramStart( - *UnitTest::GetInstance()); + TestEventListenersAccessor::GetRepeater(&listeners) + ->OnTestProgramStart(*UnitTest::GetInstance()); EXPECT_EQ(1, on_start_counter); } @@ -7162,8 +7050,8 @@ TEST(EventListenerTest, RemovingDefaultXmlGeneratorWorks) { EXPECT_FALSE(is_destroyed); // Broadcasting events now should not affect default_xml_generator. - TestEventListenersAccessor::GetRepeater(&listeners)->OnTestProgramStart( - *UnitTest::GetInstance()); + TestEventListenersAccessor::GetRepeater(&listeners) + ->OnTestProgramStart(*UnitTest::GetInstance()); EXPECT_EQ(0, on_start_counter); } // Destroying the list should not affect the listener now, too. @@ -7323,7 +7211,6 @@ TEST(GTestReferenceToConstTest, Works) { TestGTestReferenceToConst<const std::string&, const std::string&>(); } - // Tests IsContainerTest. class NonContainer {}; @@ -7335,10 +7222,9 @@ TEST(IsContainerTestTest, WorksForNonContainer) { } TEST(IsContainerTestTest, WorksForContainer) { + EXPECT_EQ(sizeof(IsContainer), sizeof(IsContainerTest<std::vector<bool>>(0))); EXPECT_EQ(sizeof(IsContainer), - sizeof(IsContainerTest<std::vector<bool> >(0))); - EXPECT_EQ(sizeof(IsContainer), - sizeof(IsContainerTest<std::map<int, double> >(0))); + sizeof(IsContainerTest<std::map<int, double>>(0))); } struct ConstOnlyContainerWithPointerIterator { @@ -7387,8 +7273,8 @@ TEST(ArrayEqTest, WorksForDegeneratedArrays) { TEST(ArrayEqTest, WorksForOneDimensionalArrays) { // Note that a and b are distinct but compatible types. - const int a[] = { 0, 1 }; - long b[] = { 0, 1 }; + const int a[] = {0, 1}; + long b[] = {0, 1}; EXPECT_TRUE(ArrayEq(a, b)); EXPECT_TRUE(ArrayEq(a, 2, b)); @@ -7398,9 +7284,9 @@ TEST(ArrayEqTest, WorksForOneDimensionalArrays) { } TEST(ArrayEqTest, WorksForTwoDimensionalArrays) { - const char a[][3] = { "hi", "lo" }; - const char b[][3] = { "hi", "lo" }; - const char c[][3] = { "hi", "li" }; + const char a[][3] = {"hi", "lo"}; + const char b[][3] = {"hi", "lo"}; + const char c[][3] = {"hi", "li"}; EXPECT_TRUE(ArrayEq(a, b)); EXPECT_TRUE(ArrayEq(a, 2, b)); @@ -7418,11 +7304,11 @@ TEST(ArrayAwareFindTest, WorksForOneDimensionalArray) { } TEST(ArrayAwareFindTest, WorksForTwoDimensionalArray) { - int a[][2] = { { 0, 1 }, { 2, 3 }, { 4, 5 } }; - const int b[2] = { 2, 3 }; + int a[][2] = {{0, 1}, {2, 3}, {4, 5}}; + const int b[2] = {2, 3}; EXPECT_EQ(a + 1, ArrayAwareFind(a, a + 3, b)); - const int c[2] = { 6, 7 }; + const int c[2] = {6, 7}; EXPECT_EQ(a + 3, ArrayAwareFind(a, a + 3, c)); } @@ -7448,7 +7334,7 @@ TEST(CopyArrayTest, WorksForOneDimensionalArrays) { } TEST(CopyArrayTest, WorksForTwoDimensionalArrays) { - const int a[2][3] = { { 0, 1, 2 }, { 3, 4, 5 } }; + const int a[2][3] = {{0, 1, 2}, {3, 4, 5}}; int b[2][3]; #ifndef __BORLANDC__ // C++Builder cannot compile some array size deductions. CopyArray(a, &b); @@ -7463,7 +7349,7 @@ TEST(CopyArrayTest, WorksForTwoDimensionalArrays) { // Tests NativeArray. TEST(NativeArrayTest, ConstructorFromArrayWorks) { - const int a[3] = { 0, 1, 2 }; + const int a[3] = {0, 1, 2}; NativeArray<int> na(a, 3, RelationToSourceReference()); EXPECT_EQ(3U, na.size()); EXPECT_EQ(a, na.begin()); @@ -7493,7 +7379,7 @@ TEST(NativeArrayTest, TypeMembersAreCorrect) { } TEST(NativeArrayTest, MethodsWork) { - const int a[3] = { 0, 1, 2 }; + const int a[3] = {0, 1, 2}; NativeArray<int> na(a, 3, RelationToSourceCopy()); ASSERT_EQ(3U, na.size()); EXPECT_EQ(3, na.end() - na.begin()); @@ -7512,14 +7398,14 @@ TEST(NativeArrayTest, MethodsWork) { NativeArray<int> na2(a, 3, RelationToSourceReference()); EXPECT_TRUE(na == na2); - const int b1[3] = { 0, 1, 1 }; - const int b2[4] = { 0, 1, 2, 3 }; + const int b1[3] = {0, 1, 1}; + const int b2[4] = {0, 1, 2, 3}; EXPECT_FALSE(na == NativeArray<int>(b1, 3, RelationToSourceReference())); EXPECT_FALSE(na == NativeArray<int>(b2, 4, RelationToSourceCopy())); } TEST(NativeArrayTest, WorksForTwoDimensionalArray) { - const char a[2][3] = { "hi", "lo" }; + const char a[2][3] = {"hi", "lo"}; NativeArray<char[3]> na(a, 2, RelationToSourceReference()); ASSERT_EQ(2U, na.size()); EXPECT_EQ(a, na.begin()); diff --git a/googletest/test/gtest_xml_outfiles_test.py b/googletest/test/gtest_xml_outfiles_test.py index 916bdf4..c129e64 100755 --- a/googletest/test/gtest_xml_outfiles_test.py +++ b/googletest/test/gtest_xml_outfiles_test.py @@ -43,7 +43,7 @@ GTEST_OUTPUT_2_TEST = "gtest_xml_outfile2_test_" EXPECTED_XML_1 = """<?xml version="1.0" encoding="UTF-8"?> <testsuites tests="1" failures="0" disabled="0" errors="0" time="*" timestamp="*" name="AllTests"> <testsuite name="PropertyOne" tests="1" failures="0" skipped="0" disabled="0" errors="0" time="*" timestamp="*"> - <testcase name="TestSomeProperties" status="run" result="completed" time="*" timestamp="*" classname="PropertyOne"> + <testcase name="TestSomeProperties" file="gtest_xml_outfile1_test_.cc" line="41" status="run" result="completed" time="*" timestamp="*" classname="PropertyOne"> <properties> <property name="SetUpProp" value="1"/> <property name="TestSomeProperty" value="1"/> @@ -57,7 +57,7 @@ EXPECTED_XML_1 = """<?xml version="1.0" encoding="UTF-8"?> EXPECTED_XML_2 = """<?xml version="1.0" encoding="UTF-8"?> <testsuites tests="1" failures="0" disabled="0" errors="0" time="*" timestamp="*" name="AllTests"> <testsuite name="PropertyTwo" tests="1" failures="0" skipped="0" disabled="0" errors="0" time="*" timestamp="*"> - <testcase name="TestSomeProperties" status="run" result="completed" time="*" timestamp="*" classname="PropertyTwo"> + <testcase name="TestSomeProperties" file="gtest_xml_outfile2_test_.cc" line="41" status="run" result="completed" time="*" timestamp="*" classname="PropertyTwo"> <properties> <property name="SetUpProp" value="2"/> <property name="TestSomeProperty" value="2"/> diff --git a/googletest/test/gtest_xml_output_unittest.py b/googletest/test/gtest_xml_output_unittest.py index f0b0c3b..e1b7f1f 100755 --- a/googletest/test/gtest_xml_output_unittest.py +++ b/googletest/test/gtest_xml_output_unittest.py @@ -67,10 +67,10 @@ else: EXPECTED_NON_EMPTY_XML = """<?xml version="1.0" encoding="UTF-8"?> <testsuites tests="26" failures="5" disabled="2" errors="0" time="*" timestamp="*" name="AllTests" ad_hoc_property="42"> <testsuite name="SuccessfulTest" tests="1" failures="0" disabled="0" skipped="0" errors="0" time="*" timestamp="*"> - <testcase name="Succeeds" status="run" result="completed" time="*" timestamp="*" classname="SuccessfulTest"/> + <testcase name="Succeeds" file="gtest_xml_output_unittest_.cc" line="51" status="run" result="completed" time="*" timestamp="*" classname="SuccessfulTest"/> </testsuite> <testsuite name="FailedTest" tests="1" failures="1" disabled="0" skipped="0" errors="0" time="*" timestamp="*"> - <testcase name="Fails" status="run" result="completed" time="*" timestamp="*" classname="FailedTest"> + <testcase name="Fails" file="gtest_xml_output_unittest_.cc" line="59" status="run" result="completed" time="*" timestamp="*" classname="FailedTest"> <failure message="gtest_xml_output_unittest_.cc:*
Expected equality of these values:
 1
 2" type=""><![CDATA[gtest_xml_output_unittest_.cc:* Expected equality of these values: 1 @@ -78,8 +78,8 @@ Expected equality of these values: </testcase> </testsuite> <testsuite name="MixedResultTest" tests="3" failures="1" disabled="1" skipped="0" errors="0" time="*" timestamp="*"> - <testcase name="Succeeds" status="run" result="completed" time="*" timestamp="*" classname="MixedResultTest"/> - <testcase name="Fails" status="run" result="completed" time="*" timestamp="*" classname="MixedResultTest"> + <testcase name="Succeeds" file="gtest_xml_output_unittest_.cc" line="86" status="run" result="completed" time="*" timestamp="*" classname="MixedResultTest"/> + <testcase name="Fails" file="gtest_xml_output_unittest_.cc" line="91" status="run" result="completed" time="*" timestamp="*" classname="MixedResultTest"> <failure message="gtest_xml_output_unittest_.cc:*
Expected equality of these values:
 1
 2" type=""><![CDATA[gtest_xml_output_unittest_.cc:* Expected equality of these values: 1 @@ -89,35 +89,35 @@ Expected equality of these values: 2 3%(stack)s]]></failure> </testcase> - <testcase name="DISABLED_test" status="notrun" result="suppressed" time="*" timestamp="*" classname="MixedResultTest"/> + <testcase name="DISABLED_test" file="gtest_xml_output_unittest_.cc" line="96" status="notrun" result="suppressed" time="*" timestamp="*" classname="MixedResultTest"/> </testsuite> <testsuite name="XmlQuotingTest" tests="1" failures="1" disabled="0" skipped="0" errors="0" time="*" timestamp="*"> - <testcase name="OutputsCData" status="run" result="completed" time="*" timestamp="*" classname="XmlQuotingTest"> + <testcase name="OutputsCData" file="gtest_xml_output_unittest_.cc" line="100" status="run" result="completed" time="*" timestamp="*" classname="XmlQuotingTest"> <failure message="gtest_xml_output_unittest_.cc:*
Failed
XML output: <?xml encoding="utf-8"><top><![CDATA[cdata text]]></top>" type=""><![CDATA[gtest_xml_output_unittest_.cc:* Failed XML output: <?xml encoding="utf-8"><top><![CDATA[cdata text]]>]]><![CDATA[</top>%(stack)s]]></failure> </testcase> </testsuite> <testsuite name="InvalidCharactersTest" tests="1" failures="1" disabled="0" skipped="0" errors="0" time="*" timestamp="*"> - <testcase name="InvalidCharactersInMessage" status="run" result="completed" time="*" timestamp="*" classname="InvalidCharactersTest"> + <testcase name="InvalidCharactersInMessage" file="gtest_xml_output_unittest_.cc" line="107" status="run" result="completed" time="*" timestamp="*" classname="InvalidCharactersTest"> <failure message="gtest_xml_output_unittest_.cc:*
Failed
Invalid characters in brackets []" type=""><![CDATA[gtest_xml_output_unittest_.cc:* Failed Invalid characters in brackets []%(stack)s]]></failure> </testcase> </testsuite> <testsuite name="DisabledTest" tests="1" failures="0" disabled="1" skipped="0" errors="0" time="*" timestamp="*"> - <testcase name="DISABLED_test_not_run" status="notrun" result="suppressed" time="*" timestamp="*" classname="DisabledTest"/> + <testcase name="DISABLED_test_not_run" file="gtest_xml_output_unittest_.cc" line="66" status="notrun" result="suppressed" time="*" timestamp="*" classname="DisabledTest"/> </testsuite> <testsuite name="SkippedTest" tests="3" failures="1" disabled="0" skipped="2" errors="0" time="*" timestamp="*"> - <testcase name="Skipped" status="run" result="skipped" time="*" timestamp="*" classname="SkippedTest"> + <testcase name="Skipped" status="run" file="gtest_xml_output_unittest_.cc" line="73" result="skipped" time="*" timestamp="*" classname="SkippedTest"> <skipped message="gtest_xml_output_unittest_.cc:*
"><![CDATA[gtest_xml_output_unittest_.cc:* %(stack)s]]></skipped> </testcase> - <testcase name="SkippedWithMessage" status="run" result="skipped" time="*" timestamp="*" classname="SkippedTest"> + <testcase name="SkippedWithMessage" file="gtest_xml_output_unittest_.cc" line="77" status="run" result="skipped" time="*" timestamp="*" classname="SkippedTest"> <skipped message="gtest_xml_output_unittest_.cc:*
It is good practice to tell why you skip a test."><![CDATA[gtest_xml_output_unittest_.cc:* It is good practice to tell why you skip a test.%(stack)s]]></skipped> </testcase> - <testcase name="SkippedAfterFailure" status="run" result="completed" time="*" timestamp="*" classname="SkippedTest"> + <testcase name="SkippedAfterFailure" file="gtest_xml_output_unittest_.cc" line="81" status="run" result="completed" time="*" timestamp="*" classname="SkippedTest"> <failure message="gtest_xml_output_unittest_.cc:*
Expected equality of these values:
 1
 2" type=""><![CDATA[gtest_xml_output_unittest_.cc:* Expected equality of these values: 1 @@ -128,63 +128,63 @@ It is good practice to tell why you skip a test.%(stack)s]]></skipped> </testsuite> <testsuite name="PropertyRecordingTest" tests="4" failures="0" disabled="0" skipped="0" errors="0" time="*" timestamp="*" SetUpTestSuite="yes" TearDownTestSuite="aye"> - <testcase name="OneProperty" status="run" result="completed" time="*" timestamp="*" classname="PropertyRecordingTest"> + <testcase name="OneProperty" file="gtest_xml_output_unittest_.cc" line="119" status="run" result="completed" time="*" timestamp="*" classname="PropertyRecordingTest"> <properties> <property name="key_1" value="1"/> </properties> </testcase> - <testcase name="IntValuedProperty" status="run" result="completed" time="*" timestamp="*" classname="PropertyRecordingTest"> + <testcase name="IntValuedProperty" file="gtest_xml_output_unittest_.cc" line="123" status="run" result="completed" time="*" timestamp="*" classname="PropertyRecordingTest"> <properties> <property name="key_int" value="1"/> </properties> </testcase> - <testcase name="ThreeProperties" status="run" result="completed" time="*" timestamp="*" classname="PropertyRecordingTest"> + <testcase name="ThreeProperties" file="gtest_xml_output_unittest_.cc" line="127" status="run" result="completed" time="*" timestamp="*" classname="PropertyRecordingTest"> <properties> <property name="key_1" value="1"/> <property name="key_2" value="2"/> <property name="key_3" value="3"/> </properties> </testcase> - <testcase name="TwoValuesForOneKeyUsesLastValue" status="run" result="completed" time="*" timestamp="*" classname="PropertyRecordingTest"> + <testcase name="TwoValuesForOneKeyUsesLastValue" file="gtest_xml_output_unittest_.cc" line="133" status="run" result="completed" time="*" timestamp="*" classname="PropertyRecordingTest"> <properties> <property name="key_1" value="2"/> </properties> </testcase> </testsuite> <testsuite name="NoFixtureTest" tests="3" failures="0" disabled="0" skipped="0" errors="0" time="*" timestamp="*"> - <testcase name="RecordProperty" status="run" result="completed" time="*" timestamp="*" classname="NoFixtureTest"> + <testcase name="RecordProperty" file="gtest_xml_output_unittest_.cc" line="138" status="run" result="completed" time="*" timestamp="*" classname="NoFixtureTest"> <properties> <property name="key" value="1"/> </properties> </testcase> - <testcase name="ExternalUtilityThatCallsRecordIntValuedProperty" status="run" result="completed" time="*" timestamp="*" classname="NoFixtureTest"> + <testcase name="ExternalUtilityThatCallsRecordIntValuedProperty" file="gtest_xml_output_unittest_.cc" line="151" status="run" result="completed" time="*" timestamp="*" classname="NoFixtureTest"> <properties> <property name="key_for_utility_int" value="1"/> </properties> </testcase> - <testcase name="ExternalUtilityThatCallsRecordStringValuedProperty" status="run" result="completed" time="*" timestamp="*" classname="NoFixtureTest"> + <testcase name="ExternalUtilityThatCallsRecordStringValuedProperty" file="gtest_xml_output_unittest_.cc" line="155" status="run" result="completed" time="*" timestamp="*" classname="NoFixtureTest"> <properties> <property name="key_for_utility_string" value="1"/> </properties> </testcase> </testsuite> <testsuite name="Single/ValueParamTest" tests="4" failures="0" disabled="0" skipped="0" errors="0" time="*" timestamp="*"> - <testcase name="HasValueParamAttribute/0" value_param="33" status="run" result="completed" time="*" timestamp="*" classname="Single/ValueParamTest" /> - <testcase name="HasValueParamAttribute/1" value_param="42" status="run" result="completed" time="*" timestamp="*" classname="Single/ValueParamTest" /> - <testcase name="AnotherTestThatHasValueParamAttribute/0" value_param="33" status="run" result="completed" time="*" timestamp="*" classname="Single/ValueParamTest" /> - <testcase name="AnotherTestThatHasValueParamAttribute/1" value_param="42" status="run" result="completed" time="*" timestamp="*" classname="Single/ValueParamTest" /> + <testcase name="HasValueParamAttribute/0" file="gtest_xml_output_unittest_.cc" line="162" value_param="33" status="run" result="completed" time="*" timestamp="*" classname="Single/ValueParamTest" /> + <testcase name="HasValueParamAttribute/1" file="gtest_xml_output_unittest_.cc" line="162" value_param="42" status="run" result="completed" time="*" timestamp="*" classname="Single/ValueParamTest" /> + <testcase name="AnotherTestThatHasValueParamAttribute/0" file="gtest_xml_output_unittest_.cc" line="163" value_param="33" status="run" result="completed" time="*" timestamp="*" classname="Single/ValueParamTest" /> + <testcase name="AnotherTestThatHasValueParamAttribute/1" file="gtest_xml_output_unittest_.cc" line="163" value_param="42" status="run" result="completed" time="*" timestamp="*" classname="Single/ValueParamTest" /> </testsuite> <testsuite name="TypedTest/0" tests="1" failures="0" disabled="0" skipped="0" errors="0" time="*" timestamp="*"> - <testcase name="HasTypeParamAttribute" type_param="*" status="run" result="completed" time="*" timestamp="*" classname="TypedTest/0" /> + <testcase name="HasTypeParamAttribute" file="gtest_xml_output_unittest_.cc" line="171" type_param="*" status="run" result="completed" time="*" timestamp="*" classname="TypedTest/0" /> </testsuite> <testsuite name="TypedTest/1" tests="1" failures="0" disabled="0" skipped="0" errors="0" time="*" timestamp="*"> - <testcase name="HasTypeParamAttribute" type_param="*" status="run" result="completed" time="*" timestamp="*" classname="TypedTest/1" /> + <testcase name="HasTypeParamAttribute" file="gtest_xml_output_unittest_.cc" line="171" type_param="*" status="run" result="completed" time="*" timestamp="*" classname="TypedTest/1" /> </testsuite> <testsuite name="Single/TypeParameterizedTestSuite/0" tests="1" failures="0" disabled="0" skipped="0" errors="0" time="*" timestamp="*"> - <testcase name="HasTypeParamAttribute" type_param="*" status="run" result="completed" time="*" timestamp="*" classname="Single/TypeParameterizedTestSuite/0" /> + <testcase name="HasTypeParamAttribute" file="gtest_xml_output_unittest_.cc" line="178" type_param="*" status="run" result="completed" time="*" timestamp="*" classname="Single/TypeParameterizedTestSuite/0" /> </testsuite> <testsuite name="Single/TypeParameterizedTestSuite/1" tests="1" failures="0" disabled="0" skipped="0" errors="0" time="*" timestamp="*"> - <testcase name="HasTypeParamAttribute" type_param="*" status="run" result="completed" time="*" timestamp="*" classname="Single/TypeParameterizedTestSuite/1" /> + <testcase name="HasTypeParamAttribute" file="gtest_xml_output_unittest_.cc" line="178" type_param="*" status="run" result="completed" time="*" timestamp="*" classname="Single/TypeParameterizedTestSuite/1" /> </testsuite> </testsuites>""" % { 'stack': STACK_TRACE_TEMPLATE @@ -195,24 +195,24 @@ EXPECTED_FILTERED_TEST_XML = """<?xml version="1.0" encoding="UTF-8"?> timestamp="*" name="AllTests" ad_hoc_property="42"> <testsuite name="SuccessfulTest" tests="1" failures="0" disabled="0" skipped="0" errors="0" time="*" timestamp="*"> - <testcase name="Succeeds" status="run" result="completed" time="*" timestamp="*" classname="SuccessfulTest"/> + <testcase name="Succeeds" file="gtest_xml_output_unittest_.cc" line="51" status="run" result="completed" time="*" timestamp="*" classname="SuccessfulTest"/> </testsuite> </testsuites>""" EXPECTED_SHARDED_TEST_XML = """<?xml version="1.0" encoding="UTF-8"?> <testsuites tests="3" failures="0" disabled="0" errors="0" time="*" timestamp="*" name="AllTests" ad_hoc_property="42"> <testsuite name="SuccessfulTest" tests="1" failures="0" disabled="0" skipped="0" errors="0" time="*" timestamp="*"> - <testcase name="Succeeds" status="run" result="completed" time="*" timestamp="*" classname="SuccessfulTest"/> + <testcase name="Succeeds" file="gtest_xml_output_unittest_.cc" line="51" status="run" result="completed" time="*" timestamp="*" classname="SuccessfulTest"/> </testsuite> <testsuite name="PropertyRecordingTest" tests="1" failures="0" disabled="0" skipped="0" errors="0" time="*" timestamp="*" SetUpTestSuite="yes" TearDownTestSuite="aye"> - <testcase name="IntValuedProperty" status="run" result="completed" time="*" timestamp="*" classname="PropertyRecordingTest"> + <testcase name="IntValuedProperty" file="gtest_xml_output_unittest_.cc" line="123" status="run" result="completed" time="*" timestamp="*" classname="PropertyRecordingTest"> <properties> <property name="key_int" value="1"/> </properties> </testcase> </testsuite> <testsuite name="Single/ValueParamTest" tests="1" failures="0" disabled="0" skipped="0" errors="0" time="*" timestamp="*"> - <testcase name="HasValueParamAttribute/0" value_param="33" status="run" result="completed" time="*" timestamp="*" classname="Single/ValueParamTest" /> + <testcase name="HasValueParamAttribute/0" file="gtest_xml_output_unittest_.cc" line="162" value_param="33" status="run" result="completed" time="*" timestamp="*" classname="Single/ValueParamTest" /> </testsuite> </testsuites>""" diff --git a/googletest/test/gtest_xml_output_unittest_.cc b/googletest/test/gtest_xml_output_unittest_.cc index c0036aa..4bdb0c7 100644 --- a/googletest/test/gtest_xml_output_unittest_.cc +++ b/googletest/test/gtest_xml_output_unittest_.cc @@ -35,18 +35,18 @@ // // This program will be invoked from a Python unit test. Don't run it // directly. +// clang-format off #include "gtest/gtest.h" using ::testing::InitGoogleTest; +using ::testing::Test; using ::testing::TestEventListeners; using ::testing::TestWithParam; using ::testing::UnitTest; -using ::testing::Test; using ::testing::Values; -class SuccessfulTest : public Test { -}; +class SuccessfulTest : public Test {}; TEST_F(SuccessfulTest, Succeeds) { SUCCEED() << "This is a success."; @@ -191,3 +191,5 @@ int main(int argc, char** argv) { testing::Test::RecordProperty("ad_hoc_property", "42"); return RUN_ALL_TESTS(); } + +// clang-format on diff --git a/googletest/test/gtest_xml_test_utils.py b/googletest/test/gtest_xml_test_utils.py index 50c6e7d..c6fb9f4 100755 --- a/googletest/test/gtest_xml_test_utils.py +++ b/googletest/test/gtest_xml_test_utils.py @@ -170,6 +170,10 @@ class GTestXMLTestCase(gtest_test_utils.TestCase): * The stack traces are removed. """ + if element.tagName == 'testcase': + source_file = element.getAttributeNode('file') + if source_file: + source_file.value = re.sub(r'^.*[/\\](.*)', '\\1', source_file.value) if element.tagName in ('testsuites', 'testsuite', 'testcase'): timestamp = element.getAttributeNode('timestamp') timestamp.value = re.sub(r'^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d\.\d\d\d$', diff --git a/googletest/test/production.h b/googletest/test/production.h index 41a5472..4dec8d4 100644 --- a/googletest/test/production.h +++ b/googletest/test/production.h @@ -46,6 +46,7 @@ class PrivateCode { PrivateCode(); int x() const { return x_; } + private: void set_x(int an_x) { x_ = an_x; } int x_; |