108 #ifndef GTEST_INCLUDE_GTEST_GTEST_SPI_H_ 109 #define GTEST_INCLUDE_GTEST_GTEST_SPI_H_ 126 class GTEST_API_ ScopedFakeTestPartResultReporter
127 :
public TestPartResultReporterInterface {
131 INTERCEPT_ONLY_CURRENT_THREAD,
132 INTERCEPT_ALL_THREADS
139 explicit ScopedFakeTestPartResultReporter(TestPartResultArray* result);
142 ScopedFakeTestPartResultReporter(InterceptMode intercept_mode,
143 TestPartResultArray* result);
146 ~ScopedFakeTestPartResultReporter()
override;
153 void ReportTestPartResult(
const TestPartResult& result)
override;
158 const InterceptMode intercept_mode_;
159 TestPartResultReporterInterface* old_reporter_;
160 TestPartResultArray*
const result_;
175 SingleFailureChecker(
const TestPartResultArray* results,
176 TestPartResult::Type type,
const std::string& substr);
177 ~SingleFailureChecker();
179 const TestPartResultArray*
const results_;
180 const TestPartResult::Type type_;
215 #define EXPECT_FATAL_FAILURE(statement, substr) \ 217 class GTestExpectFatalFailureHelper {\ 219 static void Execute() { statement; }\ 221 ::testing::TestPartResultArray gtest_failures;\ 222 ::testing::internal::SingleFailureChecker gtest_checker(\ 223 >est_failures, ::testing::TestPartResult::kFatalFailure, (substr));\ 225 ::testing::ScopedFakeTestPartResultReporter gtest_reporter(\ 226 ::testing::ScopedFakeTestPartResultReporter:: \ 227 INTERCEPT_ONLY_CURRENT_THREAD, >est_failures);\ 228 GTestExpectFatalFailureHelper::Execute();\ 230 } while (::testing::internal::AlwaysFalse()) 232 #define EXPECT_FATAL_FAILURE_ON_ALL_THREADS(statement, substr) \ 234 class GTestExpectFatalFailureHelper {\ 236 static void Execute() { statement; }\ 238 ::testing::TestPartResultArray gtest_failures;\ 239 ::testing::internal::SingleFailureChecker gtest_checker(\ 240 >est_failures, ::testing::TestPartResult::kFatalFailure, (substr));\ 242 ::testing::ScopedFakeTestPartResultReporter gtest_reporter(\ 243 ::testing::ScopedFakeTestPartResultReporter:: \ 244 INTERCEPT_ALL_THREADS, >est_failures);\ 245 GTestExpectFatalFailureHelper::Execute();\ 247 } while (::testing::internal::AlwaysFalse()) 281 #define EXPECT_NONFATAL_FAILURE(statement, substr) \ 283 ::testing::TestPartResultArray gtest_failures;\ 284 ::testing::internal::SingleFailureChecker gtest_checker(\ 285 >est_failures, ::testing::TestPartResult::kNonFatalFailure, \ 288 ::testing::ScopedFakeTestPartResultReporter gtest_reporter(\ 289 ::testing::ScopedFakeTestPartResultReporter:: \ 290 INTERCEPT_ONLY_CURRENT_THREAD, >est_failures);\ 291 if (::testing::internal::AlwaysTrue()) { statement; }\ 293 } while (::testing::internal::AlwaysFalse()) 295 #define EXPECT_NONFATAL_FAILURE_ON_ALL_THREADS(statement, substr) \ 297 ::testing::TestPartResultArray gtest_failures;\ 298 ::testing::internal::SingleFailureChecker gtest_checker(\ 299 >est_failures, ::testing::TestPartResult::kNonFatalFailure, \ 302 ::testing::ScopedFakeTestPartResultReporter gtest_reporter(\ 303 ::testing::ScopedFakeTestPartResultReporter::INTERCEPT_ALL_THREADS, \ 305 if (::testing::internal::AlwaysTrue()) { statement; }\ 307 } while (::testing::internal::AlwaysFalse()) 309 #endif // GTEST_INCLUDE_GTEST_GTEST_SPI_H_ 331 # define GTEST_HAS_GETTIMEOFDAY_ 1 337 # include <strings.h> 338 # include <sys/mman.h> 339 # include <sys/time.h> 344 # define GTEST_HAS_GETTIMEOFDAY_ 1 345 # include <sys/time.h> 348 # include <strings.h> 350 #elif GTEST_OS_WINDOWS_MOBILE // We are on Windows CE. 352 # include <windows.h> 355 #elif GTEST_OS_WINDOWS // We are on Windows proper. 358 # include <sys/timeb.h> 359 # include <sys/types.h> 360 # include <sys/stat.h> 362 # if GTEST_OS_WINDOWS_MINGW 364 # define GTEST_HAS_GETTIMEOFDAY_ 1 365 # include <sys/time.h> 366 # endif // GTEST_OS_WINDOWS_MINGW 370 # include <windows.h> 376 # define GTEST_HAS_GETTIMEOFDAY_ 1 380 # include <sys/time.h> 383 #endif // GTEST_OS_LINUX 385 #if GTEST_HAS_EXCEPTIONS 386 # include <stdexcept> 389 #if GTEST_CAN_STREAM_RESULTS_ 390 # include <arpa/inet.h> 392 # include <sys/socket.h> 393 # include <sys/types.h> 429 #ifndef GTEST_SRC_GTEST_INTERNAL_INL_H_ 430 #define GTEST_SRC_GTEST_INTERNAL_INL_H_ 434 #endif // !_WIN32_WCE 445 #if GTEST_CAN_STREAM_RESULTS_ 446 # include <arpa/inet.h> 451 # include <windows.h> 452 #endif // GTEST_OS_WINDOWS 474 const char kAlsoRunDisabledTestsFlag[] =
"also_run_disabled_tests";
475 const char kBreakOnFailureFlag[] =
"break_on_failure";
476 const char kCatchExceptionsFlag[] =
"catch_exceptions";
477 const char kColorFlag[] =
"color";
478 const char kFilterFlag[] =
"filter";
479 const char kListTestsFlag[] =
"list_tests";
480 const char kOutputFlag[] =
"output";
481 const char kPrintTimeFlag[] =
"print_time";
482 const char kPrintUTF8Flag[] =
"print_utf8";
483 const char kRandomSeedFlag[] =
"random_seed";
484 const char kRepeatFlag[] =
"repeat";
485 const char kShuffleFlag[] =
"shuffle";
486 const char kStackTraceDepthFlag[] =
"stack_trace_depth";
487 const char kStreamResultToFlag[] =
"stream_result_to";
488 const char kThrowOnFailureFlag[] =
"throw_on_failure";
489 const char kFlagfileFlag[] =
"flagfile";
492 const int kMaxRandomSeed = 99999;
502 GTEST_API_ bool ShouldUseColor(
bool stdout_is_tty);
518 const char* str,
const char* flag,
Int32* value);
522 inline int GetRandomSeedFromFlag(
Int32 random_seed_flag) {
523 const unsigned int raw_seed = (random_seed_flag == 0) ?
524 static_cast<unsigned int>(GetTimeInMillis()) :
525 static_cast<unsigned int>(random_seed_flag);
529 const int normalized_seed =
530 static_cast<int>((raw_seed - 1U) %
531 static_cast<unsigned int>(kMaxRandomSeed)) + 1;
532 return normalized_seed;
538 inline int GetNextRandomSeed(
int seed) {
540 <<
"Invalid random seed " << seed <<
" - must be in [1, " 541 << kMaxRandomSeed <<
"].";
542 const int next_seed = seed + 1;
543 return (next_seed > kMaxRandomSeed) ? 1 : next_seed;
548 class GTestFlagSaver {
552 also_run_disabled_tests_ =
GTEST_FLAG(also_run_disabled_tests);
553 break_on_failure_ =
GTEST_FLAG(break_on_failure);
554 catch_exceptions_ =
GTEST_FLAG(catch_exceptions);
556 death_test_style_ =
GTEST_FLAG(death_test_style);
557 death_test_use_fork_ =
GTEST_FLAG(death_test_use_fork);
559 internal_run_death_test_ =
GTEST_FLAG(internal_run_death_test);
567 stack_trace_depth_ =
GTEST_FLAG(stack_trace_depth);
568 stream_result_to_ =
GTEST_FLAG(stream_result_to);
569 throw_on_failure_ =
GTEST_FLAG(throw_on_failure);
574 GTEST_FLAG(also_run_disabled_tests) = also_run_disabled_tests_;
575 GTEST_FLAG(break_on_failure) = break_on_failure_;
576 GTEST_FLAG(catch_exceptions) = catch_exceptions_;
578 GTEST_FLAG(death_test_style) = death_test_style_;
579 GTEST_FLAG(death_test_use_fork) = death_test_use_fork_;
581 GTEST_FLAG(internal_run_death_test) = internal_run_death_test_;
589 GTEST_FLAG(stack_trace_depth) = stack_trace_depth_;
590 GTEST_FLAG(stream_result_to) = stream_result_to_;
591 GTEST_FLAG(throw_on_failure) = throw_on_failure_;
596 bool also_run_disabled_tests_;
597 bool break_on_failure_;
598 bool catch_exceptions_;
601 bool death_test_use_fork_;
613 bool throw_on_failure_;
643 void WriteToShardStatusFileIfNeeded();
651 GTEST_API_ bool ShouldShard(
const char* total_shards_str,
652 const char* shard_index_str,
653 bool in_subprocess_for_death_test);
665 int total_shards,
int shard_index,
int test_id);
671 template <
class Container,
typename Predicate>
672 inline int CountIf(
const Container& c,
Predicate predicate) {
676 for (
typename Container::const_iterator it = c.begin(); it != c.end(); ++it) {
684 template <
class Container,
typename Functor>
685 void ForEach(
const Container& c, Functor functor) {
686 std::for_each(c.begin(), c.end(), functor);
691 template <
typename E>
692 inline E GetElementOr(
const std::vector<E>& v,
int i, E default_value) {
693 return (i < 0 || i >= static_cast<int>(v.size())) ? default_value : v[i];
700 template <
typename E>
701 void ShuffleRange(internal::Random* random,
int begin,
int end,
703 const int size =
static_cast<int>(v->size());
705 <<
"Invalid shuffle range start " << begin <<
": must be in range [0, " 708 <<
"Invalid shuffle range finish " << end <<
": must be in range [" 709 << begin <<
", " <<
size <<
"].";
713 for (
int range_width = end - begin; range_width >= 2; range_width--) {
714 const int last_in_range = begin + range_width - 1;
715 const int selected = begin + random->Generate(range_width);
716 std::swap((*v)[selected], (*v)[last_in_range]);
721 template <
typename E>
722 inline void Shuffle(internal::Random* random, std::vector<E>* v) {
723 ShuffleRange(random, 0, static_cast<int>(v->size()), v);
728 template <
typename T>
729 static void Delete(T* x) {
736 class TestPropertyKeyIs {
741 explicit TestPropertyKeyIs(
const std::string& key) : key_(key) {}
744 bool operator()(
const TestProperty& test_property)
const {
745 return test_property.key() == key_;
781 static bool PatternMatchesString(
const char *pattern,
const char *str);
785 static bool FilterMatchesTest(
const std::string& test_suite_name,
794 static int GTestShouldProcessSEH(DWORD exception_code);
795 #endif // GTEST_OS_WINDOWS 804 GTEST_API_ FilePath GetCurrentExecutableName();
807 class OsStackTraceGetterInterface {
809 OsStackTraceGetterInterface() {}
810 virtual ~OsStackTraceGetterInterface() {}
818 virtual std::string CurrentStackTrace(
int max_depth,
int skip_count) = 0;
823 virtual void UponLeavingGTest() = 0;
827 static const char*
const kElidedFramesMarker;
834 class OsStackTraceGetter :
public OsStackTraceGetterInterface {
836 OsStackTraceGetter() {}
838 std::string CurrentStackTrace(
int max_depth,
int skip_count)
override;
839 void UponLeavingGTest()
override;
849 void* caller_frame_ =
nullptr;
850 #endif // GTEST_HAS_ABSL 864 class DefaultGlobalTestPartResultReporter
865 :
public TestPartResultReporterInterface {
867 explicit DefaultGlobalTestPartResultReporter(UnitTestImpl* unit_test);
870 void ReportTestPartResult(
const TestPartResult& result)
override;
873 UnitTestImpl*
const unit_test_;
880 class DefaultPerThreadTestPartResultReporter
881 :
public TestPartResultReporterInterface {
883 explicit DefaultPerThreadTestPartResultReporter(UnitTestImpl* unit_test);
886 void ReportTestPartResult(
const TestPartResult& result)
override;
889 UnitTestImpl*
const unit_test_;
900 explicit UnitTestImpl(UnitTest* parent);
901 virtual ~UnitTestImpl();
911 TestPartResultReporterInterface* GetGlobalTestPartResultReporter();
914 void SetGlobalTestPartResultReporter(
915 TestPartResultReporterInterface* reporter);
918 TestPartResultReporterInterface* GetTestPartResultReporterForCurrentThread();
921 void SetTestPartResultReporterForCurrentThread(
922 TestPartResultReporterInterface* reporter);
925 int successful_test_suite_count()
const;
928 int failed_test_suite_count()
const;
931 int total_test_suite_count()
const;
935 int test_suite_to_run_count()
const;
938 int successful_test_count()
const;
941 int skipped_test_count()
const;
944 int failed_test_count()
const;
947 int reportable_disabled_test_count()
const;
950 int disabled_test_count()
const;
953 int reportable_test_count()
const;
956 int total_test_count()
const;
959 int test_to_run_count()
const;
963 TimeInMillis start_timestamp()
const {
return start_timestamp_; }
966 TimeInMillis elapsed_time()
const {
return elapsed_time_; }
969 bool Passed()
const {
return !Failed(); }
973 bool Failed()
const {
974 return failed_test_suite_count() > 0 || ad_hoc_test_result()->Failed();
979 const TestSuite* GetTestSuite(
int i)
const {
980 const int index = GetElementOr(test_suite_indices_, i, -1);
981 return index < 0 ? nullptr : test_suites_[i];
985 #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_ 986 const TestCase* GetTestCase(
int i)
const {
return GetTestSuite(i); }
987 #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_ 991 TestSuite* GetMutableSuiteCase(
int i) {
992 const int index = GetElementOr(test_suite_indices_, i, -1);
993 return index < 0 ? nullptr : test_suites_[index];
997 TestEventListeners* listeners() {
return &listeners_; }
1001 TestResult* current_test_result();
1004 const TestResult* ad_hoc_test_result()
const {
return &ad_hoc_test_result_; }
1011 void set_os_stack_trace_getter(OsStackTraceGetterInterface* getter);
1016 OsStackTraceGetterInterface* os_stack_trace_getter();
1040 TestSuite* GetTestSuite(
const char* test_suite_name,
const char* type_param,
1045 #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_ 1046 TestCase* GetTestCase(
const char* test_case_name,
const char* type_param,
1049 return GetTestSuite(test_case_name, type_param, set_up_tc, tear_down_tc);
1051 #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_ 1062 TestInfo* test_info) {
1070 if (original_working_dir_.IsEmpty()) {
1071 original_working_dir_.Set(FilePath::GetCurrentDir());
1073 <<
"Failed to get the current working directory.";
1076 GetTestSuite(test_info->test_suite_name(), test_info->type_param(),
1077 set_up_tc, tear_down_tc)
1078 ->AddTestInfo(test_info);
1083 internal::ParameterizedTestSuiteRegistry& parameterized_test_registry() {
1084 return parameterized_test_registry_;
1088 void set_current_test_suite(TestSuite* a_current_test_suite) {
1089 current_test_suite_ = a_current_test_suite;
1095 void set_current_test_info(TestInfo* a_current_test_info) {
1096 current_test_info_ = a_current_test_info;
1105 void RegisterParameterizedTests();
1114 void ClearNonAdHocTestResult() {
1115 ForEach(test_suites_, TestSuite::ClearTestSuiteResult);
1119 void ClearAdHocTestResult() {
1120 ad_hoc_test_result_.Clear();
1127 void RecordProperty(
const TestProperty& test_property);
1129 enum ReactionToSharding {
1130 HONOR_SHARDING_PROTOCOL,
1131 IGNORE_SHARDING_PROTOCOL
1140 int FilterTests(ReactionToSharding shard_tests);
1143 void ListTestsMatchingFilter();
1145 const TestSuite* current_test_suite()
const {
return current_test_suite_; }
1146 TestInfo* current_test_info() {
return current_test_info_; }
1147 const TestInfo* current_test_info()
const {
return current_test_info_; }
1151 std::vector<Environment*>& environments() {
return environments_; }
1154 std::vector<TraceInfo>& gtest_trace_stack() {
1155 return *(gtest_trace_stack_.pointer());
1157 const std::vector<TraceInfo>& gtest_trace_stack()
const {
1158 return gtest_trace_stack_.get();
1161 #if GTEST_HAS_DEATH_TEST 1162 void InitDeathTestSubprocessControlInfo() {
1163 internal_run_death_test_flag_.reset(ParseInternalRunDeathTestFlag());
1169 const InternalRunDeathTestFlag* internal_run_death_test_flag()
const {
1170 return internal_run_death_test_flag_.get();
1174 internal::DeathTestFactory* death_test_factory() {
1175 return death_test_factory_.get();
1178 void SuppressTestEventsIfInSubprocess();
1180 friend class ReplaceDeathTestFactory;
1181 #endif // GTEST_HAS_DEATH_TEST 1185 void ConfigureXmlOutput();
1187 #if GTEST_CAN_STREAM_RESULTS_ 1190 void ConfigureStreamingOutput();
1198 void PostFlagParsingInit();
1201 int random_seed()
const {
return random_seed_; }
1204 internal::Random* random() {
return &random_; }
1208 void ShuffleTests();
1211 void UnshuffleTests();
1215 bool catch_exceptions()
const {
return catch_exceptions_; }
1218 friend class ::testing::UnitTest;
1222 void set_catch_exceptions(
bool value) { catch_exceptions_ = value; }
1225 UnitTest*
const parent_;
1229 internal::FilePath original_working_dir_;
1232 DefaultGlobalTestPartResultReporter default_global_test_part_result_reporter_;
1233 DefaultPerThreadTestPartResultReporter
1234 default_per_thread_test_part_result_reporter_;
1237 TestPartResultReporterInterface* global_test_part_result_repoter_;
1240 internal::Mutex global_test_part_result_reporter_mutex_;
1243 internal::ThreadLocal<TestPartResultReporterInterface*>
1244 per_thread_test_part_result_reporter_;
1248 std::vector<Environment*> environments_;
1252 std::vector<TestSuite*> test_suites_;
1258 std::vector<int> test_suite_indices_;
1262 internal::ParameterizedTestSuiteRegistry parameterized_test_registry_;
1265 bool parameterized_tests_registered_;
1268 int last_death_test_suite_;
1274 TestSuite* current_test_suite_;
1280 TestInfo* current_test_info_;
1290 TestResult ad_hoc_test_result_;
1294 TestEventListeners listeners_;
1300 OsStackTraceGetterInterface* os_stack_trace_getter_;
1303 bool post_flag_parse_init_performed_;
1309 internal::Random random_;
1318 #if GTEST_HAS_DEATH_TEST 1321 std::unique_ptr<InternalRunDeathTestFlag> internal_run_death_test_flag_;
1322 std::unique_ptr<internal::DeathTestFactory> death_test_factory_;
1323 #endif // GTEST_HAS_DEATH_TEST 1326 internal::ThreadLocal<std::vector<TraceInfo> > gtest_trace_stack_;
1330 bool catch_exceptions_;
1337 inline UnitTestImpl* GetUnitTestImpl() {
1338 return UnitTest::GetInstance()->impl();
1341 #if GTEST_USES_SIMPLE_RE 1345 GTEST_API_ bool IsInSet(
char ch,
const char* str);
1352 GTEST_API_ bool AtomMatchesChar(
bool escaped,
char pattern,
char ch);
1353 GTEST_API_ bool ValidateRegex(
const char* regex);
1354 GTEST_API_ bool MatchRegexAtHead(
const char* regex,
const char* str);
1355 GTEST_API_ bool MatchRepetitionAndRegexAtHead(
1356 bool escaped,
char ch,
char repeat,
const char* regex,
const char* str);
1357 GTEST_API_ bool MatchRegexAnywhere(
const char* regex,
const char* str);
1359 #endif // GTEST_USES_SIMPLE_RE 1363 GTEST_API_ void ParseGoogleTestFlagsOnly(
int* argc,
char** argv);
1364 GTEST_API_ void ParseGoogleTestFlagsOnly(
int* argc,
wchar_t** argv);
1366 #if GTEST_HAS_DEATH_TEST 1376 template <
typename Integer>
1381 if (str.empty() || !
IsDigit(str[0])) {
1390 # if GTEST_OS_WINDOWS && !defined(__GNUC__) 1393 typedef unsigned __int64 BiggestConvertible;
1394 const BiggestConvertible parsed = _strtoui64(str.c_str(), &end, 10);
1398 typedef unsigned long long BiggestConvertible;
1399 const BiggestConvertible parsed = strtoull(str.c_str(), &end, 10);
1401 # endif // GTEST_OS_WINDOWS && !defined(__GNUC__) 1403 const bool parse_success = *end ==
'\0' && errno == 0;
1407 const Integer result =
static_cast<Integer
>(parsed);
1408 if (parse_success && static_cast<BiggestConvertible>(result) == parsed) {
1414 #endif // GTEST_HAS_DEATH_TEST 1422 class TestResultAccessor {
1424 static void RecordProperty(TestResult* test_result,
1426 const TestProperty& property) {
1427 test_result->RecordProperty(xml_element, property);
1430 static void ClearTestPartResults(TestResult* test_result) {
1431 test_result->ClearTestPartResults();
1434 static const std::vector<testing::TestPartResult>& test_part_results(
1435 const TestResult& test_result) {
1436 return test_result.test_part_results();
1440 #if GTEST_CAN_STREAM_RESULTS_ 1443 class StreamingListener :
public EmptyTestEventListener {
1446 class AbstractSocketWriter {
1448 virtual ~AbstractSocketWriter() {}
1451 virtual void Send(
const std::string& message) = 0;
1454 virtual void CloseConnection() {}
1457 void SendLn(
const std::string& message) { Send(message +
"\n"); }
1461 class SocketWriter :
public AbstractSocketWriter {
1464 : sockfd_(-1), host_name_(host), port_num_(port) {
1468 ~SocketWriter()
override {
1476 <<
"Send() can be called only when there is a connection.";
1478 const int len =
static_cast<int>(message.length());
1479 if (write(sockfd_, message.c_str(), len) != len) {
1481 <<
"stream_result_to: failed to stream to " 1482 << host_name_ <<
":" << port_num_;
1488 void MakeConnection();
1491 void CloseConnection()
override {
1493 <<
"CloseConnection() can be called only when there is a connection.";
1510 : socket_writer_(
new SocketWriter(host, port)) {
1514 explicit StreamingListener(AbstractSocketWriter* socket_writer)
1515 : socket_writer_(socket_writer) { Start(); }
1517 void OnTestProgramStart(
const UnitTest& )
override {
1518 SendLn(
"event=TestProgramStart");
1521 void OnTestProgramEnd(
const UnitTest& unit_test)
override {
1524 SendLn(
"event=TestProgramEnd&passed=" + FormatBool(unit_test.Passed()));
1527 socket_writer_->CloseConnection();
1530 void OnTestIterationStart(
const UnitTest& ,
1531 int iteration)
override {
1532 SendLn(
"event=TestIterationStart&iteration=" +
1536 void OnTestIterationEnd(
const UnitTest& unit_test,
1538 SendLn(
"event=TestIterationEnd&passed=" +
1539 FormatBool(unit_test.Passed()) +
"&elapsed_time=" +
1545 void OnTestCaseStart(
const TestCase& test_case)
override {
1546 SendLn(
std::string(
"event=TestCaseStart&name=") + test_case.name());
1551 void OnTestCaseEnd(
const TestCase& test_case)
override {
1552 SendLn(
"event=TestCaseEnd&passed=" + FormatBool(test_case.Passed()) +
1557 void OnTestStart(
const TestInfo& test_info)
override {
1558 SendLn(
std::string(
"event=TestStart&name=") + test_info.name());
1561 void OnTestEnd(
const TestInfo& test_info)
override {
1562 SendLn(
"event=TestEnd&passed=" +
1563 FormatBool((test_info.result())->Passed()) +
1568 void OnTestPartResult(
const TestPartResult& test_part_result)
override {
1569 const char* file_name = test_part_result.file_name();
1570 if (file_name ==
nullptr) file_name =
"";
1571 SendLn(
"event=TestPartResult&file=" + UrlEncode(file_name) +
1573 "&message=" + UrlEncode(test_part_result.message()));
1578 void SendLn(
const std::string& message) { socket_writer_->SendLn(message); }
1582 void Start() { SendLn(
"gtest_streaming_protocol_version=1.0"); }
1584 std::string FormatBool(
bool value) {
return value ?
"1" :
"0"; }
1586 const std::unique_ptr<AbstractSocketWriter> socket_writer_;
1591 #endif // GTEST_CAN_STREAM_RESULTS_ 1598 #endif // GTEST_SRC_GTEST_INTERNAL_INL_H_ 1600 #if GTEST_OS_WINDOWS 1601 # define vsnprintf _vsnprintf 1602 #endif // GTEST_OS_WINDOWS 1605 #ifndef GTEST_OS_IOS 1606 #include <crt_externs.h> 1611 #include "absl/debugging/failure_signal_handler.h" 1612 #include "absl/debugging/stacktrace.h" 1613 #include "absl/debugging/symbolize.h" 1614 #include "absl/strings/str_cat.h" 1615 #endif // GTEST_HAS_ABSL 1619 using internal::CountIf;
1620 using internal::ForEach;
1621 using internal::GetElementOr;
1622 using internal::Shuffle;
1628 static const char kDisableTestFilter[] =
"DISABLED_*:*/DISABLED_*";
1633 static const char kDeathTestSuiteFilter[] =
"*DeathTest:*DeathTest/*";
1636 static const char kUniversalFilter[] =
"*";
1639 static const char kDefaultOutputFormat[] =
"xml";
1641 static const char kDefaultOutputFile[] =
"test_detail";
1644 static const char kTestShardIndex[] =
"GTEST_SHARD_INDEX";
1646 static const char kTestTotalShards[] =
"GTEST_TOTAL_SHARDS";
1648 static const char kTestShardStatusFile[] =
"GTEST_SHARD_STATUS_FILE";
1650 namespace internal {
1658 bool g_help_flag =
false;
1661 static FILE* OpenFileForWriting(
const std::string& output_file) {
1662 FILE* fileout =
nullptr;
1663 FilePath output_file_path(output_file);
1664 FilePath output_dir(output_file_path.RemoveFileName());
1666 if (output_dir.CreateDirectoriesRecursively()) {
1669 if (fileout ==
nullptr) {
1670 GTEST_LOG_(FATAL) <<
"Unable to open file \"" << output_file <<
"\"";
1679 static const char* GetDefaultFilter() {
1680 const char*
const testbridge_test_only =
1682 if (testbridge_test_only !=
nullptr) {
1683 return testbridge_test_only;
1685 return kUniversalFilter;
1689 also_run_disabled_tests,
1691 "Run disabled tests too, in addition to the tests normally being run.");
1696 "True iff a failed assertion should be a debugger break-point.");
1702 " should catch exceptions and treat them as test failures.");
1707 "Whether to use colors in the output. Valid values: yes, no, " 1708 "and auto. 'auto' means to use colors if the output is " 1709 "being sent to a terminal and the TERM environment variable " 1710 "is set to a terminal type that supports colors.");
1715 "A colon-separated list of glob (not regex) patterns " 1716 "for filtering the tests to run, optionally followed by a " 1717 "'-' and a : separated list of negative patterns (tests to " 1718 "exclude). A test is run if it matches one of the positive " 1719 "patterns and does not match any of the negative patterns.");
1722 install_failure_signal_handler,
1724 "If true and supported on the current platform, " GTEST_NAME_ " should " 1725 "install a signal handler that dumps debugging information when fatal " 1726 "signals are raised.");
1729 "List all tests without running them.");
1740 "A format (defaults to \"xml\" but can be specified to be \"json\"), " 1741 "optionally followed by a colon and an output file name or directory. " 1742 "A directory is indicated by a trailing pathname separator. " 1743 "Examples: \"xml:filename.xml\", \"xml::directoryname/\". " 1744 "If a directory is specified, output files will be created " 1745 "within that directory, with file-names based on the test " 1746 "executable's name and, if necessary, made unique by adding " 1753 " should display elapsed time in text output.");
1759 " prints UTF8 characters as text.");
1764 "Random number seed to use when shuffling test orders. Must be in range " 1765 "[1, 99999], or 0 to use a seed based on the current time.");
1770 "How many times to repeat each test. Specify a negative number " 1771 "for repeating forever. Useful for shaking out flaky tests.");
1774 show_internal_stack_frames,
false,
1775 "True iff " GTEST_NAME_ " should include internal stack frames when " 1776 "printing test failure stack traces.");
1782 " should randomize tests' order on every run.");
1787 "The maximum number of stack frames to print when an " 1788 "assertion fails. The valid range is 0 through 100, inclusive.");
1793 "This flag specifies the host name and the port number on which to stream " 1794 "test results. Example: \"localhost:555\". The flag is effective only on " 1800 "When this flag is specified, a failed assertion will throw an exception " 1801 "if exceptions are enabled or exit the program with a non-zero code " 1802 "otherwise. For use with an external test framework.");
1804 #if GTEST_USE_OWN_FLAGFILE_FLAG_ 1808 "This flag specifies the flagfile to read command-line flags from.");
1809 #endif // GTEST_USE_OWN_FLAGFILE_FLAG_ 1811 namespace internal {
1819 state_ =
static_cast<UInt32>(1103515245ULL*state_ + 12345U) %
kMaxRange;
1822 <<
"Cannot generate a number in the range [0, 0).";
1824 <<
"Generation of a number in [0, " << range <<
") was requested, " 1825 <<
"but this can only generate numbers in [0, " <<
kMaxRange <<
").";
1830 return state_ % range;
1836 static bool GTestIsInitialized() {
return GetArgvs().size() > 0; }
1841 static int SumOverTestSuiteList(
const std::vector<TestSuite*>& case_list,
1842 int (TestSuite::*method)()
const) {
1844 for (
size_t i = 0; i < case_list.size(); i++) {
1845 sum += (case_list[i]->*method)();
1851 static bool TestSuitePassed(
const TestSuite* test_suite) {
1852 return test_suite->should_run() && test_suite->Passed();
1856 static bool TestSuiteFailed(
const TestSuite* test_suite) {
1857 return test_suite->should_run() && test_suite->Failed();
1862 static bool ShouldRunTestSuite(
const TestSuite* test_suite) {
1863 return test_suite->should_run();
1870 const char* message)
1871 : data_(new AssertHelperData(type, file, line, message)) {
1874 AssertHelper::~AssertHelper() {
1879 void AssertHelper::operator=(
const Message& message)
const {
1880 UnitTest::GetInstance()->
1881 AddTestPartResult(data_->type, data_->file, data_->line,
1883 UnitTest::GetInstance()->impl()
1884 ->CurrentOsStackTraceExceptTop(1)
1890 static ::std::vector<std::string> g_argvs;
1892 ::std::vector<std::string>
GetArgvs() {
1893 #if defined(GTEST_CUSTOM_GET_ARGVS_) 1896 const auto& custom = GTEST_CUSTOM_GET_ARGVS_();
1897 return ::std::vector<std::string>(custom.begin(), custom.end());
1898 #else // defined(GTEST_CUSTOM_GET_ARGVS_) 1900 #endif // defined(GTEST_CUSTOM_GET_ARGVS_) 1905 FilePath GetCurrentExecutableName() {
1908 #if GTEST_OS_WINDOWS || GTEST_OS_OS2 1909 result.Set(FilePath(
GetArgvs()[0]).RemoveExtension(
"exe"));
1911 result.Set(FilePath(
GetArgvs()[0]));
1912 #endif // GTEST_OS_WINDOWS 1914 return result.RemoveDirectoryName();
1921 const char*
const gtest_output_flag =
GTEST_FLAG(output).c_str();
1922 const char*
const colon = strchr(gtest_output_flag,
':');
1923 return (colon ==
nullptr)
1925 : std::
string(gtest_output_flag, colon - gtest_output_flag);
1930 std::string UnitTestOptions::GetAbsolutePathToOutputFile() {
1931 const char*
const gtest_output_flag =
GTEST_FLAG(output).c_str();
1937 const char*
const colon = strchr(gtest_output_flag,
':');
1938 if (colon ==
nullptr)
1939 return internal::FilePath::MakeFileName(
1941 UnitTest::GetInstance()->original_working_dir()),
1942 internal::FilePath(kDefaultOutputFile), 0,
1943 format.c_str()).
string();
1945 internal::FilePath output_name(colon + 1);
1946 if (!output_name.IsAbsolutePath())
1947 output_name = internal::FilePath::ConcatPaths(
1948 internal::FilePath(UnitTest::GetInstance()->original_working_dir()),
1949 internal::FilePath(colon + 1));
1951 if (!output_name.IsDirectory())
1952 return output_name.string();
1954 internal::FilePath result(internal::FilePath::GenerateUniqueFileName(
1955 output_name, internal::GetCurrentExecutableName(),
1956 GetOutputFormat().c_str()));
1957 return result.string();
1965 bool UnitTestOptions::PatternMatchesString(
const char *pattern,
1970 return *str ==
'\0';
1972 return *str !=
'\0' && PatternMatchesString(pattern + 1, str + 1);
1974 return (*str !=
'\0' && PatternMatchesString(pattern, str + 1)) ||
1975 PatternMatchesString(pattern + 1, str);
1977 return *pattern == *str &&
1978 PatternMatchesString(pattern + 1, str + 1);
1982 bool UnitTestOptions::MatchesFilter(
1984 const char *cur_pattern =
filter;
1986 if (PatternMatchesString(cur_pattern, name.c_str())) {
1991 cur_pattern = strchr(cur_pattern,
':');
1994 if (cur_pattern ==
nullptr) {
2005 bool UnitTestOptions::FilterMatchesTest(
const std::string& test_suite_name,
2007 const std::string& full_name = test_suite_name +
"." + test_name.c_str();
2012 const char*
const dash = strchr(p,
'-');
2015 if (dash ==
nullptr) {
2021 if (positive.empty()) {
2023 positive = kUniversalFilter;
2029 return (MatchesFilter(full_name, positive.c_str()) &&
2030 !MatchesFilter(full_name, negative.c_str()));
2037 int UnitTestOptions::GTestShouldProcessSEH(DWORD exception_code) {
2046 const DWORD kCxxExceptionCode = 0xe06d7363;
2048 bool should_handle =
true;
2051 should_handle =
false;
2052 else if (exception_code == EXCEPTION_BREAKPOINT)
2053 should_handle =
false;
2054 else if (exception_code == kCxxExceptionCode)
2055 should_handle =
false;
2057 return should_handle ? EXCEPTION_EXECUTE_HANDLER : EXCEPTION_CONTINUE_SEARCH;
2059 #endif // GTEST_HAS_SEH 2066 ScopedFakeTestPartResultReporter::ScopedFakeTestPartResultReporter(
2067 TestPartResultArray* result)
2068 : intercept_mode_(INTERCEPT_ONLY_CURRENT_THREAD),
2076 ScopedFakeTestPartResultReporter::ScopedFakeTestPartResultReporter(
2077 InterceptMode intercept_mode, TestPartResultArray* result)
2078 : intercept_mode_(intercept_mode),
2083 void ScopedFakeTestPartResultReporter::Init() {
2084 internal::UnitTestImpl*
const impl = internal::GetUnitTestImpl();
2085 if (intercept_mode_ == INTERCEPT_ALL_THREADS) {
2086 old_reporter_ = impl->GetGlobalTestPartResultReporter();
2087 impl->SetGlobalTestPartResultReporter(
this);
2089 old_reporter_ = impl->GetTestPartResultReporterForCurrentThread();
2090 impl->SetTestPartResultReporterForCurrentThread(
this);
2096 ScopedFakeTestPartResultReporter::~ScopedFakeTestPartResultReporter() {
2097 internal::UnitTestImpl*
const impl = internal::GetUnitTestImpl();
2098 if (intercept_mode_ == INTERCEPT_ALL_THREADS) {
2099 impl->SetGlobalTestPartResultReporter(old_reporter_);
2101 impl->SetTestPartResultReporterForCurrentThread(old_reporter_);
2107 void ScopedFakeTestPartResultReporter::ReportTestPartResult(
2108 const TestPartResult& result) {
2109 result_->Append(result);
2112 namespace internal {
2124 return GetTypeId<Test>();
2134 static AssertionResult HasOneFailure(
const char* ,
2137 const TestPartResultArray& results,
2138 TestPartResult::Type type,
2140 const std::string expected(type == TestPartResult::kFatalFailure ?
2142 "1 non-fatal failure");
2144 if (results.size() != 1) {
2145 msg <<
"Expected: " << expected <<
"\n" 2146 <<
" Actual: " << results.size() <<
" failures";
2147 for (
int i = 0; i < results.size(); i++) {
2148 msg <<
"\n" << results.GetTestPartResult(i);
2150 return AssertionFailure() << msg;
2153 const TestPartResult& r = results.GetTestPartResult(0);
2154 if (r.type() != type) {
2155 return AssertionFailure() <<
"Expected: " << expected <<
"\n" 2160 if (strstr(r.message(), substr.c_str()) ==
nullptr) {
2161 return AssertionFailure() <<
"Expected: " << expected <<
" containing \"" 2167 return AssertionSuccess();
2173 SingleFailureChecker::SingleFailureChecker(
const TestPartResultArray* results,
2174 TestPartResult::Type type,
2176 : results_(results), type_(type), substr_(substr) {}
2182 SingleFailureChecker::~SingleFailureChecker() {
2186 DefaultGlobalTestPartResultReporter::DefaultGlobalTestPartResultReporter(
2187 UnitTestImpl* unit_test) : unit_test_(unit_test) {}
2189 void DefaultGlobalTestPartResultReporter::ReportTestPartResult(
2190 const TestPartResult& result) {
2191 unit_test_->current_test_result()->AddTestPartResult(result);
2192 unit_test_->listeners()->repeater()->OnTestPartResult(result);
2195 DefaultPerThreadTestPartResultReporter::DefaultPerThreadTestPartResultReporter(
2196 UnitTestImpl* unit_test) : unit_test_(unit_test) {}
2198 void DefaultPerThreadTestPartResultReporter::ReportTestPartResult(
2199 const TestPartResult& result) {
2200 unit_test_->GetGlobalTestPartResultReporter()->ReportTestPartResult(result);
2204 TestPartResultReporterInterface*
2205 UnitTestImpl::GetGlobalTestPartResultReporter() {
2207 return global_test_part_result_repoter_;
2211 void UnitTestImpl::SetGlobalTestPartResultReporter(
2212 TestPartResultReporterInterface* reporter) {
2214 global_test_part_result_repoter_ = reporter;
2218 TestPartResultReporterInterface*
2219 UnitTestImpl::GetTestPartResultReporterForCurrentThread() {
2220 return per_thread_test_part_result_reporter_.get();
2224 void UnitTestImpl::SetTestPartResultReporterForCurrentThread(
2225 TestPartResultReporterInterface* reporter) {
2226 per_thread_test_part_result_reporter_.set(reporter);
2230 int UnitTestImpl::successful_test_suite_count()
const {
2231 return CountIf(test_suites_, TestSuitePassed);
2235 int UnitTestImpl::failed_test_suite_count()
const {
2236 return CountIf(test_suites_, TestSuiteFailed);
2240 int UnitTestImpl::total_test_suite_count()
const {
2241 return static_cast<int>(test_suites_.size());
2246 int UnitTestImpl::test_suite_to_run_count()
const {
2247 return CountIf(test_suites_, ShouldRunTestSuite);
2251 int UnitTestImpl::successful_test_count()
const {
2252 return SumOverTestSuiteList(test_suites_, &TestSuite::successful_test_count);
2256 int UnitTestImpl::skipped_test_count()
const {
2257 return SumOverTestSuiteList(test_suites_, &TestSuite::skipped_test_count);
2261 int UnitTestImpl::failed_test_count()
const {
2262 return SumOverTestSuiteList(test_suites_, &TestSuite::failed_test_count);
2266 int UnitTestImpl::reportable_disabled_test_count()
const {
2267 return SumOverTestSuiteList(test_suites_,
2268 &TestSuite::reportable_disabled_test_count);
2272 int UnitTestImpl::disabled_test_count()
const {
2273 return SumOverTestSuiteList(test_suites_, &TestSuite::disabled_test_count);
2277 int UnitTestImpl::reportable_test_count()
const {
2278 return SumOverTestSuiteList(test_suites_, &TestSuite::reportable_test_count);
2282 int UnitTestImpl::total_test_count()
const {
2283 return SumOverTestSuiteList(test_suites_, &TestSuite::total_test_count);
2287 int UnitTestImpl::test_to_run_count()
const {
2288 return SumOverTestSuiteList(test_suites_, &TestSuite::test_to_run_count);
2301 std::string UnitTestImpl::CurrentOsStackTraceExceptTop(
int skip_count) {
2302 return os_stack_trace_getter()->CurrentStackTrace(
2303 static_cast<int>(
GTEST_FLAG(stack_trace_depth)),
2312 #if GTEST_OS_WINDOWS_MOBILE || defined(__BORLANDC__) 2317 const DWORD kTenthMicrosInMilliSecond = 10000;
2319 SYSTEMTIME now_systime;
2320 FILETIME now_filetime;
2321 ULARGE_INTEGER now_int64;
2322 GetSystemTime(&now_systime);
2323 if (SystemTimeToFileTime(&now_systime, &now_filetime)) {
2324 now_int64.LowPart = now_filetime.dwLowDateTime;
2325 now_int64.HighPart = now_filetime.dwHighDateTime;
2326 now_int64.QuadPart = (now_int64.QuadPart / kTenthMicrosInMilliSecond) -
2327 kJavaEpochToWinFileTimeDelta;
2328 return now_int64.QuadPart;
2331 #elif GTEST_OS_WINDOWS && !GTEST_HAS_GETTIMEOFDAY_ 2340 return static_cast<
TimeInMillis>(now.time) * 1000 + now.millitm;
2341 #elif GTEST_HAS_GETTIMEOFDAY_ 2343 gettimeofday(&now,
nullptr);
2344 return static_cast<TimeInMillis>(now.tv_sec) * 1000 + now.tv_usec / 1000;
2346 # error
"Don't know how to get the current time on your system." 2354 #if GTEST_OS_WINDOWS_MOBILE 2359 LPCWSTR String::AnsiToUtf16(
const char* ansi) {
2360 if (!ansi)
return nullptr;
2361 const int length = strlen(ansi);
2362 const int unicode_length =
2363 MultiByteToWideChar(CP_ACP, 0, ansi, length,
nullptr, 0);
2364 WCHAR* unicode =
new WCHAR[unicode_length + 1];
2365 MultiByteToWideChar(CP_ACP, 0, ansi, length,
2366 unicode, unicode_length);
2367 unicode[unicode_length] = 0;
2375 const char* String::Utf16ToAnsi(LPCWSTR utf16_str) {
2376 if (!utf16_str)
return nullptr;
2377 const int ansi_length = WideCharToMultiByte(CP_ACP, 0, utf16_str, -1,
nullptr,
2378 0,
nullptr,
nullptr);
2379 char* ansi =
new char[ansi_length + 1];
2380 WideCharToMultiByte(CP_ACP, 0, utf16_str, -1, ansi, ansi_length,
nullptr,
2382 ansi[ansi_length] = 0;
2386 #endif // GTEST_OS_WINDOWS_MOBILE 2393 bool String::CStringEquals(
const char * lhs,
const char * rhs) {
2394 if (lhs ==
nullptr)
return rhs ==
nullptr;
2396 if (rhs ==
nullptr)
return false;
2398 return strcmp(lhs, rhs) == 0;
2401 #if GTEST_HAS_STD_WSTRING || GTEST_HAS_GLOBAL_WSTRING 2405 static void StreamWideCharsToMessage(
const wchar_t* wstr,
size_t length,
2407 for (
size_t i = 0; i != length; ) {
2408 if (wstr[i] != L
'\0') {
2409 *msg << WideStringToUtf8(wstr + i, static_cast<int>(length - i));
2410 while (i != length && wstr[i] != L
'\0')
2419 #endif // GTEST_HAS_STD_WSTRING || GTEST_HAS_GLOBAL_WSTRING 2422 ::std::vector< ::std::string>* dest) {
2423 ::std::vector< ::std::string> parsed;
2424 ::std::string::size_type pos = 0;
2426 const ::std::string::size_type colon = str.find(delimiter, pos);
2427 if (colon == ::std::string::npos) {
2428 parsed.push_back(str.substr(pos));
2431 parsed.push_back(str.substr(pos, colon - pos));
2445 Message::Message() : ss_(new ::std::stringstream) {
2448 *ss_ << std::setprecision(std::numeric_limits<double>::digits10 + 2);
2454 return *
this << internal::String::ShowWideCString(wide_c_str);
2457 return *
this << internal::String::ShowWideCString(wide_c_str);
2460 #if GTEST_HAS_STD_WSTRING 2464 internal::StreamWideCharsToMessage(wstr.c_str(), wstr.length(),
this);
2467 #endif // GTEST_HAS_STD_WSTRING 2469 #if GTEST_HAS_GLOBAL_WSTRING 2473 internal::StreamWideCharsToMessage(wstr.c_str(), wstr.length(),
this);
2476 #endif // GTEST_HAS_GLOBAL_WSTRING 2481 return internal::StringStreamToString(ss_.get());
2486 AssertionResult::AssertionResult(
const AssertionResult& other)
2487 : success_(other.success_),
2488 message_(other.message_.
get() != nullptr
2489 ? new ::std::
string(*other.message_)
2490 : static_cast< ::std::
string*>(nullptr)) {}
2495 swap(success_, other.success_);
2496 swap(message_, other.message_);
2500 AssertionResult AssertionResult::operator!()
const {
2501 AssertionResult negation(!success_);
2502 if (message_.get() !=
nullptr) negation << *message_;
2507 AssertionResult AssertionSuccess() {
2508 return AssertionResult(
true);
2512 AssertionResult AssertionFailure() {
2513 return AssertionResult(
false);
2518 AssertionResult AssertionFailure(
const Message& message) {
2519 return AssertionFailure() << message;
2522 namespace internal {
2524 namespace edit_distance {
2526 const std::vector<size_t>& right) {
2527 std::vector<std::vector<double> > costs(
2528 left.size() + 1, std::vector<double>(right.size() + 1));
2529 std::vector<std::vector<EditType> > best_move(
2530 left.size() + 1, std::vector<EditType>(right.size() + 1));
2533 for (
size_t l_i = 0; l_i < costs.size(); ++l_i) {
2534 costs[l_i][0] =
static_cast<double>(l_i);
2538 for (
size_t r_i = 1; r_i < costs[0].size(); ++r_i) {
2539 costs[0][r_i] =
static_cast<double>(r_i);
2540 best_move[0][r_i] =
kAdd;
2543 for (
size_t l_i = 0; l_i < left.size(); ++l_i) {
2544 for (
size_t r_i = 0; r_i < right.size(); ++r_i) {
2545 if (left[l_i] == right[r_i]) {
2547 costs[l_i + 1][r_i + 1] = costs[l_i][r_i];
2548 best_move[l_i + 1][r_i + 1] =
kMatch;
2552 const double add = costs[l_i + 1][r_i];
2553 const double remove = costs[l_i][r_i + 1];
2554 const double replace = costs[l_i][r_i];
2556 costs[l_i + 1][r_i + 1] =
add + 1;
2557 best_move[l_i + 1][r_i + 1] =
kAdd;
2558 }
else if (
remove <
add &&
remove <
replace) {
2559 costs[l_i + 1][r_i + 1] =
remove + 1;
2560 best_move[l_i + 1][r_i + 1] =
kRemove;
2564 costs[l_i + 1][r_i + 1] =
replace + 1.00001;
2565 best_move[l_i + 1][r_i + 1] =
kReplace;
2571 std::vector<EditType> best_path;
2572 for (
size_t l_i = left.size(), r_i = right.size(); l_i > 0 || r_i > 0;) {
2573 EditType move = best_move[l_i][r_i];
2574 best_path.push_back(move);
2575 l_i -= move !=
kAdd;
2585 class InternalStrings {
2588 IdMap::iterator it = ids_.find(str);
2589 if (it != ids_.end())
return it->second;
2590 size_t id = ids_.size();
2591 return ids_[str] = id;
2595 typedef std::map<std::string, size_t> IdMap;
2602 const std::vector<std::string>& left,
2603 const std::vector<std::string>& right) {
2604 std::vector<size_t> left_ids, right_ids;
2606 InternalStrings intern_table;
2607 for (
size_t i = 0; i < left.size(); ++i) {
2608 left_ids.push_back(intern_table.GetId(left[i]));
2610 for (
size_t i = 0; i < right.size(); ++i) {
2611 right_ids.push_back(intern_table.GetId(right[i]));
2625 Hunk(
size_t left_start,
size_t right_start)
2626 : left_start_(left_start),
2627 right_start_(right_start),
2632 void PushLine(
char edit,
const char* line) {
2637 hunk_.push_back(std::make_pair(
' ', line));
2641 hunk_removes_.push_back(std::make_pair(
'-', line));
2645 hunk_adds_.push_back(std::make_pair(
'+', line));
2650 void PrintTo(std::ostream* os) {
2653 for (std::list<std::pair<char, const char*> >::const_iterator it =
2655 it != hunk_.end(); ++it) {
2656 *os << it->first << it->second <<
"\n";
2660 bool has_edits()
const {
return adds_ || removes_; }
2664 hunk_.splice(hunk_.end(), hunk_removes_);
2665 hunk_.splice(hunk_.end(), hunk_adds_);
2672 void PrintHeader(std::ostream* ss)
const {
2675 *ss <<
"-" << left_start_ <<
"," << (removes_ + common_);
2677 if (removes_ && adds_) {
2681 *ss <<
"+" << right_start_ <<
"," << (adds_ + common_);
2686 size_t left_start_, right_start_;
2687 size_t adds_, removes_, common_;
2688 std::list<std::pair<char, const char*> > hunk_, hunk_adds_, hunk_removes_;
2701 const std::vector<std::string>& right,
2705 size_t l_i = 0, r_i = 0, edit_i = 0;
2706 std::stringstream ss;
2707 while (edit_i < edits.size()) {
2709 while (edit_i < edits.size() && edits[edit_i] ==
kMatch) {
2716 const size_t prefix_context = std::min(l_i, context);
2717 Hunk hunk(l_i - prefix_context + 1, r_i - prefix_context + 1);
2718 for (
size_t i = prefix_context; i > 0; --i) {
2719 hunk.PushLine(
' ', left[l_i - i].c_str());
2724 size_t n_suffix = 0;
2725 for (; edit_i < edits.size(); ++edit_i) {
2726 if (n_suffix >= context) {
2728 std::vector<EditType>::const_iterator it = edits.begin() + edit_i;
2729 while (it != edits.end() && *it ==
kMatch) ++it;
2730 if (it == edits.end() || (it - edits.begin()) - edit_i >= context) {
2738 n_suffix = edit ==
kMatch ? n_suffix + 1 : 0;
2741 hunk.PushLine(edit ==
kMatch ?
' ' :
'-', left[l_i].c_str());
2744 hunk.PushLine(
'+', right[r_i].c_str());
2748 l_i += edit !=
kAdd;
2752 if (!hunk.has_edits()) {
2769 std::vector<std::string> SplitEscapedString(
const std::string& str) {
2770 std::vector<std::string> lines;
2771 size_t start = 0, end = str.size();
2772 if (end > 2 && str[0] ==
'"' && str[end - 1] ==
'"') {
2776 bool escaped =
false;
2777 for (
size_t i = start; i + 1 < end; ++i) {
2780 if (str[i] ==
'n') {
2781 lines.push_back(str.substr(start, i - start - 1));
2785 escaped = str[i] ==
'\\';
2788 lines.push_back(str.substr(start, end - start));
2809 AssertionResult
EqFailure(
const char* lhs_expression,
2810 const char* rhs_expression,
2813 bool ignoring_case) {
2815 msg <<
"Expected equality of these values:";
2816 msg <<
"\n " << lhs_expression;
2817 if (lhs_value != lhs_expression) {
2818 msg <<
"\n Which is: " << lhs_value;
2820 msg <<
"\n " << rhs_expression;
2821 if (rhs_value != rhs_expression) {
2822 msg <<
"\n Which is: " << rhs_value;
2825 if (ignoring_case) {
2826 msg <<
"\nIgnoring case";
2829 if (!lhs_value.empty() && !rhs_value.empty()) {
2830 const std::vector<std::string> lhs_lines =
2831 SplitEscapedString(lhs_value);
2832 const std::vector<std::string> rhs_lines =
2833 SplitEscapedString(rhs_value);
2834 if (lhs_lines.size() > 1 || rhs_lines.size() > 1) {
2835 msg <<
"\nWith diff:\n" 2840 return AssertionFailure() << msg;
2845 const AssertionResult& assertion_result,
2846 const char* expression_text,
2847 const char* actual_predicate_value,
2848 const char* expected_predicate_value) {
2849 const char* actual_message = assertion_result.message();
2851 msg <<
"Value of: " << expression_text
2852 <<
"\n Actual: " << actual_predicate_value;
2853 if (actual_message[0] !=
'\0')
2854 msg <<
" (" << actual_message <<
")";
2855 msg <<
"\nExpected: " << expected_predicate_value;
2856 return msg.GetString();
2862 const char* abs_error_expr,
2866 const double diff = fabs(val1 - val2);
2867 if (diff <= abs_error)
return AssertionSuccess();
2869 return AssertionFailure()
2870 <<
"The difference between " << expr1 <<
" and " << expr2
2871 <<
" is " << diff <<
", which exceeds " << abs_error_expr <<
", where\n" 2872 << expr1 <<
" evaluates to " << val1 <<
",\n" 2873 << expr2 <<
" evaluates to " << val2 <<
", and\n" 2874 << abs_error_expr <<
" evaluates to " << abs_error <<
".";
2879 template <
typename RawType>
2880 AssertionResult FloatingPointLE(
const char* expr1,
2886 return AssertionSuccess();
2890 const FloatingPoint<RawType> lhs(val1), rhs(val2);
2891 if (lhs.AlmostEquals(rhs)) {
2892 return AssertionSuccess();
2899 ::std::stringstream val1_ss;
2900 val1_ss << std::setprecision(std::numeric_limits<RawType>::digits10 + 2)
2903 ::std::stringstream val2_ss;
2904 val2_ss << std::setprecision(std::numeric_limits<RawType>::digits10 + 2)
2907 return AssertionFailure()
2908 <<
"Expected: (" << expr1 <<
") <= (" << expr2 <<
")\n" 2909 <<
" Actual: " << StringStreamToString(&val1_ss) <<
" vs " 2910 << StringStreamToString(&val2_ss);
2917 AssertionResult
FloatLE(
const char* expr1,
const char* expr2,
2918 float val1,
float val2) {
2919 return internal::FloatingPointLE<float>(expr1, expr2, val1, val2);
2924 AssertionResult
DoubleLE(
const char* expr1,
const char* expr2,
2925 double val1,
double val2) {
2926 return internal::FloatingPointLE<double>(expr1, expr2, val1, val2);
2929 namespace internal {
2933 AssertionResult
CmpHelperEQ(
const char* lhs_expression,
2934 const char* rhs_expression,
2938 return AssertionSuccess();
2951 #define GTEST_IMPL_CMP_HELPER_(op_name, op)\ 2952 AssertionResult CmpHelper##op_name(const char* expr1, const char* expr2, \ 2953 BiggestInt val1, BiggestInt val2) {\ 2954 if (val1 op val2) {\ 2955 return AssertionSuccess();\ 2957 return AssertionFailure() \ 2958 << "Expected: (" << expr1 << ") " #op " (" << expr2\ 2959 << "), actual: " << FormatForComparisonFailureMessage(val1, val2)\ 2960 << " vs " << FormatForComparisonFailureMessage(val2, val1);\ 2980 #undef GTEST_IMPL_CMP_HELPER_ 2984 const char* rhs_expression,
2987 if (String::CStringEquals(lhs, rhs)) {
2988 return AssertionSuccess();
3000 const char* rhs_expression,
3003 if (String::CaseInsensitiveCStringEquals(lhs, rhs)) {
3004 return AssertionSuccess();
3016 const char* s2_expression,
3019 if (!String::CStringEquals(s1, s2)) {
3020 return AssertionSuccess();
3022 return AssertionFailure() <<
"Expected: (" << s1_expression <<
") != (" 3023 << s2_expression <<
"), actual: \"" 3024 << s1 <<
"\" vs \"" << s2 <<
"\"";
3030 const char* s2_expression,
3033 if (!String::CaseInsensitiveCStringEquals(s1, s2)) {
3034 return AssertionSuccess();
3036 return AssertionFailure()
3037 <<
"Expected: (" << s1_expression <<
") != (" 3038 << s2_expression <<
") (ignoring case), actual: \"" 3039 << s1 <<
"\" vs \"" << s2 <<
"\"";
3053 bool IsSubstringPred(
const char* needle,
const char* haystack) {
3054 if (needle ==
nullptr || haystack ==
nullptr)
return needle == haystack;
3056 return strstr(haystack, needle) !=
nullptr;
3059 bool IsSubstringPred(
const wchar_t* needle,
const wchar_t* haystack) {
3060 if (needle ==
nullptr || haystack ==
nullptr)
return needle == haystack;
3062 return wcsstr(haystack, needle) !=
nullptr;
3066 template <
typename StringType>
3067 bool IsSubstringPred(
const StringType& needle,
3068 const StringType& haystack) {
3069 return haystack.find(needle) != StringType::npos;
3076 template <
typename StringType>
3077 AssertionResult IsSubstringImpl(
3078 bool expected_to_be_substring,
3079 const char* needle_expr,
const char* haystack_expr,
3080 const StringType& needle,
const StringType& haystack) {
3081 if (IsSubstringPred(needle, haystack) == expected_to_be_substring)
3082 return AssertionSuccess();
3084 const bool is_wide_string =
sizeof(needle[0]) > 1;
3085 const char*
const begin_string_quote = is_wide_string ?
"L\"" :
"\"";
3086 return AssertionFailure()
3087 <<
"Value of: " << needle_expr <<
"\n" 3088 <<
" Actual: " << begin_string_quote << needle <<
"\"\n" 3089 <<
"Expected: " << (expected_to_be_substring ?
"" :
"not ")
3090 <<
"a substring of " << haystack_expr <<
"\n" 3091 <<
"Which is: " << begin_string_quote << haystack <<
"\"";
3101 const char* needle_expr,
const char* haystack_expr,
3102 const char* needle,
const char* haystack) {
3103 return IsSubstringImpl(
true, needle_expr, haystack_expr, needle, haystack);
3107 const char* needle_expr,
const char* haystack_expr,
3108 const wchar_t* needle,
const wchar_t* haystack) {
3109 return IsSubstringImpl(
true, needle_expr, haystack_expr, needle, haystack);
3113 const char* needle_expr,
const char* haystack_expr,
3114 const char* needle,
const char* haystack) {
3115 return IsSubstringImpl(
false, needle_expr, haystack_expr, needle, haystack);
3119 const char* needle_expr,
const char* haystack_expr,
3120 const wchar_t* needle,
const wchar_t* haystack) {
3121 return IsSubstringImpl(
false, needle_expr, haystack_expr, needle, haystack);
3125 const char* needle_expr,
const char* haystack_expr,
3127 return IsSubstringImpl(
true, needle_expr, haystack_expr, needle, haystack);
3131 const char* needle_expr,
const char* haystack_expr,
3133 return IsSubstringImpl(
false, needle_expr, haystack_expr, needle, haystack);
3136 #if GTEST_HAS_STD_WSTRING 3138 const char* needle_expr,
const char* haystack_expr,
3140 return IsSubstringImpl(
true, needle_expr, haystack_expr, needle, haystack);
3144 const char* needle_expr,
const char* haystack_expr,
3146 return IsSubstringImpl(
false, needle_expr, haystack_expr, needle, haystack);
3148 #endif // GTEST_HAS_STD_WSTRING 3150 namespace internal {
3152 #if GTEST_OS_WINDOWS 3157 AssertionResult HRESULTFailureHelper(
const char* expr,
3158 const char* expected,
3160 # if GTEST_OS_WINDOWS_MOBILE || GTEST_OS_WINDOWS_TV_TITLE 3163 const char error_text[] =
"";
3170 const DWORD kFlags = FORMAT_MESSAGE_FROM_SYSTEM |
3171 FORMAT_MESSAGE_IGNORE_INSERTS;
3172 const DWORD kBufSize = 4096;
3174 char error_text[kBufSize] = {
'\0' };
3175 DWORD message_length = ::FormatMessageA(kFlags,
3183 for (; message_length &&
IsSpace(error_text[message_length - 1]);
3185 error_text[message_length - 1] =
'\0';
3188 # endif // GTEST_OS_WINDOWS_MOBILE 3190 const std::string error_hex(
"0x" + String::FormatHexInt(hr));
3191 return ::testing::AssertionFailure()
3192 <<
"Expected: " << expr <<
" " << expected <<
".\n" 3193 <<
" Actual: " << error_hex <<
" " << error_text <<
"\n";
3198 AssertionResult IsHRESULTSuccess(
const char* expr,
long hr) {
3199 if (SUCCEEDED(hr)) {
3200 return AssertionSuccess();
3202 return HRESULTFailureHelper(expr,
"succeeds", hr);
3205 AssertionResult IsHRESULTFailure(
const char* expr,
long hr) {
3207 return AssertionSuccess();
3209 return HRESULTFailureHelper(expr,
"fails", hr);
3212 #endif // GTEST_OS_WINDOWS 3227 const UInt32 kMaxCodePoint1 = (
static_cast<UInt32>(1) << 7) - 1;
3230 const UInt32 kMaxCodePoint2 = (
static_cast<UInt32>(1) << (5 + 6)) - 1;
3233 const UInt32 kMaxCodePoint3 = (
static_cast<UInt32>(1) << (4 + 2*6)) - 1;
3236 const UInt32 kMaxCodePoint4 = (
static_cast<UInt32>(1) << (3 + 3*6)) - 1;
3242 const UInt32 low_bits = *bits & ((
static_cast<UInt32>(1) << n) - 1);
3254 if (code_point > kMaxCodePoint4) {
3255 return "(Invalid Unicode 0x" + String::FormatHexInt(code_point) +
")";
3259 if (code_point <= kMaxCodePoint1) {
3261 str[0] =
static_cast<char>(code_point);
3262 }
else if (code_point <= kMaxCodePoint2) {
3264 str[1] =
static_cast<char>(0x80 | ChopLowBits(&code_point, 6));
3265 str[0] =
static_cast<char>(0xC0 | code_point);
3266 }
else if (code_point <= kMaxCodePoint3) {
3268 str[2] =
static_cast<char>(0x80 | ChopLowBits(&code_point, 6));
3269 str[1] =
static_cast<char>(0x80 | ChopLowBits(&code_point, 6));
3270 str[0] =
static_cast<char>(0xE0 | code_point);
3273 str[3] =
static_cast<char>(0x80 | ChopLowBits(&code_point, 6));
3274 str[2] =
static_cast<char>(0x80 | ChopLowBits(&code_point, 6));
3275 str[1] =
static_cast<char>(0x80 | ChopLowBits(&code_point, 6));
3276 str[0] =
static_cast<char>(0xF0 | code_point);
3288 inline bool IsUtf16SurrogatePair(
wchar_t first,
wchar_t second) {
3289 return sizeof(wchar_t) == 2 &&
3290 (first & 0xFC00) == 0xD800 && (second & 0xFC00) == 0xDC00;
3294 inline UInt32 CreateCodePointFromUtf16SurrogatePair(
wchar_t first,
3296 const UInt32 mask = (1 << 10) - 1;
3297 return (
sizeof(
wchar_t) == 2) ?
3298 (((first & mask) << 10) | (second & mask)) + 0x10000 :
3301 static_cast<UInt32>(first);
3317 std::string WideStringToUtf8(
const wchar_t* str,
int num_chars) {
3318 if (num_chars == -1)
3319 num_chars =
static_cast<int>(wcslen(str));
3321 ::std::stringstream stream;
3322 for (
int i = 0; i < num_chars; ++i) {
3323 UInt32 unicode_code_point;
3325 if (str[i] == L
'\0') {
3327 }
else if (i + 1 < num_chars && IsUtf16SurrogatePair(str[i], str[i + 1])) {
3328 unicode_code_point = CreateCodePointFromUtf16SurrogatePair(str[i],
3332 unicode_code_point =
static_cast<UInt32>(str[i]);
3335 stream << CodePointToUtf8(unicode_code_point);
3337 return StringStreamToString(&stream);
3342 std::string String::ShowWideCString(
const wchar_t * wide_c_str) {
3343 if (wide_c_str ==
nullptr)
return "(null)";
3345 return internal::WideStringToUtf8(wide_c_str, -1);
3354 bool String::WideCStringEquals(
const wchar_t * lhs,
const wchar_t * rhs) {
3355 if (lhs ==
nullptr)
return rhs ==
nullptr;
3357 if (rhs ==
nullptr)
return false;
3359 return wcscmp(lhs, rhs) == 0;
3364 const char* rhs_expression,
3366 const wchar_t* rhs) {
3367 if (String::WideCStringEquals(lhs, rhs)) {
3368 return AssertionSuccess();
3380 const char* s2_expression,
3382 const wchar_t* s2) {
3383 if (!String::WideCStringEquals(s1, s2)) {
3384 return AssertionSuccess();
3387 return AssertionFailure() <<
"Expected: (" << s1_expression <<
") != (" 3388 << s2_expression <<
"), actual: " 3399 bool String::CaseInsensitiveCStringEquals(
const char * lhs,
const char * rhs) {
3400 if (lhs ==
nullptr)
return rhs ==
nullptr;
3401 if (rhs ==
nullptr)
return false;
3417 bool String::CaseInsensitiveWideCStringEquals(
const wchar_t* lhs,
3418 const wchar_t* rhs) {
3419 if (lhs ==
nullptr)
return rhs ==
nullptr;
3421 if (rhs ==
nullptr)
return false;
3423 #if GTEST_OS_WINDOWS 3424 return _wcsicmp(lhs, rhs) == 0;
3425 #elif GTEST_OS_LINUX && !GTEST_OS_LINUX_ANDROID 3426 return wcscasecmp(lhs, rhs) == 0;
3432 left = towlower(*lhs++);
3433 right = towlower(*rhs++);
3434 }
while (left && left == right);
3435 return left == right;
3436 #endif // OS selector 3441 bool String::EndsWithCaseInsensitive(
3443 const size_t str_len = str.length();
3444 const size_t suffix_len = suffix.length();
3445 return (str_len >= suffix_len) &&
3446 CaseInsensitiveCStringEquals(str.c_str() + str_len - suffix_len,
3452 std::stringstream ss;
3453 ss << std::setfill(
'0') << std::setw(2) << value;
3459 std::stringstream ss;
3460 ss << std::hex << std::uppercase << value;
3465 std::string String::FormatByte(
unsigned char value) {
3466 std::stringstream ss;
3467 ss << std::setfill(
'0') << std::setw(2) << std::hex << std::uppercase
3468 <<
static_cast<unsigned int>(value);
3474 std::string StringStreamToString(::std::stringstream* ss) {
3476 const char*
const start = str.c_str();
3477 const char*
const end = start + str.length();
3480 result.reserve(2 * (end - start));
3481 for (
const char* ch = start; ch != end; ++ch) {
3494 const Message& user_msg) {
3496 const std::string user_msg_string = user_msg.GetString();
3497 if (user_msg_string.empty()) {
3501 return gtest_msg +
"\n" + user_msg_string;
3509 TestResult::TestResult()
3510 : death_test_count_(0),
3515 TestResult::~TestResult() {
3521 const TestPartResult& TestResult::GetTestPartResult(
int i)
const {
3522 if (i < 0 || i >= total_part_count())
3524 return test_part_results_.at(i);
3530 const TestProperty& TestResult::GetTestProperty(
int i)
const {
3531 if (i < 0 || i >= test_property_count())
3533 return test_properties_.at(i);
3537 void TestResult::ClearTestPartResults() {
3538 test_part_results_.clear();
3542 void TestResult::AddTestPartResult(
const TestPartResult& test_part_result) {
3543 test_part_results_.push_back(test_part_result);
3549 void TestResult::RecordProperty(
const std::string& xml_element,
3550 const TestProperty& test_property) {
3551 if (!ValidateTestProperty(xml_element, test_property)) {
3555 const std::vector<TestProperty>::iterator property_with_matching_key =
3556 std::find_if(test_properties_.begin(), test_properties_.end(),
3557 internal::TestPropertyKeyIs(test_property.key()));
3558 if (property_with_matching_key == test_properties_.end()) {
3559 test_properties_.push_back(test_property);
3562 property_with_matching_key->SetValue(test_property.value());
3567 static const char*
const kReservedTestSuitesAttributes[] = {
3580 static const char*
const kReservedTestSuiteAttributes[] = {
3590 static const char*
const kReservedTestCaseAttributes[] = {
3591 "classname",
"name",
"status",
"time",
3592 "type_param",
"value_param",
"file",
"line"};
3594 template <
int kSize>
3595 std::vector<std::string> ArrayAsVector(
const char*
const (&array)[kSize]) {
3596 return std::vector<std::string>(array, array + kSize);
3599 static std::vector<std::string> GetReservedAttributesForElement(
3601 if (xml_element ==
"testsuites") {
3602 return ArrayAsVector(kReservedTestSuitesAttributes);
3603 }
else if (xml_element ==
"testsuite") {
3604 return ArrayAsVector(kReservedTestSuiteAttributes);
3605 }
else if (xml_element ==
"testcase") {
3606 return ArrayAsVector(kReservedTestCaseAttributes);
3608 GTEST_CHECK_(
false) <<
"Unrecognized xml_element provided: " << xml_element;
3611 return std::vector<std::string>();
3614 static std::string FormatWordList(
const std::vector<std::string>& words) {
3616 for (
size_t i = 0; i < words.size(); ++i) {
3617 if (i > 0 && words.size() > 2) {
3620 if (i == words.size() - 1) {
3621 word_list <<
"and ";
3623 word_list <<
"'" << words[i] <<
"'";
3625 return word_list.GetString();
3628 static bool ValidateTestPropertyName(
3630 const std::vector<std::string>& reserved_names) {
3631 if (
std::find(reserved_names.begin(), reserved_names.end(), property_name) !=
3632 reserved_names.end()) {
3633 ADD_FAILURE() <<
"Reserved key used in RecordProperty(): " << property_name
3634 <<
" (" << FormatWordList(reserved_names)
3643 bool TestResult::ValidateTestProperty(
const std::string& xml_element,
3644 const TestProperty& test_property) {
3645 return ValidateTestPropertyName(test_property.key(),
3646 GetReservedAttributesForElement(xml_element));
3650 void TestResult::Clear() {
3651 test_part_results_.clear();
3652 test_properties_.clear();
3653 death_test_count_ = 0;
3658 static bool TestPartSkipped(
const TestPartResult& result) {
3659 return result.skipped();
3663 bool TestResult::Skipped()
const {
3664 return !Failed() && CountIf(test_part_results_, TestPartSkipped) > 0;
3668 bool TestResult::Failed()
const {
3669 for (
int i = 0; i < total_part_count(); ++i) {
3670 if (GetTestPartResult(i).failed())
3677 static bool TestPartFatallyFailed(
const TestPartResult& result) {
3678 return result.fatally_failed();
3682 bool TestResult::HasFatalFailure()
const {
3683 return CountIf(test_part_results_, TestPartFatallyFailed) > 0;
3687 static bool TestPartNonfatallyFailed(
const TestPartResult& result) {
3688 return result.nonfatally_failed();
3692 bool TestResult::HasNonfatalFailure()
const {
3693 return CountIf(test_part_results_, TestPartNonfatallyFailed) > 0;
3698 int TestResult::total_part_count()
const {
3699 return static_cast<int>(test_part_results_.size());
3703 int TestResult::test_property_count()
const {
3704 return static_cast<int>(test_properties_.size());
3725 void Test::SetUp() {
3731 void Test::TearDown() {
3736 UnitTest::GetInstance()->RecordProperty(key, value);
3740 void Test::RecordProperty(
const std::string& key,
int value) {
3741 Message value_message;
3742 value_message << value;
3743 RecordProperty(key, value_message.GetString().c_str());
3746 namespace internal {
3748 void ReportFailureInUnknownLocation(TestPartResult::Type result_type,
3752 UnitTest::GetInstance()->AddTestPartResult(
3767 bool Test::HasSameFixtureClass() {
3768 internal::UnitTestImpl*
const impl = internal::GetUnitTestImpl();
3769 const TestSuite*
const test_suite = impl->current_test_suite();
3772 const TestInfo*
const first_test_info = test_suite->test_info_list()[0];
3773 const internal::TypeId first_fixture_id = first_test_info->fixture_class_id_;
3774 const char*
const first_test_name = first_test_info->name();
3777 const TestInfo*
const this_test_info = impl->current_test_info();
3778 const internal::TypeId this_fixture_id = this_test_info->fixture_class_id_;
3779 const char*
const this_test_name = this_test_info->name();
3781 if (this_fixture_id != first_fixture_id) {
3787 if (first_is_TEST || this_is_TEST) {
3794 const char*
const TEST_name =
3795 first_is_TEST ? first_test_name : this_test_name;
3796 const char*
const TEST_F_name =
3797 first_is_TEST ? this_test_name : first_test_name;
3800 <<
"All tests in the same test suite must use the same test fixture\n" 3801 <<
"class, so mixing TEST_F and TEST in the same test suite is\n" 3802 <<
"illegal. In test suite " << this_test_info->test_suite_name()
3804 <<
"test " << TEST_F_name <<
" is defined using TEST_F but\n" 3805 <<
"test " << TEST_name <<
" is defined using TEST. You probably\n" 3806 <<
"want to change the TEST to TEST_F or move it to another test\n" 3812 <<
"All tests in the same test suite must use the same test fixture\n" 3813 <<
"class. However, in test suite " 3814 << this_test_info->test_suite_name() <<
",\n" 3815 <<
"you defined test " << first_test_name <<
" and test " 3816 << this_test_name <<
"\n" 3817 <<
"using two different test fixture classes. This can happen if\n" 3818 <<
"the two classes are from different namespaces or translation\n" 3819 <<
"units and have the same name. You should probably rename one\n" 3820 <<
"of the classes to put the tests into different test suites.";
3834 static std::string* FormatSehExceptionMessage(DWORD exception_code,
3835 const char* location) {
3837 message <<
"SEH exception with code 0x" << std::setbase(16) <<
3838 exception_code << std::setbase(10) <<
" thrown in " << location <<
".";
3843 #endif // GTEST_HAS_SEH 3845 namespace internal {
3847 #if GTEST_HAS_EXCEPTIONS 3850 static std::string FormatCxxExceptionMessage(
const char* description,
3851 const char* location) {
3853 if (description !=
nullptr) {
3854 message <<
"C++ exception with description \"" << description <<
"\"";
3856 message <<
"Unknown C++ exception";
3858 message <<
" thrown in " << location <<
".";
3860 return message.GetString();
3864 const TestPartResult& test_part_result);
3866 GoogleTestFailureException::GoogleTestFailureException(
3867 const TestPartResult& failure)
3868 : ::std::runtime_error(PrintTestPartResultToString(failure).c_str()) {}
3870 #endif // GTEST_HAS_EXCEPTIONS 3880 template <
class T,
typename Result>
3881 Result HandleSehExceptionsInMethodIfSupported(
3882 T*
object, Result (T::*method)(),
const char* location) {
3885 return (object->*method)();
3886 } __except (internal::UnitTestOptions::GTestShouldProcessSEH(
3887 GetExceptionCode())) {
3891 std::string* exception_message = FormatSehExceptionMessage(
3892 GetExceptionCode(), location);
3893 internal::ReportFailureInUnknownLocation(TestPartResult::kFatalFailure,
3894 *exception_message);
3895 delete exception_message;
3896 return static_cast<Result
>(0);
3900 return (object->*method)();
3901 #endif // GTEST_HAS_SEH 3907 template <
class T,
typename Result>
3908 Result HandleExceptionsInMethodIfSupported(
3909 T*
object, Result (T::*method)(),
const char* location) {
3933 if (internal::GetUnitTestImpl()->catch_exceptions()) {
3934 #if GTEST_HAS_EXCEPTIONS 3936 return HandleSehExceptionsInMethodIfSupported(
object, method, location);
3937 }
catch (
const AssertionException&) {
3939 }
catch (
const internal::GoogleTestFailureException&) {
3944 }
catch (
const std::exception& e) {
3945 internal::ReportFailureInUnknownLocation(
3946 TestPartResult::kFatalFailure,
3947 FormatCxxExceptionMessage(e.what(), location));
3949 internal::ReportFailureInUnknownLocation(
3950 TestPartResult::kFatalFailure,
3951 FormatCxxExceptionMessage(
nullptr, location));
3953 return static_cast<Result
>(0);
3955 return HandleSehExceptionsInMethodIfSupported(
object, method, location);
3956 #endif // GTEST_HAS_EXCEPTIONS 3958 return (object->*method)();
3966 if (!HasSameFixtureClass())
return;
3968 internal::UnitTestImpl*
const impl = internal::GetUnitTestImpl();
3969 impl->os_stack_trace_getter()->UponLeavingGTest();
3970 internal::HandleExceptionsInMethodIfSupported(
this, &Test::SetUp,
"SetUp()");
3973 if (!HasFatalFailure() && !IsSkipped()) {
3974 impl->os_stack_trace_getter()->UponLeavingGTest();
3975 internal::HandleExceptionsInMethodIfSupported(
3976 this, &Test::TestBody,
"the test body");
3982 impl->os_stack_trace_getter()->UponLeavingGTest();
3983 internal::HandleExceptionsInMethodIfSupported(
3984 this, &Test::TearDown,
"TearDown()");
3988 bool Test::HasFatalFailure() {
3989 return internal::GetUnitTestImpl()->current_test_result()->HasFatalFailure();
3993 bool Test::HasNonfatalFailure() {
3994 return internal::GetUnitTestImpl()->current_test_result()->
3995 HasNonfatalFailure();
3999 bool Test::IsSkipped() {
4000 return internal::GetUnitTestImpl()->current_test_result()->Skipped();
4007 TestInfo::TestInfo(
const std::string& a_test_suite_name,
4008 const std::string& a_name,
const char* a_type_param,
4009 const char* a_value_param,
4010 internal::CodeLocation a_code_location,
4012 internal::TestFactoryBase* factory)
4013 : test_suite_name_(a_test_suite_name),
4015 type_param_(a_type_param ? new std::
string(a_type_param) : nullptr),
4016 value_param_(a_value_param ? new std::
string(a_value_param) : nullptr),
4017 location_(a_code_location),
4018 fixture_class_id_(fixture_class_id),
4020 is_disabled_(false),
4021 matches_filter_(false),
4026 TestInfo::~TestInfo() {
delete factory_; }
4028 namespace internal {
4049 const char* test_suite_name,
const char* name,
const char* type_param,
4050 const char* value_param, CodeLocation code_location,
4053 TestInfo*
const test_info =
4054 new TestInfo(test_suite_name, name, type_param, value_param,
4055 code_location, fixture_class_id, factory);
4056 GetUnitTestImpl()->AddTestInfo(set_up_tc, tear_down_tc, test_info);
4061 CodeLocation code_location) {
4064 <<
"Attempted redefinition of test suite " << test_suite_name <<
".\n" 4065 <<
"All tests in the same test suite must use the same test fixture\n" 4066 <<
"class. However, in test suite " << test_suite_name <<
", you tried\n" 4067 <<
"to define a test using a fixture class different from the one\n" 4068 <<
"used earlier. This can happen if the two fixture classes are\n" 4069 <<
"from different namespaces and have the same name. You should\n" 4070 <<
"probably rename one of the classes to put the tests into different\n" 4075 <<
" " << errors.GetString();
4094 explicit TestNameIs(
const char* name)
4098 bool operator()(
const TestInfo * test_info)
const {
4099 return test_info && test_info->name() == name_;
4108 namespace internal {
4113 void UnitTestImpl::RegisterParameterizedTests() {
4114 if (!parameterized_tests_registered_) {
4115 parameterized_test_registry_.RegisterTests();
4116 parameterized_tests_registered_ =
true;
4124 void TestInfo::Run() {
4125 if (!should_run_)
return;
4128 internal::UnitTestImpl*
const impl = internal::GetUnitTestImpl();
4129 impl->set_current_test_info(
this);
4131 TestEventListener* repeater = UnitTest::GetInstance()->listeners().repeater();
4134 repeater->OnTestStart(*
this);
4136 const TimeInMillis start = internal::GetTimeInMillis();
4138 impl->os_stack_trace_getter()->UponLeavingGTest();
4141 Test*
const test = internal::HandleExceptionsInMethodIfSupported(
4142 factory_, &internal::TestFactoryBase::CreateTest,
4143 "the test fixture's constructor");
4148 if (!Test::HasFatalFailure() && !Test::IsSkipped()) {
4155 impl->os_stack_trace_getter()->UponLeavingGTest();
4156 internal::HandleExceptionsInMethodIfSupported(
4157 test, &Test::DeleteSelf_,
"the test fixture's destructor");
4159 result_.set_elapsed_time(internal::GetTimeInMillis() - start);
4162 repeater->OnTestEnd(*
this);
4166 impl->set_current_test_info(
nullptr);
4172 int TestSuite::successful_test_count()
const {
4173 return CountIf(test_info_list_, TestPassed);
4177 int TestSuite::skipped_test_count()
const {
4178 return CountIf(test_info_list_, TestSkipped);
4182 int TestSuite::failed_test_count()
const {
4183 return CountIf(test_info_list_, TestFailed);
4187 int TestSuite::reportable_disabled_test_count()
const {
4188 return CountIf(test_info_list_, TestReportableDisabled);
4192 int TestSuite::disabled_test_count()
const {
4193 return CountIf(test_info_list_, TestDisabled);
4197 int TestSuite::reportable_test_count()
const {
4198 return CountIf(test_info_list_, TestReportable);
4202 int TestSuite::test_to_run_count()
const {
4203 return CountIf(test_info_list_, ShouldRunTest);
4207 int TestSuite::total_test_count()
const {
4208 return static_cast<int>(test_info_list_.size());
4220 TestSuite::TestSuite(
const char* a_name,
const char* a_type_param,
4224 type_param_(a_type_param ? new std::
string(a_type_param) : nullptr),
4225 set_up_tc_(set_up_tc),
4226 tear_down_tc_(tear_down_tc),
4231 TestSuite::~TestSuite() {
4233 ForEach(test_info_list_, internal::Delete<TestInfo>);
4238 const TestInfo* TestSuite::GetTestInfo(
int i)
const {
4239 const int index = GetElementOr(test_indices_, i, -1);
4240 return index < 0 ? nullptr : test_info_list_[index];
4245 TestInfo* TestSuite::GetMutableTestInfo(
int i) {
4246 const int index = GetElementOr(test_indices_, i, -1);
4247 return index < 0 ? nullptr : test_info_list_[index];
4252 void TestSuite::AddTestInfo(TestInfo* test_info) {
4253 test_info_list_.push_back(test_info);
4254 test_indices_.push_back(static_cast<int>(test_indices_.size()));
4258 void TestSuite::Run() {
4259 if (!should_run_)
return;
4261 internal::UnitTestImpl*
const impl = internal::GetUnitTestImpl();
4262 impl->set_current_test_suite(
this);
4264 TestEventListener* repeater = UnitTest::GetInstance()->listeners().repeater();
4267 repeater->OnTestSuiteStart(*
this);
4269 #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI 4270 repeater->OnTestCaseStart(*
this);
4271 #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI 4273 impl->os_stack_trace_getter()->UponLeavingGTest();
4274 internal::HandleExceptionsInMethodIfSupported(
4275 this, &TestSuite::RunSetUpTestSuite,
"SetUpTestSuite()");
4278 for (
int i = 0; i < total_test_count(); i++) {
4279 GetMutableTestInfo(i)->Run();
4281 elapsed_time_ = internal::GetTimeInMillis() - start;
4283 impl->os_stack_trace_getter()->UponLeavingGTest();
4284 internal::HandleExceptionsInMethodIfSupported(
4285 this, &TestSuite::RunTearDownTestSuite,
"TearDownTestSuite()");
4288 repeater->OnTestSuiteEnd(*
this);
4290 #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI 4291 repeater->OnTestCaseEnd(*
this);
4292 #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI 4294 impl->set_current_test_suite(
nullptr);
4298 void TestSuite::ClearResult() {
4299 ad_hoc_test_result_.Clear();
4300 ForEach(test_info_list_, TestInfo::ClearTestResult);
4304 void TestSuite::ShuffleTests(internal::Random* random) {
4305 Shuffle(random, &test_indices_);
4309 void TestSuite::UnshuffleTests() {
4310 for (
size_t i = 0; i < test_indices_.size(); i++) {
4311 test_indices_[i] =
static_cast<int>(i);
4321 const char * singular_form,
4322 const char * plural_form) {
4324 (
count == 1 ? singular_form : plural_form);
4328 static std::string FormatTestCount(
int test_count) {
4329 return FormatCountableNoun(test_count,
"test",
"tests");
4333 static std::string FormatTestSuiteCount(
int test_suite_count) {
4334 return FormatCountableNoun(test_suite_count,
"test suite",
"test suites");
4341 static const char * TestPartResultTypeToString(TestPartResult::Type type) {
4343 case TestPartResult::kSkip:
4345 case TestPartResult::kSuccess:
4348 case TestPartResult::kNonFatalFailure:
4349 case TestPartResult::kFatalFailure:
4356 return "Unknown result type";
4360 namespace internal {
4364 const TestPartResult& test_part_result) {
4367 test_part_result.line_number())
4368 <<
" " << TestPartResultTypeToString(test_part_result.type())
4369 << test_part_result.message()).GetString();
4373 static void PrintTestPartResult(
const TestPartResult& test_part_result) {
4375 PrintTestPartResultToString(test_part_result);
4376 printf(
"%s\n", result.c_str());
4382 #if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE 4386 ::OutputDebugStringA(result.c_str());
4387 ::OutputDebugStringA(
"\n");
4392 #if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE && \ 4393 !GTEST_OS_WINDOWS_PHONE && !GTEST_OS_WINDOWS_RT && !GTEST_OS_WINDOWS_MINGW 4396 static WORD GetColorAttribute(
GTestColor color) {
4400 case COLOR_YELLOW:
return FOREGROUND_RED | FOREGROUND_GREEN;
4405 static int GetBitOffset(WORD color_mask) {
4406 if (color_mask == 0)
return 0;
4409 while ((color_mask & 1) == 0) {
4416 static WORD GetNewColor(
GTestColor color, WORD old_color_attrs) {
4418 static const WORD background_mask = BACKGROUND_BLUE | BACKGROUND_GREEN |
4419 BACKGROUND_RED | BACKGROUND_INTENSITY;
4420 static const WORD foreground_mask = FOREGROUND_BLUE | FOREGROUND_GREEN |
4421 FOREGROUND_RED | FOREGROUND_INTENSITY;
4422 const WORD existing_bg = old_color_attrs & background_mask;
4425 GetColorAttribute(color) | existing_bg | FOREGROUND_INTENSITY;
4426 static const int bg_bitOffset = GetBitOffset(background_mask);
4427 static const int fg_bitOffset = GetBitOffset(foreground_mask);
4429 if (((new_color & background_mask) >> bg_bitOffset) ==
4430 ((new_color & foreground_mask) >> fg_bitOffset)) {
4431 new_color ^= FOREGROUND_INTENSITY;
4440 static const char* GetAnsiColorCode(
GTestColor color) {
4450 #endif // GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE 4453 bool ShouldUseColor(
bool stdout_is_tty) {
4454 const char*
const gtest_color =
GTEST_FLAG(color).c_str();
4456 if (String::CaseInsensitiveCStringEquals(gtest_color,
"auto")) {
4457 #if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MINGW 4460 return stdout_is_tty;
4464 const bool term_supports_color =
4465 String::CStringEquals(term,
"xterm") ||
4466 String::CStringEquals(term,
"xterm-color") ||
4467 String::CStringEquals(term,
"xterm-256color") ||
4468 String::CStringEquals(term,
"screen") ||
4469 String::CStringEquals(term,
"screen-256color") ||
4470 String::CStringEquals(term,
"tmux") ||
4471 String::CStringEquals(term,
"tmux-256color") ||
4472 String::CStringEquals(term,
"rxvt-unicode") ||
4473 String::CStringEquals(term,
"rxvt-unicode-256color") ||
4474 String::CStringEquals(term,
"linux") ||
4475 String::CStringEquals(term,
"cygwin");
4476 return stdout_is_tty && term_supports_color;
4477 #endif // GTEST_OS_WINDOWS 4480 return String::CaseInsensitiveCStringEquals(gtest_color,
"yes") ||
4481 String::CaseInsensitiveCStringEquals(gtest_color,
"true") ||
4482 String::CaseInsensitiveCStringEquals(gtest_color,
"t") ||
4483 String::CStringEquals(gtest_color,
"1");
4493 void ColoredPrintf(
GTestColor color,
const char*
fmt, ...) {
4495 va_start(args,
fmt);
4497 #if GTEST_OS_WINDOWS_MOBILE || GTEST_OS_ZOS || GTEST_OS_IOS || \ 4498 GTEST_OS_WINDOWS_PHONE || GTEST_OS_WINDOWS_RT 4501 static const bool in_color_mode =
4503 const bool use_color = in_color_mode && (color !=
COLOR_DEFAULT);
4504 #endif // GTEST_OS_WINDOWS_MOBILE || GTEST_OS_ZOS 4512 #if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE && \ 4513 !GTEST_OS_WINDOWS_PHONE && !GTEST_OS_WINDOWS_RT && !GTEST_OS_WINDOWS_MINGW 4514 const HANDLE stdout_handle = GetStdHandle(STD_OUTPUT_HANDLE);
4517 CONSOLE_SCREEN_BUFFER_INFO buffer_info;
4518 GetConsoleScreenBufferInfo(stdout_handle, &buffer_info);
4519 const WORD old_color_attrs = buffer_info.wAttributes;
4520 const WORD new_color = GetNewColor(color, old_color_attrs);
4526 SetConsoleTextAttribute(stdout_handle, new_color);
4532 SetConsoleTextAttribute(stdout_handle, old_color_attrs);
4534 printf(
"\033[0;3%sm", GetAnsiColorCode(color));
4537 #endif // GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE 4543 static const char kTypeParamLabel[] =
"TypeParam";
4544 static const char kValueParamLabel[] =
"GetParam()";
4546 static void PrintFullTestCommentIfPresent(
const TestInfo& test_info) {
4547 const char*
const type_param = test_info.type_param();
4548 const char*
const value_param = test_info.value_param();
4550 if (type_param !=
nullptr || value_param !=
nullptr) {
4552 if (type_param !=
nullptr) {
4553 printf(
"%s = %s", kTypeParamLabel, type_param);
4554 if (value_param !=
nullptr) printf(
" and ");
4556 if (value_param !=
nullptr) {
4557 printf(
"%s = %s", kValueParamLabel, value_param);
4565 class PrettyUnitTestResultPrinter :
public TestEventListener {
4567 PrettyUnitTestResultPrinter() {}
4568 static void PrintTestName(
const char* test_suite,
const char* test) {
4569 printf(
"%s.%s", test_suite, test);
4573 void OnTestProgramStart(
const UnitTest& )
override {}
4574 void OnTestIterationStart(
const UnitTest& unit_test,
int iteration)
override;
4575 void OnEnvironmentsSetUpStart(
const UnitTest& unit_test)
override;
4576 void OnEnvironmentsSetUpEnd(
const UnitTest& )
override {}
4577 void OnTestCaseStart(
const TestSuite& test_suite)
override;
4578 void OnTestStart(
const TestInfo& test_info)
override;
4579 void OnTestPartResult(
const TestPartResult& result)
override;
4580 void OnTestEnd(
const TestInfo& test_info)
override;
4581 void OnTestCaseEnd(
const TestSuite& test_suite)
override;
4582 void OnEnvironmentsTearDownStart(
const UnitTest& unit_test)
override;
4583 void OnEnvironmentsTearDownEnd(
const UnitTest& )
override {}
4584 void OnTestIterationEnd(
const UnitTest& unit_test,
int iteration)
override;
4585 void OnTestProgramEnd(
const UnitTest& )
override {}
4588 static void PrintFailedTests(
const UnitTest& unit_test);
4589 static void PrintSkippedTests(
const UnitTest& unit_test);
4593 void PrettyUnitTestResultPrinter::OnTestIterationStart(
4594 const UnitTest& unit_test,
int iteration) {
4596 printf(
"\nRepeating all tests (iteration %d) . . .\n\n", iteration + 1);
4602 if (!String::CStringEquals(
filter, kUniversalFilter)) {
4607 if (internal::ShouldShard(kTestTotalShards, kTestShardIndex,
false)) {
4608 const Int32 shard_index = Int32FromEnvOrDie(kTestShardIndex, -1);
4610 "Note: This is test shard %d of %s.\n",
4611 static_cast<int>(shard_index) + 1,
4617 "Note: Randomizing tests' orders with a seed of %d .\n",
4618 unit_test.random_seed());
4622 printf(
"Running %s from %s.\n",
4623 FormatTestCount(unit_test.test_to_run_count()).c_str(),
4624 FormatTestSuiteCount(unit_test.test_suite_to_run_count()).c_str());
4628 void PrettyUnitTestResultPrinter::OnEnvironmentsSetUpStart(
4631 printf(
"Global test environment set-up.\n");
4635 void PrettyUnitTestResultPrinter::OnTestCaseStart(
const TestSuite& test_suite) {
4637 FormatCountableNoun(test_suite.test_to_run_count(),
"test",
"tests");
4639 printf(
"%s from %s", counts.c_str(), test_suite.name());
4640 if (test_suite.type_param() ==
nullptr) {
4643 printf(
", where %s = %s\n", kTypeParamLabel, test_suite.type_param());
4648 void PrettyUnitTestResultPrinter::OnTestStart(
const TestInfo& test_info) {
4650 PrintTestName(test_info.test_suite_name(), test_info.name());
4656 void PrettyUnitTestResultPrinter::OnTestPartResult(
4657 const TestPartResult& result) {
4658 switch (result.type()) {
4661 case TestPartResult::kSkip:
4662 case TestPartResult::kSuccess:
4667 PrintTestPartResult(result);
4672 void PrettyUnitTestResultPrinter::OnTestEnd(
const TestInfo& test_info) {
4673 if (test_info.result()->Passed()) {
4675 }
else if (test_info.result()->Skipped()) {
4678 ColoredPrintf(
COLOR_RED,
"[ FAILED ] ");
4680 PrintTestName(test_info.test_suite_name(), test_info.name());
4681 if (test_info.result()->Failed())
4682 PrintFullTestCommentIfPresent(test_info);
4686 test_info.result()->elapsed_time()).c_str());
4693 void PrettyUnitTestResultPrinter::OnTestCaseEnd(
const TestSuite& test_suite) {
4697 FormatCountableNoun(test_suite.test_to_run_count(),
"test",
"tests");
4699 printf(
"%s from %s (%s ms total)\n\n", counts.c_str(), test_suite.name(),
4704 void PrettyUnitTestResultPrinter::OnEnvironmentsTearDownStart(
4707 printf(
"Global test environment tear-down\n");
4712 void PrettyUnitTestResultPrinter::PrintFailedTests(
const UnitTest& unit_test) {
4713 const int failed_test_count = unit_test.failed_test_count();
4714 if (failed_test_count == 0) {
4718 for (
int i = 0; i < unit_test.total_test_suite_count(); ++i) {
4719 const TestSuite& test_suite = *unit_test.GetTestSuite(i);
4720 if (!test_suite.should_run() || (test_suite.failed_test_count() == 0)) {
4723 for (
int j = 0; j < test_suite.total_test_count(); ++j) {
4724 const TestInfo& test_info = *test_suite.GetTestInfo(j);
4725 if (!test_info.should_run() || !test_info.result()->Failed()) {
4728 ColoredPrintf(
COLOR_RED,
"[ FAILED ] ");
4729 printf(
"%s.%s", test_suite.name(), test_info.name());
4730 PrintFullTestCommentIfPresent(test_info);
4737 void PrettyUnitTestResultPrinter::PrintSkippedTests(
const UnitTest& unit_test) {
4738 const int skipped_test_count = unit_test.skipped_test_count();
4739 if (skipped_test_count == 0) {
4743 for (
int i = 0; i < unit_test.total_test_suite_count(); ++i) {
4744 const TestSuite& test_suite = *unit_test.GetTestSuite(i);
4745 if (!test_suite.should_run() || (test_suite.skipped_test_count() == 0)) {
4748 for (
int j = 0; j < test_suite.total_test_count(); ++j) {
4749 const TestInfo& test_info = *test_suite.GetTestInfo(j);
4750 if (!test_info.should_run() || !test_info.result()->Skipped()) {
4754 printf(
"%s.%s", test_suite.name(), test_info.name());
4760 void PrettyUnitTestResultPrinter::OnTestIterationEnd(
const UnitTest& unit_test,
4763 printf(
"%s from %s ran.",
4764 FormatTestCount(unit_test.test_to_run_count()).c_str(),
4765 FormatTestSuiteCount(unit_test.test_suite_to_run_count()).c_str());
4767 printf(
" (%s ms total)",
4772 printf(
"%s.\n", FormatTestCount(unit_test.successful_test_count()).c_str());
4774 const int skipped_test_count = unit_test.skipped_test_count();
4775 if (skipped_test_count > 0) {
4777 printf(
"%s, listed below:\n", FormatTestCount(skipped_test_count).c_str());
4778 PrintSkippedTests(unit_test);
4781 int num_failures = unit_test.failed_test_count();
4782 if (!unit_test.Passed()) {
4783 const int failed_test_count = unit_test.failed_test_count();
4784 ColoredPrintf(
COLOR_RED,
"[ FAILED ] ");
4785 printf(
"%s, listed below:\n", FormatTestCount(failed_test_count).c_str());
4786 PrintFailedTests(unit_test);
4787 printf(
"\n%2d FAILED %s\n", num_failures,
4788 num_failures == 1 ?
"TEST" :
"TESTS");
4791 int num_disabled = unit_test.reportable_disabled_test_count();
4792 if (num_disabled && !
GTEST_FLAG(also_run_disabled_tests)) {
4793 if (!num_failures) {
4797 " YOU HAVE %d DISABLED %s\n\n",
4799 num_disabled == 1 ?
"TEST" :
"TESTS");
4810 class TestEventRepeater :
public TestEventListener {
4812 TestEventRepeater() : forwarding_enabled_(true) {}
4813 ~TestEventRepeater()
override;
4814 void Append(TestEventListener *listener);
4815 TestEventListener* Release(TestEventListener* listener);
4819 bool forwarding_enabled()
const {
return forwarding_enabled_; }
4820 void set_forwarding_enabled(
bool enable) { forwarding_enabled_ = enable; }
4822 void OnTestProgramStart(
const UnitTest& unit_test)
override;
4823 void OnTestIterationStart(
const UnitTest& unit_test,
int iteration)
override;
4824 void OnEnvironmentsSetUpStart(
const UnitTest& unit_test)
override;
4825 void OnEnvironmentsSetUpEnd(
const UnitTest& unit_test)
override;
4827 #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI 4828 void OnTestCaseStart(
const TestSuite& parameter)
override;
4829 #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI 4830 void OnTestSuiteStart(
const TestSuite& parameter)
override;
4831 void OnTestStart(
const TestInfo& test_info)
override;
4832 void OnTestPartResult(
const TestPartResult& result)
override;
4833 void OnTestEnd(
const TestInfo& test_info)
override;
4835 #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI 4836 void OnTestCaseEnd(
const TestSuite& parameter)
override;
4837 #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI 4838 void OnTestSuiteEnd(
const TestSuite& parameter)
override;
4839 void OnEnvironmentsTearDownStart(
const UnitTest& unit_test)
override;
4840 void OnEnvironmentsTearDownEnd(
const UnitTest& unit_test)
override;
4841 void OnTestIterationEnd(
const UnitTest& unit_test,
int iteration)
override;
4842 void OnTestProgramEnd(
const UnitTest& unit_test)
override;
4847 bool forwarding_enabled_;
4849 std::vector<TestEventListener*> listeners_;
4854 TestEventRepeater::~TestEventRepeater() {
4855 ForEach(listeners_, Delete<TestEventListener>);
4858 void TestEventRepeater::Append(TestEventListener *listener) {
4859 listeners_.push_back(listener);
4862 TestEventListener* TestEventRepeater::Release(TestEventListener *listener) {
4863 for (
size_t i = 0; i < listeners_.size(); ++i) {
4864 if (listeners_[i] == listener) {
4865 listeners_.erase(listeners_.begin() + i);
4875 #define GTEST_REPEATER_METHOD_(Name, Type) \ 4876 void TestEventRepeater::Name(const Type& parameter) { \ 4877 if (forwarding_enabled_) { \ 4878 for (size_t i = 0; i < listeners_.size(); i++) { \ 4879 listeners_[i]->Name(parameter); \ 4885 #define GTEST_REVERSE_REPEATER_METHOD_(Name, Type) \ 4886 void TestEventRepeater::Name(const Type& parameter) { \ 4887 if (forwarding_enabled_) { \ 4888 for (int i = static_cast<int>(listeners_.size()) - 1; i >= 0; i--) { \ 4889 listeners_[i]->Name(parameter); \ 4897 #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_ 4899 #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_ 4908 #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_ 4910 #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_ 4914 #undef GTEST_REPEATER_METHOD_ 4915 #undef GTEST_REVERSE_REPEATER_METHOD_ 4917 void TestEventRepeater::OnTestIterationStart(
const UnitTest& unit_test,
4919 if (forwarding_enabled_) {
4920 for (
size_t i = 0; i < listeners_.size(); i++) {
4921 listeners_[i]->OnTestIterationStart(unit_test, iteration);
4926 void TestEventRepeater::OnTestIterationEnd(
const UnitTest& unit_test,
4928 if (forwarding_enabled_) {
4929 for (
int i = static_cast<int>(listeners_.size()) - 1; i >= 0; i--) {
4930 listeners_[i]->OnTestIterationEnd(unit_test, iteration);
4938 class XmlUnitTestResultPrinter :
public EmptyTestEventListener {
4940 explicit XmlUnitTestResultPrinter(
const char* output_file);
4942 void OnTestIterationEnd(
const UnitTest& unit_test,
int iteration)
override;
4943 void ListTestsMatchingFilter(
const std::vector<TestSuite*>& test_suites);
4946 static void PrintXmlTestsList(std::ostream* stream,
4947 const std::vector<TestSuite*>& test_suites);
4952 static bool IsNormalizableWhitespace(
char c) {
4953 return c == 0x9 || c == 0xA || c == 0xD;
4957 static bool IsValidXmlCharacter(
char c) {
4958 return IsNormalizableWhitespace(c) || c >= 0x20;
4972 return EscapeXml(str,
true);
4976 static std::string EscapeXmlText(
const char* str) {
4977 return EscapeXml(str,
false);
4982 static void OutputXmlAttribute(std::ostream* stream,
4988 static void OutputXmlCDataSection(::std::ostream* stream,
const char* data);
4991 static void OutputXmlTestInfo(::std::ostream* stream,
4992 const char* test_suite_name,
4993 const TestInfo& test_info);
4996 static void PrintXmlTestSuite(::std::ostream* stream,
4997 const TestSuite& test_suite);
5000 static void PrintXmlUnitTest(::std::ostream* stream,
5001 const UnitTest& unit_test);
5007 static std::string TestPropertiesAsXmlAttributes(
const TestResult& result);
5011 static void OutputXmlTestProperties(std::ostream* stream,
5012 const TestResult& result);
5021 XmlUnitTestResultPrinter::XmlUnitTestResultPrinter(
const char* output_file)
5022 : output_file_(output_file) {
5023 if (output_file_.empty()) {
5024 GTEST_LOG_(FATAL) <<
"XML output file may not be null";
5029 void XmlUnitTestResultPrinter::OnTestIterationEnd(
const UnitTest& unit_test,
5031 FILE* xmlout = OpenFileForWriting(output_file_);
5032 std::stringstream stream;
5033 PrintXmlUnitTest(&stream, unit_test);
5034 fprintf(xmlout,
"%s", StringStreamToString(&stream).c_str());
5038 void XmlUnitTestResultPrinter::ListTestsMatchingFilter(
5039 const std::vector<TestSuite*>& test_suites) {
5040 FILE* xmlout = OpenFileForWriting(output_file_);
5041 std::stringstream stream;
5042 PrintXmlTestsList(&stream, test_suites);
5043 fprintf(xmlout,
"%s", StringStreamToString(&stream).c_str());
5061 for (
size_t i = 0; i < str.size(); ++i) {
5062 const char ch = str[i];
5086 if (IsValidXmlCharacter(ch)) {
5087 if (is_attribute && IsNormalizableWhitespace(ch))
5088 m <<
"&#x" << String::FormatByte(static_cast<unsigned char>(ch))
5097 return m.GetString();
5103 std::string XmlUnitTestResultPrinter::RemoveInvalidXmlCharacters(
5106 output.reserve(str.size());
5107 for (std::string::const_iterator it = str.begin(); it != str.end(); ++it)
5108 if (IsValidXmlCharacter(*it))
5109 output.push_back(*it);
5133 ::std::stringstream ss;
5134 ss << (static_cast<double>(ms) * 1e-3);
5138 static bool PortableLocaltime(time_t seconds,
struct tm* out) {
5139 #if defined(_MSC_VER) 5140 return localtime_s(out, &seconds) == 0;
5141 #elif defined(__MINGW32__) || defined(__MINGW64__) 5144 struct tm* tm_ptr = localtime(&seconds);
5145 if (tm_ptr ==
nullptr)
return false;
5149 return localtime_r(&seconds, out) !=
nullptr;
5156 struct tm time_struct;
5157 if (!PortableLocaltime(static_cast<time_t>(ms / 1000), &time_struct))
5161 String::FormatIntWidth2(time_struct.tm_mon + 1) +
"-" +
5162 String::FormatIntWidth2(time_struct.tm_mday) +
"T" +
5163 String::FormatIntWidth2(time_struct.tm_hour) +
":" +
5164 String::FormatIntWidth2(time_struct.tm_min) +
":" +
5165 String::FormatIntWidth2(time_struct.tm_sec);
5169 void XmlUnitTestResultPrinter::OutputXmlCDataSection(::std::ostream* stream,
5171 const char* segment = data;
5172 *stream <<
"<![CDATA[";
5174 const char*
const next_segment = strstr(segment,
"]]>");
5175 if (next_segment !=
nullptr) {
5177 segment, static_cast<std::streamsize>(next_segment - segment));
5178 *stream <<
"]]>]]><![CDATA[";
5179 segment = next_segment + strlen(
"]]>");
5188 void XmlUnitTestResultPrinter::OutputXmlAttribute(
5189 std::ostream* stream,
5193 const std::vector<std::string>& allowed_names =
5194 GetReservedAttributesForElement(element_name);
5197 allowed_names.end())
5198 <<
"Attribute " << name <<
" is not allowed for element <" << element_name
5201 *stream <<
" " << name <<
"=\"" << EscapeXmlAttribute(value) <<
"\"";
5205 void XmlUnitTestResultPrinter::OutputXmlTestInfo(::std::ostream* stream,
5206 const char* test_suite_name,
5207 const TestInfo& test_info) {
5208 const TestResult& result = *test_info.result();
5211 if (test_info.is_in_another_shard()) {
5215 *stream <<
" <testcase";
5216 OutputXmlAttribute(stream, kTestsuite,
"name", test_info.name());
5218 if (test_info.value_param() !=
nullptr) {
5219 OutputXmlAttribute(stream, kTestsuite,
"value_param",
5220 test_info.value_param());
5222 if (test_info.type_param() !=
nullptr) {
5223 OutputXmlAttribute(stream, kTestsuite,
"type_param",
5224 test_info.type_param());
5227 OutputXmlAttribute(stream, kTestsuite,
"file", test_info.file());
5228 OutputXmlAttribute(stream, kTestsuite,
"line",
5235 stream, kTestsuite,
"status",
5236 result.Skipped() ?
"skipped" : test_info.should_run() ?
"run" :
"notrun");
5237 OutputXmlAttribute(stream, kTestsuite,
"time",
5238 FormatTimeInMillisAsSeconds(result.elapsed_time()));
5239 OutputXmlAttribute(stream, kTestsuite,
"classname", test_suite_name);
5242 for (
int i = 0; i < result.total_part_count(); ++i) {
5243 const TestPartResult& part = result.GetTestPartResult(i);
5244 if (part.failed()) {
5245 if (++failures == 1) {
5250 part.line_number());
5251 const std::string summary = location +
"\n" + part.summary();
5252 *stream <<
" <failure message=\"" 5253 << EscapeXmlAttribute(summary.c_str())
5255 const std::string detail = location +
"\n" + part.message();
5256 OutputXmlCDataSection(stream, RemoveInvalidXmlCharacters(detail).c_str());
5257 *stream <<
"</failure>\n";
5261 if (failures == 0 && result.test_property_count() == 0) {
5264 if (failures == 0) {
5267 OutputXmlTestProperties(stream, result);
5268 *stream <<
" </testcase>\n";
5273 void XmlUnitTestResultPrinter::PrintXmlTestSuite(std::ostream* stream,
5274 const TestSuite& test_suite) {
5276 *stream <<
" <" << kTestsuite;
5277 OutputXmlAttribute(stream, kTestsuite,
"name", test_suite.name());
5278 OutputXmlAttribute(stream, kTestsuite,
"tests",
5281 OutputXmlAttribute(stream, kTestsuite,
"failures",
5284 stream, kTestsuite,
"disabled",
5286 OutputXmlAttribute(stream, kTestsuite,
"errors",
"0");
5287 OutputXmlAttribute(stream, kTestsuite,
"time",
5288 FormatTimeInMillisAsSeconds(test_suite.elapsed_time()));
5289 *stream << TestPropertiesAsXmlAttributes(test_suite.ad_hoc_test_result());
5292 for (
int i = 0; i < test_suite.total_test_count(); ++i) {
5293 if (test_suite.GetTestInfo(i)->is_reportable())
5294 OutputXmlTestInfo(stream, test_suite.name(), *test_suite.GetTestInfo(i));
5296 *stream <<
" </" << kTestsuite <<
">\n";
5300 void XmlUnitTestResultPrinter::PrintXmlUnitTest(std::ostream* stream,
5301 const UnitTest& unit_test) {
5304 *stream <<
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
5305 *stream <<
"<" << kTestsuites;
5307 OutputXmlAttribute(stream, kTestsuites,
"tests",
5309 OutputXmlAttribute(stream, kTestsuites,
"failures",
5312 stream, kTestsuites,
"disabled",
5314 OutputXmlAttribute(stream, kTestsuites,
"errors",
"0");
5316 stream, kTestsuites,
"timestamp",
5317 FormatEpochTimeInMillisAsIso8601(unit_test.start_timestamp()));
5318 OutputXmlAttribute(stream, kTestsuites,
"time",
5319 FormatTimeInMillisAsSeconds(unit_test.elapsed_time()));
5322 OutputXmlAttribute(stream, kTestsuites,
"random_seed",
5325 *stream << TestPropertiesAsXmlAttributes(unit_test.ad_hoc_test_result());
5327 OutputXmlAttribute(stream, kTestsuites,
"name",
"AllTests");
5330 for (
int i = 0; i < unit_test.total_test_suite_count(); ++i) {
5331 if (unit_test.GetTestSuite(i)->reportable_test_count() > 0)
5332 PrintXmlTestSuite(stream, *unit_test.GetTestSuite(i));
5334 *stream <<
"</" << kTestsuites <<
">\n";
5337 void XmlUnitTestResultPrinter::PrintXmlTestsList(
5338 std::ostream* stream,
const std::vector<TestSuite*>& test_suites) {
5341 *stream <<
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
5342 *stream <<
"<" << kTestsuites;
5344 int total_tests = 0;
5345 for (
auto test_suite : test_suites) {
5346 total_tests += test_suite->total_test_count();
5348 OutputXmlAttribute(stream, kTestsuites,
"tests",
5350 OutputXmlAttribute(stream, kTestsuites,
"name",
"AllTests");
5353 for (
auto test_suite : test_suites) {
5354 PrintXmlTestSuite(stream, *test_suite);
5356 *stream <<
"</" << kTestsuites <<
">\n";
5361 std::string XmlUnitTestResultPrinter::TestPropertiesAsXmlAttributes(
5362 const TestResult& result) {
5364 for (
int i = 0; i < result.test_property_count(); ++i) {
5365 const TestProperty&
property = result.GetTestProperty(i);
5366 attributes <<
" " <<
property.key() <<
"=" 5367 <<
"\"" << EscapeXmlAttribute(property.value()) <<
"\"";
5369 return attributes.GetString();
5372 void XmlUnitTestResultPrinter::OutputXmlTestProperties(
5373 std::ostream* stream,
const TestResult& result) {
5377 if (result.test_property_count() <= 0) {
5381 *stream <<
"<" << kProperties <<
">\n";
5382 for (
int i = 0; i < result.test_property_count(); ++i) {
5383 const TestProperty&
property = result.GetTestProperty(i);
5384 *stream <<
"<" << kProperty;
5385 *stream <<
" name=\"" << EscapeXmlAttribute(property.key()) <<
"\"";
5386 *stream <<
" value=\"" << EscapeXmlAttribute(property.value()) <<
"\"";
5389 *stream <<
"</" << kProperties <<
">\n";
5395 class JsonUnitTestResultPrinter :
public EmptyTestEventListener {
5397 explicit JsonUnitTestResultPrinter(
const char* output_file);
5399 void OnTestIterationEnd(
const UnitTest& unit_test,
int iteration)
override;
5402 static void PrintJsonTestList(::std::ostream* stream,
5403 const std::vector<TestSuite*>& test_suites);
5411 static void OutputJsonKey(std::ostream* stream,
5417 static void OutputJsonKey(std::ostream* stream,
5425 static void OutputJsonTestInfo(::std::ostream* stream,
5426 const char* test_suite_name,
5427 const TestInfo& test_info);
5430 static void PrintJsonTestSuite(::std::ostream* stream,
5431 const TestSuite& test_suite);
5434 static void PrintJsonUnitTest(::std::ostream* stream,
5435 const UnitTest& unit_test);
5439 static std::string TestPropertiesAsJson(
const TestResult& result,
5449 JsonUnitTestResultPrinter::JsonUnitTestResultPrinter(
const char* output_file)
5450 : output_file_(output_file) {
5451 if (output_file_.empty()) {
5452 GTEST_LOG_(FATAL) <<
"JSON output file may not be null";
5456 void JsonUnitTestResultPrinter::OnTestIterationEnd(
const UnitTest& unit_test,
5458 FILE* jsonout = OpenFileForWriting(output_file_);
5459 std::stringstream stream;
5460 PrintJsonUnitTest(&stream, unit_test);
5461 fprintf(jsonout,
"%s", StringStreamToString(&stream).c_str());
5469 for (
size_t i = 0; i < str.size(); ++i) {
5470 const char ch = str[i];
5494 m <<
"\\u00" << String::FormatByte(static_cast<unsigned char>(ch));
5502 return m.GetString();
5510 ::std::stringstream ss;
5511 ss << (static_cast<double>(ms) * 1e-3) <<
"s";
5518 struct tm time_struct;
5519 if (!PortableLocaltime(static_cast<time_t>(ms / 1000), &time_struct))
5523 String::FormatIntWidth2(time_struct.tm_mon + 1) +
"-" +
5524 String::FormatIntWidth2(time_struct.tm_mday) +
"T" +
5525 String::FormatIntWidth2(time_struct.tm_hour) +
":" +
5526 String::FormatIntWidth2(time_struct.tm_min) +
":" +
5527 String::FormatIntWidth2(time_struct.tm_sec) +
"Z";
5534 void JsonUnitTestResultPrinter::OutputJsonKey(
5535 std::ostream* stream,
5541 const std::vector<std::string>& allowed_names =
5542 GetReservedAttributesForElement(element_name);
5545 allowed_names.end())
5546 <<
"Key \"" << name <<
"\" is not allowed for value \"" << element_name
5549 *stream << indent <<
"\"" << name <<
"\": \"" << EscapeJson(value) <<
"\"";
5554 void JsonUnitTestResultPrinter::OutputJsonKey(
5555 std::ostream* stream,
5561 const std::vector<std::string>& allowed_names =
5562 GetReservedAttributesForElement(element_name);
5565 allowed_names.end())
5566 <<
"Key \"" << name <<
"\" is not allowed for value \"" << element_name
5575 void JsonUnitTestResultPrinter::OutputJsonTestInfo(::std::ostream* stream,
5576 const char* test_suite_name,
5577 const TestInfo& test_info) {
5578 const TestResult& result = *test_info.result();
5582 *stream << Indent(8) <<
"{\n";
5583 OutputJsonKey(stream, kTestsuite,
"name", test_info.name(), kIndent);
5585 if (test_info.value_param() !=
nullptr) {
5586 OutputJsonKey(stream, kTestsuite,
"value_param", test_info.value_param(),
5589 if (test_info.type_param() !=
nullptr) {
5590 OutputJsonKey(stream, kTestsuite,
"type_param", test_info.type_param(),
5594 OutputJsonKey(stream, kTestsuite,
"file", test_info.file(), kIndent);
5595 OutputJsonKey(stream, kTestsuite,
"line", test_info.line(), kIndent,
false);
5596 *stream <<
"\n" << Indent(8) <<
"}";
5601 stream, kTestsuite,
"status",
5602 result.Skipped() ?
"SKIPPED" : test_info.should_run() ?
"RUN" :
"NOTRUN",
5604 OutputJsonKey(stream, kTestsuite,
"time",
5605 FormatTimeInMillisAsDuration(result.elapsed_time()), kIndent);
5606 OutputJsonKey(stream, kTestsuite,
"classname", test_suite_name, kIndent,
5608 *stream << TestPropertiesAsJson(result, kIndent);
5611 for (
int i = 0; i < result.total_part_count(); ++i) {
5612 const TestPartResult& part = result.GetTestPartResult(i);
5613 if (part.failed()) {
5615 if (++failures == 1) {
5616 *stream << kIndent <<
"\"" <<
"failures" <<
"\": [\n";
5620 part.line_number());
5621 const std::string message = EscapeJson(location +
"\n" + part.message());
5622 *stream << kIndent <<
" {\n" 5623 << kIndent <<
" \"failure\": \"" << message <<
"\",\n" 5624 << kIndent <<
" \"type\": \"\"\n" 5630 *stream <<
"\n" << kIndent <<
"]";
5631 *stream <<
"\n" << Indent(8) <<
"}";
5635 void JsonUnitTestResultPrinter::PrintJsonTestSuite(
5636 std::ostream* stream,
const TestSuite& test_suite) {
5640 *stream << Indent(4) <<
"{\n";
5641 OutputJsonKey(stream, kTestsuite,
"name", test_suite.name(), kIndent);
5642 OutputJsonKey(stream, kTestsuite,
"tests", test_suite.reportable_test_count(),
5645 OutputJsonKey(stream, kTestsuite,
"failures",
5646 test_suite.failed_test_count(), kIndent);
5647 OutputJsonKey(stream, kTestsuite,
"disabled",
5648 test_suite.reportable_disabled_test_count(), kIndent);
5649 OutputJsonKey(stream, kTestsuite,
"errors", 0, kIndent);
5650 OutputJsonKey(stream, kTestsuite,
"time",
5651 FormatTimeInMillisAsDuration(test_suite.elapsed_time()),
5653 *stream << TestPropertiesAsJson(test_suite.ad_hoc_test_result(), kIndent)
5657 *stream << kIndent <<
"\"" << kTestsuite <<
"\": [\n";
5660 for (
int i = 0; i < test_suite.total_test_count(); ++i) {
5661 if (test_suite.GetTestInfo(i)->is_reportable()) {
5667 OutputJsonTestInfo(stream, test_suite.name(), *test_suite.GetTestInfo(i));
5670 *stream <<
"\n" << kIndent <<
"]\n" << Indent(4) <<
"}";
5674 void JsonUnitTestResultPrinter::PrintJsonUnitTest(std::ostream* stream,
5675 const UnitTest& unit_test) {
5680 OutputJsonKey(stream, kTestsuites,
"tests", unit_test.reportable_test_count(),
5682 OutputJsonKey(stream, kTestsuites,
"failures", unit_test.failed_test_count(),
5684 OutputJsonKey(stream, kTestsuites,
"disabled",
5685 unit_test.reportable_disabled_test_count(), kIndent);
5686 OutputJsonKey(stream, kTestsuites,
"errors", 0, kIndent);
5688 OutputJsonKey(stream, kTestsuites,
"random_seed", unit_test.random_seed(),
5691 OutputJsonKey(stream, kTestsuites,
"timestamp",
5692 FormatEpochTimeInMillisAsRFC3339(unit_test.start_timestamp()),
5694 OutputJsonKey(stream, kTestsuites,
"time",
5695 FormatTimeInMillisAsDuration(unit_test.elapsed_time()), kIndent,
5698 *stream << TestPropertiesAsJson(unit_test.ad_hoc_test_result(), kIndent)
5701 OutputJsonKey(stream, kTestsuites,
"name",
"AllTests", kIndent);
5702 *stream << kIndent <<
"\"" << kTestsuites <<
"\": [\n";
5705 for (
int i = 0; i < unit_test.total_test_suite_count(); ++i) {
5706 if (unit_test.GetTestSuite(i)->reportable_test_count() > 0) {
5712 PrintJsonTestSuite(stream, *unit_test.GetTestSuite(i));
5716 *stream <<
"\n" << kIndent <<
"]\n" <<
"}\n";
5719 void JsonUnitTestResultPrinter::PrintJsonTestList(
5720 std::ostream* stream,
const std::vector<TestSuite*>& test_suites) {
5724 int total_tests = 0;
5725 for (
auto test_suite : test_suites) {
5726 total_tests += test_suite->total_test_count();
5728 OutputJsonKey(stream, kTestsuites,
"tests", total_tests, kIndent);
5730 OutputJsonKey(stream, kTestsuites,
"name",
"AllTests", kIndent);
5731 *stream << kIndent <<
"\"" << kTestsuites <<
"\": [\n";
5733 for (
size_t i = 0; i < test_suites.size(); ++i) {
5737 PrintJsonTestSuite(stream, *test_suites[i]);
5746 std::string JsonUnitTestResultPrinter::TestPropertiesAsJson(
5747 const TestResult& result,
const std::string& indent) {
5749 for (
int i = 0; i < result.test_property_count(); ++i) {
5750 const TestProperty&
property = result.GetTestProperty(i);
5751 attributes <<
",\n" << indent <<
"\"" <<
property.key() <<
"\": " 5752 <<
"\"" << EscapeJson(property.value()) <<
"\"";
5754 return attributes.GetString();
5759 #if GTEST_CAN_STREAM_RESULTS_ 5766 std::string StreamingListener::UrlEncode(
const char* str) {
5768 result.reserve(strlen(str) + 1);
5769 for (
char ch = *str; ch !=
'\0'; ch = *++str) {
5775 result.append(
"%" + String::FormatByte(static_cast<unsigned char>(ch)));
5778 result.push_back(ch);
5785 void StreamingListener::SocketWriter::MakeConnection() {
5787 <<
"MakeConnection() can't be called when there is already a connection.";
5790 memset(&hints, 0,
sizeof(hints));
5791 hints.ai_family = AF_UNSPEC;
5792 hints.ai_socktype = SOCK_STREAM;
5793 addrinfo* servinfo =
nullptr;
5797 const int error_num = getaddrinfo(
5798 host_name_.c_str(), port_num_.c_str(), &hints, &servinfo);
5799 if (error_num != 0) {
5800 GTEST_LOG_(WARNING) <<
"stream_result_to: getaddrinfo() failed: " 5801 << gai_strerror(error_num);
5805 for (addrinfo* cur_addr = servinfo; sockfd_ == -1 && cur_addr !=
nullptr;
5806 cur_addr = cur_addr->ai_next) {
5808 cur_addr->ai_family, cur_addr->ai_socktype, cur_addr->ai_protocol);
5809 if (sockfd_ != -1) {
5811 if (connect(sockfd_, cur_addr->ai_addr, cur_addr->ai_addrlen) == -1) {
5818 freeaddrinfo(servinfo);
5820 if (sockfd_ == -1) {
5821 GTEST_LOG_(WARNING) <<
"stream_result_to: failed to connect to " 5822 << host_name_ <<
":" << port_num_;
5827 #endif // GTEST_CAN_STREAM_RESULTS__ 5831 const char*
const OsStackTraceGetterInterface::kElidedFramesMarker =
5834 std::string OsStackTraceGetter::CurrentStackTrace(
int max_depth,
int skip_count)
5839 if (max_depth <= 0) {
5843 max_depth = std::min(max_depth, kMaxStackTraceDepth);
5845 std::vector<void*> raw_stack(max_depth);
5847 const int raw_stack_size =
5848 absl::GetStackTrace(&raw_stack[0], max_depth, skip_count + 1);
5850 void* caller_frame =
nullptr;
5853 caller_frame = caller_frame_;
5856 for (
int i = 0; i < raw_stack_size; ++i) {
5857 if (raw_stack[i] == caller_frame &&
5860 absl::StrAppend(&result, kElidedFramesMarker,
"\n");
5865 const char* symbol =
"(unknown)";
5866 if (absl::Symbolize(raw_stack[i], tmp,
sizeof(tmp))) {
5871 snprintf(line,
sizeof(line),
" %p: %s\n", raw_stack[i], symbol);
5877 #else // !GTEST_HAS_ABSL 5878 static_cast<void>(max_depth);
5879 static_cast<void>(skip_count);
5881 #endif // GTEST_HAS_ABSL 5886 void* caller_frame =
nullptr;
5887 if (absl::GetStackTrace(&caller_frame, 1, 3) <= 0) {
5888 caller_frame =
nullptr;
5892 caller_frame_ = caller_frame;
5893 #endif // GTEST_HAS_ABSL 5898 class ScopedPrematureExitFile {
5900 explicit ScopedPrematureExitFile(
const char* premature_exit_filepath)
5901 : premature_exit_filepath_(premature_exit_filepath ?
5902 premature_exit_filepath :
"") {
5904 if (!premature_exit_filepath_.empty()) {
5908 FILE* pfile =
posix::FOpen(premature_exit_filepath,
"w");
5909 fwrite(
"0", 1, 1, pfile);
5914 ~ScopedPrematureExitFile() {
5915 if (!premature_exit_filepath_.empty()) {
5916 int retval =
remove(premature_exit_filepath_.c_str());
5918 GTEST_LOG_(ERROR) <<
"Failed to remove premature exit filepath \"" 5919 << premature_exit_filepath_ <<
"\" with error " 5935 TestEventListeners::TestEventListeners()
5936 : repeater_(new internal::TestEventRepeater()),
5937 default_result_printer_(nullptr),
5938 default_xml_generator_(nullptr) {}
5940 TestEventListeners::~TestEventListeners() {
delete repeater_; }
5946 void TestEventListeners::Append(TestEventListener* listener) {
5947 repeater_->Append(listener);
5953 TestEventListener* TestEventListeners::Release(TestEventListener* listener) {
5954 if (listener == default_result_printer_)
5955 default_result_printer_ =
nullptr;
5956 else if (listener == default_xml_generator_)
5957 default_xml_generator_ =
nullptr;
5958 return repeater_->Release(listener);
5963 TestEventListener* TestEventListeners::repeater() {
return repeater_; }
5970 void TestEventListeners::SetDefaultResultPrinter(TestEventListener* listener) {
5971 if (default_result_printer_ != listener) {
5974 delete Release(default_result_printer_);
5975 default_result_printer_ = listener;
5976 if (listener !=
nullptr) Append(listener);
5985 void TestEventListeners::SetDefaultXmlGenerator(TestEventListener* listener) {
5986 if (default_xml_generator_ != listener) {
5989 delete Release(default_xml_generator_);
5990 default_xml_generator_ = listener;
5991 if (listener !=
nullptr) Append(listener);
5997 bool TestEventListeners::EventForwardingEnabled()
const {
5998 return repeater_->forwarding_enabled();
6001 void TestEventListeners::SuppressEventForwarding() {
6002 repeater_->set_forwarding_enabled(
false);
6014 UnitTest* UnitTest::GetInstance() {
6019 #if defined(__BORLANDC__) 6020 static UnitTest*
const instance =
new UnitTest;
6023 static UnitTest instance;
6025 #endif // defined(__BORLANDC__) 6029 int UnitTest::successful_test_suite_count()
const {
6030 return impl()->successful_test_suite_count();
6034 int UnitTest::failed_test_suite_count()
const {
6035 return impl()->failed_test_suite_count();
6039 int UnitTest::total_test_suite_count()
const {
6040 return impl()->total_test_suite_count();
6045 int UnitTest::test_suite_to_run_count()
const {
6046 return impl()->test_suite_to_run_count();
6050 #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_ 6051 int UnitTest::successful_test_case_count()
const {
6052 return impl()->successful_test_suite_count();
6054 int UnitTest::failed_test_case_count()
const {
6055 return impl()->failed_test_suite_count();
6057 int UnitTest::total_test_case_count()
const {
6058 return impl()->total_test_suite_count();
6060 int UnitTest::test_case_to_run_count()
const {
6061 return impl()->test_suite_to_run_count();
6063 #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_ 6066 int UnitTest::successful_test_count()
const {
6067 return impl()->successful_test_count();
6071 int UnitTest::skipped_test_count()
const {
6072 return impl()->skipped_test_count();
6076 int UnitTest::failed_test_count()
const {
return impl()->failed_test_count(); }
6079 int UnitTest::reportable_disabled_test_count()
const {
6080 return impl()->reportable_disabled_test_count();
6084 int UnitTest::disabled_test_count()
const {
6085 return impl()->disabled_test_count();
6089 int UnitTest::reportable_test_count()
const {
6090 return impl()->reportable_test_count();
6094 int UnitTest::total_test_count()
const {
return impl()->total_test_count(); }
6097 int UnitTest::test_to_run_count()
const {
return impl()->test_to_run_count(); }
6102 return impl()->start_timestamp();
6107 return impl()->elapsed_time();
6111 bool UnitTest::Passed()
const {
return impl()->Passed(); }
6115 bool UnitTest::Failed()
const {
return impl()->Failed(); }
6119 const TestSuite* UnitTest::GetTestSuite(
int i)
const {
6120 return impl()->GetTestSuite(i);
6124 #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_ 6125 const TestCase* UnitTest::GetTestCase(
int i)
const {
6126 return impl()->GetTestCase(i);
6128 #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_ 6132 const TestResult& UnitTest::ad_hoc_test_result()
const {
6133 return *impl()->ad_hoc_test_result();
6138 TestSuite* UnitTest::GetMutableTestSuite(
int i) {
6139 return impl()->GetMutableSuiteCase(i);
6144 TestEventListeners& UnitTest::listeners() {
6145 return *impl()->listeners();
6158 Environment* UnitTest::AddEnvironment(Environment* env) {
6159 if (env ==
nullptr) {
6163 impl_->environments().push_back(env);
6171 void UnitTest::AddTestPartResult(
6172 TestPartResult::Type result_type,
6173 const char* file_name,
6181 if (impl_->gtest_trace_stack().size() > 0) {
6184 for (
int i = static_cast<int>(impl_->gtest_trace_stack().size());
6186 const internal::TraceInfo& trace = impl_->gtest_trace_stack()[i - 1];
6188 <<
" " << trace.message;
6192 if (os_stack_trace.c_str() !=
nullptr && !os_stack_trace.empty()) {
6196 const TestPartResult result = TestPartResult(
6197 result_type, file_name, line_number, msg.GetString().c_str());
6198 impl_->GetTestPartResultReporterForCurrentThread()->
6199 ReportTestPartResult(result);
6201 if (result_type != TestPartResult::kSuccess &&
6202 result_type != TestPartResult::kSkip) {
6209 #if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_PHONE && !GTEST_OS_WINDOWS_RT 6214 #elif (!defined(__native_client__)) && \ 6215 ((defined(__clang__) || defined(__GNUC__)) && \ 6216 (defined(__x86_64__) || defined(__i386__))) 6223 *
static_cast<volatile int*
>(
nullptr) = 1;
6224 #endif // GTEST_OS_WINDOWS 6226 #if GTEST_HAS_EXCEPTIONS 6227 throw internal::GoogleTestFailureException(result);
6242 void UnitTest::RecordProperty(
const std::string& key,
6244 impl_->RecordProperty(TestProperty(key, value));
6252 int UnitTest::Run() {
6253 const bool in_death_test_child_process =
6277 const internal::ScopedPrematureExitFile premature_exit_file(
6278 in_death_test_child_process
6284 impl()->set_catch_exceptions(
GTEST_FLAG(catch_exceptions));
6286 #if GTEST_OS_WINDOWS 6291 if (impl()->catch_exceptions() || in_death_test_child_process) {
6292 # if !GTEST_OS_WINDOWS_MOBILE && !GTEST_OS_WINDOWS_PHONE && !GTEST_OS_WINDOWS_RT 6294 SetErrorMode(SEM_FAILCRITICALERRORS | SEM_NOALIGNMENTFAULTEXCEPT |
6295 SEM_NOGPFAULTERRORBOX | SEM_NOOPENFILEERRORBOX);
6296 # endif // !GTEST_OS_WINDOWS_MOBILE 6298 # if (defined(_MSC_VER) || GTEST_OS_WINDOWS_MINGW) && !GTEST_OS_WINDOWS_MOBILE 6302 _set_error_mode(_OUT_TO_STDERR);
6305 # if defined(_MSC_VER) && !GTEST_OS_WINDOWS_MOBILE 6312 _set_abort_behavior(
6314 _WRITE_ABORT_MSG | _CALL_REPORTFAULT);
6317 #endif // GTEST_OS_WINDOWS 6319 return internal::HandleExceptionsInMethodIfSupported(
6321 &internal::UnitTestImpl::RunAllTests,
6322 "auxiliary test code (environments or event listeners)") ? 0 : 1;
6327 const char* UnitTest::original_working_dir()
const {
6328 return impl_->original_working_dir_.c_str();
6333 const TestSuite* UnitTest::current_test_suite() const
6336 return impl_->current_test_suite();
6340 #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_ 6341 const TestCase* UnitTest::current_test_case() const
6344 return impl_->current_test_suite();
6350 const TestInfo* UnitTest::current_test_info() const
6353 return impl_->current_test_info();
6357 int UnitTest::random_seed()
const {
return impl_->random_seed(); }
6361 internal::ParameterizedTestSuiteRegistry&
6363 return impl_->parameterized_test_registry();
6367 UnitTest::UnitTest() {
6368 impl_ =
new internal::UnitTestImpl(
this);
6372 UnitTest::~UnitTest() {
6378 void UnitTest::PushGTestTrace(
const internal::TraceInfo& trace)
6381 impl_->gtest_trace_stack().push_back(trace);
6385 void UnitTest::PopGTestTrace()
6388 impl_->gtest_trace_stack().pop_back();
6391 namespace internal {
6393 UnitTestImpl::UnitTestImpl(UnitTest* parent)
6396 default_global_test_part_result_reporter_(this),
6397 default_per_thread_test_part_result_reporter_(this),
6399 &default_global_test_part_result_reporter_),
6400 per_thread_test_part_result_reporter_(
6401 &default_per_thread_test_part_result_reporter_),
6402 parameterized_test_registry_(),
6403 parameterized_tests_registered_(false),
6404 last_death_test_suite_(-1),
6405 current_test_suite_(nullptr),
6406 current_test_info_(nullptr),
6407 ad_hoc_test_result_(),
6408 os_stack_trace_getter_(nullptr),
6409 post_flag_parse_init_performed_(false),
6412 start_timestamp_(0),
6414 #if GTEST_HAS_DEATH_TEST
6415 death_test_factory_(new DefaultDeathTestFactory),
6418 catch_exceptions_(false) {
6419 listeners()->SetDefaultResultPrinter(
new PrettyUnitTestResultPrinter);
6422 UnitTestImpl::~UnitTestImpl() {
6424 ForEach(test_suites_, internal::Delete<TestSuite>);
6427 ForEach(environments_, internal::Delete<Environment>);
6429 delete os_stack_trace_getter_;
6437 void UnitTestImpl::RecordProperty(
const TestProperty& test_property) {
6439 TestResult* test_result;
6441 if (current_test_info_ !=
nullptr) {
6442 xml_element =
"testcase";
6443 test_result = &(current_test_info_->result_);
6444 }
else if (current_test_suite_ !=
nullptr) {
6445 xml_element =
"testsuite";
6446 test_result = &(current_test_suite_->ad_hoc_test_result_);
6448 xml_element =
"testsuites";
6449 test_result = &ad_hoc_test_result_;
6451 test_result->RecordProperty(xml_element, test_property);
6454 #if GTEST_HAS_DEATH_TEST 6457 void UnitTestImpl::SuppressTestEventsIfInSubprocess() {
6458 if (internal_run_death_test_flag_.get() !=
nullptr)
6459 listeners()->SuppressEventForwarding();
6461 #endif // GTEST_HAS_DEATH_TEST 6465 void UnitTestImpl::ConfigureXmlOutput() {
6466 const std::string& output_format = UnitTestOptions::GetOutputFormat();
6467 if (output_format ==
"xml") {
6468 listeners()->SetDefaultXmlGenerator(
new XmlUnitTestResultPrinter(
6469 UnitTestOptions::GetAbsolutePathToOutputFile().c_str()));
6470 }
else if (output_format ==
"json") {
6471 listeners()->SetDefaultXmlGenerator(
new JsonUnitTestResultPrinter(
6472 UnitTestOptions::GetAbsolutePathToOutputFile().c_str()));
6473 }
else if (output_format !=
"") {
6474 GTEST_LOG_(WARNING) <<
"WARNING: unrecognized output format \"" 6475 << output_format <<
"\" ignored.";
6479 #if GTEST_CAN_STREAM_RESULTS_ 6482 void UnitTestImpl::ConfigureStreamingOutput() {
6484 if (!target.empty()) {
6485 const size_t pos = target.find(
':');
6486 if (pos != std::string::npos) {
6487 listeners()->Append(
new StreamingListener(target.substr(0, pos),
6488 target.substr(pos+1)));
6490 GTEST_LOG_(WARNING) <<
"unrecognized streaming target \"" << target
6495 #endif // GTEST_CAN_STREAM_RESULTS_ 6502 void UnitTestImpl::PostFlagParsingInit() {
6504 if (!post_flag_parse_init_performed_) {
6505 post_flag_parse_init_performed_ =
true;
6507 #if defined(GTEST_CUSTOM_TEST_EVENT_LISTENER_) 6509 listeners()->Append(
new GTEST_CUSTOM_TEST_EVENT_LISTENER_());
6510 #endif // defined(GTEST_CUSTOM_TEST_EVENT_LISTENER_) 6512 #if GTEST_HAS_DEATH_TEST 6513 InitDeathTestSubprocessControlInfo();
6514 SuppressTestEventsIfInSubprocess();
6515 #endif // GTEST_HAS_DEATH_TEST 6520 RegisterParameterizedTests();
6524 ConfigureXmlOutput();
6526 #if GTEST_CAN_STREAM_RESULTS_ 6528 ConfigureStreamingOutput();
6529 #endif // GTEST_CAN_STREAM_RESULTS_ 6532 if (
GTEST_FLAG(install_failure_signal_handler)) {
6533 absl::FailureSignalHandlerOptions options;
6534 absl::InstallFailureSignalHandler(options);
6536 #endif // GTEST_HAS_ABSL 6548 class TestSuiteNameIs {
6551 explicit TestSuiteNameIs(
const std::string& name) : name_(name) {}
6554 bool operator()(
const TestSuite* test_suite)
const {
6555 return test_suite !=
nullptr &&
6556 strcmp(test_suite->name(), name_.c_str()) == 0;
6575 TestSuite* UnitTestImpl::GetTestSuite(
6576 const char* test_suite_name,
const char* type_param,
6580 const auto test_suite =
6581 std::find_if(test_suites_.rbegin(), test_suites_.rend(),
6582 TestSuiteNameIs(test_suite_name));
6584 if (test_suite != test_suites_.rend())
return *test_suite;
6587 auto*
const new_test_suite =
6588 new TestSuite(test_suite_name, type_param, set_up_tc, tear_down_tc);
6591 if (internal::UnitTestOptions::MatchesFilter(test_suite_name,
6592 kDeathTestSuiteFilter)) {
6597 ++last_death_test_suite_;
6598 test_suites_.insert(test_suites_.begin() + last_death_test_suite_,
6602 test_suites_.push_back(new_test_suite);
6605 test_suite_indices_.push_back(static_cast<int>(test_suite_indices_.size()));
6606 return new_test_suite;
6611 static void SetUpEnvironment(Environment* env) { env->SetUp(); }
6612 static void TearDownEnvironment(Environment* env) { env->TearDown(); }
6623 bool UnitTestImpl::RunAllTests() {
6625 const bool gtest_is_initialized_before_run_all_tests = GTestIsInitialized();
6633 PostFlagParsingInit();
6638 internal::WriteToShardStatusFileIfNeeded();
6642 bool in_subprocess_for_death_test =
false;
6644 #if GTEST_HAS_DEATH_TEST 6645 in_subprocess_for_death_test =
6646 (internal_run_death_test_flag_.get() !=
nullptr);
6647 # if defined(GTEST_EXTRA_DEATH_TEST_CHILD_SETUP_) 6648 if (in_subprocess_for_death_test) {
6649 GTEST_EXTRA_DEATH_TEST_CHILD_SETUP_();
6651 # endif // defined(GTEST_EXTRA_DEATH_TEST_CHILD_SETUP_) 6652 #endif // GTEST_HAS_DEATH_TEST 6654 const bool should_shard = ShouldShard(kTestTotalShards, kTestShardIndex,
6655 in_subprocess_for_death_test);
6659 const bool has_tests_to_run = FilterTests(should_shard
6660 ? HONOR_SHARDING_PROTOCOL
6661 : IGNORE_SHARDING_PROTOCOL) > 0;
6666 ListTestsMatchingFilter();
6671 GetRandomSeedFromFlag(
GTEST_FLAG(random_seed)) : 0;
6674 bool failed =
false;
6676 TestEventListener* repeater = listeners()->repeater();
6678 start_timestamp_ = GetTimeInMillis();
6679 repeater->OnTestProgramStart(*parent_);
6685 const bool forever =
repeat < 0;
6686 for (
int i = 0; forever || i !=
repeat; i++) {
6689 ClearNonAdHocTestResult();
6694 if (has_tests_to_run &&
GTEST_FLAG(shuffle)) {
6695 random()->Reseed(random_seed_);
6703 repeater->OnTestIterationStart(*parent_, i);
6706 if (has_tests_to_run) {
6708 repeater->OnEnvironmentsSetUpStart(*parent_);
6709 ForEach(environments_, SetUpEnvironment);
6710 repeater->OnEnvironmentsSetUpEnd(*parent_);
6714 if (!Test::HasFatalFailure()) {
6715 for (
int test_index = 0; test_index < total_test_suite_count();
6717 GetMutableSuiteCase(test_index)->Run();
6722 repeater->OnEnvironmentsTearDownStart(*parent_);
6723 std::for_each(environments_.rbegin(), environments_.rend(),
6724 TearDownEnvironment);
6725 repeater->OnEnvironmentsTearDownEnd(*parent_);
6728 elapsed_time_ = GetTimeInMillis() - start;
6731 repeater->OnTestIterationEnd(*parent_, i);
6748 random_seed_ = GetNextRandomSeed(random_seed_);
6752 repeater->OnTestProgramEnd(*parent_);
6754 if (!gtest_is_initialized_before_run_all_tests) {
6757 "\nIMPORTANT NOTICE - DO NOT IGNORE:\n" 6759 "() before calling RUN_ALL_TESTS(). This is INVALID. Soon " GTEST_NAME_ 6760 " will start to enforce the valid usage. " 6761 "Please fix it ASAP, or IT WILL START TO FAIL.\n");
6762 #if GTEST_FOR_GOOGLE_ 6764 "For more details, see http://wiki/Main/ValidGUnitMain.\n");
6765 #endif // GTEST_FOR_GOOGLE_ 6775 void WriteToShardStatusFileIfNeeded() {
6776 const char*
const test_shard_file =
posix::GetEnv(kTestShardStatusFile);
6777 if (test_shard_file !=
nullptr) {
6779 if (file ==
nullptr) {
6781 "Could not write to the test shard status file \"%s\" " 6782 "specified by the %s environment variable.\n",
6783 test_shard_file, kTestShardStatusFile);
6797 bool ShouldShard(
const char* total_shards_env,
6798 const char* shard_index_env,
6799 bool in_subprocess_for_death_test) {
6800 if (in_subprocess_for_death_test) {
6804 const Int32 total_shards = Int32FromEnvOrDie(total_shards_env, -1);
6805 const Int32 shard_index = Int32FromEnvOrDie(shard_index_env, -1);
6807 if (total_shards == -1 && shard_index == -1) {
6809 }
else if (total_shards == -1 && shard_index != -1) {
6810 const Message msg = Message()
6811 <<
"Invalid environment variables: you have " 6812 << kTestShardIndex <<
" = " << shard_index
6813 <<
", but have left " << kTestTotalShards <<
" unset.\n";
6814 ColoredPrintf(
COLOR_RED,
"%s", msg.GetString().c_str());
6817 }
else if (total_shards != -1 && shard_index == -1) {
6818 const Message msg = Message()
6819 <<
"Invalid environment variables: you have " 6820 << kTestTotalShards <<
" = " << total_shards
6821 <<
", but have left " << kTestShardIndex <<
" unset.\n";
6822 ColoredPrintf(
COLOR_RED,
"%s", msg.GetString().c_str());
6825 }
else if (shard_index < 0 || shard_index >= total_shards) {
6826 const Message msg = Message()
6827 <<
"Invalid environment variables: we require 0 <= " 6828 << kTestShardIndex <<
" < " << kTestTotalShards
6829 <<
", but you have " << kTestShardIndex <<
"=" << shard_index
6830 <<
", " << kTestTotalShards <<
"=" << total_shards <<
".\n";
6831 ColoredPrintf(
COLOR_RED,
"%s", msg.GetString().c_str());
6836 return total_shards > 1;
6842 Int32 Int32FromEnvOrDie(
const char* var,
Int32 default_val) {
6844 if (str_val ==
nullptr) {
6849 if (!
ParseInt32(Message() <<
"The value of environment variable " << var,
6850 str_val, &result)) {
6860 bool ShouldRunTestOnShard(
int total_shards,
int shard_index,
int test_id) {
6861 return (test_id % total_shards) == shard_index;
6871 int UnitTestImpl::FilterTests(ReactionToSharding shard_tests) {
6872 const Int32 total_shards = shard_tests == HONOR_SHARDING_PROTOCOL ?
6873 Int32FromEnvOrDie(kTestTotalShards, -1) : -1;
6874 const Int32 shard_index = shard_tests == HONOR_SHARDING_PROTOCOL ?
6875 Int32FromEnvOrDie(kTestShardIndex, -1) : -1;
6881 int num_runnable_tests = 0;
6882 int num_selected_tests = 0;
6883 for (
auto* test_suite : test_suites_) {
6884 const std::string& test_suite_name = test_suite->name();
6885 test_suite->set_should_run(
false);
6887 for (
size_t j = 0; j < test_suite->test_info_list().size(); j++) {
6888 TestInfo*
const test_info = test_suite->test_info_list()[j];
6892 const bool is_disabled = internal::UnitTestOptions::MatchesFilter(
6893 test_suite_name, kDisableTestFilter) ||
6894 internal::UnitTestOptions::MatchesFilter(
6895 test_name, kDisableTestFilter);
6896 test_info->is_disabled_ = is_disabled;
6898 const bool matches_filter = internal::UnitTestOptions::FilterMatchesTest(
6899 test_suite_name, test_name);
6900 test_info->matches_filter_ = matches_filter;
6902 const bool is_runnable =
6903 (
GTEST_FLAG(also_run_disabled_tests) || !is_disabled) &&
6906 const bool is_in_another_shard =
6907 shard_tests != IGNORE_SHARDING_PROTOCOL &&
6908 !ShouldRunTestOnShard(total_shards, shard_index, num_runnable_tests);
6909 test_info->is_in_another_shard_ = is_in_another_shard;
6910 const bool is_selected = is_runnable && !is_in_another_shard;
6912 num_runnable_tests += is_runnable;
6913 num_selected_tests += is_selected;
6915 test_info->should_run_ = is_selected;
6916 test_suite->set_should_run(test_suite->should_run() || is_selected);
6919 return num_selected_tests;
6926 static void PrintOnOneLine(
const char* str,
int max_length) {
6927 if (str !=
nullptr) {
6928 for (
int i = 0; *str !=
'\0'; ++str) {
6929 if (i >= max_length) {
6945 void UnitTestImpl::ListTestsMatchingFilter() {
6947 const int kMaxParamLength = 250;
6949 for (
auto* test_suite : test_suites_) {
6950 bool printed_test_suite_name =
false;
6952 for (
size_t j = 0; j < test_suite->test_info_list().size(); j++) {
6953 const TestInfo*
const test_info = test_suite->test_info_list()[j];
6954 if (test_info->matches_filter_) {
6955 if (!printed_test_suite_name) {
6956 printed_test_suite_name =
true;
6957 printf(
"%s.", test_suite->name());
6958 if (test_suite->type_param() !=
nullptr) {
6959 printf(
" # %s = ", kTypeParamLabel);
6962 PrintOnOneLine(test_suite->type_param(), kMaxParamLength);
6966 printf(
" %s", test_info->name());
6967 if (test_info->value_param() !=
nullptr) {
6968 printf(
" # %s = ", kValueParamLabel);
6971 PrintOnOneLine(test_info->value_param(), kMaxParamLength);
6978 const std::string& output_format = UnitTestOptions::GetOutputFormat();
6979 if (output_format ==
"xml" || output_format ==
"json") {
6980 FILE* fileout = OpenFileForWriting(
6981 UnitTestOptions::GetAbsolutePathToOutputFile().c_str());
6982 std::stringstream stream;
6983 if (output_format ==
"xml") {
6984 XmlUnitTestResultPrinter(
6985 UnitTestOptions::GetAbsolutePathToOutputFile().c_str())
6986 .PrintXmlTestsList(&stream, test_suites_);
6987 }
else if (output_format ==
"json") {
6988 JsonUnitTestResultPrinter(
6989 UnitTestOptions::GetAbsolutePathToOutputFile().c_str())
6990 .PrintJsonTestList(&stream, test_suites_);
6992 fprintf(fileout,
"%s", StringStreamToString(&stream).c_str());
7002 void UnitTestImpl::set_os_stack_trace_getter(
7003 OsStackTraceGetterInterface* getter) {
7004 if (os_stack_trace_getter_ != getter) {
7005 delete os_stack_trace_getter_;
7006 os_stack_trace_getter_ = getter;
7013 OsStackTraceGetterInterface* UnitTestImpl::os_stack_trace_getter() {
7014 if (os_stack_trace_getter_ ==
nullptr) {
7015 #ifdef GTEST_OS_STACK_TRACE_GETTER_ 7016 os_stack_trace_getter_ =
new GTEST_OS_STACK_TRACE_GETTER_;
7018 os_stack_trace_getter_ =
new OsStackTraceGetter;
7019 #endif // GTEST_OS_STACK_TRACE_GETTER_ 7022 return os_stack_trace_getter_;
7026 TestResult* UnitTestImpl::current_test_result() {
7027 if (current_test_info_ !=
nullptr) {
7028 return ¤t_test_info_->result_;
7030 if (current_test_suite_ !=
nullptr) {
7031 return ¤t_test_suite_->ad_hoc_test_result_;
7033 return &ad_hoc_test_result_;
7038 void UnitTestImpl::ShuffleTests() {
7040 ShuffleRange(random(), 0, last_death_test_suite_ + 1, &test_suite_indices_);
7043 ShuffleRange(random(), last_death_test_suite_ + 1,
7044 static_cast<int>(test_suites_.size()), &test_suite_indices_);
7047 for (
auto& test_suite : test_suites_) {
7048 test_suite->ShuffleTests(random());
7053 void UnitTestImpl::UnshuffleTests() {
7054 for (
size_t i = 0; i < test_suites_.size(); i++) {
7056 test_suites_[i]->UnshuffleTests();
7058 test_suite_indices_[i] =
static_cast<int>(i);
7076 return GetUnitTestImpl()->CurrentOsStackTraceExceptTop(skip_count + 1);
7082 class ClassUniqueToAlwaysTrue {};
7085 bool IsTrue(
bool condition) {
return condition; }
7088 #if GTEST_HAS_EXCEPTIONS 7092 throw ClassUniqueToAlwaysTrue();
7093 #endif // GTEST_HAS_EXCEPTIONS 7100 bool SkipPrefix(
const char* prefix,
const char** pstr) {
7101 const size_t prefix_len = strlen(prefix);
7102 if (strncmp(*pstr, prefix, prefix_len) == 0) {
7103 *pstr += prefix_len;
7114 static const char* ParseFlagValue(
const char* str,
const char* flag,
7115 bool def_optional) {
7117 if (str ==
nullptr || flag ==
nullptr)
return nullptr;
7121 const size_t flag_len = flag_str.length();
7122 if (strncmp(str, flag_str.c_str(), flag_len) != 0)
return nullptr;
7125 const char* flag_end = str + flag_len;
7128 if (def_optional && (flag_end[0] ==
'\0')) {
7135 if (flag_end[0] !=
'=')
return nullptr;
7138 return flag_end + 1;
7151 static bool ParseBoolFlag(
const char* str,
const char* flag,
bool* value) {
7153 const char*
const value_str = ParseFlagValue(str, flag,
true);
7156 if (value_str ==
nullptr)
return false;
7159 *value = !(*value_str ==
'0' || *value_str ==
'f' || *value_str ==
'F');
7168 bool ParseInt32Flag(
const char* str,
const char* flag,
Int32* value) {
7170 const char*
const value_str = ParseFlagValue(str, flag,
false);
7173 if (value_str ==
nullptr)
return false;
7176 return ParseInt32(Message() <<
"The value of flag --" << flag,
7185 template <
typename String>
7186 static bool ParseStringFlag(
const char* str,
const char* flag, String* value) {
7188 const char*
const value_str = ParseFlagValue(str, flag,
false);
7191 if (value_str ==
nullptr)
return false;
7204 static bool HasGoogleTestFlagPrefix(
const char* str) {
7222 static void PrintColorEncoded(
const char* str) {
7230 const char* p = strchr(str,
'@');
7232 ColoredPrintf(color,
"%s", str);
7236 ColoredPrintf(color,
"%s",
std::string(str, p).c_str());
7238 const char ch = p[1];
7241 ColoredPrintf(color,
"@");
7242 }
else if (ch ==
'D') {
7244 }
else if (ch ==
'R') {
7246 }
else if (ch ==
'G') {
7248 }
else if (ch ==
'Y') {
7256 static const char kColorEncodedHelpMessage[] =
7257 "This program contains tests written using " GTEST_NAME_ ". You can use the\n" 7258 "following command line flags to control its behavior:\n" 7262 " List the names of all tests instead of running them. The name of\n" 7263 " TEST(Foo, Bar) is \"Foo.Bar\".\n" 7265 "[@G-@YNEGATIVE_PATTERNS]@D\n" 7266 " Run only the tests whose name matches one of the positive patterns but\n" 7267 " none of the negative patterns. '?' matches any single character; '*'\n" 7268 " matches any substring; ':' separates two patterns.\n" 7270 " Run all disabled tests too.\n" 7274 " Run the tests repeatedly; use a negative count to repeat forever.\n" 7276 " Randomize tests' orders on every iteration.\n" 7278 " Random number seed to use for shuffling test orders (between 1 and\n" 7279 " 99999, or 0 to use a seed based on the current time).\n" 7283 " Enable/disable colored output. The default is @Gauto@D.\n" 7285 " Don't print the elapsed time of each test.\n" 7288 " Generate a JSON or XML report in the given directory or with the given\n" 7289 " file name. @YFILE_PATH@D defaults to @Gtest_detail.xml@D.\n" 7290 # if GTEST_CAN_STREAM_RESULTS_ 7292 " Stream test results to the given server.\n" 7293 # endif // GTEST_CAN_STREAM_RESULTS_ 7295 "Assertion Behavior:\n" 7296 # if GTEST_HAS_DEATH_TEST && !GTEST_OS_WINDOWS 7298 " Set the default death test style.\n" 7299 # endif // GTEST_HAS_DEATH_TEST && !GTEST_OS_WINDOWS 7301 " Turn assertion failures into debugger break-points.\n" 7303 " Turn assertion failures into C++ exceptions for use by an external\n" 7304 " test framework.\n" 7306 " Do not report exceptions as test failures. Instead, allow them\n" 7307 " to crash the program or throw a pop-up (on Windows).\n" 7310 "the corresponding\n" 7311 "environment variable of a flag (all letters in upper-case). For example, to\n" 7313 "color=no@D or set\n" 7316 "For more information, please read the " GTEST_NAME_ " documentation at\n" 7318 "(not one in your own code or tests), please report it to\n" 7321 static bool ParseGoogleTestFlag(
const char*
const arg) {
7322 return ParseBoolFlag(arg, kAlsoRunDisabledTestsFlag,
7324 ParseBoolFlag(arg, kBreakOnFailureFlag,
7326 ParseBoolFlag(arg, kCatchExceptionsFlag,
7328 ParseStringFlag(arg, kColorFlag, &
GTEST_FLAG(color)) ||
7329 ParseStringFlag(arg, kDeathTestStyleFlag,
7331 ParseBoolFlag(arg, kDeathTestUseFork,
7334 ParseStringFlag(arg, kInternalRunDeathTestFlag,
7336 ParseBoolFlag(arg, kListTestsFlag, &
GTEST_FLAG(list_tests)) ||
7337 ParseStringFlag(arg, kOutputFlag, &
GTEST_FLAG(output)) ||
7338 ParseBoolFlag(arg, kPrintTimeFlag, &
GTEST_FLAG(print_time)) ||
7339 ParseBoolFlag(arg, kPrintUTF8Flag, &
GTEST_FLAG(print_utf8)) ||
7340 ParseInt32Flag(arg, kRandomSeedFlag, &
GTEST_FLAG(random_seed)) ||
7342 ParseBoolFlag(arg, kShuffleFlag, &
GTEST_FLAG(shuffle)) ||
7343 ParseInt32Flag(arg, kStackTraceDepthFlag,
7345 ParseStringFlag(arg, kStreamResultToFlag,
7347 ParseBoolFlag(arg, kThrowOnFailureFlag,
7351 #if GTEST_USE_OWN_FLAGFILE_FLAG_ 7352 static void LoadFlagsFromFile(
const std::string& path) {
7360 std::vector<std::string> lines;
7361 SplitString(contents,
'\n', &lines);
7362 for (
size_t i = 0; i < lines.size(); ++i) {
7363 if (lines[i].
empty())
7365 if (!ParseGoogleTestFlag(lines[i].c_str()))
7369 #endif // GTEST_USE_OWN_FLAGFILE_FLAG_ 7374 template <
typename CharType>
7375 void ParseGoogleTestFlagsOnlyImpl(
int* argc, CharType** argv) {
7376 for (
int i = 1; i < *argc; i++) {
7378 const char*
const arg = arg_string.c_str();
7380 using internal::ParseBoolFlag;
7381 using internal::ParseInt32Flag;
7382 using internal::ParseStringFlag;
7384 bool remove_flag =
false;
7385 if (ParseGoogleTestFlag(arg)) {
7387 #if GTEST_USE_OWN_FLAGFILE_FLAG_ 7388 }
else if (ParseStringFlag(arg, kFlagfileFlag, &
GTEST_FLAG(flagfile))) {
7391 #endif // GTEST_USE_OWN_FLAGFILE_FLAG_ 7392 }
else if (arg_string ==
"--help" || arg_string ==
"-h" ||
7393 arg_string ==
"-?" || arg_string ==
"/?" ||
7394 HasGoogleTestFlagPrefix(arg)) {
7405 for (
int j = i; j != *argc; j++) {
7406 argv[j] = argv[j + 1];
7422 PrintColorEncoded(kColorEncodedHelpMessage);
7428 void ParseGoogleTestFlagsOnly(
int* argc,
char** argv) {
7429 ParseGoogleTestFlagsOnlyImpl(argc, argv);
7435 #ifndef GTEST_OS_IOS 7436 if (*_NSGetArgv() == argv) {
7437 *_NSGetArgc() = *argc;
7442 void ParseGoogleTestFlagsOnly(
int* argc,
wchar_t** argv) {
7443 ParseGoogleTestFlagsOnlyImpl(argc, argv);
7450 template <
typename CharType>
7451 void InitGoogleTestImpl(
int* argc, CharType** argv) {
7453 if (GTestIsInitialized())
return;
7455 if (*argc <= 0)
return;
7458 for (
int i = 0; i != *argc; i++) {
7463 absl::InitializeSymbolizer(g_argvs[0].c_str());
7464 #endif // GTEST_HAS_ABSL 7466 ParseGoogleTestFlagsOnly(argc, argv);
7467 GetUnitTestImpl()->PostFlagParsingInit();
7482 #if defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_) 7483 GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_(argc, argv);
7484 #else // defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_) 7485 internal::InitGoogleTestImpl(argc, argv);
7486 #endif // defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_) 7492 #if defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_) 7493 GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_(argc, argv);
7494 #else // defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_) 7495 internal::InitGoogleTestImpl(argc, argv);
7496 #endif // defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_) 7500 #if defined(GTEST_CUSTOM_TEMPDIR_FUNCTION_) 7501 return GTEST_CUSTOM_TEMPDIR_FUNCTION_();
7504 #if GTEST_OS_WINDOWS_MOBILE 7506 #elif GTEST_OS_WINDOWS 7508 if (temp_dir ==
nullptr || temp_dir[0] ==
'\0')
7510 else if (temp_dir[strlen(temp_dir) - 1] ==
'\\')
7514 #elif GTEST_OS_LINUX_ANDROID 7518 #endif // GTEST_OS_WINDOWS_MOBILE 7525 void ScopedTrace::PushTrace(
const char* file,
int line,
std::string message) {
7526 internal::TraceInfo trace;
7529 trace.message.swap(message);
7531 UnitTest::GetInstance()->PushGTestTrace(trace);
7535 ScopedTrace::~ScopedTrace()
7537 UnitTest::GetInstance()->PopGTestTrace();
7577 #if GTEST_HAS_DEATH_TEST 7580 # include <crt_externs.h> 7581 # endif // GTEST_OS_MAC 7585 # include <limits.h> 7588 # include <signal.h> 7589 # endif // GTEST_OS_LINUX 7591 # include <stdarg.h> 7593 # if GTEST_OS_WINDOWS 7594 # include <windows.h> 7596 # include <sys/mman.h> 7597 # include <sys/wait.h> 7598 # endif // GTEST_OS_WINDOWS 7602 # endif // GTEST_OS_QNX 7604 # if GTEST_OS_FUCHSIA 7605 # include <lib/fdio/io.h> 7606 # include <lib/fdio/spawn.h> 7607 # include <lib/fdio/util.h> 7608 # include <lib/zx/socket.h> 7609 # include <lib/zx/port.h> 7610 # include <lib/zx/process.h> 7611 # include <zircon/processargs.h> 7612 # include <zircon/syscalls.h> 7613 # include <zircon/syscalls/policy.h> 7614 # include <zircon/syscalls/port.h> 7615 # endif // GTEST_OS_FUCHSIA 7617 #endif // GTEST_HAS_DEATH_TEST 7634 "Indicates how to run a death test in a forked child process: " 7635 "\"threadsafe\" (child process re-executes the test binary " 7636 "from the beginning, running only the specific death test) or " 7637 "\"fast\" (child process runs the death test immediately " 7641 death_test_use_fork,
7643 "Instructs to use fork()/_exit() instead of clone() in death tests. " 7644 "Ignored and always uses fork() on POSIX systems where clone() is not " 7645 "implemented. Useful when running under valgrind or similar tools if " 7646 "those do not support clone(). Valgrind 3.3.1 will just fail if " 7647 "it sees an unsupported combination of clone() flags. " 7648 "It is not recommended to use this flag w/o valgrind though it will " 7649 "work in 99% of the cases. Once valgrind is fixed, this flag will " 7650 "most likely be removed.");
7652 namespace internal {
7654 internal_run_death_test,
"",
7655 "Indicates the file, line number, temporal index of " 7656 "the single death test to run, and a file descriptor to " 7657 "which a success code may be sent, all separated by " 7658 "the '|' characters. This flag is specified if and only if the current " 7659 "process is a sub-process launched for running a thread-safe " 7660 "death test. FOR INTERNAL USE ONLY.");
7663 #if GTEST_HAS_DEATH_TEST 7665 namespace internal {
7669 # if !GTEST_OS_WINDOWS && !GTEST_OS_FUCHSIA 7670 static bool g_in_fast_death_test_child =
false;
7678 bool InDeathTestChild() {
7679 # if GTEST_OS_WINDOWS || GTEST_OS_FUCHSIA 7683 return !
GTEST_FLAG(internal_run_death_test).empty();
7687 if (
GTEST_FLAG(death_test_style) ==
"threadsafe")
7688 return !
GTEST_FLAG(internal_run_death_test).empty();
7690 return g_in_fast_death_test_child;
7697 ExitedWithCode::ExitedWithCode(
int exit_code) : exit_code_(exit_code) {
7701 bool ExitedWithCode::operator()(
int exit_status)
const {
7702 # if GTEST_OS_WINDOWS || GTEST_OS_FUCHSIA 7704 return exit_status == exit_code_;
7708 return WIFEXITED(exit_status) && WEXITSTATUS(exit_status) == exit_code_;
7710 # endif // GTEST_OS_WINDOWS || GTEST_OS_FUCHSIA 7713 # if !GTEST_OS_WINDOWS && !GTEST_OS_FUCHSIA 7715 KilledBySignal::KilledBySignal(
int signum) : signum_(signum) {
7719 bool KilledBySignal::operator()(
int exit_status)
const {
7720 # if defined(GTEST_KILLED_BY_SIGNAL_OVERRIDE_) 7723 if (GTEST_KILLED_BY_SIGNAL_OVERRIDE_(signum_, exit_status, &result)) {
7727 # endif // defined(GTEST_KILLED_BY_SIGNAL_OVERRIDE_) 7728 return WIFSIGNALED(exit_status) && WTERMSIG(exit_status) == signum_;
7730 # endif // !GTEST_OS_WINDOWS && !GTEST_OS_FUCHSIA 7732 namespace internal {
7741 # if GTEST_OS_WINDOWS || GTEST_OS_FUCHSIA 7743 m <<
"Exited with exit status " << exit_code;
7747 if (WIFEXITED(exit_code)) {
7748 m <<
"Exited with exit status " << WEXITSTATUS(exit_code);
7749 }
else if (WIFSIGNALED(exit_code)) {
7750 m <<
"Terminated by signal " << WTERMSIG(exit_code);
7753 if (WCOREDUMP(exit_code)) {
7754 m <<
" (core dumped)";
7757 # endif // GTEST_OS_WINDOWS || GTEST_OS_FUCHSIA 7759 return m.GetString();
7764 bool ExitedUnsuccessfully(
int exit_status) {
7765 return !ExitedWithCode(0)(exit_status);
7768 # if !GTEST_OS_WINDOWS && !GTEST_OS_FUCHSIA 7773 static std::string DeathTestThreadWarning(
size_t thread_count) {
7775 msg <<
"Death tests use fork(), which is unsafe particularly" 7776 <<
" in a threaded context. For this test, " <<
GTEST_NAME_ <<
" ";
7777 if (thread_count == 0) {
7778 msg <<
"couldn't detect the number of threads.";
7780 msg <<
"detected " << thread_count <<
" threads.";
7783 "https://github.com/google/googletest/blob/master/googletest/docs/" 7784 "advanced.md#death-tests-and-threads" 7785 <<
" for more explanation and suggested solutions, especially if" 7786 <<
" this is the last message you see before your test times out.";
7787 return msg.GetString();
7789 # endif // !GTEST_OS_WINDOWS && !GTEST_OS_FUCHSIA 7792 static const char kDeathTestLived =
'L';
7793 static const char kDeathTestReturned =
'R';
7794 static const char kDeathTestThrew =
'T';
7795 static const char kDeathTestInternalError =
'I';
7797 #if GTEST_OS_FUCHSIA 7800 static const int kFuchsiaReadPipeFd = 3;
7811 enum DeathTestOutcome { IN_PROGRESS, DIED, LIVED, RETURNED, THREW };
7818 static void DeathTestAbort(
const std::string& message) {
7822 const InternalRunDeathTestFlag*
const flag =
7823 GetUnitTestImpl()->internal_run_death_test_flag();
7824 if (flag !=
nullptr) {
7826 fputc(kDeathTestInternalError, parent);
7827 fprintf(parent,
"%s", message.c_str());
7831 fprintf(stderr,
"%s", message.c_str());
7839 # define GTEST_DEATH_TEST_CHECK_(expression) \ 7841 if (!::testing::internal::IsTrue(expression)) { \ 7843 ::std::string("CHECK failed: File ") + __FILE__ + ", line " \ 7844 + ::testing::internal::StreamableToString(__LINE__) + ": " \ 7847 } while (::testing::internal::AlwaysFalse()) 7856 # define GTEST_DEATH_TEST_CHECK_SYSCALL_(expression) \ 7860 gtest_retval = (expression); \ 7861 } while (gtest_retval == -1 && errno == EINTR); \ 7862 if (gtest_retval == -1) { \ 7864 ::std::string("CHECK failed: File ") + __FILE__ + ", line " \ 7865 + ::testing::internal::StreamableToString(__LINE__) + ": " \ 7866 + #expression + " != -1"); \ 7868 } while (::testing::internal::AlwaysFalse()) 7879 static void FailFromInternalError(
int fd) {
7885 while ((num_read =
posix::Read(fd, buffer, 255)) > 0) {
7886 buffer[num_read] =
'\0';
7889 }
while (num_read == -1 && errno == EINTR);
7891 if (num_read == 0) {
7894 const int last_error = errno;
7895 GTEST_LOG_(FATAL) <<
"Error while reading death test internal: " 7896 << GetLastErrnoDescription() <<
" [" << last_error <<
"]";
7902 DeathTest::DeathTest() {
7903 TestInfo*
const info = GetUnitTestImpl()->current_test_info();
7904 if (info ==
nullptr) {
7905 DeathTestAbort(
"Cannot run a death test outside of a TEST or " 7906 "TEST_F construct");
7912 bool DeathTest::Create(
const char* statement,
7913 Matcher<const std::string&> matcher,
const char* file,
7914 int line, DeathTest** test) {
7915 return GetUnitTestImpl()->death_test_factory()->Create(
7916 statement, std::move(matcher), file, line, test);
7919 const char* DeathTest::LastMessage() {
7920 return last_death_test_message_.c_str();
7923 void DeathTest::set_last_death_test_message(
const std::string& message) {
7924 last_death_test_message_ = message;
7930 class DeathTestImpl :
public DeathTest {
7932 DeathTestImpl(
const char* a_statement, Matcher<const std::string&> matcher)
7933 : statement_(a_statement),
7934 matcher_(std::move(matcher)),
7937 outcome_(IN_PROGRESS),
7942 ~DeathTestImpl()
override { GTEST_DEATH_TEST_CHECK_(read_fd_ == -1); }
7944 void Abort(AbortReason reason)
override;
7945 bool Passed(
bool status_ok)
override;
7947 const char* statement()
const {
return statement_; }
7948 bool spawned()
const {
return spawned_; }
7949 void set_spawned(
bool is_spawned) { spawned_ = is_spawned; }
7950 int status()
const {
return status_; }
7951 void set_status(
int a_status) { status_ = a_status; }
7952 DeathTestOutcome outcome()
const {
return outcome_; }
7953 void set_outcome(DeathTestOutcome an_outcome) { outcome_ = an_outcome; }
7954 int read_fd()
const {
return read_fd_; }
7955 void set_read_fd(
int fd) { read_fd_ = fd; }
7956 int write_fd()
const {
return write_fd_; }
7957 void set_write_fd(
int fd) { write_fd_ = fd; }
7963 void ReadAndInterpretStatusByte();
7971 const char*
const statement_;
7973 Matcher<const std::string&> matcher_;
7979 DeathTestOutcome outcome_;
7994 void DeathTestImpl::ReadAndInterpretStatusByte() {
8004 }
while (bytes_read == -1 && errno == EINTR);
8006 if (bytes_read == 0) {
8008 }
else if (bytes_read == 1) {
8010 case kDeathTestReturned:
8011 set_outcome(RETURNED);
8013 case kDeathTestThrew:
8016 case kDeathTestLived:
8019 case kDeathTestInternalError:
8020 FailFromInternalError(read_fd());
8023 GTEST_LOG_(FATAL) <<
"Death test child process reported " 8024 <<
"unexpected status byte (" 8025 <<
static_cast<unsigned int>(flag) <<
")";
8028 GTEST_LOG_(FATAL) <<
"Read from death test child process failed: " 8029 << GetLastErrnoDescription();
8031 GTEST_DEATH_TEST_CHECK_SYSCALL_(
posix::Close(read_fd()));
8047 const char status_ch =
8048 reason == TEST_DID_NOT_DIE ? kDeathTestLived :
8049 reason == TEST_THREW_EXCEPTION ? kDeathTestThrew : kDeathTestReturned;
8051 GTEST_DEATH_TEST_CHECK_SYSCALL_(
posix::Write(write_fd(), &status_ch, 1));
8068 for (
size_t at = 0; ; ) {
8069 const size_t line_end = output.find(
'\n',
at);
8070 ret +=
"[ DEATH ] ";
8071 if (line_end == ::std::string::npos) {
8072 ret += output.substr(
at);
8075 ret += output.substr(
at, line_end + 1 -
at);
8102 bool DeathTestImpl::Passed(
bool status_ok) {
8108 bool success =
false;
8111 buffer <<
"Death test: " << statement() <<
"\n";
8112 switch (outcome()) {
8114 buffer <<
" Result: failed to die.\n" 8115 <<
" Error msg:\n" << FormatDeathTestOutput(error_message);
8118 buffer <<
" Result: threw an exception.\n" 8119 <<
" Error msg:\n" << FormatDeathTestOutput(error_message);
8122 buffer <<
" Result: illegal return in test statement.\n" 8123 <<
" Error msg:\n" << FormatDeathTestOutput(error_message);
8127 if (matcher_.Matches(error_message)) {
8130 std::ostringstream stream;
8131 matcher_.DescribeTo(&stream);
8132 buffer <<
" Result: died but not with expected error.\n" 8133 <<
" Expected: " << stream.str() <<
"\n" 8135 << FormatDeathTestOutput(error_message);
8138 buffer <<
" Result: died but not with expected exit code:\n" 8139 <<
" " << ExitSummary(status()) <<
"\n" 8140 <<
"Actual msg:\n" << FormatDeathTestOutput(error_message);
8146 <<
"DeathTest::Passed somehow called before conclusion of test";
8149 DeathTest::set_last_death_test_message(buffer.GetString());
8153 # if GTEST_OS_WINDOWS 8182 class WindowsDeathTest :
public DeathTestImpl {
8184 WindowsDeathTest(
const char* a_statement, Matcher<const std::string&> matcher,
8185 const char* file,
int line)
8186 : DeathTestImpl(a_statement, std::move(matcher)),
8192 virtual TestRole AssumeRole();
8196 const char*
const file_;
8200 AutoHandle write_handle_;
8202 AutoHandle child_handle_;
8207 AutoHandle event_handle_;
8213 int WindowsDeathTest::Wait() {
8219 const HANDLE wait_handles[2] = { child_handle_.Get(), event_handle_.Get() };
8220 switch (::WaitForMultipleObjects(2,
8225 case WAIT_OBJECT_0 + 1:
8228 GTEST_DEATH_TEST_CHECK_(
false);
8233 write_handle_.Reset();
8234 event_handle_.Reset();
8236 ReadAndInterpretStatusByte();
8242 GTEST_DEATH_TEST_CHECK_(
8243 WAIT_OBJECT_0 == ::WaitForSingleObject(child_handle_.Get(),
8246 GTEST_DEATH_TEST_CHECK_(
8247 ::GetExitCodeProcess(child_handle_.Get(), &status_code) != FALSE);
8248 child_handle_.Reset();
8249 set_status(static_cast<int>(status_code));
8258 DeathTest::TestRole WindowsDeathTest::AssumeRole() {
8259 const UnitTestImpl*
const impl = GetUnitTestImpl();
8260 const InternalRunDeathTestFlag*
const flag =
8261 impl->internal_run_death_test_flag();
8262 const TestInfo*
const info = impl->current_test_info();
8263 const int death_test_index = info->result()->death_test_count();
8265 if (flag !=
nullptr) {
8268 set_write_fd(flag->write_fd());
8269 return EXECUTE_TEST;
8274 SECURITY_ATTRIBUTES handles_are_inheritable = {
sizeof(SECURITY_ATTRIBUTES),
8276 HANDLE read_handle, write_handle;
8277 GTEST_DEATH_TEST_CHECK_(
8278 ::CreatePipe(&read_handle, &write_handle, &handles_are_inheritable,
8281 set_read_fd(::_open_osfhandle(reinterpret_cast<intptr_t>(read_handle),
8283 write_handle_.Reset(write_handle);
8284 event_handle_.Reset(::CreateEvent(
8285 &handles_are_inheritable,
8289 GTEST_DEATH_TEST_CHECK_(event_handle_.Get() !=
nullptr);
8291 kFilterFlag +
"=" + info->test_suite_name() +
8304 char executable_path[_MAX_PATH + 1];
8305 GTEST_DEATH_TEST_CHECK_(_MAX_PATH + 1 != ::GetModuleFileNameA(
nullptr,
8310 std::string(::GetCommandLineA()) +
" " + filter_flag +
" \"" +
8311 internal_flag +
"\"";
8313 DeathTest::set_last_death_test_message(
"");
8320 STARTUPINFOA startup_info;
8321 memset(&startup_info, 0,
sizeof(STARTUPINFO));
8322 startup_info.dwFlags = STARTF_USESTDHANDLES;
8323 startup_info.hStdInput = ::GetStdHandle(STD_INPUT_HANDLE);
8324 startup_info.hStdOutput = ::GetStdHandle(STD_OUTPUT_HANDLE);
8325 startup_info.hStdError = ::GetStdHandle(STD_ERROR_HANDLE);
8327 PROCESS_INFORMATION process_info;
8328 GTEST_DEATH_TEST_CHECK_(
8330 executable_path, const_cast<char*>(command_line.c_str()),
8337 &process_info) != FALSE);
8338 child_handle_.Reset(process_info.hProcess);
8339 ::CloseHandle(process_info.hThread);
8341 return OVERSEE_TEST;
8344 # elif GTEST_OS_FUCHSIA 8346 class FuchsiaDeathTest :
public DeathTestImpl {
8348 FuchsiaDeathTest(
const char* a_statement, Matcher<const std::string&> matcher,
8349 const char* file,
int line)
8350 : DeathTestImpl(a_statement, std::move(matcher)),
8355 int Wait()
override;
8356 TestRole AssumeRole()
override;
8361 const char*
const file_;
8367 zx::process child_process_;
8369 zx::socket stderr_socket_;
8375 Arguments() { args_.push_back(
nullptr); }
8378 for (std::vector<char*>::iterator i = args_.begin(); i != args_.end();
8383 void AddArgument(
const char* argument) {
8387 template <
typename Str>
8388 void AddArguments(const ::std::vector<Str>& arguments) {
8389 for (typename ::std::vector<Str>::const_iterator i = arguments.begin();
8390 i != arguments.end();
8395 char*
const* Argv() {
8400 return args_.size() - 1;
8404 std::vector<char*> args_;
8410 int FuchsiaDeathTest::Wait() {
8411 const int kProcessKey = 0;
8412 const int kSocketKey = 1;
8418 zx_status_t status_zx;
8419 status_zx = child_process_.wait_async(
8420 port_, kProcessKey, ZX_PROCESS_TERMINATED, ZX_WAIT_ASYNC_ONCE);
8421 GTEST_DEATH_TEST_CHECK_(status_zx == ZX_OK);
8423 status_zx = stderr_socket_.wait_async(
8424 port_, kSocketKey, ZX_SOCKET_READABLE | ZX_SOCKET_PEER_CLOSED,
8425 ZX_WAIT_ASYNC_REPEATING);
8426 GTEST_DEATH_TEST_CHECK_(status_zx == ZX_OK);
8428 bool process_terminated =
false;
8429 bool socket_closed =
false;
8431 zx_port_packet_t packet = {};
8432 status_zx = port_.wait(zx::time::infinite(), &packet);
8433 GTEST_DEATH_TEST_CHECK_(status_zx == ZX_OK);
8435 if (packet.key == kProcessKey) {
8436 if (ZX_PKT_IS_EXCEPTION(packet.type)) {
8440 status_zx = child_process_.kill();
8441 GTEST_DEATH_TEST_CHECK_(status_zx == ZX_OK);
8444 GTEST_DEATH_TEST_CHECK_(ZX_PKT_IS_SIGNAL_ONE(packet.type));
8445 GTEST_DEATH_TEST_CHECK_(packet.signal.observed & ZX_PROCESS_TERMINATED);
8446 process_terminated =
true;
8448 }
else if (packet.key == kSocketKey) {
8449 GTEST_DEATH_TEST_CHECK_(ZX_PKT_IS_SIGNAL_REP(packet.type));
8450 if (packet.signal.observed & ZX_SOCKET_READABLE) {
8452 constexpr
size_t kBufferSize = 1024;
8454 size_t old_length = captured_stderr_.length();
8455 size_t bytes_read = 0;
8456 captured_stderr_.resize(old_length + kBufferSize);
8457 status_zx = stderr_socket_.read(
8458 0, &captured_stderr_.front() + old_length, kBufferSize,
8460 captured_stderr_.resize(old_length + bytes_read);
8461 }
while (status_zx == ZX_OK);
8462 if (status_zx == ZX_ERR_PEER_CLOSED) {
8463 socket_closed =
true;
8465 GTEST_DEATH_TEST_CHECK_(status_zx == ZX_ERR_SHOULD_WAIT);
8468 GTEST_DEATH_TEST_CHECK_(packet.signal.observed & ZX_SOCKET_PEER_CLOSED);
8469 socket_closed =
true;
8472 }
while (!process_terminated && !socket_closed);
8474 ReadAndInterpretStatusByte();
8476 zx_info_process_t buffer;
8477 status_zx = child_process_.get_info(
8478 ZX_INFO_PROCESS, &buffer,
sizeof(buffer),
nullptr,
nullptr);
8479 GTEST_DEATH_TEST_CHECK_(status_zx == ZX_OK);
8481 GTEST_DEATH_TEST_CHECK_(buffer.exited);
8482 set_status(buffer.return_code);
8491 DeathTest::TestRole FuchsiaDeathTest::AssumeRole() {
8492 const UnitTestImpl*
const impl = GetUnitTestImpl();
8493 const InternalRunDeathTestFlag*
const flag =
8494 impl->internal_run_death_test_flag();
8495 const TestInfo*
const info = impl->current_test_info();
8496 const int death_test_index = info->result()->death_test_count();
8498 if (flag !=
nullptr) {
8501 set_write_fd(kFuchsiaReadPipeFd);
8502 return EXECUTE_TEST;
8510 kFilterFlag +
"=" + info->test_suite_name() +
8518 args.AddArguments(GetInjectableArgvs());
8519 args.AddArgument(filter_flag.c_str());
8520 args.AddArgument(internal_flag.c_str());
8524 zx_handle_t child_pipe_handle;
8526 status = fdio_pipe_half(&child_pipe_handle, &type);
8527 GTEST_DEATH_TEST_CHECK_(status >= 0);
8528 set_read_fd(status);
8531 fdio_spawn_action_t spawn_actions[2] = {};
8532 fdio_spawn_action_t* add_handle_action = &spawn_actions[0];
8533 add_handle_action->action = FDIO_SPAWN_ACTION_ADD_HANDLE;
8534 add_handle_action->h.id = PA_HND(type, kFuchsiaReadPipeFd);
8535 add_handle_action->h.handle = child_pipe_handle;
8538 zx::socket stderr_producer_socket;
8540 zx::socket::create(0, &stderr_producer_socket, &stderr_socket_);
8541 GTEST_DEATH_TEST_CHECK_(status >= 0);
8542 int stderr_producer_fd = -1;
8543 zx_handle_t producer_handle[1] = { stderr_producer_socket.release() };
8544 uint32_t producer_handle_type[1] = { PA_FDIO_SOCKET };
8545 status = fdio_create_fd(
8546 producer_handle, producer_handle_type, 1, &stderr_producer_fd);
8547 GTEST_DEATH_TEST_CHECK_(status >= 0);
8550 GTEST_DEATH_TEST_CHECK_(fcntl(stderr_producer_fd, F_SETFL, 0) == 0);
8552 fdio_spawn_action_t* add_stderr_action = &spawn_actions[1];
8553 add_stderr_action->action = FDIO_SPAWN_ACTION_CLONE_FD;
8554 add_stderr_action->fd.local_fd = stderr_producer_fd;
8555 add_stderr_action->fd.target_fd = STDERR_FILENO;
8558 zx_handle_t child_job = ZX_HANDLE_INVALID;
8559 status = zx_job_create(zx_job_default(), 0, & child_job);
8560 GTEST_DEATH_TEST_CHECK_(status == ZX_OK);
8561 zx_policy_basic_t policy;
8562 policy.condition = ZX_POL_NEW_ANY;
8563 policy.policy = ZX_POL_ACTION_ALLOW;
8564 status = zx_job_set_policy(
8565 child_job, ZX_JOB_POL_RELATIVE, ZX_JOB_POL_BASIC, &policy, 1);
8566 GTEST_DEATH_TEST_CHECK_(status == ZX_OK);
8570 status = zx::port::create(0, &port_);
8571 GTEST_DEATH_TEST_CHECK_(status == ZX_OK);
8572 status = zx_task_bind_exception_port(
8573 child_job, port_.get(), 0 , 0 );
8574 GTEST_DEATH_TEST_CHECK_(status == ZX_OK);
8577 status = fdio_spawn_etc(
8578 child_job, FDIO_SPAWN_CLONE_ALL, args.Argv()[0], args.Argv(),
nullptr,
8579 2, spawn_actions, child_process_.reset_and_get_address(),
nullptr);
8580 GTEST_DEATH_TEST_CHECK_(status == ZX_OK);
8583 return OVERSEE_TEST;
8587 return captured_stderr_;
8590 #else // We are neither on Windows, nor on Fuchsia. 8595 class ForkingDeathTest :
public DeathTestImpl {
8597 ForkingDeathTest(
const char* statement, Matcher<const std::string&> matcher);
8600 int Wait()
override;
8603 void set_child_pid(pid_t child_pid) { child_pid_ = child_pid; }
8611 ForkingDeathTest::ForkingDeathTest(
const char* a_statement,
8612 Matcher<const std::string&> matcher)
8613 : DeathTestImpl(a_statement, std::move(matcher)), child_pid_(-1) {}
8618 int ForkingDeathTest::Wait() {
8622 ReadAndInterpretStatusByte();
8625 GTEST_DEATH_TEST_CHECK_SYSCALL_(waitpid(child_pid_, &status_value, 0));
8626 set_status(status_value);
8627 return status_value;
8632 class NoExecDeathTest :
public ForkingDeathTest {
8634 NoExecDeathTest(
const char* a_statement, Matcher<const std::string&> matcher)
8635 : ForkingDeathTest(a_statement, std::move(matcher)) {}
8636 TestRole AssumeRole()
override;
8641 DeathTest::TestRole NoExecDeathTest::AssumeRole() {
8643 if (thread_count != 1) {
8644 GTEST_LOG_(WARNING) << DeathTestThreadWarning(thread_count);
8648 GTEST_DEATH_TEST_CHECK_(pipe(pipe_fd) != -1);
8650 DeathTest::set_last_death_test_message(
"");
8661 const pid_t child_pid = fork();
8662 GTEST_DEATH_TEST_CHECK_(child_pid != -1);
8663 set_child_pid(child_pid);
8664 if (child_pid == 0) {
8665 GTEST_DEATH_TEST_CHECK_SYSCALL_(close(pipe_fd[0]));
8666 set_write_fd(pipe_fd[1]);
8673 GetUnitTestImpl()->listeners()->SuppressEventForwarding();
8674 g_in_fast_death_test_child =
true;
8675 return EXECUTE_TEST;
8677 GTEST_DEATH_TEST_CHECK_SYSCALL_(close(pipe_fd[1]));
8678 set_read_fd(pipe_fd[0]);
8680 return OVERSEE_TEST;
8687 class ExecDeathTest :
public ForkingDeathTest {
8689 ExecDeathTest(
const char* a_statement, Matcher<const std::string&> matcher,
8690 const char* file,
int line)
8691 : ForkingDeathTest(a_statement, std::move(matcher)),
8694 TestRole AssumeRole()
override;
8697 static ::std::vector<std::string> GetArgvsForDeathTestChildProcess() {
8698 ::std::vector<std::string> args = GetInjectableArgvs();
8699 # if defined(GTEST_EXTRA_DEATH_TEST_COMMAND_LINE_ARGS_) 8700 ::std::vector<std::string> extra_args =
8701 GTEST_EXTRA_DEATH_TEST_COMMAND_LINE_ARGS_();
8702 args.insert(args.end(), extra_args.begin(), extra_args.end());
8703 # endif // defined(GTEST_EXTRA_DEATH_TEST_COMMAND_LINE_ARGS_) 8707 const char*
const file_;
8715 Arguments() { args_.push_back(
nullptr); }
8718 for (std::vector<char*>::iterator i = args_.begin(); i != args_.end();
8723 void AddArgument(
const char* argument) {
8727 template <
typename Str>
8728 void AddArguments(const ::std::vector<Str>& arguments) {
8729 for (typename ::std::vector<Str>::const_iterator i = arguments.begin();
8730 i != arguments.end();
8735 char*
const* Argv() {
8740 std::vector<char*> args_;
8745 struct ExecDeathTestArgs {
8751 inline char** GetEnviron() {
8755 return *_NSGetEnviron();
8760 extern "C" char** environ;
8761 inline char** GetEnviron() {
return environ; }
8762 # endif // GTEST_OS_MAC 8768 static int ExecDeathTestChildMain(
void* child_arg) {
8769 ExecDeathTestArgs*
const args =
static_cast<ExecDeathTestArgs*
>(child_arg);
8770 GTEST_DEATH_TEST_CHECK_SYSCALL_(close(args->close_fd));
8775 const char*
const original_dir =
8778 if (chdir(original_dir) != 0) {
8779 DeathTestAbort(
std::string(
"chdir(\"") + original_dir +
"\") failed: " +
8780 GetLastErrnoDescription());
8781 return EXIT_FAILURE;
8789 execve(args->argv[0], args->argv, GetEnviron());
8790 DeathTestAbort(
std::string(
"execve(") + args->argv[0] +
", ...) in " +
8791 original_dir +
" failed: " +
8792 GetLastErrnoDescription());
8793 return EXIT_FAILURE;
8795 # endif // !GTEST_OS_QNX 8797 # if GTEST_HAS_CLONE 8807 static void StackLowerThanAddress(
const void* ptr,
8809 static void StackLowerThanAddress(
const void* ptr,
bool* result) {
8811 *result = (&dummy < ptr);
8816 static bool StackGrowsDown() {
8819 StackLowerThanAddress(&dummy, &result);
8822 # endif // GTEST_HAS_CLONE 8831 static pid_t ExecDeathTestSpawnChild(
char*
const* argv,
int close_fd) {
8832 ExecDeathTestArgs args = { argv, close_fd };
8833 pid_t child_pid = -1;
8838 const int cwd_fd = open(
".", O_RDONLY);
8839 GTEST_DEATH_TEST_CHECK_(cwd_fd != -1);
8840 GTEST_DEATH_TEST_CHECK_SYSCALL_(fcntl(cwd_fd, F_SETFD, FD_CLOEXEC));
8844 const char*
const original_dir =
8847 if (chdir(original_dir) != 0) {
8848 DeathTestAbort(
std::string(
"chdir(\"") + original_dir +
"\") failed: " +
8849 GetLastErrnoDescription());
8850 return EXIT_FAILURE;
8855 GTEST_DEATH_TEST_CHECK_SYSCALL_(fd_flags = fcntl(close_fd, F_GETFD));
8856 GTEST_DEATH_TEST_CHECK_SYSCALL_(fcntl(close_fd, F_SETFD,
8857 fd_flags | FD_CLOEXEC));
8858 struct inheritance inherit = {0};
8861 spawn(args.argv[0], 0,
nullptr, &inherit, args.argv, GetEnviron());
8863 GTEST_DEATH_TEST_CHECK_(fchdir(cwd_fd) != -1);
8864 GTEST_DEATH_TEST_CHECK_SYSCALL_(close(cwd_fd));
8866 # else // GTEST_OS_QNX 8871 struct sigaction saved_sigprof_action;
8872 struct sigaction ignore_sigprof_action;
8873 memset(&ignore_sigprof_action, 0,
sizeof(ignore_sigprof_action));
8874 sigemptyset(&ignore_sigprof_action.sa_mask);
8875 ignore_sigprof_action.sa_handler = SIG_IGN;
8876 GTEST_DEATH_TEST_CHECK_SYSCALL_(sigaction(
8877 SIGPROF, &ignore_sigprof_action, &saved_sigprof_action));
8878 # endif // GTEST_OS_LINUX 8880 # if GTEST_HAS_CLONE 8881 const bool use_fork =
GTEST_FLAG(death_test_use_fork);
8884 static const bool stack_grows_down = StackGrowsDown();
8885 const size_t stack_size = getpagesize();
8887 void*
const stack = mmap(
nullptr, stack_size, PROT_READ | PROT_WRITE,
8888 MAP_ANON | MAP_PRIVATE, -1, 0);
8889 GTEST_DEATH_TEST_CHECK_(stack != MAP_FAILED);
8897 const size_t kMaxStackAlignment = 64;
8898 void*
const stack_top =
8899 static_cast<char*
>(stack) +
8900 (stack_grows_down ? stack_size - kMaxStackAlignment : 0);
8901 GTEST_DEATH_TEST_CHECK_(stack_size > kMaxStackAlignment &&
8902 reinterpret_cast<intptr_t>(stack_top) % kMaxStackAlignment == 0);
8904 child_pid = clone(&ExecDeathTestChildMain, stack_top, SIGCHLD, &args);
8906 GTEST_DEATH_TEST_CHECK_(munmap(stack, stack_size) != -1);
8909 const bool use_fork =
true;
8910 # endif // GTEST_HAS_CLONE 8912 if (use_fork && (child_pid = fork()) == 0) {
8913 ExecDeathTestChildMain(&args);
8916 # endif // GTEST_OS_QNX 8918 GTEST_DEATH_TEST_CHECK_SYSCALL_(
8919 sigaction(SIGPROF, &saved_sigprof_action,
nullptr));
8920 # endif // GTEST_OS_LINUX 8922 GTEST_DEATH_TEST_CHECK_(child_pid != -1);
8930 DeathTest::TestRole ExecDeathTest::AssumeRole() {
8931 const UnitTestImpl*
const impl = GetUnitTestImpl();
8932 const InternalRunDeathTestFlag*
const flag =
8933 impl->internal_run_death_test_flag();
8934 const TestInfo*
const info = impl->current_test_info();
8935 const int death_test_index = info->result()->death_test_count();
8937 if (flag !=
nullptr) {
8938 set_write_fd(flag->write_fd());
8939 return EXECUTE_TEST;
8943 GTEST_DEATH_TEST_CHECK_(pipe(pipe_fd) != -1);
8946 GTEST_DEATH_TEST_CHECK_(fcntl(pipe_fd[1], F_SETFD, 0) != -1);
8949 kFilterFlag +
"=" + info->test_suite_name() +
8957 args.AddArguments(GetArgvsForDeathTestChildProcess());
8958 args.AddArgument(filter_flag.c_str());
8959 args.AddArgument(internal_flag.c_str());
8961 DeathTest::set_last_death_test_message(
"");
8968 const pid_t child_pid = ExecDeathTestSpawnChild(args.Argv(), pipe_fd[0]);
8969 GTEST_DEATH_TEST_CHECK_SYSCALL_(close(pipe_fd[1]));
8970 set_child_pid(child_pid);
8971 set_read_fd(pipe_fd[0]);
8973 return OVERSEE_TEST;
8976 # endif // !GTEST_OS_WINDOWS 8983 bool DefaultDeathTestFactory::Create(
const char* statement,
8984 Matcher<const std::string&> matcher,
8985 const char* file,
int line,
8987 UnitTestImpl*
const impl = GetUnitTestImpl();
8988 const InternalRunDeathTestFlag*
const flag =
8989 impl->internal_run_death_test_flag();
8990 const int death_test_index = impl->current_test_info()
8991 ->increment_death_test_count();
8993 if (flag !=
nullptr) {
8994 if (death_test_index > flag->index()) {
8995 DeathTest::set_last_death_test_message(
8997 +
") somehow exceeded expected maximum (" 9002 if (!(flag->file() == file && flag->line() == line &&
9003 flag->index() == death_test_index)) {
9009 # if GTEST_OS_WINDOWS 9011 if (
GTEST_FLAG(death_test_style) ==
"threadsafe" ||
9013 *test =
new WindowsDeathTest(statement, std::move(matcher), file, line);
9016 # elif GTEST_OS_FUCHSIA 9018 if (
GTEST_FLAG(death_test_style) ==
"threadsafe" ||
9020 *test =
new FuchsiaDeathTest(statement, std::move(matcher), file, line);
9025 if (
GTEST_FLAG(death_test_style) ==
"threadsafe") {
9026 *test =
new ExecDeathTest(statement, std::move(matcher), file, line);
9027 }
else if (
GTEST_FLAG(death_test_style) ==
"fast") {
9028 *test =
new NoExecDeathTest(statement, std::move(matcher));
9031 # endif // GTEST_OS_WINDOWS 9034 DeathTest::set_last_death_test_message(
9035 "Unknown death test style \"" +
GTEST_FLAG(death_test_style)
9036 +
"\" encountered");
9043 # if GTEST_OS_WINDOWS 9047 static int GetStatusFileDescriptor(
unsigned int parent_process_id,
9048 size_t write_handle_as_size_t,
9049 size_t event_handle_as_size_t) {
9050 AutoHandle parent_process_handle(::OpenProcess(PROCESS_DUP_HANDLE,
9052 parent_process_id));
9053 if (parent_process_handle.Get() == INVALID_HANDLE_VALUE) {
9054 DeathTestAbort(
"Unable to open parent process " +
9060 const HANDLE write_handle =
9061 reinterpret_cast<HANDLE
>(write_handle_as_size_t);
9062 HANDLE dup_write_handle;
9067 if (!::DuplicateHandle(parent_process_handle.Get(), write_handle,
9068 ::GetCurrentProcess(), &dup_write_handle,
9072 DUPLICATE_SAME_ACCESS)) {
9073 DeathTestAbort(
"Unable to duplicate the pipe handle " +
9075 " from the parent process " +
9079 const HANDLE event_handle =
reinterpret_cast<HANDLE
>(event_handle_as_size_t);
9080 HANDLE dup_event_handle;
9082 if (!::DuplicateHandle(parent_process_handle.Get(), event_handle,
9083 ::GetCurrentProcess(), &dup_event_handle,
9086 DUPLICATE_SAME_ACCESS)) {
9087 DeathTestAbort(
"Unable to duplicate the event handle " +
9089 " from the parent process " +
9093 const int write_fd =
9094 ::_open_osfhandle(reinterpret_cast<intptr_t>(dup_write_handle), O_APPEND);
9095 if (write_fd == -1) {
9096 DeathTestAbort(
"Unable to convert pipe handle " +
9098 " to a file descriptor");
9103 ::SetEvent(dup_event_handle);
9107 # endif // GTEST_OS_WINDOWS 9112 InternalRunDeathTestFlag* ParseInternalRunDeathTestFlag() {
9113 if (
GTEST_FLAG(internal_run_death_test) ==
"")
return nullptr;
9119 ::std::vector< ::std::string> fields;
9120 SplitString(
GTEST_FLAG(internal_run_death_test).c_str(),
'|', &fields);
9123 # if GTEST_OS_WINDOWS 9125 unsigned int parent_process_id = 0;
9126 size_t write_handle_as_size_t = 0;
9127 size_t event_handle_as_size_t = 0;
9129 if (fields.size() != 6
9130 || !ParseNaturalNumber(fields[1], &line)
9131 || !ParseNaturalNumber(fields[2], &index)
9132 || !ParseNaturalNumber(fields[3], &parent_process_id)
9133 || !ParseNaturalNumber(fields[4], &write_handle_as_size_t)
9134 || !ParseNaturalNumber(fields[5], &event_handle_as_size_t)) {
9135 DeathTestAbort(
"Bad --gtest_internal_run_death_test flag: " +
9138 write_fd = GetStatusFileDescriptor(parent_process_id,
9139 write_handle_as_size_t,
9140 event_handle_as_size_t);
9142 # elif GTEST_OS_FUCHSIA 9144 if (fields.size() != 3
9145 || !ParseNaturalNumber(fields[1], &line)
9146 || !ParseNaturalNumber(fields[2], &index)) {
9147 DeathTestAbort(
"Bad --gtest_internal_run_death_test flag: " 9153 if (fields.size() != 4
9154 || !ParseNaturalNumber(fields[1], &line)
9155 || !ParseNaturalNumber(fields[2], &index)
9156 || !ParseNaturalNumber(fields[3], &write_fd)) {
9157 DeathTestAbort(
"Bad --gtest_internal_run_death_test flag: " 9161 # endif // GTEST_OS_WINDOWS 9163 return new InternalRunDeathTestFlag(fields[0], line, index, write_fd);
9168 #endif // GTEST_HAS_DEATH_TEST 9203 #if GTEST_OS_WINDOWS_MOBILE 9204 # include <windows.h> 9205 #elif GTEST_OS_WINDOWS 9206 # include <direct.h> 9209 # include <limits.h> 9211 #endif // GTEST_OS_WINDOWS_MOBILE 9214 #if GTEST_OS_WINDOWS 9215 # define GTEST_PATH_MAX_ _MAX_PATH 9216 #elif defined(PATH_MAX) 9217 # define GTEST_PATH_MAX_ PATH_MAX 9218 #elif defined(_XOPEN_PATH_MAX) 9219 # define GTEST_PATH_MAX_ _XOPEN_PATH_MAX 9221 # define GTEST_PATH_MAX_ _POSIX_PATH_MAX 9222 #endif // GTEST_OS_WINDOWS 9225 namespace internal {
9227 #if GTEST_OS_WINDOWS 9233 const char kAlternatePathSeparator =
'/';
9234 const char kAlternatePathSeparatorString[] =
"/";
9235 # if GTEST_OS_WINDOWS_MOBILE 9241 const DWORD kInvalidFileAttributes = 0xffffffff;
9244 # endif // GTEST_OS_WINDOWS_MOBILE 9248 #endif // GTEST_OS_WINDOWS 9251 static bool IsPathSeparator(
char c) {
9252 #if GTEST_HAS_ALT_PATH_SEP_ 9260 FilePath FilePath::GetCurrentDir() {
9261 #if GTEST_OS_WINDOWS_MOBILE || GTEST_OS_WINDOWS_PHONE || GTEST_OS_WINDOWS_RT 9265 #elif GTEST_OS_WINDOWS 9267 return FilePath(_getcwd(cwd,
sizeof(cwd)) ==
nullptr ?
"" : cwd);
9270 char* result = getcwd(cwd,
sizeof(cwd));
9276 # endif // GTEST_OS_NACL 9277 return FilePath(result ==
nullptr ?
"" : cwd);
9278 #endif // GTEST_OS_WINDOWS_MOBILE 9285 FilePath FilePath::RemoveExtension(
const char* extension)
const {
9287 if (String::EndsWithCaseInsensitive(pathname_, dot_extension)) {
9288 return FilePath(pathname_.substr(
9289 0, pathname_.length() - dot_extension.length()));
9297 const char* FilePath::FindLastPathSeparator()
const {
9299 #if GTEST_HAS_ALT_PATH_SEP_ 9300 const char*
const last_alt_sep = strrchr(c_str(), kAlternatePathSeparator);
9302 if (last_alt_sep !=
nullptr &&
9303 (last_sep ==
nullptr || last_alt_sep > last_sep)) {
9304 return last_alt_sep;
9316 FilePath FilePath::RemoveDirectoryName()
const {
9317 const char*
const last_sep = FindLastPathSeparator();
9318 return last_sep ? FilePath(last_sep + 1) : *this;
9327 FilePath FilePath::RemoveFileName()
const {
9328 const char*
const last_sep = FindLastPathSeparator();
9331 dir =
std::string(c_str(), last_sep + 1 - c_str());
9335 return FilePath(dir);
9344 FilePath FilePath::MakeFileName(
const FilePath& directory,
9345 const FilePath& base_name,
9347 const char* extension) {
9350 file = base_name.string() +
"." + extension;
9355 return ConcatPaths(directory, FilePath(file));
9360 FilePath FilePath::ConcatPaths(
const FilePath& directory,
9361 const FilePath& relative_path) {
9362 if (directory.IsEmpty())
9363 return relative_path;
9364 const FilePath dir(directory.RemoveTrailingPathSeparator());
9365 return FilePath(dir.string() +
kPathSeparator + relative_path.string());
9370 bool FilePath::FileOrDirectoryExists()
const {
9371 #if GTEST_OS_WINDOWS_MOBILE 9372 LPCWSTR unicode = String::AnsiToUtf16(pathname_.c_str());
9373 const DWORD attributes = GetFileAttributes(unicode);
9375 return attributes != kInvalidFileAttributes;
9378 return posix::Stat(pathname_.c_str(), &file_stat) == 0;
9379 #endif // GTEST_OS_WINDOWS_MOBILE 9384 bool FilePath::DirectoryExists()
const {
9385 bool result =
false;
9386 #if GTEST_OS_WINDOWS 9389 const FilePath& path(IsRootDirectory() ? *
this :
9390 RemoveTrailingPathSeparator());
9392 const FilePath& path(*
this);
9395 #if GTEST_OS_WINDOWS_MOBILE 9396 LPCWSTR unicode = String::AnsiToUtf16(path.c_str());
9397 const DWORD attributes = GetFileAttributes(unicode);
9399 if ((attributes != kInvalidFileAttributes) &&
9400 (attributes & FILE_ATTRIBUTE_DIRECTORY)) {
9405 result =
posix::Stat(path.c_str(), &file_stat) == 0 &&
9407 #endif // GTEST_OS_WINDOWS_MOBILE 9414 bool FilePath::IsRootDirectory()
const {
9415 #if GTEST_OS_WINDOWS 9416 return pathname_.length() == 3 && IsAbsolutePath();
9418 return pathname_.length() == 1 && IsPathSeparator(pathname_.c_str()[0]);
9423 bool FilePath::IsAbsolutePath()
const {
9424 const char*
const name = pathname_.c_str();
9425 #if GTEST_OS_WINDOWS 9426 return pathname_.length() >= 3 &&
9427 ((name[0] >=
'a' && name[0] <=
'z') ||
9428 (name[0] >=
'A' && name[0] <=
'Z')) &&
9430 IsPathSeparator(name[2]);
9432 return IsPathSeparator(name[0]);
9444 FilePath FilePath::GenerateUniqueFileName(
const FilePath& directory,
9445 const FilePath& base_name,
9446 const char* extension) {
9447 FilePath full_pathname;
9450 full_pathname.Set(MakeFileName(directory, base_name, number++, extension));
9451 }
while (full_pathname.FileOrDirectoryExists());
9452 return full_pathname;
9458 bool FilePath::IsDirectory()
const {
9459 return !pathname_.empty() &&
9460 IsPathSeparator(pathname_.c_str()[pathname_.length() - 1]);
9466 bool FilePath::CreateDirectoriesRecursively()
const {
9467 if (!this->IsDirectory()) {
9471 if (pathname_.length() == 0 || this->DirectoryExists()) {
9475 const FilePath parent(this->RemoveTrailingPathSeparator().RemoveFileName());
9476 return parent.CreateDirectoriesRecursively() && this->CreateFolder();
9483 bool FilePath::CreateFolder()
const {
9484 #if GTEST_OS_WINDOWS_MOBILE 9485 FilePath removed_sep(this->RemoveTrailingPathSeparator());
9486 LPCWSTR unicode = String::AnsiToUtf16(removed_sep.c_str());
9487 int result = CreateDirectory(unicode,
nullptr) ? 0 : -1;
9489 #elif GTEST_OS_WINDOWS 9490 int result = _mkdir(pathname_.c_str());
9492 int result = mkdir(pathname_.c_str(), 0777);
9493 #endif // GTEST_OS_WINDOWS_MOBILE 9496 return this->DirectoryExists();
9504 FilePath FilePath::RemoveTrailingPathSeparator()
const {
9505 return IsDirectory()
9506 ? FilePath(pathname_.substr(0, pathname_.length() - 1))
9513 void FilePath::Normalize() {
9514 if (pathname_.c_str() ==
nullptr) {
9518 const char* src = pathname_.c_str();
9519 char*
const dest =
new char[pathname_.length() + 1];
9520 char* dest_ptr = dest;
9521 memset(dest_ptr, 0, pathname_.length() + 1);
9523 while (*src !=
'\0') {
9525 if (!IsPathSeparator(*src)) {
9528 #if GTEST_HAS_ALT_PATH_SEP_ 9529 if (*dest_ptr == kAlternatePathSeparator) {
9533 while (IsPathSeparator(*src))
9586 Matcher<const std::string&>::Matcher(
const std::string& s) { *
this = Eq(s); }
9588 #if GTEST_HAS_GLOBAL_STRING 9592 *
this = Eq(static_cast<std::string>(s));
9594 #endif // GTEST_HAS_GLOBAL_STRING 9598 Matcher<const std::string&>::Matcher(
const char* s) {
9604 Matcher<std::string>::Matcher(
const std::string& s) { *
this = Eq(s); }
9606 #if GTEST_HAS_GLOBAL_STRING 9610 *
this = Eq(static_cast<std::string>(s));
9612 #endif // GTEST_HAS_GLOBAL_STRING 9616 Matcher<std::string>::Matcher(
const char* s) { *
this = Eq(
std::string(s)); }
9618 #if GTEST_HAS_GLOBAL_STRING 9621 Matcher<const ::string&>::Matcher(
const std::string& s) {
9622 *
this = Eq(static_cast<::string>(s));
9627 Matcher<const ::string&>::Matcher(
const ::string& s) { *
this = Eq(s); }
9631 Matcher<const ::string&>::Matcher(
const char* s) { *
this = Eq(::
string(s)); }
9634 Matcher<::string>::Matcher(
const std::string& s) {
9635 *
this = Eq(static_cast<::string>(s));
9642 Matcher<::string>::Matcher(
const char* s) { *
this = Eq(::
string(s)); }
9643 #endif // GTEST_HAS_GLOBAL_STRING 9648 Matcher<const absl::string_view&>::Matcher(
const std::string& s) {
9652 #if GTEST_HAS_GLOBAL_STRING 9655 Matcher<const absl::string_view&>::Matcher(
const ::string& s) { *
this = Eq(s); }
9656 #endif // GTEST_HAS_GLOBAL_STRING 9660 Matcher<const absl::string_view&>::Matcher(
const char* s) {
9666 Matcher<const absl::string_view&>::Matcher(absl::string_view s) {
9672 Matcher<absl::string_view>::Matcher(
const std::string& s) { *
this = Eq(s); }
9674 #if GTEST_HAS_GLOBAL_STRING 9677 Matcher<absl::string_view>::Matcher(
const ::string& s) { *
this = Eq(s); }
9678 #endif // GTEST_HAS_GLOBAL_STRING 9682 Matcher<absl::string_view>::Matcher(
const char* s) {
9688 Matcher<absl::string_view>::Matcher(absl::string_view s) {
9691 #endif // GTEST_HAS_ABSL 9732 #if GTEST_OS_WINDOWS 9733 # include <windows.h> 9735 # include <sys/stat.h> 9738 # include <crtdbg.h> 9741 # include <unistd.h> 9742 #endif // GTEST_OS_WINDOWS 9745 # include <mach/mach_init.h> 9746 # include <mach/task.h> 9747 # include <mach/vm_map.h> 9748 #endif // GTEST_OS_MAC 9751 # include <devctl.h> 9753 # include <sys/procfs.h> 9754 #endif // GTEST_OS_QNX 9757 # include <procinfo.h> 9758 # include <sys/types.h> 9759 #endif // GTEST_OS_AIX 9761 #if GTEST_OS_FUCHSIA 9762 # include <zircon/process.h> 9763 # include <zircon/syscalls.h> 9764 #endif // GTEST_OS_FUCHSIA 9768 namespace internal {
9770 #if defined(_MSC_VER) || defined(__BORLANDC__) 9782 template <
typename T>
9783 T ReadProcFileField(
const std::string& filename,
int field) {
9785 std::ifstream file(filename.c_str());
9786 while (field-- > 0) {
9798 (
Message() <<
"/proc/" << getpid() <<
"/stat").GetString();
9799 return ReadProcFileField<int>(filename, 19);
9805 const task_t task = mach_task_self();
9806 mach_msg_type_number_t thread_count;
9807 thread_act_array_t thread_list;
9808 const kern_return_t status = task_threads(task, &thread_list, &thread_count);
9809 if (status == KERN_SUCCESS) {
9813 reinterpret_cast<vm_address_t>(thread_list),
9814 sizeof(thread_t) * thread_count);
9815 return static_cast<size_t>(thread_count);
9826 const int fd = open(
"/proc/self/as", O_RDONLY);
9830 procfs_info process_info;
9832 devctl(fd, DCMD_PROC_INFO, &process_info,
sizeof(process_info),
nullptr);
9834 if (status == EOK) {
9835 return static_cast<size_t>(process_info.num_threads);
9844 struct procentry64 entry;
9845 pid_t pid = getpid();
9846 int status = getprocs64(&entry,
sizeof(entry),
nullptr, 0, &pid, 1);
9848 return entry.pi_thcount;
9854 #elif GTEST_OS_FUCHSIA 9859 zx_status_t status = zx_object_get_info(
9861 ZX_INFO_PROCESS_THREADS,
9866 if (status == ZX_OK) {
9881 #endif // GTEST_OS_LINUX 9883 #if GTEST_IS_THREADSAFE && GTEST_OS_WINDOWS 9885 void SleepMilliseconds(
int n) {
9889 AutoHandle::AutoHandle()
9890 : handle_(INVALID_HANDLE_VALUE) {}
9892 AutoHandle::AutoHandle(Handle handle)
9893 : handle_(handle) {}
9895 AutoHandle::~AutoHandle() {
9899 AutoHandle::Handle AutoHandle::Get()
const {
9903 void AutoHandle::Reset() {
9904 Reset(INVALID_HANDLE_VALUE);
9907 void AutoHandle::Reset(HANDLE handle) {
9909 if (handle_ != handle) {
9910 if (IsCloseable()) {
9911 ::CloseHandle(handle_);
9916 <<
"Resetting a valid handle to itself is likely a programmer error " 9917 "and thus not allowed.";
9921 bool AutoHandle::IsCloseable()
const {
9924 return handle_ !=
nullptr && handle_ != INVALID_HANDLE_VALUE;
9927 Notification::Notification()
9928 : event_(::CreateEvent(nullptr,
9935 void Notification::Notify() {
9939 void Notification::WaitForNotification() {
9941 ::WaitForSingleObject(event_.Get(), INFINITE) == WAIT_OBJECT_0);
9945 : owner_thread_id_(0),
9947 critical_section_init_phase_(0),
9948 critical_section_(new CRITICAL_SECTION) {
9949 ::InitializeCriticalSection(critical_section_);
9955 if (type_ == kDynamic) {
9956 ::DeleteCriticalSection(critical_section_);
9957 delete critical_section_;
9958 critical_section_ =
nullptr;
9962 void Mutex::Lock() {
9963 ThreadSafeLazyInit();
9964 ::EnterCriticalSection(critical_section_);
9965 owner_thread_id_ = ::GetCurrentThreadId();
9968 void Mutex::Unlock() {
9969 ThreadSafeLazyInit();
9973 owner_thread_id_ = 0;
9974 ::LeaveCriticalSection(critical_section_);
9979 void Mutex::AssertHeld() {
9980 ThreadSafeLazyInit();
9981 GTEST_CHECK_(owner_thread_id_ == ::GetCurrentThreadId())
9982 <<
"The current thread is not holding the mutex @" <<
this;
9995 class MemoryIsNotDeallocated
9998 MemoryIsNotDeallocated() : old_crtdbg_flag_(0) {
10000 old_crtdbg_flag_ = _CrtSetDbgFlag(_CRTDBG_REPORT_FLAG);
10003 _CrtSetDbgFlag(old_crtdbg_flag_ & ~_CRTDBG_ALLOC_MEM_DF);
10007 ~MemoryIsNotDeallocated() {
10010 _CrtSetDbgFlag(old_crtdbg_flag_);
10015 int old_crtdbg_flag_;
10023 void Mutex::ThreadSafeLazyInit() {
10025 if (type_ == kStatic) {
10027 ::InterlockedCompareExchange(&critical_section_init_phase_, 1L, 0L)) {
10031 owner_thread_id_ = 0;
10034 MemoryIsNotDeallocated memory_is_not_deallocated;
10035 critical_section_ =
new CRITICAL_SECTION;
10037 ::InitializeCriticalSection(critical_section_);
10041 &critical_section_init_phase_, 2L, 1L) ==
10047 while (::InterlockedCompareExchange(&critical_section_init_phase_,
10061 <<
"Unexpected value of critical_section_init_phase_ " 10062 <<
"while initializing a static mutex.";
10069 class ThreadWithParamSupport :
public ThreadWithParamBase {
10071 static HANDLE CreateThread(Runnable* runnable,
10072 Notification* thread_can_start) {
10073 ThreadMainParam* param =
new ThreadMainParam(runnable, thread_can_start);
10075 HANDLE thread_handle = ::CreateThread(
10078 &ThreadWithParamSupport::ThreadMain,
10083 <<
"CreateThread failed with error " << ::GetLastError() <<
".";
10084 if (thread_handle ==
nullptr) {
10087 return thread_handle;
10091 struct ThreadMainParam {
10092 ThreadMainParam(Runnable* runnable, Notification* thread_can_start)
10093 : runnable_(runnable),
10094 thread_can_start_(thread_can_start) {
10096 std::unique_ptr<Runnable> runnable_;
10098 Notification* thread_can_start_;
10101 static DWORD WINAPI ThreadMain(
void* ptr) {
10103 std::unique_ptr<ThreadMainParam> param(static_cast<ThreadMainParam*>(ptr));
10104 if (param->thread_can_start_ !=
nullptr)
10105 param->thread_can_start_->WaitForNotification();
10106 param->runnable_->Run();
10111 ThreadWithParamSupport();
10118 ThreadWithParamBase::ThreadWithParamBase(Runnable *runnable,
10119 Notification* thread_can_start)
10120 : thread_(ThreadWithParamSupport::CreateThread(runnable,
10121 thread_can_start)) {
10124 ThreadWithParamBase::~ThreadWithParamBase() {
10128 void ThreadWithParamBase::Join() {
10129 GTEST_CHECK_(::WaitForSingleObject(thread_.Get(), INFINITE) == WAIT_OBJECT_0)
10130 <<
"Failed to join the thread with error " << ::GetLastError() <<
".";
10137 class ThreadLocalRegistryImpl {
10141 static ThreadLocalValueHolderBase* GetValueOnCurrentThread(
10142 const ThreadLocalBase* thread_local_instance) {
10143 DWORD current_thread = ::GetCurrentThreadId();
10145 ThreadIdToThreadLocals*
const thread_to_thread_locals =
10146 GetThreadLocalsMapLocked();
10147 ThreadIdToThreadLocals::iterator thread_local_pos =
10148 thread_to_thread_locals->find(current_thread);
10149 if (thread_local_pos == thread_to_thread_locals->end()) {
10150 thread_local_pos = thread_to_thread_locals->insert(
10151 std::make_pair(current_thread, ThreadLocalValues())).first;
10152 StartWatcherThreadFor(current_thread);
10154 ThreadLocalValues& thread_local_values = thread_local_pos->second;
10155 ThreadLocalValues::iterator value_pos =
10156 thread_local_values.find(thread_local_instance);
10157 if (value_pos == thread_local_values.end()) {
10159 thread_local_values
10160 .insert(std::make_pair(
10161 thread_local_instance,
10162 std::shared_ptr<ThreadLocalValueHolderBase>(
10163 thread_local_instance->NewValueForCurrentThread())))
10166 return value_pos->second.get();
10169 static void OnThreadLocalDestroyed(
10170 const ThreadLocalBase* thread_local_instance) {
10171 std::vector<std::shared_ptr<ThreadLocalValueHolderBase> > value_holders;
10176 ThreadIdToThreadLocals*
const thread_to_thread_locals =
10177 GetThreadLocalsMapLocked();
10178 for (ThreadIdToThreadLocals::iterator it =
10179 thread_to_thread_locals->begin();
10180 it != thread_to_thread_locals->end();
10182 ThreadLocalValues& thread_local_values = it->second;
10183 ThreadLocalValues::iterator value_pos =
10184 thread_local_values.find(thread_local_instance);
10185 if (value_pos != thread_local_values.end()) {
10186 value_holders.push_back(value_pos->second);
10187 thread_local_values.erase(value_pos);
10197 static void OnThreadExit(DWORD thread_id) {
10199 std::vector<std::shared_ptr<ThreadLocalValueHolderBase> > value_holders;
10204 ThreadIdToThreadLocals*
const thread_to_thread_locals =
10205 GetThreadLocalsMapLocked();
10206 ThreadIdToThreadLocals::iterator thread_local_pos =
10207 thread_to_thread_locals->find(thread_id);
10208 if (thread_local_pos != thread_to_thread_locals->end()) {
10209 ThreadLocalValues& thread_local_values = thread_local_pos->second;
10210 for (ThreadLocalValues::iterator value_pos =
10211 thread_local_values.begin();
10212 value_pos != thread_local_values.end();
10214 value_holders.push_back(value_pos->second);
10216 thread_to_thread_locals->erase(thread_local_pos);
10225 typedef std::map<
const ThreadLocalBase*,
10226 std::shared_ptr<ThreadLocalValueHolderBase> >
10230 typedef std::map<DWORD, ThreadLocalValues> ThreadIdToThreadLocals;
10234 typedef std::pair<DWORD, HANDLE> ThreadIdAndHandle;
10236 static void StartWatcherThreadFor(DWORD thread_id) {
10239 HANDLE thread = ::OpenThread(SYNCHRONIZE | THREAD_QUERY_INFORMATION,
10245 DWORD watcher_thread_id;
10246 HANDLE watcher_thread = ::CreateThread(
10249 &ThreadLocalRegistryImpl::WatcherThreadFunc,
10250 reinterpret_cast<LPVOID>(
new ThreadIdAndHandle(thread_id, thread)),
10251 CREATE_SUSPENDED, &watcher_thread_id);
10255 ::SetThreadPriority(watcher_thread,
10256 ::GetThreadPriority(::GetCurrentThread()));
10257 ::ResumeThread(watcher_thread);
10258 ::CloseHandle(watcher_thread);
10263 static DWORD WINAPI WatcherThreadFunc(LPVOID param) {
10264 const ThreadIdAndHandle* tah =
10265 reinterpret_cast<const ThreadIdAndHandle*
>(param);
10267 ::WaitForSingleObject(tah->second, INFINITE) == WAIT_OBJECT_0);
10268 OnThreadExit(tah->first);
10269 ::CloseHandle(tah->second);
10275 static ThreadIdToThreadLocals* GetThreadLocalsMapLocked() {
10276 mutex_.AssertHeld();
10277 MemoryIsNotDeallocated memory_is_not_deallocated;
10278 static ThreadIdToThreadLocals* map =
new ThreadIdToThreadLocals();
10283 static Mutex mutex_;
10285 static Mutex thread_map_mutex_;
10288 Mutex ThreadLocalRegistryImpl::mutex_(Mutex::kStaticMutex);
10289 Mutex ThreadLocalRegistryImpl::thread_map_mutex_(Mutex::kStaticMutex);
10291 ThreadLocalValueHolderBase* ThreadLocalRegistry::GetValueOnCurrentThread(
10292 const ThreadLocalBase* thread_local_instance) {
10293 return ThreadLocalRegistryImpl::GetValueOnCurrentThread(
10294 thread_local_instance);
10297 void ThreadLocalRegistry::OnThreadLocalDestroyed(
10298 const ThreadLocalBase* thread_local_instance) {
10299 ThreadLocalRegistryImpl::OnThreadLocalDestroyed(thread_local_instance);
10302 #endif // GTEST_IS_THREADSAFE && GTEST_OS_WINDOWS 10304 #if GTEST_USES_POSIX_RE 10314 regfree(&partial_regex_);
10315 regfree(&full_regex_);
10317 free(const_cast<char*>(pattern_));
10321 bool RE::FullMatch(
const char* str,
const RE& re) {
10322 if (!re.is_valid_)
return false;
10325 return regexec(&re.full_regex_, str, 1, &match, 0) == 0;
10330 bool RE::PartialMatch(
const char* str,
const RE& re) {
10331 if (!re.is_valid_)
return false;
10334 return regexec(&re.partial_regex_, str, 1, &match, 0) == 0;
10338 void RE::Init(
const char* regex) {
10343 const size_t full_regex_len = strlen(regex) + 10;
10344 char*
const full_pattern =
new char[full_regex_len];
10346 snprintf(full_pattern, full_regex_len,
"^(%s)$", regex);
10347 is_valid_ = regcomp(&full_regex_, full_pattern, REG_EXTENDED) == 0;
10357 const char*
const partial_regex = (*regex ==
'\0') ?
"()" : regex;
10358 is_valid_ = regcomp(&partial_regex_, partial_regex, REG_EXTENDED) == 0;
10361 <<
"Regular expression \"" << regex
10362 <<
"\" is not a valid POSIX Extended regular expression.";
10364 delete[] full_pattern;
10367 #elif GTEST_USES_SIMPLE_RE 10371 bool IsInSet(
char ch,
const char* str) {
10372 return ch !=
'\0' && strchr(str, ch) !=
nullptr;
10378 bool IsAsciiDigit(
char ch) {
return '0' <= ch && ch <=
'9'; }
10379 bool IsAsciiPunct(
char ch) {
10380 return IsInSet(ch,
"^-!\"#$%&'()*+,./:;<=>?@[\\]_`{|}~");
10382 bool IsRepeat(
char ch) {
return IsInSet(ch,
"?*+"); }
10383 bool IsAsciiWhiteSpace(
char ch) {
return IsInSet(ch,
" \f\n\r\t\v"); }
10384 bool IsAsciiWordChar(
char ch) {
10385 return (
'a' <= ch && ch <=
'z') || (
'A' <= ch && ch <=
'Z') ||
10386 (
'0' <= ch && ch <=
'9') || ch ==
'_';
10390 bool IsValidEscape(
char c) {
10391 return (IsAsciiPunct(c) || IsInSet(c,
"dDfnrsStvwW"));
10396 bool AtomMatchesChar(
bool escaped,
char pattern_char,
char ch) {
10398 switch (pattern_char) {
10399 case 'd':
return IsAsciiDigit(ch);
10400 case 'D':
return !IsAsciiDigit(ch);
10401 case 'f':
return ch ==
'\f';
10402 case 'n':
return ch ==
'\n';
10403 case 'r':
return ch ==
'\r';
10404 case 's':
return IsAsciiWhiteSpace(ch);
10405 case 'S':
return !IsAsciiWhiteSpace(ch);
10406 case 't':
return ch ==
'\t';
10407 case 'v':
return ch ==
'\v';
10408 case 'w':
return IsAsciiWordChar(ch);
10409 case 'W':
return !IsAsciiWordChar(ch);
10411 return IsAsciiPunct(pattern_char) && pattern_char == ch;
10414 return (pattern_char ==
'.' && ch !=
'\n') || pattern_char == ch;
10418 static std::string FormatRegexSyntaxError(
const char* regex,
int index) {
10419 return (Message() <<
"Syntax error at index " << index
10420 <<
" in simple regular expression \"" << regex <<
"\": ").GetString();
10425 bool ValidateRegex(
const char* regex) {
10426 if (regex ==
nullptr) {
10427 ADD_FAILURE() <<
"NULL is not a valid simple regular expression.";
10431 bool is_valid =
true;
10434 bool prev_repeatable =
false;
10435 for (
int i = 0; regex[i]; i++) {
10436 if (regex[i] ==
'\\') {
10438 if (regex[i] ==
'\0') {
10439 ADD_FAILURE() << FormatRegexSyntaxError(regex, i - 1)
10440 <<
"'\\' cannot appear at the end.";
10444 if (!IsValidEscape(regex[i])) {
10445 ADD_FAILURE() << FormatRegexSyntaxError(regex, i - 1)
10446 <<
"invalid escape sequence \"\\" << regex[i] <<
"\".";
10449 prev_repeatable =
true;
10451 const char ch = regex[i];
10453 if (ch ==
'^' && i > 0) {
10454 ADD_FAILURE() << FormatRegexSyntaxError(regex, i)
10455 <<
"'^' can only appear at the beginning.";
10457 }
else if (ch ==
'$' && regex[i + 1] !=
'\0') {
10458 ADD_FAILURE() << FormatRegexSyntaxError(regex, i)
10459 <<
"'$' can only appear at the end.";
10461 }
else if (IsInSet(ch,
"()[]{}|")) {
10462 ADD_FAILURE() << FormatRegexSyntaxError(regex, i)
10463 <<
"'" << ch <<
"' is unsupported.";
10465 }
else if (IsRepeat(ch) && !prev_repeatable) {
10466 ADD_FAILURE() << FormatRegexSyntaxError(regex, i)
10467 <<
"'" << ch <<
"' can only follow a repeatable token.";
10471 prev_repeatable = !IsInSet(ch,
"^$?*+");
10485 bool MatchRepetitionAndRegexAtHead(
10486 bool escaped,
char c,
char repeat,
const char* regex,
10488 const size_t min_count = (
repeat ==
'+') ? 1 : 0;
10489 const size_t max_count = (
repeat ==
'?') ? 1 :
10490 static_cast<size_t>(-1) - 1;
10494 for (
size_t i = 0; i <= max_count; ++i) {
10496 if (i >= min_count && MatchRegexAtHead(regex, str + i)) {
10503 if (str[i] ==
'\0' || !AtomMatchesChar(escaped, c, str[i]))
10512 bool MatchRegexAtHead(
const char* regex,
const char* str) {
10513 if (*regex ==
'\0')
10519 return *str ==
'\0';
10522 const bool escaped = *regex ==
'\\';
10525 if (IsRepeat(regex[1])) {
10529 return MatchRepetitionAndRegexAtHead(
10530 escaped, regex[0], regex[1], regex + 2, str);
10535 return (*str !=
'\0') && AtomMatchesChar(escaped, *regex, *str) &&
10536 MatchRegexAtHead(regex + 1, str + 1);
10548 bool MatchRegexAnywhere(
const char* regex,
const char* str) {
10549 if (regex ==
nullptr || str ==
nullptr)
return false;
10552 return MatchRegexAtHead(regex + 1, str);
10556 if (MatchRegexAtHead(regex, str))
10558 }
while (*str++ !=
'\0');
10565 free(const_cast<char*>(pattern_));
10566 free(const_cast<char*>(full_pattern_));
10570 bool RE::FullMatch(
const char* str,
const RE& re) {
10571 return re.is_valid_ && MatchRegexAnywhere(re.full_pattern_, str);
10576 bool RE::PartialMatch(
const char* str,
const RE& re) {
10577 return re.is_valid_ && MatchRegexAnywhere(re.pattern_, str);
10581 void RE::Init(
const char* regex) {
10582 pattern_ = full_pattern_ =
nullptr;
10583 if (regex !=
nullptr) {
10587 is_valid_ = ValidateRegex(regex);
10593 const size_t len = strlen(regex);
10597 char* buffer =
static_cast<char*
>(malloc(len + 3));
10598 full_pattern_ = buffer;
10605 memcpy(buffer, regex, len);
10608 if (len == 0 || regex[len - 1] !=
'$')
10614 #endif // GTEST_USES_POSIX_RE 10624 return file_name +
":";
10639 const char* file,
int line) {
10649 : severity_(severity) {
10650 const char*
const marker =
10653 severity ==
GTEST_ERROR ?
"[ ERROR ]" :
"[ FATAL ]";
10654 GetStream() << ::std::endl << marker <<
" " 10671 #if GTEST_HAS_STREAM_REDIRECTION 10678 # if GTEST_OS_WINDOWS 10679 char temp_dir_path[MAX_PATH + 1] = {
'\0' };
10680 char temp_file_path[MAX_PATH + 1] = {
'\0' };
10682 ::GetTempPathA(
sizeof(temp_dir_path), temp_dir_path);
10683 const UINT success = ::GetTempFileNameA(temp_dir_path,
10688 <<
"Unable to create a temporary file in " << temp_dir_path;
10689 const int captured_fd = creat(temp_file_path, _S_IREAD | _S_IWRITE);
10690 GTEST_CHECK_(captured_fd != -1) <<
"Unable to open temporary file " 10692 filename_ = temp_file_path;
10698 # if GTEST_OS_LINUX_ANDROID 10713 char name_template[] =
"/sdcard/gtest_captured_stream.XXXXXX";
10715 char name_template[] =
"/tmp/captured_stream.XXXXXX";
10716 # endif // GTEST_OS_LINUX_ANDROID 10717 const int captured_fd = mkstemp(name_template);
10718 filename_ = name_template;
10719 # endif // GTEST_OS_WINDOWS 10721 dup2(captured_fd, fd_);
10722 close(captured_fd);
10726 remove(filename_.c_str());
10730 if (uncaptured_fd_ != -1) {
10733 dup2(uncaptured_fd_, fd_);
10734 close(uncaptured_fd_);
10735 uncaptured_fd_ = -1;
10738 FILE*
const file =
posix::FOpen(filename_.c_str(),
"r");
10746 int uncaptured_fd_;
10755 static CapturedStream* g_captured_stderr =
nullptr;
10756 static CapturedStream* g_captured_stdout =
nullptr;
10759 static
void CaptureStream(
int fd, const
char* stream_name,
10760 CapturedStream** stream) {
10761 if (*stream !=
nullptr) {
10762 GTEST_LOG_(FATAL) <<
"Only one " << stream_name
10763 <<
" capturer can exist at a time.";
10765 *stream =
new CapturedStream(fd);
10769 static std::string GetCapturedStream(CapturedStream** captured_stream) {
10770 const std::string content = (*captured_stream)->GetCapturedString();
10772 delete *captured_stream;
10773 *captured_stream =
nullptr;
10780 CaptureStream(
kStdOutFileno,
"stdout", &g_captured_stdout);
10785 CaptureStream(
kStdErrFileno,
"stderr", &g_captured_stderr);
10790 return GetCapturedStream(&g_captured_stdout);
10795 return GetCapturedStream(&g_captured_stderr);
10798 #endif // GTEST_HAS_STREAM_REDIRECTION 10805 fseek(file, 0, SEEK_END);
10806 return static_cast<size_t>(ftell(file));
10811 char*
const buffer =
new char[file_size];
10813 size_t bytes_last_read = 0;
10814 size_t bytes_read = 0;
10816 fseek(file, 0, SEEK_SET);
10821 bytes_last_read = fread(buffer+bytes_read, 1, file_size-bytes_read, file);
10822 bytes_read += bytes_last_read;
10823 }
while (bytes_last_read > 0 && bytes_read < file_size);
10831 #if GTEST_HAS_DEATH_TEST 10832 static const std::vector<std::string>* g_injected_test_argvs =
10835 std::vector<std::string> GetInjectableArgvs() {
10836 if (g_injected_test_argvs !=
nullptr) {
10837 return *g_injected_test_argvs;
10842 void SetInjectableArgvs(
const std::vector<std::string>* new_argvs) {
10843 if (g_injected_test_argvs != new_argvs)
delete g_injected_test_argvs;
10844 g_injected_test_argvs = new_argvs;
10847 void SetInjectableArgvs(
const std::vector<std::string>& new_argvs) {
10848 SetInjectableArgvs(
10849 new std::vector<std::string>(new_argvs.begin(), new_argvs.end()));
10852 #if GTEST_HAS_GLOBAL_STRING 10853 void SetInjectableArgvs(
const std::vector< ::string>& new_argvs) {
10854 SetInjectableArgvs(
10855 new std::vector<std::string>(new_argvs.begin(), new_argvs.end()));
10857 #endif // GTEST_HAS_GLOBAL_STRING 10859 void ClearInjectableArgvs() {
10860 delete g_injected_test_argvs;
10861 g_injected_test_argvs =
nullptr;
10863 #endif // GTEST_HAS_DEATH_TEST 10865 #if GTEST_OS_WINDOWS_MOBILE 10869 TerminateProcess(GetCurrentProcess(), 1);
10872 #endif // GTEST_OS_WINDOWS_MOBILE 10877 static std::string FlagToEnvVar(
const char* flag) {
10882 for (
size_t i = 0; i != full_flag.length(); i++) {
10883 env_var <<
ToUpper(full_flag.c_str()[i]);
10886 return env_var.GetString();
10894 char* end =
nullptr;
10895 const long long_value = strtol(str, &end, 10);
10898 if (*end !=
'\0') {
10901 msg <<
"WARNING: " << src_text
10902 <<
" is expected to be a 32-bit integer, but actually" 10903 <<
" has value \"" << str <<
"\".\n";
10910 const Int32 result =
static_cast<Int32>(long_value);
10911 if (long_value == LONG_MAX || long_value == LONG_MIN ||
10914 result != long_value
10918 msg <<
"WARNING: " << src_text
10919 <<
" is expected to be a 32-bit integer, but actually" 10920 <<
" has value " << str <<
", which overflows.\n";
10935 #if defined(GTEST_GET_BOOL_FROM_ENV_) 10936 return GTEST_GET_BOOL_FROM_ENV_(flag, default_value);
10939 const char*
const string_value =
posix::GetEnv(env_var.c_str());
10940 return string_value ==
nullptr ? default_value
10941 : strcmp(string_value,
"0") != 0;
10942 #endif // defined(GTEST_GET_BOOL_FROM_ENV_) 10949 #if defined(GTEST_GET_INT32_FROM_ENV_) 10950 return GTEST_GET_INT32_FROM_ENV_(flag, default_value);
10953 const char*
const string_value =
posix::GetEnv(env_var.c_str());
10954 if (string_value ==
nullptr) {
10956 return default_value;
10959 Int32 result = default_value;
10961 string_value, &result)) {
10962 printf(
"The default value %s is used.\n",
10963 (
Message() << default_value).GetString().c_str());
10965 return default_value;
10969 #endif // defined(GTEST_GET_INT32_FROM_ENV_) 10982 const char* xml_output_file_env =
posix::GetEnv(
"XML_OUTPUT_FILE");
10983 if (
nullptr != xml_output_file_env) {
10984 default_value_for_output_flag =
std::string(
"xml:") + xml_output_file_env;
10986 return default_value_for_output_flag;
10992 #if defined(GTEST_GET_STRING_FROM_ENV_) 10993 return GTEST_GET_STRING_FROM_ENV_(flag, default_value);
10997 return value ==
nullptr ? default_value : value;
10998 #endif // defined(GTEST_GET_STRING_FROM_ENV_) 11056 using ::std::ostream;
11062 void PrintByteSegmentInObjectTo(
const unsigned char* obj_bytes,
size_t start,
11063 size_t count, ostream* os) {
11065 for (
size_t i = 0; i !=
count; i++) {
11066 const size_t j = start + i;
11081 void PrintBytesInObjectToImpl(
const unsigned char* obj_bytes,
size_t count,
11084 *os <<
count <<
"-byte object <";
11086 const size_t kThreshold = 132;
11087 const size_t kChunkSize = 64;
11091 if (
count < kThreshold) {
11092 PrintByteSegmentInObjectTo(obj_bytes, 0,
count, os);
11094 PrintByteSegmentInObjectTo(obj_bytes, 0, kChunkSize, os);
11097 const size_t resume_pos = (
count - kChunkSize + 1)/2*2;
11098 PrintByteSegmentInObjectTo(obj_bytes, resume_pos,
count - resume_pos, os);
11105 namespace internal2 {
11114 PrintBytesInObjectToImpl(obj_bytes,
count, os);
11119 namespace internal {
11136 return 0x20 <= c && c <= 0x7E;
11143 template <
typename Un
signedChar,
typename Char>
11144 static CharFormat PrintAsCharLiteralTo(Char c, ostream* os) {
11145 switch (static_cast<wchar_t>(c)) {
11178 *os << static_cast<char>(c);
11181 ostream::fmtflags flags = os->flags();
11182 *os <<
"\\x" << std::hex << std::uppercase
11183 <<
static_cast<int>(
static_cast<UnsignedChar
>(c));
11193 static CharFormat PrintAsStringLiteralTo(
wchar_t c, ostream* os) {
11202 return PrintAsCharLiteralTo<wchar_t>(c, os);
11208 static CharFormat PrintAsStringLiteralTo(
char c, ostream* os) {
11209 return PrintAsStringLiteralTo(
11210 static_cast<wchar_t>(static_cast<unsigned char>(c)), os);
11217 template <
typename Un
signedChar,
typename Char>
11220 *os << ((sizeof(c) > 1) ?
"L'" :
"'");
11221 const CharFormat format = PrintAsCharLiteralTo<UnsignedChar>(c, os);
11229 *os <<
" (" <<
static_cast<int>(c);
11234 if (format ==
kHexEscape || (1 <= c && c <= 9)) {
11237 *os <<
", 0x" << String::FormatHexInt(static_cast<UnsignedChar>(c));
11243 PrintCharAndCodeTo<unsigned char>(c, os);
11246 PrintCharAndCodeTo<unsigned char>(c, os);
11252 PrintCharAndCodeTo<wchar_t>(wc, os);
11259 template <
typename CharType>
11264 const CharType* begin,
size_t len, ostream* os) {
11265 const char*
const kQuoteBegin =
sizeof(CharType) == 1 ?
"\"" :
"L\"";
11266 *os << kQuoteBegin;
11267 bool is_previous_hex =
false;
11269 for (
size_t index = 0; index < len; ++index) {
11270 const CharType cur = begin[index];
11271 if (is_previous_hex &&
IsXDigit(cur)) {
11275 *os <<
"\" " << kQuoteBegin;
11277 is_previous_hex = PrintAsStringLiteralTo(cur, os) ==
kHexEscape;
11279 if (is_previous_hex) {
11284 return print_format;
11289 template <
typename CharType>
11293 static void UniversalPrintCharArray(
11294 const CharType* begin,
size_t len, ostream* os) {
11302 if (len > 0 && begin[len - 1] ==
'\0') {
11303 PrintCharsAsStringTo(begin, len - 1, os);
11311 PrintCharsAsStringTo(begin, len, os);
11312 *os <<
" (no terminating NUL)";
11317 UniversalPrintCharArray(begin, len, os);
11323 UniversalPrintCharArray(begin, len, os);
11328 if (s ==
nullptr) {
11331 *os << ImplicitCast_<const void*>(s) <<
" pointing to ";
11332 PrintCharsAsStringTo(s, strlen(s), os);
11342 #if !defined(_MSC_VER) || defined(_NATIVE_WCHAR_T_DEFINED) 11345 if (s ==
nullptr) {
11348 *os << ImplicitCast_<const void*>(s) <<
" pointing to ";
11349 PrintCharsAsStringTo(s, wcslen(s), os);
11352 #endif // wchar_t is native 11356 bool ContainsUnprintableControlCodes(
const char* str,
size_t length) {
11357 const unsigned char *s =
reinterpret_cast<const unsigned char *
>(str);
11359 for (
size_t i = 0; i < length; i++) {
11360 unsigned char ch = *s++;
11361 if (std::iscntrl(ch)) {
11375 bool IsUTF8TrailByte(
unsigned char t) {
return 0x80 <= t && t<= 0xbf; }
11377 bool IsValidUTF8(
const char* str,
size_t length) {
11378 const unsigned char *s =
reinterpret_cast<const unsigned char *
>(str);
11380 for (
size_t i = 0; i < length;) {
11381 unsigned char lead = s[i++];
11383 if (lead <= 0x7f) {
11388 }
else if (lead <= 0xdf && (i + 1) <= length && IsUTF8TrailByte(s[i])) {
11390 }
else if (0xe0 <= lead && lead <= 0xef && (i + 2) <= length &&
11391 IsUTF8TrailByte(s[i]) &&
11392 IsUTF8TrailByte(s[i + 1]) &&
11394 (lead != 0xe0 || s[i] >= 0xa0) &&
11395 (lead != 0xed || s[i] < 0xa0)) {
11397 }
else if (0xf0 <= lead && lead <= 0xf4 && (i + 3) <= length &&
11398 IsUTF8TrailByte(s[i]) &&
11399 IsUTF8TrailByte(s[i + 1]) &&
11400 IsUTF8TrailByte(s[i + 2]) &&
11402 (lead != 0xf0 || s[i] >= 0x90) &&
11403 (lead != 0xf4 || s[i] < 0x90)) {
11412 void ConditionalPrintAsText(
const char* str,
size_t length, ostream* os) {
11413 if (!ContainsUnprintableControlCodes(str, length) &&
11414 IsValidUTF8(str, length)) {
11415 *os <<
"\n As Text: \"" << str <<
"\"";
11422 #if GTEST_HAS_GLOBAL_STRING 11424 if (PrintCharsAsStringTo(s.data(), s.size(), os) ==
kHexEscape) {
11426 ConditionalPrintAsText(s.data(), s.size(), os);
11430 #endif // GTEST_HAS_GLOBAL_STRING 11433 if (PrintCharsAsStringTo(s.data(), s.size(), os) ==
kHexEscape) {
11435 ConditionalPrintAsText(s.data(), s.size(), os);
11441 #if GTEST_HAS_GLOBAL_WSTRING 11443 PrintCharsAsStringTo(s.data(), s.size(), os);
11445 #endif // GTEST_HAS_GLOBAL_WSTRING 11447 #if GTEST_HAS_STD_WSTRING 11449 PrintCharsAsStringTo(s.data(), s.size(), os);
11451 #endif // GTEST_HAS_STD_WSTRING 11491 using internal::GetUnitTestImpl;
11495 std::string TestPartResult::ExtractSummary(
const char* message) {
11497 return stack_trace ==
nullptr ? message :
std::string(message, stack_trace);
11501 std::ostream&
operator<<(std::ostream& os,
const TestPartResult& result) {
11502 return os << result.file_name() <<
":" << result.line_number() <<
": " 11503 << (result.type() == TestPartResult::kSuccess
11505 : result.type() == TestPartResult::kSkip
11507 : result.type() == TestPartResult::kFatalFailure
11509 :
"Non-fatal failure")
11511 << result.message() << std::endl;
11515 void TestPartResultArray::Append(
const TestPartResult& result) {
11516 array_.push_back(result);
11520 const TestPartResult& TestPartResultArray::GetTestPartResult(
int index)
const {
11521 if (index < 0 || index >=
size()) {
11522 printf(
"\nInvalid index (%d) into TestPartResultArray.\n", index);
11526 return array_[index];
11531 return static_cast<int>(array_.size());
11534 namespace internal {
11536 HasNewFatalFailureHelper::HasNewFatalFailureHelper()
11537 : has_new_fatal_failure_(false),
11538 original_reporter_(GetUnitTestImpl()->
11539 GetTestPartResultReporterForCurrentThread()) {
11540 GetUnitTestImpl()->SetTestPartResultReporterForCurrentThread(
this);
11543 HasNewFatalFailureHelper::~HasNewFatalFailureHelper() {
11544 GetUnitTestImpl()->SetTestPartResultReporterForCurrentThread(
11545 original_reporter_);
11548 void HasNewFatalFailureHelper::ReportTestPartResult(
11549 const TestPartResult& result) {
11550 if (result.fatally_failed())
11551 has_new_fatal_failure_ =
true;
11552 original_reporter_->ReportTestPartResult(result);
11591 namespace internal {
11593 #if GTEST_HAS_TYPED_TEST_P 11597 static const char* SkipSpaces(
const char* str) {
11603 static std::vector<std::string> SplitIntoTestNames(
const char* src) {
11604 std::vector<std::string> name_vec;
11605 src = SkipSpaces(src);
11606 for (; src !=
nullptr; src = SkipComma(src)) {
11615 const char* TypedTestSuitePState::VerifyRegisteredTestNames(
11616 const char* file,
int line,
const char* registered_tests) {
11617 typedef RegisteredTestsMap::const_iterator RegisteredTestIter;
11618 registered_ =
true;
11620 std::vector<std::string> name_vec = SplitIntoTestNames(registered_tests);
11624 std::set<std::string> tests;
11625 for (std::vector<std::string>::const_iterator name_it = name_vec.begin();
11626 name_it != name_vec.end(); ++name_it) {
11628 if (tests.count(name) != 0) {
11629 errors <<
"Test " << name <<
" is listed more than once.\n";
11633 bool found =
false;
11634 for (RegisteredTestIter it = registered_tests_.begin();
11635 it != registered_tests_.end();
11637 if (name == it->first) {
11644 tests.insert(name);
11646 errors <<
"No test named " << name
11647 <<
" can be found in this test suite.\n";
11651 for (RegisteredTestIter it = registered_tests_.begin();
11652 it != registered_tests_.end();
11654 if (tests.count(it->first) == 0) {
11655 errors <<
"You forgot to list test " << it->first <<
".\n";
11659 const std::string& errors_str = errors.GetString();
11660 if (errors_str !=
"") {
11662 errors_str.c_str());
11667 return registered_tests;
11670 #endif // GTEST_HAS_TYPED_TEST_P
void PrintCharAndCodeTo(Char c, ostream *os)
GTEST_API_ AssertionResult DoubleLE(const char *expr1, const char *expr2, double val1, double val2)
GTEST_API_ bool AlwaysTrue()
std::string GetCapturedStdout()
GTEST_API_ AssertionResult DoubleNearPredFormat(const char *expr1, const char *expr2, const char *abs_error_expr, double val1, double val2, double abs_error)
std::string GetCapturedStderr()
GTEST_API_ std::string GetCurrentOsStackTraceExceptTop(UnitTest *unit_test, int skip_count)
void(*)() SetUpTestSuiteFunc
#define GTEST_INIT_GOOGLE_TEST_NAME_
GTEST_API_ bool SkipPrefix(const char *prefix, const char **pstr)
#define GTEST_DEFINE_int32_(name, default_val, doc)
#define GTEST_FLAG_PREFIX_DASH_
AssertionResult CmpHelperEQ(const char *lhs_expression, const char *rhs_expression, const T1 &lhs, const T2 &rhs)
GTEST_API_ bool IsTrue(bool condition)
::std::string PrintToString(const T &value)
std::string ReadEntireFile(FILE *file)
#define GTEST_DISABLE_MSC_DEPRECATED_POP_()
GTEST_API_ AssertionResult CmpHelperSTRNE(const char *s1_expression, const char *s2_expression, const char *s1, const char *s2)
bool BoolFromGTestEnv(const char *flag, bool default_value)
GTEST_API_ AssertionResult IsSubstring(const char *needle_expr, const char *haystack_expr, const char *needle, const char *haystack)
GTEST_API_ ::std::string FormatFileLocation(const char *file, int line)
Int32 Int32FromGTestEnv(const char *flag, Int32 default_value)
#define GTEST_ATTRIBUTE_NO_SANITIZE_MEMORY_
GTEST_DISABLE_MSC_WARNINGS_PUSH_(4251) namespace testing
GTEST_API_ std::vector< EditType > CalculateOptimalEdits(const std::vector< size_t > &left, const std::vector< size_t > &right)
#define GTEST_DEFAULT_DEATH_TEST_STYLE
bool ParseInt32(const Message &src_text, const char *str, Int32 *value)
int Stat(const char *path, StatStruct *buf)
GTEST_API_ AssertionResult IsNotSubstring(const char *needle_expr, const char *haystack_expr, const char *needle, const char *haystack)
GTEST_DISABLE_MSC_WARNINGS_POP_() GTEST_DISABLE_MSC_WARNINGS_PUSH_(4251) namespace testing
const char * GetEnv(const char *name)
void PrintStringTo(const ::std::string &s, ostream *os)
std::string FormatForComparisonFailureMessage(const T1 &value, const T2 &)
#define GTEST_DISABLE_MSC_DEPRECATED_PUSH_()
TypeWithSize< 8 >::Int TimeInMillis
GTEST_API_ AssertionResult EqFailure(const char *expected_expression, const char *actual_expression, const std::string &expected_value, const std::string &actual_value, bool ignoring_case)
std::ostream & operator<<(std::ostream &os, const TestPartResult &result)
const char kCurrentDirectoryString[]
#define GTEST_DECLARE_bool_(name)
size_t GetFileSize(FILE *file)
std::string StreamableToString(const T &streamable)
#define GTEST_LOG_(severity)
TypeWithSize< 4 >::UInt UInt32
const char * StringFromGTestEnv(const char *flag, const char *default_value)
int Write(int fd, const void *buf, unsigned int count)
void PrintBytesInObjectTo(const unsigned char *obj_bytes, size_t count, ostream *os)
GTEST_API_ AssertionResult CmpHelperSTRCASEEQ(const char *s1_expression, const char *s2_expression, const char *s1, const char *s2)
TypeWithSize< 4 >::Int Int32
#define GTEST_REVERSE_REPEATER_METHOD_(Name, Type)
GTEST_API_ const char * fmt
GTEST_API_ std::string TempDir()
void PrintTo(const wchar_t *s, ostream *os)
GTEST_API_ const char kStackTraceMarker[]
GTEST_DEFINE_string_(death_test_style, internal::StringFromGTestEnv("death_test_style", kDefaultDeathTestStyle), "Indicates how to run a death test in a forked child process: " "\hreadsafe\(child process re-executes the test binary " "from the beginning, running only the specific death test) or " "\ast\(child process runs the death test immediately " "after forking).")
::std::ostream & GetStream()
GTEST_DEFINE_string_(internal_run_death_test, "", "Indicates the file, line number, temporal index of " "the single death test to run, and a file descriptor to " "which a success code may be sent, all separated by " "the '|' characters. This flag is specified if and only if the current " "process is a sub-process launched for running a thread-safe " "death test. FOR INTERNAL USE ONLY.")
#define GTEST_IMPL_CMP_HELPER_(op_name, op)
GTEST_API_ AssertionResult CmpHelperSTRCASENE(const char *s1_expression, const char *s2_expression, const char *s1, const char *s2)
void(*)() TearDownTestSuiteFunc
GTEST_API_ void InitGoogleTest(int *argc, char **argv)
#define GTEST_REPEATER_METHOD_(Name, Type)
GTEST_API_ std::vector< std::string > GetArgvs()
GTEST_API_ TestInfo * MakeAndRegisterTestInfo(const char *test_suite_name, const char *name, const char *type_param, const char *value_param, CodeLocation code_location, TypeId fixture_class_id, SetUpTestSuiteFunc set_up_tc, TearDownTestSuiteFunc tear_down_tc, TestFactoryBase *factory)
int Read(int fd, void *buf, unsigned int count)
#define GTEST_CHECK_(condition)
#define EXPECT_PRED_FORMAT3(pred_format, v1, v2, v3)
int StrCaseCmp(const char *s1, const char *s2)
static const UInt32 kMaxRange
bool IsDir(const StatStruct &st)
bool IsPrintableAscii(wchar_t c)
#define GTEST_DISALLOW_COPY_AND_ASSIGN_(type)
#define GTEST_FLAG_PREFIX_UPPER_
void PrintTo(unsigned char c, ::std::ostream *os)
GTEST_API_ std::string GetBoolAssertionFailureMessage(const AssertionResult &assertion_result, const char *expression_text, const char *actual_predicate_value, const char *expected_predicate_value)
GTEST_API_ ::std::string FormatCompilerIndependentFileLocation(const char *file, int line)
FILE * FOpen(const char *path, const char *mode)
const char kUnknownFile[]
#define GTEST_FLAG_PREFIX_
GTEST_DEFINE_bool_(death_test_use_fork, internal::BoolFromGTestEnv("death_test_use_fork", false), "Instructs to use fork()/_exit() instead of clone() in death tests. " "Ignored and always uses fork() on POSIX systems where clone() is not " "implemented. Useful when running under valgrind or similar tools if " "those do not support clone(). Valgrind 3.3.1 will just fail if " "it sees an unsupported combination of clone() flags. " "It is not recommended to use this flag w/o valgrind though it will " "work in 99% of the cases. Once valgrind is fixed, this flag will " "most likely be removed.")
void UniversalPrintArray(const char *begin, size_t len, ostream *os)
const char * original_working_dir() const
GTEST_API_ void ReportInvalidTestSuiteType(const char *test_suite_name, CodeLocation code_location)
GTEST_API_ std::string AppendUserMessage(const std::string >est_msg, const Message &user_msg)
UInt32 Generate(UInt32 range)
GTEST_API_ AssertionResult CmpHelperSTREQ(const char *s1_expression, const char *s2_expression, const char *s1, const char *s2)
GTEST_API_ AssertionResult FloatLE(const char *expr1, const char *expr2, float val1, float val2)
AssertHelper(TestPartResult::Type type, const char *file, int line, const char *message)
#define GTEST_ATTRIBUTE_UNUSED_
#define GTEST_LOCK_EXCLUDED_(locks)
void PrintWideStringTo(const ::std::wstring &s, ostream *os)
std::string GetCapturedString()
#define EXPECT_TRUE(condition)
#define GTEST_ATTRIBUTE_NO_SANITIZE_ADDRESS_
#define GTEST_FLAG_SAVER_
GTEST_API_ std::string CreateUnifiedDiff(const std::vector< std::string > &left, const std::vector< std::string > &right, size_t context=2)
void swap(array< _Tp, _Nm > &lhs, array< _Tp, _Nm > &rhs) noexcept(noexcept(lhs.swap(rhs)))
FILE * FDOpen(int fd, const char *mode)
static UnitTest * GetInstance()
#define GTEST_ATTRIBUTE_NO_SANITIZE_THREAD_
char * StrDup(const char *src)
const char * StrError(int errnum)
std::string OutputFlagAlsoCheckEnvVar()
GTEST_API_ TypeId GetTestTypeId()
#define GTEST_PROJECT_URL_
std::string StripTrailingSpaces(std::string str)
std::string GetString() const
const char kPathSeparator
constexpr _Tp & get(array< _Tp, _Nm > &arr) noexcept