33#include "gtest/gtest.h"
47#include <initializer_list>
55#include <unordered_set>
58#include "gtest/gtest-assertion-result.h"
59#include "gtest/gtest-spi.h"
60#include "gtest/internal/custom/gtest.h"
81#elif GTEST_OS_WINDOWS_MOBILE
100#if GTEST_OS_WINDOWS_MINGW
113#if GTEST_HAS_EXCEPTIONS
117#if GTEST_CAN_STREAM_RESULTS_
118#include <arpa/inet.h>
120#include <sys/socket.h>
121#include <sys/types.h>
124#include "src/gtest-internal-inl.h"
127#define vsnprintf _vsnprintf
132#include <crt_externs.h>
137#include "absl/debugging/failure_signal_handler.h"
138#include "absl/debugging/stacktrace.h"
139#include "absl/debugging/symbolize.h"
140#include "absl/flags/parse.h"
141#include "absl/flags/usage.h"
142#include "absl/strings/str_cat.h"
143#include "absl/strings/str_replace.h"
148#if defined(__has_builtin)
149#define GTEST_HAS_BUILTIN(x) __has_builtin(x)
151#define GTEST_HAS_BUILTIN(x) 0
156using internal::CountIf;
157using internal::ForEach;
158using internal::GetElementOr;
159using internal::Shuffle;
165static const char kDisableTestFilter[] =
"DISABLED_*:*/DISABLED_*";
170static const char kDeathTestSuiteFilter[] =
"*DeathTest:*DeathTest/*";
173static const char kUniversalFilter[] =
"*";
176static const char kDefaultOutputFormat[] =
"xml";
178static const char kDefaultOutputFile[] =
"test_detail";
181static const char kTestShardIndex[] =
"GTEST_SHARD_INDEX";
183static const char kTestTotalShards[] =
"GTEST_TOTAL_SHARDS";
185static const char kTestShardStatusFile[] =
"GTEST_SHARD_STATUS_FILE";
191const char kStackTraceMarker[] =
"\nStack trace:\n";
195bool g_help_flag =
false;
198static FILE* OpenFileForWriting(
const std::string& output_file) {
199 FILE* fileout =
nullptr;
200 FilePath output_file_path(output_file);
201 FilePath output_dir(output_file_path.RemoveFileName());
203 if (output_dir.CreateDirectoriesRecursively()) {
204 fileout = posix::FOpen(output_file.c_str(),
"w");
206 if (fileout ==
nullptr) {
207 GTEST_LOG_(FATAL) <<
"Unable to open file \"" << output_file <<
"\"";
216static const char* GetDefaultFilter() {
217 const char*
const testbridge_test_only =
218 internal::posix::GetEnv(
"TESTBRIDGE_TEST_ONLY");
219 if (testbridge_test_only !=
nullptr) {
220 return testbridge_test_only;
222 return kUniversalFilter;
227static bool GetDefaultFailFast() {
228 const char*
const testbridge_test_runner_fail_fast =
229 internal::posix::GetEnv(
"TESTBRIDGE_TEST_RUNNER_FAIL_FAST");
230 if (testbridge_test_runner_fail_fast !=
nullptr) {
231 return strcmp(testbridge_test_runner_fail_fast,
"1") == 0;
240 testing::internal::BoolFromGTestEnv(
"fail_fast",
241 testing::GetDefaultFailFast()),
242 "True if and only if a test failure should stop further test execution.");
245 also_run_disabled_tests,
246 testing::internal::BoolFromGTestEnv(
"also_run_disabled_tests",
false),
247 "Run disabled tests too, in addition to the tests normally being run.");
251 testing::internal::BoolFromGTestEnv(
"break_on_failure",
false),
252 "True if and only if a failed assertion should be a debugger "
255GTEST_DEFINE_bool_(catch_exceptions,
256 testing::internal::BoolFromGTestEnv(
"catch_exceptions",
258 "True if and only if " GTEST_NAME_
259 " should catch exceptions and treat them as test failures.");
262 color, testing::internal::StringFromGTestEnv(
"color",
"auto"),
263 "Whether to use colors in the output. Valid values: yes, no, "
264 "and auto. 'auto' means to use colors if the output is "
265 "being sent to a terminal and the TERM environment variable "
266 "is set to a terminal type that supports colors.");
270 testing::internal::StringFromGTestEnv(
"filter",
271 testing::GetDefaultFilter()),
272 "A colon-separated list of glob (not regex) patterns "
273 "for filtering the tests to run, optionally followed by a "
274 "'-' and a : separated list of negative patterns (tests to "
275 "exclude). A test is run if it matches one of the positive "
276 "patterns and does not match any of the negative patterns.");
279 install_failure_signal_handler,
280 testing::internal::BoolFromGTestEnv(
"install_failure_signal_handler",
282 "If true and supported on the current platform, " GTEST_NAME_
284 "install a signal handler that dumps debugging information when fatal "
285 "signals are raised.");
287GTEST_DEFINE_bool_(list_tests,
false,
"List all tests without running them.");
296 testing::internal::StringFromGTestEnv(
297 "output", testing::internal::OutputFlagAlsoCheckEnvVar().c_str()),
298 "A format (defaults to \"xml\" but can be specified to be \"json\"), "
299 "optionally followed by a colon and an output file name or directory. "
300 "A directory is indicated by a trailing pathname separator. "
301 "Examples: \"xml:filename.xml\", \"xml::directoryname/\". "
302 "If a directory is specified, output files will be created "
303 "within that directory, with file-names based on the test "
304 "executable's name and, if necessary, made unique by adding "
308 brief, testing::internal::BoolFromGTestEnv(
"brief",
false),
309 "True if only test failures should be displayed in text output.");
311GTEST_DEFINE_bool_(print_time,
312 testing::internal::BoolFromGTestEnv(
"print_time",
true),
313 "True if and only if " GTEST_NAME_
314 " should display elapsed time in text output.");
316GTEST_DEFINE_bool_(print_utf8,
317 testing::internal::BoolFromGTestEnv(
"print_utf8",
true),
318 "True if and only if " GTEST_NAME_
319 " prints UTF8 characters as text.");
322 random_seed, testing::internal::Int32FromGTestEnv(
"random_seed", 0),
323 "Random number seed to use when shuffling test orders. Must be in range "
324 "[1, 99999], or 0 to use a seed based on the current time.");
327 repeat, testing::internal::Int32FromGTestEnv(
"repeat", 1),
328 "How many times to repeat each test. Specify a negative number "
329 "for repeating forever. Useful for shaking out flaky tests.");
332 recreate_environments_when_repeating,
333 testing::internal::BoolFromGTestEnv(
"recreate_environments_when_repeating",
335 "Controls whether global test environments are recreated for each repeat "
336 "of the tests. If set to false the global test environments are only set "
337 "up once, for the first iteration, and only torn down once, for the last. "
338 "Useful for shaking out flaky tests with stable, expensive test "
339 "environments. If --gtest_repeat is set to a negative number, meaning "
340 "there is no last run, the environments will always be recreated to avoid "
343GTEST_DEFINE_bool_(show_internal_stack_frames,
false,
344 "True if and only if " GTEST_NAME_
345 " should include internal stack frames when "
346 "printing test failure stack traces.");
348GTEST_DEFINE_bool_(shuffle,
349 testing::internal::BoolFromGTestEnv(
"shuffle",
false),
350 "True if and only if " GTEST_NAME_
351 " should randomize tests' order on every run.");
355 testing::internal::Int32FromGTestEnv(
"stack_trace_depth",
356 testing::kMaxStackTraceDepth),
357 "The maximum number of stack frames to print when an "
358 "assertion fails. The valid range is 0 through 100, inclusive.");
362 testing::internal::StringFromGTestEnv(
"stream_result_to",
""),
363 "This flag specifies the host name and the port number on which to stream "
364 "test results. Example: \"localhost:555\". The flag is effective only on "
369 testing::internal::BoolFromGTestEnv(
"throw_on_failure",
false),
370 "When this flag is specified, a failed assertion will throw an exception "
371 "if exceptions are enabled or exit the program with a non-zero code "
372 "otherwise. For use with an external test framework.");
374#if GTEST_USE_OWN_FLAGFILE_FLAG_
376 flagfile, testing::internal::StringFromGTestEnv(
"flagfile",
""),
377 "This flag specifies the flagfile to read command-line flags from.");
383const uint32_t Random::kMaxRange;
388uint32_t Random::Generate(uint32_t range) {
391 state_ =
static_cast<uint32_t
>(1103515245ULL * state_ + 12345U) % kMaxRange;
393 GTEST_CHECK_(range > 0) <<
"Cannot generate a number in the range [0, 0).";
394 GTEST_CHECK_(range <= kMaxRange)
395 <<
"Generation of a number in [0, " << range <<
") was requested, "
396 <<
"but this can only generate numbers in [0, " << kMaxRange <<
").";
401 return state_ % range;
407static bool GTestIsInitialized() {
return GetArgvs().size() > 0; }
412static int SumOverTestSuiteList(
const std::vector<TestSuite*>& case_list,
413 int (TestSuite::*method)()
const) {
415 for (
size_t i = 0; i < case_list.size(); i++) {
416 sum += (case_list[i]->*method)();
422static bool TestSuitePassed(
const TestSuite* test_suite) {
423 return test_suite->should_run() && test_suite->Passed();
427static bool TestSuiteFailed(
const TestSuite* test_suite) {
428 return test_suite->should_run() && test_suite->Failed();
433static bool ShouldRunTestSuite(
const TestSuite* test_suite) {
434 return test_suite->should_run();
438AssertHelper::AssertHelper(TestPartResult::Type type,
const char* file,
439 int line,
const char* message)
440 : data_(new AssertHelperData(type, file, line, message)) {}
442AssertHelper::~AssertHelper() {
delete data_; }
445void AssertHelper::operator=(
const Message& message)
const {
446 UnitTest::GetInstance()->AddTestPartResult(
447 data_->type, data_->file, data_->line,
448 AppendUserMessage(data_->message, message),
449 UnitTest::GetInstance()->impl()->CurrentOsStackTraceExceptTop(1)
461constexpr bool kErrorOnUninstantiatedParameterizedTest =
true;
462constexpr bool kErrorOnUninstantiatedTypeParameterizedTest =
true;
465class FailureTest :
public Test {
467 explicit FailureTest(
const CodeLocation& loc, std::string error_message,
470 error_message_(std::move(error_message)),
471 as_error_(as_error) {}
473 void TestBody()
override {
475 AssertHelper(TestPartResult::kNonFatalFailure, loc_.file.c_str(),
476 loc_.line,
"") = Message() << error_message_;
478 std::cout << error_message_ << std::endl;
483 const CodeLocation loc_;
484 const std::string error_message_;
485 const bool as_error_;
490std::set<std::string>* GetIgnoredParameterizedTestSuites() {
491 return UnitTest::GetInstance()->impl()->ignored_parameterized_test_suites();
495MarkAsIgnored::MarkAsIgnored(
const char* test_suite) {
496 GetIgnoredParameterizedTestSuites()->insert(test_suite);
501void InsertSyntheticTestCase(
const std::string& name, CodeLocation location,
503 const auto& ignored = *GetIgnoredParameterizedTestSuites();
504 if (ignored.find(name) != ignored.end())
return;
506 const char kMissingInstantiation[] =
507 " is defined via TEST_P, but never instantiated. None of the test cases "
508 "will run. Either no INSTANTIATE_TEST_SUITE_P is provided or the only "
509 "ones provided expand to nothing."
511 "Ideally, TEST_P definitions should only ever be included as part of "
512 "binaries that intend to use them. (As opposed to, for example, being "
513 "placed in a library that may be linked in to get other utilities.)";
515 const char kMissingTestCase[] =
516 " is instantiated via INSTANTIATE_TEST_SUITE_P, but no tests are "
517 "defined via TEST_P . No test cases will run."
519 "Ideally, INSTANTIATE_TEST_SUITE_P should only ever be invoked from "
520 "code that always depend on code that provides TEST_P. Failing to do "
521 "so is often an indication of dead code, e.g. the last TEST_P was "
522 "removed but the rest got left behind.";
524 std::string message =
525 "Parameterized test suite " + name +
526 (has_test_p ? kMissingInstantiation : kMissingTestCase) +
528 "To suppress this error for this test suite, insert the following line "
529 "(in a non-header) in the namespace it is defined in:"
531 "GTEST_ALLOW_UNINSTANTIATED_PARAMETERIZED_TEST(" +
534 std::string full_name =
"UninstantiatedParameterizedTestSuite<" + name +
">";
536 "GoogleTestVerification", full_name.c_str(),
539 location.file.c_str(), location.line, [message, location] {
540 return new FailureTest(location, message,
541 kErrorOnUninstantiatedParameterizedTest);
545void RegisterTypeParameterizedTestSuite(
const char* test_suite_name,
546 CodeLocation code_location) {
547 GetUnitTestImpl()->type_parameterized_test_registry().RegisterTestSuite(
548 test_suite_name, code_location);
551void RegisterTypeParameterizedTestSuiteInstantiation(
const char* case_name) {
552 GetUnitTestImpl()->type_parameterized_test_registry().RegisterInstantiation(
556void TypeParameterizedTestSuiteRegistry::RegisterTestSuite(
557 const char* test_suite_name, CodeLocation code_location) {
558 suites_.emplace(std::string(test_suite_name),
559 TypeParameterizedTestSuiteInfo(code_location));
562void TypeParameterizedTestSuiteRegistry::RegisterInstantiation(
563 const char* test_suite_name) {
564 auto it = suites_.find(std::string(test_suite_name));
565 if (it != suites_.end()) {
566 it->second.instantiated =
true;
568 GTEST_LOG_(ERROR) <<
"Unknown type parameterized test suit '"
569 << test_suite_name <<
"'";
573void TypeParameterizedTestSuiteRegistry::CheckForInstantiations() {
574 const auto& ignored = *GetIgnoredParameterizedTestSuites();
575 for (
const auto& testcase : suites_) {
576 if (testcase.second.instantiated)
continue;
577 if (ignored.find(testcase.first) != ignored.end())
continue;
579 std::string message =
580 "Type parameterized test suite " + testcase.first +
581 " is defined via REGISTER_TYPED_TEST_SUITE_P, but never instantiated "
582 "via INSTANTIATE_TYPED_TEST_SUITE_P. None of the test cases will run."
584 "Ideally, TYPED_TEST_P definitions should only ever be included as "
585 "part of binaries that intend to use them. (As opposed to, for "
586 "example, being placed in a library that may be linked in to get other "
589 "To suppress this error for this test suite, insert the following line "
590 "(in a non-header) in the namespace it is defined in:"
592 "GTEST_ALLOW_UNINSTANTIATED_PARAMETERIZED_TEST(" +
593 testcase.first +
");";
595 std::string full_name =
596 "UninstantiatedTypeParameterizedTestSuite<" + testcase.first +
">";
598 "GoogleTestVerification", full_name.c_str(),
601 testcase.second.code_location.file.c_str(),
602 testcase.second.code_location.line, [message, testcase] {
603 return new FailureTest(testcase.second.code_location, message,
604 kErrorOnUninstantiatedTypeParameterizedTest);
610static ::std::vector<std::string> g_argvs;
612::std::vector<std::string> GetArgvs() {
613#if defined(GTEST_CUSTOM_GET_ARGVS_)
616 const auto& custom = GTEST_CUSTOM_GET_ARGVS_();
617 return ::std::vector<std::string>(custom.begin(), custom.end());
625FilePath GetCurrentExecutableName() {
628#if GTEST_OS_WINDOWS || GTEST_OS_OS2
629 result.Set(FilePath(GetArgvs()[0]).RemoveExtension(
"exe"));
631 result.Set(FilePath(GetArgvs()[0]));
634 return result.RemoveDirectoryName();
640std::string UnitTestOptions::GetOutputFormat() {
641 std::string s = GTEST_FLAG_GET(output);
642 const char*
const gtest_output_flag = s.c_str();
643 const char*
const colon = strchr(gtest_output_flag,
':');
644 return (colon ==
nullptr)
645 ? std::string(gtest_output_flag)
646 : std::string(gtest_output_flag,
647 static_cast<size_t>(colon - gtest_output_flag));
652std::string UnitTestOptions::GetAbsolutePathToOutputFile() {
653 std::string s = GTEST_FLAG_GET(output);
654 const char*
const gtest_output_flag = s.c_str();
656 std::string format = GetOutputFormat();
657 if (format.empty()) format = std::string(kDefaultOutputFormat);
659 const char*
const colon = strchr(gtest_output_flag,
':');
660 if (colon ==
nullptr)
661 return internal::FilePath::MakeFileName(
663 UnitTest::GetInstance()->original_working_dir()),
664 internal::FilePath(kDefaultOutputFile), 0, format.c_str())
667 internal::FilePath output_name(colon + 1);
668 if (!output_name.IsAbsolutePath())
669 output_name = internal::FilePath::ConcatPaths(
670 internal::FilePath(UnitTest::GetInstance()->original_working_dir()),
671 internal::FilePath(colon + 1));
673 if (!output_name.IsDirectory())
return output_name.string();
675 internal::FilePath result(internal::FilePath::GenerateUniqueFileName(
676 output_name, internal::GetCurrentExecutableName(),
677 GetOutputFormat().c_str()));
678 return result.string();
687static bool PatternMatchesString(
const std::string& name_str,
688 const char* pattern,
const char* pattern_end) {
689 const char* name = name_str.c_str();
690 const char*
const name_begin = name;
691 const char*
const name_end = name + name_str.size();
693 const char* pattern_next = pattern;
694 const char* name_next = name;
696 while (pattern < pattern_end || name < name_end) {
697 if (pattern < pattern_end) {
700 if (name < name_end && *name == *pattern) {
707 if (name < name_end) {
717 pattern_next = pattern;
718 name_next = name + 1;
724 if (name_begin < name_next && name_next <= name_end) {
725 pattern = pattern_next;
736bool IsGlobPattern(
const std::string& pattern) {
737 return std::any_of(pattern.begin(), pattern.end(),
738 [](
const char c) { return c ==
'?' || c ==
'*'; });
741class UnitTestFilter {
743 UnitTestFilter() =
default;
746 explicit UnitTestFilter(
const std::string& filter) {
748 std::vector<std::string> all_patterns;
749 SplitString(filter,
':', &all_patterns);
750 const auto exact_match_patterns_begin = std::partition(
751 all_patterns.begin(), all_patterns.end(), &IsGlobPattern);
753 glob_patterns_.reserve(
static_cast<size_t>(
754 std::distance(all_patterns.begin(), exact_match_patterns_begin)));
755 std::move(all_patterns.begin(), exact_match_patterns_begin,
756 std::inserter(glob_patterns_, glob_patterns_.begin()));
758 exact_match_patterns_begin, all_patterns.end(),
759 std::inserter(exact_match_patterns_, exact_match_patterns_.begin()));
764 bool MatchesName(
const std::string& name)
const {
765 return exact_match_patterns_.count(name) > 0 ||
766 std::any_of(glob_patterns_.begin(), glob_patterns_.end(),
767 [&name](
const std::string& pattern) {
768 return PatternMatchesString(
769 name, pattern.c_str(),
770 pattern.c_str() + pattern.size());
775 std::vector<std::string> glob_patterns_;
776 std::unordered_set<std::string> exact_match_patterns_;
779class PositiveAndNegativeUnitTestFilter {
786 explicit PositiveAndNegativeUnitTestFilter(
const std::string& filter) {
787 std::vector<std::string> positive_and_negative_filters;
790 SplitString(filter,
'-', &positive_and_negative_filters);
791 const auto& positive_filter = positive_and_negative_filters.front();
793 if (positive_and_negative_filters.size() > 1) {
794 positive_filter_ = UnitTestFilter(
795 positive_filter.empty() ? kUniversalFilter : positive_filter);
800 auto negative_filter_string = positive_and_negative_filters[1];
801 for (std::size_t i = 2; i < positive_and_negative_filters.size(); i++)
802 negative_filter_string =
803 negative_filter_string +
'-' + positive_and_negative_filters[i];
804 negative_filter_ = UnitTestFilter(negative_filter_string);
809 positive_filter_ = UnitTestFilter(positive_filter);
816 bool MatchesTest(
const std::string& test_suite_name,
817 const std::string& test_name)
const {
818 return MatchesName(test_suite_name +
"." + test_name);
823 bool MatchesName(
const std::string& name)
const {
824 return positive_filter_.MatchesName(name) &&
825 !negative_filter_.MatchesName(name);
829 UnitTestFilter positive_filter_;
830 UnitTestFilter negative_filter_;
834bool UnitTestOptions::MatchesFilter(
const std::string& name_str,
835 const char* filter) {
836 return UnitTestFilter(filter).MatchesName(name_str);
841bool UnitTestOptions::FilterMatchesTest(
const std::string& test_suite_name,
842 const std::string& test_name) {
845 return PositiveAndNegativeUnitTestFilter(GTEST_FLAG_GET(filter))
846 .MatchesTest(test_suite_name, test_name);
853int UnitTestOptions::GTestShouldProcessSEH(DWORD exception_code) {
862 const DWORD kCxxExceptionCode = 0xe06d7363;
864 bool should_handle =
true;
866 if (!GTEST_FLAG_GET(catch_exceptions))
867 should_handle =
false;
868 else if (exception_code == EXCEPTION_BREAKPOINT)
869 should_handle =
false;
870 else if (exception_code == kCxxExceptionCode)
871 should_handle =
false;
873 return should_handle ? EXCEPTION_EXECUTE_HANDLER : EXCEPTION_CONTINUE_SEARCH;
882ScopedFakeTestPartResultReporter::ScopedFakeTestPartResultReporter(
883 TestPartResultArray* result)
884 : intercept_mode_(INTERCEPT_ONLY_CURRENT_THREAD), result_(result) {
891ScopedFakeTestPartResultReporter::ScopedFakeTestPartResultReporter(
892 InterceptMode intercept_mode, TestPartResultArray* result)
893 : intercept_mode_(intercept_mode), result_(result) {
897void ScopedFakeTestPartResultReporter::Init() {
898 internal::UnitTestImpl*
const impl = internal::GetUnitTestImpl();
899 if (intercept_mode_ == INTERCEPT_ALL_THREADS) {
900 old_reporter_ = impl->GetGlobalTestPartResultReporter();
901 impl->SetGlobalTestPartResultReporter(
this);
903 old_reporter_ = impl->GetTestPartResultReporterForCurrentThread();
904 impl->SetTestPartResultReporterForCurrentThread(
this);
910ScopedFakeTestPartResultReporter::~ScopedFakeTestPartResultReporter() {
911 internal::UnitTestImpl*
const impl = internal::GetUnitTestImpl();
912 if (intercept_mode_ == INTERCEPT_ALL_THREADS) {
913 impl->SetGlobalTestPartResultReporter(old_reporter_);
915 impl->SetTestPartResultReporterForCurrentThread(old_reporter_);
921void ScopedFakeTestPartResultReporter::ReportTestPartResult(
922 const TestPartResult& result) {
923 result_->Append(result);
937TypeId GetTestTypeId() {
return GetTypeId<Test>(); }
941extern const TypeId kTestTypeIdInGoogleTest = GetTestTypeId();
946static AssertionResult HasOneFailure(
const char* ,
949 const TestPartResultArray& results,
950 TestPartResult::Type type,
951 const std::string& substr) {
952 const std::string expected(type == TestPartResult::kFatalFailure
954 :
"1 non-fatal failure");
956 if (results.size() != 1) {
957 msg <<
"Expected: " << expected <<
"\n"
958 <<
" Actual: " << results.size() <<
" failures";
959 for (
int i = 0; i < results.size(); i++) {
960 msg <<
"\n" << results.GetTestPartResult(i);
962 return AssertionFailure() << msg;
965 const TestPartResult& r = results.GetTestPartResult(0);
966 if (r.type() != type) {
967 return AssertionFailure() <<
"Expected: " << expected <<
"\n"
972 if (strstr(r.message(), substr.c_str()) ==
nullptr) {
973 return AssertionFailure()
974 <<
"Expected: " << expected <<
" containing \"" << substr <<
"\"\n"
979 return AssertionSuccess();
985SingleFailureChecker::SingleFailureChecker(
const TestPartResultArray* results,
986 TestPartResult::Type type,
987 const std::string& substr)
988 : results_(results), type_(type), substr_(substr) {}
994SingleFailureChecker::~SingleFailureChecker() {
995 EXPECT_PRED_FORMAT3(HasOneFailure, *results_, type_, substr_);
998DefaultGlobalTestPartResultReporter::DefaultGlobalTestPartResultReporter(
999 UnitTestImpl* unit_test)
1000 : unit_test_(unit_test) {}
1002void DefaultGlobalTestPartResultReporter::ReportTestPartResult(
1003 const TestPartResult& result) {
1004 unit_test_->current_test_result()->AddTestPartResult(result);
1005 unit_test_->listeners()->repeater()->OnTestPartResult(result);
1008DefaultPerThreadTestPartResultReporter::DefaultPerThreadTestPartResultReporter(
1009 UnitTestImpl* unit_test)
1010 : unit_test_(unit_test) {}
1012void DefaultPerThreadTestPartResultReporter::ReportTestPartResult(
1013 const TestPartResult& result) {
1014 unit_test_->GetGlobalTestPartResultReporter()->ReportTestPartResult(result);
1018TestPartResultReporterInterface*
1019UnitTestImpl::GetGlobalTestPartResultReporter() {
1020 internal::MutexLock lock(&global_test_part_result_reporter_mutex_);
1021 return global_test_part_result_reporter_;
1025void UnitTestImpl::SetGlobalTestPartResultReporter(
1026 TestPartResultReporterInterface* reporter) {
1027 internal::MutexLock lock(&global_test_part_result_reporter_mutex_);
1028 global_test_part_result_reporter_ = reporter;
1032TestPartResultReporterInterface*
1033UnitTestImpl::GetTestPartResultReporterForCurrentThread() {
1034 return per_thread_test_part_result_reporter_.get();
1038void UnitTestImpl::SetTestPartResultReporterForCurrentThread(
1039 TestPartResultReporterInterface* reporter) {
1040 per_thread_test_part_result_reporter_.set(reporter);
1044int UnitTestImpl::successful_test_suite_count()
const {
1045 return CountIf(test_suites_, TestSuitePassed);
1049int UnitTestImpl::failed_test_suite_count()
const {
1050 return CountIf(test_suites_, TestSuiteFailed);
1054int UnitTestImpl::total_test_suite_count()
const {
1055 return static_cast<int>(test_suites_.size());
1060int UnitTestImpl::test_suite_to_run_count()
const {
1061 return CountIf(test_suites_, ShouldRunTestSuite);
1065int UnitTestImpl::successful_test_count()
const {
1066 return SumOverTestSuiteList(test_suites_, &TestSuite::successful_test_count);
1070int UnitTestImpl::skipped_test_count()
const {
1071 return SumOverTestSuiteList(test_suites_, &TestSuite::skipped_test_count);
1075int UnitTestImpl::failed_test_count()
const {
1076 return SumOverTestSuiteList(test_suites_, &TestSuite::failed_test_count);
1080int UnitTestImpl::reportable_disabled_test_count()
const {
1081 return SumOverTestSuiteList(test_suites_,
1082 &TestSuite::reportable_disabled_test_count);
1086int UnitTestImpl::disabled_test_count()
const {
1087 return SumOverTestSuiteList(test_suites_, &TestSuite::disabled_test_count);
1091int UnitTestImpl::reportable_test_count()
const {
1092 return SumOverTestSuiteList(test_suites_, &TestSuite::reportable_test_count);
1096int UnitTestImpl::total_test_count()
const {
1097 return SumOverTestSuiteList(test_suites_, &TestSuite::total_test_count);
1101int UnitTestImpl::test_to_run_count()
const {
1102 return SumOverTestSuiteList(test_suites_, &TestSuite::test_to_run_count);
1115std::string UnitTestImpl::CurrentOsStackTraceExceptTop(
int skip_count) {
1116 return os_stack_trace_getter()->CurrentStackTrace(
1117 static_cast<int>(GTEST_FLAG_GET(stack_trace_depth)), skip_count + 1
1126 Timer() : start_(std::chrono::steady_clock::now()) {}
1129 TimeInMillis Elapsed() {
1130 return std::chrono::duration_cast<std::chrono::milliseconds>(
1131 std::chrono::steady_clock::now() - start_)
1136 std::chrono::steady_clock::time_point start_;
1142TimeInMillis GetTimeInMillis() {
1143 return std::chrono::duration_cast<std::chrono::milliseconds>(
1144 std::chrono::system_clock::now() -
1145 std::chrono::system_clock::from_time_t(0))
1153#if GTEST_OS_WINDOWS_MOBILE
1158LPCWSTR String::AnsiToUtf16(
const char* ansi) {
1159 if (!ansi)
return nullptr;
1160 const int length = strlen(ansi);
1161 const int unicode_length =
1162 MultiByteToWideChar(CP_ACP, 0, ansi, length,
nullptr, 0);
1163 WCHAR* unicode =
new WCHAR[unicode_length + 1];
1164 MultiByteToWideChar(CP_ACP, 0, ansi, length, unicode, unicode_length);
1165 unicode[unicode_length] = 0;
1173const char* String::Utf16ToAnsi(LPCWSTR utf16_str) {
1174 if (!utf16_str)
return nullptr;
1175 const int ansi_length = WideCharToMultiByte(CP_ACP, 0, utf16_str, -1,
nullptr,
1176 0,
nullptr,
nullptr);
1177 char* ansi =
new char[ansi_length + 1];
1178 WideCharToMultiByte(CP_ACP, 0, utf16_str, -1, ansi, ansi_length,
nullptr,
1180 ansi[ansi_length] = 0;
1192bool String::CStringEquals(
const char* lhs,
const char* rhs) {
1193 if (lhs ==
nullptr)
return rhs ==
nullptr;
1195 if (rhs ==
nullptr)
return false;
1197 return strcmp(lhs, rhs) == 0;
1200#if GTEST_HAS_STD_WSTRING
1204static void StreamWideCharsToMessage(
const wchar_t* wstr,
size_t length,
1206 for (
size_t i = 0; i != length;) {
1207 if (wstr[i] != L
'\0') {
1208 *msg << WideStringToUtf8(wstr + i, static_cast<int>(length - i));
1209 while (i != length && wstr[i] != L
'\0') i++;
1219void SplitString(const ::std::string& str,
char delimiter,
1220 ::std::vector< ::std::string>* dest) {
1221 ::std::vector< ::std::string> parsed;
1222 ::std::string::size_type pos = 0;
1223 while (::testing::internal::AlwaysTrue()) {
1224 const ::std::string::size_type colon = str.find(delimiter, pos);
1225 if (colon == ::std::string::npos) {
1226 parsed.push_back(str.substr(pos));
1229 parsed.push_back(str.substr(pos, colon - pos));
1243Message::Message() : ss_(new ::std::stringstream) {
1246 *ss_ << std::setprecision(std::numeric_limits<double>::digits10 + 2);
1251Message& Message::operator<<(
const wchar_t* wide_c_str) {
1252 return *
this << internal::String::ShowWideCString(wide_c_str);
1254Message& Message::operator<<(
wchar_t* wide_c_str) {
1255 return *
this << internal::String::ShowWideCString(wide_c_str);
1258#if GTEST_HAS_STD_WSTRING
1261Message& Message::operator<<(const ::std::wstring& wstr) {
1262 internal::StreamWideCharsToMessage(wstr.c_str(), wstr.length(),
this);
1269std::string Message::GetString()
const {
1270 return internal::StringStreamToString(ss_.get());
1275namespace edit_distance {
1276std::vector<EditType> CalculateOptimalEdits(
const std::vector<size_t>& left,
1277 const std::vector<size_t>& right) {
1278 std::vector<std::vector<double> > costs(
1279 left.size() + 1, std::vector<double>(right.size() + 1));
1280 std::vector<std::vector<EditType> > best_move(
1281 left.size() + 1, std::vector<EditType>(right.size() + 1));
1284 for (
size_t l_i = 0; l_i < costs.size(); ++l_i) {
1285 costs[l_i][0] =
static_cast<double>(l_i);
1286 best_move[l_i][0] = kRemove;
1289 for (
size_t r_i = 1; r_i < costs[0].size(); ++r_i) {
1290 costs[0][r_i] =
static_cast<double>(r_i);
1291 best_move[0][r_i] = kAdd;
1294 for (
size_t l_i = 0; l_i < left.size(); ++l_i) {
1295 for (
size_t r_i = 0; r_i < right.size(); ++r_i) {
1296 if (left[l_i] == right[r_i]) {
1298 costs[l_i + 1][r_i + 1] = costs[l_i][r_i];
1299 best_move[l_i + 1][r_i + 1] = kMatch;
1303 const double add = costs[l_i + 1][r_i];
1304 const double remove = costs[l_i][r_i + 1];
1305 const double replace = costs[l_i][r_i];
1306 if (add < remove && add < replace) {
1307 costs[l_i + 1][r_i + 1] = add + 1;
1308 best_move[l_i + 1][r_i + 1] = kAdd;
1309 }
else if (remove < add && remove < replace) {
1310 costs[l_i + 1][r_i + 1] = remove + 1;
1311 best_move[l_i + 1][r_i + 1] = kRemove;
1315 costs[l_i + 1][r_i + 1] = replace + 1.00001;
1316 best_move[l_i + 1][r_i + 1] = kReplace;
1322 std::vector<EditType> best_path;
1323 for (
size_t l_i = left.size(), r_i = right.size(); l_i > 0 || r_i > 0;) {
1324 EditType move = best_move[l_i][r_i];
1325 best_path.push_back(move);
1326 l_i -= move != kAdd;
1327 r_i -= move != kRemove;
1329 std::reverse(best_path.begin(), best_path.end());
1336class InternalStrings {
1338 size_t GetId(
const std::string& str) {
1339 IdMap::iterator it = ids_.find(str);
1340 if (it != ids_.end())
return it->second;
1341 size_t id = ids_.size();
1342 return ids_[str] = id;
1346 typedef std::map<std::string, size_t> IdMap;
1352std::vector<EditType> CalculateOptimalEdits(
1353 const std::vector<std::string>& left,
1354 const std::vector<std::string>& right) {
1355 std::vector<size_t> left_ids, right_ids;
1357 InternalStrings intern_table;
1358 for (
size_t i = 0; i < left.size(); ++i) {
1359 left_ids.push_back(intern_table.GetId(left[i]));
1361 for (
size_t i = 0; i < right.size(); ++i) {
1362 right_ids.push_back(intern_table.GetId(right[i]));
1365 return CalculateOptimalEdits(left_ids, right_ids);
1376 Hunk(
size_t left_start,
size_t right_start)
1377 : left_start_(left_start),
1378 right_start_(right_start),
1383 void PushLine(
char edit,
const char* line) {
1388 hunk_.push_back(std::make_pair(
' ', line));
1392 hunk_removes_.push_back(std::make_pair(
'-', line));
1396 hunk_adds_.push_back(std::make_pair(
'+', line));
1401 void PrintTo(std::ostream* os) {
1404 for (std::list<std::pair<char, const char*> >::const_iterator it =
1406 it != hunk_.end(); ++it) {
1407 *os << it->first << it->second <<
"\n";
1411 bool has_edits()
const {
return adds_ || removes_; }
1415 hunk_.splice(hunk_.end(), hunk_removes_);
1416 hunk_.splice(hunk_.end(), hunk_adds_);
1423 void PrintHeader(std::ostream* ss)
const {
1426 *ss <<
"-" << left_start_ <<
"," << (removes_ + common_);
1428 if (removes_ && adds_) {
1432 *ss <<
"+" << right_start_ <<
"," << (adds_ + common_);
1437 size_t left_start_, right_start_;
1438 size_t adds_, removes_, common_;
1439 std::list<std::pair<char, const char*> > hunk_, hunk_adds_, hunk_removes_;
1451std::string CreateUnifiedDiff(
const std::vector<std::string>& left,
1452 const std::vector<std::string>& right,
1454 const std::vector<EditType> edits = CalculateOptimalEdits(left, right);
1456 size_t l_i = 0, r_i = 0, edit_i = 0;
1457 std::stringstream ss;
1458 while (edit_i < edits.size()) {
1460 while (edit_i < edits.size() && edits[edit_i] == kMatch) {
1467 const size_t prefix_context = std::min(l_i, context);
1468 Hunk hunk(l_i - prefix_context + 1, r_i - prefix_context + 1);
1469 for (
size_t i = prefix_context; i > 0; --i) {
1470 hunk.PushLine(
' ', left[l_i - i].c_str());
1475 size_t n_suffix = 0;
1476 for (; edit_i < edits.size(); ++edit_i) {
1477 if (n_suffix >= context) {
1479 auto it = edits.begin() +
static_cast<int>(edit_i);
1480 while (it != edits.end() && *it == kMatch) ++it;
1481 if (it == edits.end() ||
1482 static_cast<size_t>(it - edits.begin()) - edit_i >= context) {
1488 EditType edit = edits[edit_i];
1490 n_suffix = edit == kMatch ? n_suffix + 1 : 0;
1492 if (edit == kMatch || edit == kRemove || edit == kReplace) {
1493 hunk.PushLine(edit == kMatch ?
' ' :
'-', left[l_i].c_str());
1495 if (edit == kAdd || edit == kReplace) {
1496 hunk.PushLine(
'+', right[r_i].c_str());
1500 l_i += edit != kAdd;
1501 r_i += edit != kRemove;
1504 if (!hunk.has_edits()) {
1521std::vector<std::string> SplitEscapedString(
const std::string& str) {
1522 std::vector<std::string> lines;
1523 size_t start = 0, end = str.size();
1524 if (end > 2 && str[0] ==
'"' && str[end - 1] ==
'"') {
1528 bool escaped =
false;
1529 for (
size_t i = start; i + 1 < end; ++i) {
1532 if (str[i] ==
'n') {
1533 lines.push_back(str.substr(start, i - start - 1));
1537 escaped = str[i] ==
'\\';
1540 lines.push_back(str.substr(start, end - start));
1561AssertionResult EqFailure(
const char* lhs_expression,
1562 const char* rhs_expression,
1563 const std::string& lhs_value,
1564 const std::string& rhs_value,
bool ignoring_case) {
1566 msg <<
"Expected equality of these values:";
1567 msg <<
"\n " << lhs_expression;
1568 if (lhs_value != lhs_expression) {
1569 msg <<
"\n Which is: " << lhs_value;
1571 msg <<
"\n " << rhs_expression;
1572 if (rhs_value != rhs_expression) {
1573 msg <<
"\n Which is: " << rhs_value;
1576 if (ignoring_case) {
1577 msg <<
"\nIgnoring case";
1580 if (!lhs_value.empty() && !rhs_value.empty()) {
1581 const std::vector<std::string> lhs_lines = SplitEscapedString(lhs_value);
1582 const std::vector<std::string> rhs_lines = SplitEscapedString(rhs_value);
1583 if (lhs_lines.size() > 1 || rhs_lines.size() > 1) {
1584 msg <<
"\nWith diff:\n"
1585 << edit_distance::CreateUnifiedDiff(lhs_lines, rhs_lines);
1589 return AssertionFailure() << msg;
1593std::string GetBoolAssertionFailureMessage(
1594 const AssertionResult& assertion_result,
const char* expression_text,
1595 const char* actual_predicate_value,
const char* expected_predicate_value) {
1596 const char* actual_message = assertion_result.message();
1598 msg <<
"Value of: " << expression_text
1599 <<
"\n Actual: " << actual_predicate_value;
1600 if (actual_message[0] !=
'\0') msg <<
" (" << actual_message <<
")";
1601 msg <<
"\nExpected: " << expected_predicate_value;
1602 return msg.GetString();
1606AssertionResult DoubleNearPredFormat(
const char* expr1,
const char* expr2,
1607 const char* abs_error_expr,
double val1,
1608 double val2,
double abs_error) {
1609 const double diff = fabs(val1 - val2);
1610 if (diff <= abs_error)
return AssertionSuccess();
1613 const double min_abs = std::min(fabs(val1), fabs(val2));
1615 const double epsilon =
1616 nextafter(min_abs, std::numeric_limits<double>::infinity()) - min_abs;
1623 if (!(std::isnan)(val1) && !(std::isnan)(val2) && abs_error > 0 &&
1624 abs_error < epsilon) {
1625 return AssertionFailure()
1626 <<
"The difference between " << expr1 <<
" and " << expr2 <<
" is "
1627 << diff <<
", where\n"
1628 << expr1 <<
" evaluates to " << val1 <<
",\n"
1629 << expr2 <<
" evaluates to " << val2 <<
".\nThe abs_error parameter "
1630 << abs_error_expr <<
" evaluates to " << abs_error
1631 <<
" which is smaller than the minimum distance between doubles for "
1632 "numbers of this magnitude which is "
1634 <<
", thus making this EXPECT_NEAR check equivalent to "
1635 "EXPECT_EQUAL. Consider using EXPECT_DOUBLE_EQ instead.";
1637 return AssertionFailure()
1638 <<
"The difference between " << expr1 <<
" and " << expr2 <<
" is "
1639 << diff <<
", which exceeds " << abs_error_expr <<
", where\n"
1640 << expr1 <<
" evaluates to " << val1 <<
",\n"
1641 << expr2 <<
" evaluates to " << val2 <<
", and\n"
1642 << abs_error_expr <<
" evaluates to " << abs_error <<
".";
1646template <
typename RawType>
1647AssertionResult FloatingPointLE(
const char* expr1,
const char* expr2,
1648 RawType val1, RawType val2) {
1651 return AssertionSuccess();
1655 const FloatingPoint<RawType> lhs(val1), rhs(val2);
1656 if (lhs.AlmostEquals(rhs)) {
1657 return AssertionSuccess();
1664 ::std::stringstream val1_ss;
1665 val1_ss << std::setprecision(std::numeric_limits<RawType>::digits10 + 2)
1668 ::std::stringstream val2_ss;
1669 val2_ss << std::setprecision(std::numeric_limits<RawType>::digits10 + 2)
1672 return AssertionFailure()
1673 <<
"Expected: (" << expr1 <<
") <= (" << expr2 <<
")\n"
1674 <<
" Actual: " << StringStreamToString(&val1_ss) <<
" vs "
1675 << StringStreamToString(&val2_ss);
1682AssertionResult FloatLE(
const char* expr1,
const char* expr2,
float val1,
1684 return internal::FloatingPointLE<float>(expr1, expr2, val1, val2);
1689AssertionResult DoubleLE(
const char* expr1,
const char* expr2,
double val1,
1691 return internal::FloatingPointLE<double>(expr1, expr2, val1, val2);
1697AssertionResult CmpHelperSTREQ(
const char* lhs_expression,
1698 const char* rhs_expression,
const char* lhs,
1700 if (String::CStringEquals(lhs, rhs)) {
1701 return AssertionSuccess();
1704 return EqFailure(lhs_expression, rhs_expression, PrintToString(lhs),
1705 PrintToString(rhs),
false);
1709AssertionResult CmpHelperSTRCASEEQ(
const char* lhs_expression,
1710 const char* rhs_expression,
const char* lhs,
1712 if (String::CaseInsensitiveCStringEquals(lhs, rhs)) {
1713 return AssertionSuccess();
1716 return EqFailure(lhs_expression, rhs_expression, PrintToString(lhs),
1717 PrintToString(rhs),
true);
1721AssertionResult CmpHelperSTRNE(
const char* s1_expression,
1722 const char* s2_expression,
const char* s1,
1724 if (!String::CStringEquals(s1, s2)) {
1725 return AssertionSuccess();
1727 return AssertionFailure()
1728 <<
"Expected: (" << s1_expression <<
") != (" << s2_expression
1729 <<
"), actual: \"" << s1 <<
"\" vs \"" << s2 <<
"\"";
1734AssertionResult CmpHelperSTRCASENE(
const char* s1_expression,
1735 const char* s2_expression,
const char* s1,
1737 if (!String::CaseInsensitiveCStringEquals(s1, s2)) {
1738 return AssertionSuccess();
1740 return AssertionFailure()
1741 <<
"Expected: (" << s1_expression <<
") != (" << s2_expression
1742 <<
") (ignoring case), actual: \"" << s1 <<
"\" vs \"" << s2 <<
"\"";
1756bool IsSubstringPred(
const char* needle,
const char* haystack) {
1757 if (needle ==
nullptr || haystack ==
nullptr)
return needle == haystack;
1759 return strstr(haystack, needle) !=
nullptr;
1762bool IsSubstringPred(
const wchar_t* needle,
const wchar_t* haystack) {
1763 if (needle ==
nullptr || haystack ==
nullptr)
return needle == haystack;
1765 return wcsstr(haystack, needle) !=
nullptr;
1769template <
typename StringType>
1770bool IsSubstringPred(
const StringType& needle,
const StringType& haystack) {
1771 return haystack.find(needle) != StringType::npos;
1778template <
typename StringType>
1779AssertionResult IsSubstringImpl(
bool expected_to_be_substring,
1780 const char* needle_expr,
1781 const char* haystack_expr,
1782 const StringType& needle,
1783 const StringType& haystack) {
1784 if (IsSubstringPred(needle, haystack) == expected_to_be_substring)
1785 return AssertionSuccess();
1787 const bool is_wide_string =
sizeof(needle[0]) > 1;
1788 const char*
const begin_string_quote = is_wide_string ?
"L\"" :
"\"";
1789 return AssertionFailure()
1790 <<
"Value of: " << needle_expr <<
"\n"
1791 <<
" Actual: " << begin_string_quote << needle <<
"\"\n"
1792 <<
"Expected: " << (expected_to_be_substring ?
"" :
"not ")
1793 <<
"a substring of " << haystack_expr <<
"\n"
1794 <<
"Which is: " << begin_string_quote << haystack <<
"\"";
1803AssertionResult IsSubstring(
const char* needle_expr,
const char* haystack_expr,
1804 const char* needle,
const char* haystack) {
1805 return IsSubstringImpl(
true, needle_expr, haystack_expr, needle, haystack);
1808AssertionResult IsSubstring(
const char* needle_expr,
const char* haystack_expr,
1809 const wchar_t* needle,
const wchar_t* haystack) {
1810 return IsSubstringImpl(
true, needle_expr, haystack_expr, needle, haystack);
1813AssertionResult IsNotSubstring(
const char* needle_expr,
1814 const char* haystack_expr,
const char* needle,
1815 const char* haystack) {
1816 return IsSubstringImpl(
false, needle_expr, haystack_expr, needle, haystack);
1819AssertionResult IsNotSubstring(
const char* needle_expr,
1820 const char* haystack_expr,
const wchar_t* needle,
1821 const wchar_t* haystack) {
1822 return IsSubstringImpl(
false, needle_expr, haystack_expr, needle, haystack);
1825AssertionResult IsSubstring(
const char* needle_expr,
const char* haystack_expr,
1826 const ::std::string& needle,
1827 const ::std::string& haystack) {
1828 return IsSubstringImpl(
true, needle_expr, haystack_expr, needle, haystack);
1831AssertionResult IsNotSubstring(
const char* needle_expr,
1832 const char* haystack_expr,
1833 const ::std::string& needle,
1834 const ::std::string& haystack) {
1835 return IsSubstringImpl(
false, needle_expr, haystack_expr, needle, haystack);
1838#if GTEST_HAS_STD_WSTRING
1839AssertionResult IsSubstring(
const char* needle_expr,
const char* haystack_expr,
1840 const ::std::wstring& needle,
1841 const ::std::wstring& haystack) {
1842 return IsSubstringImpl(
true, needle_expr, haystack_expr, needle, haystack);
1845AssertionResult IsNotSubstring(
const char* needle_expr,
1846 const char* haystack_expr,
1847 const ::std::wstring& needle,
1848 const ::std::wstring& haystack) {
1849 return IsSubstringImpl(
false, needle_expr, haystack_expr, needle, haystack);
1860AssertionResult HRESULTFailureHelper(
const char* expr,
const char* expected,
1862#if GTEST_OS_WINDOWS_MOBILE || GTEST_OS_WINDOWS_TV_TITLE
1865 const char error_text[] =
"";
1872 const DWORD kFlags =
1873 FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS;
1874 const DWORD kBufSize = 4096;
1876 char error_text[kBufSize] = {
'\0'};
1877 DWORD message_length = ::FormatMessageA(kFlags,
1879 static_cast<DWORD
>(hr),
1885 for (; message_length && IsSpace(error_text[message_length - 1]);
1887 error_text[message_length - 1] =
'\0';
1892 const std::string error_hex(
"0x" + String::FormatHexInt(hr));
1893 return ::testing::AssertionFailure()
1894 <<
"Expected: " << expr <<
" " << expected <<
".\n"
1895 <<
" Actual: " << error_hex <<
" " << error_text <<
"\n";
1900AssertionResult IsHRESULTSuccess(
const char* expr,
long hr) {
1901 if (SUCCEEDED(hr)) {
1902 return AssertionSuccess();
1904 return HRESULTFailureHelper(expr,
"succeeds", hr);
1907AssertionResult IsHRESULTFailure(
const char* expr,
long hr) {
1909 return AssertionSuccess();
1911 return HRESULTFailureHelper(expr,
"fails", hr);
1929constexpr uint32_t kMaxCodePoint1 = (
static_cast<uint32_t
>(1) << 7) - 1;
1932constexpr uint32_t kMaxCodePoint2 = (
static_cast<uint32_t
>(1) << (5 + 6)) - 1;
1935constexpr uint32_t kMaxCodePoint3 =
1936 (
static_cast<uint32_t
>(1) << (4 + 2 * 6)) - 1;
1939constexpr uint32_t kMaxCodePoint4 =
1940 (
static_cast<uint32_t
>(1) << (3 + 3 * 6)) - 1;
1945inline uint32_t ChopLowBits(uint32_t* bits,
int n) {
1946 const uint32_t low_bits = *bits & ((
static_cast<uint32_t
>(1) << n) - 1);
1957std::string CodePointToUtf8(uint32_t code_point) {
1958 if (code_point > kMaxCodePoint4) {
1959 return "(Invalid Unicode 0x" + String::FormatHexUInt32(code_point) +
")";
1963 if (code_point <= kMaxCodePoint1) {
1965 str[0] =
static_cast<char>(code_point);
1966 }
else if (code_point <= kMaxCodePoint2) {
1968 str[1] =
static_cast<char>(0x80 | ChopLowBits(&code_point, 6));
1969 str[0] =
static_cast<char>(0xC0 | code_point);
1970 }
else if (code_point <= kMaxCodePoint3) {
1972 str[2] =
static_cast<char>(0x80 | ChopLowBits(&code_point, 6));
1973 str[1] =
static_cast<char>(0x80 | ChopLowBits(&code_point, 6));
1974 str[0] =
static_cast<char>(0xE0 | code_point);
1977 str[3] =
static_cast<char>(0x80 | ChopLowBits(&code_point, 6));
1978 str[2] =
static_cast<char>(0x80 | ChopLowBits(&code_point, 6));
1979 str[1] =
static_cast<char>(0x80 | ChopLowBits(&code_point, 6));
1980 str[0] =
static_cast<char>(0xF0 | code_point);
1992inline bool IsUtf16SurrogatePair(
wchar_t first,
wchar_t second) {
1993 return sizeof(wchar_t) == 2 && (first & 0xFC00) == 0xD800 &&
1994 (second & 0xFC00) == 0xDC00;
1998inline uint32_t CreateCodePointFromUtf16SurrogatePair(
wchar_t first,
2000 const auto first_u =
static_cast<uint32_t
>(first);
2001 const auto second_u =
static_cast<uint32_t
>(second);
2002 const uint32_t mask = (1 << 10) - 1;
2003 return (
sizeof(
wchar_t) == 2)
2004 ? (((first_u & mask) << 10) | (second_u & mask)) + 0x10000
2024std::string WideStringToUtf8(
const wchar_t* str,
int num_chars) {
2025 if (num_chars == -1) num_chars =
static_cast<int>(wcslen(str));
2027 ::std::stringstream stream;
2028 for (
int i = 0; i < num_chars; ++i) {
2029 uint32_t unicode_code_point;
2031 if (str[i] == L
'\0') {
2033 }
else if (i + 1 < num_chars && IsUtf16SurrogatePair(str[i], str[i + 1])) {
2034 unicode_code_point =
2035 CreateCodePointFromUtf16SurrogatePair(str[i], str[i + 1]);
2038 unicode_code_point =
static_cast<uint32_t
>(str[i]);
2041 stream << CodePointToUtf8(unicode_code_point);
2043 return StringStreamToString(&stream);
2048std::string String::ShowWideCString(
const wchar_t* wide_c_str) {
2049 if (wide_c_str ==
nullptr)
return "(null)";
2051 return internal::WideStringToUtf8(wide_c_str, -1);
2060bool String::WideCStringEquals(
const wchar_t* lhs,
const wchar_t* rhs) {
2061 if (lhs ==
nullptr)
return rhs ==
nullptr;
2063 if (rhs ==
nullptr)
return false;
2065 return wcscmp(lhs, rhs) == 0;
2069AssertionResult CmpHelperSTREQ(
const char* lhs_expression,
2070 const char* rhs_expression,
const wchar_t* lhs,
2071 const wchar_t* rhs) {
2072 if (String::WideCStringEquals(lhs, rhs)) {
2073 return AssertionSuccess();
2076 return EqFailure(lhs_expression, rhs_expression, PrintToString(lhs),
2077 PrintToString(rhs),
false);
2081AssertionResult CmpHelperSTRNE(
const char* s1_expression,
2082 const char* s2_expression,
const wchar_t* s1,
2083 const wchar_t* s2) {
2084 if (!String::WideCStringEquals(s1, s2)) {
2085 return AssertionSuccess();
2088 return AssertionFailure()
2089 <<
"Expected: (" << s1_expression <<
") != (" << s2_expression
2090 <<
"), actual: " << PrintToString(s1) <<
" vs " << PrintToString(s2);
2099bool String::CaseInsensitiveCStringEquals(
const char* lhs,
const char* rhs) {
2100 if (lhs ==
nullptr)
return rhs ==
nullptr;
2101 if (rhs ==
nullptr)
return false;
2102 return posix::StrCaseCmp(lhs, rhs) == 0;
2117bool String::CaseInsensitiveWideCStringEquals(
const wchar_t* lhs,
2118 const wchar_t* rhs) {
2119 if (lhs ==
nullptr)
return rhs ==
nullptr;
2121 if (rhs ==
nullptr)
return false;
2124 return _wcsicmp(lhs, rhs) == 0;
2125#elif GTEST_OS_LINUX && !GTEST_OS_LINUX_ANDROID
2126 return wcscasecmp(lhs, rhs) == 0;
2132 left = towlower(
static_cast<wint_t
>(*lhs++));
2133 right = towlower(
static_cast<wint_t
>(*rhs++));
2134 }
while (left && left == right);
2135 return left == right;
2141bool String::EndsWithCaseInsensitive(
const std::string& str,
2142 const std::string& suffix) {
2143 const size_t str_len = str.length();
2144 const size_t suffix_len = suffix.length();
2145 return (str_len >= suffix_len) &&
2146 CaseInsensitiveCStringEquals(str.c_str() + str_len - suffix_len,
2151std::string String::FormatIntWidth2(
int value) {
2152 return FormatIntWidthN(value, 2);
2156std::string String::FormatIntWidthN(
int value,
int width) {
2157 std::stringstream ss;
2158 ss << std::setfill(
'0') << std::setw(width) << value;
2163std::string String::FormatHexUInt32(uint32_t value) {
2164 std::stringstream ss;
2165 ss << std::hex << std::uppercase << value;
2170std::string String::FormatHexInt(
int value) {
2171 return FormatHexUInt32(
static_cast<uint32_t
>(value));
2175std::string String::FormatByte(
unsigned char value) {
2176 std::stringstream ss;
2177 ss << std::setfill(
'0') << std::setw(2) << std::hex << std::uppercase
2178 <<
static_cast<unsigned int>(value);
2184std::string StringStreamToString(::std::stringstream* ss) {
2185 const ::std::string& str = ss->str();
2186 const char*
const start = str.c_str();
2187 const char*
const end = start + str.length();
2190 result.reserve(
static_cast<size_t>(2 * (end - start)));
2191 for (
const char* ch = start; ch != end; ++ch) {
2203std::string AppendUserMessage(
const std::string& gtest_msg,
2204 const Message& user_msg) {
2206 const std::string user_msg_string = user_msg.GetString();
2207 if (user_msg_string.empty()) {
2210 if (gtest_msg.empty()) {
2211 return user_msg_string;
2213 return gtest_msg +
"\n" + user_msg_string;
2221TestResult::TestResult()
2222 : death_test_count_(0), start_timestamp_(0), elapsed_time_(0) {}
2225TestResult::~TestResult() {}
2230const TestPartResult& TestResult::GetTestPartResult(
int i)
const {
2231 if (i < 0 || i >= total_part_count()) internal::posix::Abort();
2232 return test_part_results_.at(
static_cast<size_t>(i));
2238const TestProperty& TestResult::GetTestProperty(
int i)
const {
2239 if (i < 0 || i >= test_property_count()) internal::posix::Abort();
2240 return test_properties_.at(
static_cast<size_t>(i));
2244void TestResult::ClearTestPartResults() { test_part_results_.clear(); }
2247void TestResult::AddTestPartResult(
const TestPartResult& test_part_result) {
2248 test_part_results_.push_back(test_part_result);
2254void TestResult::RecordProperty(
const std::string& xml_element,
2255 const TestProperty& test_property) {
2256 if (!ValidateTestProperty(xml_element, test_property)) {
2259 internal::MutexLock lock(&test_properties_mutex_);
2260 const std::vector<TestProperty>::iterator property_with_matching_key =
2261 std::find_if(test_properties_.begin(), test_properties_.end(),
2262 internal::TestPropertyKeyIs(test_property.key()));
2263 if (property_with_matching_key == test_properties_.end()) {
2264 test_properties_.push_back(test_property);
2267 property_with_matching_key->SetValue(test_property.value());
2272static const char*
const kReservedTestSuitesAttributes[] = {
2273 "disabled",
"errors",
"failures",
"name",
2274 "random_seed",
"tests",
"time",
"timestamp"};
2278static const char*
const kReservedTestSuiteAttributes[] = {
2279 "disabled",
"errors",
"failures",
"name",
2280 "tests",
"time",
"timestamp",
"skipped"};
2283static const char*
const kReservedTestCaseAttributes[] = {
2284 "classname",
"name",
"status",
"time",
2285 "type_param",
"value_param",
"file",
"line"};
2289static const char*
const kReservedOutputTestCaseAttributes[] = {
2290 "classname",
"name",
"status",
"time",
"type_param",
2291 "value_param",
"file",
"line",
"result",
"timestamp"};
2293template <
size_t kSize>
2294std::vector<std::string> ArrayAsVector(
const char*
const (&array)[kSize]) {
2295 return std::vector<std::string>(array, array + kSize);
2298static std::vector<std::string> GetReservedAttributesForElement(
2299 const std::string& xml_element) {
2300 if (xml_element ==
"testsuites") {
2301 return ArrayAsVector(kReservedTestSuitesAttributes);
2302 }
else if (xml_element ==
"testsuite") {
2303 return ArrayAsVector(kReservedTestSuiteAttributes);
2304 }
else if (xml_element ==
"testcase") {
2305 return ArrayAsVector(kReservedTestCaseAttributes);
2307 GTEST_CHECK_(
false) <<
"Unrecognized xml_element provided: " << xml_element;
2310 return std::vector<std::string>();
2314static std::vector<std::string> GetReservedOutputAttributesForElement(
2315 const std::string& xml_element) {
2316 if (xml_element ==
"testsuites") {
2317 return ArrayAsVector(kReservedTestSuitesAttributes);
2318 }
else if (xml_element ==
"testsuite") {
2319 return ArrayAsVector(kReservedTestSuiteAttributes);
2320 }
else if (xml_element ==
"testcase") {
2321 return ArrayAsVector(kReservedOutputTestCaseAttributes);
2323 GTEST_CHECK_(
false) <<
"Unrecognized xml_element provided: " << xml_element;
2326 return std::vector<std::string>();
2329static std::string FormatWordList(
const std::vector<std::string>& words) {
2331 for (
size_t i = 0; i < words.size(); ++i) {
2332 if (i > 0 && words.size() > 2) {
2335 if (i == words.size() - 1) {
2336 word_list <<
"and ";
2338 word_list <<
"'" << words[i] <<
"'";
2340 return word_list.GetString();
2343static bool ValidateTestPropertyName(
2344 const std::string& property_name,
2345 const std::vector<std::string>& reserved_names) {
2346 if (std::find(reserved_names.begin(), reserved_names.end(), property_name) !=
2347 reserved_names.end()) {
2348 ADD_FAILURE() <<
"Reserved key used in RecordProperty(): " << property_name
2349 <<
" (" << FormatWordList(reserved_names)
2350 <<
" are reserved by " << GTEST_NAME_ <<
")";
2358bool TestResult::ValidateTestProperty(
const std::string& xml_element,
2359 const TestProperty& test_property) {
2360 return ValidateTestPropertyName(test_property.key(),
2361 GetReservedAttributesForElement(xml_element));
2365void TestResult::Clear() {
2366 test_part_results_.clear();
2367 test_properties_.clear();
2368 death_test_count_ = 0;
2373static bool TestPartSkipped(
const TestPartResult& result) {
2374 return result.skipped();
2378bool TestResult::Skipped()
const {
2379 return !Failed() && CountIf(test_part_results_, TestPartSkipped) > 0;
2383bool TestResult::Failed()
const {
2384 for (
int i = 0; i < total_part_count(); ++i) {
2385 if (GetTestPartResult(i).failed())
return true;
2391static bool TestPartFatallyFailed(
const TestPartResult& result) {
2392 return result.fatally_failed();
2396bool TestResult::HasFatalFailure()
const {
2397 return CountIf(test_part_results_, TestPartFatallyFailed) > 0;
2401static bool TestPartNonfatallyFailed(
const TestPartResult& result) {
2402 return result.nonfatally_failed();
2406bool TestResult::HasNonfatalFailure()
const {
2407 return CountIf(test_part_results_, TestPartNonfatallyFailed) > 0;
2412int TestResult::total_part_count()
const {
2413 return static_cast<int>(test_part_results_.size());
2417int TestResult::test_property_count()
const {
2418 return static_cast<int>(test_properties_.size());
2426Test::Test() : gtest_flag_saver_(new GTEST_FLAG_SAVER_) {}
2436void Test::SetUp() {}
2441void Test::TearDown() {}
2444void Test::RecordProperty(
const std::string& key,
const std::string& value) {
2445 UnitTest::GetInstance()->RecordProperty(key, value);
2449void Test::RecordProperty(
const std::string& key,
int value) {
2450 Message value_message;
2451 value_message << value;
2452 RecordProperty(key, value_message.GetString().c_str());
2457void ReportFailureInUnknownLocation(TestPartResult::Type result_type,
2458 const std::string& message) {
2461 UnitTest::GetInstance()->AddTestPartResult(
2476bool Test::HasSameFixtureClass() {
2477 internal::UnitTestImpl*
const impl = internal::GetUnitTestImpl();
2478 const TestSuite*
const test_suite = impl->current_test_suite();
2481 const TestInfo*
const first_test_info = test_suite->test_info_list()[0];
2482 const internal::TypeId first_fixture_id = first_test_info->fixture_class_id_;
2483 const char*
const first_test_name = first_test_info->name();
2486 const TestInfo*
const this_test_info = impl->current_test_info();
2487 const internal::TypeId this_fixture_id = this_test_info->fixture_class_id_;
2488 const char*
const this_test_name = this_test_info->name();
2490 if (this_fixture_id != first_fixture_id) {
2492 const bool first_is_TEST = first_fixture_id == internal::GetTestTypeId();
2494 const bool this_is_TEST = this_fixture_id == internal::GetTestTypeId();
2496 if (first_is_TEST || this_is_TEST) {
2503 const char*
const TEST_name =
2504 first_is_TEST ? first_test_name : this_test_name;
2505 const char*
const TEST_F_name =
2506 first_is_TEST ? this_test_name : first_test_name;
2509 <<
"All tests in the same test suite must use the same test fixture\n"
2510 <<
"class, so mixing TEST_F and TEST in the same test suite is\n"
2511 <<
"illegal. In test suite " << this_test_info->test_suite_name()
2513 <<
"test " << TEST_F_name <<
" is defined using TEST_F but\n"
2514 <<
"test " << TEST_name <<
" is defined using TEST. You probably\n"
2515 <<
"want to change the TEST to TEST_F or move it to another test\n"
2521 <<
"All tests in the same test suite must use the same test fixture\n"
2522 <<
"class. However, in test suite "
2523 << this_test_info->test_suite_name() <<
",\n"
2524 <<
"you defined test " << first_test_name <<
" and test "
2525 << this_test_name <<
"\n"
2526 <<
"using two different test fixture classes. This can happen if\n"
2527 <<
"the two classes are from different namespaces or translation\n"
2528 <<
"units and have the same name. You should probably rename one\n"
2529 <<
"of the classes to put the tests into different test suites.";
2543static std::string* FormatSehExceptionMessage(DWORD exception_code,
2544 const char* location) {
2546 message <<
"SEH exception with code 0x" << std::setbase(16) << exception_code
2547 << std::setbase(10) <<
" thrown in " << location <<
".";
2549 return new std::string(message.GetString());
2556#if GTEST_HAS_EXCEPTIONS
2559static std::string FormatCxxExceptionMessage(
const char* description,
2560 const char* location) {
2562 if (description !=
nullptr) {
2563 message <<
"C++ exception with description \"" << description <<
"\"";
2565 message <<
"Unknown C++ exception";
2567 message <<
" thrown in " << location <<
".";
2569 return message.GetString();
2572static std::string PrintTestPartResultToString(
2573 const TestPartResult& test_part_result);
2575GoogleTestFailureException::GoogleTestFailureException(
2576 const TestPartResult& failure)
2577 : ::std::runtime_error(PrintTestPartResultToString(failure).c_str()) {}
2589template <
class T,
typename Result>
2590Result HandleSehExceptionsInMethodIfSupported(T*
object, Result (T::*method)(),
2591 const char* location) {
2594 return (object->*method)();
2595 } __except (internal::UnitTestOptions::GTestShouldProcessSEH(
2596 GetExceptionCode())) {
2600 std::string* exception_message =
2601 FormatSehExceptionMessage(GetExceptionCode(), location);
2602 internal::ReportFailureInUnknownLocation(TestPartResult::kFatalFailure,
2603 *exception_message);
2604 delete exception_message;
2605 return static_cast<Result
>(0);
2609 return (object->*method)();
2616template <
class T,
typename Result>
2617Result HandleExceptionsInMethodIfSupported(T*
object, Result (T::*method)(),
2618 const char* location) {
2642 if (internal::GetUnitTestImpl()->catch_exceptions()) {
2643#if GTEST_HAS_EXCEPTIONS
2645 return HandleSehExceptionsInMethodIfSupported(
object, method, location);
2646 }
catch (
const AssertionException&) {
2648 }
catch (
const internal::GoogleTestFailureException&) {
2653 }
catch (
const std::exception& e) {
2654 internal::ReportFailureInUnknownLocation(
2655 TestPartResult::kFatalFailure,
2656 FormatCxxExceptionMessage(e.what(), location));
2658 internal::ReportFailureInUnknownLocation(
2659 TestPartResult::kFatalFailure,
2660 FormatCxxExceptionMessage(
nullptr, location));
2662 return static_cast<Result
>(0);
2664 return HandleSehExceptionsInMethodIfSupported(
object, method, location);
2667 return (object->*method)();
2675 if (!HasSameFixtureClass())
return;
2677 internal::UnitTestImpl*
const impl = internal::GetUnitTestImpl();
2678 impl->os_stack_trace_getter()->UponLeavingGTest();
2679 internal::HandleExceptionsInMethodIfSupported(
this, &Test::SetUp,
"SetUp()");
2682 if (!HasFatalFailure() && !IsSkipped()) {
2683 impl->os_stack_trace_getter()->UponLeavingGTest();
2684 internal::HandleExceptionsInMethodIfSupported(
this, &Test::TestBody,
2691 impl->os_stack_trace_getter()->UponLeavingGTest();
2692 internal::HandleExceptionsInMethodIfSupported(
this, &Test::TearDown,
2697bool Test::HasFatalFailure() {
2698 return internal::GetUnitTestImpl()->current_test_result()->HasFatalFailure();
2702bool Test::HasNonfatalFailure() {
2703 return internal::GetUnitTestImpl()
2704 ->current_test_result()
2705 ->HasNonfatalFailure();
2709bool Test::IsSkipped() {
2710 return internal::GetUnitTestImpl()->current_test_result()->Skipped();
2717TestInfo::TestInfo(
const std::string& a_test_suite_name,
2718 const std::string& a_name,
const char* a_type_param,
2719 const char* a_value_param,
2720 internal::CodeLocation a_code_location,
2721 internal::TypeId fixture_class_id,
2722 internal::TestFactoryBase* factory)
2723 : test_suite_name_(a_test_suite_name),
2725 name_(a_name.begin(), a_name.end()),
2726 type_param_(a_type_param ? new std::string(a_type_param) : nullptr),
2727 value_param_(a_value_param ? new std::string(a_value_param) : nullptr),
2728 location_(a_code_location),
2729 fixture_class_id_(fixture_class_id),
2731 is_disabled_(false),
2732 matches_filter_(false),
2733 is_in_another_shard_(false),
2738TestInfo::~TestInfo() {
delete factory_; }
2760TestInfo* MakeAndRegisterTestInfo(
2761 const char* test_suite_name,
const char* name,
const char* type_param,
2762 const char* value_param, CodeLocation code_location,
2763 TypeId fixture_class_id, SetUpTestSuiteFunc set_up_tc,
2764 TearDownTestSuiteFunc tear_down_tc, TestFactoryBase* factory) {
2765 TestInfo*
const test_info =
2766 new TestInfo(test_suite_name, name, type_param, value_param,
2767 code_location, fixture_class_id, factory);
2768 GetUnitTestImpl()->AddTestInfo(set_up_tc, tear_down_tc, test_info);
2772void ReportInvalidTestSuiteType(
const char* test_suite_name,
2773 CodeLocation code_location) {
2776 <<
"Attempted redefinition of test suite " << test_suite_name <<
".\n"
2777 <<
"All tests in the same test suite must use the same test fixture\n"
2778 <<
"class. However, in test suite " << test_suite_name <<
", you tried\n"
2779 <<
"to define a test using a fixture class different from the one\n"
2780 <<
"used earlier. This can happen if the two fixture classes are\n"
2781 <<
"from different namespaces and have the same name. You should\n"
2782 <<
"probably rename one of the classes to put the tests into different\n"
2785 GTEST_LOG_(ERROR) << FormatFileLocation(code_location.file.c_str(),
2787 <<
" " << errors.GetString();
2806 explicit TestNameIs(
const char* name) : name_(name) {}
2809 bool operator()(
const TestInfo* test_info)
const {
2810 return test_info && test_info->name() == name_;
2824void UnitTestImpl::RegisterParameterizedTests() {
2825 if (!parameterized_tests_registered_) {
2826 parameterized_test_registry_.RegisterTests();
2827 type_parameterized_test_registry_.CheckForInstantiations();
2828 parameterized_tests_registered_ =
true;
2836void TestInfo::Run() {
2837 TestEventListener* repeater = UnitTest::GetInstance()->listeners().repeater();
2839 if (is_disabled_ && matches_filter_) repeater->OnTestDisabled(*
this);
2844 internal::UnitTestImpl*
const impl = internal::GetUnitTestImpl();
2845 impl->set_current_test_info(
this);
2848 repeater->OnTestStart(*
this);
2849 result_.set_start_timestamp(internal::GetTimeInMillis());
2850 internal::Timer timer;
2851 impl->os_stack_trace_getter()->UponLeavingGTest();
2854 Test*
const test = internal::HandleExceptionsInMethodIfSupported(
2855 factory_, &internal::TestFactoryBase::CreateTest,
2856 "the test fixture's constructor");
2861 if (!Test::HasFatalFailure() && !Test::IsSkipped()) {
2867 if (test !=
nullptr) {
2869 impl->os_stack_trace_getter()->UponLeavingGTest();
2870 internal::HandleExceptionsInMethodIfSupported(
2871 test, &Test::DeleteSelf_,
"the test fixture's destructor");
2874 result_.set_elapsed_time(timer.Elapsed());
2877 repeater->OnTestEnd(*
this);
2881 impl->set_current_test_info(
nullptr);
2885void TestInfo::Skip() {
2886 if (!should_run_)
return;
2888 internal::UnitTestImpl*
const impl = internal::GetUnitTestImpl();
2889 impl->set_current_test_info(
this);
2891 TestEventListener* repeater = UnitTest::GetInstance()->listeners().repeater();
2894 repeater->OnTestStart(*
this);
2896 const TestPartResult test_part_result =
2897 TestPartResult(TestPartResult::kSkip, this->file(), this->line(),
"");
2898 impl->GetTestPartResultReporterForCurrentThread()->ReportTestPartResult(
2902 repeater->OnTestEnd(*
this);
2903 impl->set_current_test_info(
nullptr);
2909int TestSuite::successful_test_count()
const {
2910 return CountIf(test_info_list_, TestPassed);
2914int TestSuite::skipped_test_count()
const {
2915 return CountIf(test_info_list_, TestSkipped);
2919int TestSuite::failed_test_count()
const {
2920 return CountIf(test_info_list_, TestFailed);
2924int TestSuite::reportable_disabled_test_count()
const {
2925 return CountIf(test_info_list_, TestReportableDisabled);
2929int TestSuite::disabled_test_count()
const {
2930 return CountIf(test_info_list_, TestDisabled);
2934int TestSuite::reportable_test_count()
const {
2935 return CountIf(test_info_list_, TestReportable);
2939int TestSuite::test_to_run_count()
const {
2940 return CountIf(test_info_list_, ShouldRunTest);
2944int TestSuite::total_test_count()
const {
2945 return static_cast<int>(test_info_list_.size());
2957TestSuite::TestSuite(
const char* a_name,
const char* a_type_param,
2958 internal::SetUpTestSuiteFunc set_up_tc,
2959 internal::TearDownTestSuiteFunc tear_down_tc)
2961 type_param_(a_type_param ? new std::string(a_type_param) : nullptr),
2962 set_up_tc_(set_up_tc),
2963 tear_down_tc_(tear_down_tc),
2965 start_timestamp_(0),
2969TestSuite::~TestSuite() {
2971 ForEach(test_info_list_, internal::Delete<TestInfo>);
2976const TestInfo* TestSuite::GetTestInfo(
int i)
const {
2977 const int index = GetElementOr(test_indices_, i, -1);
2978 return index < 0 ? nullptr : test_info_list_[static_cast<size_t>(index)];
2983TestInfo* TestSuite::GetMutableTestInfo(
int i) {
2984 const int index = GetElementOr(test_indices_, i, -1);
2985 return index < 0 ? nullptr : test_info_list_[static_cast<size_t>(index)];
2990void TestSuite::AddTestInfo(TestInfo* test_info) {
2991 test_info_list_.push_back(test_info);
2992 test_indices_.push_back(
static_cast<int>(test_indices_.size()));
2996void TestSuite::Run() {
2997 if (!should_run_)
return;
2999 internal::UnitTestImpl*
const impl = internal::GetUnitTestImpl();
3000 impl->set_current_test_suite(
this);
3002 TestEventListener* repeater = UnitTest::GetInstance()->listeners().repeater();
3005 repeater->OnTestSuiteStart(*
this);
3007#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
3008 repeater->OnTestCaseStart(*
this);
3011 impl->os_stack_trace_getter()->UponLeavingGTest();
3012 internal::HandleExceptionsInMethodIfSupported(
3013 this, &TestSuite::RunSetUpTestSuite,
"SetUpTestSuite()");
3015 const bool skip_all = ad_hoc_test_result().Failed();
3017 start_timestamp_ = internal::GetTimeInMillis();
3018 internal::Timer timer;
3019 for (
int i = 0; i < total_test_count(); i++) {
3021 GetMutableTestInfo(i)->Skip();
3023 GetMutableTestInfo(i)->Run();
3025 if (GTEST_FLAG_GET(fail_fast) &&
3026 GetMutableTestInfo(i)->result()->Failed()) {
3027 for (
int j = i + 1; j < total_test_count(); j++) {
3028 GetMutableTestInfo(j)->Skip();
3033 elapsed_time_ = timer.Elapsed();
3035 impl->os_stack_trace_getter()->UponLeavingGTest();
3036 internal::HandleExceptionsInMethodIfSupported(
3037 this, &TestSuite::RunTearDownTestSuite,
"TearDownTestSuite()");
3040 repeater->OnTestSuiteEnd(*
this);
3042#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
3043 repeater->OnTestCaseEnd(*
this);
3046 impl->set_current_test_suite(
nullptr);
3050void TestSuite::Skip() {
3051 if (!should_run_)
return;
3053 internal::UnitTestImpl*
const impl = internal::GetUnitTestImpl();
3054 impl->set_current_test_suite(
this);
3056 TestEventListener* repeater = UnitTest::GetInstance()->listeners().repeater();
3059 repeater->OnTestSuiteStart(*
this);
3061#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
3062 repeater->OnTestCaseStart(*
this);
3065 for (
int i = 0; i < total_test_count(); i++) {
3066 GetMutableTestInfo(i)->Skip();
3070 repeater->OnTestSuiteEnd(*
this);
3072#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
3073 repeater->OnTestCaseEnd(*
this);
3076 impl->set_current_test_suite(
nullptr);
3080void TestSuite::ClearResult() {
3081 ad_hoc_test_result_.Clear();
3082 ForEach(test_info_list_, TestInfo::ClearTestResult);
3086void TestSuite::ShuffleTests(internal::Random* random) {
3087 Shuffle(random, &test_indices_);
3091void TestSuite::UnshuffleTests() {
3092 for (
size_t i = 0; i < test_indices_.size(); i++) {
3093 test_indices_[i] =
static_cast<int>(i);
3102static std::string FormatCountableNoun(
int count,
const char* singular_form,
3103 const char* plural_form) {
3104 return internal::StreamableToString(count) +
" " +
3105 (count == 1 ? singular_form : plural_form);
3109static std::string FormatTestCount(
int test_count) {
3110 return FormatCountableNoun(test_count,
"test",
"tests");
3114static std::string FormatTestSuiteCount(
int test_suite_count) {
3115 return FormatCountableNoun(test_suite_count,
"test suite",
"test suites");
3122static const char* TestPartResultTypeToString(TestPartResult::Type type) {
3124 case TestPartResult::kSkip:
3126 case TestPartResult::kSuccess:
3129 case TestPartResult::kNonFatalFailure:
3130 case TestPartResult::kFatalFailure:
3137 return "Unknown result type";
3143enum class GTestColor { kDefault, kRed, kGreen, kYellow };
3147static std::string PrintTestPartResultToString(
3148 const TestPartResult& test_part_result) {
3149 return (Message() << internal::FormatFileLocation(
3150 test_part_result.file_name(),
3151 test_part_result.line_number())
3153 << TestPartResultTypeToString(test_part_result.type())
3154 << test_part_result.message())
3159static void PrintTestPartResult(
const TestPartResult& test_part_result) {
3160 const std::string& result = PrintTestPartResultToString(test_part_result);
3161 printf(
"%s\n", result.c_str());
3167#if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE
3171 ::OutputDebugStringA(result.c_str());
3172 ::OutputDebugStringA(
"\n");
3177#if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE && !GTEST_OS_WINDOWS_PHONE && \
3178 !GTEST_OS_WINDOWS_RT && !GTEST_OS_WINDOWS_MINGW
3181static WORD GetColorAttribute(GTestColor color) {
3183 case GTestColor::kRed:
3184 return FOREGROUND_RED;
3185 case GTestColor::kGreen:
3186 return FOREGROUND_GREEN;
3187 case GTestColor::kYellow:
3188 return FOREGROUND_RED | FOREGROUND_GREEN;
3194static int GetBitOffset(WORD color_mask) {
3195 if (color_mask == 0)
return 0;
3198 while ((color_mask & 1) == 0) {
3205static WORD GetNewColor(GTestColor color, WORD old_color_attrs) {
3207 static const WORD background_mask = BACKGROUND_BLUE | BACKGROUND_GREEN |
3208 BACKGROUND_RED | BACKGROUND_INTENSITY;
3209 static const WORD foreground_mask = FOREGROUND_BLUE | FOREGROUND_GREEN |
3210 FOREGROUND_RED | FOREGROUND_INTENSITY;
3211 const WORD existing_bg = old_color_attrs & background_mask;
3214 GetColorAttribute(color) | existing_bg | FOREGROUND_INTENSITY;
3215 static const int bg_bitOffset = GetBitOffset(background_mask);
3216 static const int fg_bitOffset = GetBitOffset(foreground_mask);
3218 if (((new_color & background_mask) >> bg_bitOffset) ==
3219 ((new_color & foreground_mask) >> fg_bitOffset)) {
3220 new_color ^= FOREGROUND_INTENSITY;
3229static const char* GetAnsiColorCode(GTestColor color) {
3231 case GTestColor::kRed:
3233 case GTestColor::kGreen:
3235 case GTestColor::kYellow:
3245bool ShouldUseColor(
bool stdout_is_tty) {
3246 std::string c = GTEST_FLAG_GET(color);
3247 const char*
const gtest_color = c.c_str();
3249 if (String::CaseInsensitiveCStringEquals(gtest_color,
"auto")) {
3250#if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MINGW
3253 return stdout_is_tty;
3256 const char*
const term = posix::GetEnv(
"TERM");
3257 const bool term_supports_color = term !=
nullptr && (
3258 String::CStringEquals(term,
"xterm") ||
3259 String::CStringEquals(term,
"xterm-color") ||
3260 String::CStringEquals(term,
"screen") ||
3261 String::CStringEquals(term,
"tmux") ||
3262 String::CStringEquals(term,
"rxvt-unicode") ||
3263 String::CStringEquals(term,
"linux") ||
3264 String::CStringEquals(term,
"cygwin") ||
3265 String::EndsWithCaseInsensitive(term,
"-256color"));
3266 return stdout_is_tty && term_supports_color;
3270 return String::CaseInsensitiveCStringEquals(gtest_color,
"yes") ||
3271 String::CaseInsensitiveCStringEquals(gtest_color,
"true") ||
3272 String::CaseInsensitiveCStringEquals(gtest_color,
"t") ||
3273 String::CStringEquals(gtest_color,
"1");
3284GTEST_ATTRIBUTE_PRINTF_(2, 3)
3285static
void ColoredPrintf(GTestColor color, const
char* fmt, ...) {
3287 va_start(args, fmt);
3289 static const bool in_color_mode =
3290 ShouldUseColor(posix::IsATTY(posix::FileNo(stdout)) != 0);
3291 const bool use_color = in_color_mode && (color != GTestColor::kDefault);
3299#if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE && !GTEST_OS_WINDOWS_PHONE && \
3300 !GTEST_OS_WINDOWS_RT && !GTEST_OS_WINDOWS_MINGW
3301 const HANDLE stdout_handle = GetStdHandle(STD_OUTPUT_HANDLE);
3304 CONSOLE_SCREEN_BUFFER_INFO buffer_info;
3305 GetConsoleScreenBufferInfo(stdout_handle, &buffer_info);
3306 const WORD old_color_attrs = buffer_info.wAttributes;
3307 const WORD new_color = GetNewColor(color, old_color_attrs);
3313 SetConsoleTextAttribute(stdout_handle, new_color);
3319 SetConsoleTextAttribute(stdout_handle, old_color_attrs);
3321 printf(
"\033[0;3%sm", GetAnsiColorCode(color));
3330static const char kTypeParamLabel[] =
"TypeParam";
3331static const char kValueParamLabel[] =
"GetParam()";
3333static void PrintFullTestCommentIfPresent(
const TestInfo& test_info) {
3334 const char*
const type_param = test_info.type_param();
3335 const char*
const value_param = test_info.value_param();
3337 if (type_param !=
nullptr || value_param !=
nullptr) {
3339 if (type_param !=
nullptr) {
3340 printf(
"%s = %s", kTypeParamLabel, type_param);
3341 if (value_param !=
nullptr) printf(
" and ");
3343 if (value_param !=
nullptr) {
3344 printf(
"%s = %s", kValueParamLabel, value_param);
3355 static void PrintTestName(
const char* test_suite,
const char* test) {
3356 printf(
"%s.%s", test_suite, test);
3360 void OnTestProgramStart(
const UnitTest& )
override {}
3361 void OnTestIterationStart(
const UnitTest& unit_test,
int iteration)
override;
3362 void OnEnvironmentsSetUpStart(
const UnitTest& unit_test)
override;
3363 void OnEnvironmentsSetUpEnd(
const UnitTest& )
override {}
3364#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
3365 void OnTestCaseStart(
const TestCase& test_case)
override;
3367 void OnTestSuiteStart(
const TestSuite& test_suite)
override;
3370 void OnTestStart(
const TestInfo& test_info)
override;
3371 void OnTestDisabled(
const TestInfo& test_info)
override;
3373 void OnTestPartResult(
const TestPartResult& result)
override;
3374 void OnTestEnd(
const TestInfo& test_info)
override;
3375#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
3376 void OnTestCaseEnd(
const TestCase& test_case)
override;
3378 void OnTestSuiteEnd(
const TestSuite& test_suite)
override;
3381 void OnEnvironmentsTearDownStart(
const UnitTest& unit_test)
override;
3382 void OnEnvironmentsTearDownEnd(
const UnitTest& )
override {}
3383 void OnTestIterationEnd(
const UnitTest& unit_test,
int iteration)
override;
3384 void OnTestProgramEnd(
const UnitTest& )
override {}
3387 static void PrintFailedTests(
const UnitTest& unit_test);
3388 static void PrintFailedTestSuites(
const UnitTest& unit_test);
3389 static void PrintSkippedTests(
const UnitTest& unit_test);
3393void PrettyUnitTestResultPrinter::OnTestIterationStart(
3394 const UnitTest& unit_test,
int iteration) {
3395 if (GTEST_FLAG_GET(repeat) != 1)
3396 printf(
"\nRepeating all tests (iteration %d) . . .\n\n", iteration + 1);
3398 std::string f = GTEST_FLAG_GET(filter);
3399 const char*
const filter = f.c_str();
3403 if (!String::CStringEquals(filter, kUniversalFilter)) {
3404 ColoredPrintf(GTestColor::kYellow,
"Note: %s filter = %s\n", GTEST_NAME_,
3408 if (internal::ShouldShard(kTestTotalShards, kTestShardIndex,
false)) {
3409 const int32_t shard_index = Int32FromEnvOrDie(kTestShardIndex, -1);
3410 ColoredPrintf(GTestColor::kYellow,
"Note: This is test shard %d of %s.\n",
3411 static_cast<int>(shard_index) + 1,
3412 internal::posix::GetEnv(kTestTotalShards));
3415 if (GTEST_FLAG_GET(shuffle)) {
3416 ColoredPrintf(GTestColor::kYellow,
3417 "Note: Randomizing tests' orders with a seed of %d .\n",
3418 unit_test.random_seed());
3421 ColoredPrintf(GTestColor::kGreen,
"[==========] ");
3422 printf(
"Running %s from %s.\n",
3423 FormatTestCount(unit_test.test_to_run_count()).c_str(),
3424 FormatTestSuiteCount(unit_test.test_suite_to_run_count()).c_str());
3428void PrettyUnitTestResultPrinter::OnEnvironmentsSetUpStart(
3430 ColoredPrintf(GTestColor::kGreen,
"[----------] ");
3431 printf(
"Global test environment set-up.\n");
3435#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
3436void PrettyUnitTestResultPrinter::OnTestCaseStart(
const TestCase& test_case) {
3437 const std::string counts =
3438 FormatCountableNoun(test_case.test_to_run_count(),
"test",
"tests");
3439 ColoredPrintf(GTestColor::kGreen,
"[----------] ");
3440 printf(
"%s from %s", counts.c_str(), test_case.name());
3441 if (test_case.type_param() ==
nullptr) {
3444 printf(
", where %s = %s\n", kTypeParamLabel, test_case.type_param());
3449void PrettyUnitTestResultPrinter::OnTestSuiteStart(
3450 const TestSuite& test_suite) {
3451 const std::string counts =
3452 FormatCountableNoun(test_suite.test_to_run_count(),
"test",
"tests");
3453 ColoredPrintf(GTestColor::kGreen,
"[----------] ");
3454 printf(
"%s from %s", counts.c_str(), test_suite.name());
3455 if (test_suite.type_param() ==
nullptr) {
3458 printf(
", where %s = %s\n", kTypeParamLabel, test_suite.type_param());
3464void PrettyUnitTestResultPrinter::OnTestStart(
const TestInfo& test_info) {
3465 ColoredPrintf(GTestColor::kGreen,
"[ RUN ] ");
3466 PrintTestName(test_info.test_suite_name(), test_info.name());
3471void PrettyUnitTestResultPrinter::OnTestDisabled(
const TestInfo& test_info) {
3472 ColoredPrintf(GTestColor::kYellow,
"[ DISABLED ] ");
3473 PrintTestName(test_info.test_suite_name(), test_info.name());
3479void PrettyUnitTestResultPrinter::OnTestPartResult(
3480 const TestPartResult& result) {
3481 switch (result.type()) {
3483 case TestPartResult::kSuccess:
3488 PrintTestPartResult(result);
3493void PrettyUnitTestResultPrinter::OnTestEnd(
const TestInfo& test_info) {
3494 if (test_info.result()->Passed()) {
3495 ColoredPrintf(GTestColor::kGreen,
"[ OK ] ");
3496 }
else if (test_info.result()->Skipped()) {
3497 ColoredPrintf(GTestColor::kGreen,
"[ SKIPPED ] ");
3499 ColoredPrintf(GTestColor::kRed,
"[ FAILED ] ");
3501 PrintTestName(test_info.test_suite_name(), test_info.name());
3502 if (test_info.result()->Failed()) PrintFullTestCommentIfPresent(test_info);
3504 if (GTEST_FLAG_GET(print_time)) {
3505 printf(
" (%s ms)\n",
3506 internal::StreamableToString(test_info.result()->elapsed_time())
3514#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
3515void PrettyUnitTestResultPrinter::OnTestCaseEnd(
const TestCase& test_case) {
3516 if (!GTEST_FLAG_GET(print_time))
return;
3518 const std::string counts =
3519 FormatCountableNoun(test_case.test_to_run_count(),
"test",
"tests");
3520 ColoredPrintf(GTestColor::kGreen,
"[----------] ");
3521 printf(
"%s from %s (%s ms total)\n\n", counts.c_str(), test_case.name(),
3522 internal::StreamableToString(test_case.elapsed_time()).c_str());
3526void PrettyUnitTestResultPrinter::OnTestSuiteEnd(
const TestSuite& test_suite) {
3527 if (!GTEST_FLAG_GET(print_time))
return;
3529 const std::string counts =
3530 FormatCountableNoun(test_suite.test_to_run_count(),
"test",
"tests");
3531 ColoredPrintf(GTestColor::kGreen,
"[----------] ");
3532 printf(
"%s from %s (%s ms total)\n\n", counts.c_str(), test_suite.name(),
3533 internal::StreamableToString(test_suite.elapsed_time()).c_str());
3538void PrettyUnitTestResultPrinter::OnEnvironmentsTearDownStart(
3540 ColoredPrintf(GTestColor::kGreen,
"[----------] ");
3541 printf(
"Global test environment tear-down\n");
3546void PrettyUnitTestResultPrinter::PrintFailedTests(
const UnitTest& unit_test) {
3547 const int failed_test_count = unit_test.failed_test_count();
3548 ColoredPrintf(GTestColor::kRed,
"[ FAILED ] ");
3549 printf(
"%s, listed below:\n", FormatTestCount(failed_test_count).c_str());
3551 for (
int i = 0; i < unit_test.total_test_suite_count(); ++i) {
3552 const TestSuite& test_suite = *unit_test.GetTestSuite(i);
3553 if (!test_suite.should_run() || (test_suite.failed_test_count() == 0)) {
3556 for (
int j = 0; j < test_suite.total_test_count(); ++j) {
3557 const TestInfo& test_info = *test_suite.GetTestInfo(j);
3558 if (!test_info.should_run() || !test_info.result()->Failed()) {
3561 ColoredPrintf(GTestColor::kRed,
"[ FAILED ] ");
3562 printf(
"%s.%s", test_suite.name(), test_info.name());
3563 PrintFullTestCommentIfPresent(test_info);
3567 printf(
"\n%2d FAILED %s\n", failed_test_count,
3568 failed_test_count == 1 ?
"TEST" :
"TESTS");
3573void PrettyUnitTestResultPrinter::PrintFailedTestSuites(
3574 const UnitTest& unit_test) {
3575 int suite_failure_count = 0;
3576 for (
int i = 0; i < unit_test.total_test_suite_count(); ++i) {
3577 const TestSuite& test_suite = *unit_test.GetTestSuite(i);
3578 if (!test_suite.should_run()) {
3581 if (test_suite.ad_hoc_test_result().Failed()) {
3582 ColoredPrintf(GTestColor::kRed,
"[ FAILED ] ");
3583 printf(
"%s: SetUpTestSuite or TearDownTestSuite\n", test_suite.name());
3584 ++suite_failure_count;
3587 if (suite_failure_count > 0) {
3588 printf(
"\n%2d FAILED TEST %s\n", suite_failure_count,
3589 suite_failure_count == 1 ?
"SUITE" :
"SUITES");
3594void PrettyUnitTestResultPrinter::PrintSkippedTests(
const UnitTest& unit_test) {
3595 const int skipped_test_count = unit_test.skipped_test_count();
3596 if (skipped_test_count == 0) {
3600 for (
int i = 0; i < unit_test.total_test_suite_count(); ++i) {
3601 const TestSuite& test_suite = *unit_test.GetTestSuite(i);
3602 if (!test_suite.should_run() || (test_suite.skipped_test_count() == 0)) {
3605 for (
int j = 0; j < test_suite.total_test_count(); ++j) {
3606 const TestInfo& test_info = *test_suite.GetTestInfo(j);
3607 if (!test_info.should_run() || !test_info.result()->Skipped()) {
3610 ColoredPrintf(GTestColor::kGreen,
"[ SKIPPED ] ");
3611 printf(
"%s.%s", test_suite.name(), test_info.name());
3617void PrettyUnitTestResultPrinter::OnTestIterationEnd(
const UnitTest& unit_test,
3619 ColoredPrintf(GTestColor::kGreen,
"[==========] ");
3620 printf(
"%s from %s ran.",
3621 FormatTestCount(unit_test.test_to_run_count()).c_str(),
3622 FormatTestSuiteCount(unit_test.test_suite_to_run_count()).c_str());
3623 if (GTEST_FLAG_GET(print_time)) {
3624 printf(
" (%s ms total)",
3625 internal::StreamableToString(unit_test.elapsed_time()).c_str());
3628 ColoredPrintf(GTestColor::kGreen,
"[ PASSED ] ");
3629 printf(
"%s.\n", FormatTestCount(unit_test.successful_test_count()).c_str());
3631 const int skipped_test_count = unit_test.skipped_test_count();
3632 if (skipped_test_count > 0) {
3633 ColoredPrintf(GTestColor::kGreen,
"[ SKIPPED ] ");
3634 printf(
"%s, listed below:\n", FormatTestCount(skipped_test_count).c_str());
3635 PrintSkippedTests(unit_test);
3638 if (!unit_test.Passed()) {
3639 PrintFailedTests(unit_test);
3640 PrintFailedTestSuites(unit_test);
3643 int num_disabled = unit_test.reportable_disabled_test_count();
3644 if (num_disabled && !GTEST_FLAG_GET(also_run_disabled_tests)) {
3645 if (unit_test.Passed()) {
3648 ColoredPrintf(GTestColor::kYellow,
" YOU HAVE %d DISABLED %s\n\n",
3649 num_disabled, num_disabled == 1 ?
"TEST" :
"TESTS");
3663 static void PrintTestName(
const char* test_suite,
const char* test) {
3664 printf(
"%s.%s", test_suite, test);
3668 void OnTestProgramStart(
const UnitTest& )
override {}
3669 void OnTestIterationStart(
const UnitTest& ,
3671 void OnEnvironmentsSetUpStart(
const UnitTest& )
override {}
3672 void OnEnvironmentsSetUpEnd(
const UnitTest& )
override {}
3673#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
3674 void OnTestCaseStart(
const TestCase& )
override {}
3676 void OnTestSuiteStart(
const TestSuite& )
override {}
3679 void OnTestStart(
const TestInfo& )
override {}
3680 void OnTestDisabled(
const TestInfo& )
override {}
3682 void OnTestPartResult(
const TestPartResult& result)
override;
3683 void OnTestEnd(
const TestInfo& test_info)
override;
3684#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
3685 void OnTestCaseEnd(
const TestCase& )
override {}
3687 void OnTestSuiteEnd(
const TestSuite& )
override {}
3690 void OnEnvironmentsTearDownStart(
const UnitTest& )
override {}
3691 void OnEnvironmentsTearDownEnd(
const UnitTest& )
override {}
3692 void OnTestIterationEnd(
const UnitTest& unit_test,
int iteration)
override;
3693 void OnTestProgramEnd(
const UnitTest& )
override {}
3697void BriefUnitTestResultPrinter::OnTestPartResult(
3698 const TestPartResult& result) {
3699 switch (result.type()) {
3701 case TestPartResult::kSuccess:
3706 PrintTestPartResult(result);
3711void BriefUnitTestResultPrinter::OnTestEnd(
const TestInfo& test_info) {
3712 if (test_info.result()->Failed()) {
3713 ColoredPrintf(GTestColor::kRed,
"[ FAILED ] ");
3714 PrintTestName(test_info.test_suite_name(), test_info.name());
3715 PrintFullTestCommentIfPresent(test_info);
3717 if (GTEST_FLAG_GET(print_time)) {
3718 printf(
" (%s ms)\n",
3719 internal::StreamableToString(test_info.result()->elapsed_time())
3728void BriefUnitTestResultPrinter::OnTestIterationEnd(
const UnitTest& unit_test,
3730 ColoredPrintf(GTestColor::kGreen,
"[==========] ");
3731 printf(
"%s from %s ran.",
3732 FormatTestCount(unit_test.test_to_run_count()).c_str(),
3733 FormatTestSuiteCount(unit_test.test_suite_to_run_count()).c_str());
3734 if (GTEST_FLAG_GET(print_time)) {
3735 printf(
" (%s ms total)",
3736 internal::StreamableToString(unit_test.elapsed_time()).c_str());
3739 ColoredPrintf(GTestColor::kGreen,
"[ PASSED ] ");
3740 printf(
"%s.\n", FormatTestCount(unit_test.successful_test_count()).c_str());
3742 const int skipped_test_count = unit_test.skipped_test_count();
3743 if (skipped_test_count > 0) {
3744 ColoredPrintf(GTestColor::kGreen,
"[ SKIPPED ] ");
3745 printf(
"%s.\n", FormatTestCount(skipped_test_count).c_str());
3748 int num_disabled = unit_test.reportable_disabled_test_count();
3749 if (num_disabled && !GTEST_FLAG_GET(also_run_disabled_tests)) {
3750 if (unit_test.Passed()) {
3753 ColoredPrintf(GTestColor::kYellow,
" YOU HAVE %d DISABLED %s\n\n",
3754 num_disabled, num_disabled == 1 ?
"TEST" :
"TESTS");
3774 bool forwarding_enabled()
const {
return forwarding_enabled_; }
3775 void set_forwarding_enabled(
bool enable) { forwarding_enabled_ = enable; }
3777 void OnTestProgramStart(
const UnitTest& unit_test)
override;
3778 void OnTestIterationStart(
const UnitTest& unit_test,
int iteration)
override;
3779 void OnEnvironmentsSetUpStart(
const UnitTest& unit_test)
override;
3780 void OnEnvironmentsSetUpEnd(
const UnitTest& unit_test)
override;
3782#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
3783 void OnTestCaseStart(
const TestSuite& parameter)
override;
3785 void OnTestSuiteStart(
const TestSuite& parameter)
override;
3786 void OnTestStart(
const TestInfo& test_info)
override;
3787 void OnTestDisabled(
const TestInfo& test_info)
override;
3788 void OnTestPartResult(
const TestPartResult& result)
override;
3789 void OnTestEnd(
const TestInfo& test_info)
override;
3791#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
3792 void OnTestCaseEnd(
const TestCase& parameter)
override;
3794 void OnTestSuiteEnd(
const TestSuite& parameter)
override;
3795 void OnEnvironmentsTearDownStart(
const UnitTest& unit_test)
override;
3796 void OnEnvironmentsTearDownEnd(
const UnitTest& unit_test)
override;
3797 void OnTestIterationEnd(
const UnitTest& unit_test,
int iteration)
override;
3798 void OnTestProgramEnd(
const UnitTest& unit_test)
override;
3803 bool forwarding_enabled_;
3805 std::vector<TestEventListener*> listeners_;
3811TestEventRepeater::~TestEventRepeater() {
3812 ForEach(listeners_, Delete<TestEventListener>);
3816 listeners_.push_back(listener);
3819TestEventListener* TestEventRepeater::Release(TestEventListener* listener) {
3820 for (
size_t i = 0; i < listeners_.size(); ++i) {
3821 if (listeners_[i] == listener) {
3822 listeners_.erase(listeners_.begin() +
static_cast<int>(i));
3832#define GTEST_REPEATER_METHOD_(Name, Type) \
3833 void TestEventRepeater::Name(const Type& parameter) { \
3834 if (forwarding_enabled_) { \
3835 for (size_t i = 0; i < listeners_.size(); i++) { \
3836 listeners_[i]->Name(parameter); \
3842#define GTEST_REVERSE_REPEATER_METHOD_(Name, Type) \
3843 void TestEventRepeater::Name(const Type& parameter) { \
3844 if (forwarding_enabled_) { \
3845 for (size_t i = listeners_.size(); i != 0; i--) { \
3846 listeners_[i - 1]->Name(parameter); \
3851GTEST_REPEATER_METHOD_(OnTestProgramStart, UnitTest)
3852GTEST_REPEATER_METHOD_(OnEnvironmentsSetUpStart, UnitTest)
3854#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
3855GTEST_REPEATER_METHOD_(OnTestCaseStart, TestSuite)
3857GTEST_REPEATER_METHOD_(OnTestSuiteStart, TestSuite)
3858GTEST_REPEATER_METHOD_(OnTestStart, TestInfo)
3859GTEST_REPEATER_METHOD_(OnTestDisabled, TestInfo)
3860GTEST_REPEATER_METHOD_(OnTestPartResult, TestPartResult)
3861GTEST_REPEATER_METHOD_(OnEnvironmentsTearDownStart, UnitTest)
3862GTEST_REVERSE_REPEATER_METHOD_(OnEnvironmentsSetUpEnd, UnitTest)
3863GTEST_REVERSE_REPEATER_METHOD_(OnEnvironmentsTearDownEnd, UnitTest)
3864GTEST_REVERSE_REPEATER_METHOD_(OnTestEnd, TestInfo)
3866#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
3867GTEST_REVERSE_REPEATER_METHOD_(OnTestCaseEnd, TestSuite)
3869GTEST_REVERSE_REPEATER_METHOD_(OnTestSuiteEnd, TestSuite)
3870GTEST_REVERSE_REPEATER_METHOD_(OnTestProgramEnd, UnitTest)
3872#undef GTEST_REPEATER_METHOD_
3873#undef GTEST_REVERSE_REPEATER_METHOD_
3875void TestEventRepeater::OnTestIterationStart(
const UnitTest& unit_test,
3877 if (forwarding_enabled_) {
3878 for (
size_t i = 0; i < listeners_.size(); i++) {
3879 listeners_[i]->OnTestIterationStart(unit_test, iteration);
3884void TestEventRepeater::OnTestIterationEnd(
const UnitTest& unit_test,
3886 if (forwarding_enabled_) {
3887 for (
size_t i = listeners_.size(); i > 0; i--) {
3888 listeners_[i - 1]->OnTestIterationEnd(unit_test, iteration);
3900 void OnTestIterationEnd(
const UnitTest& unit_test,
int iteration)
override;
3901 void ListTestsMatchingFilter(
const std::vector<TestSuite*>& test_suites);
3904 static void PrintXmlTestsList(std::ostream* stream,
3905 const std::vector<TestSuite*>& test_suites);
3910 static bool IsNormalizableWhitespace(
unsigned char c) {
3911 return c ==
'\t' || c ==
'\n' || c ==
'\r';
3916 static bool IsValidXmlCharacter(
unsigned char c) {
3917 return IsNormalizableWhitespace(c) || c >= 0x20;
3924 static std::string EscapeXml(
const std::string& str,
bool is_attribute);
3927 static std::string RemoveInvalidXmlCharacters(
const std::string& str);
3930 static std::string EscapeXmlAttribute(
const std::string& str) {
3931 return EscapeXml(str,
true);
3935 static std::string EscapeXmlText(
const char* str) {
3936 return EscapeXml(str,
false);
3941 static void OutputXmlAttribute(std::ostream* stream,
3942 const std::string& element_name,
3943 const std::string& name,
3944 const std::string& value);
3947 static void OutputXmlCDataSection(::std::ostream* stream,
const char* data);
3952 static void OutputXmlTestSuiteForTestResult(::std::ostream* stream,
3956 static void OutputXmlTestResult(::std::ostream* stream,
3960 static void OutputXmlTestInfo(::std::ostream* stream,
3961 const char* test_suite_name,
3965 static void PrintXmlTestSuite(::std::ostream* stream,
3969 static void PrintXmlUnitTest(::std::ostream* stream,
3976 static std::string TestPropertiesAsXmlAttributes(
const TestResult& result);
3980 static void OutputXmlTestProperties(std::ostream* stream,
3984 const std::string output_file_;
3991XmlUnitTestResultPrinter::XmlUnitTestResultPrinter(
const char* output_file)
3992 : output_file_(output_file) {
3993 if (output_file_.empty()) {
3994 GTEST_LOG_(FATAL) <<
"XML output file may not be null";
3999void XmlUnitTestResultPrinter::OnTestIterationEnd(
const UnitTest& unit_test,
4001 FILE* xmlout = OpenFileForWriting(output_file_);
4002 std::stringstream stream;
4003 PrintXmlUnitTest(&stream, unit_test);
4004 fprintf(xmlout,
"%s", StringStreamToString(&stream).c_str());
4008void XmlUnitTestResultPrinter::ListTestsMatchingFilter(
4009 const std::vector<TestSuite*>& test_suites) {
4010 FILE* xmlout = OpenFileForWriting(output_file_);
4011 std::stringstream stream;
4012 PrintXmlTestsList(&stream, test_suites);
4013 fprintf(xmlout,
"%s", StringStreamToString(&stream).c_str());
4027std::string XmlUnitTestResultPrinter::EscapeXml(
const std::string& str,
4028 bool is_attribute) {
4031 for (
size_t i = 0; i < str.size(); ++i) {
4032 const char ch = str[i];
4056 if (IsValidXmlCharacter(
static_cast<unsigned char>(ch))) {
4058 IsNormalizableWhitespace(
static_cast<unsigned char>(ch)))
4059 m <<
"&#x" << String::FormatByte(
static_cast<unsigned char>(ch))
4068 return m.GetString();
4074std::string XmlUnitTestResultPrinter::RemoveInvalidXmlCharacters(
4075 const std::string& str) {
4077 output.reserve(str.size());
4078 for (std::string::const_iterator it = str.begin(); it != str.end(); ++it)
4079 if (IsValidXmlCharacter(
static_cast<unsigned char>(*it)))
4080 output.push_back(*it);
4102std::string FormatTimeInMillisAsSeconds(TimeInMillis ms) {
4103 ::std::stringstream ss;
4104 ss << (static_cast<double>(ms) * 1e-3);
4108static bool PortableLocaltime(time_t seconds,
struct tm* out) {
4109#if defined(_MSC_VER)
4110 return localtime_s(out, &seconds) == 0;
4111#elif defined(__MINGW32__) || defined(__MINGW64__)
4114 struct tm* tm_ptr = localtime(&seconds);
4115 if (tm_ptr ==
nullptr)
return false;
4118#elif defined(__STDC_LIB_EXT1__)
4121 return localtime_s(&seconds, out) !=
nullptr;
4123 return localtime_r(&seconds, out) !=
nullptr;
4129std::string FormatEpochTimeInMillisAsIso8601(TimeInMillis ms) {
4130 struct tm time_struct;
4131 if (!PortableLocaltime(
static_cast<time_t
>(ms / 1000), &time_struct))
4134 return StreamableToString(time_struct.tm_year + 1900) +
"-" +
4135 String::FormatIntWidth2(time_struct.tm_mon + 1) +
"-" +
4136 String::FormatIntWidth2(time_struct.tm_mday) +
"T" +
4137 String::FormatIntWidth2(time_struct.tm_hour) +
":" +
4138 String::FormatIntWidth2(time_struct.tm_min) +
":" +
4139 String::FormatIntWidth2(time_struct.tm_sec) +
"." +
4140 String::FormatIntWidthN(
static_cast<int>(ms % 1000), 3);
4144void XmlUnitTestResultPrinter::OutputXmlCDataSection(::std::ostream* stream,
4146 const char* segment = data;
4147 *stream <<
"<![CDATA[";
4149 const char*
const next_segment = strstr(segment,
"]]>");
4150 if (next_segment !=
nullptr) {
4151 stream->write(segment,
4152 static_cast<std::streamsize
>(next_segment - segment));
4153 *stream <<
"]]>]]><![CDATA[";
4154 segment = next_segment + strlen(
"]]>");
4163void XmlUnitTestResultPrinter::OutputXmlAttribute(
4164 std::ostream* stream,
const std::string& element_name,
4165 const std::string& name,
const std::string& value) {
4166 const std::vector<std::string>& allowed_names =
4167 GetReservedOutputAttributesForElement(element_name);
4169 GTEST_CHECK_(std::find(allowed_names.begin(), allowed_names.end(), name) !=
4170 allowed_names.end())
4171 <<
"Attribute " << name <<
" is not allowed for element <" << element_name
4174 *stream <<
" " << name <<
"=\"" << EscapeXmlAttribute(value) <<
"\"";
4178void XmlUnitTestResultPrinter::OutputXmlTestSuiteForTestResult(
4179 ::std::ostream* stream,
const TestResult& result) {
4181 *stream <<
" <testsuite";
4182 OutputXmlAttribute(stream,
"testsuite",
"name",
"NonTestSuiteFailure");
4183 OutputXmlAttribute(stream,
"testsuite",
"tests",
"1");
4184 OutputXmlAttribute(stream,
"testsuite",
"failures",
"1");
4185 OutputXmlAttribute(stream,
"testsuite",
"disabled",
"0");
4186 OutputXmlAttribute(stream,
"testsuite",
"skipped",
"0");
4187 OutputXmlAttribute(stream,
"testsuite",
"errors",
"0");
4188 OutputXmlAttribute(stream,
"testsuite",
"time",
4189 FormatTimeInMillisAsSeconds(result.elapsed_time()));
4191 stream,
"testsuite",
"timestamp",
4192 FormatEpochTimeInMillisAsIso8601(result.start_timestamp()));
4196 *stream <<
" <testcase";
4197 OutputXmlAttribute(stream,
"testcase",
"name",
"");
4198 OutputXmlAttribute(stream,
"testcase",
"status",
"run");
4199 OutputXmlAttribute(stream,
"testcase",
"result",
"completed");
4200 OutputXmlAttribute(stream,
"testcase",
"classname",
"");
4201 OutputXmlAttribute(stream,
"testcase",
"time",
4202 FormatTimeInMillisAsSeconds(result.elapsed_time()));
4204 stream,
"testcase",
"timestamp",
4205 FormatEpochTimeInMillisAsIso8601(result.start_timestamp()));
4208 OutputXmlTestResult(stream, result);
4211 *stream <<
" </testsuite>\n";
4215void XmlUnitTestResultPrinter::OutputXmlTestInfo(::std::ostream* stream,
4216 const char* test_suite_name,
4217 const TestInfo& test_info) {
4218 const TestResult& result = *test_info.result();
4219 const std::string kTestsuite =
"testcase";
4221 if (test_info.is_in_another_shard()) {
4225 *stream <<
" <testcase";
4226 OutputXmlAttribute(stream, kTestsuite,
"name", test_info.name());
4228 if (test_info.value_param() !=
nullptr) {
4229 OutputXmlAttribute(stream, kTestsuite,
"value_param",
4230 test_info.value_param());
4232 if (test_info.type_param() !=
nullptr) {
4233 OutputXmlAttribute(stream, kTestsuite,
"type_param",
4234 test_info.type_param());
4237 OutputXmlAttribute(stream, kTestsuite,
"file", test_info.file());
4238 OutputXmlAttribute(stream, kTestsuite,
"line",
4239 StreamableToString(test_info.line()));
4240 if (GTEST_FLAG_GET(list_tests)) {
4245 OutputXmlAttribute(stream, kTestsuite,
"status",
4246 test_info.should_run() ?
"run" :
"notrun");
4247 OutputXmlAttribute(stream, kTestsuite,
"result",
4248 test_info.should_run()
4249 ? (result.Skipped() ?
"skipped" :
"completed")
4251 OutputXmlAttribute(stream, kTestsuite,
"time",
4252 FormatTimeInMillisAsSeconds(result.elapsed_time()));
4254 stream, kTestsuite,
"timestamp",
4255 FormatEpochTimeInMillisAsIso8601(result.start_timestamp()));
4256 OutputXmlAttribute(stream, kTestsuite,
"classname", test_suite_name);
4258 OutputXmlTestResult(stream, result);
4261void XmlUnitTestResultPrinter::OutputXmlTestResult(::std::ostream* stream,
4262 const TestResult& result) {
4265 for (
int i = 0; i < result.total_part_count(); ++i) {
4266 const TestPartResult& part = result.GetTestPartResult(i);
4267 if (part.failed()) {
4268 if (++failures == 1 && skips == 0) {
4271 const std::string location =
4272 internal::FormatCompilerIndependentFileLocation(part.file_name(),
4273 part.line_number());
4274 const std::string summary = location +
"\n" + part.summary();
4275 *stream <<
" <failure message=\"" << EscapeXmlAttribute(summary)
4277 const std::string detail = location +
"\n" + part.message();
4278 OutputXmlCDataSection(stream, RemoveInvalidXmlCharacters(detail).c_str());
4279 *stream <<
"</failure>\n";
4280 }
else if (part.skipped()) {
4281 if (++skips == 1 && failures == 0) {
4284 const std::string location =
4285 internal::FormatCompilerIndependentFileLocation(part.file_name(),
4286 part.line_number());
4287 const std::string summary = location +
"\n" + part.summary();
4288 *stream <<
" <skipped message=\""
4289 << EscapeXmlAttribute(summary.c_str()) <<
"\">";
4290 const std::string detail = location +
"\n" + part.message();
4291 OutputXmlCDataSection(stream, RemoveInvalidXmlCharacters(detail).c_str());
4292 *stream <<
"</skipped>\n";
4296 if (failures == 0 && skips == 0 && result.test_property_count() == 0) {
4299 if (failures == 0 && skips == 0) {
4302 OutputXmlTestProperties(stream, result);
4303 *stream <<
" </testcase>\n";
4308void XmlUnitTestResultPrinter::PrintXmlTestSuite(std::ostream* stream,
4309 const TestSuite& test_suite) {
4310 const std::string kTestsuite =
"testsuite";
4311 *stream <<
" <" << kTestsuite;
4312 OutputXmlAttribute(stream, kTestsuite,
"name", test_suite.name());
4313 OutputXmlAttribute(stream, kTestsuite,
"tests",
4314 StreamableToString(test_suite.reportable_test_count()));
4315 if (!GTEST_FLAG_GET(list_tests)) {
4316 OutputXmlAttribute(stream, kTestsuite,
"failures",
4317 StreamableToString(test_suite.failed_test_count()));
4319 stream, kTestsuite,
"disabled",
4320 StreamableToString(test_suite.reportable_disabled_test_count()));
4321 OutputXmlAttribute(stream, kTestsuite,
"skipped",
4322 StreamableToString(test_suite.skipped_test_count()));
4324 OutputXmlAttribute(stream, kTestsuite,
"errors",
"0");
4326 OutputXmlAttribute(stream, kTestsuite,
"time",
4327 FormatTimeInMillisAsSeconds(test_suite.elapsed_time()));
4329 stream, kTestsuite,
"timestamp",
4330 FormatEpochTimeInMillisAsIso8601(test_suite.start_timestamp()));
4331 *stream << TestPropertiesAsXmlAttributes(test_suite.ad_hoc_test_result());
4334 for (
int i = 0; i < test_suite.total_test_count(); ++i) {
4335 if (test_suite.GetTestInfo(i)->is_reportable())
4336 OutputXmlTestInfo(stream, test_suite.name(), *test_suite.GetTestInfo(i));
4338 *stream <<
" </" << kTestsuite <<
">\n";
4342void XmlUnitTestResultPrinter::PrintXmlUnitTest(std::ostream* stream,
4343 const UnitTest& unit_test) {
4344 const std::string kTestsuites =
"testsuites";
4346 *stream <<
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
4347 *stream <<
"<" << kTestsuites;
4349 OutputXmlAttribute(stream, kTestsuites,
"tests",
4350 StreamableToString(unit_test.reportable_test_count()));
4351 OutputXmlAttribute(stream, kTestsuites,
"failures",
4352 StreamableToString(unit_test.failed_test_count()));
4354 stream, kTestsuites,
"disabled",
4355 StreamableToString(unit_test.reportable_disabled_test_count()));
4356 OutputXmlAttribute(stream, kTestsuites,
"errors",
"0");
4357 OutputXmlAttribute(stream, kTestsuites,
"time",
4358 FormatTimeInMillisAsSeconds(unit_test.elapsed_time()));
4360 stream, kTestsuites,
"timestamp",
4361 FormatEpochTimeInMillisAsIso8601(unit_test.start_timestamp()));
4363 if (GTEST_FLAG_GET(shuffle)) {
4364 OutputXmlAttribute(stream, kTestsuites,
"random_seed",
4365 StreamableToString(unit_test.random_seed()));
4367 *stream << TestPropertiesAsXmlAttributes(unit_test.ad_hoc_test_result());
4369 OutputXmlAttribute(stream, kTestsuites,
"name",
"AllTests");
4372 for (
int i = 0; i < unit_test.total_test_suite_count(); ++i) {
4373 if (unit_test.GetTestSuite(i)->reportable_test_count() > 0)
4374 PrintXmlTestSuite(stream, *unit_test.GetTestSuite(i));
4379 if (unit_test.ad_hoc_test_result().Failed()) {
4380 OutputXmlTestSuiteForTestResult(stream, unit_test.ad_hoc_test_result());
4383 *stream <<
"</" << kTestsuites <<
">\n";
4386void XmlUnitTestResultPrinter::PrintXmlTestsList(
4387 std::ostream* stream,
const std::vector<TestSuite*>& test_suites) {
4388 const std::string kTestsuites =
"testsuites";
4390 *stream <<
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
4391 *stream <<
"<" << kTestsuites;
4393 int total_tests = 0;
4394 for (
auto test_suite : test_suites) {
4395 total_tests += test_suite->total_test_count();
4397 OutputXmlAttribute(stream, kTestsuites,
"tests",
4398 StreamableToString(total_tests));
4399 OutputXmlAttribute(stream, kTestsuites,
"name",
"AllTests");
4402 for (
auto test_suite : test_suites) {
4403 PrintXmlTestSuite(stream, *test_suite);
4405 *stream <<
"</" << kTestsuites <<
">\n";
4410std::string XmlUnitTestResultPrinter::TestPropertiesAsXmlAttributes(
4411 const TestResult& result) {
4413 for (
int i = 0; i < result.test_property_count(); ++i) {
4414 const TestProperty&
property = result.GetTestProperty(i);
4415 attributes <<
" " <<
property.key() <<
"="
4416 <<
"\"" << EscapeXmlAttribute(property.value()) <<
"\"";
4418 return attributes.GetString();
4421void XmlUnitTestResultPrinter::OutputXmlTestProperties(
4422 std::ostream* stream,
const TestResult& result) {
4423 const std::string kProperties =
"properties";
4424 const std::string kProperty =
"property";
4426 if (result.test_property_count() <= 0) {
4430 *stream <<
" <" << kProperties <<
">\n";
4431 for (
int i = 0; i < result.test_property_count(); ++i) {
4432 const TestProperty&
property = result.GetTestProperty(i);
4433 *stream <<
" <" << kProperty;
4434 *stream <<
" name=\"" << EscapeXmlAttribute(property.key()) <<
"\"";
4435 *stream <<
" value=\"" << EscapeXmlAttribute(property.value()) <<
"\"";
4438 *stream <<
" </" << kProperties <<
">\n";
4448 void OnTestIterationEnd(
const UnitTest& unit_test,
int iteration)
override;
4451 static void PrintJsonTestList(::std::ostream* stream,
4452 const std::vector<TestSuite*>& test_suites);
4456 static std::string EscapeJson(
const std::string& str);
4460 static void OutputJsonKey(std::ostream* stream,
4461 const std::string& element_name,
4462 const std::string& name,
const std::string& value,
4463 const std::string& indent,
bool comma =
true);
4464 static void OutputJsonKey(std::ostream* stream,
4465 const std::string& element_name,
4466 const std::string& name,
int value,
4467 const std::string& indent,
bool comma =
true);
4472 static void OutputJsonTestSuiteForTestResult(::std::ostream* stream,
4476 static void OutputJsonTestResult(::std::ostream* stream,
4480 static void OutputJsonTestInfo(::std::ostream* stream,
4481 const char* test_suite_name,
4485 static void PrintJsonTestSuite(::std::ostream* stream,
4489 static void PrintJsonUnitTest(::std::ostream* stream,
4494 static std::string TestPropertiesAsJson(
const TestResult& result,
4495 const std::string& indent);
4498 const std::string output_file_;
4506JsonUnitTestResultPrinter::JsonUnitTestResultPrinter(
const char* output_file)
4507 : output_file_(output_file) {
4508 if (output_file_.empty()) {
4509 GTEST_LOG_(FATAL) <<
"JSON output file may not be null";
4513void JsonUnitTestResultPrinter::OnTestIterationEnd(
const UnitTest& unit_test,
4515 FILE* jsonout = OpenFileForWriting(output_file_);
4516 std::stringstream stream;
4517 PrintJsonUnitTest(&stream, unit_test);
4518 fprintf(jsonout,
"%s", StringStreamToString(&stream).c_str());
4523std::string JsonUnitTestResultPrinter::EscapeJson(
const std::string& str) {
4526 for (
size_t i = 0; i < str.size(); ++i) {
4527 const char ch = str[i];
4551 m <<
"\\u00" << String::FormatByte(
static_cast<unsigned char>(ch));
4559 return m.GetString();
4566static std::string FormatTimeInMillisAsDuration(TimeInMillis ms) {
4567 ::std::stringstream ss;
4568 ss << (static_cast<double>(ms) * 1e-3) <<
"s";
4574static std::string FormatEpochTimeInMillisAsRFC3339(TimeInMillis ms) {
4575 struct tm time_struct;
4576 if (!PortableLocaltime(
static_cast<time_t
>(ms / 1000), &time_struct))
4579 return StreamableToString(time_struct.tm_year + 1900) +
"-" +
4580 String::FormatIntWidth2(time_struct.tm_mon + 1) +
"-" +
4581 String::FormatIntWidth2(time_struct.tm_mday) +
"T" +
4582 String::FormatIntWidth2(time_struct.tm_hour) +
":" +
4583 String::FormatIntWidth2(time_struct.tm_min) +
":" +
4584 String::FormatIntWidth2(time_struct.tm_sec) +
"Z";
4587static inline std::string Indent(
size_t width) {
4588 return std::string(width,
' ');
4591void JsonUnitTestResultPrinter::OutputJsonKey(std::ostream* stream,
4592 const std::string& element_name,
4593 const std::string& name,
4594 const std::string& value,
4595 const std::string& indent,
4597 const std::vector<std::string>& allowed_names =
4598 GetReservedOutputAttributesForElement(element_name);
4600 GTEST_CHECK_(std::find(allowed_names.begin(), allowed_names.end(), name) !=
4601 allowed_names.end())
4602 <<
"Key \"" << name <<
"\" is not allowed for value \"" << element_name
4605 *stream << indent <<
"\"" << name <<
"\": \"" << EscapeJson(value) <<
"\"";
4606 if (comma) *stream <<
",\n";
4609void JsonUnitTestResultPrinter::OutputJsonKey(
4610 std::ostream* stream,
const std::string& element_name,
4611 const std::string& name,
int value,
const std::string& indent,
bool comma) {
4612 const std::vector<std::string>& allowed_names =
4613 GetReservedOutputAttributesForElement(element_name);
4615 GTEST_CHECK_(std::find(allowed_names.begin(), allowed_names.end(), name) !=
4616 allowed_names.end())
4617 <<
"Key \"" << name <<
"\" is not allowed for value \"" << element_name
4620 *stream << indent <<
"\"" << name <<
"\": " << StreamableToString(value);
4621 if (comma) *stream <<
",\n";
4625void JsonUnitTestResultPrinter::OutputJsonTestSuiteForTestResult(
4626 ::std::ostream* stream,
const TestResult& result) {
4628 *stream << Indent(4) <<
"{\n";
4629 OutputJsonKey(stream,
"testsuite",
"name",
"NonTestSuiteFailure", Indent(6));
4630 OutputJsonKey(stream,
"testsuite",
"tests", 1, Indent(6));
4631 if (!GTEST_FLAG_GET(list_tests)) {
4632 OutputJsonKey(stream,
"testsuite",
"failures", 1, Indent(6));
4633 OutputJsonKey(stream,
"testsuite",
"disabled", 0, Indent(6));
4634 OutputJsonKey(stream,
"testsuite",
"skipped", 0, Indent(6));
4635 OutputJsonKey(stream,
"testsuite",
"errors", 0, Indent(6));
4636 OutputJsonKey(stream,
"testsuite",
"time",
4637 FormatTimeInMillisAsDuration(result.elapsed_time()),
4639 OutputJsonKey(stream,
"testsuite",
"timestamp",
4640 FormatEpochTimeInMillisAsRFC3339(result.start_timestamp()),
4643 *stream << Indent(6) <<
"\"testsuite\": [\n";
4646 *stream << Indent(8) <<
"{\n";
4647 OutputJsonKey(stream,
"testcase",
"name",
"", Indent(10));
4648 OutputJsonKey(stream,
"testcase",
"status",
"RUN", Indent(10));
4649 OutputJsonKey(stream,
"testcase",
"result",
"COMPLETED", Indent(10));
4650 OutputJsonKey(stream,
"testcase",
"timestamp",
4651 FormatEpochTimeInMillisAsRFC3339(result.start_timestamp()),
4653 OutputJsonKey(stream,
"testcase",
"time",
4654 FormatTimeInMillisAsDuration(result.elapsed_time()),
4656 OutputJsonKey(stream,
"testcase",
"classname",
"", Indent(10),
false);
4657 *stream << TestPropertiesAsJson(result, Indent(10));
4660 OutputJsonTestResult(stream, result);
4663 *stream <<
"\n" << Indent(6) <<
"]\n" << Indent(4) <<
"}";
4667void JsonUnitTestResultPrinter::OutputJsonTestInfo(::std::ostream* stream,
4668 const char* test_suite_name,
4669 const TestInfo& test_info) {
4670 const TestResult& result = *test_info.result();
4671 const std::string kTestsuite =
"testcase";
4672 const std::string kIndent = Indent(10);
4674 *stream << Indent(8) <<
"{\n";
4675 OutputJsonKey(stream, kTestsuite,
"name", test_info.name(), kIndent);
4677 if (test_info.value_param() !=
nullptr) {
4678 OutputJsonKey(stream, kTestsuite,
"value_param", test_info.value_param(),
4681 if (test_info.type_param() !=
nullptr) {
4682 OutputJsonKey(stream, kTestsuite,
"type_param", test_info.type_param(),
4686 OutputJsonKey(stream, kTestsuite,
"file", test_info.file(), kIndent);
4687 OutputJsonKey(stream, kTestsuite,
"line", test_info.line(), kIndent,
false);
4688 if (GTEST_FLAG_GET(list_tests)) {
4689 *stream <<
"\n" << Indent(8) <<
"}";
4695 OutputJsonKey(stream, kTestsuite,
"status",
4696 test_info.should_run() ?
"RUN" :
"NOTRUN", kIndent);
4697 OutputJsonKey(stream, kTestsuite,
"result",
4698 test_info.should_run()
4699 ? (result.Skipped() ?
"SKIPPED" :
"COMPLETED")
4702 OutputJsonKey(stream, kTestsuite,
"timestamp",
4703 FormatEpochTimeInMillisAsRFC3339(result.start_timestamp()),
4705 OutputJsonKey(stream, kTestsuite,
"time",
4706 FormatTimeInMillisAsDuration(result.elapsed_time()), kIndent);
4707 OutputJsonKey(stream, kTestsuite,
"classname", test_suite_name, kIndent,
4709 *stream << TestPropertiesAsJson(result, kIndent);
4711 OutputJsonTestResult(stream, result);
4714void JsonUnitTestResultPrinter::OutputJsonTestResult(::std::ostream* stream,
4715 const TestResult& result) {
4716 const std::string kIndent = Indent(10);
4719 for (
int i = 0; i < result.total_part_count(); ++i) {
4720 const TestPartResult& part = result.GetTestPartResult(i);
4721 if (part.failed()) {
4723 if (++failures == 1) {
4724 *stream << kIndent <<
"\""
4728 const std::string location =
4729 internal::FormatCompilerIndependentFileLocation(part.file_name(),
4730 part.line_number());
4731 const std::string message = EscapeJson(location +
"\n" + part.message());
4732 *stream << kIndent <<
" {\n"
4733 << kIndent <<
" \"failure\": \"" << message <<
"\",\n"
4734 << kIndent <<
" \"type\": \"\"\n"
4739 if (failures > 0) *stream <<
"\n" << kIndent <<
"]";
4740 *stream <<
"\n" << Indent(8) <<
"}";
4744void JsonUnitTestResultPrinter::PrintJsonTestSuite(
4745 std::ostream* stream,
const TestSuite& test_suite) {
4746 const std::string kTestsuite =
"testsuite";
4747 const std::string kIndent = Indent(6);
4749 *stream << Indent(4) <<
"{\n";
4750 OutputJsonKey(stream, kTestsuite,
"name", test_suite.name(), kIndent);
4751 OutputJsonKey(stream, kTestsuite,
"tests", test_suite.reportable_test_count(),
4753 if (!GTEST_FLAG_GET(list_tests)) {
4754 OutputJsonKey(stream, kTestsuite,
"failures",
4755 test_suite.failed_test_count(), kIndent);
4756 OutputJsonKey(stream, kTestsuite,
"disabled",
4757 test_suite.reportable_disabled_test_count(), kIndent);
4758 OutputJsonKey(stream, kTestsuite,
"errors", 0, kIndent);
4760 stream, kTestsuite,
"timestamp",
4761 FormatEpochTimeInMillisAsRFC3339(test_suite.start_timestamp()),
4763 OutputJsonKey(stream, kTestsuite,
"time",
4764 FormatTimeInMillisAsDuration(test_suite.elapsed_time()),
4766 *stream << TestPropertiesAsJson(test_suite.ad_hoc_test_result(), kIndent)
4770 *stream << kIndent <<
"\"" << kTestsuite <<
"\": [\n";
4773 for (
int i = 0; i < test_suite.total_test_count(); ++i) {
4774 if (test_suite.GetTestInfo(i)->is_reportable()) {
4780 OutputJsonTestInfo(stream, test_suite.name(), *test_suite.GetTestInfo(i));
4783 *stream <<
"\n" << kIndent <<
"]\n" << Indent(4) <<
"}";
4787void JsonUnitTestResultPrinter::PrintJsonUnitTest(std::ostream* stream,
4788 const UnitTest& unit_test) {
4789 const std::string kTestsuites =
"testsuites";
4790 const std::string kIndent = Indent(2);
4793 OutputJsonKey(stream, kTestsuites,
"tests", unit_test.reportable_test_count(),
4795 OutputJsonKey(stream, kTestsuites,
"failures", unit_test.failed_test_count(),
4797 OutputJsonKey(stream, kTestsuites,
"disabled",
4798 unit_test.reportable_disabled_test_count(), kIndent);
4799 OutputJsonKey(stream, kTestsuites,
"errors", 0, kIndent);
4800 if (GTEST_FLAG_GET(shuffle)) {
4801 OutputJsonKey(stream, kTestsuites,
"random_seed", unit_test.random_seed(),
4804 OutputJsonKey(stream, kTestsuites,
"timestamp",
4805 FormatEpochTimeInMillisAsRFC3339(unit_test.start_timestamp()),
4807 OutputJsonKey(stream, kTestsuites,
"time",
4808 FormatTimeInMillisAsDuration(unit_test.elapsed_time()), kIndent,
4811 *stream << TestPropertiesAsJson(unit_test.ad_hoc_test_result(), kIndent)
4814 OutputJsonKey(stream, kTestsuites,
"name",
"AllTests", kIndent);
4815 *stream << kIndent <<
"\"" << kTestsuites <<
"\": [\n";
4818 for (
int i = 0; i < unit_test.total_test_suite_count(); ++i) {
4819 if (unit_test.GetTestSuite(i)->reportable_test_count() > 0) {
4825 PrintJsonTestSuite(stream, *unit_test.GetTestSuite(i));
4831 if (unit_test.ad_hoc_test_result().Failed()) {
4835 OutputJsonTestSuiteForTestResult(stream, unit_test.ad_hoc_test_result());
4843void JsonUnitTestResultPrinter::PrintJsonTestList(
4844 std::ostream* stream,
const std::vector<TestSuite*>& test_suites) {
4845 const std::string kTestsuites =
"testsuites";
4846 const std::string kIndent = Indent(2);
4848 int total_tests = 0;
4849 for (
auto test_suite : test_suites) {
4850 total_tests += test_suite->total_test_count();
4852 OutputJsonKey(stream, kTestsuites,
"tests", total_tests, kIndent);
4854 OutputJsonKey(stream, kTestsuites,
"name",
"AllTests", kIndent);
4855 *stream << kIndent <<
"\"" << kTestsuites <<
"\": [\n";
4857 for (
size_t i = 0; i < test_suites.size(); ++i) {
4861 PrintJsonTestSuite(stream, *test_suites[i]);
4870std::string JsonUnitTestResultPrinter::TestPropertiesAsJson(
4871 const TestResult& result,
const std::string& indent) {
4873 for (
int i = 0; i < result.test_property_count(); ++i) {
4874 const TestProperty&
property = result.GetTestProperty(i);
4876 << indent <<
"\"" <<
property.key() <<
"\": "
4877 <<
"\"" << EscapeJson(property.value()) <<
"\"";
4879 return attributes.GetString();
4884#if GTEST_CAN_STREAM_RESULTS_
4891std::string StreamingListener::UrlEncode(
const char* str) {
4893 result.reserve(strlen(str) + 1);
4894 for (
char ch = *str; ch !=
'\0'; ch = *++str) {
4900 result.append(
"%" + String::FormatByte(
static_cast<unsigned char>(ch)));
4903 result.push_back(ch);
4910void StreamingListener::SocketWriter::MakeConnection() {
4911 GTEST_CHECK_(sockfd_ == -1)
4912 <<
"MakeConnection() can't be called when there is already a connection.";
4915 memset(&hints, 0,
sizeof(hints));
4916 hints.ai_family = AF_UNSPEC;
4917 hints.ai_socktype = SOCK_STREAM;
4918 addrinfo* servinfo =
nullptr;
4922 const int error_num =
4923 getaddrinfo(host_name_.c_str(), port_num_.c_str(), &hints, &servinfo);
4924 if (error_num != 0) {
4925 GTEST_LOG_(WARNING) <<
"stream_result_to: getaddrinfo() failed: "
4926 << gai_strerror(error_num);
4930 for (addrinfo* cur_addr = servinfo; sockfd_ == -1 && cur_addr !=
nullptr;
4931 cur_addr = cur_addr->ai_next) {
4932 sockfd_ = socket(cur_addr->ai_family, cur_addr->ai_socktype,
4933 cur_addr->ai_protocol);
4934 if (sockfd_ != -1) {
4936 if (connect(sockfd_, cur_addr->ai_addr, cur_addr->ai_addrlen) == -1) {
4943 freeaddrinfo(servinfo);
4945 if (sockfd_ == -1) {
4946 GTEST_LOG_(WARNING) <<
"stream_result_to: failed to connect to "
4947 << host_name_ <<
":" << port_num_;
4956const char*
const OsStackTraceGetterInterface::kElidedFramesMarker =
4957 "... " GTEST_NAME_
" internal frames ...";
4959std::string OsStackTraceGetter::CurrentStackTrace(
int max_depth,
int skip_count)
4960 GTEST_LOCK_EXCLUDED_(mutex_) {
4964 if (max_depth <= 0) {
4968 max_depth = std::min(max_depth, kMaxStackTraceDepth);
4970 std::vector<void*> raw_stack(max_depth);
4972 const int raw_stack_size =
4973 absl::GetStackTrace(&raw_stack[0], max_depth, skip_count + 1);
4975 void* caller_frame =
nullptr;
4977 MutexLock lock(&mutex_);
4978 caller_frame = caller_frame_;
4981 for (
int i = 0; i < raw_stack_size; ++i) {
4982 if (raw_stack[i] == caller_frame &&
4983 !GTEST_FLAG_GET(show_internal_stack_frames)) {
4985 absl::StrAppend(&result, kElidedFramesMarker,
"\n");
4990 const char* symbol =
"(unknown)";
4991 if (absl::Symbolize(raw_stack[i], tmp,
sizeof(tmp))) {
4996 snprintf(line,
sizeof(line),
" %p: %s\n", raw_stack[i], symbol);
5003 static_cast<void>(max_depth);
5004 static_cast<void>(skip_count);
5009void OsStackTraceGetter::UponLeavingGTest() GTEST_LOCK_EXCLUDED_(mutex_) {
5011 void* caller_frame =
nullptr;
5012 if (absl::GetStackTrace(&caller_frame, 1, 3) <= 0) {
5013 caller_frame =
nullptr;
5016 MutexLock lock(&mutex_);
5017 caller_frame_ = caller_frame;
5026 : premature_exit_filepath_(
5027 premature_exit_filepath ? premature_exit_filepath :
"") {
5029 if (!premature_exit_filepath_.empty()) {
5033 FILE* pfile = posix::FOpen(premature_exit_filepath_.c_str(),
"w");
5034 fwrite(
"0", 1, 1, pfile);
5040#if !defined GTEST_OS_ESP8266
5041 if (!premature_exit_filepath_.empty()) {
5042 int retval = remove(premature_exit_filepath_.c_str());
5044 GTEST_LOG_(ERROR) <<
"Failed to remove premature exit filepath \""
5045 << premature_exit_filepath_ <<
"\" with error "
5053 const std::string premature_exit_filepath_;
5063TestEventListeners::TestEventListeners()
5064 : repeater_(new internal::TestEventRepeater()),
5065 default_result_printer_(nullptr),
5066 default_xml_generator_(nullptr) {}
5068TestEventListeners::~TestEventListeners() {
delete repeater_; }
5074void TestEventListeners::Append(TestEventListener* listener) {
5075 repeater_->Append(listener);
5081TestEventListener* TestEventListeners::Release(TestEventListener* listener) {
5082 if (listener == default_result_printer_)
5083 default_result_printer_ =
nullptr;
5084 else if (listener == default_xml_generator_)
5085 default_xml_generator_ =
nullptr;
5086 return repeater_->Release(listener);
5091TestEventListener* TestEventListeners::repeater() {
return repeater_; }
5098void TestEventListeners::SetDefaultResultPrinter(TestEventListener* listener) {
5099 if (default_result_printer_ != listener) {
5102 delete Release(default_result_printer_);
5103 default_result_printer_ = listener;
5104 if (listener !=
nullptr) Append(listener);
5113void TestEventListeners::SetDefaultXmlGenerator(TestEventListener* listener) {
5114 if (default_xml_generator_ != listener) {
5117 delete Release(default_xml_generator_);
5118 default_xml_generator_ = listener;
5119 if (listener !=
nullptr) Append(listener);
5125bool TestEventListeners::EventForwardingEnabled()
const {
5126 return repeater_->forwarding_enabled();
5129void TestEventListeners::SuppressEventForwarding() {
5130 repeater_->set_forwarding_enabled(
false);
5142UnitTest* UnitTest::GetInstance() {
5147#if defined(__BORLANDC__)
5148 static UnitTest*
const instance =
new UnitTest;
5151 static UnitTest instance;
5157int UnitTest::successful_test_suite_count()
const {
5158 return impl()->successful_test_suite_count();
5162int UnitTest::failed_test_suite_count()
const {
5163 return impl()->failed_test_suite_count();
5167int UnitTest::total_test_suite_count()
const {
5168 return impl()->total_test_suite_count();
5173int UnitTest::test_suite_to_run_count()
const {
5174 return impl()->test_suite_to_run_count();
5178#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
5179int UnitTest::successful_test_case_count()
const {
5180 return impl()->successful_test_suite_count();
5182int UnitTest::failed_test_case_count()
const {
5183 return impl()->failed_test_suite_count();
5185int UnitTest::total_test_case_count()
const {
5186 return impl()->total_test_suite_count();
5188int UnitTest::test_case_to_run_count()
const {
5189 return impl()->test_suite_to_run_count();
5194int UnitTest::successful_test_count()
const {
5195 return impl()->successful_test_count();
5199int UnitTest::skipped_test_count()
const {
5200 return impl()->skipped_test_count();
5204int UnitTest::failed_test_count()
const {
return impl()->failed_test_count(); }
5207int UnitTest::reportable_disabled_test_count()
const {
5208 return impl()->reportable_disabled_test_count();
5212int UnitTest::disabled_test_count()
const {
5213 return impl()->disabled_test_count();
5217int UnitTest::reportable_test_count()
const {
5218 return impl()->reportable_test_count();
5222int UnitTest::total_test_count()
const {
return impl()->total_test_count(); }
5225int UnitTest::test_to_run_count()
const {
return impl()->test_to_run_count(); }
5229internal::TimeInMillis UnitTest::start_timestamp()
const {
5230 return impl()->start_timestamp();
5234internal::TimeInMillis UnitTest::elapsed_time()
const {
5235 return impl()->elapsed_time();
5240bool UnitTest::Passed()
const {
return impl()->Passed(); }
5244bool UnitTest::Failed()
const {
return impl()->Failed(); }
5248const TestSuite* UnitTest::GetTestSuite(
int i)
const {
5249 return impl()->GetTestSuite(i);
5253#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
5254const TestCase* UnitTest::GetTestCase(
int i)
const {
5255 return impl()->GetTestCase(i);
5261const TestResult& UnitTest::ad_hoc_test_result()
const {
5262 return *impl()->ad_hoc_test_result();
5267TestSuite* UnitTest::GetMutableTestSuite(
int i) {
5268 return impl()->GetMutableSuiteCase(i);
5273TestEventListeners& UnitTest::listeners() {
return *impl()->listeners(); }
5285Environment* UnitTest::AddEnvironment(Environment* env) {
5286 if (env ==
nullptr) {
5290 impl_->environments().push_back(env);
5298void UnitTest::AddTestPartResult(TestPartResult::Type result_type,
5299 const char* file_name,
int line_number,
5300 const std::string& message,
5301 const std::string& os_stack_trace)
5302 GTEST_LOCK_EXCLUDED_(mutex_) {
5306 internal::MutexLock lock(&mutex_);
5307 if (impl_->gtest_trace_stack().size() > 0) {
5308 msg <<
"\n" << GTEST_NAME_ <<
" trace:";
5310 for (
size_t i = impl_->gtest_trace_stack().size(); i > 0; --i) {
5311 const internal::TraceInfo& trace = impl_->gtest_trace_stack()[i - 1];
5313 << internal::FormatFileLocation(trace.file, trace.line) <<
" "
5318 if (os_stack_trace.c_str() !=
nullptr && !os_stack_trace.empty()) {
5319 msg << internal::kStackTraceMarker << os_stack_trace;
5322 const TestPartResult result = TestPartResult(
5323 result_type, file_name, line_number, msg.GetString().c_str());
5324 impl_->GetTestPartResultReporterForCurrentThread()->ReportTestPartResult(
5327 if (result_type != TestPartResult::kSuccess &&
5328 result_type != TestPartResult::kSkip) {
5334 if (GTEST_FLAG_GET(break_on_failure)) {
5335#if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_PHONE && !GTEST_OS_WINDOWS_RT
5340#elif (!defined(__native_client__)) && \
5341 ((defined(__clang__) || defined(__GNUC__)) && \
5342 (defined(__x86_64__) || defined(__i386__)))
5345#elif GTEST_HAS_BUILTIN(__builtin_trap)
5347#elif defined(SIGTRAP)
5353 *
static_cast<volatile int*
>(
nullptr) = 1;
5355 }
else if (GTEST_FLAG_GET(throw_on_failure)) {
5356#if GTEST_HAS_EXCEPTIONS
5357 throw internal::GoogleTestFailureException(result);
5372void UnitTest::RecordProperty(
const std::string& key,
5373 const std::string& value) {
5374 impl_->RecordProperty(TestProperty(key, value));
5382int UnitTest::Run() {
5383 const bool in_death_test_child_process =
5384 GTEST_FLAG_GET(internal_run_death_test).length() > 0;
5407 const internal::ScopedPrematureExitFile premature_exit_file(
5408 in_death_test_child_process
5410 : internal::posix::GetEnv(
"TEST_PREMATURE_EXIT_FILE"));
5414 impl()->set_catch_exceptions(GTEST_FLAG_GET(catch_exceptions));
5421 if (impl()->catch_exceptions() || in_death_test_child_process) {
5422#if !GTEST_OS_WINDOWS_MOBILE && !GTEST_OS_WINDOWS_PHONE && !GTEST_OS_WINDOWS_RT
5424 SetErrorMode(SEM_FAILCRITICALERRORS | SEM_NOALIGNMENTFAULTEXCEPT |
5425 SEM_NOGPFAULTERRORBOX | SEM_NOOPENFILEERRORBOX);
5428#if (defined(_MSC_VER) || GTEST_OS_WINDOWS_MINGW) && !GTEST_OS_WINDOWS_MOBILE
5432 _set_error_mode(_OUT_TO_STDERR);
5435#if defined(_MSC_VER) && !GTEST_OS_WINDOWS_MOBILE
5441 if (!GTEST_FLAG_GET(break_on_failure))
5442 _set_abort_behavior(
5444 _WRITE_ABORT_MSG | _CALL_REPORTFAULT);
5450 if (!IsDebuggerPresent()) {
5451 (void)_CrtSetReportMode(_CRT_ASSERT,
5452 _CRTDBG_MODE_FILE | _CRTDBG_MODE_DEBUG);
5453 (void)_CrtSetReportFile(_CRT_ASSERT, _CRTDBG_FILE_STDERR);
5459 return internal::HandleExceptionsInMethodIfSupported(
5460 impl(), &internal::UnitTestImpl::RunAllTests,
5461 "auxiliary test code (environments or event listeners)")
5468const char* UnitTest::original_working_dir()
const {
5469 return impl_->original_working_dir_.c_str();
5474const TestSuite* UnitTest::current_test_suite() const
5475 GTEST_LOCK_EXCLUDED_(mutex_) {
5476 internal::MutexLock lock(&mutex_);
5477 return impl_->current_test_suite();
5481#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
5482const TestCase* UnitTest::current_test_case() const
5483 GTEST_LOCK_EXCLUDED_(mutex_) {
5484 internal::MutexLock lock(&mutex_);
5485 return impl_->current_test_suite();
5491const TestInfo* UnitTest::current_test_info() const
5492 GTEST_LOCK_EXCLUDED_(mutex_) {
5493 internal::MutexLock lock(&mutex_);
5494 return impl_->current_test_info();
5498int UnitTest::random_seed()
const {
return impl_->random_seed(); }
5502internal::ParameterizedTestSuiteRegistry&
5503UnitTest::parameterized_test_registry() GTEST_LOCK_EXCLUDED_(mutex_) {
5504 return impl_->parameterized_test_registry();
5508UnitTest::UnitTest() { impl_ =
new internal::UnitTestImpl(
this); }
5511UnitTest::~UnitTest() {
delete impl_; }
5515void UnitTest::PushGTestTrace(
const internal::TraceInfo& trace)
5516 GTEST_LOCK_EXCLUDED_(mutex_) {
5517 internal::MutexLock lock(&mutex_);
5518 impl_->gtest_trace_stack().push_back(trace);
5522void UnitTest::PopGTestTrace() GTEST_LOCK_EXCLUDED_(mutex_) {
5523 internal::MutexLock lock(&mutex_);
5524 impl_->gtest_trace_stack().pop_back();
5529UnitTestImpl::UnitTestImpl(UnitTest* parent)
5531 GTEST_DISABLE_MSC_WARNINGS_PUSH_(4355 )
5532 default_global_test_part_result_reporter_(this),
5533 default_per_thread_test_part_result_reporter_(this),
5534 GTEST_DISABLE_MSC_WARNINGS_POP_() global_test_part_result_reporter_(
5535 &default_global_test_part_result_reporter_),
5536 per_thread_test_part_result_reporter_(
5537 &default_per_thread_test_part_result_reporter_),
5538 parameterized_test_registry_(),
5539 parameterized_tests_registered_(false),
5540 last_death_test_suite_(-1),
5541 current_test_suite_(nullptr),
5542 current_test_info_(nullptr),
5543 ad_hoc_test_result_(),
5544 os_stack_trace_getter_(nullptr),
5545 post_flag_parse_init_performed_(false),
5548 start_timestamp_(0),
5550#if GTEST_HAS_DEATH_TEST
5551 death_test_factory_(new DefaultDeathTestFactory),
5554 catch_exceptions_(false) {
5555 listeners()->SetDefaultResultPrinter(
new PrettyUnitTestResultPrinter);
5558UnitTestImpl::~UnitTestImpl() {
5560 ForEach(test_suites_, internal::Delete<TestSuite>);
5563 ForEach(environments_, internal::Delete<Environment>);
5565 delete os_stack_trace_getter_;
5573void UnitTestImpl::RecordProperty(
const TestProperty& test_property) {
5574 std::string xml_element;
5575 TestResult* test_result;
5577 if (current_test_info_ !=
nullptr) {
5578 xml_element =
"testcase";
5579 test_result = &(current_test_info_->result_);
5580 }
else if (current_test_suite_ !=
nullptr) {
5581 xml_element =
"testsuite";
5582 test_result = &(current_test_suite_->ad_hoc_test_result_);
5584 xml_element =
"testsuites";
5585 test_result = &ad_hoc_test_result_;
5587 test_result->RecordProperty(xml_element, test_property);
5590#if GTEST_HAS_DEATH_TEST
5593void UnitTestImpl::SuppressTestEventsIfInSubprocess() {
5594 if (internal_run_death_test_flag_.get() !=
nullptr)
5595 listeners()->SuppressEventForwarding();
5601void UnitTestImpl::ConfigureXmlOutput() {
5602 const std::string& output_format = UnitTestOptions::GetOutputFormat();
5603 if (output_format ==
"xml") {
5604 listeners()->SetDefaultXmlGenerator(
new XmlUnitTestResultPrinter(
5605 UnitTestOptions::GetAbsolutePathToOutputFile().c_str()));
5606 }
else if (output_format ==
"json") {
5607 listeners()->SetDefaultXmlGenerator(
new JsonUnitTestResultPrinter(
5608 UnitTestOptions::GetAbsolutePathToOutputFile().c_str()));
5609 }
else if (output_format !=
"") {
5610 GTEST_LOG_(WARNING) <<
"WARNING: unrecognized output format \""
5611 << output_format <<
"\" ignored.";
5615#if GTEST_CAN_STREAM_RESULTS_
5618void UnitTestImpl::ConfigureStreamingOutput() {
5619 const std::string& target = GTEST_FLAG_GET(stream_result_to);
5620 if (!target.empty()) {
5621 const size_t pos = target.find(
':');
5622 if (pos != std::string::npos) {
5623 listeners()->Append(
5624 new StreamingListener(target.substr(0, pos), target.substr(pos + 1)));
5626 GTEST_LOG_(WARNING) <<
"unrecognized streaming target \"" << target
5638void UnitTestImpl::PostFlagParsingInit() {
5640 if (!post_flag_parse_init_performed_) {
5641 post_flag_parse_init_performed_ =
true;
5643#if defined(GTEST_CUSTOM_TEST_EVENT_LISTENER_)
5645 listeners()->Append(
new GTEST_CUSTOM_TEST_EVENT_LISTENER_());
5648#if GTEST_HAS_DEATH_TEST
5649 InitDeathTestSubprocessControlInfo();
5650 SuppressTestEventsIfInSubprocess();
5656 RegisterParameterizedTests();
5660 ConfigureXmlOutput();
5662 if (GTEST_FLAG_GET(brief)) {
5663 listeners()->SetDefaultResultPrinter(
new BriefUnitTestResultPrinter);
5666#if GTEST_CAN_STREAM_RESULTS_
5668 ConfigureStreamingOutput();
5672 if (GTEST_FLAG_GET(install_failure_signal_handler)) {
5673 absl::FailureSignalHandlerOptions options;
5674 absl::InstallFailureSignalHandler(options);
5694 bool operator()(
const TestSuite* test_suite)
const {
5695 return test_suite !=
nullptr &&
5696 strcmp(test_suite->name(), name_.c_str()) == 0;
5716 const char* test_suite_name,
const char* type_param,
5717 internal::SetUpTestSuiteFunc set_up_tc,
5718 internal::TearDownTestSuiteFunc tear_down_tc) {
5720 const auto test_suite =
5721 std::find_if(test_suites_.rbegin(), test_suites_.rend(),
5724 if (test_suite != test_suites_.rend())
return *test_suite;
5727 auto*
const new_test_suite =
5728 new TestSuite(test_suite_name, type_param, set_up_tc, tear_down_tc);
5730 const UnitTestFilter death_test_suite_filter(kDeathTestSuiteFilter);
5732 if (death_test_suite_filter.MatchesName(test_suite_name)) {
5737 ++last_death_test_suite_;
5738 test_suites_.insert(test_suites_.begin() + last_death_test_suite_,
5742 test_suites_.push_back(new_test_suite);
5745 test_suite_indices_.push_back(
static_cast<int>(test_suite_indices_.size()));
5746 return new_test_suite;
5751static void SetUpEnvironment(Environment* env) { env->SetUp(); }
5752static void TearDownEnvironment(Environment* env) { env->TearDown(); }
5763bool UnitTestImpl::RunAllTests() {
5766 const bool gtest_is_initialized_before_run_all_tests = GTestIsInitialized();
5769 if (g_help_flag)
return true;
5773 PostFlagParsingInit();
5778 internal::WriteToShardStatusFileIfNeeded();
5782 bool in_subprocess_for_death_test =
false;
5784#if GTEST_HAS_DEATH_TEST
5785 in_subprocess_for_death_test =
5786 (internal_run_death_test_flag_.get() !=
nullptr);
5787#if defined(GTEST_EXTRA_DEATH_TEST_CHILD_SETUP_)
5788 if (in_subprocess_for_death_test) {
5789 GTEST_EXTRA_DEATH_TEST_CHILD_SETUP_();
5794 const bool should_shard = ShouldShard(kTestTotalShards, kTestShardIndex,
5795 in_subprocess_for_death_test);
5799 const bool has_tests_to_run =
5800 FilterTests(should_shard ? HONOR_SHARDING_PROTOCOL
5801 : IGNORE_SHARDING_PROTOCOL) > 0;
5804 if (GTEST_FLAG_GET(list_tests)) {
5806 ListTestsMatchingFilter();
5810 random_seed_ = GetRandomSeedFromFlag(GTEST_FLAG_GET(random_seed));
5813 bool failed =
false;
5815 TestEventListener* repeater = listeners()->repeater();
5817 start_timestamp_ = GetTimeInMillis();
5818 repeater->OnTestProgramStart(*parent_);
5822 const int repeat = in_subprocess_for_death_test ? 1 : GTEST_FLAG_GET(repeat);
5825 const bool gtest_repeat_forever = repeat < 0;
5833 const bool recreate_environments_when_repeating =
5834 GTEST_FLAG_GET(recreate_environments_when_repeating) ||
5835 gtest_repeat_forever;
5837 for (
int i = 0; gtest_repeat_forever || i != repeat; i++) {
5840 ClearNonAdHocTestResult();
5845 if (has_tests_to_run && GTEST_FLAG_GET(shuffle)) {
5846 random()->Reseed(
static_cast<uint32_t
>(random_seed_));
5854 repeater->OnTestIterationStart(*parent_, i);
5857 if (has_tests_to_run) {
5860 if (i == 0 || recreate_environments_when_repeating) {
5861 repeater->OnEnvironmentsSetUpStart(*parent_);
5862 ForEach(environments_, SetUpEnvironment);
5863 repeater->OnEnvironmentsSetUpEnd(*parent_);
5868 if (Test::IsSkipped()) {
5871 TestResult& test_result =
5872 *internal::GetUnitTestImpl()->current_test_result();
5873 for (
int j = 0; j < test_result.total_part_count(); ++j) {
5874 const TestPartResult& test_part_result =
5875 test_result.GetTestPartResult(j);
5876 if (test_part_result.type() == TestPartResult::kSkip) {
5877 const std::string& result = test_part_result.message();
5878 printf(
"%s\n", result.c_str());
5882 }
else if (!Test::HasFatalFailure()) {
5883 for (
int test_index = 0; test_index < total_test_suite_count();
5885 GetMutableSuiteCase(test_index)->Run();
5886 if (GTEST_FLAG_GET(fail_fast) &&
5887 GetMutableSuiteCase(test_index)->Failed()) {
5888 for (
int j = test_index + 1; j < total_test_suite_count(); j++) {
5889 GetMutableSuiteCase(j)->Skip();
5894 }
else if (Test::HasFatalFailure()) {
5898 for (
int test_index = 0; test_index < total_test_suite_count();
5900 GetMutableSuiteCase(test_index)->Skip();
5907 if (i == repeat - 1 || recreate_environments_when_repeating) {
5908 repeater->OnEnvironmentsTearDownStart(*parent_);
5909 std::for_each(environments_.rbegin(), environments_.rend(),
5910 TearDownEnvironment);
5911 repeater->OnEnvironmentsTearDownEnd(*parent_);
5915 elapsed_time_ = timer.Elapsed();
5918 repeater->OnTestIterationEnd(*parent_, i);
5933 if (GTEST_FLAG_GET(shuffle)) {
5935 random_seed_ = GetNextRandomSeed(random_seed_);
5939 repeater->OnTestProgramEnd(*parent_);
5941 if (!gtest_is_initialized_before_run_all_tests) {
5944 "\nIMPORTANT NOTICE - DO NOT IGNORE:\n"
5945 "This test program did NOT call " GTEST_INIT_GOOGLE_TEST_NAME_
5946 "() before calling RUN_ALL_TESTS(). This is INVALID. Soon " GTEST_NAME_
5947 " will start to enforce the valid usage. "
5948 "Please fix it ASAP, or IT WILL START TO FAIL.\n");
5949#if GTEST_FOR_GOOGLE_
5950 ColoredPrintf(GTestColor::kRed,
5951 "For more details, see http://wiki/Main/ValidGUnitMain.\n");
5962void WriteToShardStatusFileIfNeeded() {
5963 const char*
const test_shard_file = posix::GetEnv(kTestShardStatusFile);
5964 if (test_shard_file !=
nullptr) {
5965 FILE*
const file = posix::FOpen(test_shard_file,
"w");
5966 if (file ==
nullptr) {
5967 ColoredPrintf(GTestColor::kRed,
5968 "Could not write to the test shard status file \"%s\" "
5969 "specified by the %s environment variable.\n",
5970 test_shard_file, kTestShardStatusFile);
5984bool ShouldShard(
const char* total_shards_env,
const char* shard_index_env,
5985 bool in_subprocess_for_death_test) {
5986 if (in_subprocess_for_death_test) {
5990 const int32_t total_shards = Int32FromEnvOrDie(total_shards_env, -1);
5991 const int32_t shard_index = Int32FromEnvOrDie(shard_index_env, -1);
5993 if (total_shards == -1 && shard_index == -1) {
5995 }
else if (total_shards == -1 && shard_index != -1) {
5996 const Message msg = Message() <<
"Invalid environment variables: you have "
5997 << kTestShardIndex <<
" = " << shard_index
5998 <<
", but have left " << kTestTotalShards
6000 ColoredPrintf(GTestColor::kRed,
"%s", msg.GetString().c_str());
6003 }
else if (total_shards != -1 && shard_index == -1) {
6004 const Message msg = Message()
6005 <<
"Invalid environment variables: you have "
6006 << kTestTotalShards <<
" = " << total_shards
6007 <<
", but have left " << kTestShardIndex <<
" unset.\n";
6008 ColoredPrintf(GTestColor::kRed,
"%s", msg.GetString().c_str());
6011 }
else if (shard_index < 0 || shard_index >= total_shards) {
6013 Message() <<
"Invalid environment variables: we require 0 <= "
6014 << kTestShardIndex <<
" < " << kTestTotalShards
6015 <<
", but you have " << kTestShardIndex <<
"=" << shard_index
6016 <<
", " << kTestTotalShards <<
"=" << total_shards <<
".\n";
6017 ColoredPrintf(GTestColor::kRed,
"%s", msg.GetString().c_str());
6022 return total_shards > 1;
6028int32_t Int32FromEnvOrDie(
const char* var, int32_t default_val) {
6029 const char* str_val = posix::GetEnv(var);
6030 if (str_val ==
nullptr) {
6035 if (!ParseInt32(Message() <<
"The value of environment variable " << var,
6036 str_val, &result)) {
6046bool ShouldRunTestOnShard(
int total_shards,
int shard_index,
int test_id) {
6047 return (test_id % total_shards) == shard_index;
6057int UnitTestImpl::FilterTests(ReactionToSharding shard_tests) {
6058 const int32_t total_shards = shard_tests == HONOR_SHARDING_PROTOCOL
6059 ? Int32FromEnvOrDie(kTestTotalShards, -1)
6061 const int32_t shard_index = shard_tests == HONOR_SHARDING_PROTOCOL
6062 ? Int32FromEnvOrDie(kTestShardIndex, -1)
6065 const PositiveAndNegativeUnitTestFilter gtest_flag_filter(
6066 GTEST_FLAG_GET(filter));
6067 const UnitTestFilter disable_test_filter(kDisableTestFilter);
6072 int num_runnable_tests = 0;
6073 int num_selected_tests = 0;
6074 for (
auto* test_suite : test_suites_) {
6075 const std::string& test_suite_name = test_suite->name();
6076 test_suite->set_should_run(
false);
6078 for (
size_t j = 0; j < test_suite->test_info_list().size(); j++) {
6079 TestInfo*
const test_info = test_suite->test_info_list()[j];
6080 const std::string test_name(test_info->name());
6083 const bool is_disabled =
6084 disable_test_filter.MatchesName(test_suite_name) ||
6085 disable_test_filter.MatchesName(test_name);
6086 test_info->is_disabled_ = is_disabled;
6088 const bool matches_filter =
6089 gtest_flag_filter.MatchesTest(test_suite_name, test_name);
6090 test_info->matches_filter_ = matches_filter;
6092 const bool is_runnable =
6093 (GTEST_FLAG_GET(also_run_disabled_tests) || !is_disabled) &&
6096 const bool is_in_another_shard =
6097 shard_tests != IGNORE_SHARDING_PROTOCOL &&
6098 !ShouldRunTestOnShard(total_shards, shard_index, num_runnable_tests);
6099 test_info->is_in_another_shard_ = is_in_another_shard;
6100 const bool is_selected = is_runnable && !is_in_another_shard;
6102 num_runnable_tests += is_runnable;
6103 num_selected_tests += is_selected;
6105 test_info->should_run_ = is_selected;
6106 test_suite->set_should_run(test_suite->should_run() || is_selected);
6109 return num_selected_tests;
6116static void PrintOnOneLine(
const char* str,
int max_length) {
6117 if (str !=
nullptr) {
6118 for (
int i = 0; *str !=
'\0'; ++str) {
6119 if (i >= max_length) {
6135void UnitTestImpl::ListTestsMatchingFilter() {
6137 const int kMaxParamLength = 250;
6139 for (
auto* test_suite : test_suites_) {
6140 bool printed_test_suite_name =
false;
6142 for (
size_t j = 0; j < test_suite->test_info_list().size(); j++) {
6143 const TestInfo*
const test_info = test_suite->test_info_list()[j];
6144 if (test_info->matches_filter_) {
6145 if (!printed_test_suite_name) {
6146 printed_test_suite_name =
true;
6147 printf(
"%s.", test_suite->name());
6148 if (test_suite->type_param() !=
nullptr) {
6149 printf(
" # %s = ", kTypeParamLabel);
6152 PrintOnOneLine(test_suite->type_param(), kMaxParamLength);
6156 printf(
" %s", test_info->name());
6157 if (test_info->value_param() !=
nullptr) {
6158 printf(
" # %s = ", kValueParamLabel);
6161 PrintOnOneLine(test_info->value_param(), kMaxParamLength);
6168 const std::string& output_format = UnitTestOptions::GetOutputFormat();
6169 if (output_format ==
"xml" || output_format ==
"json") {
6170 FILE* fileout = OpenFileForWriting(
6171 UnitTestOptions::GetAbsolutePathToOutputFile().c_str());
6172 std::stringstream stream;
6173 if (output_format ==
"xml") {
6174 XmlUnitTestResultPrinter(
6175 UnitTestOptions::GetAbsolutePathToOutputFile().c_str())
6176 .PrintXmlTestsList(&stream, test_suites_);
6177 }
else if (output_format ==
"json") {
6178 JsonUnitTestResultPrinter(
6179 UnitTestOptions::GetAbsolutePathToOutputFile().c_str())
6180 .PrintJsonTestList(&stream, test_suites_);
6182 fprintf(fileout,
"%s", StringStreamToString(&stream).c_str());
6192void UnitTestImpl::set_os_stack_trace_getter(
6193 OsStackTraceGetterInterface* getter) {
6194 if (os_stack_trace_getter_ != getter) {
6195 delete os_stack_trace_getter_;
6196 os_stack_trace_getter_ = getter;
6203OsStackTraceGetterInterface* UnitTestImpl::os_stack_trace_getter() {
6204 if (os_stack_trace_getter_ ==
nullptr) {
6205#ifdef GTEST_OS_STACK_TRACE_GETTER_
6206 os_stack_trace_getter_ =
new GTEST_OS_STACK_TRACE_GETTER_;
6208 os_stack_trace_getter_ =
new OsStackTraceGetter;
6212 return os_stack_trace_getter_;
6216TestResult* UnitTestImpl::current_test_result() {
6217 if (current_test_info_ !=
nullptr) {
6218 return ¤t_test_info_->result_;
6220 if (current_test_suite_ !=
nullptr) {
6221 return ¤t_test_suite_->ad_hoc_test_result_;
6223 return &ad_hoc_test_result_;
6228void UnitTestImpl::ShuffleTests() {
6230 ShuffleRange(random(), 0, last_death_test_suite_ + 1, &test_suite_indices_);
6233 ShuffleRange(random(), last_death_test_suite_ + 1,
6234 static_cast<int>(test_suites_.size()), &test_suite_indices_);
6237 for (
auto& test_suite : test_suites_) {
6238 test_suite->ShuffleTests(random());
6243void UnitTestImpl::UnshuffleTests() {
6244 for (
size_t i = 0; i < test_suites_.size(); i++) {
6246 test_suites_[i]->UnshuffleTests();
6248 test_suite_indices_[i] =
static_cast<int>(i);
6262GTEST_NO_INLINE_ GTEST_NO_TAIL_CALL_ std::string
6263GetCurrentOsStackTraceExceptTop(
int skip_count) {
6266 return GetUnitTestImpl()->CurrentOsStackTraceExceptTop(skip_count + 1);
6272class ClassUniqueToAlwaysTrue {};
6275bool IsTrue(
bool condition) {
return condition; }
6278#if GTEST_HAS_EXCEPTIONS
6281 if (IsTrue(
false))
throw ClassUniqueToAlwaysTrue();
6289bool SkipPrefix(
const char* prefix,
const char** pstr) {
6290 const size_t prefix_len = strlen(prefix);
6291 if (strncmp(*pstr, prefix, prefix_len) == 0) {
6292 *pstr += prefix_len;
6303static const char* ParseFlagValue(
const char* str,
const char* flag_name,
6304 bool def_optional) {
6306 if (str ==
nullptr || flag_name ==
nullptr)
return nullptr;
6309 const std::string flag_str =
6310 std::string(
"--") + GTEST_FLAG_PREFIX_ + flag_name;
6311 const size_t flag_len = flag_str.length();
6312 if (strncmp(str, flag_str.c_str(), flag_len) != 0)
return nullptr;
6315 const char* flag_end = str + flag_len;
6318 if (def_optional && (flag_end[0] ==
'\0')) {
6325 if (flag_end[0] !=
'=')
return nullptr;
6328 return flag_end + 1;
6341static bool ParseFlag(
const char* str,
const char* flag_name,
bool* value) {
6343 const char*
const value_str = ParseFlagValue(str, flag_name,
true);
6346 if (value_str ==
nullptr)
return false;
6349 *value = !(*value_str ==
'0' || *value_str ==
'f' || *value_str ==
'F');
6357bool ParseFlag(
const char* str,
const char* flag_name, int32_t* value) {
6359 const char*
const value_str = ParseFlagValue(str, flag_name,
false);
6362 if (value_str ==
nullptr)
return false;
6365 return ParseInt32(Message() <<
"The value of flag --" << flag_name, value_str,
6373template <
typename String>
6374static bool ParseFlag(
const char* str,
const char* flag_name, String* value) {
6376 const char*
const value_str = ParseFlagValue(str, flag_name,
false);
6379 if (value_str ==
nullptr)
return false;
6392static bool HasGoogleTestFlagPrefix(
const char* str) {
6393 return (SkipPrefix(
"--", &str) || SkipPrefix(
"-", &str) ||
6394 SkipPrefix(
"/", &str)) &&
6395 !SkipPrefix(GTEST_FLAG_PREFIX_
"internal_", &str) &&
6396 (SkipPrefix(GTEST_FLAG_PREFIX_, &str) ||
6397 SkipPrefix(GTEST_FLAG_PREFIX_DASH_, &str));
6409static void PrintColorEncoded(
const char* str) {
6410 GTestColor color = GTestColor::kDefault;
6417 const char* p = strchr(str,
'@');
6419 ColoredPrintf(color,
"%s", str);
6423 ColoredPrintf(color,
"%s", std::string(str, p).c_str());
6425 const char ch = p[1];
6428 ColoredPrintf(color,
"@");
6429 }
else if (ch ==
'D') {
6430 color = GTestColor::kDefault;
6431 }
else if (ch ==
'R') {
6432 color = GTestColor::kRed;
6433 }
else if (ch ==
'G') {
6434 color = GTestColor::kGreen;
6435 }
else if (ch ==
'Y') {
6436 color = GTestColor::kYellow;
6443static const char kColorEncodedHelpMessage[] =
6444 "This program contains tests written using " GTEST_NAME_
6445 ". You can use the\n"
6446 "following command line flags to control its behavior:\n"
6449 " @G--" GTEST_FLAG_PREFIX_
6451 " List the names of all tests instead of running them. The name of\n"
6452 " TEST(Foo, Bar) is \"Foo.Bar\".\n"
6453 " @G--" GTEST_FLAG_PREFIX_
6454 "filter=@YPOSITIVE_PATTERNS"
6455 "[@G-@YNEGATIVE_PATTERNS]@D\n"
6456 " Run only the tests whose name matches one of the positive patterns "
6458 " none of the negative patterns. '?' matches any single character; "
6460 " matches any substring; ':' separates two patterns.\n"
6461 " @G--" GTEST_FLAG_PREFIX_
6462 "also_run_disabled_tests@D\n"
6463 " Run all disabled tests too.\n"
6466 " @G--" GTEST_FLAG_PREFIX_
6467 "repeat=@Y[COUNT]@D\n"
6468 " Run the tests repeatedly; use a negative count to repeat forever.\n"
6469 " @G--" GTEST_FLAG_PREFIX_
6471 " Randomize tests' orders on every iteration.\n"
6472 " @G--" GTEST_FLAG_PREFIX_
6473 "random_seed=@Y[NUMBER]@D\n"
6474 " Random number seed to use for shuffling test orders (between 1 and\n"
6475 " 99999, or 0 to use a seed based on the current time).\n"
6476 " @G--" GTEST_FLAG_PREFIX_
6477 "recreate_environments_when_repeating@D\n"
6478 " Sets up and tears down the global test environment on each repeat\n"
6482 " @G--" GTEST_FLAG_PREFIX_
6483 "color=@Y(@Gyes@Y|@Gno@Y|@Gauto@Y)@D\n"
6484 " Enable/disable colored output. The default is @Gauto@D.\n"
6485 " @G--" GTEST_FLAG_PREFIX_
6487 " Only print test failures.\n"
6488 " @G--" GTEST_FLAG_PREFIX_
6490 " Don't print the elapsed time of each test.\n"
6491 " @G--" GTEST_FLAG_PREFIX_
6492 "output=@Y(@Gjson@Y|@Gxml@Y)[@G:@YDIRECTORY_PATH@G" GTEST_PATH_SEP_
6493 "@Y|@G:@YFILE_PATH]@D\n"
6494 " Generate a JSON or XML report in the given directory or with the "
6496 " file name. @YFILE_PATH@D defaults to @Gtest_detail.xml@D.\n"
6497#if GTEST_CAN_STREAM_RESULTS_
6498 " @G--" GTEST_FLAG_PREFIX_
6499 "stream_result_to=@YHOST@G:@YPORT@D\n"
6500 " Stream test results to the given server.\n"
6503 "Assertion Behavior:\n"
6504#if GTEST_HAS_DEATH_TEST && !GTEST_OS_WINDOWS
6505 " @G--" GTEST_FLAG_PREFIX_
6506 "death_test_style=@Y(@Gfast@Y|@Gthreadsafe@Y)@D\n"
6507 " Set the default death test style.\n"
6509 " @G--" GTEST_FLAG_PREFIX_
6510 "break_on_failure@D\n"
6511 " Turn assertion failures into debugger break-points.\n"
6512 " @G--" GTEST_FLAG_PREFIX_
6513 "throw_on_failure@D\n"
6514 " Turn assertion failures into C++ exceptions for use by an external\n"
6515 " test framework.\n"
6516 " @G--" GTEST_FLAG_PREFIX_
6517 "catch_exceptions=0@D\n"
6518 " Do not report exceptions as test failures. Instead, allow them\n"
6519 " to crash the program or throw a pop-up (on Windows).\n"
6521 "Except for @G--" GTEST_FLAG_PREFIX_
6522 "list_tests@D, you can alternatively set "
6523 "the corresponding\n"
6524 "environment variable of a flag (all letters in upper-case). For example, "
6526 "disable colored text output, you can either specify "
6527 "@G--" GTEST_FLAG_PREFIX_
6528 "color=no@D or set\n"
6529 "the @G" GTEST_FLAG_PREFIX_UPPER_
6530 "COLOR@D environment variable to @Gno@D.\n"
6532 "For more information, please read the " GTEST_NAME_
6533 " documentation at\n"
6534 "@G" GTEST_PROJECT_URL_
"@D. If you find a bug in " GTEST_NAME_
6536 "(not one in your own code or tests), please report it to\n"
6537 "@G<" GTEST_DEV_EMAIL_
">@D.\n";
6539static bool ParseGoogleTestFlag(
const char*
const arg) {
6540#define GTEST_INTERNAL_PARSE_FLAG(flag_name) \
6542 auto value = GTEST_FLAG_GET(flag_name); \
6543 if (ParseFlag(arg, #flag_name, &value)) { \
6544 GTEST_FLAG_SET(flag_name, value); \
6549 GTEST_INTERNAL_PARSE_FLAG(also_run_disabled_tests);
6550 GTEST_INTERNAL_PARSE_FLAG(break_on_failure);
6551 GTEST_INTERNAL_PARSE_FLAG(catch_exceptions);
6552 GTEST_INTERNAL_PARSE_FLAG(color);
6553 GTEST_INTERNAL_PARSE_FLAG(death_test_style);
6554 GTEST_INTERNAL_PARSE_FLAG(death_test_use_fork);
6555 GTEST_INTERNAL_PARSE_FLAG(fail_fast);
6556 GTEST_INTERNAL_PARSE_FLAG(filter);
6557 GTEST_INTERNAL_PARSE_FLAG(internal_run_death_test);
6558 GTEST_INTERNAL_PARSE_FLAG(list_tests);
6559 GTEST_INTERNAL_PARSE_FLAG(output);
6560 GTEST_INTERNAL_PARSE_FLAG(brief);
6561 GTEST_INTERNAL_PARSE_FLAG(print_time);
6562 GTEST_INTERNAL_PARSE_FLAG(print_utf8);
6563 GTEST_INTERNAL_PARSE_FLAG(random_seed);
6564 GTEST_INTERNAL_PARSE_FLAG(repeat);
6565 GTEST_INTERNAL_PARSE_FLAG(recreate_environments_when_repeating);
6566 GTEST_INTERNAL_PARSE_FLAG(shuffle);
6567 GTEST_INTERNAL_PARSE_FLAG(stack_trace_depth);
6568 GTEST_INTERNAL_PARSE_FLAG(stream_result_to);
6569 GTEST_INTERNAL_PARSE_FLAG(throw_on_failure);
6573#if GTEST_USE_OWN_FLAGFILE_FLAG_
6574static void LoadFlagsFromFile(
const std::string& path) {
6575 FILE* flagfile = posix::FOpen(path.c_str(),
"r");
6577 GTEST_LOG_(FATAL) <<
"Unable to open file \"" << GTEST_FLAG_GET(flagfile)
6580 std::string contents(ReadEntireFile(flagfile));
6581 posix::FClose(flagfile);
6582 std::vector<std::string> lines;
6583 SplitString(contents,
'\n', &lines);
6584 for (
size_t i = 0; i < lines.size(); ++i) {
6585 if (lines[i].empty())
continue;
6586 if (!ParseGoogleTestFlag(lines[i].c_str())) g_help_flag =
true;
6594template <
typename CharType>
6595void ParseGoogleTestFlagsOnlyImpl(
int* argc, CharType** argv) {
6596 std::string flagfile_value;
6597 for (
int i = 1; i < *argc; i++) {
6598 const std::string arg_string = StreamableToString(argv[i]);
6599 const char*
const arg = arg_string.c_str();
6601 using internal::ParseFlag;
6603 bool remove_flag =
false;
6604 if (ParseGoogleTestFlag(arg)) {
6606#if GTEST_USE_OWN_FLAGFILE_FLAG_
6607 }
else if (ParseFlag(arg,
"flagfile", &flagfile_value)) {
6608 GTEST_FLAG_SET(flagfile, flagfile_value);
6609 LoadFlagsFromFile(flagfile_value);
6612 }
else if (arg_string ==
"--help" || HasGoogleTestFlagPrefix(arg)) {
6623 for (
int j = i; j != *argc; j++) {
6624 argv[j] = argv[j + 1];
6640 PrintColorEncoded(kColorEncodedHelpMessage);
6646void ParseGoogleTestFlagsOnly(
int* argc,
char** argv) {
6650 auto positional_args = absl::flags_internal::ParseCommandLineImpl(
6651 *argc, argv, absl::flags_internal::ArgvListAction::kRemoveParsedArgs,
6652 absl::flags_internal::UsageFlagsAction::kHandleUsage,
6653 absl::flags_internal::OnUndefinedFlag::kReportUndefined);
6659 std::copy(positional_args.begin(), positional_args.end(), argv);
6660 if (
static_cast<int>(positional_args.size()) < *argc) {
6661 argv[positional_args.size()] =
nullptr;
6662 *argc =
static_cast<int>(positional_args.size());
6666 ParseGoogleTestFlagsOnlyImpl(argc, argv);
6674 if (*_NSGetArgv() == argv) {
6675 *_NSGetArgc() = *argc;
6680void ParseGoogleTestFlagsOnly(
int* argc,
wchar_t** argv) {
6681 ParseGoogleTestFlagsOnlyImpl(argc, argv);
6688template <
typename CharType>
6689void InitGoogleTestImpl(
int* argc, CharType** argv) {
6691 if (GTestIsInitialized())
return;
6693 if (*argc <= 0)
return;
6696 for (
int i = 0; i != *argc; i++) {
6697 g_argvs.push_back(StreamableToString(argv[i]));
6701 absl::InitializeSymbolizer(g_argvs[0].c_str());
6705 absl::SetProgramUsageMessage(absl::StrReplaceAll(
6706 kColorEncodedHelpMessage,
6707 {{
"@D",
""}, {
"@R",
""}, {
"@G",
""}, {
"@Y",
""}, {
"@@",
"@"}}));
6710 ParseGoogleTestFlagsOnly(argc, argv);
6711 GetUnitTestImpl()->PostFlagParsingInit();
6725void InitGoogleTest(
int* argc,
char** argv) {
6726#if defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_)
6727 GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_(argc, argv);
6729 internal::InitGoogleTestImpl(argc, argv);
6735void InitGoogleTest(
int* argc,
wchar_t** argv) {
6736#if defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_)
6737 GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_(argc, argv);
6739 internal::InitGoogleTestImpl(argc, argv);
6745void InitGoogleTest() {
6748 const auto arg0 =
"dummy";
6749 char* argv0 =
const_cast<char*
>(arg0);
6750 char** argv = &argv0;
6752#if defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_)
6753 GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_(&argc, argv);
6755 internal::InitGoogleTestImpl(&argc, argv);
6759#if !defined(GTEST_CUSTOM_TEMPDIR_FUNCTION_)
6764static std::string GetTempDirFromEnv(
6765 std::initializer_list<const char*> environment_variables,
6766 const char* fallback,
char separator) {
6767 for (
const char* variable_name : environment_variables) {
6768 const char* value = internal::posix::GetEnv(variable_name);
6769 if (value !=
nullptr && value[0] !=
'\0') {
6770 if (value[strlen(value) - 1] != separator) {
6771 return std::string(value).append(1, separator);
6780std::string TempDir() {
6781#if defined(GTEST_CUSTOM_TEMPDIR_FUNCTION_)
6782 return GTEST_CUSTOM_TEMPDIR_FUNCTION_();
6783#elif GTEST_OS_WINDOWS || GTEST_OS_WINDOWS_MOBILE
6784 return GetTempDirFromEnv({
"TEST_TMPDIR",
"TEMP"},
"\\temp\\",
'\\');
6785#elif GTEST_OS_LINUX_ANDROID
6786 return GetTempDirFromEnv({
"TEST_TMPDIR",
"TMPDIR"},
"/data/local/tmp/",
'/');
6788 return GetTempDirFromEnv({
"TEST_TMPDIR",
"TMPDIR"},
"/tmp/",
'/');
6796void ScopedTrace::PushTrace(
const char* file,
int line, std::string message) {
6797 internal::TraceInfo trace;
6800 trace.message.swap(message);
6802 UnitTest::GetInstance()->PushGTestTrace(trace);
6806ScopedTrace::~ScopedTrace() GTEST_LOCK_EXCLUDED_(&UnitTest::mutex_) {
6807 UnitTest::GetInstance()->PopGTestTrace();