Merge branch 'main' into promote-inclusive-behavior

pull/3779/head
Brad Messer 3 years ago committed by GitHub
commit 9e71237221
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
  1. 1
      CONTRIBUTORS
  2. 21
      docs/advanced.md
  3. 4
      docs/reference/testing.md
  4. 167
      googlemock/include/gmock/gmock-actions.h
  5. 4
      googlemock/include/gmock/gmock-cardinalities.h
  6. 2
      googlemock/include/gmock/gmock-function-mocker.h
  7. 596
      googlemock/include/gmock/gmock-more-actions.h
  8. 11
      googlemock/include/gmock/gmock-more-matchers.h
  9. 208
      googlemock/include/gmock/gmock-spec-builders.h
  10. 71
      googlemock/include/gmock/internal/gmock-internal-utils.h
  11. 23
      googlemock/include/gmock/internal/gmock-port.h
  12. 9
      googlemock/src/gmock-cardinalities.cc
  13. 24
      googlemock/src/gmock-internal-utils.cc
  14. 1
      googlemock/src/gmock-matchers.cc
  15. 62
      googlemock/src/gmock-spec-builders.cc
  16. 2
      googlemock/src/gmock.cc
  17. 4
      googlemock/src/gmock_main.cc
  18. 168
      googlemock/test/gmock-actions_test.cc
  19. 108
      googlemock/test/gmock-cardinalities_test.cc
  20. 83
      googlemock/test/gmock-function-mocker_test.cc
  21. 143
      googlemock/test/gmock-internal-utils_test.cc
  22. 808
      googlemock/test/gmock-matchers_test.cc
  23. 33
      googlemock/test/gmock-more-actions_test.cc
  24. 20
      googlemock/test/gmock-nice-strict_test.cc
  25. 2
      googlemock/test/gmock-port_test.cc
  26. 3
      googlemock/test/gmock-pp-string_test.cc
  27. 909
      googlemock/test/gmock-spec-builders_test.cc
  28. 2
      googlemock/test/gmock_ex_test.cc
  29. 1
      googlemock/test/gmock_leak_test_.cc
  30. 1
      googlemock/test/gmock_link2_test.cc
  31. 1
      googlemock/test/gmock_link_test.cc
  32. 34
      googlemock/test/gmock_link_test.h
  33. 63
      googlemock/test/gmock_output_test_.cc
  34. 53
      googlemock/test/gmock_stress_test.cc
  35. 2
      googlemock/test/gmock_test.cc
  36. 77
      googletest/include/gtest/gtest-death-test.h
  37. 55
      googletest/include/gtest/gtest-matchers.h
  38. 22
      googletest/include/gtest/gtest-message.h
  39. 71
      googletest/include/gtest/gtest-param-test.h
  40. 38
      googletest/include/gtest/gtest-printers.h
  41. 111
      googletest/include/gtest/gtest-spi.h
  42. 2
      googletest/include/gtest/gtest-test-part.h
  43. 34
      googletest/include/gtest/gtest-typed-test.h
  44. 268
      googletest/include/gtest/gtest.h
  45. 188
      googletest/include/gtest/gtest_pred_impl.h
  46. 4
      googletest/include/gtest/gtest_prod.h
  47. 54
      googletest/include/gtest/internal/gtest-death-test-internal.h
  48. 11
      googletest/include/gtest/internal/gtest-filepath.h
  49. 238
      googletest/include/gtest/internal/gtest-internal.h
  50. 120
      googletest/include/gtest/internal/gtest-param-util.h
  51. 98
      googletest/include/gtest/internal/gtest-port-arch.h
  52. 594
      googletest/include/gtest/internal/gtest-port.h
  53. 12
      googletest/include/gtest/internal/gtest-string.h
  54. 17
      googletest/include/gtest/internal/gtest-type-util.h
  55. 8
      googletest/samples/prime_tables.h
  56. 4
      googletest/samples/sample1.cc
  57. 8
      googletest/samples/sample10_unittest.cc
  58. 11
      googletest/samples/sample1_unittest.cc
  59. 2
      googletest/samples/sample2.cc
  60. 1
      googletest/samples/sample2.h
  61. 4
      googletest/samples/sample2_unittest.cc
  62. 9
      googletest/samples/sample3-inl.h
  63. 11
      googletest/samples/sample3_unittest.cc
  64. 14
      googletest/samples/sample4.cc
  65. 2
      googletest/samples/sample4_unittest.cc
  66. 13
      googletest/samples/sample5_unittest.cc
  67. 5
      googletest/samples/sample6_unittest.cc
  68. 6
      googletest/samples/sample7_unittest.cc
  69. 6
      googletest/samples/sample8_unittest.cc
  70. 27
      googletest/samples/sample9_unittest.cc
  71. 2
      googletest/src/gtest-all.cc
  72. 10
      googletest/src/gtest-assertion-result.cc
  73. 433
      googletest/src/gtest-death-test.cc
  74. 78
      googletest/src/gtest-filepath.cc
  75. 65
      googletest/src/gtest-internal-inl.h
  76. 5
      googletest/src/gtest-matchers.cc
  77. 292
      googletest/src/gtest-port.cc
  78. 77
      googletest/src/gtest-printers.cc
  79. 19
      googletest/src/gtest-test-part.cc
  80. 7
      googletest/src/gtest-typed-test.cc
  81. 839
      googletest/src/gtest.cc
  82. 5
      googletest/src/gtest_main.cc
  83. 19
      googletest/test/googletest-break-on-failure-unittest_.cc
  84. 16
      googletest/test/googletest-catch-exceptions-test_.cc
  85. 4
      googletest/test/googletest-color-test_.cc
  86. 342
      googletest/test/googletest-death-test-test.cc
  87. 21
      googletest/test/googletest-death-test_ex_test.cc
  88. 4
      googletest/test/googletest-env-var-test_.cc
  89. 3
      googletest/test/googletest-failfast-unittest_.cc
  90. 174
      googletest/test/googletest-filepath-test.cc
  91. 71
      googletest/test/googletest-filter-unittest_.cc
  92. 4
      googletest/test/googletest-json-outfiles-test.py
  93. 64
      googletest/test/googletest-json-output-unittest.py
  94. 90
      googletest/test/googletest-list-tests-unittest_.cc
  95. 35
      googletest/test/googletest-listener-test.cc
  96. 18
      googletest/test/googletest-message-test.cc
  97. 43
      googletest/test/googletest-options-test.cc
  98. 251
      googletest/test/googletest-output-test_.cc
  99. 8
      googletest/test/googletest-param-test-invalid-name1-test_.cc
  100. 11
      googletest/test/googletest-param-test-invalid-name2-test_.cc
  101. Some files were not shown because too many files have changed in this diff Show More

@ -56,6 +56,7 @@ Russ Rufer <russ@pentad.com>
Sean Mcafee <eefacm@gmail.com>
Sigurður Ásgeirsson <siggi@google.com>
Sverre Sundsdal <sundsdal@gmail.com>
Szymon Sobik <sobik.szymon@gmail.com>
Takeshi Yoshino <tyoshino@google.com>
Tracy Bialik <tracy@pentad.com>
Vadim Berman <vadimb@google.com>

@ -839,7 +839,7 @@ will output XML like this:
```xml
...
<testcase name="MinAndMaxWidgets" status="run" time="0.006" classname="WidgetUsageTest" MaximumWidgets="12" MinimumWidgets="9" />
<testcase name="MinAndMaxWidgets" file="test.cpp" line="1" status="run" time="0.006" classname="WidgetUsageTest" MaximumWidgets="12" MinimumWidgets="9" />
...
```
@ -2082,15 +2082,15 @@ could generate this report:
<?xml version="1.0" encoding="UTF-8"?>
<testsuites tests="3" failures="1" errors="0" time="0.035" timestamp="2011-10-31T18:52:42" name="AllTests">
<testsuite name="MathTest" tests="2" failures="1" errors="0" time="0.015">
<testcase name="Addition" status="run" time="0.007" classname="">
<testcase name="Addition" file="test.cpp" line="1" status="run" time="0.007" classname="">
<failure message="Value of: add(1, 1)&#x0A; Actual: 3&#x0A;Expected: 2" type="">...</failure>
<failure message="Value of: add(1, -1)&#x0A; Actual: 1&#x0A;Expected: 0" type="">...</failure>
</testcase>
<testcase name="Subtraction" status="run" time="0.005" classname="">
<testcase name="Subtraction" file="test.cpp" line="2" status="run" time="0.005" classname="">
</testcase>
</testsuite>
<testsuite name="LogicTest" tests="1" failures="0" errors="0" time="0.005">
<testcase name="NonContradiction" status="run" time="0.005" classname="">
<testcase name="NonContradiction" file="test.cpp" line="3" status="run" time="0.005" classname="">
</testcase>
</testsuite>
</testsuites>
@ -2108,6 +2108,9 @@ Things to note:
* The `timestamp` attribute records the local date and time of the test
execution.
* The `file` and `line` attributes record the source file location, where the
test was defined.
* Each `<failure>` element corresponds to a single failed googletest
assertion.
@ -2147,6 +2150,8 @@ The report format conforms to the following JSON Schema:
"type": "object",
"properties": {
"name": { "type": "string" },
"file": { "type": "string" },
"line": { "type": "integer" },
"status": {
"type": "string",
"enum": ["RUN", "NOTRUN"]
@ -2224,6 +2229,8 @@ message TestCase {
message TestInfo {
string name = 1;
string file = 6;
int32 line = 7;
enum Status {
RUN = 0;
NOTRUN = 1;
@ -2267,6 +2274,8 @@ could generate this report:
"testsuite": [
{
"name": "Addition",
"file": "test.cpp",
"line": 1,
"status": "RUN",
"time": "0.007s",
"classname": "",
@ -2283,6 +2292,8 @@ could generate this report:
},
{
"name": "Subtraction",
"file": "test.cpp",
"line": 2,
"status": "RUN",
"time": "0.005s",
"classname": ""
@ -2298,6 +2309,8 @@ could generate this report:
"testsuite": [
{
"name": "NonContradiction",
"file": "test.cpp",
"line": 3,
"status": "RUN",
"time": "0.005s",
"classname": ""

@ -518,8 +518,8 @@ Logs a property for the current test, test suite, or entire invocation of the
test program. Only the last value for a given key is logged.
The key must be a valid XML attribute name, and cannot conflict with the ones
already used by GoogleTest (`name`, `status`, `time`, `classname`, `type_param`,
and `value_param`).
already used by GoogleTest (`name`, `file`, `line`, `status`, `time`,
`classname`, `type_param`, and `value_param`).
`RecordProperty` is `public static` so it can be called from utility functions
that are not members of the test fixture.

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

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

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

@ -129,170 +129,207 @@
// Declares the template parameters.
#define GMOCK_INTERNAL_DECL_HAS_1_TEMPLATE_PARAMS(kind0, name0) kind0 name0
#define GMOCK_INTERNAL_DECL_HAS_2_TEMPLATE_PARAMS(kind0, name0, kind1, \
name1) kind0 name0, kind1 name1
#define GMOCK_INTERNAL_DECL_HAS_2_TEMPLATE_PARAMS(kind0, name0, kind1, name1) \
kind0 name0, kind1 name1
#define GMOCK_INTERNAL_DECL_HAS_3_TEMPLATE_PARAMS(kind0, name0, kind1, name1, \
kind2, name2) kind0 name0, kind1 name1, kind2 name2
kind2, name2) \
kind0 name0, kind1 name1, kind2 name2
#define GMOCK_INTERNAL_DECL_HAS_4_TEMPLATE_PARAMS(kind0, name0, kind1, name1, \
kind2, name2, kind3, name3) kind0 name0, kind1 name1, kind2 name2, \
kind3 name3
#define GMOCK_INTERNAL_DECL_HAS_5_TEMPLATE_PARAMS(kind0, name0, kind1, name1, \
kind2, name2, kind3, name3, kind4, name4) kind0 name0, kind1 name1, \
kind2 name2, kind3 name3, kind4 name4
kind2, name2, kind3, name3) \
kind0 name0, kind1 name1, kind2 name2, kind3 name3
#define GMOCK_INTERNAL_DECL_HAS_5_TEMPLATE_PARAMS( \
kind0, name0, kind1, name1, kind2, name2, kind3, name3, kind4, name4) \
kind0 name0, kind1 name1, kind2 name2, kind3 name3, kind4 name4
#define GMOCK_INTERNAL_DECL_HAS_6_TEMPLATE_PARAMS(kind0, name0, kind1, name1, \
kind2, name2, kind3, name3, kind4, name4, kind5, name5) kind0 name0, \
kind1 name1, kind2 name2, kind3 name3, kind4 name4, kind5 name5
#define GMOCK_INTERNAL_DECL_HAS_7_TEMPLATE_PARAMS(kind0, name0, kind1, name1, \
kind2, name2, kind3, name3, kind4, name4, kind5, name5, kind6, \
name6) kind0 name0, kind1 name1, kind2 name2, kind3 name3, kind4 name4, \
kind5 name5, kind6 name6
#define GMOCK_INTERNAL_DECL_HAS_8_TEMPLATE_PARAMS(kind0, name0, kind1, name1, \
kind2, name2, kind3, name3, kind4, name4, kind5, name5, kind6, name6, \
kind7, name7) kind0 name0, kind1 name1, kind2 name2, kind3 name3, \
kind4 name4, kind5 name5, kind6 name6, kind7 name7
#define GMOCK_INTERNAL_DECL_HAS_9_TEMPLATE_PARAMS(kind0, name0, kind1, name1, \
kind2, name2, kind3, name3, kind4, name4, kind5, name5, kind6, name6, \
kind7, name7, kind8, name8) kind0 name0, kind1 name1, kind2 name2, \
kind3 name3, kind4 name4, kind5 name5, kind6 name6, kind7 name7, \
kind8 name8
#define GMOCK_INTERNAL_DECL_HAS_10_TEMPLATE_PARAMS(kind0, name0, kind1, \
name1, kind2, name2, kind3, name3, kind4, name4, kind5, name5, kind6, \
name6, kind7, name7, kind8, name8, kind9, name9) kind0 name0, \
kind1 name1, kind2 name2, kind3 name3, kind4 name4, kind5 name5, \
kind6 name6, kind7 name7, kind8 name8, kind9 name9
kind2, name2, kind3, name3, \
kind4, name4, kind5, name5) \
kind0 name0, kind1 name1, kind2 name2, kind3 name3, kind4 name4, kind5 name5
#define GMOCK_INTERNAL_DECL_HAS_7_TEMPLATE_PARAMS( \
kind0, name0, kind1, name1, kind2, name2, kind3, name3, kind4, name4, \
kind5, name5, kind6, name6) \
kind0 name0, kind1 name1, kind2 name2, kind3 name3, kind4 name4, \
kind5 name5, kind6 name6
#define GMOCK_INTERNAL_DECL_HAS_8_TEMPLATE_PARAMS( \
kind0, name0, kind1, name1, kind2, name2, kind3, name3, kind4, name4, \
kind5, name5, kind6, name6, kind7, name7) \
kind0 name0, kind1 name1, kind2 name2, kind3 name3, kind4 name4, \
kind5 name5, kind6 name6, kind7 name7
#define GMOCK_INTERNAL_DECL_HAS_9_TEMPLATE_PARAMS( \
kind0, name0, kind1, name1, kind2, name2, kind3, name3, kind4, name4, \
kind5, name5, kind6, name6, kind7, name7, kind8, name8) \
kind0 name0, kind1 name1, kind2 name2, kind3 name3, kind4 name4, \
kind5 name5, kind6 name6, kind7 name7, kind8 name8
#define GMOCK_INTERNAL_DECL_HAS_10_TEMPLATE_PARAMS( \
kind0, name0, kind1, name1, kind2, name2, kind3, name3, kind4, name4, \
kind5, name5, kind6, name6, kind7, name7, kind8, name8, kind9, name9) \
kind0 name0, kind1 name1, kind2 name2, kind3 name3, kind4 name4, \
kind5 name5, kind6 name6, kind7 name7, kind8 name8, kind9 name9
// Lists the template parameters.
#define GMOCK_INTERNAL_LIST_HAS_1_TEMPLATE_PARAMS(kind0, name0) name0
#define GMOCK_INTERNAL_LIST_HAS_2_TEMPLATE_PARAMS(kind0, name0, kind1, \
name1) name0, name1
#define GMOCK_INTERNAL_LIST_HAS_2_TEMPLATE_PARAMS(kind0, name0, kind1, name1) \
name0, name1
#define GMOCK_INTERNAL_LIST_HAS_3_TEMPLATE_PARAMS(kind0, name0, kind1, name1, \
kind2, name2) name0, name1, name2
kind2, name2) \
name0, name1, name2
#define GMOCK_INTERNAL_LIST_HAS_4_TEMPLATE_PARAMS(kind0, name0, kind1, name1, \
kind2, name2, kind3, name3) name0, name1, name2, name3
#define GMOCK_INTERNAL_LIST_HAS_5_TEMPLATE_PARAMS(kind0, name0, kind1, name1, \
kind2, name2, kind3, name3, kind4, name4) name0, name1, name2, name3, \
name4
kind2, name2, kind3, name3) \
name0, name1, name2, name3
#define GMOCK_INTERNAL_LIST_HAS_5_TEMPLATE_PARAMS( \
kind0, name0, kind1, name1, kind2, name2, kind3, name3, kind4, name4) \
name0, name1, name2, name3, name4
#define GMOCK_INTERNAL_LIST_HAS_6_TEMPLATE_PARAMS(kind0, name0, kind1, name1, \
kind2, name2, kind3, name3, kind4, name4, kind5, name5) name0, name1, \
name2, name3, name4, name5
#define GMOCK_INTERNAL_LIST_HAS_7_TEMPLATE_PARAMS(kind0, name0, kind1, name1, \
kind2, name2, kind3, name3, kind4, name4, kind5, name5, kind6, \
name6) name0, name1, name2, name3, name4, name5, name6
#define GMOCK_INTERNAL_LIST_HAS_8_TEMPLATE_PARAMS(kind0, name0, kind1, name1, \
kind2, name2, kind3, name3, kind4, name4, kind5, name5, kind6, name6, \
kind7, name7) name0, name1, name2, name3, name4, name5, name6, name7
#define GMOCK_INTERNAL_LIST_HAS_9_TEMPLATE_PARAMS(kind0, name0, kind1, name1, \
kind2, name2, kind3, name3, kind4, name4, kind5, name5, kind6, name6, \
kind7, name7, kind8, name8) name0, name1, name2, name3, name4, name5, \
name6, name7, name8
#define GMOCK_INTERNAL_LIST_HAS_10_TEMPLATE_PARAMS(kind0, name0, kind1, \
name1, kind2, name2, kind3, name3, kind4, name4, kind5, name5, kind6, \
name6, kind7, name7, kind8, name8, kind9, name9) name0, name1, name2, \
name3, name4, name5, name6, name7, name8, name9
kind2, name2, kind3, name3, \
kind4, name4, kind5, name5) \
name0, name1, name2, name3, name4, name5
#define GMOCK_INTERNAL_LIST_HAS_7_TEMPLATE_PARAMS( \
kind0, name0, kind1, name1, kind2, name2, kind3, name3, kind4, name4, \
kind5, name5, kind6, name6) \
name0, name1, name2, name3, name4, name5, name6
#define GMOCK_INTERNAL_LIST_HAS_8_TEMPLATE_PARAMS( \
kind0, name0, kind1, name1, kind2, name2, kind3, name3, kind4, name4, \
kind5, name5, kind6, name6, kind7, name7) \
name0, name1, name2, name3, name4, name5, name6, name7
#define GMOCK_INTERNAL_LIST_HAS_9_TEMPLATE_PARAMS( \
kind0, name0, kind1, name1, kind2, name2, kind3, name3, kind4, name4, \
kind5, name5, kind6, name6, kind7, name7, kind8, name8) \
name0, name1, name2, name3, name4, name5, name6, name7, name8
#define GMOCK_INTERNAL_LIST_HAS_10_TEMPLATE_PARAMS( \
kind0, name0, kind1, name1, kind2, name2, kind3, name3, kind4, name4, \
kind5, name5, kind6, name6, kind7, name7, kind8, name8, kind9, name9) \
name0, name1, name2, name3, name4, name5, name6, name7, name8, name9
// Declares the types of value parameters.
#define GMOCK_INTERNAL_DECL_TYPE_AND_0_VALUE_PARAMS()
#define GMOCK_INTERNAL_DECL_TYPE_AND_1_VALUE_PARAMS(p0) , typename p0##_type
#define GMOCK_INTERNAL_DECL_TYPE_AND_2_VALUE_PARAMS(p0, p1) , \
typename p0##_type, typename p1##_type
#define GMOCK_INTERNAL_DECL_TYPE_AND_3_VALUE_PARAMS(p0, p1, p2) , \
typename p0##_type, typename p1##_type, typename p2##_type
#define GMOCK_INTERNAL_DECL_TYPE_AND_4_VALUE_PARAMS(p0, p1, p2, p3) , \
typename p0##_type, typename p1##_type, typename p2##_type, \
typename p3##_type
#define GMOCK_INTERNAL_DECL_TYPE_AND_5_VALUE_PARAMS(p0, p1, p2, p3, p4) , \
typename p0##_type, typename p1##_type, typename p2##_type, \
typename p3##_type, typename p4##_type
#define GMOCK_INTERNAL_DECL_TYPE_AND_6_VALUE_PARAMS(p0, p1, p2, p3, p4, p5) , \
typename p0##_type, typename p1##_type, typename p2##_type, \
typename p3##_type, typename p4##_type, typename p5##_type
#define GMOCK_INTERNAL_DECL_TYPE_AND_2_VALUE_PARAMS(p0, p1) \
, typename p0##_type, typename p1##_type
#define GMOCK_INTERNAL_DECL_TYPE_AND_3_VALUE_PARAMS(p0, p1, p2) \
, typename p0##_type, typename p1##_type, typename p2##_type
#define GMOCK_INTERNAL_DECL_TYPE_AND_4_VALUE_PARAMS(p0, p1, p2, p3) \
, typename p0##_type, typename p1##_type, typename p2##_type, \
typename p3##_type
#define GMOCK_INTERNAL_DECL_TYPE_AND_5_VALUE_PARAMS(p0, p1, p2, p3, p4) \
, typename p0##_type, typename p1##_type, typename p2##_type, \
typename p3##_type, typename p4##_type
#define GMOCK_INTERNAL_DECL_TYPE_AND_6_VALUE_PARAMS(p0, p1, p2, p3, p4, p5) \
, typename p0##_type, typename p1##_type, typename p2##_type, \
typename p3##_type, typename p4##_type, typename p5##_type
#define GMOCK_INTERNAL_DECL_TYPE_AND_7_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, \
p6) , typename p0##_type, typename p1##_type, typename p2##_type, \
typename p3##_type, typename p4##_type, typename p5##_type, \
typename p6##_type
p6) \
, typename p0##_type, typename p1##_type, typename p2##_type, \
typename p3##_type, typename p4##_type, typename p5##_type, \
typename p6##_type
#define GMOCK_INTERNAL_DECL_TYPE_AND_8_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, \
p6, p7) , typename p0##_type, typename p1##_type, typename p2##_type, \
typename p3##_type, typename p4##_type, typename p5##_type, \
typename p6##_type, typename p7##_type
p6, p7) \
, typename p0##_type, typename p1##_type, typename p2##_type, \
typename p3##_type, typename p4##_type, typename p5##_type, \
typename p6##_type, typename p7##_type
#define GMOCK_INTERNAL_DECL_TYPE_AND_9_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, \
p6, p7, p8) , typename p0##_type, typename p1##_type, typename p2##_type, \
typename p3##_type, typename p4##_type, typename p5##_type, \
typename p6##_type, typename p7##_type, typename p8##_type
p6, p7, p8) \
, typename p0##_type, typename p1##_type, typename p2##_type, \
typename p3##_type, typename p4##_type, typename p5##_type, \
typename p6##_type, typename p7##_type, typename p8##_type
#define GMOCK_INTERNAL_DECL_TYPE_AND_10_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, \
p6, p7, p8, p9) , typename p0##_type, typename p1##_type, \
typename p2##_type, typename p3##_type, typename p4##_type, \
typename p5##_type, typename p6##_type, typename p7##_type, \
typename p8##_type, typename p9##_type
p6, p7, p8, p9) \
, typename p0##_type, typename p1##_type, typename p2##_type, \
typename p3##_type, typename p4##_type, typename p5##_type, \
typename p6##_type, typename p7##_type, typename p8##_type, \
typename p9##_type
// Initializes the value parameters.
#define GMOCK_INTERNAL_INIT_AND_0_VALUE_PARAMS()\
()
#define GMOCK_INTERNAL_INIT_AND_1_VALUE_PARAMS(p0)\
(p0##_type gmock_p0) : p0(::std::move(gmock_p0))
#define GMOCK_INTERNAL_INIT_AND_2_VALUE_PARAMS(p0, p1)\
(p0##_type gmock_p0, p1##_type gmock_p1) : p0(::std::move(gmock_p0)), \
p1(::std::move(gmock_p1))
#define GMOCK_INTERNAL_INIT_AND_3_VALUE_PARAMS(p0, p1, p2)\
(p0##_type gmock_p0, p1##_type gmock_p1, \
p2##_type gmock_p2) : p0(::std::move(gmock_p0)), \
p1(::std::move(gmock_p1)), p2(::std::move(gmock_p2))
#define GMOCK_INTERNAL_INIT_AND_4_VALUE_PARAMS(p0, p1, p2, p3)\
(p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \
p3##_type gmock_p3) : p0(::std::move(gmock_p0)), \
p1(::std::move(gmock_p1)), p2(::std::move(gmock_p2)), \
#define GMOCK_INTERNAL_INIT_AND_0_VALUE_PARAMS() ()
#define GMOCK_INTERNAL_INIT_AND_1_VALUE_PARAMS(p0) \
(p0##_type gmock_p0) : p0(::std::move(gmock_p0))
#define GMOCK_INTERNAL_INIT_AND_2_VALUE_PARAMS(p0, p1) \
(p0##_type gmock_p0, p1##_type gmock_p1) \
: p0(::std::move(gmock_p0)), p1(::std::move(gmock_p1))
#define GMOCK_INTERNAL_INIT_AND_3_VALUE_PARAMS(p0, p1, p2) \
(p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2) \
: p0(::std::move(gmock_p0)), \
p1(::std::move(gmock_p1)), \
p2(::std::move(gmock_p2))
#define GMOCK_INTERNAL_INIT_AND_4_VALUE_PARAMS(p0, p1, p2, p3) \
(p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \
p3##_type gmock_p3) \
: p0(::std::move(gmock_p0)), \
p1(::std::move(gmock_p1)), \
p2(::std::move(gmock_p2)), \
p3(::std::move(gmock_p3))
#define GMOCK_INTERNAL_INIT_AND_5_VALUE_PARAMS(p0, p1, p2, p3, p4)\
(p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \
p3##_type gmock_p3, p4##_type gmock_p4) : p0(::std::move(gmock_p0)), \
p1(::std::move(gmock_p1)), p2(::std::move(gmock_p2)), \
p3(::std::move(gmock_p3)), p4(::std::move(gmock_p4))
#define GMOCK_INTERNAL_INIT_AND_6_VALUE_PARAMS(p0, p1, p2, p3, p4, p5)\
(p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \
p3##_type gmock_p3, p4##_type gmock_p4, \
p5##_type gmock_p5) : p0(::std::move(gmock_p0)), \
p1(::std::move(gmock_p1)), p2(::std::move(gmock_p2)), \
p3(::std::move(gmock_p3)), p4(::std::move(gmock_p4)), \
#define GMOCK_INTERNAL_INIT_AND_5_VALUE_PARAMS(p0, p1, p2, p3, p4) \
(p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \
p3##_type gmock_p3, p4##_type gmock_p4) \
: p0(::std::move(gmock_p0)), \
p1(::std::move(gmock_p1)), \
p2(::std::move(gmock_p2)), \
p3(::std::move(gmock_p3)), \
p4(::std::move(gmock_p4))
#define GMOCK_INTERNAL_INIT_AND_6_VALUE_PARAMS(p0, p1, p2, p3, p4, p5) \
(p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \
p3##_type gmock_p3, p4##_type gmock_p4, p5##_type gmock_p5) \
: p0(::std::move(gmock_p0)), \
p1(::std::move(gmock_p1)), \
p2(::std::move(gmock_p2)), \
p3(::std::move(gmock_p3)), \
p4(::std::move(gmock_p4)), \
p5(::std::move(gmock_p5))
#define GMOCK_INTERNAL_INIT_AND_7_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6)\
(p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \
p3##_type gmock_p3, p4##_type gmock_p4, p5##_type gmock_p5, \
p6##_type gmock_p6) : p0(::std::move(gmock_p0)), \
p1(::std::move(gmock_p1)), p2(::std::move(gmock_p2)), \
p3(::std::move(gmock_p3)), p4(::std::move(gmock_p4)), \
p5(::std::move(gmock_p5)), p6(::std::move(gmock_p6))
#define GMOCK_INTERNAL_INIT_AND_8_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, p7)\
(p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \
p3##_type gmock_p3, p4##_type gmock_p4, p5##_type gmock_p5, \
p6##_type gmock_p6, p7##_type gmock_p7) : p0(::std::move(gmock_p0)), \
p1(::std::move(gmock_p1)), p2(::std::move(gmock_p2)), \
p3(::std::move(gmock_p3)), p4(::std::move(gmock_p4)), \
p5(::std::move(gmock_p5)), p6(::std::move(gmock_p6)), \
#define GMOCK_INTERNAL_INIT_AND_7_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6) \
(p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \
p3##_type gmock_p3, p4##_type gmock_p4, p5##_type gmock_p5, \
p6##_type gmock_p6) \
: p0(::std::move(gmock_p0)), \
p1(::std::move(gmock_p1)), \
p2(::std::move(gmock_p2)), \
p3(::std::move(gmock_p3)), \
p4(::std::move(gmock_p4)), \
p5(::std::move(gmock_p5)), \
p6(::std::move(gmock_p6))
#define GMOCK_INTERNAL_INIT_AND_8_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, p7) \
(p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \
p3##_type gmock_p3, p4##_type gmock_p4, p5##_type gmock_p5, \
p6##_type gmock_p6, p7##_type gmock_p7) \
: p0(::std::move(gmock_p0)), \
p1(::std::move(gmock_p1)), \
p2(::std::move(gmock_p2)), \
p3(::std::move(gmock_p3)), \
p4(::std::move(gmock_p4)), \
p5(::std::move(gmock_p5)), \
p6(::std::move(gmock_p6)), \
p7(::std::move(gmock_p7))
#define GMOCK_INTERNAL_INIT_AND_9_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, \
p7, p8)\
(p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \
p3##_type gmock_p3, p4##_type gmock_p4, p5##_type gmock_p5, \
p6##_type gmock_p6, p7##_type gmock_p7, \
p8##_type gmock_p8) : p0(::std::move(gmock_p0)), \
p1(::std::move(gmock_p1)), p2(::std::move(gmock_p2)), \
p3(::std::move(gmock_p3)), p4(::std::move(gmock_p4)), \
p5(::std::move(gmock_p5)), p6(::std::move(gmock_p6)), \
p7(::std::move(gmock_p7)), p8(::std::move(gmock_p8))
#define GMOCK_INTERNAL_INIT_AND_9_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, p7, \
p8) \
(p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \
p3##_type gmock_p3, p4##_type gmock_p4, p5##_type gmock_p5, \
p6##_type gmock_p6, p7##_type gmock_p7, p8##_type gmock_p8) \
: p0(::std::move(gmock_p0)), \
p1(::std::move(gmock_p1)), \
p2(::std::move(gmock_p2)), \
p3(::std::move(gmock_p3)), \
p4(::std::move(gmock_p4)), \
p5(::std::move(gmock_p5)), \
p6(::std::move(gmock_p6)), \
p7(::std::move(gmock_p7)), \
p8(::std::move(gmock_p8))
#define GMOCK_INTERNAL_INIT_AND_10_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, \
p7, p8, p9)\
(p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \
p3##_type gmock_p3, p4##_type gmock_p4, p5##_type gmock_p5, \
p6##_type gmock_p6, p7##_type gmock_p7, p8##_type gmock_p8, \
p9##_type gmock_p9) : p0(::std::move(gmock_p0)), \
p1(::std::move(gmock_p1)), p2(::std::move(gmock_p2)), \
p3(::std::move(gmock_p3)), p4(::std::move(gmock_p4)), \
p5(::std::move(gmock_p5)), p6(::std::move(gmock_p6)), \
p7(::std::move(gmock_p7)), p8(::std::move(gmock_p8)), \
p7, p8, p9) \
(p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \
p3##_type gmock_p3, p4##_type gmock_p4, p5##_type gmock_p5, \
p6##_type gmock_p6, p7##_type gmock_p7, p8##_type gmock_p8, \
p9##_type gmock_p9) \
: p0(::std::move(gmock_p0)), \
p1(::std::move(gmock_p1)), \
p2(::std::move(gmock_p2)), \
p3(::std::move(gmock_p3)), \
p4(::std::move(gmock_p4)), \
p5(::std::move(gmock_p5)), \
p6(::std::move(gmock_p6)), \
p7(::std::move(gmock_p7)), \
p8(::std::move(gmock_p8)), \
p9(::std::move(gmock_p9))
// Defines the copy constructor
#define GMOCK_INTERNAL_DEFN_COPY_AND_0_VALUE_PARAMS() \
{} // Avoid https://gcc.gnu.org/bugzilla/show_bug.cgi?id=82134
{} // Avoid https://gcc.gnu.org/bugzilla/show_bug.cgi?id=82134
#define GMOCK_INTERNAL_DEFN_COPY_AND_1_VALUE_PARAMS(...) = default;
#define GMOCK_INTERNAL_DEFN_COPY_AND_2_VALUE_PARAMS(...) = default;
#define GMOCK_INTERNAL_DEFN_COPY_AND_3_VALUE_PARAMS(...) = default;
@ -307,30 +344,71 @@
// Declares the fields for storing the value parameters.
#define GMOCK_INTERNAL_DEFN_AND_0_VALUE_PARAMS()
#define GMOCK_INTERNAL_DEFN_AND_1_VALUE_PARAMS(p0) p0##_type p0;
#define GMOCK_INTERNAL_DEFN_AND_2_VALUE_PARAMS(p0, p1) p0##_type p0; \
p1##_type p1;
#define GMOCK_INTERNAL_DEFN_AND_3_VALUE_PARAMS(p0, p1, p2) p0##_type p0; \
p1##_type p1; p2##_type p2;
#define GMOCK_INTERNAL_DEFN_AND_4_VALUE_PARAMS(p0, p1, p2, p3) p0##_type p0; \
p1##_type p1; p2##_type p2; p3##_type p3;
#define GMOCK_INTERNAL_DEFN_AND_5_VALUE_PARAMS(p0, p1, p2, p3, \
p4) p0##_type p0; p1##_type p1; p2##_type p2; p3##_type p3; p4##_type p4;
#define GMOCK_INTERNAL_DEFN_AND_6_VALUE_PARAMS(p0, p1, p2, p3, p4, \
p5) p0##_type p0; p1##_type p1; p2##_type p2; p3##_type p3; p4##_type p4; \
p5##_type p5;
#define GMOCK_INTERNAL_DEFN_AND_7_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, \
p6) p0##_type p0; p1##_type p1; p2##_type p2; p3##_type p3; p4##_type p4; \
p5##_type p5; p6##_type p6;
#define GMOCK_INTERNAL_DEFN_AND_8_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, \
p7) p0##_type p0; p1##_type p1; p2##_type p2; p3##_type p3; p4##_type p4; \
p5##_type p5; p6##_type p6; p7##_type p7;
#define GMOCK_INTERNAL_DEFN_AND_9_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, \
p7, p8) p0##_type p0; p1##_type p1; p2##_type p2; p3##_type p3; \
p4##_type p4; p5##_type p5; p6##_type p6; p7##_type p7; p8##_type p8;
#define GMOCK_INTERNAL_DEFN_AND_2_VALUE_PARAMS(p0, p1) \
p0##_type p0; \
p1##_type p1;
#define GMOCK_INTERNAL_DEFN_AND_3_VALUE_PARAMS(p0, p1, p2) \
p0##_type p0; \
p1##_type p1; \
p2##_type p2;
#define GMOCK_INTERNAL_DEFN_AND_4_VALUE_PARAMS(p0, p1, p2, p3) \
p0##_type p0; \
p1##_type p1; \
p2##_type p2; \
p3##_type p3;
#define GMOCK_INTERNAL_DEFN_AND_5_VALUE_PARAMS(p0, p1, p2, p3, p4) \
p0##_type p0; \
p1##_type p1; \
p2##_type p2; \
p3##_type p3; \
p4##_type p4;
#define GMOCK_INTERNAL_DEFN_AND_6_VALUE_PARAMS(p0, p1, p2, p3, p4, p5) \
p0##_type p0; \
p1##_type p1; \
p2##_type p2; \
p3##_type p3; \
p4##_type p4; \
p5##_type p5;
#define GMOCK_INTERNAL_DEFN_AND_7_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6) \
p0##_type p0; \
p1##_type p1; \
p2##_type p2; \
p3##_type p3; \
p4##_type p4; \
p5##_type p5; \
p6##_type p6;
#define GMOCK_INTERNAL_DEFN_AND_8_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, p7) \
p0##_type p0; \
p1##_type p1; \
p2##_type p2; \
p3##_type p3; \
p4##_type p4; \
p5##_type p5; \
p6##_type p6; \
p7##_type p7;
#define GMOCK_INTERNAL_DEFN_AND_9_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, p7, \
p8) \
p0##_type p0; \
p1##_type p1; \
p2##_type p2; \
p3##_type p3; \
p4##_type p4; \
p5##_type p5; \
p6##_type p6; \
p7##_type p7; \
p8##_type p8;
#define GMOCK_INTERNAL_DEFN_AND_10_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, \
p7, p8, p9) p0##_type p0; p1##_type p1; p2##_type p2; p3##_type p3; \
p4##_type p4; p5##_type p5; p6##_type p6; p7##_type p7; p8##_type p8; \
p9##_type p9;
p7, p8, p9) \
p0##_type p0; \
p1##_type p1; \
p2##_type p2; \
p3##_type p3; \
p4##_type p4; \
p5##_type p5; \
p6##_type p6; \
p7##_type p7; \
p8##_type p8; \
p9##_type p9;
// Lists the value parameters.
#define GMOCK_INTERNAL_LIST_AND_0_VALUE_PARAMS()
@ -338,72 +416,78 @@
#define GMOCK_INTERNAL_LIST_AND_2_VALUE_PARAMS(p0, p1) p0, p1
#define GMOCK_INTERNAL_LIST_AND_3_VALUE_PARAMS(p0, p1, p2) p0, p1, p2
#define GMOCK_INTERNAL_LIST_AND_4_VALUE_PARAMS(p0, p1, p2, p3) p0, p1, p2, p3
#define GMOCK_INTERNAL_LIST_AND_5_VALUE_PARAMS(p0, p1, p2, p3, p4) p0, p1, \
p2, p3, p4
#define GMOCK_INTERNAL_LIST_AND_6_VALUE_PARAMS(p0, p1, p2, p3, p4, p5) p0, \
p1, p2, p3, p4, p5
#define GMOCK_INTERNAL_LIST_AND_7_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, \
p6) p0, p1, p2, p3, p4, p5, p6
#define GMOCK_INTERNAL_LIST_AND_8_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, \
p7) p0, p1, p2, p3, p4, p5, p6, p7
#define GMOCK_INTERNAL_LIST_AND_9_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, \
p7, p8) p0, p1, p2, p3, p4, p5, p6, p7, p8
#define GMOCK_INTERNAL_LIST_AND_5_VALUE_PARAMS(p0, p1, p2, p3, p4) \
p0, p1, p2, p3, p4
#define GMOCK_INTERNAL_LIST_AND_6_VALUE_PARAMS(p0, p1, p2, p3, p4, p5) \
p0, p1, p2, p3, p4, p5
#define GMOCK_INTERNAL_LIST_AND_7_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6) \
p0, p1, p2, p3, p4, p5, p6
#define GMOCK_INTERNAL_LIST_AND_8_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, p7) \
p0, p1, p2, p3, p4, p5, p6, p7
#define GMOCK_INTERNAL_LIST_AND_9_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, p7, \
p8) \
p0, p1, p2, p3, p4, p5, p6, p7, p8
#define GMOCK_INTERNAL_LIST_AND_10_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, \
p7, p8, p9) p0, p1, p2, p3, p4, p5, p6, p7, p8, p9
p7, p8, p9) \
p0, p1, p2, p3, p4, p5, p6, p7, p8, p9
// Lists the value parameter types.
#define GMOCK_INTERNAL_LIST_TYPE_AND_0_VALUE_PARAMS()
#define GMOCK_INTERNAL_LIST_TYPE_AND_1_VALUE_PARAMS(p0) , p0##_type
#define GMOCK_INTERNAL_LIST_TYPE_AND_2_VALUE_PARAMS(p0, p1) , p0##_type, \
p1##_type
#define GMOCK_INTERNAL_LIST_TYPE_AND_3_VALUE_PARAMS(p0, p1, p2) , p0##_type, \
p1##_type, p2##_type
#define GMOCK_INTERNAL_LIST_TYPE_AND_4_VALUE_PARAMS(p0, p1, p2, p3) , \
p0##_type, p1##_type, p2##_type, p3##_type
#define GMOCK_INTERNAL_LIST_TYPE_AND_5_VALUE_PARAMS(p0, p1, p2, p3, p4) , \
p0##_type, p1##_type, p2##_type, p3##_type, p4##_type
#define GMOCK_INTERNAL_LIST_TYPE_AND_6_VALUE_PARAMS(p0, p1, p2, p3, p4, p5) , \
p0##_type, p1##_type, p2##_type, p3##_type, p4##_type, p5##_type
#define GMOCK_INTERNAL_LIST_TYPE_AND_2_VALUE_PARAMS(p0, p1) \
, p0##_type, p1##_type
#define GMOCK_INTERNAL_LIST_TYPE_AND_3_VALUE_PARAMS(p0, p1, p2) \
, p0##_type, p1##_type, p2##_type
#define GMOCK_INTERNAL_LIST_TYPE_AND_4_VALUE_PARAMS(p0, p1, p2, p3) \
, p0##_type, p1##_type, p2##_type, p3##_type
#define GMOCK_INTERNAL_LIST_TYPE_AND_5_VALUE_PARAMS(p0, p1, p2, p3, p4) \
, p0##_type, p1##_type, p2##_type, p3##_type, p4##_type
#define GMOCK_INTERNAL_LIST_TYPE_AND_6_VALUE_PARAMS(p0, p1, p2, p3, p4, p5) \
, p0##_type, p1##_type, p2##_type, p3##_type, p4##_type, p5##_type
#define GMOCK_INTERNAL_LIST_TYPE_AND_7_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, \
p6) , p0##_type, p1##_type, p2##_type, p3##_type, p4##_type, p5##_type, \
p6##_type
p6) \
, p0##_type, p1##_type, p2##_type, p3##_type, p4##_type, p5##_type, p6##_type
#define GMOCK_INTERNAL_LIST_TYPE_AND_8_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, \
p6, p7) , p0##_type, p1##_type, p2##_type, p3##_type, p4##_type, \
p5##_type, p6##_type, p7##_type
p6, p7) \
, p0##_type, p1##_type, p2##_type, p3##_type, p4##_type, p5##_type, \
p6##_type, p7##_type
#define GMOCK_INTERNAL_LIST_TYPE_AND_9_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, \
p6, p7, p8) , p0##_type, p1##_type, p2##_type, p3##_type, p4##_type, \
p5##_type, p6##_type, p7##_type, p8##_type
p6, p7, p8) \
, p0##_type, p1##_type, p2##_type, p3##_type, p4##_type, p5##_type, \
p6##_type, p7##_type, p8##_type
#define GMOCK_INTERNAL_LIST_TYPE_AND_10_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, \
p6, p7, p8, p9) , p0##_type, p1##_type, p2##_type, p3##_type, p4##_type, \
p5##_type, p6##_type, p7##_type, p8##_type, p9##_type
p6, p7, p8, p9) \
, p0##_type, p1##_type, p2##_type, p3##_type, p4##_type, p5##_type, \
p6##_type, p7##_type, p8##_type, p9##_type
// Declares the value parameters.
#define GMOCK_INTERNAL_DECL_AND_0_VALUE_PARAMS()
#define GMOCK_INTERNAL_DECL_AND_1_VALUE_PARAMS(p0) p0##_type p0
#define GMOCK_INTERNAL_DECL_AND_2_VALUE_PARAMS(p0, p1) p0##_type p0, \
p1##_type p1
#define GMOCK_INTERNAL_DECL_AND_3_VALUE_PARAMS(p0, p1, p2) p0##_type p0, \
p1##_type p1, p2##_type p2
#define GMOCK_INTERNAL_DECL_AND_4_VALUE_PARAMS(p0, p1, p2, p3) p0##_type p0, \
p1##_type p1, p2##_type p2, p3##_type p3
#define GMOCK_INTERNAL_DECL_AND_5_VALUE_PARAMS(p0, p1, p2, p3, \
p4) p0##_type p0, p1##_type p1, p2##_type p2, p3##_type p3, p4##_type p4
#define GMOCK_INTERNAL_DECL_AND_6_VALUE_PARAMS(p0, p1, p2, p3, p4, \
p5) p0##_type p0, p1##_type p1, p2##_type p2, p3##_type p3, p4##_type p4, \
p5##_type p5
#define GMOCK_INTERNAL_DECL_AND_7_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, \
p6) p0##_type p0, p1##_type p1, p2##_type p2, p3##_type p3, p4##_type p4, \
p5##_type p5, p6##_type p6
#define GMOCK_INTERNAL_DECL_AND_8_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, \
p7) p0##_type p0, p1##_type p1, p2##_type p2, p3##_type p3, p4##_type p4, \
p5##_type p5, p6##_type p6, p7##_type p7
#define GMOCK_INTERNAL_DECL_AND_9_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, \
p7, p8) p0##_type p0, p1##_type p1, p2##_type p2, p3##_type p3, \
p4##_type p4, p5##_type p5, p6##_type p6, p7##_type p7, p8##_type p8
#define GMOCK_INTERNAL_DECL_AND_2_VALUE_PARAMS(p0, p1) \
p0##_type p0, p1##_type p1
#define GMOCK_INTERNAL_DECL_AND_3_VALUE_PARAMS(p0, p1, p2) \
p0##_type p0, p1##_type p1, p2##_type p2
#define GMOCK_INTERNAL_DECL_AND_4_VALUE_PARAMS(p0, p1, p2, p3) \
p0##_type p0, p1##_type p1, p2##_type p2, p3##_type p3
#define GMOCK_INTERNAL_DECL_AND_5_VALUE_PARAMS(p0, p1, p2, p3, p4) \
p0##_type p0, p1##_type p1, p2##_type p2, p3##_type p3, p4##_type p4
#define GMOCK_INTERNAL_DECL_AND_6_VALUE_PARAMS(p0, p1, p2, p3, p4, p5) \
p0##_type p0, p1##_type p1, p2##_type p2, p3##_type p3, p4##_type p4, \
p5##_type p5
#define GMOCK_INTERNAL_DECL_AND_7_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6) \
p0##_type p0, p1##_type p1, p2##_type p2, p3##_type p3, p4##_type p4, \
p5##_type p5, p6##_type p6
#define GMOCK_INTERNAL_DECL_AND_8_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, p7) \
p0##_type p0, p1##_type p1, p2##_type p2, p3##_type p3, p4##_type p4, \
p5##_type p5, p6##_type p6, p7##_type p7
#define GMOCK_INTERNAL_DECL_AND_9_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, p7, \
p8) \
p0##_type p0, p1##_type p1, p2##_type p2, p3##_type p3, p4##_type p4, \
p5##_type p5, p6##_type p6, p7##_type p7, p8##_type p8
#define GMOCK_INTERNAL_DECL_AND_10_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, \
p7, p8, p9) p0##_type p0, p1##_type p1, p2##_type p2, p3##_type p3, \
p4##_type p4, p5##_type p5, p6##_type p6, p7##_type p7, p8##_type p8, \
p9##_type p9
p7, p8, p9) \
p0##_type p0, p1##_type p1, p2##_type p2, p3##_type p3, p4##_type p4, \
p5##_type p5, p6##_type p6, p7##_type p7, p8##_type p8, p9##_type p9
// The suffix of the class template implementing the action template.
#define GMOCK_INTERNAL_COUNT_AND_0_VALUE_PARAMS()
@ -415,40 +499,43 @@
#define GMOCK_INTERNAL_COUNT_AND_6_VALUE_PARAMS(p0, p1, p2, p3, p4, p5) P6
#define GMOCK_INTERNAL_COUNT_AND_7_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6) P7
#define GMOCK_INTERNAL_COUNT_AND_8_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, \
p7) P8
p7) \
P8
#define GMOCK_INTERNAL_COUNT_AND_9_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, \
p7, p8) P9
p7, p8) \
P9
#define GMOCK_INTERNAL_COUNT_AND_10_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, \
p7, p8, p9) P10
p7, p8, p9) \
P10
// The name of the class template implementing the action template.
#define GMOCK_ACTION_CLASS_(name, value_params)\
GTEST_CONCAT_TOKEN_(name##Action, GMOCK_INTERNAL_COUNT_##value_params)
#define GMOCK_ACTION_CLASS_(name, value_params) \
GTEST_CONCAT_TOKEN_(name##Action, GMOCK_INTERNAL_COUNT_##value_params)
#define ACTION_TEMPLATE(name, template_params, value_params) \
template <GMOCK_INTERNAL_DECL_##template_params \
GMOCK_INTERNAL_DECL_TYPE_##value_params> \
GMOCK_INTERNAL_DECL_TYPE_##value_params> \
class GMOCK_ACTION_CLASS_(name, value_params) { \
public: \
explicit GMOCK_ACTION_CLASS_(name, value_params)( \
GMOCK_INTERNAL_DECL_##value_params) \
GMOCK_PP_IF(GMOCK_PP_IS_EMPTY(GMOCK_INTERNAL_COUNT_##value_params), \
= default; , \
= default; \
, \
: impl_(std::make_shared<gmock_Impl>( \
GMOCK_INTERNAL_LIST_##value_params)) { }) \
GMOCK_ACTION_CLASS_(name, value_params)( \
const GMOCK_ACTION_CLASS_(name, value_params)&) noexcept \
GMOCK_INTERNAL_DEFN_COPY_##value_params \
GMOCK_ACTION_CLASS_(name, value_params)( \
GMOCK_ACTION_CLASS_(name, value_params)&&) noexcept \
GMOCK_INTERNAL_DEFN_COPY_##value_params \
template <typename F> \
operator ::testing::Action<F>() const { \
GMOCK_INTERNAL_LIST_##value_params)){}) \
GMOCK_ACTION_CLASS_(name, value_params)(const GMOCK_ACTION_CLASS_( \
name, value_params) &) noexcept GMOCK_INTERNAL_DEFN_COPY_ \
##value_params GMOCK_ACTION_CLASS_(name, value_params)( \
GMOCK_ACTION_CLASS_(name, value_params) &&) noexcept \
GMOCK_INTERNAL_DEFN_COPY_##value_params template <typename F> \
operator ::testing::Action<F>() const { \
return GMOCK_PP_IF( \
GMOCK_PP_IS_EMPTY(GMOCK_INTERNAL_COUNT_##value_params), \
(::testing::internal::MakeAction<F, gmock_Impl>()), \
(::testing::internal::MakeAction<F>(impl_))); \
(::testing::internal::MakeAction<F, gmock_Impl>()), \
(::testing::internal::MakeAction<F>(impl_))); \
} \
\
private: \
class gmock_Impl { \
public: \
@ -458,34 +545,35 @@
return_type gmock_PerformImpl(GMOCK_ACTION_ARG_TYPES_AND_NAMES_) const; \
GMOCK_INTERNAL_DEFN_##value_params \
}; \
GMOCK_PP_IF(GMOCK_PP_IS_EMPTY(GMOCK_INTERNAL_COUNT_##value_params), \
, std::shared_ptr<const gmock_Impl> impl_;) \
GMOCK_PP_IF(GMOCK_PP_IS_EMPTY(GMOCK_INTERNAL_COUNT_##value_params), , \
std::shared_ptr<const gmock_Impl> impl_;) \
}; \
template <GMOCK_INTERNAL_DECL_##template_params \
GMOCK_INTERNAL_DECL_TYPE_##value_params> \
GMOCK_ACTION_CLASS_(name, value_params)< \
GMOCK_INTERNAL_LIST_##template_params \
GMOCK_INTERNAL_LIST_TYPE_##value_params> name( \
GMOCK_INTERNAL_DECL_##value_params) GTEST_MUST_USE_RESULT_; \
GMOCK_INTERNAL_DECL_TYPE_##value_params> \
GMOCK_ACTION_CLASS_( \
name, value_params)<GMOCK_INTERNAL_LIST_##template_params \
GMOCK_INTERNAL_LIST_TYPE_##value_params> \
name(GMOCK_INTERNAL_DECL_##value_params) GTEST_MUST_USE_RESULT_; \
template <GMOCK_INTERNAL_DECL_##template_params \
GMOCK_INTERNAL_DECL_TYPE_##value_params> \
inline GMOCK_ACTION_CLASS_(name, value_params)< \
GMOCK_INTERNAL_LIST_##template_params \
GMOCK_INTERNAL_LIST_TYPE_##value_params> name( \
GMOCK_INTERNAL_DECL_##value_params) { \
return GMOCK_ACTION_CLASS_(name, value_params)< \
GMOCK_INTERNAL_LIST_##template_params \
GMOCK_INTERNAL_LIST_TYPE_##value_params>( \
GMOCK_INTERNAL_LIST_##value_params); \
GMOCK_INTERNAL_DECL_TYPE_##value_params> \
inline GMOCK_ACTION_CLASS_( \
name, value_params)<GMOCK_INTERNAL_LIST_##template_params \
GMOCK_INTERNAL_LIST_TYPE_##value_params> \
name(GMOCK_INTERNAL_DECL_##value_params) { \
return GMOCK_ACTION_CLASS_( \
name, value_params)<GMOCK_INTERNAL_LIST_##template_params \
GMOCK_INTERNAL_LIST_TYPE_##value_params>( \
GMOCK_INTERNAL_LIST_##value_params); \
} \
template <GMOCK_INTERNAL_DECL_##template_params \
GMOCK_INTERNAL_DECL_TYPE_##value_params> \
GMOCK_INTERNAL_DECL_TYPE_##value_params> \
template <typename function_type, typename return_type, typename args_type, \
GMOCK_ACTION_TEMPLATE_ARGS_NAMES_> \
return_type GMOCK_ACTION_CLASS_(name, value_params)< \
GMOCK_INTERNAL_LIST_##template_params \
GMOCK_INTERNAL_LIST_TYPE_##value_params>::gmock_Impl::gmock_PerformImpl( \
GMOCK_ACTION_ARG_TYPES_AND_NAMES_UNUSED_) const
return_type GMOCK_ACTION_CLASS_( \
name, value_params)<GMOCK_INTERNAL_LIST_##template_params \
GMOCK_INTERNAL_LIST_TYPE_##value_params>:: \
gmock_Impl::gmock_PerformImpl(GMOCK_ACTION_ARG_TYPES_AND_NAMES_UNUSED_) \
const
namespace testing {
@ -495,8 +583,8 @@ namespace testing {
// is expanded and macro expansion cannot contain #pragma. Therefore
// we suppress them here.
#ifdef _MSC_VER
# pragma warning(push)
# pragma warning(disable:4100)
#pragma warning(push)
#pragma warning(disable : 4100)
#endif
namespace internal {
@ -565,7 +653,7 @@ InvokeArgument(Params&&... params) {
}
#ifdef _MSC_VER
# pragma warning(pop)
#pragma warning(pop)
#endif
} // namespace testing

@ -47,13 +47,13 @@ namespace testing {
// Silence C4100 (unreferenced formal
// parameter) for MSVC
#ifdef _MSC_VER
# pragma warning(push)
# pragma warning(disable:4100)
#pragma warning(push)
#pragma warning(disable : 4100)
#if (_MSC_VER == 1900)
// and silence C4800 (C4800: 'int *const ': forcing value
// to bool 'true' or 'false') for MSVC 14
# pragma warning(disable:4800)
#endif
#pragma warning(disable : 4800)
#endif
#endif
// Defines a matcher that matches an empty container. The container must
@ -83,10 +83,9 @@ MATCHER(IsFalse, negation ? "is true" : "is false") {
}
#ifdef _MSC_VER
# pragma warning(pop)
#pragma warning(pop)
#endif
} // namespace testing
#endif // GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_MORE_MATCHERS_H_

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

@ -59,9 +59,9 @@ namespace internal {
// Silence MSVC C4100 (unreferenced formal parameter) and
// C4805('==': unsafe mix of type 'const int' and type 'const bool')
#ifdef _MSC_VER
# pragma warning(push)
# pragma warning(disable:4100)
# pragma warning(disable:4805)
#pragma warning(push)
#pragma warning(disable : 4100)
#pragma warning(disable : 4805)
#endif
// Joins a vector of strings as if they are fields of a tuple; returns
@ -91,7 +91,9 @@ inline const Element* GetRawPointer(const std::reference_wrapper<Element>& r) {
// This overloaded version is for the raw pointer case.
template <typename Element>
inline Element* GetRawPointer(Element* p) { return p; }
inline Element* GetRawPointer(Element* p) {
return p;
}
// MSVC treats wchar_t as a native type usually, but treats it as the
// same as unsigned short when the compiler option /Zc:wchar_t- is
@ -100,7 +102,7 @@ inline Element* GetRawPointer(Element* p) { return p; }
#if defined(_MSC_VER) && !defined(_NATIVE_WCHAR_T_DEFINED)
// wchar_t is a typedef.
#else
# define GMOCK_WCHAR_T_IS_NATIVE_ 1
#define GMOCK_WCHAR_T_IS_NATIVE_ 1
#endif
// In what follows, we use the term "kind" to indicate whether a type
@ -108,18 +110,20 @@ inline Element* GetRawPointer(Element* p) { return p; }
// or none of them. This categorization is useful for determining
// when a matcher argument type can be safely converted to another
// type in the implementation of SafeMatcherCast.
enum TypeKind {
kBool, kInteger, kFloatingPoint, kOther
};
enum TypeKind { kBool, kInteger, kFloatingPoint, kOther };
// KindOf<T>::value is the kind of type T.
template <typename T> struct KindOf {
template <typename T>
struct KindOf {
enum { value = kOther }; // The default kind.
};
// This macro declares that the kind of 'type' is 'kind'.
#define GMOCK_DECLARE_KIND_(type, kind) \
template <> struct KindOf<type> { enum { value = kind }; }
template <> \
struct KindOf<type> { \
enum { value = kind }; \
}
GMOCK_DECLARE_KIND_(bool, kBool);
@ -127,13 +131,13 @@ GMOCK_DECLARE_KIND_(bool, kBool);
GMOCK_DECLARE_KIND_(char, kInteger);
GMOCK_DECLARE_KIND_(signed char, kInteger);
GMOCK_DECLARE_KIND_(unsigned char, kInteger);
GMOCK_DECLARE_KIND_(short, kInteger); // NOLINT
GMOCK_DECLARE_KIND_(short, kInteger); // NOLINT
GMOCK_DECLARE_KIND_(unsigned short, kInteger); // NOLINT
GMOCK_DECLARE_KIND_(int, kInteger);
GMOCK_DECLARE_KIND_(unsigned int, kInteger);
GMOCK_DECLARE_KIND_(long, kInteger); // NOLINT
GMOCK_DECLARE_KIND_(unsigned long, kInteger); // NOLINT
GMOCK_DECLARE_KIND_(long long, kInteger); // NOLINT
GMOCK_DECLARE_KIND_(long, kInteger); // NOLINT
GMOCK_DECLARE_KIND_(unsigned long, kInteger); // NOLINT
GMOCK_DECLARE_KIND_(long long, kInteger); // NOLINT
GMOCK_DECLARE_KIND_(unsigned long long, kInteger); // NOLINT
#if GMOCK_WCHAR_T_IS_NATIVE_
@ -148,7 +152,7 @@ GMOCK_DECLARE_KIND_(long double, kFloatingPoint);
#undef GMOCK_DECLARE_KIND_
// Evaluates to the kind of 'type'.
#define GMOCK_KIND_OF_(type) \
#define GMOCK_KIND_OF_(type) \
static_cast< ::testing::internal::TypeKind>( \
::testing::internal::KindOf<type>::value)
@ -204,9 +208,7 @@ using LosslessArithmeticConvertible =
class FailureReporterInterface {
public:
// The type of a failure (either non-fatal or fatal).
enum FailureType {
kNonfatal, kFatal
};
enum FailureType { kNonfatal, kFatal };
virtual ~FailureReporterInterface() {}
@ -226,8 +228,8 @@ GTEST_API_ FailureReporterInterface* GetFailureReporter();
inline void Assert(bool condition, const char* file, int line,
const std::string& msg) {
if (!condition) {
GetFailureReporter()->ReportFailure(FailureReporterInterface::kFatal,
file, line, msg);
GetFailureReporter()->ReportFailure(FailureReporterInterface::kFatal, file,
line, msg);
}
}
inline void Assert(bool condition, const char* file, int line) {
@ -248,10 +250,7 @@ inline void Expect(bool condition, const char* file, int line) {
}
// Severity level of a log.
enum LogSeverity {
kInfo = 0,
kWarning = 1
};
enum LogSeverity { kInfo = 0, kWarning = 1 };
// Valid values for the --gmock_verbose flag.
@ -294,8 +293,8 @@ GTEST_API_ WithoutMatchers GetWithoutMatchers();
// Disable MSVC warnings for infinite recursion, since in this case the
// recursion is unreachable.
#ifdef _MSC_VER
# pragma warning(push)
# pragma warning(disable:4717)
#pragma warning(push)
#pragma warning(disable : 4717)
#endif
// Invalid<T>() is usable as an expression of type T, but will terminate
@ -313,7 +312,7 @@ inline T Invalid() {
}
#ifdef _MSC_VER
# pragma warning(pop)
#pragma warning(pop)
#endif
// Given a raw type (i.e. having no top-level reference or const
@ -392,7 +391,8 @@ class StlContainerView< ::std::tuple<ElementPointer, Size> > {
// The following specialization prevents the user from instantiating
// StlContainer with a reference type.
template <typename T> class StlContainerView<T&>;
template <typename T>
class StlContainerView<T&>;
// A type transform to remove constness from the first part of a pair.
// Pairs like that are used as the value_type of associative containers,
@ -413,17 +413,18 @@ struct RemoveConstFromKey<std::pair<const K, V> > {
GTEST_API_ void IllegalDoDefault(const char* file, int line);
template <typename F, typename Tuple, size_t... Idx>
auto ApplyImpl(F&& f, Tuple&& args, IndexSequence<Idx...>) -> decltype(
std::forward<F>(f)(std::get<Idx>(std::forward<Tuple>(args))...)) {
auto ApplyImpl(F&& f, Tuple&& args, IndexSequence<Idx...>)
-> decltype(std::forward<F>(f)(
std::get<Idx>(std::forward<Tuple>(args))...)) {
return std::forward<F>(f)(std::get<Idx>(std::forward<Tuple>(args))...);
}
// Apply the function to a tuple of arguments.
template <typename F, typename Tuple>
auto Apply(F&& f, Tuple&& args) -> decltype(
ApplyImpl(std::forward<F>(f), std::forward<Tuple>(args),
MakeIndexSequence<std::tuple_size<
typename std::remove_reference<Tuple>::type>::value>())) {
auto Apply(F&& f, Tuple&& args) -> decltype(ApplyImpl(
std::forward<F>(f), std::forward<Tuple>(args),
MakeIndexSequence<std::tuple_size<
typename std::remove_reference<Tuple>::type>::value>())) {
return ApplyImpl(std::forward<F>(f), std::forward<Tuple>(args),
MakeIndexSequence<std::tuple_size<
typename std::remove_reference<Tuple>::type>::value>());
@ -463,7 +464,7 @@ constexpr size_t Function<R(Args...)>::ArgumentCount;
bool Base64Unescape(const std::string& encoded, std::string* decoded);
#ifdef _MSC_VER
# pragma warning(pop)
#pragma warning(pop)
#endif
} // namespace internal

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

@ -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());
}
}

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

@ -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

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

@ -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,

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

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

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

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

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

File diff suppressed because it is too large Load Diff

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

@ -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),

@ -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

@ -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

@ -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

@ -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

@ -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

@ -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

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

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

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

@ -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"

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

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

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

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

@ -258,12 +258,10 @@ struct ConvertibleToStringViewPrinter {
#endif
};
// Prints the given number of bytes in the given object to the given
// ostream.
GTEST_API_ void PrintBytesInObjectTo(const unsigned char* obj_bytes,
size_t count,
::std::ostream* os);
size_t count, ::std::ostream* os);
struct RawBytesPrinter {
// SFINAE on `sizeof` to make sure we have a complete type.
template <typename T, size_t = sizeof(T)>
@ -376,12 +374,12 @@ GTEST_IMPL_FORMAT_C_STRING_AS_POINTER_(const char32_t);
// to point to a NUL-terminated string, and thus can print it as a string.
#define GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(CharType, OtherStringType) \
template <> \
class FormatForComparison<CharType*, OtherStringType> { \
public: \
static ::std::string Format(CharType* value) { \
return ::testing::PrintToString(value); \
} \
template <> \
class FormatForComparison<CharType*, OtherStringType> { \
public: \
static ::std::string Format(CharType* value) { \
return ::testing::PrintToString(value); \
} \
}
GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(char, ::std::string);
@ -411,8 +409,8 @@ GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(const wchar_t, ::std::wstring);
//
// INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.
template <typename T1, typename T2>
std::string FormatForComparisonFailureMessage(
const T1& value, const T2& /* other_operand */) {
std::string FormatForComparisonFailureMessage(const T1& value,
const T2& /* other_operand */) {
return FormatForComparison<T1, T2>::Format(value);
}
@ -552,7 +550,7 @@ void PrintRawArrayTo(const T a[], size_t count, ::std::ostream* os) {
}
// Overloads for ::std::string.
GTEST_API_ void PrintStringTo(const ::std::string&s, ::std::ostream* os);
GTEST_API_ void PrintStringTo(const ::std::string& s, ::std::ostream* os);
inline void PrintTo(const ::std::string& s, ::std::ostream* os) {
PrintStringTo(s, os);
}
@ -579,7 +577,7 @@ inline void PrintTo(const ::std::u32string& s, ::std::ostream* os) {
// Overloads for ::std::wstring.
#if GTEST_HAS_STD_WSTRING
GTEST_API_ void PrintWideStringTo(const ::std::wstring&s, ::std::ostream* os);
GTEST_API_ void PrintWideStringTo(const ::std::wstring& s, ::std::ostream* os);
inline void PrintTo(const ::std::wstring& s, ::std::ostream* os) {
PrintWideStringTo(s, os);
}
@ -823,8 +821,8 @@ void UniversalPrintArray(const T* begin, size_t len, ::std::ostream* os) {
}
}
// This overload prints a (const) char array compactly.
GTEST_API_ void UniversalPrintArray(
const char* begin, size_t len, ::std::ostream* os);
GTEST_API_ void UniversalPrintArray(const char* begin, size_t len,
::std::ostream* os);
#ifdef __cpp_char8_t
// This overload prints a (const) char8_t array compactly.
@ -841,8 +839,8 @@ GTEST_API_ void UniversalPrintArray(const char32_t* begin, size_t len,
::std::ostream* os);
// This overload prints a (const) wchar_t array compactly.
GTEST_API_ void UniversalPrintArray(
const wchar_t* begin, size_t len, ::std::ostream* os);
GTEST_API_ void UniversalPrintArray(const wchar_t* begin, size_t len,
::std::ostream* os);
// Implements printing an array type T[N].
template <typename T, size_t N>
@ -1001,10 +999,10 @@ void UniversalPrint(const T& value, ::std::ostream* os) {
UniversalPrinter<T1>::Print(value, os);
}
typedef ::std::vector< ::std::string> Strings;
typedef ::std::vector<::std::string> Strings;
// Tersely prints the first N fields of a tuple to a string vector,
// one element for each field.
// Tersely prints the first N fields of a tuple to a string vector,
// one element for each field.
template <typename Tuple>
void TersePrintPrefixToStrings(const Tuple&, std::integral_constant<size_t, 0>,
Strings*) {}

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

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

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

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

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

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

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

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

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

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

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

File diff suppressed because it is too large Load Diff

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

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

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

@ -52,9 +52,9 @@ bool IsPrime(int n) {
// Now, we have that n is odd and n >= 3.
// Try to divide n by every odd number i, starting from 3
for (int i = 3; ; i += 2) {
for (int i = 3;; i += 2) {
// We only have to try i up to the square root of n
if (i > n/i) break;
if (i > n / i) break;
// Now, we have i <= n/i < n.
// If n is divisible by i, n is not prime.

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

@ -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.

@ -38,7 +38,7 @@ const char* MyString::CloneCString(const char* a_c_string) {
if (a_c_string == nullptr) return nullptr;
const size_t len = strlen(a_c_string);
char* const clone = new char[ len + 1 ];
char* const clone = new char[len + 1];
memcpy(clone, a_c_string, len + 1);
return clone;

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

@ -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.

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

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

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

@ -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 {

@ -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) {

@ -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

@ -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() {

@ -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

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

@ -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"

@ -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.

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

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

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

@ -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

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

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

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

@ -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

@ -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(); }

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

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

@ -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);

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

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

@ -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) {

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

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

@ -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));

@ -71,6 +71,8 @@ EXPECTED_1 = {
u'*',
u'testsuite': [{
u'name': u'TestSomeProperties',
u'file': u'gtest_xml_outfile1_test_.cc',
u'line': 41,
u'status': u'RUN',
u'result': u'COMPLETED',
u'time': u'*',
@ -115,6 +117,8 @@ EXPECTED_2 = {
u'*',
u'testsuite': [{
u'name': u'TestSomeProperties',
u'file': u'gtest_xml_outfile2_test_.cc',
u'line': 41,
u'status': u'RUN',
u'result': u'COMPLETED',
u'timestamp': u'*',

@ -90,6 +90,8 @@ EXPECTED_NON_EMPTY = {
u'*',
u'testsuite': [{
u'name': u'Succeeds',
u'file': u'gtest_xml_output_unittest_.cc',
u'line': 51,
u'status': u'RUN',
u'result': u'COMPLETED',
u'time': u'*',
@ -114,6 +116,10 @@ EXPECTED_NON_EMPTY = {
u'testsuite': [{
u'name':
u'Fails',
u'file':
u'gtest_xml_output_unittest_.cc',
u'line':
59,
u'status':
u'RUN',
u'result':
@ -148,6 +154,8 @@ EXPECTED_NON_EMPTY = {
u'*',
u'testsuite': [{
u'name': u'DISABLED_test_not_run',
u'file': u'gtest_xml_output_unittest_.cc',
u'line': 66,
u'status': u'NOTRUN',
u'result': u'SUPPRESSED',
u'time': u'*',
@ -171,6 +179,8 @@ EXPECTED_NON_EMPTY = {
u'*',
u'testsuite': [{
u'name': u'Skipped',
u'file': 'gtest_xml_output_unittest_.cc',
u'line': 73,
u'status': u'RUN',
u'result': u'SKIPPED',
u'time': u'*',
@ -178,6 +188,8 @@ EXPECTED_NON_EMPTY = {
u'classname': u'SkippedTest'
}, {
u'name': u'SkippedWithMessage',
u'file': 'gtest_xml_output_unittest_.cc',
u'line': 77,
u'status': u'RUN',
u'result': u'SKIPPED',
u'time': u'*',
@ -186,6 +198,10 @@ EXPECTED_NON_EMPTY = {
}, {
u'name':
u'SkippedAfterFailure',
u'file':
'gtest_xml_output_unittest_.cc',
u'line':
81,
u'status':
u'RUN',
u'result':
@ -220,6 +236,8 @@ EXPECTED_NON_EMPTY = {
u'*',
u'testsuite': [{
u'name': u'Succeeds',
u'file': 'gtest_xml_output_unittest_.cc',
u'line': 86,
u'status': u'RUN',
u'result': u'COMPLETED',
u'time': u'*',
@ -228,6 +246,10 @@ EXPECTED_NON_EMPTY = {
}, {
u'name':
u'Fails',
u'file':
u'gtest_xml_output_unittest_.cc',
u'line':
91,
u'status':
u'RUN',
u'result':
@ -251,6 +273,8 @@ EXPECTED_NON_EMPTY = {
}]
}, {
u'name': u'DISABLED_test',
u'file': u'gtest_xml_output_unittest_.cc',
u'line': 96,
u'status': u'NOTRUN',
u'result': u'SUPPRESSED',
u'time': u'*',
@ -275,6 +299,10 @@ EXPECTED_NON_EMPTY = {
u'testsuite': [{
u'name':
u'OutputsCData',
u'file':
u'gtest_xml_output_unittest_.cc',
u'line':
100,
u'status':
u'RUN',
u'result':
@ -311,6 +339,10 @@ EXPECTED_NON_EMPTY = {
u'testsuite': [{
u'name':
u'InvalidCharactersInMessage',
u'file':
u'gtest_xml_output_unittest_.cc',
u'line':
107,
u'status':
u'RUN',
u'result':
@ -349,6 +381,8 @@ EXPECTED_NON_EMPTY = {
u'aye',
u'testsuite': [{
u'name': u'OneProperty',
u'file': u'gtest_xml_output_unittest_.cc',
u'line': 119,
u'status': u'RUN',
u'result': u'COMPLETED',
u'time': u'*',
@ -357,6 +391,8 @@ EXPECTED_NON_EMPTY = {
u'key_1': u'1'
}, {
u'name': u'IntValuedProperty',
u'file': u'gtest_xml_output_unittest_.cc',
u'line': 123,
u'status': u'RUN',
u'result': u'COMPLETED',
u'time': u'*',
@ -365,6 +401,8 @@ EXPECTED_NON_EMPTY = {
u'key_int': u'1'
}, {
u'name': u'ThreeProperties',
u'file': u'gtest_xml_output_unittest_.cc',
u'line': 127,
u'status': u'RUN',
u'result': u'COMPLETED',
u'time': u'*',
@ -375,6 +413,8 @@ EXPECTED_NON_EMPTY = {
u'key_3': u'3'
}, {
u'name': u'TwoValuesForOneKeyUsesLastValue',
u'file': u'gtest_xml_output_unittest_.cc',
u'line': 133,
u'status': u'RUN',
u'result': u'COMPLETED',
u'time': u'*',
@ -399,6 +439,8 @@ EXPECTED_NON_EMPTY = {
u'*',
u'testsuite': [{
u'name': u'RecordProperty',
u'file': u'gtest_xml_output_unittest_.cc',
u'line': 138,
u'status': u'RUN',
u'result': u'COMPLETED',
u'time': u'*',
@ -407,6 +449,8 @@ EXPECTED_NON_EMPTY = {
u'key': u'1'
}, {
u'name': u'ExternalUtilityThatCallsRecordIntValuedProperty',
u'file': u'gtest_xml_output_unittest_.cc',
u'line': 151,
u'status': u'RUN',
u'result': u'COMPLETED',
u'time': u'*',
@ -415,6 +459,8 @@ EXPECTED_NON_EMPTY = {
u'key_for_utility_int': u'1'
}, {
u'name': u'ExternalUtilityThatCallsRecordStringValuedProperty',
u'file': u'gtest_xml_output_unittest_.cc',
u'line': 155,
u'status': u'RUN',
u'result': u'COMPLETED',
u'time': u'*',
@ -440,6 +486,8 @@ EXPECTED_NON_EMPTY = {
u'testsuite': [{
u'name': u'HasTypeParamAttribute',
u'type_param': u'int',
u'file': u'gtest_xml_output_unittest_.cc',
u'line': 171,
u'status': u'RUN',
u'result': u'COMPLETED',
u'time': u'*',
@ -464,6 +512,8 @@ EXPECTED_NON_EMPTY = {
u'testsuite': [{
u'name': u'HasTypeParamAttribute',
u'type_param': u'long',
u'file': u'gtest_xml_output_unittest_.cc',
u'line': 171,
u'status': u'RUN',
u'result': u'COMPLETED',
u'time': u'*',
@ -488,6 +538,8 @@ EXPECTED_NON_EMPTY = {
u'testsuite': [{
u'name': u'HasTypeParamAttribute',
u'type_param': u'int',
u'file': u'gtest_xml_output_unittest_.cc',
u'line': 178,
u'status': u'RUN',
u'result': u'COMPLETED',
u'time': u'*',
@ -512,6 +564,8 @@ EXPECTED_NON_EMPTY = {
u'testsuite': [{
u'name': u'HasTypeParamAttribute',
u'type_param': u'long',
u'file': u'gtest_xml_output_unittest_.cc',
u'line': 178,
u'status': u'RUN',
u'result': u'COMPLETED',
u'time': u'*',
@ -536,6 +590,8 @@ EXPECTED_NON_EMPTY = {
u'testsuite': [{
u'name': u'HasValueParamAttribute/0',
u'value_param': u'33',
u'file': u'gtest_xml_output_unittest_.cc',
u'line': 162,
u'status': u'RUN',
u'result': u'COMPLETED',
u'time': u'*',
@ -544,6 +600,8 @@ EXPECTED_NON_EMPTY = {
}, {
u'name': u'HasValueParamAttribute/1',
u'value_param': u'42',
u'file': u'gtest_xml_output_unittest_.cc',
u'line': 162,
u'status': u'RUN',
u'result': u'COMPLETED',
u'time': u'*',
@ -552,6 +610,8 @@ EXPECTED_NON_EMPTY = {
}, {
u'name': u'AnotherTestThatHasValueParamAttribute/0',
u'value_param': u'33',
u'file': u'gtest_xml_output_unittest_.cc',
u'line': 163,
u'status': u'RUN',
u'result': u'COMPLETED',
u'time': u'*',
@ -560,6 +620,8 @@ EXPECTED_NON_EMPTY = {
}, {
u'name': u'AnotherTestThatHasValueParamAttribute/1',
u'value_param': u'42',
u'file': u'gtest_xml_output_unittest_.cc',
u'line': 163,
u'status': u'RUN',
u'result': u'COMPLETED',
u'time': u'*',
@ -603,6 +665,8 @@ EXPECTED_FILTERED = {
u'*',
u'testsuite': [{
u'name': u'Succeeds',
u'file': u'gtest_xml_output_unittest_.cc',
u'line': 51,
u'status': u'RUN',
u'result': u'COMPLETED',
u'time': u'*',

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

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

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

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

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

@ -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();
}

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

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

Loading…
Cancel
Save