Unverified Commit 9e712372 authored by Brad Messer's avatar Brad Messer Committed by GitHub
Browse files

Merge branch 'main' into promote-inclusive-behavior

parents 794da715 b007c54f
...@@ -60,69 +60,70 @@ ...@@ -60,69 +60,70 @@
#if GTEST_OS_LINUX #if GTEST_OS_LINUX
# include <fcntl.h> // NOLINT #include <fcntl.h> // NOLINT
# include <limits.h> // NOLINT #include <limits.h> // NOLINT
# include <sched.h> // NOLINT #include <sched.h> // NOLINT
// Declares vsnprintf(). This header is not available on Windows. // Declares vsnprintf(). This header is not available on Windows.
# include <strings.h> // NOLINT #include <strings.h> // NOLINT
# include <sys/mman.h> // NOLINT #include <sys/mman.h> // NOLINT
# include <sys/time.h> // NOLINT #include <sys/time.h> // NOLINT
# include <unistd.h> // NOLINT #include <unistd.h> // NOLINT
# include <string>
#include <string>
#elif GTEST_OS_ZOS #elif GTEST_OS_ZOS
# include <sys/time.h> // NOLINT #include <sys/time.h> // NOLINT
// On z/OS we additionally need strings.h for strcasecmp. // On z/OS we additionally need strings.h for strcasecmp.
# include <strings.h> // NOLINT #include <strings.h> // NOLINT
#elif GTEST_OS_WINDOWS_MOBILE // We are on Windows CE. #elif GTEST_OS_WINDOWS_MOBILE // We are on Windows CE.
# include <windows.h> // NOLINT #include <windows.h> // NOLINT
# undef min #undef min
#elif GTEST_OS_WINDOWS // We are on Windows proper. #elif GTEST_OS_WINDOWS // We are on Windows proper.
# include <windows.h> // NOLINT #include <windows.h> // NOLINT
# undef min #undef min
#ifdef _MSC_VER #ifdef _MSC_VER
# include <crtdbg.h> // NOLINT #include <crtdbg.h> // NOLINT
#endif #endif
# include <io.h> // NOLINT #include <io.h> // NOLINT
# include <sys/timeb.h> // NOLINT #include <sys/stat.h> // NOLINT
# include <sys/types.h> // NOLINT #include <sys/timeb.h> // NOLINT
# include <sys/stat.h> // NOLINT #include <sys/types.h> // NOLINT
# if GTEST_OS_WINDOWS_MINGW #if GTEST_OS_WINDOWS_MINGW
# include <sys/time.h> // NOLINT #include <sys/time.h> // NOLINT
# endif // GTEST_OS_WINDOWS_MINGW #endif // GTEST_OS_WINDOWS_MINGW
#else #else
// cpplint thinks that the header is already included, so we want to // cpplint thinks that the header is already included, so we want to
// silence it. // silence it.
# include <sys/time.h> // NOLINT #include <sys/time.h> // NOLINT
# include <unistd.h> // NOLINT #include <unistd.h> // NOLINT
#endif // GTEST_OS_LINUX #endif // GTEST_OS_LINUX
#if GTEST_HAS_EXCEPTIONS #if GTEST_HAS_EXCEPTIONS
# include <stdexcept> #include <stdexcept>
#endif #endif
#if GTEST_CAN_STREAM_RESULTS_ #if GTEST_CAN_STREAM_RESULTS_
# include <arpa/inet.h> // NOLINT #include <arpa/inet.h> // NOLINT
# include <netdb.h> // NOLINT #include <netdb.h> // NOLINT
# include <sys/socket.h> // NOLINT #include <sys/socket.h> // NOLINT
# include <sys/types.h> // NOLINT #include <sys/types.h> // NOLINT
#endif #endif
#include "src/gtest-internal-inl.h" #include "src/gtest-internal-inl.h"
#if GTEST_OS_WINDOWS #if GTEST_OS_WINDOWS
# define vsnprintf _vsnprintf #define vsnprintf _vsnprintf
#endif // GTEST_OS_WINDOWS #endif // GTEST_OS_WINDOWS
#if GTEST_OS_MAC #if GTEST_OS_MAC
...@@ -271,8 +272,7 @@ GTEST_DEFINE_bool_( ...@@ -271,8 +272,7 @@ GTEST_DEFINE_bool_(
"install a signal handler that dumps debugging information when fatal " "install a signal handler that dumps debugging information when fatal "
"signals are raised."); "signals are raised.");
GTEST_DEFINE_bool_(list_tests, false, GTEST_DEFINE_bool_(list_tests, false, "List all tests without running them.");
"List all tests without running them.");
// The net priority order after flag processing is thus: // The net priority order after flag processing is thus:
// --gtest_output command line flag // --gtest_output command line flag
...@@ -374,10 +374,9 @@ namespace internal { ...@@ -374,10 +374,9 @@ namespace internal {
uint32_t Random::Generate(uint32_t range) { uint32_t Random::Generate(uint32_t range) {
// These constants are the same as are used in glibc's rand(3). // These constants are the same as are used in glibc's rand(3).
// Use wider types than necessary to prevent unsigned overflow diagnostics. // Use wider types than necessary to prevent unsigned overflow diagnostics.
state_ = static_cast<uint32_t>(1103515245ULL*state_ + 12345U) % kMaxRange; state_ = static_cast<uint32_t>(1103515245ULL * state_ + 12345U) % kMaxRange;
GTEST_CHECK_(range > 0) GTEST_CHECK_(range > 0) << "Cannot generate a number in the range [0, 0).";
<< "Cannot generate a number in the range [0, 0).";
GTEST_CHECK_(range <= kMaxRange) GTEST_CHECK_(range <= kMaxRange)
<< "Generation of a number in [0, " << range << ") was requested, " << "Generation of a number in [0, " << range << ") was requested, "
<< "but this can only generate numbers in [0, " << kMaxRange << ")."; << "but this can only generate numbers in [0, " << kMaxRange << ").";
...@@ -422,26 +421,20 @@ static bool ShouldRunTestSuite(const TestSuite* test_suite) { ...@@ -422,26 +421,20 @@ static bool ShouldRunTestSuite(const TestSuite* test_suite) {
} }
// AssertHelper constructor. // AssertHelper constructor.
AssertHelper::AssertHelper(TestPartResult::Type type, AssertHelper::AssertHelper(TestPartResult::Type type, const char* file,
const char* file, int line, const char* message)
int line, : data_(new AssertHelperData(type, file, line, message)) {}
const char* message)
: data_(new AssertHelperData(type, file, line, message)) {
}
AssertHelper::~AssertHelper() { AssertHelper::~AssertHelper() { delete data_; }
delete data_;
}
// Message assignment, for assertion streaming support. // Message assignment, for assertion streaming support.
void AssertHelper::operator=(const Message& message) const { void AssertHelper::operator=(const Message& message) const {
UnitTest::GetInstance()-> UnitTest::GetInstance()->AddTestPartResult(
AddTestPartResult(data_->type, data_->file, data_->line, data_->type, data_->file, data_->line,
AppendUserMessage(data_->message, message), AppendUserMessage(data_->message, message),
UnitTest::GetInstance()->impl() UnitTest::GetInstance()->impl()->CurrentOsStackTraceExceptTop(1)
->CurrentOsStackTraceExceptTop(1) // Skips the stack frame for this function itself.
// Skips the stack frame for this function itself. ); // NOLINT
); // NOLINT
} }
namespace { namespace {
...@@ -478,7 +471,6 @@ class FailureTest : public Test { ...@@ -478,7 +471,6 @@ class FailureTest : public Test {
const bool as_error_; const bool as_error_;
}; };
} // namespace } // namespace
std::set<std::string>* GetIgnoredParameterizedTestSuites() { std::set<std::string>* GetIgnoredParameterizedTestSuites() {
...@@ -522,7 +514,8 @@ void InsertSyntheticTestCase(const std::string& name, CodeLocation location, ...@@ -522,7 +514,8 @@ void InsertSyntheticTestCase(const std::string& name, CodeLocation location,
"To suppress this error for this test suite, insert the following line " "To suppress this error for this test suite, insert the following line "
"(in a non-header) in the namespace it is defined in:" "(in a non-header) in the namespace it is defined in:"
"\n\n" "\n\n"
"GTEST_ALLOW_UNINSTANTIATED_PARAMETERIZED_TEST(" + name + ");"; "GTEST_ALLOW_UNINSTANTIATED_PARAMETERIZED_TEST(" +
name + ");";
std::string full_name = "UninstantiatedParameterizedTestSuite<" + name + ">"; std::string full_name = "UninstantiatedParameterizedTestSuite<" + name + ">";
RegisterTest( // RegisterTest( //
...@@ -542,19 +535,18 @@ void RegisterTypeParameterizedTestSuite(const char* test_suite_name, ...@@ -542,19 +535,18 @@ void RegisterTypeParameterizedTestSuite(const char* test_suite_name,
} }
void RegisterTypeParameterizedTestSuiteInstantiation(const char* case_name) { void RegisterTypeParameterizedTestSuiteInstantiation(const char* case_name) {
GetUnitTestImpl() GetUnitTestImpl()->type_parameterized_test_registry().RegisterInstantiation(
->type_parameterized_test_registry() case_name);
.RegisterInstantiation(case_name);
} }
void TypeParameterizedTestSuiteRegistry::RegisterTestSuite( void TypeParameterizedTestSuiteRegistry::RegisterTestSuite(
const char* test_suite_name, CodeLocation code_location) { const char* test_suite_name, CodeLocation code_location) {
suites_.emplace(std::string(test_suite_name), suites_.emplace(std::string(test_suite_name),
TypeParameterizedTestSuiteInfo(code_location)); TypeParameterizedTestSuiteInfo(code_location));
} }
void TypeParameterizedTestSuiteRegistry::RegisterInstantiation( void TypeParameterizedTestSuiteRegistry::RegisterInstantiation(
const char* test_suite_name) { const char* test_suite_name) {
auto it = suites_.find(std::string(test_suite_name)); auto it = suites_.find(std::string(test_suite_name));
if (it != suites_.end()) { if (it != suites_.end()) {
it->second.instantiated = true; it->second.instantiated = true;
...@@ -648,16 +640,15 @@ std::string UnitTestOptions::GetAbsolutePathToOutputFile() { ...@@ -648,16 +640,15 @@ std::string UnitTestOptions::GetAbsolutePathToOutputFile() {
const char* const gtest_output_flag = s.c_str(); const char* const gtest_output_flag = s.c_str();
std::string format = GetOutputFormat(); std::string format = GetOutputFormat();
if (format.empty()) if (format.empty()) format = std::string(kDefaultOutputFormat);
format = std::string(kDefaultOutputFormat);
const char* const colon = strchr(gtest_output_flag, ':'); const char* const colon = strchr(gtest_output_flag, ':');
if (colon == nullptr) if (colon == nullptr)
return internal::FilePath::MakeFileName( return internal::FilePath::MakeFileName(
internal::FilePath( internal::FilePath(
UnitTest::GetInstance()->original_working_dir()), UnitTest::GetInstance()->original_working_dir()),
internal::FilePath(kDefaultOutputFile), 0, internal::FilePath(kDefaultOutputFile), 0, format.c_str())
format.c_str()).string(); .string();
internal::FilePath output_name(colon + 1); internal::FilePath output_name(colon + 1);
if (!output_name.IsAbsolutePath()) if (!output_name.IsAbsolutePath())
...@@ -665,8 +656,7 @@ std::string UnitTestOptions::GetAbsolutePathToOutputFile() { ...@@ -665,8 +656,7 @@ std::string UnitTestOptions::GetAbsolutePathToOutputFile() {
internal::FilePath(UnitTest::GetInstance()->original_working_dir()), internal::FilePath(UnitTest::GetInstance()->original_working_dir()),
internal::FilePath(colon + 1)); internal::FilePath(colon + 1));
if (!output_name.IsDirectory()) if (!output_name.IsDirectory()) return output_name.string();
return output_name.string();
internal::FilePath result(internal::FilePath::GenerateUniqueFileName( internal::FilePath result(internal::FilePath::GenerateUniqueFileName(
output_name, internal::GetCurrentExecutableName(), output_name, internal::GetCurrentExecutableName(),
...@@ -877,8 +867,7 @@ int UnitTestOptions::GTestShouldProcessSEH(DWORD exception_code) { ...@@ -877,8 +867,7 @@ int UnitTestOptions::GTestShouldProcessSEH(DWORD exception_code) {
// results. Intercepts only failures from the current thread. // results. Intercepts only failures from the current thread.
ScopedFakeTestPartResultReporter::ScopedFakeTestPartResultReporter( ScopedFakeTestPartResultReporter::ScopedFakeTestPartResultReporter(
TestPartResultArray* result) TestPartResultArray* result)
: intercept_mode_(INTERCEPT_ONLY_CURRENT_THREAD), : intercept_mode_(INTERCEPT_ONLY_CURRENT_THREAD), result_(result) {
result_(result) {
Init(); Init();
} }
...@@ -887,8 +876,7 @@ ScopedFakeTestPartResultReporter::ScopedFakeTestPartResultReporter( ...@@ -887,8 +876,7 @@ ScopedFakeTestPartResultReporter::ScopedFakeTestPartResultReporter(
// results. // results.
ScopedFakeTestPartResultReporter::ScopedFakeTestPartResultReporter( ScopedFakeTestPartResultReporter::ScopedFakeTestPartResultReporter(
InterceptMode intercept_mode, TestPartResultArray* result) InterceptMode intercept_mode, TestPartResultArray* result)
: intercept_mode_(intercept_mode), : intercept_mode_(intercept_mode), result_(result) {
result_(result) {
Init(); Init();
} }
...@@ -932,9 +920,7 @@ namespace internal { ...@@ -932,9 +920,7 @@ namespace internal {
// from user test code. GetTestTypeId() is guaranteed to always // from user test code. GetTestTypeId() is guaranteed to always
// return the same value, as it always calls GetTypeId<>() from the // return the same value, as it always calls GetTypeId<>() from the
// gtest.cc, which is within the Google Test framework. // gtest.cc, which is within the Google Test framework.
TypeId GetTestTypeId() { TypeId GetTestTypeId() { return GetTypeId<Test>(); }
return GetTypeId<Test>();
}
// The value of GetTestTypeId() as seen from within the Google Test // The value of GetTestTypeId() as seen from within the Google Test
// library. This is solely for testing GetTestTypeId(). // library. This is solely for testing GetTestTypeId().
...@@ -949,9 +935,9 @@ static AssertionResult HasOneFailure(const char* /* results_expr */, ...@@ -949,9 +935,9 @@ static AssertionResult HasOneFailure(const char* /* results_expr */,
const TestPartResultArray& results, const TestPartResultArray& results,
TestPartResult::Type type, TestPartResult::Type type,
const std::string& substr) { const std::string& substr) {
const std::string expected(type == TestPartResult::kFatalFailure ? const std::string expected(type == TestPartResult::kFatalFailure
"1 fatal failure" : ? "1 fatal failure"
"1 non-fatal failure"); : "1 non-fatal failure");
Message msg; Message msg;
if (results.size() != 1) { if (results.size() != 1) {
msg << "Expected: " << expected << "\n" msg << "Expected: " << expected << "\n"
...@@ -970,10 +956,10 @@ static AssertionResult HasOneFailure(const char* /* results_expr */, ...@@ -970,10 +956,10 @@ static AssertionResult HasOneFailure(const char* /* results_expr */,
} }
if (strstr(r.message(), substr.c_str()) == nullptr) { if (strstr(r.message(), substr.c_str()) == nullptr) {
return AssertionFailure() << "Expected: " << expected << " containing \"" return AssertionFailure()
<< substr << "\"\n" << "Expected: " << expected << " containing \"" << substr << "\"\n"
<< " Actual:\n" << " Actual:\n"
<< r; << r;
} }
return AssertionSuccess(); return AssertionSuccess();
...@@ -996,7 +982,8 @@ SingleFailureChecker::~SingleFailureChecker() { ...@@ -996,7 +982,8 @@ SingleFailureChecker::~SingleFailureChecker() {
} }
DefaultGlobalTestPartResultReporter::DefaultGlobalTestPartResultReporter( DefaultGlobalTestPartResultReporter::DefaultGlobalTestPartResultReporter(
UnitTestImpl* unit_test) : unit_test_(unit_test) {} UnitTestImpl* unit_test)
: unit_test_(unit_test) {}
void DefaultGlobalTestPartResultReporter::ReportTestPartResult( void DefaultGlobalTestPartResultReporter::ReportTestPartResult(
const TestPartResult& result) { const TestPartResult& result) {
...@@ -1005,7 +992,8 @@ void DefaultGlobalTestPartResultReporter::ReportTestPartResult( ...@@ -1005,7 +992,8 @@ void DefaultGlobalTestPartResultReporter::ReportTestPartResult(
} }
DefaultPerThreadTestPartResultReporter::DefaultPerThreadTestPartResultReporter( DefaultPerThreadTestPartResultReporter::DefaultPerThreadTestPartResultReporter(
UnitTestImpl* unit_test) : unit_test_(unit_test) {} UnitTestImpl* unit_test)
: unit_test_(unit_test) {}
void DefaultPerThreadTestPartResultReporter::ReportTestPartResult( void DefaultPerThreadTestPartResultReporter::ReportTestPartResult(
const TestPartResult& result) { const TestPartResult& result) {
...@@ -1159,8 +1147,7 @@ LPCWSTR String::AnsiToUtf16(const char* ansi) { ...@@ -1159,8 +1147,7 @@ LPCWSTR String::AnsiToUtf16(const char* ansi) {
const int unicode_length = const int unicode_length =
MultiByteToWideChar(CP_ACP, 0, ansi, length, nullptr, 0); MultiByteToWideChar(CP_ACP, 0, ansi, length, nullptr, 0);
WCHAR* unicode = new WCHAR[unicode_length + 1]; WCHAR* unicode = new WCHAR[unicode_length + 1];
MultiByteToWideChar(CP_ACP, 0, ansi, length, MultiByteToWideChar(CP_ACP, 0, ansi, length, unicode, unicode_length);
unicode, unicode_length);
unicode[unicode_length] = 0; unicode[unicode_length] = 0;
return unicode; return unicode;
} }
...@@ -1169,7 +1156,7 @@ LPCWSTR String::AnsiToUtf16(const char* ansi) { ...@@ -1169,7 +1156,7 @@ LPCWSTR String::AnsiToUtf16(const char* ansi) {
// memory using new. The caller is responsible for deleting the return // memory using new. The caller is responsible for deleting the return
// value using delete[]. Returns the ANSI string, or NULL if the // value using delete[]. Returns the ANSI string, or NULL if the
// input is NULL. // input is NULL.
const char* String::Utf16ToAnsi(LPCWSTR utf16_str) { const char* String::Utf16ToAnsi(LPCWSTR utf16_str) {
if (!utf16_str) return nullptr; if (!utf16_str) return nullptr;
const int ansi_length = WideCharToMultiByte(CP_ACP, 0, utf16_str, -1, nullptr, const int ansi_length = WideCharToMultiByte(CP_ACP, 0, utf16_str, -1, nullptr,
0, nullptr, nullptr); 0, nullptr, nullptr);
...@@ -1188,7 +1175,7 @@ const char* String::Utf16ToAnsi(LPCWSTR utf16_str) { ...@@ -1188,7 +1175,7 @@ const char* String::Utf16ToAnsi(LPCWSTR utf16_str) {
// Unlike strcmp(), this function can handle NULL argument(s). A NULL // Unlike strcmp(), this function can handle NULL argument(s). A NULL
// C string is considered different to any non-NULL C string, // C string is considered different to any non-NULL C string,
// including the empty string. // including the empty string.
bool String::CStringEquals(const char * lhs, const char * rhs) { bool String::CStringEquals(const char* lhs, const char* rhs) {
if (lhs == nullptr) return rhs == nullptr; if (lhs == nullptr) return rhs == nullptr;
if (rhs == nullptr) return false; if (rhs == nullptr) return false;
...@@ -1202,11 +1189,10 @@ bool String::CStringEquals(const char * lhs, const char * rhs) { ...@@ -1202,11 +1189,10 @@ bool String::CStringEquals(const char * lhs, const char * rhs) {
// encoding, and streams the result to the given Message object. // encoding, and streams the result to the given Message object.
static void StreamWideCharsToMessage(const wchar_t* wstr, size_t length, static void StreamWideCharsToMessage(const wchar_t* wstr, size_t length,
Message* msg) { Message* msg) {
for (size_t i = 0; i != length; ) { // NOLINT for (size_t i = 0; i != length;) { // NOLINT
if (wstr[i] != L'\0') { if (wstr[i] != L'\0') {
*msg << WideStringToUtf8(wstr + i, static_cast<int>(length - i)); *msg << WideStringToUtf8(wstr + i, static_cast<int>(length - i));
while (i != length && wstr[i] != L'\0') while (i != length && wstr[i] != L'\0') i++;
i++;
} else { } else {
*msg << '\0'; *msg << '\0';
i++; i++;
...@@ -1248,17 +1234,17 @@ Message::Message() : ss_(new ::std::stringstream) { ...@@ -1248,17 +1234,17 @@ Message::Message() : ss_(new ::std::stringstream) {
// These two overloads allow streaming a wide C string to a Message // These two overloads allow streaming a wide C string to a Message
// using the UTF-8 encoding. // using the UTF-8 encoding.
Message& Message::operator <<(const wchar_t* wide_c_str) { Message& Message::operator<<(const wchar_t* wide_c_str) {
return *this << internal::String::ShowWideCString(wide_c_str); return *this << internal::String::ShowWideCString(wide_c_str);
} }
Message& Message::operator <<(wchar_t* wide_c_str) { Message& Message::operator<<(wchar_t* wide_c_str) {
return *this << internal::String::ShowWideCString(wide_c_str); return *this << internal::String::ShowWideCString(wide_c_str);
} }
#if GTEST_HAS_STD_WSTRING #if GTEST_HAS_STD_WSTRING
// Converts the given wide string to a narrow string using the UTF-8 // Converts the given wide string to a narrow string using the UTF-8
// encoding, and streams the result to this Message object. // encoding, and streams the result to this Message object.
Message& Message::operator <<(const ::std::wstring& wstr) { Message& Message::operator<<(const ::std::wstring& wstr) {
internal::StreamWideCharsToMessage(wstr.c_str(), wstr.length(), this); internal::StreamWideCharsToMessage(wstr.c_str(), wstr.length(), this);
return *this; return *this;
} }
...@@ -1561,8 +1547,7 @@ std::vector<std::string> SplitEscapedString(const std::string& str) { ...@@ -1561,8 +1547,7 @@ std::vector<std::string> SplitEscapedString(const std::string& str) {
AssertionResult EqFailure(const char* lhs_expression, AssertionResult EqFailure(const char* lhs_expression,
const char* rhs_expression, const char* rhs_expression,
const std::string& lhs_value, const std::string& lhs_value,
const std::string& rhs_value, const std::string& rhs_value, bool ignoring_case) {
bool ignoring_case) {
Message msg; Message msg;
msg << "Expected equality of these values:"; msg << "Expected equality of these values:";
msg << "\n " << lhs_expression; msg << "\n " << lhs_expression;
...@@ -1579,10 +1564,8 @@ AssertionResult EqFailure(const char* lhs_expression, ...@@ -1579,10 +1564,8 @@ AssertionResult EqFailure(const char* lhs_expression,
} }
if (!lhs_value.empty() && !rhs_value.empty()) { if (!lhs_value.empty() && !rhs_value.empty()) {
const std::vector<std::string> lhs_lines = const std::vector<std::string> lhs_lines = SplitEscapedString(lhs_value);
SplitEscapedString(lhs_value); const std::vector<std::string> rhs_lines = SplitEscapedString(rhs_value);
const std::vector<std::string> rhs_lines =
SplitEscapedString(rhs_value);
if (lhs_lines.size() > 1 || rhs_lines.size() > 1) { if (lhs_lines.size() > 1 || rhs_lines.size() > 1) {
msg << "\nWith diff:\n" msg << "\nWith diff:\n"
<< edit_distance::CreateUnifiedDiff(lhs_lines, rhs_lines); << edit_distance::CreateUnifiedDiff(lhs_lines, rhs_lines);
...@@ -1594,27 +1577,21 @@ AssertionResult EqFailure(const char* lhs_expression, ...@@ -1594,27 +1577,21 @@ AssertionResult EqFailure(const char* lhs_expression,
// Constructs a failure message for Boolean assertions such as EXPECT_TRUE. // Constructs a failure message for Boolean assertions such as EXPECT_TRUE.
std::string GetBoolAssertionFailureMessage( std::string GetBoolAssertionFailureMessage(
const AssertionResult& assertion_result, const AssertionResult& assertion_result, const char* expression_text,
const char* expression_text, const char* actual_predicate_value, const char* expected_predicate_value) {
const char* actual_predicate_value,
const char* expected_predicate_value) {
const char* actual_message = assertion_result.message(); const char* actual_message = assertion_result.message();
Message msg; Message msg;
msg << "Value of: " << expression_text msg << "Value of: " << expression_text
<< "\n Actual: " << actual_predicate_value; << "\n Actual: " << actual_predicate_value;
if (actual_message[0] != '\0') if (actual_message[0] != '\0') msg << " (" << actual_message << ")";
msg << " (" << actual_message << ")";
msg << "\nExpected: " << expected_predicate_value; msg << "\nExpected: " << expected_predicate_value;
return msg.GetString(); return msg.GetString();
} }
// Helper function for implementing ASSERT_NEAR. // Helper function for implementing ASSERT_NEAR.
AssertionResult DoubleNearPredFormat(const char* expr1, AssertionResult DoubleNearPredFormat(const char* expr1, const char* expr2,
const char* expr2, const char* abs_error_expr, double val1,
const char* abs_error_expr, double val2, double abs_error) {
double val1,
double val2,
double abs_error) {
const double diff = fabs(val1 - val2); const double diff = fabs(val1 - val2);
if (diff <= abs_error) return AssertionSuccess(); if (diff <= abs_error) return AssertionSuccess();
...@@ -1644,20 +1621,17 @@ AssertionResult DoubleNearPredFormat(const char* expr1, ...@@ -1644,20 +1621,17 @@ AssertionResult DoubleNearPredFormat(const char* expr1,
"EXPECT_EQUAL. Consider using EXPECT_DOUBLE_EQ instead."; "EXPECT_EQUAL. Consider using EXPECT_DOUBLE_EQ instead.";
} }
return AssertionFailure() return AssertionFailure()
<< "The difference between " << expr1 << " and " << expr2 << "The difference between " << expr1 << " and " << expr2 << " is "
<< " is " << diff << ", which exceeds " << abs_error_expr << ", where\n" << diff << ", which exceeds " << abs_error_expr << ", where\n"
<< expr1 << " evaluates to " << val1 << ",\n" << expr1 << " evaluates to " << val1 << ",\n"
<< expr2 << " evaluates to " << val2 << ", and\n" << expr2 << " evaluates to " << val2 << ", and\n"
<< abs_error_expr << " evaluates to " << abs_error << "."; << abs_error_expr << " evaluates to " << abs_error << ".";
} }
// Helper template for implementing FloatLE() and DoubleLE(). // Helper template for implementing FloatLE() and DoubleLE().
template <typename RawType> template <typename RawType>
AssertionResult FloatingPointLE(const char* expr1, AssertionResult FloatingPointLE(const char* expr1, const char* expr2,
const char* expr2, RawType val1, RawType val2) {
RawType val1,
RawType val2) {
// Returns success if val1 is less than val2, // Returns success if val1 is less than val2,
if (val1 < val2) { if (val1 < val2) {
return AssertionSuccess(); return AssertionSuccess();
...@@ -1682,24 +1656,24 @@ AssertionResult FloatingPointLE(const char* expr1, ...@@ -1682,24 +1656,24 @@ AssertionResult FloatingPointLE(const char* expr1,
<< val2; << val2;
return AssertionFailure() return AssertionFailure()
<< "Expected: (" << expr1 << ") <= (" << expr2 << ")\n" << "Expected: (" << expr1 << ") <= (" << expr2 << ")\n"
<< " Actual: " << StringStreamToString(&val1_ss) << " vs " << " Actual: " << StringStreamToString(&val1_ss) << " vs "
<< StringStreamToString(&val2_ss); << StringStreamToString(&val2_ss);
} }
} // namespace internal } // namespace internal
// Asserts that val1 is less than, or almost equal to, val2. Fails // Asserts that val1 is less than, or almost equal to, val2. Fails
// otherwise. In particular, it fails if either val1 or val2 is NaN. // otherwise. In particular, it fails if either val1 or val2 is NaN.
AssertionResult FloatLE(const char* expr1, const char* expr2, AssertionResult FloatLE(const char* expr1, const char* expr2, float val1,
float val1, float val2) { float val2) {
return internal::FloatingPointLE<float>(expr1, expr2, val1, val2); return internal::FloatingPointLE<float>(expr1, expr2, val1, val2);
} }
// Asserts that val1 is less than, or almost equal to, val2. Fails // Asserts that val1 is less than, or almost equal to, val2. Fails
// otherwise. In particular, it fails if either val1 or val2 is NaN. // otherwise. In particular, it fails if either val1 or val2 is NaN.
AssertionResult DoubleLE(const char* expr1, const char* expr2, AssertionResult DoubleLE(const char* expr1, const char* expr2, double val1,
double val1, double val2) { double val2) {
return internal::FloatingPointLE<double>(expr1, expr2, val1, val2); return internal::FloatingPointLE<double>(expr1, expr2, val1, val2);
} }
...@@ -1707,62 +1681,51 @@ namespace internal { ...@@ -1707,62 +1681,51 @@ namespace internal {
// The helper function for {ASSERT|EXPECT}_STREQ. // The helper function for {ASSERT|EXPECT}_STREQ.
AssertionResult CmpHelperSTREQ(const char* lhs_expression, AssertionResult CmpHelperSTREQ(const char* lhs_expression,
const char* rhs_expression, const char* rhs_expression, const char* lhs,
const char* lhs,
const char* rhs) { const char* rhs) {
if (String::CStringEquals(lhs, rhs)) { if (String::CStringEquals(lhs, rhs)) {
return AssertionSuccess(); return AssertionSuccess();
} }
return EqFailure(lhs_expression, return EqFailure(lhs_expression, rhs_expression, PrintToString(lhs),
rhs_expression, PrintToString(rhs), false);
PrintToString(lhs),
PrintToString(rhs),
false);
} }
// The helper function for {ASSERT|EXPECT}_STRCASEEQ. // The helper function for {ASSERT|EXPECT}_STRCASEEQ.
AssertionResult CmpHelperSTRCASEEQ(const char* lhs_expression, AssertionResult CmpHelperSTRCASEEQ(const char* lhs_expression,
const char* rhs_expression, const char* rhs_expression, const char* lhs,
const char* lhs,
const char* rhs) { const char* rhs) {
if (String::CaseInsensitiveCStringEquals(lhs, rhs)) { if (String::CaseInsensitiveCStringEquals(lhs, rhs)) {
return AssertionSuccess(); return AssertionSuccess();
} }
return EqFailure(lhs_expression, return EqFailure(lhs_expression, rhs_expression, PrintToString(lhs),
rhs_expression, PrintToString(rhs), true);
PrintToString(lhs),
PrintToString(rhs),
true);
} }
// The helper function for {ASSERT|EXPECT}_STRNE. // The helper function for {ASSERT|EXPECT}_STRNE.
AssertionResult CmpHelperSTRNE(const char* s1_expression, AssertionResult CmpHelperSTRNE(const char* s1_expression,
const char* s2_expression, const char* s2_expression, const char* s1,
const char* s1,
const char* s2) { const char* s2) {
if (!String::CStringEquals(s1, s2)) { if (!String::CStringEquals(s1, s2)) {
return AssertionSuccess(); return AssertionSuccess();
} else { } else {
return AssertionFailure() << "Expected: (" << s1_expression << ") != (" return AssertionFailure()
<< s2_expression << "), actual: \"" << "Expected: (" << s1_expression << ") != (" << s2_expression
<< s1 << "\" vs \"" << s2 << "\""; << "), actual: \"" << s1 << "\" vs \"" << s2 << "\"";
} }
} }
// The helper function for {ASSERT|EXPECT}_STRCASENE. // The helper function for {ASSERT|EXPECT}_STRCASENE.
AssertionResult CmpHelperSTRCASENE(const char* s1_expression, AssertionResult CmpHelperSTRCASENE(const char* s1_expression,
const char* s2_expression, const char* s2_expression, const char* s1,
const char* s1,
const char* s2) { const char* s2) {
if (!String::CaseInsensitiveCStringEquals(s1, s2)) { if (!String::CaseInsensitiveCStringEquals(s1, s2)) {
return AssertionSuccess(); return AssertionSuccess();
} else { } else {
return AssertionFailure() return AssertionFailure()
<< "Expected: (" << s1_expression << ") != (" << "Expected: (" << s1_expression << ") != (" << s2_expression
<< s2_expression << ") (ignoring case), actual: \"" << ") (ignoring case), actual: \"" << s1 << "\" vs \"" << s2 << "\"";
<< s1 << "\" vs \"" << s2 << "\"";
} }
} }
...@@ -1790,8 +1753,7 @@ bool IsSubstringPred(const wchar_t* needle, const wchar_t* haystack) { ...@@ -1790,8 +1753,7 @@ bool IsSubstringPred(const wchar_t* needle, const wchar_t* haystack) {
// StringType here can be either ::std::string or ::std::wstring. // StringType here can be either ::std::string or ::std::wstring.
template <typename StringType> template <typename StringType>
bool IsSubstringPred(const StringType& needle, bool IsSubstringPred(const StringType& needle, const StringType& haystack) {
const StringType& haystack) {
return haystack.find(needle) != StringType::npos; return haystack.find(needle) != StringType::npos;
} }
...@@ -1800,21 +1762,22 @@ bool IsSubstringPred(const StringType& needle, ...@@ -1800,21 +1762,22 @@ bool IsSubstringPred(const StringType& needle,
// StringType here can be const char*, const wchar_t*, ::std::string, // StringType here can be const char*, const wchar_t*, ::std::string,
// or ::std::wstring. // or ::std::wstring.
template <typename StringType> template <typename StringType>
AssertionResult IsSubstringImpl( AssertionResult IsSubstringImpl(bool expected_to_be_substring,
bool expected_to_be_substring, const char* needle_expr,
const char* needle_expr, const char* haystack_expr, const char* haystack_expr,
const StringType& needle, const StringType& haystack) { const StringType& needle,
const StringType& haystack) {
if (IsSubstringPred(needle, haystack) == expected_to_be_substring) if (IsSubstringPred(needle, haystack) == expected_to_be_substring)
return AssertionSuccess(); return AssertionSuccess();
const bool is_wide_string = sizeof(needle[0]) > 1; const bool is_wide_string = sizeof(needle[0]) > 1;
const char* const begin_string_quote = is_wide_string ? "L\"" : "\""; const char* const begin_string_quote = is_wide_string ? "L\"" : "\"";
return AssertionFailure() return AssertionFailure()
<< "Value of: " << needle_expr << "\n" << "Value of: " << needle_expr << "\n"
<< " Actual: " << begin_string_quote << needle << "\"\n" << " Actual: " << begin_string_quote << needle << "\"\n"
<< "Expected: " << (expected_to_be_substring ? "" : "not ") << "Expected: " << (expected_to_be_substring ? "" : "not ")
<< "a substring of " << haystack_expr << "\n" << "a substring of " << haystack_expr << "\n"
<< "Which is: " << begin_string_quote << haystack << "\""; << "Which is: " << begin_string_quote << haystack << "\"";
} }
} // namespace } // namespace
...@@ -1823,52 +1786,52 @@ AssertionResult IsSubstringImpl( ...@@ -1823,52 +1786,52 @@ AssertionResult IsSubstringImpl(
// substring of haystack (NULL is considered a substring of itself // substring of haystack (NULL is considered a substring of itself
// only), and return an appropriate error message when they fail. // only), and return an appropriate error message when they fail.
AssertionResult IsSubstring( AssertionResult IsSubstring(const char* needle_expr, const char* haystack_expr,
const char* needle_expr, const char* haystack_expr, const char* needle, const char* haystack) {
const char* needle, const char* haystack) {
return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack); return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack);
} }
AssertionResult IsSubstring( AssertionResult IsSubstring(const char* needle_expr, const char* haystack_expr,
const char* needle_expr, const char* haystack_expr, const wchar_t* needle, const wchar_t* haystack) {
const wchar_t* needle, const wchar_t* haystack) {
return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack); return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack);
} }
AssertionResult IsNotSubstring( AssertionResult IsNotSubstring(const char* needle_expr,
const char* needle_expr, const char* haystack_expr, const char* haystack_expr, const char* needle,
const char* needle, const char* haystack) { const char* haystack) {
return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack); return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack);
} }
AssertionResult IsNotSubstring( AssertionResult IsNotSubstring(const char* needle_expr,
const char* needle_expr, const char* haystack_expr, const char* haystack_expr, const wchar_t* needle,
const wchar_t* needle, const wchar_t* haystack) { const wchar_t* haystack) {
return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack); return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack);
} }
AssertionResult IsSubstring( AssertionResult IsSubstring(const char* needle_expr, const char* haystack_expr,
const char* needle_expr, const char* haystack_expr, const ::std::string& needle,
const ::std::string& needle, const ::std::string& haystack) { const ::std::string& haystack) {
return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack); return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack);
} }
AssertionResult IsNotSubstring( AssertionResult IsNotSubstring(const char* needle_expr,
const char* needle_expr, const char* haystack_expr, const char* haystack_expr,
const ::std::string& needle, const ::std::string& haystack) { const ::std::string& needle,
const ::std::string& haystack) {
return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack); return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack);
} }
#if GTEST_HAS_STD_WSTRING #if GTEST_HAS_STD_WSTRING
AssertionResult IsSubstring( AssertionResult IsSubstring(const char* needle_expr, const char* haystack_expr,
const char* needle_expr, const char* haystack_expr, const ::std::wstring& needle,
const ::std::wstring& needle, const ::std::wstring& haystack) { const ::std::wstring& haystack) {
return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack); return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack);
} }
AssertionResult IsNotSubstring( AssertionResult IsNotSubstring(const char* needle_expr,
const char* needle_expr, const char* haystack_expr, const char* haystack_expr,
const ::std::wstring& needle, const ::std::wstring& haystack) { const ::std::wstring& needle,
const ::std::wstring& haystack) {
return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack); return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack);
} }
#endif // GTEST_HAS_STD_WSTRING #endif // GTEST_HAS_STD_WSTRING
...@@ -1880,43 +1843,42 @@ namespace internal { ...@@ -1880,43 +1843,42 @@ namespace internal {
namespace { namespace {
// Helper function for IsHRESULT{SuccessFailure} predicates // Helper function for IsHRESULT{SuccessFailure} predicates
AssertionResult HRESULTFailureHelper(const char* expr, AssertionResult HRESULTFailureHelper(const char* expr, const char* expected,
const char* expected,
long hr) { // NOLINT long hr) { // NOLINT
# if GTEST_OS_WINDOWS_MOBILE || GTEST_OS_WINDOWS_TV_TITLE #if GTEST_OS_WINDOWS_MOBILE || GTEST_OS_WINDOWS_TV_TITLE
// Windows CE doesn't support FormatMessage. // Windows CE doesn't support FormatMessage.
const char error_text[] = ""; const char error_text[] = "";
# else #else
// Looks up the human-readable system message for the HRESULT code // Looks up the human-readable system message for the HRESULT code
// and since we're not passing any params to FormatMessage, we don't // and since we're not passing any params to FormatMessage, we don't
// want inserts expanded. // want inserts expanded.
const DWORD kFlags = FORMAT_MESSAGE_FROM_SYSTEM | const DWORD kFlags =
FORMAT_MESSAGE_IGNORE_INSERTS; FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS;
const DWORD kBufSize = 4096; const DWORD kBufSize = 4096;
// Gets the system's human readable message string for this HRESULT. // Gets the system's human readable message string for this HRESULT.
char error_text[kBufSize] = { '\0' }; char error_text[kBufSize] = {'\0'};
DWORD message_length = ::FormatMessageA(kFlags, DWORD message_length = ::FormatMessageA(kFlags,
0, // no source, we're asking system 0, // no source, we're asking system
static_cast<DWORD>(hr), // the error static_cast<DWORD>(hr), // the error
0, // no line width restrictions 0, // no line width restrictions
error_text, // output buffer error_text, // output buffer
kBufSize, // buf size kBufSize, // buf size
nullptr); // no arguments for inserts nullptr); // no arguments for inserts
// Trims tailing white space (FormatMessage leaves a trailing CR-LF) // Trims tailing white space (FormatMessage leaves a trailing CR-LF)
for (; message_length && IsSpace(error_text[message_length - 1]); for (; message_length && IsSpace(error_text[message_length - 1]);
--message_length) { --message_length) {
error_text[message_length - 1] = '\0'; error_text[message_length - 1] = '\0';
} }
# endif // GTEST_OS_WINDOWS_MOBILE #endif // GTEST_OS_WINDOWS_MOBILE
const std::string error_hex("0x" + String::FormatHexInt(hr)); const std::string error_hex("0x" + String::FormatHexInt(hr));
return ::testing::AssertionFailure() return ::testing::AssertionFailure()
<< "Expected: " << expr << " " << expected << ".\n" << "Expected: " << expr << " " << expected << ".\n"
<< " Actual: " << error_hex << " " << error_text << "\n"; << " Actual: " << error_hex << " " << error_text << "\n";
} }
} // namespace } // namespace
...@@ -1950,16 +1912,18 @@ AssertionResult IsHRESULTFailure(const char* expr, long hr) { // NOLINT ...@@ -1950,16 +1912,18 @@ AssertionResult IsHRESULTFailure(const char* expr, long hr) { // NOLINT
// 17 - 21 bits 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx // 17 - 21 bits 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
// The maximum code-point a one-byte UTF-8 sequence can represent. // The maximum code-point a one-byte UTF-8 sequence can represent.
constexpr uint32_t kMaxCodePoint1 = (static_cast<uint32_t>(1) << 7) - 1; constexpr uint32_t kMaxCodePoint1 = (static_cast<uint32_t>(1) << 7) - 1;
// The maximum code-point a two-byte UTF-8 sequence can represent. // The maximum code-point a two-byte UTF-8 sequence can represent.
constexpr uint32_t kMaxCodePoint2 = (static_cast<uint32_t>(1) << (5 + 6)) - 1; constexpr uint32_t kMaxCodePoint2 = (static_cast<uint32_t>(1) << (5 + 6)) - 1;
// The maximum code-point a three-byte UTF-8 sequence can represent. // The maximum code-point a three-byte UTF-8 sequence can represent.
constexpr uint32_t kMaxCodePoint3 = (static_cast<uint32_t>(1) << (4 + 2*6)) - 1; constexpr uint32_t kMaxCodePoint3 =
(static_cast<uint32_t>(1) << (4 + 2 * 6)) - 1;
// The maximum code-point a four-byte UTF-8 sequence can represent. // The maximum code-point a four-byte UTF-8 sequence can represent.
constexpr uint32_t kMaxCodePoint4 = (static_cast<uint32_t>(1) << (3 + 3*6)) - 1; constexpr uint32_t kMaxCodePoint4 =
(static_cast<uint32_t>(1) << (3 + 3 * 6)) - 1;
// Chops off the n lowest bits from a bit pattern. Returns the n // Chops off the n lowest bits from a bit pattern. Returns the n
// lowest bits. As a side effect, the original bit pattern will be // lowest bits. As a side effect, the original bit pattern will be
...@@ -1984,7 +1948,7 @@ std::string CodePointToUtf8(uint32_t code_point) { ...@@ -1984,7 +1948,7 @@ std::string CodePointToUtf8(uint32_t code_point) {
char str[5]; // Big enough for the largest valid code point. char str[5]; // Big enough for the largest valid code point.
if (code_point <= kMaxCodePoint1) { if (code_point <= kMaxCodePoint1) {
str[1] = '\0'; str[1] = '\0';
str[0] = static_cast<char>(code_point); // 0xxxxxxx str[0] = static_cast<char>(code_point); // 0xxxxxxx
} else if (code_point <= kMaxCodePoint2) { } else if (code_point <= kMaxCodePoint2) {
str[2] = '\0'; str[2] = '\0';
str[1] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx str[1] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx
...@@ -2012,8 +1976,8 @@ std::string CodePointToUtf8(uint32_t code_point) { ...@@ -2012,8 +1976,8 @@ std::string CodePointToUtf8(uint32_t code_point) {
// and thus should be combined into a single Unicode code point // and thus should be combined into a single Unicode code point
// using CreateCodePointFromUtf16SurrogatePair. // using CreateCodePointFromUtf16SurrogatePair.
inline bool IsUtf16SurrogatePair(wchar_t first, wchar_t second) { inline bool IsUtf16SurrogatePair(wchar_t first, wchar_t second) {
return sizeof(wchar_t) == 2 && return sizeof(wchar_t) == 2 && (first & 0xFC00) == 0xD800 &&
(first & 0xFC00) == 0xD800 && (second & 0xFC00) == 0xDC00; (second & 0xFC00) == 0xDC00;
} }
// Creates a Unicode code point from UTF16 surrogate pair. // Creates a Unicode code point from UTF16 surrogate pair.
...@@ -2044,8 +2008,7 @@ inline uint32_t CreateCodePointFromUtf16SurrogatePair(wchar_t first, ...@@ -2044,8 +2008,7 @@ inline uint32_t CreateCodePointFromUtf16SurrogatePair(wchar_t first,
// and contains invalid UTF-16 surrogate pairs, values in those pairs // and contains invalid UTF-16 surrogate pairs, values in those pairs
// will be encoded as individual Unicode characters from Basic Normal Plane. // will be encoded as individual Unicode characters from Basic Normal Plane.
std::string WideStringToUtf8(const wchar_t* str, int num_chars) { std::string WideStringToUtf8(const wchar_t* str, int num_chars) {
if (num_chars == -1) if (num_chars == -1) num_chars = static_cast<int>(wcslen(str));
num_chars = static_cast<int>(wcslen(str));
::std::stringstream stream; ::std::stringstream stream;
for (int i = 0; i < num_chars; ++i) { for (int i = 0; i < num_chars; ++i) {
...@@ -2054,8 +2017,8 @@ std::string WideStringToUtf8(const wchar_t* str, int num_chars) { ...@@ -2054,8 +2017,8 @@ std::string WideStringToUtf8(const wchar_t* str, int num_chars) {
if (str[i] == L'\0') { if (str[i] == L'\0') {
break; break;
} else if (i + 1 < num_chars && IsUtf16SurrogatePair(str[i], str[i + 1])) { } else if (i + 1 < num_chars && IsUtf16SurrogatePair(str[i], str[i + 1])) {
unicode_code_point = CreateCodePointFromUtf16SurrogatePair(str[i], unicode_code_point =
str[i + 1]); CreateCodePointFromUtf16SurrogatePair(str[i], str[i + 1]);
i++; i++;
} else { } else {
unicode_code_point = static_cast<uint32_t>(str[i]); unicode_code_point = static_cast<uint32_t>(str[i]);
...@@ -2068,7 +2031,7 @@ std::string WideStringToUtf8(const wchar_t* str, int num_chars) { ...@@ -2068,7 +2031,7 @@ std::string WideStringToUtf8(const wchar_t* str, int num_chars) {
// Converts a wide C string to an std::string using the UTF-8 encoding. // Converts a wide C string to an std::string using the UTF-8 encoding.
// NULL will be converted to "(null)". // NULL will be converted to "(null)".
std::string String::ShowWideCString(const wchar_t * wide_c_str) { std::string String::ShowWideCString(const wchar_t* wide_c_str) {
if (wide_c_str == nullptr) return "(null)"; if (wide_c_str == nullptr) return "(null)";
return internal::WideStringToUtf8(wide_c_str, -1); return internal::WideStringToUtf8(wide_c_str, -1);
...@@ -2080,7 +2043,7 @@ std::string String::ShowWideCString(const wchar_t * wide_c_str) { ...@@ -2080,7 +2043,7 @@ std::string String::ShowWideCString(const wchar_t * wide_c_str) {
// Unlike wcscmp(), this function can handle NULL argument(s). A NULL // Unlike wcscmp(), this function can handle NULL argument(s). A NULL
// C string is considered different to any non-NULL C string, // C string is considered different to any non-NULL C string,
// including the empty string. // including the empty string.
bool String::WideCStringEquals(const wchar_t * lhs, const wchar_t * rhs) { bool String::WideCStringEquals(const wchar_t* lhs, const wchar_t* rhs) {
if (lhs == nullptr) return rhs == nullptr; if (lhs == nullptr) return rhs == nullptr;
if (rhs == nullptr) return false; if (rhs == nullptr) return false;
...@@ -2090,33 +2053,27 @@ bool String::WideCStringEquals(const wchar_t * lhs, const wchar_t * rhs) { ...@@ -2090,33 +2053,27 @@ bool String::WideCStringEquals(const wchar_t * lhs, const wchar_t * rhs) {
// Helper function for *_STREQ on wide strings. // Helper function for *_STREQ on wide strings.
AssertionResult CmpHelperSTREQ(const char* lhs_expression, AssertionResult CmpHelperSTREQ(const char* lhs_expression,
const char* rhs_expression, const char* rhs_expression, const wchar_t* lhs,
const wchar_t* lhs,
const wchar_t* rhs) { const wchar_t* rhs) {
if (String::WideCStringEquals(lhs, rhs)) { if (String::WideCStringEquals(lhs, rhs)) {
return AssertionSuccess(); return AssertionSuccess();
} }
return EqFailure(lhs_expression, return EqFailure(lhs_expression, rhs_expression, PrintToString(lhs),
rhs_expression, PrintToString(rhs), false);
PrintToString(lhs),
PrintToString(rhs),
false);
} }
// Helper function for *_STRNE on wide strings. // Helper function for *_STRNE on wide strings.
AssertionResult CmpHelperSTRNE(const char* s1_expression, AssertionResult CmpHelperSTRNE(const char* s1_expression,
const char* s2_expression, const char* s2_expression, const wchar_t* s1,
const wchar_t* s1,
const wchar_t* s2) { const wchar_t* s2) {
if (!String::WideCStringEquals(s1, s2)) { if (!String::WideCStringEquals(s1, s2)) {
return AssertionSuccess(); return AssertionSuccess();
} }
return AssertionFailure() << "Expected: (" << s1_expression << ") != (" return AssertionFailure()
<< s2_expression << "), actual: " << "Expected: (" << s1_expression << ") != (" << s2_expression
<< PrintToString(s1) << "), actual: " << PrintToString(s1) << " vs " << PrintToString(s2);
<< " vs " << PrintToString(s2);
} }
// Compares two C strings, ignoring case. Returns true if and only if they have // Compares two C strings, ignoring case. Returns true if and only if they have
...@@ -2125,7 +2082,7 @@ AssertionResult CmpHelperSTRNE(const char* s1_expression, ...@@ -2125,7 +2082,7 @@ AssertionResult CmpHelperSTRNE(const char* s1_expression,
// Unlike strcasecmp(), this function can handle NULL argument(s). A // Unlike strcasecmp(), this function can handle NULL argument(s). A
// NULL C string is considered different to any non-NULL C string, // NULL C string is considered different to any non-NULL C string,
// including the empty string. // including the empty string.
bool String::CaseInsensitiveCStringEquals(const char * lhs, const char * rhs) { bool String::CaseInsensitiveCStringEquals(const char* lhs, const char* rhs) {
if (lhs == nullptr) return rhs == nullptr; if (lhs == nullptr) return rhs == nullptr;
if (rhs == nullptr) return false; if (rhs == nullptr) return false;
return posix::StrCaseCmp(lhs, rhs) == 0; return posix::StrCaseCmp(lhs, rhs) == 0;
...@@ -2167,8 +2124,8 @@ bool String::CaseInsensitiveWideCStringEquals(const wchar_t* lhs, ...@@ -2167,8 +2124,8 @@ bool String::CaseInsensitiveWideCStringEquals(const wchar_t* lhs,
// Returns true if and only if str ends with the given suffix, ignoring case. // Returns true if and only if str ends with the given suffix, ignoring case.
// Any string is considered to end with an empty suffix. // Any string is considered to end with an empty suffix.
bool String::EndsWithCaseInsensitive( bool String::EndsWithCaseInsensitive(const std::string& str,
const std::string& str, const std::string& suffix) { const std::string& suffix) {
const size_t str_len = str.length(); const size_t str_len = str.length();
const size_t suffix_len = suffix.length(); const size_t suffix_len = suffix.length();
return (str_len >= suffix_len) && return (str_len >= suffix_len) &&
...@@ -2251,15 +2208,13 @@ TestResult::TestResult() ...@@ -2251,15 +2208,13 @@ TestResult::TestResult()
: death_test_count_(0), start_timestamp_(0), elapsed_time_(0) {} : death_test_count_(0), start_timestamp_(0), elapsed_time_(0) {}
// D'tor. // D'tor.
TestResult::~TestResult() { TestResult::~TestResult() {}
}
// Returns the i-th test part result among all the results. i can // Returns the i-th test part result among all the results. i can
// range from 0 to total_part_count() - 1. If i is not in that range, // range from 0 to total_part_count() - 1. If i is not in that range,
// aborts the program. // aborts the program.
const TestPartResult& TestResult::GetTestPartResult(int i) const { const TestPartResult& TestResult::GetTestPartResult(int i) const {
if (i < 0 || i >= total_part_count()) if (i < 0 || i >= total_part_count()) internal::posix::Abort();
internal::posix::Abort();
return test_part_results_.at(static_cast<size_t>(i)); return test_part_results_.at(static_cast<size_t>(i));
} }
...@@ -2267,15 +2222,12 @@ const TestPartResult& TestResult::GetTestPartResult(int i) const { ...@@ -2267,15 +2222,12 @@ const TestPartResult& TestResult::GetTestPartResult(int i) const {
// test_property_count() - 1. If i is not in that range, aborts the // test_property_count() - 1. If i is not in that range, aborts the
// program. // program.
const TestProperty& TestResult::GetTestProperty(int i) const { const TestProperty& TestResult::GetTestProperty(int i) const {
if (i < 0 || i >= test_property_count()) if (i < 0 || i >= test_property_count()) internal::posix::Abort();
internal::posix::Abort();
return test_properties_.at(static_cast<size_t>(i)); return test_properties_.at(static_cast<size_t>(i));
} }
// Clears the test part results. // Clears the test part results.
void TestResult::ClearTestPartResults() { void TestResult::ClearTestPartResults() { test_part_results_.clear(); }
test_part_results_.clear();
}
// Adds a test part result to the list. // Adds a test part result to the list.
void TestResult::AddTestPartResult(const TestPartResult& test_part_result) { void TestResult::AddTestPartResult(const TestPartResult& test_part_result) {
...@@ -2304,15 +2256,8 @@ void TestResult::RecordProperty(const std::string& xml_element, ...@@ -2304,15 +2256,8 @@ void TestResult::RecordProperty(const std::string& xml_element,
// The list of reserved attributes used in the <testsuites> element of XML // The list of reserved attributes used in the <testsuites> element of XML
// output. // output.
static const char* const kReservedTestSuitesAttributes[] = { static const char* const kReservedTestSuitesAttributes[] = {
"disabled", "disabled", "errors", "failures", "name",
"errors", "random_seed", "tests", "time", "timestamp"};
"failures",
"name",
"random_seed",
"tests",
"time",
"timestamp"
};
// The list of reserved attributes used in the <testsuite> element of XML // The list of reserved attributes used in the <testsuite> element of XML
// output. // output.
...@@ -2322,8 +2267,8 @@ static const char* const kReservedTestSuiteAttributes[] = { ...@@ -2322,8 +2267,8 @@ static const char* const kReservedTestSuiteAttributes[] = {
// The list of reserved attributes used in the <testcase> element of XML output. // The list of reserved attributes used in the <testcase> element of XML output.
static const char* const kReservedTestCaseAttributes[] = { static const char* const kReservedTestCaseAttributes[] = {
"classname", "name", "status", "time", "type_param", "classname", "name", "status", "time",
"value_param", "file", "line"}; "type_param", "value_param", "file", "line"};
// Use a slightly different set for allowed output to ensure existing tests can // Use a slightly different set for allowed output to ensure existing tests can
// still RecordProperty("result") or "RecordProperty(timestamp") // still RecordProperty("result") or "RecordProperty(timestamp")
...@@ -2385,7 +2330,7 @@ static bool ValidateTestPropertyName( ...@@ -2385,7 +2330,7 @@ static bool ValidateTestPropertyName(
const std::string& property_name, const std::string& property_name,
const std::vector<std::string>& reserved_names) { const std::vector<std::string>& reserved_names) {
if (std::find(reserved_names.begin(), reserved_names.end(), property_name) != if (std::find(reserved_names.begin(), reserved_names.end(), property_name) !=
reserved_names.end()) { reserved_names.end()) {
ADD_FAILURE() << "Reserved key used in RecordProperty(): " << property_name ADD_FAILURE() << "Reserved key used in RecordProperty(): " << property_name
<< " (" << FormatWordList(reserved_names) << " (" << FormatWordList(reserved_names)
<< " are reserved by " << GTEST_NAME_ << ")"; << " are reserved by " << GTEST_NAME_ << ")";
...@@ -2423,8 +2368,7 @@ bool TestResult::Skipped() const { ...@@ -2423,8 +2368,7 @@ bool TestResult::Skipped() const {
// Returns true if and only if the test failed. // Returns true if and only if the test failed.
bool TestResult::Failed() const { bool TestResult::Failed() const {
for (int i = 0; i < total_part_count(); ++i) { for (int i = 0; i < total_part_count(); ++i) {
if (GetTestPartResult(i).failed()) if (GetTestPartResult(i).failed()) return true;
return true;
} }
return false; return false;
} }
...@@ -2465,27 +2409,22 @@ int TestResult::test_property_count() const { ...@@ -2465,27 +2409,22 @@ int TestResult::test_property_count() const {
// Creates a Test object. // Creates a Test object.
// The c'tor saves the states of all flags. // The c'tor saves the states of all flags.
Test::Test() Test::Test() : gtest_flag_saver_(new GTEST_FLAG_SAVER_) {}
: gtest_flag_saver_(new GTEST_FLAG_SAVER_) {
}
// The d'tor restores the states of all flags. The actual work is // The d'tor restores the states of all flags. The actual work is
// done by the d'tor of the gtest_flag_saver_ field, and thus not // done by the d'tor of the gtest_flag_saver_ field, and thus not
// visible here. // visible here.
Test::~Test() { Test::~Test() {}
}
// Sets up the test fixture. // Sets up the test fixture.
// //
// A sub-class may override this. // A sub-class may override this.
void Test::SetUp() { void Test::SetUp() {}
}
// Tears down the test fixture. // Tears down the test fixture.
// //
// A sub-class may override this. // A sub-class may override this.
void Test::TearDown() { void Test::TearDown() {}
}
// Allows user supplied key value pairs to be recorded for later output. // Allows user supplied key value pairs to be recorded for later output.
void Test::RecordProperty(const std::string& key, const std::string& value) { void Test::RecordProperty(const std::string& key, const std::string& value) {
...@@ -2590,8 +2529,8 @@ bool Test::HasSameFixtureClass() { ...@@ -2590,8 +2529,8 @@ bool Test::HasSameFixtureClass() {
static std::string* FormatSehExceptionMessage(DWORD exception_code, static std::string* FormatSehExceptionMessage(DWORD exception_code,
const char* location) { const char* location) {
Message message; Message message;
message << "SEH exception with code 0x" << std::setbase(16) << message << "SEH exception with code 0x" << std::setbase(16) << exception_code
exception_code << std::setbase(10) << " thrown in " << location << "."; << std::setbase(10) << " thrown in " << location << ".";
return new std::string(message.GetString()); return new std::string(message.GetString());
} }
...@@ -2634,8 +2573,8 @@ GoogleTestFailureException::GoogleTestFailureException( ...@@ -2634,8 +2573,8 @@ GoogleTestFailureException::GoogleTestFailureException(
// exceptions in the same function. Therefore, we provide a separate // exceptions in the same function. Therefore, we provide a separate
// wrapper function for handling SEH exceptions.) // wrapper function for handling SEH exceptions.)
template <class T, typename Result> template <class T, typename Result>
Result HandleSehExceptionsInMethodIfSupported( Result HandleSehExceptionsInMethodIfSupported(T* object, Result (T::*method)(),
T* object, Result (T::*method)(), const char* location) { const char* location) {
#if GTEST_HAS_SEH #if GTEST_HAS_SEH
__try { __try {
return (object->*method)(); return (object->*method)();
...@@ -2644,8 +2583,8 @@ Result HandleSehExceptionsInMethodIfSupported( ...@@ -2644,8 +2583,8 @@ Result HandleSehExceptionsInMethodIfSupported(
// We create the exception message on the heap because VC++ prohibits // We create the exception message on the heap because VC++ prohibits
// creation of objects with destructors on stack in functions using __try // creation of objects with destructors on stack in functions using __try
// (see error C2712). // (see error C2712).
std::string* exception_message = FormatSehExceptionMessage( std::string* exception_message =
GetExceptionCode(), location); FormatSehExceptionMessage(GetExceptionCode(), location);
internal::ReportFailureInUnknownLocation(TestPartResult::kFatalFailure, internal::ReportFailureInUnknownLocation(TestPartResult::kFatalFailure,
*exception_message); *exception_message);
delete exception_message; delete exception_message;
...@@ -2661,8 +2600,8 @@ Result HandleSehExceptionsInMethodIfSupported( ...@@ -2661,8 +2600,8 @@ Result HandleSehExceptionsInMethodIfSupported(
// exceptions, if they are supported; returns the 0-value for type // exceptions, if they are supported; returns the 0-value for type
// Result in case of an SEH exception. // Result in case of an SEH exception.
template <class T, typename Result> template <class T, typename Result>
Result HandleExceptionsInMethodIfSupported( Result HandleExceptionsInMethodIfSupported(T* object, Result (T::*method)(),
T* object, Result (T::*method)(), const char* location) { const char* location) {
// NOTE: The user code can affect the way in which Google Test handles // NOTE: The user code can affect the way in which Google Test handles
// exceptions by setting GTEST_FLAG(catch_exceptions), but only before // exceptions by setting GTEST_FLAG(catch_exceptions), but only before
// RUN_ALL_TESTS() starts. It is technically possible to check the flag // RUN_ALL_TESTS() starts. It is technically possible to check the flag
...@@ -2728,16 +2667,16 @@ void Test::Run() { ...@@ -2728,16 +2667,16 @@ void Test::Run() {
// GTEST_SKIP(). // GTEST_SKIP().
if (!HasFatalFailure() && !IsSkipped()) { if (!HasFatalFailure() && !IsSkipped()) {
impl->os_stack_trace_getter()->UponLeavingGTest(); impl->os_stack_trace_getter()->UponLeavingGTest();
internal::HandleExceptionsInMethodIfSupported( internal::HandleExceptionsInMethodIfSupported(this, &Test::TestBody,
this, &Test::TestBody, "the test body"); "the test body");
} }
// However, we want to clean up as much as possible. Hence we will // However, we want to clean up as much as possible. Hence we will
// always call TearDown(), even if SetUp() or the test body has // always call TearDown(), even if SetUp() or the test body has
// failed. // failed.
impl->os_stack_trace_getter()->UponLeavingGTest(); impl->os_stack_trace_getter()->UponLeavingGTest();
internal::HandleExceptionsInMethodIfSupported( internal::HandleExceptionsInMethodIfSupported(this, &Test::TearDown,
this, &Test::TearDown, "TearDown()"); "TearDown()");
} }
// Returns true if and only if the current test has a fatal failure. // Returns true if and only if the current test has a fatal failure.
...@@ -2747,8 +2686,9 @@ bool Test::HasFatalFailure() { ...@@ -2747,8 +2686,9 @@ bool Test::HasFatalFailure() {
// Returns true if and only if the current test has a non-fatal failure. // Returns true if and only if the current test has a non-fatal failure.
bool Test::HasNonfatalFailure() { bool Test::HasNonfatalFailure() {
return internal::GetUnitTestImpl()->current_test_result()-> return internal::GetUnitTestImpl()
HasNonfatalFailure(); ->current_test_result()
->HasNonfatalFailure();
} }
// Returns true if and only if the current test was skipped. // Returns true if and only if the current test was skipped.
...@@ -2848,11 +2788,10 @@ class TestNameIs { ...@@ -2848,11 +2788,10 @@ class TestNameIs {
// Constructor. // Constructor.
// //
// TestNameIs has NO default constructor. // TestNameIs has NO default constructor.
explicit TestNameIs(const char* name) explicit TestNameIs(const char* name) : name_(name) {}
: name_(name) {}
// Returns true if and only if the test name of test_info matches name_. // Returns true if and only if the test name of test_info matches name_.
bool operator()(const TestInfo * test_info) const { bool operator()(const TestInfo* test_info) const {
return test_info && test_info->name() == name_; return test_info && test_info->name() == name_;
} }
...@@ -3145,11 +3084,10 @@ void TestSuite::UnshuffleTests() { ...@@ -3145,11 +3084,10 @@ void TestSuite::UnshuffleTests() {
// //
// FormatCountableNoun(1, "formula", "formuli") returns "1 formula". // FormatCountableNoun(1, "formula", "formuli") returns "1 formula".
// FormatCountableNoun(5, "book", "books") returns "5 books". // FormatCountableNoun(5, "book", "books") returns "5 books".
static std::string FormatCountableNoun(int count, static std::string FormatCountableNoun(int count, const char* singular_form,
const char * singular_form, const char* plural_form) {
const char * plural_form) {
return internal::StreamableToString(count) + " " + return internal::StreamableToString(count) + " " +
(count == 1 ? singular_form : plural_form); (count == 1 ? singular_form : plural_form);
} }
// Formats the count of tests. // Formats the count of tests.
...@@ -3166,7 +3104,7 @@ static std::string FormatTestSuiteCount(int test_suite_count) { ...@@ -3166,7 +3104,7 @@ static std::string FormatTestSuiteCount(int test_suite_count) {
// representation. Both kNonFatalFailure and kFatalFailure are translated // representation. Both kNonFatalFailure and kFatalFailure are translated
// to "Failure", as the user usually doesn't care about the difference // to "Failure", as the user usually doesn't care about the difference
// between the two when viewing the test result. // between the two when viewing the test result.
static const char * TestPartResultTypeToString(TestPartResult::Type type) { static const char* TestPartResultTypeToString(TestPartResult::Type type) {
switch (type) { switch (type) {
case TestPartResult::kSkip: case TestPartResult::kSkip:
return "Skipped\n"; return "Skipped\n";
...@@ -3193,17 +3131,18 @@ enum class GTestColor { kDefault, kRed, kGreen, kYellow }; ...@@ -3193,17 +3131,18 @@ enum class GTestColor { kDefault, kRed, kGreen, kYellow };
// Prints a TestPartResult to an std::string. // Prints a TestPartResult to an std::string.
static std::string PrintTestPartResultToString( static std::string PrintTestPartResultToString(
const TestPartResult& test_part_result) { const TestPartResult& test_part_result) {
return (Message() return (Message() << internal::FormatFileLocation(
<< internal::FormatFileLocation(test_part_result.file_name(), test_part_result.file_name(),
test_part_result.line_number()) test_part_result.line_number())
<< " " << TestPartResultTypeToString(test_part_result.type()) << " "
<< test_part_result.message()).GetString(); << TestPartResultTypeToString(test_part_result.type())
<< test_part_result.message())
.GetString();
} }
// Prints a TestPartResult. // Prints a TestPartResult.
static void PrintTestPartResult(const TestPartResult& test_part_result) { static void PrintTestPartResult(const TestPartResult& test_part_result) {
const std::string& result = const std::string& result = PrintTestPartResultToString(test_part_result);
PrintTestPartResultToString(test_part_result);
printf("%s\n", result.c_str()); printf("%s\n", result.c_str());
fflush(stdout); fflush(stdout);
// If the test program runs in Visual Studio or a debugger, the // If the test program runs in Visual Studio or a debugger, the
...@@ -3220,8 +3159,8 @@ static void PrintTestPartResult(const TestPartResult& test_part_result) { ...@@ -3220,8 +3159,8 @@ static void PrintTestPartResult(const TestPartResult& test_part_result) {
} }
// class PrettyUnitTestResultPrinter // class PrettyUnitTestResultPrinter
#if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE && \ #if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE && !GTEST_OS_WINDOWS_PHONE && \
!GTEST_OS_WINDOWS_PHONE && !GTEST_OS_WINDOWS_RT && !GTEST_OS_WINDOWS_MINGW !GTEST_OS_WINDOWS_RT && !GTEST_OS_WINDOWS_MINGW
// 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) {
...@@ -3232,7 +3171,8 @@ static WORD GetColorAttribute(GTestColor color) { ...@@ -3232,7 +3171,8 @@ static WORD GetColorAttribute(GTestColor color) {
return FOREGROUND_GREEN; return FOREGROUND_GREEN;
case GTestColor::kYellow: case GTestColor::kYellow:
return FOREGROUND_RED | FOREGROUND_GREEN; return FOREGROUND_RED | FOREGROUND_GREEN;
default: return 0; default:
return 0;
} }
} }
...@@ -3316,9 +3256,9 @@ bool ShouldUseColor(bool stdout_is_tty) { ...@@ -3316,9 +3256,9 @@ bool ShouldUseColor(bool stdout_is_tty) {
} }
return String::CaseInsensitiveCStringEquals(gtest_color, "yes") || return String::CaseInsensitiveCStringEquals(gtest_color, "yes") ||
String::CaseInsensitiveCStringEquals(gtest_color, "true") || String::CaseInsensitiveCStringEquals(gtest_color, "true") ||
String::CaseInsensitiveCStringEquals(gtest_color, "t") || String::CaseInsensitiveCStringEquals(gtest_color, "t") ||
String::CStringEquals(gtest_color, "1"); String::CStringEquals(gtest_color, "1");
// We take "yes", "true", "t", and "1" as meaning "yes". If the // We take "yes", "true", "t", and "1" as meaning "yes". If the
// value is neither one of these nor "auto", we treat it as "no" to // value is neither one of these nor "auto", we treat it as "no" to
// be conservative. // be conservative.
...@@ -3330,7 +3270,7 @@ bool ShouldUseColor(bool stdout_is_tty) { ...@@ -3330,7 +3270,7 @@ bool ShouldUseColor(bool stdout_is_tty) {
// that would be colored when printed, as can be done on Linux. // that would be colored when printed, as can be done on Linux.
GTEST_ATTRIBUTE_PRINTF_(2, 3) GTEST_ATTRIBUTE_PRINTF_(2, 3)
static void ColoredPrintf(GTestColor color, const char *fmt, ...) { static void ColoredPrintf(GTestColor color, const char* fmt, ...) {
va_list args; va_list args;
va_start(args, fmt); va_start(args, fmt);
...@@ -3349,8 +3289,8 @@ static void ColoredPrintf(GTestColor color, const char *fmt, ...) { ...@@ -3349,8 +3289,8 @@ static void ColoredPrintf(GTestColor color, const char *fmt, ...) {
return; return;
} }
#if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE && \ #if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE && !GTEST_OS_WINDOWS_PHONE && \
!GTEST_OS_WINDOWS_PHONE && !GTEST_OS_WINDOWS_RT && !GTEST_OS_WINDOWS_MINGW !GTEST_OS_WINDOWS_RT && !GTEST_OS_WINDOWS_MINGW
const HANDLE stdout_handle = GetStdHandle(STD_OUTPUT_HANDLE); const HANDLE stdout_handle = GetStdHandle(STD_OUTPUT_HANDLE);
// Gets the current text color. // Gets the current text color.
...@@ -3442,7 +3382,7 @@ class PrettyUnitTestResultPrinter : public TestEventListener { ...@@ -3442,7 +3382,7 @@ class PrettyUnitTestResultPrinter : public TestEventListener {
static void PrintSkippedTests(const UnitTest& unit_test); static void PrintSkippedTests(const UnitTest& unit_test);
}; };
// Fired before each iteration of tests starts. // Fired before each iteration of tests starts.
void PrettyUnitTestResultPrinter::OnTestIterationStart( void PrettyUnitTestResultPrinter::OnTestIterationStart(
const UnitTest& unit_test, int iteration) { const UnitTest& unit_test, int iteration) {
if (GTEST_FLAG_GET(repeat) != 1) if (GTEST_FLAG_GET(repeat) != 1)
...@@ -3552,12 +3492,12 @@ void PrettyUnitTestResultPrinter::OnTestEnd(const TestInfo& test_info) { ...@@ -3552,12 +3492,12 @@ void PrettyUnitTestResultPrinter::OnTestEnd(const TestInfo& test_info) {
ColoredPrintf(GTestColor::kRed, "[ 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()) PrintFullTestCommentIfPresent(test_info);
PrintFullTestCommentIfPresent(test_info);
if (GTEST_FLAG_GET(print_time)) { if (GTEST_FLAG_GET(print_time)) {
printf(" (%s ms)\n", internal::StreamableToString( printf(" (%s ms)\n",
test_info.result()->elapsed_time()).c_str()); internal::StreamableToString(test_info.result()->elapsed_time())
.c_str());
} else { } else {
printf("\n"); printf("\n");
} }
...@@ -3819,7 +3759,7 @@ class TestEventRepeater : public TestEventListener { ...@@ -3819,7 +3759,7 @@ class TestEventRepeater : public TestEventListener {
public: public:
TestEventRepeater() : forwarding_enabled_(true) {} TestEventRepeater() : forwarding_enabled_(true) {}
~TestEventRepeater() override; ~TestEventRepeater() override;
void Append(TestEventListener *listener); void Append(TestEventListener* listener);
TestEventListener* Release(TestEventListener* listener); TestEventListener* Release(TestEventListener* listener);
// Controls whether events will be forwarded to listeners_. Set to false // Controls whether events will be forwarded to listeners_. Set to false
...@@ -3864,11 +3804,11 @@ TestEventRepeater::~TestEventRepeater() { ...@@ -3864,11 +3804,11 @@ TestEventRepeater::~TestEventRepeater() {
ForEach(listeners_, Delete<TestEventListener>); ForEach(listeners_, Delete<TestEventListener>);
} }
void TestEventRepeater::Append(TestEventListener *listener) { void TestEventRepeater::Append(TestEventListener* listener) {
listeners_.push_back(listener); listeners_.push_back(listener);
} }
TestEventListener* TestEventRepeater::Release(TestEventListener *listener) { TestEventListener* TestEventRepeater::Release(TestEventListener* listener) {
for (size_t i = 0; i < listeners_.size(); ++i) { for (size_t i = 0; i < listeners_.size(); ++i) {
if (listeners_[i] == listener) { if (listeners_[i] == listener) {
listeners_.erase(listeners_.begin() + static_cast<int>(i)); listeners_.erase(listeners_.begin() + static_cast<int>(i));
...@@ -3881,14 +3821,14 @@ TestEventListener* TestEventRepeater::Release(TestEventListener *listener) { ...@@ -3881,14 +3821,14 @@ TestEventListener* TestEventRepeater::Release(TestEventListener *listener) {
// Since most methods are very similar, use macros to reduce boilerplate. // Since most methods are very similar, use macros to reduce boilerplate.
// This defines a member that forwards the call to all listeners. // This defines a member that forwards the call to all listeners.
#define GTEST_REPEATER_METHOD_(Name, Type) \ #define GTEST_REPEATER_METHOD_(Name, Type) \
void TestEventRepeater::Name(const Type& parameter) { \ void TestEventRepeater::Name(const Type& parameter) { \
if (forwarding_enabled_) { \ if (forwarding_enabled_) { \
for (size_t i = 0; i < listeners_.size(); i++) { \ for (size_t i = 0; i < listeners_.size(); i++) { \
listeners_[i]->Name(parameter); \ listeners_[i]->Name(parameter); \
} \ } \
} \ } \
} }
// This defines a member that forwards the call to all listeners in reverse // This defines a member that forwards the call to all listeners in reverse
// order. // order.
#define GTEST_REVERSE_REPEATER_METHOD_(Name, Type) \ #define GTEST_REVERSE_REPEATER_METHOD_(Name, Type) \
...@@ -4075,8 +4015,8 @@ void XmlUnitTestResultPrinter::ListTestsMatchingFilter( ...@@ -4075,8 +4015,8 @@ void XmlUnitTestResultPrinter::ListTestsMatchingFilter(
// module will consist of ordinary English text. // module will consist of ordinary English text.
// If this module is ever modified to produce version 1.1 XML output, // If this module is ever modified to produce version 1.1 XML output,
// most invalid characters can be retained using character references. // most invalid characters can be retained using character references.
std::string XmlUnitTestResultPrinter::EscapeXml( std::string XmlUnitTestResultPrinter::EscapeXml(const std::string& str,
const std::string& str, bool is_attribute) { bool is_attribute) {
Message m; Message m;
for (size_t i = 0; i < str.size(); ++i) { for (size_t i = 0; i < str.size(); ++i) {
...@@ -4183,12 +4123,12 @@ std::string FormatEpochTimeInMillisAsIso8601(TimeInMillis ms) { ...@@ -4183,12 +4123,12 @@ std::string FormatEpochTimeInMillisAsIso8601(TimeInMillis ms) {
return ""; return "";
// YYYY-MM-DDThh:mm:ss.sss // YYYY-MM-DDThh:mm:ss.sss
return StreamableToString(time_struct.tm_year + 1900) + "-" + return StreamableToString(time_struct.tm_year + 1900) + "-" +
String::FormatIntWidth2(time_struct.tm_mon + 1) + "-" + String::FormatIntWidth2(time_struct.tm_mon + 1) + "-" +
String::FormatIntWidth2(time_struct.tm_mday) + "T" + String::FormatIntWidth2(time_struct.tm_mday) + "T" +
String::FormatIntWidth2(time_struct.tm_hour) + ":" + String::FormatIntWidth2(time_struct.tm_hour) + ":" +
String::FormatIntWidth2(time_struct.tm_min) + ":" + String::FormatIntWidth2(time_struct.tm_min) + ":" +
String::FormatIntWidth2(time_struct.tm_sec) + "." + String::FormatIntWidth2(time_struct.tm_sec) + "." +
String::FormatIntWidthN(static_cast<int>(ms % 1000), 3); String::FormatIntWidthN(static_cast<int>(ms % 1000), 3);
} }
// Streams an XML CDATA section, escaping invalid CDATA sequences as needed. // Streams an XML CDATA section, escaping invalid CDATA sequences as needed.
...@@ -4199,8 +4139,8 @@ void XmlUnitTestResultPrinter::OutputXmlCDataSection(::std::ostream* stream, ...@@ -4199,8 +4139,8 @@ void XmlUnitTestResultPrinter::OutputXmlCDataSection(::std::ostream* stream,
for (;;) { for (;;) {
const char* const next_segment = strstr(segment, "]]>"); const char* const next_segment = strstr(segment, "]]>");
if (next_segment != nullptr) { if (next_segment != nullptr) {
stream->write( stream->write(segment,
segment, static_cast<std::streamsize>(next_segment - segment)); static_cast<std::streamsize>(next_segment - segment));
*stream << "]]>]]&gt;<![CDATA["; *stream << "]]>]]&gt;<![CDATA[";
segment = next_segment + strlen("]]>"); segment = next_segment + strlen("]]>");
} else { } else {
...@@ -4212,15 +4152,13 @@ void XmlUnitTestResultPrinter::OutputXmlCDataSection(::std::ostream* stream, ...@@ -4212,15 +4152,13 @@ void XmlUnitTestResultPrinter::OutputXmlCDataSection(::std::ostream* stream,
} }
void XmlUnitTestResultPrinter::OutputXmlAttribute( void XmlUnitTestResultPrinter::OutputXmlAttribute(
std::ostream* stream, std::ostream* stream, const std::string& element_name,
const std::string& element_name, const std::string& name, const std::string& value) {
const std::string& name,
const std::string& value) {
const std::vector<std::string>& allowed_names = const std::vector<std::string>& allowed_names =
GetReservedOutputAttributesForElement(element_name); GetReservedOutputAttributesForElement(element_name);
GTEST_CHECK_(std::find(allowed_names.begin(), allowed_names.end(), name) != GTEST_CHECK_(std::find(allowed_names.begin(), allowed_names.end(), name) !=
allowed_names.end()) allowed_names.end())
<< "Attribute " << name << " is not allowed for element <" << element_name << "Attribute " << name << " is not allowed for element <" << element_name
<< ">."; << ">.";
...@@ -4286,10 +4224,11 @@ void XmlUnitTestResultPrinter::OutputXmlTestInfo(::std::ostream* stream, ...@@ -4286,10 +4224,11 @@ void XmlUnitTestResultPrinter::OutputXmlTestInfo(::std::ostream* stream,
OutputXmlAttribute(stream, kTestsuite, "type_param", OutputXmlAttribute(stream, kTestsuite, "type_param",
test_info.type_param()); test_info.type_param());
} }
OutputXmlAttribute(stream, kTestsuite, "file", test_info.file());
OutputXmlAttribute(stream, kTestsuite, "line",
StreamableToString(test_info.line()));
if (GTEST_FLAG_GET(list_tests)) { if (GTEST_FLAG_GET(list_tests)) {
OutputXmlAttribute(stream, kTestsuite, "file", test_info.file());
OutputXmlAttribute(stream, kTestsuite, "line",
StreamableToString(test_info.line()));
*stream << " />\n"; *stream << " />\n";
return; return;
} }
...@@ -4324,8 +4263,7 @@ void XmlUnitTestResultPrinter::OutputXmlTestResult(::std::ostream* stream, ...@@ -4324,8 +4263,7 @@ void XmlUnitTestResultPrinter::OutputXmlTestResult(::std::ostream* stream,
internal::FormatCompilerIndependentFileLocation(part.file_name(), internal::FormatCompilerIndependentFileLocation(part.file_name(),
part.line_number()); part.line_number());
const std::string summary = location + "\n" + part.summary(); const std::string summary = location + "\n" + part.summary();
*stream << " <failure message=\"" *stream << " <failure message=\"" << EscapeXmlAttribute(summary)
<< EscapeXmlAttribute(summary)
<< "\" type=\"\">"; << "\" type=\"\">";
const std::string detail = location + "\n" + part.message(); const std::string detail = location + "\n" + part.message();
OutputXmlCDataSection(stream, RemoveInvalidXmlCharacters(detail).c_str()); OutputXmlCDataSection(stream, RemoveInvalidXmlCharacters(detail).c_str());
...@@ -4466,7 +4404,7 @@ std::string XmlUnitTestResultPrinter::TestPropertiesAsXmlAttributes( ...@@ -4466,7 +4404,7 @@ std::string XmlUnitTestResultPrinter::TestPropertiesAsXmlAttributes(
for (int i = 0; i < result.test_property_count(); ++i) { for (int i = 0; i < result.test_property_count(); ++i) {
const TestProperty& property = result.GetTestProperty(i); const TestProperty& property = result.GetTestProperty(i);
attributes << " " << property.key() << "=" attributes << " " << property.key() << "="
<< "\"" << EscapeXmlAttribute(property.value()) << "\""; << "\"" << EscapeXmlAttribute(property.value()) << "\"";
} }
return attributes.GetString(); return attributes.GetString();
} }
...@@ -4512,16 +4450,12 @@ class JsonUnitTestResultPrinter : public EmptyTestEventListener { ...@@ -4512,16 +4450,12 @@ class JsonUnitTestResultPrinter : public EmptyTestEventListener {
//// streams the attribute as JSON. //// streams the attribute as JSON.
static void OutputJsonKey(std::ostream* stream, static void OutputJsonKey(std::ostream* stream,
const std::string& element_name, const std::string& element_name,
const std::string& name, const std::string& name, const std::string& value,
const std::string& value, const std::string& indent, bool comma = true);
const std::string& indent,
bool comma = true);
static void OutputJsonKey(std::ostream* stream, static void OutputJsonKey(std::ostream* stream,
const std::string& element_name, const std::string& element_name,
const std::string& name, const std::string& name, int value,
int value, const std::string& indent, bool comma = true);
const std::string& indent,
bool comma = true);
// Streams a test suite JSON stanza containing the given test result. // Streams a test suite JSON stanza containing the given test result.
// //
...@@ -4566,7 +4500,7 @@ JsonUnitTestResultPrinter::JsonUnitTestResultPrinter(const char* output_file) ...@@ -4566,7 +4500,7 @@ JsonUnitTestResultPrinter::JsonUnitTestResultPrinter(const char* output_file)
} }
void JsonUnitTestResultPrinter::OnTestIterationEnd(const UnitTest& unit_test, void JsonUnitTestResultPrinter::OnTestIterationEnd(const UnitTest& unit_test,
int /*iteration*/) { int /*iteration*/) {
FILE* jsonout = OpenFileForWriting(output_file_); FILE* jsonout = OpenFileForWriting(output_file_);
std::stringstream stream; std::stringstream stream;
PrintJsonUnitTest(&stream, unit_test); PrintJsonUnitTest(&stream, unit_test);
...@@ -4632,55 +4566,48 @@ static std::string FormatEpochTimeInMillisAsRFC3339(TimeInMillis ms) { ...@@ -4632,55 +4566,48 @@ static std::string FormatEpochTimeInMillisAsRFC3339(TimeInMillis ms) {
return ""; return "";
// YYYY-MM-DDThh:mm:ss // YYYY-MM-DDThh:mm:ss
return StreamableToString(time_struct.tm_year + 1900) + "-" + return StreamableToString(time_struct.tm_year + 1900) + "-" +
String::FormatIntWidth2(time_struct.tm_mon + 1) + "-" + String::FormatIntWidth2(time_struct.tm_mon + 1) + "-" +
String::FormatIntWidth2(time_struct.tm_mday) + "T" + String::FormatIntWidth2(time_struct.tm_mday) + "T" +
String::FormatIntWidth2(time_struct.tm_hour) + ":" + String::FormatIntWidth2(time_struct.tm_hour) + ":" +
String::FormatIntWidth2(time_struct.tm_min) + ":" + String::FormatIntWidth2(time_struct.tm_min) + ":" +
String::FormatIntWidth2(time_struct.tm_sec) + "Z"; String::FormatIntWidth2(time_struct.tm_sec) + "Z";
} }
static inline std::string Indent(size_t width) { static inline std::string Indent(size_t width) {
return std::string(width, ' '); return std::string(width, ' ');
} }
void JsonUnitTestResultPrinter::OutputJsonKey( void JsonUnitTestResultPrinter::OutputJsonKey(std::ostream* stream,
std::ostream* stream, const std::string& element_name,
const std::string& element_name, const std::string& name,
const std::string& name, const std::string& value,
const std::string& value, const std::string& indent,
const std::string& indent, bool comma) {
bool comma) {
const std::vector<std::string>& allowed_names = const std::vector<std::string>& allowed_names =
GetReservedOutputAttributesForElement(element_name); GetReservedOutputAttributesForElement(element_name);
GTEST_CHECK_(std::find(allowed_names.begin(), allowed_names.end(), name) != GTEST_CHECK_(std::find(allowed_names.begin(), allowed_names.end(), name) !=
allowed_names.end()) allowed_names.end())
<< "Key \"" << name << "\" is not allowed for value \"" << element_name << "Key \"" << name << "\" is not allowed for value \"" << element_name
<< "\"."; << "\".";
*stream << indent << "\"" << name << "\": \"" << EscapeJson(value) << "\""; *stream << indent << "\"" << name << "\": \"" << EscapeJson(value) << "\"";
if (comma) if (comma) *stream << ",\n";
*stream << ",\n";
} }
void JsonUnitTestResultPrinter::OutputJsonKey( void JsonUnitTestResultPrinter::OutputJsonKey(
std::ostream* stream, std::ostream* stream, const std::string& element_name,
const std::string& element_name, const std::string& name, int value, const std::string& indent, bool comma) {
const std::string& name,
int value,
const std::string& indent,
bool comma) {
const std::vector<std::string>& allowed_names = const std::vector<std::string>& allowed_names =
GetReservedOutputAttributesForElement(element_name); GetReservedOutputAttributesForElement(element_name);
GTEST_CHECK_(std::find(allowed_names.begin(), allowed_names.end(), name) != GTEST_CHECK_(std::find(allowed_names.begin(), allowed_names.end(), name) !=
allowed_names.end()) allowed_names.end())
<< "Key \"" << name << "\" is not allowed for value \"" << element_name << "Key \"" << name << "\" is not allowed for value \"" << element_name
<< "\"."; << "\".";
*stream << indent << "\"" << name << "\": " << StreamableToString(value); *stream << indent << "\"" << name << "\": " << StreamableToString(value);
if (comma) if (comma) *stream << ",\n";
*stream << ",\n";
} }
// Streams a test suite JSON stanza containing the given test result. // Streams a test suite JSON stanza containing the given test result.
...@@ -4744,11 +4671,14 @@ void JsonUnitTestResultPrinter::OutputJsonTestInfo(::std::ostream* stream, ...@@ -4744,11 +4671,14 @@ void JsonUnitTestResultPrinter::OutputJsonTestInfo(::std::ostream* stream,
OutputJsonKey(stream, kTestsuite, "type_param", test_info.type_param(), OutputJsonKey(stream, kTestsuite, "type_param", test_info.type_param(),
kIndent); kIndent);
} }
OutputJsonKey(stream, kTestsuite, "file", test_info.file(), kIndent);
OutputJsonKey(stream, kTestsuite, "line", test_info.line(), kIndent, false);
if (GTEST_FLAG_GET(list_tests)) { if (GTEST_FLAG_GET(list_tests)) {
OutputJsonKey(stream, kTestsuite, "file", test_info.file(), kIndent);
OutputJsonKey(stream, kTestsuite, "line", test_info.line(), kIndent, false);
*stream << "\n" << Indent(8) << "}"; *stream << "\n" << Indent(8) << "}";
return; return;
} else {
*stream << ",\n";
} }
OutputJsonKey(stream, kTestsuite, "status", OutputJsonKey(stream, kTestsuite, "status",
...@@ -4780,7 +4710,9 @@ void JsonUnitTestResultPrinter::OutputJsonTestResult(::std::ostream* stream, ...@@ -4780,7 +4710,9 @@ void JsonUnitTestResultPrinter::OutputJsonTestResult(::std::ostream* stream,
if (part.failed()) { if (part.failed()) {
*stream << ",\n"; *stream << ",\n";
if (++failures == 1) { if (++failures == 1) {
*stream << kIndent << "\"" << "failures" << "\": [\n"; *stream << kIndent << "\""
<< "failures"
<< "\": [\n";
} }
const std::string location = const std::string location =
internal::FormatCompilerIndependentFileLocation(part.file_name(), internal::FormatCompilerIndependentFileLocation(part.file_name(),
...@@ -4793,8 +4725,7 @@ void JsonUnitTestResultPrinter::OutputJsonTestResult(::std::ostream* stream, ...@@ -4793,8 +4725,7 @@ void JsonUnitTestResultPrinter::OutputJsonTestResult(::std::ostream* stream,
} }
} }
if (failures > 0) if (failures > 0) *stream << "\n" << kIndent << "]";
*stream << "\n" << kIndent << "]";
*stream << "\n" << Indent(8) << "}"; *stream << "\n" << Indent(8) << "}";
} }
...@@ -4890,7 +4821,9 @@ void JsonUnitTestResultPrinter::PrintJsonUnitTest(std::ostream* stream, ...@@ -4890,7 +4821,9 @@ void JsonUnitTestResultPrinter::PrintJsonUnitTest(std::ostream* stream,
OutputJsonTestSuiteForTestResult(stream, unit_test.ad_hoc_test_result()); OutputJsonTestSuiteForTestResult(stream, unit_test.ad_hoc_test_result());
} }
*stream << "\n" << kIndent << "]\n" << "}\n"; *stream << "\n"
<< kIndent << "]\n"
<< "}\n";
} }
void JsonUnitTestResultPrinter::PrintJsonTestList( void JsonUnitTestResultPrinter::PrintJsonTestList(
...@@ -4925,7 +4858,8 @@ std::string JsonUnitTestResultPrinter::TestPropertiesAsJson( ...@@ -4925,7 +4858,8 @@ std::string JsonUnitTestResultPrinter::TestPropertiesAsJson(
Message attributes; Message attributes;
for (int i = 0; i < result.test_property_count(); ++i) { for (int i = 0; i < result.test_property_count(); ++i) {
const TestProperty& property = result.GetTestProperty(i); const TestProperty& property = result.GetTestProperty(i);
attributes << ",\n" << indent << "\"" << property.key() << "\": " attributes << ",\n"
<< indent << "\"" << property.key() << "\": "
<< "\"" << EscapeJson(property.value()) << "\""; << "\"" << EscapeJson(property.value()) << "\"";
} }
return attributes.GetString(); return attributes.GetString();
...@@ -4965,14 +4899,14 @@ void StreamingListener::SocketWriter::MakeConnection() { ...@@ -4965,14 +4899,14 @@ void StreamingListener::SocketWriter::MakeConnection() {
addrinfo hints; addrinfo hints;
memset(&hints, 0, sizeof(hints)); memset(&hints, 0, sizeof(hints));
hints.ai_family = AF_UNSPEC; // To allow both IPv4 and IPv6 addresses. hints.ai_family = AF_UNSPEC; // To allow both IPv4 and IPv6 addresses.
hints.ai_socktype = SOCK_STREAM; hints.ai_socktype = SOCK_STREAM;
addrinfo* servinfo = nullptr; addrinfo* servinfo = nullptr;
// Use the getaddrinfo() to get a linked list of IP addresses for // Use the getaddrinfo() to get a linked list of IP addresses for
// the given host name. // the given host name.
const int error_num = getaddrinfo( const int error_num =
host_name_.c_str(), port_num_.c_str(), &hints, &servinfo); getaddrinfo(host_name_.c_str(), port_num_.c_str(), &hints, &servinfo);
if (error_num != 0) { if (error_num != 0) {
GTEST_LOG_(WARNING) << "stream_result_to: getaddrinfo() failed: " GTEST_LOG_(WARNING) << "stream_result_to: getaddrinfo() failed: "
<< gai_strerror(error_num); << gai_strerror(error_num);
...@@ -4981,8 +4915,8 @@ void StreamingListener::SocketWriter::MakeConnection() { ...@@ -4981,8 +4915,8 @@ void StreamingListener::SocketWriter::MakeConnection() {
// Loop through all the results and connect to the first we can. // Loop through all the results and connect to the first we can.
for (addrinfo* cur_addr = servinfo; sockfd_ == -1 && cur_addr != nullptr; for (addrinfo* cur_addr = servinfo; sockfd_ == -1 && cur_addr != nullptr;
cur_addr = cur_addr->ai_next) { cur_addr = cur_addr->ai_next) {
sockfd_ = socket( sockfd_ = socket(cur_addr->ai_family, cur_addr->ai_socktype,
cur_addr->ai_family, cur_addr->ai_socktype, cur_addr->ai_protocol); cur_addr->ai_protocol);
if (sockfd_ != -1) { if (sockfd_ != -1) {
// Connect the client socket to the server socket. // Connect the client socket to the server socket.
if (connect(sockfd_, cur_addr->ai_addr, cur_addr->ai_addrlen) == -1) { if (connect(sockfd_, cur_addr->ai_addr, cur_addr->ai_addrlen) == -1) {
...@@ -5051,7 +4985,7 @@ std::string OsStackTraceGetter::CurrentStackTrace(int max_depth, int skip_count) ...@@ -5051,7 +4985,7 @@ std::string OsStackTraceGetter::CurrentStackTrace(int max_depth, int skip_count)
return result; return result;
#else // !GTEST_HAS_ABSL #else // !GTEST_HAS_ABSL
static_cast<void>(max_depth); static_cast<void>(max_depth);
static_cast<void>(skip_count); static_cast<void>(skip_count);
return ""; return "";
...@@ -5075,8 +5009,8 @@ void OsStackTraceGetter::UponLeavingGTest() GTEST_LOCK_EXCLUDED_(mutex_) { ...@@ -5075,8 +5009,8 @@ void OsStackTraceGetter::UponLeavingGTest() GTEST_LOCK_EXCLUDED_(mutex_) {
class ScopedPrematureExitFile { class ScopedPrematureExitFile {
public: public:
explicit ScopedPrematureExitFile(const char* premature_exit_filepath) explicit ScopedPrematureExitFile(const char* premature_exit_filepath)
: premature_exit_filepath_(premature_exit_filepath ? : premature_exit_filepath_(
premature_exit_filepath : "") { premature_exit_filepath ? premature_exit_filepath : "") {
// If a path to the premature-exit file is specified... // If a path to the premature-exit file is specified...
if (!premature_exit_filepath_.empty()) { if (!premature_exit_filepath_.empty()) {
// create the file with a single "0" character in it. I/O // create the file with a single "0" character in it. I/O
...@@ -5278,7 +5212,7 @@ int UnitTest::test_to_run_count() const { return impl()->test_to_run_count(); } ...@@ -5278,7 +5212,7 @@ int UnitTest::test_to_run_count() const { return impl()->test_to_run_count(); }
// Gets the time of the test program start, in ms from the start of the // Gets the time of the test program start, in ms from the start of the
// UNIX epoch. // UNIX epoch.
internal::TimeInMillis UnitTest::start_timestamp() const { internal::TimeInMillis UnitTest::start_timestamp() const {
return impl()->start_timestamp(); return impl()->start_timestamp();
} }
// Gets the elapsed time, in milliseconds. // Gets the elapsed time, in milliseconds.
...@@ -5321,9 +5255,7 @@ TestSuite* UnitTest::GetMutableTestSuite(int i) { ...@@ -5321,9 +5255,7 @@ TestSuite* UnitTest::GetMutableTestSuite(int i) {
// Returns the list of event listeners that can be used to track events // Returns the list of event listeners that can be used to track events
// inside Google Test. // inside Google Test.
TestEventListeners& UnitTest::listeners() { TestEventListeners& UnitTest::listeners() { return *impl()->listeners(); }
return *impl()->listeners();
}
// Registers and returns a global test environment. When a test // Registers and returns a global test environment. When a test
// program is run, all global test environments will be set-up in the // program is run, all global test environments will be set-up in the
...@@ -5348,12 +5280,11 @@ Environment* UnitTest::AddEnvironment(Environment* env) { ...@@ -5348,12 +5280,11 @@ Environment* UnitTest::AddEnvironment(Environment* env) {
// assertion macros (e.g. ASSERT_TRUE, EXPECT_EQ, etc) eventually call // assertion macros (e.g. ASSERT_TRUE, EXPECT_EQ, etc) eventually call
// this to report their results. The user code should use the // this to report their results. The user code should use the
// assertion macros instead of calling this directly. // assertion macros instead of calling this directly.
void UnitTest::AddTestPartResult( void UnitTest::AddTestPartResult(TestPartResult::Type result_type,
TestPartResult::Type result_type, const char* file_name, int line_number,
const char* file_name, const std::string& message,
int line_number, const std::string& os_stack_trace)
const std::string& message, GTEST_LOCK_EXCLUDED_(mutex_) {
const std::string& os_stack_trace) GTEST_LOCK_EXCLUDED_(mutex_) {
Message msg; Message msg;
msg << message; msg << message;
...@@ -5363,8 +5294,9 @@ void UnitTest::AddTestPartResult( ...@@ -5363,8 +5294,9 @@ void UnitTest::AddTestPartResult(
for (size_t i = impl_->gtest_trace_stack().size(); i > 0; --i) { for (size_t i = impl_->gtest_trace_stack().size(); i > 0; --i) {
const internal::TraceInfo& trace = impl_->gtest_trace_stack()[i - 1]; const internal::TraceInfo& trace = impl_->gtest_trace_stack()[i - 1];
msg << "\n" << internal::FormatFileLocation(trace.file, trace.line) msg << "\n"
<< " " << trace.message; << internal::FormatFileLocation(trace.file, trace.line) << " "
<< trace.message;
} }
} }
...@@ -5374,8 +5306,8 @@ void UnitTest::AddTestPartResult( ...@@ -5374,8 +5306,8 @@ void UnitTest::AddTestPartResult(
const TestPartResult result = TestPartResult( const TestPartResult result = TestPartResult(
result_type, file_name, line_number, msg.GetString().c_str()); result_type, file_name, line_number, msg.GetString().c_str());
impl_->GetTestPartResultReporterForCurrentThread()-> impl_->GetTestPartResultReporterForCurrentThread()->ReportTestPartResult(
ReportTestPartResult(result); result);
if (result_type != TestPartResult::kSuccess && if (result_type != TestPartResult::kSuccess &&
result_type != TestPartResult::kSkip) { result_type != TestPartResult::kSkip) {
...@@ -5468,20 +5400,20 @@ int UnitTest::Run() { ...@@ -5468,20 +5400,20 @@ int UnitTest::Run() {
// process. In either case the user does not want to see pop-up dialogs // process. In either case the user does not want to see pop-up dialogs
// about crashes - they are expected. // about crashes - they are expected.
if (impl()->catch_exceptions() || in_death_test_child_process) { if (impl()->catch_exceptions() || in_death_test_child_process) {
# if !GTEST_OS_WINDOWS_MOBILE && !GTEST_OS_WINDOWS_PHONE && !GTEST_OS_WINDOWS_RT #if !GTEST_OS_WINDOWS_MOBILE && !GTEST_OS_WINDOWS_PHONE && !GTEST_OS_WINDOWS_RT
// SetErrorMode doesn't exist on CE. // SetErrorMode doesn't exist on CE.
SetErrorMode(SEM_FAILCRITICALERRORS | SEM_NOALIGNMENTFAULTEXCEPT | SetErrorMode(SEM_FAILCRITICALERRORS | SEM_NOALIGNMENTFAULTEXCEPT |
SEM_NOGPFAULTERRORBOX | SEM_NOOPENFILEERRORBOX); SEM_NOGPFAULTERRORBOX | SEM_NOOPENFILEERRORBOX);
# endif // !GTEST_OS_WINDOWS_MOBILE #endif // !GTEST_OS_WINDOWS_MOBILE
# if (defined(_MSC_VER) || GTEST_OS_WINDOWS_MINGW) && !GTEST_OS_WINDOWS_MOBILE #if (defined(_MSC_VER) || GTEST_OS_WINDOWS_MINGW) && !GTEST_OS_WINDOWS_MOBILE
// Death test children can be terminated with _abort(). On Windows, // Death test children can be terminated with _abort(). On Windows,
// _abort() can show a dialog with a warning message. This forces the // _abort() can show a dialog with a warning message. This forces the
// abort message to go to stderr instead. // abort message to go to stderr instead.
_set_error_mode(_OUT_TO_STDERR); _set_error_mode(_OUT_TO_STDERR);
# endif #endif
# if defined(_MSC_VER) && !GTEST_OS_WINDOWS_MOBILE #if defined(_MSC_VER) && !GTEST_OS_WINDOWS_MOBILE
// In the debug version, Visual Studio pops up a separate dialog // In the debug version, Visual Studio pops up a separate dialog
// offering a choice to debug the aborted program. We need to suppress // offering a choice to debug the aborted program. We need to suppress
// this dialog or it will pop up for every EXPECT/ASSERT_DEATH statement // this dialog or it will pop up for every EXPECT/ASSERT_DEATH statement
...@@ -5501,14 +5433,15 @@ int UnitTest::Run() { ...@@ -5501,14 +5433,15 @@ int UnitTest::Run() {
_CRTDBG_MODE_FILE | _CRTDBG_MODE_DEBUG); _CRTDBG_MODE_FILE | _CRTDBG_MODE_DEBUG);
(void)_CrtSetReportFile(_CRT_ASSERT, _CRTDBG_FILE_STDERR); (void)_CrtSetReportFile(_CRT_ASSERT, _CRTDBG_FILE_STDERR);
} }
# endif #endif
} }
#endif // GTEST_OS_WINDOWS #endif // GTEST_OS_WINDOWS
return internal::HandleExceptionsInMethodIfSupported( return internal::HandleExceptionsInMethodIfSupported(
impl(), impl(), &internal::UnitTestImpl::RunAllTests,
&internal::UnitTestImpl::RunAllTests, "auxiliary test code (environments or event listeners)")
"auxiliary test code (environments or event listeners)") ? 0 : 1; ? 0
: 1;
} }
// Returns the working directory when the first TEST() or TEST_F() was // Returns the working directory when the first TEST() or TEST_F() was
...@@ -5553,14 +5486,10 @@ UnitTest::parameterized_test_registry() GTEST_LOCK_EXCLUDED_(mutex_) { ...@@ -5553,14 +5486,10 @@ UnitTest::parameterized_test_registry() GTEST_LOCK_EXCLUDED_(mutex_) {
} }
// Creates an empty UnitTest. // Creates an empty UnitTest.
UnitTest::UnitTest() { UnitTest::UnitTest() { impl_ = new internal::UnitTestImpl(this); }
impl_ = new internal::UnitTestImpl(this);
}
// Destructor of UnitTest. // Destructor of UnitTest.
UnitTest::~UnitTest() { UnitTest::~UnitTest() { delete impl_; }
delete impl_;
}
// Pushes a trace defined by SCOPED_TRACE() on to the per-thread // Pushes a trace defined by SCOPED_TRACE() on to the per-thread
// Google Test trace stack. // Google Test trace stack.
...@@ -5571,8 +5500,7 @@ void UnitTest::PushGTestTrace(const internal::TraceInfo& trace) ...@@ -5571,8 +5500,7 @@ void UnitTest::PushGTestTrace(const internal::TraceInfo& trace)
} }
// Pops a trace from the per-thread Google Test trace stack. // Pops a trace from the per-thread Google Test trace stack.
void UnitTest::PopGTestTrace() void UnitTest::PopGTestTrace() GTEST_LOCK_EXCLUDED_(mutex_) {
GTEST_LOCK_EXCLUDED_(mutex_) {
internal::MutexLock lock(&mutex_); internal::MutexLock lock(&mutex_);
impl_->gtest_trace_stack().pop_back(); impl_->gtest_trace_stack().pop_back();
} }
...@@ -5673,8 +5601,8 @@ void UnitTestImpl::ConfigureStreamingOutput() { ...@@ -5673,8 +5601,8 @@ void UnitTestImpl::ConfigureStreamingOutput() {
if (!target.empty()) { if (!target.empty()) {
const size_t pos = target.find(':'); const size_t pos = target.find(':');
if (pos != std::string::npos) { if (pos != std::string::npos) {
listeners()->Append(new StreamingListener(target.substr(0, pos), listeners()->Append(
target.substr(pos+1))); new StreamingListener(target.substr(0, pos), target.substr(pos + 1)));
} else { } else {
GTEST_LOG_(WARNING) << "unrecognized streaming target \"" << target GTEST_LOG_(WARNING) << "unrecognized streaming target \"" << target
<< "\" ignored."; << "\" ignored.";
...@@ -5819,8 +5747,7 @@ bool UnitTestImpl::RunAllTests() { ...@@ -5819,8 +5747,7 @@ bool UnitTestImpl::RunAllTests() {
const bool gtest_is_initialized_before_run_all_tests = GTestIsInitialized(); const bool gtest_is_initialized_before_run_all_tests = GTestIsInitialized();
// Do not run any test if the --help flag was specified. // Do not run any test if the --help flag was specified.
if (g_help_flag) if (g_help_flag) return true;
return true;
// Repeats the call to the post-flag parsing initialization in case the // Repeats the call to the post-flag parsing initialization in case the
// user didn't call InitGoogleTest. // user didn't call InitGoogleTest.
...@@ -5838,11 +5765,11 @@ bool UnitTestImpl::RunAllTests() { ...@@ -5838,11 +5765,11 @@ bool UnitTestImpl::RunAllTests() {
#if GTEST_HAS_DEATH_TEST #if GTEST_HAS_DEATH_TEST
in_subprocess_for_death_test = in_subprocess_for_death_test =
(internal_run_death_test_flag_.get() != nullptr); (internal_run_death_test_flag_.get() != nullptr);
# if defined(GTEST_EXTRA_DEATH_TEST_CHILD_SETUP_) #if defined(GTEST_EXTRA_DEATH_TEST_CHILD_SETUP_)
if (in_subprocess_for_death_test) { if (in_subprocess_for_death_test) {
GTEST_EXTRA_DEATH_TEST_CHILD_SETUP_(); GTEST_EXTRA_DEATH_TEST_CHILD_SETUP_();
} }
# endif // defined(GTEST_EXTRA_DEATH_TEST_CHILD_SETUP_) #endif // defined(GTEST_EXTRA_DEATH_TEST_CHILD_SETUP_)
#endif // GTEST_HAS_DEATH_TEST #endif // GTEST_HAS_DEATH_TEST
const bool should_shard = ShouldShard(kTestTotalShards, kTestShardIndex, const bool should_shard = ShouldShard(kTestTotalShards, kTestShardIndex,
...@@ -5850,9 +5777,9 @@ bool UnitTestImpl::RunAllTests() { ...@@ -5850,9 +5777,9 @@ bool UnitTestImpl::RunAllTests() {
// Compares the full test names with the filter to decide which // Compares the full test names with the filter to decide which
// tests to run. // tests to run.
const bool has_tests_to_run = FilterTests(should_shard const bool has_tests_to_run =
? HONOR_SHARDING_PROTOCOL FilterTests(should_shard ? HONOR_SHARDING_PROTOCOL
: IGNORE_SHARDING_PROTOCOL) > 0; : IGNORE_SHARDING_PROTOCOL) > 0;
// Lists the tests and exits if the --gtest_list_tests flag was specified. // Lists the tests and exits if the --gtest_list_tests flag was specified.
if (GTEST_FLAG_GET(list_tests)) { if (GTEST_FLAG_GET(list_tests)) {
...@@ -6035,8 +5962,7 @@ void WriteToShardStatusFileIfNeeded() { ...@@ -6035,8 +5962,7 @@ void WriteToShardStatusFileIfNeeded() {
// an error and exits. If in_subprocess_for_death_test, sharding is // an error and exits. If in_subprocess_for_death_test, sharding is
// disabled because it must only be applied to the original test // disabled because it must only be applied to the original test
// process. Otherwise, we could filter out death tests we intended to execute. // process. Otherwise, we could filter out death tests we intended to execute.
bool ShouldShard(const char* total_shards_env, bool ShouldShard(const char* total_shards_env, const char* shard_index_env,
const char* shard_index_env,
bool in_subprocess_for_death_test) { bool in_subprocess_for_death_test) {
if (in_subprocess_for_death_test) { if (in_subprocess_for_death_test) {
return false; return false;
...@@ -6048,27 +5974,27 @@ bool ShouldShard(const char* total_shards_env, ...@@ -6048,27 +5974,27 @@ bool ShouldShard(const char* total_shards_env,
if (total_shards == -1 && shard_index == -1) { if (total_shards == -1 && shard_index == -1) {
return false; return false;
} else if (total_shards == -1 && shard_index != -1) { } else if (total_shards == -1 && shard_index != -1) {
const Message msg = Message() const Message msg = Message() << "Invalid environment variables: you have "
<< "Invalid environment variables: you have " << kTestShardIndex << " = " << shard_index
<< kTestShardIndex << " = " << shard_index << ", but have left " << kTestTotalShards
<< ", but have left " << kTestTotalShards << " unset.\n"; << " unset.\n";
ColoredPrintf(GTestColor::kRed, "%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) {
const Message msg = Message() const Message msg = Message()
<< "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(GTestColor::kRed, "%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) {
const Message msg = Message() const Message msg =
<< "Invalid environment variables: we require 0 <= " Message() << "Invalid environment variables: we require 0 <= "
<< 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(GTestColor::kRed, "%s", msg.GetString().c_str()); ColoredPrintf(GTestColor::kRed, "%s", msg.GetString().c_str());
fflush(stdout); fflush(stdout);
exit(EXIT_FAILURE); exit(EXIT_FAILURE);
...@@ -6110,10 +6036,12 @@ bool ShouldRunTestOnShard(int total_shards, int shard_index, int test_id) { ...@@ -6110,10 +6036,12 @@ bool ShouldRunTestOnShard(int total_shards, int shard_index, int test_id) {
// https://github.com/google/googletest/blob/master/googletest/docs/advanced.md // https://github.com/google/googletest/blob/master/googletest/docs/advanced.md
// . Returns the number of tests that should run. // . Returns the number of tests that should run.
int UnitTestImpl::FilterTests(ReactionToSharding shard_tests) { int UnitTestImpl::FilterTests(ReactionToSharding shard_tests) {
const int32_t total_shards = shard_tests == HONOR_SHARDING_PROTOCOL ? const int32_t total_shards = shard_tests == HONOR_SHARDING_PROTOCOL
Int32FromEnvOrDie(kTestTotalShards, -1) : -1; ? Int32FromEnvOrDie(kTestTotalShards, -1)
const int32_t shard_index = shard_tests == HONOR_SHARDING_PROTOCOL ? : -1;
Int32FromEnvOrDie(kTestShardIndex, -1) : -1; const int32_t shard_index = shard_tests == HONOR_SHARDING_PROTOCOL
? Int32FromEnvOrDie(kTestShardIndex, -1)
: -1;
const PositiveAndNegativeUnitTestFilter gtest_flag_filter( const PositiveAndNegativeUnitTestFilter gtest_flag_filter(
GTEST_FLAG_GET(filter)); GTEST_FLAG_GET(filter));
...@@ -6323,7 +6251,7 @@ GetCurrentOsStackTraceExceptTop(UnitTest* /*unit_test*/, int skip_count) { ...@@ -6323,7 +6251,7 @@ GetCurrentOsStackTraceExceptTop(UnitTest* /*unit_test*/, int skip_count) {
// suppress unreachable code warnings. // suppress unreachable code warnings.
namespace { namespace {
class ClassUniqueToAlwaysTrue {}; class ClassUniqueToAlwaysTrue {};
} } // namespace
bool IsTrue(bool condition) { return condition; } bool IsTrue(bool condition) { return condition; }
...@@ -6331,8 +6259,7 @@ bool AlwaysTrue() { ...@@ -6331,8 +6259,7 @@ bool AlwaysTrue() {
#if GTEST_HAS_EXCEPTIONS #if GTEST_HAS_EXCEPTIONS
// This condition is always false so AlwaysTrue() never actually throws, // This condition is always false so AlwaysTrue() never actually throws,
// but it makes the compiler think that it may throw. // but it makes the compiler think that it may throw.
if (IsTrue(false)) if (IsTrue(false)) throw ClassUniqueToAlwaysTrue();
throw ClassUniqueToAlwaysTrue();
#endif // GTEST_HAS_EXCEPTIONS #endif // GTEST_HAS_EXCEPTIONS
return true; return true;
} }
...@@ -6444,8 +6371,7 @@ static bool ParseFlag(const char* str, const char* flag_name, String* value) { ...@@ -6444,8 +6371,7 @@ static bool ParseFlag(const char* str, const char* flag_name, String* value) {
// GTEST_INTERNAL_PREFIX_ followed by "internal_" are considered Google Test // GTEST_INTERNAL_PREFIX_ followed by "internal_" are considered Google Test
// internal flags and do not trigger the help message. // internal flags and do not trigger the help message.
static bool HasGoogleTestFlagPrefix(const char* str) { static bool HasGoogleTestFlagPrefix(const char* str) {
return (SkipPrefix("--", &str) || return (SkipPrefix("--", &str) || SkipPrefix("-", &str) ||
SkipPrefix("-", &str) ||
SkipPrefix("/", &str)) && SkipPrefix("/", &str)) &&
!SkipPrefix(GTEST_FLAG_PREFIX_ "internal_", &str) && !SkipPrefix(GTEST_FLAG_PREFIX_ "internal_", &str) &&
(SkipPrefix(GTEST_FLAG_PREFIX_, &str) || (SkipPrefix(GTEST_FLAG_PREFIX_, &str) ||
...@@ -6549,18 +6475,18 @@ static const char kColorEncodedHelpMessage[] = ...@@ -6549,18 +6475,18 @@ static const char kColorEncodedHelpMessage[] =
" Generate a JSON or XML report in the given directory or with the " " Generate a JSON or XML report in the given directory or with the "
"given\n" "given\n"
" file name. @YFILE_PATH@D defaults to @Gtest_detail.xml@D.\n" " file name. @YFILE_PATH@D defaults to @Gtest_detail.xml@D.\n"
# if GTEST_CAN_STREAM_RESULTS_ #if GTEST_CAN_STREAM_RESULTS_
" @G--" GTEST_FLAG_PREFIX_ " @G--" GTEST_FLAG_PREFIX_
"stream_result_to=@YHOST@G:@YPORT@D\n" "stream_result_to=@YHOST@G:@YPORT@D\n"
" Stream test results to the given server.\n" " Stream test results to the given server.\n"
# endif // GTEST_CAN_STREAM_RESULTS_ #endif // GTEST_CAN_STREAM_RESULTS_
"\n" "\n"
"Assertion Behavior:\n" "Assertion Behavior:\n"
# if GTEST_HAS_DEATH_TEST && !GTEST_OS_WINDOWS #if GTEST_HAS_DEATH_TEST && !GTEST_OS_WINDOWS
" @G--" GTEST_FLAG_PREFIX_ " @G--" GTEST_FLAG_PREFIX_
"death_test_style=@Y(@Gfast@Y|@Gthreadsafe@Y)@D\n" "death_test_style=@Y(@Gfast@Y|@Gthreadsafe@Y)@D\n"
" Set the default death test style.\n" " Set the default death test style.\n"
# endif // GTEST_HAS_DEATH_TEST && !GTEST_OS_WINDOWS #endif // GTEST_HAS_DEATH_TEST && !GTEST_OS_WINDOWS
" @G--" GTEST_FLAG_PREFIX_ " @G--" GTEST_FLAG_PREFIX_
"break_on_failure@D\n" "break_on_failure@D\n"
" Turn assertion failures into debugger break-points.\n" " Turn assertion failures into debugger break-points.\n"
...@@ -6637,10 +6563,8 @@ static void LoadFlagsFromFile(const std::string& path) { ...@@ -6637,10 +6563,8 @@ static void LoadFlagsFromFile(const std::string& path) {
std::vector<std::string> lines; std::vector<std::string> lines;
SplitString(contents, '\n', &lines); SplitString(contents, '\n', &lines);
for (size_t i = 0; i < lines.size(); ++i) { for (size_t i = 0; i < lines.size(); ++i) {
if (lines[i].empty()) if (lines[i].empty()) continue;
continue; if (!ParseGoogleTestFlag(lines[i].c_str())) g_help_flag = true;
if (!ParseGoogleTestFlag(lines[i].c_str()))
g_help_flag = true;
} }
} }
#endif // GTEST_USE_OWN_FLAGFILE_FLAG_ #endif // GTEST_USE_OWN_FLAGFILE_FLAG_
...@@ -6758,7 +6682,7 @@ void InitGoogleTestImpl(int* argc, CharType** argv) { ...@@ -6758,7 +6682,7 @@ void InitGoogleTestImpl(int* argc, CharType** argv) {
void InitGoogleTest(int* argc, char** argv) { void InitGoogleTest(int* argc, char** argv) {
#if defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_) #if defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_)
GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_(argc, argv); GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_(argc, argv);
#else // defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_) #else // defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_)
internal::InitGoogleTestImpl(argc, argv); internal::InitGoogleTestImpl(argc, argv);
#endif // defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_) #endif // defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_)
} }
...@@ -6768,7 +6692,7 @@ void InitGoogleTest(int* argc, char** argv) { ...@@ -6768,7 +6692,7 @@ void InitGoogleTest(int* argc, char** argv) {
void InitGoogleTest(int* argc, wchar_t** argv) { void InitGoogleTest(int* argc, wchar_t** argv) {
#if defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_) #if defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_)
GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_(argc, argv); GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_(argc, argv);
#else // defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_) #else // defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_)
internal::InitGoogleTestImpl(argc, argv); internal::InitGoogleTestImpl(argc, argv);
#endif // defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_) #endif // defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_)
} }
...@@ -6784,7 +6708,7 @@ void InitGoogleTest() { ...@@ -6784,7 +6708,7 @@ void InitGoogleTest() {
#if defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_) #if defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_)
GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_(&argc, argv); GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_(&argc, argv);
#else // defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_) #else // defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_)
internal::InitGoogleTestImpl(&argc, argv); internal::InitGoogleTestImpl(&argc, argv);
#endif // defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_) #endif // defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_)
} }
...@@ -6836,8 +6760,7 @@ void ScopedTrace::PushTrace(const char* file, int line, std::string message) { ...@@ -6836,8 +6760,7 @@ void ScopedTrace::PushTrace(const char* file, int line, std::string message) {
} }
// Pops the info pushed by the c'tor. // Pops the info pushed by the c'tor.
ScopedTrace::~ScopedTrace() ScopedTrace::~ScopedTrace() GTEST_LOCK_EXCLUDED_(&UnitTest::mutex_) {
GTEST_LOCK_EXCLUDED_(&UnitTest::mutex_) {
UnitTest::GetInstance()->PopGTestTrace(); UnitTest::GetInstance()->PopGTestTrace();
} }
......
...@@ -28,15 +28,14 @@ ...@@ -28,15 +28,14 @@
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include <cstdio> #include <cstdio>
#include "gtest/gtest.h" #include "gtest/gtest.h"
#if GTEST_OS_ESP8266 || GTEST_OS_ESP32 #if GTEST_OS_ESP8266 || GTEST_OS_ESP32
#if GTEST_OS_ESP8266 #if GTEST_OS_ESP8266
extern "C" { extern "C" {
#endif #endif
void setup() { void setup() { testing::InitGoogleTest(); }
testing::InitGoogleTest();
}
void loop() { RUN_ALL_TESTS(); } void loop() { RUN_ALL_TESTS(); }
......
...@@ -27,7 +27,6 @@ ...@@ -27,7 +27,6 @@
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// Unit test for Google Test's break-on-failure mode. // Unit test for Google Test's break-on-failure mode.
// //
// A user can ask Google Test to seg-fault when an assertion fails, using // A user can ask Google Test to seg-fault when an assertion fails, using
...@@ -41,34 +40,32 @@ ...@@ -41,34 +40,32 @@
#include "gtest/gtest.h" #include "gtest/gtest.h"
#if GTEST_OS_WINDOWS #if GTEST_OS_WINDOWS
# include <windows.h> #include <stdlib.h>
# include <stdlib.h> #include <windows.h>
#endif #endif
namespace { namespace {
// A test that's expected to fail. // A test that's expected to fail.
TEST(Foo, Bar) { TEST(Foo, Bar) { EXPECT_EQ(2, 3); }
EXPECT_EQ(2, 3);
}
#if GTEST_HAS_SEH && !GTEST_OS_WINDOWS_MOBILE #if GTEST_HAS_SEH && !GTEST_OS_WINDOWS_MOBILE
// On Windows Mobile global exception handlers are not supported. // On Windows Mobile global exception handlers are not supported.
LONG WINAPI ExitWithExceptionCode( LONG WINAPI
struct _EXCEPTION_POINTERS* exception_pointers) { ExitWithExceptionCode(struct _EXCEPTION_POINTERS* exception_pointers) {
exit(exception_pointers->ExceptionRecord->ExceptionCode); exit(exception_pointers->ExceptionRecord->ExceptionCode);
} }
#endif #endif
} // namespace } // namespace
int main(int argc, char **argv) { int main(int argc, char** argv) {
#if GTEST_OS_WINDOWS #if GTEST_OS_WINDOWS
// Suppresses display of the Windows error dialog upon encountering // Suppresses display of the Windows error dialog upon encountering
// a general protection fault (segment violation). // a general protection fault (segment violation).
SetErrorMode(SEM_NOGPFAULTERRORBOX | SEM_FAILCRITICALERRORS); SetErrorMode(SEM_NOGPFAULTERRORBOX | SEM_FAILCRITICALERRORS);
# if GTEST_HAS_SEH && !GTEST_OS_WINDOWS_MOBILE #if GTEST_HAS_SEH && !GTEST_OS_WINDOWS_MOBILE
// The default unhandled exception filter does not always exit // The default unhandled exception filter does not always exit
// with the exception code as exit code - for example it exits with // with the exception code as exit code - for example it exits with
...@@ -78,7 +75,7 @@ int main(int argc, char **argv) { ...@@ -78,7 +75,7 @@ int main(int argc, char **argv) {
// exceptions. // exceptions.
SetUnhandledExceptionFilter(ExitWithExceptionCode); SetUnhandledExceptionFilter(ExitWithExceptionCode);
# endif #endif
#endif // GTEST_OS_WINDOWS #endif // GTEST_OS_WINDOWS
testing::InitGoogleTest(&argc, argv); testing::InitGoogleTest(&argc, argv);
......
...@@ -32,18 +32,18 @@ ...@@ -32,18 +32,18 @@
// exceptions, and the output is verified by // exceptions, and the output is verified by
// googletest-catch-exceptions-test.py. // googletest-catch-exceptions-test.py.
#include <stdio.h> // NOLINT #include <stdio.h> // NOLINT
#include <stdlib.h> // For exit(). #include <stdlib.h> // For exit().
#include "gtest/gtest.h" #include "gtest/gtest.h"
#if GTEST_HAS_SEH #if GTEST_HAS_SEH
# include <windows.h> #include <windows.h>
#endif #endif
#if GTEST_HAS_EXCEPTIONS #if GTEST_HAS_EXCEPTIONS
# include <exception> // For set_terminate(). #include <exception> // For set_terminate().
# include <stdexcept> #include <stdexcept>
#endif #endif
using testing::Test; using testing::Test;
...@@ -93,9 +93,7 @@ class SehExceptionInTearDownTest : public Test { ...@@ -93,9 +93,7 @@ class SehExceptionInTearDownTest : public Test {
TEST_F(SehExceptionInTearDownTest, ThrowsExceptionInTearDown) {} TEST_F(SehExceptionInTearDownTest, ThrowsExceptionInTearDown) {}
TEST(SehExceptionTest, ThrowsSehException) { TEST(SehExceptionTest, ThrowsSehException) { RaiseException(42, 0, 0, NULL); }
RaiseException(42, 0, 0, NULL);
}
#endif // GTEST_HAS_SEH #endif // GTEST_HAS_SEH
...@@ -269,9 +267,7 @@ TEST_F(CxxExceptionInTestBodyTest, ThrowsStdCxxException) { ...@@ -269,9 +267,7 @@ TEST_F(CxxExceptionInTestBodyTest, ThrowsStdCxxException) {
throw std::runtime_error("Standard C++ exception"); throw std::runtime_error("Standard C++ exception");
} }
TEST(CxxExceptionTest, ThrowsNonStdCxxException) { TEST(CxxExceptionTest, ThrowsNonStdCxxException) { throw "C-string"; }
throw "C-string";
}
// This terminate handler aborts the program using exit() rather than abort(). // This terminate handler aborts the program using exit() rather than abort().
// This avoids showing pop-ups on Windows systems and core dumps on Unix-like // This avoids showing pop-ups on Windows systems and core dumps on Unix-like
......
...@@ -27,7 +27,6 @@ ...@@ -27,7 +27,6 @@
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// A helper program for testing how Google Test determines whether to use // A helper program for testing how Google Test determines whether to use
// colors in the output. It prints "YES" and returns 1 if Google Test // colors in the output. It prints "YES" and returns 1 if Google Test
// decides to use colors, and prints "NO" and returns 0 otherwise. // decides to use colors, and prints "NO" and returns 0 otherwise.
...@@ -43,8 +42,7 @@ using testing::internal::ShouldUseColor; ...@@ -43,8 +42,7 @@ using testing::internal::ShouldUseColor;
// created before main() is entered, and thus that ShouldUseColor() // created before main() is entered, and thus that ShouldUseColor()
// works the same way as in a real Google-Test-based test. We don't actual // works the same way as in a real Google-Test-based test. We don't actual
// run the TEST itself. // run the TEST itself.
TEST(GTestColorTest, Dummy) { TEST(GTestColorTest, Dummy) {}
}
int main(int argc, char** argv) { int main(int argc, char** argv) {
testing::InitGoogleTest(&argc, argv); testing::InitGoogleTest(&argc, argv);
......
...@@ -31,7 +31,6 @@ ...@@ -31,7 +31,6 @@
// Tests for death tests. // Tests for death tests.
#include "gtest/gtest-death-test.h" #include "gtest/gtest-death-test.h"
#include "gtest/gtest.h" #include "gtest/gtest.h"
#include "gtest/internal/gtest-filepath.h" #include "gtest/internal/gtest-filepath.h"
...@@ -40,25 +39,25 @@ using testing::internal::AlwaysTrue; ...@@ -40,25 +39,25 @@ using testing::internal::AlwaysTrue;
#if GTEST_HAS_DEATH_TEST #if GTEST_HAS_DEATH_TEST
# if GTEST_OS_WINDOWS #if GTEST_OS_WINDOWS
# include <fcntl.h> // For O_BINARY #include <direct.h> // For chdir().
# include <direct.h> // For chdir(). #include <fcntl.h> // For O_BINARY
# include <io.h> #include <io.h>
# else #else
# include <unistd.h> #include <sys/wait.h> // For waitpid.
# include <sys/wait.h> // For waitpid. #include <unistd.h>
# endif // GTEST_OS_WINDOWS #endif // GTEST_OS_WINDOWS
# include <limits.h> #include <limits.h>
# include <signal.h> #include <signal.h>
# include <stdio.h> #include <stdio.h>
# if GTEST_OS_LINUX #if GTEST_OS_LINUX
# include <sys/time.h> #include <sys/time.h>
# endif // GTEST_OS_LINUX #endif // GTEST_OS_LINUX
# include "gtest/gtest-spi.h" #include "gtest/gtest-spi.h"
# include "src/gtest-internal-inl.h" #include "src/gtest-internal-inl.h"
namespace posix = ::testing::internal::posix; namespace posix = ::testing::internal::posix;
...@@ -90,6 +89,7 @@ class ReplaceDeathTestFactory { ...@@ -90,6 +89,7 @@ class ReplaceDeathTestFactory {
unit_test_impl_->death_test_factory_.release(); unit_test_impl_->death_test_factory_.release();
unit_test_impl_->death_test_factory_.reset(old_factory_); unit_test_impl_->death_test_factory_.reset(old_factory_);
} }
private: private:
// Prevents copying ReplaceDeathTestFactory objects. // Prevents copying ReplaceDeathTestFactory objects.
ReplaceDeathTestFactory(const ReplaceDeathTestFactory&); ReplaceDeathTestFactory(const ReplaceDeathTestFactory&);
...@@ -116,8 +116,7 @@ void DieWithMessage(const ::std::string& message) { ...@@ -116,8 +116,7 @@ void DieWithMessage(const ::std::string& message) {
// Some compilers can recognize that _exit() never returns and issue the // Some compilers can recognize that _exit() never returns and issue the
// 'unreachable code' warning for code following this function, unless // 'unreachable code' warning for code following this function, unless
// fooled by a fake condition. // fooled by a fake condition.
if (AlwaysTrue()) if (AlwaysTrue()) _exit(1);
_exit(1);
} }
void DieInside(const ::std::string& function) { void DieInside(const ::std::string& function) {
...@@ -137,8 +136,7 @@ class TestForDeathTest : public testing::Test { ...@@ -137,8 +136,7 @@ class TestForDeathTest : public testing::Test {
// A method of the test fixture that may die. // A method of the test fixture that may die.
void MemberFunction() { void MemberFunction() {
if (should_die_) if (should_die_) DieInside("MemberFunction");
DieInside("MemberFunction");
} }
// True if and only if MemberFunction() should die. // True if and only if MemberFunction() should die.
...@@ -153,8 +151,7 @@ class MayDie { ...@@ -153,8 +151,7 @@ class MayDie {
// A member function that may die. // A member function that may die.
void MemberFunction() const { void MemberFunction() const {
if (should_die_) if (should_die_) DieInside("MayDie::MemberFunction");
DieInside("MayDie::MemberFunction");
} }
private: private:
...@@ -173,8 +170,7 @@ int NonVoidFunction() { ...@@ -173,8 +170,7 @@ int NonVoidFunction() {
// A unary function that may die. // A unary function that may die.
void DieIf(bool should_die) { void DieIf(bool should_die) {
if (should_die) if (should_die) DieInside("DieIf");
DieInside("DieIf");
} }
// A binary function that may die. // A binary function that may die.
...@@ -195,16 +191,16 @@ void DeathTestSubroutine() { ...@@ -195,16 +191,16 @@ void DeathTestSubroutine() {
int DieInDebugElse12(int* sideeffect) { int DieInDebugElse12(int* sideeffect) {
if (sideeffect) *sideeffect = 12; if (sideeffect) *sideeffect = 12;
# ifndef NDEBUG #ifndef NDEBUG
DieInside("DieInDebugElse12"); DieInside("DieInDebugElse12");
# endif // NDEBUG #endif // NDEBUG
return 12; return 12;
} }
# if GTEST_OS_WINDOWS #if GTEST_OS_WINDOWS
// Death in dbg due to Windows CRT assertion failure, not opt. // Death in dbg due to Windows CRT assertion failure, not opt.
int DieInCRTDebugElse12(int* sideeffect) { int DieInCRTDebugElse12(int* sideeffect) {
...@@ -224,7 +220,7 @@ int DieInCRTDebugElse12(int* sideeffect) { ...@@ -224,7 +220,7 @@ int DieInCRTDebugElse12(int* sideeffect) {
#endif // GTEST_OS_WINDOWS #endif // GTEST_OS_WINDOWS
# if GTEST_OS_WINDOWS || GTEST_OS_FUCHSIA #if GTEST_OS_WINDOWS || GTEST_OS_FUCHSIA
// Tests the ExitedWithCode predicate. // Tests the ExitedWithCode predicate.
TEST(ExitStatusPredicateTest, ExitedWithCode) { TEST(ExitStatusPredicateTest, ExitedWithCode) {
...@@ -237,7 +233,7 @@ TEST(ExitStatusPredicateTest, ExitedWithCode) { ...@@ -237,7 +233,7 @@ TEST(ExitStatusPredicateTest, ExitedWithCode) {
EXPECT_FALSE(testing::ExitedWithCode(1)(0)); EXPECT_FALSE(testing::ExitedWithCode(1)(0));
} }
# else #else
// Returns the exit status of a process that calls _exit(2) with a // Returns the exit status of a process that calls _exit(2) with a
// given exit code. This is a helper function for the // given exit code. This is a helper function for the
...@@ -270,14 +266,14 @@ static int KilledExitStatus(int signum) { ...@@ -270,14 +266,14 @@ static int KilledExitStatus(int signum) {
// Tests the ExitedWithCode predicate. // Tests the ExitedWithCode predicate.
TEST(ExitStatusPredicateTest, ExitedWithCode) { TEST(ExitStatusPredicateTest, ExitedWithCode) {
const int status0 = NormalExitStatus(0); const int status0 = NormalExitStatus(0);
const int status1 = NormalExitStatus(1); const int status1 = NormalExitStatus(1);
const int status42 = NormalExitStatus(42); const int status42 = NormalExitStatus(42);
const testing::ExitedWithCode pred0(0); const testing::ExitedWithCode pred0(0);
const testing::ExitedWithCode pred1(1); const testing::ExitedWithCode pred1(1);
const testing::ExitedWithCode pred42(42); const testing::ExitedWithCode pred42(42);
EXPECT_PRED1(pred0, status0); EXPECT_PRED1(pred0, status0);
EXPECT_PRED1(pred1, status1); EXPECT_PRED1(pred1, status1);
EXPECT_PRED1(pred42, status42); EXPECT_PRED1(pred42, status42);
EXPECT_FALSE(pred0(status1)); EXPECT_FALSE(pred0(status1));
EXPECT_FALSE(pred42(status0)); EXPECT_FALSE(pred42(status0));
...@@ -296,7 +292,7 @@ TEST(ExitStatusPredicateTest, KilledBySignal) { ...@@ -296,7 +292,7 @@ TEST(ExitStatusPredicateTest, KilledBySignal) {
EXPECT_FALSE(pred_kill(status_segv)); EXPECT_FALSE(pred_kill(status_segv));
} }
# endif // GTEST_OS_WINDOWS || GTEST_OS_FUCHSIA #endif // GTEST_OS_WINDOWS || GTEST_OS_FUCHSIA
// The following code intentionally tests a suboptimal syntax. // The following code intentionally tests a suboptimal syntax.
#ifdef __GNUC__ #ifdef __GNUC__
...@@ -320,8 +316,7 @@ TEST_F(TestForDeathTest, SingleStatement) { ...@@ -320,8 +316,7 @@ TEST_F(TestForDeathTest, SingleStatement) {
// doesn't expand into an "if" statement without an "else" // doesn't expand into an "if" statement without an "else"
; ;
if (AlwaysFalse()) if (AlwaysFalse()) ASSERT_DEATH(return, "") << "did not die";
ASSERT_DEATH(return, "") << "did not die";
if (AlwaysFalse()) if (AlwaysFalse())
; ;
...@@ -332,7 +327,7 @@ TEST_F(TestForDeathTest, SingleStatement) { ...@@ -332,7 +327,7 @@ TEST_F(TestForDeathTest, SingleStatement) {
#pragma GCC diagnostic pop #pragma GCC diagnostic pop
#endif #endif
# if GTEST_USES_PCRE #if GTEST_USES_PCRE
void DieWithEmbeddedNul() { void DieWithEmbeddedNul() {
fprintf(stderr, "Hello%cmy null world.\n", '\0'); fprintf(stderr, "Hello%cmy null world.\n", '\0');
...@@ -347,7 +342,7 @@ TEST_F(TestForDeathTest, EmbeddedNulInMessage) { ...@@ -347,7 +342,7 @@ TEST_F(TestForDeathTest, EmbeddedNulInMessage) {
ASSERT_DEATH(DieWithEmbeddedNul(), "my null world"); ASSERT_DEATH(DieWithEmbeddedNul(), "my null world");
} }
# endif // GTEST_USES_PCRE #endif // GTEST_USES_PCRE
// Tests that death test macros expand to code which interacts well with switch // Tests that death test macros expand to code which interacts well with switch
// statements. // statements.
...@@ -357,12 +352,12 @@ TEST_F(TestForDeathTest, SwitchStatement) { ...@@ -357,12 +352,12 @@ TEST_F(TestForDeathTest, SwitchStatement) {
GTEST_DISABLE_MSC_WARNINGS_PUSH_(4065) GTEST_DISABLE_MSC_WARNINGS_PUSH_(4065)
switch (0) switch (0)
default: default:
ASSERT_DEATH(_exit(1), "") << "exit in default switch handler"; ASSERT_DEATH(_exit(1), "") << "exit in default switch handler";
switch (0) switch (0)
case 0: case 0:
EXPECT_DEATH(_exit(1), "") << "exit in switch case"; EXPECT_DEATH(_exit(1), "") << "exit in switch case";
GTEST_DISABLE_MSC_WARNINGS_POP_() GTEST_DISABLE_MSC_WARNINGS_POP_()
} }
...@@ -396,8 +391,9 @@ TEST_F(TestForDeathTest, FastDeathTestInChangedDir) { ...@@ -396,8 +391,9 @@ TEST_F(TestForDeathTest, FastDeathTestInChangedDir) {
ASSERT_DEATH(_exit(1), ""); ASSERT_DEATH(_exit(1), "");
} }
# if GTEST_OS_LINUX #if GTEST_OS_LINUX
void SigprofAction(int, siginfo_t*, void*) { /* no op */ } void SigprofAction(int, siginfo_t*, void*) { /* no op */
}
// Sets SIGPROF action and ITIMER_PROF timer (interval: 1ms). // Sets SIGPROF action and ITIMER_PROF timer (interval: 1ms).
void SetSigprofActionAndTimer() { void SetSigprofActionAndTimer() {
...@@ -448,7 +444,7 @@ TEST_F(TestForDeathTest, ThreadSafeSigprofActionSet) { ...@@ -448,7 +444,7 @@ TEST_F(TestForDeathTest, ThreadSafeSigprofActionSet) {
DisableSigprofActionAndTimer(&old_signal_action); DisableSigprofActionAndTimer(&old_signal_action);
EXPECT_TRUE(old_signal_action.sa_sigaction == SigprofAction); EXPECT_TRUE(old_signal_action.sa_sigaction == SigprofAction);
} }
# endif // GTEST_OS_LINUX #endif // GTEST_OS_LINUX
// Repeats a representative sample of death tests in the "threadsafe" style: // Repeats a representative sample of death tests in the "threadsafe" style:
...@@ -487,13 +483,11 @@ TEST_F(TestForDeathTest, MixedStyles) { ...@@ -487,13 +483,11 @@ TEST_F(TestForDeathTest, MixedStyles) {
EXPECT_DEATH(_exit(1), ""); EXPECT_DEATH(_exit(1), "");
} }
# if GTEST_HAS_CLONE && GTEST_HAS_PTHREAD #if GTEST_HAS_CLONE && GTEST_HAS_PTHREAD
bool pthread_flag; bool pthread_flag;
void SetPthreadFlag() { void SetPthreadFlag() { pthread_flag = true; }
pthread_flag = true;
}
TEST_F(TestForDeathTest, DoesNotExecuteAtforkHooks) { TEST_F(TestForDeathTest, DoesNotExecuteAtforkHooks) {
if (!GTEST_FLAG_GET(death_test_use_fork)) { if (!GTEST_FLAG_GET(death_test_use_fork)) {
...@@ -505,7 +499,7 @@ TEST_F(TestForDeathTest, DoesNotExecuteAtforkHooks) { ...@@ -505,7 +499,7 @@ TEST_F(TestForDeathTest, DoesNotExecuteAtforkHooks) {
} }
} }
# endif // GTEST_HAS_CLONE && GTEST_HAS_PTHREAD #endif // GTEST_HAS_CLONE && GTEST_HAS_PTHREAD
// Tests that a method of another class can be used in a death test. // Tests that a method of another class can be used in a death test.
TEST_F(TestForDeathTest, MethodOfAnotherClass) { TEST_F(TestForDeathTest, MethodOfAnotherClass) {
...@@ -527,7 +521,7 @@ TEST_F(TestForDeathTest, AcceptsAnythingConvertibleToRE) { ...@@ -527,7 +521,7 @@ TEST_F(TestForDeathTest, AcceptsAnythingConvertibleToRE) {
const testing::internal::RE regex(regex_c_str); const testing::internal::RE regex(regex_c_str);
EXPECT_DEATH(GlobalFunction(), regex); EXPECT_DEATH(GlobalFunction(), regex);
# if !GTEST_USES_PCRE #if !GTEST_USES_PCRE
const ::std::string regex_std_str(regex_c_str); const ::std::string regex_std_str(regex_c_str);
EXPECT_DEATH(GlobalFunction(), regex_std_str); EXPECT_DEATH(GlobalFunction(), regex_std_str);
...@@ -536,7 +530,7 @@ TEST_F(TestForDeathTest, AcceptsAnythingConvertibleToRE) { ...@@ -536,7 +530,7 @@ TEST_F(TestForDeathTest, AcceptsAnythingConvertibleToRE) {
// lifetime extension of the pointer is not sufficient. // lifetime extension of the pointer is not sufficient.
EXPECT_DEATH(GlobalFunction(), ::std::string(regex_c_str).c_str()); EXPECT_DEATH(GlobalFunction(), ::std::string(regex_c_str).c_str());
# endif // !GTEST_USES_PCRE #endif // !GTEST_USES_PCRE
} }
// Tests that a non-void function can be used in a death test. // Tests that a non-void function can be used in a death test.
...@@ -551,9 +545,7 @@ TEST_F(TestForDeathTest, FunctionWithParameter) { ...@@ -551,9 +545,7 @@ TEST_F(TestForDeathTest, FunctionWithParameter) {
} }
// Tests that ASSERT_DEATH can be used outside a TEST, TEST_F, or test fixture. // Tests that ASSERT_DEATH can be used outside a TEST, TEST_F, or test fixture.
TEST_F(TestForDeathTest, OutsideFixture) { TEST_F(TestForDeathTest, OutsideFixture) { DeathTestSubroutine(); }
DeathTestSubroutine();
}
// Tests that death tests can be done inside a loop. // Tests that death tests can be done inside a loop.
TEST_F(TestForDeathTest, InsideLoop) { TEST_F(TestForDeathTest, InsideLoop) {
...@@ -564,25 +556,28 @@ TEST_F(TestForDeathTest, InsideLoop) { ...@@ -564,25 +556,28 @@ TEST_F(TestForDeathTest, InsideLoop) {
// Tests that a compound statement can be used in a death test. // Tests that a compound statement can be used in a death test.
TEST_F(TestForDeathTest, CompoundStatement) { TEST_F(TestForDeathTest, CompoundStatement) {
EXPECT_DEATH({ // NOLINT EXPECT_DEATH(
const int x = 2; { // NOLINT
const int y = x + 1; const int x = 2;
DieIfLessThan(x, y); const int y = x + 1;
}, DieIfLessThan(x, y);
"DieIfLessThan"); },
"DieIfLessThan");
} }
// Tests that code that doesn't die causes a death test to fail. // Tests that code that doesn't die causes a death test to fail.
TEST_F(TestForDeathTest, DoesNotDie) { TEST_F(TestForDeathTest, DoesNotDie) {
EXPECT_NONFATAL_FAILURE(EXPECT_DEATH(DieIf(false), "DieIf"), EXPECT_NONFATAL_FAILURE(EXPECT_DEATH(DieIf(false), "DieIf"), "failed to die");
"failed to die");
} }
// Tests that a death test fails when the error message isn't expected. // Tests that a death test fails when the error message isn't expected.
TEST_F(TestForDeathTest, ErrorMessageMismatch) { TEST_F(TestForDeathTest, ErrorMessageMismatch) {
EXPECT_NONFATAL_FAILURE({ // NOLINT EXPECT_NONFATAL_FAILURE(
EXPECT_DEATH(DieIf(true), "DieIfLessThan") << "End of death test message."; { // NOLINT
}, "died but not with expected error"); EXPECT_DEATH(DieIf(true), "DieIfLessThan")
<< "End of death test message.";
},
"died but not with expected error");
} }
// On exit, *aborted will be true if and only if the EXPECT_DEATH() // On exit, *aborted will be true if and only if the EXPECT_DEATH()
...@@ -596,19 +591,20 @@ void ExpectDeathTestHelper(bool* aborted) { ...@@ -596,19 +591,20 @@ void ExpectDeathTestHelper(bool* aborted) {
// Tests that EXPECT_DEATH doesn't abort the test on failure. // Tests that EXPECT_DEATH doesn't abort the test on failure.
TEST_F(TestForDeathTest, EXPECT_DEATH) { TEST_F(TestForDeathTest, EXPECT_DEATH) {
bool aborted = true; bool aborted = true;
EXPECT_NONFATAL_FAILURE(ExpectDeathTestHelper(&aborted), EXPECT_NONFATAL_FAILURE(ExpectDeathTestHelper(&aborted), "failed to die");
"failed to die");
EXPECT_FALSE(aborted); EXPECT_FALSE(aborted);
} }
// Tests that ASSERT_DEATH does abort the test on failure. // Tests that ASSERT_DEATH does abort the test on failure.
TEST_F(TestForDeathTest, ASSERT_DEATH) { TEST_F(TestForDeathTest, ASSERT_DEATH) {
static bool aborted; static bool aborted;
EXPECT_FATAL_FAILURE({ // NOLINT EXPECT_FATAL_FAILURE(
aborted = true; { // NOLINT
ASSERT_DEATH(DieIf(false), "DieIf"); // This assertion should fail. aborted = true;
aborted = false; ASSERT_DEATH(DieIf(false), "DieIf"); // This assertion should fail.
}, "failed to die"); aborted = false;
},
"failed to die");
EXPECT_TRUE(aborted); EXPECT_TRUE(aborted);
} }
...@@ -653,20 +649,20 @@ TEST_F(TestForDeathTest, TestExpectDebugDeath) { ...@@ -653,20 +649,20 @@ TEST_F(TestForDeathTest, TestExpectDebugDeath) {
EXPECT_DEBUG_DEATH(DieInDebugElse12(&sideeffect), regex) EXPECT_DEBUG_DEATH(DieInDebugElse12(&sideeffect), regex)
<< "Must accept a streamed message"; << "Must accept a streamed message";
# ifdef NDEBUG #ifdef NDEBUG
// Checks that the assignment occurs in opt mode (sideeffect). // Checks that the assignment occurs in opt mode (sideeffect).
EXPECT_EQ(12, sideeffect); EXPECT_EQ(12, sideeffect);
# else #else
// Checks that the assignment does not occur in dbg mode (no sideeffect). // Checks that the assignment does not occur in dbg mode (no sideeffect).
EXPECT_EQ(0, sideeffect); EXPECT_EQ(0, sideeffect);
# endif #endif
} }
# if GTEST_OS_WINDOWS #if GTEST_OS_WINDOWS
// https://docs.microsoft.com/en-us/cpp/c-runtime-library/reference/crtsetreportmode // https://docs.microsoft.com/en-us/cpp/c-runtime-library/reference/crtsetreportmode
// In debug mode, the calls to _CrtSetReportMode and _CrtSetReportFile enable // In debug mode, the calls to _CrtSetReportMode and _CrtSetReportFile enable
...@@ -682,7 +678,7 @@ TEST_F(TestForDeathTest, CRTDebugDeath) { ...@@ -682,7 +678,7 @@ TEST_F(TestForDeathTest, CRTDebugDeath) {
} }
#endif // _DEBUG #endif // _DEBUG
# endif // GTEST_OS_WINDOWS #endif // GTEST_OS_WINDOWS
// Tests that ASSERT_DEBUG_DEATH works as expected, that is, you can stream a // Tests that ASSERT_DEBUG_DEATH works as expected, that is, you can stream a
// message to it, and in debug mode it: // message to it, and in debug mode it:
...@@ -697,20 +693,20 @@ TEST_F(TestForDeathTest, TestAssertDebugDeath) { ...@@ -697,20 +693,20 @@ TEST_F(TestForDeathTest, TestAssertDebugDeath) {
ASSERT_DEBUG_DEATH(DieInDebugElse12(&sideeffect), "death.*DieInDebugElse12") ASSERT_DEBUG_DEATH(DieInDebugElse12(&sideeffect), "death.*DieInDebugElse12")
<< "Must accept a streamed message"; << "Must accept a streamed message";
# ifdef NDEBUG #ifdef NDEBUG
// Checks that the assignment occurs in opt mode (sideeffect). // Checks that the assignment occurs in opt mode (sideeffect).
EXPECT_EQ(12, sideeffect); EXPECT_EQ(12, sideeffect);
# else #else
// Checks that the assignment does not occur in dbg mode (no sideeffect). // Checks that the assignment does not occur in dbg mode (no sideeffect).
EXPECT_EQ(0, sideeffect); EXPECT_EQ(0, sideeffect);
# endif #endif
} }
# ifndef NDEBUG #ifndef NDEBUG
void ExpectDebugDeathHelper(bool* aborted) { void ExpectDebugDeathHelper(bool* aborted) {
*aborted = true; *aborted = true;
...@@ -718,10 +714,11 @@ void ExpectDebugDeathHelper(bool* aborted) { ...@@ -718,10 +714,11 @@ void ExpectDebugDeathHelper(bool* aborted) {
*aborted = false; *aborted = false;
} }
# if GTEST_OS_WINDOWS #if GTEST_OS_WINDOWS
TEST(PopUpDeathTest, DoesNotShowPopUpOnAbort) { TEST(PopUpDeathTest, DoesNotShowPopUpOnAbort) {
printf("This test should be considered failing if it shows " printf(
"any pop-up dialogs.\n"); "This test should be considered failing if it shows "
"any pop-up dialogs.\n");
fflush(stdout); fflush(stdout);
EXPECT_DEATH( EXPECT_DEATH(
...@@ -731,7 +728,7 @@ TEST(PopUpDeathTest, DoesNotShowPopUpOnAbort) { ...@@ -731,7 +728,7 @@ TEST(PopUpDeathTest, DoesNotShowPopUpOnAbort) {
}, },
""); "");
} }
# endif // GTEST_OS_WINDOWS #endif // GTEST_OS_WINDOWS
// Tests that EXPECT_DEBUG_DEATH in debug mode does not abort // Tests that EXPECT_DEBUG_DEATH in debug mode does not abort
// the function. // the function.
...@@ -822,42 +819,44 @@ TEST_F(TestForDeathTest, AssertDebugDeathAborts10) { ...@@ -822,42 +819,44 @@ TEST_F(TestForDeathTest, AssertDebugDeathAborts10) {
EXPECT_TRUE(aborted); EXPECT_TRUE(aborted);
} }
# endif // _NDEBUG #endif // _NDEBUG
// Tests the *_EXIT family of macros, using a variety of predicates. // Tests the *_EXIT family of macros, using a variety of predicates.
static void TestExitMacros() { static void TestExitMacros() {
EXPECT_EXIT(_exit(1), testing::ExitedWithCode(1), ""); EXPECT_EXIT(_exit(1), testing::ExitedWithCode(1), "");
ASSERT_EXIT(_exit(42), testing::ExitedWithCode(42), ""); ASSERT_EXIT(_exit(42), testing::ExitedWithCode(42), "");
# if GTEST_OS_WINDOWS #if GTEST_OS_WINDOWS
// Of all signals effects on the process exit code, only those of SIGABRT // Of all signals effects on the process exit code, only those of SIGABRT
// are documented on Windows. // are documented on Windows.
// See https://msdn.microsoft.com/en-us/query-bi/m/dwwzkt4c. // See https://msdn.microsoft.com/en-us/query-bi/m/dwwzkt4c.
EXPECT_EXIT(raise(SIGABRT), testing::ExitedWithCode(3), "") << "b_ar"; EXPECT_EXIT(raise(SIGABRT), testing::ExitedWithCode(3), "") << "b_ar";
# elif !GTEST_OS_FUCHSIA #elif !GTEST_OS_FUCHSIA
// Fuchsia has no unix signals. // Fuchsia has no unix signals.
EXPECT_EXIT(raise(SIGKILL), testing::KilledBySignal(SIGKILL), "") << "foo"; EXPECT_EXIT(raise(SIGKILL), testing::KilledBySignal(SIGKILL), "") << "foo";
ASSERT_EXIT(raise(SIGUSR2), testing::KilledBySignal(SIGUSR2), "") << "bar"; ASSERT_EXIT(raise(SIGUSR2), testing::KilledBySignal(SIGUSR2), "") << "bar";
EXPECT_FATAL_FAILURE({ // NOLINT EXPECT_FATAL_FAILURE(
ASSERT_EXIT(_exit(0), testing::KilledBySignal(SIGSEGV), "") { // NOLINT
<< "This failure is expected, too."; ASSERT_EXIT(_exit(0), testing::KilledBySignal(SIGSEGV), "")
}, "This failure is expected, too."); << "This failure is expected, too.";
},
"This failure is expected, too.");
# endif // GTEST_OS_WINDOWS #endif // GTEST_OS_WINDOWS
EXPECT_NONFATAL_FAILURE({ // NOLINT EXPECT_NONFATAL_FAILURE(
EXPECT_EXIT(raise(SIGSEGV), testing::ExitedWithCode(0), "") { // NOLINT
<< "This failure is expected."; EXPECT_EXIT(raise(SIGSEGV), testing::ExitedWithCode(0), "")
}, "This failure is expected."); << "This failure is expected.";
},
"This failure is expected.");
} }
TEST_F(TestForDeathTest, ExitMacros) { TEST_F(TestForDeathTest, ExitMacros) { TestExitMacros(); }
TestExitMacros();
}
TEST_F(TestForDeathTest, ExitMacrosUsingFork) { TEST_F(TestForDeathTest, ExitMacrosUsingFork) {
GTEST_FLAG_SET(death_test_use_fork, true); GTEST_FLAG_SET(death_test_use_fork, true);
...@@ -866,39 +865,40 @@ TEST_F(TestForDeathTest, ExitMacrosUsingFork) { ...@@ -866,39 +865,40 @@ TEST_F(TestForDeathTest, ExitMacrosUsingFork) {
TEST_F(TestForDeathTest, InvalidStyle) { TEST_F(TestForDeathTest, InvalidStyle) {
GTEST_FLAG_SET(death_test_style, "rococo"); GTEST_FLAG_SET(death_test_style, "rococo");
EXPECT_NONFATAL_FAILURE({ // NOLINT EXPECT_NONFATAL_FAILURE(
EXPECT_DEATH(_exit(0), "") << "This failure is expected."; { // NOLINT
}, "This failure is expected."); EXPECT_DEATH(_exit(0), "") << "This failure is expected.";
},
"This failure is expected.");
} }
TEST_F(TestForDeathTest, DeathTestFailedOutput) { TEST_F(TestForDeathTest, DeathTestFailedOutput) {
GTEST_FLAG_SET(death_test_style, "fast"); GTEST_FLAG_SET(death_test_style, "fast");
EXPECT_NONFATAL_FAILURE( EXPECT_NONFATAL_FAILURE(
EXPECT_DEATH(DieWithMessage("death\n"), EXPECT_DEATH(DieWithMessage("death\n"), "expected message"),
"expected message"),
"Actual msg:\n" "Actual msg:\n"
"[ DEATH ] death\n"); "[ DEATH ] death\n");
} }
TEST_F(TestForDeathTest, DeathTestUnexpectedReturnOutput) { TEST_F(TestForDeathTest, DeathTestUnexpectedReturnOutput) {
GTEST_FLAG_SET(death_test_style, "fast"); GTEST_FLAG_SET(death_test_style, "fast");
EXPECT_NONFATAL_FAILURE( EXPECT_NONFATAL_FAILURE(EXPECT_DEATH(
EXPECT_DEATH({ {
fprintf(stderr, "returning\n"); fprintf(stderr, "returning\n");
fflush(stderr); fflush(stderr);
return; return;
}, ""), },
" Result: illegal return in test statement.\n" ""),
" Error msg:\n" " Result: illegal return in test statement.\n"
"[ DEATH ] returning\n"); " Error msg:\n"
"[ DEATH ] returning\n");
} }
TEST_F(TestForDeathTest, DeathTestBadExitCodeOutput) { TEST_F(TestForDeathTest, DeathTestBadExitCodeOutput) {
GTEST_FLAG_SET(death_test_style, "fast"); GTEST_FLAG_SET(death_test_style, "fast");
EXPECT_NONFATAL_FAILURE( EXPECT_NONFATAL_FAILURE(
EXPECT_EXIT(DieWithMessage("exiting with rc 1\n"), EXPECT_EXIT(DieWithMessage("exiting with rc 1\n"),
testing::ExitedWithCode(3), testing::ExitedWithCode(3), "expected message"),
"expected message"),
" Result: died but not with expected exit code:\n" " Result: died but not with expected exit code:\n"
" Exited with exit status 1\n" " Exited with exit status 1\n"
"Actual msg:\n" "Actual msg:\n"
...@@ -931,8 +931,8 @@ class MockDeathTestFactory : public DeathTestFactory { ...@@ -931,8 +931,8 @@ class MockDeathTestFactory : public DeathTestFactory {
int line, DeathTest** test) override; int line, DeathTest** test) override;
// Sets the parameters for subsequent calls to Create. // Sets the parameters for subsequent calls to Create.
void SetParameters(bool create, DeathTest::TestRole role, void SetParameters(bool create, DeathTest::TestRole role, int status,
int status, bool passed); bool passed);
// Accessors. // Accessors.
int AssumeRoleCalls() const { return assume_role_calls_; } int AssumeRoleCalls() const { return assume_role_calls_; }
...@@ -974,17 +974,15 @@ class MockDeathTestFactory : public DeathTestFactory { ...@@ -974,17 +974,15 @@ class MockDeathTestFactory : public DeathTestFactory {
bool test_deleted_; bool test_deleted_;
}; };
// A DeathTest implementation useful in testing. It returns values set // A DeathTest implementation useful in testing. It returns values set
// at its creation from its various inherited DeathTest methods, and // at its creation from its various inherited DeathTest methods, and
// reports calls to those methods to its parent MockDeathTestFactory // reports calls to those methods to its parent MockDeathTestFactory
// object. // object.
class MockDeathTest : public DeathTest { class MockDeathTest : public DeathTest {
public: public:
MockDeathTest(MockDeathTestFactory *parent, MockDeathTest(MockDeathTestFactory* parent, TestRole role, int status,
TestRole role, int status, bool passed) : bool passed)
parent_(parent), role_(role), status_(status), passed_(passed) { : parent_(parent), role_(role), status_(status), passed_(passed) {}
}
~MockDeathTest() override { parent_->test_deleted_ = true; } ~MockDeathTest() override { parent_->test_deleted_ = true; }
TestRole AssumeRole() override { TestRole AssumeRole() override {
++parent_->assume_role_calls_; ++parent_->assume_role_calls_;
...@@ -1009,7 +1007,6 @@ class MockDeathTest : public DeathTest { ...@@ -1009,7 +1007,6 @@ class MockDeathTest : public DeathTest {
const bool passed_; const bool passed_;
}; };
// MockDeathTestFactory constructor. // MockDeathTestFactory constructor.
MockDeathTestFactory::MockDeathTestFactory() MockDeathTestFactory::MockDeathTestFactory()
: create_(true), : create_(true),
...@@ -1019,13 +1016,10 @@ MockDeathTestFactory::MockDeathTestFactory() ...@@ -1019,13 +1016,10 @@ MockDeathTestFactory::MockDeathTestFactory()
assume_role_calls_(0), assume_role_calls_(0),
wait_calls_(0), wait_calls_(0),
passed_args_(), passed_args_(),
abort_args_() { abort_args_() {}
}
// Sets the parameters for subsequent calls to Create. // Sets the parameters for subsequent calls to Create.
void MockDeathTestFactory::SetParameters(bool create, void MockDeathTestFactory::SetParameters(bool create, DeathTest::TestRole role,
DeathTest::TestRole role,
int status, bool passed) { int status, bool passed) {
create_ = create; create_ = create;
role_ = role; role_ = role;
...@@ -1038,7 +1032,6 @@ void MockDeathTestFactory::SetParameters(bool create, ...@@ -1038,7 +1032,6 @@ void MockDeathTestFactory::SetParameters(bool create,
abort_args_.clear(); abort_args_.clear();
} }
// Sets test to NULL (if create_ is false) or to the address of a new // Sets test to NULL (if create_ is false) or to the address of a new
// MockDeathTest object with parameters taken from the last call // MockDeathTest object with parameters taken from the last call
// to SetParameters (if create_ is true). Always returns true. // to SetParameters (if create_ is true). Always returns true.
...@@ -1078,10 +1071,12 @@ class MacroLogicDeathTest : public testing::Test { ...@@ -1078,10 +1071,12 @@ class MacroLogicDeathTest : public testing::Test {
// test cannot be run directly from a test routine that uses a // test cannot be run directly from a test routine that uses a
// MockDeathTest, or the remainder of the routine will not be executed. // MockDeathTest, or the remainder of the routine will not be executed.
static void RunReturningDeathTest(bool* flag) { static void RunReturningDeathTest(bool* flag) {
ASSERT_DEATH({ // NOLINT ASSERT_DEATH(
*flag = true; { // NOLINT
return; *flag = true;
}, ""); return;
},
"");
} }
}; };
...@@ -1166,8 +1161,7 @@ TEST_F(MacroLogicDeathTest, ChildDoesNotDie) { ...@@ -1166,8 +1161,7 @@ TEST_F(MacroLogicDeathTest, ChildDoesNotDie) {
// _exit(2) is called in that case by ForkingDeathTest, but not by // _exit(2) is called in that case by ForkingDeathTest, but not by
// our MockDeathTest. // our MockDeathTest.
ASSERT_EQ(2U, factory_->AbortCalls()); ASSERT_EQ(2U, factory_->AbortCalls());
EXPECT_EQ(DeathTest::TEST_DID_NOT_DIE, EXPECT_EQ(DeathTest::TEST_DID_NOT_DIE, factory_->AbortArgument(0));
factory_->AbortArgument(0));
EXPECT_EQ(DeathTest::TEST_ENCOUNTERED_RETURN_STATEMENT, EXPECT_EQ(DeathTest::TEST_ENCOUNTERED_RETURN_STATEMENT,
factory_->AbortArgument(1)); factory_->AbortArgument(1));
EXPECT_TRUE(factory_->TestDeleted()); EXPECT_TRUE(factory_->TestDeleted());
...@@ -1183,12 +1177,16 @@ TEST(SuccessRegistrationDeathTest, NoSuccessPart) { ...@@ -1183,12 +1177,16 @@ TEST(SuccessRegistrationDeathTest, NoSuccessPart) {
TEST(StreamingAssertionsDeathTest, DeathTest) { TEST(StreamingAssertionsDeathTest, DeathTest) {
EXPECT_DEATH(_exit(1), "") << "unexpected failure"; EXPECT_DEATH(_exit(1), "") << "unexpected failure";
ASSERT_DEATH(_exit(1), "") << "unexpected failure"; ASSERT_DEATH(_exit(1), "") << "unexpected failure";
EXPECT_NONFATAL_FAILURE({ // NOLINT EXPECT_NONFATAL_FAILURE(
EXPECT_DEATH(_exit(0), "") << "expected failure"; { // NOLINT
}, "expected failure"); EXPECT_DEATH(_exit(0), "") << "expected failure";
EXPECT_FATAL_FAILURE({ // NOLINT },
ASSERT_DEATH(_exit(0), "") << "expected failure"; "expected failure");
}, "expected failure"); EXPECT_FATAL_FAILURE(
{ // NOLINT
ASSERT_DEATH(_exit(0), "") << "expected failure";
},
"expected failure");
} }
// Tests that GetLastErrnoDescription returns an empty string when the // Tests that GetLastErrnoDescription returns an empty string when the
...@@ -1200,7 +1198,7 @@ TEST(GetLastErrnoDescription, GetLastErrnoDescriptionWorks) { ...@@ -1200,7 +1198,7 @@ TEST(GetLastErrnoDescription, GetLastErrnoDescriptionWorks) {
EXPECT_STREQ("", GetLastErrnoDescription().c_str()); EXPECT_STREQ("", GetLastErrnoDescription().c_str());
} }
# if GTEST_OS_WINDOWS #if GTEST_OS_WINDOWS
TEST(AutoHandleTest, AutoHandleWorks) { TEST(AutoHandleTest, AutoHandleWorks) {
HANDLE handle = ::CreateEvent(NULL, FALSE, FALSE, NULL); HANDLE handle = ::CreateEvent(NULL, FALSE, FALSE, NULL);
ASSERT_NE(INVALID_HANDLE_VALUE, handle); ASSERT_NE(INVALID_HANDLE_VALUE, handle);
...@@ -1225,15 +1223,15 @@ TEST(AutoHandleTest, AutoHandleWorks) { ...@@ -1225,15 +1223,15 @@ TEST(AutoHandleTest, AutoHandleWorks) {
testing::internal::AutoHandle auto_handle2; testing::internal::AutoHandle auto_handle2;
EXPECT_EQ(INVALID_HANDLE_VALUE, auto_handle2.Get()); EXPECT_EQ(INVALID_HANDLE_VALUE, auto_handle2.Get());
} }
# endif // GTEST_OS_WINDOWS #endif // GTEST_OS_WINDOWS
# if GTEST_OS_WINDOWS #if GTEST_OS_WINDOWS
typedef unsigned __int64 BiggestParsable; typedef unsigned __int64 BiggestParsable;
typedef signed __int64 BiggestSignedParsable; typedef signed __int64 BiggestSignedParsable;
# else #else
typedef unsigned long long BiggestParsable; typedef unsigned long long BiggestParsable;
typedef signed long long BiggestSignedParsable; typedef signed long long BiggestSignedParsable;
# endif // GTEST_OS_WINDOWS #endif // GTEST_OS_WINDOWS
// We cannot use std::numeric_limits<T>::max() as it clashes with the // We cannot use std::numeric_limits<T>::max() as it clashes with the
// max() macro defined by <windows.h>. // max() macro defined by <windows.h>.
...@@ -1324,11 +1322,11 @@ TEST(ParseNaturalNumberTest, WorksForShorterIntegers) { ...@@ -1324,11 +1322,11 @@ TEST(ParseNaturalNumberTest, WorksForShorterIntegers) {
EXPECT_EQ(123, char_result); EXPECT_EQ(123, char_result);
} }
# if GTEST_OS_WINDOWS #if GTEST_OS_WINDOWS
TEST(EnvironmentTest, HandleFitsIntoSizeT) { TEST(EnvironmentTest, HandleFitsIntoSizeT) {
ASSERT_TRUE(sizeof(HANDLE) <= sizeof(size_t)); ASSERT_TRUE(sizeof(HANDLE) <= sizeof(size_t));
} }
# endif // GTEST_OS_WINDOWS #endif // GTEST_OS_WINDOWS
// Tests that EXPECT_DEATH_IF_SUPPORTED/ASSERT_DEATH_IF_SUPPORTED trigger // Tests that EXPECT_DEATH_IF_SUPPORTED/ASSERT_DEATH_IF_SUPPORTED trigger
// failures when death tests are available on the system. // failures when death tests are available on the system.
...@@ -1346,21 +1344,25 @@ TEST(ConditionalDeathMacrosDeathTest, ExpectsDeathWhenDeathTestsAvailable) { ...@@ -1346,21 +1344,25 @@ TEST(ConditionalDeathMacrosDeathTest, ExpectsDeathWhenDeathTestsAvailable) {
TEST(InDeathTestChildDeathTest, ReportsDeathTestCorrectlyInFastStyle) { TEST(InDeathTestChildDeathTest, ReportsDeathTestCorrectlyInFastStyle) {
GTEST_FLAG_SET(death_test_style, "fast"); GTEST_FLAG_SET(death_test_style, "fast");
EXPECT_FALSE(InDeathTestChild()); EXPECT_FALSE(InDeathTestChild());
EXPECT_DEATH({ EXPECT_DEATH(
fprintf(stderr, InDeathTestChild() ? "Inside" : "Outside"); {
fflush(stderr); fprintf(stderr, InDeathTestChild() ? "Inside" : "Outside");
_exit(1); fflush(stderr);
}, "Inside"); _exit(1);
},
"Inside");
} }
TEST(InDeathTestChildDeathTest, ReportsDeathTestCorrectlyInThreadSafeStyle) { TEST(InDeathTestChildDeathTest, ReportsDeathTestCorrectlyInThreadSafeStyle) {
GTEST_FLAG_SET(death_test_style, "threadsafe"); GTEST_FLAG_SET(death_test_style, "threadsafe");
EXPECT_FALSE(InDeathTestChild()); EXPECT_FALSE(InDeathTestChild());
EXPECT_DEATH({ EXPECT_DEATH(
fprintf(stderr, InDeathTestChild() ? "Inside" : "Outside"); {
fflush(stderr); fprintf(stderr, InDeathTestChild() ? "Inside" : "Outside");
_exit(1); fflush(stderr);
}, "Inside"); _exit(1);
},
"Inside");
} }
void DieWithMessage(const char* message) { void DieWithMessage(const char* message) {
...@@ -1488,8 +1490,7 @@ TEST(ConditionalDeathMacrosSyntaxDeathTest, SingleStatement) { ...@@ -1488,8 +1490,7 @@ TEST(ConditionalDeathMacrosSyntaxDeathTest, SingleStatement) {
// doesn't expand into an "if" statement without an "else" // doesn't expand into an "if" statement without an "else"
; // NOLINT ; // NOLINT
if (AlwaysFalse()) if (AlwaysFalse()) ASSERT_DEATH_IF_SUPPORTED(return, "") << "did not die";
ASSERT_DEATH_IF_SUPPORTED(return, "") << "did not die";
if (AlwaysFalse()) if (AlwaysFalse())
; // NOLINT ; // NOLINT
...@@ -1508,21 +1509,18 @@ TEST(ConditionalDeathMacrosSyntaxDeathTest, SwitchStatement) { ...@@ -1508,21 +1509,18 @@ TEST(ConditionalDeathMacrosSyntaxDeathTest, SwitchStatement) {
GTEST_DISABLE_MSC_WARNINGS_PUSH_(4065) GTEST_DISABLE_MSC_WARNINGS_PUSH_(4065)
switch (0) switch (0)
default: default:
ASSERT_DEATH_IF_SUPPORTED(_exit(1), "") ASSERT_DEATH_IF_SUPPORTED(_exit(1), "") << "exit in default switch handler";
<< "exit in default switch handler";
switch (0) switch (0)
case 0: case 0:
EXPECT_DEATH_IF_SUPPORTED(_exit(1), "") << "exit in switch case"; EXPECT_DEATH_IF_SUPPORTED(_exit(1), "") << "exit in switch case";
GTEST_DISABLE_MSC_WARNINGS_POP_() GTEST_DISABLE_MSC_WARNINGS_POP_()
} }
// Tests that a test case whose name ends with "DeathTest" works fine // Tests that a test case whose name ends with "DeathTest" works fine
// on Windows. // on Windows.
TEST(NotADeathTest, Test) { TEST(NotADeathTest, Test) { SUCCEED(); }
SUCCEED();
}
} // namespace } // namespace
...@@ -35,15 +35,15 @@ ...@@ -35,15 +35,15 @@
#if GTEST_HAS_DEATH_TEST #if GTEST_HAS_DEATH_TEST
# if GTEST_HAS_SEH #if GTEST_HAS_SEH
# include <windows.h> // For RaiseException(). #include <windows.h> // For RaiseException().
# endif #endif
# include "gtest/gtest-spi.h" #include "gtest/gtest-spi.h"
# if GTEST_HAS_EXCEPTIONS #if GTEST_HAS_EXCEPTIONS
# include <exception> // For std::exception. #include <exception> // For std::exception.
// Tests that death tests report thrown exceptions as failures and that the // Tests that death tests report thrown exceptions as failures and that the
// exceptions do not escape death test macros. // exceptions do not escape death test macros.
...@@ -67,12 +67,11 @@ TEST(CxxExceptionDeathTest, PrintsMessageForStdExceptions) { ...@@ -67,12 +67,11 @@ TEST(CxxExceptionDeathTest, PrintsMessageForStdExceptions) {
EXPECT_NONFATAL_FAILURE(EXPECT_DEATH(throw TestException(), ""), EXPECT_NONFATAL_FAILURE(EXPECT_DEATH(throw TestException(), ""),
"exceptional message"); "exceptional message");
// Verifies that the location is mentioned in the failure text. // Verifies that the location is mentioned in the failure text.
EXPECT_NONFATAL_FAILURE(EXPECT_DEATH(throw TestException(), ""), EXPECT_NONFATAL_FAILURE(EXPECT_DEATH(throw TestException(), ""), __FILE__);
__FILE__);
} }
# endif // GTEST_HAS_EXCEPTIONS #endif // GTEST_HAS_EXCEPTIONS
# if GTEST_HAS_SEH #if GTEST_HAS_SEH
// Tests that enabling interception of SEH exceptions with the // Tests that enabling interception of SEH exceptions with the
// catch_exceptions flag does not interfere with SEH exceptions being // catch_exceptions flag does not interfere with SEH exceptions being
// treated as death by death tests. // treated as death by death tests.
...@@ -81,7 +80,7 @@ TEST(SehExceptionDeasTest, CatchExceptionsDoesNotInterfere) { ...@@ -81,7 +80,7 @@ TEST(SehExceptionDeasTest, CatchExceptionsDoesNotInterfere) {
<< "with catch_exceptions " << "with catch_exceptions "
<< (GTEST_FLAG_GET(catch_exceptions) ? "enabled" : "disabled"); << (GTEST_FLAG_GET(catch_exceptions) ? "enabled" : "disabled");
} }
# endif #endif
#endif // GTEST_HAS_DEATH_TEST #endif // GTEST_HAS_DEATH_TEST
......
...@@ -27,7 +27,6 @@ ...@@ -27,7 +27,6 @@
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// A helper program for testing that Google Test parses the environment // A helper program for testing that Google Test parses the environment
// variables correctly. // variables correctly.
...@@ -43,8 +42,7 @@ namespace testing { ...@@ -43,8 +42,7 @@ namespace testing {
// The purpose of this is to make the test more realistic by ensuring // The purpose of this is to make the test more realistic by ensuring
// that the UnitTest singleton is created before main() is entered. // that the UnitTest singleton is created before main() is entered.
// We don't actual run the TEST itself. // We don't actual run the TEST itself.
TEST(GTestEnvVarTest, Dummy) { TEST(GTestEnvVarTest, Dummy) {}
}
void PrintFlag(const char* flag) { void PrintFlag(const char* flag) {
if (strcmp(flag, "break_on_failure") == 0) { if (strcmp(flag, "break_on_failure") == 0) {
......
...@@ -27,7 +27,6 @@ ...@@ -27,7 +27,6 @@
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// Unit test for Google Test test filters. // Unit test for Google Test test filters.
// //
// A user can specify which test(s) in a Google Test program to run via // A user can specify which test(s) in a Google Test program to run via
...@@ -160,7 +159,7 @@ TEST(HasSkipTest, Test4) { FAIL() << "Expected failure."; } ...@@ -160,7 +159,7 @@ TEST(HasSkipTest, Test4) { FAIL() << "Expected failure."; }
} // namespace } // namespace
int main(int argc, char **argv) { int main(int argc, char** argv) {
::testing::InitGoogleTest(&argc, argv); ::testing::InitGoogleTest(&argc, argv);
::testing::UnitTest::GetInstance()->listeners().Append(new MyTestListener()); ::testing::UnitTest::GetInstance()->listeners().Append(new MyTestListener());
return RUN_ALL_TESTS(); return RUN_ALL_TESTS();
......
...@@ -35,15 +35,15 @@ ...@@ -35,15 +35,15 @@
// This file is #included from gtest-internal.h. // This file is #included from gtest-internal.h.
// Do not #include this file anywhere else! // Do not #include this file anywhere else!
#include "gtest/internal/gtest-filepath.h"
#include "gtest/gtest.h" #include "gtest/gtest.h"
#include "gtest/internal/gtest-filepath.h"
#include "src/gtest-internal-inl.h" #include "src/gtest-internal-inl.h"
#if GTEST_OS_WINDOWS_MOBILE #if GTEST_OS_WINDOWS_MOBILE
# include <windows.h> // NOLINT #include <windows.h> // NOLINT
#elif GTEST_OS_WINDOWS #elif GTEST_OS_WINDOWS
# include <direct.h> // NOLINT #include <direct.h> // NOLINT
#endif // GTEST_OS_WINDOWS_MOBILE #endif // GTEST_OS_WINDOWS_MOBILE
namespace testing { namespace testing {
namespace internal { namespace internal {
...@@ -55,16 +55,16 @@ namespace { ...@@ -55,16 +55,16 @@ namespace {
int remove(const char* path) { int remove(const char* path) {
LPCWSTR wpath = String::AnsiToUtf16(path); LPCWSTR wpath = String::AnsiToUtf16(path);
int ret = DeleteFile(wpath) ? 0 : -1; int ret = DeleteFile(wpath) ? 0 : -1;
delete [] wpath; delete[] wpath;
return ret; return ret;
} }
// Windows CE doesn't have the _rmdir C function. // Windows CE doesn't have the _rmdir C function.
int _rmdir(const char* path) { int _rmdir(const char* path) {
FilePath filepath(path); FilePath filepath(path);
LPCWSTR wpath = String::AnsiToUtf16( LPCWSTR wpath =
filepath.RemoveTrailingPathSeparator().c_str()); String::AnsiToUtf16(filepath.RemoveTrailingPathSeparator().c_str());
int ret = RemoveDirectory(wpath) ? 0 : -1; int ret = RemoveDirectory(wpath) ? 0 : -1;
delete [] wpath; delete[] wpath;
return ret; return ret;
} }
...@@ -78,18 +78,18 @@ TEST(GetCurrentDirTest, ReturnsCurrentDir) { ...@@ -78,18 +78,18 @@ TEST(GetCurrentDirTest, ReturnsCurrentDir) {
const FilePath cwd = FilePath::GetCurrentDir(); const FilePath cwd = FilePath::GetCurrentDir();
posix::ChDir(original_dir.c_str()); posix::ChDir(original_dir.c_str());
# if GTEST_OS_WINDOWS || GTEST_OS_OS2 #if GTEST_OS_WINDOWS || GTEST_OS_OS2
// Skips the ":". // Skips the ":".
const char* const cwd_without_drive = strchr(cwd.c_str(), ':'); const char* const cwd_without_drive = strchr(cwd.c_str(), ':');
ASSERT_TRUE(cwd_without_drive != NULL); ASSERT_TRUE(cwd_without_drive != NULL);
EXPECT_STREQ(GTEST_PATH_SEP_, cwd_without_drive + 1); EXPECT_STREQ(GTEST_PATH_SEP_, cwd_without_drive + 1);
# else #else
EXPECT_EQ(GTEST_PATH_SEP_, cwd.string()); EXPECT_EQ(GTEST_PATH_SEP_, cwd.string());
# endif #endif
} }
#endif // GTEST_OS_WINDOWS_MOBILE #endif // GTEST_OS_WINDOWS_MOBILE
...@@ -112,33 +112,34 @@ TEST(RemoveDirectoryNameTest, WhenEmptyName) { ...@@ -112,33 +112,34 @@ TEST(RemoveDirectoryNameTest, WhenEmptyName) {
// RemoveDirectoryName "afile" -> "afile" // RemoveDirectoryName "afile" -> "afile"
TEST(RemoveDirectoryNameTest, ButNoDirectory) { TEST(RemoveDirectoryNameTest, ButNoDirectory) {
EXPECT_EQ("afile", EXPECT_EQ("afile", FilePath("afile").RemoveDirectoryName().string());
FilePath("afile").RemoveDirectoryName().string());
} }
// RemoveDirectoryName "/afile" -> "afile" // RemoveDirectoryName "/afile" -> "afile"
TEST(RemoveDirectoryNameTest, RootFileShouldGiveFileName) { TEST(RemoveDirectoryNameTest, RootFileShouldGiveFileName) {
EXPECT_EQ("afile", EXPECT_EQ("afile",
FilePath(GTEST_PATH_SEP_ "afile").RemoveDirectoryName().string()); FilePath(GTEST_PATH_SEP_ "afile").RemoveDirectoryName().string());
} }
// RemoveDirectoryName "adir/" -> "" // RemoveDirectoryName "adir/" -> ""
TEST(RemoveDirectoryNameTest, WhereThereIsNoFileName) { TEST(RemoveDirectoryNameTest, WhereThereIsNoFileName) {
EXPECT_EQ("", EXPECT_EQ("",
FilePath("adir" GTEST_PATH_SEP_).RemoveDirectoryName().string()); FilePath("adir" GTEST_PATH_SEP_).RemoveDirectoryName().string());
} }
// RemoveDirectoryName "adir/afile" -> "afile" // RemoveDirectoryName "adir/afile" -> "afile"
TEST(RemoveDirectoryNameTest, ShouldGiveFileName) { TEST(RemoveDirectoryNameTest, ShouldGiveFileName) {
EXPECT_EQ("afile", EXPECT_EQ(
"afile",
FilePath("adir" GTEST_PATH_SEP_ "afile").RemoveDirectoryName().string()); FilePath("adir" GTEST_PATH_SEP_ "afile").RemoveDirectoryName().string());
} }
// RemoveDirectoryName "adir/subdir/afile" -> "afile" // RemoveDirectoryName "adir/subdir/afile" -> "afile"
TEST(RemoveDirectoryNameTest, ShouldAlsoGiveFileName) { TEST(RemoveDirectoryNameTest, ShouldAlsoGiveFileName) {
EXPECT_EQ("afile", EXPECT_EQ("afile",
FilePath("adir" GTEST_PATH_SEP_ "subdir" GTEST_PATH_SEP_ "afile") FilePath("adir" GTEST_PATH_SEP_ "subdir" GTEST_PATH_SEP_ "afile")
.RemoveDirectoryName().string()); .RemoveDirectoryName()
.string());
} }
#if GTEST_HAS_ALT_PATH_SEP_ #if GTEST_HAS_ALT_PATH_SEP_
...@@ -182,7 +183,7 @@ TEST(RemoveFileNameTest, EmptyName) { ...@@ -182,7 +183,7 @@ TEST(RemoveFileNameTest, EmptyName) {
// RemoveFileName "adir/" -> "adir/" // RemoveFileName "adir/" -> "adir/"
TEST(RemoveFileNameTest, ButNoFile) { TEST(RemoveFileNameTest, ButNoFile) {
EXPECT_EQ("adir" GTEST_PATH_SEP_, EXPECT_EQ("adir" GTEST_PATH_SEP_,
FilePath("adir" GTEST_PATH_SEP_).RemoveFileName().string()); FilePath("adir" GTEST_PATH_SEP_).RemoveFileName().string());
} }
// RemoveFileName "adir/afile" -> "adir/" // RemoveFileName "adir/afile" -> "adir/"
...@@ -194,14 +195,15 @@ TEST(RemoveFileNameTest, GivesDirName) { ...@@ -194,14 +195,15 @@ TEST(RemoveFileNameTest, GivesDirName) {
// RemoveFileName "adir/subdir/afile" -> "adir/subdir/" // RemoveFileName "adir/subdir/afile" -> "adir/subdir/"
TEST(RemoveFileNameTest, GivesDirAndSubDirName) { TEST(RemoveFileNameTest, GivesDirAndSubDirName) {
EXPECT_EQ("adir" GTEST_PATH_SEP_ "subdir" GTEST_PATH_SEP_, EXPECT_EQ("adir" GTEST_PATH_SEP_ "subdir" GTEST_PATH_SEP_,
FilePath("adir" GTEST_PATH_SEP_ "subdir" GTEST_PATH_SEP_ "afile") FilePath("adir" GTEST_PATH_SEP_ "subdir" GTEST_PATH_SEP_ "afile")
.RemoveFileName().string()); .RemoveFileName()
.string());
} }
// RemoveFileName "/afile" -> "/" // RemoveFileName "/afile" -> "/"
TEST(RemoveFileNameTest, GivesRootDir) { TEST(RemoveFileNameTest, GivesRootDir) {
EXPECT_EQ(GTEST_PATH_SEP_, EXPECT_EQ(GTEST_PATH_SEP_,
FilePath(GTEST_PATH_SEP_ "afile").RemoveFileName().string()); FilePath(GTEST_PATH_SEP_ "afile").RemoveFileName().string());
} }
#if GTEST_HAS_ALT_PATH_SEP_ #if GTEST_HAS_ALT_PATH_SEP_
...@@ -235,44 +237,43 @@ TEST(RemoveFileNameTest, GivesRootDirForAlternateSeparator) { ...@@ -235,44 +237,43 @@ TEST(RemoveFileNameTest, GivesRootDirForAlternateSeparator) {
#endif #endif
TEST(MakeFileNameTest, GenerateWhenNumberIsZero) { TEST(MakeFileNameTest, GenerateWhenNumberIsZero) {
FilePath actual = FilePath::MakeFileName(FilePath("foo"), FilePath("bar"), FilePath actual =
0, "xml"); FilePath::MakeFileName(FilePath("foo"), FilePath("bar"), 0, "xml");
EXPECT_EQ("foo" GTEST_PATH_SEP_ "bar.xml", actual.string()); EXPECT_EQ("foo" GTEST_PATH_SEP_ "bar.xml", actual.string());
} }
TEST(MakeFileNameTest, GenerateFileNameNumberGtZero) { TEST(MakeFileNameTest, GenerateFileNameNumberGtZero) {
FilePath actual = FilePath::MakeFileName(FilePath("foo"), FilePath("bar"), FilePath actual =
12, "xml"); FilePath::MakeFileName(FilePath("foo"), FilePath("bar"), 12, "xml");
EXPECT_EQ("foo" GTEST_PATH_SEP_ "bar_12.xml", actual.string()); EXPECT_EQ("foo" GTEST_PATH_SEP_ "bar_12.xml", actual.string());
} }
TEST(MakeFileNameTest, GenerateFileNameWithSlashNumberIsZero) { TEST(MakeFileNameTest, GenerateFileNameWithSlashNumberIsZero) {
FilePath actual = FilePath::MakeFileName(FilePath("foo" GTEST_PATH_SEP_), FilePath actual = FilePath::MakeFileName(FilePath("foo" GTEST_PATH_SEP_),
FilePath("bar"), 0, "xml"); FilePath("bar"), 0, "xml");
EXPECT_EQ("foo" GTEST_PATH_SEP_ "bar.xml", actual.string()); EXPECT_EQ("foo" GTEST_PATH_SEP_ "bar.xml", actual.string());
} }
TEST(MakeFileNameTest, GenerateFileNameWithSlashNumberGtZero) { TEST(MakeFileNameTest, GenerateFileNameWithSlashNumberGtZero) {
FilePath actual = FilePath::MakeFileName(FilePath("foo" GTEST_PATH_SEP_), FilePath actual = FilePath::MakeFileName(FilePath("foo" GTEST_PATH_SEP_),
FilePath("bar"), 12, "xml"); FilePath("bar"), 12, "xml");
EXPECT_EQ("foo" GTEST_PATH_SEP_ "bar_12.xml", actual.string()); EXPECT_EQ("foo" GTEST_PATH_SEP_ "bar_12.xml", actual.string());
} }
TEST(MakeFileNameTest, GenerateWhenNumberIsZeroAndDirIsEmpty) { TEST(MakeFileNameTest, GenerateWhenNumberIsZeroAndDirIsEmpty) {
FilePath actual = FilePath::MakeFileName(FilePath(""), FilePath("bar"), FilePath actual =
0, "xml"); FilePath::MakeFileName(FilePath(""), FilePath("bar"), 0, "xml");
EXPECT_EQ("bar.xml", actual.string()); EXPECT_EQ("bar.xml", actual.string());
} }
TEST(MakeFileNameTest, GenerateWhenNumberIsNotZeroAndDirIsEmpty) { TEST(MakeFileNameTest, GenerateWhenNumberIsNotZeroAndDirIsEmpty) {
FilePath actual = FilePath::MakeFileName(FilePath(""), FilePath("bar"), FilePath actual =
14, "xml"); FilePath::MakeFileName(FilePath(""), FilePath("bar"), 14, "xml");
EXPECT_EQ("bar_14.xml", actual.string()); EXPECT_EQ("bar_14.xml", actual.string());
} }
TEST(ConcatPathsTest, WorksWhenDirDoesNotEndWithPathSep) { TEST(ConcatPathsTest, WorksWhenDirDoesNotEndWithPathSep) {
FilePath actual = FilePath::ConcatPaths(FilePath("foo"), FilePath actual = FilePath::ConcatPaths(FilePath("foo"), FilePath("bar.xml"));
FilePath("bar.xml"));
EXPECT_EQ("foo" GTEST_PATH_SEP_ "bar.xml", actual.string()); EXPECT_EQ("foo" GTEST_PATH_SEP_ "bar.xml", actual.string());
} }
...@@ -283,8 +284,7 @@ TEST(ConcatPathsTest, WorksWhenPath1EndsWithPathSep) { ...@@ -283,8 +284,7 @@ TEST(ConcatPathsTest, WorksWhenPath1EndsWithPathSep) {
} }
TEST(ConcatPathsTest, Path1BeingEmpty) { TEST(ConcatPathsTest, Path1BeingEmpty) {
FilePath actual = FilePath::ConcatPaths(FilePath(""), FilePath actual = FilePath::ConcatPaths(FilePath(""), FilePath("bar.xml"));
FilePath("bar.xml"));
EXPECT_EQ("bar.xml", actual.string()); EXPECT_EQ("bar.xml", actual.string());
} }
...@@ -294,8 +294,7 @@ TEST(ConcatPathsTest, Path2BeingEmpty) { ...@@ -294,8 +294,7 @@ TEST(ConcatPathsTest, Path2BeingEmpty) {
} }
TEST(ConcatPathsTest, BothPathBeingEmpty) { TEST(ConcatPathsTest, BothPathBeingEmpty) {
FilePath actual = FilePath::ConcatPaths(FilePath(""), FilePath actual = FilePath::ConcatPaths(FilePath(""), FilePath(""));
FilePath(""));
EXPECT_EQ("", actual.string()); EXPECT_EQ("", actual.string());
} }
...@@ -307,16 +306,16 @@ TEST(ConcatPathsTest, Path1ContainsPathSep) { ...@@ -307,16 +306,16 @@ TEST(ConcatPathsTest, Path1ContainsPathSep) {
} }
TEST(ConcatPathsTest, Path2ContainsPathSep) { TEST(ConcatPathsTest, Path2ContainsPathSep) {
FilePath actual = FilePath::ConcatPaths( FilePath actual =
FilePath("foo" GTEST_PATH_SEP_), FilePath::ConcatPaths(FilePath("foo" GTEST_PATH_SEP_),
FilePath("bar" GTEST_PATH_SEP_ "bar.xml")); FilePath("bar" GTEST_PATH_SEP_ "bar.xml"));
EXPECT_EQ("foo" GTEST_PATH_SEP_ "bar" GTEST_PATH_SEP_ "bar.xml", EXPECT_EQ("foo" GTEST_PATH_SEP_ "bar" GTEST_PATH_SEP_ "bar.xml",
actual.string()); actual.string());
} }
TEST(ConcatPathsTest, Path2EndsWithPathSep) { TEST(ConcatPathsTest, Path2EndsWithPathSep) {
FilePath actual = FilePath::ConcatPaths(FilePath("foo"), FilePath actual =
FilePath("bar" GTEST_PATH_SEP_)); FilePath::ConcatPaths(FilePath("foo"), FilePath("bar" GTEST_PATH_SEP_));
EXPECT_EQ("foo" GTEST_PATH_SEP_ "bar" GTEST_PATH_SEP_, actual.string()); EXPECT_EQ("foo" GTEST_PATH_SEP_ "bar" GTEST_PATH_SEP_, actual.string());
} }
...@@ -332,7 +331,8 @@ TEST(RemoveTrailingPathSeparatorTest, FileNoSlashString) { ...@@ -332,7 +331,8 @@ TEST(RemoveTrailingPathSeparatorTest, FileNoSlashString) {
// RemoveTrailingPathSeparator "foo/" -> "foo" // RemoveTrailingPathSeparator "foo/" -> "foo"
TEST(RemoveTrailingPathSeparatorTest, ShouldRemoveTrailingSeparator) { TEST(RemoveTrailingPathSeparatorTest, ShouldRemoveTrailingSeparator) {
EXPECT_EQ("foo", EXPECT_EQ(
"foo",
FilePath("foo" GTEST_PATH_SEP_).RemoveTrailingPathSeparator().string()); FilePath("foo" GTEST_PATH_SEP_).RemoveTrailingPathSeparator().string());
#if GTEST_HAS_ALT_PATH_SEP_ #if GTEST_HAS_ALT_PATH_SEP_
EXPECT_EQ("foo", FilePath("foo/").RemoveTrailingPathSeparator().string()); EXPECT_EQ("foo", FilePath("foo/").RemoveTrailingPathSeparator().string());
...@@ -343,18 +343,19 @@ TEST(RemoveTrailingPathSeparatorTest, ShouldRemoveTrailingSeparator) { ...@@ -343,18 +343,19 @@ TEST(RemoveTrailingPathSeparatorTest, ShouldRemoveTrailingSeparator) {
TEST(RemoveTrailingPathSeparatorTest, ShouldRemoveLastSeparator) { TEST(RemoveTrailingPathSeparatorTest, ShouldRemoveLastSeparator) {
EXPECT_EQ("foo" GTEST_PATH_SEP_ "bar", EXPECT_EQ("foo" GTEST_PATH_SEP_ "bar",
FilePath("foo" GTEST_PATH_SEP_ "bar" GTEST_PATH_SEP_) FilePath("foo" GTEST_PATH_SEP_ "bar" GTEST_PATH_SEP_)
.RemoveTrailingPathSeparator().string()); .RemoveTrailingPathSeparator()
.string());
} }
// RemoveTrailingPathSeparator "foo/bar" -> "foo/bar" // RemoveTrailingPathSeparator "foo/bar" -> "foo/bar"
TEST(RemoveTrailingPathSeparatorTest, ShouldReturnUnmodified) { TEST(RemoveTrailingPathSeparatorTest, ShouldReturnUnmodified) {
EXPECT_EQ("foo" GTEST_PATH_SEP_ "bar", EXPECT_EQ("foo" GTEST_PATH_SEP_ "bar", FilePath("foo" GTEST_PATH_SEP_ "bar")
FilePath("foo" GTEST_PATH_SEP_ "bar") .RemoveTrailingPathSeparator()
.RemoveTrailingPathSeparator().string()); .string());
} }
TEST(DirectoryTest, RootDirectoryExists) { TEST(DirectoryTest, RootDirectoryExists) {
#if GTEST_OS_WINDOWS // We are on Windows. #if GTEST_OS_WINDOWS // We are on Windows.
char current_drive[_MAX_PATH]; // NOLINT char current_drive[_MAX_PATH]; // NOLINT
current_drive[0] = static_cast<char>(_getdrive() + 'A' - 1); current_drive[0] = static_cast<char>(_getdrive() + 'A' - 1);
current_drive[1] = ':'; current_drive[1] = ':';
...@@ -393,12 +394,12 @@ TEST(DirectoryTest, EmptyPathDirectoryDoesNotExist) { ...@@ -393,12 +394,12 @@ TEST(DirectoryTest, EmptyPathDirectoryDoesNotExist) {
TEST(DirectoryTest, CurrentDirectoryExists) { TEST(DirectoryTest, CurrentDirectoryExists) {
#if GTEST_OS_WINDOWS // We are on Windows. #if GTEST_OS_WINDOWS // We are on Windows.
# ifndef _WIN32_CE // Windows CE doesn't have a current directory. #ifndef _WIN32_CE // Windows CE doesn't have a current directory.
EXPECT_TRUE(FilePath(".").DirectoryExists()); EXPECT_TRUE(FilePath(".").DirectoryExists());
EXPECT_TRUE(FilePath(".\\").DirectoryExists()); EXPECT_TRUE(FilePath(".\\").DirectoryExists());
# endif // _WIN32_CE #endif // _WIN32_CE
#else #else
EXPECT_TRUE(FilePath(".").DirectoryExists()); EXPECT_TRUE(FilePath(".").DirectoryExists());
EXPECT_TRUE(FilePath("./").DirectoryExists()); EXPECT_TRUE(FilePath("./").DirectoryExists());
...@@ -411,29 +412,30 @@ TEST(NormalizeTest, MultipleConsecutiveSepaparatorsInMidstring) { ...@@ -411,29 +412,30 @@ TEST(NormalizeTest, MultipleConsecutiveSepaparatorsInMidstring) {
FilePath("foo" GTEST_PATH_SEP_ "bar").string()); FilePath("foo" GTEST_PATH_SEP_ "bar").string());
EXPECT_EQ("foo" GTEST_PATH_SEP_ "bar", EXPECT_EQ("foo" GTEST_PATH_SEP_ "bar",
FilePath("foo" GTEST_PATH_SEP_ GTEST_PATH_SEP_ "bar").string()); FilePath("foo" GTEST_PATH_SEP_ GTEST_PATH_SEP_ "bar").string());
EXPECT_EQ("foo" GTEST_PATH_SEP_ "bar", EXPECT_EQ(
FilePath("foo" GTEST_PATH_SEP_ GTEST_PATH_SEP_ "foo" GTEST_PATH_SEP_ "bar",
GTEST_PATH_SEP_ "bar").string()); FilePath("foo" GTEST_PATH_SEP_ GTEST_PATH_SEP_ GTEST_PATH_SEP_ "bar")
.string());
} }
// "/bar" == //bar" == "///bar" // "/bar" == //bar" == "///bar"
TEST(NormalizeTest, MultipleConsecutiveSepaparatorsAtStringStart) { TEST(NormalizeTest, MultipleConsecutiveSepaparatorsAtStringStart) {
EXPECT_EQ(GTEST_PATH_SEP_ "bar", FilePath(GTEST_PATH_SEP_ "bar").string());
EXPECT_EQ(GTEST_PATH_SEP_ "bar", EXPECT_EQ(GTEST_PATH_SEP_ "bar",
FilePath(GTEST_PATH_SEP_ "bar").string()); FilePath(GTEST_PATH_SEP_ GTEST_PATH_SEP_ "bar").string());
EXPECT_EQ(GTEST_PATH_SEP_ "bar", EXPECT_EQ(
FilePath(GTEST_PATH_SEP_ GTEST_PATH_SEP_ "bar").string()); GTEST_PATH_SEP_ "bar",
EXPECT_EQ(GTEST_PATH_SEP_ "bar", FilePath(GTEST_PATH_SEP_ GTEST_PATH_SEP_ GTEST_PATH_SEP_ "bar").string());
FilePath(GTEST_PATH_SEP_ GTEST_PATH_SEP_ GTEST_PATH_SEP_ "bar").string());
} }
// "foo/" == foo//" == "foo///" // "foo/" == foo//" == "foo///"
TEST(NormalizeTest, MultipleConsecutiveSepaparatorsAtStringEnd) { TEST(NormalizeTest, MultipleConsecutiveSepaparatorsAtStringEnd) {
EXPECT_EQ("foo" GTEST_PATH_SEP_, FilePath("foo" GTEST_PATH_SEP_).string());
EXPECT_EQ("foo" GTEST_PATH_SEP_, EXPECT_EQ("foo" GTEST_PATH_SEP_,
FilePath("foo" GTEST_PATH_SEP_).string()); FilePath("foo" GTEST_PATH_SEP_ GTEST_PATH_SEP_).string());
EXPECT_EQ("foo" GTEST_PATH_SEP_, EXPECT_EQ(
FilePath("foo" GTEST_PATH_SEP_ GTEST_PATH_SEP_).string()); "foo" GTEST_PATH_SEP_,
EXPECT_EQ("foo" GTEST_PATH_SEP_, FilePath("foo" GTEST_PATH_SEP_ GTEST_PATH_SEP_ GTEST_PATH_SEP_).string());
FilePath("foo" GTEST_PATH_SEP_ GTEST_PATH_SEP_ GTEST_PATH_SEP_).string());
} }
#if GTEST_HAS_ALT_PATH_SEP_ #if GTEST_HAS_ALT_PATH_SEP_
...@@ -442,12 +444,10 @@ TEST(NormalizeTest, MultipleConsecutiveSepaparatorsAtStringEnd) { ...@@ -442,12 +444,10 @@ TEST(NormalizeTest, MultipleConsecutiveSepaparatorsAtStringEnd) {
// regardless of their combination (e.g. "foo\" =="foo/\" == // regardless of their combination (e.g. "foo\" =="foo/\" ==
// "foo\\/"). // "foo\\/").
TEST(NormalizeTest, MixAlternateSeparatorAtStringEnd) { TEST(NormalizeTest, MixAlternateSeparatorAtStringEnd) {
EXPECT_EQ("foo" GTEST_PATH_SEP_, EXPECT_EQ("foo" GTEST_PATH_SEP_, FilePath("foo/").string());
FilePath("foo/").string());
EXPECT_EQ("foo" GTEST_PATH_SEP_, EXPECT_EQ("foo" GTEST_PATH_SEP_,
FilePath("foo" GTEST_PATH_SEP_ "/").string()); FilePath("foo" GTEST_PATH_SEP_ "/").string());
EXPECT_EQ("foo" GTEST_PATH_SEP_, EXPECT_EQ("foo" GTEST_PATH_SEP_, FilePath("foo//" GTEST_PATH_SEP_).string());
FilePath("foo//" GTEST_PATH_SEP_).string());
} }
#endif #endif
...@@ -478,15 +478,15 @@ TEST(AssignmentOperatorTest, ConstAssignedToNonConst) { ...@@ -478,15 +478,15 @@ TEST(AssignmentOperatorTest, ConstAssignedToNonConst) {
class DirectoryCreationTest : public Test { class DirectoryCreationTest : public Test {
protected: protected:
void SetUp() override { void SetUp() override {
testdata_path_.Set(FilePath( testdata_path_.Set(
TempDir() + GetCurrentExecutableName().string() + FilePath(TempDir() + GetCurrentExecutableName().string() +
"_directory_creation" GTEST_PATH_SEP_ "test" GTEST_PATH_SEP_)); "_directory_creation" GTEST_PATH_SEP_ "test" GTEST_PATH_SEP_));
testdata_file_.Set(testdata_path_.RemoveTrailingPathSeparator()); testdata_file_.Set(testdata_path_.RemoveTrailingPathSeparator());
unique_file0_.Set(FilePath::MakeFileName(testdata_path_, FilePath("unique"), unique_file0_.Set(
0, "txt")); FilePath::MakeFileName(testdata_path_, FilePath("unique"), 0, "txt"));
unique_file1_.Set(FilePath::MakeFileName(testdata_path_, FilePath("unique"), unique_file1_.Set(
1, "txt")); FilePath::MakeFileName(testdata_path_, FilePath("unique"), 1, "txt"));
remove(testdata_file_.c_str()); remove(testdata_file_.c_str());
remove(unique_file0_.c_str()); remove(unique_file0_.c_str());
...@@ -512,8 +512,8 @@ class DirectoryCreationTest : public Test { ...@@ -512,8 +512,8 @@ class DirectoryCreationTest : public Test {
// a directory named 'test' from a file named 'test'. Example names: // a directory named 'test' from a file named 'test'. Example names:
FilePath testdata_path_; // "/tmp/directory_creation/test/" FilePath testdata_path_; // "/tmp/directory_creation/test/"
FilePath testdata_file_; // "/tmp/directory_creation/test" FilePath testdata_file_; // "/tmp/directory_creation/test"
FilePath unique_file0_; // "/tmp/directory_creation/test/unique.txt" FilePath unique_file0_; // "/tmp/directory_creation/test/unique.txt"
FilePath unique_file1_; // "/tmp/directory_creation/test/unique_1.txt" FilePath unique_file1_; // "/tmp/directory_creation/test/unique_1.txt"
}; };
TEST_F(DirectoryCreationTest, CreateDirectoriesRecursively) { TEST_F(DirectoryCreationTest, CreateDirectoriesRecursively) {
...@@ -530,8 +530,8 @@ TEST_F(DirectoryCreationTest, CreateDirectoriesForAlreadyExistingPath) { ...@@ -530,8 +530,8 @@ TEST_F(DirectoryCreationTest, CreateDirectoriesForAlreadyExistingPath) {
} }
TEST_F(DirectoryCreationTest, CreateDirectoriesAndUniqueFilename) { TEST_F(DirectoryCreationTest, CreateDirectoriesAndUniqueFilename) {
FilePath file_path(FilePath::GenerateUniqueFileName(testdata_path_, FilePath file_path(FilePath::GenerateUniqueFileName(
FilePath("unique"), "txt")); testdata_path_, FilePath("unique"), "txt"));
EXPECT_EQ(unique_file0_.string(), file_path.string()); EXPECT_EQ(unique_file0_.string(), file_path.string());
EXPECT_FALSE(file_path.FileOrDirectoryExists()); // file not there EXPECT_FALSE(file_path.FileOrDirectoryExists()); // file not there
...@@ -540,8 +540,8 @@ TEST_F(DirectoryCreationTest, CreateDirectoriesAndUniqueFilename) { ...@@ -540,8 +540,8 @@ TEST_F(DirectoryCreationTest, CreateDirectoriesAndUniqueFilename) {
CreateTextFile(file_path.c_str()); CreateTextFile(file_path.c_str());
EXPECT_TRUE(file_path.FileOrDirectoryExists()); EXPECT_TRUE(file_path.FileOrDirectoryExists());
FilePath file_path2(FilePath::GenerateUniqueFileName(testdata_path_, FilePath file_path2(FilePath::GenerateUniqueFileName(
FilePath("unique"), "txt")); testdata_path_, FilePath("unique"), "txt"));
EXPECT_EQ(unique_file1_.string(), file_path2.string()); EXPECT_EQ(unique_file1_.string(), file_path2.string());
EXPECT_FALSE(file_path2.FileOrDirectoryExists()); // file not there EXPECT_FALSE(file_path2.FileOrDirectoryExists()); // file not there
CreateTextFile(file_path2.c_str()); CreateTextFile(file_path2.c_str());
...@@ -614,14 +614,16 @@ TEST(FilePathTest, IsAbsolutePath) { ...@@ -614,14 +614,16 @@ TEST(FilePathTest, IsAbsolutePath) {
EXPECT_FALSE(FilePath("is" GTEST_PATH_SEP_ "relative").IsAbsolutePath()); EXPECT_FALSE(FilePath("is" GTEST_PATH_SEP_ "relative").IsAbsolutePath());
EXPECT_FALSE(FilePath("").IsAbsolutePath()); EXPECT_FALSE(FilePath("").IsAbsolutePath());
#if GTEST_OS_WINDOWS #if GTEST_OS_WINDOWS
EXPECT_TRUE(FilePath("c:\\" GTEST_PATH_SEP_ "is_not" EXPECT_TRUE(
GTEST_PATH_SEP_ "relative").IsAbsolutePath()); FilePath("c:\\" GTEST_PATH_SEP_ "is_not" GTEST_PATH_SEP_ "relative")
.IsAbsolutePath());
EXPECT_FALSE(FilePath("c:foo" GTEST_PATH_SEP_ "bar").IsAbsolutePath()); EXPECT_FALSE(FilePath("c:foo" GTEST_PATH_SEP_ "bar").IsAbsolutePath());
EXPECT_TRUE(FilePath("c:/" GTEST_PATH_SEP_ "is_not" EXPECT_TRUE(
GTEST_PATH_SEP_ "relative").IsAbsolutePath()); FilePath("c:/" GTEST_PATH_SEP_ "is_not" GTEST_PATH_SEP_ "relative")
.IsAbsolutePath());
#else #else
EXPECT_TRUE(FilePath(GTEST_PATH_SEP_ "is_not" GTEST_PATH_SEP_ "relative") EXPECT_TRUE(FilePath(GTEST_PATH_SEP_ "is_not" GTEST_PATH_SEP_ "relative")
.IsAbsolutePath()); .IsAbsolutePath());
#endif // GTEST_OS_WINDOWS #endif // GTEST_OS_WINDOWS
} }
......
...@@ -27,7 +27,6 @@ ...@@ -27,7 +27,6 @@
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// Unit test for Google Test test filters. // Unit test for Google Test test filters.
// //
// A user can specify which test(s) in a Google Test program to run via // A user can specify which test(s) in a Google Test program to run via
...@@ -43,87 +42,57 @@ namespace { ...@@ -43,87 +42,57 @@ namespace {
// Test case FooTest. // Test case FooTest.
class FooTest : public testing::Test { class FooTest : public testing::Test {};
};
TEST_F(FooTest, Abc) { TEST_F(FooTest, Abc) {}
}
TEST_F(FooTest, Xyz) { TEST_F(FooTest, Xyz) { FAIL() << "Expected failure."; }
FAIL() << "Expected failure.";
}
// Test case BarTest. // Test case BarTest.
TEST(BarTest, TestOne) { TEST(BarTest, TestOne) {}
}
TEST(BarTest, TestTwo) { TEST(BarTest, TestTwo) {}
}
TEST(BarTest, TestThree) { TEST(BarTest, TestThree) {}
}
TEST(BarTest, DISABLED_TestFour) { TEST(BarTest, DISABLED_TestFour) { FAIL() << "Expected failure."; }
FAIL() << "Expected failure.";
}
TEST(BarTest, DISABLED_TestFive) { TEST(BarTest, DISABLED_TestFive) { FAIL() << "Expected failure."; }
FAIL() << "Expected failure.";
}
// Test case BazTest. // Test case BazTest.
TEST(BazTest, TestOne) { TEST(BazTest, TestOne) { FAIL() << "Expected failure."; }
FAIL() << "Expected failure.";
}
TEST(BazTest, TestA) { TEST(BazTest, TestA) {}
}
TEST(BazTest, TestB) { TEST(BazTest, TestB) {}
}
TEST(BazTest, DISABLED_TestC) { TEST(BazTest, DISABLED_TestC) { FAIL() << "Expected failure."; }
FAIL() << "Expected failure.";
}
// Test case HasDeathTest // Test case HasDeathTest
TEST(HasDeathTest, Test1) { TEST(HasDeathTest, Test1) { EXPECT_DEATH_IF_SUPPORTED(exit(1), ".*"); }
EXPECT_DEATH_IF_SUPPORTED(exit(1), ".*");
}
// We need at least two death tests to make sure that the all death tests // We need at least two death tests to make sure that the all death tests
// aren't on the first shard. // aren't on the first shard.
TEST(HasDeathTest, Test2) { TEST(HasDeathTest, Test2) { EXPECT_DEATH_IF_SUPPORTED(exit(1), ".*"); }
EXPECT_DEATH_IF_SUPPORTED(exit(1), ".*");
}
// Test case FoobarTest // Test case FoobarTest
TEST(DISABLED_FoobarTest, Test1) { TEST(DISABLED_FoobarTest, Test1) { FAIL() << "Expected failure."; }
FAIL() << "Expected failure.";
}
TEST(DISABLED_FoobarTest, DISABLED_Test2) { TEST(DISABLED_FoobarTest, DISABLED_Test2) { FAIL() << "Expected failure."; }
FAIL() << "Expected failure.";
}
// Test case FoobarbazTest // Test case FoobarbazTest
TEST(DISABLED_FoobarbazTest, TestA) { TEST(DISABLED_FoobarbazTest, TestA) { FAIL() << "Expected failure."; }
FAIL() << "Expected failure.";
}
class ParamTest : public testing::TestWithParam<int> { class ParamTest : public testing::TestWithParam<int> {};
};
TEST_P(ParamTest, TestX) { TEST_P(ParamTest, TestX) {}
}
TEST_P(ParamTest, TestY) { TEST_P(ParamTest, TestY) {}
}
INSTANTIATE_TEST_SUITE_P(SeqP, ParamTest, testing::Values(1, 2)); INSTANTIATE_TEST_SUITE_P(SeqP, ParamTest, testing::Values(1, 2));
INSTANTIATE_TEST_SUITE_P(SeqQ, ParamTest, testing::Values(5, 6)); INSTANTIATE_TEST_SUITE_P(SeqQ, ParamTest, testing::Values(5, 6));
......
...@@ -71,6 +71,8 @@ EXPECTED_1 = { ...@@ -71,6 +71,8 @@ EXPECTED_1 = {
u'*', u'*',
u'testsuite': [{ u'testsuite': [{
u'name': u'TestSomeProperties', u'name': u'TestSomeProperties',
u'file': u'gtest_xml_outfile1_test_.cc',
u'line': 41,
u'status': u'RUN', u'status': u'RUN',
u'result': u'COMPLETED', u'result': u'COMPLETED',
u'time': u'*', u'time': u'*',
...@@ -115,6 +117,8 @@ EXPECTED_2 = { ...@@ -115,6 +117,8 @@ EXPECTED_2 = {
u'*', u'*',
u'testsuite': [{ u'testsuite': [{
u'name': u'TestSomeProperties', u'name': u'TestSomeProperties',
u'file': u'gtest_xml_outfile2_test_.cc',
u'line': 41,
u'status': u'RUN', u'status': u'RUN',
u'result': u'COMPLETED', u'result': u'COMPLETED',
u'timestamp': u'*', u'timestamp': u'*',
......
...@@ -90,6 +90,8 @@ EXPECTED_NON_EMPTY = { ...@@ -90,6 +90,8 @@ EXPECTED_NON_EMPTY = {
u'*', u'*',
u'testsuite': [{ u'testsuite': [{
u'name': u'Succeeds', u'name': u'Succeeds',
u'file': u'gtest_xml_output_unittest_.cc',
u'line': 51,
u'status': u'RUN', u'status': u'RUN',
u'result': u'COMPLETED', u'result': u'COMPLETED',
u'time': u'*', u'time': u'*',
...@@ -114,6 +116,10 @@ EXPECTED_NON_EMPTY = { ...@@ -114,6 +116,10 @@ EXPECTED_NON_EMPTY = {
u'testsuite': [{ u'testsuite': [{
u'name': u'name':
u'Fails', u'Fails',
u'file':
u'gtest_xml_output_unittest_.cc',
u'line':
59,
u'status': u'status':
u'RUN', u'RUN',
u'result': u'result':
...@@ -148,6 +154,8 @@ EXPECTED_NON_EMPTY = { ...@@ -148,6 +154,8 @@ EXPECTED_NON_EMPTY = {
u'*', u'*',
u'testsuite': [{ u'testsuite': [{
u'name': u'DISABLED_test_not_run', u'name': u'DISABLED_test_not_run',
u'file': u'gtest_xml_output_unittest_.cc',
u'line': 66,
u'status': u'NOTRUN', u'status': u'NOTRUN',
u'result': u'SUPPRESSED', u'result': u'SUPPRESSED',
u'time': u'*', u'time': u'*',
...@@ -171,6 +179,8 @@ EXPECTED_NON_EMPTY = { ...@@ -171,6 +179,8 @@ EXPECTED_NON_EMPTY = {
u'*', u'*',
u'testsuite': [{ u'testsuite': [{
u'name': u'Skipped', u'name': u'Skipped',
u'file': 'gtest_xml_output_unittest_.cc',
u'line': 73,
u'status': u'RUN', u'status': u'RUN',
u'result': u'SKIPPED', u'result': u'SKIPPED',
u'time': u'*', u'time': u'*',
...@@ -178,6 +188,8 @@ EXPECTED_NON_EMPTY = { ...@@ -178,6 +188,8 @@ EXPECTED_NON_EMPTY = {
u'classname': u'SkippedTest' u'classname': u'SkippedTest'
}, { }, {
u'name': u'SkippedWithMessage', u'name': u'SkippedWithMessage',
u'file': 'gtest_xml_output_unittest_.cc',
u'line': 77,
u'status': u'RUN', u'status': u'RUN',
u'result': u'SKIPPED', u'result': u'SKIPPED',
u'time': u'*', u'time': u'*',
...@@ -186,6 +198,10 @@ EXPECTED_NON_EMPTY = { ...@@ -186,6 +198,10 @@ EXPECTED_NON_EMPTY = {
}, { }, {
u'name': u'name':
u'SkippedAfterFailure', u'SkippedAfterFailure',
u'file':
'gtest_xml_output_unittest_.cc',
u'line':
81,
u'status': u'status':
u'RUN', u'RUN',
u'result': u'result':
...@@ -220,6 +236,8 @@ EXPECTED_NON_EMPTY = { ...@@ -220,6 +236,8 @@ EXPECTED_NON_EMPTY = {
u'*', u'*',
u'testsuite': [{ u'testsuite': [{
u'name': u'Succeeds', u'name': u'Succeeds',
u'file': 'gtest_xml_output_unittest_.cc',
u'line': 86,
u'status': u'RUN', u'status': u'RUN',
u'result': u'COMPLETED', u'result': u'COMPLETED',
u'time': u'*', u'time': u'*',
...@@ -228,6 +246,10 @@ EXPECTED_NON_EMPTY = { ...@@ -228,6 +246,10 @@ EXPECTED_NON_EMPTY = {
}, { }, {
u'name': u'name':
u'Fails', u'Fails',
u'file':
u'gtest_xml_output_unittest_.cc',
u'line':
91,
u'status': u'status':
u'RUN', u'RUN',
u'result': u'result':
...@@ -251,6 +273,8 @@ EXPECTED_NON_EMPTY = { ...@@ -251,6 +273,8 @@ EXPECTED_NON_EMPTY = {
}] }]
}, { }, {
u'name': u'DISABLED_test', u'name': u'DISABLED_test',
u'file': u'gtest_xml_output_unittest_.cc',
u'line': 96,
u'status': u'NOTRUN', u'status': u'NOTRUN',
u'result': u'SUPPRESSED', u'result': u'SUPPRESSED',
u'time': u'*', u'time': u'*',
...@@ -275,6 +299,10 @@ EXPECTED_NON_EMPTY = { ...@@ -275,6 +299,10 @@ EXPECTED_NON_EMPTY = {
u'testsuite': [{ u'testsuite': [{
u'name': u'name':
u'OutputsCData', u'OutputsCData',
u'file':
u'gtest_xml_output_unittest_.cc',
u'line':
100,
u'status': u'status':
u'RUN', u'RUN',
u'result': u'result':
...@@ -311,6 +339,10 @@ EXPECTED_NON_EMPTY = { ...@@ -311,6 +339,10 @@ EXPECTED_NON_EMPTY = {
u'testsuite': [{ u'testsuite': [{
u'name': u'name':
u'InvalidCharactersInMessage', u'InvalidCharactersInMessage',
u'file':
u'gtest_xml_output_unittest_.cc',
u'line':
107,
u'status': u'status':
u'RUN', u'RUN',
u'result': u'result':
...@@ -349,6 +381,8 @@ EXPECTED_NON_EMPTY = { ...@@ -349,6 +381,8 @@ EXPECTED_NON_EMPTY = {
u'aye', u'aye',
u'testsuite': [{ u'testsuite': [{
u'name': u'OneProperty', u'name': u'OneProperty',
u'file': u'gtest_xml_output_unittest_.cc',
u'line': 119,
u'status': u'RUN', u'status': u'RUN',
u'result': u'COMPLETED', u'result': u'COMPLETED',
u'time': u'*', u'time': u'*',
...@@ -357,6 +391,8 @@ EXPECTED_NON_EMPTY = { ...@@ -357,6 +391,8 @@ EXPECTED_NON_EMPTY = {
u'key_1': u'1' u'key_1': u'1'
}, { }, {
u'name': u'IntValuedProperty', u'name': u'IntValuedProperty',
u'file': u'gtest_xml_output_unittest_.cc',
u'line': 123,
u'status': u'RUN', u'status': u'RUN',
u'result': u'COMPLETED', u'result': u'COMPLETED',
u'time': u'*', u'time': u'*',
...@@ -365,6 +401,8 @@ EXPECTED_NON_EMPTY = { ...@@ -365,6 +401,8 @@ EXPECTED_NON_EMPTY = {
u'key_int': u'1' u'key_int': u'1'
}, { }, {
u'name': u'ThreeProperties', u'name': u'ThreeProperties',
u'file': u'gtest_xml_output_unittest_.cc',
u'line': 127,
u'status': u'RUN', u'status': u'RUN',
u'result': u'COMPLETED', u'result': u'COMPLETED',
u'time': u'*', u'time': u'*',
...@@ -375,6 +413,8 @@ EXPECTED_NON_EMPTY = { ...@@ -375,6 +413,8 @@ EXPECTED_NON_EMPTY = {
u'key_3': u'3' u'key_3': u'3'
}, { }, {
u'name': u'TwoValuesForOneKeyUsesLastValue', u'name': u'TwoValuesForOneKeyUsesLastValue',
u'file': u'gtest_xml_output_unittest_.cc',
u'line': 133,
u'status': u'RUN', u'status': u'RUN',
u'result': u'COMPLETED', u'result': u'COMPLETED',
u'time': u'*', u'time': u'*',
...@@ -399,6 +439,8 @@ EXPECTED_NON_EMPTY = { ...@@ -399,6 +439,8 @@ EXPECTED_NON_EMPTY = {
u'*', u'*',
u'testsuite': [{ u'testsuite': [{
u'name': u'RecordProperty', u'name': u'RecordProperty',
u'file': u'gtest_xml_output_unittest_.cc',
u'line': 138,
u'status': u'RUN', u'status': u'RUN',
u'result': u'COMPLETED', u'result': u'COMPLETED',
u'time': u'*', u'time': u'*',
...@@ -407,6 +449,8 @@ EXPECTED_NON_EMPTY = { ...@@ -407,6 +449,8 @@ EXPECTED_NON_EMPTY = {
u'key': u'1' u'key': u'1'
}, { }, {
u'name': u'ExternalUtilityThatCallsRecordIntValuedProperty', u'name': u'ExternalUtilityThatCallsRecordIntValuedProperty',
u'file': u'gtest_xml_output_unittest_.cc',
u'line': 151,
u'status': u'RUN', u'status': u'RUN',
u'result': u'COMPLETED', u'result': u'COMPLETED',
u'time': u'*', u'time': u'*',
...@@ -415,6 +459,8 @@ EXPECTED_NON_EMPTY = { ...@@ -415,6 +459,8 @@ EXPECTED_NON_EMPTY = {
u'key_for_utility_int': u'1' u'key_for_utility_int': u'1'
}, { }, {
u'name': u'ExternalUtilityThatCallsRecordStringValuedProperty', u'name': u'ExternalUtilityThatCallsRecordStringValuedProperty',
u'file': u'gtest_xml_output_unittest_.cc',
u'line': 155,
u'status': u'RUN', u'status': u'RUN',
u'result': u'COMPLETED', u'result': u'COMPLETED',
u'time': u'*', u'time': u'*',
...@@ -440,6 +486,8 @@ EXPECTED_NON_EMPTY = { ...@@ -440,6 +486,8 @@ EXPECTED_NON_EMPTY = {
u'testsuite': [{ u'testsuite': [{
u'name': u'HasTypeParamAttribute', u'name': u'HasTypeParamAttribute',
u'type_param': u'int', u'type_param': u'int',
u'file': u'gtest_xml_output_unittest_.cc',
u'line': 171,
u'status': u'RUN', u'status': u'RUN',
u'result': u'COMPLETED', u'result': u'COMPLETED',
u'time': u'*', u'time': u'*',
...@@ -464,6 +512,8 @@ EXPECTED_NON_EMPTY = { ...@@ -464,6 +512,8 @@ EXPECTED_NON_EMPTY = {
u'testsuite': [{ u'testsuite': [{
u'name': u'HasTypeParamAttribute', u'name': u'HasTypeParamAttribute',
u'type_param': u'long', u'type_param': u'long',
u'file': u'gtest_xml_output_unittest_.cc',
u'line': 171,
u'status': u'RUN', u'status': u'RUN',
u'result': u'COMPLETED', u'result': u'COMPLETED',
u'time': u'*', u'time': u'*',
...@@ -488,6 +538,8 @@ EXPECTED_NON_EMPTY = { ...@@ -488,6 +538,8 @@ EXPECTED_NON_EMPTY = {
u'testsuite': [{ u'testsuite': [{
u'name': u'HasTypeParamAttribute', u'name': u'HasTypeParamAttribute',
u'type_param': u'int', u'type_param': u'int',
u'file': u'gtest_xml_output_unittest_.cc',
u'line': 178,
u'status': u'RUN', u'status': u'RUN',
u'result': u'COMPLETED', u'result': u'COMPLETED',
u'time': u'*', u'time': u'*',
...@@ -512,6 +564,8 @@ EXPECTED_NON_EMPTY = { ...@@ -512,6 +564,8 @@ EXPECTED_NON_EMPTY = {
u'testsuite': [{ u'testsuite': [{
u'name': u'HasTypeParamAttribute', u'name': u'HasTypeParamAttribute',
u'type_param': u'long', u'type_param': u'long',
u'file': u'gtest_xml_output_unittest_.cc',
u'line': 178,
u'status': u'RUN', u'status': u'RUN',
u'result': u'COMPLETED', u'result': u'COMPLETED',
u'time': u'*', u'time': u'*',
...@@ -536,6 +590,8 @@ EXPECTED_NON_EMPTY = { ...@@ -536,6 +590,8 @@ EXPECTED_NON_EMPTY = {
u'testsuite': [{ u'testsuite': [{
u'name': u'HasValueParamAttribute/0', u'name': u'HasValueParamAttribute/0',
u'value_param': u'33', u'value_param': u'33',
u'file': u'gtest_xml_output_unittest_.cc',
u'line': 162,
u'status': u'RUN', u'status': u'RUN',
u'result': u'COMPLETED', u'result': u'COMPLETED',
u'time': u'*', u'time': u'*',
...@@ -544,6 +600,8 @@ EXPECTED_NON_EMPTY = { ...@@ -544,6 +600,8 @@ EXPECTED_NON_EMPTY = {
}, { }, {
u'name': u'HasValueParamAttribute/1', u'name': u'HasValueParamAttribute/1',
u'value_param': u'42', u'value_param': u'42',
u'file': u'gtest_xml_output_unittest_.cc',
u'line': 162,
u'status': u'RUN', u'status': u'RUN',
u'result': u'COMPLETED', u'result': u'COMPLETED',
u'time': u'*', u'time': u'*',
...@@ -552,6 +610,8 @@ EXPECTED_NON_EMPTY = { ...@@ -552,6 +610,8 @@ EXPECTED_NON_EMPTY = {
}, { }, {
u'name': u'AnotherTestThatHasValueParamAttribute/0', u'name': u'AnotherTestThatHasValueParamAttribute/0',
u'value_param': u'33', u'value_param': u'33',
u'file': u'gtest_xml_output_unittest_.cc',
u'line': 163,
u'status': u'RUN', u'status': u'RUN',
u'result': u'COMPLETED', u'result': u'COMPLETED',
u'time': u'*', u'time': u'*',
...@@ -560,6 +620,8 @@ EXPECTED_NON_EMPTY = { ...@@ -560,6 +620,8 @@ EXPECTED_NON_EMPTY = {
}, { }, {
u'name': u'AnotherTestThatHasValueParamAttribute/1', u'name': u'AnotherTestThatHasValueParamAttribute/1',
u'value_param': u'42', u'value_param': u'42',
u'file': u'gtest_xml_output_unittest_.cc',
u'line': 163,
u'status': u'RUN', u'status': u'RUN',
u'result': u'COMPLETED', u'result': u'COMPLETED',
u'time': u'*', u'time': u'*',
...@@ -603,6 +665,8 @@ EXPECTED_FILTERED = { ...@@ -603,6 +665,8 @@ EXPECTED_FILTERED = {
u'*', u'*',
u'testsuite': [{ u'testsuite': [{
u'name': u'Succeeds', u'name': u'Succeeds',
u'file': u'gtest_xml_output_unittest_.cc',
u'line': 51,
u'status': u'RUN', u'status': u'RUN',
u'result': u'COMPLETED', u'result': u'COMPLETED',
u'time': u'*', u'time': u'*',
......
...@@ -27,7 +27,6 @@ ...@@ -27,7 +27,6 @@
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// Unit test for Google Test's --gtest_list_tests flag. // Unit test for Google Test's --gtest_list_tests flag.
// //
// A user can ask Google Test to list all tests that will run // A user can ask Google Test to list all tests that will run
...@@ -40,38 +39,27 @@ ...@@ -40,38 +39,27 @@
#include "gtest/gtest.h" #include "gtest/gtest.h"
// Several different test cases and tests that will be listed. // Several different test cases and tests that will be listed.
TEST(Foo, Bar1) { TEST(Foo, Bar1) {}
}
TEST(Foo, Bar2) { TEST(Foo, Bar2) {}
}
TEST(Foo, DISABLED_Bar3) { TEST(Foo, DISABLED_Bar3) {}
}
TEST(Abc, Xyz) { TEST(Abc, Xyz) {}
}
TEST(Abc, Def) { TEST(Abc, Def) {}
}
TEST(FooBar, Baz) { TEST(FooBar, Baz) {}
}
class FooTest : public testing::Test { class FooTest : public testing::Test {};
};
TEST_F(FooTest, Test1) { TEST_F(FooTest, Test1) {}
}
TEST_F(FooTest, DISABLED_Test2) { TEST_F(FooTest, DISABLED_Test2) {}
}
TEST_F(FooTest, Test3) { TEST_F(FooTest, Test3) {}
}
TEST(FooDeathTest, Test1) { TEST(FooDeathTest, Test1) {}
}
// A group of value-parameterized tests. // A group of value-parameterized tests.
...@@ -86,70 +74,66 @@ class MyType { ...@@ -86,70 +74,66 @@ class MyType {
}; };
// Teaches Google Test how to print a MyType. // Teaches Google Test how to print a MyType.
void PrintTo(const MyType& x, std::ostream* os) { void PrintTo(const MyType& x, std::ostream* os) { *os << x.value(); }
*os << x.value();
}
class ValueParamTest : public testing::TestWithParam<MyType> { class ValueParamTest : public testing::TestWithParam<MyType> {};
};
TEST_P(ValueParamTest, TestA) { TEST_P(ValueParamTest, TestA) {}
}
TEST_P(ValueParamTest, TestB) { TEST_P(ValueParamTest, TestB) {}
}
INSTANTIATE_TEST_SUITE_P( INSTANTIATE_TEST_SUITE_P(
MyInstantiation, ValueParamTest, MyInstantiation, ValueParamTest,
testing::Values(MyType("one line"), testing::Values(
MyType("two\nlines"), MyType("one line"), MyType("two\nlines"),
MyType("a very\nloooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong line"))); // NOLINT MyType("a "
"very\nloooooooooooooooooooooooooooooooooooooooooooooooooooooooo"
"ooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo"
"ooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo"
"ooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo"
"ooooong line"))); // NOLINT
// A group of typed tests. // A group of typed tests.
// A deliberately long type name for testing the line-truncating // A deliberately long type name for testing the line-truncating
// behavior when printing a type parameter. // behavior when printing a type parameter.
class VeryLoooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooogName { // NOLINT class
VeryLoooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooogName { // NOLINT
}; };
template <typename T> template <typename T>
class TypedTest : public testing::Test { class TypedTest : public testing::Test {};
};
template <typename T, int kSize> template <typename T, int kSize>
class MyArray { class MyArray {};
};
typedef testing::Types<VeryLoooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooogName, // NOLINT typedef testing::Types<
int*, MyArray<bool, 42> > MyTypes; VeryLoooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooogName, // NOLINT
int*, MyArray<bool, 42> >
MyTypes;
TYPED_TEST_SUITE(TypedTest, MyTypes); TYPED_TEST_SUITE(TypedTest, MyTypes);
TYPED_TEST(TypedTest, TestA) { TYPED_TEST(TypedTest, TestA) {}
}
TYPED_TEST(TypedTest, TestB) { TYPED_TEST(TypedTest, TestB) {}
}
// A group of type-parameterized tests. // A group of type-parameterized tests.
template <typename T> template <typename T>
class TypeParamTest : public testing::Test { class TypeParamTest : public testing::Test {};
};
TYPED_TEST_SUITE_P(TypeParamTest); TYPED_TEST_SUITE_P(TypeParamTest);
TYPED_TEST_P(TypeParamTest, TestA) { TYPED_TEST_P(TypeParamTest, TestA) {}
}
TYPED_TEST_P(TypeParamTest, TestB) { TYPED_TEST_P(TypeParamTest, TestB) {}
}
REGISTER_TYPED_TEST_SUITE_P(TypeParamTest, TestA, TestB); REGISTER_TYPED_TEST_SUITE_P(TypeParamTest, TestA, TestB);
INSTANTIATE_TYPED_TEST_SUITE_P(My, TypeParamTest, MyTypes); INSTANTIATE_TYPED_TEST_SUITE_P(My, TypeParamTest, MyTypes);
int main(int argc, char **argv) { int main(int argc, char** argv) {
::testing::InitGoogleTest(&argc, argv); ::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS(); return RUN_ALL_TESTS();
......
...@@ -41,10 +41,10 @@ using ::testing::AddGlobalTestEnvironment; ...@@ -41,10 +41,10 @@ using ::testing::AddGlobalTestEnvironment;
using ::testing::Environment; using ::testing::Environment;
using ::testing::InitGoogleTest; using ::testing::InitGoogleTest;
using ::testing::Test; using ::testing::Test;
using ::testing::TestSuite;
using ::testing::TestEventListener; using ::testing::TestEventListener;
using ::testing::TestInfo; using ::testing::TestInfo;
using ::testing::TestPartResult; using ::testing::TestPartResult;
using ::testing::TestSuite;
using ::testing::UnitTest; using ::testing::UnitTest;
// Used by tests to register their events. // Used by tests to register their events.
...@@ -65,8 +65,8 @@ class EventRecordingListener : public TestEventListener { ...@@ -65,8 +65,8 @@ class EventRecordingListener : public TestEventListener {
void OnTestIterationStart(const UnitTest& /*unit_test*/, void OnTestIterationStart(const UnitTest& /*unit_test*/,
int iteration) override { int iteration) override {
Message message; Message message;
message << GetFullMethodName("OnTestIterationStart") message << GetFullMethodName("OnTestIterationStart") << "(" << iteration
<< "(" << iteration << ")"; << ")";
g_events->push_back(message.GetString()); g_events->push_back(message.GetString());
} }
...@@ -112,8 +112,8 @@ class EventRecordingListener : public TestEventListener { ...@@ -112,8 +112,8 @@ class EventRecordingListener : public TestEventListener {
void OnTestIterationEnd(const UnitTest& /*unit_test*/, void OnTestIterationEnd(const UnitTest& /*unit_test*/,
int iteration) override { int iteration) override {
Message message; Message message;
message << GetFullMethodName("OnTestIterationEnd") message << GetFullMethodName("OnTestIterationEnd") << "(" << iteration
<< "(" << iteration << ")"; << ")";
g_events->push_back(message.GetString()); g_events->push_back(message.GetString());
} }
...@@ -122,9 +122,7 @@ class EventRecordingListener : public TestEventListener { ...@@ -122,9 +122,7 @@ class EventRecordingListener : public TestEventListener {
} }
private: private:
std::string GetFullMethodName(const char* name) { std::string GetFullMethodName(const char* name) { return name_ + "." + name; }
return name_ + "." + name;
}
std::string name_; std::string name_;
}; };
...@@ -252,22 +250,21 @@ void VerifyResults(const std::vector<std::string>& data, ...@@ -252,22 +250,21 @@ void VerifyResults(const std::vector<std::string>& data,
EXPECT_EQ(expected_data_size, actual_size); EXPECT_EQ(expected_data_size, actual_size);
// Compares the common prefix. // Compares the common prefix.
const size_t shorter_size = expected_data_size <= actual_size ? const size_t shorter_size =
expected_data_size : actual_size; expected_data_size <= actual_size ? expected_data_size : actual_size;
size_t i = 0; size_t i = 0;
for (; i < shorter_size; ++i) { for (; i < shorter_size; ++i) {
ASSERT_STREQ(expected_data[i], data[i].c_str()) ASSERT_STREQ(expected_data[i], data[i].c_str()) << "at position " << i;
<< "at position " << i;
} }
// Prints extra elements in the actual data. // Prints extra elements in the actual data.
for (; i < actual_size; ++i) { for (; i < actual_size; ++i) {
printf(" Actual event #%lu: %s\n", printf(" Actual event #%lu: %s\n", static_cast<unsigned long>(i),
static_cast<unsigned long>(i), data[i].c_str()); data[i].c_str());
} }
} }
int main(int argc, char **argv) { int main(int argc, char** argv) {
std::vector<std::string> events; std::vector<std::string> events;
g_events = &events; g_events = &events;
InitGoogleTest(&argc, argv); InitGoogleTest(&argc, argv);
...@@ -506,14 +503,12 @@ int main(int argc, char **argv) { ...@@ -506,14 +503,12 @@ int main(int argc, char **argv) {
"1st.OnTestProgramEnd"}; "1st.OnTestProgramEnd"};
#endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_ #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
VerifyResults(events, VerifyResults(events, expected_events,
expected_events, sizeof(expected_events) / sizeof(expected_events[0]));
sizeof(expected_events)/sizeof(expected_events[0]));
// We need to check manually for ad hoc test failures that happen after // We need to check manually for ad hoc test failures that happen after
// RUN_ALL_TESTS finishes. // RUN_ALL_TESTS finishes.
if (UnitTest::GetInstance()->Failed()) if (UnitTest::GetInstance()->Failed()) ret_val = 1;
ret_val = 1;
return ret_val; return ret_val;
} }
...@@ -31,7 +31,6 @@ ...@@ -31,7 +31,6 @@
// Tests for the Message class. // Tests for the Message class.
#include "gtest/gtest-message.h" #include "gtest/gtest-message.h"
#include "gtest/gtest.h" #include "gtest/gtest.h"
namespace { namespace {
...@@ -69,8 +68,9 @@ TEST(MessageTest, StreamsFloat) { ...@@ -69,8 +68,9 @@ TEST(MessageTest, StreamsFloat) {
// Tests streaming a double. // Tests streaming a double.
TEST(MessageTest, StreamsDouble) { TEST(MessageTest, StreamsDouble) {
const std::string s = (Message() << 1260570880.4555497 << " " const std::string s =
<< 1260572265.1954534).GetString(); (Message() << 1260570880.4555497 << " " << 1260572265.1954534)
.GetString();
// Both numbers should be printed with enough precision. // Both numbers should be printed with enough precision.
EXPECT_PRED_FORMAT2(testing::IsSubstring, "1260570880.45", s.c_str()); EXPECT_PRED_FORMAT2(testing::IsSubstring, "1260570880.45", s.c_str());
EXPECT_PRED_FORMAT2(testing::IsSubstring, " 1260572265.19", s.c_str()); EXPECT_PRED_FORMAT2(testing::IsSubstring, " 1260572265.19", s.c_str());
...@@ -108,8 +108,7 @@ TEST(MessageTest, StreamsString) { ...@@ -108,8 +108,7 @@ TEST(MessageTest, StreamsString) {
// Tests that we can output strings containing embedded NULs. // Tests that we can output strings containing embedded NULs.
TEST(MessageTest, StreamsStringWithEmbeddedNUL) { TEST(MessageTest, StreamsStringWithEmbeddedNUL) {
const char char_array_with_nul[] = const char char_array_with_nul[] = "Here's a NUL\0 and some more string";
"Here's a NUL\0 and some more string";
const ::std::string string_with_nul(char_array_with_nul, const ::std::string string_with_nul(char_array_with_nul,
sizeof(char_array_with_nul) - 1); sizeof(char_array_with_nul) - 1);
EXPECT_EQ("Here's a NUL\\0 and some more string", EXPECT_EQ("Here's a NUL\\0 and some more string",
...@@ -129,10 +128,11 @@ TEST(MessageTest, StreamsInt) { ...@@ -129,10 +128,11 @@ TEST(MessageTest, StreamsInt) {
// Tests that basic IO manipulators (endl, ends, and flush) can be // Tests that basic IO manipulators (endl, ends, and flush) can be
// streamed to Message. // streamed to Message.
TEST(MessageTest, StreamsBasicIoManip) { TEST(MessageTest, StreamsBasicIoManip) {
EXPECT_EQ("Line 1.\nA NUL char \\0 in line 2.", EXPECT_EQ(
(Message() << "Line 1." << std::endl "Line 1.\nA NUL char \\0 in line 2.",
<< "A NUL char " << std::ends << std::flush (Message() << "Line 1." << std::endl
<< " in line 2.").GetString()); << "A NUL char " << std::ends << std::flush << " in line 2.")
.GetString());
} }
// Tests Message::GetString() // Tests Message::GetString()
......
...@@ -39,9 +39,9 @@ ...@@ -39,9 +39,9 @@
#include "gtest/gtest.h" #include "gtest/gtest.h"
#if GTEST_OS_WINDOWS_MOBILE #if GTEST_OS_WINDOWS_MOBILE
# include <windows.h> #include <windows.h>
#elif GTEST_OS_WINDOWS #elif GTEST_OS_WINDOWS
# include <direct.h> #include <direct.h>
#elif GTEST_OS_OS2 #elif GTEST_OS_OS2
// For strcasecmp on OS/2 // For strcasecmp on OS/2
#include <strings.h> #include <strings.h>
...@@ -85,9 +85,9 @@ TEST(XmlOutputTest, GetOutputFileSingleFile) { ...@@ -85,9 +85,9 @@ TEST(XmlOutputTest, GetOutputFileSingleFile) {
TEST(XmlOutputTest, GetOutputFileFromDirectoryPath) { TEST(XmlOutputTest, GetOutputFileFromDirectoryPath) {
GTEST_FLAG_SET(output, "xml:path" GTEST_PATH_SEP_); GTEST_FLAG_SET(output, "xml:path" GTEST_PATH_SEP_);
const std::string expected_output_file = const std::string expected_output_file =
GetAbsolutePathOf( GetAbsolutePathOf(FilePath(std::string("path") + GTEST_PATH_SEP_ +
FilePath(std::string("path") + GTEST_PATH_SEP_ + GetCurrentExecutableName().string() + ".xml"))
GetCurrentExecutableName().string() + ".xml")).string(); .string();
const std::string& output_file = const std::string& output_file =
UnitTestOptions::GetAbsolutePathToOutputFile(); UnitTestOptions::GetAbsolutePathToOutputFile();
#if GTEST_OS_WINDOWS #if GTEST_OS_WINDOWS
...@@ -115,13 +115,10 @@ TEST(OutputFileHelpersTest, GetCurrentExecutableName) { ...@@ -115,13 +115,10 @@ TEST(OutputFileHelpersTest, GetCurrentExecutableName) {
const bool success = exe_str == "app"; const bool success = exe_str == "app";
#else #else
const bool success = const bool success =
exe_str == "googletest-options-test" || exe_str == "googletest-options-test" || exe_str == "gtest_all_test" ||
exe_str == "gtest_all_test" || exe_str == "lt-gtest_all_test" || exe_str == "gtest_dll_test";
exe_str == "lt-gtest_all_test" ||
exe_str == "gtest_dll_test";
#endif // GTEST_OS_WINDOWS #endif // GTEST_OS_WINDOWS
if (!success) if (!success) FAIL() << "GetCurrentExecutableName() returns " << exe_str;
FAIL() << "GetCurrentExecutableName() returns " << exe_str;
} }
#if !GTEST_OS_FUCHSIA #if !GTEST_OS_FUCHSIA
...@@ -145,23 +142,26 @@ class XmlOutputChangeDirTest : public Test { ...@@ -145,23 +142,26 @@ class XmlOutputChangeDirTest : public Test {
TEST_F(XmlOutputChangeDirTest, PreserveOriginalWorkingDirWithDefault) { TEST_F(XmlOutputChangeDirTest, PreserveOriginalWorkingDirWithDefault) {
GTEST_FLAG_SET(output, ""); GTEST_FLAG_SET(output, "");
EXPECT_EQ(FilePath::ConcatPaths(original_working_dir_, EXPECT_EQ(
FilePath("test_detail.xml")).string(), FilePath::ConcatPaths(original_working_dir_, FilePath("test_detail.xml"))
UnitTestOptions::GetAbsolutePathToOutputFile()); .string(),
UnitTestOptions::GetAbsolutePathToOutputFile());
} }
TEST_F(XmlOutputChangeDirTest, PreserveOriginalWorkingDirWithDefaultXML) { TEST_F(XmlOutputChangeDirTest, PreserveOriginalWorkingDirWithDefaultXML) {
GTEST_FLAG_SET(output, "xml"); GTEST_FLAG_SET(output, "xml");
EXPECT_EQ(FilePath::ConcatPaths(original_working_dir_, EXPECT_EQ(
FilePath("test_detail.xml")).string(), FilePath::ConcatPaths(original_working_dir_, FilePath("test_detail.xml"))
UnitTestOptions::GetAbsolutePathToOutputFile()); .string(),
UnitTestOptions::GetAbsolutePathToOutputFile());
} }
TEST_F(XmlOutputChangeDirTest, PreserveOriginalWorkingDirWithRelativeFile) { TEST_F(XmlOutputChangeDirTest, PreserveOriginalWorkingDirWithRelativeFile) {
GTEST_FLAG_SET(output, "xml:filename.abc"); GTEST_FLAG_SET(output, "xml:filename.abc");
EXPECT_EQ(FilePath::ConcatPaths(original_working_dir_, EXPECT_EQ(
FilePath("filename.abc")).string(), FilePath::ConcatPaths(original_working_dir_, FilePath("filename.abc"))
UnitTestOptions::GetAbsolutePathToOutputFile()); .string(),
UnitTestOptions::GetAbsolutePathToOutputFile());
} }
TEST_F(XmlOutputChangeDirTest, PreserveOriginalWorkingDirWithRelativePath) { TEST_F(XmlOutputChangeDirTest, PreserveOriginalWorkingDirWithRelativePath) {
...@@ -170,7 +170,8 @@ TEST_F(XmlOutputChangeDirTest, PreserveOriginalWorkingDirWithRelativePath) { ...@@ -170,7 +170,8 @@ TEST_F(XmlOutputChangeDirTest, PreserveOriginalWorkingDirWithRelativePath) {
FilePath::ConcatPaths( FilePath::ConcatPaths(
original_working_dir_, original_working_dir_,
FilePath(std::string("path") + GTEST_PATH_SEP_ + FilePath(std::string("path") + GTEST_PATH_SEP_ +
GetCurrentExecutableName().string() + ".xml")).string(); GetCurrentExecutableName().string() + ".xml"))
.string();
const std::string& output_file = const std::string& output_file =
UnitTestOptions::GetAbsolutePathToOutputFile(); UnitTestOptions::GetAbsolutePathToOutputFile();
#if GTEST_OS_WINDOWS #if GTEST_OS_WINDOWS
......
...@@ -33,12 +33,12 @@ ...@@ -33,12 +33,12 @@
// desired messages. Therefore, most tests in this file are MEANT TO // desired messages. Therefore, most tests in this file are MEANT TO
// FAIL. // FAIL.
#include <stdlib.h>
#include "gtest/gtest-spi.h" #include "gtest/gtest-spi.h"
#include "gtest/gtest.h" #include "gtest/gtest.h"
#include "src/gtest-internal-inl.h" #include "src/gtest-internal-inl.h"
#include <stdlib.h>
#if _MSC_VER #if _MSC_VER
GTEST_DISABLE_MSC_WARNINGS_PUSH_(4127 /* conditional expression is constant */) GTEST_DISABLE_MSC_WARNINGS_PUSH_(4127 /* conditional expression is constant */)
#endif // _MSC_VER #endif // _MSC_VER
...@@ -56,9 +56,7 @@ namespace posix = ::testing::internal::posix; ...@@ -56,9 +56,7 @@ namespace posix = ::testing::internal::posix;
// Tests catching fatal failures. // Tests catching fatal failures.
// A subroutine used by the following test. // A subroutine used by the following test.
void TestEq1(int x) { void TestEq1(int x) { ASSERT_EQ(1, x); }
ASSERT_EQ(1, x);
}
// This function calls a test subroutine, catches the fatal failure it // This function calls a test subroutine, catches the fatal failure it
// generates, and then returns early. // generates, and then returns early.
...@@ -76,24 +74,19 @@ void TryTestSubroutine() { ...@@ -76,24 +74,19 @@ void TryTestSubroutine() {
FAIL() << "This should never be reached."; FAIL() << "This should never be reached.";
} }
TEST(PassingTest, PassingTest1) { TEST(PassingTest, PassingTest1) {}
}
TEST(PassingTest, PassingTest2) { TEST(PassingTest, PassingTest2) {}
}
// Tests that parameters of failing parameterized tests are printed in the // Tests that parameters of failing parameterized tests are printed in the
// failing test summary. // failing test summary.
class FailingParamTest : public testing::TestWithParam<int> {}; class FailingParamTest : public testing::TestWithParam<int> {};
TEST_P(FailingParamTest, Fails) { TEST_P(FailingParamTest, Fails) { EXPECT_EQ(1, GetParam()); }
EXPECT_EQ(1, GetParam());
}
// This generates a test which will fail. Google Test is expected to print // This generates a test which will fail. Google Test is expected to print
// its parameter when it outputs the list of all failed tests. // its parameter when it outputs the list of all failed tests.
INSTANTIATE_TEST_SUITE_P(PrintingFailingParams, INSTANTIATE_TEST_SUITE_P(PrintingFailingParams, FailingParamTest,
FailingParamTest,
testing::Values(2)); testing::Values(2));
// Tests that an empty value for the test suite basename yields just // Tests that an empty value for the test suite basename yields just
...@@ -146,18 +139,16 @@ TEST(FatalFailureTest, FatalFailureInNestedSubroutine) { ...@@ -146,18 +139,16 @@ TEST(FatalFailureTest, FatalFailureInNestedSubroutine) {
// Tests HasFatalFailure() after a failed EXPECT check. // Tests HasFatalFailure() after a failed EXPECT check.
TEST(FatalFailureTest, NonfatalFailureInSubroutine) { TEST(FatalFailureTest, NonfatalFailureInSubroutine) {
printf("(expecting a failure on false)\n"); printf("(expecting a failure on false)\n");
EXPECT_TRUE(false); // Generates a nonfatal failure EXPECT_TRUE(false); // Generates a nonfatal failure
ASSERT_FALSE(HasFatalFailure()); // This should succeed. ASSERT_FALSE(HasFatalFailure()); // This should succeed.
} }
// Tests interleaving user logging and Google Test assertions. // Tests interleaving user logging and Google Test assertions.
TEST(LoggingTest, InterleavingLoggingAndAssertions) { TEST(LoggingTest, InterleavingLoggingAndAssertions) {
static const int a[4] = { static const int a[4] = {3, 9, 2, 6};
3, 9, 2, 6
};
printf("(expecting 2 failures on (3) >= (a[i]))\n"); printf("(expecting 2 failures on (3) >= (a[i]))\n");
for (int i = 0; i < static_cast<int>(sizeof(a)/sizeof(*a)); i++) { for (int i = 0; i < static_cast<int>(sizeof(a) / sizeof(*a)); i++) {
printf("i == %d\n", i); printf("i == %d\n", i);
EXPECT_GE(3, a[i]); EXPECT_GE(3, a[i]);
} }
...@@ -297,16 +288,14 @@ struct CheckPoints { ...@@ -297,16 +288,14 @@ struct CheckPoints {
static void ThreadWithScopedTrace(CheckPoints* check_points) { static void ThreadWithScopedTrace(CheckPoints* check_points) {
{ {
SCOPED_TRACE("Trace B"); SCOPED_TRACE("Trace B");
ADD_FAILURE() ADD_FAILURE() << "Expected failure #1 (in thread B, only trace B alive).";
<< "Expected failure #1 (in thread B, only trace B alive).";
check_points->n1.Notify(); check_points->n1.Notify();
check_points->n2.WaitForNotification(); check_points->n2.WaitForNotification();
ADD_FAILURE() ADD_FAILURE()
<< "Expected failure #3 (in thread B, trace A & B both alive)."; << "Expected failure #3 (in thread B, trace A & B both alive).";
} // Trace B dies here. } // Trace B dies here.
ADD_FAILURE() ADD_FAILURE() << "Expected failure #4 (in thread B, only trace A alive).";
<< "Expected failure #4 (in thread B, only trace A alive).";
check_points->n3.Notify(); check_points->n3.Notify();
} }
...@@ -325,11 +314,9 @@ TEST(SCOPED_TRACETest, WorksConcurrently) { ...@@ -325,11 +314,9 @@ TEST(SCOPED_TRACETest, WorksConcurrently) {
check_points.n2.Notify(); check_points.n2.Notify();
check_points.n3.WaitForNotification(); check_points.n3.WaitForNotification();
ADD_FAILURE() ADD_FAILURE() << "Expected failure #5 (in thread A, only trace A alive).";
<< "Expected failure #5 (in thread A, only trace A alive).";
} // Trace A dies here. } // Trace A dies here.
ADD_FAILURE() ADD_FAILURE() << "Expected failure #6 (in thread A, no trace alive).";
<< "Expected failure #6 (in thread A, no trace alive).";
thread.Join(); thread.Join();
} }
#endif // GTEST_IS_THREADSAFE #endif // GTEST_IS_THREADSAFE
...@@ -412,9 +399,7 @@ class FatalFailureInFixtureConstructorTest : public testing::Test { ...@@ -412,9 +399,7 @@ class FatalFailureInFixtureConstructorTest : public testing::Test {
} }
private: private:
void Init() { void Init() { FAIL() << "Expected failure #1, in the test fixture c'tor."; }
FAIL() << "Expected failure #1, in the test fixture c'tor.";
}
}; };
TEST_F(FatalFailureInFixtureConstructorTest, FailureInConstructor) { TEST_F(FatalFailureInFixtureConstructorTest, FailureInConstructor) {
...@@ -436,9 +421,7 @@ class NonFatalFailureInSetUpTest : public testing::Test { ...@@ -436,9 +421,7 @@ class NonFatalFailureInSetUpTest : public testing::Test {
void TearDown() override { FAIL() << "Expected failure #3, in TearDown()."; } void TearDown() override { FAIL() << "Expected failure #3, in TearDown()."; }
private: private:
void Deinit() { void Deinit() { FAIL() << "Expected failure #4, in the test fixture d'tor."; }
FAIL() << "Expected failure #4, in the test fixture d'tor.";
}
}; };
TEST_F(NonFatalFailureInSetUpTest, FailureInSetUp) { TEST_F(NonFatalFailureInSetUpTest, FailureInSetUp) {
...@@ -458,9 +441,7 @@ class FatalFailureInSetUpTest : public testing::Test { ...@@ -458,9 +441,7 @@ class FatalFailureInSetUpTest : public testing::Test {
void TearDown() override { FAIL() << "Expected failure #2, in TearDown()."; } void TearDown() override { FAIL() << "Expected failure #2, in TearDown()."; }
private: private:
void Deinit() { void Deinit() { FAIL() << "Expected failure #3, in the test fixture d'tor."; }
FAIL() << "Expected failure #3, in the test fixture d'tor.";
}
}; };
TEST_F(FatalFailureInSetUpTest, FailureInSetUp) { TEST_F(FatalFailureInSetUpTest, FailureInSetUp) {
...@@ -488,14 +469,12 @@ TEST(GtestFailAtTest, MessageContainsSpecifiedFileAndLineNumber) { ...@@ -488,14 +469,12 @@ TEST(GtestFailAtTest, MessageContainsSpecifiedFileAndLineNumber) {
namespace foo { namespace foo {
class MixedUpTestSuiteTest : public testing::Test { class MixedUpTestSuiteTest : public testing::Test {};
};
TEST_F(MixedUpTestSuiteTest, FirstTestFromNamespaceFoo) {} TEST_F(MixedUpTestSuiteTest, FirstTestFromNamespaceFoo) {}
TEST_F(MixedUpTestSuiteTest, SecondTestFromNamespaceFoo) {} TEST_F(MixedUpTestSuiteTest, SecondTestFromNamespaceFoo) {}
class MixedUpTestSuiteWithSameTestNameTest : public testing::Test { class MixedUpTestSuiteWithSameTestNameTest : public testing::Test {};
};
TEST_F(MixedUpTestSuiteWithSameTestNameTest, TEST_F(MixedUpTestSuiteWithSameTestNameTest,
TheSecondTestWithThisNameShouldFail) {} TheSecondTestWithThisNameShouldFail) {}
...@@ -504,16 +483,14 @@ TEST_F(MixedUpTestSuiteWithSameTestNameTest, ...@@ -504,16 +483,14 @@ TEST_F(MixedUpTestSuiteWithSameTestNameTest,
namespace bar { namespace bar {
class MixedUpTestSuiteTest : public testing::Test { class MixedUpTestSuiteTest : public testing::Test {};
};
// The following two tests are expected to fail. We rely on the // The following two tests are expected to fail. We rely on the
// golden file to check that Google Test generates the right error message. // golden file to check that Google Test generates the right error message.
TEST_F(MixedUpTestSuiteTest, ThisShouldFail) {} TEST_F(MixedUpTestSuiteTest, ThisShouldFail) {}
TEST_F(MixedUpTestSuiteTest, ThisShouldFailToo) {} TEST_F(MixedUpTestSuiteTest, ThisShouldFailToo) {}
class MixedUpTestSuiteWithSameTestNameTest : public testing::Test { class MixedUpTestSuiteWithSameTestNameTest : public testing::Test {};
};
// Expected to fail. We rely on the golden file to check that Google Test // Expected to fail. We rely on the golden file to check that Google Test
// generates the right error message. // generates the right error message.
...@@ -527,8 +504,7 @@ TEST_F(MixedUpTestSuiteWithSameTestNameTest, ...@@ -527,8 +504,7 @@ TEST_F(MixedUpTestSuiteWithSameTestNameTest,
// test case checks the scenario where TEST_F appears before TEST, and // test case checks the scenario where TEST_F appears before TEST, and
// the second one checks where TEST appears before TEST_F. // the second one checks where TEST appears before TEST_F.
class TEST_F_before_TEST_in_same_test_case : public testing::Test { class TEST_F_before_TEST_in_same_test_case : public testing::Test {};
};
TEST_F(TEST_F_before_TEST_in_same_test_case, DefinedUsingTEST_F) {} TEST_F(TEST_F_before_TEST_in_same_test_case, DefinedUsingTEST_F) {}
...@@ -536,15 +512,13 @@ TEST_F(TEST_F_before_TEST_in_same_test_case, DefinedUsingTEST_F) {} ...@@ -536,15 +512,13 @@ TEST_F(TEST_F_before_TEST_in_same_test_case, DefinedUsingTEST_F) {}
// generates the right error message. // generates the right error message.
TEST(TEST_F_before_TEST_in_same_test_case, DefinedUsingTESTAndShouldFail) {} TEST(TEST_F_before_TEST_in_same_test_case, DefinedUsingTESTAndShouldFail) {}
class TEST_before_TEST_F_in_same_test_case : public testing::Test { class TEST_before_TEST_F_in_same_test_case : public testing::Test {};
};
TEST(TEST_before_TEST_F_in_same_test_case, DefinedUsingTEST) {} TEST(TEST_before_TEST_F_in_same_test_case, DefinedUsingTEST) {}
// Expected to fail. We rely on the golden file to check that Google Test // Expected to fail. We rely on the golden file to check that Google Test
// generates the right error message. // generates the right error message.
TEST_F(TEST_before_TEST_F_in_same_test_case, DefinedUsingTEST_FAndShouldFail) { TEST_F(TEST_before_TEST_F_in_same_test_case, DefinedUsingTEST_FAndShouldFail) {}
}
// Used for testing EXPECT_NONFATAL_FAILURE() and EXPECT_FATAL_FAILURE(). // Used for testing EXPECT_NONFATAL_FAILURE() and EXPECT_FATAL_FAILURE().
int global_integer = 0; int global_integer = 0;
...@@ -552,9 +526,9 @@ int global_integer = 0; ...@@ -552,9 +526,9 @@ int global_integer = 0;
// Tests that EXPECT_NONFATAL_FAILURE() can reference global variables. // Tests that EXPECT_NONFATAL_FAILURE() can reference global variables.
TEST(ExpectNonfatalFailureTest, CanReferenceGlobalVariables) { TEST(ExpectNonfatalFailureTest, CanReferenceGlobalVariables) {
global_integer = 0; global_integer = 0;
EXPECT_NONFATAL_FAILURE({ EXPECT_NONFATAL_FAILURE(
EXPECT_EQ(1, global_integer) << "Expected non-fatal failure."; { EXPECT_EQ(1, global_integer) << "Expected non-fatal failure."; },
}, "Expected non-fatal failure."); "Expected non-fatal failure.");
} }
// Tests that EXPECT_NONFATAL_FAILURE() can reference local variables // Tests that EXPECT_NONFATAL_FAILURE() can reference local variables
...@@ -563,53 +537,48 @@ TEST(ExpectNonfatalFailureTest, CanReferenceLocalVariables) { ...@@ -563,53 +537,48 @@ TEST(ExpectNonfatalFailureTest, CanReferenceLocalVariables) {
int m = 0; int m = 0;
static int n; static int n;
n = 1; n = 1;
EXPECT_NONFATAL_FAILURE({ EXPECT_NONFATAL_FAILURE({ EXPECT_EQ(m, n) << "Expected non-fatal failure."; },
EXPECT_EQ(m, n) << "Expected non-fatal failure."; "Expected non-fatal failure.");
}, "Expected non-fatal failure.");
} }
// Tests that EXPECT_NONFATAL_FAILURE() succeeds when there is exactly // Tests that EXPECT_NONFATAL_FAILURE() succeeds when there is exactly
// one non-fatal failure and no fatal failure. // one non-fatal failure and no fatal failure.
TEST(ExpectNonfatalFailureTest, SucceedsWhenThereIsOneNonfatalFailure) { TEST(ExpectNonfatalFailureTest, SucceedsWhenThereIsOneNonfatalFailure) {
EXPECT_NONFATAL_FAILURE({ EXPECT_NONFATAL_FAILURE({ ADD_FAILURE() << "Expected non-fatal failure."; },
ADD_FAILURE() << "Expected non-fatal failure."; "Expected non-fatal failure.");
}, "Expected non-fatal failure.");
} }
// Tests that EXPECT_NONFATAL_FAILURE() fails when there is no // Tests that EXPECT_NONFATAL_FAILURE() fails when there is no
// non-fatal failure. // non-fatal failure.
TEST(ExpectNonfatalFailureTest, FailsWhenThereIsNoNonfatalFailure) { TEST(ExpectNonfatalFailureTest, FailsWhenThereIsNoNonfatalFailure) {
printf("(expecting a failure)\n"); printf("(expecting a failure)\n");
EXPECT_NONFATAL_FAILURE({ EXPECT_NONFATAL_FAILURE({}, "");
}, "");
} }
// Tests that EXPECT_NONFATAL_FAILURE() fails when there are two // Tests that EXPECT_NONFATAL_FAILURE() fails when there are two
// non-fatal failures. // non-fatal failures.
TEST(ExpectNonfatalFailureTest, FailsWhenThereAreTwoNonfatalFailures) { TEST(ExpectNonfatalFailureTest, FailsWhenThereAreTwoNonfatalFailures) {
printf("(expecting a failure)\n"); printf("(expecting a failure)\n");
EXPECT_NONFATAL_FAILURE({ EXPECT_NONFATAL_FAILURE(
ADD_FAILURE() << "Expected non-fatal failure 1."; {
ADD_FAILURE() << "Expected non-fatal failure 2."; ADD_FAILURE() << "Expected non-fatal failure 1.";
}, ""); ADD_FAILURE() << "Expected non-fatal failure 2.";
},
"");
} }
// Tests that EXPECT_NONFATAL_FAILURE() fails when there is one fatal // Tests that EXPECT_NONFATAL_FAILURE() fails when there is one fatal
// failure. // failure.
TEST(ExpectNonfatalFailureTest, FailsWhenThereIsOneFatalFailure) { TEST(ExpectNonfatalFailureTest, FailsWhenThereIsOneFatalFailure) {
printf("(expecting a failure)\n"); printf("(expecting a failure)\n");
EXPECT_NONFATAL_FAILURE({ EXPECT_NONFATAL_FAILURE({ FAIL() << "Expected fatal failure."; }, "");
FAIL() << "Expected fatal failure.";
}, "");
} }
// Tests that EXPECT_NONFATAL_FAILURE() fails when the statement being // Tests that EXPECT_NONFATAL_FAILURE() fails when the statement being
// tested returns. // tested returns.
TEST(ExpectNonfatalFailureTest, FailsWhenStatementReturns) { TEST(ExpectNonfatalFailureTest, FailsWhenStatementReturns) {
printf("(expecting a failure)\n"); printf("(expecting a failure)\n");
EXPECT_NONFATAL_FAILURE({ EXPECT_NONFATAL_FAILURE({ return; }, "");
return;
}, "");
} }
#if GTEST_HAS_EXCEPTIONS #if GTEST_HAS_EXCEPTIONS
...@@ -619,10 +588,8 @@ TEST(ExpectNonfatalFailureTest, FailsWhenStatementReturns) { ...@@ -619,10 +588,8 @@ TEST(ExpectNonfatalFailureTest, FailsWhenStatementReturns) {
TEST(ExpectNonfatalFailureTest, FailsWhenStatementThrows) { TEST(ExpectNonfatalFailureTest, FailsWhenStatementThrows) {
printf("(expecting a failure)\n"); printf("(expecting a failure)\n");
try { try {
EXPECT_NONFATAL_FAILURE({ EXPECT_NONFATAL_FAILURE({ throw 0; }, "");
throw 0; } catch (int) { // NOLINT
}, "");
} catch(int) { // NOLINT
} }
} }
...@@ -631,9 +598,9 @@ TEST(ExpectNonfatalFailureTest, FailsWhenStatementThrows) { ...@@ -631,9 +598,9 @@ TEST(ExpectNonfatalFailureTest, FailsWhenStatementThrows) {
// Tests that EXPECT_FATAL_FAILURE() can reference global variables. // Tests that EXPECT_FATAL_FAILURE() can reference global variables.
TEST(ExpectFatalFailureTest, CanReferenceGlobalVariables) { TEST(ExpectFatalFailureTest, CanReferenceGlobalVariables) {
global_integer = 0; global_integer = 0;
EXPECT_FATAL_FAILURE({ EXPECT_FATAL_FAILURE(
ASSERT_EQ(1, global_integer) << "Expected fatal failure."; { ASSERT_EQ(1, global_integer) << "Expected fatal failure."; },
}, "Expected fatal failure."); "Expected fatal failure.");
} }
// Tests that EXPECT_FATAL_FAILURE() can reference local static // Tests that EXPECT_FATAL_FAILURE() can reference local static
...@@ -641,58 +608,51 @@ TEST(ExpectFatalFailureTest, CanReferenceGlobalVariables) { ...@@ -641,58 +608,51 @@ TEST(ExpectFatalFailureTest, CanReferenceGlobalVariables) {
TEST(ExpectFatalFailureTest, CanReferenceLocalStaticVariables) { TEST(ExpectFatalFailureTest, CanReferenceLocalStaticVariables) {
static int n; static int n;
n = 1; n = 1;
EXPECT_FATAL_FAILURE({ EXPECT_FATAL_FAILURE({ ASSERT_EQ(0, n) << "Expected fatal failure."; },
ASSERT_EQ(0, n) << "Expected fatal failure."; "Expected fatal failure.");
}, "Expected fatal failure.");
} }
// Tests that EXPECT_FATAL_FAILURE() succeeds when there is exactly // Tests that EXPECT_FATAL_FAILURE() succeeds when there is exactly
// one fatal failure and no non-fatal failure. // one fatal failure and no non-fatal failure.
TEST(ExpectFatalFailureTest, SucceedsWhenThereIsOneFatalFailure) { TEST(ExpectFatalFailureTest, SucceedsWhenThereIsOneFatalFailure) {
EXPECT_FATAL_FAILURE({ EXPECT_FATAL_FAILURE({ FAIL() << "Expected fatal failure."; },
FAIL() << "Expected fatal failure."; "Expected fatal failure.");
}, "Expected fatal failure.");
} }
// Tests that EXPECT_FATAL_FAILURE() fails when there is no fatal // Tests that EXPECT_FATAL_FAILURE() fails when there is no fatal
// failure. // failure.
TEST(ExpectFatalFailureTest, FailsWhenThereIsNoFatalFailure) { TEST(ExpectFatalFailureTest, FailsWhenThereIsNoFatalFailure) {
printf("(expecting a failure)\n"); printf("(expecting a failure)\n");
EXPECT_FATAL_FAILURE({ EXPECT_FATAL_FAILURE({}, "");
}, "");
} }
// A helper for generating a fatal failure. // A helper for generating a fatal failure.
void FatalFailure() { void FatalFailure() { FAIL() << "Expected fatal failure."; }
FAIL() << "Expected fatal failure.";
}
// Tests that EXPECT_FATAL_FAILURE() fails when there are two // Tests that EXPECT_FATAL_FAILURE() fails when there are two
// fatal failures. // fatal failures.
TEST(ExpectFatalFailureTest, FailsWhenThereAreTwoFatalFailures) { TEST(ExpectFatalFailureTest, FailsWhenThereAreTwoFatalFailures) {
printf("(expecting a failure)\n"); printf("(expecting a failure)\n");
EXPECT_FATAL_FAILURE({ EXPECT_FATAL_FAILURE(
FatalFailure(); {
FatalFailure(); FatalFailure();
}, ""); FatalFailure();
},
"");
} }
// Tests that EXPECT_FATAL_FAILURE() fails when there is one non-fatal // Tests that EXPECT_FATAL_FAILURE() fails when there is one non-fatal
// failure. // failure.
TEST(ExpectFatalFailureTest, FailsWhenThereIsOneNonfatalFailure) { TEST(ExpectFatalFailureTest, FailsWhenThereIsOneNonfatalFailure) {
printf("(expecting a failure)\n"); printf("(expecting a failure)\n");
EXPECT_FATAL_FAILURE({ EXPECT_FATAL_FAILURE({ ADD_FAILURE() << "Expected non-fatal failure."; }, "");
ADD_FAILURE() << "Expected non-fatal failure.";
}, "");
} }
// Tests that EXPECT_FATAL_FAILURE() fails when the statement being // Tests that EXPECT_FATAL_FAILURE() fails when the statement being
// tested returns. // tested returns.
TEST(ExpectFatalFailureTest, FailsWhenStatementReturns) { TEST(ExpectFatalFailureTest, FailsWhenStatementReturns) {
printf("(expecting a failure)\n"); printf("(expecting a failure)\n");
EXPECT_FATAL_FAILURE({ EXPECT_FATAL_FAILURE({ return; }, "");
return;
}, "");
} }
#if GTEST_HAS_EXCEPTIONS #if GTEST_HAS_EXCEPTIONS
...@@ -702,10 +662,8 @@ TEST(ExpectFatalFailureTest, FailsWhenStatementReturns) { ...@@ -702,10 +662,8 @@ TEST(ExpectFatalFailureTest, FailsWhenStatementReturns) {
TEST(ExpectFatalFailureTest, FailsWhenStatementThrows) { TEST(ExpectFatalFailureTest, FailsWhenStatementThrows) {
printf("(expecting a failure)\n"); printf("(expecting a failure)\n");
try { try {
EXPECT_FATAL_FAILURE({ EXPECT_FATAL_FAILURE({ throw 0; }, "");
throw 0; } catch (int) { // NOLINT
}, "");
} catch(int) { // NOLINT
} }
} }
...@@ -717,21 +675,14 @@ std::string ParamNameFunc(const testing::TestParamInfo<std::string>& info) { ...@@ -717,21 +675,14 @@ std::string ParamNameFunc(const testing::TestParamInfo<std::string>& info) {
return info.param; return info.param;
} }
class ParamTest : public testing::TestWithParam<std::string> { class ParamTest : public testing::TestWithParam<std::string> {};
};
TEST_P(ParamTest, Success) { TEST_P(ParamTest, Success) { EXPECT_EQ("a", GetParam()); }
EXPECT_EQ("a", GetParam());
}
TEST_P(ParamTest, Failure) { TEST_P(ParamTest, Failure) { EXPECT_EQ("b", GetParam()) << "Expected failure"; }
EXPECT_EQ("b", GetParam()) << "Expected failure";
}
INSTANTIATE_TEST_SUITE_P(PrintingStrings, INSTANTIATE_TEST_SUITE_P(PrintingStrings, ParamTest,
ParamTest, testing::Values(std::string("a")), ParamNameFunc);
testing::Values(std::string("a")),
ParamNameFunc);
// The case where a suite has INSTANTIATE_TEST_SUITE_P but not TEST_P. // The case where a suite has INSTANTIATE_TEST_SUITE_P but not TEST_P.
using NoTests = ParamTest; using NoTests = ParamTest;
...@@ -739,20 +690,17 @@ INSTANTIATE_TEST_SUITE_P(ThisIsOdd, NoTests, ::testing::Values("Hello")); ...@@ -739,20 +690,17 @@ INSTANTIATE_TEST_SUITE_P(ThisIsOdd, NoTests, ::testing::Values("Hello"));
// fails under kErrorOnUninstantiatedParameterizedTest=true // fails under kErrorOnUninstantiatedParameterizedTest=true
class DetectNotInstantiatedTest : public testing::TestWithParam<int> {}; class DetectNotInstantiatedTest : public testing::TestWithParam<int> {};
TEST_P(DetectNotInstantiatedTest, Used) { } TEST_P(DetectNotInstantiatedTest, Used) {}
// This would make the test failure from the above go away. // This would make the test failure from the above go away.
// INSTANTIATE_TEST_SUITE_P(Fix, DetectNotInstantiatedTest, testing::Values(1)); // INSTANTIATE_TEST_SUITE_P(Fix, DetectNotInstantiatedTest, testing::Values(1));
template <typename T> template <typename T>
class TypedTest : public testing::Test { class TypedTest : public testing::Test {};
};
TYPED_TEST_SUITE(TypedTest, testing::Types<int>); TYPED_TEST_SUITE(TypedTest, testing::Types<int>);
TYPED_TEST(TypedTest, Success) { TYPED_TEST(TypedTest, Success) { EXPECT_EQ(0, TypeParam()); }
EXPECT_EQ(0, TypeParam());
}
TYPED_TEST(TypedTest, Failure) { TYPED_TEST(TypedTest, Failure) {
EXPECT_EQ(1, TypeParam()) << "Expected failure"; EXPECT_EQ(1, TypeParam()) << "Expected failure";
...@@ -781,14 +729,11 @@ TYPED_TEST(TypedTestWithNames, Success) {} ...@@ -781,14 +729,11 @@ TYPED_TEST(TypedTestWithNames, Success) {}
TYPED_TEST(TypedTestWithNames, Failure) { FAIL(); } TYPED_TEST(TypedTestWithNames, Failure) { FAIL(); }
template <typename T> template <typename T>
class TypedTestP : public testing::Test { class TypedTestP : public testing::Test {};
};
TYPED_TEST_SUITE_P(TypedTestP); TYPED_TEST_SUITE_P(TypedTestP);
TYPED_TEST_P(TypedTestP, Success) { TYPED_TEST_P(TypedTestP, Success) { EXPECT_EQ(0U, TypeParam()); }
EXPECT_EQ(0U, TypeParam());
}
TYPED_TEST_P(TypedTestP, Failure) { TYPED_TEST_P(TypedTestP, Failure) {
EXPECT_EQ(1U, TypeParam()) << "Expected failure"; EXPECT_EQ(1U, TypeParam()) << "Expected failure";
...@@ -813,7 +758,7 @@ class TypedTestPNames { ...@@ -813,7 +758,7 @@ class TypedTestPNames {
}; };
INSTANTIATE_TYPED_TEST_SUITE_P(UnsignedCustomName, TypedTestP, UnsignedTypes, INSTANTIATE_TYPED_TEST_SUITE_P(UnsignedCustomName, TypedTestP, UnsignedTypes,
TypedTestPNames); TypedTestPNames);
template <typename T> template <typename T>
class DetectNotInstantiatedTypesTest : public testing::Test {}; class DetectNotInstantiatedTypesTest : public testing::Test {};
...@@ -835,34 +780,28 @@ REGISTER_TYPED_TEST_SUITE_P(DetectNotInstantiatedTypesTest, Used); ...@@ -835,34 +780,28 @@ REGISTER_TYPED_TEST_SUITE_P(DetectNotInstantiatedTypesTest, Used);
// We rely on the golden file to verify that tests whose test case // We rely on the golden file to verify that tests whose test case
// name ends with DeathTest are run first. // name ends with DeathTest are run first.
TEST(ADeathTest, ShouldRunFirst) { TEST(ADeathTest, ShouldRunFirst) {}
}
// We rely on the golden file to verify that typed tests whose test // We rely on the golden file to verify that typed tests whose test
// case name ends with DeathTest are run first. // case name ends with DeathTest are run first.
template <typename T> template <typename T>
class ATypedDeathTest : public testing::Test { class ATypedDeathTest : public testing::Test {};
};
typedef testing::Types<int, double> NumericTypes; typedef testing::Types<int, double> NumericTypes;
TYPED_TEST_SUITE(ATypedDeathTest, NumericTypes); TYPED_TEST_SUITE(ATypedDeathTest, NumericTypes);
TYPED_TEST(ATypedDeathTest, ShouldRunFirst) { TYPED_TEST(ATypedDeathTest, ShouldRunFirst) {}
}
// We rely on the golden file to verify that type-parameterized tests // We rely on the golden file to verify that type-parameterized tests
// whose test case name ends with DeathTest are run first. // whose test case name ends with DeathTest are run first.
template <typename T> template <typename T>
class ATypeParamDeathTest : public testing::Test { class ATypeParamDeathTest : public testing::Test {};
};
TYPED_TEST_SUITE_P(ATypeParamDeathTest); TYPED_TEST_SUITE_P(ATypeParamDeathTest);
TYPED_TEST_P(ATypeParamDeathTest, ShouldRunFirst) { TYPED_TEST_P(ATypeParamDeathTest, ShouldRunFirst) {}
}
REGISTER_TYPED_TEST_SUITE_P(ATypeParamDeathTest, ShouldRunFirst); REGISTER_TYPED_TEST_SUITE_P(ATypeParamDeathTest, ShouldRunFirst);
...@@ -874,10 +813,7 @@ INSTANTIATE_TYPED_TEST_SUITE_P(My, ATypeParamDeathTest, NumericTypes); ...@@ -874,10 +813,7 @@ INSTANTIATE_TYPED_TEST_SUITE_P(My, ATypeParamDeathTest, NumericTypes);
// EXPECT_{,NON}FATAL_FAILURE{,_ON_ALL_THREADS}. // EXPECT_{,NON}FATAL_FAILURE{,_ON_ALL_THREADS}.
class ExpectFailureTest : public testing::Test { class ExpectFailureTest : public testing::Test {
public: // Must be public and not protected due to a bug in g++ 3.4.2. public: // Must be public and not protected due to a bug in g++ 3.4.2.
enum FailureMode { enum FailureMode { FATAL_FAILURE, NONFATAL_FAILURE };
FATAL_FAILURE,
NONFATAL_FAILURE
};
static void AddFailure(FailureMode failure) { static void AddFailure(FailureMode failure) {
if (failure == FATAL_FAILURE) { if (failure == FATAL_FAILURE) {
FAIL() << "Expected fatal failure."; FAIL() << "Expected fatal failure.";
...@@ -893,11 +829,13 @@ TEST_F(ExpectFailureTest, ExpectFatalFailure) { ...@@ -893,11 +829,13 @@ TEST_F(ExpectFailureTest, ExpectFatalFailure) {
EXPECT_FATAL_FAILURE(SUCCEED(), "Expected fatal failure."); EXPECT_FATAL_FAILURE(SUCCEED(), "Expected fatal failure.");
// Expected fatal failure, but got a non-fatal failure. // Expected fatal failure, but got a non-fatal failure.
printf("(expecting 1 failure)\n"); printf("(expecting 1 failure)\n");
EXPECT_FATAL_FAILURE(AddFailure(NONFATAL_FAILURE), "Expected non-fatal " EXPECT_FATAL_FAILURE(AddFailure(NONFATAL_FAILURE),
"Expected non-fatal "
"failure."); "failure.");
// Wrong message. // Wrong message.
printf("(expecting 1 failure)\n"); printf("(expecting 1 failure)\n");
EXPECT_FATAL_FAILURE(AddFailure(FATAL_FAILURE), "Some other fatal failure " EXPECT_FATAL_FAILURE(AddFailure(FATAL_FAILURE),
"Some other fatal failure "
"expected."); "expected.");
} }
...@@ -910,7 +848,8 @@ TEST_F(ExpectFailureTest, ExpectNonFatalFailure) { ...@@ -910,7 +848,8 @@ TEST_F(ExpectFailureTest, ExpectNonFatalFailure) {
EXPECT_NONFATAL_FAILURE(AddFailure(FATAL_FAILURE), "Expected fatal failure."); EXPECT_NONFATAL_FAILURE(AddFailure(FATAL_FAILURE), "Expected fatal failure.");
// Wrong message. // Wrong message.
printf("(expecting 1 failure)\n"); printf("(expecting 1 failure)\n");
EXPECT_NONFATAL_FAILURE(AddFailure(NONFATAL_FAILURE), "Some other non-fatal " EXPECT_NONFATAL_FAILURE(AddFailure(NONFATAL_FAILURE),
"Some other non-fatal "
"failure."); "failure.");
} }
...@@ -975,7 +914,8 @@ TEST_F(ExpectFailureTest, ExpectFatalFailureOnAllThreads) { ...@@ -975,7 +914,8 @@ TEST_F(ExpectFailureTest, ExpectFatalFailureOnAllThreads) {
TEST_F(ExpectFailureTest, ExpectNonFatalFailureOnAllThreads) { TEST_F(ExpectFailureTest, ExpectNonFatalFailureOnAllThreads) {
// Expected non-fatal failure, but succeeds. // Expected non-fatal failure, but succeeds.
printf("(expecting 1 failure)\n"); printf("(expecting 1 failure)\n");
EXPECT_NONFATAL_FAILURE_ON_ALL_THREADS(SUCCEED(), "Expected non-fatal " EXPECT_NONFATAL_FAILURE_ON_ALL_THREADS(SUCCEED(),
"Expected non-fatal "
"failure."); "failure.");
// Expected non-fatal failure, but got a fatal failure. // Expected non-fatal failure, but got a fatal failure.
printf("(expecting 1 failure)\n"); printf("(expecting 1 failure)\n");
...@@ -1064,16 +1004,14 @@ class TestSuiteThatFailsToSetUp : public testing::Test { ...@@ -1064,16 +1004,14 @@ class TestSuiteThatFailsToSetUp : public testing::Test {
public: public:
static void SetUpTestSuite() { EXPECT_TRUE(false); } static void SetUpTestSuite() { EXPECT_TRUE(false); }
}; };
TEST_F(TestSuiteThatFailsToSetUp, ShouldNotRun) { TEST_F(TestSuiteThatFailsToSetUp, ShouldNotRun) { std::abort(); }
std::abort();
}
// The main function. // The main function.
// //
// The idea is to use Google Test to run all the tests we have defined (some // The idea is to use Google Test to run all the tests we have defined (some
// of them are intended to fail), and then compare the test results // of them are intended to fail), and then compare the test results
// with the "golden" file. // with the "golden" file.
int main(int argc, char **argv) { int main(int argc, char** argv) {
GTEST_FLAG_SET(print_time, false); GTEST_FLAG_SET(print_time, false);
// We just run the tests, knowing some of them are intended to fail. // We just run the tests, knowing some of them are intended to fail.
...@@ -1092,17 +1030,16 @@ int main(int argc, char **argv) { ...@@ -1092,17 +1030,16 @@ int main(int argc, char **argv) {
if (GTEST_FLAG_GET(internal_run_death_test) != "") { if (GTEST_FLAG_GET(internal_run_death_test) != "") {
// Skip the usual output capturing if we're running as the child // Skip the usual output capturing if we're running as the child
// process of an threadsafe-style death test. // process of an threadsafe-style death test.
# if GTEST_OS_WINDOWS #if GTEST_OS_WINDOWS
posix::FReopen("nul:", "w", stdout); posix::FReopen("nul:", "w", stdout);
# else #else
posix::FReopen("/dev/null", "w", stdout); posix::FReopen("/dev/null", "w", stdout);
# endif // GTEST_OS_WINDOWS #endif // GTEST_OS_WINDOWS
return RUN_ALL_TESTS(); return RUN_ALL_TESTS();
} }
#endif // GTEST_HAS_DEATH_TEST #endif // GTEST_HAS_DEATH_TEST
if (internal_skip_environment_and_ad_hoc_tests) if (internal_skip_environment_and_ad_hoc_tests) return RUN_ALL_TESTS();
return RUN_ALL_TESTS();
// Registers two global test environments. // Registers two global test environments.
// The golden file verifies that they are set up in the order they // The golden file verifies that they are set up in the order they
...@@ -1110,7 +1047,7 @@ int main(int argc, char **argv) { ...@@ -1110,7 +1047,7 @@ int main(int argc, char **argv) {
testing::AddGlobalTestEnvironment(new FooEnvironment); testing::AddGlobalTestEnvironment(new FooEnvironment);
testing::AddGlobalTestEnvironment(new BarEnvironment); testing::AddGlobalTestEnvironment(new BarEnvironment);
#if _MSC_VER #if _MSC_VER
GTEST_DISABLE_MSC_WARNINGS_POP_() // 4127 GTEST_DISABLE_MSC_WARNINGS_POP_() // 4127
#endif // _MSC_VER #endif // _MSC_VER
return RunAllTests(); return RunAllTests();
} }
...@@ -27,17 +27,14 @@ ...@@ -27,17 +27,14 @@
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include "gtest/gtest.h" #include "gtest/gtest.h"
namespace { namespace {
class DummyTest : public ::testing::TestWithParam<const char *> {}; class DummyTest : public ::testing::TestWithParam<const char *> {};
TEST_P(DummyTest, Dummy) { TEST_P(DummyTest, Dummy) {}
}
INSTANTIATE_TEST_SUITE_P(InvalidTestName, INSTANTIATE_TEST_SUITE_P(InvalidTestName, DummyTest,
DummyTest,
::testing::Values("InvalidWithQuotes"), ::testing::Values("InvalidWithQuotes"),
::testing::PrintToStringParamName()); ::testing::PrintToStringParamName());
...@@ -47,4 +44,3 @@ int main(int argc, char *argv[]) { ...@@ -47,4 +44,3 @@ int main(int argc, char *argv[]) {
testing::InitGoogleTest(&argc, argv); testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS(); return RUN_ALL_TESTS();
} }
...@@ -27,22 +27,19 @@ ...@@ -27,22 +27,19 @@
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include "gtest/gtest.h" #include "gtest/gtest.h"
namespace { namespace {
class DummyTest : public ::testing::TestWithParam<const char *> {}; class DummyTest : public ::testing::TestWithParam<const char *> {};
std::string StringParamTestSuffix( std::string StringParamTestSuffix(
const testing::TestParamInfo<const char*>& info) { const testing::TestParamInfo<const char *> &info) {
return std::string(info.param); return std::string(info.param);
} }
TEST_P(DummyTest, Dummy) { TEST_P(DummyTest, Dummy) {}
}
INSTANTIATE_TEST_SUITE_P(DuplicateTestNames, INSTANTIATE_TEST_SUITE_P(DuplicateTestNames, DummyTest,
DummyTest,
::testing::Values("a", "b", "a", "c"), ::testing::Values("a", "b", "a", "c"),
StringParamTestSuffix); StringParamTestSuffix);
} // namespace } // namespace
...@@ -51,5 +48,3 @@ int main(int argc, char *argv[]) { ...@@ -51,5 +48,3 @@ int main(int argc, char *argv[]) {
testing::InitGoogleTest(&argc, argv); testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS(); return RUN_ALL_TESTS();
} }
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment