Compare commits

...

3 Commits

Author SHA1 Message Date
Abseil Team
7f56ae0f08 Export Test - Do Not Merge
Rename internal color enumerators to avoid conflicts with curses.h macro definitions.
Fixes #2685

PiperOrigin-RevId: 297639382
2020-02-28 16:08:31 -05:00
Abseil Team
75feebda2f Export Test - Do Not Merge
Relax the implementation of MatcherCast to allow conversion of `Matcher<T>` to
`Matcher<const T&>`. They have the same match signature.

PiperOrigin-RevId: 297115843
2020-02-28 16:08:23 -05:00
Abseil Team
c914258241 Export Test - Do Not Merge
Allow construction of an Action from a callable of zero args

Action already allows construction from a callable with the same args as the mocked function, without needing to wrap the callable in Invoke. However, if you don't care about the arguments to the mocked function you need to either accept all of them or wrap your callable in InvokeWithoutArgs. This change makes both of those unnecessary, since it allows you to pass a no-args callable to Action directly.

PiperOrigin-RevId: 296117034
2020-02-28 16:08:12 -05:00
7 changed files with 130 additions and 76 deletions

View File

@ -2174,7 +2174,7 @@ own precedence order distinct from the `ON_CALL` precedence order.
### Using Functions/Methods/Functors/Lambdas as Actions {#FunctionsAsActions} ### Using Functions/Methods/Functors/Lambdas as Actions {#FunctionsAsActions}
If the built-in actions don't suit you, you can use an existing callable If the built-in actions don't suit you, you can use an existing callable
(function, `std::function`, method, functor, lambda as an action. (function, `std::function`, method, functor, lambda) as an action.
<!-- GOOGLETEST_CM0024 DO NOT DELETE --> <!-- GOOGLETEST_CM0024 DO NOT DELETE -->
@ -2203,6 +2203,7 @@ class Helper {
.WillRepeatedly(Invoke(NewPermanentCallback(Sum3, 1))); .WillRepeatedly(Invoke(NewPermanentCallback(Sum3, 1)));
EXPECT_CALL(foo, ComplexJob(_)) EXPECT_CALL(foo, ComplexJob(_))
.WillOnce(Invoke(&helper, &Helper::ComplexJob)) .WillOnce(Invoke(&helper, &Helper::ComplexJob))
.WillOnce([] { return true; })
.WillRepeatedly([](int x) { return x > 0; }); .WillRepeatedly([](int x) { return x > 0; });
foo.Sum(5, 6); // Invokes CalculateSum(5, 6). foo.Sum(5, 6); // Invokes CalculateSum(5, 6).
@ -2212,11 +2213,11 @@ class Helper {
``` ```
The only requirement is that the type of the function, etc must be *compatible* The only requirement is that the type of the function, etc must be *compatible*
with the signature of the mock function, meaning that the latter's arguments can with the signature of the mock function, meaning that the latter's arguments (if
be implicitly converted to the corresponding arguments of the former, and the it takes any) can be implicitly converted to the corresponding arguments of the
former's return type can be implicitly converted to that of the latter. So, you former, and the former's return type can be implicitly converted to that of the
can invoke something whose type is *not* exactly the same as the mock function, latter. So, you can invoke something whose type is *not* exactly the same as the
as long as it's safe to do so - nice, huh? mock function, as long as it's safe to do so - nice, huh?
**`Note:`{.escaped}** **`Note:`{.escaped}**
@ -2267,19 +2268,20 @@ TEST_F(FooTest, Test) {
### Invoking a Function/Method/Functor/Lambda/Callback Without Arguments ### Invoking a Function/Method/Functor/Lambda/Callback Without Arguments
`Invoke()` is very useful for doing actions that are more complex. It passes the `Invoke()` passes the mock function's arguments to the function, etc being
mock function's arguments to the function, etc being invoked such that the invoked such that the callee has the full context of the call to work with. If
callee has the full context of the call to work with. If the invoked function is the invoked function is not interested in some or all of the arguments, it can
not interested in some or all of the arguments, it can simply ignore them. simply ignore them.
Yet, a common pattern is that a test author wants to invoke a function without Yet, a common pattern is that a test author wants to invoke a function without
the arguments of the mock function. `Invoke()` allows her to do that using a the arguments of the mock function. She could do that using a wrapper function
wrapper function that throws away the arguments before invoking an underlining that throws away the arguments before invoking an underlining nullary function.
nullary function. Needless to say, this can be tedious and obscures the intent Needless to say, this can be tedious and obscures the intent of the test.
of the test.
`InvokeWithoutArgs()` solves this problem. It's like `Invoke()` except that it There are two solutions to this problem. First, you can pass any callable of
doesn't pass the mock function's arguments to the callee. Here's an example: zero args as an action. Alternatively, use `InvokeWithoutArgs()`, which is like
`Invoke()` except that it doesn't pass the mock function's arguments to the
callee. Here's an example of each:
```cpp ```cpp
using ::testing::_; using ::testing::_;
@ -2296,7 +2298,7 @@ bool Job2(int n, char c) { ... }
... ...
MockFoo foo; MockFoo foo;
EXPECT_CALL(foo, ComplexJob(_)) EXPECT_CALL(foo, ComplexJob(_))
.WillOnce(InvokeWithoutArgs(Job1)) .WillOnce([] { Job1(); });
.WillOnce(InvokeWithoutArgs(NewPermanentCallback(Job2, 5, 'a'))); .WillOnce(InvokeWithoutArgs(NewPermanentCallback(Job2, 5, 'a')));
foo.ComplexJob(10); // Invokes Job1(). foo.ComplexJob(10); // Invokes Job1().

View File

@ -263,6 +263,10 @@ GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(double, 0);
#undef GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_ #undef GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_
// Simple two-arg form of std::disjunction.
template <typename P, typename Q>
using disjunction = typename ::std::conditional<P::value, P, Q>::type;
} // namespace internal } // namespace internal
// When an unexpected function call is encountered, Google Mock will // When an unexpected function call is encountered, Google Mock will
@ -456,9 +460,15 @@ class Action {
// This cannot take std::function directly, because then Action would not be // This cannot take std::function directly, because then Action would not be
// directly constructible from lambda (it would require two conversions). // directly constructible from lambda (it would require two conversions).
template <typename G, template <typename G,
typename = typename ::std::enable_if< typename IsCompatibleFunctor =
::std::is_constructible<::std::function<F>, G>::value>::type> ::std::is_constructible<::std::function<F>, G>,
Action(G&& fun) : fun_(::std::forward<G>(fun)) {} // NOLINT typename IsNoArgsFunctor =
::std::is_constructible<::std::function<Result()>, G>,
typename = typename ::std::enable_if<internal::disjunction<
IsCompatibleFunctor, IsNoArgsFunctor>::value>::type>
Action(G&& fun) { // NOLINT
Init(::std::forward<G>(fun), IsCompatibleFunctor());
}
// Constructs an Action from its implementation. // Constructs an Action from its implementation.
explicit Action(ActionInterface<F>* impl) explicit Action(ActionInterface<F>* impl)
@ -490,6 +500,26 @@ class Action {
template <typename G> template <typename G>
friend class Action; friend class Action;
template <typename G>
void Init(G&& g, ::std::true_type) {
fun_ = ::std::forward<G>(g);
}
template <typename G>
void Init(G&& g, ::std::false_type) {
fun_ = IgnoreArgs<typename ::std::decay<G>::type>{::std::forward<G>(g)};
}
template <typename FunctionImpl>
struct IgnoreArgs {
template <typename... Args>
Result operator()(const Args&...) const {
return function_impl();
}
FunctionImpl function_impl;
};
// fun_ is an empty function if and only if this is the DoDefault() action. // fun_ is an empty function if and only if this is the DoDefault() action.
::std::function<F> fun_; ::std::function<F> fun_;
}; };

View File

@ -424,7 +424,14 @@ class MatcherCastImpl<T, Matcher<U> > {
!std::is_base_of<FromType, ToType>::value, !std::is_base_of<FromType, ToType>::value,
"Can't implicitly convert from <base> to <derived>"); "Can't implicitly convert from <base> to <derived>");
return source_matcher_.MatchAndExplain(static_cast<U>(x), listener); // Do the cast to `U` explicitly if necessary.
// Otherwise, let implicit conversions do the trick.
using CastType =
typename std::conditional<std::is_convertible<T&, const U&>::value,
T&, U>::type;
return source_matcher_.MatchAndExplain(static_cast<CastType>(x),
listener);
} }
void DescribeTo(::std::ostream* os) const override { void DescribeTo(::std::ostream* os) const override {
@ -524,7 +531,7 @@ inline Matcher<T> SafeMatcherCast(const M& polymorphic_matcher_or_value) {
template <typename T, typename U> template <typename T, typename U>
inline Matcher<T> SafeMatcherCast(const Matcher<U>& matcher) { inline Matcher<T> SafeMatcherCast(const Matcher<U>& matcher) {
// Enforce that T can be implicitly converted to U. // Enforce that T can be implicitly converted to U.
GTEST_COMPILE_ASSERT_((std::is_convertible<T, U>::value), static_assert(std::is_convertible<const T&, const U&>::value,
"T must be implicitly convertible to U"); "T must be implicitly convertible to U");
// Enforce that we are not converting a non-reference type T to a reference // Enforce that we are not converting a non-reference type T to a reference
// type U. // type U.

View File

@ -1470,8 +1470,19 @@ TEST(FunctorActionTest, TypeConversion) {
EXPECT_EQ(1, s2.Perform(std::make_tuple("hello"))); EXPECT_EQ(1, s2.Perform(std::make_tuple("hello")));
// Also between the lambda and the action itself. // Also between the lambda and the action itself.
const Action<bool(std::string)> x = [](Unused) { return 42; }; const Action<bool(std::string)> x1 = [](Unused) { return 42; };
EXPECT_TRUE(x.Perform(std::make_tuple("hello"))); const Action<bool(std::string)> x2 = [] { return 42; };
EXPECT_TRUE(x1.Perform(std::make_tuple("hello")));
EXPECT_TRUE(x2.Perform(std::make_tuple("hello")));
// Ensure decay occurs where required.
std::function<int()> f = [] { return 7; };
Action<int(int)> d = f;
f = nullptr;
EXPECT_EQ(7, d.Perform(std::make_tuple(1)));
// Ensure creation of an empty action succeeds.
Action<void(int)>(nullptr);
} }
TEST(FunctorActionTest, UnusedArguments) { TEST(FunctorActionTest, UnusedArguments) {

View File

@ -765,10 +765,11 @@ TEST(SafeMatcherCastTest, FromConstReferenceToReference) {
// Tests that MatcherCast<const T&>(m) works when m is a Matcher<T>. // Tests that MatcherCast<const T&>(m) works when m is a Matcher<T>.
TEST(SafeMatcherCastTest, FromNonReferenceToConstReference) { TEST(SafeMatcherCastTest, FromNonReferenceToConstReference) {
Matcher<int> m1 = Eq(0); Matcher<std::unique_ptr<int>> m1 = IsNull();
Matcher<const int&> m2 = SafeMatcherCast<const int&>(m1); Matcher<const std::unique_ptr<int>&> m2 =
EXPECT_TRUE(m2.Matches(0)); SafeMatcherCast<const std::unique_ptr<int>&>(m1);
EXPECT_FALSE(m2.Matches(1)); EXPECT_TRUE(m2.Matches(std::unique_ptr<int>()));
EXPECT_FALSE(m2.Matches(std::unique_ptr<int>(new int)));
} }
// Tests that SafeMatcherCast<T&>(m) works when m is a Matcher<T>. // Tests that SafeMatcherCast<T&>(m) works when m is a Matcher<T>.

View File

@ -1807,7 +1807,7 @@ class GTEST_API_ AssertHelper {
GTEST_DISALLOW_COPY_AND_ASSIGN_(AssertHelper); GTEST_DISALLOW_COPY_AND_ASSIGN_(AssertHelper);
}; };
enum GTestColor { COLOR_DEFAULT, COLOR_RED, COLOR_GREEN, COLOR_YELLOW }; enum class GTestColor { kDefault, kRed, kGreen, kYellow };
GTEST_API_ GTEST_ATTRIBUTE_PRINTF_(2, 3) void ColoredPrintf(GTestColor color, GTEST_API_ GTEST_ATTRIBUTE_PRINTF_(2, 3) void ColoredPrintf(GTestColor color,
const char* fmt, const char* fmt,

View File

@ -3093,9 +3093,12 @@ static void PrintTestPartResult(const TestPartResult& test_part_result) {
// Returns the character attribute for the given color. // Returns the character attribute for the given color.
static WORD GetColorAttribute(GTestColor color) { static WORD GetColorAttribute(GTestColor color) {
switch (color) { switch (color) {
case COLOR_RED: return FOREGROUND_RED; case GTestColor::kRed:
case COLOR_GREEN: return FOREGROUND_GREEN; return FOREGROUND_RED;
case COLOR_YELLOW: return FOREGROUND_RED | FOREGROUND_GREEN; case GTestColor::kGreen:
return FOREGROUND_GREEN;
case GTestColor::kYellow:
return FOREGROUND_RED | FOREGROUND_GREEN;
default: return 0; default: return 0;
} }
} }
@ -3133,13 +3136,16 @@ static WORD GetNewColor(GTestColor color, WORD old_color_attrs) {
#else #else
// Returns the ANSI color code for the given color. COLOR_DEFAULT is // Returns the ANSI color code for the given color. GTestColor::kDefault is
// an invalid input. // an invalid input.
static const char* GetAnsiColorCode(GTestColor color) { static const char* GetAnsiColorCode(GTestColor color) {
switch (color) { switch (color) {
case COLOR_RED: return "1"; case GTestColor::kRed:
case COLOR_GREEN: return "2"; return "1";
case COLOR_YELLOW: return "3"; case GTestColor::kGreen:
return "2";
case GTestColor::kYellow:
return "3";
default: default:
return nullptr; return nullptr;
} }
@ -3198,7 +3204,7 @@ void ColoredPrintf(GTestColor color, const char* fmt, ...) {
#else #else
static const bool in_color_mode = static const bool in_color_mode =
ShouldUseColor(posix::IsATTY(posix::FileNo(stdout)) != 0); ShouldUseColor(posix::IsATTY(posix::FileNo(stdout)) != 0);
const bool use_color = in_color_mode && (color != COLOR_DEFAULT); const bool use_color = in_color_mode && (color != GTestColor::kDefault);
#endif // GTEST_OS_WINDOWS_MOBILE || GTEST_OS_ZOS #endif // GTEST_OS_WINDOWS_MOBILE || GTEST_OS_ZOS
if (!use_color) { if (!use_color) {
@ -3310,25 +3316,24 @@ void PrettyUnitTestResultPrinter::OnTestIterationStart(
// Prints the filter if it's not *. This reminds the user that some // Prints the filter if it's not *. This reminds the user that some
// tests may be skipped. // tests may be skipped.
if (!String::CStringEquals(filter, kUniversalFilter)) { if (!String::CStringEquals(filter, kUniversalFilter)) {
ColoredPrintf(COLOR_YELLOW, ColoredPrintf(GTestColor::kYellow, "Note: %s filter = %s\n", GTEST_NAME_,
"Note: %s filter = %s\n", GTEST_NAME_, filter); filter);
} }
if (internal::ShouldShard(kTestTotalShards, kTestShardIndex, false)) { if (internal::ShouldShard(kTestTotalShards, kTestShardIndex, false)) {
const int32_t shard_index = Int32FromEnvOrDie(kTestShardIndex, -1); const int32_t shard_index = Int32FromEnvOrDie(kTestShardIndex, -1);
ColoredPrintf(COLOR_YELLOW, ColoredPrintf(GTestColor::kYellow, "Note: This is test shard %d of %s.\n",
"Note: This is test shard %d of %s.\n",
static_cast<int>(shard_index) + 1, static_cast<int>(shard_index) + 1,
internal::posix::GetEnv(kTestTotalShards)); internal::posix::GetEnv(kTestTotalShards));
} }
if (GTEST_FLAG(shuffle)) { if (GTEST_FLAG(shuffle)) {
ColoredPrintf(COLOR_YELLOW, ColoredPrintf(GTestColor::kYellow,
"Note: Randomizing tests' orders with a seed of %d .\n", "Note: Randomizing tests' orders with a seed of %d .\n",
unit_test.random_seed()); unit_test.random_seed());
} }
ColoredPrintf(COLOR_GREEN, "[==========] "); ColoredPrintf(GTestColor::kGreen, "[==========] ");
printf("Running %s from %s.\n", printf("Running %s from %s.\n",
FormatTestCount(unit_test.test_to_run_count()).c_str(), FormatTestCount(unit_test.test_to_run_count()).c_str(),
FormatTestSuiteCount(unit_test.test_suite_to_run_count()).c_str()); FormatTestSuiteCount(unit_test.test_suite_to_run_count()).c_str());
@ -3337,7 +3342,7 @@ void PrettyUnitTestResultPrinter::OnTestIterationStart(
void PrettyUnitTestResultPrinter::OnEnvironmentsSetUpStart( void PrettyUnitTestResultPrinter::OnEnvironmentsSetUpStart(
const UnitTest& /*unit_test*/) { const UnitTest& /*unit_test*/) {
ColoredPrintf(COLOR_GREEN, "[----------] "); ColoredPrintf(GTestColor::kGreen, "[----------] ");
printf("Global test environment set-up.\n"); printf("Global test environment set-up.\n");
fflush(stdout); fflush(stdout);
} }
@ -3346,7 +3351,7 @@ void PrettyUnitTestResultPrinter::OnEnvironmentsSetUpStart(
void PrettyUnitTestResultPrinter::OnTestCaseStart(const TestCase& test_case) { void PrettyUnitTestResultPrinter::OnTestCaseStart(const TestCase& test_case) {
const std::string counts = const std::string counts =
FormatCountableNoun(test_case.test_to_run_count(), "test", "tests"); FormatCountableNoun(test_case.test_to_run_count(), "test", "tests");
ColoredPrintf(COLOR_GREEN, "[----------] "); ColoredPrintf(GTestColor::kGreen, "[----------] ");
printf("%s from %s", counts.c_str(), test_case.name()); printf("%s from %s", counts.c_str(), test_case.name());
if (test_case.type_param() == nullptr) { if (test_case.type_param() == nullptr) {
printf("\n"); printf("\n");
@ -3360,7 +3365,7 @@ void PrettyUnitTestResultPrinter::OnTestSuiteStart(
const TestSuite& test_suite) { const TestSuite& test_suite) {
const std::string counts = const std::string counts =
FormatCountableNoun(test_suite.test_to_run_count(), "test", "tests"); FormatCountableNoun(test_suite.test_to_run_count(), "test", "tests");
ColoredPrintf(COLOR_GREEN, "[----------] "); ColoredPrintf(GTestColor::kGreen, "[----------] ");
printf("%s from %s", counts.c_str(), test_suite.name()); printf("%s from %s", counts.c_str(), test_suite.name());
if (test_suite.type_param() == nullptr) { if (test_suite.type_param() == nullptr) {
printf("\n"); printf("\n");
@ -3372,7 +3377,7 @@ void PrettyUnitTestResultPrinter::OnTestSuiteStart(
#endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_ #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
void PrettyUnitTestResultPrinter::OnTestStart(const TestInfo& test_info) { void PrettyUnitTestResultPrinter::OnTestStart(const TestInfo& test_info) {
ColoredPrintf(COLOR_GREEN, "[ RUN ] "); ColoredPrintf(GTestColor::kGreen, "[ RUN ] ");
PrintTestName(test_info.test_suite_name(), test_info.name()); PrintTestName(test_info.test_suite_name(), test_info.name());
printf("\n"); printf("\n");
fflush(stdout); fflush(stdout);
@ -3395,11 +3400,11 @@ void PrettyUnitTestResultPrinter::OnTestPartResult(
void PrettyUnitTestResultPrinter::OnTestEnd(const TestInfo& test_info) { void PrettyUnitTestResultPrinter::OnTestEnd(const TestInfo& test_info) {
if (test_info.result()->Passed()) { if (test_info.result()->Passed()) {
ColoredPrintf(COLOR_GREEN, "[ OK ] "); ColoredPrintf(GTestColor::kGreen, "[ OK ] ");
} else if (test_info.result()->Skipped()) { } else if (test_info.result()->Skipped()) {
ColoredPrintf(COLOR_GREEN, "[ SKIPPED ] "); ColoredPrintf(GTestColor::kGreen, "[ SKIPPED ] ");
} else { } else {
ColoredPrintf(COLOR_RED, "[ FAILED ] "); ColoredPrintf(GTestColor::kRed, "[ FAILED ] ");
} }
PrintTestName(test_info.test_suite_name(), test_info.name()); PrintTestName(test_info.test_suite_name(), test_info.name());
if (test_info.result()->Failed()) if (test_info.result()->Failed())
@ -3420,7 +3425,7 @@ void PrettyUnitTestResultPrinter::OnTestCaseEnd(const TestCase& test_case) {
const std::string counts = const std::string counts =
FormatCountableNoun(test_case.test_to_run_count(), "test", "tests"); FormatCountableNoun(test_case.test_to_run_count(), "test", "tests");
ColoredPrintf(COLOR_GREEN, "[----------] "); ColoredPrintf(GTestColor::kGreen, "[----------] ");
printf("%s from %s (%s ms total)\n\n", counts.c_str(), test_case.name(), printf("%s from %s (%s ms total)\n\n", counts.c_str(), test_case.name(),
internal::StreamableToString(test_case.elapsed_time()).c_str()); internal::StreamableToString(test_case.elapsed_time()).c_str());
fflush(stdout); fflush(stdout);
@ -3431,7 +3436,7 @@ void PrettyUnitTestResultPrinter::OnTestSuiteEnd(const TestSuite& test_suite) {
const std::string counts = const std::string counts =
FormatCountableNoun(test_suite.test_to_run_count(), "test", "tests"); FormatCountableNoun(test_suite.test_to_run_count(), "test", "tests");
ColoredPrintf(COLOR_GREEN, "[----------] "); ColoredPrintf(GTestColor::kGreen, "[----------] ");
printf("%s from %s (%s ms total)\n\n", counts.c_str(), test_suite.name(), printf("%s from %s (%s ms total)\n\n", counts.c_str(), test_suite.name(),
internal::StreamableToString(test_suite.elapsed_time()).c_str()); internal::StreamableToString(test_suite.elapsed_time()).c_str());
fflush(stdout); fflush(stdout);
@ -3440,7 +3445,7 @@ void PrettyUnitTestResultPrinter::OnTestSuiteEnd(const TestSuite& test_suite) {
void PrettyUnitTestResultPrinter::OnEnvironmentsTearDownStart( void PrettyUnitTestResultPrinter::OnEnvironmentsTearDownStart(
const UnitTest& /*unit_test*/) { const UnitTest& /*unit_test*/) {
ColoredPrintf(COLOR_GREEN, "[----------] "); ColoredPrintf(GTestColor::kGreen, "[----------] ");
printf("Global test environment tear-down\n"); printf("Global test environment tear-down\n");
fflush(stdout); fflush(stdout);
} }
@ -3448,7 +3453,7 @@ void PrettyUnitTestResultPrinter::OnEnvironmentsTearDownStart(
// Internal helper for printing the list of failed tests. // Internal helper for printing the list of failed tests.
void PrettyUnitTestResultPrinter::PrintFailedTests(const UnitTest& unit_test) { void PrettyUnitTestResultPrinter::PrintFailedTests(const UnitTest& unit_test) {
const int failed_test_count = unit_test.failed_test_count(); const int failed_test_count = unit_test.failed_test_count();
ColoredPrintf(COLOR_RED, "[ FAILED ] "); ColoredPrintf(GTestColor::kRed, "[ FAILED ] ");
printf("%s, listed below:\n", FormatTestCount(failed_test_count).c_str()); printf("%s, listed below:\n", FormatTestCount(failed_test_count).c_str());
for (int i = 0; i < unit_test.total_test_suite_count(); ++i) { for (int i = 0; i < unit_test.total_test_suite_count(); ++i) {
@ -3461,7 +3466,7 @@ void PrettyUnitTestResultPrinter::PrintFailedTests(const UnitTest& unit_test) {
if (!test_info.should_run() || !test_info.result()->Failed()) { if (!test_info.should_run() || !test_info.result()->Failed()) {
continue; continue;
} }
ColoredPrintf(COLOR_RED, "[ FAILED ] "); ColoredPrintf(GTestColor::kRed, "[ FAILED ] ");
printf("%s.%s", test_suite.name(), test_info.name()); printf("%s.%s", test_suite.name(), test_info.name());
PrintFullTestCommentIfPresent(test_info); PrintFullTestCommentIfPresent(test_info);
printf("\n"); printf("\n");
@ -3482,7 +3487,7 @@ void PrettyUnitTestResultPrinter::PrintFailedTestSuites(
continue; continue;
} }
if (test_suite.ad_hoc_test_result().Failed()) { if (test_suite.ad_hoc_test_result().Failed()) {
ColoredPrintf(COLOR_RED, "[ FAILED ] "); ColoredPrintf(GTestColor::kRed, "[ FAILED ] ");
printf("%s: SetUpTestSuite or TearDownTestSuite\n", test_suite.name()); printf("%s: SetUpTestSuite or TearDownTestSuite\n", test_suite.name());
++suite_failure_count; ++suite_failure_count;
} }
@ -3510,7 +3515,7 @@ void PrettyUnitTestResultPrinter::PrintSkippedTests(const UnitTest& unit_test) {
if (!test_info.should_run() || !test_info.result()->Skipped()) { if (!test_info.should_run() || !test_info.result()->Skipped()) {
continue; continue;
} }
ColoredPrintf(COLOR_GREEN, "[ SKIPPED ] "); ColoredPrintf(GTestColor::kGreen, "[ SKIPPED ] ");
printf("%s.%s", test_suite.name(), test_info.name()); printf("%s.%s", test_suite.name(), test_info.name());
printf("\n"); printf("\n");
} }
@ -3519,7 +3524,7 @@ void PrettyUnitTestResultPrinter::PrintSkippedTests(const UnitTest& unit_test) {
void PrettyUnitTestResultPrinter::OnTestIterationEnd(const UnitTest& unit_test, void PrettyUnitTestResultPrinter::OnTestIterationEnd(const UnitTest& unit_test,
int /*iteration*/) { int /*iteration*/) {
ColoredPrintf(COLOR_GREEN, "[==========] "); ColoredPrintf(GTestColor::kGreen, "[==========] ");
printf("%s from %s ran.", printf("%s from %s ran.",
FormatTestCount(unit_test.test_to_run_count()).c_str(), FormatTestCount(unit_test.test_to_run_count()).c_str(),
FormatTestSuiteCount(unit_test.test_suite_to_run_count()).c_str()); FormatTestSuiteCount(unit_test.test_suite_to_run_count()).c_str());
@ -3528,12 +3533,12 @@ void PrettyUnitTestResultPrinter::OnTestIterationEnd(const UnitTest& unit_test,
internal::StreamableToString(unit_test.elapsed_time()).c_str()); internal::StreamableToString(unit_test.elapsed_time()).c_str());
} }
printf("\n"); printf("\n");
ColoredPrintf(COLOR_GREEN, "[ PASSED ] "); ColoredPrintf(GTestColor::kGreen, "[ PASSED ] ");
printf("%s.\n", FormatTestCount(unit_test.successful_test_count()).c_str()); printf("%s.\n", FormatTestCount(unit_test.successful_test_count()).c_str());
const int skipped_test_count = unit_test.skipped_test_count(); const int skipped_test_count = unit_test.skipped_test_count();
if (skipped_test_count > 0) { if (skipped_test_count > 0) {
ColoredPrintf(COLOR_GREEN, "[ SKIPPED ] "); ColoredPrintf(GTestColor::kGreen, "[ SKIPPED ] ");
printf("%s, listed below:\n", FormatTestCount(skipped_test_count).c_str()); printf("%s, listed below:\n", FormatTestCount(skipped_test_count).c_str());
PrintSkippedTests(unit_test); PrintSkippedTests(unit_test);
} }
@ -3548,10 +3553,8 @@ void PrettyUnitTestResultPrinter::OnTestIterationEnd(const UnitTest& unit_test,
if (unit_test.Passed()) { if (unit_test.Passed()) {
printf("\n"); // Add a spacer if no FAILURE banner is displayed. printf("\n"); // Add a spacer if no FAILURE banner is displayed.
} }
ColoredPrintf(COLOR_YELLOW, ColoredPrintf(GTestColor::kYellow, " YOU HAVE %d DISABLED %s\n\n",
" YOU HAVE %d DISABLED %s\n\n", num_disabled, num_disabled == 1 ? "TEST" : "TESTS");
num_disabled,
num_disabled == 1 ? "TEST" : "TESTS");
} }
// Ensure that Google Test output is printed before, e.g., heapchecker output. // Ensure that Google Test output is printed before, e.g., heapchecker output.
fflush(stdout); fflush(stdout);
@ -5554,14 +5557,14 @@ bool UnitTestImpl::RunAllTests() {
if (!gtest_is_initialized_before_run_all_tests) { if (!gtest_is_initialized_before_run_all_tests) {
ColoredPrintf( ColoredPrintf(
COLOR_RED, GTestColor::kRed,
"\nIMPORTANT NOTICE - DO NOT IGNORE:\n" "\nIMPORTANT NOTICE - DO NOT IGNORE:\n"
"This test program did NOT call " GTEST_INIT_GOOGLE_TEST_NAME_ "This test program did NOT call " GTEST_INIT_GOOGLE_TEST_NAME_
"() before calling RUN_ALL_TESTS(). This is INVALID. Soon " GTEST_NAME_ "() before calling RUN_ALL_TESTS(). This is INVALID. Soon " GTEST_NAME_
" will start to enforce the valid usage. " " will start to enforce the valid usage. "
"Please fix it ASAP, or IT WILL START TO FAIL.\n"); // NOLINT "Please fix it ASAP, or IT WILL START TO FAIL.\n"); // NOLINT
#if GTEST_FOR_GOOGLE_ #if GTEST_FOR_GOOGLE_
ColoredPrintf(COLOR_RED, ColoredPrintf(GTestColor::kRed,
"For more details, see http://wiki/Main/ValidGUnitMain.\n"); "For more details, see http://wiki/Main/ValidGUnitMain.\n");
#endif // GTEST_FOR_GOOGLE_ #endif // GTEST_FOR_GOOGLE_
} }
@ -5578,7 +5581,7 @@ void WriteToShardStatusFileIfNeeded() {
if (test_shard_file != nullptr) { if (test_shard_file != nullptr) {
FILE* const file = posix::FOpen(test_shard_file, "w"); FILE* const file = posix::FOpen(test_shard_file, "w");
if (file == nullptr) { if (file == nullptr) {
ColoredPrintf(COLOR_RED, ColoredPrintf(GTestColor::kRed,
"Could not write to the test shard status file \"%s\" " "Could not write to the test shard status file \"%s\" "
"specified by the %s environment variable.\n", "specified by the %s environment variable.\n",
test_shard_file, kTestShardStatusFile); test_shard_file, kTestShardStatusFile);
@ -5612,7 +5615,7 @@ bool ShouldShard(const char* total_shards_env,
<< "Invalid environment variables: you have " << "Invalid environment variables: you have "
<< kTestShardIndex << " = " << shard_index << kTestShardIndex << " = " << shard_index
<< ", but have left " << kTestTotalShards << " unset.\n"; << ", but have left " << kTestTotalShards << " unset.\n";
ColoredPrintf(COLOR_RED, "%s", msg.GetString().c_str()); ColoredPrintf(GTestColor::kRed, "%s", msg.GetString().c_str());
fflush(stdout); fflush(stdout);
exit(EXIT_FAILURE); exit(EXIT_FAILURE);
} else if (total_shards != -1 && shard_index == -1) { } else if (total_shards != -1 && shard_index == -1) {
@ -5620,7 +5623,7 @@ bool ShouldShard(const char* total_shards_env,
<< "Invalid environment variables: you have " << "Invalid environment variables: you have "
<< kTestTotalShards << " = " << total_shards << kTestTotalShards << " = " << total_shards
<< ", but have left " << kTestShardIndex << " unset.\n"; << ", but have left " << kTestShardIndex << " unset.\n";
ColoredPrintf(COLOR_RED, "%s", msg.GetString().c_str()); ColoredPrintf(GTestColor::kRed, "%s", msg.GetString().c_str());
fflush(stdout); fflush(stdout);
exit(EXIT_FAILURE); exit(EXIT_FAILURE);
} else if (shard_index < 0 || shard_index >= total_shards) { } else if (shard_index < 0 || shard_index >= total_shards) {
@ -5629,7 +5632,7 @@ bool ShouldShard(const char* total_shards_env,
<< kTestShardIndex << " < " << kTestTotalShards << kTestShardIndex << " < " << kTestTotalShards
<< ", but you have " << kTestShardIndex << "=" << shard_index << ", but you have " << kTestShardIndex << "=" << shard_index
<< ", " << kTestTotalShards << "=" << total_shards << ".\n"; << ", " << kTestTotalShards << "=" << total_shards << ".\n";
ColoredPrintf(COLOR_RED, "%s", msg.GetString().c_str()); ColoredPrintf(GTestColor::kRed, "%s", msg.GetString().c_str());
fflush(stdout); fflush(stdout);
exit(EXIT_FAILURE); exit(EXIT_FAILURE);
} }
@ -6019,7 +6022,7 @@ static bool HasGoogleTestFlagPrefix(const char* str) {
// @D changes to the default terminal text color. // @D changes to the default terminal text color.
// //
static void PrintColorEncoded(const char* str) { static void PrintColorEncoded(const char* str) {
GTestColor color = COLOR_DEFAULT; // The current color. GTestColor color = GTestColor::kDefault; // The current color.
// Conceptually, we split the string into segments divided by escape // Conceptually, we split the string into segments divided by escape
// sequences. Then we print one segment at a time. At the end of // sequences. Then we print one segment at a time. At the end of
@ -6039,13 +6042,13 @@ static void PrintColorEncoded(const char* str) {
if (ch == '@') { if (ch == '@') {
ColoredPrintf(color, "@"); ColoredPrintf(color, "@");
} else if (ch == 'D') { } else if (ch == 'D') {
color = COLOR_DEFAULT; color = GTestColor::kDefault;
} else if (ch == 'R') { } else if (ch == 'R') {
color = COLOR_RED; color = GTestColor::kRed;
} else if (ch == 'G') { } else if (ch == 'G') {
color = COLOR_GREEN; color = GTestColor::kGreen;
} else if (ch == 'Y') { } else if (ch == 'Y') {
color = COLOR_YELLOW; color = GTestColor::kYellow;
} else { } else {
--str; --str;
} }