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

@ -196,9 +196,7 @@ class BuiltInDefaultValue {
public:
// This function returns true if and only if type T has a built-in default
// value.
static bool Exists() {
return ::std::is_default_constructible<T>::value;
}
static bool Exists() { return ::std::is_default_constructible<T>::value; }
static T Get() {
return BuiltInDefaultValueGetter<
@ -862,7 +860,9 @@ class DoDefaultAction {
// This template type conversion operator allows DoDefault() to be
// used in any function.
template <typename F>
operator Action<F>() const { return Action<F>(); } // NOLINT
operator Action<F>() const {
return Action<F>();
} // NOLINT
};
// Implements the Assign action to set a given pointer referent to a
@ -890,8 +890,7 @@ template <typename T>
class SetErrnoAndReturnAction {
public:
SetErrnoAndReturnAction(int errno_value, T result)
: errno_(errno_value),
result_(result) {}
: errno_(errno_value), result_(result) {}
template <typename Result, typename ArgumentTuple>
Result Perform(const ArgumentTuple& /* args */) const {
errno = errno_;
@ -1002,8 +1001,8 @@ class IgnoreResultAction {
private:
// Type OriginalFunction is the same as F except that its return
// type is IgnoredValue.
typedef typename internal::Function<F>::MakeResultIgnoredValue
OriginalFunction;
typedef
typename internal::Function<F>::MakeResultIgnoredValue OriginalFunction;
const Action<OriginalFunction> action_;
};
@ -1020,8 +1019,8 @@ struct WithArgsAction {
template <typename R, typename... Args>
operator Action<R(Args...)>() const { // NOLINT
using TupleType = std::tuple<Args...>;
Action<R(typename std::tuple_element<I, TupleType>::type...)>
converted(action);
Action<R(typename std::tuple_element<I, TupleType>::type...)> converted(
action);
return [converted](Args... args) -> R {
return converted.Perform(std::forward_as_tuple(
@ -1212,8 +1211,8 @@ internal::DoAllAction<typename std::decay<Action>::type...> DoAll(
// multiple arguments. For convenience, we also provide
// WithArgs<k>(an_action) (defined below) as a synonym.
template <size_t k, typename InnerAction>
internal::WithArgsAction<typename std::decay<InnerAction>::type, k>
WithArg(InnerAction&& action) {
internal::WithArgsAction<typename std::decay<InnerAction>::type, k> WithArg(
InnerAction&& action) {
return {std::forward<InnerAction>(action)};
}
@ -1232,8 +1231,8 @@ WithArgs(InnerAction&& action) {
// argument. In other words, it adapts an action accepting no
// argument to one that accepts (and ignores) arguments.
template <typename InnerAction>
internal::WithArgsAction<typename std::decay<InnerAction>::type>
WithoutArgs(InnerAction&& action) {
internal::WithArgsAction<typename std::decay<InnerAction>::type> WithoutArgs(
InnerAction&& action) {
return {std::forward<InnerAction>(action)};
}
@ -1327,8 +1326,8 @@ PolymorphicAction<internal::AssignAction<T1, T2> > Assign(T1* ptr, T2 val) {
// Creates an action that sets errno and returns the appropriate error.
template <typename T>
PolymorphicAction<internal::SetErrnoAndReturnAction<T> >
SetErrnoAndReturn(int errval, T result) {
PolymorphicAction<internal::SetErrnoAndReturnAction<T>> SetErrnoAndReturn(
int errval, T result) {
return MakePolymorphicAction(
internal::SetErrnoAndReturnAction<T>(errval, result));
}
@ -1482,7 +1481,8 @@ struct ExcessiveArg {};
// Builds an implementation of an Action<> for some particular signature, using
// a class defined by an ACTION* macro.
template <typename F, typename Impl> struct ActionImpl;
template <typename F, typename Impl>
struct ActionImpl;
template <typename Impl>
struct ImplBase {
@ -1521,10 +1521,12 @@ struct ActionImpl<R(Args...), Impl> : ImplBase<Impl>::type {
// args_type get passed, followed by a dummy of unspecified type for the
// remainder up to 10 explicit args.
static constexpr ExcessiveArg kExcessArg{};
return static_cast<const Impl&>(*this).template gmock_PerformImpl<
return static_cast<const Impl&>(*this)
.template gmock_PerformImpl<
/*function_type=*/function_type, /*return_type=*/R,
/*args_type=*/args_type,
/*argN_type=*/typename std::tuple_element<arg_id, args_type>::type...>(
/*argN_type=*/
typename std::tuple_element<arg_id, args_type>::type...>(
/*args=*/args, std::get<arg_id>(args)...,
((void)excess_id, kExcessArg)...);
}
@ -1597,6 +1599,7 @@ template <typename F, typename Impl>
operator ::testing::Action<F>() const { \
return ::testing::internal::MakeAction<F>(impl_); \
} \
\
private: \
class gmock_Impl { \
public: \
@ -1621,8 +1624,9 @@ template <typename F, typename Impl>
template <GMOCK_ACTION_TYPENAME_PARAMS_(params)> \
template <typename function_type, typename return_type, typename args_type, \
GMOCK_ACTION_TEMPLATE_ARGS_NAMES_> \
return_type full_name<GMOCK_ACTION_TYPE_PARAMS_(params)>::gmock_Impl:: \
gmock_PerformImpl(GMOCK_ACTION_ARG_TYPES_AND_NAMES_UNUSED_) const
return_type \
full_name<GMOCK_ACTION_TYPE_PARAMS_(params)>::gmock_Impl::gmock_PerformImpl( \
GMOCK_ACTION_ARG_TYPES_AND_NAMES_UNUSED_) const
} // namespace internal
@ -1636,6 +1640,7 @@ template <typename F, typename Impl>
operator ::testing::Action<F>() const { \
return ::testing::internal::MakeAction<F, gmock_Impl>(); \
} \
\
private: \
class gmock_Impl { \
public: \

View File

@ -40,8 +40,10 @@
#define GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_CARDINALITIES_H_
#include <limits.h>
#include <memory>
#include <ostream> // NOLINT
#include "gmock/internal/gmock-port.h"
#include "gtest/gtest.h"

View File

@ -129,165 +129,202 @@
// Declares the template parameters.
#define GMOCK_INTERNAL_DECL_HAS_1_TEMPLATE_PARAMS(kind0, name0) kind0 name0
#define GMOCK_INTERNAL_DECL_HAS_2_TEMPLATE_PARAMS(kind0, name0, kind1, \
name1) kind0 name0, kind1 name1
#define GMOCK_INTERNAL_DECL_HAS_2_TEMPLATE_PARAMS(kind0, name0, kind1, name1) \
kind0 name0, kind1 name1
#define GMOCK_INTERNAL_DECL_HAS_3_TEMPLATE_PARAMS(kind0, name0, kind1, name1, \
kind2, name2) kind0 name0, kind1 name1, kind2 name2
kind2, name2) \
kind0 name0, kind1 name1, kind2 name2
#define GMOCK_INTERNAL_DECL_HAS_4_TEMPLATE_PARAMS(kind0, name0, kind1, name1, \
kind2, name2, kind3, name3) kind0 name0, kind1 name1, kind2 name2, \
kind3 name3
#define GMOCK_INTERNAL_DECL_HAS_5_TEMPLATE_PARAMS(kind0, name0, kind1, name1, \
kind2, name2, kind3, name3, kind4, name4) kind0 name0, kind1 name1, \
kind2 name2, kind3 name3, kind4 name4
kind2, name2, kind3, name3) \
kind0 name0, kind1 name1, kind2 name2, kind3 name3
#define GMOCK_INTERNAL_DECL_HAS_5_TEMPLATE_PARAMS( \
kind0, name0, kind1, name1, kind2, name2, kind3, name3, kind4, name4) \
kind0 name0, kind1 name1, kind2 name2, kind3 name3, kind4 name4
#define GMOCK_INTERNAL_DECL_HAS_6_TEMPLATE_PARAMS(kind0, name0, kind1, name1, \
kind2, name2, kind3, name3, kind4, name4, kind5, name5) kind0 name0, \
kind1 name1, kind2 name2, kind3 name3, kind4 name4, kind5 name5
#define GMOCK_INTERNAL_DECL_HAS_7_TEMPLATE_PARAMS(kind0, name0, kind1, name1, \
kind2, name2, kind3, name3, kind4, name4, kind5, name5, kind6, \
name6) kind0 name0, kind1 name1, kind2 name2, kind3 name3, kind4 name4, \
kind2, name2, kind3, name3, \
kind4, name4, kind5, name5) \
kind0 name0, kind1 name1, kind2 name2, kind3 name3, kind4 name4, kind5 name5
#define GMOCK_INTERNAL_DECL_HAS_7_TEMPLATE_PARAMS( \
kind0, name0, kind1, name1, kind2, name2, kind3, name3, kind4, name4, \
kind5, name5, kind6, name6) \
kind0 name0, kind1 name1, kind2 name2, kind3 name3, kind4 name4, \
kind5 name5, kind6 name6
#define GMOCK_INTERNAL_DECL_HAS_8_TEMPLATE_PARAMS(kind0, name0, kind1, name1, \
kind2, name2, kind3, name3, kind4, name4, kind5, name5, kind6, name6, \
kind7, name7) kind0 name0, kind1 name1, kind2 name2, kind3 name3, \
kind4 name4, kind5 name5, kind6 name6, kind7 name7
#define GMOCK_INTERNAL_DECL_HAS_9_TEMPLATE_PARAMS(kind0, name0, kind1, name1, \
kind2, name2, kind3, name3, kind4, name4, kind5, name5, kind6, name6, \
kind7, name7, kind8, name8) kind0 name0, kind1 name1, kind2 name2, \
kind3 name3, kind4 name4, kind5 name5, kind6 name6, kind7 name7, \
kind8 name8
#define GMOCK_INTERNAL_DECL_HAS_10_TEMPLATE_PARAMS(kind0, name0, kind1, \
name1, kind2, name2, kind3, name3, kind4, name4, kind5, name5, kind6, \
name6, kind7, name7, kind8, name8, kind9, name9) kind0 name0, \
kind1 name1, kind2 name2, kind3 name3, kind4 name4, kind5 name5, \
kind6 name6, kind7 name7, kind8 name8, kind9 name9
#define GMOCK_INTERNAL_DECL_HAS_8_TEMPLATE_PARAMS( \
kind0, name0, kind1, name1, kind2, name2, kind3, name3, kind4, name4, \
kind5, name5, kind6, name6, kind7, name7) \
kind0 name0, kind1 name1, kind2 name2, kind3 name3, kind4 name4, \
kind5 name5, kind6 name6, kind7 name7
#define GMOCK_INTERNAL_DECL_HAS_9_TEMPLATE_PARAMS( \
kind0, name0, kind1, name1, kind2, name2, kind3, name3, kind4, name4, \
kind5, name5, kind6, name6, kind7, name7, kind8, name8) \
kind0 name0, kind1 name1, kind2 name2, kind3 name3, kind4 name4, \
kind5 name5, kind6 name6, kind7 name7, kind8 name8
#define GMOCK_INTERNAL_DECL_HAS_10_TEMPLATE_PARAMS( \
kind0, name0, kind1, name1, kind2, name2, kind3, name3, kind4, name4, \
kind5, name5, kind6, name6, kind7, name7, kind8, name8, kind9, name9) \
kind0 name0, kind1 name1, kind2 name2, kind3 name3, kind4 name4, \
kind5 name5, kind6 name6, kind7 name7, kind8 name8, kind9 name9
// Lists the template parameters.
#define GMOCK_INTERNAL_LIST_HAS_1_TEMPLATE_PARAMS(kind0, name0) name0
#define GMOCK_INTERNAL_LIST_HAS_2_TEMPLATE_PARAMS(kind0, name0, kind1, \
name1) name0, name1
#define GMOCK_INTERNAL_LIST_HAS_2_TEMPLATE_PARAMS(kind0, name0, kind1, name1) \
name0, name1
#define GMOCK_INTERNAL_LIST_HAS_3_TEMPLATE_PARAMS(kind0, name0, kind1, name1, \
kind2, name2) name0, name1, name2
kind2, name2) \
name0, name1, name2
#define GMOCK_INTERNAL_LIST_HAS_4_TEMPLATE_PARAMS(kind0, name0, kind1, name1, \
kind2, name2, kind3, name3) name0, name1, name2, name3
#define GMOCK_INTERNAL_LIST_HAS_5_TEMPLATE_PARAMS(kind0, name0, kind1, name1, \
kind2, name2, kind3, name3, kind4, name4) name0, name1, name2, name3, \
name4
kind2, name2, kind3, name3) \
name0, name1, name2, name3
#define GMOCK_INTERNAL_LIST_HAS_5_TEMPLATE_PARAMS( \
kind0, name0, kind1, name1, kind2, name2, kind3, name3, kind4, name4) \
name0, name1, name2, name3, name4
#define GMOCK_INTERNAL_LIST_HAS_6_TEMPLATE_PARAMS(kind0, name0, kind1, name1, \
kind2, name2, kind3, name3, kind4, name4, kind5, name5) name0, name1, \
name2, name3, name4, name5
#define GMOCK_INTERNAL_LIST_HAS_7_TEMPLATE_PARAMS(kind0, name0, kind1, name1, \
kind2, name2, kind3, name3, kind4, name4, kind5, name5, kind6, \
name6) name0, name1, name2, name3, name4, name5, name6
#define GMOCK_INTERNAL_LIST_HAS_8_TEMPLATE_PARAMS(kind0, name0, kind1, name1, \
kind2, name2, kind3, name3, kind4, name4, kind5, name5, kind6, name6, \
kind7, name7) name0, name1, name2, name3, name4, name5, name6, name7
#define GMOCK_INTERNAL_LIST_HAS_9_TEMPLATE_PARAMS(kind0, name0, kind1, name1, \
kind2, name2, kind3, name3, kind4, name4, kind5, name5, kind6, name6, \
kind7, name7, kind8, name8) name0, name1, name2, name3, name4, name5, \
name6, name7, name8
#define GMOCK_INTERNAL_LIST_HAS_10_TEMPLATE_PARAMS(kind0, name0, kind1, \
name1, kind2, name2, kind3, name3, kind4, name4, kind5, name5, kind6, \
name6, kind7, name7, kind8, name8, kind9, name9) name0, name1, name2, \
name3, name4, name5, name6, name7, name8, name9
kind2, name2, kind3, name3, \
kind4, name4, kind5, name5) \
name0, name1, name2, name3, name4, name5
#define GMOCK_INTERNAL_LIST_HAS_7_TEMPLATE_PARAMS( \
kind0, name0, kind1, name1, kind2, name2, kind3, name3, kind4, name4, \
kind5, name5, kind6, name6) \
name0, name1, name2, name3, name4, name5, name6
#define GMOCK_INTERNAL_LIST_HAS_8_TEMPLATE_PARAMS( \
kind0, name0, kind1, name1, kind2, name2, kind3, name3, kind4, name4, \
kind5, name5, kind6, name6, kind7, name7) \
name0, name1, name2, name3, name4, name5, name6, name7
#define GMOCK_INTERNAL_LIST_HAS_9_TEMPLATE_PARAMS( \
kind0, name0, kind1, name1, kind2, name2, kind3, name3, kind4, name4, \
kind5, name5, kind6, name6, kind7, name7, kind8, name8) \
name0, name1, name2, name3, name4, name5, name6, name7, name8
#define GMOCK_INTERNAL_LIST_HAS_10_TEMPLATE_PARAMS( \
kind0, name0, kind1, name1, kind2, name2, kind3, name3, kind4, name4, \
kind5, name5, kind6, name6, kind7, name7, kind8, name8, kind9, name9) \
name0, name1, name2, name3, name4, name5, name6, name7, name8, name9
// Declares the types of value parameters.
#define GMOCK_INTERNAL_DECL_TYPE_AND_0_VALUE_PARAMS()
#define GMOCK_INTERNAL_DECL_TYPE_AND_1_VALUE_PARAMS(p0) , typename p0##_type
#define GMOCK_INTERNAL_DECL_TYPE_AND_2_VALUE_PARAMS(p0, p1) , \
typename p0##_type, typename p1##_type
#define GMOCK_INTERNAL_DECL_TYPE_AND_3_VALUE_PARAMS(p0, p1, p2) , \
typename p0##_type, typename p1##_type, typename p2##_type
#define GMOCK_INTERNAL_DECL_TYPE_AND_4_VALUE_PARAMS(p0, p1, p2, p3) , \
typename p0##_type, typename p1##_type, typename p2##_type, \
#define GMOCK_INTERNAL_DECL_TYPE_AND_2_VALUE_PARAMS(p0, p1) \
, typename p0##_type, typename p1##_type
#define GMOCK_INTERNAL_DECL_TYPE_AND_3_VALUE_PARAMS(p0, p1, p2) \
, typename p0##_type, typename p1##_type, typename p2##_type
#define GMOCK_INTERNAL_DECL_TYPE_AND_4_VALUE_PARAMS(p0, p1, p2, p3) \
, typename p0##_type, typename p1##_type, typename p2##_type, \
typename p3##_type
#define GMOCK_INTERNAL_DECL_TYPE_AND_5_VALUE_PARAMS(p0, p1, p2, p3, p4) , \
typename p0##_type, typename p1##_type, typename p2##_type, \
#define GMOCK_INTERNAL_DECL_TYPE_AND_5_VALUE_PARAMS(p0, p1, p2, p3, p4) \
, typename p0##_type, typename p1##_type, typename p2##_type, \
typename p3##_type, typename p4##_type
#define GMOCK_INTERNAL_DECL_TYPE_AND_6_VALUE_PARAMS(p0, p1, p2, p3, p4, p5) , \
typename p0##_type, typename p1##_type, typename p2##_type, \
#define GMOCK_INTERNAL_DECL_TYPE_AND_6_VALUE_PARAMS(p0, p1, p2, p3, p4, p5) \
, typename p0##_type, typename p1##_type, typename p2##_type, \
typename p3##_type, typename p4##_type, typename p5##_type
#define GMOCK_INTERNAL_DECL_TYPE_AND_7_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, \
p6) , typename p0##_type, typename p1##_type, typename p2##_type, \
p6) \
, typename p0##_type, typename p1##_type, typename p2##_type, \
typename p3##_type, typename p4##_type, typename p5##_type, \
typename p6##_type
#define GMOCK_INTERNAL_DECL_TYPE_AND_8_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, \
p6, p7) , typename p0##_type, typename p1##_type, typename p2##_type, \
p6, p7) \
, typename p0##_type, typename p1##_type, typename p2##_type, \
typename p3##_type, typename p4##_type, typename p5##_type, \
typename p6##_type, typename p7##_type
#define GMOCK_INTERNAL_DECL_TYPE_AND_9_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, \
p6, p7, p8) , typename p0##_type, typename p1##_type, typename p2##_type, \
p6, p7, p8) \
, typename p0##_type, typename p1##_type, typename p2##_type, \
typename p3##_type, typename p4##_type, typename p5##_type, \
typename p6##_type, typename p7##_type, typename p8##_type
#define GMOCK_INTERNAL_DECL_TYPE_AND_10_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, \
p6, p7, p8, p9) , typename p0##_type, typename p1##_type, \
typename p2##_type, typename p3##_type, typename p4##_type, \
typename p5##_type, typename p6##_type, typename p7##_type, \
typename p8##_type, typename p9##_type
p6, p7, p8, p9) \
, typename p0##_type, typename p1##_type, typename p2##_type, \
typename p3##_type, typename p4##_type, typename p5##_type, \
typename p6##_type, typename p7##_type, typename p8##_type, \
typename p9##_type
// Initializes the value parameters.
#define GMOCK_INTERNAL_INIT_AND_0_VALUE_PARAMS()\
()
#define GMOCK_INTERNAL_INIT_AND_0_VALUE_PARAMS() ()
#define GMOCK_INTERNAL_INIT_AND_1_VALUE_PARAMS(p0) \
(p0##_type gmock_p0) : p0(::std::move(gmock_p0))
#define GMOCK_INTERNAL_INIT_AND_2_VALUE_PARAMS(p0, p1) \
(p0##_type gmock_p0, p1##_type gmock_p1) : p0(::std::move(gmock_p0)), \
p1(::std::move(gmock_p1))
(p0##_type gmock_p0, p1##_type gmock_p1) \
: p0(::std::move(gmock_p0)), p1(::std::move(gmock_p1))
#define GMOCK_INTERNAL_INIT_AND_3_VALUE_PARAMS(p0, p1, p2) \
(p0##_type gmock_p0, p1##_type gmock_p1, \
p2##_type gmock_p2) : p0(::std::move(gmock_p0)), \
p1(::std::move(gmock_p1)), p2(::std::move(gmock_p2))
(p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2) \
: p0(::std::move(gmock_p0)), \
p1(::std::move(gmock_p1)), \
p2(::std::move(gmock_p2))
#define GMOCK_INTERNAL_INIT_AND_4_VALUE_PARAMS(p0, p1, p2, p3) \
(p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \
p3##_type gmock_p3) : p0(::std::move(gmock_p0)), \
p1(::std::move(gmock_p1)), p2(::std::move(gmock_p2)), \
p3##_type gmock_p3) \
: p0(::std::move(gmock_p0)), \
p1(::std::move(gmock_p1)), \
p2(::std::move(gmock_p2)), \
p3(::std::move(gmock_p3))
#define GMOCK_INTERNAL_INIT_AND_5_VALUE_PARAMS(p0, p1, p2, p3, p4) \
(p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \
p3##_type gmock_p3, p4##_type gmock_p4) : p0(::std::move(gmock_p0)), \
p1(::std::move(gmock_p1)), p2(::std::move(gmock_p2)), \
p3(::std::move(gmock_p3)), p4(::std::move(gmock_p4))
p3##_type gmock_p3, p4##_type gmock_p4) \
: p0(::std::move(gmock_p0)), \
p1(::std::move(gmock_p1)), \
p2(::std::move(gmock_p2)), \
p3(::std::move(gmock_p3)), \
p4(::std::move(gmock_p4))
#define GMOCK_INTERNAL_INIT_AND_6_VALUE_PARAMS(p0, p1, p2, p3, p4, p5) \
(p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \
p3##_type gmock_p3, p4##_type gmock_p4, \
p5##_type gmock_p5) : p0(::std::move(gmock_p0)), \
p1(::std::move(gmock_p1)), p2(::std::move(gmock_p2)), \
p3(::std::move(gmock_p3)), p4(::std::move(gmock_p4)), \
p3##_type gmock_p3, p4##_type gmock_p4, p5##_type gmock_p5) \
: p0(::std::move(gmock_p0)), \
p1(::std::move(gmock_p1)), \
p2(::std::move(gmock_p2)), \
p3(::std::move(gmock_p3)), \
p4(::std::move(gmock_p4)), \
p5(::std::move(gmock_p5))
#define GMOCK_INTERNAL_INIT_AND_7_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6) \
(p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \
p3##_type gmock_p3, p4##_type gmock_p4, p5##_type gmock_p5, \
p6##_type gmock_p6) : p0(::std::move(gmock_p0)), \
p1(::std::move(gmock_p1)), p2(::std::move(gmock_p2)), \
p3(::std::move(gmock_p3)), p4(::std::move(gmock_p4)), \
p5(::std::move(gmock_p5)), p6(::std::move(gmock_p6))
p6##_type gmock_p6) \
: p0(::std::move(gmock_p0)), \
p1(::std::move(gmock_p1)), \
p2(::std::move(gmock_p2)), \
p3(::std::move(gmock_p3)), \
p4(::std::move(gmock_p4)), \
p5(::std::move(gmock_p5)), \
p6(::std::move(gmock_p6))
#define GMOCK_INTERNAL_INIT_AND_8_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, p7) \
(p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \
p3##_type gmock_p3, p4##_type gmock_p4, p5##_type gmock_p5, \
p6##_type gmock_p6, p7##_type gmock_p7) : p0(::std::move(gmock_p0)), \
p1(::std::move(gmock_p1)), p2(::std::move(gmock_p2)), \
p3(::std::move(gmock_p3)), p4(::std::move(gmock_p4)), \
p5(::std::move(gmock_p5)), p6(::std::move(gmock_p6)), \
p6##_type gmock_p6, p7##_type gmock_p7) \
: p0(::std::move(gmock_p0)), \
p1(::std::move(gmock_p1)), \
p2(::std::move(gmock_p2)), \
p3(::std::move(gmock_p3)), \
p4(::std::move(gmock_p4)), \
p5(::std::move(gmock_p5)), \
p6(::std::move(gmock_p6)), \
p7(::std::move(gmock_p7))
#define GMOCK_INTERNAL_INIT_AND_9_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, \
p7, p8)\
#define GMOCK_INTERNAL_INIT_AND_9_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, p7, \
p8) \
(p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \
p3##_type gmock_p3, p4##_type gmock_p4, p5##_type gmock_p5, \
p6##_type gmock_p6, p7##_type gmock_p7, \
p8##_type gmock_p8) : p0(::std::move(gmock_p0)), \
p1(::std::move(gmock_p1)), p2(::std::move(gmock_p2)), \
p3(::std::move(gmock_p3)), p4(::std::move(gmock_p4)), \
p5(::std::move(gmock_p5)), p6(::std::move(gmock_p6)), \
p7(::std::move(gmock_p7)), p8(::std::move(gmock_p8))
p6##_type gmock_p6, p7##_type gmock_p7, p8##_type gmock_p8) \
: p0(::std::move(gmock_p0)), \
p1(::std::move(gmock_p1)), \
p2(::std::move(gmock_p2)), \
p3(::std::move(gmock_p3)), \
p4(::std::move(gmock_p4)), \
p5(::std::move(gmock_p5)), \
p6(::std::move(gmock_p6)), \
p7(::std::move(gmock_p7)), \
p8(::std::move(gmock_p8))
#define GMOCK_INTERNAL_INIT_AND_10_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, \
p7, p8, p9) \
(p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \
p3##_type gmock_p3, p4##_type gmock_p4, p5##_type gmock_p5, \
p6##_type gmock_p6, p7##_type gmock_p7, p8##_type gmock_p8, \
p9##_type gmock_p9) : p0(::std::move(gmock_p0)), \
p1(::std::move(gmock_p1)), p2(::std::move(gmock_p2)), \
p3(::std::move(gmock_p3)), p4(::std::move(gmock_p4)), \
p5(::std::move(gmock_p5)), p6(::std::move(gmock_p6)), \
p7(::std::move(gmock_p7)), p8(::std::move(gmock_p8)), \
p9##_type gmock_p9) \
: p0(::std::move(gmock_p0)), \
p1(::std::move(gmock_p1)), \
p2(::std::move(gmock_p2)), \
p3(::std::move(gmock_p3)), \
p4(::std::move(gmock_p4)), \
p5(::std::move(gmock_p5)), \
p6(::std::move(gmock_p6)), \
p7(::std::move(gmock_p7)), \
p8(::std::move(gmock_p8)), \
p9(::std::move(gmock_p9))
// Defines the copy constructor
@ -307,29 +344,70 @@
// Declares the fields for storing the value parameters.
#define GMOCK_INTERNAL_DEFN_AND_0_VALUE_PARAMS()
#define GMOCK_INTERNAL_DEFN_AND_1_VALUE_PARAMS(p0) p0##_type p0;
#define GMOCK_INTERNAL_DEFN_AND_2_VALUE_PARAMS(p0, p1) p0##_type p0; \
#define GMOCK_INTERNAL_DEFN_AND_2_VALUE_PARAMS(p0, p1) \
p0##_type p0; \
p1##_type p1;
#define GMOCK_INTERNAL_DEFN_AND_3_VALUE_PARAMS(p0, p1, p2) p0##_type p0; \
p1##_type p1; p2##_type p2;
#define GMOCK_INTERNAL_DEFN_AND_4_VALUE_PARAMS(p0, p1, p2, p3) p0##_type p0; \
p1##_type p1; p2##_type p2; p3##_type p3;
#define GMOCK_INTERNAL_DEFN_AND_5_VALUE_PARAMS(p0, p1, p2, p3, \
p4) p0##_type p0; p1##_type p1; p2##_type p2; p3##_type p3; p4##_type p4;
#define GMOCK_INTERNAL_DEFN_AND_6_VALUE_PARAMS(p0, p1, p2, p3, p4, \
p5) p0##_type p0; p1##_type p1; p2##_type p2; p3##_type p3; p4##_type p4; \
#define GMOCK_INTERNAL_DEFN_AND_3_VALUE_PARAMS(p0, p1, p2) \
p0##_type p0; \
p1##_type p1; \
p2##_type p2;
#define GMOCK_INTERNAL_DEFN_AND_4_VALUE_PARAMS(p0, p1, p2, p3) \
p0##_type p0; \
p1##_type p1; \
p2##_type p2; \
p3##_type p3;
#define GMOCK_INTERNAL_DEFN_AND_5_VALUE_PARAMS(p0, p1, p2, p3, p4) \
p0##_type p0; \
p1##_type p1; \
p2##_type p2; \
p3##_type p3; \
p4##_type p4;
#define GMOCK_INTERNAL_DEFN_AND_6_VALUE_PARAMS(p0, p1, p2, p3, p4, p5) \
p0##_type p0; \
p1##_type p1; \
p2##_type p2; \
p3##_type p3; \
p4##_type p4; \
p5##_type p5;
#define GMOCK_INTERNAL_DEFN_AND_7_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, \
p6) p0##_type p0; p1##_type p1; p2##_type p2; p3##_type p3; p4##_type p4; \
p5##_type p5; p6##_type p6;
#define GMOCK_INTERNAL_DEFN_AND_8_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, \
p7) p0##_type p0; p1##_type p1; p2##_type p2; p3##_type p3; p4##_type p4; \
p5##_type p5; p6##_type p6; p7##_type p7;
#define GMOCK_INTERNAL_DEFN_AND_9_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, \
p7, p8) p0##_type p0; p1##_type p1; p2##_type p2; p3##_type p3; \
p4##_type p4; p5##_type p5; p6##_type p6; p7##_type p7; p8##_type p8;
#define GMOCK_INTERNAL_DEFN_AND_7_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6) \
p0##_type p0; \
p1##_type p1; \
p2##_type p2; \
p3##_type p3; \
p4##_type p4; \
p5##_type p5; \
p6##_type p6;
#define GMOCK_INTERNAL_DEFN_AND_8_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, p7) \
p0##_type p0; \
p1##_type p1; \
p2##_type p2; \
p3##_type p3; \
p4##_type p4; \
p5##_type p5; \
p6##_type p6; \
p7##_type p7;
#define GMOCK_INTERNAL_DEFN_AND_9_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, p7, \
p8) \
p0##_type p0; \
p1##_type p1; \
p2##_type p2; \
p3##_type p3; \
p4##_type p4; \
p5##_type p5; \
p6##_type p6; \
p7##_type p7; \
p8##_type p8;
#define GMOCK_INTERNAL_DEFN_AND_10_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, \
p7, p8, p9) p0##_type p0; p1##_type p1; p2##_type p2; p3##_type p3; \
p4##_type p4; p5##_type p5; p6##_type p6; p7##_type p7; p8##_type p8; \
p7, p8, p9) \
p0##_type p0; \
p1##_type p1; \
p2##_type p2; \
p3##_type p3; \
p4##_type p4; \
p5##_type p5; \
p6##_type p6; \
p7##_type p7; \
p8##_type p8; \
p9##_type p9;
// Lists the value parameters.
@ -338,72 +416,78 @@
#define GMOCK_INTERNAL_LIST_AND_2_VALUE_PARAMS(p0, p1) p0, p1
#define GMOCK_INTERNAL_LIST_AND_3_VALUE_PARAMS(p0, p1, p2) p0, p1, p2
#define GMOCK_INTERNAL_LIST_AND_4_VALUE_PARAMS(p0, p1, p2, p3) p0, p1, p2, p3
#define GMOCK_INTERNAL_LIST_AND_5_VALUE_PARAMS(p0, p1, p2, p3, p4) p0, p1, \
p2, p3, p4
#define GMOCK_INTERNAL_LIST_AND_6_VALUE_PARAMS(p0, p1, p2, p3, p4, p5) p0, \
p1, p2, p3, p4, p5
#define GMOCK_INTERNAL_LIST_AND_7_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, \
p6) p0, p1, p2, p3, p4, p5, p6
#define GMOCK_INTERNAL_LIST_AND_8_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, \
p7) p0, p1, p2, p3, p4, p5, p6, p7
#define GMOCK_INTERNAL_LIST_AND_9_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, \
p7, p8) p0, p1, p2, p3, p4, p5, p6, p7, p8
#define GMOCK_INTERNAL_LIST_AND_5_VALUE_PARAMS(p0, p1, p2, p3, p4) \
p0, p1, p2, p3, p4
#define GMOCK_INTERNAL_LIST_AND_6_VALUE_PARAMS(p0, p1, p2, p3, p4, p5) \
p0, p1, p2, p3, p4, p5
#define GMOCK_INTERNAL_LIST_AND_7_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6) \
p0, p1, p2, p3, p4, p5, p6
#define GMOCK_INTERNAL_LIST_AND_8_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, p7) \
p0, p1, p2, p3, p4, p5, p6, p7
#define GMOCK_INTERNAL_LIST_AND_9_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, p7, \
p8) \
p0, p1, p2, p3, p4, p5, p6, p7, p8
#define GMOCK_INTERNAL_LIST_AND_10_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, \
p7, p8, p9) p0, p1, p2, p3, p4, p5, p6, p7, p8, p9
p7, p8, p9) \
p0, p1, p2, p3, p4, p5, p6, p7, p8, p9
// Lists the value parameter types.
#define GMOCK_INTERNAL_LIST_TYPE_AND_0_VALUE_PARAMS()
#define GMOCK_INTERNAL_LIST_TYPE_AND_1_VALUE_PARAMS(p0) , p0##_type
#define GMOCK_INTERNAL_LIST_TYPE_AND_2_VALUE_PARAMS(p0, p1) , p0##_type, \
p1##_type
#define GMOCK_INTERNAL_LIST_TYPE_AND_3_VALUE_PARAMS(p0, p1, p2) , p0##_type, \
p1##_type, p2##_type
#define GMOCK_INTERNAL_LIST_TYPE_AND_4_VALUE_PARAMS(p0, p1, p2, p3) , \
p0##_type, p1##_type, p2##_type, p3##_type
#define GMOCK_INTERNAL_LIST_TYPE_AND_5_VALUE_PARAMS(p0, p1, p2, p3, p4) , \
p0##_type, p1##_type, p2##_type, p3##_type, p4##_type
#define GMOCK_INTERNAL_LIST_TYPE_AND_6_VALUE_PARAMS(p0, p1, p2, p3, p4, p5) , \
p0##_type, p1##_type, p2##_type, p3##_type, p4##_type, p5##_type
#define GMOCK_INTERNAL_LIST_TYPE_AND_2_VALUE_PARAMS(p0, p1) \
, p0##_type, p1##_type
#define GMOCK_INTERNAL_LIST_TYPE_AND_3_VALUE_PARAMS(p0, p1, p2) \
, p0##_type, p1##_type, p2##_type
#define GMOCK_INTERNAL_LIST_TYPE_AND_4_VALUE_PARAMS(p0, p1, p2, p3) \
, p0##_type, p1##_type, p2##_type, p3##_type
#define GMOCK_INTERNAL_LIST_TYPE_AND_5_VALUE_PARAMS(p0, p1, p2, p3, p4) \
, p0##_type, p1##_type, p2##_type, p3##_type, p4##_type
#define GMOCK_INTERNAL_LIST_TYPE_AND_6_VALUE_PARAMS(p0, p1, p2, p3, p4, p5) \
, p0##_type, p1##_type, p2##_type, p3##_type, p4##_type, p5##_type
#define GMOCK_INTERNAL_LIST_TYPE_AND_7_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, \
p6) , p0##_type, p1##_type, p2##_type, p3##_type, p4##_type, p5##_type, \
p6##_type
p6) \
, p0##_type, p1##_type, p2##_type, p3##_type, p4##_type, p5##_type, p6##_type
#define GMOCK_INTERNAL_LIST_TYPE_AND_8_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, \
p6, p7) , p0##_type, p1##_type, p2##_type, p3##_type, p4##_type, \
p5##_type, p6##_type, p7##_type
p6, p7) \
, p0##_type, p1##_type, p2##_type, p3##_type, p4##_type, p5##_type, \
p6##_type, p7##_type
#define GMOCK_INTERNAL_LIST_TYPE_AND_9_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, \
p6, p7, p8) , p0##_type, p1##_type, p2##_type, p3##_type, p4##_type, \
p5##_type, p6##_type, p7##_type, p8##_type
p6, p7, p8) \
, p0##_type, p1##_type, p2##_type, p3##_type, p4##_type, p5##_type, \
p6##_type, p7##_type, p8##_type
#define GMOCK_INTERNAL_LIST_TYPE_AND_10_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, \
p6, p7, p8, p9) , p0##_type, p1##_type, p2##_type, p3##_type, p4##_type, \
p5##_type, p6##_type, p7##_type, p8##_type, p9##_type
p6, p7, p8, p9) \
, p0##_type, p1##_type, p2##_type, p3##_type, p4##_type, p5##_type, \
p6##_type, p7##_type, p8##_type, p9##_type
// Declares the value parameters.
#define GMOCK_INTERNAL_DECL_AND_0_VALUE_PARAMS()
#define GMOCK_INTERNAL_DECL_AND_1_VALUE_PARAMS(p0) p0##_type p0
#define GMOCK_INTERNAL_DECL_AND_2_VALUE_PARAMS(p0, p1) p0##_type p0, \
p1##_type p1
#define GMOCK_INTERNAL_DECL_AND_3_VALUE_PARAMS(p0, p1, p2) p0##_type p0, \
p1##_type p1, p2##_type p2
#define GMOCK_INTERNAL_DECL_AND_4_VALUE_PARAMS(p0, p1, p2, p3) p0##_type p0, \
p1##_type p1, p2##_type p2, p3##_type p3
#define GMOCK_INTERNAL_DECL_AND_5_VALUE_PARAMS(p0, p1, p2, p3, \
p4) p0##_type p0, p1##_type p1, p2##_type p2, p3##_type p3, p4##_type p4
#define GMOCK_INTERNAL_DECL_AND_6_VALUE_PARAMS(p0, p1, p2, p3, p4, \
p5) p0##_type p0, p1##_type p1, p2##_type p2, p3##_type p3, p4##_type p4, \
#define GMOCK_INTERNAL_DECL_AND_2_VALUE_PARAMS(p0, p1) \
p0##_type p0, p1##_type p1
#define GMOCK_INTERNAL_DECL_AND_3_VALUE_PARAMS(p0, p1, p2) \
p0##_type p0, p1##_type p1, p2##_type p2
#define GMOCK_INTERNAL_DECL_AND_4_VALUE_PARAMS(p0, p1, p2, p3) \
p0##_type p0, p1##_type p1, p2##_type p2, p3##_type p3
#define GMOCK_INTERNAL_DECL_AND_5_VALUE_PARAMS(p0, p1, p2, p3, p4) \
p0##_type p0, p1##_type p1, p2##_type p2, p3##_type p3, p4##_type p4
#define GMOCK_INTERNAL_DECL_AND_6_VALUE_PARAMS(p0, p1, p2, p3, p4, p5) \
p0##_type p0, p1##_type p1, p2##_type p2, p3##_type p3, p4##_type p4, \
p5##_type p5
#define GMOCK_INTERNAL_DECL_AND_7_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, \
p6) p0##_type p0, p1##_type p1, p2##_type p2, p3##_type p3, p4##_type p4, \
#define GMOCK_INTERNAL_DECL_AND_7_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6) \
p0##_type p0, p1##_type p1, p2##_type p2, p3##_type p3, p4##_type p4, \
p5##_type p5, p6##_type p6
#define GMOCK_INTERNAL_DECL_AND_8_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, \
p7) p0##_type p0, p1##_type p1, p2##_type p2, p3##_type p3, p4##_type p4, \
#define GMOCK_INTERNAL_DECL_AND_8_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, p7) \
p0##_type p0, p1##_type p1, p2##_type p2, p3##_type p3, p4##_type p4, \
p5##_type p5, p6##_type p6, p7##_type p7
#define GMOCK_INTERNAL_DECL_AND_9_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, \
p7, p8) p0##_type p0, p1##_type p1, p2##_type p2, p3##_type p3, \
p4##_type p4, p5##_type p5, p6##_type p6, p7##_type p7, p8##_type p8
#define GMOCK_INTERNAL_DECL_AND_9_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, p7, \
p8) \
p0##_type p0, p1##_type p1, p2##_type p2, p3##_type p3, p4##_type p4, \
p5##_type p5, p6##_type p6, p7##_type p7, p8##_type p8
#define GMOCK_INTERNAL_DECL_AND_10_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, \
p7, p8, p9) p0##_type p0, p1##_type p1, p2##_type p2, p3##_type p3, \
p4##_type p4, p5##_type p5, p6##_type p6, p7##_type p7, p8##_type p8, \
p9##_type p9
p7, p8, p9) \
p0##_type p0, p1##_type p1, p2##_type p2, p3##_type p3, p4##_type p4, \
p5##_type p5, p6##_type p6, p7##_type p7, p8##_type p8, p9##_type p9
// The suffix of the class template implementing the action template.
#define GMOCK_INTERNAL_COUNT_AND_0_VALUE_PARAMS()
@ -415,11 +499,14 @@
#define GMOCK_INTERNAL_COUNT_AND_6_VALUE_PARAMS(p0, p1, p2, p3, p4, p5) P6
#define GMOCK_INTERNAL_COUNT_AND_7_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6) P7
#define GMOCK_INTERNAL_COUNT_AND_8_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, \
p7) P8
p7) \
P8
#define GMOCK_INTERNAL_COUNT_AND_9_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, \
p7, p8) P9
p7, p8) \
P9
#define GMOCK_INTERNAL_COUNT_AND_10_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, \
p7, p8, p9) P10
p7, p8, p9) \
P10
// The name of the class template implementing the action template.
#define GMOCK_ACTION_CLASS_(name, value_params) \
@ -433,22 +520,22 @@
explicit GMOCK_ACTION_CLASS_(name, value_params)( \
GMOCK_INTERNAL_DECL_##value_params) \
GMOCK_PP_IF(GMOCK_PP_IS_EMPTY(GMOCK_INTERNAL_COUNT_##value_params), \
= default; , \
= default; \
, \
: impl_(std::make_shared<gmock_Impl>( \
GMOCK_INTERNAL_LIST_##value_params)){}) \
GMOCK_ACTION_CLASS_(name, value_params)( \
const GMOCK_ACTION_CLASS_(name, value_params)&) noexcept \
GMOCK_INTERNAL_DEFN_COPY_##value_params \
GMOCK_ACTION_CLASS_(name, value_params)( \
GMOCK_ACTION_CLASS_(name, value_params)(const GMOCK_ACTION_CLASS_( \
name, value_params) &) noexcept GMOCK_INTERNAL_DEFN_COPY_ \
##value_params GMOCK_ACTION_CLASS_(name, value_params)( \
GMOCK_ACTION_CLASS_(name, value_params) &&) noexcept \
GMOCK_INTERNAL_DEFN_COPY_##value_params \
template <typename F> \
GMOCK_INTERNAL_DEFN_COPY_##value_params template <typename F> \
operator ::testing::Action<F>() const { \
return GMOCK_PP_IF( \
GMOCK_PP_IS_EMPTY(GMOCK_INTERNAL_COUNT_##value_params), \
(::testing::internal::MakeAction<F, gmock_Impl>()), \
(::testing::internal::MakeAction<F>(impl_))); \
} \
\
private: \
class gmock_Impl { \
public: \
@ -458,23 +545,23 @@
return_type gmock_PerformImpl(GMOCK_ACTION_ARG_TYPES_AND_NAMES_) const; \
GMOCK_INTERNAL_DEFN_##value_params \
}; \
GMOCK_PP_IF(GMOCK_PP_IS_EMPTY(GMOCK_INTERNAL_COUNT_##value_params), \
, std::shared_ptr<const gmock_Impl> impl_;) \
GMOCK_PP_IF(GMOCK_PP_IS_EMPTY(GMOCK_INTERNAL_COUNT_##value_params), , \
std::shared_ptr<const gmock_Impl> impl_;) \
}; \
template <GMOCK_INTERNAL_DECL_##template_params \
GMOCK_INTERNAL_DECL_TYPE_##value_params> \
GMOCK_ACTION_CLASS_(name, value_params)< \
GMOCK_INTERNAL_LIST_##template_params \
GMOCK_INTERNAL_LIST_TYPE_##value_params> name( \
GMOCK_INTERNAL_DECL_##value_params) GTEST_MUST_USE_RESULT_; \
GMOCK_ACTION_CLASS_( \
name, value_params)<GMOCK_INTERNAL_LIST_##template_params \
GMOCK_INTERNAL_LIST_TYPE_##value_params> \
name(GMOCK_INTERNAL_DECL_##value_params) GTEST_MUST_USE_RESULT_; \
template <GMOCK_INTERNAL_DECL_##template_params \
GMOCK_INTERNAL_DECL_TYPE_##value_params> \
inline GMOCK_ACTION_CLASS_(name, value_params)< \
GMOCK_INTERNAL_LIST_##template_params \
GMOCK_INTERNAL_LIST_TYPE_##value_params> name( \
GMOCK_INTERNAL_DECL_##value_params) { \
return GMOCK_ACTION_CLASS_(name, value_params)< \
GMOCK_INTERNAL_LIST_##template_params \
inline GMOCK_ACTION_CLASS_( \
name, value_params)<GMOCK_INTERNAL_LIST_##template_params \
GMOCK_INTERNAL_LIST_TYPE_##value_params> \
name(GMOCK_INTERNAL_DECL_##value_params) { \
return GMOCK_ACTION_CLASS_( \
name, value_params)<GMOCK_INTERNAL_LIST_##template_params \
GMOCK_INTERNAL_LIST_TYPE_##value_params>( \
GMOCK_INTERNAL_LIST_##value_params); \
} \
@ -482,10 +569,11 @@
GMOCK_INTERNAL_DECL_TYPE_##value_params> \
template <typename function_type, typename return_type, typename args_type, \
GMOCK_ACTION_TEMPLATE_ARGS_NAMES_> \
return_type GMOCK_ACTION_CLASS_(name, value_params)< \
GMOCK_INTERNAL_LIST_##template_params \
GMOCK_INTERNAL_LIST_TYPE_##value_params>::gmock_Impl::gmock_PerformImpl( \
GMOCK_ACTION_ARG_TYPES_AND_NAMES_UNUSED_) const
return_type GMOCK_ACTION_CLASS_( \
name, value_params)<GMOCK_INTERNAL_LIST_##template_params \
GMOCK_INTERNAL_LIST_TYPE_##value_params>:: \
gmock_Impl::gmock_PerformImpl(GMOCK_ACTION_ARG_TYPES_AND_NAMES_UNUSED_) \
const
namespace testing {

View File

@ -86,7 +86,6 @@ MATCHER(IsFalse, negation ? "is true" : "is false") {
#pragma warning(pop)
#endif
} // namespace testing
#endif // GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_MORE_MATCHERS_H_

View File

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

View File

@ -91,7 +91,9 @@ inline const Element* GetRawPointer(const std::reference_wrapper<Element>& r) {
// This overloaded version is for the raw pointer case.
template <typename Element>
inline Element* GetRawPointer(Element* p) { return p; }
inline Element* GetRawPointer(Element* p) {
return p;
}
// MSVC treats wchar_t as a native type usually, but treats it as the
// same as unsigned short when the compiler option /Zc:wchar_t- is
@ -108,18 +110,20 @@ inline Element* GetRawPointer(Element* p) { return p; }
// or none of them. This categorization is useful for determining
// when a matcher argument type can be safely converted to another
// type in the implementation of SafeMatcherCast.
enum TypeKind {
kBool, kInteger, kFloatingPoint, kOther
};
enum TypeKind { kBool, kInteger, kFloatingPoint, kOther };
// KindOf<T>::value is the kind of type T.
template <typename T> struct KindOf {
template <typename T>
struct KindOf {
enum { value = kOther }; // The default kind.
};
// This macro declares that the kind of 'type' is 'kind'.
#define GMOCK_DECLARE_KIND_(type, kind) \
template <> struct KindOf<type> { enum { value = kind }; }
template <> \
struct KindOf<type> { \
enum { value = kind }; \
}
GMOCK_DECLARE_KIND_(bool, kBool);
@ -204,9 +208,7 @@ using LosslessArithmeticConvertible =
class FailureReporterInterface {
public:
// The type of a failure (either non-fatal or fatal).
enum FailureType {
kNonfatal, kFatal
};
enum FailureType { kNonfatal, kFatal };
virtual ~FailureReporterInterface() {}
@ -226,8 +228,8 @@ GTEST_API_ FailureReporterInterface* GetFailureReporter();
inline void Assert(bool condition, const char* file, int line,
const std::string& msg) {
if (!condition) {
GetFailureReporter()->ReportFailure(FailureReporterInterface::kFatal,
file, line, msg);
GetFailureReporter()->ReportFailure(FailureReporterInterface::kFatal, file,
line, msg);
}
}
inline void Assert(bool condition, const char* file, int line) {
@ -248,10 +250,7 @@ inline void Expect(bool condition, const char* file, int line) {
}
// Severity level of a log.
enum LogSeverity {
kInfo = 0,
kWarning = 1
};
enum LogSeverity { kInfo = 0, kWarning = 1 };
// Valid values for the --gmock_verbose flag.
@ -392,7 +391,8 @@ class StlContainerView< ::std::tuple<ElementPointer, Size> > {
// The following specialization prevents the user from instantiating
// StlContainer with a reference type.
template <typename T> class StlContainerView<T&>;
template <typename T>
class StlContainerView<T&>;
// A type transform to remove constness from the first part of a pair.
// Pairs like that are used as the value_type of associative containers,
@ -413,15 +413,16 @@ struct RemoveConstFromKey<std::pair<const K, V> > {
GTEST_API_ void IllegalDoDefault(const char* file, int line);
template <typename F, typename Tuple, size_t... Idx>
auto ApplyImpl(F&& f, Tuple&& args, IndexSequence<Idx...>) -> decltype(
std::forward<F>(f)(std::get<Idx>(std::forward<Tuple>(args))...)) {
auto ApplyImpl(F&& f, Tuple&& args, IndexSequence<Idx...>)
-> decltype(std::forward<F>(f)(
std::get<Idx>(std::forward<Tuple>(args))...)) {
return std::forward<F>(f)(std::get<Idx>(std::forward<Tuple>(args))...);
}
// Apply the function to a tuple of arguments.
template <typename F, typename Tuple>
auto Apply(F&& f, Tuple&& args) -> decltype(
ApplyImpl(std::forward<F>(f), std::forward<Tuple>(args),
auto Apply(F&& f, Tuple&& args) -> decltype(ApplyImpl(
std::forward<F>(f), std::forward<Tuple>(args),
MakeIndexSequence<std::tuple_size<
typename std::remove_reference<Tuple>::type>::value>())) {
return ApplyImpl(std::forward<F>(f), std::forward<Tuple>(args),

View File

@ -42,6 +42,7 @@
#include <assert.h>
#include <stdlib.h>
#include <cstdint>
#include <iostream>
@ -53,8 +54,8 @@
// here, as Google Mock depends on Google Test. Only add a utility
// here if it's truly specific to Google Mock.
#include "gtest/internal/gtest-port.h"
#include "gmock/internal/custom/gmock-port.h"
#include "gtest/internal/gtest-port.h"
// For MS Visual C++, check the compiler version. At least VS 2015 is
// required to compile Google Mock.
@ -72,29 +73,35 @@
#define GMOCK_DECLARE_bool_(name) \
namespace testing { \
GTEST_API_ extern bool GMOCK_FLAG(name); \
} static_assert(true, "no-op to require trailing semicolon")
} \
static_assert(true, "no-op to require trailing semicolon")
#define GMOCK_DECLARE_int32_(name) \
namespace testing { \
GTEST_API_ extern int32_t GMOCK_FLAG(name); \
} static_assert(true, "no-op to require trailing semicolon")
} \
static_assert(true, "no-op to require trailing semicolon")
#define GMOCK_DECLARE_string_(name) \
namespace testing { \
GTEST_API_ extern ::std::string GMOCK_FLAG(name); \
} static_assert(true, "no-op to require trailing semicolon")
} \
static_assert(true, "no-op to require trailing semicolon")
// Macros for defining flags.
#define GMOCK_DEFINE_bool_(name, default_val, doc) \
namespace testing { \
GTEST_API_ bool GMOCK_FLAG(name) = (default_val); \
} static_assert(true, "no-op to require trailing semicolon")
} \
static_assert(true, "no-op to require trailing semicolon")
#define GMOCK_DEFINE_int32_(name, default_val, doc) \
namespace testing { \
GTEST_API_ int32_t GMOCK_FLAG(name) = (default_val); \
} static_assert(true, "no-op to require trailing semicolon")
} \
static_assert(true, "no-op to require trailing semicolon")
#define GMOCK_DEFINE_string_(name, default_val, doc) \
namespace testing { \
GTEST_API_ ::std::string GMOCK_FLAG(name) = (default_val); \
} static_assert(true, "no-op to require trailing semicolon")
} \
static_assert(true, "no-op to require trailing semicolon")
#endif // !defined(GMOCK_DECLARE_bool_)
#if !defined(GMOCK_FLAG_GET)

View File

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

View File

@ -27,7 +27,6 @@
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// Google Mock - a framework for writing C++ mock classes.
//
// This file defines some utilities useful for implementing Google
@ -88,8 +87,7 @@ GTEST_API_ std::string ConvertIdentifierNameToWords(const char* id_name) {
(!IsDigit(prev_char) && IsDigit(*p));
if (IsAlNum(*p)) {
if (starts_new_word && result != "")
result += ' ';
if (starts_new_word && result != "") result += ' ';
result += ToLower(*p);
}
}
@ -103,12 +101,9 @@ class GoogleTestFailureReporter : public FailureReporterInterface {
public:
void ReportFailure(FailureType type, const char* file, int line,
const std::string& message) override {
AssertHelper(type == kFatal ?
TestPartResult::kFatalFailure :
TestPartResult::kNonFatalFailure,
file,
line,
message.c_str()) = Message();
AssertHelper(type == kFatal ? TestPartResult::kFatalFailure
: TestPartResult::kNonFatalFailure,
file, line, message.c_str()) = Message();
if (type == kFatal) {
posix::Abort();
}
@ -156,8 +151,7 @@ GTEST_API_ bool LogIsVisible(LogSeverity severity) {
// conservative.
GTEST_API_ void Log(LogSeverity severity, const std::string& message,
int stack_frames_to_skip) {
if (!LogIsVisible(severity))
return;
if (!LogIsVisible(severity)) return;
// Ensures that logs from different threads don't interleave.
MutexLock l(&g_log_mutex);

View File

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

View File

@ -27,7 +27,6 @@
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// Google Mock - a framework for writing C++ mock classes.
//
// This file implements the spec builder syntax (ON_CALL and
@ -195,11 +194,12 @@ void ExpectationBase::DescribeCallCountTo(::std::ostream* os) const
// Describes the state of the expectation (e.g. is it satisfied?
// is it active?).
*os << " - " << (IsOverSaturated() ? "over-saturated" :
IsSaturated() ? "saturated" :
IsSatisfied() ? "satisfied" : "unsatisfied")
<< " and "
<< (is_retired() ? "retired" : "active");
*os << " - "
<< (IsOverSaturated() ? "over-saturated"
: IsSaturated() ? "saturated"
: IsSatisfied() ? "satisfied"
: "unsatisfied")
<< " and " << (is_retired() ? "retired" : "active");
}
// Checks the action count (i.e. the number of WillOnce() and
@ -242,13 +242,12 @@ void ExpectationBase::CheckActionCountIfNotDone() const
::std::stringstream ss;
DescribeLocationTo(&ss);
ss << "Too " << (too_many ? "many" : "few")
<< " actions specified in " << source_text() << "...\n"
ss << "Too " << (too_many ? "many" : "few") << " actions specified in "
<< source_text() << "...\n"
<< "Expected to be ";
cardinality().DescribeTo(&ss);
ss << ", but has " << (too_many ? "" : "only ")
<< action_count << " WillOnce()"
<< (action_count == 1 ? "" : "s");
ss << ", but has " << (too_many ? "" : "only ") << action_count
<< " WillOnce()" << (action_count == 1 ? "" : "s");
if (repeated_action_specified_) {
ss << " and a WillRepeatedly()";
}
@ -505,8 +504,7 @@ UntypedActionResultHolderBase* UntypedFunctionMockerBase::UntypedInvokeWith(
Expectation UntypedFunctionMockerBase::GetHandleOf(ExpectationBase* exp) {
// See the definition of untyped_expectations_ for why access to it
// is unprotected here.
for (UntypedExpectations::const_iterator it =
untyped_expectations_.begin();
for (UntypedExpectations::const_iterator it = untyped_expectations_.begin();
it != untyped_expectations_.end(); ++it) {
if (it->get() == exp) {
return Expectation(*it);
@ -526,8 +524,7 @@ bool UntypedFunctionMockerBase::VerifyAndClearExpectationsLocked()
GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
g_gmock_mutex.AssertHeld();
bool expectations_met = true;
for (UntypedExpectations::const_iterator it =
untyped_expectations_.begin();
for (UntypedExpectations::const_iterator it = untyped_expectations_.begin();
it != untyped_expectations_.end(); ++it) {
ExpectationBase* const untyped_expectation = it->get();
if (untyped_expectation->IsOverSaturated()) {
@ -545,8 +542,8 @@ bool UntypedFunctionMockerBase::VerifyAndClearExpectationsLocked()
// takes care of it.
untyped_expectation->MaybeDescribeExtraMatcherTo(&ss);
untyped_expectation->DescribeCallCountTo(&ss);
Expect(false, untyped_expectation->file(),
untyped_expectation->line(), ss.str());
Expect(false, untyped_expectation->file(), untyped_expectation->line(),
ss.str());
}
}
@ -712,8 +709,7 @@ void Mock::UnregisterCallReaction(const void* mock_obj)
// Returns the reaction Google Mock will have on uninteresting calls
// made on the given mock object.
internal::CallReaction Mock::GetReactionOnUninterestingCalls(
const void* mock_obj)
GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {
const void* mock_obj) GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {
internal::MutexLock l(&internal::g_gmock_mutex);
return (g_uninteresting_call_reaction.count(mock_obj) == 0)
? internal::intToCallReaction(
@ -873,8 +869,8 @@ Expectation::~Expectation() {}
void Sequence::AddExpectation(const Expectation& expectation) const {
if (*last_expectation_ != expectation) {
if (last_expectation_->expectation_base() != nullptr) {
expectation.expectation_base()->immediate_prerequisites_
+= *last_expectation_;
expectation.expectation_base()->immediate_prerequisites_ +=
*last_expectation_;
}
*last_expectation_ = expectation;
}

View File

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

View File

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

View File

@ -27,7 +27,6 @@
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// Google Mock - a framework for writing C++ mock classes.
//
// This file tests the built-in actions.
@ -44,15 +43,17 @@
#endif
#include "gmock/gmock-actions.h"
#include <algorithm>
#include <iterator>
#include <memory>
#include <string>
#include <type_traits>
#include "gmock/gmock.h"
#include "gmock/internal/gmock-port.h"
#include "gtest/gtest.h"
#include "gtest/gtest-spi.h"
#include "gtest/gtest.h"
namespace {
@ -208,7 +209,6 @@ class MyNonDefaultConstructible {
int value_;
};
TEST(BuiltInDefaultValueTest, ExistsForDefaultConstructibleType) {
EXPECT_TRUE(BuiltInDefaultValue<MyDefaultConstructible>::Exists());
}
@ -217,25 +217,19 @@ TEST(BuiltInDefaultValueTest, IsDefaultConstructedForDefaultConstructibleType) {
EXPECT_EQ(42, BuiltInDefaultValue<MyDefaultConstructible>::Get().value());
}
TEST(BuiltInDefaultValueTest, DoesNotExistForNonDefaultConstructibleType) {
EXPECT_FALSE(BuiltInDefaultValue<MyNonDefaultConstructible>::Exists());
}
// Tests that BuiltInDefaultValue<T&>::Get() aborts the program.
TEST(BuiltInDefaultValueDeathTest, IsUndefinedForReferences) {
EXPECT_DEATH_IF_SUPPORTED({
BuiltInDefaultValue<int&>::Get();
}, "");
EXPECT_DEATH_IF_SUPPORTED({
BuiltInDefaultValue<const char&>::Get();
}, "");
EXPECT_DEATH_IF_SUPPORTED({ BuiltInDefaultValue<int&>::Get(); }, "");
EXPECT_DEATH_IF_SUPPORTED({ BuiltInDefaultValue<const char&>::Get(); }, "");
}
TEST(BuiltInDefaultValueDeathTest, IsUndefinedForNonDefaultConstructibleType) {
EXPECT_DEATH_IF_SUPPORTED({
BuiltInDefaultValue<MyNonDefaultConstructible>::Get();
}, "");
EXPECT_DEATH_IF_SUPPORTED(
{ BuiltInDefaultValue<MyNonDefaultConstructible>::Get(); }, "");
}
// Tests that DefaultValue<T>::IsSet() is false initially.
@ -281,26 +275,22 @@ TEST(DefaultValueDeathTest, GetReturnsBuiltInDefaultValueWhenUnset) {
EXPECT_EQ(0, DefaultValue<int>::Get());
EXPECT_DEATH_IF_SUPPORTED({
DefaultValue<MyNonDefaultConstructible>::Get();
}, "");
EXPECT_DEATH_IF_SUPPORTED({ DefaultValue<MyNonDefaultConstructible>::Get(); },
"");
}
TEST(DefaultValueTest, GetWorksForMoveOnlyIfSet) {
EXPECT_TRUE(DefaultValue<std::unique_ptr<int>>::Exists());
EXPECT_TRUE(DefaultValue<std::unique_ptr<int>>::Get() == nullptr);
DefaultValue<std::unique_ptr<int>>::SetFactory([] {
return std::unique_ptr<int>(new int(42));
});
DefaultValue<std::unique_ptr<int>>::SetFactory(
[] { return std::unique_ptr<int>(new int(42)); });
EXPECT_TRUE(DefaultValue<std::unique_ptr<int>>::Exists());
std::unique_ptr<int> i = DefaultValue<std::unique_ptr<int>>::Get();
EXPECT_EQ(42, *i);
}
// Tests that DefaultValue<void>::Get() returns void.
TEST(DefaultValueTest, GetWorksForVoid) {
return DefaultValue<void>::Get();
}
TEST(DefaultValueTest, GetWorksForVoid) { return DefaultValue<void>::Get(); }
// Tests using DefaultValue with a reference type.
@ -348,12 +338,9 @@ TEST(DefaultValueOfReferenceDeathTest, GetReturnsBuiltInDefaultValueWhenUnset) {
EXPECT_FALSE(DefaultValue<int&>::IsSet());
EXPECT_FALSE(DefaultValue<MyNonDefaultConstructible&>::IsSet());
EXPECT_DEATH_IF_SUPPORTED({
DefaultValue<int&>::Get();
}, "");
EXPECT_DEATH_IF_SUPPORTED({
DefaultValue<MyNonDefaultConstructible>::Get();
}, "");
EXPECT_DEATH_IF_SUPPORTED({ DefaultValue<int&>::Get(); }, "");
EXPECT_DEATH_IF_SUPPORTED({ DefaultValue<MyNonDefaultConstructible>::Get(); },
"");
}
// Tests that ActionInterface can be implemented by defining the
@ -648,7 +635,9 @@ TEST(ReturnRefTest, IsCovariant) {
}
template <typename T, typename = decltype(ReturnRef(std::declval<T&&>()))>
bool CanCallReturnRef(T&&) { return true; }
bool CanCallReturnRef(T&&) {
return true;
}
bool CanCallReturnRef(Unused) { return false; }
// Tests that ReturnRef(v) is working with non-temporaries (T&)
@ -754,8 +743,7 @@ class MockClass {
// return type by default.
TEST(DoDefaultTest, ReturnsBuiltInDefaultValueByDefault) {
MockClass mock;
EXPECT_CALL(mock, IntFunc(_))
.WillOnce(DoDefault());
EXPECT_CALL(mock, IntFunc(_)).WillOnce(DoDefault());
EXPECT_EQ(0, mock.IntFunc(true));
}
@ -763,14 +751,11 @@ TEST(DoDefaultTest, ReturnsBuiltInDefaultValueByDefault) {
// the process when there is no built-in default value for the return type.
TEST(DoDefaultDeathTest, DiesForUnknowType) {
MockClass mock;
EXPECT_CALL(mock, Foo())
.WillRepeatedly(DoDefault());
EXPECT_CALL(mock, Foo()).WillRepeatedly(DoDefault());
#if GTEST_HAS_EXCEPTIONS
EXPECT_ANY_THROW(mock.Foo());
#else
EXPECT_DEATH_IF_SUPPORTED({
mock.Foo();
}, "");
EXPECT_DEATH_IF_SUPPORTED({ mock.Foo(); }, "");
#endif
}
@ -782,16 +767,13 @@ void VoidFunc(bool /* flag */) {}
TEST(DoDefaultDeathTest, DiesIfUsedInCompositeAction) {
MockClass mock;
EXPECT_CALL(mock, IntFunc(_))
.WillRepeatedly(DoAll(Invoke(VoidFunc),
DoDefault()));
.WillRepeatedly(DoAll(Invoke(VoidFunc), DoDefault()));
// Ideally we should verify the error message as well. Sadly,
// EXPECT_DEATH() can only capture stderr, while Google Mock's
// errors are printed on stdout. Therefore we have to settle for
// not verifying the message.
EXPECT_DEATH_IF_SUPPORTED({
mock.IntFunc(true);
}, "");
EXPECT_DEATH_IF_SUPPORTED({ mock.IntFunc(true); }, "");
}
// Tests that DoDefault() returns the default value set by
@ -799,8 +781,7 @@ TEST(DoDefaultDeathTest, DiesIfUsedInCompositeAction) {
TEST(DoDefaultTest, ReturnsUserSpecifiedPerTypeDefaultValueWhenThereIsOne) {
DefaultValue<int>::Set(1);
MockClass mock;
EXPECT_CALL(mock, IntFunc(_))
.WillOnce(DoDefault());
EXPECT_CALL(mock, IntFunc(_)).WillOnce(DoDefault());
EXPECT_EQ(1, mock.IntFunc(false));
DefaultValue<int>::Clear();
}
@ -808,20 +789,19 @@ TEST(DoDefaultTest, ReturnsUserSpecifiedPerTypeDefaultValueWhenThereIsOne) {
// Tests that DoDefault() does the action specified by ON_CALL().
TEST(DoDefaultTest, DoesWhatOnCallSpecifies) {
MockClass mock;
ON_CALL(mock, IntFunc(_))
.WillByDefault(Return(2));
EXPECT_CALL(mock, IntFunc(_))
.WillOnce(DoDefault());
ON_CALL(mock, IntFunc(_)).WillByDefault(Return(2));
EXPECT_CALL(mock, IntFunc(_)).WillOnce(DoDefault());
EXPECT_EQ(2, mock.IntFunc(false));
}
// Tests that using DoDefault() in ON_CALL() leads to a run-time failure.
TEST(DoDefaultTest, CannotBeUsedInOnCall) {
MockClass mock;
EXPECT_NONFATAL_FAILURE({ // NOLINT
ON_CALL(mock, IntFunc(_))
.WillByDefault(DoDefault());
}, "DoDefault() cannot be used in ON_CALL()");
EXPECT_NONFATAL_FAILURE(
{ // NOLINT
ON_CALL(mock, IntFunc(_)).WillByDefault(DoDefault());
},
"DoDefault() cannot be used in ON_CALL()");
}
// Tests that SetArgPointee<N>(v) sets the variable pointed to by
@ -1079,7 +1059,6 @@ TEST(AssignTest, CompatibleTypes) {
EXPECT_DOUBLE_EQ(5, x);
}
// Tests using WithArgs and with an action that takes 1 argument.
TEST(WithArgsTest, OneArg) {
Action<bool(double x, int n)> a = WithArgs<1>(Invoke(Unary)); // NOLINT
@ -1375,8 +1354,9 @@ TEST(MockMethodTest, CanReturnMoveOnlyValue_DoAllReturn) {
MockClass mock;
std::unique_ptr<int> i(new int(19));
EXPECT_CALL(mock_function, Call());
EXPECT_CALL(mock, MakeUnique()).WillOnce(DoAll(
InvokeWithoutArgs(&mock_function, &testing::MockFunction<void()>::Call),
EXPECT_CALL(mock, MakeUnique())
.WillOnce(DoAll(InvokeWithoutArgs(&mock_function,
&testing::MockFunction<void()>::Call),
Return(ByMove(std::move(i)))));
std::unique_ptr<int> result1 = mock.MakeUnique();
@ -1387,9 +1367,8 @@ TEST(MockMethodTest, CanReturnMoveOnlyValue_Invoke) {
MockClass mock;
// Check default value
DefaultValue<std::unique_ptr<int>>::SetFactory([] {
return std::unique_ptr<int>(new int(42));
});
DefaultValue<std::unique_ptr<int>>::SetFactory(
[] { return std::unique_ptr<int>(new int(42)); });
EXPECT_EQ(42, *mock.MakeUnique());
EXPECT_CALL(mock, MakeUnique()).WillRepeatedly(Invoke(UniquePtrSource));
@ -1449,7 +1428,6 @@ TEST(MockMethodTest, CanTakeMoveOnlyValue) {
EXPECT_EQ(42, *saved);
}
// Tests for std::function based action.
int Add(int val, int& ref, int* ptr) { // NOLINT
@ -1463,7 +1441,9 @@ int Deref(std::unique_ptr<int> ptr) { return *ptr; }
struct Double {
template <typename T>
T operator()(T t) { return 2 * t; }
T operator()(T t) {
return 2 * t;
}
};
std::unique_ptr<int> UniqueInt(int i) {
@ -1532,8 +1512,9 @@ TEST(FunctorActionTest, TypeConversion) {
TEST(FunctorActionTest, UnusedArguments) {
// Verify that users can ignore uninteresting arguments.
Action<int(int, double y, double z)> a =
[](int i, Unused, Unused) { return 2 * i; };
Action<int(int, double y, double z)> a = [](int i, Unused, Unused) {
return 2 * i;
};
std::tuple<int, double, double> dummy = std::make_tuple(3, 7.3, 9.44);
EXPECT_EQ(6, a.Perform(dummy));
}
@ -1552,9 +1533,7 @@ TEST(MoveOnlyArgumentsTest, ReturningActions) {
EXPECT_EQ(x, 3);
}
ACTION(ReturnArity) {
return std::tuple_size<args_type>::value;
}
ACTION(ReturnArity) { return std::tuple_size<args_type>::value; }
TEST(ActionMacro, LargeArity) {
EXPECT_EQ(
@ -1580,4 +1559,3 @@ TEST(ActionMacro, LargeArity) {
#pragma warning(pop)
#endif
#endif

View File

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

View File

@ -27,7 +27,6 @@
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// Google Mock - a framework for writing C++ mock classes.
//
// This file tests the function mocker classes.
@ -595,10 +594,8 @@ TYPED_TEST(TemplateMockTest, Works) {
.WillOnce(Return(0));
EXPECT_CALL(mock, Push(_));
int n = 5;
EXPECT_CALL(mock, GetTop())
.WillOnce(ReturnRef(n));
EXPECT_CALL(mock, Pop())
.Times(AnyNumber());
EXPECT_CALL(mock, GetTop()).WillOnce(ReturnRef(n));
EXPECT_CALL(mock, Pop()).Times(AnyNumber());
EXPECT_EQ(0, mock.GetSize());
mock.Push(5);
@ -612,10 +609,8 @@ TYPED_TEST(TemplateMockTest, MethodWithCommaInReturnTypeWorks) {
TypeParam mock;
const std::map<int, int> a_map;
EXPECT_CALL(mock, ReturnTypeWithComma())
.WillOnce(Return(a_map));
EXPECT_CALL(mock, ReturnTypeWithComma(1))
.WillOnce(Return(a_map));
EXPECT_CALL(mock, ReturnTypeWithComma()).WillOnce(Return(a_map));
EXPECT_CALL(mock, ReturnTypeWithComma(1)).WillOnce(Return(a_map));
EXPECT_EQ(a_map, mock.ReturnTypeWithComma());
EXPECT_EQ(a_map, mock.ReturnTypeWithComma(1));
@ -685,10 +680,8 @@ TYPED_TEST(TemplateMockTestWithCallType, Works) {
.WillOnce(Return(0));
EXPECT_CALL(mock, Push(_));
int n = 5;
EXPECT_CALL(mock, GetTop())
.WillOnce(ReturnRef(n));
EXPECT_CALL(mock, Pop())
.Times(AnyNumber());
EXPECT_CALL(mock, GetTop()).WillOnce(ReturnRef(n));
EXPECT_CALL(mock, Pop()).Times(AnyNumber());
EXPECT_EQ(0, mock.GetSize());
mock.Push(5);
@ -779,9 +772,7 @@ TEST(MockMethodMockFunctionTest, WorksForVoidNullary) {
TEST(MockMethodMockFunctionTest, WorksForNonVoidNullary) {
MockFunction<int()> foo;
EXPECT_CALL(foo, Call())
.WillOnce(Return(1))
.WillOnce(Return(2));
EXPECT_CALL(foo, Call()).WillOnce(Return(1)).WillOnce(Return(2));
EXPECT_EQ(1, foo.Call());
EXPECT_EQ(2, foo.Call());
}
@ -794,19 +785,17 @@ TEST(MockMethodMockFunctionTest, WorksForVoidUnary) {
TEST(MockMethodMockFunctionTest, WorksForNonVoidBinary) {
MockFunction<int(bool, int)> foo;
EXPECT_CALL(foo, Call(false, 42))
.WillOnce(Return(1))
.WillOnce(Return(2));
EXPECT_CALL(foo, Call(true, Ge(100)))
.WillOnce(Return(3));
EXPECT_CALL(foo, Call(false, 42)).WillOnce(Return(1)).WillOnce(Return(2));
EXPECT_CALL(foo, Call(true, Ge(100))).WillOnce(Return(3));
EXPECT_EQ(1, foo.Call(false, 42));
EXPECT_EQ(2, foo.Call(false, 42));
EXPECT_EQ(3, foo.Call(true, 120));
}
TEST(MockMethodMockFunctionTest, WorksFor10Arguments) {
MockFunction<int(bool a0, char a1, int a2, int a3, int a4,
int a5, int a6, char a7, int a8, bool a9)> foo;
MockFunction<int(bool a0, char a1, int a2, int a3, int a4, int a5, int a6,
char a7, int a8, bool a9)>
foo;
EXPECT_CALL(foo, Call(_, 'a', _, _, _, _, _, _, _, _))
.WillOnce(Return(1))
.WillOnce(Return(2));
@ -816,9 +805,7 @@ TEST(MockMethodMockFunctionTest, WorksFor10Arguments) {
TEST(MockMethodMockFunctionTest, AsStdFunction) {
MockFunction<int(int)> foo;
auto call = [](const std::function<int(int)> &f, int i) {
return f(i);
};
auto call = [](const std::function<int(int)>& f, int i) { return f(i); };
EXPECT_CALL(foo, Call(1)).WillOnce(Return(-1));
EXPECT_CALL(foo, Call(2)).WillOnce(Return(-2));
EXPECT_EQ(-1, call(foo.AsStdFunction(), 1));
@ -837,9 +824,7 @@ TEST(MockMethodMockFunctionTest, AsStdFunctionReturnsReference) {
TEST(MockMethodMockFunctionTest, AsStdFunctionWithReferenceParameter) {
MockFunction<int(int&)> foo;
auto call = [](const std::function<int(int& )> &f, int &i) {
return f(i);
};
auto call = [](const std::function<int(int&)>& f, int& i) { return f(i); };
int i = 42;
EXPECT_CALL(foo, Call(i)).WillOnce(Return(-1));
EXPECT_EQ(-1, call(foo.AsStdFunction(), i));
@ -888,8 +873,7 @@ TYPED_TEST(
}
template <typename F>
struct AlternateCallable {
};
struct AlternateCallable {};
TYPED_TEST(MockMethodMockFunctionSignatureTest,
IsMockFunctionTemplateArgumentDeducedForAlternateCallable) {
@ -898,8 +882,7 @@ TYPED_TEST(MockMethodMockFunctionSignatureTest,
EXPECT_TRUE(IsMockFunctionTemplateArgumentDeducedTo<TypeParam>(foo));
}
TYPED_TEST(
MockMethodMockFunctionSignatureTest,
TYPED_TEST(MockMethodMockFunctionSignatureTest,
IsMockFunctionCallMethodSignatureTheSameForAlternateCallable) {
using ForRawSignature = decltype(&MockFunction<TypeParam>::Call);
using ForStdFunction =
@ -907,7 +890,6 @@ TYPED_TEST(
EXPECT_TRUE((std::is_same<ForRawSignature, ForStdFunction>::value));
}
struct MockMethodSizes0 {
MOCK_METHOD(void, func, ());
};
@ -940,7 +922,6 @@ struct LegacyMockMethodSizes4 {
MOCK_METHOD4(func, void(int, int, int, int));
};
TEST(MockMethodMockFunctionTest, MockMethodSizeOverhead) {
EXPECT_EQ(sizeof(MockMethodSizes0), sizeof(MockMethodSizes1));
EXPECT_EQ(sizeof(MockMethodSizes0), sizeof(MockMethodSizes2));

View File

@ -27,7 +27,6 @@
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// Google Mock - a framework for writing C++ mock classes.
//
// This file tests the internal utilities.
@ -214,26 +213,26 @@ TEST(LosslessArithmeticConvertibleTest, IntegerToInteger) {
EXPECT_TRUE((LosslessArithmeticConvertible<unsigned char, int>::value));
// Unsigned => larger unsigned is fine.
EXPECT_TRUE((LosslessArithmeticConvertible<
unsigned short, uint64_t>::value)); // NOLINT
EXPECT_TRUE((LosslessArithmeticConvertible<unsigned short,
uint64_t>::value)); // NOLINT
// Signed => unsigned is not fine.
EXPECT_FALSE((LosslessArithmeticConvertible<
short, uint64_t>::value)); // NOLINT
EXPECT_FALSE((LosslessArithmeticConvertible<
signed char, unsigned int>::value)); // NOLINT
EXPECT_FALSE(
(LosslessArithmeticConvertible<short, uint64_t>::value)); // NOLINT
EXPECT_FALSE((LosslessArithmeticConvertible<signed char,
unsigned int>::value)); // NOLINT
// Same size and same signedness: fine too.
EXPECT_TRUE((LosslessArithmeticConvertible<
unsigned char, unsigned char>::value));
EXPECT_TRUE(
(LosslessArithmeticConvertible<unsigned char, unsigned char>::value));
EXPECT_TRUE((LosslessArithmeticConvertible<int, int>::value));
EXPECT_TRUE((LosslessArithmeticConvertible<wchar_t, wchar_t>::value));
EXPECT_TRUE((LosslessArithmeticConvertible<
unsigned long, unsigned long>::value)); // NOLINT
EXPECT_TRUE((LosslessArithmeticConvertible<unsigned long,
unsigned long>::value)); // NOLINT
// Same size, different signedness: not fine.
EXPECT_FALSE((LosslessArithmeticConvertible<
unsigned char, signed char>::value));
EXPECT_FALSE(
(LosslessArithmeticConvertible<unsigned char, signed char>::value));
EXPECT_FALSE((LosslessArithmeticConvertible<int, unsigned int>::value));
EXPECT_FALSE((LosslessArithmeticConvertible<uint64_t, int64_t>::value));
@ -248,8 +247,8 @@ TEST(LosslessArithmeticConvertibleTest, IntegerToFloatingPoint) {
// the format of the latter is implementation-defined.
EXPECT_FALSE((LosslessArithmeticConvertible<char, float>::value));
EXPECT_FALSE((LosslessArithmeticConvertible<int, double>::value));
EXPECT_FALSE((LosslessArithmeticConvertible<
short, long double>::value)); // NOLINT
EXPECT_FALSE(
(LosslessArithmeticConvertible<short, long double>::value)); // NOLINT
}
TEST(LosslessArithmeticConvertibleTest, FloatingPointToBool) {
@ -336,13 +335,10 @@ TEST(AssertTest, SucceedsOnTrue) {
// Tests that Assert(false, ...) generates a fatal failure.
TEST(AssertTest, FailsFatallyOnFalse) {
EXPECT_DEATH_IF_SUPPORTED({
Assert(false, __FILE__, __LINE__, "This should fail.");
}, "");
EXPECT_DEATH_IF_SUPPORTED(
{ Assert(false, __FILE__, __LINE__, "This should fail."); }, "");
EXPECT_DEATH_IF_SUPPORTED({
Assert(false, __FILE__, __LINE__);
}, "");
EXPECT_DEATH_IF_SUPPORTED({ Assert(false, __FILE__, __LINE__); }, "");
}
// Tests that Expect(true, ...) succeeds.
@ -353,13 +349,17 @@ TEST(ExpectTest, SucceedsOnTrue) {
// Tests that Expect(false, ...) generates a non-fatal failure.
TEST(ExpectTest, FailsNonfatallyOnFalse) {
EXPECT_NONFATAL_FAILURE({ // NOLINT
EXPECT_NONFATAL_FAILURE(
{ // NOLINT
Expect(false, __FILE__, __LINE__, "This should fail.");
}, "This should fail");
},
"This should fail");
EXPECT_NONFATAL_FAILURE({ // NOLINT
EXPECT_NONFATAL_FAILURE(
{ // NOLINT
Expect(false, __FILE__, __LINE__);
}, "Expectation failed");
},
"Expectation failed");
}
// Tests LogIsVisible().
@ -404,11 +404,11 @@ void TestLogWithSeverity(const std::string& verbosity, LogSeverity severity,
CaptureStdout();
Log(severity, "Test log.\n", 0);
if (should_print) {
EXPECT_THAT(GetCapturedStdout().c_str(),
ContainsRegex(
severity == kWarning ?
"^\nGMOCK WARNING:\nTest log\\.\nStack trace:\n" :
"^\nTest log\\.\nStack trace:\n"));
EXPECT_THAT(
GetCapturedStdout().c_str(),
ContainsRegex(severity == kWarning
? "^\nGMOCK WARNING:\nTest log\\.\nStack trace:\n"
: "^\nTest log\\.\nStack trace:\n"));
} else {
EXPECT_STREQ("", GetCapturedStdout().c_str());
}
@ -597,8 +597,7 @@ TEST(StlContainerViewTest, WorksForStlContainer) {
}
TEST(StlContainerViewTest, WorksForStaticNativeArray) {
StaticAssertTypeEq<NativeArray<int>,
StlContainerView<int[3]>::type>();
StaticAssertTypeEq<NativeArray<int>, StlContainerView<int[3]>::type>();
StaticAssertTypeEq<NativeArray<double>,
StlContainerView<const double[4]>::type>();
StaticAssertTypeEq<NativeArray<char[3]>,

File diff suppressed because it is too large Load Diff

View File

@ -291,8 +291,7 @@ TEST(InvokeTest, FunctionWithUnusedParameters) {
std::make_tuple(10, 2, 5.6, std::string("hi"));
EXPECT_EQ(12, a1.Perform(dummy));
Action<int(int, int, bool, int*)> a2 =
Invoke(SumOfFirst2);
Action<int(int, int, bool, int*)> a2 = Invoke(SumOfFirst2);
EXPECT_EQ(
23, a2.Perform(std::make_tuple(20, 3, true, static_cast<int*>(nullptr))));
}
@ -303,8 +302,7 @@ TEST(InvokeTest, MethodWithUnusedParameters) {
Action<int(std::string, bool, int, int)> a1 = Invoke(&foo, &Foo::SumOfLast2);
EXPECT_EQ(12, a1.Perform(std::make_tuple(CharPtr("hi"), true, 10, 2)));
Action<int(char, double, int, int)> a2 =
Invoke(&foo, &Foo::SumOfLast2);
Action<int(char, double, int, int)> a2 = Invoke(&foo, &Foo::SumOfLast2);
EXPECT_EQ(23, a2.Perform(std::make_tuple('a', 2.5, 20, 3)));
}
@ -362,7 +360,8 @@ TEST(InvokeMethodTest, MethodThatTakes4Arguments) {
// Tests using Invoke() with a 5-argument method.
TEST(InvokeMethodTest, MethodThatTakes5Arguments) {
Foo foo;
Action<int(int, int, int, int, int)> a = Invoke(&foo, &Foo::SumOf5); // NOLINT
Action<int(int, int, int, int, int)> a =
Invoke(&foo, &Foo::SumOf5); // NOLINT
EXPECT_EQ(12345, a.Perform(std::make_tuple(10000, 2000, 300, 40, 5)));
}
@ -523,15 +522,12 @@ TEST(SetArgRefereeActionTest, WorksWithExtraArguments) {
// the bool provided to the constructor to true when destroyed.
class DeletionTester {
public:
explicit DeletionTester(bool* is_deleted)
: is_deleted_(is_deleted) {
explicit DeletionTester(bool* is_deleted) : is_deleted_(is_deleted) {
// Make sure the bit is set to false.
*is_deleted_ = false;
}
~DeletionTester() {
*is_deleted_ = true;
}
~DeletionTester() { *is_deleted_ = true; }
private:
bool* is_deleted_;
@ -549,8 +545,9 @@ TEST(DeleteArgActionTest, OneArg) {
TEST(DeleteArgActionTest, TenArgs) {
bool is_deleted = false;
DeletionTester* t = new DeletionTester(&is_deleted);
const Action<void(bool, int, int, const char*, bool,
int, int, int, int, DeletionTester*)> a1 = DeleteArg<9>();
const Action<void(bool, int, int, const char*, bool, int, int, int, int,
DeletionTester*)>
a1 = DeleteArg<9>();
EXPECT_FALSE(is_deleted);
a1.Perform(std::make_tuple(true, 5, 6, CharPtr("hi"), false, 7, 8, 9, 10, t));
EXPECT_TRUE(is_deleted);

View File

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

View File

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

View File

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

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
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// Tests Google Mock's functionality that depends on exceptions.
#include "gmock/gmock.h"
@ -75,6 +74,5 @@ TEST(DefaultValueTest, ThrowsRuntimeErrorWhenNoDefaultValue) {
}
}
} // unnamed namespace
#endif

View File

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

View File

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

View File

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

View File

@ -27,7 +27,6 @@
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// Google Mock - a framework for writing C++ mock classes.
//
// This file tests that:
@ -301,8 +300,8 @@ TEST(LinkTest, TestSetArrayArgument) {
char ch = 'x';
char ch2 = 'y';
EXPECT_CALL(mock, VoidFromString(_)).WillOnce(SetArrayArgument<0>(&ch2,
&ch2 + 1));
EXPECT_CALL(mock, VoidFromString(_))
.WillOnce(SetArrayArgument<0>(&ch2, &ch2 + 1));
mock.VoidFromString(&ch);
}
@ -339,8 +338,8 @@ TEST(LinkTest, TestInvokeWithoutArgs) {
EXPECT_CALL(mock, VoidFromString(_))
.WillOnce(InvokeWithoutArgs(&InvokeHelper::StaticVoidFromVoid))
.WillOnce(InvokeWithoutArgs(&test_invoke_helper,
&InvokeHelper::VoidFromVoid));
.WillOnce(
InvokeWithoutArgs(&test_invoke_helper, &InvokeHelper::VoidFromVoid));
mock.VoidFromString(nullptr);
mock.VoidFromString(nullptr);
}
@ -431,7 +430,7 @@ TEST(LinkTest, TestThrow) {
// Tests the linkage of actions created using ACTION macro.
namespace {
ACTION(Return1) { return 1; }
}
} // namespace
TEST(LinkTest, TestActionMacro) {
Mock mock;
@ -443,7 +442,7 @@ TEST(LinkTest, TestActionMacro) {
// Tests the linkage of actions created using ACTION_P macro.
namespace {
ACTION_P(ReturnArgument, ret_value) { return ret_value; }
}
} // namespace
TEST(LinkTest, TestActionPMacro) {
Mock mock;
@ -457,7 +456,7 @@ namespace {
ACTION_P2(ReturnEqualsEitherOf, first, second) {
return arg0 == first || arg0 == second;
}
}
} // namespace
#ifdef _MSC_VER
#pragma warning(pop)
@ -492,8 +491,7 @@ TEST(LinkTest, TestMatchersEq) {
const char* p = "x";
ON_CALL(mock, VoidFromString(Eq(p))).WillByDefault(Return());
ON_CALL(mock, VoidFromString(const_cast<char*>("y")))
.WillByDefault(Return());
ON_CALL(mock, VoidFromString(const_cast<char*>("y"))).WillByDefault(Return());
}
// Tests the linkage of the Lt, Gt, Le, Ge, and Ne matchers.

View File

@ -27,15 +27,14 @@
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// Tests Google Mock's output in various scenarios. This ensures that
// Google Mock's messages are readable and useful.
#include "gmock/gmock.h"
#include <stdio.h>
#include <string>
#include "gmock/gmock.h"
#include "gtest/gtest.h"
// Silence C4100 (unreferenced formal parameter)
@ -90,9 +89,7 @@ TEST_F(GMockOutputTest, ExpectedCallToVoidFunction) {
}
TEST_F(GMockOutputTest, ExplicitActionsRunOut) {
EXPECT_CALL(foo_, Bar2(_, _))
.Times(2)
.WillOnce(Return(false));
EXPECT_CALL(foo_, Bar2(_, _)).Times(2).WillOnce(Return(false));
foo_.Bar2(2, 2);
foo_.Bar2(1, 1); // Explicit actions in EXPECT_CALL run out.
}
@ -134,8 +131,7 @@ TEST_F(GMockOutputTest, UninterestingCallToVoidFunction) {
}
TEST_F(GMockOutputTest, RetiredExpectation) {
EXPECT_CALL(foo_, Bar2(_, _))
.RetiresOnSaturation();
EXPECT_CALL(foo_, Bar2(_, _)).RetiresOnSaturation();
EXPECT_CALL(foo_, Bar2(0, 0));
foo_.Bar2(1, 1);
@ -160,12 +156,9 @@ TEST_F(GMockOutputTest, UnsatisfiedPrerequisite) {
TEST_F(GMockOutputTest, UnsatisfiedPrerequisites) {
Sequence s1, s2;
EXPECT_CALL(foo_, Bar(_, 0, _))
.InSequence(s1);
EXPECT_CALL(foo_, Bar2(0, 0))
.InSequence(s2);
EXPECT_CALL(foo_, Bar2(1, _))
.InSequence(s1, s2);
EXPECT_CALL(foo_, Bar(_, 0, _)).InSequence(s1);
EXPECT_CALL(foo_, Bar2(0, 0)).InSequence(s2);
EXPECT_CALL(foo_, Bar2(1, _)).InSequence(s1, s2);
foo_.Bar2(1, 0); // Has two immediate unsatisfied pre-requisites
foo_.Bar("Hi", 0, 0);
@ -179,8 +172,7 @@ TEST_F(GMockOutputTest, UnsatisfiedWith) {
TEST_F(GMockOutputTest, UnsatisfiedExpectation) {
EXPECT_CALL(foo_, Bar(_, _, _));
EXPECT_CALL(foo_, Bar2(0, _))
.Times(2);
EXPECT_CALL(foo_, Bar2(0, _)).Times(2);
foo_.Bar2(0, 1);
}
@ -194,26 +186,22 @@ TEST_F(GMockOutputTest, MismatchArguments) {
}
TEST_F(GMockOutputTest, MismatchWith) {
EXPECT_CALL(foo_, Bar2(Ge(2), Ge(1)))
.With(Ge());
EXPECT_CALL(foo_, Bar2(Ge(2), Ge(1))).With(Ge());
foo_.Bar2(2, 3); // Mismatch With()
foo_.Bar2(2, 1);
}
TEST_F(GMockOutputTest, MismatchArgumentsAndWith) {
EXPECT_CALL(foo_, Bar2(Ge(2), Ge(1)))
.With(Ge());
EXPECT_CALL(foo_, Bar2(Ge(2), Ge(1))).With(Ge());
foo_.Bar2(1, 3); // Mismatch arguments and mismatch With()
foo_.Bar2(2, 1);
}
TEST_F(GMockOutputTest, UnexpectedCallWithDefaultAction) {
ON_CALL(foo_, Bar2(_, _))
.WillByDefault(Return(true)); // Default action #1
ON_CALL(foo_, Bar2(1, _))
.WillByDefault(Return(false)); // Default action #2
ON_CALL(foo_, Bar2(_, _)).WillByDefault(Return(true)); // Default action #1
ON_CALL(foo_, Bar2(1, _)).WillByDefault(Return(false)); // Default action #2
EXPECT_CALL(foo_, Bar2(2, 2));
foo_.Bar2(1, 0); // Unexpected call, takes default action #2.
@ -222,10 +210,8 @@ TEST_F(GMockOutputTest, UnexpectedCallWithDefaultAction) {
}
TEST_F(GMockOutputTest, ExcessiveCallWithDefaultAction) {
ON_CALL(foo_, Bar2(_, _))
.WillByDefault(Return(true)); // Default action #1
ON_CALL(foo_, Bar2(1, _))
.WillByDefault(Return(false)); // Default action #2
ON_CALL(foo_, Bar2(_, _)).WillByDefault(Return(true)); // Default action #1
ON_CALL(foo_, Bar2(1, _)).WillByDefault(Return(false)); // Default action #2
EXPECT_CALL(foo_, Bar2(2, 2));
EXPECT_CALL(foo_, Bar2(1, 1));
@ -237,22 +223,17 @@ TEST_F(GMockOutputTest, ExcessiveCallWithDefaultAction) {
}
TEST_F(GMockOutputTest, UninterestingCallWithDefaultAction) {
ON_CALL(foo_, Bar2(_, _))
.WillByDefault(Return(true)); // Default action #1
ON_CALL(foo_, Bar2(1, _))
.WillByDefault(Return(false)); // Default action #2
ON_CALL(foo_, Bar2(_, _)).WillByDefault(Return(true)); // Default action #1
ON_CALL(foo_, Bar2(1, _)).WillByDefault(Return(false)); // Default action #2
foo_.Bar2(2, 2); // Uninteresting call, takes default action #1.
foo_.Bar2(1, 1); // Uninteresting call, takes default action #2.
}
TEST_F(GMockOutputTest, ExplicitActionsRunOutWithDefaultAction) {
ON_CALL(foo_, Bar2(_, _))
.WillByDefault(Return(true)); // Default action #1
ON_CALL(foo_, Bar2(_, _)).WillByDefault(Return(true)); // Default action #1
EXPECT_CALL(foo_, Bar2(_, _))
.Times(2)
.WillOnce(Return(false));
EXPECT_CALL(foo_, Bar2(_, _)).Times(2).WillOnce(Return(false));
foo_.Bar2(2, 2);
foo_.Bar2(1, 1); // Explicit actions in EXPECT_CALL run out.
}

View File

@ -27,7 +27,6 @@
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// Tests that Google Mock constructs can be used in a large number of
// threads concurrently.
@ -62,21 +61,16 @@ void JoinAndDelete(ThreadWithParam<T>* t) {
struct Dummy {};
// Tests that different mock objects can be used in their respective
// threads. This should generate no Google Test failure.
void TestConcurrentMockObjects(Dummy /* dummy */) {
// Creates a mock and does some typical operations on it.
MockFoo foo;
ON_CALL(foo, Bar(_))
.WillByDefault(Return(1));
ON_CALL(foo, Baz(_, _))
.WillByDefault(Return('b'));
ON_CALL(foo, Baz(_, "you"))
.WillByDefault(Return('a'));
ON_CALL(foo, Bar(_)).WillByDefault(Return(1));
ON_CALL(foo, Baz(_, _)).WillByDefault(Return('b'));
ON_CALL(foo, Baz(_, "you")).WillByDefault(Return('a'));
EXPECT_CALL(foo, Bar(0))
.Times(AtMost(3));
EXPECT_CALL(foo, Bar(0)).Times(AtMost(3));
EXPECT_CALL(foo, Baz(_, _));
EXPECT_CALL(foo, Baz("hi", "you"))
.WillOnce(Return('z'))
@ -119,11 +113,8 @@ void Helper1(Helper1Param param) {
void TestConcurrentCallsOnSameObject(Dummy /* dummy */) {
MockFoo foo;
ON_CALL(foo, Bar(_))
.WillByDefault(Return(1));
EXPECT_CALL(foo, Baz(_, "b"))
.Times(kRepeat)
.WillRepeatedly(Return('a'));
ON_CALL(foo, Bar(_)).WillByDefault(Return(1));
EXPECT_CALL(foo, Baz(_, "b")).Times(kRepeat).WillRepeatedly(Return('a'));
EXPECT_CALL(foo, Baz(_, "c")); // Expected to be unsatisfied.
// This chunk of code should generate kRepeat failures about
@ -162,22 +153,18 @@ void TestPartiallyOrderedExpectationsWithThreads(Dummy /* dummy */) {
{
InSequence dummy;
EXPECT_CALL(foo, Bar(0));
EXPECT_CALL(foo, Bar(1))
.InSequence(s1, s2);
EXPECT_CALL(foo, Bar(1)).InSequence(s1, s2);
}
EXPECT_CALL(foo, Bar(2))
.Times(2 * kRepeat)
.InSequence(s1)
.RetiresOnSaturation();
EXPECT_CALL(foo, Bar(3))
.Times(2*kRepeat)
.InSequence(s2);
EXPECT_CALL(foo, Bar(3)).Times(2 * kRepeat).InSequence(s2);
{
InSequence dummy;
EXPECT_CALL(foo, Bar(2))
.InSequence(s1, s2);
EXPECT_CALL(foo, Bar(2)).InSequence(s1, s2);
EXPECT_CALL(foo, Bar(4));
}

View File

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

View File

@ -198,6 +198,7 @@ class GTEST_API_ ExitedWithCode {
ExitedWithCode(const ExitedWithCode&) = default;
void operator=(const ExitedWithCode& other) = delete;
bool operator()(int exit_status) const;
private:
const int exit_code_;
};
@ -209,6 +210,7 @@ class GTEST_API_ KilledBySignal {
public:
explicit KilledBySignal(int signum);
bool operator()(int exit_status) const;
private:
const int signum_;
};
@ -267,11 +269,9 @@ class GTEST_API_ KilledBySignal {
#else
# define EXPECT_DEBUG_DEATH(statement, regex) \
EXPECT_DEATH(statement, regex)
#define EXPECT_DEBUG_DEATH(statement, regex) EXPECT_DEATH(statement, regex)
# define ASSERT_DEBUG_DEATH(statement, regex) \
ASSERT_DEATH(statement, regex)
#define ASSERT_DEBUG_DEATH(statement, regex) ASSERT_DEATH(statement, regex)
#endif // NDEBUG for EXPECT_DEBUG_DEATH
#endif // GTEST_HAS_DEATH_TEST
@ -314,8 +314,7 @@ class GTEST_API_ KilledBySignal {
#define GTEST_UNSUPPORTED_DEATH_TEST(statement, regex, terminator) \
GTEST_AMBIGUOUS_ELSE_BLOCKER_ \
if (::testing::internal::AlwaysTrue()) { \
GTEST_LOG_(WARNING) \
<< "Death tests are not supported on this platform.\n" \
GTEST_LOG_(WARNING) << "Death tests are not supported on this platform.\n" \
<< "Statement '" #statement "' cannot be verified."; \
} else if (::testing::internal::AlwaysFalse()) { \
::testing::internal::RE::PartialMatch(".*", (regex)); \

View File

@ -105,8 +105,7 @@ class MatchResultListener {
GTEST_DISALLOW_COPY_AND_ASSIGN_(MatchResultListener);
};
inline MatchResultListener::~MatchResultListener() {
}
inline MatchResultListener::~MatchResultListener() {}
// An instance of a subclass of this knows how to describe itself as a
// matcher.
@ -180,27 +179,39 @@ namespace internal {
struct AnyEq {
template <typename A, typename B>
bool operator()(const A& a, const B& b) const { return a == b; }
bool operator()(const A& a, const B& b) const {
return a == b;
}
};
struct AnyNe {
template <typename A, typename B>
bool operator()(const A& a, const B& b) const { return a != b; }
bool operator()(const A& a, const B& b) const {
return a != b;
}
};
struct AnyLt {
template <typename A, typename B>
bool operator()(const A& a, const B& b) const { return a < b; }
bool operator()(const A& a, const B& b) const {
return a < b;
}
};
struct AnyGt {
template <typename A, typename B>
bool operator()(const A& a, const B& b) const { return a > b; }
bool operator()(const A& a, const B& b) const {
return a > b;
}
};
struct AnyLe {
template <typename A, typename B>
bool operator()(const A& a, const B& b) const { return a <= b; }
bool operator()(const A& a, const B& b) const {
return a <= b;
}
};
struct AnyGe {
template <typename A, typename B>
bool operator()(const A& a, const B& b) const { return a >= b; }
bool operator()(const A& a, const B& b) const {
return a >= b;
}
};
// A match result listener that ignores the explanation.
@ -424,8 +435,8 @@ class MatcherBase : private MatcherDescriberInterface {
static const M& Get(const MatcherBase& m) {
// When inlined along with Init, need to be explicit to avoid violating
// strict aliasing rules.
const M *ptr = static_cast<const M*>(
static_cast<const void*>(&m.buffer_));
const M* ptr =
static_cast<const M*>(static_cast<const void*>(&m.buffer_));
return *ptr;
}
static void Init(MatcherBase& m, M impl) {
@ -876,12 +887,16 @@ PolymorphicMatcher<internal::MatchesRegexMatcher> ContainsRegex(
// Note: if the parameter of Eq() were declared as const T&, Eq("foo")
// wouldn't compile.
template <typename T>
inline internal::EqMatcher<T> Eq(T x) { return internal::EqMatcher<T>(x); }
inline internal::EqMatcher<T> Eq(T x) {
return internal::EqMatcher<T>(x);
}
// Constructs a Matcher<T> from a 'value' of type T. The constructed
// matcher matches any value that's equal to 'value'.
template <typename T>
Matcher<T>::Matcher(T value) { *this = Eq(value); }
Matcher<T>::Matcher(T value) {
*this = Eq(value);
}
// Creates a monomorphic matcher that matches anything with type Lhs
// and equal to rhs. A user may need to use this instead of Eq(...)
@ -896,7 +911,9 @@ Matcher<T>::Matcher(T value) { *this = Eq(value); }
// can always write Matcher<T>(Lt(5)) to be explicit about the type,
// for example.
template <typename Lhs, typename Rhs>
inline Matcher<Lhs> TypedEq(const Rhs& rhs) { return Eq(rhs); }
inline Matcher<Lhs> TypedEq(const Rhs& rhs) {
return Eq(rhs);
}
// Creates a polymorphic matcher that matches anything >= x.
template <typename Rhs>

View File

@ -166,9 +166,7 @@ class GTEST_API_ Message {
}
// Instead of 1/0, we want to see true/false for bool values.
Message& operator <<(bool b) {
return *this << (b ? "true" : "false");
}
Message& operator<<(bool b) { return *this << (b ? "true" : "false"); }
// These two overloads allow streaming a wide C string to a Message
// using the UTF-8 encoding.

View File

@ -356,9 +356,7 @@ internal::ValueArray<T...> Values(T... v) {
// }
// INSTANTIATE_TEST_SUITE_P(BoolSequence, FlagDependentTest, Bool());
//
inline internal::ParamGenerator<bool> Bool() {
return Values(false, true);
}
inline internal::ParamGenerator<bool> Bool() { return Values(false, true); }
// Combine() allows the user to combine two or more sequences to produce
// values of a Cartesian product of those sequences' elements.
@ -490,7 +488,6 @@ internal::CartesianProductHolder<Generator...> Combine(const Generator&... g) {
&gtest_##prefix##test_suite_name##_EvalGenerateName_, \
__FILE__, __LINE__)
// Allow Marking a Parameterized test class as not needing to be instantiated.
#define GTEST_ALLOW_UNINSTANTIATED_PARAMETERIZED_TEST(T) \
namespace gtest_do_not_use_outside_namespace_scope {} \

View File

@ -258,12 +258,10 @@ struct ConvertibleToStringViewPrinter {
#endif
};
// Prints the given number of bytes in the given object to the given
// ostream.
GTEST_API_ void PrintBytesInObjectTo(const unsigned char* obj_bytes,
size_t count,
::std::ostream* os);
size_t count, ::std::ostream* os);
struct RawBytesPrinter {
// SFINAE on `sizeof` to make sure we have a complete type.
template <typename T, size_t = sizeof(T)>
@ -411,8 +409,8 @@ GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(const wchar_t, ::std::wstring);
//
// INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.
template <typename T1, typename T2>
std::string FormatForComparisonFailureMessage(
const T1& value, const T2& /* other_operand */) {
std::string FormatForComparisonFailureMessage(const T1& value,
const T2& /* other_operand */) {
return FormatForComparison<T1, T2>::Format(value);
}
@ -823,8 +821,8 @@ void UniversalPrintArray(const T* begin, size_t len, ::std::ostream* os) {
}
}
// This overload prints a (const) char array compactly.
GTEST_API_ void UniversalPrintArray(
const char* begin, size_t len, ::std::ostream* os);
GTEST_API_ void UniversalPrintArray(const char* begin, size_t len,
::std::ostream* os);
#ifdef __cpp_char8_t
// This overload prints a (const) char8_t array compactly.
@ -841,8 +839,8 @@ GTEST_API_ void UniversalPrintArray(const char32_t* begin, size_t len,
::std::ostream* os);
// This overload prints a (const) wchar_t array compactly.
GTEST_API_ void UniversalPrintArray(
const wchar_t* begin, size_t len, ::std::ostream* os);
GTEST_API_ void UniversalPrintArray(const wchar_t* begin, size_t len,
::std::ostream* os);
// Implements printing an array type T[N].
template <typename T, size_t N>

View File

@ -101,6 +101,7 @@ class GTEST_API_ SingleFailureChecker {
SingleFailureChecker(const TestPartResultArray* results,
TestPartResult::Type type, const std::string& substr);
~SingleFailureChecker();
private:
const TestPartResultArray* const results_;
const TestPartResult::Type type_;
@ -150,7 +151,8 @@ GTEST_DISABLE_MSC_WARNINGS_POP_() // 4251
{ \
::testing::ScopedFakeTestPartResultReporter gtest_reporter( \
::testing::ScopedFakeTestPartResultReporter:: \
INTERCEPT_ONLY_CURRENT_THREAD, &gtest_failures);\
INTERCEPT_ONLY_CURRENT_THREAD, \
&gtest_failures); \
GTestExpectFatalFailureHelper::Execute(); \
} \
} while (::testing::internal::AlwaysFalse())
@ -166,8 +168,8 @@ GTEST_DISABLE_MSC_WARNINGS_POP_() // 4251
&gtest_failures, ::testing::TestPartResult::kFatalFailure, (substr)); \
{ \
::testing::ScopedFakeTestPartResultReporter gtest_reporter( \
::testing::ScopedFakeTestPartResultReporter:: \
INTERCEPT_ALL_THREADS, &gtest_failures);\
::testing::ScopedFakeTestPartResultReporter::INTERCEPT_ALL_THREADS, \
&gtest_failures); \
GTestExpectFatalFailureHelper::Execute(); \
} \
} while (::testing::internal::AlwaysFalse())
@ -213,8 +215,11 @@ GTEST_DISABLE_MSC_WARNINGS_POP_() // 4251
{ \
::testing::ScopedFakeTestPartResultReporter gtest_reporter( \
::testing::ScopedFakeTestPartResultReporter:: \
INTERCEPT_ONLY_CURRENT_THREAD, &gtest_failures);\
if (::testing::internal::AlwaysTrue()) { statement; }\
INTERCEPT_ONLY_CURRENT_THREAD, \
&gtest_failures); \
if (::testing::internal::AlwaysTrue()) { \
statement; \
} \
} \
} while (::testing::internal::AlwaysFalse())
@ -228,7 +233,9 @@ GTEST_DISABLE_MSC_WARNINGS_POP_() // 4251
::testing::ScopedFakeTestPartResultReporter gtest_reporter( \
::testing::ScopedFakeTestPartResultReporter::INTERCEPT_ALL_THREADS, \
&gtest_failures); \
if (::testing::internal::AlwaysTrue()) { statement; }\
if (::testing::internal::AlwaysTrue()) { \
statement; \
} \
} \
} while (::testing::internal::AlwaysFalse())

View File

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

View File

@ -353,24 +353,17 @@ class TestProperty {
// C'tor. TestProperty does NOT have a default constructor.
// Always use this constructor (with parameters) to create a
// TestProperty object.
TestProperty(const std::string& a_key, const std::string& a_value) :
key_(a_key), value_(a_value) {
}
TestProperty(const std::string& a_key, const std::string& a_value)
: key_(a_key), value_(a_value) {}
// Gets the user supplied key.
const char* key() const {
return key_.c_str();
}
const char* key() const { return key_.c_str(); }
// Gets the user supplied value.
const char* value() const {
return value_.c_str();
}
const char* value() const { return value_.c_str(); }
// Sets a new value, overriding the one supplied in the constructor.
void SetValue(const std::string& new_value) {
value_ = new_value;
}
void SetValue(const std::string& new_value) { value_ = new_value; }
private:
// The key supplied by the user.
@ -886,6 +879,7 @@ class Environment {
// Override this to define how to tear down the environment.
virtual void TearDown() {}
private:
// If you see an error about overriding the following function or
// about it being private, you have mis-spelled SetUp() as Setup().
@ -963,8 +957,7 @@ class TestEventListener {
virtual void OnEnvironmentsTearDownEnd(const UnitTest& unit_test) = 0;
// Fired after each iteration of tests finishes.
virtual void OnTestIterationEnd(const UnitTest& unit_test,
int iteration) = 0;
virtual void OnTestIterationEnd(const UnitTest& unit_test, int iteration) = 0;
// Fired after all test activities have ended.
virtual void OnTestProgramEnd(const UnitTest& unit_test) = 0;
@ -1122,8 +1115,7 @@ class GTEST_API_ UnitTest {
// Returns the TestInfo object for the test that's currently running,
// or NULL if no test is running.
const TestInfo* current_test_info() const
GTEST_LOCK_EXCLUDED_(mutex_);
const TestInfo* current_test_info() const GTEST_LOCK_EXCLUDED_(mutex_);
// Returns the random seed used at the start of the current test run.
int random_seed() const;
@ -1229,8 +1221,7 @@ class GTEST_API_ UnitTest {
// eventually call this to report their results. The user code
// should use the assertion macros instead of calling this directly.
void AddTestPartResult(TestPartResult::Type result_type,
const char* file_name,
int line_number,
const char* file_name, int line_number,
const std::string& message,
const std::string& os_stack_trace)
GTEST_LOCK_EXCLUDED_(mutex_);
@ -1261,8 +1252,7 @@ class GTEST_API_ UnitTest {
friend std::set<std::string>* internal::GetIgnoredParameterizedTestSuites();
friend internal::UnitTestImpl* internal::GetUnitTestImpl();
friend void internal::ReportFailureInUnknownLocation(
TestPartResult::Type result_type,
const std::string& message);
TestPartResult::Type result_type, const std::string& message);
// Creates an empty UnitTest.
UnitTest();
@ -1276,8 +1266,7 @@ class GTEST_API_ UnitTest {
GTEST_LOCK_EXCLUDED_(mutex_);
// Pops a trace from the per-thread Google Test trace stack.
void PopGTestTrace()
GTEST_LOCK_EXCLUDED_(mutex_);
void PopGTestTrace() GTEST_LOCK_EXCLUDED_(mutex_);
// Protects mutable state in *impl_. This is mutable as some const
// methods need to lock it too.
@ -1341,13 +1330,11 @@ namespace internal {
// when calling EXPECT_* in a tight loop.
template <typename T1, typename T2>
AssertionResult CmpHelperEQFailure(const char* lhs_expression,
const char* rhs_expression,
const T1& lhs, const T2& rhs) {
return EqFailure(lhs_expression,
rhs_expression,
const char* rhs_expression, const T1& lhs,
const T2& rhs) {
return EqFailure(lhs_expression, rhs_expression,
FormatForComparisonFailureMessage(lhs, rhs),
FormatForComparisonFailureMessage(rhs, lhs),
false);
FormatForComparisonFailureMessage(rhs, lhs), false);
}
// This block of code defines operator==/!=
@ -1360,8 +1347,7 @@ inline bool operator!=(faketype, faketype) { return false; }
// The helper function for {ASSERT|EXPECT}_EQ.
template <typename T1, typename T2>
AssertionResult CmpHelperEQ(const char* lhs_expression,
const char* rhs_expression,
const T1& lhs,
const char* rhs_expression, const T1& lhs,
const T2& rhs) {
if (lhs == rhs) {
return AssertionSuccess();
@ -1392,8 +1378,7 @@ class EqHelper {
// Even though its body looks the same as the above version, we
// cannot merge the two, as it will make anonymous enums unhappy.
static AssertionResult Compare(const char* lhs_expression,
const char* rhs_expression,
BiggestInt lhs,
const char* rhs_expression, BiggestInt lhs,
BiggestInt rhs) {
return CmpHelperEQ(lhs_expression, rhs_expression, lhs, rhs);
}
@ -1459,49 +1444,42 @@ GTEST_IMPL_CMP_HELPER_(GT, >)
// INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.
GTEST_API_ AssertionResult CmpHelperSTREQ(const char* s1_expression,
const char* s2_expression,
const char* s1,
const char* s2);
const char* s1, const char* s2);
// The helper function for {ASSERT|EXPECT}_STRCASEEQ.
//
// INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.
GTEST_API_ AssertionResult CmpHelperSTRCASEEQ(const char* s1_expression,
const char* s2_expression,
const char* s1,
const char* s2);
const char* s1, const char* s2);
// The helper function for {ASSERT|EXPECT}_STRNE.
//
// INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.
GTEST_API_ AssertionResult CmpHelperSTRNE(const char* s1_expression,
const char* s2_expression,
const char* s1,
const char* s2);
const char* s1, const char* s2);
// The helper function for {ASSERT|EXPECT}_STRCASENE.
//
// INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.
GTEST_API_ AssertionResult CmpHelperSTRCASENE(const char* s1_expression,
const char* s2_expression,
const char* s1,
const char* s2);
const char* s1, const char* s2);
// Helper function for *_STREQ on wide strings.
//
// INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.
GTEST_API_ AssertionResult CmpHelperSTREQ(const char* s1_expression,
const char* s2_expression,
const wchar_t* s1,
const wchar_t* s2);
const wchar_t* s1, const wchar_t* s2);
// Helper function for *_STRNE on wide strings.
//
// INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.
GTEST_API_ AssertionResult CmpHelperSTRNE(const char* s1_expression,
const char* s2_expression,
const wchar_t* s1,
const wchar_t* s2);
const wchar_t* s1, const wchar_t* s2);
} // namespace internal
@ -1513,32 +1491,40 @@ GTEST_API_ AssertionResult CmpHelperSTRNE(const char* s1_expression,
//
// The {needle,haystack}_expr arguments are the stringified
// expressions that generated the two real arguments.
GTEST_API_ AssertionResult IsSubstring(
const char* needle_expr, const char* haystack_expr,
const char* needle, const char* haystack);
GTEST_API_ AssertionResult IsSubstring(
const char* needle_expr, const char* haystack_expr,
const wchar_t* needle, const wchar_t* haystack);
GTEST_API_ AssertionResult IsNotSubstring(
const char* needle_expr, const char* haystack_expr,
const char* needle, const char* haystack);
GTEST_API_ AssertionResult IsNotSubstring(
const char* needle_expr, const char* haystack_expr,
const wchar_t* needle, const wchar_t* haystack);
GTEST_API_ AssertionResult IsSubstring(
const char* needle_expr, const char* haystack_expr,
const ::std::string& needle, const ::std::string& haystack);
GTEST_API_ AssertionResult IsNotSubstring(
const char* needle_expr, const char* haystack_expr,
const ::std::string& needle, const ::std::string& haystack);
GTEST_API_ AssertionResult IsSubstring(const char* needle_expr,
const char* haystack_expr,
const char* needle,
const char* haystack);
GTEST_API_ AssertionResult IsSubstring(const char* needle_expr,
const char* haystack_expr,
const wchar_t* needle,
const wchar_t* haystack);
GTEST_API_ AssertionResult IsNotSubstring(const char* needle_expr,
const char* haystack_expr,
const char* needle,
const char* haystack);
GTEST_API_ AssertionResult IsNotSubstring(const char* needle_expr,
const char* haystack_expr,
const wchar_t* needle,
const wchar_t* haystack);
GTEST_API_ AssertionResult IsSubstring(const char* needle_expr,
const char* haystack_expr,
const ::std::string& needle,
const ::std::string& haystack);
GTEST_API_ AssertionResult IsNotSubstring(const char* needle_expr,
const char* haystack_expr,
const ::std::string& needle,
const ::std::string& haystack);
#if GTEST_HAS_STD_WSTRING
GTEST_API_ AssertionResult IsSubstring(
const char* needle_expr, const char* haystack_expr,
const ::std::wstring& needle, const ::std::wstring& haystack);
GTEST_API_ AssertionResult IsNotSubstring(
const char* needle_expr, const char* haystack_expr,
const ::std::wstring& needle, const ::std::wstring& haystack);
GTEST_API_ AssertionResult IsSubstring(const char* needle_expr,
const char* haystack_expr,
const ::std::wstring& needle,
const ::std::wstring& haystack);
GTEST_API_ AssertionResult IsNotSubstring(const char* needle_expr,
const char* haystack_expr,
const ::std::wstring& needle,
const ::std::wstring& haystack);
#endif // GTEST_HAS_STD_WSTRING
namespace internal {
@ -1553,8 +1539,7 @@ namespace internal {
template <typename RawType>
AssertionResult CmpHelperFloatingPointEQ(const char* lhs_expression,
const char* rhs_expression,
RawType lhs_value,
RawType rhs_value) {
RawType lhs_value, RawType rhs_value) {
const FloatingPoint<RawType> lhs(lhs_value), rhs(rhs_value);
if (lhs.AlmostEquals(rhs)) {
@ -1569,10 +1554,8 @@ AssertionResult CmpHelperFloatingPointEQ(const char* lhs_expression,
rhs_ss << std::setprecision(std::numeric_limits<RawType>::digits10 + 2)
<< rhs_value;
return EqFailure(lhs_expression,
rhs_expression,
StringStreamToString(&lhs_ss),
StringStreamToString(&rhs_ss),
return EqFailure(lhs_expression, rhs_expression,
StringStreamToString(&lhs_ss), StringStreamToString(&rhs_ss),
false);
}
@ -1582,8 +1565,7 @@ AssertionResult CmpHelperFloatingPointEQ(const char* lhs_expression,
GTEST_API_ AssertionResult DoubleNearPredFormat(const char* expr1,
const char* expr2,
const char* abs_error_expr,
double val1,
double val2,
double val1, double val2,
double abs_error);
// INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE.
@ -1591,9 +1573,7 @@ GTEST_API_ AssertionResult DoubleNearPredFormat(const char* expr1,
class GTEST_API_ AssertHelper {
public:
// Constructor.
AssertHelper(TestPartResult::Type type,
const char* file,
int line,
AssertHelper(TestPartResult::Type type, const char* file, int line,
const char* message);
~AssertHelper();
@ -1607,9 +1587,7 @@ class GTEST_API_ AssertHelper {
// re-using stack space even for temporary variables, so every EXPECT_EQ
// reserves stack space for another AssertHelper.
struct AssertHelperData {
AssertHelperData(TestPartResult::Type t,
const char* srcfile,
int line_num,
AssertHelperData(TestPartResult::Type t, const char* srcfile, int line_num,
const char* msg)
: type(t), file(srcfile), line(line_num), message(msg) {}
@ -1681,15 +1659,14 @@ class WithParamInterface {
private:
// Sets parameter value. The caller is responsible for making sure the value
// remains alive and unchanged throughout the current test.
static void SetParam(const ParamType* parameter) {
parameter_ = parameter;
}
static void SetParam(const ParamType* parameter) { parameter_ = parameter; }
// Static value used for accessing parameter during a test lifetime.
static const ParamType* parameter_;
// TestClass must be a subclass of WithParamInterface<T> and Test.
template <class TestClass> friend class internal::ParameterizedTestFactory;
template <class TestClass>
friend class internal::ParameterizedTestFactory;
};
template <typename T>
@ -1699,8 +1676,7 @@ const T* WithParamInterface<T>::parameter_ = nullptr;
// WithParamInterface, and can just inherit from ::testing::TestWithParam.
template <typename T>
class TestWithParam : public Test, public WithParamInterface<T> {
};
class TestWithParam : public Test, public WithParamInterface<T> {};
// Macros for indicating success/failure in test code.
@ -1790,8 +1766,7 @@ class TestWithParam : public Test, public WithParamInterface<T> {
GTEST_TEST_BOOLEAN_(!(condition), #condition, true, false, \
GTEST_NONFATAL_FAILURE_)
#define GTEST_ASSERT_TRUE(condition) \
GTEST_TEST_BOOLEAN_(condition, #condition, false, true, \
GTEST_FATAL_FAILURE_)
GTEST_TEST_BOOLEAN_(condition, #condition, false, true, GTEST_FATAL_FAILURE_)
#define GTEST_ASSERT_FALSE(condition) \
GTEST_TEST_BOOLEAN_(!(condition), #condition, true, false, \
GTEST_FATAL_FAILURE_)
@ -1979,12 +1954,12 @@ class TestWithParam : public Test, public WithParamInterface<T> {
val1, val2)
#define EXPECT_NEAR(val1, val2, abs_error) \
EXPECT_PRED_FORMAT3(::testing::internal::DoubleNearPredFormat, \
val1, val2, abs_error)
EXPECT_PRED_FORMAT3(::testing::internal::DoubleNearPredFormat, val1, val2, \
abs_error)
#define ASSERT_NEAR(val1, val2, abs_error) \
ASSERT_PRED_FORMAT3(::testing::internal::DoubleNearPredFormat, \
val1, val2, abs_error)
ASSERT_PRED_FORMAT3(::testing::internal::DoubleNearPredFormat, val1, val2, \
abs_error)
// These predicate format functions work on floating-point values, and
// can be used in {ASSERT|EXPECT}_PRED_FORMAT2*(), e.g.
@ -1998,7 +1973,6 @@ GTEST_API_ AssertionResult FloatLE(const char* expr1, const char* expr2,
GTEST_API_ AssertionResult DoubleLE(const char* expr1, const char* expr2,
double val1, double val2);
#if GTEST_OS_WINDOWS
// Macros that test for HRESULT failure and success, these are only useful
@ -2307,9 +2281,7 @@ TestInfo* RegisterTest(const char* test_suite_name, const char* test_name,
// namespace and has an all-caps name.
int RUN_ALL_TESTS() GTEST_MUST_USE_RESULT_;
inline int RUN_ALL_TESTS() {
return ::testing::UnitTest::GetInstance()->Run();
}
inline int RUN_ALL_TESTS() { return ::testing::UnitTest::GetInstance()->Run(); }
GTEST_DISABLE_MSC_WARNINGS_POP_() // 4251

View File

@ -81,15 +81,11 @@ namespace testing {
else \
on_failure(gtest_ar.failure_message())
// Helper function for implementing {EXPECT|ASSERT}_PRED1. Don't use
// this in your code.
template <typename Pred,
typename T1>
AssertionResult AssertPred1Helper(const char* pred_text,
const char* e1,
Pred pred,
const T1& v1) {
template <typename Pred, typename T1>
AssertionResult AssertPred1Helper(const char* pred_text, const char* e1,
Pred pred, const T1& v1) {
if (pred(v1)) return AssertionSuccess();
return AssertionFailure()
@ -101,39 +97,26 @@ AssertionResult AssertPred1Helper(const char* pred_text,
// Internal macro for implementing {EXPECT|ASSERT}_PRED_FORMAT1.
// Don't use this in your code.
#define GTEST_PRED_FORMAT1_(pred_format, v1, on_failure) \
GTEST_ASSERT_(pred_format(#v1, v1), \
on_failure)
GTEST_ASSERT_(pred_format(#v1, v1), on_failure)
// Internal macro for implementing {EXPECT|ASSERT}_PRED1. Don't use
// this in your code.
#define GTEST_PRED1_(pred, v1, on_failure) \
GTEST_ASSERT_(::testing::AssertPred1Helper(#pred, \
#v1, \
pred, \
v1), on_failure)
GTEST_ASSERT_(::testing::AssertPred1Helper(#pred, #v1, pred, v1), on_failure)
// Unary predicate assertion macros.
#define EXPECT_PRED_FORMAT1(pred_format, v1) \
GTEST_PRED_FORMAT1_(pred_format, v1, GTEST_NONFATAL_FAILURE_)
#define EXPECT_PRED1(pred, v1) \
GTEST_PRED1_(pred, v1, GTEST_NONFATAL_FAILURE_)
#define EXPECT_PRED1(pred, v1) GTEST_PRED1_(pred, v1, GTEST_NONFATAL_FAILURE_)
#define ASSERT_PRED_FORMAT1(pred_format, v1) \
GTEST_PRED_FORMAT1_(pred_format, v1, GTEST_FATAL_FAILURE_)
#define ASSERT_PRED1(pred, v1) \
GTEST_PRED1_(pred, v1, GTEST_FATAL_FAILURE_)
#define ASSERT_PRED1(pred, v1) GTEST_PRED1_(pred, v1, GTEST_FATAL_FAILURE_)
// Helper function for implementing {EXPECT|ASSERT}_PRED2. Don't use
// this in your code.
template <typename Pred,
typename T1,
typename T2>
AssertionResult AssertPred2Helper(const char* pred_text,
const char* e1,
const char* e2,
Pred pred,
const T1& v1,
template <typename Pred, typename T1, typename T2>
AssertionResult AssertPred2Helper(const char* pred_text, const char* e1,
const char* e2, Pred pred, const T1& v1,
const T2& v2) {
if (pred(v1, v2)) return AssertionSuccess();
@ -148,18 +131,13 @@ AssertionResult AssertPred2Helper(const char* pred_text,
// Internal macro for implementing {EXPECT|ASSERT}_PRED_FORMAT2.
// Don't use this in your code.
#define GTEST_PRED_FORMAT2_(pred_format, v1, v2, on_failure) \
GTEST_ASSERT_(pred_format(#v1, #v2, v1, v2), \
on_failure)
GTEST_ASSERT_(pred_format(#v1, #v2, v1, v2), on_failure)
// Internal macro for implementing {EXPECT|ASSERT}_PRED2. Don't use
// this in your code.
#define GTEST_PRED2_(pred, v1, v2, on_failure) \
GTEST_ASSERT_(::testing::AssertPred2Helper(#pred, \
#v1, \
#v2, \
pred, \
v1, \
v2), on_failure)
GTEST_ASSERT_(::testing::AssertPred2Helper(#pred, #v1, #v2, pred, v1, v2), \
on_failure)
// Binary predicate assertion macros.
#define EXPECT_PRED_FORMAT2(pred_format, v1, v2) \
@ -171,22 +149,12 @@ AssertionResult AssertPred2Helper(const char* pred_text,
#define ASSERT_PRED2(pred, v1, v2) \
GTEST_PRED2_(pred, v1, v2, GTEST_FATAL_FAILURE_)
// Helper function for implementing {EXPECT|ASSERT}_PRED3. Don't use
// this in your code.
template <typename Pred,
typename T1,
typename T2,
typename T3>
AssertionResult AssertPred3Helper(const char* pred_text,
const char* e1,
const char* e2,
const char* e3,
Pred pred,
const T1& v1,
const T2& v2,
const T3& v3) {
template <typename Pred, typename T1, typename T2, typename T3>
AssertionResult AssertPred3Helper(const char* pred_text, const char* e1,
const char* e2, const char* e3, Pred pred,
const T1& v1, const T2& v2, const T3& v3) {
if (pred(v1, v2, v3)) return AssertionSuccess();
return AssertionFailure()
@ -201,20 +169,14 @@ AssertionResult AssertPred3Helper(const char* pred_text,
// Internal macro for implementing {EXPECT|ASSERT}_PRED_FORMAT3.
// Don't use this in your code.
#define GTEST_PRED_FORMAT3_(pred_format, v1, v2, v3, on_failure) \
GTEST_ASSERT_(pred_format(#v1, #v2, #v3, v1, v2, v3), \
on_failure)
GTEST_ASSERT_(pred_format(#v1, #v2, #v3, v1, v2, v3), on_failure)
// Internal macro for implementing {EXPECT|ASSERT}_PRED3. Don't use
// this in your code.
#define GTEST_PRED3_(pred, v1, v2, v3, on_failure) \
GTEST_ASSERT_(::testing::AssertPred3Helper(#pred, \
#v1, \
#v2, \
#v3, \
pred, \
v1, \
v2, \
v3), on_failure)
GTEST_ASSERT_( \
::testing::AssertPred3Helper(#pred, #v1, #v2, #v3, pred, v1, v2, v3), \
on_failure)
// Ternary predicate assertion macros.
#define EXPECT_PRED_FORMAT3(pred_format, v1, v2, v3) \
@ -226,25 +188,13 @@ AssertionResult AssertPred3Helper(const char* pred_text,
#define ASSERT_PRED3(pred, v1, v2, v3) \
GTEST_PRED3_(pred, v1, v2, v3, GTEST_FATAL_FAILURE_)
// Helper function for implementing {EXPECT|ASSERT}_PRED4. Don't use
// this in your code.
template <typename Pred,
typename T1,
typename T2,
typename T3,
typename T4>
AssertionResult AssertPred4Helper(const char* pred_text,
const char* e1,
const char* e2,
const char* e3,
const char* e4,
Pred pred,
const T1& v1,
const T2& v2,
const T3& v3,
const T4& v4) {
template <typename Pred, typename T1, typename T2, typename T3, typename T4>
AssertionResult AssertPred4Helper(const char* pred_text, const char* e1,
const char* e2, const char* e3,
const char* e4, Pred pred, const T1& v1,
const T2& v2, const T3& v3, const T4& v4) {
if (pred(v1, v2, v3, v4)) return AssertionSuccess();
return AssertionFailure()
@ -260,22 +210,14 @@ AssertionResult AssertPred4Helper(const char* pred_text,
// Internal macro for implementing {EXPECT|ASSERT}_PRED_FORMAT4.
// Don't use this in your code.
#define GTEST_PRED_FORMAT4_(pred_format, v1, v2, v3, v4, on_failure) \
GTEST_ASSERT_(pred_format(#v1, #v2, #v3, #v4, v1, v2, v3, v4), \
on_failure)
GTEST_ASSERT_(pred_format(#v1, #v2, #v3, #v4, v1, v2, v3, v4), on_failure)
// Internal macro for implementing {EXPECT|ASSERT}_PRED4. Don't use
// this in your code.
#define GTEST_PRED4_(pred, v1, v2, v3, v4, on_failure) \
GTEST_ASSERT_(::testing::AssertPred4Helper(#pred, \
#v1, \
#v2, \
#v3, \
#v4, \
pred, \
v1, \
v2, \
v3, \
v4), on_failure)
GTEST_ASSERT_(::testing::AssertPred4Helper(#pred, #v1, #v2, #v3, #v4, pred, \
v1, v2, v3, v4), \
on_failure)
// 4-ary predicate assertion macros.
#define EXPECT_PRED_FORMAT4(pred_format, v1, v2, v3, v4) \
@ -287,28 +229,15 @@ AssertionResult AssertPred4Helper(const char* pred_text,
#define ASSERT_PRED4(pred, v1, v2, v3, v4) \
GTEST_PRED4_(pred, v1, v2, v3, v4, GTEST_FATAL_FAILURE_)
// Helper function for implementing {EXPECT|ASSERT}_PRED5. Don't use
// this in your code.
template <typename Pred,
typename T1,
typename T2,
typename T3,
typename T4,
template <typename Pred, typename T1, typename T2, typename T3, typename T4,
typename T5>
AssertionResult AssertPred5Helper(const char* pred_text,
const char* e1,
const char* e2,
const char* e3,
const char* e4,
const char* e5,
Pred pred,
const T1& v1,
const T2& v2,
const T3& v3,
const T4& v4,
const T5& v5) {
AssertionResult AssertPred5Helper(const char* pred_text, const char* e1,
const char* e2, const char* e3,
const char* e4, const char* e5, Pred pred,
const T1& v1, const T2& v2, const T3& v3,
const T4& v4, const T5& v5) {
if (pred(v1, v2, v3, v4, v5)) return AssertionSuccess();
return AssertionFailure()
@ -331,18 +260,9 @@ AssertionResult AssertPred5Helper(const char* pred_text,
// Internal macro for implementing {EXPECT|ASSERT}_PRED5. Don't use
// this in your code.
#define GTEST_PRED5_(pred, v1, v2, v3, v4, v5, on_failure) \
GTEST_ASSERT_(::testing::AssertPred5Helper(#pred, \
#v1, \
#v2, \
#v3, \
#v4, \
#v5, \
pred, \
v1, \
v2, \
v3, \
v4, \
v5), on_failure)
GTEST_ASSERT_(::testing::AssertPred5Helper(#pred, #v1, #v2, #v3, #v4, #v5, \
pred, v1, v2, v3, v4, v5), \
on_failure)
// 5-ary predicate assertion macros.
#define EXPECT_PRED_FORMAT5(pred_format, v1, v2, v3, v4, v5) \
@ -354,8 +274,6 @@ AssertionResult AssertPred5Helper(const char* pred_text,
#define ASSERT_PRED5(pred, v1, v2, v3, v4, v5) \
GTEST_PRED5_(pred, v1, v2, v3, v4, v5, GTEST_FATAL_FAILURE_)
} // namespace testing
#endif // GOOGLETEST_INCLUDE_GTEST_GTEST_PRED_IMPL_H_

View File

@ -39,12 +39,13 @@
#ifndef GOOGLETEST_INCLUDE_GTEST_INTERNAL_GTEST_DEATH_TEST_INTERNAL_H_
#define GOOGLETEST_INCLUDE_GTEST_INTERNAL_GTEST_DEATH_TEST_INTERNAL_H_
#include <stdio.h>
#include <memory>
#include "gtest/gtest-matchers.h"
#include "gtest/internal/gtest-internal.h"
#include <stdio.h>
#include <memory>
GTEST_DECLARE_string_(internal_run_death_test);
namespace testing {
@ -93,6 +94,7 @@ class GTEST_API_ DeathTest {
public:
explicit ReturnSentinel(DeathTest* test) : test_(test) {}
~ReturnSentinel() { test_->Abort(TEST_ENCOUNTERED_RETURN_STATEMENT); }
private:
DeathTest* const test_;
GTEST_DISALLOW_COPY_AND_ASSIGN_(ReturnSentinel);
@ -266,16 +268,12 @@ inline Matcher<const ::std::string&> MakeDeathTestMatcher(
// RUN_ALL_TESTS was called.
class InternalRunDeathTestFlag {
public:
InternalRunDeathTestFlag(const std::string& a_file,
int a_line,
int an_index,
InternalRunDeathTestFlag(const std::string& a_file, int a_line, int an_index,
int a_write_fd)
: file_(a_file), line_(a_line), index_(an_index),
write_fd_(a_write_fd) {}
: file_(a_file), line_(a_line), index_(an_index), write_fd_(a_write_fd) {}
~InternalRunDeathTestFlag() {
if (write_fd_ >= 0)
posix::Close(write_fd_);
if (write_fd_ >= 0) posix::Close(write_fd_);
}
const std::string& file() const { return file_; }

View File

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

View File

@ -55,6 +55,7 @@
#include <ctype.h>
#include <float.h>
#include <string.h>
#include <cstdint>
#include <iomanip>
#include <limits>
@ -123,6 +124,7 @@ GTEST_API_ extern const char kStackTraceMarker[];
// An IgnoredValue object can be implicitly constructed from ANY value.
class IgnoredValue {
struct Sink {};
public:
// This constructor template allows any value to be implicitly
// converted to IgnoredValue. The object has no data member and
@ -138,13 +140,13 @@ class IgnoredValue {
};
// Appends the user-supplied message to the Google-Test-generated message.
GTEST_API_ std::string AppendUserMessage(
const std::string& gtest_msg, const Message& user_msg);
GTEST_API_ std::string AppendUserMessage(const std::string& gtest_msg,
const Message& user_msg);
#if GTEST_HAS_EXCEPTIONS
GTEST_DISABLE_MSC_WARNINGS_PUSH_(4275 \
/* an exported class was derived from a class that was not exported */)
GTEST_DISABLE_MSC_WARNINGS_PUSH_(
4275 /* an exported class was derived from a class that was not exported */)
// This exception is thrown by (and only by) a failed Google Test
// assertion when GTEST_FLAG(throw_on_failure) is true (if exceptions
@ -214,10 +216,8 @@ GTEST_API_ AssertionResult EqFailure(const char* expected_expression,
// Constructs a failure message for Boolean assertions such as EXPECT_TRUE.
GTEST_API_ std::string GetBoolAssertionFailureMessage(
const AssertionResult& assertion_result,
const char* expression_text,
const char* actual_predicate_value,
const char* expected_predicate_value);
const AssertionResult& assertion_result, const char* expression_text,
const char* actual_predicate_value, const char* expected_predicate_value);
// This template class represents an IEEE floating-point number
// (either single-precision or double-precision, depending on the
@ -271,8 +271,8 @@ class FloatingPoint {
static const Bits kSignBitMask = static_cast<Bits>(1) << (kBitCount - 1);
// The mask for the fraction bits.
static const Bits kFractionBitMask =
~static_cast<Bits>(0) >> (kExponentBitCount + 1);
static const Bits kFractionBitMask = ~static_cast<Bits>(0) >>
(kExponentBitCount + 1);
// The mask for the exponent bits.
static const Bits kExponentBitMask = ~(kSignBitMask | kFractionBitMask);
@ -311,9 +311,7 @@ class FloatingPoint {
}
// Returns the floating-point number that represent positive infinity.
static RawType Infinity() {
return ReinterpretBits(kExponentBitMask);
}
static RawType Infinity() { return ReinterpretBits(kExponentBitMask); }
// Returns the maximum representable finite floating-point number.
static RawType Max();
@ -350,8 +348,8 @@ class FloatingPoint {
// a NAN must return false.
if (is_nan() || rhs.is_nan()) return false;
return DistanceBetweenSignAndMagnitudeNumbers(u_.bits_, rhs.u_.bits_)
<= kMaxUlps;
return DistanceBetweenSignAndMagnitudeNumbers(u_.bits_, rhs.u_.bits_) <=
kMaxUlps;
}
private:
@ -401,9 +399,13 @@ class FloatingPoint {
// We cannot use std::numeric_limits<T>::max() as it clashes with the max()
// macro defined by <windows.h>.
template <>
inline float FloatingPoint<float>::Max() { return FLT_MAX; }
inline float FloatingPoint<float>::Max() {
return FLT_MAX;
}
template <>
inline double FloatingPoint<double>::Max() { return DBL_MAX; }
inline double FloatingPoint<double>::Max() {
return DBL_MAX;
}
// Typedefs the instances of the FloatingPoint template class that we
// care to use.
@ -656,7 +658,8 @@ inline const char* SkipComma(const char* str) {
if (comma == nullptr) {
return nullptr;
}
while (IsSpace(*(++comma))) {}
while (IsSpace(*(++comma))) {
}
return comma;
}
@ -783,13 +786,13 @@ class TypeParameterizedTestSuite {
const std::vector<std::string>& type_names =
GenerateNames<DefaultNameGenerator, Types>()) {
RegisterTypeParameterizedTestSuiteInstantiation(case_name);
std::string test_name = StripTrailingSpaces(
GetPrefixUntilComma(test_names));
std::string test_name =
StripTrailingSpaces(GetPrefixUntilComma(test_names));
if (!state->TestExists(test_name)) {
fprintf(stderr, "Failed to get code location for test %s.%s at %s.",
case_name, test_name.c_str(),
FormatFileLocation(code_location.file.c_str(),
code_location.line).c_str());
FormatFileLocation(code_location.file.c_str(), code_location.line)
.c_str());
fflush(stderr);
posix::Abort();
}
@ -833,8 +836,8 @@ class TypeParameterizedTestSuite<Fixture, internal::None, Types> {
// For example, if Foo() calls Bar(), which in turn calls
// GetCurrentOsStackTraceExceptTop(..., 1), Foo() will be included in
// the trace but Bar() and GetCurrentOsStackTraceExceptTop() won't.
GTEST_API_ std::string GetCurrentOsStackTraceExceptTop(
UnitTest* unit_test, int skip_count);
GTEST_API_ std::string GetCurrentOsStackTraceExceptTop(UnitTest* unit_test,
int skip_count);
// Helpers for suppressing warnings on unreachable code or constant
// condition.
@ -956,7 +959,9 @@ IsContainer IsContainerTest(int /* dummy */) {
typedef char IsNotContainer;
template <class C>
IsNotContainer IsContainerTest(long /* dummy */) { return '\0'; }
IsNotContainer IsContainerTest(long /* dummy */) {
return '\0';
}
// Trait to detect whether a type T is a hash table.
// The heuristic used is that the type contains an inner type `hasher` and does
@ -1019,7 +1024,9 @@ bool ArrayEq(const T* lhs, size_t size, const U* rhs);
// This generic version is used when k is 0.
template <typename T, typename U>
inline bool ArrayEq(const T& lhs, const U& rhs) { return lhs == rhs; }
inline bool ArrayEq(const T& lhs, const U& rhs) {
return lhs == rhs;
}
// This overload is used when k >= 1.
template <typename T, typename U, size_t N>
@ -1033,8 +1040,7 @@ inline bool ArrayEq(const T(&lhs)[N], const U(&rhs)[N]) {
template <typename T, typename U>
bool ArrayEq(const T* lhs, size_t size, const U* rhs) {
for (size_t i = 0; i != size; i++) {
if (!internal::ArrayEq(lhs[i], rhs[i]))
return false;
if (!internal::ArrayEq(lhs[i], rhs[i])) return false;
}
return true;
}
@ -1044,8 +1050,7 @@ bool ArrayEq(const T* lhs, size_t size, const U* rhs) {
template <typename Iter, typename Element>
Iter ArrayAwareFind(Iter begin, Iter end, const Element& elem) {
for (Iter it = begin; it != end; ++it) {
if (internal::ArrayEq(*it, elem))
return it;
if (internal::ArrayEq(*it, elem)) return it;
}
return end;
}
@ -1059,7 +1064,9 @@ void CopyArray(const T* from, size_t size, U* to);
// This generic version is used when k is 0.
template <typename T, typename U>
inline void CopyArray(const T& from, U* to) { *to = from; }
inline void CopyArray(const T& from, U* to) {
*to = from;
}
// This overload is used when k >= 1.
template <typename T, typename U, size_t N>
@ -1116,8 +1123,7 @@ class NativeArray {
}
~NativeArray() {
if (clone_ != &NativeArray::InitRef)
delete[] array_;
if (clone_ != &NativeArray::InitRef) delete[] array_;
}
// STL-style container methods.
@ -1125,8 +1131,7 @@ class NativeArray {
const_iterator begin() const { return array_; }
const_iterator end() const { return array_ + size_; }
bool operator==(const NativeArray& rhs) const {
return size() == rhs.size() &&
ArrayEq(begin(), size(), rhs.begin());
return size() == rhs.size() && ArrayEq(begin(), size(), rhs.begin());
}
private:
@ -1338,8 +1343,8 @@ struct tuple_size<testing::internal::FlatTuple<Ts...>>
} // namespace std
#define GTEST_MESSAGE_AT_(file, line, message, result_type) \
::testing::internal::AssertHelper(result_type, file, line, message) \
= ::testing::Message()
::testing::internal::AssertHelper(result_type, file, line, message) = \
::testing::Message()
#define GTEST_MESSAGE_(message, result_type) \
GTEST_MESSAGE_AT_(__FILE__, __LINE__, message, result_type)
@ -1472,9 +1477,11 @@ class NeverThrown {
goto GTEST_CONCAT_TOKEN_(gtest_label_testnothrow_, __LINE__); \
} \
} else \
GTEST_CONCAT_TOKEN_(gtest_label_testnothrow_, __LINE__): \
fail(("Expected: " #statement " doesn't throw an exception.\n" \
" Actual: " + gtest_msg.value).c_str())
GTEST_CONCAT_TOKEN_(gtest_label_testnothrow_, __LINE__) \
: fail(("Expected: " #statement " doesn't throw an exception.\n" \
" Actual: " + \
gtest_msg.value) \
.c_str())
#define GTEST_TEST_ANY_THROW_(statement, fail) \
GTEST_AMBIGUOUS_ELSE_BLOCKER_ \
@ -1482,19 +1489,18 @@ class NeverThrown {
bool gtest_caught_any = false; \
try { \
GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement); \
} \
catch (...) { \
} catch (...) { \
gtest_caught_any = true; \
} \
if (!gtest_caught_any) { \
goto GTEST_CONCAT_TOKEN_(gtest_label_testanythrow_, __LINE__); \
} \
} else \
GTEST_CONCAT_TOKEN_(gtest_label_testanythrow_, __LINE__): \
fail("Expected: " #statement " throws an exception.\n" \
GTEST_CONCAT_TOKEN_(gtest_label_testanythrow_, __LINE__) \
: fail("Expected: " #statement \
" throws an exception.\n" \
" Actual: it doesn't.")
// Implements Boolean test assertions such as EXPECT_TRUE. expression can be
// either a boolean expression or an AssertionResult. text is a textual
// representation of expression as it was passed into the EXPECT_TRUE.
@ -1505,7 +1511,8 @@ class NeverThrown {
; \
else \
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) \
GTEST_AMBIGUOUS_ELSE_BLOCKER_ \
@ -1516,8 +1523,9 @@ class NeverThrown {
goto GTEST_CONCAT_TOKEN_(gtest_label_testnofatal_, __LINE__); \
} \
} else \
GTEST_CONCAT_TOKEN_(gtest_label_testnofatal_, __LINE__): \
fail("Expected: " #statement " doesn't generate new fatal " \
GTEST_CONCAT_TOKEN_(gtest_label_testnofatal_, __LINE__) \
: fail("Expected: " #statement \
" doesn't generate new fatal " \
"failures in the current thread.\n" \
" Actual: it does.")

View File

@ -47,19 +47,18 @@
#include <utility>
#include <vector>
#include "gtest/internal/gtest-internal.h"
#include "gtest/internal/gtest-port.h"
#include "gtest/gtest-printers.h"
#include "gtest/gtest-test-part.h"
#include "gtest/internal/gtest-internal.h"
#include "gtest/internal/gtest-port.h"
namespace testing {
// Input to a parameterized test name generator, describing a test parameter.
// Consists of the parameter value and the integer parameter index.
template <class ParamType>
struct TestParamInfo {
TestParamInfo(const ParamType& a_param, size_t an_index) :
param(a_param),
index(an_index) {}
TestParamInfo(const ParamType& a_param, size_t an_index)
: param(a_param), index(an_index) {}
ParamType param;
size_t index;
};
@ -85,8 +84,10 @@ namespace internal {
GTEST_API_ void ReportInvalidTestSuiteType(const char* test_suite_name,
CodeLocation code_location);
template <typename> class ParamGeneratorInterface;
template <typename> class ParamGenerator;
template <typename>
class ParamGeneratorInterface;
template <typename>
class ParamGenerator;
// Interface for iterating over elements provided by an implementation
// of ParamGeneratorInterface<T>.
@ -130,8 +131,7 @@ class ParamIterator {
// ParamIterator assumes ownership of the impl_ pointer.
ParamIterator(const ParamIterator& other) : impl_(other.impl_->Clone()) {}
ParamIterator& operator=(const ParamIterator& other) {
if (this != &other)
impl_.reset(other.impl_->Clone());
if (this != &other) impl_.reset(other.impl_->Clone());
return *this;
}
@ -208,8 +208,10 @@ template <typename T, typename IncrementT>
class RangeGenerator : public ParamGeneratorInterface<T> {
public:
RangeGenerator(T begin, T end, IncrementT step)
: begin_(begin), end_(end),
step_(step), end_index_(CalculateEndIndex(begin, end, step)) {}
: begin_(begin),
end_(end),
step_(step),
end_index_(CalculateEndIndex(begin, end, step)) {}
~RangeGenerator() override {}
ParamIteratorInterface<T>* Begin() const override {
@ -252,7 +254,9 @@ class RangeGenerator : public ParamGeneratorInterface<T> {
private:
Iterator(const Iterator& other)
: ParamIteratorInterface<T>(),
base_(other.base_), value_(other.value_), index_(other.index_),
base_(other.base_),
value_(other.value_),
index_(other.index_),
step_(other.step_) {}
// No implementation - assignment is unsupported.
@ -264,12 +268,10 @@ class RangeGenerator : public ParamGeneratorInterface<T> {
const IncrementT step_;
}; // class RangeGenerator::Iterator
static int CalculateEndIndex(const T& begin,
const T& end,
static int CalculateEndIndex(const T& begin, const T& end,
const IncrementT& step) {
int end_index = 0;
for (T i = begin; i < end; i = static_cast<T>(i + step))
end_index++;
for (T i = begin; i < end; i = static_cast<T>(i + step)) end_index++;
return end_index;
}
@ -284,7 +286,6 @@ class RangeGenerator : public ParamGeneratorInterface<T> {
const int end_index_;
}; // class RangeGenerator
// Generates values from a pair of STL-style iterators. Used in the
// ValuesIn() function. The elements are copied from the source range
// since the source can be located on the stack, and the generator
@ -395,8 +396,8 @@ template <class TestClass>
class ParameterizedTestFactory : public TestFactoryBase {
public:
typedef typename TestClass::ParamType ParamType;
explicit ParameterizedTestFactory(ParamType parameter) :
parameter_(parameter) {}
explicit ParameterizedTestFactory(ParamType parameter)
: parameter_(parameter) {}
Test* CreateTest() override {
TestClass::SetParam(&parameter_);
return new TestClass();
@ -548,8 +549,8 @@ class ParameterizedTestSuiteInfo : public ParameterizedTestSuiteInfoBase {
test_it != tests_.end(); ++test_it) {
std::shared_ptr<TestInfo> test_info = *test_it;
for (typename InstantiationContainer::iterator gen_it =
instantiations_.begin(); gen_it != instantiations_.end();
++gen_it) {
instantiations_.begin();
gen_it != instantiations_.end(); ++gen_it) {
const std::string& instantiation_name = gen_it->name;
ParamGenerator<ParamType> generator((*gen_it->generator)());
ParamNameGeneratorFunc* name_func = gen_it->name_func;
@ -570,17 +571,16 @@ class ParameterizedTestSuiteInfo : public ParameterizedTestSuiteInfoBase {
Message test_name_stream;
std::string param_name = name_func(
TestParamInfo<ParamType>(*param_it, i));
std::string param_name =
name_func(TestParamInfo<ParamType>(*param_it, i));
GTEST_CHECK_(IsValidParamName(param_name))
<< "Parameterized test name '" << param_name
<< "' is invalid, in " << file
<< " line " << line << std::endl;
<< "' is invalid, in " << file << " line " << line << std::endl;
GTEST_CHECK_(test_param_names.count(param_name) == 0)
<< "Duplicate parameterized test name '" << param_name
<< "', in " << file << " line " << line << std::endl;
<< "Duplicate parameterized test name '" << param_name << "', in "
<< file << " line " << line << std::endl;
test_param_names.insert(param_name);
@ -631,8 +631,7 @@ class ParameterizedTestSuiteInfo : public ParameterizedTestSuiteInfoBase {
struct InstantiationInfo {
InstantiationInfo(const std::string& name_in,
GeneratorCreationFunc* generator_in,
ParamNameGeneratorFunc* name_func_in,
const char* file_in,
ParamNameGeneratorFunc* name_func_in, const char* file_in,
int line_in)
: name(name_in),
generator(generator_in),
@ -650,13 +649,11 @@ class ParameterizedTestSuiteInfo : public ParameterizedTestSuiteInfoBase {
static bool IsValidParamName(const std::string& name) {
// Check for empty string
if (name.empty())
return false;
if (name.empty()) return false;
// Check for invalid characters
for (std::string::size_type index = 0; index < name.size(); ++index) {
if (!IsAlNum(name[index]) && name[index] != '_')
return false;
if (!IsAlNum(name[index]) && name[index] != '_') return false;
}
return true;
@ -837,7 +834,8 @@ class CartesianProductGenerator
: public ParamIteratorInterface<ParamType> {
public:
IteratorImpl(const ParamGeneratorInterface<ParamType>* base,
const std::tuple<ParamGenerator<T>...>& generators, bool is_end)
const std::tuple<ParamGenerator<T>...>& generators,
bool is_end)
: base_(base),
begin_(std::get<I>(generators).begin()...),
end_(std::get<I>(generators).end()...),

View File

@ -275,8 +275,8 @@
#include <vector>
#ifndef _WIN32_WCE
# include <sys/types.h>
#include <sys/stat.h>
#include <sys/types.h>
#endif // !_WIN32_WCE
#if defined __APPLE__
@ -314,10 +314,8 @@
// GTEST_DISABLE_MSC_WARNINGS_POP_()
#if defined(_MSC_VER)
#define GTEST_DISABLE_MSC_WARNINGS_PUSH_(warnings) \
__pragma(warning(push)) \
__pragma(warning(disable: warnings))
# define GTEST_DISABLE_MSC_WARNINGS_POP_() \
__pragma(warning(pop))
__pragma(warning(push)) __pragma(warning(disable : warnings))
#define GTEST_DISABLE_MSC_WARNINGS_POP_() __pragma(warning(pop))
#else
// Not all compilers are MSVC
#define GTEST_DISABLE_MSC_WARNINGS_PUSH_(warnings)
@ -331,13 +329,11 @@
_Pragma("clang diagnostic push") \
_Pragma("clang diagnostic ignored \"-Wdeprecated-declarations\"") \
_Pragma("clang diagnostic ignored \"-Wdeprecated-implementations\"")
#define GTEST_DISABLE_MSC_DEPRECATED_POP_() \
_Pragma("clang diagnostic pop")
#define GTEST_DISABLE_MSC_DEPRECATED_POP_() _Pragma("clang diagnostic pop")
#else
#define GTEST_DISABLE_MSC_DEPRECATED_PUSH_() \
GTEST_DISABLE_MSC_WARNINGS_PUSH_(4996)
# define GTEST_DISABLE_MSC_DEPRECATED_POP_() \
GTEST_DISABLE_MSC_WARNINGS_POP_()
#define GTEST_DISABLE_MSC_DEPRECATED_POP_() GTEST_DISABLE_MSC_WARNINGS_POP_()
#endif
// Brings in definitions for functions used in the testing::internal::posix
@ -367,8 +363,8 @@ typedef struct _RTL_CRITICAL_SECTION GTEST_CRITICAL_SECTION;
// This assumes that non-Windows OSes provide unistd.h. For OSes where this
// is not the case, we need to include headers that provide the functions
// mentioned above.
# include <unistd.h>
#include <strings.h>
#include <unistd.h>
#endif // GTEST_OS_WINDOWS
#if GTEST_OS_LINUX_ANDROID
@ -494,8 +490,7 @@ typedef struct _RTL_CRITICAL_SECTION GTEST_CRITICAL_SECTION;
// -frtti -fno-exceptions, the build fails at link time with undefined
// references to __cxa_bad_typeid. Note sure if STL or toolchain bug,
// so disable RTTI when detected.
# if GTEST_OS_LINUX_ANDROID && defined(_STLPORT_MAJOR) && \
!defined(__EXCEPTIONS)
#if GTEST_OS_LINUX_ANDROID && defined(_STLPORT_MAJOR) && !defined(__EXCEPTIONS)
#define GTEST_HAS_RTTI 0
#else
#define GTEST_HAS_RTTI 1
@ -570,8 +565,7 @@ typedef struct _RTL_CRITICAL_SECTION GTEST_CRITICAL_SECTION;
#if GTEST_OS_LINUX_ANDROID
// On Android, clone() became available at different API levels for each 32-bit
// architecture.
# if defined(__LP64__) || \
(defined(__arm__) && __ANDROID_API__ >= 9) || \
#if defined(__LP64__) || (defined(__arm__) && __ANDROID_API__ >= 9) || \
(defined(__mips__) && __ANDROID_API__ >= 12) || \
(defined(__i386__) && __ANDROID_API__ >= 17)
#define GTEST_HAS_CLONE 1
@ -646,7 +640,10 @@ typedef struct _RTL_CRITICAL_SECTION GTEST_CRITICAL_SECTION;
#ifdef __INTEL_COMPILER
#define GTEST_AMBIGUOUS_ELSE_BLOCKER_
#else
# define GTEST_AMBIGUOUS_ELSE_BLOCKER_ switch (0) case 0: default: // NOLINT
#define GTEST_AMBIGUOUS_ELSE_BLOCKER_ \
switch (0) \
case 0: \
default: // NOLINT
#endif
// Use this annotation at the end of a struct/class definition to
@ -678,8 +675,8 @@ typedef struct _RTL_CRITICAL_SECTION GTEST_CRITICAL_SECTION;
// matches the selected implementation. See
// https://sourceforge.net/p/mingw-w64/wiki2/gnu%20printf/.
#define GTEST_ATTRIBUTE_PRINTF_(string_index, first_to_check) \
__attribute__((__format__(__MINGW_PRINTF_FORMAT, string_index, \
first_to_check)))
__attribute__(( \
__format__(__MINGW_PRINTF_FORMAT, string_index, first_to_check)))
#else
#define GTEST_ATTRIBUTE_PRINTF_(string_index, first_to_check) \
__attribute__((__format__(__printf__, string_index, first_to_check)))
@ -723,8 +720,7 @@ typedef struct _RTL_CRITICAL_SECTION GTEST_CRITICAL_SECTION;
// }
#define GTEST_INTENTIONAL_CONST_COND_PUSH_() \
GTEST_DISABLE_MSC_WARNINGS_PUSH_(4127)
# define GTEST_INTENTIONAL_CONST_COND_POP_() \
GTEST_DISABLE_MSC_WARNINGS_POP_()
#define GTEST_INTENTIONAL_CONST_COND_POP_() GTEST_DISABLE_MSC_WARNINGS_POP_()
// Determine whether the compiler supports Microsoft's Structured Exception
// Handling. This is supported by several Windows compilers but generally
@ -816,8 +812,7 @@ typedef struct _RTL_CRITICAL_SECTION GTEST_CRITICAL_SECTION;
// memory when built with MemorySanitizer.
#if defined(__clang__)
#if __has_feature(memory_sanitizer)
# define GTEST_ATTRIBUTE_NO_SANITIZE_MEMORY_ \
__attribute__((no_sanitize_memory))
#define GTEST_ATTRIBUTE_NO_SANITIZE_MEMORY_ __attribute__((no_sanitize_memory))
#else
#define GTEST_ATTRIBUTE_NO_SANITIZE_MEMORY_
#endif // __has_feature(memory_sanitizer)
@ -852,8 +847,7 @@ typedef struct _RTL_CRITICAL_SECTION GTEST_CRITICAL_SECTION;
// A function level attribute to disable ThreadSanitizer instrumentation.
#if defined(__clang__)
#if __has_feature(thread_sanitizer)
# define GTEST_ATTRIBUTE_NO_SANITIZE_THREAD_ \
__attribute__((no_sanitize_thread))
#define GTEST_ATTRIBUTE_NO_SANITIZE_THREAD_ __attribute__((no_sanitize_thread))
#else
#define GTEST_ATTRIBUTE_NO_SANITIZE_THREAD_
#endif // __has_feature(thread_sanitizer)
@ -967,12 +961,7 @@ GTEST_API_ ::std::string FormatCompilerIndependentFileLocation(const char* file,
// LogToStderr() - directs all log messages to stderr.
// FlushInfoLog() - flushes informational log messages.
enum GTestLogSeverity {
GTEST_INFO,
GTEST_WARNING,
GTEST_ERROR,
GTEST_FATAL
};
enum GTestLogSeverity { GTEST_INFO, GTEST_WARNING, GTEST_ERROR, GTEST_FATAL };
// Formats log entry severity, provides a stream object for streaming the
// log message, and terminates the message with a newline when going out of
@ -996,7 +985,8 @@ class GTEST_API_ GTestLog {
#define GTEST_LOG_(severity) \
::testing::internal::GTestLog(::testing::internal::GTEST_##severity, \
__FILE__, __LINE__).GetStream()
__FILE__, __LINE__) \
.GetStream()
inline void LogToStderr() {}
inline void FlushInfoLog() { fflush(nullptr); }
@ -1033,8 +1023,7 @@ inline void FlushInfoLog() { fflush(nullptr); }
// branch.
#define GTEST_CHECK_POSIX_SUCCESS_(posix_call) \
if (const int gtest_error = (posix_call)) \
GTEST_LOG_(FATAL) << #posix_call << "failed with error " \
<< gtest_error
GTEST_LOG_(FATAL) << #posix_call << "failed with error " << gtest_error
// Transforms "T" into "const T&" according to standard reference collapsing
// rules (this is only needed as a backport for C++98 compilers that do not
@ -1048,9 +1037,13 @@ inline void FlushInfoLog() { fflush(nullptr); }
// Note that the non-const reference will not have "const" added. This is
// standard, and necessary so that "T" can always bind to "const T&".
template <typename T>
struct ConstRef { typedef const T& type; };
struct ConstRef {
typedef const T& type;
};
template <typename T>
struct ConstRef<T&> { typedef T& type; };
struct ConstRef<T&> {
typedef T& type;
};
// The argument T must depend on some template parameters.
#define GTEST_REFERENCE_TO_CONST_(T) \
@ -1077,7 +1070,9 @@ struct ConstRef<T&> { typedef T& type; };
// similar functions users may have (e.g., implicit_cast). The internal
// namespace alone is not enough because the function can be found by ADL.
template <typename To>
inline To ImplicitCast_(To x) { return x; }
inline To ImplicitCast_(To x) {
return x;
}
// When you upcast (that is, cast a pointer from type Foo to type
// SuperclassOfFoo), it's fine to use ImplicitCast_<>, since upcasts
@ -1405,8 +1400,7 @@ class GTEST_API_ Mutex {
// "MutexLock l(&mu)". Hence the typedef trick below.
class GTestMutexLock {
public:
explicit GTestMutexLock(Mutex* mutex)
: mutex_(mutex) { mutex_->Lock(); }
explicit GTestMutexLock(Mutex* mutex) : mutex_(mutex) { mutex_->Lock(); }
~GTestMutexLock() { mutex_->Unlock(); }
@ -1483,21 +1477,15 @@ class ThreadWithParam : public ThreadWithParamBase {
typedef void UserThreadFunc(T);
ThreadWithParam(UserThreadFunc* func, T param, Notification* thread_can_start)
: ThreadWithParamBase(new RunnableImpl(func, param), thread_can_start) {
}
: ThreadWithParamBase(new RunnableImpl(func, param), thread_can_start) {}
virtual ~ThreadWithParam() {}
private:
class RunnableImpl : public Runnable {
public:
RunnableImpl(UserThreadFunc* func, T param)
: func_(func),
param_(param) {
}
RunnableImpl(UserThreadFunc* func, T param) : func_(func), param_(param) {}
virtual ~RunnableImpl() {}
virtual void Run() {
func_(param_);
}
virtual void Run() { func_(param_); }
private:
UserThreadFunc* const func_;
@ -1565,10 +1553,10 @@ class ThreadLocal : public ThreadLocalBase {
GTEST_DISALLOW_COPY_AND_ASSIGN_(ValueHolder);
};
T* GetOrCreateValue() const {
return static_cast<ValueHolder*>(
ThreadLocalRegistry::GetValueOnCurrentThread(this))->pointer();
ThreadLocalRegistry::GetValueOnCurrentThread(this))
->pointer();
}
virtual ThreadLocalValueHolderBase* NewValueForCurrentThread() const {
@ -1679,9 +1667,7 @@ class Mutex : public MutexBase {
GTEST_CHECK_POSIX_SUCCESS_(pthread_mutex_init(&mutex_, nullptr));
has_owner_ = false;
}
~Mutex() {
GTEST_CHECK_POSIX_SUCCESS_(pthread_mutex_destroy(&mutex_));
}
~Mutex() { GTEST_CHECK_POSIX_SUCCESS_(pthread_mutex_destroy(&mutex_)); }
private:
GTEST_DISALLOW_COPY_AND_ASSIGN_(Mutex);
@ -1694,8 +1680,7 @@ class Mutex : public MutexBase {
// "MutexLock l(&mu)". Hence the typedef trick below.
class GTestMutexLock {
public:
explicit GTestMutexLock(MutexBase* mutex)
: mutex_(mutex) { mutex_->Lock(); }
explicit GTestMutexLock(MutexBase* mutex) : mutex_(mutex) { mutex_->Lock(); }
~GTestMutexLock() { mutex_->Unlock(); }
@ -1866,6 +1851,7 @@ class GTEST_API_ ThreadLocal {
const T* pointer() const { return &value_; }
const T& get() const { return value_; }
void set(const T& value) { value_ = value; }
private:
T value_;
};
@ -1939,8 +1925,7 @@ inline char ToUpper(char ch) {
inline std::string StripTrailingSpaces(std::string str) {
std::string::iterator it = str.end();
while (it != str.begin() && IsSpace(*--it))
it = str.erase(it);
while (it != str.begin() && IsSpace(*--it)) it = str.erase(it);
return str;
}
@ -1984,9 +1969,7 @@ inline int FileNo(FILE* file) { return reinterpret_cast<int>(_fileno(file)); }
inline int FileNo(FILE* file) { return _fileno(file); }
inline int Stat(const char* path, StatStruct* buf) { return _stat(path, buf); }
inline int RmDir(const char* dir) { return _rmdir(dir); }
inline bool IsDir(const StatStruct& st) {
return (_S_IFDIR & st.st_mode) != 0;
}
inline bool IsDir(const StatStruct& st) { return (_S_IFDIR & st.st_mode) != 0; }
#endif // GTEST_OS_WINDOWS_MOBILE
#elif GTEST_OS_ESP8266
@ -2188,29 +2171,35 @@ using TimeInMillis = int64_t; // Represents time in milliseconds.
#define GTEST_DECLARE_bool_(name) \
namespace testing { \
GTEST_API_ extern bool GTEST_FLAG(name); \
} static_assert(true, "no-op to require trailing semicolon")
} \
static_assert(true, "no-op to require trailing semicolon")
#define GTEST_DECLARE_int32_(name) \
namespace testing { \
GTEST_API_ extern std::int32_t GTEST_FLAG(name); \
} static_assert(true, "no-op to require trailing semicolon")
} \
static_assert(true, "no-op to require trailing semicolon")
#define GTEST_DECLARE_string_(name) \
namespace testing { \
GTEST_API_ extern ::std::string GTEST_FLAG(name); \
} static_assert(true, "no-op to require trailing semicolon")
} \
static_assert(true, "no-op to require trailing semicolon")
// Macros for defining flags.
#define GTEST_DEFINE_bool_(name, default_val, doc) \
namespace testing { \
GTEST_API_ bool GTEST_FLAG(name) = (default_val); \
} static_assert(true, "no-op to require trailing semicolon")
} \
static_assert(true, "no-op to require trailing semicolon")
#define GTEST_DEFINE_int32_(name, default_val, doc) \
namespace testing { \
GTEST_API_ std::int32_t GTEST_FLAG(name) = (default_val); \
} static_assert(true, "no-op to require trailing semicolon")
} \
static_assert(true, "no-op to require trailing semicolon")
#define GTEST_DEFINE_string_(name, default_val, doc) \
namespace testing { \
GTEST_API_ ::std::string GTEST_FLAG(name) = (default_val); \
} static_assert(true, "no-op to require trailing semicolon")
} \
static_assert(true, "no-op to require trailing semicolon")
#endif // !defined(GTEST_DECLARE_bool_)
@ -2373,7 +2362,8 @@ template <typename... T>
using Variant = ::std::variant<T...>;
} // namespace internal
} // namespace testing
// The case where absl is configured NOT to alias std::variant is not supported.
// The case where absl is configured NOT to alias std::variant is not
// supported.
#endif // __has_include(<variant>) && __cplusplus >= 201703L
#endif // __has_include
#endif // GTEST_HAS_ABSL

View File

@ -49,6 +49,7 @@
#endif
#include <string.h>
#include <cstdint>
#include <string>
@ -125,8 +126,7 @@ class GTEST_API_ String {
// Unlike strcasecmp(), this function can handle NULL argument(s).
// A NULL C string is considered different to any non-NULL C string,
// including the empty string.
static bool CaseInsensitiveCStringEquals(const char* lhs,
const char* rhs);
static bool CaseInsensitiveCStringEquals(const char* lhs, const char* rhs);
// Compares two wide C strings, ignoring case. Returns true if and only if
// they have the same content.
@ -145,8 +145,8 @@ class GTEST_API_ String {
// Returns true if and only if the given string ends with the given suffix,
// ignoring case. Any string is considered to end with an empty suffix.
static bool EndsWithCaseInsensitive(
const std::string& str, const std::string& suffix);
static bool EndsWithCaseInsensitive(const std::string& str,
const std::string& suffix);
// Formats an int value as "%02d".
static std::string FormatIntWidth2(int value); // "%02d" for width == 2

View File

@ -103,7 +103,9 @@ std::string GetTypeName() {
// A unique type indicating an empty node
struct None {};
# define GTEST_TEMPLATE_ template <typename T> class
#define GTEST_TEMPLATE_ \
template <typename T> \
class
// The template "selector" struct TemplateSel<Tmpl> is used to
// represent Tmpl, which must be a class template with one type
@ -121,8 +123,7 @@ struct TemplateSel {
};
};
# define GTEST_BIND_(TmplSel, T) \
TmplSel::template Bind<T>::type
#define GTEST_BIND_(TmplSel, T) TmplSel::template Bind<T>::type
template <GTEST_TEMPLATE_ Head_, GTEST_TEMPLATE_... Tail_>
struct Templates {

View File

@ -27,8 +27,6 @@
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// This provides interface PrimeTable that determines whether a number is a
// prime and determines a next prime number. This interface is used
// in Google Test samples demonstrating use of parameterized tests.

View File

@ -26,7 +26,6 @@
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// This sample shows how to use Google Test listener API to implement
// a primitive leak checker.
@ -111,7 +110,8 @@ int main(int argc, char **argv) {
if (argc > 1 && strcmp(argv[1], "--check_for_leaks") == 0)
check_for_leaks = true;
else
printf("%s\n", "Run this program with --check_for_leaks to enable "
printf("%s\n",
"Run this program with --check_for_leaks to enable "
"custom leak checking in the tests.");
// If we are given the --check_for_leaks command line flag, installs the

View File

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

View File

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

View File

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

View File

@ -34,7 +34,6 @@
#include <stddef.h>
// Queue is a simple queue implemented as a singled-linked list.
//
// The element type must support copy constructor.

View File

@ -67,7 +67,6 @@ namespace {
class QueueTestSmpl3 : public testing::Test {
protected: // You should make the members protected s.t. they can be
// accessed from sub-classes.
// virtual void SetUp() will be called before each test is run. You
// should define it if you need to initialize the variables.
// Otherwise, this can be skipped.
@ -85,9 +84,7 @@ class QueueTestSmpl3 : public testing::Test {
// }
// A helper function that some test uses.
static int Double(int n) {
return 2*n;
}
static int Double(int n) { return 2 * n; }
// A helper function for testing Queue::Map().
void MapTester(const Queue<int>* q) {

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -35,8 +35,8 @@
#include <functional>
#include <utility>
#include "gtest/internal/gtest-port.h"
#include "gtest/internal/custom/gtest.h"
#include "gtest/internal/gtest-port.h"
#if GTEST_HAS_DEATH_TEST
@ -165,8 +165,7 @@ bool InDeathTestChild() {
} // namespace internal
// ExitedWithCode constructor.
ExitedWithCode::ExitedWithCode(int exit_code) : exit_code_(exit_code) {
}
ExitedWithCode::ExitedWithCode(int exit_code) : exit_code_(exit_code) {}
// ExitedWithCode function-call operator.
bool ExitedWithCode::operator()(int exit_status) const {
@ -183,8 +182,7 @@ bool ExitedWithCode::operator()(int exit_status) const {
#if !GTEST_OS_WINDOWS && !GTEST_OS_FUCHSIA
// KilledBySignal constructor.
KilledBySignal::KilledBySignal(int signum) : signum_(signum) {
}
KilledBySignal::KilledBySignal(int signum) : signum_(signum) {}
// KilledBySignal function-call operator.
bool KilledBySignal::operator()(int exit_status) const {
@ -310,10 +308,10 @@ static void DeathTestAbort(const std::string& message) {
#define GTEST_DEATH_TEST_CHECK_(expression) \
do { \
if (!::testing::internal::IsTrue(expression)) { \
DeathTestAbort( \
::std::string("CHECK failed: File ") + __FILE__ + ", line " \
+ ::testing::internal::StreamableToString(__LINE__) + ": " \
+ #expression); \
DeathTestAbort(::std::string("CHECK failed: File ") + __FILE__ + \
", line " + \
::testing::internal::StreamableToString(__LINE__) + \
": " + #expression); \
} \
} while (::testing::internal::AlwaysFalse())
@ -331,10 +329,10 @@ static void DeathTestAbort(const std::string& message) {
gtest_retval = (expression); \
} while (gtest_retval == -1 && errno == EINTR); \
if (gtest_retval == -1) { \
DeathTestAbort( \
::std::string("CHECK failed: File ") + __FILE__ + ", line " \
+ ::testing::internal::StreamableToString(__LINE__) + ": " \
+ #expression + " != -1"); \
DeathTestAbort(::std::string("CHECK failed: File ") + __FILE__ + \
", line " + \
::testing::internal::StreamableToString(__LINE__) + \
": " + #expression + " != -1"); \
} \
} while (::testing::internal::AlwaysFalse())
@ -373,7 +371,8 @@ static void FailFromInternalError(int fd) {
DeathTest::DeathTest() {
TestInfo* const info = GetUnitTestImpl()->current_test_info();
if (info == nullptr) {
DeathTestAbort("Cannot run a death test outside of a TEST or "
DeathTestAbort(
"Cannot run a death test outside of a TEST or "
"TEST_F construct");
}
}
@ -503,9 +502,7 @@ void DeathTestImpl::ReadAndInterpretStatusByte() {
set_read_fd(-1);
}
std::string DeathTestImpl::GetErrorLogs() {
return GetCapturedStderr();
}
std::string DeathTestImpl::GetErrorLogs() { return GetCapturedStderr(); }
// Signals that the death test code which should have exited, didn't.
// Should be called only in a death test child process.
@ -515,9 +512,9 @@ void DeathTestImpl::Abort(AbortReason reason) {
// The parent process considers the death test to be a failure if
// it finds any data in our pipe. So, here we write a single flag byte
// to the pipe, then exit.
const char status_ch =
reason == TEST_DID_NOT_DIE ? kDeathTestLived :
reason == TEST_THREW_EXCEPTION ? kDeathTestThrew : kDeathTestReturned;
const char status_ch = reason == TEST_DID_NOT_DIE ? kDeathTestLived
: reason == TEST_THREW_EXCEPTION ? kDeathTestThrew
: kDeathTestReturned;
GTEST_DEATH_TEST_CHECK_SYSCALL_(posix::Write(write_fd(), &status_ch, 1));
// We are leaking the descriptor here because on some platforms (i.e.,
@ -571,8 +568,7 @@ static ::std::string FormatDeathTestOutput(const ::std::string& output) {
// the first failing condition, in the order given above, is the one that is
// reported. Also sets the last death test message string.
bool DeathTestImpl::Passed(bool status_ok) {
if (!spawned())
return false;
if (!spawned()) return false;
const std::string error_message = GetErrorLogs();
@ -583,15 +579,18 @@ bool DeathTestImpl::Passed(bool status_ok) {
switch (outcome()) {
case LIVED:
buffer << " Result: failed to die.\n"
<< " Error msg:\n" << FormatDeathTestOutput(error_message);
<< " Error msg:\n"
<< FormatDeathTestOutput(error_message);
break;
case THREW:
buffer << " Result: threw an exception.\n"
<< " Error msg:\n" << FormatDeathTestOutput(error_message);
<< " Error msg:\n"
<< FormatDeathTestOutput(error_message);
break;
case RETURNED:
buffer << " Result: illegal return in test statement.\n"
<< " Error msg:\n" << FormatDeathTestOutput(error_message);
<< " Error msg:\n"
<< FormatDeathTestOutput(error_message);
break;
case DIED:
if (status_ok) {
@ -608,7 +607,8 @@ bool DeathTestImpl::Passed(bool status_ok) {
} else {
buffer << " Result: died but not with expected exit code:\n"
<< " " << ExitSummary(status()) << "\n"
<< "Actual msg:\n" << FormatDeathTestOutput(error_message);
<< "Actual msg:\n"
<< FormatDeathTestOutput(error_message);
}
break;
case IN_PROGRESS:
@ -682,14 +682,12 @@ class WindowsDeathTest : public DeathTestImpl {
// status, or 0 if no child process exists. As a side effect, sets the
// outcome data member.
int WindowsDeathTest::Wait() {
if (!spawned())
return 0;
if (!spawned()) return 0;
// Wait until the child either signals that it has acquired the write end
// of the pipe or it dies.
const HANDLE wait_handles[2] = {child_handle_.Get(), event_handle_.Get()};
switch (::WaitForMultipleObjects(2,
wait_handles,
switch (::WaitForMultipleObjects(2, wait_handles,
FALSE, // Waits for any of the handles.
INFINITE)) {
case WAIT_OBJECT_0:
@ -710,9 +708,8 @@ int WindowsDeathTest::Wait() {
// returns immediately if the child has already exited, regardless of
// whether previous calls to WaitForMultipleObjects synchronized on this
// handle or not.
GTEST_DEATH_TEST_CHECK_(
WAIT_OBJECT_0 == ::WaitForSingleObject(child_handle_.Get(),
INFINITE));
GTEST_DEATH_TEST_CHECK_(WAIT_OBJECT_0 ==
::WaitForSingleObject(child_handle_.Get(), INFINITE));
DWORD status_code;
GTEST_DEATH_TEST_CHECK_(
::GetExitCodeProcess(child_handle_.Get(), &status_code) != FALSE);
@ -745,12 +742,12 @@ DeathTest::TestRole WindowsDeathTest::AssumeRole() {
SECURITY_ATTRIBUTES handles_are_inheritable = {sizeof(SECURITY_ATTRIBUTES),
nullptr, TRUE};
HANDLE read_handle, write_handle;
GTEST_DEATH_TEST_CHECK_(
::CreatePipe(&read_handle, &write_handle, &handles_are_inheritable,
GTEST_DEATH_TEST_CHECK_(::CreatePipe(&read_handle, &write_handle,
&handles_are_inheritable,
0) // Default buffer size.
!= FALSE);
set_read_fd(::_open_osfhandle(reinterpret_cast<intptr_t>(read_handle),
O_RDONLY));
set_read_fd(
::_open_osfhandle(reinterpret_cast<intptr_t>(read_handle), O_RDONLY));
write_handle_.Reset(write_handle);
event_handle_.Reset(::CreateEvent(
&handles_are_inheritable,
@ -777,9 +774,8 @@ DeathTest::TestRole WindowsDeathTest::AssumeRole() {
executable_path,
_MAX_PATH));
std::string command_line =
std::string(::GetCommandLineA()) + " " + filter_flag + " \"" +
internal_flag + "\"";
std::string command_line = std::string(::GetCommandLineA()) + " " +
filter_flag + " \"" + internal_flag + "\"";
DeathTest::set_last_death_test_message("");
@ -858,18 +854,13 @@ class Arguments {
template <typename Str>
void AddArguments(const ::std::vector<Str>& arguments) {
for (typename ::std::vector<Str>::const_iterator i = arguments.begin();
i != arguments.end();
++i) {
i != arguments.end(); ++i) {
args_.insert(args_.end() - 1, posix::StrDup(i->c_str()));
}
}
char* const* Argv() {
return &args_[0];
}
char* const* Argv() { return &args_[0]; }
int size() {
return static_cast<int>(args_.size()) - 1;
}
int size() { return static_cast<int>(args_.size()) - 1; }
private:
std::vector<char*> args_;
@ -883,8 +874,7 @@ int FuchsiaDeathTest::Wait() {
const int kSocketKey = 1;
const int kExceptionKey = 2;
if (!spawned())
return 0;
if (!spawned()) return 0;
// Create a port to wait for socket/task/exception events.
zx_status_t status_zx;
@ -893,8 +883,8 @@ int FuchsiaDeathTest::Wait() {
GTEST_DEATH_TEST_CHECK_(status_zx == ZX_OK);
// Register to wait for the child process to terminate.
status_zx = child_process_.wait_async(
port, kProcessKey, ZX_PROCESS_TERMINATED, 0);
status_zx =
child_process_.wait_async(port, kProcessKey, ZX_PROCESS_TERMINATED, 0);
GTEST_DEATH_TEST_CHECK_(status_zx == ZX_OK);
// Register to wait for the socket to be readable or closed.
@ -903,8 +893,8 @@ int FuchsiaDeathTest::Wait() {
GTEST_DEATH_TEST_CHECK_(status_zx == ZX_OK);
// Register to wait for an exception.
status_zx = exception_channel_.wait_async(
port, kExceptionKey, ZX_CHANNEL_READABLE, 0);
status_zx = exception_channel_.wait_async(port, kExceptionKey,
ZX_CHANNEL_READABLE, 0);
GTEST_DEATH_TEST_CHECK_(status_zx == ZX_OK);
bool process_terminated = false;
@ -934,9 +924,9 @@ int FuchsiaDeathTest::Wait() {
size_t old_length = captured_stderr_.length();
size_t bytes_read = 0;
captured_stderr_.resize(old_length + kBufferSize);
status_zx = stderr_socket_.read(
0, &captured_stderr_.front() + old_length, kBufferSize,
&bytes_read);
status_zx =
stderr_socket_.read(0, &captured_stderr_.front() + old_length,
kBufferSize, &bytes_read);
captured_stderr_.resize(old_length + bytes_read);
} while (status_zx == ZX_OK);
if (status_zx == ZX_ERR_PEER_CLOSED) {
@ -992,11 +982,10 @@ DeathTest::TestRole FuchsiaDeathTest::AssumeRole() {
const std::string filter_flag = std::string("--") + GTEST_FLAG_PREFIX_ +
"filter=" + info->test_suite_name() + "." +
info->name();
const std::string internal_flag =
std::string("--") + GTEST_FLAG_PREFIX_ + kInternalRunDeathTestFlag + "="
+ file_ + "|"
+ StreamableToString(line_) + "|"
+ StreamableToString(death_test_index);
const std::string internal_flag = std::string("--") + GTEST_FLAG_PREFIX_ +
kInternalRunDeathTestFlag + "=" + file_ +
"|" + StreamableToString(line_) + "|" +
StreamableToString(death_test_index);
Arguments args;
args.AddArguments(GetInjectableArgvs());
args.AddArgument(filter_flag.c_str());
@ -1019,8 +1008,7 @@ DeathTest::TestRole FuchsiaDeathTest::AssumeRole() {
// Create a socket pair will be used to receive the child process' stderr.
zx::socket stderr_producer_socket;
status =
zx::socket::create(0, &stderr_producer_socket, &stderr_socket_);
status = zx::socket::create(0, &stderr_producer_socket, &stderr_socket_);
GTEST_DEATH_TEST_CHECK_(status >= 0);
int stderr_producer_fd = -1;
status =
@ -1042,30 +1030,27 @@ DeathTest::TestRole FuchsiaDeathTest::AssumeRole() {
zx_policy_basic_t policy;
policy.condition = ZX_POL_NEW_ANY;
policy.policy = ZX_POL_ACTION_ALLOW;
status = zx_job_set_policy(
child_job, ZX_JOB_POL_RELATIVE, ZX_JOB_POL_BASIC, &policy, 1);
status = zx_job_set_policy(child_job, ZX_JOB_POL_RELATIVE, ZX_JOB_POL_BASIC,
&policy, 1);
GTEST_DEATH_TEST_CHECK_(status == ZX_OK);
// Create an exception channel attached to the |child_job|, to allow
// us to suppress the system default exception handler from firing.
status =
zx_task_create_exception_channel(
status = zx_task_create_exception_channel(
child_job, 0, exception_channel_.reset_and_get_address());
GTEST_DEATH_TEST_CHECK_(status == ZX_OK);
// Spawn the child process.
status = fdio_spawn_etc(
child_job, FDIO_SPAWN_CLONE_ALL, args.Argv()[0], args.Argv(), nullptr,
2, spawn_actions, child_process_.reset_and_get_address(), nullptr);
status = fdio_spawn_etc(child_job, FDIO_SPAWN_CLONE_ALL, args.Argv()[0],
args.Argv(), nullptr, 2, spawn_actions,
child_process_.reset_and_get_address(), nullptr);
GTEST_DEATH_TEST_CHECK_(status == ZX_OK);
set_spawned(true);
return OVERSEE_TEST;
}
std::string FuchsiaDeathTest::GetErrorLogs() {
return captured_stderr_;
}
std::string FuchsiaDeathTest::GetErrorLogs() { return captured_stderr_; }
#else // We are neither on Windows, nor on Fuchsia.
@ -1096,8 +1081,7 @@ ForkingDeathTest::ForkingDeathTest(const char* a_statement,
// status, or 0 if no child process exists. As a side effect, sets the
// outcome data member.
int ForkingDeathTest::Wait() {
if (!spawned())
return 0;
if (!spawned()) return 0;
ReadAndInterpretStatusByte();
@ -1207,14 +1191,11 @@ class Arguments {
template <typename Str>
void AddArguments(const ::std::vector<Str>& arguments) {
for (typename ::std::vector<Str>::const_iterator i = arguments.begin();
i != arguments.end();
++i) {
i != arguments.end(); ++i) {
args_.insert(args_.end() - 1, posix::StrDup(i->c_str()));
}
}
char* const* Argv() {
return &args_[0];
}
char* const* Argv() { return &args_[0]; }
private:
std::vector<char*> args_;
@ -1244,8 +1225,8 @@ static int ExecDeathTestChildMain(void* child_arg) {
UnitTest::GetInstance()->original_working_dir();
// We can safely call chdir() as it's a direct system call.
if (chdir(original_dir) != 0) {
DeathTestAbort(std::string("chdir(\"") + original_dir + "\") failed: " +
GetLastErrnoDescription());
DeathTestAbort(std::string("chdir(\"") + original_dir +
"\") failed: " + GetLastErrnoDescription());
return EXIT_FAILURE;
}
@ -1256,8 +1237,7 @@ static int ExecDeathTestChildMain(void* child_arg) {
// one path separator.
execv(args->argv[0], args->argv);
DeathTestAbort(std::string("execv(") + args->argv[0] + ", ...) in " +
original_dir + " failed: " +
GetLastErrnoDescription());
original_dir + " failed: " + GetLastErrnoDescription());
return EXIT_FAILURE;
}
#endif // GTEST_OS_QNX
@ -1322,16 +1302,16 @@ static pid_t ExecDeathTestSpawnChild(char* const* argv, int close_fd) {
UnitTest::GetInstance()->original_working_dir();
// We can safely call chdir() as it's a direct system call.
if (chdir(original_dir) != 0) {
DeathTestAbort(std::string("chdir(\"") + original_dir + "\") failed: " +
GetLastErrnoDescription());
DeathTestAbort(std::string("chdir(\"") + original_dir +
"\") failed: " + GetLastErrnoDescription());
return EXIT_FAILURE;
}
int fd_flags;
// Set close_fd to be closed after spawn.
GTEST_DEATH_TEST_CHECK_SYSCALL_(fd_flags = fcntl(close_fd, F_GETFD));
GTEST_DEATH_TEST_CHECK_SYSCALL_(fcntl(close_fd, F_SETFD,
fd_flags | FD_CLOEXEC));
GTEST_DEATH_TEST_CHECK_SYSCALL_(
fcntl(close_fd, F_SETFD, fd_flags | FD_CLOEXEC));
struct inheritance inherit = {0};
// spawn is a system call.
child_pid = spawn(args.argv[0], 0, nullptr, &inherit, args.argv, environ);
@ -1349,8 +1329,8 @@ static pid_t ExecDeathTestSpawnChild(char* const* argv, int close_fd) {
memset(&ignore_sigprof_action, 0, sizeof(ignore_sigprof_action));
sigemptyset(&ignore_sigprof_action.sa_mask);
ignore_sigprof_action.sa_handler = SIG_IGN;
GTEST_DEATH_TEST_CHECK_SYSCALL_(sigaction(
SIGPROF, &ignore_sigprof_action, &saved_sigprof_action));
GTEST_DEATH_TEST_CHECK_SYSCALL_(
sigaction(SIGPROF, &ignore_sigprof_action, &saved_sigprof_action));
#endif // GTEST_OS_LINUX
#if GTEST_HAS_CLONE
@ -1464,15 +1444,15 @@ bool DefaultDeathTestFactory::Create(const char* statement,
UnitTestImpl* const impl = GetUnitTestImpl();
const InternalRunDeathTestFlag* const flag =
impl->internal_run_death_test_flag();
const int death_test_index = impl->current_test_info()
->increment_death_test_count();
const int death_test_index =
impl->current_test_info()->increment_death_test_count();
if (flag != nullptr) {
if (death_test_index > flag->index()) {
DeathTest::set_last_death_test_message(
"Death test count (" + StreamableToString(death_test_index)
+ ") somehow exceeded expected maximum ("
+ StreamableToString(flag->index()) + ")");
"Death test count (" + StreamableToString(death_test_index) +
") somehow exceeded expected maximum (" +
StreamableToString(flag->index()) + ")");
return false;
}
@ -1534,8 +1514,7 @@ static int GetStatusFileDescriptor(unsigned int parent_process_id,
GTEST_CHECK_(sizeof(HANDLE) <= sizeof(size_t));
const HANDLE write_handle =
reinterpret_cast<HANDLE>(write_handle_as_size_t);
const HANDLE write_handle = reinterpret_cast<HANDLE>(write_handle_as_size_t);
HANDLE dup_write_handle;
// The newly initialized handle is accessible only in the parent
@ -1557,9 +1536,7 @@ static int GetStatusFileDescriptor(unsigned int parent_process_id,
HANDLE dup_event_handle;
if (!::DuplicateHandle(parent_process_handle.Get(), event_handle,
::GetCurrentProcess(), &dup_event_handle,
0x0,
FALSE,
::GetCurrentProcess(), &dup_event_handle, 0x0, FALSE,
DUPLICATE_SAME_ACCESS)) {
DeathTestAbort("Unable to duplicate the event handle " +
StreamableToString(event_handle_as_size_t) +
@ -1603,34 +1580,30 @@ InternalRunDeathTestFlag* ParseInternalRunDeathTestFlag() {
size_t write_handle_as_size_t = 0;
size_t event_handle_as_size_t = 0;
if (fields.size() != 6
|| !ParseNaturalNumber(fields[1], &line)
|| !ParseNaturalNumber(fields[2], &index)
|| !ParseNaturalNumber(fields[3], &parent_process_id)
|| !ParseNaturalNumber(fields[4], &write_handle_as_size_t)
|| !ParseNaturalNumber(fields[5], &event_handle_as_size_t)) {
if (fields.size() != 6 || !ParseNaturalNumber(fields[1], &line) ||
!ParseNaturalNumber(fields[2], &index) ||
!ParseNaturalNumber(fields[3], &parent_process_id) ||
!ParseNaturalNumber(fields[4], &write_handle_as_size_t) ||
!ParseNaturalNumber(fields[5], &event_handle_as_size_t)) {
DeathTestAbort("Bad --gtest_internal_run_death_test flag: " +
GTEST_FLAG_GET(internal_run_death_test));
}
write_fd = GetStatusFileDescriptor(parent_process_id,
write_handle_as_size_t,
write_fd = GetStatusFileDescriptor(parent_process_id, write_handle_as_size_t,
event_handle_as_size_t);
#elif GTEST_OS_FUCHSIA
if (fields.size() != 3
|| !ParseNaturalNumber(fields[1], &line)
|| !ParseNaturalNumber(fields[2], &index)) {
if (fields.size() != 3 || !ParseNaturalNumber(fields[1], &line) ||
!ParseNaturalNumber(fields[2], &index)) {
DeathTestAbort("Bad --gtest_internal_run_death_test flag: " +
GTEST_FLAG_GET(internal_run_death_test));
}
#else
if (fields.size() != 4
|| !ParseNaturalNumber(fields[1], &line)
|| !ParseNaturalNumber(fields[2], &index)
|| !ParseNaturalNumber(fields[3], &write_fd)) {
if (fields.size() != 4 || !ParseNaturalNumber(fields[1], &line) ||
!ParseNaturalNumber(fields[2], &index) ||
!ParseNaturalNumber(fields[3], &write_fd)) {
DeathTestAbort("Bad --gtest_internal_run_death_test flag: " +
GTEST_FLAG_GET(internal_run_death_test));
}

View File

@ -30,8 +30,9 @@
#include "gtest/internal/gtest-filepath.h"
#include <stdlib.h>
#include "gtest/internal/gtest-port.h"
#include "gtest/gtest-message.h"
#include "gtest/internal/gtest-port.h"
#if GTEST_OS_WINDOWS_MOBILE
#include <windows.h>
@ -40,6 +41,7 @@
#include <io.h>
#else
#include <limits.h>
#include <climits> // Some Linux distributions define PATH_MAX here.
#endif // GTEST_OS_WINDOWS_MOBILE
@ -121,8 +123,8 @@ FilePath FilePath::GetCurrentDir() {
FilePath FilePath::RemoveExtension(const char* extension) const {
const std::string dot_extension = std::string(".") + extension;
if (String::EndsWithCaseInsensitive(pathname_, dot_extension)) {
return FilePath(pathname_.substr(
0, pathname_.length() - dot_extension.length()));
return FilePath(
pathname_.substr(0, pathname_.length() - dot_extension.length()));
}
return *this;
}
@ -178,15 +180,14 @@ FilePath FilePath::RemoveFileName() const {
// than zero (e.g., 12), returns "dir/test_12.xml".
// On Windows platform, uses \ as the separator rather than /.
FilePath FilePath::MakeFileName(const FilePath& directory,
const FilePath& base_name,
int number,
const FilePath& base_name, int number,
const char* extension) {
std::string file;
if (number == 0) {
file = base_name.string() + "." + extension;
} else {
file = base_name.string() + "_" + StreamableToString(number)
+ "." + extension;
file =
base_name.string() + "_" + StreamableToString(number) + "." + extension;
}
return ConcatPaths(directory, FilePath(file));
}
@ -195,8 +196,7 @@ FilePath FilePath::MakeFileName(const FilePath& directory,
// On Windows, uses \ as the separator rather than /.
FilePath FilePath::ConcatPaths(const FilePath& directory,
const FilePath& relative_path) {
if (directory.IsEmpty())
return relative_path;
if (directory.IsEmpty()) return relative_path;
const FilePath dir(directory.RemoveTrailingPathSeparator());
return FilePath(dir.string() + kPathSeparator + relative_path.string());
}
@ -222,8 +222,8 @@ bool FilePath::DirectoryExists() const {
#if GTEST_OS_WINDOWS
// Don't strip off trailing separator if path is a root directory on
// Windows (like "C:\\").
const FilePath& path(IsRootDirectory() ? *this :
RemoveTrailingPathSeparator());
const FilePath& path(IsRootDirectory() ? *this
: RemoveTrailingPathSeparator());
#else
const FilePath& path(*this);
#endif
@ -238,8 +238,8 @@ bool FilePath::DirectoryExists() const {
}
#else
posix::StatStruct file_stat{};
result = posix::Stat(path.c_str(), &file_stat) == 0 &&
posix::IsDir(file_stat);
result =
posix::Stat(path.c_str(), &file_stat) == 0 && posix::IsDir(file_stat);
#endif // GTEST_OS_WINDOWS_MOBILE
return result;
@ -262,8 +262,7 @@ bool FilePath::IsAbsolutePath() const {
return pathname_.length() >= 3 &&
((name[0] >= 'a' && name[0] <= 'z') ||
(name[0] >= 'A' && name[0] <= 'Z')) &&
name[1] == ':' &&
IsPathSeparator(name[2]);
name[1] == ':' && IsPathSeparator(name[2]);
#else
return IsPathSeparator(name[0]);
#endif
@ -341,8 +340,7 @@ bool FilePath::CreateFolder() const {
// name, otherwise return the name string unmodified.
// On Windows platform, uses \ as the separator, other platforms use /.
FilePath FilePath::RemoveTrailingPathSeparator() const {
return IsDirectory()
? FilePath(pathname_.substr(0, pathname_.length() - 1))
return IsDirectory() ? FilePath(pathname_.substr(0, pathname_.length() - 1))
: *this;
}

View File

@ -58,8 +58,8 @@
#include <windows.h> // NOLINT
#endif // GTEST_OS_WINDOWS
#include "gtest/gtest.h"
#include "gtest/gtest-spi.h"
#include "gtest/gtest.h"
GTEST_DISABLE_MSC_WARNINGS_PUSH_(4251 \
/* class A needs to have dll-interface to be used by clients of class B */)
@ -109,15 +109,16 @@ GTEST_API_ bool ParseFlag(const char* str, const char* flag, int32_t* value);
// Returns a random seed in range [1, kMaxRandomSeed] based on the
// given --gtest_random_seed flag value.
inline int GetRandomSeedFromFlag(int32_t random_seed_flag) {
const unsigned int raw_seed = (random_seed_flag == 0) ?
static_cast<unsigned int>(GetTimeInMillis()) :
static_cast<unsigned int>(random_seed_flag);
const unsigned int raw_seed =
(random_seed_flag == 0) ? static_cast<unsigned int>(GetTimeInMillis())
: static_cast<unsigned int>(random_seed_flag);
// Normalizes the actual seed to range [1, kMaxRandomSeed] such that
// it's easy to type.
const int normalized_seed =
static_cast<int>((raw_seed - 1U) %
static_cast<unsigned int>(kMaxRandomSeed)) + 1;
static_cast<unsigned int>(kMaxRandomSeed)) +
1;
return normalized_seed;
}
@ -261,8 +262,8 @@ GTEST_API_ int32_t Int32FromEnvOrDie(const char* env_var, int32_t default_val);
// returns true if and only if the test should be run on this shard. The test id
// is some arbitrary but unique non-negative integer assigned to each test
// method. Assumes that 0 <= shard_index < total_shards.
GTEST_API_ bool ShouldRunTestOnShard(
int total_shards, int shard_index, int test_id);
GTEST_API_ bool ShouldRunTestOnShard(int total_shards, int shard_index,
int test_id);
// STL container utilities.
@ -274,8 +275,7 @@ inline int CountIf(const Container& c, Predicate predicate) {
// Solaris has a non-standard signature.
int count = 0;
for (auto it = c.begin(); it != c.end(); ++it) {
if (predicate(*it))
++count;
if (predicate(*it)) ++count;
}
return count;
}
@ -728,9 +728,7 @@ class GTEST_API_ UnitTestImpl {
}
// Clears the results of ad-hoc test assertions.
void ClearAdHocTestResult() {
ad_hoc_test_result_.Clear();
}
void ClearAdHocTestResult() { ad_hoc_test_result_.Clear(); }
// Adds a TestProperty to the current TestResult object when invoked in a
// context of a test or a test suite, or to the global property set. If the
@ -738,10 +736,7 @@ class GTEST_API_ UnitTestImpl {
// updated.
void RecordProperty(const TestProperty& test_property);
enum ReactionToSharding {
HONOR_SHARDING_PROTOCOL,
IGNORE_SHARDING_PROTOCOL
};
enum ReactionToSharding { HONOR_SHARDING_PROTOCOL, IGNORE_SHARDING_PROTOCOL };
// Matches the full name of each test against the user-specified
// filter to decide whether the test should run, then records the
@ -970,8 +965,9 @@ GTEST_API_ bool IsValidEscape(char ch);
GTEST_API_ bool AtomMatchesChar(bool escaped, char pattern, char ch);
GTEST_API_ bool ValidateRegex(const char* regex);
GTEST_API_ bool MatchRegexAtHead(const char* regex, const char* str);
GTEST_API_ bool MatchRepetitionAndRegexAtHead(
bool escaped, char ch, char repeat, const char* regex, const char* str);
GTEST_API_ bool MatchRepetitionAndRegexAtHead(bool escaped, char ch,
char repeat, const char* regex,
const char* str);
GTEST_API_ bool MatchRegexAnywhere(const char* regex, const char* str);
#endif // GTEST_USES_SIMPLE_RE
@ -1073,8 +1069,7 @@ class StreamingListener : public EmptyTestEventListener {
}
~SocketWriter() override {
if (sockfd_ != -1)
CloseConnection();
if (sockfd_ != -1) CloseConnection();
}
// Sends a string to the socket.
@ -1084,8 +1079,7 @@ class StreamingListener : public EmptyTestEventListener {
const auto len = static_cast<size_t>(message.length());
if (write(sockfd_, message.c_str(), len) != static_cast<ssize_t>(len)) {
GTEST_LOG_(WARNING)
<< "stream_result_to: failed to stream to "
GTEST_LOG_(WARNING) << "stream_result_to: failed to stream to "
<< host_name_ << ":" << port_num_;
}
}
@ -1119,7 +1113,9 @@ class StreamingListener : public EmptyTestEventListener {
}
explicit StreamingListener(AbstractSocketWriter* socket_writer)
: socket_writer_(socket_writer) { Start(); }
: socket_writer_(socket_writer) {
Start();
}
void OnTestProgramStart(const UnitTest& /* unit_test */) override {
SendLn("event=TestProgramStart");
@ -1142,9 +1138,9 @@ class StreamingListener : public EmptyTestEventListener {
void OnTestIterationEnd(const UnitTest& unit_test,
int /* iteration */) override {
SendLn("event=TestIterationEnd&passed=" +
FormatBool(unit_test.Passed()) + "&elapsed_time=" +
StreamableToString(unit_test.elapsed_time()) + "ms");
SendLn("event=TestIterationEnd&passed=" + FormatBool(unit_test.Passed()) +
"&elapsed_time=" + StreamableToString(unit_test.elapsed_time()) +
"ms");
}
// Note that "event=TestCaseStart" is a wire format and has to remain
@ -1167,8 +1163,7 @@ class StreamingListener : public EmptyTestEventListener {
void OnTestEnd(const TestInfo& test_info) override {
SendLn("event=TestEnd&passed=" +
FormatBool((test_info.result())->Passed()) +
"&elapsed_time=" +
FormatBool((test_info.result())->Passed()) + "&elapsed_time=" +
StreamableToString((test_info.result())->elapsed_time()) + "ms");
}

View File

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

View File

@ -27,21 +27,22 @@
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include "gtest/internal/gtest-port.h"
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <cstdint>
#include <fstream>
#include <memory>
#if GTEST_OS_WINDOWS
# include <windows.h>
#include <io.h>
#include <sys/stat.h>
#include <windows.h>
#include <map> // Used in ThreadLocal.
#ifdef _MSC_VER
#include <crtdbg.h>
@ -80,8 +81,8 @@
#include <zircon/syscalls.h>
#endif // GTEST_OS_FUCHSIA
#include "gtest/gtest-spi.h"
#include "gtest/gtest-message.h"
#include "gtest/gtest-spi.h"
#include "gtest/internal/gtest-internal.h"
#include "gtest/internal/gtest-string.h"
#include "src/gtest-internal-inl.h"
@ -131,8 +132,7 @@ size_t GetThreadCount() {
if (status == KERN_SUCCESS) {
// task_threads allocates resources in thread_list and we need to free them
// to avoid leaks.
vm_deallocate(task,
reinterpret_cast<vm_address_t>(thread_list),
vm_deallocate(task, reinterpret_cast<vm_address_t>(thread_list),
sizeof(thread_t) * thread_count);
return static_cast<size_t>(thread_count);
} else {
@ -210,8 +210,7 @@ size_t GetThreadCount() {
// exclude empty members
size_t nthreads = 0;
for (size_t i = 0; i < size / static_cast<size_t>(mib[4]); i++) {
if (info[i].p_tid != -1)
nthreads++;
if (info[i].p_tid != -1) nthreads++;
}
return nthreads;
}
@ -254,13 +253,9 @@ size_t GetThreadCount() {
size_t GetThreadCount() {
int dummy_buffer;
size_t avail;
zx_status_t status = zx_object_get_info(
zx_process_self(),
ZX_INFO_PROCESS_THREADS,
&dummy_buffer,
0,
nullptr,
&avail);
zx_status_t status =
zx_object_get_info(zx_process_self(), ZX_INFO_PROCESS_THREADS,
&dummy_buffer, 0, nullptr, &avail);
if (status == ZX_OK) {
return avail;
} else {
@ -280,23 +275,15 @@ size_t GetThreadCount() {
#if GTEST_IS_THREADSAFE && GTEST_OS_WINDOWS
AutoHandle::AutoHandle()
: handle_(INVALID_HANDLE_VALUE) {}
AutoHandle::AutoHandle() : handle_(INVALID_HANDLE_VALUE) {}
AutoHandle::AutoHandle(Handle handle)
: handle_(handle) {}
AutoHandle::AutoHandle(Handle handle) : handle_(handle) {}
AutoHandle::~AutoHandle() {
Reset();
}
AutoHandle::~AutoHandle() { Reset(); }
AutoHandle::Handle AutoHandle::Get() const {
return handle_;
}
AutoHandle::Handle AutoHandle::Get() const { return handle_; }
void AutoHandle::Reset() {
Reset(INVALID_HANDLE_VALUE);
}
void AutoHandle::Reset() { Reset(INVALID_HANDLE_VALUE); }
void AutoHandle::Reset(HANDLE handle) {
// Resetting with the same handle we already own is invalid.
@ -370,8 +357,7 @@ namespace {
// MemoryIsNotDeallocated memory_is_not_deallocated;
// critical_section_ = new CRITICAL_SECTION;
//
class MemoryIsNotDeallocated
{
class MemoryIsNotDeallocated {
public:
MemoryIsNotDeallocated() : old_crtdbg_flag_(0) {
old_crtdbg_flag_ = _CrtSetDbgFlag(_CRTDBG_REPORT_FLAG);
@ -414,15 +400,13 @@ void Mutex::ThreadSafeLazyInit() {
::InitializeCriticalSection(critical_section_);
// Updates the critical_section_init_phase_ to 2 to signal
// initialization complete.
GTEST_CHECK_(::InterlockedCompareExchange(
&critical_section_init_phase_, 2L, 1L) ==
1L);
GTEST_CHECK_(::InterlockedCompareExchange(&critical_section_init_phase_,
2L, 1L) == 1L);
break;
case 1:
// Somebody else is already initializing the mutex; spin until they
// are done.
while (::InterlockedCompareExchange(&critical_section_init_phase_,
2L,
while (::InterlockedCompareExchange(&critical_section_init_phase_, 2L,
2L) != 2L) {
// Possibly yields the rest of the thread's time slice to other
// threads.
@ -467,9 +451,7 @@ class ThreadWithParamSupport : public ThreadWithParamBase {
private:
struct ThreadMainParam {
ThreadMainParam(Runnable* runnable, Notification* thread_can_start)
: runnable_(runnable),
thread_can_start_(thread_can_start) {
}
: runnable_(runnable), thread_can_start_(thread_can_start) {}
std::unique_ptr<Runnable> runnable_;
// Does not own.
Notification* thread_can_start_;
@ -494,13 +476,10 @@ class ThreadWithParamSupport : public ThreadWithParamBase {
ThreadWithParamBase::ThreadWithParamBase(Runnable* runnable,
Notification* thread_can_start)
: thread_(ThreadWithParamSupport::CreateThread(runnable,
thread_can_start)) {
}
: thread_(
ThreadWithParamSupport::CreateThread(runnable, thread_can_start)) {}
ThreadWithParamBase::~ThreadWithParamBase() {
Join();
}
ThreadWithParamBase::~ThreadWithParamBase() { Join(); }
void ThreadWithParamBase::Join() {
GTEST_CHECK_(::WaitForSingleObject(thread_.Get(), INFINITE) == WAIT_OBJECT_0)
@ -527,8 +506,10 @@ class ThreadLocalRegistryImpl {
ThreadIdToThreadLocals::iterator thread_local_pos =
thread_to_thread_locals->find(current_thread);
if (thread_local_pos == thread_to_thread_locals->end()) {
thread_local_pos = thread_to_thread_locals->insert(
std::make_pair(current_thread, ThreadLocalValues())).first;
thread_local_pos =
thread_to_thread_locals
->insert(std::make_pair(current_thread, ThreadLocalValues()))
.first;
StartWatcherThreadFor(current_thread);
}
ThreadLocalValues& thread_local_values = thread_local_pos->second;
@ -557,8 +538,7 @@ class ThreadLocalRegistryImpl {
GetThreadLocalsMapLocked();
for (ThreadIdToThreadLocals::iterator it =
thread_to_thread_locals->begin();
it != thread_to_thread_locals->end();
++it) {
it != thread_to_thread_locals->end(); ++it) {
ThreadLocalValues& thread_local_values = it->second;
ThreadLocalValues::iterator value_pos =
thread_local_values.find(thread_local_instance);
@ -589,8 +569,7 @@ class ThreadLocalRegistryImpl {
ThreadLocalValues& thread_local_values = thread_local_pos->second;
for (ThreadLocalValues::iterator value_pos =
thread_local_values.begin();
value_pos != thread_local_values.end();
++value_pos) {
value_pos != thread_local_values.end(); ++value_pos) {
value_holders.push_back(value_pos->second);
}
thread_to_thread_locals->erase(thread_local_pos);
@ -616,9 +595,8 @@ class ThreadLocalRegistryImpl {
static void StartWatcherThreadFor(DWORD thread_id) {
// The returned handle will be kept in thread_map and closed by
// watcher_thread in WatcherThreadFunc.
HANDLE thread = ::OpenThread(SYNCHRONIZE | THREAD_QUERY_INFORMATION,
FALSE,
thread_id);
HANDLE thread =
::OpenThread(SYNCHRONIZE | THREAD_QUERY_INFORMATION, FALSE, thread_id);
GTEST_CHECK_(thread != nullptr);
// We need to pass a valid thread ID pointer into CreateThread for it
// to work correctly under Win98.
@ -644,8 +622,7 @@ class ThreadLocalRegistryImpl {
static DWORD WINAPI WatcherThreadFunc(LPVOID param) {
const ThreadIdAndHandle* tah =
reinterpret_cast<const ThreadIdAndHandle*>(param);
GTEST_CHECK_(
::WaitForSingleObject(tah->second, INFINITE) == WAIT_OBJECT_0);
GTEST_CHECK_(::WaitForSingleObject(tah->second, INFINITE) == WAIT_OBJECT_0);
OnThreadExit(tah->first);
::CloseHandle(tah->second);
delete tah;
@ -669,7 +646,8 @@ class ThreadLocalRegistryImpl {
};
Mutex ThreadLocalRegistryImpl::mutex_(Mutex::kStaticMutex); // NOLINT
Mutex ThreadLocalRegistryImpl::thread_map_mutex_(Mutex::kStaticMutex); // NOLINT
Mutex ThreadLocalRegistryImpl::thread_map_mutex_(
Mutex::kStaticMutex); // NOLINT
ThreadLocalValueHolderBase* ThreadLocalRegistry::GetValueOnCurrentThread(
const ThreadLocalBase* thread_local_instance) {
@ -779,17 +757,28 @@ bool IsValidEscape(char c) {
bool AtomMatchesChar(bool escaped, char pattern_char, char ch) {
if (escaped) { // "\\p" where p is pattern_char.
switch (pattern_char) {
case 'd': return IsAsciiDigit(ch);
case 'D': return !IsAsciiDigit(ch);
case 'f': return ch == '\f';
case 'n': return ch == '\n';
case 'r': return ch == '\r';
case 's': return IsAsciiWhiteSpace(ch);
case 'S': return !IsAsciiWhiteSpace(ch);
case 't': return ch == '\t';
case 'v': return ch == '\v';
case 'w': return IsAsciiWordChar(ch);
case 'W': return !IsAsciiWordChar(ch);
case 'd':
return IsAsciiDigit(ch);
case 'D':
return !IsAsciiDigit(ch);
case 'f':
return ch == '\f';
case 'n':
return ch == '\n';
case 'r':
return ch == '\r';
case 's':
return IsAsciiWhiteSpace(ch);
case 'S':
return !IsAsciiWhiteSpace(ch);
case 't':
return ch == '\t';
case 'v':
return ch == '\v';
case 'w':
return IsAsciiWordChar(ch);
case 'W':
return !IsAsciiWordChar(ch);
}
return IsAsciiPunct(pattern_char) && pattern_char == ch;
}
@ -800,7 +789,8 @@ bool AtomMatchesChar(bool escaped, char pattern_char, char ch) {
// Helper function used by ValidateRegex() to format error messages.
static std::string FormatRegexSyntaxError(const char* regex, int index) {
return (Message() << "Syntax error at index " << index
<< " in simple regular expression \"" << regex << "\": ").GetString();
<< " in simple regular expression \"" << regex << "\": ")
.GetString();
}
// Generates non-fatal failures and returns false if regex is invalid;
@ -842,12 +832,12 @@ bool ValidateRegex(const char* regex) {
<< "'$' can only appear at the end.";
is_valid = false;
} else if (IsInSet(ch, "()[]{}|")) {
ADD_FAILURE() << FormatRegexSyntaxError(regex, i)
<< "'" << ch << "' is unsupported.";
ADD_FAILURE() << FormatRegexSyntaxError(regex, i) << "'" << ch
<< "' is unsupported.";
is_valid = false;
} else if (IsRepeat(ch) && !prev_repeatable) {
ADD_FAILURE() << FormatRegexSyntaxError(regex, i)
<< "'" << ch << "' can only follow a repeatable token.";
ADD_FAILURE() << FormatRegexSyntaxError(regex, i) << "'" << ch
<< "' can only follow a repeatable token.";
is_valid = false;
}
@ -865,12 +855,10 @@ bool ValidateRegex(const char* regex) {
// characters to be indexable by size_t, in which case the test will
// probably time out anyway. We are fine with this limitation as
// std::string has it too.
bool MatchRepetitionAndRegexAtHead(
bool escaped, char c, char repeat, const char* regex,
const char* str) {
bool MatchRepetitionAndRegexAtHead(bool escaped, char c, char repeat,
const char* regex, const char* str) {
const size_t min_count = (repeat == '+') ? 1 : 0;
const size_t max_count = (repeat == '?') ? 1 :
static_cast<size_t>(-1) - 1;
const size_t max_count = (repeat == '?') ? 1 : static_cast<size_t>(-1) - 1;
// We cannot call numeric_limits::max() as it conflicts with the
// max() macro on Windows.
@ -883,8 +871,7 @@ bool MatchRepetitionAndRegexAtHead(
// greedy match.
return true;
}
if (str[i] == '\0' || !AtomMatchesChar(escaped, c, str[i]))
return false;
if (str[i] == '\0' || !AtomMatchesChar(escaped, c, str[i])) return false;
}
return false;
}
@ -898,19 +885,17 @@ bool MatchRegexAtHead(const char* regex, const char* str) {
// "$" only matches the end of a string. Note that regex being
// valid guarantees that there's nothing after "$" in it.
if (*regex == '$')
return *str == '\0';
if (*regex == '$') return *str == '\0';
// Is the first thing in regex an escape sequence?
const bool escaped = *regex == '\\';
if (escaped)
++regex;
if (escaped) ++regex;
if (IsRepeat(regex[1])) {
// MatchRepetitionAndRegexAtHead() calls MatchRegexAtHead(), so
// here's an indirect recursion. It terminates as the regex gets
// shorter in each recursion.
return MatchRepetitionAndRegexAtHead(
escaped, regex[0], regex[1], regex + 2, str);
return MatchRepetitionAndRegexAtHead(escaped, regex[0], regex[1], regex + 2,
str);
} else {
// regex isn't empty, isn't "$", and doesn't start with a
// repetition. We match the first atom of regex with the first
@ -931,13 +916,11 @@ bool MatchRegexAtHead(const char* regex, const char* str) {
bool MatchRegexAnywhere(const char* regex, const char* str) {
if (regex == nullptr || str == nullptr) return false;
if (*regex == '^')
return MatchRegexAtHead(regex + 1, str);
if (*regex == '^') return MatchRegexAtHead(regex + 1, str);
// A successful match can be anywhere in str.
do {
if (MatchRegexAtHead(regex, str))
return true;
if (MatchRegexAtHead(regex, str)) return true;
} while (*str++ != '\0');
return false;
}
@ -1018,8 +1001,8 @@ GTEST_API_ ::std::string FormatFileLocation(const char* file, int line) {
// FormatFileLocation in order to contrast the two functions.
// Note that FormatCompilerIndependentFileLocation() does NOT append colon
// to the file location it produces, unlike FormatFileLocation().
GTEST_API_ ::std::string FormatCompilerIndependentFileLocation(
const char* file, int line) {
GTEST_API_ ::std::string FormatCompilerIndependentFileLocation(const char* file,
int line) {
const std::string file_name(file == nullptr ? kUnknownFile : file);
if (line < 0)
@ -1030,12 +1013,13 @@ GTEST_API_ ::std::string FormatCompilerIndependentFileLocation(
GTestLog::GTestLog(GTestLogSeverity severity, const char* file, int line)
: severity_(severity) {
const char* const marker =
severity == GTEST_INFO ? "[ INFO ]" :
severity == GTEST_WARNING ? "[WARNING]" :
severity == GTEST_ERROR ? "[ ERROR ]" : "[ FATAL ]";
GetStream() << ::std::endl << marker << " "
<< FormatFileLocation(file, line).c_str() << ": ";
const char* const marker = severity == GTEST_INFO ? "[ INFO ]"
: severity == GTEST_WARNING ? "[WARNING]"
: severity == GTEST_ERROR ? "[ ERROR ]"
: "[ FATAL ]";
GetStream() << ::std::endl
<< marker << " " << FormatFileLocation(file, line).c_str()
<< ": ";
}
// Flushes the buffers and, if severity is GTEST_FATAL, aborts the program.
@ -1063,15 +1047,14 @@ class CapturedStream {
char temp_file_path[MAX_PATH + 1] = {'\0'}; // NOLINT
::GetTempPathA(sizeof(temp_dir_path), temp_dir_path);
const UINT success = ::GetTempFileNameA(temp_dir_path,
"gtest_redir",
const UINT success = ::GetTempFileNameA(temp_dir_path, "gtest_redir",
0, // Generate unique file name.
temp_file_path);
GTEST_CHECK_(success != 0)
<< "Unable to create a temporary file in " << temp_dir_path;
const int captured_fd = creat(temp_file_path, _S_IREAD | _S_IWRITE);
GTEST_CHECK_(captured_fd != -1) << "Unable to open temporary file "
<< temp_file_path;
GTEST_CHECK_(captured_fd != -1)
<< "Unable to open temporary file " << temp_file_path;
filename_ = temp_file_path;
#else
// There's no guarantee that a test has write access to the current
@ -1136,9 +1119,7 @@ class CapturedStream {
close(captured_fd);
}
~CapturedStream() {
remove(filename_.c_str());
}
~CapturedStream() { remove(filename_.c_str()); }
std::string GetCapturedString() {
if (uncaptured_fd_ != -1) {
@ -1215,10 +1196,6 @@ std::string GetCapturedStderr() {
#endif // GTEST_HAS_STREAM_REDIRECTION
size_t GetFileSize(FILE* file) {
fseek(file, 0, SEEK_END);
return static_cast<size_t>(ftell(file));
@ -1236,7 +1213,8 @@ std::string ReadEntireFile(FILE* file) {
// Keeps reading the file until we cannot read further or the
// pre-determined file size is reached.
do {
bytes_last_read = fread(buffer+bytes_read, 1, file_size-bytes_read, file);
bytes_last_read =
fread(buffer + bytes_read, 1, file_size - bytes_read, file);
bytes_read += bytes_last_read;
} while (bytes_last_read > 0 && bytes_read < file_size);
@ -1368,8 +1346,8 @@ int32_t Int32FromGTestEnv(const char* flag, int32_t default_value) {
}
int32_t result = default_value;
if (!ParseInt32(Message() << "Environment variable " << env_var,
string_value, &result)) {
if (!ParseInt32(Message() << "Environment variable " << env_var, string_value,
&result)) {
printf("The default value %s is used.\n",
(Message() << default_value).GetString().c_str());
fflush(stdout);

View File

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

View File

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

View File

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

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.
#include <cstdio>
#include "gtest/gtest.h"
#if GTEST_OS_ESP8266 || GTEST_OS_ESP32
#if GTEST_OS_ESP8266
extern "C" {
#endif
void setup() {
testing::InitGoogleTest();
}
void setup() { testing::InitGoogleTest(); }
void loop() { RUN_ALL_TESTS(); }

View File

@ -27,7 +27,6 @@
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// Unit test for Google Test's break-on-failure mode.
//
// A user can ask Google Test to seg-fault when an assertion fails, using
@ -41,21 +40,19 @@
#include "gtest/gtest.h"
#if GTEST_OS_WINDOWS
# include <windows.h>
#include <stdlib.h>
#include <windows.h>
#endif
namespace {
// A test that's expected to fail.
TEST(Foo, Bar) {
EXPECT_EQ(2, 3);
}
TEST(Foo, Bar) { EXPECT_EQ(2, 3); }
#if GTEST_HAS_SEH && !GTEST_OS_WINDOWS_MOBILE
// On Windows Mobile global exception handlers are not supported.
LONG WINAPI ExitWithExceptionCode(
struct _EXCEPTION_POINTERS* exception_pointers) {
LONG WINAPI
ExitWithExceptionCode(struct _EXCEPTION_POINTERS* exception_pointers) {
exit(exception_pointers->ExceptionRecord->ExceptionCode);
}
#endif

View File

@ -93,9 +93,7 @@ class SehExceptionInTearDownTest : public Test {
TEST_F(SehExceptionInTearDownTest, ThrowsExceptionInTearDown) {}
TEST(SehExceptionTest, ThrowsSehException) {
RaiseException(42, 0, 0, NULL);
}
TEST(SehExceptionTest, ThrowsSehException) { RaiseException(42, 0, 0, NULL); }
#endif // GTEST_HAS_SEH
@ -269,9 +267,7 @@ TEST_F(CxxExceptionInTestBodyTest, ThrowsStdCxxException) {
throw std::runtime_error("Standard C++ exception");
}
TEST(CxxExceptionTest, ThrowsNonStdCxxException) {
throw "C-string";
}
TEST(CxxExceptionTest, ThrowsNonStdCxxException) { throw "C-string"; }
// This terminate handler aborts the program using exit() rather than abort().
// This avoids showing pop-ups on Windows systems and core dumps on Unix-like

View File

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

View File

@ -31,7 +31,6 @@
// Tests for death tests.
#include "gtest/gtest-death-test.h"
#include "gtest/gtest.h"
#include "gtest/internal/gtest-filepath.h"
@ -41,12 +40,12 @@ using testing::internal::AlwaysTrue;
#if GTEST_HAS_DEATH_TEST
#if GTEST_OS_WINDOWS
# include <fcntl.h> // For O_BINARY
#include <direct.h> // For chdir().
#include <fcntl.h> // For O_BINARY
#include <io.h>
#else
# include <unistd.h>
#include <sys/wait.h> // For waitpid.
#include <unistd.h>
#endif // GTEST_OS_WINDOWS
#include <limits.h>
@ -90,6 +89,7 @@ class ReplaceDeathTestFactory {
unit_test_impl_->death_test_factory_.release();
unit_test_impl_->death_test_factory_.reset(old_factory_);
}
private:
// Prevents copying ReplaceDeathTestFactory objects.
ReplaceDeathTestFactory(const ReplaceDeathTestFactory&);
@ -116,8 +116,7 @@ void DieWithMessage(const ::std::string& message) {
// Some compilers can recognize that _exit() never returns and issue the
// 'unreachable code' warning for code following this function, unless
// fooled by a fake condition.
if (AlwaysTrue())
_exit(1);
if (AlwaysTrue()) _exit(1);
}
void DieInside(const ::std::string& function) {
@ -137,8 +136,7 @@ class TestForDeathTest : public testing::Test {
// A method of the test fixture that may die.
void MemberFunction() {
if (should_die_)
DieInside("MemberFunction");
if (should_die_) DieInside("MemberFunction");
}
// True if and only if MemberFunction() should die.
@ -153,8 +151,7 @@ class MayDie {
// A member function that may die.
void MemberFunction() const {
if (should_die_)
DieInside("MayDie::MemberFunction");
if (should_die_) DieInside("MayDie::MemberFunction");
}
private:
@ -173,8 +170,7 @@ int NonVoidFunction() {
// A unary function that may die.
void DieIf(bool should_die) {
if (should_die)
DieInside("DieIf");
if (should_die) DieInside("DieIf");
}
// A binary function that may die.
@ -320,8 +316,7 @@ TEST_F(TestForDeathTest, SingleStatement) {
// doesn't expand into an "if" statement without an "else"
;
if (AlwaysFalse())
ASSERT_DEATH(return, "") << "did not die";
if (AlwaysFalse()) ASSERT_DEATH(return, "") << "did not die";
if (AlwaysFalse())
;
@ -397,7 +392,8 @@ TEST_F(TestForDeathTest, FastDeathTestInChangedDir) {
}
#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).
void SetSigprofActionAndTimer() {
@ -491,9 +487,7 @@ TEST_F(TestForDeathTest, MixedStyles) {
bool pthread_flag;
void SetPthreadFlag() {
pthread_flag = true;
}
void SetPthreadFlag() { pthread_flag = true; }
TEST_F(TestForDeathTest, DoesNotExecuteAtforkHooks) {
if (!GTEST_FLAG_GET(death_test_use_fork)) {
@ -551,9 +545,7 @@ TEST_F(TestForDeathTest, FunctionWithParameter) {
}
// Tests that ASSERT_DEATH can be used outside a TEST, TEST_F, or test fixture.
TEST_F(TestForDeathTest, OutsideFixture) {
DeathTestSubroutine();
}
TEST_F(TestForDeathTest, OutsideFixture) { DeathTestSubroutine(); }
// Tests that death tests can be done inside a loop.
TEST_F(TestForDeathTest, InsideLoop) {
@ -564,7 +556,8 @@ TEST_F(TestForDeathTest, InsideLoop) {
// Tests that a compound statement can be used in a death test.
TEST_F(TestForDeathTest, CompoundStatement) {
EXPECT_DEATH({ // NOLINT
EXPECT_DEATH(
{ // NOLINT
const int x = 2;
const int y = x + 1;
DieIfLessThan(x, y);
@ -574,15 +567,17 @@ TEST_F(TestForDeathTest, CompoundStatement) {
// Tests that code that doesn't die causes a death test to fail.
TEST_F(TestForDeathTest, DoesNotDie) {
EXPECT_NONFATAL_FAILURE(EXPECT_DEATH(DieIf(false), "DieIf"),
"failed to die");
EXPECT_NONFATAL_FAILURE(EXPECT_DEATH(DieIf(false), "DieIf"), "failed to die");
}
// Tests that a death test fails when the error message isn't expected.
TEST_F(TestForDeathTest, ErrorMessageMismatch) {
EXPECT_NONFATAL_FAILURE({ // NOLINT
EXPECT_DEATH(DieIf(true), "DieIfLessThan") << "End of death test message.";
}, "died but not with expected error");
EXPECT_NONFATAL_FAILURE(
{ // NOLINT
EXPECT_DEATH(DieIf(true), "DieIfLessThan")
<< "End of death test message.";
},
"died but not with expected error");
}
// On exit, *aborted will be true if and only if the EXPECT_DEATH()
@ -596,19 +591,20 @@ void ExpectDeathTestHelper(bool* aborted) {
// Tests that EXPECT_DEATH doesn't abort the test on failure.
TEST_F(TestForDeathTest, EXPECT_DEATH) {
bool aborted = true;
EXPECT_NONFATAL_FAILURE(ExpectDeathTestHelper(&aborted),
"failed to die");
EXPECT_NONFATAL_FAILURE(ExpectDeathTestHelper(&aborted), "failed to die");
EXPECT_FALSE(aborted);
}
// Tests that ASSERT_DEATH does abort the test on failure.
TEST_F(TestForDeathTest, ASSERT_DEATH) {
static bool aborted;
EXPECT_FATAL_FAILURE({ // NOLINT
EXPECT_FATAL_FAILURE(
{ // NOLINT
aborted = true;
ASSERT_DEATH(DieIf(false), "DieIf"); // This assertion should fail.
aborted = false;
}, "failed to die");
},
"failed to die");
EXPECT_TRUE(aborted);
}
@ -720,7 +716,8 @@ void ExpectDebugDeathHelper(bool* aborted) {
#if GTEST_OS_WINDOWS
TEST(PopUpDeathTest, DoesNotShowPopUpOnAbort) {
printf("This test should be considered failing if it shows "
printf(
"This test should be considered failing if it shows "
"any pop-up dialogs.\n");
fflush(stdout);
@ -842,22 +839,24 @@ static void TestExitMacros() {
EXPECT_EXIT(raise(SIGKILL), testing::KilledBySignal(SIGKILL), "") << "foo";
ASSERT_EXIT(raise(SIGUSR2), testing::KilledBySignal(SIGUSR2), "") << "bar";
EXPECT_FATAL_FAILURE({ // NOLINT
EXPECT_FATAL_FAILURE(
{ // NOLINT
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
EXPECT_NONFATAL_FAILURE({ // NOLINT
EXPECT_NONFATAL_FAILURE(
{ // NOLINT
EXPECT_EXIT(raise(SIGSEGV), testing::ExitedWithCode(0), "")
<< "This failure is expected.";
}, "This failure is expected.");
},
"This failure is expected.");
}
TEST_F(TestForDeathTest, ExitMacros) {
TestExitMacros();
}
TEST_F(TestForDeathTest, ExitMacros) { TestExitMacros(); }
TEST_F(TestForDeathTest, ExitMacrosUsingFork) {
GTEST_FLAG_SET(death_test_use_fork, true);
@ -866,28 +865,30 @@ TEST_F(TestForDeathTest, ExitMacrosUsingFork) {
TEST_F(TestForDeathTest, InvalidStyle) {
GTEST_FLAG_SET(death_test_style, "rococo");
EXPECT_NONFATAL_FAILURE({ // NOLINT
EXPECT_NONFATAL_FAILURE(
{ // NOLINT
EXPECT_DEATH(_exit(0), "") << "This failure is expected.";
}, "This failure is expected.");
},
"This failure is expected.");
}
TEST_F(TestForDeathTest, DeathTestFailedOutput) {
GTEST_FLAG_SET(death_test_style, "fast");
EXPECT_NONFATAL_FAILURE(
EXPECT_DEATH(DieWithMessage("death\n"),
"expected message"),
EXPECT_DEATH(DieWithMessage("death\n"), "expected message"),
"Actual msg:\n"
"[ DEATH ] death\n");
}
TEST_F(TestForDeathTest, DeathTestUnexpectedReturnOutput) {
GTEST_FLAG_SET(death_test_style, "fast");
EXPECT_NONFATAL_FAILURE(
EXPECT_DEATH({
EXPECT_NONFATAL_FAILURE(EXPECT_DEATH(
{
fprintf(stderr, "returning\n");
fflush(stderr);
return;
}, ""),
},
""),
" Result: illegal return in test statement.\n"
" Error msg:\n"
"[ DEATH ] returning\n");
@ -897,8 +898,7 @@ TEST_F(TestForDeathTest, DeathTestBadExitCodeOutput) {
GTEST_FLAG_SET(death_test_style, "fast");
EXPECT_NONFATAL_FAILURE(
EXPECT_EXIT(DieWithMessage("exiting with rc 1\n"),
testing::ExitedWithCode(3),
"expected message"),
testing::ExitedWithCode(3), "expected message"),
" Result: died but not with expected exit code:\n"
" Exited with exit status 1\n"
"Actual msg:\n"
@ -931,8 +931,8 @@ class MockDeathTestFactory : public DeathTestFactory {
int line, DeathTest** test) override;
// Sets the parameters for subsequent calls to Create.
void SetParameters(bool create, DeathTest::TestRole role,
int status, bool passed);
void SetParameters(bool create, DeathTest::TestRole role, int status,
bool passed);
// Accessors.
int AssumeRoleCalls() const { return assume_role_calls_; }
@ -974,17 +974,15 @@ class MockDeathTestFactory : public DeathTestFactory {
bool test_deleted_;
};
// A DeathTest implementation useful in testing. It returns values set
// at its creation from its various inherited DeathTest methods, and
// reports calls to those methods to its parent MockDeathTestFactory
// object.
class MockDeathTest : public DeathTest {
public:
MockDeathTest(MockDeathTestFactory *parent,
TestRole role, int status, bool passed) :
parent_(parent), role_(role), status_(status), passed_(passed) {
}
MockDeathTest(MockDeathTestFactory* parent, TestRole role, int status,
bool passed)
: parent_(parent), role_(role), status_(status), passed_(passed) {}
~MockDeathTest() override { parent_->test_deleted_ = true; }
TestRole AssumeRole() override {
++parent_->assume_role_calls_;
@ -1009,7 +1007,6 @@ class MockDeathTest : public DeathTest {
const bool passed_;
};
// MockDeathTestFactory constructor.
MockDeathTestFactory::MockDeathTestFactory()
: create_(true),
@ -1019,13 +1016,10 @@ MockDeathTestFactory::MockDeathTestFactory()
assume_role_calls_(0),
wait_calls_(0),
passed_args_(),
abort_args_() {
}
abort_args_() {}
// Sets the parameters for subsequent calls to Create.
void MockDeathTestFactory::SetParameters(bool create,
DeathTest::TestRole role,
void MockDeathTestFactory::SetParameters(bool create, DeathTest::TestRole role,
int status, bool passed) {
create_ = create;
role_ = role;
@ -1038,7 +1032,6 @@ void MockDeathTestFactory::SetParameters(bool create,
abort_args_.clear();
}
// Sets test to NULL (if create_ is false) or to the address of a new
// MockDeathTest object with parameters taken from the last call
// to SetParameters (if create_ is true). Always returns true.
@ -1078,10 +1071,12 @@ class MacroLogicDeathTest : public testing::Test {
// test cannot be run directly from a test routine that uses a
// MockDeathTest, or the remainder of the routine will not be executed.
static void RunReturningDeathTest(bool* flag) {
ASSERT_DEATH({ // NOLINT
ASSERT_DEATH(
{ // NOLINT
*flag = true;
return;
}, "");
},
"");
}
};
@ -1166,8 +1161,7 @@ TEST_F(MacroLogicDeathTest, ChildDoesNotDie) {
// _exit(2) is called in that case by ForkingDeathTest, but not by
// our MockDeathTest.
ASSERT_EQ(2U, factory_->AbortCalls());
EXPECT_EQ(DeathTest::TEST_DID_NOT_DIE,
factory_->AbortArgument(0));
EXPECT_EQ(DeathTest::TEST_DID_NOT_DIE, factory_->AbortArgument(0));
EXPECT_EQ(DeathTest::TEST_ENCOUNTERED_RETURN_STATEMENT,
factory_->AbortArgument(1));
EXPECT_TRUE(factory_->TestDeleted());
@ -1183,12 +1177,16 @@ TEST(SuccessRegistrationDeathTest, NoSuccessPart) {
TEST(StreamingAssertionsDeathTest, DeathTest) {
EXPECT_DEATH(_exit(1), "") << "unexpected failure";
ASSERT_DEATH(_exit(1), "") << "unexpected failure";
EXPECT_NONFATAL_FAILURE({ // NOLINT
EXPECT_NONFATAL_FAILURE(
{ // NOLINT
EXPECT_DEATH(_exit(0), "") << "expected failure";
}, "expected failure");
EXPECT_FATAL_FAILURE({ // NOLINT
},
"expected failure");
EXPECT_FATAL_FAILURE(
{ // NOLINT
ASSERT_DEATH(_exit(0), "") << "expected failure";
}, "expected failure");
},
"expected failure");
}
// Tests that GetLastErrnoDescription returns an empty string when the
@ -1346,21 +1344,25 @@ TEST(ConditionalDeathMacrosDeathTest, ExpectsDeathWhenDeathTestsAvailable) {
TEST(InDeathTestChildDeathTest, ReportsDeathTestCorrectlyInFastStyle) {
GTEST_FLAG_SET(death_test_style, "fast");
EXPECT_FALSE(InDeathTestChild());
EXPECT_DEATH({
EXPECT_DEATH(
{
fprintf(stderr, InDeathTestChild() ? "Inside" : "Outside");
fflush(stderr);
_exit(1);
}, "Inside");
},
"Inside");
}
TEST(InDeathTestChildDeathTest, ReportsDeathTestCorrectlyInThreadSafeStyle) {
GTEST_FLAG_SET(death_test_style, "threadsafe");
EXPECT_FALSE(InDeathTestChild());
EXPECT_DEATH({
EXPECT_DEATH(
{
fprintf(stderr, InDeathTestChild() ? "Inside" : "Outside");
fflush(stderr);
_exit(1);
}, "Inside");
},
"Inside");
}
void DieWithMessage(const char* message) {
@ -1488,8 +1490,7 @@ TEST(ConditionalDeathMacrosSyntaxDeathTest, SingleStatement) {
// doesn't expand into an "if" statement without an "else"
; // NOLINT
if (AlwaysFalse())
ASSERT_DEATH_IF_SUPPORTED(return, "") << "did not die";
if (AlwaysFalse()) ASSERT_DEATH_IF_SUPPORTED(return, "") << "did not die";
if (AlwaysFalse())
; // NOLINT
@ -1509,8 +1510,7 @@ TEST(ConditionalDeathMacrosSyntaxDeathTest, SwitchStatement) {
switch (0)
default:
ASSERT_DEATH_IF_SUPPORTED(_exit(1), "")
<< "exit in default switch handler";
ASSERT_DEATH_IF_SUPPORTED(_exit(1), "") << "exit in default switch handler";
switch (0)
case 0:
@ -1521,8 +1521,6 @@ TEST(ConditionalDeathMacrosSyntaxDeathTest, SwitchStatement) {
// Tests that a test case whose name ends with "DeathTest" works fine
// on Windows.
TEST(NotADeathTest, Test) {
SUCCEED();
}
TEST(NotADeathTest, Test) { SUCCEED(); }
} // namespace

View File

@ -67,8 +67,7 @@ TEST(CxxExceptionDeathTest, PrintsMessageForStdExceptions) {
EXPECT_NONFATAL_FAILURE(EXPECT_DEATH(throw TestException(), ""),
"exceptional message");
// Verifies that the location is mentioned in the failure text.
EXPECT_NONFATAL_FAILURE(EXPECT_DEATH(throw TestException(), ""),
__FILE__);
EXPECT_NONFATAL_FAILURE(EXPECT_DEATH(throw TestException(), ""), __FILE__);
}
#endif // GTEST_HAS_EXCEPTIONS

View File

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

View File

@ -27,7 +27,6 @@
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// Unit test for Google Test test filters.
//
// A user can specify which test(s) in a Google Test program to run via

View File

@ -35,8 +35,8 @@
// This file is #included from gtest-internal.h.
// Do not #include this file anywhere else!
#include "gtest/internal/gtest-filepath.h"
#include "gtest/gtest.h"
#include "gtest/internal/gtest-filepath.h"
#include "src/gtest-internal-inl.h"
#if GTEST_OS_WINDOWS_MOBILE
@ -61,8 +61,8 @@ int remove(const char* path) {
// Windows CE doesn't have the _rmdir C function.
int _rmdir(const char* path) {
FilePath filepath(path);
LPCWSTR wpath = String::AnsiToUtf16(
filepath.RemoveTrailingPathSeparator().c_str());
LPCWSTR wpath =
String::AnsiToUtf16(filepath.RemoveTrailingPathSeparator().c_str());
int ret = RemoveDirectory(wpath) ? 0 : -1;
delete[] wpath;
return ret;
@ -112,8 +112,7 @@ TEST(RemoveDirectoryNameTest, WhenEmptyName) {
// RemoveDirectoryName "afile" -> "afile"
TEST(RemoveDirectoryNameTest, ButNoDirectory) {
EXPECT_EQ("afile",
FilePath("afile").RemoveDirectoryName().string());
EXPECT_EQ("afile", FilePath("afile").RemoveDirectoryName().string());
}
// RemoveDirectoryName "/afile" -> "afile"
@ -130,7 +129,8 @@ TEST(RemoveDirectoryNameTest, WhereThereIsNoFileName) {
// RemoveDirectoryName "adir/afile" -> "afile"
TEST(RemoveDirectoryNameTest, ShouldGiveFileName) {
EXPECT_EQ("afile",
EXPECT_EQ(
"afile",
FilePath("adir" GTEST_PATH_SEP_ "afile").RemoveDirectoryName().string());
}
@ -138,7 +138,8 @@ TEST(RemoveDirectoryNameTest, ShouldGiveFileName) {
TEST(RemoveDirectoryNameTest, ShouldAlsoGiveFileName) {
EXPECT_EQ("afile",
FilePath("adir" GTEST_PATH_SEP_ "subdir" GTEST_PATH_SEP_ "afile")
.RemoveDirectoryName().string());
.RemoveDirectoryName()
.string());
}
#if GTEST_HAS_ALT_PATH_SEP_
@ -195,7 +196,8 @@ TEST(RemoveFileNameTest, GivesDirName) {
TEST(RemoveFileNameTest, GivesDirAndSubDirName) {
EXPECT_EQ("adir" GTEST_PATH_SEP_ "subdir" GTEST_PATH_SEP_,
FilePath("adir" GTEST_PATH_SEP_ "subdir" GTEST_PATH_SEP_ "afile")
.RemoveFileName().string());
.RemoveFileName()
.string());
}
// RemoveFileName "/afile" -> "/"
@ -235,14 +237,14 @@ TEST(RemoveFileNameTest, GivesRootDirForAlternateSeparator) {
#endif
TEST(MakeFileNameTest, GenerateWhenNumberIsZero) {
FilePath actual = FilePath::MakeFileName(FilePath("foo"), FilePath("bar"),
0, "xml");
FilePath actual =
FilePath::MakeFileName(FilePath("foo"), FilePath("bar"), 0, "xml");
EXPECT_EQ("foo" GTEST_PATH_SEP_ "bar.xml", actual.string());
}
TEST(MakeFileNameTest, GenerateFileNameNumberGtZero) {
FilePath actual = FilePath::MakeFileName(FilePath("foo"), FilePath("bar"),
12, "xml");
FilePath actual =
FilePath::MakeFileName(FilePath("foo"), FilePath("bar"), 12, "xml");
EXPECT_EQ("foo" GTEST_PATH_SEP_ "bar_12.xml", actual.string());
}
@ -259,20 +261,19 @@ TEST(MakeFileNameTest, GenerateFileNameWithSlashNumberGtZero) {
}
TEST(MakeFileNameTest, GenerateWhenNumberIsZeroAndDirIsEmpty) {
FilePath actual = FilePath::MakeFileName(FilePath(""), FilePath("bar"),
0, "xml");
FilePath actual =
FilePath::MakeFileName(FilePath(""), FilePath("bar"), 0, "xml");
EXPECT_EQ("bar.xml", actual.string());
}
TEST(MakeFileNameTest, GenerateWhenNumberIsNotZeroAndDirIsEmpty) {
FilePath actual = FilePath::MakeFileName(FilePath(""), FilePath("bar"),
14, "xml");
FilePath actual =
FilePath::MakeFileName(FilePath(""), FilePath("bar"), 14, "xml");
EXPECT_EQ("bar_14.xml", actual.string());
}
TEST(ConcatPathsTest, WorksWhenDirDoesNotEndWithPathSep) {
FilePath actual = FilePath::ConcatPaths(FilePath("foo"),
FilePath("bar.xml"));
FilePath actual = FilePath::ConcatPaths(FilePath("foo"), FilePath("bar.xml"));
EXPECT_EQ("foo" GTEST_PATH_SEP_ "bar.xml", actual.string());
}
@ -283,8 +284,7 @@ TEST(ConcatPathsTest, WorksWhenPath1EndsWithPathSep) {
}
TEST(ConcatPathsTest, Path1BeingEmpty) {
FilePath actual = FilePath::ConcatPaths(FilePath(""),
FilePath("bar.xml"));
FilePath actual = FilePath::ConcatPaths(FilePath(""), FilePath("bar.xml"));
EXPECT_EQ("bar.xml", actual.string());
}
@ -294,8 +294,7 @@ TEST(ConcatPathsTest, Path2BeingEmpty) {
}
TEST(ConcatPathsTest, BothPathBeingEmpty) {
FilePath actual = FilePath::ConcatPaths(FilePath(""),
FilePath(""));
FilePath actual = FilePath::ConcatPaths(FilePath(""), FilePath(""));
EXPECT_EQ("", actual.string());
}
@ -307,16 +306,16 @@ TEST(ConcatPathsTest, Path1ContainsPathSep) {
}
TEST(ConcatPathsTest, Path2ContainsPathSep) {
FilePath actual = FilePath::ConcatPaths(
FilePath("foo" GTEST_PATH_SEP_),
FilePath actual =
FilePath::ConcatPaths(FilePath("foo" GTEST_PATH_SEP_),
FilePath("bar" GTEST_PATH_SEP_ "bar.xml"));
EXPECT_EQ("foo" GTEST_PATH_SEP_ "bar" GTEST_PATH_SEP_ "bar.xml",
actual.string());
}
TEST(ConcatPathsTest, Path2EndsWithPathSep) {
FilePath actual = FilePath::ConcatPaths(FilePath("foo"),
FilePath("bar" GTEST_PATH_SEP_));
FilePath actual =
FilePath::ConcatPaths(FilePath("foo"), FilePath("bar" GTEST_PATH_SEP_));
EXPECT_EQ("foo" GTEST_PATH_SEP_ "bar" GTEST_PATH_SEP_, actual.string());
}
@ -332,7 +331,8 @@ TEST(RemoveTrailingPathSeparatorTest, FileNoSlashString) {
// RemoveTrailingPathSeparator "foo/" -> "foo"
TEST(RemoveTrailingPathSeparatorTest, ShouldRemoveTrailingSeparator) {
EXPECT_EQ("foo",
EXPECT_EQ(
"foo",
FilePath("foo" GTEST_PATH_SEP_).RemoveTrailingPathSeparator().string());
#if GTEST_HAS_ALT_PATH_SEP_
EXPECT_EQ("foo", FilePath("foo/").RemoveTrailingPathSeparator().string());
@ -343,14 +343,15 @@ TEST(RemoveTrailingPathSeparatorTest, ShouldRemoveTrailingSeparator) {
TEST(RemoveTrailingPathSeparatorTest, ShouldRemoveLastSeparator) {
EXPECT_EQ("foo" GTEST_PATH_SEP_ "bar",
FilePath("foo" GTEST_PATH_SEP_ "bar" GTEST_PATH_SEP_)
.RemoveTrailingPathSeparator().string());
.RemoveTrailingPathSeparator()
.string());
}
// RemoveTrailingPathSeparator "foo/bar" -> "foo/bar"
TEST(RemoveTrailingPathSeparatorTest, ShouldReturnUnmodified) {
EXPECT_EQ("foo" GTEST_PATH_SEP_ "bar",
FilePath("foo" GTEST_PATH_SEP_ "bar")
.RemoveTrailingPathSeparator().string());
EXPECT_EQ("foo" GTEST_PATH_SEP_ "bar", FilePath("foo" GTEST_PATH_SEP_ "bar")
.RemoveTrailingPathSeparator()
.string());
}
TEST(DirectoryTest, RootDirectoryExists) {
@ -411,28 +412,29 @@ TEST(NormalizeTest, MultipleConsecutiveSepaparatorsInMidstring) {
FilePath("foo" GTEST_PATH_SEP_ "bar").string());
EXPECT_EQ("foo" GTEST_PATH_SEP_ "bar",
FilePath("foo" GTEST_PATH_SEP_ GTEST_PATH_SEP_ "bar").string());
EXPECT_EQ("foo" GTEST_PATH_SEP_ "bar",
FilePath("foo" GTEST_PATH_SEP_ GTEST_PATH_SEP_
GTEST_PATH_SEP_ "bar").string());
EXPECT_EQ(
"foo" GTEST_PATH_SEP_ "bar",
FilePath("foo" GTEST_PATH_SEP_ GTEST_PATH_SEP_ GTEST_PATH_SEP_ "bar")
.string());
}
// "/bar" == //bar" == "///bar"
TEST(NormalizeTest, MultipleConsecutiveSepaparatorsAtStringStart) {
EXPECT_EQ(GTEST_PATH_SEP_ "bar",
FilePath(GTEST_PATH_SEP_ "bar").string());
EXPECT_EQ(GTEST_PATH_SEP_ "bar", FilePath(GTEST_PATH_SEP_ "bar").string());
EXPECT_EQ(GTEST_PATH_SEP_ "bar",
FilePath(GTEST_PATH_SEP_ GTEST_PATH_SEP_ "bar").string());
EXPECT_EQ(GTEST_PATH_SEP_ "bar",
EXPECT_EQ(
GTEST_PATH_SEP_ "bar",
FilePath(GTEST_PATH_SEP_ GTEST_PATH_SEP_ GTEST_PATH_SEP_ "bar").string());
}
// "foo/" == foo//" == "foo///"
TEST(NormalizeTest, MultipleConsecutiveSepaparatorsAtStringEnd) {
EXPECT_EQ("foo" GTEST_PATH_SEP_,
FilePath("foo" GTEST_PATH_SEP_).string());
EXPECT_EQ("foo" GTEST_PATH_SEP_, FilePath("foo" GTEST_PATH_SEP_).string());
EXPECT_EQ("foo" GTEST_PATH_SEP_,
FilePath("foo" GTEST_PATH_SEP_ GTEST_PATH_SEP_).string());
EXPECT_EQ("foo" GTEST_PATH_SEP_,
EXPECT_EQ(
"foo" GTEST_PATH_SEP_,
FilePath("foo" GTEST_PATH_SEP_ GTEST_PATH_SEP_ GTEST_PATH_SEP_).string());
}
@ -442,12 +444,10 @@ TEST(NormalizeTest, MultipleConsecutiveSepaparatorsAtStringEnd) {
// regardless of their combination (e.g. "foo\" =="foo/\" ==
// "foo\\/").
TEST(NormalizeTest, MixAlternateSeparatorAtStringEnd) {
EXPECT_EQ("foo" GTEST_PATH_SEP_,
FilePath("foo/").string());
EXPECT_EQ("foo" GTEST_PATH_SEP_, FilePath("foo/").string());
EXPECT_EQ("foo" GTEST_PATH_SEP_,
FilePath("foo" GTEST_PATH_SEP_ "/").string());
EXPECT_EQ("foo" GTEST_PATH_SEP_,
FilePath("foo//" GTEST_PATH_SEP_).string());
EXPECT_EQ("foo" GTEST_PATH_SEP_, FilePath("foo//" GTEST_PATH_SEP_).string());
}
#endif
@ -478,15 +478,15 @@ TEST(AssignmentOperatorTest, ConstAssignedToNonConst) {
class DirectoryCreationTest : public Test {
protected:
void SetUp() override {
testdata_path_.Set(FilePath(
TempDir() + GetCurrentExecutableName().string() +
testdata_path_.Set(
FilePath(TempDir() + GetCurrentExecutableName().string() +
"_directory_creation" GTEST_PATH_SEP_ "test" GTEST_PATH_SEP_));
testdata_file_.Set(testdata_path_.RemoveTrailingPathSeparator());
unique_file0_.Set(FilePath::MakeFileName(testdata_path_, FilePath("unique"),
0, "txt"));
unique_file1_.Set(FilePath::MakeFileName(testdata_path_, FilePath("unique"),
1, "txt"));
unique_file0_.Set(
FilePath::MakeFileName(testdata_path_, FilePath("unique"), 0, "txt"));
unique_file1_.Set(
FilePath::MakeFileName(testdata_path_, FilePath("unique"), 1, "txt"));
remove(testdata_file_.c_str());
remove(unique_file0_.c_str());
@ -530,8 +530,8 @@ TEST_F(DirectoryCreationTest, CreateDirectoriesForAlreadyExistingPath) {
}
TEST_F(DirectoryCreationTest, CreateDirectoriesAndUniqueFilename) {
FilePath file_path(FilePath::GenerateUniqueFileName(testdata_path_,
FilePath("unique"), "txt"));
FilePath file_path(FilePath::GenerateUniqueFileName(
testdata_path_, FilePath("unique"), "txt"));
EXPECT_EQ(unique_file0_.string(), file_path.string());
EXPECT_FALSE(file_path.FileOrDirectoryExists()); // file not there
@ -540,8 +540,8 @@ TEST_F(DirectoryCreationTest, CreateDirectoriesAndUniqueFilename) {
CreateTextFile(file_path.c_str());
EXPECT_TRUE(file_path.FileOrDirectoryExists());
FilePath file_path2(FilePath::GenerateUniqueFileName(testdata_path_,
FilePath("unique"), "txt"));
FilePath file_path2(FilePath::GenerateUniqueFileName(
testdata_path_, FilePath("unique"), "txt"));
EXPECT_EQ(unique_file1_.string(), file_path2.string());
EXPECT_FALSE(file_path2.FileOrDirectoryExists()); // file not there
CreateTextFile(file_path2.c_str());
@ -614,11 +614,13 @@ TEST(FilePathTest, IsAbsolutePath) {
EXPECT_FALSE(FilePath("is" GTEST_PATH_SEP_ "relative").IsAbsolutePath());
EXPECT_FALSE(FilePath("").IsAbsolutePath());
#if GTEST_OS_WINDOWS
EXPECT_TRUE(FilePath("c:\\" GTEST_PATH_SEP_ "is_not"
GTEST_PATH_SEP_ "relative").IsAbsolutePath());
EXPECT_TRUE(
FilePath("c:\\" GTEST_PATH_SEP_ "is_not" GTEST_PATH_SEP_ "relative")
.IsAbsolutePath());
EXPECT_FALSE(FilePath("c:foo" GTEST_PATH_SEP_ "bar").IsAbsolutePath());
EXPECT_TRUE(FilePath("c:/" GTEST_PATH_SEP_ "is_not"
GTEST_PATH_SEP_ "relative").IsAbsolutePath());
EXPECT_TRUE(
FilePath("c:/" GTEST_PATH_SEP_ "is_not" GTEST_PATH_SEP_ "relative")
.IsAbsolutePath());
#else
EXPECT_TRUE(FilePath(GTEST_PATH_SEP_ "is_not" GTEST_PATH_SEP_ "relative")
.IsAbsolutePath());

View File

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

View File

@ -27,7 +27,6 @@
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// Unit test for Google Test's --gtest_list_tests flag.
//
// A user can ask Google Test to list all tests that will run
@ -40,38 +39,27 @@
#include "gtest/gtest.h"
// Several different test cases and tests that will be listed.
TEST(Foo, Bar1) {
}
TEST(Foo, Bar1) {}
TEST(Foo, Bar2) {
}
TEST(Foo, Bar2) {}
TEST(Foo, DISABLED_Bar3) {
}
TEST(Foo, DISABLED_Bar3) {}
TEST(Abc, Xyz) {
}
TEST(Abc, Xyz) {}
TEST(Abc, Def) {
}
TEST(Abc, Def) {}
TEST(FooBar, Baz) {
}
TEST(FooBar, Baz) {}
class FooTest : public testing::Test {
};
class FooTest : public testing::Test {};
TEST_F(FooTest, Test1) {
}
TEST_F(FooTest, Test1) {}
TEST_F(FooTest, DISABLED_Test2) {
}
TEST_F(FooTest, DISABLED_Test2) {}
TEST_F(FooTest, Test3) {
}
TEST_F(FooTest, Test3) {}
TEST(FooDeathTest, Test1) {
}
TEST(FooDeathTest, Test1) {}
// A group of value-parameterized tests.
@ -86,64 +74,60 @@ class MyType {
};
// Teaches Google Test how to print a MyType.
void PrintTo(const MyType& x, std::ostream* os) {
*os << x.value();
}
void PrintTo(const MyType& x, std::ostream* os) { *os << x.value(); }
class ValueParamTest : public testing::TestWithParam<MyType> {
};
class ValueParamTest : public testing::TestWithParam<MyType> {};
TEST_P(ValueParamTest, TestA) {
}
TEST_P(ValueParamTest, TestA) {}
TEST_P(ValueParamTest, TestB) {
}
TEST_P(ValueParamTest, TestB) {}
INSTANTIATE_TEST_SUITE_P(
MyInstantiation, ValueParamTest,
testing::Values(MyType("one line"),
MyType("two\nlines"),
MyType("a very\nloooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong line"))); // NOLINT
testing::Values(
MyType("one line"), MyType("two\nlines"),
MyType("a "
"very\nloooooooooooooooooooooooooooooooooooooooooooooooooooooooo"
"ooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo"
"ooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo"
"ooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo"
"ooooong line"))); // NOLINT
// A group of typed tests.
// A deliberately long type name for testing the line-truncating
// behavior when printing a type parameter.
class VeryLoooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooogName { // NOLINT
class
VeryLoooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooogName { // NOLINT
};
template <typename T>
class TypedTest : public testing::Test {
};
class TypedTest : public testing::Test {};
template <typename T, int kSize>
class MyArray {
};
class MyArray {};
typedef testing::Types<VeryLoooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooogName, // NOLINT
int*, MyArray<bool, 42> > MyTypes;
typedef testing::Types<
VeryLoooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooogName, // NOLINT
int*, MyArray<bool, 42> >
MyTypes;
TYPED_TEST_SUITE(TypedTest, MyTypes);
TYPED_TEST(TypedTest, TestA) {
}
TYPED_TEST(TypedTest, TestA) {}
TYPED_TEST(TypedTest, TestB) {
}
TYPED_TEST(TypedTest, TestB) {}
// A group of type-parameterized tests.
template <typename T>
class TypeParamTest : public testing::Test {
};
class TypeParamTest : public testing::Test {};
TYPED_TEST_SUITE_P(TypeParamTest);
TYPED_TEST_P(TypeParamTest, TestA) {
}
TYPED_TEST_P(TypeParamTest, TestA) {}
TYPED_TEST_P(TypeParamTest, TestB) {
}
TYPED_TEST_P(TypeParamTest, TestB) {}
REGISTER_TYPED_TEST_SUITE_P(TypeParamTest, TestA, TestB);

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -32,7 +32,7 @@
// generators objects produce correct parameter sequences and that
// Google Test runtime instantiates correct tests from those sequences.
#include "gtest/gtest.h"
#include "test/googletest-param-test-test.h"
#include <algorithm>
#include <iostream>
@ -42,11 +42,11 @@
#include <string>
#include <vector>
#include "gtest/gtest.h"
#include "src/gtest-internal-inl.h" // for UnitTestOptions
# include "test/googletest-param-test-test.h"
using ::std::vector;
using ::std::sort;
using ::std::vector;
using ::testing::AddGlobalTestEnvironment;
using ::testing::Bool;
@ -85,9 +85,8 @@ void VerifyGenerator(const ParamGenerator<T>& generator,
// We cannot use EXPECT_EQ() here as the values may be tuples,
// which don't support <<.
EXPECT_TRUE(expected_values[i] == *it)
<< "where i is " << i
<< ", expected_values[i] is " << PrintValue(expected_values[i])
<< ", *it is " << PrintValue(*it)
<< "where i is " << i << ", expected_values[i] is "
<< PrintValue(expected_values[i]) << ", *it is " << PrintValue(*it)
<< ", and 'it' is an iterator created with the copy constructor.\n";
++it;
}
@ -105,9 +104,8 @@ void VerifyGenerator(const ParamGenerator<T>& generator,
<< "At element " << i << " when accessing via an iterator "
<< "created with the assignment operator.\n";
EXPECT_TRUE(expected_values[i] == *it)
<< "where i is " << i
<< ", expected_values[i] is " << PrintValue(expected_values[i])
<< ", *it is " << PrintValue(*it)
<< "where i is " << i << ", expected_values[i] is "
<< PrintValue(expected_values[i]) << ", *it is " << PrintValue(*it)
<< ", and 'it' is an iterator created with the copy constructor.\n";
++it;
}
@ -216,8 +214,7 @@ class DogAdder {
DogAdder(const DogAdder& other) : value_(other.value_.c_str()) {}
DogAdder operator=(const DogAdder& other) {
if (this != &other)
value_ = other.value_;
if (this != &other) value_ = other.value_;
return *this;
}
DogAdder operator+(const DogAdder& other) const {
@ -225,9 +222,7 @@ class DogAdder {
msg << value_.c_str() << other.value_.c_str();
return DogAdder(msg.GetString().c_str());
}
bool operator<(const DogAdder& other) const {
return value_ < other.value_;
}
bool operator<(const DogAdder& other) const { return value_ < other.value_; }
const std::string& value() const { return value_; }
private:
@ -372,19 +367,17 @@ TEST(ValuesTest, ValuesWorksForValuesOfCompatibleTypes) {
}
TEST(ValuesTest, ValuesWorksForMaxLengthList) {
const ParamGenerator<int> gen = Values(
10, 20, 30, 40, 50, 60, 70, 80, 90, 100,
110, 120, 130, 140, 150, 160, 170, 180, 190, 200,
210, 220, 230, 240, 250, 260, 270, 280, 290, 300,
310, 320, 330, 340, 350, 360, 370, 380, 390, 400,
410, 420, 430, 440, 450, 460, 470, 480, 490, 500);
const ParamGenerator<int> gen =
Values(10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 110, 120, 130, 140, 150,
160, 170, 180, 190, 200, 210, 220, 230, 240, 250, 260, 270, 280,
290, 300, 310, 320, 330, 340, 350, 360, 370, 380, 390, 400, 410,
420, 430, 440, 450, 460, 470, 480, 490, 500);
const int expected_values[] = {
10, 20, 30, 40, 50, 60, 70, 80, 90, 100,
110, 120, 130, 140, 150, 160, 170, 180, 190, 200,
210, 220, 230, 240, 250, 260, 270, 280, 290, 300,
310, 320, 330, 340, 350, 360, 370, 380, 390, 400,
410, 420, 430, 440, 450, 460, 470, 480, 490, 500};
10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 110, 120, 130,
140, 150, 160, 170, 180, 190, 200, 210, 220, 230, 240, 250, 260,
270, 280, 290, 300, 310, 320, 330, 340, 350, 360, 370, 380, 390,
400, 410, 420, 430, 440, 450, 460, 470, 480, 490, 500};
VerifyGenerator(gen, expected_values);
}
@ -530,7 +523,6 @@ TEST(CombineTest, NonDefaultConstructAssign) {
EXPECT_TRUE(it == gen.end());
}
// Tests that an generator produces correct sequence after being
// assigned from another generator.
TEST(ParamGeneratorTest, AssignmentWorks) {
@ -595,8 +587,11 @@ class TestGenerationEnvironment : public ::testing::Environment {
}
private:
TestGenerationEnvironment() : fixture_constructor_count_(0), set_up_count_(0),
tear_down_count_(0), test_body_count_(0) {}
TestGenerationEnvironment()
: fixture_constructor_count_(0),
set_up_count_(0),
tear_down_count_(0),
test_body_count_(0) {}
int fixture_constructor_count_;
int set_up_count_;
@ -729,8 +724,7 @@ TEST_P(ExternalInstantiationTest, IsMultipleOf33) {
// Tests that a parameterized test case can be instantiated with multiple
// generators.
class MultipleInstantiationTest : public TestWithParam<int> {};
TEST_P(MultipleInstantiationTest, AllowsMultipleInstances) {
}
TEST_P(MultipleInstantiationTest, AllowsMultipleInstances) {}
INSTANTIATE_TEST_SUITE_P(Sequence1, MultipleInstantiationTest, Values(1, 2));
INSTANTIATE_TEST_SUITE_P(Sequence2, MultipleInstantiationTest, Range(3, 5));
@ -839,8 +833,7 @@ TEST(MacroNameing, LookupNames) {
EXPECT_NE( //
know_suite_names.find("FortyTwo/MacroNamingTest"),
know_suite_names.end());
EXPECT_NE(
know_suite_names.find("MacroNamingTestNonParametrized"),
EXPECT_NE(know_suite_names.find("MacroNamingTestNonParametrized"),
know_suite_names.end());
// Check that the expected form of the test name actually exists.
EXPECT_NE( //
@ -1022,6 +1015,7 @@ INSTANTIATE_TEST_SUITE_P(InstantiationWithComments, CommentTest,
class NonParameterizedBaseTest : public ::testing::Test {
public:
NonParameterizedBaseTest() : n_(17) {}
protected:
int n_;
};
@ -1036,9 +1030,7 @@ class ParameterizedDerivedTest : public NonParameterizedBaseTest,
int ParameterizedDerivedTest::global_count_ = 0;
TEST_F(NonParameterizedBaseTest, FixtureIsInitialized) {
EXPECT_EQ(17, n_);
}
TEST_F(NonParameterizedBaseTest, FixtureIsInitialized) { EXPECT_EQ(17, n_); }
TEST_P(ParameterizedDerivedTest, SeesSequence) {
EXPECT_EQ(17, n_);
@ -1049,8 +1041,7 @@ TEST_P(ParameterizedDerivedTest, SeesSequence) {
class ParameterizedDeathTest : public ::testing::TestWithParam<int> {};
TEST_F(ParameterizedDeathTest, GetParamDiesFromTestF) {
EXPECT_DEATH_IF_SUPPORTED(GetParam(),
".* value-parameterized test .*");
EXPECT_DEATH_IF_SUPPORTED(GetParam(), ".* value-parameterized test .*");
}
INSTANTIATE_TEST_SUITE_P(RangeZeroToFive, ParameterizedDerivedTest,

View File

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

View File

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

View File

@ -43,8 +43,8 @@
#include <utility> // For std::pair and std::make_pair.
#include <vector>
#include "gtest/gtest.h"
#include "gtest/gtest-spi.h"
#include "gtest/gtest.h"
#include "src/gtest-internal-inl.h"
using std::make_pair;
@ -372,10 +372,12 @@ TEST(GtestCheckDeathTest, DiesWithCorrectOutputOnFailure) {
#if GTEST_HAS_DEATH_TEST
TEST(GtestCheckDeathTest, LivesSilentlyOnSuccess) {
EXPECT_EXIT({
EXPECT_EXIT(
{
GTEST_CHECK_(true) << "Extra info";
::std::cerr << "Success\n";
exit(0); },
exit(0);
},
::testing::ExitedWithCode(0), "Success");
}
@ -423,9 +425,9 @@ TYPED_TEST(RETest, ImplicitConstructorWorks) {
// Tests that RE's constructors reject invalid regular expressions.
TYPED_TEST(RETest, RejectsInvalidRegex) {
EXPECT_NONFATAL_FAILURE({
const RE invalid(TypeParam("?"));
}, "\"?\" is not a valid POSIX Extended regular expression.");
EXPECT_NONFATAL_FAILURE(
{ const RE invalid(TypeParam("?")); },
"\"?\" is not a valid POSIX Extended regular expression.");
}
// Tests RE::FullMatch().
@ -819,8 +821,7 @@ TEST(MatchRegexAtHeadTest, WorksWhenRegexStartsWithRepetition) {
EXPECT_TRUE(MatchRegexAtHead("a?b", "ab"));
}
TEST(MatchRegexAtHeadTest,
WorksWhenRegexStartsWithRepetionOfEscapeSequence) {
TEST(MatchRegexAtHeadTest, WorksWhenRegexStartsWithRepetionOfEscapeSequence) {
EXPECT_FALSE(MatchRegexAtHead("\\.+a", "abc"));
EXPECT_FALSE(MatchRegexAtHead("\\s?b", " b"));
@ -876,17 +877,14 @@ TEST(RETest, ImplicitConstructorWorks) {
// Tests that RE's constructors reject invalid regular expressions.
TEST(RETest, RejectsInvalidRegex) {
EXPECT_NONFATAL_FAILURE({
const RE normal(NULL);
}, "NULL is not a valid simple regular expression");
EXPECT_NONFATAL_FAILURE({ const RE normal(NULL); },
"NULL is not a valid simple regular expression");
EXPECT_NONFATAL_FAILURE({
const RE normal(".*(\\w+");
}, "'(' is unsupported");
EXPECT_NONFATAL_FAILURE({ const RE normal(".*(\\w+"); },
"'(' is unsupported");
EXPECT_NONFATAL_FAILURE({
const RE invalid("^?");
}, "'?' can only follow a repeatable token");
EXPECT_NONFATAL_FAILURE({ const RE invalid("^?"); },
"'?' can only follow a repeatable token");
}
// Tests RE::FullMatch().
@ -1028,7 +1026,8 @@ TEST(ThreadWithParamTest, ConstructorExecutesThreadFunc) {
TEST(MutexDeathTest, AssertHeldShouldAssertWhenNotLocked) {
// AssertHeld() is flaky only in the presence of multiple threads accessing
// the lock. In this case, the test is robust.
EXPECT_DEATH_IF_SUPPORTED({
EXPECT_DEATH_IF_SUPPORTED(
{
Mutex m;
{ MutexLock lock(&m); }
m.AssertHeld();
@ -1044,8 +1043,8 @@ TEST(MutexTest, AssertHeldShouldNotAssertWhenLocked) {
class AtomicCounterWithMutex {
public:
explicit AtomicCounterWithMutex(Mutex* mutex) :
value_(0), mutex_(mutex), random_(42) {}
explicit AtomicCounterWithMutex(Mutex* mutex)
: value_(0), mutex_(mutex), random_(42) {}
void Increment() {
MutexLock lock(mutex_);
@ -1090,8 +1089,7 @@ class AtomicCounterWithMutex {
};
void CountingThreadFunc(pair<AtomicCounterWithMutex*, int> param) {
for (int i = 0; i < param.second; ++i)
param.first->Increment();
for (int i = 0; i < param.second; ++i) param.first->Increment();
}
// Tests that the mutex only lets one thread at a time to lock it.
@ -1107,14 +1105,12 @@ TEST(MutexTest, OnlyOneThreadCanLockAtATime) {
// Creates and runs kThreadCount threads that increment locked_counter
// kCycleCount times each.
for (int i = 0; i < kThreadCount; ++i) {
counting_threads[i].reset(new ThreadType(&CountingThreadFunc,
make_pair(&locked_counter,
kCycleCount),
counting_threads[i].reset(new ThreadType(
&CountingThreadFunc, make_pair(&locked_counter, kCycleCount),
&threads_can_start));
}
threads_can_start.Notify();
for (int i = 0; i < kThreadCount; ++i)
counting_threads[i]->Join();
for (int i = 0; i < kThreadCount; ++i) counting_threads[i]->Join();
// If the mutex lets more than one thread to increment the counter at a
// time, they are likely to encounter a race condition and have some

View File

@ -27,7 +27,6 @@
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// Google Test - The Google C++ Testing and Mocking Framework
//
// This file tests the universal value printer.
@ -56,30 +55,20 @@
// Some user-defined types for testing the universal value printer.
// An anonymous enum type.
enum AnonymousEnum {
kAE1 = -1,
kAE2 = 1
};
enum AnonymousEnum { kAE1 = -1, kAE2 = 1 };
// An enum without a user-defined printer.
enum EnumWithoutPrinter {
kEWP1 = -2,
kEWP2 = 42
};
enum EnumWithoutPrinter { kEWP1 = -2, kEWP2 = 42 };
// An enum with a << operator.
enum EnumWithStreaming {
kEWS1 = 10
};
enum EnumWithStreaming { kEWS1 = 10 };
std::ostream& operator<<(std::ostream& os, EnumWithStreaming e) {
return os << (e == kEWS1 ? "kEWS1" : "invalid");
}
// An enum with a PrintTo() function.
enum EnumWithPrintTo {
kEWPT1 = 1
};
enum EnumWithPrintTo { kEWPT1 = 1 };
void PrintTo(EnumWithPrintTo e, std::ostream* os) {
*os << (e == kEWPT1 ? "kEWPT1" : "invalid");
@ -108,6 +97,7 @@ template <typename T>
class UnprintableTemplateInGlobal {
public:
UnprintableTemplateInGlobal() : value_() {}
private:
T value_;
};
@ -133,6 +123,7 @@ class UnprintableInFoo {
public:
UnprintableInFoo() : z_(0) { memcpy(xy_, "\xEF\x12\x0\x0\x34\xAB\x0\x0", 8); }
double z() const { return z_; }
private:
char xy_[8];
double z_;
@ -149,8 +140,7 @@ void PrintTo(const PrintableViaPrintTo& x, ::std::ostream* os) {
}
// A type with a user-defined << for printing its pointer.
struct PointerPrintable {
};
struct PointerPrintable {};
::std::ostream& operator<<(::std::ostream& os,
const PointerPrintable* /* x */) {
@ -164,6 +154,7 @@ class PrintableViaPrintToTemplate {
explicit PrintableViaPrintToTemplate(const T& a_value) : value_(a_value) {}
const T& value() const { return value_; }
private:
T value_;
};
@ -180,6 +171,7 @@ class StreamableTemplateInFoo {
StreamableTemplateInFoo() : value_() {}
const T& value() const { return value_; }
private:
T value_;
};
@ -255,7 +247,6 @@ class UniversalPrinter<Wrapper<T>> {
};
} // namespace internal
namespace gtest_printers_test {
using ::std::deque;
@ -350,29 +341,21 @@ TEST(PrintCharTest, PlainChar) {
// signed char.
TEST(PrintCharTest, SignedChar) {
EXPECT_EQ("'\\0'", Print(static_cast<signed char>('\0')));
EXPECT_EQ("'\\xCE' (-50)",
Print(static_cast<signed char>(-50)));
EXPECT_EQ("'\\xCE' (-50)", Print(static_cast<signed char>(-50)));
}
// unsigned char.
TEST(PrintCharTest, UnsignedChar) {
EXPECT_EQ("'\\0'", Print(static_cast<unsigned char>('\0')));
EXPECT_EQ("'b' (98, 0x62)",
Print(static_cast<unsigned char>('b')));
EXPECT_EQ("'b' (98, 0x62)", Print(static_cast<unsigned char>('b')));
}
TEST(PrintCharTest, Char16) {
EXPECT_EQ("U+0041", Print(u'A'));
}
TEST(PrintCharTest, Char16) { EXPECT_EQ("U+0041", Print(u'A')); }
TEST(PrintCharTest, Char32) {
EXPECT_EQ("U+0041", Print(U'A'));
}
TEST(PrintCharTest, Char32) { EXPECT_EQ("U+0041", Print(U'A')); }
#ifdef __cpp_char8_t
TEST(PrintCharTest, Char8) {
EXPECT_EQ("U+0041", Print(u8'A'));
}
TEST(PrintCharTest, Char8) { EXPECT_EQ("U+0041", Print(u8'A')); }
#endif
// Tests printing other simple, built-in types.
@ -516,7 +499,8 @@ TEST(PrintCStringTest, Null) {
// Tests that C strings are escaped properly.
TEST(PrintCStringTest, EscapesProperly) {
const char* p = "'\"?\\\a\b\f\n\r\t\v\x7F\xFF a";
EXPECT_EQ(PrintPointer(p) + " pointing to \"'\\\"?\\\\\\a\\b\\f"
EXPECT_EQ(PrintPointer(p) +
" pointing to \"'\\\"?\\\\\\a\\b\\f"
"\\n\\r\\t\\v\\x7F\\xFF a\"",
Print(p));
}
@ -636,9 +620,11 @@ TEST(PrintWideCStringTest, Null) {
// Tests that wide C strings are escaped properly.
TEST(PrintWideCStringTest, EscapesProperly) {
const wchar_t s[] = {'\'', '"', '?', '\\', '\a', '\b', '\f', '\n', '\r',
'\t', '\v', 0xD3, 0x576, 0x8D3, 0xC74D, ' ', 'a', '\0'};
EXPECT_EQ(PrintPointer(s) + " pointing to L\"'\\\"?\\\\\\a\\b\\f"
const wchar_t s[] = {'\'', '"', '?', '\\', '\a', '\b',
'\f', '\n', '\r', '\t', '\v', 0xD3,
0x576, 0x8D3, 0xC74D, ' ', 'a', '\0'};
EXPECT_EQ(PrintPointer(s) +
" pointing to L\"'\\\"?\\\\\\a\\b\\f"
"\\n\\r\\t\\v\\xD3\\x576\\x8D3\\xC74D a\"",
Print(static_cast<const wchar_t*>(s)));
}
@ -721,8 +707,7 @@ TEST(PrintPointerTest, NonMemberFunctionPointer) {
// standard disallows casting between pointers to functions and
// pointers to objects, and some compilers (e.g. GCC 3.4) enforce
// this limitation.
EXPECT_EQ(
PrintPointer(reinterpret_cast<const void*>(
EXPECT_EQ(PrintPointer(reinterpret_cast<const void*>(
reinterpret_cast<internal::BiggestInt>(&MyFunction))),
Print(&MyFunction));
int (*p)(bool) = NULL; // NOLINT
@ -733,8 +718,7 @@ TEST(PrintPointerTest, NonMemberFunctionPointer) {
// another.
template <typename StringType>
AssertionResult HasPrefix(const StringType& str, const StringType& prefix) {
if (str.find(prefix, 0) == 0)
return AssertionSuccess();
if (str.find(prefix, 0) == 0) return AssertionSuccess();
const bool is_wide_string = sizeof(prefix[0]) > 1;
const char* const begin_string_quote = is_wide_string ? "L\"" : "\"";
@ -761,8 +745,7 @@ TEST(PrintPointerTest, MemberVariablePointer) {
EXPECT_TRUE(HasPrefix(Print(&Foo::value),
Print(sizeof(&Foo::value)) + "-byte object "));
int Foo::*p = NULL; // NOLINT
EXPECT_TRUE(HasPrefix(Print(p),
Print(sizeof(p)) + "-byte object "));
EXPECT_TRUE(HasPrefix(Print(p), Print(sizeof(p)) + "-byte object "));
}
// Tests printing member function pointers. Although they are called
@ -776,8 +759,7 @@ TEST(PrintPointerTest, MemberFunctionPointer) {
HasPrefix(Print(&Foo::MyVirtualMethod),
Print(sizeof((&Foo::MyVirtualMethod))) + "-byte object "));
int (Foo::*p)(char) = NULL; // NOLINT
EXPECT_TRUE(HasPrefix(Print(p),
Print(sizeof(p)) + "-byte object "));
EXPECT_TRUE(HasPrefix(Print(p), Print(sizeof(p)) + "-byte object "));
}
// Tests printing C arrays.
@ -797,10 +779,7 @@ TEST(PrintArrayTest, OneDimensionalArray) {
// Two-dimensional array.
TEST(PrintArrayTest, TwoDimensionalArray) {
int a[2][5] = {
{ 1, 2, 3, 4, 5 },
{ 6, 7, 8, 9, 0 }
};
int a[2][5] = {{1, 2, 3, 4, 5}, {6, 7, 8, 9, 0}};
EXPECT_EQ("{ { 1, 2, 3, 4, 5 }, { 6, 7, 8, 9, 0 } }", PrintArrayHelper(a));
}
@ -834,9 +813,7 @@ TEST(PrintArrayTest, Char8ArrayWithNoTerminatingNul) {
// char8_t array with terminating NUL.
TEST(PrintArrayTest, Char8ArrayWithTerminatingNul) {
const char8_t a[] = u8"\0世界";
EXPECT_EQ(
"u8\"\\0\\xE4\\xB8\\x96\\xE7\\x95\\x8C\"",
PrintArrayHelper(a));
EXPECT_EQ("u8\"\\0\\xE4\\xB8\\x96\\xE7\\x95\\x8C\"", PrintArrayHelper(a));
}
#endif
@ -909,11 +886,14 @@ TEST(PrintStringTest, StringAmbiguousHex) {
// '\x6', '\x6B', or '\x6BA'.
// a hex escaping sequence following by a decimal digit
EXPECT_EQ("\"0\\x12\" \"3\"", Print(::std::string("0\x12" "3")));
EXPECT_EQ("\"0\\x12\" \"3\"", Print(::std::string("0\x12"
"3")));
// a hex escaping sequence following by a hex digit (lower-case)
EXPECT_EQ("\"mm\\x6\" \"bananas\"", Print(::std::string("mm\x6" "bananas")));
EXPECT_EQ("\"mm\\x6\" \"bananas\"", Print(::std::string("mm\x6"
"bananas")));
// a hex escaping sequence following by a hex digit (upper-case)
EXPECT_EQ("\"NOM\\x6\" \"BANANA\"", Print(::std::string("NOM\x6" "BANANA")));
EXPECT_EQ("\"NOM\\x6\" \"BANANA\"", Print(::std::string("NOM\x6"
"BANANA")));
// a hex escaping sequence following by a non-xdigit
EXPECT_EQ("\"!\\x5-!\"", Print(::std::string("!\x5-!")));
}
@ -924,18 +904,20 @@ TEST(PrintStringTest, StringAmbiguousHex) {
TEST(PrintWideStringTest, StringInStdNamespace) {
const wchar_t s[] = L"'\"?\\\a\b\f\n\0\r\t\v\xD3\x576\x8D3\xC74D a";
const ::std::wstring str(s, sizeof(s) / sizeof(wchar_t));
EXPECT_EQ("L\"'\\\"?\\\\\\a\\b\\f\\n\\0\\r\\t\\v"
EXPECT_EQ(
"L\"'\\\"?\\\\\\a\\b\\f\\n\\0\\r\\t\\v"
"\\xD3\\x576\\x8D3\\xC74D a\\0\"",
Print(str));
}
TEST(PrintWideStringTest, StringAmbiguousHex) {
// same for wide strings.
EXPECT_EQ("L\"0\\x12\" L\"3\"", Print(::std::wstring(L"0\x12" L"3")));
EXPECT_EQ("L\"mm\\x6\" L\"bananas\"",
Print(::std::wstring(L"mm\x6" L"bananas")));
EXPECT_EQ("L\"NOM\\x6\" L\"BANANA\"",
Print(::std::wstring(L"NOM\x6" L"BANANA")));
EXPECT_EQ("L\"0\\x12\" L\"3\"", Print(::std::wstring(L"0\x12"
L"3")));
EXPECT_EQ("L\"mm\\x6\" L\"bananas\"", Print(::std::wstring(L"mm\x6"
L"bananas")));
EXPECT_EQ("L\"NOM\\x6\" L\"BANANA\"", Print(::std::wstring(L"NOM\x6"
L"BANANA")));
EXPECT_EQ("L\"!\\x5-!\"", Print(::std::wstring(L"!\x5-!")));
}
#endif // GTEST_HAS_STD_WSTRING
@ -1049,7 +1031,6 @@ TEST(PrintStlContainerTest, NonEmptyDeque) {
EXPECT_EQ("{ 1, 3 }", Print(non_empty));
}
TEST(PrintStlContainerTest, OneElementHashMap) {
::std::unordered_map<int, char> map1;
map1[1] = 'a';
@ -1068,8 +1049,6 @@ TEST(PrintStlContainerTest, HashMultiMap) {
<< " where Print(map1) returns \"" << result << "\".";
}
TEST(PrintStlContainerTest, HashSet) {
::std::unordered_set<int> set1;
set1.insert(1);
@ -1094,8 +1073,8 @@ TEST(PrintStlContainerTest, HashMultiSet) {
ASSERT_NE(isdigit(static_cast<unsigned char>(result[i])), 0);
numbers.push_back(result[i] - '0');
} else {
EXPECT_EQ(expected_pattern[i], result[i]) << " where result is "
<< result;
EXPECT_EQ(expected_pattern[i], result[i])
<< " where result is " << result;
}
}
@ -1105,7 +1084,6 @@ TEST(PrintStlContainerTest, HashMultiSet) {
EXPECT_TRUE(std::equal(a, a + kSize, numbers.begin()));
}
TEST(PrintStlContainerTest, List) {
const std::string a[] = {"hello", "world"};
const list<std::string> strings(a, a + 2);
@ -1146,7 +1124,6 @@ TEST(PrintStlContainerTest, MultiSet) {
EXPECT_EQ("{ 1, 1, 1, 2, 5 }", Print(set1));
}
TEST(PrintStlContainerTest, SinglyLinkedList) {
int a[] = {9, 2, 8};
const std::forward_list<int> ints(a, a + 3);
@ -1168,8 +1145,10 @@ TEST(PrintStlContainerTest, Vector) {
TEST(PrintStlContainerTest, LongSequence) {
const int a[100] = {1, 2, 3};
const vector<int> v(a, a + 100);
EXPECT_EQ("{ 1, 2, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, "
"0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, ... }", Print(v));
EXPECT_EQ(
"{ 1, 2, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, "
"0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, ... }",
Print(v));
}
TEST(PrintStlContainerTest, NestedContainer) {
@ -1249,14 +1228,12 @@ TEST(PrintStdTupleTest, VariousSizes) {
// Nested tuples.
TEST(PrintStdTupleTest, NestedTuple) {
::std::tuple< ::std::tuple<int, bool>, char> nested(
::std::make_tuple(5, true), 'a');
::std::tuple<::std::tuple<int, bool>, char> nested(::std::make_tuple(5, true),
'a');
EXPECT_EQ("((5, true), 'a' (97, 0x61))", Print(nested));
}
TEST(PrintNullptrT, Basic) {
EXPECT_EQ("(nullptr)", Print(nullptr));
}
TEST(PrintNullptrT, Basic) { EXPECT_EQ("(nullptr)", Print(nullptr)); }
TEST(PrintReferenceWrapper, Printable) {
int x = 5;
@ -1280,8 +1257,7 @@ TEST(PrintReferenceWrapper, Unprintable) {
// Unprintable types in the global namespace.
TEST(PrintUnprintableTypeTest, InGlobalNamespace) {
EXPECT_EQ("1-byte object <00>",
Print(UnprintableTemplateInGlobal<char>()));
EXPECT_EQ("1-byte object <00>", Print(UnprintableTemplateInGlobal<char>()));
}
// Unprintable types in a user namespace.
@ -1298,7 +1274,8 @@ struct Big {
};
TEST(PrintUnpritableTypeTest, BigObject) {
EXPECT_EQ("257-byte object <00-00 00-00 00-00 00-00 00-00 00-00 "
EXPECT_EQ(
"257-byte object <00-00 00-00 00-00 00-00 00-00 00-00 "
"00-00 00-00 00-00 00-00 00-00 00-00 00-00 00-00 00-00 00-00 "
"00-00 00-00 00-00 00-00 00-00 00-00 00-00 00-00 00-00 00-00 "
"00-00 00-00 00-00 00-00 00-00 00-00 ... 00-00 00-00 00-00 "
@ -1348,8 +1325,7 @@ TEST(PrintStreamableTypeTest, PathLikeInUserNamespace) {
// Tests printing user-defined types that have a PrintTo() function.
TEST(PrintPrintableTypeTest, InUserNamespace) {
EXPECT_EQ("PrintableViaPrintTo: 0",
Print(::foo::PrintableViaPrintTo()));
EXPECT_EQ("PrintableViaPrintTo: 0", Print(::foo::PrintableViaPrintTo()));
}
// Tests printing a pointer to a user-defined type that has a <<
@ -1371,15 +1347,13 @@ TEST(PrintReferenceTest, PrintsAddressAndValue) {
int n = 5;
EXPECT_EQ("@" + PrintPointer(&n) + " 5", PrintByRef(n));
int a[2][3] = {
{ 0, 1, 2 },
{ 3, 4, 5 }
};
int a[2][3] = {{0, 1, 2}, {3, 4, 5}};
EXPECT_EQ("@" + PrintPointer(a) + " { { 0, 1, 2 }, { 3, 4, 5 } }",
PrintByRef(a));
const ::foo::UnprintableInFoo x;
EXPECT_EQ("@" + PrintPointer(&x) + " 16-byte object "
EXPECT_EQ("@" + PrintPointer(&x) +
" 16-byte object "
"<EF-12 00-00 34-AB 00-00 00-00 00-00 00-00 00-00>",
PrintByRef(x));
}
@ -1396,33 +1370,29 @@ TEST(PrintReferenceTest, HandlesFunctionPointer) {
// this limitation.
const std::string fp_string = PrintPointer(reinterpret_cast<const void*>(
reinterpret_cast<internal::BiggestInt>(fp)));
EXPECT_EQ("@" + fp_pointer_string + " " + fp_string,
PrintByRef(fp));
EXPECT_EQ("@" + fp_pointer_string + " " + fp_string, PrintByRef(fp));
}
// Tests that the universal printer prints a member function pointer
// passed by reference.
TEST(PrintReferenceTest, HandlesMemberFunctionPointer) {
int (Foo::*p)(char ch) = &Foo::MyMethod;
EXPECT_TRUE(HasPrefix(
PrintByRef(p),
"@" + PrintPointer(reinterpret_cast<const void*>(&p)) + " " +
Print(sizeof(p)) + "-byte object "));
EXPECT_TRUE(HasPrefix(PrintByRef(p),
"@" + PrintPointer(reinterpret_cast<const void*>(&p)) +
" " + Print(sizeof(p)) + "-byte object "));
char (Foo::*p2)(int n) = &Foo::MyVirtualMethod;
EXPECT_TRUE(HasPrefix(
PrintByRef(p2),
"@" + PrintPointer(reinterpret_cast<const void*>(&p2)) + " " +
Print(sizeof(p2)) + "-byte object "));
EXPECT_TRUE(HasPrefix(PrintByRef(p2),
"@" + PrintPointer(reinterpret_cast<const void*>(&p2)) +
" " + Print(sizeof(p2)) + "-byte object "));
}
// Tests that the universal printer prints a member variable pointer
// passed by reference.
TEST(PrintReferenceTest, HandlesMemberVariablePointer) {
int Foo::*p = &Foo::value; // NOLINT
EXPECT_TRUE(HasPrefix(
PrintByRef(p),
"@" + PrintPointer(&p) + " " + Print(sizeof(p)) + "-byte object "));
EXPECT_TRUE(HasPrefix(PrintByRef(p), "@" + PrintPointer(&p) + " " +
Print(sizeof(p)) + "-byte object "));
}
// Tests that FormatForComparisonFailureMessage(), which is used to print
@ -1431,8 +1401,7 @@ TEST(PrintReferenceTest, HandlesMemberVariablePointer) {
// scalar
TEST(FormatForComparisonFailureMessageTest, WorksForScalar) {
EXPECT_STREQ("123",
FormatForComparisonFailureMessage(123, 124).c_str());
EXPECT_STREQ("123", FormatForComparisonFailureMessage(123, 124).c_str());
}
// non-char pointer
@ -1447,8 +1416,7 @@ TEST(FormatForComparisonFailureMessageTest, FormatsNonCharArrayAsPointer) {
// In expression 'array == x', 'array' is compared by pointer.
// Therefore we want to print an array operand as a pointer.
int n[] = {1, 2, 3};
EXPECT_EQ(PrintPointer(n),
FormatForComparisonFailureMessage(n, n).c_str());
EXPECT_EQ(PrintPointer(n), FormatForComparisonFailureMessage(n, n).c_str());
}
// Tests formatting a char pointer when it's compared with another pointer.
@ -1464,8 +1432,7 @@ TEST(FormatForComparisonFailureMessageTest, WorksForCharPointerVsPointer) {
// const char*
const char* s = "hello";
EXPECT_EQ(PrintPointer(s),
FormatForComparisonFailureMessage(s, s).c_str());
EXPECT_EQ(PrintPointer(s), FormatForComparisonFailureMessage(s, s).c_str());
// char*
char ch = 'a';
@ -1482,8 +1449,7 @@ TEST(FormatForComparisonFailureMessageTest, WorksForWCharPointerVsPointer) {
// const wchar_t*
const wchar_t* s = L"hello";
EXPECT_EQ(PrintPointer(s),
FormatForComparisonFailureMessage(s, s).c_str());
EXPECT_EQ(PrintPointer(s), FormatForComparisonFailureMessage(s, s).c_str());
// wchar_t*
wchar_t ch = L'a';
@ -1584,9 +1550,7 @@ TEST(FormatForComparisonFailureMessageTest, WorksForWCharArrayVsStdWString) {
EXPECT_TRUE(PrintToString(value) == (expected_string)) \
<< " where " #value " prints as " << (PrintToString(value))
TEST(PrintToStringTest, WorksForScalar) {
EXPECT_PRINT_TO_STRING_(123, "123");
}
TEST(PrintToStringTest, WorksForScalar) { EXPECT_PRINT_TO_STRING_(123, "123"); }
TEST(PrintToStringTest, WorksForPointerToConstChar) {
const char* p = "hello";
@ -1677,7 +1641,8 @@ TEST(IsValidUTF8Test, IllFormedUTF8) {
// Non-shortest sequences.
{"\xE0\x80\x80", "\"\\xE0\\x80\\x80\""},
{"\xf0\x80\x80\x80", "\"\\xF0\\x80\\x80\\x80\""},
// Last valid code point before surrogate range, should be printed as text,
// Last valid code point before surrogate range, should be printed as
// text,
// too.
{"\xED\x9F\xBF", "\"\\xED\\x9F\\xBF\"\n As Text: \"\""},
// Start of surrogate lead. Surrogates are not printed as text.
@ -1690,10 +1655,10 @@ TEST(IsValidUTF8Test, IllFormedUTF8) {
{"\xED\xAF\xBF", "\"\\xED\\xAF\\xBF\""},
// Mid-point of surrogate trail.
{"\xED\xB3\xBF", "\"\\xED\\xB3\\xBF\""},
// First valid code point after surrogate range, should be printed as text,
// First valid code point after surrogate range, should be printed as
// text,
// too.
{"\xEE\x80\x80", "\"\\xEE\\x80\\x80\"\n As Text: \"\""}
};
{"\xEE\x80\x80", "\"\\xEE\\x80\\x80\"\n As Text: \"\""}};
for (int i = 0; i < int(sizeof(kTestdata) / sizeof(kTestdata[0])); ++i) {
EXPECT_PRINT_TO_STRING_(kTestdata[i][0], kTestdata[i][1]);
@ -1844,15 +1809,15 @@ TEST(UniversalTersePrintTupleFieldsToStringsTestWithStd, PrintsEmptyTuple) {
}
TEST(UniversalTersePrintTupleFieldsToStringsTestWithStd, PrintsOneTuple) {
Strings result = UniversalTersePrintTupleFieldsToStrings(
::std::make_tuple(1));
Strings result =
UniversalTersePrintTupleFieldsToStrings(::std::make_tuple(1));
ASSERT_EQ(1u, result.size());
EXPECT_EQ("1", result[0]);
}
TEST(UniversalTersePrintTupleFieldsToStringsTestWithStd, PrintsTwoTuple) {
Strings result = UniversalTersePrintTupleFieldsToStrings(
::std::make_tuple(1, 'a'));
Strings result =
UniversalTersePrintTupleFieldsToStrings(::std::make_tuple(1, 'a'));
ASSERT_EQ(2u, result.size());
EXPECT_EQ("1", result[0]);
EXPECT_EQ("'a' (97, 0x61)", result[1]);

View File

@ -27,23 +27,18 @@
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include "gtest/gtest.h"
class SetupFailTest : public ::testing::Test {
protected:
static void SetUpTestSuite() {
ASSERT_EQ("", "SET_UP_FAIL");
}
static void SetUpTestSuite() { ASSERT_EQ("", "SET_UP_FAIL"); }
};
TEST_F(SetupFailTest, NoopPassingTest) {}
class TearDownFailTest : public ::testing::Test {
protected:
static void TearDownTestSuite() {
ASSERT_EQ("", "TEAR_DOWN_FAIL");
}
static void TearDownTestSuite() { ASSERT_EQ("", "TEAR_DOWN_FAIL"); }
};
TEST_F(TearDownFailTest, NoopPassingTest) {}

View File

@ -27,7 +27,6 @@
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// Verifies that test shuffling works.
#include "gtest/gtest.h"

View File

@ -28,7 +28,6 @@
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include "gtest/gtest-test-part.h"
#include "gtest/gtest.h"
using testing::Message;
@ -52,17 +51,14 @@ class TestPartResultTest : public Test {
TestPartResult r1_, r2_, r3_, r4_;
};
TEST_F(TestPartResultTest, ConstructorWorks) {
Message message;
message << "something is terribly wrong";
message << static_cast<const char*>(testing::internal::kStackTraceMarker);
message << "some unimportant stack trace";
const TestPartResult result(TestPartResult::kNonFatalFailure,
"some_file.cc",
42,
message.GetString().c_str());
const TestPartResult result(TestPartResult::kNonFatalFailure, "some_file.cc",
42, message.GetString().c_str());
EXPECT_EQ(TestPartResult::kNonFatalFailure, result.type());
EXPECT_STREQ("some_file.cc", result.file_name());
@ -72,9 +68,7 @@ TEST_F(TestPartResultTest, ConstructorWorks) {
}
TEST_F(TestPartResultTest, ResultAccessorsWork) {
const TestPartResult success(TestPartResult::kSuccess,
"file.cc",
42,
const TestPartResult success(TestPartResult::kSuccess, "file.cc", 42,
"message");
EXPECT_TRUE(success.passed());
EXPECT_FALSE(success.failed());
@ -83,19 +77,15 @@ TEST_F(TestPartResultTest, ResultAccessorsWork) {
EXPECT_FALSE(success.skipped());
const TestPartResult nonfatal_failure(TestPartResult::kNonFatalFailure,
"file.cc",
42,
"message");
"file.cc", 42, "message");
EXPECT_FALSE(nonfatal_failure.passed());
EXPECT_TRUE(nonfatal_failure.failed());
EXPECT_TRUE(nonfatal_failure.nonfatally_failed());
EXPECT_FALSE(nonfatal_failure.fatally_failed());
EXPECT_FALSE(nonfatal_failure.skipped());
const TestPartResult fatal_failure(TestPartResult::kFatalFailure,
"file.cc",
42,
"message");
const TestPartResult fatal_failure(TestPartResult::kFatalFailure, "file.cc",
42, "message");
EXPECT_FALSE(fatal_failure.passed());
EXPECT_TRUE(fatal_failure.failed());
EXPECT_FALSE(fatal_failure.nonfatally_failed());

View File

@ -27,19 +27,19 @@
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// Tests Google Test's throw-on-failure mode with exceptions disabled.
//
// This program must be compiled with exceptions disabled. It will be
// invoked by googletest-throw-on-failure-test.py, and is expected to exit
// with non-zero in the throw-on-failure mode or 0 otherwise.
#include "gtest/gtest.h"
#include <stdio.h> // for fflush, fprintf, NULL, etc.
#include <stdlib.h> // for exit
#include <exception> // for set_terminate
#include "gtest/gtest.h"
// This terminate handler aborts the program using exit() rather than abort().
// This avoids showing pop-ups on Windows systems and core dumps on Unix-like
// ones.

View File

@ -27,7 +27,6 @@
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include "gtest/gtest.h"
TEST(DummyTest, Dummy) {
@ -37,6 +36,4 @@ TEST(DummyTest, Dummy) {
// testing::InitGoogleTest() being called first.
}
int main() {
return RUN_ALL_TESTS();
}
int main() { return RUN_ALL_TESTS(); }

View File

@ -27,11 +27,10 @@
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include <vector>
#include "test/gtest-typed-test_test.h"
#include "gtest/gtest.h"
#include "test/gtest-typed-test_test.h"
// Tests that the same type-parameterized test case can be
// instantiated in different translation units linked together.

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