Running clang-format over all of GoogleTest

A few tests are examining code locations and looking af the resulting line
numbers to verify that GoogleTest shows those to users correctly. Some of those
locations change when clang-format is run. For those locations, I've wrapped
portions in:
// clang-format off
...
// clang-format on

There may be other locations that are currently not tickled by running
clang-format.

PiperOrigin-RevId: 434844712
Change-Id: I3a9f0a6f39eff741c576b6de389bef9b1d11139d
This commit is contained in:
Abseil Team 2022-03-15 13:41:41 -07:00 committed by Copybara-Service
parent 8a422b8398
commit b007c54f29
126 changed files with 5799 additions and 7083 deletions

View File

@ -131,7 +131,7 @@
#define GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_ACTIONS_H_ #define GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_ACTIONS_H_
#ifndef _WIN32_WCE #ifndef _WIN32_WCE
# include <errno.h> #include <errno.h>
#endif #endif
#include <algorithm> #include <algorithm>
@ -147,8 +147,8 @@
#include "gmock/internal/gmock-pp.h" #include "gmock/internal/gmock-pp.h"
#ifdef _MSC_VER #ifdef _MSC_VER
# pragma warning(push) #pragma warning(push)
# pragma warning(disable:4100) #pragma warning(disable : 4100)
#endif #endif
namespace testing { namespace testing {
@ -196,9 +196,7 @@ class BuiltInDefaultValue {
public: public:
// This function returns true if and only if type T has a built-in default // This function returns true if and only if type T has a built-in default
// value. // value.
static bool Exists() { static bool Exists() { return ::std::is_default_constructible<T>::value; }
return ::std::is_default_constructible<T>::value;
}
static T Get() { static T Get() {
return BuiltInDefaultValueGetter< return BuiltInDefaultValueGetter<
@ -227,11 +225,11 @@ class BuiltInDefaultValue<T*> {
// The following specializations define the default values for // The following specializations define the default values for
// specific types we care about. // specific types we care about.
#define GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(type, value) \ #define GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(type, value) \
template <> \ template <> \
class BuiltInDefaultValue<type> { \ class BuiltInDefaultValue<type> { \
public: \ public: \
static bool Exists() { return true; } \ static bool Exists() { return true; } \
static type Get() { return value; } \ static type Get() { return value; } \
} }
GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(void, ); // NOLINT 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_(signed short, 0); // NOLINT
GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(unsigned int, 0U); 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_(signed int, 0);
GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(unsigned long, 0UL); // 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_(signed long, 0L); // NOLINT
GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(unsigned long long, 0); // 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_(float, 0);
GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(double, 0); GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(double, 0);
@ -839,7 +837,7 @@ class ReturnRoundRobinAction {
template <typename... Args> template <typename... Args>
T operator()(Args&&...) const { T operator()(Args&&...) const {
return state_->Next(); return state_->Next();
} }
private: private:
@ -862,7 +860,9 @@ class DoDefaultAction {
// This template type conversion operator allows DoDefault() to be // This template type conversion operator allows DoDefault() to be
// used in any function. // used in any function.
template <typename F> 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 // Implements the Assign action to set a given pointer referent to a
@ -890,8 +890,7 @@ template <typename T>
class SetErrnoAndReturnAction { class SetErrnoAndReturnAction {
public: public:
SetErrnoAndReturnAction(int errno_value, T result) SetErrnoAndReturnAction(int errno_value, T result)
: errno_(errno_value), : errno_(errno_value), result_(result) {}
result_(result) {}
template <typename Result, typename ArgumentTuple> template <typename Result, typename ArgumentTuple>
Result Perform(const ArgumentTuple& /* args */) const { Result Perform(const ArgumentTuple& /* args */) const {
errno = errno_; errno = errno_;
@ -1002,8 +1001,8 @@ class IgnoreResultAction {
private: private:
// Type OriginalFunction is the same as F except that its return // Type OriginalFunction is the same as F except that its return
// type is IgnoredValue. // type is IgnoredValue.
typedef typename internal::Function<F>::MakeResultIgnoredValue typedef
OriginalFunction; typename internal::Function<F>::MakeResultIgnoredValue OriginalFunction;
const Action<OriginalFunction> action_; const Action<OriginalFunction> action_;
}; };
@ -1020,12 +1019,12 @@ struct WithArgsAction {
template <typename R, typename... Args> template <typename R, typename... Args>
operator Action<R(Args...)>() const { // NOLINT operator Action<R(Args...)>() const { // NOLINT
using TupleType = std::tuple<Args...>; using TupleType = std::tuple<Args...>;
Action<R(typename std::tuple_element<I, TupleType>::type...)> Action<R(typename std::tuple_element<I, TupleType>::type...)> converted(
converted(action); action);
return [converted](Args... args) -> R { return [converted](Args... args) -> R {
return converted.Perform(std::forward_as_tuple( 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 // multiple arguments. For convenience, we also provide
// WithArgs<k>(an_action) (defined below) as a synonym. // WithArgs<k>(an_action) (defined below) as a synonym.
template <size_t k, typename InnerAction> template <size_t k, typename InnerAction>
internal::WithArgsAction<typename std::decay<InnerAction>::type, k> internal::WithArgsAction<typename std::decay<InnerAction>::type, k> WithArg(
WithArg(InnerAction&& action) { InnerAction&& action) {
return {std::forward<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. In other words, it adapts an action accepting no
// argument to one that accepts (and ignores) arguments. // argument to one that accepts (and ignores) arguments.
template <typename InnerAction> template <typename InnerAction>
internal::WithArgsAction<typename std::decay<InnerAction>::type> internal::WithArgsAction<typename std::decay<InnerAction>::type> WithoutArgs(
WithoutArgs(InnerAction&& action) { InnerAction&& action) {
return {std::forward<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. // Creates an action that sets a pointer referent to a given value.
template <typename T1, typename T2> 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)); 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. // Creates an action that sets errno and returns the appropriate error.
template <typename T> template <typename T>
PolymorphicAction<internal::SetErrnoAndReturnAction<T> > PolymorphicAction<internal::SetErrnoAndReturnAction<T>> SetErrnoAndReturn(
SetErrnoAndReturn(int errval, T result) { int errval, T result) {
return MakePolymorphicAction( return MakePolymorphicAction(
internal::SetErrnoAndReturnAction<T>(errval, result)); internal::SetErrnoAndReturnAction<T>(errval, result));
} }
@ -1482,7 +1481,8 @@ struct ExcessiveArg {};
// Builds an implementation of an Action<> for some particular signature, using // Builds an implementation of an Action<> for some particular signature, using
// a class defined by an ACTION* macro. // a class defined by an ACTION* macro.
template <typename F, typename Impl> struct ActionImpl; template <typename F, typename Impl>
struct ActionImpl;
template <typename Impl> template <typename Impl>
struct ImplBase { struct ImplBase {
@ -1502,7 +1502,7 @@ struct ActionImpl<R(Args...), Impl> : ImplBase<Impl>::type {
using args_type = std::tuple<Args...>; using args_type = std::tuple<Args...>;
ActionImpl() = default; // Only defined if appropriate for Base. 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 { R operator()(Args&&... arg) const {
static constexpr size_t kMaxArgs = 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 // args_type get passed, followed by a dummy of unspecified type for the
// remainder up to 10 explicit args. // remainder up to 10 explicit args.
static constexpr ExcessiveArg kExcessArg{}; static constexpr ExcessiveArg kExcessArg{};
return static_cast<const Impl&>(*this).template gmock_PerformImpl< return static_cast<const Impl&>(*this)
/*function_type=*/function_type, /*return_type=*/R, .template gmock_PerformImpl<
/*args_type=*/args_type, /*function_type=*/function_type, /*return_type=*/R,
/*argN_type=*/typename std::tuple_element<arg_id, args_type>::type...>( /*args_type=*/args_type,
/*args=*/args, std::get<arg_id>(args)..., /*argN_type=*/
((void)excess_id, kExcessArg)...); 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) \ #define GMOCK_INTERNAL_ARG_UNUSED(i, data, el) \
, const arg##i##_type& arg##i GTEST_ATTRIBUTE_UNUSED_ , 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( \ const args_type& args GTEST_ATTRIBUTE_UNUSED_ GMOCK_PP_REPEAT( \
GMOCK_INTERNAL_ARG_UNUSED, , 10) GMOCK_INTERNAL_ARG_UNUSED, , 10)
@ -1584,45 +1586,47 @@ template <typename F, typename Impl>
#define GMOCK_ACTION_FIELD_PARAMS_(params) \ #define GMOCK_ACTION_FIELD_PARAMS_(params) \
GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_FIELD_PARAM, , params) GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_FIELD_PARAM, , params)
#define GMOCK_INTERNAL_ACTION(name, full_name, params) \ #define GMOCK_INTERNAL_ACTION(name, full_name, params) \
template <GMOCK_ACTION_TYPENAME_PARAMS_(params)> \ template <GMOCK_ACTION_TYPENAME_PARAMS_(params)> \
class full_name { \ class full_name { \
public: \ public: \
explicit full_name(GMOCK_ACTION_TYPE_GVALUE_PARAMS_(params)) \ explicit full_name(GMOCK_ACTION_TYPE_GVALUE_PARAMS_(params)) \
: impl_(std::make_shared<gmock_Impl>( \ : impl_(std::make_shared<gmock_Impl>( \
GMOCK_ACTION_GVALUE_PARAMS_(params))) { } \ GMOCK_ACTION_GVALUE_PARAMS_(params))) {} \
full_name(const full_name&) = default; \ full_name(const full_name&) = default; \
full_name(full_name&&) noexcept = default; \ full_name(full_name&&) noexcept = default; \
template <typename F> \ template <typename F> \
operator ::testing::Action<F>() const { \ operator ::testing::Action<F>() const { \
return ::testing::internal::MakeAction<F>(impl_); \ return ::testing::internal::MakeAction<F>(impl_); \
} \ } \
private: \ \
class gmock_Impl { \ private: \
public: \ class gmock_Impl { \
explicit gmock_Impl(GMOCK_ACTION_TYPE_GVALUE_PARAMS_(params)) \ public: \
: GMOCK_ACTION_INIT_PARAMS_(params) {} \ explicit gmock_Impl(GMOCK_ACTION_TYPE_GVALUE_PARAMS_(params)) \
template <typename function_type, typename return_type, \ : GMOCK_ACTION_INIT_PARAMS_(params) {} \
typename args_type, GMOCK_ACTION_TEMPLATE_ARGS_NAMES_> \ template <typename function_type, typename return_type, \
return_type gmock_PerformImpl(GMOCK_ACTION_ARG_TYPES_AND_NAMES_) const; \ typename args_type, GMOCK_ACTION_TEMPLATE_ARGS_NAMES_> \
GMOCK_ACTION_FIELD_PARAMS_(params) \ return_type gmock_PerformImpl(GMOCK_ACTION_ARG_TYPES_AND_NAMES_) const; \
}; \ GMOCK_ACTION_FIELD_PARAMS_(params) \
std::shared_ptr<const gmock_Impl> impl_; \ }; \
}; \ std::shared_ptr<const gmock_Impl> impl_; \
template <GMOCK_ACTION_TYPENAME_PARAMS_(params)> \ }; \
inline full_name<GMOCK_ACTION_TYPE_PARAMS_(params)> name( \ template <GMOCK_ACTION_TYPENAME_PARAMS_(params)> \
GMOCK_ACTION_TYPE_GVALUE_PARAMS_(params)) GTEST_MUST_USE_RESULT_; \ inline full_name<GMOCK_ACTION_TYPE_PARAMS_(params)> name( \
template <GMOCK_ACTION_TYPENAME_PARAMS_(params)> \ GMOCK_ACTION_TYPE_GVALUE_PARAMS_(params)) GTEST_MUST_USE_RESULT_; \
inline full_name<GMOCK_ACTION_TYPE_PARAMS_(params)> name( \ template <GMOCK_ACTION_TYPENAME_PARAMS_(params)> \
GMOCK_ACTION_TYPE_GVALUE_PARAMS_(params)) { \ inline full_name<GMOCK_ACTION_TYPE_PARAMS_(params)> name( \
return full_name<GMOCK_ACTION_TYPE_PARAMS_(params)>( \ GMOCK_ACTION_TYPE_GVALUE_PARAMS_(params)) { \
GMOCK_ACTION_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, \ template <GMOCK_ACTION_TYPENAME_PARAMS_(params)> \
GMOCK_ACTION_TEMPLATE_ARGS_NAMES_> \ template <typename function_type, typename return_type, typename args_type, \
return_type full_name<GMOCK_ACTION_TYPE_PARAMS_(params)>::gmock_Impl:: \ GMOCK_ACTION_TEMPLATE_ARGS_NAMES_> \
gmock_PerformImpl(GMOCK_ACTION_ARG_TYPES_AND_NAMES_UNUSED_) const return_type \
full_name<GMOCK_ACTION_TYPE_PARAMS_(params)>::gmock_Impl::gmock_PerformImpl( \
GMOCK_ACTION_ARG_TYPES_AND_NAMES_UNUSED_) const
} // namespace internal } // namespace internal
@ -1630,12 +1634,13 @@ template <typename F, typename Impl>
#define ACTION(name) \ #define ACTION(name) \
class name##Action { \ class name##Action { \
public: \ public: \
explicit name##Action() noexcept {} \ explicit name##Action() noexcept {} \
name##Action(const name##Action&) noexcept {} \ name##Action(const name##Action&) noexcept {} \
template <typename F> \ template <typename F> \
operator ::testing::Action<F>() const { \ operator ::testing::Action<F>() const { \
return ::testing::internal::MakeAction<F, gmock_Impl>(); \ return ::testing::internal::MakeAction<F, gmock_Impl>(); \
} \ } \
\
private: \ private: \
class gmock_Impl { \ class gmock_Impl { \
public: \ public: \
@ -1684,7 +1689,7 @@ template <typename F, typename Impl>
} // namespace testing } // namespace testing
#ifdef _MSC_VER #ifdef _MSC_VER
# pragma warning(pop) #pragma warning(pop)
#endif #endif
#endif // GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_ACTIONS_H_ #endif // GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_ACTIONS_H_

View File

@ -40,8 +40,10 @@
#define GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_CARDINALITIES_H_ #define GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_CARDINALITIES_H_
#include <limits.h> #include <limits.h>
#include <memory> #include <memory>
#include <ostream> // NOLINT #include <ostream> // NOLINT
#include "gmock/internal/gmock-port.h" #include "gmock/internal/gmock-port.h"
#include "gtest/gtest.h" #include "gtest/gtest.h"
@ -116,7 +118,7 @@ class GTEST_API_ Cardinality {
// cardinality, i.e. exceed the maximum number of allowed calls. // cardinality, i.e. exceed the maximum number of allowed calls.
bool IsOverSaturatedByCallCount(int call_count) const { bool IsOverSaturatedByCallCount(int call_count) const {
return impl_->IsSaturatedByCallCount(call_count) && return impl_->IsSaturatedByCallCount(call_count) &&
!impl_->IsSatisfiedByCallCount(call_count); !impl_->IsSatisfiedByCallCount(call_count);
} }
// Describes self to an ostream // Describes self to an ostream

View File

@ -201,7 +201,7 @@ using internal::FunctionMocker;
GMOCK_INTERNAL_A_MATCHER_ARGUMENT, _Signature, _N)); \ GMOCK_INTERNAL_A_MATCHER_ARGUMENT, _Signature, _N)); \
} \ } \
mutable ::testing::FunctionMocker<GMOCK_PP_REMOVE_PARENS(_Signature)> \ mutable ::testing::FunctionMocker<GMOCK_PP_REMOVE_PARENS(_Signature)> \
GMOCK_MOCKER_(_N, _Constness, _MethodName) GMOCK_MOCKER_(_N, _Constness, _MethodName)
#define GMOCK_INTERNAL_EXPAND(...) __VA_ARGS__ #define GMOCK_INTERNAL_EXPAND(...) __VA_ARGS__

View File

@ -129,170 +129,207 @@
// Declares the template parameters. // Declares the template parameters.
#define GMOCK_INTERNAL_DECL_HAS_1_TEMPLATE_PARAMS(kind0, name0) kind0 name0 #define GMOCK_INTERNAL_DECL_HAS_1_TEMPLATE_PARAMS(kind0, name0) kind0 name0
#define GMOCK_INTERNAL_DECL_HAS_2_TEMPLATE_PARAMS(kind0, name0, kind1, \ #define GMOCK_INTERNAL_DECL_HAS_2_TEMPLATE_PARAMS(kind0, name0, kind1, name1) \
name1) kind0 name0, kind1 name1 kind0 name0, kind1 name1
#define GMOCK_INTERNAL_DECL_HAS_3_TEMPLATE_PARAMS(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, \ #define GMOCK_INTERNAL_DECL_HAS_4_TEMPLATE_PARAMS(kind0, name0, kind1, name1, \
kind2, name2, kind3, name3) kind0 name0, kind1 name1, kind2 name2, \ kind2, name2, kind3, name3) \
kind3 name3 kind0 name0, kind1 name1, kind2 name2, kind3 name3
#define GMOCK_INTERNAL_DECL_HAS_5_TEMPLATE_PARAMS(kind0, name0, kind1, name1, \ #define GMOCK_INTERNAL_DECL_HAS_5_TEMPLATE_PARAMS( \
kind2, name2, kind3, name3, kind4, name4) kind0 name0, kind1 name1, \ kind0, name0, kind1, name1, kind2, name2, kind3, name3, kind4, name4) \
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, \ #define GMOCK_INTERNAL_DECL_HAS_6_TEMPLATE_PARAMS(kind0, name0, kind1, name1, \
kind2, name2, kind3, name3, kind4, name4, kind5, name5) kind0 name0, \ kind2, name2, kind3, name3, \
kind1 name1, kind2 name2, kind3 name3, kind4 name4, kind5 name5 kind4, name4, kind5, name5) \
#define GMOCK_INTERNAL_DECL_HAS_7_TEMPLATE_PARAMS(kind0, name0, kind1, name1, \ kind0 name0, kind1 name1, kind2 name2, kind3 name3, kind4 name4, kind5 name5
kind2, name2, kind3, name3, kind4, name4, kind5, name5, kind6, \ #define GMOCK_INTERNAL_DECL_HAS_7_TEMPLATE_PARAMS( \
name6) kind0 name0, kind1 name1, kind2 name2, kind3 name3, kind4 name4, \ kind0, name0, kind1, name1, kind2, name2, kind3, name3, kind4, name4, \
kind5 name5, kind6 name6 kind5, name5, kind6, name6) \
#define GMOCK_INTERNAL_DECL_HAS_8_TEMPLATE_PARAMS(kind0, name0, kind1, name1, \ kind0 name0, kind1 name1, kind2 name2, kind3 name3, kind4 name4, \
kind2, name2, kind3, name3, kind4, name4, kind5, name5, kind6, name6, \ kind5 name5, kind6 name6
kind7, name7) kind0 name0, kind1 name1, kind2 name2, kind3 name3, \ #define GMOCK_INTERNAL_DECL_HAS_8_TEMPLATE_PARAMS( \
kind4 name4, kind5 name5, kind6 name6, kind7 name7 kind0, name0, kind1, name1, kind2, name2, kind3, name3, kind4, name4, \
#define GMOCK_INTERNAL_DECL_HAS_9_TEMPLATE_PARAMS(kind0, name0, kind1, name1, \ kind5, name5, kind6, name6, kind7, name7) \
kind2, name2, kind3, name3, kind4, name4, kind5, name5, kind6, name6, \ kind0 name0, kind1 name1, kind2 name2, kind3 name3, kind4 name4, \
kind7, name7, kind8, name8) kind0 name0, kind1 name1, kind2 name2, \ kind5 name5, kind6 name6, kind7 name7
kind3 name3, kind4 name4, kind5 name5, kind6 name6, kind7 name7, \ #define GMOCK_INTERNAL_DECL_HAS_9_TEMPLATE_PARAMS( \
kind8 name8 kind0, name0, kind1, name1, kind2, name2, kind3, name3, kind4, name4, \
#define GMOCK_INTERNAL_DECL_HAS_10_TEMPLATE_PARAMS(kind0, name0, kind1, \ kind5, name5, kind6, name6, kind7, name7, kind8, name8) \
name1, kind2, name2, kind3, name3, kind4, name4, kind5, name5, kind6, \ kind0 name0, kind1 name1, kind2 name2, kind3 name3, kind4 name4, \
name6, kind7, name7, kind8, name8, kind9, name9) kind0 name0, \ kind5 name5, kind6 name6, kind7 name7, kind8 name8
kind1 name1, kind2 name2, kind3 name3, kind4 name4, kind5 name5, \ #define GMOCK_INTERNAL_DECL_HAS_10_TEMPLATE_PARAMS( \
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) \
kind0 name0, kind1 name1, kind2 name2, kind3 name3, kind4 name4, \
kind5 name5, kind6 name6, kind7 name7, kind8 name8, kind9 name9
// Lists the template parameters. // Lists the template parameters.
#define GMOCK_INTERNAL_LIST_HAS_1_TEMPLATE_PARAMS(kind0, name0) name0 #define GMOCK_INTERNAL_LIST_HAS_1_TEMPLATE_PARAMS(kind0, name0) name0
#define GMOCK_INTERNAL_LIST_HAS_2_TEMPLATE_PARAMS(kind0, name0, kind1, \ #define GMOCK_INTERNAL_LIST_HAS_2_TEMPLATE_PARAMS(kind0, name0, kind1, name1) \
name1) name0, name1 name0, name1
#define GMOCK_INTERNAL_LIST_HAS_3_TEMPLATE_PARAMS(kind0, name0, kind1, 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, \ #define GMOCK_INTERNAL_LIST_HAS_4_TEMPLATE_PARAMS(kind0, name0, kind1, name1, \
kind2, name2, kind3, name3) name0, name1, name2, name3 kind2, name2, kind3, name3) \
#define GMOCK_INTERNAL_LIST_HAS_5_TEMPLATE_PARAMS(kind0, name0, kind1, name1, \ name0, name1, name2, name3
kind2, name2, kind3, name3, kind4, name4) name0, name1, name2, name3, \ #define GMOCK_INTERNAL_LIST_HAS_5_TEMPLATE_PARAMS( \
name4 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, \ #define GMOCK_INTERNAL_LIST_HAS_6_TEMPLATE_PARAMS(kind0, name0, kind1, name1, \
kind2, name2, kind3, name3, kind4, name4, kind5, name5) name0, name1, \ kind2, name2, kind3, name3, \
name2, name3, name4, name5 kind4, name4, kind5, name5) \
#define GMOCK_INTERNAL_LIST_HAS_7_TEMPLATE_PARAMS(kind0, name0, kind1, name1, \ name0, name1, name2, name3, name4, name5
kind2, name2, kind3, name3, kind4, name4, kind5, name5, kind6, \ #define GMOCK_INTERNAL_LIST_HAS_7_TEMPLATE_PARAMS( \
name6) name0, name1, name2, name3, name4, name5, name6 kind0, name0, kind1, name1, kind2, name2, kind3, name3, kind4, name4, \
#define GMOCK_INTERNAL_LIST_HAS_8_TEMPLATE_PARAMS(kind0, name0, kind1, name1, \ kind5, name5, kind6, name6) \
kind2, name2, kind3, name3, kind4, name4, kind5, name5, kind6, name6, \ name0, name1, name2, name3, name4, name5, name6
kind7, name7) name0, name1, name2, name3, name4, name5, name6, name7 #define GMOCK_INTERNAL_LIST_HAS_8_TEMPLATE_PARAMS( \
#define GMOCK_INTERNAL_LIST_HAS_9_TEMPLATE_PARAMS(kind0, name0, kind1, name1, \ kind0, name0, kind1, name1, kind2, name2, kind3, name3, kind4, name4, \
kind2, name2, kind3, name3, kind4, name4, kind5, name5, kind6, name6, \ kind5, name5, kind6, name6, kind7, name7) \
kind7, name7, kind8, name8) name0, name1, name2, name3, name4, name5, \ name0, name1, name2, name3, name4, name5, name6, name7
name6, name7, name8 #define GMOCK_INTERNAL_LIST_HAS_9_TEMPLATE_PARAMS( \
#define GMOCK_INTERNAL_LIST_HAS_10_TEMPLATE_PARAMS(kind0, name0, kind1, \ kind0, name0, kind1, name1, kind2, name2, kind3, name3, kind4, name4, \
name1, kind2, name2, kind3, name3, kind4, name4, kind5, name5, kind6, \ kind5, name5, kind6, name6, kind7, name7, kind8, name8) \
name6, kind7, name7, kind8, name8, kind9, name9) name0, name1, name2, \ name0, name1, name2, name3, name4, name5, name6, name7, name8
name3, name4, name5, name6, name7, name8, name9 #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. // Declares the types of value parameters.
#define GMOCK_INTERNAL_DECL_TYPE_AND_0_VALUE_PARAMS() #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_1_VALUE_PARAMS(p0) , typename p0##_type
#define GMOCK_INTERNAL_DECL_TYPE_AND_2_VALUE_PARAMS(p0, p1) , \ #define GMOCK_INTERNAL_DECL_TYPE_AND_2_VALUE_PARAMS(p0, p1) \
typename p0##_type, typename p1##_type , typename p0##_type, typename p1##_type
#define GMOCK_INTERNAL_DECL_TYPE_AND_3_VALUE_PARAMS(p0, p1, p2) , \ #define GMOCK_INTERNAL_DECL_TYPE_AND_3_VALUE_PARAMS(p0, p1, p2) \
typename p0##_type, typename p1##_type, typename p2##_type , typename p0##_type, typename p1##_type, typename p2##_type
#define GMOCK_INTERNAL_DECL_TYPE_AND_4_VALUE_PARAMS(p0, p1, p2, p3) , \ #define GMOCK_INTERNAL_DECL_TYPE_AND_4_VALUE_PARAMS(p0, p1, p2, p3) \
typename p0##_type, typename p1##_type, typename p2##_type, \ , typename p0##_type, typename p1##_type, typename p2##_type, \
typename p3##_type typename p3##_type
#define GMOCK_INTERNAL_DECL_TYPE_AND_5_VALUE_PARAMS(p0, p1, p2, p3, p4) , \ #define GMOCK_INTERNAL_DECL_TYPE_AND_5_VALUE_PARAMS(p0, p1, p2, p3, p4) \
typename p0##_type, typename p1##_type, typename p2##_type, \ , typename p0##_type, typename p1##_type, typename p2##_type, \
typename p3##_type, typename p4##_type typename p3##_type, typename p4##_type
#define GMOCK_INTERNAL_DECL_TYPE_AND_6_VALUE_PARAMS(p0, p1, p2, p3, p4, p5) , \ #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 p0##_type, typename p1##_type, typename p2##_type, \
typename p3##_type, typename p4##_type, typename p5##_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, \ #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, \ p6) \
typename p3##_type, typename p4##_type, typename p5##_type, \ , typename p0##_type, typename p1##_type, typename p2##_type, \
typename p6##_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, \ #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, \ p6, p7) \
typename p3##_type, typename p4##_type, typename p5##_type, \ , typename p0##_type, typename p1##_type, typename p2##_type, \
typename p6##_type, typename p7##_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, \ #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, \ p6, p7, p8) \
typename p3##_type, typename p4##_type, typename p5##_type, \ , typename p0##_type, typename p1##_type, typename p2##_type, \
typename p6##_type, typename p7##_type, typename p8##_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, \ #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, \ p6, p7, p8, p9) \
typename p2##_type, typename p3##_type, typename p4##_type, \ , typename p0##_type, typename p1##_type, typename p2##_type, \
typename p5##_type, typename p6##_type, typename p7##_type, \ typename p3##_type, typename p4##_type, typename p5##_type, \
typename p8##_type, typename p9##_type typename p6##_type, typename p7##_type, typename p8##_type, \
typename p9##_type
// Initializes the value parameters. // Initializes the value parameters.
#define GMOCK_INTERNAL_INIT_AND_0_VALUE_PARAMS()\ #define GMOCK_INTERNAL_INIT_AND_0_VALUE_PARAMS() ()
() #define GMOCK_INTERNAL_INIT_AND_1_VALUE_PARAMS(p0) \
#define GMOCK_INTERNAL_INIT_AND_1_VALUE_PARAMS(p0)\ (p0##_type gmock_p0) : p0(::std::move(gmock_p0))
(p0##_type gmock_p0) : p0(::std::move(gmock_p0)) #define GMOCK_INTERNAL_INIT_AND_2_VALUE_PARAMS(p0, p1) \
#define GMOCK_INTERNAL_INIT_AND_2_VALUE_PARAMS(p0, p1)\ (p0##_type gmock_p0, p1##_type gmock_p1) \
(p0##_type gmock_p0, p1##_type gmock_p1) : p0(::std::move(gmock_p0)), \ : p0(::std::move(gmock_p0)), p1(::std::move(gmock_p1))
p1(::std::move(gmock_p1)) #define GMOCK_INTERNAL_INIT_AND_3_VALUE_PARAMS(p0, p1, p2) \
#define GMOCK_INTERNAL_INIT_AND_3_VALUE_PARAMS(p0, p1, p2)\ (p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2) \
(p0##_type gmock_p0, p1##_type gmock_p1, \ : p0(::std::move(gmock_p0)), \
p2##_type gmock_p2) : p0(::std::move(gmock_p0)), \ p1(::std::move(gmock_p1)), \
p1(::std::move(gmock_p1)), p2(::std::move(gmock_p2)) p2(::std::move(gmock_p2))
#define GMOCK_INTERNAL_INIT_AND_4_VALUE_PARAMS(p0, p1, p2, p3)\ #define GMOCK_INTERNAL_INIT_AND_4_VALUE_PARAMS(p0, p1, p2, p3) \
(p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \ (p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \
p3##_type gmock_p3) : p0(::std::move(gmock_p0)), \ p3##_type gmock_p3) \
p1(::std::move(gmock_p1)), p2(::std::move(gmock_p2)), \ : p0(::std::move(gmock_p0)), \
p1(::std::move(gmock_p1)), \
p2(::std::move(gmock_p2)), \
p3(::std::move(gmock_p3)) p3(::std::move(gmock_p3))
#define GMOCK_INTERNAL_INIT_AND_5_VALUE_PARAMS(p0, p1, p2, p3, 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, \ (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)), \ p3##_type gmock_p3, p4##_type gmock_p4) \
p1(::std::move(gmock_p1)), p2(::std::move(gmock_p2)), \ : p0(::std::move(gmock_p0)), \
p3(::std::move(gmock_p3)), p4(::std::move(gmock_p4)) p1(::std::move(gmock_p1)), \
#define GMOCK_INTERNAL_INIT_AND_6_VALUE_PARAMS(p0, p1, p2, p3, p4, p5)\ p2(::std::move(gmock_p2)), \
(p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \ p3(::std::move(gmock_p3)), \
p3##_type gmock_p3, p4##_type gmock_p4, \ p4(::std::move(gmock_p4))
p5##_type gmock_p5) : p0(::std::move(gmock_p0)), \ #define GMOCK_INTERNAL_INIT_AND_6_VALUE_PARAMS(p0, p1, p2, p3, p4, p5) \
p1(::std::move(gmock_p1)), p2(::std::move(gmock_p2)), \ (p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \
p3(::std::move(gmock_p3)), p4(::std::move(gmock_p4)), \ 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)) p5(::std::move(gmock_p5))
#define GMOCK_INTERNAL_INIT_AND_7_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, 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, \ (p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \
p3##_type gmock_p3, p4##_type gmock_p4, p5##_type gmock_p5, \ p3##_type gmock_p3, p4##_type gmock_p4, p5##_type gmock_p5, \
p6##_type gmock_p6) : p0(::std::move(gmock_p0)), \ p6##_type gmock_p6) \
p1(::std::move(gmock_p1)), p2(::std::move(gmock_p2)), \ : p0(::std::move(gmock_p0)), \
p3(::std::move(gmock_p3)), p4(::std::move(gmock_p4)), \ p1(::std::move(gmock_p1)), \
p5(::std::move(gmock_p5)), p6(::std::move(gmock_p6)) p2(::std::move(gmock_p2)), \
#define GMOCK_INTERNAL_INIT_AND_8_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, p7)\ p3(::std::move(gmock_p3)), \
(p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \ p4(::std::move(gmock_p4)), \
p3##_type gmock_p3, p4##_type gmock_p4, p5##_type gmock_p5, \ p5(::std::move(gmock_p5)), \
p6##_type gmock_p6, p7##_type gmock_p7) : p0(::std::move(gmock_p0)), \ p6(::std::move(gmock_p6))
p1(::std::move(gmock_p1)), p2(::std::move(gmock_p2)), \ #define GMOCK_INTERNAL_INIT_AND_8_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, p7) \
p3(::std::move(gmock_p3)), p4(::std::move(gmock_p4)), \ (p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \
p5(::std::move(gmock_p5)), p6(::std::move(gmock_p6)), \ 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)) p7(::std::move(gmock_p7))
#define GMOCK_INTERNAL_INIT_AND_9_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, \ #define GMOCK_INTERNAL_INIT_AND_9_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, p7, \
p7, p8)\ p8) \
(p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \ (p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \
p3##_type gmock_p3, p4##_type gmock_p4, p5##_type gmock_p5, \ p3##_type gmock_p3, p4##_type gmock_p4, p5##_type gmock_p5, \
p6##_type gmock_p6, p7##_type gmock_p7, \ p6##_type gmock_p6, p7##_type gmock_p7, p8##_type gmock_p8) \
p8##_type gmock_p8) : p0(::std::move(gmock_p0)), \ : p0(::std::move(gmock_p0)), \
p1(::std::move(gmock_p1)), p2(::std::move(gmock_p2)), \ p1(::std::move(gmock_p1)), \
p3(::std::move(gmock_p3)), p4(::std::move(gmock_p4)), \ p2(::std::move(gmock_p2)), \
p5(::std::move(gmock_p5)), p6(::std::move(gmock_p6)), \ p3(::std::move(gmock_p3)), \
p7(::std::move(gmock_p7)), p8(::std::move(gmock_p8)) 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, \ #define GMOCK_INTERNAL_INIT_AND_10_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, \
p7, p8, p9)\ p7, p8, p9) \
(p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \ (p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \
p3##_type gmock_p3, p4##_type gmock_p4, p5##_type gmock_p5, \ p3##_type gmock_p3, p4##_type gmock_p4, p5##_type gmock_p5, \
p6##_type gmock_p6, p7##_type gmock_p7, p8##_type gmock_p8, \ p6##_type gmock_p6, p7##_type gmock_p7, p8##_type gmock_p8, \
p9##_type gmock_p9) : p0(::std::move(gmock_p0)), \ p9##_type gmock_p9) \
p1(::std::move(gmock_p1)), p2(::std::move(gmock_p2)), \ : p0(::std::move(gmock_p0)), \
p3(::std::move(gmock_p3)), p4(::std::move(gmock_p4)), \ p1(::std::move(gmock_p1)), \
p5(::std::move(gmock_p5)), p6(::std::move(gmock_p6)), \ p2(::std::move(gmock_p2)), \
p7(::std::move(gmock_p7)), p8(::std::move(gmock_p8)), \ 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)) p9(::std::move(gmock_p9))
// Defines the copy constructor // Defines the copy constructor
#define GMOCK_INTERNAL_DEFN_COPY_AND_0_VALUE_PARAMS() \ #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_1_VALUE_PARAMS(...) = default;
#define GMOCK_INTERNAL_DEFN_COPY_AND_2_VALUE_PARAMS(...) = default; #define GMOCK_INTERNAL_DEFN_COPY_AND_2_VALUE_PARAMS(...) = default;
#define GMOCK_INTERNAL_DEFN_COPY_AND_3_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. // Declares the fields for storing the value parameters.
#define GMOCK_INTERNAL_DEFN_AND_0_VALUE_PARAMS() #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_1_VALUE_PARAMS(p0) p0##_type p0;
#define GMOCK_INTERNAL_DEFN_AND_2_VALUE_PARAMS(p0, p1) p0##_type p0; \ #define GMOCK_INTERNAL_DEFN_AND_2_VALUE_PARAMS(p0, p1) \
p1##_type p1; p0##_type p0; \
#define GMOCK_INTERNAL_DEFN_AND_3_VALUE_PARAMS(p0, p1, p2) p0##_type p0; \ p1##_type p1;
p1##_type p1; p2##_type p2; #define GMOCK_INTERNAL_DEFN_AND_3_VALUE_PARAMS(p0, p1, p2) \
#define GMOCK_INTERNAL_DEFN_AND_4_VALUE_PARAMS(p0, p1, p2, p3) p0##_type p0; \ p0##_type p0; \
p1##_type p1; p2##_type p2; p3##_type p3; p1##_type p1; \
#define GMOCK_INTERNAL_DEFN_AND_5_VALUE_PARAMS(p0, p1, p2, p3, \ p2##_type p2;
p4) p0##_type p0; p1##_type p1; p2##_type p2; p3##_type p3; p4##_type p4; #define GMOCK_INTERNAL_DEFN_AND_4_VALUE_PARAMS(p0, p1, p2, p3) \
#define GMOCK_INTERNAL_DEFN_AND_6_VALUE_PARAMS(p0, p1, p2, p3, p4, \ p0##_type p0; \
p5) p0##_type p0; p1##_type p1; p2##_type p2; p3##_type p3; p4##_type p4; \ p1##_type p1; \
p5##_type p5; p2##_type p2; \
#define GMOCK_INTERNAL_DEFN_AND_7_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, \ p3##_type p3;
p6) p0##_type p0; p1##_type p1; p2##_type p2; p3##_type p3; p4##_type p4; \ #define GMOCK_INTERNAL_DEFN_AND_5_VALUE_PARAMS(p0, p1, p2, p3, p4) \
p5##_type p5; p6##_type p6; p0##_type p0; \
#define GMOCK_INTERNAL_DEFN_AND_8_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, \ p1##_type p1; \
p7) p0##_type p0; p1##_type p1; p2##_type p2; p3##_type p3; p4##_type p4; \ p2##_type p2; \
p5##_type p5; p6##_type p6; p7##_type p7; p3##_type p3; \
#define GMOCK_INTERNAL_DEFN_AND_9_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, \ p4##_type p4;
p7, p8) p0##_type p0; p1##_type p1; p2##_type p2; p3##_type p3; \ #define GMOCK_INTERNAL_DEFN_AND_6_VALUE_PARAMS(p0, p1, p2, p3, p4, p5) \
p4##_type p4; p5##_type p5; p6##_type p6; p7##_type p7; p8##_type p8; 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, \ #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; \ p7, p8, p9) \
p4##_type p4; p5##_type p5; p6##_type p6; p7##_type p7; p8##_type p8; \ p0##_type p0; \
p9##_type p9; 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. // Lists the value parameters.
#define GMOCK_INTERNAL_LIST_AND_0_VALUE_PARAMS() #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_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_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_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, \ #define GMOCK_INTERNAL_LIST_AND_5_VALUE_PARAMS(p0, p1, p2, p3, p4) \
p2, p3, p4 p0, p1, p2, p3, p4
#define GMOCK_INTERNAL_LIST_AND_6_VALUE_PARAMS(p0, p1, p2, p3, p4, p5) p0, \ #define GMOCK_INTERNAL_LIST_AND_6_VALUE_PARAMS(p0, p1, p2, p3, p4, p5) \
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, \ #define GMOCK_INTERNAL_LIST_AND_7_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6) \
p6) 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, \ #define GMOCK_INTERNAL_LIST_AND_8_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, p7) \
p7) 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, \ #define GMOCK_INTERNAL_LIST_AND_9_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, p7, \
p7, p8) p0, p1, p2, p3, p4, p5, p6, p7, p8 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, \ #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. // Lists the value parameter types.
#define GMOCK_INTERNAL_LIST_TYPE_AND_0_VALUE_PARAMS() #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_1_VALUE_PARAMS(p0) , p0##_type
#define GMOCK_INTERNAL_LIST_TYPE_AND_2_VALUE_PARAMS(p0, p1) , p0##_type, \ #define GMOCK_INTERNAL_LIST_TYPE_AND_2_VALUE_PARAMS(p0, p1) \
p1##_type , p0##_type, p1##_type
#define GMOCK_INTERNAL_LIST_TYPE_AND_3_VALUE_PARAMS(p0, p1, p2) , p0##_type, \ #define GMOCK_INTERNAL_LIST_TYPE_AND_3_VALUE_PARAMS(p0, p1, p2) \
p1##_type, p2##_type , p0##_type, p1##_type, p2##_type
#define GMOCK_INTERNAL_LIST_TYPE_AND_4_VALUE_PARAMS(p0, p1, p2, p3) , \ #define GMOCK_INTERNAL_LIST_TYPE_AND_4_VALUE_PARAMS(p0, p1, p2, p3) \
p0##_type, p1##_type, p2##_type, p3##_type , p0##_type, p1##_type, p2##_type, p3##_type
#define GMOCK_INTERNAL_LIST_TYPE_AND_5_VALUE_PARAMS(p0, p1, p2, p3, p4) , \ #define GMOCK_INTERNAL_LIST_TYPE_AND_5_VALUE_PARAMS(p0, p1, p2, p3, p4) \
p0##_type, p1##_type, p2##_type, p3##_type, p4##_type , 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) , \ #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 , 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, \ #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) \
p6##_type , 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, \ #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, \ p6, p7) \
p5##_type, p6##_type, p7##_type , 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, \ #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, \ p6, p7, p8) \
p5##_type, p6##_type, p7##_type, p8##_type , 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, \ #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, \ p6, p7, p8, p9) \
p5##_type, p6##_type, p7##_type, p8##_type, p9##_type , p0##_type, p1##_type, p2##_type, p3##_type, p4##_type, p5##_type, \
p6##_type, p7##_type, p8##_type, p9##_type
// Declares the value parameters. // Declares the value parameters.
#define GMOCK_INTERNAL_DECL_AND_0_VALUE_PARAMS() #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_1_VALUE_PARAMS(p0) p0##_type p0
#define GMOCK_INTERNAL_DECL_AND_2_VALUE_PARAMS(p0, p1) p0##_type p0, \ #define GMOCK_INTERNAL_DECL_AND_2_VALUE_PARAMS(p0, p1) \
p1##_type p1 p0##_type p0, p1##_type p1
#define GMOCK_INTERNAL_DECL_AND_3_VALUE_PARAMS(p0, p1, p2) p0##_type p0, \ #define GMOCK_INTERNAL_DECL_AND_3_VALUE_PARAMS(p0, p1, p2) \
p1##_type p1, p2##_type 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, \ #define GMOCK_INTERNAL_DECL_AND_4_VALUE_PARAMS(p0, p1, p2, p3) \
p1##_type p1, p2##_type p2, p3##_type 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, \ #define GMOCK_INTERNAL_DECL_AND_5_VALUE_PARAMS(p0, p1, p2, p3, p4) \
p4) p0##_type p0, p1##_type p1, p2##_type p2, p3##_type p3, p4##_type 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, \ #define GMOCK_INTERNAL_DECL_AND_6_VALUE_PARAMS(p0, p1, p2, p3, p4, p5) \
p5) p0##_type p0, p1##_type p1, p2##_type p2, p3##_type p3, p4##_type p4, \ p0##_type p0, p1##_type p1, p2##_type p2, p3##_type p3, p4##_type p4, \
p5##_type p5 p5##_type p5
#define GMOCK_INTERNAL_DECL_AND_7_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, \ #define GMOCK_INTERNAL_DECL_AND_7_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6) \
p6) p0##_type p0, p1##_type p1, p2##_type p2, p3##_type p3, p4##_type p4, \ p0##_type p0, p1##_type p1, p2##_type p2, p3##_type p3, p4##_type p4, \
p5##_type p5, p6##_type p6 p5##_type p5, p6##_type p6
#define GMOCK_INTERNAL_DECL_AND_8_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, \ #define GMOCK_INTERNAL_DECL_AND_8_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, p7) \
p7) p0##_type p0, p1##_type p1, p2##_type p2, p3##_type p3, p4##_type p4, \ p0##_type p0, p1##_type p1, p2##_type p2, p3##_type p3, p4##_type p4, \
p5##_type p5, p6##_type p6, p7##_type p7 p5##_type p5, p6##_type p6, p7##_type p7
#define GMOCK_INTERNAL_DECL_AND_9_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, \ #define GMOCK_INTERNAL_DECL_AND_9_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, p7, \
p7, p8) p0##_type p0, p1##_type p1, p2##_type p2, p3##_type p3, \ p8) \
p4##_type p4, p5##_type p5, p6##_type p6, p7##_type p7, p8##_type 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, \ #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, \ p7, p8, p9) \
p4##_type p4, p5##_type p5, p6##_type p6, p7##_type p7, p8##_type p8, \ p0##_type p0, p1##_type p1, p2##_type p2, p3##_type p3, p4##_type p4, \
p9##_type p9 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. // The suffix of the class template implementing the action template.
#define GMOCK_INTERNAL_COUNT_AND_0_VALUE_PARAMS() #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_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_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, \ #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, \ #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, \ #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. // The name of the class template implementing the action template.
#define GMOCK_ACTION_CLASS_(name, value_params)\ #define GMOCK_ACTION_CLASS_(name, value_params) \
GTEST_CONCAT_TOKEN_(name##Action, GMOCK_INTERNAL_COUNT_##value_params) GTEST_CONCAT_TOKEN_(name##Action, GMOCK_INTERNAL_COUNT_##value_params)
#define ACTION_TEMPLATE(name, template_params, value_params) \ #define ACTION_TEMPLATE(name, template_params, value_params) \
template <GMOCK_INTERNAL_DECL_##template_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) { \ class GMOCK_ACTION_CLASS_(name, value_params) { \
public: \ public: \
explicit GMOCK_ACTION_CLASS_(name, value_params)( \ explicit GMOCK_ACTION_CLASS_(name, value_params)( \
GMOCK_INTERNAL_DECL_##value_params) \ GMOCK_INTERNAL_DECL_##value_params) \
GMOCK_PP_IF(GMOCK_PP_IS_EMPTY(GMOCK_INTERNAL_COUNT_##value_params), \ GMOCK_PP_IF(GMOCK_PP_IS_EMPTY(GMOCK_INTERNAL_COUNT_##value_params), \
= default; , \ = default; \
, \
: impl_(std::make_shared<gmock_Impl>( \ : impl_(std::make_shared<gmock_Impl>( \
GMOCK_INTERNAL_LIST_##value_params)) { }) \ GMOCK_INTERNAL_LIST_##value_params)){}) \
GMOCK_ACTION_CLASS_(name, value_params)( \ GMOCK_ACTION_CLASS_(name, value_params)(const GMOCK_ACTION_CLASS_( \
const GMOCK_ACTION_CLASS_(name, value_params)&) noexcept \ name, value_params) &) noexcept GMOCK_INTERNAL_DEFN_COPY_ \
GMOCK_INTERNAL_DEFN_COPY_##value_params \ ##value_params GMOCK_ACTION_CLASS_(name, value_params)( \
GMOCK_ACTION_CLASS_(name, value_params)( \ GMOCK_ACTION_CLASS_(name, value_params) &&) noexcept \
GMOCK_ACTION_CLASS_(name, value_params)&&) noexcept \ GMOCK_INTERNAL_DEFN_COPY_##value_params template <typename F> \
GMOCK_INTERNAL_DEFN_COPY_##value_params \ operator ::testing::Action<F>() const { \
template <typename F> \
operator ::testing::Action<F>() const { \
return GMOCK_PP_IF( \ return GMOCK_PP_IF( \
GMOCK_PP_IS_EMPTY(GMOCK_INTERNAL_COUNT_##value_params), \ GMOCK_PP_IS_EMPTY(GMOCK_INTERNAL_COUNT_##value_params), \
(::testing::internal::MakeAction<F, gmock_Impl>()), \ (::testing::internal::MakeAction<F, gmock_Impl>()), \
(::testing::internal::MakeAction<F>(impl_))); \ (::testing::internal::MakeAction<F>(impl_))); \
} \ } \
\
private: \ private: \
class gmock_Impl { \ class gmock_Impl { \
public: \ public: \
@ -458,34 +545,35 @@
return_type gmock_PerformImpl(GMOCK_ACTION_ARG_TYPES_AND_NAMES_) const; \ return_type gmock_PerformImpl(GMOCK_ACTION_ARG_TYPES_AND_NAMES_) const; \
GMOCK_INTERNAL_DEFN_##value_params \ GMOCK_INTERNAL_DEFN_##value_params \
}; \ }; \
GMOCK_PP_IF(GMOCK_PP_IS_EMPTY(GMOCK_INTERNAL_COUNT_##value_params), \ GMOCK_PP_IF(GMOCK_PP_IS_EMPTY(GMOCK_INTERNAL_COUNT_##value_params), , \
, std::shared_ptr<const gmock_Impl> impl_;) \ std::shared_ptr<const gmock_Impl> impl_;) \
}; \ }; \
template <GMOCK_INTERNAL_DECL_##template_params \ template <GMOCK_INTERNAL_DECL_##template_params \
GMOCK_INTERNAL_DECL_TYPE_##value_params> \ GMOCK_INTERNAL_DECL_TYPE_##value_params> \
GMOCK_ACTION_CLASS_(name, value_params)< \ GMOCK_ACTION_CLASS_( \
GMOCK_INTERNAL_LIST_##template_params \ name, value_params)<GMOCK_INTERNAL_LIST_##template_params \
GMOCK_INTERNAL_LIST_TYPE_##value_params> name( \ GMOCK_INTERNAL_LIST_TYPE_##value_params> \
GMOCK_INTERNAL_DECL_##value_params) GTEST_MUST_USE_RESULT_; \ name(GMOCK_INTERNAL_DECL_##value_params) GTEST_MUST_USE_RESULT_; \
template <GMOCK_INTERNAL_DECL_##template_params \ template <GMOCK_INTERNAL_DECL_##template_params \
GMOCK_INTERNAL_DECL_TYPE_##value_params> \ GMOCK_INTERNAL_DECL_TYPE_##value_params> \
inline GMOCK_ACTION_CLASS_(name, value_params)< \ inline GMOCK_ACTION_CLASS_( \
GMOCK_INTERNAL_LIST_##template_params \ name, value_params)<GMOCK_INTERNAL_LIST_##template_params \
GMOCK_INTERNAL_LIST_TYPE_##value_params> name( \ GMOCK_INTERNAL_LIST_TYPE_##value_params> \
GMOCK_INTERNAL_DECL_##value_params) { \ name(GMOCK_INTERNAL_DECL_##value_params) { \
return GMOCK_ACTION_CLASS_(name, value_params)< \ return GMOCK_ACTION_CLASS_( \
GMOCK_INTERNAL_LIST_##template_params \ name, value_params)<GMOCK_INTERNAL_LIST_##template_params \
GMOCK_INTERNAL_LIST_TYPE_##value_params>( \ GMOCK_INTERNAL_LIST_TYPE_##value_params>( \
GMOCK_INTERNAL_LIST_##value_params); \ GMOCK_INTERNAL_LIST_##value_params); \
} \ } \
template <GMOCK_INTERNAL_DECL_##template_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, \ template <typename function_type, typename return_type, typename args_type, \
GMOCK_ACTION_TEMPLATE_ARGS_NAMES_> \ GMOCK_ACTION_TEMPLATE_ARGS_NAMES_> \
return_type GMOCK_ACTION_CLASS_(name, value_params)< \ return_type GMOCK_ACTION_CLASS_( \
GMOCK_INTERNAL_LIST_##template_params \ name, value_params)<GMOCK_INTERNAL_LIST_##template_params \
GMOCK_INTERNAL_LIST_TYPE_##value_params>::gmock_Impl::gmock_PerformImpl( \ GMOCK_INTERNAL_LIST_TYPE_##value_params>:: \
GMOCK_ACTION_ARG_TYPES_AND_NAMES_UNUSED_) const gmock_Impl::gmock_PerformImpl(GMOCK_ACTION_ARG_TYPES_AND_NAMES_UNUSED_) \
const
namespace testing { namespace testing {
@ -495,8 +583,8 @@ namespace testing {
// is expanded and macro expansion cannot contain #pragma. Therefore // is expanded and macro expansion cannot contain #pragma. Therefore
// we suppress them here. // we suppress them here.
#ifdef _MSC_VER #ifdef _MSC_VER
# pragma warning(push) #pragma warning(push)
# pragma warning(disable:4100) #pragma warning(disable : 4100)
#endif #endif
namespace internal { namespace internal {
@ -565,7 +653,7 @@ InvokeArgument(Params&&... params) {
} }
#ifdef _MSC_VER #ifdef _MSC_VER
# pragma warning(pop) #pragma warning(pop)
#endif #endif
} // namespace testing } // namespace testing

View File

@ -47,13 +47,13 @@ namespace testing {
// Silence C4100 (unreferenced formal // Silence C4100 (unreferenced formal
// parameter) for MSVC // parameter) for MSVC
#ifdef _MSC_VER #ifdef _MSC_VER
# pragma warning(push) #pragma warning(push)
# pragma warning(disable:4100) #pragma warning(disable : 4100)
#if (_MSC_VER == 1900) #if (_MSC_VER == 1900)
// and silence C4800 (C4800: 'int *const ': forcing value // and silence C4800 (C4800: 'int *const ': forcing value
// to bool 'true' or 'false') for MSVC 14 // to bool 'true' or 'false') for MSVC 14
# pragma warning(disable:4800) #pragma warning(disable : 4800)
#endif #endif
#endif #endif
// Defines a matcher that matches an empty container. The container must // 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 #ifdef _MSC_VER
# pragma warning(pop) #pragma warning(pop)
#endif #endif
} // namespace testing } // namespace testing
#endif // GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_MORE_MATCHERS_H_ #endif // GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_MORE_MATCHERS_H_

View File

@ -70,6 +70,7 @@
#include <type_traits> #include <type_traits>
#include <utility> #include <utility>
#include <vector> #include <vector>
#include "gmock/gmock-actions.h" #include "gmock/gmock-actions.h"
#include "gmock/gmock-cardinalities.h" #include "gmock/gmock-cardinalities.h"
#include "gmock/gmock-matchers.h" #include "gmock/gmock-matchers.h"
@ -78,7 +79,7 @@
#include "gtest/gtest.h" #include "gtest/gtest.h"
#if GTEST_HAS_EXCEPTIONS #if GTEST_HAS_EXCEPTIONS
# include <stdexcept> // NOLINT #include <stdexcept> // NOLINT
#endif #endif
GTEST_DISABLE_MSC_WARNINGS_PUSH_(4251 \ GTEST_DISABLE_MSC_WARNINGS_PUSH_(4251 \
@ -97,13 +98,15 @@ class ExpectationSet;
namespace internal { namespace internal {
// Implements a mock function. // Implements a mock function.
template <typename F> class FunctionMocker; template <typename F>
class FunctionMocker;
// Base class for expectations. // Base class for expectations.
class ExpectationBase; class ExpectationBase;
// Implements an expectation. // Implements an expectation.
template <typename F> class TypedExpectation; template <typename F>
class TypedExpectation;
// Helper class for testing the Expectation class template. // Helper class for testing the Expectation class template.
class ExpectationTester; class ExpectationTester;
@ -171,10 +174,9 @@ class GTEST_API_ UntypedFunctionMockerBase {
// Writes a message that the call is uninteresting (i.e. neither // Writes a message that the call is uninteresting (i.e. neither
// explicitly expected nor explicitly unexpected) to the given // explicitly expected nor explicitly unexpected) to the given
// ostream. // ostream.
virtual void UntypedDescribeUninterestingCall( virtual void UntypedDescribeUninterestingCall(const void* untyped_args,
const void* untyped_args, ::std::ostream* os) const
::std::ostream* os) const GTEST_LOCK_EXCLUDED_(g_gmock_mutex) = 0;
GTEST_LOCK_EXCLUDED_(g_gmock_mutex) = 0;
// Returns the expectation that matches the given function arguments // Returns the expectation that matches the given function arguments
// (or NULL is there's no match); when a match is found, // (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 // is_excessive is modified to indicate whether the call exceeds the
// expected number. // expected number.
virtual const ExpectationBase* UntypedFindMatchingExpectation( virtual const ExpectationBase* UntypedFindMatchingExpectation(
const void* untyped_args, const void* untyped_args, const void** untyped_action, bool* is_excessive,
const void** untyped_action, bool* is_excessive,
::std::ostream* what, ::std::ostream* why) ::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. // Prints the given function arguments to the ostream.
virtual void UntypedPrintArgs(const void* untyped_args, 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 // this information in the global mock registry. Will be called
// whenever an EXPECT_CALL() or ON_CALL() is executed on this mock // whenever an EXPECT_CALL() or ON_CALL() is executed on this mock
// method. // method.
void RegisterOwner(const void* mock_obj) void RegisterOwner(const void* mock_obj) GTEST_LOCK_EXCLUDED_(g_gmock_mutex);
GTEST_LOCK_EXCLUDED_(g_gmock_mutex);
// Sets the mock object this mock method belongs to, and sets the // Sets the mock object this mock method belongs to, and sets the
// name of the mock function. Will be called upon each invocation // 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 // Returns the mock object this mock method belongs to. Must be
// called after RegisterOwner() or SetOwnerAndName() has been // called after RegisterOwner() or SetOwnerAndName() has been
// called. // called.
const void* MockObject() const const void* MockObject() const GTEST_LOCK_EXCLUDED_(g_gmock_mutex);
GTEST_LOCK_EXCLUDED_(g_gmock_mutex);
// Returns the name of this mock method. Must be called after // Returns the name of this mock method. Must be called after
// SetOwnerAndName() has been called. // SetOwnerAndName() has been called.
const char* Name() const const char* Name() const GTEST_LOCK_EXCLUDED_(g_gmock_mutex);
GTEST_LOCK_EXCLUDED_(g_gmock_mutex);
// Returns the result of invoking this mock function with the given // Returns the result of invoking this mock function with the given
// arguments. This function can be safely called from multiple // 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 // Returns the reaction Google Mock will have on uninteresting calls
// made on the given mock object. // made on the given mock object.
static internal::CallReaction GetReactionOnUninterestingCalls( static internal::CallReaction GetReactionOnUninterestingCalls(
const void* mock_obj) const void* mock_obj) GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
// Verifies that all expectations on the given mock object have been // Verifies that all expectations on the given mock object have been
// satisfied. Reports one or more Google Test non-fatal failures // 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); GTEST_EXCLUSIVE_LOCK_REQUIRED_(internal::g_gmock_mutex);
// Registers a mock object and a mock method it owns. // Registers a mock object and a mock method it owns.
static void Register( static void Register(const void* mock_obj,
const void* mock_obj, internal::UntypedFunctionMockerBase* mocker)
internal::UntypedFunctionMockerBase* mocker) GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
// Tells Google Mock where in the source code mock_obj is used in an // 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 // ON_CALL or EXPECT_CALL. In case mock_obj is leaked, this
// information helps the user identify which object it is. // information helps the user identify which object it is.
static void RegisterUseByOnCallOrExpectCall( static void RegisterUseByOnCallOrExpectCall(const void* mock_obj,
const void* mock_obj, const char* file, int line) const char* file, int line)
GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex); GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
// Unregisters a mock method; removes the owning mock object from // Unregisters a mock method; removes the owning mock object from
// the registry when the last mock method associated with it has // the registry when the last mock method associated with it has
@ -632,7 +628,6 @@ class ExpectationSet {
Expectation::Set expectations_; Expectation::Set expectations_;
}; };
// Sequence objects are used by a user to specify the relative order // Sequence objects are used by a user to specify the relative order
// in which the expectations should match. They are copyable (we rely // in which the expectations should match. They are copyable (we rely
// on the compiler-defined copy constructor and assignment operator). // on the compiler-defined copy constructor and assignment operator).
@ -678,6 +673,7 @@ class GTEST_API_ InSequence {
public: public:
InSequence(); InSequence();
~InSequence(); ~InSequence();
private: private:
bool sequence_created_; bool sequence_created_;
@ -784,40 +780,34 @@ class GTEST_API_ ExpectationBase {
// the current thread. // the current thread.
// Retires all pre-requisites of this expectation. // Retires all pre-requisites of this expectation.
void RetireAllPreRequisites() void RetireAllPreRequisites() GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex);
GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex);
// Returns true if and only if this expectation is retired. // Returns true if and only if this expectation is retired.
bool is_retired() const bool is_retired() const GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
g_gmock_mutex.AssertHeld(); g_gmock_mutex.AssertHeld();
return retired_; return retired_;
} }
// Retires this expectation. // Retires this expectation.
void Retire() void Retire() GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
g_gmock_mutex.AssertHeld(); g_gmock_mutex.AssertHeld();
retired_ = true; retired_ = true;
} }
// Returns true if and only if this expectation is satisfied. // Returns true if and only if this expectation is satisfied.
bool IsSatisfied() const bool IsSatisfied() const GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
g_gmock_mutex.AssertHeld(); g_gmock_mutex.AssertHeld();
return cardinality().IsSatisfiedByCallCount(call_count_); return cardinality().IsSatisfiedByCallCount(call_count_);
} }
// Returns true if and only if this expectation is saturated. // Returns true if and only if this expectation is saturated.
bool IsSaturated() const bool IsSaturated() const GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
g_gmock_mutex.AssertHeld(); g_gmock_mutex.AssertHeld();
return cardinality().IsSaturatedByCallCount(call_count_); return cardinality().IsSaturatedByCallCount(call_count_);
} }
// Returns true if and only if this expectation is over-saturated. // Returns true if and only if this expectation is over-saturated.
bool IsOverSaturated() const bool IsOverSaturated() const GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
g_gmock_mutex.AssertHeld(); g_gmock_mutex.AssertHeld();
return cardinality().IsOverSaturatedByCallCount(call_count_); return cardinality().IsOverSaturatedByCallCount(call_count_);
} }
@ -832,15 +822,13 @@ class GTEST_API_ ExpectationBase {
GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex); GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex);
// Returns the number this expectation has been invoked. // Returns the number this expectation has been invoked.
int call_count() const int call_count() const GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
g_gmock_mutex.AssertHeld(); g_gmock_mutex.AssertHeld();
return call_count_; return call_count_;
} }
// Increments the number this expectation has been invoked. // Increments the number this expectation has been invoked.
void IncrementCallCount() void IncrementCallCount() GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
g_gmock_mutex.AssertHeld(); g_gmock_mutex.AssertHeld();
call_count_++; call_count_++;
} }
@ -849,8 +837,7 @@ class GTEST_API_ ExpectationBase {
// WillRepeatedly() clauses) against the cardinality if this hasn't // WillRepeatedly() clauses) against the cardinality if this hasn't
// been done before. Prints a warning if there are too many or too // been done before. Prints a warning if there are too many or too
// few actions. // few actions.
void CheckActionCountIfNotDone() const void CheckActionCountIfNotDone() const GTEST_LOCK_EXCLUDED_(mutex_);
GTEST_LOCK_EXCLUDED_(mutex_);
friend class ::testing::Sequence; friend class ::testing::Sequence;
friend class ::testing::internal::ExpectationTester; 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 // This group of fields are part of the spec and won't change after
// an EXPECT_CALL() statement finishes. // an EXPECT_CALL() statement finishes.
const char* file_; // The file that contains the expectation. const char* file_; // The file that contains the expectation.
int line_; // The line number of the expectation. int line_; // The line number of the expectation.
const std::string source_text_; // The EXPECT_CALL(...) source text. const std::string source_text_; // The EXPECT_CALL(...) source text.
// True if and only if the cardinality is specified explicitly. // True if and only if the cardinality is specified explicitly.
bool cardinality_specified_; 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 // The immediate pre-requisites (i.e. expectations that must be
// satisfied before this expectation can be matched) of this // satisfied before this expectation can be matched) of this
// expectation. We use std::shared_ptr in the set because we want an // 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_; bool retires_on_saturation_;
Clause last_clause_; Clause last_clause_;
mutable bool action_count_checked_; // Under mutex_. mutable bool action_count_checked_; // Under mutex_.
mutable Mutex mutex_; // Protects action_count_checked_. mutable Mutex mutex_; // Protects action_count_checked_.
}; // class ExpectationBase }; // class ExpectationBase
// Implements an expectation for the given function type. // Implements an expectation for the given function type.
template <typename F> template <typename F>
@ -945,9 +932,7 @@ class TypedExpectation : public ExpectationBase {
} }
// Implements the .Times() clause. // Implements the .Times() clause.
TypedExpectation& Times(int n) { TypedExpectation& Times(int n) { return Times(Exactly(n)); }
return Times(Exactly(n));
}
// Implements the .InSequence() clause. // Implements the .InSequence() clause.
TypedExpectation& InSequence(const Sequence& s) { TypedExpectation& InSequence(const Sequence& s) {
@ -1062,9 +1047,7 @@ class TypedExpectation : public ExpectationBase {
// Returns the matchers for the arguments as specified inside the // Returns the matchers for the arguments as specified inside the
// EXPECT_CALL() macro. // EXPECT_CALL() macro.
const ArgumentMatcherTuple& matchers() const { const ArgumentMatcherTuple& matchers() const { return matchers_; }
return matchers_;
}
// Returns the matcher specified by the .With() clause. // Returns the matcher specified by the .With() clause.
const Matcher<const ArgumentTuple&>& extra_matcher() const { const Matcher<const ArgumentTuple&>& extra_matcher() const {
@ -1119,10 +1102,8 @@ class TypedExpectation : public ExpectationBase {
// Describes the result of matching the arguments against this // Describes the result of matching the arguments against this
// expectation to the given ostream. // expectation to the given ostream.
void ExplainMatchResultTo( void ExplainMatchResultTo(const ArgumentTuple& args, ::std::ostream* os) const
const ArgumentTuple& args, GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
::std::ostream* os) const
GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
g_gmock_mutex.AssertHeld(); g_gmock_mutex.AssertHeld();
if (is_retired()) { if (is_retired()) {
@ -1181,9 +1162,9 @@ class TypedExpectation : public ExpectationBase {
::std::stringstream ss; ::std::stringstream ss;
DescribeLocationTo(&ss); DescribeLocationTo(&ss);
ss << "Actions ran out in " << source_text() << "...\n" ss << "Actions ran out in " << source_text() << "...\n"
<< "Called " << count << " times, but only " << "Called " << count << " times, but only " << action_count
<< action_count << " WillOnce()" << " WillOnce()" << (action_count == 1 ? " is" : "s are")
<< (action_count == 1 ? " is" : "s are") << " specified - "; << " specified - ";
mocker->DescribeDefaultActionTo(args, &ss); mocker->DescribeDefaultActionTo(args, &ss);
Log(kWarning, ss.str(), 1); Log(kWarning, ss.str(), 1);
} }
@ -1225,7 +1206,7 @@ class TypedExpectation : public ExpectationBase {
} }
// Must be done after IncrementCount()! // 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)); return &(GetCurrentAction(mocker, args));
} }
@ -1258,8 +1239,8 @@ template <typename F>
class MockSpec { class MockSpec {
public: public:
typedef typename internal::Function<F>::ArgumentTuple ArgumentTuple; typedef typename internal::Function<F>::ArgumentTuple ArgumentTuple;
typedef typename internal::Function<F>::ArgumentMatcherTuple typedef
ArgumentMatcherTuple; typename internal::Function<F>::ArgumentMatcherTuple ArgumentMatcherTuple;
// Constructs a MockSpec object, given the function mocker object // Constructs a MockSpec object, given the function mocker object
// that the spec is associated with. // that the spec is associated with.
@ -1269,8 +1250,9 @@ class MockSpec {
// Adds a new default action spec to the function mocker and returns // Adds a new default action spec to the function mocker and returns
// the newly created spec. // the newly created spec.
internal::OnCallSpec<F>& InternalDefaultActionSetAt( internal::OnCallSpec<F>& InternalDefaultActionSetAt(const char* file,
const char* file, int line, const char* obj, const char* call) { int line, const char* obj,
const char* call) {
LogWithLocation(internal::kInfo, file, line, LogWithLocation(internal::kInfo, file, line,
std::string("ON_CALL(") + obj + ", " + call + ") invoked"); std::string("ON_CALL(") + obj + ", " + call + ") invoked");
return function_mocker_->AddNewOnCallSpec(file, line, matchers_); return function_mocker_->AddNewOnCallSpec(file, line, matchers_);
@ -1278,13 +1260,14 @@ class MockSpec {
// Adds a new expectation spec to the function mocker and returns // Adds a new expectation spec to the function mocker and returns
// the newly created spec. // the newly created spec.
internal::TypedExpectation<F>& InternalExpectedAt( internal::TypedExpectation<F>& InternalExpectedAt(const char* file, int line,
const char* file, int line, const char* obj, const char* call) { const char* obj,
const char* call) {
const std::string source_text(std::string("EXPECT_CALL(") + obj + ", " + const std::string source_text(std::string("EXPECT_CALL(") + obj + ", " +
call + ")"); call + ")");
LogWithLocation(internal::kInfo, file, line, source_text + " invoked"); LogWithLocation(internal::kInfo, file, line, source_text + " invoked");
return function_mocker_->AddNewExpectation( return function_mocker_->AddNewExpectation(file, line, source_text,
file, line, source_text, matchers_); matchers_);
} }
// This operator overload is used to swallow the superfluous parameter list // This operator overload is used to swallow the superfluous parameter list
@ -1317,9 +1300,7 @@ template <typename T>
class ReferenceOrValueWrapper { class ReferenceOrValueWrapper {
public: public:
// Constructs a wrapper from the given value/reference. // Constructs a wrapper from the given value/reference.
explicit ReferenceOrValueWrapper(T value) explicit ReferenceOrValueWrapper(T value) : value_(std::move(value)) {}
: value_(std::move(value)) {
}
// Unwraps and returns the underlying value/reference, exactly as // Unwraps and returns the underlying value/reference, exactly as
// originally passed. The behavior of calling this more than once on // originally passed. The behavior of calling this more than once on
@ -1330,9 +1311,7 @@ class ReferenceOrValueWrapper {
// Always returns a const reference (more precisely, // Always returns a const reference (more precisely,
// const std::add_lvalue_reference<T>::type). The behavior of calling this // const std::add_lvalue_reference<T>::type). The behavior of calling this
// after calling Unwrap on the same object is unspecified. // after calling Unwrap on the same object is unspecified.
const T& Peek() const { const T& Peek() const { return value_; }
return value_;
}
private: private:
T value_; T value_;
@ -1346,8 +1325,7 @@ class ReferenceOrValueWrapper<T&> {
// Workaround for debatable pass-by-reference lint warning (c-library-team // Workaround for debatable pass-by-reference lint warning (c-library-team
// policy precludes NOLINT in this context) // policy precludes NOLINT in this context)
typedef T& reference; typedef T& reference;
explicit ReferenceOrValueWrapper(reference ref) explicit ReferenceOrValueWrapper(reference ref) : value_ptr_(&ref) {}
: value_ptr_(&ref) {}
T& Unwrap() { return *value_ptr_; } T& Unwrap() { return *value_ptr_; }
const T& Peek() const { return *value_ptr_; } const T& Peek() const { return *value_ptr_; }
@ -1377,9 +1355,7 @@ template <typename T>
class ActionResultHolder : public UntypedActionResultHolderBase { class ActionResultHolder : public UntypedActionResultHolderBase {
public: public:
// Returns the held value. Must not be called more than once. // Returns the held value. Must not be called more than once.
T Unwrap() { T Unwrap() { return result_.Unwrap(); }
return result_.Unwrap();
}
// Prints the held value as an action's result to os. // Prints the held value as an action's result to os.
void PrintAsActionResult(::std::ostream* os) const override { void PrintAsActionResult(::std::ostream* os) const override {
@ -1395,8 +1371,8 @@ class ActionResultHolder : public UntypedActionResultHolderBase {
const FunctionMocker<F>* func_mocker, const FunctionMocker<F>* func_mocker,
typename Function<F>::ArgumentTuple&& args, typename Function<F>::ArgumentTuple&& args,
const std::string& call_description) { const std::string& call_description) {
return new ActionResultHolder(Wrapper(func_mocker->PerformDefaultAction( return new ActionResultHolder(Wrapper(
std::move(args), call_description))); func_mocker->PerformDefaultAction(std::move(args), call_description)));
} }
// Performs the given action and returns the result in a new-ed // Performs the given action and returns the result in a new-ed
@ -1404,16 +1380,13 @@ class ActionResultHolder : public UntypedActionResultHolderBase {
template <typename F> template <typename F>
static ActionResultHolder* PerformAction( static ActionResultHolder* PerformAction(
const Action<F>& action, typename Function<F>::ArgumentTuple&& args) { const Action<F>& action, typename Function<F>::ArgumentTuple&& args) {
return new ActionResultHolder( return new ActionResultHolder(Wrapper(action.Perform(std::move(args))));
Wrapper(action.Perform(std::move(args))));
} }
private: private:
typedef ReferenceOrValueWrapper<T> Wrapper; typedef ReferenceOrValueWrapper<T> Wrapper;
explicit ActionResultHolder(Wrapper result) explicit ActionResultHolder(Wrapper result) : result_(std::move(result)) {}
: result_(std::move(result)) {
}
Wrapper result_; Wrapper result_;
@ -1424,7 +1397,7 @@ class ActionResultHolder : public UntypedActionResultHolderBase {
template <> template <>
class ActionResultHolder<void> : public UntypedActionResultHolderBase { class ActionResultHolder<void> : public UntypedActionResultHolderBase {
public: public:
void Unwrap() { } void Unwrap() {}
void PrintAsActionResult(::std::ostream* /* os */) const override {} 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 // Returns the ON_CALL spec that matches this mock function with the
// given arguments; returns NULL if no matching ON_CALL is found. // given arguments; returns NULL if no matching ON_CALL is found.
// L = * // L = *
const OnCallSpec<F>* FindOnCallSpec( const OnCallSpec<F>* FindOnCallSpec(const ArgumentTuple& args) const {
const ArgumentTuple& args) const { for (UntypedOnCallSpecs::const_reverse_iterator it =
for (UntypedOnCallSpecs::const_reverse_iterator it untyped_on_call_specs_.rbegin();
= untyped_on_call_specs_.rbegin();
it != untyped_on_call_specs_.rend(); ++it) { it != untyped_on_call_specs_.rend(); ++it) {
const OnCallSpec<F>* spec = static_cast<const OnCallSpec<F>*>(*it); const OnCallSpec<F>* spec = static_cast<const OnCallSpec<F>*>(*it);
if (spec->Matches(args)) if (spec->Matches(args)) return spec;
return spec;
} }
return nullptr; return nullptr;
@ -1517,8 +1488,7 @@ class FunctionMocker<R(Args...)> final : public UntypedFunctionMockerBase {
// L = * // L = *
Result PerformDefaultAction(ArgumentTuple&& args, Result PerformDefaultAction(ArgumentTuple&& args,
const std::string& call_description) const { const std::string& call_description) const {
const OnCallSpec<F>* const spec = const OnCallSpec<F>* const spec = this->FindOnCallSpec(args);
this->FindOnCallSpec(args);
if (spec != nullptr) { if (spec != nullptr) {
return spec->GetAction().Perform(std::move(args)); 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); untyped_on_call_specs_.swap(specs_to_delete);
g_gmock_mutex.Unlock(); g_gmock_mutex.Unlock();
for (UntypedOnCallSpecs::const_iterator it = for (UntypedOnCallSpecs::const_iterator it = specs_to_delete.begin();
specs_to_delete.begin();
it != specs_to_delete.end(); ++it) { it != specs_to_delete.end(); ++it) {
delete static_cast<const OnCallSpec<F>*>(*it); delete static_cast<const OnCallSpec<F>*>(*it);
} }
@ -1611,10 +1580,9 @@ class FunctionMocker<R(Args...)> final : public UntypedFunctionMockerBase {
typedef ActionResultHolder<Result> ResultHolder; typedef ActionResultHolder<Result> ResultHolder;
// Adds and returns a default action spec for this mock function. // Adds and returns a default action spec for this mock function.
OnCallSpec<F>& AddNewOnCallSpec( OnCallSpec<F>& AddNewOnCallSpec(const char* file, int line,
const char* file, int line, const ArgumentMatcherTuple& m)
const ArgumentMatcherTuple& m) GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
Mock::RegisterUseByOnCallOrExpectCall(MockObject(), file, line); Mock::RegisterUseByOnCallOrExpectCall(MockObject(), file, line);
OnCallSpec<F>* const on_call_spec = new OnCallSpec<F>(file, line, m); OnCallSpec<F>* const on_call_spec = new OnCallSpec<F>(file, line, m);
untyped_on_call_specs_.push_back(on_call_spec); untyped_on_call_specs_.push_back(on_call_spec);
@ -1644,7 +1612,8 @@ class FunctionMocker<R(Args...)> final : public UntypedFunctionMockerBase {
} }
private: private:
template <typename Func> friend class TypedExpectation; template <typename Func>
friend class TypedExpectation;
// Some utilities needed for implementing UntypedInvokeWith(). // 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 // Returns the expectation that matches the arguments, or NULL if no
// expectation matches them. // expectation matches them.
TypedExpectation<F>* FindMatchingExpectationLocked( TypedExpectation<F>* FindMatchingExpectationLocked(const ArgumentTuple& args)
const ArgumentTuple& args) const const GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
g_gmock_mutex.AssertHeld(); g_gmock_mutex.AssertHeld();
// See the definition of untyped_expectations_ for why access to // See the definition of untyped_expectations_ for why access to
// it is unprotected here. // 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. // Returns a message that the arguments don't match any expectation.
void FormatUnexpectedCallMessageLocked( void FormatUnexpectedCallMessageLocked(const ArgumentTuple& args,
const ArgumentTuple& args, ::std::ostream* os,
::std::ostream* os, ::std::ostream* why) const
::std::ostream* why) const GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
g_gmock_mutex.AssertHeld(); g_gmock_mutex.AssertHeld();
*os << "\nUnexpected mock function call - "; *os << "\nUnexpected mock function call - ";
DescribeDefaultActionTo(args, os); 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 // Prints a list of expectations that have been tried against the
// current mock function call. // current mock function call.
void PrintTriedExpectationsLocked( void PrintTriedExpectationsLocked(const ArgumentTuple& args,
const ArgumentTuple& args, ::std::ostream* why) const
::std::ostream* why) const GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
g_gmock_mutex.AssertHeld(); g_gmock_mutex.AssertHeld();
const size_t count = untyped_expectations_.size(); const size_t count = untyped_expectations_.size();
*why << "Google Mock tried the following " << count << " " *why << "Google Mock tried the following " << count << " "
<< (count == 1 ? "expectation, but it didn't match" : << (count == 1 ? "expectation, but it didn't match"
"expectations, but none matched") : "expectations, but none matched")
<< ":\n"; << ":\n";
for (size_t i = 0; i < count; i++) { for (size_t i = 0; i < count; i++) {
TypedExpectation<F>* const expectation = TypedExpectation<F>* const expectation =
@ -1952,7 +1918,9 @@ using internal::MockSpec;
// // Expects a call to const MockFoo::Bar(). // // Expects a call to const MockFoo::Bar().
// EXPECT_CALL(Const(foo), Bar()); // EXPECT_CALL(Const(foo), Bar());
template <typename T> 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. // Constructs an Expectation object that references and co-owns exp.
inline Expectation::Expectation(internal::ExpectationBase& exp) // NOLINT inline Expectation::Expectation(internal::ExpectationBase& exp) // NOLINT

View File

@ -59,9 +59,9 @@ namespace internal {
// Silence MSVC C4100 (unreferenced formal parameter) and // Silence MSVC C4100 (unreferenced formal parameter) and
// C4805('==': unsafe mix of type 'const int' and type 'const bool') // C4805('==': unsafe mix of type 'const int' and type 'const bool')
#ifdef _MSC_VER #ifdef _MSC_VER
# pragma warning(push) #pragma warning(push)
# pragma warning(disable:4100) #pragma warning(disable : 4100)
# pragma warning(disable:4805) #pragma warning(disable : 4805)
#endif #endif
// Joins a vector of strings as if they are fields of a tuple; returns // 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. // This overloaded version is for the raw pointer case.
template <typename Element> 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 // 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 // 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) #if defined(_MSC_VER) && !defined(_NATIVE_WCHAR_T_DEFINED)
// wchar_t is a typedef. // wchar_t is a typedef.
#else #else
# define GMOCK_WCHAR_T_IS_NATIVE_ 1 #define GMOCK_WCHAR_T_IS_NATIVE_ 1
#endif #endif
// In what follows, we use the term "kind" to indicate whether a type // 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 // or none of them. This categorization is useful for determining
// when a matcher argument type can be safely converted to another // when a matcher argument type can be safely converted to another
// type in the implementation of SafeMatcherCast. // type in the implementation of SafeMatcherCast.
enum TypeKind { enum TypeKind { kBool, kInteger, kFloatingPoint, kOther };
kBool, kInteger, kFloatingPoint, kOther
};
// KindOf<T>::value is the kind of type T. // 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. enum { value = kOther }; // The default kind.
}; };
// This macro declares that the kind of 'type' is 'kind'. // This macro declares that the kind of 'type' is 'kind'.
#define GMOCK_DECLARE_KIND_(type, 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); GMOCK_DECLARE_KIND_(bool, kBool);
@ -127,13 +131,13 @@ GMOCK_DECLARE_KIND_(bool, kBool);
GMOCK_DECLARE_KIND_(char, kInteger); GMOCK_DECLARE_KIND_(char, kInteger);
GMOCK_DECLARE_KIND_(signed char, kInteger); GMOCK_DECLARE_KIND_(signed char, kInteger);
GMOCK_DECLARE_KIND_(unsigned 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_(unsigned short, kInteger); // NOLINT
GMOCK_DECLARE_KIND_(int, kInteger); GMOCK_DECLARE_KIND_(int, kInteger);
GMOCK_DECLARE_KIND_(unsigned int, kInteger); GMOCK_DECLARE_KIND_(unsigned int, kInteger);
GMOCK_DECLARE_KIND_(long, kInteger); // NOLINT GMOCK_DECLARE_KIND_(long, kInteger); // NOLINT
GMOCK_DECLARE_KIND_(unsigned long, kInteger); // NOLINT GMOCK_DECLARE_KIND_(unsigned long, kInteger); // NOLINT
GMOCK_DECLARE_KIND_(long long, kInteger); // NOLINT GMOCK_DECLARE_KIND_(long long, kInteger); // NOLINT
GMOCK_DECLARE_KIND_(unsigned long long, kInteger); // NOLINT GMOCK_DECLARE_KIND_(unsigned long long, kInteger); // NOLINT
#if GMOCK_WCHAR_T_IS_NATIVE_ #if GMOCK_WCHAR_T_IS_NATIVE_
@ -148,7 +152,7 @@ GMOCK_DECLARE_KIND_(long double, kFloatingPoint);
#undef GMOCK_DECLARE_KIND_ #undef GMOCK_DECLARE_KIND_
// Evaluates to the kind of 'type'. // Evaluates to the kind of 'type'.
#define GMOCK_KIND_OF_(type) \ #define GMOCK_KIND_OF_(type) \
static_cast< ::testing::internal::TypeKind>( \ static_cast< ::testing::internal::TypeKind>( \
::testing::internal::KindOf<type>::value) ::testing::internal::KindOf<type>::value)
@ -204,9 +208,7 @@ using LosslessArithmeticConvertible =
class FailureReporterInterface { class FailureReporterInterface {
public: public:
// The type of a failure (either non-fatal or fatal). // The type of a failure (either non-fatal or fatal).
enum FailureType { enum FailureType { kNonfatal, kFatal };
kNonfatal, kFatal
};
virtual ~FailureReporterInterface() {} virtual ~FailureReporterInterface() {}
@ -226,8 +228,8 @@ GTEST_API_ FailureReporterInterface* GetFailureReporter();
inline void Assert(bool condition, const char* file, int line, inline void Assert(bool condition, const char* file, int line,
const std::string& msg) { const std::string& msg) {
if (!condition) { if (!condition) {
GetFailureReporter()->ReportFailure(FailureReporterInterface::kFatal, GetFailureReporter()->ReportFailure(FailureReporterInterface::kFatal, file,
file, line, msg); line, msg);
} }
} }
inline void Assert(bool condition, const char* file, int line) { 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. // Severity level of a log.
enum LogSeverity { enum LogSeverity { kInfo = 0, kWarning = 1 };
kInfo = 0,
kWarning = 1
};
// Valid values for the --gmock_verbose flag. // 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 // Disable MSVC warnings for infinite recursion, since in this case the
// recursion is unreachable. // recursion is unreachable.
#ifdef _MSC_VER #ifdef _MSC_VER
# pragma warning(push) #pragma warning(push)
# pragma warning(disable:4717) #pragma warning(disable : 4717)
#endif #endif
// Invalid<T>() is usable as an expression of type T, but will terminate // Invalid<T>() is usable as an expression of type T, but will terminate
@ -313,7 +312,7 @@ inline T Invalid() {
} }
#ifdef _MSC_VER #ifdef _MSC_VER
# pragma warning(pop) #pragma warning(pop)
#endif #endif
// Given a raw type (i.e. having no top-level reference or const // 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 // The following specialization prevents the user from instantiating
// StlContainer with a reference type. // 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. // 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, // 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); GTEST_API_ void IllegalDoDefault(const char* file, int line);
template <typename F, typename Tuple, size_t... Idx> template <typename F, typename Tuple, size_t... Idx>
auto ApplyImpl(F&& f, Tuple&& args, IndexSequence<Idx...>) -> decltype( auto ApplyImpl(F&& f, Tuple&& args, IndexSequence<Idx...>)
std::forward<F>(f)(std::get<Idx>(std::forward<Tuple>(args))...)) { -> decltype(std::forward<F>(f)(
std::get<Idx>(std::forward<Tuple>(args))...)) {
return 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. // Apply the function to a tuple of arguments.
template <typename F, typename Tuple> template <typename F, typename Tuple>
auto Apply(F&& f, Tuple&& args) -> decltype( auto Apply(F&& f, Tuple&& args) -> decltype(ApplyImpl(
ApplyImpl(std::forward<F>(f), std::forward<Tuple>(args), std::forward<F>(f), std::forward<Tuple>(args),
MakeIndexSequence<std::tuple_size< MakeIndexSequence<std::tuple_size<
typename std::remove_reference<Tuple>::type>::value>())) { typename std::remove_reference<Tuple>::type>::value>())) {
return ApplyImpl(std::forward<F>(f), std::forward<Tuple>(args), return ApplyImpl(std::forward<F>(f), std::forward<Tuple>(args),
MakeIndexSequence<std::tuple_size< MakeIndexSequence<std::tuple_size<
typename std::remove_reference<Tuple>::type>::value>()); 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); bool Base64Unescape(const std::string& encoded, std::string* decoded);
#ifdef _MSC_VER #ifdef _MSC_VER
# pragma warning(pop) #pragma warning(pop)
#endif #endif
} // namespace internal } // namespace internal

View File

@ -42,6 +42,7 @@
#include <assert.h> #include <assert.h>
#include <stdlib.h> #include <stdlib.h>
#include <cstdint> #include <cstdint>
#include <iostream> #include <iostream>
@ -53,13 +54,13 @@
// here, as Google Mock depends on Google Test. Only add a utility // here, as Google Mock depends on Google Test. Only add a utility
// here if it's truly specific to Google Mock. // here if it's truly specific to Google Mock.
#include "gtest/internal/gtest-port.h"
#include "gmock/internal/custom/gmock-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 // For MS Visual C++, check the compiler version. At least VS 2015 is
// required to compile Google Mock. // required to compile Google Mock.
#if defined(_MSC_VER) && _MSC_VER < 1900 #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 #endif
// Macro for referencing flags. This is public as we want the user to // Macro for referencing flags. This is public as we want the user to
@ -72,29 +73,35 @@
#define GMOCK_DECLARE_bool_(name) \ #define GMOCK_DECLARE_bool_(name) \
namespace testing { \ namespace testing { \
GTEST_API_ extern bool GMOCK_FLAG(name); \ 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) \ #define GMOCK_DECLARE_int32_(name) \
namespace testing { \ namespace testing { \
GTEST_API_ extern int32_t GMOCK_FLAG(name); \ 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) \ #define GMOCK_DECLARE_string_(name) \
namespace testing { \ namespace testing { \
GTEST_API_ extern ::std::string GMOCK_FLAG(name); \ 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. // Macros for defining flags.
#define GMOCK_DEFINE_bool_(name, default_val, doc) \ #define GMOCK_DEFINE_bool_(name, default_val, doc) \
namespace testing { \ namespace testing { \
GTEST_API_ bool GMOCK_FLAG(name) = (default_val); \ 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) \ #define GMOCK_DEFINE_int32_(name, default_val, doc) \
namespace testing { \ namespace testing { \
GTEST_API_ int32_t GMOCK_FLAG(name) = (default_val); \ 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) \ #define GMOCK_DEFINE_string_(name, default_val, doc) \
namespace testing { \ namespace testing { \
GTEST_API_ ::std::string GMOCK_FLAG(name) = (default_val); \ 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_) #endif // !defined(GMOCK_DECLARE_bool_)
#if !defined(GMOCK_FLAG_GET) #if !defined(GMOCK_FLAG_GET)

View File

@ -27,7 +27,6 @@
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// Google Mock - a framework for writing C++ mock classes. // Google Mock - a framework for writing C++ mock classes.
// //
// This file implements cardinalities. // This file implements cardinalities.
@ -35,9 +34,11 @@
#include "gmock/gmock-cardinalities.h" #include "gmock/gmock-cardinalities.h"
#include <limits.h> #include <limits.h>
#include <ostream> // NOLINT #include <ostream> // NOLINT
#include <sstream> #include <sstream>
#include <string> #include <string>
#include "gmock/internal/gmock-internal-utils.h" #include "gmock/internal/gmock-internal-utils.h"
#include "gtest/gtest.h" #include "gtest/gtest.h"
@ -49,8 +50,7 @@ namespace {
class BetweenCardinalityImpl : public CardinalityInterface { class BetweenCardinalityImpl : public CardinalityInterface {
public: public:
BetweenCardinalityImpl(int min, int max) BetweenCardinalityImpl(int min, int max)
: min_(min >= 0 ? min : 0), : min_(min >= 0 ? min : 0), max_(max >= min_ ? max : min_) {
max_(max >= min_ ? max : min_) {
std::stringstream ss; std::stringstream ss;
if (min < 0) { if (min < 0) {
ss << "The invocation lower bound must be >= 0, " ss << "The invocation lower bound must be >= 0, "
@ -62,8 +62,7 @@ class BetweenCardinalityImpl : public CardinalityInterface {
internal::Expect(false, __FILE__, __LINE__, ss.str()); internal::Expect(false, __FILE__, __LINE__, ss.str());
} else if (min > max) { } else if (min > max) {
ss << "The invocation upper bound (" << 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()); internal::Expect(false, __FILE__, __LINE__, ss.str());
} }
} }

View File

@ -27,7 +27,6 @@
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// Google Mock - a framework for writing C++ mock classes. // Google Mock - a framework for writing C++ mock classes.
// //
// This file defines some utilities useful for implementing Google // 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 // We don't care about the current locale as the input is
// guaranteed to be a valid C++ identifier name. // guaranteed to be a valid C++ identifier name.
const bool starts_new_word = IsUpper(*p) || const bool starts_new_word = IsUpper(*p) ||
(!IsAlpha(prev_char) && IsLower(*p)) || (!IsAlpha(prev_char) && IsLower(*p)) ||
(!IsDigit(prev_char) && IsDigit(*p)); (!IsDigit(prev_char) && IsDigit(*p));
if (IsAlNum(*p)) { if (IsAlNum(*p)) {
if (starts_new_word && result != "") if (starts_new_word && result != "") result += ' ';
result += ' ';
result += ToLower(*p); result += ToLower(*p);
} }
} }
@ -103,12 +101,9 @@ class GoogleTestFailureReporter : public FailureReporterInterface {
public: public:
void ReportFailure(FailureType type, const char* file, int line, void ReportFailure(FailureType type, const char* file, int line,
const std::string& message) override { const std::string& message) override {
AssertHelper(type == kFatal ? AssertHelper(type == kFatal ? TestPartResult::kFatalFailure
TestPartResult::kFatalFailure : : TestPartResult::kNonFatalFailure,
TestPartResult::kNonFatalFailure, file, line, message.c_str()) = Message();
file,
line,
message.c_str()) = Message();
if (type == kFatal) { if (type == kFatal) {
posix::Abort(); posix::Abort();
} }
@ -156,8 +151,7 @@ GTEST_API_ bool LogIsVisible(LogSeverity severity) {
// conservative. // conservative.
GTEST_API_ void Log(LogSeverity severity, const std::string& message, GTEST_API_ void Log(LogSeverity severity, const std::string& message,
int stack_frames_to_skip) { int stack_frames_to_skip) {
if (!LogIsVisible(severity)) if (!LogIsVisible(severity)) return;
return;
// Ensures that logs from different threads don't interleave. // Ensures that logs from different threads don't interleave.
MutexLock l(&g_log_mutex); MutexLock l(&g_log_mutex);
@ -186,8 +180,8 @@ GTEST_API_ void Log(LogSeverity severity, const std::string& message,
std::cout << "\n"; std::cout << "\n";
} }
std::cout << "Stack trace:\n" std::cout << "Stack trace:\n"
<< ::testing::internal::GetCurrentOsStackTraceExceptTop( << ::testing::internal::GetCurrentOsStackTraceExceptTop(
::testing::UnitTest::GetInstance(), actual_to_skip); ::testing::UnitTest::GetInstance(), actual_to_skip);
} }
std::cout << ::std::flush; std::cout << ::std::flush;
} }

View File

@ -27,7 +27,6 @@
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// Google Mock - a framework for writing C++ mock classes. // Google Mock - a framework for writing C++ mock classes.
// //
// This file implements Matcher<const string&>, Matcher<string>, and // This file implements Matcher<const string&>, Matcher<string>, and

View File

@ -27,7 +27,6 @@
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// Google Mock - a framework for writing C++ mock classes. // Google Mock - a framework for writing C++ mock classes.
// //
// This file implements the spec builder syntax (ON_CALL and // This file implements the spec builder syntax (ON_CALL and
@ -49,15 +48,15 @@
#include "gtest/internal/gtest-port.h" #include "gtest/internal/gtest-port.h"
#if GTEST_OS_CYGWIN || GTEST_OS_LINUX || GTEST_OS_MAC #if GTEST_OS_CYGWIN || GTEST_OS_LINUX || GTEST_OS_MAC
# include <unistd.h> // NOLINT #include <unistd.h> // NOLINT
#endif #endif
// Silence C4800 (C4800: 'int *const ': forcing value // Silence C4800 (C4800: 'int *const ': forcing value
// to bool 'true' or 'false') for MSVC 15 // to bool 'true' or 'false') for MSVC 15
#ifdef _MSC_VER #ifdef _MSC_VER
#if _MSC_VER == 1900 #if _MSC_VER == 1900
# pragma warning(push) #pragma warning(push)
# pragma warning(disable:4800) #pragma warning(disable : 4800)
#endif #endif
#endif #endif
@ -195,11 +194,12 @@ void ExpectationBase::DescribeCallCountTo(::std::ostream* os) const
// Describes the state of the expectation (e.g. is it satisfied? // Describes the state of the expectation (e.g. is it satisfied?
// is it active?). // is it active?).
*os << " - " << (IsOverSaturated() ? "over-saturated" : *os << " - "
IsSaturated() ? "saturated" : << (IsOverSaturated() ? "over-saturated"
IsSatisfied() ? "satisfied" : "unsatisfied") : IsSaturated() ? "saturated"
<< " and " : IsSatisfied() ? "satisfied"
<< (is_retired() ? "retired" : "active"); : "unsatisfied")
<< " and " << (is_retired() ? "retired" : "active");
} }
// Checks the action count (i.e. the number of WillOnce() and // Checks the action count (i.e. the number of WillOnce() and
@ -242,13 +242,12 @@ void ExpectationBase::CheckActionCountIfNotDone() const
::std::stringstream ss; ::std::stringstream ss;
DescribeLocationTo(&ss); DescribeLocationTo(&ss);
ss << "Too " << (too_many ? "many" : "few") ss << "Too " << (too_many ? "many" : "few") << " actions specified in "
<< " actions specified in " << source_text() << "...\n" << source_text() << "...\n"
<< "Expected to be "; << "Expected to be ";
cardinality().DescribeTo(&ss); cardinality().DescribeTo(&ss);
ss << ", but has " << (too_many ? "" : "only ") ss << ", but has " << (too_many ? "" : "only ") << action_count
<< action_count << " WillOnce()" << " WillOnce()" << (action_count == 1 ? "" : "s");
<< (action_count == 1 ? "" : "s");
if (repeated_action_specified_) { if (repeated_action_specified_) {
ss << " and a WillRepeatedly()"; ss << " and a WillRepeatedly()";
} }
@ -398,11 +397,11 @@ UntypedActionResultHolderBase* UntypedFunctionMockerBase::UntypedInvokeWith(
// If the user wants this to be a warning, we print // If the user wants this to be a warning, we print
// it only when they want to see warnings. // it only when they want to see warnings.
reaction == kWarn reaction == kWarn
? LogIsVisible(kWarning) ? LogIsVisible(kWarning)
: :
// Otherwise, the user wants this to be an error, and we // Otherwise, the user wants this to be an error, and we
// should always print detailed information in the error. // should always print detailed information in the error.
true; true;
if (!need_to_report_uninteresting_call) { if (!need_to_report_uninteresting_call) {
// Perform the action without printing the call information. // Perform the action without printing the call information.
@ -505,8 +504,7 @@ UntypedActionResultHolderBase* UntypedFunctionMockerBase::UntypedInvokeWith(
Expectation UntypedFunctionMockerBase::GetHandleOf(ExpectationBase* exp) { Expectation UntypedFunctionMockerBase::GetHandleOf(ExpectationBase* exp) {
// See the definition of untyped_expectations_ for why access to it // See the definition of untyped_expectations_ for why access to it
// is unprotected here. // is unprotected here.
for (UntypedExpectations::const_iterator it = for (UntypedExpectations::const_iterator it = untyped_expectations_.begin();
untyped_expectations_.begin();
it != untyped_expectations_.end(); ++it) { it != untyped_expectations_.end(); ++it) {
if (it->get() == exp) { if (it->get() == exp) {
return Expectation(*it); return Expectation(*it);
@ -526,8 +524,7 @@ bool UntypedFunctionMockerBase::VerifyAndClearExpectationsLocked()
GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) { GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
g_gmock_mutex.AssertHeld(); g_gmock_mutex.AssertHeld();
bool expectations_met = true; bool expectations_met = true;
for (UntypedExpectations::const_iterator it = for (UntypedExpectations::const_iterator it = untyped_expectations_.begin();
untyped_expectations_.begin();
it != untyped_expectations_.end(); ++it) { it != untyped_expectations_.end(); ++it) {
ExpectationBase* const untyped_expectation = it->get(); ExpectationBase* const untyped_expectation = it->get();
if (untyped_expectation->IsOverSaturated()) { if (untyped_expectation->IsOverSaturated()) {
@ -538,15 +535,15 @@ bool UntypedFunctionMockerBase::VerifyAndClearExpectationsLocked()
} else if (!untyped_expectation->IsSatisfied()) { } else if (!untyped_expectation->IsSatisfied()) {
expectations_met = false; expectations_met = false;
::std::stringstream ss; ::std::stringstream ss;
ss << "Actual function call count doesn't match " ss << "Actual function call count doesn't match "
<< untyped_expectation->source_text() << "...\n"; << untyped_expectation->source_text() << "...\n";
// No need to show the source file location of the expectation // No need to show the source file location of the expectation
// in the description, as the Expect() call that follows already // in the description, as the Expect() call that follows already
// takes care of it. // takes care of it.
untyped_expectation->MaybeDescribeExtraMatcherTo(&ss); untyped_expectation->MaybeDescribeExtraMatcherTo(&ss);
untyped_expectation->DescribeCallCountTo(&ss); untyped_expectation->DescribeCallCountTo(&ss);
Expect(false, untyped_expectation->file(), Expect(false, untyped_expectation->file(), untyped_expectation->line(),
untyped_expectation->line(), ss.str()); ss.str());
} }
} }
@ -633,7 +630,7 @@ class MockObjectRegistry {
<< state.first_used_test << ")"; << state.first_used_test << ")";
} }
std::cout << " should be deleted but never is. Its address is @" std::cout << " should be deleted but never is. Its address is @"
<< it->first << "."; << it->first << ".";
leaked_count++; leaked_count++;
} }
if (leaked_count > 0) { 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 // Returns the reaction Google Mock will have on uninteresting calls
// made on the given mock object. // made on the given mock object.
internal::CallReaction Mock::GetReactionOnUninterestingCalls( internal::CallReaction Mock::GetReactionOnUninterestingCalls(
const void* mock_obj) const void* mock_obj) GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {
GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {
internal::MutexLock l(&internal::g_gmock_mutex); internal::MutexLock l(&internal::g_gmock_mutex);
return (g_uninteresting_call_reaction.count(mock_obj) == 0) return (g_uninteresting_call_reaction.count(mock_obj) == 0)
? internal::intToCallReaction( ? internal::intToCallReaction(
@ -873,8 +869,8 @@ Expectation::~Expectation() {}
void Sequence::AddExpectation(const Expectation& expectation) const { void Sequence::AddExpectation(const Expectation& expectation) const {
if (*last_expectation_ != expectation) { if (*last_expectation_ != expectation) {
if (last_expectation_->expectation_base() != nullptr) { if (last_expectation_->expectation_base() != nullptr) {
expectation.expectation_base()->immediate_prerequisites_ expectation.expectation_base()->immediate_prerequisites_ +=
+= *last_expectation_; *last_expectation_;
} }
*last_expectation_ = expectation; *last_expectation_ = expectation;
} }
@ -903,6 +899,6 @@ InSequence::~InSequence() {
#ifdef _MSC_VER #ifdef _MSC_VER
#if _MSC_VER == 1900 #if _MSC_VER == 1900
# pragma warning(pop) #pragma warning(pop)
#endif #endif
#endif #endif

View File

@ -27,8 +27,8 @@
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include "gmock/gmock.h" #include "gmock/gmock.h"
#include "gmock/internal/gmock-port.h" #include "gmock/internal/gmock-port.h"
GMOCK_DEFINE_bool_(catch_leaked_mocks, true, GMOCK_DEFINE_bool_(catch_leaked_mocks, true,

View File

@ -27,8 +27,8 @@
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include <iostream> #include <iostream>
#include "gmock/gmock.h" #include "gmock/gmock.h"
#include "gtest/gtest.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 // https://web.archive.org/web/20170912203238/connect.microsoft.com/VisualStudio/feedback/details/394464/wmain-link-error-in-the-static-library
// // NOLINT // // NOLINT
#if GTEST_OS_WINDOWS_MOBILE #if GTEST_OS_WINDOWS_MOBILE
# include <tchar.h> // NOLINT #include <tchar.h> // NOLINT
GTEST_API_ int _tmain(int argc, TCHAR** argv) { GTEST_API_ int _tmain(int argc, TCHAR** argv) {
#else #else

View File

@ -27,32 +27,33 @@
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// Google Mock - a framework for writing C++ mock classes. // Google Mock - a framework for writing C++ mock classes.
// //
// This file tests the built-in actions. // This file tests the built-in actions.
// Silence C4100 (unreferenced formal parameter) for MSVC // Silence C4100 (unreferenced formal parameter) for MSVC
#ifdef _MSC_VER #ifdef _MSC_VER
# pragma warning(push) #pragma warning(push)
# pragma warning(disable:4100) #pragma warning(disable : 4100)
#if _MSC_VER == 1900 #if _MSC_VER == 1900
// and silence C4800 (C4800: 'int *const ': forcing value // and silence C4800 (C4800: 'int *const ': forcing value
// to bool 'true' or 'false') for MSVC 15 // to bool 'true' or 'false') for MSVC 15
# pragma warning(disable:4800) #pragma warning(disable : 4800)
#endif #endif
#endif #endif
#include "gmock/gmock-actions.h" #include "gmock/gmock-actions.h"
#include <algorithm> #include <algorithm>
#include <iterator> #include <iterator>
#include <memory> #include <memory>
#include <string> #include <string>
#include <type_traits> #include <type_traits>
#include "gmock/gmock.h" #include "gmock/gmock.h"
#include "gmock/internal/gmock-port.h" #include "gmock/internal/gmock-port.h"
#include "gtest/gtest.h"
#include "gtest/gtest-spi.h" #include "gtest/gtest-spi.h"
#include "gtest/gtest.h"
namespace { namespace {
@ -114,17 +115,17 @@ TEST(BuiltInDefaultValueTest, IsZeroForNumericTypes) {
#endif #endif
#endif #endif
EXPECT_EQ(0U, BuiltInDefaultValue<unsigned short>::Get()); // NOLINT EXPECT_EQ(0U, BuiltInDefaultValue<unsigned short>::Get()); // NOLINT
EXPECT_EQ(0, BuiltInDefaultValue<signed short>::Get()); // NOLINT EXPECT_EQ(0, BuiltInDefaultValue<signed short>::Get()); // NOLINT
EXPECT_EQ(0, BuiltInDefaultValue<short>::Get()); // NOLINT EXPECT_EQ(0, BuiltInDefaultValue<short>::Get()); // NOLINT
EXPECT_EQ(0U, BuiltInDefaultValue<unsigned int>::Get()); EXPECT_EQ(0U, BuiltInDefaultValue<unsigned int>::Get());
EXPECT_EQ(0, BuiltInDefaultValue<signed int>::Get()); EXPECT_EQ(0, BuiltInDefaultValue<signed int>::Get());
EXPECT_EQ(0, BuiltInDefaultValue<int>::Get()); EXPECT_EQ(0, BuiltInDefaultValue<int>::Get());
EXPECT_EQ(0U, BuiltInDefaultValue<unsigned long>::Get()); // NOLINT EXPECT_EQ(0U, BuiltInDefaultValue<unsigned long>::Get()); // NOLINT
EXPECT_EQ(0, BuiltInDefaultValue<signed long>::Get()); // NOLINT EXPECT_EQ(0, BuiltInDefaultValue<signed long>::Get()); // NOLINT
EXPECT_EQ(0, BuiltInDefaultValue<long>::Get()); // NOLINT EXPECT_EQ(0, BuiltInDefaultValue<long>::Get()); // NOLINT
EXPECT_EQ(0U, BuiltInDefaultValue<unsigned long 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<signed long long>::Get()); // NOLINT
EXPECT_EQ(0, BuiltInDefaultValue<long long>::Get()); // NOLINT EXPECT_EQ(0, BuiltInDefaultValue<long long>::Get()); // NOLINT
EXPECT_EQ(0, BuiltInDefaultValue<float>::Get()); EXPECT_EQ(0, BuiltInDefaultValue<float>::Get());
EXPECT_EQ(0, BuiltInDefaultValue<double>::Get()); EXPECT_EQ(0, BuiltInDefaultValue<double>::Get());
} }
@ -139,17 +140,17 @@ TEST(BuiltInDefaultValueTest, ExistsForNumericTypes) {
EXPECT_TRUE(BuiltInDefaultValue<wchar_t>::Exists()); EXPECT_TRUE(BuiltInDefaultValue<wchar_t>::Exists());
#endif #endif
EXPECT_TRUE(BuiltInDefaultValue<unsigned short>::Exists()); // NOLINT EXPECT_TRUE(BuiltInDefaultValue<unsigned short>::Exists()); // NOLINT
EXPECT_TRUE(BuiltInDefaultValue<signed short>::Exists()); // NOLINT EXPECT_TRUE(BuiltInDefaultValue<signed short>::Exists()); // NOLINT
EXPECT_TRUE(BuiltInDefaultValue<short>::Exists()); // NOLINT EXPECT_TRUE(BuiltInDefaultValue<short>::Exists()); // NOLINT
EXPECT_TRUE(BuiltInDefaultValue<unsigned int>::Exists()); EXPECT_TRUE(BuiltInDefaultValue<unsigned int>::Exists());
EXPECT_TRUE(BuiltInDefaultValue<signed int>::Exists()); EXPECT_TRUE(BuiltInDefaultValue<signed int>::Exists());
EXPECT_TRUE(BuiltInDefaultValue<int>::Exists()); EXPECT_TRUE(BuiltInDefaultValue<int>::Exists());
EXPECT_TRUE(BuiltInDefaultValue<unsigned long>::Exists()); // NOLINT EXPECT_TRUE(BuiltInDefaultValue<unsigned long>::Exists()); // NOLINT
EXPECT_TRUE(BuiltInDefaultValue<signed long>::Exists()); // NOLINT EXPECT_TRUE(BuiltInDefaultValue<signed long>::Exists()); // NOLINT
EXPECT_TRUE(BuiltInDefaultValue<long>::Exists()); // NOLINT EXPECT_TRUE(BuiltInDefaultValue<long>::Exists()); // NOLINT
EXPECT_TRUE(BuiltInDefaultValue<unsigned long long>::Exists()); // NOLINT EXPECT_TRUE(BuiltInDefaultValue<unsigned long long>::Exists()); // NOLINT
EXPECT_TRUE(BuiltInDefaultValue<signed long long>::Exists()); // NOLINT EXPECT_TRUE(BuiltInDefaultValue<signed long long>::Exists()); // NOLINT
EXPECT_TRUE(BuiltInDefaultValue<long long>::Exists()); // NOLINT EXPECT_TRUE(BuiltInDefaultValue<long long>::Exists()); // NOLINT
EXPECT_TRUE(BuiltInDefaultValue<float>::Exists()); EXPECT_TRUE(BuiltInDefaultValue<float>::Exists());
EXPECT_TRUE(BuiltInDefaultValue<double>::Exists()); EXPECT_TRUE(BuiltInDefaultValue<double>::Exists());
} }
@ -167,13 +168,13 @@ TEST(BuiltInDefaultValueTest, BoolExists) {
// Tests that BuiltInDefaultValue<T>::Get() returns "" when T is a // Tests that BuiltInDefaultValue<T>::Get() returns "" when T is a
// string type. // string type.
TEST(BuiltInDefaultValueTest, IsEmptyStringForString) { 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 // Tests that BuiltInDefaultValue<T>::Exists() returns true when T is a
// string type. // string type.
TEST(BuiltInDefaultValueTest, ExistsForString) { TEST(BuiltInDefaultValueTest, ExistsForString) {
EXPECT_TRUE(BuiltInDefaultValue< ::std::string>::Exists()); EXPECT_TRUE(BuiltInDefaultValue<::std::string>::Exists());
} }
// Tests that BuiltInDefaultValue<const T>::Get() returns the same // Tests that BuiltInDefaultValue<const T>::Get() returns the same
@ -208,7 +209,6 @@ class MyNonDefaultConstructible {
int value_; int value_;
}; };
TEST(BuiltInDefaultValueTest, ExistsForDefaultConstructibleType) { TEST(BuiltInDefaultValueTest, ExistsForDefaultConstructibleType) {
EXPECT_TRUE(BuiltInDefaultValue<MyDefaultConstructible>::Exists()); EXPECT_TRUE(BuiltInDefaultValue<MyDefaultConstructible>::Exists());
} }
@ -217,25 +217,19 @@ TEST(BuiltInDefaultValueTest, IsDefaultConstructedForDefaultConstructibleType) {
EXPECT_EQ(42, BuiltInDefaultValue<MyDefaultConstructible>::Get().value()); EXPECT_EQ(42, BuiltInDefaultValue<MyDefaultConstructible>::Get().value());
} }
TEST(BuiltInDefaultValueTest, DoesNotExistForNonDefaultConstructibleType) { TEST(BuiltInDefaultValueTest, DoesNotExistForNonDefaultConstructibleType) {
EXPECT_FALSE(BuiltInDefaultValue<MyNonDefaultConstructible>::Exists()); EXPECT_FALSE(BuiltInDefaultValue<MyNonDefaultConstructible>::Exists());
} }
// Tests that BuiltInDefaultValue<T&>::Get() aborts the program. // Tests that BuiltInDefaultValue<T&>::Get() aborts the program.
TEST(BuiltInDefaultValueDeathTest, IsUndefinedForReferences) { TEST(BuiltInDefaultValueDeathTest, IsUndefinedForReferences) {
EXPECT_DEATH_IF_SUPPORTED({ EXPECT_DEATH_IF_SUPPORTED({ BuiltInDefaultValue<int&>::Get(); }, "");
BuiltInDefaultValue<int&>::Get(); EXPECT_DEATH_IF_SUPPORTED({ BuiltInDefaultValue<const char&>::Get(); }, "");
}, "");
EXPECT_DEATH_IF_SUPPORTED({
BuiltInDefaultValue<const char&>::Get();
}, "");
} }
TEST(BuiltInDefaultValueDeathTest, IsUndefinedForNonDefaultConstructibleType) { TEST(BuiltInDefaultValueDeathTest, IsUndefinedForNonDefaultConstructibleType) {
EXPECT_DEATH_IF_SUPPORTED({ EXPECT_DEATH_IF_SUPPORTED(
BuiltInDefaultValue<MyNonDefaultConstructible>::Get(); { BuiltInDefaultValue<MyNonDefaultConstructible>::Get(); }, "");
}, "");
} }
// Tests that DefaultValue<T>::IsSet() is false initially. // Tests that DefaultValue<T>::IsSet() is false initially.
@ -281,26 +275,22 @@ TEST(DefaultValueDeathTest, GetReturnsBuiltInDefaultValueWhenUnset) {
EXPECT_EQ(0, DefaultValue<int>::Get()); EXPECT_EQ(0, DefaultValue<int>::Get());
EXPECT_DEATH_IF_SUPPORTED({ EXPECT_DEATH_IF_SUPPORTED({ DefaultValue<MyNonDefaultConstructible>::Get(); },
DefaultValue<MyNonDefaultConstructible>::Get(); "");
}, "");
} }
TEST(DefaultValueTest, GetWorksForMoveOnlyIfSet) { TEST(DefaultValueTest, GetWorksForMoveOnlyIfSet) {
EXPECT_TRUE(DefaultValue<std::unique_ptr<int>>::Exists()); EXPECT_TRUE(DefaultValue<std::unique_ptr<int>>::Exists());
EXPECT_TRUE(DefaultValue<std::unique_ptr<int>>::Get() == nullptr); EXPECT_TRUE(DefaultValue<std::unique_ptr<int>>::Get() == nullptr);
DefaultValue<std::unique_ptr<int>>::SetFactory([] { DefaultValue<std::unique_ptr<int>>::SetFactory(
return std::unique_ptr<int>(new int(42)); [] { return std::unique_ptr<int>(new int(42)); });
});
EXPECT_TRUE(DefaultValue<std::unique_ptr<int>>::Exists()); EXPECT_TRUE(DefaultValue<std::unique_ptr<int>>::Exists());
std::unique_ptr<int> i = DefaultValue<std::unique_ptr<int>>::Get(); std::unique_ptr<int> i = DefaultValue<std::unique_ptr<int>>::Get();
EXPECT_EQ(42, *i); EXPECT_EQ(42, *i);
} }
// Tests that DefaultValue<void>::Get() returns void. // Tests that DefaultValue<void>::Get() returns void.
TEST(DefaultValueTest, GetWorksForVoid) { TEST(DefaultValueTest, GetWorksForVoid) { return DefaultValue<void>::Get(); }
return DefaultValue<void>::Get();
}
// Tests using DefaultValue with a reference type. // Tests using DefaultValue with a reference type.
@ -348,12 +338,9 @@ TEST(DefaultValueOfReferenceDeathTest, GetReturnsBuiltInDefaultValueWhenUnset) {
EXPECT_FALSE(DefaultValue<int&>::IsSet()); EXPECT_FALSE(DefaultValue<int&>::IsSet());
EXPECT_FALSE(DefaultValue<MyNonDefaultConstructible&>::IsSet()); EXPECT_FALSE(DefaultValue<MyNonDefaultConstructible&>::IsSet());
EXPECT_DEATH_IF_SUPPORTED({ EXPECT_DEATH_IF_SUPPORTED({ DefaultValue<int&>::Get(); }, "");
DefaultValue<int&>::Get(); EXPECT_DEATH_IF_SUPPORTED({ DefaultValue<MyNonDefaultConstructible>::Get(); },
}, ""); "");
EXPECT_DEATH_IF_SUPPORTED({
DefaultValue<MyNonDefaultConstructible>::Get();
}, "");
} }
// Tests that ActionInterface can be implemented by defining the // Tests that ActionInterface can be implemented by defining the
@ -433,7 +420,7 @@ class IsNotZero : public ActionInterface<bool(int)> { // NOLINT
}; };
TEST(ActionTest, CanBeConvertedToOtherActionType) { 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 const Action<int(char)> a2 = Action<int(char)>(a1); // NOLINT
EXPECT_EQ(1, a2.Perform(std::make_tuple('a'))); EXPECT_EQ(1, a2.Perform(std::make_tuple('a')));
EXPECT_EQ(0, a2.Perform(std::make_tuple('\0'))); 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 // Test struct which wraps a vector of integers. Used in
// 'SupportsWrapperReturnType' test. // 'SupportsWrapperReturnType' test.
struct IntegerVectorWrapper { struct IntegerVectorWrapper {
std::vector<int> * v; std::vector<int>* v;
IntegerVectorWrapper(std::vector<int>& _v) : v(&_v) {} // NOLINT IntegerVectorWrapper(std::vector<int>& _v) : v(&_v) {} // NOLINT
}; };
@ -648,7 +635,9 @@ TEST(ReturnRefTest, IsCovariant) {
} }
template <typename T, typename = decltype(ReturnRef(std::declval<T&&>()))> template <typename T, typename = decltype(ReturnRef(std::declval<T&&>()))>
bool CanCallReturnRef(T&&) { return true; } bool CanCallReturnRef(T&&) {
return true;
}
bool CanCallReturnRef(Unused) { return false; } bool CanCallReturnRef(Unused) { return false; }
// Tests that ReturnRef(v) is working with non-temporaries (T&) // 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&&) // Tests that ReturnRef(v) is not working with temporaries (T&&)
TEST(ReturnRefTest, DoesNotWorkForTemporary) { TEST(ReturnRefTest, DoesNotWorkForTemporary) {
auto scalar_value = []() -> int { return 123; }; auto scalar_value = []() -> int { return 123; };
EXPECT_FALSE(CanCallReturnRef(scalar_value())); EXPECT_FALSE(CanCallReturnRef(scalar_value()));
auto non_scalar_value = []() -> std::string { return "ABC"; }; auto non_scalar_value = []() -> std::string { return "ABC"; };
@ -754,8 +743,7 @@ class MockClass {
// return type by default. // return type by default.
TEST(DoDefaultTest, ReturnsBuiltInDefaultValueByDefault) { TEST(DoDefaultTest, ReturnsBuiltInDefaultValueByDefault) {
MockClass mock; MockClass mock;
EXPECT_CALL(mock, IntFunc(_)) EXPECT_CALL(mock, IntFunc(_)).WillOnce(DoDefault());
.WillOnce(DoDefault());
EXPECT_EQ(0, mock.IntFunc(true)); 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. // the process when there is no built-in default value for the return type.
TEST(DoDefaultDeathTest, DiesForUnknowType) { TEST(DoDefaultDeathTest, DiesForUnknowType) {
MockClass mock; MockClass mock;
EXPECT_CALL(mock, Foo()) EXPECT_CALL(mock, Foo()).WillRepeatedly(DoDefault());
.WillRepeatedly(DoDefault());
#if GTEST_HAS_EXCEPTIONS #if GTEST_HAS_EXCEPTIONS
EXPECT_ANY_THROW(mock.Foo()); EXPECT_ANY_THROW(mock.Foo());
#else #else
EXPECT_DEATH_IF_SUPPORTED({ EXPECT_DEATH_IF_SUPPORTED({ mock.Foo(); }, "");
mock.Foo();
}, "");
#endif #endif
} }
@ -782,16 +767,13 @@ void VoidFunc(bool /* flag */) {}
TEST(DoDefaultDeathTest, DiesIfUsedInCompositeAction) { TEST(DoDefaultDeathTest, DiesIfUsedInCompositeAction) {
MockClass mock; MockClass mock;
EXPECT_CALL(mock, IntFunc(_)) EXPECT_CALL(mock, IntFunc(_))
.WillRepeatedly(DoAll(Invoke(VoidFunc), .WillRepeatedly(DoAll(Invoke(VoidFunc), DoDefault()));
DoDefault()));
// Ideally we should verify the error message as well. Sadly, // Ideally we should verify the error message as well. Sadly,
// EXPECT_DEATH() can only capture stderr, while Google Mock's // EXPECT_DEATH() can only capture stderr, while Google Mock's
// errors are printed on stdout. Therefore we have to settle for // errors are printed on stdout. Therefore we have to settle for
// not verifying the message. // not verifying the message.
EXPECT_DEATH_IF_SUPPORTED({ EXPECT_DEATH_IF_SUPPORTED({ mock.IntFunc(true); }, "");
mock.IntFunc(true);
}, "");
} }
// Tests that DoDefault() returns the default value set by // Tests that DoDefault() returns the default value set by
@ -799,8 +781,7 @@ TEST(DoDefaultDeathTest, DiesIfUsedInCompositeAction) {
TEST(DoDefaultTest, ReturnsUserSpecifiedPerTypeDefaultValueWhenThereIsOne) { TEST(DoDefaultTest, ReturnsUserSpecifiedPerTypeDefaultValueWhenThereIsOne) {
DefaultValue<int>::Set(1); DefaultValue<int>::Set(1);
MockClass mock; MockClass mock;
EXPECT_CALL(mock, IntFunc(_)) EXPECT_CALL(mock, IntFunc(_)).WillOnce(DoDefault());
.WillOnce(DoDefault());
EXPECT_EQ(1, mock.IntFunc(false)); EXPECT_EQ(1, mock.IntFunc(false));
DefaultValue<int>::Clear(); DefaultValue<int>::Clear();
} }
@ -808,20 +789,19 @@ TEST(DoDefaultTest, ReturnsUserSpecifiedPerTypeDefaultValueWhenThereIsOne) {
// Tests that DoDefault() does the action specified by ON_CALL(). // Tests that DoDefault() does the action specified by ON_CALL().
TEST(DoDefaultTest, DoesWhatOnCallSpecifies) { TEST(DoDefaultTest, DoesWhatOnCallSpecifies) {
MockClass mock; MockClass mock;
ON_CALL(mock, IntFunc(_)) ON_CALL(mock, IntFunc(_)).WillByDefault(Return(2));
.WillByDefault(Return(2)); EXPECT_CALL(mock, IntFunc(_)).WillOnce(DoDefault());
EXPECT_CALL(mock, IntFunc(_))
.WillOnce(DoDefault());
EXPECT_EQ(2, mock.IntFunc(false)); EXPECT_EQ(2, mock.IntFunc(false));
} }
// Tests that using DoDefault() in ON_CALL() leads to a run-time failure. // Tests that using DoDefault() in ON_CALL() leads to a run-time failure.
TEST(DoDefaultTest, CannotBeUsedInOnCall) { TEST(DoDefaultTest, CannotBeUsedInOnCall) {
MockClass mock; MockClass mock;
EXPECT_NONFATAL_FAILURE({ // NOLINT EXPECT_NONFATAL_FAILURE(
ON_CALL(mock, IntFunc(_)) { // NOLINT
.WillByDefault(DoDefault()); ON_CALL(mock, IntFunc(_)).WillByDefault(DoDefault());
}, "DoDefault() cannot be used in ON_CALL()"); },
"DoDefault() cannot be used in ON_CALL()");
} }
// Tests that SetArgPointee<N>(v) sets the variable pointed to by // Tests that SetArgPointee<N>(v) sets the variable pointed to by
@ -868,7 +848,7 @@ TEST(SetArgPointeeTest, AcceptsWideStringLiteral) {
a.Perform(std::make_tuple(&ptr)); a.Perform(std::make_tuple(&ptr));
EXPECT_STREQ(L"world", ptr); EXPECT_STREQ(L"world", ptr);
# if GTEST_HAS_STD_WSTRING #if GTEST_HAS_STD_WSTRING
typedef void MyStringFunction(std::wstring*); typedef void MyStringFunction(std::wstring*);
Action<MyStringFunction> a2 = SetArgPointee<0>(L"world"); Action<MyStringFunction> a2 = SetArgPointee<0>(L"world");
@ -876,7 +856,7 @@ TEST(SetArgPointeeTest, AcceptsWideStringLiteral) {
a2.Perform(std::make_tuple(&str)); a2.Perform(std::make_tuple(&str));
EXPECT_EQ(L"world", str); EXPECT_EQ(L"world", str);
# endif #endif
} }
// Tests that SetArgPointee<N>() accepts a char pointer. // Tests that SetArgPointee<N>() accepts a char pointer.
@ -907,7 +887,7 @@ TEST(SetArgPointeeTest, AcceptsWideCharPointer) {
a.Perform(std::make_tuple(true, &ptr)); a.Perform(std::make_tuple(true, &ptr));
EXPECT_EQ(hi, ptr); EXPECT_EQ(hi, ptr);
# if GTEST_HAS_STD_WSTRING #if GTEST_HAS_STD_WSTRING
typedef void MyStringFunction(bool, std::wstring*); typedef void MyStringFunction(bool, std::wstring*);
wchar_t world_array[] = L"world"; wchar_t world_array[] = L"world";
@ -916,7 +896,7 @@ TEST(SetArgPointeeTest, AcceptsWideCharPointer) {
std::wstring str; std::wstring str;
a2.Perform(std::make_tuple(true, &str)); a2.Perform(std::make_tuple(true, &str));
EXPECT_EQ(world_array, str); EXPECT_EQ(world_array, str);
# endif #endif
} }
// Tests that SetArgumentPointee<N>(v) sets the variable pointed to by // Tests that SetArgumentPointee<N>(v) sets the variable pointed to by
@ -1079,7 +1059,6 @@ TEST(AssignTest, CompatibleTypes) {
EXPECT_DOUBLE_EQ(5, x); EXPECT_DOUBLE_EQ(5, x);
} }
// Tests using WithArgs and with an action that takes 1 argument. // Tests using WithArgs and with an action that takes 1 argument.
TEST(WithArgsTest, OneArg) { TEST(WithArgsTest, OneArg) {
Action<bool(double x, int n)> a = WithArgs<1>(Invoke(Unary)); // NOLINT Action<bool(double x, int n)> a = WithArgs<1>(Invoke(Unary)); // NOLINT
@ -1235,7 +1214,7 @@ TEST(ByRefTest, IsCopyable) {
TEST(ByRefTest, ConstValue) { TEST(ByRefTest, ConstValue) {
const int n = 0; const int n = 0;
// int& ref = ByRef(n); // This shouldn't compile - we have a // 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); const int& const_ref = ByRef(n);
EXPECT_EQ(&n, &const_ref); EXPECT_EQ(&n, &const_ref);
} }
@ -1260,7 +1239,7 @@ TEST(ByRefTest, ExplicitType) {
EXPECT_EQ(&n, &r1); EXPECT_EQ(&n, &r1);
// ByRef<char>(n); // This shouldn't compile - we have a negative // ByRef<char>(n); // This shouldn't compile - we have a negative
// compilation test to catch it. // compilation test to catch it.
Derived d; Derived d;
Derived& r2 = ByRef<Derived>(d); Derived& r2 = ByRef<Derived>(d);
@ -1375,9 +1354,10 @@ TEST(MockMethodTest, CanReturnMoveOnlyValue_DoAllReturn) {
MockClass mock; MockClass mock;
std::unique_ptr<int> i(new int(19)); std::unique_ptr<int> i(new int(19));
EXPECT_CALL(mock_function, Call()); EXPECT_CALL(mock_function, Call());
EXPECT_CALL(mock, MakeUnique()).WillOnce(DoAll( EXPECT_CALL(mock, MakeUnique())
InvokeWithoutArgs(&mock_function, &testing::MockFunction<void()>::Call), .WillOnce(DoAll(InvokeWithoutArgs(&mock_function,
Return(ByMove(std::move(i))))); &testing::MockFunction<void()>::Call),
Return(ByMove(std::move(i)))));
std::unique_ptr<int> result1 = mock.MakeUnique(); std::unique_ptr<int> result1 = mock.MakeUnique();
EXPECT_EQ(19, *result1); EXPECT_EQ(19, *result1);
@ -1387,9 +1367,8 @@ TEST(MockMethodTest, CanReturnMoveOnlyValue_Invoke) {
MockClass mock; MockClass mock;
// Check default value // Check default value
DefaultValue<std::unique_ptr<int>>::SetFactory([] { DefaultValue<std::unique_ptr<int>>::SetFactory(
return std::unique_ptr<int>(new int(42)); [] { return std::unique_ptr<int>(new int(42)); });
});
EXPECT_EQ(42, *mock.MakeUnique()); EXPECT_EQ(42, *mock.MakeUnique());
EXPECT_CALL(mock, MakeUnique()).WillRepeatedly(Invoke(UniquePtrSource)); EXPECT_CALL(mock, MakeUnique()).WillRepeatedly(Invoke(UniquePtrSource));
@ -1449,7 +1428,6 @@ TEST(MockMethodTest, CanTakeMoveOnlyValue) {
EXPECT_EQ(42, *saved); EXPECT_EQ(42, *saved);
} }
// Tests for std::function based action. // Tests for std::function based action.
int Add(int val, int& ref, int* ptr) { // NOLINT int Add(int val, int& ref, int* ptr) { // NOLINT
@ -1463,7 +1441,9 @@ int Deref(std::unique_ptr<int> ptr) { return *ptr; }
struct Double { struct Double {
template <typename T> template <typename T>
T operator()(T t) { return 2 * t; } T operator()(T t) {
return 2 * t;
}
}; };
std::unique_ptr<int> UniqueInt(int i) { std::unique_ptr<int> UniqueInt(int i) {
@ -1532,8 +1512,9 @@ TEST(FunctorActionTest, TypeConversion) {
TEST(FunctorActionTest, UnusedArguments) { TEST(FunctorActionTest, UnusedArguments) {
// Verify that users can ignore uninteresting arguments. // Verify that users can ignore uninteresting arguments.
Action<int(int, double y, double z)> a = Action<int(int, double y, double z)> a = [](int i, Unused, Unused) {
[](int i, Unused, Unused) { return 2 * i; }; return 2 * i;
};
std::tuple<int, double, double> dummy = std::make_tuple(3, 7.3, 9.44); std::tuple<int, double, double> dummy = std::make_tuple(3, 7.3, 9.44);
EXPECT_EQ(6, a.Perform(dummy)); EXPECT_EQ(6, a.Perform(dummy));
} }
@ -1552,9 +1533,7 @@ TEST(MoveOnlyArgumentsTest, ReturningActions) {
EXPECT_EQ(x, 3); EXPECT_EQ(x, 3);
} }
ACTION(ReturnArity) { ACTION(ReturnArity) { return std::tuple_size<args_type>::value; }
return std::tuple_size<args_type>::value;
}
TEST(ActionMacro, LargeArity) { TEST(ActionMacro, LargeArity) {
EXPECT_EQ( EXPECT_EQ(
@ -1577,7 +1556,6 @@ TEST(ActionMacro, LargeArity) {
#ifdef _MSC_VER #ifdef _MSC_VER
#if _MSC_VER == 1900 #if _MSC_VER == 1900
# pragma warning(pop) #pragma warning(pop)
#endif #endif
#endif #endif

View File

@ -27,14 +27,13 @@
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// Google Mock - a framework for writing C++ mock classes. // Google Mock - a framework for writing C++ mock classes.
// //
// This file tests the built-in cardinalities. // This file tests the built-in cardinalities.
#include "gmock/gmock.h" #include "gmock/gmock.h"
#include "gtest/gtest.h"
#include "gtest/gtest-spi.h" #include "gtest/gtest-spi.h"
#include "gtest/gtest.h"
namespace { namespace {
@ -59,9 +58,7 @@ class MockFoo {
}; };
// Tests that Cardinality objects can be default constructed. // Tests that Cardinality objects can be default constructed.
TEST(CardinalityTest, IsDefaultConstructable) { TEST(CardinalityTest, IsDefaultConstructable) { Cardinality c; }
Cardinality c;
}
// Tests that Cardinality objects are copyable. // Tests that Cardinality objects are copyable.
TEST(CardinalityTest, IsCopyable) { TEST(CardinalityTest, IsCopyable) {
@ -119,8 +116,7 @@ TEST(AnyNumber, Works) {
stringstream ss; stringstream ss;
c.DescribeTo(&ss); c.DescribeTo(&ss);
EXPECT_PRED_FORMAT2(IsSubstring, "called any number of times", EXPECT_PRED_FORMAT2(IsSubstring, "called any number of times", ss.str());
ss.str());
} }
TEST(AnyNumberTest, HasCorrectBounds) { TEST(AnyNumberTest, HasCorrectBounds) {
@ -132,9 +128,11 @@ TEST(AnyNumberTest, HasCorrectBounds) {
// Tests AtLeast(n). // Tests AtLeast(n).
TEST(AtLeastTest, OnNegativeNumber) { TEST(AtLeastTest, OnNegativeNumber) {
EXPECT_NONFATAL_FAILURE({ // NOLINT EXPECT_NONFATAL_FAILURE(
AtLeast(-1); { // NOLINT
}, "The invocation lower bound must be >= 0"); AtLeast(-1);
},
"The invocation lower bound must be >= 0");
} }
TEST(AtLeastTest, OnZero) { TEST(AtLeastTest, OnZero) {
@ -147,8 +145,7 @@ TEST(AtLeastTest, OnZero) {
stringstream ss; stringstream ss;
c.DescribeTo(&ss); c.DescribeTo(&ss);
EXPECT_PRED_FORMAT2(IsSubstring, "any number of times", EXPECT_PRED_FORMAT2(IsSubstring, "any number of times", ss.str());
ss.str());
} }
TEST(AtLeastTest, OnPositiveNumber) { TEST(AtLeastTest, OnPositiveNumber) {
@ -164,18 +161,15 @@ TEST(AtLeastTest, OnPositiveNumber) {
stringstream ss1; stringstream ss1;
AtLeast(1).DescribeTo(&ss1); AtLeast(1).DescribeTo(&ss1);
EXPECT_PRED_FORMAT2(IsSubstring, "at least once", EXPECT_PRED_FORMAT2(IsSubstring, "at least once", ss1.str());
ss1.str());
stringstream ss2; stringstream ss2;
c.DescribeTo(&ss2); c.DescribeTo(&ss2);
EXPECT_PRED_FORMAT2(IsSubstring, "at least twice", EXPECT_PRED_FORMAT2(IsSubstring, "at least twice", ss2.str());
ss2.str());
stringstream ss3; stringstream ss3;
AtLeast(3).DescribeTo(&ss3); AtLeast(3).DescribeTo(&ss3);
EXPECT_PRED_FORMAT2(IsSubstring, "at least 3 times", EXPECT_PRED_FORMAT2(IsSubstring, "at least 3 times", ss3.str());
ss3.str());
} }
TEST(AtLeastTest, HasCorrectBounds) { TEST(AtLeastTest, HasCorrectBounds) {
@ -187,9 +181,11 @@ TEST(AtLeastTest, HasCorrectBounds) {
// Tests AtMost(n). // Tests AtMost(n).
TEST(AtMostTest, OnNegativeNumber) { TEST(AtMostTest, OnNegativeNumber) {
EXPECT_NONFATAL_FAILURE({ // NOLINT EXPECT_NONFATAL_FAILURE(
AtMost(-1); { // NOLINT
}, "The invocation upper bound must be >= 0"); AtMost(-1);
},
"The invocation upper bound must be >= 0");
} }
TEST(AtMostTest, OnZero) { TEST(AtMostTest, OnZero) {
@ -202,8 +198,7 @@ TEST(AtMostTest, OnZero) {
stringstream ss; stringstream ss;
c.DescribeTo(&ss); c.DescribeTo(&ss);
EXPECT_PRED_FORMAT2(IsSubstring, "never called", EXPECT_PRED_FORMAT2(IsSubstring, "never called", ss.str());
ss.str());
} }
TEST(AtMostTest, OnPositiveNumber) { TEST(AtMostTest, OnPositiveNumber) {
@ -219,18 +214,15 @@ TEST(AtMostTest, OnPositiveNumber) {
stringstream ss1; stringstream ss1;
AtMost(1).DescribeTo(&ss1); AtMost(1).DescribeTo(&ss1);
EXPECT_PRED_FORMAT2(IsSubstring, "called at most once", EXPECT_PRED_FORMAT2(IsSubstring, "called at most once", ss1.str());
ss1.str());
stringstream ss2; stringstream ss2;
c.DescribeTo(&ss2); c.DescribeTo(&ss2);
EXPECT_PRED_FORMAT2(IsSubstring, "called at most twice", EXPECT_PRED_FORMAT2(IsSubstring, "called at most twice", ss2.str());
ss2.str());
stringstream ss3; stringstream ss3;
AtMost(3).DescribeTo(&ss3); AtMost(3).DescribeTo(&ss3);
EXPECT_PRED_FORMAT2(IsSubstring, "called at most 3 times", EXPECT_PRED_FORMAT2(IsSubstring, "called at most 3 times", ss3.str());
ss3.str());
} }
TEST(AtMostTest, HasCorrectBounds) { TEST(AtMostTest, HasCorrectBounds) {
@ -242,22 +234,28 @@ TEST(AtMostTest, HasCorrectBounds) {
// Tests Between(m, n). // Tests Between(m, n).
TEST(BetweenTest, OnNegativeStart) { TEST(BetweenTest, OnNegativeStart) {
EXPECT_NONFATAL_FAILURE({ // NOLINT EXPECT_NONFATAL_FAILURE(
Between(-1, 2); { // NOLINT
}, "The invocation lower bound must be >= 0, but is actually -1"); Between(-1, 2);
},
"The invocation lower bound must be >= 0, but is actually -1");
} }
TEST(BetweenTest, OnNegativeEnd) { TEST(BetweenTest, OnNegativeEnd) {
EXPECT_NONFATAL_FAILURE({ // NOLINT EXPECT_NONFATAL_FAILURE(
Between(1, -2); { // NOLINT
}, "The invocation upper bound must be >= 0, but is actually -2"); Between(1, -2);
},
"The invocation upper bound must be >= 0, but is actually -2");
} }
TEST(BetweenTest, OnStartBiggerThanEnd) { TEST(BetweenTest, OnStartBiggerThanEnd) {
EXPECT_NONFATAL_FAILURE({ // NOLINT EXPECT_NONFATAL_FAILURE(
Between(2, 1); { // NOLINT
}, "The invocation upper bound (1) must be >= " Between(2, 1);
"the invocation lower bound (2)"); },
"The invocation upper bound (1) must be >= "
"the invocation lower bound (2)");
} }
TEST(BetweenTest, OnZeroStartAndZeroEnd) { TEST(BetweenTest, OnZeroStartAndZeroEnd) {
@ -271,8 +269,7 @@ TEST(BetweenTest, OnZeroStartAndZeroEnd) {
stringstream ss; stringstream ss;
c.DescribeTo(&ss); c.DescribeTo(&ss);
EXPECT_PRED_FORMAT2(IsSubstring, "never called", EXPECT_PRED_FORMAT2(IsSubstring, "never called", ss.str());
ss.str());
} }
TEST(BetweenTest, OnZeroStartAndNonZeroEnd) { TEST(BetweenTest, OnZeroStartAndNonZeroEnd) {
@ -289,8 +286,7 @@ TEST(BetweenTest, OnZeroStartAndNonZeroEnd) {
stringstream ss; stringstream ss;
c.DescribeTo(&ss); c.DescribeTo(&ss);
EXPECT_PRED_FORMAT2(IsSubstring, "called at most twice", EXPECT_PRED_FORMAT2(IsSubstring, "called at most twice", ss.str());
ss.str());
} }
TEST(BetweenTest, OnSameStartAndEnd) { TEST(BetweenTest, OnSameStartAndEnd) {
@ -307,8 +303,7 @@ TEST(BetweenTest, OnSameStartAndEnd) {
stringstream ss; stringstream ss;
c.DescribeTo(&ss); c.DescribeTo(&ss);
EXPECT_PRED_FORMAT2(IsSubstring, "called 3 times", EXPECT_PRED_FORMAT2(IsSubstring, "called 3 times", ss.str());
ss.str());
} }
TEST(BetweenTest, OnDifferentStartAndEnd) { TEST(BetweenTest, OnDifferentStartAndEnd) {
@ -328,8 +323,7 @@ TEST(BetweenTest, OnDifferentStartAndEnd) {
stringstream ss; stringstream ss;
c.DescribeTo(&ss); c.DescribeTo(&ss);
EXPECT_PRED_FORMAT2(IsSubstring, "called between 3 and 5 times", EXPECT_PRED_FORMAT2(IsSubstring, "called between 3 and 5 times", ss.str());
ss.str());
} }
TEST(BetweenTest, HasCorrectBounds) { TEST(BetweenTest, HasCorrectBounds) {
@ -341,9 +335,11 @@ TEST(BetweenTest, HasCorrectBounds) {
// Tests Exactly(n). // Tests Exactly(n).
TEST(ExactlyTest, OnNegativeNumber) { TEST(ExactlyTest, OnNegativeNumber) {
EXPECT_NONFATAL_FAILURE({ // NOLINT EXPECT_NONFATAL_FAILURE(
Exactly(-1); { // NOLINT
}, "The invocation lower bound must be >= 0"); Exactly(-1);
},
"The invocation lower bound must be >= 0");
} }
TEST(ExactlyTest, OnZero) { TEST(ExactlyTest, OnZero) {
@ -356,8 +352,7 @@ TEST(ExactlyTest, OnZero) {
stringstream ss; stringstream ss;
c.DescribeTo(&ss); c.DescribeTo(&ss);
EXPECT_PRED_FORMAT2(IsSubstring, "never called", EXPECT_PRED_FORMAT2(IsSubstring, "never called", ss.str());
ss.str());
} }
TEST(ExactlyTest, OnPositiveNumber) { TEST(ExactlyTest, OnPositiveNumber) {
@ -370,18 +365,15 @@ TEST(ExactlyTest, OnPositiveNumber) {
stringstream ss1; stringstream ss1;
Exactly(1).DescribeTo(&ss1); Exactly(1).DescribeTo(&ss1);
EXPECT_PRED_FORMAT2(IsSubstring, "called once", EXPECT_PRED_FORMAT2(IsSubstring, "called once", ss1.str());
ss1.str());
stringstream ss2; stringstream ss2;
c.DescribeTo(&ss2); c.DescribeTo(&ss2);
EXPECT_PRED_FORMAT2(IsSubstring, "called twice", EXPECT_PRED_FORMAT2(IsSubstring, "called twice", ss2.str());
ss2.str());
stringstream ss3; stringstream ss3;
Exactly(3).DescribeTo(&ss3); Exactly(3).DescribeTo(&ss3);
EXPECT_PRED_FORMAT2(IsSubstring, "called 3 times", EXPECT_PRED_FORMAT2(IsSubstring, "called 3 times", ss3.str());
ss3.str());
} }
TEST(ExactlyTest, HasCorrectBounds) { TEST(ExactlyTest, HasCorrectBounds) {

View File

@ -27,7 +27,6 @@
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// Google Mock - a framework for writing C++ mock classes. // Google Mock - a framework for writing C++ mock classes.
// //
// This file tests the function mocker 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 // 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 // we are getting compiler errors if we use basetyps.h, hence including
// objbase.h for definition of STDMETHOD. // objbase.h for definition of STDMETHOD.
# include <objbase.h> #include <objbase.h>
#endif // GTEST_OS_WINDOWS #endif // GTEST_OS_WINDOWS
#include <functional> #include <functional>
@ -65,7 +64,7 @@ using testing::Return;
using testing::ReturnRef; using testing::ReturnRef;
using testing::TypedEq; using testing::TypedEq;
template<typename T> template <typename T>
class TemplatedCopyable { class TemplatedCopyable {
public: public:
TemplatedCopyable() {} TemplatedCopyable() {}
@ -82,7 +81,7 @@ class FooInterface {
virtual int Nullary() = 0; virtual int Nullary() = 0;
virtual bool Unary(int x) = 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 virtual int Decimal(bool b, char c, short d, int e, long f, // NOLINT
float g, double h, unsigned i, char* j, float g, double h, unsigned i, char* j,
const std::string& k) = 0; const std::string& k) = 0;
@ -133,8 +132,8 @@ class FooInterface {
// signature. This was fixed in Visual Studio 2008. However, the compiler // signature. This was fixed in Visual Studio 2008. However, the compiler
// still emits a warning that alerts about this change in behavior. // still emits a warning that alerts about this change in behavior.
#ifdef _MSC_VER #ifdef _MSC_VER
# pragma warning(push) #pragma warning(push)
# pragma warning(disable : 4373) #pragma warning(disable : 4373)
#endif #endif
class MockFoo : public FooInterface { class MockFoo : public FooInterface {
public: public:
@ -279,7 +278,7 @@ class LegacyMockFoo : public FooInterface {
}; };
#ifdef _MSC_VER #ifdef _MSC_VER
# pragma warning(pop) #pragma warning(pop)
#endif #endif
template <class T> template <class T>
@ -595,10 +594,8 @@ TYPED_TEST(TemplateMockTest, Works) {
.WillOnce(Return(0)); .WillOnce(Return(0));
EXPECT_CALL(mock, Push(_)); EXPECT_CALL(mock, Push(_));
int n = 5; int n = 5;
EXPECT_CALL(mock, GetTop()) EXPECT_CALL(mock, GetTop()).WillOnce(ReturnRef(n));
.WillOnce(ReturnRef(n)); EXPECT_CALL(mock, Pop()).Times(AnyNumber());
EXPECT_CALL(mock, Pop())
.Times(AnyNumber());
EXPECT_EQ(0, mock.GetSize()); EXPECT_EQ(0, mock.GetSize());
mock.Push(5); mock.Push(5);
@ -612,10 +609,8 @@ TYPED_TEST(TemplateMockTest, MethodWithCommaInReturnTypeWorks) {
TypeParam mock; TypeParam mock;
const std::map<int, int> a_map; const std::map<int, int> a_map;
EXPECT_CALL(mock, ReturnTypeWithComma()) EXPECT_CALL(mock, ReturnTypeWithComma()).WillOnce(Return(a_map));
.WillOnce(Return(a_map)); EXPECT_CALL(mock, ReturnTypeWithComma(1)).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());
EXPECT_EQ(a_map, mock.ReturnTypeWithComma(1)); EXPECT_EQ(a_map, mock.ReturnTypeWithComma(1));
@ -685,10 +680,8 @@ TYPED_TEST(TemplateMockTestWithCallType, Works) {
.WillOnce(Return(0)); .WillOnce(Return(0));
EXPECT_CALL(mock, Push(_)); EXPECT_CALL(mock, Push(_));
int n = 5; int n = 5;
EXPECT_CALL(mock, GetTop()) EXPECT_CALL(mock, GetTop()).WillOnce(ReturnRef(n));
.WillOnce(ReturnRef(n)); EXPECT_CALL(mock, Pop()).Times(AnyNumber());
EXPECT_CALL(mock, Pop())
.Times(AnyNumber());
EXPECT_EQ(0, mock.GetSize()); EXPECT_EQ(0, mock.GetSize());
mock.Push(5); mock.Push(5);
@ -747,9 +740,9 @@ TYPED_TEST(OverloadedMockMethodTest, CanOverloadOnArgNumberInMacroBody) {
EXPECT_TRUE(mock.Overloaded(true, 1)); EXPECT_TRUE(mock.Overloaded(true, 1));
} }
#define MY_MOCK_METHODS2_ \ #define MY_MOCK_METHODS2_ \
MOCK_CONST_METHOD1(Overloaded, int(int n)); \ MOCK_CONST_METHOD1(Overloaded, int(int n)); \
MOCK_METHOD1(Overloaded, int(int n)) MOCK_METHOD1(Overloaded, int(int n))
class MockOverloadedOnConstness { class MockOverloadedOnConstness {
public: public:
@ -779,9 +772,7 @@ TEST(MockMethodMockFunctionTest, WorksForVoidNullary) {
TEST(MockMethodMockFunctionTest, WorksForNonVoidNullary) { TEST(MockMethodMockFunctionTest, WorksForNonVoidNullary) {
MockFunction<int()> foo; MockFunction<int()> foo;
EXPECT_CALL(foo, Call()) EXPECT_CALL(foo, Call()).WillOnce(Return(1)).WillOnce(Return(2));
.WillOnce(Return(1))
.WillOnce(Return(2));
EXPECT_EQ(1, foo.Call()); EXPECT_EQ(1, foo.Call());
EXPECT_EQ(2, foo.Call()); EXPECT_EQ(2, foo.Call());
} }
@ -794,19 +785,17 @@ TEST(MockMethodMockFunctionTest, WorksForVoidUnary) {
TEST(MockMethodMockFunctionTest, WorksForNonVoidBinary) { TEST(MockMethodMockFunctionTest, WorksForNonVoidBinary) {
MockFunction<int(bool, int)> foo; MockFunction<int(bool, int)> foo;
EXPECT_CALL(foo, Call(false, 42)) EXPECT_CALL(foo, Call(false, 42)).WillOnce(Return(1)).WillOnce(Return(2));
.WillOnce(Return(1)) EXPECT_CALL(foo, Call(true, Ge(100))).WillOnce(Return(3));
.WillOnce(Return(2));
EXPECT_CALL(foo, Call(true, Ge(100)))
.WillOnce(Return(3));
EXPECT_EQ(1, foo.Call(false, 42)); EXPECT_EQ(1, foo.Call(false, 42));
EXPECT_EQ(2, foo.Call(false, 42)); EXPECT_EQ(2, foo.Call(false, 42));
EXPECT_EQ(3, foo.Call(true, 120)); EXPECT_EQ(3, foo.Call(true, 120));
} }
TEST(MockMethodMockFunctionTest, WorksFor10Arguments) { TEST(MockMethodMockFunctionTest, WorksFor10Arguments) {
MockFunction<int(bool a0, char a1, int a2, int a3, int a4, MockFunction<int(bool a0, char a1, int a2, int a3, int a4, int a5, int a6,
int a5, int a6, char a7, int a8, bool a9)> foo; char a7, int a8, bool a9)>
foo;
EXPECT_CALL(foo, Call(_, 'a', _, _, _, _, _, _, _, _)) EXPECT_CALL(foo, Call(_, 'a', _, _, _, _, _, _, _, _))
.WillOnce(Return(1)) .WillOnce(Return(1))
.WillOnce(Return(2)); .WillOnce(Return(2));
@ -816,9 +805,7 @@ TEST(MockMethodMockFunctionTest, WorksFor10Arguments) {
TEST(MockMethodMockFunctionTest, AsStdFunction) { TEST(MockMethodMockFunctionTest, AsStdFunction) {
MockFunction<int(int)> foo; MockFunction<int(int)> foo;
auto call = [](const std::function<int(int)> &f, int i) { auto call = [](const std::function<int(int)>& f, int i) { return f(i); };
return f(i);
};
EXPECT_CALL(foo, Call(1)).WillOnce(Return(-1)); EXPECT_CALL(foo, Call(1)).WillOnce(Return(-1));
EXPECT_CALL(foo, Call(2)).WillOnce(Return(-2)); EXPECT_CALL(foo, Call(2)).WillOnce(Return(-2));
EXPECT_EQ(-1, call(foo.AsStdFunction(), 1)); EXPECT_EQ(-1, call(foo.AsStdFunction(), 1));
@ -836,10 +823,8 @@ TEST(MockMethodMockFunctionTest, AsStdFunctionReturnsReference) {
} }
TEST(MockMethodMockFunctionTest, AsStdFunctionWithReferenceParameter) { TEST(MockMethodMockFunctionTest, AsStdFunctionWithReferenceParameter) {
MockFunction<int(int &)> foo; MockFunction<int(int&)> foo;
auto call = [](const std::function<int(int& )> &f, int &i) { auto call = [](const std::function<int(int&)>& f, int& i) { return f(i); };
return f(i);
};
int i = 42; int i = 42;
EXPECT_CALL(foo, Call(i)).WillOnce(Return(-1)); EXPECT_CALL(foo, Call(i)).WillOnce(Return(-1));
EXPECT_EQ(-1, call(foo.AsStdFunction(), i)); EXPECT_EQ(-1, call(foo.AsStdFunction(), i));
@ -888,8 +873,7 @@ TYPED_TEST(
} }
template <typename F> template <typename F>
struct AlternateCallable { struct AlternateCallable {};
};
TYPED_TEST(MockMethodMockFunctionSignatureTest, TYPED_TEST(MockMethodMockFunctionSignatureTest,
IsMockFunctionTemplateArgumentDeducedForAlternateCallable) { IsMockFunctionTemplateArgumentDeducedForAlternateCallable) {
@ -898,16 +882,14 @@ TYPED_TEST(MockMethodMockFunctionSignatureTest,
EXPECT_TRUE(IsMockFunctionTemplateArgumentDeducedTo<TypeParam>(foo)); EXPECT_TRUE(IsMockFunctionTemplateArgumentDeducedTo<TypeParam>(foo));
} }
TYPED_TEST( TYPED_TEST(MockMethodMockFunctionSignatureTest,
MockMethodMockFunctionSignatureTest, IsMockFunctionCallMethodSignatureTheSameForAlternateCallable) {
IsMockFunctionCallMethodSignatureTheSameForAlternateCallable) {
using ForRawSignature = decltype(&MockFunction<TypeParam>::Call); using ForRawSignature = decltype(&MockFunction<TypeParam>::Call);
using ForStdFunction = using ForStdFunction =
decltype(&MockFunction<std::function<TypeParam>>::Call); decltype(&MockFunction<std::function<TypeParam>>::Call);
EXPECT_TRUE((std::is_same<ForRawSignature, ForStdFunction>::value)); EXPECT_TRUE((std::is_same<ForRawSignature, ForStdFunction>::value));
} }
struct MockMethodSizes0 { struct MockMethodSizes0 {
MOCK_METHOD(void, func, ()); MOCK_METHOD(void, func, ());
}; };
@ -925,22 +907,21 @@ struct MockMethodSizes4 {
}; };
struct LegacyMockMethodSizes0 { struct LegacyMockMethodSizes0 {
MOCK_METHOD0(func, void()); MOCK_METHOD0(func, void());
}; };
struct LegacyMockMethodSizes1 { struct LegacyMockMethodSizes1 {
MOCK_METHOD1(func, void(int)); MOCK_METHOD1(func, void(int));
}; };
struct LegacyMockMethodSizes2 { struct LegacyMockMethodSizes2 {
MOCK_METHOD2(func, void(int, int)); MOCK_METHOD2(func, void(int, int));
}; };
struct LegacyMockMethodSizes3 { struct LegacyMockMethodSizes3 {
MOCK_METHOD3(func, void(int, int, int)); MOCK_METHOD3(func, void(int, int, int));
}; };
struct LegacyMockMethodSizes4 { struct LegacyMockMethodSizes4 {
MOCK_METHOD4(func, void(int, int, int, int)); MOCK_METHOD4(func, void(int, int, int, int));
}; };
TEST(MockMethodMockFunctionTest, MockMethodSizeOverhead) { TEST(MockMethodMockFunctionTest, MockMethodSizeOverhead) {
EXPECT_EQ(sizeof(MockMethodSizes0), sizeof(MockMethodSizes1)); EXPECT_EQ(sizeof(MockMethodSizes0), sizeof(MockMethodSizes1));
EXPECT_EQ(sizeof(MockMethodSizes0), sizeof(MockMethodSizes2)); EXPECT_EQ(sizeof(MockMethodSizes0), sizeof(MockMethodSizes2));

View File

@ -27,7 +27,6 @@
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// Google Mock - a framework for writing C++ mock classes. // Google Mock - a framework for writing C++ mock classes.
// //
// This file tests the internal utilities. // This file tests the internal utilities.
@ -58,7 +57,7 @@
#undef GTEST_IMPLEMENTATION_ #undef GTEST_IMPLEMENTATION_
#if GTEST_OS_CYGWIN #if GTEST_OS_CYGWIN
# include <sys/types.h> // For ssize_t. NOLINT #include <sys/types.h> // For ssize_t. NOLINT
#endif #endif
namespace proto2 { namespace proto2 {
@ -155,19 +154,19 @@ TEST(KindOfTest, Bool) {
} }
TEST(KindOfTest, Integer) { TEST(KindOfTest, Integer) {
EXPECT_EQ(kInteger, GMOCK_KIND_OF_(char)); // NOLINT EXPECT_EQ(kInteger, GMOCK_KIND_OF_(char)); // NOLINT
EXPECT_EQ(kInteger, GMOCK_KIND_OF_(signed 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_(unsigned char)); // NOLINT
EXPECT_EQ(kInteger, GMOCK_KIND_OF_(short)); // NOLINT EXPECT_EQ(kInteger, GMOCK_KIND_OF_(short)); // NOLINT
EXPECT_EQ(kInteger, GMOCK_KIND_OF_(unsigned 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_(int)); // NOLINT
EXPECT_EQ(kInteger, GMOCK_KIND_OF_(unsigned 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_(long)); // NOLINT
EXPECT_EQ(kInteger, GMOCK_KIND_OF_(unsigned 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_(long long)); // NOLINT
EXPECT_EQ(kInteger, GMOCK_KIND_OF_(unsigned 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_(wchar_t)); // NOLINT
EXPECT_EQ(kInteger, GMOCK_KIND_OF_(size_t)); // NOLINT EXPECT_EQ(kInteger, GMOCK_KIND_OF_(size_t)); // NOLINT
#if GTEST_OS_LINUX || GTEST_OS_MAC || GTEST_OS_CYGWIN #if GTEST_OS_LINUX || GTEST_OS_MAC || GTEST_OS_CYGWIN
// ssize_t is not defined on Windows and possibly some other OSes. // ssize_t is not defined on Windows and possibly some other OSes.
EXPECT_EQ(kInteger, GMOCK_KIND_OF_(ssize_t)); // NOLINT EXPECT_EQ(kInteger, GMOCK_KIND_OF_(ssize_t)); // NOLINT
@ -175,15 +174,15 @@ TEST(KindOfTest, Integer) {
} }
TEST(KindOfTest, FloatingPoint) { TEST(KindOfTest, FloatingPoint) {
EXPECT_EQ(kFloatingPoint, GMOCK_KIND_OF_(float)); // NOLINT EXPECT_EQ(kFloatingPoint, GMOCK_KIND_OF_(float)); // NOLINT
EXPECT_EQ(kFloatingPoint, GMOCK_KIND_OF_(double)); // NOLINT EXPECT_EQ(kFloatingPoint, GMOCK_KIND_OF_(double)); // NOLINT
EXPECT_EQ(kFloatingPoint, GMOCK_KIND_OF_(long double)); // NOLINT EXPECT_EQ(kFloatingPoint, GMOCK_KIND_OF_(long double)); // NOLINT
} }
TEST(KindOfTest, Other) { 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_(char**)); // NOLINT
EXPECT_EQ(kOther, GMOCK_KIND_OF_(Base)); // NOLINT EXPECT_EQ(kOther, GMOCK_KIND_OF_(Base)); // NOLINT
} }
// Tests LosslessArithmeticConvertible<T, U>. // Tests LosslessArithmeticConvertible<T, U>.
@ -214,26 +213,26 @@ TEST(LosslessArithmeticConvertibleTest, IntegerToInteger) {
EXPECT_TRUE((LosslessArithmeticConvertible<unsigned char, int>::value)); EXPECT_TRUE((LosslessArithmeticConvertible<unsigned char, int>::value));
// Unsigned => larger unsigned is fine. // Unsigned => larger unsigned is fine.
EXPECT_TRUE((LosslessArithmeticConvertible< EXPECT_TRUE((LosslessArithmeticConvertible<unsigned short,
unsigned short, uint64_t>::value)); // NOLINT uint64_t>::value)); // NOLINT
// Signed => unsigned is not fine. // Signed => unsigned is not fine.
EXPECT_FALSE((LosslessArithmeticConvertible< EXPECT_FALSE(
short, uint64_t>::value)); // NOLINT (LosslessArithmeticConvertible<short, uint64_t>::value)); // NOLINT
EXPECT_FALSE((LosslessArithmeticConvertible< EXPECT_FALSE((LosslessArithmeticConvertible<signed char,
signed char, unsigned int>::value)); // NOLINT unsigned int>::value)); // NOLINT
// Same size and same signedness: fine too. // Same size and same signedness: fine too.
EXPECT_TRUE((LosslessArithmeticConvertible< EXPECT_TRUE(
unsigned char, unsigned char>::value)); (LosslessArithmeticConvertible<unsigned char, unsigned char>::value));
EXPECT_TRUE((LosslessArithmeticConvertible<int, int>::value)); EXPECT_TRUE((LosslessArithmeticConvertible<int, int>::value));
EXPECT_TRUE((LosslessArithmeticConvertible<wchar_t, wchar_t>::value)); EXPECT_TRUE((LosslessArithmeticConvertible<wchar_t, wchar_t>::value));
EXPECT_TRUE((LosslessArithmeticConvertible< EXPECT_TRUE((LosslessArithmeticConvertible<unsigned long,
unsigned long, unsigned long>::value)); // NOLINT unsigned long>::value)); // NOLINT
// Same size, different signedness: not fine. // Same size, different signedness: not fine.
EXPECT_FALSE((LosslessArithmeticConvertible< EXPECT_FALSE(
unsigned char, signed char>::value)); (LosslessArithmeticConvertible<unsigned char, signed char>::value));
EXPECT_FALSE((LosslessArithmeticConvertible<int, unsigned int>::value)); EXPECT_FALSE((LosslessArithmeticConvertible<int, unsigned int>::value));
EXPECT_FALSE((LosslessArithmeticConvertible<uint64_t, int64_t>::value)); EXPECT_FALSE((LosslessArithmeticConvertible<uint64_t, int64_t>::value));
@ -248,8 +247,8 @@ TEST(LosslessArithmeticConvertibleTest, IntegerToFloatingPoint) {
// the format of the latter is implementation-defined. // the format of the latter is implementation-defined.
EXPECT_FALSE((LosslessArithmeticConvertible<char, float>::value)); EXPECT_FALSE((LosslessArithmeticConvertible<char, float>::value));
EXPECT_FALSE((LosslessArithmeticConvertible<int, double>::value)); EXPECT_FALSE((LosslessArithmeticConvertible<int, double>::value));
EXPECT_FALSE((LosslessArithmeticConvertible< EXPECT_FALSE(
short, long double>::value)); // NOLINT (LosslessArithmeticConvertible<short, long double>::value)); // NOLINT
} }
TEST(LosslessArithmeticConvertibleTest, FloatingPointToBool) { TEST(LosslessArithmeticConvertibleTest, FloatingPointToBool) {
@ -277,7 +276,7 @@ TEST(LosslessArithmeticConvertibleTest, FloatingPointToFloatingPoint) {
EXPECT_FALSE((LosslessArithmeticConvertible<double, float>::value)); EXPECT_FALSE((LosslessArithmeticConvertible<double, float>::value));
GTEST_INTENTIONAL_CONST_COND_PUSH_() GTEST_INTENTIONAL_CONST_COND_PUSH_()
if (sizeof(double) == sizeof(long double)) { // NOLINT 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 // In some implementations (e.g. MSVC), double and long double
// have the same size. // have the same size.
EXPECT_TRUE((LosslessArithmeticConvertible<long double, double>::value)); EXPECT_TRUE((LosslessArithmeticConvertible<long double, double>::value));
@ -296,7 +295,7 @@ TEST(TupleMatchesTest, WorksForSize0) {
} }
TEST(TupleMatchesTest, WorksForSize1) { TEST(TupleMatchesTest, WorksForSize1) {
std::tuple<Matcher<int> > matchers(Eq(1)); std::tuple<Matcher<int>> matchers(Eq(1));
std::tuple<int> values1(1), values2(2); std::tuple<int> values1(1), values2(2);
EXPECT_TRUE(TupleMatches(matchers, values1)); EXPECT_TRUE(TupleMatches(matchers, values1));
@ -304,7 +303,7 @@ TEST(TupleMatchesTest, WorksForSize1) {
} }
TEST(TupleMatchesTest, WorksForSize2) { 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'), std::tuple<int, char> values1(1, 'a'), values2(1, 'b'), values3(2, 'a'),
values4(2, 'b'); values4(2, 'b');
@ -317,7 +316,7 @@ TEST(TupleMatchesTest, WorksForSize2) {
TEST(TupleMatchesTest, WorksForSize5) { TEST(TupleMatchesTest, WorksForSize5) {
std::tuple<Matcher<int>, Matcher<char>, Matcher<bool>, std::tuple<Matcher<int>, Matcher<char>, Matcher<bool>,
Matcher<long>, // NOLINT Matcher<long>, // NOLINT
Matcher<std::string> > Matcher<std::string>>
matchers(Eq(1), Eq('a'), Eq(true), Eq(2L), Eq("hi")); matchers(Eq(1), Eq('a'), Eq(true), Eq(2L), Eq("hi"));
std::tuple<int, char, bool, long, std::string> // NOLINT std::tuple<int, char, bool, long, std::string> // NOLINT
values1(1, 'a', true, 2L, "hi"), values2(1, 'a', true, 2L, "hello"), 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. // Tests that Assert(false, ...) generates a fatal failure.
TEST(AssertTest, FailsFatallyOnFalse) { TEST(AssertTest, FailsFatallyOnFalse) {
EXPECT_DEATH_IF_SUPPORTED({ EXPECT_DEATH_IF_SUPPORTED(
Assert(false, __FILE__, __LINE__, "This should fail."); { Assert(false, __FILE__, __LINE__, "This should fail."); }, "");
}, "");
EXPECT_DEATH_IF_SUPPORTED({ EXPECT_DEATH_IF_SUPPORTED({ Assert(false, __FILE__, __LINE__); }, "");
Assert(false, __FILE__, __LINE__);
}, "");
} }
// Tests that Expect(true, ...) succeeds. // Tests that Expect(true, ...) succeeds.
@ -353,13 +349,17 @@ TEST(ExpectTest, SucceedsOnTrue) {
// Tests that Expect(false, ...) generates a non-fatal failure. // Tests that Expect(false, ...) generates a non-fatal failure.
TEST(ExpectTest, FailsNonfatallyOnFalse) { TEST(ExpectTest, FailsNonfatallyOnFalse) {
EXPECT_NONFATAL_FAILURE({ // NOLINT EXPECT_NONFATAL_FAILURE(
Expect(false, __FILE__, __LINE__, "This should fail."); { // NOLINT
}, "This should fail"); Expect(false, __FILE__, __LINE__, "This should fail.");
},
"This should fail");
EXPECT_NONFATAL_FAILURE({ // NOLINT EXPECT_NONFATAL_FAILURE(
Expect(false, __FILE__, __LINE__); { // NOLINT
}, "Expectation failed"); Expect(false, __FILE__, __LINE__);
},
"Expectation failed");
} }
// Tests LogIsVisible(). // Tests LogIsVisible().
@ -404,11 +404,11 @@ void TestLogWithSeverity(const std::string& verbosity, LogSeverity severity,
CaptureStdout(); CaptureStdout();
Log(severity, "Test log.\n", 0); Log(severity, "Test log.\n", 0);
if (should_print) { if (should_print) {
EXPECT_THAT(GetCapturedStdout().c_str(), EXPECT_THAT(
ContainsRegex( GetCapturedStdout().c_str(),
severity == kWarning ? ContainsRegex(severity == kWarning
"^\nGMOCK WARNING:\nTest log\\.\nStack trace:\n" : ? "^\nGMOCK WARNING:\nTest log\\.\nStack trace:\n"
"^\nTest log\\.\nStack trace:\n")); : "^\nTest log\\.\nStack trace:\n"));
} else { } else {
EXPECT_STREQ("", GetCapturedStdout().c_str()); EXPECT_STREQ("", GetCapturedStdout().c_str());
} }
@ -455,13 +455,13 @@ TEST(LogTest, NoSkippingStackFrameInOptMode) {
EXPECT_THAT(log, HasSubstr(expected_message)); EXPECT_THAT(log, HasSubstr(expected_message));
int skip_count = atoi(log.substr(expected_message.size()).c_str()); 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. // In opt mode, no stack frame should be skipped.
const int expected_skip_count = 0; const int expected_skip_count = 0;
# else #else
// In dbg mode, the stack frames should be skipped. // In dbg mode, the stack frames should be skipped.
const int expected_skip_count = 100; const int expected_skip_count = 100;
# endif #endif
// Note that each inner implementation layer will +1 the number to remove // 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 // 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 // Verifies that Log() behaves correctly for the given verbosity level
// and log severity. // 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); const std::string saved_flag = GMOCK_FLAG_GET(verbose);
GMOCK_FLAG_SET(verbose, verbosity); GMOCK_FLAG_SET(verbose, verbosity);
CaptureStdout(); CaptureStdout();
@ -538,7 +538,7 @@ TEST(ExpectCallTest, DoesNotLogWhenVerbosityIsWarning) {
// Verifies that EXPECT_CALL doesn't log // Verifies that EXPECT_CALL doesn't log
// if the --gmock_verbose flag is set to "error". // if the --gmock_verbose flag is set to "error".
TEST(ExpectCallTest, DoesNotLogWhenVerbosityIsError) { TEST(ExpectCallTest, DoesNotLogWhenVerbosityIsError) {
EXPECT_STREQ("", GrabOutput(ExpectCallLogger, kErrorVerbosity).c_str()); EXPECT_STREQ("", GrabOutput(ExpectCallLogger, kErrorVerbosity).c_str());
} }
@ -582,9 +582,9 @@ TEST(OnCallTest, LogsAnythingArgument) {
TEST(StlContainerViewTest, WorksForStlContainer) { TEST(StlContainerViewTest, WorksForStlContainer) {
StaticAssertTypeEq<std::vector<int>, StaticAssertTypeEq<std::vector<int>,
StlContainerView<std::vector<int> >::type>(); StlContainerView<std::vector<int>>::type>();
StaticAssertTypeEq<const std::vector<double>&, StaticAssertTypeEq<const std::vector<double>&,
StlContainerView<std::vector<double> >::const_reference>(); StlContainerView<std::vector<double>>::const_reference>();
typedef std::vector<char> Chars; typedef std::vector<char> Chars;
Chars v1; Chars v1;
@ -597,17 +597,16 @@ TEST(StlContainerViewTest, WorksForStlContainer) {
} }
TEST(StlContainerViewTest, WorksForStaticNativeArray) { TEST(StlContainerViewTest, WorksForStaticNativeArray) {
StaticAssertTypeEq<NativeArray<int>, StaticAssertTypeEq<NativeArray<int>, StlContainerView<int[3]>::type>();
StlContainerView<int[3]>::type>();
StaticAssertTypeEq<NativeArray<double>, StaticAssertTypeEq<NativeArray<double>,
StlContainerView<const double[4]>::type>(); StlContainerView<const double[4]>::type>();
StaticAssertTypeEq<NativeArray<char[3]>, StaticAssertTypeEq<NativeArray<char[3]>,
StlContainerView<const char[2][3]>::type>(); StlContainerView<const char[2][3]>::type>();
StaticAssertTypeEq<const NativeArray<int>, 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); NativeArray<int> a2 = StlContainerView<int[3]>::ConstReference(a1);
EXPECT_EQ(3U, a2.size()); EXPECT_EQ(3U, a2.size());
EXPECT_EQ(a1, a2.begin()); EXPECT_EQ(a1, a2.begin());
@ -625,24 +624,24 @@ TEST(StlContainerViewTest, WorksForStaticNativeArray) {
TEST(StlContainerViewTest, WorksForDynamicNativeArray) { TEST(StlContainerViewTest, WorksForDynamicNativeArray) {
StaticAssertTypeEq<NativeArray<int>, StaticAssertTypeEq<NativeArray<int>,
StlContainerView<std::tuple<const int*, size_t> >::type>(); StlContainerView<std::tuple<const int*, size_t>>::type>();
StaticAssertTypeEq< StaticAssertTypeEq<
NativeArray<double>, NativeArray<double>,
StlContainerView<std::tuple<std::shared_ptr<double>, int> >::type>(); StlContainerView<std::tuple<std::shared_ptr<double>, int>>::type>();
StaticAssertTypeEq< StaticAssertTypeEq<
const NativeArray<int>, 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; const int* const p1 = a1;
NativeArray<int> a2 = NativeArray<int> a2 =
StlContainerView<std::tuple<const int*, int> >::ConstReference( StlContainerView<std::tuple<const int*, int>>::ConstReference(
std::make_tuple(p1, 3)); std::make_tuple(p1, 3));
EXPECT_EQ(3U, a2.size()); EXPECT_EQ(3U, a2.size());
EXPECT_EQ(a1, a2.begin()); 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)); std::make_tuple(static_cast<int*>(a1), 3));
ASSERT_EQ(3U, a3.size()); ASSERT_EQ(3U, a3.size());
EXPECT_EQ(0, a3.begin()[0]); EXPECT_EQ(0, a3.begin()[0]);

File diff suppressed because it is too large Load Diff

View File

@ -145,7 +145,7 @@ class Foo {
std::string Binary(const std::string& str, char c) const { return str + c; } std::string Binary(const std::string& str, char c) const { return str + c; }
int Ternary(int x, bool y, char z) { return value_ + x + y*z; } int Ternary(int x, bool y, char z) { return value_ + x + y * z; }
int SumOf4(int a, int b, int c, int d) const { int SumOf4(int a, int b, int c, int d) const {
return a + b + c + d + value_; return a + b + c + d + value_;
@ -291,8 +291,7 @@ TEST(InvokeTest, FunctionWithUnusedParameters) {
std::make_tuple(10, 2, 5.6, std::string("hi")); std::make_tuple(10, 2, 5.6, std::string("hi"));
EXPECT_EQ(12, a1.Perform(dummy)); EXPECT_EQ(12, a1.Perform(dummy));
Action<int(int, int, bool, int*)> a2 = Action<int(int, int, bool, int*)> a2 = Invoke(SumOfFirst2);
Invoke(SumOfFirst2);
EXPECT_EQ( EXPECT_EQ(
23, a2.Perform(std::make_tuple(20, 3, true, static_cast<int*>(nullptr)))); 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); 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))); EXPECT_EQ(12, a1.Perform(std::make_tuple(CharPtr("hi"), true, 10, 2)));
Action<int(char, double, int, int)> a2 = Action<int(char, double, int, int)> a2 = Invoke(&foo, &Foo::SumOfLast2);
Invoke(&foo, &Foo::SumOfLast2);
EXPECT_EQ(23, a2.Perform(std::make_tuple('a', 2.5, 20, 3))); 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. // Tests using Invoke() with a 5-argument method.
TEST(InvokeMethodTest, MethodThatTakes5Arguments) { TEST(InvokeMethodTest, MethodThatTakes5Arguments) {
Foo foo; 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))); 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. // the bool provided to the constructor to true when destroyed.
class DeletionTester { class DeletionTester {
public: public:
explicit DeletionTester(bool* is_deleted) explicit DeletionTester(bool* is_deleted) : is_deleted_(is_deleted) {
: is_deleted_(is_deleted) {
// Make sure the bit is set to false. // Make sure the bit is set to false.
*is_deleted_ = false; *is_deleted_ = false;
} }
~DeletionTester() { ~DeletionTester() { *is_deleted_ = true; }
*is_deleted_ = true;
}
private: private:
bool* is_deleted_; bool* is_deleted_;
@ -540,7 +536,7 @@ class DeletionTester {
TEST(DeleteArgActionTest, OneArg) { TEST(DeleteArgActionTest, OneArg) {
bool is_deleted = false; bool is_deleted = false;
DeletionTester* t = new DeletionTester(&is_deleted); 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); EXPECT_FALSE(is_deleted);
a1.Perform(std::make_tuple(t)); a1.Perform(std::make_tuple(t));
EXPECT_TRUE(is_deleted); EXPECT_TRUE(is_deleted);
@ -549,8 +545,9 @@ TEST(DeleteArgActionTest, OneArg) {
TEST(DeleteArgActionTest, TenArgs) { TEST(DeleteArgActionTest, TenArgs) {
bool is_deleted = false; bool is_deleted = false;
DeletionTester* t = new DeletionTester(&is_deleted); DeletionTester* t = new DeletionTester(&is_deleted);
const Action<void(bool, int, int, const char*, bool, const Action<void(bool, int, int, const char*, bool, int, int, int, int,
int, int, int, int, DeletionTester*)> a1 = DeleteArg<9>(); DeletionTester*)>
a1 = DeleteArg<9>();
EXPECT_FALSE(is_deleted); EXPECT_FALSE(is_deleted);
a1.Perform(std::make_tuple(true, 5, 6, CharPtr("hi"), false, 7, 8, 9, 10, t)); a1.Perform(std::make_tuple(true, 5, 6, CharPtr("hi"), false, 7, 8, 9, 10, t));
EXPECT_TRUE(is_deleted); 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). // pointed to by the N-th (0-based) argument to values in range [first, last).
TEST(SetArrayArgumentTest, SetsTheNthArray) { TEST(SetArrayArgumentTest, SetsTheNthArray) {
using MyFunction = void(bool, int*, char*); using MyFunction = void(bool, int*, char*);
int numbers[] = { 1, 2, 3 }; int numbers[] = {1, 2, 3};
Action<MyFunction> a = SetArrayArgument<1>(numbers, numbers + 3); Action<MyFunction> a = SetArrayArgument<1>(numbers, numbers + 3);
int n[4] = {}; int n[4] = {};
@ -644,7 +641,7 @@ TEST(SetArrayArgumentTest, SetsTheNthArray) {
// Tests SetArrayArgument<N>(first, last) where first == last. // Tests SetArrayArgument<N>(first, last) where first == last.
TEST(SetArrayArgumentTest, SetsTheNthArrayWithEmptyRange) { TEST(SetArrayArgumentTest, SetsTheNthArrayWithEmptyRange) {
using MyFunction = void(bool, int*); using MyFunction = void(bool, int*);
int numbers[] = { 1, 2, 3 }; int numbers[] = {1, 2, 3};
Action<MyFunction> a = SetArrayArgument<1>(numbers, numbers); Action<MyFunction> a = SetArrayArgument<1>(numbers, numbers);
int n[4] = {}; int n[4] = {};
@ -660,10 +657,10 @@ TEST(SetArrayArgumentTest, SetsTheNthArrayWithEmptyRange) {
// (but not equal) to the argument type. // (but not equal) to the argument type.
TEST(SetArrayArgumentTest, SetsTheNthArrayWithConvertibleType) { TEST(SetArrayArgumentTest, SetsTheNthArrayWithConvertibleType) {
using MyFunction = void(bool, int*); using MyFunction = void(bool, int*);
char chars[] = { 97, 98, 99 }; char chars[] = {97, 98, 99};
Action<MyFunction> a = SetArrayArgument<1>(chars, chars + 3); 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; int* pcodes = codes;
a.Perform(std::make_tuple(true, pcodes)); a.Perform(std::make_tuple(true, pcodes));
EXPECT_EQ(97, codes[0]); EXPECT_EQ(97, codes[0]);

View File

@ -31,6 +31,7 @@
#include <string> #include <string>
#include <utility> #include <utility>
#include "gmock/gmock.h" #include "gmock/gmock.h"
#include "gtest/gtest-spi.h" #include "gtest/gtest-spi.h"
#include "gtest/gtest.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, 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) { const std::string& a7, const std::string& a8, bool a9, bool a10) {
str_ = std::string() + a1 + a2 + a3 + a4 + static_cast<char>(a5) + 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() {} virtual ~MockBar() {}
@ -118,7 +120,6 @@ class MockBar {
GTEST_DISALLOW_COPY_AND_ASSIGN_(MockBar); GTEST_DISALLOW_COPY_AND_ASSIGN_(MockBar);
}; };
class MockBaz { class MockBaz {
public: public:
class MoveOnly { class MoveOnly {
@ -161,8 +162,7 @@ TEST(RawMockTest, WarningForUninterestingCallAfterDeath) {
MockFoo* const raw_foo = new MockFoo; MockFoo* const raw_foo = new MockFoo;
ON_CALL(*raw_foo, DoThis()) ON_CALL(*raw_foo, DoThis()).WillByDefault(Invoke(raw_foo, &MockFoo::Delete));
.WillByDefault(Invoke(raw_foo, &MockFoo::Delete));
CaptureStdout(); CaptureStdout();
raw_foo->DoThis(); raw_foo->DoThis();
@ -280,8 +280,8 @@ TEST(NiceMockTest, NonDefaultConstructor) {
// Tests that NiceMock works with a mock class that has a 10-ary // Tests that NiceMock works with a mock class that has a 10-ary
// non-default constructor. // non-default constructor.
TEST(NiceMockTest, NonDefaultConstructor10) { TEST(NiceMockTest, NonDefaultConstructor10) {
NiceMock<MockBar> nice_bar('a', 'b', "c", "d", 'e', 'f', NiceMock<MockBar> nice_bar('a', 'b', "c", "d", 'e', 'f', "g", "h", true,
"g", "h", true, false); false);
EXPECT_EQ("abcdefghTF", nice_bar.str()); EXPECT_EQ("abcdefghTF", nice_bar.str());
nice_bar.This(); nice_bar.This();
@ -390,8 +390,8 @@ TEST(NaggyMockTest, NonDefaultConstructor) {
// Tests that NaggyMock works with a mock class that has a 10-ary // Tests that NaggyMock works with a mock class that has a 10-ary
// non-default constructor. // non-default constructor.
TEST(NaggyMockTest, NonDefaultConstructor10) { TEST(NaggyMockTest, NonDefaultConstructor10) {
NaggyMock<MockBar> naggy_bar('0', '1', "2", "3", '4', '5', NaggyMock<MockBar> naggy_bar('0', '1', "2", "3", '4', '5', "6", "7", true,
"6", "7", true, false); false);
EXPECT_EQ("01234567TF", naggy_bar.str()); EXPECT_EQ("01234567TF", naggy_bar.str());
naggy_bar.This(); naggy_bar.This();
@ -490,8 +490,8 @@ TEST(StrictMockTest, NonDefaultConstructor) {
// Tests that StrictMock works with a mock class that has a 10-ary // Tests that StrictMock works with a mock class that has a 10-ary
// non-default constructor. // non-default constructor.
TEST(StrictMockTest, NonDefaultConstructor10) { TEST(StrictMockTest, NonDefaultConstructor10) {
StrictMock<MockBar> strict_bar('a', 'b', "c", "d", 'e', 'f', StrictMock<MockBar> strict_bar('a', 'b', "c", "d", 'e', 'f', "g", "h", true,
"g", "h", true, false); false);
EXPECT_EQ("abcdefghTF", strict_bar.str()); EXPECT_EQ("abcdefghTF", strict_bar.str());
EXPECT_NONFATAL_FAILURE(strict_bar.That(5, true), EXPECT_NONFATAL_FAILURE(strict_bar.That(5, true),

View File

@ -27,12 +27,12 @@
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// Google Mock - a framework for writing C++ mock classes. // Google Mock - a framework for writing C++ mock classes.
// //
// This file tests the internal cross-platform support utilities. // This file tests the internal cross-platform support utilities.
#include "gmock/internal/gmock-port.h" #include "gmock/internal/gmock-port.h"
#include "gtest/gtest.h" #include "gtest/gtest.h"
// NOTE: if this file is left without tests for some reason, put a dummy // NOTE: if this file is left without tests for some reason, put a dummy

View File

@ -30,11 +30,10 @@
// Google Mock - a framework for writing C++ mock classes. // Google Mock - a framework for writing C++ mock classes.
// //
// This file tests the internal preprocessor macro library. // This file tests the internal preprocessor macro library.
#include "gmock/internal/gmock-pp.h"
#include <string> #include <string>
#include "gmock/gmock.h" #include "gmock/gmock.h"
#include "gmock/internal/gmock-pp.h"
namespace testing { namespace testing {
namespace { namespace {

File diff suppressed because it is too large Load Diff

View File

@ -27,7 +27,6 @@
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// Tests Google Mock's functionality that depends on exceptions. // Tests Google Mock's functionality that depends on exceptions.
#include "gmock/gmock.h" #include "gmock/gmock.h"
@ -75,6 +74,5 @@ TEST(DefaultValueTest, ThrowsRuntimeErrorWhenNoDefaultValue) {
} }
} }
} // unnamed namespace } // unnamed namespace
#endif #endif

View File

@ -27,7 +27,6 @@
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// Google Mock - a framework for writing C++ mock classes. // Google Mock - a framework for writing C++ mock classes.
// //
// This program is for verifying that a leaked mock object can be // This program is for verifying that a leaked mock object can be

View File

@ -27,7 +27,6 @@
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// Google Mock - a framework for writing C++ mock classes. // Google Mock - a framework for writing C++ mock classes.
// //
// This file is for verifying that various Google Mock constructs do not // This file is for verifying that various Google Mock constructs do not

View File

@ -27,7 +27,6 @@
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// Google Mock - a framework for writing C++ mock classes. // Google Mock - a framework for writing C++ mock classes.
// //
// This file is for verifying that various Google Mock constructs do not // This file is for verifying that various Google Mock constructs do not

View File

@ -27,7 +27,6 @@
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// Google Mock - a framework for writing C++ mock classes. // Google Mock - a framework for writing C++ mock classes.
// //
// This file tests that: // This file tests that:
@ -118,7 +117,7 @@
#include "gmock/gmock.h" #include "gmock/gmock.h"
#if !GTEST_OS_WINDOWS_MOBILE #if !GTEST_OS_WINDOWS_MOBILE
# include <errno.h> #include <errno.h>
#endif #endif
#include <iostream> #include <iostream>
@ -200,14 +199,14 @@ class Interface {
virtual char* StringFromString(char* str) = 0; virtual char* StringFromString(char* str) = 0;
virtual int IntFromString(char* str) = 0; virtual int IntFromString(char* str) = 0;
virtual int& IntRefFromString(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 VoidFromIntRef(int& n) = 0; // NOLINT
virtual void VoidFromFloat(float n) = 0; virtual void VoidFromFloat(float n) = 0;
virtual void VoidFromDouble(double n) = 0; virtual void VoidFromDouble(double n) = 0;
virtual void VoidFromVector(const std::vector<int>& v) = 0; virtual void VoidFromVector(const std::vector<int>& v) = 0;
}; };
class Mock: public Interface { class Mock : public Interface {
public: public:
Mock() {} Mock() {}
@ -215,7 +214,7 @@ class Mock: public Interface {
MOCK_METHOD1(StringFromString, char*(char* str)); MOCK_METHOD1(StringFromString, char*(char* str));
MOCK_METHOD1(IntFromString, int(char* str)); MOCK_METHOD1(IntFromString, int(char* str));
MOCK_METHOD1(IntRefFromString, 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(VoidFromIntRef, void(int& n)); // NOLINT
MOCK_METHOD1(VoidFromFloat, void(float n)); MOCK_METHOD1(VoidFromFloat, void(float n));
MOCK_METHOD1(VoidFromDouble, void(double n)); MOCK_METHOD1(VoidFromDouble, void(double n));
@ -301,8 +300,8 @@ TEST(LinkTest, TestSetArrayArgument) {
char ch = 'x'; char ch = 'x';
char ch2 = 'y'; char ch2 = 'y';
EXPECT_CALL(mock, VoidFromString(_)).WillOnce(SetArrayArgument<0>(&ch2, EXPECT_CALL(mock, VoidFromString(_))
&ch2 + 1)); .WillOnce(SetArrayArgument<0>(&ch2, &ch2 + 1));
mock.VoidFromString(&ch); mock.VoidFromString(&ch);
} }
@ -339,8 +338,8 @@ TEST(LinkTest, TestInvokeWithoutArgs) {
EXPECT_CALL(mock, VoidFromString(_)) EXPECT_CALL(mock, VoidFromString(_))
.WillOnce(InvokeWithoutArgs(&InvokeHelper::StaticVoidFromVoid)) .WillOnce(InvokeWithoutArgs(&InvokeHelper::StaticVoidFromVoid))
.WillOnce(InvokeWithoutArgs(&test_invoke_helper, .WillOnce(
&InvokeHelper::VoidFromVoid)); InvokeWithoutArgs(&test_invoke_helper, &InvokeHelper::VoidFromVoid));
mock.VoidFromString(nullptr); mock.VoidFromString(nullptr);
mock.VoidFromString(nullptr); mock.VoidFromString(nullptr);
} }
@ -424,14 +423,14 @@ TEST(LinkTest, TestThrow) {
// is expanded and macro expansion cannot contain #pragma. Therefore // is expanded and macro expansion cannot contain #pragma. Therefore
// we suppress them here. // we suppress them here.
#ifdef _MSC_VER #ifdef _MSC_VER
# pragma warning(push) #pragma warning(push)
# pragma warning(disable:4100) #pragma warning(disable : 4100)
#endif #endif
// Tests the linkage of actions created using ACTION macro. // Tests the linkage of actions created using ACTION macro.
namespace { namespace {
ACTION(Return1) { return 1; } ACTION(Return1) { return 1; }
} } // namespace
TEST(LinkTest, TestActionMacro) { TEST(LinkTest, TestActionMacro) {
Mock mock; Mock mock;
@ -443,7 +442,7 @@ TEST(LinkTest, TestActionMacro) {
// Tests the linkage of actions created using ACTION_P macro. // Tests the linkage of actions created using ACTION_P macro.
namespace { namespace {
ACTION_P(ReturnArgument, ret_value) { return ret_value; } ACTION_P(ReturnArgument, ret_value) { return ret_value; }
} } // namespace
TEST(LinkTest, TestActionPMacro) { TEST(LinkTest, TestActionPMacro) {
Mock mock; Mock mock;
@ -457,10 +456,10 @@ namespace {
ACTION_P2(ReturnEqualsEitherOf, first, second) { ACTION_P2(ReturnEqualsEitherOf, first, second) {
return arg0 == first || arg0 == second; return arg0 == first || arg0 == second;
} }
} } // namespace
#ifdef _MSC_VER #ifdef _MSC_VER
# pragma warning(pop) #pragma warning(pop)
#endif #endif
TEST(LinkTest, TestActionP2Macro) { TEST(LinkTest, TestActionP2Macro) {
@ -492,8 +491,7 @@ TEST(LinkTest, TestMatchersEq) {
const char* p = "x"; const char* p = "x";
ON_CALL(mock, VoidFromString(Eq(p))).WillByDefault(Return()); ON_CALL(mock, VoidFromString(Eq(p))).WillByDefault(Return());
ON_CALL(mock, VoidFromString(const_cast<char*>("y"))) ON_CALL(mock, VoidFromString(const_cast<char*>("y"))).WillByDefault(Return());
.WillByDefault(Return());
} }
// Tests the linkage of the Lt, Gt, Le, Ge, and Ne matchers. // 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. // Tests the linkage of the ElementsAreArray matcher.
TEST(LinkTest, TestMatcherElementsAreArray) { TEST(LinkTest, TestMatcherElementsAreArray) {
Mock mock; Mock mock;
char arr[] = { 'a', 'b' }; char arr[] = {'a', 'b'};
ON_CALL(mock, VoidFromVector(ElementsAreArray(arr))).WillByDefault(Return()); ON_CALL(mock, VoidFromVector(ElementsAreArray(arr))).WillByDefault(Return());
} }

View File

@ -27,21 +27,20 @@
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// Tests Google Mock's output in various scenarios. This ensures that // Tests Google Mock's output in various scenarios. This ensures that
// Google Mock's messages are readable and useful. // Google Mock's messages are readable and useful.
#include "gmock/gmock.h"
#include <stdio.h> #include <stdio.h>
#include <string> #include <string>
#include "gmock/gmock.h"
#include "gtest/gtest.h" #include "gtest/gtest.h"
// Silence C4100 (unreferenced formal parameter) // Silence C4100 (unreferenced formal parameter)
#ifdef _MSC_VER #ifdef _MSC_VER
# pragma warning(push) #pragma warning(push)
# pragma warning(disable:4100) #pragma warning(disable : 4100)
#endif #endif
using testing::_; using testing::_;
@ -90,9 +89,7 @@ TEST_F(GMockOutputTest, ExpectedCallToVoidFunction) {
} }
TEST_F(GMockOutputTest, ExplicitActionsRunOut) { TEST_F(GMockOutputTest, ExplicitActionsRunOut) {
EXPECT_CALL(foo_, Bar2(_, _)) EXPECT_CALL(foo_, Bar2(_, _)).Times(2).WillOnce(Return(false));
.Times(2)
.WillOnce(Return(false));
foo_.Bar2(2, 2); foo_.Bar2(2, 2);
foo_.Bar2(1, 1); // Explicit actions in EXPECT_CALL run out. foo_.Bar2(1, 1); // Explicit actions in EXPECT_CALL run out.
} }
@ -134,8 +131,7 @@ TEST_F(GMockOutputTest, UninterestingCallToVoidFunction) {
} }
TEST_F(GMockOutputTest, RetiredExpectation) { TEST_F(GMockOutputTest, RetiredExpectation) {
EXPECT_CALL(foo_, Bar2(_, _)) EXPECT_CALL(foo_, Bar2(_, _)).RetiresOnSaturation();
.RetiresOnSaturation();
EXPECT_CALL(foo_, Bar2(0, 0)); EXPECT_CALL(foo_, Bar2(0, 0));
foo_.Bar2(1, 1); foo_.Bar2(1, 1);
@ -160,12 +156,9 @@ TEST_F(GMockOutputTest, UnsatisfiedPrerequisite) {
TEST_F(GMockOutputTest, UnsatisfiedPrerequisites) { TEST_F(GMockOutputTest, UnsatisfiedPrerequisites) {
Sequence s1, s2; Sequence s1, s2;
EXPECT_CALL(foo_, Bar(_, 0, _)) EXPECT_CALL(foo_, Bar(_, 0, _)).InSequence(s1);
.InSequence(s1); EXPECT_CALL(foo_, Bar2(0, 0)).InSequence(s2);
EXPECT_CALL(foo_, Bar2(0, 0)) EXPECT_CALL(foo_, Bar2(1, _)).InSequence(s1, s2);
.InSequence(s2);
EXPECT_CALL(foo_, Bar2(1, _))
.InSequence(s1, s2);
foo_.Bar2(1, 0); // Has two immediate unsatisfied pre-requisites foo_.Bar2(1, 0); // Has two immediate unsatisfied pre-requisites
foo_.Bar("Hi", 0, 0); foo_.Bar("Hi", 0, 0);
@ -179,8 +172,7 @@ TEST_F(GMockOutputTest, UnsatisfiedWith) {
TEST_F(GMockOutputTest, UnsatisfiedExpectation) { TEST_F(GMockOutputTest, UnsatisfiedExpectation) {
EXPECT_CALL(foo_, Bar(_, _, _)); EXPECT_CALL(foo_, Bar(_, _, _));
EXPECT_CALL(foo_, Bar2(0, _)) EXPECT_CALL(foo_, Bar2(0, _)).Times(2);
.Times(2);
foo_.Bar2(0, 1); foo_.Bar2(0, 1);
} }
@ -194,26 +186,22 @@ TEST_F(GMockOutputTest, MismatchArguments) {
} }
TEST_F(GMockOutputTest, MismatchWith) { TEST_F(GMockOutputTest, MismatchWith) {
EXPECT_CALL(foo_, Bar2(Ge(2), Ge(1))) EXPECT_CALL(foo_, Bar2(Ge(2), Ge(1))).With(Ge());
.With(Ge());
foo_.Bar2(2, 3); // Mismatch With() foo_.Bar2(2, 3); // Mismatch With()
foo_.Bar2(2, 1); foo_.Bar2(2, 1);
} }
TEST_F(GMockOutputTest, MismatchArgumentsAndWith) { TEST_F(GMockOutputTest, MismatchArgumentsAndWith) {
EXPECT_CALL(foo_, Bar2(Ge(2), Ge(1))) EXPECT_CALL(foo_, Bar2(Ge(2), Ge(1))).With(Ge());
.With(Ge());
foo_.Bar2(1, 3); // Mismatch arguments and mismatch With() foo_.Bar2(1, 3); // Mismatch arguments and mismatch With()
foo_.Bar2(2, 1); foo_.Bar2(2, 1);
} }
TEST_F(GMockOutputTest, UnexpectedCallWithDefaultAction) { TEST_F(GMockOutputTest, UnexpectedCallWithDefaultAction) {
ON_CALL(foo_, Bar2(_, _)) ON_CALL(foo_, Bar2(_, _)).WillByDefault(Return(true)); // Default action #1
.WillByDefault(Return(true)); // Default action #1 ON_CALL(foo_, Bar2(1, _)).WillByDefault(Return(false)); // Default action #2
ON_CALL(foo_, Bar2(1, _))
.WillByDefault(Return(false)); // Default action #2
EXPECT_CALL(foo_, Bar2(2, 2)); EXPECT_CALL(foo_, Bar2(2, 2));
foo_.Bar2(1, 0); // Unexpected call, takes default action #2. foo_.Bar2(1, 0); // Unexpected call, takes default action #2.
@ -222,10 +210,8 @@ TEST_F(GMockOutputTest, UnexpectedCallWithDefaultAction) {
} }
TEST_F(GMockOutputTest, ExcessiveCallWithDefaultAction) { TEST_F(GMockOutputTest, ExcessiveCallWithDefaultAction) {
ON_CALL(foo_, Bar2(_, _)) ON_CALL(foo_, Bar2(_, _)).WillByDefault(Return(true)); // Default action #1
.WillByDefault(Return(true)); // Default action #1 ON_CALL(foo_, Bar2(1, _)).WillByDefault(Return(false)); // Default action #2
ON_CALL(foo_, Bar2(1, _))
.WillByDefault(Return(false)); // Default action #2
EXPECT_CALL(foo_, Bar2(2, 2)); EXPECT_CALL(foo_, Bar2(2, 2));
EXPECT_CALL(foo_, Bar2(1, 1)); EXPECT_CALL(foo_, Bar2(1, 1));
@ -237,22 +223,17 @@ TEST_F(GMockOutputTest, ExcessiveCallWithDefaultAction) {
} }
TEST_F(GMockOutputTest, UninterestingCallWithDefaultAction) { TEST_F(GMockOutputTest, UninterestingCallWithDefaultAction) {
ON_CALL(foo_, Bar2(_, _)) ON_CALL(foo_, Bar2(_, _)).WillByDefault(Return(true)); // Default action #1
.WillByDefault(Return(true)); // Default action #1 ON_CALL(foo_, Bar2(1, _)).WillByDefault(Return(false)); // Default action #2
ON_CALL(foo_, Bar2(1, _))
.WillByDefault(Return(false)); // Default action #2
foo_.Bar2(2, 2); // Uninteresting call, takes default action #1. foo_.Bar2(2, 2); // Uninteresting call, takes default action #1.
foo_.Bar2(1, 1); // Uninteresting call, takes default action #2. foo_.Bar2(1, 1); // Uninteresting call, takes default action #2.
} }
TEST_F(GMockOutputTest, ExplicitActionsRunOutWithDefaultAction) { TEST_F(GMockOutputTest, ExplicitActionsRunOutWithDefaultAction) {
ON_CALL(foo_, Bar2(_, _)) ON_CALL(foo_, Bar2(_, _)).WillByDefault(Return(true)); // Default action #1
.WillByDefault(Return(true)); // Default action #1
EXPECT_CALL(foo_, Bar2(_, _)) EXPECT_CALL(foo_, Bar2(_, _)).Times(2).WillOnce(Return(false));
.Times(2)
.WillOnce(Return(false));
foo_.Bar2(2, 2); foo_.Bar2(2, 2);
foo_.Bar2(1, 1); // Explicit actions in EXPECT_CALL run out. foo_.Bar2(1, 1); // Explicit actions in EXPECT_CALL run out.
} }
@ -293,7 +274,7 @@ void TestCatchesLeakedMocksInAdHocTests() {
// foo is deliberately leaked. // foo is deliberately leaked.
} }
int main(int argc, char **argv) { int main(int argc, char** argv) {
testing::InitGoogleMock(&argc, argv); testing::InitGoogleMock(&argc, argv);
// Ensures that the tests pass no matter what value of // Ensures that the tests pass no matter what value of
// --gmock_catch_leaked_mocks and --gmock_verbose the user specifies. // --gmock_catch_leaked_mocks and --gmock_verbose the user specifies.
@ -305,5 +286,5 @@ int main(int argc, char **argv) {
} }
#ifdef _MSC_VER #ifdef _MSC_VER
# pragma warning(pop) #pragma warning(pop)
#endif #endif

View File

@ -27,7 +27,6 @@
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // 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 // Tests that Google Mock constructs can be used in a large number of
// threads concurrently. // threads concurrently.
@ -49,7 +48,7 @@ const int kRepeat = 50;
class MockFoo { class MockFoo {
public: 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 MOCK_METHOD2(Baz, char(const char* s1, const std::string& s2)); // NOLINT
}; };
@ -62,21 +61,16 @@ void JoinAndDelete(ThreadWithParam<T>* t) {
struct Dummy {}; struct Dummy {};
// Tests that different mock objects can be used in their respective // Tests that different mock objects can be used in their respective
// threads. This should generate no Google Test failure. // threads. This should generate no Google Test failure.
void TestConcurrentMockObjects(Dummy /* dummy */) { void TestConcurrentMockObjects(Dummy /* dummy */) {
// Creates a mock and does some typical operations on it. // Creates a mock and does some typical operations on it.
MockFoo foo; MockFoo foo;
ON_CALL(foo, Bar(_)) ON_CALL(foo, Bar(_)).WillByDefault(Return(1));
.WillByDefault(Return(1)); ON_CALL(foo, Baz(_, _)).WillByDefault(Return('b'));
ON_CALL(foo, Baz(_, _)) ON_CALL(foo, Baz(_, "you")).WillByDefault(Return('a'));
.WillByDefault(Return('b'));
ON_CALL(foo, Baz(_, "you"))
.WillByDefault(Return('a'));
EXPECT_CALL(foo, Bar(0)) EXPECT_CALL(foo, Bar(0)).Times(AtMost(3));
.Times(AtMost(3));
EXPECT_CALL(foo, Baz(_, _)); EXPECT_CALL(foo, Baz(_, _));
EXPECT_CALL(foo, Baz("hi", "you")) EXPECT_CALL(foo, Baz("hi", "you"))
.WillOnce(Return('z')) .WillOnce(Return('z'))
@ -119,22 +113,19 @@ void Helper1(Helper1Param param) {
void TestConcurrentCallsOnSameObject(Dummy /* dummy */) { void TestConcurrentCallsOnSameObject(Dummy /* dummy */) {
MockFoo foo; MockFoo foo;
ON_CALL(foo, Bar(_)) ON_CALL(foo, Bar(_)).WillByDefault(Return(1));
.WillByDefault(Return(1)); EXPECT_CALL(foo, Baz(_, "b")).Times(kRepeat).WillRepeatedly(Return('a'));
EXPECT_CALL(foo, Baz(_, "b"))
.Times(kRepeat)
.WillRepeatedly(Return('a'));
EXPECT_CALL(foo, Baz(_, "c")); // Expected to be unsatisfied. EXPECT_CALL(foo, Baz(_, "c")); // Expected to be unsatisfied.
// This chunk of code should generate kRepeat failures about // This chunk of code should generate kRepeat failures about
// excessive calls, and 2*kRepeat failures about unexpected calls. // excessive calls, and 2*kRepeat failures about unexpected calls.
int count1 = 0; int count1 = 0;
const Helper1Param param = { &foo, &count1 }; const Helper1Param param = {&foo, &count1};
ThreadWithParam<Helper1Param>* const t = ThreadWithParam<Helper1Param>* const t =
new ThreadWithParam<Helper1Param>(Helper1, param, nullptr); new ThreadWithParam<Helper1Param>(Helper1, param, nullptr);
int count2 = 0; int count2 = 0;
const Helper1Param param2 = { &foo, &count2 }; const Helper1Param param2 = {&foo, &count2};
Helper1(param2); Helper1(param2);
JoinAndDelete(t); JoinAndDelete(t);
@ -162,22 +153,18 @@ void TestPartiallyOrderedExpectationsWithThreads(Dummy /* dummy */) {
{ {
InSequence dummy; InSequence dummy;
EXPECT_CALL(foo, Bar(0)); EXPECT_CALL(foo, Bar(0));
EXPECT_CALL(foo, Bar(1)) EXPECT_CALL(foo, Bar(1)).InSequence(s1, s2);
.InSequence(s1, s2);
} }
EXPECT_CALL(foo, Bar(2)) EXPECT_CALL(foo, Bar(2))
.Times(2*kRepeat) .Times(2 * kRepeat)
.InSequence(s1) .InSequence(s1)
.RetiresOnSaturation(); .RetiresOnSaturation();
EXPECT_CALL(foo, Bar(3)) EXPECT_CALL(foo, Bar(3)).Times(2 * kRepeat).InSequence(s2);
.Times(2*kRepeat)
.InSequence(s2);
{ {
InSequence dummy; InSequence dummy;
EXPECT_CALL(foo, Bar(2)) EXPECT_CALL(foo, Bar(2)).InSequence(s1, s2);
.InSequence(s1, s2);
EXPECT_CALL(foo, Bar(4)); EXPECT_CALL(foo, Bar(4));
} }
@ -196,12 +183,12 @@ void TestPartiallyOrderedExpectationsWithThreads(Dummy /* dummy */) {
// Tests using Google Mock constructs in many threads concurrently. // Tests using Google Mock constructs in many threads concurrently.
TEST(StressTest, CanUseGMockWithThreads) { TEST(StressTest, CanUseGMockWithThreads) {
void (*test_routines[])(Dummy dummy) = { void (*test_routines[])(Dummy dummy) = {
&TestConcurrentMockObjects, &TestConcurrentMockObjects,
&TestConcurrentCallsOnSameObject, &TestConcurrentCallsOnSameObject,
&TestPartiallyOrderedExpectationsWithThreads, &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 kCopiesOfEachRoutine = kMaxTestThreads / kRoutines;
const int kTestThreads = kCopiesOfEachRoutine * kRoutines; const int kTestThreads = kCopiesOfEachRoutine * kRoutines;
ThreadWithParam<Dummy>* threads[kTestThreads] = {}; ThreadWithParam<Dummy>* threads[kTestThreads] = {};
@ -220,7 +207,7 @@ TEST(StressTest, CanUseGMockWithThreads) {
// Ensures that the correct number of failures have been reported. // Ensures that the correct number of failures have been reported.
const TestInfo* const info = UnitTest::GetInstance()->current_test_info(); const TestInfo* const info = UnitTest::GetInstance()->current_test_info();
const TestResult& result = *info->result(); 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()) GTEST_CHECK_(kExpectedFailures == result.total_part_count())
<< "Expected " << kExpectedFailures << " failures, but got " << "Expected " << kExpectedFailures << " failures, but got "
<< result.total_part_count(); << result.total_part_count();
@ -229,7 +216,7 @@ TEST(StressTest, CanUseGMockWithThreads) {
} // namespace } // namespace
} // namespace testing } // namespace testing
int main(int argc, char **argv) { int main(int argc, char** argv) {
testing::InitGoogleMock(&argc, argv); testing::InitGoogleMock(&argc, argv);
const int exit_code = RUN_ALL_TESTS(); // Expected to fail. const int exit_code = RUN_ALL_TESTS(); // Expected to fail.

View File

@ -27,7 +27,6 @@
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// Google Mock - a framework for writing C++ mock classes. // Google Mock - a framework for writing C++ mock classes.
// //
// This file tests code in gmock.cc. // This file tests code in gmock.cc.
@ -35,6 +34,7 @@
#include "gmock/gmock.h" #include "gmock/gmock.h"
#include <string> #include <string>
#include "gtest/gtest.h" #include "gtest/gtest.h"
#include "gtest/internal/custom/gtest.h" #include "gtest/internal/custom/gtest.h"

View File

@ -170,24 +170,24 @@ GTEST_API_ bool InDeathTestChild();
// Asserts that a given `statement` causes the program to exit, with an // Asserts that a given `statement` causes the program to exit, with an
// integer exit status that satisfies `predicate`, and emitting error output // integer exit status that satisfies `predicate`, and emitting error output
// that matches `matcher`. // that matches `matcher`.
# define ASSERT_EXIT(statement, predicate, matcher) \ #define ASSERT_EXIT(statement, predicate, matcher) \
GTEST_DEATH_TEST_(statement, predicate, matcher, GTEST_FATAL_FAILURE_) GTEST_DEATH_TEST_(statement, predicate, matcher, GTEST_FATAL_FAILURE_)
// Like `ASSERT_EXIT`, but continues on to successive tests in the // Like `ASSERT_EXIT`, but continues on to successive tests in the
// test suite, if any: // test suite, if any:
# define EXPECT_EXIT(statement, predicate, matcher) \ #define EXPECT_EXIT(statement, predicate, matcher) \
GTEST_DEATH_TEST_(statement, predicate, matcher, GTEST_NONFATAL_FAILURE_) GTEST_DEATH_TEST_(statement, predicate, matcher, GTEST_NONFATAL_FAILURE_)
// Asserts that a given `statement` causes the program to exit, either by // Asserts that a given `statement` causes the program to exit, either by
// explicitly exiting with a nonzero exit code or being killed by a // explicitly exiting with a nonzero exit code or being killed by a
// signal, and emitting error output that matches `matcher`. // signal, and emitting error output that matches `matcher`.
# define ASSERT_DEATH(statement, matcher) \ #define ASSERT_DEATH(statement, matcher) \
ASSERT_EXIT(statement, ::testing::internal::ExitedUnsuccessfully, matcher) ASSERT_EXIT(statement, ::testing::internal::ExitedUnsuccessfully, matcher)
// Like `ASSERT_DEATH`, but continues on to successive tests in the // Like `ASSERT_DEATH`, but continues on to successive tests in the
// test suite, if any: // test suite, if any:
# define EXPECT_DEATH(statement, matcher) \ #define EXPECT_DEATH(statement, matcher) \
EXPECT_EXIT(statement, ::testing::internal::ExitedUnsuccessfully, matcher) EXPECT_EXIT(statement, ::testing::internal::ExitedUnsuccessfully, matcher)
// Two predicate classes that can be used in {ASSERT,EXPECT}_EXIT*: // Two predicate classes that can be used in {ASSERT,EXPECT}_EXIT*:
@ -198,21 +198,23 @@ class GTEST_API_ ExitedWithCode {
ExitedWithCode(const ExitedWithCode&) = default; ExitedWithCode(const ExitedWithCode&) = default;
void operator=(const ExitedWithCode& other) = delete; void operator=(const ExitedWithCode& other) = delete;
bool operator()(int exit_status) const; bool operator()(int exit_status) const;
private: private:
const int exit_code_; 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 // Tests that an exit code describes an exit due to termination by a
// given signal. // given signal.
class GTEST_API_ KilledBySignal { class GTEST_API_ KilledBySignal {
public: public:
explicit KilledBySignal(int signum); explicit KilledBySignal(int signum);
bool operator()(int exit_status) const; bool operator()(int exit_status) const;
private: private:
const int signum_; const int signum_;
}; };
# endif // !GTEST_OS_WINDOWS #endif // !GTEST_OS_WINDOWS
// EXPECT_DEBUG_DEATH asserts that the given statements die in debug mode. // EXPECT_DEBUG_DEATH asserts that the given statements die in debug mode.
// The death testing framework causes this to have interesting semantics, // The death testing framework causes this to have interesting semantics,
@ -257,23 +259,21 @@ class GTEST_API_ KilledBySignal {
// EXPECT_EQ(12, DieInDebugOr12(&sideeffect)); // EXPECT_EQ(12, DieInDebugOr12(&sideeffect));
// }, "death"); // }, "death");
// //
# ifdef NDEBUG #ifdef NDEBUG
# define EXPECT_DEBUG_DEATH(statement, regex) \ #define EXPECT_DEBUG_DEATH(statement, regex) \
GTEST_EXECUTE_STATEMENT_(statement, regex) GTEST_EXECUTE_STATEMENT_(statement, regex)
# define ASSERT_DEBUG_DEATH(statement, regex) \ #define ASSERT_DEBUG_DEATH(statement, regex) \
GTEST_EXECUTE_STATEMENT_(statement, regex) GTEST_EXECUTE_STATEMENT_(statement, regex)
# else #else
# define EXPECT_DEBUG_DEATH(statement, regex) \ #define EXPECT_DEBUG_DEATH(statement, regex) EXPECT_DEATH(statement, regex)
EXPECT_DEATH(statement, regex)
# define ASSERT_DEBUG_DEATH(statement, regex) \ #define ASSERT_DEBUG_DEATH(statement, regex) ASSERT_DEATH(statement, regex)
ASSERT_DEATH(statement, regex)
# endif // NDEBUG for EXPECT_DEBUG_DEATH #endif // NDEBUG for EXPECT_DEBUG_DEATH
#endif // GTEST_HAS_DEATH_TEST #endif // GTEST_HAS_DEATH_TEST
// This macro is used for implementing macros such as // 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 // statement unconditionally returns or throws. The Message constructor at
// the end allows the syntax of streaming additional messages into the // the end allows the syntax of streaming additional messages into the
// macro, for compilational compatibility with EXPECT_DEATH/ASSERT_DEATH. // macro, for compilational compatibility with EXPECT_DEATH/ASSERT_DEATH.
# define GTEST_UNSUPPORTED_DEATH_TEST(statement, regex, terminator) \ #define GTEST_UNSUPPORTED_DEATH_TEST(statement, regex, terminator) \
GTEST_AMBIGUOUS_ELSE_BLOCKER_ \ GTEST_AMBIGUOUS_ELSE_BLOCKER_ \
if (::testing::internal::AlwaysTrue()) { \ if (::testing::internal::AlwaysTrue()) { \
GTEST_LOG_(WARNING) \ GTEST_LOG_(WARNING) << "Death tests are not supported on this platform.\n" \
<< "Death tests are not supported on this platform.\n" \ << "Statement '" #statement "' cannot be verified."; \
<< "Statement '" #statement "' cannot be verified."; \ } else if (::testing::internal::AlwaysFalse()) { \
} else if (::testing::internal::AlwaysFalse()) { \ ::testing::internal::RE::PartialMatch(".*", (regex)); \
::testing::internal::RE::PartialMatch(".*", (regex)); \ GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement); \
GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement); \ terminator; \
terminator; \ } else \
} else \ ::testing::Message()
::testing::Message()
// EXPECT_DEATH_IF_SUPPORTED(statement, regex) and // EXPECT_DEATH_IF_SUPPORTED(statement, regex) and
// ASSERT_DEATH_IF_SUPPORTED(statement, regex) expand to real death tests if // 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 // useful when you are combining death test assertions with normal test
// assertions in one test. // assertions in one test.
#if GTEST_HAS_DEATH_TEST #if GTEST_HAS_DEATH_TEST
# define EXPECT_DEATH_IF_SUPPORTED(statement, regex) \ #define EXPECT_DEATH_IF_SUPPORTED(statement, regex) \
EXPECT_DEATH(statement, regex) EXPECT_DEATH(statement, regex)
# define ASSERT_DEATH_IF_SUPPORTED(statement, regex) \ #define ASSERT_DEATH_IF_SUPPORTED(statement, regex) \
ASSERT_DEATH(statement, regex) ASSERT_DEATH(statement, regex)
#else #else
# define EXPECT_DEATH_IF_SUPPORTED(statement, regex) \ #define EXPECT_DEATH_IF_SUPPORTED(statement, regex) \
GTEST_UNSUPPORTED_DEATH_TEST(statement, regex, ) GTEST_UNSUPPORTED_DEATH_TEST(statement, regex, )
# define ASSERT_DEATH_IF_SUPPORTED(statement, regex) \ #define ASSERT_DEATH_IF_SUPPORTED(statement, regex) \
GTEST_UNSUPPORTED_DEATH_TEST(statement, regex, return) GTEST_UNSUPPORTED_DEATH_TEST(statement, regex, return)
#endif #endif
} // namespace testing } // namespace testing

View File

@ -105,8 +105,7 @@ class MatchResultListener {
GTEST_DISALLOW_COPY_AND_ASSIGN_(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 // An instance of a subclass of this knows how to describe itself as a
// matcher. // matcher.
@ -180,27 +179,39 @@ namespace internal {
struct AnyEq { struct AnyEq {
template <typename A, typename B> 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 { struct AnyNe {
template <typename A, typename B> 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 { struct AnyLt {
template <typename A, typename B> 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 { struct AnyGt {
template <typename A, typename B> 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 { struct AnyLe {
template <typename A, typename B> 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 { struct AnyGe {
template <typename A, typename B> 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. // A match result listener that ignores the explanation.
@ -424,8 +435,8 @@ class MatcherBase : private MatcherDescriberInterface {
static const M& Get(const MatcherBase& m) { static const M& Get(const MatcherBase& m) {
// When inlined along with Init, need to be explicit to avoid violating // When inlined along with Init, need to be explicit to avoid violating
// strict aliasing rules. // strict aliasing rules.
const M *ptr = static_cast<const M*>( const M* ptr =
static_cast<const void*>(&m.buffer_)); static_cast<const M*>(static_cast<const void*>(&m.buffer_));
return *ptr; return *ptr;
} }
static void Init(MatcherBase& m, M impl) { static void Init(MatcherBase& m, M impl) {
@ -745,7 +756,7 @@ template <typename Rhs>
class EqMatcher : public ComparisonBase<EqMatcher<Rhs>, Rhs, AnyEq> { class EqMatcher : public ComparisonBase<EqMatcher<Rhs>, Rhs, AnyEq> {
public: public:
explicit EqMatcher(const Rhs& rhs) 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* Desc() { return "is equal to"; }
static const char* NegatedDesc() { return "isn't 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> { class NeMatcher : public ComparisonBase<NeMatcher<Rhs>, Rhs, AnyNe> {
public: public:
explicit NeMatcher(const Rhs& rhs) 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* Desc() { return "isn't equal to"; }
static const char* NegatedDesc() { return "is 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> { class LtMatcher : public ComparisonBase<LtMatcher<Rhs>, Rhs, AnyLt> {
public: public:
explicit LtMatcher(const Rhs& rhs) 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* Desc() { return "is <"; }
static const char* NegatedDesc() { return "isn't <"; } static const char* NegatedDesc() { return "isn't <"; }
}; };
@ -769,7 +780,7 @@ template <typename Rhs>
class GtMatcher : public ComparisonBase<GtMatcher<Rhs>, Rhs, AnyGt> { class GtMatcher : public ComparisonBase<GtMatcher<Rhs>, Rhs, AnyGt> {
public: public:
explicit GtMatcher(const Rhs& rhs) 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* Desc() { return "is >"; }
static const char* NegatedDesc() { return "isn't >"; } static const char* NegatedDesc() { return "isn't >"; }
}; };
@ -777,7 +788,7 @@ template <typename Rhs>
class LeMatcher : public ComparisonBase<LeMatcher<Rhs>, Rhs, AnyLe> { class LeMatcher : public ComparisonBase<LeMatcher<Rhs>, Rhs, AnyLe> {
public: public:
explicit LeMatcher(const Rhs& rhs) 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* Desc() { return "is <="; }
static const char* NegatedDesc() { return "isn't <="; } static const char* NegatedDesc() { return "isn't <="; }
}; };
@ -785,7 +796,7 @@ template <typename Rhs>
class GeMatcher : public ComparisonBase<GeMatcher<Rhs>, Rhs, AnyGe> { class GeMatcher : public ComparisonBase<GeMatcher<Rhs>, Rhs, AnyGe> {
public: public:
explicit GeMatcher(const Rhs& rhs) 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* Desc() { return "is >="; }
static const char* NegatedDesc() { return "isn't >="; } 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") // Note: if the parameter of Eq() were declared as const T&, Eq("foo")
// wouldn't compile. // wouldn't compile.
template <typename T> 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 // Constructs a Matcher<T> from a 'value' of type T. The constructed
// matcher matches any value that's equal to 'value'. // matcher matches any value that's equal to 'value'.
template <typename T> 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 // Creates a monomorphic matcher that matches anything with type Lhs
// and equal to rhs. A user may need to use this instead of Eq(...) // 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, // can always write Matcher<T>(Lt(5)) to be explicit about the type,
// for example. // for example.
template <typename Lhs, typename Rhs> 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. // Creates a polymorphic matcher that matches anything >= x.
template <typename Rhs> template <typename Rhs>

View File

@ -111,8 +111,8 @@ class GTEST_API_ Message {
// Streams a non-pointer value to this object. // Streams a non-pointer value to this object.
template <typename T> template <typename T>
inline Message& operator <<(const T& val) { inline Message& operator<<(const T& val) {
// Some libraries overload << for STL containers. These // Some libraries overload << for STL containers. These
// overloads are defined in the global namespace instead of ::std. // overloads are defined in the global namespace instead of ::std.
// //
// C++'s symbol lookup rule (i.e. Koenig lookup) says that these // 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, // from the global namespace. With this using declaration,
// overloads of << defined in the global namespace and those // overloads of << defined in the global namespace and those
// visible via Koenig lookup are both exposed in this function. // visible via Koenig lookup are both exposed in this function.
using ::operator <<; using ::operator<<;
*ss_ << val; *ss_ << val;
return *this; return *this;
} }
@ -145,7 +145,7 @@ class GTEST_API_ Message {
// ensure consistent result across compilers, we always treat NULL // ensure consistent result across compilers, we always treat NULL
// as "(null)". // as "(null)".
template <typename T> template <typename T>
inline Message& operator <<(T* const& pointer) { // NOLINT inline Message& operator<<(T* const& pointer) { // NOLINT
if (pointer == nullptr) { if (pointer == nullptr) {
*ss_ << "(null)"; *ss_ << "(null)";
} else { } else {
@ -160,25 +160,23 @@ class GTEST_API_ Message {
// templatized version above. Without this definition, streaming // templatized version above. Without this definition, streaming
// endl or other basic IO manipulators to Message will confuse the // endl or other basic IO manipulators to Message will confuse the
// compiler. // compiler.
Message& operator <<(BasicNarrowIoManip val) { Message& operator<<(BasicNarrowIoManip val) {
*ss_ << val; *ss_ << val;
return *this; return *this;
} }
// Instead of 1/0, we want to see true/false for bool values. // Instead of 1/0, we want to see true/false for bool values.
Message& operator <<(bool b) { Message& operator<<(bool b) { return *this << (b ? "true" : "false"); }
return *this << (b ? "true" : "false");
}
// These two overloads allow streaming a wide C string to a Message // These two overloads allow streaming a wide C string to a Message
// using the UTF-8 encoding. // using the UTF-8 encoding.
Message& operator <<(const wchar_t* wide_c_str); Message& operator<<(const wchar_t* wide_c_str);
Message& operator <<(wchar_t* wide_c_str); Message& operator<<(wchar_t* wide_c_str);
#if GTEST_HAS_STD_WSTRING #if GTEST_HAS_STD_WSTRING
// Converts the given wide string to a narrow string using the UTF-8 // Converts the given wide string to a narrow string using the UTF-8
// encoding, and streams the result to this Message object. // 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 #endif // GTEST_HAS_STD_WSTRING
// Gets the text streamed to this object so far as an std::string. // 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. // 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(); return os << sb.GetString();
} }

View File

@ -356,9 +356,7 @@ internal::ValueArray<T...> Values(T... v) {
// } // }
// INSTANTIATE_TEST_SUITE_P(BoolSequence, FlagDependentTest, Bool()); // INSTANTIATE_TEST_SUITE_P(BoolSequence, FlagDependentTest, Bool());
// //
inline internal::ParamGenerator<bool> Bool() { inline internal::ParamGenerator<bool> Bool() { return Values(false, true); }
return Values(false, true);
}
// Combine() allows the user to combine two or more sequences to produce // Combine() allows the user to combine two or more sequences to produce
// values of a Cartesian product of those sequences' elements. // 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_FIRST_(first, ...) first
#define GTEST_GET_SECOND_(first, second, ...) second #define GTEST_GET_SECOND_(first, second, ...) second
#define INSTANTIATE_TEST_SUITE_P(prefix, test_suite_name, ...) \ #define INSTANTIATE_TEST_SUITE_P(prefix, test_suite_name, ...) \
static ::testing::internal::ParamGenerator<test_suite_name::ParamType> \ static ::testing::internal::ParamGenerator<test_suite_name::ParamType> \
gtest_##prefix##test_suite_name##_EvalGenerator_() { \ gtest_##prefix##test_suite_name##_EvalGenerator_() { \
return GTEST_EXPAND_(GTEST_GET_FIRST_(__VA_ARGS__, DUMMY_PARAM_)); \ return GTEST_EXPAND_(GTEST_GET_FIRST_(__VA_ARGS__, DUMMY_PARAM_)); \
} \ } \
static ::std::string gtest_##prefix##test_suite_name##_EvalGenerateName_( \ static ::std::string gtest_##prefix##test_suite_name##_EvalGenerateName_( \
const ::testing::TestParamInfo<test_suite_name::ParamType>& info) { \ const ::testing::TestParamInfo<test_suite_name::ParamType>& info) { \
if (::testing::internal::AlwaysFalse()) { \ if (::testing::internal::AlwaysFalse()) { \
::testing::internal::TestNotEmpty(GTEST_EXPAND_(GTEST_GET_SECOND_( \ ::testing::internal::TestNotEmpty(GTEST_EXPAND_(GTEST_GET_SECOND_( \
__VA_ARGS__, \ __VA_ARGS__, \
::testing::internal::DefaultParamName<test_suite_name::ParamType>, \ ::testing::internal::DefaultParamName<test_suite_name::ParamType>, \
DUMMY_PARAM_))); \ DUMMY_PARAM_))); \
auto t = std::make_tuple(__VA_ARGS__); \ auto t = std::make_tuple(__VA_ARGS__); \
static_assert(std::tuple_size<decltype(t)>::value <= 2, \ static_assert(std::tuple_size<decltype(t)>::value <= 2, \
"Too Many Args!"); \ "Too Many Args!"); \
} \ } \
return ((GTEST_EXPAND_(GTEST_GET_SECOND_( \ return ((GTEST_EXPAND_(GTEST_GET_SECOND_( \
__VA_ARGS__, \ __VA_ARGS__, \
::testing::internal::DefaultParamName<test_suite_name::ParamType>, \ ::testing::internal::DefaultParamName<test_suite_name::ParamType>, \
DUMMY_PARAM_))))(info); \ DUMMY_PARAM_))))(info); \
} \ } \
static int gtest_##prefix##test_suite_name##_dummy_ \ static int gtest_##prefix##test_suite_name##_dummy_ \
GTEST_ATTRIBUTE_UNUSED_ = \ GTEST_ATTRIBUTE_UNUSED_ = \
::testing::UnitTest::GetInstance() \ ::testing::UnitTest::GetInstance() \
->parameterized_test_registry() \ ->parameterized_test_registry() \
.GetTestSuitePatternHolder<test_suite_name>( \ .GetTestSuitePatternHolder<test_suite_name>( \
GTEST_STRINGIFY_(test_suite_name), \ GTEST_STRINGIFY_(test_suite_name), \
::testing::internal::CodeLocation(__FILE__, __LINE__)) \ ::testing::internal::CodeLocation(__FILE__, __LINE__)) \
->AddTestSuiteInstantiation( \ ->AddTestSuiteInstantiation( \
GTEST_STRINGIFY_(prefix), \ GTEST_STRINGIFY_(prefix), \
&gtest_##prefix##test_suite_name##_EvalGenerator_, \ &gtest_##prefix##test_suite_name##_EvalGenerator_, \
&gtest_##prefix##test_suite_name##_EvalGenerateName_, \ &gtest_##prefix##test_suite_name##_EvalGenerateName_, \
__FILE__, __LINE__) __FILE__, __LINE__)
// Allow Marking a Parameterized test class as not needing to be instantiated. // 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 {} \ namespace gtest_do_not_use_outside_namespace_scope {} \
static const ::testing::internal::MarkAsIgnored gtest_allow_ignore_##T( \ static const ::testing::internal::MarkAsIgnored gtest_allow_ignore_##T( \
GTEST_STRINGIFY_(T)) GTEST_STRINGIFY_(T))

View File

@ -258,12 +258,10 @@ struct ConvertibleToStringViewPrinter {
#endif #endif
}; };
// Prints the given number of bytes in the given object to the given // Prints the given number of bytes in the given object to the given
// ostream. // ostream.
GTEST_API_ void PrintBytesInObjectTo(const unsigned char* obj_bytes, GTEST_API_ void PrintBytesInObjectTo(const unsigned char* obj_bytes,
size_t count, size_t count, ::std::ostream* os);
::std::ostream* os);
struct RawBytesPrinter { struct RawBytesPrinter {
// SFINAE on `sizeof` to make sure we have a complete type. // SFINAE on `sizeof` to make sure we have a complete type.
template <typename T, size_t = sizeof(T)> 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. // 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) \ #define GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(CharType, OtherStringType) \
template <> \ template <> \
class FormatForComparison<CharType*, OtherStringType> { \ class FormatForComparison<CharType*, OtherStringType> { \
public: \ public: \
static ::std::string Format(CharType* value) { \ static ::std::string Format(CharType* value) { \
return ::testing::PrintToString(value); \ return ::testing::PrintToString(value); \
} \ } \
} }
GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(char, ::std::string); 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. // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.
template <typename T1, typename T2> template <typename T1, typename T2>
std::string FormatForComparisonFailureMessage( std::string FormatForComparisonFailureMessage(const T1& value,
const T1& value, const T2& /* other_operand */) { const T2& /* other_operand */) {
return FormatForComparison<T1, T2>::Format(value); 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. // 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) { inline void PrintTo(const ::std::string& s, ::std::ostream* os) {
PrintStringTo(s, os); PrintStringTo(s, os);
} }
@ -579,7 +577,7 @@ inline void PrintTo(const ::std::u32string& s, ::std::ostream* os) {
// Overloads for ::std::wstring. // Overloads for ::std::wstring.
#if GTEST_HAS_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) { inline void PrintTo(const ::std::wstring& s, ::std::ostream* os) {
PrintWideStringTo(s, 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. // This overload prints a (const) char array compactly.
GTEST_API_ void UniversalPrintArray( GTEST_API_ void UniversalPrintArray(const char* begin, size_t len,
const char* begin, size_t len, ::std::ostream* os); ::std::ostream* os);
#ifdef __cpp_char8_t #ifdef __cpp_char8_t
// This overload prints a (const) char8_t array compactly. // 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); ::std::ostream* os);
// This overload prints a (const) wchar_t array compactly. // This overload prints a (const) wchar_t array compactly.
GTEST_API_ void UniversalPrintArray( GTEST_API_ void UniversalPrintArray(const wchar_t* begin, size_t len,
const wchar_t* begin, size_t len, ::std::ostream* os); ::std::ostream* os);
// Implements printing an array type T[N]. // Implements printing an array type T[N].
template <typename T, size_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); 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, // Tersely prints the first N fields of a tuple to a string vector,
// one element for each field. // one element for each field.
template <typename Tuple> template <typename Tuple>
void TersePrintPrefixToStrings(const Tuple&, std::integral_constant<size_t, 0>, void TersePrintPrefixToStrings(const Tuple&, std::integral_constant<size_t, 0>,
Strings*) {} Strings*) {}

View File

@ -101,6 +101,7 @@ class GTEST_API_ SingleFailureChecker {
SingleFailureChecker(const TestPartResultArray* results, SingleFailureChecker(const TestPartResultArray* results,
TestPartResult::Type type, const std::string& substr); TestPartResult::Type type, const std::string& substr);
~SingleFailureChecker(); ~SingleFailureChecker();
private: private:
const TestPartResultArray* const results_; const TestPartResultArray* const results_;
const TestPartResult::Type type_; const TestPartResult::Type type_;
@ -138,38 +139,39 @@ GTEST_DISABLE_MSC_WARNINGS_POP_() // 4251
// helper macro, due to some peculiarity in how the preprocessor // helper macro, due to some peculiarity in how the preprocessor
// works. The AcceptsMacroThatExpandsToUnprotectedComma test in // works. The AcceptsMacroThatExpandsToUnprotectedComma test in
// gtest_unittest.cc will fail to compile if we do that. // gtest_unittest.cc will fail to compile if we do that.
#define EXPECT_FATAL_FAILURE(statement, substr) \ #define EXPECT_FATAL_FAILURE(statement, substr) \
do { \ do { \
class GTestExpectFatalFailureHelper {\ class GTestExpectFatalFailureHelper { \
public:\ public: \
static void Execute() { statement; }\ static void Execute() { statement; } \
};\ }; \
::testing::TestPartResultArray gtest_failures;\ ::testing::TestPartResultArray gtest_failures; \
::testing::internal::SingleFailureChecker gtest_checker(\ ::testing::internal::SingleFailureChecker gtest_checker( \
&gtest_failures, ::testing::TestPartResult::kFatalFailure, (substr));\ &gtest_failures, ::testing::TestPartResult::kFatalFailure, (substr)); \
{\ { \
::testing::ScopedFakeTestPartResultReporter gtest_reporter(\ ::testing::ScopedFakeTestPartResultReporter gtest_reporter( \
::testing::ScopedFakeTestPartResultReporter:: \ ::testing::ScopedFakeTestPartResultReporter:: \
INTERCEPT_ONLY_CURRENT_THREAD, &gtest_failures);\ INTERCEPT_ONLY_CURRENT_THREAD, \
GTestExpectFatalFailureHelper::Execute();\ &gtest_failures); \
}\ GTestExpectFatalFailureHelper::Execute(); \
} \
} while (::testing::internal::AlwaysFalse()) } while (::testing::internal::AlwaysFalse())
#define EXPECT_FATAL_FAILURE_ON_ALL_THREADS(statement, substr) \ #define EXPECT_FATAL_FAILURE_ON_ALL_THREADS(statement, substr) \
do { \ do { \
class GTestExpectFatalFailureHelper {\ class GTestExpectFatalFailureHelper { \
public:\ public: \
static void Execute() { statement; }\ static void Execute() { statement; } \
};\ }; \
::testing::TestPartResultArray gtest_failures;\ ::testing::TestPartResultArray gtest_failures; \
::testing::internal::SingleFailureChecker gtest_checker(\ ::testing::internal::SingleFailureChecker gtest_checker( \
&gtest_failures, ::testing::TestPartResult::kFatalFailure, (substr));\ &gtest_failures, ::testing::TestPartResult::kFatalFailure, (substr)); \
{\ { \
::testing::ScopedFakeTestPartResultReporter gtest_reporter(\ ::testing::ScopedFakeTestPartResultReporter gtest_reporter( \
::testing::ScopedFakeTestPartResultReporter:: \ ::testing::ScopedFakeTestPartResultReporter::INTERCEPT_ALL_THREADS, \
INTERCEPT_ALL_THREADS, &gtest_failures);\ &gtest_failures); \
GTestExpectFatalFailureHelper::Execute();\ GTestExpectFatalFailureHelper::Execute(); \
}\ } \
} while (::testing::internal::AlwaysFalse()) } while (::testing::internal::AlwaysFalse())
// A macro for testing Google Test assertions or code that's expected to // 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 // instead of
// GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement) // GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement)
// to avoid an MSVC warning on unreachable code. // to avoid an MSVC warning on unreachable code.
#define EXPECT_NONFATAL_FAILURE(statement, substr) \ #define EXPECT_NONFATAL_FAILURE(statement, substr) \
do {\ do { \
::testing::TestPartResultArray gtest_failures;\ ::testing::TestPartResultArray gtest_failures; \
::testing::internal::SingleFailureChecker gtest_checker(\ ::testing::internal::SingleFailureChecker gtest_checker( \
&gtest_failures, ::testing::TestPartResult::kNonFatalFailure, \ &gtest_failures, ::testing::TestPartResult::kNonFatalFailure, \
(substr));\ (substr)); \
{\ { \
::testing::ScopedFakeTestPartResultReporter gtest_reporter(\ ::testing::ScopedFakeTestPartResultReporter gtest_reporter( \
::testing::ScopedFakeTestPartResultReporter:: \ ::testing::ScopedFakeTestPartResultReporter:: \
INTERCEPT_ONLY_CURRENT_THREAD, &gtest_failures);\ INTERCEPT_ONLY_CURRENT_THREAD, \
if (::testing::internal::AlwaysTrue()) { statement; }\ &gtest_failures); \
}\ if (::testing::internal::AlwaysTrue()) { \
statement; \
} \
} \
} while (::testing::internal::AlwaysFalse()) } while (::testing::internal::AlwaysFalse())
#define EXPECT_NONFATAL_FAILURE_ON_ALL_THREADS(statement, substr) \ #define EXPECT_NONFATAL_FAILURE_ON_ALL_THREADS(statement, substr) \
do {\ do { \
::testing::TestPartResultArray gtest_failures;\ ::testing::TestPartResultArray gtest_failures; \
::testing::internal::SingleFailureChecker gtest_checker(\ ::testing::internal::SingleFailureChecker gtest_checker( \
&gtest_failures, ::testing::TestPartResult::kNonFatalFailure, \ &gtest_failures, ::testing::TestPartResult::kNonFatalFailure, \
(substr));\ (substr)); \
{\ { \
::testing::ScopedFakeTestPartResultReporter gtest_reporter(\ ::testing::ScopedFakeTestPartResultReporter gtest_reporter( \
::testing::ScopedFakeTestPartResultReporter::INTERCEPT_ALL_THREADS, \ ::testing::ScopedFakeTestPartResultReporter::INTERCEPT_ALL_THREADS, \
&gtest_failures);\ &gtest_failures); \
if (::testing::internal::AlwaysTrue()) { statement; }\ if (::testing::internal::AlwaysTrue()) { \
}\ statement; \
} \
} \
} while (::testing::internal::AlwaysFalse()) } while (::testing::internal::AlwaysFalse())
#endif // GOOGLETEST_INCLUDE_GTEST_GTEST_SPI_H_ #endif // GOOGLETEST_INCLUDE_GTEST_GTEST_SPI_H_

View File

@ -36,6 +36,7 @@
#include <iosfwd> #include <iosfwd>
#include <vector> #include <vector>
#include "gtest/internal/gtest-internal.h" #include "gtest/internal/gtest-internal.h"
#include "gtest/internal/gtest-string.h" #include "gtest/internal/gtest-string.h"
@ -170,6 +171,7 @@ class GTEST_API_ HasNewFatalFailureHelper
~HasNewFatalFailureHelper() override; ~HasNewFatalFailureHelper() override;
void ReportTestPartResult(const TestPartResult& result) override; void ReportTestPartResult(const TestPartResult& result) override;
bool has_new_fatal_failure() const { return has_new_fatal_failure_; } bool has_new_fatal_failure() const { return has_new_fatal_failure_; }
private: private:
bool has_new_fatal_failure_; bool has_new_fatal_failure_;
TestPartResultReporterInterface* original_reporter_; TestPartResultReporterInterface* original_reporter_;

View File

@ -192,7 +192,7 @@ INSTANTIATE_TYPED_TEST_SUITE_P(My, FooTest, MyTypes);
typedef ::testing::internal::GenerateTypeList<Types>::type \ typedef ::testing::internal::GenerateTypeList<Types>::type \
GTEST_TYPE_PARAMS_(CaseName); \ GTEST_TYPE_PARAMS_(CaseName); \
typedef ::testing::internal::NameGeneratorSelector<__VA_ARGS__>::type \ typedef ::testing::internal::NameGeneratorSelector<__VA_ARGS__>::type \
GTEST_NAME_GENERATOR_(CaseName) GTEST_NAME_GENERATOR_(CaseName)
#define TYPED_TEST(CaseName, TestName) \ #define TYPED_TEST(CaseName, TestName) \
static_assert(sizeof(GTEST_STRINGIFY_(TestName)) > 1, \ 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. // #included in multiple translation units linked together.
#define TYPED_TEST_SUITE_P(SuiteName) \ #define TYPED_TEST_SUITE_P(SuiteName) \
static ::testing::internal::TypedTestSuitePState \ 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 // Legacy API is deprecated but still available
#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_ #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
@ -303,21 +303,21 @@ INSTANTIATE_TYPED_TEST_SUITE_P(My, FooTest, MyTypes);
REGISTER_TYPED_TEST_SUITE_P REGISTER_TYPED_TEST_SUITE_P
#endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_ #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
#define INSTANTIATE_TYPED_TEST_SUITE_P(Prefix, SuiteName, Types, ...) \ #define INSTANTIATE_TYPED_TEST_SUITE_P(Prefix, SuiteName, Types, ...) \
static_assert(sizeof(GTEST_STRINGIFY_(Prefix)) > 1, \ static_assert(sizeof(GTEST_STRINGIFY_(Prefix)) > 1, \
"test-suit-prefix must not be empty"); \ "test-suit-prefix must not be empty"); \
static bool gtest_##Prefix##_##SuiteName GTEST_ATTRIBUTE_UNUSED_ = \ static bool gtest_##Prefix##_##SuiteName GTEST_ATTRIBUTE_UNUSED_ = \
::testing::internal::TypeParameterizedTestSuite< \ ::testing::internal::TypeParameterizedTestSuite< \
SuiteName, GTEST_SUITE_NAMESPACE_(SuiteName)::gtest_AllTests_, \ SuiteName, GTEST_SUITE_NAMESPACE_(SuiteName)::gtest_AllTests_, \
::testing::internal::GenerateTypeList<Types>::type>:: \ ::testing::internal::GenerateTypeList<Types>::type>:: \
Register(GTEST_STRINGIFY_(Prefix), \ Register(GTEST_STRINGIFY_(Prefix), \
::testing::internal::CodeLocation(__FILE__, __LINE__), \ ::testing::internal::CodeLocation(__FILE__, __LINE__), \
&GTEST_TYPED_TEST_SUITE_P_STATE_(SuiteName), \ &GTEST_TYPED_TEST_SUITE_P_STATE_(SuiteName), \
GTEST_STRINGIFY_(SuiteName), \ GTEST_STRINGIFY_(SuiteName), \
GTEST_REGISTERED_TEST_NAMES_(SuiteName), \ GTEST_REGISTERED_TEST_NAMES_(SuiteName), \
::testing::internal::GenerateNames< \ ::testing::internal::GenerateNames< \
::testing::internal::NameGeneratorSelector< \ ::testing::internal::NameGeneratorSelector< \
__VA_ARGS__>::type, \ __VA_ARGS__>::type, \
::testing::internal::GenerateTypeList<Types>::type>()) ::testing::internal::GenerateTypeList<Types>::type>())
// Legacy API is deprecated but still available // Legacy API is deprecated but still available

View File

@ -353,24 +353,17 @@ class TestProperty {
// C'tor. TestProperty does NOT have a default constructor. // C'tor. TestProperty does NOT have a default constructor.
// Always use this constructor (with parameters) to create a // Always use this constructor (with parameters) to create a
// TestProperty object. // TestProperty object.
TestProperty(const std::string& a_key, const std::string& a_value) : TestProperty(const std::string& a_key, const std::string& a_value)
key_(a_key), value_(a_value) { : key_(a_key), value_(a_value) {}
}
// Gets the user supplied key. // Gets the user supplied key.
const char* key() const { const char* key() const { return key_.c_str(); }
return key_.c_str();
}
// Gets the user supplied value. // Gets the user supplied value.
const char* value() const { const char* value() const { return value_.c_str(); }
return value_.c_str();
}
// Sets a new value, overriding the one supplied in the constructor. // Sets a new value, overriding the one supplied in the constructor.
void SetValue(const std::string& new_value) { void SetValue(const std::string& new_value) { value_ = new_value; }
value_ = new_value;
}
private: private:
// The key supplied by the user. // The key supplied by the user.
@ -628,8 +621,8 @@ class GTEST_API_ TestInfo {
} }
// These fields are immutable properties of the test. // These fields are immutable properties of the test.
const std::string test_suite_name_; // test suite name const std::string test_suite_name_; // test suite name
const std::string name_; // Test name const std::string name_; // Test name
// Name of the parameter type, or NULL if this is not a typed or a // Name of the parameter type, or NULL if this is not a typed or a
// type-parameterized test. // type-parameterized test.
const std::unique_ptr<const ::std::string> type_param_; 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 // Adds a TestInfo to this test suite. Will delete the TestInfo upon
// destruction of the TestSuite object. // 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. // Clears the results of all tests in this test suite.
void ClearResult(); void ClearResult();
@ -886,6 +879,7 @@ class Environment {
// Override this to define how to tear down the environment. // Override this to define how to tear down the environment.
virtual void TearDown() {} virtual void TearDown() {}
private: private:
// If you see an error about overriding the following function or // If you see an error about overriding the following function or
// about it being private, you have mis-spelled SetUp() as Setup(). // 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; virtual void OnEnvironmentsTearDownEnd(const UnitTest& unit_test) = 0;
// Fired after each iteration of tests finishes. // Fired after each iteration of tests finishes.
virtual void OnTestIterationEnd(const UnitTest& unit_test, virtual void OnTestIterationEnd(const UnitTest& unit_test, int iteration) = 0;
int iteration) = 0;
// Fired after all test activities have ended. // Fired after all test activities have ended.
virtual void OnTestProgramEnd(const UnitTest& unit_test) = 0; 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, // Returns the TestInfo object for the test that's currently running,
// or NULL if no test is running. // or NULL if no test is running.
const TestInfo* current_test_info() const const TestInfo* current_test_info() const GTEST_LOCK_EXCLUDED_(mutex_);
GTEST_LOCK_EXCLUDED_(mutex_);
// Returns the random seed used at the start of the current test run. // Returns the random seed used at the start of the current test run.
int random_seed() const; int random_seed() const;
@ -1229,8 +1221,7 @@ class GTEST_API_ UnitTest {
// eventually call this to report their results. The user code // eventually call this to report their results. The user code
// should use the assertion macros instead of calling this directly. // should use the assertion macros instead of calling this directly.
void AddTestPartResult(TestPartResult::Type result_type, void AddTestPartResult(TestPartResult::Type result_type,
const char* file_name, const char* file_name, int line_number,
int line_number,
const std::string& message, const std::string& message,
const std::string& os_stack_trace) const std::string& os_stack_trace)
GTEST_LOCK_EXCLUDED_(mutex_); GTEST_LOCK_EXCLUDED_(mutex_);
@ -1261,8 +1252,7 @@ class GTEST_API_ UnitTest {
friend std::set<std::string>* internal::GetIgnoredParameterizedTestSuites(); friend std::set<std::string>* internal::GetIgnoredParameterizedTestSuites();
friend internal::UnitTestImpl* internal::GetUnitTestImpl(); friend internal::UnitTestImpl* internal::GetUnitTestImpl();
friend void internal::ReportFailureInUnknownLocation( friend void internal::ReportFailureInUnknownLocation(
TestPartResult::Type result_type, TestPartResult::Type result_type, const std::string& message);
const std::string& message);
// Creates an empty UnitTest. // Creates an empty UnitTest.
UnitTest(); UnitTest();
@ -1276,8 +1266,7 @@ class GTEST_API_ UnitTest {
GTEST_LOCK_EXCLUDED_(mutex_); GTEST_LOCK_EXCLUDED_(mutex_);
// Pops a trace from the per-thread Google Test trace stack. // Pops a trace from the per-thread Google Test trace stack.
void PopGTestTrace() void PopGTestTrace() GTEST_LOCK_EXCLUDED_(mutex_);
GTEST_LOCK_EXCLUDED_(mutex_);
// Protects mutable state in *impl_. This is mutable as some const // Protects mutable state in *impl_. This is mutable as some const
// methods need to lock it too. // methods need to lock it too.
@ -1341,13 +1330,11 @@ namespace internal {
// when calling EXPECT_* in a tight loop. // when calling EXPECT_* in a tight loop.
template <typename T1, typename T2> template <typename T1, typename T2>
AssertionResult CmpHelperEQFailure(const char* lhs_expression, AssertionResult CmpHelperEQFailure(const char* lhs_expression,
const char* rhs_expression, const char* rhs_expression, const T1& lhs,
const T1& lhs, const T2& rhs) { const T2& rhs) {
return EqFailure(lhs_expression, return EqFailure(lhs_expression, rhs_expression,
rhs_expression,
FormatForComparisonFailureMessage(lhs, rhs), FormatForComparisonFailureMessage(lhs, rhs),
FormatForComparisonFailureMessage(rhs, lhs), FormatForComparisonFailureMessage(rhs, lhs), false);
false);
} }
// This block of code defines operator==/!= // This block of code defines operator==/!=
@ -1360,8 +1347,7 @@ inline bool operator!=(faketype, faketype) { return false; }
// The helper function for {ASSERT|EXPECT}_EQ. // The helper function for {ASSERT|EXPECT}_EQ.
template <typename T1, typename T2> template <typename T1, typename T2>
AssertionResult CmpHelperEQ(const char* lhs_expression, AssertionResult CmpHelperEQ(const char* lhs_expression,
const char* rhs_expression, const char* rhs_expression, const T1& lhs,
const T1& lhs,
const T2& rhs) { const T2& rhs) {
if (lhs == rhs) { if (lhs == rhs) {
return AssertionSuccess(); return AssertionSuccess();
@ -1392,8 +1378,7 @@ class EqHelper {
// Even though its body looks the same as the above version, we // Even though its body looks the same as the above version, we
// cannot merge the two, as it will make anonymous enums unhappy. // cannot merge the two, as it will make anonymous enums unhappy.
static AssertionResult Compare(const char* lhs_expression, static AssertionResult Compare(const char* lhs_expression,
const char* rhs_expression, const char* rhs_expression, BiggestInt lhs,
BiggestInt lhs,
BiggestInt rhs) { BiggestInt rhs) {
return CmpHelperEQ(lhs_expression, rhs_expression, lhs, 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. // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.
#define GTEST_IMPL_CMP_HELPER_(op_name, op)\ #define GTEST_IMPL_CMP_HELPER_(op_name, op) \
template <typename T1, typename T2>\ template <typename T1, typename T2> \
AssertionResult CmpHelper##op_name(const char* expr1, const char* expr2, \ AssertionResult CmpHelper##op_name(const char* expr1, const char* expr2, \
const T1& val1, const T2& val2) {\ const T1& val1, const T2& val2) { \
if (val1 op val2) {\ if (val1 op val2) { \
return AssertionSuccess();\ return AssertionSuccess(); \
} else {\ } else { \
return CmpHelperOpFailure(expr1, expr2, val1, val2, #op);\ return CmpHelperOpFailure(expr1, expr2, val1, val2, #op); \
}\ } \
} }
// INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM. // 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. // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.
GTEST_API_ AssertionResult CmpHelperSTREQ(const char* s1_expression, GTEST_API_ AssertionResult CmpHelperSTREQ(const char* s1_expression,
const char* s2_expression, const char* s2_expression,
const char* s1, const char* s1, const char* s2);
const char* s2);
// The helper function for {ASSERT|EXPECT}_STRCASEEQ. // The helper function for {ASSERT|EXPECT}_STRCASEEQ.
// //
// INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM. // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.
GTEST_API_ AssertionResult CmpHelperSTRCASEEQ(const char* s1_expression, GTEST_API_ AssertionResult CmpHelperSTRCASEEQ(const char* s1_expression,
const char* s2_expression, const char* s2_expression,
const char* s1, const char* s1, const char* s2);
const char* s2);
// The helper function for {ASSERT|EXPECT}_STRNE. // The helper function for {ASSERT|EXPECT}_STRNE.
// //
// INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM. // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.
GTEST_API_ AssertionResult CmpHelperSTRNE(const char* s1_expression, GTEST_API_ AssertionResult CmpHelperSTRNE(const char* s1_expression,
const char* s2_expression, const char* s2_expression,
const char* s1, const char* s1, const char* s2);
const char* s2);
// The helper function for {ASSERT|EXPECT}_STRCASENE. // The helper function for {ASSERT|EXPECT}_STRCASENE.
// //
// INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM. // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.
GTEST_API_ AssertionResult CmpHelperSTRCASENE(const char* s1_expression, GTEST_API_ AssertionResult CmpHelperSTRCASENE(const char* s1_expression,
const char* s2_expression, const char* s2_expression,
const char* s1, const char* s1, const char* s2);
const char* s2);
// Helper function for *_STREQ on wide strings. // Helper function for *_STREQ on wide strings.
// //
// INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM. // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.
GTEST_API_ AssertionResult CmpHelperSTREQ(const char* s1_expression, GTEST_API_ AssertionResult CmpHelperSTREQ(const char* s1_expression,
const char* s2_expression, const char* s2_expression,
const wchar_t* s1, const wchar_t* s1, const wchar_t* s2);
const wchar_t* s2);
// Helper function for *_STRNE on wide strings. // Helper function for *_STRNE on wide strings.
// //
// INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM. // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.
GTEST_API_ AssertionResult CmpHelperSTRNE(const char* s1_expression, GTEST_API_ AssertionResult CmpHelperSTRNE(const char* s1_expression,
const char* s2_expression, const char* s2_expression,
const wchar_t* s1, const wchar_t* s1, const wchar_t* s2);
const wchar_t* s2);
} // namespace internal } // namespace internal
@ -1513,32 +1491,40 @@ GTEST_API_ AssertionResult CmpHelperSTRNE(const char* s1_expression,
// //
// The {needle,haystack}_expr arguments are the stringified // The {needle,haystack}_expr arguments are the stringified
// expressions that generated the two real arguments. // expressions that generated the two real arguments.
GTEST_API_ AssertionResult IsSubstring( GTEST_API_ AssertionResult IsSubstring(const char* needle_expr,
const char* needle_expr, const char* haystack_expr, const char* haystack_expr,
const char* needle, const char* haystack); const char* needle,
GTEST_API_ AssertionResult IsSubstring( const char* haystack);
const char* needle_expr, const char* haystack_expr, GTEST_API_ AssertionResult IsSubstring(const char* needle_expr,
const wchar_t* needle, const wchar_t* haystack); const char* haystack_expr,
GTEST_API_ AssertionResult IsNotSubstring( const wchar_t* needle,
const char* needle_expr, const char* haystack_expr, const wchar_t* haystack);
const char* needle, const char* haystack); GTEST_API_ AssertionResult IsNotSubstring(const char* needle_expr,
GTEST_API_ AssertionResult IsNotSubstring( const char* haystack_expr,
const char* needle_expr, const char* haystack_expr, const char* needle,
const wchar_t* needle, const wchar_t* haystack); const char* haystack);
GTEST_API_ AssertionResult IsSubstring( GTEST_API_ AssertionResult IsNotSubstring(const char* needle_expr,
const char* needle_expr, const char* haystack_expr, const char* haystack_expr,
const ::std::string& needle, const ::std::string& haystack); const wchar_t* needle,
GTEST_API_ AssertionResult IsNotSubstring( const wchar_t* haystack);
const char* needle_expr, const char* haystack_expr, GTEST_API_ AssertionResult IsSubstring(const char* needle_expr,
const ::std::string& needle, const ::std::string& haystack); 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 #if GTEST_HAS_STD_WSTRING
GTEST_API_ AssertionResult IsSubstring( GTEST_API_ AssertionResult IsSubstring(const char* needle_expr,
const char* needle_expr, const char* haystack_expr, const char* haystack_expr,
const ::std::wstring& needle, const ::std::wstring& haystack); const ::std::wstring& needle,
GTEST_API_ AssertionResult IsNotSubstring( const ::std::wstring& haystack);
const char* needle_expr, const char* haystack_expr, GTEST_API_ AssertionResult IsNotSubstring(const char* needle_expr,
const ::std::wstring& needle, const ::std::wstring& haystack); const char* haystack_expr,
const ::std::wstring& needle,
const ::std::wstring& haystack);
#endif // GTEST_HAS_STD_WSTRING #endif // GTEST_HAS_STD_WSTRING
namespace internal { namespace internal {
@ -1553,8 +1539,7 @@ namespace internal {
template <typename RawType> template <typename RawType>
AssertionResult CmpHelperFloatingPointEQ(const char* lhs_expression, AssertionResult CmpHelperFloatingPointEQ(const char* lhs_expression,
const char* rhs_expression, const char* rhs_expression,
RawType lhs_value, RawType lhs_value, RawType rhs_value) {
RawType rhs_value) {
const FloatingPoint<RawType> lhs(lhs_value), rhs(rhs_value); const FloatingPoint<RawType> lhs(lhs_value), rhs(rhs_value);
if (lhs.AlmostEquals(rhs)) { 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_ss << std::setprecision(std::numeric_limits<RawType>::digits10 + 2)
<< rhs_value; << rhs_value;
return EqFailure(lhs_expression, return EqFailure(lhs_expression, rhs_expression,
rhs_expression, StringStreamToString(&lhs_ss), StringStreamToString(&rhs_ss),
StringStreamToString(&lhs_ss),
StringStreamToString(&rhs_ss),
false); false);
} }
@ -1582,8 +1565,7 @@ AssertionResult CmpHelperFloatingPointEQ(const char* lhs_expression,
GTEST_API_ AssertionResult DoubleNearPredFormat(const char* expr1, GTEST_API_ AssertionResult DoubleNearPredFormat(const char* expr1,
const char* expr2, const char* expr2,
const char* abs_error_expr, const char* abs_error_expr,
double val1, double val1, double val2,
double val2,
double abs_error); double abs_error);
// INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE. // INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE.
@ -1591,9 +1573,7 @@ GTEST_API_ AssertionResult DoubleNearPredFormat(const char* expr1,
class GTEST_API_ AssertHelper { class GTEST_API_ AssertHelper {
public: public:
// Constructor. // Constructor.
AssertHelper(TestPartResult::Type type, AssertHelper(TestPartResult::Type type, const char* file, int line,
const char* file,
int line,
const char* message); const char* message);
~AssertHelper(); ~AssertHelper();
@ -1607,11 +1587,9 @@ class GTEST_API_ AssertHelper {
// re-using stack space even for temporary variables, so every EXPECT_EQ // re-using stack space even for temporary variables, so every EXPECT_EQ
// reserves stack space for another AssertHelper. // reserves stack space for another AssertHelper.
struct AssertHelperData { struct AssertHelperData {
AssertHelperData(TestPartResult::Type t, AssertHelperData(TestPartResult::Type t, const char* srcfile, int line_num,
const char* srcfile,
int line_num,
const char* msg) 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; TestPartResult::Type const type;
const char* const file; const char* const file;
@ -1681,15 +1659,14 @@ class WithParamInterface {
private: private:
// Sets parameter value. The caller is responsible for making sure the value // Sets parameter value. The caller is responsible for making sure the value
// remains alive and unchanged throughout the current test. // remains alive and unchanged throughout the current test.
static void SetParam(const ParamType* parameter) { static void SetParam(const ParamType* parameter) { parameter_ = parameter; }
parameter_ = parameter;
}
// Static value used for accessing parameter during a test lifetime. // Static value used for accessing parameter during a test lifetime.
static const ParamType* parameter_; static const ParamType* parameter_;
// TestClass must be a subclass of WithParamInterface<T> and Test. // 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> template <typename T>
@ -1699,8 +1676,7 @@ const T* WithParamInterface<T>::parameter_ = nullptr;
// WithParamInterface, and can just inherit from ::testing::TestWithParam. // WithParamInterface, and can just inherit from ::testing::TestWithParam.
template <typename T> 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. // 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 // Generates a nonfatal failure at the given source file location with
// a generic message. // a generic message.
#define ADD_FAILURE_AT(file, line) \ #define ADD_FAILURE_AT(file, line) \
GTEST_MESSAGE_AT_(file, line, "Failed", \ GTEST_MESSAGE_AT_(file, line, "Failed", \
::testing::TestPartResult::kNonFatalFailure) ::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 // Define this macro to 1 to omit the definition of FAIL(), which is a
// generic name and clashes with some other libraries. // generic name and clashes with some other libraries.
#if !GTEST_DONT_DEFINE_FAIL #if !GTEST_DONT_DEFINE_FAIL
# define FAIL() GTEST_FAIL() #define FAIL() GTEST_FAIL()
#endif #endif
// Generates a success with a generic message. // 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 // Define this macro to 1 to omit the definition of SUCCEED(), which
// is a generic name and clashes with some other libraries. // is a generic name and clashes with some other libraries.
#if !GTEST_DONT_DEFINE_SUCCEED #if !GTEST_DONT_DEFINE_SUCCEED
# define SUCCEED() GTEST_SUCCEED() #define SUCCEED() GTEST_SUCCEED()
#endif #endif
// Macros for testing exceptions. // 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 // Boolean assertions. Condition can be either a Boolean expression or an
// AssertionResult. For more information on how to use AssertionResult with // AssertionResult. For more information on how to use AssertionResult with
// these macros see comments on that class. // 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_TEST_BOOLEAN_(condition, #condition, false, true, \
GTEST_NONFATAL_FAILURE_) GTEST_NONFATAL_FAILURE_)
#define GTEST_EXPECT_FALSE(condition) \ #define GTEST_EXPECT_FALSE(condition) \
GTEST_TEST_BOOLEAN_(!(condition), #condition, true, false, \ GTEST_TEST_BOOLEAN_(!(condition), #condition, true, false, \
GTEST_NONFATAL_FAILURE_) GTEST_NONFATAL_FAILURE_)
#define GTEST_ASSERT_TRUE(condition) \ #define GTEST_ASSERT_TRUE(condition) \
GTEST_TEST_BOOLEAN_(condition, #condition, false, true, \ GTEST_TEST_BOOLEAN_(condition, #condition, false, true, GTEST_FATAL_FAILURE_)
GTEST_FATAL_FAILURE_) #define GTEST_ASSERT_FALSE(condition) \
#define GTEST_ASSERT_FALSE(condition) \
GTEST_TEST_BOOLEAN_(!(condition), #condition, true, false, \ GTEST_TEST_BOOLEAN_(!(condition), #condition, true, false, \
GTEST_FATAL_FAILURE_) GTEST_FATAL_FAILURE_)
@ -1891,27 +1866,27 @@ class TestWithParam : public Test, public WithParamInterface<T> {
// ASSERT_XY(), which clashes with some users' own code. // ASSERT_XY(), which clashes with some users' own code.
#if !GTEST_DONT_DEFINE_ASSERT_EQ #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 #endif
#if !GTEST_DONT_DEFINE_ASSERT_NE #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 #endif
#if !GTEST_DONT_DEFINE_ASSERT_LE #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 #endif
#if !GTEST_DONT_DEFINE_ASSERT_LT #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 #endif
#if !GTEST_DONT_DEFINE_ASSERT_GE #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 #endif
#if !GTEST_DONT_DEFINE_ASSERT_GT #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 #endif
// C-string Comparisons. All tests treat NULL and any non-NULL string // 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) EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperSTRNE, s1, s2)
#define EXPECT_STRCASEEQ(s1, s2) \ #define EXPECT_STRCASEEQ(s1, s2) \
EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperSTRCASEEQ, 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) EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperSTRCASENE, s1, s2)
#define ASSERT_STREQ(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) ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperSTRNE, s1, s2)
#define ASSERT_STRCASEEQ(s1, s2) \ #define ASSERT_STRCASEEQ(s1, s2) \
ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperSTRCASEEQ, 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) ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperSTRCASENE, s1, s2)
// Macros for comparing floating-point numbers. // 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 // FloatingPoint template class in gtest-internal.h if you are
// interested in the implementation details. // interested in the implementation details.
#define EXPECT_FLOAT_EQ(val1, val2)\ #define EXPECT_FLOAT_EQ(val1, val2) \
EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperFloatingPointEQ<float>, \ EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperFloatingPointEQ<float>, \
val1, val2) val1, val2)
#define EXPECT_DOUBLE_EQ(val1, val2)\ #define EXPECT_DOUBLE_EQ(val1, val2) \
EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperFloatingPointEQ<double>, \ EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperFloatingPointEQ<double>, \
val1, val2) val1, val2)
#define ASSERT_FLOAT_EQ(val1, val2)\ #define ASSERT_FLOAT_EQ(val1, val2) \
ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperFloatingPointEQ<float>, \ ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperFloatingPointEQ<float>, \
val1, val2) val1, val2)
#define ASSERT_DOUBLE_EQ(val1, val2)\ #define ASSERT_DOUBLE_EQ(val1, val2) \
ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperFloatingPointEQ<double>, \ ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperFloatingPointEQ<double>, \
val1, val2) val1, val2)
#define EXPECT_NEAR(val1, val2, abs_error)\ #define EXPECT_NEAR(val1, val2, abs_error) \
EXPECT_PRED_FORMAT3(::testing::internal::DoubleNearPredFormat, \ EXPECT_PRED_FORMAT3(::testing::internal::DoubleNearPredFormat, val1, val2, \
val1, val2, abs_error) abs_error)
#define ASSERT_NEAR(val1, val2, abs_error)\ #define ASSERT_NEAR(val1, val2, abs_error) \
ASSERT_PRED_FORMAT3(::testing::internal::DoubleNearPredFormat, \ ASSERT_PRED_FORMAT3(::testing::internal::DoubleNearPredFormat, val1, val2, \
val1, val2, abs_error) abs_error)
// These predicate format functions work on floating-point values, and // These predicate format functions work on floating-point values, and
// can be used in {ASSERT|EXPECT}_PRED_FORMAT2*(), e.g. // 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, GTEST_API_ AssertionResult DoubleLE(const char* expr1, const char* expr2,
double val1, double val2); double val1, double val2);
#if GTEST_OS_WINDOWS #if GTEST_OS_WINDOWS
// Macros that test for HRESULT failure and success, these are only useful // 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 // expected result and the actual result with both a human-readable
// string representation of the error, if available, as well as the // string representation of the error, if available, as well as the
// hex result code. // hex result code.
# define EXPECT_HRESULT_SUCCEEDED(expr) \ #define EXPECT_HRESULT_SUCCEEDED(expr) \
EXPECT_PRED_FORMAT1(::testing::internal::IsHRESULTSuccess, (expr)) EXPECT_PRED_FORMAT1(::testing::internal::IsHRESULTSuccess, (expr))
# define ASSERT_HRESULT_SUCCEEDED(expr) \ #define ASSERT_HRESULT_SUCCEEDED(expr) \
ASSERT_PRED_FORMAT1(::testing::internal::IsHRESULTSuccess, (expr)) ASSERT_PRED_FORMAT1(::testing::internal::IsHRESULTSuccess, (expr))
# define EXPECT_HRESULT_FAILED(expr) \ #define EXPECT_HRESULT_FAILED(expr) \
EXPECT_PRED_FORMAT1(::testing::internal::IsHRESULTFailure, (expr)) EXPECT_PRED_FORMAT1(::testing::internal::IsHRESULTFailure, (expr))
# define ASSERT_HRESULT_FAILED(expr) \ #define ASSERT_HRESULT_FAILED(expr) \
ASSERT_PRED_FORMAT1(::testing::internal::IsHRESULTFailure, (expr)) ASSERT_PRED_FORMAT1(::testing::internal::IsHRESULTFailure, (expr))
#endif // GTEST_OS_WINDOWS #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"; // ASSERT_NO_FATAL_FAILURE(Process()) << "Process() failed";
// //
#define ASSERT_NO_FATAL_FAILURE(statement) \ #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) \ #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, // 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 // 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. // Assuming that each thread maintains its own stack of traces.
// Therefore, a SCOPED_TRACE() would (correctly) only affect the // Therefore, a SCOPED_TRACE() would (correctly) only affect the
// assertions in its own thread. // assertions in its own thread.
#define SCOPED_TRACE(message) \ #define SCOPED_TRACE(message) \
::testing::ScopedTrace GTEST_CONCAT_TOKEN_(gtest_trace_, __LINE__)(\ ::testing::ScopedTrace GTEST_CONCAT_TOKEN_(gtest_trace_, __LINE__)( \
__FILE__, __LINE__, (message)) __FILE__, __LINE__, (message))
// Compile-time assertion for type equality. // Compile-time assertion for type equality.
// StaticAssertTypeEq<type1, type2>() compiles if and only if type1 and type2 // 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(a_.size(), 0);
// EXPECT_EQ(b_.size(), 1); // 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, \ GTEST_TEST_(test_fixture, test_name, test_fixture, \
::testing::internal::GetTypeId<test_fixture>()) ::testing::internal::GetTypeId<test_fixture>())
#if !GTEST_DONT_DEFINE_TEST_F #if !GTEST_DONT_DEFINE_TEST_F
@ -2211,7 +2185,7 @@ constexpr bool StaticAssertTypeEq() noexcept {
GTEST_API_ std::string TempDir(); GTEST_API_ std::string TempDir();
#ifdef _MSC_VER #ifdef _MSC_VER
# pragma warning(pop) #pragma warning(pop)
#endif #endif
// Dynamically registers a test with the framework. // 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. // namespace and has an all-caps name.
int RUN_ALL_TESTS() GTEST_MUST_USE_RESULT_; int RUN_ALL_TESTS() GTEST_MUST_USE_RESULT_;
inline int RUN_ALL_TESTS() { inline int RUN_ALL_TESTS() { return ::testing::UnitTest::GetInstance()->Run(); }
return ::testing::UnitTest::GetInstance()->Run();
}
GTEST_DISABLE_MSC_WARNINGS_POP_() // 4251 GTEST_DISABLE_MSC_WARNINGS_POP_() // 4251

View File

@ -74,22 +74,18 @@ namespace testing {
// GTEST_ASSERT_ is the basic statement to which all of the assertions // GTEST_ASSERT_ is the basic statement to which all of the assertions
// in this file reduce. Don't use this in your code. // in this file reduce. Don't use this in your code.
#define GTEST_ASSERT_(expression, on_failure) \ #define GTEST_ASSERT_(expression, on_failure) \
GTEST_AMBIGUOUS_ELSE_BLOCKER_ \ GTEST_AMBIGUOUS_ELSE_BLOCKER_ \
if (const ::testing::AssertionResult gtest_ar = (expression)) \ if (const ::testing::AssertionResult gtest_ar = (expression)) \
; \ ; \
else \ else \
on_failure(gtest_ar.failure_message()) on_failure(gtest_ar.failure_message())
// Helper function for implementing {EXPECT|ASSERT}_PRED1. Don't use // Helper function for implementing {EXPECT|ASSERT}_PRED1. Don't use
// this in your code. // this in your code.
template <typename Pred, template <typename Pred, typename T1>
typename T1> AssertionResult AssertPred1Helper(const char* pred_text, const char* e1,
AssertionResult AssertPred1Helper(const char* pred_text, Pred pred, const T1& v1) {
const char* e1,
Pred pred,
const T1& v1) {
if (pred(v1)) return AssertionSuccess(); if (pred(v1)) return AssertionSuccess();
return AssertionFailure() return AssertionFailure()
@ -100,40 +96,27 @@ AssertionResult AssertPred1Helper(const char* pred_text,
// Internal macro for implementing {EXPECT|ASSERT}_PRED_FORMAT1. // Internal macro for implementing {EXPECT|ASSERT}_PRED_FORMAT1.
// Don't use this in your code. // Don't use this in your code.
#define GTEST_PRED_FORMAT1_(pred_format, v1, on_failure)\ #define GTEST_PRED_FORMAT1_(pred_format, v1, on_failure) \
GTEST_ASSERT_(pred_format(#v1, v1), \ GTEST_ASSERT_(pred_format(#v1, v1), on_failure)
on_failure)
// Internal macro for implementing {EXPECT|ASSERT}_PRED1. Don't use // Internal macro for implementing {EXPECT|ASSERT}_PRED1. Don't use
// this in your code. // this in your code.
#define GTEST_PRED1_(pred, v1, on_failure)\ #define GTEST_PRED1_(pred, v1, on_failure) \
GTEST_ASSERT_(::testing::AssertPred1Helper(#pred, \ GTEST_ASSERT_(::testing::AssertPred1Helper(#pred, #v1, pred, v1), on_failure)
#v1, \
pred, \
v1), on_failure)
// Unary predicate assertion macros. // Unary predicate assertion macros.
#define EXPECT_PRED_FORMAT1(pred_format, v1) \ #define EXPECT_PRED_FORMAT1(pred_format, v1) \
GTEST_PRED_FORMAT1_(pred_format, v1, GTEST_NONFATAL_FAILURE_) GTEST_PRED_FORMAT1_(pred_format, v1, GTEST_NONFATAL_FAILURE_)
#define EXPECT_PRED1(pred, v1) \ #define EXPECT_PRED1(pred, v1) GTEST_PRED1_(pred, v1, GTEST_NONFATAL_FAILURE_)
GTEST_PRED1_(pred, v1, GTEST_NONFATAL_FAILURE_)
#define ASSERT_PRED_FORMAT1(pred_format, v1) \ #define ASSERT_PRED_FORMAT1(pred_format, v1) \
GTEST_PRED_FORMAT1_(pred_format, v1, GTEST_FATAL_FAILURE_) GTEST_PRED_FORMAT1_(pred_format, v1, GTEST_FATAL_FAILURE_)
#define ASSERT_PRED1(pred, v1) \ #define ASSERT_PRED1(pred, v1) GTEST_PRED1_(pred, v1, GTEST_FATAL_FAILURE_)
GTEST_PRED1_(pred, v1, GTEST_FATAL_FAILURE_)
// Helper function for implementing {EXPECT|ASSERT}_PRED2. Don't use // Helper function for implementing {EXPECT|ASSERT}_PRED2. Don't use
// this in your code. // this in your code.
template <typename Pred, template <typename Pred, typename T1, typename T2>
typename T1, AssertionResult AssertPred2Helper(const char* pred_text, const char* e1,
typename T2> const char* e2, Pred pred, const T1& v1,
AssertionResult AssertPred2Helper(const char* pred_text,
const char* e1,
const char* e2,
Pred pred,
const T1& v1,
const T2& v2) { const T2& v2) {
if (pred(v1, v2)) return AssertionSuccess(); if (pred(v1, v2)) return AssertionSuccess();
@ -147,19 +130,14 @@ AssertionResult AssertPred2Helper(const char* pred_text,
// Internal macro for implementing {EXPECT|ASSERT}_PRED_FORMAT2. // Internal macro for implementing {EXPECT|ASSERT}_PRED_FORMAT2.
// Don't use this in your code. // Don't use this in your code.
#define GTEST_PRED_FORMAT2_(pred_format, v1, v2, on_failure)\ #define GTEST_PRED_FORMAT2_(pred_format, v1, v2, on_failure) \
GTEST_ASSERT_(pred_format(#v1, #v2, v1, v2), \ GTEST_ASSERT_(pred_format(#v1, #v2, v1, v2), on_failure)
on_failure)
// Internal macro for implementing {EXPECT|ASSERT}_PRED2. Don't use // Internal macro for implementing {EXPECT|ASSERT}_PRED2. Don't use
// this in your code. // this in your code.
#define GTEST_PRED2_(pred, v1, v2, on_failure)\ #define GTEST_PRED2_(pred, v1, v2, on_failure) \
GTEST_ASSERT_(::testing::AssertPred2Helper(#pred, \ GTEST_ASSERT_(::testing::AssertPred2Helper(#pred, #v1, #v2, pred, v1, v2), \
#v1, \ on_failure)
#v2, \
pred, \
v1, \
v2), on_failure)
// Binary predicate assertion macros. // Binary predicate assertion macros.
#define EXPECT_PRED_FORMAT2(pred_format, v1, v2) \ #define EXPECT_PRED_FORMAT2(pred_format, v1, v2) \
@ -171,22 +149,12 @@ AssertionResult AssertPred2Helper(const char* pred_text,
#define ASSERT_PRED2(pred, v1, v2) \ #define ASSERT_PRED2(pred, v1, v2) \
GTEST_PRED2_(pred, v1, v2, GTEST_FATAL_FAILURE_) GTEST_PRED2_(pred, v1, v2, GTEST_FATAL_FAILURE_)
// Helper function for implementing {EXPECT|ASSERT}_PRED3. Don't use // Helper function for implementing {EXPECT|ASSERT}_PRED3. Don't use
// this in your code. // this in your code.
template <typename Pred, template <typename Pred, typename T1, typename T2, typename T3>
typename T1, AssertionResult AssertPred3Helper(const char* pred_text, const char* e1,
typename T2, const char* e2, const char* e3, Pred pred,
typename T3> const T1& v1, const T2& v2, const T3& v3) {
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(); if (pred(v1, v2, v3)) return AssertionSuccess();
return AssertionFailure() return AssertionFailure()
@ -200,21 +168,15 @@ AssertionResult AssertPred3Helper(const char* pred_text,
// Internal macro for implementing {EXPECT|ASSERT}_PRED_FORMAT3. // Internal macro for implementing {EXPECT|ASSERT}_PRED_FORMAT3.
// Don't use this in your code. // Don't use this in your code.
#define GTEST_PRED_FORMAT3_(pred_format, 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), \ GTEST_ASSERT_(pred_format(#v1, #v2, #v3, v1, v2, v3), on_failure)
on_failure)
// Internal macro for implementing {EXPECT|ASSERT}_PRED3. Don't use // Internal macro for implementing {EXPECT|ASSERT}_PRED3. Don't use
// this in your code. // this in your code.
#define GTEST_PRED3_(pred, v1, v2, v3, on_failure)\ #define GTEST_PRED3_(pred, v1, v2, v3, on_failure) \
GTEST_ASSERT_(::testing::AssertPred3Helper(#pred, \ GTEST_ASSERT_( \
#v1, \ ::testing::AssertPred3Helper(#pred, #v1, #v2, #v3, pred, v1, v2, v3), \
#v2, \ on_failure)
#v3, \
pred, \
v1, \
v2, \
v3), on_failure)
// Ternary predicate assertion macros. // Ternary predicate assertion macros.
#define EXPECT_PRED_FORMAT3(pred_format, v1, v2, v3) \ #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) \ #define ASSERT_PRED3(pred, v1, v2, v3) \
GTEST_PRED3_(pred, v1, v2, v3, GTEST_FATAL_FAILURE_) GTEST_PRED3_(pred, v1, v2, v3, GTEST_FATAL_FAILURE_)
// Helper function for implementing {EXPECT|ASSERT}_PRED4. Don't use // Helper function for implementing {EXPECT|ASSERT}_PRED4. Don't use
// this in your code. // this in your code.
template <typename Pred, template <typename Pred, typename T1, typename T2, typename T3, typename T4>
typename T1, AssertionResult AssertPred4Helper(const char* pred_text, const char* e1,
typename T2, const char* e2, const char* e3,
typename T3, const char* e4, Pred pred, const T1& v1,
typename T4> const T2& v2, const T3& v3, const T4& v4) {
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(); if (pred(v1, v2, v3, v4)) return AssertionSuccess();
return AssertionFailure() return AssertionFailure()
@ -259,23 +209,15 @@ AssertionResult AssertPred4Helper(const char* pred_text,
// Internal macro for implementing {EXPECT|ASSERT}_PRED_FORMAT4. // Internal macro for implementing {EXPECT|ASSERT}_PRED_FORMAT4.
// Don't use this in your code. // Don't use this in your code.
#define GTEST_PRED_FORMAT4_(pred_format, 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), \ GTEST_ASSERT_(pred_format(#v1, #v2, #v3, #v4, v1, v2, v3, v4), on_failure)
on_failure)
// Internal macro for implementing {EXPECT|ASSERT}_PRED4. Don't use // Internal macro for implementing {EXPECT|ASSERT}_PRED4. Don't use
// this in your code. // this in your code.
#define GTEST_PRED4_(pred, v1, v2, v3, v4, on_failure)\ #define GTEST_PRED4_(pred, v1, v2, v3, v4, on_failure) \
GTEST_ASSERT_(::testing::AssertPred4Helper(#pred, \ GTEST_ASSERT_(::testing::AssertPred4Helper(#pred, #v1, #v2, #v3, #v4, pred, \
#v1, \ v1, v2, v3, v4), \
#v2, \ on_failure)
#v3, \
#v4, \
pred, \
v1, \
v2, \
v3, \
v4), on_failure)
// 4-ary predicate assertion macros. // 4-ary predicate assertion macros.
#define EXPECT_PRED_FORMAT4(pred_format, v1, v2, v3, v4) \ #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) \ #define ASSERT_PRED4(pred, v1, v2, v3, v4) \
GTEST_PRED4_(pred, v1, v2, v3, v4, GTEST_FATAL_FAILURE_) GTEST_PRED4_(pred, v1, v2, v3, v4, GTEST_FATAL_FAILURE_)
// Helper function for implementing {EXPECT|ASSERT}_PRED5. Don't use // Helper function for implementing {EXPECT|ASSERT}_PRED5. Don't use
// this in your code. // this in your code.
template <typename Pred, template <typename Pred, typename T1, typename T2, typename T3, typename T4,
typename T1,
typename T2,
typename T3,
typename T4,
typename T5> typename T5>
AssertionResult AssertPred5Helper(const char* pred_text, AssertionResult AssertPred5Helper(const char* pred_text, const char* e1,
const char* e1, const char* e2, const char* e3,
const char* e2, const char* e4, const char* e5, Pred pred,
const char* e3, const T1& v1, const T2& v2, const T3& v3,
const char* e4, const T4& v4, const T5& v5) {
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(); if (pred(v1, v2, v3, v4, v5)) return AssertionSuccess();
return AssertionFailure() return AssertionFailure()
@ -324,25 +253,16 @@ AssertionResult AssertPred5Helper(const char* pred_text,
// Internal macro for implementing {EXPECT|ASSERT}_PRED_FORMAT5. // Internal macro for implementing {EXPECT|ASSERT}_PRED_FORMAT5.
// Don't use this in your code. // 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), \ GTEST_ASSERT_(pred_format(#v1, #v2, #v3, #v4, #v5, v1, v2, v3, v4, v5), \
on_failure) on_failure)
// Internal macro for implementing {EXPECT|ASSERT}_PRED5. Don't use // Internal macro for implementing {EXPECT|ASSERT}_PRED5. Don't use
// this in your code. // this in your code.
#define GTEST_PRED5_(pred, v1, v2, v3, v4, v5, on_failure)\ #define GTEST_PRED5_(pred, v1, v2, v3, v4, v5, on_failure) \
GTEST_ASSERT_(::testing::AssertPred5Helper(#pred, \ GTEST_ASSERT_(::testing::AssertPred5Helper(#pred, #v1, #v2, #v3, #v4, #v5, \
#v1, \ pred, v1, v2, v3, v4, v5), \
#v2, \ on_failure)
#v3, \
#v4, \
#v5, \
pred, \
v1, \
v2, \
v3, \
v4, \
v5), on_failure)
// 5-ary predicate assertion macros. // 5-ary predicate assertion macros.
#define EXPECT_PRED_FORMAT5(pred_format, v1, v2, v3, v4, v5) \ #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) \ #define ASSERT_PRED5(pred, v1, v2, v3, v4, v5) \
GTEST_PRED5_(pred, v1, v2, v3, v4, v5, GTEST_FATAL_FAILURE_) GTEST_PRED5_(pred, v1, v2, v3, v4, v5, GTEST_FATAL_FAILURE_)
} // namespace testing } // namespace testing
#endif // GOOGLETEST_INCLUDE_GTEST_GTEST_PRED_IMPL_H_ #endif // GOOGLETEST_INCLUDE_GTEST_GTEST_PRED_IMPL_H_

View File

@ -54,7 +54,7 @@
// Note: The test class must be in the same namespace as the class being tested. // 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. // For example, putting MyClassTest in an anonymous namespace will not work.
#define FRIEND_TEST(test_case_name, test_name)\ #define FRIEND_TEST(test_case_name, test_name) \
friend class test_case_name##_##test_name##_Test friend class test_case_name##_##test_name##_Test
#endif // GOOGLETEST_INCLUDE_GTEST_GTEST_PROD_H_ #endif // GOOGLETEST_INCLUDE_GTEST_GTEST_PROD_H_

View File

@ -39,12 +39,13 @@
#ifndef GOOGLETEST_INCLUDE_GTEST_INTERNAL_GTEST_DEATH_TEST_INTERNAL_H_ #ifndef GOOGLETEST_INCLUDE_GTEST_INTERNAL_GTEST_DEATH_TEST_INTERNAL_H_
#define GOOGLETEST_INCLUDE_GTEST_INTERNAL_GTEST_DEATH_TEST_INTERNAL_H_ #define GOOGLETEST_INCLUDE_GTEST_INTERNAL_GTEST_DEATH_TEST_INTERNAL_H_
#include <stdio.h>
#include <memory>
#include "gtest/gtest-matchers.h" #include "gtest/gtest-matchers.h"
#include "gtest/internal/gtest-internal.h" #include "gtest/internal/gtest-internal.h"
#include <stdio.h>
#include <memory>
GTEST_DECLARE_string_(internal_run_death_test); GTEST_DECLARE_string_(internal_run_death_test);
namespace testing { namespace testing {
@ -86,13 +87,14 @@ class GTEST_API_ DeathTest {
static bool Create(const char* statement, Matcher<const std::string&> matcher, static bool Create(const char* statement, Matcher<const std::string&> matcher,
const char* file, int line, DeathTest** test); const char* file, int line, DeathTest** test);
DeathTest(); DeathTest();
virtual ~DeathTest() { } virtual ~DeathTest() {}
// A helper class that aborts a death test when it's deleted. // A helper class that aborts a death test when it's deleted.
class ReturnSentinel { class ReturnSentinel {
public: public:
explicit ReturnSentinel(DeathTest* test) : test_(test) { } explicit ReturnSentinel(DeathTest* test) : test_(test) {}
~ReturnSentinel() { test_->Abort(TEST_ENCOUNTERED_RETURN_STATEMENT); } ~ReturnSentinel() { test_->Abort(TEST_ENCOUNTERED_RETURN_STATEMENT); }
private: private:
DeathTest* const test_; DeathTest* const test_;
GTEST_DISALLOW_COPY_AND_ASSIGN_(ReturnSentinel); 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. // Factory interface for death tests. May be mocked out for testing.
class DeathTestFactory { class DeathTestFactory {
public: public:
virtual ~DeathTestFactory() { } virtual ~DeathTestFactory() {}
virtual bool Create(const char* statement, virtual bool Create(const char* statement,
Matcher<const std::string&> matcher, const char* file, Matcher<const std::string&> matcher, const char* file,
int line, DeathTest** test) = 0; 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 // Traps C++ exceptions escaping statement and reports them as test
// failures. Note that trapping SEH exceptions is not implemented here. // failures. Note that trapping SEH exceptions is not implemented here.
# if GTEST_HAS_EXCEPTIONS #if GTEST_HAS_EXCEPTIONS
# define GTEST_EXECUTE_DEATH_TEST_STATEMENT_(statement, death_test) \ #define GTEST_EXECUTE_DEATH_TEST_STATEMENT_(statement, death_test) \
try { \ try { \
GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement); \ GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement); \
} catch (const ::std::exception& gtest_exception) { \ } catch (const ::std::exception& gtest_exception) { \
fprintf(\ fprintf( \
stderr, \ stderr, \
"\n%s: Caught std::exception-derived exception escaping the " \ "\n%s: Caught std::exception-derived exception escaping the " \
"death test statement. Exception message: %s\n", \ "death test statement. Exception message: %s\n", \
::testing::internal::FormatFileLocation(__FILE__, __LINE__).c_str(), \ ::testing::internal::FormatFileLocation(__FILE__, __LINE__).c_str(), \
gtest_exception.what()); \ gtest_exception.what()); \
fflush(stderr); \ fflush(stderr); \
death_test->Abort(::testing::internal::DeathTest::TEST_THREW_EXCEPTION); \ death_test->Abort(::testing::internal::DeathTest::TEST_THREW_EXCEPTION); \
} catch (...) { \ } catch (...) { \
death_test->Abort(::testing::internal::DeathTest::TEST_THREW_EXCEPTION); \ death_test->Abort(::testing::internal::DeathTest::TEST_THREW_EXCEPTION); \
} }
# else #else
# define GTEST_EXECUTE_DEATH_TEST_STATEMENT_(statement, death_test) \ #define GTEST_EXECUTE_DEATH_TEST_STATEMENT_(statement, death_test) \
GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement) GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement)
# endif #endif
// This macro is for implementing ASSERT_DEATH*, EXPECT_DEATH*, // This macro is for implementing ASSERT_DEATH*, EXPECT_DEATH*,
// ASSERT_EXIT*, and EXPECT_EXIT*. // ASSERT_EXIT*, and EXPECT_EXIT*.
@ -266,16 +268,12 @@ inline Matcher<const ::std::string&> MakeDeathTestMatcher(
// RUN_ALL_TESTS was called. // RUN_ALL_TESTS was called.
class InternalRunDeathTestFlag { class InternalRunDeathTestFlag {
public: public:
InternalRunDeathTestFlag(const std::string& a_file, InternalRunDeathTestFlag(const std::string& a_file, int a_line, int an_index,
int a_line,
int an_index,
int a_write_fd) int a_write_fd)
: file_(a_file), line_(a_line), index_(an_index), : file_(a_file), line_(a_line), index_(an_index), write_fd_(a_write_fd) {}
write_fd_(a_write_fd) {}
~InternalRunDeathTestFlag() { ~InternalRunDeathTestFlag() {
if (write_fd_ >= 0) if (write_fd_ >= 0) posix::Close(write_fd_);
posix::Close(write_fd_);
} }
const std::string& file() const { return file_; } const std::string& file() const { return file_; }

View File

@ -63,8 +63,8 @@ namespace internal {
class GTEST_API_ FilePath { class GTEST_API_ FilePath {
public: public:
FilePath() : pathname_("") { } FilePath() : pathname_("") {}
FilePath(const FilePath& rhs) : pathname_(rhs.pathname_) { } FilePath(const FilePath& rhs) : pathname_(rhs.pathname_) {}
explicit FilePath(const std::string& pathname) : pathname_(pathname) { explicit FilePath(const std::string& pathname) : pathname_(pathname) {
Normalize(); Normalize();
@ -75,9 +75,7 @@ class GTEST_API_ FilePath {
return *this; return *this;
} }
void Set(const FilePath& rhs) { void Set(const FilePath& rhs) { pathname_ = rhs.pathname_; }
pathname_ = rhs.pathname_;
}
const std::string& string() const { return pathname_; } const std::string& string() const { return pathname_; }
const char* c_str() const { return pathname_.c_str(); } 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". // than zero (e.g., 12), returns "dir/test_12.xml".
// On Windows platform, uses \ as the separator rather than /. // On Windows platform, uses \ as the separator rather than /.
static FilePath MakeFileName(const FilePath& directory, static FilePath MakeFileName(const FilePath& directory,
const FilePath& base_name, const FilePath& base_name, int number,
int number,
const char* extension); const char* extension);
// Given directory = "dir", relative_path = "test.xml", // Given directory = "dir", relative_path = "test.xml",

View File

@ -42,19 +42,20 @@
#include "gtest/internal/gtest-port.h" #include "gtest/internal/gtest-port.h"
#if GTEST_OS_LINUX #if GTEST_OS_LINUX
# include <stdlib.h> #include <stdlib.h>
# include <sys/types.h> #include <sys/types.h>
# include <sys/wait.h> #include <sys/wait.h>
# include <unistd.h> #include <unistd.h>
#endif // GTEST_OS_LINUX #endif // GTEST_OS_LINUX
#if GTEST_HAS_EXCEPTIONS #if GTEST_HAS_EXCEPTIONS
# include <stdexcept> #include <stdexcept>
#endif #endif
#include <ctype.h> #include <ctype.h>
#include <float.h> #include <float.h>
#include <string.h> #include <string.h>
#include <cstdint> #include <cstdint>
#include <iomanip> #include <iomanip>
#include <limits> #include <limits>
@ -78,7 +79,7 @@
// the current line number. For more details, see // the current line number. For more details, see
// http://www.parashift.com/c++-faq-lite/misc-technical-issues.html#faq-39.6 // 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_(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. // Stringifies its argument.
// Work around a bug in visual studio which doesn't accept code like this: // Work around a bug in visual studio which doesn't accept code like this:
@ -100,21 +101,21 @@ namespace testing {
// Forward declarations. // Forward declarations.
class AssertionResult; // Result of an assertion. class AssertionResult; // Result of an assertion.
class Message; // Represents a failure message. class Message; // Represents a failure message.
class Test; // Represents a test. class Test; // Represents a test.
class TestInfo; // Information about a test. class TestInfo; // Information about a test.
class TestPartResult; // Result of a test part. class TestPartResult; // Result of a test part.
class UnitTest; // A collection of test suites. class UnitTest; // A collection of test suites.
template <typename T> template <typename T>
::std::string PrintToString(const T& value); ::std::string PrintToString(const T& value);
namespace internal { namespace internal {
struct TraceInfo; // Information about a trace point. struct TraceInfo; // Information about a trace point.
class TestInfoImpl; // Opaque implementation of TestInfo class TestInfoImpl; // Opaque implementation of TestInfo
class UnitTestImpl; // Opaque implementation of UnitTest class UnitTestImpl; // Opaque implementation of UnitTest
// The text used in failure messages to indicate the start of the // The text used in failure messages to indicate the start of the
// stack trace. // stack trace.
@ -123,6 +124,7 @@ GTEST_API_ extern const char kStackTraceMarker[];
// An IgnoredValue object can be implicitly constructed from ANY value. // An IgnoredValue object can be implicitly constructed from ANY value.
class IgnoredValue { class IgnoredValue {
struct Sink {}; struct Sink {};
public: public:
// This constructor template allows any value to be implicitly // This constructor template allows any value to be implicitly
// converted to IgnoredValue. The object has no data member and // 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. // Appends the user-supplied message to the Google-Test-generated message.
GTEST_API_ std::string AppendUserMessage( GTEST_API_ std::string AppendUserMessage(const std::string& gtest_msg,
const std::string& gtest_msg, const Message& user_msg); const Message& user_msg);
#if GTEST_HAS_EXCEPTIONS #if GTEST_HAS_EXCEPTIONS
GTEST_DISABLE_MSC_WARNINGS_PUSH_(4275 \ GTEST_DISABLE_MSC_WARNINGS_PUSH_(
/* an exported class was derived from a class that was not exported */) 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 // This exception is thrown by (and only by) a failed Google Test
// assertion when GTEST_FLAG(throw_on_failure) is true (if exceptions // 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. // Constructs a failure message for Boolean assertions such as EXPECT_TRUE.
GTEST_API_ std::string GetBoolAssertionFailureMessage( GTEST_API_ std::string GetBoolAssertionFailureMessage(
const AssertionResult& assertion_result, const AssertionResult& assertion_result, const char* expression_text,
const char* expression_text, const char* actual_predicate_value, const char* expected_predicate_value);
const char* actual_predicate_value,
const char* expected_predicate_value);
// This template class represents an IEEE floating-point number // This template class represents an IEEE floating-point number
// (either single-precision or double-precision, depending on the // (either single-precision or double-precision, depending on the
@ -258,11 +258,11 @@ class FloatingPoint {
// Constants. // Constants.
// # of bits in a number. // # 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. // # of fraction bits in a number.
static const size_t kFractionBitCount = static const size_t kFractionBitCount =
std::numeric_limits<RawType>::digits - 1; std::numeric_limits<RawType>::digits - 1;
// # of exponent bits in a number. // # of exponent bits in a number.
static const size_t kExponentBitCount = kBitCount - 1 - kFractionBitCount; static const size_t kExponentBitCount = kBitCount - 1 - kFractionBitCount;
@ -271,8 +271,8 @@ class FloatingPoint {
static const Bits kSignBitMask = static_cast<Bits>(1) << (kBitCount - 1); static const Bits kSignBitMask = static_cast<Bits>(1) << (kBitCount - 1);
// The mask for the fraction bits. // The mask for the fraction bits.
static const Bits kFractionBitMask = static const Bits kFractionBitMask = ~static_cast<Bits>(0) >>
~static_cast<Bits>(0) >> (kExponentBitCount + 1); (kExponentBitCount + 1);
// The mask for the exponent bits. // The mask for the exponent bits.
static const Bits kExponentBitMask = ~(kSignBitMask | kFractionBitMask); static const Bits kExponentBitMask = ~(kSignBitMask | kFractionBitMask);
@ -311,9 +311,7 @@ class FloatingPoint {
} }
// Returns the floating-point number that represent positive infinity. // Returns the floating-point number that represent positive infinity.
static RawType Infinity() { static RawType Infinity() { return ReinterpretBits(kExponentBitMask); }
return ReinterpretBits(kExponentBitMask);
}
// Returns the maximum representable finite floating-point number. // Returns the maximum representable finite floating-point number.
static RawType Max(); static RawType Max();
@ -321,7 +319,7 @@ class FloatingPoint {
// Non-static methods // Non-static methods
// Returns the bits that represents this number. // 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. // Returns the exponent bits of this number.
Bits exponent_bits() const { return kExponentBitMask & u_.bits_; } Bits exponent_bits() const { return kExponentBitMask & u_.bits_; }
@ -350,8 +348,8 @@ class FloatingPoint {
// a NAN must return false. // a NAN must return false.
if (is_nan() || rhs.is_nan()) return false; if (is_nan() || rhs.is_nan()) return false;
return DistanceBetweenSignAndMagnitudeNumbers(u_.bits_, rhs.u_.bits_) return DistanceBetweenSignAndMagnitudeNumbers(u_.bits_, rhs.u_.bits_) <=
<= kMaxUlps; kMaxUlps;
} }
private: private:
@ -376,7 +374,7 @@ class FloatingPoint {
// //
// Read http://en.wikipedia.org/wiki/Signed_number_representations // Read http://en.wikipedia.org/wiki/Signed_number_representations
// for more details on 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) { if (kSignBitMask & sam) {
// sam represents a negative number. // sam represents a negative number.
return ~sam + 1; return ~sam + 1;
@ -388,8 +386,8 @@ class FloatingPoint {
// Given two numbers in the sign-and-magnitude representation, // Given two numbers in the sign-and-magnitude representation,
// returns the distance between them as an unsigned number. // returns the distance between them as an unsigned number.
static Bits DistanceBetweenSignAndMagnitudeNumbers(const Bits &sam1, static Bits DistanceBetweenSignAndMagnitudeNumbers(const Bits& sam1,
const Bits &sam2) { const Bits& sam2) {
const Bits biased1 = SignAndMagnitudeToBiased(sam1); const Bits biased1 = SignAndMagnitudeToBiased(sam1);
const Bits biased2 = SignAndMagnitudeToBiased(sam2); const Bits biased2 = SignAndMagnitudeToBiased(sam2);
return (biased1 >= biased2) ? (biased1 - biased2) : (biased2 - biased1); 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() // We cannot use std::numeric_limits<T>::max() as it clashes with the max()
// macro defined by <windows.h>. // macro defined by <windows.h>.
template <> template <>
inline float FloatingPoint<float>::Max() { return FLT_MAX; } inline float FloatingPoint<float>::Max() {
return FLT_MAX;
}
template <> 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 // Typedefs the instances of the FloatingPoint template class that we
// care to use. // care to use.
@ -656,7 +658,8 @@ inline const char* SkipComma(const char* str) {
if (comma == nullptr) { if (comma == nullptr) {
return nullptr; return nullptr;
} }
while (IsSpace(*(++comma))) {} while (IsSpace(*(++comma))) {
}
return 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 // Splits a given string on a given delimiter, populating a given
// vector with the fields. // vector with the fields.
void SplitString(const ::std::string& str, char delimiter, 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 // The default argument to the template below for the case when the user does
// not provide a name generator. // not provide a name generator.
@ -783,13 +786,13 @@ class TypeParameterizedTestSuite {
const std::vector<std::string>& type_names = const std::vector<std::string>& type_names =
GenerateNames<DefaultNameGenerator, Types>()) { GenerateNames<DefaultNameGenerator, Types>()) {
RegisterTypeParameterizedTestSuiteInstantiation(case_name); RegisterTypeParameterizedTestSuiteInstantiation(case_name);
std::string test_name = StripTrailingSpaces( std::string test_name =
GetPrefixUntilComma(test_names)); StripTrailingSpaces(GetPrefixUntilComma(test_names));
if (!state->TestExists(test_name)) { if (!state->TestExists(test_name)) {
fprintf(stderr, "Failed to get code location for test %s.%s at %s.", fprintf(stderr, "Failed to get code location for test %s.%s at %s.",
case_name, test_name.c_str(), case_name, test_name.c_str(),
FormatFileLocation(code_location.file.c_str(), FormatFileLocation(code_location.file.c_str(), code_location.line)
code_location.line).c_str()); .c_str());
fflush(stderr); fflush(stderr);
posix::Abort(); posix::Abort();
} }
@ -833,8 +836,8 @@ class TypeParameterizedTestSuite<Fixture, internal::None, Types> {
// For example, if Foo() calls Bar(), which in turn calls // For example, if Foo() calls Bar(), which in turn calls
// GetCurrentOsStackTraceExceptTop(..., 1), Foo() will be included in // GetCurrentOsStackTraceExceptTop(..., 1), Foo() will be included in
// the trace but Bar() and GetCurrentOsStackTraceExceptTop() won't. // the trace but Bar() and GetCurrentOsStackTraceExceptTop() won't.
GTEST_API_ std::string GetCurrentOsStackTraceExceptTop( GTEST_API_ std::string GetCurrentOsStackTraceExceptTop(UnitTest* unit_test,
UnitTest* unit_test, int skip_count); int skip_count);
// Helpers for suppressing warnings on unreachable code or constant // Helpers for suppressing warnings on unreachable code or constant
// condition. // condition.
@ -956,7 +959,9 @@ IsContainer IsContainerTest(int /* dummy */) {
typedef char IsNotContainer; typedef char IsNotContainer;
template <class C> 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. // 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 // 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. // This generic version is used when k is 0.
template <typename T, typename U> 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. // This overload is used when k >= 1.
template <typename T, typename U, size_t N> 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); 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> template <typename T, typename U>
bool ArrayEq(const T* lhs, size_t size, const U* rhs) { bool ArrayEq(const T* lhs, size_t size, const U* rhs) {
for (size_t i = 0; i != size; i++) { for (size_t i = 0; i != size; i++) {
if (!internal::ArrayEq(lhs[i], rhs[i])) if (!internal::ArrayEq(lhs[i], rhs[i])) return false;
return false;
} }
return true; return true;
} }
@ -1044,8 +1050,7 @@ bool ArrayEq(const T* lhs, size_t size, const U* rhs) {
template <typename Iter, typename Element> template <typename Iter, typename Element>
Iter ArrayAwareFind(Iter begin, Iter end, const Element& elem) { Iter ArrayAwareFind(Iter begin, Iter end, const Element& elem) {
for (Iter it = begin; it != end; ++it) { for (Iter it = begin; it != end; ++it) {
if (internal::ArrayEq(*it, elem)) if (internal::ArrayEq(*it, elem)) return it;
return it;
} }
return end; 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. // This generic version is used when k is 0.
template <typename T, typename U> 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. // This overload is used when k >= 1.
template <typename T, typename U, size_t N> 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); internal::CopyArray(from, N, *to);
} }
@ -1116,8 +1123,7 @@ class NativeArray {
} }
~NativeArray() { ~NativeArray() {
if (clone_ != &NativeArray::InitRef) if (clone_ != &NativeArray::InitRef) delete[] array_;
delete[] array_;
} }
// STL-style container methods. // STL-style container methods.
@ -1125,8 +1131,7 @@ class NativeArray {
const_iterator begin() const { return array_; } const_iterator begin() const { return array_; }
const_iterator end() const { return array_ + size_; } const_iterator end() const { return array_ + size_; }
bool operator==(const NativeArray& rhs) const { bool operator==(const NativeArray& rhs) const {
return size() == rhs.size() && return size() == rhs.size() && ArrayEq(begin(), size(), rhs.begin());
ArrayEq(begin(), size(), rhs.begin());
} }
private: private:
@ -1337,9 +1342,9 @@ struct tuple_size<testing::internal::FlatTuple<Ts...>>
#endif #endif
} // namespace std } // namespace std
#define GTEST_MESSAGE_AT_(file, line, message, result_type) \ #define GTEST_MESSAGE_AT_(file, line, message, result_type) \
::testing::internal::AssertHelper(result_type, file, line, message) \ ::testing::internal::AssertHelper(result_type, file, line, message) = \
= ::testing::Message() ::testing::Message()
#define GTEST_MESSAGE_(message, result_type) \ #define GTEST_MESSAGE_(message, result_type) \
GTEST_MESSAGE_AT_(__FILE__, __LINE__, message, result_type) GTEST_MESSAGE_AT_(__FILE__, __LINE__, message, result_type)
@ -1460,66 +1465,69 @@ class NeverThrown {
#endif // GTEST_HAS_EXCEPTIONS #endif // GTEST_HAS_EXCEPTIONS
#define GTEST_TEST_NO_THROW_(statement, fail) \ #define GTEST_TEST_NO_THROW_(statement, fail) \
GTEST_AMBIGUOUS_ELSE_BLOCKER_ \ GTEST_AMBIGUOUS_ELSE_BLOCKER_ \
if (::testing::internal::TrueWithString gtest_msg{}) { \ if (::testing::internal::TrueWithString gtest_msg{}) { \
try { \ try { \
GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement); \ GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement); \
} \ } \
GTEST_TEST_NO_THROW_CATCH_STD_EXCEPTION_() \ GTEST_TEST_NO_THROW_CATCH_STD_EXCEPTION_() \
catch (...) { \ catch (...) { \
gtest_msg.value = "it throws."; \ gtest_msg.value = "it throws."; \
goto GTEST_CONCAT_TOKEN_(gtest_label_testnothrow_, __LINE__); \ goto GTEST_CONCAT_TOKEN_(gtest_label_testnothrow_, __LINE__); \
} \ } \
} else \ } else \
GTEST_CONCAT_TOKEN_(gtest_label_testnothrow_, __LINE__): \ GTEST_CONCAT_TOKEN_(gtest_label_testnothrow_, __LINE__) \
fail(("Expected: " #statement " doesn't throw an exception.\n" \ : fail(("Expected: " #statement " doesn't throw an exception.\n" \
" Actual: " + gtest_msg.value).c_str()) " Actual: " + \
gtest_msg.value) \
.c_str())
#define GTEST_TEST_ANY_THROW_(statement, fail) \ #define GTEST_TEST_ANY_THROW_(statement, fail) \
GTEST_AMBIGUOUS_ELSE_BLOCKER_ \ GTEST_AMBIGUOUS_ELSE_BLOCKER_ \
if (::testing::internal::AlwaysTrue()) { \ if (::testing::internal::AlwaysTrue()) { \
bool gtest_caught_any = false; \ bool gtest_caught_any = false; \
try { \ try { \
GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement); \ GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement); \
} \ } catch (...) { \
catch (...) { \ gtest_caught_any = true; \
gtest_caught_any = true; \ } \
} \ if (!gtest_caught_any) { \
if (!gtest_caught_any) { \
goto GTEST_CONCAT_TOKEN_(gtest_label_testanythrow_, __LINE__); \ goto GTEST_CONCAT_TOKEN_(gtest_label_testanythrow_, __LINE__); \
} \ } \
} else \ } else \
GTEST_CONCAT_TOKEN_(gtest_label_testanythrow_, __LINE__): \ GTEST_CONCAT_TOKEN_(gtest_label_testanythrow_, __LINE__) \
fail("Expected: " #statement " throws an exception.\n" \ : fail("Expected: " #statement \
" Actual: it doesn't.") " throws an exception.\n" \
" Actual: it doesn't.")
// Implements Boolean test assertions such as EXPECT_TRUE. expression can be // Implements Boolean test assertions such as EXPECT_TRUE. expression can be
// either a boolean expression or an AssertionResult. text is a textual // either a boolean expression or an AssertionResult. text is a textual
// representation of expression as it was passed into the EXPECT_TRUE. // representation of expression as it was passed into the EXPECT_TRUE.
#define GTEST_TEST_BOOLEAN_(expression, text, actual, expected, fail) \ #define GTEST_TEST_BOOLEAN_(expression, text, actual, expected, fail) \
GTEST_AMBIGUOUS_ELSE_BLOCKER_ \ GTEST_AMBIGUOUS_ELSE_BLOCKER_ \
if (const ::testing::AssertionResult gtest_ar_ = \ if (const ::testing::AssertionResult gtest_ar_ = \
::testing::AssertionResult(expression)) \ ::testing::AssertionResult(expression)) \
; \ ; \
else \ else \
fail(::testing::internal::GetBoolAssertionFailureMessage(\ fail(::testing::internal::GetBoolAssertionFailureMessage( \
gtest_ar_, text, #actual, #expected).c_str()) gtest_ar_, text, #actual, #expected) \
.c_str())
#define GTEST_TEST_NO_FATAL_FAILURE_(statement, fail) \ #define GTEST_TEST_NO_FATAL_FAILURE_(statement, fail) \
GTEST_AMBIGUOUS_ELSE_BLOCKER_ \ GTEST_AMBIGUOUS_ELSE_BLOCKER_ \
if (::testing::internal::AlwaysTrue()) { \ if (::testing::internal::AlwaysTrue()) { \
::testing::internal::HasNewFatalFailureHelper gtest_fatal_failure_checker; \ ::testing::internal::HasNewFatalFailureHelper gtest_fatal_failure_checker; \
GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement); \ GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement); \
if (gtest_fatal_failure_checker.has_new_fatal_failure()) { \ if (gtest_fatal_failure_checker.has_new_fatal_failure()) { \
goto GTEST_CONCAT_TOKEN_(gtest_label_testnofatal_, __LINE__); \ goto GTEST_CONCAT_TOKEN_(gtest_label_testnofatal_, __LINE__); \
} \ } \
} else \ } else \
GTEST_CONCAT_TOKEN_(gtest_label_testnofatal_, __LINE__): \ GTEST_CONCAT_TOKEN_(gtest_label_testnofatal_, __LINE__) \
fail("Expected: " #statement " doesn't generate new fatal " \ : fail("Expected: " #statement \
"failures in the current thread.\n" \ " doesn't generate new fatal " \
" Actual: it does.") "failures in the current thread.\n" \
" Actual: it does.")
// Expands to the name of the class that implements the given test. // Expands to the name of the class that implements the given test.
#define GTEST_TEST_CLASS_NAME_(test_suite_name, test_name) \ #define GTEST_TEST_CLASS_NAME_(test_suite_name, test_name) \

View File

@ -47,19 +47,18 @@
#include <utility> #include <utility>
#include <vector> #include <vector>
#include "gtest/internal/gtest-internal.h"
#include "gtest/internal/gtest-port.h"
#include "gtest/gtest-printers.h" #include "gtest/gtest-printers.h"
#include "gtest/gtest-test-part.h" #include "gtest/gtest-test-part.h"
#include "gtest/internal/gtest-internal.h"
#include "gtest/internal/gtest-port.h"
namespace testing { namespace testing {
// Input to a parameterized test name generator, describing a test parameter. // Input to a parameterized test name generator, describing a test parameter.
// Consists of the parameter value and the integer parameter index. // Consists of the parameter value and the integer parameter index.
template <class ParamType> template <class ParamType>
struct TestParamInfo { struct TestParamInfo {
TestParamInfo(const ParamType& a_param, size_t an_index) : TestParamInfo(const ParamType& a_param, size_t an_index)
param(a_param), : param(a_param), index(an_index) {}
index(an_index) {}
ParamType param; ParamType param;
size_t index; size_t index;
}; };
@ -85,8 +84,10 @@ namespace internal {
GTEST_API_ void ReportInvalidTestSuiteType(const char* test_suite_name, GTEST_API_ void ReportInvalidTestSuiteType(const char* test_suite_name,
CodeLocation code_location); CodeLocation code_location);
template <typename> class ParamGeneratorInterface; template <typename>
template <typename> class ParamGenerator; class ParamGeneratorInterface;
template <typename>
class ParamGenerator;
// Interface for iterating over elements provided by an implementation // Interface for iterating over elements provided by an implementation
// of ParamGeneratorInterface<T>. // of ParamGeneratorInterface<T>.
@ -130,8 +131,7 @@ class ParamIterator {
// ParamIterator assumes ownership of the impl_ pointer. // ParamIterator assumes ownership of the impl_ pointer.
ParamIterator(const ParamIterator& other) : impl_(other.impl_->Clone()) {} ParamIterator(const ParamIterator& other) : impl_(other.impl_->Clone()) {}
ParamIterator& operator=(const ParamIterator& other) { ParamIterator& operator=(const ParamIterator& other) {
if (this != &other) if (this != &other) impl_.reset(other.impl_->Clone());
impl_.reset(other.impl_->Clone());
return *this; return *this;
} }
@ -158,7 +158,7 @@ class ParamIterator {
private: private:
friend class ParamGenerator<T>; friend class ParamGenerator<T>;
explicit ParamIterator(ParamIteratorInterface<T>* impl) : impl_(impl) {} 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 // ParamGeneratorInterface<T> is the binary interface to access generators
@ -180,7 +180,7 @@ class ParamGeneratorInterface {
// This class implements copy initialization semantics and the contained // This class implements copy initialization semantics and the contained
// ParamGeneratorInterface<T> instance is shared among all copies // ParamGeneratorInterface<T> instance is shared among all copies
// of the original object. This is possible because that instance is immutable. // of the original object. This is possible because that instance is immutable.
template<typename T> template <typename T>
class ParamGenerator { class ParamGenerator {
public: public:
typedef ParamIterator<T> iterator; typedef ParamIterator<T> iterator;
@ -197,7 +197,7 @@ class ParamGenerator {
iterator end() const { return iterator(impl_->End()); } iterator end() const { return iterator(impl_->End()); }
private: 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 // 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> { class RangeGenerator : public ParamGeneratorInterface<T> {
public: public:
RangeGenerator(T begin, T end, IncrementT step) RangeGenerator(T begin, T end, IncrementT step)
: begin_(begin), end_(end), : begin_(begin),
step_(step), end_index_(CalculateEndIndex(begin, end, step)) {} end_(end),
step_(step),
end_index_(CalculateEndIndex(begin, end, step)) {}
~RangeGenerator() override {} ~RangeGenerator() override {}
ParamIteratorInterface<T>* Begin() const override { ParamIteratorInterface<T>* Begin() const override {
@ -252,7 +254,9 @@ class RangeGenerator : public ParamGeneratorInterface<T> {
private: private:
Iterator(const Iterator& other) Iterator(const Iterator& other)
: ParamIteratorInterface<T>(), : ParamIteratorInterface<T>(),
base_(other.base_), value_(other.value_), index_(other.index_), base_(other.base_),
value_(other.value_),
index_(other.index_),
step_(other.step_) {} step_(other.step_) {}
// No implementation - assignment is unsupported. // No implementation - assignment is unsupported.
@ -264,12 +268,10 @@ class RangeGenerator : public ParamGeneratorInterface<T> {
const IncrementT step_; const IncrementT step_;
}; // class RangeGenerator::Iterator }; // class RangeGenerator::Iterator
static int CalculateEndIndex(const T& begin, static int CalculateEndIndex(const T& begin, const T& end,
const T& end,
const IncrementT& step) { const IncrementT& step) {
int end_index = 0; int end_index = 0;
for (T i = begin; i < end; i = static_cast<T>(i + step)) for (T i = begin; i < end; i = static_cast<T>(i + step)) end_index++;
end_index++;
return end_index; return end_index;
} }
@ -284,7 +286,6 @@ class RangeGenerator : public ParamGeneratorInterface<T> {
const int end_index_; const int end_index_;
}; // class RangeGenerator }; // class RangeGenerator
// Generates values from a pair of STL-style iterators. Used in the // Generates values from a pair of STL-style iterators. Used in the
// ValuesIn() function. The elements are copied from the source range // ValuesIn() function. The elements are copied from the source range
// since the source can be located on the stack, and the generator // 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 " << "The program attempted to compare iterators "
<< "from different generators." << std::endl; << "from different generators." << std::endl;
return iterator_ == return iterator_ ==
CheckedDowncastToActualType<const Iterator>(&other)->iterator_; CheckedDowncastToActualType<const Iterator>(&other)->iterator_;
} }
private: private:
Iterator(const Iterator& other) Iterator(const Iterator& other)
// The explicit constructor call suppresses a false warning // The explicit constructor call suppresses a false warning
// emitted by gcc when supplied with the -Wextra option. // emitted by gcc when supplied with the -Wextra option.
: ParamIteratorInterface<T>(), : ParamIteratorInterface<T>(),
base_(other.base_), base_(other.base_),
iterator_(other.iterator_) {} iterator_(other.iterator_) {}
@ -395,8 +396,8 @@ template <class TestClass>
class ParameterizedTestFactory : public TestFactoryBase { class ParameterizedTestFactory : public TestFactoryBase {
public: public:
typedef typename TestClass::ParamType ParamType; typedef typename TestClass::ParamType ParamType;
explicit ParameterizedTestFactory(ParamType parameter) : explicit ParameterizedTestFactory(ParamType parameter)
parameter_(parameter) {} : parameter_(parameter) {}
Test* CreateTest() override { Test* CreateTest() override {
TestClass::SetParam(&parameter_); TestClass::SetParam(&parameter_);
return new TestClass(); return new TestClass();
@ -548,8 +549,8 @@ class ParameterizedTestSuiteInfo : public ParameterizedTestSuiteInfoBase {
test_it != tests_.end(); ++test_it) { test_it != tests_.end(); ++test_it) {
std::shared_ptr<TestInfo> test_info = *test_it; std::shared_ptr<TestInfo> test_info = *test_it;
for (typename InstantiationContainer::iterator gen_it = for (typename InstantiationContainer::iterator gen_it =
instantiations_.begin(); gen_it != instantiations_.end(); instantiations_.begin();
++gen_it) { gen_it != instantiations_.end(); ++gen_it) {
const std::string& instantiation_name = gen_it->name; const std::string& instantiation_name = gen_it->name;
ParamGenerator<ParamType> generator((*gen_it->generator)()); ParamGenerator<ParamType> generator((*gen_it->generator)());
ParamNameGeneratorFunc* name_func = gen_it->name_func; ParamNameGeneratorFunc* name_func = gen_it->name_func;
@ -557,7 +558,7 @@ class ParameterizedTestSuiteInfo : public ParameterizedTestSuiteInfoBase {
int line = gen_it->line; int line = gen_it->line;
std::string test_suite_name; std::string test_suite_name;
if ( !instantiation_name.empty() ) if (!instantiation_name.empty())
test_suite_name = instantiation_name + "/"; test_suite_name = instantiation_name + "/";
test_suite_name += test_info->test_suite_base_name; test_suite_name += test_info->test_suite_base_name;
@ -570,17 +571,16 @@ class ParameterizedTestSuiteInfo : public ParameterizedTestSuiteInfoBase {
Message test_name_stream; Message test_name_stream;
std::string param_name = name_func( std::string param_name =
TestParamInfo<ParamType>(*param_it, i)); name_func(TestParamInfo<ParamType>(*param_it, i));
GTEST_CHECK_(IsValidParamName(param_name)) GTEST_CHECK_(IsValidParamName(param_name))
<< "Parameterized test name '" << param_name << "Parameterized test name '" << param_name
<< "' is invalid, in " << file << "' is invalid, in " << file << " line " << line << std::endl;
<< " line " << line << std::endl;
GTEST_CHECK_(test_param_names.count(param_name) == 0) GTEST_CHECK_(test_param_names.count(param_name) == 0)
<< "Duplicate parameterized test name '" << param_name << "Duplicate parameterized test name '" << param_name << "', in "
<< "', in " << file << " line " << line << std::endl; << file << " line " << line << std::endl;
test_param_names.insert(param_name); test_param_names.insert(param_name);
@ -597,15 +597,15 @@ class ParameterizedTestSuiteInfo : public ParameterizedTestSuiteInfoBase {
SuiteApiResolver<TestSuite>::GetTearDownCaseOrSuite(file, line), SuiteApiResolver<TestSuite>::GetTearDownCaseOrSuite(file, line),
test_info->test_meta_factory->CreateTestFactory(*param_it)); test_info->test_meta_factory->CreateTestFactory(*param_it));
} // for param_it } // for param_it
} // for gen_it } // for gen_it
} // for test_it } // for test_it
if (!generated_instantiations) { if (!generated_instantiations) {
// There are no generaotrs, or they all generate nothing ... // There are no generaotrs, or they all generate nothing ...
InsertSyntheticTestCase(GetTestSuiteName(), code_location_, InsertSyntheticTestCase(GetTestSuiteName(), code_location_,
!tests_.empty()); !tests_.empty());
} }
} // RegisterTests } // RegisterTests
private: private:
// LocalTestInfo structure keeps information about a single test registered // 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_suite_base_name;
const std::string test_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; 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: // Records data received from INSTANTIATE_TEST_SUITE_P macros:
// <Instantiation name, Sequence generator creation function, // <Instantiation name, Sequence generator creation function,
// Name generator function, Source file, Source line> // Name generator function, Source file, Source line>
struct InstantiationInfo { struct InstantiationInfo {
InstantiationInfo(const std::string &name_in, InstantiationInfo(const std::string& name_in,
GeneratorCreationFunc* generator_in, GeneratorCreationFunc* generator_in,
ParamNameGeneratorFunc* name_func_in, ParamNameGeneratorFunc* name_func_in, const char* file_in,
const char* file_in, int line_in)
int line_in) : name(name_in),
: name(name_in), generator(generator_in),
generator(generator_in), name_func(name_func_in),
name_func(name_func_in), file(file_in),
file(file_in), line(line_in) {}
line(line_in) {}
std::string name; std::string name;
GeneratorCreationFunc* generator; GeneratorCreationFunc* generator;
ParamNameGeneratorFunc* name_func; ParamNameGeneratorFunc* name_func;
const char* file; const char* file;
int line; int line;
}; };
typedef ::std::vector<InstantiationInfo> InstantiationContainer; typedef ::std::vector<InstantiationInfo> InstantiationContainer;
static bool IsValidParamName(const std::string& name) { static bool IsValidParamName(const std::string& name) {
// Check for empty string // Check for empty string
if (name.empty()) if (name.empty()) return false;
return false;
// Check for invalid characters // Check for invalid characters
for (std::string::size_type index = 0; index < name.size(); ++index) { for (std::string::size_type index = 0; index < name.size(); ++index) {
if (!IsAlNum(name[index]) && name[index] != '_') if (!IsAlNum(name[index]) && name[index] != '_') return false;
return false;
} }
return true; return true;
@ -710,7 +707,7 @@ class ParameterizedTestSuiteRegistry {
// type we are looking for, so we downcast it to that type // type we are looking for, so we downcast it to that type
// without further checks. // without further checks.
typed_test_info = CheckedDowncastToActualType< typed_test_info = CheckedDowncastToActualType<
ParameterizedTestSuiteInfo<TestSuite> >(test_suite_info); ParameterizedTestSuiteInfo<TestSuite>>(test_suite_info);
} }
break; break;
} }
@ -837,7 +834,8 @@ class CartesianProductGenerator
: public ParamIteratorInterface<ParamType> { : public ParamIteratorInterface<ParamType> {
public: public:
IteratorImpl(const ParamGeneratorInterface<ParamType>* base, 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), : base_(base),
begin_(std::get<I>(generators).begin()...), begin_(std::get<I>(generators).begin()...),
end_(std::get<I>(generators).end()...), end_(std::get<I>(generators).end()...),

View File

@ -37,72 +37,72 @@
// Determines the platform on which Google Test is compiled. // Determines the platform on which Google Test is compiled.
#ifdef __CYGWIN__ #ifdef __CYGWIN__
# define GTEST_OS_CYGWIN 1 #define GTEST_OS_CYGWIN 1
# elif defined(__MINGW__) || defined(__MINGW32__) || defined(__MINGW64__) #elif defined(__MINGW__) || defined(__MINGW32__) || defined(__MINGW64__)
# define GTEST_OS_WINDOWS_MINGW 1 #define GTEST_OS_WINDOWS_MINGW 1
# define GTEST_OS_WINDOWS 1 #define GTEST_OS_WINDOWS 1
#elif defined _WIN32 #elif defined _WIN32
# define GTEST_OS_WINDOWS 1 #define GTEST_OS_WINDOWS 1
# ifdef _WIN32_WCE #ifdef _WIN32_WCE
# define GTEST_OS_WINDOWS_MOBILE 1 #define GTEST_OS_WINDOWS_MOBILE 1
# elif defined(WINAPI_FAMILY) #elif defined(WINAPI_FAMILY)
# include <winapifamily.h> #include <winapifamily.h>
# if WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_DESKTOP) #if WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_DESKTOP)
# define GTEST_OS_WINDOWS_DESKTOP 1 #define GTEST_OS_WINDOWS_DESKTOP 1
# elif WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_PHONE_APP) #elif WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_PHONE_APP)
# define GTEST_OS_WINDOWS_PHONE 1 #define GTEST_OS_WINDOWS_PHONE 1
# elif WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_APP) #elif WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_APP)
# define GTEST_OS_WINDOWS_RT 1 #define GTEST_OS_WINDOWS_RT 1
# elif WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_TV_TITLE) #elif WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_TV_TITLE)
# define GTEST_OS_WINDOWS_PHONE 1 #define GTEST_OS_WINDOWS_PHONE 1
# define GTEST_OS_WINDOWS_TV_TITLE 1 #define GTEST_OS_WINDOWS_TV_TITLE 1
# else #else
// WINAPI_FAMILY defined but no known partition matched. // WINAPI_FAMILY defined but no known partition matched.
// Default to desktop. // Default to desktop.
# define GTEST_OS_WINDOWS_DESKTOP 1 #define GTEST_OS_WINDOWS_DESKTOP 1
# endif #endif
# else #else
# define GTEST_OS_WINDOWS_DESKTOP 1 #define GTEST_OS_WINDOWS_DESKTOP 1
# endif // _WIN32_WCE #endif // _WIN32_WCE
#elif defined __OS2__ #elif defined __OS2__
# define GTEST_OS_OS2 1 #define GTEST_OS_OS2 1
#elif defined __APPLE__ #elif defined __APPLE__
# define GTEST_OS_MAC 1 #define GTEST_OS_MAC 1
# include <TargetConditionals.h> #include <TargetConditionals.h>
# if TARGET_OS_IPHONE #if TARGET_OS_IPHONE
# define GTEST_OS_IOS 1 #define GTEST_OS_IOS 1
# endif #endif
#elif defined __DragonFly__ #elif defined __DragonFly__
# define GTEST_OS_DRAGONFLY 1 #define GTEST_OS_DRAGONFLY 1
#elif defined __FreeBSD__ #elif defined __FreeBSD__
# define GTEST_OS_FREEBSD 1 #define GTEST_OS_FREEBSD 1
#elif defined __Fuchsia__ #elif defined __Fuchsia__
# define GTEST_OS_FUCHSIA 1 #define GTEST_OS_FUCHSIA 1
#elif defined(__GNU__) #elif defined(__GNU__)
# define GTEST_OS_GNU_HURD 1 #define GTEST_OS_GNU_HURD 1
#elif defined(__GLIBC__) && defined(__FreeBSD_kernel__) #elif defined(__GLIBC__) && defined(__FreeBSD_kernel__)
# define GTEST_OS_GNU_KFREEBSD 1 #define GTEST_OS_GNU_KFREEBSD 1
#elif defined __linux__ #elif defined __linux__
# define GTEST_OS_LINUX 1 #define GTEST_OS_LINUX 1
# if defined __ANDROID__ #if defined __ANDROID__
# define GTEST_OS_LINUX_ANDROID 1 #define GTEST_OS_LINUX_ANDROID 1
# endif #endif
#elif defined __MVS__ #elif defined __MVS__
# define GTEST_OS_ZOS 1 #define GTEST_OS_ZOS 1
#elif defined(__sun) && defined(__SVR4) #elif defined(__sun) && defined(__SVR4)
# define GTEST_OS_SOLARIS 1 #define GTEST_OS_SOLARIS 1
#elif defined(_AIX) #elif defined(_AIX)
# define GTEST_OS_AIX 1 #define GTEST_OS_AIX 1
#elif defined(__hpux) #elif defined(__hpux)
# define GTEST_OS_HPUX 1 #define GTEST_OS_HPUX 1
#elif defined __native_client__ #elif defined __native_client__
# define GTEST_OS_NACL 1 #define GTEST_OS_NACL 1
#elif defined __NetBSD__ #elif defined __NetBSD__
# define GTEST_OS_NETBSD 1 #define GTEST_OS_NETBSD 1
#elif defined __OpenBSD__ #elif defined __OpenBSD__
# define GTEST_OS_OPENBSD 1 #define GTEST_OS_OPENBSD 1
#elif defined __QNX__ #elif defined __QNX__
# define GTEST_OS_QNX 1 #define GTEST_OS_QNX 1
#elif defined(__HAIKU__) #elif defined(__HAIKU__)
#define GTEST_OS_HAIKU 1 #define GTEST_OS_HAIKU 1
#elif defined ESP8266 #elif defined ESP8266

File diff suppressed because it is too large Load Diff

View File

@ -45,10 +45,11 @@
#ifdef __BORLANDC__ #ifdef __BORLANDC__
// string.h is not guaranteed to provide strcpy on C++ Builder. // string.h is not guaranteed to provide strcpy on C++ Builder.
# include <mem.h> #include <mem.h>
#endif #endif
#include <string.h> #include <string.h>
#include <cstdint> #include <cstdint>
#include <string> #include <string>
@ -125,8 +126,7 @@ class GTEST_API_ String {
// Unlike strcasecmp(), this function can handle NULL argument(s). // Unlike strcasecmp(), this function can handle NULL argument(s).
// A NULL C string is considered different to any non-NULL C string, // A NULL C string is considered different to any non-NULL C string,
// including the empty string. // including the empty string.
static bool CaseInsensitiveCStringEquals(const char* lhs, static bool CaseInsensitiveCStringEquals(const char* lhs, const char* rhs);
const char* rhs);
// Compares two wide C strings, ignoring case. Returns true if and only if // Compares two wide C strings, ignoring case. Returns true if and only if
// they have the same content. // 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, // 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. // ignoring case. Any string is considered to end with an empty suffix.
static bool EndsWithCaseInsensitive( static bool EndsWithCaseInsensitive(const std::string& str,
const std::string& str, const std::string& suffix); const std::string& suffix);
// Formats an int value as "%02d". // Formats an int value as "%02d".
static std::string FormatIntWidth2(int value); // "%02d" for width == 2 static std::string FormatIntWidth2(int value); // "%02d" for width == 2
@ -165,7 +165,7 @@ class GTEST_API_ String {
private: private:
String(); // Not meant to be instantiated. String(); // Not meant to be instantiated.
}; // class String }; // class String
// Gets the content of the stringstream's buffer as an std::string. Each '\0' // Gets the content of the stringstream's buffer as an std::string. Each '\0'
// character in the buffer is replaced with "\\0". // character in the buffer is replaced with "\\0".

View File

@ -41,11 +41,11 @@
// #ifdef __GNUC__ is too general here. It is possible to use gcc without using // #ifdef __GNUC__ is too general here. It is possible to use gcc without using
// libstdc++ (which is where cxxabi.h comes from). // libstdc++ (which is where cxxabi.h comes from).
# if GTEST_HAS_CXXABI_H_ #if GTEST_HAS_CXXABI_H_
# include <cxxabi.h> #include <cxxabi.h>
# elif defined(__HP_aCC) #elif defined(__HP_aCC)
# include <acxx_demangle.h> #include <acxx_demangle.h>
# endif // GTEST_HASH_CXXABI_H_ #endif // GTEST_HASH_CXXABI_H_
namespace testing { namespace testing {
namespace internal { namespace internal {
@ -103,7 +103,9 @@ std::string GetTypeName() {
// A unique type indicating an empty node // A unique type indicating an empty node
struct None {}; 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 // The template "selector" struct TemplateSel<Tmpl> is used to
// represent Tmpl, which must be a class template with one type // represent Tmpl, which must be a class template with one type
@ -121,8 +123,7 @@ struct TemplateSel {
}; };
}; };
# define GTEST_BIND_(TmplSel, T) \ #define GTEST_BIND_(TmplSel, T) TmplSel::template Bind<T>::type
TmplSel::template Bind<T>::type
template <GTEST_TEMPLATE_ Head_, GTEST_TEMPLATE_... Tail_> template <GTEST_TEMPLATE_ Head_, GTEST_TEMPLATE_... Tail_>
struct Templates { struct Templates {

View File

@ -27,8 +27,6 @@
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// This provides interface PrimeTable that determines whether a number is a // This provides interface PrimeTable that determines whether a number is a
// prime and determines a next prime number. This interface is used // prime and determines a next prime number. This interface is used
// in Google Test samples demonstrating use of parameterized tests. // in Google Test samples demonstrating use of parameterized tests.
@ -57,7 +55,7 @@ class OnTheFlyPrimeTable : public PrimeTable {
bool IsPrime(int n) const override { bool IsPrime(int n) const override {
if (n <= 1) return false; 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. // n is divisible by an integer other than 1 and itself.
if ((n % i) == 0) return false; 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 // Checks every candidate for prime number (we know that 2 is the only even
// prime). // 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; if (!is_prime_[i]) continue;
// Marks all multiples of i (except i itself) as non-prime. // Marks all multiples of i (except i itself) as non-prime.
// We are starting here from i-th multiplier, because all smaller // We are starting here from i-th multiplier, because all smaller
// complex numbers were already marked. // 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; is_prime_[j] = false;
} }
} }

View File

@ -52,9 +52,9 @@ bool IsPrime(int n) {
// Now, we have that n is odd and n >= 3. // Now, we have that n is odd and n >= 3.
// Try to divide n by every odd number i, starting from 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 // 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. // Now, we have i <= n/i < n.
// If n is divisible by i, n is not prime. // If n is divisible by i, n is not prime.

View File

@ -26,7 +26,6 @@
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// This sample shows how to use Google Test listener API to implement // This sample shows how to use Google Test listener API to implement
// a primitive leak checker. // a primitive leak checker.
@ -104,14 +103,15 @@ TEST(ListenersTest, LeaksWater) {
} }
} // namespace } // namespace
int main(int argc, char **argv) { int main(int argc, char** argv) {
InitGoogleTest(&argc, argv); InitGoogleTest(&argc, argv);
bool check_for_leaks = false; 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; check_for_leaks = true;
else 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."); "custom leak checking in the tests.");
// If we are given the --check_for_leaks command line flag, installs the // If we are given the --check_for_leaks command line flag, installs the

View File

@ -34,14 +34,15 @@
// //
// Writing a unit test using Google C++ testing framework is easy as 1-2-3: // 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 // Step 1. Include necessary header files such that the stuff your
// test logic needs is declared. // test logic needs is declared.
// //
// Don't forget gtest.h, which declares the testing framework. // Don't forget gtest.h, which declares the testing framework.
#include <limits.h>
#include "sample1.h" #include "sample1.h"
#include <limits.h>
#include "gtest/gtest.h" #include "gtest/gtest.h"
namespace { namespace {
@ -69,7 +70,6 @@ namespace {
// //
// </TechnicalDetails> // </TechnicalDetails>
// Tests Factorial(). // Tests Factorial().
// Tests factorial of negative numbers. // Tests factorial of negative numbers.
@ -97,9 +97,7 @@ TEST(FactorialTest, Negative) {
} }
// Tests factorial of 0. // Tests factorial of 0.
TEST(FactorialTest, Zero) { TEST(FactorialTest, Zero) { EXPECT_EQ(1, Factorial(0)); }
EXPECT_EQ(1, Factorial(0));
}
// Tests factorial of positive numbers. // Tests factorial of positive numbers.
TEST(FactorialTest, Positive) { TEST(FactorialTest, Positive) {
@ -109,7 +107,6 @@ TEST(FactorialTest, Positive) {
EXPECT_EQ(40320, Factorial(8)); EXPECT_EQ(40320, Factorial(8));
} }
// Tests IsPrime() // Tests IsPrime()
// Tests negative input. // Tests negative input.

View File

@ -38,7 +38,7 @@ const char* MyString::CloneCString(const char* a_c_string) {
if (a_c_string == nullptr) return nullptr; if (a_c_string == nullptr) return nullptr;
const size_t len = strlen(a_c_string); 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); memcpy(clone, a_c_string, len + 1);
return clone; return clone;

View File

@ -34,7 +34,6 @@
#include <string.h> #include <string.h>
// A simple string class. // A simple string class.
class MyString { class MyString {
private: private:

View File

@ -38,6 +38,7 @@
// needed. // needed.
#include "sample2.h" #include "sample2.h"
#include "gtest/gtest.h" #include "gtest/gtest.h"
namespace { namespace {
// In this example, we test the MyString class (a simple string). // In this example, we test the MyString class (a simple string).
@ -77,8 +78,7 @@ const char kHelloString[] = "Hello, world!";
TEST(MyString, ConstructorFromCString) { TEST(MyString, ConstructorFromCString) {
const MyString s(kHelloString); const MyString s(kHelloString);
EXPECT_EQ(0, strcmp(s.c_string(), kHelloString)); EXPECT_EQ(0, strcmp(s.c_string(), kHelloString));
EXPECT_EQ(sizeof(kHelloString)/sizeof(kHelloString[0]) - 1, EXPECT_EQ(sizeof(kHelloString) / sizeof(kHelloString[0]) - 1, s.Length());
s.Length());
} }
// Tests the copy c'tor. // Tests the copy c'tor.

View File

@ -34,7 +34,6 @@
#include <stddef.h> #include <stddef.h>
// Queue is a simple queue implemented as a singled-linked list. // Queue is a simple queue implemented as a singled-linked list.
// //
// The element type must support copy constructor. // The element type must support copy constructor.
@ -62,7 +61,7 @@ class QueueNode {
: element_(an_element), next_(nullptr) {} : element_(an_element), next_(nullptr) {}
// We disable the default assignment operator and copy c'tor. // We disable the default assignment operator and copy c'tor.
const QueueNode& operator = (const QueueNode&); const QueueNode& operator=(const QueueNode&);
QueueNode(const QueueNode&); QueueNode(const QueueNode&);
E element_; E element_;
@ -84,7 +83,7 @@ class Queue {
// 1. Deletes every node. // 1. Deletes every node.
QueueNode<E>* node = head_; QueueNode<E>* node = head_;
QueueNode<E>* next = node->next(); QueueNode<E>* next = node->next();
for (; ;) { for (;;) {
delete node; delete node;
node = next; node = next;
if (node == nullptr) break; if (node == nullptr) break;
@ -162,11 +161,11 @@ class Queue {
private: private:
QueueNode<E>* head_; // The first node of the queue. QueueNode<E>* head_; // The first node of the queue.
QueueNode<E>* last_; // The last 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. // We disallow copying a queue.
Queue(const Queue&); Queue(const Queue&);
const Queue& operator = (const Queue&); const Queue& operator=(const Queue&);
}; };
#endif // GOOGLETEST_SAMPLES_SAMPLE3_INL_H_ #endif // GOOGLETEST_SAMPLES_SAMPLE3_INL_H_

View File

@ -67,7 +67,6 @@ namespace {
class QueueTestSmpl3 : public testing::Test { class QueueTestSmpl3 : public testing::Test {
protected: // You should make the members protected s.t. they can be protected: // You should make the members protected s.t. they can be
// accessed from sub-classes. // accessed from sub-classes.
// virtual void SetUp() will be called before each test is run. You // virtual void SetUp() will be called before each test is run. You
// should define it if you need to initialize the variables. // should define it if you need to initialize the variables.
// Otherwise, this can be skipped. // Otherwise, this can be skipped.
@ -85,15 +84,13 @@ class QueueTestSmpl3 : public testing::Test {
// } // }
// A helper function that some test uses. // A helper function that some test uses.
static int Double(int n) { static int Double(int n) { return 2 * n; }
return 2*n;
}
// A helper function for testing Queue::Map(). // 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 // Creates a new queue, where each element is twice as big as the
// corresponding one in q. // 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. // Verifies that the new queue has the same size as q.
ASSERT_EQ(q->Size(), new_q->Size()); ASSERT_EQ(q->Size(), new_q->Size());
@ -124,7 +121,7 @@ TEST_F(QueueTestSmpl3, DefaultConstructor) {
// Tests Dequeue(). // Tests Dequeue().
TEST_F(QueueTestSmpl3, Dequeue) { TEST_F(QueueTestSmpl3, Dequeue) {
int * n = q0_.Dequeue(); int* n = q0_.Dequeue();
EXPECT_TRUE(n == nullptr); EXPECT_TRUE(n == nullptr);
n = q1_.Dequeue(); n = q1_.Dequeue();

View File

@ -29,26 +29,22 @@
// A sample program demonstrating using Google C++ testing framework. // A sample program demonstrating using Google C++ testing framework.
#include <stdio.h>
#include "sample4.h" #include "sample4.h"
#include <stdio.h>
// Returns the current counter value, and increments it. // Returns the current counter value, and increments it.
int Counter::Increment() { int Counter::Increment() { return counter_++; }
return counter_++;
}
// Returns the current counter value, and decrements it. // Returns the current counter value, and decrements it.
// counter can not be less than 0, return 0 in this case // counter can not be less than 0, return 0 in this case
int Counter::Decrement() { int Counter::Decrement() {
if (counter_ == 0) { if (counter_ == 0) {
return counter_; return counter_;
} else { } else {
return counter_--; return counter_--;
} }
} }
// Prints the current counter value to STDOUT. // Prints the current counter value to STDOUT.
void Counter::Print() const { void Counter::Print() const { printf("%d", counter_); }
printf("%d", counter_);
}

View File

@ -27,8 +27,8 @@
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include "sample4.h" #include "sample4.h"
#include "gtest/gtest.h" #include "gtest/gtest.h"
namespace { namespace {

View File

@ -27,7 +27,6 @@
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// This sample teaches how to reuse a test fixture in multiple test // This sample teaches how to reuse a test fixture in multiple test
// cases by deriving sub-fixtures from it. // cases by deriving sub-fixtures from it.
// //
@ -45,9 +44,10 @@
#include <limits.h> #include <limits.h>
#include <time.h> #include <time.h>
#include "gtest/gtest.h"
#include "sample1.h" #include "sample1.h"
#include "sample3-inl.h" #include "sample3-inl.h"
#include "gtest/gtest.h"
namespace { namespace {
// In this sample, we want to ensure that every test finishes within // 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 // ~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_; time_t start_time_;
}; };
// We derive a fixture named IntegerFunctionTest from the QuickTest // We derive a fixture named IntegerFunctionTest from the QuickTest
// fixture. All tests using this fixture will be automatically // fixture. All tests using this fixture will be automatically
// required to be quick. // required to be quick.
@ -90,7 +89,6 @@ class IntegerFunctionTest : public QuickTest {
// Therefore the body is empty. // Therefore the body is empty.
}; };
// Now we can write tests in the IntegerFunctionTest test case. // Now we can write tests in the IntegerFunctionTest test case.
// Tests Factorial() // Tests Factorial()
@ -110,7 +108,6 @@ TEST_F(IntegerFunctionTest, Factorial) {
EXPECT_EQ(40320, Factorial(8)); EXPECT_EQ(40320, Factorial(8));
} }
// Tests IsPrime() // Tests IsPrime()
TEST_F(IntegerFunctionTest, IsPrime) { TEST_F(IntegerFunctionTest, IsPrime) {
// Tests negative input. // Tests negative input.
@ -131,7 +128,6 @@ TEST_F(IntegerFunctionTest, IsPrime) {
EXPECT_TRUE(IsPrime(23)); EXPECT_TRUE(IsPrime(23));
} }
// The next test case (named "QueueTest") also needs to be quick, so // The next test case (named "QueueTest") also needs to be quick, so
// we derive another fixture from QuickTest. // we derive another fixture from QuickTest.
// //
@ -163,13 +159,10 @@ class QueueTest : public QuickTest {
Queue<int> q2_; Queue<int> q2_;
}; };
// Now, let's write tests using the QueueTest fixture. // Now, let's write tests using the QueueTest fixture.
// Tests the default constructor. // Tests the default constructor.
TEST_F(QueueTest, DefaultConstructor) { TEST_F(QueueTest, DefaultConstructor) { EXPECT_EQ(0u, q0_.Size()); }
EXPECT_EQ(0u, q0_.Size());
}
// Tests Dequeue(). // Tests Dequeue().
TEST_F(QueueTest, Dequeue) { TEST_F(QueueTest, Dequeue) {

View File

@ -27,13 +27,11 @@
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// This sample shows how to test common properties of multiple // This sample shows how to test common properties of multiple
// implementations of the same interface (aka interface tests). // implementations of the same interface (aka interface tests).
// The interface and its implementations are in this header. // The interface and its implementations are in this header.
#include "prime_tables.h" #include "prime_tables.h"
#include "gtest/gtest.h" #include "gtest/gtest.h"
namespace { namespace {
// First, we define some factory functions for creating instances of // First, we define some factory functions for creating instances of
@ -151,8 +149,7 @@ using testing::Types;
// the PrimeTableTest fixture defined earlier: // the PrimeTableTest fixture defined earlier:
template <class T> 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 // 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 // fixture, and also the name of the test case (as usual). The _P

View File

@ -27,7 +27,6 @@
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// This sample shows how to test common properties of multiple // This sample shows how to test common properties of multiple
// implementations of an interface (aka interface tests) using // implementations of an interface (aka interface tests) using
// value-parameterized tests. Each test in the test case has // value-parameterized tests. Each test in the test case has
@ -36,7 +35,6 @@
// The interface and its implementations are in this header. // The interface and its implementations are in this header.
#include "prime_tables.h" #include "prime_tables.h"
#include "gtest/gtest.h" #include "gtest/gtest.h"
namespace { namespace {
@ -50,9 +48,7 @@ using ::testing::Values;
// SetUp() method and delete them in TearDown() method. // SetUp() method and delete them in TearDown() method.
typedef PrimeTable* CreatePrimeTableFunc(); typedef PrimeTable* CreatePrimeTableFunc();
PrimeTable* CreateOnTheFlyPrimeTable() { PrimeTable* CreateOnTheFlyPrimeTable() { return new OnTheFlyPrimeTable(); }
return new OnTheFlyPrimeTable();
}
template <size_t max_precalculated> template <size_t max_precalculated>
PrimeTable* CreatePreCalculatedPrimeTable() { PrimeTable* CreatePreCalculatedPrimeTable() {

View File

@ -27,14 +27,12 @@
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // 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. // This sample shows how to test code relying on some global flag variables.
// Combine() helps with generating all possible combinations of such flags, // Combine() helps with generating all possible combinations of such flags,
// and each test is given one combination as a parameter. // and each test is given one combination as a parameter.
// Use class definitions to test from this header. // Use class definitions to test from this header.
#include "prime_tables.h" #include "prime_tables.h"
#include "gtest/gtest.h" #include "gtest/gtest.h"
namespace { namespace {
@ -79,10 +77,10 @@ class HybridPrimeTable : public PrimeTable {
int max_precalculated_; int max_precalculated_;
}; };
using ::testing::TestWithParam;
using ::testing::Bool; using ::testing::Bool;
using ::testing::Values;
using ::testing::Combine; using ::testing::Combine;
using ::testing::TestWithParam;
using ::testing::Values;
// To test all code paths for HybridPrimeTable we must test it with numbers // To test all code paths for HybridPrimeTable we must test it with numbers
// both within and outside PreCalculatedPrimeTable's capacity and also with // both within and outside PreCalculatedPrimeTable's capacity and also with

View File

@ -26,7 +26,6 @@
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// This sample shows how to use Google Test listener API to implement // This sample shows how to use Google Test listener API to implement
// an alternative console output and how to use the UnitTest reflection API // an alternative console output and how to use the UnitTest reflection API
// to enumerate test suites and tests and to inspect their results. // to enumerate test suites and tests and to inspect their results.
@ -38,10 +37,10 @@
using ::testing::EmptyTestEventListener; using ::testing::EmptyTestEventListener;
using ::testing::InitGoogleTest; using ::testing::InitGoogleTest;
using ::testing::Test; using ::testing::Test;
using ::testing::TestSuite;
using ::testing::TestEventListeners; using ::testing::TestEventListeners;
using ::testing::TestInfo; using ::testing::TestInfo;
using ::testing::TestPartResult; using ::testing::TestPartResult;
using ::testing::TestSuite;
using ::testing::UnitTest; using ::testing::UnitTest;
namespace { namespace {
// Provides alternative output mode which produces minimal amount of // Provides alternative output mode which produces minimal amount of
@ -59,29 +58,23 @@ class TersePrinter : public EmptyTestEventListener {
// Called before a test starts. // Called before a test starts.
void OnTestStart(const TestInfo& test_info) override { void OnTestStart(const TestInfo& test_info) override {
fprintf(stdout, fprintf(stdout, "*** Test %s.%s starting.\n", test_info.test_suite_name(),
"*** Test %s.%s starting.\n",
test_info.test_suite_name(),
test_info.name()); test_info.name());
fflush(stdout); fflush(stdout);
} }
// Called after a failed assertion or a SUCCEED() invocation. // Called after a failed assertion or a SUCCEED() invocation.
void OnTestPartResult(const TestPartResult& test_part_result) override { void OnTestPartResult(const TestPartResult& test_part_result) override {
fprintf(stdout, fprintf(stdout, "%s in %s:%d\n%s\n",
"%s in %s:%d\n%s\n",
test_part_result.failed() ? "*** Failure" : "Success", test_part_result.failed() ? "*** Failure" : "Success",
test_part_result.file_name(), test_part_result.file_name(), test_part_result.line_number(),
test_part_result.line_number(),
test_part_result.summary()); test_part_result.summary());
fflush(stdout); fflush(stdout);
} }
// Called after a test ends. // Called after a test ends.
void OnTestEnd(const TestInfo& test_info) override { void OnTestEnd(const TestInfo& test_info) override {
fprintf(stdout, fprintf(stdout, "*** Test %s.%s ending.\n", test_info.test_suite_name(),
"*** Test %s.%s ending.\n",
test_info.test_suite_name(),
test_info.name()); test_info.name());
fflush(stdout); fflush(stdout);
} }
@ -101,14 +94,15 @@ TEST(CustomOutputTest, Fails) {
} }
} // namespace } // namespace
int main(int argc, char **argv) { int main(int argc, char** argv) {
InitGoogleTest(&argc, argv); InitGoogleTest(&argc, argv);
bool terse_output = false; 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; terse_output = true;
else 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."); "it prints its output.");
UnitTest& unit_test = *UnitTest::GetInstance(); 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. // Test that were meant to fail should not affect the test program outcome.
if (unexpectedly_failed_tests == 0) if (unexpectedly_failed_tests == 0) ret_val = 0;
ret_val = 0;
return ret_val; return ret_val;
} }

View File

@ -38,7 +38,6 @@
#include "gtest/gtest.h" #include "gtest/gtest.h"
// The following lines pull in the real gtest *.cc files. // The following lines pull in the real gtest *.cc files.
#include "src/gtest.cc"
#include "src/gtest-assertion-result.cc" #include "src/gtest-assertion-result.cc"
#include "src/gtest-death-test.cc" #include "src/gtest-death-test.cc"
#include "src/gtest-filepath.cc" #include "src/gtest-filepath.cc"
@ -47,3 +46,4 @@
#include "src/gtest-printers.cc" #include "src/gtest-printers.cc"
#include "src/gtest-test-part.cc" #include "src/gtest-test-part.cc"
#include "src/gtest-typed-test.cc" #include "src/gtest-typed-test.cc"
#include "src/gtest.cc"

View File

@ -33,8 +33,8 @@
#include "gtest/gtest-assertion-result.h" #include "gtest/gtest-assertion-result.h"
#include <utility>
#include <string> #include <string>
#include <utility>
#include "gtest/gtest-message.h" #include "gtest/gtest-message.h"
@ -63,14 +63,10 @@ AssertionResult AssertionResult::operator!() const {
} }
// Makes a successful assertion result. // Makes a successful assertion result.
AssertionResult AssertionSuccess() { AssertionResult AssertionSuccess() { return AssertionResult(true); }
return AssertionResult(true);
}
// Makes a failed assertion result. // Makes a failed assertion result.
AssertionResult AssertionFailure() { AssertionResult AssertionFailure() { return AssertionResult(false); }
return AssertionResult(false);
}
// Makes a failed assertion result with the given failure message. // Makes a failed assertion result with the given failure message.
// Deprecated; use AssertionFailure() << message. // Deprecated; use AssertionFailure() << message.

View File

@ -35,49 +35,49 @@
#include <functional> #include <functional>
#include <utility> #include <utility>
#include "gtest/internal/gtest-port.h"
#include "gtest/internal/custom/gtest.h" #include "gtest/internal/custom/gtest.h"
#include "gtest/internal/gtest-port.h"
#if GTEST_HAS_DEATH_TEST #if GTEST_HAS_DEATH_TEST
# if GTEST_OS_MAC #if GTEST_OS_MAC
# include <crt_externs.h> #include <crt_externs.h>
# endif // GTEST_OS_MAC #endif // GTEST_OS_MAC
# include <errno.h> #include <errno.h>
# include <fcntl.h> #include <fcntl.h>
# include <limits.h> #include <limits.h>
# if GTEST_OS_LINUX #if GTEST_OS_LINUX
# include <signal.h> #include <signal.h>
# endif // GTEST_OS_LINUX #endif // GTEST_OS_LINUX
# include <stdarg.h> #include <stdarg.h>
# if GTEST_OS_WINDOWS #if GTEST_OS_WINDOWS
# include <windows.h> #include <windows.h>
# else #else
# include <sys/mman.h> #include <sys/mman.h>
# include <sys/wait.h> #include <sys/wait.h>
# endif // GTEST_OS_WINDOWS #endif // GTEST_OS_WINDOWS
# if GTEST_OS_QNX #if GTEST_OS_QNX
# include <spawn.h> #include <spawn.h>
# endif // GTEST_OS_QNX #endif // GTEST_OS_QNX
# if GTEST_OS_FUCHSIA #if GTEST_OS_FUCHSIA
# include <lib/fdio/fd.h> #include <lib/fdio/fd.h>
# include <lib/fdio/io.h> #include <lib/fdio/io.h>
# include <lib/fdio/spawn.h> #include <lib/fdio/spawn.h>
# include <lib/zx/channel.h> #include <lib/zx/channel.h>
# include <lib/zx/port.h> #include <lib/zx/port.h>
# include <lib/zx/process.h> #include <lib/zx/process.h>
# include <lib/zx/socket.h> #include <lib/zx/socket.h>
# include <zircon/processargs.h> #include <zircon/processargs.h>
# include <zircon/syscalls.h> #include <zircon/syscalls.h>
# include <zircon/syscalls/policy.h> #include <zircon/syscalls/policy.h>
# include <zircon/syscalls/port.h> #include <zircon/syscalls/port.h>
# endif // GTEST_OS_FUCHSIA #endif // GTEST_OS_FUCHSIA
#endif // GTEST_HAS_DEATH_TEST #endif // GTEST_HAS_DEATH_TEST
@ -137,9 +137,9 @@ namespace internal {
// Valid only for fast death tests. Indicates the code is running in the // Valid only for fast death tests. Indicates the code is running in the
// child process of a fast style death test. // 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; static bool g_in_fast_death_test_child = false;
# endif #endif
// Returns a Boolean value indicating whether the caller is currently // Returns a Boolean value indicating whether the caller is currently
// executing in the context of the death test child process. Tools such as // 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 // tests. IMPORTANT: This is an internal utility. Using it may break the
// implementation of death tests. User code MUST NOT use it. // implementation of death tests. User code MUST NOT use it.
bool InDeathTestChild() { 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 // On Windows and Fuchsia, death tests are thread-safe regardless of the value
// of the death_test_style flag. // of the death_test_style flag.
return !GTEST_FLAG_GET(internal_run_death_test).empty(); return !GTEST_FLAG_GET(internal_run_death_test).empty();
# else #else
if (GTEST_FLAG_GET(death_test_style) == "threadsafe") if (GTEST_FLAG_GET(death_test_style) == "threadsafe")
return !GTEST_FLAG_GET(internal_run_death_test).empty(); return !GTEST_FLAG_GET(internal_run_death_test).empty();
@ -165,40 +165,38 @@ bool InDeathTestChild() {
} // namespace internal } // namespace internal
// ExitedWithCode constructor. // ExitedWithCode constructor.
ExitedWithCode::ExitedWithCode(int exit_code) : exit_code_(exit_code) { ExitedWithCode::ExitedWithCode(int exit_code) : exit_code_(exit_code) {}
}
// ExitedWithCode function-call operator. // ExitedWithCode function-call operator.
bool ExitedWithCode::operator()(int exit_status) const { 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_; return exit_status == exit_code_;
# else #else
return WIFEXITED(exit_status) && WEXITSTATUS(exit_status) == exit_code_; 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 constructor.
KilledBySignal::KilledBySignal(int signum) : signum_(signum) { KilledBySignal::KilledBySignal(int signum) : signum_(signum) {}
}
// KilledBySignal function-call operator. // KilledBySignal function-call operator.
bool KilledBySignal::operator()(int exit_status) const { bool KilledBySignal::operator()(int exit_status) const {
# if defined(GTEST_KILLED_BY_SIGNAL_OVERRIDE_) #if defined(GTEST_KILLED_BY_SIGNAL_OVERRIDE_)
{ {
bool result; bool result;
if (GTEST_KILLED_BY_SIGNAL_OVERRIDE_(signum_, exit_status, &result)) { if (GTEST_KILLED_BY_SIGNAL_OVERRIDE_(signum_, exit_status, &result)) {
return 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_; return WIFSIGNALED(exit_status) && WTERMSIG(exit_status) == signum_;
} }
# endif // !GTEST_OS_WINDOWS && !GTEST_OS_FUCHSIA #endif // !GTEST_OS_WINDOWS && !GTEST_OS_FUCHSIA
namespace internal { namespace internal {
@ -209,23 +207,23 @@ namespace internal {
static std::string ExitSummary(int exit_code) { static std::string ExitSummary(int exit_code) {
Message m; Message m;
# if GTEST_OS_WINDOWS || GTEST_OS_FUCHSIA #if GTEST_OS_WINDOWS || GTEST_OS_FUCHSIA
m << "Exited with exit status " << exit_code; m << "Exited with exit status " << exit_code;
# else #else
if (WIFEXITED(exit_code)) { if (WIFEXITED(exit_code)) {
m << "Exited with exit status " << WEXITSTATUS(exit_code); m << "Exited with exit status " << WEXITSTATUS(exit_code);
} else if (WIFSIGNALED(exit_code)) { } else if (WIFSIGNALED(exit_code)) {
m << "Terminated by signal " << WTERMSIG(exit_code); m << "Terminated by signal " << WTERMSIG(exit_code);
} }
# ifdef WCOREDUMP #ifdef WCOREDUMP
if (WCOREDUMP(exit_code)) { if (WCOREDUMP(exit_code)) {
m << " (core dumped)"; m << " (core dumped)";
} }
# endif #endif
# endif // GTEST_OS_WINDOWS || GTEST_OS_FUCHSIA #endif // GTEST_OS_WINDOWS || GTEST_OS_FUCHSIA
return m.GetString(); return m.GetString();
} }
@ -236,7 +234,7 @@ bool ExitedUnsuccessfully(int exit_status) {
return !ExitedWithCode(0)(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 // Generates a textual failure message when a death test finds more than
// one thread running, or cannot determine the number of threads, prior // one thread running, or cannot determine the number of threads, prior
// to executing the given statement. It is the responsibility of the // 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."; << " this is the last message you see before your test times out.";
return msg.GetString(); 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. // Flag characters for reporting a death test that did not die.
static const char kDeathTestLived = 'L'; 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 // A replacement for CHECK that calls DeathTestAbort if the assertion
// fails. // fails.
# define GTEST_DEATH_TEST_CHECK_(expression) \ #define GTEST_DEATH_TEST_CHECK_(expression) \
do { \ do { \
if (!::testing::internal::IsTrue(expression)) { \ if (!::testing::internal::IsTrue(expression)) { \
DeathTestAbort( \ DeathTestAbort(::std::string("CHECK failed: File ") + __FILE__ + \
::std::string("CHECK failed: File ") + __FILE__ + ", line " \ ", line " + \
+ ::testing::internal::StreamableToString(__LINE__) + ": " \ ::testing::internal::StreamableToString(__LINE__) + \
+ #expression); \ ": " + #expression); \
} \ } \
} while (::testing::internal::AlwaysFalse()) } while (::testing::internal::AlwaysFalse())
// This macro is similar to GTEST_DEATH_TEST_CHECK_, but it is meant for // 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 // evaluates the expression as long as it evaluates to -1 and sets
// errno to EINTR. If the expression evaluates to -1 but errno is // errno to EINTR. If the expression evaluates to -1 but errno is
// something other than EINTR, DeathTestAbort is called. // something other than EINTR, DeathTestAbort is called.
# define GTEST_DEATH_TEST_CHECK_SYSCALL_(expression) \ #define GTEST_DEATH_TEST_CHECK_SYSCALL_(expression) \
do { \ do { \
int gtest_retval; \ int gtest_retval; \
do { \ do { \
gtest_retval = (expression); \ gtest_retval = (expression); \
} while (gtest_retval == -1 && errno == EINTR); \ } while (gtest_retval == -1 && errno == EINTR); \
if (gtest_retval == -1) { \ if (gtest_retval == -1) { \
DeathTestAbort( \ DeathTestAbort(::std::string("CHECK failed: File ") + __FILE__ + \
::std::string("CHECK failed: File ") + __FILE__ + ", line " \ ", line " + \
+ ::testing::internal::StreamableToString(__LINE__) + ": " \ ::testing::internal::StreamableToString(__LINE__) + \
+ #expression + " != -1"); \ ": " + #expression + " != -1"); \
} \ } \
} while (::testing::internal::AlwaysFalse()) } while (::testing::internal::AlwaysFalse())
// Returns the message describing the last system error in errno. // Returns the message describing the last system error in errno.
std::string GetLastErrnoDescription() { 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 // This is called from a death test parent process to read a failure
@ -373,8 +371,9 @@ static void FailFromInternalError(int fd) {
DeathTest::DeathTest() { DeathTest::DeathTest() {
TestInfo* const info = GetUnitTestImpl()->current_test_info(); TestInfo* const info = GetUnitTestImpl()->current_test_info();
if (info == nullptr) { if (info == nullptr) {
DeathTestAbort("Cannot run a death test outside of a TEST or " DeathTestAbort(
"TEST_F construct"); "Cannot run a death test outside of a TEST or "
"TEST_F construct");
} }
} }
@ -503,9 +502,7 @@ void DeathTestImpl::ReadAndInterpretStatusByte() {
set_read_fd(-1); set_read_fd(-1);
} }
std::string DeathTestImpl::GetErrorLogs() { std::string DeathTestImpl::GetErrorLogs() { return GetCapturedStderr(); }
return GetCapturedStderr();
}
// Signals that the death test code which should have exited, didn't. // Signals that the death test code which should have exited, didn't.
// Should be called only in a death test child process. // 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 // 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 // it finds any data in our pipe. So, here we write a single flag byte
// to the pipe, then exit. // to the pipe, then exit.
const char status_ch = const char status_ch = reason == TEST_DID_NOT_DIE ? kDeathTestLived
reason == TEST_DID_NOT_DIE ? kDeathTestLived : : reason == TEST_THREW_EXCEPTION ? kDeathTestThrew
reason == TEST_THREW_EXCEPTION ? kDeathTestThrew : kDeathTestReturned; : kDeathTestReturned;
GTEST_DEATH_TEST_CHECK_SYSCALL_(posix::Write(write_fd(), &status_ch, 1)); GTEST_DEATH_TEST_CHECK_SYSCALL_(posix::Write(write_fd(), &status_ch, 1));
// We are leaking the descriptor here because on some platforms (i.e., // We are leaking the descriptor here because on some platforms (i.e.,
@ -536,7 +533,7 @@ void DeathTestImpl::Abort(AbortReason reason) {
// much easier. // much easier.
static ::std::string FormatDeathTestOutput(const ::std::string& output) { static ::std::string FormatDeathTestOutput(const ::std::string& output) {
::std::string ret; ::std::string ret;
for (size_t at = 0; ; ) { for (size_t at = 0;;) {
const size_t line_end = output.find('\n', at); const size_t line_end = output.find('\n', at);
ret += "[ DEATH ] "; ret += "[ DEATH ] ";
if (line_end == ::std::string::npos) { 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 // the first failing condition, in the order given above, is the one that is
// reported. Also sets the last death test message string. // reported. Also sets the last death test message string.
bool DeathTestImpl::Passed(bool status_ok) { bool DeathTestImpl::Passed(bool status_ok) {
if (!spawned()) if (!spawned()) return false;
return false;
const std::string error_message = GetErrorLogs(); const std::string error_message = GetErrorLogs();
@ -583,15 +579,18 @@ bool DeathTestImpl::Passed(bool status_ok) {
switch (outcome()) { switch (outcome()) {
case LIVED: case LIVED:
buffer << " Result: failed to die.\n" buffer << " Result: failed to die.\n"
<< " Error msg:\n" << FormatDeathTestOutput(error_message); << " Error msg:\n"
<< FormatDeathTestOutput(error_message);
break; break;
case THREW: case THREW:
buffer << " Result: threw an exception.\n" buffer << " Result: threw an exception.\n"
<< " Error msg:\n" << FormatDeathTestOutput(error_message); << " Error msg:\n"
<< FormatDeathTestOutput(error_message);
break; break;
case RETURNED: case RETURNED:
buffer << " Result: illegal return in test statement.\n" buffer << " Result: illegal return in test statement.\n"
<< " Error msg:\n" << FormatDeathTestOutput(error_message); << " Error msg:\n"
<< FormatDeathTestOutput(error_message);
break; break;
case DIED: case DIED:
if (status_ok) { if (status_ok) {
@ -608,7 +607,8 @@ bool DeathTestImpl::Passed(bool status_ok) {
} else { } else {
buffer << " Result: died but not with expected exit code:\n" buffer << " Result: died but not with expected exit code:\n"
<< " " << ExitSummary(status()) << "\n" << " " << ExitSummary(status()) << "\n"
<< "Actual msg:\n" << FormatDeathTestOutput(error_message); << "Actual msg:\n"
<< FormatDeathTestOutput(error_message);
} }
break; break;
case IN_PROGRESS: case IN_PROGRESS:
@ -621,7 +621,7 @@ bool DeathTestImpl::Passed(bool status_ok) {
return success; return success;
} }
# if GTEST_OS_WINDOWS #if GTEST_OS_WINDOWS
// WindowsDeathTest implements death tests on Windows. Due to the // WindowsDeathTest implements death tests on Windows. Due to the
// specifics of starting new processes on Windows, death tests there are // specifics of starting new processes on Windows, death tests there are
// always threadsafe, and Google Test considers the // 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 // status, or 0 if no child process exists. As a side effect, sets the
// outcome data member. // outcome data member.
int WindowsDeathTest::Wait() { int WindowsDeathTest::Wait() {
if (!spawned()) if (!spawned()) return 0;
return 0;
// Wait until the child either signals that it has acquired the write end // Wait until the child either signals that it has acquired the write end
// of the pipe or it dies. // of the pipe or it dies.
const HANDLE wait_handles[2] = { child_handle_.Get(), event_handle_.Get() }; const HANDLE wait_handles[2] = {child_handle_.Get(), event_handle_.Get()};
switch (::WaitForMultipleObjects(2, switch (::WaitForMultipleObjects(2, wait_handles,
wait_handles,
FALSE, // Waits for any of the handles. FALSE, // Waits for any of the handles.
INFINITE)) { INFINITE)) {
case WAIT_OBJECT_0: case WAIT_OBJECT_0:
@ -710,9 +708,8 @@ int WindowsDeathTest::Wait() {
// returns immediately if the child has already exited, regardless of // returns immediately if the child has already exited, regardless of
// whether previous calls to WaitForMultipleObjects synchronized on this // whether previous calls to WaitForMultipleObjects synchronized on this
// handle or not. // handle or not.
GTEST_DEATH_TEST_CHECK_( GTEST_DEATH_TEST_CHECK_(WAIT_OBJECT_0 ==
WAIT_OBJECT_0 == ::WaitForSingleObject(child_handle_.Get(), ::WaitForSingleObject(child_handle_.Get(), INFINITE));
INFINITE));
DWORD status_code; DWORD status_code;
GTEST_DEATH_TEST_CHECK_( GTEST_DEATH_TEST_CHECK_(
::GetExitCodeProcess(child_handle_.Get(), &status_code) != FALSE); ::GetExitCodeProcess(child_handle_.Get(), &status_code) != FALSE);
@ -745,12 +742,12 @@ DeathTest::TestRole WindowsDeathTest::AssumeRole() {
SECURITY_ATTRIBUTES handles_are_inheritable = {sizeof(SECURITY_ATTRIBUTES), SECURITY_ATTRIBUTES handles_are_inheritable = {sizeof(SECURITY_ATTRIBUTES),
nullptr, TRUE}; nullptr, TRUE};
HANDLE read_handle, write_handle; HANDLE read_handle, write_handle;
GTEST_DEATH_TEST_CHECK_( GTEST_DEATH_TEST_CHECK_(::CreatePipe(&read_handle, &write_handle,
::CreatePipe(&read_handle, &write_handle, &handles_are_inheritable, &handles_are_inheritable,
0) // Default buffer size. 0) // Default buffer size.
!= FALSE); != FALSE);
set_read_fd(::_open_osfhandle(reinterpret_cast<intptr_t>(read_handle), set_read_fd(
O_RDONLY)); ::_open_osfhandle(reinterpret_cast<intptr_t>(read_handle), O_RDONLY));
write_handle_.Reset(write_handle); write_handle_.Reset(write_handle);
event_handle_.Reset(::CreateEvent( event_handle_.Reset(::CreateEvent(
&handles_are_inheritable, &handles_are_inheritable,
@ -777,9 +774,8 @@ DeathTest::TestRole WindowsDeathTest::AssumeRole() {
executable_path, executable_path,
_MAX_PATH)); _MAX_PATH));
std::string command_line = std::string command_line = std::string(::GetCommandLineA()) + " " +
std::string(::GetCommandLineA()) + " " + filter_flag + " \"" + filter_flag + " \"" + internal_flag + "\"";
internal_flag + "\"";
DeathTest::set_last_death_test_message(""); DeathTest::set_last_death_test_message("");
@ -812,7 +808,7 @@ DeathTest::TestRole WindowsDeathTest::AssumeRole() {
return OVERSEE_TEST; return OVERSEE_TEST;
} }
# elif GTEST_OS_FUCHSIA #elif GTEST_OS_FUCHSIA
class FuchsiaDeathTest : public DeathTestImpl { class FuchsiaDeathTest : public DeathTestImpl {
public: public:
@ -858,18 +854,13 @@ class Arguments {
template <typename Str> template <typename Str>
void AddArguments(const ::std::vector<Str>& arguments) { void AddArguments(const ::std::vector<Str>& arguments) {
for (typename ::std::vector<Str>::const_iterator i = arguments.begin(); for (typename ::std::vector<Str>::const_iterator i = arguments.begin();
i != arguments.end(); i != arguments.end(); ++i) {
++i) {
args_.insert(args_.end() - 1, posix::StrDup(i->c_str())); args_.insert(args_.end() - 1, posix::StrDup(i->c_str()));
} }
} }
char* const* Argv() { char* const* Argv() { return &args_[0]; }
return &args_[0];
}
int size() { int size() { return static_cast<int>(args_.size()) - 1; }
return static_cast<int>(args_.size()) - 1;
}
private: private:
std::vector<char*> args_; std::vector<char*> args_;
@ -883,8 +874,7 @@ int FuchsiaDeathTest::Wait() {
const int kSocketKey = 1; const int kSocketKey = 1;
const int kExceptionKey = 2; const int kExceptionKey = 2;
if (!spawned()) if (!spawned()) return 0;
return 0;
// Create a port to wait for socket/task/exception events. // Create a port to wait for socket/task/exception events.
zx_status_t status_zx; zx_status_t status_zx;
@ -893,8 +883,8 @@ int FuchsiaDeathTest::Wait() {
GTEST_DEATH_TEST_CHECK_(status_zx == ZX_OK); GTEST_DEATH_TEST_CHECK_(status_zx == ZX_OK);
// Register to wait for the child process to terminate. // Register to wait for the child process to terminate.
status_zx = child_process_.wait_async( status_zx =
port, kProcessKey, ZX_PROCESS_TERMINATED, 0); child_process_.wait_async(port, kProcessKey, ZX_PROCESS_TERMINATED, 0);
GTEST_DEATH_TEST_CHECK_(status_zx == ZX_OK); GTEST_DEATH_TEST_CHECK_(status_zx == ZX_OK);
// Register to wait for the socket to be readable or closed. // 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); GTEST_DEATH_TEST_CHECK_(status_zx == ZX_OK);
// Register to wait for an exception. // Register to wait for an exception.
status_zx = exception_channel_.wait_async( status_zx = exception_channel_.wait_async(port, kExceptionKey,
port, kExceptionKey, ZX_CHANNEL_READABLE, 0); ZX_CHANNEL_READABLE, 0);
GTEST_DEATH_TEST_CHECK_(status_zx == ZX_OK); GTEST_DEATH_TEST_CHECK_(status_zx == ZX_OK);
bool process_terminated = false; bool process_terminated = false;
@ -934,9 +924,9 @@ int FuchsiaDeathTest::Wait() {
size_t old_length = captured_stderr_.length(); size_t old_length = captured_stderr_.length();
size_t bytes_read = 0; size_t bytes_read = 0;
captured_stderr_.resize(old_length + kBufferSize); captured_stderr_.resize(old_length + kBufferSize);
status_zx = stderr_socket_.read( status_zx =
0, &captured_stderr_.front() + old_length, kBufferSize, stderr_socket_.read(0, &captured_stderr_.front() + old_length,
&bytes_read); kBufferSize, &bytes_read);
captured_stderr_.resize(old_length + bytes_read); captured_stderr_.resize(old_length + bytes_read);
} while (status_zx == ZX_OK); } while (status_zx == ZX_OK);
if (status_zx == ZX_ERR_PEER_CLOSED) { 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_ + const std::string filter_flag = std::string("--") + GTEST_FLAG_PREFIX_ +
"filter=" + info->test_suite_name() + "." + "filter=" + info->test_suite_name() + "." +
info->name(); info->name();
const std::string internal_flag = const std::string internal_flag = std::string("--") + GTEST_FLAG_PREFIX_ +
std::string("--") + GTEST_FLAG_PREFIX_ + kInternalRunDeathTestFlag + "=" kInternalRunDeathTestFlag + "=" + file_ +
+ file_ + "|" "|" + StreamableToString(line_) + "|" +
+ StreamableToString(line_) + "|" StreamableToString(death_test_index);
+ StreamableToString(death_test_index);
Arguments args; Arguments args;
args.AddArguments(GetInjectableArgvs()); args.AddArguments(GetInjectableArgvs());
args.AddArgument(filter_flag.c_str()); 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. // Create a socket pair will be used to receive the child process' stderr.
zx::socket stderr_producer_socket; zx::socket stderr_producer_socket;
status = status = zx::socket::create(0, &stderr_producer_socket, &stderr_socket_);
zx::socket::create(0, &stderr_producer_socket, &stderr_socket_);
GTEST_DEATH_TEST_CHECK_(status >= 0); GTEST_DEATH_TEST_CHECK_(status >= 0);
int stderr_producer_fd = -1; int stderr_producer_fd = -1;
status = status =
@ -1037,35 +1025,32 @@ DeathTest::TestRole FuchsiaDeathTest::AssumeRole() {
// Create a child job. // Create a child job.
zx_handle_t child_job = ZX_HANDLE_INVALID; 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); GTEST_DEATH_TEST_CHECK_(status == ZX_OK);
zx_policy_basic_t policy; zx_policy_basic_t policy;
policy.condition = ZX_POL_NEW_ANY; policy.condition = ZX_POL_NEW_ANY;
policy.policy = ZX_POL_ACTION_ALLOW; policy.policy = ZX_POL_ACTION_ALLOW;
status = zx_job_set_policy( status = zx_job_set_policy(child_job, ZX_JOB_POL_RELATIVE, ZX_JOB_POL_BASIC,
child_job, ZX_JOB_POL_RELATIVE, ZX_JOB_POL_BASIC, &policy, 1); &policy, 1);
GTEST_DEATH_TEST_CHECK_(status == ZX_OK); GTEST_DEATH_TEST_CHECK_(status == ZX_OK);
// Create an exception channel attached to the |child_job|, to allow // Create an exception channel attached to the |child_job|, to allow
// us to suppress the system default exception handler from firing. // us to suppress the system default exception handler from firing.
status = status = zx_task_create_exception_channel(
zx_task_create_exception_channel( child_job, 0, exception_channel_.reset_and_get_address());
child_job, 0, exception_channel_.reset_and_get_address());
GTEST_DEATH_TEST_CHECK_(status == ZX_OK); GTEST_DEATH_TEST_CHECK_(status == ZX_OK);
// Spawn the child process. // Spawn the child process.
status = fdio_spawn_etc( status = fdio_spawn_etc(child_job, FDIO_SPAWN_CLONE_ALL, args.Argv()[0],
child_job, FDIO_SPAWN_CLONE_ALL, args.Argv()[0], args.Argv(), nullptr, args.Argv(), nullptr, 2, spawn_actions,
2, spawn_actions, child_process_.reset_and_get_address(), nullptr); child_process_.reset_and_get_address(), nullptr);
GTEST_DEATH_TEST_CHECK_(status == ZX_OK); GTEST_DEATH_TEST_CHECK_(status == ZX_OK);
set_spawned(true); set_spawned(true);
return OVERSEE_TEST; return OVERSEE_TEST;
} }
std::string FuchsiaDeathTest::GetErrorLogs() { std::string FuchsiaDeathTest::GetErrorLogs() { return captured_stderr_; }
return captured_stderr_;
}
#else // We are neither on Windows, nor on Fuchsia. #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 // status, or 0 if no child process exists. As a side effect, sets the
// outcome data member. // outcome data member.
int ForkingDeathTest::Wait() { int ForkingDeathTest::Wait() {
if (!spawned()) if (!spawned()) return 0;
return 0;
ReadAndInterpretStatusByte(); ReadAndInterpretStatusByte();
@ -1176,11 +1160,11 @@ class ExecDeathTest : public ForkingDeathTest {
private: private:
static ::std::vector<std::string> GetArgvsForDeathTestChildProcess() { static ::std::vector<std::string> GetArgvsForDeathTestChildProcess() {
::std::vector<std::string> args = GetInjectableArgvs(); ::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 = ::std::vector<std::string> extra_args =
GTEST_EXTRA_DEATH_TEST_COMMAND_LINE_ARGS_(); GTEST_EXTRA_DEATH_TEST_COMMAND_LINE_ARGS_();
args.insert(args.end(), extra_args.begin(), extra_args.end()); 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; return args;
} }
// The name of the file in which the death test is located. // The name of the file in which the death test is located.
@ -1207,14 +1191,11 @@ class Arguments {
template <typename Str> template <typename Str>
void AddArguments(const ::std::vector<Str>& arguments) { void AddArguments(const ::std::vector<Str>& arguments) {
for (typename ::std::vector<Str>::const_iterator i = arguments.begin(); for (typename ::std::vector<Str>::const_iterator i = arguments.begin();
i != arguments.end(); i != arguments.end(); ++i) {
++i) {
args_.insert(args_.end() - 1, posix::StrDup(i->c_str())); args_.insert(args_.end() - 1, posix::StrDup(i->c_str()));
} }
} }
char* const* Argv() { char* const* Argv() { return &args_[0]; }
return &args_[0];
}
private: private:
std::vector<char*> args_; std::vector<char*> args_;
@ -1227,9 +1208,9 @@ struct ExecDeathTestArgs {
int close_fd; // File descriptor to close; the read end of a pipe 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; extern "C" char** environ;
# else // GTEST_OS_QNX #else // GTEST_OS_QNX
// The main function for a threadsafe-style death test child process. // The main function for a threadsafe-style death test child process.
// This function is called in a clone()-ed process and thus must avoid // This function is called in a clone()-ed process and thus must avoid
// any potentially unsafe operations like malloc or libc functions. // any potentially unsafe operations like malloc or libc functions.
@ -1244,8 +1225,8 @@ static int ExecDeathTestChildMain(void* child_arg) {
UnitTest::GetInstance()->original_working_dir(); UnitTest::GetInstance()->original_working_dir();
// We can safely call chdir() as it's a direct system call. // We can safely call chdir() as it's a direct system call.
if (chdir(original_dir) != 0) { if (chdir(original_dir) != 0) {
DeathTestAbort(std::string("chdir(\"") + original_dir + "\") failed: " + DeathTestAbort(std::string("chdir(\"") + original_dir +
GetLastErrnoDescription()); "\") failed: " + GetLastErrnoDescription());
return EXIT_FAILURE; return EXIT_FAILURE;
} }
@ -1256,13 +1237,12 @@ static int ExecDeathTestChildMain(void* child_arg) {
// one path separator. // one path separator.
execv(args->argv[0], args->argv); execv(args->argv[0], args->argv);
DeathTestAbort(std::string("execv(") + args->argv[0] + ", ...) in " + DeathTestAbort(std::string("execv(") + args->argv[0] + ", ...) in " +
original_dir + " failed: " + original_dir + " failed: " + GetLastErrnoDescription());
GetLastErrnoDescription());
return EXIT_FAILURE; 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 // Two utility routines that together determine the direction the stack
// grows. // grows.
// This could be accomplished more elegantly by a single recursive // This could be accomplished more elegantly by a single recursive
@ -1296,7 +1276,7 @@ static bool StackGrowsDown() {
StackLowerThanAddress(&dummy, &result); StackLowerThanAddress(&dummy, &result);
return result; return result;
} }
# endif // GTEST_HAS_CLONE #endif // GTEST_HAS_CLONE
// Spawns a child process with the same executable as the current process in // 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 // 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 // spawn(2) there instead. The function dies with an error message if
// anything goes wrong. // anything goes wrong.
static pid_t ExecDeathTestSpawnChild(char* const* argv, int close_fd) { 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; 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 // Obtains the current directory and sets it to be closed in the child
// process. // process.
const int cwd_fd = open(".", O_RDONLY); 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(); UnitTest::GetInstance()->original_working_dir();
// We can safely call chdir() as it's a direct system call. // We can safely call chdir() as it's a direct system call.
if (chdir(original_dir) != 0) { if (chdir(original_dir) != 0) {
DeathTestAbort(std::string("chdir(\"") + original_dir + "\") failed: " + DeathTestAbort(std::string("chdir(\"") + original_dir +
GetLastErrnoDescription()); "\") failed: " + GetLastErrnoDescription());
return EXIT_FAILURE; return EXIT_FAILURE;
} }
int fd_flags; int fd_flags;
// Set close_fd to be closed after spawn. // 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_(fd_flags = fcntl(close_fd, F_GETFD));
GTEST_DEATH_TEST_CHECK_SYSCALL_(fcntl(close_fd, F_SETFD, GTEST_DEATH_TEST_CHECK_SYSCALL_(
fd_flags | FD_CLOEXEC)); fcntl(close_fd, F_SETFD, fd_flags | FD_CLOEXEC));
struct inheritance inherit = {0}; struct inheritance inherit = {0};
// spawn is a system call. // spawn is a system call.
child_pid = spawn(args.argv[0], 0, nullptr, &inherit, args.argv, environ); 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_(fchdir(cwd_fd) != -1);
GTEST_DEATH_TEST_CHECK_SYSCALL_(close(cwd_fd)); GTEST_DEATH_TEST_CHECK_SYSCALL_(close(cwd_fd));
# else // GTEST_OS_QNX #else // GTEST_OS_QNX
# if GTEST_OS_LINUX #if GTEST_OS_LINUX
// When a SIGPROF signal is received while fork() or clone() are executing, // 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 // the process may hang. To avoid this, we ignore SIGPROF here and re-enable
// it after the call to fork()/clone() is complete. // 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)); memset(&ignore_sigprof_action, 0, sizeof(ignore_sigprof_action));
sigemptyset(&ignore_sigprof_action.sa_mask); sigemptyset(&ignore_sigprof_action.sa_mask);
ignore_sigprof_action.sa_handler = SIG_IGN; ignore_sigprof_action.sa_handler = SIG_IGN;
GTEST_DEATH_TEST_CHECK_SYSCALL_(sigaction( GTEST_DEATH_TEST_CHECK_SYSCALL_(
SIGPROF, &ignore_sigprof_action, &saved_sigprof_action)); sigaction(SIGPROF, &ignore_sigprof_action, &saved_sigprof_action));
# endif // GTEST_OS_LINUX #endif // GTEST_OS_LINUX
# if GTEST_HAS_CLONE #if GTEST_HAS_CLONE
const bool use_fork = GTEST_FLAG_GET(death_test_use_fork); const bool use_fork = GTEST_FLAG_GET(death_test_use_fork);
if (!use_fork) { if (!use_fork) {
@ -1373,7 +1353,7 @@ static pid_t ExecDeathTestSpawnChild(char* const* argv, int close_fd) {
const size_t kMaxStackAlignment = 64; const size_t kMaxStackAlignment = 64;
void* const stack_top = void* const stack_top =
static_cast<char*>(stack) + static_cast<char*>(stack) +
(stack_grows_down ? stack_size - kMaxStackAlignment : 0); (stack_grows_down ? stack_size - kMaxStackAlignment : 0);
GTEST_DEATH_TEST_CHECK_( GTEST_DEATH_TEST_CHECK_(
static_cast<size_t>(stack_size) > kMaxStackAlignment && static_cast<size_t>(stack_size) > kMaxStackAlignment &&
reinterpret_cast<uintptr_t>(stack_top) % kMaxStackAlignment == 0); 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); GTEST_DEATH_TEST_CHECK_(munmap(stack, stack_size) != -1);
} }
# else #else
const bool use_fork = true; const bool use_fork = true;
# endif // GTEST_HAS_CLONE #endif // GTEST_HAS_CLONE
if (use_fork && (child_pid = fork()) == 0) { if (use_fork && (child_pid = fork()) == 0) {
ExecDeathTestChildMain(&args); ExecDeathTestChildMain(&args);
_exit(0); _exit(0);
} }
# endif // GTEST_OS_QNX #endif // GTEST_OS_QNX
# if GTEST_OS_LINUX #if GTEST_OS_LINUX
GTEST_DEATH_TEST_CHECK_SYSCALL_( GTEST_DEATH_TEST_CHECK_SYSCALL_(
sigaction(SIGPROF, &saved_sigprof_action, nullptr)); sigaction(SIGPROF, &saved_sigprof_action, nullptr));
# endif // GTEST_OS_LINUX #endif // GTEST_OS_LINUX
GTEST_DEATH_TEST_CHECK_(child_pid != -1); GTEST_DEATH_TEST_CHECK_(child_pid != -1);
return child_pid; return child_pid;
@ -1450,7 +1430,7 @@ DeathTest::TestRole ExecDeathTest::AssumeRole() {
return OVERSEE_TEST; return OVERSEE_TEST;
} }
# endif // !GTEST_OS_WINDOWS #endif // !GTEST_OS_WINDOWS
// Creates a concrete DeathTest-derived class that depends on the // Creates a concrete DeathTest-derived class that depends on the
// --gtest_death_test_style flag, and sets the pointer pointed to // --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(); UnitTestImpl* const impl = GetUnitTestImpl();
const InternalRunDeathTestFlag* const flag = const InternalRunDeathTestFlag* const flag =
impl->internal_run_death_test_flag(); impl->internal_run_death_test_flag();
const int death_test_index = impl->current_test_info() const int death_test_index =
->increment_death_test_count(); impl->current_test_info()->increment_death_test_count();
if (flag != nullptr) { if (flag != nullptr) {
if (death_test_index > flag->index()) { if (death_test_index > flag->index()) {
DeathTest::set_last_death_test_message( DeathTest::set_last_death_test_message(
"Death test count (" + StreamableToString(death_test_index) "Death test count (" + StreamableToString(death_test_index) +
+ ") somehow exceeded expected maximum (" ") somehow exceeded expected maximum (" +
+ StreamableToString(flag->index()) + ")"); StreamableToString(flag->index()) + ")");
return false; 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" || if (GTEST_FLAG_GET(death_test_style) == "threadsafe" ||
GTEST_FLAG_GET(death_test_style) == "fast") { GTEST_FLAG_GET(death_test_style) == "fast") {
*test = new WindowsDeathTest(statement, std::move(matcher), file, line); *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" || if (GTEST_FLAG_GET(death_test_style) == "threadsafe" ||
GTEST_FLAG_GET(death_test_style) == "fast") { GTEST_FLAG_GET(death_test_style) == "fast") {
*test = new FuchsiaDeathTest(statement, std::move(matcher), file, line); *test = new FuchsiaDeathTest(statement, std::move(matcher), file, line);
} }
# else #else
if (GTEST_FLAG_GET(death_test_style) == "threadsafe") { if (GTEST_FLAG_GET(death_test_style) == "threadsafe") {
*test = new ExecDeathTest(statement, std::move(matcher), file, line); *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)); *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. else { // NOLINT - this is more readable than unbalanced brackets inside #if.
DeathTest::set_last_death_test_message("Unknown death test style \"" + DeathTest::set_last_death_test_message("Unknown death test style \"" +
@ -1517,16 +1497,16 @@ bool DefaultDeathTestFactory::Create(const char* statement,
return true; return true;
} }
# if GTEST_OS_WINDOWS #if GTEST_OS_WINDOWS
// Recreates the pipe and event handles from the provided parameters, // Recreates the pipe and event handles from the provided parameters,
// signals the event, and returns a file descriptor wrapped around the pipe // signals the event, and returns a file descriptor wrapped around the pipe
// handle. This function is called in the child process only. // handle. This function is called in the child process only.
static int GetStatusFileDescriptor(unsigned int parent_process_id, static int GetStatusFileDescriptor(unsigned int parent_process_id,
size_t write_handle_as_size_t, size_t write_handle_as_size_t,
size_t event_handle_as_size_t) { size_t event_handle_as_size_t) {
AutoHandle parent_process_handle(::OpenProcess(PROCESS_DUP_HANDLE, AutoHandle parent_process_handle(::OpenProcess(PROCESS_DUP_HANDLE,
FALSE, // Non-inheritable. FALSE, // Non-inheritable.
parent_process_id)); parent_process_id));
if (parent_process_handle.Get() == INVALID_HANDLE_VALUE) { if (parent_process_handle.Get() == INVALID_HANDLE_VALUE) {
DeathTestAbort("Unable to open parent process " + DeathTestAbort("Unable to open parent process " +
StreamableToString(parent_process_id)); StreamableToString(parent_process_id));
@ -1534,8 +1514,7 @@ static int GetStatusFileDescriptor(unsigned int parent_process_id,
GTEST_CHECK_(sizeof(HANDLE) <= sizeof(size_t)); GTEST_CHECK_(sizeof(HANDLE) <= sizeof(size_t));
const HANDLE write_handle = const HANDLE write_handle = reinterpret_cast<HANDLE>(write_handle_as_size_t);
reinterpret_cast<HANDLE>(write_handle_as_size_t);
HANDLE dup_write_handle; HANDLE dup_write_handle;
// The newly initialized handle is accessible only in the parent // 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; HANDLE dup_event_handle;
if (!::DuplicateHandle(parent_process_handle.Get(), event_handle, if (!::DuplicateHandle(parent_process_handle.Get(), event_handle,
::GetCurrentProcess(), &dup_event_handle, ::GetCurrentProcess(), &dup_event_handle, 0x0, FALSE,
0x0,
FALSE,
DUPLICATE_SAME_ACCESS)) { DUPLICATE_SAME_ACCESS)) {
DeathTestAbort("Unable to duplicate the event handle " + DeathTestAbort("Unable to duplicate the event handle " +
StreamableToString(event_handle_as_size_t) + StreamableToString(event_handle_as_size_t) +
@ -1581,7 +1558,7 @@ static int GetStatusFileDescriptor(unsigned int parent_process_id,
return write_fd; return write_fd;
} }
# endif // GTEST_OS_WINDOWS #endif // GTEST_OS_WINDOWS
// Returns a newly created InternalRunDeathTestFlag object with fields // Returns a newly created InternalRunDeathTestFlag object with fields
// initialized from the GTEST_FLAG(internal_run_death_test) flag if // 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); SplitString(GTEST_FLAG_GET(internal_run_death_test), '|', &fields);
int write_fd = -1; int write_fd = -1;
# if GTEST_OS_WINDOWS #if GTEST_OS_WINDOWS
unsigned int parent_process_id = 0; unsigned int parent_process_id = 0;
size_t write_handle_as_size_t = 0; size_t write_handle_as_size_t = 0;
size_t event_handle_as_size_t = 0; size_t event_handle_as_size_t = 0;
if (fields.size() != 6 if (fields.size() != 6 || !ParseNaturalNumber(fields[1], &line) ||
|| !ParseNaturalNumber(fields[1], &line) !ParseNaturalNumber(fields[2], &index) ||
|| !ParseNaturalNumber(fields[2], &index) !ParseNaturalNumber(fields[3], &parent_process_id) ||
|| !ParseNaturalNumber(fields[3], &parent_process_id) !ParseNaturalNumber(fields[4], &write_handle_as_size_t) ||
|| !ParseNaturalNumber(fields[4], &write_handle_as_size_t) !ParseNaturalNumber(fields[5], &event_handle_as_size_t)) {
|| !ParseNaturalNumber(fields[5], &event_handle_as_size_t)) {
DeathTestAbort("Bad --gtest_internal_run_death_test flag: " + DeathTestAbort("Bad --gtest_internal_run_death_test flag: " +
GTEST_FLAG_GET(internal_run_death_test)); GTEST_FLAG_GET(internal_run_death_test));
} }
write_fd = GetStatusFileDescriptor(parent_process_id, write_fd = GetStatusFileDescriptor(parent_process_id, write_handle_as_size_t,
write_handle_as_size_t,
event_handle_as_size_t); event_handle_as_size_t);
# elif GTEST_OS_FUCHSIA #elif GTEST_OS_FUCHSIA
if (fields.size() != 3 if (fields.size() != 3 || !ParseNaturalNumber(fields[1], &line) ||
|| !ParseNaturalNumber(fields[1], &line) !ParseNaturalNumber(fields[2], &index)) {
|| !ParseNaturalNumber(fields[2], &index)) {
DeathTestAbort("Bad --gtest_internal_run_death_test flag: " + DeathTestAbort("Bad --gtest_internal_run_death_test flag: " +
GTEST_FLAG_GET(internal_run_death_test)); GTEST_FLAG_GET(internal_run_death_test));
} }
# else #else
if (fields.size() != 4 if (fields.size() != 4 || !ParseNaturalNumber(fields[1], &line) ||
|| !ParseNaturalNumber(fields[1], &line) !ParseNaturalNumber(fields[2], &index) ||
|| !ParseNaturalNumber(fields[2], &index) !ParseNaturalNumber(fields[3], &write_fd)) {
|| !ParseNaturalNumber(fields[3], &write_fd)) {
DeathTestAbort("Bad --gtest_internal_run_death_test flag: " + DeathTestAbort("Bad --gtest_internal_run_death_test flag: " +
GTEST_FLAG_GET(internal_run_death_test)); GTEST_FLAG_GET(internal_run_death_test));
} }
# endif // GTEST_OS_WINDOWS #endif // GTEST_OS_WINDOWS
return new InternalRunDeathTestFlag(fields[0], line, index, write_fd); return new InternalRunDeathTestFlag(fields[0], line, index, write_fd);
} }

View File

@ -30,29 +30,31 @@
#include "gtest/internal/gtest-filepath.h" #include "gtest/internal/gtest-filepath.h"
#include <stdlib.h> #include <stdlib.h>
#include "gtest/internal/gtest-port.h"
#include "gtest/gtest-message.h" #include "gtest/gtest-message.h"
#include "gtest/internal/gtest-port.h"
#if GTEST_OS_WINDOWS_MOBILE #if GTEST_OS_WINDOWS_MOBILE
# include <windows.h> #include <windows.h>
#elif GTEST_OS_WINDOWS #elif GTEST_OS_WINDOWS
# include <direct.h> #include <direct.h>
# include <io.h> #include <io.h>
#else #else
# include <limits.h> #include <limits.h>
# include <climits> // Some Linux distributions define PATH_MAX here.
#endif // GTEST_OS_WINDOWS_MOBILE #include <climits> // Some Linux distributions define PATH_MAX here.
#endif // GTEST_OS_WINDOWS_MOBILE
#include "gtest/internal/gtest-string.h" #include "gtest/internal/gtest-string.h"
#if GTEST_OS_WINDOWS #if GTEST_OS_WINDOWS
# define GTEST_PATH_MAX_ _MAX_PATH #define GTEST_PATH_MAX_ _MAX_PATH
#elif defined(PATH_MAX) #elif defined(PATH_MAX)
# define GTEST_PATH_MAX_ PATH_MAX #define GTEST_PATH_MAX_ PATH_MAX
#elif defined(_XOPEN_PATH_MAX) #elif defined(_XOPEN_PATH_MAX)
# define GTEST_PATH_MAX_ _XOPEN_PATH_MAX #define GTEST_PATH_MAX_ _XOPEN_PATH_MAX
#else #else
# define GTEST_PATH_MAX_ _POSIX_PATH_MAX #define GTEST_PATH_MAX_ _POSIX_PATH_MAX
#endif // GTEST_OS_WINDOWS #endif // GTEST_OS_WINDOWS
namespace testing { namespace testing {
@ -66,16 +68,16 @@ namespace internal {
const char kPathSeparator = '\\'; const char kPathSeparator = '\\';
const char kAlternatePathSeparator = '/'; const char kAlternatePathSeparator = '/';
const char kAlternatePathSeparatorString[] = "/"; 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 // Windows CE doesn't have a current directory. You should not use
// the current directory in tests on Windows CE, but this at least // the current directory in tests on Windows CE, but this at least
// provides a reasonable fallback. // provides a reasonable fallback.
const char kCurrentDirectoryString[] = "\\"; const char kCurrentDirectoryString[] = "\\";
// Windows CE doesn't define INVALID_FILE_ATTRIBUTES // Windows CE doesn't define INVALID_FILE_ATTRIBUTES
const DWORD kInvalidFileAttributes = 0xffffffff; const DWORD kInvalidFileAttributes = 0xffffffff;
# else #else
const char kCurrentDirectoryString[] = ".\\"; const char kCurrentDirectoryString[] = ".\\";
# endif // GTEST_OS_WINDOWS_MOBILE #endif // GTEST_OS_WINDOWS_MOBILE
#else #else
const char kPathSeparator = '/'; const char kPathSeparator = '/';
const char kCurrentDirectoryString[] = "./"; const char kCurrentDirectoryString[] = "./";
@ -99,17 +101,17 @@ FilePath FilePath::GetCurrentDir() {
// something reasonable. // something reasonable.
return FilePath(kCurrentDirectoryString); return FilePath(kCurrentDirectoryString);
#elif GTEST_OS_WINDOWS #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); return FilePath(_getcwd(cwd, sizeof(cwd)) == nullptr ? "" : cwd);
#else #else
char cwd[GTEST_PATH_MAX_ + 1] = { '\0' }; char cwd[GTEST_PATH_MAX_ + 1] = {'\0'};
char* result = getcwd(cwd, sizeof(cwd)); 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 // getcwd will likely fail in NaCl due to the sandbox, so return something
// reasonable. The user may have provided a shim implementation for getcwd, // reasonable. The user may have provided a shim implementation for getcwd,
// however, so fallback only when failure is detected. // however, so fallback only when failure is detected.
return FilePath(result == nullptr ? kCurrentDirectoryString : cwd); return FilePath(result == nullptr ? kCurrentDirectoryString : cwd);
# endif // GTEST_OS_NACL #endif // GTEST_OS_NACL
return FilePath(result == nullptr ? "" : cwd); return FilePath(result == nullptr ? "" : cwd);
#endif // GTEST_OS_WINDOWS_MOBILE #endif // GTEST_OS_WINDOWS_MOBILE
} }
@ -121,8 +123,8 @@ FilePath FilePath::GetCurrentDir() {
FilePath FilePath::RemoveExtension(const char* extension) const { FilePath FilePath::RemoveExtension(const char* extension) const {
const std::string dot_extension = std::string(".") + extension; const std::string dot_extension = std::string(".") + extension;
if (String::EndsWithCaseInsensitive(pathname_, dot_extension)) { if (String::EndsWithCaseInsensitive(pathname_, dot_extension)) {
return FilePath(pathname_.substr( return FilePath(
0, pathname_.length() - dot_extension.length())); pathname_.substr(0, pathname_.length() - dot_extension.length()));
} }
return *this; return *this;
} }
@ -178,15 +180,14 @@ FilePath FilePath::RemoveFileName() const {
// than zero (e.g., 12), returns "dir/test_12.xml". // than zero (e.g., 12), returns "dir/test_12.xml".
// On Windows platform, uses \ as the separator rather than /. // On Windows platform, uses \ as the separator rather than /.
FilePath FilePath::MakeFileName(const FilePath& directory, FilePath FilePath::MakeFileName(const FilePath& directory,
const FilePath& base_name, const FilePath& base_name, int number,
int number,
const char* extension) { const char* extension) {
std::string file; std::string file;
if (number == 0) { if (number == 0) {
file = base_name.string() + "." + extension; file = base_name.string() + "." + extension;
} else { } else {
file = base_name.string() + "_" + StreamableToString(number) file =
+ "." + extension; base_name.string() + "_" + StreamableToString(number) + "." + extension;
} }
return ConcatPaths(directory, FilePath(file)); return ConcatPaths(directory, FilePath(file));
} }
@ -195,8 +196,7 @@ FilePath FilePath::MakeFileName(const FilePath& directory,
// On Windows, uses \ as the separator rather than /. // On Windows, uses \ as the separator rather than /.
FilePath FilePath::ConcatPaths(const FilePath& directory, FilePath FilePath::ConcatPaths(const FilePath& directory,
const FilePath& relative_path) { const FilePath& relative_path) {
if (directory.IsEmpty()) if (directory.IsEmpty()) return relative_path;
return relative_path;
const FilePath dir(directory.RemoveTrailingPathSeparator()); const FilePath dir(directory.RemoveTrailingPathSeparator());
return FilePath(dir.string() + kPathSeparator + relative_path.string()); return FilePath(dir.string() + kPathSeparator + relative_path.string());
} }
@ -207,7 +207,7 @@ bool FilePath::FileOrDirectoryExists() const {
#if GTEST_OS_WINDOWS_MOBILE #if GTEST_OS_WINDOWS_MOBILE
LPCWSTR unicode = String::AnsiToUtf16(pathname_.c_str()); LPCWSTR unicode = String::AnsiToUtf16(pathname_.c_str());
const DWORD attributes = GetFileAttributes(unicode); const DWORD attributes = GetFileAttributes(unicode);
delete [] unicode; delete[] unicode;
return attributes != kInvalidFileAttributes; return attributes != kInvalidFileAttributes;
#else #else
posix::StatStruct file_stat{}; posix::StatStruct file_stat{};
@ -222,8 +222,8 @@ bool FilePath::DirectoryExists() const {
#if GTEST_OS_WINDOWS #if GTEST_OS_WINDOWS
// Don't strip off trailing separator if path is a root directory on // Don't strip off trailing separator if path is a root directory on
// Windows (like "C:\\"). // Windows (like "C:\\").
const FilePath& path(IsRootDirectory() ? *this : const FilePath& path(IsRootDirectory() ? *this
RemoveTrailingPathSeparator()); : RemoveTrailingPathSeparator());
#else #else
const FilePath& path(*this); const FilePath& path(*this);
#endif #endif
@ -231,15 +231,15 @@ bool FilePath::DirectoryExists() const {
#if GTEST_OS_WINDOWS_MOBILE #if GTEST_OS_WINDOWS_MOBILE
LPCWSTR unicode = String::AnsiToUtf16(path.c_str()); LPCWSTR unicode = String::AnsiToUtf16(path.c_str());
const DWORD attributes = GetFileAttributes(unicode); const DWORD attributes = GetFileAttributes(unicode);
delete [] unicode; delete[] unicode;
if ((attributes != kInvalidFileAttributes) && if ((attributes != kInvalidFileAttributes) &&
(attributes & FILE_ATTRIBUTE_DIRECTORY)) { (attributes & FILE_ATTRIBUTE_DIRECTORY)) {
result = true; result = true;
} }
#else #else
posix::StatStruct file_stat{}; posix::StatStruct file_stat{};
result = posix::Stat(path.c_str(), &file_stat) == 0 && result =
posix::IsDir(file_stat); posix::Stat(path.c_str(), &file_stat) == 0 && posix::IsDir(file_stat);
#endif // GTEST_OS_WINDOWS_MOBILE #endif // GTEST_OS_WINDOWS_MOBILE
return result; return result;
@ -260,10 +260,9 @@ bool FilePath::IsAbsolutePath() const {
const char* const name = pathname_.c_str(); const char* const name = pathname_.c_str();
#if GTEST_OS_WINDOWS #if GTEST_OS_WINDOWS
return pathname_.length() >= 3 && return pathname_.length() >= 3 &&
((name[0] >= 'a' && name[0] <= 'z') || ((name[0] >= 'a' && name[0] <= 'z') ||
(name[0] >= 'A' && name[0] <= 'Z')) && (name[0] >= 'A' && name[0] <= 'Z')) &&
name[1] == ':' && name[1] == ':' && IsPathSeparator(name[2]);
IsPathSeparator(name[2]);
#else #else
return IsPathSeparator(name[0]); return IsPathSeparator(name[0]);
#endif #endif
@ -321,7 +320,7 @@ bool FilePath::CreateFolder() const {
FilePath removed_sep(this->RemoveTrailingPathSeparator()); FilePath removed_sep(this->RemoveTrailingPathSeparator());
LPCWSTR unicode = String::AnsiToUtf16(removed_sep.c_str()); LPCWSTR unicode = String::AnsiToUtf16(removed_sep.c_str());
int result = CreateDirectory(unicode, nullptr) ? 0 : -1; int result = CreateDirectory(unicode, nullptr) ? 0 : -1;
delete [] unicode; delete[] unicode;
#elif GTEST_OS_WINDOWS #elif GTEST_OS_WINDOWS
int result = _mkdir(pathname_.c_str()); int result = _mkdir(pathname_.c_str());
#elif GTEST_OS_ESP8266 || GTEST_OS_XTENSA #elif GTEST_OS_ESP8266 || GTEST_OS_XTENSA
@ -341,9 +340,8 @@ bool FilePath::CreateFolder() const {
// name, otherwise return the name string unmodified. // name, otherwise return the name string unmodified.
// On Windows platform, uses \ as the separator, other platforms use /. // On Windows platform, uses \ as the separator, other platforms use /.
FilePath FilePath::RemoveTrailingPathSeparator() const { FilePath FilePath::RemoveTrailingPathSeparator() const {
return IsDirectory() return IsDirectory() ? FilePath(pathname_.substr(0, pathname_.length() - 1))
? FilePath(pathname_.substr(0, pathname_.length() - 1)) : *this;
: *this;
} }
// Removes any redundant separators that might be in the pathname. // Removes any redundant separators that might be in the pathname.

View File

@ -35,7 +35,7 @@
#define GOOGLETEST_SRC_GTEST_INTERNAL_INL_H_ #define GOOGLETEST_SRC_GTEST_INTERNAL_INL_H_
#ifndef _WIN32_WCE #ifndef _WIN32_WCE
# include <errno.h> #include <errno.h>
#endif // !_WIN32_WCE #endif // !_WIN32_WCE
#include <stddef.h> #include <stddef.h>
#include <stdlib.h> // For strtoll/_strtoul64/malloc/free. #include <stdlib.h> // For strtoll/_strtoul64/malloc/free.
@ -50,16 +50,16 @@
#include "gtest/internal/gtest-port.h" #include "gtest/internal/gtest-port.h"
#if GTEST_CAN_STREAM_RESULTS_ #if GTEST_CAN_STREAM_RESULTS_
# include <arpa/inet.h> // NOLINT #include <arpa/inet.h> // NOLINT
# include <netdb.h> // NOLINT #include <netdb.h> // NOLINT
#endif #endif
#if GTEST_OS_WINDOWS #if GTEST_OS_WINDOWS
# include <windows.h> // NOLINT #include <windows.h> // NOLINT
#endif // GTEST_OS_WINDOWS #endif // GTEST_OS_WINDOWS
#include "gtest/gtest.h"
#include "gtest/gtest-spi.h" #include "gtest/gtest-spi.h"
#include "gtest/gtest.h"
GTEST_DISABLE_MSC_WARNINGS_PUSH_(4251 \ GTEST_DISABLE_MSC_WARNINGS_PUSH_(4251 \
/* class A needs to have dll-interface to be used by clients of class B */) /* 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 // Returns a random seed in range [1, kMaxRandomSeed] based on the
// given --gtest_random_seed flag value. // given --gtest_random_seed flag value.
inline int GetRandomSeedFromFlag(int32_t random_seed_flag) { inline int GetRandomSeedFromFlag(int32_t random_seed_flag) {
const unsigned int raw_seed = (random_seed_flag == 0) ? const unsigned int raw_seed =
static_cast<unsigned int>(GetTimeInMillis()) : (random_seed_flag == 0) ? static_cast<unsigned int>(GetTimeInMillis())
static_cast<unsigned int>(random_seed_flag); : static_cast<unsigned int>(random_seed_flag);
// Normalizes the actual seed to range [1, kMaxRandomSeed] such that // Normalizes the actual seed to range [1, kMaxRandomSeed] such that
// it's easy to type. // it's easy to type.
const int normalized_seed = const int normalized_seed =
static_cast<int>((raw_seed - 1U) % static_cast<int>((raw_seed - 1U) %
static_cast<unsigned int>(kMaxRandomSeed)) + 1; static_cast<unsigned int>(kMaxRandomSeed)) +
1;
return normalized_seed; 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 // 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 // is some arbitrary but unique non-negative integer assigned to each test
// method. Assumes that 0 <= shard_index < total_shards. // method. Assumes that 0 <= shard_index < total_shards.
GTEST_API_ bool ShouldRunTestOnShard( GTEST_API_ bool ShouldRunTestOnShard(int total_shards, int shard_index,
int total_shards, int shard_index, int test_id); int test_id);
// STL container utilities. // STL container utilities.
@ -274,8 +275,7 @@ inline int CountIf(const Container& c, Predicate predicate) {
// Solaris has a non-standard signature. // Solaris has a non-standard signature.
int count = 0; int count = 0;
for (auto it = c.begin(); it != c.end(); ++it) { for (auto it = c.begin(); it != c.end(); ++it) {
if (predicate(*it)) if (predicate(*it)) ++count;
++count;
} }
return count; return count;
} }
@ -459,7 +459,7 @@ struct TraceInfo {
// This is the default global test part result reporter used in UnitTestImpl. // This is the default global test part result reporter used in UnitTestImpl.
// This class should only be used by UnitTestImpl. // This class should only be used by UnitTestImpl.
class DefaultGlobalTestPartResultReporter class DefaultGlobalTestPartResultReporter
: public TestPartResultReporterInterface { : public TestPartResultReporterInterface {
public: public:
explicit DefaultGlobalTestPartResultReporter(UnitTestImpl* unit_test); explicit DefaultGlobalTestPartResultReporter(UnitTestImpl* unit_test);
// Implements the TestPartResultReporterInterface. Reports the test part // Implements the TestPartResultReporterInterface. Reports the test part
@ -728,9 +728,7 @@ class GTEST_API_ UnitTestImpl {
} }
// Clears the results of ad-hoc test assertions. // Clears the results of ad-hoc test assertions.
void ClearAdHocTestResult() { void ClearAdHocTestResult() { ad_hoc_test_result_.Clear(); }
ad_hoc_test_result_.Clear();
}
// Adds a TestProperty to the current TestResult object when invoked in a // 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 // 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. // updated.
void RecordProperty(const TestProperty& test_property); void RecordProperty(const TestProperty& test_property);
enum ReactionToSharding { enum ReactionToSharding { HONOR_SHARDING_PROTOCOL, IGNORE_SHARDING_PROTOCOL };
HONOR_SHARDING_PROTOCOL,
IGNORE_SHARDING_PROTOCOL
};
// Matches the full name of each test against the user-specified // Matches the full name of each test against the user-specified
// filter to decide whether the test should run, then records the // 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 AtomMatchesChar(bool escaped, char pattern, char ch);
GTEST_API_ bool ValidateRegex(const char* regex); GTEST_API_ bool ValidateRegex(const char* regex);
GTEST_API_ bool MatchRegexAtHead(const char* regex, const char* str); GTEST_API_ bool MatchRegexAtHead(const char* regex, const char* str);
GTEST_API_ bool MatchRepetitionAndRegexAtHead( GTEST_API_ bool MatchRepetitionAndRegexAtHead(bool escaped, char ch,
bool escaped, char ch, char repeat, const char* regex, const char* str); char repeat, const char* regex,
const char* str);
GTEST_API_ bool MatchRegexAnywhere(const char* regex, const char* str); GTEST_API_ bool MatchRegexAnywhere(const char* regex, const char* str);
#endif // GTEST_USES_SIMPLE_RE #endif // GTEST_USES_SIMPLE_RE
@ -1073,8 +1069,7 @@ class StreamingListener : public EmptyTestEventListener {
} }
~SocketWriter() override { ~SocketWriter() override {
if (sockfd_ != -1) if (sockfd_ != -1) CloseConnection();
CloseConnection();
} }
// Sends a string to the socket. // Sends a string to the socket.
@ -1084,9 +1079,8 @@ class StreamingListener : public EmptyTestEventListener {
const auto len = static_cast<size_t>(message.length()); const auto len = static_cast<size_t>(message.length());
if (write(sockfd_, message.c_str(), len) != static_cast<ssize_t>(len)) { if (write(sockfd_, message.c_str(), len) != static_cast<ssize_t>(len)) {
GTEST_LOG_(WARNING) GTEST_LOG_(WARNING) << "stream_result_to: failed to stream to "
<< "stream_result_to: failed to stream to " << host_name_ << ":" << port_num_;
<< host_name_ << ":" << port_num_;
} }
} }
@ -1119,7 +1113,9 @@ class StreamingListener : public EmptyTestEventListener {
} }
explicit StreamingListener(AbstractSocketWriter* socket_writer) explicit StreamingListener(AbstractSocketWriter* socket_writer)
: socket_writer_(socket_writer) { Start(); } : socket_writer_(socket_writer) {
Start();
}
void OnTestProgramStart(const UnitTest& /* unit_test */) override { void OnTestProgramStart(const UnitTest& /* unit_test */) override {
SendLn("event=TestProgramStart"); SendLn("event=TestProgramStart");
@ -1142,9 +1138,9 @@ class StreamingListener : public EmptyTestEventListener {
void OnTestIterationEnd(const UnitTest& unit_test, void OnTestIterationEnd(const UnitTest& unit_test,
int /* iteration */) override { int /* iteration */) override {
SendLn("event=TestIterationEnd&passed=" + SendLn("event=TestIterationEnd&passed=" + FormatBool(unit_test.Passed()) +
FormatBool(unit_test.Passed()) + "&elapsed_time=" + "&elapsed_time=" + StreamableToString(unit_test.elapsed_time()) +
StreamableToString(unit_test.elapsed_time()) + "ms"); "ms");
} }
// Note that "event=TestCaseStart" is a wire format and has to remain // 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 { void OnTestEnd(const TestInfo& test_info) override {
SendLn("event=TestEnd&passed=" + SendLn("event=TestEnd&passed=" +
FormatBool((test_info.result())->Passed()) + FormatBool((test_info.result())->Passed()) + "&elapsed_time=" +
"&elapsed_time=" +
StreamableToString((test_info.result())->elapsed_time()) + "ms"); StreamableToString((test_info.result())->elapsed_time()) + "ms");
} }

View File

@ -32,12 +32,13 @@
// This file implements just enough of the matcher interface to allow // This file implements just enough of the matcher interface to allow
// EXPECT_DEATH and friends to accept a matcher argument. // 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 "gtest/gtest-matchers.h"
#include <string> #include <string>
#include "gtest/internal/gtest-internal.h"
#include "gtest/internal/gtest-port.h"
namespace testing { namespace testing {
// Constructs a matcher that matches a const std::string& whose value is // Constructs a matcher that matches a const std::string& whose value is

View File

@ -27,61 +27,62 @@
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include "gtest/internal/gtest-port.h" #include "gtest/internal/gtest-port.h"
#include <limits.h> #include <limits.h>
#include <stdio.h> #include <stdio.h>
#include <stdlib.h> #include <stdlib.h>
#include <string.h> #include <string.h>
#include <cstdint> #include <cstdint>
#include <fstream> #include <fstream>
#include <memory> #include <memory>
#if GTEST_OS_WINDOWS #if GTEST_OS_WINDOWS
# include <windows.h> #include <io.h>
# include <io.h> #include <sys/stat.h>
# include <sys/stat.h> #include <windows.h>
# include <map> // Used in ThreadLocal.
# ifdef _MSC_VER #include <map> // Used in ThreadLocal.
# include <crtdbg.h> #ifdef _MSC_VER
# endif // _MSC_VER #include <crtdbg.h>
#endif // _MSC_VER
#else #else
# include <unistd.h> #include <unistd.h>
#endif // GTEST_OS_WINDOWS #endif // GTEST_OS_WINDOWS
#if GTEST_OS_MAC #if GTEST_OS_MAC
# include <mach/mach_init.h> #include <mach/mach_init.h>
# include <mach/task.h> #include <mach/task.h>
# include <mach/vm_map.h> #include <mach/vm_map.h>
#endif // GTEST_OS_MAC #endif // GTEST_OS_MAC
#if GTEST_OS_DRAGONFLY || GTEST_OS_FREEBSD || GTEST_OS_GNU_KFREEBSD || \ #if GTEST_OS_DRAGONFLY || GTEST_OS_FREEBSD || GTEST_OS_GNU_KFREEBSD || \
GTEST_OS_NETBSD || GTEST_OS_OPENBSD GTEST_OS_NETBSD || GTEST_OS_OPENBSD
# include <sys/sysctl.h> #include <sys/sysctl.h>
# if GTEST_OS_DRAGONFLY || GTEST_OS_FREEBSD || GTEST_OS_GNU_KFREEBSD #if GTEST_OS_DRAGONFLY || GTEST_OS_FREEBSD || GTEST_OS_GNU_KFREEBSD
# include <sys/user.h> #include <sys/user.h>
# endif #endif
#endif #endif
#if GTEST_OS_QNX #if GTEST_OS_QNX
# include <devctl.h> #include <devctl.h>
# include <fcntl.h> #include <fcntl.h>
# include <sys/procfs.h> #include <sys/procfs.h>
#endif // GTEST_OS_QNX #endif // GTEST_OS_QNX
#if GTEST_OS_AIX #if GTEST_OS_AIX
# include <procinfo.h> #include <procinfo.h>
# include <sys/types.h> #include <sys/types.h>
#endif // GTEST_OS_AIX #endif // GTEST_OS_AIX
#if GTEST_OS_FUCHSIA #if GTEST_OS_FUCHSIA
# include <zircon/process.h> #include <zircon/process.h>
# include <zircon/syscalls.h> #include <zircon/syscalls.h>
#endif // GTEST_OS_FUCHSIA #endif // GTEST_OS_FUCHSIA
#include "gtest/gtest-spi.h"
#include "gtest/gtest-message.h" #include "gtest/gtest-message.h"
#include "gtest/gtest-spi.h"
#include "gtest/internal/gtest-internal.h" #include "gtest/internal/gtest-internal.h"
#include "gtest/internal/gtest-string.h" #include "gtest/internal/gtest-string.h"
#include "src/gtest-internal-inl.h" #include "src/gtest-internal-inl.h"
@ -131,8 +132,7 @@ size_t GetThreadCount() {
if (status == KERN_SUCCESS) { if (status == KERN_SUCCESS) {
// task_threads allocates resources in thread_list and we need to free them // task_threads allocates resources in thread_list and we need to free them
// to avoid leaks. // to avoid leaks.
vm_deallocate(task, vm_deallocate(task, reinterpret_cast<vm_address_t>(thread_list),
reinterpret_cast<vm_address_t>(thread_list),
sizeof(thread_t) * thread_count); sizeof(thread_t) * thread_count);
return static_cast<size_t>(thread_count); return static_cast<size_t>(thread_count);
} else { } else {
@ -141,7 +141,7 @@ size_t GetThreadCount() {
} }
#elif GTEST_OS_DRAGONFLY || GTEST_OS_FREEBSD || GTEST_OS_GNU_KFREEBSD || \ #elif GTEST_OS_DRAGONFLY || GTEST_OS_FREEBSD || GTEST_OS_GNU_KFREEBSD || \
GTEST_OS_NETBSD GTEST_OS_NETBSD
#if GTEST_OS_NETBSD #if GTEST_OS_NETBSD
#undef KERN_PROC #undef KERN_PROC
@ -184,12 +184,12 @@ size_t GetThreadCount() {
// we cannot detect it. // we cannot detect it.
size_t GetThreadCount() { size_t GetThreadCount() {
int mib[] = { int mib[] = {
CTL_KERN, CTL_KERN,
KERN_PROC, KERN_PROC,
KERN_PROC_PID | KERN_PROC_SHOW_THREADS, KERN_PROC_PID | KERN_PROC_SHOW_THREADS,
getpid(), getpid(),
sizeof(struct kinfo_proc), sizeof(struct kinfo_proc),
0, 0,
}; };
u_int miblen = sizeof(mib) / sizeof(mib[0]); u_int miblen = sizeof(mib) / sizeof(mib[0]);
@ -210,8 +210,7 @@ size_t GetThreadCount() {
// exclude empty members // exclude empty members
size_t nthreads = 0; size_t nthreads = 0;
for (size_t i = 0; i < size / static_cast<size_t>(mib[4]); i++) { for (size_t i = 0; i < size / static_cast<size_t>(mib[4]); i++) {
if (info[i].p_tid != -1) if (info[i].p_tid != -1) nthreads++;
nthreads++;
} }
return nthreads; return nthreads;
} }
@ -254,13 +253,9 @@ size_t GetThreadCount() {
size_t GetThreadCount() { size_t GetThreadCount() {
int dummy_buffer; int dummy_buffer;
size_t avail; size_t avail;
zx_status_t status = zx_object_get_info( zx_status_t status =
zx_process_self(), zx_object_get_info(zx_process_self(), ZX_INFO_PROCESS_THREADS,
ZX_INFO_PROCESS_THREADS, &dummy_buffer, 0, nullptr, &avail);
&dummy_buffer,
0,
nullptr,
&avail);
if (status == ZX_OK) { if (status == ZX_OK) {
return avail; return avail;
} else { } else {
@ -280,23 +275,15 @@ size_t GetThreadCount() {
#if GTEST_IS_THREADSAFE && GTEST_OS_WINDOWS #if GTEST_IS_THREADSAFE && GTEST_OS_WINDOWS
AutoHandle::AutoHandle() AutoHandle::AutoHandle() : handle_(INVALID_HANDLE_VALUE) {}
: handle_(INVALID_HANDLE_VALUE) {}
AutoHandle::AutoHandle(Handle handle) AutoHandle::AutoHandle(Handle handle) : handle_(handle) {}
: handle_(handle) {}
AutoHandle::~AutoHandle() { AutoHandle::~AutoHandle() { Reset(); }
Reset();
}
AutoHandle::Handle AutoHandle::Get() const { AutoHandle::Handle AutoHandle::Get() const { return handle_; }
return handle_;
}
void AutoHandle::Reset() { void AutoHandle::Reset() { Reset(INVALID_HANDLE_VALUE); }
Reset(INVALID_HANDLE_VALUE);
}
void AutoHandle::Reset(HANDLE handle) { void AutoHandle::Reset(HANDLE handle) {
// Resetting with the same handle we already own is invalid. // Resetting with the same handle we already own is invalid.
@ -308,7 +295,7 @@ void AutoHandle::Reset(HANDLE handle) {
} else { } else {
GTEST_CHECK_(!IsCloseable()) GTEST_CHECK_(!IsCloseable())
<< "Resetting a valid handle to itself is likely a programmer error " << "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; // MemoryIsNotDeallocated memory_is_not_deallocated;
// critical_section_ = new CRITICAL_SECTION; // critical_section_ = new CRITICAL_SECTION;
// //
class MemoryIsNotDeallocated class MemoryIsNotDeallocated {
{
public: public:
MemoryIsNotDeallocated() : old_crtdbg_flag_(0) { MemoryIsNotDeallocated() : old_crtdbg_flag_(0) {
old_crtdbg_flag_ = _CrtSetDbgFlag(_CRTDBG_REPORT_FLAG); old_crtdbg_flag_ = _CrtSetDbgFlag(_CRTDBG_REPORT_FLAG);
@ -414,15 +400,13 @@ void Mutex::ThreadSafeLazyInit() {
::InitializeCriticalSection(critical_section_); ::InitializeCriticalSection(critical_section_);
// Updates the critical_section_init_phase_ to 2 to signal // Updates the critical_section_init_phase_ to 2 to signal
// initialization complete. // initialization complete.
GTEST_CHECK_(::InterlockedCompareExchange( GTEST_CHECK_(::InterlockedCompareExchange(&critical_section_init_phase_,
&critical_section_init_phase_, 2L, 1L) == 2L, 1L) == 1L);
1L);
break; break;
case 1: case 1:
// Somebody else is already initializing the mutex; spin until they // Somebody else is already initializing the mutex; spin until they
// are done. // are done.
while (::InterlockedCompareExchange(&critical_section_init_phase_, while (::InterlockedCompareExchange(&critical_section_init_phase_, 2L,
2L,
2L) != 2L) { 2L) != 2L) {
// Possibly yields the rest of the thread's time slice to other // Possibly yields the rest of the thread's time slice to other
// threads. // threads.
@ -467,9 +451,7 @@ class ThreadWithParamSupport : public ThreadWithParamBase {
private: private:
struct ThreadMainParam { struct ThreadMainParam {
ThreadMainParam(Runnable* runnable, Notification* thread_can_start) ThreadMainParam(Runnable* runnable, Notification* thread_can_start)
: runnable_(runnable), : runnable_(runnable), thread_can_start_(thread_can_start) {}
thread_can_start_(thread_can_start) {
}
std::unique_ptr<Runnable> runnable_; std::unique_ptr<Runnable> runnable_;
// Does not own. // Does not own.
Notification* thread_can_start_; Notification* thread_can_start_;
@ -492,15 +474,12 @@ class ThreadWithParamSupport : public ThreadWithParamBase {
} // namespace } // namespace
ThreadWithParamBase::ThreadWithParamBase(Runnable *runnable, ThreadWithParamBase::ThreadWithParamBase(Runnable* runnable,
Notification* thread_can_start) Notification* thread_can_start)
: thread_(ThreadWithParamSupport::CreateThread(runnable, : thread_(
thread_can_start)) { ThreadWithParamSupport::CreateThread(runnable, thread_can_start)) {}
}
ThreadWithParamBase::~ThreadWithParamBase() { ThreadWithParamBase::~ThreadWithParamBase() { Join(); }
Join();
}
void ThreadWithParamBase::Join() { void ThreadWithParamBase::Join() {
GTEST_CHECK_(::WaitForSingleObject(thread_.Get(), INFINITE) == WAIT_OBJECT_0) GTEST_CHECK_(::WaitForSingleObject(thread_.Get(), INFINITE) == WAIT_OBJECT_0)
@ -527,8 +506,10 @@ class ThreadLocalRegistryImpl {
ThreadIdToThreadLocals::iterator thread_local_pos = ThreadIdToThreadLocals::iterator thread_local_pos =
thread_to_thread_locals->find(current_thread); thread_to_thread_locals->find(current_thread);
if (thread_local_pos == thread_to_thread_locals->end()) { if (thread_local_pos == thread_to_thread_locals->end()) {
thread_local_pos = thread_to_thread_locals->insert( thread_local_pos =
std::make_pair(current_thread, ThreadLocalValues())).first; thread_to_thread_locals
->insert(std::make_pair(current_thread, ThreadLocalValues()))
.first;
StartWatcherThreadFor(current_thread); StartWatcherThreadFor(current_thread);
} }
ThreadLocalValues& thread_local_values = thread_local_pos->second; ThreadLocalValues& thread_local_values = thread_local_pos->second;
@ -556,9 +537,8 @@ class ThreadLocalRegistryImpl {
ThreadIdToThreadLocals* const thread_to_thread_locals = ThreadIdToThreadLocals* const thread_to_thread_locals =
GetThreadLocalsMapLocked(); GetThreadLocalsMapLocked();
for (ThreadIdToThreadLocals::iterator it = for (ThreadIdToThreadLocals::iterator it =
thread_to_thread_locals->begin(); thread_to_thread_locals->begin();
it != thread_to_thread_locals->end(); it != thread_to_thread_locals->end(); ++it) {
++it) {
ThreadLocalValues& thread_local_values = it->second; ThreadLocalValues& thread_local_values = it->second;
ThreadLocalValues::iterator value_pos = ThreadLocalValues::iterator value_pos =
thread_local_values.find(thread_local_instance); thread_local_values.find(thread_local_instance);
@ -588,9 +568,8 @@ class ThreadLocalRegistryImpl {
if (thread_local_pos != thread_to_thread_locals->end()) { if (thread_local_pos != thread_to_thread_locals->end()) {
ThreadLocalValues& thread_local_values = thread_local_pos->second; ThreadLocalValues& thread_local_values = thread_local_pos->second;
for (ThreadLocalValues::iterator value_pos = for (ThreadLocalValues::iterator value_pos =
thread_local_values.begin(); thread_local_values.begin();
value_pos != thread_local_values.end(); value_pos != thread_local_values.end(); ++value_pos) {
++value_pos) {
value_holders.push_back(value_pos->second); value_holders.push_back(value_pos->second);
} }
thread_to_thread_locals->erase(thread_local_pos); thread_to_thread_locals->erase(thread_local_pos);
@ -616,9 +595,8 @@ class ThreadLocalRegistryImpl {
static void StartWatcherThreadFor(DWORD thread_id) { static void StartWatcherThreadFor(DWORD thread_id) {
// The returned handle will be kept in thread_map and closed by // The returned handle will be kept in thread_map and closed by
// watcher_thread in WatcherThreadFunc. // watcher_thread in WatcherThreadFunc.
HANDLE thread = ::OpenThread(SYNCHRONIZE | THREAD_QUERY_INFORMATION, HANDLE thread =
FALSE, ::OpenThread(SYNCHRONIZE | THREAD_QUERY_INFORMATION, FALSE, thread_id);
thread_id);
GTEST_CHECK_(thread != nullptr); GTEST_CHECK_(thread != nullptr);
// We need to pass a valid thread ID pointer into CreateThread for it // We need to pass a valid thread ID pointer into CreateThread for it
// to work correctly under Win98. // to work correctly under Win98.
@ -644,8 +622,7 @@ class ThreadLocalRegistryImpl {
static DWORD WINAPI WatcherThreadFunc(LPVOID param) { static DWORD WINAPI WatcherThreadFunc(LPVOID param) {
const ThreadIdAndHandle* tah = const ThreadIdAndHandle* tah =
reinterpret_cast<const ThreadIdAndHandle*>(param); reinterpret_cast<const ThreadIdAndHandle*>(param);
GTEST_CHECK_( GTEST_CHECK_(::WaitForSingleObject(tah->second, INFINITE) == WAIT_OBJECT_0);
::WaitForSingleObject(tah->second, INFINITE) == WAIT_OBJECT_0);
OnThreadExit(tah->first); OnThreadExit(tah->first);
::CloseHandle(tah->second); ::CloseHandle(tah->second);
delete tah; delete tah;
@ -669,16 +646,17 @@ class ThreadLocalRegistryImpl {
}; };
Mutex ThreadLocalRegistryImpl::mutex_(Mutex::kStaticMutex); // NOLINT 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( ThreadLocalValueHolderBase* ThreadLocalRegistry::GetValueOnCurrentThread(
const ThreadLocalBase* thread_local_instance) { const ThreadLocalBase* thread_local_instance) {
return ThreadLocalRegistryImpl::GetValueOnCurrentThread( return ThreadLocalRegistryImpl::GetValueOnCurrentThread(
thread_local_instance); thread_local_instance);
} }
void ThreadLocalRegistry::OnThreadLocalDestroyed( void ThreadLocalRegistry::OnThreadLocalDestroyed(
const ThreadLocalBase* thread_local_instance) { const ThreadLocalBase* thread_local_instance) {
ThreadLocalRegistryImpl::OnThreadLocalDestroyed(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 IsAsciiWhiteSpace(char ch) { return IsInSet(ch, " \f\n\r\t\v"); }
bool IsAsciiWordChar(char ch) { bool IsAsciiWordChar(char ch) {
return ('a' <= ch && ch <= 'z') || ('A' <= ch && ch <= 'Z') || 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. // 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) { bool AtomMatchesChar(bool escaped, char pattern_char, char ch) {
if (escaped) { // "\\p" where p is pattern_char. if (escaped) { // "\\p" where p is pattern_char.
switch (pattern_char) { switch (pattern_char) {
case 'd': return IsAsciiDigit(ch); case 'd':
case 'D': return !IsAsciiDigit(ch); return IsAsciiDigit(ch);
case 'f': return ch == '\f'; case 'D':
case 'n': return ch == '\n'; return !IsAsciiDigit(ch);
case 'r': return ch == '\r'; case 'f':
case 's': return IsAsciiWhiteSpace(ch); return ch == '\f';
case 'S': return !IsAsciiWhiteSpace(ch); case 'n':
case 't': return ch == '\t'; return ch == '\n';
case 'v': return ch == '\v'; case 'r':
case 'w': return IsAsciiWordChar(ch); return ch == '\r';
case 'W': return !IsAsciiWordChar(ch); 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; 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. // Helper function used by ValidateRegex() to format error messages.
static std::string FormatRegexSyntaxError(const char* regex, int index) { static std::string FormatRegexSyntaxError(const char* regex, int index) {
return (Message() << "Syntax error at index " << 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; // 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."; << "'$' can only appear at the end.";
is_valid = false; is_valid = false;
} else if (IsInSet(ch, "()[]{}|")) { } else if (IsInSet(ch, "()[]{}|")) {
ADD_FAILURE() << FormatRegexSyntaxError(regex, i) ADD_FAILURE() << FormatRegexSyntaxError(regex, i) << "'" << ch
<< "'" << ch << "' is unsupported."; << "' is unsupported.";
is_valid = false; is_valid = false;
} else if (IsRepeat(ch) && !prev_repeatable) { } else if (IsRepeat(ch) && !prev_repeatable) {
ADD_FAILURE() << FormatRegexSyntaxError(regex, i) ADD_FAILURE() << FormatRegexSyntaxError(regex, i) << "'" << ch
<< "'" << ch << "' can only follow a repeatable token."; << "' can only follow a repeatable token.";
is_valid = false; 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 // characters to be indexable by size_t, in which case the test will
// probably time out anyway. We are fine with this limitation as // probably time out anyway. We are fine with this limitation as
// std::string has it too. // std::string has it too.
bool MatchRepetitionAndRegexAtHead( bool MatchRepetitionAndRegexAtHead(bool escaped, char c, char repeat,
bool escaped, char c, char repeat, const char* regex, const char* regex, const char* str) {
const char* str) {
const size_t min_count = (repeat == '+') ? 1 : 0; const size_t min_count = (repeat == '+') ? 1 : 0;
const size_t max_count = (repeat == '?') ? 1 : const size_t max_count = (repeat == '?') ? 1 : static_cast<size_t>(-1) - 1;
static_cast<size_t>(-1) - 1;
// We cannot call numeric_limits::max() as it conflicts with the // We cannot call numeric_limits::max() as it conflicts with the
// max() macro on Windows. // max() macro on Windows.
@ -883,8 +871,7 @@ bool MatchRepetitionAndRegexAtHead(
// greedy match. // greedy match.
return true; return true;
} }
if (str[i] == '\0' || !AtomMatchesChar(escaped, c, str[i])) if (str[i] == '\0' || !AtomMatchesChar(escaped, c, str[i])) return false;
return false;
} }
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 // "$" only matches the end of a string. Note that regex being
// valid guarantees that there's nothing after "$" in it. // valid guarantees that there's nothing after "$" in it.
if (*regex == '$') if (*regex == '$') return *str == '\0';
return *str == '\0';
// Is the first thing in regex an escape sequence? // Is the first thing in regex an escape sequence?
const bool escaped = *regex == '\\'; const bool escaped = *regex == '\\';
if (escaped) if (escaped) ++regex;
++regex;
if (IsRepeat(regex[1])) { if (IsRepeat(regex[1])) {
// MatchRepetitionAndRegexAtHead() calls MatchRegexAtHead(), so // MatchRepetitionAndRegexAtHead() calls MatchRegexAtHead(), so
// here's an indirect recursion. It terminates as the regex gets // here's an indirect recursion. It terminates as the regex gets
// shorter in each recursion. // shorter in each recursion.
return MatchRepetitionAndRegexAtHead( return MatchRepetitionAndRegexAtHead(escaped, regex[0], regex[1], regex + 2,
escaped, regex[0], regex[1], regex + 2, str); str);
} else { } else {
// regex isn't empty, isn't "$", and doesn't start with a // regex isn't empty, isn't "$", and doesn't start with a
// repetition. We match the first atom of regex with the first // repetition. We match the first atom of regex with the first
// character of str and recurse. // character of str and recurse.
return (*str != '\0') && AtomMatchesChar(escaped, *regex, *str) && 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) { bool MatchRegexAnywhere(const char* regex, const char* str) {
if (regex == nullptr || str == nullptr) return false; if (regex == nullptr || str == nullptr) return false;
if (*regex == '^') if (*regex == '^') return MatchRegexAtHead(regex + 1, str);
return MatchRegexAtHead(regex + 1, str);
// A successful match can be anywhere in str. // A successful match can be anywhere in str.
do { do {
if (MatchRegexAtHead(regex, str)) if (MatchRegexAtHead(regex, str)) return true;
return true;
} while (*str++ != '\0'); } while (*str++ != '\0');
return false; return false;
} }
@ -1018,8 +1001,8 @@ GTEST_API_ ::std::string FormatFileLocation(const char* file, int line) {
// FormatFileLocation in order to contrast the two functions. // FormatFileLocation in order to contrast the two functions.
// Note that FormatCompilerIndependentFileLocation() does NOT append colon // Note that FormatCompilerIndependentFileLocation() does NOT append colon
// to the file location it produces, unlike FormatFileLocation(). // to the file location it produces, unlike FormatFileLocation().
GTEST_API_ ::std::string FormatCompilerIndependentFileLocation( GTEST_API_ ::std::string FormatCompilerIndependentFileLocation(const char* file,
const char* file, int line) { int line) {
const std::string file_name(file == nullptr ? kUnknownFile : file); const std::string file_name(file == nullptr ? kUnknownFile : file);
if (line < 0) if (line < 0)
@ -1030,12 +1013,13 @@ GTEST_API_ ::std::string FormatCompilerIndependentFileLocation(
GTestLog::GTestLog(GTestLogSeverity severity, const char* file, int line) GTestLog::GTestLog(GTestLogSeverity severity, const char* file, int line)
: severity_(severity) { : severity_(severity) {
const char* const marker = const char* const marker = severity == GTEST_INFO ? "[ INFO ]"
severity == GTEST_INFO ? "[ INFO ]" : : severity == GTEST_WARNING ? "[WARNING]"
severity == GTEST_WARNING ? "[WARNING]" : : severity == GTEST_ERROR ? "[ ERROR ]"
severity == GTEST_ERROR ? "[ ERROR ]" : "[ FATAL ]"; : "[ FATAL ]";
GetStream() << ::std::endl << marker << " " GetStream() << ::std::endl
<< FormatFileLocation(file, line).c_str() << ": "; << marker << " " << FormatFileLocation(file, line).c_str()
<< ": ";
} }
// Flushes the buffers and, if severity is GTEST_FATAL, aborts the program. // Flushes the buffers and, if severity is GTEST_FATAL, aborts the program.
@ -1058,27 +1042,26 @@ class CapturedStream {
public: public:
// The ctor redirects the stream to a temporary file. // The ctor redirects the stream to a temporary file.
explicit CapturedStream(int fd) : fd_(fd), uncaptured_fd_(dup(fd)) { explicit CapturedStream(int fd) : fd_(fd), uncaptured_fd_(dup(fd)) {
# if GTEST_OS_WINDOWS #if GTEST_OS_WINDOWS
char temp_dir_path[MAX_PATH + 1] = { '\0' }; // NOLINT char temp_dir_path[MAX_PATH + 1] = {'\0'}; // NOLINT
char temp_file_path[MAX_PATH + 1] = { '\0' }; // NOLINT char temp_file_path[MAX_PATH + 1] = {'\0'}; // NOLINT
::GetTempPathA(sizeof(temp_dir_path), temp_dir_path); ::GetTempPathA(sizeof(temp_dir_path), temp_dir_path);
const UINT success = ::GetTempFileNameA(temp_dir_path, const UINT success = ::GetTempFileNameA(temp_dir_path, "gtest_redir",
"gtest_redir",
0, // Generate unique file name. 0, // Generate unique file name.
temp_file_path); temp_file_path);
GTEST_CHECK_(success != 0) GTEST_CHECK_(success != 0)
<< "Unable to create a temporary file in " << temp_dir_path; << "Unable to create a temporary file in " << temp_dir_path;
const int captured_fd = creat(temp_file_path, _S_IREAD | _S_IWRITE); const int captured_fd = creat(temp_file_path, _S_IREAD | _S_IWRITE);
GTEST_CHECK_(captured_fd != -1) << "Unable to open temporary file " GTEST_CHECK_(captured_fd != -1)
<< temp_file_path; << "Unable to open temporary file " << temp_file_path;
filename_ = temp_file_path; filename_ = temp_file_path;
# else #else
// There's no guarantee that a test has write access to the current // There's no guarantee that a test has write access to the current
// directory, so we create the temporary file in a temporary directory. // directory, so we create the temporary file in a temporary directory.
std::string name_template; std::string name_template;
# if GTEST_OS_LINUX_ANDROID #if GTEST_OS_LINUX_ANDROID
// Note: Android applications are expected to call the framework's // Note: Android applications are expected to call the framework's
// Context.getExternalStorageDirectory() method through JNI to get // Context.getExternalStorageDirectory() method through JNI to get
// the location of the world-writable SD Card directory. However, // 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 // '/sdcard' and other variants cannot be relied on, as they are not
// guaranteed to be mounted, or may have a delay in mounting. // guaranteed to be mounted, or may have a delay in mounting.
name_template = "/data/local/tmp/"; name_template = "/data/local/tmp/";
# elif GTEST_OS_IOS #elif GTEST_OS_IOS
char user_temp_dir[PATH_MAX + 1]; char user_temp_dir[PATH_MAX + 1];
// Documented alternative to NSTemporaryDirectory() (for obtaining creating // Documented alternative to NSTemporaryDirectory() (for obtaining creating
@ -1112,9 +1095,9 @@ class CapturedStream {
name_template = user_temp_dir; name_template = user_temp_dir;
if (name_template.back() != GTEST_PATH_SEP_[0]) if (name_template.back() != GTEST_PATH_SEP_[0])
name_template.push_back(GTEST_PATH_SEP_[0]); name_template.push_back(GTEST_PATH_SEP_[0]);
# else #else
name_template = "/tmp/"; name_template = "/tmp/";
# endif #endif
name_template.append("gtest_captured_stream.XXXXXX"); name_template.append("gtest_captured_stream.XXXXXX");
// mkstemp() modifies the string bytes in place, and does not go beyond the // 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?"; << " for test; does the test have access to the /tmp directory?";
} }
filename_ = std::move(name_template); filename_ = std::move(name_template);
# endif // GTEST_OS_WINDOWS #endif // GTEST_OS_WINDOWS
fflush(nullptr); fflush(nullptr);
dup2(captured_fd, fd_); dup2(captured_fd, fd_);
close(captured_fd); close(captured_fd);
} }
~CapturedStream() { ~CapturedStream() { remove(filename_.c_str()); }
remove(filename_.c_str());
}
std::string GetCapturedString() { std::string GetCapturedString() {
if (uncaptured_fd_ != -1) { if (uncaptured_fd_ != -1) {
@ -1215,10 +1196,6 @@ std::string GetCapturedStderr() {
#endif // GTEST_HAS_STREAM_REDIRECTION #endif // GTEST_HAS_STREAM_REDIRECTION
size_t GetFileSize(FILE* file) { size_t GetFileSize(FILE* file) {
fseek(file, 0, SEEK_END); fseek(file, 0, SEEK_END);
return static_cast<size_t>(ftell(file)); 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 // Keeps reading the file until we cannot read further or the
// pre-determined file size is reached. // pre-determined file size is reached.
do { 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; bytes_read += bytes_last_read;
} while (bytes_last_read > 0 && bytes_read < file_size); } 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.) // LONG_MAX or LONG_MIN when the input overflows.)
result != long_value result != long_value
// The parsed value overflows as an int32_t. // The parsed value overflows as an int32_t.
) { ) {
Message msg; Message msg;
msg << "WARNING: " << src_text msg << "WARNING: " << src_text
<< " is expected to be a 32-bit integer, but actually" << " 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; int32_t result = default_value;
if (!ParseInt32(Message() << "Environment variable " << env_var, if (!ParseInt32(Message() << "Environment variable " << env_var, string_value,
string_value, &result)) { &result)) {
printf("The default value %s is used.\n", printf("The default value %s is used.\n",
(Message() << default_value).GetString().c_str()); (Message() << default_value).GetString().c_str());
fflush(stdout); fflush(stdout);
@ -1388,7 +1366,7 @@ int32_t Int32FromGTestEnv(const char* flag, int32_t default_value) {
// not check that the flag is 'output' // not check that the flag is 'output'
// In essence this checks an env variable called XML_OUTPUT_FILE // 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 "" // 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 = ""; std::string default_value_for_output_flag = "";
const char* xml_output_file_env = posix::GetEnv("XML_OUTPUT_FILE"); const char* xml_output_file_env = posix::GetEnv("XML_OUTPUT_FILE");
if (nullptr != xml_output_file_env) { if (nullptr != xml_output_file_env) {

View File

@ -27,7 +27,6 @@
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// Google Test - The Google C++ Testing and Mocking Framework // Google Test - The Google C++ Testing and Mocking Framework
// //
// This file implements a universal value printer that can print a // 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); PrintByteSegmentInObjectTo(obj_bytes, 0, kChunkSize, os);
*os << " ... "; *os << " ... ";
// Rounds up to 2-byte boundary. // 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); PrintByteSegmentInObjectTo(obj_bytes, resume_pos, count - resume_pos, os);
} }
*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 is if it's a printable ASCII (e.g. 'a', '2', ' '),
// - as a hexadecimal escape sequence (e.g. '\x7F'), or // - as a hexadecimal escape sequence (e.g. '\x7F'), or
// - as a special escape sequence (e.g. '\r', '\n'). // - as a special escape sequence (e.g. '\r', '\n').
enum CharFormat { enum CharFormat { kAsIs, kHexEscape, kSpecialEscape };
kAsIs,
kHexEscape,
kSpecialEscape
};
// Returns true if c is a printable ASCII character. We test the // Returns true if c is a printable ASCII character. We test the
// value of c directly instead of calling isprint(), which is buggy on // 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) { static const char* GetCharWidthPrefix(char) { return ""; }
return "";
}
static const char* GetCharWidthPrefix(signed char) { static const char* GetCharWidthPrefix(signed char) { return ""; }
return "";
}
static const char* GetCharWidthPrefix(unsigned char) { static const char* GetCharWidthPrefix(unsigned char) { return ""; }
return "";
}
#ifdef __cpp_char8_t #ifdef __cpp_char8_t
static const char* GetCharWidthPrefix(char8_t) { static const char* GetCharWidthPrefix(char8_t) { return "u8"; }
return "u8";
}
#endif #endif
static const char* GetCharWidthPrefix(char16_t) { static const char* GetCharWidthPrefix(char16_t) { return "u"; }
return "u";
}
static const char* GetCharWidthPrefix(char32_t) { static const char* GetCharWidthPrefix(char32_t) { return "U"; }
return "U";
}
static const char* GetCharWidthPrefix(wchar_t) { static const char* GetCharWidthPrefix(wchar_t) { return "L"; }
return "L";
}
// Prints a char c as if it's part of a string literal, escaping it when // Prints a char c as if it's part of a string literal, escaping it when
// necessary; returns how c was formatted. // 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 // 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 // it's 0 (in which case c was printed as '\\0', making the code
// obvious). // obvious).
if (c == 0) if (c == 0) return;
return;
*os << " (" << static_cast<int>(c); *os << " (" << static_cast<int>(c);
// For more convenience, we print c's code again in hexadecimal, // 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 // The array starts at begin, the length is len, it may include '\0' characters
// and may not be NUL-terminated. // and may not be NUL-terminated.
template <typename CharType> template <typename CharType>
GTEST_ATTRIBUTE_NO_SANITIZE_MEMORY_ GTEST_ATTRIBUTE_NO_SANITIZE_MEMORY_ GTEST_ATTRIBUTE_NO_SANITIZE_ADDRESS_
GTEST_ATTRIBUTE_NO_SANITIZE_ADDRESS_ GTEST_ATTRIBUTE_NO_SANITIZE_HWADDRESS_
GTEST_ATTRIBUTE_NO_SANITIZE_HWADDRESS_ GTEST_ATTRIBUTE_NO_SANITIZE_THREAD_ static CharFormat
GTEST_ATTRIBUTE_NO_SANITIZE_THREAD_ PrintCharsAsStringTo(const CharType* begin, size_t len, ostream* os) {
static CharFormat PrintCharsAsStringTo(
const CharType* begin, size_t len, ostream* os) {
const char* const quote_prefix = GetCharWidthPrefix(*begin); const char* const quote_prefix = GetCharWidthPrefix(*begin);
*os << quote_prefix << "\""; *os << quote_prefix << "\"";
bool is_previous_hex = false; 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 // Prints a (const) char/wchar_t array of 'len' elements, starting at address
// 'begin'. CharType must be either char or wchar_t. // 'begin'. CharType must be either char or wchar_t.
template <typename CharType> template <typename CharType>
GTEST_ATTRIBUTE_NO_SANITIZE_MEMORY_ GTEST_ATTRIBUTE_NO_SANITIZE_MEMORY_ GTEST_ATTRIBUTE_NO_SANITIZE_ADDRESS_
GTEST_ATTRIBUTE_NO_SANITIZE_ADDRESS_ GTEST_ATTRIBUTE_NO_SANITIZE_HWADDRESS_
GTEST_ATTRIBUTE_NO_SANITIZE_HWADDRESS_ GTEST_ATTRIBUTE_NO_SANITIZE_THREAD_ static void
GTEST_ATTRIBUTE_NO_SANITIZE_THREAD_ UniversalPrintCharArray(const CharType* begin, size_t len,
static void UniversalPrintCharArray( ostream* os) {
const CharType* begin, size_t len, ostream* os) {
// The code // The code
// const char kFoo[] = "foo"; // const char kFoo[] = "foo";
// generates an array of 4, not 3, elements, with the last one being '\0'. // 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 { namespace {
bool ContainsUnprintableControlCodes(const char* str, size_t length) { 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++) { for (size_t i = 0; i < length; i++) {
unsigned char ch = *s++; unsigned char ch = *s++;
if (std::iscntrl(ch)) { if (std::iscntrl(ch)) {
switch (ch) { switch (ch) {
case '\t': case '\t':
case '\n': case '\n':
case '\r': case '\r':
break; break;
default: default:
return true; return true;
}
} }
}
} }
return false; 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) { 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;) { for (size_t i = 0; i < length;) {
unsigned char lead = s[i++]; 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])) { } else if (lead <= 0xdf && (i + 1) <= length && IsUTF8TrailByte(s[i])) {
++i; // 2-byte character ++i; // 2-byte character
} else if (0xe0 <= lead && lead <= 0xef && (i + 2) <= length && } else if (0xe0 <= lead && lead <= 0xef && (i + 2) <= length &&
IsUTF8TrailByte(s[i]) && IsUTF8TrailByte(s[i]) && IsUTF8TrailByte(s[i + 1]) &&
IsUTF8TrailByte(s[i + 1]) &&
// check for non-shortest form and surrogate // check for non-shortest form and surrogate
(lead != 0xe0 || s[i] >= 0xa0) && (lead != 0xe0 || s[i] >= 0xa0) &&
(lead != 0xed || s[i] < 0xa0)) { (lead != 0xed || s[i] < 0xa0)) {
i += 2; // 3-byte character i += 2; // 3-byte character
} else if (0xf0 <= lead && lead <= 0xf4 && (i + 3) <= length && } else if (0xf0 <= lead && lead <= 0xf4 && (i + 3) <= length &&
IsUTF8TrailByte(s[i]) && IsUTF8TrailByte(s[i]) && IsUTF8TrailByte(s[i + 1]) &&
IsUTF8TrailByte(s[i + 1]) &&
IsUTF8TrailByte(s[i + 2]) && IsUTF8TrailByte(s[i + 2]) &&
// check for non-shortest form // check for non-shortest form
(lead != 0xf0 || s[i] >= 0x90) && (lead != 0xf0 || s[i] >= 0x90) &&

View File

@ -51,13 +51,11 @@ std::ostream& operator<<(std::ostream& os, const TestPartResult& result) {
return os << internal::FormatFileLocation(result.file_name(), return os << internal::FormatFileLocation(result.file_name(),
result.line_number()) result.line_number())
<< " " << " "
<< (result.type() == TestPartResult::kSuccess << (result.type() == TestPartResult::kSuccess ? "Success"
? "Success" : result.type() == TestPartResult::kSkip ? "Skipped"
: result.type() == TestPartResult::kSkip : result.type() == TestPartResult::kFatalFailure
? "Skipped" ? "Fatal failure"
: result.type() == TestPartResult::kFatalFailure : "Non-fatal failure")
? "Fatal failure"
: "Non-fatal failure")
<< ":\n" << ":\n"
<< result.message() << std::endl; << result.message() << std::endl;
} }
@ -86,8 +84,8 @@ namespace internal {
HasNewFatalFailureHelper::HasNewFatalFailureHelper() HasNewFatalFailureHelper::HasNewFatalFailureHelper()
: has_new_fatal_failure_(false), : has_new_fatal_failure_(false),
original_reporter_(GetUnitTestImpl()-> original_reporter_(
GetTestPartResultReporterForCurrentThread()) { GetUnitTestImpl()->GetTestPartResultReporterForCurrentThread()) {
GetUnitTestImpl()->SetTestPartResultReporterForCurrentThread(this); GetUnitTestImpl()->SetTestPartResultReporterForCurrentThread(this);
} }
@ -98,8 +96,7 @@ HasNewFatalFailureHelper::~HasNewFatalFailureHelper() {
void HasNewFatalFailureHelper::ReportTestPartResult( void HasNewFatalFailureHelper::ReportTestPartResult(
const TestPartResult& result) { const TestPartResult& result) {
if (result.fatally_failed()) if (result.fatally_failed()) has_new_fatal_failure_ = true;
has_new_fatal_failure_ = true;
original_reporter_->ReportTestPartResult(result); original_reporter_->ReportTestPartResult(result);
} }

View File

@ -27,7 +27,6 @@
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include "gtest/gtest-typed-test.h" #include "gtest/gtest-typed-test.h"
#include "gtest/gtest.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 // Skips to the first non-space char in str. Returns an empty string if str
// contains only whitespace characters. // contains only whitespace characters.
static const char* SkipSpaces(const char* str) { static const char* SkipSpaces(const char* str) {
while (IsSpace(*str)) while (IsSpace(*str)) str++;
str++;
return str; return str;
} }
@ -85,8 +83,7 @@ const char* TypedTestSuitePState::VerifyRegisteredTestNames(
} }
for (RegisteredTestIter it = registered_tests_.begin(); for (RegisteredTestIter it = registered_tests_.begin();
it != registered_tests_.end(); it != registered_tests_.end(); ++it) {
++it) {
if (tests.count(it->first) == 0) { if (tests.count(it->first) == 0) {
errors << "You forgot to list test " << it->first << ".\n"; errors << "You forgot to list test " << it->first << ".\n";
} }

File diff suppressed because it is too large Load Diff

View File

@ -28,15 +28,14 @@
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include <cstdio> #include <cstdio>
#include "gtest/gtest.h" #include "gtest/gtest.h"
#if GTEST_OS_ESP8266 || GTEST_OS_ESP32 #if GTEST_OS_ESP8266 || GTEST_OS_ESP32
#if GTEST_OS_ESP8266 #if GTEST_OS_ESP8266
extern "C" { extern "C" {
#endif #endif
void setup() { void setup() { testing::InitGoogleTest(); }
testing::InitGoogleTest();
}
void loop() { RUN_ALL_TESTS(); } void loop() { RUN_ALL_TESTS(); }

View File

@ -27,7 +27,6 @@
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// Unit test for Google Test's break-on-failure mode. // Unit test for Google Test's break-on-failure mode.
// //
// A user can ask Google Test to seg-fault when an assertion fails, using // A user can ask Google Test to seg-fault when an assertion fails, using
@ -41,34 +40,32 @@
#include "gtest/gtest.h" #include "gtest/gtest.h"
#if GTEST_OS_WINDOWS #if GTEST_OS_WINDOWS
# include <windows.h> #include <stdlib.h>
# include <stdlib.h> #include <windows.h>
#endif #endif
namespace { namespace {
// A test that's expected to fail. // A test that's expected to fail.
TEST(Foo, Bar) { TEST(Foo, Bar) { EXPECT_EQ(2, 3); }
EXPECT_EQ(2, 3);
}
#if GTEST_HAS_SEH && !GTEST_OS_WINDOWS_MOBILE #if GTEST_HAS_SEH && !GTEST_OS_WINDOWS_MOBILE
// On Windows Mobile global exception handlers are not supported. // On Windows Mobile global exception handlers are not supported.
LONG WINAPI ExitWithExceptionCode( LONG WINAPI
struct _EXCEPTION_POINTERS* exception_pointers) { ExitWithExceptionCode(struct _EXCEPTION_POINTERS* exception_pointers) {
exit(exception_pointers->ExceptionRecord->ExceptionCode); exit(exception_pointers->ExceptionRecord->ExceptionCode);
} }
#endif #endif
} // namespace } // namespace
int main(int argc, char **argv) { int main(int argc, char** argv) {
#if GTEST_OS_WINDOWS #if GTEST_OS_WINDOWS
// Suppresses display of the Windows error dialog upon encountering // Suppresses display of the Windows error dialog upon encountering
// a general protection fault (segment violation). // a general protection fault (segment violation).
SetErrorMode(SEM_NOGPFAULTERRORBOX | SEM_FAILCRITICALERRORS); 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 // The default unhandled exception filter does not always exit
// with the exception code as exit code - for example it exits with // with the exception code as exit code - for example it exits with
@ -78,7 +75,7 @@ int main(int argc, char **argv) {
// exceptions. // exceptions.
SetUnhandledExceptionFilter(ExitWithExceptionCode); SetUnhandledExceptionFilter(ExitWithExceptionCode);
# endif #endif
#endif // GTEST_OS_WINDOWS #endif // GTEST_OS_WINDOWS
testing::InitGoogleTest(&argc, argv); testing::InitGoogleTest(&argc, argv);

View File

@ -32,18 +32,18 @@
// exceptions, and the output is verified by // exceptions, and the output is verified by
// googletest-catch-exceptions-test.py. // googletest-catch-exceptions-test.py.
#include <stdio.h> // NOLINT #include <stdio.h> // NOLINT
#include <stdlib.h> // For exit(). #include <stdlib.h> // For exit().
#include "gtest/gtest.h" #include "gtest/gtest.h"
#if GTEST_HAS_SEH #if GTEST_HAS_SEH
# include <windows.h> #include <windows.h>
#endif #endif
#if GTEST_HAS_EXCEPTIONS #if GTEST_HAS_EXCEPTIONS
# include <exception> // For set_terminate(). #include <exception> // For set_terminate().
# include <stdexcept> #include <stdexcept>
#endif #endif
using testing::Test; using testing::Test;
@ -93,9 +93,7 @@ class SehExceptionInTearDownTest : public Test {
TEST_F(SehExceptionInTearDownTest, ThrowsExceptionInTearDown) {} TEST_F(SehExceptionInTearDownTest, ThrowsExceptionInTearDown) {}
TEST(SehExceptionTest, ThrowsSehException) { TEST(SehExceptionTest, ThrowsSehException) { RaiseException(42, 0, 0, NULL); }
RaiseException(42, 0, 0, NULL);
}
#endif // GTEST_HAS_SEH #endif // GTEST_HAS_SEH
@ -269,9 +267,7 @@ TEST_F(CxxExceptionInTestBodyTest, ThrowsStdCxxException) {
throw std::runtime_error("Standard C++ exception"); throw std::runtime_error("Standard C++ exception");
} }
TEST(CxxExceptionTest, ThrowsNonStdCxxException) { TEST(CxxExceptionTest, ThrowsNonStdCxxException) { throw "C-string"; }
throw "C-string";
}
// This terminate handler aborts the program using exit() rather than abort(). // 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 // This avoids showing pop-ups on Windows systems and core dumps on Unix-like

View File

@ -27,7 +27,6 @@
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// A helper program for testing how Google Test determines whether to use // 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 // colors in the output. It prints "YES" and returns 1 if Google Test
// decides to use colors, and prints "NO" and returns 0 otherwise. // 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() // 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 // works the same way as in a real Google-Test-based test. We don't actual
// run the TEST itself. // run the TEST itself.
TEST(GTestColorTest, Dummy) { TEST(GTestColorTest, Dummy) {}
}
int main(int argc, char** argv) { int main(int argc, char** argv) {
testing::InitGoogleTest(&argc, argv); testing::InitGoogleTest(&argc, argv);

View File

@ -31,7 +31,6 @@
// Tests for death tests. // Tests for death tests.
#include "gtest/gtest-death-test.h" #include "gtest/gtest-death-test.h"
#include "gtest/gtest.h" #include "gtest/gtest.h"
#include "gtest/internal/gtest-filepath.h" #include "gtest/internal/gtest-filepath.h"
@ -40,25 +39,25 @@ using testing::internal::AlwaysTrue;
#if GTEST_HAS_DEATH_TEST #if GTEST_HAS_DEATH_TEST
# if GTEST_OS_WINDOWS #if GTEST_OS_WINDOWS
# include <fcntl.h> // For O_BINARY #include <direct.h> // For chdir().
# include <direct.h> // For chdir(). #include <fcntl.h> // For O_BINARY
# include <io.h> #include <io.h>
# else #else
# include <unistd.h> #include <sys/wait.h> // For waitpid.
# include <sys/wait.h> // For waitpid. #include <unistd.h>
# endif // GTEST_OS_WINDOWS #endif // GTEST_OS_WINDOWS
# include <limits.h> #include <limits.h>
# include <signal.h> #include <signal.h>
# include <stdio.h> #include <stdio.h>
# if GTEST_OS_LINUX #if GTEST_OS_LINUX
# include <sys/time.h> #include <sys/time.h>
# endif // GTEST_OS_LINUX #endif // GTEST_OS_LINUX
# include "gtest/gtest-spi.h" #include "gtest/gtest-spi.h"
# include "src/gtest-internal-inl.h" #include "src/gtest-internal-inl.h"
namespace posix = ::testing::internal::posix; namespace posix = ::testing::internal::posix;
@ -90,6 +89,7 @@ class ReplaceDeathTestFactory {
unit_test_impl_->death_test_factory_.release(); unit_test_impl_->death_test_factory_.release();
unit_test_impl_->death_test_factory_.reset(old_factory_); unit_test_impl_->death_test_factory_.reset(old_factory_);
} }
private: private:
// Prevents copying ReplaceDeathTestFactory objects. // Prevents copying ReplaceDeathTestFactory objects.
ReplaceDeathTestFactory(const ReplaceDeathTestFactory&); ReplaceDeathTestFactory(const ReplaceDeathTestFactory&);
@ -116,8 +116,7 @@ void DieWithMessage(const ::std::string& message) {
// Some compilers can recognize that _exit() never returns and issue the // Some compilers can recognize that _exit() never returns and issue the
// 'unreachable code' warning for code following this function, unless // 'unreachable code' warning for code following this function, unless
// fooled by a fake condition. // fooled by a fake condition.
if (AlwaysTrue()) if (AlwaysTrue()) _exit(1);
_exit(1);
} }
void DieInside(const ::std::string& function) { void DieInside(const ::std::string& function) {
@ -137,8 +136,7 @@ class TestForDeathTest : public testing::Test {
// A method of the test fixture that may die. // A method of the test fixture that may die.
void MemberFunction() { void MemberFunction() {
if (should_die_) if (should_die_) DieInside("MemberFunction");
DieInside("MemberFunction");
} }
// True if and only if MemberFunction() should die. // True if and only if MemberFunction() should die.
@ -153,8 +151,7 @@ class MayDie {
// A member function that may die. // A member function that may die.
void MemberFunction() const { void MemberFunction() const {
if (should_die_) if (should_die_) DieInside("MayDie::MemberFunction");
DieInside("MayDie::MemberFunction");
} }
private: private:
@ -173,8 +170,7 @@ int NonVoidFunction() {
// A unary function that may die. // A unary function that may die.
void DieIf(bool should_die) { void DieIf(bool should_die) {
if (should_die) if (should_die) DieInside("DieIf");
DieInside("DieIf");
} }
// A binary function that may die. // A binary function that may die.
@ -195,16 +191,16 @@ void DeathTestSubroutine() {
int DieInDebugElse12(int* sideeffect) { int DieInDebugElse12(int* sideeffect) {
if (sideeffect) *sideeffect = 12; if (sideeffect) *sideeffect = 12;
# ifndef NDEBUG #ifndef NDEBUG
DieInside("DieInDebugElse12"); DieInside("DieInDebugElse12");
# endif // NDEBUG #endif // NDEBUG
return 12; return 12;
} }
# if GTEST_OS_WINDOWS #if GTEST_OS_WINDOWS
// Death in dbg due to Windows CRT assertion failure, not opt. // Death in dbg due to Windows CRT assertion failure, not opt.
int DieInCRTDebugElse12(int* sideeffect) { int DieInCRTDebugElse12(int* sideeffect) {
@ -224,7 +220,7 @@ int DieInCRTDebugElse12(int* sideeffect) {
#endif // GTEST_OS_WINDOWS #endif // GTEST_OS_WINDOWS
# if GTEST_OS_WINDOWS || GTEST_OS_FUCHSIA #if GTEST_OS_WINDOWS || GTEST_OS_FUCHSIA
// Tests the ExitedWithCode predicate. // Tests the ExitedWithCode predicate.
TEST(ExitStatusPredicateTest, ExitedWithCode) { TEST(ExitStatusPredicateTest, ExitedWithCode) {
@ -237,7 +233,7 @@ TEST(ExitStatusPredicateTest, ExitedWithCode) {
EXPECT_FALSE(testing::ExitedWithCode(1)(0)); EXPECT_FALSE(testing::ExitedWithCode(1)(0));
} }
# else #else
// Returns the exit status of a process that calls _exit(2) with a // Returns the exit status of a process that calls _exit(2) with a
// given exit code. This is a helper function for the // given exit code. This is a helper function for the
@ -270,14 +266,14 @@ static int KilledExitStatus(int signum) {
// Tests the ExitedWithCode predicate. // Tests the ExitedWithCode predicate.
TEST(ExitStatusPredicateTest, ExitedWithCode) { TEST(ExitStatusPredicateTest, ExitedWithCode) {
const int status0 = NormalExitStatus(0); const int status0 = NormalExitStatus(0);
const int status1 = NormalExitStatus(1); const int status1 = NormalExitStatus(1);
const int status42 = NormalExitStatus(42); const int status42 = NormalExitStatus(42);
const testing::ExitedWithCode pred0(0); const testing::ExitedWithCode pred0(0);
const testing::ExitedWithCode pred1(1); const testing::ExitedWithCode pred1(1);
const testing::ExitedWithCode pred42(42); const testing::ExitedWithCode pred42(42);
EXPECT_PRED1(pred0, status0); EXPECT_PRED1(pred0, status0);
EXPECT_PRED1(pred1, status1); EXPECT_PRED1(pred1, status1);
EXPECT_PRED1(pred42, status42); EXPECT_PRED1(pred42, status42);
EXPECT_FALSE(pred0(status1)); EXPECT_FALSE(pred0(status1));
EXPECT_FALSE(pred42(status0)); EXPECT_FALSE(pred42(status0));
@ -296,7 +292,7 @@ TEST(ExitStatusPredicateTest, KilledBySignal) {
EXPECT_FALSE(pred_kill(status_segv)); 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. // The following code intentionally tests a suboptimal syntax.
#ifdef __GNUC__ #ifdef __GNUC__
@ -320,8 +316,7 @@ TEST_F(TestForDeathTest, SingleStatement) {
// doesn't expand into an "if" statement without an "else" // doesn't expand into an "if" statement without an "else"
; ;
if (AlwaysFalse()) if (AlwaysFalse()) ASSERT_DEATH(return, "") << "did not die";
ASSERT_DEATH(return, "") << "did not die";
if (AlwaysFalse()) if (AlwaysFalse())
; ;
@ -332,7 +327,7 @@ TEST_F(TestForDeathTest, SingleStatement) {
#pragma GCC diagnostic pop #pragma GCC diagnostic pop
#endif #endif
# if GTEST_USES_PCRE #if GTEST_USES_PCRE
void DieWithEmbeddedNul() { void DieWithEmbeddedNul() {
fprintf(stderr, "Hello%cmy null world.\n", '\0'); fprintf(stderr, "Hello%cmy null world.\n", '\0');
@ -347,7 +342,7 @@ TEST_F(TestForDeathTest, EmbeddedNulInMessage) {
ASSERT_DEATH(DieWithEmbeddedNul(), "my null world"); 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 // Tests that death test macros expand to code which interacts well with switch
// statements. // statements.
@ -357,12 +352,12 @@ TEST_F(TestForDeathTest, SwitchStatement) {
GTEST_DISABLE_MSC_WARNINGS_PUSH_(4065) GTEST_DISABLE_MSC_WARNINGS_PUSH_(4065)
switch (0) switch (0)
default: default:
ASSERT_DEATH(_exit(1), "") << "exit in default switch handler"; ASSERT_DEATH(_exit(1), "") << "exit in default switch handler";
switch (0) switch (0)
case 0: case 0:
EXPECT_DEATH(_exit(1), "") << "exit in switch case"; EXPECT_DEATH(_exit(1), "") << "exit in switch case";
GTEST_DISABLE_MSC_WARNINGS_POP_() GTEST_DISABLE_MSC_WARNINGS_POP_()
} }
@ -396,8 +391,9 @@ TEST_F(TestForDeathTest, FastDeathTestInChangedDir) {
ASSERT_DEATH(_exit(1), ""); ASSERT_DEATH(_exit(1), "");
} }
# if GTEST_OS_LINUX #if GTEST_OS_LINUX
void SigprofAction(int, siginfo_t*, void*) { /* no op */ } void SigprofAction(int, siginfo_t*, void*) { /* no op */
}
// Sets SIGPROF action and ITIMER_PROF timer (interval: 1ms). // Sets SIGPROF action and ITIMER_PROF timer (interval: 1ms).
void SetSigprofActionAndTimer() { void SetSigprofActionAndTimer() {
@ -448,7 +444,7 @@ TEST_F(TestForDeathTest, ThreadSafeSigprofActionSet) {
DisableSigprofActionAndTimer(&old_signal_action); DisableSigprofActionAndTimer(&old_signal_action);
EXPECT_TRUE(old_signal_action.sa_sigaction == SigprofAction); 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: // Repeats a representative sample of death tests in the "threadsafe" style:
@ -487,13 +483,11 @@ TEST_F(TestForDeathTest, MixedStyles) {
EXPECT_DEATH(_exit(1), ""); EXPECT_DEATH(_exit(1), "");
} }
# if GTEST_HAS_CLONE && GTEST_HAS_PTHREAD #if GTEST_HAS_CLONE && GTEST_HAS_PTHREAD
bool pthread_flag; bool pthread_flag;
void SetPthreadFlag() { void SetPthreadFlag() { pthread_flag = true; }
pthread_flag = true;
}
TEST_F(TestForDeathTest, DoesNotExecuteAtforkHooks) { TEST_F(TestForDeathTest, DoesNotExecuteAtforkHooks) {
if (!GTEST_FLAG_GET(death_test_use_fork)) { 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. // Tests that a method of another class can be used in a death test.
TEST_F(TestForDeathTest, MethodOfAnotherClass) { TEST_F(TestForDeathTest, MethodOfAnotherClass) {
@ -527,7 +521,7 @@ TEST_F(TestForDeathTest, AcceptsAnythingConvertibleToRE) {
const testing::internal::RE regex(regex_c_str); const testing::internal::RE regex(regex_c_str);
EXPECT_DEATH(GlobalFunction(), regex); EXPECT_DEATH(GlobalFunction(), regex);
# if !GTEST_USES_PCRE #if !GTEST_USES_PCRE
const ::std::string regex_std_str(regex_c_str); const ::std::string regex_std_str(regex_c_str);
EXPECT_DEATH(GlobalFunction(), regex_std_str); EXPECT_DEATH(GlobalFunction(), regex_std_str);
@ -536,7 +530,7 @@ TEST_F(TestForDeathTest, AcceptsAnythingConvertibleToRE) {
// lifetime extension of the pointer is not sufficient. // lifetime extension of the pointer is not sufficient.
EXPECT_DEATH(GlobalFunction(), ::std::string(regex_c_str).c_str()); 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. // 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. // Tests that ASSERT_DEATH can be used outside a TEST, TEST_F, or test fixture.
TEST_F(TestForDeathTest, OutsideFixture) { TEST_F(TestForDeathTest, OutsideFixture) { DeathTestSubroutine(); }
DeathTestSubroutine();
}
// Tests that death tests can be done inside a loop. // Tests that death tests can be done inside a loop.
TEST_F(TestForDeathTest, InsideLoop) { TEST_F(TestForDeathTest, InsideLoop) {
@ -564,25 +556,28 @@ TEST_F(TestForDeathTest, InsideLoop) {
// Tests that a compound statement can be used in a death test. // Tests that a compound statement can be used in a death test.
TEST_F(TestForDeathTest, CompoundStatement) { TEST_F(TestForDeathTest, CompoundStatement) {
EXPECT_DEATH({ // NOLINT EXPECT_DEATH(
const int x = 2; { // NOLINT
const int y = x + 1; const int x = 2;
DieIfLessThan(x, y); const int y = x + 1;
}, DieIfLessThan(x, y);
"DieIfLessThan"); },
"DieIfLessThan");
} }
// Tests that code that doesn't die causes a death test to fail. // Tests that code that doesn't die causes a death test to fail.
TEST_F(TestForDeathTest, DoesNotDie) { TEST_F(TestForDeathTest, DoesNotDie) {
EXPECT_NONFATAL_FAILURE(EXPECT_DEATH(DieIf(false), "DieIf"), EXPECT_NONFATAL_FAILURE(EXPECT_DEATH(DieIf(false), "DieIf"), "failed to die");
"failed to die");
} }
// Tests that a death test fails when the error message isn't expected. // Tests that a death test fails when the error message isn't expected.
TEST_F(TestForDeathTest, ErrorMessageMismatch) { TEST_F(TestForDeathTest, ErrorMessageMismatch) {
EXPECT_NONFATAL_FAILURE({ // NOLINT EXPECT_NONFATAL_FAILURE(
EXPECT_DEATH(DieIf(true), "DieIfLessThan") << "End of death test message."; { // NOLINT
}, "died but not with expected error"); 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() // 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. // Tests that EXPECT_DEATH doesn't abort the test on failure.
TEST_F(TestForDeathTest, EXPECT_DEATH) { TEST_F(TestForDeathTest, EXPECT_DEATH) {
bool aborted = true; bool aborted = true;
EXPECT_NONFATAL_FAILURE(ExpectDeathTestHelper(&aborted), EXPECT_NONFATAL_FAILURE(ExpectDeathTestHelper(&aborted), "failed to die");
"failed to die");
EXPECT_FALSE(aborted); EXPECT_FALSE(aborted);
} }
// Tests that ASSERT_DEATH does abort the test on failure. // Tests that ASSERT_DEATH does abort the test on failure.
TEST_F(TestForDeathTest, ASSERT_DEATH) { TEST_F(TestForDeathTest, ASSERT_DEATH) {
static bool aborted; static bool aborted;
EXPECT_FATAL_FAILURE({ // NOLINT EXPECT_FATAL_FAILURE(
aborted = true; { // NOLINT
ASSERT_DEATH(DieIf(false), "DieIf"); // This assertion should fail. aborted = true;
aborted = false; ASSERT_DEATH(DieIf(false), "DieIf"); // This assertion should fail.
}, "failed to die"); aborted = false;
},
"failed to die");
EXPECT_TRUE(aborted); EXPECT_TRUE(aborted);
} }
@ -653,20 +649,20 @@ TEST_F(TestForDeathTest, TestExpectDebugDeath) {
EXPECT_DEBUG_DEATH(DieInDebugElse12(&sideeffect), regex) EXPECT_DEBUG_DEATH(DieInDebugElse12(&sideeffect), regex)
<< "Must accept a streamed message"; << "Must accept a streamed message";
# ifdef NDEBUG #ifdef NDEBUG
// Checks that the assignment occurs in opt mode (sideeffect). // Checks that the assignment occurs in opt mode (sideeffect).
EXPECT_EQ(12, sideeffect); EXPECT_EQ(12, sideeffect);
# else #else
// Checks that the assignment does not occur in dbg mode (no sideeffect). // Checks that the assignment does not occur in dbg mode (no sideeffect).
EXPECT_EQ(0, 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 // https://docs.microsoft.com/en-us/cpp/c-runtime-library/reference/crtsetreportmode
// In debug mode, the calls to _CrtSetReportMode and _CrtSetReportFile enable // In debug mode, the calls to _CrtSetReportMode and _CrtSetReportFile enable
@ -682,7 +678,7 @@ TEST_F(TestForDeathTest, CRTDebugDeath) {
} }
#endif // _DEBUG #endif // _DEBUG
# endif // GTEST_OS_WINDOWS #endif // GTEST_OS_WINDOWS
// Tests that ASSERT_DEBUG_DEATH works as expected, that is, you can stream a // Tests that ASSERT_DEBUG_DEATH works as expected, that is, you can stream a
// message to it, and in debug mode it: // message to it, and in debug mode it:
@ -697,20 +693,20 @@ TEST_F(TestForDeathTest, TestAssertDebugDeath) {
ASSERT_DEBUG_DEATH(DieInDebugElse12(&sideeffect), "death.*DieInDebugElse12") ASSERT_DEBUG_DEATH(DieInDebugElse12(&sideeffect), "death.*DieInDebugElse12")
<< "Must accept a streamed message"; << "Must accept a streamed message";
# ifdef NDEBUG #ifdef NDEBUG
// Checks that the assignment occurs in opt mode (sideeffect). // Checks that the assignment occurs in opt mode (sideeffect).
EXPECT_EQ(12, sideeffect); EXPECT_EQ(12, sideeffect);
# else #else
// Checks that the assignment does not occur in dbg mode (no sideeffect). // Checks that the assignment does not occur in dbg mode (no sideeffect).
EXPECT_EQ(0, sideeffect); EXPECT_EQ(0, sideeffect);
# endif #endif
} }
# ifndef NDEBUG #ifndef NDEBUG
void ExpectDebugDeathHelper(bool* aborted) { void ExpectDebugDeathHelper(bool* aborted) {
*aborted = true; *aborted = true;
@ -718,10 +714,11 @@ void ExpectDebugDeathHelper(bool* aborted) {
*aborted = false; *aborted = false;
} }
# if GTEST_OS_WINDOWS #if GTEST_OS_WINDOWS
TEST(PopUpDeathTest, DoesNotShowPopUpOnAbort) { TEST(PopUpDeathTest, DoesNotShowPopUpOnAbort) {
printf("This test should be considered failing if it shows " printf(
"any pop-up dialogs.\n"); "This test should be considered failing if it shows "
"any pop-up dialogs.\n");
fflush(stdout); fflush(stdout);
EXPECT_DEATH( 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 // Tests that EXPECT_DEBUG_DEATH in debug mode does not abort
// the function. // the function.
@ -822,42 +819,44 @@ TEST_F(TestForDeathTest, AssertDebugDeathAborts10) {
EXPECT_TRUE(aborted); EXPECT_TRUE(aborted);
} }
# endif // _NDEBUG #endif // _NDEBUG
// Tests the *_EXIT family of macros, using a variety of predicates. // Tests the *_EXIT family of macros, using a variety of predicates.
static void TestExitMacros() { static void TestExitMacros() {
EXPECT_EXIT(_exit(1), testing::ExitedWithCode(1), ""); EXPECT_EXIT(_exit(1), testing::ExitedWithCode(1), "");
ASSERT_EXIT(_exit(42), testing::ExitedWithCode(42), ""); 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 // Of all signals effects on the process exit code, only those of SIGABRT
// are documented on Windows. // are documented on Windows.
// See https://msdn.microsoft.com/en-us/query-bi/m/dwwzkt4c. // See https://msdn.microsoft.com/en-us/query-bi/m/dwwzkt4c.
EXPECT_EXIT(raise(SIGABRT), testing::ExitedWithCode(3), "") << "b_ar"; EXPECT_EXIT(raise(SIGABRT), testing::ExitedWithCode(3), "") << "b_ar";
# elif !GTEST_OS_FUCHSIA #elif !GTEST_OS_FUCHSIA
// Fuchsia has no unix signals. // Fuchsia has no unix signals.
EXPECT_EXIT(raise(SIGKILL), testing::KilledBySignal(SIGKILL), "") << "foo"; EXPECT_EXIT(raise(SIGKILL), testing::KilledBySignal(SIGKILL), "") << "foo";
ASSERT_EXIT(raise(SIGUSR2), testing::KilledBySignal(SIGUSR2), "") << "bar"; ASSERT_EXIT(raise(SIGUSR2), testing::KilledBySignal(SIGUSR2), "") << "bar";
EXPECT_FATAL_FAILURE({ // NOLINT EXPECT_FATAL_FAILURE(
ASSERT_EXIT(_exit(0), testing::KilledBySignal(SIGSEGV), "") { // NOLINT
<< "This failure is expected, too."; ASSERT_EXIT(_exit(0), testing::KilledBySignal(SIGSEGV), "")
}, "This failure is expected, too."); << "This failure is expected, too.";
},
"This failure is expected, too.");
# endif // GTEST_OS_WINDOWS #endif // GTEST_OS_WINDOWS
EXPECT_NONFATAL_FAILURE({ // NOLINT EXPECT_NONFATAL_FAILURE(
EXPECT_EXIT(raise(SIGSEGV), testing::ExitedWithCode(0), "") { // NOLINT
<< "This failure is expected."; EXPECT_EXIT(raise(SIGSEGV), testing::ExitedWithCode(0), "")
}, "This failure is expected."); << "This failure is expected.";
},
"This failure is expected.");
} }
TEST_F(TestForDeathTest, ExitMacros) { TEST_F(TestForDeathTest, ExitMacros) { TestExitMacros(); }
TestExitMacros();
}
TEST_F(TestForDeathTest, ExitMacrosUsingFork) { TEST_F(TestForDeathTest, ExitMacrosUsingFork) {
GTEST_FLAG_SET(death_test_use_fork, true); GTEST_FLAG_SET(death_test_use_fork, true);
@ -866,39 +865,40 @@ TEST_F(TestForDeathTest, ExitMacrosUsingFork) {
TEST_F(TestForDeathTest, InvalidStyle) { TEST_F(TestForDeathTest, InvalidStyle) {
GTEST_FLAG_SET(death_test_style, "rococo"); GTEST_FLAG_SET(death_test_style, "rococo");
EXPECT_NONFATAL_FAILURE({ // NOLINT EXPECT_NONFATAL_FAILURE(
EXPECT_DEATH(_exit(0), "") << "This failure is expected."; { // NOLINT
}, "This failure is expected."); EXPECT_DEATH(_exit(0), "") << "This failure is expected.";
},
"This failure is expected.");
} }
TEST_F(TestForDeathTest, DeathTestFailedOutput) { TEST_F(TestForDeathTest, DeathTestFailedOutput) {
GTEST_FLAG_SET(death_test_style, "fast"); GTEST_FLAG_SET(death_test_style, "fast");
EXPECT_NONFATAL_FAILURE( EXPECT_NONFATAL_FAILURE(
EXPECT_DEATH(DieWithMessage("death\n"), EXPECT_DEATH(DieWithMessage("death\n"), "expected message"),
"expected message"),
"Actual msg:\n" "Actual msg:\n"
"[ DEATH ] death\n"); "[ DEATH ] death\n");
} }
TEST_F(TestForDeathTest, DeathTestUnexpectedReturnOutput) { TEST_F(TestForDeathTest, DeathTestUnexpectedReturnOutput) {
GTEST_FLAG_SET(death_test_style, "fast"); GTEST_FLAG_SET(death_test_style, "fast");
EXPECT_NONFATAL_FAILURE( EXPECT_NONFATAL_FAILURE(EXPECT_DEATH(
EXPECT_DEATH({ {
fprintf(stderr, "returning\n"); fprintf(stderr, "returning\n");
fflush(stderr); fflush(stderr);
return; return;
}, ""), },
" Result: illegal return in test statement.\n" ""),
" Error msg:\n" " Result: illegal return in test statement.\n"
"[ DEATH ] returning\n"); " Error msg:\n"
"[ DEATH ] returning\n");
} }
TEST_F(TestForDeathTest, DeathTestBadExitCodeOutput) { TEST_F(TestForDeathTest, DeathTestBadExitCodeOutput) {
GTEST_FLAG_SET(death_test_style, "fast"); GTEST_FLAG_SET(death_test_style, "fast");
EXPECT_NONFATAL_FAILURE( EXPECT_NONFATAL_FAILURE(
EXPECT_EXIT(DieWithMessage("exiting with rc 1\n"), EXPECT_EXIT(DieWithMessage("exiting with rc 1\n"),
testing::ExitedWithCode(3), testing::ExitedWithCode(3), "expected message"),
"expected message"),
" Result: died but not with expected exit code:\n" " Result: died but not with expected exit code:\n"
" Exited with exit status 1\n" " Exited with exit status 1\n"
"Actual msg:\n" "Actual msg:\n"
@ -931,8 +931,8 @@ class MockDeathTestFactory : public DeathTestFactory {
int line, DeathTest** test) override; int line, DeathTest** test) override;
// Sets the parameters for subsequent calls to Create. // Sets the parameters for subsequent calls to Create.
void SetParameters(bool create, DeathTest::TestRole role, void SetParameters(bool create, DeathTest::TestRole role, int status,
int status, bool passed); bool passed);
// Accessors. // Accessors.
int AssumeRoleCalls() const { return assume_role_calls_; } int AssumeRoleCalls() const { return assume_role_calls_; }
@ -974,17 +974,15 @@ class MockDeathTestFactory : public DeathTestFactory {
bool test_deleted_; bool test_deleted_;
}; };
// A DeathTest implementation useful in testing. It returns values set // A DeathTest implementation useful in testing. It returns values set
// at its creation from its various inherited DeathTest methods, and // at its creation from its various inherited DeathTest methods, and
// reports calls to those methods to its parent MockDeathTestFactory // reports calls to those methods to its parent MockDeathTestFactory
// object. // object.
class MockDeathTest : public DeathTest { class MockDeathTest : public DeathTest {
public: public:
MockDeathTest(MockDeathTestFactory *parent, MockDeathTest(MockDeathTestFactory* parent, TestRole role, int status,
TestRole role, int status, bool passed) : bool passed)
parent_(parent), role_(role), status_(status), passed_(passed) { : parent_(parent), role_(role), status_(status), passed_(passed) {}
}
~MockDeathTest() override { parent_->test_deleted_ = true; } ~MockDeathTest() override { parent_->test_deleted_ = true; }
TestRole AssumeRole() override { TestRole AssumeRole() override {
++parent_->assume_role_calls_; ++parent_->assume_role_calls_;
@ -1009,7 +1007,6 @@ class MockDeathTest : public DeathTest {
const bool passed_; const bool passed_;
}; };
// MockDeathTestFactory constructor. // MockDeathTestFactory constructor.
MockDeathTestFactory::MockDeathTestFactory() MockDeathTestFactory::MockDeathTestFactory()
: create_(true), : create_(true),
@ -1019,13 +1016,10 @@ MockDeathTestFactory::MockDeathTestFactory()
assume_role_calls_(0), assume_role_calls_(0),
wait_calls_(0), wait_calls_(0),
passed_args_(), passed_args_(),
abort_args_() { abort_args_() {}
}
// Sets the parameters for subsequent calls to Create. // Sets the parameters for subsequent calls to Create.
void MockDeathTestFactory::SetParameters(bool create, void MockDeathTestFactory::SetParameters(bool create, DeathTest::TestRole role,
DeathTest::TestRole role,
int status, bool passed) { int status, bool passed) {
create_ = create; create_ = create;
role_ = role; role_ = role;
@ -1038,7 +1032,6 @@ void MockDeathTestFactory::SetParameters(bool create,
abort_args_.clear(); abort_args_.clear();
} }
// Sets test to NULL (if create_ is false) or to the address of a new // Sets test to NULL (if create_ is false) or to the address of a new
// MockDeathTest object with parameters taken from the last call // MockDeathTest object with parameters taken from the last call
// to SetParameters (if create_ is true). Always returns true. // 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 // test cannot be run directly from a test routine that uses a
// MockDeathTest, or the remainder of the routine will not be executed. // MockDeathTest, or the remainder of the routine will not be executed.
static void RunReturningDeathTest(bool* flag) { static void RunReturningDeathTest(bool* flag) {
ASSERT_DEATH({ // NOLINT ASSERT_DEATH(
*flag = true; { // NOLINT
return; *flag = true;
}, ""); return;
},
"");
} }
}; };
@ -1166,8 +1161,7 @@ TEST_F(MacroLogicDeathTest, ChildDoesNotDie) {
// _exit(2) is called in that case by ForkingDeathTest, but not by // _exit(2) is called in that case by ForkingDeathTest, but not by
// our MockDeathTest. // our MockDeathTest.
ASSERT_EQ(2U, factory_->AbortCalls()); ASSERT_EQ(2U, factory_->AbortCalls());
EXPECT_EQ(DeathTest::TEST_DID_NOT_DIE, EXPECT_EQ(DeathTest::TEST_DID_NOT_DIE, factory_->AbortArgument(0));
factory_->AbortArgument(0));
EXPECT_EQ(DeathTest::TEST_ENCOUNTERED_RETURN_STATEMENT, EXPECT_EQ(DeathTest::TEST_ENCOUNTERED_RETURN_STATEMENT,
factory_->AbortArgument(1)); factory_->AbortArgument(1));
EXPECT_TRUE(factory_->TestDeleted()); EXPECT_TRUE(factory_->TestDeleted());
@ -1183,12 +1177,16 @@ TEST(SuccessRegistrationDeathTest, NoSuccessPart) {
TEST(StreamingAssertionsDeathTest, DeathTest) { TEST(StreamingAssertionsDeathTest, DeathTest) {
EXPECT_DEATH(_exit(1), "") << "unexpected failure"; EXPECT_DEATH(_exit(1), "") << "unexpected failure";
ASSERT_DEATH(_exit(1), "") << "unexpected failure"; ASSERT_DEATH(_exit(1), "") << "unexpected failure";
EXPECT_NONFATAL_FAILURE({ // NOLINT EXPECT_NONFATAL_FAILURE(
EXPECT_DEATH(_exit(0), "") << "expected failure"; { // NOLINT
}, "expected failure"); EXPECT_DEATH(_exit(0), "") << "expected failure";
EXPECT_FATAL_FAILURE({ // NOLINT },
ASSERT_DEATH(_exit(0), "") << "expected failure"; "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 // Tests that GetLastErrnoDescription returns an empty string when the
@ -1200,7 +1198,7 @@ TEST(GetLastErrnoDescription, GetLastErrnoDescriptionWorks) {
EXPECT_STREQ("", GetLastErrnoDescription().c_str()); EXPECT_STREQ("", GetLastErrnoDescription().c_str());
} }
# if GTEST_OS_WINDOWS #if GTEST_OS_WINDOWS
TEST(AutoHandleTest, AutoHandleWorks) { TEST(AutoHandleTest, AutoHandleWorks) {
HANDLE handle = ::CreateEvent(NULL, FALSE, FALSE, NULL); HANDLE handle = ::CreateEvent(NULL, FALSE, FALSE, NULL);
ASSERT_NE(INVALID_HANDLE_VALUE, handle); ASSERT_NE(INVALID_HANDLE_VALUE, handle);
@ -1225,15 +1223,15 @@ TEST(AutoHandleTest, AutoHandleWorks) {
testing::internal::AutoHandle auto_handle2; testing::internal::AutoHandle auto_handle2;
EXPECT_EQ(INVALID_HANDLE_VALUE, auto_handle2.Get()); 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 unsigned __int64 BiggestParsable;
typedef signed __int64 BiggestSignedParsable; typedef signed __int64 BiggestSignedParsable;
# else #else
typedef unsigned long long BiggestParsable; typedef unsigned long long BiggestParsable;
typedef signed long long BiggestSignedParsable; 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 // We cannot use std::numeric_limits<T>::max() as it clashes with the
// max() macro defined by <windows.h>. // max() macro defined by <windows.h>.
@ -1324,11 +1322,11 @@ TEST(ParseNaturalNumberTest, WorksForShorterIntegers) {
EXPECT_EQ(123, char_result); EXPECT_EQ(123, char_result);
} }
# if GTEST_OS_WINDOWS #if GTEST_OS_WINDOWS
TEST(EnvironmentTest, HandleFitsIntoSizeT) { TEST(EnvironmentTest, HandleFitsIntoSizeT) {
ASSERT_TRUE(sizeof(HANDLE) <= sizeof(size_t)); 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 // Tests that EXPECT_DEATH_IF_SUPPORTED/ASSERT_DEATH_IF_SUPPORTED trigger
// failures when death tests are available on the system. // failures when death tests are available on the system.
@ -1346,21 +1344,25 @@ TEST(ConditionalDeathMacrosDeathTest, ExpectsDeathWhenDeathTestsAvailable) {
TEST(InDeathTestChildDeathTest, ReportsDeathTestCorrectlyInFastStyle) { TEST(InDeathTestChildDeathTest, ReportsDeathTestCorrectlyInFastStyle) {
GTEST_FLAG_SET(death_test_style, "fast"); GTEST_FLAG_SET(death_test_style, "fast");
EXPECT_FALSE(InDeathTestChild()); EXPECT_FALSE(InDeathTestChild());
EXPECT_DEATH({ EXPECT_DEATH(
fprintf(stderr, InDeathTestChild() ? "Inside" : "Outside"); {
fflush(stderr); fprintf(stderr, InDeathTestChild() ? "Inside" : "Outside");
_exit(1); fflush(stderr);
}, "Inside"); _exit(1);
},
"Inside");
} }
TEST(InDeathTestChildDeathTest, ReportsDeathTestCorrectlyInThreadSafeStyle) { TEST(InDeathTestChildDeathTest, ReportsDeathTestCorrectlyInThreadSafeStyle) {
GTEST_FLAG_SET(death_test_style, "threadsafe"); GTEST_FLAG_SET(death_test_style, "threadsafe");
EXPECT_FALSE(InDeathTestChild()); EXPECT_FALSE(InDeathTestChild());
EXPECT_DEATH({ EXPECT_DEATH(
fprintf(stderr, InDeathTestChild() ? "Inside" : "Outside"); {
fflush(stderr); fprintf(stderr, InDeathTestChild() ? "Inside" : "Outside");
_exit(1); fflush(stderr);
}, "Inside"); _exit(1);
},
"Inside");
} }
void DieWithMessage(const char* message) { void DieWithMessage(const char* message) {
@ -1488,8 +1490,7 @@ TEST(ConditionalDeathMacrosSyntaxDeathTest, SingleStatement) {
// doesn't expand into an "if" statement without an "else" // doesn't expand into an "if" statement without an "else"
; // NOLINT ; // NOLINT
if (AlwaysFalse()) if (AlwaysFalse()) ASSERT_DEATH_IF_SUPPORTED(return, "") << "did not die";
ASSERT_DEATH_IF_SUPPORTED(return, "") << "did not die";
if (AlwaysFalse()) if (AlwaysFalse())
; // NOLINT ; // NOLINT
@ -1508,21 +1509,18 @@ TEST(ConditionalDeathMacrosSyntaxDeathTest, SwitchStatement) {
GTEST_DISABLE_MSC_WARNINGS_PUSH_(4065) GTEST_DISABLE_MSC_WARNINGS_PUSH_(4065)
switch (0) switch (0)
default: default:
ASSERT_DEATH_IF_SUPPORTED(_exit(1), "") ASSERT_DEATH_IF_SUPPORTED(_exit(1), "") << "exit in default switch handler";
<< "exit in default switch handler";
switch (0) switch (0)
case 0: case 0:
EXPECT_DEATH_IF_SUPPORTED(_exit(1), "") << "exit in switch case"; EXPECT_DEATH_IF_SUPPORTED(_exit(1), "") << "exit in switch case";
GTEST_DISABLE_MSC_WARNINGS_POP_() GTEST_DISABLE_MSC_WARNINGS_POP_()
} }
// Tests that a test case whose name ends with "DeathTest" works fine // Tests that a test case whose name ends with "DeathTest" works fine
// on Windows. // on Windows.
TEST(NotADeathTest, Test) { TEST(NotADeathTest, Test) { SUCCEED(); }
SUCCEED();
}
} // namespace } // namespace

View File

@ -35,15 +35,15 @@
#if GTEST_HAS_DEATH_TEST #if GTEST_HAS_DEATH_TEST
# if GTEST_HAS_SEH #if GTEST_HAS_SEH
# include <windows.h> // For RaiseException(). #include <windows.h> // For RaiseException().
# endif #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 // Tests that death tests report thrown exceptions as failures and that the
// exceptions do not escape death test macros. // exceptions do not escape death test macros.
@ -67,12 +67,11 @@ TEST(CxxExceptionDeathTest, PrintsMessageForStdExceptions) {
EXPECT_NONFATAL_FAILURE(EXPECT_DEATH(throw TestException(), ""), EXPECT_NONFATAL_FAILURE(EXPECT_DEATH(throw TestException(), ""),
"exceptional message"); "exceptional message");
// Verifies that the location is mentioned in the failure text. // Verifies that the location is mentioned in the failure text.
EXPECT_NONFATAL_FAILURE(EXPECT_DEATH(throw TestException(), ""), EXPECT_NONFATAL_FAILURE(EXPECT_DEATH(throw TestException(), ""), __FILE__);
__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 // Tests that enabling interception of SEH exceptions with the
// catch_exceptions flag does not interfere with SEH exceptions being // catch_exceptions flag does not interfere with SEH exceptions being
// treated as death by death tests. // treated as death by death tests.
@ -81,7 +80,7 @@ TEST(SehExceptionDeasTest, CatchExceptionsDoesNotInterfere) {
<< "with catch_exceptions " << "with catch_exceptions "
<< (GTEST_FLAG_GET(catch_exceptions) ? "enabled" : "disabled"); << (GTEST_FLAG_GET(catch_exceptions) ? "enabled" : "disabled");
} }
# endif #endif
#endif // GTEST_HAS_DEATH_TEST #endif // GTEST_HAS_DEATH_TEST

View File

@ -27,7 +27,6 @@
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// A helper program for testing that Google Test parses the environment // A helper program for testing that Google Test parses the environment
// variables correctly. // variables correctly.
@ -43,8 +42,7 @@ namespace testing {
// The purpose of this is to make the test more realistic by ensuring // The purpose of this is to make the test more realistic by ensuring
// that the UnitTest singleton is created before main() is entered. // that the UnitTest singleton is created before main() is entered.
// We don't actual run the TEST itself. // We don't actual run the TEST itself.
TEST(GTestEnvVarTest, Dummy) { TEST(GTestEnvVarTest, Dummy) {}
}
void PrintFlag(const char* flag) { void PrintFlag(const char* flag) {
if (strcmp(flag, "break_on_failure") == 0) { if (strcmp(flag, "break_on_failure") == 0) {

View File

@ -27,7 +27,6 @@
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// Unit test for Google Test test filters. // Unit test for Google Test test filters.
// //
// A user can specify which test(s) in a Google Test program to run via // 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 } // namespace
int main(int argc, char **argv) { int main(int argc, char** argv) {
::testing::InitGoogleTest(&argc, argv); ::testing::InitGoogleTest(&argc, argv);
::testing::UnitTest::GetInstance()->listeners().Append(new MyTestListener()); ::testing::UnitTest::GetInstance()->listeners().Append(new MyTestListener());
return RUN_ALL_TESTS(); return RUN_ALL_TESTS();

View File

@ -35,15 +35,15 @@
// This file is #included from gtest-internal.h. // This file is #included from gtest-internal.h.
// Do not #include this file anywhere else! // Do not #include this file anywhere else!
#include "gtest/internal/gtest-filepath.h"
#include "gtest/gtest.h" #include "gtest/gtest.h"
#include "gtest/internal/gtest-filepath.h"
#include "src/gtest-internal-inl.h" #include "src/gtest-internal-inl.h"
#if GTEST_OS_WINDOWS_MOBILE #if GTEST_OS_WINDOWS_MOBILE
# include <windows.h> // NOLINT #include <windows.h> // NOLINT
#elif GTEST_OS_WINDOWS #elif GTEST_OS_WINDOWS
# include <direct.h> // NOLINT #include <direct.h> // NOLINT
#endif // GTEST_OS_WINDOWS_MOBILE #endif // GTEST_OS_WINDOWS_MOBILE
namespace testing { namespace testing {
namespace internal { namespace internal {
@ -55,16 +55,16 @@ namespace {
int remove(const char* path) { int remove(const char* path) {
LPCWSTR wpath = String::AnsiToUtf16(path); LPCWSTR wpath = String::AnsiToUtf16(path);
int ret = DeleteFile(wpath) ? 0 : -1; int ret = DeleteFile(wpath) ? 0 : -1;
delete [] wpath; delete[] wpath;
return ret; return ret;
} }
// Windows CE doesn't have the _rmdir C function. // Windows CE doesn't have the _rmdir C function.
int _rmdir(const char* path) { int _rmdir(const char* path) {
FilePath filepath(path); FilePath filepath(path);
LPCWSTR wpath = String::AnsiToUtf16( LPCWSTR wpath =
filepath.RemoveTrailingPathSeparator().c_str()); String::AnsiToUtf16(filepath.RemoveTrailingPathSeparator().c_str());
int ret = RemoveDirectory(wpath) ? 0 : -1; int ret = RemoveDirectory(wpath) ? 0 : -1;
delete [] wpath; delete[] wpath;
return ret; return ret;
} }
@ -78,18 +78,18 @@ TEST(GetCurrentDirTest, ReturnsCurrentDir) {
const FilePath cwd = FilePath::GetCurrentDir(); const FilePath cwd = FilePath::GetCurrentDir();
posix::ChDir(original_dir.c_str()); posix::ChDir(original_dir.c_str());
# if GTEST_OS_WINDOWS || GTEST_OS_OS2 #if GTEST_OS_WINDOWS || GTEST_OS_OS2
// Skips the ":". // Skips the ":".
const char* const cwd_without_drive = strchr(cwd.c_str(), ':'); const char* const cwd_without_drive = strchr(cwd.c_str(), ':');
ASSERT_TRUE(cwd_without_drive != NULL); ASSERT_TRUE(cwd_without_drive != NULL);
EXPECT_STREQ(GTEST_PATH_SEP_, cwd_without_drive + 1); EXPECT_STREQ(GTEST_PATH_SEP_, cwd_without_drive + 1);
# else #else
EXPECT_EQ(GTEST_PATH_SEP_, cwd.string()); EXPECT_EQ(GTEST_PATH_SEP_, cwd.string());
# endif #endif
} }
#endif // GTEST_OS_WINDOWS_MOBILE #endif // GTEST_OS_WINDOWS_MOBILE
@ -112,33 +112,34 @@ TEST(RemoveDirectoryNameTest, WhenEmptyName) {
// RemoveDirectoryName "afile" -> "afile" // RemoveDirectoryName "afile" -> "afile"
TEST(RemoveDirectoryNameTest, ButNoDirectory) { TEST(RemoveDirectoryNameTest, ButNoDirectory) {
EXPECT_EQ("afile", EXPECT_EQ("afile", FilePath("afile").RemoveDirectoryName().string());
FilePath("afile").RemoveDirectoryName().string());
} }
// RemoveDirectoryName "/afile" -> "afile" // RemoveDirectoryName "/afile" -> "afile"
TEST(RemoveDirectoryNameTest, RootFileShouldGiveFileName) { TEST(RemoveDirectoryNameTest, RootFileShouldGiveFileName) {
EXPECT_EQ("afile", EXPECT_EQ("afile",
FilePath(GTEST_PATH_SEP_ "afile").RemoveDirectoryName().string()); FilePath(GTEST_PATH_SEP_ "afile").RemoveDirectoryName().string());
} }
// RemoveDirectoryName "adir/" -> "" // RemoveDirectoryName "adir/" -> ""
TEST(RemoveDirectoryNameTest, WhereThereIsNoFileName) { TEST(RemoveDirectoryNameTest, WhereThereIsNoFileName) {
EXPECT_EQ("", EXPECT_EQ("",
FilePath("adir" GTEST_PATH_SEP_).RemoveDirectoryName().string()); FilePath("adir" GTEST_PATH_SEP_).RemoveDirectoryName().string());
} }
// RemoveDirectoryName "adir/afile" -> "afile" // RemoveDirectoryName "adir/afile" -> "afile"
TEST(RemoveDirectoryNameTest, ShouldGiveFileName) { TEST(RemoveDirectoryNameTest, ShouldGiveFileName) {
EXPECT_EQ("afile", EXPECT_EQ(
"afile",
FilePath("adir" GTEST_PATH_SEP_ "afile").RemoveDirectoryName().string()); FilePath("adir" GTEST_PATH_SEP_ "afile").RemoveDirectoryName().string());
} }
// RemoveDirectoryName "adir/subdir/afile" -> "afile" // RemoveDirectoryName "adir/subdir/afile" -> "afile"
TEST(RemoveDirectoryNameTest, ShouldAlsoGiveFileName) { TEST(RemoveDirectoryNameTest, ShouldAlsoGiveFileName) {
EXPECT_EQ("afile", EXPECT_EQ("afile",
FilePath("adir" GTEST_PATH_SEP_ "subdir" GTEST_PATH_SEP_ "afile") FilePath("adir" GTEST_PATH_SEP_ "subdir" GTEST_PATH_SEP_ "afile")
.RemoveDirectoryName().string()); .RemoveDirectoryName()
.string());
} }
#if GTEST_HAS_ALT_PATH_SEP_ #if GTEST_HAS_ALT_PATH_SEP_
@ -182,7 +183,7 @@ TEST(RemoveFileNameTest, EmptyName) {
// RemoveFileName "adir/" -> "adir/" // RemoveFileName "adir/" -> "adir/"
TEST(RemoveFileNameTest, ButNoFile) { TEST(RemoveFileNameTest, ButNoFile) {
EXPECT_EQ("adir" GTEST_PATH_SEP_, EXPECT_EQ("adir" GTEST_PATH_SEP_,
FilePath("adir" GTEST_PATH_SEP_).RemoveFileName().string()); FilePath("adir" GTEST_PATH_SEP_).RemoveFileName().string());
} }
// RemoveFileName "adir/afile" -> "adir/" // RemoveFileName "adir/afile" -> "adir/"
@ -194,14 +195,15 @@ TEST(RemoveFileNameTest, GivesDirName) {
// RemoveFileName "adir/subdir/afile" -> "adir/subdir/" // RemoveFileName "adir/subdir/afile" -> "adir/subdir/"
TEST(RemoveFileNameTest, GivesDirAndSubDirName) { TEST(RemoveFileNameTest, GivesDirAndSubDirName) {
EXPECT_EQ("adir" GTEST_PATH_SEP_ "subdir" GTEST_PATH_SEP_, EXPECT_EQ("adir" GTEST_PATH_SEP_ "subdir" GTEST_PATH_SEP_,
FilePath("adir" GTEST_PATH_SEP_ "subdir" GTEST_PATH_SEP_ "afile") FilePath("adir" GTEST_PATH_SEP_ "subdir" GTEST_PATH_SEP_ "afile")
.RemoveFileName().string()); .RemoveFileName()
.string());
} }
// RemoveFileName "/afile" -> "/" // RemoveFileName "/afile" -> "/"
TEST(RemoveFileNameTest, GivesRootDir) { TEST(RemoveFileNameTest, GivesRootDir) {
EXPECT_EQ(GTEST_PATH_SEP_, 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_ #if GTEST_HAS_ALT_PATH_SEP_
@ -235,44 +237,43 @@ TEST(RemoveFileNameTest, GivesRootDirForAlternateSeparator) {
#endif #endif
TEST(MakeFileNameTest, GenerateWhenNumberIsZero) { TEST(MakeFileNameTest, GenerateWhenNumberIsZero) {
FilePath actual = FilePath::MakeFileName(FilePath("foo"), FilePath("bar"), FilePath actual =
0, "xml"); FilePath::MakeFileName(FilePath("foo"), FilePath("bar"), 0, "xml");
EXPECT_EQ("foo" GTEST_PATH_SEP_ "bar.xml", actual.string()); EXPECT_EQ("foo" GTEST_PATH_SEP_ "bar.xml", actual.string());
} }
TEST(MakeFileNameTest, GenerateFileNameNumberGtZero) { TEST(MakeFileNameTest, GenerateFileNameNumberGtZero) {
FilePath actual = FilePath::MakeFileName(FilePath("foo"), FilePath("bar"), FilePath actual =
12, "xml"); FilePath::MakeFileName(FilePath("foo"), FilePath("bar"), 12, "xml");
EXPECT_EQ("foo" GTEST_PATH_SEP_ "bar_12.xml", actual.string()); EXPECT_EQ("foo" GTEST_PATH_SEP_ "bar_12.xml", actual.string());
} }
TEST(MakeFileNameTest, GenerateFileNameWithSlashNumberIsZero) { TEST(MakeFileNameTest, GenerateFileNameWithSlashNumberIsZero) {
FilePath actual = FilePath::MakeFileName(FilePath("foo" GTEST_PATH_SEP_), 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()); EXPECT_EQ("foo" GTEST_PATH_SEP_ "bar.xml", actual.string());
} }
TEST(MakeFileNameTest, GenerateFileNameWithSlashNumberGtZero) { TEST(MakeFileNameTest, GenerateFileNameWithSlashNumberGtZero) {
FilePath actual = FilePath::MakeFileName(FilePath("foo" GTEST_PATH_SEP_), 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()); EXPECT_EQ("foo" GTEST_PATH_SEP_ "bar_12.xml", actual.string());
} }
TEST(MakeFileNameTest, GenerateWhenNumberIsZeroAndDirIsEmpty) { TEST(MakeFileNameTest, GenerateWhenNumberIsZeroAndDirIsEmpty) {
FilePath actual = FilePath::MakeFileName(FilePath(""), FilePath("bar"), FilePath actual =
0, "xml"); FilePath::MakeFileName(FilePath(""), FilePath("bar"), 0, "xml");
EXPECT_EQ("bar.xml", actual.string()); EXPECT_EQ("bar.xml", actual.string());
} }
TEST(MakeFileNameTest, GenerateWhenNumberIsNotZeroAndDirIsEmpty) { TEST(MakeFileNameTest, GenerateWhenNumberIsNotZeroAndDirIsEmpty) {
FilePath actual = FilePath::MakeFileName(FilePath(""), FilePath("bar"), FilePath actual =
14, "xml"); FilePath::MakeFileName(FilePath(""), FilePath("bar"), 14, "xml");
EXPECT_EQ("bar_14.xml", actual.string()); EXPECT_EQ("bar_14.xml", actual.string());
} }
TEST(ConcatPathsTest, WorksWhenDirDoesNotEndWithPathSep) { TEST(ConcatPathsTest, WorksWhenDirDoesNotEndWithPathSep) {
FilePath actual = FilePath::ConcatPaths(FilePath("foo"), FilePath actual = FilePath::ConcatPaths(FilePath("foo"), FilePath("bar.xml"));
FilePath("bar.xml"));
EXPECT_EQ("foo" GTEST_PATH_SEP_ "bar.xml", actual.string()); EXPECT_EQ("foo" GTEST_PATH_SEP_ "bar.xml", actual.string());
} }
@ -283,8 +284,7 @@ TEST(ConcatPathsTest, WorksWhenPath1EndsWithPathSep) {
} }
TEST(ConcatPathsTest, Path1BeingEmpty) { TEST(ConcatPathsTest, Path1BeingEmpty) {
FilePath actual = FilePath::ConcatPaths(FilePath(""), FilePath actual = FilePath::ConcatPaths(FilePath(""), FilePath("bar.xml"));
FilePath("bar.xml"));
EXPECT_EQ("bar.xml", actual.string()); EXPECT_EQ("bar.xml", actual.string());
} }
@ -294,8 +294,7 @@ TEST(ConcatPathsTest, Path2BeingEmpty) {
} }
TEST(ConcatPathsTest, BothPathBeingEmpty) { TEST(ConcatPathsTest, BothPathBeingEmpty) {
FilePath actual = FilePath::ConcatPaths(FilePath(""), FilePath actual = FilePath::ConcatPaths(FilePath(""), FilePath(""));
FilePath(""));
EXPECT_EQ("", actual.string()); EXPECT_EQ("", actual.string());
} }
@ -307,16 +306,16 @@ TEST(ConcatPathsTest, Path1ContainsPathSep) {
} }
TEST(ConcatPathsTest, Path2ContainsPathSep) { TEST(ConcatPathsTest, Path2ContainsPathSep) {
FilePath actual = FilePath::ConcatPaths( FilePath actual =
FilePath("foo" GTEST_PATH_SEP_), FilePath::ConcatPaths(FilePath("foo" GTEST_PATH_SEP_),
FilePath("bar" GTEST_PATH_SEP_ "bar.xml")); FilePath("bar" GTEST_PATH_SEP_ "bar.xml"));
EXPECT_EQ("foo" GTEST_PATH_SEP_ "bar" GTEST_PATH_SEP_ "bar.xml", EXPECT_EQ("foo" GTEST_PATH_SEP_ "bar" GTEST_PATH_SEP_ "bar.xml",
actual.string()); actual.string());
} }
TEST(ConcatPathsTest, Path2EndsWithPathSep) { TEST(ConcatPathsTest, Path2EndsWithPathSep) {
FilePath actual = FilePath::ConcatPaths(FilePath("foo"), FilePath actual =
FilePath("bar" GTEST_PATH_SEP_)); FilePath::ConcatPaths(FilePath("foo"), FilePath("bar" GTEST_PATH_SEP_));
EXPECT_EQ("foo" GTEST_PATH_SEP_ "bar" GTEST_PATH_SEP_, actual.string()); EXPECT_EQ("foo" GTEST_PATH_SEP_ "bar" GTEST_PATH_SEP_, actual.string());
} }
@ -332,7 +331,8 @@ TEST(RemoveTrailingPathSeparatorTest, FileNoSlashString) {
// RemoveTrailingPathSeparator "foo/" -> "foo" // RemoveTrailingPathSeparator "foo/" -> "foo"
TEST(RemoveTrailingPathSeparatorTest, ShouldRemoveTrailingSeparator) { TEST(RemoveTrailingPathSeparatorTest, ShouldRemoveTrailingSeparator) {
EXPECT_EQ("foo", EXPECT_EQ(
"foo",
FilePath("foo" GTEST_PATH_SEP_).RemoveTrailingPathSeparator().string()); FilePath("foo" GTEST_PATH_SEP_).RemoveTrailingPathSeparator().string());
#if GTEST_HAS_ALT_PATH_SEP_ #if GTEST_HAS_ALT_PATH_SEP_
EXPECT_EQ("foo", FilePath("foo/").RemoveTrailingPathSeparator().string()); EXPECT_EQ("foo", FilePath("foo/").RemoveTrailingPathSeparator().string());
@ -343,18 +343,19 @@ TEST(RemoveTrailingPathSeparatorTest, ShouldRemoveTrailingSeparator) {
TEST(RemoveTrailingPathSeparatorTest, ShouldRemoveLastSeparator) { TEST(RemoveTrailingPathSeparatorTest, ShouldRemoveLastSeparator) {
EXPECT_EQ("foo" GTEST_PATH_SEP_ "bar", EXPECT_EQ("foo" GTEST_PATH_SEP_ "bar",
FilePath("foo" GTEST_PATH_SEP_ "bar" GTEST_PATH_SEP_) FilePath("foo" GTEST_PATH_SEP_ "bar" GTEST_PATH_SEP_)
.RemoveTrailingPathSeparator().string()); .RemoveTrailingPathSeparator()
.string());
} }
// RemoveTrailingPathSeparator "foo/bar" -> "foo/bar" // RemoveTrailingPathSeparator "foo/bar" -> "foo/bar"
TEST(RemoveTrailingPathSeparatorTest, ShouldReturnUnmodified) { TEST(RemoveTrailingPathSeparatorTest, ShouldReturnUnmodified) {
EXPECT_EQ("foo" GTEST_PATH_SEP_ "bar", EXPECT_EQ("foo" GTEST_PATH_SEP_ "bar", FilePath("foo" GTEST_PATH_SEP_ "bar")
FilePath("foo" GTEST_PATH_SEP_ "bar") .RemoveTrailingPathSeparator()
.RemoveTrailingPathSeparator().string()); .string());
} }
TEST(DirectoryTest, RootDirectoryExists) { 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 char current_drive[_MAX_PATH]; // NOLINT
current_drive[0] = static_cast<char>(_getdrive() + 'A' - 1); current_drive[0] = static_cast<char>(_getdrive() + 'A' - 1);
current_drive[1] = ':'; current_drive[1] = ':';
@ -393,12 +394,12 @@ TEST(DirectoryTest, EmptyPathDirectoryDoesNotExist) {
TEST(DirectoryTest, CurrentDirectoryExists) { TEST(DirectoryTest, CurrentDirectoryExists) {
#if GTEST_OS_WINDOWS // We are on Windows. #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());
EXPECT_TRUE(FilePath(".\\").DirectoryExists()); EXPECT_TRUE(FilePath(".\\").DirectoryExists());
# endif // _WIN32_CE #endif // _WIN32_CE
#else #else
EXPECT_TRUE(FilePath(".").DirectoryExists()); EXPECT_TRUE(FilePath(".").DirectoryExists());
EXPECT_TRUE(FilePath("./").DirectoryExists()); EXPECT_TRUE(FilePath("./").DirectoryExists());
@ -411,29 +412,30 @@ TEST(NormalizeTest, MultipleConsecutiveSepaparatorsInMidstring) {
FilePath("foo" GTEST_PATH_SEP_ "bar").string()); FilePath("foo" GTEST_PATH_SEP_ "bar").string());
EXPECT_EQ("foo" GTEST_PATH_SEP_ "bar", EXPECT_EQ("foo" GTEST_PATH_SEP_ "bar",
FilePath("foo" GTEST_PATH_SEP_ GTEST_PATH_SEP_ "bar").string()); FilePath("foo" GTEST_PATH_SEP_ GTEST_PATH_SEP_ "bar").string());
EXPECT_EQ("foo" GTEST_PATH_SEP_ "bar", EXPECT_EQ(
FilePath("foo" GTEST_PATH_SEP_ GTEST_PATH_SEP_ "foo" GTEST_PATH_SEP_ "bar",
GTEST_PATH_SEP_ "bar").string()); FilePath("foo" GTEST_PATH_SEP_ GTEST_PATH_SEP_ GTEST_PATH_SEP_ "bar")
.string());
} }
// "/bar" == //bar" == "///bar" // "/bar" == //bar" == "///bar"
TEST(NormalizeTest, MultipleConsecutiveSepaparatorsAtStringStart) { TEST(NormalizeTest, MultipleConsecutiveSepaparatorsAtStringStart) {
EXPECT_EQ(GTEST_PATH_SEP_ "bar", FilePath(GTEST_PATH_SEP_ "bar").string());
EXPECT_EQ(GTEST_PATH_SEP_ "bar", EXPECT_EQ(GTEST_PATH_SEP_ "bar",
FilePath(GTEST_PATH_SEP_ "bar").string()); FilePath(GTEST_PATH_SEP_ GTEST_PATH_SEP_ "bar").string());
EXPECT_EQ(GTEST_PATH_SEP_ "bar", EXPECT_EQ(
FilePath(GTEST_PATH_SEP_ GTEST_PATH_SEP_ "bar").string()); GTEST_PATH_SEP_ "bar",
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_ GTEST_PATH_SEP_ "bar").string());
} }
// "foo/" == foo//" == "foo///" // "foo/" == foo//" == "foo///"
TEST(NormalizeTest, MultipleConsecutiveSepaparatorsAtStringEnd) { TEST(NormalizeTest, MultipleConsecutiveSepaparatorsAtStringEnd) {
EXPECT_EQ("foo" GTEST_PATH_SEP_, FilePath("foo" GTEST_PATH_SEP_).string());
EXPECT_EQ("foo" GTEST_PATH_SEP_, EXPECT_EQ("foo" GTEST_PATH_SEP_,
FilePath("foo" GTEST_PATH_SEP_).string()); FilePath("foo" GTEST_PATH_SEP_ GTEST_PATH_SEP_).string());
EXPECT_EQ("foo" GTEST_PATH_SEP_, EXPECT_EQ(
FilePath("foo" GTEST_PATH_SEP_ GTEST_PATH_SEP_).string()); "foo" GTEST_PATH_SEP_,
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_ GTEST_PATH_SEP_).string());
} }
#if GTEST_HAS_ALT_PATH_SEP_ #if GTEST_HAS_ALT_PATH_SEP_
@ -442,12 +444,10 @@ TEST(NormalizeTest, MultipleConsecutiveSepaparatorsAtStringEnd) {
// regardless of their combination (e.g. "foo\" =="foo/\" == // regardless of their combination (e.g. "foo\" =="foo/\" ==
// "foo\\/"). // "foo\\/").
TEST(NormalizeTest, MixAlternateSeparatorAtStringEnd) { TEST(NormalizeTest, MixAlternateSeparatorAtStringEnd) {
EXPECT_EQ("foo" GTEST_PATH_SEP_, EXPECT_EQ("foo" GTEST_PATH_SEP_, FilePath("foo/").string());
FilePath("foo/").string());
EXPECT_EQ("foo" GTEST_PATH_SEP_, EXPECT_EQ("foo" GTEST_PATH_SEP_,
FilePath("foo" GTEST_PATH_SEP_ "/").string()); FilePath("foo" GTEST_PATH_SEP_ "/").string());
EXPECT_EQ("foo" GTEST_PATH_SEP_, EXPECT_EQ("foo" GTEST_PATH_SEP_, FilePath("foo//" GTEST_PATH_SEP_).string());
FilePath("foo//" GTEST_PATH_SEP_).string());
} }
#endif #endif
@ -478,15 +478,15 @@ TEST(AssignmentOperatorTest, ConstAssignedToNonConst) {
class DirectoryCreationTest : public Test { class DirectoryCreationTest : public Test {
protected: protected:
void SetUp() override { void SetUp() override {
testdata_path_.Set(FilePath( testdata_path_.Set(
TempDir() + GetCurrentExecutableName().string() + FilePath(TempDir() + GetCurrentExecutableName().string() +
"_directory_creation" GTEST_PATH_SEP_ "test" GTEST_PATH_SEP_)); "_directory_creation" GTEST_PATH_SEP_ "test" GTEST_PATH_SEP_));
testdata_file_.Set(testdata_path_.RemoveTrailingPathSeparator()); testdata_file_.Set(testdata_path_.RemoveTrailingPathSeparator());
unique_file0_.Set(FilePath::MakeFileName(testdata_path_, FilePath("unique"), unique_file0_.Set(
0, "txt")); FilePath::MakeFileName(testdata_path_, FilePath("unique"), 0, "txt"));
unique_file1_.Set(FilePath::MakeFileName(testdata_path_, FilePath("unique"), unique_file1_.Set(
1, "txt")); FilePath::MakeFileName(testdata_path_, FilePath("unique"), 1, "txt"));
remove(testdata_file_.c_str()); remove(testdata_file_.c_str());
remove(unique_file0_.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: // a directory named 'test' from a file named 'test'. Example names:
FilePath testdata_path_; // "/tmp/directory_creation/test/" FilePath testdata_path_; // "/tmp/directory_creation/test/"
FilePath testdata_file_; // "/tmp/directory_creation/test" FilePath testdata_file_; // "/tmp/directory_creation/test"
FilePath unique_file0_; // "/tmp/directory_creation/test/unique.txt" FilePath unique_file0_; // "/tmp/directory_creation/test/unique.txt"
FilePath unique_file1_; // "/tmp/directory_creation/test/unique_1.txt" FilePath unique_file1_; // "/tmp/directory_creation/test/unique_1.txt"
}; };
TEST_F(DirectoryCreationTest, CreateDirectoriesRecursively) { TEST_F(DirectoryCreationTest, CreateDirectoriesRecursively) {
@ -530,8 +530,8 @@ TEST_F(DirectoryCreationTest, CreateDirectoriesForAlreadyExistingPath) {
} }
TEST_F(DirectoryCreationTest, CreateDirectoriesAndUniqueFilename) { TEST_F(DirectoryCreationTest, CreateDirectoriesAndUniqueFilename) {
FilePath file_path(FilePath::GenerateUniqueFileName(testdata_path_, FilePath file_path(FilePath::GenerateUniqueFileName(
FilePath("unique"), "txt")); testdata_path_, FilePath("unique"), "txt"));
EXPECT_EQ(unique_file0_.string(), file_path.string()); EXPECT_EQ(unique_file0_.string(), file_path.string());
EXPECT_FALSE(file_path.FileOrDirectoryExists()); // file not there EXPECT_FALSE(file_path.FileOrDirectoryExists()); // file not there
@ -540,8 +540,8 @@ TEST_F(DirectoryCreationTest, CreateDirectoriesAndUniqueFilename) {
CreateTextFile(file_path.c_str()); CreateTextFile(file_path.c_str());
EXPECT_TRUE(file_path.FileOrDirectoryExists()); EXPECT_TRUE(file_path.FileOrDirectoryExists());
FilePath file_path2(FilePath::GenerateUniqueFileName(testdata_path_, FilePath file_path2(FilePath::GenerateUniqueFileName(
FilePath("unique"), "txt")); testdata_path_, FilePath("unique"), "txt"));
EXPECT_EQ(unique_file1_.string(), file_path2.string()); EXPECT_EQ(unique_file1_.string(), file_path2.string());
EXPECT_FALSE(file_path2.FileOrDirectoryExists()); // file not there EXPECT_FALSE(file_path2.FileOrDirectoryExists()); // file not there
CreateTextFile(file_path2.c_str()); CreateTextFile(file_path2.c_str());
@ -614,14 +614,16 @@ TEST(FilePathTest, IsAbsolutePath) {
EXPECT_FALSE(FilePath("is" GTEST_PATH_SEP_ "relative").IsAbsolutePath()); EXPECT_FALSE(FilePath("is" GTEST_PATH_SEP_ "relative").IsAbsolutePath());
EXPECT_FALSE(FilePath("").IsAbsolutePath()); EXPECT_FALSE(FilePath("").IsAbsolutePath());
#if GTEST_OS_WINDOWS #if GTEST_OS_WINDOWS
EXPECT_TRUE(FilePath("c:\\" GTEST_PATH_SEP_ "is_not" EXPECT_TRUE(
GTEST_PATH_SEP_ "relative").IsAbsolutePath()); FilePath("c:\\" GTEST_PATH_SEP_ "is_not" GTEST_PATH_SEP_ "relative")
.IsAbsolutePath());
EXPECT_FALSE(FilePath("c:foo" GTEST_PATH_SEP_ "bar").IsAbsolutePath()); EXPECT_FALSE(FilePath("c:foo" GTEST_PATH_SEP_ "bar").IsAbsolutePath());
EXPECT_TRUE(FilePath("c:/" GTEST_PATH_SEP_ "is_not" EXPECT_TRUE(
GTEST_PATH_SEP_ "relative").IsAbsolutePath()); FilePath("c:/" GTEST_PATH_SEP_ "is_not" GTEST_PATH_SEP_ "relative")
.IsAbsolutePath());
#else #else
EXPECT_TRUE(FilePath(GTEST_PATH_SEP_ "is_not" GTEST_PATH_SEP_ "relative") EXPECT_TRUE(FilePath(GTEST_PATH_SEP_ "is_not" GTEST_PATH_SEP_ "relative")
.IsAbsolutePath()); .IsAbsolutePath());
#endif // GTEST_OS_WINDOWS #endif // GTEST_OS_WINDOWS
} }

View File

@ -27,7 +27,6 @@
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// Unit test for Google Test test filters. // Unit test for Google Test test filters.
// //
// A user can specify which test(s) in a Google Test program to run via // A user can specify which test(s) in a Google Test program to run via
@ -43,87 +42,57 @@ namespace {
// Test case FooTest. // 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) { TEST_F(FooTest, Xyz) { FAIL() << "Expected failure."; }
FAIL() << "Expected failure.";
}
// Test case BarTest. // 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) { TEST(BarTest, DISABLED_TestFour) { FAIL() << "Expected failure."; }
FAIL() << "Expected failure.";
}
TEST(BarTest, DISABLED_TestFive) { TEST(BarTest, DISABLED_TestFive) { FAIL() << "Expected failure."; }
FAIL() << "Expected failure.";
}
// Test case BazTest. // Test case BazTest.
TEST(BazTest, TestOne) { TEST(BazTest, TestOne) { FAIL() << "Expected failure."; }
FAIL() << "Expected failure.";
}
TEST(BazTest, TestA) { TEST(BazTest, TestA) {}
}
TEST(BazTest, TestB) { TEST(BazTest, TestB) {}
}
TEST(BazTest, DISABLED_TestC) { TEST(BazTest, DISABLED_TestC) { FAIL() << "Expected failure."; }
FAIL() << "Expected failure.";
}
// Test case HasDeathTest // Test case HasDeathTest
TEST(HasDeathTest, Test1) { TEST(HasDeathTest, Test1) { EXPECT_DEATH_IF_SUPPORTED(exit(1), ".*"); }
EXPECT_DEATH_IF_SUPPORTED(exit(1), ".*");
}
// We need at least two death tests to make sure that the all death tests // We need at least two death tests to make sure that the all death tests
// aren't on the first shard. // aren't on the first shard.
TEST(HasDeathTest, Test2) { TEST(HasDeathTest, Test2) { EXPECT_DEATH_IF_SUPPORTED(exit(1), ".*"); }
EXPECT_DEATH_IF_SUPPORTED(exit(1), ".*");
}
// Test case FoobarTest // Test case FoobarTest
TEST(DISABLED_FoobarTest, Test1) { TEST(DISABLED_FoobarTest, Test1) { FAIL() << "Expected failure."; }
FAIL() << "Expected failure.";
}
TEST(DISABLED_FoobarTest, DISABLED_Test2) { TEST(DISABLED_FoobarTest, DISABLED_Test2) { FAIL() << "Expected failure."; }
FAIL() << "Expected failure.";
}
// Test case FoobarbazTest // Test case FoobarbazTest
TEST(DISABLED_FoobarbazTest, TestA) { TEST(DISABLED_FoobarbazTest, TestA) { FAIL() << "Expected failure."; }
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(SeqP, ParamTest, testing::Values(1, 2));
INSTANTIATE_TEST_SUITE_P(SeqQ, ParamTest, testing::Values(5, 6)); INSTANTIATE_TEST_SUITE_P(SeqQ, ParamTest, testing::Values(5, 6));

View File

@ -27,7 +27,6 @@
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// Unit test for Google Test's --gtest_list_tests flag. // Unit test for Google Test's --gtest_list_tests flag.
// //
// A user can ask Google Test to list all tests that will run // A user can ask Google Test to list all tests that will run
@ -40,38 +39,27 @@
#include "gtest/gtest.h" #include "gtest/gtest.h"
// Several different test cases and tests that will be listed. // 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. // A group of value-parameterized tests.
@ -86,70 +74,66 @@ class MyType {
}; };
// Teaches Google Test how to print a MyType. // Teaches Google Test how to print a MyType.
void PrintTo(const MyType& x, std::ostream* os) { void PrintTo(const MyType& x, std::ostream* os) { *os << x.value(); }
*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( INSTANTIATE_TEST_SUITE_P(
MyInstantiation, ValueParamTest, MyInstantiation, ValueParamTest,
testing::Values(MyType("one line"), testing::Values(
MyType("two\nlines"), MyType("one line"), MyType("two\nlines"),
MyType("a very\nloooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong line"))); // NOLINT MyType("a "
"very\nloooooooooooooooooooooooooooooooooooooooooooooooooooooooo"
"ooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo"
"ooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo"
"ooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo"
"ooooong line"))); // NOLINT
// A group of typed tests. // A group of typed tests.
// A deliberately long type name for testing the line-truncating // A deliberately long type name for testing the line-truncating
// behavior when printing a type parameter. // behavior when printing a type parameter.
class VeryLoooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooogName { // NOLINT class
VeryLoooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooogName { // NOLINT
}; };
template <typename T> template <typename T>
class TypedTest : public testing::Test { class TypedTest : public testing::Test {};
};
template <typename T, int kSize> template <typename T, int kSize>
class MyArray { class MyArray {};
};
typedef testing::Types<VeryLoooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooogName, // NOLINT typedef testing::Types<
int*, MyArray<bool, 42> > MyTypes; VeryLoooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooogName, // NOLINT
int*, MyArray<bool, 42> >
MyTypes;
TYPED_TEST_SUITE(TypedTest, 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. // A group of type-parameterized tests.
template <typename T> template <typename T>
class TypeParamTest : public testing::Test { class TypeParamTest : public testing::Test {};
};
TYPED_TEST_SUITE_P(TypeParamTest); 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); REGISTER_TYPED_TEST_SUITE_P(TypeParamTest, TestA, TestB);
INSTANTIATE_TYPED_TEST_SUITE_P(My, TypeParamTest, MyTypes); INSTANTIATE_TYPED_TEST_SUITE_P(My, TypeParamTest, MyTypes);
int main(int argc, char **argv) { int main(int argc, char** argv) {
::testing::InitGoogleTest(&argc, argv); ::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS(); return RUN_ALL_TESTS();

View File

@ -41,10 +41,10 @@ using ::testing::AddGlobalTestEnvironment;
using ::testing::Environment; using ::testing::Environment;
using ::testing::InitGoogleTest; using ::testing::InitGoogleTest;
using ::testing::Test; using ::testing::Test;
using ::testing::TestSuite;
using ::testing::TestEventListener; using ::testing::TestEventListener;
using ::testing::TestInfo; using ::testing::TestInfo;
using ::testing::TestPartResult; using ::testing::TestPartResult;
using ::testing::TestSuite;
using ::testing::UnitTest; using ::testing::UnitTest;
// Used by tests to register their events. // Used by tests to register their events.
@ -65,8 +65,8 @@ class EventRecordingListener : public TestEventListener {
void OnTestIterationStart(const UnitTest& /*unit_test*/, void OnTestIterationStart(const UnitTest& /*unit_test*/,
int iteration) override { int iteration) override {
Message message; Message message;
message << GetFullMethodName("OnTestIterationStart") message << GetFullMethodName("OnTestIterationStart") << "(" << iteration
<< "(" << iteration << ")"; << ")";
g_events->push_back(message.GetString()); g_events->push_back(message.GetString());
} }
@ -112,8 +112,8 @@ class EventRecordingListener : public TestEventListener {
void OnTestIterationEnd(const UnitTest& /*unit_test*/, void OnTestIterationEnd(const UnitTest& /*unit_test*/,
int iteration) override { int iteration) override {
Message message; Message message;
message << GetFullMethodName("OnTestIterationEnd") message << GetFullMethodName("OnTestIterationEnd") << "(" << iteration
<< "(" << iteration << ")"; << ")";
g_events->push_back(message.GetString()); g_events->push_back(message.GetString());
} }
@ -122,9 +122,7 @@ class EventRecordingListener : public TestEventListener {
} }
private: private:
std::string GetFullMethodName(const char* name) { std::string GetFullMethodName(const char* name) { return name_ + "." + name; }
return name_ + "." + name;
}
std::string name_; std::string name_;
}; };
@ -252,22 +250,21 @@ void VerifyResults(const std::vector<std::string>& data,
EXPECT_EQ(expected_data_size, actual_size); EXPECT_EQ(expected_data_size, actual_size);
// Compares the common prefix. // Compares the common prefix.
const size_t shorter_size = expected_data_size <= actual_size ? const size_t shorter_size =
expected_data_size : actual_size; expected_data_size <= actual_size ? expected_data_size : actual_size;
size_t i = 0; size_t i = 0;
for (; i < shorter_size; ++i) { for (; i < shorter_size; ++i) {
ASSERT_STREQ(expected_data[i], data[i].c_str()) ASSERT_STREQ(expected_data[i], data[i].c_str()) << "at position " << i;
<< "at position " << i;
} }
// Prints extra elements in the actual data. // Prints extra elements in the actual data.
for (; i < actual_size; ++i) { for (; i < actual_size; ++i) {
printf(" Actual event #%lu: %s\n", printf(" Actual event #%lu: %s\n", static_cast<unsigned long>(i),
static_cast<unsigned long>(i), data[i].c_str()); data[i].c_str());
} }
} }
int main(int argc, char **argv) { int main(int argc, char** argv) {
std::vector<std::string> events; std::vector<std::string> events;
g_events = &events; g_events = &events;
InitGoogleTest(&argc, argv); InitGoogleTest(&argc, argv);
@ -506,14 +503,12 @@ int main(int argc, char **argv) {
"1st.OnTestProgramEnd"}; "1st.OnTestProgramEnd"};
#endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_ #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
VerifyResults(events, VerifyResults(events, expected_events,
expected_events, sizeof(expected_events) / sizeof(expected_events[0]));
sizeof(expected_events)/sizeof(expected_events[0]));
// We need to check manually for ad hoc test failures that happen after // We need to check manually for ad hoc test failures that happen after
// RUN_ALL_TESTS finishes. // RUN_ALL_TESTS finishes.
if (UnitTest::GetInstance()->Failed()) if (UnitTest::GetInstance()->Failed()) ret_val = 1;
ret_val = 1;
return ret_val; return ret_val;
} }

View File

@ -31,7 +31,6 @@
// Tests for the Message class. // Tests for the Message class.
#include "gtest/gtest-message.h" #include "gtest/gtest-message.h"
#include "gtest/gtest.h" #include "gtest/gtest.h"
namespace { namespace {
@ -69,8 +68,9 @@ TEST(MessageTest, StreamsFloat) {
// Tests streaming a double. // Tests streaming a double.
TEST(MessageTest, StreamsDouble) { TEST(MessageTest, StreamsDouble) {
const std::string s = (Message() << 1260570880.4555497 << " " const std::string s =
<< 1260572265.1954534).GetString(); (Message() << 1260570880.4555497 << " " << 1260572265.1954534)
.GetString();
// Both numbers should be printed with enough precision. // Both numbers should be printed with enough precision.
EXPECT_PRED_FORMAT2(testing::IsSubstring, "1260570880.45", s.c_str()); EXPECT_PRED_FORMAT2(testing::IsSubstring, "1260570880.45", s.c_str());
EXPECT_PRED_FORMAT2(testing::IsSubstring, " 1260572265.19", 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. // Tests that we can output strings containing embedded NULs.
TEST(MessageTest, StreamsStringWithEmbeddedNUL) { TEST(MessageTest, StreamsStringWithEmbeddedNUL) {
const char char_array_with_nul[] = const char char_array_with_nul[] = "Here's a NUL\0 and some more string";
"Here's a NUL\0 and some more string";
const ::std::string string_with_nul(char_array_with_nul, const ::std::string string_with_nul(char_array_with_nul,
sizeof(char_array_with_nul) - 1); sizeof(char_array_with_nul) - 1);
EXPECT_EQ("Here's a NUL\\0 and some more string", 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 // Tests that basic IO manipulators (endl, ends, and flush) can be
// streamed to Message. // streamed to Message.
TEST(MessageTest, StreamsBasicIoManip) { TEST(MessageTest, StreamsBasicIoManip) {
EXPECT_EQ("Line 1.\nA NUL char \\0 in line 2.", EXPECT_EQ(
(Message() << "Line 1." << std::endl "Line 1.\nA NUL char \\0 in line 2.",
<< "A NUL char " << std::ends << std::flush (Message() << "Line 1." << std::endl
<< " in line 2.").GetString()); << "A NUL char " << std::ends << std::flush << " in line 2.")
.GetString());
} }
// Tests Message::GetString() // Tests Message::GetString()

View File

@ -39,9 +39,9 @@
#include "gtest/gtest.h" #include "gtest/gtest.h"
#if GTEST_OS_WINDOWS_MOBILE #if GTEST_OS_WINDOWS_MOBILE
# include <windows.h> #include <windows.h>
#elif GTEST_OS_WINDOWS #elif GTEST_OS_WINDOWS
# include <direct.h> #include <direct.h>
#elif GTEST_OS_OS2 #elif GTEST_OS_OS2
// For strcasecmp on OS/2 // For strcasecmp on OS/2
#include <strings.h> #include <strings.h>
@ -85,9 +85,9 @@ TEST(XmlOutputTest, GetOutputFileSingleFile) {
TEST(XmlOutputTest, GetOutputFileFromDirectoryPath) { TEST(XmlOutputTest, GetOutputFileFromDirectoryPath) {
GTEST_FLAG_SET(output, "xml:path" GTEST_PATH_SEP_); GTEST_FLAG_SET(output, "xml:path" GTEST_PATH_SEP_);
const std::string expected_output_file = const std::string expected_output_file =
GetAbsolutePathOf( GetAbsolutePathOf(FilePath(std::string("path") + GTEST_PATH_SEP_ +
FilePath(std::string("path") + GTEST_PATH_SEP_ + GetCurrentExecutableName().string() + ".xml"))
GetCurrentExecutableName().string() + ".xml")).string(); .string();
const std::string& output_file = const std::string& output_file =
UnitTestOptions::GetAbsolutePathToOutputFile(); UnitTestOptions::GetAbsolutePathToOutputFile();
#if GTEST_OS_WINDOWS #if GTEST_OS_WINDOWS
@ -115,13 +115,10 @@ TEST(OutputFileHelpersTest, GetCurrentExecutableName) {
const bool success = exe_str == "app"; const bool success = exe_str == "app";
#else #else
const bool success = const bool success =
exe_str == "googletest-options-test" || exe_str == "googletest-options-test" || exe_str == "gtest_all_test" ||
exe_str == "gtest_all_test" || exe_str == "lt-gtest_all_test" || exe_str == "gtest_dll_test";
exe_str == "lt-gtest_all_test" ||
exe_str == "gtest_dll_test";
#endif // GTEST_OS_WINDOWS #endif // GTEST_OS_WINDOWS
if (!success) if (!success) FAIL() << "GetCurrentExecutableName() returns " << exe_str;
FAIL() << "GetCurrentExecutableName() returns " << exe_str;
} }
#if !GTEST_OS_FUCHSIA #if !GTEST_OS_FUCHSIA
@ -145,23 +142,26 @@ class XmlOutputChangeDirTest : public Test {
TEST_F(XmlOutputChangeDirTest, PreserveOriginalWorkingDirWithDefault) { TEST_F(XmlOutputChangeDirTest, PreserveOriginalWorkingDirWithDefault) {
GTEST_FLAG_SET(output, ""); GTEST_FLAG_SET(output, "");
EXPECT_EQ(FilePath::ConcatPaths(original_working_dir_, EXPECT_EQ(
FilePath("test_detail.xml")).string(), FilePath::ConcatPaths(original_working_dir_, FilePath("test_detail.xml"))
UnitTestOptions::GetAbsolutePathToOutputFile()); .string(),
UnitTestOptions::GetAbsolutePathToOutputFile());
} }
TEST_F(XmlOutputChangeDirTest, PreserveOriginalWorkingDirWithDefaultXML) { TEST_F(XmlOutputChangeDirTest, PreserveOriginalWorkingDirWithDefaultXML) {
GTEST_FLAG_SET(output, "xml"); GTEST_FLAG_SET(output, "xml");
EXPECT_EQ(FilePath::ConcatPaths(original_working_dir_, EXPECT_EQ(
FilePath("test_detail.xml")).string(), FilePath::ConcatPaths(original_working_dir_, FilePath("test_detail.xml"))
UnitTestOptions::GetAbsolutePathToOutputFile()); .string(),
UnitTestOptions::GetAbsolutePathToOutputFile());
} }
TEST_F(XmlOutputChangeDirTest, PreserveOriginalWorkingDirWithRelativeFile) { TEST_F(XmlOutputChangeDirTest, PreserveOriginalWorkingDirWithRelativeFile) {
GTEST_FLAG_SET(output, "xml:filename.abc"); GTEST_FLAG_SET(output, "xml:filename.abc");
EXPECT_EQ(FilePath::ConcatPaths(original_working_dir_, EXPECT_EQ(
FilePath("filename.abc")).string(), FilePath::ConcatPaths(original_working_dir_, FilePath("filename.abc"))
UnitTestOptions::GetAbsolutePathToOutputFile()); .string(),
UnitTestOptions::GetAbsolutePathToOutputFile());
} }
TEST_F(XmlOutputChangeDirTest, PreserveOriginalWorkingDirWithRelativePath) { TEST_F(XmlOutputChangeDirTest, PreserveOriginalWorkingDirWithRelativePath) {
@ -170,7 +170,8 @@ TEST_F(XmlOutputChangeDirTest, PreserveOriginalWorkingDirWithRelativePath) {
FilePath::ConcatPaths( FilePath::ConcatPaths(
original_working_dir_, original_working_dir_,
FilePath(std::string("path") + GTEST_PATH_SEP_ + FilePath(std::string("path") + GTEST_PATH_SEP_ +
GetCurrentExecutableName().string() + ".xml")).string(); GetCurrentExecutableName().string() + ".xml"))
.string();
const std::string& output_file = const std::string& output_file =
UnitTestOptions::GetAbsolutePathToOutputFile(); UnitTestOptions::GetAbsolutePathToOutputFile();
#if GTEST_OS_WINDOWS #if GTEST_OS_WINDOWS

View File

@ -33,12 +33,12 @@
// desired messages. Therefore, most tests in this file are MEANT TO // desired messages. Therefore, most tests in this file are MEANT TO
// FAIL. // FAIL.
#include <stdlib.h>
#include "gtest/gtest-spi.h" #include "gtest/gtest-spi.h"
#include "gtest/gtest.h" #include "gtest/gtest.h"
#include "src/gtest-internal-inl.h" #include "src/gtest-internal-inl.h"
#include <stdlib.h>
#if _MSC_VER #if _MSC_VER
GTEST_DISABLE_MSC_WARNINGS_PUSH_(4127 /* conditional expression is constant */) GTEST_DISABLE_MSC_WARNINGS_PUSH_(4127 /* conditional expression is constant */)
#endif // _MSC_VER #endif // _MSC_VER
@ -56,9 +56,7 @@ namespace posix = ::testing::internal::posix;
// Tests catching fatal failures. // Tests catching fatal failures.
// A subroutine used by the following test. // A subroutine used by the following test.
void TestEq1(int x) { void TestEq1(int x) { ASSERT_EQ(1, x); }
ASSERT_EQ(1, x);
}
// This function calls a test subroutine, catches the fatal failure it // This function calls a test subroutine, catches the fatal failure it
// generates, and then returns early. // generates, and then returns early.
@ -76,24 +74,19 @@ void TryTestSubroutine() {
FAIL() << "This should never be reached."; 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 // Tests that parameters of failing parameterized tests are printed in the
// failing test summary. // failing test summary.
class FailingParamTest : public testing::TestWithParam<int> {}; class FailingParamTest : public testing::TestWithParam<int> {};
TEST_P(FailingParamTest, Fails) { TEST_P(FailingParamTest, Fails) { EXPECT_EQ(1, GetParam()); }
EXPECT_EQ(1, GetParam());
}
// This generates a test which will fail. Google Test is expected to print // This generates a test which will fail. Google Test is expected to print
// its parameter when it outputs the list of all failed tests. // its parameter when it outputs the list of all failed tests.
INSTANTIATE_TEST_SUITE_P(PrintingFailingParams, INSTANTIATE_TEST_SUITE_P(PrintingFailingParams, FailingParamTest,
FailingParamTest,
testing::Values(2)); testing::Values(2));
// Tests that an empty value for the test suite basename yields just // 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. // Tests HasFatalFailure() after a failed EXPECT check.
TEST(FatalFailureTest, NonfatalFailureInSubroutine) { TEST(FatalFailureTest, NonfatalFailureInSubroutine) {
printf("(expecting a failure on false)\n"); 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. ASSERT_FALSE(HasFatalFailure()); // This should succeed.
} }
// Tests interleaving user logging and Google Test assertions. // Tests interleaving user logging and Google Test assertions.
TEST(LoggingTest, InterleavingLoggingAndAssertions) { TEST(LoggingTest, InterleavingLoggingAndAssertions) {
static const int a[4] = { static const int a[4] = {3, 9, 2, 6};
3, 9, 2, 6
};
printf("(expecting 2 failures on (3) >= (a[i]))\n"); 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); printf("i == %d\n", i);
EXPECT_GE(3, a[i]); EXPECT_GE(3, a[i]);
} }
@ -297,16 +288,14 @@ struct CheckPoints {
static void ThreadWithScopedTrace(CheckPoints* check_points) { static void ThreadWithScopedTrace(CheckPoints* check_points) {
{ {
SCOPED_TRACE("Trace B"); SCOPED_TRACE("Trace B");
ADD_FAILURE() ADD_FAILURE() << "Expected failure #1 (in thread B, only trace B alive).";
<< "Expected failure #1 (in thread B, only trace B alive).";
check_points->n1.Notify(); check_points->n1.Notify();
check_points->n2.WaitForNotification(); check_points->n2.WaitForNotification();
ADD_FAILURE() ADD_FAILURE()
<< "Expected failure #3 (in thread B, trace A & B both alive)."; << "Expected failure #3 (in thread B, trace A & B both alive).";
} // Trace B dies here. } // Trace B dies here.
ADD_FAILURE() ADD_FAILURE() << "Expected failure #4 (in thread B, only trace A alive).";
<< "Expected failure #4 (in thread B, only trace A alive).";
check_points->n3.Notify(); check_points->n3.Notify();
} }
@ -325,11 +314,9 @@ TEST(SCOPED_TRACETest, WorksConcurrently) {
check_points.n2.Notify(); check_points.n2.Notify();
check_points.n3.WaitForNotification(); check_points.n3.WaitForNotification();
ADD_FAILURE() ADD_FAILURE() << "Expected failure #5 (in thread A, only trace A alive).";
<< "Expected failure #5 (in thread A, only trace A alive).";
} // Trace A dies here. } // Trace A dies here.
ADD_FAILURE() ADD_FAILURE() << "Expected failure #6 (in thread A, no trace alive).";
<< "Expected failure #6 (in thread A, no trace alive).";
thread.Join(); thread.Join();
} }
#endif // GTEST_IS_THREADSAFE #endif // GTEST_IS_THREADSAFE
@ -412,9 +399,7 @@ class FatalFailureInFixtureConstructorTest : public testing::Test {
} }
private: private:
void Init() { void Init() { FAIL() << "Expected failure #1, in the test fixture c'tor."; }
FAIL() << "Expected failure #1, in the test fixture c'tor.";
}
}; };
TEST_F(FatalFailureInFixtureConstructorTest, FailureInConstructor) { TEST_F(FatalFailureInFixtureConstructorTest, FailureInConstructor) {
@ -436,9 +421,7 @@ class NonFatalFailureInSetUpTest : public testing::Test {
void TearDown() override { FAIL() << "Expected failure #3, in TearDown()."; } void TearDown() override { FAIL() << "Expected failure #3, in TearDown()."; }
private: private:
void Deinit() { void Deinit() { FAIL() << "Expected failure #4, in the test fixture d'tor."; }
FAIL() << "Expected failure #4, in the test fixture d'tor.";
}
}; };
TEST_F(NonFatalFailureInSetUpTest, FailureInSetUp) { TEST_F(NonFatalFailureInSetUpTest, FailureInSetUp) {
@ -458,9 +441,7 @@ class FatalFailureInSetUpTest : public testing::Test {
void TearDown() override { FAIL() << "Expected failure #2, in TearDown()."; } void TearDown() override { FAIL() << "Expected failure #2, in TearDown()."; }
private: private:
void Deinit() { void Deinit() { FAIL() << "Expected failure #3, in the test fixture d'tor."; }
FAIL() << "Expected failure #3, in the test fixture d'tor.";
}
}; };
TEST_F(FatalFailureInSetUpTest, FailureInSetUp) { TEST_F(FatalFailureInSetUpTest, FailureInSetUp) {
@ -488,14 +469,12 @@ TEST(GtestFailAtTest, MessageContainsSpecifiedFileAndLineNumber) {
namespace foo { namespace foo {
class MixedUpTestSuiteTest : public testing::Test { class MixedUpTestSuiteTest : public testing::Test {};
};
TEST_F(MixedUpTestSuiteTest, FirstTestFromNamespaceFoo) {} TEST_F(MixedUpTestSuiteTest, FirstTestFromNamespaceFoo) {}
TEST_F(MixedUpTestSuiteTest, SecondTestFromNamespaceFoo) {} TEST_F(MixedUpTestSuiteTest, SecondTestFromNamespaceFoo) {}
class MixedUpTestSuiteWithSameTestNameTest : public testing::Test { class MixedUpTestSuiteWithSameTestNameTest : public testing::Test {};
};
TEST_F(MixedUpTestSuiteWithSameTestNameTest, TEST_F(MixedUpTestSuiteWithSameTestNameTest,
TheSecondTestWithThisNameShouldFail) {} TheSecondTestWithThisNameShouldFail) {}
@ -504,16 +483,14 @@ TEST_F(MixedUpTestSuiteWithSameTestNameTest,
namespace bar { namespace bar {
class MixedUpTestSuiteTest : public testing::Test { class MixedUpTestSuiteTest : public testing::Test {};
};
// The following two tests are expected to fail. We rely on the // The following two tests are expected to fail. We rely on the
// golden file to check that Google Test generates the right error message. // golden file to check that Google Test generates the right error message.
TEST_F(MixedUpTestSuiteTest, ThisShouldFail) {} TEST_F(MixedUpTestSuiteTest, ThisShouldFail) {}
TEST_F(MixedUpTestSuiteTest, ThisShouldFailToo) {} 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 // Expected to fail. We rely on the golden file to check that Google Test
// generates the right error message. // generates the right error message.
@ -527,8 +504,7 @@ TEST_F(MixedUpTestSuiteWithSameTestNameTest,
// test case checks the scenario where TEST_F appears before TEST, and // test case checks the scenario where TEST_F appears before TEST, and
// the second one checks where TEST appears before TEST_F. // 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) {} 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. // generates the right error message.
TEST(TEST_F_before_TEST_in_same_test_case, DefinedUsingTESTAndShouldFail) {} 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) {} TEST(TEST_before_TEST_F_in_same_test_case, DefinedUsingTEST) {}
// Expected to fail. We rely on the golden file to check that Google Test // Expected to fail. We rely on the golden file to check that Google Test
// generates the right error message. // 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(). // Used for testing EXPECT_NONFATAL_FAILURE() and EXPECT_FATAL_FAILURE().
int global_integer = 0; int global_integer = 0;
@ -552,9 +526,9 @@ int global_integer = 0;
// Tests that EXPECT_NONFATAL_FAILURE() can reference global variables. // Tests that EXPECT_NONFATAL_FAILURE() can reference global variables.
TEST(ExpectNonfatalFailureTest, CanReferenceGlobalVariables) { TEST(ExpectNonfatalFailureTest, CanReferenceGlobalVariables) {
global_integer = 0; global_integer = 0;
EXPECT_NONFATAL_FAILURE({ EXPECT_NONFATAL_FAILURE(
EXPECT_EQ(1, global_integer) << "Expected non-fatal failure."; { EXPECT_EQ(1, global_integer) << "Expected non-fatal failure."; },
}, "Expected non-fatal failure."); "Expected non-fatal failure.");
} }
// Tests that EXPECT_NONFATAL_FAILURE() can reference local variables // Tests that EXPECT_NONFATAL_FAILURE() can reference local variables
@ -563,53 +537,48 @@ TEST(ExpectNonfatalFailureTest, CanReferenceLocalVariables) {
int m = 0; int m = 0;
static int n; static int n;
n = 1; n = 1;
EXPECT_NONFATAL_FAILURE({ EXPECT_NONFATAL_FAILURE({ EXPECT_EQ(m, n) << "Expected non-fatal failure."; },
EXPECT_EQ(m, n) << "Expected non-fatal failure."; "Expected non-fatal failure.");
}, "Expected non-fatal failure.");
} }
// Tests that EXPECT_NONFATAL_FAILURE() succeeds when there is exactly // Tests that EXPECT_NONFATAL_FAILURE() succeeds when there is exactly
// one non-fatal failure and no fatal failure. // one non-fatal failure and no fatal failure.
TEST(ExpectNonfatalFailureTest, SucceedsWhenThereIsOneNonfatalFailure) { TEST(ExpectNonfatalFailureTest, SucceedsWhenThereIsOneNonfatalFailure) {
EXPECT_NONFATAL_FAILURE({ EXPECT_NONFATAL_FAILURE({ ADD_FAILURE() << "Expected non-fatal failure."; },
ADD_FAILURE() << "Expected non-fatal failure."; "Expected non-fatal failure.");
}, "Expected non-fatal failure.");
} }
// Tests that EXPECT_NONFATAL_FAILURE() fails when there is no // Tests that EXPECT_NONFATAL_FAILURE() fails when there is no
// non-fatal failure. // non-fatal failure.
TEST(ExpectNonfatalFailureTest, FailsWhenThereIsNoNonfatalFailure) { TEST(ExpectNonfatalFailureTest, FailsWhenThereIsNoNonfatalFailure) {
printf("(expecting a failure)\n"); printf("(expecting a failure)\n");
EXPECT_NONFATAL_FAILURE({ EXPECT_NONFATAL_FAILURE({}, "");
}, "");
} }
// Tests that EXPECT_NONFATAL_FAILURE() fails when there are two // Tests that EXPECT_NONFATAL_FAILURE() fails when there are two
// non-fatal failures. // non-fatal failures.
TEST(ExpectNonfatalFailureTest, FailsWhenThereAreTwoNonfatalFailures) { TEST(ExpectNonfatalFailureTest, FailsWhenThereAreTwoNonfatalFailures) {
printf("(expecting a failure)\n"); printf("(expecting a failure)\n");
EXPECT_NONFATAL_FAILURE({ EXPECT_NONFATAL_FAILURE(
ADD_FAILURE() << "Expected non-fatal failure 1."; {
ADD_FAILURE() << "Expected non-fatal failure 2."; 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 // Tests that EXPECT_NONFATAL_FAILURE() fails when there is one fatal
// failure. // failure.
TEST(ExpectNonfatalFailureTest, FailsWhenThereIsOneFatalFailure) { TEST(ExpectNonfatalFailureTest, FailsWhenThereIsOneFatalFailure) {
printf("(expecting a failure)\n"); printf("(expecting a failure)\n");
EXPECT_NONFATAL_FAILURE({ EXPECT_NONFATAL_FAILURE({ FAIL() << "Expected fatal failure."; }, "");
FAIL() << "Expected fatal failure.";
}, "");
} }
// Tests that EXPECT_NONFATAL_FAILURE() fails when the statement being // Tests that EXPECT_NONFATAL_FAILURE() fails when the statement being
// tested returns. // tested returns.
TEST(ExpectNonfatalFailureTest, FailsWhenStatementReturns) { TEST(ExpectNonfatalFailureTest, FailsWhenStatementReturns) {
printf("(expecting a failure)\n"); printf("(expecting a failure)\n");
EXPECT_NONFATAL_FAILURE({ EXPECT_NONFATAL_FAILURE({ return; }, "");
return;
}, "");
} }
#if GTEST_HAS_EXCEPTIONS #if GTEST_HAS_EXCEPTIONS
@ -619,10 +588,8 @@ TEST(ExpectNonfatalFailureTest, FailsWhenStatementReturns) {
TEST(ExpectNonfatalFailureTest, FailsWhenStatementThrows) { TEST(ExpectNonfatalFailureTest, FailsWhenStatementThrows) {
printf("(expecting a failure)\n"); printf("(expecting a failure)\n");
try { try {
EXPECT_NONFATAL_FAILURE({ EXPECT_NONFATAL_FAILURE({ throw 0; }, "");
throw 0; } catch (int) { // NOLINT
}, "");
} catch(int) { // NOLINT
} }
} }
@ -631,9 +598,9 @@ TEST(ExpectNonfatalFailureTest, FailsWhenStatementThrows) {
// Tests that EXPECT_FATAL_FAILURE() can reference global variables. // Tests that EXPECT_FATAL_FAILURE() can reference global variables.
TEST(ExpectFatalFailureTest, CanReferenceGlobalVariables) { TEST(ExpectFatalFailureTest, CanReferenceGlobalVariables) {
global_integer = 0; global_integer = 0;
EXPECT_FATAL_FAILURE({ EXPECT_FATAL_FAILURE(
ASSERT_EQ(1, global_integer) << "Expected fatal failure."; { ASSERT_EQ(1, global_integer) << "Expected fatal failure."; },
}, "Expected fatal failure."); "Expected fatal failure.");
} }
// Tests that EXPECT_FATAL_FAILURE() can reference local static // Tests that EXPECT_FATAL_FAILURE() can reference local static
@ -641,58 +608,51 @@ TEST(ExpectFatalFailureTest, CanReferenceGlobalVariables) {
TEST(ExpectFatalFailureTest, CanReferenceLocalStaticVariables) { TEST(ExpectFatalFailureTest, CanReferenceLocalStaticVariables) {
static int n; static int n;
n = 1; n = 1;
EXPECT_FATAL_FAILURE({ EXPECT_FATAL_FAILURE({ ASSERT_EQ(0, n) << "Expected fatal failure."; },
ASSERT_EQ(0, n) << "Expected fatal failure."; "Expected fatal failure.");
}, "Expected fatal failure.");
} }
// Tests that EXPECT_FATAL_FAILURE() succeeds when there is exactly // Tests that EXPECT_FATAL_FAILURE() succeeds when there is exactly
// one fatal failure and no non-fatal failure. // one fatal failure and no non-fatal failure.
TEST(ExpectFatalFailureTest, SucceedsWhenThereIsOneFatalFailure) { TEST(ExpectFatalFailureTest, SucceedsWhenThereIsOneFatalFailure) {
EXPECT_FATAL_FAILURE({ EXPECT_FATAL_FAILURE({ FAIL() << "Expected fatal failure."; },
FAIL() << "Expected fatal failure."; "Expected fatal failure.");
}, "Expected fatal failure.");
} }
// Tests that EXPECT_FATAL_FAILURE() fails when there is no fatal // Tests that EXPECT_FATAL_FAILURE() fails when there is no fatal
// failure. // failure.
TEST(ExpectFatalFailureTest, FailsWhenThereIsNoFatalFailure) { TEST(ExpectFatalFailureTest, FailsWhenThereIsNoFatalFailure) {
printf("(expecting a failure)\n"); printf("(expecting a failure)\n");
EXPECT_FATAL_FAILURE({ EXPECT_FATAL_FAILURE({}, "");
}, "");
} }
// A helper for generating a fatal failure. // A helper for generating a fatal failure.
void FatalFailure() { void FatalFailure() { FAIL() << "Expected fatal failure."; }
FAIL() << "Expected fatal failure.";
}
// Tests that EXPECT_FATAL_FAILURE() fails when there are two // Tests that EXPECT_FATAL_FAILURE() fails when there are two
// fatal failures. // fatal failures.
TEST(ExpectFatalFailureTest, FailsWhenThereAreTwoFatalFailures) { TEST(ExpectFatalFailureTest, FailsWhenThereAreTwoFatalFailures) {
printf("(expecting a failure)\n"); printf("(expecting a failure)\n");
EXPECT_FATAL_FAILURE({ EXPECT_FATAL_FAILURE(
FatalFailure(); {
FatalFailure(); FatalFailure();
}, ""); FatalFailure();
},
"");
} }
// Tests that EXPECT_FATAL_FAILURE() fails when there is one non-fatal // Tests that EXPECT_FATAL_FAILURE() fails when there is one non-fatal
// failure. // failure.
TEST(ExpectFatalFailureTest, FailsWhenThereIsOneNonfatalFailure) { TEST(ExpectFatalFailureTest, FailsWhenThereIsOneNonfatalFailure) {
printf("(expecting a failure)\n"); printf("(expecting a failure)\n");
EXPECT_FATAL_FAILURE({ EXPECT_FATAL_FAILURE({ ADD_FAILURE() << "Expected non-fatal failure."; }, "");
ADD_FAILURE() << "Expected non-fatal failure.";
}, "");
} }
// Tests that EXPECT_FATAL_FAILURE() fails when the statement being // Tests that EXPECT_FATAL_FAILURE() fails when the statement being
// tested returns. // tested returns.
TEST(ExpectFatalFailureTest, FailsWhenStatementReturns) { TEST(ExpectFatalFailureTest, FailsWhenStatementReturns) {
printf("(expecting a failure)\n"); printf("(expecting a failure)\n");
EXPECT_FATAL_FAILURE({ EXPECT_FATAL_FAILURE({ return; }, "");
return;
}, "");
} }
#if GTEST_HAS_EXCEPTIONS #if GTEST_HAS_EXCEPTIONS
@ -702,10 +662,8 @@ TEST(ExpectFatalFailureTest, FailsWhenStatementReturns) {
TEST(ExpectFatalFailureTest, FailsWhenStatementThrows) { TEST(ExpectFatalFailureTest, FailsWhenStatementThrows) {
printf("(expecting a failure)\n"); printf("(expecting a failure)\n");
try { try {
EXPECT_FATAL_FAILURE({ EXPECT_FATAL_FAILURE({ throw 0; }, "");
throw 0; } catch (int) { // NOLINT
}, "");
} catch(int) { // NOLINT
} }
} }
@ -717,21 +675,14 @@ std::string ParamNameFunc(const testing::TestParamInfo<std::string>& info) {
return info.param; return info.param;
} }
class ParamTest : public testing::TestWithParam<std::string> { class ParamTest : public testing::TestWithParam<std::string> {};
};
TEST_P(ParamTest, Success) { TEST_P(ParamTest, Success) { EXPECT_EQ("a", GetParam()); }
EXPECT_EQ("a", GetParam());
}
TEST_P(ParamTest, Failure) { TEST_P(ParamTest, Failure) { EXPECT_EQ("b", GetParam()) << "Expected failure"; }
EXPECT_EQ("b", GetParam()) << "Expected failure";
}
INSTANTIATE_TEST_SUITE_P(PrintingStrings, INSTANTIATE_TEST_SUITE_P(PrintingStrings, ParamTest,
ParamTest, testing::Values(std::string("a")), ParamNameFunc);
testing::Values(std::string("a")),
ParamNameFunc);
// The case where a suite has INSTANTIATE_TEST_SUITE_P but not TEST_P. // The case where a suite has INSTANTIATE_TEST_SUITE_P but not TEST_P.
using NoTests = ParamTest; using NoTests = ParamTest;
@ -739,20 +690,17 @@ INSTANTIATE_TEST_SUITE_P(ThisIsOdd, NoTests, ::testing::Values("Hello"));
// fails under kErrorOnUninstantiatedParameterizedTest=true // fails under kErrorOnUninstantiatedParameterizedTest=true
class DetectNotInstantiatedTest : public testing::TestWithParam<int> {}; 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. // This would make the test failure from the above go away.
// INSTANTIATE_TEST_SUITE_P(Fix, DetectNotInstantiatedTest, testing::Values(1)); // INSTANTIATE_TEST_SUITE_P(Fix, DetectNotInstantiatedTest, testing::Values(1));
template <typename T> template <typename T>
class TypedTest : public testing::Test { class TypedTest : public testing::Test {};
};
TYPED_TEST_SUITE(TypedTest, testing::Types<int>); TYPED_TEST_SUITE(TypedTest, testing::Types<int>);
TYPED_TEST(TypedTest, Success) { TYPED_TEST(TypedTest, Success) { EXPECT_EQ(0, TypeParam()); }
EXPECT_EQ(0, TypeParam());
}
TYPED_TEST(TypedTest, Failure) { TYPED_TEST(TypedTest, Failure) {
EXPECT_EQ(1, TypeParam()) << "Expected failure"; EXPECT_EQ(1, TypeParam()) << "Expected failure";
@ -781,14 +729,11 @@ TYPED_TEST(TypedTestWithNames, Success) {}
TYPED_TEST(TypedTestWithNames, Failure) { FAIL(); } TYPED_TEST(TypedTestWithNames, Failure) { FAIL(); }
template <typename T> template <typename T>
class TypedTestP : public testing::Test { class TypedTestP : public testing::Test {};
};
TYPED_TEST_SUITE_P(TypedTestP); TYPED_TEST_SUITE_P(TypedTestP);
TYPED_TEST_P(TypedTestP, Success) { TYPED_TEST_P(TypedTestP, Success) { EXPECT_EQ(0U, TypeParam()); }
EXPECT_EQ(0U, TypeParam());
}
TYPED_TEST_P(TypedTestP, Failure) { TYPED_TEST_P(TypedTestP, Failure) {
EXPECT_EQ(1U, TypeParam()) << "Expected failure"; EXPECT_EQ(1U, TypeParam()) << "Expected failure";
@ -813,7 +758,7 @@ class TypedTestPNames {
}; };
INSTANTIATE_TYPED_TEST_SUITE_P(UnsignedCustomName, TypedTestP, UnsignedTypes, INSTANTIATE_TYPED_TEST_SUITE_P(UnsignedCustomName, TypedTestP, UnsignedTypes,
TypedTestPNames); TypedTestPNames);
template <typename T> template <typename T>
class DetectNotInstantiatedTypesTest : public testing::Test {}; 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 // We rely on the golden file to verify that tests whose test case
// name ends with DeathTest are run first. // 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 // We rely on the golden file to verify that typed tests whose test
// case name ends with DeathTest are run first. // case name ends with DeathTest are run first.
template <typename T> template <typename T>
class ATypedDeathTest : public testing::Test { class ATypedDeathTest : public testing::Test {};
};
typedef testing::Types<int, double> NumericTypes; typedef testing::Types<int, double> NumericTypes;
TYPED_TEST_SUITE(ATypedDeathTest, 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 // We rely on the golden file to verify that type-parameterized tests
// whose test case name ends with DeathTest are run first. // whose test case name ends with DeathTest are run first.
template <typename T> template <typename T>
class ATypeParamDeathTest : public testing::Test { class ATypeParamDeathTest : public testing::Test {};
};
TYPED_TEST_SUITE_P(ATypeParamDeathTest); TYPED_TEST_SUITE_P(ATypeParamDeathTest);
TYPED_TEST_P(ATypeParamDeathTest, ShouldRunFirst) { TYPED_TEST_P(ATypeParamDeathTest, ShouldRunFirst) {}
}
REGISTER_TYPED_TEST_SUITE_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}. // EXPECT_{,NON}FATAL_FAILURE{,_ON_ALL_THREADS}.
class ExpectFailureTest : public testing::Test { class ExpectFailureTest : public testing::Test {
public: // Must be public and not protected due to a bug in g++ 3.4.2. public: // Must be public and not protected due to a bug in g++ 3.4.2.
enum FailureMode { enum FailureMode { FATAL_FAILURE, NONFATAL_FAILURE };
FATAL_FAILURE,
NONFATAL_FAILURE
};
static void AddFailure(FailureMode failure) { static void AddFailure(FailureMode failure) {
if (failure == FATAL_FAILURE) { if (failure == FATAL_FAILURE) {
FAIL() << "Expected fatal failure."; FAIL() << "Expected fatal failure.";
@ -893,11 +829,13 @@ TEST_F(ExpectFailureTest, ExpectFatalFailure) {
EXPECT_FATAL_FAILURE(SUCCEED(), "Expected fatal failure."); EXPECT_FATAL_FAILURE(SUCCEED(), "Expected fatal failure.");
// Expected fatal failure, but got a non-fatal failure. // Expected fatal failure, but got a non-fatal failure.
printf("(expecting 1 failure)\n"); printf("(expecting 1 failure)\n");
EXPECT_FATAL_FAILURE(AddFailure(NONFATAL_FAILURE), "Expected non-fatal " EXPECT_FATAL_FAILURE(AddFailure(NONFATAL_FAILURE),
"Expected non-fatal "
"failure."); "failure.");
// Wrong message. // Wrong message.
printf("(expecting 1 failure)\n"); 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."); "expected.");
} }
@ -910,7 +848,8 @@ TEST_F(ExpectFailureTest, ExpectNonFatalFailure) {
EXPECT_NONFATAL_FAILURE(AddFailure(FATAL_FAILURE), "Expected fatal failure."); EXPECT_NONFATAL_FAILURE(AddFailure(FATAL_FAILURE), "Expected fatal failure.");
// Wrong message. // Wrong message.
printf("(expecting 1 failure)\n"); 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."); "failure.");
} }
@ -975,7 +914,8 @@ TEST_F(ExpectFailureTest, ExpectFatalFailureOnAllThreads) {
TEST_F(ExpectFailureTest, ExpectNonFatalFailureOnAllThreads) { TEST_F(ExpectFailureTest, ExpectNonFatalFailureOnAllThreads) {
// Expected non-fatal failure, but succeeds. // Expected non-fatal failure, but succeeds.
printf("(expecting 1 failure)\n"); 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."); "failure.");
// Expected non-fatal failure, but got a fatal failure. // Expected non-fatal failure, but got a fatal failure.
printf("(expecting 1 failure)\n"); printf("(expecting 1 failure)\n");
@ -1064,16 +1004,14 @@ class TestSuiteThatFailsToSetUp : public testing::Test {
public: public:
static void SetUpTestSuite() { EXPECT_TRUE(false); } static void SetUpTestSuite() { EXPECT_TRUE(false); }
}; };
TEST_F(TestSuiteThatFailsToSetUp, ShouldNotRun) { TEST_F(TestSuiteThatFailsToSetUp, ShouldNotRun) { std::abort(); }
std::abort();
}
// The main function. // The main function.
// //
// The idea is to use Google Test to run all the tests we have defined (some // 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 // of them are intended to fail), and then compare the test results
// with the "golden" file. // with the "golden" file.
int main(int argc, char **argv) { int main(int argc, char** argv) {
GTEST_FLAG_SET(print_time, false); GTEST_FLAG_SET(print_time, false);
// We just run the tests, knowing some of them are intended to fail. // 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) != "") { if (GTEST_FLAG_GET(internal_run_death_test) != "") {
// Skip the usual output capturing if we're running as the child // Skip the usual output capturing if we're running as the child
// process of an threadsafe-style death test. // process of an threadsafe-style death test.
# if GTEST_OS_WINDOWS #if GTEST_OS_WINDOWS
posix::FReopen("nul:", "w", stdout); posix::FReopen("nul:", "w", stdout);
# else #else
posix::FReopen("/dev/null", "w", stdout); posix::FReopen("/dev/null", "w", stdout);
# endif // GTEST_OS_WINDOWS #endif // GTEST_OS_WINDOWS
return RUN_ALL_TESTS(); return RUN_ALL_TESTS();
} }
#endif // GTEST_HAS_DEATH_TEST #endif // GTEST_HAS_DEATH_TEST
if (internal_skip_environment_and_ad_hoc_tests) if (internal_skip_environment_and_ad_hoc_tests) return RUN_ALL_TESTS();
return RUN_ALL_TESTS();
// Registers two global test environments. // Registers two global test environments.
// The golden file verifies that they are set up in the order they // 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 FooEnvironment);
testing::AddGlobalTestEnvironment(new BarEnvironment); testing::AddGlobalTestEnvironment(new BarEnvironment);
#if _MSC_VER #if _MSC_VER
GTEST_DISABLE_MSC_WARNINGS_POP_() // 4127 GTEST_DISABLE_MSC_WARNINGS_POP_() // 4127
#endif // _MSC_VER #endif // _MSC_VER
return RunAllTests(); return RunAllTests();
} }

View File

@ -27,17 +27,14 @@
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include "gtest/gtest.h" #include "gtest/gtest.h"
namespace { namespace {
class DummyTest : public ::testing::TestWithParam<const char *> {}; class DummyTest : public ::testing::TestWithParam<const char *> {};
TEST_P(DummyTest, Dummy) { TEST_P(DummyTest, Dummy) {}
}
INSTANTIATE_TEST_SUITE_P(InvalidTestName, INSTANTIATE_TEST_SUITE_P(InvalidTestName, DummyTest,
DummyTest,
::testing::Values("InvalidWithQuotes"), ::testing::Values("InvalidWithQuotes"),
::testing::PrintToStringParamName()); ::testing::PrintToStringParamName());
@ -47,4 +44,3 @@ int main(int argc, char *argv[]) {
testing::InitGoogleTest(&argc, argv); testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS(); return RUN_ALL_TESTS();
} }

View File

@ -27,22 +27,19 @@
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include "gtest/gtest.h" #include "gtest/gtest.h"
namespace { namespace {
class DummyTest : public ::testing::TestWithParam<const char *> {}; class DummyTest : public ::testing::TestWithParam<const char *> {};
std::string StringParamTestSuffix( std::string StringParamTestSuffix(
const testing::TestParamInfo<const char*>& info) { const testing::TestParamInfo<const char *> &info) {
return std::string(info.param); return std::string(info.param);
} }
TEST_P(DummyTest, Dummy) { TEST_P(DummyTest, Dummy) {}
}
INSTANTIATE_TEST_SUITE_P(DuplicateTestNames, INSTANTIATE_TEST_SUITE_P(DuplicateTestNames, DummyTest,
DummyTest,
::testing::Values("a", "b", "a", "c"), ::testing::Values("a", "b", "a", "c"),
StringParamTestSuffix); StringParamTestSuffix);
} // namespace } // namespace
@ -51,5 +48,3 @@ int main(int argc, char *argv[]) {
testing::InitGoogleTest(&argc, argv); testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS(); return RUN_ALL_TESTS();
} }

View File

@ -32,21 +32,21 @@
// generators objects produce correct parameter sequences and that // generators objects produce correct parameter sequences and that
// Google Test runtime instantiates correct tests from those sequences. // Google Test runtime instantiates correct tests from those sequences.
#include "test/googletest-param-test-test.h"
#include <algorithm>
#include <iostream>
#include <list>
#include <set>
#include <sstream>
#include <string>
#include <vector>
#include "gtest/gtest.h" #include "gtest/gtest.h"
#include "src/gtest-internal-inl.h" // for UnitTestOptions
# 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"
using ::std::vector;
using ::std::sort; using ::std::sort;
using ::std::vector;
using ::testing::AddGlobalTestEnvironment; using ::testing::AddGlobalTestEnvironment;
using ::testing::Bool; 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, // We cannot use EXPECT_EQ() here as the values may be tuples,
// which don't support <<. // which don't support <<.
EXPECT_TRUE(expected_values[i] == *it) EXPECT_TRUE(expected_values[i] == *it)
<< "where i is " << i << "where i is " << i << ", expected_values[i] is "
<< ", expected_values[i] is " << PrintValue(expected_values[i]) << PrintValue(expected_values[i]) << ", *it is " << PrintValue(*it)
<< ", *it is " << PrintValue(*it)
<< ", and 'it' is an iterator created with the copy constructor.\n"; << ", and 'it' is an iterator created with the copy constructor.\n";
++it; ++it;
} }
EXPECT_TRUE(it == generator.end()) EXPECT_TRUE(it == generator.end())
<< "At the presumed end of sequence when accessing via an iterator " << "At the presumed end of sequence when accessing via an iterator "
<< "created with the copy constructor.\n"; << "created with the copy constructor.\n";
// Test the iterator assignment. The following lines verify that // Test the iterator assignment. The following lines verify that
// the sequence accessed via an iterator initialized via the // 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 " << "At element " << i << " when accessing via an iterator "
<< "created with the assignment operator.\n"; << "created with the assignment operator.\n";
EXPECT_TRUE(expected_values[i] == *it) EXPECT_TRUE(expected_values[i] == *it)
<< "where i is " << i << "where i is " << i << ", expected_values[i] is "
<< ", expected_values[i] is " << PrintValue(expected_values[i]) << PrintValue(expected_values[i]) << ", *it is " << PrintValue(*it)
<< ", *it is " << PrintValue(*it)
<< ", and 'it' is an iterator created with the copy constructor.\n"; << ", and 'it' is an iterator created with the copy constructor.\n";
++it; ++it;
} }
EXPECT_TRUE(it == generator.end()) EXPECT_TRUE(it == generator.end())
<< "At the presumed end of sequence when accessing via an iterator " << "At the presumed end of sequence when accessing via an iterator "
<< "created with the assignment operator.\n"; << "created with the assignment operator.\n";
} }
template <typename T> template <typename T>
@ -216,8 +214,7 @@ class DogAdder {
DogAdder(const DogAdder& other) : value_(other.value_.c_str()) {} DogAdder(const DogAdder& other) : value_(other.value_.c_str()) {}
DogAdder operator=(const DogAdder& other) { DogAdder operator=(const DogAdder& other) {
if (this != &other) if (this != &other) value_ = other.value_;
value_ = other.value_;
return *this; return *this;
} }
DogAdder operator+(const DogAdder& other) const { DogAdder operator+(const DogAdder& other) const {
@ -225,9 +222,7 @@ class DogAdder {
msg << value_.c_str() << other.value_.c_str(); msg << value_.c_str() << other.value_.c_str();
return DogAdder(msg.GetString().c_str()); return DogAdder(msg.GetString().c_str());
} }
bool operator<(const DogAdder& other) const { bool operator<(const DogAdder& other) const { return value_ < other.value_; }
return value_ < other.value_;
}
const std::string& value() const { return value_; } const std::string& value() const { return value_; }
private: private:
@ -372,19 +367,17 @@ TEST(ValuesTest, ValuesWorksForValuesOfCompatibleTypes) {
} }
TEST(ValuesTest, ValuesWorksForMaxLengthList) { TEST(ValuesTest, ValuesWorksForMaxLengthList) {
const ParamGenerator<int> gen = Values( const ParamGenerator<int> gen =
10, 20, 30, 40, 50, 60, 70, 80, 90, 100, Values(10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 110, 120, 130, 140, 150,
110, 120, 130, 140, 150, 160, 170, 180, 190, 200, 160, 170, 180, 190, 200, 210, 220, 230, 240, 250, 260, 270, 280,
210, 220, 230, 240, 250, 260, 270, 280, 290, 300, 290, 300, 310, 320, 330, 340, 350, 360, 370, 380, 390, 400, 410,
310, 320, 330, 340, 350, 360, 370, 380, 390, 400, 420, 430, 440, 450, 460, 470, 480, 490, 500);
410, 420, 430, 440, 450, 460, 470, 480, 490, 500);
const int expected_values[] = { const int expected_values[] = {
10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 110, 120, 130,
110, 120, 130, 140, 150, 160, 170, 180, 190, 200, 140, 150, 160, 170, 180, 190, 200, 210, 220, 230, 240, 250, 260,
210, 220, 230, 240, 250, 260, 270, 280, 290, 300, 270, 280, 290, 300, 310, 320, 330, 340, 350, 360, 370, 380, 390,
310, 320, 330, 340, 350, 360, 370, 380, 390, 400, 400, 410, 420, 430, 440, 450, 460, 470, 480, 490, 500};
410, 420, 430, 440, 450, 460, 470, 480, 490, 500};
VerifyGenerator(gen, expected_values); VerifyGenerator(gen, expected_values);
} }
@ -530,7 +523,6 @@ TEST(CombineTest, NonDefaultConstructAssign) {
EXPECT_TRUE(it == gen.end()); EXPECT_TRUE(it == gen.end());
} }
// Tests that an generator produces correct sequence after being // Tests that an generator produces correct sequence after being
// assigned from another generator. // assigned from another generator.
TEST(ParamGeneratorTest, AssignmentWorks) { TEST(ParamGeneratorTest, AssignmentWorks) {
@ -573,7 +565,7 @@ class TestGenerationEnvironment : public ::testing::Environment {
Message msg; Message msg;
msg << "TestsExpandedAndRun/" << i; msg << "TestsExpandedAndRun/" << i;
if (UnitTestOptions::FilterMatchesTest( if (UnitTestOptions::FilterMatchesTest(
"TestExpansionModule/MultipleTestGenerationTest", "TestExpansionModule/MultipleTestGenerationTest",
msg.GetString().c_str())) { msg.GetString().c_str())) {
perform_check = true; perform_check = true;
} }
@ -595,8 +587,11 @@ class TestGenerationEnvironment : public ::testing::Environment {
} }
private: private:
TestGenerationEnvironment() : fixture_constructor_count_(0), set_up_count_(0), TestGenerationEnvironment()
tear_down_count_(0), test_body_count_(0) {} : fixture_constructor_count_(0),
set_up_count_(0),
tear_down_count_(0),
test_body_count_(0) {}
int fixture_constructor_count_; int fixture_constructor_count_;
int set_up_count_; int set_up_count_;
@ -612,7 +607,7 @@ class TestGenerationTest : public TestWithParam<int> {
public: public:
enum { enum {
PARAMETER_COUNT = 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; typedef TestGenerationEnvironment<PARAMETER_COUNT> Environment;
@ -636,9 +631,9 @@ class TestGenerationTest : public TestWithParam<int> {
for (int i = 0; i < PARAMETER_COUNT; ++i) { for (int i = 0; i < PARAMETER_COUNT; ++i) {
Message test_name; Message test_name;
test_name << "TestsExpandedAndRun/" << i; test_name << "TestsExpandedAndRun/" << i;
if ( !UnitTestOptions::FilterMatchesTest( if (!UnitTestOptions::FilterMatchesTest(
"TestExpansionModule/MultipleTestGenerationTest", "TestExpansionModule/MultipleTestGenerationTest",
test_name.GetString())) { test_name.GetString())) {
all_tests_in_test_case_selected = false; 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 // Tests that a parameterized test case can be instantiated with multiple
// generators. // generators.
class MultipleInstantiationTest : public TestWithParam<int> {}; 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(Sequence1, MultipleInstantiationTest, Values(1, 2));
INSTANTIATE_TEST_SUITE_P(Sequence2, MultipleInstantiationTest, Range(3, 5)); INSTANTIATE_TEST_SUITE_P(Sequence2, MultipleInstantiationTest, Range(3, 5));
@ -780,7 +774,7 @@ class NamingTest : public TestWithParam<int> {};
TEST_P(NamingTest, TestsReportCorrectNamesAndParameters) { TEST_P(NamingTest, TestsReportCorrectNamesAndParameters) {
const ::testing::TestInfo* const test_info = 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()); 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)) { TEST_P(PREFIX_WITH_MACRO(NamingTest), PREFIX_WITH_FOO(SomeTestName)) {
const ::testing::TestInfo* const test_info = 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("FortyTwo/MacroNamingTest", test_info->test_suite_name());
EXPECT_STREQ("FooSomeTestName/0", test_info->name()); EXPECT_STREQ("FooSomeTestName/0", test_info->name());
@ -815,7 +809,7 @@ class MacroNamingTestNonParametrized : public ::testing::Test {};
TEST_F(PREFIX_WITH_MACRO(NamingTestNonParametrized), TEST_F(PREFIX_WITH_MACRO(NamingTestNonParametrized),
PREFIX_WITH_FOO(SomeTestName)) { PREFIX_WITH_FOO(SomeTestName)) {
const ::testing::TestInfo* const test_info = 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("MacroNamingTestNonParametrized", test_info->test_suite_name());
EXPECT_STREQ("FooSomeTestName", test_info->name()); EXPECT_STREQ("FooSomeTestName", test_info->name());
@ -839,9 +833,8 @@ TEST(MacroNameing, LookupNames) {
EXPECT_NE( // EXPECT_NE( //
know_suite_names.find("FortyTwo/MacroNamingTest"), know_suite_names.find("FortyTwo/MacroNamingTest"),
know_suite_names.end()); know_suite_names.end());
EXPECT_NE( EXPECT_NE(know_suite_names.find("MacroNamingTestNonParametrized"),
know_suite_names.find("MacroNamingTestNonParametrized"), know_suite_names.end());
know_suite_names.end());
// Check that the expected form of the test name actually exists. // Check that the expected form of the test name actually exists.
EXPECT_NE( // EXPECT_NE( //
know_test_names.find("FortyTwo/MacroNamingTest.FooSomeTestName/0"), know_test_names.find("FortyTwo/MacroNamingTest.FooSomeTestName/0"),
@ -924,7 +917,7 @@ class CustomIntegerNamingTest : public TestWithParam<int> {};
TEST_P(CustomIntegerNamingTest, TestsReportCorrectNames) { TEST_P(CustomIntegerNamingTest, TestsReportCorrectNames) {
const ::testing::TestInfo* const test_info = const ::testing::TestInfo* const test_info =
::testing::UnitTest::GetInstance()->current_test_info(); ::testing::UnitTest::GetInstance()->current_test_info();
Message test_name_stream; Message test_name_stream;
test_name_stream << "TestsReportCorrectNames/" << GetParam(); test_name_stream << "TestsReportCorrectNames/" << GetParam();
EXPECT_STREQ(test_name_stream.GetString().c_str(), test_info->name()); EXPECT_STREQ(test_name_stream.GetString().c_str(), test_info->name());
@ -949,7 +942,7 @@ class CustomStructNamingTest : public TestWithParam<CustomStruct> {};
TEST_P(CustomStructNamingTest, TestsReportCorrectNames) { TEST_P(CustomStructNamingTest, TestsReportCorrectNames) {
const ::testing::TestInfo* const test_info = const ::testing::TestInfo* const test_info =
::testing::UnitTest::GetInstance()->current_test_info(); ::testing::UnitTest::GetInstance()->current_test_info();
Message test_name_stream; Message test_name_stream;
test_name_stream << "TestsReportCorrectNames/" << GetParam(); test_name_stream << "TestsReportCorrectNames/" << GetParam();
EXPECT_STREQ(test_name_stream.GetString().c_str(), test_info->name()); 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) { TEST_P(StatefulNamingTest, TestsReportCorrectNames) {
const ::testing::TestInfo* const test_info = const ::testing::TestInfo* const test_info =
::testing::UnitTest::GetInstance()->current_test_info(); ::testing::UnitTest::GetInstance()->current_test_info();
sum_ += GetParam(); sum_ += GetParam();
Message test_name_stream; Message test_name_stream;
test_name_stream << "TestsReportCorrectNames/" << sum_; test_name_stream << "TestsReportCorrectNames/" << sum_;
@ -1007,7 +1000,7 @@ class CommentTest : public TestWithParam<Unstreamable> {};
TEST_P(CommentTest, TestsCorrectlyReportUnstreamableParams) { TEST_P(CommentTest, TestsCorrectlyReportUnstreamableParams) {
const ::testing::TestInfo* const test_info = 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()); EXPECT_EQ(::testing::PrintToString(GetParam()), test_info->value_param());
} }
@ -1021,7 +1014,8 @@ INSTANTIATE_TEST_SUITE_P(InstantiationWithComments, CommentTest,
// perform simple tests on both. // perform simple tests on both.
class NonParameterizedBaseTest : public ::testing::Test { class NonParameterizedBaseTest : public ::testing::Test {
public: public:
NonParameterizedBaseTest() : n_(17) { } NonParameterizedBaseTest() : n_(17) {}
protected: protected:
int n_; int n_;
}; };
@ -1029,16 +1023,14 @@ class NonParameterizedBaseTest : public ::testing::Test {
class ParameterizedDerivedTest : public NonParameterizedBaseTest, class ParameterizedDerivedTest : public NonParameterizedBaseTest,
public ::testing::WithParamInterface<int> { public ::testing::WithParamInterface<int> {
protected: protected:
ParameterizedDerivedTest() : count_(0) { } ParameterizedDerivedTest() : count_(0) {}
int count_; int count_;
static int global_count_; static int global_count_;
}; };
int ParameterizedDerivedTest::global_count_ = 0; int ParameterizedDerivedTest::global_count_ = 0;
TEST_F(NonParameterizedBaseTest, FixtureIsInitialized) { TEST_F(NonParameterizedBaseTest, FixtureIsInitialized) { EXPECT_EQ(17, n_); }
EXPECT_EQ(17, n_);
}
TEST_P(ParameterizedDerivedTest, SeesSequence) { TEST_P(ParameterizedDerivedTest, SeesSequence) {
EXPECT_EQ(17, n_); EXPECT_EQ(17, n_);
@ -1046,11 +1038,10 @@ TEST_P(ParameterizedDerivedTest, SeesSequence) {
EXPECT_EQ(GetParam(), global_count_++); EXPECT_EQ(GetParam(), global_count_++);
} }
class ParameterizedDeathTest : public ::testing::TestWithParam<int> { }; class ParameterizedDeathTest : public ::testing::TestWithParam<int> {};
TEST_F(ParameterizedDeathTest, GetParamDiesFromTestF) { TEST_F(ParameterizedDeathTest, GetParamDiesFromTestF) {
EXPECT_DEATH_IF_SUPPORTED(GetParam(), EXPECT_DEATH_IF_SUPPORTED(GetParam(), ".* value-parameterized test .*");
".* value-parameterized test .*");
} }
INSTANTIATE_TEST_SUITE_P(RangeZeroToFive, ParameterizedDerivedTest, INSTANTIATE_TEST_SUITE_P(RangeZeroToFive, ParameterizedDerivedTest,
@ -1084,11 +1075,11 @@ class NotInstantiatedTest : public testing::TestWithParam<int> {};
// ... we mark is as allowed. // ... we mark is as allowed.
GTEST_ALLOW_UNINSTANTIATED_PARAMETERIZED_TEST(NotInstantiatedTest); GTEST_ALLOW_UNINSTANTIATED_PARAMETERIZED_TEST(NotInstantiatedTest);
TEST_P(NotInstantiatedTest, Used) { } TEST_P(NotInstantiatedTest, Used) {}
using OtherName = NotInstantiatedTest; using OtherName = NotInstantiatedTest;
GTEST_ALLOW_UNINSTANTIATED_PARAMETERIZED_TEST(OtherName); GTEST_ALLOW_UNINSTANTIATED_PARAMETERIZED_TEST(OtherName);
TEST_P(OtherName, Used) { } TEST_P(OtherName, Used) {}
// Used but not instantiated, this would fail. but... // Used but not instantiated, this would fail. but...
template <typename T> template <typename T>
@ -1097,11 +1088,11 @@ TYPED_TEST_SUITE_P(NotInstantiatedTypeTest);
// ... we mark is as allowed. // ... we mark is as allowed.
GTEST_ALLOW_UNINSTANTIATED_PARAMETERIZED_TEST(NotInstantiatedTypeTest); GTEST_ALLOW_UNINSTANTIATED_PARAMETERIZED_TEST(NotInstantiatedTypeTest);
TYPED_TEST_P(NotInstantiatedTypeTest, Used) { } TYPED_TEST_P(NotInstantiatedTypeTest, Used) {}
REGISTER_TYPED_TEST_SUITE_P(NotInstantiatedTypeTest, Used); REGISTER_TYPED_TEST_SUITE_P(NotInstantiatedTypeTest, Used);
} // namespace works_here } // namespace works_here
int main(int argc, char **argv) { int main(int argc, char** argv) {
// Used in TestGenerationTest test suite. // Used in TestGenerationTest test suite.
AddGlobalTestEnvironment(TestGenerationTest::Environment::Instance()); AddGlobalTestEnvironment(TestGenerationTest::Environment::Instance());
// Used in GeneratorEvaluationTest test suite. Tests that the updated value // Used in GeneratorEvaluationTest test suite. Tests that the updated value

View File

@ -39,13 +39,11 @@
// Test fixture for testing definition and instantiation of a test // Test fixture for testing definition and instantiation of a test
// in separate translation units. // 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 // Test fixture for testing instantiation of a test in multiple
// translation units. // translation units.
class InstantiationInMultipleTranslationUnitsTest class InstantiationInMultipleTranslationUnitsTest
: public ::testing::TestWithParam<int> { : public ::testing::TestWithParam<int> {};
};
#endif // GOOGLETEST_TEST_GOOGLETEST_PARAM_TEST_TEST_H_ #endif // GOOGLETEST_TEST_GOOGLETEST_PARAM_TEST_TEST_H_

View File

@ -46,8 +46,7 @@ ParamGenerator<int> extern_gen = Values(33);
// and instantiated in another. The test is defined in // and instantiated in another. The test is defined in
// googletest-param-test-test.cc and ExternalInstantiationTest fixture class is // googletest-param-test-test.cc and ExternalInstantiationTest fixture class is
// defined in gtest-param-test_test.h. // defined in gtest-param-test_test.h.
INSTANTIATE_TEST_SUITE_P(MultiplesOf33, INSTANTIATE_TEST_SUITE_P(MultiplesOf33, ExternalInstantiationTest,
ExternalInstantiationTest,
Values(33, 66)); Values(33, 66));
// Tests that a parameterized test case can be instantiated // 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 // in googletest-param-test-test.cc and
// InstantiationInMultipleTranslationUnitsTest fixture is defined in // InstantiationInMultipleTranslationUnitsTest fixture is defined in
// gtest-param-test_test.h // gtest-param-test_test.h
INSTANTIATE_TEST_SUITE_P(Sequence2, INSTANTIATE_TEST_SUITE_P(Sequence2, InstantiationInMultipleTranslationUnitsTest,
InstantiationInMultipleTranslationUnitsTest, Values(42 * 3, 42 * 4, 42 * 5));
Values(42*3, 42*4, 42*5));

View File

@ -33,18 +33,18 @@
#include "gtest/internal/gtest-port.h" #include "gtest/internal/gtest-port.h"
#if GTEST_OS_MAC #if GTEST_OS_MAC
# include <time.h> #include <time.h>
#endif // GTEST_OS_MAC #endif // GTEST_OS_MAC
#include <chrono> // NOLINT #include <chrono> // NOLINT
#include <list> #include <list>
#include <memory> #include <memory>
#include <thread> // NOLINT #include <thread> // NOLINT
#include <utility> // For std::pair and std::make_pair. #include <utility> // For std::pair and std::make_pair.
#include <vector> #include <vector>
#include "gtest/gtest.h"
#include "gtest/gtest-spi.h" #include "gtest/gtest-spi.h"
#include "gtest/gtest.h"
#include "src/gtest-internal-inl.h" #include "src/gtest-internal-inl.h"
using std::make_pair; using std::make_pair;
@ -238,8 +238,8 @@ TEST(GtestCheckSyntaxTest, WorksWithSwitch) {
} }
switch (0) switch (0)
case 0: case 0:
GTEST_CHECK_(true) << "Check failed in switch case"; GTEST_CHECK_(true) << "Check failed in switch case";
} }
// Verifies behavior of FormatFileLocation. // Verifies behavior of FormatFileLocation.
@ -281,7 +281,7 @@ TEST(FormatCompilerIndependentFileLocationTest, FormatsUknownFileAndLine) {
} }
#if GTEST_OS_LINUX || GTEST_OS_MAC || GTEST_OS_QNX || GTEST_OS_FUCHSIA || \ #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 GTEST_OS_NETBSD || GTEST_OS_OPENBSD || GTEST_OS_GNU_HURD
void* ThreadFunc(void* data) { void* ThreadFunc(void* data) {
internal::Mutex* mutex = static_cast<internal::Mutex*>(data); internal::Mutex* mutex = static_cast<internal::Mutex*>(data);
@ -357,13 +357,13 @@ TEST(GtestCheckDeathTest, DiesWithCorrectOutputOnFailure) {
const bool a_false_condition = false; const bool a_false_condition = false;
const char regex[] = const char regex[] =
#ifdef _MSC_VER #ifdef _MSC_VER
"googletest-port-test\\.cc\\(\\d+\\):" "googletest-port-test\\.cc\\(\\d+\\):"
#elif GTEST_USES_POSIX_RE #elif GTEST_USES_POSIX_RE
"googletest-port-test\\.cc:[0-9]+" "googletest-port-test\\.cc:[0-9]+"
#else #else
"googletest-port-test\\.cc:\\d+" "googletest-port-test\\.cc:\\d+"
#endif // _MSC_VER #endif // _MSC_VER
".*a_false_condition.*Extra info.*"; ".*a_false_condition.*Extra info.*";
EXPECT_DEATH_IF_SUPPORTED(GTEST_CHECK_(a_false_condition) << "Extra info", EXPECT_DEATH_IF_SUPPORTED(GTEST_CHECK_(a_false_condition) << "Extra info",
regex); regex);
@ -372,10 +372,12 @@ TEST(GtestCheckDeathTest, DiesWithCorrectOutputOnFailure) {
#if GTEST_HAS_DEATH_TEST #if GTEST_HAS_DEATH_TEST
TEST(GtestCheckDeathTest, LivesSilentlyOnSuccess) { TEST(GtestCheckDeathTest, LivesSilentlyOnSuccess) {
EXPECT_EXIT({ EXPECT_EXIT(
GTEST_CHECK_(true) << "Extra info"; {
::std::cerr << "Success\n"; GTEST_CHECK_(true) << "Extra info";
exit(0); }, ::std::cerr << "Success\n";
exit(0);
},
::testing::ExitedWithCode(0), "Success"); ::testing::ExitedWithCode(0), "Success");
} }
@ -386,15 +388,15 @@ TEST(GtestCheckDeathTest, LivesSilentlyOnSuccess) {
// For simplicity, we only cover the most important platforms here. // For simplicity, we only cover the most important platforms here.
TEST(RegexEngineSelectionTest, SelectsCorrectRegexEngine) { TEST(RegexEngineSelectionTest, SelectsCorrectRegexEngine) {
#if !GTEST_USES_PCRE #if !GTEST_USES_PCRE
# if GTEST_HAS_POSIX_RE #if GTEST_HAS_POSIX_RE
EXPECT_TRUE(GTEST_USES_POSIX_RE); EXPECT_TRUE(GTEST_USES_POSIX_RE);
# else #else
EXPECT_TRUE(GTEST_USES_SIMPLE_RE); EXPECT_TRUE(GTEST_USES_SIMPLE_RE);
# endif #endif
#endif // !GTEST_USES_PCRE #endif // !GTEST_USES_PCRE
} }
@ -423,9 +425,9 @@ TYPED_TEST(RETest, ImplicitConstructorWorks) {
// Tests that RE's constructors reject invalid regular expressions. // Tests that RE's constructors reject invalid regular expressions.
TYPED_TEST(RETest, RejectsInvalidRegex) { TYPED_TEST(RETest, RejectsInvalidRegex) {
EXPECT_NONFATAL_FAILURE({ EXPECT_NONFATAL_FAILURE(
const RE invalid(TypeParam("?")); { const RE invalid(TypeParam("?")); },
}, "\"?\" is not a valid POSIX Extended regular expression."); "\"?\" is not a valid POSIX Extended regular expression.");
} }
// Tests RE::FullMatch(). // Tests RE::FullMatch().
@ -819,8 +821,7 @@ TEST(MatchRegexAtHeadTest, WorksWhenRegexStartsWithRepetition) {
EXPECT_TRUE(MatchRegexAtHead("a?b", "ab")); EXPECT_TRUE(MatchRegexAtHead("a?b", "ab"));
} }
TEST(MatchRegexAtHeadTest, TEST(MatchRegexAtHeadTest, WorksWhenRegexStartsWithRepetionOfEscapeSequence) {
WorksWhenRegexStartsWithRepetionOfEscapeSequence) {
EXPECT_FALSE(MatchRegexAtHead("\\.+a", "abc")); EXPECT_FALSE(MatchRegexAtHead("\\.+a", "abc"));
EXPECT_FALSE(MatchRegexAtHead("\\s?b", " b")); EXPECT_FALSE(MatchRegexAtHead("\\s?b", " b"));
@ -876,17 +877,14 @@ TEST(RETest, ImplicitConstructorWorks) {
// Tests that RE's constructors reject invalid regular expressions. // Tests that RE's constructors reject invalid regular expressions.
TEST(RETest, RejectsInvalidRegex) { TEST(RETest, RejectsInvalidRegex) {
EXPECT_NONFATAL_FAILURE({ EXPECT_NONFATAL_FAILURE({ const RE normal(NULL); },
const RE normal(NULL); "NULL is not a valid simple regular expression");
}, "NULL is not a valid simple regular expression");
EXPECT_NONFATAL_FAILURE({ EXPECT_NONFATAL_FAILURE({ const RE normal(".*(\\w+"); },
const RE normal(".*(\\w+"); "'(' is unsupported");
}, "'(' is unsupported");
EXPECT_NONFATAL_FAILURE({ EXPECT_NONFATAL_FAILURE({ const RE invalid("^?"); },
const RE invalid("^?"); "'?' can only follow a repeatable token");
}, "'?' can only follow a repeatable token");
} }
// Tests RE::FullMatch(). // Tests RE::FullMatch().
@ -1028,12 +1026,13 @@ TEST(ThreadWithParamTest, ConstructorExecutesThreadFunc) {
TEST(MutexDeathTest, AssertHeldShouldAssertWhenNotLocked) { TEST(MutexDeathTest, AssertHeldShouldAssertWhenNotLocked) {
// AssertHeld() is flaky only in the presence of multiple threads accessing // AssertHeld() is flaky only in the presence of multiple threads accessing
// the lock. In this case, the test is robust. // the lock. In this case, the test is robust.
EXPECT_DEATH_IF_SUPPORTED({ EXPECT_DEATH_IF_SUPPORTED(
Mutex m; {
{ MutexLock lock(&m); } Mutex m;
m.AssertHeld(); { MutexLock lock(&m); }
}, m.AssertHeld();
"thread .*hold"); },
"thread .*hold");
} }
TEST(MutexTest, AssertHeldShouldNotAssertWhenLocked) { TEST(MutexTest, AssertHeldShouldNotAssertWhenLocked) {
@ -1044,8 +1043,8 @@ TEST(MutexTest, AssertHeldShouldNotAssertWhenLocked) {
class AtomicCounterWithMutex { class AtomicCounterWithMutex {
public: public:
explicit AtomicCounterWithMutex(Mutex* mutex) : explicit AtomicCounterWithMutex(Mutex* mutex)
value_(0), mutex_(mutex), random_(42) {} : value_(0), mutex_(mutex), random_(42) {}
void Increment() { void Increment() {
MutexLock lock(mutex_); MutexLock lock(mutex_);
@ -1076,7 +1075,7 @@ class AtomicCounterWithMutex {
std::chrono::milliseconds(random_.Generate(30))); std::chrono::milliseconds(random_.Generate(30)));
::InterlockedIncrement(&dummy); ::InterlockedIncrement(&dummy);
#else #else
# error "Memory barrier not implemented on this platform." #error "Memory barrier not implemented on this platform."
#endif // GTEST_HAS_PTHREAD #endif // GTEST_HAS_PTHREAD
} }
value_ = temp + 1; value_ = temp + 1;
@ -1086,12 +1085,11 @@ class AtomicCounterWithMutex {
private: private:
volatile int value_; volatile int value_;
Mutex* const mutex_; // Protects value_. Mutex* const mutex_; // Protects value_.
Random random_; Random random_;
}; };
void CountingThreadFunc(pair<AtomicCounterWithMutex*, int> param) { void CountingThreadFunc(pair<AtomicCounterWithMutex*, int> param) {
for (int i = 0; i < param.second; ++i) for (int i = 0; i < param.second; ++i) param.first->Increment();
param.first->Increment();
} }
// Tests that the mutex only lets one thread at a time to lock it. // 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 // Creates and runs kThreadCount threads that increment locked_counter
// kCycleCount times each. // kCycleCount times each.
for (int i = 0; i < kThreadCount; ++i) { for (int i = 0; i < kThreadCount; ++i) {
counting_threads[i].reset(new ThreadType(&CountingThreadFunc, counting_threads[i].reset(new ThreadType(
make_pair(&locked_counter, &CountingThreadFunc, make_pair(&locked_counter, kCycleCount),
kCycleCount), &threads_can_start));
&threads_can_start));
} }
threads_can_start.Notify(); threads_can_start.Notify();
for (int i = 0; i < kThreadCount; ++i) for (int i = 0; i < kThreadCount; ++i) counting_threads[i]->Join();
counting_threads[i]->Join();
// If the mutex lets more than one thread to increment the counter at a // 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 // time, they are likely to encounter a race condition and have some
@ -1124,7 +1120,7 @@ TEST(MutexTest, OnlyOneThreadCanLockAtATime) {
} }
template <typename T> template <typename T>
void RunFromThread(void (func)(T), T param) { void RunFromThread(void(func)(T), T param) {
ThreadWithParam<T> thread(func, param, nullptr); ThreadWithParam<T> thread(func, param, nullptr);
thread.Join(); thread.Join();
} }

View File

@ -27,7 +27,6 @@
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// Google Test - The Google C++ Testing and Mocking Framework // Google Test - The Google C++ Testing and Mocking Framework
// //
// This file tests the universal value printer. // This file tests the universal value printer.
@ -56,30 +55,20 @@
// Some user-defined types for testing the universal value printer. // Some user-defined types for testing the universal value printer.
// An anonymous enum type. // An anonymous enum type.
enum AnonymousEnum { enum AnonymousEnum { kAE1 = -1, kAE2 = 1 };
kAE1 = -1,
kAE2 = 1
};
// An enum without a user-defined printer. // An enum without a user-defined printer.
enum EnumWithoutPrinter { enum EnumWithoutPrinter { kEWP1 = -2, kEWP2 = 42 };
kEWP1 = -2,
kEWP2 = 42
};
// An enum with a << operator. // An enum with a << operator.
enum EnumWithStreaming { enum EnumWithStreaming { kEWS1 = 10 };
kEWS1 = 10
};
std::ostream& operator<<(std::ostream& os, EnumWithStreaming e) { std::ostream& operator<<(std::ostream& os, EnumWithStreaming e) {
return os << (e == kEWS1 ? "kEWS1" : "invalid"); return os << (e == kEWS1 ? "kEWS1" : "invalid");
} }
// An enum with a PrintTo() function. // An enum with a PrintTo() function.
enum EnumWithPrintTo { enum EnumWithPrintTo { kEWPT1 = 1 };
kEWPT1 = 1
};
void PrintTo(EnumWithPrintTo e, std::ostream* os) { void PrintTo(EnumWithPrintTo e, std::ostream* os) {
*os << (e == kEWPT1 ? "kEWPT1" : "invalid"); *os << (e == kEWPT1 ? "kEWPT1" : "invalid");
@ -108,6 +97,7 @@ template <typename T>
class UnprintableTemplateInGlobal { class UnprintableTemplateInGlobal {
public: public:
UnprintableTemplateInGlobal() : value_() {} UnprintableTemplateInGlobal() : value_() {}
private: private:
T value_; T value_;
}; };
@ -133,6 +123,7 @@ class UnprintableInFoo {
public: public:
UnprintableInFoo() : z_(0) { memcpy(xy_, "\xEF\x12\x0\x0\x34\xAB\x0\x0", 8); } UnprintableInFoo() : z_(0) { memcpy(xy_, "\xEF\x12\x0\x0\x34\xAB\x0\x0", 8); }
double z() const { return z_; } double z() const { return z_; }
private: private:
char xy_[8]; char xy_[8];
double z_; double z_;
@ -149,8 +140,7 @@ void PrintTo(const PrintableViaPrintTo& x, ::std::ostream* os) {
} }
// A type with a user-defined << for printing its pointer. // A type with a user-defined << for printing its pointer.
struct PointerPrintable { struct PointerPrintable {};
};
::std::ostream& operator<<(::std::ostream& os, ::std::ostream& operator<<(::std::ostream& os,
const PointerPrintable* /* x */) { const PointerPrintable* /* x */) {
@ -164,6 +154,7 @@ class PrintableViaPrintToTemplate {
explicit PrintableViaPrintToTemplate(const T& a_value) : value_(a_value) {} explicit PrintableViaPrintToTemplate(const T& a_value) : value_(a_value) {}
const T& value() const { return value_; } const T& value() const { return value_; }
private: private:
T value_; T value_;
}; };
@ -180,6 +171,7 @@ class StreamableTemplateInFoo {
StreamableTemplateInFoo() : value_() {} StreamableTemplateInFoo() : value_() {}
const T& value() const { return value_; } const T& value() const { return value_; }
private: private:
T value_; T value_;
}; };
@ -255,7 +247,6 @@ class UniversalPrinter<Wrapper<T>> {
}; };
} // namespace internal } // namespace internal
namespace gtest_printers_test { namespace gtest_printers_test {
using ::std::deque; using ::std::deque;
@ -350,29 +341,21 @@ TEST(PrintCharTest, PlainChar) {
// signed char. // signed char.
TEST(PrintCharTest, SignedChar) { TEST(PrintCharTest, SignedChar) {
EXPECT_EQ("'\\0'", Print(static_cast<signed char>('\0'))); EXPECT_EQ("'\\0'", Print(static_cast<signed char>('\0')));
EXPECT_EQ("'\\xCE' (-50)", EXPECT_EQ("'\\xCE' (-50)", Print(static_cast<signed char>(-50)));
Print(static_cast<signed char>(-50)));
} }
// unsigned char. // unsigned char.
TEST(PrintCharTest, UnsignedChar) { TEST(PrintCharTest, UnsignedChar) {
EXPECT_EQ("'\\0'", Print(static_cast<unsigned char>('\0'))); EXPECT_EQ("'\\0'", Print(static_cast<unsigned char>('\0')));
EXPECT_EQ("'b' (98, 0x62)", EXPECT_EQ("'b' (98, 0x62)", Print(static_cast<unsigned char>('b')));
Print(static_cast<unsigned char>('b')));
} }
TEST(PrintCharTest, Char16) { TEST(PrintCharTest, Char16) { EXPECT_EQ("U+0041", Print(u'A')); }
EXPECT_EQ("U+0041", Print(u'A'));
}
TEST(PrintCharTest, Char32) { TEST(PrintCharTest, Char32) { EXPECT_EQ("U+0041", Print(U'A')); }
EXPECT_EQ("U+0041", Print(U'A'));
}
#ifdef __cpp_char8_t #ifdef __cpp_char8_t
TEST(PrintCharTest, Char8) { TEST(PrintCharTest, Char8) { EXPECT_EQ("U+0041", Print(u8'A')); }
EXPECT_EQ("U+0041", Print(u8'A'));
}
#endif #endif
// Tests printing other simple, built-in types. // Tests printing other simple, built-in types.
@ -414,8 +397,8 @@ TEST(PrintTypeSizeTest, Wchar_t) {
TEST(PrintBuiltInTypeTest, Integer) { TEST(PrintBuiltInTypeTest, Integer) {
EXPECT_EQ("'\\xFF' (255)", Print(static_cast<unsigned char>(255))); // uint8 EXPECT_EQ("'\\xFF' (255)", Print(static_cast<unsigned char>(255))); // uint8
EXPECT_EQ("'\\x80' (-128)", Print(static_cast<signed char>(-128))); // int8 EXPECT_EQ("'\\x80' (-128)", Print(static_cast<signed char>(-128))); // int8
EXPECT_EQ("65535", Print(std::numeric_limits<uint16_t>::max())); // uint16 EXPECT_EQ("65535", Print(std::numeric_limits<uint16_t>::max())); // uint16
EXPECT_EQ("-32768", Print(std::numeric_limits<int16_t>::min())); // int16 EXPECT_EQ("-32768", Print(std::numeric_limits<int16_t>::min())); // int16
EXPECT_EQ("4294967295", EXPECT_EQ("4294967295",
Print(std::numeric_limits<uint32_t>::max())); // uint32 Print(std::numeric_limits<uint32_t>::max())); // uint32
EXPECT_EQ("-2147483648", EXPECT_EQ("-2147483648",
@ -446,7 +429,7 @@ TEST(PrintBuiltInTypeTest, Size_t) {
#if !GTEST_OS_WINDOWS #if !GTEST_OS_WINDOWS
// Windows has no ssize_t type. // Windows has no ssize_t type.
EXPECT_EQ("-2", Print(static_cast<ssize_t>(-2))); // ssize_t. 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. // gcc/clang __{u,}int128_t values.
@ -516,8 +499,9 @@ TEST(PrintCStringTest, Null) {
// Tests that C strings are escaped properly. // Tests that C strings are escaped properly.
TEST(PrintCStringTest, EscapesProperly) { TEST(PrintCStringTest, EscapesProperly) {
const char* p = "'\"?\\\a\b\f\n\r\t\v\x7F\xFF a"; const char* p = "'\"?\\\a\b\f\n\r\t\v\x7F\xFF a";
EXPECT_EQ(PrintPointer(p) + " pointing to \"'\\\"?\\\\\\a\\b\\f" EXPECT_EQ(PrintPointer(p) +
"\\n\\r\\t\\v\\x7F\\xFF a\"", " pointing to \"'\\\"?\\\\\\a\\b\\f"
"\\n\\r\\t\\v\\x7F\\xFF a\"",
Print(p)); Print(p));
} }
@ -636,10 +620,12 @@ TEST(PrintWideCStringTest, Null) {
// Tests that wide C strings are escaped properly. // Tests that wide C strings are escaped properly.
TEST(PrintWideCStringTest, EscapesProperly) { TEST(PrintWideCStringTest, EscapesProperly) {
const wchar_t s[] = {'\'', '"', '?', '\\', '\a', '\b', '\f', '\n', '\r', const wchar_t s[] = {'\'', '"', '?', '\\', '\a', '\b',
'\t', '\v', 0xD3, 0x576, 0x8D3, 0xC74D, ' ', 'a', '\0'}; '\f', '\n', '\r', '\t', '\v', 0xD3,
EXPECT_EQ(PrintPointer(s) + " pointing to L\"'\\\"?\\\\\\a\\b\\f" 0x576, 0x8D3, 0xC74D, ' ', 'a', '\0'};
"\\n\\r\\t\\v\\xD3\\x576\\x8D3\\xC74D a\"", 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))); Print(static_cast<const wchar_t*>(s)));
} }
#endif // native wchar_t #endif // native wchar_t
@ -721,10 +707,9 @@ TEST(PrintPointerTest, NonMemberFunctionPointer) {
// standard disallows casting between pointers to functions and // standard disallows casting between pointers to functions and
// pointers to objects, and some compilers (e.g. GCC 3.4) enforce // pointers to objects, and some compilers (e.g. GCC 3.4) enforce
// this limitation. // this limitation.
EXPECT_EQ( EXPECT_EQ(PrintPointer(reinterpret_cast<const void*>(
PrintPointer(reinterpret_cast<const void*>( reinterpret_cast<internal::BiggestInt>(&MyFunction))),
reinterpret_cast<internal::BiggestInt>(&MyFunction))), Print(&MyFunction));
Print(&MyFunction));
int (*p)(bool) = NULL; // NOLINT int (*p)(bool) = NULL; // NOLINT
EXPECT_EQ("NULL", Print(p)); EXPECT_EQ("NULL", Print(p));
} }
@ -733,14 +718,13 @@ TEST(PrintPointerTest, NonMemberFunctionPointer) {
// another. // another.
template <typename StringType> template <typename StringType>
AssertionResult HasPrefix(const StringType& str, const StringType& prefix) { AssertionResult HasPrefix(const StringType& str, const StringType& prefix) {
if (str.find(prefix, 0) == 0) if (str.find(prefix, 0) == 0) return AssertionSuccess();
return AssertionSuccess();
const bool is_wide_string = sizeof(prefix[0]) > 1; const bool is_wide_string = sizeof(prefix[0]) > 1;
const char* const begin_string_quote = is_wide_string ? "L\"" : "\""; const char* const begin_string_quote = is_wide_string ? "L\"" : "\"";
return AssertionFailure() return AssertionFailure()
<< begin_string_quote << prefix << "\" is not a prefix of " << begin_string_quote << prefix << "\" is not a prefix of "
<< begin_string_quote << str << "\"\n"; << begin_string_quote << str << "\"\n";
} }
// Tests printing member variable pointers. Although they are called // Tests printing member variable pointers. Although they are called
@ -761,8 +745,7 @@ TEST(PrintPointerTest, MemberVariablePointer) {
EXPECT_TRUE(HasPrefix(Print(&Foo::value), EXPECT_TRUE(HasPrefix(Print(&Foo::value),
Print(sizeof(&Foo::value)) + "-byte object ")); Print(sizeof(&Foo::value)) + "-byte object "));
int Foo::*p = NULL; // NOLINT int Foo::*p = NULL; // NOLINT
EXPECT_TRUE(HasPrefix(Print(p), EXPECT_TRUE(HasPrefix(Print(p), Print(sizeof(p)) + "-byte object "));
Print(sizeof(p)) + "-byte object "));
} }
// Tests printing member function pointers. Although they are called // Tests printing member function pointers. Although they are called
@ -776,8 +759,7 @@ TEST(PrintPointerTest, MemberFunctionPointer) {
HasPrefix(Print(&Foo::MyVirtualMethod), HasPrefix(Print(&Foo::MyVirtualMethod),
Print(sizeof((&Foo::MyVirtualMethod))) + "-byte object ")); Print(sizeof((&Foo::MyVirtualMethod))) + "-byte object "));
int (Foo::*p)(char) = NULL; // NOLINT int (Foo::*p)(char) = NULL; // NOLINT
EXPECT_TRUE(HasPrefix(Print(p), EXPECT_TRUE(HasPrefix(Print(p), Print(sizeof(p)) + "-byte object "));
Print(sizeof(p)) + "-byte object "));
} }
// Tests printing C arrays. // Tests printing C arrays.
@ -791,29 +773,26 @@ std::string PrintArrayHelper(T (&a)[N]) {
// One-dimensional array. // One-dimensional array.
TEST(PrintArrayTest, OneDimensionalArray) { 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)); EXPECT_EQ("{ 1, 2, 3, 4, 5 }", PrintArrayHelper(a));
} }
// Two-dimensional array. // Two-dimensional array.
TEST(PrintArrayTest, TwoDimensionalArray) { TEST(PrintArrayTest, TwoDimensionalArray) {
int a[2][5] = { int a[2][5] = {{1, 2, 3, 4, 5}, {6, 7, 8, 9, 0}};
{ 1, 2, 3, 4, 5 },
{ 6, 7, 8, 9, 0 }
};
EXPECT_EQ("{ { 1, 2, 3, 4, 5 }, { 6, 7, 8, 9, 0 } }", PrintArrayHelper(a)); EXPECT_EQ("{ { 1, 2, 3, 4, 5 }, { 6, 7, 8, 9, 0 } }", PrintArrayHelper(a));
} }
// Array of const elements. // Array of const elements.
TEST(PrintArrayTest, ConstArray) { TEST(PrintArrayTest, ConstArray) {
const bool a[1] = { false }; const bool a[1] = {false};
EXPECT_EQ("{ false }", PrintArrayHelper(a)); EXPECT_EQ("{ false }", PrintArrayHelper(a));
} }
// char array without terminating NUL. // char array without terminating NUL.
TEST(PrintArrayTest, CharArrayWithNoTerminatingNul) { TEST(PrintArrayTest, CharArrayWithNoTerminatingNul) {
// Array a contains '\0' in the middle and doesn't end with '\0'. // 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)); EXPECT_EQ("\"H\\0i\" (no terminating NUL)", PrintArrayHelper(a));
} }
@ -834,9 +813,7 @@ TEST(PrintArrayTest, Char8ArrayWithNoTerminatingNul) {
// char8_t array with terminating NUL. // char8_t array with terminating NUL.
TEST(PrintArrayTest, Char8ArrayWithTerminatingNul) { TEST(PrintArrayTest, Char8ArrayWithTerminatingNul) {
const char8_t a[] = u8"\0世界"; const char8_t a[] = u8"\0世界";
EXPECT_EQ( EXPECT_EQ("u8\"\\0\\xE4\\xB8\\x96\\xE7\\x95\\x8C\"", PrintArrayHelper(a));
"u8\"\\0\\xE4\\xB8\\x96\\xE7\\x95\\x8C\"",
PrintArrayHelper(a));
} }
#endif #endif
@ -889,7 +866,7 @@ TEST(PrintArrayTest, ObjectArray) {
// Array with many elements. // Array with many elements.
TEST(PrintArrayTest, BigArray) { 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 }", EXPECT_EQ("{ 1, 2, 3, 0, 0, 0, 0, 0, ..., 0, 0, 0, 0, 0, 0, 0, 0 }",
PrintArrayHelper(a)); PrintArrayHelper(a));
} }
@ -909,11 +886,14 @@ TEST(PrintStringTest, StringAmbiguousHex) {
// '\x6', '\x6B', or '\x6BA'. // '\x6', '\x6B', or '\x6BA'.
// a hex escaping sequence following by a decimal digit // 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) // 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) // 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 // a hex escaping sequence following by a non-xdigit
EXPECT_EQ("\"!\\x5-!\"", Print(::std::string("!\x5-!"))); EXPECT_EQ("\"!\\x5-!\"", Print(::std::string("!\x5-!")));
} }
@ -923,19 +903,21 @@ TEST(PrintStringTest, StringAmbiguousHex) {
// ::std::wstring. // ::std::wstring.
TEST(PrintWideStringTest, StringInStdNamespace) { TEST(PrintWideStringTest, StringInStdNamespace) {
const wchar_t s[] = L"'\"?\\\a\b\f\n\0\r\t\v\xD3\x576\x8D3\xC74D a"; 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)); const ::std::wstring str(s, sizeof(s) / sizeof(wchar_t));
EXPECT_EQ("L\"'\\\"?\\\\\\a\\b\\f\\n\\0\\r\\t\\v" EXPECT_EQ(
"\\xD3\\x576\\x8D3\\xC74D a\\0\"", "L\"'\\\"?\\\\\\a\\b\\f\\n\\0\\r\\t\\v"
Print(str)); "\\xD3\\x576\\x8D3\\xC74D a\\0\"",
Print(str));
} }
TEST(PrintWideStringTest, StringAmbiguousHex) { TEST(PrintWideStringTest, StringAmbiguousHex) {
// same for wide strings. // same for wide strings.
EXPECT_EQ("L\"0\\x12\" L\"3\"", Print(::std::wstring(L"0\x12" L"3"))); EXPECT_EQ("L\"0\\x12\" L\"3\"", Print(::std::wstring(L"0\x12"
EXPECT_EQ("L\"mm\\x6\" L\"bananas\"", L"3")));
Print(::std::wstring(L"mm\x6" L"bananas"))); EXPECT_EQ("L\"mm\\x6\" L\"bananas\"", Print(::std::wstring(L"mm\x6"
EXPECT_EQ("L\"NOM\\x6\" L\"BANANA\"", L"bananas")));
Print(::std::wstring(L"NOM\x6" L"BANANA"))); EXPECT_EQ("L\"NOM\\x6\" L\"BANANA\"", Print(::std::wstring(L"NOM\x6"
L"BANANA")));
EXPECT_EQ("L\"!\\x5-!\"", Print(::std::wstring(L"!\x5-!"))); EXPECT_EQ("L\"!\\x5-!\"", Print(::std::wstring(L"!\x5-!")));
} }
#endif // GTEST_HAS_STD_WSTRING #endif // GTEST_HAS_STD_WSTRING
@ -1049,7 +1031,6 @@ TEST(PrintStlContainerTest, NonEmptyDeque) {
EXPECT_EQ("{ 1, 3 }", Print(non_empty)); EXPECT_EQ("{ 1, 3 }", Print(non_empty));
} }
TEST(PrintStlContainerTest, OneElementHashMap) { TEST(PrintStlContainerTest, OneElementHashMap) {
::std::unordered_map<int, char> map1; ::std::unordered_map<int, char> map1;
map1[1] = 'a'; map1[1] = 'a';
@ -1065,11 +1046,9 @@ TEST(PrintStlContainerTest, HashMultiMap) {
const std::string result = Print(map1); const std::string result = Print(map1);
EXPECT_TRUE(result == "{ (5, true), (5, false) }" || EXPECT_TRUE(result == "{ (5, true), (5, false) }" ||
result == "{ (5, false), (5, true) }") result == "{ (5, false), (5, true) }")
<< " where Print(map1) returns \"" << result << "\"."; << " where Print(map1) returns \"" << result << "\".";
} }
TEST(PrintStlContainerTest, HashSet) { TEST(PrintStlContainerTest, HashSet) {
::std::unordered_set<int> set1; ::std::unordered_set<int> set1;
set1.insert(1); set1.insert(1);
@ -1078,7 +1057,7 @@ TEST(PrintStlContainerTest, HashSet) {
TEST(PrintStlContainerTest, HashMultiSet) { TEST(PrintStlContainerTest, HashMultiSet) {
const int kSize = 5; 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); ::std::unordered_multiset<int> set1(a, a + kSize);
// Elements of hash_multiset can be printed in any order. // 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); ASSERT_NE(isdigit(static_cast<unsigned char>(result[i])), 0);
numbers.push_back(result[i] - '0'); numbers.push_back(result[i] - '0');
} else { } else {
EXPECT_EQ(expected_pattern[i], result[i]) << " where result is " EXPECT_EQ(expected_pattern[i], result[i])
<< result; << " where result is " << result;
} }
} }
@ -1105,7 +1084,6 @@ TEST(PrintStlContainerTest, HashMultiSet) {
EXPECT_TRUE(std::equal(a, a + kSize, numbers.begin())); EXPECT_TRUE(std::equal(a, a + kSize, numbers.begin()));
} }
TEST(PrintStlContainerTest, List) { TEST(PrintStlContainerTest, List) {
const std::string a[] = {"hello", "world"}; const std::string a[] = {"hello", "world"};
const list<std::string> strings(a, a + 2); const list<std::string> strings(a, a + 2);
@ -1135,20 +1113,19 @@ TEST(PrintStlContainerTest, MultiMap) {
} }
TEST(PrintStlContainerTest, Set) { TEST(PrintStlContainerTest, Set) {
const unsigned int a[] = { 3, 0, 5 }; const unsigned int a[] = {3, 0, 5};
set<unsigned int> set1(a, a + 3); set<unsigned int> set1(a, a + 3);
EXPECT_EQ("{ 0, 3, 5 }", Print(set1)); EXPECT_EQ("{ 0, 3, 5 }", Print(set1));
} }
TEST(PrintStlContainerTest, MultiSet) { 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); multiset<int> set1(a, a + 5);
EXPECT_EQ("{ 1, 1, 1, 2, 5 }", Print(set1)); EXPECT_EQ("{ 1, 1, 1, 2, 5 }", Print(set1));
} }
TEST(PrintStlContainerTest, SinglyLinkedList) { TEST(PrintStlContainerTest, SinglyLinkedList) {
int a[] = { 9, 2, 8 }; int a[] = {9, 2, 8};
const std::forward_list<int> ints(a, a + 3); const std::forward_list<int> ints(a, a + 3);
EXPECT_EQ("{ 9, 2, 8 }", Print(ints)); EXPECT_EQ("{ 9, 2, 8 }", Print(ints));
} }
@ -1166,32 +1143,34 @@ TEST(PrintStlContainerTest, Vector) {
} }
TEST(PrintStlContainerTest, LongSequence) { TEST(PrintStlContainerTest, LongSequence) {
const int a[100] = { 1, 2, 3 }; const int a[100] = {1, 2, 3};
const vector<int> v(a, a + 100); 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, " EXPECT_EQ(
"0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, ... }", Print(v)); "{ 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) { TEST(PrintStlContainerTest, NestedContainer) {
const int a1[] = { 1, 2 }; const int a1[] = {1, 2};
const int a2[] = { 3, 4, 5 }; const int a2[] = {3, 4, 5};
const list<int> l1(a1, a1 + 2); const list<int> l1(a1, a1 + 2);
const list<int> l2(a2, a2 + 3); const list<int> l2(a2, a2 + 3);
vector<list<int> > v; vector<list<int>> v;
v.push_back(l1); v.push_back(l1);
v.push_back(l2); v.push_back(l2);
EXPECT_EQ("{ { 1, 2 }, { 3, 4, 5 } }", Print(v)); EXPECT_EQ("{ { 1, 2 }, { 3, 4, 5 } }", Print(v));
} }
TEST(PrintStlContainerTest, OneDimensionalNativeArray) { TEST(PrintStlContainerTest, OneDimensionalNativeArray) {
const int a[3] = { 1, 2, 3 }; const int a[3] = {1, 2, 3};
NativeArray<int> b(a, 3, RelationToSourceReference()); NativeArray<int> b(a, 3, RelationToSourceReference());
EXPECT_EQ("{ 1, 2, 3 }", Print(b)); EXPECT_EQ("{ 1, 2, 3 }", Print(b));
} }
TEST(PrintStlContainerTest, TwoDimensionalNativeArray) { 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()); NativeArray<int[3]> b(a, 2, RelationToSourceReference());
EXPECT_EQ("{ { 1, 2, 3 }, { 4, 5, 6 } }", Print(b)); 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 t10(false, 'a', static_cast<short>(3), 4, 5, 1.5F, -2.5, str, // NOLINT
nullptr, "10"); nullptr, "10");
EXPECT_EQ("(false, 'a' (97, 0x61), 3, 4, 5, 1.5, -2.5, " + PrintPointer(str) + 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)); Print(t10));
} }
// Nested tuples. // Nested tuples.
TEST(PrintStdTupleTest, NestedTuple) { TEST(PrintStdTupleTest, NestedTuple) {
::std::tuple< ::std::tuple<int, bool>, char> nested( ::std::tuple<::std::tuple<int, bool>, char> nested(::std::make_tuple(5, true),
::std::make_tuple(5, true), 'a'); 'a');
EXPECT_EQ("((5, true), 'a' (97, 0x61))", Print(nested)); EXPECT_EQ("((5, true), 'a' (97, 0x61))", Print(nested));
} }
TEST(PrintNullptrT, Basic) { TEST(PrintNullptrT, Basic) { EXPECT_EQ("(nullptr)", Print(nullptr)); }
EXPECT_EQ("(nullptr)", Print(nullptr));
}
TEST(PrintReferenceWrapper, Printable) { TEST(PrintReferenceWrapper, Printable) {
int x = 5; int x = 5;
@ -1280,8 +1257,7 @@ TEST(PrintReferenceWrapper, Unprintable) {
// Unprintable types in the global namespace. // Unprintable types in the global namespace.
TEST(PrintUnprintableTypeTest, InGlobalNamespace) { TEST(PrintUnprintableTypeTest, InGlobalNamespace) {
EXPECT_EQ("1-byte object <00>", EXPECT_EQ("1-byte object <00>", Print(UnprintableTemplateInGlobal<char>()));
Print(UnprintableTemplateInGlobal<char>()));
} }
// Unprintable types in a user namespace. // Unprintable types in a user namespace.
@ -1298,14 +1274,15 @@ struct Big {
}; };
TEST(PrintUnpritableTypeTest, BigObject) { TEST(PrintUnpritableTypeTest, BigObject) {
EXPECT_EQ("257-byte object <00-00 00-00 00-00 00-00 00-00 00-00 " EXPECT_EQ(
"00-00 00-00 00-00 00-00 00-00 00-00 00-00 00-00 00-00 00-00 " "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-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())); "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. // Tests printing user-defined streamable types.
@ -1348,8 +1325,7 @@ TEST(PrintStreamableTypeTest, PathLikeInUserNamespace) {
// Tests printing user-defined types that have a PrintTo() function. // Tests printing user-defined types that have a PrintTo() function.
TEST(PrintPrintableTypeTest, InUserNamespace) { TEST(PrintPrintableTypeTest, InUserNamespace) {
EXPECT_EQ("PrintableViaPrintTo: 0", EXPECT_EQ("PrintableViaPrintTo: 0", Print(::foo::PrintableViaPrintTo()));
Print(::foo::PrintableViaPrintTo()));
} }
// Tests printing a pointer to a user-defined type that has a << // Tests printing a pointer to a user-defined type that has a <<
@ -1371,16 +1347,14 @@ TEST(PrintReferenceTest, PrintsAddressAndValue) {
int n = 5; int n = 5;
EXPECT_EQ("@" + PrintPointer(&n) + " 5", PrintByRef(n)); EXPECT_EQ("@" + PrintPointer(&n) + " 5", PrintByRef(n));
int a[2][3] = { int a[2][3] = {{0, 1, 2}, {3, 4, 5}};
{ 0, 1, 2 },
{ 3, 4, 5 }
};
EXPECT_EQ("@" + PrintPointer(a) + " { { 0, 1, 2 }, { 3, 4, 5 } }", EXPECT_EQ("@" + PrintPointer(a) + " { { 0, 1, 2 }, { 3, 4, 5 } }",
PrintByRef(a)); PrintByRef(a));
const ::foo::UnprintableInFoo x; const ::foo::UnprintableInFoo x;
EXPECT_EQ("@" + PrintPointer(&x) + " 16-byte object " EXPECT_EQ("@" + PrintPointer(&x) +
"<EF-12 00-00 34-AB 00-00 00-00 00-00 00-00 00-00>", " 16-byte object "
"<EF-12 00-00 34-AB 00-00 00-00 00-00 00-00 00-00>",
PrintByRef(x)); PrintByRef(x));
} }
@ -1396,33 +1370,29 @@ TEST(PrintReferenceTest, HandlesFunctionPointer) {
// this limitation. // this limitation.
const std::string fp_string = PrintPointer(reinterpret_cast<const void*>( const std::string fp_string = PrintPointer(reinterpret_cast<const void*>(
reinterpret_cast<internal::BiggestInt>(fp))); reinterpret_cast<internal::BiggestInt>(fp)));
EXPECT_EQ("@" + fp_pointer_string + " " + fp_string, EXPECT_EQ("@" + fp_pointer_string + " " + fp_string, PrintByRef(fp));
PrintByRef(fp));
} }
// Tests that the universal printer prints a member function pointer // Tests that the universal printer prints a member function pointer
// passed by reference. // passed by reference.
TEST(PrintReferenceTest, HandlesMemberFunctionPointer) { TEST(PrintReferenceTest, HandlesMemberFunctionPointer) {
int (Foo::*p)(char ch) = &Foo::MyMethod; int (Foo::*p)(char ch) = &Foo::MyMethod;
EXPECT_TRUE(HasPrefix( EXPECT_TRUE(HasPrefix(PrintByRef(p),
PrintByRef(p), "@" + PrintPointer(reinterpret_cast<const void*>(&p)) +
"@" + PrintPointer(reinterpret_cast<const void*>(&p)) + " " + " " + Print(sizeof(p)) + "-byte object "));
Print(sizeof(p)) + "-byte object "));
char (Foo::*p2)(int n) = &Foo::MyVirtualMethod; char (Foo::*p2)(int n) = &Foo::MyVirtualMethod;
EXPECT_TRUE(HasPrefix( EXPECT_TRUE(HasPrefix(PrintByRef(p2),
PrintByRef(p2), "@" + PrintPointer(reinterpret_cast<const void*>(&p2)) +
"@" + PrintPointer(reinterpret_cast<const void*>(&p2)) + " " + " " + Print(sizeof(p2)) + "-byte object "));
Print(sizeof(p2)) + "-byte object "));
} }
// Tests that the universal printer prints a member variable pointer // Tests that the universal printer prints a member variable pointer
// passed by reference. // passed by reference.
TEST(PrintReferenceTest, HandlesMemberVariablePointer) { TEST(PrintReferenceTest, HandlesMemberVariablePointer) {
int Foo::*p = &Foo::value; // NOLINT int Foo::*p = &Foo::value; // NOLINT
EXPECT_TRUE(HasPrefix( EXPECT_TRUE(HasPrefix(PrintByRef(p), "@" + PrintPointer(&p) + " " +
PrintByRef(p), Print(sizeof(p)) + "-byte object "));
"@" + PrintPointer(&p) + " " + Print(sizeof(p)) + "-byte object "));
} }
// Tests that FormatForComparisonFailureMessage(), which is used to print // Tests that FormatForComparisonFailureMessage(), which is used to print
@ -1431,8 +1401,7 @@ TEST(PrintReferenceTest, HandlesMemberVariablePointer) {
// scalar // scalar
TEST(FormatForComparisonFailureMessageTest, WorksForScalar) { TEST(FormatForComparisonFailureMessageTest, WorksForScalar) {
EXPECT_STREQ("123", EXPECT_STREQ("123", FormatForComparisonFailureMessage(123, 124).c_str());
FormatForComparisonFailureMessage(123, 124).c_str());
} }
// non-char pointer // non-char pointer
@ -1446,9 +1415,8 @@ TEST(FormatForComparisonFailureMessageTest, WorksForNonCharPointer) {
TEST(FormatForComparisonFailureMessageTest, FormatsNonCharArrayAsPointer) { TEST(FormatForComparisonFailureMessageTest, FormatsNonCharArrayAsPointer) {
// In expression 'array == x', 'array' is compared by pointer. // In expression 'array == x', 'array' is compared by pointer.
// Therefore we want to print an array operand as a pointer. // Therefore we want to print an array operand as a pointer.
int n[] = { 1, 2, 3 }; int n[] = {1, 2, 3};
EXPECT_EQ(PrintPointer(n), EXPECT_EQ(PrintPointer(n), FormatForComparisonFailureMessage(n, n).c_str());
FormatForComparisonFailureMessage(n, n).c_str());
} }
// Tests formatting a char pointer when it's compared with another pointer. // Tests formatting a char pointer when it's compared with another pointer.
@ -1464,8 +1432,7 @@ TEST(FormatForComparisonFailureMessageTest, WorksForCharPointerVsPointer) {
// const char* // const char*
const char* s = "hello"; const char* s = "hello";
EXPECT_EQ(PrintPointer(s), EXPECT_EQ(PrintPointer(s), FormatForComparisonFailureMessage(s, s).c_str());
FormatForComparisonFailureMessage(s, s).c_str());
// char* // char*
char ch = 'a'; char ch = 'a';
@ -1482,8 +1449,7 @@ TEST(FormatForComparisonFailureMessageTest, WorksForWCharPointerVsPointer) {
// const wchar_t* // const wchar_t*
const wchar_t* s = L"hello"; const wchar_t* s = L"hello";
EXPECT_EQ(PrintPointer(s), EXPECT_EQ(PrintPointer(s), FormatForComparisonFailureMessage(s, s).c_str());
FormatForComparisonFailureMessage(s, s).c_str());
// wchar_t* // wchar_t*
wchar_t ch = L'a'; wchar_t ch = L'a';
@ -1580,13 +1546,11 @@ TEST(FormatForComparisonFailureMessageTest, WorksForWCharArrayVsStdWString) {
// Useful for testing PrintToString(). We cannot use EXPECT_EQ() // Useful for testing PrintToString(). We cannot use EXPECT_EQ()
// there as its implementation uses PrintToString(). The caller must // there as its implementation uses PrintToString(). The caller must
// ensure that 'value' has no side effect. // ensure that 'value' has no side effect.
#define EXPECT_PRINT_TO_STRING_(value, expected_string) \ #define EXPECT_PRINT_TO_STRING_(value, expected_string) \
EXPECT_TRUE(PrintToString(value) == (expected_string)) \ EXPECT_TRUE(PrintToString(value) == (expected_string)) \
<< " where " #value " prints as " << (PrintToString(value)) << " where " #value " prints as " << (PrintToString(value))
TEST(PrintToStringTest, WorksForScalar) { TEST(PrintToStringTest, WorksForScalar) { EXPECT_PRINT_TO_STRING_(123, "123"); }
EXPECT_PRINT_TO_STRING_(123, "123");
}
TEST(PrintToStringTest, WorksForPointerToConstChar) { TEST(PrintToStringTest, WorksForPointerToConstChar) {
const char* p = "hello"; const char* p = "hello";
@ -1611,7 +1575,7 @@ TEST(PrintToStringTest, EscapesForPointerToNonConstChar) {
} }
TEST(PrintToStringTest, WorksForArray) { TEST(PrintToStringTest, WorksForArray) {
int n[3] = { 1, 2, 3 }; int n[3] = {1, 2, 3};
EXPECT_PRINT_TO_STRING_(n, "{ 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\""); EXPECT_PRINT_TO_STRING_(mutable_str_with_nul, "\"hello\\0 world\"");
} }
TEST(PrintToStringTest, ContainsNonLatin) { TEST(PrintToStringTest, ContainsNonLatin) {
// Sanity test with valid UTF-8. Prints both in hex and as text. // Sanity test with valid UTF-8. Prints both in hex and as text.
std::string non_ascii_str = ::std::string("오전 4:30"); std::string non_ascii_str = ::std::string("오전 4:30");
EXPECT_PRINT_TO_STRING_(non_ascii_str, 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 // as hex only (or ASCII, in case of ASCII bytes) because IsValidUTF8() is
// expected to fail, thus output does not contain "As Text:". // expected to fail, thus output does not contain "As Text:".
static const char *const kTestdata[][2] = { static const char* const kTestdata[][2] = {
// 2-byte lead byte followed by a single-byte character. // 2-byte lead byte followed by a single-byte character.
{"\xC3\x74", "\"\\xC3t\""}, {"\xC3\x74", "\"\\xC3t\""},
// Valid 2-byte character followed by an orphan trail byte. // Valid 2-byte character followed by an orphan trail byte.
{"\xC3\x84\xA4", "\"\\xC3\\x84\\xA4\""}, {"\xC3\x84\xA4", "\"\\xC3\\x84\\xA4\""},
// Lead byte without trail byte. // Lead byte without trail byte.
{"abc\xC3", "\"abc\\xC3\""}, {"abc\xC3", "\"abc\\xC3\""},
// 3-byte lead byte, single-byte character, orphan trail byte. // 3-byte lead byte, single-byte character, orphan trail byte.
{"x\xE2\x70\x94", "\"x\\xE2p\\x94\""}, {"x\xE2\x70\x94", "\"x\\xE2p\\x94\""},
// Truncated 3-byte character. // Truncated 3-byte character.
{"\xE2\x80", "\"\\xE2\\x80\""}, {"\xE2\x80", "\"\\xE2\\x80\""},
// Truncated 3-byte character followed by valid 2-byte char. // Truncated 3-byte character followed by valid 2-byte char.
{"\xE2\x80\xC3\x84", "\"\\xE2\\x80\\xC3\\x84\""}, {"\xE2\x80\xC3\x84", "\"\\xE2\\x80\\xC3\\x84\""},
// Truncated 3-byte character followed by a single-byte character. // Truncated 3-byte character followed by a single-byte character.
{"\xE2\x80\x7A", "\"\\xE2\\x80z\""}, {"\xE2\x80\x7A", "\"\\xE2\\x80z\""},
// 3-byte lead byte followed by valid 3-byte character. // 3-byte lead byte followed by valid 3-byte character.
{"\xE2\xE2\x80\x94", "\"\\xE2\\xE2\\x80\\x94\""}, {"\xE2\xE2\x80\x94", "\"\\xE2\\xE2\\x80\\x94\""},
// 4-byte lead byte followed by valid 3-byte character. // 4-byte lead byte followed by valid 3-byte character.
{"\xF0\xE2\x80\x94", "\"\\xF0\\xE2\\x80\\x94\""}, {"\xF0\xE2\x80\x94", "\"\\xF0\\xE2\\x80\\x94\""},
// Truncated 4-byte character. // Truncated 4-byte character.
{"\xF0\xE2\x80", "\"\\xF0\\xE2\\x80\""}, {"\xF0\xE2\x80", "\"\\xF0\\xE2\\x80\""},
// Invalid UTF-8 byte sequences embedded in other chars. // Invalid UTF-8 byte sequences embedded in other chars.
{"abc\xE2\x80\x94\xC3\x74xyc", "\"abc\\xE2\\x80\\x94\\xC3txyc\""}, {"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",
"\"abc\\xC3\\x84\\xE2\\x80\\xC3\\x84xyz\""}, "\"abc\\xC3\\x84\\xE2\\x80\\xC3\\x84xyz\""},
// Non-shortest UTF-8 byte sequences are also ill-formed. // Non-shortest UTF-8 byte sequences are also ill-formed.
// The classics: xC0, xC1 lead byte. // The classics: xC0, xC1 lead byte.
{"\xC0\x80", "\"\\xC0\\x80\""}, {"\xC0\x80", "\"\\xC0\\x80\""},
{"\xC1\x81", "\"\\xC1\\x81\""}, {"\xC1\x81", "\"\\xC1\\x81\""},
// Non-shortest sequences. // Non-shortest sequences.
{"\xE0\x80\x80", "\"\\xE0\\x80\\x80\""}, {"\xE0\x80\x80", "\"\\xE0\\x80\\x80\""},
{"\xf0\x80\x80\x80", "\"\\xF0\\x80\\x80\\x80\""}, {"\xf0\x80\x80\x80", "\"\\xF0\\x80\\x80\\x80\""},
// Last valid code point before surrogate range, should be printed as text, // Last valid code point before surrogate range, should be printed as
// too. // text,
{"\xED\x9F\xBF", "\"\\xED\\x9F\\xBF\"\n As Text: \"\""}, // too.
// Start of surrogate lead. Surrogates are not printed as text. {"\xED\x9F\xBF", "\"\\xED\\x9F\\xBF\"\n As Text: \"\""},
{"\xED\xA0\x80", "\"\\xED\\xA0\\x80\""}, // Start of surrogate lead. Surrogates are not printed as text.
// Last non-private surrogate lead. {"\xED\xA0\x80", "\"\\xED\\xA0\\x80\""},
{"\xED\xAD\xBF", "\"\\xED\\xAD\\xBF\""}, // Last non-private surrogate lead.
// First private-use surrogate lead. {"\xED\xAD\xBF", "\"\\xED\\xAD\\xBF\""},
{"\xED\xAE\x80", "\"\\xED\\xAE\\x80\""}, // First private-use surrogate lead.
// Last private-use surrogate lead. {"\xED\xAE\x80", "\"\\xED\\xAE\\x80\""},
{"\xED\xAF\xBF", "\"\\xED\\xAF\\xBF\""}, // Last private-use surrogate lead.
// Mid-point of surrogate trail. {"\xED\xAF\xBF", "\"\\xED\\xAF\\xBF\""},
{"\xED\xB3\xBF", "\"\\xED\\xB3\\xBF\""}, // Mid-point of surrogate trail.
// First valid code point after surrogate range, should be printed as text, {"\xED\xB3\xBF", "\"\\xED\\xB3\\xBF\""},
// too. // First valid code point after surrogate range, should be printed as
{"\xEE\x80\x80", "\"\\xEE\\x80\\x80\"\n As Text: \"\""} // text,
}; // too.
{"\xEE\x80\x80", "\"\\xEE\\x80\\x80\"\n As Text: \"\""}};
for (int i = 0; i < int(sizeof(kTestdata)/sizeof(kTestdata[0])); ++i) { for (int i = 0; i < int(sizeof(kTestdata) / sizeof(kTestdata[0])); ++i) {
EXPECT_PRINT_TO_STRING_(kTestdata[i][0], kTestdata[i][1]); EXPECT_PRINT_TO_STRING_(kTestdata[i][0], kTestdata[i][1]);
} }
} }
@ -1844,15 +1809,15 @@ TEST(UniversalTersePrintTupleFieldsToStringsTestWithStd, PrintsEmptyTuple) {
} }
TEST(UniversalTersePrintTupleFieldsToStringsTestWithStd, PrintsOneTuple) { TEST(UniversalTersePrintTupleFieldsToStringsTestWithStd, PrintsOneTuple) {
Strings result = UniversalTersePrintTupleFieldsToStrings( Strings result =
::std::make_tuple(1)); UniversalTersePrintTupleFieldsToStrings(::std::make_tuple(1));
ASSERT_EQ(1u, result.size()); ASSERT_EQ(1u, result.size());
EXPECT_EQ("1", result[0]); EXPECT_EQ("1", result[0]);
} }
TEST(UniversalTersePrintTupleFieldsToStringsTestWithStd, PrintsTwoTuple) { TEST(UniversalTersePrintTupleFieldsToStringsTestWithStd, PrintsTwoTuple) {
Strings result = UniversalTersePrintTupleFieldsToStrings( Strings result =
::std::make_tuple(1, 'a')); UniversalTersePrintTupleFieldsToStrings(::std::make_tuple(1, 'a'));
ASSERT_EQ(2u, result.size()); ASSERT_EQ(2u, result.size());
EXPECT_EQ("1", result[0]); EXPECT_EQ("1", result[0]);
EXPECT_EQ("'a' (97, 0x61)", result[1]); EXPECT_EQ("'a' (97, 0x61)", result[1]);

Some files were not shown because too many files have changed in this diff Show More