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>
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"
191 FILE* fileout =
nullptr;
192 FilePath output_file_path(output_file);
193 FilePath output_dir(output_file_path.RemoveFileName());
195 if (output_dir.CreateDirectoriesRecursively()) {
196 fileout = posix::FOpen(output_file.c_str(),
"w");
198 if (fileout ==
nullptr) {
199 GTEST_LOG_(FATAL) <<
"Unable to open file \"" << output_file <<
"\"";
209 const char*
const testbridge_test_only =
210 internal::posix::GetEnv(
"TESTBRIDGE_TEST_ONLY");
211 if (testbridge_test_only !=
nullptr) {
212 return testbridge_test_only;
220 const char*
const testbridge_test_runner_fail_fast =
221 internal::posix::GetEnv(
"TESTBRIDGE_TEST_RUNNER_FAIL_FAST");
222 if (testbridge_test_runner_fail_fast !=
nullptr) {
223 return strcmp(testbridge_test_runner_fail_fast,
"1") == 0;
234 "True if and only if a test failure should stop further test execution.");
237 also_run_disabled_tests,
239 "Run disabled tests too, in addition to the tests normally being run.");
244 "True if and only if a failed assertion should be a debugger "
250 "True if and only if " GTEST_NAME_
251 " should catch exceptions and treat them as test failures.");
255 "Whether to use colors in the output. Valid values: yes, no, "
256 "and auto. 'auto' means to use colors if the output is "
257 "being sent to a terminal and the TERM environment variable "
258 "is set to a terminal type that supports colors.");
264 "A colon-separated list of glob (not regex) patterns "
265 "for filtering the tests to run, optionally followed by a "
266 "'-' and a : separated list of negative patterns (tests to "
267 "exclude). A test is run if it matches one of the positive "
268 "patterns and does not match any of the negative patterns.");
271 install_failure_signal_handler,
274 "If true and supported on the current platform, " GTEST_NAME_
276 "install a signal handler that dumps debugging information when fatal "
277 "signals are raised.");
290 "A format (defaults to \"xml\" but can be specified to be \"json\"), "
291 "optionally followed by a colon and an output file name or directory. "
292 "A directory is indicated by a trailing pathname separator. "
293 "Examples: \"xml:filename.xml\", \"xml::directoryname/\". "
294 "If a directory is specified, output files will be created "
295 "within that directory, with file-names based on the test "
296 "executable's name and, if necessary, made unique by adding "
301 "True if only test failures should be displayed in text output.");
305 "True if and only if " GTEST_NAME_
306 " should display elapsed time in text output.");
310 "True if and only if " GTEST_NAME_
311 " prints UTF8 characters as text.");
315 "Random number seed to use when shuffling test orders. Must be in range "
316 "[1, 99999], or 0 to use a seed based on the current time.");
320 "How many times to repeat each test. Specify a negative number "
321 "for repeating forever. Useful for shaking out flaky tests.");
324 recreate_environments_when_repeating,
327 "Controls whether global test environments are recreated for each repeat "
328 "of the tests. If set to false the global test environments are only set "
329 "up once, for the first iteration, and only torn down once, for the last. "
330 "Useful for shaking out flaky tests with stable, expensive test "
331 "environments. If --gtest_repeat is set to a negative number, meaning "
332 "there is no last run, the environments will always be recreated to avoid "
336 "True if and only if " GTEST_NAME_
337 " should include internal stack frames when "
338 "printing test failure stack traces.");
342 "True if and only if " GTEST_NAME_
343 " should randomize tests' order on every run.");
348 testing::kMaxStackTraceDepth),
349 "The maximum number of stack frames to print when an "
350 "assertion fails. The valid range is 0 through 100, inclusive.");
355 "This flag specifies the host name and the port number on which to stream "
356 "test results. Example: \"localhost:555\". The flag is effective only on "
362 "When this flag is specified, a failed assertion will throw an exception "
363 "if exceptions are enabled or exit the program with a non-zero code "
364 "otherwise. For use with an external test framework.");
366#if GTEST_USE_OWN_FLAGFILE_FLAG_
369 "This flag specifies the flagfile to read command-line flags from.");
378uint32_t Random::Generate(uint32_t range) {
381 state_ =
static_cast<uint32_t
>(1103515245ULL * state_ + 12345U) % kMaxRange;
383 GTEST_CHECK_(range > 0) <<
"Cannot generate a number in the range [0, 0).";
384 GTEST_CHECK_(range <= kMaxRange)
385 <<
"Generation of a number in [0, " << range <<
") was requested, "
386 <<
"but this can only generate numbers in [0, " << kMaxRange <<
").";
391 return state_ % range;
403 int (TestSuite::*method)() const) {
405 for (
size_t i = 0; i < case_list.size(); i++) {
406 sum += (case_list[i]->*method)();
413 return test_suite->should_run() && test_suite->Passed();
418 return test_suite->should_run() && test_suite->Failed();
424 return test_suite->should_run();
428AssertHelper::AssertHelper(TestPartResult::Type type,
const char* file,
429 int line,
const char* message)
430 : data_(new AssertHelperData(type, file, line, message)) {}
432AssertHelper::~AssertHelper() {
delete data_; }
435void AssertHelper::operator=(
const Message& message)
const {
436 UnitTest::GetInstance()->AddTestPartResult(
437 data_->type, data_->file, data_->line,
439 UnitTest::GetInstance()->impl()->CurrentOsStackTraceExceptTop(1)
451constexpr bool kErrorOnUninstantiatedParameterizedTest =
true;
452constexpr bool kErrorOnUninstantiatedTypeParameterizedTest =
true;
455class FailureTest :
public Test {
457 explicit FailureTest(
const CodeLocation& loc, std::string error_message,
460 error_message_(std::move(error_message)),
461 as_error_(as_error) {}
463 void TestBody()
override {
465 AssertHelper(TestPartResult::kNonFatalFailure, loc_.file.c_str(),
466 loc_.line,
"") = Message() << error_message_;
468 std::cout << error_message_ << std::endl;
473 const CodeLocation loc_;
474 const std::string error_message_;
475 const bool as_error_;
481 return UnitTest::GetInstance()->impl()->ignored_parameterized_test_suites();
485MarkAsIgnored::MarkAsIgnored(
const char* test_suite) {
486 GetIgnoredParameterizedTestSuites()->insert(test_suite);
494 if (ignored.find(name) != ignored.end())
return;
496 const char kMissingInstantiation[] =
497 " is defined via TEST_P, but never instantiated. None of the test cases "
498 "will run. Either no INSTANTIATE_TEST_SUITE_P is provided or the only "
499 "ones provided expand to nothing."
501 "Ideally, TEST_P definitions should only ever be included as part of "
502 "binaries that intend to use them. (As opposed to, for example, being "
503 "placed in a library that may be linked in to get other utilities.)";
505 const char kMissingTestCase[] =
506 " is instantiated via INSTANTIATE_TEST_SUITE_P, but no tests are "
507 "defined via TEST_P . No test cases will run."
509 "Ideally, INSTANTIATE_TEST_SUITE_P should only ever be invoked from "
510 "code that always depend on code that provides TEST_P. Failing to do "
511 "so is often an indication of dead code, e.g. the last TEST_P was "
512 "removed but the rest got left behind.";
514 std::string message =
515 "Parameterized test suite " + name +
516 (has_test_p ? kMissingInstantiation : kMissingTestCase) +
518 "To suppress this error for this test suite, insert the following line "
519 "(in a non-header) in the namespace it is defined in:"
521 "GTEST_ALLOW_UNINSTANTIATED_PARAMETERIZED_TEST(" +
524 std::string full_name =
"UninstantiatedParameterizedTestSuite<" + name +
">";
526 "GoogleTestVerification", full_name.c_str(),
529 location.file.c_str(), location.line, [message, location] {
530 return new FailureTest(location, message,
531 kErrorOnUninstantiatedParameterizedTest);
536 CodeLocation code_location) {
537 GetUnitTestImpl()->type_parameterized_test_registry().RegisterTestSuite(
538 test_suite_name, code_location);
542 GetUnitTestImpl()->type_parameterized_test_registry().RegisterInstantiation(
546void TypeParameterizedTestSuiteRegistry::RegisterTestSuite(
547 const char* test_suite_name, CodeLocation code_location) {
548 suites_.emplace(std::string(test_suite_name),
549 TypeParameterizedTestSuiteInfo(code_location));
552void TypeParameterizedTestSuiteRegistry::RegisterInstantiation(
553 const char* test_suite_name) {
554 auto it = suites_.find(std::string(test_suite_name));
555 if (it != suites_.end()) {
556 it->second.instantiated =
true;
558 GTEST_LOG_(ERROR) <<
"Unknown type parameterized test suit '"
559 << test_suite_name <<
"'";
563void TypeParameterizedTestSuiteRegistry::CheckForInstantiations() {
565 for (
const auto& testcase : suites_) {
566 if (testcase.second.instantiated)
continue;
567 if (ignored.find(testcase.first) != ignored.end())
continue;
569 std::string message =
570 "Type parameterized test suite " + testcase.first +
571 " is defined via REGISTER_TYPED_TEST_SUITE_P, but never instantiated "
572 "via INSTANTIATE_TYPED_TEST_SUITE_P. None of the test cases will run."
574 "Ideally, TYPED_TEST_P definitions should only ever be included as "
575 "part of binaries that intend to use them. (As opposed to, for "
576 "example, being placed in a library that may be linked in to get other "
579 "To suppress this error for this test suite, insert the following line "
580 "(in a non-header) in the namespace it is defined in:"
582 "GTEST_ALLOW_UNINSTANTIATED_PARAMETERIZED_TEST(" +
583 testcase.first +
");";
585 std::string full_name =
586 "UninstantiatedTypeParameterizedTestSuite<" + testcase.first +
">";
588 "GoogleTestVerification", full_name.c_str(),
591 testcase.second.code_location.file.c_str(),
592 testcase.second.code_location.line, [message, testcase] {
593 return new FailureTest(testcase.second.code_location, message,
594 kErrorOnUninstantiatedTypeParameterizedTest);
603#if defined(GTEST_CUSTOM_GET_ARGVS_)
606 const auto& custom = GTEST_CUSTOM_GET_ARGVS_();
607 return ::std::vector<std::string>(custom.begin(), custom.end());
618#if GTEST_OS_WINDOWS || GTEST_OS_OS2
619 result.Set(FilePath(
GetArgvs()[0]).RemoveExtension(
"exe"));
621 result.Set(FilePath(
GetArgvs()[0]));
624 return result.RemoveDirectoryName();
630std::string UnitTestOptions::GetOutputFormat() {
631 std::string s = GTEST_FLAG_GET(output);
632 const char*
const gtest_output_flag = s.c_str();
633 const char*
const colon = strchr(gtest_output_flag,
':');
634 return (colon ==
nullptr)
635 ? std::string(gtest_output_flag)
636 : std::string(gtest_output_flag,
637 static_cast<size_t>(colon - gtest_output_flag));
630std::string UnitTestOptions::GetOutputFormat() {
…}
642std::string UnitTestOptions::GetAbsolutePathToOutputFile() {
643 std::string s = GTEST_FLAG_GET(output);
644 const char*
const gtest_output_flag = s.c_str();
646 std::string format = GetOutputFormat();
649 const char*
const colon = strchr(gtest_output_flag,
':');
650 if (colon ==
nullptr)
651 return internal::FilePath::MakeFileName(
653 UnitTest::GetInstance()->original_working_dir()),
657 internal::FilePath output_name(colon + 1);
658 if (!output_name.IsAbsolutePath())
659 output_name = internal::FilePath::ConcatPaths(
660 internal::FilePath(UnitTest::GetInstance()->original_working_dir()),
661 internal::FilePath(colon + 1));
663 if (!output_name.IsDirectory())
return output_name.string();
665 internal::FilePath result(internal::FilePath::GenerateUniqueFileName(
667 GetOutputFormat().c_str()));
668 return result.string();
642std::string UnitTestOptions::GetAbsolutePathToOutputFile() {
…}
678 const char* pattern,
const char* pattern_end) {
679 const char* name = name_str.c_str();
680 const char*
const name_begin = name;
681 const char*
const name_end = name + name_str.size();
683 const char* pattern_next = pattern;
684 const char* name_next = name;
686 while (pattern < pattern_end || name < name_end) {
687 if (pattern < pattern_end) {
690 if (name < name_end && *name == *pattern) {
697 if (name < name_end) {
707 pattern_next = pattern;
708 name_next = name + 1;
714 if (name_begin < name_next && name_next <= name_end) {
715 pattern = pattern_next;
726bool IsGlobPattern(
const std::string& pattern) {
727 return std::any_of(pattern.begin(), pattern.end(),
728 [](
const char c) { return c ==
'?' || c ==
'*'; });
731class UnitTestFilter {
733 UnitTestFilter() =
default;
736 explicit UnitTestFilter(
const std::string& filter) {
738 std::vector<std::string> all_patterns;
739 SplitString(filter,
':', &all_patterns);
740 const auto exact_match_patterns_begin = std::partition(
741 all_patterns.begin(), all_patterns.end(), &IsGlobPattern);
743 glob_patterns_.reserve(
static_cast<size_t>(
744 std::distance(all_patterns.begin(), exact_match_patterns_begin)));
745 std::move(all_patterns.begin(), exact_match_patterns_begin,
746 std::inserter(glob_patterns_, glob_patterns_.begin()));
748 exact_match_patterns_begin, all_patterns.end(),
749 std::inserter(exact_match_patterns_, exact_match_patterns_.begin()));
754 bool MatchesName(
const std::string& name)
const {
755 return exact_match_patterns_.count(name) > 0 ||
756 std::any_of(glob_patterns_.begin(), glob_patterns_.end(),
757 [&name](
const std::string& pattern) {
758 return PatternMatchesString(
759 name, pattern.c_str(),
760 pattern.c_str() + pattern.size());
765 std::vector<std::string> glob_patterns_;
766 std::unordered_set<std::string> exact_match_patterns_;
769class PositiveAndNegativeUnitTestFilter {
776 explicit PositiveAndNegativeUnitTestFilter(
const std::string& filter) {
777 std::vector<std::string> positive_and_negative_filters;
780 SplitString(filter,
'-', &positive_and_negative_filters);
781 const auto& positive_filter = positive_and_negative_filters.front();
783 if (positive_and_negative_filters.size() > 1) {
784 positive_filter_ = UnitTestFilter(
785 positive_filter.empty() ? kUniversalFilter : positive_filter);
790 auto negative_filter_string = positive_and_negative_filters[1];
791 for (std::size_t i = 2; i < positive_and_negative_filters.size(); i++)
792 negative_filter_string =
793 negative_filter_string +
'-' + positive_and_negative_filters[i];
794 negative_filter_ = UnitTestFilter(negative_filter_string);
799 positive_filter_ = UnitTestFilter(positive_filter);
806 bool MatchesTest(
const std::string& test_suite_name,
807 const std::string& test_name)
const {
808 return MatchesName(test_suite_name +
"." + test_name);
813 bool MatchesName(
const std::string& name)
const {
814 return positive_filter_.MatchesName(name) &&
815 !negative_filter_.MatchesName(name);
819 UnitTestFilter positive_filter_;
820 UnitTestFilter negative_filter_;
824bool UnitTestOptions::MatchesFilter(
const std::string& name_str,
825 const char* filter) {
826 return UnitTestFilter(filter).MatchesName(name_str);
824bool UnitTestOptions::MatchesFilter(
const std::string& name_str, {
…}
831bool UnitTestOptions::FilterMatchesTest(
const std::string& test_suite_name,
832 const std::string& test_name) {
835 return PositiveAndNegativeUnitTestFilter(GTEST_FLAG_GET(filter))
836 .MatchesTest(test_suite_name, test_name);
831bool UnitTestOptions::FilterMatchesTest(
const std::string& test_suite_name, {
…}
843int UnitTestOptions::GTestShouldProcessSEH(DWORD exception_code) {
852 const DWORD kCxxExceptionCode = 0xe06d7363;
854 bool should_handle =
true;
856 if (!GTEST_FLAG_GET(catch_exceptions))
857 should_handle =
false;
858 else if (exception_code == EXCEPTION_BREAKPOINT)
859 should_handle =
false;
860 else if (exception_code == kCxxExceptionCode)
861 should_handle =
false;
863 return should_handle ? EXCEPTION_EXECUTE_HANDLER : EXCEPTION_CONTINUE_SEARCH;
872ScopedFakeTestPartResultReporter::ScopedFakeTestPartResultReporter(
873 TestPartResultArray* result)
874 : intercept_mode_(INTERCEPT_ONLY_CURRENT_THREAD), result_(result) {
881ScopedFakeTestPartResultReporter::ScopedFakeTestPartResultReporter(
882 InterceptMode intercept_mode, TestPartResultArray* result)
883 : intercept_mode_(intercept_mode), result_(result) {
887void ScopedFakeTestPartResultReporter::Init() {
889 if (intercept_mode_ == INTERCEPT_ALL_THREADS) {
890 old_reporter_ = impl->GetGlobalTestPartResultReporter();
891 impl->SetGlobalTestPartResultReporter(
this);
893 old_reporter_ = impl->GetTestPartResultReporterForCurrentThread();
894 impl->SetTestPartResultReporterForCurrentThread(
this);
900ScopedFakeTestPartResultReporter::~ScopedFakeTestPartResultReporter() {
902 if (intercept_mode_ == INTERCEPT_ALL_THREADS) {
903 impl->SetGlobalTestPartResultReporter(old_reporter_);
905 impl->SetTestPartResultReporterForCurrentThread(old_reporter_);
911void ScopedFakeTestPartResultReporter::ReportTestPartResult(
912 const TestPartResult& result) {
913 result_->Append(result);
939 const TestPartResultArray& results,
940 TestPartResult::Type type,
941 const std::string& substr) {
942 const std::string expected(type == TestPartResult::kFatalFailure
944 :
"1 non-fatal failure");
946 if (results.size() != 1) {
947 msg <<
"Expected: " << expected <<
"\n"
948 <<
" Actual: " << results.size() <<
" failures";
949 for (
int i = 0; i < results.size(); i++) {
950 msg <<
"\n" << results.GetTestPartResult(i);
955 const TestPartResult& r = results.GetTestPartResult(0);
956 if (r.type() != type) {
962 if (strstr(r.message(), substr.c_str()) ==
nullptr) {
964 <<
"Expected: " << expected <<
" containing \"" << substr <<
"\"\n"
975SingleFailureChecker::SingleFailureChecker(
const TestPartResultArray* results,
976 TestPartResult::Type type,
977 const std::string& substr)
978 : results_(results), type_(type), substr_(substr) {}
984SingleFailureChecker::~SingleFailureChecker() {
985 EXPECT_PRED_FORMAT3(HasOneFailure, *results_, type_, substr_);
988DefaultGlobalTestPartResultReporter::DefaultGlobalTestPartResultReporter(
990 : unit_test_(unit_test) {}
988DefaultGlobalTestPartResultReporter::DefaultGlobalTestPartResultReporter( {
…}
993 const TestPartResult& result) {
995 unit_test_->
listeners()->repeater()->OnTestPartResult(result);
1000 : unit_test_(unit_test) {}
1003 const TestPartResult& result) {
1008TestPartResultReporterInterface*
1010 internal::MutexLock lock(&global_test_part_result_reporter_mutex_);
1011 return global_test_part_result_repoter_;
1016 TestPartResultReporterInterface* reporter) {
1017 internal::MutexLock lock(&global_test_part_result_reporter_mutex_);
1018 global_test_part_result_repoter_ = reporter;
1022TestPartResultReporterInterface*
1024 return per_thread_test_part_result_reporter_.get();
1029 TestPartResultReporterInterface* reporter) {
1030 per_thread_test_part_result_reporter_.set(reporter);
1045 return static_cast<int>(test_suites_.size());
1072 &TestSuite::reportable_disabled_test_count);
1107 static_cast<int>(GTEST_FLAG_GET(stack_trace_depth)), skip_count + 1
1116 Timer() : start_(std::chrono::steady_clock::now()) {}
1120 return std::chrono::duration_cast<std::chrono::milliseconds>(
1121 std::chrono::steady_clock::now() - start_)
1126 std::chrono::steady_clock::time_point start_;
1133 return std::chrono::duration_cast<std::chrono::milliseconds>(
1134 std::chrono::system_clock::now() -
1135 std::chrono::system_clock::from_time_t(0))
1143#if GTEST_OS_WINDOWS_MOBILE
1148LPCWSTR String::AnsiToUtf16(
const char* ansi) {
1149 if (!ansi)
return nullptr;
1150 const int length = strlen(ansi);
1151 const int unicode_length =
1152 MultiByteToWideChar(CP_ACP, 0, ansi, length,
nullptr, 0);
1153 WCHAR* unicode =
new WCHAR[unicode_length + 1];
1154 MultiByteToWideChar(CP_ACP, 0, ansi, length, unicode, unicode_length);
1155 unicode[unicode_length] = 0;
1163const char* String::Utf16ToAnsi(LPCWSTR utf16_str) {
1164 if (!utf16_str)
return nullptr;
1165 const int ansi_length = WideCharToMultiByte(CP_ACP, 0, utf16_str, -1,
nullptr,
1166 0,
nullptr,
nullptr);
1167 char* ansi =
new char[ansi_length + 1];
1168 WideCharToMultiByte(CP_ACP, 0, utf16_str, -1, ansi, ansi_length,
nullptr,
1170 ansi[ansi_length] = 0;
1182bool String::CStringEquals(
const char* lhs,
const char* rhs) {
1183 if (lhs ==
nullptr)
return rhs ==
nullptr;
1185 if (rhs ==
nullptr)
return false;
1187 return strcmp(lhs, rhs) == 0;
1190#if GTEST_HAS_STD_WSTRING
1194static void StreamWideCharsToMessage(
const wchar_t* wstr,
size_t length,
1196 for (
size_t i = 0; i != length;) {
1197 if (wstr[i] != L
'\0') {
1198 *msg << WideStringToUtf8(wstr + i, static_cast<int>(length - i));
1199 while (i != length && wstr[i] != L
'\0') i++;
1210 ::std::vector< ::std::string>* dest) {
1211 ::std::vector< ::std::string> parsed;
1212 ::std::string::size_type pos = 0;
1214 const ::std::string::size_type colon = str.find(delimiter, pos);
1215 if (colon == ::std::string::npos) {
1216 parsed.push_back(str.substr(pos));
1219 parsed.push_back(str.substr(pos, colon - pos));
1233Message::Message() : ss_(new ::std::stringstream) {
1236 *ss_ << std::setprecision(std::numeric_limits<double>::digits10 + 2);
1241Message& Message::operator<<(
const wchar_t* wide_c_str) {
1242 return *
this << internal::String::ShowWideCString(wide_c_str);
1244Message& Message::operator<<(
wchar_t* wide_c_str) {
1245 return *
this << internal::String::ShowWideCString(wide_c_str);
1248#if GTEST_HAS_STD_WSTRING
1251Message& Message::operator<<(const ::std::wstring& wstr) {
1252 internal::StreamWideCharsToMessage(wstr.c_str(), wstr.length(),
this);
1259std::string Message::GetString()
const {
1265namespace edit_distance {
1267 const std::vector<size_t>& right) {
1268 std::vector<std::vector<double> > costs(
1269 left.size() + 1, std::vector<double>(right.size() + 1));
1270 std::vector<std::vector<EditType> > best_move(
1271 left.size() + 1, std::vector<EditType>(right.size() + 1));
1274 for (
size_t l_i = 0; l_i < costs.size(); ++l_i) {
1275 costs[l_i][0] =
static_cast<double>(l_i);
1276 best_move[l_i][0] = kRemove;
1279 for (
size_t r_i = 1; r_i < costs[0].size(); ++r_i) {
1280 costs[0][r_i] =
static_cast<double>(r_i);
1281 best_move[0][r_i] = kAdd;
1284 for (
size_t l_i = 0; l_i < left.size(); ++l_i) {
1285 for (
size_t r_i = 0; r_i < right.size(); ++r_i) {
1286 if (left[l_i] == right[r_i]) {
1288 costs[l_i + 1][r_i + 1] = costs[l_i][r_i];
1289 best_move[l_i + 1][r_i + 1] = kMatch;
1293 const double add = costs[l_i + 1][r_i];
1294 const double remove = costs[l_i][r_i + 1];
1295 const double replace = costs[l_i][r_i];
1296 if (add < remove && add < replace) {
1297 costs[l_i + 1][r_i + 1] = add + 1;
1298 best_move[l_i + 1][r_i + 1] = kAdd;
1299 }
else if (remove < add && remove < replace) {
1300 costs[l_i + 1][r_i + 1] = remove + 1;
1301 best_move[l_i + 1][r_i + 1] = kRemove;
1305 costs[l_i + 1][r_i + 1] = replace + 1.00001;
1306 best_move[l_i + 1][r_i + 1] = kReplace;
1312 std::vector<EditType> best_path;
1313 for (
size_t l_i = left.size(), r_i = right.size(); l_i > 0 || r_i > 0;) {
1314 EditType move = best_move[l_i][r_i];
1315 best_path.push_back(move);
1316 l_i -= move != kAdd;
1317 r_i -= move != kRemove;
1319 std::reverse(best_path.begin(), best_path.end());
1326class InternalStrings {
1328 size_t GetId(
const std::string& str) {
1329 IdMap::iterator it = ids_.find(str);
1330 if (it != ids_.end())
return it->second;
1331 size_t id = ids_.size();
1332 return ids_[str] = id;
1336 typedef std::map<std::string, size_t> IdMap;
1343 const std::vector<std::string>& left,
1344 const std::vector<std::string>& right) {
1345 std::vector<size_t> left_ids, right_ids;
1347 InternalStrings intern_table;
1348 for (
size_t i = 0; i < left.size(); ++i) {
1349 left_ids.push_back(intern_table.GetId(left[i]));
1351 for (
size_t i = 0; i < right.size(); ++i) {
1352 right_ids.push_back(intern_table.GetId(right[i]));
1366 Hunk(
size_t left_start,
size_t right_start)
1367 : left_start_(left_start),
1368 right_start_(right_start),
1373 void PushLine(
char edit,
const char* line) {
1378 hunk_.push_back(std::make_pair(
' ', line));
1382 hunk_removes_.push_back(std::make_pair(
'-', line));
1386 hunk_adds_.push_back(std::make_pair(
'+', line));
1391 void PrintTo(std::ostream* os) {
1394 for (std::list<std::pair<char, const char*> >::const_iterator it =
1396 it != hunk_.end(); ++it) {
1397 *os << it->first << it->second <<
"\n";
1401 bool has_edits()
const {
return adds_ || removes_; }
1405 hunk_.splice(hunk_.end(), hunk_removes_);
1406 hunk_.splice(hunk_.end(), hunk_adds_);
1413 void PrintHeader(std::ostream* ss)
const {
1416 *ss <<
"-" << left_start_ <<
"," << (removes_ + common_);
1418 if (removes_ && adds_) {
1422 *ss <<
"+" << right_start_ <<
"," << (adds_ + common_);
1427 size_t left_start_, right_start_;
1428 size_t adds_, removes_, common_;
1429 std::list<std::pair<char, const char*> > hunk_, hunk_adds_, hunk_removes_;
1442 const std::vector<std::string>& right,
1446 size_t l_i = 0, r_i = 0, edit_i = 0;
1447 std::stringstream ss;
1448 while (edit_i < edits.size()) {
1450 while (edit_i < edits.size() && edits[edit_i] == kMatch) {
1457 const size_t prefix_context = std::min(l_i, context);
1458 Hunk hunk(l_i - prefix_context + 1, r_i - prefix_context + 1);
1459 for (
size_t i = prefix_context; i > 0; --i) {
1460 hunk.PushLine(
' ', left[l_i - i].c_str());
1465 size_t n_suffix = 0;
1466 for (; edit_i < edits.size(); ++edit_i) {
1467 if (n_suffix >= context) {
1469 auto it = edits.begin() +
static_cast<int>(edit_i);
1470 while (it != edits.end() && *it == kMatch) ++it;
1471 if (it == edits.end() ||
1472 static_cast<size_t>(it - edits.begin()) - edit_i >= context) {
1478 EditType edit = edits[edit_i];
1480 n_suffix = edit == kMatch ? n_suffix + 1 : 0;
1482 if (edit == kMatch || edit == kRemove || edit == kReplace) {
1483 hunk.PushLine(edit == kMatch ?
' ' :
'-', left[l_i].c_str());
1485 if (edit == kAdd || edit == kReplace) {
1486 hunk.PushLine(
'+', right[r_i].c_str());
1490 l_i += edit != kAdd;
1491 r_i += edit != kRemove;
1494 if (!hunk.has_edits()) {
1265namespace edit_distance {
…}
1511std::vector<std::string> SplitEscapedString(
const std::string& str) {
1512 std::vector<std::string> lines;
1513 size_t start = 0, end = str.size();
1514 if (end > 2 && str[0] ==
'"' && str[end - 1] ==
'"') {
1518 bool escaped =
false;
1519 for (
size_t i = start; i + 1 < end; ++i) {
1522 if (str[i] ==
'n') {
1523 lines.push_back(str.substr(start, i - start - 1));
1527 escaped = str[i] ==
'\\';
1530 lines.push_back(str.substr(start, end - start));
1552 const char* rhs_expression,
1553 const std::string& lhs_value,
1554 const std::string& rhs_value,
bool ignoring_case) {
1556 msg <<
"Expected equality of these values:";
1557 msg <<
"\n " << lhs_expression;
1558 if (lhs_value != lhs_expression) {
1559 msg <<
"\n Which is: " << lhs_value;
1561 msg <<
"\n " << rhs_expression;
1562 if (rhs_value != rhs_expression) {
1563 msg <<
"\n Which is: " << rhs_value;
1566 if (ignoring_case) {
1567 msg <<
"\nIgnoring case";
1570 if (!lhs_value.empty() && !rhs_value.empty()) {
1571 const std::vector<std::string> lhs_lines = SplitEscapedString(lhs_value);
1572 const std::vector<std::string> rhs_lines = SplitEscapedString(rhs_value);
1573 if (lhs_lines.size() > 1 || rhs_lines.size() > 1) {
1574 msg <<
"\nWith diff:\n"
1584 const AssertionResult& assertion_result,
const char* expression_text,
1585 const char* actual_predicate_value,
const char* expected_predicate_value) {
1586 const char* actual_message = assertion_result.message();
1588 msg <<
"Value of: " << expression_text
1589 <<
"\n Actual: " << actual_predicate_value;
1590 if (actual_message[0] !=
'\0') msg <<
" (" << actual_message <<
")";
1591 msg <<
"\nExpected: " << expected_predicate_value;
1592 return msg.GetString();
1597 const char* abs_error_expr,
double val1,
1598 double val2,
double abs_error) {
1599 const double diff = fabs(val1 - val2);
1603 const double min_abs = std::min(fabs(val1), fabs(val2));
1605 const double epsilon =
1606 nextafter(min_abs, std::numeric_limits<double>::infinity()) - min_abs;
1613 if (!(std::isnan)(val1) && !(std::isnan)(val2) && abs_error > 0 &&
1614 abs_error < epsilon) {
1616 <<
"The difference between " << expr1 <<
" and " << expr2 <<
" is "
1617 << diff <<
", where\n"
1618 << expr1 <<
" evaluates to " << val1 <<
",\n"
1619 << expr2 <<
" evaluates to " << val2 <<
".\nThe abs_error parameter "
1620 << abs_error_expr <<
" evaluates to " << abs_error
1621 <<
" which is smaller than the minimum distance between doubles for "
1622 "numbers of this magnitude which is "
1624 <<
", thus making this EXPECT_NEAR check equivalent to "
1625 "EXPECT_EQUAL. Consider using EXPECT_DOUBLE_EQ instead.";
1628 <<
"The difference between " << expr1 <<
" and " << expr2 <<
" is "
1629 << diff <<
", which exceeds " << abs_error_expr <<
", where\n"
1630 << expr1 <<
" evaluates to " << val1 <<
",\n"
1631 << expr2 <<
" evaluates to " << val2 <<
", and\n"
1632 << abs_error_expr <<
" evaluates to " << abs_error <<
".";
1636template <
typename RawType>
1638 RawType val1, RawType val2) {
1645 const FloatingPoint<RawType> lhs(val1), rhs(val2);
1646 if (lhs.AlmostEquals(rhs)) {
1654 ::std::stringstream val1_ss;
1655 val1_ss << std::setprecision(std::numeric_limits<RawType>::digits10 + 2)
1658 ::std::stringstream val2_ss;
1659 val2_ss << std::setprecision(std::numeric_limits<RawType>::digits10 + 2)
1663 <<
"Expected: (" << expr1 <<
") <= (" << expr2 <<
")\n"
1672AssertionResult
FloatLE(
const char* expr1,
const char* expr2,
float val1,
1674 return internal::FloatingPointLE<float>(expr1, expr2, val1, val2);
1672AssertionResult
FloatLE(
const char* expr1,
const char* expr2,
float val1, {
…}
1679AssertionResult
DoubleLE(
const char* expr1,
const char* expr2,
double val1,
1681 return internal::FloatingPointLE<double>(expr1, expr2, val1, val2);
1679AssertionResult
DoubleLE(
const char* expr1,
const char* expr2,
double val1, {
…}
1688 const char* rhs_expression,
const char* lhs,
1690 if (String::CStringEquals(lhs, rhs)) {
1694 return EqFailure(lhs_expression, rhs_expression, PrintToString(lhs),
1695 PrintToString(rhs),
false);
1700 const char* rhs_expression,
const char* lhs,
1702 if (String::CaseInsensitiveCStringEquals(lhs, rhs)) {
1706 return EqFailure(lhs_expression, rhs_expression, PrintToString(lhs),
1707 PrintToString(rhs),
true);
1712 const char* s2_expression,
const char* s1,
1714 if (!String::CStringEquals(s1, s2)) {
1718 <<
"Expected: (" << s1_expression <<
") != (" << s2_expression
1719 <<
"), actual: \"" << s1 <<
"\" vs \"" << s2 <<
"\"";
1725 const char* s2_expression,
const char* s1,
1727 if (!String::CaseInsensitiveCStringEquals(s1, s2)) {
1731 <<
"Expected: (" << s1_expression <<
") != (" << s2_expression
1732 <<
") (ignoring case), actual: \"" << s1 <<
"\" vs \"" << s2 <<
"\"";
1746bool IsSubstringPred(
const char* needle,
const char* haystack) {
1747 if (needle ==
nullptr || haystack ==
nullptr)
return needle == haystack;
1749 return strstr(haystack, needle) !=
nullptr;
1752bool IsSubstringPred(
const wchar_t* needle,
const wchar_t* haystack) {
1753 if (needle ==
nullptr || haystack ==
nullptr)
return needle == haystack;
1755 return wcsstr(haystack, needle) !=
nullptr;
1759template <
typename StringType>
1760bool IsSubstringPred(
const StringType& needle,
const StringType& haystack) {
1761 return haystack.find(needle) != StringType::npos;
1768template <
typename StringType>
1769AssertionResult IsSubstringImpl(
bool expected_to_be_substring,
1770 const char* needle_expr,
1771 const char* haystack_expr,
1772 const StringType& needle,
1773 const StringType& haystack) {
1774 if (IsSubstringPred(needle, haystack) == expected_to_be_substring)
1777 const bool is_wide_string =
sizeof(needle[0]) > 1;
1778 const char*
const begin_string_quote = is_wide_string ?
"L\"" :
"\"";
1780 <<
"Value of: " << needle_expr <<
"\n"
1781 <<
" Actual: " << begin_string_quote << needle <<
"\"\n"
1782 <<
"Expected: " << (expected_to_be_substring ?
"" :
"not ")
1783 <<
"a substring of " << haystack_expr <<
"\n"
1784 <<
"Which is: " << begin_string_quote << haystack <<
"\"";
1793AssertionResult
IsSubstring(
const char* needle_expr,
const char* haystack_expr,
1794 const char* needle,
const char* haystack) {
1795 return IsSubstringImpl(
true, needle_expr, haystack_expr, needle, haystack);
1793AssertionResult
IsSubstring(
const char* needle_expr,
const char* haystack_expr, {
…}
1798AssertionResult
IsSubstring(
const char* needle_expr,
const char* haystack_expr,
1799 const wchar_t* needle,
const wchar_t* haystack) {
1800 return IsSubstringImpl(
true, needle_expr, haystack_expr, needle, haystack);
1798AssertionResult
IsSubstring(
const char* needle_expr,
const char* haystack_expr, {
…}
1804 const char* haystack_expr,
const char* needle,
1805 const char* haystack) {
1806 return IsSubstringImpl(
false, needle_expr, haystack_expr, needle, haystack);
1810 const char* haystack_expr,
const wchar_t* needle,
1811 const wchar_t* haystack) {
1812 return IsSubstringImpl(
false, needle_expr, haystack_expr, needle, haystack);
1815AssertionResult
IsSubstring(
const char* needle_expr,
const char* haystack_expr,
1816 const ::std::string& needle,
1817 const ::std::string& haystack) {
1818 return IsSubstringImpl(
true, needle_expr, haystack_expr, needle, haystack);
1815AssertionResult
IsSubstring(
const char* needle_expr,
const char* haystack_expr, {
…}
1822 const char* haystack_expr,
1823 const ::std::string& needle,
1824 const ::std::string& haystack) {
1825 return IsSubstringImpl(
false, needle_expr, haystack_expr, needle, haystack);
1828#if GTEST_HAS_STD_WSTRING
1829AssertionResult
IsSubstring(
const char* needle_expr,
const char* haystack_expr,
1830 const ::std::wstring& needle,
1831 const ::std::wstring& haystack) {
1832 return IsSubstringImpl(
true, needle_expr, haystack_expr, needle, haystack);
1836 const char* haystack_expr,
1837 const ::std::wstring& needle,
1838 const ::std::wstring& haystack) {
1839 return IsSubstringImpl(
false, needle_expr, haystack_expr, needle, haystack);
1850AssertionResult HRESULTFailureHelper(
const char* expr,
const char* expected,
1852#if GTEST_OS_WINDOWS_MOBILE || GTEST_OS_WINDOWS_TV_TITLE
1855 const char error_text[] =
"";
1862 const DWORD kFlags =
1863 FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS;
1864 const DWORD kBufSize = 4096;
1866 char error_text[kBufSize] = {
'\0'};
1867 DWORD message_length = ::FormatMessageA(kFlags,
1869 static_cast<DWORD
>(hr),
1875 for (; message_length && IsSpace(error_text[message_length - 1]);
1877 error_text[message_length - 1] =
'\0';
1882 const std::string error_hex(
"0x" + String::FormatHexInt(hr));
1883 return ::testing::AssertionFailure()
1884 <<
"Expected: " << expr <<
" " << expected <<
".\n"
1885 <<
" Actual: " << error_hex <<
" " << error_text <<
"\n";
1890AssertionResult IsHRESULTSuccess(
const char* expr,
long hr) {
1891 if (SUCCEEDED(hr)) {
1894 return HRESULTFailureHelper(expr,
"succeeds", hr);
1897AssertionResult IsHRESULTFailure(
const char* expr,
long hr) {
1901 return HRESULTFailureHelper(expr,
"fails", hr);
1926 (
static_cast<uint32_t
>(1) << (4 + 2 * 6)) - 1;
1930 (
static_cast<uint32_t
>(1) << (3 + 3 * 6)) - 1;
1936 const uint32_t low_bits = *bits & ((
static_cast<uint32_t
>(1) << n) - 1);
1949 return "(Invalid Unicode 0x" + String::FormatHexUInt32(code_point) +
")";
1955 str[0] =
static_cast<char>(code_point);
1958 str[1] =
static_cast<char>(0x80 |
ChopLowBits(&code_point, 6));
1959 str[0] =
static_cast<char>(0xC0 | code_point);
1962 str[2] =
static_cast<char>(0x80 |
ChopLowBits(&code_point, 6));
1963 str[1] =
static_cast<char>(0x80 |
ChopLowBits(&code_point, 6));
1964 str[0] =
static_cast<char>(0xE0 | code_point);
1967 str[3] =
static_cast<char>(0x80 |
ChopLowBits(&code_point, 6));
1968 str[2] =
static_cast<char>(0x80 |
ChopLowBits(&code_point, 6));
1969 str[1] =
static_cast<char>(0x80 |
ChopLowBits(&code_point, 6));
1970 str[0] =
static_cast<char>(0xF0 | code_point);
1983 return sizeof(wchar_t) == 2 && (first & 0xFC00) == 0xD800 &&
1984 (second & 0xFC00) == 0xDC00;
1990 const auto first_u =
static_cast<uint32_t
>(first);
1991 const auto second_u =
static_cast<uint32_t
>(second);
1992 const uint32_t mask = (1 << 10) - 1;
1993 return (
sizeof(
wchar_t) == 2)
1994 ? (((first_u & mask) << 10) | (second_u & mask)) + 0x10000
2015 if (num_chars == -1) num_chars =
static_cast<int>(wcslen(str));
2017 ::std::stringstream stream;
2018 for (
int i = 0; i < num_chars; ++i) {
2019 uint32_t unicode_code_point;
2021 if (str[i] == L
'\0') {
2024 unicode_code_point =
2028 unicode_code_point =
static_cast<uint32_t
>(str[i]);
2038std::string String::ShowWideCString(
const wchar_t* wide_c_str) {
2039 if (wide_c_str ==
nullptr)
return "(null)";
2050bool String::WideCStringEquals(
const wchar_t* lhs,
const wchar_t* rhs) {
2051 if (lhs ==
nullptr)
return rhs ==
nullptr;
2053 if (rhs ==
nullptr)
return false;
2055 return wcscmp(lhs, rhs) == 0;
2060 const char* rhs_expression,
const wchar_t* lhs,
2061 const wchar_t* rhs) {
2062 if (String::WideCStringEquals(lhs, rhs)) {
2066 return EqFailure(lhs_expression, rhs_expression, PrintToString(lhs),
2067 PrintToString(rhs),
false);
2072 const char* s2_expression,
const wchar_t* s1,
2073 const wchar_t* s2) {
2074 if (!String::WideCStringEquals(s1, s2)) {
2079 <<
"Expected: (" << s1_expression <<
") != (" << s2_expression
2080 <<
"), actual: " << PrintToString(s1) <<
" vs " << PrintToString(s2);
2089bool String::CaseInsensitiveCStringEquals(
const char* lhs,
const char* rhs) {
2090 if (lhs ==
nullptr)
return rhs ==
nullptr;
2091 if (rhs ==
nullptr)
return false;
2092 return posix::StrCaseCmp(lhs, rhs) == 0;
2107bool String::CaseInsensitiveWideCStringEquals(
const wchar_t* lhs,
2108 const wchar_t* rhs) {
2109 if (lhs ==
nullptr)
return rhs ==
nullptr;
2111 if (rhs ==
nullptr)
return false;
2114 return _wcsicmp(lhs, rhs) == 0;
2115#elif GTEST_OS_LINUX && !GTEST_OS_LINUX_ANDROID
2116 return wcscasecmp(lhs, rhs) == 0;
2122 left = towlower(
static_cast<wint_t
>(*lhs++));
2123 right = towlower(
static_cast<wint_t
>(*rhs++));
2124 }
while (left && left == right);
2125 return left == right;
2131bool String::EndsWithCaseInsensitive(
const std::string& str,
2132 const std::string& suffix) {
2133 const size_t str_len = str.length();
2134 const size_t suffix_len = suffix.length();
2135 return (str_len >= suffix_len) &&
2136 CaseInsensitiveCStringEquals(str.c_str() + str_len - suffix_len,
2141std::string String::FormatIntWidth2(
int value) {
2142 return FormatIntWidthN(value, 2);
2146std::string String::FormatIntWidthN(
int value,
int width) {
2147 std::stringstream ss;
2148 ss << std::setfill(
'0') << std::setw(width) << value;
2153std::string String::FormatHexUInt32(uint32_t value) {
2154 std::stringstream ss;
2155 ss << std::hex << std::uppercase << value;
2160std::string String::FormatHexInt(
int value) {
2161 return FormatHexUInt32(
static_cast<uint32_t
>(value));
2165std::string String::FormatByte(
unsigned char value) {
2166 std::stringstream ss;
2167 ss << std::setfill(
'0') << std::setw(2) << std::hex << std::uppercase
2168 <<
static_cast<unsigned int>(value);
2175 const ::std::string& str = ss->str();
2176 const char*
const start = str.c_str();
2177 const char*
const end = start + str.length();
2180 result.reserve(
static_cast<size_t>(2 * (end - start)));
2181 for (
const char* ch = start; ch != end; ++ch) {
2194 const Message& user_msg) {
2196 const std::string user_msg_string = user_msg.GetString();
2197 if (user_msg_string.empty()) {
2200 if (gtest_msg.empty()) {
2201 return user_msg_string;
2203 return gtest_msg +
"\n" + user_msg_string;
2211TestResult::TestResult()
2212 : death_test_count_(0), start_timestamp_(0), elapsed_time_(0) {}
2215TestResult::~TestResult() {}
2220const TestPartResult& TestResult::GetTestPartResult(
int i)
const {
2221 if (i < 0 || i >= total_part_count()) internal::posix::Abort();
2222 return test_part_results_.at(
static_cast<size_t>(i));
2228const TestProperty& TestResult::GetTestProperty(
int i)
const {
2229 if (i < 0 || i >= test_property_count()) internal::posix::Abort();
2230 return test_properties_.at(
static_cast<size_t>(i));
2234void TestResult::ClearTestPartResults() { test_part_results_.clear(); }
2237void TestResult::AddTestPartResult(
const TestPartResult& test_part_result) {
2238 test_part_results_.push_back(test_part_result);
2244void TestResult::RecordProperty(
const std::string& xml_element,
2245 const TestProperty& test_property) {
2246 if (!ValidateTestProperty(xml_element, test_property)) {
2249 internal::MutexLock lock(&test_properties_mutex_);
2250 const std::vector<TestProperty>::iterator property_with_matching_key =
2251 std::find_if(test_properties_.begin(), test_properties_.end(),
2252 internal::TestPropertyKeyIs(test_property.key()));
2253 if (property_with_matching_key == test_properties_.end()) {
2254 test_properties_.push_back(test_property);
2257 property_with_matching_key->SetValue(test_property.value());
2263 "disabled",
"errors",
"failures",
"name",
2264 "random_seed",
"tests",
"time",
"timestamp"};
2269 "disabled",
"errors",
"failures",
"name",
2270 "tests",
"time",
"timestamp",
"skipped"};
2274 "classname",
"name",
"status",
"time",
2275 "type_param",
"value_param",
"file",
"line"};
2280 "classname",
"name",
"status",
"time",
"type_param",
2281 "value_param",
"file",
"line",
"result",
"timestamp"};
2283template <
size_t kSize>
2285 return std::vector<std::string>(array, array + kSize);
2289 const std::string& xml_element) {
2290 if (xml_element ==
"testsuites") {
2292 }
else if (xml_element ==
"testsuite") {
2294 }
else if (xml_element ==
"testcase") {
2297 GTEST_CHECK_(
false) <<
"Unrecognized xml_element provided: " << xml_element;
2300 return std::vector<std::string>();
2305 const std::string& xml_element) {
2306 if (xml_element ==
"testsuites") {
2308 }
else if (xml_element ==
"testsuite") {
2310 }
else if (xml_element ==
"testcase") {
2313 GTEST_CHECK_(
false) <<
"Unrecognized xml_element provided: " << xml_element;
2316 return std::vector<std::string>();
2321 for (
size_t i = 0; i < words.size(); ++i) {
2322 if (i > 0 && words.size() > 2) {
2325 if (i == words.size() - 1) {
2326 word_list <<
"and ";
2328 word_list <<
"'" << words[i] <<
"'";
2330 return word_list.GetString();
2334 const std::string& property_name,
2335 const std::vector<std::string>& reserved_names) {
2336 if (std::find(reserved_names.begin(), reserved_names.end(), property_name) !=
2337 reserved_names.end()) {
2338 ADD_FAILURE() <<
"Reserved key used in RecordProperty(): " << property_name
2340 <<
" are reserved by " << GTEST_NAME_ <<
")";
2348bool TestResult::ValidateTestProperty(
const std::string& xml_element,
2349 const TestProperty& test_property) {
2355void TestResult::Clear() {
2356 test_part_results_.clear();
2357 test_properties_.clear();
2358 death_test_count_ = 0;
2364 return result.skipped();
2368bool TestResult::Skipped()
const {
2373bool TestResult::Failed()
const {
2374 for (
int i = 0; i < total_part_count(); ++i) {
2375 if (GetTestPartResult(i).failed())
return true;
2382 return result.fatally_failed();
2386bool TestResult::HasFatalFailure()
const {
2392 return result.nonfatally_failed();
2396bool TestResult::HasNonfatalFailure()
const {
2402int TestResult::total_part_count()
const {
2403 return static_cast<int>(test_part_results_.size());
2407int TestResult::test_property_count()
const {
2408 return static_cast<int>(test_properties_.size());
2416Test::Test() : gtest_flag_saver_(new GTEST_FLAG_SAVER_) {}
2426void Test::SetUp() {}
2431void Test::TearDown() {}
2434void Test::RecordProperty(
const std::string& key,
const std::string& value) {
2435 UnitTest::GetInstance()->RecordProperty(key, value);
2439void Test::RecordProperty(
const std::string& key,
int value) {
2440 Message value_message;
2441 value_message << value;
2442 RecordProperty(key, value_message.GetString().c_str());
2448 const std::string& message) {
2451 UnitTest::GetInstance()->AddTestPartResult(
2466bool Test::HasSameFixtureClass() {
2467 internal::UnitTestImpl*
const impl = internal::GetUnitTestImpl();
2468 const TestSuite*
const test_suite = impl->current_test_suite();
2471 const TestInfo*
const first_test_info = test_suite->test_info_list()[0];
2472 const internal::TypeId first_fixture_id = first_test_info->fixture_class_id_;
2473 const char*
const first_test_name = first_test_info->name();
2476 const TestInfo*
const this_test_info = impl->current_test_info();
2477 const internal::TypeId this_fixture_id = this_test_info->fixture_class_id_;
2478 const char*
const this_test_name = this_test_info->name();
2480 if (this_fixture_id != first_fixture_id) {
2482 const bool first_is_TEST = first_fixture_id == internal::GetTestTypeId();
2484 const bool this_is_TEST = this_fixture_id == internal::GetTestTypeId();
2486 if (first_is_TEST || this_is_TEST) {
2493 const char*
const TEST_name =
2494 first_is_TEST ? first_test_name : this_test_name;
2495 const char*
const TEST_F_name =
2496 first_is_TEST ? this_test_name : first_test_name;
2499 <<
"All tests in the same test suite must use the same test fixture\n"
2500 <<
"class, so mixing TEST_F and TEST in the same test suite is\n"
2501 <<
"illegal. In test suite " << this_test_info->test_suite_name()
2503 <<
"test " << TEST_F_name <<
" is defined using TEST_F but\n"
2504 <<
"test " << TEST_name <<
" is defined using TEST. You probably\n"
2505 <<
"want to change the TEST to TEST_F or move it to another test\n"
2511 <<
"All tests in the same test suite must use the same test fixture\n"
2512 <<
"class. However, in test suite "
2513 << this_test_info->test_suite_name() <<
",\n"
2514 <<
"you defined test " << first_test_name <<
" and test "
2515 << this_test_name <<
"\n"
2516 <<
"using two different test fixture classes. This can happen if\n"
2517 <<
"the two classes are from different namespaces or translation\n"
2518 <<
"units and have the same name. You should probably rename one\n"
2519 <<
"of the classes to put the tests into different test suites.";
2533static std::string* FormatSehExceptionMessage(DWORD exception_code,
2534 const char* location) {
2536 message <<
"SEH exception with code 0x" << std::setbase(16) << exception_code
2537 << std::setbase(10) <<
" thrown in " << location <<
".";
2539 return new std::string(message.GetString());
2546#if GTEST_HAS_EXCEPTIONS
2549static std::string FormatCxxExceptionMessage(
const char* description,
2550 const char* location) {
2552 if (description !=
nullptr) {
2553 message <<
"C++ exception with description \"" << description <<
"\"";
2555 message <<
"Unknown C++ exception";
2557 message <<
" thrown in " << location <<
".";
2559 return message.GetString();
2563 const TestPartResult& test_part_result);
2565GoogleTestFailureException::GoogleTestFailureException(
2566 const TestPartResult& failure)
2579template <
class T,
typename Result>
2581 const char* location) {
2584 return (object->*method)();
2585 } __except (internal::UnitTestOptions::GTestShouldProcessSEH(
2586 GetExceptionCode())) {
2590 std::string* exception_message =
2591 FormatSehExceptionMessage(GetExceptionCode(), location);
2593 *exception_message);
2594 delete exception_message;
2595 return static_cast<Result
>(0);
2599 return (object->*method)();
2606template <
class T,
typename Result>
2608 const char* location) {
2633#if GTEST_HAS_EXCEPTIONS
2636 }
catch (
const AssertionException&) {
2638 }
catch (
const internal::GoogleTestFailureException&) {
2643 }
catch (
const std::exception& e) {
2645 TestPartResult::kFatalFailure,
2646 FormatCxxExceptionMessage(e.what(), location));
2649 TestPartResult::kFatalFailure,
2650 FormatCxxExceptionMessage(
nullptr, location));
2652 return static_cast<Result
>(0);
2657 return (object->*method)();
2665 if (!HasSameFixtureClass())
return;
2667 internal::UnitTestImpl*
const impl = internal::GetUnitTestImpl();
2668 impl->os_stack_trace_getter()->UponLeavingGTest();
2669 internal::HandleExceptionsInMethodIfSupported(
this, &Test::SetUp,
"SetUp()");
2672 if (!HasFatalFailure() && !IsSkipped()) {
2673 impl->os_stack_trace_getter()->UponLeavingGTest();
2674 internal::HandleExceptionsInMethodIfSupported(
this, &Test::TestBody,
2681 impl->os_stack_trace_getter()->UponLeavingGTest();
2682 internal::HandleExceptionsInMethodIfSupported(
this, &Test::TearDown,
2687bool Test::HasFatalFailure() {
2688 return internal::GetUnitTestImpl()->current_test_result()->HasFatalFailure();
2692bool Test::HasNonfatalFailure() {
2693 return internal::GetUnitTestImpl()
2694 ->current_test_result()
2695 ->HasNonfatalFailure();
2699bool Test::IsSkipped() {
2700 return internal::GetUnitTestImpl()->current_test_result()->Skipped();
2707TestInfo::TestInfo(
const std::string& a_test_suite_name,
2708 const std::string& a_name,
const char* a_type_param,
2709 const char* a_value_param,
2710 internal::CodeLocation a_code_location,
2711 internal::TypeId fixture_class_id,
2712 internal::TestFactoryBase* factory)
2713 : test_suite_name_(a_test_suite_name),
2715 type_param_(a_type_param ? new std::string(a_type_param) : nullptr),
2716 value_param_(a_value_param ? new std::string(a_value_param) : nullptr),
2717 location_(a_code_location),
2718 fixture_class_id_(fixture_class_id),
2720 is_disabled_(false),
2721 matches_filter_(false),
2722 is_in_another_shard_(false),
2727TestInfo::~TestInfo() {
delete factory_; }
2750 const char* test_suite_name,
const char* name,
const char* type_param,
2751 const char* value_param, CodeLocation code_location,
2752 TypeId fixture_class_id, SetUpTestSuiteFunc set_up_tc,
2753 TearDownTestSuiteFunc tear_down_tc, TestFactoryBase* factory) {
2754 TestInfo*
const test_info =
2755 new TestInfo(test_suite_name, name, type_param, value_param,
2756 code_location, fixture_class_id, factory);
2762 CodeLocation code_location) {
2765 <<
"Attempted redefinition of test suite " << test_suite_name <<
".\n"
2766 <<
"All tests in the same test suite must use the same test fixture\n"
2767 <<
"class. However, in test suite " << test_suite_name <<
", you tried\n"
2768 <<
"to define a test using a fixture class different from the one\n"
2769 <<
"used earlier. This can happen if the two fixture classes are\n"
2770 <<
"from different namespaces and have the same name. You should\n"
2771 <<
"probably rename one of the classes to put the tests into different\n"
2776 <<
" " << errors.GetString();
2795 explicit TestNameIs(
const char* name) : name_(name) {}
2798 bool operator()(
const TestInfo* test_info)
const {
2799 return test_info && test_info->name() == name_;
2814 if (!parameterized_tests_registered_) {
2815 parameterized_test_registry_.RegisterTests();
2816 type_parameterized_test_registry_.CheckForInstantiations();
2817 parameterized_tests_registered_ =
true;
2825void TestInfo::Run() {
2826 TestEventListener* repeater = UnitTest::GetInstance()->listeners().repeater();
2828 if (is_disabled_ && matches_filter_) repeater->OnTestDisabled(*
this);
2834 impl->set_current_test_info(
this);
2837 repeater->OnTestStart(*
this);
2839 internal::Timer timer;
2840 impl->os_stack_trace_getter()->UponLeavingGTest();
2844 factory_, &internal::TestFactoryBase::CreateTest,
2845 "the test fixture's constructor");
2850 if (!Test::HasFatalFailure() && !Test::IsSkipped()) {
2856 if (test !=
nullptr) {
2858 impl->os_stack_trace_getter()->UponLeavingGTest();
2860 test, &Test::DeleteSelf_,
"the test fixture's destructor");
2863 result_.set_elapsed_time(timer.Elapsed());
2866 repeater->OnTestEnd(*
this);
2870 impl->set_current_test_info(
nullptr);
2874void TestInfo::Skip() {
2875 if (!should_run_)
return;
2878 impl->set_current_test_info(
this);
2880 TestEventListener* repeater = UnitTest::GetInstance()->listeners().repeater();
2883 repeater->OnTestStart(*
this);
2885 const TestPartResult test_part_result =
2886 TestPartResult(TestPartResult::kSkip, this->file(), this->line(),
"");
2887 impl->GetTestPartResultReporterForCurrentThread()->ReportTestPartResult(
2891 repeater->OnTestEnd(*
this);
2892 impl->set_current_test_info(
nullptr);
2898int TestSuite::successful_test_count()
const {
2899 return CountIf(test_info_list_, TestPassed);
2903int TestSuite::skipped_test_count()
const {
2904 return CountIf(test_info_list_, TestSkipped);
2908int TestSuite::failed_test_count()
const {
2909 return CountIf(test_info_list_, TestFailed);
2913int TestSuite::reportable_disabled_test_count()
const {
2914 return CountIf(test_info_list_, TestReportableDisabled);
2918int TestSuite::disabled_test_count()
const {
2919 return CountIf(test_info_list_, TestDisabled);
2923int TestSuite::reportable_test_count()
const {
2924 return CountIf(test_info_list_, TestReportable);
2928int TestSuite::test_to_run_count()
const {
2929 return CountIf(test_info_list_, ShouldRunTest);
2933int TestSuite::total_test_count()
const {
2934 return static_cast<int>(test_info_list_.size());
2946TestSuite::TestSuite(
const char* a_name,
const char* a_type_param,
2947 internal::SetUpTestSuiteFunc set_up_tc,
2948 internal::TearDownTestSuiteFunc tear_down_tc)
2950 type_param_(a_type_param ? new std::string(a_type_param) : nullptr),
2951 set_up_tc_(set_up_tc),
2952 tear_down_tc_(tear_down_tc),
2954 start_timestamp_(0),
2958TestSuite::~TestSuite() {
2960 ForEach(test_info_list_, internal::Delete<TestInfo>);
2965const TestInfo* TestSuite::GetTestInfo(
int i)
const {
2967 return index < 0 ? nullptr : test_info_list_[static_cast<size_t>(index)];
2972TestInfo* TestSuite::GetMutableTestInfo(
int i) {
2974 return index < 0 ? nullptr : test_info_list_[static_cast<size_t>(index)];
2979void TestSuite::AddTestInfo(TestInfo* test_info) {
2980 test_info_list_.push_back(test_info);
2981 test_indices_.push_back(
static_cast<int>(test_indices_.size()));
2985void TestSuite::Run() {
2986 if (!should_run_)
return;
2989 impl->set_current_test_suite(
this);
2991 TestEventListener* repeater = UnitTest::GetInstance()->listeners().repeater();
2994 repeater->OnTestSuiteStart(*
this);
2996#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
2997 repeater->OnTestCaseStart(*
this);
3000 impl->os_stack_trace_getter()->UponLeavingGTest();
3002 this, &TestSuite::RunSetUpTestSuite,
"SetUpTestSuite()");
3004 const bool skip_all = ad_hoc_test_result().Failed();
3007 internal::Timer timer;
3008 for (
int i = 0; i < total_test_count(); i++) {
3010 GetMutableTestInfo(i)->Skip();
3012 GetMutableTestInfo(i)->Run();
3014 if (GTEST_FLAG_GET(fail_fast) &&
3015 GetMutableTestInfo(i)->result()->Failed()) {
3016 for (
int j = i + 1; j < total_test_count(); j++) {
3017 GetMutableTestInfo(j)->Skip();
3022 elapsed_time_ = timer.Elapsed();
3024 impl->os_stack_trace_getter()->UponLeavingGTest();
3026 this, &TestSuite::RunTearDownTestSuite,
"TearDownTestSuite()");
3029 repeater->OnTestSuiteEnd(*
this);
3031#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
3032 repeater->OnTestCaseEnd(*
this);
3035 impl->set_current_test_suite(
nullptr);
3039void TestSuite::Skip() {
3040 if (!should_run_)
return;
3043 impl->set_current_test_suite(
this);
3045 TestEventListener* repeater = UnitTest::GetInstance()->listeners().repeater();
3048 repeater->OnTestSuiteStart(*
this);
3050#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
3051 repeater->OnTestCaseStart(*
this);
3054 for (
int i = 0; i < total_test_count(); i++) {
3055 GetMutableTestInfo(i)->Skip();
3059 repeater->OnTestSuiteEnd(*
this);
3061#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
3062 repeater->OnTestCaseEnd(*
this);
3065 impl->set_current_test_suite(
nullptr);
3069void TestSuite::ClearResult() {
3070 ad_hoc_test_result_.Clear();
3071 ForEach(test_info_list_, TestInfo::ClearTestResult);
3075void TestSuite::ShuffleTests(internal::Random* random) {
3076 Shuffle(random, &test_indices_);
3080void TestSuite::UnshuffleTests() {
3081 for (
size_t i = 0; i < test_indices_.size(); i++) {
3082 test_indices_[i] =
static_cast<int>(i);
3092 const char* plural_form) {
3093 return internal::StreamableToString(count) +
" " +
3094 (count == 1 ? singular_form : plural_form);
3113 case TestPartResult::kSkip:
3115 case TestPartResult::kSuccess:
3118 case TestPartResult::kNonFatalFailure:
3119 case TestPartResult::kFatalFailure:
3126 return "Unknown result type";
3132enum class GTestColor { kDefault, kRed, kGreen, kYellow };
3137 const TestPartResult& test_part_result) {
3138 return (Message() << internal::FormatFileLocation(
3139 test_part_result.file_name(),
3140 test_part_result.line_number())
3143 << test_part_result.message())
3150 printf(
"%s\n", result.c_str());
3156#if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE
3160 ::OutputDebugStringA(result.c_str());
3161 ::OutputDebugStringA(
"\n");
3166#if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE && !GTEST_OS_WINDOWS_PHONE && \
3167 !GTEST_OS_WINDOWS_RT && !GTEST_OS_WINDOWS_MINGW
3170static WORD GetColorAttribute(GTestColor color) {
3172 case GTestColor::kRed:
3173 return FOREGROUND_RED;
3174 case GTestColor::kGreen:
3175 return FOREGROUND_GREEN;
3176 case GTestColor::kYellow:
3177 return FOREGROUND_RED | FOREGROUND_GREEN;
3183static int GetBitOffset(WORD color_mask) {
3184 if (color_mask == 0)
return 0;
3187 while ((color_mask & 1) == 0) {
3194static WORD GetNewColor(GTestColor color, WORD old_color_attrs) {
3196 static const WORD background_mask = BACKGROUND_BLUE | BACKGROUND_GREEN |
3197 BACKGROUND_RED | BACKGROUND_INTENSITY;
3198 static const WORD foreground_mask = FOREGROUND_BLUE | FOREGROUND_GREEN |
3199 FOREGROUND_RED | FOREGROUND_INTENSITY;
3200 const WORD existing_bg = old_color_attrs & background_mask;
3203 GetColorAttribute(color) | existing_bg | FOREGROUND_INTENSITY;
3204 static const int bg_bitOffset = GetBitOffset(background_mask);
3205 static const int fg_bitOffset = GetBitOffset(foreground_mask);
3207 if (((new_color & background_mask) >> bg_bitOffset) ==
3208 ((new_color & foreground_mask) >> fg_bitOffset)) {
3209 new_color ^= FOREGROUND_INTENSITY;
3220 case GTestColor::kRed:
3222 case GTestColor::kGreen:
3224 case GTestColor::kYellow:
3235 std::string c = GTEST_FLAG_GET(color);
3236 const char*
const gtest_color = c.c_str();
3238 if (String::CaseInsensitiveCStringEquals(gtest_color,
"auto")) {
3239#if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MINGW
3242 return stdout_is_tty;
3245 const char*
const term = posix::GetEnv(
"TERM");
3246 const bool term_supports_color =
3247 String::CStringEquals(term,
"xterm") ||
3248 String::CStringEquals(term,
"xterm-color") ||
3249 String::CStringEquals(term,
"xterm-256color") ||
3250 String::CStringEquals(term,
"screen") ||
3251 String::CStringEquals(term,
"screen-256color") ||
3252 String::CStringEquals(term,
"tmux") ||
3253 String::CStringEquals(term,
"tmux-256color") ||
3254 String::CStringEquals(term,
"rxvt-unicode") ||
3255 String::CStringEquals(term,
"rxvt-unicode-256color") ||
3256 String::CStringEquals(term,
"linux") ||
3257 String::CStringEquals(term,
"cygwin");
3258 return stdout_is_tty && term_supports_color;
3262 return String::CaseInsensitiveCStringEquals(gtest_color,
"yes") ||
3263 String::CaseInsensitiveCStringEquals(gtest_color,
"true") ||
3264 String::CaseInsensitiveCStringEquals(gtest_color,
"t") ||
3265 String::CStringEquals(gtest_color,
"1");
3276GTEST_ATTRIBUTE_PRINTF_(2, 3)
3277static
void ColoredPrintf(GTestColor color, const
char* fmt, ...) {
3279 va_start(args, fmt);
3281 static const bool in_color_mode =
3283 const bool use_color = in_color_mode && (color != GTestColor::kDefault);
3291#if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE && !GTEST_OS_WINDOWS_PHONE && \
3292 !GTEST_OS_WINDOWS_RT && !GTEST_OS_WINDOWS_MINGW
3293 const HANDLE stdout_handle = GetStdHandle(STD_OUTPUT_HANDLE);
3296 CONSOLE_SCREEN_BUFFER_INFO buffer_info;
3297 GetConsoleScreenBufferInfo(stdout_handle, &buffer_info);
3298 const WORD old_color_attrs = buffer_info.wAttributes;
3299 const WORD new_color = GetNewColor(color, old_color_attrs);
3305 SetConsoleTextAttribute(stdout_handle, new_color);
3311 SetConsoleTextAttribute(stdout_handle, old_color_attrs);
3277static
void ColoredPrintf(GTestColor color, const
char* fmt, ...) {
…}
3326 const char*
const type_param = test_info.type_param();
3327 const char*
const value_param = test_info.value_param();
3329 if (type_param !=
nullptr || value_param !=
nullptr) {
3331 if (type_param !=
nullptr) {
3333 if (value_param !=
nullptr) printf(
" and ");
3335 if (value_param !=
nullptr) {
3348 printf(
"%s.%s", test_suite, test);
3353 void OnTestIterationStart(
const UnitTest& unit_test,
int iteration)
override;
3354 void OnEnvironmentsSetUpStart(
const UnitTest& unit_test)
override;
3356#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
3357 void OnTestCaseStart(
const TestCase& test_case)
override;
3359 void OnTestSuiteStart(
const TestSuite& test_suite)
override;
3362 void OnTestStart(
const TestInfo& test_info)
override;
3363 void OnTestDisabled(
const TestInfo& test_info)
override;
3365 void OnTestPartResult(
const TestPartResult& result)
override;
3366 void OnTestEnd(
const TestInfo& test_info)
override;
3367#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
3368 void OnTestCaseEnd(
const TestCase& test_case)
override;
3370 void OnTestSuiteEnd(
const TestSuite& test_suite)
override;
3373 void OnEnvironmentsTearDownStart(
const UnitTest& unit_test)
override;
3375 void OnTestIterationEnd(
const UnitTest& unit_test,
int iteration)
override;
3379 static void PrintFailedTests(
const UnitTest& unit_test);
3380 static void PrintFailedTestSuites(
const UnitTest& unit_test);
3381 static void PrintSkippedTests(
const UnitTest& unit_test);
3385void PrettyUnitTestResultPrinter::OnTestIterationStart(
3386 const UnitTest& unit_test,
int iteration) {
3387 if (GTEST_FLAG_GET(repeat) != 1)
3388 printf(
"\nRepeating all tests (iteration %d) . . .\n\n", iteration + 1);
3390 std::string f = GTEST_FLAG_GET(filter);
3391 const char*
const filter = f.c_str();
3396 ColoredPrintf(GTestColor::kYellow,
"Note: %s filter = %s\n", GTEST_NAME_,
3402 ColoredPrintf(GTestColor::kYellow,
"Note: This is test shard %d of %s.\n",
3403 static_cast<int>(shard_index) + 1,
3407 if (GTEST_FLAG_GET(shuffle)) {
3409 "Note: Randomizing tests' orders with a seed of %d .\n",
3410 unit_test.random_seed());
3414 printf(
"Running %s from %s.\n",
3385void PrettyUnitTestResultPrinter::OnTestIterationStart( {
…}
3420void PrettyUnitTestResultPrinter::OnEnvironmentsSetUpStart(
3423 printf(
"Global test environment set-up.\n");
3420void PrettyUnitTestResultPrinter::OnEnvironmentsSetUpStart( {
…}
3427#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
3428void PrettyUnitTestResultPrinter::OnTestCaseStart(
const TestCase& test_case) {
3429 const std::string counts =
3432 printf(
"%s from %s", counts.c_str(), test_case.name());
3433 if (test_case.type_param() ==
nullptr) {
3428void PrettyUnitTestResultPrinter::OnTestCaseStart(
const TestCase& test_case) {
…}
3441void PrettyUnitTestResultPrinter::OnTestSuiteStart(
3442 const TestSuite& test_suite) {
3443 const std::string counts =
3446 printf(
"%s from %s", counts.c_str(), test_suite.name());
3447 if (test_suite.type_param() ==
nullptr) {
3450 printf(
", where %s = %s\n", kTypeParamLabel, test_suite.type_param());
3456void PrettyUnitTestResultPrinter::OnTestStart(
const TestInfo& test_info) {
3458 PrintTestName(test_info.test_suite_name(), test_info.name());
3456void PrettyUnitTestResultPrinter::OnTestStart(
const TestInfo& test_info) {
…}
3463void PrettyUnitTestResultPrinter::OnTestDisabled(
const TestInfo& test_info) {
3465 PrintTestName(test_info.test_suite_name(), test_info.name());
3463void PrettyUnitTestResultPrinter::OnTestDisabled(
const TestInfo& test_info) {
…}
3471void PrettyUnitTestResultPrinter::OnTestPartResult(
3472 const TestPartResult& result) {
3473 switch (result.type()) {
3475 case TestPartResult::kSuccess:
3471void PrettyUnitTestResultPrinter::OnTestPartResult( {
…}
3485void PrettyUnitTestResultPrinter::OnTestEnd(
const TestInfo& test_info) {
3486 if (test_info.result()->Passed()) {
3488 }
else if (test_info.result()->Skipped()) {
3493 PrintTestName(test_info.test_suite_name(), test_info.name());
3496 if (GTEST_FLAG_GET(print_time)) {
3497 printf(
" (%s ms)\n",
3498 internal::StreamableToString(test_info.result()->elapsed_time())
3485void PrettyUnitTestResultPrinter::OnTestEnd(
const TestInfo& test_info) {
…}
3506#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
3507void PrettyUnitTestResultPrinter::OnTestCaseEnd(
const TestCase& test_case) {
3508 if (!GTEST_FLAG_GET(print_time))
return;
3510 const std::string counts =
3513 printf(
"%s from %s (%s ms total)\n\n", counts.c_str(), test_case.name(),
3514 internal::StreamableToString(test_case.elapsed_time()).c_str());
3507void PrettyUnitTestResultPrinter::OnTestCaseEnd(
const TestCase& test_case) {
…}
3518void PrettyUnitTestResultPrinter::OnTestSuiteEnd(
const TestSuite& test_suite) {
3519 if (!GTEST_FLAG_GET(print_time))
return;
3521 const std::string counts =
3524 printf(
"%s from %s (%s ms total)\n\n", counts.c_str(), test_suite.name(),
3525 internal::StreamableToString(test_suite.elapsed_time()).c_str());
3530void PrettyUnitTestResultPrinter::OnEnvironmentsTearDownStart(
3533 printf(
"Global test environment tear-down\n");
3530void PrettyUnitTestResultPrinter::OnEnvironmentsTearDownStart( {
…}
3538void PrettyUnitTestResultPrinter::PrintFailedTests(
const UnitTest& unit_test) {
3539 const int failed_test_count = unit_test.failed_test_count();
3541 printf(
"%s, listed below:\n",
FormatTestCount(failed_test_count).c_str());
3543 for (
int i = 0; i < unit_test.total_test_suite_count(); ++i) {
3544 const TestSuite& test_suite = *unit_test.GetTestSuite(i);
3545 if (!test_suite.should_run() || (test_suite.failed_test_count() == 0)) {
3548 for (
int j = 0; j < test_suite.total_test_count(); ++j) {
3549 const TestInfo& test_info = *test_suite.GetTestInfo(j);
3550 if (!test_info.should_run() || !test_info.result()->Failed()) {
3553 ColoredPrintf(GTestColor::kRed,
"[ FAILED ] ");
3554 printf(
"%s.%s", test_suite.name(), test_info.name());
3555 PrintFullTestCommentIfPresent(test_info);
3559 printf(
"\n%2d FAILED %s\n", failed_test_count,
3560 failed_test_count == 1 ?
"TEST" :
"TESTS");
3565void PrettyUnitTestResultPrinter::PrintFailedTestSuites(
3566 const UnitTest& unit_test) {
3567 int suite_failure_count = 0;
3568 for (
int i = 0; i < unit_test.total_test_suite_count(); ++i) {
3569 const TestSuite& test_suite = *unit_test.GetTestSuite(i);
3570 if (!test_suite.should_run()) {
3573 if (test_suite.ad_hoc_test_result().Failed()) {
3575 printf(
"%s: SetUpTestSuite or TearDownTestSuite\n", test_suite.name());
3576 ++suite_failure_count;
3579 if (suite_failure_count > 0) {
3580 printf(
"\n%2d FAILED TEST %s\n", suite_failure_count,
3581 suite_failure_count == 1 ?
"SUITE" :
"SUITES");
3586void PrettyUnitTestResultPrinter::PrintSkippedTests(
const UnitTest& unit_test) {
3587 const int skipped_test_count = unit_test.skipped_test_count();
3588 if (skipped_test_count == 0) {
3592 for (
int i = 0; i < unit_test.total_test_suite_count(); ++i) {
3593 const TestSuite& test_suite = *unit_test.GetTestSuite(i);
3594 if (!test_suite.should_run() || (test_suite.skipped_test_count() == 0)) {
3597 for (
int j = 0; j < test_suite.total_test_count(); ++j) {
3598 const TestInfo& test_info = *test_suite.GetTestInfo(j);
3599 if (!test_info.should_run() || !test_info.result()->Skipped()) {
3603 printf(
"%s.%s", test_suite.name(), test_info.name());
3609void PrettyUnitTestResultPrinter::OnTestIterationEnd(
const UnitTest& unit_test,
3612 printf(
"%s from %s ran.",
3615 if (GTEST_FLAG_GET(print_time)) {
3616 printf(
" (%s ms total)",
3617 internal::StreamableToString(unit_test.elapsed_time()).c_str());
3621 printf(
"%s.\n",
FormatTestCount(unit_test.successful_test_count()).c_str());
3623 const int skipped_test_count = unit_test.skipped_test_count();
3624 if (skipped_test_count > 0) {
3626 printf(
"%s, listed below:\n",
FormatTestCount(skipped_test_count).c_str());
3627 PrintSkippedTests(unit_test);
3630 if (!unit_test.Passed()) {
3631 PrintFailedTests(unit_test);
3632 PrintFailedTestSuites(unit_test);
3635 int num_disabled = unit_test.reportable_disabled_test_count();
3636 if (num_disabled && !GTEST_FLAG_GET(also_run_disabled_tests)) {
3637 if (unit_test.Passed()) {
3640 ColoredPrintf(GTestColor::kYellow,
" YOU HAVE %d DISABLED %s\n\n",
3641 num_disabled, num_disabled == 1 ?
"TEST" :
"TESTS");
3609void PrettyUnitTestResultPrinter::OnTestIterationEnd(
const UnitTest& unit_test, {
…}
3656 printf(
"%s.%s", test_suite, test);
3665#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
3668 void OnTestSuiteStart(
const TestSuite& )
override {}
3674 void OnTestPartResult(
const TestPartResult& result)
override;
3675 void OnTestEnd(
const TestInfo& test_info)
override;
3676#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
3679 void OnTestSuiteEnd(
const TestSuite& )
override {}
3684 void OnTestIterationEnd(
const UnitTest& unit_test,
int iteration)
override;
3689void BriefUnitTestResultPrinter::OnTestPartResult(
3690 const TestPartResult& result) {
3691 switch (result.type()) {
3693 case TestPartResult::kSuccess:
3689void BriefUnitTestResultPrinter::OnTestPartResult( {
…}
3703void BriefUnitTestResultPrinter::OnTestEnd(
const TestInfo& test_info) {
3704 if (test_info.result()->Failed()) {
3706 PrintTestName(test_info.test_suite_name(), test_info.name());
3709 if (GTEST_FLAG_GET(print_time)) {
3710 printf(
" (%s ms)\n",
3711 internal::StreamableToString(test_info.result()->elapsed_time())
3703void BriefUnitTestResultPrinter::OnTestEnd(
const TestInfo& test_info) {
…}
3720void BriefUnitTestResultPrinter::OnTestIterationEnd(
const UnitTest& unit_test,
3723 printf(
"%s from %s ran.",
3726 if (GTEST_FLAG_GET(print_time)) {
3727 printf(
" (%s ms total)",
3728 internal::StreamableToString(unit_test.elapsed_time()).c_str());
3732 printf(
"%s.\n",
FormatTestCount(unit_test.successful_test_count()).c_str());
3734 const int skipped_test_count = unit_test.skipped_test_count();
3735 if (skipped_test_count > 0) {
3740 int num_disabled = unit_test.reportable_disabled_test_count();
3741 if (num_disabled && !GTEST_FLAG_GET(also_run_disabled_tests)) {
3742 if (unit_test.Passed()) {
3745 ColoredPrintf(GTestColor::kYellow,
" YOU HAVE %d DISABLED %s\n\n",
3746 num_disabled, num_disabled == 1 ?
"TEST" :
"TESTS");
3720void BriefUnitTestResultPrinter::OnTestIterationEnd(
const UnitTest& unit_test, {
…}
3761 void Append(TestEventListener* listener);
3762 TestEventListener* Release(TestEventListener* listener);
3770 void OnTestIterationStart(
const UnitTest& unit_test,
int iteration)
override;
3774#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
3783#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
3789 void OnTestIterationEnd(
const UnitTest& unit_test,
int iteration)
override;
3795 bool forwarding_enabled_;
3797 std::vector<TestEventListener*> listeners_;
3803TestEventRepeater::~TestEventRepeater() {
3804 ForEach(listeners_, Delete<TestEventListener>);
3803TestEventRepeater::~TestEventRepeater() {
…}
3807void TestEventRepeater::Append(TestEventListener* listener) {
3808 listeners_.push_back(listener);
3807void TestEventRepeater::Append(TestEventListener* listener) {
…}
3811TestEventListener* TestEventRepeater::Release(TestEventListener* listener) {
3812 for (
size_t i = 0; i < listeners_.size(); ++i) {
3813 if (listeners_[i] == listener) {
3814 listeners_.erase(listeners_.begin() +
static_cast<int>(i));
3811TestEventListener* TestEventRepeater::Release(TestEventListener* listener) {
…}
3824#define GTEST_REPEATER_METHOD_(Name, Type) \
3825 void TestEventRepeater::Name(const Type& parameter) { \
3826 if (forwarding_enabled_) { \
3827 for (size_t i = 0; i < listeners_.size(); i++) { \
3828 listeners_[i]->Name(parameter); \
3824#define GTEST_REPEATER_METHOD_(Name, Type) \ …
3834#define GTEST_REVERSE_REPEATER_METHOD_(Name, Type) \
3835 void TestEventRepeater::Name(const Type& parameter) { \
3836 if (forwarding_enabled_) { \
3837 for (size_t i = listeners_.size(); i != 0; i--) { \
3838 listeners_[i - 1]->Name(parameter); \
3834#define GTEST_REVERSE_REPEATER_METHOD_(Name, Type) \ …
3846#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
3858#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
3864#undef GTEST_REPEATER_METHOD_
3865#undef GTEST_REVERSE_REPEATER_METHOD_
3867void TestEventRepeater::OnTestIterationStart(
const UnitTest& unit_test,
3869 if (forwarding_enabled_) {
3870 for (
size_t i = 0; i < listeners_.size(); i++) {
3871 listeners_[i]->OnTestIterationStart(unit_test, iteration);
3867void TestEventRepeater::OnTestIterationStart(
const UnitTest& unit_test, {
…}
3876void TestEventRepeater::OnTestIterationEnd(
const UnitTest& unit_test,
3878 if (forwarding_enabled_) {
3879 for (
size_t i = listeners_.size(); i > 0; i--) {
3880 listeners_[i - 1]->OnTestIterationEnd(unit_test, iteration);
3876void TestEventRepeater::OnTestIterationEnd(
const UnitTest& unit_test, {
…}
3892 void OnTestIterationEnd(
const UnitTest& unit_test,
int iteration)
override;
3893 void ListTestsMatchingFilter(
const std::vector<TestSuite*>& test_suites);
3896 static void PrintXmlTestsList(std::ostream* stream,
3897 const std::vector<TestSuite*>& test_suites);
3902 static bool IsNormalizableWhitespace(
unsigned char c) {
3903 return c ==
'\t' || c ==
'\n' || c ==
'\r';
3908 static bool IsValidXmlCharacter(
unsigned char c) {
3909 return IsNormalizableWhitespace(c) || c >= 0x20;
3916 static std::string EscapeXml(
const std::string& str,
bool is_attribute);
3919 static std::string RemoveInvalidXmlCharacters(
const std::string& str);
3922 static std::string EscapeXmlAttribute(
const std::string& str) {
3923 return EscapeXml(str,
true);
3927 static std::string EscapeXmlText(
const char* str) {
3928 return EscapeXml(str,
false);
3933 static void OutputXmlAttribute(std::ostream* stream,
3934 const std::string& element_name,
3935 const std::string& name,
3936 const std::string& value);
3939 static void OutputXmlCDataSection(::std::ostream* stream,
const char* data);
3944 static void OutputXmlTestSuiteForTestResult(::std::ostream* stream,
3945 const TestResult& result);
3948 static void OutputXmlTestResult(::std::ostream* stream,
3949 const TestResult& result);
3952 static void OutputXmlTestInfo(::std::ostream* stream,
3953 const char* test_suite_name,
3954 const TestInfo& test_info);
3957 static void PrintXmlTestSuite(::std::ostream* stream,
3958 const TestSuite& test_suite);
3961 static void PrintXmlUnitTest(::std::ostream* stream,
3962 const UnitTest& unit_test);
3968 static std::string TestPropertiesAsXmlAttributes(
const TestResult& result);
3972 static void OutputXmlTestProperties(std::ostream* stream,
3973 const TestResult& result);
3976 const std::string output_file_;
3983XmlUnitTestResultPrinter::XmlUnitTestResultPrinter(
const char* output_file)
3984 : output_file_(output_file) {
3985 if (output_file_.empty()) {
3986 GTEST_LOG_(FATAL) <<
"XML output file may not be null";
3983XmlUnitTestResultPrinter::XmlUnitTestResultPrinter(
const char* output_file) {
…}
3994 std::stringstream stream;
3995 PrintXmlUnitTest(&stream, unit_test);
4001 const std::vector<TestSuite*>& test_suites) {
4003 std::stringstream stream;
4019std::string XmlUnitTestResultPrinter::EscapeXml(
const std::string& str,
4020 bool is_attribute) {
4023 for (
size_t i = 0; i < str.size(); ++i) {
4024 const char ch = str[i];
4048 if (IsValidXmlCharacter(
static_cast<unsigned char>(ch))) {
4050 IsNormalizableWhitespace(
static_cast<unsigned char>(ch)))
4051 m <<
"&#x" << String::FormatByte(
static_cast<unsigned char>(ch))
4060 return m.GetString();
4066std::string XmlUnitTestResultPrinter::RemoveInvalidXmlCharacters(
4067 const std::string& str) {
4069 output.reserve(str.size());
4070 for (std::string::const_iterator it = str.begin(); it != str.end(); ++it)
4071 if (IsValidXmlCharacter(
static_cast<unsigned char>(*it)))
4072 output.push_back(*it);
4095 ::std::stringstream ss;
4096 ss << (static_cast<double>(ms) * 1e-3);
4101#if defined(_MSC_VER)
4102 return localtime_s(out, &seconds) == 0;
4103#elif defined(__MINGW32__) || defined(__MINGW64__)
4106 struct tm* tm_ptr = localtime(&seconds);
4107 if (tm_ptr ==
nullptr)
return false;
4110#elif defined(__STDC_LIB_EXT1__)
4113 return localtime_s(&seconds, out) !=
nullptr;
4115 return localtime_r(&seconds, out) !=
nullptr;
4122 struct tm time_struct;
4126 return StreamableToString(time_struct.tm_year + 1900) +
"-" +
4127 String::FormatIntWidth2(time_struct.tm_mon + 1) +
"-" +
4128 String::FormatIntWidth2(time_struct.tm_mday) +
"T" +
4129 String::FormatIntWidth2(time_struct.tm_hour) +
":" +
4130 String::FormatIntWidth2(time_struct.tm_min) +
":" +
4131 String::FormatIntWidth2(time_struct.tm_sec) +
"." +
4132 String::FormatIntWidthN(
static_cast<int>(ms % 1000), 3);
4136void XmlUnitTestResultPrinter::OutputXmlCDataSection(::std::ostream* stream,
4138 const char* segment = data;
4139 *stream <<
"<![CDATA[";
4141 const char*
const next_segment = strstr(segment,
"]]>");
4142 if (next_segment !=
nullptr) {
4143 stream->write(segment,
4144 static_cast<std::streamsize
>(next_segment - segment));
4145 *stream <<
"]]>]]><![CDATA[";
4146 segment = next_segment + strlen(
"]]>");
4155void XmlUnitTestResultPrinter::OutputXmlAttribute(
4156 std::ostream* stream,
const std::string& element_name,
4157 const std::string& name,
const std::string& value) {
4158 const std::vector<std::string>& allowed_names =
4161 GTEST_CHECK_(std::find(allowed_names.begin(), allowed_names.end(), name) !=
4162 allowed_names.end())
4163 <<
"Attribute " << name <<
" is not allowed for element <" << element_name
4166 *stream <<
" " << name <<
"=\"" << EscapeXmlAttribute(value) <<
"\"";
4170void XmlUnitTestResultPrinter::OutputXmlTestSuiteForTestResult(
4171 ::std::ostream* stream,
const TestResult& result) {
4173 *stream <<
" <testsuite";
4174 OutputXmlAttribute(stream,
"testsuite",
"name",
"NonTestSuiteFailure");
4175 OutputXmlAttribute(stream,
"testsuite",
"tests",
"1");
4176 OutputXmlAttribute(stream,
"testsuite",
"failures",
"1");
4177 OutputXmlAttribute(stream,
"testsuite",
"disabled",
"0");
4178 OutputXmlAttribute(stream,
"testsuite",
"skipped",
"0");
4179 OutputXmlAttribute(stream,
"testsuite",
"errors",
"0");
4180 OutputXmlAttribute(stream,
"testsuite",
"time",
4183 stream,
"testsuite",
"timestamp",
4188 *stream <<
" <testcase";
4189 OutputXmlAttribute(stream,
"testcase",
"name",
"");
4190 OutputXmlAttribute(stream,
"testcase",
"status",
"run");
4191 OutputXmlAttribute(stream,
"testcase",
"result",
"completed");
4192 OutputXmlAttribute(stream,
"testcase",
"classname",
"");
4193 OutputXmlAttribute(stream,
"testcase",
"time",
4196 stream,
"testcase",
"timestamp",
4200 OutputXmlTestResult(stream, result);
4203 *stream <<
" </testsuite>\n";
4207void XmlUnitTestResultPrinter::OutputXmlTestInfo(::std::ostream* stream,
4208 const char* test_suite_name,
4209 const TestInfo& test_info) {
4210 const TestResult& result = *test_info.result();
4211 const std::string kTestsuite =
"testcase";
4213 if (test_info.is_in_another_shard()) {
4217 *stream <<
" <testcase";
4218 OutputXmlAttribute(stream, kTestsuite,
"name", test_info.name());
4220 if (test_info.value_param() !=
nullptr) {
4221 OutputXmlAttribute(stream, kTestsuite,
"value_param",
4222 test_info.value_param());
4224 if (test_info.type_param() !=
nullptr) {
4225 OutputXmlAttribute(stream, kTestsuite,
"type_param",
4226 test_info.type_param());
4229 OutputXmlAttribute(stream, kTestsuite,
"file", test_info.file());
4230 OutputXmlAttribute(stream, kTestsuite,
"line",
4231 StreamableToString(test_info.line()));
4232 if (GTEST_FLAG_GET(list_tests)) {
4237 OutputXmlAttribute(stream, kTestsuite,
"status",
4238 test_info.should_run() ?
"run" :
"notrun");
4239 OutputXmlAttribute(stream, kTestsuite,
"result",
4240 test_info.should_run()
4241 ? (result.Skipped() ?
"skipped" :
"completed")
4243 OutputXmlAttribute(stream, kTestsuite,
"time",
4246 stream, kTestsuite,
"timestamp",
4248 OutputXmlAttribute(stream, kTestsuite,
"classname", test_suite_name);
4250 OutputXmlTestResult(stream, result);
4253void XmlUnitTestResultPrinter::OutputXmlTestResult(::std::ostream* stream,
4254 const TestResult& result) {
4257 for (
int i = 0; i < result.total_part_count(); ++i) {
4258 const TestPartResult& part = result.GetTestPartResult(i);
4259 if (part.failed()) {
4260 if (++failures == 1 && skips == 0) {
4263 const std::string location =
4265 part.line_number());
4266 const std::string summary = location +
"\n" + part.summary();
4267 *stream <<
" <failure message=\"" << EscapeXmlAttribute(summary)
4269 const std::string detail = location +
"\n" + part.message();
4270 OutputXmlCDataSection(stream, RemoveInvalidXmlCharacters(detail).c_str());
4271 *stream <<
"</failure>\n";
4272 }
else if (part.skipped()) {
4273 if (++skips == 1 && failures == 0) {
4276 const std::string location =
4278 part.line_number());
4279 const std::string summary = location +
"\n" + part.summary();
4280 *stream <<
" <skipped message=\""
4281 << EscapeXmlAttribute(summary.c_str()) <<
"\">";
4282 const std::string detail = location +
"\n" + part.message();
4283 OutputXmlCDataSection(stream, RemoveInvalidXmlCharacters(detail).c_str());
4284 *stream <<
"</skipped>\n";
4288 if (failures == 0 && skips == 0 && result.test_property_count() == 0) {
4291 if (failures == 0 && skips == 0) {
4294 OutputXmlTestProperties(stream, result);
4295 *stream <<
" </testcase>\n";
4300void XmlUnitTestResultPrinter::PrintXmlTestSuite(std::ostream* stream,
4301 const TestSuite& test_suite) {
4302 const std::string kTestsuite =
"testsuite";
4303 *stream <<
" <" << kTestsuite;
4304 OutputXmlAttribute(stream, kTestsuite,
"name", test_suite.name());
4305 OutputXmlAttribute(stream, kTestsuite,
"tests",
4306 StreamableToString(test_suite.reportable_test_count()));
4307 if (!GTEST_FLAG_GET(list_tests)) {
4308 OutputXmlAttribute(stream, kTestsuite,
"failures",
4309 StreamableToString(test_suite.failed_test_count()));
4311 stream, kTestsuite,
"disabled",
4312 StreamableToString(test_suite.reportable_disabled_test_count()));
4313 OutputXmlAttribute(stream, kTestsuite,
"skipped",
4314 StreamableToString(test_suite.skipped_test_count()));
4316 OutputXmlAttribute(stream, kTestsuite,
"errors",
"0");
4318 OutputXmlAttribute(stream, kTestsuite,
"time",
4321 stream, kTestsuite,
"timestamp",
4323 *stream << TestPropertiesAsXmlAttributes(test_suite.ad_hoc_test_result());
4326 for (
int i = 0; i < test_suite.total_test_count(); ++i) {
4327 if (test_suite.GetTestInfo(i)->is_reportable())
4328 OutputXmlTestInfo(stream, test_suite.name(), *test_suite.GetTestInfo(i));
4330 *stream <<
" </" << kTestsuite <<
">\n";
4334void XmlUnitTestResultPrinter::PrintXmlUnitTest(std::ostream* stream,
4335 const UnitTest& unit_test) {
4336 const std::string kTestsuites =
"testsuites";
4338 *stream <<
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
4339 *stream <<
"<" << kTestsuites;
4341 OutputXmlAttribute(stream, kTestsuites,
"tests",
4342 StreamableToString(unit_test.reportable_test_count()));
4343 OutputXmlAttribute(stream, kTestsuites,
"failures",
4344 StreamableToString(unit_test.failed_test_count()));
4346 stream, kTestsuites,
"disabled",
4347 StreamableToString(unit_test.reportable_disabled_test_count()));
4348 OutputXmlAttribute(stream, kTestsuites,
"errors",
"0");
4349 OutputXmlAttribute(stream, kTestsuites,
"time",
4352 stream, kTestsuites,
"timestamp",
4355 if (GTEST_FLAG_GET(shuffle)) {
4356 OutputXmlAttribute(stream, kTestsuites,
"random_seed",
4357 StreamableToString(unit_test.random_seed()));
4359 *stream << TestPropertiesAsXmlAttributes(unit_test.ad_hoc_test_result());
4361 OutputXmlAttribute(stream, kTestsuites,
"name",
"AllTests");
4364 for (
int i = 0; i < unit_test.total_test_suite_count(); ++i) {
4365 if (unit_test.GetTestSuite(i)->reportable_test_count() > 0)
4366 PrintXmlTestSuite(stream, *unit_test.GetTestSuite(i));
4371 if (unit_test.ad_hoc_test_result().Failed()) {
4372 OutputXmlTestSuiteForTestResult(stream, unit_test.ad_hoc_test_result());
4375 *stream <<
"</" << kTestsuites <<
">\n";
4379 std::ostream* stream,
const std::vector<TestSuite*>& test_suites) {
4380 const std::string kTestsuites =
"testsuites";
4382 *stream <<
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
4383 *stream <<
"<" << kTestsuites;
4385 int total_tests = 0;
4386 for (
auto test_suite : test_suites) {
4387 total_tests += test_suite->total_test_count();
4389 OutputXmlAttribute(stream, kTestsuites,
"tests",
4390 StreamableToString(total_tests));
4391 OutputXmlAttribute(stream, kTestsuites,
"name",
"AllTests");
4394 for (
auto test_suite : test_suites) {
4395 PrintXmlTestSuite(stream, *test_suite);
4397 *stream <<
"</" << kTestsuites <<
">\n";
4402std::string XmlUnitTestResultPrinter::TestPropertiesAsXmlAttributes(
4403 const TestResult& result) {
4405 for (
int i = 0; i < result.test_property_count(); ++i) {
4406 const TestProperty&
property = result.GetTestProperty(i);
4407 attributes <<
" " <<
property.key() <<
"="
4408 <<
"\"" << EscapeXmlAttribute(property.value()) <<
"\"";
4410 return attributes.GetString();
4413void XmlUnitTestResultPrinter::OutputXmlTestProperties(
4414 std::ostream* stream,
const TestResult& result) {
4415 const std::string kProperties =
"properties";
4416 const std::string kProperty =
"property";
4418 if (result.test_property_count() <= 0) {
4422 *stream <<
" <" << kProperties <<
">\n";
4423 for (
int i = 0; i < result.test_property_count(); ++i) {
4424 const TestProperty&
property = result.GetTestProperty(i);
4425 *stream <<
" <" << kProperty;
4426 *stream <<
" name=\"" << EscapeXmlAttribute(property.key()) <<
"\"";
4427 *stream <<
" value=\"" << EscapeXmlAttribute(property.value()) <<
"\"";
4430 *stream <<
" </" << kProperties <<
">\n";
4444 const std::vector<TestSuite*>& test_suites);
4448 static std::string EscapeJson(
const std::string& str);
4452 static void OutputJsonKey(std::ostream* stream,
4453 const std::string& element_name,
4454 const std::string& name,
const std::string& value,
4455 const std::string& indent,
bool comma =
true);
4456 static void OutputJsonKey(std::ostream* stream,
4457 const std::string& element_name,
4458 const std::string& name,
int value,
4459 const std::string& indent,
bool comma =
true);
4464 static void OutputJsonTestSuiteForTestResult(::std::ostream* stream,
4465 const TestResult& result);
4468 static void OutputJsonTestResult(::std::ostream* stream,
4469 const TestResult& result);
4472 static void OutputJsonTestInfo(::std::ostream* stream,
4473 const char* test_suite_name,
4474 const TestInfo& test_info);
4477 static void PrintJsonTestSuite(::std::ostream* stream,
4478 const TestSuite& test_suite);
4481 static void PrintJsonUnitTest(::std::ostream* stream,
4482 const UnitTest& unit_test);
4486 static std::string TestPropertiesAsJson(
const TestResult& result,
4487 const std::string& indent);
4490 const std::string output_file_;
4499 : output_file_(output_file) {
4500 if (output_file_.empty()) {
4501 GTEST_LOG_(FATAL) <<
"JSON output file may not be null";
4508 std::stringstream stream;
4509 PrintJsonUnitTest(&stream, unit_test);
4515std::string JsonUnitTestResultPrinter::EscapeJson(
const std::string& str) {
4518 for (
size_t i = 0; i < str.size(); ++i) {
4519 const char ch = str[i];
4543 m <<
"\\u00" << String::FormatByte(
static_cast<unsigned char>(ch));
4551 return m.GetString();
4559 ::std::stringstream ss;
4560 ss << (static_cast<double>(ms) * 1e-3) <<
"s";
4567 struct tm time_struct;
4571 return StreamableToString(time_struct.tm_year + 1900) +
"-" +
4572 String::FormatIntWidth2(time_struct.tm_mon + 1) +
"-" +
4573 String::FormatIntWidth2(time_struct.tm_mday) +
"T" +
4574 String::FormatIntWidth2(time_struct.tm_hour) +
":" +
4575 String::FormatIntWidth2(time_struct.tm_min) +
":" +
4576 String::FormatIntWidth2(time_struct.tm_sec) +
"Z";
4579static inline std::string
Indent(
size_t width) {
4580 return std::string(width,
' ');
4583void JsonUnitTestResultPrinter::OutputJsonKey(std::ostream* stream,
4584 const std::string& element_name,
4585 const std::string& name,
4586 const std::string& value,
4587 const std::string& indent,
4589 const std::vector<std::string>& allowed_names =
4592 GTEST_CHECK_(std::find(allowed_names.begin(), allowed_names.end(), name) !=
4593 allowed_names.end())
4594 <<
"Key \"" << name <<
"\" is not allowed for value \"" << element_name
4597 *stream << indent <<
"\"" << name <<
"\": \"" << EscapeJson(value) <<
"\"";
4598 if (comma) *stream <<
",\n";
4601void JsonUnitTestResultPrinter::OutputJsonKey(
4602 std::ostream* stream,
const std::string& element_name,
4603 const std::string& name,
int value,
const std::string& indent,
bool comma) {
4604 const std::vector<std::string>& allowed_names =
4607 GTEST_CHECK_(std::find(allowed_names.begin(), allowed_names.end(), name) !=
4608 allowed_names.end())
4609 <<
"Key \"" << name <<
"\" is not allowed for value \"" << element_name
4612 *stream << indent <<
"\"" << name <<
"\": " << StreamableToString(value);
4613 if (comma) *stream <<
",\n";
4617void JsonUnitTestResultPrinter::OutputJsonTestSuiteForTestResult(
4618 ::std::ostream* stream,
const TestResult& result) {
4620 *stream <<
Indent(4) <<
"{\n";
4621 OutputJsonKey(stream,
"testsuite",
"name",
"NonTestSuiteFailure",
Indent(6));
4622 OutputJsonKey(stream,
"testsuite",
"tests", 1,
Indent(6));
4623 if (!GTEST_FLAG_GET(list_tests)) {
4624 OutputJsonKey(stream,
"testsuite",
"failures", 1,
Indent(6));
4625 OutputJsonKey(stream,
"testsuite",
"disabled", 0,
Indent(6));
4626 OutputJsonKey(stream,
"testsuite",
"skipped", 0,
Indent(6));
4627 OutputJsonKey(stream,
"testsuite",
"errors", 0,
Indent(6));
4628 OutputJsonKey(stream,
"testsuite",
"time",
4631 OutputJsonKey(stream,
"testsuite",
"timestamp",
4635 *stream <<
Indent(6) <<
"\"testsuite\": [\n";
4638 *stream <<
Indent(8) <<
"{\n";
4639 OutputJsonKey(stream,
"testcase",
"name",
"",
Indent(10));
4640 OutputJsonKey(stream,
"testcase",
"status",
"RUN",
Indent(10));
4641 OutputJsonKey(stream,
"testcase",
"result",
"COMPLETED",
Indent(10));
4642 OutputJsonKey(stream,
"testcase",
"timestamp",
4645 OutputJsonKey(stream,
"testcase",
"time",
4648 OutputJsonKey(stream,
"testcase",
"classname",
"",
Indent(10),
false);
4649 *stream << TestPropertiesAsJson(result,
Indent(10));
4652 OutputJsonTestResult(stream, result);
4655 *stream <<
"\n" <<
Indent(6) <<
"]\n" <<
Indent(4) <<
"}";
4659void JsonUnitTestResultPrinter::OutputJsonTestInfo(::std::ostream* stream,
4660 const char* test_suite_name,
4661 const TestInfo& test_info) {
4662 const TestResult& result = *test_info.result();
4663 const std::string kTestsuite =
"testcase";
4664 const std::string kIndent =
Indent(10);
4666 *stream <<
Indent(8) <<
"{\n";
4667 OutputJsonKey(stream, kTestsuite,
"name", test_info.name(), kIndent);
4669 if (test_info.value_param() !=
nullptr) {
4670 OutputJsonKey(stream, kTestsuite,
"value_param", test_info.value_param(),
4673 if (test_info.type_param() !=
nullptr) {
4674 OutputJsonKey(stream, kTestsuite,
"type_param", test_info.type_param(),
4678 OutputJsonKey(stream, kTestsuite,
"file", test_info.file(), kIndent);
4679 OutputJsonKey(stream, kTestsuite,
"line", test_info.line(), kIndent,
false);
4680 if (GTEST_FLAG_GET(list_tests)) {
4681 *stream <<
"\n" <<
Indent(8) <<
"}";
4687 OutputJsonKey(stream, kTestsuite,
"status",
4688 test_info.should_run() ?
"RUN" :
"NOTRUN", kIndent);
4689 OutputJsonKey(stream, kTestsuite,
"result",
4690 test_info.should_run()
4691 ? (result.Skipped() ?
"SKIPPED" :
"COMPLETED")
4694 OutputJsonKey(stream, kTestsuite,
"timestamp",
4697 OutputJsonKey(stream, kTestsuite,
"time",
4699 OutputJsonKey(stream, kTestsuite,
"classname", test_suite_name, kIndent,
4701 *stream << TestPropertiesAsJson(result, kIndent);
4703 OutputJsonTestResult(stream, result);
4706void JsonUnitTestResultPrinter::OutputJsonTestResult(::std::ostream* stream,
4707 const TestResult& result) {
4708 const std::string kIndent =
Indent(10);
4711 for (
int i = 0; i < result.total_part_count(); ++i) {
4712 const TestPartResult& part = result.GetTestPartResult(i);
4713 if (part.failed()) {
4715 if (++failures == 1) {
4716 *stream << kIndent <<
"\""
4720 const std::string location =
4722 part.line_number());
4723 const std::string message = EscapeJson(location +
"\n" + part.message());
4724 *stream << kIndent <<
" {\n"
4725 << kIndent <<
" \"failure\": \"" << message <<
"\",\n"
4726 << kIndent <<
" \"type\": \"\"\n"
4731 if (failures > 0) *stream <<
"\n" << kIndent <<
"]";
4732 *stream <<
"\n" <<
Indent(8) <<
"}";
4736void JsonUnitTestResultPrinter::PrintJsonTestSuite(
4737 std::ostream* stream,
const TestSuite& test_suite) {
4738 const std::string kTestsuite =
"testsuite";
4739 const std::string kIndent =
Indent(6);
4741 *stream <<
Indent(4) <<
"{\n";
4742 OutputJsonKey(stream, kTestsuite,
"name", test_suite.name(), kIndent);
4743 OutputJsonKey(stream, kTestsuite,
"tests", test_suite.reportable_test_count(),
4745 if (!GTEST_FLAG_GET(list_tests)) {
4746 OutputJsonKey(stream, kTestsuite,
"failures",
4747 test_suite.failed_test_count(), kIndent);
4748 OutputJsonKey(stream, kTestsuite,
"disabled",
4749 test_suite.reportable_disabled_test_count(), kIndent);
4750 OutputJsonKey(stream, kTestsuite,
"errors", 0, kIndent);
4752 stream, kTestsuite,
"timestamp",
4755 OutputJsonKey(stream, kTestsuite,
"time",
4758 *stream << TestPropertiesAsJson(test_suite.ad_hoc_test_result(), kIndent)
4762 *stream << kIndent <<
"\"" << kTestsuite <<
"\": [\n";
4765 for (
int i = 0; i < test_suite.total_test_count(); ++i) {
4766 if (test_suite.GetTestInfo(i)->is_reportable()) {
4772 OutputJsonTestInfo(stream, test_suite.name(), *test_suite.GetTestInfo(i));
4775 *stream <<
"\n" << kIndent <<
"]\n" <<
Indent(4) <<
"}";
4779void JsonUnitTestResultPrinter::PrintJsonUnitTest(std::ostream* stream,
4780 const UnitTest& unit_test) {
4781 const std::string kTestsuites =
"testsuites";
4782 const std::string kIndent =
Indent(2);
4785 OutputJsonKey(stream, kTestsuites,
"tests", unit_test.reportable_test_count(),
4787 OutputJsonKey(stream, kTestsuites,
"failures", unit_test.failed_test_count(),
4789 OutputJsonKey(stream, kTestsuites,
"disabled",
4790 unit_test.reportable_disabled_test_count(), kIndent);
4791 OutputJsonKey(stream, kTestsuites,
"errors", 0, kIndent);
4792 if (GTEST_FLAG_GET(shuffle)) {
4793 OutputJsonKey(stream, kTestsuites,
"random_seed", unit_test.random_seed(),
4796 OutputJsonKey(stream, kTestsuites,
"timestamp",
4799 OutputJsonKey(stream, kTestsuites,
"time",
4803 *stream << TestPropertiesAsJson(unit_test.ad_hoc_test_result(), kIndent)
4806 OutputJsonKey(stream, kTestsuites,
"name",
"AllTests", kIndent);
4807 *stream << kIndent <<
"\"" << kTestsuites <<
"\": [\n";
4810 for (
int i = 0; i < unit_test.total_test_suite_count(); ++i) {
4811 if (unit_test.GetTestSuite(i)->reportable_test_count() > 0) {
4817 PrintJsonTestSuite(stream, *unit_test.GetTestSuite(i));
4823 if (unit_test.ad_hoc_test_result().Failed()) {
4824 OutputJsonTestSuiteForTestResult(stream, unit_test.ad_hoc_test_result());
4833 std::ostream* stream,
const std::vector<TestSuite*>& test_suites) {
4834 const std::string kTestsuites =
"testsuites";
4835 const std::string kIndent =
Indent(2);
4837 int total_tests = 0;
4838 for (
auto test_suite : test_suites) {
4839 total_tests += test_suite->total_test_count();
4841 OutputJsonKey(stream, kTestsuites,
"tests", total_tests, kIndent);
4843 OutputJsonKey(stream, kTestsuites,
"name",
"AllTests", kIndent);
4844 *stream << kIndent <<
"\"" << kTestsuites <<
"\": [\n";
4846 for (
size_t i = 0; i < test_suites.size(); ++i) {
4850 PrintJsonTestSuite(stream, *test_suites[i]);
4859std::string JsonUnitTestResultPrinter::TestPropertiesAsJson(
4860 const TestResult& result,
const std::string& indent) {
4862 for (
int i = 0; i < result.test_property_count(); ++i) {
4863 const TestProperty&
property = result.GetTestProperty(i);
4865 << indent <<
"\"" <<
property.key() <<
"\": "
4866 <<
"\"" << EscapeJson(property.value()) <<
"\"";
4868 return attributes.GetString();
4873#if GTEST_CAN_STREAM_RESULTS_
4880std::string StreamingListener::UrlEncode(
const char* str) {
4882 result.reserve(strlen(str) + 1);
4883 for (
char ch = *str; ch !=
'\0'; ch = *++str) {
4889 result.append(
"%" + String::FormatByte(
static_cast<unsigned char>(ch)));
4892 result.push_back(ch);
4899void StreamingListener::SocketWriter::MakeConnection() {
4900 GTEST_CHECK_(sockfd_ == -1)
4901 <<
"MakeConnection() can't be called when there is already a connection.";
4904 memset(&hints, 0,
sizeof(hints));
4905 hints.ai_family = AF_UNSPEC;
4906 hints.ai_socktype = SOCK_STREAM;
4907 addrinfo* servinfo =
nullptr;
4911 const int error_num =
4912 getaddrinfo(host_name_.c_str(), port_num_.c_str(), &hints, &servinfo);
4913 if (error_num != 0) {
4914 GTEST_LOG_(WARNING) <<
"stream_result_to: getaddrinfo() failed: "
4915 << gai_strerror(error_num);
4919 for (addrinfo* cur_addr = servinfo; sockfd_ == -1 && cur_addr !=
nullptr;
4920 cur_addr = cur_addr->ai_next) {
4921 sockfd_ = socket(cur_addr->ai_family, cur_addr->ai_socktype,
4922 cur_addr->ai_protocol);
4923 if (sockfd_ != -1) {
4925 if (connect(sockfd_, cur_addr->ai_addr, cur_addr->ai_addrlen) == -1) {
4932 freeaddrinfo(servinfo);
4934 if (sockfd_ == -1) {
4935 GTEST_LOG_(WARNING) <<
"stream_result_to: failed to connect to "
4936 << host_name_ <<
":" << port_num_;
4946 "... " GTEST_NAME_
" internal frames ...";
4949 GTEST_LOCK_EXCLUDED_(mutex_) {
4953 if (max_depth <= 0) {
4957 max_depth = std::min(max_depth, kMaxStackTraceDepth);
4959 std::vector<void*> raw_stack(max_depth);
4961 const int raw_stack_size =
4962 absl::GetStackTrace(&raw_stack[0], max_depth, skip_count + 1);
4964 void* caller_frame =
nullptr;
4966 MutexLock lock(&mutex_);
4967 caller_frame = caller_frame_;
4970 for (
int i = 0; i < raw_stack_size; ++i) {
4971 if (raw_stack[i] == caller_frame &&
4972 !GTEST_FLAG_GET(show_internal_stack_frames)) {
4974 absl::StrAppend(&result, kElidedFramesMarker,
"\n");
4979 const char* symbol =
"(unknown)";
4980 if (absl::Symbolize(raw_stack[i], tmp,
sizeof(tmp))) {
4985 snprintf(line,
sizeof(line),
" %p: %s\n", raw_stack[i], symbol);
4992 static_cast<void>(max_depth);
4993 static_cast<void>(skip_count);
5000 void* caller_frame =
nullptr;
5001 if (absl::GetStackTrace(&caller_frame, 1, 3) <= 0) {
5002 caller_frame =
nullptr;
5005 MutexLock lock(&mutex_);
5006 caller_frame_ = caller_frame;
5015 : premature_exit_filepath_(
5016 premature_exit_filepath ? premature_exit_filepath :
"") {
5018 if (!premature_exit_filepath_.empty()) {
5022 FILE* pfile = posix::FOpen(premature_exit_filepath_.c_str(),
"w");
5023 fwrite(
"0", 1, 1, pfile);
5029#if !defined GTEST_OS_ESP8266
5030 if (!premature_exit_filepath_.empty()) {
5031 int retval = remove(premature_exit_filepath_.c_str());
5033 GTEST_LOG_(ERROR) <<
"Failed to remove premature exit filepath \""
5034 << premature_exit_filepath_ <<
"\" with error "
5042 const std::string premature_exit_filepath_;
5052TestEventListeners::TestEventListeners()
5053 : repeater_(new internal::TestEventRepeater()),
5054 default_result_printer_(nullptr),
5055 default_xml_generator_(nullptr) {}
5057TestEventListeners::~TestEventListeners() {
delete repeater_; }
5063void TestEventListeners::Append(TestEventListener* listener) {
5064 repeater_->Append(listener);
5070TestEventListener* TestEventListeners::Release(TestEventListener* listener) {
5071 if (listener == default_result_printer_)
5072 default_result_printer_ =
nullptr;
5073 else if (listener == default_xml_generator_)
5074 default_xml_generator_ =
nullptr;
5075 return repeater_->Release(listener);
5080TestEventListener* TestEventListeners::repeater() {
return repeater_; }
5087void TestEventListeners::SetDefaultResultPrinter(TestEventListener* listener) {
5088 if (default_result_printer_ != listener) {
5091 delete Release(default_result_printer_);
5092 default_result_printer_ = listener;
5093 if (listener !=
nullptr) Append(listener);
5102void TestEventListeners::SetDefaultXmlGenerator(TestEventListener* listener) {
5103 if (default_xml_generator_ != listener) {
5106 delete Release(default_xml_generator_);
5107 default_xml_generator_ = listener;
5108 if (listener !=
nullptr) Append(listener);
5114bool TestEventListeners::EventForwardingEnabled()
const {
5115 return repeater_->forwarding_enabled();
5118void TestEventListeners::SuppressEventForwarding() {
5119 repeater_->set_forwarding_enabled(
false);
5131UnitTest* UnitTest::GetInstance() {
5136#if defined(__BORLANDC__)
5137 static UnitTest*
const instance =
new UnitTest;
5140 static UnitTest instance;
5146int UnitTest::successful_test_suite_count()
const {
5147 return impl()->successful_test_suite_count();
5151int UnitTest::failed_test_suite_count()
const {
5152 return impl()->failed_test_suite_count();
5156int UnitTest::total_test_suite_count()
const {
5157 return impl()->total_test_suite_count();
5162int UnitTest::test_suite_to_run_count()
const {
5163 return impl()->test_suite_to_run_count();
5167#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
5168int UnitTest::successful_test_case_count()
const {
5169 return impl()->successful_test_suite_count();
5171int UnitTest::failed_test_case_count()
const {
5172 return impl()->failed_test_suite_count();
5174int UnitTest::total_test_case_count()
const {
5175 return impl()->total_test_suite_count();
5177int UnitTest::test_case_to_run_count()
const {
5178 return impl()->test_suite_to_run_count();
5183int UnitTest::successful_test_count()
const {
5184 return impl()->successful_test_count();
5188int UnitTest::skipped_test_count()
const {
5189 return impl()->skipped_test_count();
5193int UnitTest::failed_test_count()
const {
return impl()->failed_test_count(); }
5196int UnitTest::reportable_disabled_test_count()
const {
5197 return impl()->reportable_disabled_test_count();
5201int UnitTest::disabled_test_count()
const {
5202 return impl()->disabled_test_count();
5206int UnitTest::reportable_test_count()
const {
5207 return impl()->reportable_test_count();
5211int UnitTest::total_test_count()
const {
return impl()->total_test_count(); }
5214int UnitTest::test_to_run_count()
const {
return impl()->test_to_run_count(); }
5218internal::TimeInMillis UnitTest::start_timestamp()
const {
5219 return impl()->start_timestamp();
5223internal::TimeInMillis UnitTest::elapsed_time()
const {
5224 return impl()->elapsed_time();
5229bool UnitTest::Passed()
const {
return impl()->Passed(); }
5233bool UnitTest::Failed()
const {
return impl()->Failed(); }
5237const TestSuite* UnitTest::GetTestSuite(
int i)
const {
5238 return impl()->GetTestSuite(i);
5242#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
5243const TestCase* UnitTest::GetTestCase(
int i)
const {
5244 return impl()->GetTestCase(i);
5250const TestResult& UnitTest::ad_hoc_test_result()
const {
5251 return *impl()->ad_hoc_test_result();
5256TestSuite* UnitTest::GetMutableTestSuite(
int i) {
5257 return impl()->GetMutableSuiteCase(i);
5262TestEventListeners& UnitTest::listeners() {
return *impl()->listeners(); }
5274Environment* UnitTest::AddEnvironment(Environment* env) {
5275 if (env ==
nullptr) {
5279 impl_->environments().push_back(env);
5287void UnitTest::AddTestPartResult(TestPartResult::Type result_type,
5288 const char* file_name,
int line_number,
5289 const std::string& message,
5290 const std::string& os_stack_trace)
5291 GTEST_LOCK_EXCLUDED_(mutex_) {
5295 internal::MutexLock lock(&mutex_);
5296 if (impl_->gtest_trace_stack().size() > 0) {
5297 msg <<
"\n" << GTEST_NAME_ <<
" trace:";
5299 for (
size_t i = impl_->gtest_trace_stack().size(); i > 0; --i) {
5300 const internal::TraceInfo& trace = impl_->gtest_trace_stack()[i - 1];
5307 if (os_stack_trace.c_str() !=
nullptr && !os_stack_trace.empty()) {
5311 const TestPartResult result = TestPartResult(
5312 result_type, file_name, line_number, msg.GetString().c_str());
5313 impl_->GetTestPartResultReporterForCurrentThread()->ReportTestPartResult(
5316 if (result_type != TestPartResult::kSuccess &&
5317 result_type != TestPartResult::kSkip) {
5323 if (GTEST_FLAG_GET(break_on_failure)) {
5324#if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_PHONE && !GTEST_OS_WINDOWS_RT
5329#elif (!defined(__native_client__)) && \
5330 ((defined(__clang__) || defined(__GNUC__)) && \
5331 (defined(__x86_64__) || defined(__i386__)))
5338 *
static_cast<volatile int*
>(
nullptr) = 1;
5340 }
else if (GTEST_FLAG_GET(throw_on_failure)) {
5341#if GTEST_HAS_EXCEPTIONS
5342 throw internal::GoogleTestFailureException(result);
5357void UnitTest::RecordProperty(
const std::string& key,
5358 const std::string& value) {
5359 impl_->RecordProperty(TestProperty(key, value));
5367int UnitTest::Run() {
5368 const bool in_death_test_child_process =
5369 GTEST_FLAG_GET(internal_run_death_test).length() > 0;
5392 const internal::ScopedPrematureExitFile premature_exit_file(
5393 in_death_test_child_process
5395 : internal::posix::GetEnv(
"TEST_PREMATURE_EXIT_FILE"));
5399 impl()->set_catch_exceptions(GTEST_FLAG_GET(catch_exceptions));
5406 if (impl()->catch_exceptions() || in_death_test_child_process) {
5407#if !GTEST_OS_WINDOWS_MOBILE && !GTEST_OS_WINDOWS_PHONE && !GTEST_OS_WINDOWS_RT
5409 SetErrorMode(SEM_FAILCRITICALERRORS | SEM_NOALIGNMENTFAULTEXCEPT |
5410 SEM_NOGPFAULTERRORBOX | SEM_NOOPENFILEERRORBOX);
5413#if (defined(_MSC_VER) || GTEST_OS_WINDOWS_MINGW) && !GTEST_OS_WINDOWS_MOBILE
5417 _set_error_mode(_OUT_TO_STDERR);
5420#if defined(_MSC_VER) && !GTEST_OS_WINDOWS_MOBILE
5426 if (!GTEST_FLAG_GET(break_on_failure))
5427 _set_abort_behavior(
5429 _WRITE_ABORT_MSG | _CALL_REPORTFAULT);
5435 if (!IsDebuggerPresent()) {
5436 (void)_CrtSetReportMode(_CRT_ASSERT,
5437 _CRTDBG_MODE_FILE | _CRTDBG_MODE_DEBUG);
5438 (void)_CrtSetReportFile(_CRT_ASSERT, _CRTDBG_FILE_STDERR);
5446 "auxiliary test code (environments or event listeners)")
5453const char* UnitTest::original_working_dir()
const {
5454 return impl_->original_working_dir_.c_str();
5459const TestSuite* UnitTest::current_test_suite() const
5460 GTEST_LOCK_EXCLUDED_(mutex_) {
5461 internal::MutexLock lock(&mutex_);
5462 return impl_->current_test_suite();
5466#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
5467const TestCase* UnitTest::current_test_case() const
5468 GTEST_LOCK_EXCLUDED_(mutex_) {
5469 internal::MutexLock lock(&mutex_);
5470 return impl_->current_test_suite();
5476const TestInfo* UnitTest::current_test_info() const
5477 GTEST_LOCK_EXCLUDED_(mutex_) {
5478 internal::MutexLock lock(&mutex_);
5479 return impl_->current_test_info();
5483int UnitTest::random_seed()
const {
return impl_->random_seed(); }
5487internal::ParameterizedTestSuiteRegistry&
5488UnitTest::parameterized_test_registry() GTEST_LOCK_EXCLUDED_(mutex_) {
5489 return impl_->parameterized_test_registry();
5493UnitTest::UnitTest() { impl_ =
new internal::UnitTestImpl(
this); }
5496UnitTest::~UnitTest() {
delete impl_; }
5500void UnitTest::PushGTestTrace(
const internal::TraceInfo& trace)
5501 GTEST_LOCK_EXCLUDED_(mutex_) {
5502 internal::MutexLock lock(&mutex_);
5503 impl_->gtest_trace_stack().push_back(trace);
5507void UnitTest::PopGTestTrace() GTEST_LOCK_EXCLUDED_(mutex_) {
5508 internal::MutexLock lock(&mutex_);
5509 impl_->gtest_trace_stack().pop_back();
5514UnitTestImpl::UnitTestImpl(UnitTest* parent)
5517 default_global_test_part_result_reporter_(this),
5518 default_per_thread_test_part_result_reporter_(this),
5519 GTEST_DISABLE_MSC_WARNINGS_POP_() global_test_part_result_repoter_(
5520 &default_global_test_part_result_reporter_),
5521 per_thread_test_part_result_reporter_(
5522 &default_per_thread_test_part_result_reporter_),
5523 parameterized_test_registry_(),
5524 parameterized_tests_registered_(false),
5525 last_death_test_suite_(-1),
5526 current_test_suite_(nullptr),
5527 current_test_info_(nullptr),
5528 ad_hoc_test_result_(),
5529 os_stack_trace_getter_(nullptr),
5530 post_flag_parse_init_performed_(false),
5533 start_timestamp_(0),
5535#if GTEST_HAS_DEATH_TEST
5536 death_test_factory_(new DefaultDeathTestFactory),
5539 catch_exceptions_(false) {
5514UnitTestImpl::UnitTestImpl(UnitTest* parent) {
…}
5545 ForEach(test_suites_, internal::Delete<TestSuite>);
5548 ForEach(environments_, internal::Delete<Environment>);
5550 delete os_stack_trace_getter_;
5559 std::string xml_element;
5560 TestResult* test_result;
5562 if (current_test_info_ !=
nullptr) {
5563 xml_element =
"testcase";
5564 test_result = &(current_test_info_->result_);
5565 }
else if (current_test_suite_ !=
nullptr) {
5566 xml_element =
"testsuite";
5567 test_result = &(current_test_suite_->ad_hoc_test_result_);
5569 xml_element =
"testsuites";
5570 test_result = &ad_hoc_test_result_;
5572 test_result->RecordProperty(xml_element, test_property);
5575#if GTEST_HAS_DEATH_TEST
5578void UnitTestImpl::SuppressTestEventsIfInSubprocess() {
5579 if (internal_run_death_test_flag_.get() !=
nullptr)
5588 if (output_format ==
"xml") {
5591 }
else if (output_format ==
"json") {
5594 }
else if (output_format !=
"") {
5595 GTEST_LOG_(WARNING) <<
"WARNING: unrecognized output format \""
5596 << output_format <<
"\" ignored.";
5600#if GTEST_CAN_STREAM_RESULTS_
5603void UnitTestImpl::ConfigureStreamingOutput() {
5604 const std::string& target = GTEST_FLAG_GET(stream_result_to);
5605 if (!target.empty()) {
5606 const size_t pos = target.find(
':');
5607 if (pos != std::string::npos) {
5609 new StreamingListener(target.substr(0, pos), target.substr(pos + 1)));
5611 GTEST_LOG_(WARNING) <<
"unrecognized streaming target \"" << target
5625 if (!post_flag_parse_init_performed_) {
5626 post_flag_parse_init_performed_ =
true;
5628#if defined(GTEST_CUSTOM_TEST_EVENT_LISTENER_)
5630 listeners()->Append(
new GTEST_CUSTOM_TEST_EVENT_LISTENER_());
5633#if GTEST_HAS_DEATH_TEST
5634 InitDeathTestSubprocessControlInfo();
5635 SuppressTestEventsIfInSubprocess();
5647 if (GTEST_FLAG_GET(brief)) {
5651#if GTEST_CAN_STREAM_RESULTS_
5653 ConfigureStreamingOutput();
5657 if (GTEST_FLAG_GET(install_failure_signal_handler)) {
5658 absl::FailureSignalHandlerOptions options;
5659 absl::InstallFailureSignalHandler(options);
5680 return test_suite !=
nullptr &&
5681 strcmp(test_suite->name(), name_.c_str()) == 0;
5701 const char* test_suite_name,
const char* type_param,
5702 internal::SetUpTestSuiteFunc set_up_tc,
5703 internal::TearDownTestSuiteFunc tear_down_tc) {
5705 const auto test_suite =
5706 std::find_if(test_suites_.rbegin(), test_suites_.rend(),
5709 if (test_suite != test_suites_.rend())
return *test_suite;
5712 auto*
const new_test_suite =
5713 new TestSuite(test_suite_name, type_param, set_up_tc, tear_down_tc);
5717 if (death_test_suite_filter.MatchesName(test_suite_name)) {
5722 ++last_death_test_suite_;
5723 test_suites_.insert(test_suites_.begin() + last_death_test_suite_,
5727 test_suites_.push_back(new_test_suite);
5730 test_suite_indices_.push_back(
static_cast<int>(test_suite_indices_.size()));
5731 return new_test_suite;
5767 bool in_subprocess_for_death_test =
false;
5769#if GTEST_HAS_DEATH_TEST
5770 in_subprocess_for_death_test =
5771 (internal_run_death_test_flag_.get() !=
nullptr);
5772#if defined(GTEST_EXTRA_DEATH_TEST_CHILD_SETUP_)
5773 if (in_subprocess_for_death_test) {
5774 GTEST_EXTRA_DEATH_TEST_CHILD_SETUP_();
5780 in_subprocess_for_death_test);
5784 const bool has_tests_to_run =
5789 if (GTEST_FLAG_GET(list_tests)) {
5798 bool failed =
false;
5800 TestEventListener* repeater =
listeners()->repeater();
5803 repeater->OnTestProgramStart(*parent_);
5807 const int repeat = in_subprocess_for_death_test ? 1 : GTEST_FLAG_GET(repeat);
5810 const bool gtest_repeat_forever = repeat < 0;
5818 const bool recreate_environments_when_repeating =
5819 GTEST_FLAG_GET(recreate_environments_when_repeating) ||
5820 gtest_repeat_forever;
5822 for (
int i = 0; gtest_repeat_forever || i != repeat; i++) {
5830 if (has_tests_to_run && GTEST_FLAG_GET(shuffle)) {
5831 random()->Reseed(
static_cast<uint32_t
>(random_seed_));
5839 repeater->OnTestIterationStart(*parent_, i);
5842 if (has_tests_to_run) {
5845 if (i == 0 || recreate_environments_when_repeating) {
5846 repeater->OnEnvironmentsSetUpStart(*parent_);
5848 repeater->OnEnvironmentsSetUpEnd(*parent_);
5853 if (Test::IsSkipped()) {
5856 TestResult& test_result =
5858 for (
int j = 0; j < test_result.total_part_count(); ++j) {
5859 const TestPartResult& test_part_result =
5860 test_result.GetTestPartResult(j);
5861 if (test_part_result.type() == TestPartResult::kSkip) {
5862 const std::string& result = test_part_result.message();
5863 printf(
"%s\n", result.c_str());
5867 }
else if (!Test::HasFatalFailure()) {
5871 if (GTEST_FLAG_GET(fail_fast) &&
5879 }
else if (Test::HasFatalFailure()) {
5892 if (i == repeat - 1 || recreate_environments_when_repeating) {
5893 repeater->OnEnvironmentsTearDownStart(*parent_);
5894 std::for_each(environments_.rbegin(), environments_.rend(),
5896 repeater->OnEnvironmentsTearDownEnd(*parent_);
5900 elapsed_time_ = timer.
Elapsed();
5903 repeater->OnTestIterationEnd(*parent_, i);
5918 if (GTEST_FLAG_GET(shuffle)) {
5924 repeater->OnTestProgramEnd(*parent_);
5926 if (!gtest_is_initialized_before_run_all_tests) {
5929 "\nIMPORTANT NOTICE - DO NOT IGNORE:\n"
5930 "This test program did NOT call " GTEST_INIT_GOOGLE_TEST_NAME_
5931 "() before calling RUN_ALL_TESTS(). This is INVALID. Soon " GTEST_NAME_
5932 " will start to enforce the valid usage. "
5933 "Please fix it ASAP, or IT WILL START TO FAIL.\n");
5934#if GTEST_FOR_GOOGLE_
5936 "For more details, see http://wiki/Main/ValidGUnitMain.\n");
5949 if (test_shard_file !=
nullptr) {
5950 FILE*
const file = posix::FOpen(test_shard_file,
"w");
5951 if (file ==
nullptr) {
5953 "Could not write to the test shard status file \"%s\" "
5954 "specified by the %s environment variable.\n",
5969bool ShouldShard(
const char* total_shards_env,
const char* shard_index_env,
5970 bool in_subprocess_for_death_test) {
5971 if (in_subprocess_for_death_test) {
5978 if (total_shards == -1 && shard_index == -1) {
5980 }
else if (total_shards == -1 && shard_index != -1) {
5981 const Message msg = Message() <<
"Invalid environment variables: you have "
5985 ColoredPrintf(GTestColor::kRed,
"%s", msg.GetString().c_str());
5988 }
else if (total_shards != -1 && shard_index == -1) {
5989 const Message msg = Message()
5990 <<
"Invalid environment variables: you have "
5993 ColoredPrintf(GTestColor::kRed,
"%s", msg.GetString().c_str());
5996 }
else if (shard_index < 0 || shard_index >= total_shards) {
5998 Message() <<
"Invalid environment variables: we require 0 <= "
6002 ColoredPrintf(GTestColor::kRed,
"%s", msg.GetString().c_str());
6007 return total_shards > 1;
5969bool ShouldShard(
const char* total_shards_env,
const char* shard_index_env, {
…}
6014 const char* str_val = posix::GetEnv(var);
6015 if (str_val ==
nullptr) {
6020 if (!
ParseInt32(Message() <<
"The value of environment variable " << var,
6021 str_val, &result)) {
6032 return (test_id % total_shards) == shard_index;
6050 const PositiveAndNegativeUnitTestFilter gtest_flag_filter(
6051 GTEST_FLAG_GET(filter));
6057 int num_runnable_tests = 0;
6058 int num_selected_tests = 0;
6059 for (
auto* test_suite : test_suites_) {
6060 const std::string& test_suite_name = test_suite->name();
6061 test_suite->set_should_run(
false);
6063 for (
size_t j = 0; j < test_suite->test_info_list().size(); j++) {
6064 TestInfo*
const test_info = test_suite->test_info_list()[j];
6065 const std::string test_name(test_info->name());
6068 const bool is_disabled =
6069 disable_test_filter.MatchesName(test_suite_name) ||
6070 disable_test_filter.MatchesName(test_name);
6071 test_info->is_disabled_ = is_disabled;
6073 const bool matches_filter =
6074 gtest_flag_filter.MatchesTest(test_suite_name, test_name);
6075 test_info->matches_filter_ = matches_filter;
6077 const bool is_runnable =
6078 (GTEST_FLAG_GET(also_run_disabled_tests) || !is_disabled) &&
6081 const bool is_in_another_shard =
6084 test_info->is_in_another_shard_ = is_in_another_shard;
6085 const bool is_selected = is_runnable && !is_in_another_shard;
6087 num_runnable_tests += is_runnable;
6088 num_selected_tests += is_selected;
6090 test_info->should_run_ = is_selected;
6091 test_suite->set_should_run(test_suite->should_run() || is_selected);
6094 return num_selected_tests;
6102 if (str !=
nullptr) {
6103 for (
int i = 0; *str !=
'\0'; ++str) {
6104 if (i >= max_length) {
6122 const int kMaxParamLength = 250;
6124 for (
auto* test_suite : test_suites_) {
6125 bool printed_test_suite_name =
false;
6127 for (
size_t j = 0; j < test_suite->test_info_list().size(); j++) {
6128 const TestInfo*
const test_info = test_suite->test_info_list()[j];
6129 if (test_info->matches_filter_) {
6130 if (!printed_test_suite_name) {
6131 printed_test_suite_name =
true;
6132 printf(
"%s.", test_suite->name());
6133 if (test_suite->type_param() !=
nullptr) {
6141 printf(
" %s", test_info->name());
6142 if (test_info->value_param() !=
nullptr) {
6154 if (output_format ==
"xml" || output_format ==
"json") {
6157 std::stringstream stream;
6158 if (output_format ==
"xml") {
6162 }
else if (output_format ==
"json") {
6179 if (os_stack_trace_getter_ != getter) {
6180 delete os_stack_trace_getter_;
6181 os_stack_trace_getter_ = getter;
6189 if (os_stack_trace_getter_ ==
nullptr) {
6190#ifdef GTEST_OS_STACK_TRACE_GETTER_
6191 os_stack_trace_getter_ =
new GTEST_OS_STACK_TRACE_GETTER_;
6197 return os_stack_trace_getter_;
6202 if (current_test_info_ !=
nullptr) {
6203 return ¤t_test_info_->result_;
6205 if (current_test_suite_ !=
nullptr) {
6206 return ¤t_test_suite_->ad_hoc_test_result_;
6208 return &ad_hoc_test_result_;
6219 static_cast<int>(test_suites_.size()), &test_suite_indices_);
6222 for (
auto& test_suite : test_suites_) {
6223 test_suite->ShuffleTests(
random());
6229 for (
size_t i = 0; i < test_suites_.size(); i++) {
6231 test_suites_[i]->UnshuffleTests();
6233 test_suite_indices_[i] =
static_cast<int>(i);
6247GTEST_NO_INLINE_ GTEST_NO_TAIL_CALL_ std::string
6257class ClassUniqueToAlwaysTrue {};
6260bool IsTrue(
bool condition) {
return condition; }
6263#if GTEST_HAS_EXCEPTIONS
6266 if (
IsTrue(
false))
throw ClassUniqueToAlwaysTrue();
6275 const size_t prefix_len = strlen(prefix);
6276 if (strncmp(*pstr, prefix, prefix_len) == 0) {
6277 *pstr += prefix_len;
6289 bool def_optional) {
6291 if (str ==
nullptr || flag_name ==
nullptr)
return nullptr;
6294 const std::string flag_str =
6295 std::string(
"--") + GTEST_FLAG_PREFIX_ + flag_name;
6296 const size_t flag_len = flag_str.length();
6297 if (strncmp(str, flag_str.c_str(), flag_len) != 0)
return nullptr;
6300 const char* flag_end = str + flag_len;
6303 if (def_optional && (flag_end[0] ==
'\0')) {
6310 if (flag_end[0] !=
'=')
return nullptr;
6313 return flag_end + 1;
6326static bool ParseFlag(
const char* str,
const char* flag_name,
bool* value) {
6328 const char*
const value_str =
ParseFlagValue(str, flag_name,
true);
6331 if (value_str ==
nullptr)
return false;
6334 *value = !(*value_str ==
'0' || *value_str ==
'f' || *value_str ==
'F');
6326static bool ParseFlag(
const char* str,
const char* flag_name,
bool* value) {
…}
6342bool ParseFlag(
const char* str,
const char* flag_name, int32_t* value) {
6344 const char*
const value_str =
ParseFlagValue(str, flag_name,
false);
6347 if (value_str ==
nullptr)
return false;
6350 return ParseInt32(Message() <<
"The value of flag --" << flag_name, value_str,
6342bool ParseFlag(
const char* str,
const char* flag_name, int32_t* value) {
…}
6358template <
typename String>
6359static bool ParseFlag(
const char* str,
const char* flag_name, String* value) {
6361 const char*
const value_str =
ParseFlagValue(str, flag_name,
false);
6364 if (value_str ==
nullptr)
return false;
6359static bool ParseFlag(
const char* str,
const char* flag_name, String* value) {
…}
6380 !
SkipPrefix(GTEST_FLAG_PREFIX_
"internal_", &str) &&
6395 GTestColor color = GTestColor::kDefault;
6402 const char* p = strchr(str,
'@');
6410 const char ch = p[1];
6414 }
else if (ch ==
'D') {
6415 color = GTestColor::kDefault;
6416 }
else if (ch ==
'R') {
6417 color = GTestColor::kRed;
6418 }
else if (ch ==
'G') {
6419 color = GTestColor::kGreen;
6420 }
else if (ch ==
'Y') {
6421 color = GTestColor::kYellow;
6429 "This program contains tests written using " GTEST_NAME_
6430 ". You can use the\n"
6431 "following command line flags to control its behavior:\n"
6434 " @G--" GTEST_FLAG_PREFIX_
6436 " List the names of all tests instead of running them. The name of\n"
6437 " TEST(Foo, Bar) is \"Foo.Bar\".\n"
6438 " @G--" GTEST_FLAG_PREFIX_
6439 "filter=@YPOSITIVE_PATTERNS"
6440 "[@G-@YNEGATIVE_PATTERNS]@D\n"
6441 " Run only the tests whose name matches one of the positive patterns "
6443 " none of the negative patterns. '?' matches any single character; "
6445 " matches any substring; ':' separates two patterns.\n"
6446 " @G--" GTEST_FLAG_PREFIX_
6447 "also_run_disabled_tests@D\n"
6448 " Run all disabled tests too.\n"
6451 " @G--" GTEST_FLAG_PREFIX_
6452 "repeat=@Y[COUNT]@D\n"
6453 " Run the tests repeatedly; use a negative count to repeat forever.\n"
6454 " @G--" GTEST_FLAG_PREFIX_
6456 " Randomize tests' orders on every iteration.\n"
6457 " @G--" GTEST_FLAG_PREFIX_
6458 "random_seed=@Y[NUMBER]@D\n"
6459 " Random number seed to use for shuffling test orders (between 1 and\n"
6460 " 99999, or 0 to use a seed based on the current time).\n"
6461 " @G--" GTEST_FLAG_PREFIX_
6462 "recreate_environments_when_repeating@D\n"
6463 " Sets up and tears down the global test environment on each repeat\n"
6467 " @G--" GTEST_FLAG_PREFIX_
6468 "color=@Y(@Gyes@Y|@Gno@Y|@Gauto@Y)@D\n"
6469 " Enable/disable colored output. The default is @Gauto@D.\n"
6470 " @G--" GTEST_FLAG_PREFIX_
6472 " Only print test failures.\n"
6473 " @G--" GTEST_FLAG_PREFIX_
6475 " Don't print the elapsed time of each test.\n"
6476 " @G--" GTEST_FLAG_PREFIX_
6477 "output=@Y(@Gjson@Y|@Gxml@Y)[@G:@YDIRECTORY_PATH@G" GTEST_PATH_SEP_
6478 "@Y|@G:@YFILE_PATH]@D\n"
6479 " Generate a JSON or XML report in the given directory or with the "
6481 " file name. @YFILE_PATH@D defaults to @Gtest_detail.xml@D.\n"
6482#if GTEST_CAN_STREAM_RESULTS_
6483 " @G--" GTEST_FLAG_PREFIX_
6484 "stream_result_to=@YHOST@G:@YPORT@D\n"
6485 " Stream test results to the given server.\n"
6488 "Assertion Behavior:\n"
6489#if GTEST_HAS_DEATH_TEST && !GTEST_OS_WINDOWS
6490 " @G--" GTEST_FLAG_PREFIX_
6491 "death_test_style=@Y(@Gfast@Y|@Gthreadsafe@Y)@D\n"
6492 " Set the default death test style.\n"
6494 " @G--" GTEST_FLAG_PREFIX_
6495 "break_on_failure@D\n"
6496 " Turn assertion failures into debugger break-points.\n"
6497 " @G--" GTEST_FLAG_PREFIX_
6498 "throw_on_failure@D\n"
6499 " Turn assertion failures into C++ exceptions for use by an external\n"
6500 " test framework.\n"
6501 " @G--" GTEST_FLAG_PREFIX_
6502 "catch_exceptions=0@D\n"
6503 " Do not report exceptions as test failures. Instead, allow them\n"
6504 " to crash the program or throw a pop-up (on Windows).\n"
6506 "Except for @G--" GTEST_FLAG_PREFIX_
6507 "list_tests@D, you can alternatively set "
6508 "the corresponding\n"
6509 "environment variable of a flag (all letters in upper-case). For example, "
6511 "disable colored text output, you can either specify "
6512 "@G--" GTEST_FLAG_PREFIX_
6513 "color=no@D or set\n"
6514 "the @G" GTEST_FLAG_PREFIX_UPPER_
6515 "COLOR@D environment variable to @Gno@D.\n"
6517 "For more information, please read the " GTEST_NAME_
6518 " documentation at\n"
6519 "@G" GTEST_PROJECT_URL_
"@D. If you find a bug in " GTEST_NAME_
6521 "(not one in your own code or tests), please report it to\n"
6522 "@G<" GTEST_DEV_EMAIL_
">@D.\n";
6525#define GTEST_INTERNAL_PARSE_FLAG(flag_name) \
6527 auto value = GTEST_FLAG_GET(flag_name); \
6528 if (ParseFlag(arg, #flag_name, &value)) { \
6529 GTEST_FLAG_SET(flag_name, value); \
6558#if GTEST_USE_OWN_FLAGFILE_FLAG_
6559static void LoadFlagsFromFile(
const std::string& path) {
6560 FILE* flagfile = posix::FOpen(path.c_str(),
"r");
6562 GTEST_LOG_(FATAL) <<
"Unable to open file \"" << GTEST_FLAG_GET(flagfile)
6566 posix::FClose(flagfile);
6567 std::vector<std::string> lines;
6569 for (
size_t i = 0; i < lines.size(); ++i) {
6570 if (lines[i].empty())
continue;
6579template <
typename CharType>
6581 std::string flagfile_value;
6582 for (
int i = 1; i < *argc; i++) {
6583 const std::string arg_string = StreamableToString(argv[i]);
6584 const char*
const arg = arg_string.c_str();
6588 bool remove_flag =
false;
6591#if GTEST_USE_OWN_FLAGFILE_FLAG_
6592 }
else if (
ParseFlag(arg,
"flagfile", &flagfile_value)) {
6593 GTEST_FLAG_SET(flagfile, flagfile_value);
6594 LoadFlagsFromFile(flagfile_value);
6608 for (
int j = i; j != *argc; j++) {
6609 argv[j] = argv[j + 1];
6635 auto positional_args = absl::flags_internal::ParseCommandLineImpl(
6636 *argc, argv, absl::flags_internal::ArgvListAction::kRemoveParsedArgs,
6637 absl::flags_internal::UsageFlagsAction::kHandleUsage,
6638 absl::flags_internal::OnUndefinedFlag::kReportUndefined);
6644 std::copy(positional_args.begin(), positional_args.end(), argv);
6645 if (
static_cast<int>(positional_args.size()) < *argc) {
6646 argv[positional_args.size()] =
nullptr;
6647 *argc =
static_cast<int>(positional_args.size());
6659 if (*_NSGetArgv() == argv) {
6660 *_NSGetArgc() = *argc;
6673template <
typename CharType>
6678 if (*argc <= 0)
return;
6681 for (
int i = 0; i != *argc; i++) {
6682 g_argvs.push_back(StreamableToString(argv[i]));
6686 absl::InitializeSymbolizer(
g_argvs[0].c_str());
6690 absl::SetProgramUsageMessage(absl::StrReplaceAll(
6692 {{
"@D",
""}, {
"@R",
""}, {
"@G",
""}, {
"@Y",
""}, {
"@@",
"@"}}));
6711#if defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_)
6712 GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_(argc, argv);
6721#if defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_)
6722 GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_(argc, argv);
6733 const auto arg0 =
"dummy";
6734 char* argv0 =
const_cast<char*
>(arg0);
6735 char** argv = &argv0;
6737#if defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_)
6738 GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_(&argc, argv);
6744#if !defined(GTEST_CUSTOM_TEMPDIR_FUNCTION_)
6750 std::initializer_list<const char*> environment_variables,
6751 const char* fallback,
char separator) {
6752 for (
const char* variable_name : environment_variables) {
6753 const char* value = internal::posix::GetEnv(variable_name);
6754 if (value !=
nullptr && value[0] !=
'\0') {
6755 if (value[strlen(value) - 1] != separator) {
6756 return std::string(value).append(1, separator);
6766#if defined(GTEST_CUSTOM_TEMPDIR_FUNCTION_)
6767 return GTEST_CUSTOM_TEMPDIR_FUNCTION_();
6768#elif GTEST_OS_WINDOWS || GTEST_OS_WINDOWS_MOBILE
6770#elif GTEST_OS_LINUX_ANDROID
6781void ScopedTrace::PushTrace(
const char* file,
int line, std::string message) {
6782 internal::TraceInfo trace;
6785 trace.message.swap(message);
6787 UnitTest::GetInstance()->PushGTestTrace(trace);
6791ScopedTrace::~ScopedTrace() GTEST_LOCK_EXCLUDED_(&UnitTest::mutex_) {
6792 UnitTest::GetInstance()->PopGTestTrace();
void OnEnvironmentsTearDownStart(const UnitTest &) override
void OnTestIterationStart(const UnitTest &, int) override
BriefUnitTestResultPrinter()
void OnTestCaseStart(const TestCase &) override
void OnEnvironmentsSetUpStart(const UnitTest &) override
void OnEnvironmentsTearDownEnd(const UnitTest &) override
void OnTestProgramStart(const UnitTest &) override
void OnTestProgramEnd(const UnitTest &) override
static void PrintTestName(const char *test_suite, const char *test)
void OnTestStart(const TestInfo &) override
void OnTestCaseEnd(const TestCase &) override
void OnTestDisabled(const TestInfo &) override
void OnEnvironmentsSetUpEnd(const UnitTest &) override
void ReportTestPartResult(const TestPartResult &result) override
DefaultPerThreadTestPartResultReporter(UnitTestImpl *unit_test)
void ReportTestPartResult(const TestPartResult &result) override
JsonUnitTestResultPrinter(const char *output_file)
static void PrintJsonTestList(::std::ostream *stream, const std::vector< TestSuite * > &test_suites)
void OnTestIterationEnd(const UnitTest &unit_test, int iteration) override
void UponLeavingGTest() override
std::string CurrentStackTrace(int max_depth, int skip_count) override
virtual std::string CurrentStackTrace(int max_depth, int skip_count)=0
static const char *const kElidedFramesMarker
void OnTestProgramStart(const UnitTest &) override
void OnTestProgramEnd(const UnitTest &) override
void OnEnvironmentsTearDownEnd(const UnitTest &) override
PrettyUnitTestResultPrinter()
void OnEnvironmentsSetUpEnd(const UnitTest &) override
static void PrintTestName(const char *test_suite, const char *test)
ScopedPrematureExitFile(const char *premature_exit_filepath)
~ScopedPrematureExitFile()
void OnEnvironmentsTearDownEnd(const UnitTest &unit_test) override
void OnTestEnd(const TestInfo &test_info) override
void OnTestProgramEnd(const UnitTest &unit_test) override
void OnTestStart(const TestInfo &test_info) override
void OnTestSuiteEnd(const TestSuite ¶meter) override
void OnEnvironmentsSetUpStart(const UnitTest &unit_test) override
void OnEnvironmentsSetUpEnd(const UnitTest &unit_test) override
void OnTestCaseStart(const TestSuite ¶meter) override
void set_forwarding_enabled(bool enable)
void OnTestCaseEnd(const TestCase ¶meter) override
void OnEnvironmentsTearDownStart(const UnitTest &unit_test) override
void OnTestSuiteStart(const TestSuite ¶meter) override
void OnTestPartResult(const TestPartResult &result) override
bool forwarding_enabled() const
void OnTestProgramStart(const UnitTest &unit_test) override
void OnTestDisabled(const TestInfo &test_info) override
bool operator()(const TestSuite *test_suite) const
TestSuiteNameIs(const std::string &name)
int reportable_disabled_test_count() const
int disabled_test_count() const
internal::Random * random()
int test_to_run_count() const
void SetTestPartResultReporterForCurrentThread(TestPartResultReporterInterface *reporter)
void RecordProperty(const TestProperty &test_property)
TestPartResultReporterInterface * GetGlobalTestPartResultReporter()
void ConfigureXmlOutput()
TestEventListeners * listeners()
std::string CurrentOsStackTraceExceptTop(int skip_count) GTEST_NO_INLINE_ GTEST_NO_TAIL_CALL_
int test_suite_to_run_count() const
void set_os_stack_trace_getter(OsStackTraceGetterInterface *getter)
TestSuite * GetMutableSuiteCase(int i)
TestPartResultReporterInterface * GetTestPartResultReporterForCurrentThread()
OsStackTraceGetterInterface * os_stack_trace_getter()
void PostFlagParsingInit()
void SetGlobalTestPartResultReporter(TestPartResultReporterInterface *reporter)
int total_test_count() const
int successful_test_suite_count() const
void ClearNonAdHocTestResult()
void AddTestInfo(internal::SetUpTestSuiteFunc set_up_tc, internal::TearDownTestSuiteFunc tear_down_tc, TestInfo *test_info)
TestResult * current_test_result()
int FilterTests(ReactionToSharding shard_tests)
int failed_test_suite_count() const
int successful_test_count() const
@ IGNORE_SHARDING_PROTOCOL
@ HONOR_SHARDING_PROTOCOL
int failed_test_count() const
void ListTestsMatchingFilter()
int skipped_test_count() const
int reportable_test_count() const
int total_test_suite_count() const
void RegisterParameterizedTests()
const TestSuite * GetTestSuite(int i) const
static std::string GetAbsolutePathToOutputFile()
static std::string GetOutputFormat()
static void PrintXmlTestsList(std::ostream *stream, const std::vector< TestSuite * > &test_suites)
void ListTestsMatchingFilter(const std::vector< TestSuite * > &test_suites)
void OnTestIterationEnd(const UnitTest &unit_test, int iteration) override
GTEST_DISABLE_MSC_WARNINGS_PUSH_(4251) namespace testing
GTEST_DEFINE_bool_(fail_fast, testing::internal::BoolFromGTestEnv("fail_fast", testing::GetDefaultFailFast()), "True if and only if a test failure should stop further test execution.")
#define GTEST_INTERNAL_PARSE_FLAG(flag_name)
GTEST_DEFINE_int32_(random_seed, testing::internal::Int32FromGTestEnv("random_seed", 0), "Random number seed to use when shuffling test orders. Must be in range " "[1, 99999], or 0 to use a seed based on the current time.")
#define GTEST_REPEATER_METHOD_(Name, Type)
#define GTEST_REVERSE_REPEATER_METHOD_(Name, Type)
GTEST_DEFINE_string_(color, testing::internal::StringFromGTestEnv("color", "auto"), "Whether to use colors in the output. Valid values: yes, no, " "and auto. 'auto' means to use colors if the output is " "being sent to a terminal and the TERM environment variable " "is set to a terminal type that supports colors.")
std::vector< EditType > CalculateOptimalEdits(const std::vector< size_t > &left, const std::vector< size_t > &right)
std::string CreateUnifiedDiff(const std::vector< std::string > &left, const std::vector< std::string > &right, size_t context)
GTEST_API_ std::string WideStringToUtf8(const wchar_t *str, int num_chars)
const char * StringFromGTestEnv(const char *flag, const char *default_value)
std::string OutputFlagAlsoCheckEnvVar()
void ShuffleRange(internal::Random *random, int begin, int end, std::vector< E > *v)
GTEST_API_ bool ShouldShard(const char *total_shards_str, const char *shard_index_str, bool in_subprocess_for_death_test)
bool BoolFromGTestEnv(const char *flag, bool default_value)
static bool PatternMatchesString(const std::string &name_str, const char *pattern, const char *pattern_end)
::std::vector< std::string > GetArgvs()
static const char kColorEncodedHelpMessage[]
static FILE * OpenFileForWriting(const std::string &output_file)
AssertionResult FloatingPointLE(const char *expr1, const char *expr2, RawType val1, RawType val2)
void WriteToShardStatusFileIfNeeded()
int GetRandomSeedFromFlag(int32_t random_seed_flag)
std::string StringStreamToString(::std::stringstream *ss)
static void ColoredPrintf(GTestColor color, const char *fmt,...)
static ::std::vector< std::string > g_argvs
int CountIf(const Container &c, Predicate predicate)
GTEST_API_::std::string FormatCompilerIndependentFileLocation(const char *file, int line)
AssertionResult CmpHelperSTREQ(const char *lhs_expression, const char *rhs_expression, const char *lhs, const char *rhs)
static std::string Indent(size_t width)
bool SkipPrefix(const char *prefix, const char **pstr)
static bool TestSuitePassed(const TestSuite *test_suite)
std::string ReadEntireFile(FILE *file)
static const char * ParseFlagValue(const char *str, const char *flag_name, bool def_optional)
static bool ParseGoogleTestFlag(const char *const arg)
GTEST_API_::std::string FormatFileLocation(const char *file, int line)
void InsertSyntheticTestCase(const std::string &name, CodeLocation location, bool has_test_p)
GTEST_API_ bool ShouldRunTestOnShard(int total_shards, int shard_index, int test_id)
void RegisterTypeParameterizedTestSuite(const char *test_suite_name, CodeLocation code_location)
GTEST_API_ void ParseGoogleTestFlagsOnly(int *argc, char **argv)
static void PrintOnOneLine(const char *str, int max_length)
static AssertionResult HasOneFailure(const char *, const char *, const char *, const TestPartResultArray &results, TestPartResult::Type type, const std::string &substr)
bool ParseInt32(const Message &src_text, const char *str, int32_t *value)
AssertionResult DoubleNearPredFormat(const char *expr1, const char *expr2, const char *abs_error_expr, double val1, double val2, double abs_error)
bool IsTrue(bool condition)
void ForEach(const Container &c, Functor functor)
static void PrintFullTestCommentIfPresent(const TestInfo &test_info)
GTEST_API_ std::string FormatEpochTimeInMillisAsIso8601(TimeInMillis ms)
static void SetUpEnvironment(Environment *env)
std::string GetBoolAssertionFailureMessage(const AssertionResult &assertion_result, const char *expression_text, const char *actual_predicate_value, const char *expected_predicate_value)
static bool PortableLocaltime(time_t seconds, struct tm *out)
uint32_t CreateCodePointFromUtf16SurrogatePair(wchar_t first, wchar_t second)
bool IsUtf16SurrogatePair(wchar_t first, wchar_t second)
int GetNextRandomSeed(int seed)
static bool HasGoogleTestFlagPrefix(const char *str)
E GetElementOr(const std::vector< E > &v, int i, E default_value)
GTEST_API_ FilePath GetCurrentExecutableName()
GTEST_API_ bool ParseFlag(const char *str, const char *flag, int32_t *value)
static void PrintColorEncoded(const char *str)
AssertionResult CmpHelperSTRCASENE(const char *s1_expression, const char *s2_expression, const char *s1, const char *s2)
void RegisterTypeParameterizedTestSuiteInstantiation(const char *case_name)
TestInfo * MakeAndRegisterTestInfo(const char *test_suite_name, const char *name, const char *type_param, const char *value_param, CodeLocation code_location, TypeId fixture_class_id, SetUpTestSuiteFunc set_up_tc, TearDownTestSuiteFunc tear_down_tc, TestFactoryBase *factory)
constexpr uint32_t kMaxCodePoint3
void ReportFailureInUnknownLocation(TestPartResult::Type result_type, const std::string &message)
void SplitString(const ::std::string &str, char delimiter, ::std::vector< ::std::string > *dest)
GTEST_API_ std::string FormatTimeInMillisAsSeconds(TimeInMillis ms)
void Shuffle(internal::Random *random, std::vector< E > *v)
static bool GTestIsInitialized()
GTEST_API_ bool g_help_flag
static int SumOverTestSuiteList(const std::vector< TestSuite * > &case_list, int(TestSuite::*method)() const)
UnitTestImpl * GetUnitTestImpl()
int32_t Int32FromGTestEnv(const char *flag, int32_t default_value)
GTEST_API_ int32_t Int32FromEnvOrDie(const char *env_var, int32_t default_val)
AssertionResult EqFailure(const char *lhs_expression, const char *rhs_expression, const std::string &lhs_value, const std::string &rhs_value, bool ignoring_case)
constexpr uint32_t kMaxCodePoint2
void PrintTo(unsigned char c, ::std::ostream *os)
void ReportInvalidTestSuiteType(const char *test_suite_name, CodeLocation code_location)
static bool ShouldRunTestSuite(const TestSuite *test_suite)
static std::string FormatEpochTimeInMillisAsRFC3339(TimeInMillis ms)
AssertionResult CmpHelperSTRCASEEQ(const char *lhs_expression, const char *rhs_expression, const char *lhs, const char *rhs)
GTEST_API_ bool ShouldUseColor(bool stdout_is_tty)
void InitGoogleTestImpl(int *argc, CharType **argv)
static bool TestSuiteFailed(const TestSuite *test_suite)
static void TearDownEnvironment(Environment *env)
Result HandleSehExceptionsInMethodIfSupported(T *object, Result(T::*method)(), const char *location)
static std::string FormatTimeInMillisAsDuration(TimeInMillis ms)
static void PrintTestPartResult(const TestPartResult &test_part_result)
const char kStackTraceMarker[]
GTEST_API_ const TypeId kTestTypeIdInGoogleTest
GTEST_API_ std::string CodePointToUtf8(uint32_t code_point)
static std::string PrintTestPartResultToString(const TestPartResult &test_part_result)
Result HandleExceptionsInMethodIfSupported(T *object, Result(T::*method)(), const char *location)
std::string AppendUserMessage(const std::string >est_msg, const Message &user_msg)
void ParseGoogleTestFlagsOnlyImpl(int *argc, CharType **argv)
static const char kValueParamLabel[]
GTEST_API_ TimeInMillis GetTimeInMillis()
constexpr uint32_t kMaxCodePoint1
GTEST_NO_INLINE_ GTEST_NO_TAIL_CALL_ std::string GetCurrentOsStackTraceExceptTop(UnitTest *, int skip_count)
static const char kTypeParamLabel[]
AssertionResult CmpHelperSTRNE(const char *s1_expression, const char *s2_expression, const char *s1, const char *s2)
constexpr uint32_t kMaxCodePoint4
std::set< std::string > * GetIgnoredParameterizedTestSuites()
static const char * GetAnsiColorCode(GTestColor color)
uint32_t ChopLowBits(uint32_t *bits, int n)
static const char kDisableTestFilter[]
static std::vector< std::string > GetReservedAttributesForElement(const std::string &xml_element)
static bool TestPartSkipped(const TestPartResult &result)
AssertionResult IsNotSubstring(const char *needle_expr, const char *haystack_expr, const char *needle, const char *haystack)
static const char kUniversalFilter[]
AssertionResult FloatLE(const char *expr1, const char *expr2, float val1, float val2)
static std::string FormatCountableNoun(int count, const char *singular_form, const char *plural_form)
AssertionResult IsSubstring(const char *needle_expr, const char *haystack_expr, const char *needle, const char *haystack)
static std::string FormatWordList(const std::vector< std::string > &words)
static const char kTestShardStatusFile[]
static const char kTestShardIndex[]
static bool GetDefaultFailFast()
static std::string FormatTestCount(int test_count)
static const char kTestTotalShards[]
AssertionResult AssertionFailure()
static const char kDeathTestSuiteFilter[]
static std::string GetTempDirFromEnv(std::initializer_list< const char * > environment_variables, const char *fallback, char separator)
static std::string FormatTestSuiteCount(int test_suite_count)
static const char *const kReservedOutputTestCaseAttributes[]
static const char kDefaultOutputFormat[]
static bool TestPartFatallyFailed(const TestPartResult &result)
static const char * GetDefaultFilter()
static const char kDefaultOutputFile[]
std::vector< std::string > ArrayAsVector(const char *const (&array)[kSize])
AssertionResult AssertionSuccess()
static std::vector< std::string > GetReservedOutputAttributesForElement(const std::string &xml_element)
AssertionResult DoubleLE(const char *expr1, const char *expr2, double val1, double val2)
static const char *const kReservedTestCaseAttributes[]
static bool ValidateTestPropertyName(const std::string &property_name, const std::vector< std::string > &reserved_names)
static bool TestPartNonfatallyFailed(const TestPartResult &result)
static const char *const kReservedTestSuiteAttributes[]
static const char *const kReservedTestSuitesAttributes[]
static const char * TestPartResultTypeToString(TestPartResult::Type type)